From 50007d5cc6c5d5be79677840ec34fbd78f3b76a9 Mon Sep 17 00:00:00 2001 From: HeuJung Date: Mon, 7 Sep 2026 17:08:14 +0900 Subject: [PATCH] =?UTF-8?q?fix(auth):=202=EB=8B=A8=EA=B3=84=20=EC=9D=B8?= =?UTF-8?q?=EC=A6=9D=EC=9D=84=20=EC=BC=A0=20=EC=82=AC=EC=9D=B4=ED=8A=B8?= =?UTF-8?q?=EC=9D=98=20=EB=A1=9C=EA=B7=B8=EC=9D=B8=20=ED=9D=90=EB=A6=84=20?= =?UTF-8?q?=EA=B5=AC=ED=98=84?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 2단계 인증은 7.0.6 에서 서버측이 갖춰졌지만 인증번호를 입력할 화면이 어느 버전에도 없었다. 그래서 그 설정을 켠 사이트는 관리자를 포함한 전원이 로그인할 수 없었다. 원인은 `POST /api/auth/login` 이 조건에 따라 **다른 형태의 200** 을 돌려준다는 것이다. 평소에는 `{token, user}` 지만 2단계 인증이 켜져 있으면 `{two_factor_required, challenge_id, ...}` 를 돌려준다. 프론트는 앞의 형태만 선언하고 `response.data.user.language` 를 바로 읽었으므로 그 자리에서 TypeError 가 났고, 영문 원문이 로그인 화면에 그대로 노출됐다. 서버는 정상 응답했으므로 서버 로그에는 아무 흔적도 남지 않는다. 이어서 `setToken(undefined)` 가 `localStorage` 에 문자열 `"undefined"` 를 남겼다. 이 값은 truthy 라 이후 모든 요청이 `Bearer undefined` 로 나가 401 이 되고, 사용자에게는 「세션이 만료되었습니다」로 보인다. 관리자 로그인은 한발 더 나가 `null->isAdmin` 으로 500 이 되어, 설정을 되돌릴 수단까지 함께 사라졌다. ## 구현 - 로그인 응답을 판별 유니온(`LoginResult`)으로 표현하고, 형태를 판별한 뒤에 읽는다. `ApiClient.setToken` 은 비어 있지 않은 문자열만 저장한다. - 사용자·관리자 로그인 화면에 인증번호 입력 단계를 추가했다. 같은 카드 안에서 넘어가며 「인증번호 다시 받기」와 「처음부터」를 제공한다. 관리자 판정은 코드 확인에 성공한 뒤에 수행하고, 거부할 때는 그 직전에 발급된 토큰을 회수한다. - 재발송(`login/two-factor/resend`)은 기존 challenge 를 취소하고 새로 발행한다. 유효한 코드를 여러 개 살려 두면 대입 시도의 표적이 넓어진다. - 인증번호를 보내지 못하면 401 이 아니라 503 으로 답한다. 자격 증명은 올바른데 401 로 뭉개면 사용자는 비밀번호를 의심하며 같은 시도를 반복하고, 운영자는 메일 설정이 깨진 사실을 알 방법이 없다. - 공개 본인인증 경로(`identity/verify`·`cancel`)가 로그인 목적의 challenge 를 소진하지 못하도록 403 게이트를 세웠다. 소진되면 그 challenge 로 영영 로그인할 수 없다. - 로그인 시도 제한 429 응답이 다국어 문구를 싣도록 했다(종전에는 프레임워크 기본 영문). - 다국어 파라미터에서 파이프 표현식이 평가되지 않아 「유효시간 까지」처럼 값이 빠지던 문제를 함께 고쳤다. 같은 결함이 문의 목록 화면에도 있었다. ## 이번 점검에서 함께 고친 것 - 계정 잠금(423)·발송 실패(503) 응답이 사용자·관리자 컨트롤러에 동일하게 복제돼 있었고 그 주석 자신은 "단일 지점에서 만든다" 고 적혀 있었다. 페이로드에 필드가 하나 추가되면 한쪽만 따라가 같은 실패를 두 화면이 다르게 안내하게 된다 — 트레이트로 통합했다. - 테스트가 개발자 자신의 사이트 설정을 읽고 있었다. 2단계 인증을 켜 둔 환경에서는 로그인 성공을 전제한 테스트가 503 으로 깨지는데 실패 메시지가 원인을 가리키지도 않는다. 같은 결함군을 위해 이미 존재하던 단일 지점에 그 축을 추가했다. ## 버전 코어 7.0.11 · sirsoft-basic 1.1.4 · sirsoft-admin_basic 1.0.9 · 번들 일본어팩 3종 · 템플릿 엔진 engine-v1.65.0. --- .env.example | 2 +- .env.testing.example | 2 +- AGENTS.md | 20 +- CHANGELOG.md | 20 + INSTALL.md | 2 +- README.ko.md | 3 +- README.md | 3 +- .../Commands/PlaywrightSeedTwoFactor.php | 242 ++++++++ .../Auth/TwoFactorDeliveryFailedException.php | 25 + .../Controllers/Api/Admin/AuthController.php | 131 ++++- .../Controllers/Api/Auth/AuthController.php | 47 +- .../IdentityVerificationController.php | 19 + .../Concerns/BuildsAuthFailureResponses.php | 53 ++ .../Requests/Auth/TwoFactorResendRequest.php | 54 ++ app/Providers/AppServiceProvider.php | 14 +- app/Services/AuthService.php | 86 ++- config/app.php | 2 +- docs/backend/api/README.md | 4 +- docs/backend/api/auth.md | 246 ++++++++- docs/backend/api/identity.md | 8 +- docs/frontend/actions-handlers-ui.md | 106 ++++ docs/frontend/actions-handlers.md | 3 + docs/frontend/auth-system.md | 61 +- docs/frontend/identity-verification-ui.md | 11 + docs/testing/e2e-testing.md | 45 ++ lang-packs/_bundled/g7-core-ja/CHANGELOG.md | 7 + .../_bundled/g7-core-ja/backend/ja/auth.php | 1 + .../g7-core-ja/backend/ja/identity.php | 1 + .../frontend/partial/layout_editor.json | 8 + .../_bundled/g7-core-ja/language-pack.json | 2 +- .../CHANGELOG.md | 6 + .../frontend/partial/auth.json | 13 + .../language-pack.json | 2 +- .../g7-template-sirsoft-basic-ja/CHANGELOG.md | 6 + .../frontend/partial/auth.json | 13 + .../language-pack.json | 2 +- lang/en/auth.php | 1 + lang/en/identity.php | 1 + lang/ko/auth.php | 1 + lang/ko/identity.php | 1 + lang/partial/en/layout_editor.json | 8 + lang/partial/ko/layout_editor.json | 8 + public/build/core/dev-dashboard.css | 2 +- public/build/core/layout-editor.min.js | 10 +- public/build/core/template-engine.min.js | 89 ++- resources/js/core/api/ApiClient.ts | 12 + .../js/core/api/__tests__/ApiClient.test.ts | 22 + resources/js/core/auth/AuthManager.ts | 331 ++++++++--- .../core/auth/__tests__/AuthManager.test.ts | 152 ++++- resources/js/core/auth/index.ts | 2 + .../core/template-engine/ActionDispatcher.ts | 210 ++++++- .../js/core/template-engine/CHANGELOG.md | 21 + .../core/template-engine/TranslationEngine.ts | 15 + .../ActionDispatcher.globalHeaders.test.ts | 4 +- .../ActionDispatcher.loginTwoFactor.test.ts | 218 ++++++++ .../__tests__/TranslationEngine.test.ts | 29 + ...ionDispatcherNetworkFailureMessage.test.ts | 20 + .../__tests__/spec/coreActionRecipes.test.ts | 2 +- .../page-settings/ActionAddPicker.tsx | 2 + .../layout-editor/spec/coreActionRecipes.ts | 12 + .../core/template-engine/networkResilience.ts | 11 +- routes/api.php | 10 + .../_bundled/sirsoft-admin_basic/AGENTS.md | 6 +- .../_bundled/sirsoft-admin_basic/CHANGELOG.md | 14 + .../_bundled/sirsoft-admin_basic/README.md | 6 +- .../admin-login-two-factor-render.test.tsx | 337 ++++++++++++ .../admin-login-two-factor-step.test.tsx | 190 +++++++ .../sirsoft-admin_basic/docs/layouts.md | 24 + .../lang/partial/en/auth.json | 13 + .../lang/partial/ko/auth.json | 13 + .../layouts/admin_login.json | 324 +++++++++++ .../sirsoft-admin_basic/package-lock.json | 4 +- .../_bundled/sirsoft-admin_basic/package.json | 2 +- .../sirsoft-admin_basic/template.json | 4 +- .../admin-login-two-factor-step.yaml | 42 ++ templates/_bundled/sirsoft-basic/AGENTS.md | 6 +- templates/_bundled/sirsoft-basic/CHANGELOG.md | 14 + templates/_bundled/sirsoft-basic/README.md | 6 +- .../layouts/login-two-factor-render.test.tsx | 360 ++++++++++++ .../layouts/login-two-factor-step.test.tsx | 211 +++++++ .../_bundled/sirsoft-basic/docs/layouts.md | 24 + .../sirsoft-basic/lang/partial/en/auth.json | 13 + .../sirsoft-basic/lang/partial/ko/auth.json | 13 + .../sirsoft-basic/layouts/auth/login.json | 5 + .../layouts/partials/auth/_login_form.json | 302 +++++++++- .../_bundled/sirsoft-basic/package-lock.json | 4 +- templates/_bundled/sirsoft-basic/package.json | 2 +- .../src/__tests__/layouts/login.test.tsx | 48 ++ .../_bundled/sirsoft-basic/template.json | 4 +- .../scenarios/login-two-factor-step.yaml | 45 ++ tests/Feature/Auth/LoginThrottleTest.php | 39 +- tests/Feature/Auth/TwoFactorAuthTest.php | 303 +++++++++- .../Identity/IdentityLoginPurposeGateTest.php | 162 ++++++ tests/Playwright/fixtures/smtp-sink.ts | 131 +++++ tests/Playwright/fixtures/two-factor.ts | 283 ++++++++++ .../specs/auth/two-factor-login.spec.ts | 520 ++++++++++++++++++ tests/TestCase.php | 14 +- tests/scenarios/auth-two-factor-login.yaml | 94 ++++ 98 files changed, 5815 insertions(+), 231 deletions(-) create mode 100644 app/Console/Commands/PlaywrightSeedTwoFactor.php create mode 100644 app/Exceptions/Auth/TwoFactorDeliveryFailedException.php create mode 100644 app/Http/Controllers/Concerns/BuildsAuthFailureResponses.php create mode 100644 app/Http/Requests/Auth/TwoFactorResendRequest.php create mode 100644 resources/js/core/template-engine/__tests__/ActionDispatcher.loginTwoFactor.test.ts create mode 100644 templates/_bundled/sirsoft-admin_basic/__tests__/layouts/admin-login-two-factor-render.test.tsx create mode 100644 templates/_bundled/sirsoft-admin_basic/__tests__/layouts/admin-login-two-factor-step.test.tsx create mode 100644 templates/_bundled/sirsoft-admin_basic/tests/scenarios/admin-login-two-factor-step.yaml create mode 100644 templates/_bundled/sirsoft-basic/__tests__/layouts/login-two-factor-render.test.tsx create mode 100644 templates/_bundled/sirsoft-basic/__tests__/layouts/login-two-factor-step.test.tsx create mode 100644 templates/_bundled/sirsoft-basic/tests/scenarios/login-two-factor-step.yaml create mode 100644 tests/Feature/Identity/IdentityLoginPurposeGateTest.php create mode 100644 tests/Playwright/fixtures/smtp-sink.ts create mode 100644 tests/Playwright/fixtures/two-factor.ts create mode 100644 tests/Playwright/specs/auth/two-factor-login.spec.ts create mode 100644 tests/scenarios/auth-two-factor-login.yaml diff --git a/.env.example b/.env.example index 49db91b8..25f1be5e 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.10 +APP_VERSION=7.0.11 # 리버스 프록시(AWS ALB, CloudFront, Cloudflare, nginx, ngrok) 뒤에서 HTTPS 를 인식하려면 # 신뢰할 프록시를 지정합니다. 미설정 시 아무 프록시도 신뢰하지 않습니다(기존 동작). diff --git a/.env.testing.example b/.env.testing.example index dea1ab52..b5706dca 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.10 +APP_VERSION=7.0.11 # 리버스 프록시(AWS ALB, CloudFront, Cloudflare, nginx, ngrok) 뒤에서 HTTPS 를 인식하려면 # 신뢰할 프록시를 지정합니다. 미설정 시 아무 프록시도 신뢰하지 않습니다(기존 동작). diff --git a/AGENTS.md b/AGENTS.md index 2b914a09..fc2c03e9 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -149,7 +149,7 @@ | 대상 | 진입점 | 문서/엔드포인트 | |------|--------|----------------| -| 코어 | [docs/backend/api/README.md](docs/backend/api/README.md) | 36 / 325 | +| 코어 | [docs/backend/api/README.md](docs/backend/api/README.md) | 36 / 328 | ### 확장 API 레퍼런스 (14개 확장, 자동 스캔) @@ -476,6 +476,24 @@ catch-all shadow 는 보호처럼 보인다는 점이 위험하다. 가려진 > 상세: [validation.md](docs/backend/validation.md), [service-repository.md](docs/backend/service-repository.md), [frontend/security.md](docs/frontend/security.md) +### 서버가 조건에 따라 다른 형태의 200 을 돌려주는 엔드포인트 + +같은 엔드포인트가 설정·상태에 따라 **다른 형태의 2xx** 를 낸다면, 프론트는 형태를 판별한 뒤에 읽어야 한다. 한 형태만 가정하면 다른 형태에서 필드 접근이 그 자리에서 던지고, 그 원문이 오류 박스에 영문으로 노출된다. 서버는 정상 응답했으므로 **서버 로그에는 흔적이 없다** — 깨진 것은 클라이언트뿐이다. + +| ❌ 금지 | ✅ 올바른 사용 | +|--------|---------------| +| 응답 타입을 한 형태로 고정 선언하고 `response.data.user.*` 를 바로 읽기 | 판별 유니온으로 두 형태를 표현 (`LoginResult` = `{status:'authenticated', user}` \| `{status:'two_factor_required', challenge}`) | +| 저장 지점에 형태 가드 없이 `setToken(response.data.token)` | 비어 있지 않은 문자열만 저장 — `localStorage` 는 무엇을 넣든 문자열로 바꾸므로 `undefined` 가 `"undefined"`(truthy)로 남아 이후 모든 요청이 `Bearer undefined` 로 나가 401 이 된다 | +| 대체 형태 분기를 사용자 경로에만 두고 관리자 경로는 그대로 | 관리자 경로가 먼저 500 이 되면 설정을 되돌릴 수단까지 사라진다 — 두 경로 동시 적용 | +| `onSuccess` 후속 액션에 조건 없이 성공 처리를 나열 | 대체 형태에서 실행되면 안 되는 액션마다 `if:"{{!response.대체형태플래그}}"` | +| `onSuccess`·시퀀스 안에서 방금 저장한 상태(`_global.*`/`_local.*`)를 형제 액션의 `if`·값으로 재독 | 그 시점 컨텍스트는 아직 갱신 전이다 — `{{response.*}}` 만 읽는다 (`onSuccess` 결과는 `handleSequence` 의 상태 동기화 대상이 아니다) | +| 서버가 제공하는 기능의 프론트 화면 부재를 "미사용" 으로 간주 | 토글을 켠 사이트에서만 드러나는 미구현이다 — 서버 토글 ↔ 화면 존재를 전수 대조 | + +착수 전 전수조사 축은 **"서버가 대체 형태 2xx 를 내는 엔드포인트 ↔ 프론트 처리 여부"** 다. 그리고 **"서버 토글 ON 시 프론트 화면 존재 여부"** 를 함께 본다 — 2단계 인증은 도입 후 여러 버전 동안 입력 화면이 없었고, 그 토글을 켠 사이트에서만 전원 로그인 불가로 나타났다(공개 #133). + +> 상세: [auth-system.md "2단계 인증 로그인"](docs/frontend/auth-system.md) +> 정적 검사로는 잡히지 않는다 — 응답 변종은 서버 분기의 의미 판정이므로 코드 리뷰에서 확인한다. + ### 제3자 라이브러리는 쓰기 경로를 지정받는다 제3자 라이브러리는 캐시·임시파일 경로를 설정하지 않으면 **자기 설치 폴더**(vendor 안)나 시스템 temp 에 쓴다. 표준 Laravel 배포는 웹서버에 `storage/` 와 `bootstrap/cache` 만 쓰기 권한을 주므로 그 쓰기는 실패하는데, 실패가 예외가 아니라 PHP 경고라 Laravel `HandleExceptions` 가 `ErrorException` 으로 승격시켜 요청이 500 이 된다. 해시당 1회만 기록하는 라이브러리라면 캐시가 영영 생기지 않아 **매 요청이 같은 실패를 반복**한다 — 개발 머신에서는 vendor 가 쓰기 가능해 한 번 성공하고 끝나므로 재현되지 않는다 (공개 #125). diff --git a/CHANGELOG.md b/CHANGELOG.md index f393be09..00d9638b 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -4,6 +4,26 @@ 형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며, [Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다. +## [7.0.11] - 2026-09-07 + +### Added + +- 2단계 인증을 켠 사이트의 로그인 화면에 인증번호 입력 단계가 추가되었습니다. 비밀번호를 확인하면 같은 카드 안에서 인증번호 입력으로 넘어가고, 「인증번호 다시 받기」로 새 번호를 받거나 「처음부터」로 되돌아갈 수 있습니다. 관리자 로그인 화면도 같은 흐름으로 동작합니다. (#133 @keidichoi-gif 님께서 제보해주셨습니다.) + +### Changed + +- 인증번호를 보내지 못해 로그인을 마칠 수 없을 때의 응답이 「인증에 실패했습니다」(401)에서 「인증번호를 보내지 못했습니다」(503)로 바뀌었습니다. 자격 증명은 올바른데도 로그인 실패로 안내되어 사용자는 비밀번호를 의심하며 같은 시도를 반복하고, 운영자는 메일 설정이 깨진 사실을 알 방법이 없었습니다. (#133 @keidichoi-gif 님께서 제보해주셨습니다.) + +### Fixed + +- 2단계 인증을 켠 사이트에서 로그인이 되지 않던 문제를 수정했습니다. 로그인 화면에 영문 오류(`Cannot read properties of undefined`)가 표시되고 그 뒤로는 진행할 방법이 없었으며, 관리자 로그인은 서버 오류(500)가 되어 설정을 되돌릴 수단까지 사라졌습니다. 이제 인증번호 입력 단계가 표시되고 관리자도 같은 흐름으로 로그인할 수 있습니다. (#133 @keidichoi-gif 님께서 제보해주셨습니다.) +- 로그인 응답을 잘못 해석해 사용할 수 없는 인증 정보가 브라우저에 저장되던 문제를 수정했습니다. 그 뒤로는 화면을 새로 열 때마다 「세션이 만료되었습니다」 안내와 함께 로그인 화면으로 되돌아갔습니다. +- 본인인증 화면에서 로그인용 인증 요청을 처리할 수 있어, 그 요청으로는 다시 로그인할 수 없게 되던 문제를 수정했습니다. 로그인용 인증 요청은 이제 로그인 화면에서만 처리됩니다. +- 로그인 시도가 많아 잠시 차단될 때 영문 안내(`Too Many Attempts.`)가 그대로 표시되던 문제를 수정했습니다. 이제 다시 시도할 수 있는 시각과 함께 사이트 언어로 안내합니다. +- 로그인 중 네트워크가 끊겼을 때 영문 원문(`Network Error`)이 표시되던 문제를 수정했습니다. +- 로그인 시도 초과로 계정이 잠겼을 때 해제 시각이 화면에 표시되지 않던 문제를 수정했습니다. 언제 다시 시도할 수 있는지 알 수 없어 계속 눌러 보게 되었습니다. +- 안내 문구 안에 날짜·시각 서식을 넣으면 그 값만 비어 보이던 문제를 수정했습니다. + ## [7.0.10] - 2026-09-06 ### Added diff --git a/INSTALL.md b/INSTALL.md index aedfdf78..e443a788 100644 --- a/INSTALL.md +++ b/INSTALL.md @@ -289,7 +289,7 @@ unzip g7-release.zip # 압축 해제 결과 확인 — 루트 디렉토리가 g7이 아니면 이름 변경 ls -la -# (필요 시) mv g7-7.0.10 g7 +# (필요 시) mv g7-7.0.11 g7 # ZIP 파일 정리 (선택) rm g7-release.zip diff --git a/README.ko.md b/README.ko.md index 28e085cf..264d663c 100644 --- a/README.ko.md +++ b/README.ko.md @@ -6,7 +6,7 @@ A modern, extensible CMS platform built with Laravel + React

- Version + Version PHP Laravel React @@ -521,6 +521,7 @@ cp .env.example .env abc101 hwaryeon1234 koojunho + keidichoi-gif kitrio yks118 movielee2020 diff --git a/README.md b/README.md index e6ded2ed..27983fa9 100644 --- a/README.md +++ b/README.md @@ -6,7 +6,7 @@ The next generation of Gnuboard — Korea's most widely used open-source CMS

- Version + Version PHP Laravel React @@ -535,6 +535,7 @@ Thanks to everyone who reported an issue or suggested a feature that shipped — abc101 hwaryeon1234 koojunho + keidichoi-gif kitrio yks118 movielee2020 diff --git a/app/Console/Commands/PlaywrightSeedTwoFactor.php b/app/Console/Commands/PlaywrightSeedTwoFactor.php new file mode 100644 index 00000000..e5060f90 --- /dev/null +++ b/app/Console/Commands/PlaywrightSeedTwoFactor.php @@ -0,0 +1,242 @@ + --code=135790 + */ +class PlaywrightSeedTwoFactor extends Command +{ + protected $signature = 'playwright:seed-two-factor + {--ensure-user= : 이 접미사로 Active 테스트 사용자를 생성/갱신하고 이메일을 출력한다} + {--password= : --ensure-user 가 설정할 비밀번호 (기본값 Passw0rd!2fa)} + {--admin : --ensure-user 계정에 admin 역할을 부여한다} + {--plant= : 이 challenge 에 알려진 인증 코드의 해시를 심는다 (challenge UUID)} + {--code=135790 : --plant 가 심을 인증 코드} + {--gc-hours=6 : 이 시간(시)보다 오래된 playwright 2FA 테스트 계정을 정리. 0 이면 정리 안 함} + {--purge-users : 나이와 무관하게 playwright 2FA 테스트 계정을 전부 제거 (실측 종료 직후 호출)}'; + + protected $description = 'Playwright E2E 용 2단계 인증 픽스처 (테스트 계정 준비 / 인증 코드 심기)'; + + /** 테스트 전용 계정 이메일 접두사 */ + private const TEST_EMAIL_PREFIX = 'playwright_2fa_'; + + public function handle(): int + { + // ① CLI 한정 — production 웹 요청에서 절대 도달 불가 + if (php_sapi_name() !== 'cli') { + $this->error('CLI 전용 커맨드입니다. (현재 SAPI: '.php_sapi_name().')'); + + return self::FAILURE; + } + + // ② 명시 옵트인 — 환경변수 없이는 production 호출 실수 차단. + // 여기의 `env()` 는 `.env` 유래 값이 아니라 호출자가 그 자리에서 넘기는 프로세스 + // 환경변수이므로 config:cache 의 영향을 받지 않는다. + if (env('G7_PLAYWRIGHT_BYPASS') !== '1') { + $this->error('G7_PLAYWRIGHT_BYPASS=1 환경변수가 필요합니다. (예: PowerShell — $env:G7_PLAYWRIGHT_BYPASS=\'1\')'); + + return self::FAILURE; + } + + // ③ APP_DEBUG 강제 — production + debug=false 환경에서도 픽스처 조작 허용 + Config::set('app.debug', true); + + $gcHours = (int) $this->option('gc-hours'); + if ($gcHours > 0) { + $this->pruneStaleTestUsers($gcHours); + } + + $did = false; + + // 알려진 비밀번호를 가진 계정(관리자 포함)을 실측 뒤에 남기지 않는다 — + // 나이 기준 정리(gc-hours)는 그 사이의 창을 닫지 못한다. + if ($this->option('purge-users')) { + $this->purgeTestUsers(); + $did = true; + } + + if ($suffix = $this->option('ensure-user')) { + $this->ensureUser((string) $suffix); + $did = true; + } + + if ($challengeId = $this->option('plant')) { + if (! $this->plantCode((string) $challengeId, (string) $this->option('code'))) { + return self::FAILURE; + } + $did = true; + } + + if (! $did) { + $this->error('--ensure-user · --plant · --purge-users 중 하나는 지정해야 합니다.'); + + return self::FAILURE; + } + + return self::SUCCESS; + } + + /** + * 알려진 비밀번호를 가진 Active 테스트 사용자를 만들거나 갱신하고 이메일을 출력합니다. + * + * @param string $suffix 계정 구분 접미사 (예: user / nonadmin) + */ + private function ensureUser(string $suffix): void + { + $email = self::TEST_EMAIL_PREFIX.$suffix.'@example.test'; + $password = (string) ($this->option('password') ?: 'Passw0rd!2fa'); + + $user = User::where('email', $email)->first(); + + if ($user === null) { + $user = User::factory()->create([ + 'email' => $email, + 'password' => Hash::make($password), + 'status' => UserStatus::Active->value, + ]); + } else { + // 이전 실행이 남긴 계정을 재사용한다 — 매 실행마다 계정이 늘면 회원 목록이 + // 테스트 잔재로 뒤덮인다. 잠금·실패 카운트도 함께 초기화해 앞선 spec 의 + // 잠금 상태가 다음 실행으로 새지 않게 한다. + $user->forceFill([ + 'password' => Hash::make($password), + 'status' => UserStatus::Active->value, + 'locked_until' => null, + 'failed_login_attempts' => 0, + ])->save(); + } + + if ($this->option('admin')) { + $adminRole = Role::firstOrCreate( + ['identifier' => 'admin'], + [ + 'name' => ['ko' => '관리자', 'en' => 'Admin'], + 'description' => ['ko' => '시스템 관리자', 'en' => 'System Admin'], + 'extension_type' => ExtensionOwnerType::Core, + 'extension_identifier' => 'core', + 'type' => 'admin', + 'is_active' => true, + ] + ); + + if (! $user->roles()->where('roles.id', $adminRole->id)->exists()) { + $user->roles()->attach($adminRole->id, ['assigned_at' => now(), 'assigned_by' => null]); + } + } else { + // 관리자 거절 경로를 재현하려면 관리자 역할이 없어야 한다 — 재사용 계정에 + // 앞선 실행의 admin 역할이 남아 있으면 403 을 측정할 수 없다. + $user->roles()->detach(); + } + + $this->line($email); + } + + /** + * challenge 에 알려진 인증 코드의 해시를 심습니다. + * + * @param string $challengeId challenge UUID + * @param string $code 심을 인증 코드 + * @return bool 성공 여부 + */ + private function plantCode(string $challengeId, string $code): bool + { + $log = IdentityVerificationLog::find($challengeId); + + if ($log === null) { + $this->error("challenge 를 찾을 수 없습니다: {$challengeId}"); + + return false; + } + + $metadata = $log->metadata ?? []; + $metadata['code_hash'] = Hash::make($code); + + $log->metadata = $metadata; + $log->save(); + + $this->line($code); + + return true; + } + + /** + * playwright 2FA 테스트 계정을 나이와 무관하게 전부 제거합니다. + * + * 이 계정들은 알려진 비밀번호를 갖고, `--admin` 으로 만든 것은 관리자 역할까지 갖는다. + * 실측이 끝난 뒤에도 남아 있으면 그 자체가 열린 문이므로 즉시 지운다. + */ + private function purgeTestUsers(): void + { + $removed = 0; + + User::where('email', 'like', self::TEST_EMAIL_PREFIX.'%') + ->chunkById(100, function ($chunk) use (&$removed) { + foreach ($chunk as $user) { + $user->tokens()->delete(); + $user->roles()->detach(); + $user->delete(); + $removed++; + } + }); + + $this->info("[purge] playwright 2FA 테스트 계정 제거: {$removed}건"); + } + + /** + * 임계 시간보다 오래된 playwright 2FA 테스트 계정을 정리합니다. + * + * chunkById(키셋 순회) 필수 — 콜백이 순회 대상 행을 삭제하므로 OFFSET 기반 + * chunk()/each() 는 줄어든 결과 집합만큼 커서가 밀려 일부를 건너뛴다. + * + * @param int $hours 이 시간보다 오래된 계정만 정리 + */ + private function pruneStaleTestUsers(int $hours): void + { + $threshold = now()->subHours($hours); + $removed = 0; + + User::where('email', 'like', self::TEST_EMAIL_PREFIX.'%') + ->where('created_at', '<', $threshold) + ->chunkById(100, function ($chunk) use (&$removed) { + foreach ($chunk as $user) { + $user->tokens()->delete(); + $user->roles()->detach(); + $user->delete(); + $removed++; + } + }); + + if ($removed > 0) { + $this->info("[gc] playwright 2FA 테스트 계정 정리: {$removed}건"); + } + } +} diff --git a/app/Exceptions/Auth/TwoFactorDeliveryFailedException.php b/app/Exceptions/Auth/TwoFactorDeliveryFailedException.php new file mode 100644 index 00000000..e973a070 --- /dev/null +++ b/app/Exceptions/Auth/TwoFactorDeliveryFailedException.php @@ -0,0 +1,25 @@ +middleware(['auth:sanctum', 'admin'])->except([ + 'login', + 'verifyTwoFactor', + 'resendTwoFactor', + ]); } /** @@ -33,10 +48,21 @@ class AuthController extends AdminBaseController $request->validated()['password'] ); + // 2단계 인증이 켜져 있으면 아직 토큰도 사용자도 없다 — 관리자 판정은 코드 확인 + // 뒤로 미룬다. 이 분기가 없으면 $data['user'] 가 없어 500 이 되고, 관리자까지 + // 로그인할 수 없어 설정을 되돌릴 수단이 사라진다. + if ($data['two_factor_required'] ?? false) { + return $this->success('auth.two_factor_required', $data); + } + $user = $data['user']; // 관리자 권한 확인 if (! $user->isAdmin()) { + // 이 시점에는 이미 토큰과 web 세션이 발급되어 있다 — 거절하면서 남겨 두면 + // 관리자가 아닌 사용자가 응답만 403 을 받을 뿐 세션은 그대로 유효해진다. + $this->authService->revokeIssuedSession($user, $data['token']); + return $this->forbidden('auth.admin_required'); } @@ -45,22 +71,92 @@ class AuthController extends AdminBaseController return $this->success('auth.admin_login_success', $data); } catch (AccountLockedException $e) { - // 영구 잠금(무한대 설정)은 해제 시각·잔여 시간이 없다 — null 그대로 노출. - return $this->error( - $e->isPermanent() ? 'auth.account_locked_permanently' : 'auth.account_locked', - 423, - [ - 'locked_until' => $e->lockedUntil?->toIso8601String(), - 'retry_after_seconds' => $e->remainingMinutes === null ? null : $e->remainingMinutes * 60, - 'permanent' => $e->isPermanent(), - ], - ['minutes' => $e->remainingMinutes] - ); + return $this->lockedResponse($e); + } catch (TwoFactorDeliveryFailedException $e) { + return $this->deliveryFailedResponse(); } catch (ValidationException $e) { return $this->unauthorized('auth.login_failed'); } } + /** + * 관리자의 2단계 인증 코드를 확인하고 로그인을 완료합니다. + * + * 비밀번호 확인 단계(`login`)는 토큰 대신 challenge 를 돌려주며, 이 엔드포인트가 + * 코드 확인에 성공해야 비로소 토큰이 발급됩니다. + * + * @param TwoFactorChallengeRequest $request challenge 확인 요청 + * @return JsonResponse 로그인 결과와 관리자 정보, 토큰을 포함한 JSON 응답 + */ + public function verifyTwoFactor(TwoFactorChallengeRequest $request): JsonResponse + { + $validated = $request->validated(); + + try { + $data = $this->authService->completeTwoFactor( + $validated['challenge_id'], + ['code' => $validated['code']] + ); + + $user = $data['user']; + + if (! $user->isAdmin()) { + // completeTwoFactor() 는 코드 확인에 성공한 시점에 토큰을 발급한다. + // 관리자 판정으로 거절하면서 그 발급분을 회수하지 않으면 관리자가 아닌 + // 사용자가 유효한 세션을 손에 쥔 채 응답만 403 을 받는다. + $this->authService->revokeIssuedSession($user, $data['token']); + + return $this->forbidden('auth.admin_required'); + } + + $data['user'] = new UserResource($user); + + return $this->success('auth.admin_login_success', $data); + } catch (AccountLockedException $e) { + // 세션을 여는 지점이므로 `login` 과 같은 423 계약을 따른다. + return $this->lockedResponse($e); + } catch (TwoFactorDeliveryFailedException $e) { + return $this->deliveryFailedResponse(); + } catch (ValidationException $e) { + return $this->unauthorized('auth.two_factor_failed'); + } + } + + /** + * 관리자의 2단계 인증 코드를 재발송합니다. + * + * 기존 challenge 는 취소되고 새 challenge 가 발행되므로, 앞서 받은 인증번호는 + * 더 이상 통하지 않습니다. + * + * @param TwoFactorResendRequest $request challenge 재발송 요청 + * @return JsonResponse 새 challenge 정보를 포함한 JSON 응답 + */ + public function resendTwoFactor(TwoFactorResendRequest $request): JsonResponse + { + try { + $resolvedUser = null; + + $data = $this->authService->resendTwoFactorChallenge( + $request->validated()['challenge_id'], + $resolvedUser + ); + + // 이 단계는 토큰을 발급하지 않으므로 회수할 것이 없다 — 다만 완료할 수 없는 + // 상대에게 새 인증번호를 계속 보내지는 않는다. + if ($resolvedUser === null || ! $resolvedUser->isAdmin()) { + return $this->forbidden('auth.admin_required'); + } + + return $this->success('auth.two_factor_required', $data); + } catch (AccountLockedException $e) { + return $this->lockedResponse($e); + } catch (TwoFactorDeliveryFailedException $e) { + return $this->deliveryFailedResponse(); + } catch (ValidationException $e) { + return $this->validationError($e->errors(), 'auth.two_factor_invalid_challenge'); + } + } + /** * 관리자를 로그아웃시킵니다. * @@ -113,16 +209,7 @@ class AuthController extends AdminBaseController } catch (AccountLockedException $e) { // 재발급도 세션을 여는 지점이다 — 사용자 경로와 같은 423 계약을 따른다. // 이 catch 가 없으면 잠긴 계정의 재발급 시도가 500 으로 새어 나간다. - return $this->error( - $e->isPermanent() ? 'auth.account_locked_permanently' : 'auth.account_locked', - 423, - [ - 'locked_until' => $e->lockedUntil?->toIso8601String(), - 'retry_after_seconds' => $e->remainingMinutes === null ? null : $e->remainingMinutes * 60, - 'permanent' => $e->isPermanent(), - ], - ['minutes' => $e->remainingMinutes] - ); + return $this->lockedResponse($e); } catch (ValidationException $e) { return $this->unauthorized('auth.unauthenticated'); } diff --git a/app/Http/Controllers/Api/Auth/AuthController.php b/app/Http/Controllers/Api/Auth/AuthController.php index d66a9007..d5085011 100644 --- a/app/Http/Controllers/Api/Auth/AuthController.php +++ b/app/Http/Controllers/Api/Auth/AuthController.php @@ -3,13 +3,16 @@ namespace App\Http\Controllers\Api\Auth; use App\Exceptions\Auth\AccountLockedException; +use App\Exceptions\Auth\TwoFactorDeliveryFailedException; use App\Http\Controllers\Api\Base\AuthBaseController; +use App\Http\Controllers\Concerns\BuildsAuthFailureResponses; use App\Http\Requests\Auth\AuthenticatedRequest; use App\Http\Requests\Auth\ForgotPasswordRequest; use App\Http\Requests\Auth\LoginRequest; use App\Http\Requests\Auth\RegisterRequest; use App\Http\Requests\Auth\ResetPasswordRequest; use App\Http\Requests\Auth\TwoFactorChallengeRequest; +use App\Http\Requests\Auth\TwoFactorResendRequest; use App\Http\Requests\Auth\ValidateResetTokenRequest; use App\Http\Resources\UserResource; use App\Services\AuthService; @@ -18,6 +21,8 @@ use Illuminate\Validation\ValidationException; class AuthController extends AuthBaseController { + use BuildsAuthFailureResponses; + public function __construct( private AuthService $authService ) { @@ -27,8 +32,9 @@ class AuthController extends AuthBaseController // 공개 인증 엔드포인트를 제외한 나머지에만 인증 미들웨어 적용 $this->middleware('auth:sanctum')->except([ 'login', - // 2단계 인증 확인은 아직 토큰이 없는 상태에서 호출된다 — 주체는 challenge 가 식별한다 + // 2단계 인증 확인·재발송은 아직 토큰이 없는 상태에서 호출된다 — 주체는 challenge 가 식별한다 'verifyTwoFactor', + 'resendTwoFactor', 'register', 'forgotPassword', 'resetPassword', @@ -61,6 +67,8 @@ class AuthController extends AuthBaseController return $this->success('auth.login_success', $data); } catch (AccountLockedException $e) { return $this->lockedResponse($e); + } catch (TwoFactorDeliveryFailedException $e) { + return $this->deliveryFailedResponse(); } catch (ValidationException $e) { return $this->unauthorized('auth.login_failed'); } @@ -92,32 +100,37 @@ class AuthController extends AuthBaseController // 세션을 여는 지점이므로 `login` 과 같은 423 계약을 따른다 — 화면은 두 경로를 // 구분하지 않으므로 한쪽만 다른 모양이면 잠금 안내가 깨진다. return $this->lockedResponse($e); + } catch (TwoFactorDeliveryFailedException $e) { + return $this->deliveryFailedResponse(); } catch (ValidationException $e) { return $this->unauthorized('auth.two_factor_failed'); } } /** - * 계정 잠금 응답(423)을 구성합니다. + * 2단계 인증 코드를 재발송합니다. * - * 세션을 발급하는 모든 엔드포인트가 같은 페이로드를 돌려주도록 단일 지점에서 만든다. + * 기존 challenge 는 취소되고 새 challenge 가 발행되므로, 앞서 받은 인증번호는 + * 더 이상 통하지 않습니다. * - * @param AccountLockedException $e 잠금 예외 - * @return JsonResponse 423 응답 + * @param TwoFactorResendRequest $request challenge 재발송 요청 + * @return JsonResponse 새 challenge 정보를 포함한 JSON 응답 */ - private function lockedResponse(AccountLockedException $e): JsonResponse + public function resendTwoFactor(TwoFactorResendRequest $request): JsonResponse { - // 영구 잠금(무한대 설정)은 해제 시각·잔여 시간이 없다 — null 그대로 노출. - return $this->error( - $e->isPermanent() ? 'auth.account_locked_permanently' : 'auth.account_locked', - 423, - [ - 'locked_until' => $e->lockedUntil?->toIso8601String(), - 'retry_after_seconds' => $e->remainingMinutes === null ? null : $e->remainingMinutes * 60, - 'permanent' => $e->isPermanent(), - ], - ['minutes' => $e->remainingMinutes] - ); + try { + $data = $this->authService->resendTwoFactorChallenge( + $request->validated()['challenge_id'] + ); + + return $this->success('auth.two_factor_required', $data); + } catch (AccountLockedException $e) { + return $this->lockedResponse($e); + } catch (TwoFactorDeliveryFailedException $e) { + return $this->deliveryFailedResponse(); + } catch (ValidationException $e) { + return $this->validationError($e->errors(), 'auth.two_factor_invalid_challenge'); + } } /** diff --git a/app/Http/Controllers/Api/Identity/IdentityVerificationController.php b/app/Http/Controllers/Api/Identity/IdentityVerificationController.php index 89fc494e..573f6336 100644 --- a/app/Http/Controllers/Api/Identity/IdentityVerificationController.php +++ b/app/Http/Controllers/Api/Identity/IdentityVerificationController.php @@ -3,6 +3,7 @@ namespace App\Http\Controllers\Api\Identity; use App\Enums\IdentityOriginType; +use App\Enums\IdentityVerificationPurpose; use App\Extension\IdentityVerification\IdentityVerificationManager; use App\Http\Controllers\Api\Base\PublicBaseController; use App\Http\Requests\Identity\CancelChallengeRequest; @@ -96,6 +97,15 @@ class IdentityVerificationController extends PublicBaseController */ public function verify(VerifyChallengeRequest $request, IdentityVerificationLog $challenge): JsonResponse { + // 로그인 challenge 는 이 공개 경로로 다루지 않는다. 여기서 검증·취소되면 + // 바로 뒤의 `auth/login/two-factor` 가 INVALID_STATE 로 거절해, 그 challenge 로는 + // 영영 로그인할 수 없게 된다(자기 DoS). 로그인 전용 엔드포인트만 사용한다. + if ($challenge->purpose === IdentityVerificationPurpose::Login->value) { + return $this->error('identity.errors.purpose_not_allowed', 403, [ + 'failure_code' => 'PURPOSE_NOT_ALLOWED', + ]); + } + $result = $this->service->verify( challengeId: $challenge->id, input: $request->validated(), @@ -142,6 +152,15 @@ class IdentityVerificationController extends PublicBaseController */ public function cancel(CancelChallengeRequest $request, IdentityVerificationLog $challenge): JsonResponse { + // 로그인 challenge 는 이 공개 경로로 다루지 않는다. 여기서 검증·취소되면 + // 바로 뒤의 `auth/login/two-factor` 가 INVALID_STATE 로 거절해, 그 challenge 로는 + // 영영 로그인할 수 없게 된다(자기 DoS). 로그인 전용 엔드포인트만 사용한다. + if ($challenge->purpose === IdentityVerificationPurpose::Login->value) { + return $this->error('identity.errors.purpose_not_allowed', 403, [ + 'failure_code' => 'PURPOSE_NOT_ALLOWED', + ]); + } + $ok = $this->service->cancel($challenge->id); if (! $ok) { diff --git a/app/Http/Controllers/Concerns/BuildsAuthFailureResponses.php b/app/Http/Controllers/Concerns/BuildsAuthFailureResponses.php new file mode 100644 index 00000000..f5588287 --- /dev/null +++ b/app/Http/Controllers/Concerns/BuildsAuthFailureResponses.php @@ -0,0 +1,53 @@ +error( + $e->isPermanent() ? 'auth.account_locked_permanently' : 'auth.account_locked', + 423, + [ + 'locked_until' => $e->lockedUntil?->toIso8601String(), + 'retry_after_seconds' => $e->remainingMinutes === null ? null : $e->remainingMinutes * 60, + 'permanent' => $e->isPermanent(), + ], + ['minutes' => $e->remainingMinutes] + ); + } + + /** + * 인증번호 발송 실패 응답(503)을 구성합니다. + * + * 자격 증명은 올바르므로 401 로 답하지 않는다 — 사용자는 비밀번호를 의심하며 같은 + * 실패를 반복하고, 운영자는 메일 설정이 깨진 사실을 알 방법이 없다. + * + * @return JsonResponse 503 응답 + */ + protected function deliveryFailedResponse(): JsonResponse + { + return $this->error('auth.two_factor_delivery_failed', 503); + } +} diff --git a/app/Http/Requests/Auth/TwoFactorResendRequest.php b/app/Http/Requests/Auth/TwoFactorResendRequest.php new file mode 100644 index 00000000..8ba3f3cf --- /dev/null +++ b/app/Http/Requests/Auth/TwoFactorResendRequest.php @@ -0,0 +1,54 @@ + 검증 규칙 + */ + public function rules(): array + { + $rules = [ + 'challenge_id' => ['required', 'string', 'uuid'], + ]; + + // 확장이 자체 2단계 수단을 붙일 때 재발송 입력을 추가할 수 있도록 개방한다 + return HookManager::applyFilters('core.auth.two_factor_resend_validation_rules', $rules, $this); + } + + /** + * 검증 실패 메시지를 반환합니다. + * + * @return array 검증 메시지 + */ + public function messages(): array + { + return [ + 'challenge_id.required' => __('validation.auth.two_factor.challenge_required'), + 'challenge_id.uuid' => __('validation.auth.two_factor.challenge_invalid'), + ]; + } +} diff --git a/app/Providers/AppServiceProvider.php b/app/Providers/AppServiceProvider.php index 6e264c4b..ed93514f 100644 --- a/app/Providers/AppServiceProvider.php +++ b/app/Providers/AppServiceProvider.php @@ -9,6 +9,7 @@ use App\Contracts\Notifications\ChannelReadinessCheckerInterface; use App\Extension\HookManager; use App\Extension\ModuleManager; use App\Extension\PluginManager; +use App\Helpers\ResponseHelper; use App\Http\View\Composers\TemplateComposer; use App\Http\View\Composers\UserTemplateComposer; use App\Notifications\NotificationChannelManager; @@ -126,7 +127,18 @@ class AppServiceProvider extends ServiceProvider $maxPerMinute = 60; } - return Limit::perMinute($maxPerMinute)->by($request->ip()); + // 기본 응답은 영문 "Too Many Attempts." 이다 — 로그인 화면은 이 문구를 + // 그대로 노출하므로 다국어 키로 갈아끼운다. + return Limit::perMinute($maxPerMinute) + ->by($request->ip()) + ->response(function (Request $request, array $headers) { + return ResponseHelper::error( + 'auth.too_many_attempts', + 429, + null, + ['seconds' => (int) ($headers['Retry-After'] ?? 60)] + )->withHeaders($headers); + }); }); } diff --git a/app/Services/AuthService.php b/app/Services/AuthService.php index dea93863..c57dea68 100644 --- a/app/Services/AuthService.php +++ b/app/Services/AuthService.php @@ -2,6 +2,7 @@ namespace App\Services; +use App\Contracts\Repositories\IdentityVerificationLogRepositoryInterface; use App\Contracts\Repositories\PasswordResetTokenRepositoryInterface; use App\Contracts\Repositories\RoleRepositoryInterface; use App\Contracts\Repositories\UserConsentRepositoryInterface; @@ -11,6 +12,7 @@ use App\Enums\IdentityVerificationPurpose; use App\Enums\IdentityVerificationStatus; use App\Enums\UserStatus; use App\Exceptions\Auth\AccountLockedException; +use App\Exceptions\Auth\TwoFactorDeliveryFailedException; use App\Extension\HookManager; use App\Models\User; use Carbon\Carbon; @@ -30,6 +32,7 @@ class AuthService private UserConsentRepositoryInterface $userConsentRepository, private PasswordResetTokenRepositoryInterface $passwordResetTokenRepository, private IdentityPolicyService $policyService, + private IdentityVerificationLogRepositoryInterface $identityLogRepository, ) {} /** @@ -228,9 +231,9 @@ class AuthService 'provider_id' => $challenge->providerId, ]); - throw ValidationException::withMessages([ - 'email' => [__('auth.two_factor_delivery_failed')], - ]); + // 자격 증명은 올바르다 — 401 로 뭉개면 사용자는 비밀번호를 의심하며 같은 실패를 + // 반복하고, 운영자는 메일 설정이 깨진 사실을 알 방법이 없다. + throw new TwoFactorDeliveryFailedException; } HookManager::doAction('core.auth.two_factor_requested', $user, [ @@ -298,6 +301,83 @@ class AuthService return $this->issueLoginSession($user, (string) $user->email); } + /** + * 2단계 인증 코드를 재발송합니다. + * + * 아직 사용되지 않은 challenge 만 재발송 대상입니다. 기존 challenge 를 취소하고 새로 + * 발행하므로, 재발송 이후에는 앞서 받은 인증번호가 통하지 않습니다 — 재발송을 남겨 두면 + * 유효한 코드가 여러 개 동시에 살아 있어 대입 시도의 표적이 넓어집니다. + * + * 해석된 사용자는 응답 페이로드에 실리지 않고 out 파라미터로만 올린다 — 관리자 경로가 + * 그 사용자로 등급을 판정해야 하지만, 사용자 경로가 그대로 내보내면 모델이 응답에 새는다. + * + * @param string $challengeId 비밀번호 확인 단계가 돌려준 challenge UUID + * @param User|null $resolvedUser (out) challenge 가 식별한 사용자 + * @return array{two_factor_required: bool, challenge_id: string, provider_id: string, expires_at: mixed} 새 challenge 정보 + * + * @throws ValidationException challenge 가 재발송 대상이 아닐 때 + * @throws AccountLockedException 계정이 잠겨 있을 때 + * @throws TwoFactorDeliveryFailedException 인증번호를 보내지 못했을 때 + */ + public function resendTwoFactorChallenge(string $challengeId, ?User &$resolvedUser = null): array + { + $log = $this->identityLogRepository->findById($challengeId); + + // 존재하지 않음 / 다른 용도 / 이미 검증·취소·실패·만료 — 전부 같은 응답으로 답한다. + // 사유를 구분해 주면 challenge id 를 넣어 보며 상태를 캐낼 수 있다. + $resendable = [ + IdentityVerificationStatus::Requested->value, + IdentityVerificationStatus::Sent->value, + ]; + + if ($log === null + || $log->purpose !== IdentityVerificationPurpose::Login->value + || ! in_array($log->status->value, $resendable, true) + || ($log->expires_at !== null && $log->expires_at->isPast()) + ) { + throw ValidationException::withMessages([ + 'challenge_id' => [__('auth.two_factor_invalid_challenge')], + ]); + } + + $user = $log->user_id === null ? null : $this->userRepository->findById((int) $log->user_id); + + if (! $user || $user->status !== UserStatus::Active->value) { + throw ValidationException::withMessages([ + 'challenge_id' => [__('auth.two_factor_invalid_challenge')], + ]); + } + + // challenge 발급 이후에 잠겼을 수 있다 — 재발송도 잠긴 계정에는 코드를 보내지 않는다. + $this->assertNotLocked($user); + + $resolvedUser = $user; + + app(IdentityVerificationService::class)->cancel($log->id); + + return $this->startTwoFactorChallenge($user, (string) $user->email); + } + + /** + * 이미 발급된 세션(토큰 + web 세션)을 되돌립니다. + * + * 2단계 인증 완료는 코드 확인 시점에 토큰을 발급하므로, 그 뒤에 권한 검사로 거절하는 + * 경로는 발급분을 반드시 회수해야 합니다. `logout()` 은 `currentAccessToken()` 에 + * 의존해 이 시점(요청 자체는 미인증)에는 아무 일도 하지 않습니다. + * + * @param User $user 대상 사용자 + * @param string $plainTextToken 방금 발급한 평문 토큰 ({id}|{token} 형식) + */ + public function revokeIssuedSession(User $user, string $plainTextToken): void + { + PersonalAccessToken::findToken($plainTextToken)?->delete(); + + // completeTwoFactor() 의 Auth::login() 이 연 세션도 함께 닫는다. + if (request()->hasSession() && request()->session()->isStarted() && Auth::guard('web')->check()) { + Auth::guard('web')->logout(); + } + } + /** * 토큰을 발급하고 로그인 완료 훅을 실행합니다. * diff --git a/config/app.php b/config/app.php index 6903550e..ce066c68 100644 --- a/config/app.php +++ b/config/app.php @@ -231,7 +231,7 @@ return [ | */ - 'version' => env('APP_VERSION', '7.0.10'), + 'version' => env('APP_VERSION', '7.0.11'), /* |-------------------------------------------------------------------------- diff --git a/docs/backend/api/README.md b/docs/backend/api/README.md index 67a5623a..a3087ec2 100644 --- a/docs/backend/api/README.md +++ b/docs/backend/api/README.md @@ -219,14 +219,14 @@ CSS 가 아닌 자산은 바이트 그대로 서빙됩니다. 정적 게시본(` ## 코어 API 레퍼런스 -- **문서 수**: 36 · **엔드포인트 수**: 325 +- **문서 수**: 36 · **엔드포인트 수**: 328 | 문서 | 도메인 | 엔드포인트 | | --- | --- | --- | | [activity-logs.md](activity-logs.md) | `activity-logs` | 3 | | [attachment.md](attachment.md) | `attachment` | 1 | | [attachments.md](attachments.md) | `attachments` | 4 | -| [auth.md](auth.md) | `auth` | 15 | +| [auth.md](auth.md) | `auth` | 18 | | [avatar.md](avatar.md) | `avatar` | 2 | | [broadcasting.md](broadcasting.md) | `broadcasting` | 1 | | [changelog.md](changelog.md) | `changelog` | 1 | diff --git a/docs/backend/api/auth.md b/docs/backend/api/auth.md index f945840b..0f7da50e 100644 --- a/docs/backend/api/auth.md +++ b/docs/backend/api/auth.md @@ -339,6 +339,8 @@ HTTP/1.1 200 | 403 | Forbidden | 자격 증명은 맞지만 관리자 역할이 아닌 경우 (`auth.admin_required`) | | 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지) | | 423 | Locked | 로그인 실패 누적으로 계정이 잠긴 경우 (`auth.account_locked` — `error.locked_until`, `error.retry_after_seconds` 포함) | +| 429 | Too Many Requests | `throttle:auth-login` 초과 (`auth.too_many_attempts`) | +| 503 | Service Unavailable | 2단계 인증이 켜져 있고 인증번호를 보내지 못한 경우 (`auth.two_factor_delivery_failed`) | @@ -346,6 +348,169 @@ HTTP/1.1 200 관리자 로그인. `email`/`password` 검증 후 `AuthService::login()` 이 인증하고, 인증 사용자가 `isAdmin()` 이 아니면 `403 auth.admin_required` 로 거부한다. 성공 시 `data.token`(Sanctum Bearer) 과 `data.user`(UserResource) 를 반환한다. 계정 잠금 시 `AccountLockedException`, 자격 불일치 시 `422` 검증 오류를 반환한다. 이후 모든 관리자 API 호출은 이 토큰을 `Authorization: Bearer` 헤더로 실어야 한다. +**403 거부는 이미 발급된 세션을 회수한다.** `AuthService::login()` 은 관리자 판정보다 먼저 토큰과 web 세션을 발급하므로, 거부하면서 그대로 두면 관리자가 아닌 사용자가 응답만 `403` 을 받을 뿐 유효한 세션을 손에 쥔다. 거부 경로는 `AuthService::revokeIssuedSession()` 으로 그 발급분을 되돌린다. + +**2단계 인증이 켜져 있는 경우**: 사용자 로그인과 동일하게 `200` + `message: auth.two_factor_required` 와 `two_factor_required` / `challenge_id` / `provider_id` / `expires_at` 을 반환한다(필드 정의는 `POST /api/auth/login` 의 같은 절 참조). 이 단계에서는 아직 사용자도 토큰도 없으므로 **관리자 판정을 하지 않는다** — 판정은 `POST /api/auth/admin/login/two-factor` 가 코드 확인에 성공한 뒤에 수행한다. + + +### POST /api/auth/admin/login/two-factor + +- **라우트명**: `api.auth.admin.login.two-factor` +- **컨트롤러**: `App\Http\Controllers\Api\Admin\AuthController@verifyTwoFactor` +- **인증/권한**: 공개 (인증 불필요 — 주체는 challenge 가 식별한다) + +**요청 파라미터** + +| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 | +| --- | --- | --- | --- | --- | --- | +| challenge_id | body | string | 예 | uuid | 관리자 로그인 응답이 돌려준 challenge 식별자 | +| code | body | string | 예 | min 4, max 16 | 사용자가 받은 인증 코드 | + +> 이 엔드포인트는 확장이 파라미터를 추가할 수 있습니다 (`core.auth.two_factor_validation_rules`). + +**요청 예시** + +```http +POST /api/auth/admin/login/two-factor HTTP/1.1 +Host: api.example.com +Accept: application/json +Content-Type: application/json + +{ + "challenge_id": "9f1c2f2e-0b3a-4f0a-9a1e-5c1b7f9d2c40", + "code": "135790" +} +``` + +**응답 필드** (`data` 내부) + +_단건 응답: `POST /api/auth/admin/login` 의 성공 페이로드와 동일하다._ + +| 필드 | 타입 | 실측 예시값 | 용도/설명 | +| --- | --- | --- | --- | +| user | object | `{"uuid":"a234c2b1-…","is_admin":true, …}` | 로그인한 관리자 정보 (`UserResource`) | +| token | string | `75\|WgPUplvLGTv8YIj4507uIR6dEOHTXyNUed…` | 발급된 Sanctum 접근 토큰 평문 | +| token_type | string | `Bearer` | 토큰 타입 (항상 `Bearer`) | + +**응답 예시** + +```http +HTTP/1.1 200 +``` + +```json +{ + "success": true, + "message": "관리자 로그인이 성공했습니다.", + "data": { + "user": { + "uuid": "a234c2b1-cde8-437f-b28b-23323be2b98d", + "name": "API 문서 샘플 사용자", + "email": "apidoc-sample-user@example.com", + "status": "active", + "is_admin": true, + "is_owner": true + }, + "token": "{MASKED}", + "token_type": "Bearer" + } +} +``` + +> `user` 객체는 지면 절약을 위해 축약했습니다. 실제로는 `UserResource` 필드 전수가 내려옵니다. + +**에러 응답** + +| 상태코드 | 의미 | 발생 조건 | +| --- | --- | --- | +| 401 | Unauthorized | 코드가 틀렸거나(`auth.two_factor_failed`), challenge 의 `purpose` 가 `login` 이 아니거나, 확인된 사용자가 없거나 `active` 상태가 아닌 경우 | +| 403 | Forbidden | 코드 확인은 통과했으나 관리자 역할이 아닌 경우 (`auth.admin_required`) | +| 422 | Unprocessable Entity | `challenge_id`/`code` 형식 위반 | +| 423 | Locked | 로그인 실패 누적으로 계정이 잠긴 경우. 응답 형태는 `POST /api/auth/login` 의 423 과 동일 | +| 429 | Too Many Requests | `throttle:auth-login` 초과 (`auth.too_many_attempts`) | + + + +**설명** + +관리자 로그인의 인증번호 확인 단계. 사용자 경로(`POST /api/auth/login/two-factor`)와 같은 규칙으로 코드를 확인하고, **확인에 성공한 뒤에** 관리자 여부를 판정한다. + +`AuthService::completeTwoFactor()` 는 코드 확인에 성공한 시점에 토큰을 발급하므로, 관리자 판정으로 `403` 을 돌려줄 때는 반드시 그 발급분을 회수한다(`revokeIssuedSession()`). 회수하지 않으면 관리자가 아닌 사용자가 응답만 `403` 을 받을 뿐 유효한 세션을 손에 쥔다. + + +### POST /api/auth/admin/login/two-factor/resend + +- **라우트명**: `api.auth.admin.login.two-factor.resend` +- **컨트롤러**: `App\Http\Controllers\Api\Admin\AuthController@resendTwoFactor` +- **인증/권한**: 공개 (인증 불필요 — 주체는 challenge 가 식별한다) + +**요청 파라미터** + +| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 | +| --- | --- | --- | --- | --- | --- | +| challenge_id | body | string | 예 | uuid | 관리자 로그인 응답이 돌려준 challenge 식별자 | + +**요청 예시** + +```http +POST /api/auth/admin/login/two-factor/resend HTTP/1.1 +Host: api.example.com +Accept: application/json +Content-Type: application/json + +{ + "challenge_id": "9f1c2f2e-0b3a-4f0a-9a1e-5c1b7f9d2c40" +} +``` + +**응답 필드** (`data` 내부) + +_`POST /api/auth/login/two-factor/resend` 와 동일한 형태다._ + +| 필드 | 타입 | 실측 예시값 | 용도/설명 | +| --- | --- | --- | --- | +| two_factor_required | boolean | `true` | 항상 `true` | +| challenge_id | string(uuid) | `9f1c2f2e-0b3a-…` | **새** challenge 식별자 (이전 값은 취소됨) | +| provider_id | string | `g7:core.mail` | 코드를 발송한 본인인증 프로바이더 | +| expires_at | string(ISO8601)\|null | `2026-09-07T14:03:00+09:00` | 새 challenge 만료 시각 | + +**응답 예시** + +```http +HTTP/1.1 200 +``` + +```json +{ + "success": true, + "message": "인증번호를 보냈습니다. 받은 번호를 입력해 로그인을 완료해주세요.", + "data": { + "two_factor_required": true, + "challenge_id": "9f1c2f2e-0b3a-4f0a-9a1e-5c1b7f9d2c40", + "provider_id": "g7:core.mail", + "expires_at": "2026-09-07T14:03:00+09:00" + } +} +``` + +**에러 응답** + +| 상태코드 | 의미 | 발생 조건 | +| --- | --- | --- | +| 403 | Forbidden | challenge 가 식별한 사용자가 관리자 역할이 아닌 경우 (`auth.admin_required`) | +| 422 | Unprocessable Entity | 재발송 대상이 아닌 challenge (`auth.two_factor_invalid_challenge`) — 사유는 구분하지 않는다 | +| 423 | Locked | challenge 를 받은 뒤 계정이 잠긴 경우 | +| 429 | Too Many Requests | `throttle:auth-login` 초과 (`auth.too_many_attempts`) | +| 503 | Service Unavailable | 새 인증번호를 보내지 못한 경우 (`auth.two_factor_delivery_failed`) | + + + +**설명** + +관리자 로그인의 인증번호 재발송. 규칙은 `POST /api/auth/login/two-factor/resend` 와 동일하다 — 기존 challenge 를 취소하고 새로 발행하므로 앞서 받은 인증번호는 통하지 않는다. + +이 단계는 토큰을 발급하지 않으므로 회수할 것이 없다. 다만 완료할 수 없는 상대에게 새 인증번호를 계속 보내지는 않으므로, challenge 가 식별한 사용자가 관리자가 아니면 `403 auth.admin_required` 로 거부한다. 발급 자체를 막는 것이 아니라 **재발송만** 막는 것이며, 비밀번호 확인 단계(`POST /api/auth/admin/login`)는 종전대로 관리자 판정 없이 challenge 를 돌려준다. + ### POST /api/auth/forgot-password @@ -488,6 +653,8 @@ HTTP/1.1 200 | 401 | Unauthenticated | 이메일/비밀번호가 일치하지 않거나 계정 상태가 활성이 아닌 경우 (`auth.login_failed`) | | 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지) | | 423 | Locked | 로그인 실패 누적으로 계정이 잠긴 경우 (`auth.account_locked` — `error.locked_until`, `error.retry_after_seconds` 포함) | +| 429 | Too Many Requests | `throttle:auth-login` 초과 (`auth.too_many_attempts` — `Retry-After` 헤더 동반) | +| 503 | Service Unavailable | 2단계 인증이 켜져 있고 인증번호를 보내지 못한 경우 (`auth.two_factor_delivery_failed`) | @@ -504,7 +671,9 @@ HTTP/1.1 200 | `provider_id` | string | 코드를 발송한 본인인증 프로바이더 | | `expires_at` | string(ISO8601)\|null | challenge 만료 시각 | -이 응답에는 `data.token` 과 `data.user` 가 없다. 토큰 존재 여부로 로그인 완료를 판정하는 클라이언트는 그대로 동작한다. +이 응답에는 `data.token` 과 `data.user` 가 없다. **클라이언트는 `two_factor_required` 를 먼저 판정해야 한다** — 응답 형태가 하나라고 가정하고 `data.user.*` 를 읽으면 그 자리에서 예외가 나고, `data.token` 을 그대로 저장하면 `"undefined"` 문자열이 남아 이후 모든 요청이 `401` 로 튕긴다(공개 #133). 코어 클라이언트(`AuthManager.login()`)는 `LoginResult` 판별 유니온으로 두 형태를 구분해 돌려준다. + +**인증번호를 보내지 못한 경우**: 자격 증명은 올바르지만 코드를 전달할 수단이 없으므로 로그인을 완료할 수 없다. 이때는 `401`(자격 증명 오류)이 아니라 `503 auth.two_factor_delivery_failed` 를 반환한다 — `401` 로 뭉뚱그리면 사용자는 비밀번호를 의심하며 같은 실패를 반복하고, 운영자는 메일 설정이 깨진 사실을 알 방법이 없다. 발송에 실패해도 2단계 인증을 건너뛰고 로그인시키지는 않는다. ### POST /api/auth/login/two-factor @@ -590,7 +759,7 @@ HTTP/1.1 200 | 401 | Unauthorized | 코드가 틀렸거나(`auth.two_factor_failed`), challenge 의 `purpose` 가 `login` 이 아니거나, 확인된 사용자가 없거나 `active` 상태가 아닌 경우. **세 사유를 같은 응답으로 뭉뚱그린다** — 구분해 내보내면 challenge 유효성 탐색에 쓰인다 | | 422 | Unprocessable Entity | `challenge_id`/`code` 형식 위반 | | 423 | Locked | 로그인 실패 누적으로 계정이 잠긴 경우. 응답 형태는 `POST /api/auth/login` 의 423 과 동일하다 (`auth.account_locked` / 무기한이면 `auth.account_locked_permanently` — `errors.locked_until`, `errors.retry_after_seconds`, `errors.permanent`) | -| 429 | Too Many Requests | `throttle:auth-login` 초과 (로그인과 같은 제한을 공유하므로 코드 대입 시도도 함께 억제된다) | +| 429 | Too Many Requests | `throttle:auth-login` 초과 (로그인과 같은 제한을 공유하므로 코드 대입 시도도 함께 억제된다 — `auth.too_many_attempts`) | @@ -603,6 +772,79 @@ challenge 의 `purpose` 가 `login` 인지 먼저 대조한다 — 대조하지 **계정 잠금은 이 단계에서 다시 검사한다.** 세션을 여는 것은 비밀번호 단계가 아니라 이 엔드포인트이므로, challenge 를 받은 뒤 잠긴 계정은 여기서 `423` 으로 차단된다. 잠기기 전에 발급받은 challenge 를 잠긴 뒤에 완료하는 것만으로 잠금을 우회할 수 없다. 차단은 로그인 완료 훅(`core.auth.after_login`)보다 앞서므로 실패 횟수·잠금 해제 시각도 초기화되지 않는다. +### POST /api/auth/login/two-factor/resend + +- **라우트명**: `api.auth.login.two-factor.resend` +- **컨트롤러**: `App\Http\Controllers\Api\Auth\AuthController@resendTwoFactor` +- **인증/권한**: 공개 (인증 불필요) + +**요청 파라미터** + +| 이름 | 위치 | 타입 | 필수 | 허용값 | 용도 | +| --- | --- | --- | --- | --- | --- | +| challenge_id | body | string | 예 | uuid | 로그인 응답이 돌려준 challenge 식별자 | + +**요청 예시** + +```http +POST /api/auth/login/two-factor/resend HTTP/1.1 +Host: api.example.com +Accept: application/json +Content-Type: application/json + +{ + "challenge_id": "9f1c2f2e-0b3a-4f0a-9a1e-5c1b7f9d2c40" +} +``` + +**응답 필드** (`data` 내부) + +_단건 응답: `data` 객체의 필드 (`AuthService::resendTwoFactorChallenge()` 가 새로 발행한 challenge — `POST /api/auth/login` 의 2단계 인증 응답과 같은 형태)._ + +| 필드 | 타입 | 실측 예시값 | 용도/설명 | +| --- | --- | --- | --- | +| two_factor_required | boolean | `true` | 항상 `true` — 여전히 추가 확인 단계임을 나타낸다 | +| challenge_id | string(uuid) | `9f1c2f2e-0b3a-…` | **새** challenge 식별자. 이전 값은 취소되었으므로 반드시 교체해야 한다 | +| provider_id | string | `g7:core.mail` | 코드를 발송한 본인인증 프로바이더 | +| expires_at | string(ISO8601)\|null | `2026-09-07T14:03:00+09:00` | 새 challenge 만료 시각 | + +**응답 예시** + +```http +HTTP/1.1 200 +``` + +```json +{ + "success": true, + "message": "인증번호를 보냈습니다. 받은 번호를 입력해 로그인을 완료해주세요.", + "data": { + "two_factor_required": true, + "challenge_id": "9f1c2f2e-0b3a-4f0a-9a1e-5c1b7f9d2c40", + "provider_id": "g7:core.mail", + "expires_at": "2026-09-07T14:03:00+09:00" + } +} +``` + +**에러 응답** + +| 상태코드 | 의미 | 발생 조건 | +| --- | --- | --- | +| 422 | Unprocessable Entity | `challenge_id` 형식 위반, 또는 재발송 대상이 아닌 challenge (`auth.two_factor_invalid_challenge`) — 존재하지 않음 / `purpose` 가 `login` 이 아님 / 이미 검증·취소·실패 / 만료 / 대상 사용자가 없거나 `active` 가 아님. **사유를 구분하지 않는다** — 구분해 내보내면 challenge 유효성 탐색에 쓰인다 | +| 423 | Locked | challenge 를 받은 뒤 계정이 잠긴 경우. 응답 형태는 `POST /api/auth/login` 의 423 과 동일하다 | +| 429 | Too Many Requests | `throttle:auth-login` 초과 (`auth.too_many_attempts`) | +| 503 | Service Unavailable | 새 인증번호를 보내지 못한 경우 (`auth.two_factor_delivery_failed`) | + + + +**설명** + +인증번호를 받지 못했을 때 새 코드를 발행한다. 서버는 **기존 challenge 를 취소하고 새로 발행**하므로, 앞서 받은 인증번호는 더 이상 통하지 않는다 — 유효한 코드를 여러 개 동시에 살려 두면 대입 시도의 표적이 넓어진다. 클라이언트는 응답의 `challenge_id` 로 반드시 교체하고 입력란을 비워야 한다. + +계정 잠금은 여기서도 다시 검사한다. challenge 를 받은 뒤 잠긴 계정에는 새 코드를 보내지 않는다. 로그인과 같은 요청 제한(`throttle:auth-login`)이 걸린다. + + ### POST /api/auth/logout - **라우트명**: `api.auth.logout` diff --git a/docs/backend/api/identity.md b/docs/backend/api/identity.md index bace9eeb..a19a02e2 100644 --- a/docs/backend/api/identity.md +++ b/docs/backend/api/identity.md @@ -2518,13 +2518,13 @@ HTTP/1.1 200 | 상태코드 | 의미 | 발생 조건 | | --- | --- | --- | | 401 | Unauthenticated | Bearer 토큰을 보냈으나 만료/무효인 경우 (비회원은 헤더 생략 가능) | -| 403 | Forbidden | 요구 권한(`core.identity.cancel`)이 없는 경우, 또는 scope=self 가드가 본인 challenge 가 아니라고 판정한 경우 | +| 403 | Forbidden | 요구 권한(`core.identity.cancel`)이 없는 경우, scope=self 가드가 본인 challenge 가 아니라고 판정한 경우, 또는 challenge 의 `purpose` 가 `login` 인 경우 (`identity.errors.purpose_not_allowed` — `errors.failure_code = PURPOSE_NOT_ALLOWED`) | | 404 | Not Found | path 의 challenge 를 찾을 수 없거나 취소 처리에 실패한 경우 (`유효하지 않은 인증 요청입니다.`) | | 422 | Unprocessable Entity | 요청 파라미터가 검증 규칙을 위반한 경우 (`error.errors` 에 필드별 메시지) | -**설명** 진행 중인 challenge 를 취소합니다. `auth:sanctum` + `core.identity.cancel` 권한이 필요합니다. 라우트 모델 바인딩 + PermissionMiddleware 의 scope=self 가드로 로그인 사용자는 본인 challenge 만 취소할 수 있으며, 비로그인 게스트는 guest 역할 권한으로 진입합니다(모달 취소 시 audit trail 정합용). `IdentityVerificationService::cancel` 이 처리하고 대상 challenge 가 없으면 404 를 반환합니다. 사용자가 인증 모달을 닫을 때 서버 상태를 cancelled 로 남겨 이력 정합성을 맞추는 데 사용합니다. +**설명** 진행 중인 challenge 를 취소합니다. **로그인 2단계 인증 challenge(`purpose = login`)는 이 경로로 취소할 수 없습니다** — 취소되면 그 challenge 로는 더 이상 로그인을 마칠 수 없게 되어, 사용자가 자기 로그인을 스스로 막는 상태가 됩니다(자기 DoS). 로그인 흐름은 `POST /api/auth/login/two-factor` · `.../resend` 만 사용합니다. `auth:sanctum` + `core.identity.cancel` 권한이 필요합니다. 라우트 모델 바인딩 + PermissionMiddleware 의 scope=self 가드로 로그인 사용자는 본인 challenge 만 취소할 수 있으며, 비로그인 게스트는 guest 역할 권한으로 진입합니다(모달 취소 시 audit trail 정합용). `IdentityVerificationService::cancel` 이 처리하고 대상 challenge 가 없으면 404 를 반환합니다. 사용자가 인증 모달을 닫을 때 서버 상태를 cancelled 로 남겨 이력 정합성을 맞추는 데 사용합니다. ### POST /api/identity/challenges/{challenge}/verify @@ -2593,13 +2593,13 @@ HTTP/1.1 200 | 상태코드 | 의미 | 발생 조건 | | --- | --- | --- | | 401 | Unauthenticated | Bearer 토큰을 보냈으나 만료/무효인 경우 (비회원은 헤더 생략 가능) | -| 403 | Forbidden | 요구 권한(`core.identity.verify`)이 없는 경우, 또는 scope=self 가드가 본인 challenge 가 아니라고 판정한 경우 | +| 403 | Forbidden | 요구 권한(`core.identity.verify`)이 없는 경우, scope=self 가드가 본인 challenge 가 아니라고 판정한 경우, 또는 challenge 의 `purpose` 가 `login` 인 경우 (`identity.errors.purpose_not_allowed` — `errors.failure_code = PURPOSE_NOT_ALLOWED`) | | 404 | Not Found | path 파라미터에 해당하는 challenge 가 없는 경우 | | 422 | Unprocessable Entity | 검증 실패 — 응답 `error` 에 `failure_code`(예: `INVALID_CODE`/`EXPIRED`/`MAX_ATTEMPTS`) 와 서버 기준 `attempts`/`max_attempts` 를 함께 반환. 메시지는 `identity.errors.*` (`인증 코드가 올바르지 않습니다.` / `인증 시간이 만료되었습니다. 다시 시도해주세요.` / `시도 횟수를 초과했습니다. 다시 요청해주세요.` 등) | -**설명** challenge 를 검증(인증 완료) 합니다. `auth:sanctum` + `core.identity.verify` 권한이 필요합니다. 라우트 모델 바인딩 + PermissionMiddleware 의 scope=self 가드로 로그인 사용자는 본인 challenge 만 검증하며, 비로그인 게스트는 guest 역할 권한으로 진입합니다(Mode B 가입 흐름). `code`(text_code 흐름) 또는 `token`(link/redirect 흐름) 을 전달하고 `IdentityVerificationService::verify` 가 처리합니다. 실패 시 422 로 `failure_code` 와 서버 기준 `attempts`/`max_attempts` 를 함께 내려 클라이언트의 "남은 시도 횟수" UI 를 서버와 동기화하며, 성공 시 후속 민감 작업에 제출할 `verification_token` 을 반환합니다. 확장은 `core.identity.verify_validation_rules` 필터 훅으로 파라미터를 추가할 수 있습니다. +**설명** challenge 를 검증(인증 완료) 합니다. **로그인 2단계 인증 challenge(`purpose = login`)는 이 경로로 검증할 수 없습니다** — 여기서 검증되면 바로 뒤의 `POST /api/auth/login/two-factor` 가 「이미 처리된 요청」으로 거절해 그 challenge 로는 영영 로그인할 수 없게 됩니다. 게이트는 상태를 전혀 바꾸지 않으므로, 거부된 뒤에도 로그인 경로로 정상 완료할 수 있습니다. `auth:sanctum` + `core.identity.verify` 권한이 필요합니다. 라우트 모델 바인딩 + PermissionMiddleware 의 scope=self 가드로 로그인 사용자는 본인 challenge 만 검증하며, 비로그인 게스트는 guest 역할 권한으로 진입합니다(Mode B 가입 흐름). `code`(text_code 흐름) 또는 `token`(link/redirect 흐름) 을 전달하고 `IdentityVerificationService::verify` 가 처리합니다. 실패 시 422 로 `failure_code` 와 서버 기준 `attempts`/`max_attempts` 를 함께 내려 클라이언트의 "남은 시도 횟수" UI 를 서버와 동기화하며, 성공 시 후속 민감 작업에 제출할 `verification_token` 을 반환합니다. 확장은 `core.identity.verify_validation_rules` 필터 훅으로 파라미터를 추가할 수 있습니다. ### GET /api/identity/policies/resolve diff --git a/docs/frontend/actions-handlers-ui.md b/docs/frontend/actions-handlers-ui.md index 7ca56f08..bb0f335b 100644 --- a/docs/frontend/actions-handlers-ui.md +++ b/docs/frontend/actions-handlers-ui.md @@ -20,6 +20,8 @@ 12. [callExternal](#callexternal) 13. [실전 예시](#실전-예시) +> `login` 절에 `loginTwoFactor` · `loginTwoFactorResend` 가 함께 설명되어 있습니다. + --- ## login / logout @@ -61,6 +63,110 @@ | `admin` | 관리자 인증 | | `user` | 사용자 인증 | +### login 의 반환값 — 2단계 인증이 켜진 사이트 + +서버는 보안 환경설정에 따라 **두 가지 형태의 200** 을 돌려줍니다. `onSuccess` 는 두 형태 모두에서 +실행되므로, 후속 액션은 `response.two_factor_required` 로 분기해야 합니다. + +| 필드 | 타입 | 설명 | +|------|------|------| +| `user` | object \| null | 로그인한 사용자. 인증번호 확인이 남았으면 `null` | +| `two_factor_required` | boolean | `true` 면 아직 로그인이 끝나지 않았습니다 | +| `challenge_id` | string | 인증번호 확인에 그대로 전달할 식별자 | +| `provider_id` | string | 인증번호를 보낸 프로바이더 | +| `expires_at` | string \| null | 인증 요청 만료 시각 (ISO8601) | + +분기를 두지 않으면 인증이 끝나기 전에 홈으로 이동하거나, 빈 사용자 정보가 상태에 실립니다. + +```json +{ + "handler": "login", + "target": "user", + "params": { "body": { "email": "{{form.email}}", "password": "{{form.password}}" } }, + "onSuccess": [ + { + "handler": "setState", + "if": "{{response.two_factor_required}}", + "params": { + "target": "global", + "twoFactor": { + "required": true, + "challenge_id": "{{response.challenge_id}}", + "expires_at": "{{response.expires_at}}", + "code": "" + } + } + }, + { + "handler": "navigate", + "if": "{{!response.two_factor_required}}", + "params": { "path": "/" } + } + ] +} +``` + +같은 시퀀스·`onSuccess` 안에서는 방금 저장한 상태(`_global.twoFactor.*`)를 다시 읽지 않습니다 — +그 자리의 상태는 아직 갱신 전이므로 `{{response.*}}` 만 사용합니다. + +### loginTwoFactor + +인증번호를 확인해 로그인을 완료합니다. 성공 시 토큰이 발급되고 `{ user }` 를 돌려줍니다. + +```json +{ + "handler": "loginTwoFactor", + "target": "user", + "params": { + "body": { + "challenge_id": "{{_global.twoFactor?.challenge_id}}", + "code": "{{_global.twoFactor?.code}}" + } + }, + "onSuccess": [ + { "handler": "setState", "params": { "target": "global", "currentUser": "{{response.user}}", "twoFactor": null } }, + { "handler": "navigate", "params": { "path": "/" } } + ], + "onError": [ + { "handler": "setState", "params": { "target": "global", "twoFactor.error": "{{error.message}}" } } + ] +} +``` + +`params.body` 의 `challenge_id` 와 `code` 는 필수입니다. `target` 은 `login` 과 같은 값을 씁니다 +(`user` / `admin`) — 관리자 대상은 관리자 전용 엔드포인트를 호출하고, 관리자가 아니면 `403` 이 됩니다. + +### loginTwoFactorResend + +인증번호를 다시 보냅니다. 서버가 **기존 인증 요청을 취소하고 새로 발행**하므로, 반환된 +`challenge_id` 로 반드시 교체하고 입력란을 비워야 합니다 — 앞서 받은 번호는 더 이상 통하지 않습니다. + +```json +{ + "handler": "loginTwoFactorResend", + "target": "user", + "params": { "body": { "challenge_id": "{{_global.twoFactor?.challenge_id}}" } }, + "onSuccess": [ + { + "handler": "setState", + "params": { + "target": "global", + "twoFactor": { + "required": true, + "challenge_id": "{{response.challenge_id}}", + "expires_at": "{{response.expires_at}}", + "code": "", + "error": null, + "resent": true + } + } + } + ] +} +``` + +반환값은 `{ two_factor_required, challenge_id, provider_id, expires_at }` 입니다. + ### logout 로그아웃하고 토큰을 삭제합니다. diff --git a/docs/frontend/actions-handlers.md b/docs/frontend/actions-handlers.md index fb178a25..e7210490 100644 --- a/docs/frontend/actions-handlers.md +++ b/docs/frontend/actions-handlers.md @@ -56,6 +56,9 @@ ### UI 인터랙션 핸들러 → [상세 문서](actions-handlers-ui.md) 14. [login / logout](actions-handlers-ui.md#login--logout) - 인증 + - [login 의 반환값 — 2단계 인증이 켜진 사이트](actions-handlers-ui.md#login-의-반환값--2단계-인증이-켜진-사이트) + - [loginTwoFactor](actions-handlers-ui.md#logintwofactor) - 인증번호 확인 + - [loginTwoFactorResend](actions-handlers-ui.md#logintwofactorresend) - 인증번호 다시 받기 15. [openModal / closeModal](actions-handlers-ui.md#openmodal--closemodal) - 모달 16. [showAlert / toast](actions-handlers-ui.md#showalert--toast) - 알림 17. [confirm (액션 속성)](actions-handlers-ui.md#confirm-액션-속성) - 실행 전 확인 대화상자 diff --git a/docs/frontend/auth-system.md b/docs/frontend/auth-system.md index 4cea9ad1..f4d6fa09 100644 --- a/docs/frontend/auth-system.md +++ b/docs/frontend/auth-system.md @@ -98,14 +98,15 @@ private getAuthType(route: Route, pathname: string): AuthType { ## API 엔드포인트 -| 구분 | 로그인 | 사용자 정보 | 로그아웃 | 토큰 갱신 | -|------|--------|------------|---------|----------| -| **관리자** | `/auth/login` | `/admin/auth/user` | `/admin/auth/logout` | `/admin/auth/refresh` | -| **일반사용자** | `/auth/login` | `/user/auth/user` | `/user/auth/logout` | `/user/auth/refresh` | +| 구분 | 로그인 | 인증번호 확인 | 인증번호 재발송 | 사용자 정보 | 로그아웃 | 토큰 갱신 | +|------|--------|--------------|----------------|------------|---------|----------| +| **관리자** | `/auth/admin/login` | `/auth/admin/login/two-factor` | `/auth/admin/login/two-factor/resend` | `/admin/auth/user` | `/admin/auth/logout` | `/admin/auth/refresh` | +| **일반사용자** | `/auth/login` | `/auth/login/two-factor` | `/auth/login/two-factor/resend` | `/user/auth/user` | `/user/auth/logout` | `/user/auth/refresh` | **공통**: -- 로그인 엔드포인트는 관리자/일반사용자 동일 (`/auth/login`) +- 로그인 엔드포인트는 관리자/일반사용자가 다릅니다 (`AuthConfig.loginEndpoint`) +- `updateConfig({ loginEndpoint })` 로 템플릿이 재정의한 값이 그대로 사용됩니다 - 인증 후 작업은 각각 분리된 엔드포인트 사용 - API 인증은 Bearer 토큰 전용 (세션 기반 인증 미사용) - 401 응답 시 서버가 세션 쿠키 만료 헤더를 자동 전송 (잔존 쿠키 정리) @@ -161,11 +162,12 @@ user.language 확인 UI 즉시 업데이트 ``` -**구현 위치**: `AuthManager.login()` +**구현 위치**: `AuthManager.establishSession()` — 일반 로그인과 2단계 인증 완료가 같은 후처리를 +공유합니다. 갈라지면 한쪽 경로에서만 로케일 전환이나 이벤트 발행이 빠집니다. ```typescript // 로케일 변경 감지 및 처리 -const userLanguage = response.data.user.language; +const userLanguage = user.language; const currentLocale = localStorage.getItem('g7_locale'); const localeChanged = userLanguage && userLanguage !== currentLocale; @@ -187,6 +189,51 @@ if (localeChanged && window.__templateApp) { --- +## 2단계 인증 로그인 (engine-v1.65.0+) + +보안 환경설정의 「2단계 인증」이 켜져 있으면 서버는 비밀번호가 맞아도 토큰을 발급하지 않고 +인증 요청(challenge)만 돌려줍니다. 즉, **로그인 응답은 두 가지 형태의 200** 입니다. + +```typescript +export type LoginResult = + | { status: 'authenticated'; user: AuthUser } + | { status: 'two_factor_required'; challenge: TwoFactorChallenge }; +``` + +`AuthManager.login()` 은 이 판별 유니온을 돌려줍니다. 한 형태만 가정하면 challenge 응답에서 +`data.user.*` 접근이 예외가 되고, `data.token`(undefined)을 저장하면 `"undefined"` 문자열이 남아 +이후 모든 요청이 401 로 튕깁니다. + +| 메서드 | 하는 일 | +|--------|---------| +| `login(type, credentials, options?)` | 비밀번호 확인. `LoginResult` 반환 | +| `completeTwoFactor(type, { challengeId, code }, options?)` | 인증번호 확인 → 토큰 발급 → `AuthUser` 반환 | +| `resendTwoFactor(type, { challengeId }, options?)` | 인증번호 재발송 → **새** `TwoFactorChallenge` 반환 | + +레이아웃에서는 액션 핸들러 `login` / `loginTwoFactor` / `loginTwoFactorResend` 로 사용합니다 +(→ [actions-handlers-ui.md](actions-handlers-ui.md)). + +### 레이아웃 작성 규칙 + +- 1단계 블록과 2단계 블록의 `if` 는 **상보적**이어야 합니다. 두 블록이 동시에 보이면 인증번호 + 단계에서 이메일·비밀번호가 함께 노출됩니다. +- 제출 시퀀스의 `login` 과 `loginTwoFactor` 도 상호배타 `if` 를 갖습니다. `if` 가 빠지면 인증번호 + 단계에서 Enter 를 누를 때 새 challenge 가 발급되어 흐름이 깨집니다. `if` 는 시퀀스 시작 시점 + 스냅샷으로 평가되므로 한 번의 제출에 정확히 하나만 실행됩니다. +- **같은 시퀀스·`onSuccess` 안에서 방금 저장한 상태를 다시 읽지 않습니다.** 그 자리의 상태는 아직 + 갱신 전이므로 `{{response.*}}` 만 사용합니다. +- 인증번호 입력은 자동바인딩이 아니라 `value` + `onChange` 로 상태가 값을 소유해야 합니다 — + 재발송 시 입력값을 비워야 하기 때문입니다. +- 인증 단계 상태는 화면을 떠나도 남으므로, 로그인 화면 진입 시 `init_actions` 에서 초기화합니다. + +### 재발송의 계약 + +서버는 기존 challenge 를 **취소하고 새로 발행**합니다. 유효한 코드를 여러 개 동시에 살려 두면 +대입 시도의 표적이 넓어지기 때문입니다. 따라서 클라이언트는 응답의 `challenge_id` 로 반드시 +교체하고 입력란을 비워야 합니다. + +--- + ## 사용 예시 ### routes.json 설정 diff --git a/docs/frontend/identity-verification-ui.md b/docs/frontend/identity-verification-ui.md index e5beb01b..5f2c0709 100644 --- a/docs/frontend/identity-verification-ui.md +++ b/docs/frontend/identity-verification-ui.md @@ -316,6 +316,17 @@ IDV 모달 파셜 (`_identity_challenge_modal.json`) 및 동일 패턴을 따르 - code Input 의 `actions[]` 에 `event:"onChange"` + `handler:"setState"` + `target:"global"` 항목이 존재할 것 - 재전송 setState (resendCooldown=30) 의 params 에 `identityChallenge.code: ""` 가 포함될 것 +로그인 2단계 인증 화면도 같은 규칙을 따르며, 회귀 테스트는 +`templates/_bundled/{template}/__tests__/layouts/{admin-,}login-two-factor-step.test.tsx` 가 담당합니다. + +### 5. 로그인 challenge 는 이 화면으로 처리하지 않는다 + +`purpose = login` challenge 는 로그인 전용 엔드포인트(`POST /api/auth/login/two-factor`, +`.../resend`)만 사용합니다. 공개 본인인증 엔드포인트(`POST /api/identity/challenges/{id}/verify`, +`.../cancel`)는 이 목적을 `403 PURPOSE_NOT_ALLOWED` 로 거부합니다 — 여기서 검증·취소되면 그 +challenge 로는 더 이상 로그인을 마칠 수 없게 되고(자기 DoS), 이 화면은 로그인 흐름을 모르므로 +되돌릴 방법도 없기 때문입니다. + ## 관련 문서 - [identity-guard-interceptor.md](identity-guard-interceptor.md) — 코어 인터셉터 API 레퍼런스 diff --git a/docs/testing/e2e-testing.md b/docs/testing/e2e-testing.md index bf1b404a..d8a417a3 100644 --- a/docs/testing/e2e-testing.md +++ b/docs/testing/e2e-testing.md @@ -168,6 +168,7 @@ Firefox/WebKit 프로젝트를 상시 스위트에 넣지 않은 이유: |---|---|---|---| | 코어 권한/역할/유저/Sanctum 토큰 | 코어 | `app/Console/Commands/PlaywrightIssueToken.php` | `php artisan playwright:issue-token --permissions=core.xxx` (권한 경계 검증은 `--no-admin-role` 추가 — §5.1) | | 편집기 저장 spec 대상 시드 화면 | 코어 | `app/Console/Commands/PlaywrightSeedLayout.php` | `php artisan playwright:seed-layout [--remove]` (globalSetup/globalTeardown 자동 호출) | +| 로그인 2단계 인증 계정·인증번호 | 코어 | `app/Console/Commands/PlaywrightSeedTwoFactor.php` | `php artisan playwright:seed-two-factor --ensure-user=… \| --plant=` (§4.2) | | 모듈 권한 (`sirsoft-ecommerce.*`) | 모듈 | 코어 커맨드의 `--permissions=` 임의 식별자 | 동일 (Permission::firstOrCreate 자동 생성) | | 모듈 도메인 데이터 (상품/주문) | 모듈 | `modules/_bundled/{id}/src/Console/Commands/PlaywrightSeed{id}.php` | `php artisan playwright:seed-{id}` | | 플러그인 도메인 데이터 (결제 키) | 플러그인 | `plugins/_bundled/{id}/src/Console/Commands/PlaywrightSeed{id}.php` | 동일 | @@ -175,6 +176,50 @@ Firefox/WebKit 프로젝트를 상시 스위트에 넣지 않은 이유: **핵심 원칙**: 코어는 모듈 도메인을 모른다. 모듈 도메인 시드를 코어에 두면 의존 역전. +### 4.2 로그인 2단계 인증 픽스처 + +2단계 인증은 **사이트 설정과 메일 발송**에 의존하므로 브라우저만으로는 재현할 수 없다. +`tests/Playwright/fixtures/two-factor.ts` 가 세 가지를 가역적으로 준비한다. + +| 준비 항목 | 방법 | 원복 | +|---|---|---| +| 보안 설정 `security.two_factor_auth` | 관리자 토큰으로 `/api/admin/settings` GET → POST (탭 전체를 되돌려 보낸다) | 읽어 둔 탭 전체 값을 그대로 되쓴다 | +| 메일 발송 | 받아서 버리는 로컬 SMTP 싱크를 띄우고 `mail.json` 의 `host`/`port`/`encryption` 을 줄 단위 치환 | 백업 파일에서 바이트 그대로 복원 | +| 인증번호 | `php artisan playwright:seed-two-factor --plant= --code=135790` | 없음 (challenge 는 일회성) | +| 테스트 계정 | `--ensure-user=` 로 생성 | `--purge-users` 로 종료 시 즉시 제거 | + +**메일을 `log` 메일러로 돌리지 않는 이유**: `log` 는 이 제품의 설정 스키마에 없다. 저장 검증이 +등록된 메일 드라이버(`smtp`·`mailgun`·`ses`)만 허용하고, 설정 파일을 직접 고쳐도 드라이버 해석 +단계에서 `smtp` 로 되돌아간다(실측 확인). 그래서 `tests/Playwright/fixtures/smtp-sink.ts` 가 +Node 기본 `net` 만으로 최소 SMTP 서버를 127.0.0.1 에 잠깐 띄우고 그쪽으로 돌린다 — +인증도 TLS 도 요구하지 않으며 받은 메일은 어디에도 남기지 않는다. + +**메일 설정만 파일을 직접 다루는 이유**: 원래 값(빈 SMTP 호스트)은 저장 검증(`smtp` 이면 host +필수)을 통과하지 못해 **API 로는 되돌릴 수 없다**. 보안 설정은 API 로, 메일 설정은 파일 +백업·복원으로 왕복한다. + +`playwright:seed-two-factor` 계약: + +| 옵션 | 하는 일 | +|---|---| +| `--ensure-user=<접미사>` | `playwright_2fa_<접미사>@example.test` 계정을 알려진 비밀번호로 생성/갱신하고 이메일을 출력. 잠금·실패 카운트도 초기화한다 | +| `--admin` | 위 계정에 admin 역할 부여 (없으면 기존 역할을 떼어 관리자 거부 경로를 재현할 수 있게 한다) | +| `--password=` | `--ensure-user` 가 설정할 비밀번호 (기본 `Passw0rd!2fa`) | +| `--plant=` | 그 challenge 에 알려진 인증번호의 해시를 심고 코드를 출력 | +| `--code=` | `--plant` 가 심을 인증번호 (기본 `135790`) | +| `--gc-hours=` | 이 시간보다 오래된 테스트 계정 정리 (기본 6, `0` 이면 정리 안 함) | +| `--purge-users` | 나이와 무관하게 테스트 계정을 전부 제거 — 실측 종료 직후 호출한다. 이 계정들은 알려진 비밀번호를 갖고 관리자용은 관리자 역할까지 가지므로, 나이 기준 정리를 기다리는 사이가 그대로 열린 문이 된다 | + +가드는 `playwright:issue-token` 과 동형이다 — CLI 한정 + `G7_PLAYWRIGHT_BYPASS=1` + `APP_DEBUG` 강제. + +인증번호는 해시로만 저장되어 되읽을 수 없다. 메일함을 실제로 여는 대신 알려진 값을 심는 이유이며, +방식은 PHPUnit `TwoFactorAuthTest::issuedCode()` 와 같다 — 검증 대상은 코드 생성이 아니라 +로그인 흐름(코드 확인 전 토큰 미발급 / 확인 후 발급)이다. + +**원복 실패를 삼키지 않는다.** 되돌리지 못한 채 끝나면 사이트가 2단계 인증이 켜진 상태로 남아 +이후 **모든 로그인이 막힌다**. 그래서 이 spec 은 `test.describe.configure({ mode: 'serial' })` +로 한 워커에서만 실행하고, `afterAll` 의 원복 실패는 그대로 던진다. + ### 4.1 저장(PUT)하는 spec 은 제품 화면을 대상으로 두지 않는다 레이아웃 편집기 spec 이 저장까지 수행하면 그 편집 결과는 **그대로 영속된다**. 대상이 제품 화면 diff --git a/lang-packs/_bundled/g7-core-ja/CHANGELOG.md b/lang-packs/_bundled/g7-core-ja/CHANGELOG.md index 9d1c4d46..bfb41ed9 100644 --- a/lang-packs/_bundled/g7-core-ja/CHANGELOG.md +++ b/lang-packs/_bundled/g7-core-ja/CHANGELOG.md @@ -4,6 +4,13 @@ 형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며, [Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다. +## [1.0.10] - 2026-09-07 + +### Added + +- 로그인 시도가 많아 잠시 차단될 때의 안내와, 본인인증 화면에서 로그인용 인증 요청을 처리할 수 없다는 안내의 일본어 번역을 추가했습니다. +- 레이아웃 편집기 [화면 동작] 탭의 「인증번호 확인」·「인증번호 다시 받기」 항목 이름의 일본어 번역을 추가했습니다. + ## [1.0.9] - 2026-09-06 ### Added diff --git a/lang-packs/_bundled/g7-core-ja/backend/ja/auth.php b/lang-packs/_bundled/g7-core-ja/backend/ja/auth.php index 5b5c0096..d00372e7 100644 --- a/lang-packs/_bundled/g7-core-ja/backend/ja/auth.php +++ b/lang-packs/_bundled/g7-core-ja/backend/ja/auth.php @@ -36,6 +36,7 @@ return [ 'account_pending_verification' => '本人認証が完了していないアカウントです。メール認証を完了してください。', 'account_locked' => 'ログイン試行回数の超過によりアカウントがロックされました。:minutes分後に再度お試しください。', 'account_locked_permanently' => 'ログイン試行回数の超過によりアカウントがロックされました。管理者にお問い合わせください。', + 'too_many_attempts' => 'リクエストが多すぎます。:seconds秒後にもう一度お試しください。', 'account_unlocked' => 'アカウントのロックを解除しました。', 'reset_token_invalid' => '無効なパスワードリセットトークンです。', 'reset_token_expired' => 'パスワードリセットトークンが有効期限切れです。再度リクエストしてください。', diff --git a/lang-packs/_bundled/g7-core-ja/backend/ja/identity.php b/lang-packs/_bundled/g7-core-ja/backend/ja/identity.php index 3d1546a3..0ab1abb1 100644 --- a/lang-packs/_bundled/g7-core-ja/backend/ja/identity.php +++ b/lang-packs/_bundled/g7-core-ja/backend/ja/identity.php @@ -30,6 +30,7 @@ return [ 'admin_policy_has_no_default' => '管理者が直接作成したポリシーには宣言デフォルト値がありません。', 'reset_field_failed' => '宣言デフォルト値の復元に失敗しました。フィールドが有効であることを確認してください。', 'cannot_delete_system_policy' => 'システムが宣言したポリシーは削除できません。管理者が直接作成したポリシーのみ削除できます。', + 'purpose_not_allowed' => 'この認証リクエストはこの画面では処理できません。', ], 'messages' => [ 'challenge_requested' => '本人認証コードを送信しました。', diff --git a/lang-packs/_bundled/g7-core-ja/frontend/partial/layout_editor.json b/lang-packs/_bundled/g7-core-ja/frontend/partial/layout_editor.json index 983cae01..98906894 100644 --- a/lang-packs/_bundled/g7-core-ja/frontend/partial/layout_editor.json +++ b/lang-packs/_bundled/g7-core-ja/frontend/partial/layout_editor.json @@ -1280,6 +1280,14 @@ "label": "ログイン処理", "param_body": "ログイン情報" }, + "login_two_factor": { + "label": "認証番号の確認", + "param_body": "認証情報" + }, + "login_two_factor_resend": { + "label": "認証番号の再送信", + "param_body": "認証リクエスト情報" + }, "logout": { "label": "ログアウト処理", "param_target": "移動先" diff --git a/lang-packs/_bundled/g7-core-ja/language-pack.json b/lang-packs/_bundled/g7-core-ja/language-pack.json index eddb5bd1..fa5cb272 100644 --- a/lang-packs/_bundled/g7-core-ja/language-pack.json +++ b/lang-packs/_bundled/g7-core-ja/language-pack.json @@ -12,7 +12,7 @@ "en": "G7 core Japanese language pack (bundled)", "ja": "G7 コア 日本語 言語パック(バンドル)" }, - "version": "1.0.9", + "version": "1.0.10", "license": "MIT", "scope": "core", "target_identifier": null, diff --git a/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/CHANGELOG.md b/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/CHANGELOG.md index e70e3066..987903dd 100644 --- a/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/CHANGELOG.md +++ b/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/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.9] - 2026-09-07 + +### Added + +- 관리자 로그인 화면의 2단계 인증(인증번호 입력·다시 받기·처음부터·유효 시각)과 계정 잠금 해제 시각 안내의 일본어 번역을 추가했습니다. + ## [1.0.8] - 2026-09-06 ### Added diff --git a/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/frontend/partial/auth.json b/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/frontend/partial/auth.json index dcb06c03..8be0ae77 100644 --- a/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/frontend/partial/auth.json +++ b/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/frontend/partial/auth.json @@ -8,6 +8,19 @@ "processing": "処理中...", "remember": "ログイン状態を保持する", "forgot": "パスワードをお忘れですか?", + "two_factor": { + "sent": "認証番号を送信しました。受け取った番号を入力してログインを完了してください。", + "resent": "認証番号を再送信しました。新しく受け取った番号を入力してください。", + "code_label": "認証番号", + "code_placeholder": "受け取った認証番号を入力してください", + "valid_until": "有効期限 {{until}} まで", + "verify": "認証番号を確認", + "verifying": "確認中...", + "resend": "認証番号を再送信", + "restart": "最初から" + }, + "locked_until": "解除予定: {{until}}", + "locked_permanent": "管理者にお問い合わせのうえロックを解除してください。", "error": { "email_required": "メールアドレスを入力してください。", "email_invalid": "正しいメールアドレスを入力してください。", diff --git a/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/language-pack.json b/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/language-pack.json index 7c0c015d..5b1242c7 100644 --- a/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/language-pack.json +++ b/lang-packs/_bundled/g7-template-sirsoft-admin_basic-ja/language-pack.json @@ -12,7 +12,7 @@ "en": "G7 template (sirsoft-admin_basic) Japanese language pack (bundled)", "ja": "G7 テンプレート (sirsoft-admin_basic) 日本語 言語パック(バンドル)" }, - "version": "1.0.8", + "version": "1.0.9", "license": "MIT", "scope": "template", "target_identifier": "sirsoft-admin_basic", diff --git a/lang-packs/_bundled/g7-template-sirsoft-basic-ja/CHANGELOG.md b/lang-packs/_bundled/g7-template-sirsoft-basic-ja/CHANGELOG.md index b8efdd12..c83ab1ce 100644 --- a/lang-packs/_bundled/g7-template-sirsoft-basic-ja/CHANGELOG.md +++ b/lang-packs/_bundled/g7-template-sirsoft-basic-ja/CHANGELOG.md @@ -4,6 +4,12 @@ 형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며, [Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다. +## [1.1.3] - 2026-09-07 + +### Added + +- 로그인 화면의 2단계 인증(인증번호 입력·다시 받기·처음부터·유효 시각)과 계정 잠금 해제 시각 안내의 일본어 번역을 추가했습니다. + ## [1.1.2] - 2026-08-24 ### Fixed diff --git a/lang-packs/_bundled/g7-template-sirsoft-basic-ja/frontend/partial/auth.json b/lang-packs/_bundled/g7-template-sirsoft-basic-ja/frontend/partial/auth.json index 26f6ab6b..c04571ef 100644 --- a/lang-packs/_bundled/g7-template-sirsoft-basic-ja/frontend/partial/auth.json +++ b/lang-packs/_bundled/g7-template-sirsoft-basic-ja/frontend/partial/auth.json @@ -141,6 +141,19 @@ "minTypes": "{{count}}種類以上の組み合わせ (大文字/小文字、数字、特殊文字)" } }, + "two_factor": { + "sent": "認証番号を送信しました。受け取った番号を入力してログインを完了してください。", + "resent": "認証番号を再送信しました。新しく受け取った番号を入力してください。", + "code_label": "認証番号", + "code_placeholder": "受け取った認証番号を入力してください", + "valid_until": "有効期限 {{until}} まで", + "verify": "認証番号を確認", + "verifying": "確認中...", + "resend": "認証番号を再送信", + "restart": "最初から" + }, + "locked_until": "解除予定: {{until}}", + "locked_permanent": "管理者にお問い合わせのうえロックを解除してください。", "session_expired_toast": "セッションが期限切れになりました。もう一度ログインしてください。", "guest_checkout": { "divider": "または", diff --git a/lang-packs/_bundled/g7-template-sirsoft-basic-ja/language-pack.json b/lang-packs/_bundled/g7-template-sirsoft-basic-ja/language-pack.json index 40396a18..73469da6 100644 --- a/lang-packs/_bundled/g7-template-sirsoft-basic-ja/language-pack.json +++ b/lang-packs/_bundled/g7-template-sirsoft-basic-ja/language-pack.json @@ -12,7 +12,7 @@ "en": "G7 template (sirsoft-basic) Japanese language pack (bundled)", "ja": "G7 テンプレート (sirsoft-basic) 日本語 言語パック(バンドル)" }, - "version": "1.1.2", + "version": "1.1.3", "license": "MIT", "scope": "template", "target_identifier": "sirsoft-basic", diff --git a/lang/en/auth.php b/lang/en/auth.php index 3e782708..214e1472 100644 --- a/lang/en/auth.php +++ b/lang/en/auth.php @@ -38,6 +38,7 @@ return [ 'account_pending_verification' => 'Identity verification is not complete. Please complete the email verification.', 'account_locked' => 'Too many failed login attempts. Your account is locked for :minutes minute(s).', 'account_locked_permanently' => 'Too many failed login attempts. Your account has been locked. Please contact an administrator.', + 'too_many_attempts' => 'Too many requests. Please try again in :seconds second(s).', 'account_unlocked' => 'The account lock has been released.', // Password reset diff --git a/lang/en/identity.php b/lang/en/identity.php index 46cbf1d3..6bf65d03 100644 --- a/lang/en/identity.php +++ b/lang/en/identity.php @@ -31,6 +31,7 @@ return [ 'admin_policy_has_no_default' => 'Admin-created policies do not have a declared default.', 'reset_field_failed' => 'Failed to reset the field to its declared default. Check if the field is valid.', 'cannot_delete_system_policy' => 'System-declared policies cannot be deleted. Only administrator-created policies can be deleted.', + 'purpose_not_allowed' => 'This verification request cannot be handled on this screen.', ], 'messages' => [ diff --git a/lang/ko/auth.php b/lang/ko/auth.php index fe18839f..d871ef60 100644 --- a/lang/ko/auth.php +++ b/lang/ko/auth.php @@ -38,6 +38,7 @@ return [ 'account_pending_verification' => '본인인증이 완료되지 않은 계정입니다. 이메일 인증을 완료해주세요.', 'account_locked' => '로그인 시도 횟수 초과로 계정이 잠겼습니다. :minutes분 후 다시 시도해주세요.', 'account_locked_permanently' => '로그인 시도 횟수 초과로 계정이 잠겼습니다. 관리자에게 문의해주세요.', + 'too_many_attempts' => '요청이 너무 잦습니다. :seconds초 후에 다시 시도해주세요.', 'account_unlocked' => '계정 잠금이 해제되었습니다.', // 비밀번호 재설정 diff --git a/lang/ko/identity.php b/lang/ko/identity.php index 1f1d8b47..24d25ec6 100644 --- a/lang/ko/identity.php +++ b/lang/ko/identity.php @@ -31,6 +31,7 @@ return [ 'admin_policy_has_no_default' => '관리자가 직접 생성한 정책에는 선언 기본값이 없습니다.', 'reset_field_failed' => '선언 기본값 복원에 실패했습니다. 필드가 유효한지 확인하세요.', 'cannot_delete_system_policy' => '시스템이 선언한 정책은 삭제할 수 없습니다. 관리자가 직접 생성한 정책만 삭제할 수 있습니다.', + 'purpose_not_allowed' => '이 인증 요청은 이 화면에서 처리할 수 없습니다.', ], 'messages' => [ diff --git a/lang/partial/en/layout_editor.json b/lang/partial/en/layout_editor.json index e85c12b6..6d1590ca 100644 --- a/lang/partial/en/layout_editor.json +++ b/lang/partial/en/layout_editor.json @@ -1301,6 +1301,14 @@ "label": "Handle login", "param_body": "Login info" }, + "login_two_factor": { + "label": "Verify code", + "param_body": "Verification info" + }, + "login_two_factor_resend": { + "label": "Resend code", + "param_body": "Challenge info" + }, "logout": { "label": "Handle logout", "param_target": "Destination" diff --git a/lang/partial/ko/layout_editor.json b/lang/partial/ko/layout_editor.json index ee8b22ec..af4b72ef 100644 --- a/lang/partial/ko/layout_editor.json +++ b/lang/partial/ko/layout_editor.json @@ -1301,6 +1301,14 @@ "label": "로그인 처리", "param_body": "로그인 정보" }, + "login_two_factor": { + "label": "인증번호 확인", + "param_body": "인증 정보" + }, + "login_two_factor_resend": { + "label": "인증번호 다시 받기", + "param_body": "인증 요청 정보" + }, "logout": { "label": "로그아웃 처리", "param_target": "이동할 곳" diff --git a/public/build/core/dev-dashboard.css b/public/build/core/dev-dashboard.css index efe1ec67..34129338 100644 --- a/public/build/core/dev-dashboard.css +++ b/public/build/core/dev-dashboard.css @@ -1 +1 @@ -@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-content:""}}}@layer theme{:root,:host{--font-sans:-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji";--font-mono:ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace;--color-red-300:oklch(80.8% .114 19.571);--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-red-700:oklch(50.5% .213 27.518);--color-red-900:oklch(39.6% .141 25.723);--color-orange-400:oklch(75% .183 55.934);--color-orange-500:oklch(70.5% .213 47.604);--color-orange-600:oklch(64.6% .222 41.116);--color-orange-700:oklch(55.3% .195 38.402);--color-amber-400:oklch(82.8% .189 84.429);--color-amber-600:oklch(66.6% .179 58.318);--color-amber-700:oklch(55.5% .163 48.998);--color-amber-800:oklch(47.3% .137 46.201);--color-yellow-400:oklch(85.2% .199 91.936);--color-lime-600:oklch(64.8% .2 131.684);--color-lime-700:oklch(53.2% .157 131.589);--color-green-400:oklch(79.2% .209 151.711);--color-emerald-300:oklch(84.5% .143 164.978);--color-emerald-400:oklch(76.5% .177 163.223);--color-emerald-500:oklch(69.6% .17 162.48);--color-emerald-600:oklch(59.6% .145 163.225);--color-emerald-700:oklch(50.8% .118 165.612);--color-emerald-900:oklch(37.8% .077 168.94);--color-teal-500:oklch(70.4% .14 182.503);--color-teal-600:oklch(60% .118 184.704);--color-teal-700:oklch(51.1% .096 186.391);--color-cyan-300:oklch(86.5% .127 207.078);--color-cyan-400:oklch(78.9% .154 211.53);--color-cyan-500:oklch(71.5% .143 215.221);--color-cyan-600:oklch(60.9% .126 221.723);--color-cyan-700:oklch(52% .105 223.128);--color-cyan-800:oklch(45% .085 224.283);--color-sky-600:oklch(58.8% .158 241.966);--color-sky-700:oklch(50% .134 242.749);--color-sky-800:oklch(44.3% .11 240.79);--color-blue-200:oklch(88.2% .059 254.128);--color-blue-300:oklch(80.9% .105 251.813);--color-blue-400:oklch(70.7% .165 254.624);--color-blue-500:oklch(62.3% .214 259.815);--color-blue-600:oklch(54.6% .245 262.881);--color-blue-700:oklch(48.8% .243 264.376);--color-blue-800:oklch(42.4% .199 265.638);--color-indigo-600:oklch(51.1% .262 276.966);--color-indigo-700:oklch(45.7% .24 277.023);--color-violet-600:oklch(54.1% .281 293.009);--color-violet-700:oklch(49.1% .27 292.581);--color-purple-200:oklch(90.2% .063 306.703);--color-purple-300:oklch(82.7% .119 306.383);--color-purple-400:oklch(71.4% .203 305.504);--color-purple-500:oklch(62.7% .265 303.9);--color-purple-600:oklch(55.8% .288 302.321);--color-purple-700:oklch(49.6% .265 301.924);--color-fuchsia-600:oklch(59.1% .293 322.896);--color-fuchsia-700:oklch(51.8% .253 323.949);--color-fuchsia-800:oklch(45.2% .211 324.591);--color-pink-500:oklch(65.6% .241 354.308);--color-slate-50:oklch(98.4% .003 247.858);--color-slate-100:oklch(96.8% .007 247.896);--color-slate-200:oklch(92.9% .013 255.508);--color-slate-300:oklch(86.9% .022 252.894);--color-slate-400:oklch(70.4% .04 256.788);--color-slate-500:oklch(55.4% .046 257.417);--color-slate-600:oklch(44.6% .043 257.281);--color-slate-700:oklch(37.2% .044 257.287);--color-slate-800:oklch(27.9% .041 260.031);--color-slate-900:oklch(20.8% .042 265.755);--color-gray-200:oklch(92.8% .006 264.531);--color-gray-300:oklch(87.2% .01 258.338);--color-gray-400:oklch(70.7% .022 261.325);--color-gray-500:oklch(55.1% .027 264.364);--color-gray-600:oklch(44.6% .03 256.802);--color-gray-700:oklch(37.3% .034 259.733);--color-gray-900:oklch(21% .034 264.665);--color-white:#fff;--spacing:.25rem;--container-6xl:72rem;--text-xs:.75rem;--text-xs--line-height:calc(1 / .75);--text-sm:.875rem;--text-sm--line-height:calc(1.25 / .875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75 / 1.125);--text-2xl:1.5rem;--text-2xl--line-height:calc(2 / 1.5);--text-3xl:1.875rem;--text-3xl--line-height: 1.2 ;--text-4xl:2.25rem;--text-4xl--line-height:calc(2.5 / 2.25);--font-weight-light:300;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-wider:.05em;--leading-relaxed:1.625;--radius-lg:.5rem;--radius-xl:.75rem;--radius-2xl:1rem;--blur-lg:16px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4, 0, .2, 1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", "Noto Sans", Arial, sans-serif, "Apple Color Emoji", "Segoe UI Emoji", "Segoe UI Symbol", "Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", "Courier New", monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring:where(:not(iframe)){outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.relative{position:relative}.inset-0{inset:0}.top-0\.5{top:calc(var(--spacing) * .5)}.left-0\.5{left:calc(var(--spacing) * .5)}.z-10{z-index:10}.mx-auto{margin-inline:auto}.mt-0\.5{margin-top:calc(var(--spacing) * .5)}.mt-1{margin-top:var(--spacing)}.mt-1\.5{margin-top:calc(var(--spacing) * 1.5)}.mt-2{margin-top:calc(var(--spacing) * 2)}.mt-3{margin-top:calc(var(--spacing) * 3)}.mr-4{margin-right:calc(var(--spacing) * 4)}.mb-2{margin-bottom:calc(var(--spacing) * 2)}.mb-3{margin-bottom:calc(var(--spacing) * 3)}.mb-4{margin-bottom:calc(var(--spacing) * 4)}.mb-6{margin-bottom:calc(var(--spacing) * 6)}.mb-10{margin-bottom:calc(var(--spacing) * 10)}.ml-0\.5{margin-left:calc(var(--spacing) * .5)}.ml-auto{margin-left:auto}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline-flex{display:inline-flex}.h-4{height:calc(var(--spacing) * 4)}.h-5{height:calc(var(--spacing) * 5)}.h-6{height:calc(var(--spacing) * 6)}.h-7{height:calc(var(--spacing) * 7)}.h-16{height:calc(var(--spacing) * 16)}.max-h-48{max-height:calc(var(--spacing) * 48)}.max-h-96{max-height:calc(var(--spacing) * 96)}.min-h-\[42px\]{min-height:42px}.min-h-screen{min-height:100vh}.w-4{width:calc(var(--spacing) * 4)}.w-5{width:calc(var(--spacing) * 5)}.w-9{width:calc(var(--spacing) * 9)}.w-11{width:calc(var(--spacing) * 11)}.w-14{width:calc(var(--spacing) * 14)}.w-16{width:calc(var(--spacing) * 16)}.w-full{width:100%}.max-w-6xl{max-width:var(--container-6xl)}.min-w-\[120px\]{min-width:120px}.flex-1{flex:1}.shrink-0{flex-shrink:0}.rotate-180{rotate:180deg}.transform{transform:var(--tw-rotate-x,) var(--tw-rotate-y,) var(--tw-rotate-z,) var(--tw-skew-x,) var(--tw-skew-y,)}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:var(--spacing)}.gap-1\.5{gap:calc(var(--spacing) * 1.5)}.gap-2{gap:calc(var(--spacing) * 2)}.gap-3{gap:calc(var(--spacing) * 3)}.gap-4{gap:calc(var(--spacing) * 4)}.gap-8{gap:calc(var(--spacing) * 8)}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(var(--spacing) * var(--tw-space-y-reverse));margin-block-end:calc(var(--spacing) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 2) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 2) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 3) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 3) * calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing) * 4) * var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing) * 4) * calc(1 - var(--tw-space-y-reverse)))}.gap-x-3{column-gap:calc(var(--spacing) * 3)}.gap-y-1{row-gap:var(--spacing)}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-xl{border-radius:var(--radius-xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-emerald-700\/50{border-color:#00795680}@supports (color:color-mix(in lab,red,red)){.border-emerald-700\/50{border-color:color-mix(in oklab,var(--color-emerald-700) 50%,transparent)}}.border-red-700\/50{border-color:#bf000f80}@supports (color:color-mix(in lab,red,red)){.border-red-700\/50{border-color:color-mix(in oklab,var(--color-red-700) 50%,transparent)}}.border-slate-500{border-color:var(--color-slate-500)}.border-slate-600{border-color:var(--color-slate-600)}.border-slate-700{border-color:var(--color-slate-700)}.border-slate-700\/20{border-color:#31415833}@supports (color:color-mix(in lab,red,red)){.border-slate-700\/20{border-color:color-mix(in oklab,var(--color-slate-700) 20%,transparent)}}.border-slate-700\/30{border-color:#3141584d}@supports (color:color-mix(in lab,red,red)){.border-slate-700\/30{border-color:color-mix(in oklab,var(--color-slate-700) 30%,transparent)}}.border-slate-700\/40{border-color:#31415866}@supports (color:color-mix(in lab,red,red)){.border-slate-700\/40{border-color:color-mix(in oklab,var(--color-slate-700) 40%,transparent)}}.border-slate-700\/50{border-color:#31415880}@supports (color:color-mix(in lab,red,red)){.border-slate-700\/50{border-color:color-mix(in oklab,var(--color-slate-700) 50%,transparent)}}.bg-amber-600{background-color:var(--color-amber-600)}.bg-amber-700{background-color:var(--color-amber-700)}.bg-blue-600{background-color:var(--color-blue-600)}.bg-cyan-600{background-color:var(--color-cyan-600)}.bg-cyan-700{background-color:var(--color-cyan-700)}.bg-emerald-600{background-color:var(--color-emerald-600)}.bg-emerald-600\/30{background-color:#0097674d}@supports (color:color-mix(in lab,red,red)){.bg-emerald-600\/30{background-color:color-mix(in oklab,var(--color-emerald-600) 30%,transparent)}}.bg-emerald-900\/30{background-color:#004e3b4d}@supports (color:color-mix(in lab,red,red)){.bg-emerald-900\/30{background-color:color-mix(in oklab,var(--color-emerald-900) 30%,transparent)}}.bg-fuchsia-600{background-color:var(--color-fuchsia-600)}.bg-fuchsia-700{background-color:var(--color-fuchsia-700)}.bg-gray-200{background-color:var(--color-gray-200)}.bg-indigo-600{background-color:var(--color-indigo-600)}.bg-lime-600{background-color:var(--color-lime-600)}.bg-orange-600{background-color:var(--color-orange-600)}.bg-purple-600{background-color:var(--color-purple-600)}.bg-purple-600\/30{background-color:#9810fa4d}@supports (color:color-mix(in lab,red,red)){.bg-purple-600\/30{background-color:color-mix(in oklab,var(--color-purple-600) 30%,transparent)}}.bg-red-600{background-color:var(--color-red-600)}.bg-red-900\/30{background-color:#82181a4d}@supports (color:color-mix(in lab,red,red)){.bg-red-900\/30{background-color:color-mix(in oklab,var(--color-red-900) 30%,transparent)}}.bg-sky-600{background-color:var(--color-sky-600)}.bg-sky-700{background-color:var(--color-sky-700)}.bg-slate-600{background-color:var(--color-slate-600)}.bg-slate-700{background-color:var(--color-slate-700)}.bg-slate-800{background-color:var(--color-slate-800)}.bg-slate-800\/30{background-color:#1d293d4d}@supports (color:color-mix(in lab,red,red)){.bg-slate-800\/30{background-color:color-mix(in oklab,var(--color-slate-800) 30%,transparent)}}.bg-slate-800\/50{background-color:#1d293d80}@supports (color:color-mix(in lab,red,red)){.bg-slate-800\/50{background-color:color-mix(in oklab,var(--color-slate-800) 50%,transparent)}}.bg-slate-800\/80{background-color:#1d293dcc}@supports (color:color-mix(in lab,red,red)){.bg-slate-800\/80{background-color:color-mix(in oklab,var(--color-slate-800) 80%,transparent)}}.bg-slate-900{background-color:var(--color-slate-900)}.bg-slate-900\/30{background-color:#0f172b4d}@supports (color:color-mix(in lab,red,red)){.bg-slate-900\/30{background-color:color-mix(in oklab,var(--color-slate-900) 30%,transparent)}}.bg-slate-900\/40{background-color:#0f172b66}@supports (color:color-mix(in lab,red,red)){.bg-slate-900\/40{background-color:color-mix(in oklab,var(--color-slate-900) 40%,transparent)}}.bg-slate-900\/50{background-color:#0f172b80}@supports (color:color-mix(in lab,red,red)){.bg-slate-900\/50{background-color:color-mix(in oklab,var(--color-slate-900) 50%,transparent)}}.bg-teal-600{background-color:var(--color-teal-600)}.bg-transparent{background-color:#0000}.bg-violet-600{background-color:var(--color-violet-600)}.bg-white{background-color:var(--color-white)}.bg-gradient-to-br{--tw-gradient-position:to bottom right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-blue-500{--tw-gradient-from:var(--color-blue-500);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-blue-500\/0{--tw-gradient-from:#0000}@supports (color:color-mix(in lab,red,red)){.from-blue-500\/0{--tw-gradient-from:color-mix(in oklab, var(--color-blue-500) 0%, transparent)}}.from-blue-500\/0{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-emerald-500\/0{--tw-gradient-from:#0000}@supports (color:color-mix(in lab,red,red)){.from-emerald-500\/0{--tw-gradient-from:color-mix(in oklab, var(--color-emerald-500) 0%, transparent)}}.from-emerald-500\/0{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-purple-500\/0{--tw-gradient-from:#0000}@supports (color:color-mix(in lab,red,red)){.from-purple-500\/0{--tw-gradient-from:color-mix(in oklab, var(--color-purple-500) 0%, transparent)}}.from-purple-500\/0{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-red-500\/0{--tw-gradient-from:#0000}@supports (color:color-mix(in lab,red,red)){.from-red-500\/0{--tw-gradient-from:color-mix(in oklab, var(--color-red-500) 0%, transparent)}}.from-red-500\/0{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.from-slate-800\/50{--tw-gradient-from:#1d293d80}@supports (color:color-mix(in lab,red,red)){.from-slate-800\/50{--tw-gradient-from:color-mix(in oklab, var(--color-slate-800) 50%, transparent)}}.from-slate-800\/50{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-cyan-400{--tw-gradient-to:var(--color-cyan-400);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-cyan-500\/0{--tw-gradient-to:#0000}@supports (color:color-mix(in lab,red,red)){.to-cyan-500\/0{--tw-gradient-to:color-mix(in oklab, var(--color-cyan-500) 0%, transparent)}}.to-cyan-500\/0{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-orange-500\/0{--tw-gradient-to:#0000}@supports (color:color-mix(in lab,red,red)){.to-orange-500\/0{--tw-gradient-to:color-mix(in oklab, var(--color-orange-500) 0%, transparent)}}.to-orange-500\/0{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-pink-500\/0{--tw-gradient-to:#0000}@supports (color:color-mix(in lab,red,red)){.to-pink-500\/0{--tw-gradient-to:color-mix(in oklab, var(--color-pink-500) 0%, transparent)}}.to-pink-500\/0{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-slate-800\/30{--tw-gradient-to:#1d293d4d}@supports (color:color-mix(in lab,red,red)){.to-slate-800\/30{--tw-gradient-to:color-mix(in oklab, var(--color-slate-800) 30%, transparent)}}.to-slate-800\/30{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.to-teal-500\/0{--tw-gradient-to:#0000}@supports (color:color-mix(in lab,red,red)){.to-teal-500\/0{--tw-gradient-to:color-mix(in oklab, var(--color-teal-500) 0%, transparent)}}.to-teal-500\/0{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.p-2{padding:calc(var(--spacing) * 2)}.p-3{padding:calc(var(--spacing) * 3)}.p-4{padding:calc(var(--spacing) * 4)}.p-5{padding:calc(var(--spacing) * 5)}.px-1\.5{padding-inline:calc(var(--spacing) * 1.5)}.px-2{padding-inline:calc(var(--spacing) * 2)}.px-3{padding-inline:calc(var(--spacing) * 3)}.px-4{padding-inline:calc(var(--spacing) * 4)}.px-6{padding-inline:calc(var(--spacing) * 6)}.py-0\.5{padding-block:calc(var(--spacing) * .5)}.py-1{padding-block:var(--spacing)}.py-1\.5{padding-block:calc(var(--spacing) * 1.5)}.py-2{padding-block:calc(var(--spacing) * 2)}.py-4{padding-block:calc(var(--spacing) * 4)}.pt-2{padding-top:calc(var(--spacing) * 2)}.pt-3{padding-top:calc(var(--spacing) * 3)}.pb-4{padding-bottom:calc(var(--spacing) * 4)}.text-center{text-align:center}.text-left{text-align:left}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading,var(--text-4xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-light{--tw-font-weight:var(--font-weight-light);font-weight:var(--font-weight-light)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-wider{--tw-tracking:var(--tracking-wider);letter-spacing:var(--tracking-wider)}.whitespace-pre-wrap{white-space:pre-wrap}.text-amber-400{color:var(--color-amber-400)}.text-blue-400{color:var(--color-blue-400)}.text-cyan-300{color:var(--color-cyan-300)}.text-cyan-400{color:var(--color-cyan-400)}.text-emerald-300{color:var(--color-emerald-300)}.text-emerald-400{color:var(--color-emerald-400)}.text-emerald-400\/60{color:#00d29499}@supports (color:color-mix(in lab,red,red)){.text-emerald-400\/60{color:color-mix(in oklab,var(--color-emerald-400) 60%,transparent)}}.text-gray-500{color:var(--color-gray-500)}.text-gray-900{color:var(--color-gray-900)}.text-green-400{color:var(--color-green-400)}.text-orange-400{color:var(--color-orange-400)}.text-purple-300{color:var(--color-purple-300)}.text-purple-400{color:var(--color-purple-400)}.text-purple-500{color:var(--color-purple-500)}.text-red-300{color:var(--color-red-300)}.text-red-400{color:var(--color-red-400)}.text-slate-50{color:var(--color-slate-50)}.text-slate-100{color:var(--color-slate-100)}.text-slate-200{color:var(--color-slate-200)}.text-slate-300{color:var(--color-slate-300)}.text-slate-400{color:var(--color-slate-400)}.text-slate-500{color:var(--color-slate-500)}.text-white{color:var(--color-white)}.text-yellow-400{color:var(--color-yellow-400)}.uppercase{text-transform:uppercase}.placeholder-slate-500::placeholder{color:var(--color-slate-500)}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a), 0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.backdrop-blur-lg{--tw-backdrop-blur:blur(var(--blur-lg));-webkit-backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,) var(--tw-backdrop-brightness,) var(--tw-backdrop-contrast,) var(--tw-backdrop-grayscale,) var(--tw-backdrop-hue-rotate,) var(--tw-backdrop-invert,) var(--tw-backdrop-opacity,) var(--tw-backdrop-saturate,) var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-200{--tw-duration:.2s;transition-duration:.2s}.duration-300{--tw-duration:.3s;transition-duration:.3s}.outline-none{--tw-outline-style:none;outline-style:none}@media(hover:hover){.group-hover\:from-blue-500\/10:is(:where(.group):hover *){--tw-gradient-from:#3080ff1a}@supports (color:color-mix(in lab,red,red)){.group-hover\:from-blue-500\/10:is(:where(.group):hover *){--tw-gradient-from:color-mix(in oklab, var(--color-blue-500) 10%, transparent)}}.group-hover\:from-blue-500\/10:is(:where(.group):hover *){--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.group-hover\:from-purple-500\/10:is(:where(.group):hover *){--tw-gradient-from:#ac4bff1a}@supports (color:color-mix(in lab,red,red)){.group-hover\:from-purple-500\/10:is(:where(.group):hover *){--tw-gradient-from:color-mix(in oklab, var(--color-purple-500) 10%, transparent)}}.group-hover\:from-purple-500\/10:is(:where(.group):hover *){--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.group-hover\:from-red-500\/5:is(:where(.group):hover *){--tw-gradient-from:#fb2c360d}@supports (color:color-mix(in lab,red,red)){.group-hover\:from-red-500\/5:is(:where(.group):hover *){--tw-gradient-from:color-mix(in oklab, var(--color-red-500) 5%, transparent)}}.group-hover\:from-red-500\/5:is(:where(.group):hover *){--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.group-hover\:to-cyan-500\/5:is(:where(.group):hover *){--tw-gradient-to:#00b7d70d}@supports (color:color-mix(in lab,red,red)){.group-hover\:to-cyan-500\/5:is(:where(.group):hover *){--tw-gradient-to:color-mix(in oklab, var(--color-cyan-500) 5%, transparent)}}.group-hover\:to-cyan-500\/5:is(:where(.group):hover *){--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.group-hover\:to-orange-500\/5:is(:where(.group):hover *){--tw-gradient-to:#fe6e000d}@supports (color:color-mix(in lab,red,red)){.group-hover\:to-orange-500\/5:is(:where(.group):hover *){--tw-gradient-to:color-mix(in oklab, var(--color-orange-500) 5%, transparent)}}.group-hover\:to-orange-500\/5:is(:where(.group):hover *){--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.group-hover\:to-pink-500\/5:is(:where(.group):hover *){--tw-gradient-to:#f6339a0d}@supports (color:color-mix(in lab,red,red)){.group-hover\:to-pink-500\/5:is(:where(.group):hover *){--tw-gradient-to:color-mix(in oklab, var(--color-pink-500) 5%, transparent)}}.group-hover\:to-pink-500\/5:is(:where(.group):hover *){--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position), var(--tw-gradient-from) var(--tw-gradient-from-position), var(--tw-gradient-to) var(--tw-gradient-to-position))}.group-hover\:text-blue-200:is(:where(.group):hover *){color:var(--color-blue-200)}.group-hover\:text-purple-200:is(:where(.group):hover *){color:var(--color-purple-200)}}.peer-checked\:translate-x-4:is(:where(.peer):checked~*){--tw-translate-x:calc(var(--spacing) * 4);translate:var(--tw-translate-x) var(--tw-translate-y)}.peer-checked\:bg-blue-600:is(:where(.peer):checked~*){background-color:var(--color-blue-600)}.peer-checked\:bg-red-600:is(:where(.peer):checked~*){background-color:var(--color-red-600)}.peer-focus\:ring-4:is(:where(.peer):focus~*){--tw-ring-shadow:var(--tw-ring-inset,) 0 0 0 calc(4px + var(--tw-ring-offset-width)) var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.peer-focus\:ring-blue-300:is(:where(.peer):focus~*){--tw-ring-color:var(--color-blue-300)}.peer-focus\:outline-none:is(:where(.peer):focus~*){--tw-outline-style:none;outline-style:none}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:top-\[2px\]:after{content:var(--tw-content);top:2px}.after\:left-\[2px\]:after{content:var(--tw-content);left:2px}.after\:h-4:after{content:var(--tw-content);height:calc(var(--spacing) * 4)}.after\:h-5:after{content:var(--tw-content);height:calc(var(--spacing) * 5)}.after\:h-6:after{content:var(--tw-content);height:calc(var(--spacing) * 6)}.after\:w-4:after{content:var(--tw-content);width:calc(var(--spacing) * 4)}.after\:w-5:after{content:var(--tw-content);width:calc(var(--spacing) * 5)}.after\:w-6:after{content:var(--tw-content);width:calc(var(--spacing) * 6)}.after\:rounded-full:after{content:var(--tw-content);border-radius:3.40282e38px}.after\:border:after{content:var(--tw-content);border-style:var(--tw-border-style);border-width:1px}.after\:border-gray-300:after{content:var(--tw-content);border-color:var(--color-gray-300)}.after\:bg-white:after{content:var(--tw-content);background-color:var(--color-white)}.after\:transition-all:after{content:var(--tw-content);transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.after\:content-\[\'\'\]:after{--tw-content:"";content:var(--tw-content)}.peer-checked\:after\:translate-x-full:is(:where(.peer):checked~*):after{content:var(--tw-content);--tw-translate-x:100%;translate:var(--tw-translate-x) var(--tw-translate-y)}.peer-checked\:after\:border-white:is(:where(.peer):checked~*):after{content:var(--tw-content);border-color:var(--color-white)}.focus-within\:border-emerald-500:focus-within{border-color:var(--color-emerald-500)}.focus-within\:border-purple-500:focus-within{border-color:var(--color-purple-500)}@media(hover:hover){.hover\:bg-amber-700:hover{background-color:var(--color-amber-700)}.hover\:bg-amber-800:hover{background-color:var(--color-amber-800)}.hover\:bg-blue-700:hover{background-color:var(--color-blue-700)}.hover\:bg-cyan-700:hover{background-color:var(--color-cyan-700)}.hover\:bg-cyan-800:hover{background-color:var(--color-cyan-800)}.hover\:bg-emerald-700:hover{background-color:var(--color-emerald-700)}.hover\:bg-emerald-900\/30:hover{background-color:#004e3b4d}@supports (color:color-mix(in lab,red,red)){.hover\:bg-emerald-900\/30:hover{background-color:color-mix(in oklab,var(--color-emerald-900) 30%,transparent)}}.hover\:bg-fuchsia-700:hover{background-color:var(--color-fuchsia-700)}.hover\:bg-fuchsia-800:hover{background-color:var(--color-fuchsia-800)}.hover\:bg-indigo-700:hover{background-color:var(--color-indigo-700)}.hover\:bg-lime-700:hover{background-color:var(--color-lime-700)}.hover\:bg-orange-700:hover{background-color:var(--color-orange-700)}.hover\:bg-purple-700:hover{background-color:var(--color-purple-700)}.hover\:bg-red-700:hover{background-color:var(--color-red-700)}.hover\:bg-sky-700:hover{background-color:var(--color-sky-700)}.hover\:bg-sky-800:hover{background-color:var(--color-sky-800)}.hover\:bg-slate-700:hover{background-color:var(--color-slate-700)}.hover\:bg-slate-700\/20:hover{background-color:#31415833}@supports (color:color-mix(in lab,red,red)){.hover\:bg-slate-700\/20:hover{background-color:color-mix(in oklab,var(--color-slate-700) 20%,transparent)}}.hover\:bg-slate-700\/50:hover{background-color:#31415880}@supports (color:color-mix(in lab,red,red)){.hover\:bg-slate-700\/50:hover{background-color:color-mix(in oklab,var(--color-slate-700) 50%,transparent)}}.hover\:bg-teal-700:hover{background-color:var(--color-teal-700)}.hover\:bg-violet-700:hover{background-color:var(--color-violet-700)}.hover\:text-red-400:hover{color:var(--color-red-400)}.hover\:text-white:hover{color:var(--color-white)}}.focus\:border-emerald-500:focus{border-color:var(--color-emerald-500)}.focus\:ring-purple-500:focus{--tw-ring-color:var(--color-purple-500)}@media(min-width:48rem){.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(min-width:64rem){.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(prefers-color-scheme:dark){.dark\:bg-gray-700{background-color:var(--color-gray-700)}.dark\:text-gray-400{color:var(--color-gray-400)}.dark\:text-white{color:var(--color-white)}.dark\:peer-checked\:bg-blue-500:is(:where(.peer):checked~*){background-color:var(--color-blue-500)}.dark\:peer-focus\:ring-blue-800:is(:where(.peer):focus~*){--tw-ring-color:var(--color-blue-800)}.dark\:after\:border-gray-600:after{content:var(--tw-content);border-color:var(--color-gray-600)}}}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-gradient-position{syntax:"*";inherits:false}@property --tw-gradient-from{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-via{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-to{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-stops{syntax:"*";inherits:false}@property --tw-gradient-via-stops{syntax:"*";inherits:false}@property --tw-gradient-from-position{syntax:"";inherits:false;initial-value:0%}@property --tw-gradient-via-position{syntax:"";inherits:false;initial-value:50%}@property --tw-gradient-to-position{syntax:"";inherits:false;initial-value:100%}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-content{syntax:"*";inherits:false;initial-value:""} +/*! tailwindcss v4.1.16 | MIT License | https://tailwindcss.com */@layer properties{@supports (((-webkit-hyphens:none)) and (not (margin-trim:inline))) or ((-moz-orient:inline) and (not (color:rgb(from red r g b)))){*,:before,:after,::backdrop{--tw-rotate-x:initial;--tw-rotate-y:initial;--tw-rotate-z:initial;--tw-skew-x:initial;--tw-skew-y:initial;--tw-space-y-reverse:0;--tw-border-style:solid;--tw-gradient-position:initial;--tw-gradient-from:#0000;--tw-gradient-via:#0000;--tw-gradient-to:#0000;--tw-gradient-stops:initial;--tw-gradient-via-stops:initial;--tw-gradient-from-position:0%;--tw-gradient-via-position:50%;--tw-gradient-to-position:100%;--tw-leading:initial;--tw-font-weight:initial;--tw-tracking:initial;--tw-shadow:0 0 #0000;--tw-shadow-color:initial;--tw-shadow-alpha:100%;--tw-inset-shadow:0 0 #0000;--tw-inset-shadow-color:initial;--tw-inset-shadow-alpha:100%;--tw-ring-color:initial;--tw-ring-shadow:0 0 #0000;--tw-inset-ring-color:initial;--tw-inset-ring-shadow:0 0 #0000;--tw-ring-inset:initial;--tw-ring-offset-width:0px;--tw-ring-offset-color:#fff;--tw-ring-offset-shadow:0 0 #0000;--tw-backdrop-blur:initial;--tw-backdrop-brightness:initial;--tw-backdrop-contrast:initial;--tw-backdrop-grayscale:initial;--tw-backdrop-hue-rotate:initial;--tw-backdrop-invert:initial;--tw-backdrop-opacity:initial;--tw-backdrop-saturate:initial;--tw-backdrop-sepia:initial;--tw-duration:initial;--tw-translate-x:0;--tw-translate-y:0;--tw-translate-z:0;--tw-content:""}}}@layer theme{:root,:host{--font-sans:ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji";--font-mono:ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace;--color-red-300:oklch(80.8% .114 19.571);--color-red-400:oklch(70.4% .191 22.216);--color-red-500:oklch(63.7% .237 25.331);--color-red-600:oklch(57.7% .245 27.325);--color-red-700:oklch(50.5% .213 27.518);--color-red-900:oklch(39.6% .141 25.723);--color-orange-400:oklch(75% .183 55.934);--color-orange-500:oklch(70.5% .213 47.604);--color-orange-600:oklch(64.6% .222 41.116);--color-orange-700:oklch(55.3% .195 38.402);--color-amber-400:oklch(82.8% .189 84.429);--color-amber-600:oklch(66.6% .179 58.318);--color-amber-700:oklch(55.5% .163 48.998);--color-amber-800:oklch(47.3% .137 46.201);--color-yellow-400:oklch(85.2% .199 91.936);--color-lime-600:oklch(64.8% .2 131.684);--color-lime-700:oklch(53.2% .157 131.589);--color-green-400:oklch(79.2% .209 151.711);--color-emerald-300:oklch(84.5% .143 164.978);--color-emerald-400:oklch(76.5% .177 163.223);--color-emerald-500:oklch(69.6% .17 162.48);--color-emerald-600:oklch(59.6% .145 163.225);--color-emerald-700:oklch(50.8% .118 165.612);--color-emerald-900:oklch(37.8% .077 168.94);--color-teal-500:oklch(70.4% .14 182.503);--color-teal-600:oklch(60% .118 184.704);--color-teal-700:oklch(51.1% .096 186.391);--color-cyan-300:oklch(86.5% .127 207.078);--color-cyan-400:oklch(78.9% .154 211.53);--color-cyan-500:oklch(71.5% .143 215.221);--color-cyan-600:oklch(60.9% .126 221.723);--color-cyan-700:oklch(52% .105 223.128);--color-cyan-800:oklch(45% .085 224.283);--color-sky-600:oklch(58.8% .158 241.966);--color-sky-700:oklch(50% .134 242.749);--color-sky-800:oklch(44.3% .11 240.79);--color-blue-200:oklch(88.2% .059 254.128);--color-blue-300:oklch(80.9% .105 251.813);--color-blue-400:oklch(70.7% .165 254.624);--color-blue-500:oklch(62.3% .214 259.815);--color-blue-600:oklch(54.6% .245 262.881);--color-blue-700:oklch(48.8% .243 264.376);--color-blue-800:oklch(42.4% .199 265.638);--color-indigo-600:oklch(51.1% .262 276.966);--color-indigo-700:oklch(45.7% .24 277.023);--color-violet-600:oklch(54.1% .281 293.009);--color-violet-700:oklch(49.1% .27 292.581);--color-purple-200:oklch(90.2% .063 306.703);--color-purple-300:oklch(82.7% .119 306.383);--color-purple-400:oklch(71.4% .203 305.504);--color-purple-500:oklch(62.7% .265 303.9);--color-purple-600:oklch(55.8% .288 302.321);--color-purple-700:oklch(49.6% .265 301.924);--color-fuchsia-600:oklch(59.1% .293 322.896);--color-fuchsia-700:oklch(51.8% .253 323.949);--color-fuchsia-800:oklch(45.2% .211 324.591);--color-pink-500:oklch(65.6% .241 354.308);--color-slate-50:oklch(98.4% .003 247.858);--color-slate-100:oklch(96.8% .007 247.896);--color-slate-200:oklch(92.9% .013 255.508);--color-slate-300:oklch(86.9% .022 252.894);--color-slate-400:oklch(70.4% .04 256.788);--color-slate-500:oklch(55.4% .046 257.417);--color-slate-600:oklch(44.6% .043 257.281);--color-slate-700:oklch(37.2% .044 257.287);--color-slate-800:oklch(27.9% .041 260.031);--color-slate-900:oklch(20.8% .042 265.755);--color-gray-200:oklch(92.8% .006 264.531);--color-gray-300:oklch(87.2% .01 258.338);--color-gray-400:oklch(70.7% .022 261.325);--color-gray-500:oklch(55.1% .027 264.364);--color-gray-600:oklch(44.6% .03 256.802);--color-gray-700:oklch(37.3% .034 259.733);--color-gray-900:oklch(21% .034 264.665);--color-white:#fff;--spacing:.25rem;--container-6xl:72rem;--text-xs:.75rem;--text-xs--line-height:calc(1/.75);--text-sm:.875rem;--text-sm--line-height:calc(1.25/.875);--text-base:1rem;--text-base--line-height: 1.5 ;--text-lg:1.125rem;--text-lg--line-height:calc(1.75/1.125);--text-2xl:1.5rem;--text-2xl--line-height:calc(2/1.5);--text-3xl:1.875rem;--text-3xl--line-height: 1.2 ;--text-4xl:2.25rem;--text-4xl--line-height:calc(2.5/2.25);--font-weight-light:300;--font-weight-normal:400;--font-weight-medium:500;--font-weight-semibold:600;--font-weight-bold:700;--tracking-wider:.05em;--leading-relaxed:1.625;--radius-lg:.5rem;--radius-xl:.75rem;--radius-2xl:1rem;--blur-lg:16px;--default-transition-duration:.15s;--default-transition-timing-function:cubic-bezier(.4,0,.2,1);--default-font-family:var(--font-sans);--default-mono-font-family:var(--font-mono)}}@layer base{*,:after,:before,::backdrop{box-sizing:border-box;border:0 solid;margin:0;padding:0}::file-selector-button{box-sizing:border-box;border:0 solid;margin:0;padding:0}html,:host{-webkit-text-size-adjust:100%;tab-size:4;line-height:1.5;font-family:var(--default-font-family,ui-sans-serif,system-ui,sans-serif,"Apple Color Emoji","Segoe UI Emoji","Segoe UI Symbol","Noto Color Emoji");font-feature-settings:var(--default-font-feature-settings,normal);font-variation-settings:var(--default-font-variation-settings,normal);-webkit-tap-highlight-color:transparent}hr{height:0;color:inherit;border-top-width:1px}abbr:where([title]){-webkit-text-decoration:underline dotted;text-decoration:underline dotted}h1,h2,h3,h4,h5,h6{font-size:inherit;font-weight:inherit}a{color:inherit;-webkit-text-decoration:inherit;text-decoration:inherit}b,strong{font-weight:bolder}code,kbd,samp,pre{font-family:var(--default-mono-font-family,ui-monospace,SFMono-Regular,Menlo,Monaco,Consolas,"Liberation Mono","Courier New",monospace);font-feature-settings:var(--default-mono-font-feature-settings,normal);font-variation-settings:var(--default-mono-font-variation-settings,normal);font-size:1em}small{font-size:80%}sub,sup{vertical-align:baseline;font-size:75%;line-height:0;position:relative}sub{bottom:-.25em}sup{top:-.5em}table{text-indent:0;border-color:inherit;border-collapse:collapse}:-moz-focusring{outline:auto}progress{vertical-align:baseline}summary{display:list-item}ol,ul,menu{list-style:none}img,svg,video,canvas,audio,iframe,embed,object{vertical-align:middle;display:block}img,video{max-width:100%;height:auto}button,input,select,optgroup,textarea{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}::file-selector-button{font:inherit;font-feature-settings:inherit;font-variation-settings:inherit;letter-spacing:inherit;color:inherit;opacity:1;background-color:#0000;border-radius:0}:where(select:is([multiple],[size])) optgroup{font-weight:bolder}:where(select:is([multiple],[size])) optgroup option{padding-inline-start:20px}::file-selector-button{margin-inline-end:4px}::placeholder{opacity:1}@supports (not ((-webkit-appearance:-apple-pay-button))) or (contain-intrinsic-size:1px){::placeholder{color:currentColor}@supports (color:color-mix(in lab,red,red)){::placeholder{color:color-mix(in oklab,currentcolor 50%,transparent)}}}textarea{resize:vertical}::-webkit-search-decoration{-webkit-appearance:none}::-webkit-date-and-time-value{min-height:1lh;text-align:inherit}::-webkit-datetime-edit{display:inline-flex}::-webkit-datetime-edit-fields-wrapper{padding:0}::-webkit-datetime-edit{padding-block:0}::-webkit-datetime-edit-year-field{padding-block:0}::-webkit-datetime-edit-month-field{padding-block:0}::-webkit-datetime-edit-day-field{padding-block:0}::-webkit-datetime-edit-hour-field{padding-block:0}::-webkit-datetime-edit-minute-field{padding-block:0}::-webkit-datetime-edit-second-field{padding-block:0}::-webkit-datetime-edit-millisecond-field{padding-block:0}::-webkit-datetime-edit-meridiem-field{padding-block:0}::-webkit-calendar-picker-indicator{line-height:1}:-moz-ui-invalid{box-shadow:none}button,input:where([type=button],[type=reset],[type=submit]){appearance:button}::file-selector-button{appearance:button}::-webkit-inner-spin-button{height:auto}::-webkit-outer-spin-button{height:auto}[hidden]:where(:not([hidden=until-found])){display:none!important}}@layer components;@layer utilities{.sr-only{clip-path:inset(50%);white-space:nowrap;border-width:0;width:1px;height:1px;margin:-1px;padding:0;position:absolute;overflow:hidden}.absolute{position:absolute}.relative{position:relative}.inset-0{inset:calc(var(--spacing)*0)}.top-0\.5{top:calc(var(--spacing)*.5)}.left-0\.5{left:calc(var(--spacing)*.5)}.z-10{z-index:10}.mx-auto{margin-inline:auto}.mt-0\.5{margin-top:calc(var(--spacing)*.5)}.mt-1{margin-top:calc(var(--spacing)*1)}.mt-1\.5{margin-top:calc(var(--spacing)*1.5)}.mt-2{margin-top:calc(var(--spacing)*2)}.mt-3{margin-top:calc(var(--spacing)*3)}.mr-4{margin-right:calc(var(--spacing)*4)}.mb-2{margin-bottom:calc(var(--spacing)*2)}.mb-3{margin-bottom:calc(var(--spacing)*3)}.mb-4{margin-bottom:calc(var(--spacing)*4)}.mb-6{margin-bottom:calc(var(--spacing)*6)}.mb-10{margin-bottom:calc(var(--spacing)*10)}.ml-0\.5{margin-left:calc(var(--spacing)*.5)}.ml-auto{margin-left:auto}.block{display:block}.flex{display:flex}.grid{display:grid}.hidden{display:none}.inline-flex{display:inline-flex}.h-4{height:calc(var(--spacing)*4)}.h-5{height:calc(var(--spacing)*5)}.h-6{height:calc(var(--spacing)*6)}.h-7{height:calc(var(--spacing)*7)}.h-16{height:calc(var(--spacing)*16)}.max-h-48{max-height:calc(var(--spacing)*48)}.max-h-96{max-height:calc(var(--spacing)*96)}.min-h-\[42px\]{min-height:42px}.min-h-screen{min-height:100vh}.w-4{width:calc(var(--spacing)*4)}.w-5{width:calc(var(--spacing)*5)}.w-9{width:calc(var(--spacing)*9)}.w-11{width:calc(var(--spacing)*11)}.w-14{width:calc(var(--spacing)*14)}.w-16{width:calc(var(--spacing)*16)}.w-full{width:100%}.max-w-6xl{max-width:var(--container-6xl)}.min-w-\[120px\]{min-width:120px}.flex-1{flex:1}.shrink-0{flex-shrink:0}.rotate-180{rotate:180deg}.transform{transform:var(--tw-rotate-x,)var(--tw-rotate-y,)var(--tw-rotate-z,)var(--tw-skew-x,)var(--tw-skew-y,)}.cursor-not-allowed{cursor:not-allowed}.cursor-pointer{cursor:pointer}.grid-cols-1{grid-template-columns:repeat(1,minmax(0,1fr))}.grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}.flex-col{flex-direction:column}.flex-wrap{flex-wrap:wrap}.items-center{align-items:center}.justify-between{justify-content:space-between}.justify-center{justify-content:center}.gap-1{gap:calc(var(--spacing)*1)}.gap-1\.5{gap:calc(var(--spacing)*1.5)}.gap-2{gap:calc(var(--spacing)*2)}.gap-3{gap:calc(var(--spacing)*3)}.gap-4{gap:calc(var(--spacing)*4)}.gap-8{gap:calc(var(--spacing)*8)}:where(.space-y-1>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*1)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*1)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-2>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*2)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*2)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-3>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*3)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*3)*calc(1 - var(--tw-space-y-reverse)))}:where(.space-y-4>:not(:last-child)){--tw-space-y-reverse:0;margin-block-start:calc(calc(var(--spacing)*4)*var(--tw-space-y-reverse));margin-block-end:calc(calc(var(--spacing)*4)*calc(1 - var(--tw-space-y-reverse)))}.gap-x-3{column-gap:calc(var(--spacing)*3)}.gap-y-1{row-gap:calc(var(--spacing)*1)}.overflow-hidden{overflow:hidden}.overflow-y-auto{overflow-y:auto}.rounded{border-radius:.25rem}.rounded-2xl{border-radius:var(--radius-2xl)}.rounded-full{border-radius:3.40282e38px}.rounded-lg{border-radius:var(--radius-lg)}.rounded-xl{border-radius:var(--radius-xl)}.border{border-style:var(--tw-border-style);border-width:1px}.border-t{border-top-style:var(--tw-border-style);border-top-width:1px}.border-emerald-700\/50{border-color:#00795680}@supports (color:color-mix(in lab,red,red)){.border-emerald-700\/50{border-color:color-mix(in oklab,var(--color-emerald-700)50%,transparent)}}.border-red-700\/50{border-color:#bf000f80}@supports (color:color-mix(in lab,red,red)){.border-red-700\/50{border-color:color-mix(in oklab,var(--color-red-700)50%,transparent)}}.border-slate-500{border-color:var(--color-slate-500)}.border-slate-600{border-color:var(--color-slate-600)}.border-slate-700{border-color:var(--color-slate-700)}.border-slate-700\/20{border-color:#31415833}@supports (color:color-mix(in lab,red,red)){.border-slate-700\/20{border-color:color-mix(in oklab,var(--color-slate-700)20%,transparent)}}.border-slate-700\/30{border-color:#3141584d}@supports (color:color-mix(in lab,red,red)){.border-slate-700\/30{border-color:color-mix(in oklab,var(--color-slate-700)30%,transparent)}}.border-slate-700\/40{border-color:#31415866}@supports (color:color-mix(in lab,red,red)){.border-slate-700\/40{border-color:color-mix(in oklab,var(--color-slate-700)40%,transparent)}}.border-slate-700\/50{border-color:#31415880}@supports (color:color-mix(in lab,red,red)){.border-slate-700\/50{border-color:color-mix(in oklab,var(--color-slate-700)50%,transparent)}}.bg-amber-600{background-color:var(--color-amber-600)}.bg-amber-700{background-color:var(--color-amber-700)}.bg-blue-600{background-color:var(--color-blue-600)}.bg-cyan-600{background-color:var(--color-cyan-600)}.bg-cyan-700{background-color:var(--color-cyan-700)}.bg-emerald-600{background-color:var(--color-emerald-600)}.bg-emerald-600\/30{background-color:#0097674d}@supports (color:color-mix(in lab,red,red)){.bg-emerald-600\/30{background-color:color-mix(in oklab,var(--color-emerald-600)30%,transparent)}}.bg-emerald-900\/30{background-color:#004e3b4d}@supports (color:color-mix(in lab,red,red)){.bg-emerald-900\/30{background-color:color-mix(in oklab,var(--color-emerald-900)30%,transparent)}}.bg-fuchsia-600{background-color:var(--color-fuchsia-600)}.bg-fuchsia-700{background-color:var(--color-fuchsia-700)}.bg-gray-200{background-color:var(--color-gray-200)}.bg-indigo-600{background-color:var(--color-indigo-600)}.bg-lime-600{background-color:var(--color-lime-600)}.bg-orange-600{background-color:var(--color-orange-600)}.bg-purple-600{background-color:var(--color-purple-600)}.bg-purple-600\/30{background-color:#9810fa4d}@supports (color:color-mix(in lab,red,red)){.bg-purple-600\/30{background-color:color-mix(in oklab,var(--color-purple-600)30%,transparent)}}.bg-red-600{background-color:var(--color-red-600)}.bg-red-900\/30{background-color:#82181a4d}@supports (color:color-mix(in lab,red,red)){.bg-red-900\/30{background-color:color-mix(in oklab,var(--color-red-900)30%,transparent)}}.bg-sky-600{background-color:var(--color-sky-600)}.bg-sky-700{background-color:var(--color-sky-700)}.bg-slate-600{background-color:var(--color-slate-600)}.bg-slate-700{background-color:var(--color-slate-700)}.bg-slate-800{background-color:var(--color-slate-800)}.bg-slate-800\/30{background-color:#1d293d4d}@supports (color:color-mix(in lab,red,red)){.bg-slate-800\/30{background-color:color-mix(in oklab,var(--color-slate-800)30%,transparent)}}.bg-slate-800\/50{background-color:#1d293d80}@supports (color:color-mix(in lab,red,red)){.bg-slate-800\/50{background-color:color-mix(in oklab,var(--color-slate-800)50%,transparent)}}.bg-slate-800\/80{background-color:#1d293dcc}@supports (color:color-mix(in lab,red,red)){.bg-slate-800\/80{background-color:color-mix(in oklab,var(--color-slate-800)80%,transparent)}}.bg-slate-900{background-color:var(--color-slate-900)}.bg-slate-900\/30{background-color:#0f172b4d}@supports (color:color-mix(in lab,red,red)){.bg-slate-900\/30{background-color:color-mix(in oklab,var(--color-slate-900)30%,transparent)}}.bg-slate-900\/40{background-color:#0f172b66}@supports (color:color-mix(in lab,red,red)){.bg-slate-900\/40{background-color:color-mix(in oklab,var(--color-slate-900)40%,transparent)}}.bg-slate-900\/50{background-color:#0f172b80}@supports (color:color-mix(in lab,red,red)){.bg-slate-900\/50{background-color:color-mix(in oklab,var(--color-slate-900)50%,transparent)}}.bg-teal-600{background-color:var(--color-teal-600)}.bg-transparent{background-color:#0000}.bg-violet-600{background-color:var(--color-violet-600)}.bg-white{background-color:var(--color-white)}.bg-gradient-to-br{--tw-gradient-position:to bottom right in oklab;background-image:linear-gradient(var(--tw-gradient-stops))}.from-blue-500{--tw-gradient-from:var(--color-blue-500);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.from-blue-500\/0{--tw-gradient-from:#0000}@supports (color:color-mix(in lab,red,red)){.from-blue-500\/0{--tw-gradient-from:color-mix(in oklab,var(--color-blue-500)0%,transparent)}}.from-blue-500\/0{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.from-emerald-500\/0{--tw-gradient-from:#0000}@supports (color:color-mix(in lab,red,red)){.from-emerald-500\/0{--tw-gradient-from:color-mix(in oklab,var(--color-emerald-500)0%,transparent)}}.from-emerald-500\/0{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.from-purple-500\/0{--tw-gradient-from:#0000}@supports (color:color-mix(in lab,red,red)){.from-purple-500\/0{--tw-gradient-from:color-mix(in oklab,var(--color-purple-500)0%,transparent)}}.from-purple-500\/0{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.from-red-500\/0{--tw-gradient-from:#0000}@supports (color:color-mix(in lab,red,red)){.from-red-500\/0{--tw-gradient-from:color-mix(in oklab,var(--color-red-500)0%,transparent)}}.from-red-500\/0{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.from-slate-800\/50{--tw-gradient-from:#1d293d80}@supports (color:color-mix(in lab,red,red)){.from-slate-800\/50{--tw-gradient-from:color-mix(in oklab,var(--color-slate-800)50%,transparent)}}.from-slate-800\/50{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.to-cyan-400{--tw-gradient-to:var(--color-cyan-400);--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.to-cyan-500\/0{--tw-gradient-to:#0000}@supports (color:color-mix(in lab,red,red)){.to-cyan-500\/0{--tw-gradient-to:color-mix(in oklab,var(--color-cyan-500)0%,transparent)}}.to-cyan-500\/0{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.to-orange-500\/0{--tw-gradient-to:#0000}@supports (color:color-mix(in lab,red,red)){.to-orange-500\/0{--tw-gradient-to:color-mix(in oklab,var(--color-orange-500)0%,transparent)}}.to-orange-500\/0{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.to-pink-500\/0{--tw-gradient-to:#0000}@supports (color:color-mix(in lab,red,red)){.to-pink-500\/0{--tw-gradient-to:color-mix(in oklab,var(--color-pink-500)0%,transparent)}}.to-pink-500\/0{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.to-slate-800\/30{--tw-gradient-to:#1d293d4d}@supports (color:color-mix(in lab,red,red)){.to-slate-800\/30{--tw-gradient-to:color-mix(in oklab,var(--color-slate-800)30%,transparent)}}.to-slate-800\/30{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.to-teal-500\/0{--tw-gradient-to:#0000}@supports (color:color-mix(in lab,red,red)){.to-teal-500\/0{--tw-gradient-to:color-mix(in oklab,var(--color-teal-500)0%,transparent)}}.to-teal-500\/0{--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.p-2{padding:calc(var(--spacing)*2)}.p-3{padding:calc(var(--spacing)*3)}.p-4{padding:calc(var(--spacing)*4)}.p-5{padding:calc(var(--spacing)*5)}.px-1\.5{padding-inline:calc(var(--spacing)*1.5)}.px-2{padding-inline:calc(var(--spacing)*2)}.px-3{padding-inline:calc(var(--spacing)*3)}.px-4{padding-inline:calc(var(--spacing)*4)}.px-6{padding-inline:calc(var(--spacing)*6)}.py-0\.5{padding-block:calc(var(--spacing)*.5)}.py-1{padding-block:calc(var(--spacing)*1)}.py-1\.5{padding-block:calc(var(--spacing)*1.5)}.py-2{padding-block:calc(var(--spacing)*2)}.py-4{padding-block:calc(var(--spacing)*4)}.pt-2{padding-top:calc(var(--spacing)*2)}.pt-3{padding-top:calc(var(--spacing)*3)}.pb-4{padding-bottom:calc(var(--spacing)*4)}.text-center{text-align:center}.text-left{text-align:left}.font-mono{font-family:var(--font-mono)}.text-2xl{font-size:var(--text-2xl);line-height:var(--tw-leading,var(--text-2xl--line-height))}.text-3xl{font-size:var(--text-3xl);line-height:var(--tw-leading,var(--text-3xl--line-height))}.text-4xl{font-size:var(--text-4xl);line-height:var(--tw-leading,var(--text-4xl--line-height))}.text-base{font-size:var(--text-base);line-height:var(--tw-leading,var(--text-base--line-height))}.text-lg{font-size:var(--text-lg);line-height:var(--tw-leading,var(--text-lg--line-height))}.text-sm{font-size:var(--text-sm);line-height:var(--tw-leading,var(--text-sm--line-height))}.text-xs{font-size:var(--text-xs);line-height:var(--tw-leading,var(--text-xs--line-height))}.text-\[10px\]{font-size:10px}.text-\[11px\]{font-size:11px}.leading-relaxed{--tw-leading:var(--leading-relaxed);line-height:var(--leading-relaxed)}.font-bold{--tw-font-weight:var(--font-weight-bold);font-weight:var(--font-weight-bold)}.font-light{--tw-font-weight:var(--font-weight-light);font-weight:var(--font-weight-light)}.font-medium{--tw-font-weight:var(--font-weight-medium);font-weight:var(--font-weight-medium)}.font-normal{--tw-font-weight:var(--font-weight-normal);font-weight:var(--font-weight-normal)}.font-semibold{--tw-font-weight:var(--font-weight-semibold);font-weight:var(--font-weight-semibold)}.tracking-wider{--tw-tracking:var(--tracking-wider);letter-spacing:var(--tracking-wider)}.whitespace-pre-wrap{white-space:pre-wrap}.text-amber-400{color:var(--color-amber-400)}.text-blue-400{color:var(--color-blue-400)}.text-cyan-300{color:var(--color-cyan-300)}.text-cyan-400{color:var(--color-cyan-400)}.text-emerald-300{color:var(--color-emerald-300)}.text-emerald-400{color:var(--color-emerald-400)}.text-emerald-400\/60{color:#00d29499}@supports (color:color-mix(in lab,red,red)){.text-emerald-400\/60{color:color-mix(in oklab,var(--color-emerald-400)60%,transparent)}}.text-gray-500{color:var(--color-gray-500)}.text-gray-900{color:var(--color-gray-900)}.text-green-400{color:var(--color-green-400)}.text-orange-400{color:var(--color-orange-400)}.text-purple-300{color:var(--color-purple-300)}.text-purple-400{color:var(--color-purple-400)}.text-purple-500{color:var(--color-purple-500)}.text-red-300{color:var(--color-red-300)}.text-red-400{color:var(--color-red-400)}.text-slate-50{color:var(--color-slate-50)}.text-slate-100{color:var(--color-slate-100)}.text-slate-200{color:var(--color-slate-200)}.text-slate-300{color:var(--color-slate-300)}.text-slate-400{color:var(--color-slate-400)}.text-slate-500{color:var(--color-slate-500)}.text-white{color:var(--color-white)}.text-yellow-400{color:var(--color-yellow-400)}.uppercase{text-transform:uppercase}.placeholder-slate-500::placeholder{color:var(--color-slate-500)}.opacity-50{opacity:.5}.opacity-60{opacity:.6}.shadow-xl{--tw-shadow:0 20px 25px -5px var(--tw-shadow-color,#0000001a),0 8px 10px -6px var(--tw-shadow-color,#0000001a);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.backdrop-blur-lg{--tw-backdrop-blur:blur(var(--blur-lg));-webkit-backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,);backdrop-filter:var(--tw-backdrop-blur,)var(--tw-backdrop-brightness,)var(--tw-backdrop-contrast,)var(--tw-backdrop-grayscale,)var(--tw-backdrop-hue-rotate,)var(--tw-backdrop-invert,)var(--tw-backdrop-opacity,)var(--tw-backdrop-saturate,)var(--tw-backdrop-sepia,)}.transition{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to,opacity,box-shadow,transform,translate,scale,rotate,filter,-webkit-backdrop-filter,backdrop-filter,display,content-visibility,overlay,pointer-events;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-all{transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-colors{transition-property:color,background-color,border-color,outline-color,text-decoration-color,fill,stroke,--tw-gradient-from,--tw-gradient-via,--tw-gradient-to;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.transition-transform{transition-property:transform,translate,scale,rotate;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.duration-200{--tw-duration:.2s;transition-duration:.2s}.duration-300{--tw-duration:.3s;transition-duration:.3s}.outline-none{--tw-outline-style:none;outline-style:none}@media(hover:hover){.group-hover\:from-blue-500\/10:is(:where(.group):hover *){--tw-gradient-from:#3080ff1a}@supports (color:color-mix(in lab,red,red)){.group-hover\:from-blue-500\/10:is(:where(.group):hover *){--tw-gradient-from:color-mix(in oklab,var(--color-blue-500)10%,transparent)}}.group-hover\:from-blue-500\/10:is(:where(.group):hover *){--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.group-hover\:from-purple-500\/10:is(:where(.group):hover *){--tw-gradient-from:#ac4bff1a}@supports (color:color-mix(in lab,red,red)){.group-hover\:from-purple-500\/10:is(:where(.group):hover *){--tw-gradient-from:color-mix(in oklab,var(--color-purple-500)10%,transparent)}}.group-hover\:from-purple-500\/10:is(:where(.group):hover *){--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.group-hover\:from-red-500\/5:is(:where(.group):hover *){--tw-gradient-from:#fb2c360d}@supports (color:color-mix(in lab,red,red)){.group-hover\:from-red-500\/5:is(:where(.group):hover *){--tw-gradient-from:color-mix(in oklab,var(--color-red-500)5%,transparent)}}.group-hover\:from-red-500\/5:is(:where(.group):hover *){--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.group-hover\:to-cyan-500\/5:is(:where(.group):hover *){--tw-gradient-to:#00b7d70d}@supports (color:color-mix(in lab,red,red)){.group-hover\:to-cyan-500\/5:is(:where(.group):hover *){--tw-gradient-to:color-mix(in oklab,var(--color-cyan-500)5%,transparent)}}.group-hover\:to-cyan-500\/5:is(:where(.group):hover *){--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.group-hover\:to-orange-500\/5:is(:where(.group):hover *){--tw-gradient-to:#fe6e000d}@supports (color:color-mix(in lab,red,red)){.group-hover\:to-orange-500\/5:is(:where(.group):hover *){--tw-gradient-to:color-mix(in oklab,var(--color-orange-500)5%,transparent)}}.group-hover\:to-orange-500\/5:is(:where(.group):hover *){--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.group-hover\:to-pink-500\/5:is(:where(.group):hover *){--tw-gradient-to:#f6339a0d}@supports (color:color-mix(in lab,red,red)){.group-hover\:to-pink-500\/5:is(:where(.group):hover *){--tw-gradient-to:color-mix(in oklab,var(--color-pink-500)5%,transparent)}}.group-hover\:to-pink-500\/5:is(:where(.group):hover *){--tw-gradient-stops:var(--tw-gradient-via-stops,var(--tw-gradient-position),var(--tw-gradient-from)var(--tw-gradient-from-position),var(--tw-gradient-to)var(--tw-gradient-to-position))}.group-hover\:text-blue-200:is(:where(.group):hover *){color:var(--color-blue-200)}.group-hover\:text-purple-200:is(:where(.group):hover *){color:var(--color-purple-200)}}.peer-checked\:translate-x-4:is(:where(.peer):checked~*){--tw-translate-x:calc(var(--spacing)*4);translate:var(--tw-translate-x)var(--tw-translate-y)}.peer-checked\:bg-blue-600:is(:where(.peer):checked~*){background-color:var(--color-blue-600)}.peer-checked\:bg-red-600:is(:where(.peer):checked~*){background-color:var(--color-red-600)}.peer-focus\:ring-4:is(:where(.peer):focus~*){--tw-ring-shadow:var(--tw-ring-inset,)0 0 0 calc(4px + var(--tw-ring-offset-width))var(--tw-ring-color,currentcolor);box-shadow:var(--tw-inset-shadow),var(--tw-inset-ring-shadow),var(--tw-ring-offset-shadow),var(--tw-ring-shadow),var(--tw-shadow)}.peer-focus\:ring-blue-300:is(:where(.peer):focus~*){--tw-ring-color:var(--color-blue-300)}.peer-focus\:outline-none:is(:where(.peer):focus~*){--tw-outline-style:none;outline-style:none}.after\:absolute:after{content:var(--tw-content);position:absolute}.after\:top-\[2px\]:after{content:var(--tw-content);top:2px}.after\:left-\[2px\]:after{content:var(--tw-content);left:2px}.after\:h-4:after{content:var(--tw-content);height:calc(var(--spacing)*4)}.after\:h-5:after{content:var(--tw-content);height:calc(var(--spacing)*5)}.after\:h-6:after{content:var(--tw-content);height:calc(var(--spacing)*6)}.after\:w-4:after{content:var(--tw-content);width:calc(var(--spacing)*4)}.after\:w-5:after{content:var(--tw-content);width:calc(var(--spacing)*5)}.after\:w-6:after{content:var(--tw-content);width:calc(var(--spacing)*6)}.after\:rounded-full:after{content:var(--tw-content);border-radius:3.40282e38px}.after\:border:after{content:var(--tw-content);border-style:var(--tw-border-style);border-width:1px}.after\:border-gray-300:after{content:var(--tw-content);border-color:var(--color-gray-300)}.after\:bg-white:after{content:var(--tw-content);background-color:var(--color-white)}.after\:transition-all:after{content:var(--tw-content);transition-property:all;transition-timing-function:var(--tw-ease,var(--default-transition-timing-function));transition-duration:var(--tw-duration,var(--default-transition-duration))}.after\:content-\[\'\'\]:after{--tw-content:"";content:var(--tw-content)}.peer-checked\:after\:translate-x-full:is(:where(.peer):checked~*):after{content:var(--tw-content);--tw-translate-x:100%;translate:var(--tw-translate-x)var(--tw-translate-y)}.peer-checked\:after\:border-white:is(:where(.peer):checked~*):after{content:var(--tw-content);border-color:var(--color-white)}.focus-within\:border-emerald-500:focus-within{border-color:var(--color-emerald-500)}.focus-within\:border-purple-500:focus-within{border-color:var(--color-purple-500)}@media(hover:hover){.hover\:bg-amber-700:hover{background-color:var(--color-amber-700)}.hover\:bg-amber-800:hover{background-color:var(--color-amber-800)}.hover\:bg-blue-700:hover{background-color:var(--color-blue-700)}.hover\:bg-cyan-700:hover{background-color:var(--color-cyan-700)}.hover\:bg-cyan-800:hover{background-color:var(--color-cyan-800)}.hover\:bg-emerald-700:hover{background-color:var(--color-emerald-700)}.hover\:bg-emerald-900\/30:hover{background-color:#004e3b4d}@supports (color:color-mix(in lab,red,red)){.hover\:bg-emerald-900\/30:hover{background-color:color-mix(in oklab,var(--color-emerald-900)30%,transparent)}}.hover\:bg-fuchsia-700:hover{background-color:var(--color-fuchsia-700)}.hover\:bg-fuchsia-800:hover{background-color:var(--color-fuchsia-800)}.hover\:bg-indigo-700:hover{background-color:var(--color-indigo-700)}.hover\:bg-lime-700:hover{background-color:var(--color-lime-700)}.hover\:bg-orange-700:hover{background-color:var(--color-orange-700)}.hover\:bg-purple-700:hover{background-color:var(--color-purple-700)}.hover\:bg-red-700:hover{background-color:var(--color-red-700)}.hover\:bg-sky-700:hover{background-color:var(--color-sky-700)}.hover\:bg-sky-800:hover{background-color:var(--color-sky-800)}.hover\:bg-slate-700:hover{background-color:var(--color-slate-700)}.hover\:bg-slate-700\/20:hover{background-color:#31415833}@supports (color:color-mix(in lab,red,red)){.hover\:bg-slate-700\/20:hover{background-color:color-mix(in oklab,var(--color-slate-700)20%,transparent)}}.hover\:bg-slate-700\/50:hover{background-color:#31415880}@supports (color:color-mix(in lab,red,red)){.hover\:bg-slate-700\/50:hover{background-color:color-mix(in oklab,var(--color-slate-700)50%,transparent)}}.hover\:bg-teal-700:hover{background-color:var(--color-teal-700)}.hover\:bg-violet-700:hover{background-color:var(--color-violet-700)}.hover\:text-red-400:hover{color:var(--color-red-400)}.hover\:text-white:hover{color:var(--color-white)}}.focus\:border-emerald-500:focus{border-color:var(--color-emerald-500)}.focus\:ring-purple-500:focus{--tw-ring-color:var(--color-purple-500)}@media(min-width:48rem){.md\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(min-width:64rem){.lg\:grid-cols-2{grid-template-columns:repeat(2,minmax(0,1fr))}}@media(prefers-color-scheme:dark){.dark\:bg-gray-700{background-color:var(--color-gray-700)}.dark\:text-gray-400{color:var(--color-gray-400)}.dark\:text-white{color:var(--color-white)}.dark\:peer-checked\:bg-blue-500:is(:where(.peer):checked~*){background-color:var(--color-blue-500)}.dark\:peer-focus\:ring-blue-800:is(:where(.peer):focus~*){--tw-ring-color:var(--color-blue-800)}.dark\:after\:border-gray-600:after{content:var(--tw-content);border-color:var(--color-gray-600)}}}@property --tw-rotate-x{syntax:"*";inherits:false}@property --tw-rotate-y{syntax:"*";inherits:false}@property --tw-rotate-z{syntax:"*";inherits:false}@property --tw-skew-x{syntax:"*";inherits:false}@property --tw-skew-y{syntax:"*";inherits:false}@property --tw-space-y-reverse{syntax:"*";inherits:false;initial-value:0}@property --tw-border-style{syntax:"*";inherits:false;initial-value:solid}@property --tw-gradient-position{syntax:"*";inherits:false}@property --tw-gradient-from{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-via{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-to{syntax:"";inherits:false;initial-value:#0000}@property --tw-gradient-stops{syntax:"*";inherits:false}@property --tw-gradient-via-stops{syntax:"*";inherits:false}@property --tw-gradient-from-position{syntax:"";inherits:false;initial-value:0%}@property --tw-gradient-via-position{syntax:"";inherits:false;initial-value:50%}@property --tw-gradient-to-position{syntax:"";inherits:false;initial-value:100%}@property --tw-leading{syntax:"*";inherits:false}@property --tw-font-weight{syntax:"*";inherits:false}@property --tw-tracking{syntax:"*";inherits:false}@property --tw-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-shadow-color{syntax:"*";inherits:false}@property --tw-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-inset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-shadow-color{syntax:"*";inherits:false}@property --tw-inset-shadow-alpha{syntax:"";inherits:false;initial-value:100%}@property --tw-ring-color{syntax:"*";inherits:false}@property --tw-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-inset-ring-color{syntax:"*";inherits:false}@property --tw-inset-ring-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-ring-inset{syntax:"*";inherits:false}@property --tw-ring-offset-width{syntax:"";inherits:false;initial-value:0}@property --tw-ring-offset-color{syntax:"*";inherits:false;initial-value:#fff}@property --tw-ring-offset-shadow{syntax:"*";inherits:false;initial-value:0 0 #0000}@property --tw-backdrop-blur{syntax:"*";inherits:false}@property --tw-backdrop-brightness{syntax:"*";inherits:false}@property --tw-backdrop-contrast{syntax:"*";inherits:false}@property --tw-backdrop-grayscale{syntax:"*";inherits:false}@property --tw-backdrop-hue-rotate{syntax:"*";inherits:false}@property --tw-backdrop-invert{syntax:"*";inherits:false}@property --tw-backdrop-opacity{syntax:"*";inherits:false}@property --tw-backdrop-saturate{syntax:"*";inherits:false}@property --tw-backdrop-sepia{syntax:"*";inherits:false}@property --tw-duration{syntax:"*";inherits:false}@property --tw-translate-x{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-y{syntax:"*";inherits:false;initial-value:0}@property --tw-translate-z{syntax:"*";inherits:false;initial-value:0}@property --tw-content{syntax:"*";inherits:false;initial-value:""} diff --git a/public/build/core/layout-editor.min.js b/public/build/core/layout-editor.min.js index 24ce0ef6..8adad1d7 100644 --- a/public/build/core/layout-editor.min.js +++ b/public/build/core/layout-editor.min.js @@ -1,13 +1,13 @@ -var OM=Object.defineProperty;var BM=(dn,i,u)=>i in dn?OM(dn,i,{enumerable:!0,configurable:!0,writable:!0,value:u}):dn[i]=u;var Ni=(dn,i,u)=>BM(dn,typeof i!="symbol"?i+"":i,u);(function(dn,i,u,Cn){"use strict";function Lt(){const e=typeof window<"u"?window.G7Core?.__runtime:void 0;if(!e)throw new Error("[layout-editor] window.G7Core.__runtime 이 없습니다. 코어 번들(template-engine.min.js)이 편집기 번들보다 먼저 로드되어야 합니다.");return e}const Mi=Lt();Mi.TranslationProvider;const tt=Mi.useTranslation;Mi.TranslationReactContext;function rt(){return typeof window>"u"?null:window.__g7Devtools??null}function Il(e,t){const n=rt();if(!n?.trackEditorState)return;const o={templateIdentifier:e.templateIdentifier,editMode:e.editMode,selectedRoutePath:e.selectedRoute?.path??null,selectedLayoutName:e.selectedRoute?.layoutName??null,routeTreeSize:e.routeTree.length,isRouteTreeCollapsed:e.isRouteTreeCollapsed,locale:e.locale,previewDevice:e.previewDevice,previewZoom:e.previewZoom,lastAction:t,timestamp:Date.now()};try{n.trackEditorState(o)}catch{}}function Zh(){const e=rt();if(e?.clearEditorStateData)try{e.clearEditorStateData()}catch{}}function Qh(e){const t=rt();if(t?.trackEditorSampleMatch)try{t.trackEditorSampleMatch(e)}catch{}}function Rh(){const e=rt();if(e?.clearEditorSampleData)try{e.clearEditorSampleData()}catch{}}function ey(e){const t=rt();if(t?.trackEditorHistoryEntry)try{t.trackEditorHistoryEntry(e)}catch{}}function ty(){const e=rt();if(e?.clearEditorHistoryData)try{e.clearEditorHistoryData()}catch{}}function Al(e){const t=rt();if(t?.trackEditorSelection)try{t.trackEditorSelection(e)}catch{}}function ny(){const e=rt();if(e?.clearEditorSelectionData)try{e.clearEditorSelectionData()}catch{}}function dr(e){const t=rt();if(t?.trackEditorPropertyPatch)try{t.trackEditorPropertyPatch(e)}catch{}}function $n(e){const t=rt();if(t?.trackEditorDnd)try{t.trackEditorDnd(e)}catch{}}function oy(){const e=rt();if(e?.clearEditorDndData)try{e.clearEditorDndData()}catch{}}function st(e){const t=rt();if(t?.trackEditorDocument)try{t.trackEditorDocument(e)}catch{}}function ry(){const e=rt();if(e?.clearEditorDocumentData)try{e.clearEditorDocumentData()}catch{}}function iy(e){const t=rt();if(t?.trackEditorSpecMerge)try{t.trackEditorSpecMerge(e)}catch{}}function sy(){const e=rt();if(e?.clearEditorSpecMergeData)try{e.clearEditorSpecMergeData()}catch{}}function Li(e){let t=5381;for(let n=0;n>>0;return t}function Et(e){const t=rt();if(t?.trackEditorI18n)try{t.trackEditorI18n(e)}catch{}}function ay(){const e=rt();if(e?.clearEditorI18nData)try{e.clearEditorI18nData()}catch{}}function Tl(e){const t=rt();if(t?.trackPageState)try{t.trackPageState(e)}catch{}}function ly(){const e=rt();if(e?.clearPageStateData)try{e.clearPageStateData()}catch{}}const Dl="g7le.routeTree.collapsed";function dy(){if(typeof window>"u")return!1;try{return window.localStorage?.getItem(Dl)==="1"}catch{return!1}}function cy(e){if(!(typeof window>"u"))try{window.localStorage?.setItem(Dl,e?"1":"0")}catch{}}function uy(e,t){return{templateIdentifier:e,routeTree:[],routesError:null,selectedRoute:null,isRouteTreeCollapsed:dy(),editMode:"route",returnRoute:null,returnEditMode:null,locale:t,previewDevice:"desktop",previewZoom:1,previewCustomWidth:1024,previewColorScheme:"light",history:{canUndo:!1,canRedo:!1},isPaletteOpen:!1,availableStates:[],activeStateId:null,layoutVersions:{},extensionVersions:{}}}function py(e,t){switch(t.type){case"SET_ROUTE_TREE":return{...e,routeTree:t.tree,routesError:null};case"SET_ROUTES_ERROR":return{...e,routesError:t.error};case"SELECT_ROUTE":return{...e,editMode:"route",selectedRoute:t.route,returnRoute:null,returnEditMode:null};case"TOGGLE_ROUTE_TREE":return{...e,isRouteTreeCollapsed:!e.isRouteTreeCollapsed};case"SET_LOCALE":return{...e,locale:t.locale};case"ENTER_BASE_EDIT":return{...e,editMode:"base",returnRoute:t.returnRoute!==void 0?t.returnRoute:e.selectedRoute,selectedRoute:{path:`__base__/${t.layoutName}`,layoutName:t.layoutName}};case"EXIT_BASE_EDIT":return{...e,editMode:"route",selectedRoute:e.returnRoute,returnRoute:null};case"ENTER_MODAL_EDIT":return{...e,editMode:"modal",returnRoute:t.returnRoute!==void 0?t.returnRoute:e.selectedRoute,selectedRoute:{path:`__modal__/${t.modalId}`,layoutName:t.hostLayout}};case"EXIT_MODAL_EDIT":return{...e,editMode:"route",selectedRoute:e.returnRoute,returnRoute:null};case"ENTER_EXTENSION_EDIT":return{...e,editMode:"extension",returnRoute:t.returnRoute!==void 0?t.returnRoute:e.selectedRoute,selectedRoute:{path:`__extension__/${t.extensionId}`,layoutName:t.extensionHost??null}};case"SET_RETURN_ROUTE":return e.editMode==="route"||e.returnRoute!==null?e:{...e,returnRoute:t.route};case"EXIT_EXTENSION_EDIT":return{...e,editMode:"route",selectedRoute:e.returnRoute,returnRoute:null};case"ENTER_ITERATION_ITEM_EDIT":return{...e,editMode:"iteration_item",returnRoute:t.returnRoute!==void 0?t.returnRoute:e.selectedRoute,returnEditMode:e.editMode,selectedRoute:{path:`__iteration__/${t.sourcePath}`,layoutName:t.hostLayout??e.selectedRoute?.layoutName??null}};case"EXIT_ITERATION_ITEM_EDIT":return{...e,editMode:e.returnEditMode??"route",selectedRoute:e.returnRoute,returnRoute:null,returnEditMode:null};case"SET_PREVIEW_DEVICE":return{...e,previewDevice:t.device};case"SET_PREVIEW_ZOOM":return{...e,previewZoom:t.zoom};case"SET_PREVIEW_CUSTOM_WIDTH":return{...e,previewCustomWidth:t.width};case"SET_PREVIEW_COLOR_SCHEME":return{...e,previewColorScheme:t.scheme};case"TOGGLE_PALETTE":return{...e,isPaletteOpen:!e.isPaletteOpen};case"SET_PALETTE_OPEN":return{...e,isPaletteOpen:t.open};case"SET_AVAILABLE_STATES":return{...e,availableStates:t.states,activeStateId:t.activeStateId};case"SET_ACTIVE_STATE":return{...e,activeStateId:t.activeStateId};case"SET_LAYOUT_VERSIONS":return{...e,layoutVersions:t.versions};case"SET_LAYOUT_VERSION":return{...e,layoutVersions:{...e.layoutVersions,[t.layoutName]:t.version}};case"SET_EXTENSION_VERSIONS":return{...e,extensionVersions:t.versions};case"SET_EXTENSION_VERSION":return{...e,extensionVersions:{...e.extensionVersions,[t.extensionId]:t.version}};default:return e}}function fy(e,t){const n=py(e,t);return((n.selectedRoute?.path??null)!==(e.selectedRoute?.path??null)||n.editMode!==e.editMode)&&(n.availableStates.length>0||n.activeStateId!==null)?{...n,availableStates:[],activeStateId:null}:n}const zl=u.createContext(null);function gy(e,t){const n=fy(e,t);return Il(n,t.type),n}function hy({templateIdentifier:e,initialLocale:t,children:n}){const[o,r]=u.useReducer(gy,void 0,()=>{const a=uy(e,t);return Il(a,void 0),a});u.useEffect(()=>{cy(o.isRouteTreeCollapsed)},[o.isRouteTreeCollapsed]);const s=u.useMemo(()=>({state:o,dispatch:r}),[o]);return u.createElement(zl.Provider,{value:s},n)}function Qe(){const e=u.useContext(zl);if(!e)throw new Error("useLayoutEditor must be used within LayoutEditorProvider");return e}const Nl=u.createContext(null);function yy({value:e,children:t}){return u.createElement(Nl.Provider,{value:e},t)}function Ft(){return u.useContext(Nl)}const Pi=u.createContext(null);let by=1;function my({children:e,t}){const[n,o]=u.useState([]),r=u.useRef([]),[s,a]=u.useState({}),l=u.useCallback(y=>{const _=y.id??`editor-modal-${by++}`,w={id:_,content:y.content,ariaLabel:y.ariaLabel??"",closeOnBackdrop:y.closeOnBackdrop??!0,closeOnEscape:y.closeOnEscape??!0,width:y.width??"auto",height:y.height??"auto",maxHeightRatio:y.maxHeightRatio??.85,draggable:y.draggable??!1,avoidRect:y.avoidRect,onClose:y.onClose};return o(k=>{const $=[...k.filter(S=>S.id!==_),w];return r.current=$,$}),_},[]),d=u.useCallback(y=>{o(_=>{const w=_.find(x=>x.id===y),k=_.filter(x=>x.id!==y);return r.current=k,w?.onClose&&queueMicrotask(()=>w.onClose?.()),k})},[]),c=u.useCallback(()=>{const y=r.current[r.current.length-1];y&&d(y.id)},[d]),p=u.useCallback(()=>{o(y=>{for(let _=y.length-1;_>=0;_--){const w=y[_];w?.onClose&&queueMicrotask(()=>w.onClose?.())}return r.current=[],[]})},[]),f=u.useCallback((y,_)=>{a(w=>{const k=r.current.find($=>$.id===y),x=_??k?.ariaLabel??"";return{...w,[y]:x}})},[]),b=u.useCallback(y=>{a(_=>{if(!(y in _))return _;const w={..._};return delete w[y],w})},[]),g=u.useCallback(y=>{b(y),d(y)},[b,d]),m=u.useCallback(()=>{a({}),p()},[p]),h=u.useMemo(()=>Object.keys(s),[s]),v=u.useMemo(()=>({open:l,close:g,closeTop:c,closeAll:m,stack:n,minimize:f,restore:b,minimizedStack:h}),[l,g,c,m,n,f,b,h]);return u.createElement(Pi.Provider,{value:v},e,u.createElement(_y,{minimized:s,onRestore:b,t,key:"__min_bar"}))}function bo(){const e=u.useContext(Pi);if(!e)throw new Error("useEditorModal must be used within EditorModalProvider");return e}function vy(){const e=u.useContext(Pi);if(!e)return null;const{stack:t,close:n,minimizedStack:o}=e,r=u.useMemo(()=>new Set(o),[o]);return u.useEffect(()=>{if(t.length===0)return;const s=a=>{if(a.key!=="Escape"&&a.key!=="Esc")return;const l=t.filter(c=>!r.has(c.id)),d=l[l.length-1];d?.closeOnEscape&&(a.preventDefault(),a.stopPropagation(),n(d.id))};return window.addEventListener("keydown",s,!0),()=>window.removeEventListener("keydown",s,!0)},[t,n,r]),t.length===0?null:i.jsx(i.Fragment,{children:t.map((s,a)=>i.jsx(wy,{entry:s,depth:a,hidden:r.has(s.id),onClose:()=>n(s.id)},s.id))})}function _y({minimized:e,onRestore:t,t:n}){const o=n??(s=>s),r=Object.keys(e);return r.length===0?null:i.jsx("div",{className:"g7le-minimized-bar","data-testid":"g7le-minimized-bar",style:{position:"fixed",left:16,bottom:16,display:"flex",gap:8,zIndex:9300},children:r.map(s=>i.jsxs("button",{type:"button","data-testid":`g7le-minimized-${s}`,onClick:()=>t(s),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 12px",background:"#1e293b",color:"#fff",border:"none",borderRadius:8,boxShadow:"0 8px 24px rgba(15, 23, 42, 0.3)",cursor:"pointer",fontSize:13},children:[i.jsx("span",{"aria-hidden":"true",children:"🗗"}),i.jsx("span",{children:e[s]||o("layout_editor.modal.minimized_default")}),i.jsx("span",{style:{opacity:.7},children:o("layout_editor.modal.restore")})]},s))})}function xy(e,t,n){if(!e||typeof window>"u")return null;const o=window.innerWidth,r=window.innerHeight,s=16,a=e.left,l=o-(e.left+e.width),d=t+s;let c;if(l>=a&&l>=d)c=e.left+e.width+s;else if(a>=d)c=Math.max(s,e.left-s-t);else return null;c=Math.min(Math.max(s,c),Math.max(s,o-t-s));let p=e.top;return p=Math.min(Math.max(s,p),Math.max(s,r-n-s)),{left:c,top:p}}const Ml="clamp(16px, 6vh, 56px)";function wy({entry:e,depth:t,hidden:n,onClose:o}){const r=9100+t*10,s=e.maxHeightRatio>0?`${e.maxHeightRatio*100}vh`:void 0,a=e.draggable?s:`calc(100vh - (${Ml}) * 2)`,[l,d]=u.useState(null),c=u.useRef(null),p=u.useRef(null);u.useEffect(()=>{if(!e.draggable)return;const v=c.current;if(!v)return;const y=v.getBoundingClientRect(),_=xy(e.avoidRect,y.width,y.height);_&&d(_)},[e.id,e.draggable]);const f=u.useCallback(v=>{if(!e.draggable)return;const y=v.target;if(!y.closest("[data-modal-drag-handle]")||y.closest("button, a, input, textarea, select"))return;const w=c.current,k=w?.getBoundingClientRect(),x=l?.left??k?.left??0,$=l?.top??k?.top??0;p.current={startX:v.clientX,startY:v.clientY,baseLeft:x,baseTop:$};const S=T=>{const E=p.current;if(!E)return;const A=window.innerWidth,N=window.innerHeight,D=w?.offsetWidth??0,B=w?.offsetHeight??0;let M=E.baseLeft+(T.clientX-E.startX),O=E.baseTop+(T.clientY-E.startY);M=Math.min(Math.max(0,M),Math.max(0,A-D)),O=Math.min(Math.max(0,O),Math.max(0,N-B)),d({left:M,top:O})},C=()=>{p.current=null,window.removeEventListener("pointermove",S),window.removeEventListener("pointerup",C)};window.addEventListener("pointermove",S),window.addEventListener("pointerup",C)},[e.draggable,l]),b=v=>{e.closeOnBackdrop&&v.target===v.currentTarget&&o()},g=e.draggable&&l!==null,m=e.draggable?{position:"fixed",inset:0,background:"transparent",pointerEvents:"none",zIndex:r,...n?{display:"none"}:{}}:{position:"fixed",inset:0,background:"rgba(15, 23, 42, 0.45)",display:n?"none":"flex",alignItems:"flex-start",justifyContent:"center",paddingTop:Ml,boxSizing:"border-box",zIndex:r},h={background:"#fff",borderRadius:10,boxShadow:"0 20px 60px rgba(15, 23, 42, 0.25)",width:e.width,height:e.height,maxHeight:a,maxWidth:"92vw",overflow:"hidden",display:"flex",flexDirection:"column",...e.draggable?{position:"absolute",pointerEvents:"auto",left:g?l.left:"50%",top:g?l.top:"50%",transform:g?void 0:"translate(-50%, -50%)"}:{}};return i.jsx("div",{className:"g7le-modal-backdrop",role:"presentation","data-testid":`g7le-modal-backdrop-${e.id}`,"data-draggable":e.draggable?"true":"false",onClick:b,style:m,children:i.jsx("div",{ref:c,className:"g7le-modal",role:"dialog","aria-modal":"true","aria-label":e.ariaLabel||void 0,"data-testid":`g7le-modal-${e.id}`,"data-positioned":g?"true":"false",onClick:v=>v.stopPropagation(),onPointerDown:e.draggable?f:void 0,style:h,children:e.content})})}function ht({baseStyle:e,hoverStyle:t,disabled:n,style:o,children:r,...s}){const[a,l]=u.useState(!1),d={outline:"none",...e,...o,...a&&!n?t:{}};return i.jsx("button",{type:"button",disabled:n,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:d,...s,children:r})}function ky({templateIdentifier:e,templateName:t,templateVersion:n,templateList:o,onSwitch:r}){const{t:s}=tt(),[a,l]=u.useState(!1),[d,c]=u.useState(!1),p=u.useRef(null);u.useEffect(()=>{if(!a)return;const v=_=>{p.current&&!p.current.contains(_.target)&&l(!1)},y=_=>{_.key==="Escape"&&l(!1)};return document.addEventListener("mousedown",v),document.addEventListener("keydown",y),()=>{document.removeEventListener("mousedown",v),document.removeEventListener("keydown",y)}},[a]);const f=o??[],b=f.some(v=>v.identifier!==e),g=!!r&&b,m=t||e,h=v=>{if(v===e){l(!1);return}l(!1),r?.(v)};return i.jsxs("div",{ref:p,className:"g7le-toolbar__template-switcher",style:{position:"relative",display:"inline-flex"},children:[i.jsxs("button",{type:"button",className:"g7le-toolbar__template","data-testid":"g7le-toolbar-template-label","data-can-switch":g?"true":"false","aria-haspopup":g?"listbox":void 0,"aria-expanded":g?a:void 0,disabled:!g,onClick:()=>g&&l(v=>!v),onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),title:g?s("layout_editor.chrome.toolbar.switch_template"):m,style:{display:"inline-flex",alignItems:"center",gap:6,padding:"4px 8px",fontSize:13,fontWeight:600,color:"#0f172a",letterSpacing:.1,borderRadius:6,borderWidth:1,borderStyle:"solid",borderColor:g&&(d||a)?"#cbd5e1":"transparent",backgroundColor:g&&(d||a)?"#f1f5f9":"transparent",cursor:g?"pointer":"default",outline:"none",transition:"background-color 120ms, border-color 120ms"},children:[i.jsx("span",{className:"g7le-toolbar__template-name","data-testid":"g7le-toolbar-template-name",children:m}),n&&i.jsxs("span",{className:"g7le-toolbar__template-version","data-testid":"g7le-toolbar-template-version",style:{fontSize:11,fontWeight:500,color:"#64748b",padding:"1px 6px",borderRadius:999,background:"#f1f5f9",border:"1px solid #e2e8f0"},children:["v",n]}),g&&i.jsx("span",{className:"g7le-toolbar__template-caret","aria-hidden":"true",style:{fontSize:9,color:"#94a3b8",marginLeft:1},children:"▼"})]}),g&&a&&i.jsx("div",{className:"g7le-toolbar__template-menu","data-testid":"g7le-toolbar-template-menu",role:"listbox",style:{position:"absolute",top:"calc(100% + 4px)",left:0,minWidth:240,maxWidth:360,maxHeight:360,overflowY:"auto",background:"#ffffff",border:"1px solid #e2e8f0",borderRadius:8,boxShadow:"0 8px 24px rgba(15, 23, 42, 0.14)",zIndex:30,padding:4},children:f.map(v=>{const y=v.identifier===e;return i.jsxs("button",{type:"button",role:"option","aria-selected":y,"aria-current":y?"true":void 0,className:"g7le-toolbar__template-menu-item","data-testid":"g7le-toolbar-template-menu-item","data-identifier":v.identifier,"data-current":y?"true":"false",onClick:()=>h(v.identifier),style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,width:"100%",padding:"8px 10px",fontSize:13,color:"#1e293b",background:y?"#eff6ff":"transparent",border:"none",borderRadius:6,cursor:y?"default":"pointer",textAlign:"left",outline:"none"},onMouseEnter:_=>{y||(_.currentTarget.style.background="#f1f5f9")},onMouseLeave:_=>{_.currentTarget.style.background=y?"#eff6ff":"transparent"},children:[i.jsxs("span",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[i.jsx("span",{"aria-hidden":"true",style:{width:12,flex:"0 0 auto",color:"#2563eb",fontSize:12,textAlign:"center"},children:y?"✓":""}),i.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:2,minWidth:0},children:[i.jsx("span",{style:{fontWeight:600,color:y?"#1d4ed8":"#1e293b",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v.name||v.identifier}),i.jsx("span",{style:{fontSize:11,color:"#94a3b8",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v.identifier})]})]}),i.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,flex:"0 0 auto"},children:[i.jsx("span",{style:{fontSize:10,fontWeight:600,color:v.type==="admin"?"#7c3aed":"#0891b2",textTransform:"uppercase",letterSpacing:.4},children:v.type}),v.version&&i.jsxs("span",{style:{fontSize:11,color:"#64748b"},children:["v",v.version]})]})]},v.identifier)})})]})}function Sy(e={}){const{onSave:t,isDirty:n=!1,onExit:o,onEditCode:r,onManageImages:s,onManageTranslations:a,onPageSettings:l,onReset:d,onShowShortcuts:c,onPreview:p,onShowVersions:f,templateName:b,templateVersion:g,templateList:m,onSwitchTemplate:h,onToggleCustomAssets:v,customAssetsDisabled:y=!1,onManageCustomAssets:_}=e,[w,k]=u.useState(!1),[x,$]=u.useState(!1),{t:S}=tt(),{state:C,dispatch:T}=Qe(),[E,A]=u.useState(null);u.useEffect(()=>{const K=()=>{const Z=window.__g7LayoutEditorHistory;A(Z?{undo:Z.undo,redo:Z.redo,canUndo:!!Z.canUndo,canRedo:!!Z.canRedo}:null)};K();const X=window.setInterval(K,250);return()=>window.clearInterval(X)},[]);const N=()=>{T({type:"TOGGLE_ROUTE_TREE"})},D=()=>C.editMode==="base"?S("layout_editor.chrome.toolbar.mode_badge.base"):C.editMode==="modal"?S("layout_editor.chrome.toolbar.mode_badge.modal"):C.editMode==="extension"?S("layout_editor.chrome.toolbar.mode_badge.extension"):C.editMode==="iteration_item"?S("layout_editor.chrome.toolbar.mode_badge.iteration_item"):null,B=()=>{C.editMode==="base"?T({type:"EXIT_BASE_EDIT"}):C.editMode==="modal"?T({type:"EXIT_MODAL_EDIT"}):C.editMode==="extension"?T({type:"EXIT_EXTENSION_EDIT"}):C.editMode==="iteration_item"&&T({type:"EXIT_ITERATION_ITEM_EDIT"})},M=D(),O=C.editMode!=="route",z={display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",fontSize:13,fontWeight:500,borderRadius:6,borderWidth:1,borderStyle:"solid",borderColor:"transparent",backgroundColor:"transparent",color:"#475569",cursor:"pointer",transition:"background-color 120ms, color 120ms, border-color 120ms"},H={...z,backgroundColor:"#2563eb",color:"#ffffff",borderColor:"#2563eb",fontWeight:600},P={backgroundColor:"#fef3c7",borderColor:"#f59e0b",color:"#92400e",fontWeight:600},I={...z,borderColor:"#e2e8f0",backgroundColor:"#ffffff",color:"#0f172a"},L={backgroundColor:"#f1f5f9",color:"#0f172a",borderColor:"#cbd5e1"},F={backgroundColor:"#1d4ed8",borderColor:"#1d4ed8"},Y={backgroundColor:"#f8fafc",borderColor:"#cbd5e1"};return i.jsxs("div",{className:"g7le-toolbar","data-testid":"g7le-toolbar",role:"toolbar",style:{display:"flex",alignItems:"center",gap:6,padding:"8px 12px",borderBottom:"1px solid #e2e8f0",background:"#ffffff",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.04)"},children:[i.jsx("style",{children:"@keyframes g7le-spin { to { transform: rotate(360deg); } }.g7le-toolbar > * { flex-shrink: 0; white-space: nowrap; }"}),i.jsx("button",{type:"button",className:"g7le-toolbar__route-tree-toggle","data-testid":"g7le-toolbar-toggle-route-tree","aria-label":S("layout_editor.chrome.toolbar.toggle_route_tree"),title:S("layout_editor.chrome.toolbar.toggle_route_tree"),onClick:N,style:{...z,outline:"none",padding:"6px 10px",fontSize:16,lineHeight:1,color:"#64748b"},children:"☰"}),i.jsx(ky,{templateIdentifier:C.templateIdentifier,templateName:b,templateVersion:g,templateList:m,onSwitch:h}),M&&i.jsx("span",{className:"g7le-toolbar__mode-badge","data-testid":"g7le-toolbar-mode-badge","data-mode":C.editMode,style:{padding:"2px 8px",borderRadius:999,background:"#fef3c7",color:"#92400e",fontSize:11,fontWeight:600,border:"1px solid #fde68a"},children:M}),i.jsx("div",{style:{flex:1}}),i.jsxs(i.Fragment,{children:[i.jsx(ht,{"data-testid":"g7le-toolbar-undo","aria-label":S("layout_editor.chrome.toolbar.undo"),title:S("layout_editor.chrome.toolbar.undo"),disabled:!E?.canUndo,onClick:()=>E?.undo?.(),baseStyle:z,hoverStyle:L,style:{opacity:E?.canUndo?1:.4},children:"↶"}),i.jsx(ht,{"data-testid":"g7le-toolbar-redo","aria-label":S("layout_editor.chrome.toolbar.redo"),title:S("layout_editor.chrome.toolbar.redo"),disabled:!E?.canRedo,onClick:()=>E?.redo?.(),baseStyle:z,hoverStyle:L,style:{opacity:E?.canRedo?1:.4},children:"↷"}),i.jsxs(ht,{"data-testid":"g7le-toolbar-add-element","data-open":C.isPaletteOpen?"true":"false",disabled:!C.selectedRoute,onClick:()=>T({type:"TOGGLE_PALETTE"}),"aria-pressed":C.isPaletteOpen,baseStyle:z,hoverStyle:L,style:C.isPaletteOpen?{backgroundColor:"#eff6ff",color:"#1d4ed8",borderColor:"#93c5fd"}:void 0,children:["+ ",S("layout_editor.chrome.toolbar.add_element")]}),i.jsx(ht,{"data-testid":"g7le-toolbar-preview","data-previewing":x?"true":"false",disabled:!p||!C.selectedRoute?.layoutName||x,onClick:()=>{const K=p?.();K&&typeof K.then=="function"&&($(!0),K.finally(()=>$(!1)))},baseStyle:z,hoverStyle:L,style:{opacity:x?.7:1},children:x?i.jsxs(i.Fragment,{children:[i.jsx("span",{"data-testid":"g7le-toolbar-preview-spinner","aria-hidden":"true",style:{display:"inline-block",width:12,height:12,border:"2px solid rgba(71,85,105,0.35)",borderTopColor:"#475569",borderRadius:"50%",animation:"g7le-spin 600ms linear infinite"}}),S("layout_editor.chrome.toolbar.previewing")]}):i.jsxs(i.Fragment,{children:["👁 ",S("layout_editor.chrome.toolbar.preview")]})}),i.jsxs(ht,{"data-testid":"g7le-toolbar-versions",disabled:!f||!(C.selectedRoute?.layoutName||C.selectedRoute?.path?.startsWith("__extension__/")),onClick:()=>f?.(),"aria-label":S("layout_editor.chrome.toolbar.version_history"),title:S("layout_editor.chrome.toolbar.version_history"),baseStyle:z,hoverStyle:L,children:["🕘 ",S("layout_editor.chrome.toolbar.version_history")]}),i.jsxs(ht,{"data-testid":"g7le-toolbar-edit-code",disabled:!r,onClick:()=>r?.(),baseStyle:z,hoverStyle:L,children:["⟨/⟩ ",S("layout_editor.chrome.toolbar.edit_code")]}),i.jsxs(ht,{"data-testid":"g7le-toolbar-images",disabled:!s||!C.selectedRoute,onClick:()=>s?.(),baseStyle:z,hoverStyle:L,children:["🖼 ",S("layout_editor.chrome.toolbar.images")]}),i.jsxs(ht,{"data-testid":"g7le-toolbar-translations",disabled:!a||!C.selectedRoute,onClick:()=>a?.(),baseStyle:z,hoverStyle:L,children:["🌐 ",S("layout_editor.chrome.toolbar.translations")]}),i.jsxs(ht,{"data-testid":"g7le-toolbar-custom-assets",disabled:!_,onClick:()=>_?.(),title:S("layout_editor.chrome.toolbar.custom_assets_hint"),baseStyle:z,hoverStyle:L,children:["🎨 ",S("layout_editor.chrome.toolbar.custom_assets")]}),i.jsxs(ht,{"data-testid":"g7le-toolbar-toggle-custom-assets","data-custom-disabled":y?"true":"false",disabled:!v,onClick:()=>v?.(),"aria-pressed":y,title:S(y?"layout_editor.chrome.toolbar.custom_assets_on_hint":"layout_editor.chrome.toolbar.custom_assets_off_hint"),baseStyle:z,hoverStyle:L,style:y?{...z,...P}:void 0,children:[y?"👁":"🚫"," ",S(y?"layout_editor.chrome.toolbar.custom_assets_on":"layout_editor.chrome.toolbar.custom_assets_off")]}),i.jsxs(ht,{"data-testid":"g7le-toolbar-page-settings",disabled:!l||!C.selectedRoute||C.editMode==="extension"||C.editMode==="iteration_item",onClick:()=>l?.(),baseStyle:z,hoverStyle:L,children:["⚙ ",S("layout_editor.chrome.toolbar.page_settings")]}),i.jsxs(ht,{"data-testid":"g7le-toolbar-reset",disabled:!d||!n,onClick:()=>d?.(),"aria-label":S("layout_editor.chrome.toolbar.reset"),title:S("layout_editor.chrome.toolbar.reset"),baseStyle:z,hoverStyle:L,style:{opacity:n?1:.4},children:["↺ ",S("layout_editor.chrome.toolbar.reset")]}),i.jsx(ht,{"data-testid":"g7le-toolbar-save","data-dirty":n?"true":"false","data-saving":w?"true":"false",disabled:!t||w,onClick:()=>{const K=t?.();K&&typeof K.then=="function"&&(k(!0),K.finally(()=>k(!1)))},baseStyle:H,hoverStyle:F,style:{opacity:w?.7:n?1:.7},children:w?i.jsxs(i.Fragment,{children:[i.jsx("span",{"data-testid":"g7le-toolbar-save-spinner","aria-hidden":"true",className:"g7le-toolbar__spinner",style:{display:"inline-block",width:12,height:12,border:"2px solid rgba(255,255,255,0.4)",borderTopColor:"#ffffff",borderRadius:"50%",animation:"g7le-spin 600ms linear infinite"}}),S("layout_editor.chrome.toolbar.saving")]}):i.jsxs(i.Fragment,{children:["💾 ",S("layout_editor.chrome.toolbar.save")]})}),i.jsx(ht,{"data-testid":"g7le-toolbar-shortcuts",disabled:!c,onClick:()=>c?.(),"aria-label":S("layout_editor.shortcuts.title"),title:S("layout_editor.shortcuts.title"),baseStyle:z,hoverStyle:L,children:"⌨"}),i.jsxs(ht,{"data-testid":"g7le-toolbar-exit",disabled:!o,onClick:()=>o?.(),baseStyle:I,hoverStyle:Y,children:["✕ ",S("layout_editor.chrome.toolbar.exit")]})]}),O&&i.jsxs(ht,{"data-testid":"g7le-toolbar-exit-alt-mode",onClick:B,baseStyle:I,hoverStyle:Y,children:["← ",C.editMode==="base"&&S("layout_editor.chrome.toolbar.exit_base_edit"),C.editMode==="modal"&&S("layout_editor.chrome.toolbar.exit_modal_edit"),C.editMode==="extension"&&S("layout_editor.chrome.toolbar.exit_extension_edit"),C.editMode==="iteration_item"&&S("layout_editor.chrome.toolbar.exit_iteration_item_edit")]})]})}function cr(){if(typeof window>"u")return null;try{return window.localStorage?.getItem("auth_token")??null}catch{return null}}function Ne(e){const t={Accept:"application/json",...e??{}},n=cr();return n&&(t.Authorization=`Bearer ${n}`),t}function Oi(e){return encodeURIComponent(e)}async function Ll(e,t){const n=`/api/admin/templates/${Oi(e)}/layout-attachments?layout_name=${encodeURIComponent(t)}`;try{const o=await fetch(n,{method:"GET",headers:Ne(),credentials:"same-origin"}),r=await o.json().catch(()=>null);return!o.ok||!r?.success?{ok:!1,status:o.status,message:Bi(r,o.status)}:{ok:!0,data:Array.isArray(r?.data)?r.data:[]}}catch(o){return{ok:!1,status:0,message:o instanceof Error?o.message:"network error"}}}async function Pl(e,t,n){const o=`/api/admin/templates/${Oi(e)}/layout-attachments`,r=new FormData;r.append("file",n),r.append("layout_name",t);try{const s=await fetch(o,{method:"POST",headers:Ne(),body:r,credentials:"same-origin"}),a=await s.json().catch(()=>null);return!s.ok||!a?.success||!a?.data?.url?{ok:!1,status:s.status,message:Bi(a,s.status)}:{ok:!0,data:a.data}}catch(s){return{ok:!1,status:0,message:s instanceof Error?s.message:"network error"}}}async function Ol(e){const t=`/api/admin/templates/layout-attachments/${Oi(String(e))}`;try{const n=await fetch(t,{method:"DELETE",headers:Ne(),credentials:"same-origin"}),o=await n.json().catch(()=>null);return!n.ok||o&&o.success===!1?{ok:!1,status:n.status,message:Bi(o,n.status)}:{ok:!0,data:!0}}catch(n){return{ok:!1,status:0,message:n instanceof Error?n.message:"network error"}}}function Bi(e,t){if(e&&typeof e=="object"&&"message"in e){const n=e.message;if(typeof n=="string"&&n.length>0)return n}return`HTTP ${t}`}function Cy(e){return e<1024?`${e} B`:e<1024*1024?`${Math.round(e/1024)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function $y(e){if(!e)return"";const t=e.match(/^(\d{4})-(\d{2})-(\d{2})/);return t?`${t[2]}-${t[3]}`:""}function Bl({templateIdentifier:e,layoutName:t,t:n,onSelect:o,onChanged:r,onClose:s}){const[a,l]=u.useState([]),[d,c]=u.useState("idle"),[p,f]=u.useState(!1),[b,g]=u.useState(null),m=u.useRef(null),h=u.useCallback(async()=>{c("loading"),g(null);const _=await Ll(e,t);_.ok?(l(_.data),c("idle")):(g(_.message),c("error"))},[e,t]);u.useEffect(()=>{h()},[h]);const v=async _=>{const w=_.target.files?.[0];if(!w)return;f(!0),g(null);const k=await Pl(e,t,w);k.ok?(l(x=>[k.data,...x.filter($=>$.id!==k.data.id)]),r?.()):g(k.message),f(!1),m.current&&(m.current.value="")},y=async _=>{if(!(typeof window<"u"&&typeof window.confirm=="function"?window.confirm(n("layout_editor.attachment_manager.delete_confirm")):!0))return;const k=await Ol(_.id);k.ok?(l(x=>x.filter($=>$.id!==_.id)),r?.()):g(k.message)};return i.jsxs("div",{className:"g7le-attachment-manager","data-testid":"g7le-attachment-manager",style:Ey,children:[i.jsxs("div",{"data-modal-drag-handle":!0,style:Iy,children:[i.jsx("span",{style:{fontSize:14,fontWeight:700},"data-testid":"g7le-attachment-manager-title",children:n("layout_editor.attachment_manager.title")}),i.jsx("button",{type:"button","aria-label":"close",onClick:s,style:Ay,"data-testid":"g7le-attachment-manager-close",children:"✕"})]}),i.jsx("div",{style:Ty,children:i.jsxs("label",{style:Dy,"data-testid":"g7le-attachment-upload",children:[p?"…":`⬆ ${n("layout_editor.attachment_manager.upload")}`,i.jsx("input",{ref:m,type:"file",accept:"image/*",onChange:v,disabled:p,style:{display:"none"},"data-testid":"g7le-attachment-upload-input"})]})}),b&&i.jsx("div",{style:zy,"data-testid":"g7le-attachment-manager-error",children:b}),i.jsx("div",{style:Ny,children:d==="loading"?i.jsx("div",{style:Wl,"data-testid":"g7le-attachment-manager-loading",children:n("layout_editor.attachment_manager.loading")}):a.length===0&&d!=="error"?i.jsx("div",{style:Wl,"data-testid":"g7le-attachment-manager-empty",children:n("layout_editor.attachment_manager.empty")}):i.jsx("div",{style:My,"data-testid":"g7le-attachment-grid",children:a.map(_=>i.jsxs("div",{style:Ly,"data-testid":`g7le-attachment-card-${_.id}`,children:[i.jsx("div",{style:{...Py,backgroundImage:`url(${_.url})`}}),i.jsx("div",{style:Oy,title:_.original_name,children:_.original_name}),i.jsxs("div",{style:By,children:[Cy(_.size),_.created_at?` · ${$y(_.created_at)}`:""]}),i.jsxs("div",{style:Wy,children:[o&&i.jsx("button",{type:"button",onClick:()=>o(_.url),style:jy,"data-testid":`g7le-attachment-use-${_.id}`,children:n("layout_editor.attachment_manager.use_as_bg")}),i.jsx("button",{type:"button",onClick:()=>y(_),style:Hy,"data-testid":`g7le-attachment-delete-${_.id}`,children:"🗑"})]})]},_.id))})}),i.jsx("div",{style:Fy,children:i.jsx("button",{type:"button",onClick:s,style:Ky,"data-testid":"g7le-attachment-manager-footer-close",children:n("layout_editor.attachment_manager.close")})})]})}const Ey={display:"flex",flexDirection:"column",minHeight:0,flex:1},Iy={display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #e2e8f0"},Ay={border:"none",background:"transparent",fontSize:16,color:"#94a3b8",cursor:"pointer"},Ty={padding:"10px 16px",borderBottom:"1px solid #f1f5f9",display:"flex",gap:8},Dy={padding:"6px 12px",fontSize:13,border:"1px solid #2563eb",borderRadius:6,background:"#fff",color:"#2563eb",cursor:"pointer",display:"inline-flex",alignItems:"center"},zy={padding:"8px 16px",fontSize:12,color:"#b91c1c",background:"#fef2f2"},Ny={padding:16,overflow:"auto",flex:1,minHeight:120},Wl={fontSize:13,color:"#94a3b8",textAlign:"center",padding:"32px 0"},My={display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(140px, 1fr))",gap:12},Ly={display:"flex",flexDirection:"column",gap:4,border:"1px solid #e2e8f0",borderRadius:8,padding:8},Py={width:"100%",height:88,borderRadius:6,border:"1px solid #cbd5e1",backgroundSize:"cover",backgroundPosition:"center",backgroundColor:"#f8fafc"},Oy={fontSize:12,fontWeight:600,color:"#0f172a",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},By={fontSize:11,color:"#64748b"},Wy={display:"flex",gap:6,marginTop:2},jy={flex:1,padding:"4px 6px",fontSize:11,border:"1px solid #2563eb",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"},Hy={padding:"4px 8px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},Fy={padding:"10px 16px",borderTop:"1px solid #e2e8f0",display:"flex",justifyContent:"flex-end"},Ky={padding:"6px 14px",fontSize:13,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"};function ur(e){return encodeURIComponent(e)}async function Vy(e,t,n){const o=new URLSearchParams;t&&o.set("layout_name",t);const r=o.toString(),s=`/api/admin/templates/${ur(e)}/custom-translations`+(r?`?${r}`:"");try{const a=await fetch(s,{method:"GET",headers:Ne(),credentials:"same-origin"}),l=await a.json().catch(()=>null);return!a.ok||!l?.success?{ok:!1,status:a.status,message:pr(l,a.status)}:{ok:!0,data:Array.isArray(l?.data)?l.data:[]}}catch(a){return{ok:!1,status:0,message:a instanceof Error?a.message:"network error"}}}async function Uy(e,t,n,o){const r=`/api/admin/templates/${ur(e)}/custom-translations/${t}`;try{const s=await fetch(r,{method:"PUT",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({values:n,expected_lock_version:o}),credentials:"same-origin"}),a=await s.json().catch(()=>null);return!s.ok||!a?.success||!a?.data?{ok:!1,status:s.status,message:pr(a,s.status)}:{ok:!0,data:a.data}}catch(s){return{ok:!1,status:0,message:s instanceof Error?s.message:"network error"}}}async function qy(e,t){const n=`/api/admin/templates/${ur(e)}/custom-translations/${t}`;try{const o=await fetch(n,{method:"DELETE",headers:Ne(),credentials:"same-origin"}),r=await o.json().catch(()=>null);return!o.ok||r&&r.success===!1?{ok:!1,status:o.status,message:pr(r,o.status)}:{ok:!0,data:!0}}catch(o){return{ok:!1,status:0,message:o instanceof Error?o.message:"network error"}}}async function Gy(e,t){const n=`/api/admin/templates/${ur(e)}/custom-translations`;try{const o=await fetch(n,{method:"DELETE",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({ids:t}),credentials:"same-origin"}),r=await o.json().catch(()=>null);return!o.ok||!r?.success?{ok:!1,status:o.status,message:pr(r,o.status)}:{ok:!0,data:{deleted:typeof r?.data?.deleted=="number"?r.data.deleted:t.length}}}catch(o){return{ok:!1,status:0,message:o instanceof Error?o.message:"network error"}}}const jl=/\$t:(custom\.[A-Za-z0-9_\-]+\.\d+)/g;function Yy(e){const t=new Set,n=o=>{if(typeof o=="string"){if(o.includes("$t:custom.")){let r;for(jl.lastIndex=0;(r=jl.exec(o))!==null;)t.add(r[1])}return}if(Array.isArray(o)){for(const r of o)n(r);return}if(o&&typeof o=="object")for(const r of Object.values(o))n(r)};return n(e),t}function pr(e,t){if(e&&typeof e=="object"&&"message"in e){const n=e.message;if(typeof n=="string"&&n.length>0)return n}return`HTTP ${t}`}const Pt=Lt().TranslationEngine,mo=Lt().createLogger,Wi=mo("EditorSpecLoader"),Xy=["controls","componentCapabilities","actionRecipes","conditionRecipes","pageSettings","initActionRecipes","errorRecipes","computedRecipes","loadingComponents"],Jy=["actionRecipes","initActionRecipes","errorRecipes","computedRecipes","loadingComponents"];function Hl(e){if(typeof window>"u")return[];const n=window.G7Config?.[e];if(!Array.isArray(n))return[];const o=[];for(const r of n){const s=r?.identifier;typeof s=="string"&&s.length>0&&o.push(s)}return o}async function Zy(e,t,n,o){const s=`${n}/${e==="template"?"templates":e==="module"?"modules":"plugins"}/${encodeURIComponent(t)}/editor-spec`;try{const a=await o(s);if(!a.ok)return a.status!==404&&Wi.warn(`fetchOneSpec: HTTP ${a.status}`,s),null;const l=await a.json();return!l?.success||!l.data?null:l.data.spec??null}catch(a){return Wi.warn("fetchOneSpec: fetch failed",s,a),null}}function Qy(e){return Jy.includes(e)}function Ry(e,t){return e==null||typeof e!="object"?e:{...e,__source:t}}function eb(e,t,n,o){const r=t[n];if(!r||typeof r!="object")return;const s=e[n]??{};if(o&&Qy(n)){const a={};for(const[l,d]of Object.entries(r))a[l]=Ry(d,o);e[n]={...s,...a};return}e[n]={...s,...r}}function tb(e,t){if(!t.nesting)return;const n=e.nesting??{},o=new Set(n.draggable??[]);for(const r of t.nesting.draggable??[])o.add(r);n.draggable=Array.from(o),n.containers={...n.containers??{},...t.nesting.containers??{}},e.nesting=n}function nb(e,t){if(!t.componentPalette)return;const n=e.componentPalette??{},o=[...n.groups??[],...t.componentPalette.groups??[]];n.groups=o,n.entries={...n.entries??{},...t.componentPalette.entries??{}},e.componentPalette=n}function ob(e,t){if(!t.states)return;const n=e.states??{},o=[...n.groups??[],...t.states.groups??[]];n.groups=o,e.states=n}function rb(e,t){if(!Array.isArray(t.stateLabels)||t.stateLabels.length===0)return;const n=[...e.stateLabels??[],...t.stateLabels],o=new Map;for(const r of n)!r||typeof r.key!="string"||typeof r.scope!="string"||o.set(`${r.scope}:${r.key}`,r);e.stateLabels=Array.from(o.values())}function ib(e,t){if(!t.actionChipCandidates)return;const n=e.actionChipCandidates??{};for(const o of["response","error","payload"]){const r=t.actionChipCandidates[o];!Array.isArray(r)||r.length===0||(n[o]=[...n[o]??[],...r])}e.actionChipCandidates=n}function sb(e,t){if(!t.sampleData)return;const n=e.sampleData??{};n.byDataSourceId={...n.byDataSourceId??{},...t.sampleData.byDataSourceId??{}},n.byEndpointPattern={...n.byEndpointPattern??{},...t.sampleData.byEndpointPattern??{}},e.sampleData=n}function Fl(e,t,n){for(const o of Xy)eb(e,t,o,n);tb(e,t),nb(e,t),ob(e,t),rb(e,t),ib(e,t),sb(e,t),t.version&&(e.version=t.version)}async function ab(e){const t=e.apiBaseUrl??"/api",n=e.fetcher??(typeof fetch<"u"?fetch:void 0);if(!n)return Wi.warn("loadEditorSpecBundle: fetch unavailable, returning null spec"),{spec:null,sampleGlobalSources:[]};const o=e.activeModuleIdentifiers??Hl("activeModules"),r=e.activePluginIdentifiers??Hl("activePlugins"),s=[...o.map(p=>({kind:"module",id:p})),...r.map(p=>({kind:"plugin",id:p})),{kind:"template",id:e.templateIdentifier}],a=await Promise.all(s.map(p=>Zy(p.kind,p.id,t,n)));let l=null;const d=[],c={};if(e.coreSeed&&(l={},Fl(l,e.coreSeed,{kind:"core"})),s.forEach((p,f)=>{const b=a[f];if(!b)return;b.sampleGlobal&&typeof b.sampleGlobal=="object"&&d.push({id:p.id,kind:p.kind,sampleGlobal:b.sampleGlobal});const g=b.sampleData?.byDataSourceId;if(g&&typeof g=="object"){const m=p.kind==="template"?"template":`${p.kind}:${p.id}`;c[m]={...c[m]??{},...g}}l===null&&(l={}),Fl(l,b,{kind:p.kind,id:p.id})}),l!==null&&Object.keys(c).length>0){const p=l;p.sampleData={...p.sampleData??{},bySource:c}}return{spec:l,sampleGlobalSources:d}}function ji(e,t){return e?.componentCapabilities?.[t]??null}function Ct(e,t){return e?.controls?.[t]??null}function lb(e){return e?.initActionRecipes??{}}function db(e){return e?.computedRecipes??{}}function cb(e){return e?.errorRecipes??{}}function ub(e){const t=e?.loadingComponents;return!t||typeof t!="object"?[]:Object.values(t).filter(n=>n!=null&&typeof n=="object"&&typeof n.name=="string")}function pb(e,t,n){const o=e?.stateLabels;if(!Array.isArray(o))return null;for(const r of o)if(r?.scope===t&&r?.key===n)return typeof r.label_key=="string"?r.label_key:null;return null}function Hi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function fb(e){return e===null?"null":typeof e=="string"?e.length>40?`${e.slice(0,40)}…`:e:typeof e=="number"||typeof e=="boolean"?String(e):""}function gb(e){const t=e.find(n=>Hi(n));if(Hi(t))return Object.keys(t).slice(0,8)}function hb(e){return Object.keys(e).slice(0,8)}function yb(e){const t=Object.entries(e);return t.length===0?!1:t.some(([,n])=>n===null||typeof n!="object")}function Fi(e,t,n,o,r){if(Array.isArray(e)){r(t,"array",`[${e.length}]`,gb(e));return}if(Hi(e)){if(t&&yb(e)){const s=hb(e);r(t,"object",`{${s.length}}`,s)}if(n>=o)return;for(const[s,a]of Object.entries(e)){const l=t?`${t}.${s}`:s;Fi(a,l,n+1,o,r)}return}r(t,"scalar",fb(e))}function bb(e,t,n){const o=[];let r=e;for(const s of t){if(!r||(r=(Array.isArray(r.children)?r.children:[])[s],!r))break;const l=r.iteration;if(!(!l||l.source===void 0)&&(typeof l.index_var=="string"&&l.index_var.length>0&&o.push({name:l.index_var,kind:"index"}),typeof l.item_var=="string"&&l.item_var.length>0)){const d=typeof l.source=="string"?l.source:"",c=d&&n?.get(Kl(d))||[];o.push({name:l.item_var,kind:"item",itemFields:c})}}return o}function Kl(e){return e.replace(/^\{\{|\}\}$/g,"").trim()}function mb(e){const t=new Map;for(const n of e)n.shape==="array"&&n.itemFields&&n.itemFields.length>0&&t.set(Kl(n.expression),n.itemFields);return t}function Ki(e){const t=e.maxDepth??4,n=[];for(const o of e.dataSources??[])!o||typeof o.id!="string"||o.id.length===0||Fi(o.sample,"",0,t,(r,s,a,l)=>{const d=r?`{{${o.id}.${r}}}`:`{{${o.id}}}`;n.push({expression:d,source:"data_source",sourceId:o.id,path:r,shape:s,groupLabelKey:o.labelKey?.startsWith("$t:")?o.labelKey.slice(3):o.labelKey,preview:a,itemFields:l})});for(const o of e.states??[])!o||typeof o.scope!="string"||Fi(o.tree,"",0,t,(r,s,a,l)=>{if(!r)return;const d=pb(e.spec,o.scope,r)??void 0;n.push({expression:`{{${o.scope}.${r}}}`,source:o.scope,sourceId:o.scope,path:r,shape:s,labelKey:d?.startsWith("$t:")?d.slice(3):d,preview:a,itemFields:l})});for(const o of e.iterationVars??[])if(!(!o||typeof o.name!="string"||o.name.length===0)){if(o.kind==="index"){n.push({expression:`{{${o.name}}}`,source:"iteration",sourceId:o.name,path:"",shape:"scalar",preview:"0"});continue}for(const r of o.itemFields??[])n.push({expression:`{{${o.name}.${r}}}`,source:"iteration",sourceId:o.name,path:r,shape:"scalar",preview:""})}return n}const vb=["$localized"];function _b(e){const t=e.trim(),n=t.indexOf("(");if(n===-1||!t.endsWith(")"))return{fn:null,inner:t};const o=t.slice(0,n).trim();if(!vb.includes(o))return{fn:null,inner:t};const r=t.slice(n+1,-1);let s=0,a=null;for(let l=0;ln.shape===t)}function qi(e,t){const n=t.trim().toLowerCase();return n===""?e:e.filter(o=>[o.resolvedLabel??"",o.sourceId,o.path,o.preview].join(" ").toLowerCase().includes(n))}function Vl(e,t,n){const o={response:[{path:"data",labelKey:"layout_editor.action_chip.response_data",shape:"object"},{path:"message",labelKey:"layout_editor.action_chip.response_message",shape:"scalar"}],error:[{path:"status",labelKey:"layout_editor.action_chip.error_status",shape:"scalar"},{path:"message",labelKey:"layout_editor.action_chip.error_message",shape:"scalar"},{path:"errors",labelKey:"layout_editor.action_chip.error_errors",shape:"object"},{path:"data",labelKey:"layout_editor.action_chip.error_data",shape:"object"},{path:"statusText",labelKey:"layout_editor.action_chip.error_status_text",shape:"scalar"}],payload:[{path:"data",labelKey:"layout_editor.action_chip.payload_data",shape:"object"}]},r=e==="response"?"response":e==="error"?"error":"message",s=new Set,a=[];for(const d of o[e])s.has(d.path)||(s.add(d.path),a.push(d));const l=n?.[e];if(Array.isArray(l))for(const d of l)!d||typeof d.path!="string"||typeof d.labelKey!="string"||s.has(d.path)||(s.add(d.path),a.push({path:d.path,labelKey:d.labelKey,shape:d.shape??"scalar"}));return a.map(d=>({expression:`{{${r}.${d.path}}}`,source:"_local",sourceId:r,path:d.path,shape:d.shape,labelKey:d.labelKey,preview:t(d.labelKey)}))}const Gi=/\{\{(?:[^}]|\}(?!\}))*\}\}/g;function In(e){const t=[];if(typeof e!="string"||e.length===0)return t;let n=0,o=0;const r=new RegExp(Gi.source,"g");let s;for(;(s=r.exec(e))!==null;){const a=s.index,l=a+s[0].length;a>n&&t.push({kind:"literal",raw:e.slice(n,a),start:n,end:a}),t.push({kind:"binding",raw:s[0],start:a,end:l,parsed:Kt(s[0]),bindingIndex:o++}),n=l}return nt.kind==="binding")}function Yi(e){return typeof e!="string"?!1:new RegExp(Gi.source).test(e)}function wb(e){const t=new Set(e.map(o=>o.trim()));let n=0;for(;t.has(`p${n}`);)n+=1;return`p${n}`}function Ul(e,t,n){const o=typeof e=="string"?e:"",r=Math.max(0,Math.min(t,o.length)),s=o.slice(0,r),a=o.slice(r),l=s.length>0&&!/\s$/.test(s)?" ":"",d=a.length>0&&!/^\s/.test(a)?" ":"";return`${s}${l}{${n}}${d}${a}`}function Xi(e,t){const n=typeof e=="string"?e:"";return An(n).includes(t)?n:n.length===0?`{${t}}`:/\s$/.test(n)?`${n}{${t}}`:`${n} {${t}}`}function ql(e){return fr(e).map(t=>({bindingIndex:t.bindingIndex??0,expression:t.raw,parsed:t.parsed??null,isComplex:(t.parsed??null)===null}))}function gr(e){return typeof e!="string"?"":e.replace(new RegExp(Gi.source,"g")," ").replace(/\s+/g," ").trim()}const kb=/\$t:([a-zA-Z0-9._-]+)/g,Gl="custom.";function Ji(e,t){return typeof e!="string"||e.length===0?typeof e=="string"?e:"":t?In(e).map(n=>n.kind!=="literal"?n.raw:n.raw.replace(kb,(o,r)=>{if(r.startsWith(Gl))return o;const s=t(r);return s&&s!==r?s:o})).join(""):e}const Kn="(?:(?!\\|[a-zA-Z0-9_]+=).)*",Sb=new RegExp(`^\\s*\\$t:([a-zA-Z0-9._-]+)((?:\\|[a-zA-Z0-9_]+=${Kn})*)`),Cb=new RegExp(`\\|([a-zA-Z0-9_]+)=(${Kn})`,"g");function Vt(e){if(typeof e!="string")return"";const t=Kt(e);if(t)return t.path||t.sourceId;const n=e.trim().replace(/^\{\{\s*/,"").replace(/\s*\}\}$/,"");let o=-1;for(let l=0;l0){const l=n.slice(0,o).trim(),d=Kt(`{{${l}}}`);if(d)return d.path||d.sourceId;const c=l.replace(/\?\./g,".").replace(/\s*\?\?.*$/,"").trim();if(/^[A-Za-z_$][\w$.]*$/.test(c)){const p=c.split(".").filter(Boolean);return p.length>1&&p.slice(1).join(".")||c}}const r=n.replace(/\s+/g," ").trim(),s=r.replace(/\s*(\?\?|\|\|)\s*(\[\s*\]|\{\s*\}|'[^']*'|"[^"]*"|\d+|null|undefined)\s*$/,"").trim(),a=/\.([A-Za-z_$][\w$]*)\s*$/.exec(s);return a?a[1]:r}const Yl=/\$(?:core|module|plugin)_settings:[a-zA-Z0-9._:-]+/g;function Xl(e){return typeof e=="string"&&new RegExp(Yl.source).test(e)}function $b(e){return typeof e!="string"?"":e.replace(/^\$(?:core|module|plugin)_settings:/,"").split(/[.:]/).filter(Boolean).pop()||e}function Jl(e){const t=[];for(const n of In(e)){if(n.kind==="binding"){t.push({kind:"chip",label:Vt(n.raw)});continue}let o=0;const r=n.raw,s=new RegExp(Yl.source,"g");let a;for(;(a=s.exec(r))!==null;)a.index>o&&t.push({kind:"text",label:r.slice(o,a.index)}),t.push({kind:"chip",label:$b(a[0])}),o=a.index+a[0].length;o{const m=`p${o.length}`;return o.push(g),r[m]=Vt(g),`{${m}}`};let a=e,l="";const d=Sb.exec(e);if(d&&!d[1].startsWith(Gl)){const g=d[1],m=d[2]??"",h=e.slice(d[0].length),v=new Map,y=new RegExp(Cb.source,"g");let _;for(;(_=y.exec(m))!==null;)_[2]&&_[2].includes("{{")&&v.set(_[1],_[2]);const w=t?t(g):"";if(w&&w!==g&&!w.startsWith("$t:"))l=w.replace(/\{\{?([a-zA-Z0-9_]+)\}?\}/g,(k,x)=>{const $=v.get(x);return $?s($):k});else return n;a=h}const c=Ji(a,t),p=In(c).map(g=>g.kind==="binding"?s(g.raw):g.raw).join(""),f=`${l}${p}`;return/\$t:[a-zA-Z0-9._-]+/.test(f)||o.length===0?n:{chipValue:f,bindings:o,paramLabels:r,keyifiable:!0}}function Zl(e,t){return t.bindings.length?e+t.bindings.map((n,o)=>`|p${o}=${n}`).join(""):e}function Ql(e,t){const n=fr(t).map(r=>r.raw);if(n.length===0)return e;const o=n.map((r,s)=>`|p${s}=${r}`).join("");return`${e}${o}`}function Rl(e){if(typeof e!="string")return"";const t=In(e);let n=0;return t.map(o=>o.kind==="binding"?`{p${n++}}`:o.raw).join("")}const ed=new RegExp(`^\\s*\\$t:([a-zA-Z0-9._-]+)((?:\\|[a-zA-Z0-9_]+=${Kn})+)\\s*$`),Ib=new RegExp(`\\|([a-zA-Z0-9_]+)=(${Kn})`,"g");function vt(e){if(typeof e!="string")return null;const t=ed.exec(e);if(!t)return null;const n=t[1],o=t[2],r=[],s=new RegExp(Ib.source,"g");let a;for(;(a=s.exec(o))!==null;){const l=a[1],d=a[2];r.push({name:l,expression:d,parsed:Kt(d)})}return{key:n,params:r}}function td(e){return typeof e=="string"&&ed.test(e)}function An(e){if(typeof e!="string")return[];const t=[],n=/\{\{?(p\d+)\}?\}/g;let o;for(;(o=n.exec(e))!==null;)t.push(o[1]);return t.sort()}function Ab(e,t,n){if(typeof e!="string")return e;const o=new RegExp(`(\\|${t}=)${Kn}`);return o.test(e)?e.replace(o,`$1${n}`):e}function vo(e,t){if(typeof e!="string")return e;const n=new RegExp(`\\|${t}=${Kn}`);return e.replace(n,"")}function nd(e,t){return typeof e!="string"?e:e.replace(new RegExp(`\\s*\\{\\{?${t}\\}?\\}\\s*`,"g")," ").replace(/\s+/g," ").trim()}function Tb(e,t){const n=s=>fr(typeof s=="string"?s:"").map(a=>a.raw.replace(/\s+/g,"")).sort(),o=n(e),r=n(t);return o.length!==r.length?!1:o.every((s,a)=>s===r[a])}function od(e){return e.__source?.kind==="base"}function rd(e){return e.__source?.kind==="partial"}function Db(e){return e.__source?.kind==="route"}function hr(e,t){return e.__source?.kind!=="extension"?!1:t==null?!0:e.__source.extensionId!==t}function id(e){return e.type==="extension_point"}function Qi(e=[]){for(const t of e)if(t.iteration&&t.iteration.source!==void 0)return!0;return!1}function zb(e,t=[]){for(const n of t)if(n.iteration&&n.iteration.source!==void 0)return!0;return e.iteration&&e.iteration.source!==void 0?!0:sd(e)}function sd(e){if(typeof e.text=="string"&&ad(e.text)&&!Nb(e.text))return!0;if(e.props&&typeof e.props=="object"){for(const t of Object.values(e.props))if(typeof t=="string"&&ad(t))return!0}return!1}function ad(e){return/\{\{[\s\S]*?\}\}/.test(e)}function Nb(e){const t=vt(e);return t!==null&&t.key.startsWith("custom.")}function Mb(e,t){return e??t??null}function Ri(e,t,n){if(id(e))return!0;switch(t){case"route":return od(e)||rd(e)||hr(e);case"base":return hr(e);case"modal":return hr(e);case"extension":return hr(e,n)?!0:od(e)||Db(e)||rd(e);default:return!1}}function et(e){return typeof e=="object"&&e!==null&&typeof e.responsive=="string"}function yr(e,t){return et(e)?et(t)&&e.responsive===t.responsive:!et(t)&&e===t}function at(e){const t=[];let n=!1;for(const o of e){if(et(o)){t.push("responsive",o.responsive),n=!0;continue}n?t.push("children",String(o)):(t.push(String(o)),n=!0)}return t.join(".")}function Qt(e){return Array.isArray(e.children)?e.children:[]}function br(e,t){const n=e.responsive?.[t];return n&&Array.isArray(n.children)?n.children:[]}function Be(e,t){if(!e)return null;if(t.length===0)return e;let n=e,o=Qt(e);for(const r of t){if(et(r)){o=br(n,r.responsive);continue}if(r<0||r>=o.length||(n=o[r],!n))return null;o=Qt(n)}return n}function Lb(e,t,n){if(!e||t.length===0)return t;let o=e,r=Qt(e),s;for(let a=0;a=2?t[t.length-2]:void 0;if(r!==void 0&&et(r)){const a=Be(e,t.slice(0,-2));return a?{owner:a,children:br(a,r.responsive),branchKey:r.responsive,index:o}:null}const s=Be(e,t.slice(0,-1));return s?{owner:s,children:Qt(s),index:o}:null}function es(e,t){if(e.branchKey!==void 0){const n={...e.owner.responsive??{}};n[e.branchKey]={...n[e.branchKey]??{},children:t},e.owner.responsive=n}else e.owner.children=t}function Rt(e){const t={...e};t.props&&typeof t.props=="object"&&(t.props={...t.props});const n=Qt(e);if(n.length>0&&(t.children=n.map(Rt)),e.responsive&&typeof e.responsive=="object"){const o={};for(const r of Object.keys(e.responsive)){const s=e.responsive[r];if(!s||typeof s!="object"){o[r]=s;continue}const a={...s};Array.isArray(s.children)&&(a.children=s.children.map(Rt)),a.props&&typeof a.props=="object"&&(a.props={...a.props}),o[r]=a}t.responsive=o}return t}function ts(e,t,n,o){const r=Rt(e),s=t.length>0?t[t.length-1]:void 0;if(s!==void 0&&et(s)){const p=Be(r,t.slice(0,-1));if(!p)return r;const f=br(p,s.responsive),b=Math.max(0,Math.min(n,f.length)),g=[...f];return g.splice(b,0,o),es({owner:p,branchKey:s.responsive},g),r}const a=Be(r,t);if(!a)return r;const l=Qt(a),d=Math.max(0,Math.min(n,l.length)),c=[...l];return c.splice(d,0,o),a.children=c,r}function ns(e,t){if(t.length===0)return e;const n=Rt(e),o=ld(n,t);if(!o||o.index<0||o.index>=o.children.length)return n;const r=[...o.children];return r.splice(o.index,1),es(o,r),n}function Pb(e,t,n,o){if(t.length===0||!n||et(t[t.length-1]))return e;const r=Rt(e),s=Be(r,t);if(!s)return r;const a=s.responsive&&typeof s.responsive=="object"?s.responsive[n]:void 0;if(a&&Array.isArray(a.children))return r;const l=o&&s.responsive&&typeof s.responsive=="object"?s.responsive[o]:void 0,c=(l&&Array.isArray(l.children)?l.children:Qt(s)).map(Rt),p={...s.responsive??{}};return p[n]={...p[n]??{},children:c},s.responsive=p,r}function Ob(e,t,n){if(t.length===0||!n||et(t[t.length-1]))return e;const o=Rt(e),r=Be(o,t);if(!r||!r.responsive||typeof r.responsive!="object")return o;const s=r.responsive[n];if(!s||!Array.isArray(s.children))return o;const a={...r.responsive},l={...a[n]};return delete l.children,Object.keys(l).length===0?delete a[n]:a[n]=l,r.responsive=Object.keys(a).length>0?a:void 0,o}function Bb(e,t,n,o){if(t.length===0)return e;const r=Be(e,t);if(!r||Wb(t,n))return e;const s=Rt(r),a=ns(e,t),l=dd(n,t);let d=o;const c=t.slice(0,-1);if(cd(c,n)){const p=t[t.length-1];(typeof p=="number"?p:0)o){const s=[...e];return s[n]=r-1,s}return e}function cd(e,t){if(e.length!==t.length)return!1;for(let n=0;ne.length||cd(e,t)}function os(e){const t={...e};if(t.props&&typeof t.props=="object"&&(t.props={...t.props}),typeof t.id=="string"&&t.id.length>0){const o=typeof t.name=="string"?t.name:"node";t.id=`${o}_${jb()}`}const n=Qt(e);return n.length>0&&(t.children=n.map(os)),t}function Ot(e,t,n){if(t.length===0)return n(e);const o=Rt(e),r=Be(o,t);if(!r)return o;const s=n(r),a=ld(o,t);if(!a||a.index<0||a.index>=a.children.length)return o;const l=[...a.children];return l[a.index]=s,es(a,l),o}function jb(){return Math.floor(Math.random()*2821109907456).toString(36).padStart(8,"0")}function Vn(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const n of e){const o=Hb(n);o.length>0&&t.push(...o)}return t}function Hb(e){if(!e||typeof e!="object")return[];const t=e.__source,n=e._fromBase===!0,o=t?.kind;if(o==="extension"||o==="partial")return[];if(o==="base"||n){const s=Array.isArray(e.children)?e.children:[];return Vn(s)}const r={...e};return delete r.__source,delete r._fromBase,delete r.__injectedProps,Array.isArray(r.children)&&(r.children=Vn(r.children)),[r]}function _o(e){if(!e||typeof e!="object")return e;const t=e.__editor,n=t&&typeof t=="object"&&!Array.isArray(t)?t.original:void 0,o=n&&typeof n=="object"&&!Array.isArray(n)?n:void 0,r=Array.isArray(e.components)?e.components:[],s=r.length>0,a=Vn(r),l=o?{...o}:{...e};if(typeof l.extends=="string"&&l.extends.length>0){delete l.components;const c=l.slots&&typeof l.slots=="object"&&!Array.isArray(l.slots)?l.slots:{},p=Object.keys(c);if(!s&&p.length>0){const f={};for(const[b,g]of Object.entries(c))f[b]=Array.isArray(g)?Vn(g):g;l.slots=f}else if(p.length===1)l.slots={[p[0]]:a};else if(p.length===0)l.slots={content:a};else{const f={};for(const[b,g]of Object.entries(c))f[b]=Array.isArray(g)?Vn(g):g;l.slots=f}}else l.components=a,delete l.slots;return delete l.lock_version,delete l.__editor,l}const ud="extension",Un="extensionless";function Fb(){const e=globalThis?.G7Config;if(globalThis?.__g7AssetUrlMode===Un)return Un;const n=e?.assetUrlMode;return n===Un||n===ud?n:e?.settings?.general?.asset_url_mode===Un?Un:ud}function Kb(){return Fb()===Un}function en(e,t,n,o){const r=e.replace(/\/+$/,""),s=t.replace(/^\.+/,""),a=Kb()?r:`${r}.${s}`,l=[];return o&&l.push(o.replace(/^[?&]+/,"")),n!=null&&n!==""&&l.push(`v=${n}`),l.length>0?`${a}?${l.join("&")}`:a}const pd=/^\s*\$t:([a-zA-Z0-9._-]+)\s*$/,mr="custom.",Vb=/\{\{.*?\}\}/;function Ub(e){return!!(!e||e.iteration&&typeof e.iteration=="object")}function fd(e,t){const n=e?.text,o=typeof n=="string"?n:"";if(Ub(e)||typeof n!="string")return{sourceState:"plain_text",editable:!1,customKey:null,displayValue:o};const r=vt(o);if(r&&r.key.startsWith(mr)){const a=t?t(r.key):r.key;return{sourceState:"custom_key",editable:!0,customKey:r.key,displayValue:a,isParamKey:!0}}const s=pd.exec(o);if(s){const a=s[1];if(a.startsWith(mr)){const d=t?t(a):a;return{sourceState:"custom_key",editable:!0,customKey:a,displayValue:d}}const l=t?t(a):"";return{sourceState:"plain_text",editable:!0,customKey:null,displayValue:l&&l!==a?l:""}}if(Vb.test(o)){const a=gr(o),l=pd.exec(a);if(l&&l[1].startsWith(mr)){const f=l[1],b=t?t(f):f;return{sourceState:"custom_key",editable:!0,customKey:f,displayValue:b}}const d=Ji(o,t),c=gr(d),p=/\$t:[a-zA-Z0-9._-]+/.test(c);if(c.length>0){const f=Zi(o,t);return{sourceState:"plain_with_binding",editable:!0,customKey:null,displayValue:p?"":c,chipValue:f.keyifiable?f.chipValue:void 0,chipParamLabels:f.keyifiable?f.paramLabels:void 0}}return{sourceState:"binding_expression",editable:!1,customKey:null,displayValue:o}}return{sourceState:"plain_text",editable:!0,customKey:null,displayValue:o}}function qb(){const{state:e}=Qe(),t=Ft(),n=e.templateIdentifier,o=e.locale,r=e.selectedRoute?.layoutName??null,s=u.useCallback(p=>{try{const b=Pt.getInstance().translate(p,{templateId:n,locale:o});return b&&b!==p?b:""}catch{return""}},[n,o]),a=u.useCallback(p=>fd(p,s),[s]),l=u.useCallback(p=>{Et({op:"inline_edit_cancel",componentPath:p?at(p):null,timestamp:Date.now()})},[]),d=u.useCallback(async(p,f)=>{if(!t)return{kind:"error",message:"no document context"};const g={children:t.document?.raw?.components??[]},m=Be(g,p),h=fd(m,s);if(!h.editable)return Et({op:"inline_edit_blocked_binding",sourceState:h.sourceState,componentPath:at(p),timestamp:Date.now()}),{kind:"blocked"};if(h.customKey){if(f===h.displayValue)return{kind:"noop",translationKey:h.customKey};xo(n,o,h.customKey,f);const S=await vr(n,h.customKey,o,f);return S.kind==="error"?{kind:"error",message:S.message}:(await tn(n,o),Et({op:"inline_edit_update_value",sourceState:"custom_key",componentPath:at(p),translationKey:h.customKey,toLocale:o,valueLength:f.length,valueHash:Li(f),timestamp:Date.now()}),{kind:"updated",translationKey:h.customKey})}const v=typeof m?.text=="string"?m.text:"",y=h.sourceState==="plain_with_binding",_=Ji(v,s),w=y?Rl(_):f,k=S=>y?Ql(S,v):S;t.patchLayout(S=>Ot({children:S},p,E=>({...E,text:f})).children??[]);const x=await qn(n,r,o,w);if(x.kind==="error"||!x.resource)return{kind:"error",message:x.message};const $=x.resource.translation_key;return xo(n,o,$,w),t.patchLayout(S=>Ot({children:S},p,E=>({...E,text:k(`$t:${$}`)})).children??[]),await tn(n,o),Et({op:"inline_edit_create_key",sourceState:h.sourceState,componentPath:at(p),translationKey:$,toLocale:o,valueLength:f.length,valueHash:Li(f),timestamp:Date.now()}),{kind:"created",translationKey:$,id:x.resource.id}},[t,n,o,r,s]),c=u.useCallback(async(p,f)=>{if(!t)return{kind:"error",message:"no document context"};const g={children:t.document?.raw?.components??[]},m=Be(g,p),h=typeof m?.text=="string"?m.text:"",v=vt(h);if(v&&v.key.startsWith(mr))return _r(n,v.key,o,f),xo(n,o,v.key,f),t.markDirty?.(),{kind:"updated",translationKey:v.key};const y=Zi(h,s),_=gr(f.replace(/\{\{?p\d+\}?\}/g," ")).replace(/\s+/g," ").trim(),w=await qn(n,r,o,_);if(w.kind==="error"||!w.resource)return{kind:"error",message:w.message};const k=w.resource.translation_key,x=An(f),$=w.resource.values??{},S={[o]:f};for(const C of Object.keys($)){if(C===o)continue;let T=$[C]??"";for(const E of x)T=Xi(T,E);S[C]=T}return wo(n,k,S),xo(n,o,k,f),t.patchLayout(C=>Ot({children:C},p,A=>({...A,text:Zl(`$t:${k}`,y)})).children??[]),t.markDirty?.(),await tn(n,o),xo(n,o,k,f),Et({op:"inline_edit_create_key",sourceState:"plain_with_binding",componentPath:at(p),translationKey:k,toLocale:o,valueLength:f.length,valueHash:Li(f),timestamp:Date.now()}),{kind:"created",translationKey:k}},[t,n,o,r]);return{classify:a,commit:d,trackCancel:l,keyifyChipValue:c}}async function qn(e,t,n,o){const r=`/api/admin/templates/${encodeURIComponent(e)}/custom-translations`;try{const s=await fetch(r,{method:"POST",credentials:"same-origin",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({layout_name:t,locale:n,value:o})}),a=await s.json().catch(()=>null);if(!s.ok)return{kind:"error",message:a?.message??`HTTP ${s.status}`};const l=a?.data;return!l||typeof l.translation_key!="string"?{kind:"error",message:"invalid response"}:{kind:"ok",resource:l}}catch(s){return{kind:"error",message:s instanceof Error?s.message:"network error"}}}async function vr(e,t,n,o){const r=await cn(e,t);if(!r)return{kind:"error",message:"custom key not found"};const s=`/api/admin/templates/${encodeURIComponent(e)}/custom-translations/${r.id}`,a={...r.values??{},[n]:o};try{const l=await fetch(s,{method:"PUT",credentials:"same-origin",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({values:a,expected_lock_version:r.lock_version})}),d=await l.json().catch(()=>null);return l.status===409?{kind:"error",message:"concurrent_modification"}:l.ok?{kind:"ok"}:{kind:"error",message:d?.message??`HTTP ${l.status}`}}catch(l){return{kind:"error",message:l instanceof Error?l.message:"network error"}}}async function cn(e,t){const n=`/api/admin/templates/${encodeURIComponent(e)}/custom-translations`;try{const o=await fetch(n,{method:"GET",credentials:"same-origin",headers:Ne()});if(!o.ok)return null;const s=(await o.json().catch(()=>null))?.data;return Array.isArray(s)?s.find(a=>a.translation_key===t)??null:null}catch{return null}}function xo(e,t,n,o){try{Pt.getInstance().setTranslationValue(e,t,n,o)}catch{}if(typeof window<"u")try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:e,locale:t}}))}catch{}}const kt="g7le:translations-refreshed";async function tn(e,t){if(typeof window>"u")return;const n=t??window.__g7EditorContentLocale;if(n){try{const o=Pt.getInstance();try{const r=await fetch(en(`/api/templates/${encodeURIComponent(e)}/config`,"json"),{headers:{Accept:"application/json"},credentials:"same-origin"}).then(a=>a.ok?a.json():null),s=r?.data?.cache_version??r?.cache_version;if(typeof s=="number"&&s>0){o.setCacheVersion(s);const a=window;a.G7Config&&(a.G7Config.cache_version=s)}}catch{}await o.loadTranslations(e,n,"/api",!0)}catch{}try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:e,locale:n}}))}catch{}}}const nn=new Map;function _r(e,t,n,o){const r=nn.get(t)??{};r[n]=o,nn.set(t,r);try{Pt.getInstance().setTranslationValue(e,n,t,o)}catch{}if(typeof window<"u")try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:e,locale:n}}))}catch{}}function wo(e,t,n){for(const[o,r]of Object.entries(n))_r(e,t,o,r)}function It(e,t){return nn.get(e)?.[t]}function Gb(e){const t=nn.get(e);return t?{...t}:void 0}function Yb(){return nn.size>0}function gd(e,t){for(const[n,o]of nn.entries())for(const[r,s]of Object.entries(o))try{e.setTranslationValue(t,r,n,s)}catch{}}async function Xb(e){if(nn.size===0)return{ok:0,failed:[]};const t=Array.from(nn.entries());let n=0;const o=[];for(const[r,s]of t)try{const a=await cn(e,r);if(!a){o.push(r);continue}const l={...a.values??{},...s},d=`/api/admin/templates/${encodeURIComponent(e)}/custom-translations/${a.id}`;if(!(await fetch(d,{method:"PUT",credentials:"same-origin",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({values:l,expected_lock_version:a.lock_version})})).ok){o.push(r);continue}n+=1}catch{o.push(r)}for(const[r]of t)o.includes(r)||nn.delete(r);try{await tn(e)}catch{}return{ok:n,failed:o}}function Gn(e,t){const n=`layout_editor.locale.${e}`,o=t(n);return o&&o!==n?o:e.toUpperCase()}function hd(){if(typeof window>"u")return[];const t=window.G7Config?.appConfig?.supportedLocales;return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.length>0):[]}function Jb({locales:e}={}){const{t}=tt(),{state:n,dispatch:o}=Qe();u.useEffect(()=>{window.__g7EditorContentLocale=n.locale},[n.locale]);const r=e??hd(),s=r.includes(n.locale)?r:[n.locale,...r];if(s.length<=1)return i.jsxs("span",{className:"g7le-locale-switcher g7le-locale-switcher--single","data-testid":"g7le-locale-switcher-single",style:{fontSize:11,color:"#475569",padding:"0 4px"},children:[t("layout_editor.chrome.toolbar.locale_switcher_label"),": ",Gn(n.locale,t)]});const a=l=>{if(l===n.locale)return;const d=n.locale;o({type:"SET_LOCALE",locale:l}),Et({op:"locale_switch",fromLocale:d,toLocale:l,timestamp:Date.now()})};return i.jsxs("div",{className:"g7le-locale-switcher","data-testid":"g7le-locale-switcher",role:"group","aria-label":t("layout_editor.chrome.toolbar.locale_switcher_label"),style:{display:"inline-flex",alignItems:"center",gap:4},children:[i.jsx("span",{style:{fontSize:11,color:"#475569"},children:t("layout_editor.chrome.toolbar.locale_switcher_label")}),i.jsx("div",{style:{display:"inline-flex",gap:2},children:s.map(l=>{const d=l===n.locale;return i.jsx("button",{type:"button","data-testid":`g7le-locale-${l}`,"aria-pressed":d,onClick:()=>a(l),style:{padding:"2px 8px",fontSize:12,cursor:"pointer",background:d?"#0f172a":"#f8fafc",color:d?"#fff":"#0f172a",border:"1px solid #cbd5e1",borderRadius:4},children:Gn(l,t)},l)})})]})}const Zb=/\{\{?(p\d+)\}?\}/g;function Qb(e){const t=[];if(typeof e!="string"||e.length===0)return t;const n=new RegExp(Zb.source,"g");let o=0,r;for(;(r=n.exec(e))!==null;){const s=r.index,a=s+r[0].length;s>o&&t.push({kind:"text",raw:e.slice(o,s),start:o,end:s}),t.push({kind:"chip",raw:r[0],paramName:r[1],start:s,end:a}),o=a}return o{n.push({kind:"text",text:a}),r=!0};for(const a of t)a.kind==="text"?(o=a.raw,s(o),o=""):(r||s(""),n.push({kind:"chip",paramName:a.paramName}),r=!1);return r||s(""),n}function em(e,t,n,o){const r=[];return e.forEach((s,a)=>{if(s.kind==="chip"){if(s.paramName===t)return;r.push(`{${s.paramName}}`)}else{const l=s.text??"";if(a===n){const d=Math.max(0,Math.min(o,l.length));r.push(l.slice(0,d),`{${t}}`,l.slice(d))}else r.push(l)}}),r.join("")}function xr({value:e,onChange:t,t:n,paramLabels:o,onRequestInsert:r,onRemoveChip:s,testIdSuffix:a="pc",disabled:l=!1,hideInsertButton:d=!1,caretRef:c}){const p=u.useMemo(()=>Rb(e),[e]),f=u.useRef(null),[b,g]=u.useState(null),[m,h]=u.useState(null),[v,y]=u.useState(null),_=u.useMemo(()=>p.map(O=>O.kind==="chip"?`c:${O.paramName}`:"t").join("|"),[p]),w=u.useRef(null),k=u.useRef([]),x=u.useRef(!1);u.useLayoutEffect(()=>{const O=x.current;x.current=!1,!(!O&&w.current===_)&&(w.current=_,p.forEach((z,H)=>{if(z.kind!=="text")return;const P=k.current[H];P&&P.textContent!==(z.text??"")&&(P.textContent=z.text??"")}))},[_,p,e]);const $=()=>{const O=f.current;if(!O)return e;const z=[];for(const H of Array.from(O.querySelectorAll("[data-seg]")))H.dataset.seg==="chip"?z.push(`{${H.dataset.param??""}}`):z.push(H.textContent??"");return z.join("")},S=()=>{l||t($())},C=u.useRef(null),T=u.useRef(!1),E=(O,z)=>{if(!l){O.preventDefault(),O.stopPropagation(),C.current={param:z,pointerId:O.pointerId},T.current=!1,g(z);try{O.currentTarget.setPointerCapture(O.pointerId)}catch{}}},A=O=>{const z=C.current;if(!z||O.pointerId!==z.pointerId)return;T.current=!0;const H=B(O.clientX,O.clientY);H&&(h({slotIdx:H.slotIdx,offset:H.offset}),y(nm(f.current,H.slotIdx,H.offset)))},N=(O,z)=>{if(O.stopPropagation(),T.current){T.current=!1;return}s?.(z)},D=O=>{const z=C.current;if(!z||O.pointerId!==z.pointerId)return;try{O.currentTarget.releasePointerCapture(O.pointerId)}catch{}C.current=null,T.current&&typeof setTimeout=="function"&&setTimeout(()=>{T.current=!1},0);const H=B(O.clientX,O.clientY);if(g(null),h(null),y(null),!H)return;const P=f.current;if(!P)return;const L=Array.from(P.querySelectorAll("[data-seg]")).map(Y=>Y.dataset.seg==="chip"?{kind:"chip",paramName:Y.dataset.param??""}:{kind:"text",text:Y.textContent??""}),F=em(L,z.param,H.slotIdx,H.offset);F!==e&&(x.current=!0,t(F))},B=(O,z)=>{const H=f.current;if(!H)return null;const P=Array.from(H.querySelectorAll("[data-seg]")),I=H.ownerDocument,L=I.elementFromPoint(O,z);let F=L?.closest('[data-seg="text"]');if(F)return{slotIdx:P.indexOf(F),offset:tm(I,F,O,z)};const Y=L?.closest('[data-seg="chip"]');if(Y){const X=P.indexOf(Y),Z=Y.getBoundingClientRect();if(O=0){const se=P[X-1];return{slotIdx:X-1,offset:(se.textContent??"").length}}if(X+1({s:X,i:Z})).filter(X=>X.s.dataset.seg==="text").pop();return K?{slotIdx:K.i,offset:(K.s.textContent??"").length}:null},M=()=>{l||!r||r(yd(f.current,e.length))};return u.useEffect(()=>{if(c)return c.current=()=>yd(f.current,e.length),()=>{c.current=null}},[c,e.length]),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsxs("div",{ref:f,"data-testid":`g7le-chip-input-${a}`,className:"g7le-chip-input",style:om,children:[p.map((O,z)=>O.kind==="chip"?i.jsxs("span",{"data-seg":"chip","data-param":O.paramName,"data-testid":`g7le-chip-${a}-${O.paramName}`,contentEditable:!1,onPointerDown:H=>E(H,O.paramName??""),onPointerMove:A,onPointerUp:D,title:n("layout_editor.translation.placeholder_locked"),style:{...am,...b===O.paramName?lm:null,touchAction:"none"},children:[i.jsx("span",{"aria-hidden":"true",style:dm,children:"⠿"}),i.jsx("span",{"aria-hidden":"true",style:{marginRight:3},children:"🔗"}),i.jsx("span",{style:cm,children:o?.[O.paramName??""]??O.paramName}),s&&!l&&i.jsx("button",{type:"button","data-testid":`g7le-chip-remove-${a}-${O.paramName}`,"aria-label":n("layout_editor.inline_binding.clear"),title:n("layout_editor.inline_binding.clear"),onPointerDown:H=>{H.stopPropagation(),H.preventDefault()},onClick:H=>N(H,O.paramName??""),style:um,children:"✕"})]},`chip-${O.paramName}`):i.jsx("span",{ref:H=>{k.current[z]=H},"data-seg":"text",contentEditable:!l,suppressContentEditableWarning:!0,onInput:S,"data-testid":`g7le-chip-text-${a}-${z}`,style:{...rm,...b?im:null,...m?.slotIdx===z?sm:null}},`text-slot-${z}`)),v&&i.jsx("span",{"aria-hidden":"true","data-testid":`g7le-chip-caret-${a}`,style:{position:"absolute",left:v.left,top:v.top,width:2,height:v.height,background:"#2563eb",borderRadius:1,pointerEvents:"none",boxShadow:"0 0 0 1px rgba(37,99,235,0.3)"}})]}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r&&!d&&i.jsxs("button",{type:"button","data-testid":`g7le-chip-insert-${a}`,onClick:M,disabled:l,style:pm,children:["+ ",n("layout_editor.inline_binding.insert_data")]}),i.jsx("span",{style:fm,children:n("layout_editor.translation.placeholder_locked")})]})]})}function tm(e,t,n,o){const r=(t.textContent??"").length;try{const a=e;let l=null,d=0;if(typeof a.caretRangeFromPoint=="function"){const c=a.caretRangeFromPoint(n,o);c&&(l=c.startContainer,d=c.startOffset)}else if(typeof a.caretPositionFromPoint=="function"){const c=a.caretPositionFromPoint(n,o);c&&(l=c.offsetNode,d=c.offset)}if(l&&t.contains(l))return Math.max(0,Math.min(d,r))}catch{}const s=t.getBoundingClientRect();return n>s.left+s.width/2?r:0}function nm(e,t,n){if(!e)return null;const r=Array.from(e.querySelectorAll("[data-seg]"))[t];if(!r)return null;const s=e.getBoundingClientRect();try{const d=r.firstChild,c=e.ownerDocument;if(d&&d.nodeType===Node.TEXT_NODE&&(d.textContent??"").length>0){const p=c.createRange(),f=Math.max(0,Math.min(n,(d.textContent??"").length));p.setStart(d,f),p.setEnd(d,f);const b=p.getClientRects(),g=b.length>0?b[0]:p.getBoundingClientRect();if(g&&(g.height>0||g.width>=0))return{left:g.left-s.left,top:g.top-s.top,height:g.height||r.getBoundingClientRect().height}}}catch{}const a=r.getBoundingClientRect();return{left:(n>0?a.right:a.left)-s.left,top:a.top-s.top,height:a.height||16}}function yd(e,t){if(!e)return t;try{const n=e.ownerDocument.defaultView?.getSelection();if(!n||n.rangeCount===0)return t;const o=n.getRangeAt(0);let r=o.startContainer,s=null;for(;r&&r!==e;){if(r instanceof HTMLElement&&r.dataset.seg==="text"){s=r;break}r=r.parentNode}if(!s||!e.contains(s))return t;const a=Array.from(e.querySelectorAll("[data-seg]"));let l=0;for(const d of a){if(d===s)break;l+=d.dataset.seg==="chip"?`{${d.dataset.param??""}}`.length:(d.textContent??"").length}return l+o.startOffset}catch{return t}}const om={position:"relative",display:"flex",flexWrap:"wrap",alignItems:"center",gap:2,minHeight:30,padding:"4px 8px",border:"1px solid #cbd5e1",borderRadius:4,background:"#fff",fontSize:13,lineHeight:1.6},rm={outline:"none",minWidth:8,minHeight:"1.2em",whiteSpace:"pre-wrap",color:"#0f172a",display:"inline-block"},im={boxShadow:"inset 0 -2px 0 #93c5fd",background:"#eff6ff",borderRadius:2},sm={background:"#dbeafe",boxShadow:"inset 0 -2px 0 #2563eb"},am={display:"inline-flex",alignItems:"center",gap:1,background:"linear-gradient(180deg,#eff6ff,#dbeafe)",color:"#1d4ed8",border:"1px dashed #60a5fa",borderRadius:9999,padding:"1px 8px 1px 4px",margin:"0 1px",fontSize:12,fontWeight:600,cursor:"grab",userSelect:"none",whiteSpace:"nowrap",boxShadow:"0 1px 2px rgba(37,99,235,0.18)",verticalAlign:"middle"},lm={opacity:.5,borderStyle:"solid",cursor:"grabbing"},dm={color:"#2563eb",opacity:.7,fontSize:11,marginRight:1,cursor:"grab"},cm={textDecoration:"none"},um={marginLeft:4,width:14,height:14,lineHeight:"12px",padding:0,border:"none",borderRadius:9999,background:"rgba(29,78,216,0.12)",color:"#1d4ed8",fontSize:9,fontWeight:700,cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"0 0 auto"},pm={fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#334155",padding:"3px 10px",cursor:"pointer"},fm={fontSize:10,color:"#94a3b8"};function bd(e){e&&(e.style.height="auto",e.style.height=`${Math.max(e.scrollHeight,28)}px`)}function gm(e){bd(e)}function hm(e){const t=new Set;for(const n of e)for(const o of Object.keys(n.values??{}))t.add(o);return Array.from(t).sort()}function ym({templateIdentifier:e,layoutName:t,t:n,referencedKeys:o,onClose:r}){const[s,a]=u.useState([]),[l,d]=u.useState("idle"),[c,p]=u.useState(null),[f,b]=u.useState("all"),[g,m]=u.useState(new Set),[h,v]=u.useState({}),[y,_]=u.useState(null),[w,k]=u.useState({}),x=u.useCallback(async()=>{d("loading"),p(null);const z=await Vy(e,t);z.ok?(a(z.data),v({}),m(new Set),k({}),d("idle")):(p(z.message),d("error"))},[e,t]);u.useEffect(()=>{x()},[x]);const $=u.useMemo(()=>hm(s),[s]),S=u.useMemo(()=>s.filter(z=>f==="all"?!0:z.status===f).slice().sort((z,H)=>{const P=z.updated_at?Date.parse(z.updated_at):0,I=H.updated_at?Date.parse(H.updated_at):0;return I!==P?I-P:H.id-z.id}),[s,f]),C=u.useMemo(()=>s.filter(z=>z.status==="orphaned"),[s]),T=u.useCallback(z=>{const H={...z.values??{}};for(const P of Object.keys(H)){const I=It(z.translation_key,P);I!==void 0&&(H[P]=I)}return H},[]),E=u.useCallback(z=>h[z.id]??T(z),[h,T]),A=u.useCallback((z,H,P)=>{v(I=>{const L=I[z]??s.find(F=>F.id===z)?.values??{};return{...I,[z]:{...L,[H]:P}}})},[s]),N=u.useCallback(async z=>{_(z.id),k(I=>({...I,[z.id]:""}));const H=E(z),P=await Uy(e,z.id,H,z.lock_version);if(P.ok)a(I=>I.map(L=>L.id===z.id?P.data:L)),v(I=>{const L={...I};return delete L[z.id],L});else{const I=P.status===409?n("layout_editor.translation_manager.conflict"):P.message;k(L=>({...L,[z.id]:I}))}_(null)},[e,E,n]),D=u.useCallback(z=>typeof window<"u"&&typeof window.confirm=="function"?window.confirm(n("layout_editor.translation_manager.delete_confirm",{count:z})):!0,[n]),B=u.useCallback(async z=>{if(!D(1))return;const H=await qy(e,z.id);H.ok?(a(P=>P.filter(I=>I.id!==z.id)),m(P=>{const I=new Set(P);return I.delete(z.id),I})):p(H.message)},[e,D]),M=u.useCallback(async z=>{if(z.length===0||!D(z.length))return;const H=await Gy(e,z);if(H.ok){const P=new Set(z);a(I=>I.filter(L=>!P.has(L.id))),m(new Set)}else p(H.message)},[e,D]),O=u.useCallback(z=>{m(H=>{const P=new Set(H);return P.has(z)?P.delete(z):P.add(z),P})},[]);return i.jsxs("div",{className:"g7le-translation-manager","data-testid":"g7le-translation-manager",style:bm,children:[i.jsxs("div",{"data-modal-drag-handle":!0,style:mm,children:[i.jsx("span",{style:{fontSize:14,fontWeight:700},"data-testid":"g7le-translation-manager-title",children:n("layout_editor.translation_manager.title")}),i.jsx("button",{type:"button","aria-label":"close",onClick:r,style:vm,"data-testid":"g7le-translation-manager-close",children:"✕"})]}),i.jsxs("div",{style:_m,children:[i.jsx("div",{style:{display:"inline-flex",gap:4},role:"tablist","aria-label":n("layout_editor.translation_manager.filter_label"),children:["all","active","orphaned"].map(z=>i.jsx("button",{type:"button",role:"tab","aria-selected":f===z,"data-active":f===z?"true":"false",onClick:()=>b(z),style:f===z?xm:md,"data-testid":`g7le-translation-filter-${z}`,children:n(`layout_editor.translation_manager.filter_${z}`)},z))}),i.jsx("div",{style:{flex:1}}),g.size>0&&i.jsxs("button",{type:"button",onClick:()=>{M(Array.from(g))},style:vd,"data-testid":"g7le-translation-bulk-delete",children:["🗑 ",n("layout_editor.translation_manager.delete_selected",{count:g.size})]}),C.length>0&&i.jsxs("button",{type:"button",onClick:()=>{M(C.map(z=>z.id))},style:vd,"data-testid":"g7le-translation-purge-orphaned",children:["🧹 ",n("layout_editor.translation_manager.purge_orphaned",{count:C.length})]})]}),c&&i.jsx("div",{style:wm,"data-testid":"g7le-translation-manager-error",children:c}),i.jsx("div",{style:km,children:l==="loading"?i.jsx("div",{style:_d,"data-testid":"g7le-translation-manager-loading",children:n("layout_editor.translation_manager.loading")}):S.length===0&&l!=="error"?i.jsx("div",{style:_d,"data-testid":"g7le-translation-manager-empty",children:n("layout_editor.translation_manager.empty")}):i.jsx("div",{"data-testid":"g7le-translation-list",style:Sm,children:S.map(z=>{const H=E(z),P=z.status==="orphaned",I=o?o.has(z.translation_key):null;return i.jsxs("div",{style:Cm,"data-testid":`g7le-translation-row-${z.id}`,children:[i.jsxs("div",{style:$m,children:[i.jsx("input",{type:"checkbox",checked:g.has(z.id),onChange:()=>O(z.id),"aria-label":n("layout_editor.translation_manager.select_aria",{key:z.translation_key}),"data-testid":`g7le-translation-select-${z.id}`}),i.jsx("code",{style:Em,children:z.translation_key}),P&&i.jsx("span",{style:Im,"data-testid":`g7le-translation-badge-orphaned-${z.id}`,children:n("layout_editor.translation_manager.badge_orphaned")}),I===!0&&i.jsx("span",{style:Am,"data-testid":`g7le-translation-badge-live-inuse-${z.id}`,children:n("layout_editor.translation_manager.badge_live_in_use")}),I===!1&&i.jsx("span",{style:Tm,"data-testid":`g7le-translation-badge-live-unused-${z.id}`,children:n("layout_editor.translation_manager.badge_live_unused")}),i.jsx("div",{style:{flex:1}}),i.jsx("button",{type:"button",onClick:()=>{B(z)},style:Om,"data-testid":`g7le-translation-delete-${z.id}`,children:"🗑"})]}),i.jsxs("div",{style:Dm,children:[$.map(L=>{const F=H[L]??"",Y=An(F).length>0;return i.jsxs("div",{style:zm,"data-testid":`g7le-translation-field-${z.id}-${L}`,children:[i.jsxs("label",{style:Nm,title:L,children:[Gn(L,n),i.jsxs("span",{style:Mm,children:["(",L,")"]})]}),Y?i.jsx("div",{style:{flex:1},"data-testid":`g7le-translation-chip-${z.id}-${L}`,children:i.jsx(xr,{value:F,onChange:K=>A(z.id,L,K),t:n,testIdSuffix:`${z.id}-${L}`})}):i.jsx("textarea",{value:F,rows:1,ref:gm,onChange:K=>{A(z.id,L,K.currentTarget.value),bd(K.currentTarget)},style:Lm,"data-testid":`g7le-translation-input-${z.id}-${L}`})]},L)}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("button",{type:"button",disabled:y===z.id,onClick:()=>{N(z)},style:Pm,"data-testid":`g7le-translation-save-${z.id}`,children:y===z.id?n("layout_editor.translation_manager.saving"):n("layout_editor.translation_manager.save")}),w[z.id]?i.jsx("span",{style:{fontSize:11,color:"#dc2626"},"data-testid":`g7le-translation-row-error-${z.id}`,children:w[z.id]}):null]})]})]},z.id)})})}),i.jsx("div",{style:Bm,children:i.jsx("button",{type:"button",onClick:r,style:Wm,"data-testid":"g7le-translation-manager-footer-close",children:n("layout_editor.translation_manager.close")})})]})}const bm={display:"flex",flexDirection:"column",minHeight:0,flex:1},mm={display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #e2e8f0"},vm={border:"none",background:"transparent",fontSize:16,color:"#94a3b8",cursor:"pointer"},_m={padding:"10px 16px",borderBottom:"1px solid #f1f5f9",display:"flex",gap:8,alignItems:"center"},md={padding:"4px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},xm={...md,borderColor:"#2563eb",background:"#eff6ff",color:"#1d4ed8",fontWeight:600},vd={padding:"4px 10px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},wm={padding:"8px 16px",fontSize:12,color:"#b91c1c",background:"#fef2f2"},km={padding:16,overflow:"auto",flex:1,minHeight:120,display:"flex",flexDirection:"column",gap:12},_d={fontSize:13,color:"#94a3b8",textAlign:"center",padding:"32px 0"},Sm={display:"flex",flexDirection:"column",gap:20},Cm={border:"1px solid #e2e8f0",borderRadius:8,padding:10,display:"flex",flexDirection:"column",gap:6},$m={display:"flex",alignItems:"center",gap:8},Em={fontSize:11,background:"#f1f5f9",padding:"2px 6px",borderRadius:4,color:"#0f172a"},Im={fontSize:10,color:"#b45309",background:"#fef3c7",padding:"1px 6px",borderRadius:4,fontWeight:600},Am={fontSize:10,color:"#15803d",background:"#dcfce7",padding:"1px 6px",borderRadius:4,fontWeight:600},Tm={fontSize:10,color:"#9f1239",background:"#ffe4e6",padding:"1px 6px",borderRadius:4,fontWeight:600},Dm={display:"flex",flexDirection:"column",gap:6},zm={display:"flex",alignItems:"flex-start",gap:8},Nm={fontSize:12,color:"#475569",minWidth:88,fontWeight:600,paddingTop:4,display:"flex",flexDirection:"column",lineHeight:1.2},Mm={fontSize:10,color:"#94a3b8",fontWeight:400},Lm={flex:1,padding:"4px 8px",fontSize:13,border:"1px solid #cbd5e1",borderRadius:4,color:"#0f172a",resize:"vertical",overflow:"hidden",minHeight:28,lineHeight:1.4,fontFamily:"inherit",boxSizing:"border-box"},Pm={padding:"5px 12px",fontSize:12,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"},Om={padding:"4px 8px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},Bm={padding:"10px 16px",borderTop:"1px solid #e2e8f0",display:"flex",justifyContent:"flex-end"},Wm={padding:"6px 14px",fontSize:13,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"};function jm(){const e=Ft(),{state:t}=Qe(),n=e?.document?.raw??null,o=t.templateIdentifier??"",r=t.selectedRoute?.layoutName??"",s=u.useCallback((c,p)=>{const f=n?.[c];return f===void 0?p:f},[n]),a=u.useCallback((c,p,...f)=>{e&&(f.length>=1?e.patchDocumentRaw(c,p,f[0]):e.patchDocumentRaw(c,p))},[e]),l=u.useCallback(async(c,p)=>!o||!r?null:qn(o,r,c,p),[o,r]),d=u.useCallback(async(c,p,f)=>o?vr(o,c,p,f):null,[o]);return{raw:n,getValue:s,patch:a,createI18nKey:l,updateI18nKeyValue:d}}function Hm(e){const t=e.__source;return t&&(t.kind==="module"||t.kind==="plugin")&&t.identifier?`${t.kind}:${t.identifier}`:"template"}function xd(e,t){if(!t)return null;const n=Hm(e);if(n&&t.bySource){const a=t.bySource[n]?.[e.id];if(a!==void 0)return{value:a,match:{dataSourceId:e.id,resolvedBy:"spec_byId",sourceKey:n}}}const o=t.byDataSourceId?.[e.id];if(o!==void 0)return{value:o,match:{dataSourceId:e.id,resolvedBy:"spec_byId"}};const r=e.endpoint??"";if(t.byEndpointPattern&&typeof r=="string"&&r.length>0){for(const[s,a]of Object.entries(t.byEndpointPattern))if(Fm(r,s))return{value:a,match:{dataSourceId:e.id,resolvedBy:"spec_byEndpoint"}}}return null}function rs(e,t){const n=xd(e,t);if(n)return n;const o=e.fallback?.data;return o!==void 0?{value:{data:Array.isArray(o)?o:[o]},match:{dataSourceId:e.id,resolvedBy:"fallback"}}:{value:{},match:{dataSourceId:e.id,resolvedBy:"inferred"}}}function Fm(e,t){const n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(e)}function Km(e={}){const{spec:t,overrideSpec:n,onMatch:o}=e;return{has(r){return!0},resolve(r){const s=n?xd(r,n):null,{value:a,match:l}=s??rs(r,t);if(o)try{o(l)}catch{}return a}}}const wd=Lt(),kd=wd.DataBindingEngine,Sd=wd.dataBindingEngine;mo("PipeRegistry");function Vm(e){let t=null,n=0;for(let o=0;o0?e[o-1]:"",a=o{const a=t[r],l=a==null?[]:String(a).split(",").map(d=>d.trim()).filter(Boolean);return l.length===0?"":l.join(" ?? ")+(s?" ?? ":"")});return n=n.replace(/\{(\w+)\}/g,(o,r)=>{const s=t[r];return s===void 0?o:s}),n}function wr(e){const t=e.trim(),n=/^\{\{([\s\S]*)\}\}$/.exec(t);return n?n[1].trim():t}function $d(e){const t=e.trim();return/^\{\{[\s\S]*\}\}$/.test(t)?t:`{{ ${t} }}`}function Ed(e,t){const n={};for(const[r,s]of Object.entries(t))n[r]=typeof s=="string"?wr(s):s;const o=qm(e.expr,n);return $d(o)}function Gm(e,t){if(typeof e!="string")return null;const n=Id(wr(e));for(const o of t){const r=Ym(n,o.expr,o.params);if(r)return{recipeId:o.id,params:r}}return null}function Id(e){return e.replace(/\s+/g," ").trim()}function Ad(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ym(e,t,n){const o=[],r=new Set;let s="";const a=/\{(\w+)(\*?)\}(\s*\?\?\s*)?/g;let l=0,d;const c=Id(t);for(;(d=a.exec(c))!==null;){const g=c.slice(l,d.index);s+=Ad(g).replace(/\\ /g,"\\s*");const m=d[2]==="*",h=!!d[3];m?(r.add(d[1]),s+="(.*?)",h&&(s+="(?:\\s*\\?\\?\\s*)?")):(s+="(.+?)",h&&(s+="\\s*\\?\\?\\s*")),o.push(d[1]),l=a.lastIndex}s+=Ad(c.slice(l)).replace(/\\ /g,"\\s*");let p;try{p=new RegExp(`^${s}$`)}catch{return null}const f=p.exec(e);if(!f)return null;const b={};if(o.forEach((g,m)=>{let h=(f[m+1]??"").trim();r.has(g)&&(h=h.split(/\s*\?\?\s*/).map(v=>v.trim()).filter(Boolean).join(", ")),b[g]=h}),n.length>0){const g=new Set(n.map(m=>m.key));for(const m of Object.keys(b))g.has(m)||delete b[m]}return b}function Xm(e){const t=`x.${e.field}`,n=Jm(e.value);switch(e.cmp){case"=":return`${t} === ${n}`;case"!=":return`${t} !== ${n}`;case">":return`${t} > ${n}`;case"<":return`${t} < ${n}`;case">=":return`${t} >= ${n}`;case"<=":return`${t} <= ${n}`;case"includes":return`(${t} ?? []).includes(${n})`;default:return`${t} === ${n}`}}function Jm(e){const t=e.trim();return t==="true"||t==="false"||t!==""&&!Number.isNaN(Number(t))||/^['"].*['"]$/.test(t)||/[.([{]/.test(t)?t:`'${t.replace(/'/g,"\\'")}'`}function is(e){return!e||e.length===0?"true":e.map(Xm).join(" && ")}function Zm(e){const n=`(${(e.source??"").trim()||"[]"} ?? [])`;let o;switch(e.op){case"count":o=`${n}.filter(x => ${is(e.conditions)}).length`;break;case"sum":{const r=(e.sumField??"").trim()||"value";o=`${n}.filter(x => ${is(e.conditions)}).reduce((s, x) => s + (x.${r} ?? 0), 0)`;break}case"filter":o=`${n}.filter(x => ${is(e.conditions)})`;break;case"toOptions":{const r=(e.valueField??"").trim()||"value",s=(e.labelField??"").trim()||"label";o=`${n}.map(x => ({ value: x.${r}, label: x.${s} }))`;break}case"nth":{const r=(e.index??"").trim()||"0",s=(e.prop??"").trim();o=`${n}[${r}]${s?`?.${s}`:""}`;break}case"firstOf":{const r=(e.candidates??[]).map(l=>l.trim()).filter(Boolean),s=r.length>0?r.join(" ?? "):"''",a=(e.fallback??"").trim();o=a?`${s} ?? '${a.replace(/'/g,"\\'")}'`:s;break}case"literal":{const r=e.literalKind??"string",s=(e.literalValue??"").trim();r==="number"?o=s===""?"0":s:r==="boolean"?o=s==="true"?"true":"false":o=`'${s.replace(/'/g,"\\'")}'`;break}default:o="[]"}return $d(o)}function Qm(e){if(typeof e!="string")return null;const t=wr(e).trim();let n=/^\((.+?)\s*\?\?\s*\[\]\)\.filter\(x => (.+)\)\.length$/.exec(t);return n?{key:"",op:"count",source:n[1].trim(),conditions:ss(n[2])}:(n=/^\((.+?)\s*\?\?\s*\[\]\)\.filter\(x => (.+)\)\.reduce\(\(s, x\) => s \+ \(x\.(\w+(?:\.\w+)*) \?\? 0\), 0\)$/.exec(t),n?{key:"",op:"sum",source:n[1].trim(),conditions:ss(n[2]),sumField:n[3]}:(n=/^\((.+?)\s*\?\?\s*\[\]\)\.filter\(x => (.+)\)$/.exec(t),n?{key:"",op:"filter",source:n[1].trim(),conditions:ss(n[2])}:(n=/^\((.+?)\s*\?\?\s*\[\]\)\.map\(x => \(\{ value: x\.(\w+(?:\.\w+)*), label: x\.(\w+(?:\.\w+)*) \}\)\)$/.exec(t),n?{key:"",op:"toOptions",source:n[1].trim(),valueField:n[2],labelField:n[3]}:(n=/^\((.+?)\s*\?\?\s*\[\]\)\[(.+?)\](?:\?\.(\w+(?:\.\w+)*))?$/.exec(t),n?{key:"",op:"nth",source:n[1].trim(),index:n[2].trim(),prop:n[3]}:null))))}function ss(e){const t=e.trim();if(t==="true")return[];const n=[];for(const o of Rm(t)){const r=ev(o.trim());r&&n.push(r)}return n}function Rm(e){const t=[];let n=0,o=0;for(let r=0;r=|<=|>|<)\s*(.+)$/.exec(e),t){const n={"===":"=","!==":"!=",">":">","<":"<",">=":">=","<=":"<="};return{field:t[1],cmp:n[t[2]]??"=",value:Td(t[3])}}return null}function Td(e){const t=e.trim(),n=/^'(.*)'$/.exec(t)||/^"(.*)"$/.exec(t);return n?n[1]:t}function Dd(e,t){const n=Gm(e,t);if(n)return{kind:"preset",recipeId:n.recipeId,params:n.params};const o=Qm(e);return o?{kind:"custom",model:o}:{kind:"advanced"}}function tv(e){if(e==null)return"null";if(Array.isArray(e))return"list";switch(typeof e){case"number":return"number";case"boolean":return"boolean";case"string":return"string";default:return"object"}}function zd(e,t){if(typeof e!="string"||e.trim()==="")return{ok:!1,reason:"empty"};const n=wr(e);try{const o=Vm(n)?Sd.evaluatePipeExpression(n,t??{},{skipCache:!0}):Sd.evaluateExpression(n,t??{},{skipCache:!0});return{ok:!0,value:o,type:tv(o)}}catch(o){return{ok:!1,reason:o instanceof Error?o.message:String(o)}}}function Nd(e,t){const n=Array.isArray(e?.data_sources)?e.data_sources:[],o=[];for(const r of n){const s=r?.id;if(typeof s!="string"||s.length===0)continue;const{value:a}=rs(r,t?.sampleData),l=typeof r.label_key=="string"?r.label_key:void 0;o.push({id:s,sample:a,labelKey:l})}return o}function Md(e,t){const n=[];t?.sampleGlobal&&typeof t.sampleGlobal=="object"&&n.push({scope:"_global",tree:t.sampleGlobal});const o={},r={},s={},a=(l,d)=>{if(!(!d||typeof d!="object"||Array.isArray(d)))for(const[c,p]of Object.entries(d))if(p&&typeof p=="object"&&!Array.isArray(p)){const f=l[c]&&typeof l[c]=="object"&&!Array.isArray(l[c])?l[c]:l[c]={};a(f,p)}else c in l||(l[c]=p)};for(const l of t?.states?.groups??[])for(const d of l.items??[]){const c=d.initialState;c?.local&&a(o,c.local),c?.query&&a(r,c.query),c?.route&&a(s,c.route)}return Object.keys(o).length&&n.push({scope:"_local",tree:o}),Object.keys(r).length&&n.push({scope:"query",tree:r}),Object.keys(s).length&&n.push({scope:"route",tree:s}),e?.computed&&typeof e.computed=="object"&&!Array.isArray(e.computed)&&n.push({scope:"_computed",tree:e.computed}),n}function Ld(e,t){const n={};for(const r of t)r.scope!=="_computed"&&(n[r.scope]=r.tree);const o={};for(const[r,s]of Object.entries(e)){if(typeof s!="string"){o[r]=s;continue}const a=zd(s,n);o[r]=a.ok?a.value:s}return o}function nv(e,t){const n=Nd(e,t),o=Md(e,t),r={};for(const s of n)s.sample!==void 0&&(r[s.id]=s.sample);for(const s of o)s.scope==="_computed"?r[s.scope]=Ld(s.tree,o):r[s.scope]=s.tree;return r}function Pd(e){const{raw:t,spec:n,evaluateComputed:o}=e;return u.useMemo(()=>{const r=Nd(t,n),s=Md(t,n);if(o){const a=s.findIndex(l=>l.scope==="_computed");if(a>=0){const l=Ld(s[a].tree,s);s[a]={scope:"_computed",tree:l}}}return Ki({dataSources:r,states:s,spec:n??void 0})},[t,n,o])}function ov(e){const{raw:t,spec:n,pageType:o}=e;return u.useMemo(()=>{const r=Array.isArray(t?.data_sources)?t.data_sources:[],s=[];for(const d of r){const c=d?.id;if(typeof c!="string"||c.length===0)continue;const{value:p}=rs(d,n?.sampleData),f=typeof d.label_key=="string"?d.label_key:void 0;s.push({id:c,sample:p,labelKey:f})}const a=[];n?.sampleGlobal&&typeof n.sampleGlobal=="object"&&a.push({scope:"_global",tree:n.sampleGlobal}),t?.computed&&typeof t.computed=="object"&&!Array.isArray(t.computed)&&a.push({scope:"_computed",tree:t.computed});const l=Ki({dataSources:s,states:a,spec:n??void 0});if(typeof o=="string"&&o!=="")for(const d of["title","description"])l.push({expression:`{{_seo.${o}.${d}}}`,source:"_seo",sourceId:"_seo",path:`${o}.${d}`,shape:"scalar",preview:""});return l},[t,n,o])}function Od(e,t){const n=[],o=new Set,r=s=>{for(const a of s??[]){if(a.kind==="route"&&!a.isRedirect&&typeof a.path=="string"&&a.path.startsWith("/")&&!o.has(a.path)){o.add(a.path);const l=a.label.startsWith("$t:")?a.label.slice(3):a.label,d=a.label.startsWith("$t:")?t(l):l,c=d&&d!==l&&!d.startsWith("$t:")?d:"";n.push({value:a.path,label:c?`${c} (${a.path})`:a.path})}r(a.children)}};return r(e),n}function Bd(e){const t=Array.isArray(e?.data_sources)?e.data_sources:[],n=[];for(const o of t){const r=o?.id;typeof r=="string"&&r.length>0&&n.push({value:r,label:r})}return n}function as(e,t){const n=typeof e.id=="string"?e.id:"",o=typeof e.label_key=="string"?e.label_key:"";if(!o)return null;const r=o.startsWith("$t:")?o.slice(3):o,s=t(r);return s&&s!==r&&!s.startsWith("$t:")&&s!==n?s:null}function ls(e,t){const n=e.__source;if(!n||typeof n!="object"||Array.isArray(n))return null;const o=n;if(o.kind!=="extension")return null;const r=o.extensionSourceType==="plugin"?t("layout_editor.data_sources.source.plugin"):t("layout_editor.data_sources.source.module"),s=typeof o.extensionIdentifier=="string"?o.extensionIdentifier:"",a=typeof o.extensionName=="string"?o.extensionName:"",l=a&&a!==s?`${a} (${s})`:s;return l?`${r}: ${l}`:r}function rv(e,t,n){const o=Array.isArray(e?.data_sources)?e.data_sources:[],r=[],s=new Set;for(const a of o){const l=a?.id;typeof l!="string"||l.length===0||s.has(l)||(s.add(l),r.push({id:l,friendly:as(a,t),source:ls(a,n)}))}return r}function Wd(e){const t=e?.states?.groups??[],n=new Set;for(const o of t)for(const r of o.items??[]){for(const s of Object.keys(r.initialState?.local??{}))n.add(s);for(const s of Object.keys(r.initialState?.global??{}))n.add(s)}return Array.from(n).map(o=>({value:o,label:o}))}function iv(e,t){const n=Array.isArray(e?.modals)?e.modals:[],o=[],r=new Set;for(const s of n){const a=s?.id;typeof a!="string"||a.length===0||r.has(a)||(r.add(a),o.push({value:a,label:sv(s,a,t)}))}return o}function sv(e,t,n){const r=e?.meta?.editor_label;if(typeof r=="string"&&r.length>0)return jd(r,n);const s=e?.title;return typeof s=="string"&&s.length>0?jd(s,n):t}function jd(e,t){if(e.startsWith("$t:")){const n=e.slice(3),o=t?t(n):n;return o&&o!==n?o:n}return e}const Hd=mo("ActionRecipeEngine"),av={api:"apiCall",nav:"navigate",showToast:"toast",setLocalState:"setState"},lv=new Set(["comment"]);function ko(e){if(!e||typeof e!="object")return[];const t=[];for(const[n,o]of Object.entries(e)){if(lv.has(n)||!o||typeof o!="object")continue;const r=o,s=r.build&&typeof r.build=="object"?r.build:typeof r.handler=="string"?{handler:r.handler}:void 0;!s||typeof s.handler!="string"||s.handler.length===0||t.push({id:n,label:typeof r.label=="string"?r.label:void 0,params:Array.isArray(r.params)?r.params:[],build:s})}return t}function on(e){const t=/^\{\{\s*([\w.]+)\s*\}\}$/.exec(e);return t?t[1]:null}const kr="...";function dv(e,t){return e.replace(/\{\{\s*([\w.]+)\s*\}\}/g,(n,o)=>{const r=t[o];return r==null?"":String(r)})}function ds(e,t){if(typeof e=="string"){const n=on(e);return n!==null?n in t?t[n]:void 0:e.includes("{{")?dv(e,t):e}if(Array.isArray(e))return e.map(n=>ds(n,t)).filter(n=>n!==void 0);if(e&&typeof e=="object"){const n={};for(const[o,r]of Object.entries(e)){if(o===kr&&typeof r=="string"){const d=on(r),c=d!==null?t[d]:void 0;if(c&&typeof c=="object"&&!Array.isArray(c))for(const[p,f]of Object.entries(c))f===void 0||p===""||(n[p]=f);continue}const s=ds(r,t);if(s===void 0||Array.isArray(s)&&s.length===0&&(o==="onSuccess"||o==="onError"))continue;const a=on(o),l=a!==null?a in t?String(t[a]):null:o;l===null||l===""||s&&typeof s=="object"&&!Array.isArray(s)&&Object.keys(s).length===0||(n[l]=s)}return n}return e}function cv(e){const t=e.handler;if(typeof t!="string")return e;const n=av[t];if(n)return Hd.warn(`action recipe used forbidden handler "${t}" — corrected to "${n}" (core handler rules)`),{...e,handler:n};if(t==="apiCall"||t==="navigate"){const o=e.params;if(o&&typeof o=="object")for(const r of["target","onSuccess","onError"])r in o&&Hd.warn(`action recipe build placed "${r}" inside params for handler "${t}" — should be top-level (core handler rules)`)}return e}function Sr(e,t){const n=ds(e.build,t);if(typeof n.handler!="string"&&e.build.handler.includes("{{")&&(n.handler=e.build.handler),e.build.handler.includes("{{")){const o=new Set(e.params.filter(r=>r.required).map(r=>r.key));o.size>0&&Fd(e.build,n,o)}return cv(n)}function Fd(e,t,n){if(!e||typeof e!="object"||Array.isArray(e)||!t||typeof t!="object"||Array.isArray(t))return;const o=e,r=t;for(const[s,a]of Object.entries(o))if(s!=="handler"){if(typeof a=="string"){const l=on(a);l!==null&&n.has(l)&&!(s in r)&&(r[s]=a)}else if(a&&typeof a=="object"){if(!(s in r)||typeof r[s]!="object"||r[s]===null)if(JSON.stringify(a).includes("{{"))r[s]={};else continue;Fd(a,r[s],n)}}}function uv(e,t){if(!e||typeof e!="object")return null;const n=e.handler;if(typeof n!="string")return null;let o=null,r=-1;for(const s of t){const a=s.build.handler.includes("{{");if(!a&&s.build.handler!==n||a&&!pv(s.build,e))continue;const l=fv(s.build,e);if(l===null)continue;const d=Object.keys(l).length;d>r&&(r=d,o={recipeId:s.id,values:l})}return o}function pv(e,t){if(typeof t.handler=="string"&&t.handler===e.handler)return!0;const n=e.params;if(!n||typeof n!="object")return!1;const o=t.params;if(!o||typeof o!="object")return!1;const r=o,s=Object.entries(n).filter(([,a])=>typeof a=="string"&&on(a)!==null);return s.length===0?!1:s.every(([a])=>a in r)}function fv(e,t){const n={},o=(r,s)=>{if(typeof r=="string"){const a=on(r);return a!==null?(n[a]=s,!0):r.includes("{{")?typeof s=="string":r===s}if(Array.isArray(r))return Array.isArray(s);if(r&&typeof r=="object"){if(!s||typeof s!="object"||Array.isArray(s))return!1;const a=s,l=r[kr],d=typeof l=="string"?on(l):null,c=new Set(Object.keys(r).filter(p=>p!==kr));for(const[p,f]of Object.entries(r))if(p!==kr){if(typeof f=="string"&&on(f)!==null){const b=on(f);p in a&&(n[b]=a[p]);continue}if(!(p in a)){if(p==="onSuccess"||p==="onError"||p==="params"||p==="identity_target")continue;return!1}if(!o(f,a[p]))return!1}if(d!==null){const p={};for(const[f,b]of Object.entries(a))c.has(f)||(p[f]=b);Object.keys(p).length>0&&(n[d]=p)}return!0}return r===s};return o(e,t)?n:null}function Yn(e,t){const n=typeof e?.handler=="string"?e.handler:"",o=uv(e,t);return o?{kind:"preset",recipeId:o.recipeId,values:o.values,handler:n}:{kind:"advanced",handler:n}}function Kd(e,t,n){const o=e?.label,r=o?n?n(o):o:"",s=[],a=e?.params??[];for(const l of a){if(l.advanced||l.widget==="action-list")continue;const d=t[l.key];if(d==null||d==="")continue;const c=gv(d);if(c!==""&&(s.push(c),s.length>=2))break}return s.length===0?r:`${r} (${s.join(", ")})`}function gv(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`[${e.length}]`:e&&typeof e=="object"?"{…}":""}function Vd(e,t){const n={...e};return typeof t=="string"&&t.trim().length>0?n.if=t.trim():delete n.if,n}function cs(e){const t=e?.if;return typeof t=="string"&&t.trim().length>0?t:null}const hv=/^\s*\$t:(custom\.[a-zA-Z0-9._-]+)\s*$/,yv=/^\s*\$t:([a-zA-Z0-9._-]+)\s*$/,bv=/\{\{.*?\}\}/;function Ud(e,t){const n=typeof e=="string"?e:"",o=hv.exec(n);if(o){const a=o[1],l=t?t(a):"";return{customKey:a,binding:!1,paramKey:!1,displayValue:l}}const r=vt(n);if(r&&r.key.startsWith("custom.")){const a=t?t(r.key):"";return{customKey:r.key,binding:!1,paramKey:!0,displayValue:a}}if(bv.test(n))return{customKey:null,binding:!0,paramKey:!1,displayValue:n};const s=yv.exec(n);if(s){const a=s[1],l=t?t(a):"";return{customKey:null,binding:!1,paramKey:!1,displayValue:l&&l!==a?l:""}}return{customKey:null,binding:!1,paramKey:!1,displayValue:n}}function mv(){const{state:e}=Qe(),t=e.templateIdentifier,n=e.locale,o=e.selectedRoute?.layoutName??null,r=u.useCallback(l=>{try{const c=Pt.getInstance().translate(l,{templateId:t,locale:n});return c&&c!==l?c:""}catch{return""}},[t,n]),s=u.useCallback(l=>Ud(l,r),[r]),a=u.useCallback(async(l,d)=>{const c=Ud(l,r);if(c.binding)return{kind:"blocked"};if(c.customKey){if(d===c.displayValue)return{kind:"noop",customKey:c.customKey};const b=await vr(t,c.customKey,n,d);return b.kind==="error"?{kind:"error",message:b.message}:(await tn(t,n),{kind:"updated",customKey:c.customKey})}const p=await qn(t,o,n,d);if(p.kind==="error"||!p.resource)return{kind:"error",message:p.message};const f=p.resource.translation_key;return await tn(t,n),{kind:"created",customKey:f,token:`$t:${f}`}},[t,n,o,r]);return{locale:n,templateIdentifier:t,translate:r,classify:s,commitText:a}}async function us(e,t,n,o,r,s,a,l,d,c){const p=c?Zi(o,c):null,f=!!(p&&p.keyifiable),b=d?d(o):o,g=f?p.chipValue:Rl(b),h=`p${f?p.bindings.length:fr(b).length}`,v=Math.max(0,Math.min(r,g.length)),y=Ul(g,v,h),_=gr(y).replace(/\{\{?p\d+\}?\}/g," ").replace(/\s+/g," ").trim(),w=_.length>0?_:y,k=await qn(e,t,n,w);if(k.kind==="error"||!k.resource)return{kind:"error",message:k.message};const x=k.resource.translation_key,$=An(y),S=k.resource.values??{},C={[n]:y};for(const N of Object.keys(S)){if(N===n)continue;let D=S[N]??"";for(const B of $)D=Xi(D,B);C[N]=D}wo(e,x,C);const T=En(s,a,l);return{kind:"ok",text:`${f?Zl(`$t:${x}`,p):Ql(`$t:${x}`,b)}|${h}=${T}`,key:x}}async function Cr(e,t,n,o,r,s,a){let l=vt(n);if(!l&&typeof n=="string"){const h=/^\s*\$t:(custom\.[A-Za-z0-9._-]+)\s*$/.exec(n);h&&(l={key:h[1],params:[]})}if(!l)return{kind:"error",message:"not a param key"};if(!l.key.startsWith("custom."))return{kind:"error",message:"not a custom param key"};const d=wb(l.params.map(h=>h.name)),c=En(r,s,a),p=`${n.trim()}|${d}=${c}`,f=await cn(e,l.key),b=Gb(l.key)??{},g=new Set([...Object.keys(f?.values??{}),...Object.keys(b),t]);if(g.size===0)return{kind:"error",message:"custom key not found"};const m={};for(const h of g){const v=It(l.key,h)??f?.values?.[h]??"";m[h]=h===t?Ul(v,o,d):Xi(v,d)}return wo(e,l.key,m),{kind:"ok",text:p,paramName:d}}async function So(e,t,n,o){return _r(e,t,n,o),{kind:"ok"}}async function vv(e,t,n){const o=await cn(e,t);if(!o)return{kind:"error",message:"custom key not found"};const r={};for(const[s,a]of Object.entries(o.values??{})){const l=It(t,s)??a;r[s]=n(l)}wo(e,t,r);try{const s=Pt.getInstance();for(const[a,l]of Object.entries(r))s.setTranslationValue(e,a,t,l)}catch{}return{kind:"ok"}}function qd(e,t,n){return vv(e,t,o=>nd(o,n))}function Gd(e,t){if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:e,locale:t}}))}catch{}}async function $r(e,t,n,o){const r=await qd(e,t,n);return Gd(e,o),r}const _v=/^\s*\$t:(custom\.[a-zA-Z0-9._-]+)\s*$/;function xv(e,t){const n=s=>{const a=[],l=/\{\{?(p\d+)\}?\}/g;let d;for(;(d=l.exec(s))!==null;)a.push(d[1]);return a},o=n(e),r=n(t);return o.length!==r.length?!0:o.some((s,a)=>s!==r[a])}function Yd(e){const t=e.text;if(typeof t!="string")return null;const n=_v.exec(t);if(n)return n[1];const o=vt(t);return o&&o.key.startsWith("custom.")?o.key:null}function ps(e){const t={},n=vt(typeof e=="string"?e:"");for(const o of n?.params??[])t[o.name]=Vt(o.expression);return t}function wv(e){return ps(typeof e.text=="string"?e.text:"")}function Xd({customKey:e,templateIdentifier:t,t:n,paramLabels:o,locales:r,onRemoveParam:s}){const a=r??hd(),l=Ft(),d=o??{},[c,p]=u.useState({status:"idle",values:{}}),[f,b]=u.useState(!1),[g,m]=u.useState(!1),[h,v]=u.useState(null),y=u.useRef({});u.useEffect(()=>{let E=!1;if(!e){p({status:"not_a_key",values:{}});return}return p({status:"loading",values:{}}),(async()=>{const A=await cn(t,e);if(E)return;if(!A){p({status:"error",values:{}});return}const N={...A.values??{}};for(const D of Object.keys(N)){const B=It(e,D);B!==void 0&&(N[D]=B)}for(const D of a){const B=It(e,D);B!==void 0&&(N[D]=B)}y.current={...N},p({status:"loaded",id:A.id,lockVersion:A.lock_version,values:N})})(),()=>{E=!0}},[e,t]),u.useEffect(()=>{if(typeof window>"u"||!e)return;const E=A=>{const N=A.detail;N?.templateIdentifier&&N.templateIdentifier!==t||p(D=>{if(D.status!=="loaded")return D;let B=!1;const M={...D.values};for(const O of Object.keys(M)){const z=It(e,O);z!==void 0&&z!==M[O]&&(M[O]=z,B=!0)}return B?(y.current={...y.current,...M},{...D,values:M}):D})};return window.addEventListener(kt,E),()=>window.removeEventListener(kt,E)},[e,t]);const _=u.useCallback((E,A)=>{p(N=>{const D=N.values[E]??"",B={...N,values:{...N.values,[E]:A}};return e&&xv(D,A)&&(_r(t,e,E,A),y.current={...y.current,[E]:A},l?.markDirty?.(),Gd(t,E)),B})},[e,t,l]),w=u.useCallback(E=>{p(A=>{const N={};for(const[D,B]of Object.entries(A.values))N[D]=nd(B,E);return y.current={...N},{...A,values:N}}),s?.(E)},[s]),k=u.useMemo(()=>[...Object.values(c.values),...Object.values(y.current)].some(A=>An(A).length>0),[c.values]),x=u.useRef(null),$=u.useCallback(()=>{m(!0),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>m(!1),1500)},[]);u.useEffect(()=>()=>{x.current&&clearTimeout(x.current)},[]);const S=u.useCallback(async()=>{if(m(!1),c.status!=="loaded"||c.id===void 0)return;const E=y.current;for(const[N,D]of Object.entries(c.values)){const B=E[N]??"";if(k){const M=An(B);if(M.length===0)continue;const O=An(D);if(!(M.length===O.length&&M.every((H,P)=>H===O[P]))){v(n("layout_editor.translation.placeholder_mismatch"));return}continue}if(Yi(B)&&!Tb(B,D)){v(n("layout_editor.translation.token_mismatch"));return}}if(b(!0),v(null),k){wo(t,e??"",c.values),y.current={...c.values},l?.markDirty?.(),Et({op:"translation_field_update",translationKey:e,changedLocales:Object.keys(c.values),timestamp:Date.now()}),await new Promise(N=>setTimeout(N,0)),b(!1),$();return}const A=`/api/admin/templates/${encodeURIComponent(t)}/custom-translations/${c.id}`;try{const N=await fetch(A,{method:"PUT",credentials:"same-origin",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({values:c.values,expected_lock_version:c.lockVersion??0})}),D=await N.json().catch(()=>null);if(N.status===409){v(n("layout_editor.translation.conflict"));return}if(!N.ok){v(D?.message??n("layout_editor.translation.save_failed"));return}const B=typeof D?.data?.lock_version=="number"?D.data.lock_version:(c.lockVersion??0)+1;p(M=>({...M,lockVersion:B})),y.current={...c.values},await tn(t),Et({op:"translation_field_update",translationKey:e,changedLocales:Object.keys(c.values),timestamp:Date.now()}),$()}catch(N){v(N instanceof Error?N.message:n("layout_editor.translation.save_failed"))}finally{b(!1)}},[c,t,e,n]);if(c.status==="not_a_key"||!e)return i.jsx("div",{"data-testid":"g7le-translation-not-a-key",style:fs,children:n("layout_editor.translation.not_a_key")});if(c.status==="loading"||c.status==="idle")return i.jsx("div",{"data-testid":"g7le-translation-loading",style:fs,children:n("layout_editor.translation.loading")});if(c.status==="error")return i.jsx("div",{"data-testid":"g7le-translation-error",style:fs,children:n("layout_editor.translation.load_failed")});const C=new Set([...a,...Object.keys(c.values)]),T=Array.from(C);return i.jsxs("div",{"data-testid":"g7le-translation-field",style:{display:"flex",flexDirection:"column",gap:8},children:[i.jsxs("div",{"data-testid":"g7le-translation-key",style:kv,children:[n("layout_editor.translation.key_label"),": ",i.jsx("code",{style:Sv,children:e})]}),T.map(E=>{const A=c.values[E]??"",N=A.trim().length===0;return i.jsxs("div",{className:"g7le-translation-row","data-testid":`g7le-translation-row-${E}`,style:Cv,children:[i.jsxs("label",{htmlFor:`g7le-translation-input-${E}`,style:{fontSize:12,color:"#475569",minWidth:72,display:"inline-flex",alignItems:"center",gap:4},children:[Gn(E,n),N&&i.jsx("span",{"data-testid":`g7le-translation-missing-${E}`,style:$v,children:n("layout_editor.translation.needs_translation")})]}),k?i.jsx("div",{style:{flex:1},"data-testid":`g7le-translation-chip-${E}`,children:i.jsx(xr,{value:A,onChange:D=>_(E,D),t:n,paramLabels:d,testIdSuffix:E,onRemoveChip:s?w:void 0})}):i.jsx("input",{id:`g7le-translation-input-${E}`,type:"text","data-testid":`g7le-translation-input-${E}`,value:A,placeholder:N?n("layout_editor.translation.needs_translation"):"",onChange:D=>_(E,D.currentTarget.value),onBlur:S,style:{flex:1,padding:"4px 8px",fontSize:13,border:"1px solid #cbd5e1",borderRadius:4,color:N?"#94a3b8":"#0f172a"}})]},E)}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("button",{type:"button","data-testid":"g7le-translation-save",disabled:f,onClick:S,style:Ev,children:n(f?"layout_editor.translation.saving":"layout_editor.translation.save")}),g&&!f&&i.jsxs("span",{"data-testid":"g7le-translation-saved",style:{fontSize:11,color:"#16a34a",display:"inline-flex",alignItems:"center",gap:4},children:["✓ ",n("layout_editor.translation.saved")]}),h&&i.jsx("span",{"data-testid":"g7le-translation-save-error",style:{fontSize:11,color:"#dc2626"},children:h})]})]})}const fs={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},kv={fontSize:12,color:"#475569"},Sv={fontSize:11,background:"#f1f5f9",padding:"1px 4px",borderRadius:3,color:"#0f172a"},Cv={display:"flex",alignItems:"center",gap:8},$v={fontSize:10,color:"#b45309",background:"#fef3c7",padding:"0 4px",borderRadius:3},Ev={padding:"6px 12px",fontSize:12,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"};function Xn({anchorRef:e,open:t,onClose:n,children:o,placement:r="bottom",minWidth:s=240,maxWidth:a=360,margin:l=8,testid:d}){const c=u.useRef(null),[p,f]=u.useState(null),b=u.useCallback(()=>{const m=e.current,h=c.current;if(!m||!h)return;const v=m.getBoundingClientRect(),y=window.innerWidth,_=window.innerHeight,w=h.getBoundingClientRect(),k=Math.min(Math.max(w.width,s),a),x=w.height;let $=v.left;$+k+l>y&&($=v.right-k),$=Math.min(Math.max($,l),y-k-l);const S=_-v.bottom-l,C=v.top-l;let T,E;const A=r==="bottom",N=S>=Math.min(x,160),D=C>=Math.min(x,160);A&&N||A&&!D?(T=v.bottom+4,E=S):!A&&D||D?(T=v.top-4-Math.min(x,C),E=C):S>=C?(T=v.bottom+4,E=S):(T=l,E=C),f({left:$,top:T,maxHeight:Math.max(E,120)})},[e,r,s,a,l]);if(u.useLayoutEffect(()=>{if(!t){f(null);return}b()},[t,b]),u.useEffect(()=>{if(!t)return;const m=()=>b();window.addEventListener("resize",m),window.addEventListener("scroll",m,!0);const h=y=>{const _=c.current,w=e.current,k=y.target;_?.contains(k)||w?.contains(k)||n()},v=y=>{y.key==="Escape"&&n()};return document.addEventListener("pointerdown",h,!0),document.addEventListener("keydown",v),()=>{window.removeEventListener("resize",m),window.removeEventListener("scroll",m,!0),document.removeEventListener("pointerdown",h,!0),document.removeEventListener("keydown",v)}},[t,b,n,e]),!t)return null;const g={...Iv,minWidth:s,maxWidth:`min(${a}px, calc(100vw - ${l*2}px))`,...p?{left:p.left,top:p.top,maxHeight:p.maxHeight,visibility:"visible"}:{left:-9999,top:-9999,visibility:"hidden"}};return i.jsx("div",{ref:c,"data-testid":d,style:g,role:"dialog",children:o})}const Iv={position:"fixed",zIndex:1e3,background:"#fff",border:"1px solid #cbd5e1",borderRadius:8,boxShadow:"0 4px 16px rgba(0,0,0,0.14)",padding:6,overflowY:"auto",boxSizing:"border-box"};function Jd(e,t,n){if(!t)return n;const o=e(t);return!o||o===t||o.startsWith("$t:")?n:o}function $t({candidates:e,t,onSelect:n,testIdSuffix:o,defaultOpen:r=!1,floating:s=!0}){const[a,l]=u.useState(r),[d,c]=u.useState(""),p=u.useRef(null),f=u.useMemo(()=>Ui(e,"scalar").map(h=>({...h,resolvedLabel:Jd(t,h.labelKey,h.path||h.sourceId)})),[e,t]),b=u.useMemo(()=>qi(f,d),[f,d]),g=i.jsxs(i.Fragment,{children:[i.jsx("input",{type:"text",autoFocus:!0,"data-testid":`g7le-inline-binding-search-input-${o}`,value:d,placeholder:t("layout_editor.inline_binding.search_placeholder"),onChange:m=>c(m.target.value),style:zv}),i.jsx("div",{style:Nv,children:b.length===0?i.jsx("div",{style:Mv,children:t("layout_editor.inline_binding.no_results")}):b.map(m=>i.jsxs("button",{type:"button","data-testid":`g7le-inline-binding-candidate-${m.expression}`,onClick:()=>{n(m),l(!1),c("")},style:Lv,children:[i.jsxs("span",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start"},children:[i.jsx("span",{style:{fontSize:12},children:m.resolvedLabel}),i.jsxs("span",{style:Pv,children:[Jd(t,m.groupLabelKey,m.sourceId)," · ",m.path||m.sourceId]})]}),i.jsx("span",{style:Ov,children:m.preview})]},m.expression))})]});return i.jsxs("div",{style:s?Dv:{marginTop:4},children:[i.jsx("button",{ref:p,type:"button","data-testid":`g7le-inline-binding-search-toggle-${o}`,onClick:()=>l(m=>!m),title:t("layout_editor.inline_binding.search"),"aria-label":t("layout_editor.inline_binding.search"),"aria-expanded":a,style:Av,children:"🔍"}),s?i.jsx(Xn,{anchorRef:p,open:a,onClose:()=>l(!1),testid:`g7le-inline-binding-picker-${o}`,children:g}):a&&i.jsx("div",{"data-testid":`g7le-inline-binding-picker-${o}`,style:Tv,children:g})]})}const Av={fontSize:13,lineHeight:1,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#334155",padding:"4px 8px",cursor:"pointer",textAlign:"center",whiteSpace:"nowrap"},Tv={marginTop:4,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",padding:6},Dv={display:"inline-block"},zv={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},Nv={marginTop:4,maxHeight:200,overflowY:"auto",display:"flex",flexDirection:"column",gap:2},Mv={fontSize:11,color:"#94a3b8",padding:"8px 0",textAlign:"center"},Lv={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,border:"none",background:"transparent",cursor:"pointer",padding:"6px 8px",borderRadius:4,textAlign:"left"},Pv={fontSize:10,color:"#94a3b8"},Ov={fontSize:10,color:"#64748b",fontFamily:"monospace",whiteSpace:"nowrap"},Bv=["$localized"];function Jn(e){const t=e.trim();if(!t.startsWith("{{")||!t.endsWith("}}")||t.length<4)return null;let n=0;for(let o=0;oun(n).decomposed)}function Co(e,t,n,o){switch(e.kind){case"leaf":Qd(e.text,t,n,o);return;case"conditional":Co(e.then,t,n,o),o.push({kind:"ellipsis",text:"⋯"});return;case"fallback":Co(e.primary,t,n,o);return;case"concat":e.parts.forEach(r=>Co(r,t,n,o));return;default:o.push({kind:"text",text:e.source});return}}function Qd(e,t,n,o){const r=e.trim();if(/^\{\{([\s\S]*)\}\}$/.exec(r)&&!r.slice(2,-2).includes("}}")){o.push({kind:"chip",text:n(r)});return}if(r.startsWith("$t:")){const a=r.slice(3).split("|")[0];o.push({kind:"text",text:t(a)||a});return}for(const a of e.split(/(\{\{(?:[^}]|\}(?!\}))*\}\})/g))a!==""&&(/^\{\{[\s\S]*\}\}$/.test(a)?o.push({kind:"chip",text:n(a)}):o.push({kind:"text",text:a}))}function gs(e,t,n){const o=[];if(typeof e!="string"||e==="")return o;if(Jn(e)===null&&/\{\{/.test(e)){for(const a of e.split(/(\{\{(?:[^}]|\}(?!\}))*\}\})/g))if(!(a===void 0||a===""))if(/^\{\{[\s\S]*\}\}$/.test(a)){const l=un(a);Co(l.node,t,n,o)}else Qd(a,t,n,o);return o}const s=un(e);return Co(s.node,t,n,o),o}function Wv(e){if(typeof e!="string"||e.trim()==="")return"empty";const t=e.trim();if(Jn(t)===null)return"simple";const n=un(e);return n.node.kind==="leaf"?"simple":n.decomposed?"expression":"raw"}function un(e){const t=typeof e=="string"?e:"",n=t.trim();if(n==="")return{node:{kind:"leaf",text:t},decomposed:!1,original:t};const o=Jn(n);if(o===null)return{node:{kind:"leaf",text:t},decomposed:!1,original:t};let r;try{r=Yv(o)}catch{r=null}if(r===null)return{node:{kind:"raw",source:o},decomposed:!1,original:t};if(r.kind==="leaf"||r.kind==="raw")return{node:r,decomposed:!1,original:t};if(r.kind==="fallback"&&r.op==="??"&&jv(r.primary)&&Hv(r.fallback))return{node:{kind:"leaf",text:t},decomposed:!1,original:t};const s=Zn(r,!0);return Rv(o,s)?{node:r,decomposed:!0,original:t}:{node:{kind:"raw",source:o},decomposed:!1,original:t}}function Zn(e,t=!1){const n=ec(e);return t?n:e.kind==="leaf"?e.text:`{{${n}}}`}function $o(e){return Zn({kind:"conditional",condition:{kind:"simple",left:"",op:"truthy",right:""},then:{kind:"leaf",text:typeof e=="string"?e:""},else:{kind:"leaf",text:""}},!1)}function hs(e){return Zn({kind:"fallback",op:"??",primary:{kind:"leaf",text:typeof e=="string"?e:""},fallback:{kind:"leaf",text:""}},!1)}function Eo(e){switch(e.kind){case"leaf":return e.text;case"conditional":return Eo(e.then);case"fallback":return Eo(e.primary);case"concat":return e.parts.map(Eo).join("");default:return e.kind==="raw"?`{{${e.source}}}`:""}}function WM(e){return e}function Er(e){if(typeof e!="string"||e.trim()==="")return"";if(Jn(e)===null&&/\{\{/.test(e)){for(const n of e.split(/(\{\{(?:[^}]|\}(?!\}))*\}\})/g))if(!(n===void 0||n===""))return/^\{\{[\s\S]*\}\}$/.test(n)?Eo(un(n).node):n;return""}return Eo(un(e).node)}function jv(e){if(e.kind!=="leaf")return!1;const t=/^\{\{([\s\S]*)\}\}$/.exec(e.text.trim());return t?Qn(t[1].trim()):!1}function Hv(e){if(e.kind!=="leaf")return!1;const t=e.text.trim();return!(/\{\{/.test(t)||t.startsWith("$t:"))}function Ir(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}function Fv(e){const t=[];let n=0,o=0;const r=e.length;for(;on&&t.push(Ir(e.slice(n,o)));let s=o+2;for(;s=r)break;const a=e.slice(o+2,s).trim();t.push(a),o=s+2,n=o;continue}o++}return nIo(t,"concat")).join(" + ");case"fallback":return`${Io(e.primary,"fallback")} ${e.op} ${Io(e.fallback,"fallback")}`;case"conditional":return`${Vv(e.condition)} ? ${Io(e.then,"conditional")} : ${Io(e.else,"conditional")}`;default:return""}}function Io(e,t){const n=ec(e);return e.kind==="leaf"||e.kind==="raw"?n:e.kind==="conditional"?t==="conditional"?n:`(${n})`:e.kind==="fallback"?t==="concat"?`(${n})`:n:(e.kind==="concat",n)}const qv=["===","!==","??","||","&&","==","!=",">=","<="];function tc(e){const t=[];let n=0;const o=e.length;for(;n=o)throw new Error("unterminated-binding-in-string");d+=e.slice(l,c+2),l=c+2;continue}if(e[l]===a){d+=a,l++;break}if(a==="`"&&e[l]==="$"&&e[l+1]==="{")throw new Error("template-literal-interpolation-unsupported");d+=e[l],l++}if(l>o||d[d.length-1]!==a)throw new Error("unterminated-string");t.push({kind:"string",value:d,start:n,end:l}),n=l;continue}if(r==="{"&&e[n+1]==="{"){let a=n+2;for(;a"||r==="<"){t.push({kind:"op",value:r,start:n,end:n+1}),n++;continue}if(r==="!"){t.push({kind:"op",value:"!",start:n,end:n+1}),n++;continue}if(r==="("){t.push({kind:"lparen",value:"(",start:n,end:n+1}),n++;continue}if(r===")"){t.push({kind:"rparen",value:")",start:n,end:n+1}),n++;continue}if(r==="["){t.push({kind:"lbracket",value:"[",start:n,end:n+1}),n++;continue}if(r==="]"){t.push({kind:"rbracket",value:"]",start:n,end:n+1}),n++;continue}if(r==="."){t.push({kind:"dot",value:".",start:n,end:n+1}),n++;continue}if(/[0-9]/.test(r)){let a=n;for(;a=n)return"";const o=this.toks[t].start,r=this.toks[n-1].end;return this.src.slice(o,r)}parseFallback(){let t=this.parseConcat(),n=this.peek();for(;n&&n.kind==="op"&&(n.value==="??"||n.value==="||");){const o=n.value;this.next();const r=this.parseConcat();t={kind:"fallback",op:o,primary:t,fallback:r},n=this.peek()}return t}parseConcat(){const t=this.parseUnaryOrPrimary(),n=[t];let o=this.peek();for(;o&&o.kind==="op"&&o.value==="+";)this.next(),n.push(this.parseUnaryOrPrimary()),o=this.peek();return n.length===1?t:{kind:"concat",parts:n}}parseUnaryOrPrimary(){return this.parsePrimary()}parsePrimary(){const t=this.peek();if(!t)throw new Error("unexpected-end");if(t.kind==="lparen"){this.next();const n=this.parseTernary(),o=this.next();if(!o||o.kind!=="rparen")throw new Error("expected-rparen");return n}if(t.kind==="string")return this.next(),{kind:"leaf",text:oc(t.value)};if(t.kind==="tkey")return this.next(),{kind:"leaf",text:t.value};if(t.kind==="binding")return this.next(),{kind:"leaf",text:t.value};if(t.kind==="ident"&&Bv.includes(t.value)&&this.toks[this.pos+1]?.kind==="lparen"){const n=this.tryParsePathWrapperCall(t.value);if(n!==null)return n;throw new Error("path-wrapper-non-simple-arg")}if(t.kind==="ident")return{kind:"leaf",text:`{{${this.parsePath()}}}`};if(t.kind==="number")return this.next(),{kind:"leaf",text:t.value};throw new Error(`unparseable-primary:${t.kind}`)}parsePath(){let t="";const n=this.next();if(!n||n.kind!=="ident")throw new Error("expected-ident");for(t+=n.value;;){const o=this.peek();if(!o)break;if(o.kind==="op"&&o.value==="?"&&this.toks[this.pos+1]?.kind==="dot"){this.next(),this.next();const r=this.next();if(!r||r.kind!=="ident")throw new Error("expected-ident-after-optional");t+="?."+r.value;continue}if(o.kind==="dot"){this.next();const r=this.next();if(!r||r.kind!=="ident")throw new Error("expected-ident-after-dot");t+="."+r.value;continue}if(o.kind==="lbracket"){this.next();const r=this.next(),s=this.next();if(!s||s.kind!=="rbracket")throw new Error("expected-rbracket");if(r&&(r.kind==="number"||r.kind==="string")){t+=`[${r.value}]`;continue}throw new Error("non-literal-index")}if(o.kind==="lparen")throw new Error("call-expression");break}return t}tryParsePathWrapperCall(t){const n=this.pos;this.next();const o=this.next();if(!o||o.kind!=="lparen")return this.pos=n,null;let r;try{if(this.peek()?.kind!=="ident")return this.pos=n,null;r=this.parsePath()}catch{return this.pos=n,null}const s=this.next();return!s||s.kind!=="rparen"?(this.pos=n,null):{kind:"leaf",text:`{{${t}(${r})}}`}}}function Yv(e){return new Gv(e).parse()}const Xv=["===","!==","==","!=",">=","<=",">","<"];function Jv(e,t){const n=e.trim();if(n==="")return{kind:"raw",source:n};if(n===Rd)return{kind:"simple",left:"",op:"truthy",right:""};if(n.startsWith("!")){const s=n.slice(1).trim(),a=nc(s);return Qn(a)?{kind:"simple",left:a,op:"falsy",right:""}:{kind:"raw",source:n}}const o=Zv(n);if(o){const{left:s,op:a,right:l}=o,d=s.trim(),c=l.trim();return Qn(d)&&(c==="''"||c==='""')?{kind:"simple",left:d,op:a,right:""}:Qn(d)&&Qv(c)?{kind:"simple",left:d,op:a,right:c}:{kind:"raw",source:n}}const r=nc(n);return Qn(r)?{kind:"simple",left:r,op:"truthy",right:""}:{kind:"raw",source:n}}function Zv(e){let t=0,n=null;for(let o=0;o=o||!/[A-Za-z_$]/.test(t[n]))return!1;for(n++;n=o||!/[A-Za-z_$]/.test(t[n]))return!1;for(n++;n=2&&(t[0]==="'"||t[0]==='"'||t[0]==="`")?t.slice(1,-1).replace(/\\(['"`\\])/g,"$1"):t}function Rv(e,t){try{return Ar(e)===Ar(t)}catch{return!1}}function Ar(e){const t=Jn(e);return t!==null?Ar(t):tc(e).map(o=>{if(o.kind==="string")return`S:${oc(o.value)}`;if(o.kind==="binding"){const r=/^\{\{([\s\S]*)\}\}$/.exec(o.value);return`B:${r?Ar(r[1].trim()):o.value.replace(/\s+/g,"")}`}return o.kind==="tkey"?`S:${o.value}`:o.kind==="op"?`O:${o.value}`:o.kind==="ident"||o.kind==="number"?`I:${o.value}`:o.kind==="dot"?".":o.kind==="lbracket"?"[":o.kind==="rbracket"?"]":o.kind==="lparen"||o.kind==="rparen"?"":`X:${o.value}`}).join("")}function Rn({active:e,testid:t}){return i.jsx("div",{"data-testid":t,"data-active":e?"true":"false","aria-hidden":"true",style:e?t_:e_})}const e_={height:0,margin:0,transition:"height 80ms"},t_={height:3,margin:"1px 0",borderRadius:2,background:"#2563eb",boxShadow:"0 0 0 1px #93c5fd"};function ys(e){const{length:t,onMove:n,canDrag:o,canDropAt:r}=e,[s,a]=u.useState(null),[l,d]=u.useState(null),c=u.useCallback(m=>{o&&!o(m)||(a(m),d(m))},[o]),p=u.useCallback(()=>{a(null),d(null)},[]),f=u.useCallback((m,h)=>{if(s===null)return;const v=h==="before"?m:m+1;if(r&&!r(s,v)){d(null);return}d(v)},[s,r]),b=u.useCallback(()=>{if(s!==null&&l!==null){const m=l>s?l-1:l;m!==s&&(!r||r(s,l))&&n(s,m)}a(null),d(null)},[s,l,n,r]),g=u.useCallback(m=>s!==null&&l===m&&m<=t,[s,l,t]);return{dragIndex:s,dropIndex:l,dragging:s!==null,onDragStart:c,onDragEnd:p,onDragOverItem:f,onDrop:b,isDropTarget:g}}const n_={text:"",expression:"{{false ? '' : ''}}",fallback:"{{'' ?? ''}}",data:""};function rc(e,t){const n=In(e);let o=t;const r=n.map(s=>({id:o++,kind:s.kind==="literal"?"text":"expression",value:s.raw}));return r.length===0&&r.push({id:o++,kind:"text",value:""}),{segs:r,nextSeq:o}}function bs({value:e,onChange:t,t:n,candidates:o,testidPrefix:r="g7le-seg-value",renderLeafInput:s}){const a=u.useRef(0),l=u.useRef(e),d=u.useMemo(()=>{const w=rc(e,a.current);return a.current=w.nextSeq,w.segs},[]),[c,p]=u.useState(d),[f,b]=u.useState(!1);if(e!==l.current){l.current=e;const w=c.map(k=>k.value).join("");if(e!==w){const k=rc(e,a.current);a.current=k.nextSeq,p(k.segs)}}const g=u.useCallback(w=>{p(w);const k=w.map(x=>x.value).join("");l.current=k,t(k)},[t]),m=u.useCallback((w,k)=>{g(c.map(x=>x.id===w?{...x,value:k??""}:x))},[c,g]),h=u.useCallback(w=>{const k=c.filter(x=>x.id!==w);g(k.length>0?k:[{id:a.current++,kind:"text",value:""}])},[c,g]),v=u.useCallback(w=>{g([...c,{id:a.current++,kind:w,value:n_[w]}])},[c,g]),y=u.useCallback((w,k)=>{if(w===k||w<0||k<0||w>=c.length||k>=c.length)return;const x=c.slice(),[$]=x.splice(w,1);x.splice(k,0,$),g(x)},[c,g]),_=ys({length:c.length,onMove:y});return i.jsxs("div",{"data-testid":r,style:i_,children:[i.jsx("div",{style:s_,children:n("layout_editor.value_tree.segmented_hint")}),c.map((w,k)=>i.jsxs(u.Fragment,{children:[i.jsx(Rn,{active:_.isDropTarget(k),testid:`${r}-dropline-${k}`}),i.jsx(r_,{seg:w,index:k,t:n,candidates:o,testidPrefix:r,renderLeafInput:s,onValueChange:x=>m(w.id,x),onRemove:()=>h(w.id),dragging:_.dragIndex===k,onDragStartCard:()=>_.onDragStart(k),onDragEndCard:_.onDragEnd,onDragOverCard:x=>_.onDragOverItem(k,x),onDropCard:_.onDrop})]},w.id)),i.jsx(Rn,{active:_.isDropTarget(c.length),testid:`${r}-dropline-end`}),i.jsxs("div",{style:p_,"data-testid":`${r}-add-row`,children:[i.jsxs("button",{type:"button","data-testid":`${r}-add-text`,onClick:()=>v("text"),style:Tr,children:["+ ",n("layout_editor.value_tree.segment.text")]}),i.jsxs("button",{type:"button","data-testid":`${r}-add-expression`,onClick:()=>v("expression"),style:Tr,children:["+ ",n("layout_editor.value_tree.segment.expression")]}),i.jsxs("button",{type:"button","data-testid":`${r}-add-fallback`,onClick:()=>v("fallback"),style:Tr,children:["+ ",n("layout_editor.value_tree.segment.fallback")]}),i.jsxs("button",{type:"button","data-testid":`${r}-add-data`,onClick:()=>v("data"),style:Tr,children:["+ ",n("layout_editor.value_tree.segment.data")]})]}),i.jsxs("div",{style:h_,children:[i.jsxs("button",{type:"button","data-testid":`${r}-source-toggle`,"aria-expanded":f,onClick:()=>b(w=>!w),style:y_,children:[""," ",n("layout_editor.value_tree.show_source")," ",f?"▴":"▾"]}),f&&i.jsx("code",{"data-testid":`${r}-source-code`,style:b_,children:c.map(w=>w.value).join("")})]})]})}function o_({t:e,candidates:t,onPick:n,testidPrefix:o}){return!t||t.length===0?i.jsx("div",{"data-testid":`${o}-data-empty`,style:g_,children:e("layout_editor.value_tree.segment.data_no_candidates")}):i.jsxs("div",{"data-testid":`${o}-data-picker`,style:{minWidth:0},children:[i.jsx("div",{style:f_,children:e("layout_editor.value_tree.segment.data_pick_hint")}),i.jsx($t,{candidates:t,t:e,onSelect:r=>{n(En(r.sourceId,r.path,"scalar"))},testIdSuffix:`${o}-data`,defaultOpen:!0,floating:!0})]})}function r_({seg:e,index:t,t:n,candidates:o,testidPrefix:r,renderLeafInput:s,onValueChange:a,onRemove:l,dragging:d,onDragStartCard:c,onDragEndCard:p,onDragOverCard:f,onDropCard:b}){const g=e.kind==="text"?"layout_editor.value_tree.segment.text":e.kind==="data"?"layout_editor.value_tree.segment.data":e.kind==="fallback"?"layout_editor.value_tree.segment.fallback":"layout_editor.value_tree.segment.expression";return i.jsxs("div",{"data-testid":`${r}-card-${t}`,"data-seg-kind":e.kind,style:d?{...ic,opacity:.5}:ic,onDragOver:m=>{m.preventDefault();const h=m.currentTarget.getBoundingClientRect();f(m.clientY{m.preventDefault(),b()},children:[i.jsxs("div",{style:a_,children:[i.jsx("span",{"data-testid":`${r}-drag-${t}`,style:c_,draggable:!0,onDragStart:c,onDragEnd:p,title:n("layout_editor.value_tree.drag_reorder"),"aria-label":n("layout_editor.value_tree.drag_reorder"),role:"button",children:"⠿"}),i.jsx("span",{style:l_,children:n(g)}),i.jsx("button",{type:"button","data-testid":`${r}-remove-${t}`,onClick:l,title:n("layout_editor.value_tree.segment.remove"),"aria-label":n("layout_editor.value_tree.segment.remove"),style:u_,children:"✕"})]}),i.jsx("div",{style:d_,children:e.kind==="data"&&e.value.trim()===""?i.jsx(o_,{t:n,candidates:o,onPick:a,testidPrefix:`${r}-field-${t}`}):s?s({value:e.value,onChange:a,t:n,candidates:o,testidPrefix:`${r}-field-${t}`}):i.jsx(_t,{value:e.value,onChange:a,t:n,candidates:o,testidPrefix:`${r}-field-${t}`,enableExpressionTree:!0,expressionSourceToggle:!1})})]})}const i_={display:"flex",flexDirection:"column",gap:6,width:"100%",minWidth:0},s_={fontSize:11,color:"#64748b"},ic={display:"flex",flexDirection:"column",gap:4,padding:"6px 8px",border:"1px solid #e2e8f0",borderLeft:"3px solid #6366f1",borderRadius:6,background:"#f8fafc",minWidth:0},a_={display:"flex",alignItems:"center",gap:6,minWidth:0},l_={fontSize:10,fontWeight:600,color:"#6366f1",flex:1,minWidth:0},d_={minWidth:0},c_={color:"#94a3b8",cursor:"grab",fontSize:14,userSelect:"none"},u_={border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12,padding:2,flexShrink:0},p_={display:"flex",flexWrap:"wrap",gap:6,marginTop:2},f_={fontSize:11,color:"#64748b",marginBottom:2},g_={fontSize:11,color:"#94a3b8",padding:"4px 0"},Tr={padding:"4px 10px",fontSize:11,border:"1px dashed #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},h_={display:"flex",flexDirection:"column",gap:4,marginTop:2},y_={alignSelf:"flex-start",padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",fontFamily:"monospace"},b_={fontSize:11,background:"#0f172a",color:"#e2e8f0",padding:"6px 8px",borderRadius:4,wordBreak:"break-all",fontFamily:"monospace"},m_=[{value:"truthy",labelKey:"layout_editor.value_tree.cond.op_truthy"},{value:"falsy",labelKey:"layout_editor.value_tree.cond.op_falsy"},{value:"===",labelKey:"layout_editor.value_tree.cond.op_eq"},{value:"!==",labelKey:"layout_editor.value_tree.cond.op_neq"},{value:">",labelKey:"layout_editor.value_tree.cond.op_gt"},{value:"<",labelKey:"layout_editor.value_tree.cond.op_lt"},{value:">=",labelKey:"layout_editor.value_tree.cond.op_gte"},{value:"<=",labelKey:"layout_editor.value_tree.cond.op_lte"}];function sc({node:e,onChange:t,t:n,candidates:o,testidPrefix:r="g7le-value-tree",depth:s=0,showSourceToggle:a=!0,renderLeafInput:l}){const[d,c]=u.useState(!1),p=s===0,f=i.jsx(eo,{node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:l});return p?a?i.jsxs("div",{"data-testid":r,style:lc,children:[f,i.jsxs("div",{style:B_,children:[i.jsxs("button",{type:"button","data-testid":`${r}-source-toggle`,"aria-expanded":d,onClick:()=>c(b=>!b),style:W_,children:[""," ",n("layout_editor.value_tree.show_source")," ",d?"▴":"▾"]}),d&&i.jsx("code",{"data-testid":`${r}-source-code`,style:j_,children:Zn(e,!1)})]})]}):i.jsx("div",{"data-testid":r,style:lc,children:f}):f}function eo({node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a}){switch(e.kind){case"leaf":return i.jsx(bs,{value:e.text,onChange:l=>t({kind:"leaf",text:l}),t:n,candidates:o,testidPrefix:`${r}-leaf`,renderLeafInput:a});case"conditional":return i.jsx(v_,{node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a});case"fallback":return i.jsx(__,{node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a});case"concat":return i.jsx(w_,{node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a});default:return i.jsxs("div",{"data-testid":`${r}-raw`,style:H_,children:[i.jsx("code",{style:uc,children:e.source??""}),i.jsxs("span",{style:pc,children:["🔒 ",n("layout_editor.value_tree.raw_code_only")]})]})}}function v_({node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a}){const l=u.useCallback(p=>t({...e,condition:p}),[e,t]),d=u.useCallback(p=>t({...e,then:p}),[e,t]),c=u.useCallback(p=>t({...e,else:p}),[e,t]);return i.jsxs("div",{"data-testid":`${r}-conditional`,style:ms(s),children:[i.jsx(k_,{condition:e.condition,onChange:l,t:n,candidates:o,testidPrefix:r}),i.jsx(Dr,{label:n("layout_editor.value_tree.cond.when_true"),testid:`${r}-then`,children:i.jsx(eo,{node:e.then,onChange:d,t:n,candidates:o,testidPrefix:`${r}-then`,depth:s+1,renderLeafInput:a})}),i.jsx(Dr,{label:n("layout_editor.value_tree.cond.when_false"),testid:`${r}-else`,children:i.jsx(eo,{node:e.else,onChange:c,t:n,candidates:o,testidPrefix:`${r}-else`,depth:s+1,renderLeafInput:a})})]})}function __({node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a}){const l=u.useCallback(c=>t({...e,primary:c}),[e,t]),d=u.useCallback(c=>t({...e,fallback:c}),[e,t]);return i.jsxs("div",{"data-testid":`${r}-fallback`,style:ms(s),children:[i.jsx(Dr,{label:n("layout_editor.value_tree.fallback.primary"),testid:`${r}-primary`,children:i.jsx(eo,{node:e.primary,onChange:l,t:n,candidates:o,testidPrefix:`${r}-primary`,depth:s+1,renderLeafInput:a})}),i.jsx(Dr,{label:n(e.op==="??"?"layout_editor.value_tree.fallback.when_empty":"layout_editor.value_tree.fallback.when_falsy"),testid:`${r}-fallback-branch`,children:i.jsx(eo,{node:e.fallback,onChange:d,t:n,candidates:o,testidPrefix:`${r}-fallbackb`,depth:s+1,renderLeafInput:a})})]})}const x_={text:()=>({kind:"leaf",text:""}),data:()=>({kind:"leaf",text:""}),expression:()=>({kind:"conditional",condition:{kind:"simple",left:"",op:"truthy",right:""},then:{kind:"leaf",text:""},else:{kind:"leaf",text:""}}),fallback:()=>({kind:"fallback",op:"??",primary:{kind:"leaf",text:""},fallback:{kind:"leaf",text:""}})};function w_({node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a}){const l=u.useCallback((g,m)=>{const h=e.parts.slice();h[g]=m,t({...e,parts:h})},[e,t]),d=u.useCallback(g=>{g.length===0?t({kind:"leaf",text:""}):g.length===1?t(g[0]):t({...e,parts:g})},[e,t]),c=u.useCallback(g=>d(e.parts.filter((m,h)=>h!==g)),[e.parts,d]),p=u.useCallback(g=>d([...e.parts,x_[g]()]),[e.parts,d]),f=u.useCallback((g,m)=>{if(g===m||g<0||m<0||g>=e.parts.length||m>=e.parts.length)return;const h=e.parts.slice(),[v]=h.splice(g,1);h.splice(m,0,v),d(h)},[e.parts,d]),b=ys({length:e.parts.length,onMove:f});return i.jsxs("div",{"data-testid":`${r}-concat`,style:ms(s),children:[i.jsx("div",{style:z_,children:n("layout_editor.value_tree.concat.hint")}),e.parts.map((g,m)=>i.jsxs(u.Fragment,{children:[i.jsx(Rn,{active:b.isDropTarget(m),testid:`${r}-part-dropline-${m}`}),i.jsxs("div",{"data-testid":`${r}-part-card-${m}`,style:b.dragIndex===m?{...cc,opacity:.5}:cc,onDragOver:h=>{h.preventDefault();const v=h.currentTarget.getBoundingClientRect();b.onDragOverItem(m,h.clientY{h.preventDefault(),b.onDrop()},children:[i.jsxs("div",{style:N_,children:[i.jsx("span",{"data-testid":`${r}-part-handle-${m}`,style:P_,draggable:!0,onDragStart:()=>b.onDragStart(m),onDragEnd:b.onDragEnd,title:n("layout_editor.value_tree.drag_reorder"),"aria-label":n("layout_editor.value_tree.drag_reorder"),role:"button",children:"⠿"}),i.jsx("span",{style:M_,children:n("layout_editor.value_tree.concat.part",{n:m+1})}),i.jsx("button",{type:"button","data-testid":`${r}-part-remove-${m}`,onClick:()=>c(m),title:n("layout_editor.value_tree.segment.remove"),"aria-label":n("layout_editor.value_tree.segment.remove"),style:O_,children:"✕"})]}),i.jsx("div",{style:{minWidth:0},children:i.jsx(eo,{node:g,onChange:h=>l(m,h),t:n,candidates:o,testidPrefix:`${r}-part-${m}`,depth:s+1,renderLeafInput:a})})]})]},m)),i.jsx(Rn,{active:b.isDropTarget(e.parts.length),testid:`${r}-part-dropline-end`}),i.jsxs("div",{style:L_,"data-testid":`${r}-part-add-row`,children:[i.jsxs("button",{type:"button","data-testid":`${r}-part-add-text`,onClick:()=>p("text"),style:zr,children:["+ ",n("layout_editor.value_tree.segment.text")]}),i.jsxs("button",{type:"button","data-testid":`${r}-part-add-expression`,onClick:()=>p("expression"),style:zr,children:["+ ",n("layout_editor.value_tree.segment.expression")]}),i.jsxs("button",{type:"button","data-testid":`${r}-part-add-fallback`,onClick:()=>p("fallback"),style:zr,children:["+ ",n("layout_editor.value_tree.segment.fallback")]}),i.jsxs("button",{type:"button","data-testid":`${r}-part-add-data`,onClick:()=>p("data"),style:zr,children:["+ ",n("layout_editor.value_tree.segment.data")]})]})]})}function k_({condition:e,onChange:t,t:n,candidates:o,testidPrefix:r}){if(e.kind==="raw")return i.jsxs("div",{"data-testid":`${r}-cond-raw`,style:I_,children:[i.jsx("span",{style:dc,children:n("layout_editor.value_tree.cond.label")}),i.jsx("code",{style:uc,children:e.source}),i.jsxs("span",{style:pc,children:["🔒 ",n("layout_editor.value_tree.cond.code_only")]})]});const s=e,a=s.op!=="truthy"&&s.op!=="falsy";return i.jsxs("div",{"data-testid":`${r}-cond`,style:E_,children:[i.jsx("span",{style:dc,children:n("layout_editor.value_tree.cond.label")}),i.jsx(ac,{testid:`${r}-cond-left`,value:s.left,onCommit:l=>t({...s,left:l}),placeholder:n("layout_editor.value_tree.cond.field_placeholder"),candidates:o,t:n}),i.jsx("select",{"data-testid":`${r}-cond-op`,value:s.op,onChange:l=>t({...s,op:l.target.value}),style:D_,children:m_.map(l=>i.jsx("option",{value:l.value,children:n(l.labelKey)},l.value))}),a&&i.jsx(ac,{testid:`${r}-cond-right`,value:s.right,onCommit:l=>t({...s,right:l}),placeholder:n("layout_editor.value_tree.cond.value_placeholder"),candidates:o,t:n,quoteDataPick:!0})]})}function ac({testid:e,value:t,onCommit:n,placeholder:o,candidates:r,t:s,quoteDataPick:a=!1}){const[l,d]=u.useState(null),c=l!==null?l:t,p=()=>{l!==null&&(l!==t&&n(l),d(null))},f=(b,g)=>{const m=En(b,g,"scalar"),h=/^\{\{\s*([\s\S]*?)\s*\}\}$/.exec(m.trim());let v=h?h[1]:m;v=v.replace(/\s*\?\?\s*''$/,"").trim(),n(a?`'${v}'`:v),d(null)};return i.jsxs("span",{style:A_,children:[i.jsx("input",{type:"text","data-testid":e,value:c,onChange:b=>d(b.target.value),onBlur:p,onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),p())},placeholder:o,style:T_}),r&&r.length>0&&s&&i.jsx($t,{candidates:r,t:s,onSelect:b=>f(b.sourceId,b.path),testIdSuffix:`${e}-data`,floating:!0})]})}function Dr({label:e,testid:t,children:n}){return i.jsxs("div",{"data-testid":t,style:S_,children:[i.jsx("span",{style:C_,children:e}),i.jsx("div",{style:$_,children:n})]})}const lc={display:"flex",flexDirection:"column",gap:6,width:"100%",minWidth:0},ms=e=>({display:"flex",flexDirection:"column",gap:6,padding:"8px",border:"1px solid #e2e8f0",borderLeft:`3px solid ${e%2===0?"#6366f1":"#0ea5e9"}`,borderRadius:6,background:e%2===0?"#f8fafc":"#fefefe",minWidth:0}),S_={display:"flex",flexDirection:"column",gap:3,minWidth:0},C_={fontSize:11,fontWeight:600,color:"#475569"},$_={paddingLeft:8,minWidth:0},E_={display:"flex",flexWrap:"wrap",gap:4,alignItems:"center",minWidth:0},I_={display:"flex",flexWrap:"wrap",gap:4,alignItems:"center",minWidth:0},dc={fontSize:11,fontWeight:600,color:"#0f172a",whiteSpace:"nowrap"},A_={display:"inline-flex",alignItems:"flex-start",gap:2,flex:"1 1 80px",minWidth:60},T_={flex:"1 1 80px",minWidth:60,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},D_={padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff"},z_={fontSize:11,color:"#94a3b8"},cc={display:"flex",flexDirection:"column",gap:4,padding:"6px 8px",border:"1px solid #e2e8f0",borderLeft:"3px solid #6366f1",borderRadius:6,background:"#fff",minWidth:0},N_={display:"flex",alignItems:"center",gap:6,minWidth:0},M_={fontSize:10,fontWeight:600,color:"#6366f1",flex:1,minWidth:0},L_={display:"flex",flexWrap:"wrap",gap:6,marginTop:2},P_={color:"#94a3b8",cursor:"grab",fontSize:14,userSelect:"none"},O_={border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12,padding:2,flexShrink:0},zr={padding:"4px 10px",fontSize:11,border:"1px dashed #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},B_={display:"flex",flexDirection:"column",gap:4,marginTop:2},W_={alignSelf:"flex-start",padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",fontFamily:"monospace"},j_={fontSize:11,background:"#0f172a",color:"#e2e8f0",padding:"6px 8px",borderRadius:4,wordBreak:"break-all",fontFamily:"monospace"},H_={display:"flex",flexDirection:"column",gap:2,minWidth:0},uc={fontSize:11,background:"#f1f5f9",padding:"3px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all",fontFamily:"monospace"},pc={fontSize:10,color:"#64748b"};function _t({value:e,onChange:t,t:n,placeholder:o,testidPrefix:r="g7le-i18n-text-field",locales:s,candidates:a,enableExpressionTree:l=!1,expressionTreeCollapsible:d=!1,expressionSourceToggle:c=!0}){const{locale:p,templateIdentifier:f,commitText:b,classify:g,translate:m}=mv(),[h,v]=u.useState(null),[y,_]=u.useState(!1),[w,k]=u.useState(!1),[x,$]=u.useState(!1),[S,C]=u.useState(!1),[T,E]=u.useState(!1),[,A]=u.useState(0);u.useEffect(()=>{if(typeof window>"u")return;const z=H=>{const P=H.detail;P?.templateIdentifier&&P.templateIdentifier!==f||A(I=>I+1)};return window.addEventListener(kt,z),()=>window.removeEventListener(kt,z)},[f]);const N=g(e);u.useEffect(()=>{v(null),E(!1)},[p,e]);const D=h!==null?h:N.displayValue,B=u.useCallback(async()=>{if(h!==null){if(h===N.displayValue){v(null);return}_(!0);try{const z=await b(e,h);z.kind==="created"&&z.token?(t(z.token),Et({op:"prop_i18n_create_key",sourceState:"plain_text",translationKey:z.customKey,toLocale:p,valueLength:h.length,timestamp:Date.now()})):z.kind==="updated"&&Et({op:"prop_i18n_update_value",sourceState:"custom_key",translationKey:z.customKey,toLocale:p,valueLength:h.length,timestamp:Date.now()})}finally{_(!1),v(null)}}},[h,N.displayValue,b,e,t,p]),M=u.useCallback(z=>{typeof e=="string"&&(t(vo(e,z)),N.customKey&&$r(f,N.customKey,z,p))},[e,t,N.customKey,f,p]);if(N.binding){if(l&&typeof e=="string"){const z=Zd(e),H=un(e),P=!z&&Kt(e)!==null,I=(z||H.decomposed)&&!P;if(I&&d&&!x)return i.jsx(V_,{value:e,t:n,translate:m,onEdit:()=>$(!0),testidPrefix:`${r}-preview`});const F=I&&(d||z)?i.jsx(bs,{value:e,onChange:Y=>t(Y),t:n,candidates:a,testidPrefix:`${r}-seg`}):H.decomposed?i.jsx(sc,{node:H.node,onChange:Y=>t(Zn(Y,!1)),t:n,candidates:a,testidPrefix:`${r}-tree`,showSourceToggle:c}):null;if(F){if(!d)return F;const Y=Er(e),K=Y?gs(Y,X=>{const Z=m(X);return Z&&Z!==X&&!Z.startsWith("$t:")?Z:""},X=>Vt(X)):[];return i.jsxs("div",{"data-testid":`${r}-builder`,style:{display:"flex",flexDirection:"column",gap:6,width:"100%",minWidth:0},children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:6},children:[i.jsxs("button",{type:"button","data-testid":`${r}-to-plain`,onClick:()=>C(!0),style:Z_,title:n("layout_editor.value_tree.to_plain"),"aria-label":n("layout_editor.value_tree.to_plain"),children:["↩ ",n("layout_editor.value_tree.to_plain")]}),i.jsxs("button",{type:"button","data-testid":`${r}-builder-collapse`,onClick:()=>$(!1),style:hc,title:n("layout_editor.value_tree.collapse"),"aria-label":n("layout_editor.value_tree.collapse"),children:["▴ ",n("layout_editor.value_tree.collapse")]})]}),S&&i.jsxs("div",{"data-testid":`${r}-to-plain-confirm`,style:Q_,children:[i.jsx("p",{style:R_,children:n("layout_editor.value_tree.to_plain_lead")}),i.jsx("div",{style:ex,children:K.length===0?i.jsx("span",{style:{color:"#94a3b8"},children:n("layout_editor.prop_i18n.placeholder")}):K.map((X,Z)=>X.kind==="chip"?i.jsxs("span",{style:fc,children:["🔗 ",X.text]},Z):i.jsx("span",{style:X.kind==="ellipsis"?gc:void 0,children:X.text},Z))}),i.jsxs("p",{style:tx,children:["⚠ ",n("layout_editor.value_tree.to_plain_warn")]}),i.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:6},children:[i.jsx("button",{type:"button","data-testid":`${r}-to-plain-confirm-cancel`,onClick:()=>C(!1),style:hc,children:n("layout_editor.value_tree.to_plain_cancel")}),i.jsx("button",{type:"button","data-testid":`${r}-to-plain-confirm-ok`,onClick:()=>{C(!1),$(!1),t(Er(e)||void 0)},style:nx,children:n("layout_editor.value_tree.to_plain_ok")})]})]}),F]})}}return l&&typeof e=="string"&&a&&a.length>0&&Kt(e)!==null?i.jsx(U_,{value:e,onChange:t,t:n,candidates:a,testidPrefix:`${r}-data`}):i.jsxs("div",{"data-testid":`${r}-binding`,style:lx,children:[i.jsx("code",{style:dx,children:typeof e=="string"?e:""}),i.jsxs("span",{style:cx,children:["🔗 ",n("layout_editor.prop_i18n.bound_code_only")]})]})}if(!T&&typeof e=="string"&&Xl(e)){const z=Jl(e);return i.jsxs("div",{"data-testid":`${r}-settings-ref`,style:ix,children:[i.jsx("div",{"data-testid":`${r}-settings-ref-chips`,style:sx,children:z.map((H,P)=>H.kind==="chip"?i.jsxs("span",{style:ax,children:["🔗 ",H.label]},P):i.jsx("span",{children:H.label},P))}),i.jsxs("button",{type:"button","data-testid":`${r}-settings-ref-edit`,onClick:()=>E(!0),style:yc,title:n("layout_editor.value_tree.edit"),"aria-label":n("layout_editor.value_tree.edit"),children:["✎ ",n("layout_editor.value_tree.edit")]})]})}const O=i.jsxs("button",{type:"button","data-testid":`${r}-toggle`,title:`${n("layout_editor.prop_i18n.edit_languages")} (${Gn(p,n)})`,"aria-label":`${n("layout_editor.prop_i18n.edit_languages")} (${Gn(p,n)})`,"aria-expanded":w,onClick:()=>k(z=>!z),style:yc,children:["🌐 ",N.customKey?w?"⌃":"⌄":"+"]});return i.jsxs("div",{"data-testid":r,style:{display:"flex",flexDirection:"column",gap:4,width:"100%"},children:[i.jsx("div",{style:ox,children:N.paramKey&&N.customKey?i.jsx(F_,{customKey:N.customKey,value:typeof e=="string"?e:"",onChange:t,t:n,candidates:a,testidPrefix:r,showExprButton:l&&d,onToExpression:()=>{$(!0),t($o(typeof e=="string"?e:""))},langToggle:O}):i.jsxs(i.Fragment,{children:[i.jsx("input",{type:"text","data-testid":`${r}-preview`,value:D,placeholder:o??n("layout_editor.prop_i18n.placeholder"),onChange:z=>v(z.target.value),onBlur:()=>{B(),T&&E(!1)},disabled:y,style:rx}),a&&a.length>0&&i.jsx(K_,{value:typeof e=="string"?e:"",customKey:N.customKey,onChange:t,t:n,candidates:a,testidPrefix:r}),l&&d&&i.jsx("button",{type:"button","data-testid":`${r}-to-expr`,onClick:()=>{$(!0),t($o(typeof e=="string"?e:""))},title:n("layout_editor.value_tree.to_expression"),"aria-label":n("layout_editor.value_tree.to_expression"),style:Ao,children:"ƒx"}),O]})}),w&&(N.customKey?i.jsx(Xd,{customKey:N.customKey,templateIdentifier:f,t:n,paramLabels:ps(e),locales:s,onRemoveParam:M},N.customKey):i.jsx("div",{"data-testid":`${r}-expand-hint`,style:ux,children:n("layout_editor.prop_i18n.create_first")}))]})}function F_({customKey:e,value:t,onChange:n,t:o,candidates:r,testidPrefix:s,showExprButton:a=!1,onToExpression:l,langToggle:d}){const{state:c}=Qe(),p=c.templateIdentifier,f=c.locale,b=Ft(),[g,m]=u.useState(null),h=u.useRef(""),v=u.useRef(null),y=u.useRef(null),_=u.useRef(null),[w,k]=u.useState(null),[x,$]=u.useState(!1),S=ps(t),C=u.useCallback(async()=>{const D=It(e,f);if(D!==void 0){h.current=D,m(D);return}const M=(await cn(p,e))?.values?.[f]??"";h.current=M,m(M)},[e,p,f]);u.useEffect(()=>{let D=!1;return(async()=>{const B=It(e,f);if(B!==void 0){D||(h.current=B,m(B));return}const M=await cn(p,e);if(D)return;const O=M?.values?.[f]??"";h.current=O,m(O)})(),()=>{D=!0}},[e,p,f]),u.useEffect(()=>{if(typeof window>"u")return;const D=B=>{const M=B.detail;if(M?.templateIdentifier&&M.templateIdentifier!==p)return;const O=It(e,f);O!==void 0&&O!==g&&(h.current=O,m(O))};return window.addEventListener(kt,D),()=>window.removeEventListener(kt,D)},[e,p,f,g]);const T=u.useCallback(D=>{m(D),So(p,e,f,D).then(()=>{b?.markDirty?.()})},[p,e,f,b]),E=u.useCallback(D=>{n(vo(t,D)),$r(p,e,D,f).then(()=>{C(),b?.markDirty?.()})},[t,n,p,e,f,C,b]),A=u.useCallback(async D=>{if(!(w===null||x)){$(!0);try{g!==null&&g!==h.current&&(await So(p,e,f,g),h.current=g);const B=await Cr(p,f,t,w,D.sourceId,D.path,"scalar");B.kind==="ok"&&(n(B.text),await C(),b?.markDirty?.())}finally{$(!1),k(null)}}},[w,x,g,t,p,e,f,n,C,b]),N=!!r&&r.length>0;return i.jsxs("div",{"data-testid":`${s}-chipfield-wrap`,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:4},children:[i.jsx("div",{ref:v,"data-testid":`${s}-chipfield`,style:{flex:1,minWidth:0},children:g===null?i.jsx("div",{"data-testid":`${s}-chipfield-loading`,style:{fontSize:11,color:"#94a3b8",padding:"4px 0"},children:o("layout_editor.translation.loading")}):i.jsx(xr,{value:g,onChange:T,t:o,paramLabels:S,testIdSuffix:`${s}-field`,onRequestInsert:N?D=>k(D):void 0,onRemoveChip:E,hideInsertButton:!0,caretRef:_})}),N&&i.jsx("button",{ref:y,type:"button","data-testid":`${s}-plus-data-btn`,onClick:()=>k(_.current?_.current():g?.length??0),title:o("layout_editor.inline_binding.insert_data"),"aria-label":o("layout_editor.inline_binding.insert_data"),style:Ao,children:"+"}),a&&l&&i.jsx("button",{type:"button","data-testid":`${s}-to-expr`,onClick:l,title:o("layout_editor.value_tree.to_expression"),"aria-label":o("layout_editor.value_tree.to_expression"),style:Ao,children:"ƒx"}),d,N&&i.jsx(Xn,{anchorRef:y,open:w!==null,onClose:()=>k(null),children:i.jsx("div",{"data-testid":`${s}-chipfield-picker`,children:i.jsx($t,{candidates:r,t:o,onSelect:D=>{A(D)},testIdSuffix:`${s}-field-insert`,defaultOpen:!0,floating:!1})})})]})}function K_({value:e,customKey:t,onChange:n,t:o,candidates:r,testidPrefix:s}){const{state:a}=Qe(),l=a.templateIdentifier,d=a.selectedRoute?.layoutName??null,c=a.locale,p=Ft(),[f,b]=u.useState(!1),[g,m]=u.useState(!1),h=u.useRef(null),v=u.useCallback(w=>{const k=o(w);return k&&k!==w&&!k.startsWith("$t:")?k:""},[o]),y=u.useCallback(w=>w.replace(/\$t:[a-zA-Z0-9._-]+/g,k=>v(k.slice(3))).replace(/\s+/g," ").trim(),[v]),_=u.useCallback(async w=>{if(!g){m(!0);try{if(t){const k=await Cr(l,c,e,Number.MAX_SAFE_INTEGER,w.sourceId,w.path,"scalar");k.kind==="ok"&&(n(k.text),p?.markDirty?.())}else{const k=await us(l,d,c,e,e.length,w.sourceId,w.path,"scalar",y,x=>o(x));k.kind==="ok"&&(n(k.text),p?.markDirty?.())}}finally{m(!1),b(!1)}}},[g,t,l,d,c,e,n,p,o,y]);return i.jsxs("div",{"data-testid":`${s}-plus-data`,style:{display:"inline-block"},children:[i.jsx("button",{ref:h,type:"button","data-testid":`${s}-plus-data-btn`,disabled:g,onClick:()=>b(w=>!w),title:o("layout_editor.inline_binding.insert_data"),"aria-label":o("layout_editor.inline_binding.insert_data"),style:Ao,children:"+"}),i.jsx(Xn,{anchorRef:h,open:f,onClose:()=>b(!1),children:i.jsx($t,{candidates:r,t:o,onSelect:w=>{_(w)},testIdSuffix:`${s}-plus-insert`,defaultOpen:!0,floating:!1})})]})}function V_({value:e,t,translate:n,onEdit:o,testidPrefix:r}){const s=gs(e,a=>{const l=n(a);return l&&l!==a&&!l.startsWith("$t:")?l:""},a=>Vt(a));return i.jsxs("div",{"data-testid":r,style:Y_,children:[i.jsx("div",{"data-testid":`${r}-text`,style:X_,children:s.length===0?i.jsx("span",{style:{color:"#94a3b8"},children:t("layout_editor.prop_i18n.placeholder")}):s.map((a,l)=>a.kind==="chip"?i.jsxs("span",{style:fc,children:["🔗 ",a.text]},l):i.jsx("span",{style:a.kind==="ellipsis"?gc:void 0,children:a.text},l))}),i.jsxs("button",{type:"button","data-testid":`${r}-edit`,onClick:o,style:J_,title:t("layout_editor.value_tree.edit"),"aria-label":t("layout_editor.value_tree.edit"),children:["✎ ",t("layout_editor.value_tree.edit")]})]})}function U_({value:e,onChange:t,t:n,candidates:o,testidPrefix:r}){const[s,a]=u.useState(!1),l=u.useRef(null),d=Vt(e);return i.jsxs("div",{"data-testid":r,style:{display:"flex",flexDirection:"column",gap:4,width:"100%",minWidth:0},children:[i.jsxs("div",{style:q_,children:[i.jsxs("span",{"data-testid":`${r}-chip`,style:G_,children:["🔗 ",d]}),i.jsx("button",{ref:l,type:"button","data-testid":`${r}-change`,onClick:()=>a(c=>!c),style:Ao,title:n("layout_editor.value_tree.change_data"),"aria-label":n("layout_editor.value_tree.change_data"),children:n("layout_editor.value_tree.change_data")})]}),i.jsx(Xn,{anchorRef:l,open:s,onClose:()=>a(!1),children:i.jsx($t,{candidates:o,t:n,onSelect:c=>{const p=c.path?c.path.split(".").filter(Boolean):[],f=[c.sourceId,...p].join("?.");t(`{{${f}}}`),a(!1)},testIdSuffix:`${r}-pick`,defaultOpen:!0,floating:!1})})]})}const q_={display:"flex",alignItems:"center",gap:6,width:"100%",minWidth:0,flexWrap:"wrap"},G_={fontSize:11,background:"#eef2ff",color:"#4338ca",padding:"3px 8px",borderRadius:12,wordBreak:"break-all"},Y_={display:"flex",alignItems:"center",gap:8,width:"100%",minWidth:0},X_={flex:1,minWidth:0,display:"flex",flexWrap:"wrap",alignItems:"center",gap:4,padding:"5px 8px",fontSize:12,color:"#334155",border:"1px solid #e2e8f0",borderRadius:6,background:"#f8fafc",overflow:"hidden"},fc={fontSize:11,background:"#eef2ff",color:"#4338ca",padding:"1px 6px",borderRadius:10,whiteSpace:"nowrap"},gc={color:"#94a3b8"},J_={padding:"4px 10px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#2563eb",cursor:"pointer",whiteSpace:"nowrap",flexShrink:0},hc={padding:"3px 10px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},Z_={padding:"3px 10px",fontSize:11,border:"1px solid #fca5a5",borderRadius:6,background:"#fef2f2",color:"#b91c1c",cursor:"pointer",whiteSpace:"nowrap"},Q_={display:"flex",flexDirection:"column",gap:6,padding:10,border:"1px solid #fca5a5",borderRadius:8,background:"#fffbeb"},R_={margin:0,fontSize:12,color:"#334155"},ex={padding:"5px 8px",fontSize:12,color:"#0f172a",background:"#fff",border:"1px solid #e2e8f0",borderRadius:6,wordBreak:"break-all"},tx={margin:0,fontSize:11,color:"#b45309"},nx={padding:"3px 12px",fontSize:11,border:"1px solid #dc2626",borderRadius:6,background:"#dc2626",color:"#fff",cursor:"pointer",whiteSpace:"nowrap"},ox={display:"flex",gap:4,alignItems:"center",width:"100%",minWidth:0},rx={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:0,width:"100%"},yc={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},Ao={padding:"4px 8px",fontSize:13,lineHeight:1,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},ix={display:"flex",alignItems:"center",gap:6,width:"100%",minWidth:0,flexWrap:"wrap"},sx={flex:1,minWidth:0,display:"flex",flexWrap:"wrap",alignItems:"center",gap:4,fontSize:12,color:"#334155"},ax={fontSize:11,background:"#eef2ff",color:"#4338ca",padding:"2px 8px",borderRadius:12,whiteSpace:"nowrap"},lx={display:"flex",flexDirection:"column",gap:2,width:"100%"},dx={fontSize:11,background:"#f1f5f9",padding:"3px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all"},cx={fontSize:10,color:"#64748b"},ux={fontSize:11,color:"#94a3b8",padding:"6px 8px",border:"1px dashed #cbd5e1",borderRadius:6,background:"#f8fafc"};function vs({value:e,onChange:t,candidates:n,t:o}){const r=Array.isArray(e)?e:[],s=n??[],[a,l]=u.useState(!1),d=g=>s.find(m=>m.value===g)?.label??g,c=g=>d(g)!==g,p=g=>{const m=r.filter(h=>h!==g);t(m.length===0?void 0:m)},f=g=>{r.includes(g)||(t([...r,g]),l(!1))},b=s.filter(g=>!r.includes(g.value));return i.jsxs("div",{className:"g7le-widget g7le-widget--tag-input","data-testid":"g7le-widget-tag-input",style:px,children:[i.jsxs("div",{style:fx,children:[r.map(g=>i.jsxs("span",{"data-testid":`g7le-tag-chip-${g}`,style:gx,children:[i.jsx("span",{style:hx,children:d(g)}),c(g)&&i.jsx("code",{"data-testid":`g7le-tag-chip-id-${g}`,style:yx,children:g}),i.jsx("button",{type:"button","aria-label":`remove ${g}`,"data-testid":`g7le-tag-remove-${g}`,onClick:()=>p(g),style:bx,children:"✕"})]},g)),i.jsx("button",{type:"button","data-testid":"g7le-tag-add",onClick:()=>l(g=>!g),disabled:b.length===0,style:mx,children:o("layout_editor.control.tag_add")})]}),a&&b.length>0&&i.jsx("div",{"data-testid":"g7le-tag-candidates",style:vx,children:b.map(g=>{const m=g.value!==g.label;return i.jsxs("button",{type:"button","data-testid":`g7le-tag-candidate-${g.value}`,onClick:()=>f(g.value),style:_x,children:[i.jsx("span",{style:xx,children:g.label}),m&&i.jsx("code",{"data-testid":`g7le-tag-candidate-id-${g.value}`,style:wx,children:g.value})]},g.value)})})]})}const px={display:"flex",flexDirection:"column",gap:6},fx={display:"flex",flexWrap:"wrap",gap:4,alignItems:"center"},gx={display:"inline-flex",alignItems:"center",gap:4,padding:"2px 6px",fontSize:12,background:"#e0e7ff",color:"#1d4ed8",borderRadius:12},hx={fontSize:12},yx={fontSize:10,color:"#4f46e5",background:"#c7d2fe",borderRadius:4,padding:"0 4px",fontFamily:"monospace"},bx={border:"none",background:"transparent",color:"#1d4ed8",cursor:"pointer",fontSize:10,padding:0,lineHeight:1},mx={padding:"2px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:12,background:"#fff",cursor:"pointer",color:"#475569"},vx={display:"flex",flexDirection:"column",maxHeight:180,overflowY:"auto",border:"1px solid #cbd5e1",borderRadius:6,background:"#fff"},_x={display:"flex",flexDirection:"column",gap:1,textAlign:"left",padding:"6px 10px",fontSize:12,border:"none",borderBottom:"1px solid #f1f5f9",background:"transparent",cursor:"pointer",color:"#0f172a"},xx={fontSize:12,color:"#0f172a"},wx={fontSize:10,color:"#64748b",fontFamily:"monospace"},bc=new Map;function Ze(e,t){bc.set(e,t)}function Tn(e){return e?bc.get(e)??null:null}function Nr(e,t){const o=e("meta",{})?.[t];return typeof o=="string"?o:""}function kx({getValue:e,patch:t,t:n,fieldT:o,spec:r,permissionCandidates:s,bindingCandidates:a}){const l=o??n,d=Nr(e,"title"),c=Nr(e,"description"),p=Nr(e,"icon"),f=Nr(e,"editor_label"),b=e("permissions",[]),g=u.useCallback((y,_)=>{const w={...e("meta",{})??{}};_===void 0||_===""?delete w[y]:w[y]=_,t("meta",w)},[e,t]),m=u.useCallback(y=>{const _=Array.isArray(y)?y:[];_.length===0?t("permissions",void 0):t("permissions",_)},[t]),h=Tn("icon-picker"),v=Ct(r,"icon-picker")??Ct(r,"icon")??(r?.controls?Object.values(r.controls).find(y=>y&&typeof y=="object"&&y.widget==="icon-picker")??null:null);return i.jsxs("div",{className:"g7le-meta-form","data-testid":"g7le-meta-form",style:Cx,children:[i.jsx(To,{label:n("layout_editor.page_settings.meta.title"),children:i.jsx(_t,{value:d,onChange:y=>g("title",y),t:l,testidPrefix:"g7le-meta-title",candidates:a,enableExpressionTree:!0,expressionTreeCollapsible:!0})}),i.jsx(To,{label:n("layout_editor.page_settings.meta.description"),children:i.jsx(_t,{value:c,onChange:y=>g("description",y),t:l,testidPrefix:"g7le-meta-description",candidates:a,enableExpressionTree:!0,expressionTreeCollapsible:!0})}),i.jsx(To,{label:n("layout_editor.page_settings.meta.icon"),children:h?i.jsx(Sx,{icon:p,t:n,onChange:y=>g("icon",typeof y=="string"?y:void 0),IconWidget:h,iconControl:v??{widget:"icon-picker"}}):i.jsx("input",{type:"text","data-testid":"g7le-meta-icon",value:p,placeholder:n("layout_editor.page_settings.meta.icon_placeholder"),onChange:y=>g("icon",y.target.value),style:Ax})}),i.jsx(To,{label:n("layout_editor.page_settings.meta.editor_label"),hint:n("layout_editor.page_settings.meta.editor_label_hint"),children:i.jsx(_t,{value:f,onChange:y=>g("editor_label",y),t:l,testidPrefix:"g7le-meta-editor-label",candidates:a,enableExpressionTree:!0,expressionTreeCollapsible:!0})}),i.jsx(To,{label:n("layout_editor.page_settings.meta.permissions"),hint:n("layout_editor.page_settings.meta.permissions_hint"),children:i.jsx("div",{"data-testid":"g7le-meta-permissions",children:i.jsx(vs,{control:{widget:"tag-input"},value:b,onChange:m,t:n,candidates:s})})})]})}function To({label:e,hint:t,children:n}){return i.jsxs("div",{className:"g7le-meta-field",style:$x,children:[i.jsx("label",{style:Ex,children:e}),n,t?i.jsxs("p",{style:Ix,children:["ⓘ ",t]}):null]})}function Sx({icon:e,onChange:t,t:n,IconWidget:o,iconControl:r}){const[s,a]=u.useState(!1),l=e?/\bfa-/.test(e)?i.jsx("i",{className:e,"aria-hidden":"true"}):e:"📄";return i.jsxs("div",{"data-testid":"g7le-meta-icon",style:{display:"flex",flexDirection:"column",gap:6,minWidth:0},children:[i.jsxs("button",{type:"button","data-testid":"g7le-meta-icon-toggle","aria-expanded":s,onClick:()=>a(d=>!d),style:{display:"flex",alignItems:"center",gap:8,padding:"5px 8px",border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",cursor:"pointer",fontSize:12,color:"#475569",width:"fit-content"},children:[i.jsx("span",{style:{fontSize:16},"aria-hidden":"true",children:l}),i.jsx("span",{children:e||n("layout_editor.page_settings.meta.icon_placeholder")}),i.jsx("span",{"aria-hidden":"true",children:s?"▴":"▾"})]}),s?i.jsx(o,{control:r,value:e,onChange:d=>{t(d),a(!1)},t:n}):null]})}const Cx={display:"flex",flexDirection:"column",gap:16,minWidth:0},$x={display:"flex",flexDirection:"column",gap:6,minWidth:0},Ex={fontSize:13,fontWeight:600,color:"#0f172a"},Ix={margin:0,fontSize:11,color:"#94a3b8"},Ax={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:0,width:"100%"};function Mr({checked:e,onChange:t,label:n,testid:o,ariaLabel:r,disabled:s=!1}){return i.jsxs("label",{style:{...Mx,...s?{cursor:"not-allowed"}:{}},children:[i.jsx("button",{type:"button","data-testid":o,role:"switch","aria-checked":e,"aria-label":r,disabled:s,onClick:()=>t(!e),style:Lx(e,s),children:i.jsx("span",{style:Px(e)})}),n!=null?i.jsx("span",{style:Ox(s),children:n}):null]})}function Lr({disabled:e,children:t,testid:n,style:o}){return i.jsx("div",{"data-testid":n,"data-disabled":e?"true":"false","aria-disabled":e,style:{...o,...e?{opacity:.5,pointerEvents:"none",userSelect:"none"}:{}},children:t})}function Tx({filled:e,sourceLabel:t,onRevert:n,revertLabel:o,hint:r,children:s,testid:a}){const l=e&&typeof n=="function",d=!e&&t!=null&&t!=="";return i.jsxs("div",{"data-testid":a,style:Dx,children:[s,l?i.jsxs("button",{type:"button","data-testid":a?`${a}-revert`:void 0,onClick:n,title:r??o,"aria-label":o,style:Nx,children:["↩ ",o]}):d?i.jsx("span",{"data-testid":a?`${a}-source`:void 0,title:r,style:zx,children:t}):null]})}const Dx={position:"relative",minWidth:0,width:"100%"},zx={position:"absolute",right:8,top:"50%",transform:"translateY(-50%)",fontSize:10,color:"#94a3b8",background:"#f1f5f9",borderRadius:4,padding:"1px 6px",pointerEvents:"none",maxWidth:"45%",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},Nx={position:"absolute",right:6,top:"50%",transform:"translateY(-50%)",fontSize:10,color:"#0369a1",background:"#e0f2fe",border:"1px solid #bae6fd",borderRadius:4,padding:"1px 6px",cursor:"pointer",whiteSpace:"nowrap"},Mx={display:"inline-flex",alignItems:"center",gap:8,cursor:"pointer"},Lx=(e,t)=>({position:"relative",width:38,height:22,flexShrink:0,borderRadius:999,border:"none",padding:0,background:t?"#e2e8f0":e?"#2563eb":"#cbd5e1",cursor:t?"not-allowed":"pointer",transition:"background 0.15s ease"}),Px=e=>({position:"absolute",top:2,left:e?18:2,width:18,height:18,borderRadius:"50%",background:"#fff",boxShadow:"0 1px 2px rgba(0,0,0,0.2)",transition:"left 0.15s ease"}),Ox=e=>({fontSize:13,fontWeight:600,color:e?"#94a3b8":"#0f172a"}),Bx=/\$(?:core|module|plugin)_settings:[a-zA-Z0-9._:-]+/;function Wx(e){const t=[];let n=!1;const o=s=>{t.push({kind:"text",text:s}),n=!0},r=(s,a,l)=>{n||o(""),t.push({kind:"chip",raw:s,text:a,removable:l}),n=!1};for(const s of jx(e))s.kind==="text"?o(s.raw):r(s.raw,s.label,s.removable);return n||o(""),t}function jx(e){const t=[];if(typeof e!="string"||e.length===0)return t;const n=e.length;let o=0,r=0;const s=a=>{a>r&&t.push({kind:"text",raw:e.slice(r,a),label:"",removable:!1})};for(;o=n){o++;continue}s(o);const l=e.slice(o,a+2);t.push({kind:"chip",raw:l,label:Vt(l),removable:!0}),o=a+2,r=o;continue}if(e[o]==="$"){const a=Bx.exec(e.slice(o));if(a&&a.index===0){s(o);const l=a[0],d=l.split(":").pop()||l;t.push({kind:"chip",raw:l,label:d,removable:!1}),o+=l.length,r=o;continue}}o++}return s(n),t}function Hx(e,t,n,o){const r=[];let s=!1;return e.forEach((a,l)=>{if(a.kind==="chip"){if(!s&&a.raw===t){s=!0;return}r.push(a.raw??"")}else{const d=a.text??"";if(l===n){const c=Math.max(0,Math.min(o,d.length));r.push(d.slice(0,c),t,d.slice(c))}else r.push(d)}}),r.join("")}function Fx(e,t,n){const o=Math.max(0,Math.min(t,e.length));return e.slice(0,o)+n+e.slice(o)}function Kx(e,t){const n=e.indexOf(t);return n<0?e:e.slice(0,n)+e.slice(n+t.length)}function _s({value:e,onChange:t,t:n,candidates:o,onDone:r,testidPrefix:s="g7le-binding-chip-text",disabled:a=!1}){const l=u.useMemo(()=>Wx(e),[e]),d=u.useRef(null),c=!!o&&o.length>0,[p,f]=u.useState(null),[b,g]=u.useState(null),[m,h]=u.useState(null),[v,y]=u.useState(!1),_=u.useRef(0),w=u.useRef(null),k=u.useMemo(()=>l.map(P=>P.kind==="chip"?`c:${P.raw}`:"t").join("|"),[l]),x=u.useRef(null),$=u.useRef([]),S=u.useRef(!1);u.useLayoutEffect(()=>{const P=S.current;S.current=!1,!(!P&&x.current===k)&&(x.current=k,l.forEach((I,L)=>{if(I.kind!=="text")return;const F=$.current[L];F&&F.textContent!==(I.text??"")&&(F.textContent=I.text??"")}))},[k,l,e]);const C=u.useCallback(()=>{const P=d.current;if(!P)return e;const I=[];for(const L of Array.from(P.querySelectorAll("[data-seg]")))L.dataset.seg==="chip"?I.push(L.dataset.raw??""):I.push(L.textContent??"");return I.join("")},[e]),T=u.useCallback(()=>{a||t(C())},[a,t,C]),E=u.useRef(null),A=u.useRef(!1),N=(P,I)=>{if(!a){P.preventDefault(),P.stopPropagation(),E.current={raw:I,pointerId:P.pointerId},A.current=!1,f(I);try{P.currentTarget.setPointerCapture(P.pointerId)}catch{}}},D=P=>{const I=E.current;if(!I||P.pointerId!==I.pointerId)return;A.current=!0;const L=O(P.clientX,P.clientY);L&&(g({slotIdx:L.slotIdx,offset:L.offset}),h(Ux(d.current,L.slotIdx,L.offset)))},B=(P,I)=>{if(P.stopPropagation(),A.current){A.current=!1;return}S.current=!0,t(Kx(e,I))},M=P=>{const I=E.current;if(!I||P.pointerId!==I.pointerId)return;try{P.currentTarget.releasePointerCapture(P.pointerId)}catch{}E.current=null,A.current&&typeof setTimeout=="function"&&setTimeout(()=>{A.current=!1},0);const L=O(P.clientX,P.clientY);if(f(null),g(null),h(null),!L)return;const F=d.current;if(!F)return;const K=Array.from(F.querySelectorAll("[data-seg]")).map(Z=>Z.dataset.seg==="chip"?{kind:"chip",raw:Z.dataset.raw??""}:{kind:"text",text:Z.textContent??""}),X=Hx(K,I.raw,L.slotIdx,L.offset);X!==e&&(S.current=!0,t(X))},O=(P,I)=>{const L=d.current;if(!L)return null;const F=Array.from(L.querySelectorAll("[data-seg]")),Y=L.ownerDocument,K=Y.elementFromPoint(P,I),X=K?.closest('[data-seg="text"]');if(X)return{slotIdx:F.indexOf(X),offset:Vx(Y,X,P,I)};const Z=K?.closest('[data-seg="chip"]');if(Z){const oe=F.indexOf(Z),G=Z.getBoundingClientRect();if(P=0){const ee=F[oe-1];return{slotIdx:oe-1,offset:(ee.textContent??"").length}}if(oe+1({s:oe,i:G})).filter(oe=>oe.s.dataset.seg==="text").pop();return se?{slotIdx:se.i,offset:(se.s.textContent??"").length}:null},z=()=>{a||!c||(_.current=qx(d.current,e.length),y(P=>!P))},H=P=>{const I=P.path?P.path.split(".").filter(Boolean):[],L=[P.sourceId,...I].join("?.");S.current=!0,t(Fx(e,_.current,`{{${L}}}`)),y(!1)};return i.jsxs("div",{"data-testid":s,style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsxs("div",{ref:d,"data-testid":`${s}-box`,className:"g7le-binding-chip-input",style:Gx,children:[l.map((P,I)=>P.kind==="chip"?i.jsxs("span",{"data-seg":"chip","data-raw":P.raw,"data-testid":`${s}-chip-${I}`,contentEditable:!1,onPointerDown:L=>N(L,P.raw??""),onPointerMove:D,onPointerUp:M,title:P.removable?n("layout_editor.value_tree.change_data"):n("layout_editor.prop_i18n.bound_code_only"),style:{...Zx,...p===P.raw?Qx:null,touchAction:"none"},children:[i.jsx("span",{"aria-hidden":"true",style:Rx,children:"⠿"}),i.jsx("span",{"aria-hidden":"true",style:{marginRight:3},children:"🔗"}),i.jsx("span",{children:P.text}),P.removable&&!a&&i.jsx("button",{type:"button","data-testid":`${s}-chip-remove-${I}`,"aria-label":n("layout_editor.inline_binding.clear"),title:n("layout_editor.inline_binding.clear"),onPointerDown:L=>{L.stopPropagation(),L.preventDefault()},onClick:L=>B(L,P.raw??""),style:ew,children:"✕"})]},`chip-${P.raw}-${I}`):i.jsx("span",{ref:L=>{$.current[I]=L},"data-seg":"text",contentEditable:!a,suppressContentEditableWarning:!0,onInput:T,"data-testid":`${s}-text-${I}`,style:{...Yx,...p?Xx:null,...b?.slotIdx===I?Jx:null}},`text-slot-${I}`)),m&&i.jsx("span",{"aria-hidden":"true","data-testid":`${s}-caret`,style:{position:"absolute",left:m.left,top:m.top,width:2,height:m.height,background:"#2563eb",borderRadius:1,pointerEvents:"none",boxShadow:"0 0 0 1px rgba(37,99,235,0.3)"}})]}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[r&&i.jsxs("button",{type:"button","data-testid":`${s}-done`,onClick:r,style:mc,title:n("layout_editor.value_tree.done"),"aria-label":n("layout_editor.value_tree.done"),children:["✓ ",n("layout_editor.value_tree.done")]}),c&&i.jsxs("div",{style:{position:"relative"},children:[i.jsxs("button",{ref:w,type:"button","data-testid":`${s}-insert`,onClick:z,disabled:a,style:mc,title:n("layout_editor.inline_binding.insert_data"),"aria-label":n("layout_editor.inline_binding.insert_data"),children:["+ ",n("layout_editor.inline_binding.insert_data")]}),i.jsx(Xn,{anchorRef:w,open:v,onClose:()=>y(!1),children:i.jsx($t,{candidates:o,t:n,onSelect:H,testIdSuffix:`${s}-insert`,defaultOpen:!0,floating:!1})})]}),i.jsx("span",{style:tw,children:n("layout_editor.translation.placeholder_locked")})]})]})}function Vx(e,t,n,o){const r=(t.textContent??"").length;try{const a=e;let l=null,d=0;if(typeof a.caretRangeFromPoint=="function"){const c=a.caretRangeFromPoint(n,o);c&&(l=c.startContainer,d=c.startOffset)}else if(typeof a.caretPositionFromPoint=="function"){const c=a.caretPositionFromPoint(n,o);c&&(l=c.offsetNode,d=c.offset)}if(l&&t.contains(l))return Math.max(0,Math.min(d,r))}catch{}const s=t.getBoundingClientRect();return n>s.left+s.width/2?r:0}function Ux(e,t,n){if(!e)return null;const r=Array.from(e.querySelectorAll("[data-seg]"))[t];if(!r)return null;const s=e.getBoundingClientRect();try{const d=r.firstChild,c=e.ownerDocument;if(d&&d.nodeType===Node.TEXT_NODE&&(d.textContent??"").length>0){const p=c.createRange(),f=Math.max(0,Math.min(n,(d.textContent??"").length));p.setStart(d,f),p.setEnd(d,f);const b=p.getClientRects(),g=b.length>0?b[0]:p.getBoundingClientRect();if(g&&(g.height>0||g.width>=0))return{left:g.left-s.left,top:g.top-s.top,height:g.height||r.getBoundingClientRect().height}}}catch{}const a=r.getBoundingClientRect();return{left:(n>0?a.right:a.left)-s.left,top:a.top-s.top,height:a.height||16}}function qx(e,t){if(!e)return t;try{const n=e.ownerDocument.defaultView?.getSelection();if(!n||n.rangeCount===0)return t;const o=n.getRangeAt(0);let r=o.startContainer,s=null;for(;r&&r!==e;){if(r instanceof HTMLElement&&r.dataset.seg==="text"){s=r;break}r=r.parentNode}if(!s||!e.contains(s))return t;const a=Array.from(e.querySelectorAll("[data-seg]"));let l=0;for(const d of a){if(d===s)break;l+=d.dataset.seg==="chip"?(d.dataset.raw??"").length:(d.textContent??"").length}return l+o.startOffset}catch{return t}}const Gx={position:"relative",display:"flex",flexWrap:"wrap",alignItems:"center",gap:2,minHeight:30,padding:"4px 8px",border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",fontSize:12,lineHeight:1.6,minWidth:0,width:"100%",boxSizing:"border-box"},Yx={outline:"none",minWidth:8,minHeight:"1.2em",whiteSpace:"pre-wrap",color:"#0f172a",display:"inline-block",wordBreak:"break-all"},Xx={boxShadow:"inset 0 -2px 0 #93c5fd",background:"#eff6ff",borderRadius:2},Jx={background:"#dbeafe",boxShadow:"inset 0 -2px 0 #2563eb"},Zx={display:"inline-flex",alignItems:"center",gap:1,background:"linear-gradient(180deg,#eff6ff,#dbeafe)",color:"#1d4ed8",border:"1px dashed #60a5fa",borderRadius:9999,padding:"1px 8px 1px 4px",margin:"0 1px",fontSize:11,fontWeight:600,cursor:"grab",userSelect:"none",whiteSpace:"nowrap",boxShadow:"0 1px 2px rgba(37,99,235,0.18)",verticalAlign:"middle"},Qx={opacity:.5,borderStyle:"solid",cursor:"grabbing"},Rx={color:"#2563eb",opacity:.7,fontSize:11,marginRight:1,cursor:"grab"},ew={marginLeft:4,width:14,height:14,lineHeight:"12px",padding:0,border:"none",borderRadius:9999,background:"rgba(29,78,216,0.12)",color:"#1d4ed8",fontSize:9,fontWeight:700,cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"0 0 auto"},mc={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},tw={fontSize:10,color:"#94a3b8"},nw=Jl;function xs(e){return Eb(e)}function Ke({value:e,onChange:t,t:n,candidates:o,placeholder:r,testidPrefix:s="g7le-data-chip-value",readOnly:a=!1,enableExpressionTree:l=!0}){const d=typeof e=="string"?e:"",c=!!o&&o.length>0,[p,f]=u.useState(!1),[b,g]=u.useState(!1),[m,h]=u.useState(!1),v=u.useCallback(S=>i.jsx(Ke,{value:S.value,onChange:C=>S.onChange(C),t:S.t,candidates:S.candidates,testidPrefix:S.testidPrefix,enableExpressionTree:!0}),[]),y=()=>i.jsx("div",{style:{display:"flex",gap:4,alignItems:"center",width:"100%",minWidth:0},children:i.jsx("input",{type:"text","data-testid":`${s}-input`,value:d,placeholder:r??n("layout_editor.page_settings.seo.value_placeholder"),readOnly:a,onChange:S=>t(S.target.value),onFocus:()=>f(!0),onBlur:()=>f(!1),style:{flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:0,width:"100%",background:a?"#f1f5f9":"#fff",color:a?"#64748b":"#0f172a"}})}),_=u.useCallback(S=>{const C=d?`${d} ${S.expression}`:S.expression;t(C)},[d,t]);if(!l||a)return i.jsxs("div",{"data-testid":s,style:pn,children:[y(),!a&&c&&i.jsx($t,{candidates:o,t:n,onSelect:_,testIdSuffix:`${s}-pick`})]});const w=Wv(d),k=Zd(d),x=Kt(d),$=S=>{const C=Er(d),T=C?gs(C,()=>"",E=>Vt(E)):[];return i.jsxs(i.Fragment,{children:[i.jsx("div",{style:{display:"flex",justifyContent:"flex-start"},children:i.jsxs("button",{type:"button","data-testid":`${S}-to-plain`,onClick:()=>h(!0),style:sw,title:n("layout_editor.value_tree.to_plain"),"aria-label":n("layout_editor.value_tree.to_plain"),children:["↩ ",n("layout_editor.value_tree.to_plain")]})}),m&&i.jsxs("div",{"data-testid":`${S}-to-plain-confirm`,style:aw,children:[i.jsx("p",{style:lw,children:n("layout_editor.value_tree.to_plain_lead")}),i.jsx("div",{style:dw,children:T.length===0?i.jsx("span",{style:{color:"#94a3b8"},children:n("layout_editor.page_settings.seo.value_placeholder")}):T.map((E,A)=>E.kind==="chip"?i.jsxs("span",{style:ws,children:["🔗 ",E.text]},A):i.jsx("span",{style:E.kind==="ellipsis"?{color:"#94a3b8"}:void 0,children:E.text},A))}),i.jsxs("p",{style:cw,children:["⚠ ",n("layout_editor.value_tree.to_plain_warn")]}),i.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:6},children:[i.jsx("button",{type:"button","data-testid":`${S}-to-plain-confirm-cancel`,onClick:()=>h(!1),style:Ut,children:n("layout_editor.value_tree.to_plain_cancel")}),i.jsx("button",{type:"button","data-testid":`${S}-to-plain-confirm-ok`,onClick:()=>{h(!1),t(Er(d)||"")},style:uw,children:n("layout_editor.value_tree.to_plain_ok")})]})]})]})};if(!p&&(w==="expression"||k)){if(k)return i.jsxs("div",{"data-testid":s,style:pn,children:[!a&&$(`${s}-seg`),i.jsx(bs,{value:d,onChange:C=>t(C),t:n,candidates:o,testidPrefix:`${s}-seg`,renderLeafInput:v})]});const S=un(d);return i.jsxs("div",{"data-testid":s,style:pn,children:[!a&&$(`${s}-tree`),i.jsx(sc,{node:S.node,onChange:C=>t(Zn(C,!1)),t:n,candidates:o,testidPrefix:`${s}-tree`,renderLeafInput:v})]})}if(x&&!p&&!b)return i.jsx(ow,{value:d,onChange:t,t:n,candidates:o,testidPrefix:s,onEditRaw:()=>g(!0)});if(!p&&!b&&xs(d)){const S=nw(d);return i.jsx("div",{"data-testid":s,style:pn,children:i.jsxs("div",{style:vc,children:[i.jsx("div",{"data-testid":`${s}-chips`,style:rw,children:S.map((C,T)=>C.kind==="chip"?i.jsxs("span",{style:ws,children:["🔗 ",C.label]},T):i.jsx("span",{children:C.label},T))}),i.jsxs("button",{type:"button","data-testid":`${s}-edit-raw`,onClick:()=>g(!0),style:Ut,title:n("layout_editor.value_tree.edit"),"aria-label":n("layout_editor.value_tree.edit"),children:["✎ ",n("layout_editor.value_tree.edit")]})]})})}return b&&xs(d)?i.jsxs("div",{"data-testid":s,style:pn,children:[i.jsx(_s,{value:d,onChange:t,t:n,candidates:o,disabled:a,onDone:()=>g(!1),testidPrefix:`${s}-chipedit`}),!a&&w!=="raw"&&i.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:[i.jsxs("button",{type:"button","data-testid":`${s}-to-expr`,onClick:()=>t($o(d)),style:Ut,title:n("layout_editor.value_tree.to_expression"),"aria-label":n("layout_editor.value_tree.to_expression"),children:["ƒx ",n("layout_editor.value_tree.to_expression")]}),i.jsxs("button",{type:"button","data-testid":`${s}-to-fallback`,onClick:()=>t(hs(d)),style:Ut,title:n("layout_editor.value_tree.segment.fallback"),"aria-label":n("layout_editor.value_tree.segment.fallback"),children:["?? ",n("layout_editor.value_tree.segment.fallback")]})]}),w==="raw"&&i.jsxs("p",{"data-testid":`${s}-raw-hint`,style:ks,children:["ⓘ ",n("layout_editor.value_tree.raw_expression_hint")]})]}):!p&&xs(d)?i.jsxs("div",{"data-testid":s,style:pn,children:[i.jsx(_s,{value:d,onChange:t,t:n,candidates:o,disabled:a,onDone:()=>{g(!1),f(!1)},testidPrefix:`${s}-chipedit`}),!a&&w!=="raw"&&i.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:[i.jsxs("button",{type:"button","data-testid":`${s}-to-expr`,onClick:()=>t($o(d)),style:Ut,title:n("layout_editor.value_tree.to_expression"),"aria-label":n("layout_editor.value_tree.to_expression"),children:["ƒx ",n("layout_editor.value_tree.to_expression")]}),i.jsxs("button",{type:"button","data-testid":`${s}-to-fallback`,onClick:()=>t(hs(d)),style:Ut,title:n("layout_editor.value_tree.segment.fallback"),"aria-label":n("layout_editor.value_tree.segment.fallback"),children:["?? ",n("layout_editor.value_tree.segment.fallback")]})]}),w==="raw"&&i.jsxs("p",{"data-testid":`${s}-raw-hint`,style:ks,children:["ⓘ ",n("layout_editor.value_tree.raw_expression_hint")]})]}):i.jsxs("div",{"data-testid":s,style:pn,children:[y(),i.jsxs("div",{style:iw,children:[c&&i.jsx($t,{candidates:o,t:n,onSelect:_,testIdSuffix:`${s}-pick`}),w!=="raw"&&i.jsxs("div",{style:{display:"flex",gap:4},children:[i.jsxs("button",{type:"button","data-testid":`${s}-to-expr`,onClick:()=>t($o(d)),style:Ut,title:n("layout_editor.value_tree.to_expression"),"aria-label":n("layout_editor.value_tree.to_expression"),children:["ƒx ",n("layout_editor.value_tree.to_expression")]}),i.jsxs("button",{type:"button","data-testid":`${s}-to-fallback`,onClick:()=>t(hs(d)),style:Ut,title:n("layout_editor.value_tree.segment.fallback"),"aria-label":n("layout_editor.value_tree.segment.fallback"),children:["?? ",n("layout_editor.value_tree.segment.fallback")]})]})]}),w==="raw"&&!p&&i.jsxs("p",{"data-testid":`${s}-raw-hint`,style:ks,children:["ⓘ ",n("layout_editor.value_tree.raw_expression_hint")]})]})}function ow({value:e,onChange:t,t:n,candidates:o,testidPrefix:r,onEditRaw:s}){const[a,l]=u.useState(!1),d=u.useRef(null),c=Vt(e),p=!!o&&o.length>0,f=Kt(e)?.localeFn;return i.jsxs("div",{"data-testid":r,style:pn,children:[i.jsxs("div",{style:vc,children:[i.jsxs("span",{"data-testid":`${r}-chip`,style:ws,children:["🔗 ",c]}),p&&i.jsx("button",{ref:d,type:"button","data-testid":`${r}-change`,onClick:()=>l(b=>!b),style:Ut,title:n("layout_editor.value_tree.change_data"),"aria-label":n("layout_editor.value_tree.change_data"),children:n("layout_editor.value_tree.change_data")}),i.jsx("button",{type:"button","data-testid":`${r}-edit-raw`,onClick:s,style:Ut,title:n("layout_editor.value_tree.edit"),"aria-label":n("layout_editor.value_tree.edit"),children:"✎"})]}),p&&i.jsx(Xn,{anchorRef:d,open:a,onClose:()=>l(!1),children:i.jsx($t,{candidates:o,t:n,onSelect:b=>{if(f){const h=[b.sourceId,...b.path?b.path.split(".").filter(Boolean):[]].join(".");t(`{{${f}(${h})}}`),l(!1);return}const g=b.path?b.path.split(".").filter(Boolean):[],m=[b.sourceId,...g].join("?.");t(`{{${m}}}`),l(!1)},testIdSuffix:`${r}-pick`,defaultOpen:!0,floating:!1})})]})}const pn={display:"flex",flexDirection:"column",gap:4,width:"100%",minWidth:0},vc={display:"flex",alignItems:"center",gap:6,width:"100%",minWidth:0,flexWrap:"wrap"},rw={flex:1,minWidth:0,display:"flex",flexWrap:"wrap",alignItems:"center",gap:4,padding:"5px 8px",fontSize:12,color:"#334155",border:"1px solid #e2e8f0",borderRadius:6,background:"#f8fafc"},ws={fontSize:11,background:"#eef2ff",color:"#4338ca",padding:"2px 8px",borderRadius:12,whiteSpace:"nowrap"},Ut={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},iw={display:"flex",flexWrap:"wrap",alignItems:"center",gap:6},ks={margin:"2px 0 0",fontSize:11,color:"#94a3b8",lineHeight:1.4},sw={padding:"3px 10px",fontSize:11,border:"1px solid #fca5a5",borderRadius:6,background:"#fef2f2",color:"#b91c1c",cursor:"pointer",whiteSpace:"nowrap"},aw={display:"flex",flexDirection:"column",gap:6,padding:10,border:"1px solid #fca5a5",borderRadius:8,background:"#fffbeb"},lw={margin:0,fontSize:12,color:"#334155"},dw={padding:"5px 8px",fontSize:12,color:"#0f172a",background:"#fff",border:"1px solid #e2e8f0",borderRadius:6,wordBreak:"break-all",display:"flex",flexWrap:"wrap",gap:4,alignItems:"center"},cw={margin:0,fontSize:11,color:"#b45309"},uw={padding:"3px 12px",fontSize:11,border:"1px solid #dc2626",borderRadius:6,background:"#dc2626",color:"#fff",cursor:"pointer",whiteSpace:"nowrap"};let _c=0;function Pr({value:e,onChange:t,keyField:n,valueField:o="content",t:r,candidates:s,testidPrefix:a="g7le-kv-chip-editor",keyPlaceholder:l,valuePlaceholder:d,addLabel:c,renderKeyInput:p}){const f=u.useMemo(()=>(Array.isArray(e)?e:[]).map(w=>({id:_c++,k:typeof w[n]=="string"?w[n]:"",v:typeof w[o]=="string"?w[o]:""})),[]),[b,g]=u.useState(f),m=u.useCallback(w=>{g(w);const k=w.filter(x=>x.k.trim()!=="").map(x=>({[n]:x.k,[o]:x.v}));t(k)},[n,o,t]),h=u.useCallback(()=>{m([...b,{id:_c++,k:"",v:""}])},[b,m]),v=u.useCallback(w=>{m(b.filter(k=>k.id!==w))},[b,m]),y=u.useCallback((w,k)=>{m(b.map(x=>x.id===w?{...x,k}:x))},[b,m]),_=u.useCallback((w,k)=>{m(b.map(x=>x.id===w?{...x,v:k}:x))},[b,m]);return i.jsxs("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:6},children:[b.map(w=>i.jsxs("div",{"data-testid":`${a}-row-${w.id}`,style:{display:"flex",gap:6,alignItems:"flex-start",border:"1px solid #e2e8f0",borderRadius:8,padding:8},children:[i.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:6},children:[i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:2,minWidth:0},children:p?i.jsx("div",{style:{minWidth:0},children:p({value:w.k,onChange:k=>y(w.id,k),testid:`${a}-key-${w.id}`,placeholder:l??r(`layout_editor.page_settings.seo.extra_${n}`)})}):i.jsx("input",{type:"text","data-testid":`${a}-key-${w.id}`,value:w.k,placeholder:l??r(`layout_editor.page_settings.seo.extra_${n}`),onChange:k=>y(w.id,k.target.value),style:{width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:0,boxSizing:"border-box"}})}),i.jsx("div",{style:{minWidth:0},children:i.jsx(Ke,{value:w.v,onChange:k=>_(w.id,k),t:r,candidates:s,placeholder:d??r("layout_editor.page_settings.seo.extra_content"),testidPrefix:`${a}-value-${w.id}`})})]}),i.jsx("button",{type:"button","data-testid":`${a}-remove-${w.id}`,onClick:()=>v(w.id),title:r("layout_editor.page_settings.seo.remove"),"aria-label":r("layout_editor.page_settings.seo.remove"),style:{flex:"0 0 auto",padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"},children:"✕"})]},w.id)),i.jsxs("button",{type:"button","data-testid":`${a}-add`,onClick:h,style:{alignSelf:"flex-start",padding:"5px 10px",fontSize:12,border:"1px dashed #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},children:["+ ",c??r("layout_editor.page_settings.seo.add_extra")]})]})}const pw=["website","article","product","profile"],fw=["summary","summary_large_image","app","player"];function gw(e){switch(e){case"core":return"layout_editor.page_settings.seo.og_source_core";case"inherited":return"layout_editor.page_settings.seo.og_source_inherited";case"filter":return"layout_editor.page_settings.seo.og_source_filter";case"layout":return null;default:return e?"layout_editor.page_settings.seo.og_source_module":null}}function xc(e){const t={};for(const n of e??[])t[n.key]=n;return t}function wc(e,t){return!!e&&t&&typeof e.sourceExpr=="string"&&e.sourceExpr!==""&&!e.overriddenByLayout&&!e.lockedByFilter}function kc({label:e,sourceExpr:t,onReplace:n,t:o,testid:r}){return i.jsxs("div",{"data-testid":r,style:Sw,children:[i.jsxs("span",{"data-testid":`${r}-chip`,style:Cw,title:t,children:["🔗 ",e||t]}),i.jsx("span",{"data-testid":`${r}-badge`,style:$w,children:o("layout_editor.page_settings.seo.auto_chip_source")}),i.jsx("button",{type:"button","data-testid":`${r}-replace`,onClick:n,style:Ew,children:o("layout_editor.page_settings.seo.auto_chip_replace")})]})}function hw({og:e,twitter:t,onChangeOg:n,onChangeTwitter:o,ogPreview:r,twitterPreview:s,defaultsAvailable:a=!1,candidates:l,t:d,testidPrefix:c="g7le-seo-og"}){const p=e&&typeof e=="object"?e:{},f=t&&typeof t=="object"?t:{},[b,g]=u.useState(p.image_height!=null||p.image_type!=null||p.image_secure_url!=null),m=xc(r),h=xc(s),v=u.useCallback((T,E)=>{const A={...p};E===void 0||E===""||E===null?delete A[T]:A[T]=E,n(A)},[p,n]),y=u.useCallback((T,E)=>{const A={...f};E===void 0||E===""||E===null?delete A[T]:A[T]=E,o(A)},[f,o]),_=(T,E,A)=>!A||!a||!A.lockedByFilter?null:i.jsx("div",{style:{display:"flex",gap:6,alignItems:"center",marginTop:2},children:i.jsxs("span",{"data-testid":`${T}-locked-${E}`,style:xw,children:["🔒 ",d("layout_editor.page_settings.seo.og_locked")]})}),w=T=>{if(!T||!a||T.lockedByFilter||T.overriddenByLayout)return;const E=gw(T.source);return E?d(E):void 0},k=(T,E)=>T&&a?T.overriddenByLayout===!0:E!=="",x=(T,E,A,N,D,B)=>{const M=B[E],O=!!M?.lockedByFilter,z=typeof N[E]=="string"?N[E]:"";return i.jsxs("div",{"data-testid":`${T}-${E}`,style:Dn,children:[i.jsx("label",{style:to,children:d(A)}),O?i.jsx("div",{"data-testid":`${T}-locked-value-${E}`,style:_w,children:String(M?.effectiveValue??"")}):wc(M,a)?i.jsx(kc,{label:M.label??"",sourceExpr:M.sourceExpr,onReplace:()=>D(E,M.sourceExpr),t:d,testid:`${T}-${E}-auto`}):i.jsx(_t,{value:z,onChange:H=>D(E,H??""),t:d,candidates:l,placeholder:a&&M?.effectiveValue!=null?String(M.effectiveValue):void 0,testidPrefix:`${T}-${E}-field`,enableExpressionTree:!0,expressionTreeCollapsible:!0}),_(T,E,M)]})},$=(T,E,A,N,D,B)=>{const M=B[E],O=!!M?.lockedByFilter,z=typeof N[E]=="string"?N[E]:"";return i.jsxs("div",{"data-testid":`${T}-${E}`,style:Dn,children:[i.jsx("label",{style:to,children:d(A)}),wc(M,a)?i.jsx(kc,{label:M.label??"",sourceExpr:M.sourceExpr,onReplace:()=>D(E,M.sourceExpr),t:d,testid:`${T}-${E}-auto`}):i.jsx(Ke,{value:z,onChange:H=>D(E,H),t:d,candidates:l,readOnly:O,placeholder:a&&M?.effectiveValue!=null?String(M.effectiveValue):void 0,testidPrefix:`${T}-${E}-field`}),_(T,E,M)]})},S=(T,E,A,N,D,B)=>{const M=B[E],O=!!M?.lockedByFilter,z=typeof N[E]=="string"?N[E]:"",H=k(M,z),P=H?z:"";return i.jsxs("div",{"data-testid":`${T}-${E}`,style:Dn,children:[i.jsx("label",{style:to,children:d(A)}),i.jsx(Tx,{filled:H,sourceLabel:w(M),onRevert:O?void 0:()=>D(E,void 0),revertLabel:d("layout_editor.page_settings.seo.revert_default"),testid:`${T}-${E}-overlay`,children:i.jsx("div",{"data-testid":`${T}-${E}-input`,style:{minWidth:0},children:i.jsx(Ke,{value:P,onChange:I=>D(E,I),t:d,candidates:l,readOnly:O,placeholder:a&&M?.effectiveValue!=null?String(M.effectiveValue):void 0,testidPrefix:`${T}-${E}-chip`})})}),_(T,E,M)]})},C=(T,E,A,N,D,B,M)=>{const O=M[E],z=typeof D[E]=="string"?D[E]:"",H=k(O,z),P=w(O),I=H?z:"";return i.jsxs("div",{"data-testid":`${T}-${E}`,style:Dn,children:[i.jsxs("div",{style:bw,children:[i.jsx("label",{style:to,children:d(A)}),P?i.jsxs("span",{"data-testid":`${T}-${E}-source-inline`,style:mw,children:["· ",P]}):null]}),i.jsxs("select",{"data-testid":`${T}-${E}-select`,value:I,onChange:L=>B(E,L.target.value),style:vw,children:[i.jsx("option",{value:"",children:a&&O?.effectiveValue!=null&&O.effectiveValue!==""?`${d("layout_editor.page_settings.seo.use_default")} (${String(O.effectiveValue)})`:d("layout_editor.page_settings.seo.use_default")}),N.map(L=>i.jsx("option",{value:L,children:L},L))]}),_(T,E,O)]})};return i.jsxs("div",{"data-testid":c,style:{display:"flex",flexDirection:"column",gap:12},children:[i.jsxs("div",{"data-testid":`${c}-og-section`,style:Sc,children:[i.jsx("div",{style:Cc,children:d("layout_editor.page_settings.seo.og_section")}),i.jsxs("p",{"data-testid":`${c}-intro`,style:yw,children:["ⓘ ",d("layout_editor.page_settings.seo.og_intro")]}),C(c,"type","layout_editor.page_settings.seo.og_type",pw,p,v,m),x(c,"title","layout_editor.page_settings.seo.og_title",p,v,m),x(c,"description","layout_editor.page_settings.seo.og_description",p,v,m),$(c,"image","layout_editor.page_settings.seo.og_image",p,v,m),x(c,"image_alt","layout_editor.page_settings.seo.og_image_alt",p,v,m),i.jsxs("div",{style:Dn,children:[i.jsxs("button",{type:"button","data-testid":`${c}-image-adv-toggle`,"aria-expanded":b,onClick:()=>g(T=>!T),style:ww,children:[b?"▾":"▸"," ",d("layout_editor.page_settings.seo.og_image_adv")]}),b?i.jsxs("div",{"data-testid":`${c}-image-adv`,style:kw,children:[S(c,"image_height","layout_editor.page_settings.seo.og_image_height",p,v,m),S(c,"image_type","layout_editor.page_settings.seo.og_image_type",p,v,m),S(c,"image_secure_url","layout_editor.page_settings.seo.og_image_secure_url",p,v,m)]}):null]}),S(c,"site_name","layout_editor.page_settings.seo.og_site_name",p,v,m),S(c,"locale","layout_editor.page_settings.seo.og_locale",p,v,m),i.jsxs("div",{"data-testid":`${c}-extra`,style:Dn,children:[i.jsx("label",{style:to,children:d("layout_editor.page_settings.seo.og_extra")}),i.jsx(Pr,{value:Array.isArray(p.extra)?p.extra:[],onChange:T=>v("extra",T.length>0?T:void 0),keyField:"property",t:d,candidates:l,testidPrefix:`${c}-extra-editor`})]})]}),i.jsxs("div",{"data-testid":`${c}-tw-section`,style:Sc,children:[i.jsx("div",{style:Cc,children:d("layout_editor.page_settings.seo.tw_section")}),i.jsx("p",{style:{margin:"0 0 6px",fontSize:11,color:"#94a3b8"},children:d("layout_editor.page_settings.seo.tw_fallback_note")}),C("g7le-seo-tw","card","layout_editor.page_settings.seo.tw_card",fw,f,y,h),S("g7le-seo-tw","site","layout_editor.page_settings.seo.tw_site",f,y,h),S("g7le-seo-tw","creator","layout_editor.page_settings.seo.tw_creator",f,y,h),x("g7le-seo-tw","title","layout_editor.page_settings.seo.tw_title",f,y,h),x("g7le-seo-tw","description","layout_editor.page_settings.seo.tw_description",f,y,h),$("g7le-seo-tw","image","layout_editor.page_settings.seo.tw_image",f,y,h),x("g7le-seo-tw","image_alt","layout_editor.page_settings.seo.tw_image_alt",f,y,h),i.jsxs("div",{"data-testid":"g7le-seo-tw-extra",style:Dn,children:[i.jsx("label",{style:to,children:d("layout_editor.page_settings.seo.tw_extra")}),i.jsx(Pr,{value:Array.isArray(f.extra)?f.extra:[],onChange:T=>y("extra",T.length>0?T:void 0),keyField:"name",t:d,candidates:l,testidPrefix:"g7le-seo-tw-extra-editor"})]})]})]})}const Sc={border:"1px solid #e2e8f0",borderRadius:8,padding:12,display:"flex",flexDirection:"column",gap:10},Cc={fontSize:13,fontWeight:600,color:"#0f172a"},yw={margin:0,fontSize:11,color:"#64748b",background:"#f8fafc",borderRadius:6,padding:"6px 8px"},Dn={display:"flex",flexDirection:"column",gap:4},to={fontSize:12,color:"#475569"},bw={display:"flex",alignItems:"center",gap:6},mw={fontSize:11,color:"#94a3b8"},vw={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",minWidth:0,boxSizing:"border-box"},_w={padding:"5px 8px",fontSize:12,border:"1px solid #e2e8f0",borderRadius:6,background:"#f1f5f9",color:"#64748b"},xw={fontSize:11,color:"#7c3aed"},ww={alignSelf:"flex-start",padding:"2px 0",fontSize:12,fontWeight:600,color:"#475569",background:"transparent",border:"none",cursor:"pointer"},kw={display:"flex",flexDirection:"column",gap:8,paddingLeft:14,marginTop:4,minWidth:0},Sw={display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",minWidth:0},Cw={display:"inline-flex",alignItems:"center",maxWidth:"100%",padding:"3px 8px",fontSize:12,color:"#1d4ed8",background:"#eff6ff",border:"1px solid #bfdbfe",borderRadius:6,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},$w={fontSize:11,color:"#94a3b8"},Ew={padding:"2px 8px",fontSize:11,color:"#475569",background:"#fff",border:"1px solid #cbd5e1",borderRadius:6,cursor:"pointer"},Iw=["WebPage","WebSite","ItemList","BreadcrumbList","Organization","Person","CollectionPage","AboutPage","ContactPage","SearchAction"];function Or(e){const t=[],n=(o,r)=>{for(const[s,a]of Object.entries(o)){if(s==="@type"||s==="@context")continue;const l=r?`${r}.${s}`:s;a!==null&&typeof a=="object"&&!Array.isArray(a)?n(a,l):t.push({key:l,value:a==null?"":String(a)})}};return n(e,""),t}function $c(e,t){const n={"@type":e};for(const{key:o,value:r}of t){if(o.trim()==="")continue;const s=o.split(".");let a=n;for(let l=0;lp?Or(e).map(D=>({id:Ss++,...D})):[]),_=u.useCallback((D,B)=>{h(D),y(B),t($c(D,B.map(M=>({key:M.key,value:M.value}))))},[t]),w=u.useCallback(()=>{const D=n,B=typeof D["@type"]=="string"?D["@type"]:m,M=Or(D).map(O=>({id:Ss++,key:O.key,value:o?.[O.key]?.expr??O.value}));return{type:B,rows:M}},[n,o,m]),k=u.useCallback(D=>{if(b(D),D){if(v.length===0&&n&&typeof n=="object"){const B=w();_(B.type,B.rows);return}t($c(m,v.map(B=>({key:B.key,value:B.value}))))}else t(null)},[m,v,n,w,_,t]),x=u.useCallback(()=>{if(!n)return;const D=w();_(D.type,D.rows)},[n,w,_]),$=u.useCallback(()=>{_(m,[...v,{id:Ss++,key:"",value:""}])},[m,v,_]),S=u.useCallback(D=>{_(m,v.filter(B=>B.id!==D))},[m,v,_]),C=u.useCallback((D,B)=>{_(m,v.map(M=>M.id===D?{...M,key:B}:M))},[m,v,_]),T=u.useCallback((D,B)=>{_(m,v.map(M=>M.id===D?{...M,value:B}:M))},[m,v,_]),E=u.useMemo(()=>n?Or(n):[],[n]),A=u.useMemo(()=>s?Or(s):[],[s]),N=v.some(D=>D.key.trim()!==""&&D.value.trim()==="");if(r){const D=s&&typeof s["@type"]=="string"?s["@type"]:"";return i.jsxs("div",{"data-testid":c,style:Ec,children:[i.jsxs("div",{style:Ic,children:[i.jsx("span",{style:Tw,children:"🔒"}),i.jsx("span",{style:{fontSize:13,fontWeight:600},children:d("layout_editor.page_settings.seo.sd_mode")}),i.jsx("span",{"data-testid":`${c}-locked-badge`,style:Dw,children:d("layout_editor.page_settings.seo.sd_filter_locked")})]}),i.jsxs("div",{"data-testid":`${c}-locked`,style:zw,children:[i.jsxs("p",{style:{margin:"0 0 6px",fontSize:12,color:"#475569"},children:["ⓘ ",d("layout_editor.page_settings.seo.sd_filter_locked_note")]}),i.jsxs("div",{"data-testid":`${c}-filtered-block`,children:[D?i.jsxs("div",{style:{fontSize:12,fontWeight:600,marginBottom:4},children:["@type: ",D]}):null,A.map(B=>i.jsxs("div",{"data-testid":`${c}-filtered-row-${B.key}`,style:Ac,children:[i.jsx("code",{style:Tc,children:B.key}),i.jsx("span",{style:Dc,children:B.value})]},B.key))]})]})]})}return i.jsxs("div",{"data-testid":c,style:Ec,children:[i.jsx("div",{style:Ic,children:i.jsx(Mr,{checked:f,onChange:k,testid:`${c}-mode`,label:d("layout_editor.page_settings.seo.sd_manual_toggle")})}),!f&&i.jsxs("div",{"data-testid":`${c}-auto`,style:{marginTop:8},children:[i.jsxs("div",{"data-testid":`${c}-auto-preview`,style:Nw,children:[i.jsxs("div",{style:{fontSize:12,fontWeight:600,marginBottom:6},children:[d("layout_editor.page_settings.seo.sd_auto_title"),n&&typeof n["@type"]=="string"?`: ${n["@type"]}`:"",a?i.jsxs("span",{style:{marginLeft:6,color:"#94a3b8",fontWeight:400},children:["(",a,")"]}):null]}),E.length===0?i.jsx("p",{style:{margin:0,fontSize:12,color:"#94a3b8"},children:d("layout_editor.page_settings.seo.sd_auto_empty")}):E.map(D=>{const B=o?.[D.key];return i.jsxs("div",{"data-testid":`${c}-auto-row-${D.key}`,style:Ac,children:[i.jsx("code",{style:Tc,children:D.key}),B?i.jsxs("span",{"data-testid":`${c}-auto-chip-${D.key}`,style:Mw,title:B.expr,children:["🔗 ",B.label||B.expr]}):i.jsx("span",{style:Dc,children:D.value})]},D.key)})]}),i.jsxs("p",{"data-testid":`${c}-replace-warn`,style:Lw,children:["ⓘ ",d("layout_editor.page_settings.seo.sd_replace_pre_warn")]})]}),f&&i.jsxs("div",{"data-testid":`${c}-manual`,style:{marginTop:8},children:[i.jsxs("p",{"data-testid":`${c}-replace-warn`,style:Pw,children:["⚠ ",d("layout_editor.page_settings.seo.sd_replace_warn")]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,color:"#475569"},children:d("layout_editor.page_settings.seo.sd_type")}),i.jsx("input",{type:"text","data-testid":`${c}-type`,list:`${c}-type-options`,value:m,onChange:D=>_(D.target.value,v),style:Ow}),i.jsx("datalist",{id:`${c}-type-options`,children:Iw.map(D=>i.jsx("option",{value:D},D))})]}),i.jsx("div",{style:{marginTop:8,display:"flex",flexDirection:"column",gap:6},children:v.map(D=>i.jsxs("div",{"data-testid":`${c}-prop-${D.id}`,style:Bw,children:[i.jsx("input",{type:"text","data-testid":`${c}-prop-key-${D.id}`,value:D.key,placeholder:d("layout_editor.page_settings.seo.sd_prop_key"),onChange:B=>C(D.id,B.target.value),style:{width:160,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:0}}),i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(Ke,{value:D.value,onChange:B=>T(D.id,B),t:d,candidates:l,placeholder:d("layout_editor.page_settings.seo.sd_prop_value"),testidPrefix:`${c}-prop-value-${D.id}`})}),i.jsx("button",{type:"button","data-testid":`${c}-prop-remove-${D.id}`,onClick:()=>S(D.id),title:d("layout_editor.page_settings.seo.remove"),"aria-label":d("layout_editor.page_settings.seo.remove"),style:Ww,children:"✕"})]},D.id))}),i.jsxs("div",{style:{marginTop:8,display:"flex",gap:8},children:[i.jsxs("button",{type:"button","data-testid":`${c}-add`,onClick:$,style:zc,children:["+ ",d("layout_editor.page_settings.seo.sd_add_prop")]}),n?i.jsxs("button",{type:"button","data-testid":`${c}-seed-from-module`,onClick:x,style:zc,children:["↩ ",d("layout_editor.page_settings.seo.sd_seed_from_module")]}):null]}),i.jsxs("p",{"data-testid":`${c}-empty-note`,style:jw,children:["ⓘ ",d("layout_editor.page_settings.seo.sd_empty_note"),N?i.jsxs("span",{style:{color:"#b45309"},children:[" ",d("layout_editor.page_settings.seo.sd_has_empty")]}):null]})]})]})}const Ec={display:"flex",flexDirection:"column"},Ic={display:"flex",alignItems:"center",gap:8},Tw={fontSize:14},Dw={fontSize:11,padding:"2px 6px",borderRadius:4,background:"#f1f5f9",color:"#64748b"},zw={marginTop:8,border:"1px solid #fcd34d",borderRadius:8,padding:10,background:"#fffbeb"},Nw={border:"1px solid #e2e8f0",borderRadius:8,padding:10,background:"#f8fafc"},Ac={display:"flex",gap:8,alignItems:"center",padding:"2px 0"},Tc={fontSize:11,color:"#475569",background:"#fff",padding:"2px 6px",borderRadius:4,minWidth:120},Dc={fontSize:11,color:"#0f172a",fontFamily:"monospace",wordBreak:"break-all"},Mw={display:"inline-flex",alignItems:"center",padding:"2px 8px",fontSize:11,color:"#1d4ed8",background:"#eff6ff",border:"1px solid #bfdbfe",borderRadius:6},Lw={margin:"6px 0 0",fontSize:12,color:"#64748b"},Pw={margin:"0 0 8px",fontSize:12,color:"#b45309",background:"#fffbeb",border:"1px solid #fcd34d",borderRadius:6,padding:"6px 8px"},Ow={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",minWidth:0},Bw={display:"flex",gap:6,alignItems:"flex-start",border:"1px solid #e2e8f0",borderRadius:8,padding:8},Ww={padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"},zc={padding:"5px 10px",fontSize:12,border:"1px dashed #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},jw={margin:"8px 0 0",fontSize:11,color:"#94a3b8"},Nc=new Set(["core_setting","setting","query","route"]);function Hw({vars:e,onChange:t,varCandidates:n,gatingMet:o=!1,candidates:r,t:s,testidPrefix:a="g7le-seo-vars"}){const l=u.useMemo(()=>e&&typeof e=="object"?{...e}:{},[e]),d=u.useMemo(()=>Array.isArray(n)?n:[],[n]),c=u.useMemo(()=>o?d.filter(x=>Nc.has(x.source)):[],[d,o]),p=u.useMemo(()=>o?d.filter(x=>x.source==="data"):[],[d,o]);u.useMemo(()=>new Set(c.map(x=>x.name)),[c]);const f=u.useMemo(()=>new Set(p.map(x=>x.name)),[p]),b=u.useMemo(()=>{const x=new Set;for(const $ of d)Nc.has($.source)&&x.add($.name);return x},[d]),g=u.useMemo(()=>Object.keys(l).filter(x=>!f.has(x)),[l,f]),m=u.useCallback((x,$)=>{const S={...l};$===void 0?delete S[x]:S[x]=$,t(S)},[l,t]),[h,v]=u.useState(""),y=h.trim()!==""&&b.has(h.trim()),_=h.trim()!==""&&Object.prototype.hasOwnProperty.call(l,h.trim()),w=h.trim()!==""&&!y&&!_&&!f.has(h.trim()),k=u.useCallback(()=>{const x=h.trim();x===""||b.has(x)||Object.prototype.hasOwnProperty.call(l,x)||(t({...l,[x]:""}),v(""))},[h,b,l,t]);return i.jsxs("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:10},children:[i.jsx("span",{"data-testid":"g7le-seo-var-list",hidden:!0,"data-gating":o?"1":"0"}),!o&&i.jsxs("div",{"data-testid":`${a}-precondition`,style:Fw,children:["⚠ ",s("layout_editor.page_settings.seo.vars_precondition")]}),c.length>0&&i.jsxs("div",{"data-testid":`${a}-auto-group`,style:Cs,children:[i.jsx("div",{style:$s,children:s("layout_editor.page_settings.seo.vars_auto_group")}),c.map(x=>i.jsxs("div",{"data-testid":`g7le-seo-var-auto-${x.name}`,style:Kw,children:[i.jsx("span",{style:Vw,children:"🔒"}),i.jsx("code",{style:Es,children:x.name}),i.jsxs("span",{style:Uw,children:["〔",s("layout_editor.page_settings.seo.vars_auto"),"·",x.source,"〕"]}),x.owner?.name?i.jsx("span",{style:qw,children:x.owner.name}):null]},x.name))]}),p.length>0&&i.jsxs("div",{"data-testid":`${a}-data-group`,style:Cs,children:[i.jsx("div",{style:$s,children:s("layout_editor.page_settings.seo.vars_data_group")}),p.map(x=>{const $=l[x.name]??"",S=$.trim()==="";return i.jsxs("div",{"data-testid":`g7le-seo-var-data-${x.name}`,style:Mc,children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[i.jsx("code",{style:Es,children:x.name}),x.required?i.jsx("span",{"data-testid":`g7le-seo-var-required-${x.name}`,style:Gw,children:"*"}):null]}),i.jsx(Ke,{value:$,onChange:C=>m(x.name,C??""),t:s,candidates:r,testidPrefix:`g7le-seo-var-data-field-${x.name}`}),x.required&&S?i.jsxs("p",{"data-testid":`g7le-seo-var-empty-warn-${x.name}`,style:Is,children:["⚠ ",s("layout_editor.page_settings.seo.vars_required_empty")]}):null]},x.name)})]}),i.jsxs("div",{"data-testid":`${a}-custom-group`,style:Cs,children:[i.jsx("div",{style:$s,children:s("layout_editor.page_settings.seo.vars_custom_group")}),g.map(x=>i.jsxs("div",{"data-testid":`g7le-seo-var-custom-${x}`,style:Mc,children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[i.jsx("code",{style:Es,children:x}),i.jsx("button",{type:"button","data-testid":`g7le-seo-var-custom-remove-${x}`,onClick:()=>m(x,void 0),title:s("layout_editor.page_settings.seo.remove"),"aria-label":s("layout_editor.page_settings.seo.remove"),style:{marginLeft:"auto",padding:"2px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"},children:"✕"})]}),i.jsx(Ke,{value:l[x]??"",onChange:$=>m(x,$??""),t:s,candidates:r,testidPrefix:`g7le-seo-var-custom-field-${x}`})]},x)),i.jsxs("div",{"data-testid":"g7le-seo-var-add",style:{display:"flex",flexDirection:"column",gap:4,marginTop:6},children:[i.jsxs("div",{style:{display:"flex",gap:6},children:[i.jsx("input",{type:"text","data-testid":"g7le-seo-var-add-name",value:h,placeholder:s("layout_editor.page_settings.seo.vars_add_name"),onChange:x=>v(x.target.value),style:{flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:0}}),i.jsxs("button",{type:"button","data-testid":"g7le-seo-var-add-confirm",onClick:k,disabled:h.trim()===""||y||_,style:Yw,children:["+ ",s("layout_editor.page_settings.seo.vars_add")]})]}),y?i.jsxs("p",{"data-testid":"g7le-seo-var-add-reserved-warn",style:Is,children:["⚠ ",s("layout_editor.page_settings.seo.vars_name_reserved",{name:h.trim()})]}):null,_&&!y?i.jsxs("p",{"data-testid":"g7le-seo-var-add-duplicate-warn",style:Is,children:["⚠ ",s("layout_editor.page_settings.seo.vars_name_duplicate",{name:h.trim()})]}):null,w?i.jsxs("p",{"data-testid":"g7le-seo-var-add-not-provided-hint",style:{margin:0,fontSize:11,color:"#94a3b8"},children:["ⓘ ",s("layout_editor.page_settings.seo.vars_name_not_provided",{name:h.trim()})]}):null]})]}),i.jsxs("p",{style:{margin:0,fontSize:11,color:"#94a3b8"},children:["ⓘ ",s("layout_editor.page_settings.seo.vars_value_hint")]})]})}const Fw={fontSize:12,color:"#b45309",background:"#fffbeb",border:"1px solid #fcd34d",borderRadius:6,padding:"6px 8px"},Cs={border:"1px solid #e2e8f0",borderRadius:8,padding:10,display:"flex",flexDirection:"column",gap:6},$s={fontSize:12,fontWeight:600,color:"#475569"},Kw={display:"flex",alignItems:"center",gap:6,padding:"2px 0"},Mc={display:"flex",flexDirection:"column",border:"1px solid #f1f5f9",borderRadius:6,padding:8},Vw={fontSize:13},Es={fontSize:12,color:"#0f172a",background:"#f1f5f9",padding:"2px 6px",borderRadius:4},Uw={fontSize:11,color:"#64748b"},qw={fontSize:11,color:"#94a3b8"},Gw={color:"#dc2626",fontWeight:700},Is={margin:"4px 0 0",fontSize:11,color:"#b45309"},Yw={padding:"5px 10px",fontSize:12,border:"1px dashed #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"};function Xw({templateIdentifier:e,layout:t,url:n,locale:o,seedContext:r,routeParams:s,settingsSignature:a,t:l,debounceMs:d=400,fetchImpl:c,testidPrefix:p="g7le-seo-bot-preview"}){const[f,b]=u.useState(!0),[g,m]=u.useState(null),[h,v]=u.useState(!1),[y,_]=u.useState(null),w=u.useRef(null),k=u.useRef({templateIdentifier:e,layout:t,url:n,locale:o,seedContext:r,routeParams:s});k.current={templateIdentifier:e,layout:t,url:n,locale:o,seedContext:r,routeParams:s};const x=u.useCallback(async()=>{const T=c??(typeof fetch<"u"?fetch:void 0);if(!T)return;const{templateIdentifier:E,layout:A,url:N,locale:D,seedContext:B,routeParams:M}=k.current;v(!0),_(null);try{const O=`/api/admin/templates/${encodeURIComponent(E)}/editor/seo-bot-preview`,z=await T(O,{method:"POST",credentials:"same-origin",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({layout:A,url:N,locale:D,seed_context:B??{},route_params:M??{}})}),H=await z.json().catch(()=>null);if(!z.ok){_(H?.message??`HTTP ${z.status}`);return}const P=H?.data??null;m(P)}catch(O){_(O instanceof Error?O.message:String(O))}finally{v(!1)}},[c]);u.useEffect(()=>{if(f)return w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{x()},d),()=>{w.current&&clearTimeout(w.current)}},[a,f,d,x]);const $=u.useCallback(()=>{w.current&&clearTimeout(w.current),x()},[x]),S=g?.html??null,C=g?.enabled??!0;return i.jsxs("div",{"data-testid":p,style:Jw,children:[i.jsxs("div",{style:Zw,children:[i.jsxs("button",{type:"button","data-testid":`${p}-toggle`,onClick:()=>b(T=>!T),"aria-expanded":f,style:Qw,children:[f?"▾":"▸"," ",l("layout_editor.page_settings.seo.bot_preview_title")]}),f?i.jsxs("button",{type:"button","data-testid":`${p}-refresh`,onClick:$,disabled:h,style:Rw,children:["⟳ ",l("layout_editor.page_settings.seo.bot_preview_refresh")]}):null]}),f&&i.jsxs("div",{style:{marginTop:8},children:[g&&!C?i.jsxs("p",{"data-testid":`${p}-disabled`,style:e0,children:["ⓘ ",l("layout_editor.page_settings.seo.bot_preview_disabled")]}):i.jsx("div",{"data-testid":`${p}-body`,style:t0,children:h&&!S?i.jsx("p",{style:As,children:l("layout_editor.translation.loading")}):y?i.jsx("p",{"data-testid":`${p}-error`,style:{...As,color:"#dc2626"},children:y}):S==null?i.jsx("p",{style:As,children:l("layout_editor.page_settings.seo.bot_preview_empty")}):i.jsx("pre",{"data-testid":`${p}-code`,style:n0,children:S})}),i.jsxs("p",{"data-testid":`${p}-sample-note`,style:o0,children:["ⓘ ",l("layout_editor.page_settings.seo.bot_preview_sample_note")]})]})]})}const Jw={borderTop:"1px solid #e2e8f0",paddingTop:10,marginTop:12},Zw={display:"flex",alignItems:"center",gap:8},Qw={background:"none",border:"none",cursor:"pointer",fontSize:13,fontWeight:600,color:"#0f172a",padding:0},Rw={marginLeft:"auto",padding:"4px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},e0={margin:0,fontSize:12,color:"#64748b",background:"#f8fafc",border:"1px solid #e2e8f0",borderRadius:6,padding:"8px 10px"},t0={border:"1px solid #e2e8f0",borderRadius:8,background:"#0b1020",padding:0,minHeight:80,overflow:"hidden"},n0={margin:0,padding:12,fontSize:11,lineHeight:1.5,color:"#d1fae5",fontFamily:"monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto"},As={margin:0,padding:12,fontSize:12,color:"#94a3b8"},o0={margin:"8px 0 0",fontSize:11,color:"#94a3b8"};function Lc({option:e,testIdPrefix:t}){const{id:n,friendly:o,source:r}=e;return i.jsxs("span",{style:r0,children:[i.jsx("span",{"data-testid":t?`${t}-title`:void 0,style:i0,children:o??n}),o?i.jsx("span",{"data-testid":t?`${t}-id`:void 0,style:s0,children:n}):null,r?i.jsx("span",{"data-testid":t?`${t}-source`:void 0,style:a0,children:r}):null]})}const r0={display:"inline-flex",alignItems:"baseline",gap:4,flexWrap:"wrap",minWidth:0},i0={fontSize:12,color:"#0f172a"},s0={fontSize:10,color:"#94a3b8",fontFamily:"ui-monospace, monospace"},a0={fontSize:9,fontWeight:600,color:"#7c3aed",background:"#f5f3ff",border:"1px solid #ddd6fe",borderRadius:4,padding:"0 5px",whiteSpace:"nowrap"},l0=["always","hourly","daily","weekly","monthly","yearly","never"];function d0({getValue:e,patch:t,t:n,templateIdentifier:o,candidates:r,availableExtensions:s=[],dataSourceOptions:a=[],previewUrl:l="/",previewLocale:d="ko",seedContext:c,candidatesFetcher:p,ogPreviewFetcher:f,botFetchImpl:b,testidPrefix:g="g7le-seo"}){const m=e("meta",{}).seo,h=m&&typeof m=="object"?m:{},v=u.useCallback((V,te)=>{const be={...e("meta",{})},Ee={...be.seo??{}};te==null||te===""?delete Ee[V]:Ee[V]=te,be.seo=Ee,t("meta",be)},[e,t]),y=h.enabled===!0,_=typeof h.page_type=="string"?h.page_type:"",w=Array.isArray(h.extensions)?h.extensions:[],k=Array.isArray(h.data_sources)?h.data_sources:[],x=w.length>0&&_!=="",[$,S]=u.useState(null),[C,T]=u.useState(null),E=u.useCallback(async(V,te)=>{if(p)return p(V,te);if(typeof fetch>"u")return null;const be=new URLSearchParams;V&&be.set("page_type",V),Array.isArray(te)&&te.length>0&&be.set("extensions",JSON.stringify(te.map(Ue=>({type:Ue.type,id:Ue.id}))));const Ee=be.toString()?`?${be.toString()}`:"",De=await fetch(en(`/api/admin/templates/${encodeURIComponent(o)}/editor/seo-candidates`,"json",null,Ee.replace(/^[?&]+/,"")),{credentials:"same-origin",headers:Ne()}),Se=await De.json().catch(()=>null);return De.ok?Se?.data??null:null},[p,o]),A=u.useMemo(()=>{const be=(e("__editor",{})??{}).original?.meta?.seo;return be&&typeof be=="object"?be:void 0},[e]),N=u.useRef(A);N.current=A;const D=u.useCallback(async V=>{if(f)return f(V);if(typeof fetch>"u")return null;const te=await fetch(`/api/admin/templates/${encodeURIComponent(o)}/editor/seo-og-preview`,{method:"POST",credentials:"same-origin",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({seo:V,own_seo:N.current??null,seed_context:c??{},route_params:{}})}),be=await te.json().catch(()=>null);return te.ok?be?.data??null:null},[f,o,c]),B=u.useMemo(()=>JSON.stringify(w),[w]),M=u.useRef(h);M.current=h,u.useEffect(()=>{let V=!1;return(async()=>{const te=await E(_,w);V||S(te)})(),()=>{V=!0}},[_,B]);const O=u.useMemo(()=>JSON.stringify({og:h.og??null,twitter:h.twitter??null,structured_data:h.structured_data??null}),[h.og,h.twitter,h.structured_data]),z=u.useRef(!1);u.useEffect(()=>{let V=!1;const te=()=>{(async()=>{const Ee=await D(M.current);V||T(Ee)})()};if(!z.current)return z.current=!0,te(),()=>{V=!0};const be=setTimeout(te,180);return()=>{V=!0,clearTimeout(be)}},[_,B,O]);const H=$?.page_types??[],P=$?.toggle_settings??[],I=$?.vars??[],L=u.useMemo(()=>JSON.stringify(h),[h]),F=u.useMemo(()=>e("meta")?{meta:e("meta"),components:e("components",[])}:{meta:{},components:[]},[e]),Y=u.useCallback(V=>{w.some(te=>te.type===V.type&&te.id===V.id)||v("extensions",[...w,{type:V.type,id:V.id}])},[w,v]),K=u.useCallback(V=>{const te=w.filter(be=>!(be.type===V.type&&be.id===V.id));v("extensions",te.length>0?te:void 0)},[w,v]),[X,Z]=u.useState(!1),[se,oe]=u.useState(""),G=u.useMemo(()=>{const V=se.trim().toLowerCase();return V?P.filter(te=>`${te.ref} ${te.label??""}`.toLowerCase().includes(V)):P},[P,se]),ee=typeof h.toggle_setting=="string"?h.toggle_setting:"",ge=u.useCallback(V=>{const be=k.includes(V)?k.filter(Ee=>Ee!==V):[...k,V];v("data_sources",be.length>0?be:void 0)},[k,v]);return i.jsxs("div",{"data-testid":g,style:{display:"flex",flexDirection:"column",gap:14},children:[i.jsxs("div",{style:Bt,children:[i.jsx(Mr,{checked:y,onChange:V=>v("enabled",V),testid:`${g}-enabled`,label:n("layout_editor.page_settings.seo.enabled")}),y?null:i.jsxs("p",{"data-testid":`${g}-disabled-note`,style:no,children:["ⓘ ",n("layout_editor.page_settings.seo.disabled_note")]})]}),i.jsx(Lr,{disabled:!y,testid:`${g}-body`,style:{display:"flex",flexDirection:"column",gap:14},children:i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.page_type")}),H.length>0?i.jsxs("select",{"data-testid":`${g}-page-type`,value:_,onChange:V=>v("page_type",V.target.value),style:Br,children:[i.jsx("option",{value:"",children:n("layout_editor.page_settings.seo.page_type_none")}),H.map(V=>i.jsxs("option",{value:V.value,children:[V.label??V.value,V.owner?.name?` (${V.owner.name})`:""]},V.value))]}):i.jsxs(i.Fragment,{children:[i.jsx("input",{type:"text","data-testid":`${g}-page-type-free`,value:_,placeholder:n("layout_editor.page_settings.seo.page_type_free_placeholder"),onChange:V=>v("page_type",V.target.value),style:Br}),i.jsxs("p",{"data-testid":`${g}-page-type-free-note`,style:no,children:["ⓘ ",n("layout_editor.page_settings.seo.page_type_free_note")]})]})]}),i.jsxs("div",{style:Bt,children:[i.jsxs("label",{style:qt,children:["★ ",n("layout_editor.page_settings.seo.extensions")]}),i.jsxs("div",{"data-testid":`${g}-extensions`,style:{display:"flex",flexWrap:"wrap",gap:6},children:[w.map(V=>i.jsxs("span",{"data-testid":`${g}-extension-${V.type}-${V.id}`,style:Pc,children:[V.name??`${V.type}:${V.id}`,i.jsx("button",{type:"button","data-testid":`${g}-extension-remove-${V.type}-${V.id}`,onClick:()=>K(V),style:Oc,children:"✕"})]},`${V.type}:${V.id}`)),i.jsxs("button",{type:"button","data-testid":`${g}-extension-add`,onClick:()=>Z(V=>!V),style:p0,children:["+ ",n("layout_editor.page_settings.seo.add_extension")]})]}),X&&i.jsx("div",{"data-testid":`${g}-extension-picker`,style:Bc,children:s.length===0?i.jsx("p",{style:no,children:n("layout_editor.page_settings.seo.no_extension_candidate")}):s.map(V=>i.jsx("button",{type:"button","data-testid":`${g}-extension-option-${V.type}-${V.id}`,onClick:()=>{Y(V),Z(!1)},style:Wc,children:V.name??`${V.type}:${V.id}`},`${V.type}:${V.id}`))})]}),!x&&i.jsxs("div",{"data-testid":`${g}-defaults-precondition`,style:u0,children:["⚠ ",n("layout_editor.page_settings.seo.defaults_precondition"),i.jsxs("div",{"data-testid":`${g}-defaults-missing`,style:{fontSize:11,marginTop:4},children:[w.length===0?n("layout_editor.page_settings.seo.missing_extensions"):"",_===""?` ${n("layout_editor.page_settings.seo.missing_page_type")}`:""]})]}),i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.toggle_setting")}),i.jsxs("div",{"data-testid":`${g}-toggle-setting`,children:[ee?i.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center",marginBottom:4},children:[i.jsx("code",{style:Pc,children:ee}),i.jsx("button",{type:"button","data-testid":`${g}-toggle-setting-clear`,onClick:()=>v("toggle_setting",void 0),style:Oc,children:"✕"})]}):null,i.jsx("input",{type:"text","data-testid":`${g}-toggle-setting-search`,value:se,placeholder:n("layout_editor.page_settings.seo.toggle_setting_search"),onChange:V=>oe(V.target.value),style:Br}),se.trim()!==""&&i.jsx("div",{"data-testid":`${g}-toggle-setting-results`,style:Bc,children:G.length===0?i.jsx("p",{style:no,children:n("layout_editor.inline_binding.no_results")}):G.map(V=>i.jsx("button",{type:"button","data-testid":`${g}-toggle-setting-option-${V.ref}`,onClick:()=>{v("toggle_setting",V.ref),oe("")},style:Wc,children:V.label??V.ref},V.ref))})]})]}),i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.data_sources")}),i.jsx("p",{style:no,children:n("layout_editor.page_settings.seo.data_sources_hint")}),i.jsx("div",{"data-testid":`${g}-data-sources`,style:{display:"flex",flexDirection:"column",gap:6},children:a.length===0?i.jsx("span",{style:no,children:n("layout_editor.page_settings.seo.data_sources_empty")}):a.map(V=>{const te=k.includes(V.id);return i.jsxs("label",{"data-testid":`${g}-data-source-${V.id}`,style:c0(te),children:[i.jsx("input",{type:"checkbox","data-testid":`${g}-data-source-check-${V.id}`,checked:te,onChange:()=>ge(V.id)}),i.jsx(Lc,{option:V,testIdPrefix:`${g}-data-source-${V.id}`})]},V.id)})})]}),i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.priority")}),i.jsx("input",{type:"range","data-testid":`${g}-priority`,min:0,max:1,step:.1,value:typeof h.priority=="number"?h.priority:.5,onChange:V=>v("priority",Number(V.target.value))}),i.jsx("span",{"data-testid":`${g}-priority-value`,style:{fontSize:12,color:"#475569"},children:typeof h.priority=="number"?h.priority:.5})]}),i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.changefreq")}),i.jsxs("select",{"data-testid":`${g}-changefreq`,value:typeof h.changefreq=="string"?h.changefreq:"",onChange:V=>v("changefreq",V.target.value),style:Br,children:[i.jsx("option",{value:"",children:n("layout_editor.page_settings.seo.use_default")}),l0.map(V=>i.jsx("option",{value:V,children:V},V))]})]}),i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.title")}),i.jsx(_t,{value:typeof h.title=="string"?h.title:"",onChange:V=>v("title",V??""),t:n,candidates:r,testidPrefix:`${g}-title`,enableExpressionTree:!0,expressionTreeCollapsible:!0})]}),i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.description")}),i.jsx(_t,{value:typeof h.description=="string"?h.description:"",onChange:V=>v("description",V??""),t:n,candidates:r,testidPrefix:`${g}-description`,enableExpressionTree:!0,expressionTreeCollapsible:!0})]}),i.jsx(hw,{og:h.og,twitter:h.twitter,onChangeOg:V=>v("og",Object.keys(V).length>0?V:void 0),onChangeTwitter:V=>v("twitter",Object.keys(V).length>0?V:void 0),ogPreview:C?.og,twitterPreview:C?.twitter,defaultsAvailable:C?.defaultsAvailable??!1,candidates:r,t:n}),i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.structured_data")}),i.jsx(Aw,{value:h.structured_data,onChange:V=>v("structured_data",V??void 0),autoBlock:C?.structured?.autoBlock,autoMeta:C?.structured?.autoMeta,lockedByFilter:C?.structured?.lockedByFilter,filteredBlock:C?.structured?.filteredBlock,pageType:_,candidates:r,t:n})]}),i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.vars")}),i.jsx(Hw,{vars:h.vars,onChange:V=>v("vars",Object.keys(V).length>0?V:void 0),varCandidates:I,gatingMet:x,candidates:r,t:n})]}),i.jsx(Xw,{templateIdentifier:o,layout:F,url:l,locale:d,seedContext:c,settingsSignature:L,t:n,fetchImpl:b})]})})]})}const Bt={display:"flex",flexDirection:"column",gap:4},qt={fontSize:12,fontWeight:600,color:"#334155"},Br={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",minWidth:0,boxSizing:"border-box"},no={margin:"4px 0 0",fontSize:11,color:"#94a3b8"},c0=e=>({display:"flex",alignItems:"center",gap:8,padding:"6px 10px",fontSize:12,border:`1px solid ${e?"#3b82f6":"#e2e8f0"}`,borderRadius:8,background:e?"#eff6ff":"#fff",cursor:"pointer",minWidth:0}),u0={fontSize:12,color:"#b45309",background:"#fffbeb",border:"1px solid #fcd34d",borderRadius:6,padding:"8px 10px"},Pc={display:"inline-flex",alignItems:"center",gap:4,fontSize:11,padding:"3px 8px",borderRadius:999,background:"#eef2ff",color:"#3730a3"},Oc={border:"none",background:"transparent",cursor:"pointer",color:"#6366f1",fontSize:11,padding:0},p0={fontSize:11,padding:"3px 10px",borderRadius:999,border:"1px dashed #cbd5e1",background:"#f8fafc",color:"#475569",cursor:"pointer"},Bc={marginTop:4,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",padding:6,display:"flex",flexDirection:"column",gap:2},Wc={textAlign:"left",border:"none",background:"transparent",cursor:"pointer",padding:"5px 8px",borderRadius:4,fontSize:12,color:"#0f172a"},f0={setState:"state",loadFromLocalStorage:"state",saveToLocalStorage:"state",navigate:"nav",openWindow:"nav",navigateBack:"nav",navigateForward:"nav",replaceUrl:"nav",toast:"notify",openModal:"notify",closeModal:"notify",showAlert:"notify",setError:"notify",refetchDataSource:"data",appendDataSource:"data",updateDataSource:"data",apiCall:"data",scrollIntoView:"etc",login:"etc",logout:"etc",setLocale:"locale",emitEvent:"etc",conditions:"flow",sequence:"flow",parallel:"flow",switch:"flow",suppress:"flow",showErrorPage:"error"},g0={state:"layout_editor.action.group.state",nav:"layout_editor.action.group.nav",notify:"layout_editor.action.group.notify",data:"layout_editor.action.group.data",locale:"layout_editor.action.group.locale",etc:"layout_editor.action.group.etc",flow:"layout_editor.action.group.flow",error:"layout_editor.action.group.error",extension:"layout_editor.action.group.extension"},h0={init:["state","data","notify","nav","locale","etc","flow","error","extension"],component:["nav","notify","data","state","locale","etc","flow","error","extension"]};function y0(e,t){const n=e?.[t];if(n&&typeof n=="object"){const o=n.__source;if(o&&typeof o=="object")return o}return null}function b0(e,t){return!e||e.kind==="core"?t("layout_editor.action.source_core"):e.id??t(`layout_editor.action.source_${e.kind}`)}function jc(e,t,n){return typeof e!="string"?n:e.startsWith("$t:")?t(e.slice(3)):e}function m0({recipes:e,t,onAdd:n,context:o="init",testIdPrefix:r="g7le-action-add"}){const[s,a]=u.useState(!1),[l,d]=u.useState(""),c=u.useMemo(()=>ko(e),[e]),p=u.useMemo(()=>{const f=h0[o],b=new Map;for(const m of c){const h=y0(e,m.id),y=h!=null&&h.kind!=="core"?"extension":f0[m.id]??"etc",_=b.get(y)??[];_.push({recipe:m,source:h}),b.set(y,_)}const g=l.trim().toLowerCase();return f.map(m=>{let h=b.get(m)??[];return g&&(h=h.filter(({recipe:v})=>jc(v.label,t,v.id).toLowerCase().includes(g)||v.id.toLowerCase().includes(g)||v.build.handler.toLowerCase().includes(g))),{groupKey:m,items:h}}).filter(m=>m.items.length>0)},[c,e,o,l,t]);return c.length===0?i.jsx("div",{"data-testid":`${r}-empty`,style:I0,children:t("layout_editor.action.no_recipes")}):i.jsxs("div",{className:r,"data-testid":r,style:{minWidth:0},children:[i.jsxs("button",{type:"button","data-testid":`${r}-toggle`,onClick:()=>a(f=>!f),style:v0,children:[t("layout_editor.action.add_action")," ▾"]}),s?i.jsxs("div",{"data-testid":`${r}-list`,style:_0,children:[i.jsx("input",{type:"text","data-testid":`${r}-search`,value:l,placeholder:t("layout_editor.action.add_search"),onChange:f=>d(f.target.value),style:x0}),p.map(({groupKey:f,items:b})=>i.jsxs("div",{"data-testid":`${r}-group-${f}`,children:[i.jsxs("div",{style:w0,children:["━━ ",t(g0[f]??f)," ━━"]}),b.map(({recipe:g,source:m})=>i.jsxs("button",{type:"button","data-testid":`g7le-init-action-spec-${g.id}`,onClick:()=>{n(Sr(g,{})),a(!1),d("")},style:k0,children:[i.jsx("span",{style:S0,children:jc(g.label,t,g.id)}),i.jsxs("span",{"data-testid":`g7le-init-action-spec-source-${g.id}`,style:C0,children:["〔",b0(m,t),"〕"]}),i.jsx("code",{style:$0,children:g.build.handler})]},g.id))]},f)),p.length===0?i.jsx("div",{"data-testid":`${r}-no-match`,style:E0,children:t("layout_editor.action.add_no_match")}):null]}):null]})}const v0={padding:"6px 12px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},_0={marginTop:6,border:"1px solid #cbd5e1",borderRadius:8,background:"#fff",maxHeight:320,overflowY:"auto",padding:8},x0={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,marginBottom:6,boxSizing:"border-box"},w0={fontSize:11,fontWeight:700,color:"#94a3b8",padding:"6px 4px 2px"},k0={display:"flex",alignItems:"center",gap:6,width:"100%",textAlign:"left",padding:"6px 8px",fontSize:12,border:"none",background:"transparent",cursor:"pointer",borderRadius:6},S0={flex:1,minWidth:0,color:"#0f172a"},C0={fontSize:10,color:"#64748b",whiteSpace:"nowrap"},$0={fontSize:10,color:"#cbd5e1",fontFamily:"monospace",whiteSpace:"nowrap"},E0={fontSize:12,color:"#94a3b8",padding:"8px 4px"},I0={fontSize:12,color:"#94a3b8",padding:"8px 0"};function A0(e,t){return t.startsWith("$t:")?e(t.slice(3)):t}function T0({action:e,recipe:t,values:n={},t:o,missingRequired:r=!1,showCodeButton:s=!0,testIdPrefix:a="g7le-action-preview"}){const[l,d]=u.useState(!1),c=t?Kd(t,n,p=>A0(o,p)):typeof e.handler=="string"?e.handler:o("layout_editor.action.advanced_action");return i.jsxs("div",{className:a,"data-testid":a,style:D0,children:[r?i.jsxs("span",{"data-testid":`${a}-missing`,style:N0,children:["⚠ ",o("layout_editor.action.summary_missing_required")]}):i.jsx("span",{"data-testid":`${a}-summary`,style:z0,children:c}),s?i.jsx("button",{type:"button","data-testid":`${a}-code-toggle`,onClick:()=>d(p=>!p),style:M0,"aria-expanded":l,"aria-label":o("layout_editor.action.view_code"),children:""}):null,s&&l?i.jsx("pre",{"data-testid":`${a}-code`,style:L0,children:JSON.stringify(e,null,2)}):null]})}const D0={display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,minWidth:0},z0={flex:1,minWidth:0,fontSize:12,color:"#475569"},N0={flex:1,minWidth:0,fontSize:12,color:"#b45309"},M0={border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",fontSize:11,padding:"2px 6px",whiteSpace:"nowrap"},L0={flexBasis:"100%",margin:"6px 0 0",padding:8,background:"#0f172a",color:"#e2e8f0",borderRadius:6,fontSize:11,overflow:"auto"},Hc="__g7le_custom__";function Wr({value:e,onChange:t,candidates:n,placeholder:o,testid:r,t:s,bindingCandidates:a}){const l=e==null?"":String(e),d=Array.isArray(n)&&n.length>0,c=d&&n.some(b=>b.value===l),[p,f]=u.useState(!d||l!==""&&!c);return u.useEffect(()=>{l!==""&&d&&!c&&f(!0)},[l,d,c]),d&&!p?i.jsxs("div",{style:Uc,children:[i.jsxs("select",{className:"g7le-widget g7le-widget--picker","data-testid":r,value:c?l:"",onChange:b=>{const g=b.target.value;if(g===Hc){f(!0);return}t(g===""?void 0:g)},style:{...Kc,flex:1,minWidth:0},children:[i.jsx("option",{value:"",children:s("layout_editor.control.default")}),n.map(b=>i.jsx("option",{value:b.value,children:b.label},b.value)),i.jsx("option",{value:Hc,children:s("layout_editor.recipe.custom_input")})]}),i.jsx("button",{type:"button","data-testid":`${r}-to-custom`,title:s("layout_editor.recipe.custom_input"),"aria-label":s("layout_editor.recipe.custom_input"),onClick:()=>f(!0),style:qc,children:"✎"})]}):i.jsxs("div",{style:Uc,children:[i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(Ke,{value:l,onChange:b=>t(b===""?void 0:b),t:s,candidates:a,placeholder:o,testidPrefix:`${r}-input`})}),d&&i.jsx("button",{type:"button","data-testid":`${r}-pick`,title:s("layout_editor.recipe.pick_from_list"),onClick:()=>{f(!1),t(void 0)},style:qc,children:"≡"})]})}function P0({value:e,onChange:t,candidates:n,t:o,bindingCandidates:r}){return i.jsx(Wr,{value:e,onChange:t,candidates:n,placeholder:o("layout_editor.recipe.page_placeholder"),testid:"g7le-widget-page-picker",t:o,bindingCandidates:r})}function Fc({value:e,onChange:t,candidates:n,t:o,bindingCandidates:r}){return i.jsx(Wr,{value:e,onChange:t,candidates:n,placeholder:o("layout_editor.recipe.datasource_placeholder"),testid:"g7le-widget-datasource-picker",t:o,bindingCandidates:r})}function Ts({value:e,onChange:t,candidates:n,t:o,bindingCandidates:r}){return i.jsx(Wr,{value:e,onChange:t,candidates:n,placeholder:o("layout_editor.recipe.state_key_placeholder"),testid:"g7le-widget-state-key-picker",t:o,bindingCandidates:r})}function O0({value:e,onChange:t,candidates:n,t:o,bindingCandidates:r}){return i.jsx(Wr,{value:e,onChange:t,candidates:n,placeholder:o("layout_editor.recipe.modal_placeholder"),testid:"g7le-widget-modal-picker",t:o,bindingCandidates:r})}function B0({value:e,onChange:t,t:n,bindingCandidates:o}){const r=typeof e=="string"?e:e==null?"":String(e);return i.jsx("div",{className:"g7le-widget g7le-widget--i18n-text","data-testid":"g7le-widget-i18n-text",style:{flex:1,minWidth:100,width:"100%"},children:i.jsx(_t,{value:r,onChange:s=>t(s===""?void 0:s),t:n,placeholder:n("layout_editor.recipe.i18n_text_placeholder"),testidPrefix:"g7le-widget-i18n-text-field",candidates:o,enableExpressionTree:!0,expressionTreeCollapsible:!0})})}function W0({value:e,onChange:t,candidates:n,t:o}){const r=e==null?"":String(e),s=r.split(",").map(d=>d.trim()).filter(Boolean),a=Array.isArray(n)&&n.length>0,l=d=>{if(!d)return;const c=[...s,d];t(c.join(", "))};return i.jsxs("div",{className:"g7le-widget g7le-widget--binding-list","data-testid":"g7le-widget-binding-list",style:{display:"flex",flexDirection:"column",gap:4,width:"100%"},children:[i.jsx("input",{type:"text","data-testid":"g7le-widget-binding-list-input",value:r,placeholder:o("layout_editor.recipe.datasource_placeholder"),onChange:d=>t(d.target.value===""?void 0:d.target.value),style:Vc}),a?i.jsxs("select",{className:"g7le-widget g7le-widget--picker","data-testid":"g7le-widget-binding-list-add",value:"",onChange:d=>{l(d.target.value),d.target.value=""},style:{...Kc,minWidth:0},children:[i.jsx("option",{value:"",children:o("layout_editor.recipe.pick_from_list")}),n.map(d=>i.jsx("option",{value:d.value,children:d.label},d.value))]}):null]})}function j0({value:e,onChange:t}){const n=e==null?"":String(e);return i.jsx("input",{type:"text",className:"g7le-widget g7le-widget--text","data-testid":"g7le-widget-text",value:n,onChange:o=>t(o.target.value===""?void 0:o.target.value),style:Vc})}const Kc={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",minWidth:140,width:"100%"},Vc={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:100,width:"100%"},Uc={display:"flex",gap:4,alignItems:"flex-start",width:"100%"},qc={padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"};function H0(e){if(e==null)return"null";if(Array.isArray(e))return"list";switch(typeof e){case"number":return"number";case"boolean":return"boolean";case"string":return"string";default:return"object"}}function Gc(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;case"null":return null;case"list":return[];case"object":return{};default:return null}}function Ds(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}function F0(e,t,n){return t.includes(n)?"self":e.includes(n)?"inherited":"self"}function K0(e){const t=e.state&&typeof e.state=="object"&&Object.keys(e.state).length>0,n=e.initLocal&&typeof e.initLocal=="object"?e.initLocal:void 0;if(!t)return{initLocal:n??{},migrated:!1};const o={...e.state};if(n)for(const[r,s]of Object.entries(n))o[r]=s;return{initLocal:o,migrated:!0}}const Yc=[{kind:"string",labelKey:"layout_editor.initstate.kind_string"},{kind:"number",labelKey:"layout_editor.initstate.kind_number"},{kind:"boolean",labelKey:"layout_editor.initstate.kind_boolean"},{kind:"null",labelKey:"layout_editor.initstate.kind_null"},{kind:"list",labelKey:"layout_editor.initstate.kind_list"},{kind:"object",labelKey:"layout_editor.initstate.kind_object"}];function zn({value:e,onChange:t,t:n,path:o,scope:r,depth:s=0,renderStringLeaf:a}){const l=H0(e),d=c=>{t(Gc(c))};return i.jsxs("div",{className:"g7le-initstate-value",style:{paddingLeft:s>0?12:0,minWidth:0},children:[i.jsxs("div",{style:U0,children:[i.jsx("select",{"data-testid":`g7le-initstate-type-${o}`,value:l,onChange:c=>d(c.target.value),style:Xc,children:Yc.map(({kind:c,labelKey:p})=>i.jsx("option",{value:c,children:n(p)},c))}),l==="string"?a?i.jsx("div",{style:{flex:1,minWidth:0},children:a({value:String(e??""),onChange:c=>t(c),testidPrefix:`g7le-initstate-value-${o}`})}):i.jsx("input",{type:"text","data-testid":`g7le-initstate-value-${o}`,value:String(e??""),onChange:c=>t(c.target.value),style:Jc}):l==="number"?i.jsx("input",{type:"number","data-testid":`g7le-initstate-value-${o}`,value:typeof e=="number"?e:"",onChange:c=>{const p=parseFloat(c.target.value);t(Number.isNaN(p)?0:p)},style:Jc}):l==="boolean"?i.jsx(Mr,{checked:!!e,onChange:t,testid:`g7le-initstate-value-${o}`,label:n(e?"layout_editor.overlay.on":"layout_editor.overlay.off")}):l==="null"?i.jsx("span",{"data-testid":`g7le-initstate-value-${o}`,style:q0,children:"null"}):null]}),l==="list"?i.jsxs("div",{style:Zc,children:[e.map((c,p)=>i.jsxs("div",{style:G0,children:[i.jsxs("span",{style:Y0,children:["[",p,"]"]}),i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(zn,{value:c,onChange:f=>{const b=e.slice();b[p]=f,t(b)},t:n,path:`${o}.${p}`,scope:r,depth:s+1,renderStringLeaf:a})}),i.jsx("button",{type:"button","data-testid":`g7le-initstate-item-remove-${o}.${p}`,onClick:()=>t(e.filter((f,b)=>b!==p)),style:Qc,children:"✕"})]},p)),i.jsxs("button",{type:"button","data-testid":`g7le-initstate-item-add-${o}`,onClick:()=>t([...e,""]),style:Rc,children:["+ ",n("layout_editor.initstate.add_item")]})]}):null,l==="object"?i.jsx(V0,{value:e,onChange:t,t:n,path:o,scope:r,depth:s+1,renderStringLeaf:a}):null]})}function V0({value:e,onChange:t,t:n,path:o,scope:r,depth:s,renderStringLeaf:a}){const[l,d]=u.useState(""),[c,p]=u.useState("string"),[f,b]=u.useState(null),g=Object.entries(e),m=()=>{const h=l.trim();if(!h){b(n("layout_editor.initstate.name_required"));return}if(!Ds(h)){b(n("layout_editor.initstate.name_invalid"));return}if(h in e){b(n("layout_editor.initstate.name_duplicate"));return}t({...e,[h]:Gc(c)}),d(""),b(null)};return i.jsxs("div",{style:Zc,children:[g.map(([h,v])=>i.jsxs("div",{style:X0,children:[i.jsx("code",{style:J0,children:h}),i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(zn,{value:v,onChange:y=>t({...e,[h]:y}),t:n,path:`${o}.${h}`,scope:r,depth:s,renderStringLeaf:a})}),i.jsx("button",{type:"button","data-testid":`g7le-initstate-subremove-${o}.${h}`,onClick:()=>{const y={...e};delete y[h],t(y)},style:Qc,children:"✕"})]},h)),i.jsxs("div",{style:Z0,children:[i.jsx("input",{type:"text","data-testid":`g7le-initstate-subkey-input-${o}`,value:l,placeholder:n("layout_editor.initstate.subkey_name"),onChange:h=>{d(h.target.value),f&&b(null)},onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),m())},"aria-invalid":f?!0:void 0,style:{...Q0,...f?R0:null}}),i.jsx("select",{"data-testid":`g7le-initstate-subkey-kind-${o}`,value:c,onChange:h=>p(h.target.value),"aria-label":n("layout_editor.initstate.value_kind"),style:Xc,children:Yc.map(({kind:h,labelKey:v})=>i.jsx("option",{value:h,children:n(v)},h))}),i.jsxs("button",{type:"button","data-testid":`g7le-initstate-subkey-add-${o}`,onClick:m,style:Rc,children:["+ ",n("layout_editor.initstate.add_subkey")]})]}),f?i.jsx("p",{"data-testid":`g7le-initstate-subkey-error-${o}`,style:ek,children:f}):null]})}const U0={display:"flex",gap:6,alignItems:"center",minWidth:0},Xc={padding:"4px 6px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,color:"#64748b"},Jc={flex:1,minWidth:0,padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},q0={fontSize:12,color:"#94a3b8",fontFamily:"monospace"},Zc={display:"flex",flexDirection:"column",gap:6,marginTop:6,paddingLeft:8,borderLeft:"2px solid #e2e8f0"},G0={display:"flex",gap:6,alignItems:"flex-start",minWidth:0},Y0={fontSize:11,color:"#94a3b8",minWidth:28,paddingTop:4},X0={display:"flex",gap:6,alignItems:"flex-start",minWidth:0},J0={fontSize:11,color:"#475569",fontFamily:"monospace",minWidth:72,paddingTop:4},Qc={border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12},Rc={alignSelf:"flex-start",padding:"2px 8px",fontSize:11,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},Z0={display:"flex",gap:6,alignItems:"center"},Q0={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6},R0={border:"1px solid #dc2626"},ek={margin:"2px 0 0",fontSize:11,color:"#dc2626"},tk=new Set(["text","data-chip","number"]),nk=new Set(["select","toggle","page-picker","datasource-picker","state-key-picker","modal-picker","component-target-picker","tag-input","locale-picker","i18n-text","segmented","slider","color","image"]);function ok(e,t,n){return typeof e!="string"?n:e.startsWith("$t:")?t(e.slice(3)):e}function rk(e,t){if(e==="page-picker")return t.pageCandidates;if(e==="datasource-picker")return t.dataSourceCandidates;if(e==="state-key-picker")return t.stateKeyCandidates;if(e==="modal-picker")return t.modalCandidates}function ik({param:e,value:t,t:n,pools:o,onChange:r,testIdPrefix:s,renderActionList:a,siblingValues:l}){const d=ok(e.label,n,e.key);if(e.advanced)return i.jsxs("div",{"data-testid":`${s}-locked-${e.key}`,style:hk,children:[i.jsx("span",{style:yk,children:d}),i.jsxs("span",{style:bk,children:["[",n("layout_editor.action.advanced"),"] ",n("layout_editor.init_actions.advanced_param_hint")]})]});if(e.widget==="action-list"&&a){const f=Array.isArray(t)?t.filter(b=>!!b&&typeof b=="object"):[];return i.jsxs("div",{"data-testid":`${s}-param-${e.key}`,style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsx("span",{style:oo,children:d}),a(f,b=>r(b.length===0?void 0:b),`${s}-${e.key}`,e.key)]})}if(e.widget==="branch-list"&&a){const f=Array.isArray(t)?t.filter(b=>!!b&&typeof b=="object"):[];return i.jsxs("div",{"data-testid":`${s}-param-${e.key}`,style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsx("span",{style:oo,children:d}),i.jsx(sk,{branches:f,onChange:b=>r(b.length===0?void 0:b),t:n,pools:o,renderActionList:a,testIdPrefix:`${s}-${e.key}`})]})}if(e.widget==="key-value")return i.jsxs("div",{"data-testid":`${s}-param-${e.key}`,style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsx("span",{style:oo,children:d}),i.jsx(uk,{value:t,onChange:r,t:n,candidates:o.bindingCandidates,testIdPrefix:`${s}-kv-${e.key}`})]});if(e.widget==="state-key-value")return i.jsxs("div",{"data-testid":`${s}-param-${e.key}`,style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsx("span",{style:oo,children:d}),i.jsx(pk,{value:t,onChange:r,t:n,candidates:o.bindingCandidates,stateKeyCandidates:o.stateKeyCandidates,param:e,siblingTarget:l?.target,testIdPrefix:`${s}-skv-${e.key}`})]});if(tk.has(e.widget??"")||!nk.has(e.widget??""))return i.jsxs("div",{"data-testid":`${s}-param-${e.key}`,style:tu,children:[i.jsx("span",{style:oo,children:d}),i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(Ke,{value:typeof t=="string"?t:t==null?"":String(t),onChange:f=>r(f===""?void 0:f),t:n,candidates:o.bindingCandidates,placeholder:e.widget==="number"?n("layout_editor.action_param.number_placeholder"):void 0,testidPrefix:`${s}-chip-${e.key}`})})]});const p=Tn(e.widget);return i.jsxs("div",{"data-testid":`${s}-param-${e.key}`,style:tu,children:[i.jsx("span",{style:oo,children:d}),i.jsx("div",{style:{flex:1,minWidth:0},children:p?i.jsx(p,{control:{...e},value:t,onChange:r,t:n,candidates:rk(e.widget,o),bindingCandidates:o.bindingCandidates}):i.jsx(Ke,{value:typeof t=="string"?t:t==null?"":String(t),onChange:f=>r(f===""?void 0:f),t:n,candidates:o.bindingCandidates,testidPrefix:`${s}-chip-${e.key}`})})]})}function sk({branches:e,onChange:t,t:n,pools:o,renderActionList:r,testIdPrefix:s}){const a=b=>Array.isArray(b)?b.filter(g=>!!g&&typeof g=="object"):b&&typeof b=="object"?[b]:[],l=b=>{if(b.length!==0)return b.length===1?b[0]:b},d=(b,g)=>{const m=e.slice();m[b]=g,t(m)},c=b=>{t(e.filter((g,m)=>m!==b))},p=(b,g)=>{if(g<0||g>=e.length)return;const m=e.slice(),[h]=m.splice(b,1);m.splice(g,0,h),t(m)},f=()=>{t([...e,{if:"",then:void 0}])};return i.jsxs("div",{"data-testid":`${s}-branches`,style:{display:"flex",flexDirection:"column",gap:8},children:[e.map((b,g)=>{const m=typeof b.if=="string"?b.if:"",h=a(b.then);return i.jsxs("div",{"data-testid":`${s}-branch-${g}`,style:ak,children:[i.jsxs("div",{style:lk,children:[i.jsxs("span",{style:dk,children:[n(m?"layout_editor.action_recipe.conditions.branch_when":"layout_editor.action_recipe.conditions.branch_else")," ",g+1]}),i.jsxs("span",{style:{display:"flex",gap:4},children:[i.jsx("button",{type:"button","data-testid":`${s}-branch-${g}-up`,onClick:()=>p(g,g-1),disabled:g===0,style:zs,title:n("layout_editor.action_recipe.conditions.move_up"),children:"↑"}),i.jsx("button",{type:"button","data-testid":`${s}-branch-${g}-down`,onClick:()=>p(g,g+1),disabled:g===e.length-1,style:zs,title:n("layout_editor.action_recipe.conditions.move_down"),children:"↓"}),i.jsx("button",{type:"button","data-testid":`${s}-branch-${g}-remove`,onClick:()=>c(g),style:zs,title:n("layout_editor.action_recipe.conditions.remove_branch"),children:"✕"})]})]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[i.jsx("span",{style:eu,children:n("layout_editor.action_recipe.conditions.param_if")}),i.jsx(Ke,{value:m,onChange:v=>d(g,{...b,if:v}),t:n,candidates:o.bindingCandidates,testidPrefix:`${s}-branch-${g}-if`})]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[i.jsx("span",{style:eu,children:n("layout_editor.action_recipe.conditions.param_then")}),r(h,v=>d(g,{...b,then:l(v)}),`${s}-branch-${g}-then`)]})]},g)}),i.jsxs("button",{type:"button","data-testid":`${s}-add-branch`,onClick:f,style:ck,children:["+ ",n("layout_editor.action_recipe.conditions.add_branch")]})]})}const ak={border:"1px solid #e2e8f0",borderRadius:6,padding:8,display:"flex",flexDirection:"column",gap:6,background:"#f8fafc"},lk={display:"flex",justifyContent:"space-between",alignItems:"center"},dk={fontSize:12,fontWeight:700,color:"#475569"},eu={fontSize:11,color:"#64748b"},zs={border:"1px solid #cbd5e1",background:"#fff",borderRadius:4,width:22,height:22,cursor:"pointer",fontSize:12,lineHeight:"1",color:"#475569"},ck={border:"1px dashed #94a3b8",background:"#fff",borderRadius:6,padding:"6px 10px",cursor:"pointer",fontSize:12,color:"#475569",alignSelf:"flex-start"};function uk({value:e,onChange:t,t:n,candidates:o,testIdPrefix:r,renderKeyInput:s}){const a=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).map(([l,d])=>({key:l,value:typeof d=="string"?d:d==null?"":String(d)})):[];return i.jsx(Pr,{value:a,onChange:l=>{const d={};for(const c of l)c.key.trim()!==""&&(d[c.key]=c.value??"");t(Object.keys(d).length===0?void 0:d)},keyField:"key",valueField:"value",t:n,candidates:o,testidPrefix:r,keyPlaceholder:n("layout_editor.action_param.key_placeholder"),valuePlaceholder:n("layout_editor.action_param.value_placeholder"),addLabel:n("layout_editor.action_param.add_pair"),renderKeyInput:s})}function pk({value:e,onChange:t,t:n,candidates:o,stateKeyCandidates:r,param:s,siblingTarget:a,testIdPrefix:l}){const d=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e):[],c=typeof a=="string"?a:"";if((c.startsWith("_local.")||c.startsWith("global.")||c.startsWith("$parent._local.")||c.startsWith("$root._local."))&&d.length===1&&d[0][0]==="value"){const y=d[0][1];return i.jsx("div",{"data-testid":`${l}-path-value`,style:{display:"flex",flexDirection:"column",gap:4},children:i.jsx(zn,{value:y,onChange:_=>t(_===void 0?void 0:{value:_}),t:n,path:"value",scope:`${l}-path-value-val`,renderStringLeaf:_=>i.jsx(Ke,{value:_.value,onChange:_.onChange,t:n,candidates:o,testidPrefix:_.testidPrefix})})})}const b=(y,_)=>{const w={};for(const[k,x]of d)w[k]=k===y?_:x;t(Object.keys(w).length===0?void 0:w)},g=y=>{const _={};for(const[w,k]of d)w!==y&&(_[w]=k);t(Object.keys(_).length===0?void 0:_)},[m,h]=u.useState(""),v=()=>{const y=m.trim();if(y===""||d.some(([w])=>w===y))return;const _={};for(const[w,k]of d)_[w]=k;_[y]="",t(_),h("")};return i.jsxs("div",{"data-testid":l,style:{display:"flex",flexDirection:"column",gap:6},children:[d.map(([y,_])=>i.jsxs("div",{"data-testid":`${l}-row-${y}`,style:{display:"flex",gap:6,alignItems:"flex-start",border:"1px solid #e2e8f0",borderRadius:8,padding:8},children:[i.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:6},children:[i.jsx("div",{style:{minWidth:0},children:i.jsx(Ts,{control:{...s},value:y,onChange:w=>{const k=w==null?"":String(w);if(k===""||k===y||d.some(([$])=>$===k))return;const x={};for(const[$,S]of d)x[$===y?k:$]=S;t(x)},t:n,candidates:r})}),i.jsx("div",{style:{minWidth:0},children:i.jsx(zn,{value:_,onChange:w=>b(y,w),t:n,path:y,scope:`${l}-val`,renderStringLeaf:w=>i.jsx(Ke,{value:w.value,onChange:w.onChange,t:n,candidates:o,testidPrefix:w.testidPrefix})})})]}),i.jsx("button",{type:"button","data-testid":`${l}-remove-${y}`,onClick:()=>g(y),title:n("layout_editor.page_settings.seo.remove"),"aria-label":n("layout_editor.page_settings.seo.remove"),style:{flex:"0 0 auto",padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"},children:"✕"})]},y)),i.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(Ts,{control:{...s},value:m,onChange:y=>h(y==null?"":String(y)),t:n,candidates:r})}),i.jsxs("button",{type:"button","data-testid":`${l}-add`,onClick:v,style:{flex:"0 0 auto",padding:"5px 10px",fontSize:12,border:"1px dashed #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},children:["+ ",n("layout_editor.action_param.add_pair")]})]})]})}function Ns({raw:e,recipe:t,values:n,t:o,pools:r,onChange:s,testIdPrefix:a,renderActionList:l}){const d=(c,p)=>{const f={...n,[c]:p},b=Sr(t,f),g=cs(e);s(g?Vd(b,g):b)};return i.jsx(i.Fragment,{children:t.params.filter(c=>fk(c,n)).map(c=>i.jsx(ik,{param:c,value:n[c.key],t:o,pools:r,onChange:p=>d(c.key,p),testIdPrefix:a,renderActionList:l,siblingValues:n},c.key))})}function fk(e,t){const n=e.dependsOn;return!n||typeof n!="object"||typeof n.param!="string"?!0:t[n.param]===n.equals}function gk({raw:e,t,onChange:n,testIdPrefix:o,candidates:r}){const[s,a]=u.useState(!1);return i.jsxs("div",{"data-testid":`${o}-if`,style:mk,children:[i.jsxs("button",{type:"button",onClick:()=>a(l=>!l),style:vk,children:["▸ ",t("layout_editor.init_actions.if_label")]}),s?i.jsx("div",{"data-testid":`${o}-if-input`,style:{minWidth:0},children:i.jsx(Ke,{value:cs(e)??"",onChange:l=>n(Vd(e,l)),t,candidates:r,placeholder:t("layout_editor.init_actions.if_placeholder"),testidPrefix:`${o}-if-chip`})}):null]})}const tu={display:"flex",alignItems:"center",gap:8,minWidth:0},oo={fontSize:11,color:"#64748b",minWidth:80},hk={display:"flex",alignItems:"center",gap:8,padding:"4px 0"},yk={fontSize:11,color:"#64748b",minWidth:80},bk={fontSize:11,color:"#92400e"},mk={display:"flex",flexDirection:"column",gap:4},vk={textAlign:"left",border:"none",background:"transparent",color:"#475569",cursor:"pointer",fontSize:11,padding:0};function _k(e,t,n){if(!t)return n("layout_editor.action.source_core");const o=e?.[t],r=o&&typeof o=="object"&&o.__source?o.__source:null;return!r||r.kind==="core"?n("layout_editor.action.source_core"):r.id??n(`layout_editor.action.source_${r.kind}`)}function xk(e,t,n){const o=Yn(e,t);if(o.kind==="preset"){const r=t.find(s=>s.id===o.recipeId);return Kd(r??null,o.values,s=>n(s.startsWith("$t:")?s.slice(3):s))}return typeof e.handler=="string"?e.handler:n("layout_editor.action_list.unknown")}function Gt({actions:e,onChange:t,t:n,recipes:o,chipContext:r,actionChipCandidates:s,addContext:a="init",renderAddPicker:l,renderEditor:d,candidatePools:c,showSourceBadge:p=!1,canDrag:f,canDropAt:b,isLocked:g,hideAddPicker:m=!1,testIdPrefix:h="g7le-action-list"}){const v=u.useMemo(()=>ko(o),[o]),y=u.useMemo(()=>{if(r==null||r==="init")return c;const B=Vl(r,n,s??null);if(B.length===0)return c;const M=c??{},O=new Set((M.bindingCandidates??[]).map(H=>H.expression)),z=B.filter(H=>!O.has(H.expression));return z.length===0?c:{...M,bindingCandidates:[...z,...M.bindingCandidates??[]]}},[r,s,c,n]),[_,w]=u.useState(null),[k,x]=u.useState(null),$=u.useCallback((B,M)=>{if(B===M||B<0||M<0||B>=e.length||M>=e.length)return;const O=e.slice(),[z]=O.splice(B,1);O.splice(M,0,z),t(O)},[e,t]),S=ys({length:e.length,onMove:$,canDrag:f,canDropAt:b}),C=u.useCallback(B=>{t(e.filter((M,O)=>O!==B))},[e,t]),T=u.useCallback((B,M)=>{const O=e.slice();O[B]=M,t(O)},[e,t]),E=u.useCallback(B=>{t([...e,B])},[e,t]),A=u.useCallback((B,M)=>{const O=Yn(B,v),z=O.kind==="preset"?v.find(P=>P.id===O.recipeId)??null:null;if(!z)return null;const H=O.kind==="preset"?O.values:{};return i.jsxs("div",{style:Ck,children:[i.jsx(Ns,{raw:B,recipe:z,values:H,t:n,pools:y??{},onChange:M,testIdPrefix:`${h}-edit`,renderActionList:(P,I,L,F)=>{const Y=F==="onSuccess"?"response":F==="onError"?"error":void 0;return i.jsx(Gt,{actions:P,onChange:I,t:n,recipes:o,chipContext:Y,actionChipCandidates:Y?s:void 0,candidatePools:Y?c:y,addContext:a,showSourceBadge:p,testIdPrefix:L})}}),i.jsx(gk,{raw:B,t:n,onChange:M,testIdPrefix:`${h}-edit`,candidates:y?.bindingCandidates})]})},[v,n,y,c,s,h,o,a,p]),N=d??(o?A:void 0),D=m?null:l?l(E):o?i.jsx(m0,{recipes:o,t:n,onAdd:E,context:a,testIdPrefix:`${h}-add-picker`}):null;return i.jsxs("div",{className:h,"data-testid":h,children:[i.jsxs("ul",{style:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:6},children:[e.map((B,M)=>{const O=Yn(B,v),z=O.kind==="preset"?O.recipeId:null,H=z?v.find(Y=>Y.id===z)??null:null,P=H===null,I=g?.(M)??!1,L=cs(B)!==null,F=N?N(B,Y=>T(M,Y)):null;return i.jsxs(u.Fragment,{children:[I?null:i.jsx("li",{"aria-hidden":"true",style:{listStyle:"none",margin:0,padding:0},children:i.jsx(Rn,{active:S.isDropTarget(M),testid:`${h}-dropline-${M}`})}),i.jsxs("li",{"data-testid":`${h}-item-${M}`,"data-drag-source":S.dragIndex===M?"true":void 0,style:{border:"1px solid #e2e8f0",borderRadius:8,padding:"8px 10px",...S.dragIndex===M?{opacity:.5}:{}},onDragOver:S.dragging&&!I?Y=>{Y.preventDefault();const K=Y.currentTarget.getBoundingClientRect();S.onDragOverItem(M,Y.clientY{Y.preventDefault(),S.onDrop()}:void 0,children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[I?i.jsx("span",{style:{fontSize:12},children:"🔒"}):i.jsx("span",{"data-testid":`${h}-drag-${M}`,style:{color:"#94a3b8",cursor:"grab",fontSize:14,userSelect:"none"},draggable:!0,onDragStart:()=>S.onDragStart(M),onDragEnd:S.onDragEnd,"aria-label":n("layout_editor.action_list.drag_reorder"),role:"button",children:"⠿"}),i.jsx("span",{style:{flex:1,minWidth:0,fontSize:13},"data-testid":`${h}-summary-${M}`,children:xk(B,v,n)}),p?i.jsxs("span",{"data-testid":`${h}-source-${M}`,style:wk,children:["〔",_k(o,z,n),"〕"]}):null,L?i.jsxs("span",{"data-testid":`${h}-cond-badge-${M}`,style:kk,children:["〔",n("layout_editor.init_actions.cond_badge"),"〕"]}):null,P?i.jsxs("span",{"data-testid":`${h}-advanced-${M}`,style:Sk,children:["[",n("layout_editor.action.advanced"),"]"]}):null,!I&&F?i.jsxs("button",{type:"button","data-testid":`${h}-edit-${M}`,onClick:()=>x(k===M?null:M),"aria-label":n("layout_editor.init_actions.edit"),title:n("layout_editor.init_actions.edit"),style:k===M?$k:nu,children:["✎ ",n("layout_editor.init_actions.edit")]}):null,i.jsx("button",{type:"button","data-testid":`${h}-code-${M}`,onClick:()=>w(_===M?null:M),"aria-label":n("layout_editor.action_list.view_code"),title:n("layout_editor.action_list.view_code"),style:_===M?Ek:Ms,children:""}),I?null:i.jsx("button",{type:"button","data-testid":`${h}-remove-${M}`,onClick:()=>C(M),"aria-label":n("layout_editor.action_list.remove"),title:n("layout_editor.action_list.remove"),style:Ik,children:"✕"})]}),H?i.jsx(T0,{action:B,recipe:H,values:O.kind==="preset"?O.values:{},t:n,showCodeButton:!1,testIdPrefix:`${h}-preview-${M}`}):null,k===M&&!I&&F?i.jsx("div",{"data-testid":`${h}-edit-body-${M}`,children:F}):null,d&&k!==M?d(B,Y=>T(M,Y)):null,_===M?i.jsx("pre",{"data-testid":`${h}-code-view-${M}`,style:{margin:"8px 0 0",padding:8,background:"#0f172a",color:"#e2e8f0",borderRadius:6,fontSize:12,overflow:"auto"},children:JSON.stringify(B,null,2)}):null]})]},M)}),i.jsx("li",{"aria-hidden":"true",style:{listStyle:"none",margin:0,padding:0},children:i.jsx(Rn,{active:S.isDropTarget(e.length),testid:`${h}-dropline-end`})})]}),D?i.jsx("div",{style:{marginTop:8},children:D}):null]})}const wk={fontSize:10,color:"#64748b",whiteSpace:"nowrap"},kk={fontSize:10,color:"#7c3aed",whiteSpace:"nowrap"},Sk={fontSize:10,color:"#92400e",whiteSpace:"nowrap"},Ck={display:"flex",flexDirection:"column",gap:6,paddingTop:6,borderTop:"1px dashed #e2e8f0",marginTop:6},nu={flex:"0 0 auto",padding:"3px 8px",fontSize:11,fontWeight:500,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",whiteSpace:"nowrap",lineHeight:1.4},$k={...nu,background:"#eff6ff",borderColor:"#bfdbfe",color:"#2563eb"},Ms={flex:"0 0 auto",width:26,height:24,display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:11,border:"1px solid #e2e8f0",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer",fontFamily:"ui-monospace, monospace"},Ek={...Ms,background:"#0f172a",borderColor:"#0f172a",color:"#e2e8f0"},Ik={...Ms,color:"#dc2626",borderColor:"#fecaca",fontFamily:"inherit"};function ou(e){const t=e.__source;return t&&typeof t=="object"?t:null}function Ak({actions:e,onChange:t,recipes:n,t:o,bindingCandidates:r,pageCandidates:s,dataSourceCandidates:a,stateKeyCandidates:l,modalCandidates:d}){const c=u.useMemo(()=>({pageCandidates:s,dataSourceCandidates:a,stateKeyCandidates:l,modalCandidates:d,bindingCandidates:r}),[s,a,l,d,r]),p=u.useMemo(()=>e.filter(h=>ou(h)?.kind==="base"),[e]),f=u.useMemo(()=>e.filter(h=>ou(h)?.kind!=="base"),[e]),b=p.length>0,g=u.useCallback(h=>{t(b?[...p,...h]:h)},[t,b,p]),m=u.useCallback(()=>{},[]);return i.jsxs("div",{className:"g7le-init-actions-form","data-testid":"g7le-init-actions-form",style:Tk,children:[i.jsx("p",{style:Dk,children:o("layout_editor.page_settings.init_actions.heading")}),b?i.jsxs(i.Fragment,{children:[i.jsxs("div",{"data-testid":"g7le-init-action-group-base",style:ru,children:[i.jsx("div",{style:iu,children:o("layout_editor.init_actions.group_base")}),i.jsx(Gt,{actions:p,onChange:m,t:o,recipes:n,candidatePools:c,addContext:"init",showSourceBadge:!0,isLocked:()=>!0,hideAddPicker:!0,testIdPrefix:"g7le-init-action-base"}),i.jsxs("p",{"data-testid":"g7le-init-action-base-hint",style:zk,children:["ⓘ ",o("layout_editor.init_actions.base_readonly_hint")]})]}),i.jsxs("div",{"data-testid":"g7le-init-action-group-self",style:ru,children:[i.jsx("div",{style:iu,children:o("layout_editor.init_actions.group_self")}),f.length===0?i.jsx("p",{style:su,children:o("layout_editor.init_actions.empty_self")}):null,i.jsx(Gt,{actions:f,onChange:g,t:o,recipes:n,candidatePools:c,addContext:"init",showSourceBadge:!0,testIdPrefix:"g7le-init-action-self"})]}),i.jsxs("p",{"data-testid":"g7le-init-action-merge-order",style:Nk,children:["ⓘ ",o("layout_editor.init_actions.merge_order")]})]}):i.jsxs(i.Fragment,{children:[e.length===0?i.jsx("p",{"data-testid":"g7le-init-action-empty",style:su,children:o("layout_editor.init_actions.empty")}):null,i.jsx(Gt,{actions:e,onChange:t,t:o,recipes:n,candidatePools:c,addContext:"init",showSourceBadge:!0,testIdPrefix:"g7le-init-action"})]})]})}const Tk={display:"flex",flexDirection:"column",gap:12,minWidth:0},Dk={margin:0,fontSize:13,fontWeight:700,color:"#0f172a"},ru={border:"1px solid #e2e8f0",borderRadius:10,padding:10,display:"flex",flexDirection:"column",gap:8},iu={fontSize:12,fontWeight:700,color:"#475569"},zk={margin:0,fontSize:11,color:"#64748b"},su={margin:0,fontSize:12,color:"#94a3b8"},Nk={margin:0,fontSize:11,color:"#64748b"};function Mk(e){return e==="spinner"?new Set(["spinner","page"]):new Set(["skeleton"])}function au(e,t,n){return typeof e!="string"?n:e.startsWith("$t:")?t(e.slice(3)):e}function lu({candidates:e,value:t,onSelect:n,styleKind:o,t:r,testIdPrefix:s="g7le-loading-component-picker"}){const a=bo(),l=()=>{const d=a.open({ariaLabel:r("layout_editor.overlay.loading_picker.select"),width:520,maxHeightRatio:.7,content:i.jsx(Lk,{candidates:e,value:t,styleKind:o,t:r,testIdPrefix:s,onPick:c=>{n(c),a.close(d)},onClose:()=>a.close(d)})})};return i.jsx("div",{className:s,"data-testid":s,style:{minWidth:0},children:i.jsxs("div",{style:Pk,children:[i.jsx("span",{"data-testid":`${s}-current`,style:Ok,children:t&&t.length>0?t:r("layout_editor.overlay.loading_picker.none")}),i.jsxs("button",{type:"button","data-testid":`${s}-open`,onClick:l,style:Bk,children:["🔍 ",r("layout_editor.overlay.loading_picker.select")]})]})})}function Lk({candidates:e,value:t,styleKind:n,t:o,testIdPrefix:r,onPick:s,onClose:a}){const[l,d]=u.useState(""),c=Mk(n),p=u.useMemo(()=>{const f=l.trim().toLowerCase();return e.filter(b=>c.has(b.role)).filter(b=>f?au(b.label,o,b.name).toLowerCase().includes(f)||b.name.toLowerCase().includes(f):!0)},[e,n,l,o]);return i.jsxs("div",{"data-testid":`${r}-modal`,style:Wk,children:[i.jsxs("div",{style:jk,children:[i.jsxs("span",{style:Hk,children:["🔍 ",o("layout_editor.overlay.loading_picker.select")]}),i.jsx("button",{type:"button","data-testid":`${r}-close`,onClick:a,"aria-label":o("layout_editor.overlay.loading_picker.select"),style:Fk,children:"✕"})]}),i.jsx("input",{type:"text","data-testid":`${r}-search`,value:l,placeholder:o("layout_editor.overlay.loading_picker.search"),onChange:f=>d(f.target.value),style:Kk,autoFocus:!0}),p.length===0?i.jsx("p",{"data-testid":`${r}-empty`,style:Jk,children:o("layout_editor.overlay.loading_picker.empty")}):i.jsx("ul",{style:Vk,children:p.map(f=>i.jsx("li",{children:i.jsxs("button",{type:"button","data-testid":`${r}-item-${f.name}`,onClick:()=>s(f.name),style:{...Uk,...t===f.name?qk:{}},children:[i.jsx("span",{style:Gk,children:au(f.label,o,f.name)}),i.jsx("code",{style:Yk,children:f.name}),i.jsx("span",{style:Xk,children:f.role})]})},f.name))})]})}const Pk={display:"flex",alignItems:"center",gap:6,minWidth:0},Ok={flex:1,minWidth:0,fontSize:12,color:"#0f172a",fontFamily:"monospace"},Bk={padding:"4px 10px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},Wk={display:"flex",flexDirection:"column",minHeight:0,padding:16,boxSizing:"border-box",fontFamily:"system-ui, -apple-system, sans-serif"},jk={display:"flex",alignItems:"center",gap:8,paddingBottom:8,borderBottom:"1px solid #e2e8f0",marginBottom:10},Hk={flex:1,fontSize:14,fontWeight:700,color:"#0f172a",minWidth:0},Fk={border:"none",background:"transparent",color:"#64748b",cursor:"pointer",fontSize:15,lineHeight:1,padding:4},Kk={width:"100%",padding:"6px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,marginBottom:8,boxSizing:"border-box"},Vk={listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:2,overflowY:"auto",minHeight:0},Uk={display:"flex",alignItems:"center",gap:6,width:"100%",textAlign:"left",padding:"8px 10px",fontSize:12,border:"1px solid transparent",background:"transparent",cursor:"pointer",borderRadius:6},qk={border:"1px solid #3b82f6",background:"#eff6ff"},Gk={flex:1,minWidth:0,color:"#0f172a"},Yk={fontSize:10,color:"#94a3b8",fontFamily:"monospace"},Xk={fontSize:10,color:"#64748b",background:"#f1f5f9",borderRadius:4,padding:"0 4px"},Jk={margin:0,fontSize:12,color:"#94a3b8",padding:"8px 4px"};function du(e){return e===!0?{enabled:!0}:e===!1||e===void 0?{}:e}const Zk=["opaque","blur","fade","skeleton","spinner"];function Qk({value:e,patch:t,t:n,baseValue:o,ownValue:r,loadingComponents:s=[],progressiveDataSources:a=[],bindingCandidates:l}){const d=du(e),c=d.enabled??!1,p=!!o&&Object.keys(o).length>0,f=Tn("component-target-picker"),[b,g]=u.useState((d.wait_for??[]).length>0),m=u.useCallback(k=>{const x={...du(e)};k(x),t(x)},[e,t]),h=r&&typeof r=="object"?r:e&&typeof e=="object"?e:{},v=u.useCallback(k=>p&&o!==void 0&&k in o&&!(k in h),[p,o,h]),y=u.useCallback(k=>{o&&m(x=>{x[k]=o[k]})},[o,m]),_=u.useCallback(k=>m(x=>{x.enabled=k}),[m]),w=d.target!==void 0?"region":"full";return i.jsxs("div",{className:"g7le-overlay-form","data-testid":"g7le-overlay-form",style:Rk,children:[p?i.jsxs("p",{"data-testid":"g7le-overlay-inherit-banner",style:e1,children:["ⓘ ",n("layout_editor.overlay.inherit_banner")]}):null,i.jsxs("div",{style:Hr,children:[i.jsx(Ls,{label:n("layout_editor.overlay.enabled_label"),inherited:v("enabled"),hasInheritance:p,onOverride:()=>y("enabled"),testidKey:"enabled",t:n}),i.jsx(Lr,{disabled:v("enabled"),children:i.jsx(Mr,{checked:c,onChange:_,testid:"g7le-overlay-enabled",ariaLabel:n("layout_editor.overlay.enabled_label"),label:n(c?"layout_editor.overlay.on":"layout_editor.overlay.off")})}),i.jsxs("p",{style:Fr,children:["ⓘ ",n("layout_editor.overlay.enabled_hint")]})]}),i.jsx(Lr,{disabled:!c,testid:"g7le-overlay-body",style:{display:"flex",flexDirection:"column",gap:16,minWidth:0},children:i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:Hr,children:[i.jsx(Ls,{label:n("layout_editor.overlay.scope_label"),inherited:v("target"),hasInheritance:p,onOverride:()=>y("target"),testidKey:"target",t:n}),i.jsxs("div",{"data-testid":"g7le-overlay-scope",style:Ps,children:[i.jsx(jr,{active:w==="full",onClick:()=>m(k=>{delete k.target,delete k.fallback_target}),testid:"g7le-overlay-scope-full",children:n("layout_editor.overlay.scope_full")}),i.jsx(jr,{active:w==="region",onClick:()=>m(k=>{k.target=k.target??""}),testid:"g7le-overlay-scope-region",children:n("layout_editor.overlay.scope_region")})]}),i.jsx(Lr,{disabled:w!=="region",testid:"g7le-overlay-region-box",style:r1,children:i.jsxs(i.Fragment,{children:[i.jsx(Nn,{label:n("layout_editor.overlay.target_label"),children:i.jsx("div",{"data-testid":"g7le-overlay-target-picker",children:f?i.jsx(f,{control:{label:n("layout_editor.overlay.target_label")},value:d.target??"",onChange:k=>m(x=>{x.target=typeof k=="string"?k:""}),t:n}):i.jsx("input",{type:"text","data-testid":"g7le-overlay-target-input",value:d.target??"",onChange:k=>m(x=>{x.target=k.target.value}),style:a1})})}),i.jsx(Nn,{label:n("layout_editor.overlay.fallback_label"),children:i.jsx("div",{"data-testid":"g7le-overlay-fallback-picker",children:f?i.jsx(f,{control:{label:n("layout_editor.overlay.fallback_label")},value:d.fallback_target??"",onChange:k=>m(x=>{const $=typeof k=="string"?k:"";$===""?delete x.fallback_target:x.fallback_target=$}),t:n}):null})}),i.jsxs("p",{style:Fr,children:["ⓘ ",n("layout_editor.overlay.fallback_hint")]})]})})]}),i.jsxs("div",{style:Hr,children:[i.jsx(Ls,{label:n("layout_editor.overlay.style_label"),inherited:v("style"),hasInheritance:p,onOverride:()=>y("style"),testidKey:"style",t:n}),i.jsx("div",{"data-testid":"g7le-overlay-style",style:Ps,children:Zk.map(k=>i.jsx(jr,{active:(d.style??"opaque")===k,onClick:()=>m(x=>{x.style=k}),testid:`g7le-overlay-style-${k}`,children:n(`layout_editor.overlay.style_${k}`)},k))}),d.style==="skeleton"?i.jsxs("div",{style:cu,children:[i.jsx(Nn,{label:n("layout_editor.overlay.skeleton_component"),children:i.jsx(lu,{candidates:s,value:d.skeleton?.component,styleKind:"skeleton",onSelect:k=>m(x=>{x.skeleton={...x.skeleton,component:k}}),t:n,testIdPrefix:"g7le-overlay-skeleton-component"})}),i.jsx(Nn,{label:n("layout_editor.overlay.skeleton_animation"),children:i.jsx("div",{"data-testid":"g7le-overlay-skeleton-anim",style:Ps,children:["wave","pulse","none"].map(k=>i.jsx(jr,{active:(d.skeleton?.animation??"wave")===k,onClick:()=>m(x=>{x.skeleton={...x.skeleton,animation:k}}),testid:`g7le-overlay-skeleton-anim-${k}`,children:n(`layout_editor.overlay.anim_${k}`)},k))})}),i.jsx(Nn,{label:n("layout_editor.overlay.skeleton_count"),children:i.jsx("input",{type:"number","data-testid":"g7le-overlay-skeleton-count",value:d.skeleton?.iteration_count??"",onChange:k=>m(x=>{const $=parseInt(k.target.value,10);x.skeleton={...x.skeleton,iteration_count:Number.isNaN($)?void 0:$}}),style:l1})})]}):null,d.style==="spinner"?i.jsxs("div",{style:cu,children:[i.jsx(Nn,{label:n("layout_editor.overlay.spinner_component"),children:i.jsx(lu,{candidates:s,value:d.spinner?.component,styleKind:"spinner",onSelect:k=>m(x=>{x.spinner={...x.spinner,component:k}}),t:n,testIdPrefix:"g7le-overlay-spinner-component"})}),i.jsx(Nn,{label:n("layout_editor.overlay.spinner_text"),children:i.jsx("div",{"data-testid":"g7le-overlay-spinner-text",style:{minWidth:0},children:i.jsx(_t,{value:d.spinner?.text??"",onChange:k=>m(x=>{x.spinner={...x.spinner,text:k===void 0||k===""?void 0:k}}),t:n,candidates:l,enableExpressionTree:!0,expressionTreeCollapsible:!0,testidPrefix:"g7le-overlay-spinner-text-field"})})})]}):null]}),i.jsxs("div",{style:Hr,children:[i.jsxs("button",{type:"button","data-testid":"g7le-overlay-waitfor-toggle","aria-expanded":b,onClick:()=>g(k=>!k),style:u1,children:[b?"▾":"▸"," ",n("layout_editor.overlay.waitfor_label")]}),b?i.jsxs("div",{"data-testid":"g7le-overlay-waitfor-body",style:p1,children:[i.jsxs("p",{"data-testid":"g7le-overlay-waitfor-hint",style:Fr,children:["ⓘ ",n("layout_editor.overlay.waitfor_hint")]}),a.length===0?i.jsx("p",{"data-testid":"g7le-overlay-waitfor-empty",style:Fr,children:n("layout_editor.overlay.waitfor_empty")}):i.jsx("div",{"data-testid":"g7le-overlay-waitfor",style:{display:"flex",flexWrap:"wrap",gap:6},children:a.map(k=>{const x=(d.wait_for??[]).includes(k.id);return i.jsxs("label",{"data-testid":`g7le-overlay-waitfor-${k.id}`,style:d1(x),children:[i.jsx("input",{type:"checkbox",checked:x,onChange:()=>m($=>{const S=new Set($.wait_for??[]);S.has(k.id)?S.delete(k.id):S.add(k.id);const C=Array.from(S);C.length===0?delete $.wait_for:$.wait_for=C})}),i.jsx(Lc,{option:k,testIdPrefix:`g7le-overlay-waitfor-${k.id}`})]},k.id)})})]}):null]}),p?i.jsxs("button",{type:"button","data-testid":"g7le-overlay-reset-inherit",onClick:()=>t(void 0),style:c1,children:["⟲ ",n("layout_editor.overlay.reset_inherit")]}):null]})})]})}function jr({active:e,onClick:t,children:n,testid:o}){return i.jsx("button",{type:"button","data-testid":o,"aria-pressed":e,onClick:t,style:{...n1,...e?o1:{}},children:n})}function Ls({label:e,inherited:t,hasInheritance:n,onOverride:o,testidKey:r,t:s}){return i.jsxs("div",{style:f1,children:[i.jsx("label",{style:t1,children:e}),n?t?i.jsxs(i.Fragment,{children:[i.jsxs("span",{"data-testid":`g7le-overlay-inherited-${r}`,style:g1,children:["〔",s("layout_editor.overlay.inherited_badge"),"〕"]}),i.jsx("button",{type:"button","data-testid":`g7le-overlay-override-${r}`,onClick:o,style:y1,children:s("layout_editor.overlay.override_field")})]}):i.jsxs("span",{"data-testid":`g7le-overlay-overridden-${r}`,style:h1,children:["〔",s("layout_editor.overlay.overridden_badge"),"〕"]}):null]})}function Nn({label:e,children:t}){return i.jsxs("div",{style:i1,children:[i.jsx("span",{style:s1,children:e}),i.jsx("div",{style:{flex:1,minWidth:0},children:t})]})}const Rk={display:"flex",flexDirection:"column",gap:16,minWidth:0},e1={margin:0,fontSize:12,color:"#1d4ed8",background:"#eff6ff",padding:"8px 10px",borderRadius:6},Hr={display:"flex",flexDirection:"column",gap:6,minWidth:0},t1={fontSize:13,fontWeight:600,color:"#0f172a"},Fr={margin:0,fontSize:11,color:"#94a3b8"},Ps={display:"flex",gap:4,flexWrap:"wrap"},n1={padding:"4px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},o1={border:"1px solid #3b82f6",background:"#eff6ff",color:"#1d4ed8"},r1={display:"flex",flexDirection:"column",gap:8,padding:8,border:"1px dashed #e2e8f0",borderRadius:8},cu={display:"flex",flexDirection:"column",gap:8,padding:8,border:"1px dashed #e2e8f0",borderRadius:8},i1={display:"flex",alignItems:"center",gap:8,minWidth:0},s1={fontSize:11,color:"#64748b",minWidth:90},a1={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},l1={width:80,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},d1=e=>({display:"inline-flex",alignItems:"center",gap:4,padding:"4px 8px",fontSize:12,border:`1px solid ${e?"#3b82f6":"#cbd5e1"}`,borderRadius:12,background:e?"#eff6ff":"#fff",cursor:"pointer"}),c1={alignSelf:"flex-start",padding:"6px 12px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},u1={alignSelf:"flex-start",padding:"4px 0",fontSize:13,fontWeight:600,color:"#0f172a",background:"transparent",border:"none",cursor:"pointer"},p1={display:"flex",flexDirection:"column",gap:6,paddingLeft:14,minWidth:0},f1={display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",minWidth:0},g1={fontSize:11,color:"#64748b",background:"#f1f5f9",borderRadius:4,padding:"1px 6px"},h1={fontSize:11,color:"#0369a1",background:"#e0f2fe",borderRadius:4,padding:"1px 6px"},y1={padding:"2px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},b1="g7le:computed-effect-preview",m1={number:"layout_editor.computed.type_number",string:"layout_editor.computed.type_string",boolean:"layout_editor.computed.type_boolean",list:"layout_editor.computed.type_list",object:"layout_editor.computed.type_object",null:"layout_editor.computed.type_null"};function v1(e,t,n){if(t==="list"){const o=e,r=o.slice(0,2).map(s=>JSON.stringify(s)).join(", ");return o.length<=2?`[${r}]`:`[${r}, ${n("layout_editor.computed.list_more",{count:o.length})}]`}return t==="object"?JSON.stringify(e):t==="boolean"?e?"true":"false":t==="null"?n("layout_editor.computed.value_none"):String(e)}function uu({expr:e,computedKey:t,sampleContext:n,t:o,isEffect:r=!1,testIdPrefix:s="g7le-computed-preview"}){const a=zd(e,n),l=()=>{typeof window>"u"||!t||window.dispatchEvent(new CustomEvent(b1,{detail:{key:t}}))};return a.ok?i.jsxs("div",{className:s,"data-testid":s,style:_1,children:[i.jsx("span",{style:x1,children:o("layout_editor.computed.preview_label")}),i.jsx("span",{"data-testid":`${s}-value`,style:w1,children:v1(a.value,a.type,o)}),i.jsxs("span",{"data-testid":`${s}-type`,style:k1,children:["(",o(m1[a.type]),")"]}),r&&a.type==="boolean"?i.jsxs("button",{type:"button","data-testid":`${s}-effect`,onClick:l,style:S1,children:["▷ ",o("layout_editor.computed.effect_preview")]}):null]}):i.jsxs("div",{"data-testid":`${s}-error`,style:C1,children:["⚠ ",o("layout_editor.computed.preview_error")]})}const _1={display:"flex",alignItems:"center",flexWrap:"wrap",gap:6,minWidth:0},x1={fontSize:11,color:"#94a3b8"},w1={fontSize:12,color:"#0f172a",fontFamily:"monospace",wordBreak:"break-all"},k1={fontSize:10,color:"#64748b"},S1={padding:"2px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},C1={fontSize:12,color:"#b45309"},$1=[{op:"count",labelKey:"layout_editor.computed.op_count"},{op:"sum",labelKey:"layout_editor.computed.op_sum"},{op:"filter",labelKey:"layout_editor.computed.op_filter"},{op:"toOptions",labelKey:"layout_editor.computed.op_to_options"},{op:"nth",labelKey:"layout_editor.computed.op_nth"},{op:"firstOf",labelKey:"layout_editor.computed.op_first_of"},{op:"literal",labelKey:"layout_editor.computed.op_literal"}],E1=["=","!=",">","<",">=","<=","includes"],I1=new Set(["count","sum","filter"]);function pu({model:e,onChange:t,t:n,dataSourceCandidates:o,bindingCandidates:r,existingKeys:s=[]}){const a=u.useCallback(g=>{const m={...e};g(m),t(m)},[e,t]),l=e.conditions??[],d=Tn("datasource-picker"),c=e.key!==""&&s.includes(e.key),p=()=>a(g=>{g.conditions=[...g.conditions??[],{field:"",cmp:"=",value:""}]}),f=(g,m)=>a(h=>{const v=(h.conditions??[]).slice(),y={...v[g]};m(y),v[g]=y,h.conditions=v}),b=g=>a(m=>{m.conditions=(m.conditions??[]).filter((h,v)=>v!==g)});return i.jsxs("div",{className:"g7le-computed-custom","data-testid":"g7le-computed-custom",style:A1,children:[i.jsx(Os,{label:`① ${n("layout_editor.computed.custom_step1")}`,children:i.jsx("div",{"data-testid":"g7le-computed-custom-source",children:d?i.jsx(d,{control:{},value:e.source,onChange:g=>a(m=>{m.source=typeof g=="string"?g:void 0}),t:n,candidates:o}):i.jsx("input",{type:"text",value:e.source??"",onChange:g=>a(m=>{m.source=g.target.value}),style:ro})})}),i.jsxs(Os,{label:`② ${n("layout_editor.computed.custom_step2")}`,children:[i.jsx("select",{"data-testid":"g7le-computed-custom-op",value:e.op,onChange:g=>a(m=>{m.op=g.target.value}),style:ro,children:$1.map(({op:g,labelKey:m})=>i.jsx("option",{value:g,children:n(m)},g))}),e.op==="sum"?i.jsx("div",{"data-testid":"g7le-computed-custom-sumfield",style:{minWidth:0},children:i.jsx(Ke,{value:e.sumField??"",onChange:g=>a(m=>{m.sumField=g}),t:n,candidates:r,placeholder:n("layout_editor.computed.custom_sum_field"),testidPrefix:"g7le-computed-custom-sumfield-chip"})}):null,e.op==="toOptions"?i.jsxs("div",{style:{display:"flex",gap:6},children:[i.jsx("div",{"data-testid":"g7le-computed-custom-valuefield",style:{flex:1,minWidth:0},children:i.jsx(Ke,{value:e.valueField??"",onChange:g=>a(m=>{m.valueField=g}),t:n,candidates:r,placeholder:n("layout_editor.computed.custom_value_field"),testidPrefix:"g7le-computed-custom-valuefield-chip"})}),i.jsx("div",{"data-testid":"g7le-computed-custom-labelfield",style:{flex:1,minWidth:0},children:i.jsx(Ke,{value:e.labelField??"",onChange:g=>a(m=>{m.labelField=g}),t:n,candidates:r,placeholder:n("layout_editor.computed.custom_label_field"),testidPrefix:"g7le-computed-custom-labelfield-chip"})})]}):null,e.op==="nth"?i.jsxs("div",{style:{display:"flex",gap:6},children:[i.jsx("input",{type:"text","data-testid":"g7le-computed-custom-index",value:e.index??"",placeholder:"0",onChange:g=>a(m=>{m.index=g.target.value}),style:ro}),i.jsx("div",{"data-testid":"g7le-computed-custom-prop",style:{flex:1,minWidth:0},children:i.jsx(Ke,{value:e.prop??"",onChange:g=>a(m=>{m.prop=g}),t:n,candidates:r,placeholder:n("layout_editor.computed.custom_prop"),testidPrefix:"g7le-computed-custom-prop-chip"})})]}):null,e.op==="literal"?i.jsxs("div",{style:{display:"flex",gap:6},children:[i.jsxs("select",{"data-testid":"g7le-computed-custom-literalkind",value:e.literalKind??"string",onChange:g=>a(m=>{m.literalKind=g.target.value}),style:ro,children:[i.jsx("option",{value:"string",children:n("layout_editor.computed.kind_string")}),i.jsx("option",{value:"number",children:n("layout_editor.computed.kind_number")}),i.jsx("option",{value:"boolean",children:n("layout_editor.computed.kind_boolean")})]}),i.jsx("div",{"data-testid":"g7le-computed-custom-literalvalue",style:{flex:1,minWidth:0},children:i.jsx(Ke,{value:e.literalValue??"",onChange:g=>a(m=>{m.literalValue=g}),t:n,candidates:r,testidPrefix:"g7le-computed-custom-literalvalue-chip"})})]}):null,e.op==="firstOf"?i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("input",{type:"text","data-testid":"g7le-computed-custom-candidates",value:(e.candidates??[]).join(", "),placeholder:n("layout_editor.computed.custom_candidates"),onChange:g=>a(m=>{m.candidates=g.target.value.split(",").map(h=>h.trim()).filter(Boolean)}),style:ro}),i.jsx("div",{"data-testid":"g7le-computed-custom-fallback",style:{minWidth:0},children:i.jsx(Ke,{value:e.fallback??"",onChange:g=>a(m=>{m.fallback=g}),t:n,candidates:r,placeholder:n("layout_editor.computed.custom_fallback"),testidPrefix:"g7le-computed-custom-fallback-chip"})})]}):null,I1.has(e.op)?i.jsxs("div",{style:N1,children:[l.map((g,m)=>i.jsxs("div",{"data-testid":`g7le-computed-custom-cond-${m}`,style:M1,children:[i.jsx("div",{"data-testid":`g7le-computed-custom-cond-field-${m}`,style:{flex:1,minWidth:0},children:i.jsx(Ke,{value:g.field,onChange:h=>f(m,v=>{v.field=h}),t:n,candidates:r,placeholder:n("layout_editor.computed.cond_field"),testidPrefix:`g7le-computed-custom-cond-field-${m}-chip`})}),i.jsx("select",{value:g.cmp,onChange:h=>f(m,v=>{v.cmp=h.target.value}),style:L1,children:E1.map(h=>i.jsx("option",{value:h,children:h},h))}),i.jsx("div",{"data-testid":`g7le-computed-custom-cond-value-${m}`,style:{flex:1,minWidth:0},children:i.jsx(Ke,{value:g.value,onChange:h=>f(m,v=>{v.value=h}),t:n,candidates:r,placeholder:n("layout_editor.computed.cond_value"),testidPrefix:`g7le-computed-custom-cond-value-${m}-chip`})}),i.jsx("button",{type:"button","data-testid":`g7le-computed-custom-cond-remove-${m}`,onClick:()=>b(m),style:P1,children:"✕"})]},m)),i.jsxs("button",{type:"button","data-testid":"g7le-computed-custom-cond-add",onClick:p,style:O1,children:["+ ",n("layout_editor.computed.cond_add")]})]}):null]}),i.jsxs(Os,{label:`③ ${n("layout_editor.computed.custom_step3")}`,children:[i.jsx("input",{type:"text","data-testid":"g7le-computed-custom-key",value:e.key,onChange:g=>a(m=>{m.key=g.target.value}),style:{...ro,...c?z1:{}}}),c?i.jsxs("p",{"data-testid":"g7le-computed-custom-key-dup",style:B1,children:["⚠ ",n("layout_editor.computed.key_duplicate")]}):null]})]})}function Os({label:e,children:t}){return i.jsxs("div",{style:T1,children:[i.jsx("div",{style:D1,children:e}),i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0},children:t})]})}function Bs(e){return Zm(e)}const A1={display:"flex",flexDirection:"column",gap:12,padding:10,border:"1px solid #cbd5e1",borderRadius:8,background:"#fff"},T1={display:"flex",flexDirection:"column",gap:4,minWidth:0},D1={fontSize:12,fontWeight:600,color:"#475569"},ro={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:0,width:"100%",boxSizing:"border-box"},z1={border:"1px solid #ef4444"},N1={display:"flex",flexDirection:"column",gap:6,marginTop:4},M1={display:"flex",gap:4,alignItems:"center",minWidth:0},L1={padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},P1={border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12},O1={alignSelf:"flex-start",padding:"2px 8px",fontSize:11,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},B1={margin:0,fontSize:11,color:"#b45309"};function Ws(e,t,n){return typeof e!="string"?n:e.startsWith("$t:")?t(e.slice(3)):e}function W1(e){if(e&&typeof e=="object"){const t=e.__source;if(t&&typeof t=="object")return t}return null}function j1({computed:e,onChange:t,recipes:n,t:o,sampleContext:r,dataSourceCandidates:s,bindingCandidates:a,computedSource:l={},effectKeys:d=[],onRevert:c}){const p=u.useMemo(()=>Cd(n),[n]),[f,b]=u.useState(!1),[g,m]=u.useState(null),h=Object.keys(e),v=u.useCallback((x,$)=>{t({...e,[x]:$})},[e,t]),y=u.useCallback(x=>{const $={...e};delete $[x],t($)},[e,t]),_=u.useCallback((x,$,S)=>{const C={...e};x&&x!==$&&delete C[x],C[$]=S,t(C)},[e,t]),w=u.useCallback(x=>{const $=Ed(x,{});let S=x.id,C=1;for(;S in e;)S=`${x.id}${++C}`;t({...e,[S]:$}),b(!1)},[e,t]),k=u.useCallback(()=>{!g||!g.key||(t({...e,[g.key]:Bs(g)}),m(null),b(!1))},[g,e,t]);return i.jsxs("div",{className:"g7le-computed-form","data-testid":"g7le-computed-form",style:V1,children:[i.jsx("p",{style:U1,children:o("layout_editor.page_settings.computed.heading")}),h.length>0?h.map(x=>i.jsx(H1,{computedKey:x,expr:e[x],recipes:p,rawRecipes:n,t:o,sampleContext:r,dataSourceCandidates:s,bindingCandidates:a,source:l[x],isEffect:d.includes(x),existingKeys:h,onPatchExpr:$=>v(x,$),onRename:($,S)=>_(x,$,S),onRemove:()=>y(x),onRevert:c?()=>c(x):void 0},x)):i.jsx("p",{"data-testid":"g7le-computed-empty",style:gS,children:o("layout_editor.computed.empty")}),i.jsxs("div",{style:{minWidth:0},children:[i.jsxs("button",{type:"button","data-testid":"g7le-computed-add",onClick:()=>b(x=>!x),style:sS,children:["+ ",o("layout_editor.computed.add")," ▾"]}),f?i.jsxs("div",{"data-testid":"g7le-computed-add-list",style:aS,children:[["common","more"].map(x=>{const $=p.filter(S=>(S.group??"more")===x);return $.length===0?null:i.jsxs("div",{children:[i.jsxs("div",{style:lS,children:["━━ ",o(`layout_editor.computed.group_${x}`)," ━━"]}),$.map(S=>{const C=W1(n?.[S.id]);return i.jsxs("button",{type:"button","data-testid":`g7le-computed-preset-${S.id}`,onClick:()=>w(S),style:dS,children:[i.jsx("span",{style:cS,children:Ws(S.label,o,S.id)}),C&&C.kind!=="core"?i.jsxs("span",{"data-testid":`g7le-computed-preset-source-${S.id}`,style:uS,children:["〔",C.id??C.kind,"〕"]}):null]},S.id)})]},x)}),i.jsxs("div",{style:{borderTop:"1px solid #e2e8f0",marginTop:6,paddingTop:6},children:[i.jsxs("button",{type:"button","data-testid":"g7le-computed-custom-open",onClick:()=>m(g?null:{key:"",op:"count",source:"",conditions:[]}),style:pS,children:["⚙ ",o("layout_editor.computed.custom_open")," ▾"]}),g?i.jsxs("div",{style:{marginTop:6},children:[i.jsx(pu,{model:g,onChange:m,t:o,dataSourceCandidates:s,bindingCandidates:a,existingKeys:h}),i.jsx("div",{"data-testid":"g7le-computed-custom-preview",style:{marginTop:6},children:i.jsx(uu,{expr:Bs(g),sampleContext:r,t:o,testIdPrefix:"g7le-computed-custom-preview-eval"})}),i.jsx("button",{type:"button","data-testid":"g7le-computed-custom-commit",disabled:!g.key||h.includes(g.key),onClick:k,style:fS,children:o("layout_editor.computed.custom_add")})]}):null]})]}):null]})]})}function H1({computedKey:e,expr:t,recipes:n,rawRecipes:o,t:r,sampleContext:s,dataSourceCandidates:a,bindingCandidates:l,source:d,isEffect:c,existingKeys:p,onPatchExpr:f,onRename:b,onRemove:g,onRevert:m}){const[h,v]=u.useState(!1),[y,_]=u.useState(!1),w=u.useMemo(()=>Dd(t,n),[t,n]),k=d==="base",x=d==="route-override",$=w.kind==="advanced",S=w.kind==="preset"?n.find(E=>E.id===w.recipeId)??null:null,C=S?Ws(S.label,r,e):e,T=(E,A)=>{if(w.kind!=="preset"||!S)return;const N={...w.params,[E]:A};f(Ed(S,N))};return i.jsxs("div",{"data-testid":`g7le-computed-item-${e}`,style:q1,children:[i.jsxs("div",{style:G1,children:[i.jsx("span",{style:Y1,children:C}),i.jsx("code",{style:X1,children:e}),k?i.jsxs("span",{"data-testid":`g7le-computed-source-${e}`,style:J1,children:["〔",r("layout_editor.computed.source_base"),"〕"]}):null,x?i.jsxs("span",{"data-testid":`g7le-computed-overridden-${e}`,style:Z1,children:["〔",r("layout_editor.computed.source_overridden"),"〕"]}):null,$?i.jsxs("span",{"data-testid":"g7le-computed-advanced",style:Q1,children:["[",r("layout_editor.action.advanced"),"]"]}):null,i.jsx("span",{style:{flex:1}}),i.jsx("button",{type:"button","data-testid":`g7le-computed-code-${e}`,onClick:()=>_(E=>!E),style:js,"aria-label":r("layout_editor.value_tree.show_source"),title:r("layout_editor.value_tree.show_source"),children:""}),$?null:i.jsx("button",{type:"button","data-testid":`g7le-computed-edit-${e}`,onClick:()=>v(E=>!E),style:js,children:r("layout_editor.init_actions.edit")}),i.jsx("button",{type:"button","data-testid":`g7le-computed-remove-${e}`,onClick:g,style:js,"aria-label":r("layout_editor.init_actions.remove"),children:"✕"})]}),y?i.jsx("pre",{"data-testid":`g7le-computed-code-block-${e}`,style:hS,children:t}):null,i.jsx("div",{"data-testid":`g7le-computed-preview-${e}`,children:i.jsx(uu,{expr:t,computedKey:e,sampleContext:s,t:r,isEffect:c,testIdPrefix:`g7le-computed-preview-${e}-eval`})}),x&&m?i.jsxs("div",{style:R1,children:[i.jsxs("span",{style:eS,children:["ⓘ ",r("layout_editor.computed.overridden_hint")]}),i.jsx("button",{type:"button","data-testid":`g7le-computed-revert-${e}`,onClick:m,style:tS,children:r("layout_editor.computed.revert")})]}):null,h&&!$?i.jsxs("div",{style:nS,children:[k?i.jsxs("p",{"data-testid":`g7le-computed-override-notice-${e}`,style:oS,children:["⚠ ",r("layout_editor.computed.override_notice")]}):null,w.kind==="preset"&&S?i.jsx(i.Fragment,{children:S.params.map(E=>i.jsx(K1,{param:E,value:w.params[E.key]??"",t:r,dataSourceCandidates:a,bindingCandidates:l,onChange:A=>T(E.key,A)},E.key))}):w.kind==="custom"?i.jsx(pu,{model:{...w.model,key:e},onChange:E=>b(E.key,Bs(E)),t:r,dataSourceCandidates:a,bindingCandidates:l,existingKeys:p.filter(E=>E!==e)}):null]}):null]})}const F1=new Set(["datasource-picker","binding-picker","select","toggle","state-key-picker","page-picker"]);function K1({param:e,value:t,t:n,dataSourceCandidates:o,bindingCandidates:r,onChange:s}){const a=Ws(e.label,n,e.key),l=e.widget??"",c=F1.has(l)?Tn(e.widget):null,p=l==="datasource-picker"||l==="binding-picker"?o:void 0;return i.jsxs("div",{"data-testid":`g7le-computed-param-${e.key}`,style:rS,children:[i.jsx("span",{style:iS,children:a}),i.jsx("div",{style:{flex:1,minWidth:0},children:c?i.jsx(c,{control:{...e},value:t,onChange:f=>s(typeof f=="string"?f:""),t:n,candidates:p}):i.jsx(Ke,{value:t,onChange:f=>s(f),t:n,candidates:r,testidPrefix:`g7le-computed-param-${e.key}-chip`})})]})}const V1={display:"flex",flexDirection:"column",gap:12,minWidth:0},U1={margin:0,fontSize:13,fontWeight:700,color:"#0f172a"},q1={border:"1px solid #e2e8f0",borderRadius:8,padding:"8px 10px",display:"flex",flexDirection:"column",gap:6,background:"#f8fafc"},G1={display:"flex",alignItems:"center",gap:6},Y1={fontSize:13,fontWeight:600,color:"#0f172a"},X1={fontSize:10,color:"#64748b",fontFamily:"monospace"},J1={fontSize:10,color:"#0891b2",whiteSpace:"nowrap"},Z1={fontSize:10,color:"#7c3aed",whiteSpace:"nowrap"},Q1={fontSize:10,color:"#92400e",whiteSpace:"nowrap"},R1={display:"flex",alignItems:"center",gap:8,marginTop:4,minWidth:0},eS={fontSize:11,color:"#7c3aed",flex:1,minWidth:0},tS={border:"1px solid #c4b5fd",borderRadius:6,background:"#f5f3ff",color:"#6d28d9",cursor:"pointer",fontSize:11,padding:"2px 8px",whiteSpace:"nowrap"},js={border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",fontSize:11,padding:"2px 6px"},nS={display:"flex",flexDirection:"column",gap:6,paddingTop:6,borderTop:"1px dashed #e2e8f0"},oS={margin:0,fontSize:11,color:"#b45309",background:"#fef3c7",padding:"6px 8px",borderRadius:6},rS={display:"flex",alignItems:"center",gap:8,minWidth:0},iS={fontSize:11,color:"#64748b",minWidth:90},sS={padding:"6px 12px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},aS={marginTop:6,border:"1px solid #cbd5e1",borderRadius:8,background:"#fff",padding:8,maxHeight:380,overflowY:"auto"},lS={fontSize:11,fontWeight:700,color:"#94a3b8",padding:"6px 4px 2px"},dS={display:"flex",alignItems:"center",gap:6,width:"100%",textAlign:"left",padding:"6px 8px",fontSize:12,border:"none",background:"transparent",cursor:"pointer",borderRadius:6},cS={flex:1,minWidth:0,color:"#0f172a"},uS={fontSize:10,color:"#64748b",whiteSpace:"nowrap"},pS={padding:"6px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},fS={marginTop:6,padding:"6px 12px",fontSize:12,border:"1px solid #3b82f6",borderRadius:6,background:"#3b82f6",color:"#fff",cursor:"pointer"},gS={margin:0,fontSize:12,color:"#94a3b8"},hS={margin:"2px 0 0",padding:"6px 8px",fontSize:11,fontFamily:"monospace",color:"#0f172a",background:"#f1f5f9",border:"1px solid #e2e8f0",borderRadius:6,whiteSpace:"pre-wrap",wordBreak:"break-all",overflowX:"auto"};function yS(e,t){return t==="any"?!0:e===null||typeof e!="object"?!1:t==="object"?!Array.isArray(e):!0}function Hs({value:e,onChange:t,onValidityChange:n,t:o,shape:r="any",emptyValue:s=void 0,placeholder:a,minHeight:l=80,testidPrefix:d="g7le-json-block",shapeErrorKey:c,invalidErrorKey:p,ariaLabel:f,id:b,validate:g}){const[m,h]=u.useState(()=>Kr(e)),[v,y]=u.useState(null),_=u.useRef(!1),w=u.useRef(e);u.useEffect(()=>{if(!_.current&&!Object.is(e,w.current)){if(Kr(e)===Kr(w.current)){w.current=e;return}h(Kr(e)),y(null),w.current=e,n?.(!0)}},[e]);const k=x=>{if(_.current=!0,h(x),x.trim()===""){y(null),w.current=s,n?.(!0),t(s);return}let $;try{$=JSON.parse(x)}catch{y(o(p??"layout_editor.json_block.invalid")),n?.(!1);return}if(!yS($,r)){y(o(c??"layout_editor.json_block.invalid")),n?.(!1);return}const S=g?.($)??null;if(S){y(S),n?.(!1);return}y(null),w.current=$,n?.(!0),t($)};return i.jsxs("div",{className:"g7le-json-block",style:bS,children:[i.jsx("textarea",{id:b,"data-testid":d,style:{...mS,minHeight:l},value:m,spellCheck:!1,"aria-label":f,"aria-invalid":v?!0:void 0,placeholder:a,onChange:x=>k(x.target.value),onBlur:()=>{_.current=!1}}),v?i.jsx("div",{"data-testid":`${d}-error`,style:vS,children:v}):null]})}function Kr(e){if(e===void 0)return"";try{return JSON.stringify(e,null,2)??""}catch{return""}}const bS={display:"flex",flexDirection:"column",gap:4,minWidth:0},mS={width:"100%",boxSizing:"border-box",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:12,lineHeight:1.5,color:"#0f172a",background:"#fff",border:"1px solid #cbd5e1",borderRadius:6,padding:"6px 8px",resize:"vertical"},vS={fontSize:11,color:"#dc2626"},_S=[{kind:"string",labelKey:"layout_editor.initstate.kind_string"},{kind:"number",labelKey:"layout_editor.initstate.kind_number"},{kind:"boolean",labelKey:"layout_editor.initstate.kind_boolean"},{kind:"null",labelKey:"layout_editor.initstate.kind_null"},{kind:"list",labelKey:"layout_editor.initstate.kind_list"},{kind:"object",labelKey:"layout_editor.initstate.kind_object"}],Fs={local:"initLocal",global:"initGlobal",isolated:"initIsolated"};function xS({raw:e,own:t,patch:n,t:o,isolatedOrphan:r={}}){const s=u.useMemo(()=>{const f=t?.state&&typeof t.state=="object"?t.state:void 0,b=e?.state&&typeof e.state=="object"?e.state:void 0;if(!(!f&&!b))return{...b??{},...f??{}}},[t,e]),{initLocal:a,migrated:l}=u.useMemo(()=>K0({initLocal:e?.initLocal,state:s}),[e,s]),d=f=>{if(f==="local")return a;const b=e?.[Fs[f]];return b&&typeof b=="object"?b:{}},c=f=>{if(f==="local"){const b=t?.initLocal??{},g=s?Object.keys(s):[];return Array.from(new Set([...Object.keys(b),...g]))}return Object.keys(t?.[Fs[f]]??{})},p=u.useCallback((f,b)=>{const g=Fs[f];f==="local"&&l&&n("state",void 0),n(g,Object.keys(b).length===0?void 0:b)},[n,l]);return i.jsxs("div",{className:"g7le-initstate-form","data-testid":"g7le-initstate-form",style:kS,children:[i.jsx("p",{style:SS,children:o("layout_editor.page_settings.initstate.heading")}),l?i.jsxs("p",{"data-testid":"g7le-initstate-legacy-state",style:CS,children:["ⓘ ",o("layout_editor.initstate.legacy_state")]}):null,i.jsx(Ks,{scope:"local",label:o("layout_editor.initstate.section_local"),value:d("local"),ownKeys:c("local"),patchSection:p,t:o}),i.jsx(Ks,{scope:"global",label:o("layout_editor.initstate.section_global"),value:d("global"),ownKeys:c("global"),patchSection:p,t:o}),i.jsx(Ks,{scope:"isolated",label:o("layout_editor.initstate.section_isolated"),description:o("layout_editor.initstate.section_isolated_desc"),value:d("isolated"),ownKeys:c("isolated"),patchSection:p,t:o,orphan:r}),i.jsxs("p",{style:KS,children:["ⓘ ",o("layout_editor.initstate.isolated_dynamic_hint")]})]})}function Ks({scope:e,label:t,description:n,value:o,ownKeys:r,patchSection:s,t:a,orphan:l={}}){const[d,c]=u.useState(""),[p,f]=u.useState("string"),[b,g]=u.useState(null),[m,h]=u.useState(!1),v=Object.keys(o),y=v,_=(x,$)=>{s(e,{...o,[x]:$})},w=x=>{const $={...o};delete $[x],s(e,$)},k=()=>{const x=d.trim();if(!x){g(a("layout_editor.initstate.name_required"));return}if(!Ds(x)){g(a("layout_editor.initstate.name_invalid"));return}if(x in o){g(a("layout_editor.initstate.name_duplicate"));return}const $={string:"",number:0,boolean:!1,null:null,list:[],object:{}};s(e,{...o,[x]:$[p]}),c(""),g(null)};return i.jsxs("div",{"data-testid":`g7le-initstate-section-${e}`,style:$S,children:[i.jsxs("div",{style:ES,children:[i.jsx("div",{style:IS,children:t}),i.jsx("button",{type:"button","data-testid":`g7le-initstate-${e}-mode-toggle`,onClick:()=>h(x=>!x),style:TS,children:a(m?"layout_editor.json_block.mode_block":"layout_editor.json_block.mode_code")})]}),n?i.jsxs("p",{style:AS,children:["ⓘ ",n]}):null,m?i.jsx(Hs,{value:o,shape:"object",emptyValue:{},onChange:x=>s(e,x??{}),t:a,testidPrefix:`g7le-initstate-${e}-code`,placeholder:`{ +var OM=Object.defineProperty;var BM=(dn,i,u)=>i in dn?OM(dn,i,{enumerable:!0,configurable:!0,writable:!0,value:u}):dn[i]=u;var Ni=(dn,i,u)=>BM(dn,typeof i!="symbol"?i+"":i,u);(function(dn,i,u,Cn){"use strict";function Lt(){const e=typeof window<"u"?window.G7Core?.__runtime:void 0;if(!e)throw new Error("[layout-editor] window.G7Core.__runtime 이 없습니다. 코어 번들(template-engine.min.js)이 편집기 번들보다 먼저 로드되어야 합니다.");return e}const Mi=Lt();Mi.TranslationProvider;const tt=Mi.useTranslation;Mi.TranslationReactContext;function rt(){return typeof window>"u"?null:window.__g7Devtools??null}function Il(e,t){const n=rt();if(!n?.trackEditorState)return;const o={templateIdentifier:e.templateIdentifier,editMode:e.editMode,selectedRoutePath:e.selectedRoute?.path??null,selectedLayoutName:e.selectedRoute?.layoutName??null,routeTreeSize:e.routeTree.length,isRouteTreeCollapsed:e.isRouteTreeCollapsed,locale:e.locale,previewDevice:e.previewDevice,previewZoom:e.previewZoom,lastAction:t,timestamp:Date.now()};try{n.trackEditorState(o)}catch{}}function Zh(){const e=rt();if(e?.clearEditorStateData)try{e.clearEditorStateData()}catch{}}function Qh(e){const t=rt();if(t?.trackEditorSampleMatch)try{t.trackEditorSampleMatch(e)}catch{}}function Rh(){const e=rt();if(e?.clearEditorSampleData)try{e.clearEditorSampleData()}catch{}}function ey(e){const t=rt();if(t?.trackEditorHistoryEntry)try{t.trackEditorHistoryEntry(e)}catch{}}function ty(){const e=rt();if(e?.clearEditorHistoryData)try{e.clearEditorHistoryData()}catch{}}function Al(e){const t=rt();if(t?.trackEditorSelection)try{t.trackEditorSelection(e)}catch{}}function ny(){const e=rt();if(e?.clearEditorSelectionData)try{e.clearEditorSelectionData()}catch{}}function dr(e){const t=rt();if(t?.trackEditorPropertyPatch)try{t.trackEditorPropertyPatch(e)}catch{}}function $n(e){const t=rt();if(t?.trackEditorDnd)try{t.trackEditorDnd(e)}catch{}}function oy(){const e=rt();if(e?.clearEditorDndData)try{e.clearEditorDndData()}catch{}}function st(e){const t=rt();if(t?.trackEditorDocument)try{t.trackEditorDocument(e)}catch{}}function ry(){const e=rt();if(e?.clearEditorDocumentData)try{e.clearEditorDocumentData()}catch{}}function iy(e){const t=rt();if(t?.trackEditorSpecMerge)try{t.trackEditorSpecMerge(e)}catch{}}function sy(){const e=rt();if(e?.clearEditorSpecMergeData)try{e.clearEditorSpecMergeData()}catch{}}function Li(e){let t=5381;for(let n=0;n>>0;return t}function Et(e){const t=rt();if(t?.trackEditorI18n)try{t.trackEditorI18n(e)}catch{}}function ay(){const e=rt();if(e?.clearEditorI18nData)try{e.clearEditorI18nData()}catch{}}function Tl(e){const t=rt();if(t?.trackPageState)try{t.trackPageState(e)}catch{}}function ly(){const e=rt();if(e?.clearPageStateData)try{e.clearPageStateData()}catch{}}const Dl="g7le.routeTree.collapsed";function dy(){if(typeof window>"u")return!1;try{return window.localStorage?.getItem(Dl)==="1"}catch{return!1}}function cy(e){if(!(typeof window>"u"))try{window.localStorage?.setItem(Dl,e?"1":"0")}catch{}}function uy(e,t){return{templateIdentifier:e,routeTree:[],routesError:null,selectedRoute:null,isRouteTreeCollapsed:dy(),editMode:"route",returnRoute:null,returnEditMode:null,locale:t,previewDevice:"desktop",previewZoom:1,previewCustomWidth:1024,previewColorScheme:"light",history:{canUndo:!1,canRedo:!1},isPaletteOpen:!1,availableStates:[],activeStateId:null,layoutVersions:{},extensionVersions:{}}}function py(e,t){switch(t.type){case"SET_ROUTE_TREE":return{...e,routeTree:t.tree,routesError:null};case"SET_ROUTES_ERROR":return{...e,routesError:t.error};case"SELECT_ROUTE":return{...e,editMode:"route",selectedRoute:t.route,returnRoute:null,returnEditMode:null};case"TOGGLE_ROUTE_TREE":return{...e,isRouteTreeCollapsed:!e.isRouteTreeCollapsed};case"SET_LOCALE":return{...e,locale:t.locale};case"ENTER_BASE_EDIT":return{...e,editMode:"base",returnRoute:t.returnRoute!==void 0?t.returnRoute:e.selectedRoute,selectedRoute:{path:`__base__/${t.layoutName}`,layoutName:t.layoutName}};case"EXIT_BASE_EDIT":return{...e,editMode:"route",selectedRoute:e.returnRoute,returnRoute:null};case"ENTER_MODAL_EDIT":return{...e,editMode:"modal",returnRoute:t.returnRoute!==void 0?t.returnRoute:e.selectedRoute,selectedRoute:{path:`__modal__/${t.modalId}`,layoutName:t.hostLayout}};case"EXIT_MODAL_EDIT":return{...e,editMode:"route",selectedRoute:e.returnRoute,returnRoute:null};case"ENTER_EXTENSION_EDIT":return{...e,editMode:"extension",returnRoute:t.returnRoute!==void 0?t.returnRoute:e.selectedRoute,selectedRoute:{path:`__extension__/${t.extensionId}`,layoutName:t.extensionHost??null}};case"SET_RETURN_ROUTE":return e.editMode==="route"||e.returnRoute!==null?e:{...e,returnRoute:t.route};case"EXIT_EXTENSION_EDIT":return{...e,editMode:"route",selectedRoute:e.returnRoute,returnRoute:null};case"ENTER_ITERATION_ITEM_EDIT":return{...e,editMode:"iteration_item",returnRoute:t.returnRoute!==void 0?t.returnRoute:e.selectedRoute,returnEditMode:e.editMode,selectedRoute:{path:`__iteration__/${t.sourcePath}`,layoutName:t.hostLayout??e.selectedRoute?.layoutName??null}};case"EXIT_ITERATION_ITEM_EDIT":return{...e,editMode:e.returnEditMode??"route",selectedRoute:e.returnRoute,returnRoute:null,returnEditMode:null};case"SET_PREVIEW_DEVICE":return{...e,previewDevice:t.device};case"SET_PREVIEW_ZOOM":return{...e,previewZoom:t.zoom};case"SET_PREVIEW_CUSTOM_WIDTH":return{...e,previewCustomWidth:t.width};case"SET_PREVIEW_COLOR_SCHEME":return{...e,previewColorScheme:t.scheme};case"TOGGLE_PALETTE":return{...e,isPaletteOpen:!e.isPaletteOpen};case"SET_PALETTE_OPEN":return{...e,isPaletteOpen:t.open};case"SET_AVAILABLE_STATES":return{...e,availableStates:t.states,activeStateId:t.activeStateId};case"SET_ACTIVE_STATE":return{...e,activeStateId:t.activeStateId};case"SET_LAYOUT_VERSIONS":return{...e,layoutVersions:t.versions};case"SET_LAYOUT_VERSION":return{...e,layoutVersions:{...e.layoutVersions,[t.layoutName]:t.version}};case"SET_EXTENSION_VERSIONS":return{...e,extensionVersions:t.versions};case"SET_EXTENSION_VERSION":return{...e,extensionVersions:{...e.extensionVersions,[t.extensionId]:t.version}};default:return e}}function fy(e,t){const n=py(e,t);return((n.selectedRoute?.path??null)!==(e.selectedRoute?.path??null)||n.editMode!==e.editMode)&&(n.availableStates.length>0||n.activeStateId!==null)?{...n,availableStates:[],activeStateId:null}:n}const zl=u.createContext(null);function gy(e,t){const n=fy(e,t);return Il(n,t.type),n}function hy({templateIdentifier:e,initialLocale:t,children:n}){const[o,r]=u.useReducer(gy,void 0,()=>{const a=uy(e,t);return Il(a,void 0),a});u.useEffect(()=>{cy(o.isRouteTreeCollapsed)},[o.isRouteTreeCollapsed]);const s=u.useMemo(()=>({state:o,dispatch:r}),[o]);return u.createElement(zl.Provider,{value:s},n)}function Qe(){const e=u.useContext(zl);if(!e)throw new Error("useLayoutEditor must be used within LayoutEditorProvider");return e}const Nl=u.createContext(null);function yy({value:e,children:t}){return u.createElement(Nl.Provider,{value:e},t)}function Ft(){return u.useContext(Nl)}const Pi=u.createContext(null);let by=1;function my({children:e,t}){const[n,o]=u.useState([]),r=u.useRef([]),[s,a]=u.useState({}),l=u.useCallback(y=>{const _=y.id??`editor-modal-${by++}`,w={id:_,content:y.content,ariaLabel:y.ariaLabel??"",closeOnBackdrop:y.closeOnBackdrop??!0,closeOnEscape:y.closeOnEscape??!0,width:y.width??"auto",height:y.height??"auto",maxHeightRatio:y.maxHeightRatio??.85,draggable:y.draggable??!1,avoidRect:y.avoidRect,onClose:y.onClose};return o(k=>{const $=[...k.filter(S=>S.id!==_),w];return r.current=$,$}),_},[]),d=u.useCallback(y=>{o(_=>{const w=_.find(x=>x.id===y),k=_.filter(x=>x.id!==y);return r.current=k,w?.onClose&&queueMicrotask(()=>w.onClose?.()),k})},[]),c=u.useCallback(()=>{const y=r.current[r.current.length-1];y&&d(y.id)},[d]),p=u.useCallback(()=>{o(y=>{for(let _=y.length-1;_>=0;_--){const w=y[_];w?.onClose&&queueMicrotask(()=>w.onClose?.())}return r.current=[],[]})},[]),f=u.useCallback((y,_)=>{a(w=>{const k=r.current.find($=>$.id===y),x=_??k?.ariaLabel??"";return{...w,[y]:x}})},[]),b=u.useCallback(y=>{a(_=>{if(!(y in _))return _;const w={..._};return delete w[y],w})},[]),g=u.useCallback(y=>{b(y),d(y)},[b,d]),m=u.useCallback(()=>{a({}),p()},[p]),h=u.useMemo(()=>Object.keys(s),[s]),v=u.useMemo(()=>({open:l,close:g,closeTop:c,closeAll:m,stack:n,minimize:f,restore:b,minimizedStack:h}),[l,g,c,m,n,f,b,h]);return u.createElement(Pi.Provider,{value:v},e,u.createElement(_y,{minimized:s,onRestore:b,t,key:"__min_bar"}))}function bo(){const e=u.useContext(Pi);if(!e)throw new Error("useEditorModal must be used within EditorModalProvider");return e}function vy(){const e=u.useContext(Pi);if(!e)return null;const{stack:t,close:n,minimizedStack:o}=e,r=u.useMemo(()=>new Set(o),[o]);return u.useEffect(()=>{if(t.length===0)return;const s=a=>{if(a.key!=="Escape"&&a.key!=="Esc")return;const l=t.filter(c=>!r.has(c.id)),d=l[l.length-1];d?.closeOnEscape&&(a.preventDefault(),a.stopPropagation(),n(d.id))};return window.addEventListener("keydown",s,!0),()=>window.removeEventListener("keydown",s,!0)},[t,n,r]),t.length===0?null:i.jsx(i.Fragment,{children:t.map((s,a)=>i.jsx(wy,{entry:s,depth:a,hidden:r.has(s.id),onClose:()=>n(s.id)},s.id))})}function _y({minimized:e,onRestore:t,t:n}){const o=n??(s=>s),r=Object.keys(e);return r.length===0?null:i.jsx("div",{className:"g7le-minimized-bar","data-testid":"g7le-minimized-bar",style:{position:"fixed",left:16,bottom:16,display:"flex",gap:8,zIndex:9300},children:r.map(s=>i.jsxs("button",{type:"button","data-testid":`g7le-minimized-${s}`,onClick:()=>t(s),style:{display:"flex",alignItems:"center",gap:6,padding:"8px 12px",background:"#1e293b",color:"#fff",border:"none",borderRadius:8,boxShadow:"0 8px 24px rgba(15, 23, 42, 0.3)",cursor:"pointer",fontSize:13},children:[i.jsx("span",{"aria-hidden":"true",children:"🗗"}),i.jsx("span",{children:e[s]||o("layout_editor.modal.minimized_default")}),i.jsx("span",{style:{opacity:.7},children:o("layout_editor.modal.restore")})]},s))})}function xy(e,t,n){if(!e||typeof window>"u")return null;const o=window.innerWidth,r=window.innerHeight,s=16,a=e.left,l=o-(e.left+e.width),d=t+s;let c;if(l>=a&&l>=d)c=e.left+e.width+s;else if(a>=d)c=Math.max(s,e.left-s-t);else return null;c=Math.min(Math.max(s,c),Math.max(s,o-t-s));let p=e.top;return p=Math.min(Math.max(s,p),Math.max(s,r-n-s)),{left:c,top:p}}const Ml="clamp(16px, 6vh, 56px)";function wy({entry:e,depth:t,hidden:n,onClose:o}){const r=9100+t*10,s=e.maxHeightRatio>0?`${e.maxHeightRatio*100}vh`:void 0,a=e.draggable?s:`calc(100vh - (${Ml}) * 2)`,[l,d]=u.useState(null),c=u.useRef(null),p=u.useRef(null);u.useEffect(()=>{if(!e.draggable)return;const v=c.current;if(!v)return;const y=v.getBoundingClientRect(),_=xy(e.avoidRect,y.width,y.height);_&&d(_)},[e.id,e.draggable]);const f=u.useCallback(v=>{if(!e.draggable)return;const y=v.target;if(!y.closest("[data-modal-drag-handle]")||y.closest("button, a, input, textarea, select"))return;const w=c.current,k=w?.getBoundingClientRect(),x=l?.left??k?.left??0,$=l?.top??k?.top??0;p.current={startX:v.clientX,startY:v.clientY,baseLeft:x,baseTop:$};const S=T=>{const E=p.current;if(!E)return;const A=window.innerWidth,N=window.innerHeight,D=w?.offsetWidth??0,B=w?.offsetHeight??0;let M=E.baseLeft+(T.clientX-E.startX),O=E.baseTop+(T.clientY-E.startY);M=Math.min(Math.max(0,M),Math.max(0,A-D)),O=Math.min(Math.max(0,O),Math.max(0,N-B)),d({left:M,top:O})},C=()=>{p.current=null,window.removeEventListener("pointermove",S),window.removeEventListener("pointerup",C)};window.addEventListener("pointermove",S),window.addEventListener("pointerup",C)},[e.draggable,l]),b=v=>{e.closeOnBackdrop&&v.target===v.currentTarget&&o()},g=e.draggable&&l!==null,m=e.draggable?{position:"fixed",inset:0,background:"transparent",pointerEvents:"none",zIndex:r,...n?{display:"none"}:{}}:{position:"fixed",inset:0,background:"rgba(15, 23, 42, 0.45)",display:n?"none":"flex",alignItems:"flex-start",justifyContent:"center",paddingTop:Ml,boxSizing:"border-box",zIndex:r},h={background:"#fff",borderRadius:10,boxShadow:"0 20px 60px rgba(15, 23, 42, 0.25)",width:e.width,height:e.height,maxHeight:a,maxWidth:"92vw",overflow:"hidden",display:"flex",flexDirection:"column",...e.draggable?{position:"absolute",pointerEvents:"auto",left:g?l.left:"50%",top:g?l.top:"50%",transform:g?void 0:"translate(-50%, -50%)"}:{}};return i.jsx("div",{className:"g7le-modal-backdrop",role:"presentation","data-testid":`g7le-modal-backdrop-${e.id}`,"data-draggable":e.draggable?"true":"false",onClick:b,style:m,children:i.jsx("div",{ref:c,className:"g7le-modal",role:"dialog","aria-modal":"true","aria-label":e.ariaLabel||void 0,"data-testid":`g7le-modal-${e.id}`,"data-positioned":g?"true":"false",onClick:v=>v.stopPropagation(),onPointerDown:e.draggable?f:void 0,style:h,children:e.content})})}function ht({baseStyle:e,hoverStyle:t,disabled:n,style:o,children:r,...s}){const[a,l]=u.useState(!1),d={outline:"none",...e,...o,...a&&!n?t:{}};return i.jsx("button",{type:"button",disabled:n,onMouseEnter:()=>l(!0),onMouseLeave:()=>l(!1),style:d,...s,children:r})}function ky({templateIdentifier:e,templateName:t,templateVersion:n,templateList:o,onSwitch:r}){const{t:s}=tt(),[a,l]=u.useState(!1),[d,c]=u.useState(!1),p=u.useRef(null);u.useEffect(()=>{if(!a)return;const v=_=>{p.current&&!p.current.contains(_.target)&&l(!1)},y=_=>{_.key==="Escape"&&l(!1)};return document.addEventListener("mousedown",v),document.addEventListener("keydown",y),()=>{document.removeEventListener("mousedown",v),document.removeEventListener("keydown",y)}},[a]);const f=o??[],b=f.some(v=>v.identifier!==e),g=!!r&&b,m=t||e,h=v=>{if(v===e){l(!1);return}l(!1),r?.(v)};return i.jsxs("div",{ref:p,className:"g7le-toolbar__template-switcher",style:{position:"relative",display:"inline-flex"},children:[i.jsxs("button",{type:"button",className:"g7le-toolbar__template","data-testid":"g7le-toolbar-template-label","data-can-switch":g?"true":"false","aria-haspopup":g?"listbox":void 0,"aria-expanded":g?a:void 0,disabled:!g,onClick:()=>g&&l(v=>!v),onMouseEnter:()=>c(!0),onMouseLeave:()=>c(!1),title:g?s("layout_editor.chrome.toolbar.switch_template"):m,style:{display:"inline-flex",alignItems:"center",gap:6,padding:"4px 8px",fontSize:13,fontWeight:600,color:"#0f172a",letterSpacing:.1,borderRadius:6,borderWidth:1,borderStyle:"solid",borderColor:g&&(d||a)?"#cbd5e1":"transparent",backgroundColor:g&&(d||a)?"#f1f5f9":"transparent",cursor:g?"pointer":"default",outline:"none",transition:"background-color 120ms, border-color 120ms"},children:[i.jsx("span",{className:"g7le-toolbar__template-name","data-testid":"g7le-toolbar-template-name",children:m}),n&&i.jsxs("span",{className:"g7le-toolbar__template-version","data-testid":"g7le-toolbar-template-version",style:{fontSize:11,fontWeight:500,color:"#64748b",padding:"1px 6px",borderRadius:999,background:"#f1f5f9",border:"1px solid #e2e8f0"},children:["v",n]}),g&&i.jsx("span",{className:"g7le-toolbar__template-caret","aria-hidden":"true",style:{fontSize:9,color:"#94a3b8",marginLeft:1},children:"▼"})]}),g&&a&&i.jsx("div",{className:"g7le-toolbar__template-menu","data-testid":"g7le-toolbar-template-menu",role:"listbox",style:{position:"absolute",top:"calc(100% + 4px)",left:0,minWidth:240,maxWidth:360,maxHeight:360,overflowY:"auto",background:"#ffffff",border:"1px solid #e2e8f0",borderRadius:8,boxShadow:"0 8px 24px rgba(15, 23, 42, 0.14)",zIndex:30,padding:4},children:f.map(v=>{const y=v.identifier===e;return i.jsxs("button",{type:"button",role:"option","aria-selected":y,"aria-current":y?"true":void 0,className:"g7le-toolbar__template-menu-item","data-testid":"g7le-toolbar-template-menu-item","data-identifier":v.identifier,"data-current":y?"true":"false",onClick:()=>h(v.identifier),style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,width:"100%",padding:"8px 10px",fontSize:13,color:"#1e293b",background:y?"#eff6ff":"transparent",border:"none",borderRadius:6,cursor:y?"default":"pointer",textAlign:"left",outline:"none"},onMouseEnter:_=>{y||(_.currentTarget.style.background="#f1f5f9")},onMouseLeave:_=>{_.currentTarget.style.background=y?"#eff6ff":"transparent"},children:[i.jsxs("span",{style:{display:"flex",alignItems:"center",gap:8,minWidth:0},children:[i.jsx("span",{"aria-hidden":"true",style:{width:12,flex:"0 0 auto",color:"#2563eb",fontSize:12,textAlign:"center"},children:y?"✓":""}),i.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:2,minWidth:0},children:[i.jsx("span",{style:{fontWeight:600,color:y?"#1d4ed8":"#1e293b",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v.name||v.identifier}),i.jsx("span",{style:{fontSize:11,color:"#94a3b8",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:v.identifier})]})]}),i.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:6,flex:"0 0 auto"},children:[i.jsx("span",{style:{fontSize:10,fontWeight:600,color:v.type==="admin"?"#7c3aed":"#0891b2",textTransform:"uppercase",letterSpacing:.4},children:v.type}),v.version&&i.jsxs("span",{style:{fontSize:11,color:"#64748b"},children:["v",v.version]})]})]},v.identifier)})})]})}function Sy(e={}){const{onSave:t,isDirty:n=!1,onExit:o,onEditCode:r,onManageImages:s,onManageTranslations:a,onPageSettings:l,onReset:d,onShowShortcuts:c,onPreview:p,onShowVersions:f,templateName:b,templateVersion:g,templateList:m,onSwitchTemplate:h,onToggleCustomAssets:v,customAssetsDisabled:y=!1,onManageCustomAssets:_}=e,[w,k]=u.useState(!1),[x,$]=u.useState(!1),{t:S}=tt(),{state:C,dispatch:T}=Qe(),[E,A]=u.useState(null);u.useEffect(()=>{const K=()=>{const Z=window.__g7LayoutEditorHistory;A(Z?{undo:Z.undo,redo:Z.redo,canUndo:!!Z.canUndo,canRedo:!!Z.canRedo}:null)};K();const X=window.setInterval(K,250);return()=>window.clearInterval(X)},[]);const N=()=>{T({type:"TOGGLE_ROUTE_TREE"})},D=()=>C.editMode==="base"?S("layout_editor.chrome.toolbar.mode_badge.base"):C.editMode==="modal"?S("layout_editor.chrome.toolbar.mode_badge.modal"):C.editMode==="extension"?S("layout_editor.chrome.toolbar.mode_badge.extension"):C.editMode==="iteration_item"?S("layout_editor.chrome.toolbar.mode_badge.iteration_item"):null,B=()=>{C.editMode==="base"?T({type:"EXIT_BASE_EDIT"}):C.editMode==="modal"?T({type:"EXIT_MODAL_EDIT"}):C.editMode==="extension"?T({type:"EXIT_EXTENSION_EDIT"}):C.editMode==="iteration_item"&&T({type:"EXIT_ITERATION_ITEM_EDIT"})},M=D(),O=C.editMode!=="route",z={display:"inline-flex",alignItems:"center",gap:6,padding:"6px 12px",fontSize:13,fontWeight:500,borderRadius:6,borderWidth:1,borderStyle:"solid",borderColor:"transparent",backgroundColor:"transparent",color:"#475569",cursor:"pointer",transition:"background-color 120ms, color 120ms, border-color 120ms"},H={...z,backgroundColor:"#2563eb",color:"#ffffff",borderColor:"#2563eb",fontWeight:600},P={backgroundColor:"#fef3c7",borderColor:"#f59e0b",color:"#92400e",fontWeight:600},I={...z,borderColor:"#e2e8f0",backgroundColor:"#ffffff",color:"#0f172a"},L={backgroundColor:"#f1f5f9",color:"#0f172a",borderColor:"#cbd5e1"},F={backgroundColor:"#1d4ed8",borderColor:"#1d4ed8"},Y={backgroundColor:"#f8fafc",borderColor:"#cbd5e1"};return i.jsxs("div",{className:"g7le-toolbar","data-testid":"g7le-toolbar",role:"toolbar",style:{display:"flex",alignItems:"center",gap:6,padding:"8px 12px",borderBottom:"1px solid #e2e8f0",background:"#ffffff",boxShadow:"0 1px 2px rgba(15, 23, 42, 0.04)"},children:[i.jsx("style",{children:"@keyframes g7le-spin { to { transform: rotate(360deg); } }.g7le-toolbar > * { flex-shrink: 0; white-space: nowrap; }"}),i.jsx("button",{type:"button",className:"g7le-toolbar__route-tree-toggle","data-testid":"g7le-toolbar-toggle-route-tree","aria-label":S("layout_editor.chrome.toolbar.toggle_route_tree"),title:S("layout_editor.chrome.toolbar.toggle_route_tree"),onClick:N,style:{...z,outline:"none",padding:"6px 10px",fontSize:16,lineHeight:1,color:"#64748b"},children:"☰"}),i.jsx(ky,{templateIdentifier:C.templateIdentifier,templateName:b,templateVersion:g,templateList:m,onSwitch:h}),M&&i.jsx("span",{className:"g7le-toolbar__mode-badge","data-testid":"g7le-toolbar-mode-badge","data-mode":C.editMode,style:{padding:"2px 8px",borderRadius:999,background:"#fef3c7",color:"#92400e",fontSize:11,fontWeight:600,border:"1px solid #fde68a"},children:M}),i.jsx("div",{style:{flex:1}}),i.jsxs(i.Fragment,{children:[i.jsx(ht,{"data-testid":"g7le-toolbar-undo","aria-label":S("layout_editor.chrome.toolbar.undo"),title:S("layout_editor.chrome.toolbar.undo"),disabled:!E?.canUndo,onClick:()=>E?.undo?.(),baseStyle:z,hoverStyle:L,style:{opacity:E?.canUndo?1:.4},children:"↶"}),i.jsx(ht,{"data-testid":"g7le-toolbar-redo","aria-label":S("layout_editor.chrome.toolbar.redo"),title:S("layout_editor.chrome.toolbar.redo"),disabled:!E?.canRedo,onClick:()=>E?.redo?.(),baseStyle:z,hoverStyle:L,style:{opacity:E?.canRedo?1:.4},children:"↷"}),i.jsxs(ht,{"data-testid":"g7le-toolbar-add-element","data-open":C.isPaletteOpen?"true":"false",disabled:!C.selectedRoute,onClick:()=>T({type:"TOGGLE_PALETTE"}),"aria-pressed":C.isPaletteOpen,baseStyle:z,hoverStyle:L,style:C.isPaletteOpen?{backgroundColor:"#eff6ff",color:"#1d4ed8",borderColor:"#93c5fd"}:void 0,children:["+ ",S("layout_editor.chrome.toolbar.add_element")]}),i.jsx(ht,{"data-testid":"g7le-toolbar-preview","data-previewing":x?"true":"false",disabled:!p||!C.selectedRoute?.layoutName||x,onClick:()=>{const K=p?.();K&&typeof K.then=="function"&&($(!0),K.finally(()=>$(!1)))},baseStyle:z,hoverStyle:L,style:{opacity:x?.7:1},children:x?i.jsxs(i.Fragment,{children:[i.jsx("span",{"data-testid":"g7le-toolbar-preview-spinner","aria-hidden":"true",style:{display:"inline-block",width:12,height:12,border:"2px solid rgba(71,85,105,0.35)",borderTopColor:"#475569",borderRadius:"50%",animation:"g7le-spin 600ms linear infinite"}}),S("layout_editor.chrome.toolbar.previewing")]}):i.jsxs(i.Fragment,{children:["👁 ",S("layout_editor.chrome.toolbar.preview")]})}),i.jsxs(ht,{"data-testid":"g7le-toolbar-versions",disabled:!f||!(C.selectedRoute?.layoutName||C.selectedRoute?.path?.startsWith("__extension__/")),onClick:()=>f?.(),"aria-label":S("layout_editor.chrome.toolbar.version_history"),title:S("layout_editor.chrome.toolbar.version_history"),baseStyle:z,hoverStyle:L,children:["🕘 ",S("layout_editor.chrome.toolbar.version_history")]}),i.jsxs(ht,{"data-testid":"g7le-toolbar-edit-code",disabled:!r,onClick:()=>r?.(),baseStyle:z,hoverStyle:L,children:["⟨/⟩ ",S("layout_editor.chrome.toolbar.edit_code")]}),i.jsxs(ht,{"data-testid":"g7le-toolbar-images",disabled:!s||!C.selectedRoute,onClick:()=>s?.(),baseStyle:z,hoverStyle:L,children:["🖼 ",S("layout_editor.chrome.toolbar.images")]}),i.jsxs(ht,{"data-testid":"g7le-toolbar-translations",disabled:!a||!C.selectedRoute,onClick:()=>a?.(),baseStyle:z,hoverStyle:L,children:["🌐 ",S("layout_editor.chrome.toolbar.translations")]}),i.jsxs(ht,{"data-testid":"g7le-toolbar-custom-assets",disabled:!_,onClick:()=>_?.(),title:S("layout_editor.chrome.toolbar.custom_assets_hint"),baseStyle:z,hoverStyle:L,children:["🎨 ",S("layout_editor.chrome.toolbar.custom_assets")]}),i.jsxs(ht,{"data-testid":"g7le-toolbar-toggle-custom-assets","data-custom-disabled":y?"true":"false",disabled:!v,onClick:()=>v?.(),"aria-pressed":y,title:S(y?"layout_editor.chrome.toolbar.custom_assets_on_hint":"layout_editor.chrome.toolbar.custom_assets_off_hint"),baseStyle:z,hoverStyle:L,style:y?{...z,...P}:void 0,children:[y?"👁":"🚫"," ",S(y?"layout_editor.chrome.toolbar.custom_assets_on":"layout_editor.chrome.toolbar.custom_assets_off")]}),i.jsxs(ht,{"data-testid":"g7le-toolbar-page-settings",disabled:!l||!C.selectedRoute||C.editMode==="extension"||C.editMode==="iteration_item",onClick:()=>l?.(),baseStyle:z,hoverStyle:L,children:["⚙ ",S("layout_editor.chrome.toolbar.page_settings")]}),i.jsxs(ht,{"data-testid":"g7le-toolbar-reset",disabled:!d||!n,onClick:()=>d?.(),"aria-label":S("layout_editor.chrome.toolbar.reset"),title:S("layout_editor.chrome.toolbar.reset"),baseStyle:z,hoverStyle:L,style:{opacity:n?1:.4},children:["↺ ",S("layout_editor.chrome.toolbar.reset")]}),i.jsx(ht,{"data-testid":"g7le-toolbar-save","data-dirty":n?"true":"false","data-saving":w?"true":"false",disabled:!t||w,onClick:()=>{const K=t?.();K&&typeof K.then=="function"&&(k(!0),K.finally(()=>k(!1)))},baseStyle:H,hoverStyle:F,style:{opacity:w?.7:n?1:.7},children:w?i.jsxs(i.Fragment,{children:[i.jsx("span",{"data-testid":"g7le-toolbar-save-spinner","aria-hidden":"true",className:"g7le-toolbar__spinner",style:{display:"inline-block",width:12,height:12,border:"2px solid rgba(255,255,255,0.4)",borderTopColor:"#ffffff",borderRadius:"50%",animation:"g7le-spin 600ms linear infinite"}}),S("layout_editor.chrome.toolbar.saving")]}):i.jsxs(i.Fragment,{children:["💾 ",S("layout_editor.chrome.toolbar.save")]})}),i.jsx(ht,{"data-testid":"g7le-toolbar-shortcuts",disabled:!c,onClick:()=>c?.(),"aria-label":S("layout_editor.shortcuts.title"),title:S("layout_editor.shortcuts.title"),baseStyle:z,hoverStyle:L,children:"⌨"}),i.jsxs(ht,{"data-testid":"g7le-toolbar-exit",disabled:!o,onClick:()=>o?.(),baseStyle:I,hoverStyle:Y,children:["✕ ",S("layout_editor.chrome.toolbar.exit")]})]}),O&&i.jsxs(ht,{"data-testid":"g7le-toolbar-exit-alt-mode",onClick:B,baseStyle:I,hoverStyle:Y,children:["← ",C.editMode==="base"&&S("layout_editor.chrome.toolbar.exit_base_edit"),C.editMode==="modal"&&S("layout_editor.chrome.toolbar.exit_modal_edit"),C.editMode==="extension"&&S("layout_editor.chrome.toolbar.exit_extension_edit"),C.editMode==="iteration_item"&&S("layout_editor.chrome.toolbar.exit_iteration_item_edit")]})]})}function cr(){if(typeof window>"u")return null;try{return window.localStorage?.getItem("auth_token")??null}catch{return null}}function Ne(e){const t={Accept:"application/json",...e??{}},n=cr();return n&&(t.Authorization=`Bearer ${n}`),t}function Oi(e){return encodeURIComponent(e)}async function Ll(e,t){const n=`/api/admin/templates/${Oi(e)}/layout-attachments?layout_name=${encodeURIComponent(t)}`;try{const o=await fetch(n,{method:"GET",headers:Ne(),credentials:"same-origin"}),r=await o.json().catch(()=>null);return!o.ok||!r?.success?{ok:!1,status:o.status,message:Bi(r,o.status)}:{ok:!0,data:Array.isArray(r?.data)?r.data:[]}}catch(o){return{ok:!1,status:0,message:o instanceof Error?o.message:"network error"}}}async function Pl(e,t,n){const o=`/api/admin/templates/${Oi(e)}/layout-attachments`,r=new FormData;r.append("file",n),r.append("layout_name",t);try{const s=await fetch(o,{method:"POST",headers:Ne(),body:r,credentials:"same-origin"}),a=await s.json().catch(()=>null);return!s.ok||!a?.success||!a?.data?.url?{ok:!1,status:s.status,message:Bi(a,s.status)}:{ok:!0,data:a.data}}catch(s){return{ok:!1,status:0,message:s instanceof Error?s.message:"network error"}}}async function Ol(e){const t=`/api/admin/templates/layout-attachments/${Oi(String(e))}`;try{const n=await fetch(t,{method:"DELETE",headers:Ne(),credentials:"same-origin"}),o=await n.json().catch(()=>null);return!n.ok||o&&o.success===!1?{ok:!1,status:n.status,message:Bi(o,n.status)}:{ok:!0,data:!0}}catch(n){return{ok:!1,status:0,message:n instanceof Error?n.message:"network error"}}}function Bi(e,t){if(e&&typeof e=="object"&&"message"in e){const n=e.message;if(typeof n=="string"&&n.length>0)return n}return`HTTP ${t}`}function Cy(e){return e<1024?`${e} B`:e<1024*1024?`${Math.round(e/1024)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function $y(e){if(!e)return"";const t=e.match(/^(\d{4})-(\d{2})-(\d{2})/);return t?`${t[2]}-${t[3]}`:""}function Bl({templateIdentifier:e,layoutName:t,t:n,onSelect:o,onChanged:r,onClose:s}){const[a,l]=u.useState([]),[d,c]=u.useState("idle"),[p,f]=u.useState(!1),[b,g]=u.useState(null),m=u.useRef(null),h=u.useCallback(async()=>{c("loading"),g(null);const _=await Ll(e,t);_.ok?(l(_.data),c("idle")):(g(_.message),c("error"))},[e,t]);u.useEffect(()=>{h()},[h]);const v=async _=>{const w=_.target.files?.[0];if(!w)return;f(!0),g(null);const k=await Pl(e,t,w);k.ok?(l(x=>[k.data,...x.filter($=>$.id!==k.data.id)]),r?.()):g(k.message),f(!1),m.current&&(m.current.value="")},y=async _=>{if(!(typeof window<"u"&&typeof window.confirm=="function"?window.confirm(n("layout_editor.attachment_manager.delete_confirm")):!0))return;const k=await Ol(_.id);k.ok?(l(x=>x.filter($=>$.id!==_.id)),r?.()):g(k.message)};return i.jsxs("div",{className:"g7le-attachment-manager","data-testid":"g7le-attachment-manager",style:Ey,children:[i.jsxs("div",{"data-modal-drag-handle":!0,style:Iy,children:[i.jsx("span",{style:{fontSize:14,fontWeight:700},"data-testid":"g7le-attachment-manager-title",children:n("layout_editor.attachment_manager.title")}),i.jsx("button",{type:"button","aria-label":"close",onClick:s,style:Ay,"data-testid":"g7le-attachment-manager-close",children:"✕"})]}),i.jsx("div",{style:Ty,children:i.jsxs("label",{style:Dy,"data-testid":"g7le-attachment-upload",children:[p?"…":`⬆ ${n("layout_editor.attachment_manager.upload")}`,i.jsx("input",{ref:m,type:"file",accept:"image/*",onChange:v,disabled:p,style:{display:"none"},"data-testid":"g7le-attachment-upload-input"})]})}),b&&i.jsx("div",{style:zy,"data-testid":"g7le-attachment-manager-error",children:b}),i.jsx("div",{style:Ny,children:d==="loading"?i.jsx("div",{style:Wl,"data-testid":"g7le-attachment-manager-loading",children:n("layout_editor.attachment_manager.loading")}):a.length===0&&d!=="error"?i.jsx("div",{style:Wl,"data-testid":"g7le-attachment-manager-empty",children:n("layout_editor.attachment_manager.empty")}):i.jsx("div",{style:My,"data-testid":"g7le-attachment-grid",children:a.map(_=>i.jsxs("div",{style:Ly,"data-testid":`g7le-attachment-card-${_.id}`,children:[i.jsx("div",{style:{...Py,backgroundImage:`url(${_.url})`}}),i.jsx("div",{style:Oy,title:_.original_name,children:_.original_name}),i.jsxs("div",{style:By,children:[Cy(_.size),_.created_at?` · ${$y(_.created_at)}`:""]}),i.jsxs("div",{style:Wy,children:[o&&i.jsx("button",{type:"button",onClick:()=>o(_.url),style:jy,"data-testid":`g7le-attachment-use-${_.id}`,children:n("layout_editor.attachment_manager.use_as_bg")}),i.jsx("button",{type:"button",onClick:()=>y(_),style:Hy,"data-testid":`g7le-attachment-delete-${_.id}`,children:"🗑"})]})]},_.id))})}),i.jsx("div",{style:Fy,children:i.jsx("button",{type:"button",onClick:s,style:Ky,"data-testid":"g7le-attachment-manager-footer-close",children:n("layout_editor.attachment_manager.close")})})]})}const Ey={display:"flex",flexDirection:"column",minHeight:0,flex:1},Iy={display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #e2e8f0"},Ay={border:"none",background:"transparent",fontSize:16,color:"#94a3b8",cursor:"pointer"},Ty={padding:"10px 16px",borderBottom:"1px solid #f1f5f9",display:"flex",gap:8},Dy={padding:"6px 12px",fontSize:13,border:"1px solid #2563eb",borderRadius:6,background:"#fff",color:"#2563eb",cursor:"pointer",display:"inline-flex",alignItems:"center"},zy={padding:"8px 16px",fontSize:12,color:"#b91c1c",background:"#fef2f2"},Ny={padding:16,overflow:"auto",flex:1,minHeight:120},Wl={fontSize:13,color:"#94a3b8",textAlign:"center",padding:"32px 0"},My={display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(140px, 1fr))",gap:12},Ly={display:"flex",flexDirection:"column",gap:4,border:"1px solid #e2e8f0",borderRadius:8,padding:8},Py={width:"100%",height:88,borderRadius:6,border:"1px solid #cbd5e1",backgroundSize:"cover",backgroundPosition:"center",backgroundColor:"#f8fafc"},Oy={fontSize:12,fontWeight:600,color:"#0f172a",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},By={fontSize:11,color:"#64748b"},Wy={display:"flex",gap:6,marginTop:2},jy={flex:1,padding:"4px 6px",fontSize:11,border:"1px solid #2563eb",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"},Hy={padding:"4px 8px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},Fy={padding:"10px 16px",borderTop:"1px solid #e2e8f0",display:"flex",justifyContent:"flex-end"},Ky={padding:"6px 14px",fontSize:13,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"};function ur(e){return encodeURIComponent(e)}async function Vy(e,t,n){const o=new URLSearchParams;t&&o.set("layout_name",t);const r=o.toString(),s=`/api/admin/templates/${ur(e)}/custom-translations`+(r?`?${r}`:"");try{const a=await fetch(s,{method:"GET",headers:Ne(),credentials:"same-origin"}),l=await a.json().catch(()=>null);return!a.ok||!l?.success?{ok:!1,status:a.status,message:pr(l,a.status)}:{ok:!0,data:Array.isArray(l?.data)?l.data:[]}}catch(a){return{ok:!1,status:0,message:a instanceof Error?a.message:"network error"}}}async function Uy(e,t,n,o){const r=`/api/admin/templates/${ur(e)}/custom-translations/${t}`;try{const s=await fetch(r,{method:"PUT",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({values:n,expected_lock_version:o}),credentials:"same-origin"}),a=await s.json().catch(()=>null);return!s.ok||!a?.success||!a?.data?{ok:!1,status:s.status,message:pr(a,s.status)}:{ok:!0,data:a.data}}catch(s){return{ok:!1,status:0,message:s instanceof Error?s.message:"network error"}}}async function qy(e,t){const n=`/api/admin/templates/${ur(e)}/custom-translations/${t}`;try{const o=await fetch(n,{method:"DELETE",headers:Ne(),credentials:"same-origin"}),r=await o.json().catch(()=>null);return!o.ok||r&&r.success===!1?{ok:!1,status:o.status,message:pr(r,o.status)}:{ok:!0,data:!0}}catch(o){return{ok:!1,status:0,message:o instanceof Error?o.message:"network error"}}}async function Gy(e,t){const n=`/api/admin/templates/${ur(e)}/custom-translations`;try{const o=await fetch(n,{method:"DELETE",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({ids:t}),credentials:"same-origin"}),r=await o.json().catch(()=>null);return!o.ok||!r?.success?{ok:!1,status:o.status,message:pr(r,o.status)}:{ok:!0,data:{deleted:typeof r?.data?.deleted=="number"?r.data.deleted:t.length}}}catch(o){return{ok:!1,status:0,message:o instanceof Error?o.message:"network error"}}}const jl=/\$t:(custom\.[A-Za-z0-9_\-]+\.\d+)/g;function Yy(e){const t=new Set,n=o=>{if(typeof o=="string"){if(o.includes("$t:custom.")){let r;for(jl.lastIndex=0;(r=jl.exec(o))!==null;)t.add(r[1])}return}if(Array.isArray(o)){for(const r of o)n(r);return}if(o&&typeof o=="object")for(const r of Object.values(o))n(r)};return n(e),t}function pr(e,t){if(e&&typeof e=="object"&&"message"in e){const n=e.message;if(typeof n=="string"&&n.length>0)return n}return`HTTP ${t}`}const Pt=Lt().TranslationEngine,mo=Lt().createLogger,Wi=mo("EditorSpecLoader"),Xy=["controls","componentCapabilities","actionRecipes","conditionRecipes","pageSettings","initActionRecipes","errorRecipes","computedRecipes","loadingComponents"],Jy=["actionRecipes","initActionRecipes","errorRecipes","computedRecipes","loadingComponents"];function Hl(e){if(typeof window>"u")return[];const n=window.G7Config?.[e];if(!Array.isArray(n))return[];const o=[];for(const r of n){const s=r?.identifier;typeof s=="string"&&s.length>0&&o.push(s)}return o}async function Zy(e,t,n,o){const s=`${n}/${e==="template"?"templates":e==="module"?"modules":"plugins"}/${encodeURIComponent(t)}/editor-spec`;try{const a=await o(s);if(!a.ok)return a.status!==404&&Wi.warn(`fetchOneSpec: HTTP ${a.status}`,s),null;const l=await a.json();return!l?.success||!l.data?null:l.data.spec??null}catch(a){return Wi.warn("fetchOneSpec: fetch failed",s,a),null}}function Qy(e){return Jy.includes(e)}function Ry(e,t){return e==null||typeof e!="object"?e:{...e,__source:t}}function eb(e,t,n,o){const r=t[n];if(!r||typeof r!="object")return;const s=e[n]??{};if(o&&Qy(n)){const a={};for(const[l,d]of Object.entries(r))a[l]=Ry(d,o);e[n]={...s,...a};return}e[n]={...s,...r}}function tb(e,t){if(!t.nesting)return;const n=e.nesting??{},o=new Set(n.draggable??[]);for(const r of t.nesting.draggable??[])o.add(r);n.draggable=Array.from(o),n.containers={...n.containers??{},...t.nesting.containers??{}},e.nesting=n}function nb(e,t){if(!t.componentPalette)return;const n=e.componentPalette??{},o=[...n.groups??[],...t.componentPalette.groups??[]];n.groups=o,n.entries={...n.entries??{},...t.componentPalette.entries??{}},e.componentPalette=n}function ob(e,t){if(!t.states)return;const n=e.states??{},o=[...n.groups??[],...t.states.groups??[]];n.groups=o,e.states=n}function rb(e,t){if(!Array.isArray(t.stateLabels)||t.stateLabels.length===0)return;const n=[...e.stateLabels??[],...t.stateLabels],o=new Map;for(const r of n)!r||typeof r.key!="string"||typeof r.scope!="string"||o.set(`${r.scope}:${r.key}`,r);e.stateLabels=Array.from(o.values())}function ib(e,t){if(!t.actionChipCandidates)return;const n=e.actionChipCandidates??{};for(const o of["response","error","payload"]){const r=t.actionChipCandidates[o];!Array.isArray(r)||r.length===0||(n[o]=[...n[o]??[],...r])}e.actionChipCandidates=n}function sb(e,t){if(!t.sampleData)return;const n=e.sampleData??{};n.byDataSourceId={...n.byDataSourceId??{},...t.sampleData.byDataSourceId??{}},n.byEndpointPattern={...n.byEndpointPattern??{},...t.sampleData.byEndpointPattern??{}},e.sampleData=n}function Fl(e,t,n){for(const o of Xy)eb(e,t,o,n);tb(e,t),nb(e,t),ob(e,t),rb(e,t),ib(e,t),sb(e,t),t.version&&(e.version=t.version)}async function ab(e){const t=e.apiBaseUrl??"/api",n=e.fetcher??(typeof fetch<"u"?fetch:void 0);if(!n)return Wi.warn("loadEditorSpecBundle: fetch unavailable, returning null spec"),{spec:null,sampleGlobalSources:[]};const o=e.activeModuleIdentifiers??Hl("activeModules"),r=e.activePluginIdentifiers??Hl("activePlugins"),s=[...o.map(p=>({kind:"module",id:p})),...r.map(p=>({kind:"plugin",id:p})),{kind:"template",id:e.templateIdentifier}],a=await Promise.all(s.map(p=>Zy(p.kind,p.id,t,n)));let l=null;const d=[],c={};if(e.coreSeed&&(l={},Fl(l,e.coreSeed,{kind:"core"})),s.forEach((p,f)=>{const b=a[f];if(!b)return;b.sampleGlobal&&typeof b.sampleGlobal=="object"&&d.push({id:p.id,kind:p.kind,sampleGlobal:b.sampleGlobal});const g=b.sampleData?.byDataSourceId;if(g&&typeof g=="object"){const m=p.kind==="template"?"template":`${p.kind}:${p.id}`;c[m]={...c[m]??{},...g}}l===null&&(l={}),Fl(l,b,{kind:p.kind,id:p.id})}),l!==null&&Object.keys(c).length>0){const p=l;p.sampleData={...p.sampleData??{},bySource:c}}return{spec:l,sampleGlobalSources:d}}function ji(e,t){return e?.componentCapabilities?.[t]??null}function Ct(e,t){return e?.controls?.[t]??null}function lb(e){return e?.initActionRecipes??{}}function db(e){return e?.computedRecipes??{}}function cb(e){return e?.errorRecipes??{}}function ub(e){const t=e?.loadingComponents;return!t||typeof t!="object"?[]:Object.values(t).filter(n=>n!=null&&typeof n=="object"&&typeof n.name=="string")}function pb(e,t,n){const o=e?.stateLabels;if(!Array.isArray(o))return null;for(const r of o)if(r?.scope===t&&r?.key===n)return typeof r.label_key=="string"?r.label_key:null;return null}function Hi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function fb(e){return e===null?"null":typeof e=="string"?e.length>40?`${e.slice(0,40)}…`:e:typeof e=="number"||typeof e=="boolean"?String(e):""}function gb(e){const t=e.find(n=>Hi(n));if(Hi(t))return Object.keys(t).slice(0,8)}function hb(e){return Object.keys(e).slice(0,8)}function yb(e){const t=Object.entries(e);return t.length===0?!1:t.some(([,n])=>n===null||typeof n!="object")}function Fi(e,t,n,o,r){if(Array.isArray(e)){r(t,"array",`[${e.length}]`,gb(e));return}if(Hi(e)){if(t&&yb(e)){const s=hb(e);r(t,"object",`{${s.length}}`,s)}if(n>=o)return;for(const[s,a]of Object.entries(e)){const l=t?`${t}.${s}`:s;Fi(a,l,n+1,o,r)}return}r(t,"scalar",fb(e))}function bb(e,t,n){const o=[];let r=e;for(const s of t){if(!r||(r=(Array.isArray(r.children)?r.children:[])[s],!r))break;const l=r.iteration;if(!(!l||l.source===void 0)&&(typeof l.index_var=="string"&&l.index_var.length>0&&o.push({name:l.index_var,kind:"index"}),typeof l.item_var=="string"&&l.item_var.length>0)){const d=typeof l.source=="string"?l.source:"",c=d&&n?.get(Kl(d))||[];o.push({name:l.item_var,kind:"item",itemFields:c})}}return o}function Kl(e){return e.replace(/^\{\{|\}\}$/g,"").trim()}function mb(e){const t=new Map;for(const n of e)n.shape==="array"&&n.itemFields&&n.itemFields.length>0&&t.set(Kl(n.expression),n.itemFields);return t}function Ki(e){const t=e.maxDepth??4,n=[];for(const o of e.dataSources??[])!o||typeof o.id!="string"||o.id.length===0||Fi(o.sample,"",0,t,(r,s,a,l)=>{const d=r?`{{${o.id}.${r}}}`:`{{${o.id}}}`;n.push({expression:d,source:"data_source",sourceId:o.id,path:r,shape:s,groupLabelKey:o.labelKey?.startsWith("$t:")?o.labelKey.slice(3):o.labelKey,preview:a,itemFields:l})});for(const o of e.states??[])!o||typeof o.scope!="string"||Fi(o.tree,"",0,t,(r,s,a,l)=>{if(!r)return;const d=pb(e.spec,o.scope,r)??void 0;n.push({expression:`{{${o.scope}.${r}}}`,source:o.scope,sourceId:o.scope,path:r,shape:s,labelKey:d?.startsWith("$t:")?d.slice(3):d,preview:a,itemFields:l})});for(const o of e.iterationVars??[])if(!(!o||typeof o.name!="string"||o.name.length===0)){if(o.kind==="index"){n.push({expression:`{{${o.name}}}`,source:"iteration",sourceId:o.name,path:"",shape:"scalar",preview:"0"});continue}for(const r of o.itemFields??[])n.push({expression:`{{${o.name}.${r}}}`,source:"iteration",sourceId:o.name,path:r,shape:"scalar",preview:""})}return n}const vb=["$localized"];function _b(e){const t=e.trim(),n=t.indexOf("(");if(n===-1||!t.endsWith(")"))return{fn:null,inner:t};const o=t.slice(0,n).trim();if(!vb.includes(o))return{fn:null,inner:t};const r=t.slice(n+1,-1);let s=0,a=null;for(let l=0;ln.shape===t)}function qi(e,t){const n=t.trim().toLowerCase();return n===""?e:e.filter(o=>[o.resolvedLabel??"",o.sourceId,o.path,o.preview].join(" ").toLowerCase().includes(n))}function Vl(e,t,n){const o={response:[{path:"data",labelKey:"layout_editor.action_chip.response_data",shape:"object"},{path:"message",labelKey:"layout_editor.action_chip.response_message",shape:"scalar"}],error:[{path:"status",labelKey:"layout_editor.action_chip.error_status",shape:"scalar"},{path:"message",labelKey:"layout_editor.action_chip.error_message",shape:"scalar"},{path:"errors",labelKey:"layout_editor.action_chip.error_errors",shape:"object"},{path:"data",labelKey:"layout_editor.action_chip.error_data",shape:"object"},{path:"statusText",labelKey:"layout_editor.action_chip.error_status_text",shape:"scalar"}],payload:[{path:"data",labelKey:"layout_editor.action_chip.payload_data",shape:"object"}]},r=e==="response"?"response":e==="error"?"error":"message",s=new Set,a=[];for(const d of o[e])s.has(d.path)||(s.add(d.path),a.push(d));const l=n?.[e];if(Array.isArray(l))for(const d of l)!d||typeof d.path!="string"||typeof d.labelKey!="string"||s.has(d.path)||(s.add(d.path),a.push({path:d.path,labelKey:d.labelKey,shape:d.shape??"scalar"}));return a.map(d=>({expression:`{{${r}.${d.path}}}`,source:"_local",sourceId:r,path:d.path,shape:d.shape,labelKey:d.labelKey,preview:t(d.labelKey)}))}const Gi=/\{\{(?:[^}]|\}(?!\}))*\}\}/g;function In(e){const t=[];if(typeof e!="string"||e.length===0)return t;let n=0,o=0;const r=new RegExp(Gi.source,"g");let s;for(;(s=r.exec(e))!==null;){const a=s.index,l=a+s[0].length;a>n&&t.push({kind:"literal",raw:e.slice(n,a),start:n,end:a}),t.push({kind:"binding",raw:s[0],start:a,end:l,parsed:Kt(s[0]),bindingIndex:o++}),n=l}return nt.kind==="binding")}function Yi(e){return typeof e!="string"?!1:new RegExp(Gi.source).test(e)}function wb(e){const t=new Set(e.map(o=>o.trim()));let n=0;for(;t.has(`p${n}`);)n+=1;return`p${n}`}function Ul(e,t,n){const o=typeof e=="string"?e:"",r=Math.max(0,Math.min(t,o.length)),s=o.slice(0,r),a=o.slice(r),l=s.length>0&&!/\s$/.test(s)?" ":"",d=a.length>0&&!/^\s/.test(a)?" ":"";return`${s}${l}{${n}}${d}${a}`}function Xi(e,t){const n=typeof e=="string"?e:"";return An(n).includes(t)?n:n.length===0?`{${t}}`:/\s$/.test(n)?`${n}{${t}}`:`${n} {${t}}`}function ql(e){return fr(e).map(t=>({bindingIndex:t.bindingIndex??0,expression:t.raw,parsed:t.parsed??null,isComplex:(t.parsed??null)===null}))}function gr(e){return typeof e!="string"?"":e.replace(new RegExp(Gi.source,"g")," ").replace(/\s+/g," ").trim()}const kb=/\$t:([a-zA-Z0-9._-]+)/g,Gl="custom.";function Ji(e,t){return typeof e!="string"||e.length===0?typeof e=="string"?e:"":t?In(e).map(n=>n.kind!=="literal"?n.raw:n.raw.replace(kb,(o,r)=>{if(r.startsWith(Gl))return o;const s=t(r);return s&&s!==r?s:o})).join(""):e}const Kn="(?:(?!\\|[a-zA-Z0-9_]+=).)*",Sb=new RegExp(`^\\s*\\$t:([a-zA-Z0-9._-]+)((?:\\|[a-zA-Z0-9_]+=${Kn})*)`),Cb=new RegExp(`\\|([a-zA-Z0-9_]+)=(${Kn})`,"g");function Vt(e){if(typeof e!="string")return"";const t=Kt(e);if(t)return t.path||t.sourceId;const n=e.trim().replace(/^\{\{\s*/,"").replace(/\s*\}\}$/,"");let o=-1;for(let l=0;l0){const l=n.slice(0,o).trim(),d=Kt(`{{${l}}}`);if(d)return d.path||d.sourceId;const c=l.replace(/\?\./g,".").replace(/\s*\?\?.*$/,"").trim();if(/^[A-Za-z_$][\w$.]*$/.test(c)){const p=c.split(".").filter(Boolean);return p.length>1&&p.slice(1).join(".")||c}}const r=n.replace(/\s+/g," ").trim(),s=r.replace(/\s*(\?\?|\|\|)\s*(\[\s*\]|\{\s*\}|'[^']*'|"[^"]*"|\d+|null|undefined)\s*$/,"").trim(),a=/\.([A-Za-z_$][\w$]*)\s*$/.exec(s);return a?a[1]:r}const Yl=/\$(?:core|module|plugin)_settings:[a-zA-Z0-9._:-]+/g;function Xl(e){return typeof e=="string"&&new RegExp(Yl.source).test(e)}function $b(e){return typeof e!="string"?"":e.replace(/^\$(?:core|module|plugin)_settings:/,"").split(/[.:]/).filter(Boolean).pop()||e}function Jl(e){const t=[];for(const n of In(e)){if(n.kind==="binding"){t.push({kind:"chip",label:Vt(n.raw)});continue}let o=0;const r=n.raw,s=new RegExp(Yl.source,"g");let a;for(;(a=s.exec(r))!==null;)a.index>o&&t.push({kind:"text",label:r.slice(o,a.index)}),t.push({kind:"chip",label:$b(a[0])}),o=a.index+a[0].length;o{const m=`p${o.length}`;return o.push(g),r[m]=Vt(g),`{${m}}`};let a=e,l="";const d=Sb.exec(e);if(d&&!d[1].startsWith(Gl)){const g=d[1],m=d[2]??"",h=e.slice(d[0].length),v=new Map,y=new RegExp(Cb.source,"g");let _;for(;(_=y.exec(m))!==null;)_[2]&&_[2].includes("{{")&&v.set(_[1],_[2]);const w=t?t(g):"";if(w&&w!==g&&!w.startsWith("$t:"))l=w.replace(/\{\{?([a-zA-Z0-9_]+)\}?\}/g,(k,x)=>{const $=v.get(x);return $?s($):k});else return n;a=h}const c=Ji(a,t),p=In(c).map(g=>g.kind==="binding"?s(g.raw):g.raw).join(""),f=`${l}${p}`;return/\$t:[a-zA-Z0-9._-]+/.test(f)||o.length===0?n:{chipValue:f,bindings:o,paramLabels:r,keyifiable:!0}}function Zl(e,t){return t.bindings.length?e+t.bindings.map((n,o)=>`|p${o}=${n}`).join(""):e}function Ql(e,t){const n=fr(t).map(r=>r.raw);if(n.length===0)return e;const o=n.map((r,s)=>`|p${s}=${r}`).join("");return`${e}${o}`}function Rl(e){if(typeof e!="string")return"";const t=In(e);let n=0;return t.map(o=>o.kind==="binding"?`{p${n++}}`:o.raw).join("")}const ed=new RegExp(`^\\s*\\$t:([a-zA-Z0-9._-]+)((?:\\|[a-zA-Z0-9_]+=${Kn})+)\\s*$`),Ib=new RegExp(`\\|([a-zA-Z0-9_]+)=(${Kn})`,"g");function vt(e){if(typeof e!="string")return null;const t=ed.exec(e);if(!t)return null;const n=t[1],o=t[2],r=[],s=new RegExp(Ib.source,"g");let a;for(;(a=s.exec(o))!==null;){const l=a[1],d=a[2];r.push({name:l,expression:d,parsed:Kt(d)})}return{key:n,params:r}}function td(e){return typeof e=="string"&&ed.test(e)}function An(e){if(typeof e!="string")return[];const t=[],n=/\{\{?(p\d+)\}?\}/g;let o;for(;(o=n.exec(e))!==null;)t.push(o[1]);return t.sort()}function Ab(e,t,n){if(typeof e!="string")return e;const o=new RegExp(`(\\|${t}=)${Kn}`);return o.test(e)?e.replace(o,`$1${n}`):e}function vo(e,t){if(typeof e!="string")return e;const n=new RegExp(`\\|${t}=${Kn}`);return e.replace(n,"")}function nd(e,t){return typeof e!="string"?e:e.replace(new RegExp(`\\s*\\{\\{?${t}\\}?\\}\\s*`,"g")," ").replace(/\s+/g," ").trim()}function Tb(e,t){const n=s=>fr(typeof s=="string"?s:"").map(a=>a.raw.replace(/\s+/g,"")).sort(),o=n(e),r=n(t);return o.length!==r.length?!1:o.every((s,a)=>s===r[a])}function od(e){return e.__source?.kind==="base"}function rd(e){return e.__source?.kind==="partial"}function Db(e){return e.__source?.kind==="route"}function hr(e,t){return e.__source?.kind!=="extension"?!1:t==null?!0:e.__source.extensionId!==t}function id(e){return e.type==="extension_point"}function Qi(e=[]){for(const t of e)if(t.iteration&&t.iteration.source!==void 0)return!0;return!1}function zb(e,t=[]){for(const n of t)if(n.iteration&&n.iteration.source!==void 0)return!0;return e.iteration&&e.iteration.source!==void 0?!0:sd(e)}function sd(e){if(typeof e.text=="string"&&ad(e.text)&&!Nb(e.text))return!0;if(e.props&&typeof e.props=="object"){for(const t of Object.values(e.props))if(typeof t=="string"&&ad(t))return!0}return!1}function ad(e){return/\{\{[\s\S]*?\}\}/.test(e)}function Nb(e){const t=vt(e);return t!==null&&t.key.startsWith("custom.")}function Mb(e,t){return e??t??null}function Ri(e,t,n){if(id(e))return!0;switch(t){case"route":return od(e)||rd(e)||hr(e);case"base":return hr(e);case"modal":return hr(e);case"extension":return hr(e,n)?!0:od(e)||Db(e)||rd(e);default:return!1}}function et(e){return typeof e=="object"&&e!==null&&typeof e.responsive=="string"}function yr(e,t){return et(e)?et(t)&&e.responsive===t.responsive:!et(t)&&e===t}function at(e){const t=[];let n=!1;for(const o of e){if(et(o)){t.push("responsive",o.responsive),n=!0;continue}n?t.push("children",String(o)):(t.push(String(o)),n=!0)}return t.join(".")}function Qt(e){return Array.isArray(e.children)?e.children:[]}function br(e,t){const n=e.responsive?.[t];return n&&Array.isArray(n.children)?n.children:[]}function Be(e,t){if(!e)return null;if(t.length===0)return e;let n=e,o=Qt(e);for(const r of t){if(et(r)){o=br(n,r.responsive);continue}if(r<0||r>=o.length||(n=o[r],!n))return null;o=Qt(n)}return n}function Lb(e,t,n){if(!e||t.length===0)return t;let o=e,r=Qt(e),s;for(let a=0;a=2?t[t.length-2]:void 0;if(r!==void 0&&et(r)){const a=Be(e,t.slice(0,-2));return a?{owner:a,children:br(a,r.responsive),branchKey:r.responsive,index:o}:null}const s=Be(e,t.slice(0,-1));return s?{owner:s,children:Qt(s),index:o}:null}function es(e,t){if(e.branchKey!==void 0){const n={...e.owner.responsive??{}};n[e.branchKey]={...n[e.branchKey]??{},children:t},e.owner.responsive=n}else e.owner.children=t}function Rt(e){const t={...e};t.props&&typeof t.props=="object"&&(t.props={...t.props});const n=Qt(e);if(n.length>0&&(t.children=n.map(Rt)),e.responsive&&typeof e.responsive=="object"){const o={};for(const r of Object.keys(e.responsive)){const s=e.responsive[r];if(!s||typeof s!="object"){o[r]=s;continue}const a={...s};Array.isArray(s.children)&&(a.children=s.children.map(Rt)),a.props&&typeof a.props=="object"&&(a.props={...a.props}),o[r]=a}t.responsive=o}return t}function ts(e,t,n,o){const r=Rt(e),s=t.length>0?t[t.length-1]:void 0;if(s!==void 0&&et(s)){const p=Be(r,t.slice(0,-1));if(!p)return r;const f=br(p,s.responsive),b=Math.max(0,Math.min(n,f.length)),g=[...f];return g.splice(b,0,o),es({owner:p,branchKey:s.responsive},g),r}const a=Be(r,t);if(!a)return r;const l=Qt(a),d=Math.max(0,Math.min(n,l.length)),c=[...l];return c.splice(d,0,o),a.children=c,r}function ns(e,t){if(t.length===0)return e;const n=Rt(e),o=ld(n,t);if(!o||o.index<0||o.index>=o.children.length)return n;const r=[...o.children];return r.splice(o.index,1),es(o,r),n}function Pb(e,t,n,o){if(t.length===0||!n||et(t[t.length-1]))return e;const r=Rt(e),s=Be(r,t);if(!s)return r;const a=s.responsive&&typeof s.responsive=="object"?s.responsive[n]:void 0;if(a&&Array.isArray(a.children))return r;const l=o&&s.responsive&&typeof s.responsive=="object"?s.responsive[o]:void 0,c=(l&&Array.isArray(l.children)?l.children:Qt(s)).map(Rt),p={...s.responsive??{}};return p[n]={...p[n]??{},children:c},s.responsive=p,r}function Ob(e,t,n){if(t.length===0||!n||et(t[t.length-1]))return e;const o=Rt(e),r=Be(o,t);if(!r||!r.responsive||typeof r.responsive!="object")return o;const s=r.responsive[n];if(!s||!Array.isArray(s.children))return o;const a={...r.responsive},l={...a[n]};return delete l.children,Object.keys(l).length===0?delete a[n]:a[n]=l,r.responsive=Object.keys(a).length>0?a:void 0,o}function Bb(e,t,n,o){if(t.length===0)return e;const r=Be(e,t);if(!r||Wb(t,n))return e;const s=Rt(r),a=ns(e,t),l=dd(n,t);let d=o;const c=t.slice(0,-1);if(cd(c,n)){const p=t[t.length-1];(typeof p=="number"?p:0)o){const s=[...e];return s[n]=r-1,s}return e}function cd(e,t){if(e.length!==t.length)return!1;for(let n=0;ne.length||cd(e,t)}function os(e){const t={...e};if(t.props&&typeof t.props=="object"&&(t.props={...t.props}),typeof t.id=="string"&&t.id.length>0){const o=typeof t.name=="string"?t.name:"node";t.id=`${o}_${jb()}`}const n=Qt(e);return n.length>0&&(t.children=n.map(os)),t}function Ot(e,t,n){if(t.length===0)return n(e);const o=Rt(e),r=Be(o,t);if(!r)return o;const s=n(r),a=ld(o,t);if(!a||a.index<0||a.index>=a.children.length)return o;const l=[...a.children];return l[a.index]=s,es(a,l),o}function jb(){return Math.floor(Math.random()*2821109907456).toString(36).padStart(8,"0")}function Vn(e){if(!Array.isArray(e)||e.length===0)return[];const t=[];for(const n of e){const o=Hb(n);o.length>0&&t.push(...o)}return t}function Hb(e){if(!e||typeof e!="object")return[];const t=e.__source,n=e._fromBase===!0,o=t?.kind;if(o==="extension"||o==="partial")return[];if(o==="base"||n){const s=Array.isArray(e.children)?e.children:[];return Vn(s)}const r={...e};return delete r.__source,delete r._fromBase,delete r.__injectedProps,Array.isArray(r.children)&&(r.children=Vn(r.children)),[r]}function _o(e){if(!e||typeof e!="object")return e;const t=e.__editor,n=t&&typeof t=="object"&&!Array.isArray(t)?t.original:void 0,o=n&&typeof n=="object"&&!Array.isArray(n)?n:void 0,r=Array.isArray(e.components)?e.components:[],s=r.length>0,a=Vn(r),l=o?{...o}:{...e};if(typeof l.extends=="string"&&l.extends.length>0){delete l.components;const c=l.slots&&typeof l.slots=="object"&&!Array.isArray(l.slots)?l.slots:{},p=Object.keys(c);if(!s&&p.length>0){const f={};for(const[b,g]of Object.entries(c))f[b]=Array.isArray(g)?Vn(g):g;l.slots=f}else if(p.length===1)l.slots={[p[0]]:a};else if(p.length===0)l.slots={content:a};else{const f={};for(const[b,g]of Object.entries(c))f[b]=Array.isArray(g)?Vn(g):g;l.slots=f}}else l.components=a,delete l.slots;return delete l.lock_version,delete l.__editor,l}const ud="extension",Un="extensionless";function Fb(){const e=globalThis?.G7Config;if(globalThis?.__g7AssetUrlMode===Un)return Un;const n=e?.assetUrlMode;return n===Un||n===ud?n:e?.settings?.general?.asset_url_mode===Un?Un:ud}function Kb(){return Fb()===Un}function en(e,t,n,o){const r=e.replace(/\/+$/,""),s=t.replace(/^\.+/,""),a=Kb()?r:`${r}.${s}`,l=[];return o&&l.push(o.replace(/^[?&]+/,"")),n!=null&&n!==""&&l.push(`v=${n}`),l.length>0?`${a}?${l.join("&")}`:a}const pd=/^\s*\$t:([a-zA-Z0-9._-]+)\s*$/,mr="custom.",Vb=/\{\{.*?\}\}/;function Ub(e){return!!(!e||e.iteration&&typeof e.iteration=="object")}function fd(e,t){const n=e?.text,o=typeof n=="string"?n:"";if(Ub(e)||typeof n!="string")return{sourceState:"plain_text",editable:!1,customKey:null,displayValue:o};const r=vt(o);if(r&&r.key.startsWith(mr)){const a=t?t(r.key):r.key;return{sourceState:"custom_key",editable:!0,customKey:r.key,displayValue:a,isParamKey:!0}}const s=pd.exec(o);if(s){const a=s[1];if(a.startsWith(mr)){const d=t?t(a):a;return{sourceState:"custom_key",editable:!0,customKey:a,displayValue:d}}const l=t?t(a):"";return{sourceState:"plain_text",editable:!0,customKey:null,displayValue:l&&l!==a?l:""}}if(Vb.test(o)){const a=gr(o),l=pd.exec(a);if(l&&l[1].startsWith(mr)){const f=l[1],b=t?t(f):f;return{sourceState:"custom_key",editable:!0,customKey:f,displayValue:b}}const d=Ji(o,t),c=gr(d),p=/\$t:[a-zA-Z0-9._-]+/.test(c);if(c.length>0){const f=Zi(o,t);return{sourceState:"plain_with_binding",editable:!0,customKey:null,displayValue:p?"":c,chipValue:f.keyifiable?f.chipValue:void 0,chipParamLabels:f.keyifiable?f.paramLabels:void 0}}return{sourceState:"binding_expression",editable:!1,customKey:null,displayValue:o}}return{sourceState:"plain_text",editable:!0,customKey:null,displayValue:o}}function qb(){const{state:e}=Qe(),t=Ft(),n=e.templateIdentifier,o=e.locale,r=e.selectedRoute?.layoutName??null,s=u.useCallback(p=>{try{const b=Pt.getInstance().translate(p,{templateId:n,locale:o});return b&&b!==p?b:""}catch{return""}},[n,o]),a=u.useCallback(p=>fd(p,s),[s]),l=u.useCallback(p=>{Et({op:"inline_edit_cancel",componentPath:p?at(p):null,timestamp:Date.now()})},[]),d=u.useCallback(async(p,f)=>{if(!t)return{kind:"error",message:"no document context"};const g={children:t.document?.raw?.components??[]},m=Be(g,p),h=fd(m,s);if(!h.editable)return Et({op:"inline_edit_blocked_binding",sourceState:h.sourceState,componentPath:at(p),timestamp:Date.now()}),{kind:"blocked"};if(h.customKey){if(f===h.displayValue)return{kind:"noop",translationKey:h.customKey};xo(n,o,h.customKey,f);const S=await vr(n,h.customKey,o,f);return S.kind==="error"?{kind:"error",message:S.message}:(await tn(n,o),Et({op:"inline_edit_update_value",sourceState:"custom_key",componentPath:at(p),translationKey:h.customKey,toLocale:o,valueLength:f.length,valueHash:Li(f),timestamp:Date.now()}),{kind:"updated",translationKey:h.customKey})}const v=typeof m?.text=="string"?m.text:"",y=h.sourceState==="plain_with_binding",_=Ji(v,s),w=y?Rl(_):f,k=S=>y?Ql(S,v):S;t.patchLayout(S=>Ot({children:S},p,E=>({...E,text:f})).children??[]);const x=await qn(n,r,o,w);if(x.kind==="error"||!x.resource)return{kind:"error",message:x.message};const $=x.resource.translation_key;return xo(n,o,$,w),t.patchLayout(S=>Ot({children:S},p,E=>({...E,text:k(`$t:${$}`)})).children??[]),await tn(n,o),Et({op:"inline_edit_create_key",sourceState:h.sourceState,componentPath:at(p),translationKey:$,toLocale:o,valueLength:f.length,valueHash:Li(f),timestamp:Date.now()}),{kind:"created",translationKey:$,id:x.resource.id}},[t,n,o,r,s]),c=u.useCallback(async(p,f)=>{if(!t)return{kind:"error",message:"no document context"};const g={children:t.document?.raw?.components??[]},m=Be(g,p),h=typeof m?.text=="string"?m.text:"",v=vt(h);if(v&&v.key.startsWith(mr))return _r(n,v.key,o,f),xo(n,o,v.key,f),t.markDirty?.(),{kind:"updated",translationKey:v.key};const y=Zi(h,s),_=gr(f.replace(/\{\{?p\d+\}?\}/g," ")).replace(/\s+/g," ").trim(),w=await qn(n,r,o,_);if(w.kind==="error"||!w.resource)return{kind:"error",message:w.message};const k=w.resource.translation_key,x=An(f),$=w.resource.values??{},S={[o]:f};for(const C of Object.keys($)){if(C===o)continue;let T=$[C]??"";for(const E of x)T=Xi(T,E);S[C]=T}return wo(n,k,S),xo(n,o,k,f),t.patchLayout(C=>Ot({children:C},p,A=>({...A,text:Zl(`$t:${k}`,y)})).children??[]),t.markDirty?.(),await tn(n,o),xo(n,o,k,f),Et({op:"inline_edit_create_key",sourceState:"plain_with_binding",componentPath:at(p),translationKey:k,toLocale:o,valueLength:f.length,valueHash:Li(f),timestamp:Date.now()}),{kind:"created",translationKey:k}},[t,n,o,r]);return{classify:a,commit:d,trackCancel:l,keyifyChipValue:c}}async function qn(e,t,n,o){const r=`/api/admin/templates/${encodeURIComponent(e)}/custom-translations`;try{const s=await fetch(r,{method:"POST",credentials:"same-origin",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({layout_name:t,locale:n,value:o})}),a=await s.json().catch(()=>null);if(!s.ok)return{kind:"error",message:a?.message??`HTTP ${s.status}`};const l=a?.data;return!l||typeof l.translation_key!="string"?{kind:"error",message:"invalid response"}:{kind:"ok",resource:l}}catch(s){return{kind:"error",message:s instanceof Error?s.message:"network error"}}}async function vr(e,t,n,o){const r=await cn(e,t);if(!r)return{kind:"error",message:"custom key not found"};const s=`/api/admin/templates/${encodeURIComponent(e)}/custom-translations/${r.id}`,a={...r.values??{},[n]:o};try{const l=await fetch(s,{method:"PUT",credentials:"same-origin",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({values:a,expected_lock_version:r.lock_version})}),d=await l.json().catch(()=>null);return l.status===409?{kind:"error",message:"concurrent_modification"}:l.ok?{kind:"ok"}:{kind:"error",message:d?.message??`HTTP ${l.status}`}}catch(l){return{kind:"error",message:l instanceof Error?l.message:"network error"}}}async function cn(e,t){const n=`/api/admin/templates/${encodeURIComponent(e)}/custom-translations`;try{const o=await fetch(n,{method:"GET",credentials:"same-origin",headers:Ne()});if(!o.ok)return null;const s=(await o.json().catch(()=>null))?.data;return Array.isArray(s)?s.find(a=>a.translation_key===t)??null:null}catch{return null}}function xo(e,t,n,o){try{Pt.getInstance().setTranslationValue(e,t,n,o)}catch{}if(typeof window<"u")try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:e,locale:t}}))}catch{}}const kt="g7le:translations-refreshed";async function tn(e,t){if(typeof window>"u")return;const n=t??window.__g7EditorContentLocale;if(n){try{const o=Pt.getInstance();try{const r=await fetch(en(`/api/templates/${encodeURIComponent(e)}/config`,"json"),{headers:{Accept:"application/json"},credentials:"same-origin"}).then(a=>a.ok?a.json():null),s=r?.data?.cache_version??r?.cache_version;if(typeof s=="number"&&s>0){o.setCacheVersion(s);const a=window;a.G7Config&&(a.G7Config.cache_version=s)}}catch{}await o.loadTranslations(e,n,"/api",!0)}catch{}try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:e,locale:n}}))}catch{}}}const nn=new Map;function _r(e,t,n,o){const r=nn.get(t)??{};r[n]=o,nn.set(t,r);try{Pt.getInstance().setTranslationValue(e,n,t,o)}catch{}if(typeof window<"u")try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:e,locale:n}}))}catch{}}function wo(e,t,n){for(const[o,r]of Object.entries(n))_r(e,t,o,r)}function It(e,t){return nn.get(e)?.[t]}function Gb(e){const t=nn.get(e);return t?{...t}:void 0}function Yb(){return nn.size>0}function gd(e,t){for(const[n,o]of nn.entries())for(const[r,s]of Object.entries(o))try{e.setTranslationValue(t,r,n,s)}catch{}}async function Xb(e){if(nn.size===0)return{ok:0,failed:[]};const t=Array.from(nn.entries());let n=0;const o=[];for(const[r,s]of t)try{const a=await cn(e,r);if(!a){o.push(r);continue}const l={...a.values??{},...s},d=`/api/admin/templates/${encodeURIComponent(e)}/custom-translations/${a.id}`;if(!(await fetch(d,{method:"PUT",credentials:"same-origin",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({values:l,expected_lock_version:a.lock_version})})).ok){o.push(r);continue}n+=1}catch{o.push(r)}for(const[r]of t)o.includes(r)||nn.delete(r);try{await tn(e)}catch{}return{ok:n,failed:o}}function Gn(e,t){const n=`layout_editor.locale.${e}`,o=t(n);return o&&o!==n?o:e.toUpperCase()}function hd(){if(typeof window>"u")return[];const t=window.G7Config?.appConfig?.supportedLocales;return Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.length>0):[]}function Jb({locales:e}={}){const{t}=tt(),{state:n,dispatch:o}=Qe();u.useEffect(()=>{window.__g7EditorContentLocale=n.locale},[n.locale]);const r=e??hd(),s=r.includes(n.locale)?r:[n.locale,...r];if(s.length<=1)return i.jsxs("span",{className:"g7le-locale-switcher g7le-locale-switcher--single","data-testid":"g7le-locale-switcher-single",style:{fontSize:11,color:"#475569",padding:"0 4px"},children:[t("layout_editor.chrome.toolbar.locale_switcher_label"),": ",Gn(n.locale,t)]});const a=l=>{if(l===n.locale)return;const d=n.locale;o({type:"SET_LOCALE",locale:l}),Et({op:"locale_switch",fromLocale:d,toLocale:l,timestamp:Date.now()})};return i.jsxs("div",{className:"g7le-locale-switcher","data-testid":"g7le-locale-switcher",role:"group","aria-label":t("layout_editor.chrome.toolbar.locale_switcher_label"),style:{display:"inline-flex",alignItems:"center",gap:4},children:[i.jsx("span",{style:{fontSize:11,color:"#475569"},children:t("layout_editor.chrome.toolbar.locale_switcher_label")}),i.jsx("div",{style:{display:"inline-flex",gap:2},children:s.map(l=>{const d=l===n.locale;return i.jsx("button",{type:"button","data-testid":`g7le-locale-${l}`,"aria-pressed":d,onClick:()=>a(l),style:{padding:"2px 8px",fontSize:12,cursor:"pointer",background:d?"#0f172a":"#f8fafc",color:d?"#fff":"#0f172a",border:"1px solid #cbd5e1",borderRadius:4},children:Gn(l,t)},l)})})]})}const Zb=/\{\{?(p\d+)\}?\}/g;function Qb(e){const t=[];if(typeof e!="string"||e.length===0)return t;const n=new RegExp(Zb.source,"g");let o=0,r;for(;(r=n.exec(e))!==null;){const s=r.index,a=s+r[0].length;s>o&&t.push({kind:"text",raw:e.slice(o,s),start:o,end:s}),t.push({kind:"chip",raw:r[0],paramName:r[1],start:s,end:a}),o=a}return o{n.push({kind:"text",text:a}),r=!0};for(const a of t)a.kind==="text"?(o=a.raw,s(o),o=""):(r||s(""),n.push({kind:"chip",paramName:a.paramName}),r=!1);return r||s(""),n}function em(e,t,n,o){const r=[];return e.forEach((s,a)=>{if(s.kind==="chip"){if(s.paramName===t)return;r.push(`{${s.paramName}}`)}else{const l=s.text??"";if(a===n){const d=Math.max(0,Math.min(o,l.length));r.push(l.slice(0,d),`{${t}}`,l.slice(d))}else r.push(l)}}),r.join("")}function xr({value:e,onChange:t,t:n,paramLabels:o,onRequestInsert:r,onRemoveChip:s,testIdSuffix:a="pc",disabled:l=!1,hideInsertButton:d=!1,caretRef:c}){const p=u.useMemo(()=>Rb(e),[e]),f=u.useRef(null),[b,g]=u.useState(null),[m,h]=u.useState(null),[v,y]=u.useState(null),_=u.useMemo(()=>p.map(O=>O.kind==="chip"?`c:${O.paramName}`:"t").join("|"),[p]),w=u.useRef(null),k=u.useRef([]),x=u.useRef(!1);u.useLayoutEffect(()=>{const O=x.current;x.current=!1,!(!O&&w.current===_)&&(w.current=_,p.forEach((z,H)=>{if(z.kind!=="text")return;const P=k.current[H];P&&P.textContent!==(z.text??"")&&(P.textContent=z.text??"")}))},[_,p,e]);const $=()=>{const O=f.current;if(!O)return e;const z=[];for(const H of Array.from(O.querySelectorAll("[data-seg]")))H.dataset.seg==="chip"?z.push(`{${H.dataset.param??""}}`):z.push(H.textContent??"");return z.join("")},S=()=>{l||t($())},C=u.useRef(null),T=u.useRef(!1),E=(O,z)=>{if(!l){O.preventDefault(),O.stopPropagation(),C.current={param:z,pointerId:O.pointerId},T.current=!1,g(z);try{O.currentTarget.setPointerCapture(O.pointerId)}catch{}}},A=O=>{const z=C.current;if(!z||O.pointerId!==z.pointerId)return;T.current=!0;const H=B(O.clientX,O.clientY);H&&(h({slotIdx:H.slotIdx,offset:H.offset}),y(nm(f.current,H.slotIdx,H.offset)))},N=(O,z)=>{if(O.stopPropagation(),T.current){T.current=!1;return}s?.(z)},D=O=>{const z=C.current;if(!z||O.pointerId!==z.pointerId)return;try{O.currentTarget.releasePointerCapture(O.pointerId)}catch{}C.current=null,T.current&&typeof setTimeout=="function"&&setTimeout(()=>{T.current=!1},0);const H=B(O.clientX,O.clientY);if(g(null),h(null),y(null),!H)return;const P=f.current;if(!P)return;const L=Array.from(P.querySelectorAll("[data-seg]")).map(Y=>Y.dataset.seg==="chip"?{kind:"chip",paramName:Y.dataset.param??""}:{kind:"text",text:Y.textContent??""}),F=em(L,z.param,H.slotIdx,H.offset);F!==e&&(x.current=!0,t(F))},B=(O,z)=>{const H=f.current;if(!H)return null;const P=Array.from(H.querySelectorAll("[data-seg]")),I=H.ownerDocument,L=I.elementFromPoint(O,z);let F=L?.closest('[data-seg="text"]');if(F)return{slotIdx:P.indexOf(F),offset:tm(I,F,O,z)};const Y=L?.closest('[data-seg="chip"]');if(Y){const X=P.indexOf(Y),Z=Y.getBoundingClientRect();if(O=0){const ae=P[X-1];return{slotIdx:X-1,offset:(ae.textContent??"").length}}if(X+1({s:X,i:Z})).filter(X=>X.s.dataset.seg==="text").pop();return K?{slotIdx:K.i,offset:(K.s.textContent??"").length}:null},M=()=>{l||!r||r(yd(f.current,e.length))};return u.useEffect(()=>{if(c)return c.current=()=>yd(f.current,e.length),()=>{c.current=null}},[c,e.length]),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsxs("div",{ref:f,"data-testid":`g7le-chip-input-${a}`,className:"g7le-chip-input",style:om,children:[p.map((O,z)=>O.kind==="chip"?i.jsxs("span",{"data-seg":"chip","data-param":O.paramName,"data-testid":`g7le-chip-${a}-${O.paramName}`,contentEditable:!1,onPointerDown:H=>E(H,O.paramName??""),onPointerMove:A,onPointerUp:D,title:n("layout_editor.translation.placeholder_locked"),style:{...am,...b===O.paramName?lm:null,touchAction:"none"},children:[i.jsx("span",{"aria-hidden":"true",style:dm,children:"⠿"}),i.jsx("span",{"aria-hidden":"true",style:{marginRight:3},children:"🔗"}),i.jsx("span",{style:cm,children:o?.[O.paramName??""]??O.paramName}),s&&!l&&i.jsx("button",{type:"button","data-testid":`g7le-chip-remove-${a}-${O.paramName}`,"aria-label":n("layout_editor.inline_binding.clear"),title:n("layout_editor.inline_binding.clear"),onPointerDown:H=>{H.stopPropagation(),H.preventDefault()},onClick:H=>N(H,O.paramName??""),style:um,children:"✕"})]},`chip-${O.paramName}`):i.jsx("span",{ref:H=>{k.current[z]=H},"data-seg":"text",contentEditable:!l,suppressContentEditableWarning:!0,onInput:S,"data-testid":`g7le-chip-text-${a}-${z}`,style:{...rm,...b?im:null,...m?.slotIdx===z?sm:null}},`text-slot-${z}`)),v&&i.jsx("span",{"aria-hidden":"true","data-testid":`g7le-chip-caret-${a}`,style:{position:"absolute",left:v.left,top:v.top,width:2,height:v.height,background:"#2563eb",borderRadius:1,pointerEvents:"none",boxShadow:"0 0 0 1px rgba(37,99,235,0.3)"}})]}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[r&&!d&&i.jsxs("button",{type:"button","data-testid":`g7le-chip-insert-${a}`,onClick:M,disabled:l,style:pm,children:["+ ",n("layout_editor.inline_binding.insert_data")]}),i.jsx("span",{style:fm,children:n("layout_editor.translation.placeholder_locked")})]})]})}function tm(e,t,n,o){const r=(t.textContent??"").length;try{const a=e;let l=null,d=0;if(typeof a.caretRangeFromPoint=="function"){const c=a.caretRangeFromPoint(n,o);c&&(l=c.startContainer,d=c.startOffset)}else if(typeof a.caretPositionFromPoint=="function"){const c=a.caretPositionFromPoint(n,o);c&&(l=c.offsetNode,d=c.offset)}if(l&&t.contains(l))return Math.max(0,Math.min(d,r))}catch{}const s=t.getBoundingClientRect();return n>s.left+s.width/2?r:0}function nm(e,t,n){if(!e)return null;const r=Array.from(e.querySelectorAll("[data-seg]"))[t];if(!r)return null;const s=e.getBoundingClientRect();try{const d=r.firstChild,c=e.ownerDocument;if(d&&d.nodeType===Node.TEXT_NODE&&(d.textContent??"").length>0){const p=c.createRange(),f=Math.max(0,Math.min(n,(d.textContent??"").length));p.setStart(d,f),p.setEnd(d,f);const b=p.getClientRects(),g=b.length>0?b[0]:p.getBoundingClientRect();if(g&&(g.height>0||g.width>=0))return{left:g.left-s.left,top:g.top-s.top,height:g.height||r.getBoundingClientRect().height}}}catch{}const a=r.getBoundingClientRect();return{left:(n>0?a.right:a.left)-s.left,top:a.top-s.top,height:a.height||16}}function yd(e,t){if(!e)return t;try{const n=e.ownerDocument.defaultView?.getSelection();if(!n||n.rangeCount===0)return t;const o=n.getRangeAt(0);let r=o.startContainer,s=null;for(;r&&r!==e;){if(r instanceof HTMLElement&&r.dataset.seg==="text"){s=r;break}r=r.parentNode}if(!s||!e.contains(s))return t;const a=Array.from(e.querySelectorAll("[data-seg]"));let l=0;for(const d of a){if(d===s)break;l+=d.dataset.seg==="chip"?`{${d.dataset.param??""}}`.length:(d.textContent??"").length}return l+o.startOffset}catch{return t}}const om={position:"relative",display:"flex",flexWrap:"wrap",alignItems:"center",gap:2,minHeight:30,padding:"4px 8px",border:"1px solid #cbd5e1",borderRadius:4,background:"#fff",fontSize:13,lineHeight:1.6},rm={outline:"none",minWidth:8,minHeight:"1.2em",whiteSpace:"pre-wrap",color:"#0f172a",display:"inline-block"},im={boxShadow:"inset 0 -2px 0 #93c5fd",background:"#eff6ff",borderRadius:2},sm={background:"#dbeafe",boxShadow:"inset 0 -2px 0 #2563eb"},am={display:"inline-flex",alignItems:"center",gap:1,background:"linear-gradient(180deg,#eff6ff,#dbeafe)",color:"#1d4ed8",border:"1px dashed #60a5fa",borderRadius:9999,padding:"1px 8px 1px 4px",margin:"0 1px",fontSize:12,fontWeight:600,cursor:"grab",userSelect:"none",whiteSpace:"nowrap",boxShadow:"0 1px 2px rgba(37,99,235,0.18)",verticalAlign:"middle"},lm={opacity:.5,borderStyle:"solid",cursor:"grabbing"},dm={color:"#2563eb",opacity:.7,fontSize:11,marginRight:1,cursor:"grab"},cm={textDecoration:"none"},um={marginLeft:4,width:14,height:14,lineHeight:"12px",padding:0,border:"none",borderRadius:9999,background:"rgba(29,78,216,0.12)",color:"#1d4ed8",fontSize:9,fontWeight:700,cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"0 0 auto"},pm={fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#334155",padding:"3px 10px",cursor:"pointer"},fm={fontSize:10,color:"#94a3b8"};function bd(e){e&&(e.style.height="auto",e.style.height=`${Math.max(e.scrollHeight,28)}px`)}function gm(e){bd(e)}function hm(e){const t=new Set;for(const n of e)for(const o of Object.keys(n.values??{}))t.add(o);return Array.from(t).sort()}function ym({templateIdentifier:e,layoutName:t,t:n,referencedKeys:o,onClose:r}){const[s,a]=u.useState([]),[l,d]=u.useState("idle"),[c,p]=u.useState(null),[f,b]=u.useState("all"),[g,m]=u.useState(new Set),[h,v]=u.useState({}),[y,_]=u.useState(null),[w,k]=u.useState({}),x=u.useCallback(async()=>{d("loading"),p(null);const z=await Vy(e,t);z.ok?(a(z.data),v({}),m(new Set),k({}),d("idle")):(p(z.message),d("error"))},[e,t]);u.useEffect(()=>{x()},[x]);const $=u.useMemo(()=>hm(s),[s]),S=u.useMemo(()=>s.filter(z=>f==="all"?!0:z.status===f).slice().sort((z,H)=>{const P=z.updated_at?Date.parse(z.updated_at):0,I=H.updated_at?Date.parse(H.updated_at):0;return I!==P?I-P:H.id-z.id}),[s,f]),C=u.useMemo(()=>s.filter(z=>z.status==="orphaned"),[s]),T=u.useCallback(z=>{const H={...z.values??{}};for(const P of Object.keys(H)){const I=It(z.translation_key,P);I!==void 0&&(H[P]=I)}return H},[]),E=u.useCallback(z=>h[z.id]??T(z),[h,T]),A=u.useCallback((z,H,P)=>{v(I=>{const L=I[z]??s.find(F=>F.id===z)?.values??{};return{...I,[z]:{...L,[H]:P}}})},[s]),N=u.useCallback(async z=>{_(z.id),k(I=>({...I,[z.id]:""}));const H=E(z),P=await Uy(e,z.id,H,z.lock_version);if(P.ok)a(I=>I.map(L=>L.id===z.id?P.data:L)),v(I=>{const L={...I};return delete L[z.id],L});else{const I=P.status===409?n("layout_editor.translation_manager.conflict"):P.message;k(L=>({...L,[z.id]:I}))}_(null)},[e,E,n]),D=u.useCallback(z=>typeof window<"u"&&typeof window.confirm=="function"?window.confirm(n("layout_editor.translation_manager.delete_confirm",{count:z})):!0,[n]),B=u.useCallback(async z=>{if(!D(1))return;const H=await qy(e,z.id);H.ok?(a(P=>P.filter(I=>I.id!==z.id)),m(P=>{const I=new Set(P);return I.delete(z.id),I})):p(H.message)},[e,D]),M=u.useCallback(async z=>{if(z.length===0||!D(z.length))return;const H=await Gy(e,z);if(H.ok){const P=new Set(z);a(I=>I.filter(L=>!P.has(L.id))),m(new Set)}else p(H.message)},[e,D]),O=u.useCallback(z=>{m(H=>{const P=new Set(H);return P.has(z)?P.delete(z):P.add(z),P})},[]);return i.jsxs("div",{className:"g7le-translation-manager","data-testid":"g7le-translation-manager",style:bm,children:[i.jsxs("div",{"data-modal-drag-handle":!0,style:mm,children:[i.jsx("span",{style:{fontSize:14,fontWeight:700},"data-testid":"g7le-translation-manager-title",children:n("layout_editor.translation_manager.title")}),i.jsx("button",{type:"button","aria-label":"close",onClick:r,style:vm,"data-testid":"g7le-translation-manager-close",children:"✕"})]}),i.jsxs("div",{style:_m,children:[i.jsx("div",{style:{display:"inline-flex",gap:4},role:"tablist","aria-label":n("layout_editor.translation_manager.filter_label"),children:["all","active","orphaned"].map(z=>i.jsx("button",{type:"button",role:"tab","aria-selected":f===z,"data-active":f===z?"true":"false",onClick:()=>b(z),style:f===z?xm:md,"data-testid":`g7le-translation-filter-${z}`,children:n(`layout_editor.translation_manager.filter_${z}`)},z))}),i.jsx("div",{style:{flex:1}}),g.size>0&&i.jsxs("button",{type:"button",onClick:()=>void M(Array.from(g)),style:vd,"data-testid":"g7le-translation-bulk-delete",children:["🗑 ",n("layout_editor.translation_manager.delete_selected",{count:g.size})]}),C.length>0&&i.jsxs("button",{type:"button",onClick:()=>void M(C.map(z=>z.id)),style:vd,"data-testid":"g7le-translation-purge-orphaned",children:["🧹 ",n("layout_editor.translation_manager.purge_orphaned",{count:C.length})]})]}),c&&i.jsx("div",{style:wm,"data-testid":"g7le-translation-manager-error",children:c}),i.jsx("div",{style:km,children:l==="loading"?i.jsx("div",{style:_d,"data-testid":"g7le-translation-manager-loading",children:n("layout_editor.translation_manager.loading")}):S.length===0&&l!=="error"?i.jsx("div",{style:_d,"data-testid":"g7le-translation-manager-empty",children:n("layout_editor.translation_manager.empty")}):i.jsx("div",{"data-testid":"g7le-translation-list",style:Sm,children:S.map(z=>{const H=E(z),P=z.status==="orphaned",I=o?o.has(z.translation_key):null;return i.jsxs("div",{style:Cm,"data-testid":`g7le-translation-row-${z.id}`,children:[i.jsxs("div",{style:$m,children:[i.jsx("input",{type:"checkbox",checked:g.has(z.id),onChange:()=>O(z.id),"aria-label":n("layout_editor.translation_manager.select_aria",{key:z.translation_key}),"data-testid":`g7le-translation-select-${z.id}`}),i.jsx("code",{style:Em,children:z.translation_key}),P&&i.jsx("span",{style:Im,"data-testid":`g7le-translation-badge-orphaned-${z.id}`,children:n("layout_editor.translation_manager.badge_orphaned")}),I===!0&&i.jsx("span",{style:Am,"data-testid":`g7le-translation-badge-live-inuse-${z.id}`,children:n("layout_editor.translation_manager.badge_live_in_use")}),I===!1&&i.jsx("span",{style:Tm,"data-testid":`g7le-translation-badge-live-unused-${z.id}`,children:n("layout_editor.translation_manager.badge_live_unused")}),i.jsx("div",{style:{flex:1}}),i.jsx("button",{type:"button",onClick:()=>void B(z),style:Om,"data-testid":`g7le-translation-delete-${z.id}`,children:"🗑"})]}),i.jsxs("div",{style:Dm,children:[$.map(L=>{const F=H[L]??"",Y=An(F).length>0;return i.jsxs("div",{style:zm,"data-testid":`g7le-translation-field-${z.id}-${L}`,children:[i.jsxs("label",{style:Nm,title:L,children:[Gn(L,n),i.jsxs("span",{style:Mm,children:["(",L,")"]})]}),Y?i.jsx("div",{style:{flex:1},"data-testid":`g7le-translation-chip-${z.id}-${L}`,children:i.jsx(xr,{value:F,onChange:K=>A(z.id,L,K),t:n,testIdSuffix:`${z.id}-${L}`})}):i.jsx("textarea",{value:F,rows:1,ref:gm,onChange:K=>{A(z.id,L,K.currentTarget.value),bd(K.currentTarget)},style:Lm,"data-testid":`g7le-translation-input-${z.id}-${L}`})]},L)}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("button",{type:"button",disabled:y===z.id,onClick:()=>void N(z),style:Pm,"data-testid":`g7le-translation-save-${z.id}`,children:y===z.id?n("layout_editor.translation_manager.saving"):n("layout_editor.translation_manager.save")}),w[z.id]?i.jsx("span",{style:{fontSize:11,color:"#dc2626"},"data-testid":`g7le-translation-row-error-${z.id}`,children:w[z.id]}):null]})]})]},z.id)})})}),i.jsx("div",{style:Bm,children:i.jsx("button",{type:"button",onClick:r,style:Wm,"data-testid":"g7le-translation-manager-footer-close",children:n("layout_editor.translation_manager.close")})})]})}const bm={display:"flex",flexDirection:"column",minHeight:0,flex:1},mm={display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #e2e8f0"},vm={border:"none",background:"transparent",fontSize:16,color:"#94a3b8",cursor:"pointer"},_m={padding:"10px 16px",borderBottom:"1px solid #f1f5f9",display:"flex",gap:8,alignItems:"center"},md={padding:"4px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},xm={...md,borderColor:"#2563eb",background:"#eff6ff",color:"#1d4ed8",fontWeight:600},vd={padding:"4px 10px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},wm={padding:"8px 16px",fontSize:12,color:"#b91c1c",background:"#fef2f2"},km={padding:16,overflow:"auto",flex:1,minHeight:120,display:"flex",flexDirection:"column",gap:12},_d={fontSize:13,color:"#94a3b8",textAlign:"center",padding:"32px 0"},Sm={display:"flex",flexDirection:"column",gap:20},Cm={border:"1px solid #e2e8f0",borderRadius:8,padding:10,display:"flex",flexDirection:"column",gap:6},$m={display:"flex",alignItems:"center",gap:8},Em={fontSize:11,background:"#f1f5f9",padding:"2px 6px",borderRadius:4,color:"#0f172a"},Im={fontSize:10,color:"#b45309",background:"#fef3c7",padding:"1px 6px",borderRadius:4,fontWeight:600},Am={fontSize:10,color:"#15803d",background:"#dcfce7",padding:"1px 6px",borderRadius:4,fontWeight:600},Tm={fontSize:10,color:"#9f1239",background:"#ffe4e6",padding:"1px 6px",borderRadius:4,fontWeight:600},Dm={display:"flex",flexDirection:"column",gap:6},zm={display:"flex",alignItems:"flex-start",gap:8},Nm={fontSize:12,color:"#475569",minWidth:88,fontWeight:600,paddingTop:4,display:"flex",flexDirection:"column",lineHeight:1.2},Mm={fontSize:10,color:"#94a3b8",fontWeight:400},Lm={flex:1,padding:"4px 8px",fontSize:13,border:"1px solid #cbd5e1",borderRadius:4,color:"#0f172a",resize:"vertical",overflow:"hidden",minHeight:28,lineHeight:1.4,fontFamily:"inherit",boxSizing:"border-box"},Pm={padding:"5px 12px",fontSize:12,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"},Om={padding:"4px 8px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},Bm={padding:"10px 16px",borderTop:"1px solid #e2e8f0",display:"flex",justifyContent:"flex-end"},Wm={padding:"6px 14px",fontSize:13,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"};function jm(){const e=Ft(),{state:t}=Qe(),n=e?.document?.raw??null,o=t.templateIdentifier??"",r=t.selectedRoute?.layoutName??"",s=u.useCallback((c,p)=>{const f=n?.[c];return f===void 0?p:f},[n]),a=u.useCallback((c,p,...f)=>{e&&(f.length>=1?e.patchDocumentRaw(c,p,f[0]):e.patchDocumentRaw(c,p))},[e]),l=u.useCallback(async(c,p)=>!o||!r?null:qn(o,r,c,p),[o,r]),d=u.useCallback(async(c,p,f)=>o?vr(o,c,p,f):null,[o]);return{raw:n,getValue:s,patch:a,createI18nKey:l,updateI18nKeyValue:d}}function Hm(e){const t=e.__source;return t&&(t.kind==="module"||t.kind==="plugin")&&t.identifier?`${t.kind}:${t.identifier}`:"template"}function xd(e,t){if(!t)return null;const n=Hm(e);if(n&&t.bySource){const a=t.bySource[n]?.[e.id];if(a!==void 0)return{value:a,match:{dataSourceId:e.id,resolvedBy:"spec_byId",sourceKey:n}}}const o=t.byDataSourceId?.[e.id];if(o!==void 0)return{value:o,match:{dataSourceId:e.id,resolvedBy:"spec_byId"}};const r=e.endpoint??"";if(t.byEndpointPattern&&typeof r=="string"&&r.length>0){for(const[s,a]of Object.entries(t.byEndpointPattern))if(Fm(r,s))return{value:a,match:{dataSourceId:e.id,resolvedBy:"spec_byEndpoint"}}}return null}function rs(e,t){const n=xd(e,t);if(n)return n;const o=e.fallback?.data;return o!==void 0?{value:{data:Array.isArray(o)?o:[o]},match:{dataSourceId:e.id,resolvedBy:"fallback"}}:{value:{},match:{dataSourceId:e.id,resolvedBy:"inferred"}}}function Fm(e,t){const n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(e)}function Km(e={}){const{spec:t,overrideSpec:n,onMatch:o}=e;return{has(r){return!0},resolve(r){const s=n?xd(r,n):null,{value:a,match:l}=s??rs(r,t);if(o)try{o(l)}catch{}return a}}}const wd=Lt(),kd=wd.DataBindingEngine,Sd=wd.dataBindingEngine;mo("PipeRegistry");function Vm(e){let t=null,n=0;for(let o=0;o0?e[o-1]:"",a=o{const a=t[r],l=a==null?[]:String(a).split(",").map(d=>d.trim()).filter(Boolean);return l.length===0?"":l.join(" ?? ")+(s?" ?? ":"")});return n=n.replace(/\{(\w+)\}/g,(o,r)=>{const s=t[r];return s===void 0?o:s}),n}function wr(e){const t=e.trim(),n=/^\{\{([\s\S]*)\}\}$/.exec(t);return n?n[1].trim():t}function $d(e){const t=e.trim();return/^\{\{[\s\S]*\}\}$/.test(t)?t:`{{ ${t} }}`}function Ed(e,t){const n={};for(const[r,s]of Object.entries(t))n[r]=typeof s=="string"?wr(s):s;const o=qm(e.expr,n);return $d(o)}function Gm(e,t){if(typeof e!="string")return null;const n=Id(wr(e));for(const o of t){const r=Ym(n,o.expr,o.params);if(r)return{recipeId:o.id,params:r}}return null}function Id(e){return e.replace(/\s+/g," ").trim()}function Ad(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ym(e,t,n){const o=[],r=new Set;let s="";const a=/\{(\w+)(\*?)\}(\s*\?\?\s*)?/g;let l=0,d;const c=Id(t);for(;(d=a.exec(c))!==null;){const g=c.slice(l,d.index);s+=Ad(g).replace(/\\ /g,"\\s*");const m=d[2]==="*",h=!!d[3];m?(r.add(d[1]),s+="(.*?)",h&&(s+="(?:\\s*\\?\\?\\s*)?")):(s+="(.+?)",h&&(s+="\\s*\\?\\?\\s*")),o.push(d[1]),l=a.lastIndex}s+=Ad(c.slice(l)).replace(/\\ /g,"\\s*");let p;try{p=new RegExp(`^${s}$`)}catch{return null}const f=p.exec(e);if(!f)return null;const b={};if(o.forEach((g,m)=>{let h=(f[m+1]??"").trim();r.has(g)&&(h=h.split(/\s*\?\?\s*/).map(v=>v.trim()).filter(Boolean).join(", ")),b[g]=h}),n.length>0){const g=new Set(n.map(m=>m.key));for(const m of Object.keys(b))g.has(m)||delete b[m]}return b}function Xm(e){const t=`x.${e.field}`,n=Jm(e.value);switch(e.cmp){case"=":return`${t} === ${n}`;case"!=":return`${t} !== ${n}`;case">":return`${t} > ${n}`;case"<":return`${t} < ${n}`;case">=":return`${t} >= ${n}`;case"<=":return`${t} <= ${n}`;case"includes":return`(${t} ?? []).includes(${n})`;default:return`${t} === ${n}`}}function Jm(e){const t=e.trim();return t==="true"||t==="false"||t!==""&&!Number.isNaN(Number(t))||/^['"].*['"]$/.test(t)||/[.([{]/.test(t)?t:`'${t.replace(/'/g,"\\'")}'`}function is(e){return!e||e.length===0?"true":e.map(Xm).join(" && ")}function Zm(e){const n=`(${(e.source??"").trim()||"[]"} ?? [])`;let o;switch(e.op){case"count":o=`${n}.filter(x => ${is(e.conditions)}).length`;break;case"sum":{const r=(e.sumField??"").trim()||"value";o=`${n}.filter(x => ${is(e.conditions)}).reduce((s, x) => s + (x.${r} ?? 0), 0)`;break}case"filter":o=`${n}.filter(x => ${is(e.conditions)})`;break;case"toOptions":{const r=(e.valueField??"").trim()||"value",s=(e.labelField??"").trim()||"label";o=`${n}.map(x => ({ value: x.${r}, label: x.${s} }))`;break}case"nth":{const r=(e.index??"").trim()||"0",s=(e.prop??"").trim();o=`${n}[${r}]${s?`?.${s}`:""}`;break}case"firstOf":{const r=(e.candidates??[]).map(l=>l.trim()).filter(Boolean),s=r.length>0?r.join(" ?? "):"''",a=(e.fallback??"").trim();o=a?`${s} ?? '${a.replace(/'/g,"\\'")}'`:s;break}case"literal":{const r=e.literalKind??"string",s=(e.literalValue??"").trim();r==="number"?o=s===""?"0":s:r==="boolean"?o=s==="true"?"true":"false":o=`'${s.replace(/'/g,"\\'")}'`;break}default:o="[]"}return $d(o)}function Qm(e){if(typeof e!="string")return null;const t=wr(e).trim();let n=/^\((.+?)\s*\?\?\s*\[\]\)\.filter\(x => (.+)\)\.length$/.exec(t);return n?{key:"",op:"count",source:n[1].trim(),conditions:ss(n[2])}:(n=/^\((.+?)\s*\?\?\s*\[\]\)\.filter\(x => (.+)\)\.reduce\(\(s, x\) => s \+ \(x\.(\w+(?:\.\w+)*) \?\? 0\), 0\)$/.exec(t),n?{key:"",op:"sum",source:n[1].trim(),conditions:ss(n[2]),sumField:n[3]}:(n=/^\((.+?)\s*\?\?\s*\[\]\)\.filter\(x => (.+)\)$/.exec(t),n?{key:"",op:"filter",source:n[1].trim(),conditions:ss(n[2])}:(n=/^\((.+?)\s*\?\?\s*\[\]\)\.map\(x => \(\{ value: x\.(\w+(?:\.\w+)*), label: x\.(\w+(?:\.\w+)*) \}\)\)$/.exec(t),n?{key:"",op:"toOptions",source:n[1].trim(),valueField:n[2],labelField:n[3]}:(n=/^\((.+?)\s*\?\?\s*\[\]\)\[(.+?)\](?:\?\.(\w+(?:\.\w+)*))?$/.exec(t),n?{key:"",op:"nth",source:n[1].trim(),index:n[2].trim(),prop:n[3]}:null))))}function ss(e){const t=e.trim();if(t==="true")return[];const n=[];for(const o of Rm(t)){const r=ev(o.trim());r&&n.push(r)}return n}function Rm(e){const t=[];let n=0,o=0;for(let r=0;r=|<=|>|<)\s*(.+)$/.exec(e),t){const n={"===":"=","!==":"!=",">":">","<":"<",">=":">=","<=":"<="};return{field:t[1],cmp:n[t[2]]??"=",value:Td(t[3])}}return null}function Td(e){const t=e.trim(),n=/^'(.*)'$/.exec(t)||/^"(.*)"$/.exec(t);return n?n[1]:t}function Dd(e,t){const n=Gm(e,t);if(n)return{kind:"preset",recipeId:n.recipeId,params:n.params};const o=Qm(e);return o?{kind:"custom",model:o}:{kind:"advanced"}}function tv(e){if(e==null)return"null";if(Array.isArray(e))return"list";switch(typeof e){case"number":return"number";case"boolean":return"boolean";case"string":return"string";default:return"object"}}function zd(e,t){if(typeof e!="string"||e.trim()==="")return{ok:!1,reason:"empty"};const n=wr(e);try{const o=Vm(n)?Sd.evaluatePipeExpression(n,t??{},{skipCache:!0}):Sd.evaluateExpression(n,t??{},{skipCache:!0});return{ok:!0,value:o,type:tv(o)}}catch(o){return{ok:!1,reason:o instanceof Error?o.message:String(o)}}}function Nd(e,t){const n=Array.isArray(e?.data_sources)?e.data_sources:[],o=[];for(const r of n){const s=r?.id;if(typeof s!="string"||s.length===0)continue;const{value:a}=rs(r,t?.sampleData),l=typeof r.label_key=="string"?r.label_key:void 0;o.push({id:s,sample:a,labelKey:l})}return o}function Md(e,t){const n=[];t?.sampleGlobal&&typeof t.sampleGlobal=="object"&&n.push({scope:"_global",tree:t.sampleGlobal});const o={},r={},s={},a=(l,d)=>{if(!(!d||typeof d!="object"||Array.isArray(d)))for(const[c,p]of Object.entries(d))if(p&&typeof p=="object"&&!Array.isArray(p)){const f=l[c]&&typeof l[c]=="object"&&!Array.isArray(l[c])?l[c]:l[c]={};a(f,p)}else c in l||(l[c]=p)};for(const l of t?.states?.groups??[])for(const d of l.items??[]){const c=d.initialState;c?.local&&a(o,c.local),c?.query&&a(r,c.query),c?.route&&a(s,c.route)}return Object.keys(o).length&&n.push({scope:"_local",tree:o}),Object.keys(r).length&&n.push({scope:"query",tree:r}),Object.keys(s).length&&n.push({scope:"route",tree:s}),e?.computed&&typeof e.computed=="object"&&!Array.isArray(e.computed)&&n.push({scope:"_computed",tree:e.computed}),n}function Ld(e,t){const n={};for(const r of t)r.scope!=="_computed"&&(n[r.scope]=r.tree);const o={};for(const[r,s]of Object.entries(e)){if(typeof s!="string"){o[r]=s;continue}const a=zd(s,n);o[r]=a.ok?a.value:s}return o}function nv(e,t){const n=Nd(e,t),o=Md(e,t),r={};for(const s of n)s.sample!==void 0&&(r[s.id]=s.sample);for(const s of o)s.scope==="_computed"?r[s.scope]=Ld(s.tree,o):r[s.scope]=s.tree;return r}function Pd(e){const{raw:t,spec:n,evaluateComputed:o}=e;return u.useMemo(()=>{const r=Nd(t,n),s=Md(t,n);if(o){const a=s.findIndex(l=>l.scope==="_computed");if(a>=0){const l=Ld(s[a].tree,s);s[a]={scope:"_computed",tree:l}}}return Ki({dataSources:r,states:s,spec:n??void 0})},[t,n,o])}function ov(e){const{raw:t,spec:n,pageType:o}=e;return u.useMemo(()=>{const r=Array.isArray(t?.data_sources)?t.data_sources:[],s=[];for(const d of r){const c=d?.id;if(typeof c!="string"||c.length===0)continue;const{value:p}=rs(d,n?.sampleData),f=typeof d.label_key=="string"?d.label_key:void 0;s.push({id:c,sample:p,labelKey:f})}const a=[];n?.sampleGlobal&&typeof n.sampleGlobal=="object"&&a.push({scope:"_global",tree:n.sampleGlobal}),t?.computed&&typeof t.computed=="object"&&!Array.isArray(t.computed)&&a.push({scope:"_computed",tree:t.computed});const l=Ki({dataSources:s,states:a,spec:n??void 0});if(typeof o=="string"&&o!=="")for(const d of["title","description"])l.push({expression:`{{_seo.${o}.${d}}}`,source:"_seo",sourceId:"_seo",path:`${o}.${d}`,shape:"scalar",preview:""});return l},[t,n,o])}function Od(e,t){const n=[],o=new Set,r=s=>{for(const a of s??[]){if(a.kind==="route"&&!a.isRedirect&&typeof a.path=="string"&&a.path.startsWith("/")&&!o.has(a.path)){o.add(a.path);const l=a.label.startsWith("$t:")?a.label.slice(3):a.label,d=a.label.startsWith("$t:")?t(l):l,c=d&&d!==l&&!d.startsWith("$t:")?d:"";n.push({value:a.path,label:c?`${c} (${a.path})`:a.path})}r(a.children)}};return r(e),n}function Bd(e){const t=Array.isArray(e?.data_sources)?e.data_sources:[],n=[];for(const o of t){const r=o?.id;typeof r=="string"&&r.length>0&&n.push({value:r,label:r})}return n}function as(e,t){const n=typeof e.id=="string"?e.id:"",o=typeof e.label_key=="string"?e.label_key:"";if(!o)return null;const r=o.startsWith("$t:")?o.slice(3):o,s=t(r);return s&&s!==r&&!s.startsWith("$t:")&&s!==n?s:null}function ls(e,t){const n=e.__source;if(!n||typeof n!="object"||Array.isArray(n))return null;const o=n;if(o.kind!=="extension")return null;const r=o.extensionSourceType==="plugin"?t("layout_editor.data_sources.source.plugin"):t("layout_editor.data_sources.source.module"),s=typeof o.extensionIdentifier=="string"?o.extensionIdentifier:"",a=typeof o.extensionName=="string"?o.extensionName:"",l=a&&a!==s?`${a} (${s})`:s;return l?`${r}: ${l}`:r}function rv(e,t,n){const o=Array.isArray(e?.data_sources)?e.data_sources:[],r=[],s=new Set;for(const a of o){const l=a?.id;typeof l!="string"||l.length===0||s.has(l)||(s.add(l),r.push({id:l,friendly:as(a,t),source:ls(a,n)}))}return r}function Wd(e){const t=e?.states?.groups??[],n=new Set;for(const o of t)for(const r of o.items??[]){for(const s of Object.keys(r.initialState?.local??{}))n.add(s);for(const s of Object.keys(r.initialState?.global??{}))n.add(s)}return Array.from(n).map(o=>({value:o,label:o}))}function iv(e,t){const n=Array.isArray(e?.modals)?e.modals:[],o=[],r=new Set;for(const s of n){const a=s?.id;typeof a!="string"||a.length===0||r.has(a)||(r.add(a),o.push({value:a,label:sv(s,a,t)}))}return o}function sv(e,t,n){const r=e?.meta?.editor_label;if(typeof r=="string"&&r.length>0)return jd(r,n);const s=e?.title;return typeof s=="string"&&s.length>0?jd(s,n):t}function jd(e,t){if(e.startsWith("$t:")){const n=e.slice(3),o=t?t(n):n;return o&&o!==n?o:n}return e}const Hd=mo("ActionRecipeEngine"),av={api:"apiCall",nav:"navigate",showToast:"toast",setLocalState:"setState"},lv=new Set(["comment"]);function ko(e){if(!e||typeof e!="object")return[];const t=[];for(const[n,o]of Object.entries(e)){if(lv.has(n)||!o||typeof o!="object")continue;const r=o,s=r.build&&typeof r.build=="object"?r.build:typeof r.handler=="string"?{handler:r.handler}:void 0;!s||typeof s.handler!="string"||s.handler.length===0||t.push({id:n,label:typeof r.label=="string"?r.label:void 0,params:Array.isArray(r.params)?r.params:[],build:s})}return t}function on(e){const t=/^\{\{\s*([\w.]+)\s*\}\}$/.exec(e);return t?t[1]:null}const kr="...";function dv(e,t){return e.replace(/\{\{\s*([\w.]+)\s*\}\}/g,(n,o)=>{const r=t[o];return r==null?"":String(r)})}function ds(e,t){if(typeof e=="string"){const n=on(e);return n!==null?n in t?t[n]:void 0:e.includes("{{")?dv(e,t):e}if(Array.isArray(e))return e.map(n=>ds(n,t)).filter(n=>n!==void 0);if(e&&typeof e=="object"){const n={};for(const[o,r]of Object.entries(e)){if(o===kr&&typeof r=="string"){const d=on(r),c=d!==null?t[d]:void 0;if(c&&typeof c=="object"&&!Array.isArray(c))for(const[p,f]of Object.entries(c))f===void 0||p===""||(n[p]=f);continue}const s=ds(r,t);if(s===void 0||Array.isArray(s)&&s.length===0&&(o==="onSuccess"||o==="onError"))continue;const a=on(o),l=a!==null?a in t?String(t[a]):null:o;l===null||l===""||s&&typeof s=="object"&&!Array.isArray(s)&&Object.keys(s).length===0||(n[l]=s)}return n}return e}function cv(e){const t=e.handler;if(typeof t!="string")return e;const n=av[t];if(n)return Hd.warn(`action recipe used forbidden handler "${t}" — corrected to "${n}" (core handler rules)`),{...e,handler:n};if(t==="apiCall"||t==="navigate"){const o=e.params;if(o&&typeof o=="object")for(const r of["target","onSuccess","onError"])r in o&&Hd.warn(`action recipe build placed "${r}" inside params for handler "${t}" — should be top-level (core handler rules)`)}return e}function Sr(e,t){const n=ds(e.build,t);if(typeof n.handler!="string"&&e.build.handler.includes("{{")&&(n.handler=e.build.handler),e.build.handler.includes("{{")){const o=new Set(e.params.filter(r=>r.required).map(r=>r.key));o.size>0&&Fd(e.build,n,o)}return cv(n)}function Fd(e,t,n){if(!e||typeof e!="object"||Array.isArray(e)||!t||typeof t!="object"||Array.isArray(t))return;const o=e,r=t;for(const[s,a]of Object.entries(o))if(s!=="handler"){if(typeof a=="string"){const l=on(a);l!==null&&n.has(l)&&!(s in r)&&(r[s]=a)}else if(a&&typeof a=="object"){if(!(s in r)||typeof r[s]!="object"||r[s]===null)if(JSON.stringify(a).includes("{{"))r[s]={};else continue;Fd(a,r[s],n)}}}function uv(e,t){if(!e||typeof e!="object")return null;const n=e.handler;if(typeof n!="string")return null;let o=null,r=-1;for(const s of t){const a=s.build.handler.includes("{{");if(!a&&s.build.handler!==n||a&&!pv(s.build,e))continue;const l=fv(s.build,e);if(l===null)continue;const d=Object.keys(l).length;d>r&&(r=d,o={recipeId:s.id,values:l})}return o}function pv(e,t){if(typeof t.handler=="string"&&t.handler===e.handler)return!0;const n=e.params;if(!n||typeof n!="object")return!1;const o=t.params;if(!o||typeof o!="object")return!1;const r=o,s=Object.entries(n).filter(([,a])=>typeof a=="string"&&on(a)!==null);return s.length===0?!1:s.every(([a])=>a in r)}function fv(e,t){const n={},o=(r,s)=>{if(typeof r=="string"){const a=on(r);return a!==null?(n[a]=s,!0):r.includes("{{")?typeof s=="string":r===s}if(Array.isArray(r))return Array.isArray(s);if(r&&typeof r=="object"){if(!s||typeof s!="object"||Array.isArray(s))return!1;const a=s,l=r[kr],d=typeof l=="string"?on(l):null,c=new Set(Object.keys(r).filter(p=>p!==kr));for(const[p,f]of Object.entries(r))if(p!==kr){if(typeof f=="string"&&on(f)!==null){const b=on(f);p in a&&(n[b]=a[p]);continue}if(!(p in a)){if(p==="onSuccess"||p==="onError"||p==="params"||p==="identity_target")continue;return!1}if(!o(f,a[p]))return!1}if(d!==null){const p={};for(const[f,b]of Object.entries(a))c.has(f)||(p[f]=b);Object.keys(p).length>0&&(n[d]=p)}return!0}return r===s};return o(e,t)?n:null}function Yn(e,t){const n=typeof e?.handler=="string"?e.handler:"",o=uv(e,t);return o?{kind:"preset",recipeId:o.recipeId,values:o.values,handler:n}:{kind:"advanced",handler:n}}function Kd(e,t,n){const o=e?.label,r=o?n?n(o):o:"",s=[],a=e?.params??[];for(const l of a){if(l.advanced||l.widget==="action-list")continue;const d=t[l.key];if(d==null||d==="")continue;const c=gv(d);if(c!==""&&(s.push(c),s.length>=2))break}return s.length===0?r:`${r} (${s.join(", ")})`}function gv(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`[${e.length}]`:e&&typeof e=="object"?"{…}":""}function Vd(e,t){const n={...e};return typeof t=="string"&&t.trim().length>0?n.if=t.trim():delete n.if,n}function cs(e){const t=e?.if;return typeof t=="string"&&t.trim().length>0?t:null}const hv=/^\s*\$t:(custom\.[a-zA-Z0-9._-]+)\s*$/,yv=/^\s*\$t:([a-zA-Z0-9._-]+)\s*$/,bv=/\{\{.*?\}\}/;function Ud(e,t){const n=typeof e=="string"?e:"",o=hv.exec(n);if(o){const a=o[1],l=t?t(a):"";return{customKey:a,binding:!1,paramKey:!1,displayValue:l}}const r=vt(n);if(r&&r.key.startsWith("custom.")){const a=t?t(r.key):"";return{customKey:r.key,binding:!1,paramKey:!0,displayValue:a}}if(bv.test(n))return{customKey:null,binding:!0,paramKey:!1,displayValue:n};const s=yv.exec(n);if(s){const a=s[1],l=t?t(a):"";return{customKey:null,binding:!1,paramKey:!1,displayValue:l&&l!==a?l:""}}return{customKey:null,binding:!1,paramKey:!1,displayValue:n}}function mv(){const{state:e}=Qe(),t=e.templateIdentifier,n=e.locale,o=e.selectedRoute?.layoutName??null,r=u.useCallback(l=>{try{const c=Pt.getInstance().translate(l,{templateId:t,locale:n});return c&&c!==l?c:""}catch{return""}},[t,n]),s=u.useCallback(l=>Ud(l,r),[r]),a=u.useCallback(async(l,d)=>{const c=Ud(l,r);if(c.binding)return{kind:"blocked"};if(c.customKey){if(d===c.displayValue)return{kind:"noop",customKey:c.customKey};const b=await vr(t,c.customKey,n,d);return b.kind==="error"?{kind:"error",message:b.message}:(await tn(t,n),{kind:"updated",customKey:c.customKey})}const p=await qn(t,o,n,d);if(p.kind==="error"||!p.resource)return{kind:"error",message:p.message};const f=p.resource.translation_key;return await tn(t,n),{kind:"created",customKey:f,token:`$t:${f}`}},[t,n,o,r]);return{locale:n,templateIdentifier:t,translate:r,classify:s,commitText:a}}async function us(e,t,n,o,r,s,a,l,d,c){const p=c?Zi(o,c):null,f=!!(p&&p.keyifiable),b=d?d(o):o,g=f?p.chipValue:Rl(b),h=`p${f?p.bindings.length:fr(b).length}`,v=Math.max(0,Math.min(r,g.length)),y=Ul(g,v,h),_=gr(y).replace(/\{\{?p\d+\}?\}/g," ").replace(/\s+/g," ").trim(),w=_.length>0?_:y,k=await qn(e,t,n,w);if(k.kind==="error"||!k.resource)return{kind:"error",message:k.message};const x=k.resource.translation_key,$=An(y),S=k.resource.values??{},C={[n]:y};for(const N of Object.keys(S)){if(N===n)continue;let D=S[N]??"";for(const B of $)D=Xi(D,B);C[N]=D}wo(e,x,C);const T=En(s,a,l);return{kind:"ok",text:`${f?Zl(`$t:${x}`,p):Ql(`$t:${x}`,b)}|${h}=${T}`,key:x}}async function Cr(e,t,n,o,r,s,a){let l=vt(n);if(!l&&typeof n=="string"){const h=/^\s*\$t:(custom\.[A-Za-z0-9._-]+)\s*$/.exec(n);h&&(l={key:h[1],params:[]})}if(!l)return{kind:"error",message:"not a param key"};if(!l.key.startsWith("custom."))return{kind:"error",message:"not a custom param key"};const d=wb(l.params.map(h=>h.name)),c=En(r,s,a),p=`${n.trim()}|${d}=${c}`,f=await cn(e,l.key),b=Gb(l.key)??{},g=new Set([...Object.keys(f?.values??{}),...Object.keys(b),t]);if(g.size===0)return{kind:"error",message:"custom key not found"};const m={};for(const h of g){const v=It(l.key,h)??f?.values?.[h]??"";m[h]=h===t?Ul(v,o,d):Xi(v,d)}return wo(e,l.key,m),{kind:"ok",text:p,paramName:d}}async function So(e,t,n,o){return _r(e,t,n,o),{kind:"ok"}}async function vv(e,t,n){const o=await cn(e,t);if(!o)return{kind:"error",message:"custom key not found"};const r={};for(const[s,a]of Object.entries(o.values??{})){const l=It(t,s)??a;r[s]=n(l)}wo(e,t,r);try{const s=Pt.getInstance();for(const[a,l]of Object.entries(r))s.setTranslationValue(e,a,t,l)}catch{}return{kind:"ok"}}function qd(e,t,n){return vv(e,t,o=>nd(o,n))}function Gd(e,t){if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:e,locale:t}}))}catch{}}async function $r(e,t,n,o){const r=await qd(e,t,n);return Gd(e,o),r}const _v=/^\s*\$t:(custom\.[a-zA-Z0-9._-]+)\s*$/;function xv(e,t){const n=s=>{const a=[],l=/\{\{?(p\d+)\}?\}/g;let d;for(;(d=l.exec(s))!==null;)a.push(d[1]);return a},o=n(e),r=n(t);return o.length!==r.length?!0:o.some((s,a)=>s!==r[a])}function Yd(e){const t=e.text;if(typeof t!="string")return null;const n=_v.exec(t);if(n)return n[1];const o=vt(t);return o&&o.key.startsWith("custom.")?o.key:null}function ps(e){const t={},n=vt(typeof e=="string"?e:"");for(const o of n?.params??[])t[o.name]=Vt(o.expression);return t}function wv(e){return ps(typeof e.text=="string"?e.text:"")}function Xd({customKey:e,templateIdentifier:t,t:n,paramLabels:o,locales:r,onRemoveParam:s}){const a=r??hd(),l=Ft(),d=o??{},[c,p]=u.useState({status:"idle",values:{}}),[f,b]=u.useState(!1),[g,m]=u.useState(!1),[h,v]=u.useState(null),y=u.useRef({});u.useEffect(()=>{let E=!1;if(!e){p({status:"not_a_key",values:{}});return}return p({status:"loading",values:{}}),(async()=>{const A=await cn(t,e);if(E)return;if(!A){p({status:"error",values:{}});return}const N={...A.values??{}};for(const D of Object.keys(N)){const B=It(e,D);B!==void 0&&(N[D]=B)}for(const D of a){const B=It(e,D);B!==void 0&&(N[D]=B)}y.current={...N},p({status:"loaded",id:A.id,lockVersion:A.lock_version,values:N})})(),()=>{E=!0}},[e,t]),u.useEffect(()=>{if(typeof window>"u"||!e)return;const E=A=>{const N=A.detail;N?.templateIdentifier&&N.templateIdentifier!==t||p(D=>{if(D.status!=="loaded")return D;let B=!1;const M={...D.values};for(const O of Object.keys(M)){const z=It(e,O);z!==void 0&&z!==M[O]&&(M[O]=z,B=!0)}return B?(y.current={...y.current,...M},{...D,values:M}):D})};return window.addEventListener(kt,E),()=>window.removeEventListener(kt,E)},[e,t]);const _=u.useCallback((E,A)=>{p(N=>{const D=N.values[E]??"",B={...N,values:{...N.values,[E]:A}};return e&&xv(D,A)&&(_r(t,e,E,A),y.current={...y.current,[E]:A},l?.markDirty?.(),Gd(t,E)),B})},[e,t,l]),w=u.useCallback(E=>{p(A=>{const N={};for(const[D,B]of Object.entries(A.values))N[D]=nd(B,E);return y.current={...N},{...A,values:N}}),s?.(E)},[s]),k=u.useMemo(()=>[...Object.values(c.values),...Object.values(y.current)].some(A=>An(A).length>0),[c.values]),x=u.useRef(null),$=u.useCallback(()=>{m(!0),x.current&&clearTimeout(x.current),x.current=setTimeout(()=>m(!1),1500)},[]);u.useEffect(()=>()=>{x.current&&clearTimeout(x.current)},[]);const S=u.useCallback(async()=>{if(m(!1),c.status!=="loaded"||c.id===void 0)return;const E=y.current;for(const[N,D]of Object.entries(c.values)){const B=E[N]??"";if(k){const M=An(B);if(M.length===0)continue;const O=An(D);if(!(M.length===O.length&&M.every((H,P)=>H===O[P]))){v(n("layout_editor.translation.placeholder_mismatch"));return}continue}if(Yi(B)&&!Tb(B,D)){v(n("layout_editor.translation.token_mismatch"));return}}if(b(!0),v(null),k){wo(t,e??"",c.values),y.current={...c.values},l?.markDirty?.(),Et({op:"translation_field_update",translationKey:e,changedLocales:Object.keys(c.values),timestamp:Date.now()}),await new Promise(N=>setTimeout(N,0)),b(!1),$();return}const A=`/api/admin/templates/${encodeURIComponent(t)}/custom-translations/${c.id}`;try{const N=await fetch(A,{method:"PUT",credentials:"same-origin",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({values:c.values,expected_lock_version:c.lockVersion??0})}),D=await N.json().catch(()=>null);if(N.status===409){v(n("layout_editor.translation.conflict"));return}if(!N.ok){v(D?.message??n("layout_editor.translation.save_failed"));return}const B=typeof D?.data?.lock_version=="number"?D.data.lock_version:(c.lockVersion??0)+1;p(M=>({...M,lockVersion:B})),y.current={...c.values},await tn(t),Et({op:"translation_field_update",translationKey:e,changedLocales:Object.keys(c.values),timestamp:Date.now()}),$()}catch(N){v(N instanceof Error?N.message:n("layout_editor.translation.save_failed"))}finally{b(!1)}},[c,t,e,n]);if(c.status==="not_a_key"||!e)return i.jsx("div",{"data-testid":"g7le-translation-not-a-key",style:fs,children:n("layout_editor.translation.not_a_key")});if(c.status==="loading"||c.status==="idle")return i.jsx("div",{"data-testid":"g7le-translation-loading",style:fs,children:n("layout_editor.translation.loading")});if(c.status==="error")return i.jsx("div",{"data-testid":"g7le-translation-error",style:fs,children:n("layout_editor.translation.load_failed")});const C=new Set([...a,...Object.keys(c.values)]),T=Array.from(C);return i.jsxs("div",{"data-testid":"g7le-translation-field",style:{display:"flex",flexDirection:"column",gap:8},children:[i.jsxs("div",{"data-testid":"g7le-translation-key",style:kv,children:[n("layout_editor.translation.key_label"),": ",i.jsx("code",{style:Sv,children:e})]}),T.map(E=>{const A=c.values[E]??"",N=A.trim().length===0;return i.jsxs("div",{className:"g7le-translation-row","data-testid":`g7le-translation-row-${E}`,style:Cv,children:[i.jsxs("label",{htmlFor:`g7le-translation-input-${E}`,style:{fontSize:12,color:"#475569",minWidth:72,display:"inline-flex",alignItems:"center",gap:4},children:[Gn(E,n),N&&i.jsx("span",{"data-testid":`g7le-translation-missing-${E}`,style:$v,children:n("layout_editor.translation.needs_translation")})]}),k?i.jsx("div",{style:{flex:1},"data-testid":`g7le-translation-chip-${E}`,children:i.jsx(xr,{value:A,onChange:D=>_(E,D),t:n,paramLabels:d,testIdSuffix:E,onRemoveChip:s?w:void 0})}):i.jsx("input",{id:`g7le-translation-input-${E}`,type:"text","data-testid":`g7le-translation-input-${E}`,value:A,placeholder:N?n("layout_editor.translation.needs_translation"):"",onChange:D=>_(E,D.currentTarget.value),onBlur:S,style:{flex:1,padding:"4px 8px",fontSize:13,border:"1px solid #cbd5e1",borderRadius:4,color:N?"#94a3b8":"#0f172a"}})]},E)}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("button",{type:"button","data-testid":"g7le-translation-save",disabled:f,onClick:S,style:Ev,children:n(f?"layout_editor.translation.saving":"layout_editor.translation.save")}),g&&!f&&i.jsxs("span",{"data-testid":"g7le-translation-saved",style:{fontSize:11,color:"#16a34a",display:"inline-flex",alignItems:"center",gap:4},children:["✓ ",n("layout_editor.translation.saved")]}),h&&i.jsx("span",{"data-testid":"g7le-translation-save-error",style:{fontSize:11,color:"#dc2626"},children:h})]})]})}const fs={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},kv={fontSize:12,color:"#475569"},Sv={fontSize:11,background:"#f1f5f9",padding:"1px 4px",borderRadius:3,color:"#0f172a"},Cv={display:"flex",alignItems:"center",gap:8},$v={fontSize:10,color:"#b45309",background:"#fef3c7",padding:"0 4px",borderRadius:3},Ev={padding:"6px 12px",fontSize:12,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"};function Xn({anchorRef:e,open:t,onClose:n,children:o,placement:r="bottom",minWidth:s=240,maxWidth:a=360,margin:l=8,testid:d}){const c=u.useRef(null),[p,f]=u.useState(null),b=u.useCallback(()=>{const m=e.current,h=c.current;if(!m||!h)return;const v=m.getBoundingClientRect(),y=window.innerWidth,_=window.innerHeight,w=h.getBoundingClientRect(),k=Math.min(Math.max(w.width,s),a),x=w.height;let $=v.left;$+k+l>y&&($=v.right-k),$=Math.min(Math.max($,l),y-k-l);const S=_-v.bottom-l,C=v.top-l;let T,E;const A=r==="bottom",N=S>=Math.min(x,160),D=C>=Math.min(x,160);A&&N||A&&!D?(T=v.bottom+4,E=S):!A&&D||D?(T=v.top-4-Math.min(x,C),E=C):S>=C?(T=v.bottom+4,E=S):(T=l,E=C),f({left:$,top:T,maxHeight:Math.max(E,120)})},[e,r,s,a,l]);if(u.useLayoutEffect(()=>{if(!t){f(null);return}b()},[t,b]),u.useEffect(()=>{if(!t)return;const m=()=>b();window.addEventListener("resize",m),window.addEventListener("scroll",m,!0);const h=y=>{const _=c.current,w=e.current,k=y.target;_?.contains(k)||w?.contains(k)||n()},v=y=>{y.key==="Escape"&&n()};return document.addEventListener("pointerdown",h,!0),document.addEventListener("keydown",v),()=>{window.removeEventListener("resize",m),window.removeEventListener("scroll",m,!0),document.removeEventListener("pointerdown",h,!0),document.removeEventListener("keydown",v)}},[t,b,n,e]),!t)return null;const g={...Iv,minWidth:s,maxWidth:`min(${a}px, calc(100vw - ${l*2}px))`,...p?{left:p.left,top:p.top,maxHeight:p.maxHeight,visibility:"visible"}:{left:-9999,top:-9999,visibility:"hidden"}};return i.jsx("div",{ref:c,"data-testid":d,style:g,role:"dialog",children:o})}const Iv={position:"fixed",zIndex:1e3,background:"#fff",border:"1px solid #cbd5e1",borderRadius:8,boxShadow:"0 4px 16px rgba(0,0,0,0.14)",padding:6,overflowY:"auto",boxSizing:"border-box"};function Jd(e,t,n){if(!t)return n;const o=e(t);return!o||o===t||o.startsWith("$t:")?n:o}function $t({candidates:e,t,onSelect:n,testIdSuffix:o,defaultOpen:r=!1,floating:s=!0}){const[a,l]=u.useState(r),[d,c]=u.useState(""),p=u.useRef(null),f=u.useMemo(()=>Ui(e,"scalar").map(h=>({...h,resolvedLabel:Jd(t,h.labelKey,h.path||h.sourceId)})),[e,t]),b=u.useMemo(()=>qi(f,d),[f,d]),g=i.jsxs(i.Fragment,{children:[i.jsx("input",{type:"text",autoFocus:!0,"data-testid":`g7le-inline-binding-search-input-${o}`,value:d,placeholder:t("layout_editor.inline_binding.search_placeholder"),onChange:m=>c(m.target.value),style:zv}),i.jsx("div",{style:Nv,children:b.length===0?i.jsx("div",{style:Mv,children:t("layout_editor.inline_binding.no_results")}):b.map(m=>i.jsxs("button",{type:"button","data-testid":`g7le-inline-binding-candidate-${m.expression}`,onClick:()=>{n(m),l(!1),c("")},style:Lv,children:[i.jsxs("span",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start"},children:[i.jsx("span",{style:{fontSize:12},children:m.resolvedLabel}),i.jsxs("span",{style:Pv,children:[Jd(t,m.groupLabelKey,m.sourceId)," · ",m.path||m.sourceId]})]}),i.jsx("span",{style:Ov,children:m.preview})]},m.expression))})]});return i.jsxs("div",{style:s?Dv:{marginTop:4},children:[i.jsx("button",{ref:p,type:"button","data-testid":`g7le-inline-binding-search-toggle-${o}`,onClick:()=>l(m=>!m),title:t("layout_editor.inline_binding.search"),"aria-label":t("layout_editor.inline_binding.search"),"aria-expanded":a,style:Av,children:"🔍"}),s?i.jsx(Xn,{anchorRef:p,open:a,onClose:()=>l(!1),testid:`g7le-inline-binding-picker-${o}`,children:g}):a&&i.jsx("div",{"data-testid":`g7le-inline-binding-picker-${o}`,style:Tv,children:g})]})}const Av={fontSize:13,lineHeight:1,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#334155",padding:"4px 8px",cursor:"pointer",textAlign:"center",whiteSpace:"nowrap"},Tv={marginTop:4,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",padding:6},Dv={display:"inline-block"},zv={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},Nv={marginTop:4,maxHeight:200,overflowY:"auto",display:"flex",flexDirection:"column",gap:2},Mv={fontSize:11,color:"#94a3b8",padding:"8px 0",textAlign:"center"},Lv={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,border:"none",background:"transparent",cursor:"pointer",padding:"6px 8px",borderRadius:4,textAlign:"left"},Pv={fontSize:10,color:"#94a3b8"},Ov={fontSize:10,color:"#64748b",fontFamily:"monospace",whiteSpace:"nowrap"},Bv=["$localized"];function Jn(e){const t=e.trim();if(!t.startsWith("{{")||!t.endsWith("}}")||t.length<4)return null;let n=0;for(let o=0;oun(n).decomposed)}function Co(e,t,n,o){switch(e.kind){case"leaf":Qd(e.text,t,n,o);return;case"conditional":Co(e.then,t,n,o),o.push({kind:"ellipsis",text:"⋯"});return;case"fallback":Co(e.primary,t,n,o);return;case"concat":e.parts.forEach(r=>Co(r,t,n,o));return;case"raw":default:o.push({kind:"text",text:e.source});return}}function Qd(e,t,n,o){const r=e.trim();if(/^\{\{([\s\S]*)\}\}$/.exec(r)&&!r.slice(2,-2).includes("}}")){o.push({kind:"chip",text:n(r)});return}if(r.startsWith("$t:")){const a=r.slice(3).split("|")[0];o.push({kind:"text",text:t(a)||a});return}for(const a of e.split(/(\{\{(?:[^}]|\}(?!\}))*\}\})/g))a!==""&&(/^\{\{[\s\S]*\}\}$/.test(a)?o.push({kind:"chip",text:n(a)}):o.push({kind:"text",text:a}))}function gs(e,t,n){const o=[];if(typeof e!="string"||e==="")return o;if(Jn(e)===null&&/\{\{/.test(e)){for(const a of e.split(/(\{\{(?:[^}]|\}(?!\}))*\}\})/g))if(!(a===void 0||a===""))if(/^\{\{[\s\S]*\}\}$/.test(a)){const l=un(a);Co(l.node,t,n,o)}else Qd(a,t,n,o);return o}const s=un(e);return Co(s.node,t,n,o),o}function Wv(e){if(typeof e!="string"||e.trim()==="")return"empty";const t=e.trim();if(Jn(t)===null)return"simple";const n=un(e);return n.node.kind==="leaf"?"simple":n.decomposed?"expression":"raw"}function un(e){const t=typeof e=="string"?e:"",n=t.trim();if(n==="")return{node:{kind:"leaf",text:t},decomposed:!1,original:t};const o=Jn(n);if(o===null)return{node:{kind:"leaf",text:t},decomposed:!1,original:t};let r;try{r=Yv(o)}catch{r=null}if(r===null)return{node:{kind:"raw",source:o},decomposed:!1,original:t};if(r.kind==="leaf"||r.kind==="raw")return{node:r,decomposed:!1,original:t};if(r.kind==="fallback"&&r.op==="??"&&jv(r.primary)&&Hv(r.fallback))return{node:{kind:"leaf",text:t},decomposed:!1,original:t};const s=Zn(r,!0);return Rv(o,s)?{node:r,decomposed:!0,original:t}:{node:{kind:"raw",source:o},decomposed:!1,original:t}}function Zn(e,t=!1){const n=ec(e);return t?n:e.kind==="leaf"?e.text:`{{${n}}}`}function $o(e){return Zn({kind:"conditional",condition:{kind:"simple",left:"",op:"truthy",right:""},then:{kind:"leaf",text:typeof e=="string"?e:""},else:{kind:"leaf",text:""}},!1)}function hs(e){return Zn({kind:"fallback",op:"??",primary:{kind:"leaf",text:typeof e=="string"?e:""},fallback:{kind:"leaf",text:""}},!1)}function Eo(e){switch(e.kind){case"leaf":return e.text;case"conditional":return Eo(e.then);case"fallback":return Eo(e.primary);case"concat":return e.parts.map(Eo).join("");case"raw":default:return e.kind==="raw"?`{{${e.source}}}`:""}}function WM(e){return e}function Er(e){if(typeof e!="string"||e.trim()==="")return"";if(Jn(e)===null&&/\{\{/.test(e)){for(const n of e.split(/(\{\{(?:[^}]|\}(?!\}))*\}\})/g))if(!(n===void 0||n===""))return/^\{\{[\s\S]*\}\}$/.test(n)?Eo(un(n).node):n;return""}return Eo(un(e).node)}function jv(e){if(e.kind!=="leaf")return!1;const t=/^\{\{([\s\S]*)\}\}$/.exec(e.text.trim());return t?Qn(t[1].trim()):!1}function Hv(e){if(e.kind!=="leaf")return!1;const t=e.text.trim();return!(/\{\{/.test(t)||t.startsWith("$t:"))}function Ir(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}function Fv(e){const t=[];let n=0,o=0;const r=e.length;for(;on&&t.push(Ir(e.slice(n,o)));let s=o+2;for(;s=r)break;const a=e.slice(o+2,s).trim();t.push(a),o=s+2,n=o;continue}o++}return nIo(t,"concat")).join(" + ");case"fallback":return`${Io(e.primary,"fallback")} ${e.op} ${Io(e.fallback,"fallback")}`;case"conditional":return`${Vv(e.condition)} ? ${Io(e.then,"conditional")} : ${Io(e.else,"conditional")}`;default:return""}}function Io(e,t){const n=ec(e);return e.kind==="leaf"||e.kind==="raw"?n:e.kind==="conditional"?t==="conditional"?n:`(${n})`:e.kind==="fallback"?t==="concat"?`(${n})`:n:(e.kind==="concat",n)}const qv=["===","!==","??","||","&&","==","!=",">=","<="];function tc(e){const t=[];let n=0;const o=e.length;for(;n=o)throw new Error("unterminated-binding-in-string");d+=e.slice(l,c+2),l=c+2;continue}if(e[l]===a){d+=a,l++;break}if(a==="`"&&e[l]==="$"&&e[l+1]==="{")throw new Error("template-literal-interpolation-unsupported");d+=e[l],l++}if(l>o||d[d.length-1]!==a)throw new Error("unterminated-string");t.push({kind:"string",value:d,start:n,end:l}),n=l;continue}if(r==="{"&&e[n+1]==="{"){let a=n+2;for(;a"||r==="<"){t.push({kind:"op",value:r,start:n,end:n+1}),n++;continue}if(r==="!"){t.push({kind:"op",value:"!",start:n,end:n+1}),n++;continue}if(r==="("){t.push({kind:"lparen",value:"(",start:n,end:n+1}),n++;continue}if(r===")"){t.push({kind:"rparen",value:")",start:n,end:n+1}),n++;continue}if(r==="["){t.push({kind:"lbracket",value:"[",start:n,end:n+1}),n++;continue}if(r==="]"){t.push({kind:"rbracket",value:"]",start:n,end:n+1}),n++;continue}if(r==="."){t.push({kind:"dot",value:".",start:n,end:n+1}),n++;continue}if(/[0-9]/.test(r)){let a=n;for(;a=n)return"";const o=this.toks[t].start,r=this.toks[n-1].end;return this.src.slice(o,r)}parseFallback(){let t=this.parseConcat(),n=this.peek();for(;n&&n.kind==="op"&&(n.value==="??"||n.value==="||");){const o=n.value;this.next();const r=this.parseConcat();t={kind:"fallback",op:o,primary:t,fallback:r},n=this.peek()}return t}parseConcat(){const t=this.parseUnaryOrPrimary(),n=[t];let o=this.peek();for(;o&&o.kind==="op"&&o.value==="+";)this.next(),n.push(this.parseUnaryOrPrimary()),o=this.peek();return n.length===1?t:{kind:"concat",parts:n}}parseUnaryOrPrimary(){return this.parsePrimary()}parsePrimary(){const t=this.peek();if(!t)throw new Error("unexpected-end");if(t.kind==="lparen"){this.next();const n=this.parseTernary(),o=this.next();if(!o||o.kind!=="rparen")throw new Error("expected-rparen");return n}if(t.kind==="string")return this.next(),{kind:"leaf",text:oc(t.value)};if(t.kind==="tkey")return this.next(),{kind:"leaf",text:t.value};if(t.kind==="binding")return this.next(),{kind:"leaf",text:t.value};if(t.kind==="ident"&&Bv.includes(t.value)&&this.toks[this.pos+1]?.kind==="lparen"){const n=this.tryParsePathWrapperCall(t.value);if(n!==null)return n;throw new Error("path-wrapper-non-simple-arg")}if(t.kind==="ident")return{kind:"leaf",text:`{{${this.parsePath()}}}`};if(t.kind==="number")return this.next(),{kind:"leaf",text:t.value};throw new Error(`unparseable-primary:${t.kind}`)}parsePath(){let t="";const n=this.next();if(!n||n.kind!=="ident")throw new Error("expected-ident");for(t+=n.value;;){const o=this.peek();if(!o)break;if(o.kind==="op"&&o.value==="?"&&this.toks[this.pos+1]?.kind==="dot"){this.next(),this.next();const r=this.next();if(!r||r.kind!=="ident")throw new Error("expected-ident-after-optional");t+="?."+r.value;continue}if(o.kind==="dot"){this.next();const r=this.next();if(!r||r.kind!=="ident")throw new Error("expected-ident-after-dot");t+="."+r.value;continue}if(o.kind==="lbracket"){this.next();const r=this.next(),s=this.next();if(!s||s.kind!=="rbracket")throw new Error("expected-rbracket");if(r&&(r.kind==="number"||r.kind==="string")){t+=`[${r.value}]`;continue}throw new Error("non-literal-index")}if(o.kind==="lparen")throw new Error("call-expression");break}return t}tryParsePathWrapperCall(t){const n=this.pos;this.next();const o=this.next();if(!o||o.kind!=="lparen")return this.pos=n,null;let r;try{if(this.peek()?.kind!=="ident")return this.pos=n,null;r=this.parsePath()}catch{return this.pos=n,null}const s=this.next();return!s||s.kind!=="rparen"?(this.pos=n,null):{kind:"leaf",text:`{{${t}(${r})}}`}}}function Yv(e){return new Gv(e).parse()}const Xv=["===","!==","==","!=",">=","<=",">","<"];function Jv(e,t){const n=e.trim();if(n==="")return{kind:"raw",source:n};if(n===Rd)return{kind:"simple",left:"",op:"truthy",right:""};if(n.startsWith("!")){const s=n.slice(1).trim(),a=nc(s);return Qn(a)?{kind:"simple",left:a,op:"falsy",right:""}:{kind:"raw",source:n}}const o=Zv(n);if(o){const{left:s,op:a,right:l}=o,d=s.trim(),c=l.trim();return Qn(d)&&(c==="''"||c==='""')?{kind:"simple",left:d,op:a,right:""}:Qn(d)&&Qv(c)?{kind:"simple",left:d,op:a,right:c}:{kind:"raw",source:n}}const r=nc(n);return Qn(r)?{kind:"simple",left:r,op:"truthy",right:""}:{kind:"raw",source:n}}function Zv(e){let t=0,n=null;for(let o=0;o=o||!/[A-Za-z_$]/.test(t[n]))return!1;for(n++;n=o||!/[A-Za-z_$]/.test(t[n]))return!1;for(n++;n=2&&(t[0]==="'"||t[0]==='"'||t[0]==="`")?t.slice(1,-1).replace(/\\(['"`\\])/g,"$1"):t}function Rv(e,t){try{return Ar(e)===Ar(t)}catch{return!1}}function Ar(e){const t=Jn(e);return t!==null?Ar(t):tc(e).map(o=>{if(o.kind==="string")return`S:${oc(o.value)}`;if(o.kind==="binding"){const r=/^\{\{([\s\S]*)\}\}$/.exec(o.value);return`B:${r?Ar(r[1].trim()):o.value.replace(/\s+/g,"")}`}return o.kind==="tkey"?`S:${o.value}`:o.kind==="op"?`O:${o.value}`:o.kind==="ident"||o.kind==="number"?`I:${o.value}`:o.kind==="dot"?".":o.kind==="lbracket"?"[":o.kind==="rbracket"?"]":o.kind==="lparen"||o.kind==="rparen"?"":`X:${o.value}`}).join("")}function Rn({active:e,testid:t}){return i.jsx("div",{"data-testid":t,"data-active":e?"true":"false","aria-hidden":"true",style:e?t_:e_})}const e_={height:0,margin:0,transition:"height 80ms"},t_={height:3,margin:"1px 0",borderRadius:2,background:"#2563eb",boxShadow:"0 0 0 1px #93c5fd"};function ys(e){const{length:t,onMove:n,canDrag:o,canDropAt:r}=e,[s,a]=u.useState(null),[l,d]=u.useState(null),c=u.useCallback(m=>{o&&!o(m)||(a(m),d(m))},[o]),p=u.useCallback(()=>{a(null),d(null)},[]),f=u.useCallback((m,h)=>{if(s===null)return;const v=h==="before"?m:m+1;if(r&&!r(s,v)){d(null);return}d(v)},[s,r]),b=u.useCallback(()=>{if(s!==null&&l!==null){const m=l>s?l-1:l;m!==s&&(!r||r(s,l))&&n(s,m)}a(null),d(null)},[s,l,n,r]),g=u.useCallback(m=>s!==null&&l===m&&m<=t,[s,l,t]);return{dragIndex:s,dropIndex:l,dragging:s!==null,onDragStart:c,onDragEnd:p,onDragOverItem:f,onDrop:b,isDropTarget:g}}const n_={text:"",expression:"{{false ? '' : ''}}",fallback:"{{'' ?? ''}}",data:""};function rc(e,t){const n=In(e);let o=t;const r=n.map(s=>({id:o++,kind:s.kind==="literal"?"text":"expression",value:s.raw}));return r.length===0&&r.push({id:o++,kind:"text",value:""}),{segs:r,nextSeq:o}}function bs({value:e,onChange:t,t:n,candidates:o,testidPrefix:r="g7le-seg-value",renderLeafInput:s}){const a=u.useRef(0),l=u.useRef(e),d=u.useMemo(()=>{const w=rc(e,a.current);return a.current=w.nextSeq,w.segs},[]),[c,p]=u.useState(d),[f,b]=u.useState(!1);if(e!==l.current){l.current=e;const w=c.map(k=>k.value).join("");if(e!==w){const k=rc(e,a.current);a.current=k.nextSeq,p(k.segs)}}const g=u.useCallback(w=>{p(w);const k=w.map(x=>x.value).join("");l.current=k,t(k)},[t]),m=u.useCallback((w,k)=>{g(c.map(x=>x.id===w?{...x,value:k??""}:x))},[c,g]),h=u.useCallback(w=>{const k=c.filter(x=>x.id!==w);g(k.length>0?k:[{id:a.current++,kind:"text",value:""}])},[c,g]),v=u.useCallback(w=>{g([...c,{id:a.current++,kind:w,value:n_[w]}])},[c,g]),y=u.useCallback((w,k)=>{if(w===k||w<0||k<0||w>=c.length||k>=c.length)return;const x=c.slice(),[$]=x.splice(w,1);x.splice(k,0,$),g(x)},[c,g]),_=ys({length:c.length,onMove:y});return i.jsxs("div",{"data-testid":r,style:i_,children:[i.jsx("div",{style:s_,children:n("layout_editor.value_tree.segmented_hint")}),c.map((w,k)=>i.jsxs(u.Fragment,{children:[i.jsx(Rn,{active:_.isDropTarget(k),testid:`${r}-dropline-${k}`}),i.jsx(r_,{seg:w,index:k,t:n,candidates:o,testidPrefix:r,renderLeafInput:s,onValueChange:x=>m(w.id,x),onRemove:()=>h(w.id),dragging:_.dragIndex===k,onDragStartCard:()=>_.onDragStart(k),onDragEndCard:_.onDragEnd,onDragOverCard:x=>_.onDragOverItem(k,x),onDropCard:_.onDrop})]},w.id)),i.jsx(Rn,{active:_.isDropTarget(c.length),testid:`${r}-dropline-end`}),i.jsxs("div",{style:p_,"data-testid":`${r}-add-row`,children:[i.jsxs("button",{type:"button","data-testid":`${r}-add-text`,onClick:()=>v("text"),style:Tr,children:["+ ",n("layout_editor.value_tree.segment.text")]}),i.jsxs("button",{type:"button","data-testid":`${r}-add-expression`,onClick:()=>v("expression"),style:Tr,children:["+ ",n("layout_editor.value_tree.segment.expression")]}),i.jsxs("button",{type:"button","data-testid":`${r}-add-fallback`,onClick:()=>v("fallback"),style:Tr,children:["+ ",n("layout_editor.value_tree.segment.fallback")]}),i.jsxs("button",{type:"button","data-testid":`${r}-add-data`,onClick:()=>v("data"),style:Tr,children:["+ ",n("layout_editor.value_tree.segment.data")]})]}),i.jsxs("div",{style:h_,children:[i.jsxs("button",{type:"button","data-testid":`${r}-source-toggle`,"aria-expanded":f,onClick:()=>b(w=>!w),style:y_,children:[""," ",n("layout_editor.value_tree.show_source")," ",f?"▴":"▾"]}),f&&i.jsx("code",{"data-testid":`${r}-source-code`,style:b_,children:c.map(w=>w.value).join("")})]})]})}function o_({t:e,candidates:t,onPick:n,testidPrefix:o}){return!t||t.length===0?i.jsx("div",{"data-testid":`${o}-data-empty`,style:g_,children:e("layout_editor.value_tree.segment.data_no_candidates")}):i.jsxs("div",{"data-testid":`${o}-data-picker`,style:{minWidth:0},children:[i.jsx("div",{style:f_,children:e("layout_editor.value_tree.segment.data_pick_hint")}),i.jsx($t,{candidates:t,t:e,onSelect:r=>{n(En(r.sourceId,r.path,"scalar"))},testIdSuffix:`${o}-data`,defaultOpen:!0,floating:!0})]})}function r_({seg:e,index:t,t:n,candidates:o,testidPrefix:r,renderLeafInput:s,onValueChange:a,onRemove:l,dragging:d,onDragStartCard:c,onDragEndCard:p,onDragOverCard:f,onDropCard:b}){const g=e.kind==="text"?"layout_editor.value_tree.segment.text":e.kind==="data"?"layout_editor.value_tree.segment.data":e.kind==="fallback"?"layout_editor.value_tree.segment.fallback":"layout_editor.value_tree.segment.expression";return i.jsxs("div",{"data-testid":`${r}-card-${t}`,"data-seg-kind":e.kind,style:d?{...ic,opacity:.5}:ic,onDragOver:m=>{m.preventDefault();const h=m.currentTarget.getBoundingClientRect();f(m.clientY{m.preventDefault(),b()},children:[i.jsxs("div",{style:a_,children:[i.jsx("span",{"data-testid":`${r}-drag-${t}`,style:c_,draggable:!0,onDragStart:c,onDragEnd:p,title:n("layout_editor.value_tree.drag_reorder"),"aria-label":n("layout_editor.value_tree.drag_reorder"),role:"button",children:"⠿"}),i.jsx("span",{style:l_,children:n(g)}),i.jsx("button",{type:"button","data-testid":`${r}-remove-${t}`,onClick:l,title:n("layout_editor.value_tree.segment.remove"),"aria-label":n("layout_editor.value_tree.segment.remove"),style:u_,children:"✕"})]}),i.jsx("div",{style:d_,children:e.kind==="data"&&e.value.trim()===""?i.jsx(o_,{t:n,candidates:o,onPick:a,testidPrefix:`${r}-field-${t}`}):s?s({value:e.value,onChange:a,t:n,candidates:o,testidPrefix:`${r}-field-${t}`}):i.jsx(_t,{value:e.value,onChange:a,t:n,candidates:o,testidPrefix:`${r}-field-${t}`,enableExpressionTree:!0,expressionSourceToggle:!1})})]})}const i_={display:"flex",flexDirection:"column",gap:6,width:"100%",minWidth:0},s_={fontSize:11,color:"#64748b"},ic={display:"flex",flexDirection:"column",gap:4,padding:"6px 8px",border:"1px solid #e2e8f0",borderLeft:"3px solid #6366f1",borderRadius:6,background:"#f8fafc",minWidth:0},a_={display:"flex",alignItems:"center",gap:6,minWidth:0},l_={fontSize:10,fontWeight:600,color:"#6366f1",flex:1,minWidth:0},d_={minWidth:0},c_={color:"#94a3b8",cursor:"grab",fontSize:14,userSelect:"none"},u_={border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12,padding:2,flexShrink:0},p_={display:"flex",flexWrap:"wrap",gap:6,marginTop:2},f_={fontSize:11,color:"#64748b",marginBottom:2},g_={fontSize:11,color:"#94a3b8",padding:"4px 0"},Tr={padding:"4px 10px",fontSize:11,border:"1px dashed #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},h_={display:"flex",flexDirection:"column",gap:4,marginTop:2},y_={alignSelf:"flex-start",padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",fontFamily:"monospace"},b_={fontSize:11,background:"#0f172a",color:"#e2e8f0",padding:"6px 8px",borderRadius:4,wordBreak:"break-all",fontFamily:"monospace"},m_=[{value:"truthy",labelKey:"layout_editor.value_tree.cond.op_truthy"},{value:"falsy",labelKey:"layout_editor.value_tree.cond.op_falsy"},{value:"===",labelKey:"layout_editor.value_tree.cond.op_eq"},{value:"!==",labelKey:"layout_editor.value_tree.cond.op_neq"},{value:">",labelKey:"layout_editor.value_tree.cond.op_gt"},{value:"<",labelKey:"layout_editor.value_tree.cond.op_lt"},{value:">=",labelKey:"layout_editor.value_tree.cond.op_gte"},{value:"<=",labelKey:"layout_editor.value_tree.cond.op_lte"}];function sc({node:e,onChange:t,t:n,candidates:o,testidPrefix:r="g7le-value-tree",depth:s=0,showSourceToggle:a=!0,renderLeafInput:l}){const[d,c]=u.useState(!1),p=s===0,f=i.jsx(eo,{node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:l});return p?a?i.jsxs("div",{"data-testid":r,style:lc,children:[f,i.jsxs("div",{style:B_,children:[i.jsxs("button",{type:"button","data-testid":`${r}-source-toggle`,"aria-expanded":d,onClick:()=>c(b=>!b),style:W_,children:[""," ",n("layout_editor.value_tree.show_source")," ",d?"▴":"▾"]}),d&&i.jsx("code",{"data-testid":`${r}-source-code`,style:j_,children:Zn(e,!1)})]})]}):i.jsx("div",{"data-testid":r,style:lc,children:f}):f}function eo({node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a}){switch(e.kind){case"leaf":return i.jsx(bs,{value:e.text,onChange:l=>t({kind:"leaf",text:l}),t:n,candidates:o,testidPrefix:`${r}-leaf`,renderLeafInput:a});case"conditional":return i.jsx(v_,{node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a});case"fallback":return i.jsx(__,{node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a});case"concat":return i.jsx(w_,{node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a});case"raw":default:return i.jsxs("div",{"data-testid":`${r}-raw`,style:H_,children:[i.jsx("code",{style:uc,children:e.source??""}),i.jsxs("span",{style:pc,children:["🔒 ",n("layout_editor.value_tree.raw_code_only")]})]})}}function v_({node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a}){const l=u.useCallback(p=>t({...e,condition:p}),[e,t]),d=u.useCallback(p=>t({...e,then:p}),[e,t]),c=u.useCallback(p=>t({...e,else:p}),[e,t]);return i.jsxs("div",{"data-testid":`${r}-conditional`,style:ms(s),children:[i.jsx(k_,{condition:e.condition,onChange:l,t:n,candidates:o,testidPrefix:r}),i.jsx(Dr,{label:n("layout_editor.value_tree.cond.when_true"),testid:`${r}-then`,children:i.jsx(eo,{node:e.then,onChange:d,t:n,candidates:o,testidPrefix:`${r}-then`,depth:s+1,renderLeafInput:a})}),i.jsx(Dr,{label:n("layout_editor.value_tree.cond.when_false"),testid:`${r}-else`,children:i.jsx(eo,{node:e.else,onChange:c,t:n,candidates:o,testidPrefix:`${r}-else`,depth:s+1,renderLeafInput:a})})]})}function __({node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a}){const l=u.useCallback(c=>t({...e,primary:c}),[e,t]),d=u.useCallback(c=>t({...e,fallback:c}),[e,t]);return i.jsxs("div",{"data-testid":`${r}-fallback`,style:ms(s),children:[i.jsx(Dr,{label:n("layout_editor.value_tree.fallback.primary"),testid:`${r}-primary`,children:i.jsx(eo,{node:e.primary,onChange:l,t:n,candidates:o,testidPrefix:`${r}-primary`,depth:s+1,renderLeafInput:a})}),i.jsx(Dr,{label:n(e.op==="??"?"layout_editor.value_tree.fallback.when_empty":"layout_editor.value_tree.fallback.when_falsy"),testid:`${r}-fallback-branch`,children:i.jsx(eo,{node:e.fallback,onChange:d,t:n,candidates:o,testidPrefix:`${r}-fallbackb`,depth:s+1,renderLeafInput:a})})]})}const x_={text:()=>({kind:"leaf",text:""}),data:()=>({kind:"leaf",text:""}),expression:()=>({kind:"conditional",condition:{kind:"simple",left:"",op:"truthy",right:""},then:{kind:"leaf",text:""},else:{kind:"leaf",text:""}}),fallback:()=>({kind:"fallback",op:"??",primary:{kind:"leaf",text:""},fallback:{kind:"leaf",text:""}})};function w_({node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a}){const l=u.useCallback((g,m)=>{const h=e.parts.slice();h[g]=m,t({...e,parts:h})},[e,t]),d=u.useCallback(g=>{g.length===0?t({kind:"leaf",text:""}):g.length===1?t(g[0]):t({...e,parts:g})},[e,t]),c=u.useCallback(g=>d(e.parts.filter((m,h)=>h!==g)),[e.parts,d]),p=u.useCallback(g=>d([...e.parts,x_[g]()]),[e.parts,d]),f=u.useCallback((g,m)=>{if(g===m||g<0||m<0||g>=e.parts.length||m>=e.parts.length)return;const h=e.parts.slice(),[v]=h.splice(g,1);h.splice(m,0,v),d(h)},[e.parts,d]),b=ys({length:e.parts.length,onMove:f});return i.jsxs("div",{"data-testid":`${r}-concat`,style:ms(s),children:[i.jsx("div",{style:z_,children:n("layout_editor.value_tree.concat.hint")}),e.parts.map((g,m)=>i.jsxs(u.Fragment,{children:[i.jsx(Rn,{active:b.isDropTarget(m),testid:`${r}-part-dropline-${m}`}),i.jsxs("div",{"data-testid":`${r}-part-card-${m}`,style:b.dragIndex===m?{...cc,opacity:.5}:cc,onDragOver:h=>{h.preventDefault();const v=h.currentTarget.getBoundingClientRect();b.onDragOverItem(m,h.clientY{h.preventDefault(),b.onDrop()},children:[i.jsxs("div",{style:N_,children:[i.jsx("span",{"data-testid":`${r}-part-handle-${m}`,style:P_,draggable:!0,onDragStart:()=>b.onDragStart(m),onDragEnd:b.onDragEnd,title:n("layout_editor.value_tree.drag_reorder"),"aria-label":n("layout_editor.value_tree.drag_reorder"),role:"button",children:"⠿"}),i.jsx("span",{style:M_,children:n("layout_editor.value_tree.concat.part",{n:m+1})}),i.jsx("button",{type:"button","data-testid":`${r}-part-remove-${m}`,onClick:()=>c(m),title:n("layout_editor.value_tree.segment.remove"),"aria-label":n("layout_editor.value_tree.segment.remove"),style:O_,children:"✕"})]}),i.jsx("div",{style:{minWidth:0},children:i.jsx(eo,{node:g,onChange:h=>l(m,h),t:n,candidates:o,testidPrefix:`${r}-part-${m}`,depth:s+1,renderLeafInput:a})})]})]},m)),i.jsx(Rn,{active:b.isDropTarget(e.parts.length),testid:`${r}-part-dropline-end`}),i.jsxs("div",{style:L_,"data-testid":`${r}-part-add-row`,children:[i.jsxs("button",{type:"button","data-testid":`${r}-part-add-text`,onClick:()=>p("text"),style:zr,children:["+ ",n("layout_editor.value_tree.segment.text")]}),i.jsxs("button",{type:"button","data-testid":`${r}-part-add-expression`,onClick:()=>p("expression"),style:zr,children:["+ ",n("layout_editor.value_tree.segment.expression")]}),i.jsxs("button",{type:"button","data-testid":`${r}-part-add-fallback`,onClick:()=>p("fallback"),style:zr,children:["+ ",n("layout_editor.value_tree.segment.fallback")]}),i.jsxs("button",{type:"button","data-testid":`${r}-part-add-data`,onClick:()=>p("data"),style:zr,children:["+ ",n("layout_editor.value_tree.segment.data")]})]})]})}function k_({condition:e,onChange:t,t:n,candidates:o,testidPrefix:r}){if(e.kind==="raw")return i.jsxs("div",{"data-testid":`${r}-cond-raw`,style:I_,children:[i.jsx("span",{style:dc,children:n("layout_editor.value_tree.cond.label")}),i.jsx("code",{style:uc,children:e.source}),i.jsxs("span",{style:pc,children:["🔒 ",n("layout_editor.value_tree.cond.code_only")]})]});const s=e,a=s.op!=="truthy"&&s.op!=="falsy";return i.jsxs("div",{"data-testid":`${r}-cond`,style:E_,children:[i.jsx("span",{style:dc,children:n("layout_editor.value_tree.cond.label")}),i.jsx(ac,{testid:`${r}-cond-left`,value:s.left,onCommit:l=>t({...s,left:l}),placeholder:n("layout_editor.value_tree.cond.field_placeholder"),candidates:o,t:n}),i.jsx("select",{"data-testid":`${r}-cond-op`,value:s.op,onChange:l=>t({...s,op:l.target.value}),style:D_,children:m_.map(l=>i.jsx("option",{value:l.value,children:n(l.labelKey)},l.value))}),a&&i.jsx(ac,{testid:`${r}-cond-right`,value:s.right,onCommit:l=>t({...s,right:l}),placeholder:n("layout_editor.value_tree.cond.value_placeholder"),candidates:o,t:n,quoteDataPick:!0})]})}function ac({testid:e,value:t,onCommit:n,placeholder:o,candidates:r,t:s,quoteDataPick:a=!1}){const[l,d]=u.useState(null),c=l!==null?l:t,p=()=>{l!==null&&(l!==t&&n(l),d(null))},f=(b,g)=>{const m=En(b,g,"scalar"),h=/^\{\{\s*([\s\S]*?)\s*\}\}$/.exec(m.trim());let v=h?h[1]:m;v=v.replace(/\s*\?\?\s*''$/,"").trim(),n(a?`'${v}'`:v),d(null)};return i.jsxs("span",{style:A_,children:[i.jsx("input",{type:"text","data-testid":e,value:c,onChange:b=>d(b.target.value),onBlur:p,onKeyDown:b=>{b.key==="Enter"&&(b.preventDefault(),p())},placeholder:o,style:T_}),r&&r.length>0&&s&&i.jsx($t,{candidates:r,t:s,onSelect:b=>f(b.sourceId,b.path),testIdSuffix:`${e}-data`,floating:!0})]})}function Dr({label:e,testid:t,children:n}){return i.jsxs("div",{"data-testid":t,style:S_,children:[i.jsx("span",{style:C_,children:e}),i.jsx("div",{style:$_,children:n})]})}const lc={display:"flex",flexDirection:"column",gap:6,width:"100%",minWidth:0},ms=e=>({display:"flex",flexDirection:"column",gap:6,padding:"8px",border:"1px solid #e2e8f0",borderLeft:`3px solid ${e%2===0?"#6366f1":"#0ea5e9"}`,borderRadius:6,background:e%2===0?"#f8fafc":"#fefefe",minWidth:0}),S_={display:"flex",flexDirection:"column",gap:3,minWidth:0},C_={fontSize:11,fontWeight:600,color:"#475569"},$_={paddingLeft:8,minWidth:0},E_={display:"flex",flexWrap:"wrap",gap:4,alignItems:"center",minWidth:0},I_={display:"flex",flexWrap:"wrap",gap:4,alignItems:"center",minWidth:0},dc={fontSize:11,fontWeight:600,color:"#0f172a",whiteSpace:"nowrap"},A_={display:"inline-flex",alignItems:"flex-start",gap:2,flex:"1 1 80px",minWidth:60},T_={flex:"1 1 80px",minWidth:60,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},D_={padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff"},z_={fontSize:11,color:"#94a3b8"},cc={display:"flex",flexDirection:"column",gap:4,padding:"6px 8px",border:"1px solid #e2e8f0",borderLeft:"3px solid #6366f1",borderRadius:6,background:"#fff",minWidth:0},N_={display:"flex",alignItems:"center",gap:6,minWidth:0},M_={fontSize:10,fontWeight:600,color:"#6366f1",flex:1,minWidth:0},L_={display:"flex",flexWrap:"wrap",gap:6,marginTop:2},P_={color:"#94a3b8",cursor:"grab",fontSize:14,userSelect:"none"},O_={border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12,padding:2,flexShrink:0},zr={padding:"4px 10px",fontSize:11,border:"1px dashed #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},B_={display:"flex",flexDirection:"column",gap:4,marginTop:2},W_={alignSelf:"flex-start",padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",fontFamily:"monospace"},j_={fontSize:11,background:"#0f172a",color:"#e2e8f0",padding:"6px 8px",borderRadius:4,wordBreak:"break-all",fontFamily:"monospace"},H_={display:"flex",flexDirection:"column",gap:2,minWidth:0},uc={fontSize:11,background:"#f1f5f9",padding:"3px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all",fontFamily:"monospace"},pc={fontSize:10,color:"#64748b"};function _t({value:e,onChange:t,t:n,placeholder:o,testidPrefix:r="g7le-i18n-text-field",locales:s,candidates:a,enableExpressionTree:l=!1,expressionTreeCollapsible:d=!1,expressionSourceToggle:c=!0}){const{locale:p,templateIdentifier:f,commitText:b,classify:g,translate:m}=mv(),[h,v]=u.useState(null),[y,_]=u.useState(!1),[w,k]=u.useState(!1),[x,$]=u.useState(!1),[S,C]=u.useState(!1),[T,E]=u.useState(!1),[,A]=u.useState(0);u.useEffect(()=>{if(typeof window>"u")return;const z=H=>{const P=H.detail;P?.templateIdentifier&&P.templateIdentifier!==f||A(I=>I+1)};return window.addEventListener(kt,z),()=>window.removeEventListener(kt,z)},[f]);const N=g(e);u.useEffect(()=>{v(null),E(!1)},[p,e]);const D=h!==null?h:N.displayValue,B=u.useCallback(async()=>{if(h!==null){if(h===N.displayValue){v(null);return}_(!0);try{const z=await b(e,h);z.kind==="created"&&z.token?(t(z.token),Et({op:"prop_i18n_create_key",sourceState:"plain_text",translationKey:z.customKey,toLocale:p,valueLength:h.length,timestamp:Date.now()})):z.kind==="updated"&&Et({op:"prop_i18n_update_value",sourceState:"custom_key",translationKey:z.customKey,toLocale:p,valueLength:h.length,timestamp:Date.now()})}finally{_(!1),v(null)}}},[h,N.displayValue,b,e,t,p]),M=u.useCallback(z=>{typeof e=="string"&&(t(vo(e,z)),N.customKey&&$r(f,N.customKey,z,p))},[e,t,N.customKey,f,p]);if(N.binding){if(l&&typeof e=="string"){const z=Zd(e),H=un(e),P=!z&&Kt(e)!==null,I=(z||H.decomposed)&&!P;if(I&&d&&!x)return i.jsx(V_,{value:e,t:n,translate:m,onEdit:()=>$(!0),testidPrefix:`${r}-preview`});const F=I&&(d||z)?i.jsx(bs,{value:e,onChange:Y=>t(Y),t:n,candidates:a,testidPrefix:`${r}-seg`}):H.decomposed?i.jsx(sc,{node:H.node,onChange:Y=>t(Zn(Y,!1)),t:n,candidates:a,testidPrefix:`${r}-tree`,showSourceToggle:c}):null;if(F){if(!d)return F;const Y=Er(e),K=Y?gs(Y,X=>{const Z=m(X);return Z&&Z!==X&&!Z.startsWith("$t:")?Z:""},X=>Vt(X)):[];return i.jsxs("div",{"data-testid":`${r}-builder`,style:{display:"flex",flexDirection:"column",gap:6,width:"100%",minWidth:0},children:[i.jsxs("div",{style:{display:"flex",justifyContent:"space-between",alignItems:"center",gap:6},children:[i.jsxs("button",{type:"button","data-testid":`${r}-to-plain`,onClick:()=>C(!0),style:Z_,title:n("layout_editor.value_tree.to_plain"),"aria-label":n("layout_editor.value_tree.to_plain"),children:["↩ ",n("layout_editor.value_tree.to_plain")]}),i.jsxs("button",{type:"button","data-testid":`${r}-builder-collapse`,onClick:()=>$(!1),style:hc,title:n("layout_editor.value_tree.collapse"),"aria-label":n("layout_editor.value_tree.collapse"),children:["▴ ",n("layout_editor.value_tree.collapse")]})]}),S&&i.jsxs("div",{"data-testid":`${r}-to-plain-confirm`,style:Q_,children:[i.jsx("p",{style:R_,children:n("layout_editor.value_tree.to_plain_lead")}),i.jsx("div",{style:ex,children:K.length===0?i.jsx("span",{style:{color:"#94a3b8"},children:n("layout_editor.prop_i18n.placeholder")}):K.map((X,Z)=>X.kind==="chip"?i.jsxs("span",{style:fc,children:["🔗 ",X.text]},Z):i.jsx("span",{style:X.kind==="ellipsis"?gc:void 0,children:X.text},Z))}),i.jsxs("p",{style:tx,children:["⚠ ",n("layout_editor.value_tree.to_plain_warn")]}),i.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:6},children:[i.jsx("button",{type:"button","data-testid":`${r}-to-plain-confirm-cancel`,onClick:()=>C(!1),style:hc,children:n("layout_editor.value_tree.to_plain_cancel")}),i.jsx("button",{type:"button","data-testid":`${r}-to-plain-confirm-ok`,onClick:()=>{C(!1),$(!1),t(Er(e)||void 0)},style:nx,children:n("layout_editor.value_tree.to_plain_ok")})]})]}),F]})}}return l&&typeof e=="string"&&a&&a.length>0&&Kt(e)!==null?i.jsx(U_,{value:e,onChange:t,t:n,candidates:a,testidPrefix:`${r}-data`}):i.jsxs("div",{"data-testid":`${r}-binding`,style:lx,children:[i.jsx("code",{style:dx,children:typeof e=="string"?e:""}),i.jsxs("span",{style:cx,children:["🔗 ",n("layout_editor.prop_i18n.bound_code_only")]})]})}if(!T&&typeof e=="string"&&Xl(e)){const z=Jl(e);return i.jsxs("div",{"data-testid":`${r}-settings-ref`,style:ix,children:[i.jsx("div",{"data-testid":`${r}-settings-ref-chips`,style:sx,children:z.map((H,P)=>H.kind==="chip"?i.jsxs("span",{style:ax,children:["🔗 ",H.label]},P):i.jsx("span",{children:H.label},P))}),i.jsxs("button",{type:"button","data-testid":`${r}-settings-ref-edit`,onClick:()=>E(!0),style:yc,title:n("layout_editor.value_tree.edit"),"aria-label":n("layout_editor.value_tree.edit"),children:["✎ ",n("layout_editor.value_tree.edit")]})]})}const O=i.jsxs("button",{type:"button","data-testid":`${r}-toggle`,title:`${n("layout_editor.prop_i18n.edit_languages")} (${Gn(p,n)})`,"aria-label":`${n("layout_editor.prop_i18n.edit_languages")} (${Gn(p,n)})`,"aria-expanded":w,onClick:()=>k(z=>!z),style:yc,children:["🌐 ",N.customKey?w?"⌃":"⌄":"+"]});return i.jsxs("div",{"data-testid":r,style:{display:"flex",flexDirection:"column",gap:4,width:"100%"},children:[i.jsx("div",{style:ox,children:N.paramKey&&N.customKey?i.jsx(F_,{customKey:N.customKey,value:typeof e=="string"?e:"",onChange:t,t:n,candidates:a,testidPrefix:r,showExprButton:l&&d,onToExpression:()=>{$(!0),t($o(typeof e=="string"?e:""))},langToggle:O}):i.jsxs(i.Fragment,{children:[i.jsx("input",{type:"text","data-testid":`${r}-preview`,value:D,placeholder:o??n("layout_editor.prop_i18n.placeholder"),onChange:z=>v(z.target.value),onBlur:()=>{B(),T&&E(!1)},disabled:y,style:rx}),a&&a.length>0&&i.jsx(K_,{value:typeof e=="string"?e:"",customKey:N.customKey,onChange:t,t:n,candidates:a,testidPrefix:r}),l&&d&&i.jsx("button",{type:"button","data-testid":`${r}-to-expr`,onClick:()=>{$(!0),t($o(typeof e=="string"?e:""))},title:n("layout_editor.value_tree.to_expression"),"aria-label":n("layout_editor.value_tree.to_expression"),style:Ao,children:"ƒx"}),O]})}),w&&(N.customKey?i.jsx(Xd,{customKey:N.customKey,templateIdentifier:f,t:n,paramLabels:ps(e),locales:s,onRemoveParam:M},N.customKey):i.jsx("div",{"data-testid":`${r}-expand-hint`,style:ux,children:n("layout_editor.prop_i18n.create_first")}))]})}function F_({customKey:e,value:t,onChange:n,t:o,candidates:r,testidPrefix:s,showExprButton:a=!1,onToExpression:l,langToggle:d}){const{state:c}=Qe(),p=c.templateIdentifier,f=c.locale,b=Ft(),[g,m]=u.useState(null),h=u.useRef(""),v=u.useRef(null),y=u.useRef(null),_=u.useRef(null),[w,k]=u.useState(null),[x,$]=u.useState(!1),S=ps(t),C=u.useCallback(async()=>{const D=It(e,f);if(D!==void 0){h.current=D,m(D);return}const M=(await cn(p,e))?.values?.[f]??"";h.current=M,m(M)},[e,p,f]);u.useEffect(()=>{let D=!1;return(async()=>{const B=It(e,f);if(B!==void 0){D||(h.current=B,m(B));return}const M=await cn(p,e);if(D)return;const O=M?.values?.[f]??"";h.current=O,m(O)})(),()=>{D=!0}},[e,p,f]),u.useEffect(()=>{if(typeof window>"u")return;const D=B=>{const M=B.detail;if(M?.templateIdentifier&&M.templateIdentifier!==p)return;const O=It(e,f);O!==void 0&&O!==g&&(h.current=O,m(O))};return window.addEventListener(kt,D),()=>window.removeEventListener(kt,D)},[e,p,f,g]);const T=u.useCallback(D=>{m(D),So(p,e,f,D).then(()=>{b?.markDirty?.()})},[p,e,f,b]),E=u.useCallback(D=>{n(vo(t,D)),$r(p,e,D,f).then(()=>{C(),b?.markDirty?.()})},[t,n,p,e,f,C,b]),A=u.useCallback(async D=>{if(!(w===null||x)){$(!0);try{g!==null&&g!==h.current&&(await So(p,e,f,g),h.current=g);const B=await Cr(p,f,t,w,D.sourceId,D.path,"scalar");B.kind==="ok"&&(n(B.text),await C(),b?.markDirty?.())}finally{$(!1),k(null)}}},[w,x,g,t,p,e,f,n,C,b]),N=!!r&&r.length>0;return i.jsxs("div",{"data-testid":`${s}-chipfield-wrap`,style:{flex:1,minWidth:0,display:"flex",alignItems:"center",gap:4},children:[i.jsx("div",{ref:v,"data-testid":`${s}-chipfield`,style:{flex:1,minWidth:0},children:g===null?i.jsx("div",{"data-testid":`${s}-chipfield-loading`,style:{fontSize:11,color:"#94a3b8",padding:"4px 0"},children:o("layout_editor.translation.loading")}):i.jsx(xr,{value:g,onChange:T,t:o,paramLabels:S,testIdSuffix:`${s}-field`,onRequestInsert:N?D=>k(D):void 0,onRemoveChip:E,hideInsertButton:!0,caretRef:_})}),N&&i.jsx("button",{ref:y,type:"button","data-testid":`${s}-plus-data-btn`,onClick:()=>k(_.current?_.current():g?.length??0),title:o("layout_editor.inline_binding.insert_data"),"aria-label":o("layout_editor.inline_binding.insert_data"),style:Ao,children:"+"}),a&&l&&i.jsx("button",{type:"button","data-testid":`${s}-to-expr`,onClick:l,title:o("layout_editor.value_tree.to_expression"),"aria-label":o("layout_editor.value_tree.to_expression"),style:Ao,children:"ƒx"}),d,N&&i.jsx(Xn,{anchorRef:y,open:w!==null,onClose:()=>k(null),children:i.jsx("div",{"data-testid":`${s}-chipfield-picker`,children:i.jsx($t,{candidates:r,t:o,onSelect:D=>void A(D),testIdSuffix:`${s}-field-insert`,defaultOpen:!0,floating:!1})})})]})}function K_({value:e,customKey:t,onChange:n,t:o,candidates:r,testidPrefix:s}){const{state:a}=Qe(),l=a.templateIdentifier,d=a.selectedRoute?.layoutName??null,c=a.locale,p=Ft(),[f,b]=u.useState(!1),[g,m]=u.useState(!1),h=u.useRef(null),v=u.useCallback(w=>{const k=o(w);return k&&k!==w&&!k.startsWith("$t:")?k:""},[o]),y=u.useCallback(w=>w.replace(/\$t:[a-zA-Z0-9._-]+/g,k=>v(k.slice(3))).replace(/\s+/g," ").trim(),[v]),_=u.useCallback(async w=>{if(!g){m(!0);try{if(t){const k=await Cr(l,c,e,Number.MAX_SAFE_INTEGER,w.sourceId,w.path,"scalar");k.kind==="ok"&&(n(k.text),p?.markDirty?.())}else{const k=await us(l,d,c,e,e.length,w.sourceId,w.path,"scalar",y,x=>o(x));k.kind==="ok"&&(n(k.text),p?.markDirty?.())}}finally{m(!1),b(!1)}}},[g,t,l,d,c,e,n,p,o,y]);return i.jsxs("div",{"data-testid":`${s}-plus-data`,style:{display:"inline-block"},children:[i.jsx("button",{ref:h,type:"button","data-testid":`${s}-plus-data-btn`,disabled:g,onClick:()=>b(w=>!w),title:o("layout_editor.inline_binding.insert_data"),"aria-label":o("layout_editor.inline_binding.insert_data"),style:Ao,children:"+"}),i.jsx(Xn,{anchorRef:h,open:f,onClose:()=>b(!1),children:i.jsx($t,{candidates:r,t:o,onSelect:w=>void _(w),testIdSuffix:`${s}-plus-insert`,defaultOpen:!0,floating:!1})})]})}function V_({value:e,t,translate:n,onEdit:o,testidPrefix:r}){const s=gs(e,a=>{const l=n(a);return l&&l!==a&&!l.startsWith("$t:")?l:""},a=>Vt(a));return i.jsxs("div",{"data-testid":r,style:Y_,children:[i.jsx("div",{"data-testid":`${r}-text`,style:X_,children:s.length===0?i.jsx("span",{style:{color:"#94a3b8"},children:t("layout_editor.prop_i18n.placeholder")}):s.map((a,l)=>a.kind==="chip"?i.jsxs("span",{style:fc,children:["🔗 ",a.text]},l):i.jsx("span",{style:a.kind==="ellipsis"?gc:void 0,children:a.text},l))}),i.jsxs("button",{type:"button","data-testid":`${r}-edit`,onClick:o,style:J_,title:t("layout_editor.value_tree.edit"),"aria-label":t("layout_editor.value_tree.edit"),children:["✎ ",t("layout_editor.value_tree.edit")]})]})}function U_({value:e,onChange:t,t:n,candidates:o,testidPrefix:r}){const[s,a]=u.useState(!1),l=u.useRef(null),d=Vt(e);return i.jsxs("div",{"data-testid":r,style:{display:"flex",flexDirection:"column",gap:4,width:"100%",minWidth:0},children:[i.jsxs("div",{style:q_,children:[i.jsxs("span",{"data-testid":`${r}-chip`,style:G_,children:["🔗 ",d]}),i.jsx("button",{ref:l,type:"button","data-testid":`${r}-change`,onClick:()=>a(c=>!c),style:Ao,title:n("layout_editor.value_tree.change_data"),"aria-label":n("layout_editor.value_tree.change_data"),children:n("layout_editor.value_tree.change_data")})]}),i.jsx(Xn,{anchorRef:l,open:s,onClose:()=>a(!1),children:i.jsx($t,{candidates:o,t:n,onSelect:c=>{const p=c.path?c.path.split(".").filter(Boolean):[],f=[c.sourceId,...p].join("?.");t(`{{${f}}}`),a(!1)},testIdSuffix:`${r}-pick`,defaultOpen:!0,floating:!1})})]})}const q_={display:"flex",alignItems:"center",gap:6,width:"100%",minWidth:0,flexWrap:"wrap"},G_={fontSize:11,background:"#eef2ff",color:"#4338ca",padding:"3px 8px",borderRadius:12,wordBreak:"break-all"},Y_={display:"flex",alignItems:"center",gap:8,width:"100%",minWidth:0},X_={flex:1,minWidth:0,display:"flex",flexWrap:"wrap",alignItems:"center",gap:4,padding:"5px 8px",fontSize:12,color:"#334155",border:"1px solid #e2e8f0",borderRadius:6,background:"#f8fafc",overflow:"hidden"},fc={fontSize:11,background:"#eef2ff",color:"#4338ca",padding:"1px 6px",borderRadius:10,whiteSpace:"nowrap"},gc={color:"#94a3b8"},J_={padding:"4px 10px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#2563eb",cursor:"pointer",whiteSpace:"nowrap",flexShrink:0},hc={padding:"3px 10px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},Z_={padding:"3px 10px",fontSize:11,border:"1px solid #fca5a5",borderRadius:6,background:"#fef2f2",color:"#b91c1c",cursor:"pointer",whiteSpace:"nowrap"},Q_={display:"flex",flexDirection:"column",gap:6,padding:10,border:"1px solid #fca5a5",borderRadius:8,background:"#fffbeb"},R_={margin:0,fontSize:12,color:"#334155"},ex={padding:"5px 8px",fontSize:12,color:"#0f172a",background:"#fff",border:"1px solid #e2e8f0",borderRadius:6,wordBreak:"break-all"},tx={margin:0,fontSize:11,color:"#b45309"},nx={padding:"3px 12px",fontSize:11,border:"1px solid #dc2626",borderRadius:6,background:"#dc2626",color:"#fff",cursor:"pointer",whiteSpace:"nowrap"},ox={display:"flex",gap:4,alignItems:"center",width:"100%",minWidth:0},rx={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:0,width:"100%"},yc={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},Ao={padding:"4px 8px",fontSize:13,lineHeight:1,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},ix={display:"flex",alignItems:"center",gap:6,width:"100%",minWidth:0,flexWrap:"wrap"},sx={flex:1,minWidth:0,display:"flex",flexWrap:"wrap",alignItems:"center",gap:4,fontSize:12,color:"#334155"},ax={fontSize:11,background:"#eef2ff",color:"#4338ca",padding:"2px 8px",borderRadius:12,whiteSpace:"nowrap"},lx={display:"flex",flexDirection:"column",gap:2,width:"100%"},dx={fontSize:11,background:"#f1f5f9",padding:"3px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all"},cx={fontSize:10,color:"#64748b"},ux={fontSize:11,color:"#94a3b8",padding:"6px 8px",border:"1px dashed #cbd5e1",borderRadius:6,background:"#f8fafc"};function vs({value:e,onChange:t,candidates:n,t:o}){const r=Array.isArray(e)?e:[],s=n??[],[a,l]=u.useState(!1),d=g=>s.find(m=>m.value===g)?.label??g,c=g=>d(g)!==g,p=g=>{const m=r.filter(h=>h!==g);t(m.length===0?void 0:m)},f=g=>{r.includes(g)||(t([...r,g]),l(!1))},b=s.filter(g=>!r.includes(g.value));return i.jsxs("div",{className:"g7le-widget g7le-widget--tag-input","data-testid":"g7le-widget-tag-input",style:px,children:[i.jsxs("div",{style:fx,children:[r.map(g=>i.jsxs("span",{"data-testid":`g7le-tag-chip-${g}`,style:gx,children:[i.jsx("span",{style:hx,children:d(g)}),c(g)&&i.jsx("code",{"data-testid":`g7le-tag-chip-id-${g}`,style:yx,children:g}),i.jsx("button",{type:"button","aria-label":`remove ${g}`,"data-testid":`g7le-tag-remove-${g}`,onClick:()=>p(g),style:bx,children:"✕"})]},g)),i.jsx("button",{type:"button","data-testid":"g7le-tag-add",onClick:()=>l(g=>!g),disabled:b.length===0,style:mx,children:o("layout_editor.control.tag_add")})]}),a&&b.length>0&&i.jsx("div",{"data-testid":"g7le-tag-candidates",style:vx,children:b.map(g=>{const m=g.value!==g.label;return i.jsxs("button",{type:"button","data-testid":`g7le-tag-candidate-${g.value}`,onClick:()=>f(g.value),style:_x,children:[i.jsx("span",{style:xx,children:g.label}),m&&i.jsx("code",{"data-testid":`g7le-tag-candidate-id-${g.value}`,style:wx,children:g.value})]},g.value)})})]})}const px={display:"flex",flexDirection:"column",gap:6},fx={display:"flex",flexWrap:"wrap",gap:4,alignItems:"center"},gx={display:"inline-flex",alignItems:"center",gap:4,padding:"2px 6px",fontSize:12,background:"#e0e7ff",color:"#1d4ed8",borderRadius:12},hx={fontSize:12},yx={fontSize:10,color:"#4f46e5",background:"#c7d2fe",borderRadius:4,padding:"0 4px",fontFamily:"monospace"},bx={border:"none",background:"transparent",color:"#1d4ed8",cursor:"pointer",fontSize:10,padding:0,lineHeight:1},mx={padding:"2px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:12,background:"#fff",cursor:"pointer",color:"#475569"},vx={display:"flex",flexDirection:"column",maxHeight:180,overflowY:"auto",border:"1px solid #cbd5e1",borderRadius:6,background:"#fff"},_x={display:"flex",flexDirection:"column",gap:1,textAlign:"left",padding:"6px 10px",fontSize:12,border:"none",borderBottom:"1px solid #f1f5f9",background:"transparent",cursor:"pointer",color:"#0f172a"},xx={fontSize:12,color:"#0f172a"},wx={fontSize:10,color:"#64748b",fontFamily:"monospace"},bc=new Map;function Ze(e,t){bc.set(e,t)}function Tn(e){return e?bc.get(e)??null:null}function Nr(e,t){const o=e("meta",{})?.[t];return typeof o=="string"?o:""}function kx({getValue:e,patch:t,t:n,fieldT:o,spec:r,permissionCandidates:s,bindingCandidates:a}){const l=o??n,d=Nr(e,"title"),c=Nr(e,"description"),p=Nr(e,"icon"),f=Nr(e,"editor_label"),b=e("permissions",[]),g=u.useCallback((y,_)=>{const w={...e("meta",{})??{}};_===void 0||_===""?delete w[y]:w[y]=_,t("meta",w)},[e,t]),m=u.useCallback(y=>{const _=Array.isArray(y)?y:[];_.length===0?t("permissions",void 0):t("permissions",_)},[t]),h=Tn("icon-picker"),v=Ct(r,"icon-picker")??Ct(r,"icon")??(r?.controls?Object.values(r.controls).find(y=>y&&typeof y=="object"&&y.widget==="icon-picker")??null:null);return i.jsxs("div",{className:"g7le-meta-form","data-testid":"g7le-meta-form",style:Cx,children:[i.jsx(To,{label:n("layout_editor.page_settings.meta.title"),children:i.jsx(_t,{value:d,onChange:y=>g("title",y),t:l,testidPrefix:"g7le-meta-title",candidates:a,enableExpressionTree:!0,expressionTreeCollapsible:!0})}),i.jsx(To,{label:n("layout_editor.page_settings.meta.description"),children:i.jsx(_t,{value:c,onChange:y=>g("description",y),t:l,testidPrefix:"g7le-meta-description",candidates:a,enableExpressionTree:!0,expressionTreeCollapsible:!0})}),i.jsx(To,{label:n("layout_editor.page_settings.meta.icon"),children:h?i.jsx(Sx,{icon:p,t:n,onChange:y=>g("icon",typeof y=="string"?y:void 0),IconWidget:h,iconControl:v??{widget:"icon-picker"}}):i.jsx("input",{type:"text","data-testid":"g7le-meta-icon",value:p,placeholder:n("layout_editor.page_settings.meta.icon_placeholder"),onChange:y=>g("icon",y.target.value),style:Ax})}),i.jsx(To,{label:n("layout_editor.page_settings.meta.editor_label"),hint:n("layout_editor.page_settings.meta.editor_label_hint"),children:i.jsx(_t,{value:f,onChange:y=>g("editor_label",y),t:l,testidPrefix:"g7le-meta-editor-label",candidates:a,enableExpressionTree:!0,expressionTreeCollapsible:!0})}),i.jsx(To,{label:n("layout_editor.page_settings.meta.permissions"),hint:n("layout_editor.page_settings.meta.permissions_hint"),children:i.jsx("div",{"data-testid":"g7le-meta-permissions",children:i.jsx(vs,{control:{widget:"tag-input"},value:b,onChange:m,t:n,candidates:s})})})]})}function To({label:e,hint:t,children:n}){return i.jsxs("div",{className:"g7le-meta-field",style:$x,children:[i.jsx("label",{style:Ex,children:e}),n,t?i.jsxs("p",{style:Ix,children:["ⓘ ",t]}):null]})}function Sx({icon:e,onChange:t,t:n,IconWidget:o,iconControl:r}){const[s,a]=u.useState(!1),l=e?/\bfa-/.test(e)?i.jsx("i",{className:e,"aria-hidden":"true"}):e:"📄";return i.jsxs("div",{"data-testid":"g7le-meta-icon",style:{display:"flex",flexDirection:"column",gap:6,minWidth:0},children:[i.jsxs("button",{type:"button","data-testid":"g7le-meta-icon-toggle","aria-expanded":s,onClick:()=>a(d=>!d),style:{display:"flex",alignItems:"center",gap:8,padding:"5px 8px",border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",cursor:"pointer",fontSize:12,color:"#475569",width:"fit-content"},children:[i.jsx("span",{style:{fontSize:16},"aria-hidden":"true",children:l}),i.jsx("span",{children:e||n("layout_editor.page_settings.meta.icon_placeholder")}),i.jsx("span",{"aria-hidden":"true",children:s?"▴":"▾"})]}),s?i.jsx(o,{control:r,value:e,onChange:d=>{t(d),a(!1)},t:n}):null]})}const Cx={display:"flex",flexDirection:"column",gap:16,minWidth:0},$x={display:"flex",flexDirection:"column",gap:6,minWidth:0},Ex={fontSize:13,fontWeight:600,color:"#0f172a"},Ix={margin:0,fontSize:11,color:"#94a3b8"},Ax={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:0,width:"100%"};function Mr({checked:e,onChange:t,label:n,testid:o,ariaLabel:r,disabled:s=!1}){return i.jsxs("label",{style:{...Mx,...s?{cursor:"not-allowed"}:{}},children:[i.jsx("button",{type:"button","data-testid":o,role:"switch","aria-checked":e,"aria-label":r,disabled:s,onClick:()=>t(!e),style:Lx(e,s),children:i.jsx("span",{style:Px(e)})}),n!=null?i.jsx("span",{style:Ox(s),children:n}):null]})}function Lr({disabled:e,children:t,testid:n,style:o}){return i.jsx("div",{"data-testid":n,"data-disabled":e?"true":"false","aria-disabled":e,style:{...o,...e?{opacity:.5,pointerEvents:"none",userSelect:"none"}:{}},children:t})}function Tx({filled:e,sourceLabel:t,onRevert:n,revertLabel:o,hint:r,children:s,testid:a}){const l=e&&typeof n=="function",d=!e&&t!=null&&t!=="";return i.jsxs("div",{"data-testid":a,style:Dx,children:[s,l?i.jsxs("button",{type:"button","data-testid":a?`${a}-revert`:void 0,onClick:n,title:r??o,"aria-label":o,style:Nx,children:["↩ ",o]}):d?i.jsx("span",{"data-testid":a?`${a}-source`:void 0,title:r,style:zx,children:t}):null]})}const Dx={position:"relative",minWidth:0,width:"100%"},zx={position:"absolute",right:8,top:"50%",transform:"translateY(-50%)",fontSize:10,color:"#94a3b8",background:"#f1f5f9",borderRadius:4,padding:"1px 6px",pointerEvents:"none",maxWidth:"45%",overflow:"hidden",whiteSpace:"nowrap",textOverflow:"ellipsis"},Nx={position:"absolute",right:6,top:"50%",transform:"translateY(-50%)",fontSize:10,color:"#0369a1",background:"#e0f2fe",border:"1px solid #bae6fd",borderRadius:4,padding:"1px 6px",cursor:"pointer",whiteSpace:"nowrap"},Mx={display:"inline-flex",alignItems:"center",gap:8,cursor:"pointer"},Lx=(e,t)=>({position:"relative",width:38,height:22,flexShrink:0,borderRadius:999,border:"none",padding:0,background:t?"#e2e8f0":e?"#2563eb":"#cbd5e1",cursor:t?"not-allowed":"pointer",transition:"background 0.15s ease"}),Px=e=>({position:"absolute",top:2,left:e?18:2,width:18,height:18,borderRadius:"50%",background:"#fff",boxShadow:"0 1px 2px rgba(0,0,0,0.2)",transition:"left 0.15s ease"}),Ox=e=>({fontSize:13,fontWeight:600,color:e?"#94a3b8":"#0f172a"}),Bx=/\$(?:core|module|plugin)_settings:[a-zA-Z0-9._:-]+/;function Wx(e){const t=[];let n=!1;const o=s=>{t.push({kind:"text",text:s}),n=!0},r=(s,a,l)=>{n||o(""),t.push({kind:"chip",raw:s,text:a,removable:l}),n=!1};for(const s of jx(e))s.kind==="text"?o(s.raw):r(s.raw,s.label,s.removable);return n||o(""),t}function jx(e){const t=[];if(typeof e!="string"||e.length===0)return t;const n=e.length;let o=0,r=0;const s=a=>{a>r&&t.push({kind:"text",raw:e.slice(r,a),label:"",removable:!1})};for(;o=n){o++;continue}s(o);const l=e.slice(o,a+2);t.push({kind:"chip",raw:l,label:Vt(l),removable:!0}),o=a+2,r=o;continue}if(e[o]==="$"){const a=Bx.exec(e.slice(o));if(a&&a.index===0){s(o);const l=a[0],d=l.split(":").pop()||l;t.push({kind:"chip",raw:l,label:d,removable:!1}),o+=l.length,r=o;continue}}o++}return s(n),t}function Hx(e,t,n,o){const r=[];let s=!1;return e.forEach((a,l)=>{if(a.kind==="chip"){if(!s&&a.raw===t){s=!0;return}r.push(a.raw??"")}else{const d=a.text??"";if(l===n){const c=Math.max(0,Math.min(o,d.length));r.push(d.slice(0,c),t,d.slice(c))}else r.push(d)}}),r.join("")}function Fx(e,t,n){const o=Math.max(0,Math.min(t,e.length));return e.slice(0,o)+n+e.slice(o)}function Kx(e,t){const n=e.indexOf(t);return n<0?e:e.slice(0,n)+e.slice(n+t.length)}function _s({value:e,onChange:t,t:n,candidates:o,onDone:r,testidPrefix:s="g7le-binding-chip-text",disabled:a=!1}){const l=u.useMemo(()=>Wx(e),[e]),d=u.useRef(null),c=!!o&&o.length>0,[p,f]=u.useState(null),[b,g]=u.useState(null),[m,h]=u.useState(null),[v,y]=u.useState(!1),_=u.useRef(0),w=u.useRef(null),k=u.useMemo(()=>l.map(P=>P.kind==="chip"?`c:${P.raw}`:"t").join("|"),[l]),x=u.useRef(null),$=u.useRef([]),S=u.useRef(!1);u.useLayoutEffect(()=>{const P=S.current;S.current=!1,!(!P&&x.current===k)&&(x.current=k,l.forEach((I,L)=>{if(I.kind!=="text")return;const F=$.current[L];F&&F.textContent!==(I.text??"")&&(F.textContent=I.text??"")}))},[k,l,e]);const C=u.useCallback(()=>{const P=d.current;if(!P)return e;const I=[];for(const L of Array.from(P.querySelectorAll("[data-seg]")))L.dataset.seg==="chip"?I.push(L.dataset.raw??""):I.push(L.textContent??"");return I.join("")},[e]),T=u.useCallback(()=>{a||t(C())},[a,t,C]),E=u.useRef(null),A=u.useRef(!1),N=(P,I)=>{if(!a){P.preventDefault(),P.stopPropagation(),E.current={raw:I,pointerId:P.pointerId},A.current=!1,f(I);try{P.currentTarget.setPointerCapture(P.pointerId)}catch{}}},D=P=>{const I=E.current;if(!I||P.pointerId!==I.pointerId)return;A.current=!0;const L=O(P.clientX,P.clientY);L&&(g({slotIdx:L.slotIdx,offset:L.offset}),h(Ux(d.current,L.slotIdx,L.offset)))},B=(P,I)=>{if(P.stopPropagation(),A.current){A.current=!1;return}S.current=!0,t(Kx(e,I))},M=P=>{const I=E.current;if(!I||P.pointerId!==I.pointerId)return;try{P.currentTarget.releasePointerCapture(P.pointerId)}catch{}E.current=null,A.current&&typeof setTimeout=="function"&&setTimeout(()=>{A.current=!1},0);const L=O(P.clientX,P.clientY);if(f(null),g(null),h(null),!L)return;const F=d.current;if(!F)return;const K=Array.from(F.querySelectorAll("[data-seg]")).map(Z=>Z.dataset.seg==="chip"?{kind:"chip",raw:Z.dataset.raw??""}:{kind:"text",text:Z.textContent??""}),X=Hx(K,I.raw,L.slotIdx,L.offset);X!==e&&(S.current=!0,t(X))},O=(P,I)=>{const L=d.current;if(!L)return null;const F=Array.from(L.querySelectorAll("[data-seg]")),Y=L.ownerDocument,K=Y.elementFromPoint(P,I),X=K?.closest('[data-seg="text"]');if(X)return{slotIdx:F.indexOf(X),offset:Vx(Y,X,P,I)};const Z=K?.closest('[data-seg="chip"]');if(Z){const oe=F.indexOf(Z),G=Z.getBoundingClientRect();if(P=0){const ee=F[oe-1];return{slotIdx:oe-1,offset:(ee.textContent??"").length}}if(oe+1({s:oe,i:G})).filter(oe=>oe.s.dataset.seg==="text").pop();return ae?{slotIdx:ae.i,offset:(ae.s.textContent??"").length}:null},z=()=>{a||!c||(_.current=qx(d.current,e.length),y(P=>!P))},H=P=>{const I=P.path?P.path.split(".").filter(Boolean):[],L=[P.sourceId,...I].join("?.");S.current=!0,t(Fx(e,_.current,`{{${L}}}`)),y(!1)};return i.jsxs("div",{"data-testid":s,style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsxs("div",{ref:d,"data-testid":`${s}-box`,className:"g7le-binding-chip-input",style:Gx,children:[l.map((P,I)=>P.kind==="chip"?i.jsxs("span",{"data-seg":"chip","data-raw":P.raw,"data-testid":`${s}-chip-${I}`,contentEditable:!1,onPointerDown:L=>N(L,P.raw??""),onPointerMove:D,onPointerUp:M,title:P.removable?n("layout_editor.value_tree.change_data"):n("layout_editor.prop_i18n.bound_code_only"),style:{...Zx,...p===P.raw?Qx:null,touchAction:"none"},children:[i.jsx("span",{"aria-hidden":"true",style:Rx,children:"⠿"}),i.jsx("span",{"aria-hidden":"true",style:{marginRight:3},children:"🔗"}),i.jsx("span",{children:P.text}),P.removable&&!a&&i.jsx("button",{type:"button","data-testid":`${s}-chip-remove-${I}`,"aria-label":n("layout_editor.inline_binding.clear"),title:n("layout_editor.inline_binding.clear"),onPointerDown:L=>{L.stopPropagation(),L.preventDefault()},onClick:L=>B(L,P.raw??""),style:ew,children:"✕"})]},`chip-${P.raw}-${I}`):i.jsx("span",{ref:L=>{$.current[I]=L},"data-seg":"text",contentEditable:!a,suppressContentEditableWarning:!0,onInput:T,"data-testid":`${s}-text-${I}`,style:{...Yx,...p?Xx:null,...b?.slotIdx===I?Jx:null}},`text-slot-${I}`)),m&&i.jsx("span",{"aria-hidden":"true","data-testid":`${s}-caret`,style:{position:"absolute",left:m.left,top:m.top,width:2,height:m.height,background:"#2563eb",borderRadius:1,pointerEvents:"none",boxShadow:"0 0 0 1px rgba(37,99,235,0.3)"}})]}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[r&&i.jsxs("button",{type:"button","data-testid":`${s}-done`,onClick:r,style:mc,title:n("layout_editor.value_tree.done"),"aria-label":n("layout_editor.value_tree.done"),children:["✓ ",n("layout_editor.value_tree.done")]}),c&&i.jsxs("div",{style:{position:"relative"},children:[i.jsxs("button",{ref:w,type:"button","data-testid":`${s}-insert`,onClick:z,disabled:a,style:mc,title:n("layout_editor.inline_binding.insert_data"),"aria-label":n("layout_editor.inline_binding.insert_data"),children:["+ ",n("layout_editor.inline_binding.insert_data")]}),i.jsx(Xn,{anchorRef:w,open:v,onClose:()=>y(!1),children:i.jsx($t,{candidates:o,t:n,onSelect:H,testIdSuffix:`${s}-insert`,defaultOpen:!0,floating:!1})})]}),i.jsx("span",{style:tw,children:n("layout_editor.translation.placeholder_locked")})]})]})}function Vx(e,t,n,o){const r=(t.textContent??"").length;try{const a=e;let l=null,d=0;if(typeof a.caretRangeFromPoint=="function"){const c=a.caretRangeFromPoint(n,o);c&&(l=c.startContainer,d=c.startOffset)}else if(typeof a.caretPositionFromPoint=="function"){const c=a.caretPositionFromPoint(n,o);c&&(l=c.offsetNode,d=c.offset)}if(l&&t.contains(l))return Math.max(0,Math.min(d,r))}catch{}const s=t.getBoundingClientRect();return n>s.left+s.width/2?r:0}function Ux(e,t,n){if(!e)return null;const r=Array.from(e.querySelectorAll("[data-seg]"))[t];if(!r)return null;const s=e.getBoundingClientRect();try{const d=r.firstChild,c=e.ownerDocument;if(d&&d.nodeType===Node.TEXT_NODE&&(d.textContent??"").length>0){const p=c.createRange(),f=Math.max(0,Math.min(n,(d.textContent??"").length));p.setStart(d,f),p.setEnd(d,f);const b=p.getClientRects(),g=b.length>0?b[0]:p.getBoundingClientRect();if(g&&(g.height>0||g.width>=0))return{left:g.left-s.left,top:g.top-s.top,height:g.height||r.getBoundingClientRect().height}}}catch{}const a=r.getBoundingClientRect();return{left:(n>0?a.right:a.left)-s.left,top:a.top-s.top,height:a.height||16}}function qx(e,t){if(!e)return t;try{const n=e.ownerDocument.defaultView?.getSelection();if(!n||n.rangeCount===0)return t;const o=n.getRangeAt(0);let r=o.startContainer,s=null;for(;r&&r!==e;){if(r instanceof HTMLElement&&r.dataset.seg==="text"){s=r;break}r=r.parentNode}if(!s||!e.contains(s))return t;const a=Array.from(e.querySelectorAll("[data-seg]"));let l=0;for(const d of a){if(d===s)break;l+=d.dataset.seg==="chip"?(d.dataset.raw??"").length:(d.textContent??"").length}return l+o.startOffset}catch{return t}}const Gx={position:"relative",display:"flex",flexWrap:"wrap",alignItems:"center",gap:2,minHeight:30,padding:"4px 8px",border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",fontSize:12,lineHeight:1.6,minWidth:0,width:"100%",boxSizing:"border-box"},Yx={outline:"none",minWidth:8,minHeight:"1.2em",whiteSpace:"pre-wrap",color:"#0f172a",display:"inline-block",wordBreak:"break-all"},Xx={boxShadow:"inset 0 -2px 0 #93c5fd",background:"#eff6ff",borderRadius:2},Jx={background:"#dbeafe",boxShadow:"inset 0 -2px 0 #2563eb"},Zx={display:"inline-flex",alignItems:"center",gap:1,background:"linear-gradient(180deg,#eff6ff,#dbeafe)",color:"#1d4ed8",border:"1px dashed #60a5fa",borderRadius:9999,padding:"1px 8px 1px 4px",margin:"0 1px",fontSize:11,fontWeight:600,cursor:"grab",userSelect:"none",whiteSpace:"nowrap",boxShadow:"0 1px 2px rgba(37,99,235,0.18)",verticalAlign:"middle"},Qx={opacity:.5,borderStyle:"solid",cursor:"grabbing"},Rx={color:"#2563eb",opacity:.7,fontSize:11,marginRight:1,cursor:"grab"},ew={marginLeft:4,width:14,height:14,lineHeight:"12px",padding:0,border:"none",borderRadius:9999,background:"rgba(29,78,216,0.12)",color:"#1d4ed8",fontSize:9,fontWeight:700,cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",flex:"0 0 auto"},mc={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},tw={fontSize:10,color:"#94a3b8"},nw=Jl;function xs(e){return Eb(e)}function Ke({value:e,onChange:t,t:n,candidates:o,placeholder:r,testidPrefix:s="g7le-data-chip-value",readOnly:a=!1,enableExpressionTree:l=!0}){const d=typeof e=="string"?e:"",c=!!o&&o.length>0,[p,f]=u.useState(!1),[b,g]=u.useState(!1),[m,h]=u.useState(!1),v=u.useCallback(S=>i.jsx(Ke,{value:S.value,onChange:C=>S.onChange(C),t:S.t,candidates:S.candidates,testidPrefix:S.testidPrefix,enableExpressionTree:!0}),[]),y=()=>i.jsx("div",{style:{display:"flex",gap:4,alignItems:"center",width:"100%",minWidth:0},children:i.jsx("input",{type:"text","data-testid":`${s}-input`,value:d,placeholder:r??n("layout_editor.page_settings.seo.value_placeholder"),readOnly:a,onChange:S=>t(S.target.value),onFocus:()=>f(!0),onBlur:()=>f(!1),style:{flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:0,width:"100%",background:a?"#f1f5f9":"#fff",color:a?"#64748b":"#0f172a"}})}),_=u.useCallback(S=>{const C=d?`${d} ${S.expression}`:S.expression;t(C)},[d,t]);if(!l||a)return i.jsxs("div",{"data-testid":s,style:pn,children:[y(),!a&&c&&i.jsx($t,{candidates:o,t:n,onSelect:_,testIdSuffix:`${s}-pick`})]});const w=Wv(d),k=Zd(d),x=Kt(d),$=S=>{const C=Er(d),T=C?gs(C,()=>"",E=>Vt(E)):[];return i.jsxs(i.Fragment,{children:[i.jsx("div",{style:{display:"flex",justifyContent:"flex-start"},children:i.jsxs("button",{type:"button","data-testid":`${S}-to-plain`,onClick:()=>h(!0),style:sw,title:n("layout_editor.value_tree.to_plain"),"aria-label":n("layout_editor.value_tree.to_plain"),children:["↩ ",n("layout_editor.value_tree.to_plain")]})}),m&&i.jsxs("div",{"data-testid":`${S}-to-plain-confirm`,style:aw,children:[i.jsx("p",{style:lw,children:n("layout_editor.value_tree.to_plain_lead")}),i.jsx("div",{style:dw,children:T.length===0?i.jsx("span",{style:{color:"#94a3b8"},children:n("layout_editor.page_settings.seo.value_placeholder")}):T.map((E,A)=>E.kind==="chip"?i.jsxs("span",{style:ws,children:["🔗 ",E.text]},A):i.jsx("span",{style:E.kind==="ellipsis"?{color:"#94a3b8"}:void 0,children:E.text},A))}),i.jsxs("p",{style:cw,children:["⚠ ",n("layout_editor.value_tree.to_plain_warn")]}),i.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:6},children:[i.jsx("button",{type:"button","data-testid":`${S}-to-plain-confirm-cancel`,onClick:()=>h(!1),style:Ut,children:n("layout_editor.value_tree.to_plain_cancel")}),i.jsx("button",{type:"button","data-testid":`${S}-to-plain-confirm-ok`,onClick:()=>{h(!1),t(Er(d)||"")},style:uw,children:n("layout_editor.value_tree.to_plain_ok")})]})]})]})};if(!p&&(w==="expression"||k)){if(k)return i.jsxs("div",{"data-testid":s,style:pn,children:[!a&&$(`${s}-seg`),i.jsx(bs,{value:d,onChange:C=>t(C),t:n,candidates:o,testidPrefix:`${s}-seg`,renderLeafInput:v})]});const S=un(d);return i.jsxs("div",{"data-testid":s,style:pn,children:[!a&&$(`${s}-tree`),i.jsx(sc,{node:S.node,onChange:C=>t(Zn(C,!1)),t:n,candidates:o,testidPrefix:`${s}-tree`,renderLeafInput:v})]})}if(x&&!p&&!b)return i.jsx(ow,{value:d,onChange:t,t:n,candidates:o,testidPrefix:s,onEditRaw:()=>g(!0)});if(!p&&!b&&xs(d)){const S=nw(d);return i.jsx("div",{"data-testid":s,style:pn,children:i.jsxs("div",{style:vc,children:[i.jsx("div",{"data-testid":`${s}-chips`,style:rw,children:S.map((C,T)=>C.kind==="chip"?i.jsxs("span",{style:ws,children:["🔗 ",C.label]},T):i.jsx("span",{children:C.label},T))}),i.jsxs("button",{type:"button","data-testid":`${s}-edit-raw`,onClick:()=>g(!0),style:Ut,title:n("layout_editor.value_tree.edit"),"aria-label":n("layout_editor.value_tree.edit"),children:["✎ ",n("layout_editor.value_tree.edit")]})]})})}return b&&xs(d)?i.jsxs("div",{"data-testid":s,style:pn,children:[i.jsx(_s,{value:d,onChange:t,t:n,candidates:o,disabled:a,onDone:()=>g(!1),testidPrefix:`${s}-chipedit`}),!a&&w!=="raw"&&i.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:[i.jsxs("button",{type:"button","data-testid":`${s}-to-expr`,onClick:()=>t($o(d)),style:Ut,title:n("layout_editor.value_tree.to_expression"),"aria-label":n("layout_editor.value_tree.to_expression"),children:["ƒx ",n("layout_editor.value_tree.to_expression")]}),i.jsxs("button",{type:"button","data-testid":`${s}-to-fallback`,onClick:()=>t(hs(d)),style:Ut,title:n("layout_editor.value_tree.segment.fallback"),"aria-label":n("layout_editor.value_tree.segment.fallback"),children:["?? ",n("layout_editor.value_tree.segment.fallback")]})]}),w==="raw"&&i.jsxs("p",{"data-testid":`${s}-raw-hint`,style:ks,children:["ⓘ ",n("layout_editor.value_tree.raw_expression_hint")]})]}):!p&&xs(d)?i.jsxs("div",{"data-testid":s,style:pn,children:[i.jsx(_s,{value:d,onChange:t,t:n,candidates:o,disabled:a,onDone:()=>{g(!1),f(!1)},testidPrefix:`${s}-chipedit`}),!a&&w!=="raw"&&i.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:[i.jsxs("button",{type:"button","data-testid":`${s}-to-expr`,onClick:()=>t($o(d)),style:Ut,title:n("layout_editor.value_tree.to_expression"),"aria-label":n("layout_editor.value_tree.to_expression"),children:["ƒx ",n("layout_editor.value_tree.to_expression")]}),i.jsxs("button",{type:"button","data-testid":`${s}-to-fallback`,onClick:()=>t(hs(d)),style:Ut,title:n("layout_editor.value_tree.segment.fallback"),"aria-label":n("layout_editor.value_tree.segment.fallback"),children:["?? ",n("layout_editor.value_tree.segment.fallback")]})]}),w==="raw"&&i.jsxs("p",{"data-testid":`${s}-raw-hint`,style:ks,children:["ⓘ ",n("layout_editor.value_tree.raw_expression_hint")]})]}):i.jsxs("div",{"data-testid":s,style:pn,children:[y(),i.jsxs("div",{style:iw,children:[c&&i.jsx($t,{candidates:o,t:n,onSelect:_,testIdSuffix:`${s}-pick`}),w!=="raw"&&i.jsxs("div",{style:{display:"flex",gap:4},children:[i.jsxs("button",{type:"button","data-testid":`${s}-to-expr`,onClick:()=>t($o(d)),style:Ut,title:n("layout_editor.value_tree.to_expression"),"aria-label":n("layout_editor.value_tree.to_expression"),children:["ƒx ",n("layout_editor.value_tree.to_expression")]}),i.jsxs("button",{type:"button","data-testid":`${s}-to-fallback`,onClick:()=>t(hs(d)),style:Ut,title:n("layout_editor.value_tree.segment.fallback"),"aria-label":n("layout_editor.value_tree.segment.fallback"),children:["?? ",n("layout_editor.value_tree.segment.fallback")]})]})]}),w==="raw"&&!p&&i.jsxs("p",{"data-testid":`${s}-raw-hint`,style:ks,children:["ⓘ ",n("layout_editor.value_tree.raw_expression_hint")]})]})}function ow({value:e,onChange:t,t:n,candidates:o,testidPrefix:r,onEditRaw:s}){const[a,l]=u.useState(!1),d=u.useRef(null),c=Vt(e),p=!!o&&o.length>0,f=Kt(e)?.localeFn;return i.jsxs("div",{"data-testid":r,style:pn,children:[i.jsxs("div",{style:vc,children:[i.jsxs("span",{"data-testid":`${r}-chip`,style:ws,children:["🔗 ",c]}),p&&i.jsx("button",{ref:d,type:"button","data-testid":`${r}-change`,onClick:()=>l(b=>!b),style:Ut,title:n("layout_editor.value_tree.change_data"),"aria-label":n("layout_editor.value_tree.change_data"),children:n("layout_editor.value_tree.change_data")}),i.jsx("button",{type:"button","data-testid":`${r}-edit-raw`,onClick:s,style:Ut,title:n("layout_editor.value_tree.edit"),"aria-label":n("layout_editor.value_tree.edit"),children:"✎"})]}),p&&i.jsx(Xn,{anchorRef:d,open:a,onClose:()=>l(!1),children:i.jsx($t,{candidates:o,t:n,onSelect:b=>{if(f){const h=[b.sourceId,...b.path?b.path.split(".").filter(Boolean):[]].join(".");t(`{{${f}(${h})}}`),l(!1);return}const g=b.path?b.path.split(".").filter(Boolean):[],m=[b.sourceId,...g].join("?.");t(`{{${m}}}`),l(!1)},testIdSuffix:`${r}-pick`,defaultOpen:!0,floating:!1})})]})}const pn={display:"flex",flexDirection:"column",gap:4,width:"100%",minWidth:0},vc={display:"flex",alignItems:"center",gap:6,width:"100%",minWidth:0,flexWrap:"wrap"},rw={flex:1,minWidth:0,display:"flex",flexWrap:"wrap",alignItems:"center",gap:4,padding:"5px 8px",fontSize:12,color:"#334155",border:"1px solid #e2e8f0",borderRadius:6,background:"#f8fafc"},ws={fontSize:11,background:"#eef2ff",color:"#4338ca",padding:"2px 8px",borderRadius:12,whiteSpace:"nowrap"},Ut={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},iw={display:"flex",flexWrap:"wrap",alignItems:"center",gap:6},ks={margin:"2px 0 0",fontSize:11,color:"#94a3b8",lineHeight:1.4},sw={padding:"3px 10px",fontSize:11,border:"1px solid #fca5a5",borderRadius:6,background:"#fef2f2",color:"#b91c1c",cursor:"pointer",whiteSpace:"nowrap"},aw={display:"flex",flexDirection:"column",gap:6,padding:10,border:"1px solid #fca5a5",borderRadius:8,background:"#fffbeb"},lw={margin:0,fontSize:12,color:"#334155"},dw={padding:"5px 8px",fontSize:12,color:"#0f172a",background:"#fff",border:"1px solid #e2e8f0",borderRadius:6,wordBreak:"break-all",display:"flex",flexWrap:"wrap",gap:4,alignItems:"center"},cw={margin:0,fontSize:11,color:"#b45309"},uw={padding:"3px 12px",fontSize:11,border:"1px solid #dc2626",borderRadius:6,background:"#dc2626",color:"#fff",cursor:"pointer",whiteSpace:"nowrap"};let _c=0;function Pr({value:e,onChange:t,keyField:n,valueField:o="content",t:r,candidates:s,testidPrefix:a="g7le-kv-chip-editor",keyPlaceholder:l,valuePlaceholder:d,addLabel:c,renderKeyInput:p}){const f=u.useMemo(()=>(Array.isArray(e)?e:[]).map(w=>({id:_c++,k:typeof w[n]=="string"?w[n]:"",v:typeof w[o]=="string"?w[o]:""})),[]),[b,g]=u.useState(f),m=u.useCallback(w=>{g(w);const k=w.filter(x=>x.k.trim()!=="").map(x=>({[n]:x.k,[o]:x.v}));t(k)},[n,o,t]),h=u.useCallback(()=>{m([...b,{id:_c++,k:"",v:""}])},[b,m]),v=u.useCallback(w=>{m(b.filter(k=>k.id!==w))},[b,m]),y=u.useCallback((w,k)=>{m(b.map(x=>x.id===w?{...x,k}:x))},[b,m]),_=u.useCallback((w,k)=>{m(b.map(x=>x.id===w?{...x,v:k}:x))},[b,m]);return i.jsxs("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:6},children:[b.map(w=>i.jsxs("div",{"data-testid":`${a}-row-${w.id}`,style:{display:"flex",gap:6,alignItems:"flex-start",border:"1px solid #e2e8f0",borderRadius:8,padding:8},children:[i.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:6},children:[i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:2,minWidth:0},children:p?i.jsx("div",{style:{minWidth:0},children:p({value:w.k,onChange:k=>y(w.id,k),testid:`${a}-key-${w.id}`,placeholder:l??r(`layout_editor.page_settings.seo.extra_${n}`)})}):i.jsx("input",{type:"text","data-testid":`${a}-key-${w.id}`,value:w.k,placeholder:l??r(`layout_editor.page_settings.seo.extra_${n}`),onChange:k=>y(w.id,k.target.value),style:{width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:0,boxSizing:"border-box"}})}),i.jsx("div",{style:{minWidth:0},children:i.jsx(Ke,{value:w.v,onChange:k=>_(w.id,k),t:r,candidates:s,placeholder:d??r("layout_editor.page_settings.seo.extra_content"),testidPrefix:`${a}-value-${w.id}`})})]}),i.jsx("button",{type:"button","data-testid":`${a}-remove-${w.id}`,onClick:()=>v(w.id),title:r("layout_editor.page_settings.seo.remove"),"aria-label":r("layout_editor.page_settings.seo.remove"),style:{flex:"0 0 auto",padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"},children:"✕"})]},w.id)),i.jsxs("button",{type:"button","data-testid":`${a}-add`,onClick:h,style:{alignSelf:"flex-start",padding:"5px 10px",fontSize:12,border:"1px dashed #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},children:["+ ",c??r("layout_editor.page_settings.seo.add_extra")]})]})}const pw=["website","article","product","profile"],fw=["summary","summary_large_image","app","player"];function gw(e){switch(e){case"core":return"layout_editor.page_settings.seo.og_source_core";case"inherited":return"layout_editor.page_settings.seo.og_source_inherited";case"filter":return"layout_editor.page_settings.seo.og_source_filter";case"layout":return null;default:return e?"layout_editor.page_settings.seo.og_source_module":null}}function xc(e){const t={};for(const n of e??[])t[n.key]=n;return t}function wc(e,t){return!!e&&t&&typeof e.sourceExpr=="string"&&e.sourceExpr!==""&&!e.overriddenByLayout&&!e.lockedByFilter}function kc({label:e,sourceExpr:t,onReplace:n,t:o,testid:r}){return i.jsxs("div",{"data-testid":r,style:Sw,children:[i.jsxs("span",{"data-testid":`${r}-chip`,style:Cw,title:t,children:["🔗 ",e||t]}),i.jsx("span",{"data-testid":`${r}-badge`,style:$w,children:o("layout_editor.page_settings.seo.auto_chip_source")}),i.jsx("button",{type:"button","data-testid":`${r}-replace`,onClick:n,style:Ew,children:o("layout_editor.page_settings.seo.auto_chip_replace")})]})}function hw({og:e,twitter:t,onChangeOg:n,onChangeTwitter:o,ogPreview:r,twitterPreview:s,defaultsAvailable:a=!1,candidates:l,t:d,testidPrefix:c="g7le-seo-og"}){const p=e&&typeof e=="object"?e:{},f=t&&typeof t=="object"?t:{},[b,g]=u.useState(p.image_height!=null||p.image_type!=null||p.image_secure_url!=null),m=xc(r),h=xc(s),v=u.useCallback((T,E)=>{const A={...p};E===void 0||E===""||E===null?delete A[T]:A[T]=E,n(A)},[p,n]),y=u.useCallback((T,E)=>{const A={...f};E===void 0||E===""||E===null?delete A[T]:A[T]=E,o(A)},[f,o]),_=(T,E,A)=>!A||!a||!A.lockedByFilter?null:i.jsx("div",{style:{display:"flex",gap:6,alignItems:"center",marginTop:2},children:i.jsxs("span",{"data-testid":`${T}-locked-${E}`,style:xw,children:["🔒 ",d("layout_editor.page_settings.seo.og_locked")]})}),w=T=>{if(!T||!a||T.lockedByFilter||T.overriddenByLayout)return;const E=gw(T.source);return E?d(E):void 0},k=(T,E)=>T&&a?T.overriddenByLayout===!0:E!=="",x=(T,E,A,N,D,B)=>{const M=B[E],O=!!M?.lockedByFilter,z=typeof N[E]=="string"?N[E]:"";return i.jsxs("div",{"data-testid":`${T}-${E}`,style:Dn,children:[i.jsx("label",{style:to,children:d(A)}),O?i.jsx("div",{"data-testid":`${T}-locked-value-${E}`,style:_w,children:String(M?.effectiveValue??"")}):wc(M,a)?i.jsx(kc,{label:M.label??"",sourceExpr:M.sourceExpr,onReplace:()=>D(E,M.sourceExpr),t:d,testid:`${T}-${E}-auto`}):i.jsx(_t,{value:z,onChange:H=>D(E,H??""),t:d,candidates:l,placeholder:a&&M?.effectiveValue!=null?String(M.effectiveValue):void 0,testidPrefix:`${T}-${E}-field`,enableExpressionTree:!0,expressionTreeCollapsible:!0}),_(T,E,M)]})},$=(T,E,A,N,D,B)=>{const M=B[E],O=!!M?.lockedByFilter,z=typeof N[E]=="string"?N[E]:"";return i.jsxs("div",{"data-testid":`${T}-${E}`,style:Dn,children:[i.jsx("label",{style:to,children:d(A)}),wc(M,a)?i.jsx(kc,{label:M.label??"",sourceExpr:M.sourceExpr,onReplace:()=>D(E,M.sourceExpr),t:d,testid:`${T}-${E}-auto`}):i.jsx(Ke,{value:z,onChange:H=>D(E,H),t:d,candidates:l,readOnly:O,placeholder:a&&M?.effectiveValue!=null?String(M.effectiveValue):void 0,testidPrefix:`${T}-${E}-field`}),_(T,E,M)]})},S=(T,E,A,N,D,B)=>{const M=B[E],O=!!M?.lockedByFilter,z=typeof N[E]=="string"?N[E]:"",H=k(M,z),P=H?z:"";return i.jsxs("div",{"data-testid":`${T}-${E}`,style:Dn,children:[i.jsx("label",{style:to,children:d(A)}),i.jsx(Tx,{filled:H,sourceLabel:w(M),onRevert:O?void 0:()=>D(E,void 0),revertLabel:d("layout_editor.page_settings.seo.revert_default"),testid:`${T}-${E}-overlay`,children:i.jsx("div",{"data-testid":`${T}-${E}-input`,style:{minWidth:0},children:i.jsx(Ke,{value:P,onChange:I=>D(E,I),t:d,candidates:l,readOnly:O,placeholder:a&&M?.effectiveValue!=null?String(M.effectiveValue):void 0,testidPrefix:`${T}-${E}-chip`})})}),_(T,E,M)]})},C=(T,E,A,N,D,B,M)=>{const O=M[E],z=typeof D[E]=="string"?D[E]:"",H=k(O,z),P=w(O),I=H?z:"";return i.jsxs("div",{"data-testid":`${T}-${E}`,style:Dn,children:[i.jsxs("div",{style:bw,children:[i.jsx("label",{style:to,children:d(A)}),P?i.jsxs("span",{"data-testid":`${T}-${E}-source-inline`,style:mw,children:["· ",P]}):null]}),i.jsxs("select",{"data-testid":`${T}-${E}-select`,value:I,onChange:L=>B(E,L.target.value),style:vw,children:[i.jsx("option",{value:"",children:a&&O?.effectiveValue!=null&&O.effectiveValue!==""?`${d("layout_editor.page_settings.seo.use_default")} (${String(O.effectiveValue)})`:d("layout_editor.page_settings.seo.use_default")}),N.map(L=>i.jsx("option",{value:L,children:L},L))]}),_(T,E,O)]})};return i.jsxs("div",{"data-testid":c,style:{display:"flex",flexDirection:"column",gap:12},children:[i.jsxs("div",{"data-testid":`${c}-og-section`,style:Sc,children:[i.jsx("div",{style:Cc,children:d("layout_editor.page_settings.seo.og_section")}),i.jsxs("p",{"data-testid":`${c}-intro`,style:yw,children:["ⓘ ",d("layout_editor.page_settings.seo.og_intro")]}),C(c,"type","layout_editor.page_settings.seo.og_type",pw,p,v,m),x(c,"title","layout_editor.page_settings.seo.og_title",p,v,m),x(c,"description","layout_editor.page_settings.seo.og_description",p,v,m),$(c,"image","layout_editor.page_settings.seo.og_image",p,v,m),x(c,"image_alt","layout_editor.page_settings.seo.og_image_alt",p,v,m),i.jsxs("div",{style:Dn,children:[i.jsxs("button",{type:"button","data-testid":`${c}-image-adv-toggle`,"aria-expanded":b,onClick:()=>g(T=>!T),style:ww,children:[b?"▾":"▸"," ",d("layout_editor.page_settings.seo.og_image_adv")]}),b?i.jsxs("div",{"data-testid":`${c}-image-adv`,style:kw,children:[S(c,"image_height","layout_editor.page_settings.seo.og_image_height",p,v,m),S(c,"image_type","layout_editor.page_settings.seo.og_image_type",p,v,m),S(c,"image_secure_url","layout_editor.page_settings.seo.og_image_secure_url",p,v,m)]}):null]}),S(c,"site_name","layout_editor.page_settings.seo.og_site_name",p,v,m),S(c,"locale","layout_editor.page_settings.seo.og_locale",p,v,m),i.jsxs("div",{"data-testid":`${c}-extra`,style:Dn,children:[i.jsx("label",{style:to,children:d("layout_editor.page_settings.seo.og_extra")}),i.jsx(Pr,{value:Array.isArray(p.extra)?p.extra:[],onChange:T=>v("extra",T.length>0?T:void 0),keyField:"property",t:d,candidates:l,testidPrefix:`${c}-extra-editor`})]})]}),i.jsxs("div",{"data-testid":`${c}-tw-section`,style:Sc,children:[i.jsx("div",{style:Cc,children:d("layout_editor.page_settings.seo.tw_section")}),i.jsx("p",{style:{margin:"0 0 6px",fontSize:11,color:"#94a3b8"},children:d("layout_editor.page_settings.seo.tw_fallback_note")}),C("g7le-seo-tw","card","layout_editor.page_settings.seo.tw_card",fw,f,y,h),S("g7le-seo-tw","site","layout_editor.page_settings.seo.tw_site",f,y,h),S("g7le-seo-tw","creator","layout_editor.page_settings.seo.tw_creator",f,y,h),x("g7le-seo-tw","title","layout_editor.page_settings.seo.tw_title",f,y,h),x("g7le-seo-tw","description","layout_editor.page_settings.seo.tw_description",f,y,h),$("g7le-seo-tw","image","layout_editor.page_settings.seo.tw_image",f,y,h),x("g7le-seo-tw","image_alt","layout_editor.page_settings.seo.tw_image_alt",f,y,h),i.jsxs("div",{"data-testid":"g7le-seo-tw-extra",style:Dn,children:[i.jsx("label",{style:to,children:d("layout_editor.page_settings.seo.tw_extra")}),i.jsx(Pr,{value:Array.isArray(f.extra)?f.extra:[],onChange:T=>y("extra",T.length>0?T:void 0),keyField:"name",t:d,candidates:l,testidPrefix:"g7le-seo-tw-extra-editor"})]})]})]})}const Sc={border:"1px solid #e2e8f0",borderRadius:8,padding:12,display:"flex",flexDirection:"column",gap:10},Cc={fontSize:13,fontWeight:600,color:"#0f172a"},yw={margin:0,fontSize:11,color:"#64748b",background:"#f8fafc",borderRadius:6,padding:"6px 8px"},Dn={display:"flex",flexDirection:"column",gap:4},to={fontSize:12,color:"#475569"},bw={display:"flex",alignItems:"center",gap:6},mw={fontSize:11,color:"#94a3b8"},vw={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",minWidth:0,boxSizing:"border-box"},_w={padding:"5px 8px",fontSize:12,border:"1px solid #e2e8f0",borderRadius:6,background:"#f1f5f9",color:"#64748b"},xw={fontSize:11,color:"#7c3aed"},ww={alignSelf:"flex-start",padding:"2px 0",fontSize:12,fontWeight:600,color:"#475569",background:"transparent",border:"none",cursor:"pointer"},kw={display:"flex",flexDirection:"column",gap:8,paddingLeft:14,marginTop:4,minWidth:0},Sw={display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",minWidth:0},Cw={display:"inline-flex",alignItems:"center",maxWidth:"100%",padding:"3px 8px",fontSize:12,color:"#1d4ed8",background:"#eff6ff",border:"1px solid #bfdbfe",borderRadius:6,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},$w={fontSize:11,color:"#94a3b8"},Ew={padding:"2px 8px",fontSize:11,color:"#475569",background:"#fff",border:"1px solid #cbd5e1",borderRadius:6,cursor:"pointer"},Iw=["WebPage","WebSite","ItemList","BreadcrumbList","Organization","Person","CollectionPage","AboutPage","ContactPage","SearchAction"];function Or(e){const t=[],n=(o,r)=>{for(const[s,a]of Object.entries(o)){if(s==="@type"||s==="@context")continue;const l=r?`${r}.${s}`:s;a!==null&&typeof a=="object"&&!Array.isArray(a)?n(a,l):t.push({key:l,value:a==null?"":String(a)})}};return n(e,""),t}function $c(e,t){const n={"@type":e};for(const{key:o,value:r}of t){if(o.trim()==="")continue;const s=o.split(".");let a=n;for(let l=0;lp?Or(e).map(D=>({id:Ss++,...D})):[]),_=u.useCallback((D,B)=>{h(D),y(B),t($c(D,B.map(M=>({key:M.key,value:M.value}))))},[t]),w=u.useCallback(()=>{const D=n,B=typeof D["@type"]=="string"?D["@type"]:m,M=Or(D).map(O=>({id:Ss++,key:O.key,value:o?.[O.key]?.expr??O.value}));return{type:B,rows:M}},[n,o,m]),k=u.useCallback(D=>{if(b(D),D){if(v.length===0&&n&&typeof n=="object"){const B=w();_(B.type,B.rows);return}t($c(m,v.map(B=>({key:B.key,value:B.value}))))}else t(null)},[m,v,n,w,_,t]),x=u.useCallback(()=>{if(!n)return;const D=w();_(D.type,D.rows)},[n,w,_]),$=u.useCallback(()=>{_(m,[...v,{id:Ss++,key:"",value:""}])},[m,v,_]),S=u.useCallback(D=>{_(m,v.filter(B=>B.id!==D))},[m,v,_]),C=u.useCallback((D,B)=>{_(m,v.map(M=>M.id===D?{...M,key:B}:M))},[m,v,_]),T=u.useCallback((D,B)=>{_(m,v.map(M=>M.id===D?{...M,value:B}:M))},[m,v,_]),E=u.useMemo(()=>n?Or(n):[],[n]),A=u.useMemo(()=>s?Or(s):[],[s]),N=v.some(D=>D.key.trim()!==""&&D.value.trim()==="");if(r){const D=s&&typeof s["@type"]=="string"?s["@type"]:"";return i.jsxs("div",{"data-testid":c,style:Ec,children:[i.jsxs("div",{style:Ic,children:[i.jsx("span",{style:Tw,children:"🔒"}),i.jsx("span",{style:{fontSize:13,fontWeight:600},children:d("layout_editor.page_settings.seo.sd_mode")}),i.jsx("span",{"data-testid":`${c}-locked-badge`,style:Dw,children:d("layout_editor.page_settings.seo.sd_filter_locked")})]}),i.jsxs("div",{"data-testid":`${c}-locked`,style:zw,children:[i.jsxs("p",{style:{margin:"0 0 6px",fontSize:12,color:"#475569"},children:["ⓘ ",d("layout_editor.page_settings.seo.sd_filter_locked_note")]}),i.jsxs("div",{"data-testid":`${c}-filtered-block`,children:[D?i.jsxs("div",{style:{fontSize:12,fontWeight:600,marginBottom:4},children:["@type: ",D]}):null,A.map(B=>i.jsxs("div",{"data-testid":`${c}-filtered-row-${B.key}`,style:Ac,children:[i.jsx("code",{style:Tc,children:B.key}),i.jsx("span",{style:Dc,children:B.value})]},B.key))]})]})]})}return i.jsxs("div",{"data-testid":c,style:Ec,children:[i.jsx("div",{style:Ic,children:i.jsx(Mr,{checked:f,onChange:k,testid:`${c}-mode`,label:d("layout_editor.page_settings.seo.sd_manual_toggle")})}),!f&&i.jsxs("div",{"data-testid":`${c}-auto`,style:{marginTop:8},children:[i.jsxs("div",{"data-testid":`${c}-auto-preview`,style:Nw,children:[i.jsxs("div",{style:{fontSize:12,fontWeight:600,marginBottom:6},children:[d("layout_editor.page_settings.seo.sd_auto_title"),n&&typeof n["@type"]=="string"?`: ${n["@type"]}`:"",a?i.jsxs("span",{style:{marginLeft:6,color:"#94a3b8",fontWeight:400},children:["(",a,")"]}):null]}),E.length===0?i.jsx("p",{style:{margin:0,fontSize:12,color:"#94a3b8"},children:d("layout_editor.page_settings.seo.sd_auto_empty")}):E.map(D=>{const B=o?.[D.key];return i.jsxs("div",{"data-testid":`${c}-auto-row-${D.key}`,style:Ac,children:[i.jsx("code",{style:Tc,children:D.key}),B?i.jsxs("span",{"data-testid":`${c}-auto-chip-${D.key}`,style:Mw,title:B.expr,children:["🔗 ",B.label||B.expr]}):i.jsx("span",{style:Dc,children:D.value})]},D.key)})]}),i.jsxs("p",{"data-testid":`${c}-replace-warn`,style:Lw,children:["ⓘ ",d("layout_editor.page_settings.seo.sd_replace_pre_warn")]})]}),f&&i.jsxs("div",{"data-testid":`${c}-manual`,style:{marginTop:8},children:[i.jsxs("p",{"data-testid":`${c}-replace-warn`,style:Pw,children:["⚠ ",d("layout_editor.page_settings.seo.sd_replace_warn")]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("label",{style:{fontSize:12,color:"#475569"},children:d("layout_editor.page_settings.seo.sd_type")}),i.jsx("input",{type:"text","data-testid":`${c}-type`,list:`${c}-type-options`,value:m,onChange:D=>_(D.target.value,v),style:Ow}),i.jsx("datalist",{id:`${c}-type-options`,children:Iw.map(D=>i.jsx("option",{value:D},D))})]}),i.jsx("div",{style:{marginTop:8,display:"flex",flexDirection:"column",gap:6},children:v.map(D=>i.jsxs("div",{"data-testid":`${c}-prop-${D.id}`,style:Bw,children:[i.jsx("input",{type:"text","data-testid":`${c}-prop-key-${D.id}`,value:D.key,placeholder:d("layout_editor.page_settings.seo.sd_prop_key"),onChange:B=>C(D.id,B.target.value),style:{width:160,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:0}}),i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(Ke,{value:D.value,onChange:B=>T(D.id,B),t:d,candidates:l,placeholder:d("layout_editor.page_settings.seo.sd_prop_value"),testidPrefix:`${c}-prop-value-${D.id}`})}),i.jsx("button",{type:"button","data-testid":`${c}-prop-remove-${D.id}`,onClick:()=>S(D.id),title:d("layout_editor.page_settings.seo.remove"),"aria-label":d("layout_editor.page_settings.seo.remove"),style:Ww,children:"✕"})]},D.id))}),i.jsxs("div",{style:{marginTop:8,display:"flex",gap:8},children:[i.jsxs("button",{type:"button","data-testid":`${c}-add`,onClick:$,style:zc,children:["+ ",d("layout_editor.page_settings.seo.sd_add_prop")]}),n?i.jsxs("button",{type:"button","data-testid":`${c}-seed-from-module`,onClick:x,style:zc,children:["↩ ",d("layout_editor.page_settings.seo.sd_seed_from_module")]}):null]}),i.jsxs("p",{"data-testid":`${c}-empty-note`,style:jw,children:["ⓘ ",d("layout_editor.page_settings.seo.sd_empty_note"),N?i.jsxs("span",{style:{color:"#b45309"},children:[" ",d("layout_editor.page_settings.seo.sd_has_empty")]}):null]})]})]})}const Ec={display:"flex",flexDirection:"column"},Ic={display:"flex",alignItems:"center",gap:8},Tw={fontSize:14},Dw={fontSize:11,padding:"2px 6px",borderRadius:4,background:"#f1f5f9",color:"#64748b"},zw={marginTop:8,border:"1px solid #fcd34d",borderRadius:8,padding:10,background:"#fffbeb"},Nw={border:"1px solid #e2e8f0",borderRadius:8,padding:10,background:"#f8fafc"},Ac={display:"flex",gap:8,alignItems:"center",padding:"2px 0"},Tc={fontSize:11,color:"#475569",background:"#fff",padding:"2px 6px",borderRadius:4,minWidth:120},Dc={fontSize:11,color:"#0f172a",fontFamily:"monospace",wordBreak:"break-all"},Mw={display:"inline-flex",alignItems:"center",padding:"2px 8px",fontSize:11,color:"#1d4ed8",background:"#eff6ff",border:"1px solid #bfdbfe",borderRadius:6},Lw={margin:"6px 0 0",fontSize:12,color:"#64748b"},Pw={margin:"0 0 8px",fontSize:12,color:"#b45309",background:"#fffbeb",border:"1px solid #fcd34d",borderRadius:6,padding:"6px 8px"},Ow={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",minWidth:0},Bw={display:"flex",gap:6,alignItems:"flex-start",border:"1px solid #e2e8f0",borderRadius:8,padding:8},Ww={padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"},zc={padding:"5px 10px",fontSize:12,border:"1px dashed #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},jw={margin:"8px 0 0",fontSize:11,color:"#94a3b8"},Nc=new Set(["core_setting","setting","query","route"]);function Hw({vars:e,onChange:t,varCandidates:n,gatingMet:o=!1,candidates:r,t:s,testidPrefix:a="g7le-seo-vars"}){const l=u.useMemo(()=>e&&typeof e=="object"?{...e}:{},[e]),d=u.useMemo(()=>Array.isArray(n)?n:[],[n]),c=u.useMemo(()=>o?d.filter(x=>Nc.has(x.source)):[],[d,o]),p=u.useMemo(()=>o?d.filter(x=>x.source==="data"):[],[d,o]);u.useMemo(()=>new Set(c.map(x=>x.name)),[c]);const f=u.useMemo(()=>new Set(p.map(x=>x.name)),[p]),b=u.useMemo(()=>{const x=new Set;for(const $ of d)Nc.has($.source)&&x.add($.name);return x},[d]),g=u.useMemo(()=>Object.keys(l).filter(x=>!f.has(x)),[l,f]),m=u.useCallback((x,$)=>{const S={...l};$===void 0?delete S[x]:S[x]=$,t(S)},[l,t]),[h,v]=u.useState(""),y=h.trim()!==""&&b.has(h.trim()),_=h.trim()!==""&&Object.prototype.hasOwnProperty.call(l,h.trim()),w=h.trim()!==""&&!y&&!_&&!f.has(h.trim()),k=u.useCallback(()=>{const x=h.trim();x===""||b.has(x)||Object.prototype.hasOwnProperty.call(l,x)||(t({...l,[x]:""}),v(""))},[h,b,l,t]);return i.jsxs("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:10},children:[i.jsx("span",{"data-testid":"g7le-seo-var-list",hidden:!0,"data-gating":o?"1":"0"}),!o&&i.jsxs("div",{"data-testid":`${a}-precondition`,style:Fw,children:["⚠ ",s("layout_editor.page_settings.seo.vars_precondition")]}),c.length>0&&i.jsxs("div",{"data-testid":`${a}-auto-group`,style:Cs,children:[i.jsx("div",{style:$s,children:s("layout_editor.page_settings.seo.vars_auto_group")}),c.map(x=>i.jsxs("div",{"data-testid":`g7le-seo-var-auto-${x.name}`,style:Kw,children:[i.jsx("span",{style:Vw,children:"🔒"}),i.jsx("code",{style:Es,children:x.name}),i.jsxs("span",{style:Uw,children:["〔",s("layout_editor.page_settings.seo.vars_auto"),"·",x.source,"〕"]}),x.owner?.name?i.jsx("span",{style:qw,children:x.owner.name}):null]},x.name))]}),p.length>0&&i.jsxs("div",{"data-testid":`${a}-data-group`,style:Cs,children:[i.jsx("div",{style:$s,children:s("layout_editor.page_settings.seo.vars_data_group")}),p.map(x=>{const $=l[x.name]??"",S=$.trim()==="";return i.jsxs("div",{"data-testid":`g7le-seo-var-data-${x.name}`,style:Mc,children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[i.jsx("code",{style:Es,children:x.name}),x.required?i.jsx("span",{"data-testid":`g7le-seo-var-required-${x.name}`,style:Gw,children:"*"}):null]}),i.jsx(Ke,{value:$,onChange:C=>m(x.name,C??""),t:s,candidates:r,testidPrefix:`g7le-seo-var-data-field-${x.name}`}),x.required&&S?i.jsxs("p",{"data-testid":`g7le-seo-var-empty-warn-${x.name}`,style:Is,children:["⚠ ",s("layout_editor.page_settings.seo.vars_required_empty")]}):null]},x.name)})]}),i.jsxs("div",{"data-testid":`${a}-custom-group`,style:Cs,children:[i.jsx("div",{style:$s,children:s("layout_editor.page_settings.seo.vars_custom_group")}),g.map(x=>i.jsxs("div",{"data-testid":`g7le-seo-var-custom-${x}`,style:Mc,children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[i.jsx("code",{style:Es,children:x}),i.jsx("button",{type:"button","data-testid":`g7le-seo-var-custom-remove-${x}`,onClick:()=>m(x,void 0),title:s("layout_editor.page_settings.seo.remove"),"aria-label":s("layout_editor.page_settings.seo.remove"),style:{marginLeft:"auto",padding:"2px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"},children:"✕"})]}),i.jsx(Ke,{value:l[x]??"",onChange:$=>m(x,$??""),t:s,candidates:r,testidPrefix:`g7le-seo-var-custom-field-${x}`})]},x)),i.jsxs("div",{"data-testid":"g7le-seo-var-add",style:{display:"flex",flexDirection:"column",gap:4,marginTop:6},children:[i.jsxs("div",{style:{display:"flex",gap:6},children:[i.jsx("input",{type:"text","data-testid":"g7le-seo-var-add-name",value:h,placeholder:s("layout_editor.page_settings.seo.vars_add_name"),onChange:x=>v(x.target.value),style:{flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:0}}),i.jsxs("button",{type:"button","data-testid":"g7le-seo-var-add-confirm",onClick:k,disabled:h.trim()===""||y||_,style:Yw,children:["+ ",s("layout_editor.page_settings.seo.vars_add")]})]}),y?i.jsxs("p",{"data-testid":"g7le-seo-var-add-reserved-warn",style:Is,children:["⚠ ",s("layout_editor.page_settings.seo.vars_name_reserved",{name:h.trim()})]}):null,_&&!y?i.jsxs("p",{"data-testid":"g7le-seo-var-add-duplicate-warn",style:Is,children:["⚠ ",s("layout_editor.page_settings.seo.vars_name_duplicate",{name:h.trim()})]}):null,w?i.jsxs("p",{"data-testid":"g7le-seo-var-add-not-provided-hint",style:{margin:0,fontSize:11,color:"#94a3b8"},children:["ⓘ ",s("layout_editor.page_settings.seo.vars_name_not_provided",{name:h.trim()})]}):null]})]}),i.jsxs("p",{style:{margin:0,fontSize:11,color:"#94a3b8"},children:["ⓘ ",s("layout_editor.page_settings.seo.vars_value_hint")]})]})}const Fw={fontSize:12,color:"#b45309",background:"#fffbeb",border:"1px solid #fcd34d",borderRadius:6,padding:"6px 8px"},Cs={border:"1px solid #e2e8f0",borderRadius:8,padding:10,display:"flex",flexDirection:"column",gap:6},$s={fontSize:12,fontWeight:600,color:"#475569"},Kw={display:"flex",alignItems:"center",gap:6,padding:"2px 0"},Mc={display:"flex",flexDirection:"column",border:"1px solid #f1f5f9",borderRadius:6,padding:8},Vw={fontSize:13},Es={fontSize:12,color:"#0f172a",background:"#f1f5f9",padding:"2px 6px",borderRadius:4},Uw={fontSize:11,color:"#64748b"},qw={fontSize:11,color:"#94a3b8"},Gw={color:"#dc2626",fontWeight:700},Is={margin:"4px 0 0",fontSize:11,color:"#b45309"},Yw={padding:"5px 10px",fontSize:12,border:"1px dashed #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"};function Xw({templateIdentifier:e,layout:t,url:n,locale:o,seedContext:r,routeParams:s,settingsSignature:a,t:l,debounceMs:d=400,fetchImpl:c,testidPrefix:p="g7le-seo-bot-preview"}){const[f,b]=u.useState(!0),[g,m]=u.useState(null),[h,v]=u.useState(!1),[y,_]=u.useState(null),w=u.useRef(null),k=u.useRef({templateIdentifier:e,layout:t,url:n,locale:o,seedContext:r,routeParams:s});k.current={templateIdentifier:e,layout:t,url:n,locale:o,seedContext:r,routeParams:s};const x=u.useCallback(async()=>{const T=c??(typeof fetch<"u"?fetch:void 0);if(!T)return;const{templateIdentifier:E,layout:A,url:N,locale:D,seedContext:B,routeParams:M}=k.current;v(!0),_(null);try{const O=`/api/admin/templates/${encodeURIComponent(E)}/editor/seo-bot-preview`,z=await T(O,{method:"POST",credentials:"same-origin",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({layout:A,url:N,locale:D,seed_context:B??{},route_params:M??{}})}),H=await z.json().catch(()=>null);if(!z.ok){_(H?.message??`HTTP ${z.status}`);return}const P=H?.data??null;m(P)}catch(O){_(O instanceof Error?O.message:String(O))}finally{v(!1)}},[c]);u.useEffect(()=>{if(f)return w.current&&clearTimeout(w.current),w.current=setTimeout(()=>{x()},d),()=>{w.current&&clearTimeout(w.current)}},[a,f,d,x]);const $=u.useCallback(()=>{w.current&&clearTimeout(w.current),x()},[x]),S=g?.html??null,C=g?.enabled??!0;return i.jsxs("div",{"data-testid":p,style:Jw,children:[i.jsxs("div",{style:Zw,children:[i.jsxs("button",{type:"button","data-testid":`${p}-toggle`,onClick:()=>b(T=>!T),"aria-expanded":f,style:Qw,children:[f?"▾":"▸"," ",l("layout_editor.page_settings.seo.bot_preview_title")]}),f?i.jsxs("button",{type:"button","data-testid":`${p}-refresh`,onClick:$,disabled:h,style:Rw,children:["⟳ ",l("layout_editor.page_settings.seo.bot_preview_refresh")]}):null]}),f&&i.jsxs("div",{style:{marginTop:8},children:[g&&!C?i.jsxs("p",{"data-testid":`${p}-disabled`,style:e0,children:["ⓘ ",l("layout_editor.page_settings.seo.bot_preview_disabled")]}):i.jsx("div",{"data-testid":`${p}-body`,style:t0,children:h&&!S?i.jsx("p",{style:As,children:l("layout_editor.translation.loading")}):y?i.jsx("p",{"data-testid":`${p}-error`,style:{...As,color:"#dc2626"},children:y}):S==null?i.jsx("p",{style:As,children:l("layout_editor.page_settings.seo.bot_preview_empty")}):i.jsx("pre",{"data-testid":`${p}-code`,style:n0,children:S})}),i.jsxs("p",{"data-testid":`${p}-sample-note`,style:o0,children:["ⓘ ",l("layout_editor.page_settings.seo.bot_preview_sample_note")]})]})]})}const Jw={borderTop:"1px solid #e2e8f0",paddingTop:10,marginTop:12},Zw={display:"flex",alignItems:"center",gap:8},Qw={background:"none",border:"none",cursor:"pointer",fontSize:13,fontWeight:600,color:"#0f172a",padding:0},Rw={marginLeft:"auto",padding:"4px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},e0={margin:0,fontSize:12,color:"#64748b",background:"#f8fafc",border:"1px solid #e2e8f0",borderRadius:6,padding:"8px 10px"},t0={border:"1px solid #e2e8f0",borderRadius:8,background:"#0b1020",padding:0,minHeight:80,overflow:"hidden"},n0={margin:0,padding:12,fontSize:11,lineHeight:1.5,color:"#d1fae5",fontFamily:"monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto"},As={margin:0,padding:12,fontSize:12,color:"#94a3b8"},o0={margin:"8px 0 0",fontSize:11,color:"#94a3b8"};function Lc({option:e,testIdPrefix:t}){const{id:n,friendly:o,source:r}=e;return i.jsxs("span",{style:r0,children:[i.jsx("span",{"data-testid":t?`${t}-title`:void 0,style:i0,children:o??n}),o?i.jsx("span",{"data-testid":t?`${t}-id`:void 0,style:s0,children:n}):null,r?i.jsx("span",{"data-testid":t?`${t}-source`:void 0,style:a0,children:r}):null]})}const r0={display:"inline-flex",alignItems:"baseline",gap:4,flexWrap:"wrap",minWidth:0},i0={fontSize:12,color:"#0f172a"},s0={fontSize:10,color:"#94a3b8",fontFamily:"ui-monospace, monospace"},a0={fontSize:9,fontWeight:600,color:"#7c3aed",background:"#f5f3ff",border:"1px solid #ddd6fe",borderRadius:4,padding:"0 5px",whiteSpace:"nowrap"},l0=["always","hourly","daily","weekly","monthly","yearly","never"];function d0({getValue:e,patch:t,t:n,templateIdentifier:o,candidates:r,availableExtensions:s=[],dataSourceOptions:a=[],previewUrl:l="/",previewLocale:d="ko",seedContext:c,candidatesFetcher:p,ogPreviewFetcher:f,botFetchImpl:b,testidPrefix:g="g7le-seo"}){const m=e("meta",{}).seo,h=m&&typeof m=="object"?m:{},v=u.useCallback((V,te)=>{const be={...e("meta",{})},Ee={...be.seo??{}};te==null||te===""?delete Ee[V]:Ee[V]=te,be.seo=Ee,t("meta",be)},[e,t]),y=h.enabled===!0,_=typeof h.page_type=="string"?h.page_type:"",w=Array.isArray(h.extensions)?h.extensions:[],k=Array.isArray(h.data_sources)?h.data_sources:[],x=w.length>0&&_!=="",[$,S]=u.useState(null),[C,T]=u.useState(null),E=u.useCallback(async(V,te)=>{if(p)return p(V,te);if(typeof fetch>"u")return null;const be=new URLSearchParams;V&&be.set("page_type",V),Array.isArray(te)&&te.length>0&&be.set("extensions",JSON.stringify(te.map(Ue=>({type:Ue.type,id:Ue.id}))));const Ee=be.toString()?`?${be.toString()}`:"",De=await fetch(en(`/api/admin/templates/${encodeURIComponent(o)}/editor/seo-candidates`,"json",null,Ee.replace(/^[?&]+/,"")),{credentials:"same-origin",headers:Ne()}),Se=await De.json().catch(()=>null);return De.ok?Se?.data??null:null},[p,o]),A=u.useMemo(()=>{const be=(e("__editor",{})??{}).original?.meta?.seo;return be&&typeof be=="object"?be:void 0},[e]),N=u.useRef(A);N.current=A;const D=u.useCallback(async V=>{if(f)return f(V);if(typeof fetch>"u")return null;const te=await fetch(`/api/admin/templates/${encodeURIComponent(o)}/editor/seo-og-preview`,{method:"POST",credentials:"same-origin",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({seo:V,own_seo:N.current??null,seed_context:c??{},route_params:{}})}),be=await te.json().catch(()=>null);return te.ok?be?.data??null:null},[f,o,c]),B=u.useMemo(()=>JSON.stringify(w),[w]),M=u.useRef(h);M.current=h,u.useEffect(()=>{let V=!1;return(async()=>{const te=await E(_,w);V||S(te)})(),()=>{V=!0}},[_,B]);const O=u.useMemo(()=>JSON.stringify({og:h.og??null,twitter:h.twitter??null,structured_data:h.structured_data??null}),[h.og,h.twitter,h.structured_data]),z=u.useRef(!1);u.useEffect(()=>{let V=!1;const te=()=>{(async()=>{const Ee=await D(M.current);V||T(Ee)})()};if(!z.current)return z.current=!0,te(),()=>{V=!0};const be=setTimeout(te,180);return()=>{V=!0,clearTimeout(be)}},[_,B,O]);const H=$?.page_types??[],P=$?.toggle_settings??[],I=$?.vars??[],L=u.useMemo(()=>JSON.stringify(h),[h]),F=u.useMemo(()=>e("meta")?{meta:e("meta"),components:e("components",[])}:{meta:{},components:[]},[e]),Y=u.useCallback(V=>{w.some(te=>te.type===V.type&&te.id===V.id)||v("extensions",[...w,{type:V.type,id:V.id}])},[w,v]),K=u.useCallback(V=>{const te=w.filter(be=>!(be.type===V.type&&be.id===V.id));v("extensions",te.length>0?te:void 0)},[w,v]),[X,Z]=u.useState(!1),[ae,oe]=u.useState(""),G=u.useMemo(()=>{const V=ae.trim().toLowerCase();return V?P.filter(te=>`${te.ref} ${te.label??""}`.toLowerCase().includes(V)):P},[P,ae]),ee=typeof h.toggle_setting=="string"?h.toggle_setting:"",ge=u.useCallback(V=>{const be=k.includes(V)?k.filter(Ee=>Ee!==V):[...k,V];v("data_sources",be.length>0?be:void 0)},[k,v]);return i.jsxs("div",{"data-testid":g,style:{display:"flex",flexDirection:"column",gap:14},children:[i.jsxs("div",{style:Bt,children:[i.jsx(Mr,{checked:y,onChange:V=>v("enabled",V),testid:`${g}-enabled`,label:n("layout_editor.page_settings.seo.enabled")}),y?null:i.jsxs("p",{"data-testid":`${g}-disabled-note`,style:no,children:["ⓘ ",n("layout_editor.page_settings.seo.disabled_note")]})]}),i.jsx(Lr,{disabled:!y,testid:`${g}-body`,style:{display:"flex",flexDirection:"column",gap:14},children:i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.page_type")}),H.length>0?i.jsxs("select",{"data-testid":`${g}-page-type`,value:_,onChange:V=>v("page_type",V.target.value),style:Br,children:[i.jsx("option",{value:"",children:n("layout_editor.page_settings.seo.page_type_none")}),H.map(V=>i.jsxs("option",{value:V.value,children:[V.label??V.value,V.owner?.name?` (${V.owner.name})`:""]},V.value))]}):i.jsxs(i.Fragment,{children:[i.jsx("input",{type:"text","data-testid":`${g}-page-type-free`,value:_,placeholder:n("layout_editor.page_settings.seo.page_type_free_placeholder"),onChange:V=>v("page_type",V.target.value),style:Br}),i.jsxs("p",{"data-testid":`${g}-page-type-free-note`,style:no,children:["ⓘ ",n("layout_editor.page_settings.seo.page_type_free_note")]})]})]}),i.jsxs("div",{style:Bt,children:[i.jsxs("label",{style:qt,children:["★ ",n("layout_editor.page_settings.seo.extensions")]}),i.jsxs("div",{"data-testid":`${g}-extensions`,style:{display:"flex",flexWrap:"wrap",gap:6},children:[w.map(V=>i.jsxs("span",{"data-testid":`${g}-extension-${V.type}-${V.id}`,style:Pc,children:[V.name??`${V.type}:${V.id}`,i.jsx("button",{type:"button","data-testid":`${g}-extension-remove-${V.type}-${V.id}`,onClick:()=>K(V),style:Oc,children:"✕"})]},`${V.type}:${V.id}`)),i.jsxs("button",{type:"button","data-testid":`${g}-extension-add`,onClick:()=>Z(V=>!V),style:p0,children:["+ ",n("layout_editor.page_settings.seo.add_extension")]})]}),X&&i.jsx("div",{"data-testid":`${g}-extension-picker`,style:Bc,children:s.length===0?i.jsx("p",{style:no,children:n("layout_editor.page_settings.seo.no_extension_candidate")}):s.map(V=>i.jsx("button",{type:"button","data-testid":`${g}-extension-option-${V.type}-${V.id}`,onClick:()=>{Y(V),Z(!1)},style:Wc,children:V.name??`${V.type}:${V.id}`},`${V.type}:${V.id}`))})]}),!x&&i.jsxs("div",{"data-testid":`${g}-defaults-precondition`,style:u0,children:["⚠ ",n("layout_editor.page_settings.seo.defaults_precondition"),i.jsxs("div",{"data-testid":`${g}-defaults-missing`,style:{fontSize:11,marginTop:4},children:[w.length===0?n("layout_editor.page_settings.seo.missing_extensions"):"",_===""?` ${n("layout_editor.page_settings.seo.missing_page_type")}`:""]})]}),i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.toggle_setting")}),i.jsxs("div",{"data-testid":`${g}-toggle-setting`,children:[ee?i.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center",marginBottom:4},children:[i.jsx("code",{style:Pc,children:ee}),i.jsx("button",{type:"button","data-testid":`${g}-toggle-setting-clear`,onClick:()=>v("toggle_setting",void 0),style:Oc,children:"✕"})]}):null,i.jsx("input",{type:"text","data-testid":`${g}-toggle-setting-search`,value:ae,placeholder:n("layout_editor.page_settings.seo.toggle_setting_search"),onChange:V=>oe(V.target.value),style:Br}),ae.trim()!==""&&i.jsx("div",{"data-testid":`${g}-toggle-setting-results`,style:Bc,children:G.length===0?i.jsx("p",{style:no,children:n("layout_editor.inline_binding.no_results")}):G.map(V=>i.jsx("button",{type:"button","data-testid":`${g}-toggle-setting-option-${V.ref}`,onClick:()=>{v("toggle_setting",V.ref),oe("")},style:Wc,children:V.label??V.ref},V.ref))})]})]}),i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.data_sources")}),i.jsx("p",{style:no,children:n("layout_editor.page_settings.seo.data_sources_hint")}),i.jsx("div",{"data-testid":`${g}-data-sources`,style:{display:"flex",flexDirection:"column",gap:6},children:a.length===0?i.jsx("span",{style:no,children:n("layout_editor.page_settings.seo.data_sources_empty")}):a.map(V=>{const te=k.includes(V.id);return i.jsxs("label",{"data-testid":`${g}-data-source-${V.id}`,style:c0(te),children:[i.jsx("input",{type:"checkbox","data-testid":`${g}-data-source-check-${V.id}`,checked:te,onChange:()=>ge(V.id)}),i.jsx(Lc,{option:V,testIdPrefix:`${g}-data-source-${V.id}`})]},V.id)})})]}),i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.priority")}),i.jsx("input",{type:"range","data-testid":`${g}-priority`,min:0,max:1,step:.1,value:typeof h.priority=="number"?h.priority:.5,onChange:V=>v("priority",Number(V.target.value))}),i.jsx("span",{"data-testid":`${g}-priority-value`,style:{fontSize:12,color:"#475569"},children:typeof h.priority=="number"?h.priority:.5})]}),i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.changefreq")}),i.jsxs("select",{"data-testid":`${g}-changefreq`,value:typeof h.changefreq=="string"?h.changefreq:"",onChange:V=>v("changefreq",V.target.value),style:Br,children:[i.jsx("option",{value:"",children:n("layout_editor.page_settings.seo.use_default")}),l0.map(V=>i.jsx("option",{value:V,children:V},V))]})]}),i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.title")}),i.jsx(_t,{value:typeof h.title=="string"?h.title:"",onChange:V=>v("title",V??""),t:n,candidates:r,testidPrefix:`${g}-title`,enableExpressionTree:!0,expressionTreeCollapsible:!0})]}),i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.description")}),i.jsx(_t,{value:typeof h.description=="string"?h.description:"",onChange:V=>v("description",V??""),t:n,candidates:r,testidPrefix:`${g}-description`,enableExpressionTree:!0,expressionTreeCollapsible:!0})]}),i.jsx(hw,{og:h.og,twitter:h.twitter,onChangeOg:V=>v("og",Object.keys(V).length>0?V:void 0),onChangeTwitter:V=>v("twitter",Object.keys(V).length>0?V:void 0),ogPreview:C?.og,twitterPreview:C?.twitter,defaultsAvailable:C?.defaultsAvailable??!1,candidates:r,t:n}),i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.structured_data")}),i.jsx(Aw,{value:h.structured_data,onChange:V=>v("structured_data",V??void 0),autoBlock:C?.structured?.autoBlock,autoMeta:C?.structured?.autoMeta,lockedByFilter:C?.structured?.lockedByFilter,filteredBlock:C?.structured?.filteredBlock,pageType:_,candidates:r,t:n})]}),i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.vars")}),i.jsx(Hw,{vars:h.vars,onChange:V=>v("vars",Object.keys(V).length>0?V:void 0),varCandidates:I,gatingMet:x,candidates:r,t:n})]}),i.jsx(Xw,{templateIdentifier:o,layout:F,url:l,locale:d,seedContext:c,settingsSignature:L,t:n,fetchImpl:b})]})})]})}const Bt={display:"flex",flexDirection:"column",gap:4},qt={fontSize:12,fontWeight:600,color:"#334155"},Br={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",minWidth:0,boxSizing:"border-box"},no={margin:"4px 0 0",fontSize:11,color:"#94a3b8"},c0=e=>({display:"flex",alignItems:"center",gap:8,padding:"6px 10px",fontSize:12,border:`1px solid ${e?"#3b82f6":"#e2e8f0"}`,borderRadius:8,background:e?"#eff6ff":"#fff",cursor:"pointer",minWidth:0}),u0={fontSize:12,color:"#b45309",background:"#fffbeb",border:"1px solid #fcd34d",borderRadius:6,padding:"8px 10px"},Pc={display:"inline-flex",alignItems:"center",gap:4,fontSize:11,padding:"3px 8px",borderRadius:999,background:"#eef2ff",color:"#3730a3"},Oc={border:"none",background:"transparent",cursor:"pointer",color:"#6366f1",fontSize:11,padding:0},p0={fontSize:11,padding:"3px 10px",borderRadius:999,border:"1px dashed #cbd5e1",background:"#f8fafc",color:"#475569",cursor:"pointer"},Bc={marginTop:4,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",padding:6,display:"flex",flexDirection:"column",gap:2},Wc={textAlign:"left",border:"none",background:"transparent",cursor:"pointer",padding:"5px 8px",borderRadius:4,fontSize:12,color:"#0f172a"},f0={setState:"state",loadFromLocalStorage:"state",saveToLocalStorage:"state",navigate:"nav",openWindow:"nav",navigateBack:"nav",navigateForward:"nav",replaceUrl:"nav",toast:"notify",openModal:"notify",closeModal:"notify",showAlert:"notify",setError:"notify",refetchDataSource:"data",appendDataSource:"data",updateDataSource:"data",apiCall:"data",scrollIntoView:"etc",login:"etc",loginTwoFactor:"etc",loginTwoFactorResend:"etc",logout:"etc",setLocale:"locale",emitEvent:"etc",conditions:"flow",sequence:"flow",parallel:"flow",switch:"flow",suppress:"flow",showErrorPage:"error"},g0={state:"layout_editor.action.group.state",nav:"layout_editor.action.group.nav",notify:"layout_editor.action.group.notify",data:"layout_editor.action.group.data",locale:"layout_editor.action.group.locale",etc:"layout_editor.action.group.etc",flow:"layout_editor.action.group.flow",error:"layout_editor.action.group.error",extension:"layout_editor.action.group.extension"},h0={init:["state","data","notify","nav","locale","etc","flow","error","extension"],component:["nav","notify","data","state","locale","etc","flow","error","extension"]};function y0(e,t){const n=e?.[t];if(n&&typeof n=="object"){const o=n.__source;if(o&&typeof o=="object")return o}return null}function b0(e,t){return!e||e.kind==="core"?t("layout_editor.action.source_core"):e.id??t(`layout_editor.action.source_${e.kind}`)}function jc(e,t,n){return typeof e!="string"?n:e.startsWith("$t:")?t(e.slice(3)):e}function m0({recipes:e,t,onAdd:n,context:o="init",testIdPrefix:r="g7le-action-add"}){const[s,a]=u.useState(!1),[l,d]=u.useState(""),c=u.useMemo(()=>ko(e),[e]),p=u.useMemo(()=>{const f=h0[o],b=new Map;for(const m of c){const h=y0(e,m.id),y=h!=null&&h.kind!=="core"?"extension":f0[m.id]??"etc",_=b.get(y)??[];_.push({recipe:m,source:h}),b.set(y,_)}const g=l.trim().toLowerCase();return f.map(m=>{let h=b.get(m)??[];return g&&(h=h.filter(({recipe:v})=>jc(v.label,t,v.id).toLowerCase().includes(g)||v.id.toLowerCase().includes(g)||v.build.handler.toLowerCase().includes(g))),{groupKey:m,items:h}}).filter(m=>m.items.length>0)},[c,e,o,l,t]);return c.length===0?i.jsx("div",{"data-testid":`${r}-empty`,style:I0,children:t("layout_editor.action.no_recipes")}):i.jsxs("div",{className:r,"data-testid":r,style:{minWidth:0},children:[i.jsxs("button",{type:"button","data-testid":`${r}-toggle`,onClick:()=>a(f=>!f),style:v0,children:[t("layout_editor.action.add_action")," ▾"]}),s?i.jsxs("div",{"data-testid":`${r}-list`,style:_0,children:[i.jsx("input",{type:"text","data-testid":`${r}-search`,value:l,placeholder:t("layout_editor.action.add_search"),onChange:f=>d(f.target.value),style:x0}),p.map(({groupKey:f,items:b})=>i.jsxs("div",{"data-testid":`${r}-group-${f}`,children:[i.jsxs("div",{style:w0,children:["━━ ",t(g0[f]??f)," ━━"]}),b.map(({recipe:g,source:m})=>i.jsxs("button",{type:"button","data-testid":`g7le-init-action-spec-${g.id}`,onClick:()=>{n(Sr(g,{})),a(!1),d("")},style:k0,children:[i.jsx("span",{style:S0,children:jc(g.label,t,g.id)}),i.jsxs("span",{"data-testid":`g7le-init-action-spec-source-${g.id}`,style:C0,children:["〔",b0(m,t),"〕"]}),i.jsx("code",{style:$0,children:g.build.handler})]},g.id))]},f)),p.length===0?i.jsx("div",{"data-testid":`${r}-no-match`,style:E0,children:t("layout_editor.action.add_no_match")}):null]}):null]})}const v0={padding:"6px 12px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},_0={marginTop:6,border:"1px solid #cbd5e1",borderRadius:8,background:"#fff",maxHeight:320,overflowY:"auto",padding:8},x0={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,marginBottom:6,boxSizing:"border-box"},w0={fontSize:11,fontWeight:700,color:"#94a3b8",padding:"6px 4px 2px"},k0={display:"flex",alignItems:"center",gap:6,width:"100%",textAlign:"left",padding:"6px 8px",fontSize:12,border:"none",background:"transparent",cursor:"pointer",borderRadius:6},S0={flex:1,minWidth:0,color:"#0f172a"},C0={fontSize:10,color:"#64748b",whiteSpace:"nowrap"},$0={fontSize:10,color:"#cbd5e1",fontFamily:"monospace",whiteSpace:"nowrap"},E0={fontSize:12,color:"#94a3b8",padding:"8px 4px"},I0={fontSize:12,color:"#94a3b8",padding:"8px 0"};function A0(e,t){return t.startsWith("$t:")?e(t.slice(3)):t}function T0({action:e,recipe:t,values:n={},t:o,missingRequired:r=!1,showCodeButton:s=!0,testIdPrefix:a="g7le-action-preview"}){const[l,d]=u.useState(!1),c=t?Kd(t,n,p=>A0(o,p)):typeof e.handler=="string"?e.handler:o("layout_editor.action.advanced_action");return i.jsxs("div",{className:a,"data-testid":a,style:D0,children:[r?i.jsxs("span",{"data-testid":`${a}-missing`,style:N0,children:["⚠ ",o("layout_editor.action.summary_missing_required")]}):i.jsx("span",{"data-testid":`${a}-summary`,style:z0,children:c}),s?i.jsx("button",{type:"button","data-testid":`${a}-code-toggle`,onClick:()=>d(p=>!p),style:M0,"aria-expanded":l,"aria-label":o("layout_editor.action.view_code"),children:""}):null,s&&l?i.jsx("pre",{"data-testid":`${a}-code`,style:L0,children:JSON.stringify(e,null,2)}):null]})}const D0={display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,minWidth:0},z0={flex:1,minWidth:0,fontSize:12,color:"#475569"},N0={flex:1,minWidth:0,fontSize:12,color:"#b45309"},M0={border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",fontSize:11,padding:"2px 6px",whiteSpace:"nowrap"},L0={flexBasis:"100%",margin:"6px 0 0",padding:8,background:"#0f172a",color:"#e2e8f0",borderRadius:6,fontSize:11,overflow:"auto"},Hc="__g7le_custom__";function Wr({value:e,onChange:t,candidates:n,placeholder:o,testid:r,t:s,bindingCandidates:a}){const l=e==null?"":String(e),d=Array.isArray(n)&&n.length>0,c=d&&n.some(b=>b.value===l),[p,f]=u.useState(!d||l!==""&&!c);return u.useEffect(()=>{l!==""&&d&&!c&&f(!0)},[l,d,c]),d&&!p?i.jsxs("div",{style:Uc,children:[i.jsxs("select",{className:"g7le-widget g7le-widget--picker","data-testid":r,value:c?l:"",onChange:b=>{const g=b.target.value;if(g===Hc){f(!0);return}t(g===""?void 0:g)},style:{...Kc,flex:1,minWidth:0},children:[i.jsx("option",{value:"",children:s("layout_editor.control.default")}),n.map(b=>i.jsx("option",{value:b.value,children:b.label},b.value)),i.jsx("option",{value:Hc,children:s("layout_editor.recipe.custom_input")})]}),i.jsx("button",{type:"button","data-testid":`${r}-to-custom`,title:s("layout_editor.recipe.custom_input"),"aria-label":s("layout_editor.recipe.custom_input"),onClick:()=>f(!0),style:qc,children:"✎"})]}):i.jsxs("div",{style:Uc,children:[i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(Ke,{value:l,onChange:b=>t(b===""?void 0:b),t:s,candidates:a,placeholder:o,testidPrefix:`${r}-input`})}),d&&i.jsx("button",{type:"button","data-testid":`${r}-pick`,title:s("layout_editor.recipe.pick_from_list"),onClick:()=>{f(!1),t(void 0)},style:qc,children:"≡"})]})}function P0({value:e,onChange:t,candidates:n,t:o,bindingCandidates:r}){return i.jsx(Wr,{value:e,onChange:t,candidates:n,placeholder:o("layout_editor.recipe.page_placeholder"),testid:"g7le-widget-page-picker",t:o,bindingCandidates:r})}function Fc({value:e,onChange:t,candidates:n,t:o,bindingCandidates:r}){return i.jsx(Wr,{value:e,onChange:t,candidates:n,placeholder:o("layout_editor.recipe.datasource_placeholder"),testid:"g7le-widget-datasource-picker",t:o,bindingCandidates:r})}function Ts({value:e,onChange:t,candidates:n,t:o,bindingCandidates:r}){return i.jsx(Wr,{value:e,onChange:t,candidates:n,placeholder:o("layout_editor.recipe.state_key_placeholder"),testid:"g7le-widget-state-key-picker",t:o,bindingCandidates:r})}function O0({value:e,onChange:t,candidates:n,t:o,bindingCandidates:r}){return i.jsx(Wr,{value:e,onChange:t,candidates:n,placeholder:o("layout_editor.recipe.modal_placeholder"),testid:"g7le-widget-modal-picker",t:o,bindingCandidates:r})}function B0({value:e,onChange:t,t:n,bindingCandidates:o}){const r=typeof e=="string"?e:e==null?"":String(e);return i.jsx("div",{className:"g7le-widget g7le-widget--i18n-text","data-testid":"g7le-widget-i18n-text",style:{flex:1,minWidth:100,width:"100%"},children:i.jsx(_t,{value:r,onChange:s=>t(s===""?void 0:s),t:n,placeholder:n("layout_editor.recipe.i18n_text_placeholder"),testidPrefix:"g7le-widget-i18n-text-field",candidates:o,enableExpressionTree:!0,expressionTreeCollapsible:!0})})}function W0({value:e,onChange:t,candidates:n,t:o}){const r=e==null?"":String(e),s=r.split(",").map(d=>d.trim()).filter(Boolean),a=Array.isArray(n)&&n.length>0,l=d=>{if(!d)return;const c=[...s,d];t(c.join(", "))};return i.jsxs("div",{className:"g7le-widget g7le-widget--binding-list","data-testid":"g7le-widget-binding-list",style:{display:"flex",flexDirection:"column",gap:4,width:"100%"},children:[i.jsx("input",{type:"text","data-testid":"g7le-widget-binding-list-input",value:r,placeholder:o("layout_editor.recipe.datasource_placeholder"),onChange:d=>t(d.target.value===""?void 0:d.target.value),style:Vc}),a?i.jsxs("select",{className:"g7le-widget g7le-widget--picker","data-testid":"g7le-widget-binding-list-add",value:"",onChange:d=>{l(d.target.value),d.target.value=""},style:{...Kc,minWidth:0},children:[i.jsx("option",{value:"",children:o("layout_editor.recipe.pick_from_list")}),n.map(d=>i.jsx("option",{value:d.value,children:d.label},d.value))]}):null]})}function j0({value:e,onChange:t}){const n=e==null?"":String(e);return i.jsx("input",{type:"text",className:"g7le-widget g7le-widget--text","data-testid":"g7le-widget-text",value:n,onChange:o=>t(o.target.value===""?void 0:o.target.value),style:Vc})}const Kc={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",minWidth:140,width:"100%"},Vc={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:100,width:"100%"},Uc={display:"flex",gap:4,alignItems:"flex-start",width:"100%"},qc={padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"};function H0(e){if(e==null)return"null";if(Array.isArray(e))return"list";switch(typeof e){case"number":return"number";case"boolean":return"boolean";case"string":return"string";default:return"object"}}function Gc(e){switch(e){case"string":return"";case"number":return 0;case"boolean":return!1;case"null":return null;case"list":return[];case"object":return{};default:return null}}function Ds(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}function F0(e,t,n){return t.includes(n)?"self":e.includes(n)?"inherited":"self"}function K0(e){const t=e.state&&typeof e.state=="object"&&Object.keys(e.state).length>0,n=e.initLocal&&typeof e.initLocal=="object"?e.initLocal:void 0;if(!t)return{initLocal:n??{},migrated:!1};const o={...e.state};if(n)for(const[r,s]of Object.entries(n))o[r]=s;return{initLocal:o,migrated:!0}}const Yc=[{kind:"string",labelKey:"layout_editor.initstate.kind_string"},{kind:"number",labelKey:"layout_editor.initstate.kind_number"},{kind:"boolean",labelKey:"layout_editor.initstate.kind_boolean"},{kind:"null",labelKey:"layout_editor.initstate.kind_null"},{kind:"list",labelKey:"layout_editor.initstate.kind_list"},{kind:"object",labelKey:"layout_editor.initstate.kind_object"}];function zn({value:e,onChange:t,t:n,path:o,scope:r,depth:s=0,renderStringLeaf:a}){const l=H0(e),d=c=>{t(Gc(c))};return i.jsxs("div",{className:"g7le-initstate-value",style:{paddingLeft:s>0?12:0,minWidth:0},children:[i.jsxs("div",{style:U0,children:[i.jsx("select",{"data-testid":`g7le-initstate-type-${o}`,value:l,onChange:c=>d(c.target.value),style:Xc,children:Yc.map(({kind:c,labelKey:p})=>i.jsx("option",{value:c,children:n(p)},c))}),l==="string"?a?i.jsx("div",{style:{flex:1,minWidth:0},children:a({value:String(e??""),onChange:c=>t(c),testidPrefix:`g7le-initstate-value-${o}`})}):i.jsx("input",{type:"text","data-testid":`g7le-initstate-value-${o}`,value:String(e??""),onChange:c=>t(c.target.value),style:Jc}):l==="number"?i.jsx("input",{type:"number","data-testid":`g7le-initstate-value-${o}`,value:typeof e=="number"?e:"",onChange:c=>{const p=parseFloat(c.target.value);t(Number.isNaN(p)?0:p)},style:Jc}):l==="boolean"?i.jsx(Mr,{checked:!!e,onChange:t,testid:`g7le-initstate-value-${o}`,label:n(e?"layout_editor.overlay.on":"layout_editor.overlay.off")}):l==="null"?i.jsx("span",{"data-testid":`g7le-initstate-value-${o}`,style:q0,children:"null"}):null]}),l==="list"?i.jsxs("div",{style:Zc,children:[e.map((c,p)=>i.jsxs("div",{style:G0,children:[i.jsxs("span",{style:Y0,children:["[",p,"]"]}),i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(zn,{value:c,onChange:f=>{const b=e.slice();b[p]=f,t(b)},t:n,path:`${o}.${p}`,scope:r,depth:s+1,renderStringLeaf:a})}),i.jsx("button",{type:"button","data-testid":`g7le-initstate-item-remove-${o}.${p}`,onClick:()=>t(e.filter((f,b)=>b!==p)),style:Qc,children:"✕"})]},p)),i.jsxs("button",{type:"button","data-testid":`g7le-initstate-item-add-${o}`,onClick:()=>t([...e,""]),style:Rc,children:["+ ",n("layout_editor.initstate.add_item")]})]}):null,l==="object"?i.jsx(V0,{value:e,onChange:t,t:n,path:o,scope:r,depth:s+1,renderStringLeaf:a}):null]})}function V0({value:e,onChange:t,t:n,path:o,scope:r,depth:s,renderStringLeaf:a}){const[l,d]=u.useState(""),[c,p]=u.useState("string"),[f,b]=u.useState(null),g=Object.entries(e),m=()=>{const h=l.trim();if(!h){b(n("layout_editor.initstate.name_required"));return}if(!Ds(h)){b(n("layout_editor.initstate.name_invalid"));return}if(h in e){b(n("layout_editor.initstate.name_duplicate"));return}t({...e,[h]:Gc(c)}),d(""),b(null)};return i.jsxs("div",{style:Zc,children:[g.map(([h,v])=>i.jsxs("div",{style:X0,children:[i.jsx("code",{style:J0,children:h}),i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(zn,{value:v,onChange:y=>t({...e,[h]:y}),t:n,path:`${o}.${h}`,scope:r,depth:s,renderStringLeaf:a})}),i.jsx("button",{type:"button","data-testid":`g7le-initstate-subremove-${o}.${h}`,onClick:()=>{const y={...e};delete y[h],t(y)},style:Qc,children:"✕"})]},h)),i.jsxs("div",{style:Z0,children:[i.jsx("input",{type:"text","data-testid":`g7le-initstate-subkey-input-${o}`,value:l,placeholder:n("layout_editor.initstate.subkey_name"),onChange:h=>{d(h.target.value),f&&b(null)},onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),m())},"aria-invalid":f?!0:void 0,style:{...Q0,...f?R0:null}}),i.jsx("select",{"data-testid":`g7le-initstate-subkey-kind-${o}`,value:c,onChange:h=>p(h.target.value),"aria-label":n("layout_editor.initstate.value_kind"),style:Xc,children:Yc.map(({kind:h,labelKey:v})=>i.jsx("option",{value:h,children:n(v)},h))}),i.jsxs("button",{type:"button","data-testid":`g7le-initstate-subkey-add-${o}`,onClick:m,style:Rc,children:["+ ",n("layout_editor.initstate.add_subkey")]})]}),f?i.jsx("p",{"data-testid":`g7le-initstate-subkey-error-${o}`,style:ek,children:f}):null]})}const U0={display:"flex",gap:6,alignItems:"center",minWidth:0},Xc={padding:"4px 6px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,color:"#64748b"},Jc={flex:1,minWidth:0,padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},q0={fontSize:12,color:"#94a3b8",fontFamily:"monospace"},Zc={display:"flex",flexDirection:"column",gap:6,marginTop:6,paddingLeft:8,borderLeft:"2px solid #e2e8f0"},G0={display:"flex",gap:6,alignItems:"flex-start",minWidth:0},Y0={fontSize:11,color:"#94a3b8",minWidth:28,paddingTop:4},X0={display:"flex",gap:6,alignItems:"flex-start",minWidth:0},J0={fontSize:11,color:"#475569",fontFamily:"monospace",minWidth:72,paddingTop:4},Qc={border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12},Rc={alignSelf:"flex-start",padding:"2px 8px",fontSize:11,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},Z0={display:"flex",gap:6,alignItems:"center"},Q0={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6},R0={border:"1px solid #dc2626"},ek={margin:"2px 0 0",fontSize:11,color:"#dc2626"},tk=new Set(["text","data-chip","number"]),nk=new Set(["select","toggle","page-picker","datasource-picker","state-key-picker","modal-picker","component-target-picker","tag-input","locale-picker","i18n-text","segmented","slider","color","image"]);function ok(e,t,n){return typeof e!="string"?n:e.startsWith("$t:")?t(e.slice(3)):e}function rk(e,t){if(e==="page-picker")return t.pageCandidates;if(e==="datasource-picker")return t.dataSourceCandidates;if(e==="state-key-picker")return t.stateKeyCandidates;if(e==="modal-picker")return t.modalCandidates}function ik({param:e,value:t,t:n,pools:o,onChange:r,testIdPrefix:s,renderActionList:a,siblingValues:l}){const d=ok(e.label,n,e.key);if(e.advanced)return i.jsxs("div",{"data-testid":`${s}-locked-${e.key}`,style:hk,children:[i.jsx("span",{style:yk,children:d}),i.jsxs("span",{style:bk,children:["[",n("layout_editor.action.advanced"),"] ",n("layout_editor.init_actions.advanced_param_hint")]})]});if(e.widget==="action-list"&&a){const f=Array.isArray(t)?t.filter(b=>!!b&&typeof b=="object"):[];return i.jsxs("div",{"data-testid":`${s}-param-${e.key}`,style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsx("span",{style:oo,children:d}),a(f,b=>r(b.length===0?void 0:b),`${s}-${e.key}`,e.key)]})}if(e.widget==="branch-list"&&a){const f=Array.isArray(t)?t.filter(b=>!!b&&typeof b=="object"):[];return i.jsxs("div",{"data-testid":`${s}-param-${e.key}`,style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsx("span",{style:oo,children:d}),i.jsx(sk,{branches:f,onChange:b=>r(b.length===0?void 0:b),t:n,pools:o,renderActionList:a,testIdPrefix:`${s}-${e.key}`})]})}if(e.widget==="key-value")return i.jsxs("div",{"data-testid":`${s}-param-${e.key}`,style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsx("span",{style:oo,children:d}),i.jsx(uk,{value:t,onChange:r,t:n,candidates:o.bindingCandidates,testIdPrefix:`${s}-kv-${e.key}`})]});if(e.widget==="state-key-value")return i.jsxs("div",{"data-testid":`${s}-param-${e.key}`,style:{display:"flex",flexDirection:"column",gap:4},children:[i.jsx("span",{style:oo,children:d}),i.jsx(pk,{value:t,onChange:r,t:n,candidates:o.bindingCandidates,stateKeyCandidates:o.stateKeyCandidates,param:e,siblingTarget:l?.target,testIdPrefix:`${s}-skv-${e.key}`})]});if(tk.has(e.widget??"")||!nk.has(e.widget??""))return i.jsxs("div",{"data-testid":`${s}-param-${e.key}`,style:tu,children:[i.jsx("span",{style:oo,children:d}),i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(Ke,{value:typeof t=="string"?t:t==null?"":String(t),onChange:f=>r(f===""?void 0:f),t:n,candidates:o.bindingCandidates,placeholder:e.widget==="number"?n("layout_editor.action_param.number_placeholder"):void 0,testidPrefix:`${s}-chip-${e.key}`})})]});const p=Tn(e.widget);return i.jsxs("div",{"data-testid":`${s}-param-${e.key}`,style:tu,children:[i.jsx("span",{style:oo,children:d}),i.jsx("div",{style:{flex:1,minWidth:0},children:p?i.jsx(p,{control:{...e},value:t,onChange:r,t:n,candidates:rk(e.widget,o),bindingCandidates:o.bindingCandidates}):i.jsx(Ke,{value:typeof t=="string"?t:t==null?"":String(t),onChange:f=>r(f===""?void 0:f),t:n,candidates:o.bindingCandidates,testidPrefix:`${s}-chip-${e.key}`})})]})}function sk({branches:e,onChange:t,t:n,pools:o,renderActionList:r,testIdPrefix:s}){const a=b=>Array.isArray(b)?b.filter(g=>!!g&&typeof g=="object"):b&&typeof b=="object"?[b]:[],l=b=>{if(b.length!==0)return b.length===1?b[0]:b},d=(b,g)=>{const m=e.slice();m[b]=g,t(m)},c=b=>{t(e.filter((g,m)=>m!==b))},p=(b,g)=>{if(g<0||g>=e.length)return;const m=e.slice(),[h]=m.splice(b,1);m.splice(g,0,h),t(m)},f=()=>{t([...e,{if:"",then:void 0}])};return i.jsxs("div",{"data-testid":`${s}-branches`,style:{display:"flex",flexDirection:"column",gap:8},children:[e.map((b,g)=>{const m=typeof b.if=="string"?b.if:"",h=a(b.then);return i.jsxs("div",{"data-testid":`${s}-branch-${g}`,style:ak,children:[i.jsxs("div",{style:lk,children:[i.jsxs("span",{style:dk,children:[n(m?"layout_editor.action_recipe.conditions.branch_when":"layout_editor.action_recipe.conditions.branch_else")," ",g+1]}),i.jsxs("span",{style:{display:"flex",gap:4},children:[i.jsx("button",{type:"button","data-testid":`${s}-branch-${g}-up`,onClick:()=>p(g,g-1),disabled:g===0,style:zs,title:n("layout_editor.action_recipe.conditions.move_up"),children:"↑"}),i.jsx("button",{type:"button","data-testid":`${s}-branch-${g}-down`,onClick:()=>p(g,g+1),disabled:g===e.length-1,style:zs,title:n("layout_editor.action_recipe.conditions.move_down"),children:"↓"}),i.jsx("button",{type:"button","data-testid":`${s}-branch-${g}-remove`,onClick:()=>c(g),style:zs,title:n("layout_editor.action_recipe.conditions.remove_branch"),children:"✕"})]})]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[i.jsx("span",{style:eu,children:n("layout_editor.action_recipe.conditions.param_if")}),i.jsx(Ke,{value:m,onChange:v=>d(g,{...b,if:v}),t:n,candidates:o.bindingCandidates,testidPrefix:`${s}-branch-${g}-if`})]}),i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:3},children:[i.jsx("span",{style:eu,children:n("layout_editor.action_recipe.conditions.param_then")}),r(h,v=>d(g,{...b,then:l(v)}),`${s}-branch-${g}-then`)]})]},g)}),i.jsxs("button",{type:"button","data-testid":`${s}-add-branch`,onClick:f,style:ck,children:["+ ",n("layout_editor.action_recipe.conditions.add_branch")]})]})}const ak={border:"1px solid #e2e8f0",borderRadius:6,padding:8,display:"flex",flexDirection:"column",gap:6,background:"#f8fafc"},lk={display:"flex",justifyContent:"space-between",alignItems:"center"},dk={fontSize:12,fontWeight:700,color:"#475569"},eu={fontSize:11,color:"#64748b"},zs={border:"1px solid #cbd5e1",background:"#fff",borderRadius:4,width:22,height:22,cursor:"pointer",fontSize:12,lineHeight:"1",color:"#475569"},ck={border:"1px dashed #94a3b8",background:"#fff",borderRadius:6,padding:"6px 10px",cursor:"pointer",fontSize:12,color:"#475569",alignSelf:"flex-start"};function uk({value:e,onChange:t,t:n,candidates:o,testIdPrefix:r,renderKeyInput:s}){const a=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e).map(([l,d])=>({key:l,value:typeof d=="string"?d:d==null?"":String(d)})):[];return i.jsx(Pr,{value:a,onChange:l=>{const d={};for(const c of l)c.key.trim()!==""&&(d[c.key]=c.value??"");t(Object.keys(d).length===0?void 0:d)},keyField:"key",valueField:"value",t:n,candidates:o,testidPrefix:r,keyPlaceholder:n("layout_editor.action_param.key_placeholder"),valuePlaceholder:n("layout_editor.action_param.value_placeholder"),addLabel:n("layout_editor.action_param.add_pair"),renderKeyInput:s})}function pk({value:e,onChange:t,t:n,candidates:o,stateKeyCandidates:r,param:s,siblingTarget:a,testIdPrefix:l}){const d=e&&typeof e=="object"&&!Array.isArray(e)?Object.entries(e):[],c=typeof a=="string"?a:"";if((c.startsWith("_local.")||c.startsWith("global.")||c.startsWith("$parent._local.")||c.startsWith("$root._local."))&&d.length===1&&d[0][0]==="value"){const y=d[0][1];return i.jsx("div",{"data-testid":`${l}-path-value`,style:{display:"flex",flexDirection:"column",gap:4},children:i.jsx(zn,{value:y,onChange:_=>t(_===void 0?void 0:{value:_}),t:n,path:"value",scope:`${l}-path-value-val`,renderStringLeaf:_=>i.jsx(Ke,{value:_.value,onChange:_.onChange,t:n,candidates:o,testidPrefix:_.testidPrefix})})})}const b=(y,_)=>{const w={};for(const[k,x]of d)w[k]=k===y?_:x;t(Object.keys(w).length===0?void 0:w)},g=y=>{const _={};for(const[w,k]of d)w!==y&&(_[w]=k);t(Object.keys(_).length===0?void 0:_)},[m,h]=u.useState(""),v=()=>{const y=m.trim();if(y===""||d.some(([w])=>w===y))return;const _={};for(const[w,k]of d)_[w]=k;_[y]="",t(_),h("")};return i.jsxs("div",{"data-testid":l,style:{display:"flex",flexDirection:"column",gap:6},children:[d.map(([y,_])=>i.jsxs("div",{"data-testid":`${l}-row-${y}`,style:{display:"flex",gap:6,alignItems:"flex-start",border:"1px solid #e2e8f0",borderRadius:8,padding:8},children:[i.jsxs("div",{style:{flex:1,minWidth:0,display:"flex",flexDirection:"column",gap:6},children:[i.jsx("div",{style:{minWidth:0},children:i.jsx(Ts,{control:{...s},value:y,onChange:w=>{const k=w==null?"":String(w);if(k===""||k===y||d.some(([$])=>$===k))return;const x={};for(const[$,S]of d)x[$===y?k:$]=S;t(x)},t:n,candidates:r})}),i.jsx("div",{style:{minWidth:0},children:i.jsx(zn,{value:_,onChange:w=>b(y,w),t:n,path:y,scope:`${l}-val`,renderStringLeaf:w=>i.jsx(Ke,{value:w.value,onChange:w.onChange,t:n,candidates:o,testidPrefix:w.testidPrefix})})})]}),i.jsx("button",{type:"button","data-testid":`${l}-remove-${y}`,onClick:()=>g(y),title:n("layout_editor.page_settings.seo.remove"),"aria-label":n("layout_editor.page_settings.seo.remove"),style:{flex:"0 0 auto",padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"},children:"✕"})]},y)),i.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(Ts,{control:{...s},value:m,onChange:y=>h(y==null?"":String(y)),t:n,candidates:r})}),i.jsxs("button",{type:"button","data-testid":`${l}-add`,onClick:v,style:{flex:"0 0 auto",padding:"5px 10px",fontSize:12,border:"1px dashed #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},children:["+ ",n("layout_editor.action_param.add_pair")]})]})]})}function Ns({raw:e,recipe:t,values:n,t:o,pools:r,onChange:s,testIdPrefix:a,renderActionList:l}){const d=(c,p)=>{const f={...n,[c]:p},b=Sr(t,f),g=cs(e);s(g?Vd(b,g):b)};return i.jsx(i.Fragment,{children:t.params.filter(c=>fk(c,n)).map(c=>i.jsx(ik,{param:c,value:n[c.key],t:o,pools:r,onChange:p=>d(c.key,p),testIdPrefix:a,renderActionList:l,siblingValues:n},c.key))})}function fk(e,t){const n=e.dependsOn;return!n||typeof n!="object"||typeof n.param!="string"?!0:t[n.param]===n.equals}function gk({raw:e,t,onChange:n,testIdPrefix:o,candidates:r}){const[s,a]=u.useState(!1);return i.jsxs("div",{"data-testid":`${o}-if`,style:mk,children:[i.jsxs("button",{type:"button",onClick:()=>a(l=>!l),style:vk,children:["▸ ",t("layout_editor.init_actions.if_label")]}),s?i.jsx("div",{"data-testid":`${o}-if-input`,style:{minWidth:0},children:i.jsx(Ke,{value:cs(e)??"",onChange:l=>n(Vd(e,l)),t,candidates:r,placeholder:t("layout_editor.init_actions.if_placeholder"),testidPrefix:`${o}-if-chip`})}):null]})}const tu={display:"flex",alignItems:"center",gap:8,minWidth:0},oo={fontSize:11,color:"#64748b",minWidth:80},hk={display:"flex",alignItems:"center",gap:8,padding:"4px 0"},yk={fontSize:11,color:"#64748b",minWidth:80},bk={fontSize:11,color:"#92400e"},mk={display:"flex",flexDirection:"column",gap:4},vk={textAlign:"left",border:"none",background:"transparent",color:"#475569",cursor:"pointer",fontSize:11,padding:0};function _k(e,t,n){if(!t)return n("layout_editor.action.source_core");const o=e?.[t],r=o&&typeof o=="object"&&o.__source?o.__source:null;return!r||r.kind==="core"?n("layout_editor.action.source_core"):r.id??n(`layout_editor.action.source_${r.kind}`)}function xk(e,t,n){const o=Yn(e,t);if(o.kind==="preset"){const r=t.find(s=>s.id===o.recipeId);return Kd(r??null,o.values,s=>n(s.startsWith("$t:")?s.slice(3):s))}return typeof e.handler=="string"?e.handler:n("layout_editor.action_list.unknown")}function Gt({actions:e,onChange:t,t:n,recipes:o,chipContext:r,actionChipCandidates:s,addContext:a="init",renderAddPicker:l,renderEditor:d,candidatePools:c,showSourceBadge:p=!1,canDrag:f,canDropAt:b,isLocked:g,hideAddPicker:m=!1,testIdPrefix:h="g7le-action-list"}){const v=u.useMemo(()=>ko(o),[o]),y=u.useMemo(()=>{if(r==null||r==="init")return c;const B=Vl(r,n,s??null);if(B.length===0)return c;const M=c??{},O=new Set((M.bindingCandidates??[]).map(H=>H.expression)),z=B.filter(H=>!O.has(H.expression));return z.length===0?c:{...M,bindingCandidates:[...z,...M.bindingCandidates??[]]}},[r,s,c,n]),[_,w]=u.useState(null),[k,x]=u.useState(null),$=u.useCallback((B,M)=>{if(B===M||B<0||M<0||B>=e.length||M>=e.length)return;const O=e.slice(),[z]=O.splice(B,1);O.splice(M,0,z),t(O)},[e,t]),S=ys({length:e.length,onMove:$,canDrag:f,canDropAt:b}),C=u.useCallback(B=>{t(e.filter((M,O)=>O!==B))},[e,t]),T=u.useCallback((B,M)=>{const O=e.slice();O[B]=M,t(O)},[e,t]),E=u.useCallback(B=>{t([...e,B])},[e,t]),A=u.useCallback((B,M)=>{const O=Yn(B,v),z=O.kind==="preset"?v.find(P=>P.id===O.recipeId)??null:null;if(!z)return null;const H=O.kind==="preset"?O.values:{};return i.jsxs("div",{style:Ck,children:[i.jsx(Ns,{raw:B,recipe:z,values:H,t:n,pools:y??{},onChange:M,testIdPrefix:`${h}-edit`,renderActionList:(P,I,L,F)=>{const Y=F==="onSuccess"?"response":F==="onError"?"error":void 0;return i.jsx(Gt,{actions:P,onChange:I,t:n,recipes:o,chipContext:Y,actionChipCandidates:Y?s:void 0,candidatePools:Y?c:y,addContext:a,showSourceBadge:p,testIdPrefix:L})}}),i.jsx(gk,{raw:B,t:n,onChange:M,testIdPrefix:`${h}-edit`,candidates:y?.bindingCandidates})]})},[v,n,y,c,s,h,o,a,p]),N=d??(o?A:void 0),D=m?null:l?l(E):o?i.jsx(m0,{recipes:o,t:n,onAdd:E,context:a,testIdPrefix:`${h}-add-picker`}):null;return i.jsxs("div",{className:h,"data-testid":h,children:[i.jsxs("ul",{style:{listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:6},children:[e.map((B,M)=>{const O=Yn(B,v),z=O.kind==="preset"?O.recipeId:null,H=z?v.find(Y=>Y.id===z)??null:null,P=H===null,I=g?.(M)??!1,L=cs(B)!==null,F=N?N(B,Y=>T(M,Y)):null;return i.jsxs(u.Fragment,{children:[I?null:i.jsx("li",{"aria-hidden":"true",style:{listStyle:"none",margin:0,padding:0},children:i.jsx(Rn,{active:S.isDropTarget(M),testid:`${h}-dropline-${M}`})}),i.jsxs("li",{"data-testid":`${h}-item-${M}`,"data-drag-source":S.dragIndex===M?"true":void 0,style:{border:"1px solid #e2e8f0",borderRadius:8,padding:"8px 10px",...S.dragIndex===M?{opacity:.5}:{}},onDragOver:S.dragging&&!I?Y=>{Y.preventDefault();const K=Y.currentTarget.getBoundingClientRect();S.onDragOverItem(M,Y.clientY{Y.preventDefault(),S.onDrop()}:void 0,children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[I?i.jsx("span",{style:{fontSize:12},children:"🔒"}):i.jsx("span",{"data-testid":`${h}-drag-${M}`,style:{color:"#94a3b8",cursor:"grab",fontSize:14,userSelect:"none"},draggable:!0,onDragStart:()=>S.onDragStart(M),onDragEnd:S.onDragEnd,"aria-label":n("layout_editor.action_list.drag_reorder"),role:"button",children:"⠿"}),i.jsx("span",{style:{flex:1,minWidth:0,fontSize:13},"data-testid":`${h}-summary-${M}`,children:xk(B,v,n)}),p?i.jsxs("span",{"data-testid":`${h}-source-${M}`,style:wk,children:["〔",_k(o,z,n),"〕"]}):null,L?i.jsxs("span",{"data-testid":`${h}-cond-badge-${M}`,style:kk,children:["〔",n("layout_editor.init_actions.cond_badge"),"〕"]}):null,P?i.jsxs("span",{"data-testid":`${h}-advanced-${M}`,style:Sk,children:["[",n("layout_editor.action.advanced"),"]"]}):null,!I&&F?i.jsxs("button",{type:"button","data-testid":`${h}-edit-${M}`,onClick:()=>x(k===M?null:M),"aria-label":n("layout_editor.init_actions.edit"),title:n("layout_editor.init_actions.edit"),style:k===M?$k:nu,children:["✎ ",n("layout_editor.init_actions.edit")]}):null,i.jsx("button",{type:"button","data-testid":`${h}-code-${M}`,onClick:()=>w(_===M?null:M),"aria-label":n("layout_editor.action_list.view_code"),title:n("layout_editor.action_list.view_code"),style:_===M?Ek:Ms,children:""}),I?null:i.jsx("button",{type:"button","data-testid":`${h}-remove-${M}`,onClick:()=>C(M),"aria-label":n("layout_editor.action_list.remove"),title:n("layout_editor.action_list.remove"),style:Ik,children:"✕"})]}),H?i.jsx(T0,{action:B,recipe:H,values:O.kind==="preset"?O.values:{},t:n,showCodeButton:!1,testIdPrefix:`${h}-preview-${M}`}):null,k===M&&!I&&F?i.jsx("div",{"data-testid":`${h}-edit-body-${M}`,children:F}):null,d&&k!==M?d(B,Y=>T(M,Y)):null,_===M?i.jsx("pre",{"data-testid":`${h}-code-view-${M}`,style:{margin:"8px 0 0",padding:8,background:"#0f172a",color:"#e2e8f0",borderRadius:6,fontSize:12,overflow:"auto"},children:JSON.stringify(B,null,2)}):null]})]},M)}),i.jsx("li",{"aria-hidden":"true",style:{listStyle:"none",margin:0,padding:0},children:i.jsx(Rn,{active:S.isDropTarget(e.length),testid:`${h}-dropline-end`})})]}),D?i.jsx("div",{style:{marginTop:8},children:D}):null]})}const wk={fontSize:10,color:"#64748b",whiteSpace:"nowrap"},kk={fontSize:10,color:"#7c3aed",whiteSpace:"nowrap"},Sk={fontSize:10,color:"#92400e",whiteSpace:"nowrap"},Ck={display:"flex",flexDirection:"column",gap:6,paddingTop:6,borderTop:"1px dashed #e2e8f0",marginTop:6},nu={flex:"0 0 auto",padding:"3px 8px",fontSize:11,fontWeight:500,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",whiteSpace:"nowrap",lineHeight:1.4},$k={...nu,background:"#eff6ff",borderColor:"#bfdbfe",color:"#2563eb"},Ms={flex:"0 0 auto",width:26,height:24,display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:11,border:"1px solid #e2e8f0",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer",fontFamily:"ui-monospace, monospace"},Ek={...Ms,background:"#0f172a",borderColor:"#0f172a",color:"#e2e8f0"},Ik={...Ms,color:"#dc2626",borderColor:"#fecaca",fontFamily:"inherit"};function ou(e){const t=e.__source;return t&&typeof t=="object"?t:null}function Ak({actions:e,onChange:t,recipes:n,t:o,bindingCandidates:r,pageCandidates:s,dataSourceCandidates:a,stateKeyCandidates:l,modalCandidates:d}){const c=u.useMemo(()=>({pageCandidates:s,dataSourceCandidates:a,stateKeyCandidates:l,modalCandidates:d,bindingCandidates:r}),[s,a,l,d,r]),p=u.useMemo(()=>e.filter(h=>ou(h)?.kind==="base"),[e]),f=u.useMemo(()=>e.filter(h=>ou(h)?.kind!=="base"),[e]),b=p.length>0,g=u.useCallback(h=>{t(b?[...p,...h]:h)},[t,b,p]),m=u.useCallback(()=>{},[]);return i.jsxs("div",{className:"g7le-init-actions-form","data-testid":"g7le-init-actions-form",style:Tk,children:[i.jsx("p",{style:Dk,children:o("layout_editor.page_settings.init_actions.heading")}),b?i.jsxs(i.Fragment,{children:[i.jsxs("div",{"data-testid":"g7le-init-action-group-base",style:ru,children:[i.jsx("div",{style:iu,children:o("layout_editor.init_actions.group_base")}),i.jsx(Gt,{actions:p,onChange:m,t:o,recipes:n,candidatePools:c,addContext:"init",showSourceBadge:!0,isLocked:()=>!0,hideAddPicker:!0,testIdPrefix:"g7le-init-action-base"}),i.jsxs("p",{"data-testid":"g7le-init-action-base-hint",style:zk,children:["ⓘ ",o("layout_editor.init_actions.base_readonly_hint")]})]}),i.jsxs("div",{"data-testid":"g7le-init-action-group-self",style:ru,children:[i.jsx("div",{style:iu,children:o("layout_editor.init_actions.group_self")}),f.length===0?i.jsx("p",{style:su,children:o("layout_editor.init_actions.empty_self")}):null,i.jsx(Gt,{actions:f,onChange:g,t:o,recipes:n,candidatePools:c,addContext:"init",showSourceBadge:!0,testIdPrefix:"g7le-init-action-self"})]}),i.jsxs("p",{"data-testid":"g7le-init-action-merge-order",style:Nk,children:["ⓘ ",o("layout_editor.init_actions.merge_order")]})]}):i.jsxs(i.Fragment,{children:[e.length===0?i.jsx("p",{"data-testid":"g7le-init-action-empty",style:su,children:o("layout_editor.init_actions.empty")}):null,i.jsx(Gt,{actions:e,onChange:t,t:o,recipes:n,candidatePools:c,addContext:"init",showSourceBadge:!0,testIdPrefix:"g7le-init-action"})]})]})}const Tk={display:"flex",flexDirection:"column",gap:12,minWidth:0},Dk={margin:0,fontSize:13,fontWeight:700,color:"#0f172a"},ru={border:"1px solid #e2e8f0",borderRadius:10,padding:10,display:"flex",flexDirection:"column",gap:8},iu={fontSize:12,fontWeight:700,color:"#475569"},zk={margin:0,fontSize:11,color:"#64748b"},su={margin:0,fontSize:12,color:"#94a3b8"},Nk={margin:0,fontSize:11,color:"#64748b"};function Mk(e){return e==="spinner"?new Set(["spinner","page"]):new Set(["skeleton"])}function au(e,t,n){return typeof e!="string"?n:e.startsWith("$t:")?t(e.slice(3)):e}function lu({candidates:e,value:t,onSelect:n,styleKind:o,t:r,testIdPrefix:s="g7le-loading-component-picker"}){const a=bo(),l=()=>{const d=a.open({ariaLabel:r("layout_editor.overlay.loading_picker.select"),width:520,maxHeightRatio:.7,content:i.jsx(Lk,{candidates:e,value:t,styleKind:o,t:r,testIdPrefix:s,onPick:c=>{n(c),a.close(d)},onClose:()=>a.close(d)})})};return i.jsx("div",{className:s,"data-testid":s,style:{minWidth:0},children:i.jsxs("div",{style:Pk,children:[i.jsx("span",{"data-testid":`${s}-current`,style:Ok,children:t&&t.length>0?t:r("layout_editor.overlay.loading_picker.none")}),i.jsxs("button",{type:"button","data-testid":`${s}-open`,onClick:l,style:Bk,children:["🔍 ",r("layout_editor.overlay.loading_picker.select")]})]})})}function Lk({candidates:e,value:t,styleKind:n,t:o,testIdPrefix:r,onPick:s,onClose:a}){const[l,d]=u.useState(""),c=Mk(n),p=u.useMemo(()=>{const f=l.trim().toLowerCase();return e.filter(b=>c.has(b.role)).filter(b=>f?au(b.label,o,b.name).toLowerCase().includes(f)||b.name.toLowerCase().includes(f):!0)},[e,n,l,o]);return i.jsxs("div",{"data-testid":`${r}-modal`,style:Wk,children:[i.jsxs("div",{style:jk,children:[i.jsxs("span",{style:Hk,children:["🔍 ",o("layout_editor.overlay.loading_picker.select")]}),i.jsx("button",{type:"button","data-testid":`${r}-close`,onClick:a,"aria-label":o("layout_editor.overlay.loading_picker.select"),style:Fk,children:"✕"})]}),i.jsx("input",{type:"text","data-testid":`${r}-search`,value:l,placeholder:o("layout_editor.overlay.loading_picker.search"),onChange:f=>d(f.target.value),style:Kk,autoFocus:!0}),p.length===0?i.jsx("p",{"data-testid":`${r}-empty`,style:Jk,children:o("layout_editor.overlay.loading_picker.empty")}):i.jsx("ul",{style:Vk,children:p.map(f=>i.jsx("li",{children:i.jsxs("button",{type:"button","data-testid":`${r}-item-${f.name}`,onClick:()=>s(f.name),style:{...Uk,...t===f.name?qk:{}},children:[i.jsx("span",{style:Gk,children:au(f.label,o,f.name)}),i.jsx("code",{style:Yk,children:f.name}),i.jsx("span",{style:Xk,children:f.role})]})},f.name))})]})}const Pk={display:"flex",alignItems:"center",gap:6,minWidth:0},Ok={flex:1,minWidth:0,fontSize:12,color:"#0f172a",fontFamily:"monospace"},Bk={padding:"4px 10px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},Wk={display:"flex",flexDirection:"column",minHeight:0,padding:16,boxSizing:"border-box",fontFamily:"system-ui, -apple-system, sans-serif"},jk={display:"flex",alignItems:"center",gap:8,paddingBottom:8,borderBottom:"1px solid #e2e8f0",marginBottom:10},Hk={flex:1,fontSize:14,fontWeight:700,color:"#0f172a",minWidth:0},Fk={border:"none",background:"transparent",color:"#64748b",cursor:"pointer",fontSize:15,lineHeight:1,padding:4},Kk={width:"100%",padding:"6px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,marginBottom:8,boxSizing:"border-box"},Vk={listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:2,overflowY:"auto",minHeight:0},Uk={display:"flex",alignItems:"center",gap:6,width:"100%",textAlign:"left",padding:"8px 10px",fontSize:12,border:"1px solid transparent",background:"transparent",cursor:"pointer",borderRadius:6},qk={border:"1px solid #3b82f6",background:"#eff6ff"},Gk={flex:1,minWidth:0,color:"#0f172a"},Yk={fontSize:10,color:"#94a3b8",fontFamily:"monospace"},Xk={fontSize:10,color:"#64748b",background:"#f1f5f9",borderRadius:4,padding:"0 4px"},Jk={margin:0,fontSize:12,color:"#94a3b8",padding:"8px 4px"};function du(e){return e===!0?{enabled:!0}:e===!1||e===void 0?{}:e}const Zk=["opaque","blur","fade","skeleton","spinner"];function Qk({value:e,patch:t,t:n,baseValue:o,ownValue:r,loadingComponents:s=[],progressiveDataSources:a=[],bindingCandidates:l}){const d=du(e),c=d.enabled??!1,p=!!o&&Object.keys(o).length>0,f=Tn("component-target-picker"),[b,g]=u.useState((d.wait_for??[]).length>0),m=u.useCallback(k=>{const x={...du(e)};k(x),t(x)},[e,t]),h=r&&typeof r=="object"?r:e&&typeof e=="object"?e:{},v=u.useCallback(k=>p&&o!==void 0&&k in o&&!(k in h),[p,o,h]),y=u.useCallback(k=>{o&&m(x=>{x[k]=o[k]})},[o,m]),_=u.useCallback(k=>m(x=>{x.enabled=k}),[m]),w=d.target!==void 0?"region":"full";return i.jsxs("div",{className:"g7le-overlay-form","data-testid":"g7le-overlay-form",style:Rk,children:[p?i.jsxs("p",{"data-testid":"g7le-overlay-inherit-banner",style:e1,children:["ⓘ ",n("layout_editor.overlay.inherit_banner")]}):null,i.jsxs("div",{style:Hr,children:[i.jsx(Ls,{label:n("layout_editor.overlay.enabled_label"),inherited:v("enabled"),hasInheritance:p,onOverride:()=>y("enabled"),testidKey:"enabled",t:n}),i.jsx(Lr,{disabled:v("enabled"),children:i.jsx(Mr,{checked:c,onChange:_,testid:"g7le-overlay-enabled",ariaLabel:n("layout_editor.overlay.enabled_label"),label:n(c?"layout_editor.overlay.on":"layout_editor.overlay.off")})}),i.jsxs("p",{style:Fr,children:["ⓘ ",n("layout_editor.overlay.enabled_hint")]})]}),i.jsx(Lr,{disabled:!c,testid:"g7le-overlay-body",style:{display:"flex",flexDirection:"column",gap:16,minWidth:0},children:i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:Hr,children:[i.jsx(Ls,{label:n("layout_editor.overlay.scope_label"),inherited:v("target"),hasInheritance:p,onOverride:()=>y("target"),testidKey:"target",t:n}),i.jsxs("div",{"data-testid":"g7le-overlay-scope",style:Ps,children:[i.jsx(jr,{active:w==="full",onClick:()=>m(k=>{delete k.target,delete k.fallback_target}),testid:"g7le-overlay-scope-full",children:n("layout_editor.overlay.scope_full")}),i.jsx(jr,{active:w==="region",onClick:()=>m(k=>{k.target=k.target??""}),testid:"g7le-overlay-scope-region",children:n("layout_editor.overlay.scope_region")})]}),i.jsx(Lr,{disabled:w!=="region",testid:"g7le-overlay-region-box",style:r1,children:i.jsxs(i.Fragment,{children:[i.jsx(Nn,{label:n("layout_editor.overlay.target_label"),children:i.jsx("div",{"data-testid":"g7le-overlay-target-picker",children:f?i.jsx(f,{control:{label:n("layout_editor.overlay.target_label")},value:d.target??"",onChange:k=>m(x=>{x.target=typeof k=="string"?k:""}),t:n}):i.jsx("input",{type:"text","data-testid":"g7le-overlay-target-input",value:d.target??"",onChange:k=>m(x=>{x.target=k.target.value}),style:a1})})}),i.jsx(Nn,{label:n("layout_editor.overlay.fallback_label"),children:i.jsx("div",{"data-testid":"g7le-overlay-fallback-picker",children:f?i.jsx(f,{control:{label:n("layout_editor.overlay.fallback_label")},value:d.fallback_target??"",onChange:k=>m(x=>{const $=typeof k=="string"?k:"";$===""?delete x.fallback_target:x.fallback_target=$}),t:n}):null})}),i.jsxs("p",{style:Fr,children:["ⓘ ",n("layout_editor.overlay.fallback_hint")]})]})})]}),i.jsxs("div",{style:Hr,children:[i.jsx(Ls,{label:n("layout_editor.overlay.style_label"),inherited:v("style"),hasInheritance:p,onOverride:()=>y("style"),testidKey:"style",t:n}),i.jsx("div",{"data-testid":"g7le-overlay-style",style:Ps,children:Zk.map(k=>i.jsx(jr,{active:(d.style??"opaque")===k,onClick:()=>m(x=>{x.style=k}),testid:`g7le-overlay-style-${k}`,children:n(`layout_editor.overlay.style_${k}`)},k))}),d.style==="skeleton"?i.jsxs("div",{style:cu,children:[i.jsx(Nn,{label:n("layout_editor.overlay.skeleton_component"),children:i.jsx(lu,{candidates:s,value:d.skeleton?.component,styleKind:"skeleton",onSelect:k=>m(x=>{x.skeleton={...x.skeleton,component:k}}),t:n,testIdPrefix:"g7le-overlay-skeleton-component"})}),i.jsx(Nn,{label:n("layout_editor.overlay.skeleton_animation"),children:i.jsx("div",{"data-testid":"g7le-overlay-skeleton-anim",style:Ps,children:["wave","pulse","none"].map(k=>i.jsx(jr,{active:(d.skeleton?.animation??"wave")===k,onClick:()=>m(x=>{x.skeleton={...x.skeleton,animation:k}}),testid:`g7le-overlay-skeleton-anim-${k}`,children:n(`layout_editor.overlay.anim_${k}`)},k))})}),i.jsx(Nn,{label:n("layout_editor.overlay.skeleton_count"),children:i.jsx("input",{type:"number","data-testid":"g7le-overlay-skeleton-count",value:d.skeleton?.iteration_count??"",onChange:k=>m(x=>{const $=parseInt(k.target.value,10);x.skeleton={...x.skeleton,iteration_count:Number.isNaN($)?void 0:$}}),style:l1})})]}):null,d.style==="spinner"?i.jsxs("div",{style:cu,children:[i.jsx(Nn,{label:n("layout_editor.overlay.spinner_component"),children:i.jsx(lu,{candidates:s,value:d.spinner?.component,styleKind:"spinner",onSelect:k=>m(x=>{x.spinner={...x.spinner,component:k}}),t:n,testIdPrefix:"g7le-overlay-spinner-component"})}),i.jsx(Nn,{label:n("layout_editor.overlay.spinner_text"),children:i.jsx("div",{"data-testid":"g7le-overlay-spinner-text",style:{minWidth:0},children:i.jsx(_t,{value:d.spinner?.text??"",onChange:k=>m(x=>{x.spinner={...x.spinner,text:k===void 0||k===""?void 0:k}}),t:n,candidates:l,enableExpressionTree:!0,expressionTreeCollapsible:!0,testidPrefix:"g7le-overlay-spinner-text-field"})})})]}):null]}),i.jsxs("div",{style:Hr,children:[i.jsxs("button",{type:"button","data-testid":"g7le-overlay-waitfor-toggle","aria-expanded":b,onClick:()=>g(k=>!k),style:u1,children:[b?"▾":"▸"," ",n("layout_editor.overlay.waitfor_label")]}),b?i.jsxs("div",{"data-testid":"g7le-overlay-waitfor-body",style:p1,children:[i.jsxs("p",{"data-testid":"g7le-overlay-waitfor-hint",style:Fr,children:["ⓘ ",n("layout_editor.overlay.waitfor_hint")]}),a.length===0?i.jsx("p",{"data-testid":"g7le-overlay-waitfor-empty",style:Fr,children:n("layout_editor.overlay.waitfor_empty")}):i.jsx("div",{"data-testid":"g7le-overlay-waitfor",style:{display:"flex",flexWrap:"wrap",gap:6},children:a.map(k=>{const x=(d.wait_for??[]).includes(k.id);return i.jsxs("label",{"data-testid":`g7le-overlay-waitfor-${k.id}`,style:d1(x),children:[i.jsx("input",{type:"checkbox",checked:x,onChange:()=>m($=>{const S=new Set($.wait_for??[]);S.has(k.id)?S.delete(k.id):S.add(k.id);const C=Array.from(S);C.length===0?delete $.wait_for:$.wait_for=C})}),i.jsx(Lc,{option:k,testIdPrefix:`g7le-overlay-waitfor-${k.id}`})]},k.id)})})]}):null]}),p?i.jsxs("button",{type:"button","data-testid":"g7le-overlay-reset-inherit",onClick:()=>t(void 0),style:c1,children:["⟲ ",n("layout_editor.overlay.reset_inherit")]}):null]})})]})}function jr({active:e,onClick:t,children:n,testid:o}){return i.jsx("button",{type:"button","data-testid":o,"aria-pressed":e,onClick:t,style:{...n1,...e?o1:{}},children:n})}function Ls({label:e,inherited:t,hasInheritance:n,onOverride:o,testidKey:r,t:s}){return i.jsxs("div",{style:f1,children:[i.jsx("label",{style:t1,children:e}),n?t?i.jsxs(i.Fragment,{children:[i.jsxs("span",{"data-testid":`g7le-overlay-inherited-${r}`,style:g1,children:["〔",s("layout_editor.overlay.inherited_badge"),"〕"]}),i.jsx("button",{type:"button","data-testid":`g7le-overlay-override-${r}`,onClick:o,style:y1,children:s("layout_editor.overlay.override_field")})]}):i.jsxs("span",{"data-testid":`g7le-overlay-overridden-${r}`,style:h1,children:["〔",s("layout_editor.overlay.overridden_badge"),"〕"]}):null]})}function Nn({label:e,children:t}){return i.jsxs("div",{style:i1,children:[i.jsx("span",{style:s1,children:e}),i.jsx("div",{style:{flex:1,minWidth:0},children:t})]})}const Rk={display:"flex",flexDirection:"column",gap:16,minWidth:0},e1={margin:0,fontSize:12,color:"#1d4ed8",background:"#eff6ff",padding:"8px 10px",borderRadius:6},Hr={display:"flex",flexDirection:"column",gap:6,minWidth:0},t1={fontSize:13,fontWeight:600,color:"#0f172a"},Fr={margin:0,fontSize:11,color:"#94a3b8"},Ps={display:"flex",gap:4,flexWrap:"wrap"},n1={padding:"4px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},o1={border:"1px solid #3b82f6",background:"#eff6ff",color:"#1d4ed8"},r1={display:"flex",flexDirection:"column",gap:8,padding:8,border:"1px dashed #e2e8f0",borderRadius:8},cu={display:"flex",flexDirection:"column",gap:8,padding:8,border:"1px dashed #e2e8f0",borderRadius:8},i1={display:"flex",alignItems:"center",gap:8,minWidth:0},s1={fontSize:11,color:"#64748b",minWidth:90},a1={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},l1={width:80,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},d1=e=>({display:"inline-flex",alignItems:"center",gap:4,padding:"4px 8px",fontSize:12,border:`1px solid ${e?"#3b82f6":"#cbd5e1"}`,borderRadius:12,background:e?"#eff6ff":"#fff",cursor:"pointer"}),c1={alignSelf:"flex-start",padding:"6px 12px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},u1={alignSelf:"flex-start",padding:"4px 0",fontSize:13,fontWeight:600,color:"#0f172a",background:"transparent",border:"none",cursor:"pointer"},p1={display:"flex",flexDirection:"column",gap:6,paddingLeft:14,minWidth:0},f1={display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",minWidth:0},g1={fontSize:11,color:"#64748b",background:"#f1f5f9",borderRadius:4,padding:"1px 6px"},h1={fontSize:11,color:"#0369a1",background:"#e0f2fe",borderRadius:4,padding:"1px 6px"},y1={padding:"2px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},b1="g7le:computed-effect-preview",m1={number:"layout_editor.computed.type_number",string:"layout_editor.computed.type_string",boolean:"layout_editor.computed.type_boolean",list:"layout_editor.computed.type_list",object:"layout_editor.computed.type_object",null:"layout_editor.computed.type_null"};function v1(e,t,n){if(t==="list"){const o=e,r=o.slice(0,2).map(s=>JSON.stringify(s)).join(", ");return o.length<=2?`[${r}]`:`[${r}, ${n("layout_editor.computed.list_more",{count:o.length})}]`}return t==="object"?JSON.stringify(e):t==="boolean"?e?"true":"false":t==="null"?n("layout_editor.computed.value_none"):String(e)}function uu({expr:e,computedKey:t,sampleContext:n,t:o,isEffect:r=!1,testIdPrefix:s="g7le-computed-preview"}){const a=zd(e,n),l=()=>{typeof window>"u"||!t||window.dispatchEvent(new CustomEvent(b1,{detail:{key:t}}))};return a.ok?i.jsxs("div",{className:s,"data-testid":s,style:_1,children:[i.jsx("span",{style:x1,children:o("layout_editor.computed.preview_label")}),i.jsx("span",{"data-testid":`${s}-value`,style:w1,children:v1(a.value,a.type,o)}),i.jsxs("span",{"data-testid":`${s}-type`,style:k1,children:["(",o(m1[a.type]),")"]}),r&&a.type==="boolean"?i.jsxs("button",{type:"button","data-testid":`${s}-effect`,onClick:l,style:S1,children:["▷ ",o("layout_editor.computed.effect_preview")]}):null]}):i.jsxs("div",{"data-testid":`${s}-error`,style:C1,children:["⚠ ",o("layout_editor.computed.preview_error")]})}const _1={display:"flex",alignItems:"center",flexWrap:"wrap",gap:6,minWidth:0},x1={fontSize:11,color:"#94a3b8"},w1={fontSize:12,color:"#0f172a",fontFamily:"monospace",wordBreak:"break-all"},k1={fontSize:10,color:"#64748b"},S1={padding:"2px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},C1={fontSize:12,color:"#b45309"},$1=[{op:"count",labelKey:"layout_editor.computed.op_count"},{op:"sum",labelKey:"layout_editor.computed.op_sum"},{op:"filter",labelKey:"layout_editor.computed.op_filter"},{op:"toOptions",labelKey:"layout_editor.computed.op_to_options"},{op:"nth",labelKey:"layout_editor.computed.op_nth"},{op:"firstOf",labelKey:"layout_editor.computed.op_first_of"},{op:"literal",labelKey:"layout_editor.computed.op_literal"}],E1=["=","!=",">","<",">=","<=","includes"],I1=new Set(["count","sum","filter"]);function pu({model:e,onChange:t,t:n,dataSourceCandidates:o,bindingCandidates:r,existingKeys:s=[]}){const a=u.useCallback(g=>{const m={...e};g(m),t(m)},[e,t]),l=e.conditions??[],d=Tn("datasource-picker"),c=e.key!==""&&s.includes(e.key),p=()=>a(g=>{g.conditions=[...g.conditions??[],{field:"",cmp:"=",value:""}]}),f=(g,m)=>a(h=>{const v=(h.conditions??[]).slice(),y={...v[g]};m(y),v[g]=y,h.conditions=v}),b=g=>a(m=>{m.conditions=(m.conditions??[]).filter((h,v)=>v!==g)});return i.jsxs("div",{className:"g7le-computed-custom","data-testid":"g7le-computed-custom",style:A1,children:[i.jsx(Os,{label:`① ${n("layout_editor.computed.custom_step1")}`,children:i.jsx("div",{"data-testid":"g7le-computed-custom-source",children:d?i.jsx(d,{control:{},value:e.source,onChange:g=>a(m=>{m.source=typeof g=="string"?g:void 0}),t:n,candidates:o}):i.jsx("input",{type:"text",value:e.source??"",onChange:g=>a(m=>{m.source=g.target.value}),style:ro})})}),i.jsxs(Os,{label:`② ${n("layout_editor.computed.custom_step2")}`,children:[i.jsx("select",{"data-testid":"g7le-computed-custom-op",value:e.op,onChange:g=>a(m=>{m.op=g.target.value}),style:ro,children:$1.map(({op:g,labelKey:m})=>i.jsx("option",{value:g,children:n(m)},g))}),e.op==="sum"?i.jsx("div",{"data-testid":"g7le-computed-custom-sumfield",style:{minWidth:0},children:i.jsx(Ke,{value:e.sumField??"",onChange:g=>a(m=>{m.sumField=g}),t:n,candidates:r,placeholder:n("layout_editor.computed.custom_sum_field"),testidPrefix:"g7le-computed-custom-sumfield-chip"})}):null,e.op==="toOptions"?i.jsxs("div",{style:{display:"flex",gap:6},children:[i.jsx("div",{"data-testid":"g7le-computed-custom-valuefield",style:{flex:1,minWidth:0},children:i.jsx(Ke,{value:e.valueField??"",onChange:g=>a(m=>{m.valueField=g}),t:n,candidates:r,placeholder:n("layout_editor.computed.custom_value_field"),testidPrefix:"g7le-computed-custom-valuefield-chip"})}),i.jsx("div",{"data-testid":"g7le-computed-custom-labelfield",style:{flex:1,minWidth:0},children:i.jsx(Ke,{value:e.labelField??"",onChange:g=>a(m=>{m.labelField=g}),t:n,candidates:r,placeholder:n("layout_editor.computed.custom_label_field"),testidPrefix:"g7le-computed-custom-labelfield-chip"})})]}):null,e.op==="nth"?i.jsxs("div",{style:{display:"flex",gap:6},children:[i.jsx("input",{type:"text","data-testid":"g7le-computed-custom-index",value:e.index??"",placeholder:"0",onChange:g=>a(m=>{m.index=g.target.value}),style:ro}),i.jsx("div",{"data-testid":"g7le-computed-custom-prop",style:{flex:1,minWidth:0},children:i.jsx(Ke,{value:e.prop??"",onChange:g=>a(m=>{m.prop=g}),t:n,candidates:r,placeholder:n("layout_editor.computed.custom_prop"),testidPrefix:"g7le-computed-custom-prop-chip"})})]}):null,e.op==="literal"?i.jsxs("div",{style:{display:"flex",gap:6},children:[i.jsxs("select",{"data-testid":"g7le-computed-custom-literalkind",value:e.literalKind??"string",onChange:g=>a(m=>{m.literalKind=g.target.value}),style:ro,children:[i.jsx("option",{value:"string",children:n("layout_editor.computed.kind_string")}),i.jsx("option",{value:"number",children:n("layout_editor.computed.kind_number")}),i.jsx("option",{value:"boolean",children:n("layout_editor.computed.kind_boolean")})]}),i.jsx("div",{"data-testid":"g7le-computed-custom-literalvalue",style:{flex:1,minWidth:0},children:i.jsx(Ke,{value:e.literalValue??"",onChange:g=>a(m=>{m.literalValue=g}),t:n,candidates:r,testidPrefix:"g7le-computed-custom-literalvalue-chip"})})]}):null,e.op==="firstOf"?i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("input",{type:"text","data-testid":"g7le-computed-custom-candidates",value:(e.candidates??[]).join(", "),placeholder:n("layout_editor.computed.custom_candidates"),onChange:g=>a(m=>{m.candidates=g.target.value.split(",").map(h=>h.trim()).filter(Boolean)}),style:ro}),i.jsx("div",{"data-testid":"g7le-computed-custom-fallback",style:{minWidth:0},children:i.jsx(Ke,{value:e.fallback??"",onChange:g=>a(m=>{m.fallback=g}),t:n,candidates:r,placeholder:n("layout_editor.computed.custom_fallback"),testidPrefix:"g7le-computed-custom-fallback-chip"})})]}):null,I1.has(e.op)?i.jsxs("div",{style:N1,children:[l.map((g,m)=>i.jsxs("div",{"data-testid":`g7le-computed-custom-cond-${m}`,style:M1,children:[i.jsx("div",{"data-testid":`g7le-computed-custom-cond-field-${m}`,style:{flex:1,minWidth:0},children:i.jsx(Ke,{value:g.field,onChange:h=>f(m,v=>{v.field=h}),t:n,candidates:r,placeholder:n("layout_editor.computed.cond_field"),testidPrefix:`g7le-computed-custom-cond-field-${m}-chip`})}),i.jsx("select",{value:g.cmp,onChange:h=>f(m,v=>{v.cmp=h.target.value}),style:L1,children:E1.map(h=>i.jsx("option",{value:h,children:h},h))}),i.jsx("div",{"data-testid":`g7le-computed-custom-cond-value-${m}`,style:{flex:1,minWidth:0},children:i.jsx(Ke,{value:g.value,onChange:h=>f(m,v=>{v.value=h}),t:n,candidates:r,placeholder:n("layout_editor.computed.cond_value"),testidPrefix:`g7le-computed-custom-cond-value-${m}-chip`})}),i.jsx("button",{type:"button","data-testid":`g7le-computed-custom-cond-remove-${m}`,onClick:()=>b(m),style:P1,children:"✕"})]},m)),i.jsxs("button",{type:"button","data-testid":"g7le-computed-custom-cond-add",onClick:p,style:O1,children:["+ ",n("layout_editor.computed.cond_add")]})]}):null]}),i.jsxs(Os,{label:`③ ${n("layout_editor.computed.custom_step3")}`,children:[i.jsx("input",{type:"text","data-testid":"g7le-computed-custom-key",value:e.key,onChange:g=>a(m=>{m.key=g.target.value}),style:{...ro,...c?z1:{}}}),c?i.jsxs("p",{"data-testid":"g7le-computed-custom-key-dup",style:B1,children:["⚠ ",n("layout_editor.computed.key_duplicate")]}):null]})]})}function Os({label:e,children:t}){return i.jsxs("div",{style:T1,children:[i.jsx("div",{style:D1,children:e}),i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0},children:t})]})}function Bs(e){return Zm(e)}const A1={display:"flex",flexDirection:"column",gap:12,padding:10,border:"1px solid #cbd5e1",borderRadius:8,background:"#fff"},T1={display:"flex",flexDirection:"column",gap:4,minWidth:0},D1={fontSize:12,fontWeight:600,color:"#475569"},ro={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:0,width:"100%",boxSizing:"border-box"},z1={border:"1px solid #ef4444"},N1={display:"flex",flexDirection:"column",gap:6,marginTop:4},M1={display:"flex",gap:4,alignItems:"center",minWidth:0},L1={padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},P1={border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12},O1={alignSelf:"flex-start",padding:"2px 8px",fontSize:11,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},B1={margin:0,fontSize:11,color:"#b45309"};function Ws(e,t,n){return typeof e!="string"?n:e.startsWith("$t:")?t(e.slice(3)):e}function W1(e){if(e&&typeof e=="object"){const t=e.__source;if(t&&typeof t=="object")return t}return null}function j1({computed:e,onChange:t,recipes:n,t:o,sampleContext:r,dataSourceCandidates:s,bindingCandidates:a,computedSource:l={},effectKeys:d=[],onRevert:c}){const p=u.useMemo(()=>Cd(n),[n]),[f,b]=u.useState(!1),[g,m]=u.useState(null),h=Object.keys(e),v=u.useCallback((x,$)=>{t({...e,[x]:$})},[e,t]),y=u.useCallback(x=>{const $={...e};delete $[x],t($)},[e,t]),_=u.useCallback((x,$,S)=>{const C={...e};x&&x!==$&&delete C[x],C[$]=S,t(C)},[e,t]),w=u.useCallback(x=>{const $=Ed(x,{});let S=x.id,C=1;for(;S in e;)S=`${x.id}${++C}`;t({...e,[S]:$}),b(!1)},[e,t]),k=u.useCallback(()=>{!g||!g.key||(t({...e,[g.key]:Bs(g)}),m(null),b(!1))},[g,e,t]);return i.jsxs("div",{className:"g7le-computed-form","data-testid":"g7le-computed-form",style:V1,children:[i.jsx("p",{style:U1,children:o("layout_editor.page_settings.computed.heading")}),h.length>0?h.map(x=>i.jsx(H1,{computedKey:x,expr:e[x],recipes:p,rawRecipes:n,t:o,sampleContext:r,dataSourceCandidates:s,bindingCandidates:a,source:l[x],isEffect:d.includes(x),existingKeys:h,onPatchExpr:$=>v(x,$),onRename:($,S)=>_(x,$,S),onRemove:()=>y(x),onRevert:c?()=>c(x):void 0},x)):i.jsx("p",{"data-testid":"g7le-computed-empty",style:gS,children:o("layout_editor.computed.empty")}),i.jsxs("div",{style:{minWidth:0},children:[i.jsxs("button",{type:"button","data-testid":"g7le-computed-add",onClick:()=>b(x=>!x),style:sS,children:["+ ",o("layout_editor.computed.add")," ▾"]}),f?i.jsxs("div",{"data-testid":"g7le-computed-add-list",style:aS,children:[["common","more"].map(x=>{const $=p.filter(S=>(S.group??"more")===x);return $.length===0?null:i.jsxs("div",{children:[i.jsxs("div",{style:lS,children:["━━ ",o(`layout_editor.computed.group_${x}`)," ━━"]}),$.map(S=>{const C=W1(n?.[S.id]);return i.jsxs("button",{type:"button","data-testid":`g7le-computed-preset-${S.id}`,onClick:()=>w(S),style:dS,children:[i.jsx("span",{style:cS,children:Ws(S.label,o,S.id)}),C&&C.kind!=="core"?i.jsxs("span",{"data-testid":`g7le-computed-preset-source-${S.id}`,style:uS,children:["〔",C.id??C.kind,"〕"]}):null]},S.id)})]},x)}),i.jsxs("div",{style:{borderTop:"1px solid #e2e8f0",marginTop:6,paddingTop:6},children:[i.jsxs("button",{type:"button","data-testid":"g7le-computed-custom-open",onClick:()=>m(g?null:{key:"",op:"count",source:"",conditions:[]}),style:pS,children:["⚙ ",o("layout_editor.computed.custom_open")," ▾"]}),g?i.jsxs("div",{style:{marginTop:6},children:[i.jsx(pu,{model:g,onChange:m,t:o,dataSourceCandidates:s,bindingCandidates:a,existingKeys:h}),i.jsx("div",{"data-testid":"g7le-computed-custom-preview",style:{marginTop:6},children:i.jsx(uu,{expr:Bs(g),sampleContext:r,t:o,testIdPrefix:"g7le-computed-custom-preview-eval"})}),i.jsx("button",{type:"button","data-testid":"g7le-computed-custom-commit",disabled:!g.key||h.includes(g.key),onClick:k,style:fS,children:o("layout_editor.computed.custom_add")})]}):null]})]}):null]})]})}function H1({computedKey:e,expr:t,recipes:n,rawRecipes:o,t:r,sampleContext:s,dataSourceCandidates:a,bindingCandidates:l,source:d,isEffect:c,existingKeys:p,onPatchExpr:f,onRename:b,onRemove:g,onRevert:m}){const[h,v]=u.useState(!1),[y,_]=u.useState(!1),w=u.useMemo(()=>Dd(t,n),[t,n]),k=d==="base",x=d==="route-override",$=w.kind==="advanced",S=w.kind==="preset"?n.find(E=>E.id===w.recipeId)??null:null,C=S?Ws(S.label,r,e):e,T=(E,A)=>{if(w.kind!=="preset"||!S)return;const N={...w.params,[E]:A};f(Ed(S,N))};return i.jsxs("div",{"data-testid":`g7le-computed-item-${e}`,style:q1,children:[i.jsxs("div",{style:G1,children:[i.jsx("span",{style:Y1,children:C}),i.jsx("code",{style:X1,children:e}),k?i.jsxs("span",{"data-testid":`g7le-computed-source-${e}`,style:J1,children:["〔",r("layout_editor.computed.source_base"),"〕"]}):null,x?i.jsxs("span",{"data-testid":`g7le-computed-overridden-${e}`,style:Z1,children:["〔",r("layout_editor.computed.source_overridden"),"〕"]}):null,$?i.jsxs("span",{"data-testid":"g7le-computed-advanced",style:Q1,children:["[",r("layout_editor.action.advanced"),"]"]}):null,i.jsx("span",{style:{flex:1}}),i.jsx("button",{type:"button","data-testid":`g7le-computed-code-${e}`,onClick:()=>_(E=>!E),style:js,"aria-label":r("layout_editor.value_tree.show_source"),title:r("layout_editor.value_tree.show_source"),children:""}),$?null:i.jsx("button",{type:"button","data-testid":`g7le-computed-edit-${e}`,onClick:()=>v(E=>!E),style:js,children:r("layout_editor.init_actions.edit")}),i.jsx("button",{type:"button","data-testid":`g7le-computed-remove-${e}`,onClick:g,style:js,"aria-label":r("layout_editor.init_actions.remove"),children:"✕"})]}),y?i.jsx("pre",{"data-testid":`g7le-computed-code-block-${e}`,style:hS,children:t}):null,i.jsx("div",{"data-testid":`g7le-computed-preview-${e}`,children:i.jsx(uu,{expr:t,computedKey:e,sampleContext:s,t:r,isEffect:c,testIdPrefix:`g7le-computed-preview-${e}-eval`})}),x&&m?i.jsxs("div",{style:R1,children:[i.jsxs("span",{style:eS,children:["ⓘ ",r("layout_editor.computed.overridden_hint")]}),i.jsx("button",{type:"button","data-testid":`g7le-computed-revert-${e}`,onClick:m,style:tS,children:r("layout_editor.computed.revert")})]}):null,h&&!$?i.jsxs("div",{style:nS,children:[k?i.jsxs("p",{"data-testid":`g7le-computed-override-notice-${e}`,style:oS,children:["⚠ ",r("layout_editor.computed.override_notice")]}):null,w.kind==="preset"&&S?i.jsx(i.Fragment,{children:S.params.map(E=>i.jsx(K1,{param:E,value:w.params[E.key]??"",t:r,dataSourceCandidates:a,bindingCandidates:l,onChange:A=>T(E.key,A)},E.key))}):w.kind==="custom"?i.jsx(pu,{model:{...w.model,key:e},onChange:E=>b(E.key,Bs(E)),t:r,dataSourceCandidates:a,bindingCandidates:l,existingKeys:p.filter(E=>E!==e)}):null]}):null]})}const F1=new Set(["datasource-picker","binding-picker","select","toggle","state-key-picker","page-picker"]);function K1({param:e,value:t,t:n,dataSourceCandidates:o,bindingCandidates:r,onChange:s}){const a=Ws(e.label,n,e.key),l=e.widget??"",c=F1.has(l)?Tn(e.widget):null,p=l==="datasource-picker"||l==="binding-picker"?o:void 0;return i.jsxs("div",{"data-testid":`g7le-computed-param-${e.key}`,style:rS,children:[i.jsx("span",{style:iS,children:a}),i.jsx("div",{style:{flex:1,minWidth:0},children:c?i.jsx(c,{control:{...e},value:t,onChange:f=>s(typeof f=="string"?f:""),t:n,candidates:p}):i.jsx(Ke,{value:t,onChange:f=>s(f),t:n,candidates:r,testidPrefix:`g7le-computed-param-${e.key}-chip`})})]})}const V1={display:"flex",flexDirection:"column",gap:12,minWidth:0},U1={margin:0,fontSize:13,fontWeight:700,color:"#0f172a"},q1={border:"1px solid #e2e8f0",borderRadius:8,padding:"8px 10px",display:"flex",flexDirection:"column",gap:6,background:"#f8fafc"},G1={display:"flex",alignItems:"center",gap:6},Y1={fontSize:13,fontWeight:600,color:"#0f172a"},X1={fontSize:10,color:"#64748b",fontFamily:"monospace"},J1={fontSize:10,color:"#0891b2",whiteSpace:"nowrap"},Z1={fontSize:10,color:"#7c3aed",whiteSpace:"nowrap"},Q1={fontSize:10,color:"#92400e",whiteSpace:"nowrap"},R1={display:"flex",alignItems:"center",gap:8,marginTop:4,minWidth:0},eS={fontSize:11,color:"#7c3aed",flex:1,minWidth:0},tS={border:"1px solid #c4b5fd",borderRadius:6,background:"#f5f3ff",color:"#6d28d9",cursor:"pointer",fontSize:11,padding:"2px 8px",whiteSpace:"nowrap"},js={border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",fontSize:11,padding:"2px 6px"},nS={display:"flex",flexDirection:"column",gap:6,paddingTop:6,borderTop:"1px dashed #e2e8f0"},oS={margin:0,fontSize:11,color:"#b45309",background:"#fef3c7",padding:"6px 8px",borderRadius:6},rS={display:"flex",alignItems:"center",gap:8,minWidth:0},iS={fontSize:11,color:"#64748b",minWidth:90},sS={padding:"6px 12px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},aS={marginTop:6,border:"1px solid #cbd5e1",borderRadius:8,background:"#fff",padding:8,maxHeight:380,overflowY:"auto"},lS={fontSize:11,fontWeight:700,color:"#94a3b8",padding:"6px 4px 2px"},dS={display:"flex",alignItems:"center",gap:6,width:"100%",textAlign:"left",padding:"6px 8px",fontSize:12,border:"none",background:"transparent",cursor:"pointer",borderRadius:6},cS={flex:1,minWidth:0,color:"#0f172a"},uS={fontSize:10,color:"#64748b",whiteSpace:"nowrap"},pS={padding:"6px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},fS={marginTop:6,padding:"6px 12px",fontSize:12,border:"1px solid #3b82f6",borderRadius:6,background:"#3b82f6",color:"#fff",cursor:"pointer"},gS={margin:0,fontSize:12,color:"#94a3b8"},hS={margin:"2px 0 0",padding:"6px 8px",fontSize:11,fontFamily:"monospace",color:"#0f172a",background:"#f1f5f9",border:"1px solid #e2e8f0",borderRadius:6,whiteSpace:"pre-wrap",wordBreak:"break-all",overflowX:"auto"};function yS(e,t){return t==="any"?!0:e===null||typeof e!="object"?!1:t==="object"?!Array.isArray(e):!0}function Hs({value:e,onChange:t,onValidityChange:n,t:o,shape:r="any",emptyValue:s=void 0,placeholder:a,minHeight:l=80,testidPrefix:d="g7le-json-block",shapeErrorKey:c,invalidErrorKey:p,ariaLabel:f,id:b,validate:g}){const[m,h]=u.useState(()=>Kr(e)),[v,y]=u.useState(null),_=u.useRef(!1),w=u.useRef(e);u.useEffect(()=>{if(!_.current&&!Object.is(e,w.current)){if(Kr(e)===Kr(w.current)){w.current=e;return}h(Kr(e)),y(null),w.current=e,n?.(!0)}},[e]);const k=x=>{if(_.current=!0,h(x),x.trim()===""){y(null),w.current=s,n?.(!0),t(s);return}let $;try{$=JSON.parse(x)}catch{y(o(p??"layout_editor.json_block.invalid")),n?.(!1);return}if(!yS($,r)){y(o(c??"layout_editor.json_block.invalid")),n?.(!1);return}const S=g?.($)??null;if(S){y(S),n?.(!1);return}y(null),w.current=$,n?.(!0),t($)};return i.jsxs("div",{className:"g7le-json-block",style:bS,children:[i.jsx("textarea",{id:b,"data-testid":d,style:{...mS,minHeight:l},value:m,spellCheck:!1,"aria-label":f,"aria-invalid":v?!0:void 0,placeholder:a,onChange:x=>k(x.target.value),onBlur:()=>{_.current=!1}}),v?i.jsx("div",{"data-testid":`${d}-error`,style:vS,children:v}):null]})}function Kr(e){if(e===void 0)return"";try{return JSON.stringify(e,null,2)??""}catch{return""}}const bS={display:"flex",flexDirection:"column",gap:4,minWidth:0},mS={width:"100%",boxSizing:"border-box",fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:12,lineHeight:1.5,color:"#0f172a",background:"#fff",border:"1px solid #cbd5e1",borderRadius:6,padding:"6px 8px",resize:"vertical"},vS={fontSize:11,color:"#dc2626"},_S=[{kind:"string",labelKey:"layout_editor.initstate.kind_string"},{kind:"number",labelKey:"layout_editor.initstate.kind_number"},{kind:"boolean",labelKey:"layout_editor.initstate.kind_boolean"},{kind:"null",labelKey:"layout_editor.initstate.kind_null"},{kind:"list",labelKey:"layout_editor.initstate.kind_list"},{kind:"object",labelKey:"layout_editor.initstate.kind_object"}],Fs={local:"initLocal",global:"initGlobal",isolated:"initIsolated"};function xS({raw:e,own:t,patch:n,t:o,isolatedOrphan:r={}}){const s=u.useMemo(()=>{const f=t?.state&&typeof t.state=="object"?t.state:void 0,b=e?.state&&typeof e.state=="object"?e.state:void 0;if(!(!f&&!b))return{...b??{},...f??{}}},[t,e]),{initLocal:a,migrated:l}=u.useMemo(()=>K0({initLocal:e?.initLocal,state:s}),[e,s]),d=f=>{if(f==="local")return a;const b=e?.[Fs[f]];return b&&typeof b=="object"?b:{}},c=f=>{if(f==="local"){const b=t?.initLocal??{},g=s?Object.keys(s):[];return Array.from(new Set([...Object.keys(b),...g]))}return Object.keys(t?.[Fs[f]]??{})},p=u.useCallback((f,b)=>{const g=Fs[f];f==="local"&&l&&n("state",void 0),n(g,Object.keys(b).length===0?void 0:b)},[n,l]);return i.jsxs("div",{className:"g7le-initstate-form","data-testid":"g7le-initstate-form",style:kS,children:[i.jsx("p",{style:SS,children:o("layout_editor.page_settings.initstate.heading")}),l?i.jsxs("p",{"data-testid":"g7le-initstate-legacy-state",style:CS,children:["ⓘ ",o("layout_editor.initstate.legacy_state")]}):null,i.jsx(Ks,{scope:"local",label:o("layout_editor.initstate.section_local"),value:d("local"),ownKeys:c("local"),patchSection:p,t:o}),i.jsx(Ks,{scope:"global",label:o("layout_editor.initstate.section_global"),value:d("global"),ownKeys:c("global"),patchSection:p,t:o}),i.jsx(Ks,{scope:"isolated",label:o("layout_editor.initstate.section_isolated"),description:o("layout_editor.initstate.section_isolated_desc"),value:d("isolated"),ownKeys:c("isolated"),patchSection:p,t:o,orphan:r}),i.jsxs("p",{style:KS,children:["ⓘ ",o("layout_editor.initstate.isolated_dynamic_hint")]})]})}function Ks({scope:e,label:t,description:n,value:o,ownKeys:r,patchSection:s,t:a,orphan:l={}}){const[d,c]=u.useState(""),[p,f]=u.useState("string"),[b,g]=u.useState(null),[m,h]=u.useState(!1),v=Object.keys(o),y=v,_=(x,$)=>{s(e,{...o,[x]:$})},w=x=>{const $={...o};delete $[x],s(e,$)},k=()=>{const x=d.trim();if(!x){g(a("layout_editor.initstate.name_required"));return}if(!Ds(x)){g(a("layout_editor.initstate.name_invalid"));return}if(x in o){g(a("layout_editor.initstate.name_duplicate"));return}const $={string:"",number:0,boolean:!1,null:null,list:[],object:{}};s(e,{...o,[x]:$[p]}),c(""),g(null)};return i.jsxs("div",{"data-testid":`g7le-initstate-section-${e}`,style:$S,children:[i.jsxs("div",{style:ES,children:[i.jsx("div",{style:IS,children:t}),i.jsx("button",{type:"button","data-testid":`g7le-initstate-${e}-mode-toggle`,onClick:()=>h(x=>!x),style:TS,children:a(m?"layout_editor.json_block.mode_block":"layout_editor.json_block.mode_code")})]}),n?i.jsxs("p",{style:AS,children:["ⓘ ",n]}):null,m?i.jsx(Hs,{value:o,shape:"object",emptyValue:{},onChange:x=>s(e,x??{}),t:a,testidPrefix:`g7le-initstate-${e}-code`,placeholder:`{ "keyword": "", "page": 1 }`,shapeErrorKey:"layout_editor.json_block.must_be_object",validate:x=>{const $=Object.keys(x??{}).filter(S=>!Ds(S));return $.length?a("layout_editor.json_block.invalid_keys",{keys:$.join(", ")}):null}}):i.jsxs(i.Fragment,{children:[v.length===0?i.jsx("p",{"data-testid":`g7le-initstate-${e}-empty`,style:FS,children:a("layout_editor.initstate.no_values")}):v.map(x=>{const S=F0(y,r,x)==="inherited",C=e==="isolated"&&l[x];return i.jsx(wS,{scope:e,itemKey:x,value:o[x],inherited:S,isOrphan:!!C,onChangeValue:T=>_(x,T),onRemove:()=>w(x),t:a},x)}),i.jsxs("div",{style:PS,children:[i.jsx("input",{type:"text","data-testid":`g7le-initstate-${e}-add-name`,value:d,placeholder:a("layout_editor.initstate.value_name"),onChange:x=>{c(x.target.value),b&&g(null)},onKeyDown:x=>{x.key==="Enter"&&(x.preventDefault(),k())},"aria-invalid":b?!0:void 0,style:{...OS,...b?BS:null}}),i.jsx("select",{"data-testid":`g7le-initstate-${e}-add-kind`,value:p,onChange:x=>f(x.target.value),"aria-label":a("layout_editor.initstate.value_kind"),style:jS,children:_S.map(x=>i.jsx("option",{value:x.kind,children:a(x.labelKey)},x.kind))}),i.jsxs("button",{type:"button","data-testid":`g7le-initstate-${e}-add`,onClick:k,style:HS,children:["+ ",a("layout_editor.initstate.add_value")]})]}),b?i.jsx("p",{"data-testid":`g7le-initstate-${e}-add-error`,style:WS,children:b}):null]})]})}function wS({scope:e,itemKey:t,value:n,inherited:o,isOrphan:r,onChangeValue:s,onRemove:a,t:l}){const[d,c]=u.useState(!1);let p;try{p=JSON.stringify(n,null,2)??String(n)}catch{p=String(n)}return i.jsxs("div",{"data-testid":`g7le-initstate-${e}-item-${t}`,style:DS,children:[i.jsxs("div",{style:zS,children:[o?i.jsx("span",{"data-testid":`g7le-initstate-inherited-${t}`,style:NS,children:"🔗"}):null,i.jsx("code",{style:MS,children:t}),i.jsx("span",{style:{flex:1}}),i.jsx("button",{type:"button","data-testid":`g7le-initstate-code-${t}`,onClick:()=>c(f=>!f),style:Vs,"aria-label":l("layout_editor.value_tree.show_source"),title:l("layout_editor.value_tree.show_source"),children:""}),o?i.jsx("button",{type:"button","data-testid":`g7le-initstate-revert-${t}`,onClick:a,style:Vs,children:l("layout_editor.initstate.revert")}):i.jsx("button",{type:"button","data-testid":`g7le-initstate-remove-${t}`,onClick:a,style:Vs,"aria-label":l("layout_editor.init_actions.remove"),children:"✕"})]}),d?i.jsx("pre",{"data-testid":`g7le-initstate-code-block-${t}`,style:VS,children:p}):null,i.jsx(zn,{value:n,onChange:s,t:l,path:t,scope:e}),r?i.jsxs("p",{"data-testid":`g7le-initstate-isolated-orphan-${t}`,style:LS,children:["⚠ ",l("layout_editor.initstate.isolated_orphan")]}):null]})}const kS={display:"flex",flexDirection:"column",gap:14,minWidth:0},SS={margin:0,fontSize:13,fontWeight:700,color:"#0f172a"},CS={margin:0,fontSize:11,color:"#1d4ed8",background:"#eff6ff",padding:"6px 8px",borderRadius:6},$S={display:"flex",flexDirection:"column",gap:8,padding:10,border:"1px solid #e2e8f0",borderRadius:10,minWidth:0},ES={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},IS={fontSize:12,fontWeight:700,color:"#475569"},AS={margin:0,fontSize:11,color:"#94a3b8"},TS={padding:"2px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},DS={display:"flex",flexDirection:"column",gap:4,padding:"6px 8px",border:"1px solid #f1f5f9",borderRadius:6,minWidth:0},zS={display:"flex",alignItems:"center",gap:6},NS={fontSize:12},MS={fontSize:12,color:"#0f172a",fontFamily:"monospace"},Vs={border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",fontSize:11,padding:"2px 6px"},LS={margin:0,fontSize:11,color:"#b45309",background:"#fef3c7",padding:"4px 6px",borderRadius:6},PS={display:"flex",gap:6,alignItems:"center"},OS={padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},BS={border:"1px solid #dc2626"},WS={margin:0,fontSize:11,color:"#dc2626"},jS={padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#0f172a"},HS={padding:"2px 10px",fontSize:11,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},FS={margin:0,fontSize:12,color:"#94a3b8"},KS={margin:0,fontSize:11,color:"#94a3b8"},VS={margin:"2px 0",padding:"6px 8px",fontSize:11,fontFamily:"monospace",color:"#0f172a",background:"#f1f5f9",border:"1px solid #e2e8f0",borderRadius:6,whiteSpace:"pre-wrap",wordBreak:"break-all",overflowX:"auto"},US={self:"layout_editor.error_rows.source_self",inherited:"layout_editor.error_rows.source_inherited",template:"layout_editor.error_rows.source_template",none:"layout_editor.error_rows.source_none"};function Us({value:e,onChange:t,t:n,codes:o,mode:r="local",sourceOf:s,renderActionList:a,testIdPrefix:l="g7le-error-rows"}){const d=o??Object.keys(e),c=u.useCallback((f,b)=>{t({...e,[f]:b})},[e,t]),p=u.useCallback(f=>{const b={...e};delete b[f],t(b)},[e,t]);return i.jsx("div",{className:l,"data-testid":l,children:d.map(f=>{const b=e[f],g=b!==void 0,m=r==="badge"&&s?s(f):null;return i.jsxs("div",{"data-testid":`${l}-row-${f}`,style:{border:"1px solid #e2e8f0",borderRadius:8,padding:"8px 10px",marginBottom:6},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("strong",{"data-testid":`${l}-code-${f}`,style:{fontSize:13},children:f==="default"?n("layout_editor.error_rows.default"):f}),m?i.jsxs("span",{"data-testid":`${l}-source-${f}`,style:{fontSize:11,padding:"2px 6px",borderRadius:4,background:"#f1f5f9",color:"#475569"},children:["〔",n(US[m]),"〕"]}):null,g?i.jsx("button",{type:"button","data-testid":`${l}-clear-${f}`,onClick:()=>p(f),style:{marginLeft:"auto",fontSize:12},children:n("layout_editor.error_rows.clear")}):i.jsx("span",{style:{marginLeft:"auto",fontSize:12,color:"#94a3b8"},children:n("layout_editor.error_rows.no_action")})]}),m==="inherited"||m==="template"?i.jsxs("div",{"data-testid":`${l}-override-${f}`,style:{marginTop:6,display:"flex",alignItems:"flex-start",gap:8},children:[i.jsxs("p",{style:{margin:0,flex:1,fontSize:12,color:"#64748b"},children:["ⓘ ",n(m==="inherited"?"layout_editor.error_rows.override_inherited":"layout_editor.error_rows.override_template")]}),g?i.jsx("button",{type:"button","data-testid":`${l}-revert-${f}`,onClick:()=>p(f),style:{fontSize:12,padding:"2px 8px",border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},children:n("layout_editor.error_rows.revert")}):i.jsx("button",{type:"button","data-testid":`${l}-override-here-${f}`,onClick:()=>c(f,{}),style:{fontSize:12,padding:"2px 8px",border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},children:n("layout_editor.error_rows.override_here")})]}):null,f==="default"?i.jsxs("p",{"data-testid":`${l}-default-warn-${f}`,style:{margin:"6px 0 0",fontSize:12,color:"#b45309"},children:["⚠ ",n("layout_editor.error_rows.default_warning")]}):null,i.jsx("div",{style:{marginTop:6},children:a?a(f,b,h=>c(f,h)):i.jsx("pre",{"data-testid":`${l}-json-${f}`,style:{margin:0,fontSize:12,color:"#475569"},children:g?JSON.stringify(b):""})})]},f)})})}function qS(e){return[...e.filter(n=>n!=="maintenance"),"default"]}function GS({value:e,onChange:t,t:n,errorConfigCodes:o=[],ownCodes:r=[],templateCodes:s=[],recipes:a,pageCandidates:l,modalCandidates:d,dataSourceCandidates:c,stateKeyCandidates:p}){const f=u.useMemo(()=>ko(a),[a]),b=u.useMemo(()=>qS(o),[o]),g=f.length>0,m=u.useMemo(()=>Vl("error",n),[n]),h=u.useMemo(()=>({pageCandidates:l,dataSourceCandidates:c,stateKeyCandidates:p,modalCandidates:d,bindingCandidates:m}),[l,c,p,d,m]),v=u.useCallback(y=>r.includes(y)?"self":y in e?"inherited":s.includes(y)?"template":"none",[r,e,s]);return g?i.jsxs("div",{className:"g7le-error-form","data-testid":"g7le-error-form",style:fu,children:[i.jsx("p",{style:gu,children:n("layout_editor.page_settings.error.heading")}),i.jsxs("p",{style:XS,children:["ⓘ ",n("layout_editor.error.intro")]}),i.jsx(Us,{value:e,onChange:t,t:n,codes:b,mode:"badge",sourceOf:v,testIdPrefix:"g7le-error-rows",renderActionList:(y,_,w)=>i.jsx(YS,{code:y,action:_,recipes:a,normalized:f,t:n,pools:h,onPatch:w})})]}):i.jsxs("div",{className:"g7le-error-form","data-testid":"g7le-error-form",style:fu,children:[i.jsx("p",{style:gu,children:n("layout_editor.page_settings.error.heading")}),i.jsxs("p",{"data-testid":"g7le-error-degrade",style:JS,children:["ⓘ ",n("layout_editor.error.degrade")]}),i.jsx(Us,{value:e,onChange:t,t:n,codes:b,mode:"badge",sourceOf:v,testIdPrefix:"g7le-error-rows"})]})}function YS({code:e,action:t,recipes:n,normalized:o,t:r,pools:s,onPatch:a}){const[l,d]=u.useState(!1),c=Array.isArray(t)?t[0]:t,p=typeof c?.handler=="string"?c.handler:"",f=o.find(_=>_.id===p)??null,b=c?Yn(c,o):null,g=b?.kind==="preset"?b.values:{},m=p==="sequence"||p==="parallel",h=_=>{if(_===""){a({});return}const w=o.find(k=>k.id===_);w&&a(Sr(w,{}))},v=["","showErrorPage","navigate","openModal","toast","setState","sequence","parallel"],y=m&&c?Array.isArray(c.params?.actions)?c.params.actions:[]:[];return i.jsxs("div",{"data-testid":`g7le-error-action-${e}`,style:ZS,children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsx("select",{"data-testid":`g7le-error-handler-${e}`,value:p,onChange:_=>h(_.target.value),style:{...QS,flex:1},children:v.map(_=>i.jsx("option",{value:_,children:r(_===""?"layout_editor.error.handler_none":`layout_editor.error.handler_${_}`)},_))}),p!==""?i.jsx("button",{type:"button","data-testid":`g7le-error-code-${e}`,onClick:()=>d(_=>!_),"aria-label":r("layout_editor.action_list.view_code"),title:r("layout_editor.action_list.view_code"),style:l?RS:hu,children:""}):null]}),m?i.jsx("div",{"data-testid":`g7le-error-actions-${e}`,children:i.jsx(Gt,{actions:y,onChange:_=>a({handler:p,params:{actions:_}}),t:r,recipes:n,candidatePools:s,chipContext:"error",testIdPrefix:`g7le-error-seq-${e}`})}):f&&c?i.jsx(Ns,{raw:c,recipe:f,values:g,t:r,pools:s,onChange:_=>a(_),testIdPrefix:`g7le-error-action-${e}-edit`}):null,l&&c?i.jsx("pre",{"data-testid":`g7le-error-code-view-${e}`,style:eC,children:JSON.stringify(t,null,2)}):null]})}const fu={display:"flex",flexDirection:"column",gap:12,minWidth:0},gu={margin:0,fontSize:13,fontWeight:700,color:"#0f172a"},XS={margin:0,fontSize:11,color:"#94a3b8"},JS={margin:0,fontSize:12,color:"#b45309",background:"#fef3c7",padding:"8px 10px",borderRadius:6},ZS={display:"flex",flexDirection:"column",gap:6,minWidth:0},QS={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},hu={flex:"0 0 auto",width:26,height:26,display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:11,border:"1px solid #e2e8f0",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer",fontFamily:"ui-monospace, monospace"},RS={...hu,background:"#0f172a",borderColor:"#0f172a",color:"#e2e8f0"},eC={margin:"4px 0 0",padding:8,background:"#0f172a",color:"#e2e8f0",borderRadius:6,fontSize:12,overflow:"auto",fontFamily:"ui-monospace, monospace"};function Vr(e){const t=e.trim(),n=/^\{\{([\s\S]*)\}\}$/.exec(t);return n?n[1].trim():t}function tC(e){let t=e;for(;t.length>=2&&t[0]==="("&&t[t.length-1]===")";){let n=0,o=!0;for(let r=0;r!!o&&typeof o.value=="string"&&typeof o.expr=="string").map(o=>({value:o.value,label:typeof o.label=="string"?o.label:void 0,params:Array.isArray(o.params)?o.params:[],expr:Vr(o.expr),aliases:yu(o.aliases)}));const n=[];for(const[o,r]of Object.entries(e)){if(o==="comment"||o==="operators"||!r||typeof r!="object")continue;const s=r;typeof s.expr=="string"&&n.push({value:o,label:typeof s.label=="string"?s.label:void 0,params:Array.isArray(s.params)?s.params:[],expr:Vr(s.expr),aliases:yu(s.aliases)})}return n}function yu(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){if(typeof n!="string")continue;const o=Vr(n);o.trim().length>0&&t.push(o)}return t}function oC(e){const t=e.params.length*1e3;return Ur(e.expr).replace(/\{\w+\}/g,"").length-t}function rC(e){return e.map((t,n)=>({op:t,idx:n,score:oC(t)})).sort((t,n)=>n.score-t.score||t.idx-n.idx).map(t=>t.op)}function iC(e,t){return e.replace(/\{(\w+)\}/g,(n,o)=>{const r=t[o];return r===void 0?n:r})}function sC(e,t){const n=t.find(o=>o.value===e.operator);return n?iC(n.expr,e.params??{}):null}function bu(e,t,n){const o=e.map(a=>sC(a,n)).filter(a=>typeof a=="string"&&a.trim().length>0);if(o.length===0)return"";if(o.length===1)return`{{ ${o[0]} }}`;const r=t==="or"?" || ":" && ";return`{{ ${o.map(a=>`(${a})`).join(r)} }}`}function mu(e,t){const n=Ur(e);for(const o of rC(t)){if(o.params.length===0){for(const r of[o.expr,...o.aliases])if(Ur(r)===n)return{operator:o.value,params:{}};continue}for(const r of[o.expr,...o.aliases]){const s=aC(o,r,n);if(s)return s}}return null}function aC(e,t,n){const o=t.trim(),r=[];let s="",a=0;for(;a=|<=|>|<|\?|:|\(|\)|!/.test(b))return null;return{operator:e.value,params:c}}function lC(e){const t=new Set,n=/(['"])\{(\w+)\}\1/g;let o;for(;(o=n.exec(e))!==null;)t.add(o[2]);return t}function dC(e,t){if(typeof e!="string"||e.trim()==="")return null;const n=Vr(e),o=mu(n,t);if(o)return{clauses:[o],combinator:"and"};const r=n.includes(") || (")?"or":(n.includes(") && ("),"and"),s=r==="or"?") || (":") && (";if(!n.startsWith("(")||!n.endsWith(")")||!n.includes(s))return null;const l=n.slice(1,-1).split(s),d=[];for(const c of l){const p=mu(c.trim(),t);if(!p)return null;d.push(p)}return{clauses:d,combinator:r}}const vu=Lt(),Mn=vu.responsiveManager,Do=vu.BREAKPOINT_PRESETS;function _u(e){const t=e.groupPrefixes;return{group:typeof e.group=="string"?e.group:void 0,apply:e.apply&&typeof e.apply=="object"?e.apply:void 0,options:Array.isArray(e.options)?e.options:void 0,scale:Array.isArray(e.scale)?e.scale:void 0,groupPrefixes:Array.isArray(t)?t.filter(n=>typeof n=="string"&&n.length>0):void 0,groupTokens:Array.isArray(e.groupTokens)?e.groupTokens.filter(n=>typeof n=="string"&&n.length>0):void 0}}function xu(e){const t={...e??{}},n=t.style&&typeof t.style=="object"&&!Array.isArray(t.style)?{...t.style}:{};return t.style=n,{props:t,style:n}}function qr(e){return typeof e!="string"?[]:e.split(/\s+/).filter(t=>t.length>0)}function wu(e,t=!1){const n=new Set,o=[],r=s=>{if(s){for(const a of s.tokens??[])n.add(a);s.tokenTemplate&&s.tokenTemplate.includes("{value}")&&o.push(s.tokenTemplate.split("{value}")[0]??"")}};r(e.apply);for(const s of e.options??[])r(s.apply);for(const s of e.groupPrefixes??[])o.push(s);for(const s of e.groupTokens??[])n.add(s);return s=>{if(t){if(!Yt(s))return!1;const a=Xs(s);return n.has(a)?!0:o.some(l=>l.length>0&&a.startsWith(l))}return Yt(s)?!1:n.has(s)?!0:o.some(a=>a.length>0&&s.startsWith(a))}}function cC(e,t,n,o,r=!1){const s=wu(t,r),a=qr(e.className).filter(p=>!s(p)),l=[];if(Array.isArray(n.tokens))l.push(...n.tokens);else if(n.tokenTemplate&&n.tokenTemplate.includes("{value}")&&o!=null){const p=String(o).split(/\s+/).filter(f=>f.length>0);for(const f of p)l.push(n.tokenTemplate.replace("{value}",f))}const d=r?l.map(Iu):l,c=[...a,...d];c.length===0?delete e.className:e.className=c.join(" ")}const qs={url:"backgroundImage",size:"backgroundSize",repeat:"backgroundRepeat",position:"backgroundPosition"};function uC(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.keys(qs).some(t=>t in e)}function pC(e){return/^url\(/i.test(e.trim())?e:`url(${e})`}function ku(e){const t=/^url\(\s*(['"]?)(.*?)\1\s*\)$/i.exec(e.trim());return t?t[2]:e}function fC(e){return e.includes("backgroundImage")}function Gs(e,t){if(e!=null){if(typeof e=="object"){const n=e[t];return typeof n=="string"||typeof n=="number"?n:void 0}return e}}function gC(e){const t=e.backgroundImage,n=Gs(e.backgroundSize,"size"),o=Gs(e.backgroundRepeat,"repeat"),r=Gs(e.backgroundPosition,"position");let s;if(typeof t=="string"?s=ku(t):t&&typeof t=="object"?s=t.url:s=void 0,s===void 0&&n===void 0&&o===void 0&&r===void 0)return;const a={};return s!==void 0&&(a.url=typeof s=="string"?ku(s):s),n!==void 0&&(a.size=n),o!==void 0&&(a.repeat=o),r!==void 0&&(a.position=r),a}function hC(e,t,n){const o=(r,s)=>{s==null||s===""?delete e[r]:e[r]=s};if(Array.isArray(t.props)){if(!t.values&&uC(n)){for(const r of t.props){const s=Object.keys(qs).find(d=>qs[d]===r);let a=s?n[s]:void 0;a!==null&&typeof a=="object"&&(a=void 0);const l=r==="backgroundImage"&&typeof a=="string"&&a!==""?pC(a):a;o(r,l)}return}for(const r of t.props){const s=t.values&&r in t.values?t.values[r]:n;o(r,s)}return}typeof t.prop=="string"&&o(t.prop,t.value!==void 0?t.value:n)}function yC(e,t,n){if(typeof t.varName!="string")return;const o=t.value!==void 0?t.value:n;o==null||o===""?delete e[t.varName]:e[t.varName]=o}function bC(e,t,n){if(typeof t.propKey!="string")return;const o=t.value!==void 0?t.value:n;o==null||o===""?delete e[t.propKey]:e[t.propKey]=o}function fn(e,t,n,o=Wt){const r=_u(t),s=o.colorScheme==="dark";let a,l=!1;if(r.options){const b=r.options.find(g=>g.value===n);l=b!==void 0,a=b?.apply??r.apply}else a=r.apply;const d=n==null||n===""||l&&a===void 0,p=(d?r.apply:a)?.type==="classToken"||(r.options?.some(b=>b.apply?.type==="classToken")??!1);if(s&&!p)return e;const f=o.breakpoint!=="base"&&p?(()=>{const b=e.props??{};return typeof b.className=="string"?b.className:void 0})():void 0;return Eu(e,o,(b,g)=>{if(f!==void 0&&typeof b.className!="string"&&(b.className=f),d){const m=wu(r,s),h=qr(b.className).filter(v=>!m(v));if(h.length===0?delete b.className:b.className=h.join(" "),!s&&r.apply){const v=r.apply;if(v.type==="styleProp")for(const y of v.props??(v.prop?[v.prop]:[]))delete g[y];else v.type==="cssVar"&&v.varName?delete g[v.varName]:v.type==="propValue"&&v.propKey&&delete b[v.propKey]}}else if(a)switch(a.type){case"classToken":cC(b,r,a,n,s);break;case"styleProp":hC(g,a,n);break;case"cssVar":yC(g,a,n);break;case"propValue":bC(b,a,n);break}})}function Gr(e,t){const n=qr(e);return t?n.filter(Yt).map(Xs):n.filter(o=>!Yt(o))}function mC(e,t,n,o){const r=new Set(t.filter(l=>typeof l=="string"&&l.length>0)),s=l=>o?Yt(l)?r.has(Xs(l)):!1:Yt(l)?!1:r.has(l),a=qr(e).filter(l=>!s(l));return n&&n.length>0&&a.push(o?Iu(n):n),a.join(" ").trim()}function Su(e,t,n,o){if(e.options&&e.options.some(s=>s.apply)){const s=Gr(t.className,o),a=[];for(const l of e.options)l.apply&&_C(l.apply,s,n,t)&&a.push(l.value);if(a.length>0)return{value:a[0],matched:!0,conflict:a.length>1?!0:void 0};if(!e.apply)return{value:void 0,matched:!1}}const r=e.apply;if(!r)return{value:void 0,matched:!1};switch(r.type){case"styleProp":{if(!r.values&&Array.isArray(r.props)&&fC(r.props)){const l=gC(n);return l===void 0?{value:void 0,matched:!1}:{value:l,matched:!0}}const s=r.prop??r.props?.[0];if(!s)return{value:void 0,matched:!1};const a=n[s];return a===void 0?{value:void 0,matched:!1}:{value:a,matched:!0}}case"cssVar":{if(!r.varName)return{value:void 0,matched:!1};const s=n[r.varName];return s===void 0?{value:void 0,matched:!1}:{value:s,matched:!0}}case"propValue":{if(!r.propKey)return{value:void 0,matched:!1};const s=t[r.propKey];return s===void 0?{value:void 0,matched:!1}:{value:s,matched:!0}}case"classToken":{const s=Gr(t.className,o);if(r.tokenTemplate&&r.tokenTemplate.includes("{value}")){const[a,l]=r.tokenTemplate.split("{value}");if((a??"")===""&&(l??"")===""&&e.groupPrefixes?.length){const d=s.filter(c=>e.groupPrefixes.some(p=>c.startsWith(p)));return d.length>0?{value:d.join(" "),matched:!0}:{value:void 0,matched:!1}}for(const d of s)if(d.startsWith(a)&&d.endsWith(l??""))return{value:d.slice(a.length,l?d.length-l.length:void 0),matched:!0}}return Array.isArray(r.tokens)&&r.tokens.every(a=>s.includes(a))?{value:!0,matched:!0}:{value:void 0,matched:!1}}default:return{value:void 0,matched:!1}}}function Cu(e){return e.style&&typeof e.style=="object"&&!Array.isArray(e.style)?e.style:{}}function zo(e,t,n=Wt){const o=_u(t),r=n.colorScheme==="dark";if(r&&!Ys(o.apply)&&!o.options?.some(m=>Ys(m.apply)))return{value:void 0,matched:!1,darkReadonly:!0};const s=CC(e,n),a=Cu(s),l=Su(o,s,a,r);if(n.breakpoint==="base")return l;const d=l.matched?l.value:void 0,c=e.props??{},p=Cu(c),f=Su(o,c,p,r),b=l.matched&&l.value!==void 0,g=b&&!vC(l.value,f.value);return{value:b?l.value:f.value,matched:g?l.matched:f.matched,conflict:g?l.conflict:f.conflict,scopedValue:g?l.value:void 0,baseFallback:g?void 0:f.value,scopedRawValue:d}}function vC(e,t){if(e===t)return!0;if(e===null||t===null||typeof e!="object"||typeof t!="object")return!1;try{return JSON.stringify(e)===JSON.stringify(t)}catch{return!1}}function _C(e,t,n,o){switch(e.type){case"classToken":return Array.isArray(e.tokens)&&e.tokens.length>0?e.tokens.every(r=>t.includes(r)):!1;case"styleProp":{const r=e.prop??e.props?.[0];if(!r)return!1;const s=e.value;return s!==void 0?n[r]===s:n[r]!==void 0}case"cssVar":return e.varName?n[e.varName]!==void 0:!1;case"propValue":return e.propKey?e.value!==void 0?o[e.propKey]===e.value:o[e.propKey]!==void 0:!1;default:return!1}}const Wt={colorScheme:"base",breakpoint:"base"},No="dark:";function xC(e){return e==="base"?!0:Mn.parseRange(e)!==null}function $u(e){return e in Do}function Yr(e,t,n){if(e==="custom"){if(typeof n=="number"){const o=t.responsive;if(o&&typeof o=="object"){const r=Mn.getMatchingKey(o,n);if(r)return r}}return"base"}return e}function wC(e){return!!e&&typeof e=="object"&&Array.isArray(e.children)}function kC(e,t,n){let o,r,s;if(e!=="custom"&&e in Do){o=e;const l=Do[e];r=l.min,s=l.max}else if(e!=="custom"){const l=Mn.parseRange(e);if(l)o=e,r=l.min,s=l.max;else{const d=typeof n=="number"?n:Mn.getWidth();o=`${d}-${d}`,r=d,s=d}}else{const l=typeof n=="number"?n:Mn.getWidth();r=l,s=l,o=`${l}-${l}`}const a=t.responsive;if(a&&typeof a=="object"){let l=null,d=1/0;for(const c of Object.keys(a)){if(!wC(a[c]))continue;const p=Mn.parseRange(c);if(p){if(p.min===r&&p.max===s)return{mode:"merge",key:c};if(p.min<=r&&p.max>=s){const f=p.max-p.min;ft.length>0):[]}function IC(e,t){if(t.colorScheme==="dark")return Eu(e,t,l=>{const d=Xr(l.className).filter(c=>!Yt(c));d.length===0?delete l.className:l.className=d.join(" ")});if(t.breakpoint==="base")return e;const o=t.breakpoint;if(!e.responsive?.[o])return e;const r={...e.responsive},s={...r[o]};delete s.props,Object.keys(s).length===0?delete r[o]:r[o]=s;const a={...e};return Object.keys(r).length===0?delete a.responsive:a.responsive=r,a}function Js(e,t){if(t.colorScheme==="dark"){const c=t.breakpoint==="base"?e.props:e.responsive?.[t.breakpoint]?.props;return Xr(c?.className).some(Yt)}if(t.breakpoint==="base")return!1;const o=e.responsive?.[t.breakpoint];if(!o)return!1;const r=o.props;if(Object.keys(o).filter(c=>c!=="props").length>0)return!0;if(!r)return!1;if(Object.keys(r).filter(c=>c!=="className").length>0)return!0;const l=new Set(Xr(e.props?.className).filter(c=>!Yt(c))),d=Xr(r.className).filter(c=>!Yt(c));return d.length!==l.size?!0:d.some(c=>!l.has(c))}function Au(e,t,n=""){return typeof e!="string"?n:e.startsWith("$t:")?t(e.slice(3)):e}function Tu(e,t,n){if(n.breakpoint!=="base")return EC(e,n,t.trim());const o={...e};if(o.props&&typeof o.props=="object"&&"if"in o.props){const r={...o.props};delete r.if,o.props=r}return t.trim()===""?delete o.if:o.if=t,o}function Du({node:e,spec:t,t:n,onPatchNode:o,dataSourceCandidates:r,stateKeyCandidates:s,scope:a=Wt}){const l=u.useMemo(()=>nC(t?.conditionRecipes),[t]),d=a.breakpoint!=="base"?$C(e,a):e.if??e.props?.if,c=u.useMemo(()=>dC(d,l),[d,l]),p=c?.clauses??[],f=c?.combinator??"and",b=typeof d=="string"&&d.trim()!==""&&c===null;if(l.length===0)return i.jsx("div",{"data-testid":"g7le-condition-no-recipes",style:AC,children:n("layout_editor.visibility.no_recipes")});const g=(w,k)=>{o(Tu(e,bu(w,k,l),a))},m=(w,k)=>{g(p.map((x,$)=>$===w?k:x),f)},h=w=>{g(p.filter((k,x)=>x!==w),f)},v=w=>{const k=l[0];g([...p,{operator:k.value,params:{}}],w)},y=w=>{if(w==="datasource-picker")return r;if(w==="state-key-picker")return s};if(b)return i.jsxs("div",{className:"g7le-condition-advanced","data-testid":"g7le-condition-advanced",style:{display:"flex",flexDirection:"column",gap:8},children:[i.jsx("div",{style:BC,children:n("layout_editor.visibility.advanced_preserved")}),i.jsx("code",{"data-testid":"g7le-condition-advanced-expr",style:Nu,children:String(d)}),i.jsx("button",{type:"button","data-testid":"g7le-condition-clear-advanced",onClick:()=>o(Tu(e,"",a)),style:WC,children:n("layout_editor.visibility.clear")})]});const _=bu(p,f,l);return i.jsxs("div",{className:"g7le-condition-builder","data-testid":"g7le-condition-builder",style:{display:"flex",flexDirection:"column",gap:10},children:[i.jsx("div",{style:TC,children:n("layout_editor.visibility.show_when")}),p.map((w,k)=>{const x=l.find($=>$.value===w.operator)??l[0];return i.jsxs("div",{className:"g7le-condition-clause","data-testid":`g7le-condition-clause-${k}`,style:DC,children:[i.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[k>0&&i.jsx("span",{"data-testid":`g7le-condition-combinator-${k}`,style:NC,children:n(f==="or"?"layout_editor.visibility.or":"layout_editor.visibility.and")}),i.jsx("select",{"data-testid":`g7le-condition-select-${k}`,value:w.operator,onChange:$=>m(k,{operator:$.target.value,params:{}}),style:zC,children:l.map($=>i.jsx("option",{value:$.value,children:Au($.label,n,$.value)},$.value))}),i.jsx("button",{type:"button","data-testid":`g7le-condition-remove-${k}`,"aria-label":n("layout_editor.visibility.remove"),onClick:()=>h(k),style:MC,children:"✕"})]}),x.params.map($=>{const S=Tn($.widget);return i.jsxs("div",{className:"g7le-condition-param","data-testid":`g7le-condition-param-${k}-${$.key}`,style:LC,children:[i.jsx("span",{style:PC,children:Au($.label,n,$.key)}),i.jsx("div",{style:{flex:1},children:S?i.jsx(S,{control:{...$},value:w.params[$.key],onChange:C=>m(k,{operator:w.operator,params:{...w.params,[$.key]:C===void 0?"":String(C)}}),t:n,candidates:y($.widget)}):i.jsx("span",{style:{fontSize:11,color:"#94a3b8"},children:n("layout_editor.property_modal.unsupported_widget")})})]},$.key)})]},k)}),i.jsxs("div",{style:{display:"flex",gap:6},children:[i.jsxs("button",{type:"button","data-testid":"g7le-condition-add-and",onClick:()=>v("and"),style:zu,children:["+ ",n("layout_editor.visibility.and")]}),i.jsxs("button",{type:"button","data-testid":"g7le-condition-add-or",onClick:()=>v("or"),style:zu,children:["+ ",n("layout_editor.visibility.or")]})]}),_!==""&&i.jsxs("div",{"data-testid":"g7le-condition-preview",style:OC,children:[i.jsx("span",{style:{fontSize:11,color:"#64748b"},children:n("layout_editor.visibility.preview")}),i.jsx("code",{style:Nu,children:_})]})]})}const AC={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},TC={fontSize:12,fontWeight:600,color:"#0f172a"},DC={border:"1px solid #e2e8f0",borderRadius:8,padding:10,display:"flex",flexDirection:"column",gap:8,background:"#f8fafc"},zC={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff"},NC={fontSize:11,fontWeight:700,color:"#2563eb",background:"#dbeafe",padding:"2px 8px",borderRadius:999},MC={border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12},zu={padding:"5px 12px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},LC={display:"flex",alignItems:"center",gap:8},PC={fontSize:11,color:"#64748b",minWidth:64},OC={display:"flex",flexDirection:"column",gap:4,padding:10,background:"#f1f5f9",borderRadius:6},Nu={fontSize:11,color:"#0f172a",fontFamily:"monospace",wordBreak:"break-all"},BC={fontSize:11,color:"#92400e",background:"#fef3c7",padding:"6px 8px",borderRadius:6},WC={padding:"5px 12px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer",alignSelf:"flex-start"};function jC(e){return typeof e=="string"?e:e===void 0?"":JSON.stringify(e)}function HC(e){const t=e.trim();if(t==="")return"";if(/^-?\d+(\.\d+)?$/.test(t)||t==="true"||t==="false"||t==="null")try{return JSON.parse(t)}catch{return e}return e}function Mu(e){return!e||typeof e!="object"||Array.isArray(e)?[]:Object.entries(e).map(([t,n])=>({key:t,value:jC(n)}))}function Zs(e){const t={};for(const n of e){const o=n.key.trim();o!==""&&(t[o]=HC(n.value))}return t}function Lu(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).some(t=>t!==null&&typeof t=="object")}function FC(e){const t={};return typeof e.if=="string"&&e.if.trim().length>0&&(t.if=e.if),t}function KC(e,t){const n={...t},o=e.if;return typeof o=="string"&&o.trim().length>0?n.if=o:delete n.if,n}const VC=["api","static","route_params","query_params","websocket"],UC=["GET","POST","PUT","PATCH","DELETE"],qC=["none","optional","required"],GC=["progressive","blocking","background"],YC=["application/json","multipart/form-data"],XC=["public","private","presence"];function JC(e){if(!e||typeof e!="object")return{own:[],inherited:[]};const t=e.__editor,n=t&&typeof t=="object"&&!Array.isArray(t)?t.original:void 0,o=n&&typeof n=="object"&&!Array.isArray(n)?n.data_sources:e.data_sources,r=Array.isArray(o)?o.filter(c=>c&&typeof c=="object"):[],s=new Set(r.map(c=>typeof c.id=="string"?c.id:"").filter(Boolean)),a=e.data_sources,d=(Array.isArray(a)?a.filter(c=>c&&typeof c=="object"):[]).filter(c=>typeof c.id=="string"&&!s.has(c.id));return{own:r,inherited:d}}function ZC(e,t){const n=(o,r="")=>typeof o=="string"?o:r;return{index:t,id:n(e.id),type:n(e.type,"api"),label_key:n(e.label_key),endpoint:n(e.endpoint),method:n(e.method,"GET"),auth_mode:n(e.auth_mode,"none"),loading_strategy:n(e.loading_strategy,"progressive"),auto_fetch:e.auto_fetch!==!1,paramRows:Mu(e.params),paramsRaw:Lu(e.params),paramsRawValue:e.params&&typeof e.params=="object"&&!Array.isArray(e.params)?e.params:{},paramsRawValid:!0,fallbackEnabled:e.fallback!==void 0,fallbackValue:e.fallback,if:n(e.if),contentType:n(e.contentType),refetchOnMount:e.refetchOnMount===!0,onSuccess:Array.isArray(e.onSuccess)?e.onSuccess.filter(o=>!!o&&typeof o=="object"):[],onError:Array.isArray(e.onError)?e.onError.filter(o=>!!o&&typeof o=="object"):[],errorHandling:e.errorHandling&&typeof e.errorHandling=="object"&&!Array.isArray(e.errorHandling)?e.errorHandling:{},channel:n(e.channel),event:n(e.event),channel_type:n(e.channel_type,"public"),target_source:n(e.target_source),onReceive:Array.isArray(e.onReceive)?e.onReceive.filter(o=>!!o&&typeof o=="object"):[]}}function QC(){return{index:-1,id:"",type:"api",label_key:"",endpoint:"",method:"GET",auth_mode:"none",loading_strategy:"progressive",auto_fetch:!0,paramRows:[],paramsRaw:!1,paramsRawValue:{},paramsRawValid:!0,fallbackEnabled:!1,fallbackValue:void 0,if:"",contentType:"",refetchOnMount:!1,onSuccess:[],onError:[],errorHandling:{},channel:"",event:"",channel_type:"public",target_source:"",onReceive:[]}}function RC(e,t,n,o){const r=e.id.trim();if(!r)return{error:o("layout_editor.data_sources.error.id_required")};if(!/^[A-Za-z_][\w]*$/.test(r))return{error:o("layout_editor.data_sources.error.id_invalid")};if(n.has(r))return{error:o("layout_editor.data_sources.error.id_duplicate",{id:r})};const s=t?{...t}:{};if(s.id=r,s.type=e.type,e.label_key.trim()?s.label_key=e.label_key.trim():delete s.label_key,e.type==="api"||e.type==="websocket"?(e.endpoint.trim()?s.endpoint=e.endpoint.trim():delete s.endpoint,s.method=e.method,s.auth_mode=e.auth_mode,s.loading_strategy=e.loading_strategy):(delete s.endpoint,delete s.method),s.auto_fetch=e.auto_fetch,e.paramsRaw){if(!e.paramsRawValid)return{error:o("layout_editor.data_sources.error.params_json")};const a=e.paramsRawValue;a&&typeof a=="object"&&Object.keys(a).length>0?s.params=a:delete s.params}else{const a=Zs(e.paramRows);Object.keys(a).length>0?s.params=a:delete s.params}return e.fallbackEnabled?s.fallback=e.fallbackValue===void 0?{}:e.fallbackValue:delete s.fallback,e.if.trim()?s.if=e.if.trim():delete s.if,e.type==="api"&&e.contentType?s.contentType=e.contentType:delete s.contentType,e.refetchOnMount?s.refetchOnMount=!0:delete s.refetchOnMount,e.onSuccess.length>0?s.onSuccess=e.onSuccess:delete s.onSuccess,e.onError.length>0?s.onError=e.onError:delete s.onError,Object.keys(e.errorHandling).length>0?s.errorHandling=e.errorHandling:delete s.errorHandling,e.type==="websocket"?(e.channel?s.channel=e.channel:delete s.channel,e.event?s.event=e.event:delete s.event,s.channel_type=e.channel_type,e.target_source?s.target_source=e.target_source:delete s.target_source,e.onReceive.length>0?s.onReceive=e.onReceive:delete s.onReceive):(delete s.channel,delete s.event,delete s.channel_type,delete s.target_source,delete s.onReceive),{entry:s}}const jt={width:"100%",padding:"6px 8px",fontSize:13,border:"1px solid #cbd5e1",borderRadius:6,outline:"none",boxSizing:"border-box",fontFamily:"inherit",color:"#0f172a",background:"#ffffff"},ct={display:"block",fontSize:12,fontWeight:600,color:"#475569",marginBottom:4},ut={marginBottom:12},rn={padding:"6px 12px",fontSize:13,fontWeight:500,borderRadius:6,border:"1px solid #cbd5e1",background:"#ffffff",color:"#0f172a",cursor:"pointer"},Pu={...rn,background:"#2563eb",borderColor:"#2563eb",color:"#ffffff",fontWeight:600},Mo={marginTop:12,padding:10,border:"1px solid #e2e8f0",borderRadius:8,background:"#f8fafc"},Lo={fontSize:12,fontWeight:700,color:"#475569",marginBottom:8},e$={margin:"0 0 6px",fontSize:11,color:"#94a3b8"},Ou={marginTop:8},Bu={alignSelf:"flex-start",padding:"2px 0",fontSize:11,border:"none",background:"none",color:"#64748b",cursor:"pointer"},Wu={margin:0,padding:8,background:"#0f172a",color:"#e2e8f0",borderRadius:6,fontSize:11,lineHeight:1.5,overflow:"auto",fontFamily:"ui-monospace, monospace"};function t$({code:e,action:t,recipes:n,pools:o,t:r,onPatch:s}){const[a,l]=u.useState(!1),d=u.useMemo(()=>ko(n),[n]),c=Array.isArray(t)?t[0]:t,p=typeof c?.handler=="string"?c.handler:"",f=d.find(_=>_.id===p)??null,b=c?Yn(c,d):null,g=b?.kind==="preset"?b.values:{},m=p==="sequence"||p==="parallel",h=["","showErrorPage","navigate","openModal","toast","setState","sequence","parallel"],v=_=>{if(_===""){s({});return}const w=d.find(k=>k.id===_);s(w?Sr(w,{}):{handler:_})},y=m&&c?Array.isArray(c.params?.actions)?c.params.actions:[]:[];return i.jsxs("div",{"data-testid":`g7le-ds-errorhandling-${e}`,style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsx("select",{"data-testid":`g7le-ds-eh-handler-${e}`,style:{...jt,flex:1},value:p,onChange:_=>v(_.target.value),children:h.map(_=>i.jsx("option",{value:_,children:r(_===""?"layout_editor.error.handler_none":`layout_editor.error.handler_${_}`)},_))}),p!==""?i.jsx("button",{type:"button","data-testid":`g7le-ds-eh-code-${e}`,onClick:()=>l(_=>!_),"aria-label":r("layout_editor.action_list.view_code"),title:r("layout_editor.action_list.view_code"),style:a?n$:ju,children:""}):null]}),m?i.jsx("div",{"data-testid":`g7le-ds-eh-actions-${e}`,children:i.jsx(Gt,{actions:y,onChange:_=>s({handler:p,params:{actions:_}}),t:r,recipes:n,candidatePools:o,chipContext:"error",testIdPrefix:`g7le-ds-eh-seq-${e}`})}):f&&c?i.jsx(Ns,{raw:c,recipe:f,values:g,t:r,pools:o,onChange:_=>s(_),testIdPrefix:`g7le-ds-eh-action-${e}-edit`}):null,a&&c?i.jsx("pre",{"data-testid":`g7le-ds-eh-code-view-${e}`,style:o$,children:JSON.stringify(t,null,2)}):null]})}const ju={flex:"0 0 auto",width:26,height:26,display:"inline-flex",alignItems:"center",justifyContent:"center",fontSize:11,border:"1px solid #e2e8f0",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer",fontFamily:"ui-monospace, monospace"},n$={...ju,background:"#0f172a",borderColor:"#0f172a",color:"#e2e8f0"},o$={margin:"4px 0 0",padding:8,background:"#0f172a",color:"#e2e8f0",borderRadius:6,fontSize:12,overflow:"auto",fontFamily:"ui-monospace, monospace"};function r$({raw:e,onChange:t,t:n,resolveLabel:o,onClose:r,actionRecipes:s,errorRecipes:a,conditionSpec:l,bindingCandidates:d,pageCandidates:c,dataSourceCandidates:p,stateKeyCandidates:f}){const b=o??n,g=u.useMemo(()=>JC(e),[e]),m=g.inherited,[h,v]=u.useState(g.own),[y,_]=u.useState(null),[w,k]=u.useState(null),[x,$]=u.useState(!1),[S,C]=u.useState(!1),[T,E]=u.useState(()=>new Set),A=u.useCallback(I=>{E(L=>{const F=new Set(L);return F.has(I)?F.delete(I):F.add(I),F})},[]),N=u.useMemo(()=>({pageCandidates:c,dataSourceCandidates:p,stateKeyCandidates:f,bindingCandidates:d}),[c,p,f,d]),D=u.useCallback(I=>{v(I),t([...m,...I],I)},[m,t]),B=u.useCallback(()=>{k(null),_(QC())},[]),M=u.useCallback((I,L)=>{k(null),_(ZC(I,L))},[]),O=u.useCallback(I=>{const L=h.filter((F,Y)=>Y!==I);D(L)},[h,D]),z=u.useCallback(()=>{_(null),k(null)},[]),H=u.useCallback(()=>{if(!y)return;const I=new Set;h.forEach((K,X)=>{X!==y.index&&typeof K.id=="string"&&I.add(K.id)}),m.forEach(K=>{typeof K.id=="string"&&I.add(K.id)});const L=y.index>=0?h[y.index]??null:null,F=RC(y,L,I,n);if("error"in F){k(F.error);return}const Y=y.index>=0?h.map((K,X)=>X===y.index?F.entry:K):[...h,F.entry];D(Y),_(null),k(null)},[y,h,m,D,n]),P=y?.type==="api"||y?.type==="websocket";return i.jsxs("div",{className:"g7le-data-sources","data-testid":"g7le-data-sources-panel",style:{flex:"1 1 auto",minHeight:0,display:"flex",flexDirection:"column",fontSize:13,color:"#0f172a",boxSizing:"border-box"},children:[i.jsxs("div",{className:"g7le-data-sources__header",style:{flex:"0 0 auto",padding:"16px 16px 12px",borderBottom:"1px solid #e2e8f0"},children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",marginBottom:8},children:[i.jsx("h2",{style:{margin:0,fontSize:16,fontWeight:700},children:n("layout_editor.data_sources.title")}),i.jsx("button",{type:"button","data-testid":"g7le-data-sources-close",onClick:r,"aria-label":n("layout_editor.data_sources.close"),style:{...rn,padding:"4px 10px"},children:"✕"})]}),i.jsx("p",{style:{margin:0,fontSize:12,color:"#64748b",lineHeight:1.5},children:n("layout_editor.data_sources.description")})]}),i.jsxs("div",{className:"g7le-data-sources__body",style:{flex:"1 1 auto",minHeight:0,overflowY:"auto",padding:16},children:[y&&i.jsxs("div",{className:"g7le-data-sources__form","data-testid":"g7le-data-sources-form",children:[i.jsx("div",{style:{fontSize:13,fontWeight:700,marginBottom:12},children:y.index>=0?n("layout_editor.data_sources.form.edit_title"):n("layout_editor.data_sources.form.add_title")}),i.jsxs("div",{style:ut,children:[i.jsx("label",{style:ct,htmlFor:"g7le-ds-id",children:n("layout_editor.data_sources.field.id")}),i.jsx("input",{id:"g7le-ds-id","data-testid":"g7le-data-sources-field-id",style:jt,value:y.id,onChange:I=>_({...y,id:I.target.value}),placeholder:"products"})]}),i.jsxs("div",{style:ut,children:[i.jsx("label",{style:ct,htmlFor:"g7le-ds-label",children:n("layout_editor.data_sources.field.label_key")}),i.jsx(_t,{value:y.label_key,onChange:I=>_({...y,label_key:I??""}),t:n,placeholder:n("layout_editor.data_sources.field.label_key_placeholder"),testidPrefix:"g7le-data-sources-field-label",candidates:d,enableExpressionTree:!0,expressionTreeCollapsible:!0}),i.jsx("div",{style:{fontSize:11,color:"#94a3b8",marginTop:4},children:n("layout_editor.data_sources.field.label_key_hint")})]}),i.jsxs("div",{style:ut,children:[i.jsx("label",{style:ct,htmlFor:"g7le-ds-type",children:n("layout_editor.data_sources.field.type")}),i.jsx("select",{id:"g7le-ds-type","data-testid":"g7le-data-sources-field-type",style:jt,value:y.type,onChange:I=>_({...y,type:I.target.value}),children:VC.map(I=>i.jsx("option",{value:I,children:n(`layout_editor.data_sources.ds_type.${I}`)},I))})]}),P&&i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:ut,children:[i.jsx("label",{style:ct,children:n("layout_editor.data_sources.field.endpoint")}),i.jsx("div",{"data-testid":"g7le-data-sources-field-endpoint",children:i.jsx(Ke,{value:y.endpoint,onChange:I=>_({...y,endpoint:I}),t:n,candidates:d,placeholder:"/api/shop/products/{{route.id}}",testidPrefix:"g7le-ds-endpoint"})})]}),i.jsxs("div",{style:{display:"flex",gap:12},children:[i.jsxs("div",{style:{...ut,flex:1},children:[i.jsx("label",{style:ct,htmlFor:"g7le-ds-method",children:n("layout_editor.data_sources.field.method")}),i.jsx("select",{id:"g7le-ds-method","data-testid":"g7le-data-sources-field-method",style:jt,value:y.method,onChange:I=>_({...y,method:I.target.value}),children:UC.map(I=>i.jsx("option",{value:I,children:I},I))})]}),i.jsxs("div",{style:{...ut,flex:1},children:[i.jsx("label",{style:ct,htmlFor:"g7le-ds-auth",children:n("layout_editor.data_sources.field.auth_mode")}),i.jsx("select",{id:"g7le-ds-auth","data-testid":"g7le-data-sources-field-auth",style:jt,value:y.auth_mode,onChange:I=>_({...y,auth_mode:I.target.value}),children:qC.map(I=>i.jsx("option",{value:I,children:n(`layout_editor.data_sources.auth_mode.${I}`)},I))})]})]}),i.jsxs("div",{style:ut,children:[i.jsx("label",{style:ct,htmlFor:"g7le-ds-loading",children:n("layout_editor.data_sources.field.loading_strategy")}),i.jsx("select",{id:"g7le-ds-loading","data-testid":"g7le-data-sources-field-loading",style:jt,value:y.loading_strategy,onChange:I=>_({...y,loading_strategy:I.target.value}),children:GC.map(I=>i.jsx("option",{value:I,children:n(`layout_editor.data_sources.loading_strategy.${I}`)},I))})]}),y.type==="api"&&i.jsxs("div",{style:ut,children:[i.jsx("label",{style:ct,htmlFor:"g7le-ds-contenttype",children:n("layout_editor.data_sources.field.content_type")}),i.jsx("select",{id:"g7le-ds-contenttype","data-testid":"g7le-ds-contenttype",style:jt,value:y.contentType||"application/json",onChange:I=>_({...y,contentType:I.target.value}),children:YC.map(I=>i.jsx("option",{value:I,children:I},I))})]})]}),i.jsx("div",{style:ut,children:i.jsxs("label",{style:{...ct,display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[i.jsx("input",{type:"checkbox","data-testid":"g7le-data-sources-field-autofetch",checked:y.auto_fetch,onChange:I=>_({...y,auto_fetch:I.target.checked})}),n("layout_editor.data_sources.field.auto_fetch")]})}),i.jsx("div",{style:ut,children:i.jsxs("label",{style:{...ct,display:"flex",alignItems:"center",gap:8,cursor:"pointer"},children:[i.jsx("input",{type:"checkbox","data-testid":"g7le-ds-refetch",checked:y.refetchOnMount,onChange:I=>_({...y,refetchOnMount:I.target.checked})}),n("layout_editor.data_sources.field.refetch_on_mount")]})}),i.jsxs("div",{style:ut,children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between"},children:[i.jsx("label",{style:ct,htmlFor:"g7le-ds-params",children:n("layout_editor.data_sources.field.params")}),i.jsx("button",{type:"button","data-testid":"g7le-ds-params-mode-toggle",onClick:()=>{if(y.paramsRaw){if(y.paramsRawValid){const I=y.paramsRawValue;I&&typeof I=="object"&&!Array.isArray(I)&&!Lu(I)&&_({...y,paramsRaw:!1,paramRows:Mu(I)})}}else{const I=Zs(y.paramRows);_({...y,paramsRaw:!0,paramsRawValue:I,paramsRawValid:!0})}},style:{...rn,padding:"2px 8px",fontSize:11},children:y.paramsRaw?n("layout_editor.data_sources.field.params_mode_block"):n("layout_editor.data_sources.field.params_mode_code")})]}),y.paramsRaw?i.jsx(Hs,{id:"g7le-ds-params",value:y.paramsRawValue,shape:"object",emptyValue:{},minHeight:64,testidPrefix:"g7le-data-sources-field-params",placeholder:`{ "page": "{{query.page ?? 1}}" -}`,shapeErrorKey:"layout_editor.data_sources.error.params_object",invalidErrorKey:"layout_editor.data_sources.error.params_json",t:n,onChange:I=>_(L=>L&&{...L,paramsRawValue:I??{},paramsRawValid:!0}),onValidityChange:I=>_(L=>L&&{...L,paramsRawValid:I})}):i.jsxs("div",{"data-testid":"g7le-data-sources-field-params",children:[y.paramRows.length===0&&i.jsx("p",{"data-testid":"g7le-ds-params-empty",style:e$,children:n("layout_editor.data_sources.field.params_empty")}),i.jsx(Pr,{value:y.paramRows.map(I=>({key:I.key,value:I.value})),onChange:I=>_({...y,paramRows:I.map(L=>({key:L.key??"",value:L.value??""}))}),keyField:"key",valueField:"value",t:n,candidates:d,testidPrefix:"g7le-ds-params-kv",keyPlaceholder:n("layout_editor.data_sources.field.param_key_placeholder"),valuePlaceholder:"{{query.page ?? 1}}",addLabel:n("layout_editor.data_sources.field.param_add")}),(()=>{const I=Zs(y.paramRows);return Object.keys(I).length===0?null:i.jsxs("div",{style:Ou,children:[i.jsxs("button",{type:"button","data-testid":"g7le-ds-params-preview-toggle","aria-expanded":x,onClick:()=>$(L=>!L),style:Bu,children:[x?"▴":"▾"," ",n("layout_editor.data_sources.field.params_preview")]}),x&&i.jsx("pre",{"data-testid":"g7le-ds-params-preview",style:{...Wu,marginTop:4},children:JSON.stringify(I,null,2)})]})})()]}),i.jsx("div",{style:{fontSize:11,color:"#94a3b8",marginTop:4},children:n("layout_editor.data_sources.field.params_hint")})]}),i.jsxs("div",{style:ut,children:[i.jsx("label",{style:ct,children:n("layout_editor.data_sources.field.fallback")}),y.fallbackEnabled?i.jsxs("div",{"data-testid":"g7le-data-sources-field-fallback",style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx(zn,{value:y.fallbackValue===void 0?{}:y.fallbackValue,onChange:I=>_({...y,fallbackValue:I}),t:n,path:"fallback",scope:"ds-fallback",renderStringLeaf:I=>i.jsx(Ke,{value:I.value,onChange:I.onChange,t:n,candidates:d,testidPrefix:I.testidPrefix})}),(()=>{const I=y.fallbackValue===void 0?{}:y.fallbackValue;return i.jsxs("div",{style:Ou,children:[i.jsxs("button",{type:"button","data-testid":"g7le-ds-fallback-preview-toggle","aria-expanded":S,onClick:()=>C(L=>!L),style:Bu,children:[S?"▴":"▾"," ",n("layout_editor.data_sources.field.fallback_preview")]}),S&&i.jsx("pre",{"data-testid":"g7le-ds-fallback-preview",style:{...Wu,marginTop:4},children:JSON.stringify(I,null,2)})]})})(),i.jsx("button",{type:"button","data-testid":"g7le-data-sources-field-fallback-clear",onClick:()=>_({...y,fallbackEnabled:!1,fallbackValue:void 0}),style:{...rn,padding:"2px 8px",fontSize:11,alignSelf:"flex-start",color:"#dc2626",borderColor:"#fecaca"},children:n("layout_editor.data_sources.field.fallback_clear")})]}):i.jsxs("button",{type:"button","data-testid":"g7le-data-sources-field-fallback-add",onClick:()=>_({...y,fallbackEnabled:!0,fallbackValue:{}}),style:{...rn,padding:"4px 10px",display:"block"},children:["+ ",n("layout_editor.data_sources.field.fallback_add")]})]}),y.type==="websocket"&&i.jsxs("div",{"data-testid":"g7le-ds-ws-section",style:Mo,children:[i.jsx("div",{style:Lo,children:n("layout_editor.data_sources.section.websocket")}),i.jsxs("div",{style:ut,children:[i.jsx("label",{style:ct,children:n("layout_editor.data_sources.field.channel")}),i.jsx("input",{"data-testid":"g7le-ds-ws-channel",style:jt,value:y.channel,onChange:I=>_({...y,channel:I.target.value}),placeholder:"core.admin.dashboard"})]}),i.jsxs("div",{style:ut,children:[i.jsx("label",{style:ct,children:n("layout_editor.data_sources.field.event")}),i.jsx("input",{"data-testid":"g7le-ds-ws-event",style:jt,value:y.event,onChange:I=>_({...y,event:I.target.value}),placeholder:"dashboard.stats.updated"})]}),i.jsxs("div",{style:ut,children:[i.jsx("label",{style:ct,children:n("layout_editor.data_sources.field.channel_type")}),i.jsx("select",{"data-testid":"g7le-ds-ws-channeltype",style:jt,value:y.channel_type,onChange:I=>_({...y,channel_type:I.target.value}),children:XC.map(I=>i.jsx("option",{value:I,children:I},I))})]}),i.jsxs("div",{style:ut,children:[i.jsx("label",{style:ct,children:n("layout_editor.data_sources.field.target_source")}),i.jsx("input",{"data-testid":"g7le-ds-ws-target",style:jt,value:y.target_source,onChange:I=>_({...y,target_source:I.target.value}),list:"g7le-ds-ws-target-list"}),i.jsx("datalist",{id:"g7le-ds-ws-target-list",children:h.filter(I=>I.id!==y.id).map(I=>typeof I.id=="string"?i.jsx("option",{value:I.id},I.id):null)})]}),i.jsxs("div",{style:ut,children:[i.jsx("label",{style:ct,children:n("layout_editor.data_sources.field.on_receive")}),i.jsx("div",{"data-testid":"g7le-ds-ws-onreceive",children:i.jsx(Gt,{actions:y.onReceive,onChange:I=>_({...y,onReceive:I}),t:n,recipes:s,candidatePools:N,chipContext:"payload",actionChipCandidates:l?.actionChipCandidates??null,testIdPrefix:"g7le-ds-onreceive-list"})})]})]}),i.jsxs("div",{style:Mo,children:[i.jsx("div",{style:Lo,children:n("layout_editor.data_sources.section.on_success")}),i.jsx("div",{"data-testid":"g7le-ds-onsuccess",children:i.jsx(Gt,{actions:y.onSuccess,onChange:I=>_({...y,onSuccess:I}),t:n,recipes:s,candidatePools:N,chipContext:"response",actionChipCandidates:l?.actionChipCandidates??null,testIdPrefix:"g7le-ds-onsuccess-list"})})]}),i.jsxs("div",{style:Mo,children:[i.jsx("div",{style:Lo,children:n("layout_editor.data_sources.section.on_error")}),i.jsx("div",{"data-testid":"g7le-ds-onerror",children:i.jsx(Gt,{actions:y.onError,onChange:I=>_({...y,onError:I}),t:n,recipes:s,candidatePools:N,chipContext:"error",actionChipCandidates:l?.actionChipCandidates??null,testIdPrefix:"g7le-ds-onerror-list"})})]}),i.jsxs("div",{style:Mo,children:[i.jsx("div",{style:Lo,children:n("layout_editor.data_sources.section.error_handling")}),i.jsxs("div",{"data-testid":"g7le-ds-errorhandling",children:[i.jsx(Us,{value:y.errorHandling,onChange:I=>_({...y,errorHandling:I}),t:n,mode:"local",testIdPrefix:"g7le-ds-eh",renderActionList:(I,L,F)=>i.jsx(t$,{code:I,action:L,recipes:a,pools:N,t:n,onPatch:F})}),i.jsxs("button",{type:"button","data-testid":"g7le-ds-errorhandling-add",onClick:()=>{const I=Object.keys(y.errorHandling),L=["403","404","500","422","default"].find(F=>!I.includes(F))??"default";_({...y,errorHandling:{...y.errorHandling,[L]:{handler:"toast"}}})},style:{...rn,padding:"4px 10px",marginTop:6},children:["+ ",n("layout_editor.data_sources.add_error_code")]})]})]}),i.jsxs("div",{style:Mo,children:[i.jsx("div",{style:Lo,children:n("layout_editor.data_sources.section.load_condition")}),i.jsx("div",{"data-testid":"g7le-ds-loadcondition",children:i.jsx(Du,{node:FC({if:y.if||void 0}),spec:l??null,t:n,dataSourceCandidates:p,stateKeyCandidates:f,onPatchNode:I=>{const L=KC(I,{});_({...y,if:typeof L.if=="string"?L.if:""})}})})]})]}),!y&&i.jsxs("button",{type:"button","data-testid":"g7le-data-sources-add",onClick:B,style:{...Pu,marginBottom:16},children:["+ ",n("layout_editor.data_sources.add")]}),i.jsxs("div",{className:"g7le-data-sources__list","data-testid":"g7le-data-sources-list",style:{display:"flex",flexDirection:"column",gap:8},children:[h.length===0&&!y&&i.jsx("div",{"data-testid":"g7le-data-sources-empty",style:{fontSize:12,color:"#94a3b8",padding:"12px 0",textAlign:"center"},children:n("layout_editor.data_sources.empty")}),h.map((I,L)=>{const F=typeof I.id=="string"?I.id:`#${L}`,Y=typeof I.endpoint=="string"?I.endpoint:"",K=typeof I.label_key=="string"?I.label_key:"",X=as(I,b);return i.jsxs("div",{"data-testid":"g7le-data-sources-item","data-ds-id":F,style:{border:"1px solid #e2e8f0",borderRadius:8,padding:"10px 12px",display:"flex",alignItems:"center",gap:8,background:"#ffffff"},children:[i.jsxs("div",{style:{flex:1,minWidth:0},children:[i.jsxs("div",{"data-testid":"g7le-data-sources-item-title",style:{fontWeight:600,fontSize:13,display:"flex",alignItems:"baseline",gap:6,flexWrap:"wrap"},children:[i.jsx("span",{children:X??F}),X&&i.jsx("span",{"data-testid":"g7le-data-sources-item-id",style:{fontSize:11,fontWeight:400,color:"#94a3b8"},children:F}),(()=>{const Z=ls(I,n);return Z?i.jsx("span",{"data-testid":"g7le-data-sources-ext-badge",style:{fontSize:10,fontWeight:600,color:"#7c3aed",background:"#f5f3ff",border:"1px solid #ddd6fe",borderRadius:4,padding:"1px 6px"},children:Z}):null})()]}),Y&&i.jsx("div",{style:{fontSize:11,color:"#94a3b8",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Y}),!K&&i.jsx("div",{"data-testid":"g7le-data-sources-nolabel",style:{fontSize:11,color:"#f59e0b"},children:n("layout_editor.data_sources.no_label")})]}),i.jsx("button",{type:"button","data-testid":"g7le-data-sources-edit",onClick:()=>M(I,L),style:{...rn,padding:"4px 10px"},children:n("layout_editor.data_sources.edit")}),i.jsx("button",{type:"button","data-testid":"g7le-data-sources-remove",onClick:()=>O(L),style:{...rn,padding:"4px 10px",color:"#dc2626",borderColor:"#fecaca"},children:n("layout_editor.data_sources.remove")})]},`${F}-${L}`)})]}),m.length>0&&i.jsxs("div",{style:{marginTop:16},children:[i.jsx("div",{style:{fontSize:12,fontWeight:600,color:"#64748b",textTransform:"uppercase",letterSpacing:.4,marginBottom:8},children:n("layout_editor.data_sources.inherited_title")}),i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:m.map((I,L)=>{const F=typeof I.id=="string"?I.id:`#${L}`,Y=T.has(F),K=[],X=(Z,se)=>{const oe=I[Z];oe!=null&&K.push([se,typeof oe=="object"?JSON.stringify(oe):String(oe)])};return X("type",n("layout_editor.data_sources.field.type")),X("endpoint",n("layout_editor.data_sources.field.endpoint")),X("method",n("layout_editor.data_sources.field.method")),X("auth_mode",n("layout_editor.data_sources.field.auth_mode")),X("loading_strategy",n("layout_editor.data_sources.field.loading_strategy")),X("auto_fetch",n("layout_editor.data_sources.field.auto_fetch")),X("params",n("layout_editor.data_sources.field.params")),i.jsxs("div",{"data-testid":"g7le-data-sources-inherited-item","data-ds-id":F,"data-expanded":Y?"true":"false",style:{border:"1px dashed #e2e8f0",borderRadius:6,fontSize:12,color:"#64748b",background:"#f8fafc",overflow:"hidden"},children:[i.jsxs("button",{type:"button","data-testid":"g7le-data-sources-inherited-toggle",onClick:()=>A(F),"aria-expanded":Y,style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"8px 12px",background:"transparent",border:"none",cursor:"pointer",color:"inherit",fontSize:12,textAlign:"left",outline:"none"},children:[i.jsx("span",{style:{flex:"0 0 auto",width:12,transition:"transform 120ms",transform:Y?"rotate(90deg)":"none"},children:"▶"}),(()=>{const Z=as(I,b),se=ls(I,n);return i.jsxs("span",{style:{flex:1,display:"inline-flex",alignItems:"baseline",gap:6,flexWrap:"wrap"},children:[i.jsx("span",{style:{fontWeight:600},children:Z??F}),Z&&i.jsx("span",{style:{fontSize:11,fontWeight:400,color:"#94a3b8"},children:F}),se&&i.jsx("span",{"data-testid":"g7le-data-sources-ext-badge",style:{fontSize:10,fontWeight:600,color:"#7c3aed",background:"#f5f3ff",border:"1px solid #ddd6fe",borderRadius:4,padding:"1px 6px"},children:se})]})})()]}),Y&&i.jsxs("div",{"data-testid":"g7le-data-sources-inherited-info",style:{padding:"0 12px 10px 32px",display:"flex",flexDirection:"column",gap:3},children:[K.length===0&&i.jsx("span",{style:{color:"#94a3b8"},children:"—"}),K.map(([Z,se])=>i.jsxs("div",{style:{display:"flex",gap:6},children:[i.jsxs("span",{style:{flex:"0 0 auto",color:"#94a3b8"},children:[Z,":"]}),i.jsx("span",{style:{flex:1,minWidth:0,wordBreak:"break-all",color:"#475569"},children:se})]},Z))]})]},`inh-${F}-${L}`)})})]})]}),y&&i.jsxs("div",{className:"g7le-data-sources__footer",style:{flex:"0 0 auto",padding:"12px 16px",borderTop:"1px solid #e2e8f0",background:"#ffffff"},children:[w&&i.jsx("div",{"data-testid":"g7le-data-sources-form-error",role:"alert",style:{fontSize:12,color:"#dc2626",marginBottom:10},children:w}),i.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[i.jsx("button",{type:"button","data-testid":"g7le-data-sources-form-cancel",onClick:z,style:rn,children:n("layout_editor.data_sources.form.cancel")}),i.jsx("button",{type:"button","data-testid":"g7le-data-sources-form-submit",onClick:H,style:Pu,children:n("layout_editor.data_sources.form.save")})]})]})]})}function i$(e){const t=e?.globalHeaders;return Array.isArray(t)?t:[]}function s$(e){const t=e?.scripts;return Array.isArray(t)?t:[]}function a$(e){const t=i$(e.raw),n=s$(e.raw);return i.jsxs("div",{className:"g7le-data-source-tab","data-testid":"g7le-data-source-tab",style:l$,children:[i.jsx(r$,{...e}),i.jsxs("div",{style:Hu,"data-testid":"g7le-global-headers",children:[i.jsx("div",{style:Fu,children:e.t("layout_editor.data_sources.global_headers")}),t.length===0?i.jsx("p",{"data-testid":"g7le-global-header-empty",style:Gu,children:e.t("layout_editor.data_sources.global_headers_empty")}):t.map((o,r)=>i.jsxs("div",{"data-testid":`g7le-global-header-${r}`,style:Ku,children:[i.jsx("code",{style:Vu,children:o.pattern??"*"}),i.jsx("span",{style:d$,children:"→"}),i.jsx("span",{style:Uu,children:Object.keys(o.headers??{}).join(", ")})]},r)),i.jsxs("p",{style:qu,children:["ⓘ ",e.t("layout_editor.data_sources.global_headers_hint")]})]}),i.jsxs("div",{style:Hu,"data-testid":"g7le-scripts",children:[i.jsx("div",{style:Fu,children:e.t("layout_editor.data_sources.scripts")}),n.length===0?i.jsx("p",{"data-testid":"g7le-script-empty",style:Gu,children:e.t("layout_editor.data_sources.scripts_empty")}):n.map((o,r)=>i.jsxs("div",{"data-testid":`g7le-script-${o.id??r}`,style:Ku,children:[i.jsx("code",{style:Vu,children:o.id??`#${r}`}),i.jsx("span",{style:Uu,children:o.src??""}),o.loading?i.jsx("span",{style:c$,children:o.loading}):null]},o.id??r)),i.jsxs("p",{style:qu,children:["ⓘ ",e.t("layout_editor.data_sources.scripts_hint")]})]})]})}const l$={display:"flex",flexDirection:"column",gap:16,minWidth:0},Hu={borderTop:"1px solid #e2e8f0",paddingTop:12,display:"flex",flexDirection:"column",gap:6},Fu={fontSize:12,fontWeight:700,color:"#475569"},Ku={display:"flex",alignItems:"center",gap:8,fontSize:12,padding:"4px 8px",border:"1px solid #f1f5f9",borderRadius:6},Vu={fontSize:11,color:"#0f172a",fontFamily:"monospace"},d$={color:"#94a3b8"},Uu={flex:1,minWidth:0,color:"#475569",wordBreak:"break-all"},c$={fontSize:10,color:"#64748b",background:"#f1f5f9",borderRadius:4,padding:"0 4px"},qu={margin:0,fontSize:11,color:"#94a3b8"},Gu={margin:0,fontSize:12,color:"#94a3b8"},u$=["meta","seo","init","overlay","computed","state","error","data"],p$=["401","403","404","500","503"],f$={meta:"layout_editor.page_settings.tab.meta",seo:"layout_editor.page_settings.tab.seo",init:"layout_editor.page_settings.tab.init",overlay:"layout_editor.page_settings.tab.overlay",computed:"layout_editor.page_settings.tab.computed",state:"layout_editor.page_settings.tab.state",error:"layout_editor.page_settings.tab.error",data:"layout_editor.page_settings.tab.data"};async function g$(e){if(typeof fetch!="function"||!e)return[];try{const t=await fetch(en(`/api/admin/templates/${encodeURIComponent(e)}/editor/seo-candidates`,"json"),{credentials:"same-origin",headers:Ne()});if(!t.ok)return[];const o=(await t.json().catch(()=>null))?.data?.extensions;if(!Array.isArray(o))return[];const r=[];for(const s of o)if(s&&typeof s=="object"){const a=s.type,l=s.id,d=s.label;typeof a=="string"&&typeof l=="string"&&l.length>0&&r.push({type:a,id:l,name:typeof d=="string"?d:l})}return r}catch{return[]}}function h$(e,t){let n=0;for(const o of e)Yn(o,t).kind==="advanced"&&(n+=1);return n}function y$(e,t){let n=0;for(const o of Object.keys(e))Dd(e[o],t).kind==="advanced"&&(n+=1);return n}function b$(e,t,n){const o=e("meta",{})??{},r=o.title;if(typeof r=="string"&&r.length>0){if(r.startsWith("$t:")){const a=n(r.slice(3));if(a&&a!==r.slice(3))return a}else if(!/\{\{[\s\S]*\}\}/.test(r))return r}const s=o.editor_label;return typeof s=="string"&&s.length>0?s.startsWith("$t:")?n(s.slice(3)):s:t||""}function m$({templateIdentifier:e,spec:t,t:n,resolveLabel:o,permissionCandidates:r,onClose:s,initialTab:a="meta",extensionsFetcher:l}){const{state:d}=Qe(),{raw:c,getValue:p,patch:f}=jm(),[b,g]=u.useState(a),m=d.selectedRoute?.path??"",h=u.useMemo(()=>Od(d.routeTree,o),[d.routeTree,o]),v=u.useMemo(()=>Bd(c),[c]),y=u.useMemo(()=>Wd(t),[t]),_=u.useMemo(()=>iv(c,o),[c,o]),w=Pd({raw:c,spec:t}),k=u.useMemo(()=>lb(t),[t]),x=u.useMemo(()=>db(t),[t]),$=u.useMemo(()=>cb(t),[t]),S=u.useMemo(()=>ub(t),[t]),C=u.useMemo(()=>ko(k),[k]),T=u.useMemo(()=>Cd(x),[x]),E=p("init_actions",void 0)??p("initActions",[]),A=p("computed",{}),N=p("__computedSource",{}),D=p("errorHandling",{}),B=p("transition_overlay",void 0),M=(p("__editor",{})??{}).original,O=u.useMemo(()=>{if(M===void 0)return;const G=M.transition_overlay;return G&&typeof G=="object"&&!Array.isArray(G)?G:{}},[M]),z=u.useMemo(()=>{const G=B;if(!G||typeof G!="object"||Array.isArray(G))return;const ee=O??{},ge={};for(const[V,te]of Object.entries(G))V in ee||(ge[V]=te);return Object.keys(ge).length>0?ge:void 0},[B,O]),[H,P]=u.useState([]);u.useEffect(()=>{let G=!1;const ee=l??g$;return(async()=>{const ge=await ee(e);G||P(ge)})(),()=>{G=!0}},[e,l]);const I=(p("meta",{})??{}).seo?.page_type,L=ov({raw:c,spec:t,pageType:typeof I=="string"?I:null}),F=u.useMemo(()=>nv(c,t),[c,t]),Y=u.useMemo(()=>({meta:0,seo:0,init:h$(E,C),overlay:0,computed:y$(A,T),state:0,error:0,data:0}),[E,C,A,T]),K=u.useMemo(()=>Object.values(Y).reduce((G,ee)=>G+ee,0),[Y]),X=u.useMemo(()=>rv(c,o,n),[c,o,n]),Z=u.useCallback(G=>{const ge={...M?.computed??{}};delete ge[G];const V={...A};delete V[G],f("computed",V,Object.keys(ge).length===0?void 0:ge)},[M,A,f]),se=b$(p,m,n),oe=()=>{switch(b){case"meta":return i.jsx(kx,{getValue:p,patch:f,t:n,fieldT:o,spec:t,permissionCandidates:r,bindingCandidates:w});case"seo":return i.jsx(d0,{getValue:p,patch:f,t:n,templateIdentifier:e,candidates:L,availableExtensions:H,dataSourceOptions:X,previewUrl:m||"/",seedContext:F});case"init":return i.jsx(Ak,{actions:E,onChange:G=>f("init_actions",G),recipes:k,t:o,bindingCandidates:w,pageCandidates:h,dataSourceCandidates:v,stateKeyCandidates:y,modalCandidates:_});case"overlay":return i.jsx(Qk,{value:B,ownValue:O,baseValue:z,patch:G=>f("transition_overlay",G),t:o,loadingComponents:S,progressiveDataSources:X,bindingCandidates:w});case"computed":return i.jsx(j1,{computed:A,onChange:G=>f("computed",G),recipes:x,t:o,sampleContext:F,dataSourceCandidates:v,bindingCandidates:w,computedSource:N,onRevert:Z});case"state":return i.jsx(xS,{raw:c,own:M?{initLocal:M.initLocal,initGlobal:M.initGlobal,initIsolated:M.initIsolated,state:M.state}:void 0,patch:f,t:n});case"error":return i.jsx(GS,{value:D,onChange:G=>f("errorHandling",G),t:o,errorConfigCodes:p$,templateCodes:Object.keys(D),ownCodes:Object.keys(M?.errorHandling??{}),recipes:$,pageCandidates:h,modalCandidates:_,dataSourceCandidates:v,stateKeyCandidates:y});case"data":return i.jsx(a$,{raw:c,t:n,resolveLabel:o,onChange:(G,ee)=>f("data_sources",G,ee),onClose:s,actionRecipes:k,errorRecipes:$,conditionSpec:t,bindingCandidates:w,pageCandidates:h,dataSourceCandidates:v,stateKeyCandidates:y});default:return i.jsx("div",{})}};return i.jsxs("div",{className:"g7le-page-settings","data-testid":"g7le-page-settings",style:v$,children:[i.jsxs("div",{style:_$,children:[i.jsx("span",{"data-testid":"g7le-page-settings-title",style:x$,children:n("layout_editor.page_settings.title",{name:se})}),i.jsx("button",{type:"button","data-testid":"g7le-page-settings-close-x",onClick:s,"aria-label":n("layout_editor.page_settings.close"),style:w$,children:"✕"})]}),i.jsx("div",{role:"tablist",style:k$,children:u$.map(G=>{const ee=Y[G];return i.jsxs("button",{type:"button",role:"tab","aria-selected":b===G,"data-testid":`g7le-page-settings-tab-${G}`,"data-active":b===G?"true":"false",onClick:()=>g(G),style:b===G?S$:Yu,children:[n(f$[G]),ee>0?i.jsxs("span",{"data-testid":`g7le-page-settings-tab-badge-${G}`,style:C$,children:["(",ee,")"]}):null]},G)})}),K>0?i.jsxs("p",{"data-testid":"g7le-page-settings-advanced-summary",style:$$,children:["⚠ ",n("layout_editor.page_settings.advanced_summary",{count:K})," ⓘ"]}):null,i.jsx("div",{"data-testid":"g7le-page-settings-panel",style:E$,children:oe()}),i.jsx("div",{style:I$,children:i.jsx("button",{type:"button","data-testid":"g7le-page-settings-close",onClick:s,style:A$,children:n("layout_editor.page_settings.close")})})]})}const v$={display:"flex",flexDirection:"column",minWidth:0,maxWidth:"100%",padding:"20px 24px",boxSizing:"border-box",flex:1,minHeight:0,maxHeight:"100%",overflow:"hidden",fontFamily:"system-ui, -apple-system, sans-serif"},_$={display:"flex",alignItems:"center",gap:8,paddingBottom:8,borderBottom:"1px solid #e2e8f0"},x$={flex:1,fontSize:15,fontWeight:700,color:"#0f172a",minWidth:0},w$={border:"none",background:"transparent",color:"#64748b",cursor:"pointer",fontSize:16,lineHeight:1,padding:4},k$={display:"flex",gap:2,paddingTop:8,borderBottom:"1px solid #e2e8f0",flexWrap:"nowrap",overflowX:"auto",overflowY:"hidden",flexShrink:0,minWidth:0},Yu={border:"none",borderBottomWidth:"2px",borderBottomStyle:"solid",borderBottomColor:"transparent",background:"transparent",color:"#64748b",cursor:"pointer",fontSize:12,padding:"6px 10px",whiteSpace:"nowrap"},S$={...Yu,color:"#2563eb",borderBottomColor:"#2563eb",fontWeight:600},C$={marginLeft:4,fontSize:10,color:"#b45309"},$$={margin:0,marginTop:8,fontSize:11,color:"#b45309",background:"#fffbeb",padding:"6px 8px",borderRadius:6},E$={flex:1,overflowY:"auto",paddingTop:12,minWidth:0,minHeight:0},I$={display:"flex",justifyContent:"flex-end",paddingTop:8,borderTop:"1px solid #e2e8f0"},A$={border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",fontSize:13,padding:"6px 16px"};function Qs(e,t){const n=`/api/admin/templates/${encodeURIComponent(e)}`;return t.kind==="layout"?`${n}/layouts/${t.layoutName}/versions`:`${n}/layout-extensions/${encodeURIComponent(t.extensionId)}/versions`}const Xu=100,Ju=500;function T$(e,t,n){const[o,r]=u.useState([]),[s,a]=u.useState(!1),[l,d]=u.useState(!1),[c,p]=u.useState(null),[f,b]=u.useState(null),[g,m]=u.useState(Xu),[h,v]=u.useState(!1),y=u.useCallback(async($,S)=>{if(!t){r([]),p(null),v(!1);return}S==="more"?d(!0):a(!0),p(null);try{const C=`${Qs(e,t)}?limit=${$}`,T=await fetch(C,{credentials:"same-origin",headers:Ne()}),E=await T.json().catch(()=>null);if(!T.ok){p(E?.message??`HTTP ${T.status}`),S==="reload"&&r([]);return}const A=E?.data,N=Array.isArray(A)?A:[];r(N),v(N.length>=$&&${await y(g,"reload")},[y,g]),w=u.useCallback(async()=>{const $=Math.min(g+Xu,Ju);if($<=g){v(!1);return}await y($,"more")},[y,g]),k=u.useCallback(async $=>{if(!t)return{kind:"not_found"};b($);try{const S=`${Qs(e,t)}/${$}/restore`,C=await fetch(S,{method:"POST",credentials:"same-origin",headers:Ne({"Content-Type":"application/json"})}),T=await C.json().catch(()=>null);if(C.status===404)return{kind:"not_found"};if(!C.ok)return{kind:"network_error",message:T?.message??`HTTP ${C.status}`};const E=typeof T?.data?.version=="number"?T.data.version:-1;return await n?.(E>=0?E:void 0),{kind:"success",newVersion:E}}catch(S){return{kind:"network_error",message:S instanceof Error?S.message:"network error"}}finally{b(null)}},[e,t,n]),x=u.useCallback(async $=>{if(!t)return{kind:"not_found"};try{const S=`${Qs(e,t)}/${$}`,C=await fetch(S,{credentials:"same-origin",headers:Ne()}),T=await C.json().catch(()=>null);if(C.status===404)return{kind:"not_found"};if(!C.ok)return{kind:"network_error",message:T?.message??`HTTP ${C.status}`};const E=T?.data;if(!E)return{kind:"not_found"};if(t.kind==="extension"&&!E.full_content){const A=E.content;if(typeof A=="string")try{const N=JSON.parse(A);N&&typeof N=="object"&&(E.full_content=N)}catch{}}return{kind:"success",detail:E}}catch(S){return{kind:"network_error",message:S instanceof Error?S.message:"network error"}}},[e,t]);return{versions:o,isLoading:s,isLoadingMore:l,error:c,restoringId:f,hasMore:h,loadVersions:_,loadMore:w,restore:k,loadVersionDetail:x}}function D$(e,t){const n=e.length,o=t.length,r=Array.from({length:n+1},()=>new Array(o+1).fill(0));for(let s=n-1;s>=0;s--)for(let a=o-1;a>=0;a--)e[s]===t[a]?r[s][a]=r[s+1][a+1]+1:r[s][a]=Math.max(r[s+1][a],r[s][a+1]);return r}function z$(e,t,n){const o=[];let r=0,s=0;const a=e.length,l=t.length;for(;r=n[r][s+1]?(o.push({kind:"remove",oldIndex:r,content:e[r]}),r++):(o.push({kind:"add",newIndex:s,content:t[s]}),s++);for(;r_(L=>L&&{...L,paramsRawValue:I??{},paramsRawValid:!0}),onValidityChange:I=>_(L=>L&&{...L,paramsRawValid:I})}):i.jsxs("div",{"data-testid":"g7le-data-sources-field-params",children:[y.paramRows.length===0&&i.jsx("p",{"data-testid":"g7le-ds-params-empty",style:e$,children:n("layout_editor.data_sources.field.params_empty")}),i.jsx(Pr,{value:y.paramRows.map(I=>({key:I.key,value:I.value})),onChange:I=>_({...y,paramRows:I.map(L=>({key:L.key??"",value:L.value??""}))}),keyField:"key",valueField:"value",t:n,candidates:d,testidPrefix:"g7le-ds-params-kv",keyPlaceholder:n("layout_editor.data_sources.field.param_key_placeholder"),valuePlaceholder:"{{query.page ?? 1}}",addLabel:n("layout_editor.data_sources.field.param_add")}),(()=>{const I=Zs(y.paramRows);return Object.keys(I).length===0?null:i.jsxs("div",{style:Ou,children:[i.jsxs("button",{type:"button","data-testid":"g7le-ds-params-preview-toggle","aria-expanded":x,onClick:()=>$(L=>!L),style:Bu,children:[x?"▴":"▾"," ",n("layout_editor.data_sources.field.params_preview")]}),x&&i.jsx("pre",{"data-testid":"g7le-ds-params-preview",style:{...Wu,marginTop:4},children:JSON.stringify(I,null,2)})]})})()]}),i.jsx("div",{style:{fontSize:11,color:"#94a3b8",marginTop:4},children:n("layout_editor.data_sources.field.params_hint")})]}),i.jsxs("div",{style:ut,children:[i.jsx("label",{style:ct,children:n("layout_editor.data_sources.field.fallback")}),y.fallbackEnabled?i.jsxs("div",{"data-testid":"g7le-data-sources-field-fallback",style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx(zn,{value:y.fallbackValue===void 0?{}:y.fallbackValue,onChange:I=>_({...y,fallbackValue:I}),t:n,path:"fallback",scope:"ds-fallback",renderStringLeaf:I=>i.jsx(Ke,{value:I.value,onChange:I.onChange,t:n,candidates:d,testidPrefix:I.testidPrefix})}),(()=>{const I=y.fallbackValue===void 0?{}:y.fallbackValue;return i.jsxs("div",{style:Ou,children:[i.jsxs("button",{type:"button","data-testid":"g7le-ds-fallback-preview-toggle","aria-expanded":S,onClick:()=>C(L=>!L),style:Bu,children:[S?"▴":"▾"," ",n("layout_editor.data_sources.field.fallback_preview")]}),S&&i.jsx("pre",{"data-testid":"g7le-ds-fallback-preview",style:{...Wu,marginTop:4},children:JSON.stringify(I,null,2)})]})})(),i.jsx("button",{type:"button","data-testid":"g7le-data-sources-field-fallback-clear",onClick:()=>_({...y,fallbackEnabled:!1,fallbackValue:void 0}),style:{...rn,padding:"2px 8px",fontSize:11,alignSelf:"flex-start",color:"#dc2626",borderColor:"#fecaca"},children:n("layout_editor.data_sources.field.fallback_clear")})]}):i.jsxs("button",{type:"button","data-testid":"g7le-data-sources-field-fallback-add",onClick:()=>_({...y,fallbackEnabled:!0,fallbackValue:{}}),style:{...rn,padding:"4px 10px",display:"block"},children:["+ ",n("layout_editor.data_sources.field.fallback_add")]})]}),y.type==="websocket"&&i.jsxs("div",{"data-testid":"g7le-ds-ws-section",style:Mo,children:[i.jsx("div",{style:Lo,children:n("layout_editor.data_sources.section.websocket")}),i.jsxs("div",{style:ut,children:[i.jsx("label",{style:ct,children:n("layout_editor.data_sources.field.channel")}),i.jsx("input",{"data-testid":"g7le-ds-ws-channel",style:jt,value:y.channel,onChange:I=>_({...y,channel:I.target.value}),placeholder:"core.admin.dashboard"})]}),i.jsxs("div",{style:ut,children:[i.jsx("label",{style:ct,children:n("layout_editor.data_sources.field.event")}),i.jsx("input",{"data-testid":"g7le-ds-ws-event",style:jt,value:y.event,onChange:I=>_({...y,event:I.target.value}),placeholder:"dashboard.stats.updated"})]}),i.jsxs("div",{style:ut,children:[i.jsx("label",{style:ct,children:n("layout_editor.data_sources.field.channel_type")}),i.jsx("select",{"data-testid":"g7le-ds-ws-channeltype",style:jt,value:y.channel_type,onChange:I=>_({...y,channel_type:I.target.value}),children:XC.map(I=>i.jsx("option",{value:I,children:I},I))})]}),i.jsxs("div",{style:ut,children:[i.jsx("label",{style:ct,children:n("layout_editor.data_sources.field.target_source")}),i.jsx("input",{"data-testid":"g7le-ds-ws-target",style:jt,value:y.target_source,onChange:I=>_({...y,target_source:I.target.value}),list:"g7le-ds-ws-target-list"}),i.jsx("datalist",{id:"g7le-ds-ws-target-list",children:h.filter(I=>I.id!==y.id).map(I=>typeof I.id=="string"?i.jsx("option",{value:I.id},I.id):null)})]}),i.jsxs("div",{style:ut,children:[i.jsx("label",{style:ct,children:n("layout_editor.data_sources.field.on_receive")}),i.jsx("div",{"data-testid":"g7le-ds-ws-onreceive",children:i.jsx(Gt,{actions:y.onReceive,onChange:I=>_({...y,onReceive:I}),t:n,recipes:s,candidatePools:N,chipContext:"payload",actionChipCandidates:l?.actionChipCandidates??null,testIdPrefix:"g7le-ds-onreceive-list"})})]})]}),i.jsxs("div",{style:Mo,children:[i.jsx("div",{style:Lo,children:n("layout_editor.data_sources.section.on_success")}),i.jsx("div",{"data-testid":"g7le-ds-onsuccess",children:i.jsx(Gt,{actions:y.onSuccess,onChange:I=>_({...y,onSuccess:I}),t:n,recipes:s,candidatePools:N,chipContext:"response",actionChipCandidates:l?.actionChipCandidates??null,testIdPrefix:"g7le-ds-onsuccess-list"})})]}),i.jsxs("div",{style:Mo,children:[i.jsx("div",{style:Lo,children:n("layout_editor.data_sources.section.on_error")}),i.jsx("div",{"data-testid":"g7le-ds-onerror",children:i.jsx(Gt,{actions:y.onError,onChange:I=>_({...y,onError:I}),t:n,recipes:s,candidatePools:N,chipContext:"error",actionChipCandidates:l?.actionChipCandidates??null,testIdPrefix:"g7le-ds-onerror-list"})})]}),i.jsxs("div",{style:Mo,children:[i.jsx("div",{style:Lo,children:n("layout_editor.data_sources.section.error_handling")}),i.jsxs("div",{"data-testid":"g7le-ds-errorhandling",children:[i.jsx(Us,{value:y.errorHandling,onChange:I=>_({...y,errorHandling:I}),t:n,mode:"local",testIdPrefix:"g7le-ds-eh",renderActionList:(I,L,F)=>i.jsx(t$,{code:I,action:L,recipes:a,pools:N,t:n,onPatch:F})}),i.jsxs("button",{type:"button","data-testid":"g7le-ds-errorhandling-add",onClick:()=>{const I=Object.keys(y.errorHandling),L=["403","404","500","422","default"].find(F=>!I.includes(F))??"default";_({...y,errorHandling:{...y.errorHandling,[L]:{handler:"toast"}}})},style:{...rn,padding:"4px 10px",marginTop:6},children:["+ ",n("layout_editor.data_sources.add_error_code")]})]})]}),i.jsxs("div",{style:Mo,children:[i.jsx("div",{style:Lo,children:n("layout_editor.data_sources.section.load_condition")}),i.jsx("div",{"data-testid":"g7le-ds-loadcondition",children:i.jsx(Du,{node:FC({if:y.if||void 0}),spec:l??null,t:n,dataSourceCandidates:p,stateKeyCandidates:f,onPatchNode:I=>{const L=KC(I,{});_({...y,if:typeof L.if=="string"?L.if:""})}})})]})]}),!y&&i.jsxs("button",{type:"button","data-testid":"g7le-data-sources-add",onClick:B,style:{...Pu,marginBottom:16},children:["+ ",n("layout_editor.data_sources.add")]}),i.jsxs("div",{className:"g7le-data-sources__list","data-testid":"g7le-data-sources-list",style:{display:"flex",flexDirection:"column",gap:8},children:[h.length===0&&!y&&i.jsx("div",{"data-testid":"g7le-data-sources-empty",style:{fontSize:12,color:"#94a3b8",padding:"12px 0",textAlign:"center"},children:n("layout_editor.data_sources.empty")}),h.map((I,L)=>{const F=typeof I.id=="string"?I.id:`#${L}`,Y=typeof I.endpoint=="string"?I.endpoint:"",K=typeof I.label_key=="string"?I.label_key:"",X=as(I,b);return i.jsxs("div",{"data-testid":"g7le-data-sources-item","data-ds-id":F,style:{border:"1px solid #e2e8f0",borderRadius:8,padding:"10px 12px",display:"flex",alignItems:"center",gap:8,background:"#ffffff"},children:[i.jsxs("div",{style:{flex:1,minWidth:0},children:[i.jsxs("div",{"data-testid":"g7le-data-sources-item-title",style:{fontWeight:600,fontSize:13,display:"flex",alignItems:"baseline",gap:6,flexWrap:"wrap"},children:[i.jsx("span",{children:X??F}),X&&i.jsx("span",{"data-testid":"g7le-data-sources-item-id",style:{fontSize:11,fontWeight:400,color:"#94a3b8"},children:F}),(()=>{const Z=ls(I,n);return Z?i.jsx("span",{"data-testid":"g7le-data-sources-ext-badge",style:{fontSize:10,fontWeight:600,color:"#7c3aed",background:"#f5f3ff",border:"1px solid #ddd6fe",borderRadius:4,padding:"1px 6px"},children:Z}):null})()]}),Y&&i.jsx("div",{style:{fontSize:11,color:"#94a3b8",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:Y}),!K&&i.jsx("div",{"data-testid":"g7le-data-sources-nolabel",style:{fontSize:11,color:"#f59e0b"},children:n("layout_editor.data_sources.no_label")})]}),i.jsx("button",{type:"button","data-testid":"g7le-data-sources-edit",onClick:()=>M(I,L),style:{...rn,padding:"4px 10px"},children:n("layout_editor.data_sources.edit")}),i.jsx("button",{type:"button","data-testid":"g7le-data-sources-remove",onClick:()=>O(L),style:{...rn,padding:"4px 10px",color:"#dc2626",borderColor:"#fecaca"},children:n("layout_editor.data_sources.remove")})]},`${F}-${L}`)})]}),m.length>0&&i.jsxs("div",{style:{marginTop:16},children:[i.jsx("div",{style:{fontSize:12,fontWeight:600,color:"#64748b",textTransform:"uppercase",letterSpacing:.4,marginBottom:8},children:n("layout_editor.data_sources.inherited_title")}),i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:m.map((I,L)=>{const F=typeof I.id=="string"?I.id:`#${L}`,Y=T.has(F),K=[],X=(Z,ae)=>{const oe=I[Z];oe!=null&&K.push([ae,typeof oe=="object"?JSON.stringify(oe):String(oe)])};return X("type",n("layout_editor.data_sources.field.type")),X("endpoint",n("layout_editor.data_sources.field.endpoint")),X("method",n("layout_editor.data_sources.field.method")),X("auth_mode",n("layout_editor.data_sources.field.auth_mode")),X("loading_strategy",n("layout_editor.data_sources.field.loading_strategy")),X("auto_fetch",n("layout_editor.data_sources.field.auto_fetch")),X("params",n("layout_editor.data_sources.field.params")),i.jsxs("div",{"data-testid":"g7le-data-sources-inherited-item","data-ds-id":F,"data-expanded":Y?"true":"false",style:{border:"1px dashed #e2e8f0",borderRadius:6,fontSize:12,color:"#64748b",background:"#f8fafc",overflow:"hidden"},children:[i.jsxs("button",{type:"button","data-testid":"g7le-data-sources-inherited-toggle",onClick:()=>A(F),"aria-expanded":Y,style:{width:"100%",display:"flex",alignItems:"center",gap:8,padding:"8px 12px",background:"transparent",border:"none",cursor:"pointer",color:"inherit",fontSize:12,textAlign:"left",outline:"none"},children:[i.jsx("span",{style:{flex:"0 0 auto",width:12,transition:"transform 120ms",transform:Y?"rotate(90deg)":"none"},children:"▶"}),(()=>{const Z=as(I,b),ae=ls(I,n);return i.jsxs("span",{style:{flex:1,display:"inline-flex",alignItems:"baseline",gap:6,flexWrap:"wrap"},children:[i.jsx("span",{style:{fontWeight:600},children:Z??F}),Z&&i.jsx("span",{style:{fontSize:11,fontWeight:400,color:"#94a3b8"},children:F}),ae&&i.jsx("span",{"data-testid":"g7le-data-sources-ext-badge",style:{fontSize:10,fontWeight:600,color:"#7c3aed",background:"#f5f3ff",border:"1px solid #ddd6fe",borderRadius:4,padding:"1px 6px"},children:ae})]})})()]}),Y&&i.jsxs("div",{"data-testid":"g7le-data-sources-inherited-info",style:{padding:"0 12px 10px 32px",display:"flex",flexDirection:"column",gap:3},children:[K.length===0&&i.jsx("span",{style:{color:"#94a3b8"},children:"—"}),K.map(([Z,ae])=>i.jsxs("div",{style:{display:"flex",gap:6},children:[i.jsxs("span",{style:{flex:"0 0 auto",color:"#94a3b8"},children:[Z,":"]}),i.jsx("span",{style:{flex:1,minWidth:0,wordBreak:"break-all",color:"#475569"},children:ae})]},Z))]})]},`inh-${F}-${L}`)})})]})]}),y&&i.jsxs("div",{className:"g7le-data-sources__footer",style:{flex:"0 0 auto",padding:"12px 16px",borderTop:"1px solid #e2e8f0",background:"#ffffff"},children:[w&&i.jsx("div",{"data-testid":"g7le-data-sources-form-error",role:"alert",style:{fontSize:12,color:"#dc2626",marginBottom:10},children:w}),i.jsxs("div",{style:{display:"flex",gap:8,justifyContent:"flex-end"},children:[i.jsx("button",{type:"button","data-testid":"g7le-data-sources-form-cancel",onClick:z,style:rn,children:n("layout_editor.data_sources.form.cancel")}),i.jsx("button",{type:"button","data-testid":"g7le-data-sources-form-submit",onClick:H,style:Pu,children:n("layout_editor.data_sources.form.save")})]})]})]})}function i$(e){const t=e?.globalHeaders;return Array.isArray(t)?t:[]}function s$(e){const t=e?.scripts;return Array.isArray(t)?t:[]}function a$(e){const t=i$(e.raw),n=s$(e.raw);return i.jsxs("div",{className:"g7le-data-source-tab","data-testid":"g7le-data-source-tab",style:l$,children:[i.jsx(r$,{...e}),i.jsxs("div",{style:Hu,"data-testid":"g7le-global-headers",children:[i.jsx("div",{style:Fu,children:e.t("layout_editor.data_sources.global_headers")}),t.length===0?i.jsx("p",{"data-testid":"g7le-global-header-empty",style:Gu,children:e.t("layout_editor.data_sources.global_headers_empty")}):t.map((o,r)=>i.jsxs("div",{"data-testid":`g7le-global-header-${r}`,style:Ku,children:[i.jsx("code",{style:Vu,children:o.pattern??"*"}),i.jsx("span",{style:d$,children:"→"}),i.jsx("span",{style:Uu,children:Object.keys(o.headers??{}).join(", ")})]},r)),i.jsxs("p",{style:qu,children:["ⓘ ",e.t("layout_editor.data_sources.global_headers_hint")]})]}),i.jsxs("div",{style:Hu,"data-testid":"g7le-scripts",children:[i.jsx("div",{style:Fu,children:e.t("layout_editor.data_sources.scripts")}),n.length===0?i.jsx("p",{"data-testid":"g7le-script-empty",style:Gu,children:e.t("layout_editor.data_sources.scripts_empty")}):n.map((o,r)=>i.jsxs("div",{"data-testid":`g7le-script-${o.id??r}`,style:Ku,children:[i.jsx("code",{style:Vu,children:o.id??`#${r}`}),i.jsx("span",{style:Uu,children:o.src??""}),o.loading?i.jsx("span",{style:c$,children:o.loading}):null]},o.id??r)),i.jsxs("p",{style:qu,children:["ⓘ ",e.t("layout_editor.data_sources.scripts_hint")]})]})]})}const l$={display:"flex",flexDirection:"column",gap:16,minWidth:0},Hu={borderTop:"1px solid #e2e8f0",paddingTop:12,display:"flex",flexDirection:"column",gap:6},Fu={fontSize:12,fontWeight:700,color:"#475569"},Ku={display:"flex",alignItems:"center",gap:8,fontSize:12,padding:"4px 8px",border:"1px solid #f1f5f9",borderRadius:6},Vu={fontSize:11,color:"#0f172a",fontFamily:"monospace"},d$={color:"#94a3b8"},Uu={flex:1,minWidth:0,color:"#475569",wordBreak:"break-all"},c$={fontSize:10,color:"#64748b",background:"#f1f5f9",borderRadius:4,padding:"0 4px"},qu={margin:0,fontSize:11,color:"#94a3b8"},Gu={margin:0,fontSize:12,color:"#94a3b8"},u$=["meta","seo","init","overlay","computed","state","error","data"],p$=["401","403","404","500","503"],f$={meta:"layout_editor.page_settings.tab.meta",seo:"layout_editor.page_settings.tab.seo",init:"layout_editor.page_settings.tab.init",overlay:"layout_editor.page_settings.tab.overlay",computed:"layout_editor.page_settings.tab.computed",state:"layout_editor.page_settings.tab.state",error:"layout_editor.page_settings.tab.error",data:"layout_editor.page_settings.tab.data"};async function g$(e){if(typeof fetch!="function"||!e)return[];try{const t=await fetch(en(`/api/admin/templates/${encodeURIComponent(e)}/editor/seo-candidates`,"json"),{credentials:"same-origin",headers:Ne()});if(!t.ok)return[];const o=(await t.json().catch(()=>null))?.data?.extensions;if(!Array.isArray(o))return[];const r=[];for(const s of o)if(s&&typeof s=="object"){const a=s.type,l=s.id,d=s.label;typeof a=="string"&&typeof l=="string"&&l.length>0&&r.push({type:a,id:l,name:typeof d=="string"?d:l})}return r}catch{return[]}}function h$(e,t){let n=0;for(const o of e)Yn(o,t).kind==="advanced"&&(n+=1);return n}function y$(e,t){let n=0;for(const o of Object.keys(e))Dd(e[o],t).kind==="advanced"&&(n+=1);return n}function b$(e,t,n){const o=e("meta",{})??{},r=o.title;if(typeof r=="string"&&r.length>0){if(r.startsWith("$t:")){const a=n(r.slice(3));if(a&&a!==r.slice(3))return a}else if(!/\{\{[\s\S]*\}\}/.test(r))return r}const s=o.editor_label;return typeof s=="string"&&s.length>0?s.startsWith("$t:")?n(s.slice(3)):s:t||""}function m$({templateIdentifier:e,spec:t,t:n,resolveLabel:o,permissionCandidates:r,onClose:s,initialTab:a="meta",extensionsFetcher:l}){const{state:d}=Qe(),{raw:c,getValue:p,patch:f}=jm(),[b,g]=u.useState(a),m=d.selectedRoute?.path??"",h=u.useMemo(()=>Od(d.routeTree,o),[d.routeTree,o]),v=u.useMemo(()=>Bd(c),[c]),y=u.useMemo(()=>Wd(t),[t]),_=u.useMemo(()=>iv(c,o),[c,o]),w=Pd({raw:c,spec:t}),k=u.useMemo(()=>lb(t),[t]),x=u.useMemo(()=>db(t),[t]),$=u.useMemo(()=>cb(t),[t]),S=u.useMemo(()=>ub(t),[t]),C=u.useMemo(()=>ko(k),[k]),T=u.useMemo(()=>Cd(x),[x]),E=p("init_actions",void 0)??p("initActions",[]),A=p("computed",{}),N=p("__computedSource",{}),D=p("errorHandling",{}),B=p("transition_overlay",void 0),M=(p("__editor",{})??{}).original,O=u.useMemo(()=>{if(M===void 0)return;const G=M.transition_overlay;return G&&typeof G=="object"&&!Array.isArray(G)?G:{}},[M]),z=u.useMemo(()=>{const G=B;if(!G||typeof G!="object"||Array.isArray(G))return;const ee=O??{},ge={};for(const[V,te]of Object.entries(G))V in ee||(ge[V]=te);return Object.keys(ge).length>0?ge:void 0},[B,O]),[H,P]=u.useState([]);u.useEffect(()=>{let G=!1;const ee=l??g$;return(async()=>{const ge=await ee(e);G||P(ge)})(),()=>{G=!0}},[e,l]);const I=(p("meta",{})??{}).seo?.page_type,L=ov({raw:c,spec:t,pageType:typeof I=="string"?I:null}),F=u.useMemo(()=>nv(c,t),[c,t]),Y=u.useMemo(()=>({meta:0,seo:0,init:h$(E,C),overlay:0,computed:y$(A,T),state:0,error:0,data:0}),[E,C,A,T]),K=u.useMemo(()=>Object.values(Y).reduce((G,ee)=>G+ee,0),[Y]),X=u.useMemo(()=>rv(c,o,n),[c,o,n]),Z=u.useCallback(G=>{const ge={...M?.computed??{}};delete ge[G];const V={...A};delete V[G],f("computed",V,Object.keys(ge).length===0?void 0:ge)},[M,A,f]),ae=b$(p,m,n),oe=()=>{switch(b){case"meta":return i.jsx(kx,{getValue:p,patch:f,t:n,fieldT:o,spec:t,permissionCandidates:r,bindingCandidates:w});case"seo":return i.jsx(d0,{getValue:p,patch:f,t:n,templateIdentifier:e,candidates:L,availableExtensions:H,dataSourceOptions:X,previewUrl:m||"/",seedContext:F});case"init":return i.jsx(Ak,{actions:E,onChange:G=>f("init_actions",G),recipes:k,t:o,bindingCandidates:w,pageCandidates:h,dataSourceCandidates:v,stateKeyCandidates:y,modalCandidates:_});case"overlay":return i.jsx(Qk,{value:B,ownValue:O,baseValue:z,patch:G=>f("transition_overlay",G),t:o,loadingComponents:S,progressiveDataSources:X,bindingCandidates:w});case"computed":return i.jsx(j1,{computed:A,onChange:G=>f("computed",G),recipes:x,t:o,sampleContext:F,dataSourceCandidates:v,bindingCandidates:w,computedSource:N,onRevert:Z});case"state":return i.jsx(xS,{raw:c,own:M?{initLocal:M.initLocal,initGlobal:M.initGlobal,initIsolated:M.initIsolated,state:M.state}:void 0,patch:f,t:n});case"error":return i.jsx(GS,{value:D,onChange:G=>f("errorHandling",G),t:o,errorConfigCodes:p$,templateCodes:Object.keys(D),ownCodes:Object.keys(M?.errorHandling??{}),recipes:$,pageCandidates:h,modalCandidates:_,dataSourceCandidates:v,stateKeyCandidates:y});case"data":return i.jsx(a$,{raw:c,t:n,resolveLabel:o,onChange:(G,ee)=>f("data_sources",G,ee),onClose:s,actionRecipes:k,errorRecipes:$,conditionSpec:t,bindingCandidates:w,pageCandidates:h,dataSourceCandidates:v,stateKeyCandidates:y});default:return i.jsx("div",{})}};return i.jsxs("div",{className:"g7le-page-settings","data-testid":"g7le-page-settings",style:v$,children:[i.jsxs("div",{style:_$,children:[i.jsx("span",{"data-testid":"g7le-page-settings-title",style:x$,children:n("layout_editor.page_settings.title",{name:ae})}),i.jsx("button",{type:"button","data-testid":"g7le-page-settings-close-x",onClick:s,"aria-label":n("layout_editor.page_settings.close"),style:w$,children:"✕"})]}),i.jsx("div",{role:"tablist",style:k$,children:u$.map(G=>{const ee=Y[G];return i.jsxs("button",{type:"button",role:"tab","aria-selected":b===G,"data-testid":`g7le-page-settings-tab-${G}`,"data-active":b===G?"true":"false",onClick:()=>g(G),style:b===G?S$:Yu,children:[n(f$[G]),ee>0?i.jsxs("span",{"data-testid":`g7le-page-settings-tab-badge-${G}`,style:C$,children:["(",ee,")"]}):null]},G)})}),K>0?i.jsxs("p",{"data-testid":"g7le-page-settings-advanced-summary",style:$$,children:["⚠ ",n("layout_editor.page_settings.advanced_summary",{count:K})," ⓘ"]}):null,i.jsx("div",{"data-testid":"g7le-page-settings-panel",style:E$,children:oe()}),i.jsx("div",{style:I$,children:i.jsx("button",{type:"button","data-testid":"g7le-page-settings-close",onClick:s,style:A$,children:n("layout_editor.page_settings.close")})})]})}const v$={display:"flex",flexDirection:"column",minWidth:0,maxWidth:"100%",padding:"20px 24px",boxSizing:"border-box",flex:1,minHeight:0,maxHeight:"100%",overflow:"hidden",fontFamily:"system-ui, -apple-system, sans-serif"},_$={display:"flex",alignItems:"center",gap:8,paddingBottom:8,borderBottom:"1px solid #e2e8f0"},x$={flex:1,fontSize:15,fontWeight:700,color:"#0f172a",minWidth:0},w$={border:"none",background:"transparent",color:"#64748b",cursor:"pointer",fontSize:16,lineHeight:1,padding:4},k$={display:"flex",gap:2,paddingTop:8,borderBottom:"1px solid #e2e8f0",flexWrap:"nowrap",overflowX:"auto",overflowY:"hidden",flexShrink:0,minWidth:0},Yu={border:"none",borderBottomWidth:"2px",borderBottomStyle:"solid",borderBottomColor:"transparent",background:"transparent",color:"#64748b",cursor:"pointer",fontSize:12,padding:"6px 10px",whiteSpace:"nowrap"},S$={...Yu,color:"#2563eb",borderBottomColor:"#2563eb",fontWeight:600},C$={marginLeft:4,fontSize:10,color:"#b45309"},$$={margin:0,marginTop:8,fontSize:11,color:"#b45309",background:"#fffbeb",padding:"6px 8px",borderRadius:6},E$={flex:1,overflowY:"auto",paddingTop:12,minWidth:0,minHeight:0},I$={display:"flex",justifyContent:"flex-end",paddingTop:8,borderTop:"1px solid #e2e8f0"},A$={border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",fontSize:13,padding:"6px 16px"};function Qs(e,t){const n=`/api/admin/templates/${encodeURIComponent(e)}`;return t.kind==="layout"?`${n}/layouts/${t.layoutName}/versions`:`${n}/layout-extensions/${encodeURIComponent(t.extensionId)}/versions`}const Xu=100,Ju=500;function T$(e,t,n){const[o,r]=u.useState([]),[s,a]=u.useState(!1),[l,d]=u.useState(!1),[c,p]=u.useState(null),[f,b]=u.useState(null),[g,m]=u.useState(Xu),[h,v]=u.useState(!1),y=u.useCallback(async($,S)=>{if(!t){r([]),p(null),v(!1);return}S==="more"?d(!0):a(!0),p(null);try{const C=`${Qs(e,t)}?limit=${$}`,T=await fetch(C,{credentials:"same-origin",headers:Ne()}),E=await T.json().catch(()=>null);if(!T.ok){p(E?.message??`HTTP ${T.status}`),S==="reload"&&r([]);return}const A=E?.data,N=Array.isArray(A)?A:[];r(N),v(N.length>=$&&${await y(g,"reload")},[y,g]),w=u.useCallback(async()=>{const $=Math.min(g+Xu,Ju);if($<=g){v(!1);return}await y($,"more")},[y,g]),k=u.useCallback(async $=>{if(!t)return{kind:"not_found"};b($);try{const S=`${Qs(e,t)}/${$}/restore`,C=await fetch(S,{method:"POST",credentials:"same-origin",headers:Ne({"Content-Type":"application/json"})}),T=await C.json().catch(()=>null);if(C.status===404)return{kind:"not_found"};if(!C.ok)return{kind:"network_error",message:T?.message??`HTTP ${C.status}`};const E=typeof T?.data?.version=="number"?T.data.version:-1;return await n?.(E>=0?E:void 0),{kind:"success",newVersion:E}}catch(S){return{kind:"network_error",message:S instanceof Error?S.message:"network error"}}finally{b(null)}},[e,t,n]),x=u.useCallback(async $=>{if(!t)return{kind:"not_found"};try{const S=`${Qs(e,t)}/${$}`,C=await fetch(S,{credentials:"same-origin",headers:Ne()}),T=await C.json().catch(()=>null);if(C.status===404)return{kind:"not_found"};if(!C.ok)return{kind:"network_error",message:T?.message??`HTTP ${C.status}`};const E=T?.data;if(!E)return{kind:"not_found"};if(t.kind==="extension"&&!E.full_content){const A=E.content;if(typeof A=="string")try{const N=JSON.parse(A);N&&typeof N=="object"&&(E.full_content=N)}catch{}}return{kind:"success",detail:E}}catch(S){return{kind:"network_error",message:S instanceof Error?S.message:"network error"}}},[e,t]);return{versions:o,isLoading:s,isLoadingMore:l,error:c,restoringId:f,hasMore:h,loadVersions:_,loadMore:w,restore:k,loadVersionDetail:x}}function D$(e,t){const n=e.length,o=t.length,r=Array.from({length:n+1},()=>new Array(o+1).fill(0));for(let s=n-1;s>=0;s--)for(let a=o-1;a>=0;a--)e[s]===t[a]?r[s][a]=r[s+1][a+1]+1:r[s][a]=Math.max(r[s+1][a],r[s][a+1]);return r}function z$(e,t,n){const o=[];let r=0,s=0;const a=e.length,l=t.length;for(;r=n[r][s+1]?(o.push({kind:"remove",oldIndex:r,content:e[r]}),r++):(o.push({kind:"add",newIndex:s,content:t[s]}),s++);for(;r0&&t[t.length-1]===""&&t.pop(),t}const Qu=4e3;function N$(e,t,n=3){const o=Zu(e),r=Zu(t);let s=0;const a=Math.min(o.length,r.length);for(;sQu||p.length>Qu)return{hunks:[],addedCount:-1,removedCount:-1,identical:!1};const f=D$(c,p),b=z$(c,p,f),g=[];let m=s,h=s,v=0,y=0;for(let k=0;k{const s=e.slice(r.start,r.end+1);let a=0,l=0,d=0,c=0;for(const g of s)g.oldLine!==null&&(a===0&&(a=g.oldLine),d++),g.newLine!==null&&(l===0&&(l=g.newLine),c++);const p=a||(d===0?0:1),f=l||(c===0?0:1);return{header:`@@ -${p},${d} +${f},${c} @@`,oldStart:p,oldCount:d,newStart:f,newCount:c,lines:s}})}function Ru(e){return JSON.stringify(Rs(e),null,2)}function Rs(e){if(Array.isArray(e))return e.map(Rs);if(e&&typeof e=="object"){const t=e,n={};for(const o of Object.keys(t).sort())n[o]=Rs(t[o]);return n}return e}const L$={display:"flex",flexDirection:"column",height:"100%",minHeight:0},P$={display:"flex",alignItems:"center",gap:8,padding:"12px 16px",borderBottom:"1px solid #e2e8f0",background:"#f8fafc"},O$={display:"inline-flex",alignItems:"center",gap:4,padding:"4px 10px",borderRadius:6,border:"1px solid #cbd5e1",background:"#ffffff",color:"#0f172a",fontSize:12,fontWeight:600,cursor:"pointer",outline:"none"},B$={marginLeft:"auto",border:"none",background:"transparent",fontSize:16,color:"#64748b",cursor:"pointer",outline:"none"},W$={display:"flex",alignItems:"center",gap:12,padding:"8px 16px",borderBottom:"1px solid #e2e8f0",background:"#ffffff",fontSize:12,fontWeight:600},j$={flex:1,minHeight:0,overflow:"auto",background:"#ffffff",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace',fontSize:12,lineHeight:1.5},ep={padding:"24px 12px",textAlign:"center",color:"#94a3b8",fontSize:13},H$={padding:"2px 12px",background:"#f1f5f9",color:"#64748b",borderTop:"1px solid #e2e8f0",borderBottom:"1px solid #e2e8f0",userSelect:"none"};function F$(e){return e==="add"?{row:{background:"#e6ffed"},gutter:{background:"#cdffd8",color:"#22863a"},sign:"+",signColor:"#22863a"}:e==="remove"?{row:{background:"#ffeef0"},gutter:{background:"#ffdce0",color:"#b31d28"},sign:"-",signColor:"#b31d28"}:{row:{background:"#ffffff"},gutter:{background:"#f8fafc",color:"#94a3b8"},sign:" ",signColor:"#94a3b8"}}const tp={display:"inline-block",width:44,textAlign:"right",padding:"0 6px",color:"#94a3b8",userSelect:"none",borderRight:"1px solid #e2e8f0",whiteSpace:"nowrap"};function K$({oldVersion:e,newVersion:t,oldContent:n,newContent:o,t:r,onBack:s,onClose:a}){const l=u.useMemo(()=>{const c=Ru(n),p=Ru(o);return N$(c,p)},[n,o]),d=l.addedCount<0;return i.jsxs("div",{className:"g7le-version-diff","data-testid":"g7le-version-diff",style:L$,children:[i.jsxs("div",{"data-modal-drag-handle":!0,style:P$,children:[i.jsxs("button",{type:"button",onClick:s,style:O$,"data-testid":"g7le-version-diff-back",children:["← ",r("layout_editor.version_history.diff_back")]}),i.jsx("span",{style:{fontSize:14,fontWeight:700},"data-testid":"g7le-version-diff-title",children:r("layout_editor.version_history.diff_title",{old:e,new:t})}),i.jsx("button",{type:"button","aria-label":r("layout_editor.version_history.close"),onClick:a,style:B$,"data-testid":"g7le-version-diff-close",children:"✕"})]}),!d&&i.jsxs("div",{style:W$,"data-testid":"g7le-version-diff-summary",children:[i.jsx("span",{style:{color:"#16a34a"},"data-testid":"g7le-version-diff-added",children:r("layout_editor.version_history.added",{count:Math.max(0,l.addedCount)})}),i.jsx("span",{style:{color:"#dc2626"},"data-testid":"g7le-version-diff-removed",children:r("layout_editor.version_history.removed",{count:Math.max(0,l.removedCount)})})]}),i.jsx("div",{style:j$,children:d?i.jsx("div",{style:ep,"data-testid":"g7le-version-diff-too-large",children:r("layout_editor.version_history.diff_too_large")}):l.identical?i.jsx("div",{style:ep,"data-testid":"g7le-version-diff-identical",children:r("layout_editor.version_history.diff_identical")}):l.hunks.map((c,p)=>i.jsxs("div",{"data-testid":`g7le-version-diff-hunk-${p}`,children:[i.jsx("div",{style:H$,"data-testid":`g7le-version-diff-hunk-header-${p}`,children:c.header}),c.lines.map((f,b)=>{const g=F$(f.kind);return i.jsxs("div",{style:{display:"flex",alignItems:"stretch",...g.row},"data-kind":f.kind,"data-testid":`g7le-version-diff-line-${p}-${b}`,children:[i.jsx("span",{style:{...tp,...g.gutter},"aria-hidden":"true",children:f.oldLine??""}),i.jsx("span",{style:{...tp,...g.gutter},"aria-hidden":"true",children:f.newLine??""}),i.jsx("span",{style:{display:"inline-block",width:16,textAlign:"center",color:g.signColor,userSelect:"none",fontWeight:700},"aria-hidden":"true",children:g.sign}),i.jsx("span",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",flex:1,padding:"0 4px"},children:f.content})]},b)})]},p))})]})}const V$={display:"flex",flexDirection:"column",height:"100%",minHeight:0},U$={display:"flex",alignItems:"center",gap:8,padding:"12px 16px",borderBottom:"1px solid #e2e8f0",background:"#f8fafc"},q$={marginLeft:"auto",border:"none",background:"transparent",fontSize:16,color:"#64748b",cursor:"pointer",outline:"none"},G$={flex:1,minHeight:0,overflowY:"auto",padding:12},np={padding:"24px 12px",textAlign:"center",color:"#94a3b8",fontSize:13},Y$={margin:"8px 16px 0",padding:"8px 12px",borderRadius:6,background:"#fef2f2",color:"#b91c1c",fontSize:12,border:"1px solid #fecaca"},X$={display:"flex",flexDirection:"column",gap:8},J$={display:"flex",alignItems:"center",gap:12,padding:"10px 12px",borderRadius:8,border:"1px solid #e2e8f0",background:"#ffffff"},Z$={display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:44,padding:"2px 8px",borderRadius:999,background:"#eff6ff",color:"#1d4ed8",fontSize:12,fontWeight:700},Q$={display:"inline-flex",alignItems:"center",padding:"1px 8px",borderRadius:999,background:"#0f172a",color:"#ffffff",fontSize:10,fontWeight:700,letterSpacing:.3},R$={display:"flex",alignItems:"center",gap:10,fontSize:11,fontWeight:600},eE={display:"flex",flexDirection:"column",gap:2,minWidth:0,flex:1},op={padding:"6px 12px",borderRadius:6,border:"1px solid #cbd5e1",background:"#ffffff",color:"#0f172a",fontSize:12,fontWeight:600,cursor:"pointer",outline:"none",whiteSpace:"nowrap"};function rp(e){return e.full_content&&typeof e.full_content=="object"?e.full_content:{endpoint:e.endpoint,components:e.components,data_sources:e.data_sources,metadata:e.metadata}}function tE(e){if(!e)return"";const t=Date.parse(e);if(Number.isNaN(t))return e;try{return new Date(t).toLocaleString()}catch{return e}}function nE({templateIdentifier:e,target:t,t:n,onRestored:o,onClose:r}){const{versions:s,isLoading:a,isLoadingMore:l,error:d,restoringId:c,hasMore:p,loadVersions:f,loadMore:b,restore:g,loadVersionDetail:m}=T$(e,t,o),[h,v]=u.useState(null),[y,_]=u.useState(null),[w,k]=u.useState(null);u.useEffect(()=>{f()},[f]);const x=u.useCallback(async C=>{v(null),k(C.version);try{const T=await m(C.version);if(T.kind!=="success"){v(T.kind==="not_found"?n("layout_editor.version_history.restore_not_found"):T.message);return}const E=C.version-1,A=s.some(D=>D.version===E);let N={};if(A){const D=await m(E);if(D.kind==="success")N=rp(D.detail);else if(D.kind==="network_error"){v(D.message);return}}_({oldVersion:A?E:0,newVersion:C.version,oldContent:N,newContent:rp(T.detail)})}finally{k(null)}},[m,s,n]),$=u.useCallback(async C=>{v(null);const T=n("layout_editor.version_history.restore_confirm");if(!(typeof window<"u"?window.confirm(T):!0))return;const A=await g(C);A.kind==="success"?r():A.kind==="not_found"?v(n("layout_editor.version_history.restore_not_found")):v(A.message)},[g,r,n]),S=h??d;return y?i.jsx(K$,{oldVersion:y.oldVersion,newVersion:y.newVersion,oldContent:y.oldContent,newContent:y.newContent,t:n,onBack:()=>_(null),onClose:r}):i.jsxs("div",{className:"g7le-version-history","data-testid":"g7le-version-history",style:V$,children:[i.jsxs("div",{"data-modal-drag-handle":!0,style:U$,children:[i.jsxs("span",{style:{fontSize:14,fontWeight:700},"data-testid":"g7le-version-history-title",children:["🕘 ",n("layout_editor.version_history.title")]}),i.jsx("button",{type:"button","aria-label":n("layout_editor.version_history.close"),onClick:r,style:q$,"data-testid":"g7le-version-history-close",children:"✕"})]}),S&&i.jsx("div",{style:Y$,"data-testid":"g7le-version-history-error",children:S}),i.jsx("div",{style:G$,children:a?i.jsx("div",{style:np,"data-testid":"g7le-version-history-loading",children:n("layout_editor.version_history.loading")}):s.length===0?i.jsx("div",{style:np,"data-testid":"g7le-version-history-empty",children:n("layout_editor.version_history.empty")}):i.jsxs("div",{"data-testid":"g7le-version-history-list",style:X$,children:[s.map((C,T)=>{const E=C.changes_summary,A=E?.added_count??0,N=E?.removed_count??0,D=E?.char_diff??0,B=tE(C.created_at),M=c===C.id,O=T===0;return i.jsxs("div",{style:J$,"data-testid":`g7le-version-row-${C.id}`,children:[i.jsxs("span",{style:Z$,"data-testid":`g7le-version-badge-${C.id}`,children:["v",C.version]}),i.jsxs("div",{style:eE,children:[i.jsxs("span",{style:{display:"flex",alignItems:"center",gap:8},children:[B&&i.jsx("span",{style:{fontSize:12,color:"#475569",fontWeight:600},children:B}),O&&i.jsx("span",{style:Q$,"data-testid":`g7le-version-latest-${C.id}`,children:n("layout_editor.version_history.latest")})]}),i.jsxs("span",{style:R$,"data-testid":`g7le-version-summary-${C.id}`,children:[i.jsx("span",{style:{color:"#16a34a"},"data-testid":`g7le-version-added-${C.id}`,children:n("layout_editor.version_history.added",{count:A})}),i.jsx("span",{style:{color:"#dc2626"},"data-testid":`g7le-version-removed-${C.id}`,children:n("layout_editor.version_history.removed",{count:N})}),i.jsx("span",{style:{color:"#94a3b8",fontWeight:500},"data-testid":`g7le-version-chars-${C.id}`,children:n("layout_editor.version_history.chars",{diff:`${D>=0?"+":""}${D}`})})]}),i.jsx("span",{style:{fontSize:11,color:"#94a3b8"},"data-testid":`g7le-version-author-${C.id}`,children:n("layout_editor.version_history.saved_by",{name:C.created_by_name??n("layout_editor.version_history.unknown_author")})})]}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsx("button",{type:"button",onClick:()=>{x(C)},disabled:w!==null,style:{...op,background:"#f8fafc",opacity:w!==null?.6:1},"data-testid":`g7le-version-compare-${C.id}`,children:w===C.version?n("layout_editor.version_history.comparing"):n("layout_editor.version_history.compare")}),!O&&i.jsx("button",{type:"button",onClick:()=>{$(C.id)},disabled:M||c!==null,style:{...op,opacity:M||c!==null?.6:1},"data-testid":`g7le-version-restore-${C.id}`,children:n(M?"layout_editor.version_history.restoring":"layout_editor.version_history.restore")})]})]},C.id)}),p&&i.jsx("button",{type:"button","data-testid":"g7le-version-history-load-more",style:oE,disabled:l,onClick:()=>{b()},children:n(l?"layout_editor.version_history.loading":"layout_editor.version_history.load_more")})]})})]})}const oE={width:"100%",marginTop:8,padding:"8px 12px",fontSize:12,color:"#475569",background:"#f8fafc",border:"1px solid #e2e8f0",borderRadius:6,cursor:"pointer"};function Po(e){return`/api/admin/extensions/${encodeURIComponent(e.type)}/${encodeURIComponent(e.identifier)}/custom-assets`}function Oo(e,t){const n=e?.message;return typeof n=="string"&&n!==""?n:`HTTP ${t}`}function rE(e){const[t,n]=u.useState([]),[o,r]=u.useState(null),[s,a]=u.useState(!1),[l,d]=u.useState(!1),[c,p]=u.useState(null),f=u.useCallback(async()=>{a(!0),p(null);try{const v=await fetch(Po(e),{credentials:"same-origin",headers:Ne()}),y=await v.json().catch(()=>null);if(v.status===401||v.status===403){d(!0),n([]);return}if(d(!1),!v.ok){p(Oo(y,v.status)),n([]);return}const _=y?.data??{},w=_.files;n(Array.isArray(w)?w:[]),r({editable_extensions:_.editable_extensions??[],uploadable_extensions:_.uploadable_extensions??[],max_text_bytes:_.max_text_bytes??0,max_upload_bytes:_.max_upload_bytes??0})}catch(v){p(v instanceof Error?v.message:"network error"),n([])}finally{a(!1)}},[e.type,e.identifier]),b=u.useCallback(async v=>{p(null);try{const y=`${Po(e)}/content?path=${encodeURIComponent(v)}`,_=await fetch(y,{credentials:"same-origin",headers:Ne()}),w=await _.json().catch(()=>null);if(!_.ok)return p(Oo(w,_.status)),null;const k=w?.data?.content;return typeof k=="string"?k:""}catch(y){return p(y instanceof Error?y.message:"network error"),null}},[e.type,e.identifier]),g=u.useCallback(async(v,y)=>{p(null);try{const _=await fetch(`${Po(e)}/content`,{method:"PUT",credentials:"same-origin",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({path:v,content:y})}),w=await _.json().catch(()=>null);return _.ok?(await f(),!0):(p(Oo(w,_.status)),!1)}catch(_){return p(_ instanceof Error?_.message:"network error"),!1}},[e.type,e.identifier,f]),m=u.useCallback(async(v,y)=>{p(null);try{const _=new FormData;_.append("file",v),y&&_.append("directory",y);const w=await fetch(`${Po(e)}/upload`,{method:"POST",credentials:"same-origin",headers:Ne(),body:_}),k=await w.json().catch(()=>null);return w.ok?(await f(),!0):(p(Oo(k,w.status)),!1)}catch(_){return p(_ instanceof Error?_.message:"network error"),!1}},[e.type,e.identifier,f]),h=u.useCallback(async v=>{p(null);try{const y=`${Po(e)}?path=${encodeURIComponent(v)}`,_=await fetch(y,{method:"DELETE",credentials:"same-origin",headers:Ne()}),w=await _.json().catch(()=>null);return _.ok?(await f(),!0):(p(Oo(w,_.status)),!1)}catch(y){return p(y instanceof Error?y.message:"network error"),!1}},[e.type,e.identifier,f]);return{files:t,meta:o,isLoading:s,forbidden:l,error:c,reload:f,read:b,save:g,upload:m,remove:h}}const iE={display:"flex",flexDirection:"column",height:"100%",minHeight:0},sE={display:"flex",alignItems:"center",gap:8,padding:"12px 16px",borderBottom:"1px solid #e2e8f0",background:"#f8fafc",fontWeight:600,color:"#0f172a"},aE={marginLeft:"auto",border:"none",background:"transparent",fontSize:16,color:"#64748b",cursor:"pointer",outline:"none"},lE={flex:1,minHeight:0,display:"flex"},dE={width:260,flexShrink:0,borderRight:"1px solid #e2e8f0",overflowY:"auto",padding:8},cE={flex:1,minWidth:0,display:"flex",flexDirection:"column",padding:12,gap:8},ip={display:"flex",alignItems:"center",gap:6,width:"100%",padding:"6px 8px",borderRadius:6,borderWidth:1,borderStyle:"solid",borderColor:"transparent",backgroundColor:"transparent",fontSize:12,color:"#334155",cursor:"pointer",textAlign:"left"},uE={...ip,backgroundColor:"#eff6ff",borderColor:"#bfdbfe",color:"#1d4ed8",fontWeight:600},pE={margin:16,padding:16,borderRadius:8,border:"1px solid #fcd34d",background:"#fffbeb",color:"#92400e",fontSize:13,lineHeight:1.7},fE={padding:"8px 12px",borderRadius:6,border:"1px solid #fecaca",background:"#fef2f2",color:"#b91c1c",fontSize:12},gE={flex:1,minHeight:220,width:"100%",boxSizing:"border-box",padding:10,borderRadius:6,borderWidth:1,borderStyle:"solid",borderColor:"#cbd5e1",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",fontSize:12,lineHeight:1.6,resize:"vertical"},sp={display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},io={padding:"6px 12px",borderRadius:6,borderWidth:1,borderStyle:"solid",borderColor:"#cbd5e1",backgroundColor:"#ffffff",color:"#334155",fontSize:12,cursor:"pointer"},hE={...io,backgroundColor:"#2563eb",borderColor:"#2563eb",color:"#ffffff",fontWeight:600},yE={...io,borderColor:"#fca5a5",color:"#b91c1c"},bE={...io,cursor:"text",minWidth:200},mE={...io,cursor:"pointer",minWidth:220};function vE(e,t){if(typeof e=="string"&&e!=="")return e;if(e&&typeof e=="object"){const n=e,o=window?.G7Config?.locale??"ko",r=n[o]??n.ko??n.en??Object.values(n)[0];if(typeof r=="string"&&r!=="")return r}return t}function _E(e){const t=(typeof window<"u"?window.G7Config:null)??{},n=[{type:"template",identifier:e,label:e}];for(const[o,r]of[["module",t.activeModules],["plugin",t.activePlugins]])if(Array.isArray(r))for(const s of r){const a=typeof s?.identifier=="string"?s.identifier:"";a&&n.push({type:o,identifier:a,label:vE(s?.display_name,a)})}return n}function xE(e){return e<1024?`${e} B`:e<1024*1024?`${Math.round(e/1024)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function wE(e){const{templateIdentifier:t,t:n,onClose:o}=e,r=u.useMemo(()=>_E(t),[t]),[s,a]=u.useState(`template:${t}`),l=u.useMemo(()=>r.find(S=>`${S.type}:${S.identifier}`===s)??r[0],[r,s]),d=rE({type:l.type,identifier:l.identifier}),{reload:c}=d,[p,f]=u.useState(null),[b,g]=u.useState(""),[m,h]=u.useState(""),[v,y]=u.useState(!1),_=u.useRef(null);u.useEffect(()=>{c()},[c]),u.useEffect(()=>{f(null),g(""),h("")},[s]);const w=u.useCallback(async S=>{if(f(S),!S.editable){g("");return}y(!0);const C=await d.read(S.path);y(!1),g(C??"")},[d]),k=u.useCallback(async()=>{const S=p?.path??m.trim();if(!S)return;y(!0);const C=await d.save(S,b);y(!1),C&&!p&&(h(""),f({path:S,name:S.split("/").pop()??S,extension:(S.split(".").pop()??"").toLowerCase(),size:b.length,modified_at:new Date().toISOString(),editable:!0,loaded:!0}))},[d,p,m,b]),x=u.useCallback(async()=>{if(!p||typeof window<"u"&&!window.confirm(n("layout_editor.custom_assets.delete_confirm")))return;y(!0);const S=await d.remove(p.path);y(!1),S&&(f(null),g(""))},[d,p,n]),$=u.useCallback(async S=>{const C=S.target.files?.[0];C&&(y(!0),await d.upload(C),y(!1),_.current&&(_.current.value=""))},[d]);return i.jsxs("div",{className:"g7le-custom-assets",style:iE,"data-testid":"g7le-custom-assets-modal",children:[i.jsxs("div",{style:sE,children:[i.jsxs("span",{children:["🎨 ",n("layout_editor.custom_assets.title")]}),i.jsx("select",{value:s,onChange:S=>a(S.target.value),style:mE,"aria-label":n("layout_editor.custom_assets.target_label"),"data-testid":"g7le-custom-assets-target",children:r.map(S=>i.jsxs("option",{value:`${S.type}:${S.identifier}`,children:[n(`layout_editor.custom_assets.type_${S.type}`)," · ",S.label]},`${S.type}:${S.identifier}`))}),i.jsx("button",{type:"button",style:aE,onClick:o,"aria-label":n("layout_editor.custom_assets.close"),"data-testid":"g7le-custom-assets-close",children:"✕"})]}),d.forbidden?i.jsx("div",{style:pE,"data-testid":"g7le-custom-assets-forbidden",children:n("layout_editor.custom_assets.forbidden")}):i.jsxs("div",{style:lE,children:[i.jsxs("div",{style:dE,"data-testid":"g7le-custom-assets-list",children:[d.isLoading&&d.files.length===0?i.jsx("div",{style:{padding:12,color:"#94a3b8",fontSize:12},children:n("layout_editor.custom_assets.loading")}):null,!d.isLoading&&d.files.length===0?i.jsx("div",{style:{padding:12,color:"#94a3b8",fontSize:12},children:n("layout_editor.custom_assets.empty")}):null,d.files.map(S=>i.jsxs("button",{type:"button",style:p?.path===S.path?uE:ip,onClick:()=>{w(S)},"data-testid":`g7le-custom-asset-row-${S.path}`,"data-loaded":S.loaded?"true":"false",children:[i.jsx("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:S.path}),i.jsx("span",{style:{color:"#94a3b8",fontSize:11},children:xE(S.size)})]},S.path))]}),i.jsxs("div",{style:cE,children:[d.error?i.jsx("div",{style:fE,"data-testid":"g7le-custom-assets-error",children:d.error}):null,i.jsxs("div",{style:sp,children:[i.jsx("input",{type:"text",value:p?p.path:m,readOnly:!!p,onChange:S=>h(S.target.value),placeholder:n("layout_editor.custom_assets.new_path_placeholder"),style:bE,"aria-label":n("layout_editor.custom_assets.path_label"),"data-testid":"g7le-custom-assets-path"}),p?i.jsx("button",{type:"button",style:io,onClick:()=>{f(null),g("")},"data-testid":"g7le-custom-assets-new",children:n("layout_editor.custom_assets.new_file")}):null]}),p&&!p.editable?i.jsx("div",{style:{color:"#64748b",fontSize:12,lineHeight:1.7},children:n("layout_editor.custom_assets.binary_hint",{extension:p.extension})}):i.jsx("textarea",{value:b,onChange:S=>g(S.target.value),style:gE,spellCheck:!1,"aria-label":n("layout_editor.custom_assets.content_label"),"data-testid":"g7le-custom-assets-content"}),i.jsxs("div",{style:sp,children:[i.jsx("button",{type:"button",style:hE,disabled:v||(p?!p.editable:m.trim()===""),onClick:()=>{k()},"data-testid":"g7le-custom-assets-save",children:n("layout_editor.custom_assets.save")}),i.jsx("button",{type:"button",style:io,disabled:v,onClick:()=>_.current?.click(),"data-testid":"g7le-custom-assets-upload",children:n("layout_editor.custom_assets.upload")}),i.jsx("input",{ref:_,type:"file",style:{display:"none"},onChange:S=>{$(S)},"data-testid":"g7le-custom-assets-file-input"}),i.jsx("button",{type:"button",style:yE,disabled:v||!p,onClick:()=>{x()},"data-testid":"g7le-custom-assets-delete",children:n("layout_editor.custom_assets.delete")}),i.jsx("span",{style:{color:"#94a3b8",fontSize:11},children:n("layout_editor.custom_assets.apply_hint")})]})]})]})]})}const ap=[{id:"copy",group:"clipboard",combos:[{key:"c",mod:!0}],labelKey:"layout_editor.shortcuts.action.copy",requiresSelection:!0},{id:"cut",group:"clipboard",combos:[{key:"x",mod:!0}],labelKey:"layout_editor.shortcuts.action.cut",requiresSelection:!0},{id:"paste",group:"clipboard",combos:[{key:"v",mod:!0}],labelKey:"layout_editor.shortcuts.action.paste"},{id:"openProps",group:"element",combos:[{key:"enter"}],labelKey:"layout_editor.shortcuts.action.open_props",requiresSelection:!0},{id:"delete",group:"element",combos:[{key:"delete"},{key:"backspace"}],labelKey:"layout_editor.shortcuts.action.delete",requiresSelection:!0},{id:"selectParent",group:"element",combos:[{key:"arrowup"}],labelKey:"layout_editor.shortcuts.action.select_parent",requiresSelection:!0},{id:"deselect",group:"element",combos:[{key:"escape"}],labelKey:"layout_editor.shortcuts.action.deselect"},{id:"addElement",group:"element",combos:[{key:"/",mod:!0}],labelKey:"layout_editor.shortcuts.action.add_element"},{id:"undo",group:"history",combos:[{key:"z",mod:!0}],labelKey:"layout_editor.shortcuts.action.undo"},{id:"redo",group:"history",combos:[{key:"z",mod:!0,shift:!0},{key:"y",mod:!0}],labelKey:"layout_editor.shortcuts.action.redo"},{id:"editCode",group:"view",combos:[{key:"e",mod:!0}],labelKey:"layout_editor.shortcuts.action.edit_code"},{id:"preview",group:"view",combos:[{key:"p",mod:!0}],labelKey:"layout_editor.shortcuts.action.preview"},{id:"translations",group:"view",combos:[{key:"l",mod:!0}],labelKey:"layout_editor.shortcuts.action.translations"},{id:"help",group:"view",combos:[{key:"?"}],labelKey:"layout_editor.shortcuts.action.help"},{id:"reset",group:"document",combos:[{key:"r",mod:!0,shift:!0}],labelKey:"layout_editor.shortcuts.action.reset"},{id:"save",group:"document",combos:[{key:"s",mod:!0}],labelKey:"layout_editor.shortcuts.action.save"},{id:"exit",group:"document",combos:[{key:"escape"}],labelKey:"layout_editor.shortcuts.action.exit"}];function kE(e){return{key:(e.key||"").toLowerCase(),mod:e.ctrlKey||e.metaKey,shift:e.shiftKey,alt:e.altKey}}function SE(e,t){return e.key===t.key&&!!e.mod==!!t.mod&&!!e.shift==!!t.shift&&!!e.alt==!!t.alt}function CE(e){for(const t of ap)if(t.combos.some(n=>SE(n,e)))return t;return null}function $E(e,t){const n=[];return e.mod&&n.push(t?"⌘":"Ctrl"),e.shift&&n.push(t?"⇧":"Shift"),e.alt&&n.push(t?"⌥":"Alt"),n.push(EE(e.key)),n.join(" + ")}function EE(e){return{arrowup:"↑",arrowdown:"↓",arrowleft:"←",arrowright:"→",enter:"Enter",escape:"Esc",delete:"Delete",backspace:"Backspace"," ":"Space"}[e]??(e.length===1?e.toUpperCase():e)}const IE=["clipboard","element","history","view","document"],AE={clipboard:"layout_editor.shortcuts.group.clipboard",element:"layout_editor.shortcuts.group.element",history:"layout_editor.shortcuts.group.history",view:"layout_editor.shortcuts.group.view",document:"layout_editor.shortcuts.group.document"};function TE(){return typeof navigator>"u"?!1:/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent||"")}function DE({t:e,onClose:t,isMac:n}){const o=n??TE(),r=u.useMemo(()=>{const s=new Map;for(const a of ap){const l=s.get(a.group)??[];l.push(a),s.set(a.group,l)}return s},[]);return i.jsxs("div",{className:"g7le-shortcut-help","data-testid":"g7le-shortcut-help",style:zE,children:[i.jsxs("div",{style:NE,children:[i.jsx("span",{style:ME,children:e("layout_editor.shortcuts.title")}),i.jsx("button",{type:"button","data-testid":"g7le-shortcut-help-close",onClick:t,"aria-label":e("layout_editor.shortcuts.close"),style:LE,children:"✕"})]}),i.jsx("div",{style:PE,children:IE.map(s=>{const a=r.get(s);return!a||a.length===0?null:i.jsxs("div",{style:OE,"data-testid":`g7le-shortcut-group-${s}`,children:[i.jsx("div",{style:BE,children:e(AE[s])}),i.jsx("table",{style:WE,children:i.jsx("tbody",{children:a.map(l=>i.jsxs("tr",{"data-testid":`g7le-shortcut-row-${l.id}`,children:[i.jsx("td",{style:jE,children:e(l.labelKey)}),i.jsx("td",{style:HE,children:l.combos.map((d,c)=>i.jsxs(u.Fragment,{children:[c>0&&i.jsx("span",{style:KE,children:e("layout_editor.shortcuts.or")}),i.jsx("kbd",{style:FE,children:$E(d,o)})]},c))})]},l.id))})})]},s)})}),i.jsx("div",{style:VE,children:e("layout_editor.shortcuts.footnote")})]})}const zE={display:"flex",flexDirection:"column",padding:20,gap:16,width:"100%",boxSizing:"border-box"},NE={display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:12,borderBottom:"1px solid #e2e8f0"},ME={fontSize:15,fontWeight:700,color:"#0f172a"},LE={width:28,height:28,border:"none",background:"transparent",color:"#64748b",cursor:"pointer",fontSize:14,borderRadius:6},PE={display:"grid",gridTemplateColumns:"1fr 1fr",columnGap:28,rowGap:18,alignItems:"start"},OE={display:"flex",flexDirection:"column",gap:6},BE={fontSize:12,fontWeight:700,color:"#2563eb"},WE={width:"100%",borderCollapse:"collapse"},jE={padding:"4px 0",fontSize:12.5,color:"#334155",textAlign:"left",whiteSpace:"nowrap",verticalAlign:"middle"},HE={padding:"4px 0",paddingLeft:12,textAlign:"right",verticalAlign:"middle"},FE={display:"inline-block",padding:"1px 6px",fontSize:11,fontFamily:"ui-monospace, monospace",color:"#0f172a",background:"#f1f5f9",border:"1px solid #cbd5e1",borderBottomWidth:2,borderRadius:5,whiteSpace:"nowrap"},KE={fontSize:11,color:"#94a3b8",margin:"0 4px"},VE={fontSize:11,color:"#94a3b8",paddingTop:12,borderTop:"1px solid #f1f5f9"};function UE(e){if(!e||!(e instanceof HTMLElement))return!1;const t=e.tagName;return!!(t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable)}function qE(){return typeof document>"u"?!1:!!document.querySelector(".g7le-modal-backdrop, .g7le-modal")}function lp(e){const{handlers:t,hasSelection:n,enabled:o=!0}=e;u.useEffect(()=>{if(!o||typeof window>"u")return;const r=s=>{if(UE(s.target))return;const a=kE(s),l=CE(a);if(!l||qE()||l.requiresSelection&&!n)return;if(l.key==="escape"||a.key==="escape"){if(n){const c=t.deselect;c&&(s.preventDefault(),c())}else{const c=t.exit;c&&(s.preventDefault(),c())}return}const d=t[l.id];d&&(s.preventDefault(),d())};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[t,n,o])}function GE(e){const{result:t,onDismiss:n,onLoadLatest:o,onKeepMyChanges:r}=e,{t:s}=tt();if(u.useEffect(()=>{if(!t||t.kind==="concurrent_modification"||t.kind==="validation_failed")return;const a=setTimeout(n,5e3);return()=>clearTimeout(a)},[t,n]),!t)return null;if(t.kind==="success")return i.jsx(Bo,{tone:"success",testId:"g7le-save-banner-success",onDismiss:n,children:s("layout_editor.save.success")});if(t.kind==="validation_failed"){const a=t.errors??{},l=Object.entries(a);return i.jsxs(Bo,{tone:"error",testId:"g7le-save-banner-validation",onDismiss:n,children:[i.jsx("strong",{children:s("layout_editor.save.validation_failed")}),l.length>0&&i.jsx("ul",{style:dp,"data-testid":"g7le-save-banner-validation-errors",children:l.map(([d,c])=>i.jsxs("li",{children:[i.jsx("code",{style:cp,children:d}),": ",c.join(", ")]},d))})]})}return t.kind==="blocked_inactive_extension"?i.jsxs(Bo,{tone:"warning",testId:"g7le-save-banner-blocked",onDismiss:n,children:[i.jsx("strong",{children:s("layout_editor.save.blocked_inactive_extension")}),t.blockedPaths.length>0&&i.jsx("ul",{style:dp,"data-testid":"g7le-save-banner-blocked-paths",children:t.blockedPaths.map(a=>i.jsx("li",{children:i.jsx("code",{style:cp,children:a})},a))})]}):t.kind==="network_error"?i.jsxs(Bo,{tone:"error",testId:"g7le-save-banner-network",onDismiss:n,children:[i.jsx("strong",{children:s("layout_editor.save.network_error_title")}),i.jsx("div",{style:{marginTop:4,fontSize:12},children:t.message})]}):t.kind==="guard_no_document"?i.jsx(Bo,{tone:"neutral",testId:"g7le-save-banner-guard-no-document",onDismiss:n,children:s("layout_editor.save.guard_no_document")}):i.jsx("div",{role:"dialog","aria-modal":"true","aria-label":s("layout_editor.save.concurrent.title"),"data-testid":"g7le-save-banner-concurrent",style:ZE,children:i.jsxs("div",{style:QE,children:[i.jsx("h2",{style:RE,children:s("layout_editor.save.concurrent.title")}),i.jsx("p",{style:e7,children:s("layout_editor.save.concurrent.message")}),i.jsx("div",{style:t7,children:s("layout_editor.save.concurrent.version_info",{current:String(t.currentVersion),yours:String(t.yourVersion)})}),i.jsxs("div",{style:n7,children:[i.jsx("button",{type:"button","data-testid":"g7le-save-banner-concurrent-load-latest",onClick:()=>{o?.(),n()},style:o7,children:s("layout_editor.save.concurrent.load_latest")}),i.jsx("button",{type:"button","data-testid":"g7le-save-banner-concurrent-keep-mine",onClick:()=>{r?.(),n()},style:r7,children:s("layout_editor.save.concurrent.view_my_changes")}),i.jsx("button",{type:"button","data-testid":"g7le-save-banner-concurrent-cancel",onClick:n,style:i7,children:s("layout_editor.save.concurrent.cancel")})]})]})})}function Bo(e){const{tone:t,testId:n,onDismiss:o,children:r}=e,s=YE[t];return i.jsxs("div",{role:"status","data-testid":n,style:{...XE,background:s.bg,borderColor:s.border,color:s.fg},children:[i.jsx("div",{style:{flex:1,minWidth:0},children:r}),i.jsx("button",{type:"button",onClick:o,"aria-label":"close","data-testid":`${n}-close`,style:JE,children:"×"})]})}const YE={success:{bg:"#dcfce7",border:"#86efac",fg:"#14532d"},error:{bg:"#fee2e2",border:"#fca5a5",fg:"#7f1d1d"},warning:{bg:"#fef3c7",border:"#fcd34d",fg:"#78350f"},neutral:{bg:"#f1f5f9",border:"#cbd5e1",fg:"#334155"}},XE={display:"flex",alignItems:"flex-start",gap:12,padding:"12px 16px",border:"1px solid",borderRadius:0,fontSize:13,lineHeight:1.5},JE={background:"transparent",border:"none",fontSize:18,cursor:"pointer",lineHeight:1,color:"inherit",padding:"0 4px",flexShrink:0},dp={margin:"8px 0 0",paddingLeft:20,fontSize:12},cp={background:"rgba(0, 0, 0, 0.06)",padding:"1px 4px",borderRadius:3,fontFamily:"monospace"},ZE={position:"fixed",inset:0,background:"rgba(15, 23, 42, 0.6)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e4},QE={background:"#fff",borderRadius:8,padding:24,width:"min(480px, 90vw)",boxShadow:"0 10px 25px rgba(0,0,0,0.15)"},RE={margin:"0 0 8px",fontSize:16,fontWeight:600,color:"#0f172a"},e7={margin:"0 0 12px",color:"#334155",fontSize:13,lineHeight:1.5},t7={marginBottom:16,padding:"8px 12px",background:"#f8fafc",borderRadius:6,fontSize:12,color:"#64748b",fontFamily:"monospace"},n7={display:"flex",gap:8,justifyContent:"flex-end"},o7={padding:"8px 14px",background:"#2563eb",color:"#fff",border:"none",borderRadius:6,fontSize:13,fontWeight:600,cursor:"pointer"},r7={padding:"8px 14px",background:"#fff",color:"#334155",border:"1px solid #cbd5e1",borderRadius:6,fontSize:13,fontWeight:500,cursor:"pointer"},i7={padding:"8px 14px",background:"transparent",color:"#64748b",border:"none",borderRadius:6,fontSize:13,cursor:"pointer"};function up(e){if(!e)return null;const n=new URLSearchParams(e).get("route");return n&&n.length>0?n:null}function ea(e,t,n){const o=`/admin/layout-editor/${encodeURIComponent(e)}`;if(!t||t.length===0)return o;if(t.startsWith("__")){let r=`${o}?edit=${encodeURIComponent(t)}`;return(t.startsWith("__modal__/")||t.startsWith("__iteration__/"))&&n&&(r+=`&host=${encodeURIComponent(n)}`),r}return`${o}?route=${encodeURIComponent(t)}`}function pp(e){if(!e)return null;const n=new URLSearchParams(e).get("host");return n&&n.length>0?n:null}function fp(e){if(!e)return null;const n=new URLSearchParams(e).get("edit");return n&&n.length>0&&n.startsWith("__")?n:null}function s7(e,t){const n=`/admin/templates/${encodeURIComponent(e)}/edit`;if(!t||t.length===0||t.startsWith("__"))return n;const o=t.replace(/^\*+/,"");return o.length===0?n:`${n}?route=${encodeURIComponent(o)}`}const a7="g7le-editor-route",l7=new Set;function ta(e){return e.path.startsWith("__group__/")||e.path.startsWith("__conngroup__/")}function gp(e,t){const{t:n,translationEngine:o,translationContext:r,templateIdentifier:s}=t,a=ta(e);if(!e.label.startsWith("$t:"))return e.label;const l=e.label.slice(3),d=l.indexOf("|"),c=d===-1?l:l.slice(0,d),p={};if(d!==-1)for(const b of l.slice(d+1).split("|")){const g=b.indexOf("=");g!==-1&&(p[b.slice(0,g)]=b.slice(g+1))}if((e.kind==="route"||e.kind==="modal")&&!a&&o&&r&&s!==r.templateId){const b={templateId:s,locale:r.locale},g=Object.keys(p).length>0?"|"+Object.entries(p).map(([h,v])=>`${h}=${v}`).join("|"):void 0,m=o.translate(c,b,g);if(m!==c)return m}const f=n(c,p);if(f===c&&typeof window<"u"){const b=window.G7Core?.t;if(typeof b=="function")try{const g=b(c,p);if(g!==c)return g}catch{}}if(f===c&&e.kind==="route"&&!a){const b=e.path;if(b&&b!=="/"){const g=b.split("/").filter(Boolean);return g[g.length-1]??b}return b==="/"?"/":c}return f}function d7(e){return e.trim().toLocaleLowerCase()}function hp(e,t){if(!t)return e;const n=e.toLocaleLowerCase(),o=[];let r=0,s=n.indexOf(t,r);if(s===-1)return e;let a=0;for(;s!==-1;)s>r&&o.push(e.slice(r,s)),o.push(i.jsx("mark",{className:"g7le-route-tree__highlight",style:{background:"#fde68a",color:"inherit",borderRadius:2,padding:"0 1px"},children:e.slice(s,s+t.length)},`m${a++}`)),r=s+t.length,s=n.indexOf(t,r);return r{const z=f.selectedRoute?.path??"";return z.startsWith("__extension__/")||z.startsWith("__modal__/")?z.slice(z.lastIndexOf("/")+1):null},[f.selectedRoute?.path]),h=u.useMemo(()=>!g||!m?!1:(e.children??[]).some(z=>z.kind==="extension"&&z.extensionId===m||z.kind==="modal"&&z.modalId===m),[g,m,e.children]),[v,y]=u.useState(!0);u.useEffect(()=>{h&&y(!1)},[h]);const _=f.editMode==="extension"?f.selectedRoute?.layoutName??null:null,w=e.kind==="extension"?bp(e,f.routeTree)??null:null,k=e.kind==="extension"&&o===e.path&&(_===null||w===null||_===w),x=f.editMode==="modal"&&o?.startsWith("__modal__/")?o.slice(o.lastIndexOf("/")+1):null,$=f.editMode==="modal"?f.selectedRoute?.layoutName??null:null,S=e.kind==="modal"&&!!x&&e.modalId===x&&($===null||e.modalHostLayout==null||$===e.modalHostLayout),C=e.kind!=="extension"&&e.kind!=="modal"&&o===e.path||k||S||e.kind==="route"&&!b&&r===e.path,E=(e.children?.length??0)>0&&(!g||l||!v),A=!b&&!!e.layoutName&&s.has(e.layoutName),N=b?void 0:e.kind==="extension"?e.extensionId?f.extensionVersions[e.extensionId]:void 0:e.layoutName?f.layoutVersions[e.layoutName]:void 0,D=()=>{if(g){y(z=>!z);return}b||n(e)},B=gp(e,{t:d,translationEngine:c,translationContext:p,templateIdentifier:f.templateIdentifier}),M=b?null:c7(e),O={paddingLeft:12+t*14,paddingRight:12,paddingTop:4,paddingBottom:4,opacity:e.isHidden?.55:1,cursor:g?"pointer":b?"default":"pointer",background:C?"#eff6ff":"transparent",borderLeft:C?"2px solid #2563eb":"2px solid transparent",fontWeight:b||C?600:400,fontSize:b?11:13,color:b?"#64748b":C?"#1d4ed8":"#1e293b",textTransform:b?"uppercase":"none",letterSpacing:b?.6:void 0,transition:"background-color 100ms, color 100ms",display:"flex",flexDirection:"column",alignItems:"stretch",gap:2,userSelect:"none"};return i.jsxs("li",{children:[i.jsxs("div",{"data-testid":b?"g7le-route-tree-group":"g7le-route-tree-item","data-route-path":e.path,"data-route-kind":e.kind,"data-conn-collapsed":g?l?"false":String(v):void 0,role:g||!b?"button":void 0,tabIndex:g||!b?0:void 0,"aria-expanded":g?l?!0:!v:void 0,onClick:D,onKeyDown:z=>{g&&(z.key==="Enter"||z.key===" ")?(z.preventDefault(),y(H=>!H)):!b&&(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),n(e))},style:O,children:[i.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[g&&i.jsx("span",{"aria-hidden":"true",style:{flex:"0 0 auto",fontSize:9,color:"#94a3b8",width:10,display:"inline-block"},children:l||!v?"▾":"▸"}),A&&i.jsx("span",{className:"g7le-route-tree__dirty-dot","data-testid":"g7le-route-tree-dirty",title:d("layout_editor.chrome.route_tree.badge.modified"),"aria-label":d("layout_editor.chrome.route_tree.badge.modified"),style:{width:7,height:7,borderRadius:"50%",background:"#f59e0b",flex:"0 0 auto"}}),b?B:hp(B,a),typeof N=="number"&&i.jsxs("span",{className:"g7le-route-tree__version-badge","data-testid":"g7le-route-tree-version",title:d("layout_editor.chrome.route_tree.badge.version_tooltip",{version:String(N)}),style:{flex:"0 0 auto",padding:"0 5px",fontSize:10,fontWeight:600,lineHeight:"16px",borderRadius:4,background:"#eef2ff",color:"#4f46e5",border:"1px solid #e0e7ff",letterSpacing:.2},children:["v",N]}),i.jsx(u7,{node:e})]}),M&&i.jsx("span",{className:"g7le-route-tree__layout-path","data-testid":"g7le-route-tree-layout-path",title:M,style:{fontSize:11,fontWeight:400,color:"#94a3b8",textTransform:"none",letterSpacing:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:hp(M,a)})]}),E&&i.jsx("ul",{style:{listStyle:"none",margin:0,padding:0},children:e.children.map(z=>i.jsx(yp,{node:z,depth:t+1,onSelect:n,selectedRoutePath:o,activeHostRoutePath:r,dirtyLayoutNames:s,query:a,forceExpand:l},z.path))})]})}function p7(e,t){if(!t||!t.startsWith("__"))return null;const n=t.startsWith("__modal__/"),o=t.startsWith("__extension__/");if(!n&&!o)return null;const r=t.slice(t.lastIndexOf("/")+1),s=a=>{for(const l of a){if(l.connectedHostRoutePath&&(n&&l.kind==="modal"&&l.modalId===r||o&&l.kind==="extension"&&l.extensionId===r))return l.connectedHostRoutePath;if(l.children&&l.children.length>0){const d=s(l.children);if(d)return d}}return null};return s(e)}function bp(e,t){if(e.connectedHostRoutePath){const n=mp(t,e.connectedHostRoutePath);if(n?.layoutName)return n.layoutName}if(e.extensionType==="overlay"&&e.extensionTargetName)return e.extensionTargetName}function mp(e,t){for(const n of e){if(n.kind==="route"&&n.path===t)return n;if(n.children&&n.children.length>0){const o=mp(n.children,t);if(o)return o}}return null}function vp(e,t,n){const o=[];for(const r of e){const s=ta(r),a=r.children&&r.children.length>0?vp(r.children,t,n):[];if(s){a.length>0&&o.push({...r,children:a});continue}const l=gp(r,n).toLocaleLowerCase(),d=r.path.toLocaleLowerCase();(l.includes(t)||!d.startsWith("__")&&d.includes(t)||a.length>0)&&o.push({...r,children:a})}return o}function f7(){const{t:e,translationEngine:t,translationContext:n}=tt(),{state:o,dispatch:r}=Qe(),a=Ft()?.dirtyLayoutNames??l7,[l,d]=u.useState(""),c=d7(l),p=u.useMemo(()=>c?vp(o.routeTree,c,{t:e,translationEngine:t,translationContext:n,templateIdentifier:o.templateIdentifier}):o.routeTree,[c,o.routeTree,o.templateIdentifier,e,t,n]),f=h=>{if(h.kind==="base"&&h.layoutName){r({type:"ENTER_BASE_EDIT",layoutName:h.layoutName});return}if(h.kind==="modal"&&h.modalId&&h.modalHostLayout){r({type:"ENTER_MODAL_EDIT",modalId:h.modalId,hostLayout:h.modalHostLayout});return}if(h.kind==="extension"&&h.extensionId){const v=bp(h,o.routeTree);r({type:"ENTER_EXTENSION_EDIT",extensionId:h.extensionId,extensionHost:v});return}if(r({type:"SELECT_ROUTE",route:{path:h.path,layoutName:h.layoutName}}),typeof window<"u"&&window.history?.pushState){const v=ea(o.templateIdentifier,h.path);`${window.location.pathname}${window.location.search}`!==v&&window.history.pushState({source:a7,routePath:h.path},"",v)}},b=o.selectedRoute?.path??null,g=u.useMemo(()=>p7(o.routeTree,b),[o.routeTree,b]);if(o.isRouteTreeCollapsed)return i.jsx("aside",{className:"g7le-route-tree g7le-route-tree--collapsed","data-testid":"g7le-route-tree-panel","data-collapsed":"true",style:{width:28,borderRight:"1px solid #e2e8f0",background:"#ffffff"}});const m=o.routeTree.length>0;return i.jsxs("aside",{className:"g7le-route-tree","data-testid":"g7le-route-tree-panel","data-collapsed":"false",style:{width:280,borderRight:"1px solid #e2e8f0",background:"#ffffff",position:"sticky",top:"var(--g7le-header-h, 0px)",alignSelf:"start",height:"calc(100vh - var(--g7le-header-h, 0px))",overflow:"hidden",minHeight:0,display:"flex",flexDirection:"column"},"aria-label":e("layout_editor.chrome.route_tree.panel_title"),children:[i.jsx("div",{className:"g7le-route-tree__title",style:{padding:"10px 14px",fontSize:12,fontWeight:600,color:"#475569",textTransform:"uppercase",letterSpacing:.6,borderBottom:"1px solid #e2e8f0",background:"#f8fafc",flex:"0 0 auto"},children:e("layout_editor.chrome.route_tree.panel_title")}),m&&i.jsxs("div",{className:"g7le-route-tree__search",style:{padding:"8px 10px",borderBottom:"1px solid #e2e8f0",background:"#ffffff",flex:"0 0 auto",position:"relative"},children:[i.jsx("input",{type:"text",className:"g7le-route-tree__search-input","data-testid":"g7le-route-tree-search",value:l,onChange:h=>d(h.target.value),placeholder:e("layout_editor.chrome.route_tree.search_placeholder"),"aria-label":e("layout_editor.chrome.route_tree.search_placeholder"),style:{width:"100%",boxSizing:"border-box",padding:l?"6px 26px 6px 10px":"6px 10px",fontSize:12,lineHeight:1.4,color:"#1e293b",border:"1px solid #cbd5e1",borderRadius:6,outline:"none",background:"#f8fafc"}}),l&&i.jsx("button",{type:"button",className:"g7le-route-tree__search-clear","data-testid":"g7le-route-tree-search-clear",onClick:()=>d(""),"aria-label":e("layout_editor.chrome.route_tree.search_clear"),title:e("layout_editor.chrome.route_tree.search_clear"),style:{position:"absolute",right:16,top:"50%",transform:"translateY(-50%)",width:18,height:18,display:"inline-flex",alignItems:"center",justifyContent:"center",border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:14,lineHeight:1,padding:0},children:"✕"})]}),!m&&i.jsx("div",{className:"g7le-route-tree__empty","data-testid":"g7le-route-tree-empty",style:{padding:16,fontSize:12,color:"#94a3b8",textAlign:"center"},children:e("layout_editor.chrome.route_tree.empty")}),m&&c&&p.length===0&&i.jsx("div",{className:"g7le-route-tree__no-results","data-testid":"g7le-route-tree-no-results",style:{padding:16,fontSize:12,color:"#94a3b8",textAlign:"center"},children:e("layout_editor.chrome.route_tree.search_no_results")}),m&&p.length>0&&i.jsx("nav",{className:"g7le-route-tree__scroll","data-testid":"g7le-route-tree-scroll",style:{flex:"1 1 auto",minHeight:0,overflowY:"auto"},children:i.jsx("ul",{style:{listStyle:"none",margin:0,padding:0},children:p.map(h=>i.jsx(yp,{node:h,depth:0,onSelect:f,selectedRoutePath:b,activeHostRoutePath:g,dirtyLayoutNames:a,query:c,forceExpand:!!c},h.path))})})]})}const g7=Lt().DynamicRenderer,na=Lt(),h7=na.ResponsiveProvider;na.useResponsive,na.ResponsiveContext;const y7=Lt().ActionDispatcher,_p=Lt(),b7=_p.DataSourceManager;_p.dataSourceManager;function Jr(e,t,n){const o=t??{},r=o.message||o.error||`HTTP ${e}`,s=o?.data?.required_permissions??o?.required_permissions;let a;return e===401?a="unauthorized":e===403?a="forbidden":e===404?a="not_found":e>=500?a="server_error":a="unknown",{kind:a,status:e,message:String(r),requiredPermissions:s?String(s):void 0,source:n}}function so(e,t){return{kind:"network",status:0,message:e instanceof Error?e.message:String(e??"Unknown network error"),source:t}}function xp(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.kind=="string"&&typeof t.status=="number"&&typeof t.message=="string"}function Re(e){if(!e)return[];const t=[],n=e.split(".");for(let o=0;o0&&(t.push({responsive:a}),o+=1);continue}const s=Number(r);Number.isFinite(s)&&Number.isInteger(s)&&s>=0&&t.push(s)}return t}function m7(e,t){if(!e)return{affordance:"none",targetPath:null};const n=v7(e);return n?_7(n)?{affordance:"dynamic_path",targetPath:n}:/^(https?:)?\/\//.test(n)?{affordance:"external_url",targetPath:n}:n.startsWith("/")?t?{affordance:t(n),targetPath:n}:{affordance:"route_not_in_tree",targetPath:n}:{affordance:"route_not_in_tree",targetPath:n}:{affordance:"none",targetPath:null}}function v7(e){const t=e.actions;if(Array.isArray(t)){for(const n of t)if(n&&typeof n=="object"&&n.handler==="navigate"){const o=n.params?.path;if(typeof o=="string"&&o.length>0)return o}}if(e.name==="A"||e.type==="A"){const n=e.props?.href;if(typeof n=="string"&&n.length>0)return n}return null}function _7(e){return/\{\{[\s\S]*?\}\}/.test(e)}function x7(e,t,n){const o=s=>!!(s?.iteration&&s.iteration.source!==void 0),r=s=>{if(!s)return s;const a=s.indexOf(".iteration."),l=s.indexOf(".sortable."),d=[a,l].filter(c=>c>=0).sort((c,p)=>c-p)[0];return d===void 0?s:s.slice(0,d)};return o(e)?{isIteration:!0,iterationSourcePath:r(n)}:n&&n.includes(".iteration.")?{isIteration:!0,iterationSourcePath:r(n)}:t.some(o)?{isIteration:!0,iterationSourcePath:r(n)}:{isIteration:!1,iterationSourcePath:null}}function w7(e,t){const n=a=>{const l=a?.iteration&&a.iteration.source;return typeof l=="string"&&l.length>0?l:null},o=n(e)??t.map(n).find(a=>a!==null)??null;if(o!==null){const a=S7(o);if(a!==null)return a}const r=[];if(typeof e.text=="string"&&r.push(...wp(e.text)),e.props&&typeof e.props=="object")for(const a of Object.values(e.props))typeof a=="string"&&r.push(...wp(a));return r.length===0?null:r.find(a=>!k7.has(a))??r[0]}const k7=new Set(["_local","_global","_computed","route","query","props","item","index","event","$event","$response","response"]);function wp(e){const t=[],n=/\{\{([\s\S]*?)\}\}/g;let o;for(;(o=n.exec(e))!==null;){const r=kp(o[1]);r!==null&&t.push(r)}return t}function S7(e){const t=e.replace(/\{\{|\}\}/g,"");return kp(t)}function kp(e){const t=/[A-Za-z_$][A-Za-z0-9_$]*/.exec(e.trim());return t?t[0]:null}function gn(e,t,n,o=[]){if(!e)return"none";if(id(e)||typeof e.slot=="string"||typeof e.__editorSlotName=="string")return"extension_point";if(t!=="route"&&Ri(e,t,n)){const s=e.__source?.kind;return s==="base"?"base":s==="partial"?"partial":s==="extension"?"extension":"base"}if(zb(e,o))return"data_bound";if(!Ri(e,t,n))return"none";const r=e.__source?.kind;return r==="base"?"base":r==="partial"?"partial":r==="extension"?"extension":"none"}function Sp(e){if(!e)return null;if(e.__source?.kind==="extension"&&typeof e.__source.extensionId=="number")return e.__source.extensionId;const t=e.__injectedProps;if(Array.isArray(t)&&t.length>0){const n=t[0]?.extensionId;if(typeof n=="number")return n}return null}function C7(e,t){if(t<=0)return e;const n=e.split(".");let o=0;const r=[];for(let s=0;s=t)break;r.push(a);continue}if(a==="iteration"||a==="sortable"){if(o>=t)break;r.push(a);continue}r.push(a);const l=n[s-1];if((l===void 0||l==="children")&&(o+=1),o>=t)break}return r.join(".")}function Cp(e,t,n,o){if(!e||!t)return t;const r=n(t),s=Lb(e,r,o);return s.length===r.length?t:C7(t,s.length)}function $p(e){return e==="none"||e==="data_bound"}function $7(e){const{rootNode:t,editMode:n,currentExtensionId:o,editableRootPath:r,pathParser:s=Re,resolveRouteMatch:a}=e,[l,d]=u.useState(null),[c,p]=u.useState(null),f=u.useCallback(_=>{if(_===null||n==="route")return!0;if(n==="iteration_item"||n==="modal"){if(!r||r.length===0)return!0;const $=s(_);return Ep($,r)}const w=oa(t,_,s);if(!w)return!0;const k=ra(t,_,s),x=gn(w,n,o,k);return x==="none"||x==="data_bound"},[t,s,n,o,r]),b=u.useCallback((_,w)=>{const x=(w?.currentTarget?.dataset??w?.dataset)?.editorPath??null,$=Cp(t,x,s,o);f($)&&d($)},[t,s,o,f]),g=u.useCallback((_,w)=>{if(_===null){p(null);return}const x=(w?.currentTarget?.dataset??w?.dataset)?.editorPath??null,$=Cp(t,x,s,o);if(!f($)){p(null);return}p($)},[t,s,o,f]),m=u.useCallback(()=>{d(null)},[]),h=u.useMemo(()=>{const _=oa(t,l,s),w=oa(t,c,s),k=_?ra(t,l,s):[];let x=gn(_,n,o,k);(n==="iteration_item"||n==="modal")&&l!==null&&_&&r&&r.length>0&&Ep(s(l),r)&&(sd(_)?x="data_bound":x==="data_bound"&&(x="none"));const{affordance:$,targetPath:S}=m7(_,a),C=x==="base"&&typeof _?.__source?.layout=="string"?_.__source.layout:null,T=x==="data_bound"&&_?w7(_,k):null,{isIteration:E,iterationSourcePath:A}=x==="data_bound"&&_?x7(_,k,l):{isIteration:!1,iterationSourcePath:null};return{selectedNode:_,hoverNode:w,selectedLockKind:x,selectedNavAffordance:$,selectedNavTargetPath:S,selectedBaseLayout:C,selectedDataSourceId:T,selectedIsIteration:E,selectedIterationSourcePath:A}},[t,l,c,n,o,r,s,a]),v=u.useRef(void 0);v.current!==l&&(v.current=l,Al({op:l===null?"clear":"select",componentPath:l,componentName:Ip(h.selectedNode),lockKind:h.selectedLockKind,navAffordance:h.selectedNavAffordance,sourceExtensionId:Sp(h.selectedNode),timestamp:Date.now()}));const y=u.useRef(void 0);return y.current!==c&&(y.current=c,c!==null&&Al({op:"hover",componentPath:c,componentName:Ip(h.hoverNode),lockKind:gn(h.hoverNode,n,o,ra(t,c,s)),navAffordance:"none",sourceExtensionId:Sp(h.hoverNode),timestamp:Date.now()})),{selectedPath:l,hoverPath:c,...h,handleSelect:b,handleHover:g,clearSelection:m}}function oa(e,t,n){if(!e||!t)return null;const o=n(t);return Be(e,o)}function Ep(e,t){if(e.length0?e.name:typeof e.type=="string"&&e.type.length>0?e.type:null:null}let Ap=0;function Tp(){return Ap}function ia(){Ap+=1}function E7(e){if(typeof e!="string")return null;const t="__modal__/";if(!e.startsWith(t))return null;const n=e.slice(t.length);return n===""||n.includes("/")?null:n}function I7(e){if(typeof e!="string")return null;const t="__iteration__/";if(!e.startsWith(t))return null;const n=e.slice(t.length);return n!==""?n:null}function Dp(){const{state:e}=Qe(),t=e.templateIdentifier,n=e.selectedRoute?.layoutName??null,o=e.editMode,r=o==="modal"?E7(e.selectedRoute?.path):null,s=o==="iteration_item"?I7(e.selectedRoute?.path):null,[a,l]=u.useState(null),[d,c]=u.useState(!1),[p,f]=u.useState(null),[b,g]=u.useState(!1),[m,h]=u.useState(0),[v,y]=u.useState(0),_=u.useRef(new Map),[w,k]=u.useState(()=>new Set),x=u.useCallback((P,I)=>`${P}|${I??""}`,[]),$=u.useRef(null);u.useEffect(()=>{$.current=a},[a]);const S=u.useCallback((P,I)=>{const L=x(o,n);_.current.set(L,{raw:P,lockVersion:I}),k(F=>{if(F.has(L))return F;const Y=new Set(F);return Y.add(L),Y})},[x,o,n]),C=u.useCallback(P=>{_.current.delete(P),k(I=>{if(!I.has(P))return I;const L=new Set(I);return L.delete(P),L})},[]),T=u.useCallback(P=>{const I=`|${P??""}`,L=[];for(const F of _.current.keys())F.endsWith(I)&&L.push(F);for(const F of L)_.current.delete(F);L.length>0&&k(F=>{let Y=!1;const K=new Set(F);for(const X of L)K.delete(X)&&(Y=!0);return Y?K:F})},[]),E=u.useCallback(async()=>{if(!n){l(null),f(null),g(!1);return}const P=x(o,n),I=_.current.get(P);if(I){l({layoutName:n,raw:I.raw,lockVersion:I.lockVersion}),g(!0),f(null),c(!1),st({op:"load",layoutName:n,editMode:o,statusCode:0,isDirty:!0,timestamp:Date.now()});return}c(!0),f(null);try{const L=window.G7Config?.cache_version??0,F=en(`/api/layouts/${encodeURIComponent(t)}/${n}`,"json",`${L}.${Tp()}`,"with_source_meta=1"),Y=cr(),K={Accept:"application/json"};Y&&(K.Authorization=`Bearer ${Y}`);const X=await fetch(F,{headers:K,credentials:"same-origin"}),Z=await X.json().catch(()=>null);if(!X.ok){f(Jr(X.status,Z,"layout")),l(null),g(!1);return}const se=(Z&&(Z.data||Z))??{},oe=typeof se.lock_version=="number"?se.lock_version:0;if(o==="modal"&&r){const ee=se,ge=Array.isArray(ee.modals)?ee.modals:[],V=ge.findIndex(te=>te&&(te.id===r||te.modal_id===r));if(V>=0){const te=ge[V],be={...te,props:{...te.props??{},isOpen:!0}},De=[...Array.isArray(ee.components)?ee.components:[],be],Se=[De.length-1];l({layoutName:n,raw:{...ee,components:De},lockVersion:oe,modalContext:{modalId:r,modalIndex:V,hostRaw:ee,originalModalNode:te,editIndexPath:Se}}),g(!1),st({op:"load",layoutName:n,editMode:o,statusCode:X.status,timestamp:Date.now()});return}}if(o==="iteration_item"&&s){const ee=se,ge=Re(s),V={children:ee.components??[]},te=Be(V,ge);if(te&&Array.isArray(te.children)){l({layoutName:n,raw:ee,lockVersion:oe,iterationContext:{sourcePath:s,sourceIndexPath:ge,hostRaw:ee}}),g(!1),st({op:"load",layoutName:n,editMode:o,statusCode:X.status,timestamp:Date.now()});return}}l({layoutName:n,raw:se,lockVersion:oe}),g(!1),st({op:"load",layoutName:n,editMode:o,statusCode:X.status,timestamp:Date.now()})}catch(L){f(so(L,"layout")),l(null),g(!1)}finally{c(!1)}},[t,n,o,r,s,x]);u.useEffect(()=>{E()},[E]);const A=u.useCallback(async()=>{C(x(o,n)),ia(),y(P=>P+1),await E()},[C,x,o,n,E]),N=u.useCallback(()=>{C(x(o,n))},[C,x,o,n]),D=u.useCallback(P=>{l(I=>{if(!I)return I;const L=I.raw.components??[],F=P(L),Y={...I.raw,components:F};return S(Y,I.lockVersion),{...I,raw:Y}}),g(!0),st({op:"patch",layoutName:n,editMode:o,isDirty:!0,timestamp:Date.now()})},[n,o,S]),B=u.useCallback(()=>{g(!0),st({op:"patch",layoutName:n,editMode:o,isDirty:!0,timestamp:Date.now()})},[n,o]),M=u.useCallback(P=>{l(I=>{if(!I)return I;const L={...I.raw,components:P};return S(L,I.lockVersion),{...I,raw:L}}),g(!0),st({op:"patch",layoutName:n,editMode:o,isDirty:!0,timestamp:Date.now()})},[n,o,S]),O=u.useCallback((P,I,...L)=>{const F=L.length>=1?L[0]:I;l(Y=>{if(!Y)return Y;const K={...Y.raw,[P]:I},X=Y.raw.__editor;if(X&&typeof X=="object"&&!Array.isArray(X)){const Z=X,se=Z.original;se&&typeof se=="object"&&!Array.isArray(se)&&(K.__editor={...Z,original:{...se,[P]:F}})}return S(K,Y.lockVersion),{...Y,raw:K}}),g(!0),st({op:"patch",layoutName:n,editMode:o,isDirty:!0,timestamp:Date.now()})},[n,o,S]),z=u.useCallback(async P=>{const I=$.current;if(!I)return st({op:"save_guard_result",layoutName:n,editMode:o,guardBlocked:!1,timestamp:Date.now()}),{kind:"guard_no_document"};if(P?.resolveActiveExtensions&&P.sessionAddedPaths?.length)try{const ge=await P.resolveActiveExtensions(),V=A7(I.raw.components,P.sessionAddedPaths,ge);if(V.length>0)return st({op:"save_guard_result",layoutName:n,editMode:o,guardBlocked:!0,guardBlockedPaths:V,timestamp:Date.now()}),{kind:"blocked_inactive_extension",blockedPaths:V}}catch{}if(Yb())try{await Xb(t)}catch{}const L=`/api/admin/templates/${encodeURIComponent(t)}/layouts/${I.layoutName}`,F=cr(),Y={Accept:"application/json","Content-Type":"application/json"};F&&(Y.Authorization=`Bearer ${F}`);const K=!!I.modalContext,X=!!I.iterationContext,Z=K||X?"host_layout_modal_patch":"layout";st({op:"save",layoutName:I.layoutName,editMode:o,saveTarget:Z,endpoint:L,isDirty:b,timestamp:Date.now()});let se;if(K&&I.modalContext){const{modalIndex:ge,hostRaw:V,originalModalNode:te,editIndexPath:be}=I.modalContext,Ee=Array.isArray(V.modals)?[...V.modals]:[],De=Array.isArray(I.raw.components)?I.raw.components:[],Se=be&&be.length===1?be[0]:0,Ue=De.length>Se?De[Se]:void 0,Me=Ue?Vn([Ue]):[],Oe=Me.length>0?{...Me[0]}:void 0;if(ge>=0&&ge({...ze,children:De})).children??[];se={...Se,components:Ye}}else se=_o(I.raw);const oe=se;let G;try{G=await fetch(L,{method:"PUT",headers:Y,credentials:"same-origin",body:JSON.stringify({content:JSON.stringify(oe),expected_lock_version:I.lockVersion})})}catch(ge){const V=ge instanceof Error?ge.message:"network error";return st({op:"save_response",layoutName:I.layoutName,editMode:o,endpoint:L,statusCode:0,timestamp:Date.now()}),{kind:"network_error",message:V}}const ee=await G.json().catch(()=>null);if(st({op:"save_response",layoutName:I.layoutName,editMode:o,endpoint:L,statusCode:G.status,conflict:G.status===409?{currentVersion:ee?.current_version,yourVersion:ee?.your_version}:void 0,timestamp:Date.now()}),G.ok){const ge=typeof ee?.data?.lock_version=="number"?ee.data.lock_version:I.lockVersion+1;l({...I,lockVersion:ge}),g(!1),C(x(o,I.layoutName)),T(I.layoutName),ia(),h(te=>te+1);const V=typeof ee?.data?.current_version=="number"?ee.data.current_version:void 0;return{kind:"success",newLockVersion:ge,newContentVersion:V,savedLayoutName:I.layoutName}}return G.status===409?{kind:"concurrent_modification",currentVersion:ee?.current_version??-1,yourVersion:ee?.your_version??I.lockVersion}:G.status===422?{kind:"validation_failed",status:422,errors:ee?.errors??null}:{kind:"network_error",message:ee?.message??`HTTP ${G.status}`}},[t,n,o,b,C,T,x,r,s]),H=u.useMemo(()=>{const P=new Set,I="route|";for(const L of w)if(L.startsWith(I)){const F=L.slice(I.length);F&&P.add(F)}return P},[w]);return{document:a,isLoading:d,error:p,isDirty:b,saveSuccessCounter:m,reloadCounter:v,dirtyKeys:w,dirtyLayoutNames:H,invalidateCurrentCache:N,reload:A,patchLayout:D,setLayoutComponents:M,patchDocumentRaw:O,save:z,markDirty:B}}function A7(e,t,n){if(!e||e.length===0)return[];const o=[],r=new Set([...n.moduleIds,...n.pluginIds]);for(const s of t){const a=T7(e,s);if(!a)continue;const l=a.__source;if(!l||l.kind!=="extension")continue;const d=String(l.extensionId??"");d.length!==0&&(r.has(d)||o.push(s))}return o}function T7(e,t){const n=Re(t);return n.length===0?null:Be({children:e},n)}function ao(e,t){if(!e)return null;const n=e.getBoundingClientRect();if(n.width===0&&n.height===0)return null;if(!t)return{left:n.left,top:n.top,width:n.width,height:n.height,scale:1};const o=t.getBoundingClientRect();return{left:n.left-o.left,top:n.top-o.top,width:n.width,height:n.height,scale:1}}function lo(e,t){if(!e)return!1;if(!t)return!0;const n=t.getBoundingClientRect(),o=1;return!(e.left>=n.width-o||e.left+e.width<=o||e.top>=n.height-o||e.top+e.height<=o)}function zp(e,t){if(typeof window>"u")return()=>{};const n=()=>{e()};window.addEventListener("scroll",n,!0),window.addEventListener("resize",n);let o=null;t&&typeof ResizeObserver<"u"&&(o=new ResizeObserver(()=>e()),o.observe(t));let r=null,s=null;const a=typeof requestAnimationFrame<"u",l=()=>{if(!a){e();return}s===null&&(s=requestAnimationFrame(()=>{s=null,e()}))};return t&&typeof MutationObserver<"u"&&(r=new MutationObserver(l),r.observe(t,{childList:!0,subtree:!0})),()=>{window.removeEventListener("scroll",n,!0),window.removeEventListener("resize",n),o&&(o.disconnect(),o=null),r&&(r.disconnect(),r=null),s!==null&&a&&typeof cancelAnimationFrame<"u"&&(cancelAnimationFrame(s),s=null)}}const Np=44;function Mp(e){if(!e)return"inside";const t=e.scale||1,n=e.width*t,o=e.height*t;return n"u"||typeof window.getComputedStyle!="function")return{kind:"unknown",display:"",flexDirection:"",flexWrap:""};let t=e,n=(window.getComputedStyle(t).display??"").toLowerCase();for(;n==="contents"&&t.parentElement;)t=t.parentElement,n=(window.getComputedStyle(t).display??"").toLowerCase();const o=window.getComputedStyle(t),r=(o.display??"").toLowerCase(),s=(o.flexDirection??"").toLowerCase(),a=(o.flexWrap??"").toLowerCase(),l=r==="flex"||r==="inline-flex";if(r==="grid"||r==="inline-grid"){const f=Array.from(e.children).filter(h=>h.offsetParent!==null||h.getClientRects().length>0);if(f.length<=1)return{kind:"grid_2d",display:r,flexDirection:s,flexWrap:a};const b=f.map(h=>h.getBoundingClientRect()),g=new Set(b.map(h=>Math.round(h.top))),m=new Set(b.map(h=>Math.round(h.left)));return g.size===1?{kind:"grid_single_row",display:r,flexDirection:s,flexWrap:a}:m.size===1?{kind:"grid_single_column",display:r,flexDirection:s,flexWrap:a}:{kind:"grid_2d",display:r,flexDirection:s,flexWrap:a}}if(!l)return{kind:"block",display:r,flexDirection:s,flexWrap:a};const c=a==="wrap"||a==="wrap-reverse";return s==="column"||s==="column-reverse"?{kind:c?"flex_column_wrap":"flex_column_single",display:r,flexDirection:s,flexWrap:a}:{kind:c?"flex_row_wrap":"flex_row_single",display:r,flexDirection:s,flexWrap:a}}function z7(e){const{parentEl:t,selectedPath:n,selectedEl:o,explicitFlow:r}=e;return u.useMemo(()=>{if(!n||n.length===0)return{points:[],flow:"unknown"};const s=r??Op(t).kind,a=n.slice(0,-1),l=n[n.length-1]??0;if((s==="flex_row_wrap"||s==="flex_column_wrap"||s==="grid_2d")&&!!o){const p=N7(s,o,a,l);if(p)return{points:p,flow:s}}return{points:M7(s,a,l),flow:s}},[t,n,o,r])}function N7(e,t,n,o){let r=t.parentElement;for(;r&&Bp(r)==="contents";)r=r.parentElement;if(!r)return null;const s=[];if(Wp(r,s),s.length===0)return null;const a=t.getBoundingClientRect(),l=a.top+a.height/2,d=[],c=[],p=[];for(const v of s){const y=v.rect,_=y.top+y.height/2,w=Math.min(a.bottom,y.bottom)-Math.max(a.top,y.top),k=Math.min(a.height,y.height)||1;w/k>.4?d.push({rect:y,path:v.path}):_v.rect.left-y.rect.left),c.sort((v,y)=>v.rect.top-y.rect.top),p.sort((v,y)=>v.rect.top-y.rect.top);const f=d.findIndex(v=>Math.abs(v.rect.left-a.left)<1&&Math.abs(v.rect.top-a.top)<1),b={direction:"above",disabled:!0,insertion:null},g={direction:"below",disabled:!0,insertion:null},m={direction:"left",disabled:!0,insertion:null},h={direction:"right",disabled:!0,insertion:null};if(f>0){const v=d[f-1],y=Qr(v.path);y&&(m.disabled=!1,m.insertion=y)}else if(d.length>0){const v=d[0],y=Zr(v.path);y&&(m.disabled=!1,m.insertion=y)}if(f>=0&&f0){const v=d[d.length-1],y=Qr(v.path);y&&(h.disabled=!1,h.insertion=y)}if(c.length>0){const v=c[c.length-1],y=Qr(v.path);y&&(b.disabled=!1,b.insertion=y)}else if(s.length>0){const v=s[0],y=Zr(v.path);y&&(b.disabled=!1,b.insertion=y)}if(p.length>0){const v=p[0],y=Zr(v.path);y&&(g.disabled=!1,g.insertion=y)}else if(s.length>0){const v=s[s.length-1],y=Qr(v.path);y&&(g.disabled=!1,g.insertion=y)}else g.disabled=!1,g.insertion={parentPath:n,index:o+1};return b.disabled&&g.disabled&&m.disabled&&h.disabled?null:[b,g,m,h]}function Bp(e){return typeof window>"u"?"":(window.getComputedStyle(e).display??"").toLowerCase()}function Wp(e,t){const n=Array.from(e.children);for(const o of n){if(Bp(o)==="contents"){Wp(o,t);continue}const s=o.getAttribute("data-editor-path");if(s&&/\.iteration\.\d+(?:$|\.)/.test(s)||!s)continue;const a=o.getBoundingClientRect();a.width===0&&a.height===0||t.push({el:o,rect:a,path:Re(s)})}}function Zr(e){if(!e||e.length===0)return null;const t=e[e.length-1];return typeof t!="number"?null:{parentPath:e.slice(0,-1),index:t}}function Qr(e){if(!e||e.length===0)return null;const t=e[e.length-1];return typeof t!="number"?null:{parentPath:e.slice(0,-1),index:t+1}}function M7(e,t,n){const o={direction:"above",disabled:!0,insertion:null},r={direction:"below",disabled:!0,insertion:null},s={direction:"left",disabled:!0,insertion:null},a={direction:"right",disabled:!0,insertion:null},l=d=>({parentPath:t,index:d});switch(e){case"block":case"unknown":{o.disabled=!1,o.insertion=l(n),r.disabled=!1,r.insertion=l(n+1);break}case"flex_row_single":case"grid_single_row":{s.disabled=!1,s.insertion=l(n),a.disabled=!1,a.insertion=l(n+1);break}case"flex_column_single":case"grid_single_column":{o.disabled=!1,o.insertion=l(n),r.disabled=!1,r.insertion=l(n+1);break}case"flex_row_wrap":case"grid_2d":{s.disabled=!1,s.insertion=l(n),a.disabled=!1,a.insertion=l(n+1),o.disabled=!1,o.insertion=l(0),r.disabled=!1,r.insertion=l(-1);break}case"flex_column_wrap":{o.disabled=!1,o.insertion=l(n),r.disabled=!1,r.insertion=l(n+1),s.disabled=!1,s.insertion=l(0),a.disabled=!1,a.insertion=l(-1);break}}return[o,r,s,a]}function L7(e=50){const t=u.useRef([]),n=u.useRef(-1),[,o]=u.useState(0),r=()=>{o(p=>(p+1)%1e6)},s=(p,f)=>{const b=t.current.length,g=n.current;ey({op:p,actionKind:f?.actionKind,label:f?.label,stackSize:b,cursor:g,canUndo:g>0,canRedo:g>=0&&g{const b=t.current.slice(0,n.current+1);for(b.push(p);b.length>e;)b.shift();t.current=b,n.current=b.length-1,r(),s("push",p)},[e]),l=u.useCallback(()=>{if(n.current<=0)return null;n.current-=1,r();const p=t.current[n.current]??null;return s("undo",p??void 0),p},[]),d=u.useCallback(()=>{const p=n.current+1;if(p>=t.current.length)return null;n.current=p,r();const f=t.current[p]??null;return s("redo",f??void 0),f},[]),c=u.useCallback(()=>{t.current=[],n.current=-1,r(),s("clear")},[]);return{push:a,undo:l,redo:d,clear:c,canUndo:n.current>0,canRedo:n.current>=0&&n.current{if(!o||typeof window>"u")return;const r=s=>{if(P7(s.target)||!(s.ctrlKey||s.metaKey))return;const l=s.key.toLowerCase();if(l==="z"&&!s.shiftKey){s.preventDefault(),t();return}if(l==="z"&&s.shiftKey||l==="y"){s.preventDefault(),n();return}};return window.addEventListener("keydown",r),()=>{window.removeEventListener("keydown",r)}},[t,n,o])}const B7=20,jp=50,W7=90,Ln=120,j7=130,Hp=80,H7=9e3,Fp=1e4;function F7(e){const t=e<0?0:e>jp?jp:e;return B7+t}function K7(e){const{anchor:t,open:n,onClose:o,onEditProps:r,onDuplicate:s,onDelete:a,onSeparateBranch:l,separateBranchLabel:d,onMergeBranch:c,mergeBranchLabel:p}=e,{t:f}=tt(),[b,g]=u.useState(null);if(!n||!t)return null;const m=[{index:0,testid:"g7le-context-menu-edit-props",label:f("layout_editor.context_menu.edit_props"),onSelect:r},{index:1,testid:"g7le-context-menu-duplicate",label:f("layout_editor.context_menu.duplicate"),onSelect:s}];return l?m.push({index:m.length,testid:"g7le-context-menu-separate-branch",label:d??f("layout_editor.context_menu.separate_branch"),onSelect:l,hint:f("layout_editor.context_menu.separate_branch_hint")}):c&&m.push({index:m.length,testid:"g7le-context-menu-merge-branch",label:p??f("layout_editor.context_menu.merge_branch"),onSelect:c,hint:f("layout_editor.context_menu.merge_branch_hint")}),m.push({index:m.length,testid:"g7le-context-menu-delete",label:f("layout_editor.context_menu.delete"),onSelect:a,danger:!0}),i.jsx("div",{className:"g7le-context-menu","data-testid":"g7le-context-menu",role:"menu",style:{position:"absolute",left:t.left,top:t.top,background:"#fff",border:"1px solid #cbd5e1",borderRadius:6,boxShadow:"0 4px 12px rgba(0,0,0,0.15)",zIndex:1200,minWidth:160,padding:4,pointerEvents:"auto"},onMouseLeave:()=>{g(null),o()},children:m.map(h=>{const v=b===h.index,y=h.danger?"#dc2626":"#0f172a",_=h.danger?"#fee2e2":"#e0e7ff",w=h.danger?"#b91c1c":"#1d4ed8";return i.jsx("button",{type:"button",role:"menuitem","data-testid":h.testid,title:h.hint,onClick:k=>{k.stopPropagation(),h.onSelect(),g(null),o()},onMouseEnter:()=>g(h.index),onFocus:()=>g(h.index),style:{...V7,color:v?w:y,background:v?_:"transparent"},children:h.label},h.testid)})})}const V7={display:"block",width:"100%",textAlign:"left",padding:"6px 12px",border:"none",fontSize:13,cursor:"pointer",borderRadius:4,pointerEvents:"auto",transition:"background-color 120ms ease, color 120ms ease"};function U7(e){const{hoverBox:t,selectedBox:n,lockKind:o,navAffordance:r,onEditProps:s,onDuplicate:a,onDelete:l,onSeparateBranch:d,separateBranchLabel:c,onMergeBranch:p,mergeBranchLabel:f,definedDeviceBranches:b,onJumpToDevice:g,onLinkEditDestination:m,onEditBase:h,onEditExtension:v,extensionLabel:y,baseLayoutLabel:_,dataSourceLabel:w,branchLabel:k,onEditIteration:x,resizeEnabledAxes:$,onResizeHandlePointerDown:S,selectedName:C,onSelectParent:T}=e,{t:E}=tt(),[A,N]=u.useState(!1),D=$p(o),B=A&&D,M=Mp(n),O=M==="outside",z=O&&n?Pp(n):null,H=z?{left:z.right.left,top:z.above.top}:{right:-30,top:-30},P={top:-28,left:0},L=O&&!!C?{top:-50,left:0}:P,F=z?{top:z.below.top+28,left:0}:{top:"auto",bottom:-28},Y=z?{top:z.below.top+56,left:0}:{top:"auto",bottom:-56};return i.jsxs("div",{className:"g7le-element-overlay","data-testid":"g7le-element-overlay",style:{position:"absolute",inset:0,pointerEvents:"none"},children:[t&&i.jsx("div",{"data-testid":"g7le-overlay-hover",style:{position:"absolute",left:t.left,top:t.top,width:t.width,height:t.height,border:"1px dashed #2563eb",pointerEvents:"none"}}),n&&i.jsxs("div",{"data-testid":"g7le-overlay-selected","data-lock-kind":o,style:{position:"absolute",left:n.left,top:n.top,width:n.width,height:n.height,border:o==="none"?"2px solid #2563eb":"2px dashed #f59e0b",pointerEvents:"none"},children:[k?i.jsxs("span",{"data-testid":"g7le-overlay-branch-badge",style:G7,children:["📱 ",k]}):null,C&&(T?i.jsxs("button",{type:"button","data-testid":"g7le-overlay-type-label","data-placement":O?"outside":"inside",title:E("layout_editor.overlay.select_parent"),"aria-label":E("layout_editor.overlay.select_parent"),onClick:K=>{K.preventDefault(),K.stopPropagation(),T()},style:O?X7:Y7,children:[i.jsx("span",{"aria-hidden":!0,style:{marginRight:3,opacity:.85},children:"↑"}),C]}):i.jsx("span",{"data-testid":"g7le-overlay-type-label","data-placement":O?"outside":"inside",style:O?Vp:Kp,children:C})),D&&i.jsx("button",{type:"button","data-testid":"g7le-overlay-info-button","aria-label":"info",onClick:K=>{K.stopPropagation(),N(X=>!X)},"data-placement":M,style:{position:"absolute",...H,width:20,height:20,borderRadius:10,border:"1px solid #2563eb",background:"#fff",color:"#2563eb",fontSize:12,fontWeight:700,cursor:"pointer",pointerEvents:"auto",padding:0,lineHeight:"18px",zIndex:Ln},children:"ⓘ"}),o==="none"&&i.jsx(q7,{enabledAxes:$,onHandlePointerDown:S}),o==="base"&&h&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-edit-base",onClick:K=>{K.stopPropagation(),h()},style:{...Wo,...P},children:["🔒 ",E("layout_editor.overlay.edit_common_layout"),_?i.jsx("span",{"data-testid":"g7le-overlay-base-layout-label",style:aa,children:_}):null]}),o==="extension"&&v&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-edit-extension",onClick:K=>{K.stopPropagation(),v()},style:{...Wo,...P},children:["🔒 ",E("layout_editor.overlay.edit_extension"),y?i.jsx("span",{"data-testid":"g7le-overlay-extension-label",style:aa,children:y}):null]}),o==="data_bound"&&i.jsxs("span",{"data-testid":"g7le-overlay-data-bound-notice",style:{...Wo,...L,pointerEvents:"none",cursor:"default"},children:[E("layout_editor.overlay.locked_data_bound"),w?i.jsx("span",{"data-testid":"g7le-overlay-data-source-label",style:aa,children:w}):null]}),o==="data_bound"&&x&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-edit-iteration",onClick:K=>{K.stopPropagation(),x()},style:{...Wo,...F},children:["↳ ",E("layout_editor.overlay.edit_iteration_item")]}),r==="route_in_tree"&&i.jsx("button",{type:"button","data-testid":"g7le-overlay-link-edit-destination",onClick:K=>{K.stopPropagation(),m()},style:{...Wo,...F},children:E("layout_editor.overlay.edit_destination_route")}),(d||p||g&&(b??[]).length>0)&&i.jsxs("div",{"data-testid":"g7le-overlay-branch-affordances",style:{position:"absolute",...Y,display:"flex",flexDirection:"column",alignItems:"flex-start",gap:4,pointerEvents:"none"},children:[g&&(b??[]).map(K=>i.jsxs("button",{type:"button","data-testid":`g7le-overlay-jump-device-${K.key}`,title:E("layout_editor.overlay.jump_device_hint",{device:K.label}),onClick:X=>{X.stopPropagation(),g(K.key)},style:sa,children:["↗ ",E("layout_editor.overlay.jump_device",{device:K.label})]},K.key)),d&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-separate-branch",title:E("layout_editor.context_menu.separate_branch_hint"),onClick:K=>{K.stopPropagation(),d()},style:sa,children:["📱 ",c??E("layout_editor.context_menu.separate_branch")]}),p&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-merge-branch",title:E("layout_editor.context_menu.merge_branch_hint"),onClick:K=>{K.stopPropagation(),p()},style:sa,children:["↩️ ",f??E("layout_editor.context_menu.merge_branch")]})]})]}),i.jsx(K7,{anchor:n&&B?{left:n.left+n.width+8,top:n.top-4}:null,open:B,onClose:()=>N(!1),onEditProps:s,onDuplicate:a,onDelete:l,onSeparateBranch:d,separateBranchLabel:c,onMergeBranch:p,mergeBranchLabel:f})]})}function q7(e){const{enabledAxes:t,onHandlePointerDown:n}=e,o=t?.width??!1,r=t?.height??!1,s=[{key:"nw",style:{left:-4,top:-4},cursor:"nwse-resize",needsWidth:!0,needsHeight:!0},{key:"n",style:{left:"50%",top:-4,transform:"translateX(-50%)"},cursor:"ns-resize",needsWidth:!1,needsHeight:!0},{key:"ne",style:{right:-4,top:-4},cursor:"nesw-resize",needsWidth:!0,needsHeight:!0},{key:"e",style:{right:-4,top:"50%",transform:"translateY(-50%)"},cursor:"ew-resize",needsWidth:!0,needsHeight:!1},{key:"se",style:{right:-4,bottom:-4},cursor:"nwse-resize",needsWidth:!0,needsHeight:!0},{key:"s",style:{left:"50%",bottom:-4,transform:"translateX(-50%)"},cursor:"ns-resize",needsWidth:!1,needsHeight:!0},{key:"sw",style:{left:-4,bottom:-4},cursor:"nesw-resize",needsWidth:!0,needsHeight:!0},{key:"w",style:{left:-4,top:"50%",transform:"translateY(-50%)"},cursor:"ew-resize",needsWidth:!0,needsHeight:!1}];return i.jsx(i.Fragment,{children:s.map(a=>{const l=!a.needsWidth||o,d=!a.needsHeight||r,c=l&&d&&!!n;return!l||!d?null:i.jsx("span",{"data-testid":`g7le-resize-handle-${a.key}`,"data-resize-handle-active":c?"true":"false",onPointerDown:c?p=>{p.preventDefault(),p.stopPropagation(),n?.(a.key,{clientX:p.clientX,clientY:p.clientY})}:void 0,style:{position:"absolute",...a.style,width:8,height:8,background:"#fff",border:"1px solid #2563eb",cursor:a.cursor,pointerEvents:c?"auto":"none",zIndex:Ln}},a.key)})})}const Wo={position:"absolute",top:-28,left:0,background:"#fff",border:"1px solid #2563eb",color:"#2563eb",padding:"2px 6px",fontSize:11,borderRadius:4,cursor:"pointer",pointerEvents:"auto",whiteSpace:"nowrap",zIndex:Ln},sa={background:"#fff",border:"1px solid #2563eb",color:"#2563eb",padding:"2px 6px",fontSize:11,borderRadius:4,cursor:"pointer",pointerEvents:"auto",whiteSpace:"nowrap",zIndex:Ln},aa={marginLeft:6,padding:"0 5px",borderRadius:3,background:"#eef2ff",border:"1px solid #c7d2fe",fontSize:10,fontWeight:600,color:"#3730a3"},G7={position:"absolute",top:0,right:0,transform:"translateY(-100%)",background:"rgba(124,58,237,0.92)",color:"#fff",padding:"1px 6px",borderRadius:"3px 3px 0 0",fontSize:10,fontWeight:600,whiteSpace:"nowrap",pointerEvents:"none"},Kp={position:"absolute",top:0,left:0,background:"rgba(37,99,235,0.55)",color:"#fff",padding:"1px 6px",fontSize:10,fontWeight:600,lineHeight:"14px",borderBottomRightRadius:4,letterSpacing:"0.02em",whiteSpace:"nowrap",pointerEvents:"none",userSelect:"none",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis"},Vp={position:"absolute",bottom:"100%",left:0,marginBottom:2,background:"rgba(37,99,235,0.55)",color:"#fff",padding:"1px 6px",fontSize:10,fontWeight:600,lineHeight:"14px",borderRadius:4,letterSpacing:"0.02em",whiteSpace:"nowrap",pointerEvents:"none",userSelect:"none"},Y7={...Kp,pointerEvents:"auto",cursor:"pointer",background:"rgba(37,99,235,0.82)",border:"none",display:"inline-flex",alignItems:"center",font:"inherit",fontSize:10,fontWeight:600,zIndex:Ln},X7={...Vp,pointerEvents:"auto",cursor:"pointer",background:"rgba(37,99,235,0.82)",border:"none",display:"inline-flex",alignItems:"center",font:"inherit",fontSize:10,fontWeight:600,zIndex:Ln},J7={above:{top:-30,left:"50%",transform:"translateX(-50%)"},below:{bottom:-30,left:"50%",transform:"translateX(-50%)"},left:{left:-30,top:"50%",transform:"translateY(-50%)"},right:{right:-30,top:"50%",transform:"translateY(-50%)"}};function Z7(e){const{selectedBox:t,points:n,onAddRequest:o}=e,{t:r}=tt();if(!t||n.length===0)return null;const s=Mp(t),l=s==="outside"?Pp(t):null;return i.jsx("div",{className:"g7le-insertion-affordances","data-testid":"g7le-insertion-affordances",style:{position:"absolute",left:t.left,top:t.top,width:t.width,height:t.height,pointerEvents:"none"},children:n.map(d=>{const c=l?{left:l[d.direction].left,top:l[d.direction].top}:J7[d.direction],p=r(`layout_editor.insertion.${d.direction}`);return i.jsx("button",{type:"button",disabled:d.disabled,"data-testid":`g7le-insertion-${d.direction}`,"data-disabled":d.disabled?"true":"false","data-placement":s,"aria-label":p,title:p,onClick:f=>{f.stopPropagation(),d.disabled||o(d)},style:{position:"absolute",...c,width:24,height:24,borderRadius:12,border:"1px solid #2563eb",background:d.disabled?"#cbd5e1":"#fff",color:d.disabled?"#94a3b8":"#2563eb",cursor:d.disabled?"not-allowed":"pointer",opacity:d.disabled?.4:1,fontSize:16,fontWeight:700,lineHeight:"20px",padding:0,pointerEvents:"auto",boxShadow:"0 1px 3px rgba(0,0,0,0.15)",zIndex:Ln},children:"+"},d.direction)})})}const Rr=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function co(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function la(e){return"nodeType"in e}function xt(e){var t,n;return e?co(e)?e:la(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function da(e){const{Document:t}=xt(e);return e instanceof t}function jo(e){return co(e)?!1:e instanceof xt(e).HTMLElement}function Up(e){return e instanceof xt(e).SVGElement}function uo(e){return e?co(e)?e.document:la(e)?da(e)?e:jo(e)||Up(e)?e.ownerDocument:document:document:document}const sn=Rr?u.useLayoutEffect:u.useEffect;function ei(e){const t=u.useRef(e);return sn(()=>{t.current=e}),u.useCallback(function(){for(var n=arguments.length,o=new Array(n),r=0;r{e.current=setInterval(o,r)},[]),n=u.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function Ho(e,t){t===void 0&&(t=[e]);const n=u.useRef(e);return sn(()=>{n.current!==e&&(n.current=e)},t),n}function Fo(e,t){const n=u.useRef();return u.useMemo(()=>{const o=e(n.current);return n.current=o,o},[...t])}function ti(e){const t=ei(e),n=u.useRef(null),o=u.useCallback(r=>{r!==n.current&&t?.(r,n.current),n.current=r},[]);return[n,o]}function ni(e){const t=u.useRef();return u.useEffect(()=>{t.current=e},[e]),t.current}let ca={};function oi(e,t){return u.useMemo(()=>{if(t)return t;const n=ca[e]==null?0:ca[e]+1;return ca[e]=n,e+"-"+n},[e,t])}function qp(e){return function(t){for(var n=arguments.length,o=new Array(n>1?n-1:0),r=1;r{const l=Object.entries(a);for(const[d,c]of l){const p=s[d];p!=null&&(s[d]=p+e*c)}return s},{...t})}}const po=qp(1),ri=qp(-1);function R7(e){return"clientX"in e&&"clientY"in e}function ua(e){if(!e)return!1;const{KeyboardEvent:t}=xt(e.target);return t&&e instanceof t}function e2(e){if(!e)return!1;const{TouchEvent:t}=xt(e.target);return t&&e instanceof t}function ii(e){if(e2(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return R7(e)?{x:e.clientX,y:e.clientY}:null}const Ko=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:n}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:n}=e;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(e){if(e)return[Ko.Translate.toString(e),Ko.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:o}=e;return t+" "+n+"ms "+o}}}),Gp="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function t2(e){return e.matches(Gp)?e:e.querySelector(Gp)}const n2={display:"none"};function o2(e){let{id:t,value:n}=e;return u.createElement("div",{id:t,style:n2},n)}function r2(e){let{id:t,announcement:n,ariaLiveType:o="assertive"}=e;const r={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 u.createElement("div",{id:t,style:r,role:"status","aria-live":o,"aria-atomic":!0},n)}function i2(){const[e,t]=u.useState("");return{announce:u.useCallback(o=>{o!=null&&t(o)},[]),announcement:e}}const Yp=u.createContext(null);function s2(e){const t=u.useContext(Yp);u.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(e)},[e,t])}function a2(){const[e]=u.useState(()=>new Set),t=u.useCallback(o=>(e.add(o),()=>e.delete(o)),[e]);return[u.useCallback(o=>{let{type:r,event:s}=o;e.forEach(a=>{var l;return(l=a[r])==null?void 0:l.call(a,s)})},[e]),t]}const l2={draggable:` +`);return t.length>0&&t[t.length-1]===""&&t.pop(),t}const Qu=4e3;function N$(e,t,n=3){const o=Zu(e),r=Zu(t);let s=0;const a=Math.min(o.length,r.length);for(;sQu||p.length>Qu)return{hunks:[],addedCount:-1,removedCount:-1,identical:!1};const f=D$(c,p),b=z$(c,p,f),g=[];let m=s,h=s,v=0,y=0;for(let k=0;k{const s=e.slice(r.start,r.end+1);let a=0,l=0,d=0,c=0;for(const g of s)g.oldLine!==null&&(a===0&&(a=g.oldLine),d++),g.newLine!==null&&(l===0&&(l=g.newLine),c++);const p=a||(d===0?0:1),f=l||(c===0?0:1);return{header:`@@ -${p},${d} +${f},${c} @@`,oldStart:p,oldCount:d,newStart:f,newCount:c,lines:s}})}function Ru(e){return JSON.stringify(Rs(e),null,2)}function Rs(e){if(Array.isArray(e))return e.map(Rs);if(e&&typeof e=="object"){const t=e,n={};for(const o of Object.keys(t).sort())n[o]=Rs(t[o]);return n}return e}const L$={display:"flex",flexDirection:"column",height:"100%",minHeight:0},P$={display:"flex",alignItems:"center",gap:8,padding:"12px 16px",borderBottom:"1px solid #e2e8f0",background:"#f8fafc"},O$={display:"inline-flex",alignItems:"center",gap:4,padding:"4px 10px",borderRadius:6,border:"1px solid #cbd5e1",background:"#ffffff",color:"#0f172a",fontSize:12,fontWeight:600,cursor:"pointer",outline:"none"},B$={marginLeft:"auto",border:"none",background:"transparent",fontSize:16,color:"#64748b",cursor:"pointer",outline:"none"},W$={display:"flex",alignItems:"center",gap:12,padding:"8px 16px",borderBottom:"1px solid #e2e8f0",background:"#ffffff",fontSize:12,fontWeight:600},j$={flex:1,minHeight:0,overflow:"auto",background:"#ffffff",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace',fontSize:12,lineHeight:1.5},ep={padding:"24px 12px",textAlign:"center",color:"#94a3b8",fontSize:13},H$={padding:"2px 12px",background:"#f1f5f9",color:"#64748b",borderTop:"1px solid #e2e8f0",borderBottom:"1px solid #e2e8f0",userSelect:"none"};function F$(e){return e==="add"?{row:{background:"#e6ffed"},gutter:{background:"#cdffd8",color:"#22863a"},sign:"+",signColor:"#22863a"}:e==="remove"?{row:{background:"#ffeef0"},gutter:{background:"#ffdce0",color:"#b31d28"},sign:"-",signColor:"#b31d28"}:{row:{background:"#ffffff"},gutter:{background:"#f8fafc",color:"#94a3b8"},sign:" ",signColor:"#94a3b8"}}const tp={display:"inline-block",width:44,textAlign:"right",padding:"0 6px",color:"#94a3b8",userSelect:"none",borderRight:"1px solid #e2e8f0",whiteSpace:"nowrap"};function K$({oldVersion:e,newVersion:t,oldContent:n,newContent:o,t:r,onBack:s,onClose:a}){const l=u.useMemo(()=>{const c=Ru(n),p=Ru(o);return N$(c,p)},[n,o]),d=l.addedCount<0;return i.jsxs("div",{className:"g7le-version-diff","data-testid":"g7le-version-diff",style:L$,children:[i.jsxs("div",{"data-modal-drag-handle":!0,style:P$,children:[i.jsxs("button",{type:"button",onClick:s,style:O$,"data-testid":"g7le-version-diff-back",children:["← ",r("layout_editor.version_history.diff_back")]}),i.jsx("span",{style:{fontSize:14,fontWeight:700},"data-testid":"g7le-version-diff-title",children:r("layout_editor.version_history.diff_title",{old:e,new:t})}),i.jsx("button",{type:"button","aria-label":r("layout_editor.version_history.close"),onClick:a,style:B$,"data-testid":"g7le-version-diff-close",children:"✕"})]}),!d&&i.jsxs("div",{style:W$,"data-testid":"g7le-version-diff-summary",children:[i.jsx("span",{style:{color:"#16a34a"},"data-testid":"g7le-version-diff-added",children:r("layout_editor.version_history.added",{count:Math.max(0,l.addedCount)})}),i.jsx("span",{style:{color:"#dc2626"},"data-testid":"g7le-version-diff-removed",children:r("layout_editor.version_history.removed",{count:Math.max(0,l.removedCount)})})]}),i.jsx("div",{style:j$,children:d?i.jsx("div",{style:ep,"data-testid":"g7le-version-diff-too-large",children:r("layout_editor.version_history.diff_too_large")}):l.identical?i.jsx("div",{style:ep,"data-testid":"g7le-version-diff-identical",children:r("layout_editor.version_history.diff_identical")}):l.hunks.map((c,p)=>i.jsxs("div",{"data-testid":`g7le-version-diff-hunk-${p}`,children:[i.jsx("div",{style:H$,"data-testid":`g7le-version-diff-hunk-header-${p}`,children:c.header}),c.lines.map((f,b)=>{const g=F$(f.kind);return i.jsxs("div",{style:{display:"flex",alignItems:"stretch",...g.row},"data-kind":f.kind,"data-testid":`g7le-version-diff-line-${p}-${b}`,children:[i.jsx("span",{style:{...tp,...g.gutter},"aria-hidden":"true",children:f.oldLine??""}),i.jsx("span",{style:{...tp,...g.gutter},"aria-hidden":"true",children:f.newLine??""}),i.jsx("span",{style:{display:"inline-block",width:16,textAlign:"center",color:g.signColor,userSelect:"none",fontWeight:700},"aria-hidden":"true",children:g.sign}),i.jsx("span",{style:{whiteSpace:"pre-wrap",wordBreak:"break-word",flex:1,padding:"0 4px"},children:f.content})]},b)})]},p))})]})}const V$={display:"flex",flexDirection:"column",height:"100%",minHeight:0},U$={display:"flex",alignItems:"center",gap:8,padding:"12px 16px",borderBottom:"1px solid #e2e8f0",background:"#f8fafc"},q$={marginLeft:"auto",border:"none",background:"transparent",fontSize:16,color:"#64748b",cursor:"pointer",outline:"none"},G$={flex:1,minHeight:0,overflowY:"auto",padding:12},np={padding:"24px 12px",textAlign:"center",color:"#94a3b8",fontSize:13},Y$={margin:"8px 16px 0",padding:"8px 12px",borderRadius:6,background:"#fef2f2",color:"#b91c1c",fontSize:12,border:"1px solid #fecaca"},X$={display:"flex",flexDirection:"column",gap:8},J$={display:"flex",alignItems:"center",gap:12,padding:"10px 12px",borderRadius:8,border:"1px solid #e2e8f0",background:"#ffffff"},Z$={display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:44,padding:"2px 8px",borderRadius:999,background:"#eff6ff",color:"#1d4ed8",fontSize:12,fontWeight:700},Q$={display:"inline-flex",alignItems:"center",padding:"1px 8px",borderRadius:999,background:"#0f172a",color:"#ffffff",fontSize:10,fontWeight:700,letterSpacing:.3},R$={display:"flex",alignItems:"center",gap:10,fontSize:11,fontWeight:600},eE={display:"flex",flexDirection:"column",gap:2,minWidth:0,flex:1},op={padding:"6px 12px",borderRadius:6,border:"1px solid #cbd5e1",background:"#ffffff",color:"#0f172a",fontSize:12,fontWeight:600,cursor:"pointer",outline:"none",whiteSpace:"nowrap"};function rp(e){return e.full_content&&typeof e.full_content=="object"?e.full_content:{endpoint:e.endpoint,components:e.components,data_sources:e.data_sources,metadata:e.metadata}}function tE(e){if(!e)return"";const t=Date.parse(e);if(Number.isNaN(t))return e;try{return new Date(t).toLocaleString()}catch{return e}}function nE({templateIdentifier:e,target:t,t:n,onRestored:o,onClose:r}){const{versions:s,isLoading:a,isLoadingMore:l,error:d,restoringId:c,hasMore:p,loadVersions:f,loadMore:b,restore:g,loadVersionDetail:m}=T$(e,t,o),[h,v]=u.useState(null),[y,_]=u.useState(null),[w,k]=u.useState(null);u.useEffect(()=>{f()},[f]);const x=u.useCallback(async C=>{v(null),k(C.version);try{const T=await m(C.version);if(T.kind!=="success"){v(T.kind==="not_found"?n("layout_editor.version_history.restore_not_found"):T.message);return}const E=C.version-1,A=s.some(D=>D.version===E);let N={};if(A){const D=await m(E);if(D.kind==="success")N=rp(D.detail);else if(D.kind==="network_error"){v(D.message);return}}_({oldVersion:A?E:0,newVersion:C.version,oldContent:N,newContent:rp(T.detail)})}finally{k(null)}},[m,s,n]),$=u.useCallback(async C=>{v(null);const T=n("layout_editor.version_history.restore_confirm");if(!(typeof window<"u"?window.confirm(T):!0))return;const A=await g(C);A.kind==="success"?r():A.kind==="not_found"?v(n("layout_editor.version_history.restore_not_found")):v(A.message)},[g,r,n]),S=h??d;return y?i.jsx(K$,{oldVersion:y.oldVersion,newVersion:y.newVersion,oldContent:y.oldContent,newContent:y.newContent,t:n,onBack:()=>_(null),onClose:r}):i.jsxs("div",{className:"g7le-version-history","data-testid":"g7le-version-history",style:V$,children:[i.jsxs("div",{"data-modal-drag-handle":!0,style:U$,children:[i.jsxs("span",{style:{fontSize:14,fontWeight:700},"data-testid":"g7le-version-history-title",children:["🕘 ",n("layout_editor.version_history.title")]}),i.jsx("button",{type:"button","aria-label":n("layout_editor.version_history.close"),onClick:r,style:q$,"data-testid":"g7le-version-history-close",children:"✕"})]}),S&&i.jsx("div",{style:Y$,"data-testid":"g7le-version-history-error",children:S}),i.jsx("div",{style:G$,children:a?i.jsx("div",{style:np,"data-testid":"g7le-version-history-loading",children:n("layout_editor.version_history.loading")}):s.length===0?i.jsx("div",{style:np,"data-testid":"g7le-version-history-empty",children:n("layout_editor.version_history.empty")}):i.jsxs("div",{"data-testid":"g7le-version-history-list",style:X$,children:[s.map((C,T)=>{const E=C.changes_summary,A=E?.added_count??0,N=E?.removed_count??0,D=E?.char_diff??0,B=tE(C.created_at),M=c===C.id,O=T===0;return i.jsxs("div",{style:J$,"data-testid":`g7le-version-row-${C.id}`,children:[i.jsxs("span",{style:Z$,"data-testid":`g7le-version-badge-${C.id}`,children:["v",C.version]}),i.jsxs("div",{style:eE,children:[i.jsxs("span",{style:{display:"flex",alignItems:"center",gap:8},children:[B&&i.jsx("span",{style:{fontSize:12,color:"#475569",fontWeight:600},children:B}),O&&i.jsx("span",{style:Q$,"data-testid":`g7le-version-latest-${C.id}`,children:n("layout_editor.version_history.latest")})]}),i.jsxs("span",{style:R$,"data-testid":`g7le-version-summary-${C.id}`,children:[i.jsx("span",{style:{color:"#16a34a"},"data-testid":`g7le-version-added-${C.id}`,children:n("layout_editor.version_history.added",{count:A})}),i.jsx("span",{style:{color:"#dc2626"},"data-testid":`g7le-version-removed-${C.id}`,children:n("layout_editor.version_history.removed",{count:N})}),i.jsx("span",{style:{color:"#94a3b8",fontWeight:500},"data-testid":`g7le-version-chars-${C.id}`,children:n("layout_editor.version_history.chars",{diff:`${D>=0?"+":""}${D}`})})]}),i.jsx("span",{style:{fontSize:11,color:"#94a3b8"},"data-testid":`g7le-version-author-${C.id}`,children:n("layout_editor.version_history.saved_by",{name:C.created_by_name??n("layout_editor.version_history.unknown_author")})})]}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsx("button",{type:"button",onClick:()=>void x(C),disabled:w!==null,style:{...op,background:"#f8fafc",opacity:w!==null?.6:1},"data-testid":`g7le-version-compare-${C.id}`,children:w===C.version?n("layout_editor.version_history.comparing"):n("layout_editor.version_history.compare")}),!O&&i.jsx("button",{type:"button",onClick:()=>void $(C.id),disabled:M||c!==null,style:{...op,opacity:M||c!==null?.6:1},"data-testid":`g7le-version-restore-${C.id}`,children:n(M?"layout_editor.version_history.restoring":"layout_editor.version_history.restore")})]})]},C.id)}),p&&i.jsx("button",{type:"button","data-testid":"g7le-version-history-load-more",style:oE,disabled:l,onClick:()=>{b()},children:n(l?"layout_editor.version_history.loading":"layout_editor.version_history.load_more")})]})})]})}const oE={width:"100%",marginTop:8,padding:"8px 12px",fontSize:12,color:"#475569",background:"#f8fafc",border:"1px solid #e2e8f0",borderRadius:6,cursor:"pointer"};function Po(e){return`/api/admin/extensions/${encodeURIComponent(e.type)}/${encodeURIComponent(e.identifier)}/custom-assets`}function Oo(e,t){const n=e?.message;return typeof n=="string"&&n!==""?n:`HTTP ${t}`}function rE(e){const[t,n]=u.useState([]),[o,r]=u.useState(null),[s,a]=u.useState(!1),[l,d]=u.useState(!1),[c,p]=u.useState(null),f=u.useCallback(async()=>{a(!0),p(null);try{const v=await fetch(Po(e),{credentials:"same-origin",headers:Ne()}),y=await v.json().catch(()=>null);if(v.status===401||v.status===403){d(!0),n([]);return}if(d(!1),!v.ok){p(Oo(y,v.status)),n([]);return}const _=y?.data??{},w=_.files;n(Array.isArray(w)?w:[]),r({editable_extensions:_.editable_extensions??[],uploadable_extensions:_.uploadable_extensions??[],max_text_bytes:_.max_text_bytes??0,max_upload_bytes:_.max_upload_bytes??0})}catch(v){p(v instanceof Error?v.message:"network error"),n([])}finally{a(!1)}},[e.type,e.identifier]),b=u.useCallback(async v=>{p(null);try{const y=`${Po(e)}/content?path=${encodeURIComponent(v)}`,_=await fetch(y,{credentials:"same-origin",headers:Ne()}),w=await _.json().catch(()=>null);if(!_.ok)return p(Oo(w,_.status)),null;const k=w?.data?.content;return typeof k=="string"?k:""}catch(y){return p(y instanceof Error?y.message:"network error"),null}},[e.type,e.identifier]),g=u.useCallback(async(v,y)=>{p(null);try{const _=await fetch(`${Po(e)}/content`,{method:"PUT",credentials:"same-origin",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({path:v,content:y})}),w=await _.json().catch(()=>null);return _.ok?(await f(),!0):(p(Oo(w,_.status)),!1)}catch(_){return p(_ instanceof Error?_.message:"network error"),!1}},[e.type,e.identifier,f]),m=u.useCallback(async(v,y)=>{p(null);try{const _=new FormData;_.append("file",v),y&&_.append("directory",y);const w=await fetch(`${Po(e)}/upload`,{method:"POST",credentials:"same-origin",headers:Ne(),body:_}),k=await w.json().catch(()=>null);return w.ok?(await f(),!0):(p(Oo(k,w.status)),!1)}catch(_){return p(_ instanceof Error?_.message:"network error"),!1}},[e.type,e.identifier,f]),h=u.useCallback(async v=>{p(null);try{const y=`${Po(e)}?path=${encodeURIComponent(v)}`,_=await fetch(y,{method:"DELETE",credentials:"same-origin",headers:Ne()}),w=await _.json().catch(()=>null);return _.ok?(await f(),!0):(p(Oo(w,_.status)),!1)}catch(y){return p(y instanceof Error?y.message:"network error"),!1}},[e.type,e.identifier,f]);return{files:t,meta:o,isLoading:s,forbidden:l,error:c,reload:f,read:b,save:g,upload:m,remove:h}}const iE={display:"flex",flexDirection:"column",height:"100%",minHeight:0},sE={display:"flex",alignItems:"center",gap:8,padding:"12px 16px",borderBottom:"1px solid #e2e8f0",background:"#f8fafc",fontWeight:600,color:"#0f172a"},aE={marginLeft:"auto",border:"none",background:"transparent",fontSize:16,color:"#64748b",cursor:"pointer",outline:"none"},lE={flex:1,minHeight:0,display:"flex"},dE={width:260,flexShrink:0,borderRight:"1px solid #e2e8f0",overflowY:"auto",padding:8},cE={flex:1,minWidth:0,display:"flex",flexDirection:"column",padding:12,gap:8},ip={display:"flex",alignItems:"center",gap:6,width:"100%",padding:"6px 8px",borderRadius:6,borderWidth:1,borderStyle:"solid",borderColor:"transparent",backgroundColor:"transparent",fontSize:12,color:"#334155",cursor:"pointer",textAlign:"left"},uE={...ip,backgroundColor:"#eff6ff",borderColor:"#bfdbfe",color:"#1d4ed8",fontWeight:600},pE={margin:16,padding:16,borderRadius:8,border:"1px solid #fcd34d",background:"#fffbeb",color:"#92400e",fontSize:13,lineHeight:1.7},fE={padding:"8px 12px",borderRadius:6,border:"1px solid #fecaca",background:"#fef2f2",color:"#b91c1c",fontSize:12},gE={flex:1,minHeight:220,width:"100%",boxSizing:"border-box",padding:10,borderRadius:6,borderWidth:1,borderStyle:"solid",borderColor:"#cbd5e1",fontFamily:"ui-monospace, SFMono-Regular, Menlo, Consolas, monospace",fontSize:12,lineHeight:1.6,resize:"vertical"},sp={display:"flex",alignItems:"center",gap:8,flexWrap:"wrap"},io={padding:"6px 12px",borderRadius:6,borderWidth:1,borderStyle:"solid",borderColor:"#cbd5e1",backgroundColor:"#ffffff",color:"#334155",fontSize:12,cursor:"pointer"},hE={...io,backgroundColor:"#2563eb",borderColor:"#2563eb",color:"#ffffff",fontWeight:600},yE={...io,borderColor:"#fca5a5",color:"#b91c1c"},bE={...io,cursor:"text",minWidth:200},mE={...io,cursor:"pointer",minWidth:220};function vE(e,t){if(typeof e=="string"&&e!=="")return e;if(e&&typeof e=="object"){const n=e,o=window?.G7Config?.locale??"ko",r=n[o]??n.ko??n.en??Object.values(n)[0];if(typeof r=="string"&&r!=="")return r}return t}function _E(e){const t=(typeof window<"u"?window.G7Config:null)??{},n=[{type:"template",identifier:e,label:e}];for(const[o,r]of[["module",t.activeModules],["plugin",t.activePlugins]])if(Array.isArray(r))for(const s of r){const a=typeof s?.identifier=="string"?s.identifier:"";a&&n.push({type:o,identifier:a,label:vE(s?.display_name,a)})}return n}function xE(e){return e<1024?`${e} B`:e<1024*1024?`${Math.round(e/1024)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function wE(e){const{templateIdentifier:t,t:n,onClose:o}=e,r=u.useMemo(()=>_E(t),[t]),[s,a]=u.useState(`template:${t}`),l=u.useMemo(()=>r.find(S=>`${S.type}:${S.identifier}`===s)??r[0],[r,s]),d=rE({type:l.type,identifier:l.identifier}),{reload:c}=d,[p,f]=u.useState(null),[b,g]=u.useState(""),[m,h]=u.useState(""),[v,y]=u.useState(!1),_=u.useRef(null);u.useEffect(()=>{c()},[c]),u.useEffect(()=>{f(null),g(""),h("")},[s]);const w=u.useCallback(async S=>{if(f(S),!S.editable){g("");return}y(!0);const C=await d.read(S.path);y(!1),g(C??"")},[d]),k=u.useCallback(async()=>{const S=p?.path??m.trim();if(!S)return;y(!0);const C=await d.save(S,b);y(!1),C&&!p&&(h(""),f({path:S,name:S.split("/").pop()??S,extension:(S.split(".").pop()??"").toLowerCase(),size:b.length,modified_at:new Date().toISOString(),editable:!0,loaded:!0}))},[d,p,m,b]),x=u.useCallback(async()=>{if(!p||typeof window<"u"&&!window.confirm(n("layout_editor.custom_assets.delete_confirm")))return;y(!0);const S=await d.remove(p.path);y(!1),S&&(f(null),g(""))},[d,p,n]),$=u.useCallback(async S=>{const C=S.target.files?.[0];C&&(y(!0),await d.upload(C),y(!1),_.current&&(_.current.value=""))},[d]);return i.jsxs("div",{className:"g7le-custom-assets",style:iE,"data-testid":"g7le-custom-assets-modal",children:[i.jsxs("div",{style:sE,children:[i.jsxs("span",{children:["🎨 ",n("layout_editor.custom_assets.title")]}),i.jsx("select",{value:s,onChange:S=>a(S.target.value),style:mE,"aria-label":n("layout_editor.custom_assets.target_label"),"data-testid":"g7le-custom-assets-target",children:r.map(S=>i.jsxs("option",{value:`${S.type}:${S.identifier}`,children:[n(`layout_editor.custom_assets.type_${S.type}`)," · ",S.label]},`${S.type}:${S.identifier}`))}),i.jsx("button",{type:"button",style:aE,onClick:o,"aria-label":n("layout_editor.custom_assets.close"),"data-testid":"g7le-custom-assets-close",children:"✕"})]}),d.forbidden?i.jsx("div",{style:pE,"data-testid":"g7le-custom-assets-forbidden",children:n("layout_editor.custom_assets.forbidden")}):i.jsxs("div",{style:lE,children:[i.jsxs("div",{style:dE,"data-testid":"g7le-custom-assets-list",children:[d.isLoading&&d.files.length===0?i.jsx("div",{style:{padding:12,color:"#94a3b8",fontSize:12},children:n("layout_editor.custom_assets.loading")}):null,!d.isLoading&&d.files.length===0?i.jsx("div",{style:{padding:12,color:"#94a3b8",fontSize:12},children:n("layout_editor.custom_assets.empty")}):null,d.files.map(S=>i.jsxs("button",{type:"button",style:p?.path===S.path?uE:ip,onClick:()=>void w(S),"data-testid":`g7le-custom-asset-row-${S.path}`,"data-loaded":S.loaded?"true":"false",children:[i.jsx("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:S.path}),i.jsx("span",{style:{color:"#94a3b8",fontSize:11},children:xE(S.size)})]},S.path))]}),i.jsxs("div",{style:cE,children:[d.error?i.jsx("div",{style:fE,"data-testid":"g7le-custom-assets-error",children:d.error}):null,i.jsxs("div",{style:sp,children:[i.jsx("input",{type:"text",value:p?p.path:m,readOnly:!!p,onChange:S=>h(S.target.value),placeholder:n("layout_editor.custom_assets.new_path_placeholder"),style:bE,"aria-label":n("layout_editor.custom_assets.path_label"),"data-testid":"g7le-custom-assets-path"}),p?i.jsx("button",{type:"button",style:io,onClick:()=>{f(null),g("")},"data-testid":"g7le-custom-assets-new",children:n("layout_editor.custom_assets.new_file")}):null]}),p&&!p.editable?i.jsx("div",{style:{color:"#64748b",fontSize:12,lineHeight:1.7},children:n("layout_editor.custom_assets.binary_hint",{extension:p.extension})}):i.jsx("textarea",{value:b,onChange:S=>g(S.target.value),style:gE,spellCheck:!1,"aria-label":n("layout_editor.custom_assets.content_label"),"data-testid":"g7le-custom-assets-content"}),i.jsxs("div",{style:sp,children:[i.jsx("button",{type:"button",style:hE,disabled:v||(p?!p.editable:m.trim()===""),onClick:()=>void k(),"data-testid":"g7le-custom-assets-save",children:n("layout_editor.custom_assets.save")}),i.jsx("button",{type:"button",style:io,disabled:v,onClick:()=>_.current?.click(),"data-testid":"g7le-custom-assets-upload",children:n("layout_editor.custom_assets.upload")}),i.jsx("input",{ref:_,type:"file",style:{display:"none"},onChange:S=>void $(S),"data-testid":"g7le-custom-assets-file-input"}),i.jsx("button",{type:"button",style:yE,disabled:v||!p,onClick:()=>void x(),"data-testid":"g7le-custom-assets-delete",children:n("layout_editor.custom_assets.delete")}),i.jsx("span",{style:{color:"#94a3b8",fontSize:11},children:n("layout_editor.custom_assets.apply_hint")})]})]})]})]})}const ap=[{id:"copy",group:"clipboard",combos:[{key:"c",mod:!0}],labelKey:"layout_editor.shortcuts.action.copy",requiresSelection:!0},{id:"cut",group:"clipboard",combos:[{key:"x",mod:!0}],labelKey:"layout_editor.shortcuts.action.cut",requiresSelection:!0},{id:"paste",group:"clipboard",combos:[{key:"v",mod:!0}],labelKey:"layout_editor.shortcuts.action.paste"},{id:"openProps",group:"element",combos:[{key:"enter"}],labelKey:"layout_editor.shortcuts.action.open_props",requiresSelection:!0},{id:"delete",group:"element",combos:[{key:"delete"},{key:"backspace"}],labelKey:"layout_editor.shortcuts.action.delete",requiresSelection:!0},{id:"selectParent",group:"element",combos:[{key:"arrowup"}],labelKey:"layout_editor.shortcuts.action.select_parent",requiresSelection:!0},{id:"deselect",group:"element",combos:[{key:"escape"}],labelKey:"layout_editor.shortcuts.action.deselect"},{id:"addElement",group:"element",combos:[{key:"/",mod:!0}],labelKey:"layout_editor.shortcuts.action.add_element"},{id:"undo",group:"history",combos:[{key:"z",mod:!0}],labelKey:"layout_editor.shortcuts.action.undo"},{id:"redo",group:"history",combos:[{key:"z",mod:!0,shift:!0},{key:"y",mod:!0}],labelKey:"layout_editor.shortcuts.action.redo"},{id:"editCode",group:"view",combos:[{key:"e",mod:!0}],labelKey:"layout_editor.shortcuts.action.edit_code"},{id:"preview",group:"view",combos:[{key:"p",mod:!0}],labelKey:"layout_editor.shortcuts.action.preview"},{id:"translations",group:"view",combos:[{key:"l",mod:!0}],labelKey:"layout_editor.shortcuts.action.translations"},{id:"help",group:"view",combos:[{key:"?"}],labelKey:"layout_editor.shortcuts.action.help"},{id:"reset",group:"document",combos:[{key:"r",mod:!0,shift:!0}],labelKey:"layout_editor.shortcuts.action.reset"},{id:"save",group:"document",combos:[{key:"s",mod:!0}],labelKey:"layout_editor.shortcuts.action.save"},{id:"exit",group:"document",combos:[{key:"escape"}],labelKey:"layout_editor.shortcuts.action.exit"}];function kE(e){return{key:(e.key||"").toLowerCase(),mod:e.ctrlKey||e.metaKey,shift:e.shiftKey,alt:e.altKey}}function SE(e,t){return e.key===t.key&&!!e.mod==!!t.mod&&!!e.shift==!!t.shift&&!!e.alt==!!t.alt}function CE(e){for(const t of ap)if(t.combos.some(n=>SE(n,e)))return t;return null}function $E(e,t){const n=[];return e.mod&&n.push(t?"⌘":"Ctrl"),e.shift&&n.push(t?"⇧":"Shift"),e.alt&&n.push(t?"⌥":"Alt"),n.push(EE(e.key)),n.join(" + ")}function EE(e){return{arrowup:"↑",arrowdown:"↓",arrowleft:"←",arrowright:"→",enter:"Enter",escape:"Esc",delete:"Delete",backspace:"Backspace"," ":"Space"}[e]??(e.length===1?e.toUpperCase():e)}const IE=["clipboard","element","history","view","document"],AE={clipboard:"layout_editor.shortcuts.group.clipboard",element:"layout_editor.shortcuts.group.element",history:"layout_editor.shortcuts.group.history",view:"layout_editor.shortcuts.group.view",document:"layout_editor.shortcuts.group.document"};function TE(){return typeof navigator>"u"?!1:/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent||"")}function DE({t:e,onClose:t,isMac:n}){const o=n??TE(),r=u.useMemo(()=>{const s=new Map;for(const a of ap){const l=s.get(a.group)??[];l.push(a),s.set(a.group,l)}return s},[]);return i.jsxs("div",{className:"g7le-shortcut-help","data-testid":"g7le-shortcut-help",style:zE,children:[i.jsxs("div",{style:NE,children:[i.jsx("span",{style:ME,children:e("layout_editor.shortcuts.title")}),i.jsx("button",{type:"button","data-testid":"g7le-shortcut-help-close",onClick:t,"aria-label":e("layout_editor.shortcuts.close"),style:LE,children:"✕"})]}),i.jsx("div",{style:PE,children:IE.map(s=>{const a=r.get(s);return!a||a.length===0?null:i.jsxs("div",{style:OE,"data-testid":`g7le-shortcut-group-${s}`,children:[i.jsx("div",{style:BE,children:e(AE[s])}),i.jsx("table",{style:WE,children:i.jsx("tbody",{children:a.map(l=>i.jsxs("tr",{"data-testid":`g7le-shortcut-row-${l.id}`,children:[i.jsx("td",{style:jE,children:e(l.labelKey)}),i.jsx("td",{style:HE,children:l.combos.map((d,c)=>i.jsxs(u.Fragment,{children:[c>0&&i.jsx("span",{style:KE,children:e("layout_editor.shortcuts.or")}),i.jsx("kbd",{style:FE,children:$E(d,o)})]},c))})]},l.id))})})]},s)})}),i.jsx("div",{style:VE,children:e("layout_editor.shortcuts.footnote")})]})}const zE={display:"flex",flexDirection:"column",padding:20,gap:16,width:"100%",boxSizing:"border-box"},NE={display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:12,borderBottom:"1px solid #e2e8f0"},ME={fontSize:15,fontWeight:700,color:"#0f172a"},LE={width:28,height:28,border:"none",background:"transparent",color:"#64748b",cursor:"pointer",fontSize:14,borderRadius:6},PE={display:"grid",gridTemplateColumns:"1fr 1fr",columnGap:28,rowGap:18,alignItems:"start"},OE={display:"flex",flexDirection:"column",gap:6},BE={fontSize:12,fontWeight:700,color:"#2563eb"},WE={width:"100%",borderCollapse:"collapse"},jE={padding:"4px 0",fontSize:12.5,color:"#334155",textAlign:"left",whiteSpace:"nowrap",verticalAlign:"middle"},HE={padding:"4px 0",paddingLeft:12,textAlign:"right",verticalAlign:"middle"},FE={display:"inline-block",padding:"1px 6px",fontSize:11,fontFamily:"ui-monospace, monospace",color:"#0f172a",background:"#f1f5f9",border:"1px solid #cbd5e1",borderBottomWidth:2,borderRadius:5,whiteSpace:"nowrap"},KE={fontSize:11,color:"#94a3b8",margin:"0 4px"},VE={fontSize:11,color:"#94a3b8",paddingTop:12,borderTop:"1px solid #f1f5f9"};function UE(e){if(!e||!(e instanceof HTMLElement))return!1;const t=e.tagName;return!!(t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable)}function qE(){return typeof document>"u"?!1:!!document.querySelector(".g7le-modal-backdrop, .g7le-modal")}function lp(e){const{handlers:t,hasSelection:n,enabled:o=!0}=e;u.useEffect(()=>{if(!o||typeof window>"u")return;const r=s=>{if(UE(s.target))return;const a=kE(s),l=CE(a);if(!l||qE()||l.requiresSelection&&!n)return;if(l.key==="escape"||a.key==="escape"){if(n){const c=t.deselect;c&&(s.preventDefault(),c())}else{const c=t.exit;c&&(s.preventDefault(),c())}return}const d=t[l.id];d&&(s.preventDefault(),d())};return window.addEventListener("keydown",r),()=>window.removeEventListener("keydown",r)},[t,n,o])}function GE(e){const{result:t,onDismiss:n,onLoadLatest:o,onKeepMyChanges:r}=e,{t:s}=tt();if(u.useEffect(()=>{if(!t||t.kind==="concurrent_modification"||t.kind==="validation_failed")return;const a=setTimeout(n,5e3);return()=>clearTimeout(a)},[t,n]),!t)return null;if(t.kind==="success")return i.jsx(Bo,{tone:"success",testId:"g7le-save-banner-success",onDismiss:n,children:s("layout_editor.save.success")});if(t.kind==="validation_failed"){const a=t.errors??{},l=Object.entries(a);return i.jsxs(Bo,{tone:"error",testId:"g7le-save-banner-validation",onDismiss:n,children:[i.jsx("strong",{children:s("layout_editor.save.validation_failed")}),l.length>0&&i.jsx("ul",{style:dp,"data-testid":"g7le-save-banner-validation-errors",children:l.map(([d,c])=>i.jsxs("li",{children:[i.jsx("code",{style:cp,children:d}),": ",c.join(", ")]},d))})]})}return t.kind==="blocked_inactive_extension"?i.jsxs(Bo,{tone:"warning",testId:"g7le-save-banner-blocked",onDismiss:n,children:[i.jsx("strong",{children:s("layout_editor.save.blocked_inactive_extension")}),t.blockedPaths.length>0&&i.jsx("ul",{style:dp,"data-testid":"g7le-save-banner-blocked-paths",children:t.blockedPaths.map(a=>i.jsx("li",{children:i.jsx("code",{style:cp,children:a})},a))})]}):t.kind==="network_error"?i.jsxs(Bo,{tone:"error",testId:"g7le-save-banner-network",onDismiss:n,children:[i.jsx("strong",{children:s("layout_editor.save.network_error_title")}),i.jsx("div",{style:{marginTop:4,fontSize:12},children:t.message})]}):t.kind==="guard_no_document"?i.jsx(Bo,{tone:"neutral",testId:"g7le-save-banner-guard-no-document",onDismiss:n,children:s("layout_editor.save.guard_no_document")}):i.jsx("div",{role:"dialog","aria-modal":"true","aria-label":s("layout_editor.save.concurrent.title"),"data-testid":"g7le-save-banner-concurrent",style:ZE,children:i.jsxs("div",{style:QE,children:[i.jsx("h2",{style:RE,children:s("layout_editor.save.concurrent.title")}),i.jsx("p",{style:e7,children:s("layout_editor.save.concurrent.message")}),i.jsx("div",{style:t7,children:s("layout_editor.save.concurrent.version_info",{current:String(t.currentVersion),yours:String(t.yourVersion)})}),i.jsxs("div",{style:n7,children:[i.jsx("button",{type:"button","data-testid":"g7le-save-banner-concurrent-load-latest",onClick:()=>{o?.(),n()},style:o7,children:s("layout_editor.save.concurrent.load_latest")}),i.jsx("button",{type:"button","data-testid":"g7le-save-banner-concurrent-keep-mine",onClick:()=>{r?.(),n()},style:r7,children:s("layout_editor.save.concurrent.view_my_changes")}),i.jsx("button",{type:"button","data-testid":"g7le-save-banner-concurrent-cancel",onClick:n,style:i7,children:s("layout_editor.save.concurrent.cancel")})]})]})})}function Bo(e){const{tone:t,testId:n,onDismiss:o,children:r}=e,s=YE[t];return i.jsxs("div",{role:"status","data-testid":n,style:{...XE,background:s.bg,borderColor:s.border,color:s.fg},children:[i.jsx("div",{style:{flex:1,minWidth:0},children:r}),i.jsx("button",{type:"button",onClick:o,"aria-label":"close","data-testid":`${n}-close`,style:JE,children:"×"})]})}const YE={success:{bg:"#dcfce7",border:"#86efac",fg:"#14532d"},error:{bg:"#fee2e2",border:"#fca5a5",fg:"#7f1d1d"},warning:{bg:"#fef3c7",border:"#fcd34d",fg:"#78350f"},neutral:{bg:"#f1f5f9",border:"#cbd5e1",fg:"#334155"}},XE={display:"flex",alignItems:"flex-start",gap:12,padding:"12px 16px",border:"1px solid",borderRadius:0,fontSize:13,lineHeight:1.5},JE={background:"transparent",border:"none",fontSize:18,cursor:"pointer",lineHeight:1,color:"inherit",padding:"0 4px",flexShrink:0},dp={margin:"8px 0 0",paddingLeft:20,fontSize:12},cp={background:"rgba(0, 0, 0, 0.06)",padding:"1px 4px",borderRadius:3,fontFamily:"monospace"},ZE={position:"fixed",inset:0,background:"rgba(15, 23, 42, 0.6)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e4},QE={background:"#fff",borderRadius:8,padding:24,width:"min(480px, 90vw)",boxShadow:"0 10px 25px rgba(0,0,0,0.15)"},RE={margin:"0 0 8px",fontSize:16,fontWeight:600,color:"#0f172a"},e7={margin:"0 0 12px",color:"#334155",fontSize:13,lineHeight:1.5},t7={marginBottom:16,padding:"8px 12px",background:"#f8fafc",borderRadius:6,fontSize:12,color:"#64748b",fontFamily:"monospace"},n7={display:"flex",gap:8,justifyContent:"flex-end"},o7={padding:"8px 14px",background:"#2563eb",color:"#fff",border:"none",borderRadius:6,fontSize:13,fontWeight:600,cursor:"pointer"},r7={padding:"8px 14px",background:"#fff",color:"#334155",border:"1px solid #cbd5e1",borderRadius:6,fontSize:13,fontWeight:500,cursor:"pointer"},i7={padding:"8px 14px",background:"transparent",color:"#64748b",border:"none",borderRadius:6,fontSize:13,cursor:"pointer"};function up(e){if(!e)return null;const n=new URLSearchParams(e).get("route");return n&&n.length>0?n:null}function ea(e,t,n){const o=`/admin/layout-editor/${encodeURIComponent(e)}`;if(!t||t.length===0)return o;if(t.startsWith("__")){let r=`${o}?edit=${encodeURIComponent(t)}`;return(t.startsWith("__modal__/")||t.startsWith("__iteration__/"))&&n&&(r+=`&host=${encodeURIComponent(n)}`),r}return`${o}?route=${encodeURIComponent(t)}`}function pp(e){if(!e)return null;const n=new URLSearchParams(e).get("host");return n&&n.length>0?n:null}function fp(e){if(!e)return null;const n=new URLSearchParams(e).get("edit");return n&&n.length>0&&n.startsWith("__")?n:null}function s7(e,t){const n=`/admin/templates/${encodeURIComponent(e)}/edit`;if(!t||t.length===0||t.startsWith("__"))return n;const o=t.replace(/^\*+/,"");return o.length===0?n:`${n}?route=${encodeURIComponent(o)}`}const a7="g7le-editor-route",l7=new Set;function ta(e){return e.path.startsWith("__group__/")||e.path.startsWith("__conngroup__/")}function gp(e,t){const{t:n,translationEngine:o,translationContext:r,templateIdentifier:s}=t,a=ta(e);if(!e.label.startsWith("$t:"))return e.label;const l=e.label.slice(3),d=l.indexOf("|"),c=d===-1?l:l.slice(0,d),p={};if(d!==-1)for(const b of l.slice(d+1).split("|")){const g=b.indexOf("=");g!==-1&&(p[b.slice(0,g)]=b.slice(g+1))}if((e.kind==="route"||e.kind==="modal")&&!a&&o&&r&&s!==r.templateId){const b={templateId:s,locale:r.locale},g=Object.keys(p).length>0?"|"+Object.entries(p).map(([h,v])=>`${h}=${v}`).join("|"):void 0,m=o.translate(c,b,g);if(m!==c)return m}const f=n(c,p);if(f===c&&typeof window<"u"){const b=window.G7Core?.t;if(typeof b=="function")try{const g=b(c,p);if(g!==c)return g}catch{}}if(f===c&&e.kind==="route"&&!a){const b=e.path;if(b&&b!=="/"){const g=b.split("/").filter(Boolean);return g[g.length-1]??b}return b==="/"?"/":c}return f}function d7(e){return e.trim().toLocaleLowerCase()}function hp(e,t){if(!t)return e;const n=e.toLocaleLowerCase(),o=[];let r=0,s=n.indexOf(t,r);if(s===-1)return e;let a=0;for(;s!==-1;)s>r&&o.push(e.slice(r,s)),o.push(i.jsx("mark",{className:"g7le-route-tree__highlight",style:{background:"#fde68a",color:"inherit",borderRadius:2,padding:"0 1px"},children:e.slice(s,s+t.length)},`m${a++}`)),r=s+t.length,s=n.indexOf(t,r);return r{const z=f.selectedRoute?.path??"";return z.startsWith("__extension__/")||z.startsWith("__modal__/")?z.slice(z.lastIndexOf("/")+1):null},[f.selectedRoute?.path]),h=u.useMemo(()=>!g||!m?!1:(e.children??[]).some(z=>z.kind==="extension"&&z.extensionId===m||z.kind==="modal"&&z.modalId===m),[g,m,e.children]),[v,y]=u.useState(!0);u.useEffect(()=>{h&&y(!1)},[h]);const _=f.editMode==="extension"?f.selectedRoute?.layoutName??null:null,w=e.kind==="extension"?bp(e,f.routeTree)??null:null,k=e.kind==="extension"&&o===e.path&&(_===null||w===null||_===w),x=f.editMode==="modal"&&o?.startsWith("__modal__/")?o.slice(o.lastIndexOf("/")+1):null,$=f.editMode==="modal"?f.selectedRoute?.layoutName??null:null,S=e.kind==="modal"&&!!x&&e.modalId===x&&($===null||e.modalHostLayout==null||$===e.modalHostLayout),C=e.kind!=="extension"&&e.kind!=="modal"&&o===e.path||k||S||e.kind==="route"&&!b&&r===e.path,E=(e.children?.length??0)>0&&(!g||l||!v),A=!b&&!!e.layoutName&&s.has(e.layoutName),N=b?void 0:e.kind==="extension"?e.extensionId?f.extensionVersions[e.extensionId]:void 0:e.layoutName?f.layoutVersions[e.layoutName]:void 0,D=()=>{if(g){y(z=>!z);return}b||n(e)},B=gp(e,{t:d,translationEngine:c,translationContext:p,templateIdentifier:f.templateIdentifier}),M=b?null:c7(e),O={paddingLeft:12+t*14,paddingRight:12,paddingTop:4,paddingBottom:4,opacity:e.isHidden?.55:1,cursor:g?"pointer":b?"default":"pointer",background:C?"#eff6ff":"transparent",borderLeft:C?"2px solid #2563eb":"2px solid transparent",fontWeight:b||C?600:400,fontSize:b?11:13,color:b?"#64748b":C?"#1d4ed8":"#1e293b",textTransform:b?"uppercase":"none",letterSpacing:b?.6:void 0,transition:"background-color 100ms, color 100ms",display:"flex",flexDirection:"column",alignItems:"stretch",gap:2,userSelect:"none"};return i.jsxs("li",{children:[i.jsxs("div",{"data-testid":b?"g7le-route-tree-group":"g7le-route-tree-item","data-route-path":e.path,"data-route-kind":e.kind,"data-conn-collapsed":g?l?"false":String(v):void 0,role:g||!b?"button":void 0,tabIndex:g||!b?0:void 0,"aria-expanded":g?l?!0:!v:void 0,onClick:D,onKeyDown:z=>{g&&(z.key==="Enter"||z.key===" ")?(z.preventDefault(),y(H=>!H)):!b&&(z.key==="Enter"||z.key===" ")&&(z.preventDefault(),n(e))},style:O,children:[i.jsxs("span",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[g&&i.jsx("span",{"aria-hidden":"true",style:{flex:"0 0 auto",fontSize:9,color:"#94a3b8",width:10,display:"inline-block"},children:l||!v?"▾":"▸"}),A&&i.jsx("span",{className:"g7le-route-tree__dirty-dot","data-testid":"g7le-route-tree-dirty",title:d("layout_editor.chrome.route_tree.badge.modified"),"aria-label":d("layout_editor.chrome.route_tree.badge.modified"),style:{width:7,height:7,borderRadius:"50%",background:"#f59e0b",flex:"0 0 auto"}}),b?B:hp(B,a),typeof N=="number"&&i.jsxs("span",{className:"g7le-route-tree__version-badge","data-testid":"g7le-route-tree-version",title:d("layout_editor.chrome.route_tree.badge.version_tooltip",{version:String(N)}),style:{flex:"0 0 auto",padding:"0 5px",fontSize:10,fontWeight:600,lineHeight:"16px",borderRadius:4,background:"#eef2ff",color:"#4f46e5",border:"1px solid #e0e7ff",letterSpacing:.2},children:["v",N]}),i.jsx(u7,{node:e})]}),M&&i.jsx("span",{className:"g7le-route-tree__layout-path","data-testid":"g7le-route-tree-layout-path",title:M,style:{fontSize:11,fontWeight:400,color:"#94a3b8",textTransform:"none",letterSpacing:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:hp(M,a)})]}),E&&i.jsx("ul",{style:{listStyle:"none",margin:0,padding:0},children:e.children.map(z=>i.jsx(yp,{node:z,depth:t+1,onSelect:n,selectedRoutePath:o,activeHostRoutePath:r,dirtyLayoutNames:s,query:a,forceExpand:l},z.path))})]})}function p7(e,t){if(!t||!t.startsWith("__"))return null;const n=t.startsWith("__modal__/"),o=t.startsWith("__extension__/");if(!n&&!o)return null;const r=t.slice(t.lastIndexOf("/")+1),s=a=>{for(const l of a){if(l.connectedHostRoutePath&&(n&&l.kind==="modal"&&l.modalId===r||o&&l.kind==="extension"&&l.extensionId===r))return l.connectedHostRoutePath;if(l.children&&l.children.length>0){const d=s(l.children);if(d)return d}}return null};return s(e)}function bp(e,t){if(e.connectedHostRoutePath){const n=mp(t,e.connectedHostRoutePath);if(n?.layoutName)return n.layoutName}if(e.extensionType==="overlay"&&e.extensionTargetName)return e.extensionTargetName}function mp(e,t){for(const n of e){if(n.kind==="route"&&n.path===t)return n;if(n.children&&n.children.length>0){const o=mp(n.children,t);if(o)return o}}return null}function vp(e,t,n){const o=[];for(const r of e){const s=ta(r),a=r.children&&r.children.length>0?vp(r.children,t,n):[];if(s){a.length>0&&o.push({...r,children:a});continue}const l=gp(r,n).toLocaleLowerCase(),d=r.path.toLocaleLowerCase();(l.includes(t)||!d.startsWith("__")&&d.includes(t)||a.length>0)&&o.push({...r,children:a})}return o}function f7(){const{t:e,translationEngine:t,translationContext:n}=tt(),{state:o,dispatch:r}=Qe(),a=Ft()?.dirtyLayoutNames??l7,[l,d]=u.useState(""),c=d7(l),p=u.useMemo(()=>c?vp(o.routeTree,c,{t:e,translationEngine:t,translationContext:n,templateIdentifier:o.templateIdentifier}):o.routeTree,[c,o.routeTree,o.templateIdentifier,e,t,n]),f=h=>{if(h.kind==="base"&&h.layoutName){r({type:"ENTER_BASE_EDIT",layoutName:h.layoutName});return}if(h.kind==="modal"&&h.modalId&&h.modalHostLayout){r({type:"ENTER_MODAL_EDIT",modalId:h.modalId,hostLayout:h.modalHostLayout});return}if(h.kind==="extension"&&h.extensionId){const v=bp(h,o.routeTree);r({type:"ENTER_EXTENSION_EDIT",extensionId:h.extensionId,extensionHost:v});return}if(r({type:"SELECT_ROUTE",route:{path:h.path,layoutName:h.layoutName}}),typeof window<"u"&&window.history?.pushState){const v=ea(o.templateIdentifier,h.path);`${window.location.pathname}${window.location.search}`!==v&&window.history.pushState({source:a7,routePath:h.path},"",v)}},b=o.selectedRoute?.path??null,g=u.useMemo(()=>p7(o.routeTree,b),[o.routeTree,b]);if(o.isRouteTreeCollapsed)return i.jsx("aside",{className:"g7le-route-tree g7le-route-tree--collapsed","data-testid":"g7le-route-tree-panel","data-collapsed":"true",style:{width:28,borderRight:"1px solid #e2e8f0",background:"#ffffff"}});const m=o.routeTree.length>0;return i.jsxs("aside",{className:"g7le-route-tree","data-testid":"g7le-route-tree-panel","data-collapsed":"false",style:{width:280,borderRight:"1px solid #e2e8f0",background:"#ffffff",position:"sticky",top:"var(--g7le-header-h, 0px)",alignSelf:"start",height:"calc(100vh - var(--g7le-header-h, 0px))",overflow:"hidden",minHeight:0,display:"flex",flexDirection:"column"},"aria-label":e("layout_editor.chrome.route_tree.panel_title"),children:[i.jsx("div",{className:"g7le-route-tree__title",style:{padding:"10px 14px",fontSize:12,fontWeight:600,color:"#475569",textTransform:"uppercase",letterSpacing:.6,borderBottom:"1px solid #e2e8f0",background:"#f8fafc",flex:"0 0 auto"},children:e("layout_editor.chrome.route_tree.panel_title")}),m&&i.jsxs("div",{className:"g7le-route-tree__search",style:{padding:"8px 10px",borderBottom:"1px solid #e2e8f0",background:"#ffffff",flex:"0 0 auto",position:"relative"},children:[i.jsx("input",{type:"text",className:"g7le-route-tree__search-input","data-testid":"g7le-route-tree-search",value:l,onChange:h=>d(h.target.value),placeholder:e("layout_editor.chrome.route_tree.search_placeholder"),"aria-label":e("layout_editor.chrome.route_tree.search_placeholder"),style:{width:"100%",boxSizing:"border-box",padding:l?"6px 26px 6px 10px":"6px 10px",fontSize:12,lineHeight:1.4,color:"#1e293b",border:"1px solid #cbd5e1",borderRadius:6,outline:"none",background:"#f8fafc"}}),l&&i.jsx("button",{type:"button",className:"g7le-route-tree__search-clear","data-testid":"g7le-route-tree-search-clear",onClick:()=>d(""),"aria-label":e("layout_editor.chrome.route_tree.search_clear"),title:e("layout_editor.chrome.route_tree.search_clear"),style:{position:"absolute",right:16,top:"50%",transform:"translateY(-50%)",width:18,height:18,display:"inline-flex",alignItems:"center",justifyContent:"center",border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:14,lineHeight:1,padding:0},children:"✕"})]}),!m&&i.jsx("div",{className:"g7le-route-tree__empty","data-testid":"g7le-route-tree-empty",style:{padding:16,fontSize:12,color:"#94a3b8",textAlign:"center"},children:e("layout_editor.chrome.route_tree.empty")}),m&&c&&p.length===0&&i.jsx("div",{className:"g7le-route-tree__no-results","data-testid":"g7le-route-tree-no-results",style:{padding:16,fontSize:12,color:"#94a3b8",textAlign:"center"},children:e("layout_editor.chrome.route_tree.search_no_results")}),m&&p.length>0&&i.jsx("nav",{className:"g7le-route-tree__scroll","data-testid":"g7le-route-tree-scroll",style:{flex:"1 1 auto",minHeight:0,overflowY:"auto"},children:i.jsx("ul",{style:{listStyle:"none",margin:0,padding:0},children:p.map(h=>i.jsx(yp,{node:h,depth:0,onSelect:f,selectedRoutePath:b,activeHostRoutePath:g,dirtyLayoutNames:a,query:c,forceExpand:!!c},h.path))})})]})}const g7=Lt().DynamicRenderer,na=Lt(),h7=na.ResponsiveProvider;na.useResponsive,na.ResponsiveContext;const y7=Lt().ActionDispatcher,_p=Lt(),b7=_p.DataSourceManager;_p.dataSourceManager;function Jr(e,t,n){const o=t??{},r=o.message||o.error||`HTTP ${e}`,s=o?.data?.required_permissions??o?.required_permissions;let a;return e===401?a="unauthorized":e===403?a="forbidden":e===404?a="not_found":e>=500?a="server_error":a="unknown",{kind:a,status:e,message:String(r),requiredPermissions:s?String(s):void 0,source:n}}function so(e,t){return{kind:"network",status:0,message:e instanceof Error?e.message:String(e??"Unknown network error"),source:t}}function xp(e){if(typeof e!="object"||e===null)return!1;const t=e;return typeof t.kind=="string"&&typeof t.status=="number"&&typeof t.message=="string"}function Re(e){if(!e)return[];const t=[],n=e.split(".");for(let o=0;o0&&(t.push({responsive:a}),o+=1);continue}const s=Number(r);Number.isFinite(s)&&Number.isInteger(s)&&s>=0&&t.push(s)}return t}function m7(e,t){if(!e)return{affordance:"none",targetPath:null};const n=v7(e);return n?_7(n)?{affordance:"dynamic_path",targetPath:n}:/^(https?:)?\/\//.test(n)?{affordance:"external_url",targetPath:n}:n.startsWith("/")?t?{affordance:t(n),targetPath:n}:{affordance:"route_not_in_tree",targetPath:n}:{affordance:"route_not_in_tree",targetPath:n}:{affordance:"none",targetPath:null}}function v7(e){const t=e.actions;if(Array.isArray(t)){for(const n of t)if(n&&typeof n=="object"&&n.handler==="navigate"){const o=n.params?.path;if(typeof o=="string"&&o.length>0)return o}}if(e.name==="A"||e.type==="A"){const n=e.props?.href;if(typeof n=="string"&&n.length>0)return n}return null}function _7(e){return/\{\{[\s\S]*?\}\}/.test(e)}function x7(e,t,n){const o=s=>!!(s?.iteration&&s.iteration.source!==void 0),r=s=>{if(!s)return s;const a=s.indexOf(".iteration."),l=s.indexOf(".sortable."),d=[a,l].filter(c=>c>=0).sort((c,p)=>c-p)[0];return d===void 0?s:s.slice(0,d)};return o(e)?{isIteration:!0,iterationSourcePath:r(n)}:n&&n.includes(".iteration.")?{isIteration:!0,iterationSourcePath:r(n)}:t.some(o)?{isIteration:!0,iterationSourcePath:r(n)}:{isIteration:!1,iterationSourcePath:null}}function w7(e,t){const n=a=>{const l=a?.iteration&&a.iteration.source;return typeof l=="string"&&l.length>0?l:null},o=n(e)??t.map(n).find(a=>a!==null)??null;if(o!==null){const a=S7(o);if(a!==null)return a}const r=[];if(typeof e.text=="string"&&r.push(...wp(e.text)),e.props&&typeof e.props=="object")for(const a of Object.values(e.props))typeof a=="string"&&r.push(...wp(a));return r.length===0?null:r.find(a=>!k7.has(a))??r[0]}const k7=new Set(["_local","_global","_computed","route","query","props","item","index","event","$event","$response","response"]);function wp(e){const t=[],n=/\{\{([\s\S]*?)\}\}/g;let o;for(;(o=n.exec(e))!==null;){const r=kp(o[1]);r!==null&&t.push(r)}return t}function S7(e){const t=e.replace(/\{\{|\}\}/g,"");return kp(t)}function kp(e){const t=/[A-Za-z_$][A-Za-z0-9_$]*/.exec(e.trim());return t?t[0]:null}function gn(e,t,n,o=[]){if(!e)return"none";if(id(e)||typeof e.slot=="string"||typeof e.__editorSlotName=="string")return"extension_point";if(t!=="route"&&Ri(e,t,n)){const s=e.__source?.kind;return s==="base"?"base":s==="partial"?"partial":s==="extension"?"extension":"base"}if(zb(e,o))return"data_bound";if(!Ri(e,t,n))return"none";const r=e.__source?.kind;return r==="base"?"base":r==="partial"?"partial":r==="extension"?"extension":"none"}function Sp(e){if(!e)return null;if(e.__source?.kind==="extension"&&typeof e.__source.extensionId=="number")return e.__source.extensionId;const t=e.__injectedProps;if(Array.isArray(t)&&t.length>0){const n=t[0]?.extensionId;if(typeof n=="number")return n}return null}function C7(e,t){if(t<=0)return e;const n=e.split(".");let o=0;const r=[];for(let s=0;s=t)break;r.push(a);continue}if(a==="iteration"||a==="sortable"){if(o>=t)break;r.push(a);continue}r.push(a);const l=n[s-1];if((l===void 0||l==="children")&&(o+=1),o>=t)break}return r.join(".")}function Cp(e,t,n,o){if(!e||!t)return t;const r=n(t),s=Lb(e,r,o);return s.length===r.length?t:C7(t,s.length)}function $p(e){return e==="none"||e==="data_bound"}function $7(e){const{rootNode:t,editMode:n,currentExtensionId:o,editableRootPath:r,pathParser:s=Re,resolveRouteMatch:a}=e,[l,d]=u.useState(null),[c,p]=u.useState(null),f=u.useCallback(_=>{if(_===null||n==="route")return!0;if(n==="iteration_item"||n==="modal"){if(!r||r.length===0)return!0;const $=s(_);return Ep($,r)}const w=oa(t,_,s);if(!w)return!0;const k=ra(t,_,s),x=gn(w,n,o,k);return x==="none"||x==="data_bound"},[t,s,n,o,r]),b=u.useCallback((_,w)=>{const x=(w?.currentTarget?.dataset??w?.dataset)?.editorPath??null,$=Cp(t,x,s,o);f($)&&d($)},[t,s,o,f]),g=u.useCallback((_,w)=>{if(_===null){p(null);return}const x=(w?.currentTarget?.dataset??w?.dataset)?.editorPath??null,$=Cp(t,x,s,o);if(!f($)){p(null);return}p($)},[t,s,o,f]),m=u.useCallback(()=>{d(null)},[]),h=u.useMemo(()=>{const _=oa(t,l,s),w=oa(t,c,s),k=_?ra(t,l,s):[];let x=gn(_,n,o,k);(n==="iteration_item"||n==="modal")&&l!==null&&_&&r&&r.length>0&&Ep(s(l),r)&&(sd(_)?x="data_bound":x==="data_bound"&&(x="none"));const{affordance:$,targetPath:S}=m7(_,a),C=x==="base"&&typeof _?.__source?.layout=="string"?_.__source.layout:null,T=x==="data_bound"&&_?w7(_,k):null,{isIteration:E,iterationSourcePath:A}=x==="data_bound"&&_?x7(_,k,l):{isIteration:!1,iterationSourcePath:null};return{selectedNode:_,hoverNode:w,selectedLockKind:x,selectedNavAffordance:$,selectedNavTargetPath:S,selectedBaseLayout:C,selectedDataSourceId:T,selectedIsIteration:E,selectedIterationSourcePath:A}},[t,l,c,n,o,r,s,a]),v=u.useRef(void 0);v.current!==l&&(v.current=l,Al({op:l===null?"clear":"select",componentPath:l,componentName:Ip(h.selectedNode),lockKind:h.selectedLockKind,navAffordance:h.selectedNavAffordance,sourceExtensionId:Sp(h.selectedNode),timestamp:Date.now()}));const y=u.useRef(void 0);return y.current!==c&&(y.current=c,c!==null&&Al({op:"hover",componentPath:c,componentName:Ip(h.hoverNode),lockKind:gn(h.hoverNode,n,o,ra(t,c,s)),navAffordance:"none",sourceExtensionId:Sp(h.hoverNode),timestamp:Date.now()})),{selectedPath:l,hoverPath:c,...h,handleSelect:b,handleHover:g,clearSelection:m}}function oa(e,t,n){if(!e||!t)return null;const o=n(t);return Be(e,o)}function Ep(e,t){if(e.length0?e.name:typeof e.type=="string"&&e.type.length>0?e.type:null:null}let Ap=0;function Tp(){return Ap}function ia(){Ap+=1}function E7(e){if(typeof e!="string")return null;const t="__modal__/";if(!e.startsWith(t))return null;const n=e.slice(t.length);return n===""||n.includes("/")?null:n}function I7(e){if(typeof e!="string")return null;const t="__iteration__/";if(!e.startsWith(t))return null;const n=e.slice(t.length);return n!==""?n:null}function Dp(){const{state:e}=Qe(),t=e.templateIdentifier,n=e.selectedRoute?.layoutName??null,o=e.editMode,r=o==="modal"?E7(e.selectedRoute?.path):null,s=o==="iteration_item"?I7(e.selectedRoute?.path):null,[a,l]=u.useState(null),[d,c]=u.useState(!1),[p,f]=u.useState(null),[b,g]=u.useState(!1),[m,h]=u.useState(0),[v,y]=u.useState(0),_=u.useRef(new Map),[w,k]=u.useState(()=>new Set),x=u.useCallback((P,I)=>`${P}|${I??""}`,[]),$=u.useRef(null);u.useEffect(()=>{$.current=a},[a]);const S=u.useCallback((P,I)=>{const L=x(o,n);_.current.set(L,{raw:P,lockVersion:I}),k(F=>{if(F.has(L))return F;const Y=new Set(F);return Y.add(L),Y})},[x,o,n]),C=u.useCallback(P=>{_.current.delete(P),k(I=>{if(!I.has(P))return I;const L=new Set(I);return L.delete(P),L})},[]),T=u.useCallback(P=>{const I=`|${P??""}`,L=[];for(const F of _.current.keys())F.endsWith(I)&&L.push(F);for(const F of L)_.current.delete(F);L.length>0&&k(F=>{let Y=!1;const K=new Set(F);for(const X of L)K.delete(X)&&(Y=!0);return Y?K:F})},[]),E=u.useCallback(async()=>{if(!n){l(null),f(null),g(!1);return}const P=x(o,n),I=_.current.get(P);if(I){l({layoutName:n,raw:I.raw,lockVersion:I.lockVersion}),g(!0),f(null),c(!1),st({op:"load",layoutName:n,editMode:o,statusCode:0,isDirty:!0,timestamp:Date.now()});return}c(!0),f(null);try{const L=window.G7Config?.cache_version??0,F=en(`/api/layouts/${encodeURIComponent(t)}/${n}`,"json",`${L}.${Tp()}`,"with_source_meta=1"),Y=cr(),K={Accept:"application/json"};Y&&(K.Authorization=`Bearer ${Y}`);const X=await fetch(F,{headers:K,credentials:"same-origin"}),Z=await X.json().catch(()=>null);if(!X.ok){f(Jr(X.status,Z,"layout")),l(null),g(!1);return}const ae=(Z&&(Z.data||Z))??{},oe=typeof ae.lock_version=="number"?ae.lock_version:0;if(o==="modal"&&r){const ee=ae,ge=Array.isArray(ee.modals)?ee.modals:[],V=ge.findIndex(te=>te&&(te.id===r||te.modal_id===r));if(V>=0){const te=ge[V],be={...te,props:{...te.props??{},isOpen:!0}},De=[...Array.isArray(ee.components)?ee.components:[],be],Se=[De.length-1];l({layoutName:n,raw:{...ee,components:De},lockVersion:oe,modalContext:{modalId:r,modalIndex:V,hostRaw:ee,originalModalNode:te,editIndexPath:Se}}),g(!1),st({op:"load",layoutName:n,editMode:o,statusCode:X.status,timestamp:Date.now()});return}}if(o==="iteration_item"&&s){const ee=ae,ge=Re(s),V={children:ee.components??[]},te=Be(V,ge);if(te&&Array.isArray(te.children)){l({layoutName:n,raw:ee,lockVersion:oe,iterationContext:{sourcePath:s,sourceIndexPath:ge,hostRaw:ee}}),g(!1),st({op:"load",layoutName:n,editMode:o,statusCode:X.status,timestamp:Date.now()});return}}l({layoutName:n,raw:ae,lockVersion:oe}),g(!1),st({op:"load",layoutName:n,editMode:o,statusCode:X.status,timestamp:Date.now()})}catch(L){f(so(L,"layout")),l(null),g(!1)}finally{c(!1)}},[t,n,o,r,s,x]);u.useEffect(()=>{E()},[E]);const A=u.useCallback(async()=>{C(x(o,n)),ia(),y(P=>P+1),await E()},[C,x,o,n,E]),N=u.useCallback(()=>{C(x(o,n))},[C,x,o,n]),D=u.useCallback(P=>{l(I=>{if(!I)return I;const L=I.raw.components??[],F=P(L),Y={...I.raw,components:F};return S(Y,I.lockVersion),{...I,raw:Y}}),g(!0),st({op:"patch",layoutName:n,editMode:o,isDirty:!0,timestamp:Date.now()})},[n,o,S]),B=u.useCallback(()=>{g(!0),st({op:"patch",layoutName:n,editMode:o,isDirty:!0,timestamp:Date.now()})},[n,o]),M=u.useCallback(P=>{l(I=>{if(!I)return I;const L={...I.raw,components:P};return S(L,I.lockVersion),{...I,raw:L}}),g(!0),st({op:"patch",layoutName:n,editMode:o,isDirty:!0,timestamp:Date.now()})},[n,o,S]),O=u.useCallback((P,I,...L)=>{const F=L.length>=1?L[0]:I;l(Y=>{if(!Y)return Y;const K={...Y.raw,[P]:I},X=Y.raw.__editor;if(X&&typeof X=="object"&&!Array.isArray(X)){const Z=X,ae=Z.original;ae&&typeof ae=="object"&&!Array.isArray(ae)&&(K.__editor={...Z,original:{...ae,[P]:F}})}return S(K,Y.lockVersion),{...Y,raw:K}}),g(!0),st({op:"patch",layoutName:n,editMode:o,isDirty:!0,timestamp:Date.now()})},[n,o,S]),z=u.useCallback(async P=>{const I=$.current;if(!I)return st({op:"save_guard_result",layoutName:n,editMode:o,guardBlocked:!1,timestamp:Date.now()}),{kind:"guard_no_document"};if(P?.resolveActiveExtensions&&P.sessionAddedPaths?.length)try{const ge=await P.resolveActiveExtensions(),V=A7(I.raw.components,P.sessionAddedPaths,ge);if(V.length>0)return st({op:"save_guard_result",layoutName:n,editMode:o,guardBlocked:!0,guardBlockedPaths:V,timestamp:Date.now()}),{kind:"blocked_inactive_extension",blockedPaths:V}}catch{}if(Yb())try{await Xb(t)}catch{}const L=`/api/admin/templates/${encodeURIComponent(t)}/layouts/${I.layoutName}`,F=cr(),Y={Accept:"application/json","Content-Type":"application/json"};F&&(Y.Authorization=`Bearer ${F}`);const K=!!I.modalContext,X=!!I.iterationContext,Z=K||X?"host_layout_modal_patch":"layout";st({op:"save",layoutName:I.layoutName,editMode:o,saveTarget:Z,endpoint:L,isDirty:b,timestamp:Date.now()});let ae;if(K&&I.modalContext){const{modalIndex:ge,hostRaw:V,originalModalNode:te,editIndexPath:be}=I.modalContext,Ee=Array.isArray(V.modals)?[...V.modals]:[],De=Array.isArray(I.raw.components)?I.raw.components:[],Se=be&&be.length===1?be[0]:0,Ue=De.length>Se?De[Se]:void 0,Me=Ue?Vn([Ue]):[],Oe=Me.length>0?{...Me[0]}:void 0;if(ge>=0&&ge({...ze,children:De})).children??[];ae={...Se,components:Ye}}else ae=_o(I.raw);const oe=ae;let G;try{G=await fetch(L,{method:"PUT",headers:Y,credentials:"same-origin",body:JSON.stringify({content:JSON.stringify(oe),expected_lock_version:I.lockVersion})})}catch(ge){const V=ge instanceof Error?ge.message:"network error";return st({op:"save_response",layoutName:I.layoutName,editMode:o,endpoint:L,statusCode:0,timestamp:Date.now()}),{kind:"network_error",message:V}}const ee=await G.json().catch(()=>null);if(st({op:"save_response",layoutName:I.layoutName,editMode:o,endpoint:L,statusCode:G.status,conflict:G.status===409?{currentVersion:ee?.current_version,yourVersion:ee?.your_version}:void 0,timestamp:Date.now()}),G.ok){const ge=typeof ee?.data?.lock_version=="number"?ee.data.lock_version:I.lockVersion+1;l({...I,lockVersion:ge}),g(!1),C(x(o,I.layoutName)),T(I.layoutName),ia(),h(te=>te+1);const V=typeof ee?.data?.current_version=="number"?ee.data.current_version:void 0;return{kind:"success",newLockVersion:ge,newContentVersion:V,savedLayoutName:I.layoutName}}return G.status===409?{kind:"concurrent_modification",currentVersion:ee?.current_version??-1,yourVersion:ee?.your_version??I.lockVersion}:G.status===422?{kind:"validation_failed",status:422,errors:ee?.errors??null}:{kind:"network_error",message:ee?.message??`HTTP ${G.status}`}},[t,n,o,b,C,T,x,r,s]),H=u.useMemo(()=>{const P=new Set,I="route|";for(const L of w)if(L.startsWith(I)){const F=L.slice(I.length);F&&P.add(F)}return P},[w]);return{document:a,isLoading:d,error:p,isDirty:b,saveSuccessCounter:m,reloadCounter:v,dirtyKeys:w,dirtyLayoutNames:H,invalidateCurrentCache:N,reload:A,patchLayout:D,setLayoutComponents:M,patchDocumentRaw:O,save:z,markDirty:B}}function A7(e,t,n){if(!e||e.length===0)return[];const o=[],r=new Set([...n.moduleIds,...n.pluginIds]);for(const s of t){const a=T7(e,s);if(!a)continue;const l=a.__source;if(!l||l.kind!=="extension")continue;const d=String(l.extensionId??"");d.length!==0&&(r.has(d)||o.push(s))}return o}function T7(e,t){const n=Re(t);return n.length===0?null:Be({children:e},n)}function ao(e,t){if(!e)return null;const n=e.getBoundingClientRect();if(n.width===0&&n.height===0)return null;if(!t)return{left:n.left,top:n.top,width:n.width,height:n.height,scale:1};const o=t.getBoundingClientRect();return{left:n.left-o.left,top:n.top-o.top,width:n.width,height:n.height,scale:1}}function lo(e,t){if(!e)return!1;if(!t)return!0;const n=t.getBoundingClientRect(),o=1;return!(e.left>=n.width-o||e.left+e.width<=o||e.top>=n.height-o||e.top+e.height<=o)}function zp(e,t){if(typeof window>"u")return()=>{};const n=()=>{e()};window.addEventListener("scroll",n,!0),window.addEventListener("resize",n);let o=null;t&&typeof ResizeObserver<"u"&&(o=new ResizeObserver(()=>e()),o.observe(t));let r=null,s=null;const a=typeof requestAnimationFrame<"u",l=()=>{if(!a){e();return}s===null&&(s=requestAnimationFrame(()=>{s=null,e()}))};return t&&typeof MutationObserver<"u"&&(r=new MutationObserver(l),r.observe(t,{childList:!0,subtree:!0})),()=>{window.removeEventListener("scroll",n,!0),window.removeEventListener("resize",n),o&&(o.disconnect(),o=null),r&&(r.disconnect(),r=null),s!==null&&a&&typeof cancelAnimationFrame<"u"&&(cancelAnimationFrame(s),s=null)}}const Np=44;function Mp(e){if(!e)return"inside";const t=e.scale||1,n=e.width*t,o=e.height*t;return n"u"||typeof window.getComputedStyle!="function")return{kind:"unknown",display:"",flexDirection:"",flexWrap:""};let t=e,n=(window.getComputedStyle(t).display??"").toLowerCase();for(;n==="contents"&&t.parentElement;)t=t.parentElement,n=(window.getComputedStyle(t).display??"").toLowerCase();const o=window.getComputedStyle(t),r=(o.display??"").toLowerCase(),s=(o.flexDirection??"").toLowerCase(),a=(o.flexWrap??"").toLowerCase(),l=r==="flex"||r==="inline-flex";if(r==="grid"||r==="inline-grid"){const f=Array.from(e.children).filter(h=>h.offsetParent!==null||h.getClientRects().length>0);if(f.length<=1)return{kind:"grid_2d",display:r,flexDirection:s,flexWrap:a};const b=f.map(h=>h.getBoundingClientRect()),g=new Set(b.map(h=>Math.round(h.top))),m=new Set(b.map(h=>Math.round(h.left)));return g.size===1?{kind:"grid_single_row",display:r,flexDirection:s,flexWrap:a}:m.size===1?{kind:"grid_single_column",display:r,flexDirection:s,flexWrap:a}:{kind:"grid_2d",display:r,flexDirection:s,flexWrap:a}}if(!l)return{kind:"block",display:r,flexDirection:s,flexWrap:a};const c=a==="wrap"||a==="wrap-reverse";return s==="column"||s==="column-reverse"?{kind:c?"flex_column_wrap":"flex_column_single",display:r,flexDirection:s,flexWrap:a}:{kind:c?"flex_row_wrap":"flex_row_single",display:r,flexDirection:s,flexWrap:a}}function z7(e){const{parentEl:t,selectedPath:n,selectedEl:o,explicitFlow:r}=e;return u.useMemo(()=>{if(!n||n.length===0)return{points:[],flow:"unknown"};const s=r??Op(t).kind,a=n.slice(0,-1),l=n[n.length-1]??0;if((s==="flex_row_wrap"||s==="flex_column_wrap"||s==="grid_2d")&&!!o){const p=N7(s,o,a,l);if(p)return{points:p,flow:s}}return{points:M7(s,a,l),flow:s}},[t,n,o,r])}function N7(e,t,n,o){let r=t.parentElement;for(;r&&Bp(r)==="contents";)r=r.parentElement;if(!r)return null;const s=[];if(Wp(r,s),s.length===0)return null;const a=t.getBoundingClientRect(),l=a.top+a.height/2,d=[],c=[],p=[];for(const v of s){const y=v.rect,_=y.top+y.height/2,w=Math.min(a.bottom,y.bottom)-Math.max(a.top,y.top),k=Math.min(a.height,y.height)||1;w/k>.4?d.push({rect:y,path:v.path}):_v.rect.left-y.rect.left),c.sort((v,y)=>v.rect.top-y.rect.top),p.sort((v,y)=>v.rect.top-y.rect.top);const f=d.findIndex(v=>Math.abs(v.rect.left-a.left)<1&&Math.abs(v.rect.top-a.top)<1),b={direction:"above",disabled:!0,insertion:null},g={direction:"below",disabled:!0,insertion:null},m={direction:"left",disabled:!0,insertion:null},h={direction:"right",disabled:!0,insertion:null};if(f>0){const v=d[f-1],y=Qr(v.path);y&&(m.disabled=!1,m.insertion=y)}else if(d.length>0){const v=d[0],y=Zr(v.path);y&&(m.disabled=!1,m.insertion=y)}if(f>=0&&f0){const v=d[d.length-1],y=Qr(v.path);y&&(h.disabled=!1,h.insertion=y)}if(c.length>0){const v=c[c.length-1],y=Qr(v.path);y&&(b.disabled=!1,b.insertion=y)}else if(s.length>0){const v=s[0],y=Zr(v.path);y&&(b.disabled=!1,b.insertion=y)}if(p.length>0){const v=p[0],y=Zr(v.path);y&&(g.disabled=!1,g.insertion=y)}else if(s.length>0){const v=s[s.length-1],y=Qr(v.path);y&&(g.disabled=!1,g.insertion=y)}else g.disabled=!1,g.insertion={parentPath:n,index:o+1};return b.disabled&&g.disabled&&m.disabled&&h.disabled?null:[b,g,m,h]}function Bp(e){return typeof window>"u"?"":(window.getComputedStyle(e).display??"").toLowerCase()}function Wp(e,t){const n=Array.from(e.children);for(const o of n){if(Bp(o)==="contents"){Wp(o,t);continue}const s=o.getAttribute("data-editor-path");if(s&&/\.iteration\.\d+(?:$|\.)/.test(s)||!s)continue;const a=o.getBoundingClientRect();a.width===0&&a.height===0||t.push({el:o,rect:a,path:Re(s)})}}function Zr(e){if(!e||e.length===0)return null;const t=e[e.length-1];return typeof t!="number"?null:{parentPath:e.slice(0,-1),index:t}}function Qr(e){if(!e||e.length===0)return null;const t=e[e.length-1];return typeof t!="number"?null:{parentPath:e.slice(0,-1),index:t+1}}function M7(e,t,n){const o={direction:"above",disabled:!0,insertion:null},r={direction:"below",disabled:!0,insertion:null},s={direction:"left",disabled:!0,insertion:null},a={direction:"right",disabled:!0,insertion:null},l=d=>({parentPath:t,index:d});switch(e){case"block":case"unknown":{o.disabled=!1,o.insertion=l(n),r.disabled=!1,r.insertion=l(n+1);break}case"flex_row_single":case"grid_single_row":{s.disabled=!1,s.insertion=l(n),a.disabled=!1,a.insertion=l(n+1);break}case"flex_column_single":case"grid_single_column":{o.disabled=!1,o.insertion=l(n),r.disabled=!1,r.insertion=l(n+1);break}case"flex_row_wrap":case"grid_2d":{s.disabled=!1,s.insertion=l(n),a.disabled=!1,a.insertion=l(n+1),o.disabled=!1,o.insertion=l(0),r.disabled=!1,r.insertion=l(-1);break}case"flex_column_wrap":{o.disabled=!1,o.insertion=l(n),r.disabled=!1,r.insertion=l(n+1),s.disabled=!1,s.insertion=l(0),a.disabled=!1,a.insertion=l(-1);break}}return[o,r,s,a]}function L7(e=50){const t=u.useRef([]),n=u.useRef(-1),[,o]=u.useState(0),r=()=>{o(p=>(p+1)%1e6)},s=(p,f)=>{const b=t.current.length,g=n.current;ey({op:p,actionKind:f?.actionKind,label:f?.label,stackSize:b,cursor:g,canUndo:g>0,canRedo:g>=0&&g{const b=t.current.slice(0,n.current+1);for(b.push(p);b.length>e;)b.shift();t.current=b,n.current=b.length-1,r(),s("push",p)},[e]),l=u.useCallback(()=>{if(n.current<=0)return null;n.current-=1,r();const p=t.current[n.current]??null;return s("undo",p??void 0),p},[]),d=u.useCallback(()=>{const p=n.current+1;if(p>=t.current.length)return null;n.current=p,r();const f=t.current[p]??null;return s("redo",f??void 0),f},[]),c=u.useCallback(()=>{t.current=[],n.current=-1,r(),s("clear")},[]);return{push:a,undo:l,redo:d,clear:c,canUndo:n.current>0,canRedo:n.current>=0&&n.current{if(!o||typeof window>"u")return;const r=s=>{if(P7(s.target)||!(s.ctrlKey||s.metaKey))return;const l=s.key.toLowerCase();if(l==="z"&&!s.shiftKey){s.preventDefault(),t();return}if(l==="z"&&s.shiftKey||l==="y"){s.preventDefault(),n();return}};return window.addEventListener("keydown",r),()=>{window.removeEventListener("keydown",r)}},[t,n,o])}const B7=20,jp=50,W7=90,Ln=120,j7=130,Hp=80,H7=9e3,Fp=1e4;function F7(e){const t=e<0?0:e>jp?jp:e;return B7+t}function K7(e){const{anchor:t,open:n,onClose:o,onEditProps:r,onDuplicate:s,onDelete:a,onSeparateBranch:l,separateBranchLabel:d,onMergeBranch:c,mergeBranchLabel:p}=e,{t:f}=tt(),[b,g]=u.useState(null);if(!n||!t)return null;const m=[{index:0,testid:"g7le-context-menu-edit-props",label:f("layout_editor.context_menu.edit_props"),onSelect:r},{index:1,testid:"g7le-context-menu-duplicate",label:f("layout_editor.context_menu.duplicate"),onSelect:s}];return l?m.push({index:m.length,testid:"g7le-context-menu-separate-branch",label:d??f("layout_editor.context_menu.separate_branch"),onSelect:l,hint:f("layout_editor.context_menu.separate_branch_hint")}):c&&m.push({index:m.length,testid:"g7le-context-menu-merge-branch",label:p??f("layout_editor.context_menu.merge_branch"),onSelect:c,hint:f("layout_editor.context_menu.merge_branch_hint")}),m.push({index:m.length,testid:"g7le-context-menu-delete",label:f("layout_editor.context_menu.delete"),onSelect:a,danger:!0}),i.jsx("div",{className:"g7le-context-menu","data-testid":"g7le-context-menu",role:"menu",style:{position:"absolute",left:t.left,top:t.top,background:"#fff",border:"1px solid #cbd5e1",borderRadius:6,boxShadow:"0 4px 12px rgba(0,0,0,0.15)",zIndex:1200,minWidth:160,padding:4,pointerEvents:"auto"},onMouseLeave:()=>{g(null),o()},children:m.map(h=>{const v=b===h.index,y=h.danger?"#dc2626":"#0f172a",_=h.danger?"#fee2e2":"#e0e7ff",w=h.danger?"#b91c1c":"#1d4ed8";return i.jsx("button",{type:"button",role:"menuitem","data-testid":h.testid,title:h.hint,onClick:k=>{k.stopPropagation(),h.onSelect(),g(null),o()},onMouseEnter:()=>g(h.index),onFocus:()=>g(h.index),style:{...V7,color:v?w:y,background:v?_:"transparent"},children:h.label},h.testid)})})}const V7={display:"block",width:"100%",textAlign:"left",padding:"6px 12px",border:"none",fontSize:13,cursor:"pointer",borderRadius:4,pointerEvents:"auto",transition:"background-color 120ms ease, color 120ms ease"};function U7(e){const{hoverBox:t,selectedBox:n,lockKind:o,navAffordance:r,onEditProps:s,onDuplicate:a,onDelete:l,onSeparateBranch:d,separateBranchLabel:c,onMergeBranch:p,mergeBranchLabel:f,definedDeviceBranches:b,onJumpToDevice:g,onLinkEditDestination:m,onEditBase:h,onEditExtension:v,extensionLabel:y,baseLayoutLabel:_,dataSourceLabel:w,branchLabel:k,onEditIteration:x,resizeEnabledAxes:$,onResizeHandlePointerDown:S,selectedName:C,onSelectParent:T}=e,{t:E}=tt(),[A,N]=u.useState(!1),D=$p(o),B=A&&D,M=Mp(n),O=M==="outside",z=O&&n?Pp(n):null,H=z?{left:z.right.left,top:z.above.top}:{right:-30,top:-30},P={top:-28,left:0},L=O&&!!C?{top:-50,left:0}:P,F=z?{top:z.below.top+28,left:0}:{top:"auto",bottom:-28},Y=z?{top:z.below.top+56,left:0}:{top:"auto",bottom:-56};return i.jsxs("div",{className:"g7le-element-overlay","data-testid":"g7le-element-overlay",style:{position:"absolute",inset:0,pointerEvents:"none"},children:[t&&i.jsx("div",{"data-testid":"g7le-overlay-hover",style:{position:"absolute",left:t.left,top:t.top,width:t.width,height:t.height,border:"1px dashed #2563eb",pointerEvents:"none"}}),n&&i.jsxs("div",{"data-testid":"g7le-overlay-selected","data-lock-kind":o,style:{position:"absolute",left:n.left,top:n.top,width:n.width,height:n.height,border:o==="none"?"2px solid #2563eb":"2px dashed #f59e0b",pointerEvents:"none"},children:[k?i.jsxs("span",{"data-testid":"g7le-overlay-branch-badge",style:G7,children:["📱 ",k]}):null,C&&(T?i.jsxs("button",{type:"button","data-testid":"g7le-overlay-type-label","data-placement":O?"outside":"inside",title:E("layout_editor.overlay.select_parent"),"aria-label":E("layout_editor.overlay.select_parent"),onClick:K=>{K.preventDefault(),K.stopPropagation(),T()},style:O?X7:Y7,children:[i.jsx("span",{"aria-hidden":!0,style:{marginRight:3,opacity:.85},children:"↑"}),C]}):i.jsx("span",{"data-testid":"g7le-overlay-type-label","data-placement":O?"outside":"inside",style:O?Vp:Kp,children:C})),D&&i.jsx("button",{type:"button","data-testid":"g7le-overlay-info-button","aria-label":"info",onClick:K=>{K.stopPropagation(),N(X=>!X)},"data-placement":M,style:{position:"absolute",...H,width:20,height:20,borderRadius:10,border:"1px solid #2563eb",background:"#fff",color:"#2563eb",fontSize:12,fontWeight:700,cursor:"pointer",pointerEvents:"auto",padding:0,lineHeight:"18px",zIndex:Ln},children:"ⓘ"}),o==="none"&&i.jsx(q7,{enabledAxes:$,onHandlePointerDown:S}),o==="base"&&h&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-edit-base",onClick:K=>{K.stopPropagation(),h()},style:{...Wo,...P},children:["🔒 ",E("layout_editor.overlay.edit_common_layout"),_?i.jsx("span",{"data-testid":"g7le-overlay-base-layout-label",style:aa,children:_}):null]}),o==="extension"&&v&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-edit-extension",onClick:K=>{K.stopPropagation(),v()},style:{...Wo,...P},children:["🔒 ",E("layout_editor.overlay.edit_extension"),y?i.jsx("span",{"data-testid":"g7le-overlay-extension-label",style:aa,children:y}):null]}),o==="data_bound"&&i.jsxs("span",{"data-testid":"g7le-overlay-data-bound-notice",style:{...Wo,...L,pointerEvents:"none",cursor:"default"},children:[E("layout_editor.overlay.locked_data_bound"),w?i.jsx("span",{"data-testid":"g7le-overlay-data-source-label",style:aa,children:w}):null]}),o==="data_bound"&&x&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-edit-iteration",onClick:K=>{K.stopPropagation(),x()},style:{...Wo,...F},children:["↳ ",E("layout_editor.overlay.edit_iteration_item")]}),r==="route_in_tree"&&i.jsx("button",{type:"button","data-testid":"g7le-overlay-link-edit-destination",onClick:K=>{K.stopPropagation(),m()},style:{...Wo,...F},children:E("layout_editor.overlay.edit_destination_route")}),(d||p||g&&(b??[]).length>0)&&i.jsxs("div",{"data-testid":"g7le-overlay-branch-affordances",style:{position:"absolute",...Y,display:"flex",flexDirection:"column",alignItems:"flex-start",gap:4,pointerEvents:"none"},children:[g&&(b??[]).map(K=>i.jsxs("button",{type:"button","data-testid":`g7le-overlay-jump-device-${K.key}`,title:E("layout_editor.overlay.jump_device_hint",{device:K.label}),onClick:X=>{X.stopPropagation(),g(K.key)},style:sa,children:["↗ ",E("layout_editor.overlay.jump_device",{device:K.label})]},K.key)),d&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-separate-branch",title:E("layout_editor.context_menu.separate_branch_hint"),onClick:K=>{K.stopPropagation(),d()},style:sa,children:["📱 ",c??E("layout_editor.context_menu.separate_branch")]}),p&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-merge-branch",title:E("layout_editor.context_menu.merge_branch_hint"),onClick:K=>{K.stopPropagation(),p()},style:sa,children:["↩️ ",f??E("layout_editor.context_menu.merge_branch")]})]})]}),i.jsx(K7,{anchor:n&&B?{left:n.left+n.width+8,top:n.top-4}:null,open:B,onClose:()=>N(!1),onEditProps:s,onDuplicate:a,onDelete:l,onSeparateBranch:d,separateBranchLabel:c,onMergeBranch:p,mergeBranchLabel:f})]})}function q7(e){const{enabledAxes:t,onHandlePointerDown:n}=e,o=t?.width??!1,r=t?.height??!1,s=[{key:"nw",style:{left:-4,top:-4},cursor:"nwse-resize",needsWidth:!0,needsHeight:!0},{key:"n",style:{left:"50%",top:-4,transform:"translateX(-50%)"},cursor:"ns-resize",needsWidth:!1,needsHeight:!0},{key:"ne",style:{right:-4,top:-4},cursor:"nesw-resize",needsWidth:!0,needsHeight:!0},{key:"e",style:{right:-4,top:"50%",transform:"translateY(-50%)"},cursor:"ew-resize",needsWidth:!0,needsHeight:!1},{key:"se",style:{right:-4,bottom:-4},cursor:"nwse-resize",needsWidth:!0,needsHeight:!0},{key:"s",style:{left:"50%",bottom:-4,transform:"translateX(-50%)"},cursor:"ns-resize",needsWidth:!1,needsHeight:!0},{key:"sw",style:{left:-4,bottom:-4},cursor:"nesw-resize",needsWidth:!0,needsHeight:!0},{key:"w",style:{left:-4,top:"50%",transform:"translateY(-50%)"},cursor:"ew-resize",needsWidth:!0,needsHeight:!1}];return i.jsx(i.Fragment,{children:s.map(a=>{const l=!a.needsWidth||o,d=!a.needsHeight||r,c=l&&d&&!!n;return!l||!d?null:i.jsx("span",{"data-testid":`g7le-resize-handle-${a.key}`,"data-resize-handle-active":c?"true":"false",onPointerDown:c?p=>{p.preventDefault(),p.stopPropagation(),n?.(a.key,{clientX:p.clientX,clientY:p.clientY})}:void 0,style:{position:"absolute",...a.style,width:8,height:8,background:"#fff",border:"1px solid #2563eb",cursor:a.cursor,pointerEvents:c?"auto":"none",zIndex:Ln}},a.key)})})}const Wo={position:"absolute",top:-28,left:0,background:"#fff",border:"1px solid #2563eb",color:"#2563eb",padding:"2px 6px",fontSize:11,borderRadius:4,cursor:"pointer",pointerEvents:"auto",whiteSpace:"nowrap",zIndex:Ln},sa={background:"#fff",border:"1px solid #2563eb",color:"#2563eb",padding:"2px 6px",fontSize:11,borderRadius:4,cursor:"pointer",pointerEvents:"auto",whiteSpace:"nowrap",zIndex:Ln},aa={marginLeft:6,padding:"0 5px",borderRadius:3,background:"#eef2ff",border:"1px solid #c7d2fe",fontSize:10,fontWeight:600,color:"#3730a3"},G7={position:"absolute",top:0,right:0,transform:"translateY(-100%)",background:"rgba(124,58,237,0.92)",color:"#fff",padding:"1px 6px",borderRadius:"3px 3px 0 0",fontSize:10,fontWeight:600,whiteSpace:"nowrap",pointerEvents:"none"},Kp={position:"absolute",top:0,left:0,background:"rgba(37,99,235,0.55)",color:"#fff",padding:"1px 6px",fontSize:10,fontWeight:600,lineHeight:"14px",borderBottomRightRadius:4,letterSpacing:"0.02em",whiteSpace:"nowrap",pointerEvents:"none",userSelect:"none",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis"},Vp={position:"absolute",bottom:"100%",left:0,marginBottom:2,background:"rgba(37,99,235,0.55)",color:"#fff",padding:"1px 6px",fontSize:10,fontWeight:600,lineHeight:"14px",borderRadius:4,letterSpacing:"0.02em",whiteSpace:"nowrap",pointerEvents:"none",userSelect:"none"},Y7={...Kp,pointerEvents:"auto",cursor:"pointer",background:"rgba(37,99,235,0.82)",border:"none",display:"inline-flex",alignItems:"center",font:"inherit",fontSize:10,fontWeight:600,zIndex:Ln},X7={...Vp,pointerEvents:"auto",cursor:"pointer",background:"rgba(37,99,235,0.82)",border:"none",display:"inline-flex",alignItems:"center",font:"inherit",fontSize:10,fontWeight:600,zIndex:Ln},J7={above:{top:-30,left:"50%",transform:"translateX(-50%)"},below:{bottom:-30,left:"50%",transform:"translateX(-50%)"},left:{left:-30,top:"50%",transform:"translateY(-50%)"},right:{right:-30,top:"50%",transform:"translateY(-50%)"}};function Z7(e){const{selectedBox:t,points:n,onAddRequest:o}=e,{t:r}=tt();if(!t||n.length===0)return null;const s=Mp(t),l=s==="outside"?Pp(t):null;return i.jsx("div",{className:"g7le-insertion-affordances","data-testid":"g7le-insertion-affordances",style:{position:"absolute",left:t.left,top:t.top,width:t.width,height:t.height,pointerEvents:"none"},children:n.map(d=>{const c=l?{left:l[d.direction].left,top:l[d.direction].top}:J7[d.direction],p=r(`layout_editor.insertion.${d.direction}`);return i.jsx("button",{type:"button",disabled:d.disabled,"data-testid":`g7le-insertion-${d.direction}`,"data-disabled":d.disabled?"true":"false","data-placement":s,"aria-label":p,title:p,onClick:f=>{f.stopPropagation(),d.disabled||o(d)},style:{position:"absolute",...c,width:24,height:24,borderRadius:12,border:"1px solid #2563eb",background:d.disabled?"#cbd5e1":"#fff",color:d.disabled?"#94a3b8":"#2563eb",cursor:d.disabled?"not-allowed":"pointer",opacity:d.disabled?.4:1,fontSize:16,fontWeight:700,lineHeight:"20px",padding:0,pointerEvents:"auto",boxShadow:"0 1px 3px rgba(0,0,0,0.15)",zIndex:Ln},children:"+"},d.direction)})})}const Rr=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function co(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function la(e){return"nodeType"in e}function xt(e){var t,n;return e?co(e)?e:la(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function da(e){const{Document:t}=xt(e);return e instanceof t}function jo(e){return co(e)?!1:e instanceof xt(e).HTMLElement}function Up(e){return e instanceof xt(e).SVGElement}function uo(e){return e?co(e)?e.document:la(e)?da(e)?e:jo(e)||Up(e)?e.ownerDocument:document:document:document}const sn=Rr?u.useLayoutEffect:u.useEffect;function ei(e){const t=u.useRef(e);return sn(()=>{t.current=e}),u.useCallback(function(){for(var n=arguments.length,o=new Array(n),r=0;r{e.current=setInterval(o,r)},[]),n=u.useCallback(()=>{e.current!==null&&(clearInterval(e.current),e.current=null)},[]);return[t,n]}function Ho(e,t){t===void 0&&(t=[e]);const n=u.useRef(e);return sn(()=>{n.current!==e&&(n.current=e)},t),n}function Fo(e,t){const n=u.useRef();return u.useMemo(()=>{const o=e(n.current);return n.current=o,o},[...t])}function ti(e){const t=ei(e),n=u.useRef(null),o=u.useCallback(r=>{r!==n.current&&t?.(r,n.current),n.current=r},[]);return[n,o]}function ni(e){const t=u.useRef();return u.useEffect(()=>{t.current=e},[e]),t.current}let ca={};function oi(e,t){return u.useMemo(()=>{if(t)return t;const n=ca[e]==null?0:ca[e]+1;return ca[e]=n,e+"-"+n},[e,t])}function qp(e){return function(t){for(var n=arguments.length,o=new Array(n>1?n-1:0),r=1;r{const l=Object.entries(a);for(const[d,c]of l){const p=s[d];p!=null&&(s[d]=p+e*c)}return s},{...t})}}const po=qp(1),ri=qp(-1);function R7(e){return"clientX"in e&&"clientY"in e}function ua(e){if(!e)return!1;const{KeyboardEvent:t}=xt(e.target);return t&&e instanceof t}function e2(e){if(!e)return!1;const{TouchEvent:t}=xt(e.target);return t&&e instanceof t}function ii(e){if(e2(e)){if(e.touches&&e.touches.length){const{clientX:t,clientY:n}=e.touches[0];return{x:t,y:n}}else if(e.changedTouches&&e.changedTouches.length){const{clientX:t,clientY:n}=e.changedTouches[0];return{x:t,y:n}}}return R7(e)?{x:e.clientX,y:e.clientY}:null}const Ko=Object.freeze({Translate:{toString(e){if(!e)return;const{x:t,y:n}=e;return"translate3d("+(t?Math.round(t):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(e){if(!e)return;const{scaleX:t,scaleY:n}=e;return"scaleX("+t+") scaleY("+n+")"}},Transform:{toString(e){if(e)return[Ko.Translate.toString(e),Ko.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:o}=e;return t+" "+n+"ms "+o}}}),Gp="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function t2(e){return e.matches(Gp)?e:e.querySelector(Gp)}const n2={display:"none"};function o2(e){let{id:t,value:n}=e;return u.createElement("div",{id:t,style:n2},n)}function r2(e){let{id:t,announcement:n,ariaLiveType:o="assertive"}=e;const r={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 u.createElement("div",{id:t,style:r,role:"status","aria-live":o,"aria-atomic":!0},n)}function i2(){const[e,t]=u.useState("");return{announce:u.useCallback(o=>{o!=null&&t(o)},[]),announcement:e}}const Yp=u.createContext(null);function s2(e){const t=u.useContext(Yp);u.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(e)},[e,t])}function a2(){const[e]=u.useState(()=>new Set),t=u.useCallback(o=>(e.add(o),()=>e.delete(o)),[e]);return[u.useCallback(o=>{let{type:r,event:s}=o;e.forEach(a=>{var l;return(l=a[r])==null?void 0:l.call(a,s)})},[e]),t]}const l2={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. - `},d2={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was moved over droppable area "+n.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was dropped over droppable area "+n.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function c2(e){let{announcements:t=d2,container:n,hiddenTextDescribedById:o,screenReaderInstructions:r=l2}=e;const{announce:s,announcement:a}=i2(),l=oi("DndLiveRegion"),[d,c]=u.useState(!1);if(u.useEffect(()=>{c(!0)},[]),s2(u.useMemo(()=>({onDragStart(f){let{active:b}=f;s(t.onDragStart({active:b}))},onDragMove(f){let{active:b,over:g}=f;t.onDragMove&&s(t.onDragMove({active:b,over:g}))},onDragOver(f){let{active:b,over:g}=f;s(t.onDragOver({active:b,over:g}))},onDragEnd(f){let{active:b,over:g}=f;s(t.onDragEnd({active:b,over:g}))},onDragCancel(f){let{active:b,over:g}=f;s(t.onDragCancel({active:b,over:g}))}}),[s,t])),!d)return null;const p=u.createElement(u.Fragment,null,u.createElement(o2,{id:o,value:r.draggable}),u.createElement(r2,{id:l,announcement:a}));return n?Cn.createPortal(p,n):p}var it;(function(e){e.DragStart="dragStart",e.DragMove="dragMove",e.DragEnd="dragEnd",e.DragCancel="dragCancel",e.DragOver="dragOver",e.RegisterDroppable="registerDroppable",e.SetDroppableDisabled="setDroppableDisabled",e.UnregisterDroppable="unregisterDroppable"})(it||(it={}));function si(){}function u2(e,t){return u.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function p2(){for(var e=arguments.length,t=new Array(e),n=0;n[...t].filter(o=>o!=null),[...t])}const Ht=Object.freeze({x:0,y:0});function f2(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function g2(e,t){const n=ii(e);if(!n)return"0 0";const o={x:(n.x-t.left)/t.width*100,y:(n.y-t.top)/t.height*100};return o.x+"% "+o.y+"%"}function h2(e,t){let{data:{value:n}}=e,{data:{value:o}}=t;return n-o}function y2(e,t){let{data:{value:n}}=e,{data:{value:o}}=t;return o-n}function b2(e){let{left:t,top:n,height:o,width:r}=e;return[{x:t,y:n},{x:t+r,y:n},{x:t,y:n+o},{x:t+r,y:n+o}]}function m2(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function v2(e,t){const n=Math.max(t.top,e.top),o=Math.max(t.left,e.left),r=Math.min(t.left+t.width,e.left+e.width),s=Math.min(t.top+t.height,e.top+e.height),a=r-o,l=s-n;if(o{let{collisionRect:t,droppableRects:n,droppableContainers:o}=e;const r=[];for(const s of o){const{id:a}=s,l=n.get(a);if(l){const d=v2(l,t);d>0&&r.push({id:a,data:{droppableContainer:s,value:d}})}}return r.sort(y2)};function x2(e,t){const{top:n,left:o,bottom:r,right:s}=t;return n<=e.y&&e.y<=r&&o<=e.x&&e.x<=s}const w2=e=>{let{droppableContainers:t,droppableRects:n,pointerCoordinates:o}=e;if(!o)return[];const r=[];for(const s of t){const{id:a}=s,l=n.get(a);if(l&&x2(o,l)){const c=b2(l).reduce((f,b)=>f+f2(o,b),0),p=Number((c/4).toFixed(4));r.push({id:a,data:{droppableContainer:s,value:p}})}}return r.sort(h2)};function k2(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function Xp(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:Ht}function S2(e){return function(n){for(var o=arguments.length,r=new Array(o>1?o-1:0),s=1;s({...a,top:a.top+e*l.y,bottom:a.bottom+e*l.y,left:a.left+e*l.x,right:a.right+e*l.x}),{...n})}}const C2=S2(1);function Jp(e){if(e.startsWith("matrix3d(")){const t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(e.startsWith("matrix(")){const t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function $2(e,t,n){const o=Jp(t);if(!o)return e;const{scaleX:r,scaleY:s,x:a,y:l}=o,d=e.left-a-(1-r)*parseFloat(n),c=e.top-l-(1-s)*parseFloat(n.slice(n.indexOf(" ")+1)),p=r?e.width/r:e.width,f=s?e.height/s:e.height;return{width:p,height:f,top:c,right:d+p,bottom:c+f,left:d}}const E2={ignoreTransform:!1};function Vo(e,t){t===void 0&&(t=E2);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:c,transformOrigin:p}=xt(e).getComputedStyle(e);c&&(n=$2(n,c,p))}const{top:o,left:r,width:s,height:a,bottom:l,right:d}=n;return{top:o,left:r,width:s,height:a,bottom:l,right:d}}function Zp(e){return Vo(e,{ignoreTransform:!0})}function I2(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function A2(e,t){return t===void 0&&(t=xt(e).getComputedStyle(e)),t.position==="fixed"}function T2(e,t){t===void 0&&(t=xt(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(r=>{const s=t[r];return typeof s=="string"?n.test(s):!1})}function pa(e,t){const n=[];function o(r){if(t!=null&&n.length>=t||!r)return n;if(da(r)&&r.scrollingElement!=null&&!n.includes(r.scrollingElement))return n.push(r.scrollingElement),n;if(!jo(r)||Up(r)||n.includes(r))return n;const s=xt(e).getComputedStyle(r);return r!==e&&T2(r,s)&&n.push(r),A2(r,s)?n:o(r.parentNode)}return e?o(e):n}function Qp(e){const[t]=pa(e,1);return t??null}function fa(e){return!Rr||!e?null:co(e)?e:la(e)?da(e)||e===uo(e).scrollingElement?window:jo(e)?e:null:null}function Rp(e){return co(e)?e.scrollX:e.scrollLeft}function ef(e){return co(e)?e.scrollY:e.scrollTop}function ga(e){return{x:Rp(e),y:ef(e)}}var lt;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(lt||(lt={}));function tf(e){return!Rr||!e?!1:e===document.scrollingElement}function nf(e){const t={x:0,y:0},n=tf(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},o={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},r=e.scrollTop<=t.y,s=e.scrollLeft<=t.x,a=e.scrollTop>=o.y,l=e.scrollLeft>=o.x;return{isTop:r,isLeft:s,isBottom:a,isRight:l,maxScroll:o,minScroll:t}}const D2={x:.2,y:.2};function z2(e,t,n,o,r){let{top:s,left:a,right:l,bottom:d}=n;o===void 0&&(o=10),r===void 0&&(r=D2);const{isTop:c,isBottom:p,isLeft:f,isRight:b}=nf(e),g={x:0,y:0},m={x:0,y:0},h={height:t.height*r.y,width:t.width*r.x};return!c&&s<=t.top+h.height?(g.y=lt.Backward,m.y=o*Math.abs((t.top+h.height-s)/h.height)):!p&&d>=t.bottom-h.height&&(g.y=lt.Forward,m.y=o*Math.abs((t.bottom-h.height-d)/h.height)),!b&&l>=t.right-h.width?(g.x=lt.Forward,m.x=o*Math.abs((t.right-h.width-l)/h.width)):!f&&a<=t.left+h.width&&(g.x=lt.Backward,m.x=o*Math.abs((t.left+h.width-a)/h.width)),{direction:g,speed:m}}function N2(e){if(e===document.scrollingElement){const{innerWidth:s,innerHeight:a}=window;return{top:0,left:0,right:s,bottom:a,width:s,height:a}}const{top:t,left:n,right:o,bottom:r}=e.getBoundingClientRect();return{top:t,left:n,right:o,bottom:r,width:e.clientWidth,height:e.clientHeight}}function of(e){return e.reduce((t,n)=>po(t,ga(n)),Ht)}function M2(e){return e.reduce((t,n)=>t+Rp(n),0)}function L2(e){return e.reduce((t,n)=>t+ef(n),0)}function rf(e,t){if(t===void 0&&(t=Vo),!e)return;const{top:n,left:o,bottom:r,right:s}=t(e);Qp(e)&&(r<=0||s<=0||n>=window.innerHeight||o>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const P2=[["x",["left","right"],M2],["y",["top","bottom"],L2]];class ha{constructor(t,n){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 o=pa(n),r=of(o);this.rect={...t},this.width=t.width,this.height=t.height;for(const[s,a,l]of P2)for(const d of a)Object.defineProperty(this,d,{get:()=>{const c=l(o),p=r[s]-c;return this.rect[d]+p},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Uo{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var o;return(o=this.target)==null?void 0:o.removeEventListener(...n)})},this.target=t}add(t,n,o){var r;(r=this.target)==null||r.addEventListener(t,n,o),this.listeners.push([t,n,o])}}function O2(e){const{EventTarget:t}=xt(e);return e instanceof t?e:uo(e)}function ya(e,t){const n=Math.abs(e.x),o=Math.abs(e.y);return typeof t=="number"?Math.sqrt(n**2+o**2)>t:"x"in t&&"y"in t?n>t.x&&o>t.y:"x"in t?n>t.x:"y"in t?o>t.y:!1}var At;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(At||(At={}));function sf(e){e.preventDefault()}function B2(e){e.stopPropagation()}var Fe;(function(e){e.Space="Space",e.Down="ArrowDown",e.Right="ArrowRight",e.Left="ArrowLeft",e.Up="ArrowUp",e.Esc="Escape",e.Enter="Enter",e.Tab="Tab"})(Fe||(Fe={}));const af={start:[Fe.Space,Fe.Enter],cancel:[Fe.Esc],end:[Fe.Space,Fe.Enter,Fe.Tab]},W2=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case Fe.Right:return{...n,x:n.x+25};case Fe.Left:return{...n,x:n.x-25};case Fe.Down:return{...n,y:n.y+25};case Fe.Up:return{...n,y:n.y-25}}};class lf{constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:n}}=t;this.props=t,this.listeners=new Uo(uo(n)),this.windowListeners=new Uo(xt(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(At.Resize,this.handleCancel),this.windowListeners.add(At.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(At.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,o=t.node.current;o&&rf(o),n(Ht)}handleKeyDown(t){if(ua(t)){const{active:n,context:o,options:r}=this.props,{keyboardCodes:s=af,coordinateGetter:a=W2,scrollBehavior:l="smooth"}=r,{code:d}=t;if(s.end.includes(d)){this.handleEnd(t);return}if(s.cancel.includes(d)){this.handleCancel(t);return}const{collisionRect:c}=o.current,p=c?{x:c.left,y:c.top}:Ht;this.referenceCoordinates||(this.referenceCoordinates=p);const f=a(t,{active:n,context:o.current,currentCoordinates:p});if(f){const b=ri(f,p),g={x:0,y:0},{scrollableAncestors:m}=o.current;for(const h of m){const v=t.code,{isTop:y,isRight:_,isLeft:w,isBottom:k,maxScroll:x,minScroll:$}=nf(h),S=N2(h),C={x:Math.min(v===Fe.Right?S.right-S.width/2:S.right,Math.max(v===Fe.Right?S.left:S.left+S.width/2,f.x)),y:Math.min(v===Fe.Down?S.bottom-S.height/2:S.bottom,Math.max(v===Fe.Down?S.top:S.top+S.height/2,f.y))},T=v===Fe.Right&&!_||v===Fe.Left&&!w,E=v===Fe.Down&&!k||v===Fe.Up&&!y;if(T&&C.x!==f.x){const A=h.scrollLeft+b.x,N=v===Fe.Right&&A<=x.x||v===Fe.Left&&A>=$.x;if(N&&!b.y){h.scrollTo({left:A,behavior:l});return}N?g.x=h.scrollLeft-A:g.x=v===Fe.Right?h.scrollLeft-x.x:h.scrollLeft-$.x,g.x&&h.scrollBy({left:-g.x,behavior:l});break}else if(E&&C.y!==f.y){const A=h.scrollTop+b.y,N=v===Fe.Down&&A<=x.y||v===Fe.Up&&A>=$.y;if(N&&!b.x){h.scrollTo({top:A,behavior:l});return}N?g.y=h.scrollTop-A:g.y=v===Fe.Down?h.scrollTop-x.y:h.scrollTop-$.y,g.y&&h.scrollBy({top:-g.y,behavior:l});break}}this.handleMove(t,po(ri(f,this.referenceCoordinates),g))}}}handleMove(t,n){const{onMove:o}=this.props;t.preventDefault(),o(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}lf.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:o=af,onActivation:r}=t,{active:s}=n;const{code:a}=e.nativeEvent;if(o.start.includes(a)){const l=s.activatorNode.current;return l&&e.target!==l?!1:(e.preventDefault(),r?.({event:e.nativeEvent}),!0)}return!1}}];function df(e){return!!(e&&"distance"in e)}function cf(e){return!!(e&&"delay"in e)}class ba{constructor(t,n,o){var r;o===void 0&&(o=O2(t.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=t,this.events=n;const{event:s}=t,{target:a}=s;this.props=t,this.events=n,this.document=uo(a),this.documentListeners=new Uo(this.document),this.listeners=new Uo(o),this.windowListeners=new Uo(xt(a)),this.initialCoordinates=(r=ii(s))!=null?r:Ht,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:t,props:{options:{activationConstraint:n,bypassActivationConstraint:o}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),t.cancel&&this.listeners.add(t.cancel.name,this.handleCancel),this.windowListeners.add(At.Resize,this.handleCancel),this.windowListeners.add(At.DragStart,sf),this.windowListeners.add(At.VisibilityChange,this.handleCancel),this.windowListeners.add(At.ContextMenu,sf),this.documentListeners.add(At.Keydown,this.handleKeydown),n){if(o!=null&&o({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(cf(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(df(n)){this.handlePending(n);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(t,n){const{active:o,onPending:r}=this.props;r(o,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(At.Click,B2,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(At.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:o,initialCoordinates:r,props:s}=this,{onMove:a,options:{activationConstraint:l}}=s;if(!r)return;const d=(n=ii(t))!=null?n:Ht,c=ri(r,d);if(!o&&l){if(df(l)){if(l.tolerance!=null&&ya(c,l.tolerance))return this.handleCancel();if(ya(c,l.distance))return this.handleStart()}if(cf(l)&&ya(c,l.tolerance))return this.handleCancel();this.handlePending(l,c);return}t.cancelable&&t.preventDefault(),a(d)}handleEnd(){const{onAbort:t,onEnd:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleCancel(){const{onAbort:t,onCancel:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleKeydown(t){t.code===Fe.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const j2={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class ma extends ba{constructor(t){const{event:n}=t,o=uo(n.target);super(t,j2,o)}}ma.activators=[{eventName:"onPointerDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:o}=t;return!n.isPrimary||n.button!==0?!1:(o?.({event:n}),!0)}}];const H2={move:{name:"mousemove"},end:{name:"mouseup"}};var va;(function(e){e[e.RightClick=2]="RightClick"})(va||(va={}));class F2 extends ba{constructor(t){super(t,H2,uo(t.event.target))}}F2.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:o}=t;return n.button===va.RightClick?!1:(o?.({event:n}),!0)}}];const _a={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class K2 extends ba{constructor(t){super(t,_a)}static setup(){return window.addEventListener(_a.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(_a.move.name,t)};function t(){}}}K2.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:o}=t;const{touches:r}=n;return r.length>1?!1:(o?.({event:n}),!0)}}];var qo;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(qo||(qo={}));var ai;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(ai||(ai={}));function V2(e){let{acceleration:t,activator:n=qo.Pointer,canScroll:o,draggingRect:r,enabled:s,interval:a=5,order:l=ai.TreeOrder,pointerCoordinates:d,scrollableAncestors:c,scrollableAncestorRects:p,delta:f,threshold:b}=e;const g=q2({delta:f,disabled:!s}),[m,h]=Q7(),v=u.useRef({x:0,y:0}),y=u.useRef({x:0,y:0}),_=u.useMemo(()=>{switch(n){case qo.Pointer:return d?{top:d.y,bottom:d.y,left:d.x,right:d.x}:null;case qo.DraggableRect:return r}},[n,r,d]),w=u.useRef(null),k=u.useCallback(()=>{const $=w.current;if(!$)return;const S=v.current.x*y.current.x,C=v.current.y*y.current.y;$.scrollBy(S,C)},[]),x=u.useMemo(()=>l===ai.TreeOrder?[...c].reverse():c,[l,c]);u.useEffect(()=>{if(!s||!c.length||!_){h();return}for(const $ of x){if(o?.($)===!1)continue;const S=c.indexOf($),C=p[S];if(!C)continue;const{direction:T,speed:E}=z2($,C,_,t,b);for(const A of["x","y"])g[A][T[A]]||(E[A]=0,T[A]=0);if(E.x>0||E.y>0){h(),w.current=$,m(k,a),v.current=E,y.current=T;return}}v.current={x:0,y:0},y.current={x:0,y:0},h()},[t,k,o,h,s,a,JSON.stringify(_),JSON.stringify(g),m,c,x,p,JSON.stringify(b)])}const U2={x:{[lt.Backward]:!1,[lt.Forward]:!1},y:{[lt.Backward]:!1,[lt.Forward]:!1}};function q2(e){let{delta:t,disabled:n}=e;const o=ni(t);return Fo(r=>{if(n||!o||!r)return U2;const s={x:Math.sign(t.x-o.x),y:Math.sign(t.y-o.y)};return{x:{[lt.Backward]:r.x[lt.Backward]||s.x===-1,[lt.Forward]:r.x[lt.Forward]||s.x===1},y:{[lt.Backward]:r.y[lt.Backward]||s.y===-1,[lt.Forward]:r.y[lt.Forward]||s.y===1}}},[n,t,o])}function G2(e,t){const n=t!=null?e.get(t):void 0,o=n?n.node.current:null;return Fo(r=>{var s;return t==null?null:(s=o??r)!=null?s:null},[o,t])}function Y2(e,t){return u.useMemo(()=>e.reduce((n,o)=>{const{sensor:r}=o,s=r.activators.map(a=>({eventName:a.eventName,handler:t(a.handler,o)}));return[...n,...s]},[]),[e,t])}var Go;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Go||(Go={}));var xa;(function(e){e.Optimized="optimized"})(xa||(xa={}));const uf=new Map;function X2(e,t){let{dragging:n,dependencies:o,config:r}=t;const[s,a]=u.useState(null),{frequency:l,measure:d,strategy:c}=r,p=u.useRef(e),f=v(),b=Ho(f),g=u.useCallback(function(y){y===void 0&&(y=[]),!b.current&&a(_=>_===null?y:_.concat(y.filter(w=>!_.includes(w))))},[b]),m=u.useRef(null),h=Fo(y=>{if(f&&!n)return uf;if(!y||y===uf||p.current!==e||s!=null){const _=new Map;for(let w of e){if(!w)continue;if(s&&s.length>0&&!s.includes(w.id)&&w.rect.current){_.set(w.id,w.rect.current);continue}const k=w.node.current,x=k?new ha(d(k),k):null;w.rect.current=x,x&&_.set(w.id,x)}return _}return y},[e,s,n,f,d]);return u.useEffect(()=>{p.current=e},[e]),u.useEffect(()=>{f||g()},[n,f]),u.useEffect(()=>{s&&s.length>0&&a(null)},[JSON.stringify(s)]),u.useEffect(()=>{f||typeof l!="number"||m.current!==null||(m.current=setTimeout(()=>{g(),m.current=null},l))},[l,f,g,...o]),{droppableRects:h,measureDroppableContainers:g,measuringScheduled:s!=null};function v(){switch(c){case Go.Always:return!1;case Go.BeforeDragging:return n;default:return!n}}}function wa(e,t){return Fo(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function J2(e,t){return wa(e,t)}function Z2(e){let{callback:t,disabled:n}=e;const o=ei(t),r=u.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:s}=window;return new s(o)},[o,n]);return u.useEffect(()=>()=>r?.disconnect(),[r]),r}function li(e){let{callback:t,disabled:n}=e;const o=ei(t),r=u.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:s}=window;return new s(o)},[n]);return u.useEffect(()=>()=>r?.disconnect(),[r]),r}function Q2(e){return new ha(Vo(e),e)}function pf(e,t,n){t===void 0&&(t=Q2);const[o,r]=u.useState(null);function s(){r(d=>{if(!e)return null;if(e.isConnected===!1){var c;return(c=d??n)!=null?c:null}const p=t(e);return JSON.stringify(d)===JSON.stringify(p)?d:p})}const a=Z2({callback(d){if(e)for(const c of d){const{type:p,target:f}=c;if(p==="childList"&&f instanceof HTMLElement&&f.contains(e)){s();break}}}}),l=li({callback:s});return sn(()=>{s(),e?(l?.observe(e),a?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),a?.disconnect())},[e]),o}function R2(e){const t=wa(e);return Xp(e,t)}const ff=[];function eI(e){const t=u.useRef(e),n=Fo(o=>e?o&&o!==ff&&e&&t.current&&e.parentNode===t.current.parentNode?o:pa(e):ff,[e]);return u.useEffect(()=>{t.current=e},[e]),n}function tI(e){const[t,n]=u.useState(null),o=u.useRef(e),r=u.useCallback(s=>{const a=fa(s.target);a&&n(l=>l?(l.set(a,ga(a)),new Map(l)):null)},[]);return u.useEffect(()=>{const s=o.current;if(e!==s){a(s);const l=e.map(d=>{const c=fa(d);return c?(c.addEventListener("scroll",r,{passive:!0}),[c,ga(c)]):null}).filter(d=>d!=null);n(l.length?new Map(l):null),o.current=e}return()=>{a(e),a(s)};function a(l){l.forEach(d=>{const c=fa(d);c?.removeEventListener("scroll",r)})}},[r,e]),u.useMemo(()=>e.length?t?Array.from(t.values()).reduce((s,a)=>po(s,a),Ht):of(e):Ht,[e,t])}function gf(e,t){t===void 0&&(t=[]);const n=u.useRef(null);return u.useEffect(()=>{n.current=null},t),u.useEffect(()=>{const o=e!==Ht;o&&!n.current&&(n.current=e),!o&&n.current&&(n.current=null)},[e]),n.current?ri(e,n.current):Ht}function nI(e){u.useEffect(()=>{if(!Rr)return;const t=e.map(n=>{let{sensor:o}=n;return o.setup==null?void 0:o.setup()});return()=>{for(const n of t)n?.()}},e.map(t=>{let{sensor:n}=t;return n}))}function oI(e,t){return u.useMemo(()=>e.reduce((n,o)=>{let{eventName:r,handler:s}=o;return n[r]=a=>{s(a,t)},n},{}),[e,t])}function hf(e){return u.useMemo(()=>e?I2(e):null,[e])}const yf=[];function rI(e,t){t===void 0&&(t=Vo);const[n]=e,o=hf(n?xt(n):null),[r,s]=u.useState(yf);function a(){s(()=>e.length?e.map(d=>tf(d)?o:new ha(t(d),d)):yf)}const l=li({callback:a});return sn(()=>{l?.disconnect(),a(),e.forEach(d=>l?.observe(d))},[e]),r}function bf(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return jo(t)?t:e}function iI(e){let{measure:t}=e;const[n,o]=u.useState(null),r=u.useCallback(c=>{for(const{target:p}of c)if(jo(p)){o(f=>{const b=t(p);return f?{...f,width:b.width,height:b.height}:b});break}},[t]),s=li({callback:r}),a=u.useCallback(c=>{const p=bf(c);s?.disconnect(),p&&s?.observe(p),o(p?t(p):null)},[t,s]),[l,d]=ti(a);return u.useMemo(()=>({nodeRef:l,rect:n,setRef:d}),[n,l,d])}const sI=[{sensor:ma,options:{}},{sensor:lf,options:{}}],aI={current:{}},di={draggable:{measure:Zp},droppable:{measure:Zp,strategy:Go.WhileDragging,frequency:xa.Optimized},dragOverlay:{measure:Vo}};class Yo extends Map{get(t){var n;return t!=null&&(n=super.get(t))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:n}=t;return!n})}getNodeFor(t){var n,o;return(n=(o=this.get(t))==null?void 0:o.node.current)!=null?n:void 0}}const lI={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Yo,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:si},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:di,measureDroppableContainers:si,windowRect:null,measuringScheduled:!1},mf={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:si,draggableNodes:new Map,over:null,measureDroppableContainers:si},Xo=u.createContext(mf),vf=u.createContext(lI);function dI(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Yo}}}function cI(e,t){switch(t.type){case it.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case it.DragMove:return e.draggable.active==null?e:{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}};case it.DragEnd:case it.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case it.RegisterDroppable:{const{element:n}=t,{id:o}=n,r=new Yo(e.droppable.containers);return r.set(o,n),{...e,droppable:{...e.droppable,containers:r}}}case it.SetDroppableDisabled:{const{id:n,key:o,disabled:r}=t,s=e.droppable.containers.get(n);if(!s||o!==s.key)return e;const a=new Yo(e.droppable.containers);return a.set(n,{...s,disabled:r}),{...e,droppable:{...e.droppable,containers:a}}}case it.UnregisterDroppable:{const{id:n,key:o}=t,r=e.droppable.containers.get(n);if(!r||o!==r.key)return e;const s=new Yo(e.droppable.containers);return s.delete(n),{...e,droppable:{...e.droppable,containers:s}}}default:return e}}function uI(e){let{disabled:t}=e;const{active:n,activatorEvent:o,draggableNodes:r}=u.useContext(Xo),s=ni(o),a=ni(n?.id);return u.useEffect(()=>{if(!t&&!o&&s&&a!=null){if(!ua(s)||document.activeElement===s.target)return;const l=r.get(a);if(!l)return;const{activatorNode:d,node:c}=l;if(!d.current&&!c.current)return;requestAnimationFrame(()=>{for(const p of[d.current,c.current]){if(!p)continue;const f=t2(p);if(f){f.focus();break}}})}},[o,t,r,a,s]),null}function _f(e,t){let{transform:n,...o}=t;return e!=null&&e.length?e.reduce((r,s)=>s({transform:r,...o}),n):n}function pI(e){return u.useMemo(()=>({draggable:{...di.draggable,...e?.draggable},droppable:{...di.droppable,...e?.droppable},dragOverlay:{...di.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function fI(e){let{activeNode:t,measure:n,initialRect:o,config:r=!0}=e;const s=u.useRef(!1),{x:a,y:l}=typeof r=="boolean"?{x:r,y:r}:r;sn(()=>{if(!a&&!l||!t){s.current=!1;return}if(s.current||!o)return;const c=t?.node.current;if(!c||c.isConnected===!1)return;const p=n(c),f=Xp(p,o);if(a||(f.x=0),l||(f.y=0),s.current=!0,Math.abs(f.x)>0||Math.abs(f.y)>0){const b=Qp(c);b&&b.scrollBy({top:f.y,left:f.x})}},[t,a,l,o,n])}const ci=u.createContext({...Ht,scaleX:1,scaleY:1});var hn;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(hn||(hn={}));const gI=u.memo(function(t){var n,o,r,s;let{id:a,accessibility:l,autoScroll:d=!0,children:c,sensors:p=sI,collisionDetection:f=_2,measuring:b,modifiers:g,...m}=t;const h=u.useReducer(cI,void 0,dI),[v,y]=h,[_,w]=a2(),[k,x]=u.useState(hn.Uninitialized),$=k===hn.Initialized,{draggable:{active:S,nodes:C,translate:T},droppable:{containers:E}}=v,A=S!=null?C.get(S):null,N=u.useRef({initial:null,translated:null}),D=u.useMemo(()=>{var Q;return S!=null?{id:S,data:(Q=A?.data)!=null?Q:aI,rect:N}:null},[S,A]),B=u.useRef(null),[M,O]=u.useState(null),[z,H]=u.useState(null),P=Ho(m,Object.values(m)),I=oi("DndDescribedBy",a),L=u.useMemo(()=>E.getEnabled(),[E]),F=pI(b),{droppableRects:Y,measureDroppableContainers:K,measuringScheduled:X}=X2(L,{dragging:$,dependencies:[T.x,T.y],config:F.droppable}),Z=G2(C,S),se=u.useMemo(()=>z?ii(z):null,[z]),oe=pe(),G=J2(Z,F.draggable.measure);fI({activeNode:S!=null?C.get(S):null,config:oe.layoutShiftCompensation,initialRect:G,measure:F.draggable.measure});const ee=pf(Z,F.draggable.measure,G),ge=pf(Z?Z.parentElement:null),V=u.useRef({activatorEvent:null,active:null,activeNode:Z,collisionRect:null,collisions:null,droppableRects:Y,draggableNodes:C,draggingNode:null,draggingNodeRect:null,droppableContainers:E,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),te=E.getNodeFor((n=V.current.over)==null?void 0:n.id),be=iI({measure:F.dragOverlay.measure}),Ee=(o=be.nodeRef.current)!=null?o:Z,De=$?(r=be.rect)!=null?r:ee:null,Se=!!(be.nodeRef.current&&be.rect),Ue=R2(Se?null:ee),Me=hf(Ee?xt(Ee):null),Oe=eI($?te??Z:null),Ye=rI(Oe),ze=_f(g,{transform:{x:T.x-Ue.x,y:T.y-Ue.y,scaleX:1,scaleY:1},activatorEvent:z,active:D,activeNodeRect:ee,containerNodeRect:ge,draggingNodeRect:De,over:V.current.over,overlayNodeRect:be.rect,scrollableAncestors:Oe,scrollableAncestorRects:Ye,windowRect:Me}),Xe=se?po(se,T):null,ve=tI(Oe),qe=gf(ve),We=gf(ve,[ee]),ce=po(ze,qe),q=De?C2(De,ze):null,re=D&&q?f({active:D,collisionRect:q,droppableRects:Y,droppableContainers:L,pointerCoordinates:Xe}):null,ie=m2(re,"id"),[me,Ce]=u.useState(null),$e=Se?ze:po(ze,We),U=k2($e,(s=me?.rect)!=null?s:null,ee),ue=u.useRef(null),fe=u.useCallback((Q,ae)=>{let{sensor:Ae,options:dt}=ae;if(B.current==null)return;const pt=C.get(B.current);if(!pt)return;const ot=Q.nativeEvent,Le=new Ae({active:B.current,activeNode:pt,event:ot,options:dt,context:V,onAbort(Je){if(!C.get(Je))return;const{onDragAbort:Dt}=P.current,zt={id:Je};Dt?.(zt),_({type:"onDragAbort",event:zt})},onPending(Je,Tt,Dt,zt){if(!C.get(Je))return;const{onDragPending:wn}=P.current,Zt={id:Je,constraint:Tt,initialCoordinates:Dt,offset:zt};wn?.(Zt),_({type:"onDragPending",event:Zt})},onStart(Je){const Tt=B.current;if(Tt==null)return;const Dt=C.get(Tt);if(!Dt)return;const{onDragStart:zt}=P.current,xn={activatorEvent:ot,active:{id:Tt,data:Dt.data,rect:N}};Cn.unstable_batchedUpdates(()=>{zt?.(xn),x(hn.Initializing),y({type:it.DragStart,initialCoordinates:Je,active:Tt}),_({type:"onDragStart",event:xn}),O(ue.current),H(ot)})},onMove(Je){y({type:it.DragMove,coordinates:Je})},onEnd:je(it.DragEnd),onCancel:je(it.DragCancel)});ue.current=Le;function je(Je){return async function(){const{active:Dt,collisions:zt,over:xn,scrollAdjustedTranslate:wn}=V.current;let Zt=null;if(Dt&&wn){const{cancelDrop:Hn}=P.current;Zt={activatorEvent:ot,active:Dt,collisions:zt,delta:wn,over:xn},Je===it.DragEnd&&typeof Hn=="function"&&await Promise.resolve(Hn(Zt))&&(Je=it.DragCancel)}B.current=null,Cn.unstable_batchedUpdates(()=>{y({type:Je}),x(hn.Uninitialized),Ce(null),O(null),H(null),ue.current=null;const Hn=Je===it.DragEnd?"onDragEnd":"onDragCancel";if(Zt){const ln=P.current[Hn];ln?.(Zt),_({type:Hn,event:Zt})}})}}},[C]),xe=u.useCallback((Q,ae)=>(Ae,dt)=>{const pt=Ae.nativeEvent,ot=C.get(dt);if(B.current!==null||!ot||pt.dndKit||pt.defaultPrevented)return;const Le={active:ot};Q(Ae,ae.options,Le)===!0&&(pt.dndKit={capturedBy:ae.sensor},B.current=dt,fe(Ae,ae))},[C,fe]),he=Y2(p,xe);nI(p),sn(()=>{ee&&k===hn.Initializing&&x(hn.Initialized)},[ee,k]),u.useEffect(()=>{const{onDragMove:Q}=P.current,{active:ae,activatorEvent:Ae,collisions:dt,over:pt}=V.current;if(!ae||!Ae)return;const ot={active:ae,activatorEvent:Ae,collisions:dt,delta:{x:ce.x,y:ce.y},over:pt};Cn.unstable_batchedUpdates(()=>{Q?.(ot),_({type:"onDragMove",event:ot})})},[ce.x,ce.y]),u.useEffect(()=>{const{active:Q,activatorEvent:ae,collisions:Ae,droppableContainers:dt,scrollAdjustedTranslate:pt}=V.current;if(!Q||B.current==null||!ae||!pt)return;const{onDragOver:ot}=P.current,Le=dt.get(ie),je=Le&&Le.rect.current?{id:Le.id,rect:Le.rect.current,data:Le.data,disabled:Le.disabled}:null,Je={active:Q,activatorEvent:ae,collisions:Ae,delta:{x:pt.x,y:pt.y},over:je};Cn.unstable_batchedUpdates(()=>{Ce(je),ot?.(Je),_({type:"onDragOver",event:Je})})},[ie]),sn(()=>{V.current={activatorEvent:z,active:D,activeNode:Z,collisionRect:q,collisions:re,droppableRects:Y,draggableNodes:C,draggingNode:Ee,draggingNodeRect:De,droppableContainers:E,over:me,scrollableAncestors:Oe,scrollAdjustedTranslate:ce},N.current={initial:De,translated:q}},[D,Z,re,q,C,Ee,De,Y,E,me,Oe,ce]),V2({...oe,delta:T,draggingRect:q,pointerCoordinates:Xe,scrollableAncestors:Oe,scrollableAncestorRects:Ye});const j=u.useMemo(()=>({active:D,activeNode:Z,activeNodeRect:ee,activatorEvent:z,collisions:re,containerNodeRect:ge,dragOverlay:be,draggableNodes:C,droppableContainers:E,droppableRects:Y,over:me,measureDroppableContainers:K,scrollableAncestors:Oe,scrollableAncestorRects:Ye,measuringConfiguration:F,measuringScheduled:X,windowRect:Me}),[D,Z,ee,z,re,ge,be,C,E,Y,me,K,Oe,Ye,F,X,Me]),ne=u.useMemo(()=>({activatorEvent:z,activators:he,active:D,activeNodeRect:ee,ariaDescribedById:{draggable:I},dispatch:y,draggableNodes:C,over:me,measureDroppableContainers:K}),[z,he,D,ee,y,I,C,me,K]);return u.createElement(Yp.Provider,{value:w},u.createElement(Xo.Provider,{value:ne},u.createElement(vf.Provider,{value:j},u.createElement(ci.Provider,{value:U},c)),u.createElement(uI,{disabled:l?.restoreFocus===!1})),u.createElement(c2,{...l,hiddenTextDescribedById:I}));function pe(){const Q=M?.autoScrollEnabled===!1,ae=typeof d=="object"?d.enabled===!1:d===!1,Ae=$&&!Q&&!ae;return typeof d=="object"?{...d,enabled:Ae}:{enabled:Ae}}}),hI=u.createContext(null),xf="button",yI="Draggable";function bI(e){let{id:t,data:n,disabled:o=!1,attributes:r}=e;const s=oi(yI),{activators:a,activatorEvent:l,active:d,activeNodeRect:c,ariaDescribedById:p,draggableNodes:f,over:b}=u.useContext(Xo),{role:g=xf,roleDescription:m="draggable",tabIndex:h=0}=r??{},v=d?.id===t,y=u.useContext(v?ci:hI),[_,w]=ti(),[k,x]=ti(),$=oI(a,t),S=Ho(n);sn(()=>(f.set(t,{id:t,key:s,node:_,activatorNode:k,data:S}),()=>{const T=f.get(t);T&&T.key===s&&f.delete(t)}),[f,t]);const C=u.useMemo(()=>({role:g,tabIndex:h,"aria-disabled":o,"aria-pressed":v&&g===xf?!0:void 0,"aria-roledescription":m,"aria-describedby":p.draggable}),[o,g,h,v,m,p.draggable]);return{active:d,activatorEvent:l,activeNodeRect:c,attributes:C,isDragging:v,listeners:o?void 0:$,node:_,over:b,setNodeRef:w,setActivatorNodeRef:x,transform:y}}function mI(){return u.useContext(vf)}const vI="Droppable",_I={timeout:25};function xI(e){let{data:t,disabled:n=!1,id:o,resizeObserverConfig:r}=e;const s=oi(vI),{active:a,dispatch:l,over:d,measureDroppableContainers:c}=u.useContext(Xo),p=u.useRef({disabled:n}),f=u.useRef(!1),b=u.useRef(null),g=u.useRef(null),{disabled:m,updateMeasurementsFor:h,timeout:v}={..._I,...r},y=Ho(h??o),_=u.useCallback(()=>{if(!f.current){f.current=!0;return}g.current!=null&&clearTimeout(g.current),g.current=setTimeout(()=>{c(Array.isArray(y.current)?y.current:[y.current]),g.current=null},v)},[v]),w=li({callback:_,disabled:m||!a}),k=u.useCallback((C,T)=>{w&&(T&&(w.unobserve(T),f.current=!1),C&&w.observe(C))},[w]),[x,$]=ti(k),S=Ho(t);return u.useEffect(()=>{!w||!x.current||(w.disconnect(),f.current=!1,w.observe(x.current))},[x,w]),u.useEffect(()=>(l({type:it.RegisterDroppable,element:{id:o,key:s,disabled:n,node:x,rect:b,data:S}}),()=>l({type:it.UnregisterDroppable,key:s,id:o})),[o]),u.useEffect(()=>{n!==p.current.disabled&&(l({type:it.SetDroppableDisabled,id:o,key:s,disabled:n}),p.current.disabled=n)},[o,s,n,l]),{active:a,rect:b,isOver:d?.id===o,node:x,over:d,setNodeRef:$}}function wI(e){let{animation:t,children:n}=e;const[o,r]=u.useState(null),[s,a]=u.useState(null),l=ni(n);return!n&&!o&&l&&r(l),sn(()=>{if(!s)return;const d=o?.key,c=o?.props.id;if(d==null||c==null){r(null);return}Promise.resolve(t(c,s)).then(()=>{r(null)})},[t,o,s]),u.createElement(u.Fragment,null,n,o?u.cloneElement(o,{ref:a}):null)}const kI={x:0,y:0,scaleX:1,scaleY:1};function SI(e){let{children:t}=e;return u.createElement(Xo.Provider,{value:mf},u.createElement(ci.Provider,{value:kI},t))}const CI={position:"fixed",touchAction:"none"},$I=e=>ua(e)?"transform 250ms ease":void 0,EI=u.forwardRef((e,t)=>{let{as:n,activatorEvent:o,adjustScale:r,children:s,className:a,rect:l,style:d,transform:c,transition:p=$I}=e;if(!l)return null;const f=r?c:{...c,scaleX:1,scaleY:1},b={...CI,width:l.width,height:l.height,top:l.top,left:l.left,transform:Ko.Transform.toString(f),transformOrigin:r&&o?g2(o,l):void 0,transition:typeof p=="function"?p(o):p,...d};return u.createElement(n,{className:a,style:b,ref:t},s)}),II={duration:250,easing:"ease",keyframes:e=>{let{transform:{initial:t,final:n}}=e;return[{transform:Ko.Transform.toString(t)},{transform:Ko.Transform.toString(n)}]},sideEffects:(e=>t=>{let{active:n,dragOverlay:o}=t;const r={},{styles:s,className:a}=e;if(s!=null&&s.active)for(const[l,d]of Object.entries(s.active))d!==void 0&&(r[l]=n.node.style.getPropertyValue(l),n.node.style.setProperty(l,d));if(s!=null&&s.dragOverlay)for(const[l,d]of Object.entries(s.dragOverlay))d!==void 0&&o.node.style.setProperty(l,d);return a!=null&&a.active&&n.node.classList.add(a.active),a!=null&&a.dragOverlay&&o.node.classList.add(a.dragOverlay),function(){for(const[d,c]of Object.entries(r))n.node.style.setProperty(d,c);a!=null&&a.active&&n.node.classList.remove(a.active)}})({styles:{active:{opacity:"0"}}})};function AI(e){let{config:t,draggableNodes:n,droppableContainers:o,measuringConfiguration:r}=e;return ei((s,a)=>{if(t===null)return;const l=n.get(s);if(!l)return;const d=l.node.current;if(!d)return;const c=bf(a);if(!c)return;const{transform:p}=xt(a).getComputedStyle(a),f=Jp(p);if(!f)return;const b=typeof t=="function"?t:TI(t);return rf(d,r.draggable.measure),b({active:{id:s,data:l.data,node:d,rect:r.draggable.measure(d)},draggableNodes:n,dragOverlay:{node:a,rect:r.dragOverlay.measure(c)},droppableContainers:o,measuringConfiguration:r,transform:f})})}function TI(e){const{duration:t,easing:n,sideEffects:o,keyframes:r}={...II,...e};return s=>{let{active:a,dragOverlay:l,transform:d,...c}=s;if(!t)return;const p={x:l.rect.left-a.rect.left,y:l.rect.top-a.rect.top},f={scaleX:d.scaleX!==1?a.rect.width*d.scaleX/l.rect.width:1,scaleY:d.scaleY!==1?a.rect.height*d.scaleY/l.rect.height:1},b={x:d.x-p.x,y:d.y-p.y,...f},g=r({...c,active:a,dragOverlay:l,transform:{initial:d,final:b}}),[m]=g,h=g[g.length-1];if(JSON.stringify(m)===JSON.stringify(h))return;const v=o?.({active:a,dragOverlay:l,...c}),y=l.node.animate(g,{duration:t,easing:n,fill:"forwards"});return new Promise(_=>{y.onfinish=()=>{v?.(),_()}})}}let wf=0;function DI(e){return u.useMemo(()=>{if(e!=null)return wf++,wf},[e])}const zI=u.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:o,style:r,transition:s,modifiers:a,wrapperElement:l="div",className:d,zIndex:c=999}=e;const{activatorEvent:p,active:f,activeNodeRect:b,containerNodeRect:g,draggableNodes:m,droppableContainers:h,dragOverlay:v,over:y,measuringConfiguration:_,scrollableAncestors:w,scrollableAncestorRects:k,windowRect:x}=mI(),$=u.useContext(ci),S=DI(f?.id),C=_f(a,{activatorEvent:p,active:f,activeNodeRect:b,containerNodeRect:g,draggingNodeRect:v.rect,over:y,overlayNodeRect:v.rect,scrollableAncestors:w,scrollableAncestorRects:k,transform:$,windowRect:x}),T=wa(b),E=AI({config:o,draggableNodes:m,droppableContainers:h,measuringConfiguration:_}),A=T?v.setRef:void 0;return u.createElement(SI,null,u.createElement(wI,{animation:E},f&&S?u.createElement(EI,{key:S,id:f.id,ref:A,as:l,activatorEvent:p,adjustScale:t,className:d,transition:s,rect:T,style:{zIndex:c,...r},transform:C},n):null))});function Jo(e,t){return!t||!Array.isArray(t.draggable)?!1:t.draggable.includes(e)}function NI({draggedComponentName:e,targetContainerName:t,nesting:n}){if(!n||!Jo(e,n))return!1;const o=n.containers;if(!o||typeof o!="object")return!1;const r=o[t];return!r||!Array.isArray(r.accepts)?!1:r.accepts.includes(e)}function kf(e,t){if(!t?.containers)return!1;const n=t.containers[e];return!!(n&&Array.isArray(n.accepts)&&n.accepts.length>0)}function MI(e,t,n,o,r){if(!n||n.length===0)return{parentPath:[],index:r};if(e&&kf(e,o))return{parentPath:n,index:t};const s=n.slice(0,-1),a=n[n.length-1]??0;return{parentPath:s,index:a+1}}function Sf(e,t){return e===t||e.startsWith(`${t}.`)}function Cf(e,t){if(e==="")return/^\d+$/.test(t)?Number(t):null;const n=`${e}.children.`;if(!t.startsWith(n))return null;const o=t.slice(n.length);return/^\d+$/.test(o)?Number(o):null}function LI(e,t){const n=[];return e.querySelectorAll("[data-editor-path]").forEach(o=>{if(o.hasAttribute("data-dnd-placeholder")||o.closest("[data-dnd-placeholder]"))return;const r=o.dataset.editorPath;typeof r=="string"&&n.push({path:t(r),domPath:r,rect:o.getBoundingClientRect()})}),n}const PI=16;function OI(e){const{frameEl:t,draggedPath:n,acceptsContainer:o,allowsNestSlot:r,includeContainer:s}=e,a=e.normalizeContainerPath??(g=>g),l=t.getBoundingClientRect(),d=LI(t,a),c=new Map;for(const g of d)c.has(g.path)||c.set(g.path,g.domPath);const p=a(n),f=new Set([""]);for(const g of d){const m=WI(g.path);m!==null&&f.add(m)}for(const g of d)f.add(g.path);const b=[];for(const g of f){const m=g==="",h=m?null:c.get(g)??g,v=m?t:t.querySelector(`[data-editor-path="${If(h)}"]`);if(!v&&!m||!m&&Sf(g,p))continue;const y=g;if(!m&&s&&!s(y))continue;const _=$=>{const S=c.get($);if(!S||typeof window>"u")return!1;const C=t.querySelector(`[data-editor-path="${If(S)}"]`);return C?(window.getComputedStyle(C).display??"").toLowerCase()==="contents":!1},w=d.filter($=>Cf(g,$.path)!==null).filter($=>!Sf($.path,p)).filter($=>!_($.path)).map($=>({origIndex:Cf(g,$.path),rect:BI($.rect,$.path,d)})).filter($=>$.rect.width>0||$.rect.height>0).sort(($,S)=>$.origIndex-S.origIndex),k=Op(m?t:v).kind,x=k==="flex_row_single"||k==="flex_row_wrap"||k==="grid_single_row"||k==="grid_2d";if(w.length>0){if(o(y)){w.forEach(S=>{b.push($f(y,S.origIndex,S.rect,l,x,"before"))});const $=w[w.length-1];b.push($f(y,$.origIndex+1,$.rect,l,x,"after"))}}else if(!m&&r(y)&&v){const $=v.getBoundingClientRect();$.width>0&&$.height>0&&b.push({id:`slot:${y}:0`,kind:"nest",containerPath:y,index:0,box:Ef($,l),orientation:"area"})}else m&&b.push({id:"slot::0",kind:"gap",containerPath:"",index:0,box:Ef(l,l),orientation:"area"})}return b.filter(g=>lo(g.box,t))}function $f(e,t,n,o,r,s){const a=PI;let l;if(r)l={left:(s==="before"?n.left:n.right)-a/2,top:n.top,width:a,height:n.height};else{const d=s==="before"?n.top:n.bottom;l={left:n.left,top:d-a/2,width:n.width,height:a}}return{id:`slot:${e}:${t}`,kind:"gap",containerPath:e,index:t,box:{left:l.left-o.left,top:l.top-o.top,width:l.width,height:l.height,scale:1},orientation:r?"vertical":"horizontal"}}function BI(e,t,n){if(e.width>0||e.height>0)return e;const o=`${t}.children.`;let r=1/0,s=1/0,a=-1/0,l=-1/0;for(const d of n)d.path.startsWith(o)&&(d.rect.width===0&&d.rect.height===0||(r=Math.min(r,d.rect.left),s=Math.min(s,d.rect.top),a=Math.max(a,d.rect.right),l=Math.max(l,d.rect.bottom)));return r===1/0?e:{left:r,top:s,width:a-r,height:l-s,right:a,bottom:l,x:r,y:s,toJSON:()=>({})}}function Ef(e,t){return{left:e.left-t.left,top:e.top-t.top,width:e.width,height:e.height,scale:1}}function WI(e){if(e==="")return null;const t=e.lastIndexOf(".children.");return t<0?"":e.slice(0,t)}function jI(e){if(!e.startsWith("slot:"))return null;const t=e.slice(5),n=t.lastIndexOf(":");if(n<0)return null;const o=t.slice(0,n),r=Number(t.slice(n+1));return Number.isFinite(r)?{containerPath:o,index:r}:null}function If(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/[^a-zA-Z0-9_\-.]/g,t=>`\\${t}`)}function ka(e){return typeof e=="string"&&e.length>0?e:null}function Sa(e,t){return t&&e.startsWith(`${t}.`)?t:e}function Af(e){if(typeof e!="string")return null;const t=jI(e);return t?{containerPath:t.containerPath,index:t.index}:null}function Ca(e,t){return t?e.startsWith(`${t}.iteration.`):!1}function $a(e,t,n){return t?n==="iteration_item"?Ca(e,t):e===t||e.startsWith(`${t}.`):!1}function HI(e){const{frameEl:t,nesting:n,editMode:o,currentExtensionId:r,editableRootPath:s,components:a,patchLayout:l,pushHistory:d,onMovePath:c,selectedPath:p,showBranchBoundaryHint:f}=e,b=(o==="iteration_item"||o==="modal")&&s&&s.length>0?at(s):null,[g,m]=u.useState(null),[h,v]=u.useState(null),[y,_]=u.useState(null),w=u.useRef({components:a,nesting:n,editMode:o,currentExtensionId:r,selectedPath:p,editableRootSourcePath:b});w.current={components:a,nesting:n,editMode:o,currentExtensionId:r,selectedPath:p,editableRootSourcePath:b};const k=u.useRef(null),x=u.useCallback(M=>({children:M}),[]),$=u.useCallback((M,O)=>{const z=Be(x(M),O);return z?typeof z.name=="string"?z.name:typeof z.type=="string"?z.type:null:null},[x]),S=u.useCallback(M=>O=>{const z=w.current;if(O==="")return Jo(M,z.nesting);const H=Re(O),P=Be(x(z.components),H);if(!P)return!1;const I=typeof P.name=="string"?P.name:typeof P.type=="string"?P.type:"";if(!I)return!1;const L=!!z.editableRootSourcePath&&(O===z.editableRootSourcePath||O.startsWith(`${z.editableRootSourcePath}.`));if(z.editableRootSourcePath&&!L)return!1;if(!L){const F=Ea(x(z.components),H);if(gn(P,z.editMode,z.currentExtensionId,F)!=="none")return!1}return kf(I,z.nesting)?NI({draggedComponentName:M,targetContainerName:I,nesting:z.nesting}):!1},[x]),C=u.useCallback(M=>{if(M==="")return!0;const O=w.current,z=Re(M),H=k.current;if(H&&H.length>0){const L=H.slice(0,-1);if(ui(z,L))return!0}const P=Be(x(O.components),z);return P?(typeof P.name=="string"?P.name:typeof P.type=="string"?P.type:"").length>0:!1},[x]),T=u.useCallback(M=>{const O=S(M),z=w.current,H=k.current,P=H?H.slice(0,-1):null,I=new Set;if(P)for(let K=P.length;K>=0;K--)I.add(pi(P.slice(0,K)));const L=pi(H??[]),F=K=>!!H&&(K===L||K.startsWith(`${L}.`)),Y=(K,X)=>{for(let Z=0;ZK===""?!0:F(K)?!1:I.has(K),allowsNestSlot:K=>{if(!O(K))return!1;if(P){const X=Re(K);if(ui(X,P))return!1}return C(K)}}},[S,C,x]),E=u.useCallback(M=>{const O=ka(M.active.id),z=w.current;if(!O)return;const H=Sa(O,z.selectedPath),P=Re(H),I=Be(x(z.components),P),L=I&&typeof I.name=="string"?I.name:I&&typeof I.type=="string"?I.type:null;m(H),v(L),_(null),k.current=I?P:null;let F="allowed";if(!L||!Jo(L,z.nesting))F="denied_no_draggable";else if(I){const Y=Ea(x(z.components),P),K=gn(I,z.editMode,z.currentExtensionId,Y);z.editableRootSourcePath&&!$a(H,z.editableRootSourcePath,z.editMode)||Qi(Y)&&!Ca(H,z.editableRootSourcePath)?F="denied_data_bound":K==="base"||K==="partial"?F="denied_base_locked":(K==="extension"||K==="extension_point")&&(F="denied_extension_locked")}$n({source:"drag",draggedComponentName:L,targetContainerName:null,targetContainerPath:null,decision:F,result:F==="allowed"?"completed":"denied",timestamp:Date.now()})},[x]),A=u.useCallback(M=>{if(!t)return;const O=ka(M.active.id);if(!O)return;const z=h;if(!z){_(null);return}const H=w.current,P=Sa(O,H.selectedPath),I=Re(P),L=Be(x(H.components),I);if(!L||!Jo(z,H.nesting)){_(null);return}const F=Ea(x(H.components),I);if(H.editableRootSourcePath&&!$a(P,H.editableRootSourcePath,H.editMode)){_(null);return}const Y=gn(L,H.editMode,H.currentExtensionId,F),K=Ca(P,H.editableRootSourcePath);if(Qi(F)&&!K||Y!=="none"&&Y!=="data_bound"&&!K){_(null);return}_(Af(M.over?.id))},[t,h,x]),N=u.useCallback(()=>{m(null),v(null),_(null),k.current=null},[]),D=u.useCallback(M=>{const O=ka(M.active.id),z=h,H=w.current,P=O?Sa(O,H.selectedPath):null;if(!t||!P||!z){N();return}const I=Af(M.over?.id),L=Re(P);if(!I){$n({source:"drag",draggedComponentName:z,targetContainerName:null,targetContainerPath:null,decision:"denied_no_accepts",result:"cancelled",timestamp:Date.now()}),N();return}const F=I.containerPath===""?[]:Re(I.containerPath),Y=I.containerPath===""?null:$(H.components,F);if(!FI(L.slice(0,-1),F)){$n({source:"drag",draggedComponentName:z,targetContainerName:Y,targetContainerPath:I.containerPath||null,decision:"denied_responsive_branch_boundary",result:"denied",timestamp:Date.now()}),f?.(),N();return}if(H.editableRootSourcePath&&!$a(I.containerPath,H.editableRootSourcePath,H.editMode)){$n({source:"drag",draggedComponentName:z,targetContainerName:Y,targetContainerPath:I.containerPath||null,decision:"denied_data_bound",result:"denied",timestamp:Date.now()}),N();return}const K=L.slice(0,-1),X=L[L.length-1]??-1;if(ui(K,F)&&(I.index===X||I.index===X+1)){$n({source:"drag",draggedComponentName:z,targetContainerName:Y,targetContainerPath:I.containerPath||null,decision:"allowed",insertionIndex:I.index,result:"cancelled",timestamp:Date.now()}),N();return}const oe=ui(K,F),G=I.index;let ee=[];l(be=>{const Se=Bb({children:be},L,F,G).children??[];return ee=Se,Se}),d(ee,`move ${z}`);const ge=dd(F,L),V=oe&&X{N()},[N]);return{activeDragPath:g,activeDragName:h,activeDropZone:y,onDragStart:E,onDragMove:A,onDragEnd:D,onDragCancel:B,buildSlotPredicates:T}}function Ea(e,t){const n=[];let o=e,r=Array.isArray(e.children)?e.children:[];for(let s=0;s0?at(s):null,{t:m}=tt(),[h,v]=u.useState(!1),y=u.useRef(null),_=u.useCallback(()=>{v(!0),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>v(!1),2600)},[]);u.useEffect(()=>()=>{y.current&&clearTimeout(y.current)},[]);const w=HI({frameEl:t,nesting:n,editMode:o,currentExtensionId:r,editableRootPath:s,components:a,patchLayout:l,pushHistory:d,onMovePath:p,selectedPath:b,showBranchBoundaryHint:_}),k=p2(u2(ma,{activationConstraint:{distance:8}})),[x,$]=u.useState([]),S=u.useCallback(()=>{if(!t){$([]);return}if(w.activeDragPath!==null)return;const P={children:a},I=t.querySelectorAll("[data-editor-path]"),L=[],F=new Map;I.forEach(Y=>{const K=Y.dataset.editorPath;if(typeof K!="string"||o!=="iteration_item"&&g&&!UI(K,g,o))return;const X=KI(K);if(X!==null&&!Zo(K,g)){if(/\.iteration\.\d+$/.test(K)){const V=ao(Y,t);if(V&&lo(V,t)){const te=F.get(X)??[];te.push(V),F.set(X,te)}}return}if(Zo(K,g)&&/\.iteration\.\d+$/.test(K))return;const Z=Re(K),se=Be(P,Z);if(!se||se.iteration&&se.iteration.source!==void 0)return;const oe=typeof se.name=="string"?se.name:typeof se.type=="string"?se.type:null;if(!oe||!Jo(oe,n))return;const G=Df(P,Z);if(Qi(G)&&!Zo(K,g))return;const ee=gn(se,o,r,G);if(ee!=="none"&&ee!=="data_bound"&&!Zo(K,g))return;const ge=ao(Y,t);ge&&lo(ge,t)&&L.push({path:K,name:oe,box:ge})});for(const[Y,K]of F){const X=Re(Y),Z=Be(P,X);if(!Z)continue;const se=typeof Z.name=="string"?Z.name:typeof Z.type=="string"?Z.type:null;if(!se)continue;const oe=Df(P,X),G=gn(Z,o,r,oe);if(G!=="none"&&G!=="data_bound")continue;const ee=qI(K);ee&&lo(ee,t)&&L.push({path:Y,name:se,box:ee,isIterationGroup:!0})}$(L)},[t,a,n,o,r,g,w.activeDragPath]);u.useEffect(()=>{S()},[S]),u.useEffect(()=>{if(t)return zp(S,t)},[t,S]);const C=w.activeDragPath!==null,T=w.activeDragName,E=w.activeDragPath,[A,N]=u.useState(null),D=u.useRef(null);u.useEffect(()=>{if(!E||!t){E||(D.current=null,N(null));return}if(D.current===E)return;D.current=E;const P=t.querySelector(`[data-editor-path="${Tf(E)}"]`);if(P){const oe=P.getBoundingClientRect();N({node:P.cloneNode(!0),width:oe.width,height:oe.height});return}const I=Array.from(t.querySelectorAll(`[data-editor-path^="${Tf(E)}.iteration."]`)).filter(oe=>/\.iteration\.\d+$/.test(oe.dataset.editorPath??""));if(I.length===0){N(null);return}let L=1/0,F=1/0,Y=-1/0,K=-1/0;for(const oe of I){const G=oe.getBoundingClientRect();L=Math.min(L,G.left),F=Math.min(F,G.top),Y=Math.max(Y,G.right),K=Math.max(K,G.bottom)}const X=Y-L,Z=K-F,se=document.createElement("div");se.style.position="relative",se.style.width=`${X}px`,se.style.height=`${Z}px`;for(const oe of I){const G=oe.getBoundingClientRect(),ee=oe.cloneNode(!0);ee.style.position="absolute",ee.style.left=`${G.left-L}px`,ee.style.top=`${G.top-F}px`,ee.style.width=`${G.width}px`,ee.style.height=`${G.height}px`,ee.style.margin="0",se.appendChild(ee)}N({node:se,width:X,height:Z})},[E,t]);const[B,M]=u.useState([]),O=u.useRef(null),z=u.useRef(w.buildSlotPredicates);if(z.current=w.buildSlotPredicates,u.useEffect(()=>{if(!E||!T||!t){O.current=null,M(F=>F.length===0?F:[]);return}if(O.current===E)return;O.current=E;const{acceptsContainer:P,allowsNestSlot:I,includeContainer:L}=z.current(T);M(OI({frameEl:t,draggedPath:E,acceptsContainer:P,allowsNestSlot:I,includeContainer:L,normalizeContainerPath:F=>VI(F)}))},[E,T,t]),!t)return null;const H=w.activeDropZone?`slot:${w.activeDropZone.containerPath}:${w.activeDropZone.index}`:null;return i.jsxs(gI,{sensors:k,collisionDetection:w2,onDragStart:w.onDragStart,onDragMove:w.onDragMove,onDragEnd:w.onDragEnd,onDragCancel:w.onDragCancel,children:[x.map(P=>i.jsx(JI,{path:P.path,name:P.name,box:P.box,dimmed:C&&w.activeDragPath!==P.path,isIterationGroup:P.isIterationGroup,onSelect:c,onRequestInlineEdit:f},P.path)),C&&B.map(P=>i.jsx(XI,{slot:P,active:P.id===H},P.id)),Cn.createPortal(i.jsx(zI,{dropAnimation:null,zIndex:Fp,children:T?A?i.jsx(YI,{name:T,node:A.node,width:A.width,height:A.height}):i.jsx("div",{className:"g7le-dnd-drag-ghost","data-testid":"g7le-dnd-drag-ghost",style:{padding:"4px 10px",background:"rgba(79,70,229,0.95)",color:"#fff",fontSize:12,fontWeight:600,borderRadius:4,pointerEvents:"none",whiteSpace:"nowrap"},children:`<${T}>`}):null}),document.body),h&&Cn.createPortal(i.jsxs("div",{"data-testid":"g7le-branch-boundary-hint",role:"status",style:{position:"absolute",left:"50%",top:12,transform:"translateX(-50%)",background:"rgba(245,158,11,0.97)",color:"#fff",fontSize:13,fontWeight:600,padding:"8px 16px",borderRadius:8,boxShadow:"0 4px 14px rgba(0,0,0,0.2)",pointerEvents:"none",whiteSpace:"nowrap",zIndex:Fp},children:["⚠️ ",m("layout_editor.overlay.branch_boundary_denied")]}),t)]})}function YI(e){const{node:t,width:n,height:o}=e,r=u.useRef(null);return u.useEffect(()=>{const s=r.current;if(s)return s.replaceChildren(),s.appendChild(t.cloneNode(!0)),()=>{s.replaceChildren()}},[t]),i.jsx("div",{ref:r,className:"g7le-dnd-drag-ghost","data-testid":"g7le-dnd-drag-ghost",style:{width:n,height:o,opacity:.7,pointerEvents:"none",boxShadow:"0 6px 18px rgba(0,0,0,0.25)",borderRadius:4,overflow:"hidden",cursor:"grabbing"}})}function XI(e){const{slot:t,active:n}=e,{setNodeRef:o}=xI({id:t.id}),r=t.orientation!=="area";return i.jsx("div",{ref:o,"data-testid":`g7le-dnd-slot-${t.id}`,"data-dnd-slot-id":t.id,style:{position:"absolute",left:t.box.left,top:t.box.top,width:t.box.width,height:t.box.height,pointerEvents:"auto",zIndex:H7,boxSizing:"border-box",...r?{background:n?"rgba(79,70,229,0.15)":"transparent",...n?t.orientation==="vertical"?{borderLeft:"2px solid #4f46e5"}:{borderTop:"2px solid #4f46e5"}:{}}:{border:n?"2px dashed #4f46e5":"1px dashed transparent",background:n?"rgba(79,70,229,0.08)":"transparent",borderRadius:4}}})}function Tf(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/[^a-zA-Z0-9_\-.]/g,t=>`\\${t}`)}function JI(e){const{path:t,box:n,dimmed:o,isIterationGroup:r,onSelect:s,onRequestInlineEdit:a}=e,{attributes:l,listeners:d,setNodeRef:c,isDragging:p}=bI({id:t}),f=(t.match(/\.children\./g)||[]).length,b=F7(f);return i.jsx("div",{ref:c,"data-testid":`g7le-dnd-handle-${t}`,"data-dnd-handle-path":t,"data-dnd-iteration-group":r?"true":void 0,...d,...l,onClick:g=>{if(g.stopPropagation(),!r&&typeof document<"u"&&typeof document.elementsFromPoint=="function"){const m=document.elementsFromPoint(g.clientX,g.clientY);for(const h of m){const y=h.closest?.("[data-editor-path]")?.dataset?.editorPath;if(typeof y=="string"&&(y===t||y.startsWith(`${t}.`))){s(y);return}}}s(t)},onDoubleClick:g=>{g.stopPropagation(),g.preventDefault(),a?.(t)},style:{position:"absolute",left:n.left,top:n.top,width:n.width,height:n.height,cursor:"grab",pointerEvents:"auto",background:p?"rgba(79,70,229,0.06)":"transparent",...r?{border:"1px dashed rgba(79,70,229,0.5)",borderRadius:4}:{},opacity:o?.6:1,zIndex:b,touchAction:"none"}})}function Df(e,t){const n=[];let o=e,r=Array.isArray(e.children)?e.children:[];for(let s=0;s0?[o]:[];const r=[],s=(a,l)=>{a.forEach((d,c)=>{const p=[...l,c];if(!Ri(d,t,n)){r.push(p);return}const b=Array.isArray(d.children)?d.children:[];b.length>0&&s(b,p)})};return s(e,[]),r}function QI(e){return at(e)}function fi(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}function RI({frameEl:e,components:t,editMode:n,currentExtensionId:o,editableRootPath:r}){const[s,a]=u.useState(null),[l]=u.useState(()=>`g7le-dim-mask-${Math.floor(Math.random()*1e9)}`);if(u.useEffect(()=>{if(!e){a(null);return}let g=0;const m=()=>{const _=ZI(t,n,o,r);if(_.length===0){a(null);return}const w=e.getBoundingClientRect(),k={left:0,top:0,width:w.width,height:w.height},x=[];for(const $ of _){const S=QI($),C=e.querySelector(`[data-editor-path="${fi(S)}"]`);let T=null;if(C){const E=C.getBoundingClientRect();E.width>0&&E.height>0&&(T={left:E.left,top:E.top,width:E.width,height:E.height})}if(!T){const E=Array.from(e.querySelectorAll(`[data-editor-path^="${fi(S)}.iteration."], [data-editor-path^="${fi(S)}.sortable."], [data-editor-path^="${fi(S)}.children."]`));let A=1/0,N=1/0,D=-1/0,B=-1/0;for(const M of E){const O=M.getBoundingClientRect();O.width<=0||O.height<=0||(A=Math.min(A,O.left),N=Math.min(N,O.top),D=Math.max(D,O.right),B=Math.max(B,O.bottom))}if(D>A&&B>N&&(T={left:A,top:N,width:D-A,height:B-N}),T&&E.length>0){const M=E[0].closest('[role="dialog"]');if(M&&e.contains(M)){const O=M.getBoundingClientRect();O.width>0&&O.height>0&&(T={left:O.left,top:O.top,width:O.width,height:O.height})}}}T&&x.push({left:T.left-w.left,top:T.top-w.top,width:T.width,height:T.height})}if(x.length===0){a(null);return}a({frame:k,holes:x})},h=()=>{g&&cancelAnimationFrame(g),g=requestAnimationFrame(m)};h();const v=typeof ResizeObserver<"u"?new ResizeObserver(h):null;v?.observe(e);const y=typeof MutationObserver<"u"?new MutationObserver(h):null;return y?.observe(e,{childList:!0,subtree:!0,attributes:!0}),window.addEventListener("scroll",h,!0),window.addEventListener("resize",h),()=>{g&&cancelAnimationFrame(g),v?.disconnect(),y?.disconnect(),window.removeEventListener("scroll",h,!0),window.removeEventListener("resize",h)}},[e,t,n,o,r?.join(".")??""]),!s||s.holes.length===0)return null;const{frame:d,holes:c}=s,p=n==="modal"||n==="iteration_item";let f=[];if(p){let g=1/0,m=1/0,h=-1/0,v=-1/0;for(const $ of c)g=Math.min(g,$.left),m=Math.min(m,$.top),h=Math.max(h,$.left+$.width),v=Math.max(v,$.top+$.height);const y=($,S,C)=>Math.max(S,Math.min(C,$)),_=y(g,0,d.width),w=y(m,0,d.height),k=y(h,0,d.width),x=y(v,0,d.height);f=[{left:0,top:0,width:d.width,height:w},{left:0,top:x,width:d.width,height:d.height-x},{left:0,top:w,width:_,height:x-w},{left:k,top:w,width:d.width-k,height:x-w}].filter($=>$.width>0&&$.height>0)}const b=g=>{g.preventDefault(),g.stopPropagation()};return i.jsxs(i.Fragment,{children:[f.map((g,m)=>i.jsx("div",{className:"g7le-source-lock-block","data-testid":"g7le-source-lock-block",onClickCapture:b,onPointerDownCapture:b,onMouseDownCapture:b,onDragStartCapture:b,style:{position:"absolute",left:g.left,top:g.top,width:g.width,height:g.height,zIndex:Hp,pointerEvents:"auto",cursor:"not-allowed",background:"transparent"}},m)),i.jsxs("svg",{className:"g7le-source-lock-dim","data-testid":"g7le-source-lock-dim",width:d.width,height:d.height,style:{position:"absolute",left:0,top:0,width:d.width,height:d.height,zIndex:Hp,pointerEvents:"none"},children:[i.jsx("defs",{children:i.jsxs("mask",{id:l,children:[i.jsx("rect",{x:0,y:0,width:d.width,height:d.height,fill:"white"}),c.map((g,m)=>i.jsx("rect",{"data-testid":"g7le-source-lock-dim-hole",x:g.left,y:g.top,width:g.width,height:g.height,rx:4,fill:"black"},m))]})}),i.jsx("rect",{"data-testid":"g7le-source-lock-dim-box",x:0,y:0,width:d.width,height:d.height,fill:"rgba(15, 23, 42, 0.45)",mask:`url(#${l})`})]})]})}function zf(e){const t={type:e.type??"basic",name:e.name},n={};if(e.props)for(const[o,r]of Object.entries(e.props))o!=="children"&&r?.default!==void 0&&(n[o]=r.default);return Object.keys(n).length>0&&(t.props=n),t}function eA(e){if(!e?.components)return[];const t=[];for(const[n,o]of Object.entries(e.components))if(Array.isArray(o))for(const r of o)t.push({...r,type:r.type??n});return t}function tA(e,t,n,o,r){const s=eA(e);let a=null;if(n&&t?.containers){const l=t.containers[n];l&&Array.isArray(l.accepts)?a=new Set(l.accepts):a=new Set}else!n&&t?.draggable&&(a=new Set(t.draggable));return s.filter(l=>{if(a&&!a.has(l.name))return!1;if(o){const d=o.toLowerCase(),c=r(l).toLowerCase(),p=l.name.toLowerCase();if(!c.includes(d)&&!p.includes(d)&&!`<${p}>`.includes(d)&&!(l.description??"").toLowerCase().includes(d))return!1}return!0})}function nA(e,t){const n={key:"all",label:"layout_editor.palette.category.all",entries:e,isI18nKey:!0};if(t?.groups&&t.groups.length>0){const a=new Map(e.map(p=>[p.name,p])),l=new Set,d=[];for(const p of t.groups){const f=[];for(const b of p.components??[]){const g=a.get(b);g&&(f.push(g),l.add(b))}f.length!==0&&d.push({key:p.kind??p.label,label:p.label,entries:f,isI18nKey:p.label.startsWith("$t:")||/^[a-z_.]+$/i.test(p.label)})}const c=e.filter(p=>!l.has(p.name));return c.length>0&&d.push({key:"other",label:"layout_editor.palette.category.other",entries:c,isI18nKey:!0}),[n,...d]}const o=new Map;for(const a of e){const l=(a.type??"basic").toLowerCase(),d=o.get(l)??[];d.push(a),o.set(l,d)}const r=["basic","composite","layout"],s=[];for(const a of r){const l=o.get(a);l&&l.length>0&&(s.push({key:a,label:`layout_editor.palette.category.fallback.${a}`,entries:l,isI18nKey:!0}),o.delete(a))}for(const[a,l]of o.entries())s.push({key:a,label:a,entries:l,isI18nKey:!1});return[n,...s]}function Nf(e){const{manifest:t,nesting:n,componentPalette:o,targetParentPath:r,targetContainerName:s,onInsert:a,insertionIndex:l,onClose:d,editorTemplateId:c,editorLocale:p}=e,{t:f,translationEngine:b}=tt(),g=u.useMemo(()=>{if(!c||!b)return f;const A=p??null;return N=>{const D={templateId:c,locale:A??"ko"},B=b.translate(N,D);return B!==N?B:f(N)}},[c,p,b,f]),[m,h]=u.useState(""),[v,y]=u.useState("all"),_=o?.entries??null,w=u.useMemo(()=>A=>{const N=_?.[A.name];return N?.label?gi(N.label,g):A.description??A.name},[_,g]),k=u.useMemo(()=>tA(t,n,s,m,w),[t,n,s,m,w]),x=u.useMemo(()=>nA(k,o??null),[k,o]),$=x.find(A=>A.key===v)??x[0]??null,S=!n||!n.draggable&&!n.containers,C=k.length===0,T=$?.entries??[],E=A=>{const N=_?.[A.name],D=!!N?.defaultNode&&typeof N.defaultNode=="object";if(N?.requiresDefaultNode&&!D)return;const B=D?JSON.parse(JSON.stringify(N.defaultNode)):zf(A),M=r??[];a(B,M,l),$n({source:"palette",draggedComponentName:A.name,targetContainerName:s,targetContainerPath:M.length===0?null:M.join("/"),decision:"allowed",insertionIndex:l,result:"completed",timestamp:Date.now()}),d()};return i.jsxs("div",{className:"g7le-palette","data-testid":"g7le-palette",style:sA,children:[i.jsxs("div",{style:aA,children:[i.jsx("strong",{style:{fontSize:16},children:f("layout_editor.palette.title")}),i.jsx("button",{type:"button",onClick:d,"aria-label":"close","data-testid":"g7le-palette-close",style:lA,children:"×"})]}),i.jsxs("div",{style:dA,children:[i.jsx("aside",{style:cA,"data-testid":"g7le-palette-sidebar",children:i.jsx("nav",{children:i.jsx("ul",{style:uA,children:x.map(A=>{const N=$?.key===A.key,D=A.isI18nKey?gi(A.label,g):A.label;return i.jsx("li",{children:i.jsxs("button",{type:"button","data-testid":`g7le-palette-category-${A.key}`,"data-active":N?"true":"false",onClick:()=>y(A.key),style:{...pA,background:N?"#eff6ff":"transparent",color:N?"#1d4ed8":"#334155",fontWeight:N?600:500},children:[i.jsx("span",{children:D}),i.jsx("span",{style:yA,children:A.entries.length})]})},A.key)})})})}),i.jsxs("main",{style:fA,children:[i.jsx("input",{type:"text",placeholder:f("layout_editor.palette.search_placeholder"),value:m,onChange:A=>h(A.target.value),"data-testid":"g7le-palette-search",style:gA}),i.jsx("div",{style:hA,children:S?i.jsx("div",{style:Mf,"data-testid":"g7le-palette-spec-missing",children:f("layout_editor.palette.spec_missing")}):C||T.length===0?i.jsx("div",{style:Mf,"data-testid":"g7le-palette-empty",children:f("layout_editor.palette.empty")}):i.jsx("div",{"data-testid":`g7le-palette-group-${$?.key??"all"}`,style:{marginBottom:16},children:i.jsx("div",{style:bA,children:T.map(A=>i.jsx(oA,{entry:A,entrySpec:_?.[A.name]??null,onClick:E,t:f,entryT:g},A.name))})})})]})]})]})}function oA(e){const{entry:t,entrySpec:n,onClick:o,t:r,entryT:s}=e,a=n?.label?gi(n.label,s):t.description??t.name,l=(t.type??"").toLowerCase(),d=l==="basic"||l==="composite"||l==="layout",c=!!n?.defaultNode&&typeof n.defaultNode=="object",p=!!n?.requiresDefaultNode&&!c,f=!c,b=p?r("layout_editor.palette.requires_default_node_missing"):n?.label?gi(n.label,s):t.name;return i.jsxs("button",{type:"button",onClick:()=>o(t),disabled:p,"aria-disabled":p||void 0,"data-testid":`g7le-palette-item-${t.name}`,"data-component-type":l||void 0,"data-blocked":p?"true":void 0,"data-default-node-missing":f?"true":void 0,title:b,style:p?vA:mA,children:[i.jsx("div",{style:xA,"aria-hidden":"true",children:iA(t)}),i.jsx("div",{style:wA,children:a}),i.jsx("div",{"data-testid":`g7le-palette-item-${t.name}-tag`,style:kA,children:`<${t.name}>`}),d&&i.jsx("div",{"data-testid":`g7le-palette-item-${t.name}-badge`,style:rA(l),children:l}),f&&i.jsx("div",{"data-testid":`g7le-palette-item-${t.name}-default-missing-badge`,style:_A,children:r("layout_editor.palette.default_node_missing_badge")})]})}function gi(e,t){return e.startsWith("$t:")?t(e.slice(3)):t(e)}function rA(e){const n={basic:{bg:"#dbeafe",fg:"#1e40af"},composite:{bg:"#dcfce7",fg:"#14532d"},layout:{bg:"#fef3c7",fg:"#854d0e"}}[e]??{bg:"#e2e8f0",fg:"#334155"};return{fontSize:9,fontWeight:600,color:n.fg,background:n.bg,padding:"1px 6px",borderRadius:999,textTransform:"uppercase",letterSpacing:.4,lineHeight:1.6}}function iA(e){const t=e.name;return{Button:"🔘",A:"🔗",Img:"🖼",Icon:"✨",Hr:"➖",P:"📄",Span:"T",H1:"H₁",H2:"H₂",H3:"H₃",H4:"H₄",Ul:"☰",Li:"•",Nav:"🧭",Div:"▢",Container:"▢",Flex:"⇆",Grid:"▦",SectionLayout:"▤",ThreeColumnLayout:"⫼",Form:"📝",Input:"⎕",Textarea:"▭",Select:"⏷",Checkbox:"☑",PasswordInput:"🔒",Label:"🏷",DataGrid:"▦",Pagination:"↔",SearchBar:"🔍",ProductCard:"🛍",ImageGallery:"🖼",Avatar:"👤",UserInfo:"👥",HtmlContent:"⟨/⟩",HtmlEditor:"✏",RichTextEditor:"✏",TabNavigation:"◰",QuantitySelector:"#",ProductImageViewer:"🖼",FileUploader:"📎",AvatarUploader:"📷",SocialLoginButtons:"🌐",PostReactions:"❤"}[t]??"◻"}const sA={display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:0,fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Apple SD Gothic Neo", "Noto Sans KR", sans-serif'},aA={display:"flex",justifyContent:"space-between",alignItems:"center",padding:"14px 20px",borderBottom:"1px solid #e2e8f0",flexShrink:0},lA={background:"transparent",border:"none",fontSize:24,cursor:"pointer",lineHeight:1,color:"#64748b",padding:"0 4px"},dA={display:"flex",flex:1,minHeight:0},cA={width:180,flexShrink:0,borderRight:"1px solid #e2e8f0",padding:"14px 8px",background:"#f8fafc",overflowY:"auto"},uA={listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:4},pA={display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",textAlign:"left",padding:"8px 12px",border:"none",borderRadius:6,fontSize:13,cursor:"pointer",transition:"background-color 120ms"},fA={flex:1,display:"flex",flexDirection:"column",minHeight:0,padding:"14px 20px"},gA={width:"100%",padding:"8px 10px",border:"1px solid #cbd5e1",borderRadius:6,marginBottom:12,fontSize:13,flexShrink:0,boxSizing:"border-box"},hA={flex:1,overflowY:"auto",minHeight:0},yA={fontSize:11,color:"#94a3b8",marginLeft:8,fontWeight:500},bA={display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(96px, 1fr))",gap:10},mA={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:6,padding:"14px 6px",background:"#fff",border:"1px solid #e2e8f0",borderRadius:8,cursor:"pointer",fontSize:12,minHeight:84,transition:"border-color 120ms, box-shadow 120ms"},vA={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:6,padding:"14px 6px",background:"#f8fafc",border:"1px dashed #cbd5e1",borderRadius:8,cursor:"not-allowed",fontSize:12,minHeight:84,color:"#94a3b8",opacity:.65},_A={fontSize:9,fontWeight:600,color:"#92400e",background:"#fef3c7",padding:"1px 6px",borderRadius:999,textTransform:"none",letterSpacing:0,lineHeight:1.6},xA={fontSize:22,lineHeight:1,color:"#475569"},wA={fontSize:12,fontWeight:500,color:"#0f172a",textAlign:"center",wordBreak:"break-word"},kA={fontFamily:'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace',fontSize:10,color:"#64748b",textAlign:"center",wordBreak:"break-all"},Mf={padding:24,color:"#64748b",fontSize:13,textAlign:"center"};function SA(e){const t=[],n=r=>{if(Array.isArray(r))for(const s of r)s&&typeof s=="object"&&t.push(s)};n(e.children);const o=e.responsive;if(o&&typeof o=="object")for(const r of Object.values(o))r&&typeof r=="object"&&n(r.children);return t}function Lf(e){const t=[],n=o=>{const r="isolatedState"in o&&o.isolatedState!=null,s=o.isolatedScopeId;(r||typeof s=="string"&&s.length>0)&&t.push({scopeId:typeof s=="string"?s:void 0,initialState:o.isolatedState&&typeof o.isolatedState=="object"?o.isolatedState:void 0});for(const a of SA(o))n(a)};if(Array.isArray(e))for(const o of e)o&&typeof o=="object"&&n(o);return t}const CA=["scroll","selector","wizard","slider"];function $A(e,t){const n=new Set;for(const o of e)o.scopeId&&n.add(o.scopeId);for(const o of t){n.add(o);for(const r of CA)n.add(`${o}-${r}`)}return Array.from(n)}function EA(e,t,n){const o=t.label;return typeof o=="string"?o.startsWith("$t:")?n(o.slice(3)):o:e}function hi({controlKey:e,control:t,node:n,t:o,onPatch:r,candidates:s,bindingCandidates:a,scope:l=Wt}){const d=Tn(t.widget),c=EA(e,t,o),p=u.useMemo(()=>zo(n,t,l),[n,t,l]),f=t.widget==="i18n-text"&&t.apply?.type==="propValue",b=t.widget==="text"&&t.apply?.type==="propValue",g=p.darkReadonly===!0||l.colorScheme==="dark"&&t.apply!==void 0&&!Ys(t.apply),m=t.apply,h=l.colorScheme==="dark"&&!g&&m?.type==="classToken"&&typeof m.tokenTemplate=="string"&&m.tokenTemplate.includes("{value}"),v=p.scopedValue===void 0&&p.baseFallback!==void 0,y=u.useCallback(_=>{if(g)return;const w=fn(n,t,_,l);r(w)},[n,t,r,l,g]);return i.jsxs("div",{className:"g7le-control-row","data-testid":`g7le-control-${e}`,style:IA,children:[i.jsxs("span",{className:"g7le-control-label",style:AA,children:[c,p.conflict&&i.jsx("span",{"data-testid":`g7le-control-conflict-${e}`,title:o("layout_editor.property_modal.value_conflict"),style:TA,children:"!"})]}),i.jsx("div",{className:"g7le-control-widget",style:{flex:1,minWidth:0,opacity:v?.45:1},"data-placeholder":v?"true":void 0,children:f?i.jsx(_t,{value:typeof p.value=="string"?p.value:"",onChange:_=>y(_),t:o,testidPrefix:`g7le-prop-i18n-${e}`,candidates:a,enableExpressionTree:!0,expressionTreeCollapsible:!0}):b?i.jsx(Ke,{value:typeof p.value=="string"?p.value:"",onChange:_=>y(_===""?void 0:_),t:o,testidPrefix:`g7le-prop-value-${e}`,candidates:a}):g?i.jsx("span",{"data-testid":`g7le-control-dark-readonly-${e}`,style:zA,children:o("layout_editor.property_modal.dark_code_only")}):d?i.jsx(d,{control:t,value:p.value,onChange:y,t:o,candidates:s,bindingCandidates:a,freeValueDisabled:h}):i.jsx("span",{"data-testid":`g7le-control-unsupported-${e}`,style:DA,children:o("layout_editor.property_modal.unsupported_widget")})})]})}const IA={display:"flex",alignItems:"center",gap:12,padding:"6px 0",minHeight:32,minWidth:0},AA={fontSize:12,color:"#475569",minWidth:88,display:"inline-flex",alignItems:"center",gap:4},TA={display:"inline-flex",width:14,height:14,borderRadius:7,background:"#f59e0b",color:"#fff",fontSize:10,alignItems:"center",justifyContent:"center",fontWeight:700},DA={fontSize:11,color:"#94a3b8",fontStyle:"italic"},zA={fontSize:11,color:"#94a3b8",fontStyle:"italic"};function yi(e,t,n){return typeof e=="string"?e.startsWith("$t:")?n(e.slice(3)):e:t}function NA(e,t){const n=e.props??{};return t.key in n?n[t.key]:t.default}function MA({spec:e,node:t,t:n,onPatchProp:o}){const r=e.groups??[];return i.jsx("div",{className:"g7le-composite-settings","data-testid":"g7le-composite-settings",style:PA,children:r.map((s,a)=>i.jsxs("div",{className:"g7le-settings-group",style:OA,children:[i.jsx("div",{style:BA,children:yi(s.label,n("layout_editor.property_modal.settings_group",{index:a+1}),n)}),(s.fields??[]).map(l=>i.jsxs("div",{className:"g7le-settings-field","data-testid":`g7le-setting-${l.key}`,style:WA,children:[i.jsx("span",{style:jA,children:yi(l.label,l.key,n)}),i.jsx("div",{style:{flex:1},children:LA(l,t,n,o)})]},l.key))]},a))})}function LA(e,t,n,o){const r=NA(t,e);switch(e.type){case"number":return i.jsx("input",{type:"number","data-testid":`g7le-setting-input-${e.key}`,value:typeof r=="number"?r:"",min:e.min,max:e.max,onChange:s=>o(e.key,s.target.value===""?void 0:Number(s.target.value)),style:Ia});case"text":return i.jsx("input",{type:"text","data-testid":`g7le-setting-input-${e.key}`,value:typeof r=="string"?r:"",onChange:s=>o(e.key,s.target.value===""?void 0:s.target.value),style:Ia});case"toggle":return i.jsx("input",{type:"checkbox","data-testid":`g7le-setting-input-${e.key}`,checked:r===!0,onChange:s=>o(e.key,s.target.checked)});case"checkbox-group":{const s=Array.isArray(r)?r:[];return i.jsx("div",{style:HA,"data-testid":`g7le-setting-input-${e.key}`,children:(e.options??[]).map(a=>{const l=s.includes(a.value);return i.jsxs("label",{style:FA,children:[i.jsx("input",{type:"checkbox",checked:l,onChange:d=>{const c=d.target.checked?[...s,a.value]:s.filter(p=>p!==a.value);o(e.key,c)}}),yi(a.label,String(a.value),n)]},String(a.value))})})}default:return i.jsxs("select",{"data-testid":`g7le-setting-input-${e.key}`,value:r==null?"":String(r),onChange:s=>{const a=s.target.value;if(a===""){o(e.key,void 0);return}const l=(e.options??[]).find(d=>String(d.value)===a);o(e.key,l?l.value:a)},style:Ia,children:[i.jsx("option",{value:"",children:"—"}),(e.options??[]).map(s=>i.jsx("option",{value:String(s.value),children:yi(s.label,String(s.value),n)},String(s.value)))]})}}const PA={display:"flex",flexDirection:"column",gap:16},OA={display:"flex",flexDirection:"column",gap:6},BA={fontSize:12,fontWeight:700,color:"#0f172a",borderBottom:"1px solid #e2e8f0",paddingBottom:4},WA={display:"flex",alignItems:"center",gap:12,minHeight:30},jA={fontSize:12,color:"#475569",minWidth:96},Ia={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",boxSizing:"border-box"},HA={display:"flex",flexWrap:"wrap",gap:10},FA={display:"inline-flex",alignItems:"center",gap:4,fontSize:12,color:"#0f172a"},KA=["data_binding","isolatedScopeId","parentFormContextProp","skipBindingKeys","isolatedState","component_layout","sortable","itemTemplate"],VA=/\{\{|\$switch|\$get|\|\s*(date|number|truncate|currency|relative)\b/;function bi(e,t=0){return t>6?!1:typeof e=="string"?VA.test(e):Array.isArray(e)?e.some(n=>bi(n,t+1)):e&&typeof e=="object"?Object.values(e).some(n=>bi(n,t+1)):!1}function UA(e){if(td(e))return!1;const t=ql(e);return t.length===0?!1:t.some(n=>n.isComplex)}function Pf(e){const t=[],n=e.props??{};for(const o of KA)o in e&&e[o]!==void 0?t.push({key:o,kind:"developer_prop"}):o in n&&n[o]!==void 0&&t.push({key:`props.${o}`,kind:"developer_prop"});typeof e.text=="string"?UA(e.text)&&t.push({key:"text",kind:"complex_expression"}):bi(e.text)&&t.push({key:"text",kind:"complex_expression"});for(const[o,r]of Object.entries(n))o==="style"||o==="className"||bi(r)&&t.push({key:`props.${o}`,kind:"complex_expression"});return t}function qA(e){return Pf(e).length>0}const GA=new Set(["permissions","blur_until_loaded","comment"]);function YA({node:e,advanced:t,t:n,onPatch:o,permissionCandidates:r}){const s=u.useMemo(()=>Pf(e),[e]),a=(l,d)=>{const c={...e};d===void 0?delete c[l]:c[l]=d,o(c)};return i.jsxs("div",{className:"g7le-advanced-props","data-testid":"g7le-advanced-props",style:XA,children:[t.map(l=>{if(!GA.has(l))return i.jsxs("div",{"data-testid":`g7le-advanced-deferred-${l}`,style:ZA,children:[n("layout_editor.property_modal.advanced_deferred"),":",l]},l);if(l==="permissions")return i.jsxs("div",{className:"g7le-advanced-group","data-testid":"g7le-advanced-permissions",style:Aa,children:[i.jsx("div",{style:Ta,children:n("layout_editor.property_modal.advanced.permissions")}),i.jsx(vs,{control:{widget:"tag-input"},value:e.permissions,onChange:d=>a("permissions",d),t:n,candidates:r})]},l);if(l==="blur_until_loaded"){const d=e.blur_until_loaded===!0||e.blur_until_loaded!=null&&e.blur_until_loaded!==!1;return i.jsxs("div",{className:"g7le-advanced-group","data-testid":"g7le-advanced-blur",style:Aa,children:[i.jsx("div",{style:Ta,children:n("layout_editor.property_modal.advanced.blur_until_loaded")}),i.jsxs("label",{style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:12},children:[i.jsx("input",{type:"checkbox","data-testid":"g7le-advanced-blur-toggle",checked:!!d,onChange:c=>a("blur_until_loaded",c.target.checked?!0:void 0)}),n("layout_editor.property_modal.advanced.blur_hint")]})]},l)}return i.jsxs("div",{className:"g7le-advanced-group","data-testid":"g7le-advanced-comment",style:Aa,children:[i.jsx("div",{style:Ta,children:n("layout_editor.property_modal.advanced.comment")}),i.jsx("input",{type:"text","data-testid":"g7le-advanced-comment-input",value:typeof e.comment=="string"?e.comment:"",onChange:d=>a("comment",d.target.value===""?void 0:d.target.value),style:JA})]},l)}),s.length>0&&i.jsxs("div",{className:"g7le-advanced-preserved","data-testid":"g7le-advanced-preserved",style:QA,children:[i.jsx("div",{style:RA,children:n("layout_editor.property_modal.advanced_preserved_title",{count:s.length})}),i.jsx("ul",{style:e6,children:s.map(l=>i.jsxs("li",{"data-testid":`g7le-advanced-preserved-${l.key}`,style:t6,children:[i.jsx("code",{style:{fontSize:11},children:l.key}),i.jsx("span",{style:{fontSize:11,color:"#94a3b8"},children:l.kind==="developer_prop"?n("layout_editor.property_modal.advanced_kind_developer"):n("layout_editor.property_modal.advanced_kind_expression")})]},l.key))})]})]})}const XA={display:"flex",flexDirection:"column",gap:14},Aa={display:"flex",flexDirection:"column",gap:6},Ta={fontSize:12,fontWeight:700,color:"#0f172a"},JA={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",boxSizing:"border-box"},ZA={fontSize:11,color:"#94a3b8",fontStyle:"italic"},QA={borderTop:"1px dashed #cbd5e1",paddingTop:10,marginTop:4},RA={fontSize:11,color:"#b45309",marginBottom:6},e6={listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:4},t6={display:"flex",justifyContent:"space-between",gap:8,padding:"3px 0"},n6={onClick:"click",onHover:"mouseenter",onChange:"change",onSubmit:"submit",onMount:"mount",onUnmount:"unmount",onFocus:"focus",onBlur:"blur"};function Da(e){return n6[e]??e.replace(/^on/,"").toLowerCase()}function Of(e){const t=e.actions;if(Array.isArray(t))return t.filter(r=>!!r&&typeof r=="object");const n=e.props??{};if(Array.isArray(n.actions))return n.actions.filter(r=>!!r&&typeof r=="object");const o=n.events;if(o&&typeof o=="object"){const r=[];for(const[s,a]of Object.entries(o)){if(!Array.isArray(a))continue;const l=Da(s);for(const d of a)d&&typeof d=="object"&&r.push("type"in d?d:{type:l,...d})}return r}return[]}function o6(e,t){const n=Da(t);return Of(e).filter(o=>o.type===n||t==="onClick"&&o.type===void 0)}function r6(e,t,n){const o=Da(t),r=Of(e).filter(d=>!(d.type===o||t==="onClick"&&d.type===void 0)),s=n.map(d=>"type"in d?d:{type:o,...d}),a={...e};if(a.props&&typeof a.props=="object"){const d={...a.props};let c=!1;"actions"in d&&(delete d.actions,c=!0),"events"in d&&(delete d.events,c=!0),c&&(a.props=d)}const l=[...r,...s];return l.length===0?delete a.actions:a.actions=l,a}function i6({node:e,spec:t,capability:n,t:o,onPatchNode:r,pageCandidates:s,dataSourceCandidates:a,stateKeyCandidates:l,bindingCandidates:d}){const c=t?.actionRecipes,p=u.useMemo(()=>({pageCandidates:s,dataSourceCandidates:a,stateKeyCandidates:l,bindingCandidates:d}),[s,a,l,d]),f=Array.isArray(n?.events)?n.events:[];return f.length===0?i.jsx("div",{"data-testid":"g7le-action-no-events",style:Bf,children:o("layout_editor.action.no_events")}):!c||Object.keys(c).length===0?i.jsx("div",{"data-testid":"g7le-action-no-recipes",style:Bf,children:o("layout_editor.action.no_recipes")}):i.jsx("div",{className:"g7le-action-editor","data-testid":"g7le-action-editor",style:{display:"flex",flexDirection:"column",gap:14},children:f.map(b=>i.jsxs("div",{className:"g7le-action-event-slot","data-testid":`g7le-action-event-${b}`,children:[i.jsx("div",{style:s6,children:o(`layout_editor.action.event.${b}`)}),i.jsx(Gt,{actions:o6(e,b),onChange:g=>r(r6(e,b,g)),t:o,recipes:c,candidatePools:p,actionChipCandidates:t?.actionChipCandidates??null,addContext:"component",showSourceBadge:!0,testIdPrefix:`g7le-action-slot-${b}`})]},b))})}const Bf={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},s6={fontSize:12,fontWeight:700,color:"#475569",marginBottom:6};function za(e,t,n){if(!t)return n;const o=e(t);return!o||o===t||o.startsWith("$t:")?n:o}function a6(e,t){return za(t,e.labelKey,e.path||e.sourceId)}function l6({node:e,spec:t,candidates:n,t:o,onPatchNode:r}){const a=(e.props??{})[t.propKey],l=typeof a=="string"?a:void 0,d=u.useMemo(()=>Kt(a),[a]),c=l!==void 0&&l!==""&&d===null,[p,f]=u.useState(!1),[b,g]=u.useState(""),m=za(o,t.label,t.propKey),h=o(t.shape==="array"?"layout_editor.binding.shape_array":t.shape==="object"?"layout_editor.binding.shape_object":"layout_editor.binding.shape_scalar"),v=u.useMemo(()=>Ui(n,t.shape).map(x=>({...x,resolvedLabel:a6(x,o)})),[n,t.shape,o]),y=u.useMemo(()=>qi(v,b),[v,b]),_=k=>{const x={...e.props??{}};k===void 0?delete x[t.propKey]:x[t.propKey]=k,r({...e,props:x})},w=k=>{_(En(k.sourceId,k.path,t.shape)),f(!1),g("")};return i.jsxs("div",{"data-testid":`g7le-binding-row-${t.propKey}`,style:p6,children:[i.jsxs("div",{style:f6,children:[i.jsx("span",{style:{fontWeight:600,fontSize:12},children:m}),i.jsx("span",{style:g6,children:h}),t.required&&i.jsx("span",{"data-testid":`g7le-binding-required-${t.propKey}`,style:h6,children:o("layout_editor.binding.required")})]}),c?i.jsxs("div",{"data-testid":`g7le-binding-complex-${t.propKey}`,style:v6,children:[o("layout_editor.binding.complex"),i.jsx("code",{style:Wf,children:l})]}):d?i.jsxs("div",{style:y6,children:[i.jsx("code",{"data-testid":`g7le-binding-expr-${t.propKey}`,style:Wf,children:l}),i.jsx("button",{type:"button","data-testid":`g7le-binding-clear-${t.propKey}`,onClick:()=>_(void 0),style:m6,children:o("layout_editor.binding.clear")})]}):i.jsx("div",{"data-testid":`g7le-binding-empty-${t.propKey}`,style:b6,children:o("layout_editor.binding.not_connected")}),d&&(t.shape==="array"||t.shape==="object")&&t.itemFields&&t.itemFields.length>0&&i.jsxs("div",{style:_6,children:[o("layout_editor.binding.item_fields"),": ",t.itemFields.join(", ")]}),!c&&i.jsxs("div",{style:{marginTop:4},children:[i.jsxs("button",{type:"button","data-testid":`g7le-binding-search-toggle-${t.propKey}`,onClick:()=>f(k=>!k),style:x6,children:["🔍 ",o("layout_editor.binding.search")]}),p&&i.jsxs("div",{"data-testid":`g7le-binding-picker-${t.propKey}`,style:w6,children:[i.jsx("input",{type:"text",autoFocus:!0,"data-testid":`g7le-binding-search-input-${t.propKey}`,value:b,placeholder:o("layout_editor.binding.search_placeholder"),onChange:k=>g(k.target.value),style:k6}),i.jsx("div",{style:S6,children:y.length===0?i.jsx("div",{style:C6,children:o("layout_editor.binding.no_results")}):y.map(k=>i.jsxs("button",{type:"button","data-testid":`g7le-binding-candidate-${k.expression}`,onClick:()=>w(k),style:$6,children:[i.jsxs("span",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start"},children:[i.jsx("span",{style:{fontSize:12},children:k.resolvedLabel}),i.jsxs("span",{style:E6,children:[za(o,k.groupLabelKey,k.sourceId)," · ",k.path||k.sourceId]})]}),i.jsx("span",{style:I6,children:k.preview})]},k.expression))})]})]})]})}function d6({node:e,dataProps:t,candidates:n,t:o,onPatchNode:r}){return!Array.isArray(t)||t.length===0?null:i.jsxs("div",{"data-testid":"g7le-data-binding-section",style:c6,children:[i.jsxs("div",{style:u6,children:["🔗 ",o("layout_editor.binding.section_title")]}),t.map(s=>i.jsx(l6,{node:e,spec:s,candidates:n,t:o,onPatchNode:r},s.propKey)),i.jsx("div",{style:A6})]})}const c6={display:"flex",flexDirection:"column",marginBottom:8},u6={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:6},p6={display:"flex",flexDirection:"column",gap:4,padding:"8px 0"},f6={display:"flex",alignItems:"center",gap:6},g6={fontSize:10,padding:"1px 6px",borderRadius:4,background:"#e0e7ff",color:"#3730a3"},h6={fontSize:10,padding:"1px 6px",borderRadius:4,background:"#fef3c7",color:"#92400e"},y6={display:"flex",alignItems:"center",gap:6},b6={fontSize:11,color:"#94a3b8"},Wf={fontSize:11,fontFamily:"monospace",background:"#f1f5f9",padding:"2px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all"},m6={fontSize:11,border:"1px solid #e2e8f0",borderRadius:4,background:"#fff",color:"#dc2626",padding:"2px 8px",cursor:"pointer"},v6={display:"flex",flexDirection:"column",gap:2,fontSize:11,color:"#64748b"},_6={fontSize:10,color:"#94a3b8"},x6={fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#334155",padding:"4px 10px",cursor:"pointer",textAlign:"left",width:"100%"},w6={marginTop:4,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",padding:6},k6={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},S6={marginTop:4,maxHeight:200,overflowY:"auto",display:"flex",flexDirection:"column",gap:2},C6={fontSize:11,color:"#94a3b8",padding:"8px 0",textAlign:"center"},$6={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,border:"none",background:"transparent",cursor:"pointer",padding:"6px 8px",borderRadius:4,textAlign:"left"},E6={fontSize:10,color:"#94a3b8"},I6={fontSize:10,color:"#64748b",fontFamily:"monospace",whiteSpace:"nowrap"},A6={borderTop:"1px solid #e2e8f0",marginTop:4};function T6({node:e,candidates:t,t:n,onPatchNode:o,templateIdentifier:r}){const s=typeof e.text=="string"?e.text:"",{state:a}=Qe(),l=r??a.templateIdentifier,d=a.selectedRoute?.layoutName??null,c=a.locale,[p,f]=u.useState(!1),b=/^\s*\$t:custom\.[A-Za-z0-9._-]+\s*$/.test(s),m=td(s)&&(vt(s)?.key.startsWith("custom.")??!1)||b,h=u.useMemo(()=>m?vt(s):null,[m,s]),v=u.useMemo(()=>m?[]:ql(s),[m,s]),y=T=>{o({...e,text:T})},_=()=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:l,locale:c}}))}catch{}},w=(T,E)=>{const A=En(E.sourceId,E.path,"scalar");y(Ab(s,T,A))},k=T=>{const E=vt(s);y(vo(s,T));const A=E?.key;l&&A&&qd(l,A,T).then(_)},x=T=>{const E=n(T);return E&&E!==T&&!E.startsWith("$t:")?E:""},$=T=>T.replace(/\$t:[a-zA-Z0-9._-]+/g,E=>x(E.slice(3))).replace(/\s+/g," ").trim(),S=T=>{p||(f(!0),us(l,d,c,s,s.length,T.sourceId,T.path,"scalar",$,E=>n(E)).then(E=>{E.kind==="ok"&&(y(E.text),_())}).finally(()=>f(!1)))},C=T=>{p||!h&&!b||(f(!0),Cr(l,c,s,Number.MAX_SAFE_INTEGER,T.sourceId,T.path,"scalar").then(E=>{E.kind==="ok"&&(y(E.text),_())}).finally(()=>f(!1)))};if(m){const T=h?.params??[];return i.jsxs("div",{"data-testid":"g7le-inline-binding-section",style:jf,children:[i.jsxs("div",{style:Hf,children:["🔗 ",n("layout_editor.inline_binding.section_title")]}),T.length===0?i.jsx("div",{"data-testid":"g7le-inline-binding-none",style:Vf,children:n("layout_editor.inline_binding.none")}):T.map(E=>i.jsx("div",{"data-testid":`g7le-inline-binding-param-${E.name}`,style:Ff,children:E.parsed===null?i.jsxs("div",{"data-testid":`g7le-inline-binding-param-complex-${E.name}`,style:z6,children:[n("layout_editor.inline_binding.complex"),i.jsx("code",{style:Na,children:E.expression})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:Kf,children:[i.jsx("code",{"data-testid":`g7le-inline-binding-param-expr-${E.name}`,style:Na,children:E.expression}),i.jsx("button",{type:"button","data-testid":`g7le-inline-binding-param-clear-${E.name}`,onClick:()=>k(E.name),style:D6,children:n("layout_editor.inline_binding.clear")})]}),i.jsx($t,{candidates:t,t:n,onSelect:A=>w(E.name,A),testIdSuffix:`param-${E.name}`})]})},E.name)),i.jsxs("div",{"data-testid":"g7le-inline-binding-param-append",style:Uf,children:[i.jsx("div",{style:Ma,children:n("layout_editor.inline_binding.append_hint")}),i.jsx($t,{candidates:t,t:n,onSelect:C,testIdSuffix:"param-append"})]}),i.jsx("div",{"data-testid":"g7le-inline-binding-param-hint",style:Ma,children:n("layout_editor.inline_binding.param_hint")}),i.jsx("div",{style:qf})]})}return i.jsxs("div",{"data-testid":"g7le-inline-binding-section",style:jf,children:[i.jsxs("div",{style:Hf,children:["🔗 ",n("layout_editor.inline_binding.section_title")]}),v.length===0?i.jsx("div",{"data-testid":"g7le-inline-binding-none",style:Vf,children:n("layout_editor.inline_binding.none")}):v.map(T=>i.jsx("div",{"data-testid":`g7le-inline-binding-row-${T.bindingIndex}`,style:Ff,children:i.jsx("div",{style:Kf,children:i.jsx("code",{"data-testid":`g7le-inline-binding-expr-${T.bindingIndex}`,style:Na,children:T.expression})})},T.bindingIndex)),i.jsxs("div",{"data-testid":"g7le-inline-binding-append",style:Uf,children:[i.jsx("div",{style:Ma,children:n("layout_editor.inline_binding.append_hint")}),i.jsx($t,{candidates:t,t:n,onSelect:S,testIdSuffix:"append"})]}),i.jsx("div",{style:qf})]})}const jf={display:"flex",flexDirection:"column",marginBottom:8},Hf={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:6},Ff={display:"flex",flexDirection:"column",gap:4,padding:"8px 0"},Kf={display:"flex",alignItems:"center",gap:6},Vf={fontSize:11,color:"#94a3b8"},Na={fontSize:11,fontFamily:"monospace",background:"#f1f5f9",padding:"2px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all"},D6={fontSize:11,border:"1px solid #e2e8f0",borderRadius:4,background:"#fff",color:"#dc2626",padding:"2px 8px",cursor:"pointer"},z6={display:"flex",flexDirection:"column",gap:2,fontSize:11,color:"#64748b"},Uf={display:"flex",flexDirection:"column",gap:2,padding:"8px 0 0"},Ma={fontSize:11,color:"#475569",fontWeight:600},qf={borderTop:"1px solid #e2e8f0",marginTop:4};function Gf(e,t,n){if(!t)return n;const o=e(t);return!o||o===t||o.startsWith("$t:")?n:o}function N6(e,t){return Gf(t,e.labelKey,e.path||e.sourceId)}function M6(e){const t=e.iteration;return t&&typeof t=="object"?t:null}function L6({node:e,candidates:t,t:n,onPatchNode:o}){const r=M6(e),s=r?.source,a=typeof s=="string"?s:void 0,l=u.useMemo(()=>Kt(s),[s]),d=a!==void 0&&a!==""&&l===null,[c,p]=u.useState(!1),[f,b]=u.useState(""),g=u.useMemo(()=>Ui(t,"array").map(k=>({...k,resolvedLabel:N6(k,n)})),[t,n]),m=u.useMemo(()=>qi(g,f),[g,f]);if(!r)return null;const h=typeof r.item_var=="string"?r.item_var:void 0,v=typeof r.index_var=="string"?r.index_var:void 0,y=w=>{const k={...r};w===void 0?delete k.source:k.source=w,o({...e,iteration:k})},_=w=>{y(En(w.sourceId,w.path,"array")),p(!1),b("")};return i.jsxs("div",{"data-testid":"g7le-iteration-binding-section",style:P6,children:[i.jsxs("div",{style:O6,children:["🔁 ",n("layout_editor.binding.iteration_title")]}),i.jsx("div",{style:B6,children:n("layout_editor.binding.iteration_hint")}),i.jsxs("div",{style:W6,children:[i.jsxs("div",{style:j6,children:[i.jsx("span",{style:{fontWeight:600,fontSize:12},children:n("layout_editor.binding.iteration_label")}),i.jsx("span",{style:H6,children:n("layout_editor.binding.shape_array")})]}),d?i.jsxs("div",{"data-testid":"g7le-iteration-binding-complex",style:U6,children:[n("layout_editor.binding.complex"),i.jsx("code",{style:Yf,children:a})]}):l?i.jsxs("div",{style:F6,children:[i.jsx("code",{"data-testid":"g7le-iteration-binding-expr",style:Yf,children:a}),i.jsx("button",{type:"button","data-testid":"g7le-iteration-binding-clear",onClick:()=>y(void 0),style:V6,children:n("layout_editor.binding.clear")})]}):i.jsx("div",{"data-testid":"g7le-iteration-binding-empty",style:K6,children:n("layout_editor.binding.not_connected")}),(h||v)&&i.jsxs("div",{"data-testid":"g7le-iteration-vars",style:q6,children:[h&&i.jsxs("span",{children:[n("layout_editor.binding.iteration_item_var"),": ",i.jsx("code",{style:Xf,children:h})]}),v&&i.jsxs("span",{children:[n("layout_editor.binding.iteration_index_var"),": ",i.jsx("code",{style:Xf,children:v})]})]}),!d&&i.jsxs("div",{style:{marginTop:4},children:[i.jsxs("button",{type:"button","data-testid":"g7le-iteration-binding-search-toggle",onClick:()=>p(w=>!w),style:G6,children:["🔍 ",n("layout_editor.binding.search")]}),c&&i.jsxs("div",{"data-testid":"g7le-iteration-binding-picker",style:Y6,children:[i.jsx("input",{type:"text",autoFocus:!0,"data-testid":"g7le-iteration-binding-search-input",value:f,placeholder:n("layout_editor.binding.search_placeholder"),onChange:w=>b(w.target.value),style:X6}),i.jsx("div",{style:J6,children:m.length===0?i.jsx("div",{style:Z6,children:n("layout_editor.binding.no_results")}):m.map(w=>i.jsxs("button",{type:"button","data-testid":`g7le-iteration-binding-candidate-${w.expression}`,onClick:()=>_(w),style:Q6,children:[i.jsxs("span",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start"},children:[i.jsx("span",{style:{fontSize:12},children:w.resolvedLabel}),i.jsxs("span",{style:R6,children:[Gf(n,w.groupLabelKey,w.sourceId)," · ",w.path||w.sourceId]})]}),i.jsx("span",{style:eT,children:w.preview})]},w.expression))})]})]})]}),i.jsx("div",{style:tT})]})}const P6={display:"flex",flexDirection:"column",marginBottom:8},O6={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:4},B6={fontSize:10,color:"#94a3b8",marginBottom:6,lineHeight:1.4},W6={display:"flex",flexDirection:"column",gap:4,padding:"8px 0"},j6={display:"flex",alignItems:"center",gap:6},H6={fontSize:10,padding:"1px 6px",borderRadius:4,background:"#e0e7ff",color:"#3730a3"},F6={display:"flex",alignItems:"center",gap:6},K6={fontSize:11,color:"#94a3b8"},Yf={fontSize:11,fontFamily:"monospace",background:"#f1f5f9",padding:"2px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all"},V6={fontSize:11,border:"1px solid #e2e8f0",borderRadius:4,background:"#fff",color:"#dc2626",padding:"2px 8px",cursor:"pointer"},U6={display:"flex",flexDirection:"column",gap:2,fontSize:11,color:"#64748b"},q6={display:"flex",gap:12,fontSize:10,color:"#94a3b8",marginTop:2},Xf={fontSize:10,fontFamily:"monospace",background:"#f1f5f9",padding:"1px 4px",borderRadius:3,color:"#475569"},G6={fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#334155",padding:"4px 10px",cursor:"pointer",textAlign:"left",width:"100%"},Y6={marginTop:4,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",padding:6},X6={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},J6={marginTop:4,maxHeight:200,overflowY:"auto",display:"flex",flexDirection:"column",gap:2},Z6={fontSize:11,color:"#94a3b8",padding:"8px 0",textAlign:"center"},Q6={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,border:"none",background:"transparent",cursor:"pointer",padding:"6px 8px",borderRadius:4,textAlign:"left"},R6={fontSize:10,color:"#94a3b8"},eT={fontSize:10,color:"#64748b",fontFamily:"monospace",whiteSpace:"nowrap"},tT={borderTop:"1px solid #e2e8f0",marginTop:4},nT=new Set(["Span","P","H1","H2","H3","H4","H5","H6","A","Button","Li","Label"]);function oT(e,t){if(!e||e.iteration&&typeof e.iteration=="object")return!1;const n=t?.textBinding;if(n===!1)return!1;if(n===!0)return!0;const o=typeof e.name=="string"?e.name:"";return nT.has(o)?!0:typeof e.text=="string"}const yn={direction:"flexDirection",justify:"flexJustify",align:"flexAlign",wrap:"flexWrap",gap:"flexGap",enable:"flexEnable"},mi={grow:"flexItemGrow",selfAlign:"flexItemAlign",order:"flexItemOrder"};function Jf(e){const t=e?.flexEditor;return t==="container"||t==="item"||t==="auto"?t:null}function rT(e){if(!e||typeof window>"u"||typeof window.getComputedStyle!="function")return!1;const t=(window.getComputedStyle(e).display??"").toLowerCase();return t==="flex"||t==="inline-flex"}function iT(e,t,n=Wt){if(!e||!t)return!1;const o=zo(e,t,n),r=t.options,s=Array.isArray(r)?t.onValue??r[0]?.value:void 0,a=l=>s!==void 0?l===s:l!==void 0&&l!==!1;return n.breakpoint!=="base"?a(o.scopedRawValue):o.matched&&a(o.value)}function sT(e,t,n=!1,o=!1,r=Wt){if(e==="container")return{showContainer:!0,showEnableButton:!1,showDisableButton:!1};if(e==="item")return{showContainer:!1,showEnableButton:!1,showDisableButton:!1};if(e==="auto"){const s=r.breakpoint==="base";return!o&&!s?{showContainer:!1,showEnableButton:!1,showDisableButton:!1}:(o?n:rT(t))?{showContainer:!0,showEnableButton:!1,showDisableButton:o}:{showContainer:!1,showEnableButton:!0,showDisableButton:!1}}return{showContainer:!1,showEnableButton:!1,showDisableButton:!1}}const aT={[yn.direction]:"layout_editor.flex.direction",[yn.justify]:"layout_editor.flex.justify",[yn.align]:"layout_editor.flex.align",[yn.wrap]:"layout_editor.flex.wrap",[yn.gap]:"layout_editor.flex.gap"},lT={[mi.grow]:"layout_editor.flex.item_grow",[mi.selfAlign]:"layout_editor.flex.item_align",[mi.order]:"layout_editor.flex.item_order"};function dT({node:e,spec:t,capability:n,t:o,onPatchNode:r,liveElement:s,scope:a=Wt}){const l=Jf(n),d=Ct(t,yn.enable),c=iT(e,d,a),{showContainer:p,showEnableButton:f,showDisableButton:b}=sT(l,s,c,!!d,a),g=Object.values(yn).filter(x=>x!==yn.enable&&Ct(t,x)),m=Object.values(mi).filter(x=>Ct(t,x)),h=d?.options,v=d?.onValue??h?.[0]?.value??!0,y=Array.isArray(h)&&h.length>=2?h[1].value:void 0,_=()=>{if(!d)return;const x=fn(e,d,v,a);r(x)},w=()=>{if(!d)return;const x=a.breakpoint!=="base"&&y!==void 0?y:void 0,$=fn(e,d,x,a);r($)},k=(x,$,S)=>i.jsx("div",{"data-testid":S,style:{display:"flex",flexDirection:"column"},children:x.map(C=>{const T=Ct(t,C);if(!T)return null;const E=T.label?T:{...T,label:`$t:${$[C]}`};return i.jsx(hi,{controlKey:C,control:E,node:e,t:o,onPatch:r,scope:a},C)})});return i.jsxs("div",{className:"g7le-flex-editor","data-testid":"g7le-flex-editor",style:{display:"flex",flexDirection:"column",gap:12},children:[f&&i.jsx("button",{type:"button","data-testid":"g7le-flex-enable",onClick:_,style:cT,children:o("layout_editor.flex.make_flex")}),p&&g.length>0&&i.jsxs("div",{className:"g7le-flex-container-section","data-testid":"g7le-flex-container-section",children:[i.jsx("div",{style:Zf,children:o("layout_editor.flex.container_title")}),k(g,aT,"g7le-flex-container-controls"),b&&i.jsx("button",{type:"button","data-testid":"g7le-flex-disable",onClick:w,style:uT,children:o("layout_editor.flex.unmake_flex")})]}),l==="item"&&m.length>0&&i.jsxs("div",{className:"g7le-flex-item-section","data-testid":"g7le-flex-item-section",children:[i.jsx("div",{style:Zf,children:o("layout_editor.flex.item_title")}),k(m,lT,"g7le-flex-item-controls")]}),!p&&!f&&l!=="item"&&i.jsx("div",{"data-testid":"g7le-flex-empty",style:pT,children:o("layout_editor.flex.not_flex")})]})}const Zf={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:6},cT={padding:"8px 12px",fontSize:12,border:"1px dashed #2563eb",borderRadius:6,background:"#eff6ff",color:"#2563eb",cursor:"pointer"},uT={marginTop:8,padding:"6px 10px",fontSize:12,border:"1px solid #e2e8f0",borderRadius:6,background:"#f8fafc",color:"#64748b",cursor:"pointer"},pT={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},Qf=["desktop","tablet","mobile","portable"],La=1280,fT=820,gT=390,hT=1920,yT=320;function bT(e){const t=[],n=new Set,o=r=>{if(!r||typeof r!="object")return;const s=r.responsive;if(s&&typeof s=="object")for(const a of Object.keys(s)){n.has(a)||(n.add(a),t.push(a));const l=s[a]?.children;if(Array.isArray(l))for(const d of l)o(d)}if(Array.isArray(r.children))for(const a of r.children)o(a)};if(Array.isArray(e))for(const r of e)o(r);return t}function mT(e){const t=[...Qf],n=new Set(Qf);for(const o of bT(e))!n.has(o)&&!t.includes(o)&&t.push(o);return t}function vT(e,t){const n=e?.responsive;if(!n||typeof n!="object")return[];const o=[];for(const r of Object.keys(n)){const s=n[r];!s||!Array.isArray(s.children)||r!==t&&o.push(r)}return o}function _T(e){switch(e){case"desktop":return La;case"tablet":return fT;case"mobile":return gT}const t=e in Do?Do[e]:Mn.parseRange(e);return!t||!Number.isFinite(t.max)?La:Math.round(Math.max(yT,Math.min(hT,t.max)))}function Rf(){const t=Ft()?.document?.raw?.components;return u.useMemo(()=>mT(t??null),[t])}const xT={desktop:"layout_editor.property_modal.scope.device_desktop",tablet:"layout_editor.property_modal.scope.device_tablet",mobile:"layout_editor.property_modal.scope.device_mobile",portable:"layout_editor.property_modal.scope.device_portable"},wT=[{key:"base",labelKey:"layout_editor.property_modal.scope.scheme_light"},{key:"dark",labelKey:"layout_editor.property_modal.scope.scheme_dark"}];function eg({scope:e,onChange:t,node:n,t:o,showColorScheme:r=!0,onClearScope:s}){const[a,l]=u.useState(!1),[d,c]=u.useState(""),[p,f]=u.useState(""),[b,g]=u.useState(null),m=Rf(),h=u.useMemo(()=>{const w=["base",...m],k=new Set(w);for(const x of Object.keys(n.responsive??{}))x!=="base"&&!k.has(x)&&(k.add(x),w.push(x));return e.breakpoint!=="base"&&!k.has(e.breakpoint)&&w.push(e.breakpoint),w},[m,n.responsive,e.breakpoint]),v=w=>t({...e,colorScheme:w}),y=w=>t({...e,breakpoint:w}),_=()=>{const w=d.trim(),k=p.trim();if(w===""&&k===""){g(o("layout_editor.property_modal.scope.custom_invalid"));return}const x=`${w}-${k}`;if(!xC(x)){g(o("layout_editor.property_modal.scope.custom_invalid"));return}g(null),l(!1),c(""),f(""),y(x)};return i.jsxs("div",{className:"g7le-style-scope-tabs","data-testid":"g7le-style-scope-tabs",style:kT,children:[r&&i.jsx("div",{className:"g7le-style-scope-scheme","data-testid":"g7le-style-scope-scheme",role:"tablist","aria-label":o("layout_editor.property_modal.scope.scheme_light"),style:tg,children:wT.map(w=>{const k=e.colorScheme===w.key;return i.jsxs("button",{type:"button",role:"tab","aria-selected":k,"data-testid":`g7le-style-scheme-${w.key}`,"data-active":k?"true":"false",onClick:()=>v(w.key),style:ng(k),children:[o(w.labelKey),w.key==="dark"&&Js(n,{colorScheme:"dark",breakpoint:e.breakpoint})&&i.jsx("span",{"data-testid":"g7le-style-scheme-dark-dot",style:og})]},w.key)})}),i.jsxs("div",{className:"g7le-style-scope-device","data-testid":"g7le-style-scope-device",role:"tablist","aria-label":o("layout_editor.property_modal.scope.device_base"),style:tg,children:[h.map(w=>{const k=e.breakpoint===w,x=w==="base"||$u(w),$=w==="base"?"layout_editor.property_modal.scope.device_base":xT[w],S=$?o($):w,C=x?`g7le-style-bp-${w}`:`g7le-style-bp-custom-${w}`;return i.jsxs("button",{type:"button",role:"tab","aria-selected":k,"data-testid":C,"data-active":k?"true":"false",onClick:()=>y(w),style:ng(k),children:[S,Js(n,{colorScheme:"base",breakpoint:w})&&i.jsx("span",{"data-testid":`${C}-dot`,style:og})]},String(w))}),i.jsxs("button",{type:"button","data-testid":"g7le-style-bp-add-custom",onClick:()=>l(w=>!w),style:$T,children:["+ ",o("layout_editor.property_modal.scope.add_custom")]})]}),a&&i.jsxs("div",{className:"g7le-style-scope-custom-input","data-testid":"g7le-style-scope-custom-input",style:ST,children:[i.jsx("input",{type:"number","data-testid":"g7le-style-custom-min",placeholder:o("layout_editor.property_modal.scope.custom_min"),value:d,onChange:w=>c(w.target.value),style:rg}),i.jsx("span",{style:{color:"#94a3b8"},children:"—"}),i.jsx("input",{type:"number","data-testid":"g7le-style-custom-max",placeholder:o("layout_editor.property_modal.scope.custom_max"),value:p,onChange:w=>f(w.target.value),style:rg}),i.jsx("button",{type:"button","data-testid":"g7le-style-custom-confirm",onClick:_,style:ET,children:o("layout_editor.property_modal.scope.add_custom")})]}),b&&i.jsx("div",{"data-testid":"g7le-style-custom-error",style:IT,children:b}),e.breakpoint!=="base"&&!$u(e.breakpoint)&&i.jsx("div",{"data-testid":"g7le-style-custom-priority-note",style:AT,children:o("layout_editor.property_modal.scope.custom_priority_note")}),s&&Js(n,e)&&i.jsxs("button",{type:"button","data-testid":"g7le-style-scope-reset",onClick:s,style:CT,children:["↺ ",o("layout_editor.property_modal.scope.reset_to_base")]})]})}const kT={display:"flex",flexDirection:"column",gap:0,padding:"0 0 8px",borderBottom:"1px solid #e2e8f0",marginBottom:8},ST={display:"flex",gap:6,alignItems:"center",marginTop:4},tg={display:"flex",gap:2,flexWrap:"wrap",borderBottom:"1px solid #e2e8f0",margin:"0 -16px",padding:"0 12px"};function ng(e){return{display:"inline-flex",alignItems:"center",gap:4,padding:"6px 12px",fontSize:12,border:"none",borderBottom:`2px solid ${e?"#2563eb":"transparent"}`,background:"transparent",color:e?"#2563eb":"#64748b",cursor:"pointer",fontWeight:e?700:500,marginBottom:-1}}const og={display:"inline-block",width:5,height:5,borderRadius:3,background:"#f59e0b"},CT={alignSelf:"flex-start",marginTop:2,padding:"3px 8px",fontSize:10,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},$T={padding:"6px 12px",fontSize:11,border:"none",borderBottom:"2px dashed #cbd5e1",background:"transparent",color:"#475569",cursor:"pointer",marginBottom:-1},rg={width:70,padding:"4px 6px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6},ET={padding:"4px 10px",fontSize:11,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"},IT={fontSize:11,color:"#dc2626"},AT={fontSize:10,color:"#94a3b8"},ig=new Map;function Pn(e,t){ig.set(e,t)}function TT(e){return e?ig.get(e)??null:null}const Pa={id:{label:"$t:layout_editor.core_props.id.label",widget:"core-id",placeholder:"$t:layout_editor.core_props.id.placeholder",apply:{type:"propValue",propKey:"id"}},dataKey:{label:"$t:layout_editor.core_props.dataKey.label",widget:"core-datakey",placeholder:"$t:layout_editor.core_props.dataKey.placeholder",apply:{type:"nodeKey",nodeKey:"dataKey"}},isolatedState:{label:"$t:layout_editor.core_props.isolatedState.label",widget:"toggle",apply:{type:"nodeKey",nodeKey:"isolatedState"}},isolatedScopeId:{label:"$t:layout_editor.core_props.isolatedScopeId.label",widget:"core-scopeid",placeholder:"$t:layout_editor.core_props.isolatedScopeId.placeholder",apply:{type:"nodeKey",nodeKey:"isolatedScopeId"}}},DT=["id"];function zT(e){return e===!1?[]:Array.isArray(e)?e.filter(t=>t in Pa):[...DT]}function sg(e){const t=e.props?.id??e.id;return typeof t=="string"&&t.length>0?`${t}-scope`:"scope"}function NT({node:e,onPatchNode:t,t:n,scopeIdCandidates:o=[],usedScopeIds:r=[]}){const s=e,a="isolatedState"in s&&s.isolatedState!=null,l=typeof s.isolatedScopeId=="string"?s.isolatedScopeId:"",[d,c]=u.useState(""),p=()=>{const h={...e};a?(delete h.isolatedState,delete h.isolatedScopeId):(h.isolatedState={},h.isolatedScopeId=sg(e)),t(h)},f=h=>{const v={...e};v.isolatedScopeId=h.trim()===""?sg(e):h,t(v)},b=h=>{const v={...e};v.isolatedState=h,t(v)},g=u.useMemo(()=>{const h=d.trim().toLowerCase();return o.filter(v=>!h||v.toLowerCase().includes(h))},[o,d]),m=l!==""&&r.includes(l);return i.jsxs("div",{className:"g7le-isolated-scope","data-testid":"g7le-isolated-scope-control",style:MT,children:[i.jsx("div",{style:LT,children:n("layout_editor.core_props.isolatedState.label")}),i.jsxs("div",{style:PT,children:[i.jsx("button",{type:"button","data-testid":"g7le-isolated-toggle",role:"switch","aria-checked":a,onClick:p,style:OT(a),children:n(a?"layout_editor.overlay.on":"layout_editor.overlay.off")}),a?null:i.jsx("span",{"data-testid":"g7le-isolated-off-hint",style:BT,children:n("layout_editor.core_props.isolatedState.off_hint")})]}),a?i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:ag,children:[i.jsx("label",{style:lg,children:n("layout_editor.core_props.isolatedScopeId.label")}),i.jsx("input",{type:"text","data-testid":"g7le-isolated-scopeid-input",value:l,placeholder:n("layout_editor.core_props.isolatedScopeId.placeholder"),onChange:h=>f(h.target.value),style:WT}),g.length>0?i.jsxs("div",{"data-testid":"g7le-isolated-scopeid-picker",style:jT,children:[i.jsx("input",{type:"text","data-testid":"g7le-isolated-scopeid-search",value:d,placeholder:n("layout_editor.core_props.isolatedScopeId.search"),onChange:h=>c(h.target.value),style:HT}),i.jsx("div",{style:FT,children:g.map(h=>i.jsx("button",{type:"button","data-testid":`g7le-isolated-scopeid-candidate-${h}`,onClick:()=>{f(h),c("")},style:KT,children:h},h))})]}):null,m?i.jsxs("p",{"data-testid":"g7le-isolated-scopeid-dup",style:VT,children:["ⓘ ",n("layout_editor.core_props.isolatedScopeId.duplicate")]}):null]}),i.jsxs("div",{style:ag,children:[i.jsx("label",{style:lg,children:n("layout_editor.core_props.isolatedState.initial_label")}),i.jsx("div",{"data-testid":"g7le-isolated-initial-value",children:i.jsx(zn,{value:s.isolatedState??{},onChange:b,t:n,path:"isolatedState",scope:"isolated-node"})})]})]}):null]})}const MT={display:"flex",flexDirection:"column",gap:8,padding:10,border:"1px solid #e2e8f0",borderRadius:8,minWidth:0},LT={fontSize:12,fontWeight:700,color:"#0f172a"},PT={display:"flex",gap:8,alignItems:"center"},OT=e=>({padding:"4px 12px",fontSize:11,border:`1px solid ${e?"#3b82f6":"#cbd5e1"}`,borderRadius:14,background:e?"#eff6ff":"#fff",color:e?"#1d4ed8":"#64748b",cursor:"pointer"}),BT={fontSize:11,color:"#94a3b8"},ag={display:"flex",flexDirection:"column",gap:4,minWidth:0},lg={fontSize:11,color:"#64748b"},WT={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box",width:"100%"},jT={border:"1px solid #e2e8f0",borderRadius:6,padding:4,background:"#fff"},HT={width:"100%",padding:"4px 6px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,marginBottom:4,boxSizing:"border-box"},FT={display:"flex",flexDirection:"column",maxHeight:120,overflowY:"auto"},KT={textAlign:"left",padding:"4px 6px",fontSize:12,border:"none",background:"transparent",cursor:"pointer",borderRadius:4,color:"#0f172a"},VT={margin:0,fontSize:11,color:"#64748b"},UT={borderTop:"2px solid #c7d2fe",background:"#eef2ff",padding:"10px 12px",display:"flex",flexDirection:"column",gap:8},dg={fontSize:13,fontWeight:700,color:"#3730a3",display:"flex",alignItems:"center",gap:6},qT={fontSize:11,fontWeight:600,color:"#4338ca",background:"#e0e7ff",border:"1px solid #c7d2fe",borderRadius:4,padding:"1px 6px"},Oa={fontSize:11,color:"#6366f1"},GT={alignSelf:"flex-start",fontSize:12,fontWeight:600,color:"#fff",background:"#4f46e5",border:"none",borderRadius:4,padding:"4px 10px",cursor:"pointer"},YT={opacity:.5,cursor:"not-allowed"},XT={fontSize:11,color:"#dc2626"};function JT({entry:e,t,onSave:n}){const[o,r]=u.useState(()=>e.props),[s,a]=u.useState(!0),[l,d]=u.useState(null),[c,p]=u.useState(!1),[f,b]=u.useState(!1),g=e.extensionName??e.extensionIdentifier??`#${e.extensionId}`,m=async()=>{if(!s){d(t("layout_editor.property_modal.injected_props.invalid_json"));return}d(null),p(!0),b(!1);try{await n(o),b(!0)}catch(h){d(h instanceof Error?h.message:String(h))}finally{p(!1)}};return i.jsxs("div",{"data-testid":`g7le-injected-props-entry-${e.extensionId}`,style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("div",{style:dg,children:i.jsx("span",{style:qT,"data-testid":"g7le-injected-props-origin-badge",children:t("layout_editor.property_modal.injected_props.origin",{source:g})})}),i.jsx(Hs,{value:o,shape:"object",emptyValue:{},testidPrefix:"g7le-injected-props-json",minHeight:80,invalidErrorKey:"layout_editor.property_modal.injected_props.invalid_json",shapeErrorKey:"layout_editor.property_modal.injected_props.invalid_json",t,onChange:h=>{r(h??{}),b(!1)},onValidityChange:h=>{a(h),h&&d(null),b(!1)}}),l&&i.jsx("div",{style:XT,"data-testid":"g7le-injected-props-error",children:l}),f&&i.jsx("div",{style:{...Oa,color:"#16a34a"},"data-testid":"g7le-injected-props-saved",children:t("layout_editor.property_modal.injected_props.saved")}),i.jsx("div",{style:Oa,children:t("layout_editor.property_modal.injected_props.save_target")}),i.jsx("button",{type:"button","data-testid":"g7le-injected-props-save",style:{...GT,...c||!s?YT:null},disabled:c||!s,onClick:m,children:c?t("layout_editor.property_modal.injected_props.saving"):t("layout_editor.property_modal.injected_props.save_button",{source:g})})]})}function ZT({injectedProps:e,t,onSaveInjectedProps:n}){return!Array.isArray(e)||e.length===0?null:i.jsxs("div",{style:UT,"data-testid":"g7le-injected-props-section",children:[i.jsxs("div",{style:dg,children:["🧩 ",t("layout_editor.property_modal.injected_props.title")]}),i.jsx("div",{style:Oa,children:t("layout_editor.property_modal.injected_props.help")}),e.map(o=>i.jsx(JT,{entry:o,t,onSave:r=>n(o.extensionId,r)},o.extensionId))]})}function QT(e,t){const n=e?.components??{};for(const o of Object.values(n)){const r=o?.find(s=>s.name===t);if(r)return r}return null}function RT({node:e,spec:t,manifest:n,t:o,onPatchNode:r,onClose:s,onDelete:a,permissionCandidates:l,pageCandidates:d,dataSourceCandidates:c,stateKeyCandidates:p,bindingCandidates:f,liveElement:b,scope:g=Wt,onScopeChange:m,templateIdentifier:h,initialTab:v,onSaveInjectedProps:y,branchLabel:_,isolatedScopeIdCandidates:w,usedScopeIds:k}){const x=e.__injectedProps,$=Array.isArray(x)&&x.length>0&&!!y,S=ve=>{m?.(ve)},C=()=>{r(IC(e,g))},T=typeof e.name=="string"?e.name:"",E=ji(t,T),N=QT(n,T)?.settings,D=!!(N?.groups&&N.groups.length>0),B=Array.isArray(E?.propControls)?E.propControls:[],M=zT(E?.coreProps),O=new Set(M.map(ve=>Pa[ve].apply?.propKey)),z=B.filter(ve=>{const We=Ct(t,ve)?.apply?.propKey;return!(We!==void 0&&O.has(We))}),H=typeof E?.nodeEditor?.kind=="string"?E.nodeEditor.kind:void 0,P=E?.nodeEditor?.params,I=H?TT(H):null,L=!!I,F=Array.isArray(E?.dataProps)?E.dataProps:[],Y=F.length>0,K=!!(e.iteration&&typeof e.iteration=="object"),X=oT(e,E),Z=M.length>0||z.length>0||L||Y||X||K,se=Array.isArray(E?.styleControls)?E.styleControls:[],oe=Array.isArray(E?.advanced)?E.advanced:[],ee=(Array.isArray(E?.events)?E.events:[]).length>0,ge=Jf(E),V=se.length>0||ge!==null,be=!(E?.visibilityCondition===!1)&&(Z||V||ee||D||oe.length>0),Ee=u.useMemo(()=>{const ve=[];return D&&ve.push("settings"),Z&&ve.push("props"),V&&ve.push("style"),ee&&ve.push("action"),be&&ve.push("visibility"),ve.push("translation"),oe.length>0&&ve.push("advanced"),ve},[D,Z,V,ee,be,oe.length]),De=z.length>0||L||Y||K,[Se,Ue]=u.useState(v&&Ee.includes(v)?v:D?"settings":De?"props":V?"style":Z?"props":Ee[0]??"style"),Me=qA(e),Oe=!Z&&!V&&!D&&!ee&&!be&&oe.length===0,Ye=E?.label?E.label.startsWith("$t:")?o(E.label.slice(3)):E.label:T||o("layout_editor.property_modal.element"),ze=(ve,qe)=>{const We={...e.props??{}};qe===void 0?delete We[ve]:We[ve]=qe,r({...e,props:We})},Xe={settings:o("layout_editor.property_modal.tab.settings"),props:o("layout_editor.property_modal.tab.props"),style:o("layout_editor.property_modal.tab.style"),action:o("layout_editor.property_modal.tab.action"),visibility:o("layout_editor.property_modal.tab.visibility"),translation:o("layout_editor.property_modal.tab.translation"),advanced:o("layout_editor.property_modal.tab.advanced")};return i.jsxs("div",{className:"g7le-property-modal","data-testid":"g7le-property-modal",style:e4,children:[i.jsxs("div",{"data-modal-drag-handle":!0,"data-testid":"g7le-property-modal-header",style:t4,children:[i.jsx("span",{"data-testid":"g7le-property-modal-title",style:{fontSize:14,fontWeight:700},children:D&&Se==="settings"?o("layout_editor.property_modal.settings_title",{name:Ye}):o("layout_editor.property_modal.title",{name:Ye})}),i.jsx("button",{type:"button","data-testid":"g7le-property-modal-close","aria-label":"close",onClick:s,style:n4,children:"✕"})]}),Me&&i.jsx("div",{"data-testid":"g7le-property-modal-advanced-badge",style:o4,children:o("layout_editor.property_modal.advanced_badge")}),_&&i.jsx("div",{"data-testid":"g7le-property-modal-branch-badge",style:r4,children:o("layout_editor.property_modal.branch_badge",{device:_})}),i.jsx("div",{style:i4,role:"tablist",children:Ee.map(ve=>i.jsx("button",{type:"button",role:"tab","aria-selected":Se===ve,"data-testid":`g7le-property-tab-${ve}`,"data-active":Se===ve?"true":"false",onClick:()=>Ue(ve),style:{...s4,color:Se===ve?"#2563eb":"#64748b",borderBottomColor:Se===ve?"#2563eb":"transparent"},children:Xe[ve]},ve))}),i.jsxs("div",{style:a4,"data-testid":"g7le-property-modal-body",children:[Oe&&!$&&i.jsx("div",{"data-testid":"g7le-property-modal-no-editable",style:ug,children:o("layout_editor.property_modal.no_editable_props")}),$&&i.jsx(ZT,{injectedProps:x,t:o,onSaveInjectedProps:y}),Se==="settings"&&N&&i.jsx(MA,{spec:N,node:e,t:o,onPatchProp:ze}),Se==="props"&&i.jsxs("div",{"data-testid":"g7le-property-props-tab",style:{display:"flex",flexDirection:"column"},children:[K&&i.jsx(L6,{node:e,candidates:f??[],t:o,onPatchNode:r}),Y&&i.jsx(d6,{node:e,dataProps:F,candidates:f??[],t:o,onPatchNode:r}),X&&i.jsx(T6,{node:e,candidates:f??[],t:o,onPatchNode:r,templateIdentifier:h}),L&&I&&i.jsx(I,{node:e,params:P,spec:t,manifest:n,t:o,onPatchNode:r,templateIdentifier:h,candidates:f}),M.map(ve=>i.jsx(hi,{controlKey:`core-${ve}`,control:Pa[ve],node:e,t:o,onPatch:r,scope:Wt,bindingCandidates:f},`core-${ve}`)),z.map(ve=>{const qe=Ct(t,ve);return qe?i.jsx(hi,{controlKey:ve,control:qe,node:e,t:o,onPatch:r,scope:Wt,bindingCandidates:f},ve):null}),i.jsx(NT,{node:e,onPatchNode:r,t:o,scopeIdCandidates:w,usedScopeIds:k})]}),Se==="style"&&i.jsxs("div",{"data-testid":"g7le-property-style-tab",style:{display:"flex",flexDirection:"column"},children:[i.jsx("div",{style:cg,children:i.jsx(eg,{scope:g,onChange:S,node:e,t:o,onClearScope:C})}),ge!==null&&i.jsx(dT,{node:e,spec:t,capability:E,t:o,onPatchNode:r,liveElement:b,scope:g}),se.map(ve=>{const qe=Ct(t,ve);return qe?i.jsx(hi,{controlKey:ve,control:qe,node:e,t:o,onPatch:r,scope:g},ve):null})]}),Se==="action"&&i.jsx(i6,{node:e,spec:t,capability:E,t:o,onPatchNode:r,pageCandidates:d,dataSourceCandidates:c,stateKeyCandidates:p,bindingCandidates:f}),Se==="visibility"&&i.jsxs("div",{"data-testid":"g7le-property-visibility-tab",style:{display:"flex",flexDirection:"column"},children:[i.jsx("div",{style:cg,children:i.jsx(eg,{scope:g,onChange:S,node:e,t:o,showColorScheme:!1})}),i.jsx(Du,{node:e,spec:t,t:o,onPatchNode:r,dataSourceCandidates:c,stateKeyCandidates:p,scope:g})]}),Se==="translation"&&(h?i.jsx(Xd,{customKey:Yd(e),templateIdentifier:h,t:o,paramLabels:wv(e),onRemoveParam:ve=>{const qe=typeof e.text=="string"?e.text:"";r({...e,text:vo(qe,ve)});const We=Yd(e);h&&We&&$r(h,We,ve)}}):i.jsx("div",{"data-testid":"g7le-property-translation-deferred",style:ug,children:o("layout_editor.translation.not_a_key")})),Se==="advanced"&&i.jsx(YA,{node:e,advanced:oe,t:o,onPatch:r,permissionCandidates:l})]}),i.jsxs("div",{style:l4,children:[i.jsx("span",{"data-testid":"g7le-property-modal-node-id",style:{fontSize:11,color:"#94a3b8"},children:typeof e.id=="string"||typeof e.id=="number"?`ID: ${e.id}`:""}),i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsx("button",{type:"button","data-testid":"g7le-property-modal-delete",onClick:a,style:d4,children:o("layout_editor.property_modal.delete_element")}),i.jsx("button",{type:"button","data-testid":"g7le-property-modal-done",onClick:s,style:c4,children:o("layout_editor.property_modal.close")})]})]})]})}const e4={display:"flex",flexDirection:"column",width:420,maxWidth:"92vw"},t4={display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #e2e8f0",cursor:"move",userSelect:"none"},n4={border:"none",background:"transparent",fontSize:14,cursor:"pointer",color:"#64748b"},o4={margin:"8px 16px 0",padding:"6px 10px",fontSize:11,background:"#fef3c7",color:"#92400e",borderRadius:6},r4={margin:"8px 16px 0",padding:"6px 10px",fontSize:11,background:"#dbeafe",color:"#1e40af",borderRadius:6},i4={display:"flex",gap:2,padding:"0 12px",borderBottom:"1px solid #e2e8f0",overflowX:"auto"},s4={padding:"8px 10px",fontSize:12,border:"none",borderBottom:"2px solid transparent",background:"transparent",cursor:"pointer",whiteSpace:"nowrap"},a4={padding:16,overflowY:"auto",maxHeight:"60vh"},cg={position:"sticky",top:-16,zIndex:2,background:"#fff",margin:"-16px -16px 0",padding:"6px 16px 0"},ug={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},l4={display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderTop:"1px solid #e2e8f0"},d4={padding:"6px 12px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},c4={padding:"6px 12px",fontSize:12,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"},Ba="g7le:component-target-picked",Wa="g7le:component-target-pick-request";let u4=1;function p4({value:e,onChange:t,t:n,control:o}){const r=bo(),s=e==null?"":String(e),a=o?.allowManualInput!==!1,l=u.useCallback(()=>{if(typeof window>"u")return;const d=`pick-${u4++}`,p=r.stack[r.stack.length-1]?.id;p&&r.minimize(p,n("layout_editor.target_picker.minimized_hint"));const f=b=>{const g=b.detail;g?.requestId===d&&(window.removeEventListener(Ba,f),p&&r.restore(p),!g.cancelled&&typeof g.id=="string"&&t(g.id))};window.addEventListener(Ba,f),window.dispatchEvent(new CustomEvent(Wa,{detail:{requestId:d}}))},[r,t,n]);return i.jsx("div",{className:"g7le-component-target-picker","data-testid":"g7le-component-target-picker",children:i.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[a?i.jsx("input",{type:"text",className:"g7le-widget g7le-widget--text","data-testid":"g7le-component-target-input",value:s,placeholder:n("layout_editor.target_picker.id_placeholder"),onChange:d=>t(d.target.value===""?void 0:d.target.value),style:{flex:1,minWidth:0,padding:"6px 8px",border:"1px solid #cbd5e1",borderRadius:6,fontSize:13}}):i.jsx("span",{"data-testid":"g7le-component-target-value",style:{flex:1,minWidth:0},children:s||n("layout_editor.target_picker.none")}),i.jsxs("button",{type:"button","data-testid":"g7le-component-target-pick",onClick:l,style:{display:"flex",alignItems:"center",gap:4,padding:"6px 10px",background:"#1e293b",color:"#fff",border:"none",borderRadius:6,cursor:"pointer",fontSize:13,whiteSpace:"nowrap"},children:[i.jsx("span",{"aria-hidden":"true",children:"🎯"}),n("layout_editor.target_picker.select_area")]})]})})}async function f4(e,t,n,o,r=fetch){const s=`/api/admin/templates/${encodeURIComponent(e)}/layout-extensions/${t}`;let a;try{a=await r(s,{headers:Ne(),credentials:"same-origin"})}catch(y){return{kind:"error",message:y instanceof Error?y.message:String(y)}}if(a.status===404)return{kind:"not_found"};if(!a.ok)return{kind:"error",message:`HTTP ${a.status}`};const l=await a.json().catch(()=>null),d=(l&&(l.data||l))??{};let c={};const p=d.content;if(typeof p=="string")try{c=JSON.parse(p)}catch{return{kind:"error",message:"invalid extension content"}}else p&&typeof p=="object"&&(c=p);const f=typeof d.lock_version=="number"?d.lock_version:0,b=Array.isArray(c.injections)?[...c.injections]:[],g=b.findIndex(y=>y&&y.position==="inject_props"&&y.target_id===n);if(g<0)return{kind:"injection_not_found"};b[g]={...b[g],props:o};const m={...c,injections:b};let h;try{h=await r(s,{method:"PUT",headers:Ne({"Content-Type":"application/json"}),credentials:"same-origin",body:JSON.stringify({content:m,expected_lock_version:f})})}catch(y){return{kind:"error",message:y instanceof Error?y.message:String(y)}}const v=await h.json().catch(()=>null);return h.ok?{kind:"success",newLockVersion:typeof v?.data?.lock_version=="number"?v.data.lock_version:f+1}:h.status===409?{kind:"conflict",currentVersion:v?.current_version??-1,yourVersion:v?.your_version??f}:{kind:"error",message:v?.message??`HTTP ${h.status}`}}const pg=new Map;function ja(e,t){pg.set(e,t)}function g4(e){return e?pg.get(e)??null:null}const fg="g7le.clipboard";function gg(){try{return typeof window>"u"||!window.sessionStorage?null:window.sessionStorage}catch{return null}}function h4(e){const t=JSON.parse(JSON.stringify(e)),n=o=>{for(const r of Object.keys(o))r.startsWith("__")&&delete o[r];Array.isArray(o.children)&&o.children.forEach(n)};return n(t),t}function hg(e,t=0){const n=gg();if(!n)return!1;try{const o={node:h4(e),copiedAt:t};return n.setItem(fg,JSON.stringify(o)),!0}catch{return!1}}function y4(){const e=gg();if(!e)return null;try{const t=e.getItem(fg);if(!t)return null;const n=JSON.parse(t);return!n||typeof n.node!="object"||n.node===null?null:JSON.parse(JSON.stringify(n.node))}catch{return null}}const Qo={nw:{width:-1,height:-1},n:{width:0,height:-1},ne:{width:1,height:-1},e:{width:1,height:0},se:{width:1,height:1},s:{width:0,height:1},sw:{width:-1,height:1},w:{width:-1,height:0}};function Ha(e){if(typeof e=="number")return e;if(typeof e=="string"){const t=e.match(/^(-?\d+(?:\.\d+)?)px$/);if(t)return Number(t[1])}return null}function b4(e,t){const n=Array.isArray(e.options)?e.options:[],o=Array.isArray(e.scale)?e.scale:[],r=n.length>0?n.map(l=>l.value):o;if(r.length===0)return;let s=r[0],a=1/0;return r.forEach((l,d)=>{const c=Ha(l)??d*40,p=Math.abs(c-t);p{if(!t)return;const m=Qo[b];if(m.width!==0&&!n||m.height!==0&&!o)return;const h=t.props?.style??{},v=s?.()??null,y=Ha(h.width)??(v?Math.round(v.width):0),_=Ha(h.height)??(v?Math.round(v.height):0);p.current={handle:b,startX:g.clientX,startY:g.clientY,startW:y,startH:_,node:t};const w=m.width!==0&&m.height!==0?"both":m.width!==0?"width":"height";d?.(w);let k=null;const x=S=>{const C=p.current;if(!C)return;const T=r||1,E=(S.clientX-C.startX)/T*Qo[C.handle].width,A=(S.clientY-C.startY)/T*Qo[C.handle].height;let N=C.node;if(Qo[C.handle].width!==0&&n){const D=yg(n,C.startW+E);N=fn(N,n,D)}if(Qo[C.handle].height!==0&&o){const D=yg(o,C.startH+A);N=fn(N,o,D)}k=N,a(N,w)},$=()=>{p.current=null,d?.(null),window.removeEventListener("pointermove",x),window.removeEventListener("pointerup",$),k&&l?.(k,w)};window.addEventListener("pointermove",x),window.addEventListener("pointerup",$)},[t,n,o,r,a,l,d]);return{enabledAxes:c,onHandlePointerDown:f}}const bg=320,mg=1920,_4=1024;function Fa(e){return Number.isFinite(e)?Math.round(Math.max(bg,Math.min(mg,e))):_4}function Ka(e={}){const{state:t,dispatch:n}=Qe(),{previewDevice:o,previewZoom:r,previewCustomWidth:s,previewColorScheme:a}=t,l=o==="custom"?Fa(s):_T(o),d=u.useMemo(()=>{const g=e.availableWidth??l,m=l*r;return r>=1||m<=g?r:Math.min(r,g/l)},[l,r,e.availableWidth]),c=u.useCallback(g=>{n({type:"SET_PREVIEW_DEVICE",device:g})},[n]),p=u.useCallback(g=>{const m=Math.max(.5,Math.min(1,g));n({type:"SET_PREVIEW_ZOOM",zoom:m})},[n]),f=u.useCallback(g=>{n({type:"SET_PREVIEW_CUSTOM_WIDTH",width:Fa(g)})},[n]),b=u.useCallback(g=>{n({type:"SET_PREVIEW_COLOR_SCHEME",scheme:g})},[n]);return{device:o,deviceWidth:l,zoom:r,scale:d,customWidth:Fa(s),setDevice:c,setZoom:p,setCustomWidth:f,colorScheme:a,setColorScheme:b}}const vi="g7le-dnd-handle-";function x4(e){if(typeof e!="string"||!e.startsWith(vi))return null;const t=e.slice(vi.length);return t.length>0?t:null}function w4(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\\]]/g,"\\$&")}function k4(e,t,n,o){const r=o?.handleFallback??!1;if(e instanceof HTMLElement){const s=e.closest("[data-editor-path]");if(s)return s;const a=e.closest('[data-testid^="g7le-"]');if(a&&!(a.getAttribute("data-testid")??"").startsWith(vi))return null;if(r){const l=e.closest(`[data-testid^="${vi}"]`);if(l&&t){const d=x4(l.getAttribute("data-testid"));if(d){const c=t.querySelector(`[data-editor-path="${w4(d)}"]`);if(c)return c}}}}if(r&&n&&typeof document<"u"&&typeof document.elementsFromPoint=="function")for(const s of document.elementsFromPoint(n.x,n.y)){const a=s.closest?.("[data-editor-path]");if(a)return a}return null}function S4(e,t,n){if(typeof e=="string"&&e.trim().length>0)return{color:e};const o=typeof n?.color=="string"&&n.color.length>0,r=typeof t=="string"&&t.trim().length>0;return o||r?{}:{color:"#0f172a"}}const C4="#ffffff",$4="#0f172a";function E4(e){const t=e.trim(),n=t.match(/^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i);if(n)return[Number(n[1]),Number(n[2]),Number(n[3])];const o=t.replace(/^#/,"");return/^[0-9a-f]{3}$/i.test(o)?[parseInt(o[0]+o[0],16),parseInt(o[1]+o[1],16),parseInt(o[2]+o[2],16)]:/^[0-9a-f]{6}$/i.test(o)?[parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4,6),16)]:null}function I4(e){if(!e||/transparent/i.test(e))return!1;const t=e.trim().match(/^oklch\(\s*([\d.]+)(%?)/i);if(t)return(t[2]==="%"?Number(t[1])/100:Number(t[1]))>=.62;const n=E4(e);if(!n)return!1;const[o,r,s]=n;return .299*o+.587*r+.114*s>=180}function A4(e,t,n){const o=typeof n?.color=="string"?n.color:null;return I4(e??o??t)?$4:C4}function T4({box:e,initialValue:t,isCustomKey:n,t:o,onCommit:r,onCancel:s,mirrorClassName:a,mirrorStyle:l,nodeEffectiveColor:d,onOpenTranslations:c}){const p=u.useRef(null),f=u.useRef(!1),[b,g]=u.useState(t.trim().length>0),[m,h]=u.useState(null);u.useEffect(()=>{const k=p.current;if(k){k.textContent=t,k.focus();try{const x=window.document.createRange();x.selectNodeContents(k);const $=window.getSelection();$?.removeAllRanges(),$?.addRange(x)}catch{}f.current=!1}},[t]),u.useEffect(()=>{const k=p.current;if(!k||typeof window.getComputedStyle!="function"){h(null);return}try{h(window.getComputedStyle(k).color||null)}catch{h(null)}},[a,l]);const v=()=>(p.current?.textContent??"").trim(),y=()=>{f.current||(f.current=!0,r(v()))},_=()=>{f.current||(f.current=!0,s())},w=k=>{k.key==="Enter"&&!k.shiftKey?(k.preventDefault(),y()):k.key==="Escape"&&(k.preventDefault(),_())};return i.jsxs("div",{className:"g7le-inline-text-editor","data-testid":"g7le-inline-text-editor","data-custom-key":n?"true":"false",style:{position:"absolute",left:e.left,top:e.top,minWidth:Math.max(e.width,60),minHeight:e.height,pointerEvents:"auto",zIndex:1e4},children:[i.jsx("div",{ref:p,role:"textbox","aria-label":o("layout_editor.inline_edit.aria_label"),"aria-multiline":"false","data-testid":"g7le-inline-text-editable",className:a,contentEditable:!0,suppressContentEditableWarning:!0,spellCheck:!1,onInput:()=>g(v().length>0),onKeyDown:w,onBlur:y,style:{outline:"2px solid #2563eb",outlineOffset:1,borderRadius:3,background:A4(d,m,l),padding:"2px 4px",minHeight:e.height,whiteSpace:"pre-wrap",wordBreak:"break-word",boxShadow:"0 2px 8px rgba(37, 99, 235, 0.25)",...l??{},...S4(d,a,l)}}),i.jsxs("div",{className:"g7le-inline-text-editor__hint","data-testid":"g7le-inline-text-editor-hint",style:{marginTop:2,display:"inline-flex",alignItems:"center",gap:4,whiteSpace:"nowrap"},children:[c?i.jsxs("button",{type:"button","data-testid":"g7le-inline-text-editor-open-translations",onMouseDown:k=>k.preventDefault(),onClick:k=>{k.preventDefault(),k.stopPropagation(),c()},title:o("layout_editor.inline_edit.open_translations"),style:{padding:"2px 8px",fontSize:11,background:n?"#eff6ff":"#f0fdf4",color:n?"#1d4ed8":"#15803d",border:`1px solid ${n?"#bfdbfe":"#bbf7d0"}`,borderRadius:4,display:"inline-flex",alignItems:"center",gap:4,cursor:"pointer",whiteSpace:"nowrap"},children:[i.jsx("span",{"aria-hidden":"true",children:"🌐"}),i.jsx("span",{children:o(n?"layout_editor.inline_edit.existing_key_hint":"layout_editor.inline_edit.new_key_hint")}),i.jsxs("span",{"aria-hidden":"true",style:{opacity:.7},children:["· ",o("layout_editor.inline_edit.open_translations")," ›"]})]}):i.jsx("span",{style:{padding:"2px 6px",fontSize:11,background:n?"#eff6ff":"#f0fdf4",color:n?"#1d4ed8":"#15803d",border:`1px solid ${n?"#bfdbfe":"#bbf7d0"}`,borderRadius:4,display:"inline-flex",alignItems:"center",gap:4,whiteSpace:"nowrap"},children:n?i.jsxs(i.Fragment,{children:["⌐ ",o("layout_editor.inline_edit.existing_key_hint")]}):i.jsxs(i.Fragment,{children:["✎ ",o("layout_editor.inline_edit.new_key_hint")]})}),!b&&i.jsx("span",{"data-testid":"g7le-inline-text-editor-empty-warn",style:{color:"#b91c1c",marginLeft:4},children:o("layout_editor.inline_edit.empty_warning")})]})]})}function D4({box:e,node:t,customKey:n,initialChipValue:o,chipParamLabels:r,onKeyify:s,templateIdentifier:a,locale:l,t:d,candidates:c,onInsertBinding:p,onRemoveBinding:f,onCommit:b,onCancel:g}){const[m,h]=u.useState(null),v=u.useRef(""),[y,_]=u.useState(!1),w=u.useRef(!1),k=u.useRef(null),x=Ft(),$=u.useRef(()=>{}),[S,C]=u.useState(null),[T,E]=u.useState(!1),A=u.useRef(n??null);u.useEffect(()=>{n&&A.current!==n&&(A.current=n)},[n]);const N=u.useMemo(()=>{if(!n&&r)return r;const P={},I=vt(typeof t.text=="string"?t.text:"");for(const L of I?.params??[])P[L.name]=Vt(L.expression);return P},[t.text,n,r]);u.useEffect(()=>{let P=!1;if(!n){const I=o??"";return v.current=I,h(I),()=>{P=!0}}return(async()=>{const I=It(n,l);if(I!==void 0){v.current=I,h(I);return}const L=await cn(a,n);if(P)return;const F=L?.values?.[l]??"";v.current=F,h(F)})(),()=>{P=!0}},[a,n,l,o]);const D=async()=>{if(w.current)return;w.current=!0;const P=m??"";if(P===v.current){b();return}_(!0);let I=A.current;if(!I){if(!s){_(!1),w.current=!1;return}if(I=await s(P),_(!1),!I){w.current=!1;return}A.current=I,b();return}const L=await So(a,I,l,P);if(_(!1),L.kind==="error"){w.current=!1;return}x?.markDirty?.(),b()},B=()=>{w.current||(w.current=!0,g())},M=P=>{C(P)},O=async P=>{if(!(S===null||!p||T)){E(!0);try{const I=A.current;I&&m!==null&&m!==v.current&&(await So(a,I,l,m),v.current=m);const L=await p(S,P);L!==null&&(h(L),v.current=L,x?.markDirty?.())}finally{E(!1),C(null)}}},z=async P=>{if(!(!f||T)){E(!0);try{const I=A.current;I&&m!==null&&m!==v.current&&(await So(a,I,l,m),v.current=m);const L=await f(P);L!==null&&(h(L),v.current=L,x?.markDirty?.())}finally{E(!1)}}},H=P=>{P.key==="Enter"&&!P.shiftKey?(P.preventDefault(),D()):P.key==="Escape"&&(P.preventDefault(),B())};return $.current=()=>{D()},u.useEffect(()=>{const P=L=>{const F=k.current;if(!F)return;const Y=L.target;if(Y&&F.contains(Y))return;const K=Y;K&&K.closest&&K.closest('[data-testid="g7le-inline-toolbar"], .g7le-inline-toolbar')||$.current()},I=k.current?.ownerDocument??document;return I.addEventListener("pointerdown",P,!0),()=>I.removeEventListener("pointerdown",P,!0)},[]),i.jsxs("div",{ref:k,className:"g7le-inline-param-chip-editor","data-testid":"g7le-inline-param-chip-editor",onKeyDown:H,style:{position:"absolute",left:e.left,top:e.top,minWidth:Math.max(e.width,120),pointerEvents:"auto",zIndex:1e4,background:"#fff",border:"2px solid #2563eb",borderRadius:4,boxShadow:"0 2px 8px rgba(37,99,235,0.25)",padding:4},children:[m===null?i.jsx("div",{"data-testid":"g7le-inline-param-chip-loading",style:{fontSize:12,color:"#94a3b8",padding:4},children:d("layout_editor.translation.loading")}):i.jsx(xr,{value:m,onChange:h,t:d,paramLabels:N,testIdSuffix:"inline",onRequestInsert:p?M:void 0,onRemoveChip:f?P=>{z(P)}:void 0}),S!==null&&p&&i.jsx("div",{"data-testid":"g7le-inline-param-chip-insert-picker",style:{marginTop:4},children:i.jsx($t,{candidates:c??[],t:d,onSelect:P=>{O(P)},testIdSuffix:"inline-insert",defaultOpen:!0,floating:!1})}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:4},children:[i.jsx("button",{type:"button","data-testid":"g7le-inline-param-chip-save",disabled:y,onMouseDown:P=>P.preventDefault(),onClick:()=>{D()},style:{fontSize:11,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",padding:"4px 12px",cursor:"pointer"},children:d(y?"layout_editor.translation.saving":"layout_editor.translation.save")}),i.jsx("span",{style:{fontSize:10,color:"#94a3b8"},children:d("layout_editor.translation.placeholder_locked")})]})]})}const z4=["fontWeight","fontBold","fontStyle","fontItalic","textDecoration","textUnderline","textAlign","fontSize","textColor"],N4={fontWeight:"B",fontBold:"B",fontStyle:"I",fontItalic:"I",textDecoration:"U",textUnderline:"U",textAlign:"≡",fontSize:"T",textColor:"A"},M4=[["fontWeight","fontBold"],["fontItalic","fontStyle"],["textUnderline","textDecoration"]];function vg({node:e,spec:t,t:n,onApplyControl:o,box:r,scope:s=Wt}){const a=typeof e.name=="string"?e.name:"",l=ji(t,a),d=Array.isArray(l?.styleControls)?l.styleControls:[];let c=z4.filter(p=>d.includes(p)&&Ct(t,p)!==null);for(const p of M4){const f=p.filter(b=>c.includes(b));if(f.length>1){const b=f[0];c=c.filter(g=>!p.includes(g)||g===b)}}return c.length===0?null:i.jsx("div",{className:"g7le-inline-toolbar","data-testid":"g7le-inline-toolbar",role:"toolbar","aria-label":n("layout_editor.inline_edit.toolbar_label"),style:{position:"absolute",left:r.left,top:r.top-40,display:"inline-flex",gap:2,padding:4,background:"#0f172a",borderRadius:8,boxShadow:"0 4px 12px rgba(15, 23, 42, 0.35)",pointerEvents:"auto",zIndex:10001},children:c.map(p=>i.jsx(P4,{controlKey:p,node:e,spec:t,t:n,scope:s,onApplyControl:o},p))})}const L4={fontWeight:"bold",fontBold:"bold",fontStyle:"italic",fontItalic:"italic",textDecoration:"underline",textUnderline:"underline"};function _g(e,t){const n=r=>(r.split(/[-\s]/).pop()??r)===t||r===t;return e.find(r=>{const s=typeof r.value=="string"?r.value:"",a=Array.isArray(r.apply?.tokens)?r.apply.tokens:[];return n(s)||a.some(n)})?.value}function P4({controlKey:e,node:t,spec:n,t:o,scope:r,onApplyControl:s}){const[a,l]=u.useState(!1),d=Ct(n,e);if(!d)return null;const c=d.options,p=Array.isArray(c),f=zo(t,d,r),b=L4[e],g=b&&Array.isArray(c)?_g(c,b):void 0,m=!b,h=g!==void 0?f.value===g:p&&f.matched&&f.value!==void 0&&f.value!=="",v=o(`layout_editor.inline_edit.format.${e}`),y=x=>typeof x.label=="string"?x.label.startsWith("$t:")?o(x.label.slice(3)):x.label:String(x.value??""),_=()=>{s(e,x=>{const $=zo(x,d,r),S=Array.isArray(c)?_g(c,b):void 0,C=S!==void 0&&$.value===S?void 0:S;return fn(x,d,C,r)})},w=x=>{s(e,$=>{const C=zo($,d,r).value===x?void 0:x;return fn($,d,C,r)}),l(!1)},k=x=>{if(x.preventDefault(),x.stopPropagation(),!m&&Array.isArray(c)){_();return}l($=>!$)};return i.jsxs("div",{style:{position:"relative",display:"inline-flex"},children:[i.jsxs("button",{type:"button","data-testid":`g7le-inline-format-${e}`,"data-active":h?"true":"false","aria-label":v,"aria-pressed":p?h:void 0,title:v,onMouseDown:x=>x.preventDefault(),onClick:k,style:{display:"inline-flex",alignItems:"center",gap:5,height:28,padding:"0 9px",fontSize:12,border:"none",borderRadius:5,cursor:"pointer",background:h?"#2563eb":"transparent",color:"#ffffff",whiteSpace:"nowrap"},children:[i.jsx("span",{"aria-hidden":"true",style:{fontWeight:e==="fontWeight"||e==="fontBold"?700:600,fontStyle:e==="fontStyle"||e==="fontItalic"?"italic":"normal",textDecoration:e==="textDecoration"||e==="textUnderline"?"underline":"none"},children:N4[e]}),i.jsx("span",{children:v}),m&&i.jsx("span",{"aria-hidden":"true",style:{fontSize:9,opacity:.8},children:"▾"})]}),m&&a&&i.jsx("div",{"data-testid":`g7le-inline-popover-${e}`,role:"listbox",onMouseDown:x=>x.preventDefault(),style:{position:"absolute",top:32,left:0,minWidth:140,maxHeight:240,overflowY:"auto",background:"#0f172a",border:"1px solid #334155",borderRadius:8,boxShadow:"0 8px 24px rgba(15,23,42,0.45)",padding:4,zIndex:10002},children:Array.isArray(c)&&c.length>0?c.map((x,$)=>{const S=f.value===x.value;return i.jsxs("button",{type:"button",role:"option","aria-selected":S,"data-testid":`g7le-inline-option-${e}-${String(x.value??$)}`,onMouseDown:C=>C.preventDefault(),onClick:C=>{C.preventDefault(),C.stopPropagation(),w(x.value)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",fontSize:12,textAlign:"left",border:"none",borderRadius:5,cursor:"pointer",background:S?"#2563eb":"transparent",color:"#ffffff"},children:[typeof x.swatch=="string"&&i.jsx("span",{"aria-hidden":"true",style:{width:14,height:14,borderRadius:3,background:x.swatch,border:"1px solid rgba(255,255,255,0.3)"}}),i.jsx("span",{children:y(x)}),S&&i.jsx("span",{"aria-hidden":"true",style:{marginLeft:"auto"},children:"✓"})]},String(x.value??$))}):i.jsx(O4,{testid:`g7le-inline-freeinput-${e}`,placeholder:o(`layout_editor.inline_edit.prompt.${e}`),initial:typeof f.value=="string"?f.value:"",onSubmit:x=>{s(e,$=>fn($,d,x,r)),l(!1)}})})]})}function O4({testid:e,placeholder:t,initial:n,onSubmit:o}){const[r,s]=u.useState(n);return i.jsx("input",{type:"text","data-testid":e,value:r,placeholder:t,autoFocus:!0,onMouseDown:a=>a.stopPropagation(),onChange:a=>s(a.currentTarget.value),onKeyDown:a=>{a.key==="Enter"&&(a.preventDefault(),o(r.trim()))},style:{width:130,padding:"6px 8px",fontSize:12,border:"1px solid #334155",borderRadius:5,background:"#1e293b",color:"#ffffff"}})}function B4(e){const{frameEl:t,manifest:n,nesting:o,componentPalette:r,spec:s=null,permissionCandidates:a,resolveRouteMatch:l,onNavigateToDestination:d,onSessionAddedPathsChange:c,onEditProps:p}=e,{state:f,dispatch:b}=Qe(),{t:g}=tt(),m=Ka(),h=u.useCallback((W,J)=>{const R=window.G7Core;if(R&&typeof R.t=="function"){const le=R.t(W,J);if(le&&le!==W&&!le.startsWith("$t:"))return le}return g(W,J)},[g]),v=Ft(),y=L7(50),_=bo(),w=u.useRef([]),k=u.useMemo(()=>v?.document?.raw?.components??[],[v?.document?.raw?.components]),x=u.useMemo(()=>k.length===0?null:{children:k},[k]),$=u.useMemo(()=>{if(f.editMode!=="extension")return;const W=/^__extension__\/(\d+)/.exec(f.selectedRoute?.path??"");return W?Number(W[1]):void 0},[f.editMode,f.selectedRoute?.path]),S=u.useMemo(()=>{if(f.editMode==="iteration_item"){const W=v?.document?.iterationContext?.sourceIndexPath;return Array.isArray(W)&&W.length>0?W:null}if(f.editMode==="modal"){const W=v?.document?.modalContext?.editIndexPath;return Array.isArray(W)&&W.length>0?W:null}return null},[f.editMode,v?.document?.iterationContext?.sourceIndexPath,v?.document?.modalContext?.editIndexPath]),C=$7({rootNode:x,editMode:f.editMode,currentExtensionId:$,editableRootPath:S,pathParser:Re,resolveRouteMatch:l}),[T,E]=u.useState(null),[A,N]=u.useState(null),[D,B]=u.useState(null),M=u.useRef(null);M.current=D;const[O,z]=u.useState(null),H=u.useRef(null),P=u.useRef(null);P.current=C.selectedPath;const I=qb(),[L,F]=u.useState(null),Y=u.useCallback(W=>{if(!t)return;const J=Re(W);if(!J)return;const R={children:ze.current.components},le=Be(R,J),ye=I.classify(le);if(!ye.editable){Et({op:"inline_edit_blocked_binding",sourceState:ye.sourceState,componentPath:at(J),timestamp:Date.now()});return}const we=fo(t,W);if(!we)return;const Te=le?.props??{},ke=wg(t,W);F({path:J,domPath:W,box:we,initialValue:ye.displayValue,isCustomKey:ye.sourceState==="custom_key",isParamKey:ye.isParamKey===!0,customKey:ye.customKey,chipValue:ye.chipValue,chipParamLabels:ye.chipParamLabels,mirrorClassName:typeof Te.className=="string"?Te.className:void 0,mirrorStyle:Te.style??void 0,nodeEffectiveColor:ke}),Et({op:"inline_edit_enter",sourceState:ye.sourceState,componentPath:at(J),timestamp:Date.now()})},[t,I]),K=u.useCallback(()=>{if(!t){E(null),N(null);return}N(fo(t,C.selectedPath)),E(fo(t,C.hoverPath))},[t,C.selectedPath,C.hoverPath,k]);u.useEffect(()=>{if(K(),typeof window<"u"&&typeof window.requestAnimationFrame=="function"){const W=window.requestAnimationFrame(()=>K());return()=>window.cancelAnimationFrame(W)}},[K]),u.useEffect(()=>{if(t)return zp(K,t)},[t,K]);const X=u.useCallback((W,J)=>{if(typeof window>"u")return;window.dispatchEvent(new CustomEvent(Ba,{detail:J===null?{requestId:W,cancelled:!0}:{requestId:W,id:J}})),B(null),z(null);const R=H.current;R?C.handleSelect("",{dataset:{editorPath:R}}):C.clearSelection(),H.current=null},[C]);u.useEffect(()=>{if(typeof window>"u")return;const W=J=>{const R=J.detail;if(typeof R?.requestId!="string")return;const le=M.current;le&&le!==R.requestId&&X(le,null),H.current=P.current,B(R.requestId)};return window.addEventListener(Wa,W),()=>window.removeEventListener(Wa,W)},[X]),u.useEffect(()=>{if(!D)return;const W=J=>{J.key==="Escape"&&(J.preventDefault(),X(D,null))};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[D,X]),u.useEffect(()=>{if(!t)return;const W=f.editMode==="iteration_item"||f.editMode==="modal",J=(_e,Ie)=>k4(_e,t,Ie?{x:Ie.clientX,y:Ie.clientY}:void 0,{handleFallback:W}),R=_e=>{const Ie=_e.dataset.editorPath??"",He=Ie?Re(Ie):null,Nt={children:ze.current.components},gt=He?Be(Nt,He):null,Mt=gt&&typeof gt.props?.id=="string"?gt.props.id:typeof gt?.id=="string"?gt.id:"";return Mt.startsWith("auto_")?"":Mt},le=_e=>{const Ie=J(_e.target,_e);if(!Ie)return;const He=M.current;if(He){_e.preventDefault(),_e.stopPropagation();const Nt=R(Ie);Nt&&X(He,Nt);return}_e.preventDefault(),_e.stopPropagation(),C.handleSelect(Ie.dataset.editorId??"",{currentTarget:Ie,dataset:Ie.dataset})},ye=_e=>{const Ie=J(_e.target,_e);if(M.current){if(!Ie){z(null);return}const He=fo(t,Ie.dataset.editorPath??null);if(!He){z(null);return}z({box:He,hasId:R(Ie)!==""});return}if(!Ie){C.handleHover(null,{});return}C.handleHover(Ie.dataset.editorId??"",{currentTarget:Ie,dataset:Ie.dataset})},we=()=>{if(M.current){z(null);return}C.handleHover(null,{})},Te=_e=>{const Ie=J(_e.target,_e);if(!Ie)return;const He=Ie.dataset.editorPath??"";He&&(_e.preventDefault(),_e.stopPropagation(),Y(He))},ke=t.parentElement??t;return ke.addEventListener("click",le,!0),ke.addEventListener("mousemove",ye,!0),ke.addEventListener("mouseleave",we,!0),ke.addEventListener("dblclick",Te,!0),()=>{ke.removeEventListener("click",le,!0),ke.removeEventListener("mousemove",ye,!0),ke.removeEventListener("mouseleave",we,!0),ke.removeEventListener("dblclick",Te,!0)}},[t,C,Y,f.editMode,X]);const Z=u.useMemo(()=>{const W=C.selectedPath;if(!W)return null;const J=W.match(/^(.*)\.children\.\d+$/);return J?J[1]:null},[C.selectedPath]),se=u.useCallback(()=>{Z&&C.handleSelect("",{dataset:{editorPath:Z}})},[Z,C]),oe=u.useMemo(()=>!t||!C.selectedPath?null:t.querySelector(`[data-editor-path="${an(C.selectedPath)}"]`),[t,C.selectedPath]),G=u.useMemo(()=>C.selectedPath?Re(C.selectedPath):null,[C.selectedPath]),ee=u.useMemo(()=>{if(!G)return null;const W=G.find(et);if(!W)return null;const{i18nKey:J,raw:R}=SC(W.responsive);return J?g(J):g("layout_editor.overlay.branch_custom",{range:R})},[G,g]),ge=u.useMemo(()=>C.selectedPath?C.selectedIsIteration&&C.selectedIterationSourcePath?C.selectedIterationSourcePath:C.selectedPath:null,[C.selectedPath,C.selectedIsIteration,C.selectedIterationSourcePath]),V=u.useMemo(()=>ge?Re(ge):null,[ge]),te=u.useMemo(()=>!t||!ge?null:t.querySelector(`[data-editor-path="${an(ge)}"]`),[t,ge]),be=u.useMemo(()=>{if(te?.parentElement)return te.parentElement;if(!t||!ge)return null;const W=ge.match(/^(.*)\.children\.\d+$/);return W?t.querySelector(`[data-editor-path="${an(W[1])}"]`):null},[te,t,ge]),Ee=u.useMemo(()=>{const W=C.selectedNode;return W&&(typeof W.name=="string"?W.name:typeof W.type=="string"?W.type:"")||null},[C.selectedNode]),De=u.useMemo(()=>{if(C.selectedLockKind!=="extension")return null;const W=C.selectedNode?.__source;if(!W||W.kind!=="extension")return null;const J=W.extensionName?.trim(),R=W.extensionIdentifier?.trim();return J&&R?`${J} (${R})`:J||R||W.extensionSourceType||null},[C.selectedLockKind,C.selectedNode]),Se=z7({parentEl:be,selectedPath:V,selectedEl:te}),Ue=u.useMemo(()=>!t||!ge||ge===C.selectedPath?A:fo(t,ge),[t,ge,A,C.selectedPath,k]),Me=u.useRef(null),Oe=u.useCallback(()=>{const W=Me.current;W&&(_.close(W),Me.current=null)},[_]),Ye=u.useRef(()=>{}),ze=u.useRef({manifest:n,nesting:o,componentPalette:r,components:k});ze.current={manifest:n,nesting:o,componentPalette:r,components:k};const Xe=u.useCallback(W=>{const J=W.insertion?.parentPath??[],R=W.insertion?.index??0,le=ze.current,ye=xg(le.components,J);Oe();const we=_.open({ariaLabel:h("layout_editor.palette.title"),width:880,maxHeightRatio:.82,content:u.createElement(Nf,{manifest:le.manifest,nesting:le.nesting,componentPalette:le.componentPalette??null,targetParentPath:J,targetContainerName:ye,onInsert:(Te,ke,_e)=>{Ye.current(Te,ke,_e)},insertionIndex:R,onClose:()=>Oe(),editorTemplateId:f.templateIdentifier,editorLocale:f.locale}),onClose:()=>{Me.current=null}});Me.current=we},[_,Oe]),ve=u.useMemo(()=>{if(!f.isPaletteOpen)return null;if(!G)return{parentPath:[],index:k.length};if(C.selectedLockKind!=="none"){const le=V;return!le||le.length===0?{parentPath:[],index:k.length}:{parentPath:le.slice(0,-1),index:(le[le.length-1]??0)+1}}const J=C.selectedNode,R=Array.isArray(J?.children)?J.children.length:0;return MI(J?.name,R,G,o,k.length)},[f.isPaletteOpen,G,V,C.selectedLockKind,C.selectedNode,k.length,o]),qe=u.useCallback(()=>{b({type:"SET_PALETTE_OPEN",open:!1})},[b]),We=u.useRef(null);u.useEffect(()=>{if(!f.isPaletteOpen){const ye=We.current;ye&&(_.close(ye),We.current=null);return}if(!ve||We.current)return;const W=ve,J=ze.current,R=xg(J.components,W.parentPath),le=_.open({ariaLabel:h("layout_editor.palette.title"),width:880,maxHeightRatio:.82,content:u.createElement(Nf,{manifest:J.manifest,nesting:J.nesting,componentPalette:J.componentPalette??null,targetParentPath:W.parentPath,targetContainerName:R,onInsert:(ye,we,Te)=>{Ye.current(ye,we,Te),qe()},insertionIndex:W.index,onClose:()=>qe(),editorTemplateId:f.templateIdentifier,editorLocale:f.locale}),onClose:()=>{We.current=null,b({type:"SET_PALETTE_OPEN",open:!1})}});We.current=le},[f.isPaletteOpen,ve,_,qe,b]);const ce=u.useRef({layoutName:null,pushed:!1});u.useEffect(()=>{const W=v?.document?.layoutName??null;if(!W){ce.current={layoutName:null,pushed:!1};return}ce.current.layoutName!==W&&(y.clear(),y.push({actionKind:"inline_text_edit",label:"baseline",snapshot:k}),ce.current={layoutName:W,pushed:!0})},[v?.document?.layoutName,k,y]);const q=u.useRef(0);u.useEffect(()=>{const W=v?.saveSuccessCounter??0;W!==q.current&&(q.current=W,W!==0&&(y.clear(),y.push({actionKind:"inline_text_edit",label:"save_baseline",snapshot:k}),w.current=[],c?.([])))},[v?.saveSuccessCounter,k,y,c]);const re=u.useRef(0);u.useEffect(()=>{const W=v?.reloadCounter??0;W!==re.current&&(re.current=W,W!==0&&(ce.current={layoutName:null,pushed:!1},w.current=[],c?.([])))},[v?.reloadCounter,c]);const ie=u.useCallback((W,J,R)=>{if(!v)return;let le=[];v.patchLayout(ke=>{const _e={children:ke},Ie=Va(_e,J),He=R<0?Array.isArray(Ie?.children)?Ie.children.length:0:R,gt=ts(_e,J,He,W).children??[];return le=gt,gt}),y.push({actionKind:"insert",label:`insert ${W.name??W.type??""}`,snapshot:le});const ye=Va({children:le},J),we=R<0?Array.isArray(ye?.children)?ye.children.length-1:0:R,Te=at([...J,we]);if(w.current=[...w.current,Te],c?.(w.current),t){const ke=`[data-editor-path="${an(Te)}"]`,_e=()=>{const Ie=t.querySelector(ke);Ie&&typeof Ie.scrollIntoView=="function"&&Ie.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"})};typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(()=>window.requestAnimationFrame(_e)):setTimeout(_e,32)}},[v,y,c,t]);Ye.current=ie;const me=u.useCallback(()=>{if(!v||!C.selectedNode||!G)return;const W=os(C.selectedNode);let J=[];v.patchLayout(R=>{const le={children:R},ye=G.slice(0,-1),we=G[G.length-1]??0,ke=ts(le,ye,we+1,W).children??[];return J=ke,ke}),y.push({actionKind:"insert",label:"duplicate",snapshot:J})},[v,C.selectedNode,G,y]),Ce=u.useCallback(()=>{if(!v||!G)return;let W=[];v.patchLayout(J=>{const ye=ns({children:J},G).children??[];return W=ye,ye}),y.push({actionKind:"remove",label:"remove",snapshot:W}),C.clearSelection()},[v,G,y,C]),$e=u.useMemo(()=>{if(!C.selectedNode||!G||G.some(et))return null;const W=C.selectedNode;if(!Array.isArray(W.children))return null;const J=kC(f.previewDevice,W,f.previewCustomWidth);return{mode:J.mode,key:J.key,sourceKey:J.sourceKey}},[C.selectedNode,G,f.previewDevice,f.previewCustomWidth]),U=u.useCallback(()=>{if(!v||!G||$e?.mode!=="separate")return;const W=$e.key,J=$e.sourceKey;let R=[];v.patchLayout(le=>(R=Pb({children:le},G,W,J).children??[],R)),y.push({actionKind:"insert",label:"separate_branch",snapshot:R})},[v,G,$e,y]),ue=u.useCallback(()=>{if(!v||!G||$e?.mode!=="merge")return;const W=$e.key;let J=[];v.patchLayout(R=>(J=Ob({children:R},G,W).children??[],J)),y.push({actionKind:"remove",label:"merge_branch",snapshot:J})},[v,G,$e,y]),fe=u.useCallback(W=>{switch(W){case"mobile":return g("layout_editor.context_menu.device_mobile");case"portable":return g("layout_editor.context_menu.device_portable");case"tablet":return g("layout_editor.context_menu.device_tablet");case"desktop":return g("layout_editor.context_menu.device_desktop");default:return g("layout_editor.context_menu.device_custom",{range:W})}},[g]),xe=u.useMemo(()=>{if(!$e)return null;const W=fe($e.key);return{separate:g("layout_editor.context_menu.separate_branch_device",{device:W}),merge:g("layout_editor.context_menu.merge_branch_device",{device:W})}},[$e,g,fe]),he=u.useMemo(()=>{if(!C.selectedNode||!G)return[];if(G.some(et))return[];const W=Yr(f.previewDevice,C.selectedNode,f.previewCustomWidth);return vT(C.selectedNode,W).map(J=>({key:J,label:fe(J)}))},[C.selectedNode,G,f.previewDevice,f.previewCustomWidth,fe]),j=u.useCallback(W=>{if(W==="desktop"||W==="tablet"||W==="mobile"||W==="portable"){m.setDevice(W);return}m.setDevice(W)},[m]),ne=u.useCallback(()=>{C.selectedNode&&hg(C.selectedNode)},[C.selectedNode]),pe=u.useCallback(()=>{C.selectedNode&&(hg(C.selectedNode),Ce())},[C.selectedNode,Ce]),Q=u.useCallback(()=>{if(!v)return;const W=y4();if(!W)return;const J=os(W);if(G&&G.length>0){const R=G.slice(0,-1),le=(G[G.length-1]??0)+1;ie(J,R,le)}else ie(J,[],k.length)},[v,G,ie,k.length]),ae=u.useCallback((W,J)=>{y.push({actionKind:"move",label:J,snapshot:W})},[y]),Ae=u.useCallback(()=>{if(C.selectedNavAffordance==="route_in_tree"&&C.selectedNavTargetPath){if(d){d(C.selectedNavTargetPath);return}b({type:"SELECT_ROUTE",route:{path:C.selectedNavTargetPath,layoutName:null}})}},[C.selectedNavAffordance,C.selectedNavTargetPath,d,b]),dt=u.useCallback(()=>{const W=Mb(C.selectedBaseLayout,f.selectedRoute?.layoutName);W&&b({type:"ENTER_BASE_EDIT",layoutName:W})},[C.selectedBaseLayout,f.selectedRoute?.layoutName,b]),pt=u.useCallback(()=>{const W=C.selectedNode?.__source?.extensionId;W!=null&&b({type:"ENTER_EXTENSION_EDIT",extensionId:String(W)})},[C.selectedNode,b]),ot=u.useCallback(()=>{const W=C.selectedIterationSourcePath;W&&b({type:"ENTER_ITERATION_ITEM_EDIT",sourcePath:W})},[C.selectedIterationSourcePath,b]),Le=u.useRef(null),je=u.useRef(null),Je=u.useRef(null),Tt=u.useRef({colorScheme:"base",breakpoint:"base"}),Dt=Le.current!==null?_.stack.some(W=>W.id===Le.current):!1,zt=u.useMemo(()=>Od(f.routeTree,h),[f.routeTree,h]),xn=u.useMemo(()=>Bd(v?.document?.raw),[v?.document?.raw]),wn=u.useMemo(()=>Wd(s),[s?.states]),Zt=u.useMemo(()=>{const W=v?.document?.raw,J=Lf(W?.components),R=W?.initIsolated,le=R&&typeof R=="object"&&!Array.isArray(R)?Object.keys(R):[];return $A(J,le)},[v?.document?.raw]),Hn=u.useMemo(()=>{const W=v?.document?.raw;return Lf(W?.components).map(J=>J.scopeId).filter(J=>typeof J=="string"&&J.length>0)},[v?.document?.raw]),ln=Pd({raw:v?.document?.raw,spec:s}),Di=u.useCallback((W,J)=>{if(!v)return;const R={children:ze.current.components},le=Be(R,W);if(!le)return;Tt.current={colorScheme:f.previewColorScheme==="dark"?"dark":"base",breakpoint:Yr(f.previewDevice,le,f.previewCustomWidth)};const ye=t?.getBoundingClientRect(),we=A&&ye?{left:ye.left+A.left,top:ye.top+A.top,width:A.width,height:A.height}:void 0,Te=oe,ke=W.find(et),_e=ke?fe(ke.responsive):null,Ie=W.filter(kn=>typeof kn=="number"),He=bb({children:ze.current.components},Ie,mb(ln)),Nt=He.length>0?[...Ki({iterationVars:He}),...ln]:ln,gt=(kn,PM)=>u.createElement(RT,{key:`pem-${at(je.current??[])}`,node:kn,spec:s,manifest:ze.current.manifest,t:h,permissionCandidates:a,pageCandidates:zt,dataSourceCandidates:xn,stateKeyCandidates:wn,bindingCandidates:Nt,liveElement:Te,templateIdentifier:f.templateIdentifier,initialTab:PM,branchLabel:_e,isolatedScopeIdCandidates:Zt,usedScopeIds:Hn,onSaveInjectedProps:async(mt,Sn)=>{const zi=typeof kn.id=="string"?kn.id:"",Fn=await f4(f.templateIdentifier,mt,zi,Sn);if(st({op:"save",layoutName:`extension:${mt}`,editMode:f.editMode,saveTarget:"layout_extension",endpoint:`/api/admin/templates/${f.templateIdentifier}/layout-extensions/${mt}`,isDirty:!0,timestamp:Date.now()}),Fn.kind!=="success")throw new Error(Fn.kind==="conflict"?h("layout_editor.save.conflict"):Fn.kind==="injection_not_found"?"injection not found":Fn.kind==="not_found"?"extension not found":Fn.message??"save failed")},scope:Tt.current,onScopeChange:mt=>{Tt.current=mt;const Sn=Le.current;Sn&&_.open({id:Sn,ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(kn),onClose:()=>{Le.current=null,je.current=null}})},onPatchNode:mt=>{let Sn=[];v.patchLayout(Fn=>(Sn=Ot({children:Fn},W,()=>mt).children??[],Sn)),y.push({actionKind:"inline_text_edit",label:"edit_props",snapshot:Sn}),dr({source:"style_control",componentPath:at(W),componentName:typeof mt.name=="string"?mt.name:null,patchKey:null,timestamp:Date.now()});const zi=Le.current;zi&&_.open({id:zi,ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(mt),onClose:()=>{Le.current=null,je.current=null}})},onDelete:()=>{const mt=Le.current;mt&&_.close(mt),Ce()},onClose:()=>{const mt=Le.current;mt&&_.close(mt)}});je.current=W;const Mt=_.open({ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(le,J),onClose:()=>{Le.current=null,je.current=null,Je.current=null}});Le.current=Mt,Je.current=kn=>{_.open({id:Mt,ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(kn),onClose:()=>{Le.current=null,je.current=null,Je.current=null}})}},[v,s,h,a,zt,xn,wn,ln,oe,y,_,Ce,t,A,f.previewColorScheme,f.previewDevice,f.previewCustomWidth,fe]);u.useEffect(()=>{const W=Je.current,J=je.current;if(!W||!J)return;const R={children:ze.current.components},le=Be(R,J);le?W(le):Le.current&&_.close(Le.current)},[k]);const vM=()=>{if(!Dt)return null;const J={position:"absolute",background:"rgba(15, 23, 42, 0.45)",pointerEvents:"auto",zIndex:W7},R=ke=>{ke.preventDefault(),ke.stopPropagation()};if(!A)return i.jsx("div",{"data-testid":"g7le-edit-lock-full",onClick:R,onMouseMove:R,style:{...J,inset:0}});const{left:le,top:ye,width:we,height:Te}=A;return i.jsxs("div",{"data-testid":"g7le-edit-lock",style:{position:"absolute",inset:0,pointerEvents:"none"},children:[i.jsx("div",{"data-testid":"g7le-edit-lock-top",onClick:R,onMouseMove:R,style:{...J,left:0,top:0,right:0,height:Math.max(0,ye)}}),i.jsx("div",{"data-testid":"g7le-edit-lock-bottom",onClick:R,onMouseMove:R,style:{...J,left:0,top:ye+Te,right:0,bottom:0}}),i.jsx("div",{"data-testid":"g7le-edit-lock-left",onClick:R,onMouseMove:R,style:{...J,left:0,top:ye,width:Math.max(0,le),height:Te}}),i.jsx("div",{"data-testid":"g7le-edit-lock-right",onClick:R,onMouseMove:R,style:{...J,left:le+we,top:ye,right:0,height:Te}})]})},wl=u.useCallback(()=>{if(G&&$p(C.selectedLockKind)){if(p&&C.selectedPath){p(C.selectedPath);return}Di(G)}},[G,C.selectedPath,C.selectedLockKind,p,Di]),{scale:kl}=m,Sl=typeof C.selectedNode?.name=="string"?C.selectedNode.name:"",Uh=s?.componentCapabilities?.[Sl]??null,qh=Array.isArray(Uh?.styleControls)?Uh.styleControls:[],_M=qh.includes("width")?Ct(s,"width"):null,xM=qh.includes("height")?Ct(s,"height"):null,wM=u.useCallback((W,J)=>{if(!v||!G)return;let R=[];v.patchLayout(le=>(R=Ot({children:le},G,()=>W).children??[],R)),dr({source:"resize",componentPath:at(G),componentName:Sl||null,patchKey:J==="height"?"height":"width",resizeAxis:J,timestamp:Date.now()})},[v,G,Sl]),kM=u.useCallback((W,J)=>{if(!v||!G)return;let R=[];v.patchLayout(le=>(R=Ot({children:le},G,()=>W).children??[],R)),y.push({actionKind:"inline_text_edit",label:`resize ${J}`,snapshot:R})},[v,G,y]),SM=u.useCallback(()=>{if(!oe)return null;const W=oe.getBoundingClientRect(),J=kl||1;return{width:W.width/J,height:W.height/J}},[oe,kl]),lr=v4({node:C.selectedNode,widthControl:_M,heightControl:xM,scale:kl,measureStartSize:SM,onResize:wM,onResizeEnd:kM}),CM=u.useCallback((W,J)=>{lr.onHandlePointerDown(W,J)},[lr]),Cl=u.useCallback(()=>{const W=y.undo();!W||!v||v.setLayoutComponents(W.snapshot)},[y,v]),$l=u.useCallback(()=>{const W=y.redo();!W||!v||v.setLayoutComponents(W.snapshot)},[y,v]);O7({onUndo:Cl,onRedo:$l});const $M=u.useMemo(()=>({copy:ne,cut:pe,paste:Q,delete:Ce,openProps:wl,selectParent:Z?se:void 0,deselect:C.clearSelection}),[ne,pe,Q,Ce,wl,Z,se,C.clearSelection]);lp({handlers:$M,hasSelection:!!C.selectedPath}),u.useEffect(()=>(window.__g7LayoutEditorHasSelection=!!C.selectedPath,()=>{try{delete window.__g7LayoutEditorHasSelection}catch{}}),[C.selectedPath]),u.useEffect(()=>(window.__g7LayoutEditorHistory={undo:Cl,redo:$l,canUndo:y.canUndo,canRedo:y.canRedo},()=>{try{delete window.__g7LayoutEditorHistory}catch{}}),[Cl,$l,y.canUndo,y.canRedo]);const EM=u.useCallback(W=>{const J=L;F(null),J&&(async()=>{if((await I.commit(J.path,W)).kind==="created"&&v){const le=v.document?.raw?.components??[];y.push({actionKind:"inline_text_edit",label:"inline_create_key",snapshot:le})}})()},[L,I,v,y]),Gh=u.useCallback(()=>{const W=L;F(null),I.trackCancel(W?.path??null)},[L,I]),IM=u.useCallback(()=>{F(null)},[]),AM=u.useCallback(async W=>{const J=L;if(!J)return null;const R=await I.keyifyChipValue(J.path,W);if(R.kind!=="created"||!R.translationKey)return null;const le=v?.document?.raw?.components??[];return y.push({actionKind:"inline_text_edit",label:"inline_keyify_chip",snapshot:le}),R.translationKey},[L,I,v,y]),TM=u.useCallback(()=>{const W=L;W&&(F(null),C.handleSelect("",{dataset:{editorPath:W.domPath}}),Di(W.path,"translation"))},[L,C,Di]),wt=u.useMemo(()=>{if(!L)return null;const W=v?.document?.raw?.components??k;return Be({children:W},L.path)},[L,v?.document,k]),DM=u.useCallback(async(W,J)=>{const R=L;if(!v||!R)return null;const le=typeof wt?.text=="string"?wt.text:"";let ye;if(R.isParamKey)ye=await Cr(f.templateIdentifier,f.locale,le,W,J.sourceId,J.path,"scalar");else{const He=Nt=>Nt.replace(/\$t:[a-zA-Z0-9._-]+/g,gt=>{const Mt=h(gt.slice(3));return Mt&&Mt!==gt.slice(3)&&!Mt.startsWith("$t:")?Mt:""}).replace(/\s+/g," ").trim();ye=await us(f.templateIdentifier,f.selectedRoute?.layoutName??null,f.locale,le,W,J.sourceId,J.path,"scalar",He,h)}if(ye.kind==="error")return null;const we=R.path;let Te=[];v.patchLayout(He=>(Te=Ot({children:He},we,Mt=>({...Mt,text:ye.text})).children??[],Te)),y.push({actionKind:"inline_text_edit",label:"inline_insert_binding",snapshot:Te});const ke=ye.kind==="ok"&&"key"in ye?ye.key:void 0;!R.isParamKey&&ke&&F(He=>He&&He.path===we?{...He,isParamKey:!0,customKey:ke,chipValue:void 0,chipParamLabels:void 0}:He);try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:f.templateIdentifier,locale:f.locale}}))}catch{}const _e=vt(ye.text),Ie=R.customKey??_e?.key??"";return Ie?It(Ie,f.locale)??null:null},[v,L,wt,f.templateIdentifier,f.locale,f.selectedRoute,y,h]),zM=u.useCallback(async W=>{const J=L;if(!v||!J)return null;const R=typeof wt?.text=="string"?wt.text:"",le=vt(R),ye=J.customKey??le?.key??null,we=vo(R,W),Te=J.path;let ke=[];return v.patchLayout(_e=>(ke=Ot({children:_e},Te,Nt=>({...Nt,text:we})).children??[],ke)),y.push({actionKind:"inline_text_edit",label:"inline_remove_binding",snapshot:ke}),ye&&await $r(f.templateIdentifier,ye,W,f.locale),ye?It(ye,f.locale)??null:null},[v,L,wt,f.templateIdentifier,f.locale,y]),[El,Yh]=u.useState({}),NM=["fontSize","color","fontStyle","textDecoration","textAlign","letterSpacing","lineHeight","fontFamily"];u.useEffect(()=>{if(!L||!t||typeof MutationObserver>"u"){Yh({});return}const W=`[data-editor-path="${an(L.domPath)}"]`,J=()=>{const ye=t.querySelector(W);if(!ye)return;const we={};for(const ke of NM){const _e=ye.style.getPropertyValue(ke.replace(/([A-Z])/g,"-$1").toLowerCase());_e&&(we[ke]=_e)}const Te=wg(t,L.domPath)??void 0;Yh({className:ye.className,style:we,effectiveColor:Te})};J();const R=t.querySelector(W);if(!R)return;const le=new MutationObserver(J);return le.observe(R,{attributes:!0,attributeFilter:["class","style"]}),le.observe(t,{childList:!0,subtree:!0}),()=>le.disconnect()},[L?.path?at(L.path):null,t]);const Xh=u.useCallback((W,J)=>{if(!v||!L)return;const R=L.path;let le=[],ye=null;v.patchLayout(we=>(le=Ot({children:we},R,_e=>{const Ie=J(_e);return ye=typeof Ie.name=="string"?Ie.name:null,Ie}).children??[],le)),y.push({actionKind:"inline_text_edit",label:`inline_format ${W}`,snapshot:le}),dr({source:"style_control",componentPath:at(R),componentName:ye,patchKey:W,timestamp:Date.now()})},[v,L,y]),ft=u.useMemo(()=>{const W=C.selectedPath;if(!W||!x)return null;const J=[];let R=W;for(;R;){J.push(R);const le=R.match(/^(.*)\.children\.\d+$/);R=le?le[1]:null}for(const le of J){const ye=Re(le);if(!ye)continue;const we=Be(x,ye),Te=typeof we?.name=="string"?we.name:null;if(!Te)continue;const ke=ji(s,Te),_e=ke?.canvasOverlay?.kind;if(typeof _e!="string"||!_e||!we)continue;const Ie=ke.canvasOverlay.params&&typeof ke.canvasOverlay.params=="object"?ke.canvasOverlay.params:void 0,He=le===W?null:W.slice(le.length+1);return{kind:_e,params:Ie,tablePath:le,tableNode:we,selectedCellRel:He}}return null},[C.selectedPath,x,s]),yo=ft?g4(ft.kind):null,Jh=u.useMemo(()=>!yo||!t||!ft?null:fo(t,ft.tablePath),[yo,t,ft,A,k]),MM=u.useMemo(()=>{if(!yo||!t||!ft)return[];const W=ft.tablePath,J=an(W),R=[];return t.querySelectorAll(`[data-editor-path^="${J}.children."]`).forEach(we=>{const Te=we.dataset.editorPath??"";if(!Te.startsWith(W+"."))return;const ke=Te.slice(W.length+1),_e=ao(we,t);_e&&R.push({path:ke,top:_e.top,left:_e.left,width:_e.width,height:_e.height})}),t.querySelectorAll(`[data-editor-item-path^="${J}."]`).forEach(we=>{const Te=we.dataset.editorItemPath??"";if(!Te.startsWith(W+"."))return;const ke=Te.slice(W.length+1),_e=ao(we,t);_e&&R.push({path:ke,top:_e.top,left:_e.left,width:_e.width,height:_e.height})}),R},[yo,t,ft,A,k]),LM=u.useCallback(W=>{const J=ft?Re(ft.tablePath):null;if(!v||!J)return;let R=[];v.patchLayout(le=>(R=Ot({children:le},J,()=>W).children??[],R)),y.push({actionKind:"inline_text_edit",label:"inplace_edit",snapshot:R}),dr({source:"style_control",componentPath:ft?.tablePath??"",componentName:typeof W.name=="string"?W.name:null,patchKey:"canvas_inplace",timestamp:Date.now()})},[v,G,y]);return t?i.jsxs("div",{className:"g7le-editor-canvas-overlay","data-testid":"g7le-editor-canvas-overlay",style:{position:"absolute",inset:0,pointerEvents:"none"},children:[!D&&vM(),D&&i.jsxs("div",{"data-testid":"g7le-canvas-pick-banner",style:{position:"absolute",top:8,left:"50%",transform:"translateX(-50%)",zIndex:9999,display:"flex",alignItems:"center",gap:12,padding:"8px 14px",background:"#1e293b",color:"#fff",borderRadius:8,fontSize:13,boxShadow:"0 4px 12px rgba(0,0,0,0.25)",pointerEvents:"auto"},children:[i.jsxs("span",{children:["🎯 ",h("layout_editor.target_picker.canvas_pick_hint")]}),i.jsx("button",{type:"button","data-testid":"g7le-canvas-pick-cancel",onClick:()=>X(D,null),style:{border:"1px solid #475569",borderRadius:6,background:"transparent",color:"#cbd5e1",cursor:"pointer",fontSize:12,padding:"3px 10px"},children:h("layout_editor.target_picker.cancel")})]}),f.editMode!=="route"&&i.jsx(RI,{frameEl:t,components:k,editMode:f.editMode,currentExtensionId:$,editableRootPath:S}),L&&((L.isParamKey&&L.customKey||L.chipValue)&&wt?i.jsxs(i.Fragment,{children:[wt&&i.jsx(vg,{node:wt,spec:s,t:h,onApplyControl:Xh,box:L.box,scope:{colorScheme:f.previewColorScheme==="dark"?"dark":"base",breakpoint:Yr(f.previewDevice,wt,f.previewCustomWidth)}}),i.jsx(D4,{box:L.box,node:wt,customKey:L.customKey??null,initialChipValue:L.chipValue,chipParamLabels:L.chipParamLabels,onKeyify:AM,templateIdentifier:f.templateIdentifier,locale:f.locale,t:h,candidates:ln,onInsertBinding:DM,onRemoveBinding:zM,onCommit:IM,onCancel:Gh})]}):i.jsxs(i.Fragment,{children:[wt&&i.jsx(vg,{node:wt,spec:s,t:h,onApplyControl:Xh,box:L.box,scope:{colorScheme:f.previewColorScheme==="dark"?"dark":"base",breakpoint:wt?Yr(f.previewDevice,wt,f.previewCustomWidth):"base"}}),i.jsx(T4,{box:L.box,initialValue:L.initialValue,isCustomKey:L.isCustomKey,t:h,onCommit:EM,onCancel:Gh,mirrorClassName:El.className,mirrorStyle:El.style,nodeEffectiveColor:El.effectiveColor??L.nodeEffectiveColor,onOpenTranslations:TM})]})),!D&&i.jsx(U7,{hoverBox:T,selectedBox:A,lockKind:C.selectedLockKind,navAffordance:C.selectedNavAffordance,onEditProps:wl,onDuplicate:me,onDelete:Ce,onSeparateBranch:$e?.mode==="separate"?U:void 0,separateBranchLabel:xe?.separate,onMergeBranch:$e?.mode==="merge"?ue:void 0,mergeBranchLabel:xe?.merge,definedDeviceBranches:he,onJumpToDevice:he.length>0?j:void 0,onLinkEditDestination:Ae,onEditBase:dt,onEditExtension:pt,extensionLabel:De,baseLayoutLabel:C.selectedBaseLayout,dataSourceLabel:C.selectedDataSourceId,branchLabel:ee,onEditIteration:C.selectedIsIteration&&f.editMode!=="iteration_item"?ot:void 0,resizeEnabledAxes:lr.enabledAxes,onResizeHandlePointerDown:lr.enabledAxes.width||lr.enabledAxes.height?CM:void 0,selectedName:Ee,onSelectParent:Z?se:void 0}),D&&O&&i.jsx("div",{"data-testid":"g7le-canvas-pick-hover","data-pick-has-id":O.hasId?"true":"false",style:{position:"absolute",left:O.box.left,top:O.box.top,width:O.box.width,height:O.box.height,pointerEvents:"none",zIndex:9998,boxSizing:"border-box",border:O.hasId?"2px solid #2563eb":"2px dashed #94a3b8",background:O.hasId?"rgba(37,99,235,0.10)":"repeating-linear-gradient(45deg, rgba(148,163,184,0.18) 0, rgba(148,163,184,0.18) 6px, transparent 6px, transparent 12px)",cursor:O.hasId?"pointer":"not-allowed"},children:!O.hasId&&i.jsx("span",{"data-testid":"g7le-canvas-pick-hover-hint",style:{position:"absolute",top:0,left:0,transform:"translateY(-100%)",background:"#475569",color:"#fff",fontSize:11,lineHeight:1.4,padding:"2px 6px",borderRadius:4,whiteSpace:"nowrap"},children:h("layout_editor.target_picker.needs_id")})}),!D&&i.jsx(Z7,{selectedBox:Ue,points:Se.points,onAddRequest:Xe}),yo&&ft&&Jh&&C.selectedLockKind==="none"&&i.jsx(yo,{node:ft.tableNode,params:ft.params,nodeBox:Jh,cellBoxes:MM,selectedCellPath:ft.selectedCellRel??void 0,colorScheme:f.previewColorScheme==="dark"?"dark":"light",t:h,onPatchNode:LM,onInsertChild:ie,onRemoveChild:W=>{const J=Re(W);if(!v||!J)return;let R=[];v.patchLayout(le=>(R=ns({children:le},J).children??[],R)),y.push({actionKind:"remove",label:"inplace_remove",snapshot:R})},onRequestInlineEdit:W=>{ft&&Y(`${ft.tablePath}.${W}`)}}),v&&i.jsx(GI,{frameEl:t,nesting:o,editMode:f.editMode,currentExtensionId:$,editableRootPath:S,components:k,patchLayout:v.patchLayout,pushHistory:ae,selectedPath:C.selectedPath,onSelectPath:W=>C.handleSelect("",{dataset:{editorPath:W}}),onMovePath:W=>C.handleSelect("",{dataset:{editorPath:W}}),onRequestInlineEdit:Y})]}):null}function xg(e,t){if(t.length===0)return null;const o=Va({children:e},t);return o&&typeof o.name=="string"?o.name:null}function Va(e,t){return Be(e,t)}function an(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/[^a-zA-Z0-9_\-.]/g,t=>`\\${t}`)}function wg(e,t){if(!t)return null;const n=e.querySelector(`[data-editor-path="${an(t)}"]`);if(!n||typeof window.getComputedStyle!="function")return null;let o=n;const r=n.ownerDocument.createTreeWalker(n,NodeFilter.SHOW_TEXT);let s=r.nextNode();for(;s;){if((s.textContent??"").trim().length>0){const a=s.parentElement;if(a&&n.contains(a)){o=a;break}}s=r.nextNode()}try{return window.getComputedStyle(o).color||null}catch{return null}}function fo(e,t){if(!t)return null;const n=e.querySelector(`[data-editor-path="${an(t)}"]`);if(n){const c=ao(n,e);return c&&lo(c,e)?c:null}const o=e.querySelectorAll(`[data-editor-path^="${an(t)}.iteration."]`);let r=1/0,s=1/0,a=-1/0,l=-1/0,d=!1;return o.forEach(c=>{const p=c.dataset.editorPath??"";if(!new RegExp("\\.iteration\\.\\d+$").test(p))return;const f=ao(c,e);f&&lo(f,e)&&(d=!0,r=Math.min(r,f.left),s=Math.min(s,f.top),a=Math.max(a,f.left+f.width),l=Math.max(l,f.top+f.height))}),d?{left:r,top:s,width:a-r,height:l-s,scale:1}:null}function W4({isEditMode:e,editorSpec:t,sampleOverride:n}){const o=t?.sampleData;return u.useMemo(()=>Km({spec:o,overrideSpec:n,onMatch:r=>{Qh(r)}}),[e,o,n])}const j4=Lt().ComponentRegistry;function H4(e){return e.replace(/[\t\n\r]/g,"").replace(/\\/g,"/").replace(/^([a-z][a-z0-9+.\-]*:)?\/{2,}/i,"$1//")}function F4(e,t){try{const n=typeof window<"u"&&window.location?.protocol||"https:",o=t||(typeof window<"u"?window.location?.origin:void 0)||"https://localhost",r=e.startsWith("//")?`${n}${e}`:e,s=new URL(r,o);return s.protocol!=="http:"&&s.protocol!=="https:"?null:s.hostname.toLowerCase()}catch{return null}}function Ua(){const e=typeof window<"u"?window.G7Config?.trustedScriptHosts:void 0;return Array.isArray(e)?e.map(t=>String(t).toLowerCase()):[]}function kg(e,t){if(typeof e!="string")return!1;const n=e.trim();if(n==="")return!1;const o=H4(n),r=o.startsWith("//"),s=/^[a-z][a-z0-9+.-]*:/i.test(o);if(!r&&!s&&o.startsWith("/"))return!0;const a=F4(o),l=t??Ua();return a!==null&&l.map(d=>String(d).toLowerCase()).includes(a)}function K4(e){return e.split(/[-_]/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}async function V4(e){const t=typeof window<"u"?window.localStorage?.getItem("auth_token"):null,n={Accept:"application/json"};t&&(n.Authorization=`Bearer ${t}`);const o=await fetch(`/api/admin/templates/${encodeURIComponent(e)}/editor-assets`,{headers:n,credentials:"same-origin"});if(!o.ok){const s=await o.json().catch(()=>null);throw Jr(o.status,s,"assets")}const r=await o.json();return r.data||r}async function U4(e){try{if(typeof fetch!="function")return 0;const t=await fetch(en(`/api/templates/${encodeURIComponent(e)}/config`,"json"),{credentials:"same-origin",headers:{Accept:"application/json"}});if(!t.ok)return 0;const n=await t.json().catch(()=>null),o=n?.data?.cache_version??n?.cache_version;return typeof o=="number"&&o>0?o:0}catch{return 0}}function q4(e){return new Promise((t,n)=>{if(typeof document>"u"){n(new Error("document undefined"));return}if(!kg(e,Ua())){n(new Error(`Blocked untrusted script src (same-origin path or declared trusted host required): ${e}`));return}if(document.querySelector(`script[data-g7le-asset="${e}"]`)){t();return}const r=document.createElement("script");r.src=e,r.async=!1,r.setAttribute("data-g7le-asset",e),r.addEventListener("load",()=>t()),r.addEventListener("error",()=>n(new Error(`script load failed: ${e}`))),document.head.appendChild(r)})}async function G4(e){if(typeof document>"u")return;const t=`[data-g7le-asset="${e}"]`;if(document.querySelector(`link${t}, style${t}`))return;if(e.includes("/api/admin/"))try{const r=typeof window<"u"?window.localStorage?.getItem("auth_token"):null,s={Accept:"text/css"};r&&(s.Authorization=`Bearer ${r}`);const a=await fetch(e,{headers:s,credentials:"same-origin"});if(a.ok){const l=await a.text(),d=document.createElement("style");d.textContent=l,d.setAttribute("data-g7le-asset",e),document.head.appendChild(d);return}}catch{}const o=document.createElement("link");o.rel="stylesheet",o.href=e,o.setAttribute("data-g7le-asset",e),document.head.appendChild(o)}function Y4(e,t,n="user"){const[o,r]=u.useState({componentRegistry:null,translationEngine:null,isReady:!1,error:null});return u.useEffect(()=>{let s=!1;return(async()=>{r(a=>({...a,isReady:!1,error:null}));try{const a=await V4(e);if(s)return;for(const b of a.css??[])if(await G4(b),s)return;const l=K4(e);if(!(typeof window<"u"&&typeof window[l]=="object")){for(const b of a.js??[])if(await q4(b),s)return}const c=j4.createIsolatedInstance();if(await c.loadComponents(e,n),s)return;const p=await U4(e);if(s)return;const f=new Pt({defaultLocale:t});if(p>0&&f.setCacheVersion(p),await f.loadTranslations(e,t),s)return;gd(f,e);try{const b=Pt.getInstance();p>b.getCacheVersion()&&b.setCacheVersion(p),await b.loadTranslations(e,t),gd(b,e)}catch{}if(s)return;r({componentRegistry:c,translationEngine:f,isReady:!0,error:null})}catch(a){if(s)return;const l=xp(a)?a:so(a,"assets");r({componentRegistry:null,translationEngine:null,isReady:!1,error:l})}})(),()=>{s=!0}},[e,t,n]),o}const Sg=Lt().AuthManager;function X4(e){switch(e){case"unauthorized":return{icon:"🔒",tone:"blue",titleKey:"layout_editor.access_error.unauthorized.title",messageKey:"layout_editor.access_error.unauthorized.message",showRequiredPermissions:!0};case"forbidden":return{icon:"⛔",tone:"rose",titleKey:"layout_editor.access_error.forbidden.title",messageKey:"layout_editor.access_error.forbidden.message",showRequiredPermissions:!0};case"not_found":return{icon:"🗂️",tone:"slate",titleKey:"layout_editor.access_error.not_found.title",messageKey:"layout_editor.access_error.not_found.message",showRequiredPermissions:!1};case"server_error":return{icon:"🛠️",tone:"amber",titleKey:"layout_editor.access_error.server_error.title",messageKey:"layout_editor.access_error.server_error.message",showRequiredPermissions:!1};case"network":return{icon:"📡",tone:"amber",titleKey:"layout_editor.access_error.network.title",messageKey:"layout_editor.access_error.network.message",showRequiredPermissions:!1};default:return{icon:"⚠️",tone:"slate",titleKey:"layout_editor.access_error.unknown.title",messageKey:"layout_editor.access_error.unknown.message",showRequiredPermissions:!1}}}const J4={blue:{bg:"#eff6ff",border:"#bfdbfe",iconBg:"#dbeafe"},rose:{bg:"#fff1f2",border:"#fecdd3",iconBg:"#ffe4e6"},amber:{bg:"#fffbeb",border:"#fde68a",iconBg:"#fef3c7"},slate:{bg:"#f8fafc",border:"#e2e8f0",iconBg:"#f1f5f9"}};function Z4({error:e}){return u.useEffect(()=>{if(e.kind!=="unauthorized"||typeof window>"u")return;const t=Sg.getInstance(),n=`${window.location.pathname}${window.location.search}`,o=t.getLoginRedirectUrl("admin",n,"session_expired"),r=window.setTimeout(()=>{window.location.href=o},600);return()=>window.clearTimeout(r)},[e.kind]),null}function qa({error:e}){const{t}=tt(),n=X4(e.kind),o=J4[n.tone],r=()=>{typeof window<"u"&&(window.location.href="/admin")},s=()=>{typeof window<"u"&&window.location.reload()},a=()=>{if(typeof window>"u")return;const l=Sg.getInstance(),d=`${window.location.pathname}${window.location.search}`;window.location.href=l.getLoginRedirectUrl("admin",d)};return i.jsxs("div",{className:"g7le-access-error","data-testid":"g7le-access-error","data-error-kind":e.kind,style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"#f1f5f9"},children:[i.jsx(Z4,{error:e}),i.jsxs("div",{style:{maxWidth:480,width:"100%",background:o.bg,border:`1px solid ${o.border}`,borderRadius:12,padding:"28px 32px",boxShadow:"0 2px 8px rgba(15, 23, 42, 0.05)",textAlign:"center"},children:[i.jsx("div",{style:{width:64,height:64,margin:"0 auto 16px",borderRadius:"50%",background:o.iconBg,display:"flex",alignItems:"center",justifyContent:"center",fontSize:32,lineHeight:1},"aria-hidden":"true",children:n.icon}),i.jsx("h2",{"data-testid":"g7le-access-error-title",style:{margin:"0 0 8px",fontSize:18,fontWeight:700,color:"#0f172a"},children:t(n.titleKey)}),i.jsx("p",{"data-testid":"g7le-access-error-message",style:{margin:"0 0 16px",fontSize:13,lineHeight:1.6,color:"#475569"},children:t(n.messageKey)}),n.showRequiredPermissions&&e.requiredPermissions&&i.jsxs("div",{"data-testid":"g7le-access-error-permissions",style:{display:"inline-flex",flexWrap:"wrap",gap:6,justifyContent:"center",padding:"8px 12px",marginBottom:16,background:"rgba(15, 23, 42, 0.04)",borderRadius:8,fontSize:12,color:"#475569"},children:[i.jsx("span",{style:{fontWeight:600},children:t("layout_editor.access_error.required_permission_label")}),e.requiredPermissions.split(/[,\s]+/).filter(Boolean).map(l=>i.jsx("code",{style:{padding:"2px 6px",background:"#fff",border:"1px solid #e2e8f0",borderRadius:4,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:11,color:"#1e293b"},children:l},l))]}),e.message&&i.jsxs("details",{"data-testid":"g7le-access-error-detail",style:{marginBottom:16,fontSize:11,color:"#94a3b8"},children:[i.jsx("summary",{style:{cursor:"pointer"},children:t("layout_editor.access_error.detail_summary")}),i.jsxs("pre",{style:{marginTop:8,padding:8,background:"#fff",border:"1px solid #e2e8f0",borderRadius:6,overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word",textAlign:"left",fontSize:11,color:"#475569"},children:[e.status>0?`HTTP ${e.status} -`:"",e.message]})]}),i.jsxs("div",{style:{display:"flex",justifyContent:"center",gap:8,flexWrap:"wrap"},children:[e.kind==="unauthorized"&&i.jsx("button",{type:"button","data-testid":"g7le-access-error-action-signin",onClick:a,style:Ga,children:t("layout_editor.access_error.action.sign_in")}),e.kind==="forbidden"&&i.jsx("button",{type:"button","data-testid":"g7le-access-error-action-home",onClick:r,style:Ga,children:t("layout_editor.access_error.action.go_home")}),(e.kind==="not_found"||e.kind==="server_error"||e.kind==="network"||e.kind==="unknown")&&i.jsx("button",{type:"button","data-testid":"g7le-access-error-action-retry",onClick:s,style:Ga,children:t("layout_editor.access_error.action.retry")}),e.kind!=="unauthorized"&&i.jsx("button",{type:"button","data-testid":"g7le-access-error-action-home-secondary",onClick:r,style:Q4,children:t("layout_editor.access_error.action.go_admin_home")})]})]})]})}const Ga={padding:"8px 16px",background:"#2563eb",color:"#fff",border:"1px solid #1d4ed8",borderRadius:6,fontSize:13,fontWeight:600,cursor:"pointer"},Q4={padding:"8px 16px",background:"#fff",color:"#475569",border:"1px solid #cbd5e1",borderRadius:6,fontSize:13,fontWeight:500,cursor:"pointer"};function R4(e){const t=window;if(typeof t>"u")return{getSnapshot:()=>({globalState:{},localState:{}}),restore:()=>{}};const n=t.G7Core||{},o={templateApp:t.__templateApp,g7CoreState:n.state,g7CoreDispatch:n.dispatch,g7CoreData:n.data,g7CoreModal:n.modal,g7CoreToast:n.toast};let r={...e.initialGlobalState??{}};r._local||(r._local={});const s=[],a=()=>{const c={globalState:{...r},localState:{...r._local??{}}};for(const p of s)try{p(r)}catch{}e.onChange?.(c)},l={},d={getGlobalState:()=>r,setGlobalState:(c,p)=>{typeof c=="function"?r=c(r):r={...r,...c},a()},onGlobalStateChange:c=>(s.push(c),()=>{const p=s.indexOf(c);p>=0&&s.splice(p,1)}),get globalState(){return r},getActionDispatcher:()=>e.actionDispatcher,getDataSource:c=>l[c]??null,setDataSource:(c,p)=>{l[c]=p},refetchDataSource:async c=>null,updateDataSourceItem:(c,p,f)=>l[c]??null,getLocale:()=>e.locale,changeLocale:c=>{},getRouter:()=>({navigate:()=>{},replace:()=>{},push:()=>{}}),updateQueryParams:()=>{}};return t.__templateApp=d,n&&typeof n.dispatch=="function"&&(n.dispatch=(c,p)=>{try{return e.actionDispatcher.executeAction(c,p??{})}catch{return}}),n&&typeof n.modal=="object"&&n.modal!==null&&(n.modal={...n.modal,open:()=>{},close:()=>{},closeAll:()=>{}}),n&&typeof n.toast=="object"&&n.toast!==null&&(n.toast={...n.toast,push:()=>{},dismiss:()=>{}}),{getSnapshot:()=>({globalState:{...r},localState:{...r._local??{}}}),restore:()=>{t.__templateApp===d&&(t.__templateApp=o.templateApp),t.G7Core&&(o.g7CoreState!==void 0&&(t.G7Core.state=o.g7CoreState),o.g7CoreDispatch!==void 0&&(t.G7Core.dispatch=o.g7CoreDispatch),o.g7CoreData!==void 0&&(t.G7Core.data=o.g7CoreData),o.g7CoreModal!==void 0&&(t.G7Core.modal=o.g7CoreModal),o.g7CoreToast!==void 0&&(t.G7Core.toast=o.g7CoreToast)),s.length=0}}}const eD=new Set(["id","userId","postId","orderId","productId","categoryId","commentId","noticeId","inquiryId","addressId","wishlistId","notificationId","roleId","menuId"]);function tD(e){if(!e)return{};const t={},n=/:([a-zA-Z_][a-zA-Z0-9_]*)/g;let o;for(;(o=n.exec(e))!==null;){const r=o[1];t[r]=nD(r)}return t}function nD(e){return eD.has(e)||/Id$|_id$/.test(e)?"1":"sample"}const oD=mo("LayoutEditor");function Ro(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _i(e){if(Array.isArray(e))return e.map(t=>_i(t));if(Ro(e)){const t={};for(const[n,o]of Object.entries(e))t[n]=_i(o);return t}return e}function Cg(e,t="",n=new Set){for(const[o,r]of Object.entries(e)){const s=t?`${t}.${o}`:o;Ro(r)?Cg(r,s,n):n.add(s)}return n}function $g(e,t,n,o,r,s=""){for(const[a,l]of Object.entries(t)){const d=s?`${s}.${a}`:a;if(n.has(d)){r(`[LayoutEditor] sampleGlobal key conflict: extension '${o}' override of core key '${d}' ignored`);continue}const c=e[a];Ro(l)&&Ro(c)?$g(c,l,n,o,r,d):e[a]=_i(l)}}function Ya(e){const t=e.warn??(r=>oD.warn(r)),n=_i(e.coreSeed??{});e.isGuestOnly&&"currentUser"in n&&delete n.currentUser;const o=Cg(n);for(const r of e.sources)Ro(r.sampleGlobal)&&$g(n,r.sampleGlobal,o,r.id,t);return e.isGuestOnly&&"currentUser"in n&&delete n.currentUser,n}function rD(e){const t={};if(!e||typeof e!="object"||Array.isArray(e))return t;for(const[n,o]of Object.entries(e))n.startsWith("$")&&(t[n]=o);return t}function iD(e){const t={};if(!e||typeof e!="object"||Array.isArray(e))return t;for(const[n,o]of Object.entries(e))n.startsWith("$")||(t[n]=o);return t}function sD(e){if(typeof e!="string")return null;const t=/^\s*\{\{\s*([\s\S]*?)\s*\}\}\s*$/.exec(e);if(!t)return null;let n=t[1];const o=n.indexOf("??");return o>=0&&(n=n.slice(0,o)),n=n.replace(/\?\./g,".").replace(/\s+/g,""),n===""||!/^[A-Za-z_$][A-Za-z0-9_$]*(\.[A-Za-z_$][A-Za-z0-9_$]*)*$/.test(n)?null:n.split(".")}function aD(e,t){const n=sD(t);if(!n||n.length===0)return e;let o=e;for(let a=0;ao.map(r=>{if(!r||typeof r!="object")return r;const s=r;let a=s;if(typeof s.slot=="string"&&!t.has(s.slot)){const{slot:l,...d}=s;a={...d,__editorSlotName:l}}if(Array.isArray(a.children)){const l=n(a.children);l!==a.children&&(a={...a,children:l})}return a});return n(e)}function St(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xt(e){if(Array.isArray(e))return e.map(t=>Xt(t));if(St(e)){const t={};for(const[n,o]of Object.entries(e))t[n]=Xt(o);return t}return e}function xi(e,t){for(const[n,o]of Object.entries(t)){const r=e[n];St(o)&&St(r)?xi(r,o):e[n]=Xt(o)}}function cD(e){const t=[];let n="";for(let o=0;o0&&(t.push(n),n="");const s=e[o+1];if(s==="'"||s==='"'){const l=e.indexOf(`${s}]`,o+2);if(l!==-1){t.push(e.slice(o+2,l)),o=l+1;continue}}const a=e.indexOf("]",o+1);if(a!==-1){t.push(e.slice(o+1,a)),o=a;continue}n+=r}else r==="."?n.length>0&&(t.push(n),n=""):n+=r}return n.length>0&&t.push(n),t.filter(o=>o.length>0)}function Xa(e,t,n){const o=cD(t);if(o.length===0)return;let r=e;for(let s=0;s0?t:void 0}const Za="g7le:editor-t-ready",Ag="data-g7le-vh-expanded";function pD(e,t){if(!e||!t)return;const n=t;e.querySelectorAll("*").forEach(r=>{const s=window.getComputedStyle(r),a=parseFloat(s.height),l=Number.isFinite(a)&&Math.abs(a-n)<=2,d=parseFloat(s.minHeight),c=Number.isFinite(d)&&Math.abs(d-n)<=2,p=s.overflowY==="auto"||s.overflowY==="scroll"||s.overflowY==="hidden"||s.overflow==="auto"||s.overflow==="scroll"||s.overflow==="hidden";l&&p?(r.style.setProperty("height","auto","important"),c&&r.style.setProperty("min-height","0","important"),r.style.setProperty("overflow","visible","important"),r.setAttribute(Ag,"1")):(s.overflowY==="auto"||s.overflowY==="scroll")&&r.scrollHeight>r.clientHeight+4&&r.clientHeight>120&&(r.style.setProperty("overflow","visible","important"),r.style.setProperty("height","auto","important"),r.setAttribute(Ag,"1"))})}const fD=[];function gD(e={}){const{manifest:t=null,nesting:n=null,componentPalette:o=null,spec:r=null,permissionCandidates:s,sampleGlobalSources:a=fD,resolveRouteMatch:l,onNavigateToDestination:d,onSessionAddedPathsChange:c}=e,{state:p}=Qe(),f=Ft(),b=Dp(),{document:g,isLoading:m,error:h}=f??b,v=u.useRef(null),[y,_]=u.useState(null),{deviceWidth:w,scale:k,colorScheme:x}=Ka(),$=u.useMemo(()=>p.activeStateId?p.availableStates.find(ce=>ce.id===p.activeStateId)??null:null,[p.activeStateId,p.availableStates]),S=u.useMemo(()=>Ig($),[$]),C=W4({isEditMode:!0,editorSpec:r??void 0,sampleOverride:S}),{t:T}=tt(),{componentRegistry:E,translationEngine:A,isReady:N,error:D}=Y4(p.templateIdentifier,p.locale),B=u.useRef(null);B.current===null&&(B.current=new kd);const M=u.useRef(null);if(M.current===null){M.current=new y7({navigate:()=>{}}),M.current.setPreviewMode(!0);try{const q=window.__templateApp?.getActionDispatcher?.();if(q&&typeof q.getRegisteredHandlers=="function"){const re=q.getRegisteredHandlers();for(const ie of re){if(!ie.includes("."))continue;const me=typeof q.getHandler=="function"?q.getHandler(ie):void 0;typeof me=="function"&&M.current.registerHandler(ie,me,{category:"plugin",source:"preview-canvas-cloned-from-host"})}}}catch{}}u.useEffect(()=>{if(!N)return;const ce=M.current;if(ce)try{const q=window.G7Core?.getActionDispatcher?.();if(!q||typeof q.getRegisteredHandlers!="function")return;const re=q.getRegisteredHandlers();for(const ie of re){if(!ie.includes(".")||typeof ce.getHandler=="function"&&ce.getHandler(ie))continue;const me=typeof q.getHandler=="function"?q.getHandler(ie):void 0;typeof me=="function"&&ce.registerHandler(ie,me,{category:"plugin",source:"preview-canvas-iife-reclone"})}}catch{}},[N]);const O=u.useMemo(()=>new b7({sampleProvider:C,actionDispatcher:M.current}),[C]),z=u.useMemo(()=>g?.raw?.meta?.guest_only===!0,[g]),H=u.useMemo(()=>Ya({sources:a,isGuestOnly:z}),[a,z]),P=u.useMemo(()=>{const ce=hD(Ja($),A,{templateId:p.templateIdentifier,locale:p.locale}),q=H._local,{global:re,local:ie}=uD({globalBaseline:H,localBaseline:q??{},patch:$?.initialState??null,formErrors:ce});return{...re,_local:ie}},[H,$,A,p.templateIdentifier,p.locale]),I=u.useMemo(()=>!$||!(!!$.initialState?.local||!!Ja($))?null:{...P._local??{},_forceLocalInit:$.id,_merge:"deep"},[$,P]),L=ce=>typeof ce=="object"&&ce!==null&&!Array.isArray(ce),F=u.useMemo(()=>L($?.initialState?.query)?$.initialState.query:null,[$]),Y=u.useMemo(()=>L($?.initialState?.route)?$.initialState.route:null,[$]),[K,X]=u.useState(()=>Ya({sources:[],isGuestOnly:!1})),Z=u.useRef(null);u.useEffect(()=>{const ce={...P},q=R4({actionDispatcher:M.current,locale:p.locale,initialGlobalState:ce,onChange:ie=>{X(ie.globalState)}});Z.current=q;const re=window.__templateApp;return re?.setGlobalState&&M.current.setGlobalStateUpdater((ie,me)=>{re.setGlobalState(ie,me)}),X(ce),Tl({kind:"applyPatch",activeStateId:p.activeStateId,routePath:p.selectedRoute?.path??null,hasInitialPatch:!!$?.initialState,hasFormErrors:!!Ja($),hasSampleOverride:!!Ig($)}),()=>{q.restore(),Z.current=null}},[p.locale,P]),u.useEffect(()=>{if(!A)return;const ce=window.G7Core;if(!ce||typeof ce.t!="function")return;const q=ce.t,re=p.templateIdentifier,ie=p.locale;return ce.t=(me,Ce)=>{try{const $e=Ce?"|"+Object.entries(Ce).map(([ue,fe])=>`${ue}=${fe}`).join("|"):void 0,U=A.translate(me,{templateId:re,locale:ie},$e);if(U!==me&&!U.startsWith("$t:"))return U}catch{}return q(me,Ce)},typeof window<"u"&&window.dispatchEvent(new CustomEvent(Za)),()=>{window.G7Core?.t&&window.G7Core.t!==q&&(window.G7Core.t=q)}},[A,p.templateIdentifier,p.locale]);const se=u.useMemo(()=>{const ce=g?.raw?.components??[];return p.editMode!=="base"?ce:dD(ce)},[g,p.editMode]),oe=g?.raw?.__editability,G=g?.raw?.__extensionId,ee=u.useMemo(()=>p.editMode!=="extension"||oe!=="ok"?[]:typeof G!="number"?[]:yD(se,G),[p.editMode,oe,G,se]),[ge,V]=u.useState(null),[te,be]=u.useState(!1),Ee=g?.layoutName??null,De=u.useMemo(()=>{const ce=g?.raw?.scripts??[];return Array.isArray(ce)?ce.map(q=>q&&typeof q.src=="string"?q.src:"").join("|"):""},[g]);u.useEffect(()=>{be(!1)},[Ee,De]),u.useEffect(()=>{let ce=!1;const q=g?.raw?.scripts??[];if(!Array.isArray(q)||q.length===0){be(!0);return}const re=[];for(const ie of q){if(!ie?.src||typeof ie.src!="string")continue;if(!kg(ie.src,Ua())){console.warn(`[PreviewCanvas] Blocked untrusted script src (same-origin path or declared trusted host required): ${ie.src}`);continue}const me=ie.id?`script#${CSS.escape(ie.id)}, script[data-g7le-canvas-script="${ie.src}"]`:`script[data-g7le-canvas-script="${ie.src}"], script[src="${ie.src}"]`,Ce=window.document.querySelector(me);if(Ce){const $e=Ce.hasAttribute("data-g7le-canvas-script");if(Ce.hasAttribute("data-g7le-script-loaded")||!$e)continue;re.push(new Promise(ue=>{if(Ce.hasAttribute("data-g7le-script-loaded")){ue();return}Ce.addEventListener("load",()=>ue()),Ce.addEventListener("error",()=>ue())}));continue}re.push(new Promise($e=>{const U=window.document.createElement("script");U.src=ie.src,U.async=!1,ie.id&&(U.id=ie.id),U.setAttribute("data-g7le-canvas-script",ie.src);const ue=()=>{U.setAttribute("data-g7le-script-loaded","1"),$e()};U.addEventListener("load",ue),U.addEventListener("error",ue),window.document.head.appendChild(U)}))}if(re.length===0){be(!0);return}return Promise.all(re).then(()=>{ce||requestAnimationFrame(()=>{requestAnimationFrame(()=>{ce||be(!0)})})}),()=>{ce=!0}},[g]);const Se=u.useMemo(()=>g?.raw?.data_sources??[],[g]),Ue=u.useMemo(()=>g?.raw?.computed??{},[g]),[Me,Oe]=u.useState({}),Ye=u.useMemo(()=>{if(p.editMode!=="iteration_item")return Me;const ce=g?.iterationContext;if(!ce)return Me;const q=g?.raw?.components??[],re=Be({children:q},ce.sourceIndexPath),ie=re&&re.iteration&&typeof re.iteration.source=="string"?re.iteration.source:null;return ie?aD(Me,ie):Me},[p.editMode,Me,g]),[ze,Xe]=u.useState(0);u.useEffect(()=>{if(typeof window>"u")return;const ce=()=>Xe(q=>q+1);return window.addEventListener(kt,ce),()=>window.removeEventListener(kt,ce)},[]);const ve=u.useMemo(()=>tD(p.selectedRoute?.path??null),[p.selectedRoute?.path]);if(u.useEffect(()=>{let ce=!1;return(async()=>{if(Se.length===0){ce||Oe({});return}try{const q=await O.fetchDataSources(Se,ve,new URLSearchParams,void 0,void 0);ce||Oe(q)}catch{ce||Oe({})}})(),()=>{ce=!0}},[Se,O,ve]),u.useEffect(()=>{const ce=y;if(!ce||typeof window>"u")return;let q=0,re=0,ie=0;const me=()=>pD(ce,window.innerHeight);q=window.requestAnimationFrame(()=>{re=window.requestAnimationFrame(me)});let Ce=null;return typeof MutationObserver<"u"&&(Ce=new MutationObserver(()=>{ie||(ie=window.requestAnimationFrame(()=>{ie=0,me()}))}),Ce.observe(ce,{childList:!0,subtree:!0})),()=>{window.cancelAnimationFrame(q),window.cancelAnimationFrame(re),ie&&window.cancelAnimationFrame(ie),Ce&&Ce.disconnect()}},[y,se,te,w,Me]),u.useEffect(()=>{const ce=y;if(!ce||typeof window>"u"||p.editMode!=="extension"||oe!=="ok"||ee.length===0){V(null);return}let q=0,re=0;const ie=ue=>{if(!ue)return!1;const fe=ue.getBoundingClientRect();return fe.width>0&&fe.height>0},me=ue=>{const fe=ce.querySelector(`[data-editor-path="${ue}"]`);if(ie(fe))return!0;const xe=ce.querySelectorAll(`[data-editor-path^="${ue}.children."]`);for(const he of Array.from(xe))if(ie(he))return!0;return!1},Ce=()=>{V(ee.some(me))};q=window.requestAnimationFrame(()=>{re=window.requestAnimationFrame(Ce)});let $e=null,U=0;return typeof MutationObserver<"u"&&($e=new MutationObserver(()=>{U||(U=window.requestAnimationFrame(()=>{U=0,Ce()}))}),$e.observe(ce,{childList:!0,subtree:!0})),()=>{window.cancelAnimationFrame(q),window.cancelAnimationFrame(re),U&&window.cancelAnimationFrame(U),$e&&$e.disconnect()}},[y,p.editMode,oe,ee,te,Me]),u.useEffect(()=>{if(typeof window>"u"||p.editMode!=="base")return;const ce=window.document,q="g7le-base-slot-style";if(ce.getElementById(q))return;const re=ce.createElement("style");re.id=q;const ie=T("layout_editor.preview.slot_area_label");return re.textContent=`.g7le-preview-frame [data-editor-slot]{position:relative;min-height:96px;outline:2px dashed #94a3b8;outline-offset:-2px;}.g7le-preview-frame [data-editor-slot]::after{content:'${ie.replace(/'/g,"\\'")} · ' attr(data-editor-slot);position:absolute;top:8px;left:50%;transform:translateX(-50%);font-size:12px;line-height:1;color:#64748b;background:rgba(241,245,249,0.92);border:1px solid #cbd5e1;border-radius:9999px;padding:4px 12px;pointer-events:none;white-space:nowrap;}`,ce.head.appendChild(re),()=>{ce.getElementById(q)?.remove()}},[p.editMode,T]),!(p.editMode==="extension"||p.editMode==="iteration_item")&&(p.selectedRoute?.layoutName===null||p.selectedRoute===null))return i.jsx("div",{className:"g7le-preview-canvas g7le-preview-canvas--empty","data-testid":"g7le-preview-empty",style:er,children:T("layout_editor.preview.empty")});if(m)return i.jsx("div",{className:"g7le-preview-canvas g7le-preview-canvas--loading","data-testid":"g7le-preview-loading",style:er,children:T("layout_editor.preview.loading")});if(h)return i.jsx(qa,{error:h});if(D)return i.jsx(qa,{error:D});if(!N||E===null||A===null)return i.jsx("div",{className:"g7le-preview-canvas g7le-preview-canvas--assets-loading","data-testid":"g7le-preview-assets-loading",style:er,children:T("layout_editor.preview.assets_loading")});if(se.length===0)return i.jsx("div",{className:"g7le-preview-canvas g7le-preview-canvas--empty-layout","data-testid":"g7le-preview-empty-layout",style:er,children:T("layout_editor.preview.empty_layout")});const We=p.editMode==="extension"?oe==="no-injection"?"no-injection":oe==="ok"&&ee.length>0&&ge!==!0?"gated-no-state":null:null;return te?i.jsx("div",{className:"g7le-preview-canvas","data-testid":"g7le-preview-canvas",style:{overflow:"visible",background:"#f1f5f9",padding:24,display:"flex",justifyContent:"center",alignItems:"flex-start",minHeight:"calc(100vh - var(--g7le-header-h, 0px))",boxSizing:"border-box"},children:i.jsxs("div",{className:"g7le-preview-frame-wrapper","data-testid":"g7le-preview-frame-wrapper",style:{position:"relative",width:w,transform:`scale(${k})`,transformOrigin:"top center"},children:[i.jsx("div",{className:x==="dark"?"g7le-preview-frame g7le-preview-dark":"g7le-preview-frame","data-testid":"g7le-preview-frame","data-color-scheme":x,ref:ce=>{v.current=ce,_(ce)},style:{width:w,background:"#fff",border:"1px solid #cbd5e1",boxShadow:"0 1px 3px rgba(0,0,0,0.05)",minHeight:400,position:"relative",transform:"translateZ(0)",overflow:"hidden"},children:i.jsx(h7,{overrideWidth:w,children:se.map((ce,q)=>i.jsx(g7,{componentDef:ce,dataContext:{...Ye,...rD(K),_global:iD(K),_computedDefinitions:Ue,...I?{_localInit:I,_local:{...Me._local??{},...K._local??{}}}:{},route:bD({...Me.route??{},...ve,path:p.selectedRoute?.path??""},Y),query:{...Me.query??{},...F??{}}},translationContext:{templateId:p.templateIdentifier,locale:p.locale},registry:E,bindingEngine:B.current,translationEngine:Pt.getInstance(),actionDispatcher:M.current,isEditMode:!0,isRootRenderer:q===0,componentPath:`${q}`,onComponentSelect:(re,ie)=>{},onComponentHover:(re,ie)=>{}},`${ce.id??`preview-${q}`}:t${ze}${p.editMode==="extension"?`:s${te?1:0}`:""}`))})}),i.jsx("div",{className:"g7le-overlay-layer","data-testid":"g7le-overlay-layer",style:{position:"absolute",left:0,top:0,width:w,height:y?y.getBoundingClientRect().height/(k||1):"100%",overflow:"visible",pointerEvents:"none"},children:i.jsx(B4,{frameEl:y,manifest:t,nesting:n,componentPalette:o,spec:r,permissionCandidates:s,resolveRouteMatch:l,onNavigateToDestination:d,onSessionAddedPathsChange:c})}),We!==null&&i.jsx("div",{className:"g7le-preview-canvas--extension-fallback","data-testid":"g7le-preview-extension-fallback","data-fallback-reason":We,style:{position:"absolute",left:0,top:0,right:0,bottom:0,minHeight:y?y.getBoundingClientRect().height/(k||1):400,background:"#f1f5f9",display:"flex",alignItems:"flex-start",justifyContent:"center",padding:24,boxSizing:"border-box",pointerEvents:"auto",zIndex:50},children:i.jsxs("div",{className:"g7le-extension-fallback-card",style:{maxWidth:440,textAlign:"center",position:"sticky",top:"calc(40vh - var(--g7le-header-h, 0px))"},children:[i.jsx("p",{className:"g7le-extension-fallback-title",style:{fontWeight:600,marginBottom:8,color:"#0f172a"},children:T(We==="no-injection"?"layout_editor.preview.extension_no_injection_title":"layout_editor.preview.extension_gated_title")}),i.jsx("p",{className:"g7le-extension-fallback-desc",style:{color:"#475569",lineHeight:1.6},children:We==="no-injection"?T("layout_editor.preview.extension_no_injection_desc"):p.availableStates.length>1?T("layout_editor.preview.extension_gated_desc_with_states"):T("layout_editor.preview.extension_gated_desc")})]})})]})}):i.jsx("div",{className:"g7le-preview-canvas g7le-preview-canvas--scripts-loading","data-testid":"g7le-preview-scripts-loading",style:er,children:T("layout_editor.preview.loading")})}function hD(e,t,n){if(!e)return;if(!t)return e;const o=s=>{if(typeof s=="string"&&s.startsWith("$t:"))try{const a=s.slice(3),l=a.indexOf("|");if(l===-1)return t.translate(a,n);const d=a.slice(0,l),c=a.slice(l);return t.translate(d,n,c)}catch{return s}return Array.isArray(s)?s.map(o):s},r={};for(const[s,a]of Object.entries(e))r[s]=o(a);return r}function yD(e,t){const n=[],o=(r,s)=>{Array.isArray(r)&&r.forEach((a,l)=>{if(!a||typeof a!="object")return;const d=s?`${s}.children.${l}`:`${l}`,c=a.__source;if(c?.kind==="extension"&&c.extensionId===t){n.push(d);return}Array.isArray(a.children)&&o(a.children,d)})};return o(e,""),n}function bD(e,t){if(!t)return e;const n={...e};for(const[o,r]of Object.entries(t))r===null?delete n[o]:n[o]=r;return n}const er={flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"#f1f5f9",color:"#64748b",fontSize:13},mD={desktop:"layout_editor.device.desktop",tablet:"layout_editor.device.tablet",mobile:"layout_editor.device.mobile",portable:"layout_editor.device.portable"};function vD(){const{device:e,zoom:t,customWidth:n,setDevice:o,setZoom:r,setCustomWidth:s,colorScheme:a,setColorScheme:l}=Ka(),{t:d}=tt(),c=Rf();return i.jsxs("div",{className:"g7le-device-toolbar","data-testid":"g7le-device-toolbar",style:{display:"inline-flex",alignItems:"center",gap:8,padding:"4px 8px",background:"#fff",border:"1px solid #cbd5e1",borderRadius:6},children:[i.jsxs("div",{role:"group","aria-label":d("layout_editor.device.group_label"),children:[c.map(p=>{const f=e===p,b=mD[p],g=b?d(b):p;return i.jsx("button",{type:"button","data-testid":`g7le-device-${p}`,"aria-pressed":f,onClick:()=>o(p),style:{padding:"2px 8px",marginRight:2,fontSize:12,cursor:"pointer",background:f?"#0f172a":"#f8fafc",color:f?"#fff":"#0f172a",border:"1px solid #cbd5e1",borderRadius:4},children:g},p)}),(()=>{const p=e==="custom";return i.jsx("button",{type:"button","data-testid":"g7le-device-custom","aria-pressed":p,onClick:()=>o("custom"),style:{padding:"2px 8px",marginRight:2,fontSize:12,cursor:"pointer",background:p?"#0f172a":"#f8fafc",color:p?"#fff":"#0f172a",border:"1px solid #cbd5e1",borderRadius:4},children:d("layout_editor.device.custom")})})()]}),e==="custom"&&i.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[i.jsx("label",{htmlFor:"g7le-custom-width-input",style:{fontSize:11,color:"#475569"},children:d("layout_editor.device.custom_width_label")}),i.jsx("input",{id:"g7le-custom-width-input",type:"number",min:bg,max:mg,step:10,value:n,"data-testid":"g7le-custom-width-input","aria-label":d("layout_editor.device.custom_width_label"),onChange:p=>{const f=parseInt(p.currentTarget.value,10);Number.isFinite(f)&&s(f)},style:{width:72,padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:4}}),i.jsx("span",{style:{fontSize:11,color:"#475569"},children:"px"})]}),i.jsx("div",{role:"group","aria-label":d("layout_editor.toolbar.color_scheme_group"),style:{display:"inline-flex",gap:2},children:["light","dark"].map(p=>{const f=a===p;return i.jsx("button",{type:"button","data-testid":`g7le-toolbar-scheme-${p}`,"aria-pressed":f,onClick:()=>l(p),style:{padding:"2px 8px",fontSize:12,cursor:"pointer",background:f?"#0f172a":"#f8fafc",color:f?"#fff":"#0f172a",border:"1px solid #cbd5e1",borderRadius:4},children:d(p==="light"?"layout_editor.toolbar.color_scheme_light":"layout_editor.toolbar.color_scheme_dark")},p)})}),i.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[i.jsx("span",{style:{fontSize:11,color:"#475569"},children:d("layout_editor.zoom.label")}),i.jsx("input",{type:"range",min:.5,max:1,step:.05,value:t,"data-testid":"g7le-zoom-slider","aria-label":d("layout_editor.zoom.aria_label"),onChange:p=>r(parseFloat(p.currentTarget.value)),style:{width:100}}),i.jsxs("span",{style:{fontSize:11,color:"#475569",minWidth:36,textAlign:"right"},children:[Math.round(t*100),"%"]})]}),i.jsx(Jb,{})]})}function _D(){const{t:e}=tt(),{state:t,dispatch:n}=Qe(),{availableStates:o,activeStateId:r}=t,[,s]=u.useState(0);u.useEffect(()=>{if(typeof window>"u")return;const p=()=>s(b=>b+1),f=window.requestAnimationFrame(p);return window.addEventListener(Za,p),()=>{window.cancelAnimationFrame(f),window.removeEventListener(Za,p)}},[]);const a=u.useCallback((p,f)=>{if(!p)return f;if(!p.startsWith("$t:"))return p;const b=p.slice(3),g=window.G7Core;if(g&&typeof g.t=="function"){const h=g.t(b);if(h&&h!==b&&!h.startsWith("$t:"))return h}const m=e(b);return m&&m!==b?m:f},[e]);if(!Array.isArray(o)||o.length<=1)return null;const l=p=>{const f=p.target.value;n({type:"SET_ACTIVE_STATE",activeStateId:f}),Tl({kind:"change",activeStateId:f,routePath:t.selectedRoute?.path??null,availableCount:o.length})},d=o.find(p=>p.id===r)??o[0],c=d?.description?a(d.description,""):"";return i.jsxs("div",{className:"g7le-state-switcher","data-testid":"g7le-state-switcher","data-active-state":r??"",style:{display:"inline-flex",alignItems:"center",gap:6,padding:"4px 8px",background:"#fff",border:"1px solid #cbd5e1",borderRadius:6},children:[i.jsx("span",{style:{fontSize:12,fontWeight:600,color:"#475569",whiteSpace:"nowrap"},children:e("layout_editor.toolbar.state")}),i.jsx("select",{"data-testid":"g7le-state-switcher-select","aria-label":e("layout_editor.toolbar.state"),value:r??o[0].id,onChange:l,style:{fontSize:12,padding:"2px 6px",border:"1px solid #cbd5e1",borderRadius:4,background:"#fff",color:"#0f172a",cursor:"pointer",outline:"none"},children:o.map(p=>i.jsx("option",{value:p.id,children:a(p.label,p.id)},p.id))}),c&&i.jsx("span",{"data-testid":"g7le-state-switcher-description",style:{fontSize:11,color:"#94a3b8",whiteSpace:"nowrap"},children:c})]})}function xD(e,t,n){if(e==="extension"){if(typeof n=="string"&&n.length>0){const o=Qa(n,"__base__/");return o?{kind:"base",match:o}:{kind:"route",match:n}}return null}if(!t)return null;switch(e){case"route":return{kind:"route",match:t};case"base":{const o=Qa(t,"__base__/");return o?{kind:"base",match:o}:null}case"modal":{const o=Qa(t,"__modal__/");return o?{kind:"modal",match:o}:null}default:return null}}function wD(e,t){if(!t||!Array.isArray(e)||e.length===0)return[];const n=[];for(const o of e)if(SD(o.scope,t))for(const r of o.items??[])r&&typeof r.id=="string"&&r.id.length>0&&n.push(r);return n}function kD(e){if(e.length===0)return null;const t=e.find(n=>n.default===!0);return t?t.id:e[0].id}function SD(e,t){if(!e||e.kind!==t.kind)return!1;const n=e.match;return typeof n!="string"||n.length===0?!1:t.kind==="route"?CD(t.match,n):n===t.match}function CD(e,t){if(t===e)return!0;if(!t.includes("*"))return!1;const n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\/\*\\\?/g,"(?:/[^/]+)?").replace(/\*/g,"[^/]+");return new RegExp(`^${n}$`).test(e)}function Qa(e,t){return e.startsWith(t)?e.slice(t.length):""}const $D="__conngroup__/modals/",ED="__conngroup__/extensions/";function ID(e){return e.meta?.editor_label?{label:e.meta.editor_label,labelSource:"editor_label"}:e.meta?.title?{label:e.meta.title,labelSource:"title"}:{label:e.path,labelSource:"path"}}function AD(e){switch(e.source.kind){case"template":return"template";case"module":return`module:${e.source.identifier??""}`;case"plugin":return`plugin:${e.source.identifier??""}`;case"core":return null;default:return null}}function TD(e,t){if(e.meta?.parent&&t.has(e.meta.parent))return e.meta.parent;const n=e.path.split("/").filter(Boolean);for(let o=n.length-1;o>=1;o--){const r="/"+n.slice(0,o).join("/");if(r!==e.path&&t.has(r))return r}return null}function DD(e){const t=new Map;for(const n of e)n.layout&&t.set(n.layout,(t.get(n.layout)??0)+1);return t}function zD(e){const t=new Map;for(const n of e){if(!n.hostLayout)continue;const o=t.get(n.hostLayout)??[];o.push(n),t.set(n.hostLayout,o)}return t}function ND(e){const t=new Map;for(const n of e)for(const o of n.extensions)for(const r of o.hostLayouts??[]){if(!r)continue;const s=t.get(r)??[];s.push({extension:o,group:n}),t.set(r,s)}return t}function MD(e,t){return{path:`__modal__/${e.hostLayout}/${e.modalId}`,layoutName:e.hostLayout,label:e.label??e.modalId,labelSource:e.label?"editor_label":"path",source:{kind:"core",identifier:null},kind:"modal",modalId:e.modalId,modalHostLayout:e.hostLayout,connectedHostRoutePath:t,children:[]}}function LD(e,t){const{extension:n,group:o}=e,r=o.sourceType==="plugin"?"🔌":"🧩";return{path:`__extension__/${n.id}`,layoutName:null,label:`${r} ${o.sourceLabel} · ${n.targetName}`,labelSource:"path",source:{kind:o.sourceType,identifier:o.sourceIdentifier},kind:"extension",extensionId:String(n.id),extensionType:n.extensionType,extensionPriority:n.priority,extensionTargetName:n.targetName,isModified:n.isModified,isInactive:!n.isActive,connectedHostRoutePath:t,children:[]}}function Tg(e,t,n){if(e.kind!=="route"&&e.kind!=="base"||!e.layoutName)return;const o=[],r=t.get(e.layoutName)??[];r.length>0&&o.push({path:`${$D}${e.path}`,layoutName:null,label:`$t:layout_editor.chrome.route_tree.connected.modals|count=${r.length}`,labelSource:"editor_label",source:{kind:"core",identifier:null},kind:"route",children:r.map(a=>MD(a,e.path))});const s=n.get(e.layoutName)??[];s.length>0&&o.push({path:`${ED}${e.path}`,layoutName:null,label:`$t:layout_editor.chrome.route_tree.connected.extensions|count=${s.length}`,labelSource:"editor_label",source:{kind:"core",identifier:null},kind:"route",children:s.map(a=>LD(a,e.path))}),o.length>0&&(e.children=[...o,...e.children??[]])}function PD(e){const t=[],n=new Set(e.routes.map(o=>o.path));for(const o of e.routes){const r=AD(o);if(!r)continue;const{label:s,labelSource:a}=ID(o),l=TD(o,n),d={path:o.path,layoutName:o.layout??null,label:s,labelSource:a,icon:o.meta?.icon??null,source:o.source,isRedirect:!!o.redirect,isHidden:!!o.meta?.hidden,kind:"route",children:[]};t.push({node:d,parentKey:l,groupKey:r})}return t}function OD(e,t){if(e==="template")return"$t:layout_editor.chrome.route_tree.group.template";if(e.startsWith("module:")){const n=e.slice(7);return`$t:layout_editor.chrome.route_tree.group.module|name=${t.moduleDisplayNames[n]??n}`}if(e.startsWith("plugin:")){const n=e.slice(7);return`$t:layout_editor.chrome.route_tree.group.plugin|name=${t.pluginDisplayNames[n]??n}`}return e}function BD(e,t){DD(e.routes);const n=zD(e.modals),o=ND(e.extensionGroups??[]),r=new Map;for(const d of t)r.has(d.groupKey)||r.set(d.groupKey,[]),r.get(d.groupKey).push(d);const s=Array.from(r.keys()).sort((d,c)=>{const p=g=>g==="template"?1:g.startsWith("module:")?2:g.startsWith("plugin:")?3:4,f=p(d),b=p(c);return f!==b?f-b:d.localeCompare(c)}),a=[];if(e.baseLayouts.length>0){const d=e.baseLayouts.map(c=>({path:`__base__/${c.layoutName}`,layoutName:c.layoutName,label:c.label??c.layoutName,labelSource:c.label?"editor_label":"path",source:{kind:"core",identifier:null},kind:"base",children:[]}));for(const c of d)Tg(c,n,o);a.push({path:"__group__/base",layoutName:null,label:"$t:layout_editor.chrome.route_tree.group.base",labelSource:"editor_label",source:{kind:"core",identifier:null},kind:"route",children:d})}for(const d of s){const c=r.get(d),p=new Map;for(const b of c)p.set(b.node.path,b);const f=[];for(const b of c)if(b.parentKey&&p.has(b.parentKey)){const g=p.get(b.parentKey);g.node.children=g.node.children??[],g.node.children.push(b.node)}else f.push(b.node);for(const b of c)Tg(b.node,n,o);a.push({path:`__group__/${d}`,layoutName:null,label:OD(d,e),labelSource:"editor_label",source:{kind:"core",identifier:null},kind:"route",children:f})}if(e.modals.length>0){const d=e.modals.map(c=>({path:`__modal__/${c.hostLayout}/${c.modalId}`,layoutName:c.hostLayout,label:c.label??c.modalId,labelSource:c.label?"editor_label":"path",source:{kind:"core",identifier:null},kind:"modal",modalId:c.modalId,modalHostLayout:c.hostLayout,children:[]}));a.push({path:"__group__/modal",layoutName:null,label:"$t:layout_editor.chrome.route_tree.group.modal",labelSource:"editor_label",source:{kind:"core",identifier:null},kind:"route",children:d})}const l=e.extensionGroups??[];if(l.length>0){const d=l.map(c=>{const p=c.sourceType==="plugin"?"🔌":"🧩",f=c.extensions.map(b=>({path:`__extension__/${b.id}`,layoutName:null,label:`${c.sourceLabel} · ${b.targetName}`,labelSource:"path",source:{kind:c.sourceType,identifier:c.sourceIdentifier},kind:"extension",extensionId:String(b.id),extensionType:b.extensionType,extensionPriority:b.priority,extensionTargetName:b.targetName,isModified:b.isModified,isInactive:!b.isActive,children:[]}));return{path:`__extgroup__/${c.sourceType}/${c.sourceIdentifier}`,layoutName:null,label:`${p} ${c.sourceLabel}`,labelSource:"path",source:{kind:c.sourceType,identifier:c.sourceIdentifier},kind:"route",children:f}});a.push({path:"__group__/extension",layoutName:null,label:"$t:layout_editor.chrome.route_tree.group.extension",labelSource:"editor_label",source:{kind:"core",identifier:null},kind:"route",children:d})}return a}function WD(e){const t=PD(e);return BD(e,t)}const On=mo("useEditorRoutes");function jD(e,t){if(typeof e=="string")return e.length>0?e:null;if(e&&typeof e=="object"){const n=e[t];if(typeof n=="string"&&n.length>0)return n;if(typeof e.en=="string"&&e.en.length>0)return e.en;for(const o of Object.values(e))if(typeof o=="string"&&o.length>0)return o}return null}function Dg(e,t){const n={};if(typeof window>"u")return n;const r=window.G7Config?.[e];if(!Array.isArray(r))return n;for(const s of r)s&&typeof s.identifier=="string"&&(n[s.identifier]=jD(s.display_name,t)??s.identifier);return n}function HD(e){const t=new kd,n=typeof window<"u"?window.G7Config:void 0,o={_global:{settings:n?.settings??{},plugins:n?.plugins??{},modules:n?.modules??{},appConfig:n?.appConfig??{}}};return e.map(r=>{const s={...r};if(typeof s.path=="string"&&s.path.includes("{{")){const a=s.path;let l=t.resolveBindings(s.path,o);l=l.replace(/\/\/+/g,"/")||"/",l.includes("{{")&&(On.warn("편집기 route path 표현식 평가 실패 — fallback 적용",{originalPath:a}),l=a.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/"),s.path=l}if(typeof s.redirect=="string"&&s.redirect.includes("{{")){const a=s.redirect;let l=t.resolveBindings(a,o);l=l.replace(/\/\/+/g,"/")||"/",l.includes("{{")&&(On.warn("편집기 route redirect 표현식 평가 실패 — fallback 적용",{originalRedirect:a}),l=a.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/"),s.redirect=l}return s})}function FD(e){const{dispatch:t}=Qe(),{translationEngine:n,translationContext:o}=tt(),{templateIdentifier:r,cacheVersion:s}=e;u.useEffect(()=>{let a=!1;const l=s??(typeof window<"u"?window.G7Config?.cache_version:void 0)??"",d=l!==""?`?v=${encodeURIComponent(String(l))}`:"",c=en(`/api/admin/templates/${encodeURIComponent(r)}/editor/routes`,"json",null,d.replace(/^[?&]+/,"")),p=o?.locale??"ko",f=n&&r!==o?.templateId?n.loadTranslations(r,p).then(()=>{On.log("편집 대상 lang 로드 완료",{targetTemplate:r,locale:p})}).catch(h=>{On.warn("편집 대상 lang 로드 실패 — 라우트 라벨 fallback 사용",h)}):Promise.resolve(),b=(()=>{if(typeof fetch!="function")return Promise.reject(so(new Error("fetch unavailable"),"routes"));try{const h=fetch(c,{credentials:"same-origin",headers:Ne()});return!h||typeof h.then!="function"?Promise.reject(so(new Error("fetch returned non-Promise (test stub?)"),"routes")):h.then(async v=>{if(!v.ok){const y=await v.json().catch(()=>null);throw Jr(v.status,y,"routes")}return v.json()})}catch(h){return Promise.reject(h)}})(),g=`/api/admin/templates/${encodeURIComponent(r)}/layout-extensions${d}`,m=(()=>{if(typeof fetch!="function")return Promise.resolve(null);try{const h=fetch(g,{credentials:"same-origin",headers:Ne()});return!h||typeof h.then!="function"?Promise.resolve(null):h.then(async v=>v.ok?await v.json():null).catch(()=>null)}catch{return Promise.resolve(null)}})();return Promise.all([b,f,m]).then(([h,,v])=>{if(a)return;if(!h||!h.success||!Array.isArray(h.data?.routes)){On.warn("routes 응답 형식이 비정상 — empty tree 로 둠",h),t({type:"SET_ROUTES_ERROR",error:{kind:"unknown",status:200,message:"routes 응답 형식이 비정상입니다.",source:"routes"}});return}const y=HD(h.data.routes),_=Dg("activeModules",p),w=Dg("activePlugins",p),k=(h.data.base_layouts??[]).map(A=>({layoutName:A.layout_name,label:A.label??void 0})),x=(h.data.modals??[]).map(A=>({modalId:A.modal_id,hostLayout:A.host_layout,label:A.label??void 0})),$=(v?.success&&Array.isArray(v.data)?v.data:[]).map(A=>({sourceIdentifier:A.source_identifier,sourceType:A.source_type,sourceLabel:A.source_label,extensions:(A.extensions??[]).map(N=>({id:N.id,extensionType:N.extension_type,targetName:N.target_name,priority:N.priority,isActive:N.is_active,isModified:N.is_modified,hostLayouts:Array.isArray(N.host_layouts)?N.host_layouts:[],currentVersion:typeof N.current_version=="number"?N.current_version:void 0}))})),S=WD({routes:y,modals:x,baseLayouts:k,extensionGroups:$,moduleDisplayNames:_,pluginDisplayNames:w});t({type:"SET_ROUTE_TREE",tree:S});const C=h.data.layout_versions,T={};if(C&&typeof C=="object"&&!Array.isArray(C))for(const[A,N]of Object.entries(C))typeof N=="number"&&Number.isFinite(N)&&(T[A]=N);t({type:"SET_LAYOUT_VERSIONS",versions:T});const E={};for(const A of $)for(const N of A.extensions){const D=N.currentVersion;typeof D=="number"&&Number.isFinite(D)&&(E[String(N.id)]=D)}t({type:"SET_EXTENSION_VERSIONS",versions:E}),On.log("routes 로드 완료",{count:y.length,groups:S.length})}).catch(h=>{if(a)return;On.error("routes 로드 실패",h);const v=xp(h)?h:so(h,"routes");t({type:"SET_ROUTES_ERROR",error:v})}),()=>{a=!0}},[r,s,t,n,o?.locale,o?.templateId])}function zg(e,t,n,o=[]){const r=t?Ng(o,t):null,s=r!==null?{path:r.path,layoutName:r.layoutName}:void 0;if(e.startsWith("__base__/")){const a=e.slice(9);if(a)return n({type:"ENTER_BASE_EDIT",layoutName:a,returnRoute:s}),!0}else if(e.startsWith("__modal__/")){const a=e.slice(10);return a&&!a.includes("/")&&t?(n({type:"ENTER_MODAL_EDIT",modalId:a,hostLayout:t,returnRoute:s}),!0):!1}else if(e.startsWith("__extension__/")){const a=e.slice(14);if(a&&!a.includes("/"))return n({type:"ENTER_EXTENSION_EDIT",extensionId:a,returnRoute:s}),!0}else if(e.startsWith("__iteration__/")){const a=e.slice(14);return a&&t?(n({type:"ENTER_ITERATION_ITEM_EDIT",sourcePath:a,hostLayout:t,returnRoute:s}),!0):!1}return!1}function Ng(e,t){for(const n of e){if(n.kind==="route"&&n.layoutName===t)return n;if(n.children&&n.children.length>0){const o=Ng(n.children,t);if(o)return o}}return null}function Ra(e,t){for(const n of e){if(n.kind==="route"&&n.path===t)return n;if(n.children&&n.children.length>0){const o=Ra(n.children,t);if(o)return o}}return null}function KD(e){const{state:t,dispatch:n}=Qe(),o=u.useRef(!1),r=u.useRef(t.editMode);r.current=t.editMode,u.useEffect(()=>{if(o.current||t.routeTree.length===0||typeof window>"u")return;const a=fp(window.location.search);if(a){const c=pp(window.location.search),p=zg(a,c,n,t.routeTree);if(o.current=!0,p)return}const l=up(window.location.search);if(!l){o.current=!0;return}const d=Ra(t.routeTree,l);d&&n({type:"SELECT_ROUTE",route:{path:d.path,layoutName:d.layoutName}}),o.current=!0},[t.routeTree,n]),u.useEffect(()=>{if(typeof window>"u")return;const a=()=>{const l=fp(window.location.search);if(l){const p=pp(window.location.search);if(zg(l,p,n,t.routeTree))return}if(r.current!=="route")switch(r.current){case"base":n({type:"EXIT_BASE_EDIT"});return;case"modal":n({type:"EXIT_MODAL_EDIT"});return;case"extension":n({type:"EXIT_EXTENSION_EDIT"});return;case"iteration_item":n({type:"EXIT_ITERATION_ITEM_EDIT"});return}const d=up(window.location.search);if(!d){n({type:"SELECT_ROUTE",route:null});return}const c=Ra(t.routeTree,d);c&&n({type:"SELECT_ROUTE",route:{path:c.path,layoutName:c.layoutName}})};return window.addEventListener("popstate",a),()=>{window.removeEventListener("popstate",a)}},[t.routeTree,n]);const s=u.useRef("route");u.useEffect(()=>{if(typeof window>"u"||!window.history?.replaceState||t.routeTree.length===0)return;const a=ea(e,t.selectedRoute?.path??null,t.selectedRoute?.layoutName??null),l=`${window.location.pathname}${window.location.search}`,d=s.current;if(s.current=t.editMode,l===a)return;d==="route"&&t.editMode!=="route"&&window.history.pushState?window.history.pushState(window.history.state,"",a):window.history.replaceState(window.history.state,"",a)},[t.selectedRoute,t.editMode,t.routeTree,e])}function VD(){u.useEffect(()=>{if(typeof document>"u")return;const e=document.documentElement;let t=e.classList.contains("dark");const n=()=>{e.classList.contains("dark")&&(t=!0,e.classList.remove("dark"))};n();let o=null;return typeof MutationObserver<"u"&&(o=new MutationObserver(n),o.observe(e,{attributes:!0,attributeFilter:["class"]})),()=>{o?.disconnect(),t&&e.classList.add("dark")}},[])}function UD(){u.useEffect(()=>{if(typeof document>"u"||!document.body)return;const e=document.body,t=()=>{e.style.overflow==="hidden"&&(e.style.overflow=""),e.style.overflowY==="hidden"&&(e.style.overflowY="")};t();let n=null;return typeof MutationObserver<"u"&&(n=new MutationObserver(t),n.observe(e,{attributes:!0,attributeFilter:["style"]})),()=>{n?.disconnect()}},[])}function qD(e){if(typeof e!="string")return null;const t="__extension__/";if(!e.startsWith(t))return null;const n=e.slice(t.length);return n===""||n.includes("/")?null:n}function GD(e){if(Array.isArray(e.components))return e.components;if(Array.isArray(e.injections)){const t=[];return e.injections.forEach((n,o)=>{if(n&&Array.isArray(n.components))for(const r of n.components)t.push({...r,__injectionIndex:o})}),t}return[]}function YD(e,t){if(Array.isArray(e.components)){const n=t.map(o=>el(o));return{...e,components:n}}if(Array.isArray(e.injections)){const n=e.injections.map(o=>({...o}));n.forEach(o=>{Array.isArray(o.components)&&(o.components=[])});for(const o of t){const r=o.__injectionIndex,s=typeof r=="number"&&r>=0&&rel(n))),t}function Mg(e,t){const n=[],o=r=>{if(Array.isArray(r))for(const s of r){if(!s||typeof s!="object")continue;const a=s.__source;if(a?.kind==="extension"&&a.extensionId===t){n.push(s);continue}Array.isArray(s.children)&&o(s.children)}};return o(e),n}function Lg(e,t){const o=Mg(e,t)[0]?.__source;return o&&o.kind==="extension"&&o.extensionId===t?o:{kind:"extension",extensionId:t}}function tl(e,t){for(const n of e){const o=n?.__source;if(o?.kind==="extension"&&o.extensionId===t||Array.isArray(n.children)&&tl(n.children,t))return!0}return!1}function XD(){const{state:e}=Qe(),t=e.templateIdentifier,n=e.editMode==="extension"?qD(e.selectedRoute?.path):null,o=e.editMode==="extension"&&typeof e.selectedRoute?.layoutName=="string"?e.selectedRoute.layoutName:null,[r,s]=u.useState(null),[a,l]=u.useState(!1),[d,c]=u.useState(null),[p,f]=u.useState(!1),[b,g]=u.useState(0),[m,h]=u.useState(null),v=u.useRef({}),y=u.useRef({kind:"extension",extensionId:0}),_=u.useRef(null);u.useEffect(()=>{_.current=r},[r]),u.useEffect(()=>{h(null)},[n]);const w=u.useCallback(async A=>{const N=window.G7Config?.cache_version??0,D=en(`/api/layouts/${encodeURIComponent(t)}/${A}`,"json",`${N}.${Tp()}`,"with_source_meta=1"),B=cr(),M={Accept:"application/json"};B&&(M.Authorization=`Bearer ${B}`);const O=await fetch(D,{headers:M,credentials:"same-origin"});if(!O.ok)return null;const z=await O.json().catch(()=>null);return(z&&(z.data||z))??{}},[t]),k=u.useCallback(async()=>{if(!n){s(null),c(null),f(!1);return}l(!0),c(null);try{const A=window.G7Config?.cache_version??0,N=`/api/admin/templates/${encodeURIComponent(t)}/layout-extensions/${encodeURIComponent(n)}?v=${A}`,D=await fetch(N,{headers:Ne(),credentials:"same-origin"}),B=await D.json().catch(()=>null);if(!D.ok){c(Jr(D.status,B,"layout")),s(null),f(!1);return}const M=(B&&(B.data||B))??{};let O={};const z=M.content;if(typeof z=="string")try{O=JSON.parse(z)}catch{O={}}else z&&typeof z=="object"&&(O=z);const H=M.extension_type==="overlay"?"overlay":"extension_point",P=typeof M.lock_version=="number"?M.lock_version:0,I=Array.isArray(M?.host_layouts)?M.host_layouts.filter(oe=>typeof oe=="string"):[],L=o??(I.length===1?I[0]:m&&I.includes(m)?m:null),F=Number(n);v.current=O;let K=GD(O),X={},Z="pending";const se={kind:"extension",extensionId:F};if(y.current=se,L){const oe=await w(L);if(oe){X=oe;const G=Array.isArray(oe.components)?oe.components:[],ee=Lg(G,F);if(y.current=ee,tl(G,F))K=G,Z="ok";else{const V=(Array.isArray(oe.modals)?oe.modals:[]).filter(te=>te&&typeof te=="object"&&tl([te],F));if(V.length>0){const te=V.map(be=>({...be,props:{...be.props??{},isOpen:!0}}));K=[...G,...te],y.current=Lg(V,F),Z="ok"}else K=G,Z="no-injection"}}}s({extensionId:F,content:O,extensionType:H,components:K,lockVersion:P,hostLayouts:I,hostLayoutName:L,hostRaw:X,editability:Z}),f(!1),st({op:"load",layoutName:`extension:${n}`,editMode:"extension",statusCode:D.status,timestamp:Date.now()})}catch(A){c(so(A,"layout")),s(null),f(!1)}finally{l(!1)}},[t,n,m,o,w]);u.useEffect(()=>{k()},[k]);const x=u.useCallback(A=>{h(A)},[]),$=u.useCallback(A=>{s(N=>N&&{...N,components:A}),f(!0),st({op:"patch",layoutName:`extension:${_.current?.extensionId??""}`,editMode:"extension",isDirty:!0,timestamp:Date.now()})},[]),S=u.useCallback(A=>{s(N=>N&&{...N,components:A(N.components)}),f(!0)},[]),C=u.useCallback(async()=>{const A=_.current;if(!A)return{kind:"guard_no_document"};const N=`/api/admin/templates/${encodeURIComponent(t)}/layout-extensions/${A.extensionId}`,D=Mg(A.components,A.extensionId),B=D.length>0?D:A.components,M=YD(v.current,B);st({op:"save",layoutName:`extension:${A.extensionId}`,editMode:"extension",saveTarget:"layout_extension",endpoint:N,isDirty:p,timestamp:Date.now()});let O;try{O=await fetch(N,{method:"PUT",headers:Ne({"Content-Type":"application/json"}),credentials:"same-origin",body:JSON.stringify({content:M,expected_lock_version:A.lockVersion})})}catch(H){return{kind:"network_error",message:H instanceof Error?H.message:"network error"}}const z=await O.json().catch(()=>null);if(st({op:"save_response",layoutName:`extension:${A.extensionId}`,editMode:"extension",endpoint:N,statusCode:O.status,conflict:O.status===409?{currentVersion:z?.errors?.current_version??z?.current_version,yourVersion:z?.errors?.your_version??z?.your_version}:void 0,timestamp:Date.now()}),O.ok){const H=z?.data??{},P=typeof H.lock_version=="number"?H.lock_version:A.lockVersion+1;s(L=>L&&{...L,lockVersion:P}),f(!1),g(L=>L+1);const I=typeof H.current_version=="number"?H.current_version:void 0;return{kind:"success",newLockVersion:P,newContentVersion:I,savedExtensionId:String(A.extensionId)}}return O.status===409?{kind:"concurrent_modification",currentVersion:z?.current_version??-1,yourVersion:z?.your_version??A.lockVersion}:O.status===422?{kind:"validation_failed",status:422,errors:z?.errors??null}:{kind:"network_error",message:z?.message??`HTTP ${O.status}`}},[t,p]),T=u.useCallback(async()=>{ia(),await k()},[k]),E=!!r&&r.hostLayouts.length>1&&r.hostLayoutName===null;return{document:r,isLoading:a,error:d,isDirty:p,saveSuccessCounter:b,setLayoutComponents:$,patchLayout:S,save:C,reload:T,needsHostPicker:E,selectHost:x}}const Pg=new Set;function JD(e,t,n){const r=e&&Object.keys(e).length>0?e:t,s=Array.isArray(r.data_sources)?r.data_sources:[],a=Array.isArray(t.data_sources)?t.data_sources:[],l=new Set,d=[];for(const c of[...s,...a]){const p=c&&typeof c=="object"?c.id:void 0,f=typeof p=="string"?p:`__anon_${d.length}`;l.has(f)||(l.add(f),d.push(c))}return{...r,components:n,...d.length>0?{data_sources:d}:{},lock_version:void 0}}function ZD(e){return{document:e.document?{layoutName:`extension:${e.document.extensionId}`,raw:{...JD(e.document.hostRaw,e.document.content,e.document.components),__editability:e.document.editability,__extensionId:e.document.extensionId},lockVersion:e.document.lockVersion}:null,isLoading:e.isLoading,error:e.error,isDirty:e.isDirty,saveSuccessCounter:e.saveSuccessCounter,reload:e.reload,patchLayout:e.patchLayout,setLayoutComponents:e.setLayoutComponents,patchDocumentRaw:()=>{},dirtyKeys:Pg,dirtyLayoutNames:Pg,invalidateCurrentCache:()=>{},reloadCounter:0,save:()=>e.save(),markDirty:()=>{}}}function QD({hostLayouts:e,extensionLabel:t,onSelect:n}){const{t:o}=tt();return i.jsx("div",{className:"g7le-host-picker__backdrop","data-testid":"g7le-host-picker",role:"dialog","aria-modal":"true","aria-label":o("layout_editor.host_picker.title"),style:{position:"fixed",inset:0,zIndex:9500,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(15, 23, 42, 0.55)"},children:i.jsxs("div",{className:"g7le-host-picker__panel",style:{width:"min(520px, 92vw)",maxHeight:"80vh",overflow:"auto",background:"#ffffff",color:"#0f172a",borderRadius:12,boxShadow:"0 20px 48px rgba(15, 23, 42, 0.28)",padding:"20px 22px"},children:[i.jsx("h2",{className:"g7le-host-picker__title",style:{margin:"0 0 6px",fontSize:16,fontWeight:700},children:o("layout_editor.host_picker.title")}),i.jsx("p",{className:"g7le-host-picker__desc",style:{margin:"0 0 16px",fontSize:13,color:"#475569",lineHeight:1.6},children:t?o("layout_editor.host_picker.description_with_label",{label:t}):o("layout_editor.host_picker.description")}),i.jsx("ul",{className:"g7le-host-picker__list",style:{listStyle:"none",margin:0,padding:0,display:"grid",gap:8},children:e.map(r=>i.jsx("li",{children:i.jsxs("button",{type:"button",className:"g7le-host-picker__item","data-testid":"g7le-host-picker-item","data-host":r,onClick:()=>n(r),style:{width:"100%",textAlign:"left",padding:"12px 14px",border:"1px solid #e2e8f0",borderRadius:8,background:"#f8fafc",cursor:"pointer",fontSize:13,fontWeight:600,color:"#0f172a",display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{"aria-hidden":!0,style:{fontSize:14},children:"🖼"}),i.jsx("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:r}),i.jsx("span",{"aria-hidden":!0,style:{color:"#94a3b8"},children:"→"})]})},r))})]})})}function RD(e,t){const[n,o]=u.useState(!1),[r,s]=u.useState(null),a=u.useCallback(async l=>{if(!t||!l)return{kind:"no_document"};o(!0),s(null);try{const d=_o(l),c=`/api/admin/templates/${encodeURIComponent(e)}/layouts/${t}/preview`,p=await fetch(c,{method:"POST",credentials:"same-origin",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({content:JSON.stringify(d)})}),f=await p.json().catch(()=>null);if(!p.ok){const h=f?.message??`HTTP ${p.status}`;return s(h),{kind:"network_error",message:h}}const b=f?.data,g=typeof b?.token=="string"?b.token:"",m=typeof b?.preview_url=="string"&&b.preview_url?b.preview_url:g?`/preview/${g}`:"";return m?(window.G7Core?.dispatch?.({handler:"openWindow",params:{path:m}}),{kind:"success",previewUrl:m,token:g}):(s("invalid preview response"),{kind:"network_error",message:"invalid preview response"})}catch(d){const c=d instanceof Error?d.message:"network error";return s(c),{kind:"network_error",message:c}}finally{o(!1)}},[e,t]);return{isCreating:n,error:r,createPreview:a}}const de="layout_editor.action_recipe",bn={setState:{label:`$t:${de}.set_state.label`,params:[{key:"target",label:`$t:${de}.set_state.param_target`,widget:"select",options:[{value:"local"},{value:"global"}]},{key:"state",label:`$t:${de}.set_state.param_state`,widget:"state-key-value"},{key:"merge",label:`$t:${de}.set_state.param_merge`,widget:"toggle"}],build:{handler:"setState",params:{target:"{{target}}",merge:"{{merge}}","...":"{{state}}"}}},loadFromLocalStorage:{label:`$t:${de}.load_local.label`,params:[{key:"key",label:`$t:${de}.load_local.param_key`,widget:"text",required:!0},{key:"stateKey",label:`$t:${de}.load_local.param_state_key`,widget:"state-key-picker"},{key:"defaultValue",label:`$t:${de}.load_local.param_default`,widget:"text"}],build:{handler:"loadFromLocalStorage",params:{key:"{{key}}",stateKey:"{{stateKey}}",defaultValue:"{{defaultValue}}"}}},saveToLocalStorage:{label:`$t:${de}.save_local.label`,params:[{key:"key",label:`$t:${de}.save_local.param_key`,widget:"text",required:!0},{key:"value",label:`$t:${de}.save_local.param_value`,widget:"data-chip"}],build:{handler:"saveToLocalStorage",params:{key:"{{key}}",value:"{{value}}"}}},navigate:{label:`$t:${de}.navigate.label`,params:[{key:"path",label:`$t:${de}.navigate.param_path`,widget:"page-picker",required:!0},{key:"query",label:`$t:${de}.navigate.param_query`,widget:"key-value"},{key:"mergeQuery",label:`$t:${de}.navigate.param_merge_query`,widget:"toggle"},{key:"scroll",label:`$t:${de}.navigate.param_scroll`,widget:"select",options:[{value:"top"},{value:"preserve"},{value:"none"}]},{key:"replace",label:`$t:${de}.navigate.param_replace`,widget:"toggle"},{key:"transition_overlay_target",label:`$t:${de}.navigate.param_overlay_target`,widget:"component-target-picker",dependsOn:{param:"replace",equals:!0}}],build:{handler:"navigate",params:{path:"{{path}}",query:"{{query}}",mergeQuery:"{{mergeQuery}}",scroll:"{{scroll}}",replace:"{{replace}}",transition_overlay_target:"{{transition_overlay_target}}"}}},openWindow:{label:`$t:${de}.open_window.label`,params:[{key:"target",label:`$t:${de}.open_window.param_target`,widget:"page-picker",required:!0},{key:"windowTarget",label:`$t:${de}.open_window.param_window_target`,widget:"select",options:[{value:"_blank"},{value:"_self"}]}],build:{handler:"openWindow",target:"{{target}}",params:{windowTarget:"{{windowTarget}}"}}},navigateBack:{label:`$t:${de}.navigate_back.label`,params:[],build:{handler:"navigateBack"}},navigateForward:{label:`$t:${de}.navigate_forward.label`,params:[],build:{handler:"navigateForward"}},replaceUrl:{label:`$t:${de}.replace_url.label`,params:[{key:"path",label:`$t:${de}.replace_url.param_path`,widget:"page-picker"},{key:"query",label:`$t:${de}.replace_url.param_query`,widget:"key-value"}],build:{handler:"replaceUrl",params:{path:"{{path}}",query:"{{query}}"}}},toast:{label:`$t:${de}.toast.label`,params:[{key:"message",label:`$t:${de}.toast.param_message`,widget:"i18n-text",required:!0},{key:"type",label:`$t:${de}.toast.param_type`,widget:"select",options:[{value:"info"},{value:"success"},{value:"warning"},{value:"error"}]},{key:"duration",label:`$t:${de}.toast.param_duration`,widget:"number"},{key:"icon",label:`$t:${de}.toast.param_icon`,widget:"text"}],build:{handler:"toast",params:{message:"{{message}}",type:"{{type}}",duration:"{{duration}}",icon:"{{icon}}"}}},openModal:{label:`$t:${de}.open_modal.label`,params:[{key:"target",label:`$t:${de}.open_modal.param_target`,widget:"modal-picker",required:!0}],build:{handler:"openModal",target:"{{target}}"}},closeModal:{label:`$t:${de}.close_modal.label`,params:[],build:{handler:"closeModal"}},showAlert:{label:`$t:${de}.show_alert.label`,params:[{key:"target",label:`$t:${de}.show_alert.param_message`,widget:"i18n-text",required:!0}],build:{handler:"showAlert",target:"{{target}}"}},setError:{label:`$t:${de}.set_error.label`,params:[{key:"target",label:`$t:${de}.set_error.param_message`,widget:"i18n-text"},{key:"stateTarget",label:`$t:${de}.set_error.param_state_target`,widget:"select",options:[{value:"local"},{value:"global"}]}],build:{handler:"setError",target:"{{target}}",params:{stateTarget:"{{stateTarget}}"}}},refetchDataSource:{label:`$t:${de}.refetch.label`,params:[{key:"dataSourceId",label:`$t:${de}.refetch.param_data_source`,widget:"datasource-picker",required:!0},{key:"sync",label:`$t:${de}.refetch.param_sync`,widget:"toggle"}],build:{handler:"refetchDataSource",params:{dataSourceId:"{{dataSourceId}}",sync:"{{sync}}"}}},appendDataSource:{label:`$t:${de}.append_data.label`,params:[{key:"dataSourceId",label:`$t:${de}.append_data.param_data_source`,widget:"datasource-picker",required:!0},{key:"dataPath",label:`$t:${de}.append_data.param_data_path`,widget:"text"},{key:"newData",label:`$t:${de}.append_data.param_new_data`,widget:"data-chip"}],build:{handler:"appendDataSource",params:{dataSourceId:"{{dataSourceId}}",dataPath:"{{dataPath}}",newData:"{{newData}}"}}},updateDataSource:{label:`$t:${de}.update_data.label`,params:[{key:"dataSourceId",label:`$t:${de}.update_data.param_data_source`,widget:"datasource-picker",required:!0},{key:"data",label:`$t:${de}.update_data.param_data`,widget:"data-chip"},{key:"merge",label:`$t:${de}.update_data.param_merge`,widget:"toggle"}],build:{handler:"updateDataSource",params:{dataSourceId:"{{dataSourceId}}",data:"{{data}}",merge:"{{merge}}"}}},scrollIntoView:{label:`$t:${de}.scroll.label`,params:[{key:"selector",label:`$t:${de}.scroll.param_selector`,widget:"text",required:!0},{key:"behavior",label:`$t:${de}.scroll.param_behavior`,widget:"select",options:[{value:"smooth"},{value:"auto"}]},{key:"block",label:`$t:${de}.scroll.param_block`,widget:"select",options:[{value:"start"},{value:"center"},{value:"end"},{value:"nearest"}]}],build:{handler:"scrollIntoView",params:{selector:"{{selector}}",behavior:"{{behavior}}",block:"{{block}}"}}},login:{label:`$t:${de}.login.label`,params:[{key:"body",label:`$t:${de}.login.param_body`,widget:"key-value"}],build:{handler:"login",params:{body:"{{body}}"}}},logout:{label:`$t:${de}.logout.label`,params:[{key:"target",label:`$t:${de}.logout.param_target`,widget:"text"}],build:{handler:"logout",target:"{{target}}"}},setLocale:{label:`$t:${de}.set_locale.label`,params:[{key:"target",label:`$t:${de}.set_locale.param_target`,widget:"locale-picker",required:!0}],build:{handler:"setLocale",target:"{{target}}"}},emitEvent:{label:`$t:${de}.emit_event.label`,params:[{key:"event",label:`$t:${de}.emit_event.param_event`,widget:"text",required:!0},{key:"data",label:`$t:${de}.emit_event.param_data`,widget:"data-chip"}],build:{handler:"emitEvent",params:{event:"{{event}}",data:"{{data}}"}}},apiCall:{label:`$t:${de}.api_call.label`,params:[{key:"target",label:`$t:${de}.api_call.param_target`,widget:"page-picker",required:!0},{key:"method",label:`$t:${de}.api_call.param_method`,widget:"select",options:[{value:"GET"},{value:"POST"},{value:"PUT"},{value:"PATCH"},{value:"DELETE"}]},{key:"body",label:`$t:${de}.api_call.param_body`,widget:"key-value"},{key:"query",label:`$t:${de}.api_call.param_query`,widget:"key-value"},{key:"identity_target_email",label:`$t:${de}.api_call.param_identity_target_email`,widget:"data-chip"},{key:"identity_target_phone",label:`$t:${de}.api_call.param_identity_target_phone`,widget:"data-chip"},{key:"onSuccess",label:`$t:${de}.api_call.param_on_success`,widget:"action-list"},{key:"onError",label:`$t:${de}.api_call.param_on_error`,widget:"action-list"}],build:{handler:"apiCall",target:"{{target}}",identity_target:{email:"{{identity_target_email}}",phone:"{{identity_target_phone}}"},onSuccess:"{{onSuccess}}",onError:"{{onError}}",params:{method:"{{method}}",body:"{{body}}",query:"{{query}}"}}},conditions:{label:`$t:${de}.conditions.label`,params:[{key:"branches",label:`$t:${de}.conditions.param_branches`,widget:"branch-list"}],build:{handler:"conditions",conditions:"{{branches}}"}},sequence:{label:`$t:${de}.sequence.label`,params:[{key:"actions",label:`$t:${de}.sequence.param_actions`,widget:"action-list"}],build:{handler:"sequence",params:{actions:"{{actions}}"}}},parallel:{label:`$t:${de}.parallel.label`,params:[{key:"actions",label:`$t:${de}.parallel.param_actions`,widget:"action-list"}],build:{handler:"parallel",params:{actions:"{{actions}}"}}},switch:{label:`$t:${de}.switch.label`,params:[{key:"value",label:`$t:${de}.switch.param_value`,widget:"data-chip"},{key:"cases",label:`$t:${de}.switch.param_cases`,widget:"action-list",advanced:!0}],build:{handler:"switch",params:{value:"{{value}}",cases:"{{cases}}"}}},suppress:{label:`$t:${de}.suppress.label`,params:[],build:{handler:"suppress"}}};function e8(){return{actionRecipes:bn,initActionRecipes:bn,errorRecipes:{navigate:bn.navigate,openModal:bn.openModal,toast:bn.toast,setState:bn.setState,sequence:bn.sequence,parallel:bn.parallel,showErrorPage:{label:`$t:${de}.show_error_page.label`,params:[{key:"target",label:`$t:${de}.show_error_page.param_target`,widget:"select",options:[{value:"content"},{value:"full"}]}],build:{handler:"showErrorPage",params:{target:"{{target}}"}}}}}}function nl(e,t){return typeof e.label=="string"?e.label.startsWith("$t:")?t(e.label.slice(3)):e.label:String(e.value)}function wi(e){return Array.isArray(e.options)?e.options:[]}function t8({control:e,value:t,onChange:n,t:o}){const r=wi(e);return i.jsx("div",{className:"g7le-widget g7le-widget--segmented","data-testid":"g7le-widget-segmented",style:f8,children:r.map(s=>{const a=s.value===t;return i.jsx("button",{type:"button","data-testid":`g7le-segment-${String(s.value)}`,"data-active":a?"true":"false",onClick:()=>n(a?void 0:s.value),style:{...x8,background:a?"#2563eb":"#fff",color:a?"#fff":"#0f172a",borderColor:a?"#2563eb":"#cbd5e1"},children:nl(s,o)},String(s.value))})})}function n8({control:e,value:t,onChange:n,t:o}){const r=Array.isArray(e.scale)?e.scale:[],s=r.findIndex(l=>l===t),a=t!=null;return i.jsxs("div",{className:"g7le-widget g7le-widget--slider","data-testid":"g7le-widget-slider",style:Bg,children:[i.jsxs("label",{style:ol,children:[i.jsx("input",{type:"checkbox","data-testid":"g7le-slider-enabled",checked:a,onChange:l=>{l.target.checked?n(r.length>0?r[Math.max(0,s===-1?0:s)]:void 0):n(void 0)}}),i.jsx("span",{style:{fontSize:12,color:"#64748b"},children:o("layout_editor.control.use")})]}),i.jsx("input",{type:"range","data-testid":"g7le-slider-range",min:0,max:Math.max(0,r.length-1),step:1,disabled:!a||r.length===0,value:s===-1?0:s,onChange:l=>{const d=Number(l.target.value);n(r[d])},style:{flex:1}}),i.jsx("span",{"data-testid":"g7le-slider-value",style:{fontSize:12,color:"#0f172a",minWidth:48,textAlign:"right"},children:a?String(t):o("layout_editor.control.default")})]})}function o8({control:e,value:t,onChange:n,t:o}){const r=wi(e);return i.jsxs("select",{className:"g7le-widget g7le-widget--select","data-testid":"g7le-widget-select",value:t==null?"":String(t),onChange:s=>{const a=s.target.value;if(a===""){n(void 0);return}const l=r.find(d=>String(d.value)===a);n(l?l.value:a)},style:w8,children:[i.jsx("option",{value:"",children:o("layout_editor.control.default")}),r.map(s=>i.jsx("option",{value:String(s.value),children:nl(s,o)},String(s.value)))]})}function r8({control:e,value:t,onChange:n}){const o=wi(e),r=o[1]?.value??!0,s=o[0]?.value??void 0,a=t===r;return i.jsx("button",{type:"button",className:"g7le-widget g7le-widget--toggle","data-testid":"g7le-widget-toggle",role:"switch","aria-checked":a,onClick:()=>n(a?s:r),style:{...k8,background:a?"#2563eb":"#cbd5e1"},children:i.jsx("span",{style:{...S8,transform:a?"translateX(18px)":"translateX(0)"}})})}function i8({control:e,value:t,onChange:n,t:o,freeValueDisabled:r}){const s=wi(e),a=t==null?"":String(t),[l,d]=u.useState(a);u.useEffect(()=>{d(a)},[a]);const c=p=>{const f=p.trim();if(f===""){n(void 0);return}n(f)};return i.jsxs("div",{className:"g7le-widget g7le-widget--dimension","data-testid":"g7le-widget-dimension",style:g8,children:[r?i.jsx("div",{"data-testid":"g7le-dimension-free-disabled",style:v8,children:o("layout_editor.property_modal.dark_preset_only")}):i.jsxs("div",{style:h8,children:[i.jsx("input",{type:"text","data-testid":"g7le-dimension-input",value:l,placeholder:o("layout_editor.control.dimension.placeholder"),onChange:p=>d(p.target.value),onBlur:p=>c(p.target.value),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),c(p.target.value))},style:y8}),i.jsx("button",{type:"button","data-testid":"g7le-dimension-clear",title:o("layout_editor.control.default"),onClick:()=>{d(""),n(void 0)},style:b8,children:o("layout_editor.control.default")})]}),s.length>0&&i.jsx("div",{style:m8,"data-testid":"g7le-dimension-chips",children:s.map(p=>{const f=String(p.value),b=f===a;return i.jsx("button",{type:"button","data-testid":`g7le-dimension-chip-${f}`,"data-active":b?"true":"false",onClick:()=>{d(f),n(f)},style:{..._8,background:b?"#2563eb":"#fff",color:b?"#fff":"#0f172a",borderColor:b?"#2563eb":"#cbd5e1"},children:nl(p,o)},f)})})]})}function s8(e){return[{key:"t",infix:`${e}t-`,labelKey:"layout_editor.control.spacing.top"},{key:"r",infix:`${e}r-`,labelKey:"layout_editor.control.spacing.right"},{key:"b",infix:`${e}b-`,labelKey:"layout_editor.control.spacing.bottom"},{key:"l",infix:`${e}l-`,labelKey:"layout_editor.control.spacing.left"}]}function a8(e,t,n,o){const r={all:-1,sides:{}};if(typeof e!="string"||e.trim()==="")return r;const s=e.split(/\s+/).filter(a=>a.length>0);for(const a of s){const l=n.find(d=>a.startsWith(d.infix));if(l){r.sides[l.key]=o.indexOf(a.slice(l.infix.length));continue}if(a.startsWith(`${t}x-`)){const d=o.indexOf(a.slice(`${t}x-`.length));r.sides.l=d,r.sides.r=d;continue}if(a.startsWith(`${t}y-`)){const d=o.indexOf(a.slice(`${t}y-`.length));r.sides.t=d,r.sides.b=d;continue}a.startsWith(`${t}-`)&&(r.all=o.indexOf(a.slice(`${t}-`.length)))}return r}function l8({control:e,value:t,onChange:n,t:o}){const r=typeof e.spacingPrefix=="string"?e.spacingPrefix:"p",s=(Array.isArray(e.scale)?e.scale:[]).map(y=>String(y)),a=s8(r),l=a8(t,r,a,s),d=Object.values(l.sides).some(y=>y>=0),c=l.all>=0||d,[p,f]=u.useState(d);u.useEffect(()=>{d&&f(!0)},[d]);const b=Math.min(4,Math.max(0,s.length-1)),g=y=>{const _=[];for(const w of a){const k=y[w.key];k!==void 0&&k>=0&&_.push(`${w.infix}${s[k]}`)}n(_.length>0?_.join(" "):void 0)},m=y=>{n(y>=0?`${r}-${s[Math.max(0,Math.min(y,s.length-1))]}`:void 0)},h=()=>({...l.sides}),v=(y,_,w,k,x)=>{const $=w>=0;return i.jsxs("div",{style:p8,"data-testid":y,children:[i.jsxs("label",{style:{...ol,minWidth:64},children:[i.jsx("input",{type:"checkbox","data-testid":`${y}-enabled`,checked:$,onChange:S=>x(S.target.checked)}),i.jsx("span",{style:{fontSize:12,color:"#0f172a"},children:o(_)})]}),i.jsx("input",{type:"range","data-testid":`${y}-range`,min:0,max:Math.max(0,s.length-1),step:1,disabled:!$||s.length===0,value:w<0?0:w,onChange:S=>k(Number(S.target.value)),style:{flex:1}}),i.jsx("span",{"data-testid":`${y}-value`,style:{fontSize:12,color:$?"#0f172a":"#94a3b8",minWidth:28,textAlign:"right"},children:$?s[w]:"–"})]},y)};return i.jsxs("div",{className:"g7le-widget g7le-widget--spacing","data-testid":"g7le-widget-spacing",style:d8,children:[i.jsxs("div",{style:c8,children:[i.jsxs("div",{style:u8,"data-testid":"g7le-spacing-mode",children:[i.jsx("button",{type:"button","data-testid":"g7le-spacing-mode-all","data-active":p?"false":"true",onClick:()=>{f(!1),d&&n(void 0)},style:{...Og,background:p?"#fff":"#2563eb",color:p?"#0f172a":"#fff",borderColor:p?"#cbd5e1":"#2563eb"},children:o("layout_editor.control.spacing.mode_all")}),i.jsx("button",{type:"button","data-testid":"g7le-spacing-mode-sides","data-active":p?"true":"false",onClick:()=>{if(f(!0),l.all>=0){const y={};for(const _ of a)y[_.key]=l.all;g(y)}},style:{...Og,background:p?"#2563eb":"#fff",color:p?"#fff":"#0f172a",borderColor:p?"#2563eb":"#cbd5e1"},children:o("layout_editor.control.spacing.mode_sides")})]}),i.jsx("span",{"data-testid":"g7le-spacing-value",style:{fontSize:11,color:"#64748b",minWidth:80,textAlign:"right"},children:c?String(t):o("layout_editor.control.default")})]}),p?i.jsx("div",{"data-testid":"g7le-spacing-sides",style:{display:"flex",flexDirection:"column",gap:4},children:a.map(y=>v(`g7le-spacing-side-${y.key}`,y.labelKey,l.sides[y.key]??-1,_=>{const w=h();w[y.key]=_,g(w)},_=>{const w=h();_?w[y.key]=l.sides[y.key]>=0?l.sides[y.key]:b:delete w[y.key],g(w)}))}):i.jsxs("div",{style:Bg,children:[i.jsxs("label",{style:{...ol,minWidth:64},children:[i.jsx("input",{type:"checkbox","data-testid":"g7le-spacing-all-enabled",checked:l.all>=0,onChange:y=>m(y.target.checked?b:-1)}),i.jsx("span",{style:{fontSize:12,color:"#64748b"},children:o("layout_editor.control.spacing.all")})]}),i.jsx("input",{type:"range","data-testid":"g7le-spacing-all-range",min:0,max:Math.max(0,s.length-1),step:1,disabled:l.all<0||s.length===0,value:l.all<0?0:l.all,onChange:y=>m(Number(y.target.value)),style:{flex:1}}),i.jsx("span",{"data-testid":"g7le-spacing-all-value",style:{fontSize:12,color:l.all>=0?"#0f172a":"#94a3b8",minWidth:28,textAlign:"right"},children:l.all>=0?s[l.all]:"–"})]})]})}const d8={display:"flex",flexDirection:"column",gap:6,width:"100%"},c8={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},u8={display:"inline-flex",gap:0,border:"1px solid #cbd5e1",borderRadius:6,overflow:"hidden"},Og={padding:"3px 10px",fontSize:11,border:"none",borderRight:"1px solid #e2e8f0",cursor:"pointer"},p8={display:"flex",alignItems:"center",gap:8,width:"100%"},f8={display:"inline-flex",gap:0,border:"1px solid #cbd5e1",borderRadius:6,overflow:"hidden"},g8={display:"flex",flexDirection:"column",gap:6,width:"100%"},h8={display:"flex",gap:6,alignItems:"center"},y8={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:80},b8={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer",whiteSpace:"nowrap"},m8={display:"flex",flexWrap:"wrap",gap:4},v8={fontSize:11,color:"#94a3b8",fontStyle:"italic",padding:"2px 0"},_8={padding:"3px 9px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:999,background:"#fff",cursor:"pointer"},x8={padding:"4px 10px",fontSize:12,border:"none",borderRight:"1px solid #e2e8f0",cursor:"pointer"},Bg={display:"flex",alignItems:"center",gap:8,width:"100%"},ol={display:"inline-flex",alignItems:"center",gap:4},w8={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",minWidth:120},k8={position:"relative",width:38,height:20,borderRadius:10,border:"none",cursor:"pointer",padding:2,display:"inline-flex",alignItems:"center",transition:"background 120ms ease"},S8={display:"block",width:16,height:16,borderRadius:8,background:"#fff",transition:"transform 120ms ease"},C8=["#0f172a","#334155","#64748b","#94a3b8","#e2e8f0","#ffffff","#dc2626","#ea580c","#d97706","#16a34a","#0891b2","#2563eb","#7c3aed","#db2777"],Wg=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function $8(e){return Array.isArray(e.options)?e.options.filter(t=>typeof t.value=="string").map(t=>({value:t.value,swatch:typeof t.swatch=="string"?t.swatch:void 0,label:typeof t.label=="string"?t.label:void 0})):[]}function E8({control:e,value:t,onChange:n,t:o,freeValueDisabled:r}){const s=$8(e),a=s.length>0,l=typeof t=="string"&&s.some(g=>g.value===t)?t:"",d=typeof t=="string"&&Wg.test(t)?t:"",[c,p]=u.useState(d);u.useEffect(()=>{p(d)},[d]);const f=g=>{const m=g.trim();if(m===""){n(void 0);return}const h=m.startsWith("#")?m:`#${m}`;Wg.test(h)&&n(h)},b=C8;return i.jsxs("div",{className:"g7le-widget g7le-widget--color","data-testid":"g7le-widget-color",style:I8,children:[r?i.jsx("div",{"data-testid":"g7le-color-free-disabled",style:M8,children:o("layout_editor.property_modal.dark_preset_only")}):i.jsxs("div",{style:A8,children:[i.jsxs("label",{style:T8,children:[i.jsx("span",{"data-testid":"g7le-color-swatch",style:{...D8,background:d||"transparent",backgroundImage:d?void 0:"linear-gradient(45deg,#e2e8f0 25%,transparent 25%,transparent 75%,#e2e8f0 75%),linear-gradient(45deg,#e2e8f0 25%,#fff 25%,#fff 75%,#e2e8f0 75%)",backgroundSize:"8px 8px",backgroundPosition:"0 0, 4px 4px"}}),i.jsx("input",{type:"color","data-testid":"g7le-color-native",value:d||"#000000",onChange:g=>n(g.target.value),style:{width:0,height:0,opacity:0,position:"absolute"}})]}),i.jsx("input",{type:"text","data-testid":"g7le-color-hex",value:c,placeholder:o("layout_editor.control.color_hex_placeholder"),onChange:g=>p(g.target.value),onBlur:g=>f(g.target.value),onKeyDown:g=>{g.key==="Enter"&&f(g.target.value)},style:z8}),i.jsx("button",{type:"button","data-testid":"g7le-color-clear",onClick:()=>n(void 0),style:N8,children:o("layout_editor.control.default")})]}),a?i.jsx("div",{style:jg,"data-testid":"g7le-color-token-presets",children:s.map(g=>{const m=l===g.value,h=g.label?g.label.startsWith("$t:")?o(g.label.slice(3)):g.label:g.value;return i.jsx("button",{type:"button","aria-label":h,title:h,"data-testid":`g7le-color-token-${g.value}`,"data-active":m?"true":"false",onClick:()=>n(m?void 0:g.value),style:{...Hg,background:g.swatch||"#e2e8f0",outline:m?"2px solid #2563eb":"none"}},g.value)})}):!r&&i.jsx("div",{style:jg,"data-testid":"g7le-color-presets",children:b.map(g=>i.jsx("button",{type:"button","aria-label":g,"data-testid":`g7le-color-preset-${g}`,onClick:()=>n(g),style:{...Hg,background:g,outline:d.toLowerCase()===g.toLowerCase()?"2px solid #2563eb":"none"}},g))})]})}const I8={display:"flex",flexDirection:"column",gap:8},A8={display:"flex",alignItems:"center",gap:6},T8={position:"relative",display:"inline-flex",cursor:"pointer"},D8={width:24,height:24,borderRadius:4,border:"1px solid #cbd5e1",display:"inline-block"},z8={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,fontFamily:"monospace"},N8={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",cursor:"pointer",color:"#64748b"},jg={display:"grid",gridTemplateColumns:"repeat(7, 1fr)",gap:4},Hg={width:"100%",height:18,borderRadius:4,border:"1px solid #cbd5e1",cursor:"pointer",padding:0},M8={fontSize:11,color:"#94a3b8",fontStyle:"italic",padding:"2px 0"},tr=[{value:"fill",labelKey:"layout_editor.control.background_image.mode_fill",size:"cover",repeat:"no-repeat"},{value:"fit",labelKey:"layout_editor.control.background_image.mode_fit",size:"contain",repeat:"no-repeat"},{value:"tile",labelKey:"layout_editor.control.background_image.mode_tile",size:"auto",repeat:"repeat"}];function L8(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Fg(e){return tr.find(n=>n.size===e.size&&n.repeat===e.repeat)?.value??"fill"}function P8({value:e,onChange:t,t:n}){const o=L8(e),{state:r}=Qe(),s=bo(),[a,l]=u.useState(!1),[d,c]=u.useState(null),[p,f]=u.useState(o.url??""),[b,g]=u.useState([]),m=u.useRef(null),h=r.templateIdentifier,v=r.selectedRoute?.layoutName??"";u.useEffect(()=>{f(o.url??"")},[o.url]);const y=u.useCallback(async()=>{if(!h||!v){g([]);return}const S=await Ll(h,v);S.ok&&g(S.data)},[h,v]);u.useEffect(()=>{y()},[y]);const _=S=>{if(!S){t(void 0);return}const C=tr.find(T=>T.value===Fg(o))??tr[0];t({url:S,size:o.size??C.size,repeat:o.repeat??C.repeat,position:o.position??"center"})},w=S=>{const C=tr.find(T=>T.value===S);!C||!o.url||t({url:o.url,size:C.size,repeat:C.repeat,position:o.position??"center"})},k=async S=>{const C=S.target.files?.[0];if(!C)return;l(!0),c(null);const T=await Pl(h,v,C);T.ok?(_(T.data.url),y()):c(n("layout_editor.control.background_image.upload_failed")),l(!1),m.current&&(m.current.value="")},x=async S=>{(await Ol(S.id)).ok&&g(T=>T.filter(E=>E.id!==S.id))},$=()=>{const S=s.open({ariaLabel:n("layout_editor.attachment_manager.title"),width:720,maxHeightRatio:.82,content:u.createElement(Bl,{templateIdentifier:h,layoutName:v,t:n,onSelect:C=>{_(C),s.close(S)},onChanged:()=>{y()},onClose:()=>s.close(S)})})};return i.jsxs("div",{className:"g7le-widget g7le-widget--image","data-testid":"g7le-widget-image",style:O8,children:[o.url&&i.jsx("div",{"data-testid":"g7le-image-preview",style:{...B8,backgroundImage:`url(${o.url})`,backgroundSize:o.size??"cover",backgroundRepeat:o.repeat??"no-repeat",backgroundPosition:o.position??"center"}}),i.jsxs("div",{style:W8,children:[i.jsxs("label",{style:j8,children:[a?"…":n("layout_editor.control.background_image.upload"),i.jsx("input",{ref:m,type:"file",accept:"image/*","data-testid":"g7le-image-file",onChange:k,disabled:a,style:{display:"none"}})]}),i.jsx("button",{type:"button","data-testid":"g7le-image-clear",onClick:()=>t(void 0),style:H8,children:n("layout_editor.control.background_image.clear")})]}),i.jsx("input",{type:"text","data-testid":"g7le-image-url",placeholder:"https://… / URL",value:p,onChange:S=>f(S.target.value),onBlur:S=>_(S.target.value.trim()||void 0),style:F8}),i.jsx("div",{style:K8,"data-testid":"g7le-image-modes",children:tr.map(S=>{const C=Fg(o)===S.value;return i.jsx("button",{type:"button","data-testid":`g7le-image-mode-${S.value}`,"data-active":C?"true":"false",disabled:!o.url,onClick:()=>w(S.value),style:{...V8,background:C&&o.url?"#2563eb":"#fff",color:C&&o.url?"#fff":"#0f172a"},children:n(S.labelKey)},S.value)})}),i.jsxs("div",{style:U8,"data-testid":"g7le-image-gallery",children:[i.jsxs("div",{style:q8,children:[i.jsx("span",{style:{fontSize:11,color:"#64748b"},children:n("layout_editor.attachment_manager.recent")}),i.jsxs("button",{type:"button","data-testid":"g7le-image-manage",onClick:$,style:G8,children:["🖼 ",n("layout_editor.attachment_manager.manage_link")]})]}),b.length>0?i.jsx("div",{style:Y8,"data-testid":"g7le-image-thumbs",children:b.slice(0,8).map(S=>i.jsxs("div",{style:X8,"data-testid":`g7le-image-thumb-${S.id}`,children:[i.jsx("button",{type:"button",title:S.original_name,onClick:()=>_(S.url),style:{...J8,backgroundImage:`url(${S.url})`},"data-testid":`g7le-image-thumb-use-${S.id}`}),i.jsx("button",{type:"button",title:n("layout_editor.attachment_manager.delete"),onClick:()=>x(S),style:Z8,"data-testid":`g7le-image-thumb-del-${S.id}`,children:"✕"})]},S.id))}):i.jsx("span",{style:{fontSize:11,color:"#94a3b8"},children:n("layout_editor.attachment_manager.empty")})]}),d&&i.jsx("span",{"data-testid":"g7le-image-error",style:{fontSize:11,color:"#dc2626"},children:d})]})}const O8={display:"flex",flexDirection:"column",gap:6},B8={width:"100%",height:80,borderRadius:6,border:"1px solid #cbd5e1"},W8={display:"flex",gap:6},j8={padding:"5px 10px",fontSize:12,border:"1px solid #2563eb",borderRadius:6,background:"#fff",color:"#2563eb",cursor:"pointer",display:"inline-flex",alignItems:"center"},H8={padding:"5px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"},F8={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},K8={display:"inline-flex",border:"1px solid #cbd5e1",borderRadius:6,overflow:"hidden"},V8={padding:"4px 10px",fontSize:12,border:"none",borderRight:"1px solid #e2e8f0",cursor:"pointer"},U8={display:"flex",flexDirection:"column",gap:4,border:"1px solid #e2e8f0",borderRadius:6,padding:6,marginTop:2},q8={display:"flex",alignItems:"center",justifyContent:"space-between"},G8={fontSize:11,color:"#2563eb",background:"transparent",border:"none",cursor:"pointer",padding:0},Y8={display:"flex",gap:6,flexWrap:"wrap"},X8={position:"relative",width:44,height:44},J8={width:44,height:44,borderRadius:6,border:"1px solid #cbd5e1",backgroundSize:"cover",backgroundPosition:"center",cursor:"pointer",padding:0},Z8={position:"absolute",top:-6,right:-6,width:16,height:16,borderRadius:"50%",border:"none",background:"#dc2626",color:"#fff",fontSize:9,lineHeight:"16px",cursor:"pointer",padding:0};function Q8(e){return Array.isArray(e)&&e.every(t=>t!==null&&typeof t=="object"&&!Array.isArray(t))}function R8(e){return typeof e=="string"&&/\{\{.*\}\}/.test(e)}function ez({value:e,onChange:t,t:n,bindingCandidates:o}){if(R8(e))return i.jsx("div",{className:"g7le-widget g7le-widget--options-list","data-testid":"g7le-widget-options-list-bound",style:lz,children:n("layout_editor.list_editor.bound_degraded")});const r=Q8(e)?e:[],s=b=>{t(b.length===0?void 0:b)},a=(b,g)=>{const m=r.map((h,v)=>v===b?{...h,...g}:h);s(m)},l=b=>{s(r.filter((g,m)=>m!==b))},d=(b,g)=>{const m=b+g;if(m<0||m>=r.length)return;const h=[...r];[h[b],h[m]]=[h[m],h[b]],s(h)},c=()=>{s([...r,{value:"",label:""}])},p=b=>typeof b.label=="string"?b.label:b.label==null?"":String(b.label),f=b=>b.value===void 0||b.value===null?"":String(b.value);return i.jsxs("div",{className:"g7le-widget g7le-widget--options-list","data-testid":"g7le-widget-options-list",style:tz,children:[r.length===0&&i.jsx("div",{"data-testid":"g7le-options-empty",style:az,children:n("layout_editor.list_editor.empty")}),r.map((b,g)=>i.jsxs("div",{"data-testid":`g7le-options-row-${g}`,style:nz,children:[i.jsxs("div",{style:Kg,children:[i.jsx("span",{style:Vg,children:n("layout_editor.list_editor.option_value")}),i.jsx("input",{type:"text","data-testid":`g7le-options-value-${g}`,value:f(b),placeholder:n("layout_editor.list_editor.option_value"),onChange:m=>a(g,{value:m.target.value}),style:rz})]}),i.jsxs("div",{style:Kg,children:[i.jsx("span",{style:Vg,children:n("layout_editor.list_editor.option_label")}),i.jsx("div",{"data-testid":`g7le-options-label-${g}`,style:{flex:1,minWidth:0},children:i.jsx(_t,{value:p(b),onChange:m=>a(g,{label:m??""}),t:n,placeholder:n("layout_editor.list_editor.option_label"),testidPrefix:`g7le-options-label-i18n-${g}`,candidates:o,enableExpressionTree:!0,expressionTreeCollapsible:!0})})]}),i.jsxs("div",{style:oz,children:[i.jsx("button",{type:"button","data-testid":`g7le-options-up-${g}`,title:n("layout_editor.list_editor.move_up"),disabled:g===0,onClick:()=>d(g,-1),style:Ug,children:"↑"}),i.jsx("button",{type:"button","data-testid":`g7le-options-down-${g}`,title:n("layout_editor.list_editor.move_down"),disabled:g===r.length-1,onClick:()=>d(g,1),style:Ug,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-options-remove-${g}`,title:n("layout_editor.list_editor.remove"),onClick:()=>l(g),style:iz,children:"✕"})]})]},g)),i.jsx("button",{type:"button","data-testid":"g7le-options-add",onClick:c,style:sz,children:n("layout_editor.list_editor.add")})]})}const tz={display:"flex",flexDirection:"column",gap:8,width:"100%"},nz={display:"flex",flexDirection:"column",gap:4,width:"100%",minWidth:0,paddingBottom:6,borderBottom:"1px solid #f1f5f9"},Kg={display:"flex",gap:6,alignItems:"center",width:"100%",minWidth:0},Vg={flexShrink:0,width:36,fontSize:11,color:"#94a3b8",textAlign:"right"},oz={display:"flex",gap:4,alignItems:"center",justifyContent:"flex-end"},rz={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},Ug={padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},iz={padding:"2px 6px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},sz={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},az={fontSize:11,color:"#94a3b8",fontStyle:"italic"},lz={fontSize:11,color:"#b45309",fontStyle:"italic",padding:"4px 2px"},qg=/[^A-Za-z0-9\-_:.]/g;function dz(e){return typeof e=="string"&&Yi(e)}function Gg(e){return Yi(e)?In(e).map(t=>t.kind==="binding"?t.raw:t.raw.replace(qg,"")).join(""):e.replace(qg,"")}const cz={width:"100%",padding:"6px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:4,fontFamily:"monospace"},uz={marginTop:4,fontSize:11,color:"#94a3b8"},pz={display:"flex",gap:6,alignItems:"center"},fz={flexShrink:0,padding:"5px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:4,background:"#f8fafc",cursor:"pointer",whiteSpace:"nowrap"};function gz({value:e,onChange:t,t:n,bindingCandidates:o}){const r=e==null?"":String(e),s=dz(e),a=!!o&&o.length>0,[l,d]=u.useState(!1),c=p=>{const f=Gg(p);t(f===""?void 0:f)};return s||l?i.jsxs("div",{"data-testid":"g7le-core-id-chip",children:[i.jsx(_s,{value:r,onChange:c,t:n,candidates:o,onDone:()=>d(!1),testidPrefix:"g7le-core-id-chip-input"}),i.jsx("div",{style:uz,children:n("layout_editor.core_props.id.binding_hint")})]}):i.jsx("div",{children:i.jsxs("div",{style:pz,children:[i.jsx("input",{type:"text",className:"g7le-widget g7le-widget--core-id","data-testid":"g7le-widget-core-id",value:r,onChange:p=>{const f=Gg(p.target.value);t(f===""?void 0:f)},spellCheck:!1,autoComplete:"off",style:cz}),a&&i.jsxs("button",{type:"button","data-testid":"g7le-core-id-add-data",onClick:()=>d(!0),style:fz,title:n("layout_editor.core_props.id.add_data"),children:["🔗 ",n("layout_editor.core_props.id.add_data")]})]})})}const hz=/[^A-Za-z0-9.\-_]/g;function yz(e){return typeof e=="string"&&/\{\{[\s\S]*?\}\}/.test(e)}function bz(e){return e.replace(hz,"")}const Yg={width:"100%",padding:"6px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:4,fontFamily:"monospace",boxSizing:"border-box"},mz={...Yg,background:"#f1f5f9",color:"#64748b",cursor:"not-allowed"},Xg={marginTop:4,fontSize:11,color:"#94a3b8"};function vz({value:e,onChange:t,t:n}){const o=e==null?"":String(e);return yz(e)?i.jsxs("div",{"data-testid":"g7le-core-datakey-bound",children:[i.jsx("input",{type:"text",className:"g7le-widget g7le-widget--core-datakey-bound","data-testid":"g7le-widget-core-datakey",value:o,readOnly:!0,disabled:!0,style:mz}),i.jsx("div",{style:Xg,children:n("layout_editor.core_props.dataKey.bound_degraded")})]}):i.jsxs("div",{children:[i.jsx("input",{type:"text",className:"g7le-widget g7le-widget--core-datakey","data-testid":"g7le-widget-core-datakey",value:o,placeholder:n("layout_editor.core_props.dataKey.placeholder"),onChange:s=>{const a=bz(s.target.value);t(a===""?void 0:a)},spellCheck:!1,autoComplete:"off",style:Yg}),i.jsx("div",{style:Xg,children:n("layout_editor.core_props.dataKey.hint")})]})}let Jg=!1;function _z(){Jg||(Ze("segmented",t8),Ze("slider",n8),Ze("select",o8),Ze("dimension",i8),Ze("spacing",l8),Ze("toggle",r8),Ze("color",E8),Ze("image",P8),Ze("tag-input",vs),Ze("page-picker",P0),Ze("datasource-picker",Fc),Ze("binding-picker",Fc),Ze("binding-list",W0),Ze("state-key-picker",Ts),Ze("modal-picker",O0),Ze("i18n-text",B0),Ze("text",j0),Ze("options-list",ez),Ze("core-id",gz),Ze("core-datakey",vz),Ze("component-target-picker",p4),Jg=!0)}function nr(e){return Array.isArray(e.children)?e.children:[]}function or(e){if(typeof e.text=="string")return[];let t=null;const n=(o,r)=>{const s=nr(o);for(let a=0;ad===o?rr(l,r,n):l);return{...e,children:a}}function Zg(e,t){const n=r=>typeof r.props?.[t]=="string";if(n(e))return[];const o=(r,s)=>{const a=nr(r);for(let l=0;lc===r?Qg(d,s,n,o):d);return{...e,children:l}}function xz(e){return Array.isArray(e.children)?e.children:[]}function wz(e){const t=e?.itemFields;if(!Array.isArray(t))return[{kind:"text"}];const n=[];for(const o of t){if(!o||typeof o!="object")continue;const r=o;r.kind==="text"?n.push({kind:"text",label:typeof r.label=="string"?r.label:void 0}):r.kind==="prop"&&typeof r.prop=="string"&&r.prop.length>0&&n.push({kind:"prop",prop:r.prop,label:typeof r.label=="string"?r.label:void 0})}return n.length>0?n:[{kind:"text"}]}function rl(e,t){if(!(typeof e!="string"||e.length===0))return e.startsWith("$t:")?t(e.slice(3)):e}function Rg({node:e,params:t,spec:n,manifest:o,t:r,onPatchNode:s,templateIdentifier:a,candidates:l}){const d=typeof t?.childComponent=="string"?t.childComponent:null,c=t?.childTemplate&&typeof t.childTemplate=="object"?t.childTemplate:null,p=wz(t),f=rl(typeof t?.childLabel=="string"?t.childLabel:void 0,r)??d??"",b=xz(e),g=u.useCallback(x=>{s({...e,children:x})},[e,s]),m=u.useCallback(()=>{if(c)return JSON.parse(JSON.stringify(c));if(!d)return null;const x=n?.componentPalette?.entries?.[d];if(x?.defaultNode&&typeof x.defaultNode=="object")return JSON.parse(JSON.stringify(x.defaultNode));const $=o?.components??{};let S=null;for(const C of Object.values($))if(Array.isArray(C)){const T=C.find(E=>E.name===d);if(T){S=T;break}}return S?zf(S):{type:"basic",name:d}},[c,d,n,o]),h=u.useCallback(()=>{const x=m();if(x){if(x.text==="")x.text=r("layout_editor.list_editor.new_item");else{const $=or(x);if($!==null&&$.length>0){const S=ki(x,$);if(S&&S.text===""){const C=rr(x,$,r("layout_editor.list_editor.new_item"));g([...b,C]);return}}}g([...b,x])}},[m,g,b,r]),v=u.useCallback(x=>{g(b.filter(($,S)=>S!==x))},[g,b]),y=u.useCallback((x,$)=>{const S=x+$;if(S<0||S>=b.length)return;const C=[...b];[C[x],C[S]]=[C[S],C[x]],g(C)},[g,b]),_=u.useCallback((x,$)=>{if(typeof $!="string"||$.length===0)return;const S=b[x];if(!S)return;const C=or(S);if(C===null)return;const T=b.map((E,A)=>A===x?rr(E,C,$):E);g(T)},[b,g]),w=u.useCallback((x,$,S)=>{if(typeof S!="string"||S.length===0)return;const C=b[x];if(!C)return;const T=Zg(C,$);if(T===null)return;const E=b.map((A,N)=>N===x?Qg(A,T,$,S):A);g(E)},[b,g]);if(!d&&!c)return i.jsx("div",{className:"g7le-node-editor g7le-node-editor--children","data-testid":"g7le-children-editor-misconfigured",style:nh,children:r("layout_editor.list_editor.no_child_component")});const k=p.length>1||p.some(x=>x.label);return i.jsxs("div",{className:"g7le-node-editor g7le-node-editor--children","data-testid":"g7le-children-editor",style:kz,children:[i.jsx("div",{style:Sz,children:r("layout_editor.list_editor.items_title")}),b.length===0&&i.jsx("div",{"data-testid":"g7le-children-empty",style:nh,children:r("layout_editor.list_editor.empty")}),b.map((x,$)=>{const S=[];for(const T of p)if(T.kind==="text"){const E=or(x),A=E!==null?ki(x,E):null;A&&typeof A.text=="string"&&S.push({key:"text",caption:rl(T.label,r)??(k?r("layout_editor.list_editor.item_label"):void 0),value:A.text,onChange:N=>_($,N),testid:`g7le-children-i18n-${$}`})}else if(T.kind==="prop"&&T.prop){const E=Zg(x,T.prop);if(E!==null){const N=ki(x,E)?.props?.[T.prop];S.push({key:`prop-${T.prop}`,caption:rl(T.label,r)??T.prop,value:typeof N=="string"?N:"",onChange:D=>w($,T.prop,D),testid:`g7le-children-prop-${T.prop}-${$}`})}}const C=typeof x?.name=="string"?x.name:r("layout_editor.list_editor.item");return i.jsxs("div",{"data-testid":`g7le-children-row-${$}`,style:Cz,children:[S.length>0?S.map(T=>i.jsx("div",{style:eh,children:i.jsxs("div",{"data-testid":T.key==="text"?`g7le-children-text-${$}`:`g7le-children-field-${T.key}-${$}`,style:$z,children:[T.caption!==void 0&&i.jsx("div",{"data-testid":`g7le-children-caption-${T.key}-${$}`,style:Ez,children:T.caption}),i.jsx(_t,{value:T.value,onChange:T.onChange,t:r,placeholder:r("layout_editor.list_editor.item_text"),testidPrefix:T.testid,candidates:l,enableExpressionTree:!0,expressionTreeCollapsible:!0})]})},T.key)):i.jsx("div",{style:eh,children:i.jsx("span",{"data-testid":`g7le-children-label-${$}`,style:Az,children:C})}),i.jsxs("div",{style:Iz,children:[i.jsx("button",{type:"button","data-testid":`g7le-children-up-${$}`,title:r("layout_editor.list_editor.move_up"),disabled:$===0,onClick:()=>y($,-1),style:th,children:"↑"}),i.jsx("button",{type:"button","data-testid":`g7le-children-down-${$}`,title:r("layout_editor.list_editor.move_down"),disabled:$===b.length-1,onClick:()=>y($,1),style:th,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-children-remove-${$}`,title:r("layout_editor.list_editor.remove"),onClick:()=>v($),style:Tz,children:"✕"})]})]},$)}),i.jsx("button",{type:"button","data-testid":"g7le-children-add",onClick:h,style:Dz,children:r("layout_editor.list_editor.add_child",{component:f})})]})}const kz={display:"flex",flexDirection:"column",gap:6,width:"100%",marginBottom:12},Sz={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:2},Cz={display:"flex",flexDirection:"column",gap:4,width:"100%",minWidth:0,paddingBottom:6,borderBottom:"1px solid #f1f5f9"},eh={display:"flex",gap:4,alignItems:"flex-start",width:"100%",minWidth:0},$z={flex:1,minWidth:0},Ez={fontSize:11,color:"#64748b",marginBottom:2},Iz={display:"flex",gap:4,alignItems:"center",justifyContent:"flex-end"},Az={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,color:"#475569",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},th={padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},Tz={padding:"2px 6px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},Dz={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},nh={fontSize:11,color:"#94a3b8",fontStyle:"italic"},go={rowContainer:"Tbody",row:"Tr",cell:"Td",headerCell:"Th",colSpanProp:"colSpan",rowSpanProp:"rowSpan"};function yt(e){return{rowContainer:e?.rowContainer??go.rowContainer,row:e?.row??go.row,cell:e?.cell??go.cell,headerCell:e?.headerCell??go.headerCell,colSpanProp:e?.colSpanProp??go.colSpanProp,rowSpanProp:e?.rowSpanProp??go.rowSpanProp}}function Bn(e){return e?Array.isArray(e.children)?e.children:[]:[]}function oh(e,t){const n=e.props?.[t],o=typeof n=="number"?n:typeof n=="string"?parseInt(n,10):NaN;return Number.isFinite(o)&&o>=1?Math.floor(o):1}function Pe(e,t){const n=yt(t),o=[],r=Bn(e),s=[];r.forEach((f,b)=>{(Bn(f).some(h=>h.name===n.row)||f.name===n.rowContainer||f.name==="Thead"||f.name==="Tfoot")&&s.push({container:f,containerIndex:b,isHeader:f.name==="Thead"})}),s.length===0&&r.some(f=>f.name===n.row)&&s.push({container:e,containerIndex:-1,isHeader:!1});const a=[],l=[];let d=0,c=0;const p=f=>{for(;a.length<=f;)a.push([]);return a[f]};s.forEach((f,b)=>{Bn(f.container).filter(m=>m.name===n.row).forEach((m,h)=>{const v=[],y=p(d);let _=0;Bn(m).filter(k=>k.name===n.cell||k.name===n.headerCell).forEach((k,x)=>{for(;y[_];)_++;const $=oh(k,n.colSpanProp),S=oh(k,n.rowSpanProp),C={cell:k,sectionIndex:b,rowIndexInSection:h,cellIndexInRow:x,gridRow:d,gridCol:_,colSpan:$,rowSpan:S,isHeader:k.name===n.headerCell};v.push(C);for(let T=0;T=0?(a.push(s.containerIndex),l=Bn(e)[s.containerIndex]??e):l=e;let d=-1,c=-1,p=null;const f=Bn(l);for(let m=0;m=r.gridRow&&t=r.gridCol&&nr){s=!0;break}if(s)break}s||t.add(r)}const n=Array.from(t).sort((r,s)=>r-s),o=[];for(let r=0;re.rows.find(l=>(l.cells[0]?.gridRow??-1)===a)?.sectionIndex??e.rows[a]?.sectionIndex??0,o=new Set([0,t]);for(let a=1;aa){l=!0;break}if(l)break}l||o.add(a)}const r=Array.from(o).sort((a,l)=>a-l),s=[];for(let a=0;at>=a.start&&t=o.length?{ok:!1,reason:"boundary"}:o[r].sectionIndex!==o[s].sectionIndex?{ok:!1,reason:"section"}:{ok:!0}}function Ci(e,t,n){const o=rh(e),r=o.findIndex(a=>t>=a.start&&t=o.length?{ok:!1,reason:"boundary"}:{ok:!0}}function Ge(e){return e?Array.isArray(e.children)?e.children:[]:[]}function mn(e,t,n){const o={...e.props??{}};n<=1?delete o[t]:o[t]=n;const r={...e,props:o};return Object.keys(o).length===0&&delete r.props,r}function $i(e,t,n=!1){const o={type:"basic",name:n?e.headerCell:e.cell},r=t?.props?.className;return typeof r=="string"&&r&&(o.props={className:r}),o.text="",o}function ir(e,t){return e.name===t.cell||e.name===t.headerCell}function nt(e,t,n,o){const r=t.sections[n];if(!r)return e;if(r.containerIndex===-1)return o(e);const s=Ge(e).map((a,l)=>l===r.containerIndex?o(a):a);return{...e,children:s}}function bt(e,t,n,o){let r=-1;const s=Ge(e).map(a=>a.name===t&&(r++,r===n)?o(a):a);return{...e,children:s}}function Ei(e,t,n){let o=-1;const r=Ge(e);for(let s=0;s0?nt(e,r,r.sections.length-1,_=>({..._,children:[...Ge(_),y]})):{...e,children:[...Ge(e),y]}}const s=Math.max(-1,Math.min(n,r.rows.length-1)),a=s<0?r.rows[0]:r.rows[s],l=a.cells[0]?.gridRow??s,d=s<0?0:l+1,c=a.sectionIndex,p=s<0?0:a.rowIndexInSection+1,f=[],b=[];let g=0;for(;g0?Ve(r,d-1,g):null;y&&y.gridRow+y.rowSpan>d&&y.rowSpan>1?(b.push(y),g+=y.colSpan):(f.push($i(o)),g+=1)}let m=e;for(const y of b)m=nt(m,r,y.sectionIndex,_=>bt(_,o.row,y.rowIndexInSection,w=>({...w,children:Ge(w).map((k,x)=>x===y.cellIndexInRow?mn(k,o.rowSpanProp,y.rowSpan+1):k)})));const h={type:"basic",name:o.row,children:f},v=Pe(m,t);return m=nt(m,v,c,y=>{const _=Ge(y);let w=0,k=_.length;for(let x=0;x<_.length;x++)if(_[x].name===o.row){if(w===p){k=x;break}w++}return{...y,children:[..._.slice(0,k),h,..._.slice(k)]}}),m}function sh(e,t,n){const o=yt(t),r=Pe(e,t);if(n<0||n>=r.rows.length||r.rows.length<=1)return e;const s=r.rows[n],a=s.cells[0]?.gridRow??n;let l=e;const d=new Set;for(let p=0;pbt(b,o.row,f.rowIndexInSection,g=>({...g,children:Ge(g).map((m,h)=>h===f.cellIndexInRow?mn(m,o.rowSpanProp,f.rowSpan-1):m)})))),p+=f?f.colSpan:1}const c=Pe(l,t);return l=nt(l,c,s.sectionIndex,p=>{let f=-1;const b=Ge(p).filter(g=>g.name===o.row?(f++,f!==s.rowIndexInSection):!0);return{...p,children:b}}),l}function ah(e,t,n,o){const r=yt(t),s=Pe(e,t);if(!Si(s,n,o).ok)return e;const a=ih(s),l=a.findIndex(h=>n>=h.start&&ns.rows.filter(v=>{const y=v.cells[0]?.gridRow??-1;return v.sectionIndex===f&&y>=h.start&&yv.rowIndexInSection),g=b(c),m=b(p);return g.length===0||m.length===0?e:nt(e,s,f,h=>{const v=[...Ge(h)],y=[];v.forEach((M,O)=>{M.name===r.row&&y.push(O)});const _=g.map(M=>y[M]).filter(M=>M!==void 0),w=m.map(M=>y[M]).filter(M=>M!==void 0);if(_.length===0||w.length===0)return h;const k=_.map(M=>v[M]),x=w.map(M=>v[M]),$=Math.min(..._)n>=m.start&&nk.gridCol>=f.start&&k.gridColk.gridCol>=b.start&&k.gridColk.cellIndexInRow),_=v.map(k=>k.cellIndexInRow),w=Pe(g,t);g=nt(g,w,m.sectionIndex,k=>bt(k,r.row,m.rowIndexInSection,x=>{const $=[...Ge(x)],S=y.map(M=>Ei(x,r,M)).filter(M=>M>=0),C=_.map(M=>Ei(x,r,M)).filter(M=>M>=0);if(S.length===0||C.length===0)return x;const T=S.map(M=>$[M]),E=C.map(M=>$[M]),A=Math.min(...S,...C),N=Math.max(...S,...C),D=[...E,...T],B=[...$.slice(0,A),...D,...$.slice(N+1)];return{...x,children:B}}))}return g}function dh(e,t,n){const o=yt(t),r=Pe(e,t);if(r.rows.length===0||r.colCount===0)return sl(e,t,-1);const s=Math.max(0,Math.min(n+1,r.colCount));let a=e;const l=new Set;for(const d of r.rows){const c=d.cells[0]?.gridRow??0,p=s>0?Ve(r,c,s-1):null,f=s1){if(!l.has(p.cell)){l.add(p.cell);const h=Pe(a,t);a=nt(a,h,p.sectionIndex,v=>bt(v,o.row,p.rowIndexInSection,y=>({...y,children:Ge(y).map((_,w)=>w===p.cellIndexInRow?mn(_,o.colSpanProp,p.colSpan+1):_)})))}continue}if(p&&p.gridRow0&&d.cells.every(h=>h.isHeader),m=Pe(a,t);a=nt(a,m,d.sectionIndex,h=>bt(h,o.row,d.rowIndexInSection,v=>{const y=[...Ge(v)];let _;if(b<0)_=y.findIndex(w=>ir(w,o)),_<0&&(_=y.length);else{const w=Ei(v,o,b);_=w<0?y.length:w+1}return y.splice(_,0,$i(o,void 0,g)),{...v,children:y}}))}return a}function ch(e,t,n){const o=yt(t),r=Pe(e,t);if(n<0||n>=r.colCount||r.colCount<=1)return e;let s=e;const a=new Set;for(const l of r.rows){const d=l.cells[0]?.gridRow??0,c=Ve(r,d,n);if(!(!c||a.has(c.cell)||c.gridRow1){const p=Pe(s,t);s=nt(s,p,c.sectionIndex,f=>bt(f,o.row,c.rowIndexInSection,b=>({...b,children:Ge(b).map((g,m)=>m===c.cellIndexInRow?mn(g,o.colSpanProp,c.colSpan-1):g)})))}else{const p=Pe(s,t);s=nt(s,p,c.sectionIndex,f=>bt(f,o.row,c.rowIndexInSection,b=>{let g=-1;const m=Ge(b).filter(h=>ir(h,o)?(g++,g!==c.cellIndexInRow):!0);return{...b,children:m}}))}}return s}function al(e,t,n,o,r,s){const a=yt(t),l=Pe(e,t),d=Math.min(n,r),c=Math.max(n,r),p=Math.min(o,s),f=Math.max(o,s);if(d===c&&p===f)return{table:e,ok:!1,reason:"single"};if(!l.valid)return{table:e,ok:!1,reason:"invalid-grid"};const b=new Set;for(let y=d;y<=c;y++)for(let _=p;_<=f;_++){const w=Ve(l,y,_);if(!w)return{table:e,ok:!1,reason:"hole"};if(w.gridRowc||w.gridCol+w.colSpan-1>f)return{table:e,ok:!1,reason:"not-rectangular"};b.add(w)}const g=Ve(l,d,p),m=Array.from(b).filter(y=>y!==g);let h=nt(e,l,g.sectionIndex,y=>bt(y,a.row,g.rowIndexInSection,_=>({..._,children:Ge(_).map((w,k)=>{if(k!==g.cellIndexInRow)return w;let x=mn(w,a.colSpanProp,f-p+1);return x=mn(x,a.rowSpanProp,c-d+1),x})})));const v=new Map;for(const y of m){const _=`${y.sectionIndex}:${y.rowIndexInSection}`,w=v.get(_)??[];w.push(y),v.set(_,w)}for(const[y,_]of v){const w=parseInt(y.split(":")[0],10),k=_[0].rowIndexInSection,x=new Set(_.map(S=>S.cellIndexInRow)),$=Pe(h,t);h=nt(h,$,w,S=>bt(S,a.row,k,C=>{let T=-1;const E=Ge(C).filter(A=>ir(A,a)?(T++,!x.has(T)):!0);return{...C,children:E}}))}return{table:h,ok:!0}}function uh(e,t,n,o){const r=yt(t),s=Pe(e,t),a=Ve(s,n,o);if(!a||a.colSpan<=1&&a.rowSpan<=1)return e;const l=a.gridRow,d=a.gridCol,c=a.gridRow+a.rowSpan-1,p=a.gridCol+a.colSpan-1,f=a.isHeader,b=typeof a.cell.props?.className=="string"?a.cell.props.className:void 0;let g=nt(e,s,a.sectionIndex,m=>bt(m,r.row,a.rowIndexInSection,h=>({...h,children:Ge(h).map((v,y)=>{if(y!==a.cellIndexInRow)return v;let _=mn(v,r.colSpanProp,1);return _=mn(_,r.rowSpanProp,1),_})})));for(let m=l;m<=c;m++)for(let h=d;h<=p;h++){if(m===l&&h===d)continue;const v=Pe(g,t),y=v.rows.find(k=>k.cells.some(x=>x.gridRow===m))??v.rows[m];if(!y)continue;let _=-1;for(const k of y.cells)k.gridRow===m&&k.gridColbt(k,r.row,y.rowIndexInSection,x=>{const $=[...Ge(x)];let S;if(_<0)S=$.findIndex(C=>ir(C,r)),S<0&&(S=$.length);else{const C=Ei(x,r,_);S=C<0?$.length:C+1}return $.splice(S,0,$i(r,w,f)),{...x,children:$}}))}return g}function Ii(e,t,n,o,r){const s=yt(t),a=Pe(e,t),l=Ve(a,n,o);return l?nt(e,a,l.sectionIndex,d=>bt(d,s.row,l.rowIndexInSection,c=>({...c,children:Ge(c).map((p,f)=>{if(f!==l.cellIndexInRow)return p;const b={...p.props??{}};r.trim()===""?delete b.className:b.className=r;const g={...p,props:b};return Object.keys(b).length===0&&delete g.props,g})}))):e}function Jt(e,t,n,o,r,s){const a=yt(t),l=Pe(e,t),d=Ve(l,n,o);return d?nt(e,l,d.sectionIndex,c=>bt(c,a.row,d.rowIndexInSection,p=>({...p,children:Ge(p).map((f,b)=>{if(b!==d.cellIndexInRow)return f;const g={...f.props??{}},m={...g.style??{}};!s||s.trim()===""?delete m[r]:m[r]=s,Object.keys(m).length===0?delete g.style:g.style=m;const h={...f,props:g};return Object.keys(g).length===0&&delete h.props,h})}))):e}function ho(e,t,n,o,r,s,a){const l=yt(t),d=Pe(e,t),c=Ve(d,n,o);if(!c)return e;const p=a==="dark";return nt(e,d,c.sectionIndex,f=>bt(f,l.row,c.rowIndexInSection,b=>({...b,children:Ge(b).map((g,m)=>{if(m!==c.cellIndexInRow)return g;const h={...g.props??{}},v=typeof h.className=="string"?h.className:"",y=mC(v,s,r,p);y===""?delete h.className:h.className=y;const _={...g,props:h};return Object.keys(h).length===0&&delete _.props,_})})))}function ph(e,t,n,o,r){const s=yt(t),a=Pe(e,t),l=Ve(a,n,o);return l?nt(e,a,l.sectionIndex,d=>bt(d,s.row,l.rowIndexInSection,c=>({...c,children:Ge(c).map((p,f)=>f===l.cellIndexInRow?{...p,text:r}:p)}))):e}function fh(e,t,n,o,r){const s=yt(t),a=Pe(e,t),l=Ve(a,n,o);return l?nt(e,a,l.sectionIndex,d=>bt(d,s.row,l.rowIndexInSection,c=>({...c,children:Ge(c).map((p,f)=>f===l.cellIndexInRow?r:p)}))):e}const gh=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function zz(e){return e.split(/\s+/).filter(Boolean)}function hh(e,t){for(const n of t)if(e===n||/^-?\d+$/.test(e.slice(n.length+1))&&e.startsWith(n+"-"))return!0;return!1}function yh({className:e,catalog:t,t:n,onChange:o,colorScheme:r="light",onPresetToken:s,colorStyle:a,onColorStyle:l,disabled:d}){const c=t?.sides??[],p=t?.widths??[],f=t?.colors??[],b=r==="dark",g=u.useMemo(()=>c.map(E=>E.prefix),[c]),m=u.useMemo(()=>new Set(f.map(E=>E.token)),[f]),h=u.useMemo(()=>zz(e),[e]),v=u.useMemo(()=>Gr(e,b),[e,b]),y=u.useMemo(()=>v.find(E=>m.has(E))??null,[v,m]),_=u.useMemo(()=>{const E=new Set;for(const A of c)h.some(D=>D===A.prefix||D.startsWith(A.prefix+"-")&&/^-?\d+$/.test(D.slice(A.prefix.length+1)))&&E.add(A.value);return E},[h,c]),w=u.useMemo(()=>{const E=h.find(N=>hh(N,g));if(!E)return"none";const A=p.filter(N=>N.value!=="none");for(const N of c){if(E===N.prefix)return A.find(D=>(D.suffix??"")==="")?.value??"thin";if(E.startsWith(N.prefix+"-")){const D=E.slice(N.prefix.length),B=A.find(M=>(M.suffix??"")===D);if(B)return B.value}}return"thin"},[h,g,c,p]);if(!t||c.length===0||p.length===0)return null;function k(E){return E.filter(A=>!hh(A,g))}function x(E,A){const N=k(h),D=p.find(O=>O.value===A);if(!D||A==="none"||E.size===0)return N.join(" ").trim();const B=D.suffix??"",M=[...N];for(const O of c)E.has(O.value)&&M.push(B?`${O.prefix}${B}`:O.prefix);return M.join(" ").trim()}const $=E=>{const A=new Set(_);A.has(E)?A.delete(E):(E==="all"?A.clear():A.delete("all"),A.add(E));const N=w==="none"?p.find(D=>D.value!=="none")?.value??"thin":w;o(x(A,N))},S=E=>{const A=_.size===0?new Set(["all"]):_;o(x(A,E))},C=E=>{s?.(E)},T=(E,A)=>E&&E.startsWith("$t:")?n(E.slice(3)):E||A;return i.jsxs("div",{className:"g7le-cell-border","data-testid":"g7le-cell-border",style:Nz,children:[i.jsx("div",{style:Mz,children:i.jsx("span",{style:Lz,children:n("layout_editor.table_editor.cell_border")})}),i.jsx("div",{style:ll,"data-testid":"g7le-cell-border-widths",children:p.map(E=>i.jsx("button",{type:"button",disabled:d,"data-testid":`g7le-cell-border-width-${E.value}`,"aria-pressed":w===E.value,onClick:()=>S(E.value),style:w===E.value?bh:dl,children:T(E.label,E.value)},E.value))}),w!=="none"&&i.jsx("div",{style:ll,"data-testid":"g7le-cell-border-sides",children:c.map(E=>i.jsx("button",{type:"button",disabled:d,"data-testid":`g7le-cell-border-side-${E.value}`,"aria-pressed":_.has(E.value),onClick:()=>$(E.value),style:_.has(E.value)?bh:dl,children:T(E.label,E.value)},E.value))}),w!=="none"&&(f.length>0||l)&&i.jsx(i.Fragment,{children:i.jsxs("div",{style:ll,"data-testid":"g7le-cell-border-colors",children:[f.map(E=>{const A=y===E.token;return i.jsx("button",{type:"button",disabled:d,title:T(E.label,E.value),"data-testid":`g7le-cell-border-color-${E.value}`,"aria-pressed":A,onClick:()=>C(E.token),style:{...mh,background:E.swatch??"#fff",outline:A?"2px solid #2563eb":"1px solid #cbd5e1"}},E.value)}),l&&(()=>{const E=!!a&&f.some(N=>N.swatch&&N.swatch.toLowerCase()===a.toLowerCase()),A=!b&&!!a&&!E;return i.jsx("label",{title:n(b?"layout_editor.table_editor.dark_free_color_hint":"layout_editor.table_inplace.custom_color"),"data-testid":"g7le-cell-border-color-custom",style:{...mh,position:"relative",overflow:"hidden",display:"inline-flex",alignItems:"center",justifyContent:"center",background:A&&gh.test(a)?a:"conic-gradient(red, yellow, lime, aqua, blue, magenta, red)",outline:A?"2px solid #2563eb":"1px solid #cbd5e1",opacity:b?.4:1,cursor:b?"not-allowed":"pointer"},children:i.jsx("input",{type:"color",disabled:d||b,"data-testid":"g7le-cell-border-color-picker",value:a&&gh.test(a)?a:"#000000",onChange:N=>l(N.target.value),style:{position:"absolute",width:0,height:0,opacity:0}})})})()]})})]})}const Nz={display:"flex",flexDirection:"column",gap:6},Mz={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},Lz={fontSize:12,fontWeight:600,color:"#475569"},ll={display:"flex",gap:4,flexWrap:"wrap",alignItems:"center"},dl={padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},bh={...dl,border:"1px solid #2563eb",background:"#eff6ff",color:"#1d4ed8",fontWeight:600},mh={width:22,height:22,borderRadius:5,padding:0,cursor:"pointer",boxSizing:"border-box"},vh=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function _h({colorStyle:e,className:t,catalog:n,t:o,colorScheme:r="light",onPresetToken:s,onCustomColor:a,onClear:l,disabled:d}){const c=n?.colors??[],p=r==="dark",f=e??"",b=Gr(t??"",p),g=c.find(_=>_.token&&b.includes(_.token))?.token??null,m=(_,w)=>_&&_.startsWith("$t:")?o(_.slice(3)):_||w,h=!g&&(p||f.trim()===""),v=!!f&&c.some(_=>_.swatch&&_.swatch.toLowerCase()===f.toLowerCase()),y=!p&&!!f&&!v;return i.jsxs("div",{className:"g7le-cell-fill","data-testid":"g7le-cell-fill",style:Pz,children:[i.jsx("div",{style:Oz,children:i.jsx("span",{style:Bz,children:o("layout_editor.table_editor.cell_fill")})}),i.jsxs("div",{style:Wz,"data-testid":"g7le-cell-fill-colors",children:[i.jsx("button",{type:"button",disabled:d,title:o("layout_editor.table_editor.cell_fill_none"),"data-testid":"g7le-cell-fill-none","aria-pressed":h,onClick:()=>l?.(),style:{...cl,background:"repeating-conic-gradient(#e2e8f0 0% 25%, #ffffff 0% 50%) 50% / 10px 10px",outline:h?"2px solid #2563eb":"1px solid #cbd5e1"}}),c.map(_=>{const w=!!_.token&&g===_.token,k=!p&&!!_.swatch&&f.toLowerCase()===(_.swatch??"").toLowerCase(),x=w||k,$=d||p&&!_.token;return i.jsx("button",{type:"button",disabled:$,title:m(_.label,_.value),"data-testid":`g7le-cell-fill-color-${_.value}`,"aria-pressed":x,onClick:()=>{_.token&&s?s(_.token):!p&&_.swatch&&a&&a(_.swatch)},style:{...cl,background:_.swatch??"#fff",outline:x?"2px solid #2563eb":"1px solid #cbd5e1",opacity:$?.4:1,cursor:$?"not-allowed":"pointer"}},_.value)}),a&&i.jsx("label",{title:o(p?"layout_editor.table_editor.dark_free_color_hint":"layout_editor.table_editor.cell_fill_custom"),"data-testid":"g7le-cell-fill-custom",style:{...cl,position:"relative",overflow:"hidden",display:"inline-flex",alignItems:"center",justifyContent:"center",background:y&&vh.test(f)?f:"conic-gradient(red, yellow, lime, aqua, blue, magenta, red)",outline:y?"2px solid #2563eb":"1px solid #cbd5e1",opacity:p?.4:1,cursor:p?"not-allowed":"pointer"},children:i.jsx("input",{type:"color",disabled:d||p,"data-testid":"g7le-cell-fill-color-picker",value:f&&vh.test(f)?f:"#ffffff",onChange:_=>a(_.target.value),style:{position:"absolute",width:0,height:0,opacity:0}})})]})]})}const Pz={display:"flex",flexDirection:"column",gap:6},Oz={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},Bz={fontSize:12,fontWeight:600,color:"#475569"},Wz={display:"flex",gap:4,flexWrap:"wrap",alignItems:"center"},cl={width:22,height:22,borderRadius:5,padding:0,cursor:"pointer",boxSizing:"border-box"};function jz(e){const t=/^(\d+)px$/.exec(e.trim());return t?parseInt(t[1],10):null}function xh({paddingStyle:e,catalog:t,t:n,onChange:o,disabled:r}){const s=t?.steps??[],a=e??"",l=jz(a),d=(h,v)=>h&&h.startsWith("$t:")?n(h.slice(3)):h||v,c=s.some(h=>(h.px??0)===(l??-1)),p=l!==null&&!c?String(l):"",[f,b]=u.useState(p);u.useEffect(()=>{b(p)},[e]);const g=h=>{o(h&&h>0?`${h}px`:""),b("")},m=h=>{const v=parseInt(h,10);Number.isFinite(v)&&v>=0&&o(v>0?`${v}px`:"")};return i.jsxs("div",{className:"g7le-cell-padding","data-testid":"g7le-cell-padding",style:Hz,children:[i.jsx("div",{style:Fz,children:n("layout_editor.table_editor.cell_padding")}),i.jsxs("div",{style:Kz,"data-testid":"g7le-cell-padding-steps",children:[s.map(h=>{const v=(h.px??0)===(l??-1)||!h.px&&a.trim()==="";return i.jsx("button",{type:"button",disabled:r,"data-testid":`g7le-cell-padding-step-${h.value}`,"aria-pressed":v,onClick:()=>g(h.px),style:v?Vz:wh,children:d(h.label,h.value)},h.value)}),i.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3},children:[i.jsx("input",{type:"number",min:0,disabled:r,"data-testid":"g7le-cell-padding-free",value:f,placeholder:n("layout_editor.table_editor.cell_padding_custom"),onChange:h=>b(h.target.value),onBlur:()=>f.trim()!==""&&m(f),onKeyDown:h=>{h.key==="Enter"&&f.trim()!==""&&m(f)},style:Uz}),i.jsx("span",{style:{fontSize:11,color:"#94a3b8"},children:"px"})]})]})]})}const Hz={display:"flex",flexDirection:"column",gap:6},Fz={fontSize:12,fontWeight:600,color:"#475569"},Kz={display:"flex",gap:4,flexWrap:"wrap",alignItems:"center"},wh={padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},Vz={...wh,border:"1px solid #2563eb",background:"#eff6ff",color:"#1d4ed8",fontWeight:600},Uz={width:48,padding:"3px 5px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"};function kh({colorScheme:e,onChange:t,t:n,disabled:o}){const r=e==="dark";return i.jsxs("div",{className:"g7le-color-scheme-tabs","data-testid":"g7le-color-scheme-tabs",style:qz,children:[i.jsxs("div",{style:Gz,children:[i.jsx("span",{style:Yz,children:n("layout_editor.table_editor.cell_color")}),i.jsxs("div",{style:Xz,children:[i.jsx("button",{type:"button",disabled:o,"data-testid":"g7le-color-scheme-light","aria-pressed":!r,onClick:()=>t("light"),style:r?ul:Sh,children:n("layout_editor.property_modal.scope.scheme_light")}),i.jsx("button",{type:"button",disabled:o,"data-testid":"g7le-color-scheme-dark","aria-pressed":r,onClick:()=>t("dark"),style:r?Sh:ul,children:n("layout_editor.property_modal.scope.scheme_dark")})]})]}),r&&i.jsx("div",{style:Jz,"data-testid":"g7le-color-scheme-dark-hint",children:n("layout_editor.table_editor.dark_free_color_hint")})]})}const qz={display:"flex",flexDirection:"column",gap:3},Gz={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},Yz={fontSize:12,fontWeight:700,color:"#0f172a"},Xz={display:"flex",gap:2},ul={padding:"2px 9px",fontSize:11,border:"none",borderBottom:"2px solid transparent",background:"transparent",color:"#94a3b8",cursor:"pointer"},Sh={...ul,color:"#1d4ed8",borderBottom:"2px solid #2563eb",fontWeight:600},Jz={fontSize:10,color:"#94a3b8",fontStyle:"italic"},pl="dark:";function Ch(e){return typeof e=="string"?e.split(/\s+/).filter(Boolean):[]}function $h(e,t){return t==="dark"?e.filter(n=>n.startsWith(pl)).map(n=>n.slice(pl.length)):e.filter(n=>!n.startsWith(pl))}const Zz={none:0,thin:1,medium:2,thick:4},Eh={top:{w:"borderTopWidth",s:"borderTopStyle",c:"borderTopColor"},bottom:{w:"borderBottomWidth",s:"borderBottomStyle",c:"borderBottomColor"},left:{w:"borderLeftWidth",s:"borderLeftStyle",c:"borderLeftColor"},right:{w:"borderRightWidth",s:"borderRightStyle",c:"borderRightColor"}},Ih=["top","bottom","left","right"];function Qz(e,t,n="light"){if(!e||!t)return{};const o=t.sides??[],r=t.widths??[],s=t.colors??[],a=Ch(e.props?.className);if(a.length===0&&!e.props?.style)return{};const l=[...r].filter(y=>y.value!=="none").sort((y,_)=>(_.suffix??"").length-(y.suffix??"").length),d={};for(const y of o)for(const _ of l){const w=_.suffix?`${y.prefix}${_.suffix}`:y.prefix;if(a.includes(w)){d[y.value]=_.value;break}}const c=e.props?.style??{},p=$h(a,n),f=s.find(y=>p.includes(y.token))?.swatch??"",g=(n==="light"&&typeof c.borderColor=="string"?c.borderColor:"")||f||"#94a3b8",m=y=>{const _=Eh[y]?.c,w=_?c[_]:void 0;return typeof w=="string"&&w?w:g},h={},v=(y,_)=>{const w=Eh[y];if(!w)return;const k=Zz[_]??1;h[w.w]=`${k}px`,h[w.s]=k>0?"solid":"none",k>0&&(h[w.c]=m(y))};if(d.all)for(const y of Ih)v(y,d.all);for(const y of Ih)d[y]&&v(y,d[y]);return h}function Rz(e,t,n="light"){if(!e?.props)return{};const o=e.props.style??{},r={},s=Ch(e.props.className),a=t?.colors?.find(c=>c.token&&$h(s,n).includes(c.token))?.swatch??"",d=(n==="light"&&typeof o.backgroundColor=="string"?o.backgroundColor:"")||a;return d&&(r.backgroundColor=d),typeof o.padding=="string"&&o.padding&&(r.padding=o.padding),r}const eN=/^\s*\$t:(custom\.[a-zA-Z0-9._-]+)\s*$/,tN=/^\s*\$t:([a-zA-Z0-9._-]+)\s*$/,nN=/\{\{.*?\}\}/;function Ah(e,t,n){const o=e?.text;if(typeof o!="string")return{display:"",editable:!1,isKey:!1};const r=vt(o);if(r&&r.key.startsWith("custom.")){let a="";try{const l=Pt.getInstance().translate(r.key,{templateId:t,locale:n});a=l&&l!==r.key?l:""}catch{a=""}return{display:a,editable:!0,isKey:!0}}if(nN.test(o))return{display:o,editable:!1,isKey:!1};const s=tN.exec(o);if(s){const a=s[1];let l="";try{const d=Pt.getInstance().translate(a,{templateId:t,locale:n});l=d&&d!==a?d:""}catch{l=""}return{display:l,editable:!0,isKey:!0}}return{display:o,editable:!0,isKey:!1}}function fl(e){const t=or(e);return t===null?{node:null,path:null}:{node:ki(e,t),path:t}}function oN(e){if(!e||typeof e.text!="string")return null;const t=eN.exec(e.text);if(t)return t[1];const n=vt(e.text);return n&&n.key.startsWith("custom.")?n.key:null}function rN({node:e,params:t,t:n,onPatchNode:o,templateIdentifier:r,candidates:s}){const{state:a}=Qe(),l=a.selectedRoute?.layoutName??null,d=a.locale,c=r??a.templateIdentifier,p=u.useMemo(()=>t&&typeof t=="object"?t:null,[t]);u.useMemo(()=>yt(p),[p]);const f=u.useMemo(()=>Pe(e,p),[e,p]),b=u.useMemo(()=>{const U=p?.cellBorder;return U&&typeof U=="object"?U:null},[p]),g=u.useMemo(()=>{const U=p?.cellBackground;return U&&typeof U=="object"?U:null},[p]),m=u.useMemo(()=>{const U=p?.cellPadding;return U&&typeof U=="object"?U:null},[p]),[h,v]=u.useState(null),[y,_]=u.useState(null),[w,k]=u.useState({}),[x,$]=u.useState(!1),[S,C]=u.useState(null),[T,E]=u.useState(null),[A,N]=u.useState("light"),D=u.useCallback(U=>o(U),[o]),B=u.useMemo(()=>h?Ve(f,h.r,h.c):null,[f,h]),M=T!==null?T:h?.c??null,O=S!==null?S:h?.r??null,z=u.useMemo(()=>{const U=(b?.sides??[]).find(xe=>xe.value==="all")??(b?.sides??[])[0],ue=(b?.widths??[]).find(xe=>xe.value!=="none");if(!U||!ue)return[];const fe=ue.suffix??"";return[fe?`${U.prefix}${fe}`:U.prefix]},[b]),H=u.useCallback((U,ue,fe)=>{if(z.length===0)return U;const xe=(b?.sides??[]).map(Q=>Q.prefix),he=Ve(Pe(U,p),ue,fe),ne=(typeof he?.cell?.props?.className=="string"?he.cell.props.className:"").split(/\s+/).filter(Boolean);return ne.some(Q=>xe.some(ae=>Q===ae||Q.startsWith(ae+"-")&&/^-?\d+$/.test(Q.slice(ae.length+1))))?U:Ii(U,p,ue,fe,[...ne,...z].join(" ").trim())},[z,b,p]),P=u.useCallback(U=>{if(!h)return;const ue=Math.min(h.r,y?.r??h.r),fe=Math.max(h.r,y?.r??h.r),xe=Math.min(h.c,y?.c??h.c),he=Math.max(h.c,y?.c??h.c),j=new Set,ne=[];for(let Q=ue;Q<=fe;Q++)for(let ae=xe;ae<=he;ae++)j.add(`${Q}:${ae}`),ne.push({r:Q,c:ae});let pe=e;for(const Q of ne){if(pe=H(pe,Q.r,Q.c),pe=Jt(pe,p,Q.r,Q.c,"borderColor",U),Q.r>0&&!j.has(`${Q.r-1}:${Q.c}`)){const ae=Ve(Pe(pe,p),Q.r-1,Q.c);ae&&(pe=Jt(pe,p,ae.gridRow,ae.gridCol,"borderBottomColor",U))}if(Q.c>0&&!j.has(`${Q.r}:${Q.c-1}`)){const ae=Ve(Pe(pe,p),Q.r,Q.c-1);ae&&(pe=Jt(pe,p,ae.gridRow,ae.gridCol,"borderRightColor",U))}}D(pe)},[h,y,e,p,D,H]),I=u.useCallback(U=>P(U),[P]),L=u.useMemo(()=>(b?.colors??[]).map(U=>U.token).filter(Boolean),[b]),F=u.useCallback(U=>{if(!h||L.length===0)return;const ue=Math.min(h.r,y?.r??h.r),fe=Math.max(h.r,y?.r??h.r),xe=Math.min(h.c,y?.c??h.c),he=Math.max(h.c,y?.c??h.c);let j=e;for(let ne=ue;ne<=fe;ne++)for(let pe=xe;pe<=he;pe++)j=H(j,ne,pe),j=ho(j,p,ne,pe,U,L,A);D(j)},[h,y,e,p,D,H,L,A]),Y=u.useMemo(()=>{if(A==="dark")return"";const U=B?.cell.props?.style;return typeof U?.borderColor=="string"?U.borderColor:""},[B,A]),K=u.useCallback((U,ue)=>{if(!h)return;const fe=Math.min(h.r,y?.r??h.r),xe=Math.max(h.r,y?.r??h.r),he=Math.min(h.c,y?.c??h.c),j=Math.max(h.c,y?.c??h.c);let ne=e;for(let pe=fe;pe<=xe;pe++)for(let Q=he;Q<=j;Q++)ne=Jt(ne,p,pe,Q,U,ue);D(ne)},[h,y,e,p,D]),X=u.useMemo(()=>(g?.colors??[]).map(U=>U.token).filter(U=>!!U),[g]),Z=u.useCallback(()=>h?{r0:Math.min(h.r,y?.r??h.r),r1:Math.max(h.r,y?.r??h.r),c0:Math.min(h.c,y?.c??h.c),c1:Math.max(h.c,y?.c??h.c)}:null,[h,y]),se=u.useCallback(U=>{const ue=Z();if(!ue||X.length===0)return;let fe=e;for(let xe=ue.r0;xe<=ue.r1;xe++)for(let he=ue.c0;he<=ue.c1;he++)fe=ho(fe,p,xe,he,U,X,A);D(fe)},[Z,e,p,D,X,A]),oe=u.useCallback(U=>K("backgroundColor",U),[K]),G=u.useCallback(()=>{const U=Z();if(!U)return;let ue=e;for(let fe=U.r0;fe<=U.r1;fe++)for(let xe=U.c0;xe<=U.c1;xe++)ue=ho(ue,p,fe,xe,void 0,X,A),A==="light"&&(ue=Jt(ue,p,fe,xe,"backgroundColor",void 0));D(ue)},[Z,e,p,D,X,A]),ee=u.useCallback(U=>K("padding",U),[K]),ge=u.useMemo(()=>{if(A==="dark")return"";const U=B?.cell.props?.style;return typeof U?.backgroundColor=="string"?U.backgroundColor:""},[B,A]),V=u.useMemo(()=>typeof B?.cell.props?.className=="string"?B.cell.props.className:"",[B]),te=u.useMemo(()=>{const U=B?.cell.props?.style;return typeof U?.padding=="string"?U.padding:""},[B]),be=u.useCallback(U=>U==="section"?n("layout_editor.table_editor.move_blocked_section"):"",[n]),Ee=u.useCallback((U,ue)=>Si(f,U,ue),[f]),De=u.useCallback((U,ue)=>Ci(f,U,ue),[f]),Se=u.useCallback(U=>D(sl(e,p,U)),[e,p,D]),Ue=u.useCallback(U=>{D(sh(e,p,U)),v(null),_(null)},[e,p,D]),Me=u.useCallback((U,ue)=>D(ah(e,p,U,ue)),[e,p,D]),Oe=u.useCallback(U=>D(dh(e,p,U)),[e,p,D]),Ye=u.useCallback(U=>{D(ch(e,p,U)),v(null),_(null)},[e,p,D]),ze=u.useCallback((U,ue)=>D(lh(e,p,U,ue)),[e,p,D]),Xe=u.useCallback(()=>{if(!h||!y)return;const U=al(e,p,h.r,h.c,y.r,y.c);U.ok&&(D(U.table),v({r:Math.min(h.r,y.r),c:Math.min(h.c,y.c)}),_(null))},[e,p,h,y,D]),ve=u.useCallback(()=>{h&&(D(uh(e,p,h.r,h.c)),_(null))},[e,p,h,D]),qe=u.useCallback(U=>{if(!h)return;const ue=Math.min(h.r,y?.r??h.r),fe=Math.max(h.r,y?.r??h.r),xe=Math.min(h.c,y?.c??h.c),he=Math.max(h.c,y?.c??h.c);let j=e;for(let ne=ue;ne<=fe;ne++)for(let pe=xe;pe<=he;pe++)j=Ii(j,p,ne,pe,U);D(j)},[e,p,h,y,D]),We=u.useCallback(async(U,ue)=>{const fe=`${U}:${ue}`,xe=w[fe];if(xe===void 0)return;const he=Ve(f,U,ue);if(!he)return;const{node:j,path:ne}=fl(he.cell);if(ne===null)return;const pe=Ah(j,c,d);if(pe.editable){if(xe===pe.display){k(Q=>{const ae={...Q};return delete ae[fe],ae});return}$(!0);try{const Q=oN(j);if(Q)await vr(c,Q,d,xe),await tn(c,d);else{const ae=await qn(c,l,d,xe);if(ae.kind==="ok"&&ae.resource){const Ae=`$t:${ae.resource.translation_key}`;if(ne.length===0)D(ph(e,p,U,ue,Ae));else{const dt=rr(he.cell,ne,Ae);D(fh(e,p,U,ue,dt))}await tn(c,d)}}}finally{$(!1),k(Q=>{const ae={...Q};return delete ae[fe],ae})}}},[w,f,c,d,l,e,p,D]),ce=u.useMemo(()=>{if(!B)return null;const{node:U,path:ue}=fl(B.cell);return ue===null?null:{value:typeof U?.text=="string"?U.text:"",editable:!0}},[B]),q=u.useCallback(U=>{if(typeof U!="string"||U.length===0||!h)return;const ue=Ve(f,h.r,h.c);if(!ue)return;const fe=or(ue.cell);if(fe!==null)if(fe.length===0)D(ph(e,p,h.r,h.c,U));else{const xe=rr(ue.cell,fe,U);D(fh(e,p,h.r,h.c,xe))}},[h,f,e,p,D]),re=u.useCallback((U,ue,fe)=>{fe?_({r:U,c:ue}):(v({r:U,c:ue}),_(null))},[]),ie=u.useMemo(()=>Array.from({length:f.colCount},(U,ue)=>ue),[f.colCount]),me=!!(h&&y&&(h.r!==y.r||h.c!==y.c)),Ce=!!(B&&(B.colSpan>1||B.rowSpan>1)),$e=B&&typeof B.cell.props?.className=="string"?B.cell.props.className:"";return i.jsxs("div",{className:"g7le-node-editor g7le-node-editor--table","data-testid":"g7le-table-editor",style:iN,children:[i.jsx("div",{style:sN,children:n("layout_editor.table_editor.title")}),i.jsx("div",{style:{overflowX:"auto"},children:i.jsxs("table",{"data-testid":"g7le-table-editor-grid",style:aN,children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{style:lN}),ie.map(U=>{const ue=De(U,-1),fe=De(U,1),xe=M===U;return i.jsx("th",{style:dN,"data-testid":`g7le-table-colgutter-${U}`,onMouseEnter:()=>E(U),onMouseLeave:()=>E(he=>he===U?null:he),children:i.jsxs("div",{style:{...uN,visibility:xe?"visible":"hidden"},children:[i.jsx("button",{type:"button",title:ue.ok?n("layout_editor.table_editor.move_col_left"):be(ue.reason)||n("layout_editor.table_editor.move_col_left"),disabled:!ue.ok||x,onClick:()=>ze(U,-1),"data-testid":`g7le-table-col-left-${U}`,style:ue.ok?vn:Ai,children:"←"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.add_col"),disabled:x,onClick:()=>Oe(U),"data-testid":`g7le-table-col-add-${U}`,style:vn,children:"+"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.remove_col"),disabled:f.colCount<=1||x,onClick:()=>Ye(U),"data-testid":`g7le-table-col-remove-${U}`,style:Th,children:"✕"}),i.jsx("button",{type:"button",title:fe.ok?n("layout_editor.table_editor.move_col_right"):be(fe.reason)||n("layout_editor.table_editor.move_col_right"),disabled:!fe.ok||x,onClick:()=>ze(U,1),"data-testid":`g7le-table-col-right-${U}`,style:fe.ok?vn:Ai,children:"→"})]})},U)})]})}),i.jsx("tbody",{children:f.rows.map((U,ue)=>{const fe=U.cells[0]?.gridRow??ue,xe=O===fe;return i.jsxs("tr",{"data-testid":`g7le-table-row-${fe}`,onMouseEnter:()=>C(fe),onMouseLeave:()=>C(he=>he===fe?null:he),children:[i.jsx("td",{style:cN,"data-testid":`g7le-table-rowgutter-${fe}`,children:(()=>{const he=Ee(fe,-1),j=Ee(fe,1);return i.jsxs("div",{style:{...pN,visibility:xe?"visible":"hidden"},children:[i.jsx("button",{type:"button",title:he.ok?n("layout_editor.table_editor.move_row_up"):be(he.reason)||n("layout_editor.table_editor.move_row_up"),disabled:!he.ok||x,onClick:()=>Me(fe,-1),"data-testid":`g7le-table-row-up-${fe}`,style:he.ok?vn:Ai,children:"↑"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.add_row"),disabled:x,onClick:()=>Se(fe),"data-testid":`g7le-table-row-add-${fe}`,style:vn,children:"+"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.remove_row"),disabled:f.rows.length<=1||x,onClick:()=>Ue(fe),"data-testid":`g7le-table-row-remove-${fe}`,style:Th,children:"✕"}),i.jsx("button",{type:"button",title:j.ok?n("layout_editor.table_editor.move_row_down"):be(j.reason)||n("layout_editor.table_editor.move_row_down"),disabled:!j.ok||x,onClick:()=>Me(fe,1),"data-testid":`g7le-table-row-down-${fe}`,style:j.ok?vn:Ai,children:"↓"})]})})()}),U.cells.map(he=>{const j=`${he.gridRow}:${he.gridCol}`,{node:ne,path:pe}=fl(he.cell),Q=Ah(ne,c,d),ae=pe!==null&&Q.editable,Ae=pe===null,dt=w[j],pt=dt!==void 0?dt:Q.display,ot=h&&h.r===he.gridRow&&h.c===he.gridCol,Le=h&&y&&he.gridRow>=Math.min(h.r,y.r)&&he.gridRow<=Math.max(h.r,y.r)&&he.gridCol>=Math.min(h.c,y.c)&&he.gridCol<=Math.max(h.c,y.c);return i.jsx("td",{colSpan:he.colSpan,rowSpan:he.rowSpan,"data-testid":`g7le-table-cell-${he.gridRow}-${he.gridCol}`,onClick:je=>re(he.gridRow,he.gridCol,je.shiftKey),style:{...fN,...Qz(he.cell,b,A),...Rz(he.cell,g,A),...he.isHeader?gN:{},...ot?hN:{},...Le&&!ot?yN:{}},children:ae?i.jsx("input",{type:"text","data-testid":`g7le-table-cell-input-${he.gridRow}-${he.gridCol}`,value:pt,placeholder:n("layout_editor.table_editor.cell_text"),disabled:x,onMouseDown:je=>{je.shiftKey&&je.preventDefault(),re(he.gridRow,he.gridCol,je.shiftKey)},onClick:je=>je.stopPropagation(),onChange:je=>k(Je=>({...Je,[j]:je.target.value})),onBlur:()=>{We(he.gridRow,he.gridCol)},style:bN}):Ae?i.jsx("span",{"data-testid":`g7le-table-cell-struct-${he.gridRow}-${he.gridCol}`,style:Dh,children:n("layout_editor.table_editor.structural_cell")}):i.jsx("span",{style:Dh,children:Q.display})},j)})]},ue)})})]})}),i.jsxs("button",{type:"button","data-testid":"g7le-table-add-row-bottom",onClick:()=>Se(f.rows.length-1),disabled:x,style:mN,children:["+ ",n("layout_editor.table_editor.add_row")]}),i.jsxs("div",{style:vN,"data-testid":"g7le-table-cell-tools",children:[i.jsx("button",{type:"button","data-testid":"g7le-table-merge",onClick:Xe,disabled:!me||x,style:zh,children:n("layout_editor.table_editor.merge_cells")}),i.jsx("button",{type:"button","data-testid":"g7le-table-unmerge",onClick:ve,disabled:!Ce||x,style:zh,children:n("layout_editor.table_editor.unmerge_cells")})]}),B&&ce&&i.jsxs("div",{style:xN,"data-testid":"g7le-table-cell-i18n-section",children:[i.jsx("div",{style:wN,children:n("layout_editor.table_editor.cell_i18n_label")}),i.jsx(_t,{value:ce.value,onChange:q,t:n,placeholder:n("layout_editor.table_editor.cell_text"),testidPrefix:"g7le-table-cell-i18n",candidates:s,enableExpressionTree:!0,expressionTreeCollapsible:!0})]}),B&&i.jsxs("div",{style:_N,"data-testid":"g7le-table-cell-color-section",children:[i.jsx(kh,{colorScheme:A,onChange:N,t:n,disabled:x}),b&&i.jsx("div",{style:gl,"data-testid":"g7le-table-cell-border-row",children:i.jsx(yh,{className:$e,catalog:b,t:n,onChange:qe,colorScheme:A,onPresetToken:F,colorStyle:Y,onColorStyle:I,disabled:x})}),i.jsx("div",{style:gl,"data-testid":"g7le-table-cell-fill-row",children:i.jsx(_h,{colorStyle:ge,className:V,catalog:g,t:n,colorScheme:A,onPresetToken:se,onCustomColor:oe,onClear:G,disabled:x})})]}),B&&i.jsx("div",{style:gl,"data-testid":"g7le-table-cell-padding-row",children:i.jsx(xh,{paddingStyle:te,catalog:m,t:n,onChange:ee,disabled:x})}),B&&!b&&i.jsxs("label",{style:kN,"data-testid":"g7le-table-cell-border-row",children:[i.jsx("span",{style:SN,children:n("layout_editor.table_editor.cell_border")}),i.jsx("input",{type:"text","data-testid":"g7le-table-cell-border-input",value:$e,placeholder:n("layout_editor.table_editor.cell_class_placeholder"),onChange:U=>qe(U.target.value),disabled:x,style:CN})]}),!f.valid&&i.jsx("div",{"data-testid":"g7le-table-grid-warning",style:$N,children:n("layout_editor.table_editor.grid_invalid")}),i.jsx("div",{style:EN,children:n("layout_editor.table_editor.select_hint")})]})}const iN={display:"flex",flexDirection:"column",gap:8,width:"100%",marginBottom:12},sN={fontSize:12,fontWeight:700,color:"#0f172a"},aN={borderCollapse:"collapse",width:"auto"},lN={width:28,background:"transparent",border:"none"},dN={padding:2,border:"none",background:"transparent"},cN={padding:2,border:"none",background:"transparent",verticalAlign:"middle"},uN={display:"flex",gap:2,justifyContent:"center"},pN={display:"grid",gridTemplateColumns:"repeat(2, 16px)",gap:2,justifyContent:"center"},vn={width:16,height:16,lineHeight:"14px",padding:0,fontSize:10,border:"1px solid #cbd5e1",borderRadius:4,background:"#fff",color:"#475569",cursor:"pointer"},Th={...vn,border:"1px solid #fecaca",color:"#dc2626"},Ai={...vn,cursor:"not-allowed",opacity:.4,color:"#94a3b8",borderColor:"#e2e8f0"},fN={border:"1px solid #cbd5e1",padding:0,width:64,minWidth:64,maxWidth:120,height:24,background:"#fff",cursor:"pointer"},gN={background:"#f1f5f9",fontWeight:600},hN={outline:"2px solid #2563eb",outlineOffset:-2},yN={background:"#dbeafe"},bN={width:"100%",boxSizing:"border-box",padding:"2px 5px",fontSize:11,height:22,lineHeight:"18px",border:"none",background:"transparent",outline:"none"},Dh={display:"block",padding:"2px 5px",fontSize:10,color:"#64748b",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:110},mN={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},vN={display:"flex",gap:6},zh={padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},_N={display:"flex",flexDirection:"column",gap:8,borderTop:"1px solid #f1f5f9",paddingTop:8},xN={display:"flex",flexDirection:"column",gap:6,borderTop:"1px solid #f1f5f9",paddingTop:8},wN={fontSize:12,fontWeight:700,color:"#0f172a"},gl={display:"flex",flexDirection:"column",gap:6},kN={display:"flex",alignItems:"center",gap:6},SN={fontSize:12,color:"#475569",minWidth:60},CN={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},$N={fontSize:11,color:"#b45309",background:"#fffbeb",border:"1px solid #fde68a",borderRadius:6,padding:"4px 6px"},EN={fontSize:11,color:"#94a3b8"},IN=/\{\{.*?\}\}/;function AN(e,t,n){const r=(e.props??{})[t];return Array.isArray(r)?r:r===void 0&&n?JSON.parse(JSON.stringify(n)):[]}function TN(e){return typeof e=="string"&&IN.test(e)}function hl(e,t,n){return e?e.startsWith("$t:")?t(e.slice(3)):e:n}function DN(e,t,n){return typeof e=="object"&&e!==null?e[t.key]:n?e:void 0}function zN(e,t,n,o){if(typeof e=="object"&&e!==null){const r={...e};return o===void 0?delete r[t.key]:r[t.key]=o,r}return n?o:{[t.key]:o}}function Nh({node:e,params:t,t:n,onPatchNode:o,templateIdentifier:r,candidates:s}){const a=typeof t?.arrayProp=="string"?t.arrayProp:null,l=Array.isArray(t?.fields)?t.fields:[],d=hl(typeof t?.itemLabel=="string"?t.itemLabel:void 0,n,n("layout_editor.array_editor.item")),c=t?.newItem,p=c&&typeof c=="object"?c:null,f=typeof c=="string"||typeof c=="number"?c:null,b=(l.find($=>$.primary)??l[0])?.key,g=(e.props??{})[a??""],m=Array.isArray(t?.defaultItems)?t.defaultItems:null,h=a?AN(e,a,m):[],v=u.useCallback($=>{if(!a)return;const S={...e.props??{}};S[a]=$,o({...e,props:S})},[a,e,o]),y=u.useCallback(()=>{if(p)return JSON.parse(JSON.stringify(p));if(f!==null)return f;const $={};for(const S of l)(S.widget??"text")==="boolean"?$[S.key]=!1:$[S.key]="";return $},[p,f,l]),_=u.useCallback(()=>{v([...h,y()])},[v,h,y]),w=u.useCallback($=>{v(h.filter((S,C)=>C!==$))},[v,h]),k=u.useCallback(($,S)=>{const C=$+S;if(C<0||C>=h.length)return;const T=[...h];[T[$],T[C]]=[T[C],T[$]],v(T)},[v,h]),x=u.useCallback(($,S,C)=>{const T=S.key===b,E=h.map((A,N)=>N===$?zN(A,S,T,C):A);v(E)},[h,v,b]);return a?TN(g)||g!==void 0&&!Array.isArray(g)?i.jsx("div",{className:"g7le-node-editor g7le-node-editor--array","data-testid":"g7le-array-editor-bound",style:HN,children:n("layout_editor.array_editor.bound_degraded")}):i.jsxs("div",{className:"g7le-node-editor g7le-node-editor--array","data-testid":"g7le-array-editor",style:NN,children:[i.jsx("div",{style:MN,children:n("layout_editor.array_editor.items_title")}),h.length===0&&i.jsx("div",{"data-testid":"g7le-array-empty",style:Lh,children:n("layout_editor.array_editor.empty")}),h.map(($,S)=>i.jsxs("div",{"data-testid":`g7le-array-row-${S}`,style:LN,children:[i.jsxs("div",{style:PN,children:[i.jsxs("span",{style:ON,children:["#",S+1]}),i.jsx("div",{style:{flex:1}}),i.jsx("button",{type:"button","data-testid":`g7le-array-up-${S}`,title:n("layout_editor.array_editor.move_up"),disabled:S===0,onClick:()=>k(S,-1),style:Mh,children:"↑"}),i.jsx("button",{type:"button","data-testid":`g7le-array-down-${S}`,title:n("layout_editor.array_editor.move_down"),disabled:S===h.length-1,onClick:()=>k(S,1),style:Mh,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-array-remove-${S}`,title:n("layout_editor.array_editor.remove"),onClick:()=>w(S),style:WN,children:"✕"})]}),l.map(C=>{const T=C.widget??"text",E=C.key===b,A=hl(C.label,n,C.key),N=DN($,C,E),D=`g7le-array-field-${S}-${C.key}`;if(T==="boolean")return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("input",{type:"checkbox","data-testid":D,checked:N===!0,onChange:M=>x(S,C,M.target.checked)})]},C.key);if(T==="select"){const M=Array.isArray(C.options)?C.options:[];return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsxs("select",{"data-testid":D,value:N==null?"":String(N),onChange:O=>x(S,C,O.target.value===""?void 0:O.target.value),style:sr,children:[i.jsx("option",{value:"",children:"—"}),M.map((O,z)=>i.jsx("option",{value:String(O.value),children:hl(O.label,n,String(O.value))},z))]})]},C.key)}if(T==="i18n-text"){const M=typeof N=="string"?N:N==null?"":String(N);return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("div",{"data-testid":D,style:{flex:1,minWidth:0},children:i.jsx(_t,{value:M,onChange:O=>x(S,C,O===""?void 0:O),t:n,placeholder:A,testidPrefix:`${D}-i18n`,candidates:s,enableExpressionTree:!0,expressionTreeCollapsible:!0})})]},C.key)}if(T==="number"){const M=N==null?"":String(N);return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("input",{type:"number","data-testid":D,value:M,onChange:O=>{const z=O.target.value;x(S,C,z===""?void 0:Number(z))},style:sr})]},C.key)}if(T==="color"){const M=typeof N=="string"?N:"",O=/^#[0-9a-fA-F]{6}$/.test(M)?M:"#000000";return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("input",{type:"color","data-testid":`${D}-swatch`,value:O,onChange:z=>x(S,C,z.target.value),style:BN}),i.jsx("input",{type:"text","data-testid":D,value:M,placeholder:"#7C3AED",onChange:z=>x(S,C,z.target.value===""?void 0:z.target.value),style:sr})]},C.key)}if(T==="number-list"){const M=Array.isArray(N)?N.join(", "):"";return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("input",{type:"text","data-testid":D,value:M,placeholder:n("layout_editor.array_editor.number_list_placeholder"),onChange:O=>{const z=O.target.value.split(",").map(H=>H.trim()).filter(H=>H!=="").map(H=>Number(H)).filter(H=>!Number.isNaN(H));x(S,C,z)},style:sr})]},C.key)}const B=N==null?"":String(N);return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("input",{type:"text","data-testid":D,value:B,placeholder:T==="icon"?n("layout_editor.array_editor.icon_placeholder"):A,onChange:M=>x(S,C,M.target.value===""?void 0:M.target.value),style:sr})]},C.key)})]},S)),i.jsx("button",{type:"button","data-testid":"g7le-array-add",onClick:_,style:jN,children:n("layout_editor.array_editor.add",{item:d})})]}):i.jsx("div",{className:"g7le-node-editor g7le-node-editor--array","data-testid":"g7le-array-editor-misconfigured",style:Lh,children:n("layout_editor.array_editor.no_array_prop")})}const NN={display:"flex",flexDirection:"column",gap:8,width:"100%",marginBottom:12},MN={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:2},LN={display:"flex",flexDirection:"column",gap:4,padding:8,border:"1px solid #e2e8f0",borderRadius:8,background:"#f8fafc"},PN={display:"flex",gap:4,alignItems:"center"},ON={fontSize:11,fontWeight:700,color:"#64748b"},Wn={display:"flex",flexWrap:"wrap",gap:6,alignItems:"center"},jn={fontSize:11,color:"#475569",minWidth:64,flexShrink:0},sr={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},BN={width:32,height:28,padding:0,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",cursor:"pointer",flexShrink:0},Mh={padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},WN={padding:"2px 6px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},jN={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},Lh={fontSize:11,color:"#94a3b8",fontStyle:"italic"},HN={fontSize:11,color:"#b45309",fontStyle:"italic",padding:"4px 2px"};function FN(e,t){return e?e.startsWith("$t:")?t(e.slice(3)):e:null}function KN(e){const{params:t,t:n}=e,o=Array.isArray(t?.groups)?t.groups:[];return o.length===0?i.jsx("div",{className:"g7le-node-editor g7le-node-editor--array-group","data-testid":"g7le-array-group-misconfigured",style:GN,children:n("layout_editor.array_editor.no_array_prop")}):i.jsx("div",{className:"g7le-node-editor g7le-node-editor--array-group","data-testid":"g7le-array-group-editor",style:VN,children:o.map((r,s)=>{const a=FN(r.title,n),{title:l,...d}=r;return i.jsxs("div",{"data-testid":`g7le-array-group-${r.arrayProp??s}`,style:UN,children:[a&&i.jsx("div",{style:qN,children:a}),i.jsx(Nh,{...e,params:d})]},r.arrayProp??s)})})}const VN={display:"flex",flexDirection:"column",gap:16,width:"100%",marginBottom:12},UN={display:"flex",flexDirection:"column",gap:4},qN={fontSize:12,fontWeight:700,color:"#1e293b",borderBottom:"1px solid #e2e8f0",paddingBottom:4},GN={fontSize:11,color:"#94a3b8",fontStyle:"italic"},YN=/\{\{.*?\}\}/;function XN(e){return typeof e=="string"&&YN.test(e)}function JN(e,t,n){return e?e.startsWith("$t:")?t(e.slice(3)):e:n}function ZN(e){const{node:t,params:n,t:o,onPatchNode:r}=e,s=typeof n?.arrayProp=="string"?n.arrayProp:null,a=typeof n?.idField=="string"?n.idField:"id",l=typeof n?.cellChildrenProp=="string"?n.cellChildrenProp:"cellChildren",d=typeof n?.cellChildComponent=="string"?n.cellChildComponent:"Div",c=JN(typeof n?.itemLabel=="string"?n.itemLabel:void 0,o,o("layout_editor.array_editor.item")),[p,f]=u.useState(null),b=s?(t.props??{})[s]:void 0,g=Array.isArray(b)?b:[],m=u.useCallback($=>{if(!s)return;const S={...t.props??{}};S[s]=$,r({...t,props:S})},[s,t,r]),h=u.useCallback(()=>{const $=n?.newItem;return $&&typeof $=="object"?JSON.parse(JSON.stringify($)):{[a]:"",[l]:[]}},[n,a,l]),v=u.useCallback(()=>{m([...g,h()])},[m,g,h]),y=u.useCallback($=>{m(g.filter((S,C)=>C!==$)),f(null)},[m,g]),_=u.useCallback(($,S)=>{const C=$+S;if(C<0||C>=g.length)return;const T=[...g];[T[$],T[C]]=[T[C],T[$]],m(T)},[m,g]),w=u.useCallback(($,S)=>{const C=g.map((T,E)=>E===$?{...T,[a]:S}:T);m(C)},[g,m,a]),k=u.useCallback($=>({type:"composite",name:"CardGridCell",children:Array.isArray($[l])?$[l]:[]}),[l]),x=u.useCallback($=>S=>{const C=Array.isArray(S.children)?S.children:[],T=g.map((E,A)=>A===$?{...E,[l]:C}:E);m(T)},[g,m,l]);return s?XN(b)||b!==void 0&&!Array.isArray(b)?i.jsx("div",{className:"g7le-node-editor g7le-node-editor--cell-tree","data-testid":"g7le-cell-tree-bound",style:lM,children:o("layout_editor.array_editor.bound_degraded")}):i.jsxs("div",{className:"g7le-node-editor g7le-node-editor--cell-tree","data-testid":"g7le-cell-tree-editor",style:QN,children:[i.jsx("div",{style:RN,children:o("layout_editor.cell_tree_editor.columns_title")}),g.length===0&&i.jsx("div",{"data-testid":"g7le-cell-tree-empty",style:Oh,children:o("layout_editor.array_editor.empty")}),g.map(($,S)=>{const C=typeof $[a]=="string"?$[a]:"",T=p===S;return i.jsxs("div",{"data-testid":`g7le-cell-tree-row-${S}`,style:eM,children:[i.jsxs("div",{style:tM,children:[i.jsxs("span",{style:nM,children:["#",S+1]}),i.jsx("input",{type:"text","data-testid":`g7le-cell-tree-id-${S}`,value:C,placeholder:o("layout_editor.cell_tree_editor.id_placeholder"),onChange:E=>w(S,E.target.value),style:oM}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-up-${S}`,title:o("layout_editor.array_editor.move_up"),disabled:S===0,onClick:()=>_(S,-1),style:Ph,children:"↑"}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-down-${S}`,title:o("layout_editor.array_editor.move_down"),disabled:S===g.length-1,onClick:()=>_(S,1),style:Ph,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-remove-${S}`,title:o("layout_editor.array_editor.remove"),onClick:()=>y(S),style:rM,children:"✕"})]}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-toggle-${S}`,onClick:()=>f(T?null:S),style:iM,children:o(T?"layout_editor.cell_tree_editor.collapse_cells":"layout_editor.cell_tree_editor.expand_cells")}),T&&i.jsx("div",{"data-testid":`g7le-cell-tree-cells-${S}`,style:sM,children:i.jsx(Rg,{...e,node:k($),params:{childComponent:d},onPatchNode:x(S)})})]},S)}),i.jsx("button",{type:"button","data-testid":"g7le-cell-tree-add",onClick:v,style:aM,children:o("layout_editor.cell_tree_editor.add_column",{item:c})})]}):i.jsx("div",{className:"g7le-node-editor g7le-node-editor--cell-tree","data-testid":"g7le-cell-tree-misconfigured",style:Oh,children:o("layout_editor.array_editor.no_array_prop")})}const QN={display:"flex",flexDirection:"column",gap:8,width:"100%",marginBottom:12},RN={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:2},eM={display:"flex",flexDirection:"column",gap:6,padding:8,border:"1px solid #e2e8f0",borderRadius:8,background:"#f8fafc"},tM={display:"flex",gap:4,alignItems:"center"},nM={fontSize:11,fontWeight:700,color:"#64748b",flexShrink:0},oM={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},Ph={padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},rM={padding:"2px 6px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},iM={padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#2563eb",cursor:"pointer",alignSelf:"flex-start"},sM={paddingLeft:8,borderLeft:"2px solid #e2e8f0"},aM={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},Oh={fontSize:11,color:"#94a3b8",fontStyle:"italic"},lM={fontSize:11,color:"#b45309",fontStyle:"italic",padding:"4px 2px"};function dM(e,t,n){const o=Pe(e,t);if(!n||n.length===0)return{measured:[],grid:o};const r=[];for(const s of o.rows)for(const a of s.cells){const d=il(e,a,t).map(p=>`children.${p}`).join("."),c=n.find(p=>p.path===d||p.path.endsWith("."+d));c&&r.push({ref:a,box:{top:c.top,left:c.left,width:c.width,height:c.height}})}return{measured:r,grid:o}}const yl=26,bl=50,ml=6,Bh=44,Wh=18,jh="g7le-table-inplace-empty-cell-style";function cM(){if(typeof document>"u"||document.getElementById(jh))return;const e=document.createElement("style");e.id=jh,e.textContent=".g7le-preview-frame td[data-editor-name],.g7le-preview-frame th[data-editor-name]{min-width:56px;height:38px;}.g7le-preview-frame table[data-editor-name]{min-width:120px;}",document.head.appendChild(e)}function uM({node:e,params:t,nodeBox:n,cellBoxes:o,selectedCellPath:r,colorScheme:s,t:a,onPatchNode:l,onRequestInlineEdit:d}){const c=u.useMemo(()=>t&&typeof t=="object"?t:null,[t]),{measured:p,grid:f}=u.useMemo(()=>dM(e,c,o),[e,c,o]),[b,g]=u.useState(null),[m,h]=u.useState(null),v=u.useMemo(()=>{if(!r)return null;for(const j of f.rows)for(const ne of j.cells){const pe=il(e,ne,c).map(Q=>`children.${Q}`).join(".");if(r===pe||r.startsWith(pe+"."))return{r:ne.gridRow,c:ne.gridCol}}return null},[r,f,e,c]),y=u.useMemo(()=>b&&Ve(f,b.r,b.c)?b:v,[b,v,f]),[_,w]=u.useState(!1),[k,x]=u.useState(s==="dark"?"dark":"light"),[$,S]=u.useState(null),[C,T]=u.useState(null),E=u.useRef(null),A=u.useCallback(()=>{E.current!==null&&(clearTimeout(E.current),E.current=null)},[]),N=u.useCallback(()=>{A(),E.current=setTimeout(()=>{S(null),T(null),E.current=null},240)},[A]);u.useEffect(()=>()=>A(),[A]),u.useEffect(()=>{cM()},[]);const D=u.useCallback(j=>l(j),[l]),B=u.useMemo(()=>y?Ve(f,y.r,y.c):null,[f,y]),M=u.useMemo(()=>B&&typeof B.cell.props?.className=="string"?B.cell.props.className:"",[B]),O=u.useCallback(j=>D(sl(e,c,j)),[e,c,D]),z=u.useCallback(j=>D(sh(e,c,j)),[e,c,D]),H=u.useCallback((j,ne)=>D(ah(e,c,j,ne)),[e,c,D]),P=u.useCallback(j=>D(dh(e,c,j)),[e,c,D]),I=u.useCallback(j=>D(ch(e,c,j)),[e,c,D]),L=u.useCallback((j,ne)=>D(lh(e,c,j,ne)),[e,c,D]),F=u.useCallback(j=>{if(!B)return;const ne=B.gridRow,pe=B.gridCol,Q=j==="down"?ne+B.rowSpan:ne+B.rowSpan-1,ae=j==="right"?pe+B.colSpan:pe+B.colSpan-1;if(Q>=f.rows.length||ae>=f.colCount)return;const Ae=al(e,c,ne,pe,Q,ae);Ae.ok&&D(Ae.table)},[B,f,e,c,D]),Y=!!(B&&B.gridCol+B.colSpan!y||!m||!Ve(f,m.r,m.c)?null:{r0:Math.min(y.r,m.r),c0:Math.min(y.c,m.c),r1:Math.max(y.r,m.r),c1:Math.max(y.c,m.c)},[y,m,f]),Z=u.useMemo(()=>{if(!X)return[];const j=new Set,ne=[];for(const pe of f.rows)for(const Q of pe.cells)if(Q.gridRow>=X.r0&&Q.gridRow<=X.r1&&Q.gridCol>=X.c0&&Q.gridCol<=X.c1){const ae=`${Q.gridRow}:${Q.gridCol}`;j.has(ae)||(j.add(ae),ne.push({r:Q.gridRow,c:Q.gridCol}))}return ne},[X,f]),se=Z.length>1,oe=u.useCallback(()=>{if(!X)return;const j=al(e,c,X.r0,X.c0,X.r1,X.c1);j.ok&&(D(j.table),h(null))},[X,e,c,D]),G=u.useCallback(()=>{y&&D(uh(e,c,y.r,y.c))},[e,c,y,D]),ee=u.useMemo(()=>{const j=c?.cellBorder;return j&&typeof j=="object"?j:null},[c]),ge=u.useMemo(()=>{const j=c?.cellBackground;return j&&typeof j=="object"?j:null},[c]),V=u.useMemo(()=>{const j=c?.cellPadding;return j&&typeof j=="object"?j:null},[c]),te=u.useMemo(()=>{if(_){const j=new Set,ne=[];for(const pe of f.rows)for(const Q of pe.cells){const ae=`${Q.gridRow}:${Q.gridCol}`;j.has(ae)||(j.add(ae),ne.push({r:Q.gridRow,c:Q.gridCol}))}return ne}return se?Z:y?[{r:y.r,c:y.c}]:[]},[_,se,Z,y,f]),be=u.useCallback(j=>{if(te.length===0)return;let ne=e;for(const pe of te){const Q=(ee?.colors??[]).map(Ae=>Ae.token),ae=j.split(/\s+/).filter(Ae=>Ae&&!Q.includes(Ae)).join(" ");ne=Ii(ne,c,pe.r,pe.c,ae)}D(ne)},[e,c,te,ee,D]),Ee=u.useMemo(()=>{const j=(ee?.sides??[]).find(Q=>Q.value==="all")??(ee?.sides??[])[0],ne=(ee?.widths??[]).find(Q=>Q.value!=="none");if(!j||!ne)return[];const pe=ne.suffix??"";return[pe?`${j.prefix}${pe}`:j.prefix]},[ee]),De=u.useCallback((j,ne,pe)=>{if(Ee.length===0)return j;const Q=(ee?.sides??[]).map(Le=>Le.prefix),ae=Ve(Pe(j,c),ne,pe),dt=(typeof ae?.cell?.props?.className=="string"?ae.cell.props.className:"").split(/\s+/).filter(Boolean);if(dt.some(Le=>Q.some(je=>Le===je||Le.startsWith(je+"-")&&/^-?\d+$/.test(Le.slice(je.length+1)))))return j;const ot=[...dt,...Ee].join(" ").trim();return Ii(j,c,ne,pe,ot)},[Ee,ee,c]),Se=u.useCallback((j,ne)=>{if(j.length===0)return;const pe=new Set(j.map(ae=>`${ae.r}:${ae.c}`));let Q=e;for(const ae of j){if(Q=De(Q,ae.r,ae.c),Q=Jt(Q,c,ae.r,ae.c,"borderColor",ne),ae.r>0&&!pe.has(`${ae.r-1}:${ae.c}`)){const Ae=Ve(Pe(Q,c),ae.r-1,ae.c);Ae&&(Q=Jt(Q,c,Ae.gridRow,Ae.gridCol,"borderBottomColor",ne))}if(ae.c>0&&!pe.has(`${ae.r}:${ae.c-1}`)){const Ae=Ve(Pe(Q,c),ae.r,ae.c-1);Ae&&(Q=Jt(Q,c,Ae.gridRow,Ae.gridCol,"borderRightColor",ne))}}D(Q)},[e,c,D,De]),Ue=u.useMemo(()=>(ee?.colors??[]).map(j=>j.token).filter(Boolean),[ee]),Me=u.useCallback(j=>{if(te.length===0||Ue.length===0)return;let ne=e;for(const pe of te)ne=De(ne,pe.r,pe.c),ne=ho(ne,c,pe.r,pe.c,j,Ue,k);D(ne)},[te,e,c,D,De,Ue,k]),Oe=u.useCallback(j=>Se(te,j),[Se,te]),Ye=u.useMemo(()=>{if(k==="dark")return"";const j=B?.cell.props?.style;return typeof j?.borderColor=="string"?j.borderColor:""},[B,k]),ze=u.useCallback((j,ne)=>{if(te.length===0)return;let pe=e;for(const Q of te)pe=Jt(pe,c,Q.r,Q.c,j,ne);D(pe)},[te,e,c,D]),Xe=u.useMemo(()=>(ge?.colors??[]).map(j=>j.token).filter(j=>!!j),[ge]),ve=u.useCallback(j=>{if(te.length===0||Xe.length===0)return;let ne=e;for(const pe of te)ne=ho(ne,c,pe.r,pe.c,j,Xe,k);D(ne)},[te,e,c,D,Xe,k]),qe=u.useCallback(j=>ze("backgroundColor",j),[ze]),We=u.useCallback(()=>{if(te.length===0)return;let j=e;for(const ne of te)j=ho(j,c,ne.r,ne.c,void 0,Xe,k),k==="light"&&(j=Jt(j,c,ne.r,ne.c,"backgroundColor",void 0));D(j)},[te,e,c,D,Xe,k]),ce=u.useCallback(j=>ze("padding",j),[ze]),q=u.useMemo(()=>{if(k==="dark")return"";const j=B?.cell.props?.style;return typeof j?.backgroundColor=="string"?j.backgroundColor:""},[B,k]),re=u.useMemo(()=>typeof B?.cell.props?.className=="string"?B.cell.props.className:"",[B]),ie=u.useMemo(()=>{const j=B?.cell.props?.style;return typeof j?.padding=="string"?j.padding:""},[B]),me=u.useCallback(j=>{const ne=j.currentTarget,pe=ne.style.pointerEvents;ne.style.pointerEvents="none";const Q=document.elementFromPoint(j.clientX,j.clientY);ne.style.pointerEvents=pe;const ae=Q?.closest?.("[data-dnd-handle-path]");ae&&ae.dispatchEvent(new PointerEvent("pointerdown",{bubbles:!0,cancelable:!0,clientX:j.clientX,clientY:j.clientY,pointerId:j.pointerId,pointerType:j.pointerType,button:j.button,isPrimary:!0}))},[]),Ce=u.useMemo(()=>{const j=new Map;for(const ne of p)j.has(ne.ref.gridCol)||j.set(ne.ref.gridCol,ne.box);return j},[p]),$e=u.useMemo(()=>{const j=new Map;for(const ne of p)j.has(ne.ref.gridRow)||j.set(ne.ref.gridRow,ne.box);return j},[p]);if(p.length===0)return null;const U=!!(B&&(B.colSpan>1||B.rowSpan>1)),ue=C!==null?C:y?.c??null,fe=$!==null?$:y?.r??null,xe=n.top-yl-ml-Bh,he=n.left-bl-ml-Bh;return i.jsxs("div",{className:"g7le-table-inplace","data-testid":"g7le-table-inplace",style:{position:"absolute",inset:0,pointerEvents:"none",zIndex:j7},children:[p.map(j=>{const ne=y&&y.r===j.ref.gridRow&&y.c===j.ref.gridCol,pe=X&&j.ref.gridRow>=X.r0&&j.ref.gridRow<=X.r1&&j.ref.gridCol>=X.c0&&j.ref.gridCol<=X.c1;return i.jsx("div",{"data-testid":`g7le-inplace-cell-${j.ref.gridRow}-${j.ref.gridCol}`,role:"button",tabIndex:-1,"aria-label":a("layout_editor.table_inplace.select_cell"),onMouseEnter:()=>{A(),S(j.ref.gridRow),T(j.ref.gridCol)},onMouseLeave:()=>{N()},onPointerDown:Q=>me(Q),onClick:Q=>{if(Q.stopPropagation(),Q.shiftKey&&(b||y))h({r:j.ref.gridRow,c:j.ref.gridCol});else{g({r:j.ref.gridRow,c:j.ref.gridCol}),h(null);const ae=il(e,j.ref,c).map(Ae=>`children.${Ae}`).join(".");d?.(ae)}},style:{position:"absolute",top:j.box.top,left:j.box.left,width:j.box.width,height:j.box.height,minWidth:Wh,minHeight:Wh,boxSizing:"border-box",pointerEvents:"auto",cursor:"pointer",outline:ne?"2px solid #2563eb":"none",outlineOffset:-2,background:pe&&!ne?"rgba(37,99,235,0.14)":"transparent"}},`cell-${j.ref.gridRow}-${j.ref.gridCol}`)}),i.jsx("div",{"data-testid":"g7le-inplace-col-rail",onMouseEnter:A,onMouseLeave:N,style:{position:"absolute",top:xe,left:n.left,width:n.width,height:yl,pointerEvents:"none"},children:ue!==null&&Ce.has(ue)&&(()=>{const j=ue,ne=Ce.get(j),pe=Ci(f,j,-1),Q=Ci(f,j,1),ae=ne.left-n.left;return i.jsxs("div",{"data-testid":`g7le-inplace-colgutter-${j}`,onMouseEnter:()=>{A(),T(j)},onMouseLeave:N,style:{position:"absolute",top:0,left:ae,width:ne.width,minWidth:96,height:yl,display:"flex",gap:3,justifyContent:"center",alignItems:"center",pointerEvents:"auto"},children:[i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.move_col_left"),disabled:!pe.ok,onClick:()=>L(j,-1),"data-testid":`g7le-inplace-col-left-${j}`,style:pe.ok?_n:Ti,children:"←"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.add_col"),onClick:()=>P(j),"data-testid":`g7le-inplace-col-add-${j}`,style:_n,children:"+"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.remove_col"),disabled:f.colCount<=1,onClick:()=>I(j),"data-testid":`g7le-inplace-col-remove-${j}`,style:Hh,children:"✕"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.move_col_right"),disabled:!Q.ok,onClick:()=>L(j,1),"data-testid":`g7le-inplace-col-right-${j}`,style:Q.ok?_n:Ti,children:"→"})]},`colgut-${j}`)})()}),i.jsx("div",{"data-testid":"g7le-inplace-row-rail",style:{position:"absolute",top:n.top,left:he,width:bl,height:n.height,pointerEvents:"none"},children:fe!==null&&$e.has(fe)&&(()=>{const j=fe,ne=$e.get(j),pe=Si(f,j,-1),Q=Si(f,j,1),ae=ne.top-n.top;return i.jsxs("div",{"data-testid":`g7le-inplace-rowgutter-${j}`,onMouseEnter:()=>{A(),S(j)},onMouseLeave:N,style:{position:"absolute",top:ae,left:0,width:bl,height:ne.height,minHeight:48,display:"grid",gridTemplateColumns:"repeat(2, 22px)",gridAutoRows:"22px",gap:3,justifyContent:"center",alignContent:"center",pointerEvents:"auto"},children:[i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.move_row_up"),disabled:!pe.ok,onClick:()=>H(j,-1),"data-testid":`g7le-inplace-row-up-${j}`,style:pe.ok?_n:Ti,children:"↑"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.add_row"),onClick:()=>O(j),"data-testid":`g7le-inplace-row-add-${j}`,style:_n,children:"+"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.remove_row"),disabled:f.rows.length<=1,onClick:()=>z(j),"data-testid":`g7le-inplace-row-remove-${j}`,style:Hh,children:"✕"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.move_row_down"),disabled:!Q.ok,onClick:()=>H(j,1),"data-testid":`g7le-inplace-row-down-${j}`,style:Q.ok?_n:Ti,children:"↓"})]},`rowgut-${j}`)})()}),i.jsxs("div",{"data-testid":"g7le-inplace-corner-add",style:{position:"absolute",top:n.top+n.height+ml,left:n.left,display:"flex",flexDirection:"column",gap:6,pointerEvents:"auto",minWidth:200,maxWidth:Math.max(240,n.width),background:"#fff",border:"1px solid #e2e8f0",borderRadius:8,padding:8,boxShadow:"0 2px 8px rgba(0,0,0,0.12)"},children:[i.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[i.jsxs("button",{type:"button","data-testid":"g7le-inplace-add-row-bottom",onClick:()=>O(f.rows.length-1),style:Fh,children:["+ ",a("layout_editor.table_inplace.add_row")]}),i.jsxs("button",{type:"button","data-testid":"g7le-inplace-add-col-right",onClick:()=>P(f.colCount-1),style:Fh,children:["+ ",a("layout_editor.table_inplace.add_col")]})]}),!y&&i.jsx("div",{"data-testid":"g7le-inplace-select-hint",style:{fontSize:11,color:"#94a3b8",borderTop:"1px solid #f1f5f9",paddingTop:6},children:a("layout_editor.table_inplace.select_cell_hint")}),y&&i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,borderTop:"1px solid #f1f5f9",paddingTop:6},children:[se&&i.jsx("div",{"data-testid":"g7le-inplace-range-count",style:{fontSize:11,color:"#2563eb"},children:a("layout_editor.table_inplace.range_selected",{count:Z.length})}),i.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",alignItems:"center"},children:[se?i.jsx("button",{type:"button","data-testid":"g7le-inplace-merge-range",onClick:oe,style:ar,children:a("layout_editor.table_inplace.merge_range")}):i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button","data-testid":"g7le-inplace-merge-right",disabled:!Y,onClick:()=>F("right"),style:Y?ar:vl,children:a("layout_editor.table_inplace.merge_right")}),i.jsx("button",{type:"button","data-testid":"g7le-inplace-merge-down",disabled:!K,onClick:()=>F("down"),style:K?ar:vl,children:a("layout_editor.table_inplace.merge_down")})]}),i.jsx("button",{type:"button","data-testid":"g7le-inplace-unmerge",disabled:!U,onClick:G,style:U?ar:vl,children:a("layout_editor.table_inplace.unmerge")})]}),i.jsxs("div",{"data-testid":"g7le-inplace-cell-color",style:{borderTop:"1px solid #f1f5f9",paddingTop:6,display:"flex",flexDirection:"column",gap:6},children:[i.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11,color:"#475569",cursor:"pointer"},children:[i.jsx("input",{type:"checkbox","data-testid":"g7le-inplace-border-all-toggle",checked:_,onChange:j=>w(j.target.checked)}),a("layout_editor.table_inplace.border_apply_all")]}),i.jsx(kh,{colorScheme:k,onChange:x,t:a}),ee&&i.jsx("div",{"data-testid":"g7le-inplace-cell-border",children:i.jsx(yh,{className:_?"":M,catalog:ee,t:a,onChange:be,colorScheme:k,onPresetToken:Me,colorStyle:_?"":Ye,onColorStyle:Oe})}),i.jsx("div",{"data-testid":"g7le-inplace-cell-fill",children:i.jsx(_h,{colorStyle:_?"":q,className:_?"":re,catalog:ge,t:a,colorScheme:k,onPresetToken:ve,onCustomColor:qe,onClear:We})})]}),i.jsx("div",{"data-testid":"g7le-inplace-cell-padding",style:{borderTop:"1px solid #f1f5f9",paddingTop:6},children:i.jsx(xh,{paddingStyle:_?"":ie,catalog:V,t:a,onChange:ce})})]})]})]})}const _n={width:22,height:22,lineHeight:"20px",padding:0,fontSize:13,border:"1px solid #cbd5e1",borderRadius:5,background:"#fff",color:"#475569",cursor:"pointer",boxShadow:"0 1px 3px rgba(0,0,0,0.18)"},Hh={..._n,border:"1px solid #fecaca",color:"#dc2626"},Ti={..._n,cursor:"not-allowed",opacity:.4,color:"#94a3b8",borderColor:"#e2e8f0"},ar={padding:"4px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",boxShadow:"0 1px 2px rgba(0,0,0,0.12)"},vl={...ar,cursor:"not-allowed",opacity:.4},Fh={padding:"3px 8px",fontSize:11,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"};let Kh=!1;function pM(){Kh||(Pn("children",Rg),Pn("table",rN),Pn("array",Nh),Pn("array-group",KN),Pn("array-cell-tree",ZN),ja("table",uM),Kh=!0)}function fM(){if(typeof window>"u")return;const e=window.G7Core;if(!e)return;const t=e.layoutEditor,n=Array.isArray(t?.__queue)?t.__queue:[],o=Array.isArray(t?.__readyCallbacks)?t.__readyCallbacks:[];e.layoutEditor={registerWidget:Ze,registerNodeEditor:Pn,registerCanvasOverlay:ja,onReady:r=>{typeof r=="function"&&r()}};for(const r of n){const[s,...a]=r;try{s==="widget"?Ze(a[0],a[1]):s==="nodeEditor"?Pn(a[0],a[1]):s==="canvasOverlay"&&ja(a[0],a[1])}catch{}}for(const r of o)try{r()}catch{}}const gM=1280;_z(),pM(),fM();async function hM(e){if(typeof fetch!="function")return[];try{const t=await fetch(en(`/api/admin/templates/${encodeURIComponent(e)}/editor/permission-candidates`,"json"),{credentials:"same-origin",headers:Ne()});if(!t.ok)return[];const o=(await t.json().catch(()=>null))?.data?.permissions;if(!Array.isArray(o))return[];const r=[];for(const s of o)if(s&&typeof s=="object"){const a=s.key,l=s.name;typeof a=="string"&&a.length>0&&r.push({value:a,label:typeof l=="string"&&l?l:a})}return r}catch{return[]}}function yM({templateIdentifier:e}){FD({templateIdentifier:e}),KD(e);const{state:t,dispatch:n}=Qe(),{t:o}=tt(),r=bo(),s=Dp(),a=XD(),l=t.selectedRoute?.layoutName??null,d=RD(e,l),c=t.editMode==="extension",p=u.useMemo(()=>c?ZD(a):s,[c,a,s]),[f,b]=u.useState(null),[g,m]=u.useState(null),[h,v]=u.useState([]),[y,_]=u.useState("user"),[w,k]=u.useState(null),[x,$]=u.useState(null),[S,C]=u.useState([]);u.useEffect(()=>{let q=!1;return(async()=>{try{const re=await fetch(en(`/api/templates/${encodeURIComponent(e)}/components`,"json"),{credentials:"same-origin",headers:{Accept:"application/json"}});if(!re.ok)return;const ie=await re.json().catch(()=>null);!q&&ie&&typeof ie=="object"&&b(ie)}catch{}})(),()=>{q=!0}},[e]),u.useEffect(()=>{let q=!1;return(async()=>{const{spec:re,sampleGlobalSources:ie}=await ab({templateIdentifier:e,coreSeed:e8()});q||(m(re),v(ie),mM(e,re,ie))})(),()=>{q=!0}},[e]),u.useEffect(()=>{let q=!1;return(async()=>{if(typeof fetch=="function")try{const re=await fetch(`/api/admin/templates/${encodeURIComponent(e)}`,{credentials:"same-origin",headers:Ne()});if(!re.ok)return;const me=(await re.json().catch(()=>null))?.data,Ce=me?.type;q||((Ce==="admin"||Ce==="user")&&_(Ce),typeof me?.name=="string"&&me.name&&k(me.name),typeof me?.version=="string"&&me.version&&$(me.version))}catch{}})(),()=>{q=!0}},[e]),u.useEffect(()=>{let q=!1;return(async()=>{if(typeof fetch=="function")try{const re=await fetch("/api/admin/templates/?per_page=100&page=1",{credentials:"same-origin",headers:Ne()});if(!re.ok)return;const me=(await re.json().catch(()=>null))?.data?.data;if(!q&&Array.isArray(me)){const Ce=[];for(const $e of me){if(!$e||typeof $e!="object")continue;const U=$e.identifier;if(typeof U!="string"||!U||$e.is_pending===!0)continue;const fe=$e.type==="admin"?"admin":"user",xe=$e.name,he=$e.version;Ce.push({identifier:U,name:typeof xe=="string"?xe:U,version:typeof he=="string"?he:"",type:fe})}C(Ce)}}catch{}})(),()=>{q=!0}},[e]);const T=g?.nesting??null,E=t.selectedRoute?.path??null,A=t.editMode,N=t.selectedRoute?.layoutName??(c?a.document?.hostLayoutName??null:null),D=t.routeTree,B=u.useMemo(()=>{if(A!=="extension"||!N)return null;const q=xl(D,N);return q||`__base__/${N}`},[A,N,D]),M=c&&t.returnRoute===null&&!!N;u.useEffect(()=>{if(!M||!N)return;const q=xl(D,N);q&&n({type:"SET_RETURN_ROUTE",route:{path:q,layoutName:N}})},[M,N,D,n]),u.useEffect(()=>{const q=xD(A,E,B),re=wD(g?.states?.groups,q);n({type:"SET_AVAILABLE_STATES",states:re,activeStateId:kD(re)})},[g,A,E,B,n]);const[O,z]=u.useState([]);u.useEffect(()=>{let q=!1;return(async()=>{const re=await hM(e);q||z(re)})(),()=>{q=!0}},[e]),VD(),UD();const H=u.useCallback(q=>{const re=t.routeTree,ie=q.split("?")[0]?.split("#")[0]??q;return bM(re,ie)?"route_in_tree":"route_not_in_tree"},[t.routeTree]),P=u.useCallback(q=>{const re=q.split("?")[0]?.split("#")[0]??q,ie=_l(t.routeTree,re);ie&&(p.isDirty&&!(!(typeof window<"u")||window.confirm(o("layout_editor.chrome.dirty_guard.message")))||n({type:"SELECT_ROUTE",route:{path:ie.path,layoutName:ie.layoutName}}))},[t.routeTree,p.isDirty,n]),I=u.useRef([]),L=u.useCallback(q=>{I.current=q},[]),[F,Y]=u.useState(null),K=u.useCallback(()=>Y(null),[]),X=u.useRef(null),Z=u.useRef(null);u.useEffect(()=>{const q=Z.current,re=X.current;if(!q||!re||typeof ResizeObserver>"u")return;const ie=()=>{re.style.setProperty("--g7le-header-h",`${Math.round(q.getBoundingClientRect().height)}px`)};ie();const me=new ResizeObserver(ie);return me.observe(q),()=>me.disconnect()},[]);const se=u.useCallback(()=>{p.reload()},[p]),oe=u.useCallback(()=>{p.isDirty&&!(!(typeof window<"u")||window.confirm(o("layout_editor.chrome.dirty_guard.message")))||window.G7Core?.dispatch?.({handler:"openWindow",params:{path:`/admin/templates/${y}`,target:"_self"}})},[p.isDirty,o,y]),G=u.useCallback(q=>{if(!q||q===e||p.isDirty&&!(typeof window<"u"?window.confirm(o("layout_editor.chrome.dirty_guard.message")):!0))return;const re=ea(q);window.G7Core?.dispatch?.({handler:"openWindow",params:{path:re,target:"_self"}})},[e,p.isDirty,o]),ee=u.useCallback(()=>{const q=r.open({ariaLabel:o("layout_editor.custom_assets.title"),width:860,maxHeightRatio:.86,content:u.createElement(wE,{templateIdentifier:e,t:o,onClose:()=>r.close(q)})})},[r,e,o]),ge=typeof window<"u"&&(!!window.G7Config?.customAssetsDisabled||new URLSearchParams(window.location.search).get("custom")==="off"),V=u.useCallback(()=>{if(typeof window>"u"||p.isDirty&&!window.confirm(o("layout_editor.chrome.dirty_guard.message")))return;const q=new URL(window.location.href);if(ge){if(q.searchParams.delete("custom"),q.toString()===window.location.href){window.location.reload();return}}else q.searchParams.set("custom","off");window.G7Core?.dispatch?.({handler:"openWindow",params:{path:`${q.pathname}${q.search}${q.hash}`,target:"_self"}})},[p.isDirty,ge,o]),te=u.useCallback(()=>{const q=s7(e,t.selectedRoute?.path??null);window.G7Core?.dispatch?.({handler:"openWindow",params:{path:q}})},[e,t.selectedRoute]),be=u.useCallback(()=>{const q=t.selectedRoute?.layoutName??"";if(!q)return;const re=r.open({ariaLabel:o("layout_editor.attachment_manager.title"),width:720,maxHeightRatio:.82,content:u.createElement(Bl,{templateIdentifier:e,layoutName:q,t:o,onClose:()=>r.close(re)})})},[r,e,t.selectedRoute,o]),Ee=u.useCallback(()=>{const q=t.selectedRoute?.layoutName??"";if(!q)return;const re=Yy(s.document?.raw??{}),ie=r.open({ariaLabel:o("layout_editor.translation_manager.title"),width:720,maxHeightRatio:.82,content:u.createElement(ym,{templateIdentifier:e,layoutName:q,t:o,referencedKeys:re,onClose:()=>r.close(ie)})})},[r,e,t.selectedRoute,o,s.document]),De=u.useCallback((q,re)=>{const ie=window.G7Core;if(ie&&typeof ie.t=="function"){const me=ie.t(q,re);if(me&&me!==q&&!me.startsWith("$t:"))return me}return o(q,re)},[o]),Se=u.useCallback(()=>{if(!t.selectedRoute||t.editMode==="extension"||t.editMode==="iteration_item")return;const q=r.open({ariaLabel:o("layout_editor.page_settings.title",{name:t.selectedRoute.path??""}),width:1080,maxHeightRatio:.88,closeOnEscape:!1,content:u.createElement(m$,{templateIdentifier:e,spec:g,t:o,resolveLabel:De,permissionCandidates:O,onClose:()=>r.close(q)})})},[r,t.selectedRoute,t.editMode,o,De,e,g,O]),Ue=u.useCallback(async()=>{const q=await d.createPreview(s.document?.raw??null);if(q.kind!=="success"){const re=q.kind==="network_error"?q.message:o("layout_editor.preview_action.no_document");typeof window<"u"&&window.alert(re)}},[d,s.document,o]),Me=u.useCallback(()=>{const q=t.selectedRoute?.layoutName??"",re=t.selectedRoute?.path??"",ie=t.editMode==="extension"&&re.startsWith("__extension__/")?re.slice(14):null,me=ie?{kind:"extension",extensionId:ie}:q?{kind:"layout",layoutName:q}:null;if(!me)return;const Ce=r.open({ariaLabel:o("layout_editor.version_history.title"),width:640,maxHeightRatio:.82,content:u.createElement(nE,{templateIdentifier:e,target:me,t:o,onRestored:async $e=>{typeof $e=="number"&&(me.kind==="extension"?n({type:"SET_EXTENSION_VERSION",extensionId:me.extensionId,version:$e}):n({type:"SET_LAYOUT_VERSION",layoutName:me.layoutName,version:$e})),await p.reload()},onClose:()=>r.close(Ce)})})},[r,e,t.selectedRoute,t.editMode,o,p,n]),Oe=p.dirtyKeys.size>0||p.isDirty;u.useEffect(()=>{if(!Oe)return;const q=re=>{re.preventDefault(),re.returnValue=""};return window.addEventListener("beforeunload",q),()=>window.removeEventListener("beforeunload",q)},[Oe]);const Ye=u.useCallback(()=>{!p.isDirty||!(!(typeof window<"u")||window.confirm(o("layout_editor.chrome.reset_guard.message")))||p.reload()},[p,o]),ze=u.useCallback(async()=>{const q=await p.save({sessionAddedPaths:I.current});Y(q),q.kind==="success"&&typeof q.newContentVersion=="number"&&(q.savedExtensionId?n({type:"SET_EXTENSION_VERSION",extensionId:q.savedExtensionId,version:q.newContentVersion}):q.savedLayoutName&&n({type:"SET_LAYOUT_VERSION",layoutName:q.savedLayoutName,version:q.newContentVersion}))},[p,n]),Xe=u.useCallback(()=>{const q=r.open({ariaLabel:o("layout_editor.shortcuts.title"),width:560,maxHeightRatio:.85,content:u.createElement(DE,{t:o,onClose:()=>r.close(q)})})},[r,o]),ve=u.useMemo(()=>({save:()=>{ze()},exit:oe,editCode:te,reset:Ye,translations:Ee,addElement:()=>{t.selectedRoute&&n({type:"TOGGLE_PALETTE"})},help:Xe,preview:()=>{t.selectedRoute?.layoutName&&Ue()}}),[ze,oe,te,Ye,Ee,t.selectedRoute,n,Xe,Ue]),[qe,We]=u.useState(!1);u.useEffect(()=>{const q=window.setInterval(()=>{We(!!window.__g7LayoutEditorHasSelection)},200);return()=>window.clearInterval(q)},[]),lp({handlers:ve,hasSelection:qe});const ce=p;return t.routesError?i.jsx("div",{className:"g7le-chrome g7le-chrome--routes-error","data-testid":"g7le-chrome-routes-error",style:{position:"fixed",inset:0,display:"flex",background:"#f8fafc",color:"#0f172a",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Apple SD Gothic Neo", "Noto Sans KR", sans-serif',fontSize:13,lineHeight:1.5,zIndex:9e3},children:i.jsx(qa,{error:t.routesError})}):i.jsx("div",{className:"g7le-chrome","data-testid":"g7le-chrome",ref:X,style:{position:"static",minHeight:"100vh",minWidth:gM,background:"#f8fafc",color:"#0f172a",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Apple SD Gothic Neo", "Noto Sans KR", sans-serif',fontSize:13,lineHeight:1.5,zIndex:9e3},children:i.jsxs(yy,{value:ce,children:[c&&a.needsHostPicker&&a.document&&i.jsx(QD,{hostLayouts:a.document.hostLayouts,extensionLabel:null,onSelect:a.selectHost}),i.jsxs("div",{className:"g7le-chrome__header","data-testid":"g7le-chrome-header",ref:Z,style:{position:"sticky",top:0,zIndex:20,background:"#f8fafc"},children:[i.jsx(Sy,{onSave:()=>{ze()},isDirty:p.isDirty,onExit:oe,onEditCode:te,onManageImages:be,onManageTranslations:Ee,onPageSettings:Se,onReset:Ye,onShowShortcuts:Xe,onPreview:Ue,onShowVersions:Me,templateName:w,templateVersion:x,templateList:S,onSwitchTemplate:G,onToggleCustomAssets:V,customAssetsDisabled:ge,onManageCustomAssets:ee}),i.jsx(GE,{result:F,onDismiss:K,onLoadLatest:se}),i.jsxs("div",{className:"g7le-chrome__device-toolbar","data-testid":"g7le-chrome-device-toolbar",style:{display:"flex",justifyContent:"center",padding:"6px 12px",background:"#f1f5f9",borderBottom:"1px solid #e2e8f0"},children:[i.jsx(vD,{}),i.jsx(_D,{})]})]}),i.jsxs("div",{className:"g7le-chrome__body",style:{display:"grid",gridTemplateColumns:"auto 1fr",alignItems:"stretch"},children:[i.jsx(f7,{}),i.jsx(gD,{manifest:f,nesting:T,componentPalette:g?.componentPalette??null,spec:g,permissionCandidates:O,sampleGlobalSources:h,resolveRouteMatch:H,onNavigateToDestination:P,onSessionAddedPathsChange:L})]}),i.jsx(vy,{})]})})}function _l(e,t){for(const n of e){if(n.kind==="route"&&n.path===t)return n;if(n.children&&n.children.length>0){const o=_l(n.children,t);if(o)return o}}return null}function bM(e,t){return _l(e,t)!==null}function xl(e,t){for(const n of e){if(n.kind==="route"&&n.layoutName===t&&typeof n.path=="string")return n.path;if(n.children&&n.children.length>0){const o=xl(n.children,t);if(o)return o}}return null}function mM(e,t,n){const o=[];Ya({sources:n,isGuestOnly:!1,warn:s=>{const a=/extension '([^']+)' override of core key '([^']+)'/.exec(s);a&&o.push(`${a[1]}:${a[2]}`)}});const r=t?.sampleData?.byDataSourceId?Object.keys(t.sampleData.byDataSourceId).length:0;iy({templateIdentifier:e,mergedSources:[...n.map(s=>({kind:s.kind,id:s.id}))],blockCounts:{controls:t?.controls?Object.keys(t.controls).length:0,componentCapabilities:t?.componentCapabilities?Object.keys(t.componentCapabilities).length:0,actionRecipes:t?.actionRecipes?Object.keys(t.actionRecipes).length:0,conditionRecipes:t?.conditionRecipes?Object.keys(t.conditionRecipes).length:0,paletteGroups:t?.componentPalette?.groups?.length??0,stateGroups:t?.states?.groups?.length??0,sampleDataIds:r},sampleGlobalSourceCount:n.length,sampleGlobalConflicts:o,timestamp:Date.now()})}function Vh({templateIdentifier:e,initialLocale:t}){return u.useEffect(()=>()=>{Zh(),Rh(),ty(),ny(),oy(),ry(),sy(),ay(),ly()},[]),i.jsx(hy,{templateIdentifier:e,initialLocale:t,children:i.jsx(my,{children:i.jsx(yM,{templateIdentifier:e})})})}if(typeof window<"u"){const e=window.G7Core||(window.G7Core={});if(e.__LayoutEditorChrome=Vh,typeof e.__onChromeReady=="function")try{e.__onChromeReady()}catch{}}dn.LayoutEditorChrome=Vh,Object.defineProperty(dn,Symbol.toStringTag,{value:"Module"})})(this.G7LayoutEditor=this.G7LayoutEditor||{},ReactJSXRuntime,React,ReactDOM); + `},d2={onDragStart(e){let{active:t}=e;return"Picked up draggable item "+t.id+"."},onDragOver(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was moved over droppable area "+n.id+".":"Draggable item "+t.id+" is no longer over a droppable area."},onDragEnd(e){let{active:t,over:n}=e;return n?"Draggable item "+t.id+" was dropped over droppable area "+n.id:"Draggable item "+t.id+" was dropped."},onDragCancel(e){let{active:t}=e;return"Dragging was cancelled. Draggable item "+t.id+" was dropped."}};function c2(e){let{announcements:t=d2,container:n,hiddenTextDescribedById:o,screenReaderInstructions:r=l2}=e;const{announce:s,announcement:a}=i2(),l=oi("DndLiveRegion"),[d,c]=u.useState(!1);if(u.useEffect(()=>{c(!0)},[]),s2(u.useMemo(()=>({onDragStart(f){let{active:b}=f;s(t.onDragStart({active:b}))},onDragMove(f){let{active:b,over:g}=f;t.onDragMove&&s(t.onDragMove({active:b,over:g}))},onDragOver(f){let{active:b,over:g}=f;s(t.onDragOver({active:b,over:g}))},onDragEnd(f){let{active:b,over:g}=f;s(t.onDragEnd({active:b,over:g}))},onDragCancel(f){let{active:b,over:g}=f;s(t.onDragCancel({active:b,over:g}))}}),[s,t])),!d)return null;const p=u.createElement(u.Fragment,null,u.createElement(o2,{id:o,value:r.draggable}),u.createElement(r2,{id:l,announcement:a}));return n?Cn.createPortal(p,n):p}var it;(function(e){e.DragStart="dragStart",e.DragMove="dragMove",e.DragEnd="dragEnd",e.DragCancel="dragCancel",e.DragOver="dragOver",e.RegisterDroppable="registerDroppable",e.SetDroppableDisabled="setDroppableDisabled",e.UnregisterDroppable="unregisterDroppable"})(it||(it={}));function si(){}function u2(e,t){return u.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function p2(){for(var e=arguments.length,t=new Array(e),n=0;n[...t].filter(o=>o!=null),[...t])}const Ht=Object.freeze({x:0,y:0});function f2(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function g2(e,t){const n=ii(e);if(!n)return"0 0";const o={x:(n.x-t.left)/t.width*100,y:(n.y-t.top)/t.height*100};return o.x+"% "+o.y+"%"}function h2(e,t){let{data:{value:n}}=e,{data:{value:o}}=t;return n-o}function y2(e,t){let{data:{value:n}}=e,{data:{value:o}}=t;return o-n}function b2(e){let{left:t,top:n,height:o,width:r}=e;return[{x:t,y:n},{x:t+r,y:n},{x:t,y:n+o},{x:t+r,y:n+o}]}function m2(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function v2(e,t){const n=Math.max(t.top,e.top),o=Math.max(t.left,e.left),r=Math.min(t.left+t.width,e.left+e.width),s=Math.min(t.top+t.height,e.top+e.height),a=r-o,l=s-n;if(o{let{collisionRect:t,droppableRects:n,droppableContainers:o}=e;const r=[];for(const s of o){const{id:a}=s,l=n.get(a);if(l){const d=v2(l,t);d>0&&r.push({id:a,data:{droppableContainer:s,value:d}})}}return r.sort(y2)};function x2(e,t){const{top:n,left:o,bottom:r,right:s}=t;return n<=e.y&&e.y<=r&&o<=e.x&&e.x<=s}const w2=e=>{let{droppableContainers:t,droppableRects:n,pointerCoordinates:o}=e;if(!o)return[];const r=[];for(const s of t){const{id:a}=s,l=n.get(a);if(l&&x2(o,l)){const c=b2(l).reduce((f,b)=>f+f2(o,b),0),p=Number((c/4).toFixed(4));r.push({id:a,data:{droppableContainer:s,value:p}})}}return r.sort(h2)};function k2(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function Xp(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:Ht}function S2(e){return function(n){for(var o=arguments.length,r=new Array(o>1?o-1:0),s=1;s({...a,top:a.top+e*l.y,bottom:a.bottom+e*l.y,left:a.left+e*l.x,right:a.right+e*l.x}),{...n})}}const C2=S2(1);function Jp(e){if(e.startsWith("matrix3d(")){const t=e.slice(9,-1).split(/, /);return{x:+t[12],y:+t[13],scaleX:+t[0],scaleY:+t[5]}}else if(e.startsWith("matrix(")){const t=e.slice(7,-1).split(/, /);return{x:+t[4],y:+t[5],scaleX:+t[0],scaleY:+t[3]}}return null}function $2(e,t,n){const o=Jp(t);if(!o)return e;const{scaleX:r,scaleY:s,x:a,y:l}=o,d=e.left-a-(1-r)*parseFloat(n),c=e.top-l-(1-s)*parseFloat(n.slice(n.indexOf(" ")+1)),p=r?e.width/r:e.width,f=s?e.height/s:e.height;return{width:p,height:f,top:c,right:d+p,bottom:c+f,left:d}}const E2={ignoreTransform:!1};function Vo(e,t){t===void 0&&(t=E2);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:c,transformOrigin:p}=xt(e).getComputedStyle(e);c&&(n=$2(n,c,p))}const{top:o,left:r,width:s,height:a,bottom:l,right:d}=n;return{top:o,left:r,width:s,height:a,bottom:l,right:d}}function Zp(e){return Vo(e,{ignoreTransform:!0})}function I2(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function A2(e,t){return t===void 0&&(t=xt(e).getComputedStyle(e)),t.position==="fixed"}function T2(e,t){t===void 0&&(t=xt(e).getComputedStyle(e));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(r=>{const s=t[r];return typeof s=="string"?n.test(s):!1})}function pa(e,t){const n=[];function o(r){if(t!=null&&n.length>=t||!r)return n;if(da(r)&&r.scrollingElement!=null&&!n.includes(r.scrollingElement))return n.push(r.scrollingElement),n;if(!jo(r)||Up(r)||n.includes(r))return n;const s=xt(e).getComputedStyle(r);return r!==e&&T2(r,s)&&n.push(r),A2(r,s)?n:o(r.parentNode)}return e?o(e):n}function Qp(e){const[t]=pa(e,1);return t??null}function fa(e){return!Rr||!e?null:co(e)?e:la(e)?da(e)||e===uo(e).scrollingElement?window:jo(e)?e:null:null}function Rp(e){return co(e)?e.scrollX:e.scrollLeft}function ef(e){return co(e)?e.scrollY:e.scrollTop}function ga(e){return{x:Rp(e),y:ef(e)}}var lt;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(lt||(lt={}));function tf(e){return!Rr||!e?!1:e===document.scrollingElement}function nf(e){const t={x:0,y:0},n=tf(e)?{height:window.innerHeight,width:window.innerWidth}:{height:e.clientHeight,width:e.clientWidth},o={x:e.scrollWidth-n.width,y:e.scrollHeight-n.height},r=e.scrollTop<=t.y,s=e.scrollLeft<=t.x,a=e.scrollTop>=o.y,l=e.scrollLeft>=o.x;return{isTop:r,isLeft:s,isBottom:a,isRight:l,maxScroll:o,minScroll:t}}const D2={x:.2,y:.2};function z2(e,t,n,o,r){let{top:s,left:a,right:l,bottom:d}=n;o===void 0&&(o=10),r===void 0&&(r=D2);const{isTop:c,isBottom:p,isLeft:f,isRight:b}=nf(e),g={x:0,y:0},m={x:0,y:0},h={height:t.height*r.y,width:t.width*r.x};return!c&&s<=t.top+h.height?(g.y=lt.Backward,m.y=o*Math.abs((t.top+h.height-s)/h.height)):!p&&d>=t.bottom-h.height&&(g.y=lt.Forward,m.y=o*Math.abs((t.bottom-h.height-d)/h.height)),!b&&l>=t.right-h.width?(g.x=lt.Forward,m.x=o*Math.abs((t.right-h.width-l)/h.width)):!f&&a<=t.left+h.width&&(g.x=lt.Backward,m.x=o*Math.abs((t.left+h.width-a)/h.width)),{direction:g,speed:m}}function N2(e){if(e===document.scrollingElement){const{innerWidth:s,innerHeight:a}=window;return{top:0,left:0,right:s,bottom:a,width:s,height:a}}const{top:t,left:n,right:o,bottom:r}=e.getBoundingClientRect();return{top:t,left:n,right:o,bottom:r,width:e.clientWidth,height:e.clientHeight}}function of(e){return e.reduce((t,n)=>po(t,ga(n)),Ht)}function M2(e){return e.reduce((t,n)=>t+Rp(n),0)}function L2(e){return e.reduce((t,n)=>t+ef(n),0)}function rf(e,t){if(t===void 0&&(t=Vo),!e)return;const{top:n,left:o,bottom:r,right:s}=t(e);Qp(e)&&(r<=0||s<=0||n>=window.innerHeight||o>=window.innerWidth)&&e.scrollIntoView({block:"center",inline:"center"})}const P2=[["x",["left","right"],M2],["y",["top","bottom"],L2]];class ha{constructor(t,n){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 o=pa(n),r=of(o);this.rect={...t},this.width=t.width,this.height=t.height;for(const[s,a,l]of P2)for(const d of a)Object.defineProperty(this,d,{get:()=>{const c=l(o),p=r[s]-c;return this.rect[d]+p},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Uo{constructor(t){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var o;return(o=this.target)==null?void 0:o.removeEventListener(...n)})},this.target=t}add(t,n,o){var r;(r=this.target)==null||r.addEventListener(t,n,o),this.listeners.push([t,n,o])}}function O2(e){const{EventTarget:t}=xt(e);return e instanceof t?e:uo(e)}function ya(e,t){const n=Math.abs(e.x),o=Math.abs(e.y);return typeof t=="number"?Math.sqrt(n**2+o**2)>t:"x"in t&&"y"in t?n>t.x&&o>t.y:"x"in t?n>t.x:"y"in t?o>t.y:!1}var At;(function(e){e.Click="click",e.DragStart="dragstart",e.Keydown="keydown",e.ContextMenu="contextmenu",e.Resize="resize",e.SelectionChange="selectionchange",e.VisibilityChange="visibilitychange"})(At||(At={}));function sf(e){e.preventDefault()}function B2(e){e.stopPropagation()}var Fe;(function(e){e.Space="Space",e.Down="ArrowDown",e.Right="ArrowRight",e.Left="ArrowLeft",e.Up="ArrowUp",e.Esc="Escape",e.Enter="Enter",e.Tab="Tab"})(Fe||(Fe={}));const af={start:[Fe.Space,Fe.Enter],cancel:[Fe.Esc],end:[Fe.Space,Fe.Enter,Fe.Tab]},W2=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case Fe.Right:return{...n,x:n.x+25};case Fe.Left:return{...n,x:n.x-25};case Fe.Down:return{...n,y:n.y+25};case Fe.Up:return{...n,y:n.y-25}}};class lf{constructor(t){this.props=void 0,this.autoScrollEnabled=!1,this.referenceCoordinates=void 0,this.listeners=void 0,this.windowListeners=void 0,this.props=t;const{event:{target:n}}=t;this.props=t,this.listeners=new Uo(uo(n)),this.windowListeners=new Uo(xt(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(At.Resize,this.handleCancel),this.windowListeners.add(At.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(At.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:t,onStart:n}=this.props,o=t.node.current;o&&rf(o),n(Ht)}handleKeyDown(t){if(ua(t)){const{active:n,context:o,options:r}=this.props,{keyboardCodes:s=af,coordinateGetter:a=W2,scrollBehavior:l="smooth"}=r,{code:d}=t;if(s.end.includes(d)){this.handleEnd(t);return}if(s.cancel.includes(d)){this.handleCancel(t);return}const{collisionRect:c}=o.current,p=c?{x:c.left,y:c.top}:Ht;this.referenceCoordinates||(this.referenceCoordinates=p);const f=a(t,{active:n,context:o.current,currentCoordinates:p});if(f){const b=ri(f,p),g={x:0,y:0},{scrollableAncestors:m}=o.current;for(const h of m){const v=t.code,{isTop:y,isRight:_,isLeft:w,isBottom:k,maxScroll:x,minScroll:$}=nf(h),S=N2(h),C={x:Math.min(v===Fe.Right?S.right-S.width/2:S.right,Math.max(v===Fe.Right?S.left:S.left+S.width/2,f.x)),y:Math.min(v===Fe.Down?S.bottom-S.height/2:S.bottom,Math.max(v===Fe.Down?S.top:S.top+S.height/2,f.y))},T=v===Fe.Right&&!_||v===Fe.Left&&!w,E=v===Fe.Down&&!k||v===Fe.Up&&!y;if(T&&C.x!==f.x){const A=h.scrollLeft+b.x,N=v===Fe.Right&&A<=x.x||v===Fe.Left&&A>=$.x;if(N&&!b.y){h.scrollTo({left:A,behavior:l});return}N?g.x=h.scrollLeft-A:g.x=v===Fe.Right?h.scrollLeft-x.x:h.scrollLeft-$.x,g.x&&h.scrollBy({left:-g.x,behavior:l});break}else if(E&&C.y!==f.y){const A=h.scrollTop+b.y,N=v===Fe.Down&&A<=x.y||v===Fe.Up&&A>=$.y;if(N&&!b.x){h.scrollTo({top:A,behavior:l});return}N?g.y=h.scrollTop-A:g.y=v===Fe.Down?h.scrollTop-x.y:h.scrollTop-$.y,g.y&&h.scrollBy({top:-g.y,behavior:l});break}}this.handleMove(t,po(ri(f,this.referenceCoordinates),g))}}}handleMove(t,n){const{onMove:o}=this.props;t.preventDefault(),o(n)}handleEnd(t){const{onEnd:n}=this.props;t.preventDefault(),this.detach(),n()}handleCancel(t){const{onCancel:n}=this.props;t.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}lf.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:o=af,onActivation:r}=t,{active:s}=n;const{code:a}=e.nativeEvent;if(o.start.includes(a)){const l=s.activatorNode.current;return l&&e.target!==l?!1:(e.preventDefault(),r?.({event:e.nativeEvent}),!0)}return!1}}];function df(e){return!!(e&&"distance"in e)}function cf(e){return!!(e&&"delay"in e)}class ba{constructor(t,n,o){var r;o===void 0&&(o=O2(t.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=t,this.events=n;const{event:s}=t,{target:a}=s;this.props=t,this.events=n,this.document=uo(a),this.documentListeners=new Uo(this.document),this.listeners=new Uo(o),this.windowListeners=new Uo(xt(a)),this.initialCoordinates=(r=ii(s))!=null?r:Ht,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:t,props:{options:{activationConstraint:n,bypassActivationConstraint:o}}}=this;if(this.listeners.add(t.move.name,this.handleMove,{passive:!1}),this.listeners.add(t.end.name,this.handleEnd),t.cancel&&this.listeners.add(t.cancel.name,this.handleCancel),this.windowListeners.add(At.Resize,this.handleCancel),this.windowListeners.add(At.DragStart,sf),this.windowListeners.add(At.VisibilityChange,this.handleCancel),this.windowListeners.add(At.ContextMenu,sf),this.documentListeners.add(At.Keydown,this.handleKeydown),n){if(o!=null&&o({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(cf(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(df(n)){this.handlePending(n);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(t,n){const{active:o,onPending:r}=this.props;r(o,t,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:t}=this,{onStart:n}=this.props;t&&(this.activated=!0,this.documentListeners.add(At.Click,B2,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(At.SelectionChange,this.removeTextSelection),n(t))}handleMove(t){var n;const{activated:o,initialCoordinates:r,props:s}=this,{onMove:a,options:{activationConstraint:l}}=s;if(!r)return;const d=(n=ii(t))!=null?n:Ht,c=ri(r,d);if(!o&&l){if(df(l)){if(l.tolerance!=null&&ya(c,l.tolerance))return this.handleCancel();if(ya(c,l.distance))return this.handleStart()}if(cf(l)&&ya(c,l.tolerance))return this.handleCancel();this.handlePending(l,c);return}t.cancelable&&t.preventDefault(),a(d)}handleEnd(){const{onAbort:t,onEnd:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleCancel(){const{onAbort:t,onCancel:n}=this.props;this.detach(),this.activated||t(this.props.active),n()}handleKeydown(t){t.code===Fe.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const j2={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class ma extends ba{constructor(t){const{event:n}=t,o=uo(n.target);super(t,j2,o)}}ma.activators=[{eventName:"onPointerDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:o}=t;return!n.isPrimary||n.button!==0?!1:(o?.({event:n}),!0)}}];const H2={move:{name:"mousemove"},end:{name:"mouseup"}};var va;(function(e){e[e.RightClick=2]="RightClick"})(va||(va={}));class F2 extends ba{constructor(t){super(t,H2,uo(t.event.target))}}F2.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:o}=t;return n.button===va.RightClick?!1:(o?.({event:n}),!0)}}];const _a={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class K2 extends ba{constructor(t){super(t,_a)}static setup(){return window.addEventListener(_a.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(_a.move.name,t)};function t(){}}}K2.activators=[{eventName:"onTouchStart",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:o}=t;const{touches:r}=n;return r.length>1?!1:(o?.({event:n}),!0)}}];var qo;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(qo||(qo={}));var ai;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(ai||(ai={}));function V2(e){let{acceleration:t,activator:n=qo.Pointer,canScroll:o,draggingRect:r,enabled:s,interval:a=5,order:l=ai.TreeOrder,pointerCoordinates:d,scrollableAncestors:c,scrollableAncestorRects:p,delta:f,threshold:b}=e;const g=q2({delta:f,disabled:!s}),[m,h]=Q7(),v=u.useRef({x:0,y:0}),y=u.useRef({x:0,y:0}),_=u.useMemo(()=>{switch(n){case qo.Pointer:return d?{top:d.y,bottom:d.y,left:d.x,right:d.x}:null;case qo.DraggableRect:return r}},[n,r,d]),w=u.useRef(null),k=u.useCallback(()=>{const $=w.current;if(!$)return;const S=v.current.x*y.current.x,C=v.current.y*y.current.y;$.scrollBy(S,C)},[]),x=u.useMemo(()=>l===ai.TreeOrder?[...c].reverse():c,[l,c]);u.useEffect(()=>{if(!s||!c.length||!_){h();return}for(const $ of x){if(o?.($)===!1)continue;const S=c.indexOf($),C=p[S];if(!C)continue;const{direction:T,speed:E}=z2($,C,_,t,b);for(const A of["x","y"])g[A][T[A]]||(E[A]=0,T[A]=0);if(E.x>0||E.y>0){h(),w.current=$,m(k,a),v.current=E,y.current=T;return}}v.current={x:0,y:0},y.current={x:0,y:0},h()},[t,k,o,h,s,a,JSON.stringify(_),JSON.stringify(g),m,c,x,p,JSON.stringify(b)])}const U2={x:{[lt.Backward]:!1,[lt.Forward]:!1},y:{[lt.Backward]:!1,[lt.Forward]:!1}};function q2(e){let{delta:t,disabled:n}=e;const o=ni(t);return Fo(r=>{if(n||!o||!r)return U2;const s={x:Math.sign(t.x-o.x),y:Math.sign(t.y-o.y)};return{x:{[lt.Backward]:r.x[lt.Backward]||s.x===-1,[lt.Forward]:r.x[lt.Forward]||s.x===1},y:{[lt.Backward]:r.y[lt.Backward]||s.y===-1,[lt.Forward]:r.y[lt.Forward]||s.y===1}}},[n,t,o])}function G2(e,t){const n=t!=null?e.get(t):void 0,o=n?n.node.current:null;return Fo(r=>{var s;return t==null?null:(s=o??r)!=null?s:null},[o,t])}function Y2(e,t){return u.useMemo(()=>e.reduce((n,o)=>{const{sensor:r}=o,s=r.activators.map(a=>({eventName:a.eventName,handler:t(a.handler,o)}));return[...n,...s]},[]),[e,t])}var Go;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Go||(Go={}));var xa;(function(e){e.Optimized="optimized"})(xa||(xa={}));const uf=new Map;function X2(e,t){let{dragging:n,dependencies:o,config:r}=t;const[s,a]=u.useState(null),{frequency:l,measure:d,strategy:c}=r,p=u.useRef(e),f=v(),b=Ho(f),g=u.useCallback(function(y){y===void 0&&(y=[]),!b.current&&a(_=>_===null?y:_.concat(y.filter(w=>!_.includes(w))))},[b]),m=u.useRef(null),h=Fo(y=>{if(f&&!n)return uf;if(!y||y===uf||p.current!==e||s!=null){const _=new Map;for(let w of e){if(!w)continue;if(s&&s.length>0&&!s.includes(w.id)&&w.rect.current){_.set(w.id,w.rect.current);continue}const k=w.node.current,x=k?new ha(d(k),k):null;w.rect.current=x,x&&_.set(w.id,x)}return _}return y},[e,s,n,f,d]);return u.useEffect(()=>{p.current=e},[e]),u.useEffect(()=>{f||g()},[n,f]),u.useEffect(()=>{s&&s.length>0&&a(null)},[JSON.stringify(s)]),u.useEffect(()=>{f||typeof l!="number"||m.current!==null||(m.current=setTimeout(()=>{g(),m.current=null},l))},[l,f,g,...o]),{droppableRects:h,measureDroppableContainers:g,measuringScheduled:s!=null};function v(){switch(c){case Go.Always:return!1;case Go.BeforeDragging:return n;default:return!n}}}function wa(e,t){return Fo(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function J2(e,t){return wa(e,t)}function Z2(e){let{callback:t,disabled:n}=e;const o=ei(t),r=u.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:s}=window;return new s(o)},[o,n]);return u.useEffect(()=>()=>r?.disconnect(),[r]),r}function li(e){let{callback:t,disabled:n}=e;const o=ei(t),r=u.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:s}=window;return new s(o)},[n]);return u.useEffect(()=>()=>r?.disconnect(),[r]),r}function Q2(e){return new ha(Vo(e),e)}function pf(e,t,n){t===void 0&&(t=Q2);const[o,r]=u.useState(null);function s(){r(d=>{if(!e)return null;if(e.isConnected===!1){var c;return(c=d??n)!=null?c:null}const p=t(e);return JSON.stringify(d)===JSON.stringify(p)?d:p})}const a=Z2({callback(d){if(e)for(const c of d){const{type:p,target:f}=c;if(p==="childList"&&f instanceof HTMLElement&&f.contains(e)){s();break}}}}),l=li({callback:s});return sn(()=>{s(),e?(l?.observe(e),a?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),a?.disconnect())},[e]),o}function R2(e){const t=wa(e);return Xp(e,t)}const ff=[];function eI(e){const t=u.useRef(e),n=Fo(o=>e?o&&o!==ff&&e&&t.current&&e.parentNode===t.current.parentNode?o:pa(e):ff,[e]);return u.useEffect(()=>{t.current=e},[e]),n}function tI(e){const[t,n]=u.useState(null),o=u.useRef(e),r=u.useCallback(s=>{const a=fa(s.target);a&&n(l=>l?(l.set(a,ga(a)),new Map(l)):null)},[]);return u.useEffect(()=>{const s=o.current;if(e!==s){a(s);const l=e.map(d=>{const c=fa(d);return c?(c.addEventListener("scroll",r,{passive:!0}),[c,ga(c)]):null}).filter(d=>d!=null);n(l.length?new Map(l):null),o.current=e}return()=>{a(e),a(s)};function a(l){l.forEach(d=>{const c=fa(d);c?.removeEventListener("scroll",r)})}},[r,e]),u.useMemo(()=>e.length?t?Array.from(t.values()).reduce((s,a)=>po(s,a),Ht):of(e):Ht,[e,t])}function gf(e,t){t===void 0&&(t=[]);const n=u.useRef(null);return u.useEffect(()=>{n.current=null},t),u.useEffect(()=>{const o=e!==Ht;o&&!n.current&&(n.current=e),!o&&n.current&&(n.current=null)},[e]),n.current?ri(e,n.current):Ht}function nI(e){u.useEffect(()=>{if(!Rr)return;const t=e.map(n=>{let{sensor:o}=n;return o.setup==null?void 0:o.setup()});return()=>{for(const n of t)n?.()}},e.map(t=>{let{sensor:n}=t;return n}))}function oI(e,t){return u.useMemo(()=>e.reduce((n,o)=>{let{eventName:r,handler:s}=o;return n[r]=a=>{s(a,t)},n},{}),[e,t])}function hf(e){return u.useMemo(()=>e?I2(e):null,[e])}const yf=[];function rI(e,t){t===void 0&&(t=Vo);const[n]=e,o=hf(n?xt(n):null),[r,s]=u.useState(yf);function a(){s(()=>e.length?e.map(d=>tf(d)?o:new ha(t(d),d)):yf)}const l=li({callback:a});return sn(()=>{l?.disconnect(),a(),e.forEach(d=>l?.observe(d))},[e]),r}function bf(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return jo(t)?t:e}function iI(e){let{measure:t}=e;const[n,o]=u.useState(null),r=u.useCallback(c=>{for(const{target:p}of c)if(jo(p)){o(f=>{const b=t(p);return f?{...f,width:b.width,height:b.height}:b});break}},[t]),s=li({callback:r}),a=u.useCallback(c=>{const p=bf(c);s?.disconnect(),p&&s?.observe(p),o(p?t(p):null)},[t,s]),[l,d]=ti(a);return u.useMemo(()=>({nodeRef:l,rect:n,setRef:d}),[n,l,d])}const sI=[{sensor:ma,options:{}},{sensor:lf,options:{}}],aI={current:{}},di={draggable:{measure:Zp},droppable:{measure:Zp,strategy:Go.WhileDragging,frequency:xa.Optimized},dragOverlay:{measure:Vo}};class Yo extends Map{get(t){var n;return t!=null&&(n=super.get(t))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(t=>{let{disabled:n}=t;return!n})}getNodeFor(t){var n,o;return(n=(o=this.get(t))==null?void 0:o.node.current)!=null?n:void 0}}const lI={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Yo,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:si},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:di,measureDroppableContainers:si,windowRect:null,measuringScheduled:!1},mf={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:si,draggableNodes:new Map,over:null,measureDroppableContainers:si},Xo=u.createContext(mf),vf=u.createContext(lI);function dI(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Yo}}}function cI(e,t){switch(t.type){case it.DragStart:return{...e,draggable:{...e.draggable,initialCoordinates:t.initialCoordinates,active:t.active}};case it.DragMove:return e.draggable.active==null?e:{...e,draggable:{...e.draggable,translate:{x:t.coordinates.x-e.draggable.initialCoordinates.x,y:t.coordinates.y-e.draggable.initialCoordinates.y}}};case it.DragEnd:case it.DragCancel:return{...e,draggable:{...e.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case it.RegisterDroppable:{const{element:n}=t,{id:o}=n,r=new Yo(e.droppable.containers);return r.set(o,n),{...e,droppable:{...e.droppable,containers:r}}}case it.SetDroppableDisabled:{const{id:n,key:o,disabled:r}=t,s=e.droppable.containers.get(n);if(!s||o!==s.key)return e;const a=new Yo(e.droppable.containers);return a.set(n,{...s,disabled:r}),{...e,droppable:{...e.droppable,containers:a}}}case it.UnregisterDroppable:{const{id:n,key:o}=t,r=e.droppable.containers.get(n);if(!r||o!==r.key)return e;const s=new Yo(e.droppable.containers);return s.delete(n),{...e,droppable:{...e.droppable,containers:s}}}default:return e}}function uI(e){let{disabled:t}=e;const{active:n,activatorEvent:o,draggableNodes:r}=u.useContext(Xo),s=ni(o),a=ni(n?.id);return u.useEffect(()=>{if(!t&&!o&&s&&a!=null){if(!ua(s)||document.activeElement===s.target)return;const l=r.get(a);if(!l)return;const{activatorNode:d,node:c}=l;if(!d.current&&!c.current)return;requestAnimationFrame(()=>{for(const p of[d.current,c.current]){if(!p)continue;const f=t2(p);if(f){f.focus();break}}})}},[o,t,r,a,s]),null}function _f(e,t){let{transform:n,...o}=t;return e!=null&&e.length?e.reduce((r,s)=>s({transform:r,...o}),n):n}function pI(e){return u.useMemo(()=>({draggable:{...di.draggable,...e?.draggable},droppable:{...di.droppable,...e?.droppable},dragOverlay:{...di.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function fI(e){let{activeNode:t,measure:n,initialRect:o,config:r=!0}=e;const s=u.useRef(!1),{x:a,y:l}=typeof r=="boolean"?{x:r,y:r}:r;sn(()=>{if(!a&&!l||!t){s.current=!1;return}if(s.current||!o)return;const c=t?.node.current;if(!c||c.isConnected===!1)return;const p=n(c),f=Xp(p,o);if(a||(f.x=0),l||(f.y=0),s.current=!0,Math.abs(f.x)>0||Math.abs(f.y)>0){const b=Qp(c);b&&b.scrollBy({top:f.y,left:f.x})}},[t,a,l,o,n])}const ci=u.createContext({...Ht,scaleX:1,scaleY:1});var hn;(function(e){e[e.Uninitialized=0]="Uninitialized",e[e.Initializing=1]="Initializing",e[e.Initialized=2]="Initialized"})(hn||(hn={}));const gI=u.memo(function(t){var n,o,r,s;let{id:a,accessibility:l,autoScroll:d=!0,children:c,sensors:p=sI,collisionDetection:f=_2,measuring:b,modifiers:g,...m}=t;const h=u.useReducer(cI,void 0,dI),[v,y]=h,[_,w]=a2(),[k,x]=u.useState(hn.Uninitialized),$=k===hn.Initialized,{draggable:{active:S,nodes:C,translate:T},droppable:{containers:E}}=v,A=S!=null?C.get(S):null,N=u.useRef({initial:null,translated:null}),D=u.useMemo(()=>{var Q;return S!=null?{id:S,data:(Q=A?.data)!=null?Q:aI,rect:N}:null},[S,A]),B=u.useRef(null),[M,O]=u.useState(null),[z,H]=u.useState(null),P=Ho(m,Object.values(m)),I=oi("DndDescribedBy",a),L=u.useMemo(()=>E.getEnabled(),[E]),F=pI(b),{droppableRects:Y,measureDroppableContainers:K,measuringScheduled:X}=X2(L,{dragging:$,dependencies:[T.x,T.y],config:F.droppable}),Z=G2(C,S),ae=u.useMemo(()=>z?ii(z):null,[z]),oe=pe(),G=J2(Z,F.draggable.measure);fI({activeNode:S!=null?C.get(S):null,config:oe.layoutShiftCompensation,initialRect:G,measure:F.draggable.measure});const ee=pf(Z,F.draggable.measure,G),ge=pf(Z?Z.parentElement:null),V=u.useRef({activatorEvent:null,active:null,activeNode:Z,collisionRect:null,collisions:null,droppableRects:Y,draggableNodes:C,draggingNode:null,draggingNodeRect:null,droppableContainers:E,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),te=E.getNodeFor((n=V.current.over)==null?void 0:n.id),be=iI({measure:F.dragOverlay.measure}),Ee=(o=be.nodeRef.current)!=null?o:Z,De=$?(r=be.rect)!=null?r:ee:null,Se=!!(be.nodeRef.current&&be.rect),Ue=R2(Se?null:ee),Me=hf(Ee?xt(Ee):null),Oe=eI($?te??Z:null),Ye=rI(Oe),ze=_f(g,{transform:{x:T.x-Ue.x,y:T.y-Ue.y,scaleX:1,scaleY:1},activatorEvent:z,active:D,activeNodeRect:ee,containerNodeRect:ge,draggingNodeRect:De,over:V.current.over,overlayNodeRect:be.rect,scrollableAncestors:Oe,scrollableAncestorRects:Ye,windowRect:Me}),Xe=ae?po(ae,T):null,ve=tI(Oe),qe=gf(ve),We=gf(ve,[ee]),ce=po(ze,qe),q=De?C2(De,ze):null,ie=D&&q?f({active:D,collisionRect:q,droppableRects:Y,droppableContainers:L,pointerCoordinates:Xe}):null,se=m2(ie,"id"),[me,Ce]=u.useState(null),$e=Se?ze:po(ze,We),U=k2($e,(s=me?.rect)!=null?s:null,ee),ue=u.useRef(null),fe=u.useCallback((Q,le)=>{let{sensor:Ae,options:dt}=le;if(B.current==null)return;const pt=C.get(B.current);if(!pt)return;const ot=Q.nativeEvent,Le=new Ae({active:B.current,activeNode:pt,event:ot,options:dt,context:V,onAbort(Je){if(!C.get(Je))return;const{onDragAbort:Dt}=P.current,zt={id:Je};Dt?.(zt),_({type:"onDragAbort",event:zt})},onPending(Je,Tt,Dt,zt){if(!C.get(Je))return;const{onDragPending:wn}=P.current,Zt={id:Je,constraint:Tt,initialCoordinates:Dt,offset:zt};wn?.(Zt),_({type:"onDragPending",event:Zt})},onStart(Je){const Tt=B.current;if(Tt==null)return;const Dt=C.get(Tt);if(!Dt)return;const{onDragStart:zt}=P.current,xn={activatorEvent:ot,active:{id:Tt,data:Dt.data,rect:N}};Cn.unstable_batchedUpdates(()=>{zt?.(xn),x(hn.Initializing),y({type:it.DragStart,initialCoordinates:Je,active:Tt}),_({type:"onDragStart",event:xn}),O(ue.current),H(ot)})},onMove(Je){y({type:it.DragMove,coordinates:Je})},onEnd:je(it.DragEnd),onCancel:je(it.DragCancel)});ue.current=Le;function je(Je){return async function(){const{active:Dt,collisions:zt,over:xn,scrollAdjustedTranslate:wn}=V.current;let Zt=null;if(Dt&&wn){const{cancelDrop:Hn}=P.current;Zt={activatorEvent:ot,active:Dt,collisions:zt,delta:wn,over:xn},Je===it.DragEnd&&typeof Hn=="function"&&await Promise.resolve(Hn(Zt))&&(Je=it.DragCancel)}B.current=null,Cn.unstable_batchedUpdates(()=>{y({type:Je}),x(hn.Uninitialized),Ce(null),O(null),H(null),ue.current=null;const Hn=Je===it.DragEnd?"onDragEnd":"onDragCancel";if(Zt){const ln=P.current[Hn];ln?.(Zt),_({type:Hn,event:Zt})}})}}},[C]),xe=u.useCallback((Q,le)=>(Ae,dt)=>{const pt=Ae.nativeEvent,ot=C.get(dt);if(B.current!==null||!ot||pt.dndKit||pt.defaultPrevented)return;const Le={active:ot};Q(Ae,le.options,Le)===!0&&(pt.dndKit={capturedBy:le.sensor},B.current=dt,fe(Ae,le))},[C,fe]),he=Y2(p,xe);nI(p),sn(()=>{ee&&k===hn.Initializing&&x(hn.Initialized)},[ee,k]),u.useEffect(()=>{const{onDragMove:Q}=P.current,{active:le,activatorEvent:Ae,collisions:dt,over:pt}=V.current;if(!le||!Ae)return;const ot={active:le,activatorEvent:Ae,collisions:dt,delta:{x:ce.x,y:ce.y},over:pt};Cn.unstable_batchedUpdates(()=>{Q?.(ot),_({type:"onDragMove",event:ot})})},[ce.x,ce.y]),u.useEffect(()=>{const{active:Q,activatorEvent:le,collisions:Ae,droppableContainers:dt,scrollAdjustedTranslate:pt}=V.current;if(!Q||B.current==null||!le||!pt)return;const{onDragOver:ot}=P.current,Le=dt.get(se),je=Le&&Le.rect.current?{id:Le.id,rect:Le.rect.current,data:Le.data,disabled:Le.disabled}:null,Je={active:Q,activatorEvent:le,collisions:Ae,delta:{x:pt.x,y:pt.y},over:je};Cn.unstable_batchedUpdates(()=>{Ce(je),ot?.(Je),_({type:"onDragOver",event:Je})})},[se]),sn(()=>{V.current={activatorEvent:z,active:D,activeNode:Z,collisionRect:q,collisions:ie,droppableRects:Y,draggableNodes:C,draggingNode:Ee,draggingNodeRect:De,droppableContainers:E,over:me,scrollableAncestors:Oe,scrollAdjustedTranslate:ce},N.current={initial:De,translated:q}},[D,Z,ie,q,C,Ee,De,Y,E,me,Oe,ce]),V2({...oe,delta:T,draggingRect:q,pointerCoordinates:Xe,scrollableAncestors:Oe,scrollableAncestorRects:Ye});const j=u.useMemo(()=>({active:D,activeNode:Z,activeNodeRect:ee,activatorEvent:z,collisions:ie,containerNodeRect:ge,dragOverlay:be,draggableNodes:C,droppableContainers:E,droppableRects:Y,over:me,measureDroppableContainers:K,scrollableAncestors:Oe,scrollableAncestorRects:Ye,measuringConfiguration:F,measuringScheduled:X,windowRect:Me}),[D,Z,ee,z,ie,ge,be,C,E,Y,me,K,Oe,Ye,F,X,Me]),ne=u.useMemo(()=>({activatorEvent:z,activators:he,active:D,activeNodeRect:ee,ariaDescribedById:{draggable:I},dispatch:y,draggableNodes:C,over:me,measureDroppableContainers:K}),[z,he,D,ee,y,I,C,me,K]);return u.createElement(Yp.Provider,{value:w},u.createElement(Xo.Provider,{value:ne},u.createElement(vf.Provider,{value:j},u.createElement(ci.Provider,{value:U},c)),u.createElement(uI,{disabled:l?.restoreFocus===!1})),u.createElement(c2,{...l,hiddenTextDescribedById:I}));function pe(){const Q=M?.autoScrollEnabled===!1,le=typeof d=="object"?d.enabled===!1:d===!1,Ae=$&&!Q&&!le;return typeof d=="object"?{...d,enabled:Ae}:{enabled:Ae}}}),hI=u.createContext(null),xf="button",yI="Draggable";function bI(e){let{id:t,data:n,disabled:o=!1,attributes:r}=e;const s=oi(yI),{activators:a,activatorEvent:l,active:d,activeNodeRect:c,ariaDescribedById:p,draggableNodes:f,over:b}=u.useContext(Xo),{role:g=xf,roleDescription:m="draggable",tabIndex:h=0}=r??{},v=d?.id===t,y=u.useContext(v?ci:hI),[_,w]=ti(),[k,x]=ti(),$=oI(a,t),S=Ho(n);sn(()=>(f.set(t,{id:t,key:s,node:_,activatorNode:k,data:S}),()=>{const T=f.get(t);T&&T.key===s&&f.delete(t)}),[f,t]);const C=u.useMemo(()=>({role:g,tabIndex:h,"aria-disabled":o,"aria-pressed":v&&g===xf?!0:void 0,"aria-roledescription":m,"aria-describedby":p.draggable}),[o,g,h,v,m,p.draggable]);return{active:d,activatorEvent:l,activeNodeRect:c,attributes:C,isDragging:v,listeners:o?void 0:$,node:_,over:b,setNodeRef:w,setActivatorNodeRef:x,transform:y}}function mI(){return u.useContext(vf)}const vI="Droppable",_I={timeout:25};function xI(e){let{data:t,disabled:n=!1,id:o,resizeObserverConfig:r}=e;const s=oi(vI),{active:a,dispatch:l,over:d,measureDroppableContainers:c}=u.useContext(Xo),p=u.useRef({disabled:n}),f=u.useRef(!1),b=u.useRef(null),g=u.useRef(null),{disabled:m,updateMeasurementsFor:h,timeout:v}={..._I,...r},y=Ho(h??o),_=u.useCallback(()=>{if(!f.current){f.current=!0;return}g.current!=null&&clearTimeout(g.current),g.current=setTimeout(()=>{c(Array.isArray(y.current)?y.current:[y.current]),g.current=null},v)},[v]),w=li({callback:_,disabled:m||!a}),k=u.useCallback((C,T)=>{w&&(T&&(w.unobserve(T),f.current=!1),C&&w.observe(C))},[w]),[x,$]=ti(k),S=Ho(t);return u.useEffect(()=>{!w||!x.current||(w.disconnect(),f.current=!1,w.observe(x.current))},[x,w]),u.useEffect(()=>(l({type:it.RegisterDroppable,element:{id:o,key:s,disabled:n,node:x,rect:b,data:S}}),()=>l({type:it.UnregisterDroppable,key:s,id:o})),[o]),u.useEffect(()=>{n!==p.current.disabled&&(l({type:it.SetDroppableDisabled,id:o,key:s,disabled:n}),p.current.disabled=n)},[o,s,n,l]),{active:a,rect:b,isOver:d?.id===o,node:x,over:d,setNodeRef:$}}function wI(e){let{animation:t,children:n}=e;const[o,r]=u.useState(null),[s,a]=u.useState(null),l=ni(n);return!n&&!o&&l&&r(l),sn(()=>{if(!s)return;const d=o?.key,c=o?.props.id;if(d==null||c==null){r(null);return}Promise.resolve(t(c,s)).then(()=>{r(null)})},[t,o,s]),u.createElement(u.Fragment,null,n,o?u.cloneElement(o,{ref:a}):null)}const kI={x:0,y:0,scaleX:1,scaleY:1};function SI(e){let{children:t}=e;return u.createElement(Xo.Provider,{value:mf},u.createElement(ci.Provider,{value:kI},t))}const CI={position:"fixed",touchAction:"none"},$I=e=>ua(e)?"transform 250ms ease":void 0,EI=u.forwardRef((e,t)=>{let{as:n,activatorEvent:o,adjustScale:r,children:s,className:a,rect:l,style:d,transform:c,transition:p=$I}=e;if(!l)return null;const f=r?c:{...c,scaleX:1,scaleY:1},b={...CI,width:l.width,height:l.height,top:l.top,left:l.left,transform:Ko.Transform.toString(f),transformOrigin:r&&o?g2(o,l):void 0,transition:typeof p=="function"?p(o):p,...d};return u.createElement(n,{className:a,style:b,ref:t},s)}),II={duration:250,easing:"ease",keyframes:e=>{let{transform:{initial:t,final:n}}=e;return[{transform:Ko.Transform.toString(t)},{transform:Ko.Transform.toString(n)}]},sideEffects:(e=>t=>{let{active:n,dragOverlay:o}=t;const r={},{styles:s,className:a}=e;if(s!=null&&s.active)for(const[l,d]of Object.entries(s.active))d!==void 0&&(r[l]=n.node.style.getPropertyValue(l),n.node.style.setProperty(l,d));if(s!=null&&s.dragOverlay)for(const[l,d]of Object.entries(s.dragOverlay))d!==void 0&&o.node.style.setProperty(l,d);return a!=null&&a.active&&n.node.classList.add(a.active),a!=null&&a.dragOverlay&&o.node.classList.add(a.dragOverlay),function(){for(const[d,c]of Object.entries(r))n.node.style.setProperty(d,c);a!=null&&a.active&&n.node.classList.remove(a.active)}})({styles:{active:{opacity:"0"}}})};function AI(e){let{config:t,draggableNodes:n,droppableContainers:o,measuringConfiguration:r}=e;return ei((s,a)=>{if(t===null)return;const l=n.get(s);if(!l)return;const d=l.node.current;if(!d)return;const c=bf(a);if(!c)return;const{transform:p}=xt(a).getComputedStyle(a),f=Jp(p);if(!f)return;const b=typeof t=="function"?t:TI(t);return rf(d,r.draggable.measure),b({active:{id:s,data:l.data,node:d,rect:r.draggable.measure(d)},draggableNodes:n,dragOverlay:{node:a,rect:r.dragOverlay.measure(c)},droppableContainers:o,measuringConfiguration:r,transform:f})})}function TI(e){const{duration:t,easing:n,sideEffects:o,keyframes:r}={...II,...e};return s=>{let{active:a,dragOverlay:l,transform:d,...c}=s;if(!t)return;const p={x:l.rect.left-a.rect.left,y:l.rect.top-a.rect.top},f={scaleX:d.scaleX!==1?a.rect.width*d.scaleX/l.rect.width:1,scaleY:d.scaleY!==1?a.rect.height*d.scaleY/l.rect.height:1},b={x:d.x-p.x,y:d.y-p.y,...f},g=r({...c,active:a,dragOverlay:l,transform:{initial:d,final:b}}),[m]=g,h=g[g.length-1];if(JSON.stringify(m)===JSON.stringify(h))return;const v=o?.({active:a,dragOverlay:l,...c}),y=l.node.animate(g,{duration:t,easing:n,fill:"forwards"});return new Promise(_=>{y.onfinish=()=>{v?.(),_()}})}}let wf=0;function DI(e){return u.useMemo(()=>{if(e!=null)return wf++,wf},[e])}const zI=u.memo(e=>{let{adjustScale:t=!1,children:n,dropAnimation:o,style:r,transition:s,modifiers:a,wrapperElement:l="div",className:d,zIndex:c=999}=e;const{activatorEvent:p,active:f,activeNodeRect:b,containerNodeRect:g,draggableNodes:m,droppableContainers:h,dragOverlay:v,over:y,measuringConfiguration:_,scrollableAncestors:w,scrollableAncestorRects:k,windowRect:x}=mI(),$=u.useContext(ci),S=DI(f?.id),C=_f(a,{activatorEvent:p,active:f,activeNodeRect:b,containerNodeRect:g,draggingNodeRect:v.rect,over:y,overlayNodeRect:v.rect,scrollableAncestors:w,scrollableAncestorRects:k,transform:$,windowRect:x}),T=wa(b),E=AI({config:o,draggableNodes:m,droppableContainers:h,measuringConfiguration:_}),A=T?v.setRef:void 0;return u.createElement(SI,null,u.createElement(wI,{animation:E},f&&S?u.createElement(EI,{key:S,id:f.id,ref:A,as:l,activatorEvent:p,adjustScale:t,className:d,transition:s,rect:T,style:{zIndex:c,...r},transform:C},n):null))});function Jo(e,t){return!t||!Array.isArray(t.draggable)?!1:t.draggable.includes(e)}function NI({draggedComponentName:e,targetContainerName:t,nesting:n}){if(!n||!Jo(e,n))return!1;const o=n.containers;if(!o||typeof o!="object")return!1;const r=o[t];return!r||!Array.isArray(r.accepts)?!1:r.accepts.includes(e)}function kf(e,t){if(!t?.containers)return!1;const n=t.containers[e];return!!(n&&Array.isArray(n.accepts)&&n.accepts.length>0)}function MI(e,t,n,o,r){if(!n||n.length===0)return{parentPath:[],index:r};if(e&&kf(e,o))return{parentPath:n,index:t};const s=n.slice(0,-1),a=n[n.length-1]??0;return{parentPath:s,index:a+1}}function Sf(e,t){return e===t||e.startsWith(`${t}.`)}function Cf(e,t){if(e==="")return/^\d+$/.test(t)?Number(t):null;const n=`${e}.children.`;if(!t.startsWith(n))return null;const o=t.slice(n.length);return/^\d+$/.test(o)?Number(o):null}function LI(e,t){const n=[];return e.querySelectorAll("[data-editor-path]").forEach(o=>{if(o.hasAttribute("data-dnd-placeholder")||o.closest("[data-dnd-placeholder]"))return;const r=o.dataset.editorPath;typeof r=="string"&&n.push({path:t(r),domPath:r,rect:o.getBoundingClientRect()})}),n}const PI=16;function OI(e){const{frameEl:t,draggedPath:n,acceptsContainer:o,allowsNestSlot:r,includeContainer:s}=e,a=e.normalizeContainerPath??(g=>g),l=t.getBoundingClientRect(),d=LI(t,a),c=new Map;for(const g of d)c.has(g.path)||c.set(g.path,g.domPath);const p=a(n),f=new Set([""]);for(const g of d){const m=WI(g.path);m!==null&&f.add(m)}for(const g of d)f.add(g.path);const b=[];for(const g of f){const m=g==="",h=m?null:c.get(g)??g,v=m?t:t.querySelector(`[data-editor-path="${If(h)}"]`);if(!v&&!m||!m&&Sf(g,p))continue;const y=g;if(!m&&s&&!s(y))continue;const _=$=>{const S=c.get($);if(!S||typeof window>"u")return!1;const C=t.querySelector(`[data-editor-path="${If(S)}"]`);return C?(window.getComputedStyle(C).display??"").toLowerCase()==="contents":!1},w=d.filter($=>Cf(g,$.path)!==null).filter($=>!Sf($.path,p)).filter($=>!_($.path)).map($=>({origIndex:Cf(g,$.path),rect:BI($.rect,$.path,d)})).filter($=>$.rect.width>0||$.rect.height>0).sort(($,S)=>$.origIndex-S.origIndex),k=Op(m?t:v).kind,x=k==="flex_row_single"||k==="flex_row_wrap"||k==="grid_single_row"||k==="grid_2d";if(w.length>0){if(o(y)){w.forEach(S=>{b.push($f(y,S.origIndex,S.rect,l,x,"before"))});const $=w[w.length-1];b.push($f(y,$.origIndex+1,$.rect,l,x,"after"))}}else if(!m&&r(y)&&v){const $=v.getBoundingClientRect();$.width>0&&$.height>0&&b.push({id:`slot:${y}:0`,kind:"nest",containerPath:y,index:0,box:Ef($,l),orientation:"area"})}else m&&b.push({id:"slot::0",kind:"gap",containerPath:"",index:0,box:Ef(l,l),orientation:"area"})}return b.filter(g=>lo(g.box,t))}function $f(e,t,n,o,r,s){const a=PI;let l;if(r)l={left:(s==="before"?n.left:n.right)-a/2,top:n.top,width:a,height:n.height};else{const d=s==="before"?n.top:n.bottom;l={left:n.left,top:d-a/2,width:n.width,height:a}}return{id:`slot:${e}:${t}`,kind:"gap",containerPath:e,index:t,box:{left:l.left-o.left,top:l.top-o.top,width:l.width,height:l.height,scale:1},orientation:r?"vertical":"horizontal"}}function BI(e,t,n){if(e.width>0||e.height>0)return e;const o=`${t}.children.`;let r=1/0,s=1/0,a=-1/0,l=-1/0;for(const d of n)d.path.startsWith(o)&&(d.rect.width===0&&d.rect.height===0||(r=Math.min(r,d.rect.left),s=Math.min(s,d.rect.top),a=Math.max(a,d.rect.right),l=Math.max(l,d.rect.bottom)));return r===1/0?e:{left:r,top:s,width:a-r,height:l-s,right:a,bottom:l,x:r,y:s,toJSON:()=>({})}}function Ef(e,t){return{left:e.left-t.left,top:e.top-t.top,width:e.width,height:e.height,scale:1}}function WI(e){if(e==="")return null;const t=e.lastIndexOf(".children.");return t<0?"":e.slice(0,t)}function jI(e){if(!e.startsWith("slot:"))return null;const t=e.slice(5),n=t.lastIndexOf(":");if(n<0)return null;const o=t.slice(0,n),r=Number(t.slice(n+1));return Number.isFinite(r)?{containerPath:o,index:r}:null}function If(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/[^a-zA-Z0-9_\-.]/g,t=>`\\${t}`)}function ka(e){return typeof e=="string"&&e.length>0?e:null}function Sa(e,t){return t&&e.startsWith(`${t}.`)?t:e}function Af(e){if(typeof e!="string")return null;const t=jI(e);return t?{containerPath:t.containerPath,index:t.index}:null}function Ca(e,t){return t?e.startsWith(`${t}.iteration.`):!1}function $a(e,t,n){return t?n==="iteration_item"?Ca(e,t):e===t||e.startsWith(`${t}.`):!1}function HI(e){const{frameEl:t,nesting:n,editMode:o,currentExtensionId:r,editableRootPath:s,components:a,patchLayout:l,pushHistory:d,onMovePath:c,selectedPath:p,showBranchBoundaryHint:f}=e,b=(o==="iteration_item"||o==="modal")&&s&&s.length>0?at(s):null,[g,m]=u.useState(null),[h,v]=u.useState(null),[y,_]=u.useState(null),w=u.useRef({components:a,nesting:n,editMode:o,currentExtensionId:r,selectedPath:p,editableRootSourcePath:b});w.current={components:a,nesting:n,editMode:o,currentExtensionId:r,selectedPath:p,editableRootSourcePath:b};const k=u.useRef(null),x=u.useCallback(M=>({children:M}),[]),$=u.useCallback((M,O)=>{const z=Be(x(M),O);return z?typeof z.name=="string"?z.name:typeof z.type=="string"?z.type:null:null},[x]),S=u.useCallback(M=>O=>{const z=w.current;if(O==="")return Jo(M,z.nesting);const H=Re(O),P=Be(x(z.components),H);if(!P)return!1;const I=typeof P.name=="string"?P.name:typeof P.type=="string"?P.type:"";if(!I)return!1;const L=!!z.editableRootSourcePath&&(O===z.editableRootSourcePath||O.startsWith(`${z.editableRootSourcePath}.`));if(z.editableRootSourcePath&&!L)return!1;if(!L){const F=Ea(x(z.components),H);if(gn(P,z.editMode,z.currentExtensionId,F)!=="none")return!1}return kf(I,z.nesting)?NI({draggedComponentName:M,targetContainerName:I,nesting:z.nesting}):!1},[x]),C=u.useCallback(M=>{if(M==="")return!0;const O=w.current,z=Re(M),H=k.current;if(H&&H.length>0){const L=H.slice(0,-1);if(ui(z,L))return!0}const P=Be(x(O.components),z);return P?(typeof P.name=="string"?P.name:typeof P.type=="string"?P.type:"").length>0:!1},[x]),T=u.useCallback(M=>{const O=S(M),z=w.current,H=k.current,P=H?H.slice(0,-1):null,I=new Set;if(P)for(let K=P.length;K>=0;K--)I.add(pi(P.slice(0,K)));const L=pi(H??[]),F=K=>!!H&&(K===L||K.startsWith(`${L}.`)),Y=(K,X)=>{for(let Z=0;ZK===""?!0:F(K)?!1:I.has(K),allowsNestSlot:K=>{if(!O(K))return!1;if(P){const X=Re(K);if(ui(X,P))return!1}return C(K)}}},[S,C,x]),E=u.useCallback(M=>{const O=ka(M.active.id),z=w.current;if(!O)return;const H=Sa(O,z.selectedPath),P=Re(H),I=Be(x(z.components),P),L=I&&typeof I.name=="string"?I.name:I&&typeof I.type=="string"?I.type:null;m(H),v(L),_(null),k.current=I?P:null;let F="allowed";if(!L||!Jo(L,z.nesting))F="denied_no_draggable";else if(I){const Y=Ea(x(z.components),P),K=gn(I,z.editMode,z.currentExtensionId,Y);z.editableRootSourcePath&&!$a(H,z.editableRootSourcePath,z.editMode)||Qi(Y)&&!Ca(H,z.editableRootSourcePath)?F="denied_data_bound":K==="base"||K==="partial"?F="denied_base_locked":(K==="extension"||K==="extension_point")&&(F="denied_extension_locked")}$n({source:"drag",draggedComponentName:L,targetContainerName:null,targetContainerPath:null,decision:F,result:F==="allowed"?"completed":"denied",timestamp:Date.now()})},[x]),A=u.useCallback(M=>{if(!t)return;const O=ka(M.active.id);if(!O)return;const z=h;if(!z){_(null);return}const H=w.current,P=Sa(O,H.selectedPath),I=Re(P),L=Be(x(H.components),I);if(!L||!Jo(z,H.nesting)){_(null);return}const F=Ea(x(H.components),I);if(H.editableRootSourcePath&&!$a(P,H.editableRootSourcePath,H.editMode)){_(null);return}const Y=gn(L,H.editMode,H.currentExtensionId,F),K=Ca(P,H.editableRootSourcePath);if(Qi(F)&&!K||Y!=="none"&&Y!=="data_bound"&&!K){_(null);return}_(Af(M.over?.id))},[t,h,x]),N=u.useCallback(()=>{m(null),v(null),_(null),k.current=null},[]),D=u.useCallback(M=>{const O=ka(M.active.id),z=h,H=w.current,P=O?Sa(O,H.selectedPath):null;if(!t||!P||!z){N();return}const I=Af(M.over?.id),L=Re(P);if(!I){$n({source:"drag",draggedComponentName:z,targetContainerName:null,targetContainerPath:null,decision:"denied_no_accepts",result:"cancelled",timestamp:Date.now()}),N();return}const F=I.containerPath===""?[]:Re(I.containerPath),Y=I.containerPath===""?null:$(H.components,F);if(!FI(L.slice(0,-1),F)){$n({source:"drag",draggedComponentName:z,targetContainerName:Y,targetContainerPath:I.containerPath||null,decision:"denied_responsive_branch_boundary",result:"denied",timestamp:Date.now()}),f?.(),N();return}if(H.editableRootSourcePath&&!$a(I.containerPath,H.editableRootSourcePath,H.editMode)){$n({source:"drag",draggedComponentName:z,targetContainerName:Y,targetContainerPath:I.containerPath||null,decision:"denied_data_bound",result:"denied",timestamp:Date.now()}),N();return}const K=L.slice(0,-1),X=L[L.length-1]??-1;if(ui(K,F)&&(I.index===X||I.index===X+1)){$n({source:"drag",draggedComponentName:z,targetContainerName:Y,targetContainerPath:I.containerPath||null,decision:"allowed",insertionIndex:I.index,result:"cancelled",timestamp:Date.now()}),N();return}const oe=ui(K,F),G=I.index;let ee=[];l(be=>{const Se=Bb({children:be},L,F,G).children??[];return ee=Se,Se}),d(ee,`move ${z}`);const ge=dd(F,L),V=oe&&X{N()},[N]);return{activeDragPath:g,activeDragName:h,activeDropZone:y,onDragStart:E,onDragMove:A,onDragEnd:D,onDragCancel:B,buildSlotPredicates:T}}function Ea(e,t){const n=[];let o=e,r=Array.isArray(e.children)?e.children:[];for(let s=0;s0?at(s):null,{t:m}=tt(),[h,v]=u.useState(!1),y=u.useRef(null),_=u.useCallback(()=>{v(!0),y.current&&clearTimeout(y.current),y.current=setTimeout(()=>v(!1),2600)},[]);u.useEffect(()=>()=>{y.current&&clearTimeout(y.current)},[]);const w=HI({frameEl:t,nesting:n,editMode:o,currentExtensionId:r,editableRootPath:s,components:a,patchLayout:l,pushHistory:d,onMovePath:p,selectedPath:b,showBranchBoundaryHint:_}),k=p2(u2(ma,{activationConstraint:{distance:8}})),[x,$]=u.useState([]),S=u.useCallback(()=>{if(!t){$([]);return}if(w.activeDragPath!==null)return;const P={children:a},I=t.querySelectorAll("[data-editor-path]"),L=[],F=new Map;I.forEach(Y=>{const K=Y.dataset.editorPath;if(typeof K!="string"||o!=="iteration_item"&&g&&!UI(K,g,o))return;const X=KI(K);if(X!==null&&!Zo(K,g)){if(/\.iteration\.\d+$/.test(K)){const V=ao(Y,t);if(V&&lo(V,t)){const te=F.get(X)??[];te.push(V),F.set(X,te)}}return}if(Zo(K,g)&&/\.iteration\.\d+$/.test(K))return;const Z=Re(K),ae=Be(P,Z);if(!ae||ae.iteration&&ae.iteration.source!==void 0)return;const oe=typeof ae.name=="string"?ae.name:typeof ae.type=="string"?ae.type:null;if(!oe||!Jo(oe,n))return;const G=Df(P,Z);if(Qi(G)&&!Zo(K,g))return;const ee=gn(ae,o,r,G);if(ee!=="none"&&ee!=="data_bound"&&!Zo(K,g))return;const ge=ao(Y,t);ge&&lo(ge,t)&&L.push({path:K,name:oe,box:ge})});for(const[Y,K]of F){const X=Re(Y),Z=Be(P,X);if(!Z)continue;const ae=typeof Z.name=="string"?Z.name:typeof Z.type=="string"?Z.type:null;if(!ae)continue;const oe=Df(P,X),G=gn(Z,o,r,oe);if(G!=="none"&&G!=="data_bound")continue;const ee=qI(K);ee&&lo(ee,t)&&L.push({path:Y,name:ae,box:ee,isIterationGroup:!0})}$(L)},[t,a,n,o,r,g,w.activeDragPath]);u.useEffect(()=>{S()},[S]),u.useEffect(()=>{if(t)return zp(S,t)},[t,S]);const C=w.activeDragPath!==null,T=w.activeDragName,E=w.activeDragPath,[A,N]=u.useState(null),D=u.useRef(null);u.useEffect(()=>{if(!E||!t){E||(D.current=null,N(null));return}if(D.current===E)return;D.current=E;const P=t.querySelector(`[data-editor-path="${Tf(E)}"]`);if(P){const oe=P.getBoundingClientRect();N({node:P.cloneNode(!0),width:oe.width,height:oe.height});return}const I=Array.from(t.querySelectorAll(`[data-editor-path^="${Tf(E)}.iteration."]`)).filter(oe=>/\.iteration\.\d+$/.test(oe.dataset.editorPath??""));if(I.length===0){N(null);return}let L=1/0,F=1/0,Y=-1/0,K=-1/0;for(const oe of I){const G=oe.getBoundingClientRect();L=Math.min(L,G.left),F=Math.min(F,G.top),Y=Math.max(Y,G.right),K=Math.max(K,G.bottom)}const X=Y-L,Z=K-F,ae=document.createElement("div");ae.style.position="relative",ae.style.width=`${X}px`,ae.style.height=`${Z}px`;for(const oe of I){const G=oe.getBoundingClientRect(),ee=oe.cloneNode(!0);ee.style.position="absolute",ee.style.left=`${G.left-L}px`,ee.style.top=`${G.top-F}px`,ee.style.width=`${G.width}px`,ee.style.height=`${G.height}px`,ee.style.margin="0",ae.appendChild(ee)}N({node:ae,width:X,height:Z})},[E,t]);const[B,M]=u.useState([]),O=u.useRef(null),z=u.useRef(w.buildSlotPredicates);if(z.current=w.buildSlotPredicates,u.useEffect(()=>{if(!E||!T||!t){O.current=null,M(F=>F.length===0?F:[]);return}if(O.current===E)return;O.current=E;const{acceptsContainer:P,allowsNestSlot:I,includeContainer:L}=z.current(T);M(OI({frameEl:t,draggedPath:E,acceptsContainer:P,allowsNestSlot:I,includeContainer:L,normalizeContainerPath:F=>VI(F)}))},[E,T,t]),!t)return null;const H=w.activeDropZone?`slot:${w.activeDropZone.containerPath}:${w.activeDropZone.index}`:null;return i.jsxs(gI,{sensors:k,collisionDetection:w2,onDragStart:w.onDragStart,onDragMove:w.onDragMove,onDragEnd:w.onDragEnd,onDragCancel:w.onDragCancel,children:[x.map(P=>i.jsx(JI,{path:P.path,name:P.name,box:P.box,dimmed:C&&w.activeDragPath!==P.path,isIterationGroup:P.isIterationGroup,onSelect:c,onRequestInlineEdit:f},P.path)),C&&B.map(P=>i.jsx(XI,{slot:P,active:P.id===H},P.id)),Cn.createPortal(i.jsx(zI,{dropAnimation:null,zIndex:Fp,children:T?A?i.jsx(YI,{name:T,node:A.node,width:A.width,height:A.height}):i.jsx("div",{className:"g7le-dnd-drag-ghost","data-testid":"g7le-dnd-drag-ghost",style:{padding:"4px 10px",background:"rgba(79,70,229,0.95)",color:"#fff",fontSize:12,fontWeight:600,borderRadius:4,pointerEvents:"none",whiteSpace:"nowrap"},children:`<${T}>`}):null}),document.body),h&&Cn.createPortal(i.jsxs("div",{"data-testid":"g7le-branch-boundary-hint",role:"status",style:{position:"absolute",left:"50%",top:12,transform:"translateX(-50%)",background:"rgba(245,158,11,0.97)",color:"#fff",fontSize:13,fontWeight:600,padding:"8px 16px",borderRadius:8,boxShadow:"0 4px 14px rgba(0,0,0,0.2)",pointerEvents:"none",whiteSpace:"nowrap",zIndex:Fp},children:["⚠️ ",m("layout_editor.overlay.branch_boundary_denied")]}),t)]})}function YI(e){const{node:t,width:n,height:o}=e,r=u.useRef(null);return u.useEffect(()=>{const s=r.current;if(s)return s.replaceChildren(),s.appendChild(t.cloneNode(!0)),()=>{s.replaceChildren()}},[t]),i.jsx("div",{ref:r,className:"g7le-dnd-drag-ghost","data-testid":"g7le-dnd-drag-ghost",style:{width:n,height:o,opacity:.7,pointerEvents:"none",boxShadow:"0 6px 18px rgba(0,0,0,0.25)",borderRadius:4,overflow:"hidden",cursor:"grabbing"}})}function XI(e){const{slot:t,active:n}=e,{setNodeRef:o}=xI({id:t.id}),r=t.orientation!=="area";return i.jsx("div",{ref:o,"data-testid":`g7le-dnd-slot-${t.id}`,"data-dnd-slot-id":t.id,style:{position:"absolute",left:t.box.left,top:t.box.top,width:t.box.width,height:t.box.height,pointerEvents:"auto",zIndex:H7,boxSizing:"border-box",...r?{background:n?"rgba(79,70,229,0.15)":"transparent",...n?t.orientation==="vertical"?{borderLeft:"2px solid #4f46e5"}:{borderTop:"2px solid #4f46e5"}:{}}:{border:n?"2px dashed #4f46e5":"1px dashed transparent",background:n?"rgba(79,70,229,0.08)":"transparent",borderRadius:4}}})}function Tf(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/[^a-zA-Z0-9_\-.]/g,t=>`\\${t}`)}function JI(e){const{path:t,box:n,dimmed:o,isIterationGroup:r,onSelect:s,onRequestInlineEdit:a}=e,{attributes:l,listeners:d,setNodeRef:c,isDragging:p}=bI({id:t}),f=(t.match(/\.children\./g)||[]).length,b=F7(f);return i.jsx("div",{ref:c,"data-testid":`g7le-dnd-handle-${t}`,"data-dnd-handle-path":t,"data-dnd-iteration-group":r?"true":void 0,...d,...l,onClick:g=>{if(g.stopPropagation(),!r&&typeof document<"u"&&typeof document.elementsFromPoint=="function"){const m=document.elementsFromPoint(g.clientX,g.clientY);for(const h of m){const y=h.closest?.("[data-editor-path]")?.dataset?.editorPath;if(typeof y=="string"&&(y===t||y.startsWith(`${t}.`))){s(y);return}}}s(t)},onDoubleClick:g=>{g.stopPropagation(),g.preventDefault(),a?.(t)},style:{position:"absolute",left:n.left,top:n.top,width:n.width,height:n.height,cursor:"grab",pointerEvents:"auto",background:p?"rgba(79,70,229,0.06)":"transparent",...r?{border:"1px dashed rgba(79,70,229,0.5)",borderRadius:4}:{},opacity:o?.6:1,zIndex:b,touchAction:"none"}})}function Df(e,t){const n=[];let o=e,r=Array.isArray(e.children)?e.children:[];for(let s=0;s0?[o]:[];const r=[],s=(a,l)=>{a.forEach((d,c)=>{const p=[...l,c];if(!Ri(d,t,n)){r.push(p);return}const b=Array.isArray(d.children)?d.children:[];b.length>0&&s(b,p)})};return s(e,[]),r}function QI(e){return at(e)}function fi(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}function RI({frameEl:e,components:t,editMode:n,currentExtensionId:o,editableRootPath:r}){const[s,a]=u.useState(null),[l]=u.useState(()=>`g7le-dim-mask-${Math.floor(Math.random()*1e9)}`);if(u.useEffect(()=>{if(!e){a(null);return}let g=0;const m=()=>{const _=ZI(t,n,o,r);if(_.length===0){a(null);return}const w=e.getBoundingClientRect(),k={left:0,top:0,width:w.width,height:w.height},x=[];for(const $ of _){const S=QI($),C=e.querySelector(`[data-editor-path="${fi(S)}"]`);let T=null;if(C){const E=C.getBoundingClientRect();E.width>0&&E.height>0&&(T={left:E.left,top:E.top,width:E.width,height:E.height})}if(!T){const E=Array.from(e.querySelectorAll(`[data-editor-path^="${fi(S)}.iteration."], [data-editor-path^="${fi(S)}.sortable."], [data-editor-path^="${fi(S)}.children."]`));let A=1/0,N=1/0,D=-1/0,B=-1/0;for(const M of E){const O=M.getBoundingClientRect();O.width<=0||O.height<=0||(A=Math.min(A,O.left),N=Math.min(N,O.top),D=Math.max(D,O.right),B=Math.max(B,O.bottom))}if(D>A&&B>N&&(T={left:A,top:N,width:D-A,height:B-N}),T&&E.length>0){const M=E[0].closest('[role="dialog"]');if(M&&e.contains(M)){const O=M.getBoundingClientRect();O.width>0&&O.height>0&&(T={left:O.left,top:O.top,width:O.width,height:O.height})}}}T&&x.push({left:T.left-w.left,top:T.top-w.top,width:T.width,height:T.height})}if(x.length===0){a(null);return}a({frame:k,holes:x})},h=()=>{g&&cancelAnimationFrame(g),g=requestAnimationFrame(m)};h();const v=typeof ResizeObserver<"u"?new ResizeObserver(h):null;v?.observe(e);const y=typeof MutationObserver<"u"?new MutationObserver(h):null;return y?.observe(e,{childList:!0,subtree:!0,attributes:!0}),window.addEventListener("scroll",h,!0),window.addEventListener("resize",h),()=>{g&&cancelAnimationFrame(g),v?.disconnect(),y?.disconnect(),window.removeEventListener("scroll",h,!0),window.removeEventListener("resize",h)}},[e,t,n,o,r?.join(".")??""]),!s||s.holes.length===0)return null;const{frame:d,holes:c}=s,p=n==="modal"||n==="iteration_item";let f=[];if(p){let g=1/0,m=1/0,h=-1/0,v=-1/0;for(const $ of c)g=Math.min(g,$.left),m=Math.min(m,$.top),h=Math.max(h,$.left+$.width),v=Math.max(v,$.top+$.height);const y=($,S,C)=>Math.max(S,Math.min(C,$)),_=y(g,0,d.width),w=y(m,0,d.height),k=y(h,0,d.width),x=y(v,0,d.height);f=[{left:0,top:0,width:d.width,height:w},{left:0,top:x,width:d.width,height:d.height-x},{left:0,top:w,width:_,height:x-w},{left:k,top:w,width:d.width-k,height:x-w}].filter($=>$.width>0&&$.height>0)}const b=g=>{g.preventDefault(),g.stopPropagation()};return i.jsxs(i.Fragment,{children:[f.map((g,m)=>i.jsx("div",{className:"g7le-source-lock-block","data-testid":"g7le-source-lock-block",onClickCapture:b,onPointerDownCapture:b,onMouseDownCapture:b,onDragStartCapture:b,style:{position:"absolute",left:g.left,top:g.top,width:g.width,height:g.height,zIndex:Hp,pointerEvents:"auto",cursor:"not-allowed",background:"transparent"}},m)),i.jsxs("svg",{className:"g7le-source-lock-dim","data-testid":"g7le-source-lock-dim",width:d.width,height:d.height,style:{position:"absolute",left:0,top:0,width:d.width,height:d.height,zIndex:Hp,pointerEvents:"none"},children:[i.jsx("defs",{children:i.jsxs("mask",{id:l,children:[i.jsx("rect",{x:0,y:0,width:d.width,height:d.height,fill:"white"}),c.map((g,m)=>i.jsx("rect",{"data-testid":"g7le-source-lock-dim-hole",x:g.left,y:g.top,width:g.width,height:g.height,rx:4,fill:"black"},m))]})}),i.jsx("rect",{"data-testid":"g7le-source-lock-dim-box",x:0,y:0,width:d.width,height:d.height,fill:"rgba(15, 23, 42, 0.45)",mask:`url(#${l})`})]})]})}function zf(e){const t={type:e.type??"basic",name:e.name},n={};if(e.props)for(const[o,r]of Object.entries(e.props))o!=="children"&&r?.default!==void 0&&(n[o]=r.default);return Object.keys(n).length>0&&(t.props=n),t}function eA(e){if(!e?.components)return[];const t=[];for(const[n,o]of Object.entries(e.components))if(Array.isArray(o))for(const r of o)t.push({...r,type:r.type??n});return t}function tA(e,t,n,o,r){const s=eA(e);let a=null;if(n&&t?.containers){const l=t.containers[n];l&&Array.isArray(l.accepts)?a=new Set(l.accepts):a=new Set}else!n&&t?.draggable&&(a=new Set(t.draggable));return s.filter(l=>{if(a&&!a.has(l.name))return!1;if(o){const d=o.toLowerCase(),c=r(l).toLowerCase(),p=l.name.toLowerCase();if(!c.includes(d)&&!p.includes(d)&&!`<${p}>`.includes(d)&&!(l.description??"").toLowerCase().includes(d))return!1}return!0})}function nA(e,t){const n={key:"all",label:"layout_editor.palette.category.all",entries:e,isI18nKey:!0};if(t?.groups&&t.groups.length>0){const a=new Map(e.map(p=>[p.name,p])),l=new Set,d=[];for(const p of t.groups){const f=[];for(const b of p.components??[]){const g=a.get(b);g&&(f.push(g),l.add(b))}f.length!==0&&d.push({key:p.kind??p.label,label:p.label,entries:f,isI18nKey:p.label.startsWith("$t:")||/^[a-z_.]+$/i.test(p.label)})}const c=e.filter(p=>!l.has(p.name));return c.length>0&&d.push({key:"other",label:"layout_editor.palette.category.other",entries:c,isI18nKey:!0}),[n,...d]}const o=new Map;for(const a of e){const l=(a.type??"basic").toLowerCase(),d=o.get(l)??[];d.push(a),o.set(l,d)}const r=["basic","composite","layout"],s=[];for(const a of r){const l=o.get(a);l&&l.length>0&&(s.push({key:a,label:`layout_editor.palette.category.fallback.${a}`,entries:l,isI18nKey:!0}),o.delete(a))}for(const[a,l]of o.entries())s.push({key:a,label:a,entries:l,isI18nKey:!1});return[n,...s]}function Nf(e){const{manifest:t,nesting:n,componentPalette:o,targetParentPath:r,targetContainerName:s,onInsert:a,insertionIndex:l,onClose:d,editorTemplateId:c,editorLocale:p}=e,{t:f,translationEngine:b}=tt(),g=u.useMemo(()=>{if(!c||!b)return f;const A=p??null;return N=>{const D={templateId:c,locale:A??"ko"},B=b.translate(N,D);return B!==N?B:f(N)}},[c,p,b,f]),[m,h]=u.useState(""),[v,y]=u.useState("all"),_=o?.entries??null,w=u.useMemo(()=>A=>{const N=_?.[A.name];return N?.label?gi(N.label,g):A.description??A.name},[_,g]),k=u.useMemo(()=>tA(t,n,s,m,w),[t,n,s,m,w]),x=u.useMemo(()=>nA(k,o??null),[k,o]),$=x.find(A=>A.key===v)??x[0]??null,S=!n||!n.draggable&&!n.containers,C=k.length===0,T=$?.entries??[],E=A=>{const N=_?.[A.name],D=!!N?.defaultNode&&typeof N.defaultNode=="object";if(N?.requiresDefaultNode&&!D)return;const B=D?JSON.parse(JSON.stringify(N.defaultNode)):zf(A),M=r??[];a(B,M,l),$n({source:"palette",draggedComponentName:A.name,targetContainerName:s,targetContainerPath:M.length===0?null:M.join("/"),decision:"allowed",insertionIndex:l,result:"completed",timestamp:Date.now()}),d()};return i.jsxs("div",{className:"g7le-palette","data-testid":"g7le-palette",style:sA,children:[i.jsxs("div",{style:aA,children:[i.jsx("strong",{style:{fontSize:16},children:f("layout_editor.palette.title")}),i.jsx("button",{type:"button",onClick:d,"aria-label":"close","data-testid":"g7le-palette-close",style:lA,children:"×"})]}),i.jsxs("div",{style:dA,children:[i.jsx("aside",{style:cA,"data-testid":"g7le-palette-sidebar",children:i.jsx("nav",{children:i.jsx("ul",{style:uA,children:x.map(A=>{const N=$?.key===A.key,D=A.isI18nKey?gi(A.label,g):A.label;return i.jsx("li",{children:i.jsxs("button",{type:"button","data-testid":`g7le-palette-category-${A.key}`,"data-active":N?"true":"false",onClick:()=>y(A.key),style:{...pA,background:N?"#eff6ff":"transparent",color:N?"#1d4ed8":"#334155",fontWeight:N?600:500},children:[i.jsx("span",{children:D}),i.jsx("span",{style:yA,children:A.entries.length})]})},A.key)})})})}),i.jsxs("main",{style:fA,children:[i.jsx("input",{type:"text",placeholder:f("layout_editor.palette.search_placeholder"),value:m,onChange:A=>h(A.target.value),"data-testid":"g7le-palette-search",style:gA}),i.jsx("div",{style:hA,children:S?i.jsx("div",{style:Mf,"data-testid":"g7le-palette-spec-missing",children:f("layout_editor.palette.spec_missing")}):C||T.length===0?i.jsx("div",{style:Mf,"data-testid":"g7le-palette-empty",children:f("layout_editor.palette.empty")}):i.jsx("div",{"data-testid":`g7le-palette-group-${$?.key??"all"}`,style:{marginBottom:16},children:i.jsx("div",{style:bA,children:T.map(A=>i.jsx(oA,{entry:A,entrySpec:_?.[A.name]??null,onClick:E,t:f,entryT:g},A.name))})})})]})]})]})}function oA(e){const{entry:t,entrySpec:n,onClick:o,t:r,entryT:s}=e,a=n?.label?gi(n.label,s):t.description??t.name,l=(t.type??"").toLowerCase(),d=l==="basic"||l==="composite"||l==="layout",c=!!n?.defaultNode&&typeof n.defaultNode=="object",p=!!n?.requiresDefaultNode&&!c,f=!c,b=p?r("layout_editor.palette.requires_default_node_missing"):n?.label?gi(n.label,s):t.name;return i.jsxs("button",{type:"button",onClick:()=>o(t),disabled:p,"aria-disabled":p||void 0,"data-testid":`g7le-palette-item-${t.name}`,"data-component-type":l||void 0,"data-blocked":p?"true":void 0,"data-default-node-missing":f?"true":void 0,title:b,style:p?vA:mA,children:[i.jsx("div",{style:xA,"aria-hidden":"true",children:iA(t)}),i.jsx("div",{style:wA,children:a}),i.jsx("div",{"data-testid":`g7le-palette-item-${t.name}-tag`,style:kA,children:`<${t.name}>`}),d&&i.jsx("div",{"data-testid":`g7le-palette-item-${t.name}-badge`,style:rA(l),children:l}),f&&i.jsx("div",{"data-testid":`g7le-palette-item-${t.name}-default-missing-badge`,style:_A,children:r("layout_editor.palette.default_node_missing_badge")})]})}function gi(e,t){return e.startsWith("$t:")?t(e.slice(3)):t(e)}function rA(e){const n={basic:{bg:"#dbeafe",fg:"#1e40af"},composite:{bg:"#dcfce7",fg:"#14532d"},layout:{bg:"#fef3c7",fg:"#854d0e"}}[e]??{bg:"#e2e8f0",fg:"#334155"};return{fontSize:9,fontWeight:600,color:n.fg,background:n.bg,padding:"1px 6px",borderRadius:999,textTransform:"uppercase",letterSpacing:.4,lineHeight:1.6}}function iA(e){const t=e.name;return{Button:"🔘",A:"🔗",Img:"🖼",Icon:"✨",Hr:"➖",P:"📄",Span:"T",H1:"H₁",H2:"H₂",H3:"H₃",H4:"H₄",Ul:"☰",Li:"•",Nav:"🧭",Div:"▢",Container:"▢",Flex:"⇆",Grid:"▦",SectionLayout:"▤",ThreeColumnLayout:"⫼",Form:"📝",Input:"⎕",Textarea:"▭",Select:"⏷",Checkbox:"☑",PasswordInput:"🔒",Label:"🏷",DataGrid:"▦",Pagination:"↔",SearchBar:"🔍",ProductCard:"🛍",ImageGallery:"🖼",Avatar:"👤",UserInfo:"👥",HtmlContent:"⟨/⟩",HtmlEditor:"✏",RichTextEditor:"✏",TabNavigation:"◰",QuantitySelector:"#",ProductImageViewer:"🖼",FileUploader:"📎",AvatarUploader:"📷",SocialLoginButtons:"🌐",PostReactions:"❤"}[t]??"◻"}const sA={display:"flex",flexDirection:"column",width:"100%",height:"100%",minHeight:0,fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Apple SD Gothic Neo", "Noto Sans KR", sans-serif'},aA={display:"flex",justifyContent:"space-between",alignItems:"center",padding:"14px 20px",borderBottom:"1px solid #e2e8f0",flexShrink:0},lA={background:"transparent",border:"none",fontSize:24,cursor:"pointer",lineHeight:1,color:"#64748b",padding:"0 4px"},dA={display:"flex",flex:1,minHeight:0},cA={width:180,flexShrink:0,borderRight:"1px solid #e2e8f0",padding:"14px 8px",background:"#f8fafc",overflowY:"auto"},uA={listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:4},pA={display:"flex",width:"100%",alignItems:"center",justifyContent:"space-between",textAlign:"left",padding:"8px 12px",border:"none",borderRadius:6,fontSize:13,cursor:"pointer",transition:"background-color 120ms"},fA={flex:1,display:"flex",flexDirection:"column",minHeight:0,padding:"14px 20px"},gA={width:"100%",padding:"8px 10px",border:"1px solid #cbd5e1",borderRadius:6,marginBottom:12,fontSize:13,flexShrink:0,boxSizing:"border-box"},hA={flex:1,overflowY:"auto",minHeight:0},yA={fontSize:11,color:"#94a3b8",marginLeft:8,fontWeight:500},bA={display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(96px, 1fr))",gap:10},mA={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:6,padding:"14px 6px",background:"#fff",border:"1px solid #e2e8f0",borderRadius:8,cursor:"pointer",fontSize:12,minHeight:84,transition:"border-color 120ms, box-shadow 120ms"},vA={display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center",gap:6,padding:"14px 6px",background:"#f8fafc",border:"1px dashed #cbd5e1",borderRadius:8,cursor:"not-allowed",fontSize:12,minHeight:84,color:"#94a3b8",opacity:.65},_A={fontSize:9,fontWeight:600,color:"#92400e",background:"#fef3c7",padding:"1px 6px",borderRadius:999,textTransform:"none",letterSpacing:0,lineHeight:1.6},xA={fontSize:22,lineHeight:1,color:"#475569"},wA={fontSize:12,fontWeight:500,color:"#0f172a",textAlign:"center",wordBreak:"break-word"},kA={fontFamily:'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace',fontSize:10,color:"#64748b",textAlign:"center",wordBreak:"break-all"},Mf={padding:24,color:"#64748b",fontSize:13,textAlign:"center"};function SA(e){const t=[],n=r=>{if(Array.isArray(r))for(const s of r)s&&typeof s=="object"&&t.push(s)};n(e.children);const o=e.responsive;if(o&&typeof o=="object")for(const r of Object.values(o))r&&typeof r=="object"&&n(r.children);return t}function Lf(e){const t=[],n=o=>{const r="isolatedState"in o&&o.isolatedState!=null,s=o.isolatedScopeId;(r||typeof s=="string"&&s.length>0)&&t.push({scopeId:typeof s=="string"?s:void 0,initialState:o.isolatedState&&typeof o.isolatedState=="object"?o.isolatedState:void 0});for(const a of SA(o))n(a)};if(Array.isArray(e))for(const o of e)o&&typeof o=="object"&&n(o);return t}const CA=["scroll","selector","wizard","slider"];function $A(e,t){const n=new Set;for(const o of e)o.scopeId&&n.add(o.scopeId);for(const o of t){n.add(o);for(const r of CA)n.add(`${o}-${r}`)}return Array.from(n)}function EA(e,t,n){const o=t.label;return typeof o=="string"?o.startsWith("$t:")?n(o.slice(3)):o:e}function hi({controlKey:e,control:t,node:n,t:o,onPatch:r,candidates:s,bindingCandidates:a,scope:l=Wt}){const d=Tn(t.widget),c=EA(e,t,o),p=u.useMemo(()=>zo(n,t,l),[n,t,l]),f=t.widget==="i18n-text"&&t.apply?.type==="propValue",b=t.widget==="text"&&t.apply?.type==="propValue",g=p.darkReadonly===!0||l.colorScheme==="dark"&&t.apply!==void 0&&!Ys(t.apply),m=t.apply,h=l.colorScheme==="dark"&&!g&&m?.type==="classToken"&&typeof m.tokenTemplate=="string"&&m.tokenTemplate.includes("{value}"),v=p.scopedValue===void 0&&p.baseFallback!==void 0,y=u.useCallback(_=>{if(g)return;const w=fn(n,t,_,l);r(w)},[n,t,r,l,g]);return i.jsxs("div",{className:"g7le-control-row","data-testid":`g7le-control-${e}`,style:IA,children:[i.jsxs("span",{className:"g7le-control-label",style:AA,children:[c,p.conflict&&i.jsx("span",{"data-testid":`g7le-control-conflict-${e}`,title:o("layout_editor.property_modal.value_conflict"),style:TA,children:"!"})]}),i.jsx("div",{className:"g7le-control-widget",style:{flex:1,minWidth:0,opacity:v?.45:1},"data-placeholder":v?"true":void 0,children:f?i.jsx(_t,{value:typeof p.value=="string"?p.value:"",onChange:_=>y(_),t:o,testidPrefix:`g7le-prop-i18n-${e}`,candidates:a,enableExpressionTree:!0,expressionTreeCollapsible:!0}):b?i.jsx(Ke,{value:typeof p.value=="string"?p.value:"",onChange:_=>y(_===""?void 0:_),t:o,testidPrefix:`g7le-prop-value-${e}`,candidates:a}):g?i.jsx("span",{"data-testid":`g7le-control-dark-readonly-${e}`,style:zA,children:o("layout_editor.property_modal.dark_code_only")}):d?i.jsx(d,{control:t,value:p.value,onChange:y,t:o,candidates:s,bindingCandidates:a,freeValueDisabled:h}):i.jsx("span",{"data-testid":`g7le-control-unsupported-${e}`,style:DA,children:o("layout_editor.property_modal.unsupported_widget")})})]})}const IA={display:"flex",alignItems:"center",gap:12,padding:"6px 0",minHeight:32,minWidth:0},AA={fontSize:12,color:"#475569",minWidth:88,display:"inline-flex",alignItems:"center",gap:4},TA={display:"inline-flex",width:14,height:14,borderRadius:7,background:"#f59e0b",color:"#fff",fontSize:10,alignItems:"center",justifyContent:"center",fontWeight:700},DA={fontSize:11,color:"#94a3b8",fontStyle:"italic"},zA={fontSize:11,color:"#94a3b8",fontStyle:"italic"};function yi(e,t,n){return typeof e=="string"?e.startsWith("$t:")?n(e.slice(3)):e:t}function NA(e,t){const n=e.props??{};return t.key in n?n[t.key]:t.default}function MA({spec:e,node:t,t:n,onPatchProp:o}){const r=e.groups??[];return i.jsx("div",{className:"g7le-composite-settings","data-testid":"g7le-composite-settings",style:PA,children:r.map((s,a)=>i.jsxs("div",{className:"g7le-settings-group",style:OA,children:[i.jsx("div",{style:BA,children:yi(s.label,n("layout_editor.property_modal.settings_group",{index:a+1}),n)}),(s.fields??[]).map(l=>i.jsxs("div",{className:"g7le-settings-field","data-testid":`g7le-setting-${l.key}`,style:WA,children:[i.jsx("span",{style:jA,children:yi(l.label,l.key,n)}),i.jsx("div",{style:{flex:1},children:LA(l,t,n,o)})]},l.key))]},a))})}function LA(e,t,n,o){const r=NA(t,e);switch(e.type){case"number":return i.jsx("input",{type:"number","data-testid":`g7le-setting-input-${e.key}`,value:typeof r=="number"?r:"",min:e.min,max:e.max,onChange:s=>o(e.key,s.target.value===""?void 0:Number(s.target.value)),style:Ia});case"text":return i.jsx("input",{type:"text","data-testid":`g7le-setting-input-${e.key}`,value:typeof r=="string"?r:"",onChange:s=>o(e.key,s.target.value===""?void 0:s.target.value),style:Ia});case"toggle":return i.jsx("input",{type:"checkbox","data-testid":`g7le-setting-input-${e.key}`,checked:r===!0,onChange:s=>o(e.key,s.target.checked)});case"checkbox-group":{const s=Array.isArray(r)?r:[];return i.jsx("div",{style:HA,"data-testid":`g7le-setting-input-${e.key}`,children:(e.options??[]).map(a=>{const l=s.includes(a.value);return i.jsxs("label",{style:FA,children:[i.jsx("input",{type:"checkbox",checked:l,onChange:d=>{const c=d.target.checked?[...s,a.value]:s.filter(p=>p!==a.value);o(e.key,c)}}),yi(a.label,String(a.value),n)]},String(a.value))})})}case"select":case"board-select":case"datasource-select":default:return i.jsxs("select",{"data-testid":`g7le-setting-input-${e.key}`,value:r==null?"":String(r),onChange:s=>{const a=s.target.value;if(a===""){o(e.key,void 0);return}const l=(e.options??[]).find(d=>String(d.value)===a);o(e.key,l?l.value:a)},style:Ia,children:[i.jsx("option",{value:"",children:"—"}),(e.options??[]).map(s=>i.jsx("option",{value:String(s.value),children:yi(s.label,String(s.value),n)},String(s.value)))]})}}const PA={display:"flex",flexDirection:"column",gap:16},OA={display:"flex",flexDirection:"column",gap:6},BA={fontSize:12,fontWeight:700,color:"#0f172a",borderBottom:"1px solid #e2e8f0",paddingBottom:4},WA={display:"flex",alignItems:"center",gap:12,minHeight:30},jA={fontSize:12,color:"#475569",minWidth:96},Ia={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",boxSizing:"border-box"},HA={display:"flex",flexWrap:"wrap",gap:10},FA={display:"inline-flex",alignItems:"center",gap:4,fontSize:12,color:"#0f172a"},KA=["data_binding","isolatedScopeId","parentFormContextProp","skipBindingKeys","isolatedState","component_layout","sortable","itemTemplate"],VA=/\{\{|\$switch|\$get|\|\s*(date|number|truncate|currency|relative)\b/;function bi(e,t=0){return t>6?!1:typeof e=="string"?VA.test(e):Array.isArray(e)?e.some(n=>bi(n,t+1)):e&&typeof e=="object"?Object.values(e).some(n=>bi(n,t+1)):!1}function UA(e){if(td(e))return!1;const t=ql(e);return t.length===0?!1:t.some(n=>n.isComplex)}function Pf(e){const t=[],n=e.props??{};for(const o of KA)o in e&&e[o]!==void 0?t.push({key:o,kind:"developer_prop"}):o in n&&n[o]!==void 0&&t.push({key:`props.${o}`,kind:"developer_prop"});typeof e.text=="string"?UA(e.text)&&t.push({key:"text",kind:"complex_expression"}):bi(e.text)&&t.push({key:"text",kind:"complex_expression"});for(const[o,r]of Object.entries(n))o==="style"||o==="className"||bi(r)&&t.push({key:`props.${o}`,kind:"complex_expression"});return t}function qA(e){return Pf(e).length>0}const GA=new Set(["permissions","blur_until_loaded","comment"]);function YA({node:e,advanced:t,t:n,onPatch:o,permissionCandidates:r}){const s=u.useMemo(()=>Pf(e),[e]),a=(l,d)=>{const c={...e};d===void 0?delete c[l]:c[l]=d,o(c)};return i.jsxs("div",{className:"g7le-advanced-props","data-testid":"g7le-advanced-props",style:XA,children:[t.map(l=>{if(!GA.has(l))return i.jsxs("div",{"data-testid":`g7le-advanced-deferred-${l}`,style:ZA,children:[n("layout_editor.property_modal.advanced_deferred"),":",l]},l);if(l==="permissions")return i.jsxs("div",{className:"g7le-advanced-group","data-testid":"g7le-advanced-permissions",style:Aa,children:[i.jsx("div",{style:Ta,children:n("layout_editor.property_modal.advanced.permissions")}),i.jsx(vs,{control:{widget:"tag-input"},value:e.permissions,onChange:d=>a("permissions",d),t:n,candidates:r})]},l);if(l==="blur_until_loaded"){const d=e.blur_until_loaded===!0||e.blur_until_loaded!=null&&e.blur_until_loaded!==!1;return i.jsxs("div",{className:"g7le-advanced-group","data-testid":"g7le-advanced-blur",style:Aa,children:[i.jsx("div",{style:Ta,children:n("layout_editor.property_modal.advanced.blur_until_loaded")}),i.jsxs("label",{style:{display:"inline-flex",alignItems:"center",gap:6,fontSize:12},children:[i.jsx("input",{type:"checkbox","data-testid":"g7le-advanced-blur-toggle",checked:!!d,onChange:c=>a("blur_until_loaded",c.target.checked?!0:void 0)}),n("layout_editor.property_modal.advanced.blur_hint")]})]},l)}return i.jsxs("div",{className:"g7le-advanced-group","data-testid":"g7le-advanced-comment",style:Aa,children:[i.jsx("div",{style:Ta,children:n("layout_editor.property_modal.advanced.comment")}),i.jsx("input",{type:"text","data-testid":"g7le-advanced-comment-input",value:typeof e.comment=="string"?e.comment:"",onChange:d=>a("comment",d.target.value===""?void 0:d.target.value),style:JA})]},l)}),s.length>0&&i.jsxs("div",{className:"g7le-advanced-preserved","data-testid":"g7le-advanced-preserved",style:QA,children:[i.jsx("div",{style:RA,children:n("layout_editor.property_modal.advanced_preserved_title",{count:s.length})}),i.jsx("ul",{style:e6,children:s.map(l=>i.jsxs("li",{"data-testid":`g7le-advanced-preserved-${l.key}`,style:t6,children:[i.jsx("code",{style:{fontSize:11},children:l.key}),i.jsx("span",{style:{fontSize:11,color:"#94a3b8"},children:l.kind==="developer_prop"?n("layout_editor.property_modal.advanced_kind_developer"):n("layout_editor.property_modal.advanced_kind_expression")})]},l.key))})]})]})}const XA={display:"flex",flexDirection:"column",gap:14},Aa={display:"flex",flexDirection:"column",gap:6},Ta={fontSize:12,fontWeight:700,color:"#0f172a"},JA={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",boxSizing:"border-box"},ZA={fontSize:11,color:"#94a3b8",fontStyle:"italic"},QA={borderTop:"1px dashed #cbd5e1",paddingTop:10,marginTop:4},RA={fontSize:11,color:"#b45309",marginBottom:6},e6={listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:4},t6={display:"flex",justifyContent:"space-between",gap:8,padding:"3px 0"},n6={onClick:"click",onHover:"mouseenter",onChange:"change",onSubmit:"submit",onMount:"mount",onUnmount:"unmount",onFocus:"focus",onBlur:"blur"};function Da(e){return n6[e]??e.replace(/^on/,"").toLowerCase()}function Of(e){const t=e.actions;if(Array.isArray(t))return t.filter(r=>!!r&&typeof r=="object");const n=e.props??{};if(Array.isArray(n.actions))return n.actions.filter(r=>!!r&&typeof r=="object");const o=n.events;if(o&&typeof o=="object"){const r=[];for(const[s,a]of Object.entries(o)){if(!Array.isArray(a))continue;const l=Da(s);for(const d of a)d&&typeof d=="object"&&r.push("type"in d?d:{type:l,...d})}return r}return[]}function o6(e,t){const n=Da(t);return Of(e).filter(o=>o.type===n||t==="onClick"&&o.type===void 0)}function r6(e,t,n){const o=Da(t),r=Of(e).filter(d=>!(d.type===o||t==="onClick"&&d.type===void 0)),s=n.map(d=>"type"in d?d:{type:o,...d}),a={...e};if(a.props&&typeof a.props=="object"){const d={...a.props};let c=!1;"actions"in d&&(delete d.actions,c=!0),"events"in d&&(delete d.events,c=!0),c&&(a.props=d)}const l=[...r,...s];return l.length===0?delete a.actions:a.actions=l,a}function i6({node:e,spec:t,capability:n,t:o,onPatchNode:r,pageCandidates:s,dataSourceCandidates:a,stateKeyCandidates:l,bindingCandidates:d}){const c=t?.actionRecipes,p=u.useMemo(()=>({pageCandidates:s,dataSourceCandidates:a,stateKeyCandidates:l,bindingCandidates:d}),[s,a,l,d]),f=Array.isArray(n?.events)?n.events:[];return f.length===0?i.jsx("div",{"data-testid":"g7le-action-no-events",style:Bf,children:o("layout_editor.action.no_events")}):!c||Object.keys(c).length===0?i.jsx("div",{"data-testid":"g7le-action-no-recipes",style:Bf,children:o("layout_editor.action.no_recipes")}):i.jsx("div",{className:"g7le-action-editor","data-testid":"g7le-action-editor",style:{display:"flex",flexDirection:"column",gap:14},children:f.map(b=>i.jsxs("div",{className:"g7le-action-event-slot","data-testid":`g7le-action-event-${b}`,children:[i.jsx("div",{style:s6,children:o(`layout_editor.action.event.${b}`)}),i.jsx(Gt,{actions:o6(e,b),onChange:g=>r(r6(e,b,g)),t:o,recipes:c,candidatePools:p,actionChipCandidates:t?.actionChipCandidates??null,addContext:"component",showSourceBadge:!0,testIdPrefix:`g7le-action-slot-${b}`})]},b))})}const Bf={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},s6={fontSize:12,fontWeight:700,color:"#475569",marginBottom:6};function za(e,t,n){if(!t)return n;const o=e(t);return!o||o===t||o.startsWith("$t:")?n:o}function a6(e,t){return za(t,e.labelKey,e.path||e.sourceId)}function l6({node:e,spec:t,candidates:n,t:o,onPatchNode:r}){const a=(e.props??{})[t.propKey],l=typeof a=="string"?a:void 0,d=u.useMemo(()=>Kt(a),[a]),c=l!==void 0&&l!==""&&d===null,[p,f]=u.useState(!1),[b,g]=u.useState(""),m=za(o,t.label,t.propKey),h=o(t.shape==="array"?"layout_editor.binding.shape_array":t.shape==="object"?"layout_editor.binding.shape_object":"layout_editor.binding.shape_scalar"),v=u.useMemo(()=>Ui(n,t.shape).map(x=>({...x,resolvedLabel:a6(x,o)})),[n,t.shape,o]),y=u.useMemo(()=>qi(v,b),[v,b]),_=k=>{const x={...e.props??{}};k===void 0?delete x[t.propKey]:x[t.propKey]=k,r({...e,props:x})},w=k=>{_(En(k.sourceId,k.path,t.shape)),f(!1),g("")};return i.jsxs("div",{"data-testid":`g7le-binding-row-${t.propKey}`,style:p6,children:[i.jsxs("div",{style:f6,children:[i.jsx("span",{style:{fontWeight:600,fontSize:12},children:m}),i.jsx("span",{style:g6,children:h}),t.required&&i.jsx("span",{"data-testid":`g7le-binding-required-${t.propKey}`,style:h6,children:o("layout_editor.binding.required")})]}),c?i.jsxs("div",{"data-testid":`g7le-binding-complex-${t.propKey}`,style:v6,children:[o("layout_editor.binding.complex"),i.jsx("code",{style:Wf,children:l})]}):d?i.jsxs("div",{style:y6,children:[i.jsx("code",{"data-testid":`g7le-binding-expr-${t.propKey}`,style:Wf,children:l}),i.jsx("button",{type:"button","data-testid":`g7le-binding-clear-${t.propKey}`,onClick:()=>_(void 0),style:m6,children:o("layout_editor.binding.clear")})]}):i.jsx("div",{"data-testid":`g7le-binding-empty-${t.propKey}`,style:b6,children:o("layout_editor.binding.not_connected")}),d&&(t.shape==="array"||t.shape==="object")&&t.itemFields&&t.itemFields.length>0&&i.jsxs("div",{style:_6,children:[o("layout_editor.binding.item_fields"),": ",t.itemFields.join(", ")]}),!c&&i.jsxs("div",{style:{marginTop:4},children:[i.jsxs("button",{type:"button","data-testid":`g7le-binding-search-toggle-${t.propKey}`,onClick:()=>f(k=>!k),style:x6,children:["🔍 ",o("layout_editor.binding.search")]}),p&&i.jsxs("div",{"data-testid":`g7le-binding-picker-${t.propKey}`,style:w6,children:[i.jsx("input",{type:"text",autoFocus:!0,"data-testid":`g7le-binding-search-input-${t.propKey}`,value:b,placeholder:o("layout_editor.binding.search_placeholder"),onChange:k=>g(k.target.value),style:k6}),i.jsx("div",{style:S6,children:y.length===0?i.jsx("div",{style:C6,children:o("layout_editor.binding.no_results")}):y.map(k=>i.jsxs("button",{type:"button","data-testid":`g7le-binding-candidate-${k.expression}`,onClick:()=>w(k),style:$6,children:[i.jsxs("span",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start"},children:[i.jsx("span",{style:{fontSize:12},children:k.resolvedLabel}),i.jsxs("span",{style:E6,children:[za(o,k.groupLabelKey,k.sourceId)," · ",k.path||k.sourceId]})]}),i.jsx("span",{style:I6,children:k.preview})]},k.expression))})]})]})]})}function d6({node:e,dataProps:t,candidates:n,t:o,onPatchNode:r}){return!Array.isArray(t)||t.length===0?null:i.jsxs("div",{"data-testid":"g7le-data-binding-section",style:c6,children:[i.jsxs("div",{style:u6,children:["🔗 ",o("layout_editor.binding.section_title")]}),t.map(s=>i.jsx(l6,{node:e,spec:s,candidates:n,t:o,onPatchNode:r},s.propKey)),i.jsx("div",{style:A6})]})}const c6={display:"flex",flexDirection:"column",marginBottom:8},u6={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:6},p6={display:"flex",flexDirection:"column",gap:4,padding:"8px 0"},f6={display:"flex",alignItems:"center",gap:6},g6={fontSize:10,padding:"1px 6px",borderRadius:4,background:"#e0e7ff",color:"#3730a3"},h6={fontSize:10,padding:"1px 6px",borderRadius:4,background:"#fef3c7",color:"#92400e"},y6={display:"flex",alignItems:"center",gap:6},b6={fontSize:11,color:"#94a3b8"},Wf={fontSize:11,fontFamily:"monospace",background:"#f1f5f9",padding:"2px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all"},m6={fontSize:11,border:"1px solid #e2e8f0",borderRadius:4,background:"#fff",color:"#dc2626",padding:"2px 8px",cursor:"pointer"},v6={display:"flex",flexDirection:"column",gap:2,fontSize:11,color:"#64748b"},_6={fontSize:10,color:"#94a3b8"},x6={fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#334155",padding:"4px 10px",cursor:"pointer",textAlign:"left",width:"100%"},w6={marginTop:4,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",padding:6},k6={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},S6={marginTop:4,maxHeight:200,overflowY:"auto",display:"flex",flexDirection:"column",gap:2},C6={fontSize:11,color:"#94a3b8",padding:"8px 0",textAlign:"center"},$6={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,border:"none",background:"transparent",cursor:"pointer",padding:"6px 8px",borderRadius:4,textAlign:"left"},E6={fontSize:10,color:"#94a3b8"},I6={fontSize:10,color:"#64748b",fontFamily:"monospace",whiteSpace:"nowrap"},A6={borderTop:"1px solid #e2e8f0",marginTop:4};function T6({node:e,candidates:t,t:n,onPatchNode:o,templateIdentifier:r}){const s=typeof e.text=="string"?e.text:"",{state:a}=Qe(),l=r??a.templateIdentifier,d=a.selectedRoute?.layoutName??null,c=a.locale,[p,f]=u.useState(!1),b=/^\s*\$t:custom\.[A-Za-z0-9._-]+\s*$/.test(s),m=td(s)&&(vt(s)?.key.startsWith("custom.")??!1)||b,h=u.useMemo(()=>m?vt(s):null,[m,s]),v=u.useMemo(()=>m?[]:ql(s),[m,s]),y=T=>{o({...e,text:T})},_=()=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:l,locale:c}}))}catch{}},w=(T,E)=>{const A=En(E.sourceId,E.path,"scalar");y(Ab(s,T,A))},k=T=>{const E=vt(s);y(vo(s,T));const A=E?.key;l&&A&&qd(l,A,T).then(_)},x=T=>{const E=n(T);return E&&E!==T&&!E.startsWith("$t:")?E:""},$=T=>T.replace(/\$t:[a-zA-Z0-9._-]+/g,E=>x(E.slice(3))).replace(/\s+/g," ").trim(),S=T=>{p||(f(!0),us(l,d,c,s,s.length,T.sourceId,T.path,"scalar",$,E=>n(E)).then(E=>{E.kind==="ok"&&(y(E.text),_())}).finally(()=>f(!1)))},C=T=>{p||!h&&!b||(f(!0),Cr(l,c,s,Number.MAX_SAFE_INTEGER,T.sourceId,T.path,"scalar").then(E=>{E.kind==="ok"&&(y(E.text),_())}).finally(()=>f(!1)))};if(m){const T=h?.params??[];return i.jsxs("div",{"data-testid":"g7le-inline-binding-section",style:jf,children:[i.jsxs("div",{style:Hf,children:["🔗 ",n("layout_editor.inline_binding.section_title")]}),T.length===0?i.jsx("div",{"data-testid":"g7le-inline-binding-none",style:Vf,children:n("layout_editor.inline_binding.none")}):T.map(E=>i.jsx("div",{"data-testid":`g7le-inline-binding-param-${E.name}`,style:Ff,children:E.parsed===null?i.jsxs("div",{"data-testid":`g7le-inline-binding-param-complex-${E.name}`,style:z6,children:[n("layout_editor.inline_binding.complex"),i.jsx("code",{style:Na,children:E.expression})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:Kf,children:[i.jsx("code",{"data-testid":`g7le-inline-binding-param-expr-${E.name}`,style:Na,children:E.expression}),i.jsx("button",{type:"button","data-testid":`g7le-inline-binding-param-clear-${E.name}`,onClick:()=>k(E.name),style:D6,children:n("layout_editor.inline_binding.clear")})]}),i.jsx($t,{candidates:t,t:n,onSelect:A=>w(E.name,A),testIdSuffix:`param-${E.name}`})]})},E.name)),i.jsxs("div",{"data-testid":"g7le-inline-binding-param-append",style:Uf,children:[i.jsx("div",{style:Ma,children:n("layout_editor.inline_binding.append_hint")}),i.jsx($t,{candidates:t,t:n,onSelect:C,testIdSuffix:"param-append"})]}),i.jsx("div",{"data-testid":"g7le-inline-binding-param-hint",style:Ma,children:n("layout_editor.inline_binding.param_hint")}),i.jsx("div",{style:qf})]})}return i.jsxs("div",{"data-testid":"g7le-inline-binding-section",style:jf,children:[i.jsxs("div",{style:Hf,children:["🔗 ",n("layout_editor.inline_binding.section_title")]}),v.length===0?i.jsx("div",{"data-testid":"g7le-inline-binding-none",style:Vf,children:n("layout_editor.inline_binding.none")}):v.map(T=>i.jsx("div",{"data-testid":`g7le-inline-binding-row-${T.bindingIndex}`,style:Ff,children:i.jsx("div",{style:Kf,children:i.jsx("code",{"data-testid":`g7le-inline-binding-expr-${T.bindingIndex}`,style:Na,children:T.expression})})},T.bindingIndex)),i.jsxs("div",{"data-testid":"g7le-inline-binding-append",style:Uf,children:[i.jsx("div",{style:Ma,children:n("layout_editor.inline_binding.append_hint")}),i.jsx($t,{candidates:t,t:n,onSelect:S,testIdSuffix:"append"})]}),i.jsx("div",{style:qf})]})}const jf={display:"flex",flexDirection:"column",marginBottom:8},Hf={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:6},Ff={display:"flex",flexDirection:"column",gap:4,padding:"8px 0"},Kf={display:"flex",alignItems:"center",gap:6},Vf={fontSize:11,color:"#94a3b8"},Na={fontSize:11,fontFamily:"monospace",background:"#f1f5f9",padding:"2px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all"},D6={fontSize:11,border:"1px solid #e2e8f0",borderRadius:4,background:"#fff",color:"#dc2626",padding:"2px 8px",cursor:"pointer"},z6={display:"flex",flexDirection:"column",gap:2,fontSize:11,color:"#64748b"},Uf={display:"flex",flexDirection:"column",gap:2,padding:"8px 0 0"},Ma={fontSize:11,color:"#475569",fontWeight:600},qf={borderTop:"1px solid #e2e8f0",marginTop:4};function Gf(e,t,n){if(!t)return n;const o=e(t);return!o||o===t||o.startsWith("$t:")?n:o}function N6(e,t){return Gf(t,e.labelKey,e.path||e.sourceId)}function M6(e){const t=e.iteration;return t&&typeof t=="object"?t:null}function L6({node:e,candidates:t,t:n,onPatchNode:o}){const r=M6(e),s=r?.source,a=typeof s=="string"?s:void 0,l=u.useMemo(()=>Kt(s),[s]),d=a!==void 0&&a!==""&&l===null,[c,p]=u.useState(!1),[f,b]=u.useState(""),g=u.useMemo(()=>Ui(t,"array").map(k=>({...k,resolvedLabel:N6(k,n)})),[t,n]),m=u.useMemo(()=>qi(g,f),[g,f]);if(!r)return null;const h=typeof r.item_var=="string"?r.item_var:void 0,v=typeof r.index_var=="string"?r.index_var:void 0,y=w=>{const k={...r};w===void 0?delete k.source:k.source=w,o({...e,iteration:k})},_=w=>{y(En(w.sourceId,w.path,"array")),p(!1),b("")};return i.jsxs("div",{"data-testid":"g7le-iteration-binding-section",style:P6,children:[i.jsxs("div",{style:O6,children:["🔁 ",n("layout_editor.binding.iteration_title")]}),i.jsx("div",{style:B6,children:n("layout_editor.binding.iteration_hint")}),i.jsxs("div",{style:W6,children:[i.jsxs("div",{style:j6,children:[i.jsx("span",{style:{fontWeight:600,fontSize:12},children:n("layout_editor.binding.iteration_label")}),i.jsx("span",{style:H6,children:n("layout_editor.binding.shape_array")})]}),d?i.jsxs("div",{"data-testid":"g7le-iteration-binding-complex",style:U6,children:[n("layout_editor.binding.complex"),i.jsx("code",{style:Yf,children:a})]}):l?i.jsxs("div",{style:F6,children:[i.jsx("code",{"data-testid":"g7le-iteration-binding-expr",style:Yf,children:a}),i.jsx("button",{type:"button","data-testid":"g7le-iteration-binding-clear",onClick:()=>y(void 0),style:V6,children:n("layout_editor.binding.clear")})]}):i.jsx("div",{"data-testid":"g7le-iteration-binding-empty",style:K6,children:n("layout_editor.binding.not_connected")}),(h||v)&&i.jsxs("div",{"data-testid":"g7le-iteration-vars",style:q6,children:[h&&i.jsxs("span",{children:[n("layout_editor.binding.iteration_item_var"),": ",i.jsx("code",{style:Xf,children:h})]}),v&&i.jsxs("span",{children:[n("layout_editor.binding.iteration_index_var"),": ",i.jsx("code",{style:Xf,children:v})]})]}),!d&&i.jsxs("div",{style:{marginTop:4},children:[i.jsxs("button",{type:"button","data-testid":"g7le-iteration-binding-search-toggle",onClick:()=>p(w=>!w),style:G6,children:["🔍 ",n("layout_editor.binding.search")]}),c&&i.jsxs("div",{"data-testid":"g7le-iteration-binding-picker",style:Y6,children:[i.jsx("input",{type:"text",autoFocus:!0,"data-testid":"g7le-iteration-binding-search-input",value:f,placeholder:n("layout_editor.binding.search_placeholder"),onChange:w=>b(w.target.value),style:X6}),i.jsx("div",{style:J6,children:m.length===0?i.jsx("div",{style:Z6,children:n("layout_editor.binding.no_results")}):m.map(w=>i.jsxs("button",{type:"button","data-testid":`g7le-iteration-binding-candidate-${w.expression}`,onClick:()=>_(w),style:Q6,children:[i.jsxs("span",{style:{display:"flex",flexDirection:"column",alignItems:"flex-start"},children:[i.jsx("span",{style:{fontSize:12},children:w.resolvedLabel}),i.jsxs("span",{style:R6,children:[Gf(n,w.groupLabelKey,w.sourceId)," · ",w.path||w.sourceId]})]}),i.jsx("span",{style:eT,children:w.preview})]},w.expression))})]})]})]}),i.jsx("div",{style:tT})]})}const P6={display:"flex",flexDirection:"column",marginBottom:8},O6={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:4},B6={fontSize:10,color:"#94a3b8",marginBottom:6,lineHeight:1.4},W6={display:"flex",flexDirection:"column",gap:4,padding:"8px 0"},j6={display:"flex",alignItems:"center",gap:6},H6={fontSize:10,padding:"1px 6px",borderRadius:4,background:"#e0e7ff",color:"#3730a3"},F6={display:"flex",alignItems:"center",gap:6},K6={fontSize:11,color:"#94a3b8"},Yf={fontSize:11,fontFamily:"monospace",background:"#f1f5f9",padding:"2px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all"},V6={fontSize:11,border:"1px solid #e2e8f0",borderRadius:4,background:"#fff",color:"#dc2626",padding:"2px 8px",cursor:"pointer"},U6={display:"flex",flexDirection:"column",gap:2,fontSize:11,color:"#64748b"},q6={display:"flex",gap:12,fontSize:10,color:"#94a3b8",marginTop:2},Xf={fontSize:10,fontFamily:"monospace",background:"#f1f5f9",padding:"1px 4px",borderRadius:3,color:"#475569"},G6={fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#334155",padding:"4px 10px",cursor:"pointer",textAlign:"left",width:"100%"},Y6={marginTop:4,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",padding:6},X6={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},J6={marginTop:4,maxHeight:200,overflowY:"auto",display:"flex",flexDirection:"column",gap:2},Z6={fontSize:11,color:"#94a3b8",padding:"8px 0",textAlign:"center"},Q6={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,border:"none",background:"transparent",cursor:"pointer",padding:"6px 8px",borderRadius:4,textAlign:"left"},R6={fontSize:10,color:"#94a3b8"},eT={fontSize:10,color:"#64748b",fontFamily:"monospace",whiteSpace:"nowrap"},tT={borderTop:"1px solid #e2e8f0",marginTop:4},nT=new Set(["Span","P","H1","H2","H3","H4","H5","H6","A","Button","Li","Label"]);function oT(e,t){if(!e||e.iteration&&typeof e.iteration=="object")return!1;const n=t?.textBinding;if(n===!1)return!1;if(n===!0)return!0;const o=typeof e.name=="string"?e.name:"";return nT.has(o)?!0:typeof e.text=="string"}const yn={direction:"flexDirection",justify:"flexJustify",align:"flexAlign",wrap:"flexWrap",gap:"flexGap",enable:"flexEnable"},mi={grow:"flexItemGrow",selfAlign:"flexItemAlign",order:"flexItemOrder"};function Jf(e){const t=e?.flexEditor;return t==="container"||t==="item"||t==="auto"?t:null}function rT(e){if(!e||typeof window>"u"||typeof window.getComputedStyle!="function")return!1;const t=(window.getComputedStyle(e).display??"").toLowerCase();return t==="flex"||t==="inline-flex"}function iT(e,t,n=Wt){if(!e||!t)return!1;const o=zo(e,t,n),r=t.options,s=Array.isArray(r)?t.onValue??r[0]?.value:void 0,a=l=>s!==void 0?l===s:l!==void 0&&l!==!1;return n.breakpoint!=="base"?a(o.scopedRawValue):o.matched&&a(o.value)}function sT(e,t,n=!1,o=!1,r=Wt){if(e==="container")return{showContainer:!0,showEnableButton:!1,showDisableButton:!1};if(e==="item")return{showContainer:!1,showEnableButton:!1,showDisableButton:!1};if(e==="auto"){const s=r.breakpoint==="base";return!o&&!s?{showContainer:!1,showEnableButton:!1,showDisableButton:!1}:(o?n:rT(t))?{showContainer:!0,showEnableButton:!1,showDisableButton:o}:{showContainer:!1,showEnableButton:!0,showDisableButton:!1}}return{showContainer:!1,showEnableButton:!1,showDisableButton:!1}}const aT={[yn.direction]:"layout_editor.flex.direction",[yn.justify]:"layout_editor.flex.justify",[yn.align]:"layout_editor.flex.align",[yn.wrap]:"layout_editor.flex.wrap",[yn.gap]:"layout_editor.flex.gap"},lT={[mi.grow]:"layout_editor.flex.item_grow",[mi.selfAlign]:"layout_editor.flex.item_align",[mi.order]:"layout_editor.flex.item_order"};function dT({node:e,spec:t,capability:n,t:o,onPatchNode:r,liveElement:s,scope:a=Wt}){const l=Jf(n),d=Ct(t,yn.enable),c=iT(e,d,a),{showContainer:p,showEnableButton:f,showDisableButton:b}=sT(l,s,c,!!d,a),g=Object.values(yn).filter(x=>x!==yn.enable&&Ct(t,x)),m=Object.values(mi).filter(x=>Ct(t,x)),h=d?.options,v=d?.onValue??h?.[0]?.value??!0,y=Array.isArray(h)&&h.length>=2?h[1].value:void 0,_=()=>{if(!d)return;const x=fn(e,d,v,a);r(x)},w=()=>{if(!d)return;const x=a.breakpoint!=="base"&&y!==void 0?y:void 0,$=fn(e,d,x,a);r($)},k=(x,$,S)=>i.jsx("div",{"data-testid":S,style:{display:"flex",flexDirection:"column"},children:x.map(C=>{const T=Ct(t,C);if(!T)return null;const E=T.label?T:{...T,label:`$t:${$[C]}`};return i.jsx(hi,{controlKey:C,control:E,node:e,t:o,onPatch:r,scope:a},C)})});return i.jsxs("div",{className:"g7le-flex-editor","data-testid":"g7le-flex-editor",style:{display:"flex",flexDirection:"column",gap:12},children:[f&&i.jsx("button",{type:"button","data-testid":"g7le-flex-enable",onClick:_,style:cT,children:o("layout_editor.flex.make_flex")}),p&&g.length>0&&i.jsxs("div",{className:"g7le-flex-container-section","data-testid":"g7le-flex-container-section",children:[i.jsx("div",{style:Zf,children:o("layout_editor.flex.container_title")}),k(g,aT,"g7le-flex-container-controls"),b&&i.jsx("button",{type:"button","data-testid":"g7le-flex-disable",onClick:w,style:uT,children:o("layout_editor.flex.unmake_flex")})]}),l==="item"&&m.length>0&&i.jsxs("div",{className:"g7le-flex-item-section","data-testid":"g7le-flex-item-section",children:[i.jsx("div",{style:Zf,children:o("layout_editor.flex.item_title")}),k(m,lT,"g7le-flex-item-controls")]}),!p&&!f&&l!=="item"&&i.jsx("div",{"data-testid":"g7le-flex-empty",style:pT,children:o("layout_editor.flex.not_flex")})]})}const Zf={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:6},cT={padding:"8px 12px",fontSize:12,border:"1px dashed #2563eb",borderRadius:6,background:"#eff6ff",color:"#2563eb",cursor:"pointer"},uT={marginTop:8,padding:"6px 10px",fontSize:12,border:"1px solid #e2e8f0",borderRadius:6,background:"#f8fafc",color:"#64748b",cursor:"pointer"},pT={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},Qf=["desktop","tablet","mobile","portable"],La=1280,fT=820,gT=390,hT=1920,yT=320;function bT(e){const t=[],n=new Set,o=r=>{if(!r||typeof r!="object")return;const s=r.responsive;if(s&&typeof s=="object")for(const a of Object.keys(s)){n.has(a)||(n.add(a),t.push(a));const l=s[a]?.children;if(Array.isArray(l))for(const d of l)o(d)}if(Array.isArray(r.children))for(const a of r.children)o(a)};if(Array.isArray(e))for(const r of e)o(r);return t}function mT(e){const t=[...Qf],n=new Set(Qf);for(const o of bT(e))!n.has(o)&&!t.includes(o)&&t.push(o);return t}function vT(e,t){const n=e?.responsive;if(!n||typeof n!="object")return[];const o=[];for(const r of Object.keys(n)){const s=n[r];!s||!Array.isArray(s.children)||r!==t&&o.push(r)}return o}function _T(e){switch(e){case"desktop":return La;case"tablet":return fT;case"mobile":return gT}const t=e in Do?Do[e]:Mn.parseRange(e);return!t||!Number.isFinite(t.max)?La:Math.round(Math.max(yT,Math.min(hT,t.max)))}function Rf(){const t=Ft()?.document?.raw?.components;return u.useMemo(()=>mT(t??null),[t])}const xT={desktop:"layout_editor.property_modal.scope.device_desktop",tablet:"layout_editor.property_modal.scope.device_tablet",mobile:"layout_editor.property_modal.scope.device_mobile",portable:"layout_editor.property_modal.scope.device_portable"},wT=[{key:"base",labelKey:"layout_editor.property_modal.scope.scheme_light"},{key:"dark",labelKey:"layout_editor.property_modal.scope.scheme_dark"}];function eg({scope:e,onChange:t,node:n,t:o,showColorScheme:r=!0,onClearScope:s}){const[a,l]=u.useState(!1),[d,c]=u.useState(""),[p,f]=u.useState(""),[b,g]=u.useState(null),m=Rf(),h=u.useMemo(()=>{const w=["base",...m],k=new Set(w);for(const x of Object.keys(n.responsive??{}))x!=="base"&&!k.has(x)&&(k.add(x),w.push(x));return e.breakpoint!=="base"&&!k.has(e.breakpoint)&&w.push(e.breakpoint),w},[m,n.responsive,e.breakpoint]),v=w=>t({...e,colorScheme:w}),y=w=>t({...e,breakpoint:w}),_=()=>{const w=d.trim(),k=p.trim();if(w===""&&k===""){g(o("layout_editor.property_modal.scope.custom_invalid"));return}const x=`${w}-${k}`;if(!xC(x)){g(o("layout_editor.property_modal.scope.custom_invalid"));return}g(null),l(!1),c(""),f(""),y(x)};return i.jsxs("div",{className:"g7le-style-scope-tabs","data-testid":"g7le-style-scope-tabs",style:kT,children:[r&&i.jsx("div",{className:"g7le-style-scope-scheme","data-testid":"g7le-style-scope-scheme",role:"tablist","aria-label":o("layout_editor.property_modal.scope.scheme_light"),style:tg,children:wT.map(w=>{const k=e.colorScheme===w.key;return i.jsxs("button",{type:"button",role:"tab","aria-selected":k,"data-testid":`g7le-style-scheme-${w.key}`,"data-active":k?"true":"false",onClick:()=>v(w.key),style:ng(k),children:[o(w.labelKey),w.key==="dark"&&Js(n,{colorScheme:"dark",breakpoint:e.breakpoint})&&i.jsx("span",{"data-testid":"g7le-style-scheme-dark-dot",style:og})]},w.key)})}),i.jsxs("div",{className:"g7le-style-scope-device","data-testid":"g7le-style-scope-device",role:"tablist","aria-label":o("layout_editor.property_modal.scope.device_base"),style:tg,children:[h.map(w=>{const k=e.breakpoint===w,x=w==="base"||$u(w),$=w==="base"?"layout_editor.property_modal.scope.device_base":xT[w],S=$?o($):w,C=x?`g7le-style-bp-${w}`:`g7le-style-bp-custom-${w}`;return i.jsxs("button",{type:"button",role:"tab","aria-selected":k,"data-testid":C,"data-active":k?"true":"false",onClick:()=>y(w),style:ng(k),children:[S,Js(n,{colorScheme:"base",breakpoint:w})&&i.jsx("span",{"data-testid":`${C}-dot`,style:og})]},String(w))}),i.jsxs("button",{type:"button","data-testid":"g7le-style-bp-add-custom",onClick:()=>l(w=>!w),style:$T,children:["+ ",o("layout_editor.property_modal.scope.add_custom")]})]}),a&&i.jsxs("div",{className:"g7le-style-scope-custom-input","data-testid":"g7le-style-scope-custom-input",style:ST,children:[i.jsx("input",{type:"number","data-testid":"g7le-style-custom-min",placeholder:o("layout_editor.property_modal.scope.custom_min"),value:d,onChange:w=>c(w.target.value),style:rg}),i.jsx("span",{style:{color:"#94a3b8"},children:"—"}),i.jsx("input",{type:"number","data-testid":"g7le-style-custom-max",placeholder:o("layout_editor.property_modal.scope.custom_max"),value:p,onChange:w=>f(w.target.value),style:rg}),i.jsx("button",{type:"button","data-testid":"g7le-style-custom-confirm",onClick:_,style:ET,children:o("layout_editor.property_modal.scope.add_custom")})]}),b&&i.jsx("div",{"data-testid":"g7le-style-custom-error",style:IT,children:b}),e.breakpoint!=="base"&&!$u(e.breakpoint)&&i.jsx("div",{"data-testid":"g7le-style-custom-priority-note",style:AT,children:o("layout_editor.property_modal.scope.custom_priority_note")}),s&&Js(n,e)&&i.jsxs("button",{type:"button","data-testid":"g7le-style-scope-reset",onClick:s,style:CT,children:["↺ ",o("layout_editor.property_modal.scope.reset_to_base")]})]})}const kT={display:"flex",flexDirection:"column",gap:0,padding:"0 0 8px",borderBottom:"1px solid #e2e8f0",marginBottom:8},ST={display:"flex",gap:6,alignItems:"center",marginTop:4},tg={display:"flex",gap:2,flexWrap:"wrap",borderBottom:"1px solid #e2e8f0",margin:"0 -16px",padding:"0 12px"};function ng(e){return{display:"inline-flex",alignItems:"center",gap:4,padding:"6px 12px",fontSize:12,border:"none",borderBottom:`2px solid ${e?"#2563eb":"transparent"}`,background:"transparent",color:e?"#2563eb":"#64748b",cursor:"pointer",fontWeight:e?700:500,marginBottom:-1}}const og={display:"inline-block",width:5,height:5,borderRadius:3,background:"#f59e0b"},CT={alignSelf:"flex-start",marginTop:2,padding:"3px 8px",fontSize:10,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},$T={padding:"6px 12px",fontSize:11,border:"none",borderBottom:"2px dashed #cbd5e1",background:"transparent",color:"#475569",cursor:"pointer",marginBottom:-1},rg={width:70,padding:"4px 6px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6},ET={padding:"4px 10px",fontSize:11,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"},IT={fontSize:11,color:"#dc2626"},AT={fontSize:10,color:"#94a3b8"},ig=new Map;function Pn(e,t){ig.set(e,t)}function TT(e){return e?ig.get(e)??null:null}const Pa={id:{label:"$t:layout_editor.core_props.id.label",widget:"core-id",placeholder:"$t:layout_editor.core_props.id.placeholder",apply:{type:"propValue",propKey:"id"}},dataKey:{label:"$t:layout_editor.core_props.dataKey.label",widget:"core-datakey",placeholder:"$t:layout_editor.core_props.dataKey.placeholder",apply:{type:"nodeKey",nodeKey:"dataKey"}},isolatedState:{label:"$t:layout_editor.core_props.isolatedState.label",widget:"toggle",apply:{type:"nodeKey",nodeKey:"isolatedState"}},isolatedScopeId:{label:"$t:layout_editor.core_props.isolatedScopeId.label",widget:"core-scopeid",placeholder:"$t:layout_editor.core_props.isolatedScopeId.placeholder",apply:{type:"nodeKey",nodeKey:"isolatedScopeId"}}},DT=["id"];function zT(e){return e===!1?[]:Array.isArray(e)?e.filter(t=>t in Pa):[...DT]}function sg(e){const t=e.props?.id??e.id;return typeof t=="string"&&t.length>0?`${t}-scope`:"scope"}function NT({node:e,onPatchNode:t,t:n,scopeIdCandidates:o=[],usedScopeIds:r=[]}){const s=e,a="isolatedState"in s&&s.isolatedState!=null,l=typeof s.isolatedScopeId=="string"?s.isolatedScopeId:"",[d,c]=u.useState(""),p=()=>{const h={...e};a?(delete h.isolatedState,delete h.isolatedScopeId):(h.isolatedState={},h.isolatedScopeId=sg(e)),t(h)},f=h=>{const v={...e};v.isolatedScopeId=h.trim()===""?sg(e):h,t(v)},b=h=>{const v={...e};v.isolatedState=h,t(v)},g=u.useMemo(()=>{const h=d.trim().toLowerCase();return o.filter(v=>!h||v.toLowerCase().includes(h))},[o,d]),m=l!==""&&r.includes(l);return i.jsxs("div",{className:"g7le-isolated-scope","data-testid":"g7le-isolated-scope-control",style:MT,children:[i.jsx("div",{style:LT,children:n("layout_editor.core_props.isolatedState.label")}),i.jsxs("div",{style:PT,children:[i.jsx("button",{type:"button","data-testid":"g7le-isolated-toggle",role:"switch","aria-checked":a,onClick:p,style:OT(a),children:n(a?"layout_editor.overlay.on":"layout_editor.overlay.off")}),a?null:i.jsx("span",{"data-testid":"g7le-isolated-off-hint",style:BT,children:n("layout_editor.core_props.isolatedState.off_hint")})]}),a?i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:ag,children:[i.jsx("label",{style:lg,children:n("layout_editor.core_props.isolatedScopeId.label")}),i.jsx("input",{type:"text","data-testid":"g7le-isolated-scopeid-input",value:l,placeholder:n("layout_editor.core_props.isolatedScopeId.placeholder"),onChange:h=>f(h.target.value),style:WT}),g.length>0?i.jsxs("div",{"data-testid":"g7le-isolated-scopeid-picker",style:jT,children:[i.jsx("input",{type:"text","data-testid":"g7le-isolated-scopeid-search",value:d,placeholder:n("layout_editor.core_props.isolatedScopeId.search"),onChange:h=>c(h.target.value),style:HT}),i.jsx("div",{style:FT,children:g.map(h=>i.jsx("button",{type:"button","data-testid":`g7le-isolated-scopeid-candidate-${h}`,onClick:()=>{f(h),c("")},style:KT,children:h},h))})]}):null,m?i.jsxs("p",{"data-testid":"g7le-isolated-scopeid-dup",style:VT,children:["ⓘ ",n("layout_editor.core_props.isolatedScopeId.duplicate")]}):null]}),i.jsxs("div",{style:ag,children:[i.jsx("label",{style:lg,children:n("layout_editor.core_props.isolatedState.initial_label")}),i.jsx("div",{"data-testid":"g7le-isolated-initial-value",children:i.jsx(zn,{value:s.isolatedState??{},onChange:b,t:n,path:"isolatedState",scope:"isolated-node"})})]})]}):null]})}const MT={display:"flex",flexDirection:"column",gap:8,padding:10,border:"1px solid #e2e8f0",borderRadius:8,minWidth:0},LT={fontSize:12,fontWeight:700,color:"#0f172a"},PT={display:"flex",gap:8,alignItems:"center"},OT=e=>({padding:"4px 12px",fontSize:11,border:`1px solid ${e?"#3b82f6":"#cbd5e1"}`,borderRadius:14,background:e?"#eff6ff":"#fff",color:e?"#1d4ed8":"#64748b",cursor:"pointer"}),BT={fontSize:11,color:"#94a3b8"},ag={display:"flex",flexDirection:"column",gap:4,minWidth:0},lg={fontSize:11,color:"#64748b"},WT={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box",width:"100%"},jT={border:"1px solid #e2e8f0",borderRadius:6,padding:4,background:"#fff"},HT={width:"100%",padding:"4px 6px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,marginBottom:4,boxSizing:"border-box"},FT={display:"flex",flexDirection:"column",maxHeight:120,overflowY:"auto"},KT={textAlign:"left",padding:"4px 6px",fontSize:12,border:"none",background:"transparent",cursor:"pointer",borderRadius:4,color:"#0f172a"},VT={margin:0,fontSize:11,color:"#64748b"},UT={borderTop:"2px solid #c7d2fe",background:"#eef2ff",padding:"10px 12px",display:"flex",flexDirection:"column",gap:8},dg={fontSize:13,fontWeight:700,color:"#3730a3",display:"flex",alignItems:"center",gap:6},qT={fontSize:11,fontWeight:600,color:"#4338ca",background:"#e0e7ff",border:"1px solid #c7d2fe",borderRadius:4,padding:"1px 6px"},Oa={fontSize:11,color:"#6366f1"},GT={alignSelf:"flex-start",fontSize:12,fontWeight:600,color:"#fff",background:"#4f46e5",border:"none",borderRadius:4,padding:"4px 10px",cursor:"pointer"},YT={opacity:.5,cursor:"not-allowed"},XT={fontSize:11,color:"#dc2626"};function JT({entry:e,t,onSave:n}){const[o,r]=u.useState(()=>e.props),[s,a]=u.useState(!0),[l,d]=u.useState(null),[c,p]=u.useState(!1),[f,b]=u.useState(!1),g=e.extensionName??e.extensionIdentifier??`#${e.extensionId}`,m=async()=>{if(!s){d(t("layout_editor.property_modal.injected_props.invalid_json"));return}d(null),p(!0),b(!1);try{await n(o),b(!0)}catch(h){d(h instanceof Error?h.message:String(h))}finally{p(!1)}};return i.jsxs("div",{"data-testid":`g7le-injected-props-entry-${e.extensionId}`,style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx("div",{style:dg,children:i.jsx("span",{style:qT,"data-testid":"g7le-injected-props-origin-badge",children:t("layout_editor.property_modal.injected_props.origin",{source:g})})}),i.jsx(Hs,{value:o,shape:"object",emptyValue:{},testidPrefix:"g7le-injected-props-json",minHeight:80,invalidErrorKey:"layout_editor.property_modal.injected_props.invalid_json",shapeErrorKey:"layout_editor.property_modal.injected_props.invalid_json",t,onChange:h=>{r(h??{}),b(!1)},onValidityChange:h=>{a(h),h&&d(null),b(!1)}}),l&&i.jsx("div",{style:XT,"data-testid":"g7le-injected-props-error",children:l}),f&&i.jsx("div",{style:{...Oa,color:"#16a34a"},"data-testid":"g7le-injected-props-saved",children:t("layout_editor.property_modal.injected_props.saved")}),i.jsx("div",{style:Oa,children:t("layout_editor.property_modal.injected_props.save_target")}),i.jsx("button",{type:"button","data-testid":"g7le-injected-props-save",style:{...GT,...c||!s?YT:null},disabled:c||!s,onClick:m,children:c?t("layout_editor.property_modal.injected_props.saving"):t("layout_editor.property_modal.injected_props.save_button",{source:g})})]})}function ZT({injectedProps:e,t,onSaveInjectedProps:n}){return!Array.isArray(e)||e.length===0?null:i.jsxs("div",{style:UT,"data-testid":"g7le-injected-props-section",children:[i.jsxs("div",{style:dg,children:["🧩 ",t("layout_editor.property_modal.injected_props.title")]}),i.jsx("div",{style:Oa,children:t("layout_editor.property_modal.injected_props.help")}),e.map(o=>i.jsx(JT,{entry:o,t,onSave:r=>n(o.extensionId,r)},o.extensionId))]})}function QT(e,t){const n=e?.components??{};for(const o of Object.values(n)){const r=o?.find(s=>s.name===t);if(r)return r}return null}function RT({node:e,spec:t,manifest:n,t:o,onPatchNode:r,onClose:s,onDelete:a,permissionCandidates:l,pageCandidates:d,dataSourceCandidates:c,stateKeyCandidates:p,bindingCandidates:f,liveElement:b,scope:g=Wt,onScopeChange:m,templateIdentifier:h,initialTab:v,onSaveInjectedProps:y,branchLabel:_,isolatedScopeIdCandidates:w,usedScopeIds:k}){const x=e.__injectedProps,$=Array.isArray(x)&&x.length>0&&!!y,S=ve=>{m?.(ve)},C=()=>{r(IC(e,g))},T=typeof e.name=="string"?e.name:"",E=ji(t,T),N=QT(n,T)?.settings,D=!!(N?.groups&&N.groups.length>0),B=Array.isArray(E?.propControls)?E.propControls:[],M=zT(E?.coreProps),O=new Set(M.map(ve=>Pa[ve].apply?.propKey)),z=B.filter(ve=>{const We=Ct(t,ve)?.apply?.propKey;return!(We!==void 0&&O.has(We))}),H=typeof E?.nodeEditor?.kind=="string"?E.nodeEditor.kind:void 0,P=E?.nodeEditor?.params,I=H?TT(H):null,L=!!I,F=Array.isArray(E?.dataProps)?E.dataProps:[],Y=F.length>0,K=!!(e.iteration&&typeof e.iteration=="object"),X=oT(e,E),Z=M.length>0||z.length>0||L||Y||X||K,ae=Array.isArray(E?.styleControls)?E.styleControls:[],oe=Array.isArray(E?.advanced)?E.advanced:[],ee=(Array.isArray(E?.events)?E.events:[]).length>0,ge=Jf(E),V=ae.length>0||ge!==null,be=!(E?.visibilityCondition===!1)&&(Z||V||ee||D||oe.length>0),Ee=u.useMemo(()=>{const ve=[];return D&&ve.push("settings"),Z&&ve.push("props"),V&&ve.push("style"),ee&&ve.push("action"),be&&ve.push("visibility"),ve.push("translation"),oe.length>0&&ve.push("advanced"),ve},[D,Z,V,ee,be,oe.length]),De=z.length>0||L||Y||K,[Se,Ue]=u.useState(v&&Ee.includes(v)?v:D?"settings":De?"props":V?"style":Z?"props":Ee[0]??"style"),Me=qA(e),Oe=!Z&&!V&&!D&&!ee&&!be&&oe.length===0,Ye=E?.label?E.label.startsWith("$t:")?o(E.label.slice(3)):E.label:T||o("layout_editor.property_modal.element"),ze=(ve,qe)=>{const We={...e.props??{}};qe===void 0?delete We[ve]:We[ve]=qe,r({...e,props:We})},Xe={settings:o("layout_editor.property_modal.tab.settings"),props:o("layout_editor.property_modal.tab.props"),style:o("layout_editor.property_modal.tab.style"),action:o("layout_editor.property_modal.tab.action"),visibility:o("layout_editor.property_modal.tab.visibility"),translation:o("layout_editor.property_modal.tab.translation"),advanced:o("layout_editor.property_modal.tab.advanced")};return i.jsxs("div",{className:"g7le-property-modal","data-testid":"g7le-property-modal",style:e4,children:[i.jsxs("div",{"data-modal-drag-handle":!0,"data-testid":"g7le-property-modal-header",style:t4,children:[i.jsx("span",{"data-testid":"g7le-property-modal-title",style:{fontSize:14,fontWeight:700},children:D&&Se==="settings"?o("layout_editor.property_modal.settings_title",{name:Ye}):o("layout_editor.property_modal.title",{name:Ye})}),i.jsx("button",{type:"button","data-testid":"g7le-property-modal-close","aria-label":"close",onClick:s,style:n4,children:"✕"})]}),Me&&i.jsx("div",{"data-testid":"g7le-property-modal-advanced-badge",style:o4,children:o("layout_editor.property_modal.advanced_badge")}),_&&i.jsx("div",{"data-testid":"g7le-property-modal-branch-badge",style:r4,children:o("layout_editor.property_modal.branch_badge",{device:_})}),i.jsx("div",{style:i4,role:"tablist",children:Ee.map(ve=>i.jsx("button",{type:"button",role:"tab","aria-selected":Se===ve,"data-testid":`g7le-property-tab-${ve}`,"data-active":Se===ve?"true":"false",onClick:()=>Ue(ve),style:{...s4,color:Se===ve?"#2563eb":"#64748b",borderBottomColor:Se===ve?"#2563eb":"transparent"},children:Xe[ve]},ve))}),i.jsxs("div",{style:a4,"data-testid":"g7le-property-modal-body",children:[Oe&&!$&&i.jsx("div",{"data-testid":"g7le-property-modal-no-editable",style:ug,children:o("layout_editor.property_modal.no_editable_props")}),$&&i.jsx(ZT,{injectedProps:x,t:o,onSaveInjectedProps:y}),Se==="settings"&&N&&i.jsx(MA,{spec:N,node:e,t:o,onPatchProp:ze}),Se==="props"&&i.jsxs("div",{"data-testid":"g7le-property-props-tab",style:{display:"flex",flexDirection:"column"},children:[K&&i.jsx(L6,{node:e,candidates:f??[],t:o,onPatchNode:r}),Y&&i.jsx(d6,{node:e,dataProps:F,candidates:f??[],t:o,onPatchNode:r}),X&&i.jsx(T6,{node:e,candidates:f??[],t:o,onPatchNode:r,templateIdentifier:h}),L&&I&&i.jsx(I,{node:e,params:P,spec:t,manifest:n,t:o,onPatchNode:r,templateIdentifier:h,candidates:f}),M.map(ve=>i.jsx(hi,{controlKey:`core-${ve}`,control:Pa[ve],node:e,t:o,onPatch:r,scope:Wt,bindingCandidates:f},`core-${ve}`)),z.map(ve=>{const qe=Ct(t,ve);return qe?i.jsx(hi,{controlKey:ve,control:qe,node:e,t:o,onPatch:r,scope:Wt,bindingCandidates:f},ve):null}),i.jsx(NT,{node:e,onPatchNode:r,t:o,scopeIdCandidates:w,usedScopeIds:k})]}),Se==="style"&&i.jsxs("div",{"data-testid":"g7le-property-style-tab",style:{display:"flex",flexDirection:"column"},children:[i.jsx("div",{style:cg,children:i.jsx(eg,{scope:g,onChange:S,node:e,t:o,onClearScope:C})}),ge!==null&&i.jsx(dT,{node:e,spec:t,capability:E,t:o,onPatchNode:r,liveElement:b,scope:g}),ae.map(ve=>{const qe=Ct(t,ve);return qe?i.jsx(hi,{controlKey:ve,control:qe,node:e,t:o,onPatch:r,scope:g},ve):null})]}),Se==="action"&&i.jsx(i6,{node:e,spec:t,capability:E,t:o,onPatchNode:r,pageCandidates:d,dataSourceCandidates:c,stateKeyCandidates:p,bindingCandidates:f}),Se==="visibility"&&i.jsxs("div",{"data-testid":"g7le-property-visibility-tab",style:{display:"flex",flexDirection:"column"},children:[i.jsx("div",{style:cg,children:i.jsx(eg,{scope:g,onChange:S,node:e,t:o,showColorScheme:!1})}),i.jsx(Du,{node:e,spec:t,t:o,onPatchNode:r,dataSourceCandidates:c,stateKeyCandidates:p,scope:g})]}),Se==="translation"&&(h?i.jsx(Xd,{customKey:Yd(e),templateIdentifier:h,t:o,paramLabels:wv(e),onRemoveParam:ve=>{const qe=typeof e.text=="string"?e.text:"";r({...e,text:vo(qe,ve)});const We=Yd(e);h&&We&&$r(h,We,ve)}}):i.jsx("div",{"data-testid":"g7le-property-translation-deferred",style:ug,children:o("layout_editor.translation.not_a_key")})),Se==="advanced"&&i.jsx(YA,{node:e,advanced:oe,t:o,onPatch:r,permissionCandidates:l})]}),i.jsxs("div",{style:l4,children:[i.jsx("span",{"data-testid":"g7le-property-modal-node-id",style:{fontSize:11,color:"#94a3b8"},children:typeof e.id=="string"||typeof e.id=="number"?`ID: ${e.id}`:""}),i.jsxs("div",{style:{display:"flex",gap:8},children:[i.jsx("button",{type:"button","data-testid":"g7le-property-modal-delete",onClick:a,style:d4,children:o("layout_editor.property_modal.delete_element")}),i.jsx("button",{type:"button","data-testid":"g7le-property-modal-done",onClick:s,style:c4,children:o("layout_editor.property_modal.close")})]})]})]})}const e4={display:"flex",flexDirection:"column",width:420,maxWidth:"92vw"},t4={display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #e2e8f0",cursor:"move",userSelect:"none"},n4={border:"none",background:"transparent",fontSize:14,cursor:"pointer",color:"#64748b"},o4={margin:"8px 16px 0",padding:"6px 10px",fontSize:11,background:"#fef3c7",color:"#92400e",borderRadius:6},r4={margin:"8px 16px 0",padding:"6px 10px",fontSize:11,background:"#dbeafe",color:"#1e40af",borderRadius:6},i4={display:"flex",gap:2,padding:"0 12px",borderBottom:"1px solid #e2e8f0",overflowX:"auto"},s4={padding:"8px 10px",fontSize:12,border:"none",borderBottom:"2px solid transparent",background:"transparent",cursor:"pointer",whiteSpace:"nowrap"},a4={padding:16,overflowY:"auto",maxHeight:"60vh"},cg={position:"sticky",top:-16,zIndex:2,background:"#fff",margin:"-16px -16px 0",padding:"6px 16px 0"},ug={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},l4={display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderTop:"1px solid #e2e8f0"},d4={padding:"6px 12px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},c4={padding:"6px 12px",fontSize:12,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"},Ba="g7le:component-target-picked",Wa="g7le:component-target-pick-request";let u4=1;function p4({value:e,onChange:t,t:n,control:o}){const r=bo(),s=e==null?"":String(e),a=o?.allowManualInput!==!1,l=u.useCallback(()=>{if(typeof window>"u")return;const d=`pick-${u4++}`,p=r.stack[r.stack.length-1]?.id;p&&r.minimize(p,n("layout_editor.target_picker.minimized_hint"));const f=b=>{const g=b.detail;g?.requestId===d&&(window.removeEventListener(Ba,f),p&&r.restore(p),!g.cancelled&&typeof g.id=="string"&&t(g.id))};window.addEventListener(Ba,f),window.dispatchEvent(new CustomEvent(Wa,{detail:{requestId:d}}))},[r,t,n]);return i.jsx("div",{className:"g7le-component-target-picker","data-testid":"g7le-component-target-picker",children:i.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[a?i.jsx("input",{type:"text",className:"g7le-widget g7le-widget--text","data-testid":"g7le-component-target-input",value:s,placeholder:n("layout_editor.target_picker.id_placeholder"),onChange:d=>t(d.target.value===""?void 0:d.target.value),style:{flex:1,minWidth:0,padding:"6px 8px",border:"1px solid #cbd5e1",borderRadius:6,fontSize:13}}):i.jsx("span",{"data-testid":"g7le-component-target-value",style:{flex:1,minWidth:0},children:s||n("layout_editor.target_picker.none")}),i.jsxs("button",{type:"button","data-testid":"g7le-component-target-pick",onClick:l,style:{display:"flex",alignItems:"center",gap:4,padding:"6px 10px",background:"#1e293b",color:"#fff",border:"none",borderRadius:6,cursor:"pointer",fontSize:13,whiteSpace:"nowrap"},children:[i.jsx("span",{"aria-hidden":"true",children:"🎯"}),n("layout_editor.target_picker.select_area")]})]})})}async function f4(e,t,n,o,r=fetch){const s=`/api/admin/templates/${encodeURIComponent(e)}/layout-extensions/${t}`;let a;try{a=await r(s,{headers:Ne(),credentials:"same-origin"})}catch(y){return{kind:"error",message:y instanceof Error?y.message:String(y)}}if(a.status===404)return{kind:"not_found"};if(!a.ok)return{kind:"error",message:`HTTP ${a.status}`};const l=await a.json().catch(()=>null),d=(l&&(l.data||l))??{};let c={};const p=d.content;if(typeof p=="string")try{c=JSON.parse(p)}catch{return{kind:"error",message:"invalid extension content"}}else p&&typeof p=="object"&&(c=p);const f=typeof d.lock_version=="number"?d.lock_version:0,b=Array.isArray(c.injections)?[...c.injections]:[],g=b.findIndex(y=>y&&y.position==="inject_props"&&y.target_id===n);if(g<0)return{kind:"injection_not_found"};b[g]={...b[g],props:o};const m={...c,injections:b};let h;try{h=await r(s,{method:"PUT",headers:Ne({"Content-Type":"application/json"}),credentials:"same-origin",body:JSON.stringify({content:m,expected_lock_version:f})})}catch(y){return{kind:"error",message:y instanceof Error?y.message:String(y)}}const v=await h.json().catch(()=>null);return h.ok?{kind:"success",newLockVersion:typeof v?.data?.lock_version=="number"?v.data.lock_version:f+1}:h.status===409?{kind:"conflict",currentVersion:v?.current_version??-1,yourVersion:v?.your_version??f}:{kind:"error",message:v?.message??`HTTP ${h.status}`}}const pg=new Map;function ja(e,t){pg.set(e,t)}function g4(e){return e?pg.get(e)??null:null}const fg="g7le.clipboard";function gg(){try{return typeof window>"u"||!window.sessionStorage?null:window.sessionStorage}catch{return null}}function h4(e){const t=JSON.parse(JSON.stringify(e)),n=o=>{for(const r of Object.keys(o))r.startsWith("__")&&delete o[r];Array.isArray(o.children)&&o.children.forEach(n)};return n(t),t}function hg(e,t=0){const n=gg();if(!n)return!1;try{const o={node:h4(e),copiedAt:t};return n.setItem(fg,JSON.stringify(o)),!0}catch{return!1}}function y4(){const e=gg();if(!e)return null;try{const t=e.getItem(fg);if(!t)return null;const n=JSON.parse(t);return!n||typeof n.node!="object"||n.node===null?null:JSON.parse(JSON.stringify(n.node))}catch{return null}}const Qo={nw:{width:-1,height:-1},n:{width:0,height:-1},ne:{width:1,height:-1},e:{width:1,height:0},se:{width:1,height:1},s:{width:0,height:1},sw:{width:-1,height:1},w:{width:-1,height:0}};function Ha(e){if(typeof e=="number")return e;if(typeof e=="string"){const t=e.match(/^(-?\d+(?:\.\d+)?)px$/);if(t)return Number(t[1])}return null}function b4(e,t){const n=Array.isArray(e.options)?e.options:[],o=Array.isArray(e.scale)?e.scale:[],r=n.length>0?n.map(l=>l.value):o;if(r.length===0)return;let s=r[0],a=1/0;return r.forEach((l,d)=>{const c=Ha(l)??d*40,p=Math.abs(c-t);p{if(!t)return;const m=Qo[b];if(m.width!==0&&!n||m.height!==0&&!o)return;const h=t.props?.style??{},v=s?.()??null,y=Ha(h.width)??(v?Math.round(v.width):0),_=Ha(h.height)??(v?Math.round(v.height):0);p.current={handle:b,startX:g.clientX,startY:g.clientY,startW:y,startH:_,node:t};const w=m.width!==0&&m.height!==0?"both":m.width!==0?"width":"height";d?.(w);let k=null;const x=S=>{const C=p.current;if(!C)return;const T=r||1,E=(S.clientX-C.startX)/T*Qo[C.handle].width,A=(S.clientY-C.startY)/T*Qo[C.handle].height;let N=C.node;if(Qo[C.handle].width!==0&&n){const D=yg(n,C.startW+E);N=fn(N,n,D)}if(Qo[C.handle].height!==0&&o){const D=yg(o,C.startH+A);N=fn(N,o,D)}k=N,a(N,w)},$=()=>{p.current=null,d?.(null),window.removeEventListener("pointermove",x),window.removeEventListener("pointerup",$),k&&l?.(k,w)};window.addEventListener("pointermove",x),window.addEventListener("pointerup",$)},[t,n,o,r,a,l,d]);return{enabledAxes:c,onHandlePointerDown:f}}const bg=320,mg=1920,_4=1024;function Fa(e){return Number.isFinite(e)?Math.round(Math.max(bg,Math.min(mg,e))):_4}function Ka(e={}){const{state:t,dispatch:n}=Qe(),{previewDevice:o,previewZoom:r,previewCustomWidth:s,previewColorScheme:a}=t,l=o==="custom"?Fa(s):_T(o),d=u.useMemo(()=>{const g=e.availableWidth??l,m=l*r;return r>=1||m<=g?r:Math.min(r,g/l)},[l,r,e.availableWidth]),c=u.useCallback(g=>{n({type:"SET_PREVIEW_DEVICE",device:g})},[n]),p=u.useCallback(g=>{const m=Math.max(.5,Math.min(1,g));n({type:"SET_PREVIEW_ZOOM",zoom:m})},[n]),f=u.useCallback(g=>{n({type:"SET_PREVIEW_CUSTOM_WIDTH",width:Fa(g)})},[n]),b=u.useCallback(g=>{n({type:"SET_PREVIEW_COLOR_SCHEME",scheme:g})},[n]);return{device:o,deviceWidth:l,zoom:r,scale:d,customWidth:Fa(s),setDevice:c,setZoom:p,setCustomWidth:f,colorScheme:a,setColorScheme:b}}const vi="g7le-dnd-handle-";function x4(e){if(typeof e!="string"||!e.startsWith(vi))return null;const t=e.slice(vi.length);return t.length>0?t:null}function w4(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\\]]/g,"\\$&")}function k4(e,t,n,o){const r=o?.handleFallback??!1;if(e instanceof HTMLElement){const s=e.closest("[data-editor-path]");if(s)return s;const a=e.closest('[data-testid^="g7le-"]');if(a&&!(a.getAttribute("data-testid")??"").startsWith(vi))return null;if(r){const l=e.closest(`[data-testid^="${vi}"]`);if(l&&t){const d=x4(l.getAttribute("data-testid"));if(d){const c=t.querySelector(`[data-editor-path="${w4(d)}"]`);if(c)return c}}}}if(r&&n&&typeof document<"u"&&typeof document.elementsFromPoint=="function")for(const s of document.elementsFromPoint(n.x,n.y)){const a=s.closest?.("[data-editor-path]");if(a)return a}return null}function S4(e,t,n){if(typeof e=="string"&&e.trim().length>0)return{color:e};const o=typeof n?.color=="string"&&n.color.length>0,r=typeof t=="string"&&t.trim().length>0;return o||r?{}:{color:"#0f172a"}}const C4="#ffffff",$4="#0f172a";function E4(e){const t=e.trim(),n=t.match(/^rgba?\(\s*([\d.]+)[\s,]+([\d.]+)[\s,]+([\d.]+)/i);if(n)return[Number(n[1]),Number(n[2]),Number(n[3])];const o=t.replace(/^#/,"");return/^[0-9a-f]{3}$/i.test(o)?[parseInt(o[0]+o[0],16),parseInt(o[1]+o[1],16),parseInt(o[2]+o[2],16)]:/^[0-9a-f]{6}$/i.test(o)?[parseInt(o.slice(0,2),16),parseInt(o.slice(2,4),16),parseInt(o.slice(4,6),16)]:null}function I4(e){if(!e||/transparent/i.test(e))return!1;const t=e.trim().match(/^oklch\(\s*([\d.]+)(%?)/i);if(t)return(t[2]==="%"?Number(t[1])/100:Number(t[1]))>=.62;const n=E4(e);if(!n)return!1;const[o,r,s]=n;return .299*o+.587*r+.114*s>=180}function A4(e,t,n){const o=typeof n?.color=="string"?n.color:null;return I4(e??o??t)?$4:C4}function T4({box:e,initialValue:t,isCustomKey:n,t:o,onCommit:r,onCancel:s,mirrorClassName:a,mirrorStyle:l,nodeEffectiveColor:d,onOpenTranslations:c}){const p=u.useRef(null),f=u.useRef(!1),[b,g]=u.useState(t.trim().length>0),[m,h]=u.useState(null);u.useEffect(()=>{const k=p.current;if(k){k.textContent=t,k.focus();try{const x=window.document.createRange();x.selectNodeContents(k);const $=window.getSelection();$?.removeAllRanges(),$?.addRange(x)}catch{}f.current=!1}},[t]),u.useEffect(()=>{const k=p.current;if(!k||typeof window.getComputedStyle!="function"){h(null);return}try{h(window.getComputedStyle(k).color||null)}catch{h(null)}},[a,l]);const v=()=>(p.current?.textContent??"").trim(),y=()=>{f.current||(f.current=!0,r(v()))},_=()=>{f.current||(f.current=!0,s())},w=k=>{k.key==="Enter"&&!k.shiftKey?(k.preventDefault(),y()):k.key==="Escape"&&(k.preventDefault(),_())};return i.jsxs("div",{className:"g7le-inline-text-editor","data-testid":"g7le-inline-text-editor","data-custom-key":n?"true":"false",style:{position:"absolute",left:e.left,top:e.top,minWidth:Math.max(e.width,60),minHeight:e.height,pointerEvents:"auto",zIndex:1e4},children:[i.jsx("div",{ref:p,role:"textbox","aria-label":o("layout_editor.inline_edit.aria_label"),"aria-multiline":"false","data-testid":"g7le-inline-text-editable",className:a,contentEditable:!0,suppressContentEditableWarning:!0,spellCheck:!1,onInput:()=>g(v().length>0),onKeyDown:w,onBlur:y,style:{outline:"2px solid #2563eb",outlineOffset:1,borderRadius:3,background:A4(d,m,l),padding:"2px 4px",minHeight:e.height,whiteSpace:"pre-wrap",wordBreak:"break-word",boxShadow:"0 2px 8px rgba(37, 99, 235, 0.25)",...l??{},...S4(d,a,l)}}),i.jsxs("div",{className:"g7le-inline-text-editor__hint","data-testid":"g7le-inline-text-editor-hint",style:{marginTop:2,display:"inline-flex",alignItems:"center",gap:4,whiteSpace:"nowrap"},children:[c?i.jsxs("button",{type:"button","data-testid":"g7le-inline-text-editor-open-translations",onMouseDown:k=>k.preventDefault(),onClick:k=>{k.preventDefault(),k.stopPropagation(),c()},title:o("layout_editor.inline_edit.open_translations"),style:{padding:"2px 8px",fontSize:11,background:n?"#eff6ff":"#f0fdf4",color:n?"#1d4ed8":"#15803d",border:`1px solid ${n?"#bfdbfe":"#bbf7d0"}`,borderRadius:4,display:"inline-flex",alignItems:"center",gap:4,cursor:"pointer",whiteSpace:"nowrap"},children:[i.jsx("span",{"aria-hidden":"true",children:"🌐"}),i.jsx("span",{children:o(n?"layout_editor.inline_edit.existing_key_hint":"layout_editor.inline_edit.new_key_hint")}),i.jsxs("span",{"aria-hidden":"true",style:{opacity:.7},children:["· ",o("layout_editor.inline_edit.open_translations")," ›"]})]}):i.jsx("span",{style:{padding:"2px 6px",fontSize:11,background:n?"#eff6ff":"#f0fdf4",color:n?"#1d4ed8":"#15803d",border:`1px solid ${n?"#bfdbfe":"#bbf7d0"}`,borderRadius:4,display:"inline-flex",alignItems:"center",gap:4,whiteSpace:"nowrap"},children:n?i.jsxs(i.Fragment,{children:["⌐ ",o("layout_editor.inline_edit.existing_key_hint")]}):i.jsxs(i.Fragment,{children:["✎ ",o("layout_editor.inline_edit.new_key_hint")]})}),!b&&i.jsx("span",{"data-testid":"g7le-inline-text-editor-empty-warn",style:{color:"#b91c1c",marginLeft:4},children:o("layout_editor.inline_edit.empty_warning")})]})]})}function D4({box:e,node:t,customKey:n,initialChipValue:o,chipParamLabels:r,onKeyify:s,templateIdentifier:a,locale:l,t:d,candidates:c,onInsertBinding:p,onRemoveBinding:f,onCommit:b,onCancel:g}){const[m,h]=u.useState(null),v=u.useRef(""),[y,_]=u.useState(!1),w=u.useRef(!1),k=u.useRef(null),x=Ft(),$=u.useRef(()=>{}),[S,C]=u.useState(null),[T,E]=u.useState(!1),A=u.useRef(n??null);u.useEffect(()=>{n&&A.current!==n&&(A.current=n)},[n]);const N=u.useMemo(()=>{if(!n&&r)return r;const P={},I=vt(typeof t.text=="string"?t.text:"");for(const L of I?.params??[])P[L.name]=Vt(L.expression);return P},[t.text,n,r]);u.useEffect(()=>{let P=!1;if(!n){const I=o??"";return v.current=I,h(I),()=>{P=!0}}return(async()=>{const I=It(n,l);if(I!==void 0){v.current=I,h(I);return}const L=await cn(a,n);if(P)return;const F=L?.values?.[l]??"";v.current=F,h(F)})(),()=>{P=!0}},[a,n,l,o]);const D=async()=>{if(w.current)return;w.current=!0;const P=m??"";if(P===v.current){b();return}_(!0);let I=A.current;if(!I){if(!s){_(!1),w.current=!1;return}if(I=await s(P),_(!1),!I){w.current=!1;return}A.current=I,b();return}const L=await So(a,I,l,P);if(_(!1),L.kind==="error"){w.current=!1;return}x?.markDirty?.(),b()},B=()=>{w.current||(w.current=!0,g())},M=P=>{C(P)},O=async P=>{if(!(S===null||!p||T)){E(!0);try{const I=A.current;I&&m!==null&&m!==v.current&&(await So(a,I,l,m),v.current=m);const L=await p(S,P);L!==null&&(h(L),v.current=L,x?.markDirty?.())}finally{E(!1),C(null)}}},z=async P=>{if(!(!f||T)){E(!0);try{const I=A.current;I&&m!==null&&m!==v.current&&(await So(a,I,l,m),v.current=m);const L=await f(P);L!==null&&(h(L),v.current=L,x?.markDirty?.())}finally{E(!1)}}},H=P=>{P.key==="Enter"&&!P.shiftKey?(P.preventDefault(),D()):P.key==="Escape"&&(P.preventDefault(),B())};return $.current=()=>{D()},u.useEffect(()=>{const P=L=>{const F=k.current;if(!F)return;const Y=L.target;if(Y&&F.contains(Y))return;const K=Y;K&&K.closest&&K.closest('[data-testid="g7le-inline-toolbar"], .g7le-inline-toolbar')||$.current()},I=k.current?.ownerDocument??document;return I.addEventListener("pointerdown",P,!0),()=>I.removeEventListener("pointerdown",P,!0)},[]),i.jsxs("div",{ref:k,className:"g7le-inline-param-chip-editor","data-testid":"g7le-inline-param-chip-editor",onKeyDown:H,style:{position:"absolute",left:e.left,top:e.top,minWidth:Math.max(e.width,120),pointerEvents:"auto",zIndex:1e4,background:"#fff",border:"2px solid #2563eb",borderRadius:4,boxShadow:"0 2px 8px rgba(37,99,235,0.25)",padding:4},children:[m===null?i.jsx("div",{"data-testid":"g7le-inline-param-chip-loading",style:{fontSize:12,color:"#94a3b8",padding:4},children:d("layout_editor.translation.loading")}):i.jsx(xr,{value:m,onChange:h,t:d,paramLabels:N,testIdSuffix:"inline",onRequestInsert:p?M:void 0,onRemoveChip:f?P=>void z(P):void 0}),S!==null&&p&&i.jsx("div",{"data-testid":"g7le-inline-param-chip-insert-picker",style:{marginTop:4},children:i.jsx($t,{candidates:c??[],t:d,onSelect:P=>void O(P),testIdSuffix:"inline-insert",defaultOpen:!0,floating:!1})}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginTop:4},children:[i.jsx("button",{type:"button","data-testid":"g7le-inline-param-chip-save",disabled:y,onMouseDown:P=>P.preventDefault(),onClick:()=>void D(),style:{fontSize:11,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",padding:"4px 12px",cursor:"pointer"},children:d(y?"layout_editor.translation.saving":"layout_editor.translation.save")}),i.jsx("span",{style:{fontSize:10,color:"#94a3b8"},children:d("layout_editor.translation.placeholder_locked")})]})]})}const z4=["fontWeight","fontBold","fontStyle","fontItalic","textDecoration","textUnderline","textAlign","fontSize","textColor"],N4={fontWeight:"B",fontBold:"B",fontStyle:"I",fontItalic:"I",textDecoration:"U",textUnderline:"U",textAlign:"≡",fontSize:"T",textColor:"A"},M4=[["fontWeight","fontBold"],["fontItalic","fontStyle"],["textUnderline","textDecoration"]];function vg({node:e,spec:t,t:n,onApplyControl:o,box:r,scope:s=Wt}){const a=typeof e.name=="string"?e.name:"",l=ji(t,a),d=Array.isArray(l?.styleControls)?l.styleControls:[];let c=z4.filter(p=>d.includes(p)&&Ct(t,p)!==null);for(const p of M4){const f=p.filter(b=>c.includes(b));if(f.length>1){const b=f[0];c=c.filter(g=>!p.includes(g)||g===b)}}return c.length===0?null:i.jsx("div",{className:"g7le-inline-toolbar","data-testid":"g7le-inline-toolbar",role:"toolbar","aria-label":n("layout_editor.inline_edit.toolbar_label"),style:{position:"absolute",left:r.left,top:r.top-40,display:"inline-flex",gap:2,padding:4,background:"#0f172a",borderRadius:8,boxShadow:"0 4px 12px rgba(15, 23, 42, 0.35)",pointerEvents:"auto",zIndex:10001},children:c.map(p=>i.jsx(P4,{controlKey:p,node:e,spec:t,t:n,scope:s,onApplyControl:o},p))})}const L4={fontWeight:"bold",fontBold:"bold",fontStyle:"italic",fontItalic:"italic",textDecoration:"underline",textUnderline:"underline"};function _g(e,t){const n=r=>(r.split(/[-\s]/).pop()??r)===t||r===t;return e.find(r=>{const s=typeof r.value=="string"?r.value:"",a=Array.isArray(r.apply?.tokens)?r.apply.tokens:[];return n(s)||a.some(n)})?.value}function P4({controlKey:e,node:t,spec:n,t:o,scope:r,onApplyControl:s}){const[a,l]=u.useState(!1),d=Ct(n,e);if(!d)return null;const c=d.options,p=Array.isArray(c),f=zo(t,d,r),b=L4[e],g=b&&Array.isArray(c)?_g(c,b):void 0,m=!b,h=g!==void 0?f.value===g:p&&f.matched&&f.value!==void 0&&f.value!=="",v=o(`layout_editor.inline_edit.format.${e}`),y=x=>typeof x.label=="string"?x.label.startsWith("$t:")?o(x.label.slice(3)):x.label:String(x.value??""),_=()=>{s(e,x=>{const $=zo(x,d,r),S=Array.isArray(c)?_g(c,b):void 0,C=S!==void 0&&$.value===S?void 0:S;return fn(x,d,C,r)})},w=x=>{s(e,$=>{const C=zo($,d,r).value===x?void 0:x;return fn($,d,C,r)}),l(!1)},k=x=>{if(x.preventDefault(),x.stopPropagation(),!m&&Array.isArray(c)){_();return}l($=>!$)};return i.jsxs("div",{style:{position:"relative",display:"inline-flex"},children:[i.jsxs("button",{type:"button","data-testid":`g7le-inline-format-${e}`,"data-active":h?"true":"false","aria-label":v,"aria-pressed":p?h:void 0,title:v,onMouseDown:x=>x.preventDefault(),onClick:k,style:{display:"inline-flex",alignItems:"center",gap:5,height:28,padding:"0 9px",fontSize:12,border:"none",borderRadius:5,cursor:"pointer",background:h?"#2563eb":"transparent",color:"#ffffff",whiteSpace:"nowrap"},children:[i.jsx("span",{"aria-hidden":"true",style:{fontWeight:e==="fontWeight"||e==="fontBold"?700:600,fontStyle:e==="fontStyle"||e==="fontItalic"?"italic":"normal",textDecoration:e==="textDecoration"||e==="textUnderline"?"underline":"none"},children:N4[e]}),i.jsx("span",{children:v}),m&&i.jsx("span",{"aria-hidden":"true",style:{fontSize:9,opacity:.8},children:"▾"})]}),m&&a&&i.jsx("div",{"data-testid":`g7le-inline-popover-${e}`,role:"listbox",onMouseDown:x=>x.preventDefault(),style:{position:"absolute",top:32,left:0,minWidth:140,maxHeight:240,overflowY:"auto",background:"#0f172a",border:"1px solid #334155",borderRadius:8,boxShadow:"0 8px 24px rgba(15,23,42,0.45)",padding:4,zIndex:10002},children:Array.isArray(c)&&c.length>0?c.map((x,$)=>{const S=f.value===x.value;return i.jsxs("button",{type:"button",role:"option","aria-selected":S,"data-testid":`g7le-inline-option-${e}-${String(x.value??$)}`,onMouseDown:C=>C.preventDefault(),onClick:C=>{C.preventDefault(),C.stopPropagation(),w(x.value)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",fontSize:12,textAlign:"left",border:"none",borderRadius:5,cursor:"pointer",background:S?"#2563eb":"transparent",color:"#ffffff"},children:[typeof x.swatch=="string"&&i.jsx("span",{"aria-hidden":"true",style:{width:14,height:14,borderRadius:3,background:x.swatch,border:"1px solid rgba(255,255,255,0.3)"}}),i.jsx("span",{children:y(x)}),S&&i.jsx("span",{"aria-hidden":"true",style:{marginLeft:"auto"},children:"✓"})]},String(x.value??$))}):i.jsx(O4,{testid:`g7le-inline-freeinput-${e}`,placeholder:o(`layout_editor.inline_edit.prompt.${e}`),initial:typeof f.value=="string"?f.value:"",onSubmit:x=>{s(e,$=>fn($,d,x,r)),l(!1)}})})]})}function O4({testid:e,placeholder:t,initial:n,onSubmit:o}){const[r,s]=u.useState(n);return i.jsx("input",{type:"text","data-testid":e,value:r,placeholder:t,autoFocus:!0,onMouseDown:a=>a.stopPropagation(),onChange:a=>s(a.currentTarget.value),onKeyDown:a=>{a.key==="Enter"&&(a.preventDefault(),o(r.trim()))},style:{width:130,padding:"6px 8px",fontSize:12,border:"1px solid #334155",borderRadius:5,background:"#1e293b",color:"#ffffff"}})}function B4(e){const{frameEl:t,manifest:n,nesting:o,componentPalette:r,spec:s=null,permissionCandidates:a,resolveRouteMatch:l,onNavigateToDestination:d,onSessionAddedPathsChange:c,onEditProps:p}=e,{state:f,dispatch:b}=Qe(),{t:g}=tt(),m=Ka(),h=u.useCallback((W,J)=>{const R=window.G7Core;if(R&&typeof R.t=="function"){const de=R.t(W,J);if(de&&de!==W&&!de.startsWith("$t:"))return de}return g(W,J)},[g]),v=Ft(),y=L7(50),_=bo(),w=u.useRef([]),k=u.useMemo(()=>v?.document?.raw?.components??[],[v?.document?.raw?.components]),x=u.useMemo(()=>k.length===0?null:{children:k},[k]),$=u.useMemo(()=>{if(f.editMode!=="extension")return;const W=/^__extension__\/(\d+)/.exec(f.selectedRoute?.path??"");return W?Number(W[1]):void 0},[f.editMode,f.selectedRoute?.path]),S=u.useMemo(()=>{if(f.editMode==="iteration_item"){const W=v?.document?.iterationContext?.sourceIndexPath;return Array.isArray(W)&&W.length>0?W:null}if(f.editMode==="modal"){const W=v?.document?.modalContext?.editIndexPath;return Array.isArray(W)&&W.length>0?W:null}return null},[f.editMode,v?.document?.iterationContext?.sourceIndexPath,v?.document?.modalContext?.editIndexPath]),C=$7({rootNode:x,editMode:f.editMode,currentExtensionId:$,editableRootPath:S,pathParser:Re,resolveRouteMatch:l}),[T,E]=u.useState(null),[A,N]=u.useState(null),[D,B]=u.useState(null),M=u.useRef(null);M.current=D;const[O,z]=u.useState(null),H=u.useRef(null),P=u.useRef(null);P.current=C.selectedPath;const I=qb(),[L,F]=u.useState(null),Y=u.useCallback(W=>{if(!t)return;const J=Re(W);if(!J)return;const R={children:ze.current.components},de=Be(R,J),ye=I.classify(de);if(!ye.editable){Et({op:"inline_edit_blocked_binding",sourceState:ye.sourceState,componentPath:at(J),timestamp:Date.now()});return}const we=fo(t,W);if(!we)return;const Te=de?.props??{},ke=wg(t,W);F({path:J,domPath:W,box:we,initialValue:ye.displayValue,isCustomKey:ye.sourceState==="custom_key",isParamKey:ye.isParamKey===!0,customKey:ye.customKey,chipValue:ye.chipValue,chipParamLabels:ye.chipParamLabels,mirrorClassName:typeof Te.className=="string"?Te.className:void 0,mirrorStyle:Te.style??void 0,nodeEffectiveColor:ke}),Et({op:"inline_edit_enter",sourceState:ye.sourceState,componentPath:at(J),timestamp:Date.now()})},[t,I]),K=u.useCallback(()=>{if(!t){E(null),N(null);return}N(fo(t,C.selectedPath)),E(fo(t,C.hoverPath))},[t,C.selectedPath,C.hoverPath,k]);u.useEffect(()=>{if(K(),typeof window<"u"&&typeof window.requestAnimationFrame=="function"){const W=window.requestAnimationFrame(()=>K());return()=>window.cancelAnimationFrame(W)}},[K]),u.useEffect(()=>{if(t)return zp(K,t)},[t,K]);const X=u.useCallback((W,J)=>{if(typeof window>"u")return;window.dispatchEvent(new CustomEvent(Ba,{detail:J===null?{requestId:W,cancelled:!0}:{requestId:W,id:J}})),B(null),z(null);const R=H.current;R?C.handleSelect("",{dataset:{editorPath:R}}):C.clearSelection(),H.current=null},[C]);u.useEffect(()=>{if(typeof window>"u")return;const W=J=>{const R=J.detail;if(typeof R?.requestId!="string")return;const de=M.current;de&&de!==R.requestId&&X(de,null),H.current=P.current,B(R.requestId)};return window.addEventListener(Wa,W),()=>window.removeEventListener(Wa,W)},[X]),u.useEffect(()=>{if(!D)return;const W=J=>{J.key==="Escape"&&(J.preventDefault(),X(D,null))};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[D,X]),u.useEffect(()=>{if(!t)return;const W=f.editMode==="iteration_item"||f.editMode==="modal",J=(_e,Ie)=>k4(_e,t,Ie?{x:Ie.clientX,y:Ie.clientY}:void 0,{handleFallback:W}),R=_e=>{const Ie=_e.dataset.editorPath??"",He=Ie?Re(Ie):null,Nt={children:ze.current.components},gt=He?Be(Nt,He):null,Mt=gt&&typeof gt.props?.id=="string"?gt.props.id:typeof gt?.id=="string"?gt.id:"";return Mt.startsWith("auto_")?"":Mt},de=_e=>{const Ie=J(_e.target,_e);if(!Ie)return;const He=M.current;if(He){_e.preventDefault(),_e.stopPropagation();const Nt=R(Ie);Nt&&X(He,Nt);return}_e.preventDefault(),_e.stopPropagation(),C.handleSelect(Ie.dataset.editorId??"",{currentTarget:Ie,dataset:Ie.dataset})},ye=_e=>{const Ie=J(_e.target,_e);if(M.current){if(!Ie){z(null);return}const He=fo(t,Ie.dataset.editorPath??null);if(!He){z(null);return}z({box:He,hasId:R(Ie)!==""});return}if(!Ie){C.handleHover(null,{});return}C.handleHover(Ie.dataset.editorId??"",{currentTarget:Ie,dataset:Ie.dataset})},we=()=>{if(M.current){z(null);return}C.handleHover(null,{})},Te=_e=>{const Ie=J(_e.target,_e);if(!Ie)return;const He=Ie.dataset.editorPath??"";He&&(_e.preventDefault(),_e.stopPropagation(),Y(He))},ke=t.parentElement??t;return ke.addEventListener("click",de,!0),ke.addEventListener("mousemove",ye,!0),ke.addEventListener("mouseleave",we,!0),ke.addEventListener("dblclick",Te,!0),()=>{ke.removeEventListener("click",de,!0),ke.removeEventListener("mousemove",ye,!0),ke.removeEventListener("mouseleave",we,!0),ke.removeEventListener("dblclick",Te,!0)}},[t,C,Y,f.editMode,X]);const Z=u.useMemo(()=>{const W=C.selectedPath;if(!W)return null;const J=W.match(/^(.*)\.children\.\d+$/);return J?J[1]:null},[C.selectedPath]),ae=u.useCallback(()=>{Z&&C.handleSelect("",{dataset:{editorPath:Z}})},[Z,C]),oe=u.useMemo(()=>!t||!C.selectedPath?null:t.querySelector(`[data-editor-path="${an(C.selectedPath)}"]`),[t,C.selectedPath]),G=u.useMemo(()=>C.selectedPath?Re(C.selectedPath):null,[C.selectedPath]),ee=u.useMemo(()=>{if(!G)return null;const W=G.find(et);if(!W)return null;const{i18nKey:J,raw:R}=SC(W.responsive);return J?g(J):g("layout_editor.overlay.branch_custom",{range:R})},[G,g]),ge=u.useMemo(()=>C.selectedPath?C.selectedIsIteration&&C.selectedIterationSourcePath?C.selectedIterationSourcePath:C.selectedPath:null,[C.selectedPath,C.selectedIsIteration,C.selectedIterationSourcePath]),V=u.useMemo(()=>ge?Re(ge):null,[ge]),te=u.useMemo(()=>!t||!ge?null:t.querySelector(`[data-editor-path="${an(ge)}"]`),[t,ge]),be=u.useMemo(()=>{if(te?.parentElement)return te.parentElement;if(!t||!ge)return null;const W=ge.match(/^(.*)\.children\.\d+$/);return W?t.querySelector(`[data-editor-path="${an(W[1])}"]`):null},[te,t,ge]),Ee=u.useMemo(()=>{const W=C.selectedNode;return W&&(typeof W.name=="string"?W.name:typeof W.type=="string"?W.type:"")||null},[C.selectedNode]),De=u.useMemo(()=>{if(C.selectedLockKind!=="extension")return null;const W=C.selectedNode?.__source;if(!W||W.kind!=="extension")return null;const J=W.extensionName?.trim(),R=W.extensionIdentifier?.trim();return J&&R?`${J} (${R})`:J||R||W.extensionSourceType||null},[C.selectedLockKind,C.selectedNode]),Se=z7({parentEl:be,selectedPath:V,selectedEl:te}),Ue=u.useMemo(()=>!t||!ge||ge===C.selectedPath?A:fo(t,ge),[t,ge,A,C.selectedPath,k]),Me=u.useRef(null),Oe=u.useCallback(()=>{const W=Me.current;W&&(_.close(W),Me.current=null)},[_]),Ye=u.useRef(()=>{}),ze=u.useRef({manifest:n,nesting:o,componentPalette:r,components:k});ze.current={manifest:n,nesting:o,componentPalette:r,components:k};const Xe=u.useCallback(W=>{const J=W.insertion?.parentPath??[],R=W.insertion?.index??0,de=ze.current,ye=xg(de.components,J);Oe();const we=_.open({ariaLabel:h("layout_editor.palette.title"),width:880,maxHeightRatio:.82,content:u.createElement(Nf,{manifest:de.manifest,nesting:de.nesting,componentPalette:de.componentPalette??null,targetParentPath:J,targetContainerName:ye,onInsert:(Te,ke,_e)=>{Ye.current(Te,ke,_e)},insertionIndex:R,onClose:()=>Oe(),editorTemplateId:f.templateIdentifier,editorLocale:f.locale}),onClose:()=>{Me.current=null}});Me.current=we},[_,Oe]),ve=u.useMemo(()=>{if(!f.isPaletteOpen)return null;if(!G)return{parentPath:[],index:k.length};if(C.selectedLockKind!=="none"){const de=V;return!de||de.length===0?{parentPath:[],index:k.length}:{parentPath:de.slice(0,-1),index:(de[de.length-1]??0)+1}}const J=C.selectedNode,R=Array.isArray(J?.children)?J.children.length:0;return MI(J?.name,R,G,o,k.length)},[f.isPaletteOpen,G,V,C.selectedLockKind,C.selectedNode,k.length,o]),qe=u.useCallback(()=>{b({type:"SET_PALETTE_OPEN",open:!1})},[b]),We=u.useRef(null);u.useEffect(()=>{if(!f.isPaletteOpen){const ye=We.current;ye&&(_.close(ye),We.current=null);return}if(!ve||We.current)return;const W=ve,J=ze.current,R=xg(J.components,W.parentPath),de=_.open({ariaLabel:h("layout_editor.palette.title"),width:880,maxHeightRatio:.82,content:u.createElement(Nf,{manifest:J.manifest,nesting:J.nesting,componentPalette:J.componentPalette??null,targetParentPath:W.parentPath,targetContainerName:R,onInsert:(ye,we,Te)=>{Ye.current(ye,we,Te),qe()},insertionIndex:W.index,onClose:()=>qe(),editorTemplateId:f.templateIdentifier,editorLocale:f.locale}),onClose:()=>{We.current=null,b({type:"SET_PALETTE_OPEN",open:!1})}});We.current=de},[f.isPaletteOpen,ve,_,qe,b]);const ce=u.useRef({layoutName:null,pushed:!1});u.useEffect(()=>{const W=v?.document?.layoutName??null;if(!W){ce.current={layoutName:null,pushed:!1};return}ce.current.layoutName!==W&&(y.clear(),y.push({actionKind:"inline_text_edit",label:"baseline",snapshot:k}),ce.current={layoutName:W,pushed:!0})},[v?.document?.layoutName,k,y]);const q=u.useRef(0);u.useEffect(()=>{const W=v?.saveSuccessCounter??0;W!==q.current&&(q.current=W,W!==0&&(y.clear(),y.push({actionKind:"inline_text_edit",label:"save_baseline",snapshot:k}),w.current=[],c?.([])))},[v?.saveSuccessCounter,k,y,c]);const ie=u.useRef(0);u.useEffect(()=>{const W=v?.reloadCounter??0;W!==ie.current&&(ie.current=W,W!==0&&(ce.current={layoutName:null,pushed:!1},w.current=[],c?.([])))},[v?.reloadCounter,c]);const se=u.useCallback((W,J,R)=>{if(!v)return;let de=[];v.patchLayout(ke=>{const _e={children:ke},Ie=Va(_e,J),He=R<0?Array.isArray(Ie?.children)?Ie.children.length:0:R,gt=ts(_e,J,He,W).children??[];return de=gt,gt}),y.push({actionKind:"insert",label:`insert ${W.name??W.type??""}`,snapshot:de});const ye=Va({children:de},J),we=R<0?Array.isArray(ye?.children)?ye.children.length-1:0:R,Te=at([...J,we]);if(w.current=[...w.current,Te],c?.(w.current),t){const ke=`[data-editor-path="${an(Te)}"]`,_e=()=>{const Ie=t.querySelector(ke);Ie&&typeof Ie.scrollIntoView=="function"&&Ie.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"})};typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(()=>window.requestAnimationFrame(_e)):setTimeout(_e,32)}},[v,y,c,t]);Ye.current=se;const me=u.useCallback(()=>{if(!v||!C.selectedNode||!G)return;const W=os(C.selectedNode);let J=[];v.patchLayout(R=>{const de={children:R},ye=G.slice(0,-1),we=G[G.length-1]??0,ke=ts(de,ye,we+1,W).children??[];return J=ke,ke}),y.push({actionKind:"insert",label:"duplicate",snapshot:J})},[v,C.selectedNode,G,y]),Ce=u.useCallback(()=>{if(!v||!G)return;let W=[];v.patchLayout(J=>{const ye=ns({children:J},G).children??[];return W=ye,ye}),y.push({actionKind:"remove",label:"remove",snapshot:W}),C.clearSelection()},[v,G,y,C]),$e=u.useMemo(()=>{if(!C.selectedNode||!G||G.some(et))return null;const W=C.selectedNode;if(!Array.isArray(W.children))return null;const J=kC(f.previewDevice,W,f.previewCustomWidth);return{mode:J.mode,key:J.key,sourceKey:J.sourceKey}},[C.selectedNode,G,f.previewDevice,f.previewCustomWidth]),U=u.useCallback(()=>{if(!v||!G||$e?.mode!=="separate")return;const W=$e.key,J=$e.sourceKey;let R=[];v.patchLayout(de=>(R=Pb({children:de},G,W,J).children??[],R)),y.push({actionKind:"insert",label:"separate_branch",snapshot:R})},[v,G,$e,y]),ue=u.useCallback(()=>{if(!v||!G||$e?.mode!=="merge")return;const W=$e.key;let J=[];v.patchLayout(R=>(J=Ob({children:R},G,W).children??[],J)),y.push({actionKind:"remove",label:"merge_branch",snapshot:J})},[v,G,$e,y]),fe=u.useCallback(W=>{switch(W){case"mobile":return g("layout_editor.context_menu.device_mobile");case"portable":return g("layout_editor.context_menu.device_portable");case"tablet":return g("layout_editor.context_menu.device_tablet");case"desktop":return g("layout_editor.context_menu.device_desktop");default:return g("layout_editor.context_menu.device_custom",{range:W})}},[g]),xe=u.useMemo(()=>{if(!$e)return null;const W=fe($e.key);return{separate:g("layout_editor.context_menu.separate_branch_device",{device:W}),merge:g("layout_editor.context_menu.merge_branch_device",{device:W})}},[$e,g,fe]),he=u.useMemo(()=>{if(!C.selectedNode||!G)return[];if(G.some(et))return[];const W=Yr(f.previewDevice,C.selectedNode,f.previewCustomWidth);return vT(C.selectedNode,W).map(J=>({key:J,label:fe(J)}))},[C.selectedNode,G,f.previewDevice,f.previewCustomWidth,fe]),j=u.useCallback(W=>{if(W==="desktop"||W==="tablet"||W==="mobile"||W==="portable"){m.setDevice(W);return}m.setDevice(W)},[m]),ne=u.useCallback(()=>{C.selectedNode&&hg(C.selectedNode)},[C.selectedNode]),pe=u.useCallback(()=>{C.selectedNode&&(hg(C.selectedNode),Ce())},[C.selectedNode,Ce]),Q=u.useCallback(()=>{if(!v)return;const W=y4();if(!W)return;const J=os(W);if(G&&G.length>0){const R=G.slice(0,-1),de=(G[G.length-1]??0)+1;se(J,R,de)}else se(J,[],k.length)},[v,G,se,k.length]),le=u.useCallback((W,J)=>{y.push({actionKind:"move",label:J,snapshot:W})},[y]),Ae=u.useCallback(()=>{if(C.selectedNavAffordance==="route_in_tree"&&C.selectedNavTargetPath){if(d){d(C.selectedNavTargetPath);return}b({type:"SELECT_ROUTE",route:{path:C.selectedNavTargetPath,layoutName:null}})}},[C.selectedNavAffordance,C.selectedNavTargetPath,d,b]),dt=u.useCallback(()=>{const W=Mb(C.selectedBaseLayout,f.selectedRoute?.layoutName);W&&b({type:"ENTER_BASE_EDIT",layoutName:W})},[C.selectedBaseLayout,f.selectedRoute?.layoutName,b]),pt=u.useCallback(()=>{const W=C.selectedNode?.__source?.extensionId;W!=null&&b({type:"ENTER_EXTENSION_EDIT",extensionId:String(W)})},[C.selectedNode,b]),ot=u.useCallback(()=>{const W=C.selectedIterationSourcePath;W&&b({type:"ENTER_ITERATION_ITEM_EDIT",sourcePath:W})},[C.selectedIterationSourcePath,b]),Le=u.useRef(null),je=u.useRef(null),Je=u.useRef(null),Tt=u.useRef({colorScheme:"base",breakpoint:"base"}),Dt=Le.current!==null?_.stack.some(W=>W.id===Le.current):!1,zt=u.useMemo(()=>Od(f.routeTree,h),[f.routeTree,h]),xn=u.useMemo(()=>Bd(v?.document?.raw),[v?.document?.raw]),wn=u.useMemo(()=>Wd(s),[s?.states]),Zt=u.useMemo(()=>{const W=v?.document?.raw,J=Lf(W?.components),R=W?.initIsolated,de=R&&typeof R=="object"&&!Array.isArray(R)?Object.keys(R):[];return $A(J,de)},[v?.document?.raw]),Hn=u.useMemo(()=>{const W=v?.document?.raw;return Lf(W?.components).map(J=>J.scopeId).filter(J=>typeof J=="string"&&J.length>0)},[v?.document?.raw]),ln=Pd({raw:v?.document?.raw,spec:s}),Di=u.useCallback((W,J)=>{if(!v)return;const R={children:ze.current.components},de=Be(R,W);if(!de)return;Tt.current={colorScheme:f.previewColorScheme==="dark"?"dark":"base",breakpoint:Yr(f.previewDevice,de,f.previewCustomWidth)};const ye=t?.getBoundingClientRect(),we=A&&ye?{left:ye.left+A.left,top:ye.top+A.top,width:A.width,height:A.height}:void 0,Te=oe,ke=W.find(et),_e=ke?fe(ke.responsive):null,Ie=W.filter(kn=>typeof kn=="number"),He=bb({children:ze.current.components},Ie,mb(ln)),Nt=He.length>0?[...Ki({iterationVars:He}),...ln]:ln,gt=(kn,PM)=>u.createElement(RT,{key:`pem-${at(je.current??[])}`,node:kn,spec:s,manifest:ze.current.manifest,t:h,permissionCandidates:a,pageCandidates:zt,dataSourceCandidates:xn,stateKeyCandidates:wn,bindingCandidates:Nt,liveElement:Te,templateIdentifier:f.templateIdentifier,initialTab:PM,branchLabel:_e,isolatedScopeIdCandidates:Zt,usedScopeIds:Hn,onSaveInjectedProps:async(mt,Sn)=>{const zi=typeof kn.id=="string"?kn.id:"",Fn=await f4(f.templateIdentifier,mt,zi,Sn);if(st({op:"save",layoutName:`extension:${mt}`,editMode:f.editMode,saveTarget:"layout_extension",endpoint:`/api/admin/templates/${f.templateIdentifier}/layout-extensions/${mt}`,isDirty:!0,timestamp:Date.now()}),Fn.kind!=="success")throw new Error(Fn.kind==="conflict"?h("layout_editor.save.conflict"):Fn.kind==="injection_not_found"?"injection not found":Fn.kind==="not_found"?"extension not found":Fn.message??"save failed")},scope:Tt.current,onScopeChange:mt=>{Tt.current=mt;const Sn=Le.current;Sn&&_.open({id:Sn,ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(kn),onClose:()=>{Le.current=null,je.current=null}})},onPatchNode:mt=>{let Sn=[];v.patchLayout(Fn=>(Sn=Ot({children:Fn},W,()=>mt).children??[],Sn)),y.push({actionKind:"inline_text_edit",label:"edit_props",snapshot:Sn}),dr({source:"style_control",componentPath:at(W),componentName:typeof mt.name=="string"?mt.name:null,patchKey:null,timestamp:Date.now()});const zi=Le.current;zi&&_.open({id:zi,ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(mt),onClose:()=>{Le.current=null,je.current=null}})},onDelete:()=>{const mt=Le.current;mt&&_.close(mt),Ce()},onClose:()=>{const mt=Le.current;mt&&_.close(mt)}});je.current=W;const Mt=_.open({ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(de,J),onClose:()=>{Le.current=null,je.current=null,Je.current=null}});Le.current=Mt,Je.current=kn=>{_.open({id:Mt,ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(kn),onClose:()=>{Le.current=null,je.current=null,Je.current=null}})}},[v,s,h,a,zt,xn,wn,ln,oe,y,_,Ce,t,A,f.previewColorScheme,f.previewDevice,f.previewCustomWidth,fe]);u.useEffect(()=>{const W=Je.current,J=je.current;if(!W||!J)return;const R={children:ze.current.components},de=Be(R,J);de?W(de):Le.current&&_.close(Le.current)},[k]);const vM=()=>{if(!Dt)return null;const J={position:"absolute",background:"rgba(15, 23, 42, 0.45)",pointerEvents:"auto",zIndex:W7},R=ke=>{ke.preventDefault(),ke.stopPropagation()};if(!A)return i.jsx("div",{"data-testid":"g7le-edit-lock-full",onClick:R,onMouseMove:R,style:{...J,inset:0}});const{left:de,top:ye,width:we,height:Te}=A;return i.jsxs("div",{"data-testid":"g7le-edit-lock",style:{position:"absolute",inset:0,pointerEvents:"none"},children:[i.jsx("div",{"data-testid":"g7le-edit-lock-top",onClick:R,onMouseMove:R,style:{...J,left:0,top:0,right:0,height:Math.max(0,ye)}}),i.jsx("div",{"data-testid":"g7le-edit-lock-bottom",onClick:R,onMouseMove:R,style:{...J,left:0,top:ye+Te,right:0,bottom:0}}),i.jsx("div",{"data-testid":"g7le-edit-lock-left",onClick:R,onMouseMove:R,style:{...J,left:0,top:ye,width:Math.max(0,de),height:Te}}),i.jsx("div",{"data-testid":"g7le-edit-lock-right",onClick:R,onMouseMove:R,style:{...J,left:de+we,top:ye,right:0,height:Te}})]})},wl=u.useCallback(()=>{if(G&&$p(C.selectedLockKind)){if(p&&C.selectedPath){p(C.selectedPath);return}Di(G)}},[G,C.selectedPath,C.selectedLockKind,p,Di]),{scale:kl}=m,Sl=typeof C.selectedNode?.name=="string"?C.selectedNode.name:"",Uh=s?.componentCapabilities?.[Sl]??null,qh=Array.isArray(Uh?.styleControls)?Uh.styleControls:[],_M=qh.includes("width")?Ct(s,"width"):null,xM=qh.includes("height")?Ct(s,"height"):null,wM=u.useCallback((W,J)=>{if(!v||!G)return;let R=[];v.patchLayout(de=>(R=Ot({children:de},G,()=>W).children??[],R)),dr({source:"resize",componentPath:at(G),componentName:Sl||null,patchKey:J==="height"?"height":"width",resizeAxis:J,timestamp:Date.now()})},[v,G,Sl]),kM=u.useCallback((W,J)=>{if(!v||!G)return;let R=[];v.patchLayout(de=>(R=Ot({children:de},G,()=>W).children??[],R)),y.push({actionKind:"inline_text_edit",label:`resize ${J}`,snapshot:R})},[v,G,y]),SM=u.useCallback(()=>{if(!oe)return null;const W=oe.getBoundingClientRect(),J=kl||1;return{width:W.width/J,height:W.height/J}},[oe,kl]),lr=v4({node:C.selectedNode,widthControl:_M,heightControl:xM,scale:kl,measureStartSize:SM,onResize:wM,onResizeEnd:kM}),CM=u.useCallback((W,J)=>{lr.onHandlePointerDown(W,J)},[lr]),Cl=u.useCallback(()=>{const W=y.undo();!W||!v||v.setLayoutComponents(W.snapshot)},[y,v]),$l=u.useCallback(()=>{const W=y.redo();!W||!v||v.setLayoutComponents(W.snapshot)},[y,v]);O7({onUndo:Cl,onRedo:$l});const $M=u.useMemo(()=>({copy:ne,cut:pe,paste:Q,delete:Ce,openProps:wl,selectParent:Z?ae:void 0,deselect:C.clearSelection}),[ne,pe,Q,Ce,wl,Z,ae,C.clearSelection]);lp({handlers:$M,hasSelection:!!C.selectedPath}),u.useEffect(()=>(window.__g7LayoutEditorHasSelection=!!C.selectedPath,()=>{try{delete window.__g7LayoutEditorHasSelection}catch{}}),[C.selectedPath]),u.useEffect(()=>(window.__g7LayoutEditorHistory={undo:Cl,redo:$l,canUndo:y.canUndo,canRedo:y.canRedo},()=>{try{delete window.__g7LayoutEditorHistory}catch{}}),[Cl,$l,y.canUndo,y.canRedo]);const EM=u.useCallback(W=>{const J=L;F(null),J&&(async()=>{if((await I.commit(J.path,W)).kind==="created"&&v){const de=v.document?.raw?.components??[];y.push({actionKind:"inline_text_edit",label:"inline_create_key",snapshot:de})}})()},[L,I,v,y]),Gh=u.useCallback(()=>{const W=L;F(null),I.trackCancel(W?.path??null)},[L,I]),IM=u.useCallback(()=>{F(null)},[]),AM=u.useCallback(async W=>{const J=L;if(!J)return null;const R=await I.keyifyChipValue(J.path,W);if(R.kind!=="created"||!R.translationKey)return null;const de=v?.document?.raw?.components??[];return y.push({actionKind:"inline_text_edit",label:"inline_keyify_chip",snapshot:de}),R.translationKey},[L,I,v,y]),TM=u.useCallback(()=>{const W=L;W&&(F(null),C.handleSelect("",{dataset:{editorPath:W.domPath}}),Di(W.path,"translation"))},[L,C,Di]),wt=u.useMemo(()=>{if(!L)return null;const W=v?.document?.raw?.components??k;return Be({children:W},L.path)},[L,v?.document,k]),DM=u.useCallback(async(W,J)=>{const R=L;if(!v||!R)return null;const de=typeof wt?.text=="string"?wt.text:"";let ye;if(R.isParamKey)ye=await Cr(f.templateIdentifier,f.locale,de,W,J.sourceId,J.path,"scalar");else{const He=Nt=>Nt.replace(/\$t:[a-zA-Z0-9._-]+/g,gt=>{const Mt=h(gt.slice(3));return Mt&&Mt!==gt.slice(3)&&!Mt.startsWith("$t:")?Mt:""}).replace(/\s+/g," ").trim();ye=await us(f.templateIdentifier,f.selectedRoute?.layoutName??null,f.locale,de,W,J.sourceId,J.path,"scalar",He,h)}if(ye.kind==="error")return null;const we=R.path;let Te=[];v.patchLayout(He=>(Te=Ot({children:He},we,Mt=>({...Mt,text:ye.text})).children??[],Te)),y.push({actionKind:"inline_text_edit",label:"inline_insert_binding",snapshot:Te});const ke=ye.kind==="ok"&&"key"in ye?ye.key:void 0;!R.isParamKey&&ke&&F(He=>He&&He.path===we?{...He,isParamKey:!0,customKey:ke,chipValue:void 0,chipParamLabels:void 0}:He);try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:f.templateIdentifier,locale:f.locale}}))}catch{}const _e=vt(ye.text),Ie=R.customKey??_e?.key??"";return Ie?It(Ie,f.locale)??null:null},[v,L,wt,f.templateIdentifier,f.locale,f.selectedRoute,y,h]),zM=u.useCallback(async W=>{const J=L;if(!v||!J)return null;const R=typeof wt?.text=="string"?wt.text:"",de=vt(R),ye=J.customKey??de?.key??null,we=vo(R,W),Te=J.path;let ke=[];return v.patchLayout(_e=>(ke=Ot({children:_e},Te,Nt=>({...Nt,text:we})).children??[],ke)),y.push({actionKind:"inline_text_edit",label:"inline_remove_binding",snapshot:ke}),ye&&await $r(f.templateIdentifier,ye,W,f.locale),ye?It(ye,f.locale)??null:null},[v,L,wt,f.templateIdentifier,f.locale,y]),[El,Yh]=u.useState({}),NM=["fontSize","color","fontStyle","textDecoration","textAlign","letterSpacing","lineHeight","fontFamily"];u.useEffect(()=>{if(!L||!t||typeof MutationObserver>"u"){Yh({});return}const W=`[data-editor-path="${an(L.domPath)}"]`,J=()=>{const ye=t.querySelector(W);if(!ye)return;const we={};for(const ke of NM){const _e=ye.style.getPropertyValue(ke.replace(/([A-Z])/g,"-$1").toLowerCase());_e&&(we[ke]=_e)}const Te=wg(t,L.domPath)??void 0;Yh({className:ye.className,style:we,effectiveColor:Te})};J();const R=t.querySelector(W);if(!R)return;const de=new MutationObserver(J);return de.observe(R,{attributes:!0,attributeFilter:["class","style"]}),de.observe(t,{childList:!0,subtree:!0}),()=>de.disconnect()},[L?.path?at(L.path):null,t]);const Xh=u.useCallback((W,J)=>{if(!v||!L)return;const R=L.path;let de=[],ye=null;v.patchLayout(we=>(de=Ot({children:we},R,_e=>{const Ie=J(_e);return ye=typeof Ie.name=="string"?Ie.name:null,Ie}).children??[],de)),y.push({actionKind:"inline_text_edit",label:`inline_format ${W}`,snapshot:de}),dr({source:"style_control",componentPath:at(R),componentName:ye,patchKey:W,timestamp:Date.now()})},[v,L,y]),ft=u.useMemo(()=>{const W=C.selectedPath;if(!W||!x)return null;const J=[];let R=W;for(;R;){J.push(R);const de=R.match(/^(.*)\.children\.\d+$/);R=de?de[1]:null}for(const de of J){const ye=Re(de);if(!ye)continue;const we=Be(x,ye),Te=typeof we?.name=="string"?we.name:null;if(!Te)continue;const ke=ji(s,Te),_e=ke?.canvasOverlay?.kind;if(typeof _e!="string"||!_e||!we)continue;const Ie=ke.canvasOverlay.params&&typeof ke.canvasOverlay.params=="object"?ke.canvasOverlay.params:void 0,He=de===W?null:W.slice(de.length+1);return{kind:_e,params:Ie,tablePath:de,tableNode:we,selectedCellRel:He}}return null},[C.selectedPath,x,s]),yo=ft?g4(ft.kind):null,Jh=u.useMemo(()=>!yo||!t||!ft?null:fo(t,ft.tablePath),[yo,t,ft,A,k]),MM=u.useMemo(()=>{if(!yo||!t||!ft)return[];const W=ft.tablePath,J=an(W),R=[];return t.querySelectorAll(`[data-editor-path^="${J}.children."]`).forEach(we=>{const Te=we.dataset.editorPath??"";if(!Te.startsWith(W+"."))return;const ke=Te.slice(W.length+1),_e=ao(we,t);_e&&R.push({path:ke,top:_e.top,left:_e.left,width:_e.width,height:_e.height})}),t.querySelectorAll(`[data-editor-item-path^="${J}."]`).forEach(we=>{const Te=we.dataset.editorItemPath??"";if(!Te.startsWith(W+"."))return;const ke=Te.slice(W.length+1),_e=ao(we,t);_e&&R.push({path:ke,top:_e.top,left:_e.left,width:_e.width,height:_e.height})}),R},[yo,t,ft,A,k]),LM=u.useCallback(W=>{const J=ft?Re(ft.tablePath):null;if(!v||!J)return;let R=[];v.patchLayout(de=>(R=Ot({children:de},J,()=>W).children??[],R)),y.push({actionKind:"inline_text_edit",label:"inplace_edit",snapshot:R}),dr({source:"style_control",componentPath:ft?.tablePath??"",componentName:typeof W.name=="string"?W.name:null,patchKey:"canvas_inplace",timestamp:Date.now()})},[v,G,y]);return t?i.jsxs("div",{className:"g7le-editor-canvas-overlay","data-testid":"g7le-editor-canvas-overlay",style:{position:"absolute",inset:0,pointerEvents:"none"},children:[!D&&vM(),D&&i.jsxs("div",{"data-testid":"g7le-canvas-pick-banner",style:{position:"absolute",top:8,left:"50%",transform:"translateX(-50%)",zIndex:9999,display:"flex",alignItems:"center",gap:12,padding:"8px 14px",background:"#1e293b",color:"#fff",borderRadius:8,fontSize:13,boxShadow:"0 4px 12px rgba(0,0,0,0.25)",pointerEvents:"auto"},children:[i.jsxs("span",{children:["🎯 ",h("layout_editor.target_picker.canvas_pick_hint")]}),i.jsx("button",{type:"button","data-testid":"g7le-canvas-pick-cancel",onClick:()=>X(D,null),style:{border:"1px solid #475569",borderRadius:6,background:"transparent",color:"#cbd5e1",cursor:"pointer",fontSize:12,padding:"3px 10px"},children:h("layout_editor.target_picker.cancel")})]}),f.editMode!=="route"&&i.jsx(RI,{frameEl:t,components:k,editMode:f.editMode,currentExtensionId:$,editableRootPath:S}),L&&((L.isParamKey&&L.customKey||L.chipValue)&&wt?i.jsxs(i.Fragment,{children:[wt&&i.jsx(vg,{node:wt,spec:s,t:h,onApplyControl:Xh,box:L.box,scope:{colorScheme:f.previewColorScheme==="dark"?"dark":"base",breakpoint:Yr(f.previewDevice,wt,f.previewCustomWidth)}}),i.jsx(D4,{box:L.box,node:wt,customKey:L.customKey??null,initialChipValue:L.chipValue,chipParamLabels:L.chipParamLabels,onKeyify:AM,templateIdentifier:f.templateIdentifier,locale:f.locale,t:h,candidates:ln,onInsertBinding:DM,onRemoveBinding:zM,onCommit:IM,onCancel:Gh})]}):i.jsxs(i.Fragment,{children:[wt&&i.jsx(vg,{node:wt,spec:s,t:h,onApplyControl:Xh,box:L.box,scope:{colorScheme:f.previewColorScheme==="dark"?"dark":"base",breakpoint:wt?Yr(f.previewDevice,wt,f.previewCustomWidth):"base"}}),i.jsx(T4,{box:L.box,initialValue:L.initialValue,isCustomKey:L.isCustomKey,t:h,onCommit:EM,onCancel:Gh,mirrorClassName:El.className,mirrorStyle:El.style,nodeEffectiveColor:El.effectiveColor??L.nodeEffectiveColor,onOpenTranslations:TM})]})),!D&&i.jsx(U7,{hoverBox:T,selectedBox:A,lockKind:C.selectedLockKind,navAffordance:C.selectedNavAffordance,onEditProps:wl,onDuplicate:me,onDelete:Ce,onSeparateBranch:$e?.mode==="separate"?U:void 0,separateBranchLabel:xe?.separate,onMergeBranch:$e?.mode==="merge"?ue:void 0,mergeBranchLabel:xe?.merge,definedDeviceBranches:he,onJumpToDevice:he.length>0?j:void 0,onLinkEditDestination:Ae,onEditBase:dt,onEditExtension:pt,extensionLabel:De,baseLayoutLabel:C.selectedBaseLayout,dataSourceLabel:C.selectedDataSourceId,branchLabel:ee,onEditIteration:C.selectedIsIteration&&f.editMode!=="iteration_item"?ot:void 0,resizeEnabledAxes:lr.enabledAxes,onResizeHandlePointerDown:lr.enabledAxes.width||lr.enabledAxes.height?CM:void 0,selectedName:Ee,onSelectParent:Z?ae:void 0}),D&&O&&i.jsx("div",{"data-testid":"g7le-canvas-pick-hover","data-pick-has-id":O.hasId?"true":"false",style:{position:"absolute",left:O.box.left,top:O.box.top,width:O.box.width,height:O.box.height,pointerEvents:"none",zIndex:9998,boxSizing:"border-box",border:O.hasId?"2px solid #2563eb":"2px dashed #94a3b8",background:O.hasId?"rgba(37,99,235,0.10)":"repeating-linear-gradient(45deg, rgba(148,163,184,0.18) 0, rgba(148,163,184,0.18) 6px, transparent 6px, transparent 12px)",cursor:O.hasId?"pointer":"not-allowed"},children:!O.hasId&&i.jsx("span",{"data-testid":"g7le-canvas-pick-hover-hint",style:{position:"absolute",top:0,left:0,transform:"translateY(-100%)",background:"#475569",color:"#fff",fontSize:11,lineHeight:1.4,padding:"2px 6px",borderRadius:4,whiteSpace:"nowrap"},children:h("layout_editor.target_picker.needs_id")})}),!D&&i.jsx(Z7,{selectedBox:Ue,points:Se.points,onAddRequest:Xe}),yo&&ft&&Jh&&C.selectedLockKind==="none"&&i.jsx(yo,{node:ft.tableNode,params:ft.params,nodeBox:Jh,cellBoxes:MM,selectedCellPath:ft.selectedCellRel??void 0,colorScheme:f.previewColorScheme==="dark"?"dark":"light",t:h,onPatchNode:LM,onInsertChild:se,onRemoveChild:W=>{const J=Re(W);if(!v||!J)return;let R=[];v.patchLayout(de=>(R=ns({children:de},J).children??[],R)),y.push({actionKind:"remove",label:"inplace_remove",snapshot:R})},onRequestInlineEdit:W=>{ft&&Y(`${ft.tablePath}.${W}`)}}),v&&i.jsx(GI,{frameEl:t,nesting:o,editMode:f.editMode,currentExtensionId:$,editableRootPath:S,components:k,patchLayout:v.patchLayout,pushHistory:le,selectedPath:C.selectedPath,onSelectPath:W=>C.handleSelect("",{dataset:{editorPath:W}}),onMovePath:W=>C.handleSelect("",{dataset:{editorPath:W}}),onRequestInlineEdit:Y})]}):null}function xg(e,t){if(t.length===0)return null;const o=Va({children:e},t);return o&&typeof o.name=="string"?o.name:null}function Va(e,t){return Be(e,t)}function an(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/[^a-zA-Z0-9_\-.]/g,t=>`\\${t}`)}function wg(e,t){if(!t)return null;const n=e.querySelector(`[data-editor-path="${an(t)}"]`);if(!n||typeof window.getComputedStyle!="function")return null;let o=n;const r=n.ownerDocument.createTreeWalker(n,NodeFilter.SHOW_TEXT);let s=r.nextNode();for(;s;){if((s.textContent??"").trim().length>0){const a=s.parentElement;if(a&&n.contains(a)){o=a;break}}s=r.nextNode()}try{return window.getComputedStyle(o).color||null}catch{return null}}function fo(e,t){if(!t)return null;const n=e.querySelector(`[data-editor-path="${an(t)}"]`);if(n){const c=ao(n,e);return c&&lo(c,e)?c:null}const o=e.querySelectorAll(`[data-editor-path^="${an(t)}.iteration."]`);let r=1/0,s=1/0,a=-1/0,l=-1/0,d=!1;return o.forEach(c=>{const p=c.dataset.editorPath??"";if(!new RegExp("\\.iteration\\.\\d+$").test(p))return;const f=ao(c,e);f&&lo(f,e)&&(d=!0,r=Math.min(r,f.left),s=Math.min(s,f.top),a=Math.max(a,f.left+f.width),l=Math.max(l,f.top+f.height))}),d?{left:r,top:s,width:a-r,height:l-s,scale:1}:null}function W4({isEditMode:e,editorSpec:t,sampleOverride:n}){const o=t?.sampleData;return u.useMemo(()=>Km({spec:o,overrideSpec:n,onMatch:r=>{Qh(r)}}),[e,o,n])}const j4=Lt().ComponentRegistry;function H4(e){return e.replace(/[\t\n\r]/g,"").replace(/\\/g,"/").replace(/^([a-z][a-z0-9+.\-]*:)?\/{2,}/i,"$1//")}function F4(e,t){try{const n=typeof window<"u"&&window.location?.protocol||"https:",o=t||(typeof window<"u"?window.location?.origin:void 0)||"https://localhost",r=e.startsWith("//")?`${n}${e}`:e,s=new URL(r,o);return s.protocol!=="http:"&&s.protocol!=="https:"?null:s.hostname.toLowerCase()}catch{return null}}function Ua(){const e=typeof window<"u"?window.G7Config?.trustedScriptHosts:void 0;return Array.isArray(e)?e.map(t=>String(t).toLowerCase()):[]}function kg(e,t){if(typeof e!="string")return!1;const n=e.trim();if(n==="")return!1;const o=H4(n),r=o.startsWith("//"),s=/^[a-z][a-z0-9+.-]*:/i.test(o);if(!r&&!s&&o.startsWith("/"))return!0;const a=F4(o),l=t??Ua();return a!==null&&l.map(d=>String(d).toLowerCase()).includes(a)}function K4(e){return e.split(/[-_]/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}async function V4(e){const t=typeof window<"u"?window.localStorage?.getItem("auth_token"):null,n={Accept:"application/json"};t&&(n.Authorization=`Bearer ${t}`);const o=await fetch(`/api/admin/templates/${encodeURIComponent(e)}/editor-assets`,{headers:n,credentials:"same-origin"});if(!o.ok){const s=await o.json().catch(()=>null);throw Jr(o.status,s,"assets")}const r=await o.json();return r.data||r}async function U4(e){try{if(typeof fetch!="function")return 0;const t=await fetch(en(`/api/templates/${encodeURIComponent(e)}/config`,"json"),{credentials:"same-origin",headers:{Accept:"application/json"}});if(!t.ok)return 0;const n=await t.json().catch(()=>null),o=n?.data?.cache_version??n?.cache_version;return typeof o=="number"&&o>0?o:0}catch{return 0}}function q4(e){return new Promise((t,n)=>{if(typeof document>"u"){n(new Error("document undefined"));return}if(!kg(e,Ua())){n(new Error(`Blocked untrusted script src (same-origin path or declared trusted host required): ${e}`));return}if(document.querySelector(`script[data-g7le-asset="${e}"]`)){t();return}const r=document.createElement("script");r.src=e,r.async=!1,r.setAttribute("data-g7le-asset",e),r.addEventListener("load",()=>t()),r.addEventListener("error",()=>n(new Error(`script load failed: ${e}`))),document.head.appendChild(r)})}async function G4(e){if(typeof document>"u")return;const t=`[data-g7le-asset="${e}"]`;if(document.querySelector(`link${t}, style${t}`))return;if(e.includes("/api/admin/"))try{const r=typeof window<"u"?window.localStorage?.getItem("auth_token"):null,s={Accept:"text/css"};r&&(s.Authorization=`Bearer ${r}`);const a=await fetch(e,{headers:s,credentials:"same-origin"});if(a.ok){const l=await a.text(),d=document.createElement("style");d.textContent=l,d.setAttribute("data-g7le-asset",e),document.head.appendChild(d);return}}catch{}const o=document.createElement("link");o.rel="stylesheet",o.href=e,o.setAttribute("data-g7le-asset",e),document.head.appendChild(o)}function Y4(e,t,n="user"){const[o,r]=u.useState({componentRegistry:null,translationEngine:null,isReady:!1,error:null});return u.useEffect(()=>{let s=!1;return(async()=>{r(a=>({...a,isReady:!1,error:null}));try{const a=await V4(e);if(s)return;for(const b of a.css??[])if(await G4(b),s)return;const l=K4(e);if(!(typeof window<"u"&&typeof window[l]=="object")){for(const b of a.js??[])if(await q4(b),s)return}const c=j4.createIsolatedInstance();if(await c.loadComponents(e,n),s)return;const p=await U4(e);if(s)return;const f=new Pt({defaultLocale:t});if(p>0&&f.setCacheVersion(p),await f.loadTranslations(e,t),s)return;gd(f,e);try{const b=Pt.getInstance();p>b.getCacheVersion()&&b.setCacheVersion(p),await b.loadTranslations(e,t),gd(b,e)}catch{}if(s)return;r({componentRegistry:c,translationEngine:f,isReady:!0,error:null})}catch(a){if(s)return;const l=xp(a)?a:so(a,"assets");r({componentRegistry:null,translationEngine:null,isReady:!1,error:l})}})(),()=>{s=!0}},[e,t,n]),o}const Sg=Lt().AuthManager;function X4(e){switch(e){case"unauthorized":return{icon:"🔒",tone:"blue",titleKey:"layout_editor.access_error.unauthorized.title",messageKey:"layout_editor.access_error.unauthorized.message",showRequiredPermissions:!0};case"forbidden":return{icon:"⛔",tone:"rose",titleKey:"layout_editor.access_error.forbidden.title",messageKey:"layout_editor.access_error.forbidden.message",showRequiredPermissions:!0};case"not_found":return{icon:"🗂️",tone:"slate",titleKey:"layout_editor.access_error.not_found.title",messageKey:"layout_editor.access_error.not_found.message",showRequiredPermissions:!1};case"server_error":return{icon:"🛠️",tone:"amber",titleKey:"layout_editor.access_error.server_error.title",messageKey:"layout_editor.access_error.server_error.message",showRequiredPermissions:!1};case"network":return{icon:"📡",tone:"amber",titleKey:"layout_editor.access_error.network.title",messageKey:"layout_editor.access_error.network.message",showRequiredPermissions:!1};default:return{icon:"⚠️",tone:"slate",titleKey:"layout_editor.access_error.unknown.title",messageKey:"layout_editor.access_error.unknown.message",showRequiredPermissions:!1}}}const J4={blue:{bg:"#eff6ff",border:"#bfdbfe",iconBg:"#dbeafe"},rose:{bg:"#fff1f2",border:"#fecdd3",iconBg:"#ffe4e6"},amber:{bg:"#fffbeb",border:"#fde68a",iconBg:"#fef3c7"},slate:{bg:"#f8fafc",border:"#e2e8f0",iconBg:"#f1f5f9"}};function Z4({error:e}){return u.useEffect(()=>{if(e.kind!=="unauthorized"||typeof window>"u")return;const t=Sg.getInstance(),n=`${window.location.pathname}${window.location.search}`,o=t.getLoginRedirectUrl("admin",n,"session_expired"),r=window.setTimeout(()=>{window.location.href=o},600);return()=>window.clearTimeout(r)},[e.kind]),null}function qa({error:e}){const{t}=tt(),n=X4(e.kind),o=J4[n.tone],r=()=>{typeof window<"u"&&(window.location.href="/admin")},s=()=>{typeof window<"u"&&window.location.reload()},a=()=>{if(typeof window>"u")return;const l=Sg.getInstance(),d=`${window.location.pathname}${window.location.search}`;window.location.href=l.getLoginRedirectUrl("admin",d)};return i.jsxs("div",{className:"g7le-access-error","data-testid":"g7le-access-error","data-error-kind":e.kind,style:{flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"#f1f5f9"},children:[i.jsx(Z4,{error:e}),i.jsxs("div",{style:{maxWidth:480,width:"100%",background:o.bg,border:`1px solid ${o.border}`,borderRadius:12,padding:"28px 32px",boxShadow:"0 2px 8px rgba(15, 23, 42, 0.05)",textAlign:"center"},children:[i.jsx("div",{style:{width:64,height:64,margin:"0 auto 16px",borderRadius:"50%",background:o.iconBg,display:"flex",alignItems:"center",justifyContent:"center",fontSize:32,lineHeight:1},"aria-hidden":"true",children:n.icon}),i.jsx("h2",{"data-testid":"g7le-access-error-title",style:{margin:"0 0 8px",fontSize:18,fontWeight:700,color:"#0f172a"},children:t(n.titleKey)}),i.jsx("p",{"data-testid":"g7le-access-error-message",style:{margin:"0 0 16px",fontSize:13,lineHeight:1.6,color:"#475569"},children:t(n.messageKey)}),n.showRequiredPermissions&&e.requiredPermissions&&i.jsxs("div",{"data-testid":"g7le-access-error-permissions",style:{display:"inline-flex",flexWrap:"wrap",gap:6,justifyContent:"center",padding:"8px 12px",marginBottom:16,background:"rgba(15, 23, 42, 0.04)",borderRadius:8,fontSize:12,color:"#475569"},children:[i.jsx("span",{style:{fontWeight:600},children:t("layout_editor.access_error.required_permission_label")}),e.requiredPermissions.split(/[,\s]+/).filter(Boolean).map(l=>i.jsx("code",{style:{padding:"2px 6px",background:"#fff",border:"1px solid #e2e8f0",borderRadius:4,fontFamily:"ui-monospace, SFMono-Regular, Menlo, monospace",fontSize:11,color:"#1e293b"},children:l},l))]}),e.message&&i.jsxs("details",{"data-testid":"g7le-access-error-detail",style:{marginBottom:16,fontSize:11,color:"#94a3b8"},children:[i.jsx("summary",{style:{cursor:"pointer"},children:t("layout_editor.access_error.detail_summary")}),i.jsxs("pre",{style:{marginTop:8,padding:8,background:"#fff",border:"1px solid #e2e8f0",borderRadius:6,overflowX:"auto",whiteSpace:"pre-wrap",wordBreak:"break-word",textAlign:"left",fontSize:11,color:"#475569"},children:[e.status>0?`HTTP ${e.status} +`:"",e.message]})]}),i.jsxs("div",{style:{display:"flex",justifyContent:"center",gap:8,flexWrap:"wrap"},children:[e.kind==="unauthorized"&&i.jsx("button",{type:"button","data-testid":"g7le-access-error-action-signin",onClick:a,style:Ga,children:t("layout_editor.access_error.action.sign_in")}),e.kind==="forbidden"&&i.jsx("button",{type:"button","data-testid":"g7le-access-error-action-home",onClick:r,style:Ga,children:t("layout_editor.access_error.action.go_home")}),(e.kind==="not_found"||e.kind==="server_error"||e.kind==="network"||e.kind==="unknown")&&i.jsx("button",{type:"button","data-testid":"g7le-access-error-action-retry",onClick:s,style:Ga,children:t("layout_editor.access_error.action.retry")}),e.kind!=="unauthorized"&&i.jsx("button",{type:"button","data-testid":"g7le-access-error-action-home-secondary",onClick:r,style:Q4,children:t("layout_editor.access_error.action.go_admin_home")})]})]})]})}const Ga={padding:"8px 16px",background:"#2563eb",color:"#fff",border:"1px solid #1d4ed8",borderRadius:6,fontSize:13,fontWeight:600,cursor:"pointer"},Q4={padding:"8px 16px",background:"#fff",color:"#475569",border:"1px solid #cbd5e1",borderRadius:6,fontSize:13,fontWeight:500,cursor:"pointer"};function R4(e){const t=window;if(typeof t>"u")return{getSnapshot:()=>({globalState:{},localState:{}}),restore:()=>{}};const n=t.G7Core||{},o={templateApp:t.__templateApp,g7CoreState:n.state,g7CoreDispatch:n.dispatch,g7CoreData:n.data,g7CoreModal:n.modal,g7CoreToast:n.toast};let r={...e.initialGlobalState??{}};r._local||(r._local={});const s=[],a=()=>{const c={globalState:{...r},localState:{...r._local??{}}};for(const p of s)try{p(r)}catch{}e.onChange?.(c)},l={},d={getGlobalState:()=>r,setGlobalState:(c,p)=>{typeof c=="function"?r=c(r):r={...r,...c},a()},onGlobalStateChange:c=>(s.push(c),()=>{const p=s.indexOf(c);p>=0&&s.splice(p,1)}),get globalState(){return r},getActionDispatcher:()=>e.actionDispatcher,getDataSource:c=>l[c]??null,setDataSource:(c,p)=>{l[c]=p},refetchDataSource:async c=>null,updateDataSourceItem:(c,p,f)=>l[c]??null,getLocale:()=>e.locale,changeLocale:c=>{},getRouter:()=>({navigate:()=>{},replace:()=>{},push:()=>{}}),updateQueryParams:()=>{}};return t.__templateApp=d,n&&typeof n.dispatch=="function"&&(n.dispatch=(c,p)=>{try{return e.actionDispatcher.executeAction(c,p??{})}catch{return}}),n&&typeof n.modal=="object"&&n.modal!==null&&(n.modal={...n.modal,open:()=>{},close:()=>{},closeAll:()=>{}}),n&&typeof n.toast=="object"&&n.toast!==null&&(n.toast={...n.toast,push:()=>{},dismiss:()=>{}}),{getSnapshot:()=>({globalState:{...r},localState:{...r._local??{}}}),restore:()=>{t.__templateApp===d&&(t.__templateApp=o.templateApp),t.G7Core&&(o.g7CoreState!==void 0&&(t.G7Core.state=o.g7CoreState),o.g7CoreDispatch!==void 0&&(t.G7Core.dispatch=o.g7CoreDispatch),o.g7CoreData!==void 0&&(t.G7Core.data=o.g7CoreData),o.g7CoreModal!==void 0&&(t.G7Core.modal=o.g7CoreModal),o.g7CoreToast!==void 0&&(t.G7Core.toast=o.g7CoreToast)),s.length=0}}}const eD=new Set(["id","userId","postId","orderId","productId","categoryId","commentId","noticeId","inquiryId","addressId","wishlistId","notificationId","roleId","menuId"]);function tD(e){if(!e)return{};const t={},n=/:([a-zA-Z_][a-zA-Z0-9_]*)/g;let o;for(;(o=n.exec(e))!==null;){const r=o[1];t[r]=nD(r)}return t}function nD(e){return eD.has(e)||/Id$|_id$/.test(e)?"1":"sample"}const oD=mo("LayoutEditor");function Ro(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function _i(e){if(Array.isArray(e))return e.map(t=>_i(t));if(Ro(e)){const t={};for(const[n,o]of Object.entries(e))t[n]=_i(o);return t}return e}function Cg(e,t="",n=new Set){for(const[o,r]of Object.entries(e)){const s=t?`${t}.${o}`:o;Ro(r)?Cg(r,s,n):n.add(s)}return n}function $g(e,t,n,o,r,s=""){for(const[a,l]of Object.entries(t)){const d=s?`${s}.${a}`:a;if(n.has(d)){r(`[LayoutEditor] sampleGlobal key conflict: extension '${o}' override of core key '${d}' ignored`);continue}const c=e[a];Ro(l)&&Ro(c)?$g(c,l,n,o,r,d):e[a]=_i(l)}}function Ya(e){const t=e.warn??(r=>oD.warn(r)),n=_i(e.coreSeed??{});e.isGuestOnly&&"currentUser"in n&&delete n.currentUser;const o=Cg(n);for(const r of e.sources)Ro(r.sampleGlobal)&&$g(n,r.sampleGlobal,o,r.id,t);return e.isGuestOnly&&"currentUser"in n&&delete n.currentUser,n}function rD(e){const t={};if(!e||typeof e!="object"||Array.isArray(e))return t;for(const[n,o]of Object.entries(e))n.startsWith("$")&&(t[n]=o);return t}function iD(e){const t={};if(!e||typeof e!="object"||Array.isArray(e))return t;for(const[n,o]of Object.entries(e))n.startsWith("$")||(t[n]=o);return t}function sD(e){if(typeof e!="string")return null;const t=/^\s*\{\{\s*([\s\S]*?)\s*\}\}\s*$/.exec(e);if(!t)return null;let n=t[1];const o=n.indexOf("??");return o>=0&&(n=n.slice(0,o)),n=n.replace(/\?\./g,".").replace(/\s+/g,""),n===""||!/^[A-Za-z_$][A-Za-z0-9_$]*(\.[A-Za-z_$][A-Za-z0-9_$]*)*$/.test(n)?null:n.split(".")}function aD(e,t){const n=sD(t);if(!n||n.length===0)return e;let o=e;for(let a=0;ao.map(r=>{if(!r||typeof r!="object")return r;const s=r;let a=s;if(typeof s.slot=="string"&&!t.has(s.slot)){const{slot:l,...d}=s;a={...d,__editorSlotName:l}}if(Array.isArray(a.children)){const l=n(a.children);l!==a.children&&(a={...a,children:l})}return a});return n(e)}function St(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Xt(e){if(Array.isArray(e))return e.map(t=>Xt(t));if(St(e)){const t={};for(const[n,o]of Object.entries(e))t[n]=Xt(o);return t}return e}function xi(e,t){for(const[n,o]of Object.entries(t)){const r=e[n];St(o)&&St(r)?xi(r,o):e[n]=Xt(o)}}function cD(e){const t=[];let n="";for(let o=0;o0&&(t.push(n),n="");const s=e[o+1];if(s==="'"||s==='"'){const l=e.indexOf(`${s}]`,o+2);if(l!==-1){t.push(e.slice(o+2,l)),o=l+1;continue}}const a=e.indexOf("]",o+1);if(a!==-1){t.push(e.slice(o+1,a)),o=a;continue}n+=r}else r==="."?n.length>0&&(t.push(n),n=""):n+=r}return n.length>0&&t.push(n),t.filter(o=>o.length>0)}function Xa(e,t,n){const o=cD(t);if(o.length===0)return;let r=e;for(let s=0;s0?t:void 0}const Za="g7le:editor-t-ready",Ag="data-g7le-vh-expanded";function pD(e,t){if(!e||!t)return;const n=t;e.querySelectorAll("*").forEach(r=>{const s=window.getComputedStyle(r),a=parseFloat(s.height),l=Number.isFinite(a)&&Math.abs(a-n)<=2,d=parseFloat(s.minHeight),c=Number.isFinite(d)&&Math.abs(d-n)<=2,p=s.overflowY==="auto"||s.overflowY==="scroll"||s.overflowY==="hidden"||s.overflow==="auto"||s.overflow==="scroll"||s.overflow==="hidden";l&&p?(r.style.setProperty("height","auto","important"),c&&r.style.setProperty("min-height","0","important"),r.style.setProperty("overflow","visible","important"),r.setAttribute(Ag,"1")):(s.overflowY==="auto"||s.overflowY==="scroll")&&r.scrollHeight>r.clientHeight+4&&r.clientHeight>120&&(r.style.setProperty("overflow","visible","important"),r.style.setProperty("height","auto","important"),r.setAttribute(Ag,"1"))})}const fD=[];function gD(e={}){const{manifest:t=null,nesting:n=null,componentPalette:o=null,spec:r=null,permissionCandidates:s,sampleGlobalSources:a=fD,resolveRouteMatch:l,onNavigateToDestination:d,onSessionAddedPathsChange:c}=e,{state:p}=Qe(),f=Ft(),b=Dp(),{document:g,isLoading:m,error:h}=f??b,v=u.useRef(null),[y,_]=u.useState(null),{deviceWidth:w,scale:k,colorScheme:x}=Ka(),$=u.useMemo(()=>p.activeStateId?p.availableStates.find(ce=>ce.id===p.activeStateId)??null:null,[p.activeStateId,p.availableStates]),S=u.useMemo(()=>Ig($),[$]),C=W4({isEditMode:!0,editorSpec:r??void 0,sampleOverride:S}),{t:T}=tt(),{componentRegistry:E,translationEngine:A,isReady:N,error:D}=Y4(p.templateIdentifier,p.locale),B=u.useRef(null);B.current===null&&(B.current=new kd);const M=u.useRef(null);if(M.current===null){M.current=new y7({navigate:()=>{}}),M.current.setPreviewMode(!0);try{const q=window.__templateApp?.getActionDispatcher?.();if(q&&typeof q.getRegisteredHandlers=="function"){const ie=q.getRegisteredHandlers();for(const se of ie){if(!se.includes("."))continue;const me=typeof q.getHandler=="function"?q.getHandler(se):void 0;typeof me=="function"&&M.current.registerHandler(se,me,{category:"plugin",source:"preview-canvas-cloned-from-host"})}}}catch{}}u.useEffect(()=>{if(!N)return;const ce=M.current;if(ce)try{const q=window.G7Core?.getActionDispatcher?.();if(!q||typeof q.getRegisteredHandlers!="function")return;const ie=q.getRegisteredHandlers();for(const se of ie){if(!se.includes(".")||typeof ce.getHandler=="function"&&ce.getHandler(se))continue;const me=typeof q.getHandler=="function"?q.getHandler(se):void 0;typeof me=="function"&&ce.registerHandler(se,me,{category:"plugin",source:"preview-canvas-iife-reclone"})}}catch{}},[N]);const O=u.useMemo(()=>new b7({sampleProvider:C,actionDispatcher:M.current}),[C]),z=u.useMemo(()=>g?.raw?.meta?.guest_only===!0,[g]),H=u.useMemo(()=>Ya({sources:a,isGuestOnly:z}),[a,z]),P=u.useMemo(()=>{const ce=hD(Ja($),A,{templateId:p.templateIdentifier,locale:p.locale}),q=H._local,{global:ie,local:se}=uD({globalBaseline:H,localBaseline:q??{},patch:$?.initialState??null,formErrors:ce});return{...ie,_local:se}},[H,$,A,p.templateIdentifier,p.locale]),I=u.useMemo(()=>!$||!(!!$.initialState?.local||!!Ja($))?null:{...P._local??{},_forceLocalInit:$.id,_merge:"deep"},[$,P]),L=ce=>typeof ce=="object"&&ce!==null&&!Array.isArray(ce),F=u.useMemo(()=>L($?.initialState?.query)?$.initialState.query:null,[$]),Y=u.useMemo(()=>L($?.initialState?.route)?$.initialState.route:null,[$]),[K,X]=u.useState(()=>Ya({sources:[],isGuestOnly:!1})),Z=u.useRef(null);u.useEffect(()=>{const ce={...P},q=R4({actionDispatcher:M.current,locale:p.locale,initialGlobalState:ce,onChange:se=>{X(se.globalState)}});Z.current=q;const ie=window.__templateApp;return ie?.setGlobalState&&M.current.setGlobalStateUpdater((se,me)=>{ie.setGlobalState(se,me)}),X(ce),Tl({kind:"applyPatch",activeStateId:p.activeStateId,routePath:p.selectedRoute?.path??null,hasInitialPatch:!!$?.initialState,hasFormErrors:!!Ja($),hasSampleOverride:!!Ig($)}),()=>{q.restore(),Z.current=null}},[p.locale,P]),u.useEffect(()=>{if(!A)return;const ce=window.G7Core;if(!ce||typeof ce.t!="function")return;const q=ce.t,ie=p.templateIdentifier,se=p.locale;return ce.t=(me,Ce)=>{try{const $e=Ce?"|"+Object.entries(Ce).map(([ue,fe])=>`${ue}=${fe}`).join("|"):void 0,U=A.translate(me,{templateId:ie,locale:se},$e);if(U!==me&&!U.startsWith("$t:"))return U}catch{}return q(me,Ce)},typeof window<"u"&&window.dispatchEvent(new CustomEvent(Za)),()=>{window.G7Core?.t&&window.G7Core.t!==q&&(window.G7Core.t=q)}},[A,p.templateIdentifier,p.locale]);const ae=u.useMemo(()=>{const ce=g?.raw?.components??[];return p.editMode!=="base"?ce:dD(ce)},[g,p.editMode]),oe=g?.raw?.__editability,G=g?.raw?.__extensionId,ee=u.useMemo(()=>p.editMode!=="extension"||oe!=="ok"?[]:typeof G!="number"?[]:yD(ae,G),[p.editMode,oe,G,ae]),[ge,V]=u.useState(null),[te,be]=u.useState(!1),Ee=g?.layoutName??null,De=u.useMemo(()=>{const ce=g?.raw?.scripts??[];return Array.isArray(ce)?ce.map(q=>q&&typeof q.src=="string"?q.src:"").join("|"):""},[g]);u.useEffect(()=>{be(!1)},[Ee,De]),u.useEffect(()=>{let ce=!1;const q=g?.raw?.scripts??[];if(!Array.isArray(q)||q.length===0){be(!0);return}const ie=[];for(const se of q){if(!se?.src||typeof se.src!="string")continue;if(!kg(se.src,Ua())){console.warn(`[PreviewCanvas] Blocked untrusted script src (same-origin path or declared trusted host required): ${se.src}`);continue}const me=se.id?`script#${CSS.escape(se.id)}, script[data-g7le-canvas-script="${se.src}"]`:`script[data-g7le-canvas-script="${se.src}"], script[src="${se.src}"]`,Ce=window.document.querySelector(me);if(Ce){const $e=Ce.hasAttribute("data-g7le-canvas-script");if(Ce.hasAttribute("data-g7le-script-loaded")||!$e)continue;ie.push(new Promise(ue=>{if(Ce.hasAttribute("data-g7le-script-loaded")){ue();return}Ce.addEventListener("load",()=>ue()),Ce.addEventListener("error",()=>ue())}));continue}ie.push(new Promise($e=>{const U=window.document.createElement("script");U.src=se.src,U.async=!1,se.id&&(U.id=se.id),U.setAttribute("data-g7le-canvas-script",se.src);const ue=()=>{U.setAttribute("data-g7le-script-loaded","1"),$e()};U.addEventListener("load",ue),U.addEventListener("error",ue),window.document.head.appendChild(U)}))}if(ie.length===0){be(!0);return}return Promise.all(ie).then(()=>{ce||requestAnimationFrame(()=>{requestAnimationFrame(()=>{ce||be(!0)})})}),()=>{ce=!0}},[g]);const Se=u.useMemo(()=>g?.raw?.data_sources??[],[g]),Ue=u.useMemo(()=>g?.raw?.computed??{},[g]),[Me,Oe]=u.useState({}),Ye=u.useMemo(()=>{if(p.editMode!=="iteration_item")return Me;const ce=g?.iterationContext;if(!ce)return Me;const q=g?.raw?.components??[],ie=Be({children:q},ce.sourceIndexPath),se=ie&&ie.iteration&&typeof ie.iteration.source=="string"?ie.iteration.source:null;return se?aD(Me,se):Me},[p.editMode,Me,g]),[ze,Xe]=u.useState(0);u.useEffect(()=>{if(typeof window>"u")return;const ce=()=>Xe(q=>q+1);return window.addEventListener(kt,ce),()=>window.removeEventListener(kt,ce)},[]);const ve=u.useMemo(()=>tD(p.selectedRoute?.path??null),[p.selectedRoute?.path]);if(u.useEffect(()=>{let ce=!1;return(async()=>{if(Se.length===0){ce||Oe({});return}try{const q=await O.fetchDataSources(Se,ve,new URLSearchParams,void 0,void 0);ce||Oe(q)}catch{ce||Oe({})}})(),()=>{ce=!0}},[Se,O,ve]),u.useEffect(()=>{const ce=y;if(!ce||typeof window>"u")return;let q=0,ie=0,se=0;const me=()=>pD(ce,window.innerHeight);q=window.requestAnimationFrame(()=>{ie=window.requestAnimationFrame(me)});let Ce=null;return typeof MutationObserver<"u"&&(Ce=new MutationObserver(()=>{se||(se=window.requestAnimationFrame(()=>{se=0,me()}))}),Ce.observe(ce,{childList:!0,subtree:!0})),()=>{window.cancelAnimationFrame(q),window.cancelAnimationFrame(ie),se&&window.cancelAnimationFrame(se),Ce&&Ce.disconnect()}},[y,ae,te,w,Me]),u.useEffect(()=>{const ce=y;if(!ce||typeof window>"u"||p.editMode!=="extension"||oe!=="ok"||ee.length===0){V(null);return}let q=0,ie=0;const se=ue=>{if(!ue)return!1;const fe=ue.getBoundingClientRect();return fe.width>0&&fe.height>0},me=ue=>{const fe=ce.querySelector(`[data-editor-path="${ue}"]`);if(se(fe))return!0;const xe=ce.querySelectorAll(`[data-editor-path^="${ue}.children."]`);for(const he of Array.from(xe))if(se(he))return!0;return!1},Ce=()=>{V(ee.some(me))};q=window.requestAnimationFrame(()=>{ie=window.requestAnimationFrame(Ce)});let $e=null,U=0;return typeof MutationObserver<"u"&&($e=new MutationObserver(()=>{U||(U=window.requestAnimationFrame(()=>{U=0,Ce()}))}),$e.observe(ce,{childList:!0,subtree:!0})),()=>{window.cancelAnimationFrame(q),window.cancelAnimationFrame(ie),U&&window.cancelAnimationFrame(U),$e&&$e.disconnect()}},[y,p.editMode,oe,ee,te,Me]),u.useEffect(()=>{if(typeof window>"u"||p.editMode!=="base")return;const ce=window.document,q="g7le-base-slot-style";if(ce.getElementById(q))return;const ie=ce.createElement("style");ie.id=q;const se=T("layout_editor.preview.slot_area_label");return ie.textContent=`.g7le-preview-frame [data-editor-slot]{position:relative;min-height:96px;outline:2px dashed #94a3b8;outline-offset:-2px;}.g7le-preview-frame [data-editor-slot]::after{content:'${se.replace(/'/g,"\\'")} · ' attr(data-editor-slot);position:absolute;top:8px;left:50%;transform:translateX(-50%);font-size:12px;line-height:1;color:#64748b;background:rgba(241,245,249,0.92);border:1px solid #cbd5e1;border-radius:9999px;padding:4px 12px;pointer-events:none;white-space:nowrap;}`,ce.head.appendChild(ie),()=>{ce.getElementById(q)?.remove()}},[p.editMode,T]),!(p.editMode==="extension"||p.editMode==="iteration_item")&&(p.selectedRoute?.layoutName===null||p.selectedRoute===null))return i.jsx("div",{className:"g7le-preview-canvas g7le-preview-canvas--empty","data-testid":"g7le-preview-empty",style:er,children:T("layout_editor.preview.empty")});if(m)return i.jsx("div",{className:"g7le-preview-canvas g7le-preview-canvas--loading","data-testid":"g7le-preview-loading",style:er,children:T("layout_editor.preview.loading")});if(h)return i.jsx(qa,{error:h});if(D)return i.jsx(qa,{error:D});if(!N||E===null||A===null)return i.jsx("div",{className:"g7le-preview-canvas g7le-preview-canvas--assets-loading","data-testid":"g7le-preview-assets-loading",style:er,children:T("layout_editor.preview.assets_loading")});if(ae.length===0)return i.jsx("div",{className:"g7le-preview-canvas g7le-preview-canvas--empty-layout","data-testid":"g7le-preview-empty-layout",style:er,children:T("layout_editor.preview.empty_layout")});const We=p.editMode==="extension"?oe==="no-injection"?"no-injection":oe==="ok"&&ee.length>0&&ge!==!0?"gated-no-state":null:null;return te?i.jsx("div",{className:"g7le-preview-canvas","data-testid":"g7le-preview-canvas",style:{overflow:"visible",background:"#f1f5f9",padding:24,display:"flex",justifyContent:"center",alignItems:"flex-start",minHeight:"calc(100vh - var(--g7le-header-h, 0px))",boxSizing:"border-box"},children:i.jsxs("div",{className:"g7le-preview-frame-wrapper","data-testid":"g7le-preview-frame-wrapper",style:{position:"relative",width:w,transform:`scale(${k})`,transformOrigin:"top center"},children:[i.jsx("div",{className:x==="dark"?"g7le-preview-frame g7le-preview-dark":"g7le-preview-frame","data-testid":"g7le-preview-frame","data-color-scheme":x,ref:ce=>{v.current=ce,_(ce)},style:{width:w,background:"#fff",border:"1px solid #cbd5e1",boxShadow:"0 1px 3px rgba(0,0,0,0.05)",minHeight:400,position:"relative",transform:"translateZ(0)",overflow:"hidden"},children:i.jsx(h7,{overrideWidth:w,children:ae.map((ce,q)=>i.jsx(g7,{componentDef:ce,dataContext:{...Ye,...rD(K),_global:iD(K),_computedDefinitions:Ue,...I?{_localInit:I,_local:{...Me._local??{},...K._local??{}}}:{},route:bD({...Me.route??{},...ve,path:p.selectedRoute?.path??""},Y),query:{...Me.query??{},...F??{}}},translationContext:{templateId:p.templateIdentifier,locale:p.locale},registry:E,bindingEngine:B.current,translationEngine:Pt.getInstance(),actionDispatcher:M.current,isEditMode:!0,isRootRenderer:q===0,componentPath:`${q}`,onComponentSelect:(ie,se)=>{},onComponentHover:(ie,se)=>{}},`${ce.id??`preview-${q}`}:t${ze}${p.editMode==="extension"?`:s${te?1:0}`:""}`))})}),i.jsx("div",{className:"g7le-overlay-layer","data-testid":"g7le-overlay-layer",style:{position:"absolute",left:0,top:0,width:w,height:y?y.getBoundingClientRect().height/(k||1):"100%",overflow:"visible",pointerEvents:"none"},children:i.jsx(B4,{frameEl:y,manifest:t,nesting:n,componentPalette:o,spec:r,permissionCandidates:s,resolveRouteMatch:l,onNavigateToDestination:d,onSessionAddedPathsChange:c})}),We!==null&&i.jsx("div",{className:"g7le-preview-canvas--extension-fallback","data-testid":"g7le-preview-extension-fallback","data-fallback-reason":We,style:{position:"absolute",left:0,top:0,right:0,bottom:0,minHeight:y?y.getBoundingClientRect().height/(k||1):400,background:"#f1f5f9",display:"flex",alignItems:"flex-start",justifyContent:"center",padding:24,boxSizing:"border-box",pointerEvents:"auto",zIndex:50},children:i.jsxs("div",{className:"g7le-extension-fallback-card",style:{maxWidth:440,textAlign:"center",position:"sticky",top:"calc(40vh - var(--g7le-header-h, 0px))"},children:[i.jsx("p",{className:"g7le-extension-fallback-title",style:{fontWeight:600,marginBottom:8,color:"#0f172a"},children:T(We==="no-injection"?"layout_editor.preview.extension_no_injection_title":"layout_editor.preview.extension_gated_title")}),i.jsx("p",{className:"g7le-extension-fallback-desc",style:{color:"#475569",lineHeight:1.6},children:We==="no-injection"?T("layout_editor.preview.extension_no_injection_desc"):p.availableStates.length>1?T("layout_editor.preview.extension_gated_desc_with_states"):T("layout_editor.preview.extension_gated_desc")})]})})]})}):i.jsx("div",{className:"g7le-preview-canvas g7le-preview-canvas--scripts-loading","data-testid":"g7le-preview-scripts-loading",style:er,children:T("layout_editor.preview.loading")})}function hD(e,t,n){if(!e)return;if(!t)return e;const o=s=>{if(typeof s=="string"&&s.startsWith("$t:"))try{const a=s.slice(3),l=a.indexOf("|");if(l===-1)return t.translate(a,n);const d=a.slice(0,l),c=a.slice(l);return t.translate(d,n,c)}catch{return s}return Array.isArray(s)?s.map(o):s},r={};for(const[s,a]of Object.entries(e))r[s]=o(a);return r}function yD(e,t){const n=[],o=(r,s)=>{Array.isArray(r)&&r.forEach((a,l)=>{if(!a||typeof a!="object")return;const d=s?`${s}.children.${l}`:`${l}`,c=a.__source;if(c?.kind==="extension"&&c.extensionId===t){n.push(d);return}Array.isArray(a.children)&&o(a.children,d)})};return o(e,""),n}function bD(e,t){if(!t)return e;const n={...e};for(const[o,r]of Object.entries(t))r===null?delete n[o]:n[o]=r;return n}const er={flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"#f1f5f9",color:"#64748b",fontSize:13},mD={desktop:"layout_editor.device.desktop",tablet:"layout_editor.device.tablet",mobile:"layout_editor.device.mobile",portable:"layout_editor.device.portable"};function vD(){const{device:e,zoom:t,customWidth:n,setDevice:o,setZoom:r,setCustomWidth:s,colorScheme:a,setColorScheme:l}=Ka(),{t:d}=tt(),c=Rf();return i.jsxs("div",{className:"g7le-device-toolbar","data-testid":"g7le-device-toolbar",style:{display:"inline-flex",alignItems:"center",gap:8,padding:"4px 8px",background:"#fff",border:"1px solid #cbd5e1",borderRadius:6},children:[i.jsxs("div",{role:"group","aria-label":d("layout_editor.device.group_label"),children:[c.map(p=>{const f=e===p,b=mD[p],g=b?d(b):p;return i.jsx("button",{type:"button","data-testid":`g7le-device-${p}`,"aria-pressed":f,onClick:()=>o(p),style:{padding:"2px 8px",marginRight:2,fontSize:12,cursor:"pointer",background:f?"#0f172a":"#f8fafc",color:f?"#fff":"#0f172a",border:"1px solid #cbd5e1",borderRadius:4},children:g},p)}),(()=>{const p=e==="custom";return i.jsx("button",{type:"button","data-testid":"g7le-device-custom","aria-pressed":p,onClick:()=>o("custom"),style:{padding:"2px 8px",marginRight:2,fontSize:12,cursor:"pointer",background:p?"#0f172a":"#f8fafc",color:p?"#fff":"#0f172a",border:"1px solid #cbd5e1",borderRadius:4},children:d("layout_editor.device.custom")})})()]}),e==="custom"&&i.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[i.jsx("label",{htmlFor:"g7le-custom-width-input",style:{fontSize:11,color:"#475569"},children:d("layout_editor.device.custom_width_label")}),i.jsx("input",{id:"g7le-custom-width-input",type:"number",min:bg,max:mg,step:10,value:n,"data-testid":"g7le-custom-width-input","aria-label":d("layout_editor.device.custom_width_label"),onChange:p=>{const f=parseInt(p.currentTarget.value,10);Number.isFinite(f)&&s(f)},style:{width:72,padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:4}}),i.jsx("span",{style:{fontSize:11,color:"#475569"},children:"px"})]}),i.jsx("div",{role:"group","aria-label":d("layout_editor.toolbar.color_scheme_group"),style:{display:"inline-flex",gap:2},children:["light","dark"].map(p=>{const f=a===p;return i.jsx("button",{type:"button","data-testid":`g7le-toolbar-scheme-${p}`,"aria-pressed":f,onClick:()=>l(p),style:{padding:"2px 8px",fontSize:12,cursor:"pointer",background:f?"#0f172a":"#f8fafc",color:f?"#fff":"#0f172a",border:"1px solid #cbd5e1",borderRadius:4},children:d(p==="light"?"layout_editor.toolbar.color_scheme_light":"layout_editor.toolbar.color_scheme_dark")},p)})}),i.jsxs("div",{style:{display:"inline-flex",alignItems:"center",gap:4},children:[i.jsx("span",{style:{fontSize:11,color:"#475569"},children:d("layout_editor.zoom.label")}),i.jsx("input",{type:"range",min:.5,max:1,step:.05,value:t,"data-testid":"g7le-zoom-slider","aria-label":d("layout_editor.zoom.aria_label"),onChange:p=>r(parseFloat(p.currentTarget.value)),style:{width:100}}),i.jsxs("span",{style:{fontSize:11,color:"#475569",minWidth:36,textAlign:"right"},children:[Math.round(t*100),"%"]})]}),i.jsx(Jb,{})]})}function _D(){const{t:e}=tt(),{state:t,dispatch:n}=Qe(),{availableStates:o,activeStateId:r}=t,[,s]=u.useState(0);u.useEffect(()=>{if(typeof window>"u")return;const p=()=>s(b=>b+1),f=window.requestAnimationFrame(p);return window.addEventListener(Za,p),()=>{window.cancelAnimationFrame(f),window.removeEventListener(Za,p)}},[]);const a=u.useCallback((p,f)=>{if(!p)return f;if(!p.startsWith("$t:"))return p;const b=p.slice(3),g=window.G7Core;if(g&&typeof g.t=="function"){const h=g.t(b);if(h&&h!==b&&!h.startsWith("$t:"))return h}const m=e(b);return m&&m!==b?m:f},[e]);if(!Array.isArray(o)||o.length<=1)return null;const l=p=>{const f=p.target.value;n({type:"SET_ACTIVE_STATE",activeStateId:f}),Tl({kind:"change",activeStateId:f,routePath:t.selectedRoute?.path??null,availableCount:o.length})},d=o.find(p=>p.id===r)??o[0],c=d?.description?a(d.description,""):"";return i.jsxs("div",{className:"g7le-state-switcher","data-testid":"g7le-state-switcher","data-active-state":r??"",style:{display:"inline-flex",alignItems:"center",gap:6,padding:"4px 8px",background:"#fff",border:"1px solid #cbd5e1",borderRadius:6},children:[i.jsx("span",{style:{fontSize:12,fontWeight:600,color:"#475569",whiteSpace:"nowrap"},children:e("layout_editor.toolbar.state")}),i.jsx("select",{"data-testid":"g7le-state-switcher-select","aria-label":e("layout_editor.toolbar.state"),value:r??o[0].id,onChange:l,style:{fontSize:12,padding:"2px 6px",border:"1px solid #cbd5e1",borderRadius:4,background:"#fff",color:"#0f172a",cursor:"pointer",outline:"none"},children:o.map(p=>i.jsx("option",{value:p.id,children:a(p.label,p.id)},p.id))}),c&&i.jsx("span",{"data-testid":"g7le-state-switcher-description",style:{fontSize:11,color:"#94a3b8",whiteSpace:"nowrap"},children:c})]})}function xD(e,t,n){if(e==="extension"){if(typeof n=="string"&&n.length>0){const o=Qa(n,"__base__/");return o?{kind:"base",match:o}:{kind:"route",match:n}}return null}if(!t)return null;switch(e){case"route":return{kind:"route",match:t};case"base":{const o=Qa(t,"__base__/");return o?{kind:"base",match:o}:null}case"modal":{const o=Qa(t,"__modal__/");return o?{kind:"modal",match:o}:null}default:return null}}function wD(e,t){if(!t||!Array.isArray(e)||e.length===0)return[];const n=[];for(const o of e)if(SD(o.scope,t))for(const r of o.items??[])r&&typeof r.id=="string"&&r.id.length>0&&n.push(r);return n}function kD(e){if(e.length===0)return null;const t=e.find(n=>n.default===!0);return t?t.id:e[0].id}function SD(e,t){if(!e||e.kind!==t.kind)return!1;const n=e.match;return typeof n!="string"||n.length===0?!1:t.kind==="route"?CD(t.match,n):n===t.match}function CD(e,t){if(t===e)return!0;if(!t.includes("*"))return!1;const n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\/\*\\\?/g,"(?:/[^/]+)?").replace(/\*/g,"[^/]+");return new RegExp(`^${n}$`).test(e)}function Qa(e,t){return e.startsWith(t)?e.slice(t.length):""}const $D="__conngroup__/modals/",ED="__conngroup__/extensions/";function ID(e){return e.meta?.editor_label?{label:e.meta.editor_label,labelSource:"editor_label"}:e.meta?.title?{label:e.meta.title,labelSource:"title"}:{label:e.path,labelSource:"path"}}function AD(e){switch(e.source.kind){case"template":return"template";case"module":return`module:${e.source.identifier??""}`;case"plugin":return`plugin:${e.source.identifier??""}`;case"core":return null;default:return null}}function TD(e,t){if(e.meta?.parent&&t.has(e.meta.parent))return e.meta.parent;const n=e.path.split("/").filter(Boolean);for(let o=n.length-1;o>=1;o--){const r="/"+n.slice(0,o).join("/");if(r!==e.path&&t.has(r))return r}return null}function DD(e){const t=new Map;for(const n of e)n.layout&&t.set(n.layout,(t.get(n.layout)??0)+1);return t}function zD(e){const t=new Map;for(const n of e){if(!n.hostLayout)continue;const o=t.get(n.hostLayout)??[];o.push(n),t.set(n.hostLayout,o)}return t}function ND(e){const t=new Map;for(const n of e)for(const o of n.extensions)for(const r of o.hostLayouts??[]){if(!r)continue;const s=t.get(r)??[];s.push({extension:o,group:n}),t.set(r,s)}return t}function MD(e,t){return{path:`__modal__/${e.hostLayout}/${e.modalId}`,layoutName:e.hostLayout,label:e.label??e.modalId,labelSource:e.label?"editor_label":"path",source:{kind:"core",identifier:null},kind:"modal",modalId:e.modalId,modalHostLayout:e.hostLayout,connectedHostRoutePath:t,children:[]}}function LD(e,t){const{extension:n,group:o}=e,r=o.sourceType==="plugin"?"🔌":"🧩";return{path:`__extension__/${n.id}`,layoutName:null,label:`${r} ${o.sourceLabel} · ${n.targetName}`,labelSource:"path",source:{kind:o.sourceType,identifier:o.sourceIdentifier},kind:"extension",extensionId:String(n.id),extensionType:n.extensionType,extensionPriority:n.priority,extensionTargetName:n.targetName,isModified:n.isModified,isInactive:!n.isActive,connectedHostRoutePath:t,children:[]}}function Tg(e,t,n){if(e.kind!=="route"&&e.kind!=="base"||!e.layoutName)return;const o=[],r=t.get(e.layoutName)??[];r.length>0&&o.push({path:`${$D}${e.path}`,layoutName:null,label:`$t:layout_editor.chrome.route_tree.connected.modals|count=${r.length}`,labelSource:"editor_label",source:{kind:"core",identifier:null},kind:"route",children:r.map(a=>MD(a,e.path))});const s=n.get(e.layoutName)??[];s.length>0&&o.push({path:`${ED}${e.path}`,layoutName:null,label:`$t:layout_editor.chrome.route_tree.connected.extensions|count=${s.length}`,labelSource:"editor_label",source:{kind:"core",identifier:null},kind:"route",children:s.map(a=>LD(a,e.path))}),o.length>0&&(e.children=[...o,...e.children??[]])}function PD(e){const t=[],n=new Set(e.routes.map(o=>o.path));for(const o of e.routes){const r=AD(o);if(!r)continue;const{label:s,labelSource:a}=ID(o),l=TD(o,n),d={path:o.path,layoutName:o.layout??null,label:s,labelSource:a,icon:o.meta?.icon??null,source:o.source,isRedirect:!!o.redirect,isHidden:!!o.meta?.hidden,kind:"route",children:[]};t.push({node:d,parentKey:l,groupKey:r})}return t}function OD(e,t){if(e==="template")return"$t:layout_editor.chrome.route_tree.group.template";if(e.startsWith("module:")){const n=e.slice(7);return`$t:layout_editor.chrome.route_tree.group.module|name=${t.moduleDisplayNames[n]??n}`}if(e.startsWith("plugin:")){const n=e.slice(7);return`$t:layout_editor.chrome.route_tree.group.plugin|name=${t.pluginDisplayNames[n]??n}`}return e}function BD(e,t){DD(e.routes);const n=zD(e.modals),o=ND(e.extensionGroups??[]),r=new Map;for(const d of t)r.has(d.groupKey)||r.set(d.groupKey,[]),r.get(d.groupKey).push(d);const s=Array.from(r.keys()).sort((d,c)=>{const p=g=>g==="template"?1:g.startsWith("module:")?2:g.startsWith("plugin:")?3:4,f=p(d),b=p(c);return f!==b?f-b:d.localeCompare(c)}),a=[];if(e.baseLayouts.length>0){const d=e.baseLayouts.map(c=>({path:`__base__/${c.layoutName}`,layoutName:c.layoutName,label:c.label??c.layoutName,labelSource:c.label?"editor_label":"path",source:{kind:"core",identifier:null},kind:"base",children:[]}));for(const c of d)Tg(c,n,o);a.push({path:"__group__/base",layoutName:null,label:"$t:layout_editor.chrome.route_tree.group.base",labelSource:"editor_label",source:{kind:"core",identifier:null},kind:"route",children:d})}for(const d of s){const c=r.get(d),p=new Map;for(const b of c)p.set(b.node.path,b);const f=[];for(const b of c)if(b.parentKey&&p.has(b.parentKey)){const g=p.get(b.parentKey);g.node.children=g.node.children??[],g.node.children.push(b.node)}else f.push(b.node);for(const b of c)Tg(b.node,n,o);a.push({path:`__group__/${d}`,layoutName:null,label:OD(d,e),labelSource:"editor_label",source:{kind:"core",identifier:null},kind:"route",children:f})}if(e.modals.length>0){const d=e.modals.map(c=>({path:`__modal__/${c.hostLayout}/${c.modalId}`,layoutName:c.hostLayout,label:c.label??c.modalId,labelSource:c.label?"editor_label":"path",source:{kind:"core",identifier:null},kind:"modal",modalId:c.modalId,modalHostLayout:c.hostLayout,children:[]}));a.push({path:"__group__/modal",layoutName:null,label:"$t:layout_editor.chrome.route_tree.group.modal",labelSource:"editor_label",source:{kind:"core",identifier:null},kind:"route",children:d})}const l=e.extensionGroups??[];if(l.length>0){const d=l.map(c=>{const p=c.sourceType==="plugin"?"🔌":"🧩",f=c.extensions.map(b=>({path:`__extension__/${b.id}`,layoutName:null,label:`${c.sourceLabel} · ${b.targetName}`,labelSource:"path",source:{kind:c.sourceType,identifier:c.sourceIdentifier},kind:"extension",extensionId:String(b.id),extensionType:b.extensionType,extensionPriority:b.priority,extensionTargetName:b.targetName,isModified:b.isModified,isInactive:!b.isActive,children:[]}));return{path:`__extgroup__/${c.sourceType}/${c.sourceIdentifier}`,layoutName:null,label:`${p} ${c.sourceLabel}`,labelSource:"path",source:{kind:c.sourceType,identifier:c.sourceIdentifier},kind:"route",children:f}});a.push({path:"__group__/extension",layoutName:null,label:"$t:layout_editor.chrome.route_tree.group.extension",labelSource:"editor_label",source:{kind:"core",identifier:null},kind:"route",children:d})}return a}function WD(e){const t=PD(e);return BD(e,t)}const On=mo("useEditorRoutes");function jD(e,t){if(typeof e=="string")return e.length>0?e:null;if(e&&typeof e=="object"){const n=e[t];if(typeof n=="string"&&n.length>0)return n;if(typeof e.en=="string"&&e.en.length>0)return e.en;for(const o of Object.values(e))if(typeof o=="string"&&o.length>0)return o}return null}function Dg(e,t){const n={};if(typeof window>"u")return n;const r=window.G7Config?.[e];if(!Array.isArray(r))return n;for(const s of r)s&&typeof s.identifier=="string"&&(n[s.identifier]=jD(s.display_name,t)??s.identifier);return n}function HD(e){const t=new kd,n=typeof window<"u"?window.G7Config:void 0,o={_global:{settings:n?.settings??{},plugins:n?.plugins??{},modules:n?.modules??{},appConfig:n?.appConfig??{}}};return e.map(r=>{const s={...r};if(typeof s.path=="string"&&s.path.includes("{{")){const a=s.path;let l=t.resolveBindings(s.path,o);l=l.replace(/\/\/+/g,"/")||"/",l.includes("{{")&&(On.warn("편집기 route path 표현식 평가 실패 — fallback 적용",{originalPath:a}),l=a.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/"),s.path=l}if(typeof s.redirect=="string"&&s.redirect.includes("{{")){const a=s.redirect;let l=t.resolveBindings(a,o);l=l.replace(/\/\/+/g,"/")||"/",l.includes("{{")&&(On.warn("편집기 route redirect 표현식 평가 실패 — fallback 적용",{originalRedirect:a}),l=a.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/"),s.redirect=l}return s})}function FD(e){const{dispatch:t}=Qe(),{translationEngine:n,translationContext:o}=tt(),{templateIdentifier:r,cacheVersion:s}=e;u.useEffect(()=>{let a=!1;const l=s??(typeof window<"u"?window.G7Config?.cache_version:void 0)??"",d=l!==""?`?v=${encodeURIComponent(String(l))}`:"",c=en(`/api/admin/templates/${encodeURIComponent(r)}/editor/routes`,"json",null,d.replace(/^[?&]+/,"")),p=o?.locale??"ko",f=n&&r!==o?.templateId?n.loadTranslations(r,p).then(()=>{On.log("편집 대상 lang 로드 완료",{targetTemplate:r,locale:p})}).catch(h=>{On.warn("편집 대상 lang 로드 실패 — 라우트 라벨 fallback 사용",h)}):Promise.resolve(),b=(()=>{if(typeof fetch!="function")return Promise.reject(so(new Error("fetch unavailable"),"routes"));try{const h=fetch(c,{credentials:"same-origin",headers:Ne()});return!h||typeof h.then!="function"?Promise.reject(so(new Error("fetch returned non-Promise (test stub?)"),"routes")):h.then(async v=>{if(!v.ok){const y=await v.json().catch(()=>null);throw Jr(v.status,y,"routes")}return v.json()})}catch(h){return Promise.reject(h)}})(),g=`/api/admin/templates/${encodeURIComponent(r)}/layout-extensions${d}`,m=(()=>{if(typeof fetch!="function")return Promise.resolve(null);try{const h=fetch(g,{credentials:"same-origin",headers:Ne()});return!h||typeof h.then!="function"?Promise.resolve(null):h.then(async v=>v.ok?await v.json():null).catch(()=>null)}catch{return Promise.resolve(null)}})();return Promise.all([b,f,m]).then(([h,,v])=>{if(a)return;if(!h||!h.success||!Array.isArray(h.data?.routes)){On.warn("routes 응답 형식이 비정상 — empty tree 로 둠",h),t({type:"SET_ROUTES_ERROR",error:{kind:"unknown",status:200,message:"routes 응답 형식이 비정상입니다.",source:"routes"}});return}const y=HD(h.data.routes),_=Dg("activeModules",p),w=Dg("activePlugins",p),k=(h.data.base_layouts??[]).map(A=>({layoutName:A.layout_name,label:A.label??void 0})),x=(h.data.modals??[]).map(A=>({modalId:A.modal_id,hostLayout:A.host_layout,label:A.label??void 0})),$=(v?.success&&Array.isArray(v.data)?v.data:[]).map(A=>({sourceIdentifier:A.source_identifier,sourceType:A.source_type,sourceLabel:A.source_label,extensions:(A.extensions??[]).map(N=>({id:N.id,extensionType:N.extension_type,targetName:N.target_name,priority:N.priority,isActive:N.is_active,isModified:N.is_modified,hostLayouts:Array.isArray(N.host_layouts)?N.host_layouts:[],currentVersion:typeof N.current_version=="number"?N.current_version:void 0}))})),S=WD({routes:y,modals:x,baseLayouts:k,extensionGroups:$,moduleDisplayNames:_,pluginDisplayNames:w});t({type:"SET_ROUTE_TREE",tree:S});const C=h.data.layout_versions,T={};if(C&&typeof C=="object"&&!Array.isArray(C))for(const[A,N]of Object.entries(C))typeof N=="number"&&Number.isFinite(N)&&(T[A]=N);t({type:"SET_LAYOUT_VERSIONS",versions:T});const E={};for(const A of $)for(const N of A.extensions){const D=N.currentVersion;typeof D=="number"&&Number.isFinite(D)&&(E[String(N.id)]=D)}t({type:"SET_EXTENSION_VERSIONS",versions:E}),On.log("routes 로드 완료",{count:y.length,groups:S.length})}).catch(h=>{if(a)return;On.error("routes 로드 실패",h);const v=xp(h)?h:so(h,"routes");t({type:"SET_ROUTES_ERROR",error:v})}),()=>{a=!0}},[r,s,t,n,o?.locale,o?.templateId])}function zg(e,t,n,o=[]){const r=t?Ng(o,t):null,s=r!==null?{path:r.path,layoutName:r.layoutName}:void 0;if(e.startsWith("__base__/")){const a=e.slice(9);if(a)return n({type:"ENTER_BASE_EDIT",layoutName:a,returnRoute:s}),!0}else if(e.startsWith("__modal__/")){const a=e.slice(10);return a&&!a.includes("/")&&t?(n({type:"ENTER_MODAL_EDIT",modalId:a,hostLayout:t,returnRoute:s}),!0):!1}else if(e.startsWith("__extension__/")){const a=e.slice(14);if(a&&!a.includes("/"))return n({type:"ENTER_EXTENSION_EDIT",extensionId:a,returnRoute:s}),!0}else if(e.startsWith("__iteration__/")){const a=e.slice(14);return a&&t?(n({type:"ENTER_ITERATION_ITEM_EDIT",sourcePath:a,hostLayout:t,returnRoute:s}),!0):!1}return!1}function Ng(e,t){for(const n of e){if(n.kind==="route"&&n.layoutName===t)return n;if(n.children&&n.children.length>0){const o=Ng(n.children,t);if(o)return o}}return null}function Ra(e,t){for(const n of e){if(n.kind==="route"&&n.path===t)return n;if(n.children&&n.children.length>0){const o=Ra(n.children,t);if(o)return o}}return null}function KD(e){const{state:t,dispatch:n}=Qe(),o=u.useRef(!1),r=u.useRef(t.editMode);r.current=t.editMode,u.useEffect(()=>{if(o.current||t.routeTree.length===0||typeof window>"u")return;const a=fp(window.location.search);if(a){const c=pp(window.location.search),p=zg(a,c,n,t.routeTree);if(o.current=!0,p)return}const l=up(window.location.search);if(!l){o.current=!0;return}const d=Ra(t.routeTree,l);d&&n({type:"SELECT_ROUTE",route:{path:d.path,layoutName:d.layoutName}}),o.current=!0},[t.routeTree,n]),u.useEffect(()=>{if(typeof window>"u")return;const a=()=>{const l=fp(window.location.search);if(l){const p=pp(window.location.search);if(zg(l,p,n,t.routeTree))return}if(r.current!=="route")switch(r.current){case"base":n({type:"EXIT_BASE_EDIT"});return;case"modal":n({type:"EXIT_MODAL_EDIT"});return;case"extension":n({type:"EXIT_EXTENSION_EDIT"});return;case"iteration_item":n({type:"EXIT_ITERATION_ITEM_EDIT"});return}const d=up(window.location.search);if(!d){n({type:"SELECT_ROUTE",route:null});return}const c=Ra(t.routeTree,d);c&&n({type:"SELECT_ROUTE",route:{path:c.path,layoutName:c.layoutName}})};return window.addEventListener("popstate",a),()=>{window.removeEventListener("popstate",a)}},[t.routeTree,n]);const s=u.useRef("route");u.useEffect(()=>{if(typeof window>"u"||!window.history?.replaceState||t.routeTree.length===0)return;const a=ea(e,t.selectedRoute?.path??null,t.selectedRoute?.layoutName??null),l=`${window.location.pathname}${window.location.search}`,d=s.current;if(s.current=t.editMode,l===a)return;d==="route"&&t.editMode!=="route"&&window.history.pushState?window.history.pushState(window.history.state,"",a):window.history.replaceState(window.history.state,"",a)},[t.selectedRoute,t.editMode,t.routeTree,e])}function VD(){u.useEffect(()=>{if(typeof document>"u")return;const e=document.documentElement;let t=e.classList.contains("dark");const n=()=>{e.classList.contains("dark")&&(t=!0,e.classList.remove("dark"))};n();let o=null;return typeof MutationObserver<"u"&&(o=new MutationObserver(n),o.observe(e,{attributes:!0,attributeFilter:["class"]})),()=>{o?.disconnect(),t&&e.classList.add("dark")}},[])}function UD(){u.useEffect(()=>{if(typeof document>"u"||!document.body)return;const e=document.body,t=()=>{e.style.overflow==="hidden"&&(e.style.overflow=""),e.style.overflowY==="hidden"&&(e.style.overflowY="")};t();let n=null;return typeof MutationObserver<"u"&&(n=new MutationObserver(t),n.observe(e,{attributes:!0,attributeFilter:["style"]})),()=>{n?.disconnect()}},[])}function qD(e){if(typeof e!="string")return null;const t="__extension__/";if(!e.startsWith(t))return null;const n=e.slice(t.length);return n===""||n.includes("/")?null:n}function GD(e){if(Array.isArray(e.components))return e.components;if(Array.isArray(e.injections)){const t=[];return e.injections.forEach((n,o)=>{if(n&&Array.isArray(n.components))for(const r of n.components)t.push({...r,__injectionIndex:o})}),t}return[]}function YD(e,t){if(Array.isArray(e.components)){const n=t.map(o=>el(o));return{...e,components:n}}if(Array.isArray(e.injections)){const n=e.injections.map(o=>({...o}));n.forEach(o=>{Array.isArray(o.components)&&(o.components=[])});for(const o of t){const r=o.__injectionIndex,s=typeof r=="number"&&r>=0&&rel(n))),t}function Mg(e,t){const n=[],o=r=>{if(Array.isArray(r))for(const s of r){if(!s||typeof s!="object")continue;const a=s.__source;if(a?.kind==="extension"&&a.extensionId===t){n.push(s);continue}Array.isArray(s.children)&&o(s.children)}};return o(e),n}function Lg(e,t){const o=Mg(e,t)[0]?.__source;return o&&o.kind==="extension"&&o.extensionId===t?o:{kind:"extension",extensionId:t}}function tl(e,t){for(const n of e){const o=n?.__source;if(o?.kind==="extension"&&o.extensionId===t||Array.isArray(n.children)&&tl(n.children,t))return!0}return!1}function XD(){const{state:e}=Qe(),t=e.templateIdentifier,n=e.editMode==="extension"?qD(e.selectedRoute?.path):null,o=e.editMode==="extension"&&typeof e.selectedRoute?.layoutName=="string"?e.selectedRoute.layoutName:null,[r,s]=u.useState(null),[a,l]=u.useState(!1),[d,c]=u.useState(null),[p,f]=u.useState(!1),[b,g]=u.useState(0),[m,h]=u.useState(null),v=u.useRef({}),y=u.useRef({kind:"extension",extensionId:0}),_=u.useRef(null);u.useEffect(()=>{_.current=r},[r]),u.useEffect(()=>{h(null)},[n]);const w=u.useCallback(async A=>{const N=window.G7Config?.cache_version??0,D=en(`/api/layouts/${encodeURIComponent(t)}/${A}`,"json",`${N}.${Tp()}`,"with_source_meta=1"),B=cr(),M={Accept:"application/json"};B&&(M.Authorization=`Bearer ${B}`);const O=await fetch(D,{headers:M,credentials:"same-origin"});if(!O.ok)return null;const z=await O.json().catch(()=>null);return(z&&(z.data||z))??{}},[t]),k=u.useCallback(async()=>{if(!n){s(null),c(null),f(!1);return}l(!0),c(null);try{const A=window.G7Config?.cache_version??0,N=`/api/admin/templates/${encodeURIComponent(t)}/layout-extensions/${encodeURIComponent(n)}?v=${A}`,D=await fetch(N,{headers:Ne(),credentials:"same-origin"}),B=await D.json().catch(()=>null);if(!D.ok){c(Jr(D.status,B,"layout")),s(null),f(!1);return}const M=(B&&(B.data||B))??{};let O={};const z=M.content;if(typeof z=="string")try{O=JSON.parse(z)}catch{O={}}else z&&typeof z=="object"&&(O=z);const H=M.extension_type==="overlay"?"overlay":"extension_point",P=typeof M.lock_version=="number"?M.lock_version:0,I=Array.isArray(M?.host_layouts)?M.host_layouts.filter(oe=>typeof oe=="string"):[],L=o??(I.length===1?I[0]:m&&I.includes(m)?m:null),F=Number(n);v.current=O;let K=GD(O),X={},Z="pending";const ae={kind:"extension",extensionId:F};if(y.current=ae,L){const oe=await w(L);if(oe){X=oe;const G=Array.isArray(oe.components)?oe.components:[],ee=Lg(G,F);if(y.current=ee,tl(G,F))K=G,Z="ok";else{const V=(Array.isArray(oe.modals)?oe.modals:[]).filter(te=>te&&typeof te=="object"&&tl([te],F));if(V.length>0){const te=V.map(be=>({...be,props:{...be.props??{},isOpen:!0}}));K=[...G,...te],y.current=Lg(V,F),Z="ok"}else K=G,Z="no-injection"}}}s({extensionId:F,content:O,extensionType:H,components:K,lockVersion:P,hostLayouts:I,hostLayoutName:L,hostRaw:X,editability:Z}),f(!1),st({op:"load",layoutName:`extension:${n}`,editMode:"extension",statusCode:D.status,timestamp:Date.now()})}catch(A){c(so(A,"layout")),s(null),f(!1)}finally{l(!1)}},[t,n,m,o,w]);u.useEffect(()=>{k()},[k]);const x=u.useCallback(A=>{h(A)},[]),$=u.useCallback(A=>{s(N=>N&&{...N,components:A}),f(!0),st({op:"patch",layoutName:`extension:${_.current?.extensionId??""}`,editMode:"extension",isDirty:!0,timestamp:Date.now()})},[]),S=u.useCallback(A=>{s(N=>N&&{...N,components:A(N.components)}),f(!0)},[]),C=u.useCallback(async()=>{const A=_.current;if(!A)return{kind:"guard_no_document"};const N=`/api/admin/templates/${encodeURIComponent(t)}/layout-extensions/${A.extensionId}`,D=Mg(A.components,A.extensionId),B=D.length>0?D:A.components,M=YD(v.current,B);st({op:"save",layoutName:`extension:${A.extensionId}`,editMode:"extension",saveTarget:"layout_extension",endpoint:N,isDirty:p,timestamp:Date.now()});let O;try{O=await fetch(N,{method:"PUT",headers:Ne({"Content-Type":"application/json"}),credentials:"same-origin",body:JSON.stringify({content:M,expected_lock_version:A.lockVersion})})}catch(H){return{kind:"network_error",message:H instanceof Error?H.message:"network error"}}const z=await O.json().catch(()=>null);if(st({op:"save_response",layoutName:`extension:${A.extensionId}`,editMode:"extension",endpoint:N,statusCode:O.status,conflict:O.status===409?{currentVersion:z?.errors?.current_version??z?.current_version,yourVersion:z?.errors?.your_version??z?.your_version}:void 0,timestamp:Date.now()}),O.ok){const H=z?.data??{},P=typeof H.lock_version=="number"?H.lock_version:A.lockVersion+1;s(L=>L&&{...L,lockVersion:P}),f(!1),g(L=>L+1);const I=typeof H.current_version=="number"?H.current_version:void 0;return{kind:"success",newLockVersion:P,newContentVersion:I,savedExtensionId:String(A.extensionId)}}return O.status===409?{kind:"concurrent_modification",currentVersion:z?.current_version??-1,yourVersion:z?.your_version??A.lockVersion}:O.status===422?{kind:"validation_failed",status:422,errors:z?.errors??null}:{kind:"network_error",message:z?.message??`HTTP ${O.status}`}},[t,p]),T=u.useCallback(async()=>{ia(),await k()},[k]),E=!!r&&r.hostLayouts.length>1&&r.hostLayoutName===null;return{document:r,isLoading:a,error:d,isDirty:p,saveSuccessCounter:b,setLayoutComponents:$,patchLayout:S,save:C,reload:T,needsHostPicker:E,selectHost:x}}const Pg=new Set;function JD(e,t,n){const r=e&&Object.keys(e).length>0?e:t,s=Array.isArray(r.data_sources)?r.data_sources:[],a=Array.isArray(t.data_sources)?t.data_sources:[],l=new Set,d=[];for(const c of[...s,...a]){const p=c&&typeof c=="object"?c.id:void 0,f=typeof p=="string"?p:`__anon_${d.length}`;l.has(f)||(l.add(f),d.push(c))}return{...r,components:n,...d.length>0?{data_sources:d}:{},lock_version:void 0}}function ZD(e){return{document:e.document?{layoutName:`extension:${e.document.extensionId}`,raw:{...JD(e.document.hostRaw,e.document.content,e.document.components),__editability:e.document.editability,__extensionId:e.document.extensionId},lockVersion:e.document.lockVersion}:null,isLoading:e.isLoading,error:e.error,isDirty:e.isDirty,saveSuccessCounter:e.saveSuccessCounter,reload:e.reload,patchLayout:e.patchLayout,setLayoutComponents:e.setLayoutComponents,patchDocumentRaw:()=>{},dirtyKeys:Pg,dirtyLayoutNames:Pg,invalidateCurrentCache:()=>{},reloadCounter:0,save:()=>e.save(),markDirty:()=>{}}}function QD({hostLayouts:e,extensionLabel:t,onSelect:n}){const{t:o}=tt();return i.jsx("div",{className:"g7le-host-picker__backdrop","data-testid":"g7le-host-picker",role:"dialog","aria-modal":"true","aria-label":o("layout_editor.host_picker.title"),style:{position:"fixed",inset:0,zIndex:9500,display:"flex",alignItems:"center",justifyContent:"center",background:"rgba(15, 23, 42, 0.55)"},children:i.jsxs("div",{className:"g7le-host-picker__panel",style:{width:"min(520px, 92vw)",maxHeight:"80vh",overflow:"auto",background:"#ffffff",color:"#0f172a",borderRadius:12,boxShadow:"0 20px 48px rgba(15, 23, 42, 0.28)",padding:"20px 22px"},children:[i.jsx("h2",{className:"g7le-host-picker__title",style:{margin:"0 0 6px",fontSize:16,fontWeight:700},children:o("layout_editor.host_picker.title")}),i.jsx("p",{className:"g7le-host-picker__desc",style:{margin:"0 0 16px",fontSize:13,color:"#475569",lineHeight:1.6},children:t?o("layout_editor.host_picker.description_with_label",{label:t}):o("layout_editor.host_picker.description")}),i.jsx("ul",{className:"g7le-host-picker__list",style:{listStyle:"none",margin:0,padding:0,display:"grid",gap:8},children:e.map(r=>i.jsx("li",{children:i.jsxs("button",{type:"button",className:"g7le-host-picker__item","data-testid":"g7le-host-picker-item","data-host":r,onClick:()=>n(r),style:{width:"100%",textAlign:"left",padding:"12px 14px",border:"1px solid #e2e8f0",borderRadius:8,background:"#f8fafc",cursor:"pointer",fontSize:13,fontWeight:600,color:"#0f172a",display:"flex",alignItems:"center",gap:8},children:[i.jsx("span",{"aria-hidden":!0,style:{fontSize:14},children:"🖼"}),i.jsx("span",{style:{flex:1,minWidth:0,overflow:"hidden",textOverflow:"ellipsis"},children:r}),i.jsx("span",{"aria-hidden":!0,style:{color:"#94a3b8"},children:"→"})]})},r))})]})})}function RD(e,t){const[n,o]=u.useState(!1),[r,s]=u.useState(null),a=u.useCallback(async l=>{if(!t||!l)return{kind:"no_document"};o(!0),s(null);try{const d=_o(l),c=`/api/admin/templates/${encodeURIComponent(e)}/layouts/${t}/preview`,p=await fetch(c,{method:"POST",credentials:"same-origin",headers:Ne({"Content-Type":"application/json"}),body:JSON.stringify({content:JSON.stringify(d)})}),f=await p.json().catch(()=>null);if(!p.ok){const h=f?.message??`HTTP ${p.status}`;return s(h),{kind:"network_error",message:h}}const b=f?.data,g=typeof b?.token=="string"?b.token:"",m=typeof b?.preview_url=="string"&&b.preview_url?b.preview_url:g?`/preview/${g}`:"";return m?(window.G7Core?.dispatch?.({handler:"openWindow",params:{path:m}}),{kind:"success",previewUrl:m,token:g}):(s("invalid preview response"),{kind:"network_error",message:"invalid preview response"})}catch(d){const c=d instanceof Error?d.message:"network error";return s(c),{kind:"network_error",message:c}}finally{o(!1)}},[e,t]);return{isCreating:n,error:r,createPreview:a}}const re="layout_editor.action_recipe",bn={setState:{label:`$t:${re}.set_state.label`,params:[{key:"target",label:`$t:${re}.set_state.param_target`,widget:"select",options:[{value:"local"},{value:"global"}]},{key:"state",label:`$t:${re}.set_state.param_state`,widget:"state-key-value"},{key:"merge",label:`$t:${re}.set_state.param_merge`,widget:"toggle"}],build:{handler:"setState",params:{target:"{{target}}",merge:"{{merge}}","...":"{{state}}"}}},loadFromLocalStorage:{label:`$t:${re}.load_local.label`,params:[{key:"key",label:`$t:${re}.load_local.param_key`,widget:"text",required:!0},{key:"stateKey",label:`$t:${re}.load_local.param_state_key`,widget:"state-key-picker"},{key:"defaultValue",label:`$t:${re}.load_local.param_default`,widget:"text"}],build:{handler:"loadFromLocalStorage",params:{key:"{{key}}",stateKey:"{{stateKey}}",defaultValue:"{{defaultValue}}"}}},saveToLocalStorage:{label:`$t:${re}.save_local.label`,params:[{key:"key",label:`$t:${re}.save_local.param_key`,widget:"text",required:!0},{key:"value",label:`$t:${re}.save_local.param_value`,widget:"data-chip"}],build:{handler:"saveToLocalStorage",params:{key:"{{key}}",value:"{{value}}"}}},navigate:{label:`$t:${re}.navigate.label`,params:[{key:"path",label:`$t:${re}.navigate.param_path`,widget:"page-picker",required:!0},{key:"query",label:`$t:${re}.navigate.param_query`,widget:"key-value"},{key:"mergeQuery",label:`$t:${re}.navigate.param_merge_query`,widget:"toggle"},{key:"scroll",label:`$t:${re}.navigate.param_scroll`,widget:"select",options:[{value:"top"},{value:"preserve"},{value:"none"}]},{key:"replace",label:`$t:${re}.navigate.param_replace`,widget:"toggle"},{key:"transition_overlay_target",label:`$t:${re}.navigate.param_overlay_target`,widget:"component-target-picker",dependsOn:{param:"replace",equals:!0}}],build:{handler:"navigate",params:{path:"{{path}}",query:"{{query}}",mergeQuery:"{{mergeQuery}}",scroll:"{{scroll}}",replace:"{{replace}}",transition_overlay_target:"{{transition_overlay_target}}"}}},openWindow:{label:`$t:${re}.open_window.label`,params:[{key:"target",label:`$t:${re}.open_window.param_target`,widget:"page-picker",required:!0},{key:"windowTarget",label:`$t:${re}.open_window.param_window_target`,widget:"select",options:[{value:"_blank"},{value:"_self"}]}],build:{handler:"openWindow",target:"{{target}}",params:{windowTarget:"{{windowTarget}}"}}},navigateBack:{label:`$t:${re}.navigate_back.label`,params:[],build:{handler:"navigateBack"}},navigateForward:{label:`$t:${re}.navigate_forward.label`,params:[],build:{handler:"navigateForward"}},replaceUrl:{label:`$t:${re}.replace_url.label`,params:[{key:"path",label:`$t:${re}.replace_url.param_path`,widget:"page-picker"},{key:"query",label:`$t:${re}.replace_url.param_query`,widget:"key-value"}],build:{handler:"replaceUrl",params:{path:"{{path}}",query:"{{query}}"}}},toast:{label:`$t:${re}.toast.label`,params:[{key:"message",label:`$t:${re}.toast.param_message`,widget:"i18n-text",required:!0},{key:"type",label:`$t:${re}.toast.param_type`,widget:"select",options:[{value:"info"},{value:"success"},{value:"warning"},{value:"error"}]},{key:"duration",label:`$t:${re}.toast.param_duration`,widget:"number"},{key:"icon",label:`$t:${re}.toast.param_icon`,widget:"text"}],build:{handler:"toast",params:{message:"{{message}}",type:"{{type}}",duration:"{{duration}}",icon:"{{icon}}"}}},openModal:{label:`$t:${re}.open_modal.label`,params:[{key:"target",label:`$t:${re}.open_modal.param_target`,widget:"modal-picker",required:!0}],build:{handler:"openModal",target:"{{target}}"}},closeModal:{label:`$t:${re}.close_modal.label`,params:[],build:{handler:"closeModal"}},showAlert:{label:`$t:${re}.show_alert.label`,params:[{key:"target",label:`$t:${re}.show_alert.param_message`,widget:"i18n-text",required:!0}],build:{handler:"showAlert",target:"{{target}}"}},setError:{label:`$t:${re}.set_error.label`,params:[{key:"target",label:`$t:${re}.set_error.param_message`,widget:"i18n-text"},{key:"stateTarget",label:`$t:${re}.set_error.param_state_target`,widget:"select",options:[{value:"local"},{value:"global"}]}],build:{handler:"setError",target:"{{target}}",params:{stateTarget:"{{stateTarget}}"}}},refetchDataSource:{label:`$t:${re}.refetch.label`,params:[{key:"dataSourceId",label:`$t:${re}.refetch.param_data_source`,widget:"datasource-picker",required:!0},{key:"sync",label:`$t:${re}.refetch.param_sync`,widget:"toggle"}],build:{handler:"refetchDataSource",params:{dataSourceId:"{{dataSourceId}}",sync:"{{sync}}"}}},appendDataSource:{label:`$t:${re}.append_data.label`,params:[{key:"dataSourceId",label:`$t:${re}.append_data.param_data_source`,widget:"datasource-picker",required:!0},{key:"dataPath",label:`$t:${re}.append_data.param_data_path`,widget:"text"},{key:"newData",label:`$t:${re}.append_data.param_new_data`,widget:"data-chip"}],build:{handler:"appendDataSource",params:{dataSourceId:"{{dataSourceId}}",dataPath:"{{dataPath}}",newData:"{{newData}}"}}},updateDataSource:{label:`$t:${re}.update_data.label`,params:[{key:"dataSourceId",label:`$t:${re}.update_data.param_data_source`,widget:"datasource-picker",required:!0},{key:"data",label:`$t:${re}.update_data.param_data`,widget:"data-chip"},{key:"merge",label:`$t:${re}.update_data.param_merge`,widget:"toggle"}],build:{handler:"updateDataSource",params:{dataSourceId:"{{dataSourceId}}",data:"{{data}}",merge:"{{merge}}"}}},scrollIntoView:{label:`$t:${re}.scroll.label`,params:[{key:"selector",label:`$t:${re}.scroll.param_selector`,widget:"text",required:!0},{key:"behavior",label:`$t:${re}.scroll.param_behavior`,widget:"select",options:[{value:"smooth"},{value:"auto"}]},{key:"block",label:`$t:${re}.scroll.param_block`,widget:"select",options:[{value:"start"},{value:"center"},{value:"end"},{value:"nearest"}]}],build:{handler:"scrollIntoView",params:{selector:"{{selector}}",behavior:"{{behavior}}",block:"{{block}}"}}},login:{label:`$t:${re}.login.label`,params:[{key:"body",label:`$t:${re}.login.param_body`,widget:"key-value"}],build:{handler:"login",params:{body:"{{body}}"}}},loginTwoFactor:{label:`$t:${re}.login_two_factor.label`,params:[{key:"body",label:`$t:${re}.login_two_factor.param_body`,widget:"key-value"}],build:{handler:"loginTwoFactor",params:{body:"{{body}}"}}},loginTwoFactorResend:{label:`$t:${re}.login_two_factor_resend.label`,params:[{key:"body",label:`$t:${re}.login_two_factor_resend.param_body`,widget:"key-value"}],build:{handler:"loginTwoFactorResend",params:{body:"{{body}}"}}},logout:{label:`$t:${re}.logout.label`,params:[{key:"target",label:`$t:${re}.logout.param_target`,widget:"text"}],build:{handler:"logout",target:"{{target}}"}},setLocale:{label:`$t:${re}.set_locale.label`,params:[{key:"target",label:`$t:${re}.set_locale.param_target`,widget:"locale-picker",required:!0}],build:{handler:"setLocale",target:"{{target}}"}},emitEvent:{label:`$t:${re}.emit_event.label`,params:[{key:"event",label:`$t:${re}.emit_event.param_event`,widget:"text",required:!0},{key:"data",label:`$t:${re}.emit_event.param_data`,widget:"data-chip"}],build:{handler:"emitEvent",params:{event:"{{event}}",data:"{{data}}"}}},apiCall:{label:`$t:${re}.api_call.label`,params:[{key:"target",label:`$t:${re}.api_call.param_target`,widget:"page-picker",required:!0},{key:"method",label:`$t:${re}.api_call.param_method`,widget:"select",options:[{value:"GET"},{value:"POST"},{value:"PUT"},{value:"PATCH"},{value:"DELETE"}]},{key:"body",label:`$t:${re}.api_call.param_body`,widget:"key-value"},{key:"query",label:`$t:${re}.api_call.param_query`,widget:"key-value"},{key:"identity_target_email",label:`$t:${re}.api_call.param_identity_target_email`,widget:"data-chip"},{key:"identity_target_phone",label:`$t:${re}.api_call.param_identity_target_phone`,widget:"data-chip"},{key:"onSuccess",label:`$t:${re}.api_call.param_on_success`,widget:"action-list"},{key:"onError",label:`$t:${re}.api_call.param_on_error`,widget:"action-list"}],build:{handler:"apiCall",target:"{{target}}",identity_target:{email:"{{identity_target_email}}",phone:"{{identity_target_phone}}"},onSuccess:"{{onSuccess}}",onError:"{{onError}}",params:{method:"{{method}}",body:"{{body}}",query:"{{query}}"}}},conditions:{label:`$t:${re}.conditions.label`,params:[{key:"branches",label:`$t:${re}.conditions.param_branches`,widget:"branch-list"}],build:{handler:"conditions",conditions:"{{branches}}"}},sequence:{label:`$t:${re}.sequence.label`,params:[{key:"actions",label:`$t:${re}.sequence.param_actions`,widget:"action-list"}],build:{handler:"sequence",params:{actions:"{{actions}}"}}},parallel:{label:`$t:${re}.parallel.label`,params:[{key:"actions",label:`$t:${re}.parallel.param_actions`,widget:"action-list"}],build:{handler:"parallel",params:{actions:"{{actions}}"}}},switch:{label:`$t:${re}.switch.label`,params:[{key:"value",label:`$t:${re}.switch.param_value`,widget:"data-chip"},{key:"cases",label:`$t:${re}.switch.param_cases`,widget:"action-list",advanced:!0}],build:{handler:"switch",params:{value:"{{value}}",cases:"{{cases}}"}}},suppress:{label:`$t:${re}.suppress.label`,params:[],build:{handler:"suppress"}}};function e8(){return{actionRecipes:bn,initActionRecipes:bn,errorRecipes:{navigate:bn.navigate,openModal:bn.openModal,toast:bn.toast,setState:bn.setState,sequence:bn.sequence,parallel:bn.parallel,showErrorPage:{label:`$t:${re}.show_error_page.label`,params:[{key:"target",label:`$t:${re}.show_error_page.param_target`,widget:"select",options:[{value:"content"},{value:"full"}]}],build:{handler:"showErrorPage",params:{target:"{{target}}"}}}}}}function nl(e,t){return typeof e.label=="string"?e.label.startsWith("$t:")?t(e.label.slice(3)):e.label:String(e.value)}function wi(e){return Array.isArray(e.options)?e.options:[]}function t8({control:e,value:t,onChange:n,t:o}){const r=wi(e);return i.jsx("div",{className:"g7le-widget g7le-widget--segmented","data-testid":"g7le-widget-segmented",style:f8,children:r.map(s=>{const a=s.value===t;return i.jsx("button",{type:"button","data-testid":`g7le-segment-${String(s.value)}`,"data-active":a?"true":"false",onClick:()=>n(a?void 0:s.value),style:{...x8,background:a?"#2563eb":"#fff",color:a?"#fff":"#0f172a",borderColor:a?"#2563eb":"#cbd5e1"},children:nl(s,o)},String(s.value))})})}function n8({control:e,value:t,onChange:n,t:o}){const r=Array.isArray(e.scale)?e.scale:[],s=r.findIndex(l=>l===t),a=t!=null;return i.jsxs("div",{className:"g7le-widget g7le-widget--slider","data-testid":"g7le-widget-slider",style:Bg,children:[i.jsxs("label",{style:ol,children:[i.jsx("input",{type:"checkbox","data-testid":"g7le-slider-enabled",checked:a,onChange:l=>{l.target.checked?n(r.length>0?r[Math.max(0,s===-1?0:s)]:void 0):n(void 0)}}),i.jsx("span",{style:{fontSize:12,color:"#64748b"},children:o("layout_editor.control.use")})]}),i.jsx("input",{type:"range","data-testid":"g7le-slider-range",min:0,max:Math.max(0,r.length-1),step:1,disabled:!a||r.length===0,value:s===-1?0:s,onChange:l=>{const d=Number(l.target.value);n(r[d])},style:{flex:1}}),i.jsx("span",{"data-testid":"g7le-slider-value",style:{fontSize:12,color:"#0f172a",minWidth:48,textAlign:"right"},children:a?String(t):o("layout_editor.control.default")})]})}function o8({control:e,value:t,onChange:n,t:o}){const r=wi(e);return i.jsxs("select",{className:"g7le-widget g7le-widget--select","data-testid":"g7le-widget-select",value:t==null?"":String(t),onChange:s=>{const a=s.target.value;if(a===""){n(void 0);return}const l=r.find(d=>String(d.value)===a);n(l?l.value:a)},style:w8,children:[i.jsx("option",{value:"",children:o("layout_editor.control.default")}),r.map(s=>i.jsx("option",{value:String(s.value),children:nl(s,o)},String(s.value)))]})}function r8({control:e,value:t,onChange:n}){const o=wi(e),r=o[1]?.value??!0,s=o[0]?.value??void 0,a=t===r;return i.jsx("button",{type:"button",className:"g7le-widget g7le-widget--toggle","data-testid":"g7le-widget-toggle",role:"switch","aria-checked":a,onClick:()=>n(a?s:r),style:{...k8,background:a?"#2563eb":"#cbd5e1"},children:i.jsx("span",{style:{...S8,transform:a?"translateX(18px)":"translateX(0)"}})})}function i8({control:e,value:t,onChange:n,t:o,freeValueDisabled:r}){const s=wi(e),a=t==null?"":String(t),[l,d]=u.useState(a);u.useEffect(()=>{d(a)},[a]);const c=p=>{const f=p.trim();if(f===""){n(void 0);return}n(f)};return i.jsxs("div",{className:"g7le-widget g7le-widget--dimension","data-testid":"g7le-widget-dimension",style:g8,children:[r?i.jsx("div",{"data-testid":"g7le-dimension-free-disabled",style:v8,children:o("layout_editor.property_modal.dark_preset_only")}):i.jsxs("div",{style:h8,children:[i.jsx("input",{type:"text","data-testid":"g7le-dimension-input",value:l,placeholder:o("layout_editor.control.dimension.placeholder"),onChange:p=>d(p.target.value),onBlur:p=>c(p.target.value),onKeyDown:p=>{p.key==="Enter"&&(p.preventDefault(),c(p.target.value))},style:y8}),i.jsx("button",{type:"button","data-testid":"g7le-dimension-clear",title:o("layout_editor.control.default"),onClick:()=>{d(""),n(void 0)},style:b8,children:o("layout_editor.control.default")})]}),s.length>0&&i.jsx("div",{style:m8,"data-testid":"g7le-dimension-chips",children:s.map(p=>{const f=String(p.value),b=f===a;return i.jsx("button",{type:"button","data-testid":`g7le-dimension-chip-${f}`,"data-active":b?"true":"false",onClick:()=>{d(f),n(f)},style:{..._8,background:b?"#2563eb":"#fff",color:b?"#fff":"#0f172a",borderColor:b?"#2563eb":"#cbd5e1"},children:nl(p,o)},f)})})]})}function s8(e){return[{key:"t",infix:`${e}t-`,labelKey:"layout_editor.control.spacing.top"},{key:"r",infix:`${e}r-`,labelKey:"layout_editor.control.spacing.right"},{key:"b",infix:`${e}b-`,labelKey:"layout_editor.control.spacing.bottom"},{key:"l",infix:`${e}l-`,labelKey:"layout_editor.control.spacing.left"}]}function a8(e,t,n,o){const r={all:-1,sides:{}};if(typeof e!="string"||e.trim()==="")return r;const s=e.split(/\s+/).filter(a=>a.length>0);for(const a of s){const l=n.find(d=>a.startsWith(d.infix));if(l){r.sides[l.key]=o.indexOf(a.slice(l.infix.length));continue}if(a.startsWith(`${t}x-`)){const d=o.indexOf(a.slice(`${t}x-`.length));r.sides.l=d,r.sides.r=d;continue}if(a.startsWith(`${t}y-`)){const d=o.indexOf(a.slice(`${t}y-`.length));r.sides.t=d,r.sides.b=d;continue}a.startsWith(`${t}-`)&&(r.all=o.indexOf(a.slice(`${t}-`.length)))}return r}function l8({control:e,value:t,onChange:n,t:o}){const r=typeof e.spacingPrefix=="string"?e.spacingPrefix:"p",s=(Array.isArray(e.scale)?e.scale:[]).map(y=>String(y)),a=s8(r),l=a8(t,r,a,s),d=Object.values(l.sides).some(y=>y>=0),c=l.all>=0||d,[p,f]=u.useState(d);u.useEffect(()=>{d&&f(!0)},[d]);const b=Math.min(4,Math.max(0,s.length-1)),g=y=>{const _=[];for(const w of a){const k=y[w.key];k!==void 0&&k>=0&&_.push(`${w.infix}${s[k]}`)}n(_.length>0?_.join(" "):void 0)},m=y=>{n(y>=0?`${r}-${s[Math.max(0,Math.min(y,s.length-1))]}`:void 0)},h=()=>({...l.sides}),v=(y,_,w,k,x)=>{const $=w>=0;return i.jsxs("div",{style:p8,"data-testid":y,children:[i.jsxs("label",{style:{...ol,minWidth:64},children:[i.jsx("input",{type:"checkbox","data-testid":`${y}-enabled`,checked:$,onChange:S=>x(S.target.checked)}),i.jsx("span",{style:{fontSize:12,color:"#0f172a"},children:o(_)})]}),i.jsx("input",{type:"range","data-testid":`${y}-range`,min:0,max:Math.max(0,s.length-1),step:1,disabled:!$||s.length===0,value:w<0?0:w,onChange:S=>k(Number(S.target.value)),style:{flex:1}}),i.jsx("span",{"data-testid":`${y}-value`,style:{fontSize:12,color:$?"#0f172a":"#94a3b8",minWidth:28,textAlign:"right"},children:$?s[w]:"–"})]},y)};return i.jsxs("div",{className:"g7le-widget g7le-widget--spacing","data-testid":"g7le-widget-spacing",style:d8,children:[i.jsxs("div",{style:c8,children:[i.jsxs("div",{style:u8,"data-testid":"g7le-spacing-mode",children:[i.jsx("button",{type:"button","data-testid":"g7le-spacing-mode-all","data-active":p?"false":"true",onClick:()=>{f(!1),d&&n(void 0)},style:{...Og,background:p?"#fff":"#2563eb",color:p?"#0f172a":"#fff",borderColor:p?"#cbd5e1":"#2563eb"},children:o("layout_editor.control.spacing.mode_all")}),i.jsx("button",{type:"button","data-testid":"g7le-spacing-mode-sides","data-active":p?"true":"false",onClick:()=>{if(f(!0),l.all>=0){const y={};for(const _ of a)y[_.key]=l.all;g(y)}},style:{...Og,background:p?"#2563eb":"#fff",color:p?"#fff":"#0f172a",borderColor:p?"#2563eb":"#cbd5e1"},children:o("layout_editor.control.spacing.mode_sides")})]}),i.jsx("span",{"data-testid":"g7le-spacing-value",style:{fontSize:11,color:"#64748b",minWidth:80,textAlign:"right"},children:c?String(t):o("layout_editor.control.default")})]}),p?i.jsx("div",{"data-testid":"g7le-spacing-sides",style:{display:"flex",flexDirection:"column",gap:4},children:a.map(y=>v(`g7le-spacing-side-${y.key}`,y.labelKey,l.sides[y.key]??-1,_=>{const w=h();w[y.key]=_,g(w)},_=>{const w=h();_?w[y.key]=l.sides[y.key]>=0?l.sides[y.key]:b:delete w[y.key],g(w)}))}):i.jsxs("div",{style:Bg,children:[i.jsxs("label",{style:{...ol,minWidth:64},children:[i.jsx("input",{type:"checkbox","data-testid":"g7le-spacing-all-enabled",checked:l.all>=0,onChange:y=>m(y.target.checked?b:-1)}),i.jsx("span",{style:{fontSize:12,color:"#64748b"},children:o("layout_editor.control.spacing.all")})]}),i.jsx("input",{type:"range","data-testid":"g7le-spacing-all-range",min:0,max:Math.max(0,s.length-1),step:1,disabled:l.all<0||s.length===0,value:l.all<0?0:l.all,onChange:y=>m(Number(y.target.value)),style:{flex:1}}),i.jsx("span",{"data-testid":"g7le-spacing-all-value",style:{fontSize:12,color:l.all>=0?"#0f172a":"#94a3b8",minWidth:28,textAlign:"right"},children:l.all>=0?s[l.all]:"–"})]})]})}const d8={display:"flex",flexDirection:"column",gap:6,width:"100%"},c8={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},u8={display:"inline-flex",gap:0,border:"1px solid #cbd5e1",borderRadius:6,overflow:"hidden"},Og={padding:"3px 10px",fontSize:11,border:"none",borderRight:"1px solid #e2e8f0",cursor:"pointer"},p8={display:"flex",alignItems:"center",gap:8,width:"100%"},f8={display:"inline-flex",gap:0,border:"1px solid #cbd5e1",borderRadius:6,overflow:"hidden"},g8={display:"flex",flexDirection:"column",gap:6,width:"100%"},h8={display:"flex",gap:6,alignItems:"center"},y8={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:80},b8={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer",whiteSpace:"nowrap"},m8={display:"flex",flexWrap:"wrap",gap:4},v8={fontSize:11,color:"#94a3b8",fontStyle:"italic",padding:"2px 0"},_8={padding:"3px 9px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:999,background:"#fff",cursor:"pointer"},x8={padding:"4px 10px",fontSize:12,border:"none",borderRight:"1px solid #e2e8f0",cursor:"pointer"},Bg={display:"flex",alignItems:"center",gap:8,width:"100%"},ol={display:"inline-flex",alignItems:"center",gap:4},w8={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",minWidth:120},k8={position:"relative",width:38,height:20,borderRadius:10,border:"none",cursor:"pointer",padding:2,display:"inline-flex",alignItems:"center",transition:"background 120ms ease"},S8={display:"block",width:16,height:16,borderRadius:8,background:"#fff",transition:"transform 120ms ease"},C8=["#0f172a","#334155","#64748b","#94a3b8","#e2e8f0","#ffffff","#dc2626","#ea580c","#d97706","#16a34a","#0891b2","#2563eb","#7c3aed","#db2777"],Wg=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function $8(e){return Array.isArray(e.options)?e.options.filter(t=>typeof t.value=="string").map(t=>({value:t.value,swatch:typeof t.swatch=="string"?t.swatch:void 0,label:typeof t.label=="string"?t.label:void 0})):[]}function E8({control:e,value:t,onChange:n,t:o,freeValueDisabled:r}){const s=$8(e),a=s.length>0,l=typeof t=="string"&&s.some(g=>g.value===t)?t:"",d=typeof t=="string"&&Wg.test(t)?t:"",[c,p]=u.useState(d);u.useEffect(()=>{p(d)},[d]);const f=g=>{const m=g.trim();if(m===""){n(void 0);return}const h=m.startsWith("#")?m:`#${m}`;Wg.test(h)&&n(h)},b=C8;return i.jsxs("div",{className:"g7le-widget g7le-widget--color","data-testid":"g7le-widget-color",style:I8,children:[r?i.jsx("div",{"data-testid":"g7le-color-free-disabled",style:M8,children:o("layout_editor.property_modal.dark_preset_only")}):i.jsxs("div",{style:A8,children:[i.jsxs("label",{style:T8,children:[i.jsx("span",{"data-testid":"g7le-color-swatch",style:{...D8,background:d||"transparent",backgroundImage:d?void 0:"linear-gradient(45deg,#e2e8f0 25%,transparent 25%,transparent 75%,#e2e8f0 75%),linear-gradient(45deg,#e2e8f0 25%,#fff 25%,#fff 75%,#e2e8f0 75%)",backgroundSize:"8px 8px",backgroundPosition:"0 0, 4px 4px"}}),i.jsx("input",{type:"color","data-testid":"g7le-color-native",value:d||"#000000",onChange:g=>n(g.target.value),style:{width:0,height:0,opacity:0,position:"absolute"}})]}),i.jsx("input",{type:"text","data-testid":"g7le-color-hex",value:c,placeholder:o("layout_editor.control.color_hex_placeholder"),onChange:g=>p(g.target.value),onBlur:g=>f(g.target.value),onKeyDown:g=>{g.key==="Enter"&&f(g.target.value)},style:z8}),i.jsx("button",{type:"button","data-testid":"g7le-color-clear",onClick:()=>n(void 0),style:N8,children:o("layout_editor.control.default")})]}),a?i.jsx("div",{style:jg,"data-testid":"g7le-color-token-presets",children:s.map(g=>{const m=l===g.value,h=g.label?g.label.startsWith("$t:")?o(g.label.slice(3)):g.label:g.value;return i.jsx("button",{type:"button","aria-label":h,title:h,"data-testid":`g7le-color-token-${g.value}`,"data-active":m?"true":"false",onClick:()=>n(m?void 0:g.value),style:{...Hg,background:g.swatch||"#e2e8f0",outline:m?"2px solid #2563eb":"none"}},g.value)})}):!r&&i.jsx("div",{style:jg,"data-testid":"g7le-color-presets",children:b.map(g=>i.jsx("button",{type:"button","aria-label":g,"data-testid":`g7le-color-preset-${g}`,onClick:()=>n(g),style:{...Hg,background:g,outline:d.toLowerCase()===g.toLowerCase()?"2px solid #2563eb":"none"}},g))})]})}const I8={display:"flex",flexDirection:"column",gap:8},A8={display:"flex",alignItems:"center",gap:6},T8={position:"relative",display:"inline-flex",cursor:"pointer"},D8={width:24,height:24,borderRadius:4,border:"1px solid #cbd5e1",display:"inline-block"},z8={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,fontFamily:"monospace"},N8={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",cursor:"pointer",color:"#64748b"},jg={display:"grid",gridTemplateColumns:"repeat(7, 1fr)",gap:4},Hg={width:"100%",height:18,borderRadius:4,border:"1px solid #cbd5e1",cursor:"pointer",padding:0},M8={fontSize:11,color:"#94a3b8",fontStyle:"italic",padding:"2px 0"},tr=[{value:"fill",labelKey:"layout_editor.control.background_image.mode_fill",size:"cover",repeat:"no-repeat"},{value:"fit",labelKey:"layout_editor.control.background_image.mode_fit",size:"contain",repeat:"no-repeat"},{value:"tile",labelKey:"layout_editor.control.background_image.mode_tile",size:"auto",repeat:"repeat"}];function L8(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Fg(e){return tr.find(n=>n.size===e.size&&n.repeat===e.repeat)?.value??"fill"}function P8({value:e,onChange:t,t:n}){const o=L8(e),{state:r}=Qe(),s=bo(),[a,l]=u.useState(!1),[d,c]=u.useState(null),[p,f]=u.useState(o.url??""),[b,g]=u.useState([]),m=u.useRef(null),h=r.templateIdentifier,v=r.selectedRoute?.layoutName??"";u.useEffect(()=>{f(o.url??"")},[o.url]);const y=u.useCallback(async()=>{if(!h||!v){g([]);return}const S=await Ll(h,v);S.ok&&g(S.data)},[h,v]);u.useEffect(()=>{y()},[y]);const _=S=>{if(!S){t(void 0);return}const C=tr.find(T=>T.value===Fg(o))??tr[0];t({url:S,size:o.size??C.size,repeat:o.repeat??C.repeat,position:o.position??"center"})},w=S=>{const C=tr.find(T=>T.value===S);!C||!o.url||t({url:o.url,size:C.size,repeat:C.repeat,position:o.position??"center"})},k=async S=>{const C=S.target.files?.[0];if(!C)return;l(!0),c(null);const T=await Pl(h,v,C);T.ok?(_(T.data.url),y()):c(n("layout_editor.control.background_image.upload_failed")),l(!1),m.current&&(m.current.value="")},x=async S=>{(await Ol(S.id)).ok&&g(T=>T.filter(E=>E.id!==S.id))},$=()=>{const S=s.open({ariaLabel:n("layout_editor.attachment_manager.title"),width:720,maxHeightRatio:.82,content:u.createElement(Bl,{templateIdentifier:h,layoutName:v,t:n,onSelect:C=>{_(C),s.close(S)},onChanged:()=>{y()},onClose:()=>s.close(S)})})};return i.jsxs("div",{className:"g7le-widget g7le-widget--image","data-testid":"g7le-widget-image",style:O8,children:[o.url&&i.jsx("div",{"data-testid":"g7le-image-preview",style:{...B8,backgroundImage:`url(${o.url})`,backgroundSize:o.size??"cover",backgroundRepeat:o.repeat??"no-repeat",backgroundPosition:o.position??"center"}}),i.jsxs("div",{style:W8,children:[i.jsxs("label",{style:j8,children:[a?"…":n("layout_editor.control.background_image.upload"),i.jsx("input",{ref:m,type:"file",accept:"image/*","data-testid":"g7le-image-file",onChange:k,disabled:a,style:{display:"none"}})]}),i.jsx("button",{type:"button","data-testid":"g7le-image-clear",onClick:()=>t(void 0),style:H8,children:n("layout_editor.control.background_image.clear")})]}),i.jsx("input",{type:"text","data-testid":"g7le-image-url",placeholder:"https://… / URL",value:p,onChange:S=>f(S.target.value),onBlur:S=>_(S.target.value.trim()||void 0),style:F8}),i.jsx("div",{style:K8,"data-testid":"g7le-image-modes",children:tr.map(S=>{const C=Fg(o)===S.value;return i.jsx("button",{type:"button","data-testid":`g7le-image-mode-${S.value}`,"data-active":C?"true":"false",disabled:!o.url,onClick:()=>w(S.value),style:{...V8,background:C&&o.url?"#2563eb":"#fff",color:C&&o.url?"#fff":"#0f172a"},children:n(S.labelKey)},S.value)})}),i.jsxs("div",{style:U8,"data-testid":"g7le-image-gallery",children:[i.jsxs("div",{style:q8,children:[i.jsx("span",{style:{fontSize:11,color:"#64748b"},children:n("layout_editor.attachment_manager.recent")}),i.jsxs("button",{type:"button","data-testid":"g7le-image-manage",onClick:$,style:G8,children:["🖼 ",n("layout_editor.attachment_manager.manage_link")]})]}),b.length>0?i.jsx("div",{style:Y8,"data-testid":"g7le-image-thumbs",children:b.slice(0,8).map(S=>i.jsxs("div",{style:X8,"data-testid":`g7le-image-thumb-${S.id}`,children:[i.jsx("button",{type:"button",title:S.original_name,onClick:()=>_(S.url),style:{...J8,backgroundImage:`url(${S.url})`},"data-testid":`g7le-image-thumb-use-${S.id}`}),i.jsx("button",{type:"button",title:n("layout_editor.attachment_manager.delete"),onClick:()=>x(S),style:Z8,"data-testid":`g7le-image-thumb-del-${S.id}`,children:"✕"})]},S.id))}):i.jsx("span",{style:{fontSize:11,color:"#94a3b8"},children:n("layout_editor.attachment_manager.empty")})]}),d&&i.jsx("span",{"data-testid":"g7le-image-error",style:{fontSize:11,color:"#dc2626"},children:d})]})}const O8={display:"flex",flexDirection:"column",gap:6},B8={width:"100%",height:80,borderRadius:6,border:"1px solid #cbd5e1"},W8={display:"flex",gap:6},j8={padding:"5px 10px",fontSize:12,border:"1px solid #2563eb",borderRadius:6,background:"#fff",color:"#2563eb",cursor:"pointer",display:"inline-flex",alignItems:"center"},H8={padding:"5px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"},F8={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},K8={display:"inline-flex",border:"1px solid #cbd5e1",borderRadius:6,overflow:"hidden"},V8={padding:"4px 10px",fontSize:12,border:"none",borderRight:"1px solid #e2e8f0",cursor:"pointer"},U8={display:"flex",flexDirection:"column",gap:4,border:"1px solid #e2e8f0",borderRadius:6,padding:6,marginTop:2},q8={display:"flex",alignItems:"center",justifyContent:"space-between"},G8={fontSize:11,color:"#2563eb",background:"transparent",border:"none",cursor:"pointer",padding:0},Y8={display:"flex",gap:6,flexWrap:"wrap"},X8={position:"relative",width:44,height:44},J8={width:44,height:44,borderRadius:6,border:"1px solid #cbd5e1",backgroundSize:"cover",backgroundPosition:"center",cursor:"pointer",padding:0},Z8={position:"absolute",top:-6,right:-6,width:16,height:16,borderRadius:"50%",border:"none",background:"#dc2626",color:"#fff",fontSize:9,lineHeight:"16px",cursor:"pointer",padding:0};function Q8(e){return Array.isArray(e)&&e.every(t=>t!==null&&typeof t=="object"&&!Array.isArray(t))}function R8(e){return typeof e=="string"&&/\{\{.*\}\}/.test(e)}function ez({value:e,onChange:t,t:n,bindingCandidates:o}){if(R8(e))return i.jsx("div",{className:"g7le-widget g7le-widget--options-list","data-testid":"g7le-widget-options-list-bound",style:lz,children:n("layout_editor.list_editor.bound_degraded")});const r=Q8(e)?e:[],s=b=>{t(b.length===0?void 0:b)},a=(b,g)=>{const m=r.map((h,v)=>v===b?{...h,...g}:h);s(m)},l=b=>{s(r.filter((g,m)=>m!==b))},d=(b,g)=>{const m=b+g;if(m<0||m>=r.length)return;const h=[...r];[h[b],h[m]]=[h[m],h[b]],s(h)},c=()=>{s([...r,{value:"",label:""}])},p=b=>typeof b.label=="string"?b.label:b.label==null?"":String(b.label),f=b=>b.value===void 0||b.value===null?"":String(b.value);return i.jsxs("div",{className:"g7le-widget g7le-widget--options-list","data-testid":"g7le-widget-options-list",style:tz,children:[r.length===0&&i.jsx("div",{"data-testid":"g7le-options-empty",style:az,children:n("layout_editor.list_editor.empty")}),r.map((b,g)=>i.jsxs("div",{"data-testid":`g7le-options-row-${g}`,style:nz,children:[i.jsxs("div",{style:Kg,children:[i.jsx("span",{style:Vg,children:n("layout_editor.list_editor.option_value")}),i.jsx("input",{type:"text","data-testid":`g7le-options-value-${g}`,value:f(b),placeholder:n("layout_editor.list_editor.option_value"),onChange:m=>a(g,{value:m.target.value}),style:rz})]}),i.jsxs("div",{style:Kg,children:[i.jsx("span",{style:Vg,children:n("layout_editor.list_editor.option_label")}),i.jsx("div",{"data-testid":`g7le-options-label-${g}`,style:{flex:1,minWidth:0},children:i.jsx(_t,{value:p(b),onChange:m=>a(g,{label:m??""}),t:n,placeholder:n("layout_editor.list_editor.option_label"),testidPrefix:`g7le-options-label-i18n-${g}`,candidates:o,enableExpressionTree:!0,expressionTreeCollapsible:!0})})]}),i.jsxs("div",{style:oz,children:[i.jsx("button",{type:"button","data-testid":`g7le-options-up-${g}`,title:n("layout_editor.list_editor.move_up"),disabled:g===0,onClick:()=>d(g,-1),style:Ug,children:"↑"}),i.jsx("button",{type:"button","data-testid":`g7le-options-down-${g}`,title:n("layout_editor.list_editor.move_down"),disabled:g===r.length-1,onClick:()=>d(g,1),style:Ug,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-options-remove-${g}`,title:n("layout_editor.list_editor.remove"),onClick:()=>l(g),style:iz,children:"✕"})]})]},g)),i.jsx("button",{type:"button","data-testid":"g7le-options-add",onClick:c,style:sz,children:n("layout_editor.list_editor.add")})]})}const tz={display:"flex",flexDirection:"column",gap:8,width:"100%"},nz={display:"flex",flexDirection:"column",gap:4,width:"100%",minWidth:0,paddingBottom:6,borderBottom:"1px solid #f1f5f9"},Kg={display:"flex",gap:6,alignItems:"center",width:"100%",minWidth:0},Vg={flexShrink:0,width:36,fontSize:11,color:"#94a3b8",textAlign:"right"},oz={display:"flex",gap:4,alignItems:"center",justifyContent:"flex-end"},rz={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},Ug={padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},iz={padding:"2px 6px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},sz={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},az={fontSize:11,color:"#94a3b8",fontStyle:"italic"},lz={fontSize:11,color:"#b45309",fontStyle:"italic",padding:"4px 2px"},qg=/[^A-Za-z0-9\-_:.]/g;function dz(e){return typeof e=="string"&&Yi(e)}function Gg(e){return Yi(e)?In(e).map(t=>t.kind==="binding"?t.raw:t.raw.replace(qg,"")).join(""):e.replace(qg,"")}const cz={width:"100%",padding:"6px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:4,fontFamily:"monospace"},uz={marginTop:4,fontSize:11,color:"#94a3b8"},pz={display:"flex",gap:6,alignItems:"center"},fz={flexShrink:0,padding:"5px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:4,background:"#f8fafc",cursor:"pointer",whiteSpace:"nowrap"};function gz({value:e,onChange:t,t:n,bindingCandidates:o}){const r=e==null?"":String(e),s=dz(e),a=!!o&&o.length>0,[l,d]=u.useState(!1),c=p=>{const f=Gg(p);t(f===""?void 0:f)};return s||l?i.jsxs("div",{"data-testid":"g7le-core-id-chip",children:[i.jsx(_s,{value:r,onChange:c,t:n,candidates:o,onDone:()=>d(!1),testidPrefix:"g7le-core-id-chip-input"}),i.jsx("div",{style:uz,children:n("layout_editor.core_props.id.binding_hint")})]}):i.jsx("div",{children:i.jsxs("div",{style:pz,children:[i.jsx("input",{type:"text",className:"g7le-widget g7le-widget--core-id","data-testid":"g7le-widget-core-id",value:r,onChange:p=>{const f=Gg(p.target.value);t(f===""?void 0:f)},spellCheck:!1,autoComplete:"off",style:cz}),a&&i.jsxs("button",{type:"button","data-testid":"g7le-core-id-add-data",onClick:()=>d(!0),style:fz,title:n("layout_editor.core_props.id.add_data"),children:["🔗 ",n("layout_editor.core_props.id.add_data")]})]})})}const hz=/[^A-Za-z0-9.\-_]/g;function yz(e){return typeof e=="string"&&/\{\{[\s\S]*?\}\}/.test(e)}function bz(e){return e.replace(hz,"")}const Yg={width:"100%",padding:"6px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:4,fontFamily:"monospace",boxSizing:"border-box"},mz={...Yg,background:"#f1f5f9",color:"#64748b",cursor:"not-allowed"},Xg={marginTop:4,fontSize:11,color:"#94a3b8"};function vz({value:e,onChange:t,t:n}){const o=e==null?"":String(e);return yz(e)?i.jsxs("div",{"data-testid":"g7le-core-datakey-bound",children:[i.jsx("input",{type:"text",className:"g7le-widget g7le-widget--core-datakey-bound","data-testid":"g7le-widget-core-datakey",value:o,readOnly:!0,disabled:!0,style:mz}),i.jsx("div",{style:Xg,children:n("layout_editor.core_props.dataKey.bound_degraded")})]}):i.jsxs("div",{children:[i.jsx("input",{type:"text",className:"g7le-widget g7le-widget--core-datakey","data-testid":"g7le-widget-core-datakey",value:o,placeholder:n("layout_editor.core_props.dataKey.placeholder"),onChange:s=>{const a=bz(s.target.value);t(a===""?void 0:a)},spellCheck:!1,autoComplete:"off",style:Yg}),i.jsx("div",{style:Xg,children:n("layout_editor.core_props.dataKey.hint")})]})}let Jg=!1;function _z(){Jg||(Ze("segmented",t8),Ze("slider",n8),Ze("select",o8),Ze("dimension",i8),Ze("spacing",l8),Ze("toggle",r8),Ze("color",E8),Ze("image",P8),Ze("tag-input",vs),Ze("page-picker",P0),Ze("datasource-picker",Fc),Ze("binding-picker",Fc),Ze("binding-list",W0),Ze("state-key-picker",Ts),Ze("modal-picker",O0),Ze("i18n-text",B0),Ze("text",j0),Ze("options-list",ez),Ze("core-id",gz),Ze("core-datakey",vz),Ze("component-target-picker",p4),Jg=!0)}function nr(e){return Array.isArray(e.children)?e.children:[]}function or(e){if(typeof e.text=="string")return[];let t=null;const n=(o,r)=>{const s=nr(o);for(let a=0;ad===o?rr(l,r,n):l);return{...e,children:a}}function Zg(e,t){const n=r=>typeof r.props?.[t]=="string";if(n(e))return[];const o=(r,s)=>{const a=nr(r);for(let l=0;lc===r?Qg(d,s,n,o):d);return{...e,children:l}}function xz(e){return Array.isArray(e.children)?e.children:[]}function wz(e){const t=e?.itemFields;if(!Array.isArray(t))return[{kind:"text"}];const n=[];for(const o of t){if(!o||typeof o!="object")continue;const r=o;r.kind==="text"?n.push({kind:"text",label:typeof r.label=="string"?r.label:void 0}):r.kind==="prop"&&typeof r.prop=="string"&&r.prop.length>0&&n.push({kind:"prop",prop:r.prop,label:typeof r.label=="string"?r.label:void 0})}return n.length>0?n:[{kind:"text"}]}function rl(e,t){if(!(typeof e!="string"||e.length===0))return e.startsWith("$t:")?t(e.slice(3)):e}function Rg({node:e,params:t,spec:n,manifest:o,t:r,onPatchNode:s,templateIdentifier:a,candidates:l}){const d=typeof t?.childComponent=="string"?t.childComponent:null,c=t?.childTemplate&&typeof t.childTemplate=="object"?t.childTemplate:null,p=wz(t),f=rl(typeof t?.childLabel=="string"?t.childLabel:void 0,r)??d??"",b=xz(e),g=u.useCallback(x=>{s({...e,children:x})},[e,s]),m=u.useCallback(()=>{if(c)return JSON.parse(JSON.stringify(c));if(!d)return null;const x=n?.componentPalette?.entries?.[d];if(x?.defaultNode&&typeof x.defaultNode=="object")return JSON.parse(JSON.stringify(x.defaultNode));const $=o?.components??{};let S=null;for(const C of Object.values($))if(Array.isArray(C)){const T=C.find(E=>E.name===d);if(T){S=T;break}}return S?zf(S):{type:"basic",name:d}},[c,d,n,o]),h=u.useCallback(()=>{const x=m();if(x){if(x.text==="")x.text=r("layout_editor.list_editor.new_item");else{const $=or(x);if($!==null&&$.length>0){const S=ki(x,$);if(S&&S.text===""){const C=rr(x,$,r("layout_editor.list_editor.new_item"));g([...b,C]);return}}}g([...b,x])}},[m,g,b,r]),v=u.useCallback(x=>{g(b.filter(($,S)=>S!==x))},[g,b]),y=u.useCallback((x,$)=>{const S=x+$;if(S<0||S>=b.length)return;const C=[...b];[C[x],C[S]]=[C[S],C[x]],g(C)},[g,b]),_=u.useCallback((x,$)=>{if(typeof $!="string"||$.length===0)return;const S=b[x];if(!S)return;const C=or(S);if(C===null)return;const T=b.map((E,A)=>A===x?rr(E,C,$):E);g(T)},[b,g]),w=u.useCallback((x,$,S)=>{if(typeof S!="string"||S.length===0)return;const C=b[x];if(!C)return;const T=Zg(C,$);if(T===null)return;const E=b.map((A,N)=>N===x?Qg(A,T,$,S):A);g(E)},[b,g]);if(!d&&!c)return i.jsx("div",{className:"g7le-node-editor g7le-node-editor--children","data-testid":"g7le-children-editor-misconfigured",style:nh,children:r("layout_editor.list_editor.no_child_component")});const k=p.length>1||p.some(x=>x.label);return i.jsxs("div",{className:"g7le-node-editor g7le-node-editor--children","data-testid":"g7le-children-editor",style:kz,children:[i.jsx("div",{style:Sz,children:r("layout_editor.list_editor.items_title")}),b.length===0&&i.jsx("div",{"data-testid":"g7le-children-empty",style:nh,children:r("layout_editor.list_editor.empty")}),b.map((x,$)=>{const S=[];for(const T of p)if(T.kind==="text"){const E=or(x),A=E!==null?ki(x,E):null;A&&typeof A.text=="string"&&S.push({key:"text",caption:rl(T.label,r)??(k?r("layout_editor.list_editor.item_label"):void 0),value:A.text,onChange:N=>_($,N),testid:`g7le-children-i18n-${$}`})}else if(T.kind==="prop"&&T.prop){const E=Zg(x,T.prop);if(E!==null){const N=ki(x,E)?.props?.[T.prop];S.push({key:`prop-${T.prop}`,caption:rl(T.label,r)??T.prop,value:typeof N=="string"?N:"",onChange:D=>w($,T.prop,D),testid:`g7le-children-prop-${T.prop}-${$}`})}}const C=typeof x?.name=="string"?x.name:r("layout_editor.list_editor.item");return i.jsxs("div",{"data-testid":`g7le-children-row-${$}`,style:Cz,children:[S.length>0?S.map(T=>i.jsx("div",{style:eh,children:i.jsxs("div",{"data-testid":T.key==="text"?`g7le-children-text-${$}`:`g7le-children-field-${T.key}-${$}`,style:$z,children:[T.caption!==void 0&&i.jsx("div",{"data-testid":`g7le-children-caption-${T.key}-${$}`,style:Ez,children:T.caption}),i.jsx(_t,{value:T.value,onChange:T.onChange,t:r,placeholder:r("layout_editor.list_editor.item_text"),testidPrefix:T.testid,candidates:l,enableExpressionTree:!0,expressionTreeCollapsible:!0})]})},T.key)):i.jsx("div",{style:eh,children:i.jsx("span",{"data-testid":`g7le-children-label-${$}`,style:Az,children:C})}),i.jsxs("div",{style:Iz,children:[i.jsx("button",{type:"button","data-testid":`g7le-children-up-${$}`,title:r("layout_editor.list_editor.move_up"),disabled:$===0,onClick:()=>y($,-1),style:th,children:"↑"}),i.jsx("button",{type:"button","data-testid":`g7le-children-down-${$}`,title:r("layout_editor.list_editor.move_down"),disabled:$===b.length-1,onClick:()=>y($,1),style:th,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-children-remove-${$}`,title:r("layout_editor.list_editor.remove"),onClick:()=>v($),style:Tz,children:"✕"})]})]},$)}),i.jsx("button",{type:"button","data-testid":"g7le-children-add",onClick:h,style:Dz,children:r("layout_editor.list_editor.add_child",{component:f})})]})}const kz={display:"flex",flexDirection:"column",gap:6,width:"100%",marginBottom:12},Sz={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:2},Cz={display:"flex",flexDirection:"column",gap:4,width:"100%",minWidth:0,paddingBottom:6,borderBottom:"1px solid #f1f5f9"},eh={display:"flex",gap:4,alignItems:"flex-start",width:"100%",minWidth:0},$z={flex:1,minWidth:0},Ez={fontSize:11,color:"#64748b",marginBottom:2},Iz={display:"flex",gap:4,alignItems:"center",justifyContent:"flex-end"},Az={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,color:"#475569",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},th={padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},Tz={padding:"2px 6px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},Dz={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},nh={fontSize:11,color:"#94a3b8",fontStyle:"italic"},go={rowContainer:"Tbody",row:"Tr",cell:"Td",headerCell:"Th",colSpanProp:"colSpan",rowSpanProp:"rowSpan"};function yt(e){return{rowContainer:e?.rowContainer??go.rowContainer,row:e?.row??go.row,cell:e?.cell??go.cell,headerCell:e?.headerCell??go.headerCell,colSpanProp:e?.colSpanProp??go.colSpanProp,rowSpanProp:e?.rowSpanProp??go.rowSpanProp}}function Bn(e){return e?Array.isArray(e.children)?e.children:[]:[]}function oh(e,t){const n=e.props?.[t],o=typeof n=="number"?n:typeof n=="string"?parseInt(n,10):NaN;return Number.isFinite(o)&&o>=1?Math.floor(o):1}function Pe(e,t){const n=yt(t),o=[],r=Bn(e),s=[];r.forEach((f,b)=>{(Bn(f).some(h=>h.name===n.row)||f.name===n.rowContainer||f.name==="Thead"||f.name==="Tfoot")&&s.push({container:f,containerIndex:b,isHeader:f.name==="Thead"})}),s.length===0&&r.some(f=>f.name===n.row)&&s.push({container:e,containerIndex:-1,isHeader:!1});const a=[],l=[];let d=0,c=0;const p=f=>{for(;a.length<=f;)a.push([]);return a[f]};s.forEach((f,b)=>{Bn(f.container).filter(m=>m.name===n.row).forEach((m,h)=>{const v=[],y=p(d);let _=0;Bn(m).filter(k=>k.name===n.cell||k.name===n.headerCell).forEach((k,x)=>{for(;y[_];)_++;const $=oh(k,n.colSpanProp),S=oh(k,n.rowSpanProp),C={cell:k,sectionIndex:b,rowIndexInSection:h,cellIndexInRow:x,gridRow:d,gridCol:_,colSpan:$,rowSpan:S,isHeader:k.name===n.headerCell};v.push(C);for(let T=0;T=0?(a.push(s.containerIndex),l=Bn(e)[s.containerIndex]??e):l=e;let d=-1,c=-1,p=null;const f=Bn(l);for(let m=0;m=r.gridRow&&t=r.gridCol&&nr){s=!0;break}if(s)break}s||t.add(r)}const n=Array.from(t).sort((r,s)=>r-s),o=[];for(let r=0;re.rows.find(l=>(l.cells[0]?.gridRow??-1)===a)?.sectionIndex??e.rows[a]?.sectionIndex??0,o=new Set([0,t]);for(let a=1;aa){l=!0;break}if(l)break}l||o.add(a)}const r=Array.from(o).sort((a,l)=>a-l),s=[];for(let a=0;at>=a.start&&t=o.length?{ok:!1,reason:"boundary"}:o[r].sectionIndex!==o[s].sectionIndex?{ok:!1,reason:"section"}:{ok:!0}}function Ci(e,t,n){const o=rh(e),r=o.findIndex(a=>t>=a.start&&t=o.length?{ok:!1,reason:"boundary"}:{ok:!0}}function Ge(e){return e?Array.isArray(e.children)?e.children:[]:[]}function mn(e,t,n){const o={...e.props??{}};n<=1?delete o[t]:o[t]=n;const r={...e,props:o};return Object.keys(o).length===0&&delete r.props,r}function $i(e,t,n=!1){const o={type:"basic",name:n?e.headerCell:e.cell},r=t?.props?.className;return typeof r=="string"&&r&&(o.props={className:r}),o.text="",o}function ir(e,t){return e.name===t.cell||e.name===t.headerCell}function nt(e,t,n,o){const r=t.sections[n];if(!r)return e;if(r.containerIndex===-1)return o(e);const s=Ge(e).map((a,l)=>l===r.containerIndex?o(a):a);return{...e,children:s}}function bt(e,t,n,o){let r=-1;const s=Ge(e).map(a=>a.name===t&&(r++,r===n)?o(a):a);return{...e,children:s}}function Ei(e,t,n){let o=-1;const r=Ge(e);for(let s=0;s0?nt(e,r,r.sections.length-1,_=>({..._,children:[...Ge(_),y]})):{...e,children:[...Ge(e),y]}}const s=Math.max(-1,Math.min(n,r.rows.length-1)),a=s<0?r.rows[0]:r.rows[s],l=a.cells[0]?.gridRow??s,d=s<0?0:l+1,c=a.sectionIndex,p=s<0?0:a.rowIndexInSection+1,f=[],b=[];let g=0;for(;g0?Ve(r,d-1,g):null;y&&y.gridRow+y.rowSpan>d&&y.rowSpan>1?(b.push(y),g+=y.colSpan):(f.push($i(o)),g+=1)}let m=e;for(const y of b)m=nt(m,r,y.sectionIndex,_=>bt(_,o.row,y.rowIndexInSection,w=>({...w,children:Ge(w).map((k,x)=>x===y.cellIndexInRow?mn(k,o.rowSpanProp,y.rowSpan+1):k)})));const h={type:"basic",name:o.row,children:f},v=Pe(m,t);return m=nt(m,v,c,y=>{const _=Ge(y);let w=0,k=_.length;for(let x=0;x<_.length;x++)if(_[x].name===o.row){if(w===p){k=x;break}w++}return{...y,children:[..._.slice(0,k),h,..._.slice(k)]}}),m}function sh(e,t,n){const o=yt(t),r=Pe(e,t);if(n<0||n>=r.rows.length||r.rows.length<=1)return e;const s=r.rows[n],a=s.cells[0]?.gridRow??n;let l=e;const d=new Set;for(let p=0;pbt(b,o.row,f.rowIndexInSection,g=>({...g,children:Ge(g).map((m,h)=>h===f.cellIndexInRow?mn(m,o.rowSpanProp,f.rowSpan-1):m)})))),p+=f?f.colSpan:1}const c=Pe(l,t);return l=nt(l,c,s.sectionIndex,p=>{let f=-1;const b=Ge(p).filter(g=>g.name===o.row?(f++,f!==s.rowIndexInSection):!0);return{...p,children:b}}),l}function ah(e,t,n,o){const r=yt(t),s=Pe(e,t);if(!Si(s,n,o).ok)return e;const a=ih(s),l=a.findIndex(h=>n>=h.start&&ns.rows.filter(v=>{const y=v.cells[0]?.gridRow??-1;return v.sectionIndex===f&&y>=h.start&&yv.rowIndexInSection),g=b(c),m=b(p);return g.length===0||m.length===0?e:nt(e,s,f,h=>{const v=[...Ge(h)],y=[];v.forEach((M,O)=>{M.name===r.row&&y.push(O)});const _=g.map(M=>y[M]).filter(M=>M!==void 0),w=m.map(M=>y[M]).filter(M=>M!==void 0);if(_.length===0||w.length===0)return h;const k=_.map(M=>v[M]),x=w.map(M=>v[M]),$=Math.min(..._)n>=m.start&&nk.gridCol>=f.start&&k.gridColk.gridCol>=b.start&&k.gridColk.cellIndexInRow),_=v.map(k=>k.cellIndexInRow),w=Pe(g,t);g=nt(g,w,m.sectionIndex,k=>bt(k,r.row,m.rowIndexInSection,x=>{const $=[...Ge(x)],S=y.map(M=>Ei(x,r,M)).filter(M=>M>=0),C=_.map(M=>Ei(x,r,M)).filter(M=>M>=0);if(S.length===0||C.length===0)return x;const T=S.map(M=>$[M]),E=C.map(M=>$[M]),A=Math.min(...S,...C),N=Math.max(...S,...C),D=[...E,...T],B=[...$.slice(0,A),...D,...$.slice(N+1)];return{...x,children:B}}))}return g}function dh(e,t,n){const o=yt(t),r=Pe(e,t);if(r.rows.length===0||r.colCount===0)return sl(e,t,-1);const s=Math.max(0,Math.min(n+1,r.colCount));let a=e;const l=new Set;for(const d of r.rows){const c=d.cells[0]?.gridRow??0,p=s>0?Ve(r,c,s-1):null,f=s1){if(!l.has(p.cell)){l.add(p.cell);const h=Pe(a,t);a=nt(a,h,p.sectionIndex,v=>bt(v,o.row,p.rowIndexInSection,y=>({...y,children:Ge(y).map((_,w)=>w===p.cellIndexInRow?mn(_,o.colSpanProp,p.colSpan+1):_)})))}continue}if(p&&p.gridRow0&&d.cells.every(h=>h.isHeader),m=Pe(a,t);a=nt(a,m,d.sectionIndex,h=>bt(h,o.row,d.rowIndexInSection,v=>{const y=[...Ge(v)];let _;if(b<0)_=y.findIndex(w=>ir(w,o)),_<0&&(_=y.length);else{const w=Ei(v,o,b);_=w<0?y.length:w+1}return y.splice(_,0,$i(o,void 0,g)),{...v,children:y}}))}return a}function ch(e,t,n){const o=yt(t),r=Pe(e,t);if(n<0||n>=r.colCount||r.colCount<=1)return e;let s=e;const a=new Set;for(const l of r.rows){const d=l.cells[0]?.gridRow??0,c=Ve(r,d,n);if(!(!c||a.has(c.cell)||c.gridRow1){const p=Pe(s,t);s=nt(s,p,c.sectionIndex,f=>bt(f,o.row,c.rowIndexInSection,b=>({...b,children:Ge(b).map((g,m)=>m===c.cellIndexInRow?mn(g,o.colSpanProp,c.colSpan-1):g)})))}else{const p=Pe(s,t);s=nt(s,p,c.sectionIndex,f=>bt(f,o.row,c.rowIndexInSection,b=>{let g=-1;const m=Ge(b).filter(h=>ir(h,o)?(g++,g!==c.cellIndexInRow):!0);return{...b,children:m}}))}}return s}function al(e,t,n,o,r,s){const a=yt(t),l=Pe(e,t),d=Math.min(n,r),c=Math.max(n,r),p=Math.min(o,s),f=Math.max(o,s);if(d===c&&p===f)return{table:e,ok:!1,reason:"single"};if(!l.valid)return{table:e,ok:!1,reason:"invalid-grid"};const b=new Set;for(let y=d;y<=c;y++)for(let _=p;_<=f;_++){const w=Ve(l,y,_);if(!w)return{table:e,ok:!1,reason:"hole"};if(w.gridRowc||w.gridCol+w.colSpan-1>f)return{table:e,ok:!1,reason:"not-rectangular"};b.add(w)}const g=Ve(l,d,p),m=Array.from(b).filter(y=>y!==g);let h=nt(e,l,g.sectionIndex,y=>bt(y,a.row,g.rowIndexInSection,_=>({..._,children:Ge(_).map((w,k)=>{if(k!==g.cellIndexInRow)return w;let x=mn(w,a.colSpanProp,f-p+1);return x=mn(x,a.rowSpanProp,c-d+1),x})})));const v=new Map;for(const y of m){const _=`${y.sectionIndex}:${y.rowIndexInSection}`,w=v.get(_)??[];w.push(y),v.set(_,w)}for(const[y,_]of v){const w=parseInt(y.split(":")[0],10),k=_[0].rowIndexInSection,x=new Set(_.map(S=>S.cellIndexInRow)),$=Pe(h,t);h=nt(h,$,w,S=>bt(S,a.row,k,C=>{let T=-1;const E=Ge(C).filter(A=>ir(A,a)?(T++,!x.has(T)):!0);return{...C,children:E}}))}return{table:h,ok:!0}}function uh(e,t,n,o){const r=yt(t),s=Pe(e,t),a=Ve(s,n,o);if(!a||a.colSpan<=1&&a.rowSpan<=1)return e;const l=a.gridRow,d=a.gridCol,c=a.gridRow+a.rowSpan-1,p=a.gridCol+a.colSpan-1,f=a.isHeader,b=typeof a.cell.props?.className=="string"?a.cell.props.className:void 0;let g=nt(e,s,a.sectionIndex,m=>bt(m,r.row,a.rowIndexInSection,h=>({...h,children:Ge(h).map((v,y)=>{if(y!==a.cellIndexInRow)return v;let _=mn(v,r.colSpanProp,1);return _=mn(_,r.rowSpanProp,1),_})})));for(let m=l;m<=c;m++)for(let h=d;h<=p;h++){if(m===l&&h===d)continue;const v=Pe(g,t),y=v.rows.find(k=>k.cells.some(x=>x.gridRow===m))??v.rows[m];if(!y)continue;let _=-1;for(const k of y.cells)k.gridRow===m&&k.gridColbt(k,r.row,y.rowIndexInSection,x=>{const $=[...Ge(x)];let S;if(_<0)S=$.findIndex(C=>ir(C,r)),S<0&&(S=$.length);else{const C=Ei(x,r,_);S=C<0?$.length:C+1}return $.splice(S,0,$i(r,w,f)),{...x,children:$}}))}return g}function Ii(e,t,n,o,r){const s=yt(t),a=Pe(e,t),l=Ve(a,n,o);return l?nt(e,a,l.sectionIndex,d=>bt(d,s.row,l.rowIndexInSection,c=>({...c,children:Ge(c).map((p,f)=>{if(f!==l.cellIndexInRow)return p;const b={...p.props??{}};r.trim()===""?delete b.className:b.className=r;const g={...p,props:b};return Object.keys(b).length===0&&delete g.props,g})}))):e}function Jt(e,t,n,o,r,s){const a=yt(t),l=Pe(e,t),d=Ve(l,n,o);return d?nt(e,l,d.sectionIndex,c=>bt(c,a.row,d.rowIndexInSection,p=>({...p,children:Ge(p).map((f,b)=>{if(b!==d.cellIndexInRow)return f;const g={...f.props??{}},m={...g.style??{}};!s||s.trim()===""?delete m[r]:m[r]=s,Object.keys(m).length===0?delete g.style:g.style=m;const h={...f,props:g};return Object.keys(g).length===0&&delete h.props,h})}))):e}function ho(e,t,n,o,r,s,a){const l=yt(t),d=Pe(e,t),c=Ve(d,n,o);if(!c)return e;const p=a==="dark";return nt(e,d,c.sectionIndex,f=>bt(f,l.row,c.rowIndexInSection,b=>({...b,children:Ge(b).map((g,m)=>{if(m!==c.cellIndexInRow)return g;const h={...g.props??{}},v=typeof h.className=="string"?h.className:"",y=mC(v,s,r,p);y===""?delete h.className:h.className=y;const _={...g,props:h};return Object.keys(h).length===0&&delete _.props,_})})))}function ph(e,t,n,o,r){const s=yt(t),a=Pe(e,t),l=Ve(a,n,o);return l?nt(e,a,l.sectionIndex,d=>bt(d,s.row,l.rowIndexInSection,c=>({...c,children:Ge(c).map((p,f)=>f===l.cellIndexInRow?{...p,text:r}:p)}))):e}function fh(e,t,n,o,r){const s=yt(t),a=Pe(e,t),l=Ve(a,n,o);return l?nt(e,a,l.sectionIndex,d=>bt(d,s.row,l.rowIndexInSection,c=>({...c,children:Ge(c).map((p,f)=>f===l.cellIndexInRow?r:p)}))):e}const gh=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function zz(e){return e.split(/\s+/).filter(Boolean)}function hh(e,t){for(const n of t)if(e===n||/^-?\d+$/.test(e.slice(n.length+1))&&e.startsWith(n+"-"))return!0;return!1}function yh({className:e,catalog:t,t:n,onChange:o,colorScheme:r="light",onPresetToken:s,colorStyle:a,onColorStyle:l,disabled:d}){const c=t?.sides??[],p=t?.widths??[],f=t?.colors??[],b=r==="dark",g=u.useMemo(()=>c.map(E=>E.prefix),[c]),m=u.useMemo(()=>new Set(f.map(E=>E.token)),[f]),h=u.useMemo(()=>zz(e),[e]),v=u.useMemo(()=>Gr(e,b),[e,b]),y=u.useMemo(()=>v.find(E=>m.has(E))??null,[v,m]),_=u.useMemo(()=>{const E=new Set;for(const A of c)h.some(D=>D===A.prefix||D.startsWith(A.prefix+"-")&&/^-?\d+$/.test(D.slice(A.prefix.length+1)))&&E.add(A.value);return E},[h,c]),w=u.useMemo(()=>{const E=h.find(N=>hh(N,g));if(!E)return"none";const A=p.filter(N=>N.value!=="none");for(const N of c){if(E===N.prefix)return A.find(D=>(D.suffix??"")==="")?.value??"thin";if(E.startsWith(N.prefix+"-")){const D=E.slice(N.prefix.length),B=A.find(M=>(M.suffix??"")===D);if(B)return B.value}}return"thin"},[h,g,c,p]);if(!t||c.length===0||p.length===0)return null;function k(E){return E.filter(A=>!hh(A,g))}function x(E,A){const N=k(h),D=p.find(O=>O.value===A);if(!D||A==="none"||E.size===0)return N.join(" ").trim();const B=D.suffix??"",M=[...N];for(const O of c)E.has(O.value)&&M.push(B?`${O.prefix}${B}`:O.prefix);return M.join(" ").trim()}const $=E=>{const A=new Set(_);A.has(E)?A.delete(E):(E==="all"?A.clear():A.delete("all"),A.add(E));const N=w==="none"?p.find(D=>D.value!=="none")?.value??"thin":w;o(x(A,N))},S=E=>{const A=_.size===0?new Set(["all"]):_;o(x(A,E))},C=E=>{s?.(E)},T=(E,A)=>E&&E.startsWith("$t:")?n(E.slice(3)):E||A;return i.jsxs("div",{className:"g7le-cell-border","data-testid":"g7le-cell-border",style:Nz,children:[i.jsx("div",{style:Mz,children:i.jsx("span",{style:Lz,children:n("layout_editor.table_editor.cell_border")})}),i.jsx("div",{style:ll,"data-testid":"g7le-cell-border-widths",children:p.map(E=>i.jsx("button",{type:"button",disabled:d,"data-testid":`g7le-cell-border-width-${E.value}`,"aria-pressed":w===E.value,onClick:()=>S(E.value),style:w===E.value?bh:dl,children:T(E.label,E.value)},E.value))}),w!=="none"&&i.jsx("div",{style:ll,"data-testid":"g7le-cell-border-sides",children:c.map(E=>i.jsx("button",{type:"button",disabled:d,"data-testid":`g7le-cell-border-side-${E.value}`,"aria-pressed":_.has(E.value),onClick:()=>$(E.value),style:_.has(E.value)?bh:dl,children:T(E.label,E.value)},E.value))}),w!=="none"&&(f.length>0||l)&&i.jsx(i.Fragment,{children:i.jsxs("div",{style:ll,"data-testid":"g7le-cell-border-colors",children:[f.map(E=>{const A=y===E.token;return i.jsx("button",{type:"button",disabled:d,title:T(E.label,E.value),"data-testid":`g7le-cell-border-color-${E.value}`,"aria-pressed":A,onClick:()=>C(E.token),style:{...mh,background:E.swatch??"#fff",outline:A?"2px solid #2563eb":"1px solid #cbd5e1"}},E.value)}),l&&(()=>{const E=!!a&&f.some(N=>N.swatch&&N.swatch.toLowerCase()===a.toLowerCase()),A=!b&&!!a&&!E;return i.jsx("label",{title:n(b?"layout_editor.table_editor.dark_free_color_hint":"layout_editor.table_inplace.custom_color"),"data-testid":"g7le-cell-border-color-custom",style:{...mh,position:"relative",overflow:"hidden",display:"inline-flex",alignItems:"center",justifyContent:"center",background:A&&gh.test(a)?a:"conic-gradient(red, yellow, lime, aqua, blue, magenta, red)",outline:A?"2px solid #2563eb":"1px solid #cbd5e1",opacity:b?.4:1,cursor:b?"not-allowed":"pointer"},children:i.jsx("input",{type:"color",disabled:d||b,"data-testid":"g7le-cell-border-color-picker",value:a&&gh.test(a)?a:"#000000",onChange:N=>l(N.target.value),style:{position:"absolute",width:0,height:0,opacity:0}})})})()]})})]})}const Nz={display:"flex",flexDirection:"column",gap:6},Mz={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},Lz={fontSize:12,fontWeight:600,color:"#475569"},ll={display:"flex",gap:4,flexWrap:"wrap",alignItems:"center"},dl={padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},bh={...dl,border:"1px solid #2563eb",background:"#eff6ff",color:"#1d4ed8",fontWeight:600},mh={width:22,height:22,borderRadius:5,padding:0,cursor:"pointer",boxSizing:"border-box"},vh=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function _h({colorStyle:e,className:t,catalog:n,t:o,colorScheme:r="light",onPresetToken:s,onCustomColor:a,onClear:l,disabled:d}){const c=n?.colors??[],p=r==="dark",f=e??"",b=Gr(t??"",p),g=c.find(_=>_.token&&b.includes(_.token))?.token??null,m=(_,w)=>_&&_.startsWith("$t:")?o(_.slice(3)):_||w,h=!g&&(p||f.trim()===""),v=!!f&&c.some(_=>_.swatch&&_.swatch.toLowerCase()===f.toLowerCase()),y=!p&&!!f&&!v;return i.jsxs("div",{className:"g7le-cell-fill","data-testid":"g7le-cell-fill",style:Pz,children:[i.jsx("div",{style:Oz,children:i.jsx("span",{style:Bz,children:o("layout_editor.table_editor.cell_fill")})}),i.jsxs("div",{style:Wz,"data-testid":"g7le-cell-fill-colors",children:[i.jsx("button",{type:"button",disabled:d,title:o("layout_editor.table_editor.cell_fill_none"),"data-testid":"g7le-cell-fill-none","aria-pressed":h,onClick:()=>l?.(),style:{...cl,background:"repeating-conic-gradient(#e2e8f0 0% 25%, #ffffff 0% 50%) 50% / 10px 10px",outline:h?"2px solid #2563eb":"1px solid #cbd5e1"}}),c.map(_=>{const w=!!_.token&&g===_.token,k=!p&&!!_.swatch&&f.toLowerCase()===(_.swatch??"").toLowerCase(),x=w||k,$=d||p&&!_.token;return i.jsx("button",{type:"button",disabled:$,title:m(_.label,_.value),"data-testid":`g7le-cell-fill-color-${_.value}`,"aria-pressed":x,onClick:()=>{_.token&&s?s(_.token):!p&&_.swatch&&a&&a(_.swatch)},style:{...cl,background:_.swatch??"#fff",outline:x?"2px solid #2563eb":"1px solid #cbd5e1",opacity:$?.4:1,cursor:$?"not-allowed":"pointer"}},_.value)}),a&&i.jsx("label",{title:o(p?"layout_editor.table_editor.dark_free_color_hint":"layout_editor.table_editor.cell_fill_custom"),"data-testid":"g7le-cell-fill-custom",style:{...cl,position:"relative",overflow:"hidden",display:"inline-flex",alignItems:"center",justifyContent:"center",background:y&&vh.test(f)?f:"conic-gradient(red, yellow, lime, aqua, blue, magenta, red)",outline:y?"2px solid #2563eb":"1px solid #cbd5e1",opacity:p?.4:1,cursor:p?"not-allowed":"pointer"},children:i.jsx("input",{type:"color",disabled:d||p,"data-testid":"g7le-cell-fill-color-picker",value:f&&vh.test(f)?f:"#ffffff",onChange:_=>a(_.target.value),style:{position:"absolute",width:0,height:0,opacity:0}})})]})]})}const Pz={display:"flex",flexDirection:"column",gap:6},Oz={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},Bz={fontSize:12,fontWeight:600,color:"#475569"},Wz={display:"flex",gap:4,flexWrap:"wrap",alignItems:"center"},cl={width:22,height:22,borderRadius:5,padding:0,cursor:"pointer",boxSizing:"border-box"};function jz(e){const t=/^(\d+)px$/.exec(e.trim());return t?parseInt(t[1],10):null}function xh({paddingStyle:e,catalog:t,t:n,onChange:o,disabled:r}){const s=t?.steps??[],a=e??"",l=jz(a),d=(h,v)=>h&&h.startsWith("$t:")?n(h.slice(3)):h||v,c=s.some(h=>(h.px??0)===(l??-1)),p=l!==null&&!c?String(l):"",[f,b]=u.useState(p);u.useEffect(()=>{b(p)},[e]);const g=h=>{o(h&&h>0?`${h}px`:""),b("")},m=h=>{const v=parseInt(h,10);Number.isFinite(v)&&v>=0&&o(v>0?`${v}px`:"")};return i.jsxs("div",{className:"g7le-cell-padding","data-testid":"g7le-cell-padding",style:Hz,children:[i.jsx("div",{style:Fz,children:n("layout_editor.table_editor.cell_padding")}),i.jsxs("div",{style:Kz,"data-testid":"g7le-cell-padding-steps",children:[s.map(h=>{const v=(h.px??0)===(l??-1)||!h.px&&a.trim()==="";return i.jsx("button",{type:"button",disabled:r,"data-testid":`g7le-cell-padding-step-${h.value}`,"aria-pressed":v,onClick:()=>g(h.px),style:v?Vz:wh,children:d(h.label,h.value)},h.value)}),i.jsxs("span",{style:{display:"inline-flex",alignItems:"center",gap:3},children:[i.jsx("input",{type:"number",min:0,disabled:r,"data-testid":"g7le-cell-padding-free",value:f,placeholder:n("layout_editor.table_editor.cell_padding_custom"),onChange:h=>b(h.target.value),onBlur:()=>f.trim()!==""&&m(f),onKeyDown:h=>{h.key==="Enter"&&f.trim()!==""&&m(f)},style:Uz}),i.jsx("span",{style:{fontSize:11,color:"#94a3b8"},children:"px"})]})]})]})}const Hz={display:"flex",flexDirection:"column",gap:6},Fz={fontSize:12,fontWeight:600,color:"#475569"},Kz={display:"flex",gap:4,flexWrap:"wrap",alignItems:"center"},wh={padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},Vz={...wh,border:"1px solid #2563eb",background:"#eff6ff",color:"#1d4ed8",fontWeight:600},Uz={width:48,padding:"3px 5px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"};function kh({colorScheme:e,onChange:t,t:n,disabled:o}){const r=e==="dark";return i.jsxs("div",{className:"g7le-color-scheme-tabs","data-testid":"g7le-color-scheme-tabs",style:qz,children:[i.jsxs("div",{style:Gz,children:[i.jsx("span",{style:Yz,children:n("layout_editor.table_editor.cell_color")}),i.jsxs("div",{style:Xz,children:[i.jsx("button",{type:"button",disabled:o,"data-testid":"g7le-color-scheme-light","aria-pressed":!r,onClick:()=>t("light"),style:r?ul:Sh,children:n("layout_editor.property_modal.scope.scheme_light")}),i.jsx("button",{type:"button",disabled:o,"data-testid":"g7le-color-scheme-dark","aria-pressed":r,onClick:()=>t("dark"),style:r?Sh:ul,children:n("layout_editor.property_modal.scope.scheme_dark")})]})]}),r&&i.jsx("div",{style:Jz,"data-testid":"g7le-color-scheme-dark-hint",children:n("layout_editor.table_editor.dark_free_color_hint")})]})}const qz={display:"flex",flexDirection:"column",gap:3},Gz={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},Yz={fontSize:12,fontWeight:700,color:"#0f172a"},Xz={display:"flex",gap:2},ul={padding:"2px 9px",fontSize:11,border:"none",borderBottom:"2px solid transparent",background:"transparent",color:"#94a3b8",cursor:"pointer"},Sh={...ul,color:"#1d4ed8",borderBottom:"2px solid #2563eb",fontWeight:600},Jz={fontSize:10,color:"#94a3b8",fontStyle:"italic"},pl="dark:";function Ch(e){return typeof e=="string"?e.split(/\s+/).filter(Boolean):[]}function $h(e,t){return t==="dark"?e.filter(n=>n.startsWith(pl)).map(n=>n.slice(pl.length)):e.filter(n=>!n.startsWith(pl))}const Zz={none:0,thin:1,medium:2,thick:4},Eh={top:{w:"borderTopWidth",s:"borderTopStyle",c:"borderTopColor"},bottom:{w:"borderBottomWidth",s:"borderBottomStyle",c:"borderBottomColor"},left:{w:"borderLeftWidth",s:"borderLeftStyle",c:"borderLeftColor"},right:{w:"borderRightWidth",s:"borderRightStyle",c:"borderRightColor"}},Ih=["top","bottom","left","right"];function Qz(e,t,n="light"){if(!e||!t)return{};const o=t.sides??[],r=t.widths??[],s=t.colors??[],a=Ch(e.props?.className);if(a.length===0&&!e.props?.style)return{};const l=[...r].filter(y=>y.value!=="none").sort((y,_)=>(_.suffix??"").length-(y.suffix??"").length),d={};for(const y of o)for(const _ of l){const w=_.suffix?`${y.prefix}${_.suffix}`:y.prefix;if(a.includes(w)){d[y.value]=_.value;break}}const c=e.props?.style??{},p=$h(a,n),f=s.find(y=>p.includes(y.token))?.swatch??"",g=(n==="light"&&typeof c.borderColor=="string"?c.borderColor:"")||f||"#94a3b8",m=y=>{const _=Eh[y]?.c,w=_?c[_]:void 0;return typeof w=="string"&&w?w:g},h={},v=(y,_)=>{const w=Eh[y];if(!w)return;const k=Zz[_]??1;h[w.w]=`${k}px`,h[w.s]=k>0?"solid":"none",k>0&&(h[w.c]=m(y))};if(d.all)for(const y of Ih)v(y,d.all);for(const y of Ih)d[y]&&v(y,d[y]);return h}function Rz(e,t,n="light"){if(!e?.props)return{};const o=e.props.style??{},r={},s=Ch(e.props.className),a=t?.colors?.find(c=>c.token&&$h(s,n).includes(c.token))?.swatch??"",d=(n==="light"&&typeof o.backgroundColor=="string"?o.backgroundColor:"")||a;return d&&(r.backgroundColor=d),typeof o.padding=="string"&&o.padding&&(r.padding=o.padding),r}const eN=/^\s*\$t:(custom\.[a-zA-Z0-9._-]+)\s*$/,tN=/^\s*\$t:([a-zA-Z0-9._-]+)\s*$/,nN=/\{\{.*?\}\}/;function Ah(e,t,n){const o=e?.text;if(typeof o!="string")return{display:"",editable:!1,isKey:!1};const r=vt(o);if(r&&r.key.startsWith("custom.")){let a="";try{const l=Pt.getInstance().translate(r.key,{templateId:t,locale:n});a=l&&l!==r.key?l:""}catch{a=""}return{display:a,editable:!0,isKey:!0}}if(nN.test(o))return{display:o,editable:!1,isKey:!1};const s=tN.exec(o);if(s){const a=s[1];let l="";try{const d=Pt.getInstance().translate(a,{templateId:t,locale:n});l=d&&d!==a?d:""}catch{l=""}return{display:l,editable:!0,isKey:!0}}return{display:o,editable:!0,isKey:!1}}function fl(e){const t=or(e);return t===null?{node:null,path:null}:{node:ki(e,t),path:t}}function oN(e){if(!e||typeof e.text!="string")return null;const t=eN.exec(e.text);if(t)return t[1];const n=vt(e.text);return n&&n.key.startsWith("custom.")?n.key:null}function rN({node:e,params:t,t:n,onPatchNode:o,templateIdentifier:r,candidates:s}){const{state:a}=Qe(),l=a.selectedRoute?.layoutName??null,d=a.locale,c=r??a.templateIdentifier,p=u.useMemo(()=>t&&typeof t=="object"?t:null,[t]);u.useMemo(()=>yt(p),[p]);const f=u.useMemo(()=>Pe(e,p),[e,p]),b=u.useMemo(()=>{const U=p?.cellBorder;return U&&typeof U=="object"?U:null},[p]),g=u.useMemo(()=>{const U=p?.cellBackground;return U&&typeof U=="object"?U:null},[p]),m=u.useMemo(()=>{const U=p?.cellPadding;return U&&typeof U=="object"?U:null},[p]),[h,v]=u.useState(null),[y,_]=u.useState(null),[w,k]=u.useState({}),[x,$]=u.useState(!1),[S,C]=u.useState(null),[T,E]=u.useState(null),[A,N]=u.useState("light"),D=u.useCallback(U=>o(U),[o]),B=u.useMemo(()=>h?Ve(f,h.r,h.c):null,[f,h]),M=T!==null?T:h?.c??null,O=S!==null?S:h?.r??null,z=u.useMemo(()=>{const U=(b?.sides??[]).find(xe=>xe.value==="all")??(b?.sides??[])[0],ue=(b?.widths??[]).find(xe=>xe.value!=="none");if(!U||!ue)return[];const fe=ue.suffix??"";return[fe?`${U.prefix}${fe}`:U.prefix]},[b]),H=u.useCallback((U,ue,fe)=>{if(z.length===0)return U;const xe=(b?.sides??[]).map(Q=>Q.prefix),he=Ve(Pe(U,p),ue,fe),ne=(typeof he?.cell?.props?.className=="string"?he.cell.props.className:"").split(/\s+/).filter(Boolean);return ne.some(Q=>xe.some(le=>Q===le||Q.startsWith(le+"-")&&/^-?\d+$/.test(Q.slice(le.length+1))))?U:Ii(U,p,ue,fe,[...ne,...z].join(" ").trim())},[z,b,p]),P=u.useCallback(U=>{if(!h)return;const ue=Math.min(h.r,y?.r??h.r),fe=Math.max(h.r,y?.r??h.r),xe=Math.min(h.c,y?.c??h.c),he=Math.max(h.c,y?.c??h.c),j=new Set,ne=[];for(let Q=ue;Q<=fe;Q++)for(let le=xe;le<=he;le++)j.add(`${Q}:${le}`),ne.push({r:Q,c:le});let pe=e;for(const Q of ne){if(pe=H(pe,Q.r,Q.c),pe=Jt(pe,p,Q.r,Q.c,"borderColor",U),Q.r>0&&!j.has(`${Q.r-1}:${Q.c}`)){const le=Ve(Pe(pe,p),Q.r-1,Q.c);le&&(pe=Jt(pe,p,le.gridRow,le.gridCol,"borderBottomColor",U))}if(Q.c>0&&!j.has(`${Q.r}:${Q.c-1}`)){const le=Ve(Pe(pe,p),Q.r,Q.c-1);le&&(pe=Jt(pe,p,le.gridRow,le.gridCol,"borderRightColor",U))}}D(pe)},[h,y,e,p,D,H]),I=u.useCallback(U=>P(U),[P]),L=u.useMemo(()=>(b?.colors??[]).map(U=>U.token).filter(Boolean),[b]),F=u.useCallback(U=>{if(!h||L.length===0)return;const ue=Math.min(h.r,y?.r??h.r),fe=Math.max(h.r,y?.r??h.r),xe=Math.min(h.c,y?.c??h.c),he=Math.max(h.c,y?.c??h.c);let j=e;for(let ne=ue;ne<=fe;ne++)for(let pe=xe;pe<=he;pe++)j=H(j,ne,pe),j=ho(j,p,ne,pe,U,L,A);D(j)},[h,y,e,p,D,H,L,A]),Y=u.useMemo(()=>{if(A==="dark")return"";const U=B?.cell.props?.style;return typeof U?.borderColor=="string"?U.borderColor:""},[B,A]),K=u.useCallback((U,ue)=>{if(!h)return;const fe=Math.min(h.r,y?.r??h.r),xe=Math.max(h.r,y?.r??h.r),he=Math.min(h.c,y?.c??h.c),j=Math.max(h.c,y?.c??h.c);let ne=e;for(let pe=fe;pe<=xe;pe++)for(let Q=he;Q<=j;Q++)ne=Jt(ne,p,pe,Q,U,ue);D(ne)},[h,y,e,p,D]),X=u.useMemo(()=>(g?.colors??[]).map(U=>U.token).filter(U=>!!U),[g]),Z=u.useCallback(()=>h?{r0:Math.min(h.r,y?.r??h.r),r1:Math.max(h.r,y?.r??h.r),c0:Math.min(h.c,y?.c??h.c),c1:Math.max(h.c,y?.c??h.c)}:null,[h,y]),ae=u.useCallback(U=>{const ue=Z();if(!ue||X.length===0)return;let fe=e;for(let xe=ue.r0;xe<=ue.r1;xe++)for(let he=ue.c0;he<=ue.c1;he++)fe=ho(fe,p,xe,he,U,X,A);D(fe)},[Z,e,p,D,X,A]),oe=u.useCallback(U=>K("backgroundColor",U),[K]),G=u.useCallback(()=>{const U=Z();if(!U)return;let ue=e;for(let fe=U.r0;fe<=U.r1;fe++)for(let xe=U.c0;xe<=U.c1;xe++)ue=ho(ue,p,fe,xe,void 0,X,A),A==="light"&&(ue=Jt(ue,p,fe,xe,"backgroundColor",void 0));D(ue)},[Z,e,p,D,X,A]),ee=u.useCallback(U=>K("padding",U),[K]),ge=u.useMemo(()=>{if(A==="dark")return"";const U=B?.cell.props?.style;return typeof U?.backgroundColor=="string"?U.backgroundColor:""},[B,A]),V=u.useMemo(()=>typeof B?.cell.props?.className=="string"?B.cell.props.className:"",[B]),te=u.useMemo(()=>{const U=B?.cell.props?.style;return typeof U?.padding=="string"?U.padding:""},[B]),be=u.useCallback(U=>U==="section"?n("layout_editor.table_editor.move_blocked_section"):"",[n]),Ee=u.useCallback((U,ue)=>Si(f,U,ue),[f]),De=u.useCallback((U,ue)=>Ci(f,U,ue),[f]),Se=u.useCallback(U=>D(sl(e,p,U)),[e,p,D]),Ue=u.useCallback(U=>{D(sh(e,p,U)),v(null),_(null)},[e,p,D]),Me=u.useCallback((U,ue)=>D(ah(e,p,U,ue)),[e,p,D]),Oe=u.useCallback(U=>D(dh(e,p,U)),[e,p,D]),Ye=u.useCallback(U=>{D(ch(e,p,U)),v(null),_(null)},[e,p,D]),ze=u.useCallback((U,ue)=>D(lh(e,p,U,ue)),[e,p,D]),Xe=u.useCallback(()=>{if(!h||!y)return;const U=al(e,p,h.r,h.c,y.r,y.c);U.ok&&(D(U.table),v({r:Math.min(h.r,y.r),c:Math.min(h.c,y.c)}),_(null))},[e,p,h,y,D]),ve=u.useCallback(()=>{h&&(D(uh(e,p,h.r,h.c)),_(null))},[e,p,h,D]),qe=u.useCallback(U=>{if(!h)return;const ue=Math.min(h.r,y?.r??h.r),fe=Math.max(h.r,y?.r??h.r),xe=Math.min(h.c,y?.c??h.c),he=Math.max(h.c,y?.c??h.c);let j=e;for(let ne=ue;ne<=fe;ne++)for(let pe=xe;pe<=he;pe++)j=Ii(j,p,ne,pe,U);D(j)},[e,p,h,y,D]),We=u.useCallback(async(U,ue)=>{const fe=`${U}:${ue}`,xe=w[fe];if(xe===void 0)return;const he=Ve(f,U,ue);if(!he)return;const{node:j,path:ne}=fl(he.cell);if(ne===null)return;const pe=Ah(j,c,d);if(pe.editable){if(xe===pe.display){k(Q=>{const le={...Q};return delete le[fe],le});return}$(!0);try{const Q=oN(j);if(Q)await vr(c,Q,d,xe),await tn(c,d);else{const le=await qn(c,l,d,xe);if(le.kind==="ok"&&le.resource){const Ae=`$t:${le.resource.translation_key}`;if(ne.length===0)D(ph(e,p,U,ue,Ae));else{const dt=rr(he.cell,ne,Ae);D(fh(e,p,U,ue,dt))}await tn(c,d)}}}finally{$(!1),k(Q=>{const le={...Q};return delete le[fe],le})}}},[w,f,c,d,l,e,p,D]),ce=u.useMemo(()=>{if(!B)return null;const{node:U,path:ue}=fl(B.cell);return ue===null?null:{value:typeof U?.text=="string"?U.text:"",editable:!0}},[B]),q=u.useCallback(U=>{if(typeof U!="string"||U.length===0||!h)return;const ue=Ve(f,h.r,h.c);if(!ue)return;const fe=or(ue.cell);if(fe!==null)if(fe.length===0)D(ph(e,p,h.r,h.c,U));else{const xe=rr(ue.cell,fe,U);D(fh(e,p,h.r,h.c,xe))}},[h,f,e,p,D]),ie=u.useCallback((U,ue,fe)=>{fe?_({r:U,c:ue}):(v({r:U,c:ue}),_(null))},[]),se=u.useMemo(()=>Array.from({length:f.colCount},(U,ue)=>ue),[f.colCount]),me=!!(h&&y&&(h.r!==y.r||h.c!==y.c)),Ce=!!(B&&(B.colSpan>1||B.rowSpan>1)),$e=B&&typeof B.cell.props?.className=="string"?B.cell.props.className:"";return i.jsxs("div",{className:"g7le-node-editor g7le-node-editor--table","data-testid":"g7le-table-editor",style:iN,children:[i.jsx("div",{style:sN,children:n("layout_editor.table_editor.title")}),i.jsx("div",{style:{overflowX:"auto"},children:i.jsxs("table",{"data-testid":"g7le-table-editor-grid",style:aN,children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{style:lN}),se.map(U=>{const ue=De(U,-1),fe=De(U,1),xe=M===U;return i.jsx("th",{style:dN,"data-testid":`g7le-table-colgutter-${U}`,onMouseEnter:()=>E(U),onMouseLeave:()=>E(he=>he===U?null:he),children:i.jsxs("div",{style:{...uN,visibility:xe?"visible":"hidden"},children:[i.jsx("button",{type:"button",title:ue.ok?n("layout_editor.table_editor.move_col_left"):be(ue.reason)||n("layout_editor.table_editor.move_col_left"),disabled:!ue.ok||x,onClick:()=>ze(U,-1),"data-testid":`g7le-table-col-left-${U}`,style:ue.ok?vn:Ai,children:"←"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.add_col"),disabled:x,onClick:()=>Oe(U),"data-testid":`g7le-table-col-add-${U}`,style:vn,children:"+"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.remove_col"),disabled:f.colCount<=1||x,onClick:()=>Ye(U),"data-testid":`g7le-table-col-remove-${U}`,style:Th,children:"✕"}),i.jsx("button",{type:"button",title:fe.ok?n("layout_editor.table_editor.move_col_right"):be(fe.reason)||n("layout_editor.table_editor.move_col_right"),disabled:!fe.ok||x,onClick:()=>ze(U,1),"data-testid":`g7le-table-col-right-${U}`,style:fe.ok?vn:Ai,children:"→"})]})},U)})]})}),i.jsx("tbody",{children:f.rows.map((U,ue)=>{const fe=U.cells[0]?.gridRow??ue,xe=O===fe;return i.jsxs("tr",{"data-testid":`g7le-table-row-${fe}`,onMouseEnter:()=>C(fe),onMouseLeave:()=>C(he=>he===fe?null:he),children:[i.jsx("td",{style:cN,"data-testid":`g7le-table-rowgutter-${fe}`,children:(()=>{const he=Ee(fe,-1),j=Ee(fe,1);return i.jsxs("div",{style:{...pN,visibility:xe?"visible":"hidden"},children:[i.jsx("button",{type:"button",title:he.ok?n("layout_editor.table_editor.move_row_up"):be(he.reason)||n("layout_editor.table_editor.move_row_up"),disabled:!he.ok||x,onClick:()=>Me(fe,-1),"data-testid":`g7le-table-row-up-${fe}`,style:he.ok?vn:Ai,children:"↑"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.add_row"),disabled:x,onClick:()=>Se(fe),"data-testid":`g7le-table-row-add-${fe}`,style:vn,children:"+"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.remove_row"),disabled:f.rows.length<=1||x,onClick:()=>Ue(fe),"data-testid":`g7le-table-row-remove-${fe}`,style:Th,children:"✕"}),i.jsx("button",{type:"button",title:j.ok?n("layout_editor.table_editor.move_row_down"):be(j.reason)||n("layout_editor.table_editor.move_row_down"),disabled:!j.ok||x,onClick:()=>Me(fe,1),"data-testid":`g7le-table-row-down-${fe}`,style:j.ok?vn:Ai,children:"↓"})]})})()}),U.cells.map(he=>{const j=`${he.gridRow}:${he.gridCol}`,{node:ne,path:pe}=fl(he.cell),Q=Ah(ne,c,d),le=pe!==null&&Q.editable,Ae=pe===null,dt=w[j],pt=dt!==void 0?dt:Q.display,ot=h&&h.r===he.gridRow&&h.c===he.gridCol,Le=h&&y&&he.gridRow>=Math.min(h.r,y.r)&&he.gridRow<=Math.max(h.r,y.r)&&he.gridCol>=Math.min(h.c,y.c)&&he.gridCol<=Math.max(h.c,y.c);return i.jsx("td",{colSpan:he.colSpan,rowSpan:he.rowSpan,"data-testid":`g7le-table-cell-${he.gridRow}-${he.gridCol}`,onClick:je=>ie(he.gridRow,he.gridCol,je.shiftKey),style:{...fN,...Qz(he.cell,b,A),...Rz(he.cell,g,A),...he.isHeader?gN:{},...ot?hN:{},...Le&&!ot?yN:{}},children:le?i.jsx("input",{type:"text","data-testid":`g7le-table-cell-input-${he.gridRow}-${he.gridCol}`,value:pt,placeholder:n("layout_editor.table_editor.cell_text"),disabled:x,onMouseDown:je=>{je.shiftKey&&je.preventDefault(),ie(he.gridRow,he.gridCol,je.shiftKey)},onClick:je=>je.stopPropagation(),onChange:je=>k(Je=>({...Je,[j]:je.target.value})),onBlur:()=>void We(he.gridRow,he.gridCol),style:bN}):Ae?i.jsx("span",{"data-testid":`g7le-table-cell-struct-${he.gridRow}-${he.gridCol}`,style:Dh,children:n("layout_editor.table_editor.structural_cell")}):i.jsx("span",{style:Dh,children:Q.display})},j)})]},ue)})})]})}),i.jsxs("button",{type:"button","data-testid":"g7le-table-add-row-bottom",onClick:()=>Se(f.rows.length-1),disabled:x,style:mN,children:["+ ",n("layout_editor.table_editor.add_row")]}),i.jsxs("div",{style:vN,"data-testid":"g7le-table-cell-tools",children:[i.jsx("button",{type:"button","data-testid":"g7le-table-merge",onClick:Xe,disabled:!me||x,style:zh,children:n("layout_editor.table_editor.merge_cells")}),i.jsx("button",{type:"button","data-testid":"g7le-table-unmerge",onClick:ve,disabled:!Ce||x,style:zh,children:n("layout_editor.table_editor.unmerge_cells")})]}),B&&ce&&i.jsxs("div",{style:xN,"data-testid":"g7le-table-cell-i18n-section",children:[i.jsx("div",{style:wN,children:n("layout_editor.table_editor.cell_i18n_label")}),i.jsx(_t,{value:ce.value,onChange:q,t:n,placeholder:n("layout_editor.table_editor.cell_text"),testidPrefix:"g7le-table-cell-i18n",candidates:s,enableExpressionTree:!0,expressionTreeCollapsible:!0})]}),B&&i.jsxs("div",{style:_N,"data-testid":"g7le-table-cell-color-section",children:[i.jsx(kh,{colorScheme:A,onChange:N,t:n,disabled:x}),b&&i.jsx("div",{style:gl,"data-testid":"g7le-table-cell-border-row",children:i.jsx(yh,{className:$e,catalog:b,t:n,onChange:qe,colorScheme:A,onPresetToken:F,colorStyle:Y,onColorStyle:I,disabled:x})}),i.jsx("div",{style:gl,"data-testid":"g7le-table-cell-fill-row",children:i.jsx(_h,{colorStyle:ge,className:V,catalog:g,t:n,colorScheme:A,onPresetToken:ae,onCustomColor:oe,onClear:G,disabled:x})})]}),B&&i.jsx("div",{style:gl,"data-testid":"g7le-table-cell-padding-row",children:i.jsx(xh,{paddingStyle:te,catalog:m,t:n,onChange:ee,disabled:x})}),B&&!b&&i.jsxs("label",{style:kN,"data-testid":"g7le-table-cell-border-row",children:[i.jsx("span",{style:SN,children:n("layout_editor.table_editor.cell_border")}),i.jsx("input",{type:"text","data-testid":"g7le-table-cell-border-input",value:$e,placeholder:n("layout_editor.table_editor.cell_class_placeholder"),onChange:U=>qe(U.target.value),disabled:x,style:CN})]}),!f.valid&&i.jsx("div",{"data-testid":"g7le-table-grid-warning",style:$N,children:n("layout_editor.table_editor.grid_invalid")}),i.jsx("div",{style:EN,children:n("layout_editor.table_editor.select_hint")})]})}const iN={display:"flex",flexDirection:"column",gap:8,width:"100%",marginBottom:12},sN={fontSize:12,fontWeight:700,color:"#0f172a"},aN={borderCollapse:"collapse",width:"auto"},lN={width:28,background:"transparent",border:"none"},dN={padding:2,border:"none",background:"transparent"},cN={padding:2,border:"none",background:"transparent",verticalAlign:"middle"},uN={display:"flex",gap:2,justifyContent:"center"},pN={display:"grid",gridTemplateColumns:"repeat(2, 16px)",gap:2,justifyContent:"center"},vn={width:16,height:16,lineHeight:"14px",padding:0,fontSize:10,border:"1px solid #cbd5e1",borderRadius:4,background:"#fff",color:"#475569",cursor:"pointer"},Th={...vn,border:"1px solid #fecaca",color:"#dc2626"},Ai={...vn,cursor:"not-allowed",opacity:.4,color:"#94a3b8",borderColor:"#e2e8f0"},fN={border:"1px solid #cbd5e1",padding:0,width:64,minWidth:64,maxWidth:120,height:24,background:"#fff",cursor:"pointer"},gN={background:"#f1f5f9",fontWeight:600},hN={outline:"2px solid #2563eb",outlineOffset:-2},yN={background:"#dbeafe"},bN={width:"100%",boxSizing:"border-box",padding:"2px 5px",fontSize:11,height:22,lineHeight:"18px",border:"none",background:"transparent",outline:"none"},Dh={display:"block",padding:"2px 5px",fontSize:10,color:"#64748b",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:110},mN={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},vN={display:"flex",gap:6},zh={padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},_N={display:"flex",flexDirection:"column",gap:8,borderTop:"1px solid #f1f5f9",paddingTop:8},xN={display:"flex",flexDirection:"column",gap:6,borderTop:"1px solid #f1f5f9",paddingTop:8},wN={fontSize:12,fontWeight:700,color:"#0f172a"},gl={display:"flex",flexDirection:"column",gap:6},kN={display:"flex",alignItems:"center",gap:6},SN={fontSize:12,color:"#475569",minWidth:60},CN={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},$N={fontSize:11,color:"#b45309",background:"#fffbeb",border:"1px solid #fde68a",borderRadius:6,padding:"4px 6px"},EN={fontSize:11,color:"#94a3b8"},IN=/\{\{.*?\}\}/;function AN(e,t,n){const r=(e.props??{})[t];return Array.isArray(r)?r:r===void 0&&n?JSON.parse(JSON.stringify(n)):[]}function TN(e){return typeof e=="string"&&IN.test(e)}function hl(e,t,n){return e?e.startsWith("$t:")?t(e.slice(3)):e:n}function DN(e,t,n){return typeof e=="object"&&e!==null?e[t.key]:n?e:void 0}function zN(e,t,n,o){if(typeof e=="object"&&e!==null){const r={...e};return o===void 0?delete r[t.key]:r[t.key]=o,r}return n?o:{[t.key]:o}}function Nh({node:e,params:t,t:n,onPatchNode:o,templateIdentifier:r,candidates:s}){const a=typeof t?.arrayProp=="string"?t.arrayProp:null,l=Array.isArray(t?.fields)?t.fields:[],d=hl(typeof t?.itemLabel=="string"?t.itemLabel:void 0,n,n("layout_editor.array_editor.item")),c=t?.newItem,p=c&&typeof c=="object"?c:null,f=typeof c=="string"||typeof c=="number"?c:null,b=(l.find($=>$.primary)??l[0])?.key,g=(e.props??{})[a??""],m=Array.isArray(t?.defaultItems)?t.defaultItems:null,h=a?AN(e,a,m):[],v=u.useCallback($=>{if(!a)return;const S={...e.props??{}};S[a]=$,o({...e,props:S})},[a,e,o]),y=u.useCallback(()=>{if(p)return JSON.parse(JSON.stringify(p));if(f!==null)return f;const $={};for(const S of l)(S.widget??"text")==="boolean"?$[S.key]=!1:$[S.key]="";return $},[p,f,l]),_=u.useCallback(()=>{v([...h,y()])},[v,h,y]),w=u.useCallback($=>{v(h.filter((S,C)=>C!==$))},[v,h]),k=u.useCallback(($,S)=>{const C=$+S;if(C<0||C>=h.length)return;const T=[...h];[T[$],T[C]]=[T[C],T[$]],v(T)},[v,h]),x=u.useCallback(($,S,C)=>{const T=S.key===b,E=h.map((A,N)=>N===$?zN(A,S,T,C):A);v(E)},[h,v,b]);return a?TN(g)||g!==void 0&&!Array.isArray(g)?i.jsx("div",{className:"g7le-node-editor g7le-node-editor--array","data-testid":"g7le-array-editor-bound",style:HN,children:n("layout_editor.array_editor.bound_degraded")}):i.jsxs("div",{className:"g7le-node-editor g7le-node-editor--array","data-testid":"g7le-array-editor",style:NN,children:[i.jsx("div",{style:MN,children:n("layout_editor.array_editor.items_title")}),h.length===0&&i.jsx("div",{"data-testid":"g7le-array-empty",style:Lh,children:n("layout_editor.array_editor.empty")}),h.map(($,S)=>i.jsxs("div",{"data-testid":`g7le-array-row-${S}`,style:LN,children:[i.jsxs("div",{style:PN,children:[i.jsxs("span",{style:ON,children:["#",S+1]}),i.jsx("div",{style:{flex:1}}),i.jsx("button",{type:"button","data-testid":`g7le-array-up-${S}`,title:n("layout_editor.array_editor.move_up"),disabled:S===0,onClick:()=>k(S,-1),style:Mh,children:"↑"}),i.jsx("button",{type:"button","data-testid":`g7le-array-down-${S}`,title:n("layout_editor.array_editor.move_down"),disabled:S===h.length-1,onClick:()=>k(S,1),style:Mh,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-array-remove-${S}`,title:n("layout_editor.array_editor.remove"),onClick:()=>w(S),style:WN,children:"✕"})]}),l.map(C=>{const T=C.widget??"text",E=C.key===b,A=hl(C.label,n,C.key),N=DN($,C,E),D=`g7le-array-field-${S}-${C.key}`;if(T==="boolean")return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("input",{type:"checkbox","data-testid":D,checked:N===!0,onChange:M=>x(S,C,M.target.checked)})]},C.key);if(T==="select"){const M=Array.isArray(C.options)?C.options:[];return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsxs("select",{"data-testid":D,value:N==null?"":String(N),onChange:O=>x(S,C,O.target.value===""?void 0:O.target.value),style:sr,children:[i.jsx("option",{value:"",children:"—"}),M.map((O,z)=>i.jsx("option",{value:String(O.value),children:hl(O.label,n,String(O.value))},z))]})]},C.key)}if(T==="i18n-text"){const M=typeof N=="string"?N:N==null?"":String(N);return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("div",{"data-testid":D,style:{flex:1,minWidth:0},children:i.jsx(_t,{value:M,onChange:O=>x(S,C,O===""?void 0:O),t:n,placeholder:A,testidPrefix:`${D}-i18n`,candidates:s,enableExpressionTree:!0,expressionTreeCollapsible:!0})})]},C.key)}if(T==="number"){const M=N==null?"":String(N);return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("input",{type:"number","data-testid":D,value:M,onChange:O=>{const z=O.target.value;x(S,C,z===""?void 0:Number(z))},style:sr})]},C.key)}if(T==="color"){const M=typeof N=="string"?N:"",O=/^#[0-9a-fA-F]{6}$/.test(M)?M:"#000000";return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("input",{type:"color","data-testid":`${D}-swatch`,value:O,onChange:z=>x(S,C,z.target.value),style:BN}),i.jsx("input",{type:"text","data-testid":D,value:M,placeholder:"#7C3AED",onChange:z=>x(S,C,z.target.value===""?void 0:z.target.value),style:sr})]},C.key)}if(T==="number-list"){const M=Array.isArray(N)?N.join(", "):"";return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("input",{type:"text","data-testid":D,value:M,placeholder:n("layout_editor.array_editor.number_list_placeholder"),onChange:O=>{const z=O.target.value.split(",").map(H=>H.trim()).filter(H=>H!=="").map(H=>Number(H)).filter(H=>!Number.isNaN(H));x(S,C,z)},style:sr})]},C.key)}const B=N==null?"":String(N);return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("input",{type:"text","data-testid":D,value:B,placeholder:T==="icon"?n("layout_editor.array_editor.icon_placeholder"):A,onChange:M=>x(S,C,M.target.value===""?void 0:M.target.value),style:sr})]},C.key)})]},S)),i.jsx("button",{type:"button","data-testid":"g7le-array-add",onClick:_,style:jN,children:n("layout_editor.array_editor.add",{item:d})})]}):i.jsx("div",{className:"g7le-node-editor g7le-node-editor--array","data-testid":"g7le-array-editor-misconfigured",style:Lh,children:n("layout_editor.array_editor.no_array_prop")})}const NN={display:"flex",flexDirection:"column",gap:8,width:"100%",marginBottom:12},MN={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:2},LN={display:"flex",flexDirection:"column",gap:4,padding:8,border:"1px solid #e2e8f0",borderRadius:8,background:"#f8fafc"},PN={display:"flex",gap:4,alignItems:"center"},ON={fontSize:11,fontWeight:700,color:"#64748b"},Wn={display:"flex",flexWrap:"wrap",gap:6,alignItems:"center"},jn={fontSize:11,color:"#475569",minWidth:64,flexShrink:0},sr={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},BN={width:32,height:28,padding:0,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",cursor:"pointer",flexShrink:0},Mh={padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},WN={padding:"2px 6px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},jN={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},Lh={fontSize:11,color:"#94a3b8",fontStyle:"italic"},HN={fontSize:11,color:"#b45309",fontStyle:"italic",padding:"4px 2px"};function FN(e,t){return e?e.startsWith("$t:")?t(e.slice(3)):e:null}function KN(e){const{params:t,t:n}=e,o=Array.isArray(t?.groups)?t.groups:[];return o.length===0?i.jsx("div",{className:"g7le-node-editor g7le-node-editor--array-group","data-testid":"g7le-array-group-misconfigured",style:GN,children:n("layout_editor.array_editor.no_array_prop")}):i.jsx("div",{className:"g7le-node-editor g7le-node-editor--array-group","data-testid":"g7le-array-group-editor",style:VN,children:o.map((r,s)=>{const a=FN(r.title,n),{title:l,...d}=r;return i.jsxs("div",{"data-testid":`g7le-array-group-${r.arrayProp??s}`,style:UN,children:[a&&i.jsx("div",{style:qN,children:a}),i.jsx(Nh,{...e,params:d})]},r.arrayProp??s)})})}const VN={display:"flex",flexDirection:"column",gap:16,width:"100%",marginBottom:12},UN={display:"flex",flexDirection:"column",gap:4},qN={fontSize:12,fontWeight:700,color:"#1e293b",borderBottom:"1px solid #e2e8f0",paddingBottom:4},GN={fontSize:11,color:"#94a3b8",fontStyle:"italic"},YN=/\{\{.*?\}\}/;function XN(e){return typeof e=="string"&&YN.test(e)}function JN(e,t,n){return e?e.startsWith("$t:")?t(e.slice(3)):e:n}function ZN(e){const{node:t,params:n,t:o,onPatchNode:r}=e,s=typeof n?.arrayProp=="string"?n.arrayProp:null,a=typeof n?.idField=="string"?n.idField:"id",l=typeof n?.cellChildrenProp=="string"?n.cellChildrenProp:"cellChildren",d=typeof n?.cellChildComponent=="string"?n.cellChildComponent:"Div",c=JN(typeof n?.itemLabel=="string"?n.itemLabel:void 0,o,o("layout_editor.array_editor.item")),[p,f]=u.useState(null),b=s?(t.props??{})[s]:void 0,g=Array.isArray(b)?b:[],m=u.useCallback($=>{if(!s)return;const S={...t.props??{}};S[s]=$,r({...t,props:S})},[s,t,r]),h=u.useCallback(()=>{const $=n?.newItem;return $&&typeof $=="object"?JSON.parse(JSON.stringify($)):{[a]:"",[l]:[]}},[n,a,l]),v=u.useCallback(()=>{m([...g,h()])},[m,g,h]),y=u.useCallback($=>{m(g.filter((S,C)=>C!==$)),f(null)},[m,g]),_=u.useCallback(($,S)=>{const C=$+S;if(C<0||C>=g.length)return;const T=[...g];[T[$],T[C]]=[T[C],T[$]],m(T)},[m,g]),w=u.useCallback(($,S)=>{const C=g.map((T,E)=>E===$?{...T,[a]:S}:T);m(C)},[g,m,a]),k=u.useCallback($=>({type:"composite",name:"CardGridCell",children:Array.isArray($[l])?$[l]:[]}),[l]),x=u.useCallback($=>S=>{const C=Array.isArray(S.children)?S.children:[],T=g.map((E,A)=>A===$?{...E,[l]:C}:E);m(T)},[g,m,l]);return s?XN(b)||b!==void 0&&!Array.isArray(b)?i.jsx("div",{className:"g7le-node-editor g7le-node-editor--cell-tree","data-testid":"g7le-cell-tree-bound",style:lM,children:o("layout_editor.array_editor.bound_degraded")}):i.jsxs("div",{className:"g7le-node-editor g7le-node-editor--cell-tree","data-testid":"g7le-cell-tree-editor",style:QN,children:[i.jsx("div",{style:RN,children:o("layout_editor.cell_tree_editor.columns_title")}),g.length===0&&i.jsx("div",{"data-testid":"g7le-cell-tree-empty",style:Oh,children:o("layout_editor.array_editor.empty")}),g.map(($,S)=>{const C=typeof $[a]=="string"?$[a]:"",T=p===S;return i.jsxs("div",{"data-testid":`g7le-cell-tree-row-${S}`,style:eM,children:[i.jsxs("div",{style:tM,children:[i.jsxs("span",{style:nM,children:["#",S+1]}),i.jsx("input",{type:"text","data-testid":`g7le-cell-tree-id-${S}`,value:C,placeholder:o("layout_editor.cell_tree_editor.id_placeholder"),onChange:E=>w(S,E.target.value),style:oM}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-up-${S}`,title:o("layout_editor.array_editor.move_up"),disabled:S===0,onClick:()=>_(S,-1),style:Ph,children:"↑"}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-down-${S}`,title:o("layout_editor.array_editor.move_down"),disabled:S===g.length-1,onClick:()=>_(S,1),style:Ph,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-remove-${S}`,title:o("layout_editor.array_editor.remove"),onClick:()=>y(S),style:rM,children:"✕"})]}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-toggle-${S}`,onClick:()=>f(T?null:S),style:iM,children:o(T?"layout_editor.cell_tree_editor.collapse_cells":"layout_editor.cell_tree_editor.expand_cells")}),T&&i.jsx("div",{"data-testid":`g7le-cell-tree-cells-${S}`,style:sM,children:i.jsx(Rg,{...e,node:k($),params:{childComponent:d},onPatchNode:x(S)})})]},S)}),i.jsx("button",{type:"button","data-testid":"g7le-cell-tree-add",onClick:v,style:aM,children:o("layout_editor.cell_tree_editor.add_column",{item:c})})]}):i.jsx("div",{className:"g7le-node-editor g7le-node-editor--cell-tree","data-testid":"g7le-cell-tree-misconfigured",style:Oh,children:o("layout_editor.array_editor.no_array_prop")})}const QN={display:"flex",flexDirection:"column",gap:8,width:"100%",marginBottom:12},RN={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:2},eM={display:"flex",flexDirection:"column",gap:6,padding:8,border:"1px solid #e2e8f0",borderRadius:8,background:"#f8fafc"},tM={display:"flex",gap:4,alignItems:"center"},nM={fontSize:11,fontWeight:700,color:"#64748b",flexShrink:0},oM={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},Ph={padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},rM={padding:"2px 6px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},iM={padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#2563eb",cursor:"pointer",alignSelf:"flex-start"},sM={paddingLeft:8,borderLeft:"2px solid #e2e8f0"},aM={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},Oh={fontSize:11,color:"#94a3b8",fontStyle:"italic"},lM={fontSize:11,color:"#b45309",fontStyle:"italic",padding:"4px 2px"};function dM(e,t,n){const o=Pe(e,t);if(!n||n.length===0)return{measured:[],grid:o};const r=[];for(const s of o.rows)for(const a of s.cells){const d=il(e,a,t).map(p=>`children.${p}`).join("."),c=n.find(p=>p.path===d||p.path.endsWith("."+d));c&&r.push({ref:a,box:{top:c.top,left:c.left,width:c.width,height:c.height}})}return{measured:r,grid:o}}const yl=26,bl=50,ml=6,Bh=44,Wh=18,jh="g7le-table-inplace-empty-cell-style";function cM(){if(typeof document>"u"||document.getElementById(jh))return;const e=document.createElement("style");e.id=jh,e.textContent=".g7le-preview-frame td[data-editor-name],.g7le-preview-frame th[data-editor-name]{min-width:56px;height:38px;}.g7le-preview-frame table[data-editor-name]{min-width:120px;}",document.head.appendChild(e)}function uM({node:e,params:t,nodeBox:n,cellBoxes:o,selectedCellPath:r,colorScheme:s,t:a,onPatchNode:l,onRequestInlineEdit:d}){const c=u.useMemo(()=>t&&typeof t=="object"?t:null,[t]),{measured:p,grid:f}=u.useMemo(()=>dM(e,c,o),[e,c,o]),[b,g]=u.useState(null),[m,h]=u.useState(null),v=u.useMemo(()=>{if(!r)return null;for(const j of f.rows)for(const ne of j.cells){const pe=il(e,ne,c).map(Q=>`children.${Q}`).join(".");if(r===pe||r.startsWith(pe+"."))return{r:ne.gridRow,c:ne.gridCol}}return null},[r,f,e,c]),y=u.useMemo(()=>b&&Ve(f,b.r,b.c)?b:v,[b,v,f]),[_,w]=u.useState(!1),[k,x]=u.useState(s==="dark"?"dark":"light"),[$,S]=u.useState(null),[C,T]=u.useState(null),E=u.useRef(null),A=u.useCallback(()=>{E.current!==null&&(clearTimeout(E.current),E.current=null)},[]),N=u.useCallback(()=>{A(),E.current=setTimeout(()=>{S(null),T(null),E.current=null},240)},[A]);u.useEffect(()=>()=>A(),[A]),u.useEffect(()=>{cM()},[]);const D=u.useCallback(j=>l(j),[l]),B=u.useMemo(()=>y?Ve(f,y.r,y.c):null,[f,y]),M=u.useMemo(()=>B&&typeof B.cell.props?.className=="string"?B.cell.props.className:"",[B]),O=u.useCallback(j=>D(sl(e,c,j)),[e,c,D]),z=u.useCallback(j=>D(sh(e,c,j)),[e,c,D]),H=u.useCallback((j,ne)=>D(ah(e,c,j,ne)),[e,c,D]),P=u.useCallback(j=>D(dh(e,c,j)),[e,c,D]),I=u.useCallback(j=>D(ch(e,c,j)),[e,c,D]),L=u.useCallback((j,ne)=>D(lh(e,c,j,ne)),[e,c,D]),F=u.useCallback(j=>{if(!B)return;const ne=B.gridRow,pe=B.gridCol,Q=j==="down"?ne+B.rowSpan:ne+B.rowSpan-1,le=j==="right"?pe+B.colSpan:pe+B.colSpan-1;if(Q>=f.rows.length||le>=f.colCount)return;const Ae=al(e,c,ne,pe,Q,le);Ae.ok&&D(Ae.table)},[B,f,e,c,D]),Y=!!(B&&B.gridCol+B.colSpan!y||!m||!Ve(f,m.r,m.c)?null:{r0:Math.min(y.r,m.r),c0:Math.min(y.c,m.c),r1:Math.max(y.r,m.r),c1:Math.max(y.c,m.c)},[y,m,f]),Z=u.useMemo(()=>{if(!X)return[];const j=new Set,ne=[];for(const pe of f.rows)for(const Q of pe.cells)if(Q.gridRow>=X.r0&&Q.gridRow<=X.r1&&Q.gridCol>=X.c0&&Q.gridCol<=X.c1){const le=`${Q.gridRow}:${Q.gridCol}`;j.has(le)||(j.add(le),ne.push({r:Q.gridRow,c:Q.gridCol}))}return ne},[X,f]),ae=Z.length>1,oe=u.useCallback(()=>{if(!X)return;const j=al(e,c,X.r0,X.c0,X.r1,X.c1);j.ok&&(D(j.table),h(null))},[X,e,c,D]),G=u.useCallback(()=>{y&&D(uh(e,c,y.r,y.c))},[e,c,y,D]),ee=u.useMemo(()=>{const j=c?.cellBorder;return j&&typeof j=="object"?j:null},[c]),ge=u.useMemo(()=>{const j=c?.cellBackground;return j&&typeof j=="object"?j:null},[c]),V=u.useMemo(()=>{const j=c?.cellPadding;return j&&typeof j=="object"?j:null},[c]),te=u.useMemo(()=>{if(_){const j=new Set,ne=[];for(const pe of f.rows)for(const Q of pe.cells){const le=`${Q.gridRow}:${Q.gridCol}`;j.has(le)||(j.add(le),ne.push({r:Q.gridRow,c:Q.gridCol}))}return ne}return ae?Z:y?[{r:y.r,c:y.c}]:[]},[_,ae,Z,y,f]),be=u.useCallback(j=>{if(te.length===0)return;let ne=e;for(const pe of te){const Q=(ee?.colors??[]).map(Ae=>Ae.token),le=j.split(/\s+/).filter(Ae=>Ae&&!Q.includes(Ae)).join(" ");ne=Ii(ne,c,pe.r,pe.c,le)}D(ne)},[e,c,te,ee,D]),Ee=u.useMemo(()=>{const j=(ee?.sides??[]).find(Q=>Q.value==="all")??(ee?.sides??[])[0],ne=(ee?.widths??[]).find(Q=>Q.value!=="none");if(!j||!ne)return[];const pe=ne.suffix??"";return[pe?`${j.prefix}${pe}`:j.prefix]},[ee]),De=u.useCallback((j,ne,pe)=>{if(Ee.length===0)return j;const Q=(ee?.sides??[]).map(Le=>Le.prefix),le=Ve(Pe(j,c),ne,pe),dt=(typeof le?.cell?.props?.className=="string"?le.cell.props.className:"").split(/\s+/).filter(Boolean);if(dt.some(Le=>Q.some(je=>Le===je||Le.startsWith(je+"-")&&/^-?\d+$/.test(Le.slice(je.length+1)))))return j;const ot=[...dt,...Ee].join(" ").trim();return Ii(j,c,ne,pe,ot)},[Ee,ee,c]),Se=u.useCallback((j,ne)=>{if(j.length===0)return;const pe=new Set(j.map(le=>`${le.r}:${le.c}`));let Q=e;for(const le of j){if(Q=De(Q,le.r,le.c),Q=Jt(Q,c,le.r,le.c,"borderColor",ne),le.r>0&&!pe.has(`${le.r-1}:${le.c}`)){const Ae=Ve(Pe(Q,c),le.r-1,le.c);Ae&&(Q=Jt(Q,c,Ae.gridRow,Ae.gridCol,"borderBottomColor",ne))}if(le.c>0&&!pe.has(`${le.r}:${le.c-1}`)){const Ae=Ve(Pe(Q,c),le.r,le.c-1);Ae&&(Q=Jt(Q,c,Ae.gridRow,Ae.gridCol,"borderRightColor",ne))}}D(Q)},[e,c,D,De]),Ue=u.useMemo(()=>(ee?.colors??[]).map(j=>j.token).filter(Boolean),[ee]),Me=u.useCallback(j=>{if(te.length===0||Ue.length===0)return;let ne=e;for(const pe of te)ne=De(ne,pe.r,pe.c),ne=ho(ne,c,pe.r,pe.c,j,Ue,k);D(ne)},[te,e,c,D,De,Ue,k]),Oe=u.useCallback(j=>Se(te,j),[Se,te]),Ye=u.useMemo(()=>{if(k==="dark")return"";const j=B?.cell.props?.style;return typeof j?.borderColor=="string"?j.borderColor:""},[B,k]),ze=u.useCallback((j,ne)=>{if(te.length===0)return;let pe=e;for(const Q of te)pe=Jt(pe,c,Q.r,Q.c,j,ne);D(pe)},[te,e,c,D]),Xe=u.useMemo(()=>(ge?.colors??[]).map(j=>j.token).filter(j=>!!j),[ge]),ve=u.useCallback(j=>{if(te.length===0||Xe.length===0)return;let ne=e;for(const pe of te)ne=ho(ne,c,pe.r,pe.c,j,Xe,k);D(ne)},[te,e,c,D,Xe,k]),qe=u.useCallback(j=>ze("backgroundColor",j),[ze]),We=u.useCallback(()=>{if(te.length===0)return;let j=e;for(const ne of te)j=ho(j,c,ne.r,ne.c,void 0,Xe,k),k==="light"&&(j=Jt(j,c,ne.r,ne.c,"backgroundColor",void 0));D(j)},[te,e,c,D,Xe,k]),ce=u.useCallback(j=>ze("padding",j),[ze]),q=u.useMemo(()=>{if(k==="dark")return"";const j=B?.cell.props?.style;return typeof j?.backgroundColor=="string"?j.backgroundColor:""},[B,k]),ie=u.useMemo(()=>typeof B?.cell.props?.className=="string"?B.cell.props.className:"",[B]),se=u.useMemo(()=>{const j=B?.cell.props?.style;return typeof j?.padding=="string"?j.padding:""},[B]),me=u.useCallback(j=>{const ne=j.currentTarget,pe=ne.style.pointerEvents;ne.style.pointerEvents="none";const Q=document.elementFromPoint(j.clientX,j.clientY);ne.style.pointerEvents=pe;const le=Q?.closest?.("[data-dnd-handle-path]");le&&le.dispatchEvent(new PointerEvent("pointerdown",{bubbles:!0,cancelable:!0,clientX:j.clientX,clientY:j.clientY,pointerId:j.pointerId,pointerType:j.pointerType,button:j.button,isPrimary:!0}))},[]),Ce=u.useMemo(()=>{const j=new Map;for(const ne of p)j.has(ne.ref.gridCol)||j.set(ne.ref.gridCol,ne.box);return j},[p]),$e=u.useMemo(()=>{const j=new Map;for(const ne of p)j.has(ne.ref.gridRow)||j.set(ne.ref.gridRow,ne.box);return j},[p]);if(p.length===0)return null;const U=!!(B&&(B.colSpan>1||B.rowSpan>1)),ue=C!==null?C:y?.c??null,fe=$!==null?$:y?.r??null,xe=n.top-yl-ml-Bh,he=n.left-bl-ml-Bh;return i.jsxs("div",{className:"g7le-table-inplace","data-testid":"g7le-table-inplace",style:{position:"absolute",inset:0,pointerEvents:"none",zIndex:j7},children:[p.map(j=>{const ne=y&&y.r===j.ref.gridRow&&y.c===j.ref.gridCol,pe=X&&j.ref.gridRow>=X.r0&&j.ref.gridRow<=X.r1&&j.ref.gridCol>=X.c0&&j.ref.gridCol<=X.c1;return i.jsx("div",{"data-testid":`g7le-inplace-cell-${j.ref.gridRow}-${j.ref.gridCol}`,role:"button",tabIndex:-1,"aria-label":a("layout_editor.table_inplace.select_cell"),onMouseEnter:()=>{A(),S(j.ref.gridRow),T(j.ref.gridCol)},onMouseLeave:()=>{N()},onPointerDown:Q=>me(Q),onClick:Q=>{if(Q.stopPropagation(),Q.shiftKey&&(b||y))h({r:j.ref.gridRow,c:j.ref.gridCol});else{g({r:j.ref.gridRow,c:j.ref.gridCol}),h(null);const le=il(e,j.ref,c).map(Ae=>`children.${Ae}`).join(".");d?.(le)}},style:{position:"absolute",top:j.box.top,left:j.box.left,width:j.box.width,height:j.box.height,minWidth:Wh,minHeight:Wh,boxSizing:"border-box",pointerEvents:"auto",cursor:"pointer",outline:ne?"2px solid #2563eb":"none",outlineOffset:-2,background:pe&&!ne?"rgba(37,99,235,0.14)":"transparent"}},`cell-${j.ref.gridRow}-${j.ref.gridCol}`)}),i.jsx("div",{"data-testid":"g7le-inplace-col-rail",onMouseEnter:A,onMouseLeave:N,style:{position:"absolute",top:xe,left:n.left,width:n.width,height:yl,pointerEvents:"none"},children:ue!==null&&Ce.has(ue)&&(()=>{const j=ue,ne=Ce.get(j),pe=Ci(f,j,-1),Q=Ci(f,j,1),le=ne.left-n.left;return i.jsxs("div",{"data-testid":`g7le-inplace-colgutter-${j}`,onMouseEnter:()=>{A(),T(j)},onMouseLeave:N,style:{position:"absolute",top:0,left:le,width:ne.width,minWidth:96,height:yl,display:"flex",gap:3,justifyContent:"center",alignItems:"center",pointerEvents:"auto"},children:[i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.move_col_left"),disabled:!pe.ok,onClick:()=>L(j,-1),"data-testid":`g7le-inplace-col-left-${j}`,style:pe.ok?_n:Ti,children:"←"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.add_col"),onClick:()=>P(j),"data-testid":`g7le-inplace-col-add-${j}`,style:_n,children:"+"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.remove_col"),disabled:f.colCount<=1,onClick:()=>I(j),"data-testid":`g7le-inplace-col-remove-${j}`,style:Hh,children:"✕"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.move_col_right"),disabled:!Q.ok,onClick:()=>L(j,1),"data-testid":`g7le-inplace-col-right-${j}`,style:Q.ok?_n:Ti,children:"→"})]},`colgut-${j}`)})()}),i.jsx("div",{"data-testid":"g7le-inplace-row-rail",style:{position:"absolute",top:n.top,left:he,width:bl,height:n.height,pointerEvents:"none"},children:fe!==null&&$e.has(fe)&&(()=>{const j=fe,ne=$e.get(j),pe=Si(f,j,-1),Q=Si(f,j,1),le=ne.top-n.top;return i.jsxs("div",{"data-testid":`g7le-inplace-rowgutter-${j}`,onMouseEnter:()=>{A(),S(j)},onMouseLeave:N,style:{position:"absolute",top:le,left:0,width:bl,height:ne.height,minHeight:48,display:"grid",gridTemplateColumns:"repeat(2, 22px)",gridAutoRows:"22px",gap:3,justifyContent:"center",alignContent:"center",pointerEvents:"auto"},children:[i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.move_row_up"),disabled:!pe.ok,onClick:()=>H(j,-1),"data-testid":`g7le-inplace-row-up-${j}`,style:pe.ok?_n:Ti,children:"↑"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.add_row"),onClick:()=>O(j),"data-testid":`g7le-inplace-row-add-${j}`,style:_n,children:"+"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.remove_row"),disabled:f.rows.length<=1,onClick:()=>z(j),"data-testid":`g7le-inplace-row-remove-${j}`,style:Hh,children:"✕"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.move_row_down"),disabled:!Q.ok,onClick:()=>H(j,1),"data-testid":`g7le-inplace-row-down-${j}`,style:Q.ok?_n:Ti,children:"↓"})]},`rowgut-${j}`)})()}),i.jsxs("div",{"data-testid":"g7le-inplace-corner-add",style:{position:"absolute",top:n.top+n.height+ml,left:n.left,display:"flex",flexDirection:"column",gap:6,pointerEvents:"auto",minWidth:200,maxWidth:Math.max(240,n.width),background:"#fff",border:"1px solid #e2e8f0",borderRadius:8,padding:8,boxShadow:"0 2px 8px rgba(0,0,0,0.12)"},children:[i.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap"},children:[i.jsxs("button",{type:"button","data-testid":"g7le-inplace-add-row-bottom",onClick:()=>O(f.rows.length-1),style:Fh,children:["+ ",a("layout_editor.table_inplace.add_row")]}),i.jsxs("button",{type:"button","data-testid":"g7le-inplace-add-col-right",onClick:()=>P(f.colCount-1),style:Fh,children:["+ ",a("layout_editor.table_inplace.add_col")]})]}),!y&&i.jsx("div",{"data-testid":"g7le-inplace-select-hint",style:{fontSize:11,color:"#94a3b8",borderTop:"1px solid #f1f5f9",paddingTop:6},children:a("layout_editor.table_inplace.select_cell_hint")}),y&&i.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:6,borderTop:"1px solid #f1f5f9",paddingTop:6},children:[ae&&i.jsx("div",{"data-testid":"g7le-inplace-range-count",style:{fontSize:11,color:"#2563eb"},children:a("layout_editor.table_inplace.range_selected",{count:Z.length})}),i.jsxs("div",{style:{display:"flex",gap:6,flexWrap:"wrap",alignItems:"center"},children:[ae?i.jsx("button",{type:"button","data-testid":"g7le-inplace-merge-range",onClick:oe,style:ar,children:a("layout_editor.table_inplace.merge_range")}):i.jsxs(i.Fragment,{children:[i.jsx("button",{type:"button","data-testid":"g7le-inplace-merge-right",disabled:!Y,onClick:()=>F("right"),style:Y?ar:vl,children:a("layout_editor.table_inplace.merge_right")}),i.jsx("button",{type:"button","data-testid":"g7le-inplace-merge-down",disabled:!K,onClick:()=>F("down"),style:K?ar:vl,children:a("layout_editor.table_inplace.merge_down")})]}),i.jsx("button",{type:"button","data-testid":"g7le-inplace-unmerge",disabled:!U,onClick:G,style:U?ar:vl,children:a("layout_editor.table_inplace.unmerge")})]}),i.jsxs("div",{"data-testid":"g7le-inplace-cell-color",style:{borderTop:"1px solid #f1f5f9",paddingTop:6,display:"flex",flexDirection:"column",gap:6},children:[i.jsxs("label",{style:{display:"flex",alignItems:"center",gap:6,fontSize:11,color:"#475569",cursor:"pointer"},children:[i.jsx("input",{type:"checkbox","data-testid":"g7le-inplace-border-all-toggle",checked:_,onChange:j=>w(j.target.checked)}),a("layout_editor.table_inplace.border_apply_all")]}),i.jsx(kh,{colorScheme:k,onChange:x,t:a}),ee&&i.jsx("div",{"data-testid":"g7le-inplace-cell-border",children:i.jsx(yh,{className:_?"":M,catalog:ee,t:a,onChange:be,colorScheme:k,onPresetToken:Me,colorStyle:_?"":Ye,onColorStyle:Oe})}),i.jsx("div",{"data-testid":"g7le-inplace-cell-fill",children:i.jsx(_h,{colorStyle:_?"":q,className:_?"":ie,catalog:ge,t:a,colorScheme:k,onPresetToken:ve,onCustomColor:qe,onClear:We})})]}),i.jsx("div",{"data-testid":"g7le-inplace-cell-padding",style:{borderTop:"1px solid #f1f5f9",paddingTop:6},children:i.jsx(xh,{paddingStyle:_?"":se,catalog:V,t:a,onChange:ce})})]})]})]})}const _n={width:22,height:22,lineHeight:"20px",padding:0,fontSize:13,border:"1px solid #cbd5e1",borderRadius:5,background:"#fff",color:"#475569",cursor:"pointer",boxShadow:"0 1px 3px rgba(0,0,0,0.18)"},Hh={..._n,border:"1px solid #fecaca",color:"#dc2626"},Ti={..._n,cursor:"not-allowed",opacity:.4,color:"#94a3b8",borderColor:"#e2e8f0"},ar={padding:"4px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",boxShadow:"0 1px 2px rgba(0,0,0,0.12)"},vl={...ar,cursor:"not-allowed",opacity:.4},Fh={padding:"3px 8px",fontSize:11,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"};let Kh=!1;function pM(){Kh||(Pn("children",Rg),Pn("table",rN),Pn("array",Nh),Pn("array-group",KN),Pn("array-cell-tree",ZN),ja("table",uM),Kh=!0)}function fM(){if(typeof window>"u")return;const e=window.G7Core;if(!e)return;const t=e.layoutEditor,n=Array.isArray(t?.__queue)?t.__queue:[],o=Array.isArray(t?.__readyCallbacks)?t.__readyCallbacks:[];e.layoutEditor={registerWidget:Ze,registerNodeEditor:Pn,registerCanvasOverlay:ja,onReady:r=>{typeof r=="function"&&r()}};for(const r of n){const[s,...a]=r;try{s==="widget"?Ze(a[0],a[1]):s==="nodeEditor"?Pn(a[0],a[1]):s==="canvasOverlay"&&ja(a[0],a[1])}catch{}}for(const r of o)try{r()}catch{}}const gM=1280;_z(),pM(),fM();async function hM(e){if(typeof fetch!="function")return[];try{const t=await fetch(en(`/api/admin/templates/${encodeURIComponent(e)}/editor/permission-candidates`,"json"),{credentials:"same-origin",headers:Ne()});if(!t.ok)return[];const o=(await t.json().catch(()=>null))?.data?.permissions;if(!Array.isArray(o))return[];const r=[];for(const s of o)if(s&&typeof s=="object"){const a=s.key,l=s.name;typeof a=="string"&&a.length>0&&r.push({value:a,label:typeof l=="string"&&l?l:a})}return r}catch{return[]}}function yM({templateIdentifier:e}){FD({templateIdentifier:e}),KD(e);const{state:t,dispatch:n}=Qe(),{t:o}=tt(),r=bo(),s=Dp(),a=XD(),l=t.selectedRoute?.layoutName??null,d=RD(e,l),c=t.editMode==="extension",p=u.useMemo(()=>c?ZD(a):s,[c,a,s]),[f,b]=u.useState(null),[g,m]=u.useState(null),[h,v]=u.useState([]),[y,_]=u.useState("user"),[w,k]=u.useState(null),[x,$]=u.useState(null),[S,C]=u.useState([]);u.useEffect(()=>{let q=!1;return(async()=>{try{const ie=await fetch(en(`/api/templates/${encodeURIComponent(e)}/components`,"json"),{credentials:"same-origin",headers:{Accept:"application/json"}});if(!ie.ok)return;const se=await ie.json().catch(()=>null);!q&&se&&typeof se=="object"&&b(se)}catch{}})(),()=>{q=!0}},[e]),u.useEffect(()=>{let q=!1;return(async()=>{const{spec:ie,sampleGlobalSources:se}=await ab({templateIdentifier:e,coreSeed:e8()});q||(m(ie),v(se),mM(e,ie,se))})(),()=>{q=!0}},[e]),u.useEffect(()=>{let q=!1;return(async()=>{if(typeof fetch=="function")try{const ie=await fetch(`/api/admin/templates/${encodeURIComponent(e)}`,{credentials:"same-origin",headers:Ne()});if(!ie.ok)return;const me=(await ie.json().catch(()=>null))?.data,Ce=me?.type;q||((Ce==="admin"||Ce==="user")&&_(Ce),typeof me?.name=="string"&&me.name&&k(me.name),typeof me?.version=="string"&&me.version&&$(me.version))}catch{}})(),()=>{q=!0}},[e]),u.useEffect(()=>{let q=!1;return(async()=>{if(typeof fetch=="function")try{const ie=await fetch("/api/admin/templates/?per_page=100&page=1",{credentials:"same-origin",headers:Ne()});if(!ie.ok)return;const me=(await ie.json().catch(()=>null))?.data?.data;if(!q&&Array.isArray(me)){const Ce=[];for(const $e of me){if(!$e||typeof $e!="object")continue;const U=$e.identifier;if(typeof U!="string"||!U||$e.is_pending===!0)continue;const fe=$e.type==="admin"?"admin":"user",xe=$e.name,he=$e.version;Ce.push({identifier:U,name:typeof xe=="string"?xe:U,version:typeof he=="string"?he:"",type:fe})}C(Ce)}}catch{}})(),()=>{q=!0}},[e]);const T=g?.nesting??null,E=t.selectedRoute?.path??null,A=t.editMode,N=t.selectedRoute?.layoutName??(c?a.document?.hostLayoutName??null:null),D=t.routeTree,B=u.useMemo(()=>{if(A!=="extension"||!N)return null;const q=xl(D,N);return q||`__base__/${N}`},[A,N,D]),M=c&&t.returnRoute===null&&!!N;u.useEffect(()=>{if(!M||!N)return;const q=xl(D,N);q&&n({type:"SET_RETURN_ROUTE",route:{path:q,layoutName:N}})},[M,N,D,n]),u.useEffect(()=>{const q=xD(A,E,B),ie=wD(g?.states?.groups,q);n({type:"SET_AVAILABLE_STATES",states:ie,activeStateId:kD(ie)})},[g,A,E,B,n]);const[O,z]=u.useState([]);u.useEffect(()=>{let q=!1;return(async()=>{const ie=await hM(e);q||z(ie)})(),()=>{q=!0}},[e]),VD(),UD();const H=u.useCallback(q=>{const ie=t.routeTree,se=q.split("?")[0]?.split("#")[0]??q;return bM(ie,se)?"route_in_tree":"route_not_in_tree"},[t.routeTree]),P=u.useCallback(q=>{const ie=q.split("?")[0]?.split("#")[0]??q,se=_l(t.routeTree,ie);se&&(p.isDirty&&!(!(typeof window<"u")||window.confirm(o("layout_editor.chrome.dirty_guard.message")))||n({type:"SELECT_ROUTE",route:{path:se.path,layoutName:se.layoutName}}))},[t.routeTree,p.isDirty,n]),I=u.useRef([]),L=u.useCallback(q=>{I.current=q},[]),[F,Y]=u.useState(null),K=u.useCallback(()=>Y(null),[]),X=u.useRef(null),Z=u.useRef(null);u.useEffect(()=>{const q=Z.current,ie=X.current;if(!q||!ie||typeof ResizeObserver>"u")return;const se=()=>{ie.style.setProperty("--g7le-header-h",`${Math.round(q.getBoundingClientRect().height)}px`)};se();const me=new ResizeObserver(se);return me.observe(q),()=>me.disconnect()},[]);const ae=u.useCallback(()=>{p.reload()},[p]),oe=u.useCallback(()=>{p.isDirty&&!(!(typeof window<"u")||window.confirm(o("layout_editor.chrome.dirty_guard.message")))||window.G7Core?.dispatch?.({handler:"openWindow",params:{path:`/admin/templates/${y}`,target:"_self"}})},[p.isDirty,o,y]),G=u.useCallback(q=>{if(!q||q===e||p.isDirty&&!(typeof window<"u"?window.confirm(o("layout_editor.chrome.dirty_guard.message")):!0))return;const ie=ea(q);window.G7Core?.dispatch?.({handler:"openWindow",params:{path:ie,target:"_self"}})},[e,p.isDirty,o]),ee=u.useCallback(()=>{const q=r.open({ariaLabel:o("layout_editor.custom_assets.title"),width:860,maxHeightRatio:.86,content:u.createElement(wE,{templateIdentifier:e,t:o,onClose:()=>r.close(q)})})},[r,e,o]),ge=typeof window<"u"&&(!!window.G7Config?.customAssetsDisabled||new URLSearchParams(window.location.search).get("custom")==="off"),V=u.useCallback(()=>{if(typeof window>"u"||p.isDirty&&!window.confirm(o("layout_editor.chrome.dirty_guard.message")))return;const q=new URL(window.location.href);if(ge){if(q.searchParams.delete("custom"),q.toString()===window.location.href){window.location.reload();return}}else q.searchParams.set("custom","off");window.G7Core?.dispatch?.({handler:"openWindow",params:{path:`${q.pathname}${q.search}${q.hash}`,target:"_self"}})},[p.isDirty,ge,o]),te=u.useCallback(()=>{const q=s7(e,t.selectedRoute?.path??null);window.G7Core?.dispatch?.({handler:"openWindow",params:{path:q}})},[e,t.selectedRoute]),be=u.useCallback(()=>{const q=t.selectedRoute?.layoutName??"";if(!q)return;const ie=r.open({ariaLabel:o("layout_editor.attachment_manager.title"),width:720,maxHeightRatio:.82,content:u.createElement(Bl,{templateIdentifier:e,layoutName:q,t:o,onClose:()=>r.close(ie)})})},[r,e,t.selectedRoute,o]),Ee=u.useCallback(()=>{const q=t.selectedRoute?.layoutName??"";if(!q)return;const ie=Yy(s.document?.raw??{}),se=r.open({ariaLabel:o("layout_editor.translation_manager.title"),width:720,maxHeightRatio:.82,content:u.createElement(ym,{templateIdentifier:e,layoutName:q,t:o,referencedKeys:ie,onClose:()=>r.close(se)})})},[r,e,t.selectedRoute,o,s.document]),De=u.useCallback((q,ie)=>{const se=window.G7Core;if(se&&typeof se.t=="function"){const me=se.t(q,ie);if(me&&me!==q&&!me.startsWith("$t:"))return me}return o(q,ie)},[o]),Se=u.useCallback(()=>{if(!t.selectedRoute||t.editMode==="extension"||t.editMode==="iteration_item")return;const q=r.open({ariaLabel:o("layout_editor.page_settings.title",{name:t.selectedRoute.path??""}),width:1080,maxHeightRatio:.88,closeOnEscape:!1,content:u.createElement(m$,{templateIdentifier:e,spec:g,t:o,resolveLabel:De,permissionCandidates:O,onClose:()=>r.close(q)})})},[r,t.selectedRoute,t.editMode,o,De,e,g,O]),Ue=u.useCallback(async()=>{const q=await d.createPreview(s.document?.raw??null);if(q.kind!=="success"){const ie=q.kind==="network_error"?q.message:o("layout_editor.preview_action.no_document");typeof window<"u"&&window.alert(ie)}},[d,s.document,o]),Me=u.useCallback(()=>{const q=t.selectedRoute?.layoutName??"",ie=t.selectedRoute?.path??"",se=t.editMode==="extension"&&ie.startsWith("__extension__/")?ie.slice(14):null,me=se?{kind:"extension",extensionId:se}:q?{kind:"layout",layoutName:q}:null;if(!me)return;const Ce=r.open({ariaLabel:o("layout_editor.version_history.title"),width:640,maxHeightRatio:.82,content:u.createElement(nE,{templateIdentifier:e,target:me,t:o,onRestored:async $e=>{typeof $e=="number"&&(me.kind==="extension"?n({type:"SET_EXTENSION_VERSION",extensionId:me.extensionId,version:$e}):n({type:"SET_LAYOUT_VERSION",layoutName:me.layoutName,version:$e})),await p.reload()},onClose:()=>r.close(Ce)})})},[r,e,t.selectedRoute,t.editMode,o,p,n]),Oe=p.dirtyKeys.size>0||p.isDirty;u.useEffect(()=>{if(!Oe)return;const q=ie=>{ie.preventDefault(),ie.returnValue=""};return window.addEventListener("beforeunload",q),()=>window.removeEventListener("beforeunload",q)},[Oe]);const Ye=u.useCallback(()=>{!p.isDirty||!(!(typeof window<"u")||window.confirm(o("layout_editor.chrome.reset_guard.message")))||p.reload()},[p,o]),ze=u.useCallback(async()=>{const q=await p.save({sessionAddedPaths:I.current});Y(q),q.kind==="success"&&typeof q.newContentVersion=="number"&&(q.savedExtensionId?n({type:"SET_EXTENSION_VERSION",extensionId:q.savedExtensionId,version:q.newContentVersion}):q.savedLayoutName&&n({type:"SET_LAYOUT_VERSION",layoutName:q.savedLayoutName,version:q.newContentVersion}))},[p,n]),Xe=u.useCallback(()=>{const q=r.open({ariaLabel:o("layout_editor.shortcuts.title"),width:560,maxHeightRatio:.85,content:u.createElement(DE,{t:o,onClose:()=>r.close(q)})})},[r,o]),ve=u.useMemo(()=>({save:()=>{ze()},exit:oe,editCode:te,reset:Ye,translations:Ee,addElement:()=>{t.selectedRoute&&n({type:"TOGGLE_PALETTE"})},help:Xe,preview:()=>{t.selectedRoute?.layoutName&&Ue()}}),[ze,oe,te,Ye,Ee,t.selectedRoute,n,Xe,Ue]),[qe,We]=u.useState(!1);u.useEffect(()=>{const q=window.setInterval(()=>{We(!!window.__g7LayoutEditorHasSelection)},200);return()=>window.clearInterval(q)},[]),lp({handlers:ve,hasSelection:qe});const ce=p;return t.routesError?i.jsx("div",{className:"g7le-chrome g7le-chrome--routes-error","data-testid":"g7le-chrome-routes-error",style:{position:"fixed",inset:0,display:"flex",background:"#f8fafc",color:"#0f172a",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Apple SD Gothic Neo", "Noto Sans KR", sans-serif',fontSize:13,lineHeight:1.5,zIndex:9e3},children:i.jsx(qa,{error:t.routesError})}):i.jsx("div",{className:"g7le-chrome","data-testid":"g7le-chrome",ref:X,style:{position:"static",minHeight:"100vh",minWidth:gM,background:"#f8fafc",color:"#0f172a",fontFamily:'-apple-system, BlinkMacSystemFont, "Segoe UI", Roboto, "Helvetica Neue", Arial, "Apple SD Gothic Neo", "Noto Sans KR", sans-serif',fontSize:13,lineHeight:1.5,zIndex:9e3},children:i.jsxs(yy,{value:ce,children:[c&&a.needsHostPicker&&a.document&&i.jsx(QD,{hostLayouts:a.document.hostLayouts,extensionLabel:null,onSelect:a.selectHost}),i.jsxs("div",{className:"g7le-chrome__header","data-testid":"g7le-chrome-header",ref:Z,style:{position:"sticky",top:0,zIndex:20,background:"#f8fafc"},children:[i.jsx(Sy,{onSave:()=>{ze()},isDirty:p.isDirty,onExit:oe,onEditCode:te,onManageImages:be,onManageTranslations:Ee,onPageSettings:Se,onReset:Ye,onShowShortcuts:Xe,onPreview:Ue,onShowVersions:Me,templateName:w,templateVersion:x,templateList:S,onSwitchTemplate:G,onToggleCustomAssets:V,customAssetsDisabled:ge,onManageCustomAssets:ee}),i.jsx(GE,{result:F,onDismiss:K,onLoadLatest:ae}),i.jsxs("div",{className:"g7le-chrome__device-toolbar","data-testid":"g7le-chrome-device-toolbar",style:{display:"flex",justifyContent:"center",padding:"6px 12px",background:"#f1f5f9",borderBottom:"1px solid #e2e8f0"},children:[i.jsx(vD,{}),i.jsx(_D,{})]})]}),i.jsxs("div",{className:"g7le-chrome__body",style:{display:"grid",gridTemplateColumns:"auto 1fr",alignItems:"stretch"},children:[i.jsx(f7,{}),i.jsx(gD,{manifest:f,nesting:T,componentPalette:g?.componentPalette??null,spec:g,permissionCandidates:O,sampleGlobalSources:h,resolveRouteMatch:H,onNavigateToDestination:P,onSessionAddedPathsChange:L})]}),i.jsx(vy,{})]})})}function _l(e,t){for(const n of e){if(n.kind==="route"&&n.path===t)return n;if(n.children&&n.children.length>0){const o=_l(n.children,t);if(o)return o}}return null}function bM(e,t){return _l(e,t)!==null}function xl(e,t){for(const n of e){if(n.kind==="route"&&n.layoutName===t&&typeof n.path=="string")return n.path;if(n.children&&n.children.length>0){const o=xl(n.children,t);if(o)return o}}return null}function mM(e,t,n){const o=[];Ya({sources:n,isGuestOnly:!1,warn:s=>{const a=/extension '([^']+)' override of core key '([^']+)'/.exec(s);a&&o.push(`${a[1]}:${a[2]}`)}});const r=t?.sampleData?.byDataSourceId?Object.keys(t.sampleData.byDataSourceId).length:0;iy({templateIdentifier:e,mergedSources:[...n.map(s=>({kind:s.kind,id:s.id}))],blockCounts:{controls:t?.controls?Object.keys(t.controls).length:0,componentCapabilities:t?.componentCapabilities?Object.keys(t.componentCapabilities).length:0,actionRecipes:t?.actionRecipes?Object.keys(t.actionRecipes).length:0,conditionRecipes:t?.conditionRecipes?Object.keys(t.conditionRecipes).length:0,paletteGroups:t?.componentPalette?.groups?.length??0,stateGroups:t?.states?.groups?.length??0,sampleDataIds:r},sampleGlobalSourceCount:n.length,sampleGlobalConflicts:o,timestamp:Date.now()})}function Vh({templateIdentifier:e,initialLocale:t}){return u.useEffect(()=>()=>{Zh(),Rh(),ty(),ny(),oy(),ry(),sy(),ay(),ly()},[]),i.jsx(hy,{templateIdentifier:e,initialLocale:t,children:i.jsx(my,{children:i.jsx(yM,{templateIdentifier:e})})})}if(typeof window<"u"){const e=window.G7Core||(window.G7Core={});if(e.__LayoutEditorChrome=Vh,typeof e.__onChromeReady=="function")try{e.__onChromeReady()}catch{}}dn.LayoutEditorChrome=Vh,Object.defineProperty(dn,Symbol.toStringTag,{value:"Module"})})(this.G7LayoutEditor=this.G7LayoutEditor||{},ReactJSXRuntime,React,ReactDOM); diff --git a/public/build/core/template-engine.min.js b/public/build/core/template-engine.min.js index a386983b..56b21084 100644 --- a/public/build/core/template-engine.min.js +++ b/public/build/core/template-engine.min.js @@ -1,23 +1,60 @@ -var CR=Object.defineProperty;var ER=(tn,na,ra)=>na in tn?CR(tn,na,{enumerable:!0,configurable:!0,writable:!0,value:ra}):tn[na]=ra;var M=(tn,na,ra)=>ER(tn,typeof na!="symbol"?na+"":na,ra);(function(tn){"use strict";function na(s,e){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}function ra(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var Ad={exports:{}},Ye={};var Mg;function a0(){if(Mg)return Ye;Mg=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),c=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),h=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),y=Symbol.for("react.activity"),v=Symbol.iterator;function S(H){return H===null||typeof H!="object"?null:(H=v&&H[v]||H["@@iterator"],typeof H=="function"?H:null)}var _={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x=Object.assign,A={};function D(H,T,fe){this.props=H,this.context=T,this.refs=A,this.updater=fe||_}D.prototype.isReactComponent={},D.prototype.setState=function(H,T){if(typeof H!="object"&&typeof H!="function"&&H!=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,H,T,"setState")},D.prototype.forceUpdate=function(H){this.updater.enqueueForceUpdate(this,H,"forceUpdate")};function O(){}O.prototype=D.prototype;function k(H,T,fe){this.props=H,this.context=T,this.refs=A,this.updater=fe||_}var L=k.prototype=new O;L.constructor=k,x(L,D.prototype),L.isPureReactComponent=!0;var B=Array.isArray;function q(){}var z={H:null,A:null,T:null,S:null},W=Object.prototype.hasOwnProperty;function de(H,T,fe){var he=fe.ref;return{$$typeof:s,type:H,key:T,ref:he!==void 0?he:null,props:fe}}function _e(H,T){return de(H.type,T,H.props)}function Se(H){return typeof H=="object"&&H!==null&&H.$$typeof===s}function Ie(H){var T={"=":"=0",":":"=2"};return"$"+H.replace(/[=:]/g,function(fe){return T[fe]})}var Fe=/\/+/g;function ze(H,T){return typeof H=="object"&&H!==null&&H.key!=null?Ie(""+H.key):T.toString(36)}function Et(H){switch(H.status){case"fulfilled":return H.value;case"rejected":throw H.reason;default:switch(typeof H.status=="string"?H.then(q,q):(H.status="pending",H.then(function(T){H.status==="pending"&&(H.status="fulfilled",H.value=T)},function(T){H.status==="pending"&&(H.status="rejected",H.reason=T)})),H.status){case"fulfilled":return H.value;case"rejected":throw H.reason}}throw H}function Q(H,T,fe,he,Ae){var se=typeof H;(se==="undefined"||se==="boolean")&&(H=null);var ge=!1;if(H===null)ge=!0;else switch(se){case"bigint":case"string":case"number":ge=!0;break;case"object":switch(H.$$typeof){case s:case e:ge=!0;break;case m:return ge=H._init,Q(ge(H._payload),T,fe,he,Ae)}}if(ge)return Ae=Ae(H),ge=he===""?"."+ze(H,0):he,B(Ae)?(fe="",ge!=null&&(fe=ge.replace(Fe,"$&/")+"/"),Q(Ae,T,fe,"",function(je){return je})):Ae!=null&&(Se(Ae)&&(Ae=_e(Ae,fe+(Ae.key==null||H&&H.key===Ae.key?"":(""+Ae.key).replace(Fe,"$&/")+"/")+ge)),T.push(Ae)),1;ge=0;var $e=he===""?".":he+":";if(B(H))for(var Te=0;Te>>1,me=Q[ee];if(0>>1;eei(fe,De))hei(Ae,fe)?(Q[ee]=Ae,Q[he]=De,ee=he):(Q[ee]=fe,Q[T]=De,ee=T);else if(hei(Ae,De))Q[ee]=Ae,Q[he]=De,ee=he;else break e}}return ue}function i(Q,ue){var De=Q.sortIndex-ue.sortIndex;return De!==0?De:Q.id-ue.id}if(s.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;s.unstable_now=function(){return l.now()}}else{var c=Date,d=c.now();s.unstable_now=function(){return c.now()-d}}var f=[],h=[],m=1,y=null,v=3,S=!1,_=!1,x=!1,A=!1,D=typeof setTimeout=="function"?setTimeout:null,O=typeof clearTimeout=="function"?clearTimeout:null,k=typeof setImmediate<"u"?setImmediate:null;function L(Q){for(var ue=n(h);ue!==null;){if(ue.callback===null)r(h);else if(ue.startTime<=Q)r(h),ue.sortIndex=ue.expirationTime,e(f,ue);else break;ue=n(h)}}function B(Q){if(x=!1,L(Q),!_)if(n(f)!==null)_=!0,q||(q=!0,Ie());else{var ue=n(h);ue!==null&&Et(B,ue.startTime-Q)}}var q=!1,z=-1,W=5,de=-1;function _e(){return A?!0:!(s.unstable_now()-deQ&&_e());){var ee=y.callback;if(typeof ee=="function"){y.callback=null,v=y.priorityLevel;var me=ee(y.expirationTime<=Q);if(Q=s.unstable_now(),typeof me=="function"){y.callback=me,L(Q),ue=!0;break t}y===n(f)&&r(f),L(Q)}else r(f);y=n(f)}if(y!==null)ue=!0;else{var H=n(h);H!==null&&Et(B,H.startTime-Q),ue=!1}}break e}finally{y=null,v=De,S=!1}ue=void 0}}finally{ue?Ie():q=!1}}}var Ie;if(typeof k=="function")Ie=function(){k(Se)};else if(typeof MessageChannel<"u"){var Fe=new MessageChannel,ze=Fe.port2;Fe.port1.onmessage=Se,Ie=function(){ze.postMessage(null)}}else Ie=function(){D(Se,0)};function Et(Q,ue){z=D(function(){Q(s.unstable_now())},ue)}s.unstable_IdlePriority=5,s.unstable_ImmediatePriority=1,s.unstable_LowPriority=4,s.unstable_NormalPriority=3,s.unstable_Profiling=null,s.unstable_UserBlockingPriority=2,s.unstable_cancelCallback=function(Q){Q.callback=null},s.unstable_forceFrameRate=function(Q){0>Q||125ee?(Q.sortIndex=De,e(h,Q),n(f)===null&&Q===n(h)&&(x?(O(z),z=-1):x=!0,Et(B,De-ee))):(Q.sortIndex=me,e(f,Q),_||S||(_=!0,q||(q=!0,Ie()))),Q},s.unstable_shouldYield=_e,s.unstable_wrapCallback=function(Q){var ue=v;return function(){var De=v;v=ue;try{return Q.apply(this,arguments)}finally{v=De}}}})(Rd)),Rd}var jg;function s0(){return jg||(jg=1,kd.exports=i0()),kd.exports}var Dd={exports:{}},An={};var Hg;function o0(){if(Hg)return An;Hg=1;var s=xd();function e(f){var h="https://react.dev/errors/"+f;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),Dd.exports=o0(),Dd.exports}var Ug;function l0(){if(Ug)return fo;Ug=1;var s=s0(),e=xd(),n=Pg();function r(t){var a="https://react.dev/errors/"+t;if(1me||(t.current=ee[me],ee[me]=null,me--)}function fe(t,a){me++,ee[me]=t.current,t.current=a}var he=H(null),Ae=H(null),se=H(null),ge=H(null);function $e(t,a){switch(fe(se,a),fe(Ae,t),fe(he,null),a.nodeType){case 9:case 11:t=(t=a.documentElement)&&(t=t.namespaceURI)?Aw(t):0;break;default:if(t=a.tagName,a=a.namespaceURI)a=Aw(a),t=xw(a,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}T(he),fe(he,t)}function Te(){T(he),T(Ae),T(se)}function je(t){t.memoizedState!==null&&fe(ge,t);var a=he.current,o=xw(a,t.type);a!==o&&(fe(Ae,t),fe(he,o))}function xt(t){Ae.current===t&&(T(he),T(Ae)),ge.current===t&&(T(ge),Xl._currentValue=De)}var rt,gt;function at(t){if(rt===void 0)try{throw Error()}catch(o){var a=o.stack.trim().match(/\n( *(at )?)/);rt=a&&a[1]||"",gt=-1ra in Yt?gk(Yt,ra,{enumerable:!0,configurable:!0,writable:!0,value:aa}):Yt[ra]=aa;var $=(Yt,ra,aa)=>mk(Yt,typeof ra!="symbol"?ra+"":ra,aa);(function(Yt){"use strict";function ra(s,e){for(var n=0;nr[i]})}}}return Object.freeze(Object.defineProperty(s,Symbol.toStringTag,{value:"Module"}))}function aa(s){return s&&s.__esModule&&Object.prototype.hasOwnProperty.call(s,"default")?s.default:s}var bd={exports:{}},Ke={};/** + * @license React + * react.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var gg;function Lw(){if(gg)return Ke;gg=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),i=Symbol.for("react.profiler"),l=Symbol.for("react.consumer"),c=Symbol.for("react.context"),d=Symbol.for("react.forward_ref"),f=Symbol.for("react.suspense"),p=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),y=Symbol.for("react.activity"),C=Symbol.iterator;function S(z){return z===null||typeof z!="object"?null:(z=C&&z[C]||z["@@iterator"],typeof z=="function"?z:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},x=Object.assign,w={};function R(z,T,pe){this.props=z,this.context=T,this.refs=w,this.updater=pe||v}R.prototype.isReactComponent={},R.prototype.setState=function(z,T){if(typeof z!="object"&&typeof z!="function"&&z!=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,z,T,"setState")},R.prototype.forceUpdate=function(z){this.updater.enqueueForceUpdate(this,z,"forceUpdate")};function L(){}L.prototype=R.prototype;function O(z,T,pe){this.props=z,this.context=T,this.refs=w,this.updater=pe||v}var j=O.prototype=new L;j.constructor=O,x(j,R.prototype),j.isPureReactComponent=!0;var F=Array.isArray;function G(){}var P={H:null,A:null,T:null,S:null},K=Object.prototype.hasOwnProperty;function he(z,T,pe){var fe=pe.ref;return{$$typeof:s,type:z,key:T,ref:fe!==void 0?fe:null,props:pe}}function Ee(z,T){return he(z.type,T,z.props)}function ke(z){return typeof z=="object"&&z!==null&&z.$$typeof===s}function ze(z){var T={"=":"=0",":":"=2"};return"$"+z.replace(/[=:]/g,function(pe){return T[pe]})}var Be=/\/+/g;function je(z,T){return typeof z=="object"&&z!==null&&z.key!=null?ze(""+z.key):T.toString(36)}function bt(z){switch(z.status){case"fulfilled":return z.value;case"rejected":throw z.reason;default:switch(typeof z.status=="string"?z.then(G,G):(z.status="pending",z.then(function(T){z.status==="pending"&&(z.status="fulfilled",z.value=T)},function(T){z.status==="pending"&&(z.status="rejected",z.reason=T)})),z.status){case"fulfilled":return z.value;case"rejected":throw z.reason}}throw z}function X(z,T,pe,fe,me){var ae=typeof z;(ae==="undefined"||ae==="boolean")&&(z=null);var Re=!1;if(z===null)Re=!0;else switch(ae){case"bigint":case"string":case"number":Re=!0;break;case"object":switch(z.$$typeof){case s:case e:Re=!0;break;case m:return Re=z._init,X(Re(z._payload),T,pe,fe,me)}}if(Re)return me=me(z),Re=fe===""?"."+je(z,0):fe,F(me)?(pe="",Re!=null&&(pe=Re.replace(Be,"$&/")+"/"),X(me,T,pe,"",function(Ge){return Ge})):me!=null&&(ke(me)&&(me=Ee(me,pe+(me.key==null||z&&z.key===me.key?"":(""+me.key).replace(Be,"$&/")+"/")+Re)),T.push(me)),1;Re=0;var Pe=fe===""?".":fe+":";if(F(z))for(var Me=0;Me>>1,ge=X[Z];if(0>>1;Zi(pe,Ce))fei(me,pe)?(X[Z]=me,X[fe]=Ce,Z=fe):(X[Z]=pe,X[T]=Ce,Z=T);else if(fei(me,Ce))X[Z]=me,X[fe]=Ce,Z=fe;else break e}}return de}function i(X,de){var Ce=X.sortIndex-de.sortIndex;return Ce!==0?Ce:X.id-de.id}if(s.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;s.unstable_now=function(){return l.now()}}else{var c=Date,d=c.now();s.unstable_now=function(){return c.now()-d}}var f=[],p=[],m=1,y=null,C=3,S=!1,v=!1,x=!1,w=!1,R=typeof setTimeout=="function"?setTimeout:null,L=typeof clearTimeout=="function"?clearTimeout:null,O=typeof setImmediate<"u"?setImmediate:null;function j(X){for(var de=n(p);de!==null;){if(de.callback===null)r(p);else if(de.startTime<=X)r(p),de.sortIndex=de.expirationTime,e(f,de);else break;de=n(p)}}function F(X){if(x=!1,j(X),!v)if(n(f)!==null)v=!0,G||(G=!0,ze());else{var de=n(p);de!==null&&bt(F,de.startTime-X)}}var G=!1,P=-1,K=5,he=-1;function Ee(){return w?!0:!(s.unstable_now()-heX&&Ee());){var Z=y.callback;if(typeof Z=="function"){y.callback=null,C=y.priorityLevel;var ge=Z(y.expirationTime<=X);if(X=s.unstable_now(),typeof ge=="function"){y.callback=ge,j(X),de=!0;break t}y===n(f)&&r(f),j(X)}else r(f);y=n(f)}if(y!==null)de=!0;else{var z=n(p);z!==null&&bt(F,z.startTime-X),de=!1}}break e}finally{y=null,C=Ce,S=!1}de=void 0}}finally{de?ze():G=!1}}}var ze;if(typeof O=="function")ze=function(){O(ke)};else if(typeof MessageChannel<"u"){var Be=new MessageChannel,je=Be.port2;Be.port1.onmessage=ke,ze=function(){je.postMessage(null)}}else ze=function(){R(ke,0)};function bt(X,de){P=R(function(){X(s.unstable_now())},de)}s.unstable_IdlePriority=5,s.unstable_ImmediatePriority=1,s.unstable_LowPriority=4,s.unstable_NormalPriority=3,s.unstable_Profiling=null,s.unstable_UserBlockingPriority=2,s.unstable_cancelCallback=function(X){X.callback=null},s.unstable_forceFrameRate=function(X){0>X||125Z?(X.sortIndex=Ce,e(p,X),n(f)===null&&X===n(p)&&(x?(L(P),P=-1):x=!0,bt(F,Ce-Z))):(X.sortIndex=ge,e(f,X),v||S||(v=!0,G||(G=!0,ze()))),X},s.unstable_shouldYield=Ee,s.unstable_wrapCallback=function(X){var de=C;return function(){var Ce=C;C=de;try{return X.apply(this,arguments)}finally{C=Ce}}}})(Cd)),Cd}var bg;function Mw(){return bg||(bg=1,wd.exports=$w()),wd.exports}var Ed={exports:{}},wn={};/** + * @license React + * react-dom.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var vg;function Nw(){if(vg)return wn;vg=1;var s=vd();function e(f){var p="https://react.dev/errors/"+f;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),Ed.exports=Nw(),Ed.exports}/** + * @license React + * react-dom-client.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Cg;function Iw(){if(Cg)return uo;Cg=1;var s=Mw(),e=vd(),n=wg();function r(t){var a="https://react.dev/errors/"+t;if(1ge||(t.current=Z[ge],Z[ge]=null,ge--)}function pe(t,a){ge++,Z[ge]=t.current,t.current=a}var fe=z(null),me=z(null),ae=z(null),Re=z(null);function Pe(t,a){switch(pe(ae,a),pe(me,t),pe(fe,null),a.nodeType){case 9:case 11:t=(t=a.documentElement)&&(t=t.namespaceURI)?ZS(t):0;break;default:if(t=a.tagName,a=a.namespaceURI)a=ZS(a),t=ew(a,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}T(fe),pe(fe,t)}function Me(){T(fe),T(me),T(ae)}function Ge(t){t.memoizedState!==null&&pe(Re,t);var a=fe.current,o=ew(a,t.type);a!==o&&(pe(me,t),pe(fe,o))}function kt(t){me.current===t&&(T(fe),T(me)),Re.current===t&&(T(Re),Ql._currentValue=Ce)}var vt,hn;function Dt(t){if(vt===void 0)try{throw Error()}catch(o){var a=o.stack.trim().match(/\n( *(at )?)/);vt=a&&a[1]||"",hn=-1)":-1p||P[u]!==X[p]){var re=` -`+P[u].replace(" at new "," at ");return t.displayName&&re.includes("")&&(re=re.replace("",t.displayName)),re}while(1<=u&&0<=p);break}}}finally{Yt=!1,Error.prepareStackTrace=o}return(o=t?t.displayName||t.name:"")?at(o):""}function bt(t,a){switch(t.tag){case 26:case 27:case 5:return at(t.type);case 16:return at("Lazy");case 13:return t.child!==a&&a!==null?at("Suspense Fallback"):at("Suspense");case 19:return at("SuspenseList");case 0:case 15:return Ht(t.type,!1);case 11:return Ht(t.type.render,!1);case 1:return Ht(t.type,!0);case 31:return at("Activity");default:return""}}function qe(t){try{var a="",o=null;do a+=bt(t,o),o=t,t=t.return;while(t);return a}catch(u){return` +`+vt+t+hn}var Xt=!1;function un(t,a){if(!t||Xt)return"";Xt=!0;var o=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var u={DetermineComponentFrameRoot:function(){try{if(a){var le=function(){throw Error()};if(Object.defineProperty(le.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(le,[])}catch(te){var Q=te}Reflect.construct(t,[],le)}else{try{le.call()}catch(te){Q=te}t.call(le.prototype)}}else{try{throw Error()}catch(te){Q=te}(le=t())&&typeof le.catch=="function"&&le.catch(function(){})}}catch(te){if(te&&Q&&typeof te.stack=="string")return[te.stack,Q.stack]}return[null,null]}};u.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var h=Object.getOwnPropertyDescriptor(u.DetermineComponentFrameRoot,"name");h&&h.configurable&&Object.defineProperty(u.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var g=u.DetermineComponentFrameRoot(),E=g[0],k=g[1];if(E&&k){var H=E.split(` +`),Y=k.split(` +`);for(h=u=0;uh||H[u]!==Y[h]){var ne=` +`+H[u].replace(" at new "," at ");return t.displayName&&ne.includes("")&&(ne=ne.replace("",t.displayName)),ne}while(1<=u&&0<=h);break}}}finally{Xt=!1,Error.prepareStackTrace=o}return(o=t?t.displayName||t.name:"")?Dt(o):""}function Ut(t,a){switch(t.tag){case 26:case 27:case 5:return Dt(t.type);case 16:return Dt("Lazy");case 13:return t.child!==a&&a!==null?Dt("Suspense Fallback"):Dt("Suspense");case 19:return Dt("SuspenseList");case 0:case 15:return un(t.type,!1);case 11:return un(t.type.render,!1);case 1:return un(t.type,!0);case 31:return Dt("Activity");default:return""}}function $r(t){try{var a="",o=null;do a+=Ut(t,o),o=t,t=t.return;while(t);return a}catch(u){return` Error generating stack: `+u.message+` -`+u.stack}}var mt=Object.prototype.hasOwnProperty,Dt=s.unstable_scheduleCallback,zt=s.unstable_cancelCallback,kn=s.unstable_shouldYield,dr=s.unstable_requestPaint,Ot=s.unstable_now,$i=s.unstable_getCurrentPriorityLevel,ua=s.unstable_ImmediatePriority,bn=s.unstable_UserBlockingPriority,Mn=s.unstable_NormalPriority,it=s.unstable_LowPriority,Pn=s.unstable_IdlePriority,vn=s.log,da=s.unstable_setDisableYieldValue,fr=null,un=null;function Rn(t){if(typeof vn=="function"&&da(t),un&&typeof un.setStrictMode=="function")try{un.setStrictMode(fr,t)}catch{}}var dn=Math.clz32?Math.clz32:ce,V=Math.log,ie=Math.LN2;function ce(t){return t>>>=0,t===0?32:31-(V(t)/ie|0)|0}var Z=256,ve=262144,pe=4194304;function Ee(t){var a=t&42;if(a!==0)return a;switch(t&-t){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 t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function xe(t,a,o){var u=t.pendingLanes;if(u===0)return 0;var p=0,g=t.suspendedLanes,C=t.pingedLanes;t=t.warmLanes;var R=u&134217727;return R!==0?(u=R&~g,u!==0?p=Ee(u):(C&=R,C!==0?p=Ee(C):o||(o=R&~t,o!==0&&(p=Ee(o))))):(R=u&~g,R!==0?p=Ee(R):C!==0?p=Ee(C):o||(o=u&~t,o!==0&&(p=Ee(o)))),p===0?0:a!==0&&a!==p&&(a&g)===0&&(g=p&-p,o=a&-a,g>=o||g===32&&(o&4194048)!==0)?a:p}function Ke(t,a){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&a)===0}function ke(t,a){switch(t){case 1:case 2:case 4:case 8:case 64:return a+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 a+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 Me(){var t=pe;return pe<<=1,(pe&62914560)===0&&(pe=4194304),t}function Re(t){for(var a=[],o=0;31>o;o++)a.push(t);return a}function tt(t,a){t.pendingLanes|=a,a!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function Pe(t,a,o,u,p,g){var C=t.pendingLanes;t.pendingLanes=o,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=o,t.entangledLanes&=o,t.errorRecoveryDisabledLanes&=o,t.shellSuspendCounter=0;var R=t.entanglements,P=t.expirationTimes,X=t.hiddenUpdates;for(o=C&~o;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var Sh=/[\n"\\]/g;function Bn(t){return t.replace(Sh,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function Os(t,a,o,u,p,g,C,R){t.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?t.type=C:t.removeAttribute("type"),a!=null?C==="number"?(a===0&&t.value===""||t.value!=a)&&(t.value=""+On(a)):t.value!==""+On(a)&&(t.value=""+On(a)):C!=="submit"&&C!=="reset"||t.removeAttribute("value"),a!=null?ha(t,C,On(a)):o!=null?ha(t,C,On(o)):u!=null&&t.removeAttribute("value"),p==null&&g!=null&&(t.defaultChecked=!!g),p!=null&&(t.checked=p&&typeof p!="function"&&typeof p!="symbol"),R!=null&&typeof R!="function"&&typeof R!="symbol"&&typeof R!="boolean"?t.name=""+On(R):t.removeAttribute("name")}function Ii(t,a,o,u,p,g,C,R){if(g!=null&&typeof g!="function"&&typeof g!="symbol"&&typeof g!="boolean"&&(t.type=g),a!=null||o!=null){if(!(g!=="submit"&&g!=="reset"||a!=null)){il(t);return}o=o!=null?""+On(o):"",a=a!=null?""+On(a):o,R||a===t.value||(t.value=a),t.defaultValue=a}u=u??p,u=typeof u!="function"&&typeof u!="symbol"&&!!u,t.checked=R?t.checked:!!u,t.defaultChecked=!!u,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(t.name=C),il(t)}function ha(t,a,o){a==="number"&&Va(t.ownerDocument)===t||t.defaultValue===""+o||(t.defaultValue=""+o)}function Ka(t,a,o,u){if(t=t.options,a){a={};for(var p=0;p"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ul=!1;if(Nr)try{var Hi={};Object.defineProperty(Hi,"passive",{get:function(){ul=!0}}),window.addEventListener("test",Hi,Hi),window.removeEventListener("test",Hi,Hi)}catch{ul=!1}var Jr=null,dl=null,$s=null;function du(){if($s)return $s;var t,a=dl,o=a.length,u,p="value"in Jr?Jr.value:Jr.textContent,g=p.length;for(t=0;t=ne),We=" ",ft=!1;function vt(t,a){switch(t){case"keyup":return $.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Vt(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var jr=!1;function Hh(t,a){switch(t){case"compositionend":return Vt(a);case"keypress":return a.which!==32?null:(ft=!0,We);case"textInput":return t=a.data,t===We&&ft?null:t;default:return null}}function bu(t,a){if(jr)return t==="compositionend"||!N&&vt(t,a)?(t=du(),$s=dl=Jr=null,jr=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:o,offset:a-t};t=u}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=qb(o)}}function Fb(t,a){return t&&a?t===a?!0:t&&t.nodeType===3?!1:a&&a.nodeType===3?Fb(t,a.parentNode):"contains"in t?t.contains(a):t.compareDocumentPosition?!!(t.compareDocumentPosition(a)&16):!1:!1}function Vb(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var a=Va(t.document);a instanceof t.HTMLIFrameElement;){try{var o=typeof a.contentWindow.location.href=="string"}catch{o=!1}if(o)t=a.contentWindow;else break;a=Va(t.document)}return a}function qh(t){var a=t&&t.nodeName&&t.nodeName.toLowerCase();return a&&(a==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||a==="textarea"||t.contentEditable==="true")}var tk=Nr&&"documentMode"in document&&11>=document.documentMode,js=null,Gh=null,wl=null,Fh=!1;function Kb(t,a,o){var u=o.window===o?o.document:o.nodeType===9?o:o.ownerDocument;Fh||js==null||js!==Va(u)||(u=js,"selectionStart"in u&&qh(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&&Sl(wl,u)||(wl=u,u=ud(Gh,"onSelect"),0>=C,p-=C,Qr=1<<32-dn(a)+p|o<Ze?(ut=Ne,Ne=null):ut=Ne.sibling;var wt=J(K,Ne,Y[Ze],oe);if(wt===null){Ne===null&&(Ne=ut);break}t&&Ne&&wt.alternate===null&&a(K,Ne),F=g(wt,F,Ze),St===null?Be=wt:St.sibling=wt,St=wt,Ne=ut}if(Ze===Y.length)return o(K,Ne),ht&&ya(K,Ze),Be;if(Ne===null){for(;ZeZe?(ut=Ne,Ne=null):ut=Ne.sibling;var vi=J(K,Ne,wt.value,oe);if(vi===null){Ne===null&&(Ne=ut);break}t&&Ne&&vi.alternate===null&&a(K,Ne),F=g(vi,F,Ze),St===null?Be=vi:St.sibling=vi,St=vi,Ne=ut}if(wt.done)return o(K,Ne),ht&&ya(K,Ze),Be;if(Ne===null){for(;!wt.done;Ze++,wt=Y.next())wt=le(K,wt.value,oe),wt!==null&&(F=g(wt,F,Ze),St===null?Be=wt:St.sibling=wt,St=wt);return ht&&ya(K,Ze),Be}for(Ne=u(Ne);!wt.done;Ze++,wt=Y.next())wt=te(Ne,K,Ze,wt.value,oe),wt!==null&&(t&&wt.alternate!==null&&Ne.delete(wt.key===null?Ze:wt.key),F=g(wt,F,Ze),St===null?Be=wt:St.sibling=wt,St=wt);return t&&Ne.forEach(function(wR){return a(K,wR)}),ht&&ya(K,Ze),Be}function Nt(K,F,Y,oe){if(typeof Y=="object"&&Y!==null&&Y.type===x&&Y.key===null&&(Y=Y.props.children),typeof Y=="object"&&Y!==null){switch(Y.$$typeof){case S:e:{for(var Be=Y.key;F!==null;){if(F.key===Be){if(Be=Y.type,Be===x){if(F.tag===7){o(K,F.sibling),oe=p(F,Y.props.children),oe.return=K,K=oe;break e}}else if(F.elementType===Be||typeof Be=="object"&&Be!==null&&Be.$$typeof===W&&es(Be)===F.type){o(K,F.sibling),oe=p(F,Y.props),Tl(oe,Y),oe.return=K,K=oe;break e}o(K,F);break}else a(K,F);F=F.sibling}Y.type===x?(oe=Yi(Y.props.children,K.mode,oe,Y.key),oe.return=K,K=oe):(oe=Tu(Y.type,Y.key,Y.props,null,K.mode,oe),Tl(oe,Y),oe.return=K,K=oe)}return C(K);case _:e:{for(Be=Y.key;F!==null;){if(F.key===Be)if(F.tag===4&&F.stateNode.containerInfo===Y.containerInfo&&F.stateNode.implementation===Y.implementation){o(K,F.sibling),oe=p(F,Y.children||[]),oe.return=K,K=oe;break e}else{o(K,F);break}else a(K,F);F=F.sibling}oe=Qh(Y,K.mode,oe),oe.return=K,K=oe}return C(K);case W:return Y=es(Y),Nt(K,F,Y,oe)}if(Et(Y))return Oe(K,F,Y,oe);if(Ie(Y)){if(Be=Ie(Y),typeof Be!="function")throw Error(r(150));return Y=Be.call(Y),Ge(K,F,Y,oe)}if(typeof Y.then=="function")return Nt(K,F,Mu(Y),oe);if(Y.$$typeof===k)return Nt(K,F,Du(K,Y),oe);Nu(K,Y)}return typeof Y=="string"&&Y!==""||typeof Y=="number"||typeof Y=="bigint"?(Y=""+Y,F!==null&&F.tag===6?(o(K,F.sibling),oe=p(F,Y),oe.return=K,K=oe):(o(K,F),oe=Jh(Y,K.mode,oe),oe.return=K,K=oe),C(K)):o(K,F)}return function(K,F,Y,oe){try{xl=0;var Be=Nt(K,F,Y,oe);return Ws=null,Be}catch(Ne){if(Ne===Ks||Ne===Lu)throw Ne;var St=er(29,Ne,null,K.mode);return St.lanes=oe,St.return=K,St}}}var ns=mv(!0),yv=mv(!1),ni=!1;function up(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function dp(t,a){t=t.updateQueue,a.updateQueue===t&&(a.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function ri(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function ai(t,a,o){var u=t.updateQueue;if(u===null)return null;if(u=u.shared,(_t&2)!==0){var p=u.pending;return p===null?a.next=a:(a.next=p.next,p.next=a),u.pending=a,a=xu(t),ev(t,null,o),a}return Au(t,u,a,o),xu(t)}function kl(t,a,o){if(a=a.updateQueue,a!==null&&(a=a.shared,(o&4194048)!==0)){var u=a.lanes;u&=t.pendingLanes,o|=u,a.lanes=o,Ce(t,o)}}function fp(t,a){var o=t.updateQueue,u=t.alternate;if(u!==null&&(u=u.updateQueue,o===u)){var p=null,g=null;if(o=o.firstBaseUpdate,o!==null){do{var C={lane:o.lane,tag:o.tag,payload:o.payload,callback:null,next:null};g===null?p=g=C:g=g.next=C,o=o.next}while(o!==null);g===null?p=g=a:g=g.next=a}else p=g=a;o={baseState:u.baseState,firstBaseUpdate:p,lastBaseUpdate:g,shared:u.shared,callbacks:u.callbacks},t.updateQueue=o;return}t=o.lastBaseUpdate,t===null?o.firstBaseUpdate=a:t.next=a,o.lastBaseUpdate=a}var hp=!1;function Rl(){if(hp){var t=Vs;if(t!==null)throw t}}function Dl(t,a,o,u){hp=!1;var p=t.updateQueue;ni=!1;var g=p.firstBaseUpdate,C=p.lastBaseUpdate,R=p.shared.pending;if(R!==null){p.shared.pending=null;var P=R,X=P.next;P.next=null,C===null?g=X:C.next=X,C=P;var re=t.alternate;re!==null&&(re=re.updateQueue,R=re.lastBaseUpdate,R!==C&&(R===null?re.firstBaseUpdate=X:R.next=X,re.lastBaseUpdate=P))}if(g!==null){var le=p.baseState;C=0,re=X=P=null,R=g;do{var J=R.lane&-536870913,te=J!==R.lane;if(te?(ct&J)===J:(u&J)===J){J!==0&&J===Fs&&(hp=!0),re!==null&&(re=re.next={lane:0,tag:R.tag,payload:R.payload,callback:null,next:null});e:{var Oe=t,Ge=R;J=a;var Nt=o;switch(Ge.tag){case 1:if(Oe=Ge.payload,typeof Oe=="function"){le=Oe.call(Nt,le,J);break e}le=Oe;break e;case 3:Oe.flags=Oe.flags&-65537|128;case 0:if(Oe=Ge.payload,J=typeof Oe=="function"?Oe.call(Nt,le,J):Oe,J==null)break e;le=y({},le,J);break e;case 2:ni=!0}}J=R.callback,J!==null&&(t.flags|=64,te&&(t.flags|=8192),te=p.callbacks,te===null?p.callbacks=[J]:te.push(J))}else te={lane:J,tag:R.tag,payload:R.payload,callback:R.callback,next:null},re===null?(X=re=te,P=le):re=re.next=te,C|=J;if(R=R.next,R===null){if(R=p.shared.pending,R===null)break;te=R,R=te.next,te.next=null,p.lastBaseUpdate=te,p.shared.pending=null}}while(!0);re===null&&(P=le),p.baseState=P,p.firstBaseUpdate=X,p.lastBaseUpdate=re,g===null&&(p.shared.lanes=0),ci|=C,t.lanes=C,t.memoizedState=le}}function bv(t,a){if(typeof t!="function")throw Error(r(191,t));t.call(a)}function vv(t,a){var o=t.callbacks;if(o!==null)for(t.callbacks=null,t=0;tg?g:8;var C=Q.T,R={};Q.T=R,Lp(t,!1,a,o);try{var P=p(),X=Q.S;if(X!==null&&X(R,P),P!==null&&typeof P=="object"&&typeof P.then=="function"){var re=uk(P,u);$l(t,a,re,ir(t))}else $l(t,a,u,ir(t))}catch(le){$l(t,a,{then:function(){},status:"rejected",reason:le},ir())}finally{ue.p=g,C!==null&&R.types!==null&&(C.types=R.types),Q.T=C}}function mk(){}function Dp(t,a,o,u){if(t.tag!==5)throw Error(r(476));var p=Jv(t).queue;Xv(t,p,a,De,o===null?mk:function(){return Qv(t),o(u)})}function Jv(t){var a=t.memoizedState;if(a!==null)return a;a={memoizedState:De,baseState:De,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:wa,lastRenderedState:De},next:null};var o={};return a.next={memoizedState:o,baseState:o,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:wa,lastRenderedState:o},next:null},t.memoizedState=a,t=t.alternate,t!==null&&(t.memoizedState=a),a}function Qv(t){var a=Jv(t);a.next===null&&(a=t.alternate.memoizedState),$l(t,a.next.queue,{},ir())}function Op(){return Cn(Xl)}function Zv(){return en().memoizedState}function eS(){return en().memoizedState}function yk(t){for(var a=t.return;a!==null;){switch(a.tag){case 24:case 3:var o=ir();t=ri(o);var u=ai(a,t,o);u!==null&&(Kn(u,a,o),kl(u,a,o)),a={cache:sp()},t.payload=a;return}a=a.return}}function bk(t,a,o){var u=ir();o={lane:u,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},Fu(t)?nS(a,o):(o=Yh(t,a,o,u),o!==null&&(Kn(o,t,u),rS(o,a,u)))}function tS(t,a,o){var u=ir();$l(t,a,o,u)}function $l(t,a,o,u){var p={lane:u,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null};if(Fu(t))nS(a,p);else{var g=t.alternate;if(t.lanes===0&&(g===null||g.lanes===0)&&(g=a.lastRenderedReducer,g!==null))try{var C=a.lastRenderedState,R=g(C,o);if(p.hasEagerState=!0,p.eagerState=R,Zn(R,C))return Au(t,a,p,0),It===null&&_u(),!1}catch{}if(o=Yh(t,a,p,u),o!==null)return Kn(o,t,u),rS(o,a,u),!0}return!1}function Lp(t,a,o,u){if(u={lane:2,revertLane:ug(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},Fu(t)){if(a)throw Error(r(479))}else a=Yh(t,o,u,2),a!==null&&Kn(a,t,2)}function Fu(t){var a=t.alternate;return t===Je||a!==null&&a===Je}function nS(t,a){Xs=Hu=!0;var o=t.pending;o===null?a.next=a:(a.next=o.next,o.next=a),t.pending=a}function rS(t,a,o){if((o&4194048)!==0){var u=a.lanes;u&=t.pendingLanes,o|=u,a.lanes=o,Ce(t,o)}}var Ml={readContext:Cn,use:Uu,useCallback:Xt,useContext:Xt,useEffect:Xt,useImperativeHandle:Xt,useLayoutEffect:Xt,useInsertionEffect:Xt,useMemo:Xt,useReducer:Xt,useRef:Xt,useState:Xt,useDebugValue:Xt,useDeferredValue:Xt,useTransition:Xt,useSyncExternalStore:Xt,useId:Xt,useHostTransitionStatus:Xt,useFormState:Xt,useActionState:Xt,useOptimistic:Xt,useMemoCache:Xt,useCacheRefresh:Xt};Ml.useEffectEvent=Xt;var aS={readContext:Cn,use:Uu,useCallback:function(t,a){return In().memoizedState=[t,a===void 0?null:a],t},useContext:Cn,useEffect:Uv,useImperativeHandle:function(t,a,o){o=o!=null?o.concat([t]):null,qu(4194308,4,Fv.bind(null,a,t),o)},useLayoutEffect:function(t,a){return qu(4194308,4,t,a)},useInsertionEffect:function(t,a){qu(4,2,t,a)},useMemo:function(t,a){var o=In();a=a===void 0?null:a;var u=t();if(rs){Rn(!0);try{t()}finally{Rn(!1)}}return o.memoizedState=[u,a],u},useReducer:function(t,a,o){var u=In();if(o!==void 0){var p=o(a);if(rs){Rn(!0);try{o(a)}finally{Rn(!1)}}}else p=a;return u.memoizedState=u.baseState=p,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:p},u.queue=t,t=t.dispatch=bk.bind(null,Je,t),[u.memoizedState,t]},useRef:function(t){var a=In();return t={current:t},a.memoizedState=t},useState:function(t){t=Ap(t);var a=t.queue,o=tS.bind(null,Je,a);return a.dispatch=o,[t.memoizedState,o]},useDebugValue:kp,useDeferredValue:function(t,a){var o=In();return Rp(o,t,a)},useTransition:function(){var t=Ap(!1);return t=Xv.bind(null,Je,t.queue,!0,!1),In().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,a,o){var u=Je,p=In();if(ht){if(o===void 0)throw Error(r(407));o=o()}else{if(o=a(),It===null)throw Error(r(349));(ct&127)!==0||Av(u,a,o)}p.memoizedState=o;var g={value:o,getSnapshot:a};return p.queue=g,Uv(Tv.bind(null,u,g,t),[t]),u.flags|=2048,Qs(9,{destroy:void 0},xv.bind(null,u,g,o,a),null),o},useId:function(){var t=In(),a=It.identifierPrefix;if(ht){var o=Zr,u=Qr;o=(u&~(1<<32-dn(u)-1)).toString(32)+o,a="_"+a+"R_"+o,o=zu++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?C.createElement("select",{is:u.is}):C.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?C.createElement(p,{is:u.is}):C.createElement(p)}}g[Ft]=a,g[Dn]=u;e:for(C=a.child;C!==null;){if(C.tag===5||C.tag===6)g.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===a)break e;for(;C.sibling===null;){if(C.return===null||C.return===a)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}a.stateNode=g;e:switch(_n(g,p,u),p){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&Ea(a)}}return Ut(a),Vp(a,a.type,t===null?null:t.memoizedProps,a.pendingProps,o),null;case 6:if(t&&a.stateNode!=null)t.memoizedProps!==u&&Ea(a);else{if(typeof u!="string"&&a.stateNode===null)throw Error(r(166));if(t=se.current,qs(a)){if(t=a.stateNode,o=a.memoizedProps,u=null,p=wn,p!==null)switch(p.tag){case 27:case 5:u=p.memoizedProps}t[Ft]=a,t=!!(t.nodeValue===o||u!==null&&u.suppressHydrationWarning===!0||Ew(t.nodeValue,o)),t||ei(a,!0)}else t=dd(t).createTextNode(u),t[Ft]=a,a.stateNode=t}return Ut(a),null;case 31:if(o=a.memoizedState,t===null||t.memoizedState!==null){if(u=qs(a),o!==null){if(t===null){if(!u)throw Error(r(318));if(t=a.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(r(557));t[Ft]=a}else Xi(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Ut(a),t=!1}else o=np(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=o),t=!0;if(!t)return a.flags&256?(nr(a),a):(nr(a),null);if((a.flags&128)!==0)throw Error(r(558))}return Ut(a),null;case 13:if(u=a.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(p=qs(a),u!==null&&u.dehydrated!==null){if(t===null){if(!p)throw Error(r(318));if(p=a.memoizedState,p=p!==null?p.dehydrated:null,!p)throw Error(r(317));p[Ft]=a}else Xi(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;Ut(a),p=!1}else p=np(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=p),p=!0;if(!p)return a.flags&256?(nr(a),a):(nr(a),null)}return nr(a),(a.flags&128)!==0?(a.lanes=o,a):(o=u!==null,t=t!==null&&t.memoizedState!==null,o&&(u=a.child,p=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(p=u.alternate.memoizedState.cachePool.pool),g=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(g=u.memoizedState.cachePool.pool),g!==p&&(u.flags|=2048)),o!==t&&o&&(a.child.flags|=8192),Xu(a,a.updateQueue),Ut(a),null);case 4:return Te(),t===null&&pg(a.stateNode.containerInfo),Ut(a),null;case 10:return va(a.type),Ut(a),null;case 19:if(T(Zt),u=a.memoizedState,u===null)return Ut(a),null;if(p=(a.flags&128)!==0,g=u.rendering,g===null)if(p)Il(u,!1);else{if(Jt!==0||t!==null&&(t.flags&128)!==0)for(t=a.child;t!==null;){if(g=ju(t),g!==null){for(a.flags|=128,Il(u,!1),t=g.updateQueue,a.updateQueue=t,Xu(a,t),a.subtreeFlags=0,t=o,o=a.child;o!==null;)tv(o,t),o=o.sibling;return fe(Zt,Zt.current&1|2),ht&&ya(a,u.treeForkCount),a.child}t=t.sibling}u.tail!==null&&Ot()>td&&(a.flags|=128,p=!0,Il(u,!1),a.lanes=4194304)}else{if(!p)if(t=ju(g),t!==null){if(a.flags|=128,p=!0,t=t.updateQueue,a.updateQueue=t,Xu(a,t),Il(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!ht)return Ut(a),null}else 2*Ot()-u.renderingStartTime>td&&o!==536870912&&(a.flags|=128,p=!0,Il(u,!1),a.lanes=4194304);u.isBackwards?(g.sibling=a.child,a.child=g):(t=u.last,t!==null?t.sibling=g:a.child=g,u.last=g)}return u.tail!==null?(t=u.tail,u.rendering=t,u.tail=t.sibling,u.renderingStartTime=Ot(),t.sibling=null,o=Zt.current,fe(Zt,p?o&1|2:o&1),ht&&ya(a,u.treeForkCount),t):(Ut(a),null);case 22:case 23:return nr(a),gp(),u=a.memoizedState!==null,t!==null?t.memoizedState!==null!==u&&(a.flags|=8192):u&&(a.flags|=8192),u?(o&536870912)!==0&&(a.flags&128)===0&&(Ut(a),a.subtreeFlags&6&&(a.flags|=8192)):Ut(a),o=a.updateQueue,o!==null&&Xu(a,o.retryQueue),o=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(o=t.memoizedState.cachePool.pool),u=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(u=a.memoizedState.cachePool.pool),u!==o&&(a.flags|=2048),t!==null&&T(Zi),null;case 24:return o=null,t!==null&&(o=t.memoizedState.cache),a.memoizedState.cache!==o&&(a.flags|=2048),va(rn),Ut(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function Ek(t,a){switch(ep(a),a.tag){case 1:return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 3:return va(rn),Te(),t=a.flags,(t&65536)!==0&&(t&128)===0?(a.flags=t&-65537|128,a):null;case 26:case 27:case 5:return xt(a),null;case 31:if(a.memoizedState!==null){if(nr(a),a.alternate===null)throw Error(r(340));Xi()}return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 13:if(nr(a),t=a.memoizedState,t!==null&&t.dehydrated!==null){if(a.alternate===null)throw Error(r(340));Xi()}return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 19:return T(Zt),null;case 4:return Te(),null;case 10:return va(a.type),null;case 22:case 23:return nr(a),gp(),t!==null&&T(Zi),t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 24:return va(rn),null;case 25:return null;default:return null}}function kS(t,a){switch(ep(a),a.tag){case 3:va(rn),Te();break;case 26:case 27:case 5:xt(a);break;case 4:Te();break;case 31:a.memoizedState!==null&&nr(a);break;case 13:nr(a);break;case 19:T(Zt);break;case 10:va(a.type);break;case 22:case 23:nr(a),gp(),t!==null&&T(Zi);break;case 24:va(rn)}}function jl(t,a){try{var o=a.updateQueue,u=o!==null?o.lastEffect:null;if(u!==null){var p=u.next;o=p;do{if((o.tag&t)===t){u=void 0;var g=o.create,C=o.inst;u=g(),C.destroy=u}o=o.next}while(o!==p)}}catch(R){kt(a,a.return,R)}}function oi(t,a,o){try{var u=a.updateQueue,p=u!==null?u.lastEffect:null;if(p!==null){var g=p.next;u=g;do{if((u.tag&t)===t){var C=u.inst,R=C.destroy;if(R!==void 0){C.destroy=void 0,p=a;var P=o,X=R;try{X()}catch(re){kt(p,P,re)}}}u=u.next}while(u!==g)}}catch(re){kt(a,a.return,re)}}function RS(t){var a=t.updateQueue;if(a!==null){var o=t.stateNode;try{vv(a,o)}catch(u){kt(t,t.return,u)}}}function DS(t,a,o){o.props=as(t.type,t.memoizedProps),o.state=t.memoizedState;try{o.componentWillUnmount()}catch(u){kt(t,a,u)}}function Hl(t,a){try{var o=t.ref;if(o!==null){switch(t.tag){case 26:case 27:case 5:var u=t.stateNode;break;case 30:u=t.stateNode;break;default:u=t.stateNode}typeof o=="function"?t.refCleanup=o(u):o.current=u}}catch(p){kt(t,a,p)}}function ea(t,a){var o=t.ref,u=t.refCleanup;if(o!==null)if(typeof u=="function")try{u()}catch(p){kt(t,a,p)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof o=="function")try{o(null)}catch(p){kt(t,a,p)}else o.current=null}function OS(t){var a=t.type,o=t.memoizedProps,u=t.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":o.autoFocus&&u.focus();break e;case"img":o.src?u.src=o.src:o.srcSet&&(u.srcset=o.srcSet)}}catch(p){kt(t,t.return,p)}}function Kp(t,a,o){try{var u=t.stateNode;Fk(u,t.type,o,a),u[Dn]=a}catch(p){kt(t,t.return,p)}}function LS(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&pi(t.type)||t.tag===4}function Wp(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||LS(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.tag===27&&pi(t.type)||t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function Yp(t,a,o){var u=t.tag;if(u===5||u===6)t=t.stateNode,a?(o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o).insertBefore(t,a):(a=o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o,a.appendChild(t),o=o._reactRootContainer,o!=null||a.onclick!==null||(a.onclick=Mr));else if(u!==4&&(u===27&&pi(t.type)&&(o=t.stateNode,a=null),t=t.child,t!==null))for(Yp(t,a,o),t=t.sibling;t!==null;)Yp(t,a,o),t=t.sibling}function Ju(t,a,o){var u=t.tag;if(u===5||u===6)t=t.stateNode,a?o.insertBefore(t,a):o.appendChild(t);else if(u!==4&&(u===27&&pi(t.type)&&(o=t.stateNode),t=t.child,t!==null))for(Ju(t,a,o),t=t.sibling;t!==null;)Ju(t,a,o),t=t.sibling}function $S(t){var a=t.stateNode,o=t.memoizedProps;try{for(var u=t.type,p=a.attributes;p.length;)a.removeAttributeNode(p[0]);_n(a,u,o),a[Ft]=t,a[Dn]=o}catch(g){kt(t,t.return,g)}}var _a=!1,on=!1,Xp=!1,MS=typeof WeakSet=="function"?WeakSet:Set,yn=null;function _k(t,a){if(t=t.containerInfo,yg=bd,t=Vb(t),qh(t)){if("selectionStart"in t)var o={start:t.selectionStart,end:t.selectionEnd};else e:{o=(o=t.ownerDocument)&&o.defaultView||window;var u=o.getSelection&&o.getSelection();if(u&&u.rangeCount!==0){o=u.anchorNode;var p=u.anchorOffset,g=u.focusNode;u=u.focusOffset;try{o.nodeType,g.nodeType}catch{o=null;break e}var C=0,R=-1,P=-1,X=0,re=0,le=t,J=null;t:for(;;){for(var te;le!==o||p!==0&&le.nodeType!==3||(R=C+p),le!==g||u!==0&&le.nodeType!==3||(P=C+u),le.nodeType===3&&(C+=le.nodeValue.length),(te=le.firstChild)!==null;)J=le,le=te;for(;;){if(le===t)break t;if(J===o&&++X===p&&(R=C),J===g&&++re===u&&(P=C),(te=le.nextSibling)!==null)break;le=J,J=le.parentNode}le=te}o=R===-1||P===-1?null:{start:R,end:P}}else o=null}o=o||{start:0,end:0}}else o=null;for(bg={focusedElem:t,selectionRange:o},bd=!1,yn=a;yn!==null;)if(a=yn,t=a.child,(a.subtreeFlags&1028)!==0&&t!==null)t.return=a,yn=t;else for(;yn!==null;){switch(a=yn,g=a.alternate,t=a.flags,a.tag){case 0:if((t&4)!==0&&(t=a.updateQueue,t=t!==null?t.events:null,t!==null))for(o=0;o title"))),_n(g,u,o),g[Ft]=t,nn(g),u=g;break e;case"link":var C=Pw("link","href",p).get(u+(o.href||""));if(C){for(var R=0;RNt&&(C=Nt,Nt=Ge,Ge=C);var K=Gb(R,Ge),F=Gb(R,Nt);if(K&&F&&(te.rangeCount!==1||te.anchorNode!==K.node||te.anchorOffset!==K.offset||te.focusNode!==F.node||te.focusOffset!==F.offset)){var Y=le.createRange();Y.setStart(K.node,K.offset),te.removeAllRanges(),Ge>Nt?(te.addRange(Y),te.extend(F.node,F.offset)):(Y.setEnd(F.node,F.offset),te.addRange(Y))}}}}for(le=[],te=R;te=te.parentNode;)te.nodeType===1&&le.push({element:te,left:te.scrollLeft,top:te.scrollTop});for(typeof R.focus=="function"&&R.focus(),R=0;Ro?32:o,Q.T=null,o=rg,rg=null;var g=di,C=Ra;if(hn=0,ro=di=null,Ra=0,(_t&6)!==0)throw Error(r(331));var R=_t;if(_t|=4,FS(g.current),BS(g,g.current,C,o),_t=R,Gl(0,!1),un&&typeof un.onPostCommitFiberRoot=="function")try{un.onPostCommitFiberRoot(fr,g)}catch{}return!0}finally{ue.p=p,Q.T=u,cw(t,a)}}function dw(t,a,o){a=gr(o,a),a=Ip(t.stateNode,a,2),t=ai(t,a,2),t!==null&&(tt(t,2),ta(t))}function kt(t,a,o){if(t.tag===3)dw(t,t,o);else for(;a!==null;){if(a.tag===3){dw(a,t,o);break}else if(a.tag===1){var u=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ui===null||!ui.has(u))){t=gr(o,t),o=fS(2),u=ai(a,o,2),u!==null&&(hS(o,u,a,t),tt(u,2),ta(u));break}}a=a.return}}function og(t,a,o){var u=t.pingCache;if(u===null){u=t.pingCache=new Tk;var p=new Set;u.set(a,p)}else p=u.get(a),p===void 0&&(p=new Set,u.set(a,p));p.has(o)||(Zp=!0,p.add(o),t=Lk.bind(null,t,a,o),a.then(t,t))}function Lk(t,a,o){var u=t.pingCache;u!==null&&u.delete(a),t.pingedLanes|=t.suspendedLanes&o,t.warmLanes&=~o,It===t&&(ct&o)===o&&(Jt===4||Jt===3&&(ct&62914560)===ct&&300>Ot()-ed?(_t&2)===0&&ao(t,0):eg|=o,no===ct&&(no=0)),ta(t)}function fw(t,a){a===0&&(a=Me()),t=Wi(t,a),t!==null&&(tt(t,a),ta(t))}function $k(t){var a=t.memoizedState,o=0;a!==null&&(o=a.retryLane),fw(t,o)}function Mk(t,a){var o=0;switch(t.tag){case 31:case 13:var u=t.stateNode,p=t.memoizedState;p!==null&&(o=p.retryLane);break;case 19:u=t.stateNode;break;case 22:u=t.stateNode._retryCache;break;default:throw Error(r(314))}u!==null&&u.delete(a),fw(t,o)}function Nk(t,a){return Dt(t,a)}var od=null,so=null,lg=!1,ld=!1,cg=!1,hi=0;function ta(t){t!==so&&t.next===null&&(so===null?od=so=t:so=so.next=t),ld=!0,lg||(lg=!0,jk())}function Gl(t,a){if(!cg&&ld){cg=!0;do for(var o=!1,u=od;u!==null;){if(t!==0){var p=u.pendingLanes;if(p===0)var g=0;else{var C=u.suspendedLanes,R=u.pingedLanes;g=(1<<31-dn(42|t)+1)-1,g&=p&~(C&~R),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(o=!0,mw(u,g))}else g=ct,g=xe(u,u===It?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||Ke(u,g)||(o=!0,mw(u,g));u=u.next}while(o);cg=!1}}function Ik(){hw()}function hw(){ld=lg=!1;var t=0;hi!==0&&Kk()&&(t=hi);for(var a=Ot(),o=null,u=od;u!==null;){var p=u.next,g=pw(u,a);g===0?(u.next=null,o===null?od=p:o.next=p,p===null&&(so=o)):(o=u,(t!==0||(g&3)!==0)&&(ld=!0)),u=p}hn!==0&&hn!==5||Gl(t),hi!==0&&(hi=0)}function pw(t,a){for(var o=t.suspendedLanes,u=t.pingedLanes,p=t.expirationTimes,g=t.pendingLanes&-62914561;0R)break;var re=P.transferSize,le=P.initiatorType;re&&_w(le)&&(P=P.responseEnd,C+=re*(P"u"?null:document;function Iw(t,a,o){var u=oo;if(u&&typeof a=="string"&&a){var p=Bn(a);p='link[rel="'+t+'"][href="'+p+'"]',typeof o=="string"&&(p+='[crossorigin="'+o+'"]'),Nw.has(p)||(Nw.add(p),t={rel:t,crossOrigin:o,href:a},u.querySelector(p)===null&&(a=u.createElement("link"),_n(a,"link",t),nn(a),u.head.appendChild(a)))}}function nR(t){Da.D(t),Iw("dns-prefetch",t,null)}function rR(t,a){Da.C(t,a),Iw("preconnect",t,a)}function aR(t,a,o){Da.L(t,a,o);var u=oo;if(u&&t&&a){var p='link[rel="preload"][as="'+Bn(a)+'"]';a==="image"&&o&&o.imageSrcSet?(p+='[imagesrcset="'+Bn(o.imageSrcSet)+'"]',typeof o.imageSizes=="string"&&(p+='[imagesizes="'+Bn(o.imageSizes)+'"]')):p+='[href="'+Bn(t)+'"]';var g=p;switch(a){case"style":g=lo(t);break;case"script":g=co(t)}wr.has(g)||(t=y({rel:"preload",href:a==="image"&&o&&o.imageSrcSet?void 0:t,as:a},o),wr.set(g,t),u.querySelector(p)!==null||a==="style"&&u.querySelector(Wl(g))||a==="script"&&u.querySelector(Yl(g))||(a=u.createElement("link"),_n(a,"link",t),nn(a),u.head.appendChild(a)))}}function iR(t,a){Da.m(t,a);var o=oo;if(o&&t){var u=a&&typeof a.as=="string"?a.as:"script",p='link[rel="modulepreload"][as="'+Bn(u)+'"][href="'+Bn(t)+'"]',g=p;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=co(t)}if(!wr.has(g)&&(t=y({rel:"modulepreload",href:t},a),wr.set(g,t),o.querySelector(p)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(o.querySelector(Yl(g)))return}u=o.createElement("link"),_n(u,"link",t),nn(u),o.head.appendChild(u)}}}function sR(t,a,o){Da.S(t,a,o);var u=oo;if(u&&t){var p=Ga(u).hoistableStyles,g=lo(t);a=a||"default";var C=p.get(g);if(!C){var R={loading:0,preload:null};if(C=u.querySelector(Wl(g)))R.loading=5;else{t=y({rel:"stylesheet",href:t,"data-precedence":a},o),(o=wr.get(g))&&Ag(t,o);var P=C=u.createElement("link");nn(P),_n(P,"link",t),P._p=new Promise(function(X,re){P.onload=X,P.onerror=re}),P.addEventListener("load",function(){R.loading|=1}),P.addEventListener("error",function(){R.loading|=2}),R.loading|=4,hd(C,a,u)}C={type:"stylesheet",instance:C,count:1,state:R},p.set(g,C)}}}function oR(t,a){Da.X(t,a);var o=oo;if(o&&t){var u=Ga(o).hoistableScripts,p=co(t),g=u.get(p);g||(g=o.querySelector(Yl(p)),g||(t=y({src:t,async:!0},a),(a=wr.get(p))&&xg(t,a),g=o.createElement("script"),nn(g),_n(g,"link",t),o.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(p,g))}}function lR(t,a){Da.M(t,a);var o=oo;if(o&&t){var u=Ga(o).hoistableScripts,p=co(t),g=u.get(p);g||(g=o.querySelector(Yl(p)),g||(t=y({src:t,async:!0,type:"module"},a),(a=wr.get(p))&&xg(t,a),g=o.createElement("script"),nn(g),_n(g,"link",t),o.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(p,g))}}function jw(t,a,o,u){var p=(p=se.current)?fd(p):null;if(!p)throw Error(r(446));switch(t){case"meta":case"title":return null;case"style":return typeof o.precedence=="string"&&typeof o.href=="string"?(a=lo(o.href),o=Ga(p).hoistableStyles,u=o.get(a),u||(u={type:"style",instance:null,count:0,state:null},o.set(a,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(o.rel==="stylesheet"&&typeof o.href=="string"&&typeof o.precedence=="string"){t=lo(o.href);var g=Ga(p).hoistableStyles,C=g.get(t);if(C||(p=p.ownerDocument||p,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(t,C),(g=p.querySelector(Wl(t)))&&!g._p&&(C.instance=g,C.state.loading=5),wr.has(t)||(o={rel:"preload",as:"style",href:o.href,crossOrigin:o.crossOrigin,integrity:o.integrity,media:o.media,hrefLang:o.hrefLang,referrerPolicy:o.referrerPolicy},wr.set(t,o),g||cR(p,t,o,C.state))),a&&u===null)throw Error(r(528,""));return C}if(a&&u!==null)throw Error(r(529,""));return null;case"script":return a=o.async,o=o.src,typeof o=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=co(o),o=Ga(p).hoistableScripts,u=o.get(a),u||(u={type:"script",instance:null,count:0,state:null},o.set(a,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,t))}}function lo(t){return'href="'+Bn(t)+'"'}function Wl(t){return'link[rel="stylesheet"]['+t+"]"}function Hw(t){return y({},t,{"data-precedence":t.precedence,precedence:null})}function cR(t,a,o,u){t.querySelector('link[rel="preload"][as="style"]['+a+"]")?u.loading=1:(a=t.createElement("link"),u.preload=a,a.addEventListener("load",function(){return u.loading|=1}),a.addEventListener("error",function(){return u.loading|=2}),_n(a,"link",o),nn(a),t.head.appendChild(a))}function co(t){return'[src="'+Bn(t)+'"]'}function Yl(t){return"script[async]"+t}function zw(t,a,o){if(a.count++,a.instance===null)switch(a.type){case"style":var u=t.querySelector('style[data-href~="'+Bn(o.href)+'"]');if(u)return a.instance=u,nn(u),u;var p=y({},o,{"data-href":o.href,"data-precedence":o.precedence,href:null,precedence:null});return u=(t.ownerDocument||t).createElement("style"),nn(u),_n(u,"style",p),hd(u,o.precedence,t),a.instance=u;case"stylesheet":p=lo(o.href);var g=t.querySelector(Wl(p));if(g)return a.state.loading|=4,a.instance=g,nn(g),g;u=Hw(o),(p=wr.get(p))&&Ag(u,p),g=(t.ownerDocument||t).createElement("link"),nn(g);var C=g;return C._p=new Promise(function(R,P){C.onload=R,C.onerror=P}),_n(g,"link",u),a.state.loading|=4,hd(g,o.precedence,t),a.instance=g;case"script":return g=co(o.src),(p=t.querySelector(Yl(g)))?(a.instance=p,nn(p),p):(u=o,(p=wr.get(g))&&(u=y({},o),xg(u,p)),t=t.ownerDocument||t,p=t.createElement("script"),nn(p),_n(p,"link",u),t.head.appendChild(p),a.instance=p);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(u=a.instance,a.state.loading|=4,hd(u,o.precedence,t));return a.instance}function hd(t,a,o){for(var u=o.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),p=u.length?u[u.length-1]:null,g=p,C=0;C title"):null)}function uR(t,a,o){if(o===1||a.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;return a.rel==="stylesheet"?(t=a.disabled,typeof a.precedence=="string"&&t==null):!0;case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function Bw(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function dR(t,a,o,u){if(o.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(o.state.loading&4)===0){if(o.instance===null){var p=lo(u.href),g=a.querySelector(Wl(p));if(g){a=g._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(t.count++,t=gd.bind(t),a.then(t,t)),o.state.loading|=4,o.instance=g,nn(g);return}g=a.ownerDocument||a,u=Hw(u),(p=wr.get(p))&&Ag(u,p),g=g.createElement("link"),nn(g);var C=g;C._p=new Promise(function(R,P){C.onload=R,C.onerror=P}),_n(g,"link",u),o.instance=g}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(o,a),(a=o.state.preload)&&(o.state.loading&3)===0&&(t.count++,o=gd.bind(t),a.addEventListener("load",o),a.addEventListener("error",o))}}var Tg=0;function fR(t,a){return t.stylesheets&&t.count===0&&yd(t,t.stylesheets),0Tg?50:800)+a);return t.unsuspend=o,function(){t.unsuspend=null,clearTimeout(u),clearTimeout(p)}}:null}function gd(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)yd(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var md=null;function yd(t,a){t.stylesheets=null,t.unsuspend!==null&&(t.count++,md=new Map,a.forEach(hR,t),md=null,gd.call(t))}function hR(t,a){if(!(a.state.loading&4)){var o=md.get(t);if(o)var u=o.get(null);else{o=new Map,md.set(t,o);for(var p=t.querySelectorAll("link[data-precedence],style[data-precedence]"),g=0;g"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),Td.exports=l0(),Td.exports}var Od=c0();const Ld=ra(Od),ho=[],u0=50;let $d=!1;function qg(){try{return window.G7Core?.devTools}catch{return}}function os(s,e,n){const r=qg();if($d&&r?.isEnabled?.()){r.trackLog?.(s,e,n);return}$d||(s==="error"||s==="warn")&&ho.length{n.isDebugEnabled()&&console.log(e,...r),os("log",s,r)},warn:(...r)=>{n.isDebugEnabled()&&console.warn(e,...r),os("warn",s,r)},error:(...r)=>{n.isDebugEnabled()&&console.error(e,...r),os("error",s,r)}}}po.getInstance();const Gg="extension",ls="extensionless",Fg="file";function d0(){const s=globalThis?.G7Config;if(globalThis?.__g7AssetUrlMode===ls)return ls;const n=s?.assetUrlMode;return n===ls||n===Gg?n:s?.settings?.general?.asset_url_mode===ls?ls:Gg}function Nd(){return d0()===ls}function f0(s,e,n){return Id("templates",s,e,n)}function h0(s,e){const n=e.replace(/^\/+/,"").replace(/\/+$/,""),r=encodeURIComponent(s),i=go(`templates/${s}/assets/${n}`);return i!==null?i:`/api/templates/assets/${r}/${n}`}function p0(s,e,n){return Id("modules",s,e,n)}function g0(s,e,n){return Id("plugins",s,e,n)}function Id(s,e,n,r){const i=n.replace(/^\/+/,""),l=encodeURIComponent(e);if(!Nd())return`/api/${s}/assets/${l}/${i}${b0(r)}`;let c=`${Fg}=${encodeURIComponent(i)}`;return r!=null&&r!==""&&(c+=`&v=${r}`),`/api/${s}/assets/${l}?${c}`}function Ur(s,e,n,r){const i=s.replace(/\/+$/,""),l=e.replace(/^\.+/,""),c=Nd()?i:`${i}.${l}`,d=[];return r&&d.push(r.replace(/^[?&]+/,"")),n!=null&&n!==""&&d.push(`v=${n}`),d.length>0?`${c}?${d.join("&")}`:c}function Vg(){const s=globalThis?.G7Config?.staticBase;return typeof s=="string"&&s!==""?s.replace(/\/+$/,""):null}function m0(){const s=Vg();if(!s)return null;const e=s.match(/\/(\d+)$/);return e?Number(e[1]):null}function go(s,e){const n=Vg();if(!n)return null;const r=s.replace(/^\/+/,"");return e!==void 0&&e>0&&e!==m0()?`${n.replace(/\/\d+$/,"")}/${e}/${r}`:`${n}/${r}`}function jd(s){if(!s)return null;const e=globalThis?.location?.origin,r=(e&&s.startsWith(e)?s.slice(e.length):s).match(/^\/build\/ext\/(\d+)\/(.+)$/);if(!r)return null;const i=r[1],l=r[2].split("?")[0],c=l.match(/^(templates|modules|plugins)\/([^/]+)\/assets\/(.+)$/);if(c){const[,h,m,y]=c;return`/api/${h}/assets/${m}/${y}?v=${i}`}const d=l.match(/^bundles\/(modules|plugins)\.(js|css)$/);if(d)return`/api/${d[1]}/bundle.${d[2]}?v=${i}`;const f=l.match(/^templates\/([^/]+)\/(routes\.json|components\.json|lang\/([a-zA-Z-]+)\.json)$/);if(f){const[,h,m]=f,y=m.replace(/\.json$/,"");return`/api/templates/${h}/${y}.json?v=${i}`}return null}function Ln(s){if(!s||!Nd())return s;const e=globalThis?.location?.origin,n=e&&s.startsWith(e)?s.slice(e.length):s;if(!n.startsWith("/api/"))return s;const[r,i]=y0(n),l=r.match(/^\/api\/(modules|plugins)\/bundle\.(js|css)$/);if(l)return Kg(`/api/${l[1]}/bundle/${l[2]}`,i);const c=r.match(/^\/api\/(templates|modules|plugins)\/assets\/([^/]+)\/(.+)$/);if(c){const[,f,h,m]=c,y=`${Fg}=${encodeURIComponent(decodeURIComponent(m))}`;return`/api/${f}/assets/${h}?${y}${i?`&${i}`:""}`}const d=r.match(/^(\/api\/.+)\.(json|js|css)$/);return d?Kg(d[1],i):s}function y0(s){const e=s.indexOf("?");return e===-1?[s,""]:[s.slice(0,e),s.slice(e+1)]}function Kg(s,e){return e?`${s}?${e}`:s}function b0(s){return s==null||s===""?"":`?v=${s}`}const aa=pt("networkResilience"),Hd=2,zd=300,Pd=2e3,v0=15e3;function Ud(s){return s?.name==="AbortError"}function Wg(s){return Ud(s)?!1:s instanceof TypeError}let ec=!1,Yg=!1;function tc(){return ec}function S0(){typeof window>"u"||Yg||(Yg=!0,window.addEventListener("pagehide",()=>{ec=!0}),window.addEventListener("pageshow",s=>{s.persisted&&(ec=!1)}),window.addEventListener("beforeunload",()=>{ec=!0}))}function Bd(s,e,n){const r=Math.min(e*Math.pow(2,s),n),i=r*.25*(Math.random()*2-1);return Math.max(0,Math.round(r+i))}function qd(s){return new Promise(e=>setTimeout(e,s))}async function nc(s,e={}){const{retries:n=Hd,baseDelayMs:r=zd,maxDelayMs:i=Pd,timeoutMs:l=v0,label:c=s,init:d}=e,f=n+1;let h;for(let m=0;m0?new AbortController:null;try{const _={...d};if(S){const A=d?.signal;A&&(A.aborted?S.abort():A.addEventListener("abort",()=>S.abort(),{once:!0})),_.signal=S.signal,v=setTimeout(()=>{y=!0,S.abort()},l)}return await fetch(s,_)}catch(_){if(h=_,Ud(_)&&!y||!(y||Wg(_)))throw _;if(tc())throw aa.warn(`Document unloading, aborting retries: ${c}`),_;if(m===f-1)throw aa.warn(`All ${f} attempts failed: ${c}`,_),_;const D=Bd(m,r,i);aa.warn(`Network failure (attempt ${m+1}/${f}), retrying in ${D}ms: ${c}`),await qd(D)}finally{v!==void 0&&clearTimeout(v)}}throw h}async function Cr(s,e={},n={}){const{retries:r=Hd,baseDelayMs:i=zd,maxDelayMs:l=Pd,label:c=s}=n,d=r+1;for(let f=0;f{const i=document.createElement("script");i.src=s,i.async=!1;for(const[l,c]of Object.entries(e))l==="id"?i.id=c:i.setAttribute(l,c);i.onload=()=>n(),i.onerror=()=>r(new Error(`Failed to load script: ${s}`)),document.head.appendChild(i)})}async function ia(s,e={},n={}){const{retries:r=Hd,baseDelayMs:i=zd,maxDelayMs:l=Pd,label:c=s}=n,d=r+1;for(let f=0;f{s.onload=()=>e(),s.onerror=()=>n(new Error(`Failed to load stylesheet: ${s.href}`))})}async function rc(s,e,n={}){if(!s)return nc(e,n);try{const r=await fetch(s,n.init);if(r.ok){const i=await r.text();try{return JSON.parse(i),new Response(i,{status:r.status,statusText:r.statusText,headers:r.headers})}catch{return console.warn(`[fetchStaticFirst] Static fast path returned malformed JSON — falling back to API: ${s}`),nc(e,n)}}console.warn(`[fetchStaticFirst] Static fast path miss (${r.status}) — falling back to API: ${s}`)}catch(r){console.warn(`[fetchStaticFirst] Static fast path fetch failed — falling back to API: ${s}`,r)}return nc(e,n)}const Br=pt("ComponentRegistry");class pn extends Error{constructor(n,r,i){super(n);M(this,"code");M(this,"details");this.code=r,this.details=i,this.name="ComponentRegistryError"}}const Qn=class Qn{constructor(){M(this,"registry",{});M(this,"manifest",null);M(this,"cacheVersion",0);M(this,"loadingState","idle");M(this,"error",null);M(this,"templateId",null);M(this,"templateType",null)}static getInstance(){return Qn.instance||(Qn.instance=new Qn),Qn.instance}static createIsolatedInstance(){return new Qn}static resetInstance(){Qn.instance=null}async loadComponents(e,n,r=0){if(this.loadingState==="loading")throw new pn("Components are already being loaded","LOADING_IN_PROGRESS");if(this.loadingState==="loaded"&&this.templateId===e&&this.templateType===n){Br.log("Components already loaded for template:",e,n);return}this.loadingState="loading",this.templateId=e,this.templateType=n,this.cacheVersion=r,this.error=null;try{await this.loadManifest(),await this.loadComponentBundle(),this.loadingState="loaded",Br.log("Successfully loaded components:",Object.keys(this.registry).length)}catch(i){throw this.loadingState="error",this.error=i instanceof Error?i:new Error(String(i)),new pn(`Failed to load components: ${this.error.message}`,"LOAD_FAILED",{originalError:this.error})}}async loadManifest(){try{if(!this.templateId)throw new pn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=`${this.templateId}:${this.templateType}:v${this.cacheVersion||0}`;if(Qn.manifestCache.has(e)){this.manifest=Qn.manifestCache.get(e),Br.log("Manifest loaded from cache:",this.manifest.templateId);return}const n=Ur(`/api/templates/${this.templateId}/components`,"json",this.cacheVersion>0?this.cacheVersion:null),r=await rc(this.cacheVersion>0?go(`templates/${this.templateId}/components.json`,this.cacheVersion):null,n,{label:"components.json"});if(!r.ok)throw new pn(`Failed to fetch manifest: ${r.status} ${r.statusText}`,"MANIFEST_FETCH_FAILED",{status:r.status,statusText:r.statusText});const i=await r.json();this.validateManifest(i),this.manifest=i,Qn.manifestCache.set(e,i),Br.log("Manifest loaded and cached:",i.templateId)}catch(e){throw e instanceof pn?e:new pn("Failed to load component manifest","MANIFEST_LOAD_FAILED",{originalError:e})}}validateManifest(e){if(!e.version)throw new pn("Manifest missing required field: version","MANIFEST_INVALID",{field:"version"});if(!e.templateId)throw new pn("Manifest missing required field: templateId","MANIFEST_INVALID",{field:"templateId"});if(!e.components||typeof e.components!="object")throw new pn("Manifest missing required field: components","MANIFEST_INVALID",{field:"components"});const n=["basic","composite","layout"];for(const r of n){if(!Array.isArray(e.components[r]))throw new pn(`Manifest field 'components.${r}' must be an array`,"MANIFEST_INVALID",{field:`components.${r}`,value:e.components[r]});e.components[r].forEach((i,l)=>{if(!i.name||typeof i.name!="string")throw new pn(`Invalid component metadata at ${r}[${l}]: missing or invalid 'name'`,"MANIFEST_INVALID",{type:r,index:l,metadata:i});if(!i.type||typeof i.type!="string")throw new pn(`Invalid component metadata at ${r}[${l}]: missing or invalid 'type'`,"MANIFEST_INVALID",{type:r,index:l,metadata:i})})}Br.log("Manifest validation passed")}async loadComponentBundle(){try{if(!this.templateId)throw new pn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=this.getGlobalVariableName(),n=window[e];if(!n||typeof n!="object")throw new pn(`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(n),Br.log("Component bundle loaded from global variable:",e)}catch(e){throw e instanceof pn?e:new pn("Failed to load component bundle","BUNDLE_LOAD_FAILED",{originalError:e})}}getGlobalVariableName(){if(!this.templateId)throw new pn("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 pn("Manifest not loaded","MANIFEST_NOT_LOADED");const n=["basic","composite","layout"];for(const r of n){const i=this.manifest.components[r]||[];for(const l of i){const c=l.name,d=e[c];if(!d){Br.warn(`Component '${c}' not found in bundle`);continue}this.registerComponent(c,d,l)}}}registerComponent(e,n,r){this.registry[e]&&Br.warn(`Component '${e}' already registered, overwriting`);const i=Xe.memo(n);this.registry[e]={component:i,metadata:r},Br.log(`[ComponentRegistry] Registered component: ${e} (${r.type})`)}getComponent(e){const n=this.registry[e];return n?n.component:null}getMetadata(e){const n=this.registry[e];return n?n.metadata:null}hasComponent(e){return e in this.registry}getComponentsByType(e){return Object.entries(this.registry).filter(([n,r])=>r.metadata.type===e).map(([n,r])=>n)}getAllComponents(){return Object.keys(this.registry)}getComponentMap(){const e={};for(const[n,r]of Object.entries(this.registry))e[n]=r.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,Br.log("Registry cleared")}};M(Qn,"instance",null),M(Qn,"manifestCache",new Map);let Er=Qn;const Xg=pt("TranslationEngine");class Gd extends Error{constructor(n,r,i){super(n);M(this,"key");M(this,"locale");this.key=r,this.locale=i,this.name="TranslationError"}}const zn=class zn{constructor(e={}){M(this,"cache",new Map);M(this,"translations",new Map);M(this,"options");M(this,"cacheVersion",0);this.options={defaultLocale:e.defaultLocale||"ko",fallbackLocale:e.fallbackLocale||"en",cacheTTL:e.cacheTTL||3e5}}static getInstance(e={}){return zn.instance||(zn.instance=new zn(e)),zn.instance}static resetInstance(){zn.instance=null}setCacheVersion(e){this.cacheVersion!==e&&(Xg.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.cache.clear())}getCacheVersion(){return this.cacheVersion}async loadTranslations(e,n,r="/api",i=!1){const l=`${e}:${n}`;if(!i){const c=this.getFromCache(l);if(c)return this.translations.set(l,c),c}try{const c=[];i&&c.push(`_=${Date.now()}`);const d=Ur(`${r}/templates/${e}/lang/${n}`,"json",this.cacheVersion>0?this.cacheVersion:null,c.length>0?c.join("&"):void 0),f=!i&&this.cacheVersion>0?go(`templates/${e}/lang/${n}.json`,this.cacheVersion):null,h=f!==null?await rc(f,d,{label:`lang/${n}.json`}):await fetch(d);if(!h.ok)throw new Gd(`Failed to load translations: ${h.statusText}`,void 0,n);const y=await h.json();return this.saveToCache(l,y),this.translations.set(l,y),y}catch(c){throw new Gd(`Failed to fetch translations for ${n}: ${c instanceof Error?c.message:String(c)}`,void 0,n)}}resolveTranslations(e,n,r){let i=e;const l=5;let c=0;for(;c"="+this.translate(m,n,void 0,r)),i===d)break;c++}return i.replace(zn.TRANSLATION_PATTERN,(d,f,h)=>{const{cleanedParams:m,trailing:y}=this.separateTrailingText(h);return this.translate(f,n,m,r)+y})}translate(e,n,r,i){const l=this.getTranslation(e,n),c=r&&this.cleanParamsStr(r);if(c){const d=this.parseParams(c,i);return this.replaceParams(l,d)}return l}getTranslation(e,n){const{templateId:r,locale:i}=n,l=`${r}:${i}`,c=this.translations.get(l);if(c){const d=this.getNestedValue(c,e);if(d!==null)return d}if(i!==this.options.fallbackLocale){const d=`${r}:${this.options.fallbackLocale}`,f=this.translations.get(d);if(f){const h=this.getNestedValue(f,e);if(h!==null)return h}}return e}getNestedValue(e,n){const r=n.split(".");let i=e;for(const l of r){if(i==null||typeof i!="object")return null;i=i[l]}return typeof i=="string"?i:null}setTranslationValue(e,n,r,i){const l=`${e}:${n}`,c=this.translations.get(l)??{},d=r.split(".");let f=c;for(let h=0;h(l.push(f),`__PLACEHOLDER_${l.length-1}__`)).matchAll(zn.PARAM_PATTERN);for(const f of d){const[,h,m]=f,y=m.replace(/__PLACEHOLDER_(\d+)__/g,(v,S)=>l[parseInt(S,10)]);r[h.trim()]=this.resolveParamValue(y.trim(),n)}return r}resolveParamValue(e,n){if(e.startsWith("{{")&&e.endsWith("}}")){const r=e.slice(2,-2).trim();if(/[|&()[\]!?:+\-*/%<>=\s]/.test(r)&&n)try{const l=of.evaluateExpression(r,n);return String(l??"")}catch(l){return Xg.error("Expression evaluation failed:",r,l),""}else{const l=this.getNestedDataValue(n,r);return String(l??"")}}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 r=e.match(/(\s+[^\p{L}\w=|&\s][^\p{L}\w=]*\s*)$/u);return r?{cleanedParams:e.slice(0,-r[1].length),trailing:r[1]}:{cleanedParams:e,trailing:""}}cleanParamsStr(e){return this.separateTrailingText(e).cleanedParams||""}getNestedDataValue(e,n){if(!e)return;const r=n.split(".");let i=e;for(const l of r){if(i==null)return;i=i[l]}return i}replaceParams(e,n){let r=e;for(const[i,l]of Object.entries(n)){const c=new RegExp(`\\{\\{${i}\\}\\}`,"g");r=r.replace(c,String(l));const d=new RegExp(`\\{${i}\\}`,"g");r=r.replace(d,String(l))}return r}getFromCache(e){const n=this.cache.get(e);return n?Date.now()-n.timestamp>this.options.cacheTTL?(this.cache.delete(e),null):n.data:null}saveToCache(e,n){this.cache.set(e,{data:n,timestamp:Date.now()})}clearCache(){this.cache.clear(),this.translations.clear()}pruneCache(){const e=Date.now(),n=[];for(const[r,i]of this.cache.entries())e-i.timestamp>this.options.cacheTTL&&n.push(r);for(const r of n)this.cache.delete(r)}getCacheStats(){const e=Date.now();let n=0;for(const r of this.cache.values())e-r.timestamp>this.options.cacheTTL&&n++;return{size:this.cache.size,expired:n}}};M(zn,"instance",null),M(zn,"TRANSLATION_PATTERN",/\$t:(?:defer:)?([a-zA-Z0-9._-]+)(\|(?:(?!\$t:).)+)?/g),M(zn,"NESTED_TRANSLATION_PARAM_PATTERN",/=(\$t:([a-zA-Z0-9._-]+))(?=[|&\s]|$)/g),M(zn,"PARAM_PATTERN",/([^=|&]+)=([^|&]+)/g);let Oa=zn,Fd=null;function _0(s){return Fd||(Fd=new Oa(s)),Fd}const Jg=Object.freeze(Object.defineProperty({__proto__:null,TranslationEngine:Oa,TranslationError:Gd,getTranslationEngine:_0},Symbol.toStringTag,{value:"Module"})),cs=pt("PipeRegistry");function Qg(s,e){const n=s.getFullYear(),r=String(s.getMonth()+1).padStart(2,"0"),i=String(s.getDate()).padStart(2,"0"),l=String(s.getHours()).padStart(2,"0"),c=String(s.getMinutes()).padStart(2,"0"),d=String(s.getSeconds()).padStart(2,"0");return e.replace("YYYY",String(n)).replace("YY",String(n).slice(-2)).replace("MM",r).replace("M",String(s.getMonth()+1)).replace("DD",i).replace("D",String(s.getDate())).replace("HH",l).replace("H",String(s.getHours())).replace("mm",c).replace("m",String(s.getMinutes())).replace("ss",d).replace("s",String(s.getSeconds()))}function A0(s,e="ko"){const r=new Date().getTime()-s.getTime(),i=Math.floor(r/1e3),l=Math.floor(i/60),c=Math.floor(l/60),d=Math.floor(c/24),f=Math.floor(d/7),h=Math.floor(d/30),m=Math.floor(d/365);return e==="ko"?i<60?"방금 전":l<60?`${l}분 전`:c<24?`${c}시간 전`:d<7?`${d}일 전`:f<4?`${f}주 전`:h<12?`${h}개월 전`:`${m}년 전`:i<60?"just now":l<60?`${l} minute${l===1?"":"s"} ago`:c<24?`${c} hour${c===1?"":"s"} ago`:d<7?`${d} day${d===1?"":"s"} ago`:f<4?`${f} week${f===1?"":"s"} ago`:h<12?`${h} month${h===1?"":"s"} ago`:`${m} year${m===1?"":"s"} ago`}function Vd(s){if(s==null)return null;if(s instanceof Date)return s;if(typeof s=="number")return new Date(s);if(typeof s=="string"){const e=new Date(s);return isNaN(e.getTime())?null:e}return null}const mo={date:{fn:(s,e="YYYY-MM-DD")=>{const n=Vd(s);return n?Qg(n,e):""},description:"날짜 포맷 (기본: YYYY-MM-DD)"},datetime:{fn:(s,e="YYYY-MM-DD HH:mm")=>{const n=Vd(s);return n?Qg(n,e):""},description:"날짜+시간 포맷 (기본: YYYY-MM-DD HH:mm)"},relativeTime:{fn:(s,e="ko")=>{const n=Vd(s);return n?A0(n,e):""},description:'상대 시간 표시 (예: "3분 전")'},number:{fn:(s,e)=>{const n=Number(s);if(isNaN(n))return String(s??"");const r={};return e!==void 0&&(r.minimumFractionDigits=e,r.maximumFractionDigits=e),n.toLocaleString(void 0,r)},description:"숫자 포맷 (천단위 구분, 선택적 소수점)"},truncate:{fn:(s,e=100,n="...")=>typeof s!="string"?String(s??""):s.length<=e?s:s.slice(0,e)+n,description:'문자열 자르기 (기본: 100자, 접미사: "...")'},uppercase:{fn:s=>typeof s!="string"?String(s??""):s.toUpperCase(),description:"대문자 변환"},lowercase:{fn:s=>typeof s!="string"?String(s??""):s.toLowerCase(),description:"소문자 변환"},stripHtml:{fn:s=>typeof s!="string"?String(s??""):s.replace(/<[^>]*>/g,""),description:"HTML 태그 제거"},default:{fn:(s,e="")=>s==null||s===""?e:s,description:"기본값 설정 (null, undefined, 빈문자열 시)"},fallback:{fn:(s,e)=>s??e,description:"폴백 값 설정 (null, undefined 시만)"},first:{fn:s=>{if(Array.isArray(s))return s[0]},description:"배열의 첫 번째 요소"},last:{fn:s=>{if(Array.isArray(s))return s[s.length-1]},description:"배열의 마지막 요소"},join:{fn:(s,e=", ")=>Array.isArray(s)?s.join(e):"",description:'배열을 문자열로 결합 (기본 구분자: ", ")'},length:{fn:s=>Array.isArray(s)||typeof s=="string"?s.length:0,description:"배열/문자열 길이"},filterBy:{fn:(s,e,n)=>Array.isArray(s)?Array.isArray(e)?s.filter(r=>{const i=n?r?.[n]:r;return e.includes(i)}):s:[],description:"배열 필터링 (allowList에 포함된 항목만 반환)"},keys:{fn:s=>s==null||typeof s!="object"?[]:Object.keys(s),description:"객체의 키 배열"},values:{fn:s=>s==null||typeof s!="object"?[]:Object.values(s),description:"객체의 값 배열"},json:{fn:(s,e)=>{try{return JSON.stringify(s,null,e)}catch{return""}},description:"JSON 문자열로 변환"},localized:{fn:(s,e)=>s==null?"":typeof s=="string"?s:typeof s!="object"?String(s):s[e||"ko"]||s.ko||s.en||Object.values(s)[0]||"",description:"다국어 객체에서 로케일에 맞는 값 추출"}},us=new Map,Oi=class Oi{static getInstance(){return Oi.instance||(Oi.instance=new Oi),Oi.instance}register(e,n,r){if(mo[e]){cs.warn(`[PipeRegistry] 내장 파이프를 덮어쓸 수 없습니다: ${e}`);return}us.set(e,{fn:n,description:r}),cs.log(`[PipeRegistry] 커스텀 파이프 등록됨: ${e}`)}unregister(e){if(mo[e])return cs.warn(`[PipeRegistry] 내장 파이프는 해제할 수 없습니다: ${e}`),!1;const n=us.delete(e);return n&&cs.log(`[PipeRegistry] 커스텀 파이프 해제됨: ${e}`),n}get(e){const n=mo[e];return n?n.fn:us.get(e)?.fn}has(e){return!!mo[e]||us.has(e)}execute(e,n,r=[]){const i=this.get(e);if(!i)return cs.warn(`[PipeRegistry] 알 수 없는 파이프: ${e}`),n;try{return i(n,...r)}catch(l){return cs.error(`[PipeRegistry] 파이프 실행 오류 (${e}):`,l),n}}list(){const e=[];for(const[n,r]of Object.entries(mo))e.push({name:n,description:r.description,type:"built-in"});for(const[n,r]of us.entries())e.push({name:n,description:r.description,type:"custom"});return e.sort((n,r)=>n.name.localeCompare(r.name))}clearCustomPipes(){us.clear()}};M(Oi,"instance",null);let ac=Oi;ac.getInstance();function x0(s){const e=s.trim(),n=e.indexOf("(");if(n===-1)return{name:e,args:[]};const r=e.slice(0,n).trim(),i=e.slice(n+1,-1);if(!i.trim())return{name:r,args:[]};const l=[];let c="",d=null,f=0;for(let h=0;h0?i[h-1]:"")==="\\"){c+=m;continue}if((m==='"'||m==="'")&&!d){d=m;continue}if(m===d){d=null;continue}if(d){c+=m;continue}if(m==="("||m==="["||m==="{"){f++,c+=m;continue}if(m===")"||m==="]"||m==="}"){f--,c+=m;continue}if(m===","&&f===0){l.push(Zg(c.trim())),c="";continue}c+=m}return c.trim()&&l.push(Zg(c.trim())),{name:r,args:l}}function Zg(s){if(s==="null")return null;if(s==="undefined")return;if(s==="true")return!0;if(s==="false")return!1;const e=Number(s);return!isNaN(e)&&s!==""?e:s}function T0(s){const e=[];let n="",r=null,i=0;for(let l=0;l0?s[l-1]:"",f=l0?s[r-1]:"",c=r0){r--;continue}return null}}return r===0?e.trim():null}function R0(s){const e=[];if(typeof s!="string")return e;for(let n=0;n0){i--;continue}if(s[c+1]==="}"){l=c;break}break}}l!==-1&&(e.push({start:n,end:l+2,expr:s.slice(n+2,l)}),n=l+1)}return e}function yo(s){return/[?:|&!+\-*/<>=()[\]{}]/.test(s)}function em(s){const e=typeof s=="string"?s.trim():"";return e===""?"empty":Kd.has(e)?"literal":Wn(e)?"pipe":yo(e)?"expression":"path"}function Wd(s,e,n,r){const i=typeof s=="string"?s.trim():"",l=em(i),c=r?.skipCache?{skipCache:!0}:void 0;if(l==="empty"){r?.onEmpty?.(s);return}if(l==="literal")return Kd.get(i);try{return l==="pipe"?n.evaluatePipeExpression(i,e,c,r?.trackingInfo):l==="expression"?n.evaluateExpression(i,e,r?.trackingInfo):n.resolve(i,e,c,r?.trackingInfo)}catch(d){if(r?.onError)return r.onError(d,i);throw d}}const sr="raw:";function tm(s){return s.startsWith(sr)?s.slice(sr.length):s}const bo="﷐",Si="﷑",$a="﷒";function vo(s){return bo+s+Si}function ic(s){return s.length>=2&&s.charCodeAt(0)===64976&&s.charCodeAt(s.length-1)===64977}function sc(s){return s.includes(bo)}function Yd(s){return s.slice(1,-1)}function ds(s){if(typeof s=="string")return vo(s);if(Array.isArray(s))return s.map(ds);if(s&&typeof s=="object"){const e={};for(const[n,r]of Object.entries(s))e[n]=ds(r);return e}return s}function Ma(s){if(typeof s=="string")return ic(s)?Yd(s):sc(s)||s.includes(Si)?s.split(bo).join("").split(Si).join(""):s;if(Array.isArray(s)){let e=!1;const n=s.map(r=>{const i=Ma(r);return i!==r&&(e=!0),i});return e?n:s}if(s&&typeof s=="object"){if(s.$$typeof!==void 0)return s;let e=!1;const n={};for(const[r,i]of Object.entries(s)){const l=Ma(i);l!==i&&(e=!0),n[r]=l}return e?n:s}return s}const So=new Set(["constructor","__proto__","prototype","__lookupGetter__","__lookupSetter__","__defineGetter__","__defineSetter__"]),D0=new Set(["Function","eval","globalThis","window","self","document","require","module","process","Reflect","Proxy","WebAssembly","import","constructor"]);function nm(s,e){if(s!==null&&(typeof s=="object"||typeof s=="function")&&rm.has(s))throw new Error(`Object.${e} on a built-in global object is not allowed`);return s}const O0=Object.freeze({keys:Object.keys,values:Object.values,entries:Object.entries,assign:(s,...e)=>{const n=nm(s,"assign");for(const r of e)if(r!=null)for(const i of Object.keys(r)){if(So.has(i))throw new Error(`Access to "${i}" is forbidden`);rf(n,i,r[i])}return n},freeze:s=>Object.freeze(nm(s,"freeze")),fromEntries:Object.fromEntries,create:Object.create,isFrozen:Object.isFrozen}),Xd={Math,JSON,Date,Array,Object:O0,Number,String,Boolean,Set,Map,WeakSet,WeakMap,parseInt,parseFloat,isNaN,isFinite},Jd={Date,Set,Map,WeakSet,WeakMap,Array,Number,String,Boolean,Object},rm=new Set([...Object.values(Xd),...Object.values(Jd)].filter(s=>s!==null&&(typeof s=="object"||typeof s=="function"))),oc=new Set(["function"]),_r=Symbol("short-circuit");class Qd{constructor(e){M(this,"value");this.value=e}}class Zd{}class ef{}function L0(s){return/[A-Za-z_$]/.test(s)}function $0(s){return/[A-Za-z0-9_$]/.test(s)}function wi(s){return s>="0"&&s<="9"}function M0(s,e,n){let r=e+1;for(;r0;){const h=s[n];if(h==="{")f++,n++;else if(h==="}"){if(f--,f===0)break;n++}else h==='"'||h==="'"?n=M0(s,n,h):h==="`"?n=am(s,n).end:n++}if(f!==0)throw new Error("Unterminated ${...} in template literal");i.push(s.slice(d,n)),n++;continue}l+=c,n++}throw new Error(`Unterminated template literal at position ${e}`)}function N0(s){const e=[];let n=0;const r=s.length,i=l=>n+l=r)throw new Error(`Unterminated string literal at position ${h}`);n++,e.push({type:"str",value:y,pos:h});continue}if(L0(l)){const h=n;for(n++;n"?(e.push({type:"punct",value:"=>",pos:c}),n+=2):i(1)==="="?i(2)==="="?(e.push({type:"punct",value:"===",pos:c}),n+=3):(e.push({type:"punct",value:"==",pos:c}),n+=2):(e.push({type:"punct",value:"=",pos:c}),n+=1);continue}case"!":{i(1)==="="?i(2)==="="?(e.push({type:"punct",value:"!==",pos:c}),n+=3):(e.push({type:"punct",value:"!=",pos:c}),n+=2):(e.push({type:"punct",value:"!",pos:c}),n+=1);continue}case"<":{if(i(1)==="=")e.push({type:"punct",value:"<=",pos:c}),n+=2;else{if(i(1)==="<")throw new Error("Bitwise/shift operators are not allowed");e.push({type:"punct",value:"<",pos:c}),n+=1}continue}case">":{if(i(1)==="=")e.push({type:"punct",value:">=",pos:c}),n+=2;else{if(i(1)===">")throw new Error("Bitwise/shift operators are not allowed");e.push({type:"punct",value:">",pos:c}),n+=1}continue}case"&":{if(i(1)==="&")e.push({type:"punct",value:"&&",pos:c}),n+=2;else throw new Error("Bitwise operators are not allowed");continue}case"|":{if(i(1)==="|")e.push({type:"punct",value:"||",pos:c}),n+=2;else throw new Error("Bitwise operators are not allowed");continue}case"?":{i(1)==="."&&!wi(i(2))?(e.push({type:"punct",value:"?.",pos:c}),n+=2):i(1)==="?"?(e.push({type:"punct",value:"??",pos:c}),n+=2):(e.push({type:"punct",value:"?",pos:c}),n+=1);continue}case"+":{if(i(1)==="+")throw new Error("Increment operator is not allowed");if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"+",pos:c}),n+=1;continue}case"-":{if(i(1)==="-")throw new Error("Decrement operator is not allowed");if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"-",pos:c}),n+=1;continue}case"*":{if(i(1)==="=")throw new Error("Assignment operators are not allowed");if(i(1)==="*")throw new Error("Exponentiation operator is not supported");e.push({type:"punct",value:"*",pos:c}),n+=1;continue}case"/":{if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"/",pos:c}),n+=1;continue}case"%":{if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"%",pos:c}),n+=1;continue}case"~":case"^":throw new Error("Bitwise operators are not allowed");case".":case":":case"(":case")":case"[":case"]":case"{":case"}":case",":e.push({type:"punct",value:l,pos:c}),n+=1;continue;case";":e.push({type:"punct",value:";",pos:c}),n+=1;continue;default:throw new Error(`Unexpected character "${l}" at position ${c}`)}}return e}const I0={"??":1,"||":1,"&&":2,"===":3,"!==":3,"==":3,"!=":3,"<":4,">":4,"<=":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},j0=new Set(["??","||","&&"]);class H0{constructor(e){M(this,"tokens");M(this,"pos",0);this.tokens=e}atEnd(){return this.pos>=this.tokens.length}peek(e=0){const n=this.pos+e;return n"}"`);this.pos++}parseExpression(){const e=this.tryParseArrow();return e||this.parseTernary()}tryParseArrow(){const e=this.pos,n=this.peek();if(!n)return null;if(n.type==="ident"&&this.isPunct("=>",1)&&!oc.has(String(n.value))){this.pos+=1,this.pos+=1;const{body:r,isBlock:i}=this.parseArrowBody();return{type:"Arrow",params:[{name:String(n.value),default:null}],body:r,isBlock:i}}if(n.type==="punct"&&n.value==="("){this.pos+=1;const r=this.tryParseParamList();if(r&&this.isPunct(")")&&(this.pos+=1,this.isPunct("=>"))){this.pos+=1;const{body:i,isBlock:l}=this.parseArrowBody();return{type:"Arrow",params:r,body:i,isBlock:l}}return this.pos=e,null}return this.pos=e,null}tryParseParamList(){const e=[];if(this.isPunct(")"))return e;for(;;){const n=this.peek();let r=null,i;if(n&&n.type==="punct"&&n.value==="["){const c=this.tryParseArrayPattern();if(!c)return null;i=c}else if(n&&n.type==="ident"&&!oc.has(String(n.value)))r=String(n.value),this.pos+=1;else return null;let l=null;if(this.isPunct("=")&&(this.pos+=1,l=this.parseExpression()),e.push(i?{name:r,elements:i,default:l}:{name:r,default:l}),this.isPunct(",")){this.pos+=1;continue}break}return e}tryParseArrayPattern(){const e=this.pos;this.pos+=1;const n=[];for(;;){if(this.isPunct("]"))return this.pos+=1,n;if(this.isPunct(",")){n.push(null),this.pos+=1;continue}const r=this.peek();if(!r||r.type!=="ident"||oc.has(String(r.value)))return this.pos=e,null;if(n.push(String(r.value)),this.pos+=1,this.isPunct(",")){this.pos+=1;continue}return this.isPunct("]")?(this.pos+=1,n):(this.pos=e,null)}}parseArrowBody(){return this.isPunct("{")?{body:this.parseBlock(),isBlock:!0}:{body:this.parseExpression(),isBlock:!1}}parseBlock(){this.expectPunct("{");const e=[];for(;!this.isPunct("}");){if(this.atEnd())throw new Error("Unterminated block");e.push(this.parseStatement())}return this.expectPunct("}"),{type:"Block",body:e}}parseStatement(){const e=this.peek();if(!e)throw new Error("Unexpected end of statement");if(e.type==="punct"&&e.value==="{")return this.parseBlock();if(e.type==="punct"&&e.value===";")return this.pos+=1,{type:"Empty"};if(e.type==="ident")switch(String(e.value)){case"const":case"let":return this.parseVarDecl();case"if":return this.parseIf();case"for":return this.parseForOf();case"return":return this.parseReturn();case"try":return this.parseTry();case"break":return this.pos+=1,this.consumeSemicolon(),{type:"Break"};case"continue":return this.pos+=1,this.consumeSemicolon(),{type:"Continue"}}const n=this.parseExpression();return this.consumeSemicolon(),{type:"ExprStmt",expression:n}}consumeSemicolon(){this.isPunct(";")&&(this.pos+=1)}parseVarDecl(){this.pos+=1;const e=[];for(;;){const n=this.peek();if(!n||n.type!=="ident")throw new Error("Expected variable name in declaration");const r=String(n.value);this.pos+=1,this.expectPunct("=");const i=this.parseExpression();if(e.push({name:r,init:i}),this.isPunct(",")){this.pos+=1;continue}break}return this.consumeSemicolon(),{type:"VarDecl",declarations:e}}parseIf(){this.pos+=1,this.expectPunct("(");const e=this.parseExpression();this.expectPunct(")");const n=this.parseStatement();let r=null;const i=this.peek();return i&&i.type==="ident"&&i.value==="else"&&(this.pos+=1,r=this.parseStatement()),{type:"If",test:e,consequent:n,alternate:r}}parseForOf(){this.pos+=1,this.expectPunct("(");const e=this.peek();if(!e||e.type!=="ident"||e.value!=="const"&&e.value!=="let")throw new Error('Only "for (const x of …)" / "for (let x of …)" loops are supported');this.pos+=1;const n=this.peek();if(!n||n.type!=="ident")throw new Error("Expected loop variable name");const r=String(n.value);this.pos+=1;const i=this.peek();if(!i||i.type!=="ident"||i.value!=="of")throw new Error("Only for-of loops are supported (for-in / C-style for are not allowed)");this.pos+=1;const l=this.parseExpression();this.expectPunct(")");const c=this.parseStatement();return{type:"ForOf",name:r,iterable:l,body:c}}parseReturn(){if(this.pos+=1,this.isPunct(";")||this.isPunct("}")||this.atEnd())return this.consumeSemicolon(),{type:"Return",argument:null};const e=this.parseExpression();return this.consumeSemicolon(),{type:"Return",argument:e}}parseTry(){this.pos+=1;const e=this.parseBlock();let n=null,r=null,i=null;const l=this.peek();if(l&&l.type==="ident"&&l.value==="catch"){if(this.pos+=1,this.isPunct("(")){this.pos+=1;const d=this.peek();d&&d.type==="ident"&&(n=String(d.value),this.pos+=1),this.expectPunct(")")}r=this.parseBlock()}const c=this.peek();if(c&&c.type==="ident"&&c.value==="finally"&&(this.pos+=1,i=this.parseBlock()),!r&&!i)throw new Error("Missing catch or finally after try");return{type:"Try",block:e,handlerParam:n,handler:r,finalizer:i}}parseFunctionExpression(){this.pos+=1;let e=null;const n=this.peek();n&&n.type==="ident"&&n.value!==void 0&&!this.isPunct("(")&&(e=String(n.value),this.pos+=1),this.expectPunct("(");const r=this.tryParseParamList();if(!r)throw new Error("Invalid function parameter list");this.expectPunct(")");const i=this.parseBlock();return{type:"Function",name:e,params:r,body:i}}parseTernary(){const e=this.parseBinary(0);if(this.isPunct("?")){this.pos+=1;const n=this.parseExpression();this.expectPunct(":");const r=this.parseExpression();return{type:"Conditional",test:e,consequent:n,alternate:r}}return e}parseBinary(e){let n=this.parseUnary();for(;;){const r=this.peek();if(!r||r.type!=="punct")break;const i=String(r.value),l=I0[i];if(l===void 0||lim(l));return{type:"Template",quasis:n,expressions:i}}if(e.type==="ident"&&e.value==="new")return this.parseNew();if(e.type==="ident"&&e.value==="function")return this.parseFunctionExpression();if(e.type==="ident"){const n=String(e.value);if(oc.has(n))throw new Error(`Keyword "${n}" is not allowed`);switch(this.pos+=1,n){case"true":return{type:"Literal",value:!0};case"false":return{type:"Literal",value:!1};case"null":return{type:"Literal",value:null};case"undefined":return{type:"Literal",value:void 0};default:return{type:"Identifier",name:n}}}if(e.type==="punct"){if(e.value==="("){this.pos+=1;const n=this.parseExpression();return this.expectPunct(")"),n}if(e.value==="[")return this.parseArrayLiteral();if(e.value==="{")return this.parseObjectLiteral()}throw new Error(`Unexpected token "${e.value}"`)}parseArrayLiteral(){this.expectPunct("[");const e=[];for(;!this.isPunct("]");){if(this.isPunct(",")){this.pos+=1,e.push({type:"Literal",value:void 0});continue}if(this.isPunct("...")?(this.pos+=1,e.push({type:"Spread",argument:this.parseExpression()})):e.push(this.parseExpression()),this.isPunct(",")){this.pos+=1;continue}break}return this.expectPunct("]"),{type:"Array",elements:e}}parseObjectLiteral(){this.expectPunct("{");const e=[];for(;!this.isPunct("}");){if(this.isPunct("..."))this.pos+=1,e.push({kind:"spread",value:this.parseExpression()});else{let n,r=!1;const i=this.peek();if(!i)throw new Error("Unexpected end of expression in object literal");if(i.type==="punct"&&i.value==="[")this.pos+=1,n=this.parseExpression(),this.expectPunct("]"),r=!0;else if(i.type==="str")this.pos+=1,n={type:"Literal",value:i.value};else if(i.type==="num")this.pos+=1,n={type:"Literal",value:String(i.value)};else if(i.type==="ident")this.pos+=1,n={type:"Literal",value:String(i.value)};else throw new Error(`Unexpected token "${i.value}" in object literal`);if(this.isPunct(":")){this.pos+=1;const l=this.parseExpression();e.push({kind:"init",key:n,computed:r,value:l})}else{if(r||n.type!=="Literal"||typeof n.value!="string")throw new Error("Invalid shorthand property in object literal");if(i.type!=="ident")throw new Error("Invalid shorthand property in object literal");e.push({kind:"init",key:n,computed:!1,value:{type:"Identifier",name:n.value}})}}if(this.isPunct(",")){this.pos+=1;continue}break}return this.expectPunct("}"),{type:"Object",properties:e}}}function im(s){const e=N0(s),n=new H0(e),r=n.parseExpression();if(!n.atEnd()){const i=n.peek();throw i&&i.type==="punct"&&i.value===","?new Error("The comma/sequence operator is not allowed"):new Error(`Unexpected token "${i?i.value:""}" after expression`)}return r}function z0(s,e){let n=e;for(;n;){if(Object.prototype.hasOwnProperty.call(n.vars,s))return n.vars[s];n=n.parent}if(Object.prototype.hasOwnProperty.call(Xd,s))return Xd[s];if(D0.has(s))throw new Error(`Reference to forbidden global "${s}" is not allowed`)}function tf(s){const e=typeof s=="symbol"?s:String(s);if(typeof e=="string"&&So.has(e))throw new Error(`Access to "${e}" is forbidden`);return e}function nf(s,e){return s.type==="Member"?sm(s,e):s.type==="Call"?om(s,e):et(s,e)}function sm(s,e){const n=nf(s.object,e);if(n===_r||s.optional&&n==null)return _r;let r;s.computed?r=et(s.property,e):r=s.property.value;const i=tf(r);if(n!=null)return n[i]}function om(s,e){let n,r;if(s.callee.type==="Member"){const l=s.callee,c=nf(l.object,e);if(c===_r||l.optional&&c==null)return _r;let d;l.computed?d=et(l.property,e):d=l.property.value;const f=tf(d);c==null?n=void 0:(n=c[f],r=c)}else if(n=nf(s.callee,e),n===_r)return _r;if(s.optional&&n==null)return _r;if(typeof n!="function")throw new Error("Attempted to call a non-function value");const i=lm(s.args,e);return n.apply(r,i)}function lm(s,e){const n=[];for(const r of s)if(r.type==="Spread"){const i=et(r.argument,e);if(i!=null)for(const l of i)n.push(l)}else n.push(et(r,e));return n}function cm(s,e,n){for(let r=0;r":return n>r;case"<=":return n<=r;case">=":return n>=r;default:throw new Error(`Unknown binary operator "${s.operator}"`)}}case"Logical":{const n=et(s.left,e);switch(s.operator){case"&&":return n&&et(s.right,e);case"||":return n||et(s.right,e);case"??":return n??et(s.right,e);default:throw new Error(`Unknown logical operator "${s.operator}"`)}}case"Conditional":return et(s.test,e)?et(s.consequent,e):et(s.alternate,e);case"Array":{const n=[];for(const r of s.elements)if(r.type==="Spread"){const i=et(r.argument,e);if(i!=null)for(const l of i)n.push(l)}else n.push(et(r,e));return n}case"Object":{const n={};for(const r of s.properties)if(r.kind==="spread"){const i=et(r.value,e);if(i!=null&&typeof i=="object")for(const l of Object.keys(i))rf(n,l,i[l])}else{let i;r.computed?i=et(r.key,e):i=r.key.value;const l=et(r.value,e);rf(n,String(i),l)}return n}case"Arrow":{const n=e,r=s.params,i=s.body,l=s.isBlock;return function(...d){const f={vars:{},parent:n};return cm(r,d,f),l?um(i,f):et(i,f)}}case"Function":{const n=e,r=s.params,i=s.body,l=s.name,c=function(...f){const h={vars:{},parent:n};return l&&(h.vars[l]=c),cm(r,f,h),um(i,h)};return c}case"Delete":{const n=s.argument,r=et(n.object,e);let i;n.computed?i=et(n.property,e):i=n.property.value;const l=tf(i);if(r==null||typeof r!="object"&&typeof r!="function")return!0;if(rm.has(r))throw new Error("delete on a built-in global object is not allowed");return delete r[l]}case"Block":{const n={vars:{},parent:e};for(const r of s.body)et(r,n);return}case"VarDecl":{for(const n of s.declarations)e.vars[n.name]=et(n.init,e);return}case"If":{et(s.test,e)?et(s.consequent,e):s.alternate&&et(s.alternate,e);return}case"ForOf":{const n=et(s.iterable,e);if(n!=null)for(const r of n){const i={vars:{},parent:e};i.vars[s.name]=r;try{et(s.body,i)}catch(l){if(l instanceof ef)continue;if(l instanceof Zd)break;throw l}}return}case"Return":throw new Qd(s.argument?et(s.argument,e):void 0);case"ExprStmt":et(s.expression,e);return;case"Break":throw new Zd;case"Continue":throw new ef;case"Empty":return;case"Try":{try{try{et(s.block,e)}catch(n){if(n instanceof Qd||n instanceof Zd||n instanceof ef)throw n;if(s.handler){const r={vars:{},parent:e};s.handlerParam&&(r.vars[s.handlerParam]=n),et(s.handler,r)}else throw n}}finally{s.finalizer&&et(s.finalizer,e)}return}case"New":{const n=Jd[s.ctor];if(typeof n!="function")throw new Error("new on non-whitelisted constructor");const r=lm(s.args,e);return new n(...r)}case"Template":{let n=s.quasis[0]??"";for(let r=0;r0}getFromRenderCycleCache(e){if(this.isRenderCycleCacheActive())return this.renderCycleCache.get(e)}saveToRenderCycleCache(e,n){this.isRenderCycleCacheActive()&&this.renderCycleCache.set(e,n)}resolveBindings(e,n,r,i){const l={...this.defaultOptions,...r},c=wo(),d=n._computed&&!n.$computed?{...n,$computed:n._computed}:n,f=(v,S)=>{const _=S.trim();let x=!1,A=_;if(_.startsWith(sr)&&(x=!0,A=_.slice(sr.length)),Wn(A))try{const z=this.evaluatePipeExpression(A,d,l,{...i,method:"resolveBindings",displayExpression:`{{${_}}}`}),W=this.formatValue(z);return x?vo(W):W}catch(z){return Na.error("Pipe expression evaluation failed:",A,z),v}if(yo(A)){const z=c?.isEnabled()?performance.now():0;try{let W,de=!1;if(l.skipCache)W=this.evaluateExpression(A,d);else{const Se=`expr:${A}`,Ie=this.getFromRenderCycleCache(Se);Ie!==void 0?(W=Ie,de=!0):(W=this.evaluateExpression(A,d),this.saveToRenderCycleCache(Se,W))}if(c?.isEnabled()){const Se=performance.now()-z;c.trackExpressionEval({expression:`{{${_}}}`,result:this.sanitizeResultForTracking(W),resultType:this.getResultType(W),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:de,duration:Se,method:"resolveBindings",skipCache:l.skipCache})}const _e=this.formatValue(W);return x?vo(_e):_e}catch(W){return Na.error("Expression evaluation failed:",A,W),v}}if(l.skipCache){const z=c?.isEnabled()?performance.now():0,W=this.resolvePath(A,d,l);if(c?.isEnabled()){const _e=performance.now()-z;c.trackExpressionEval({expression:`{{${_}}}`,result:this.sanitizeResultForTracking(W),resultType:this.getResultType(W),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:_e,method:"resolveBindings",skipCache:!0})}const de=this.formatValue(W);return x?vo(de):de}const O=A.startsWith("_global")||A.startsWith("_local")||A.startsWith("_isolated")||A.startsWith("$parent"),k=c?.isEnabled()?performance.now():0;let L,B=!1;if(O){const z=this.getFromRenderCycleCache(A);z!==void 0?(L=z,B=!0):(L=this.resolvePath(A,d,l),this.saveToRenderCycleCache(A,L))}else{const z=this.getFromCache(A);z!==void 0?(L=z,B=!0):(L=this.resolvePath(A,d,l),this.saveToCache(A,L))}if(c?.isEnabled()){const z=performance.now()-k;c.trackExpressionEval({expression:`{{${_}}}`,result:this.sanitizeResultForTracking(L),resultType:this.getResultType(L),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:B,duration:z,method:"resolveBindings",skipCache:l.skipCache})}const q=this.formatValue(L);return x?vo(q):q},h=R0(e);if(h.length===0)return e;let m="",y=0;for(const v of h)m+=e.slice(y,v.start),m+=f(e.slice(v.start,v.end),v.expr),y=v.end;return m+e.slice(y)}evaluatePipeExpression(e,n,r,i){const l={...this.defaultOptions,...r},c=wo(),d=c?.isEnabled()?performance.now():0,f=n._computed&&!n.$computed?{...n,$computed:n._computed}:n,[h,m]=T0(e);let y,v=!1;const S=yo(h),_=h.startsWith("_global")||h.startsWith("_local")||h.startsWith("_isolated")||h.startsWith("$parent");if(l.skipCache)S?y=this.evaluateExpression(h,f):y=this.resolvePath(h,f,l);else if(S){const A=this.getFromRenderCycleCache(`expr:${h}`);A!==void 0?(y=A,v=!0):(y=this.evaluateExpression(h,f),this.saveToRenderCycleCache(`expr:${h}`,y))}else if(_){const A=this.getFromRenderCycleCache(h);A!==void 0?(y=A,v=!0):(y=this.resolvePath(h,f,l),this.saveToRenderCycleCache(h,y))}else{const A=this.getFromCache(h);A!==void 0?(y=A,v=!0):(y=this.resolvePath(h,f,l),this.saveToCache(h,y))}const x=k0(y,m);if(c?.isEnabled()){const A=performance.now()-d;c.trackExpressionEval({expression:i?.displayExpression??`{{${e}}}`,result:this.sanitizeResultForTracking(x),resultType:this.getResultType(x),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:v,duration:A,method:i?.method??"evaluatePipeExpression",skipCache:l.skipCache})}return x}resolve(e,n,r,i){const l={...this.defaultOptions,...r},c=wo(),d=c?.isEnabled()?performance.now():0;if(l.skipCache){const y=this.resolvePath(e,n,l);return c?.isEnabled()&&c.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()-d,method:"resolve",skipCache:!0}),y}const f=e.startsWith("_global")||e.startsWith("_local")||e.startsWith("_isolated")||e.startsWith("$parent");let h=!1;if(f){const y=this.getFromRenderCycleCache(e);if(y!==void 0)return h=!0,c?.isEnabled()&&c.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()-d,method:"resolve",skipCache:l.skipCache}),y}else{const y=this.getFromCache(e);if(y!==void 0)return h=!0,c?.isEnabled()&&c.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()-d,method:"resolve",skipCache:l.skipCache}),y}const m=this.resolvePath(e,n,l);return f?this.saveToRenderCycleCache(e,m):this.saveToCache(e,m),c?.isEnabled()&&c.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(m),resultType:this.getResultType(m),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:h,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),m}resolvePath(e,n,r,i=0,l=new WeakSet){if(typeof e!="string"||e.trim()===""){Na.warn("resolvePath: 빈 경로가 전달되었습니다 — undefined 로 해석합니다.");return}if(r.maxDepth&&i>r.maxDepth){if(r.detectCircular)throw new sf(`Maximum depth exceeded (${r.maxDepth}). Possible circular reference.`,e,n);return r.defaultValue}const c=this.parsePath(e);let d=n;for(let f=0;fca.CACHE_EXPIRY){this.cache.delete(e),r?.isEnabled()&&r.recordCacheMiss();return}return r?.isEnabled()&&r.recordCacheHit(),n.value}saveToCache(e,n){this.cache.set(e,{value:n,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,n,r){if(this.isSwitchExpression(e)){const d=e;return this.resolveSwitch(d,n,r)}if(this.isActionDefinition(e))return{...e};if("iteration"in e)return{...e};const i={},c=[...["cellChildren","expandChildren","expandContext","render"],...r?.skipBindingKeys||[]];for(const[d,f]of Object.entries(e)){if(c.includes(d)){i[d]=f;continue}try{this.resolveObjectEntry(i,d,f,n,r)}catch(h){Na.warn(`resolveObject: 값 해석 실패 (key: ${d}):`,h),i[d]=void 0}}return i}resolveObjectEntry(e,n,r,i,l){if(typeof r=="string"){const c=La(r);if(c!==null){const d=c.trim();let f=!1,h=d;d.startsWith(sr)&&(f=!0,h=d.slice(sr.length));let m;switch(em(h)){case"empty":Na.warn(`resolveObject: 빈 바인딩 \`{{}}\` (key: ${n}) — undefined 로 해석합니다.`),m=void 0;break;case"literal":m=Kd.get(h);break;case"pipe":m=this.evaluatePipeExpression(h,i,l);break;case"expression":m=this.evaluateExpression(h,i,l);break;default:m=this.resolve(h,i,l)}e[n]=f&&m!=null?ds(m):m}else e[n]=this.resolveBindings(r,i,l)}else Array.isArray(r)?e[n]=r.map(c=>typeof c=="string"?this.resolveBindings(c,i,l):typeof c=="object"&&c!==null?this.resolveObject(c,i,l):c):r&&typeof r=="object"?e[n]=this.resolveObject(r,i,l):e[n]=r}clearCache(){this.cache.clear()}invalidateCacheByKeys(e){for(const n of this.cache.keys())for(const r of e)if(n===r||n.startsWith(`${r}.`)||n.startsWith(`${r}[`)){this.cache.delete(n);break}}pruneCache(){const e=Date.now();for(const[n,r]of this.cache.entries())e-r.timestamp>ca.CACHE_EXPIRY&&this.cache.delete(n)}getCacheStats(){const e=Date.now();let n=0;for(const r of this.cache.values())e-r.timestamp>ca.CACHE_EXPIRY&&n++;return{size:this.cache.size,expired:n}}evaluateExpression(e,n,r){const i=wo(),l=i?.isEnabled()?performance.now():0;i?.isEnabled()&&i.trackBindingEval();try{let c=this.preprocessOptionalChaining(e);c=this.preprocessTranslationTokens(c);const d=this.extractVariablesFromExpression(c),f={...n};for(const A of d)A in f||(f[A]=void 0);n._computed&&!f.$computed&&(f.$computed=n._computed);let h=n.$templateId,m=n.$locale;if(typeof window<"u"&&(!h||!m)){const A=window.__templateApp?.getConfig?.();h??(h=A?.templateId),m??(m=A?.locale)}const y=m||"ko";f.$localized=(A,D)=>{if(A==null&&!D)return"";if(typeof A=="string")return A;if(A&&typeof A=="object"&&A[y])return A[y];if(D&&typeof D=="string"){const O=f.$t?f.$t(D):D;if(O&&O!==D)return O}return A&&typeof A=="object"?A.ko||A.en||Object.values(A)[0]||"":A==null?"":String(A)};const v=typeof window<"u"?window.G7Core:void 0;f.$uuid=()=>v?.uuid?v.uuid():typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,A=>{const D=Math.random()*16|0;return(A==="x"?D:D&3|8).toString(16)});const S={templateId:h||"",locale:y};f.$t=A=>{if(!A||typeof A!="string")return"";try{return Oa.getInstance().translate(A,S)}catch(D){return Na.warn("$t() translation failed for key:",A,D),A}},f.$get=(A,D,O=void 0)=>{if(A==null)return O;const k=Array.isArray(D)?D:[D];if(k.length===0)return A;let L=A;for(const B of k){if(L==null||B==null)return O;L=L[B]}return L??O};const _=!1,x=af(c,f);if(i?.isEnabled()){const A=performance.now()-l;i.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(x),resultType:this.getResultType(x),componentId:r?.componentId,componentName:r?.componentName,propName:r?.propName,fromCache:_,duration:A,method:"evaluateExpression",skipCache:r?.skipCache})}return x}catch(c){throw new Error(`Failed to evaluate expression "${e}": ${c instanceof Error?c.message:String(c)}`)}}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 n=Object.keys(e);return n.length>20?`{Object(${n.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,(n,r,i,l)=>`$t('${l}')`),e.replace(/(['"]\s*)?(\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*)(?!\s*['"])/g,(n,r,i)=>r?n:`"${i}"`)}preprocessOptionalChaining(e){const n=[];let r=e.replace(/(['"])(?:(?!\1|\\).|\\.)*\1/g,l=>(n.push(l),`__STRING_LITERAL_${n.length-1}__`));const i=[];return r=r.replace(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*(?:\|[^'"\s,)]+)?/g,l=>(i.push(l),`__TRANSLATION_TOKEN_${i.length-1}__`)),r=r.replace(/([a-zA-Z_$][a-zA-Z0-9_$]*)\.(?!\?)/g,"$1?."),r=r.replace(/__TRANSLATION_TOKEN_(\d+)__/g,(l,c)=>i[parseInt(c,10)]),r=r.replace(/__STRING_LITERAL_(\d+)__/g,(l,c)=>n[parseInt(c,10)]),r}extractVariablesFromExpression(e){const n=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","Set","Map","WeakSet","WeakMap","Symbol","Promise","BigInt","Error","parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent"]),r=/(^|[^.\w$])([a-zA-Z_$][a-zA-Z0-9_$]*)/g,i=new Set;let l;for(;(l=r.exec(e))!==null;){const c=l[2];n.has(c)||i.add(c)}return Array.from(i)}isSwitchExpression(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"$switch"in e&&"$cases"in e}resolveSwitch(e,n,r){const i={...r,skipCache:!0};let l;try{l=this.resolveBindings(e.$switch,n,i)?.toString()?.trim()??""}catch(d){Na.warn("resolveSwitch: $switch 키 평가 실패:",e.$switch,d),l=""}let c;if(l&&e.$cases&&l in e.$cases)c=e.$cases[l];else if("$default"in e)c=e.$default;else return;return typeof c=="string"?c.includes("{{")?this.resolveBindings(c,n,i):c:c!==null&&typeof c=="object"?this.resolveObject(c,n,i):c}};M(ca,"PATH_SEGMENT_PATTERN",/([^.[\]]+)|\[(\d+)\]/g),M(ca,"CACHE_EXPIRY",3e4);let $n=ca;const of=new $n,lc={mobile:{min:0,max:767},tablet:{min:768,max:1023},desktop:{min:1024,max:1/0},portable:{min:0,max:1023}},cc=new Map;function P0(s,e){let n=null;return((...r)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{s(...r)},e)})}class U0{constructor(){M(this,"subscribers",new Set);M(this,"currentWidth",1024);M(this,"debouncedHandler",null);M(this,"isInitialized",!1);this.initialize()}initialize(){typeof window>"u"||(this.currentWidth=window.innerWidth,this.isInitialized=!0,this.debouncedHandler=P0(()=>{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(cc.has(e))return cc.get(e)??null;let n=null;if(lc[e])n={...lc[e]};else{const r=e.match(/^(-?\d*)-(-?\d*)$/);if(r){const[,i,l]=r,c=i===""?0:parseInt(i,10),d=l===""?1/0:parseInt(l,10);!isNaN(c)&&!isNaN(d)&&c<=d&&(n={min:c,max:d})}}return cc.set(e,n),n}getMatchingKey(e,n){const r=[];for(const i of Object.keys(e)){const l=this.parseRange(i);l&&n>=l.min&&n<=l.max&&r.push({key:i,range:l,isPreset:!!lc[i]})}return r.length===0?null:(r.sort((i,l)=>{if(i.isPreset!==l.isPreset)return i.isPreset?1:-1;const c=i.range.max-i.range.min,d=l.range.max-l.range.min;return c-d}),r[0].key)}matches(e){const n=this.parseRange(e);return n?this.currentWidth>=n.min&&this.currentWidth<=n.max:!1}clearSubscribers(){this.subscribers.clear()}destroy(){this.debouncedHandler&&typeof window<"u"&&window.removeEventListener("resize",this.debouncedHandler),this.clearSubscribers(),cc.clear()}_setWidthForTesting(e){this.currentWidth=e,this.notifySubscribers()}}const Ci=new U0,Co=pt("ConditionEvaluator");function B0(s,e,n,r){return Wd(tm(s),e,n,{skipCache:!0,onEmpty:()=>{Co.warn(`${r}: 빈 바인딩 \`{{}}\` — undefined 로 해석합니다.`)}})}function dm(s,e,n){if(!s)return!0;try{const r=La(s);let i;if(r!==null?i=B0(r,e,n,"evaluateStringCondition"):i=n.resolveBindings(s,e,{skipCache:!0}),typeof i=="string"){const l=i.toLowerCase().trim();if(l==="false"||l==="0"||l===""||l==="null"||l==="undefined")return!1}return!!i}catch(r){return Co.warn(`evaluateStringCondition: 조건 평가 실패: ${s}`,r),!1}}function uc(s,e,n){if(typeof s=="string")return dm(s,e,n);if("and"in s){if(!Array.isArray(s.and)||s.and.length===0)return Co.warn("evaluateConditionExpression: AND 그룹이 비어있습니다"),!0;for(const r of s.and)if(!uc(r,e,n))return!1;return!0}if("or"in s){if(!Array.isArray(s.or)||s.or.length===0)return Co.warn("evaluateConditionExpression: OR 그룹이 비어있습니다"),!1;for(const r of s.or)if(uc(r,e,n))return!0;return!1}return Co.warn("evaluateConditionExpression: 알 수 없는 조건 형식",s),!1}function fm(s,e,n){if(!Array.isArray(s)||s.length===0)return{matched:!1,branchIndex:-1};for(let r=0;r{or.warn(`evaluateIfCondition: 빈 바인딩 \`{{}}\` (컴포넌트: ${r||"unknown"}) — undefined 로 해석합니다.`)}}):l=n.resolveBindings(s,e,{skipCache:!0}),typeof l=="string"){const c=l.toLowerCase().trim();if(c==="false"||c==="0"||c===""||c==="null"||c==="undefined")return!1}return!!l}catch(i){return or.warn(`evaluateIfCondition: 조건 평가 실패 (컴포넌트: ${r||"unknown"}):`,i),!1}}function fs(s,e,n,r){if(s.if!==void 0)return mm(s.if,e,n,r);if(s.condition!==void 0)return mm(s.condition,e,n,r);if(s.conditions===void 0)return!0;const i=s.conditions;try{return q0(i)?uc(i,e,n):G0(i)?fm(i,e,n).matched:(or.warn(`evaluateRenderCondition: 알 수 없는 conditions 형식 (컴포넌트: ${r||"unknown"})`),!0)}catch(l){return or.warn(`evaluateRenderCondition: conditions 평가 실패 (컴포넌트: ${r||"unknown"}):`,l),!1}}function ym(s){if(!s.responsive)return s;const e=Ci.getWidth(),n=Ci.getMatchingKey(s.responsive,e);if(!n)return s;const r=s.responsive[n];return{...s,props:{...s.props,...r.props},children:r.children??s.children,text:r.text??s.text,if:r.if??s.if,iteration:r.iteration??s.iteration}}function Eo(s,e,n,r,i){if(!s||s.length===0)return[];const l=i?.bindingEngine??new $n,c=i?.translationEngine??Oa.getInstance(),d=i?.translationContext??{templateId:"",locale:"ko"},f=V0(e,i?.componentContext),h=(S,_)=>{if(typeof S=="string")return ic(S)||sc(S)||!/\$t:[a-zA-Z0-9._-]+/.test(S)?S:c.resolveTranslations(S,d,_);if(Array.isArray(S))return S.map(x=>h(x,_));if(S&&typeof S=="object"){const x={};for(const[A,D]of Object.entries(S))x[A]=h(D,_);return x}return S},m=(S,_)=>{if(typeof S=="string"){if(ic(S))return Yd(S);if(sc(S)){const A=[],D=S.replace(new RegExp(`${bo}([^${Si}]*)${Si}`,"g"),(k,L)=>(A.push(L),`${$a}${A.length-1}${$a}`));let O=D;return/\$t:[a-zA-Z0-9._-]+/.test(D)&&(O=c.resolveTranslations(D,d,_)),O.replace(new RegExp(`${$a}(\\d+)${$a}`,"g"),(k,L)=>A[parseInt(L)])}if(S.startsWith("$t:defer:")){const A="$t:"+S.slice(9);return c.resolveTranslations(A,d,_)}if(S.startsWith("$t:"))return c.resolveTranslations(S,d,_);if(/\$t:[a-zA-Z0-9._-]+/.test(S)){const A=S.trim();if(!(A.startsWith("{")&&A.endsWith("}")||A.startsWith("[")&&A.endsWith("]"))&&!S.includes("{{"))return c.resolveTranslations(S,d,_)}const x=gm(S);if(x!==null){let A=!1,D=x;x.startsWith(sr)&&(A=!0,D=x.slice(sr.length));let O=!1,k=Wd(D,_,l,{skipCache:!0,onError:L=>{or.warn("renderItemChildren: 표현식 평가 실패:",L),O=!0},onEmpty:()=>{or.warn("renderItemChildren: 빈 바인딩 `{{}}` 은 해석하지 않습니다.")}});return O?void 0:(A||(k=h(k,_)),A&&k!=null?ds(k):k)}if(S.includes("{{")){const A=l.resolveBindings(S,_,{skipCache:!0});return typeof A=="string"&&/\$t:[a-zA-Z0-9._-]+/.test(A)?c.resolveTranslations(A,d,_):A}return S}if(Array.isArray(S))return S.map(x=>m(x,_));if(S&&typeof S=="object"){if(l.isSwitchExpression(S))return l.resolveSwitch(S,_,{skipCache:!0});if(l.isActionDefinition(S))return{...S};const x={};for(const[A,D]of Object.entries(S))x[A]=m(D,_);return x}return S},y=(S,_)=>{if(!S)return{};const x={};for(const[A,D]of Object.entries(S))x[A]=m(D,_);return x},v=(S,_,x)=>{const A=ym(S),D=A.iteration;if(!D)return[];const O=lf(D.source,x,l);if(!Array.isArray(O))return or.warn(`renderItemChildren: iteration.source가 배열이 아닙니다: ${D.source}`),[];const k=hm();if(k?.isEnabled()){const B=`${_}-iteration`;k.trackIteration(B,D.source,D.item_var,D.index_var,O.length)}const L=n[A.name];return L?O.flatMap((B,q)=>{const z={...x,[D.item_var]:B,[`${D.item_var}_index`]:q,...D.index_var?{[D.index_var]:q}:{}},W=fs({if:A.if,condition:A.condition,conditions:A.conditions},z,l,A.id);if(A.if&&k?.isEnabled()){const Et=`${_}-iter-${q}-if`;k.trackIfCondition(Et,A.if,W,A.name)}if(!W)return[];const de=A.id?String(Ma(m(A.id,z))):void 0,_e=`${_}-iter-${q}`,Se=i?.getRemountKey?i.getRemountKey(de,_e):_e,Ie=y(A.props,z),Fe=cf(Ie,A.actions,z,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let ze=null;return A.text!==void 0?ze=m(A.text,z):A.children&&A.children.length>0&&(ze=Eo(A.children,z,n,Se,i)),k?.isEnabled()&&k.trackRender(A.name),[Xe.createElement(L,{key:Se,...Ma(Fe)},Ma(ze))]}):(or.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${A.name}`),[])};return s.flatMap((S,_)=>{const x=ym(S),A=x.id?String(Ma(m(x.id,f))):void 0,D=r?`${r}-${A||_}`:A||`child-${_}`,O=i?.getRemountKey?i.getRemountKey(A,D):D;if(x.iteration)return v(x,O,f);const k=fs({if:x.if,condition:x.condition,conditions:x.conditions},f,l,x.id),L=hm();if(x.if&&L?.isEnabled()){const de=`${O}-if`;L.trackIfCondition(de,x.if,k,x.name)}if(!k)return[];const B=n[x.name];if(!B)return or.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${x.name}`),[];const q=y(x.props,f),z=cf(q,x.actions,f,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let W=null;return x.text!==void 0?W=m(x.text,f):x.children&&x.children.length>0&&(W=Eo(x.children,f,n,O,i)),L?.isEnabled()&&L.trackRender(x.name),[Xe.createElement(B,{key:O,...Ma(z)},Ma(W))]})}function hs(s,e,n,r){let i,l;return n instanceof $n?(i=n,l=r):(i=pm,l=n),i.resolveBindings(s,e,l)}function K0(s,e,n,r){const i=n??pm,l={skipCache:!0,...r};let c;try{c=i.resolveBindings(s.key,e,{skipCache:l.skipCache})?.toString()?.trim()??""}catch(h){or.warn("resolveClassMap: key 평가 실패:",s.key,h),c=""}let d="";c&&s.variants&&c in s.variants?d=s.variants[c]:s.default&&(d=s.default);const f=[];return s.base?.trim()&&f.push(s.base.trim()),d?.trim()&&f.push(d.trim()),f.join(" ")}function bm(s,e){return function(){return s.apply(e,arguments)}}const{toString:W0}=Object.prototype,{getPrototypeOf:Ia}=Object,{iterator:_o,toStringTag:vm}=Symbol,Ao=(({hasOwnProperty:s})=>(e,n)=>s.call(e,n))(Object.prototype),Sm=s=>typeof s=="string"&&(s==="__proto__"||s==="constructor"||s==="prototype"),wm=(s,e,n)=>s===Object.prototype||!n&&e===null,Y0=s=>{if(!Object.isExtensible(s))return!1;const e=Object.getOwnPropertyNames(s);return Object.getOwnPropertySymbols&&e.push(...Object.getOwnPropertySymbols(s)),e.every(n=>{if(Sm(n))return!1;const r=Object.getOwnPropertyDescriptor(s,n);return!!r&&r.configurable&&r.writable===!0})},xo=(s,e)=>{let n=s;const r=[];for(;n!=null;){if(r.indexOf(n)!==-1)return!1;r.push(n);const i=Ia(n);if(wm(n,i,n===s))return!1;if(Ao(n,e))return!0;n=i}return!1},X0=(s,e)=>s!=null&&xo(s,e)?s[e]:void 0,J0=s=>{if(s==null||typeof s!="object"&&typeof s!="function")return s;const e=Ia(s);if(e===null&&Y0(s))return s;const n=Object.create(null),r=Object.create(null),i=[];let l=s;for(;l!=null&&i.indexOf(l)===-1;){i.push(l);const c=l===s?e:Ia(l);if(wm(l,c,l===s))break;const d=Object.getOwnPropertyNames(l);Object.getOwnPropertySymbols&&d.push(...Object.getOwnPropertySymbols(l));for(const f of d)Sm(f)||Ao(r,f)||(n[f]=s[f],r[f]=!0);l=c}return n},uf=(s=>e=>{const n=W0.call(e);return s[n]||(s[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),lr=s=>(s=s.toLowerCase(),e=>uf(e)===s),dc=s=>e=>typeof e===s,{isArray:Ei}=Array,_i=dc("undefined");function ps(s){return s!==null&&!_i(s)&&s.constructor!==null&&!_i(s.constructor)&&jn(s.constructor.isBuffer)&&s.constructor.isBuffer(s)}const Cm=lr("ArrayBuffer");function Q0(s){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(s):e=s&&s.buffer&&Cm(s.buffer),e}const Z0=dc("string"),jn=dc("function"),Em=dc("number"),gs=s=>s!==null&&typeof s=="object",eC=s=>s===!0||s===!1,fc=s=>{if(!gs(s))return!1;const e=Ia(s);return(e===null||e===Object.prototype||Ia(e)===null)&&!xo(s,vm)&&!xo(s,_o)},tC=s=>{if(!gs(s)||ps(s))return!1;try{return Object.keys(s).length===0&&Object.getPrototypeOf(s)===Object.prototype}catch{return!1}},nC=lr("Date"),rC=lr("File"),aC=s=>!!(s&&typeof s.uri<"u"),iC=s=>s&&typeof s.getParts<"u",sC=lr("Blob"),oC=lr("FileList"),lC=lr("Set"),cC=s=>gs(s)&&jn(s.pipe);function uC(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}const _m=uC(),Am=typeof _m.FormData<"u"?_m.FormData:void 0,dC=s=>{if(!s)return!1;if(Am&&s instanceof Am)return!0;const e=Ia(s);if(!e||e===Object.prototype||!jn(s.append))return!1;const n=uf(s);return n==="formdata"||n==="object"&&jn(s.toString)&&s.toString()==="[object FormData]"},fC=lr("URLSearchParams"),[hC,pC,gC,mC]=["ReadableStream","Request","Response","Headers"].map(lr),yC=s=>s.trim?s.trim():s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function To(s,e,{allOwnKeys:n=!1}={}){if(s===null||typeof s>"u")return;let r,i;if(typeof s!="object"&&(s=[s]),Ei(s))for(r=0,i=s.length;r0;)if(i=n[r],e===i.toLowerCase())return i;return null}const Ai=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Tm=s=>!_i(s)&&s!==Ai;function df(...s){const{caseless:e,skipUndefined:n}=Tm(this)&&this||{},r={},i=(l,c)=>{if(c==="__proto__"||c==="constructor"||c==="prototype")return;const d=e&&typeof c=="string"&&xm(r,c)||c,f=Ao(r,d)?r[d]:void 0;fc(f)&&fc(l)?r[d]=df(f,l):fc(l)?r[d]=df({},l):Ei(l)?r[d]=l.slice():(!n||!_i(l))&&(r[d]=l)};for(let l=0,c=s.length;l(To(e,(i,l)=>{n&&jn(i)?Object.defineProperty(s,l,{__proto__:null,value:bm(i,n),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(s,l,{__proto__:null,value:i,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:r}),s),vC=s=>(s.charCodeAt(0)===65279&&(s=s.slice(1)),s),SC=(s,e,n,r)=>{s.prototype=Object.create(e.prototype,r),Object.defineProperty(s.prototype,"constructor",{__proto__:null,value:s,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(s,"super",{__proto__:null,value:e.prototype}),n&&Object.assign(s.prototype,n)},wC=(s,e,n,r)=>{let i,l,c;const d={};if(e=e||{},s==null)return e;do{for(i=Object.getOwnPropertyNames(s),l=i.length;l-- >0;)c=i[l],(!r||r(c,s,e))&&!d[c]&&(e[c]=s[c],d[c]=!0);s=n!==!1&&Ia(s)}while(s&&(!n||n(s,e))&&s!==Object.prototype);return e},CC=(s,e,n)=>{s=String(s),(n===void 0||n>s.length)&&(n=s.length),n-=e.length;const r=s.indexOf(e,n);return r!==-1&&r===n},EC=s=>{if(!s)return null;if(Ei(s))return s;let e=s.length;if(!Em(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=s[e];return n},_C=(s=>e=>s&&e instanceof s)(typeof Uint8Array<"u"&&Ia(Uint8Array)),AC=(s,e)=>{const r=(s&&s[_o]).call(s);let i;for(;(i=r.next())&&!i.done;){const l=i.value;e.call(s,l[0],l[1])}},xC=(s,e)=>{let n;const r=[];for(;(n=s.exec(e))!==null;)r.push(n);return r},TC=lr("HTMLFormElement"),kC=s=>s.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,i){return r.toUpperCase()+i}),{propertyIsEnumerable:RC}=Object.prototype,DC=lr("RegExp"),km=(s,e)=>{const n=Object.getOwnPropertyDescriptors(s),r={};To(n,(i,l)=>{let c;(c=e(i,l,s))!==!1&&(r[l]=c||i)}),Object.defineProperties(s,r)},OC=s=>{km(s,(e,n)=>{if(jn(s)&&["arguments","caller","callee"].includes(n))return!1;const r=s[n];if(jn(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},LC=(s,e)=>{const n={},r=i=>{i.forEach(l=>{n[l]=!0})};return Ei(s)?r(s):r(String(s).split(e)),n},$C=()=>{},MC=(s,e)=>s!=null&&Number.isFinite(s=+s)?s:e;function NC(s){return!!(s&&jn(s.append)&&s[vm]==="FormData"&&s[_o])}const IC=s=>{const e=new WeakSet,n=r=>{if(gs(r)){if(e.has(r))return;if(ps(r))return r;if(!("toJSON"in r)){e.add(r);let i;if(lC(r)){i=[];for(const l of r){const c=n(l);!_i(c)&&i.push(c)}}else i=Ei(r)?[]:{},To(r,(l,c)=>{const d=n(l);!_i(d)&&(i[c]=d)});return e.delete(r),i}}return r};return n(s)},jC=lr("AsyncFunction"),HC=s=>s&&(gs(s)||jn(s))&&jn(s.then)&&jn(s.catch),Rm=((s,e)=>s?setImmediate:e?((n,r)=>(Ai.addEventListener("message",({source:i,data:l})=>{i===Ai&&l===n&&r.length&&r.shift()()},!1),i=>{r.push(i),Ai.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",jn(Ai.postMessage)),zC=typeof queueMicrotask<"u"?queueMicrotask.bind(Ai):typeof process<"u"&&process.nextTick||Rm,Dm=s=>s!=null&&jn(s[_o]),G={isArray:Ei,isArrayBuffer:Cm,isBuffer:ps,isFormData:dC,isArrayBufferView:Q0,isString:Z0,isNumber:Em,isBoolean:eC,isObject:gs,isPlainObject:fc,isEmptyObject:tC,isReadableStream:hC,isRequest:pC,isResponse:gC,isHeaders:mC,isUndefined:_i,isDate:nC,isFile:rC,isReactNativeBlob:aC,isReactNative:iC,isBlob:sC,isRegExp:DC,isFunction:jn,isStream:cC,isURLSearchParams:fC,isTypedArray:_C,isFileList:oC,forEach:To,merge:df,extend:bC,trim:yC,stripBOM:vC,inherits:SC,toFlatObject:wC,kindOf:uf,kindOfTest:lr,endsWith:CC,toArray:EC,forEachEntry:AC,matchAll:xC,isHTMLForm:TC,hasOwnProperty:Ao,hasOwnProp:Ao,hasOwnInPrototypeChain:xo,getSafeProp:X0,toSafeFlatObject:J0,reduceDescriptors:km,freezeMethods:OC,toObjectSet:LC,toCamelCase:kC,noop:$C,toFiniteNumber:MC,findKey:xm,global:Ai,isContextDefined:Tm,isSpecCompliantForm:NC,toJSONObject:IC,isAsyncFn:jC,isThenable:HC,setImmediate:Rm,asap:zC,isIterable:Dm,isSafeIterable:s=>s!=null&&xo(s,_o)&&Dm(s)},PC=G.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"]),UC=s=>{const e={};let n,r,i;return s&&s.split(` -`).forEach(function(c){i=c.indexOf(":"),n=c.substring(0,i).trim().toLowerCase(),r=c.substring(i+1).trim();const d=G.hasOwnProp(e,n);!n||d&&G.hasOwnProp(PC,n)||(n==="set-cookie"?d?e[n].push(r):e[n]=[r]:e[n]=d?e[n]+", "+r:r)}),e};function BC(s){let e=0,n=s.length;for(;ee;){const r=s.charCodeAt(n-1);if(r!==9&&r!==32)break;n-=1}return e===0&&n===s.length?s:s.slice(e,n)}const qC=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),GC=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function ff(s,e){return G.isArray(s)?s.map(n=>ff(n,e)):BC(String(s).replace(e,""))}const FC=s=>ff(s,qC),VC=s=>ff(s,GC);function Om(s){const e=Object.create(null);return G.forEach(s.toJSON(),(n,r)=>{e[r]=VC(n)}),e}const Lm=Symbol("internals");function ko(s){return s&&String(s).trim().toLowerCase()}function hc(s){return s===!1||s==null?s:G.isArray(s)?s.map(hc):FC(String(s))}function KC(s){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(s);)e[r[1]]=r[2];return e}const WC=/^[!#$%&'*+\-.^_`|~0-9A-Za-z]+$/;function hf(s){let e=0,n=s.length;for(;ee;){const r=s.charCodeAt(n-1);if(r!==9&&r!==32)break;n-=1}return e===0&&n===s.length?s:s.slice(e,n)}function YC(s){const e=s.length-1;if(e<1||s.charCodeAt(0)!==34||s.charCodeAt(e)!==34)return s;let n="";for(let r=1;r=e))return s;n+=s[r]}return n}function XC(s){const e=Object.create(null),n=String(s);let r=0,i=!1,l=!1;function c(d){const f=hf(n.slice(r,d)),h=f.indexOf("=");if(h<1)return;const m=hf(f.slice(0,h));if(!WC.test(m))return;const y=m.toLowerCase();if(y==="__proto__"||y==="constructor"||y==="prototype")return;const v=hf(f.slice(h+1));e[y]=YC(v)}for(let d=0;d/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(s.trim());function pf(s,e,n,r,i){if(G.isFunction(r))return r.call(this,e,n);if(i&&(e=n),!!G.isString(e)){if(G.isString(r))return e.indexOf(r)!==-1;if(G.isRegExp(r))return r.test(e)}}function QC(s){return s.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function ZC(s,e){const n=G.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(s,r+n,{__proto__:null,value:function(i,l,c){return this[r].call(this,e,i,l,c)},configurable:!0})})}let xn=class{constructor(e){e&&this.set(e)}set(e,n,r){const i=this;function l(d,f,h){const m=ko(f);if(!m)return;const y=G.findKey(i,m);(!y||i[y]===void 0||h===!0||h===void 0&&i[y]!==!1)&&(i[y||f]=hc(d))}const c=(d,f)=>G.forEach(d,(h,m)=>l(h,m,f));if(G.isPlainObject(e)||e instanceof this.constructor)c(e,n);else if(G.isString(e)&&(e=e.trim())&&!JC(e))c(UC(e),n);else if(G.isObject(e)&&G.isSafeIterable(e)){let d=Object.create(null),f,h;for(const m of e){if(!G.isArray(m))throw new TypeError("Object iterator must return a key-value pair");h=m[0],G.hasOwnProp(d,h)?(f=d[h],d[h]=G.isArray(f)?[...f,m[1]]:[f,m[1]]):d[h]=m[1]}c(d,n)}else e!=null&&l(n,e,r);return this}get(e,n){if(e=ko(e),e){const r=G.findKey(this,e);if(r){const i=this[r];if(!n)return i;if(n===!0)return KC(i);if(G.isFunction(n))return n.call(this,i,r);if(G.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=ko(e),e){const r=G.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||pf(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let i=!1;function l(c){if(c=ko(c),c){const d=G.findKey(r,c);d&&(!n||pf(r,r[d],d,n))&&(delete r[d],i=!0)}}return G.isArray(e)?e.forEach(l):l(e),i}clear(e){const n=Object.keys(this);let r=n.length,i=!1;for(;r--;){const l=n[r];(!e||pf(this,this[l],l,e,!0))&&(delete this[l],i=!0)}return i}normalize(e){const n=this,r={};return G.forEach(this,(i,l)=>{const c=G.findKey(r,l);if(c){n[c]=hc(i),delete n[l];return}const d=e?QC(l):String(l).trim();d!==l&&delete n[l],n[d]=hc(i),r[d]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return G.forEach(this,(r,i)=>{r!=null&&r!==!1&&(n[i]=e&&G.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).join(` -`)}getSetCookie(){const e=this.get("set-cookie");return G.isArray(e)?e:e==null||e===!1?[]:[e]}get[Symbol.toStringTag](){return"AxiosHeaders"}static from(e){return e instanceof this?e:new this(e)}static parseParameters(e){return XC(e)}static concat(e,...n){const r=new this(e);return n.forEach(i=>r.set(i)),r}static accessor(e){const r=(this[Lm]=this[Lm]={accessors:{}}).accessors,i=this.prototype;function l(c){const d=ko(c);r[d]||(ZC(i,c),r[d]=!0)}return G.isArray(e)?e.forEach(l):l(e),this}};xn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),G.reduceDescriptors(xn.prototype,({value:s},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>s,set(r){this[n]=r}}}),G.freezeMethods(xn);const pc="[REDACTED ****]";function eE(s){if(G.hasOwnProp(s,"toJSON"))return!0;let e=Object.getPrototypeOf(s);for(;e&&e!==Object.prototype;){if(G.hasOwnProp(e,"toJSON"))return!0;e=Object.getPrototypeOf(e)}return!1}function tE(s,e){const n=new Set(e.map(l=>String(l).toLowerCase())),r=[],i=l=>{if(l===null||typeof l!="object"||G.isBuffer(l))return l;if(r.indexOf(l)!==-1)return;l instanceof xn&&(l=l.toJSON()),r.push(l);let c;if(G.isArray(l))c=[],l.forEach((d,f)=>{const h=i(d);G.isUndefined(h)||(c[f]=h)});else{if(!G.isPlainObject(l)&&eE(l))return r.pop(),l;c=Object.create(null);for(const[d,f]of Object.entries(l)){const h=n.has(d.toLowerCase())?pc:i(f);G.isUndefined(h)||(c[d]=h)}}return r.pop(),c};return i(s)}function $m(s){try{return String(s)}catch{return""}}function nE(s){return s.errors.map(n=>{try{return n&&n.message?$m(n.message):$m(n)}catch{return""}}).filter(Boolean).join("; ")||s.name||"AggregateError"}let we=class n0 extends Error{static from(e,n,r,i,l,c){let d=e.message;!d&&G.isArray(e.errors)&&e.errors.length&&(d=nE(e));const f=new n0(d,n||e.code,r,i,l);return Object.defineProperty(f,"cause",{__proto__:null,value:e,writable:!0,enumerable:!1,configurable:!0}),f.name=e.name,e.status!=null&&f.status==null&&(f.status=e.status),c&&Object.assign(f,c),f}constructor(e,n,r,i,l){super(e),Object.defineProperty(this,"message",{__proto__:null,value:e,enumerable:!0,writable:!0,configurable:!0}),this.name="AxiosError",this.isAxiosError=!0,n&&(this.code=n),r&&(this.config=r),i&&(this.request=i),l&&(this.response=l,this.status=l.status)}toJSON(){const e=this.config,n=e&&G.hasOwnProp(e,"redact")?e.redact:void 0,r=G.isArray(n)&&n.length>0?tE(e,n):G.toJSONObject(e);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:r,code:this.code,status:this.status}}};we.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",we.ERR_BAD_OPTION="ERR_BAD_OPTION",we.ECONNABORTED="ECONNABORTED",we.ETIMEDOUT="ETIMEDOUT",we.ECONNREFUSED="ECONNREFUSED",we.ERR_NETWORK="ERR_NETWORK",we.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",we.ERR_DEPRECATED="ERR_DEPRECATED",we.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",we.ERR_BAD_REQUEST="ERR_BAD_REQUEST",we.ERR_CANCELED="ERR_CANCELED",we.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",we.ERR_INVALID_URL="ERR_INVALID_URL",we.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const rE=null,Mm=100;function gf(s){return G.isPlainObject(s)||G.isArray(s)}function Nm(s){return G.endsWith(s,"[]")?s.slice(0,-2):s}function mf(s,e,n){return s?s.concat(e).map(function(i,l){return i=Nm(i),!n&&l?"["+i+"]":i}).join(n?".":""):e}function aE(s){return G.isArray(s)&&!s.some(gf)}const iE=G.toFlatObject(G,{},null,function(e){return/^is[A-Z]/.test(e)});function gc(s,e,n){if(!G.isObject(s))throw new TypeError("target must be an object");e=e||new FormData;const r=(O,k)=>{const L=G.getSafeProp(n,O);return G.isUndefined(L)?k:L},i=r("metaTokens",!0),l=r("visitor")||x,c=r("dots",!1),d=r("indexes",!1),f=r("Blob")||typeof Blob<"u"&&Blob,h=r("maxDepth",Mm),m=f&&G.isSpecCompliantForm(e),y=[];if(!G.isFunction(l))throw new TypeError("visitor must be a function");function v(O){if(O===null)return"";if(G.isDate(O))return O.toISOString();if(G.isBoolean(O))return O.toString();if(!m&&G.isBlob(O))throw new we("Blob is not supported. Use a Buffer instead.");if(G.isArrayBuffer(O)||G.isTypedArray(O)){if(m&&typeof f=="function")return new f([O]);throw new we("Blob is not supported. Use a Buffer instead.",we.ERR_NOT_SUPPORT)}return O}function S(O){if(O>h)throw new we("Object is too deeply nested ("+O+" levels). Max depth: "+h,we.ERR_FORM_DATA_DEPTH_EXCEEDED)}function _(O,k){if(h===1/0)return JSON.stringify(O);const L=[];return JSON.stringify(O,function(q,z){if(!G.isObject(z))return z;for(;L.length&&L[L.length-1]!==this;)L.pop();return L.push(z),S(k+L.length-1),z})}function x(O,k,L){let B=O;if(G.isReactNative(e)&&G.isReactNativeBlob(O))return e.append(mf(L,k,c),v(O)),!1;if(O&&!L&&typeof O=="object"){if(G.endsWith(k,"{}"))k=i?k:k.slice(0,-2),O=_(O,1);else if(G.isArray(O)&&aE(O)||(G.isFileList(O)||G.endsWith(k,"[]"))&&(B=G.toArray(O)))return k=Nm(k),B.forEach(function(z,W){!(G.isUndefined(z)||z===null)&&e.append(d===!0?mf([k],W,c):d===null?k:k+"[]",v(z))}),!1}return gf(O)?!0:(e.append(mf(L,k,c),v(O)),!1)}const A=Object.assign(iE,{defaultVisitor:x,convertValue:v,isVisitable:gf});function D(O,k,L=0){if(!G.isUndefined(O)){if(S(L),y.indexOf(O)!==-1)throw new Error("Circular reference detected in "+k.join("."));y.push(O),G.forEach(O,function(q,z){(!(G.isUndefined(q)||q===null)&&l.call(e,q,G.isString(z)?z.trim():z,k,A))===!0&&D(q,k?k.concat(z):[z],L+1)}),y.pop()}}if(!G.isObject(s))throw new TypeError("data must be an object");return D(s),e}function Im(s){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(s).replace(/[!'()~]|%20/g,function(r){return e[r]})}function yf(s,e){this._pairs=[],s&&gc(s,this,e)}const jm=yf.prototype;jm.append=function(e,n){this._pairs.push([e,n])},jm.toString=function(e){const n=e?r=>e.call(this,r,Im):Im;return this._pairs.map(function(i){return n(i[0])+"="+n(i[1])},"").join("&")};function sE(s){return encodeURIComponent(s).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Hm(s,e,n){if(!e)return s;s=s||"";const r=G.isFunction(n)?{serialize:n}:n,i=G.getSafeProp(r,"encode")||sE,l=G.getSafeProp(r,"serialize");let c;if(l?c=l(e,r):c=G.isURLSearchParams(e)?e.toString():new yf(e,r).toString(i),c){const d=s.indexOf("#");d!==-1&&(s=s.slice(0,d)),s+=(s.indexOf("?")===-1?"?":"&")+c}return s}const Ro=Symbol("internals");function zm(s){return s?s.length:0}function Pm(s){if(s)for(;s.length&&s[s.length-1]===null;)s.pop()}function Do(s,e){const n=s.handlers,r=zm(n);n!==e.handlersRef?(e.handlersRef=n,e.handlerEntries.clear()):r!==e.handlersLength&&(r?e.handlerEntries.forEach(function(l,c){n[l.index]!==l.handler&&e.handlerEntries.delete(c)}):e.handlerEntries.clear()),e.handlersLength=r}class Um{constructor(){this.handlers=[],this[Ro]={handlersRef:this.handlers,handlersLength:this.handlers.length,handlerEntries:new Map,iterationDepth:0,nextId:0}}use(e,n,r){const i={fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null},l=this[Ro];this.handlers==null&&(this.handlers=[]),Do(this,l);const c=l.nextId++;return this.handlers.push(i),l.handlerEntries.set(c,{handler:i,index:this.handlers.length-1}),l.handlersLength=this.handlers.length,c}eject(e){const n=this[Ro];Do(this,n);const r=n.handlerEntries.get(e);if(r){if(n.handlerEntries.delete(e),this.handlers[r.index]!==r.handler)return;this.handlers[r.index]=null,n.iterationDepth||(Pm(this.handlers),n.handlersLength=this.handlers.length)}}clear(){this.handlers&&(this.handlers=[],Do(this,this[Ro]))}forEach(e){const n=this[Ro];Do(this,n),n.iterationDepth++;try{G.forEach(this.handlers,function(i){i!==null&&e(i)})}finally{--n.iterationDepth||(Do(this,n),Pm(this.handlers),n.handlersLength=zm(this.handlers))}}}const bf={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0,advertiseZstdAcceptEncoding:!1,validateStatusUndefinedResolves:!0},oE={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:yf,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},vf=typeof window<"u"&&typeof document<"u",Sf=typeof navigator=="object"&&navigator||void 0,lE=vf&&(!Sf||["ReactNative","NativeScript","NS"].indexOf(Sf.product)<0),cE=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",uE=vf&&window.location.href||"http://localhost",gn={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:vf,hasStandardBrowserEnv:lE,hasStandardBrowserWebWorkerEnv:cE,navigator:Sf,origin:uE},Symbol.toStringTag,{value:"Module"})),...oE};function dE(s,e){return gc(s,new gn.classes.URLSearchParams,{visitor:function(n,r,i,l){return gn.isNode&&G.isBuffer(n)?(this.append(r,n.toString("base64")),!1):l.defaultVisitor.apply(this,arguments)},...e})}const Bm=Mm;function qm(s){if(s>Bm)throw new we("FormData field is too deeply nested ("+s+" levels). Max depth: "+Bm,we.ERR_FORM_DATA_DEPTH_EXCEEDED)}function fE(s){const e=[],n=/[^.[\]]+|\[([^.[\]]*)]/g;let r;for(;(r=n.exec(s))!==null;)qm(e.length),e.push(r[0]==="[]"?"":r[1]||r[0]);return e}function hE(s){const e={},n=Object.keys(s);let r;const i=n.length;let l;for(r=0;r=n.length;return c=!c&&G.isArray(i)?i.length:c,f?(G.hasOwnProp(i,c)?i[c]=G.isArray(i[c])?i[c].concat(r):[i[c],r]:i[c]=r,!d):((!G.hasOwnProp(i,c)||!G.isObject(i[c]))&&(i[c]=[]),e(n,r,i[c],l)&&G.isArray(i[c])&&(i[c]=hE(i[c])),!d)}if(G.isFormData(s)&&G.isFunction(s.entries)){const n={};return G.forEachEntry(s,(r,i)=>{e(fE(r),i,n,0)}),n}return null}const Fm=Object.freeze(["get","delete","head","options","post","put","patch","purge","link","unlink","query"]),ms=(s,e)=>s!=null&&G.hasOwnProp(s,e)?s[e]:void 0;function pE(s,e,n){if(G.isString(s))try{return(e||JSON.parse)(s),G.trim(s)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(s)}const Oo={transitional:bf,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",i=r.indexOf("application/json")>-1,l=G.isObject(e);if(l&&G.isHTMLForm(e)&&(e=new FormData(e)),G.isFormData(e))return i?JSON.stringify(Gm(e)):e;if(G.isArrayBuffer(e)||G.isBuffer(e)||G.isStream(e)||G.isFile(e)||G.isBlob(e)||G.isReadableStream(e))return e;if(G.isArrayBufferView(e))return e.buffer;if(G.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let d;if(l){const f=ms(this,"formSerializer");if(r.indexOf("application/x-www-form-urlencoded")>-1)return dE(e,f).toString();if((d=G.isFileList(e))||r.indexOf("multipart/form-data")>-1){const h=ms(this,"env"),m=h&&h.FormData;return gc(d?{"files[]":e}:e,m&&new m,f)}}return l||i?(n.setContentType("application/json",!1),pE(e)):e}],transformResponse:[function(e){const n=ms(this,"transitional")||Oo.transitional,r=n&&n.forcedJSONParsing,i=ms(this,"responseType"),l=i==="json";if(G.isResponse(e)||G.isReadableStream(e))return e;if(e&&G.isString(e)&&(r&&!i||l)){const d=!(n&&n.silentJSONParsing)&&l;try{return JSON.parse(e,ms(this,"parseReviver"))}catch(f){if(d)throw f.name==="SyntaxError"?we.from(f,we.ERR_BAD_RESPONSE,this,null,ms(this,"response")):f}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:gn.classes.FormData,Blob:gn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};G.forEach(Fm,s=>{Oo.headers[s]={}});function wf(s,e){const n=this||Oo,r=e||n,i=xn.from(r.headers);let l=r.data;return G.forEach(s,function(d){l=d.call(n,l,i.normalize(),e?e.status:void 0)}),i.normalize(),l}function Vm(s){return!!(s&&s.__CANCEL__)}let Lo=class extends we{constructor(e,n,r){super(e??"canceled",we.ERR_CANCELED,n,r),this.name="CanceledError",this.__CANCEL__=!0}};function Km(s,e,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?s(n):e(new we("Request failed with status code "+n.status,n.status>=400&&n.status<500?we.ERR_BAD_REQUEST:we.ERR_BAD_RESPONSE,n.config,n.request,n))}const gE=/[\t\n\r]/g;function Wm(s){if(typeof s!="string")return s;let e=0;for(;e{n=y,i=null,l&&(clearTimeout(l),l=null),s(...m)};return[(...m)=>{const y=Date.now(),v=y-n;v>=r?c(m,y):(i=m,l||(l=setTimeout(()=>{l=null,c(i)},r-v)))},()=>i&&c(i),(...m)=>c(m)]}const mc=(s,e,n=3)=>{let r=0;const i=mE(50,250);return yE(l=>{if(!l||!G.isNumber(l.loaded))return;const c=l.loaded,d=l.lengthComputable?l.total:void 0,f=Math.max(0,d!=null?Math.min(c,d):c),h=Math.max(0,f-r),m=i(h);r=Math.max(r,f);const y={loaded:f,total:d,progress:d?f/d:void 0,bytes:h,rate:m||void 0,estimated:m&&d?(d-f)/m:void 0,event:l,lengthComputable:d!=null,[e?"download":"upload"]:!0};s(y)},n)},Ym=(s,e)=>{const n=s!=null;return[r=>e[0]({lengthComputable:n,total:s,loaded:r}),e[1]]},Xm=(s,e=G.asap)=>(...n)=>e(()=>s(...n)),bE=gn.hasStandardBrowserEnv?((s,e)=>n=>(n=new URL(n,gn.origin),s.protocol===n.protocol&&s.host===n.host&&(e||s.port===n.port)))(new URL(gn.origin),gn.navigator&&/(msie|trident)/i.test(gn.navigator.userAgent)):()=>!0,vE=gn.hasStandardBrowserEnv?{write(s,e,n,r,i,l,c){if(typeof document>"u")return;const d=[`${s}=${encodeURIComponent(e)}`];G.isNumber(n)&&d.push(`expires=${new Date(n).toUTCString()}`),G.isString(r)&&d.push(`path=${r}`),G.isString(i)&&d.push(`domain=${i}`),l===!0&&d.push("secure"),G.isString(c)&&d.push(`SameSite=${c}`),document.cookie=d.join("; ")},read(s){if(typeof document>"u")return null;const e=document.cookie.split(";");for(let n=0;n0&&s.charCodeAt(n-1)===47;)n--;return s.slice(0,n)+"/"+e.replace(/^\/+/,"")}const CE=/^https?:(?!\/\/)/i;function EE(s){return s&&s.replace(/(^|&)([^=&]*=)?[^&]+/g,(e,n,r="")=>`${n}${r}${pc}`)}function _E(s){const e=s.replace(/^(https?:\/{0,2})[^/?#]*@/i,`$1${pc}@`),n=e.indexOf("#"),i=(n===-1?e:e.slice(0,n)).replace(/([?&][^=&#]*=)[^&#]*/g,`$1${pc}`);return n===-1?i:`${i}#${EE(e.slice(n+1))}`}function Jm(s,e){if(typeof s=="string"){const n=Wm(s);if(CE.test(n))throw new we(`Invalid URL ${JSON.stringify(_E(n))}: missing "//" after protocol`,we.ERR_INVALID_URL,e)}}function Qm(s,e,n,r){Jm(e,r);let i=!SE(e);return s&&(i||n===!1)?(Jm(s,r),wE(s,e)):e}const Zm=s=>s instanceof xn?{...s}:s,AE=s=>Object.getOwnPropertySymbols&&Object.getOwnPropertyDescriptor?Object.keys(s).concat(Object.getOwnPropertySymbols(s).filter(e=>Object.getOwnPropertyDescriptor(s,e).enumerable)):Object.keys(s);function xi(s,e){s=s||{},e=e||{};const n=Object.create(null);Object.defineProperty(n,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function r(m,y,v,S){return G.isPlainObject(m)&&G.isPlainObject(y)?G.merge.call({caseless:S},m,y):G.isPlainObject(y)?G.merge({},y):G.isArray(y)?y.slice():y}function i(m,y,v,S){if(G.isUndefined(y)){if(!G.isUndefined(m))return r(void 0,m,v,S)}else return r(m,y,v,S)}function l(m,y){if(!G.isUndefined(y))return r(void 0,y)}function c(m,y){if(G.isUndefined(y)){if(!G.isUndefined(m))return r(void 0,m)}else return r(void 0,y)}function d(m){const y=G.hasOwnProp(e,"transitional")?e.transitional:void 0;if(!G.isUndefined(y))if(G.isPlainObject(y)){if(G.hasOwnProp(y,m))return y[m]}else return;const v=G.hasOwnProp(s,"transitional")?s.transitional:void 0;if(G.isPlainObject(v)&&G.hasOwnProp(v,m))return v[m]}function f(m,y,v){if(G.hasOwnProp(e,v))return r(m,y);if(G.hasOwnProp(s,v))return r(void 0,m)}const h={url:l,method:l,data:l,baseURL:c,transformRequest:c,transformResponse:c,paramsSerializer:c,timeout:c,timeoutErrorMessage:c,withCredentials:c,withXSRFToken:c,adapter:c,responseType:c,xsrfCookieName:c,xsrfHeaderName:c,onUploadProgress:c,onDownloadProgress:c,decompress:c,maxContentLength:c,maxBodyLength:c,beforeRedirect:c,transport:c,httpAgent:c,httpsAgent:c,cancelToken:c,socketPath:c,allowedSocketPaths:c,responseEncoding:c,validateStatus:f,headers:(m,y,v)=>i(Zm(m),Zm(y),v,!0)};return G.forEach(AE({...s,...e}),function(y){if(y==="__proto__"||y==="constructor"||y==="prototype")return;const v=G.hasOwnProp(h,y)?h[y]:i,S=G.hasOwnProp(s,y)?s[y]:void 0,_=G.hasOwnProp(e,y)?e[y]:void 0,x=v(S,_,y);G.isUndefined(x)&&v!==f||(n[y]=x)}),G.hasOwnProp(e,"validateStatus")&&G.isUndefined(e.validateStatus)&&d("validateStatusUndefinedResolves")===!1&&(G.hasOwnProp(s,"validateStatus")?n.validateStatus=r(void 0,s.validateStatus):delete n.validateStatus),n}const xE=["content-type","content-length"];function TE(s,e,n){if(n!=="content-only"){s.set(e);return}Object.entries(e||{}).forEach(([r,i])=>{xE.includes(r.toLowerCase())&&s.set(r,i)})}const kE=s=>encodeURIComponent(s).replace(/%([0-9A-F]{2})/gi,(e,n)=>String.fromCharCode(parseInt(n,16)));function ey(s){const e=xi({},s),n=v=>G.hasOwnProp(e,v)?e[v]:void 0,r=n("data");let i=n("withXSRFToken");const l=n("xsrfHeaderName"),c=n("xsrfCookieName");let d=n("headers");const f=n("auth"),h=n("baseURL"),m=n("allowAbsoluteUrls"),y=n("url");if(e.headers=d=xn.from(d),e.url=Hm(Qm(h,y,m,e),n("params"),n("paramsSerializer")),f){const v=G.getSafeProp(f,"username")||"",S=G.getSafeProp(f,"password")||"";try{d.set("Authorization","Basic "+btoa(v+":"+(S?kE(S):"")))}catch(_){throw we.from(_,we.ERR_BAD_OPTION_VALUE,s)}}if(G.isFormData(r)){const v=G.getSafeProp(r,"getHeaders");gn.hasStandardBrowserEnv||gn.hasStandardBrowserWebWorkerEnv||G.isReactNative(r)?d.setContentType(void 0):G.isFunction(v)&&TE(d,v.call(r),n("formDataHeaderPolicy"))}if(gn.hasStandardBrowserEnv&&(G.isFunction(i)&&(i=i(e)),i===!0||i==null&&bE(e.url))){const S=l&&c&&vE.read(c);S&&d.set(l,S)}return e}const RE=typeof XMLHttpRequest<"u"&&function(s){return new Promise(function(n,r){const i=ey(s);let l=i.data;const c=xn.from(i.headers).normalize();let{responseType:d,onUploadProgress:f,onDownloadProgress:h}=i,m,y,v,S,_,x;function A(){S&&S(),_&&_(),i.cancelToken&&i.cancelToken.unsubscribe(m),i.signal&&i.signal.removeEventListener("abort",m)}let D=new XMLHttpRequest;D.open(i.method.toUpperCase(),i.url,!0),D.timeout=i.timeout;function O(L){if(!D)return;if(D.status===0&&(Cf(Wm(i.url))||Cf(gn.origin))!=="file"&&!(D.responseURL&&D.responseURL.startsWith("file:"))){r(new we("Request aborted",we.ECONNABORTED,s,D)),A(),D=null;return}try{L?x&&x(L):_&&_()}catch(W){setTimeout(()=>{throw W})}if(!D)return;const B=xn.from("getAllResponseHeaders"in D&&D.getAllResponseHeaders()),z={data:!d||d==="text"||d==="json"?D.responseText:D.response,status:D.status,statusText:D.statusText,headers:B,config:s,request:D};Km(function(de){n(de),A()},function(de){r(de),A()},z),D=null}"onloadend"in D?D.onloadend=O:D.onreadystatechange=function(){!D||D.readyState!==4||D.status===0&&!(D.responseURL&&D.responseURL.startsWith("file:"))||setTimeout(O)},D.onabort=function(){D&&(r(new we("Request aborted",we.ECONNABORTED,s,D)),A(),D=null)},D.onerror=function(B){const q=B&&B.message?B.message:"Network Error",z=new we(q,we.ERR_NETWORK,s,D);z.event=B||null,r(z),A(),D=null},D.ontimeout=function(){let B=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const q=i.transitional||bf;i.timeoutErrorMessage&&(B=i.timeoutErrorMessage),r(new we(B,q.clarifyTimeoutError?we.ETIMEDOUT:we.ECONNABORTED,s,D)),A(),D=null},l===void 0&&c.setContentType(null),"setRequestHeader"in D&&G.forEach(Om(c),function(B,q){D.setRequestHeader(q,B)}),G.isUndefined(i.withCredentials)||(D.withCredentials=!!i.withCredentials),d&&d!=="json"&&(D.responseType=i.responseType),h&&([v,_,x]=mc(h,!0),D.addEventListener("progress",v)),f&&D.upload&&([y,S]=mc(f),D.upload.addEventListener("progress",y),D.upload.addEventListener("loadend",S)),(i.cancelToken||i.signal)&&(m=L=>{D&&(r(!L||L.type?new Lo(null,s,D):L),D.abort(),A(),D=null)},i.cancelToken&&i.cancelToken.subscribe(m),i.signal&&(i.signal.aborted?m():i.signal.addEventListener("abort",m)));const k=Cf(i.url);if(k&&!gn.protocols.includes(k)){r(new we("Unsupported protocol "+k+":",we.ERR_BAD_REQUEST,s)),A();return}D.send(l||null)})},DE=(s,e)=>{if(s=s?s.filter(Boolean):[],!e&&!s.length)return;const n=new AbortController;let r=!1;const i=function(f){if(!r){r=!0,c();const h=f instanceof Error?f:this.reason;n.abort(h instanceof we?h:new Lo(h instanceof Error?h.message:h))}};let l=e&&setTimeout(()=>{l=null,i(new we(`timeout of ${e}ms exceeded`,we.ETIMEDOUT))},e);const c=()=>{s&&(l&&clearTimeout(l),l=null,s.forEach(f=>{f.unsubscribe?f.unsubscribe(i):f.removeEventListener("abort",i)}),s=null)};s.forEach(f=>{if(!r){if(f.aborted){i.call(f);return}f.addEventListener("abort",i,{once:!0})}});const{signal:d}=n;return d.unsubscribe=()=>G.asap(c),d},OE=function*(s,e){let n=s.byteLength;if(n{const i=LE(s,e);let l=0,c,d=f=>{c||(c=!0,r&&r(f))};return new ReadableStream({async pull(f){try{const{done:h,value:m}=await i.next();if(h){d(),f.close();return}let y=m.byteLength;if(n){let v=l+=y;n(v)}f.enqueue(new Uint8Array(m))}catch(h){throw d(h),h}},cancel(f){return d(f),i.return()}},{highWaterMark:2})},ny=s=>s>=48&&s<=57||s>=65&&s<=70||s>=97&&s<=102,ry=(s,e,n)=>e+2s<=57?s-48:(s&223)-55,ME=s=>s>=65&&s<=90||s>=97&&s<=122||s>=48&&s<=57||s===43||s===47||s===45||s===95,NE=s=>s===9||s===10||s===12||s===13||s===32,IE=s=>{const e=Math.floor(s/4),n=s%4;return e*3+(n===2?1:n===3?2:0)},jE=s=>{const e=s.length;let n=0;return e>0&&s.charCodeAt(e-1)===61&&(n++,e>1&&s.charCodeAt(e-2)===61&&n++),Math.floor((e-n)*3/4)},HE=s=>{const e=s.length;let n=0,r=0,i=!1;for(let l=0;l0){i=!0;continue}n++}}return i||r>2||r>0&&(n+r)%4!==0||n%4===1?jE(s):IE(n)},zE=(s,e)=>{if(!s||typeof s!="string"||!s.startsWith("data:"))return 0;const n=s.indexOf(",");if(n<0)return 0;const r=s.slice(5,n),i=s.slice(n+1);if(/;base64/i.test(r))return e(i);let c=0;for(let d=0,f=i.length;d=55296&&h<=56319&&d+1=56320&&m<=57343?(c+=4,d++):c+=3}else c+=3}return c};function PE(s){const e=typeof s=="string"?s.indexOf("#"):-1;return zE(e===-1?s:s.slice(0,e),HE)}const Ef="1.20.0",iy=64*1024,UE={cache:"default",redirect:"follow",referrer:"about:client",referrerPolicy:"",mode:"cors",integrity:"",keepalive:!1,priority:"auto",window:null},{isFunction:yc}=G,BE=s=>encodeURIComponent(s).replace(/%([0-9A-F]{2})/gi,(e,n)=>String.fromCharCode(parseInt(n,16))),sy=s=>{if(!G.isString(s))return s;try{return decodeURIComponent(s)}catch{return s}},oy=(s,...e)=>{try{return!!s(...e)}catch{return!1}},qE=s=>{const e=s.indexOf("://");let n=s;return e!==-1&&(n=n.slice(e+3)),n.includes("@")||n.includes(":")},GE=s=>{const e=G.global!==void 0&&G.global!==null?G.global:globalThis,{ReadableStream:n,TextEncoder:r}=e;s=G.merge.call({skipUndefined:!0},{Request:e.Request,Response:e.Response},s);const{fetch:i,Request:l,Response:c}=s,d=i?yc(i):typeof fetch=="function",f=yc(l),h=yc(c);if(!d)return!1;const m=d&&yc(n),y=d&&(typeof r=="function"?(D=>O=>D.encode(O))(new r):async D=>new Uint8Array(await new l(D).arrayBuffer())),v=f&&m&&oy(()=>{let D=!1;const O=new l(gn.origin,{body:new n,method:"POST",get duplex(){return D=!0,"half"}}),k=O.headers.has("Content-Type");return O.body!=null&&O.body.cancel(),D&&!k}),S=h&&m&&oy(()=>G.isReadableStream(new c("").body)),_={stream:S&&(D=>D.body)};d&&["text","arrayBuffer","blob","formData","stream"].forEach(D=>{!_[D]&&(_[D]=(O,k)=>{let L=O&&O[D];if(L)return L.call(O);throw new we(`Response type '${D}' is not supported`,we.ERR_NOT_SUPPORT,k)})});const x=async D=>{if(D==null)return 0;if(G.isBlob(D))return D.size;if(G.isSpecCompliantForm(D))return(await new l(gn.origin,{method:"POST",body:D}).arrayBuffer()).byteLength;if(G.isArrayBufferView(D)||G.isArrayBuffer(D))return D.byteLength;if(G.isURLSearchParams(D)&&(D=D+""),G.isString(D))return(await y(D)).byteLength},A=async(D,O)=>{const k=G.toFiniteNumber(D.getContentLength());return k??x(O)};return async D=>{let{url:O,method:k,data:L,signal:B,cancelToken:q,timeout:z,onDownloadProgress:W,onUploadProgress:de,responseType:_e,headers:Se,withCredentials:Ie="same-origin",fetchOptions:Fe,maxContentLength:ze,maxBodyLength:Et,maxRedirects:Q}=ey(D);const ue=G.isNumber(ze)&&ze>-1,De=G.isNumber(Et)&&Et>-1,ee=ge=>G.hasOwnProp(D,ge)?D[ge]:void 0;let me=i||fetch;_e=_e?(_e+"").toLowerCase():"text";let H=DE([B,q&&q.toAbortSignal()],z),T=null;const fe=H&&H.unsubscribe&&(()=>{H.unsubscribe()});let he,Ae=null;const se=()=>new we("Request body larger than maxBodyLength limit",we.ERR_BAD_REQUEST,D,T);try{let ge;const $e=ee("auth");if($e){const qe=G.getSafeProp($e,"username")||"",mt=G.getSafeProp($e,"password")||"";ge={username:qe,password:mt}}if(qE(O)){const qe=new URL(O,gn.origin);if(!ge&&(qe.username||qe.password)){const mt=sy(qe.username),Dt=sy(qe.password);ge={username:mt,password:Dt}}(qe.username||qe.password)&&(qe.username="",qe.password="",O=qe.href)}if(ge&&(Se.delete("authorization"),Se.set("Authorization","Basic "+btoa(BE((ge.username||"")+":"+(ge.password||""))))),ue&&typeof O=="string"&&O.startsWith("data:")&&PE(O)>ze)throw new we("maxContentLength size of "+ze+" exceeded",we.ERR_BAD_RESPONSE,D,T);if(De&&k!=="get"&&k!=="head"){const qe=await x(L);if(typeof qe=="number"&&isFinite(qe)&&(he=qe,qe>Et))throw se()}const Te=De&&(G.isReadableStream(L)||G.isStream(L)),je=(qe,mt,Dt)=>ty(qe,iy,zt=>{if(De&&zt>Et)throw Ae=se();mt&&mt(zt)},Dt);if(v&&k!=="get"&&k!=="head"&&(de||Te)){if(he=he??await A(Se,L),he!==0||Te){let qe=new l(O,{method:"POST",body:L,duplex:"half"}),mt;if(G.isFormData(L)&&(mt=qe.headers.get("content-type"))&&Se.setContentType(mt),qe.body){const[Dt,zt]=de&&Ym(he,mc(Xm(de)))||[];L=je(qe.body,Dt,zt)}}}else if(Te&&!f&&m&&k!=="get"&&k!=="head")L=je(L);else if(Te&&f&&!v&&k!=="get"&&k!=="head")throw new we("Stream request bodies are not supported by the current fetch implementation",we.ERR_NOT_SUPPORT,D,T);G.isString(Ie)||(Ie=Ie?"include":"omit");const xt=f&&"credentials"in l.prototype;if(G.isFormData(L)){const qe=Se.getContentType();qe&&/^multipart\/form-data/i.test(qe)&&!/boundary=/i.test(qe)&&Se.delete("content-type")}Se.set("User-Agent","axios/"+Ef,!1);const rt=Fe==null?Fe:Object.assign(Object.create(null),Fe);rt&&(delete rt.body,delete rt.headers,delete rt.method,delete rt.signal,delete rt.duplex,delete rt.credentials);const gt=Object.assign(Object.create(null),rt,{signal:H,method:k.toUpperCase(),headers:Om(Se.normalize()),body:L,duplex:"half",credentials:xt?Ie:void 0});f&&(G.forEach(UE,(qe,mt)=>{gt[mt]===void 0&&(gt[mt]=qe)}),gt.signal===void 0&&(gt.signal=null),gt.body===void 0&&(gt.body=null)),Q===0&&(gt.redirect="manual",rt&&(rt.redirect="manual")),T=f&&new l(O,gt);let at=await(f?me(T,rt):me(O,gt));const Yt=xn.from(at.headers);if(ue){const qe=G.toFiniteNumber(Yt.getContentLength());if(qe!=null&&qe>ze)throw new we("maxContentLength size of "+ze+" exceeded",we.ERR_BAD_RESPONSE,D,T)}const Ht=S&&(_e==="stream"||_e==="response");if(S&&at.body&&(W||ue||Ht&&fe)){const qe={};["status","statusText","headers"].forEach(Ot=>{qe[Ot]=at[Ot]});const mt=G.toFiniteNumber(Yt.getContentLength()),[Dt,zt]=W&&Ym(mt,mc(Xm(W),!0))||[];let kn=0;const dr=Ot=>{if(ue&&(kn=Ot,kn>ze))throw new we("maxContentLength size of "+ze+" exceeded",we.ERR_BAD_RESPONSE,D,T);Dt&&Dt(Ot)};at=new c(ty(at.body,iy,dr,()=>{zt&&zt(),fe&&fe()}),qe)}_e=_e||"text";let bt=await _[G.findKey(_,_e)||"text"](at,D);if(ue&&!S&&!Ht){let qe;if(bt!=null&&(typeof bt.byteLength=="number"?qe=bt.byteLength:typeof bt.size=="number"?qe=bt.size:typeof bt=="string"&&(qe=typeof r=="function"?new r().encode(bt).byteLength:bt.length)),typeof qe=="number"&&qe>ze)throw new we("maxContentLength size of "+ze+" exceeded",we.ERR_BAD_RESPONSE,D,T)}return!Ht&&fe&&fe(),await new Promise((qe,mt)=>{Km(qe,mt,{data:bt,headers:xn.from(at.headers),status:at.status,statusText:at.statusText,config:D,request:T})})}catch(ge){if(fe&&fe(),H&&H.aborted&&H.reason instanceof we){const $e=H.reason;throw $e.config=D,T&&($e.request=T),ge!==$e&&Object.defineProperty($e,"cause",{__proto__:null,value:ge,writable:!0,enumerable:!1,configurable:!0}),$e}if(Ae)throw T&&!Ae.request&&(Ae.request=T),Ae;if(ge instanceof we)throw T&&!ge.request&&(ge.request=T),ge;if(ge&&ge.name==="TypeError"&&/Load failed|fetch/i.test(ge.message)){const $e=new we("Network Error",we.ERR_NETWORK,D,T,ge&&ge.response);throw Object.defineProperty($e,"cause",{__proto__:null,value:ge.cause||ge,writable:!0,enumerable:!1,configurable:!0}),$e}throw we.from(ge,ge&&ge.code,D,T,ge&&ge.response)}}},FE=new Map,ly=s=>{let e=s&&s.env||{};const{fetch:n,Request:r,Response:i}=e,l=[r,i,n];let c=l.length,d=c,f,h,m=FE;for(;d--;)f=l[d],h=m.get(f),h===void 0&&m.set(f,h=d?new Map:GE(e)),m=h;return h};ly();const _f={http:rE,xhr:RE,fetch:{get:ly}};G.forEach(_f,(s,e)=>{if(s){try{Object.defineProperty(s,"name",{__proto__:null,value:e})}catch{}Object.defineProperty(s,"adapterName",{__proto__:null,value:e})}});const cy=s=>`- ${s}`,VE=s=>G.isFunction(s)||s===null||s===!1;function KE(s,e){s=G.isArray(s)?s:[s];const{length:n}=s;let r,i;const l={};for(let c=0;c`adapter ${f} `+(h===!1?"is not supported by the environment":"is not available in the build"));let d=n?c.length>1?`since : -`+c.map(cy).join(` -`):" "+cy(c[0]):"as no adapter specified";throw new we("There is no suitable adapter to dispatch the request "+d,we.ERR_NOT_SUPPORT)}return i}const uy={getAdapter:KE,adapters:_f};function Af(s){if(s.cancelToken&&s.cancelToken.throwIfRequested(),s.signal&&s.signal.aborted)throw new Lo(null,s)}function xf(s){const e=G.toSafeFlatObject(s);return Af(e),e.headers=xn.from(G.getSafeProp(e,"headers")),e.data=wf.call(e,e.transformRequest),["post","put","patch"].indexOf(e.method)!==-1&&e.headers.setContentType("application/x-www-form-urlencoded",!1),uy.getAdapter(e.adapter||Oo.adapter,e)(e).then(function(i){Af(e),e.response=i;try{i.data=wf.call(e,e.transformResponse,i)}finally{delete e.response}return i.headers=xn.from(i.headers),i},function(i){if(!Vm(i)&&(Af(e),i&&i.response)){e.response=i.response;try{i.response.data=wf.call(e,e.transformResponse,i.response)}finally{delete e.response}i.response.headers=xn.from(i.response.headers)}return Promise.reject(i)})}const bc={};["object","boolean","number","function","string","symbol"].forEach((s,e)=>{bc[s]=function(r){return typeof r===s||"a"+(e<1?"n ":" ")+s}});const dy={};bc.transitional=function(e,n,r){function i(l,c){return"[Axios v"+Ef+"] Transitional option '"+l+"'"+c+(r?". "+r:"")}return(l,c,d)=>{if(e===!1)throw new we(i(c," has been removed"+(n?" in "+n:"")),we.ERR_DEPRECATED);return n&&!dy[c]&&(dy[c]=!0,console.warn(i(c," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(l,c,d):!0}},bc.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function WE(s,e,n){if(typeof s!="object"||s===null)throw new we("options must be an object",we.ERR_BAD_OPTION_VALUE);const r=Object.keys(s);let i=r.length;for(;i-- >0;){const l=r[i],c=Object.prototype.hasOwnProperty.call(e,l)?e[l]:void 0;if(c){const d=s[l],f=d===void 0||c(d,l,s);if(f!==!0)throw new we("option "+l+" must be "+f,we.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new we("Unknown option "+l,we.ERR_BAD_OPTION)}}const vc={assertOptions:WE,validators:bc},Tn=vc.validators;let Ti=class{constructor(e){this.defaults=e||{},this.interceptors={request:new Um,response:new Um}}async request(e,n){try{return await this._request(e,n)}catch(r){if(r instanceof Error)try{let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const l=i.stack;let c="";if(typeof l=="string"){const d=l.indexOf(` -`);c=d===-1?"":l.slice(d+1)}if(!r.stack)r.stack=c;else if(c){const d=c.indexOf(` -`),f=d===-1?-1:c.indexOf(` -`,d+1),h=f===-1?"":c.slice(f+1);String(r.stack).endsWith(h)||(r.stack+=` -`+c)}}catch{}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=xi(this.defaults,n);const{transitional:r,paramsSerializer:i,headers:l}=n;r!==void 0&&vc.assertOptions(r,{silentJSONParsing:Tn.transitional(Tn.boolean),forcedJSONParsing:Tn.transitional(Tn.boolean),clarifyTimeoutError:Tn.transitional(Tn.boolean),legacyInterceptorReqResOrdering:Tn.transitional(Tn.boolean),advertiseZstdAcceptEncoding:Tn.transitional(Tn.boolean),validateStatusUndefinedResolves:Tn.transitional(Tn.boolean)},!1),i!=null&&(G.isFunction(i)?n.paramsSerializer={serialize:i}:vc.assertOptions(i,{encode:Tn.function,serialize:Tn.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),vc.assertOptions(n,{baseUrl:Tn.spelling("baseURL"),withXsrfToken:Tn.spelling("withXSRFToken")},!0),n.method=(G.getSafeProp(n,"method")||G.getSafeProp(this.defaults,"method")||"get").toLowerCase();let c=l&&G.merge(l.common,l[n.method]);l&&G.forEach(Fm.concat("common"),_=>{delete l[_]}),n.headers=xn.concat(c,l);const d=[];let f=!0;this.interceptors.request.forEach(function(x){if(typeof x.runWhen=="function"&&x.runWhen(n)===!1)return;f=f&&x.synchronous;const A=n.transitional||bf;A&&A.legacyInterceptorReqResOrdering?d.unshift(x.fulfilled,x.rejected):d.push(x.fulfilled,x.rejected)});const h=[];this.interceptors.response.forEach(function(x){h.push(x.fulfilled,x.rejected)});let m,y=0,v;if(!f){const _=[xf.bind(this),void 0];for(_.unshift(...d),_.push(...h),v=_.length,m=Promise.resolve(n);yxf.call(this,S)))}catch(D){m=Promise.reject(D)}break}}if(!m)try{m=xf.call(this,S)}catch(_){m=Promise.reject(_)}for(y=0,v=h.length;y{if(!r._listeners)return;let l=r._listeners.length;for(;l-- >0;)r._listeners[l](i);r._listeners=null}),this.promise.then=i=>{let l;const c=new Promise(d=>{r.subscribe(d),l=d}).then(i);return c.cancel=function(){r.unsubscribe(l)},c},e(function(l,c,d){r.reason||(r.reason=new Lo(l,c,d),n(r.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 n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new r0(function(i){e=i}),cancel:e}}};function XE(s){return function(n){return s.apply(null,n)}}function JE(s){return G.isObject(s)&&s.isAxiosError===!0}const Sc={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,ContentTooLarge:413,UriTooLong:414,UnsupportedMediaType:415,RangeNotSatisfiable:416,ExpectationFailed:417,ImATeapot:418,MisdirectedRequest:421,UnprocessableEntity:422,UnprocessableContent: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,WebServerReturnsAnUnknownError:520,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Sc).forEach(([s,e])=>{Sc[e]===void 0&&(Sc[e]=s)});function fy(s){const e=new Ti(s),n=bm(Ti.prototype.request,e);return G.extend(n,Ti.prototype,e,{allOwnKeys:!0}),G.extend(n,e,null,{allOwnKeys:!0}),n.create=function(i){return fy(xi(s,i))},n}const Qt=fy(Oo);Qt.Axios=Ti,Qt.CanceledError=Lo,Qt.CancelToken=YE,Qt.isCancel=Vm,Qt.VERSION=Ef,Qt.toFormData=gc,Qt.AxiosError=we,Qt.Cancel=Qt.CanceledError,Qt.all=function(e){return Promise.all(e)},Qt.spread=XE,Qt.isAxiosError=JE,Qt.mergeConfig=xi,Qt.AxiosHeaders=xn,Qt.formToJSON=s=>Gm(G.isHTMLForm(s)?new FormData(s):s),Qt.getAdapter=uy.getAdapter,Qt.HttpStatusCode=Sc,Qt.default=Qt;const{Axios:DR,AxiosError:OR,CanceledError:LR,isCancel:$R,CancelToken:MR,VERSION:NR,all:IR,Cancel:jR,isAxiosError:HR,spread:zR,toFormData:PR,AxiosHeaders:UR,HttpStatusCode:BR,formToJSON:qR,getAdapter:GR,mergeConfig:FR,create:VR}=Qt,Tf="g7.identity.redirectStash",wc=pt("IdentityGuardInterceptor");class At{static setLauncher(e){this.launcher=e}static hasLauncher(){return this.launcher!==null}static markDomainNoticeShown(){this.domainNoticeShown=!0}static consumeDomainNoticeShown(){const e=this.domainNoticeShown;return this.domainNoticeShown=!1,e}static resolveDeferred(e){const n=this.deferredResolver;if(!n){wc.warn("IdentityGuardInterceptor.resolveDeferred 호출됐지만 대기 중인 launcher 가 없습니다. 모달이 launcher 외부에서 열렸는지 확인하세요.");return}this.deferredResolver=null,n(e)}static createDeferred(){if(this.deferredResolver){const e=this.deferredResolver;this.deferredResolver=null,e({status:"cancelled"})}return new Promise(e=>{this.deferredResolver=e})}static isIdentityRequired(e,n){return e===428&&typeof n=="object"&&n!==null&&n.error_code==="identity_verification_required"}static async handle(e,n,r){this.domainNoticeShown=!1;const i=this.launcher??ZE,c=!!(r&&(r.email||r.phone))?{...e.verification,target:r}:e.verification,d=await i(c);if(d.status!=="verified")return null;const f=c.return_request;if(!f)return null;const h=QE(f.url,d.token);return fetch(h,{method:f.method,headers:n?.headers??{Accept:"application/json","Content-Type":"application/json"},body:n?.body,credentials:n?.credentials??"same-origin"})}static redirectExternally(e){const n=e.redirect_url;if(!n)return wc.error("redirectExternally 호출 시 verification.redirect_url 이 없습니다. payload:",e),Promise.resolve({status:"failed",failureCode:"MISSING_REDIRECT_URL",reason:"verification.redirect_url is required for external_redirect flow"});if(typeof window<"u"){const r={return_url:window.location.href,payload:e,stashed_at:Date.now()};try{window.sessionStorage?.setItem(Tf,JSON.stringify(r))}catch(i){wc.warn("sessionStorage 접근 실패 — stash 없이 redirect 합니다.",i)}window.location.href=n}return new Promise(()=>{})}static reset(){if(this.deferredResolver){const e=this.deferredResolver;this.deferredResolver=null;try{e({status:"cancelled"})}catch{}}this.launcher=null,this.domainNoticeShown=!1}}M(At,"launcher",null),M(At,"deferredResolver",null),M(At,"domainNoticeShown",!1);function QE(s,e){if(!e)return s;try{const n=typeof window<"u"?window.location.origin:"http://localhost",r=new URL(s,n);return r.searchParams.set("verification_token",e),/^https?:\/\//i.test(s)?r.toString():`${r.pathname}${r.search}${r.hash}`}catch{const n=s.includes("?")?"&":"?";return`${s}${n}verification_token=${encodeURIComponent(e)}`}}const ZE=async s=>{if(typeof window>"u")return{status:"cancelled"};if(s.render_hint==="external_redirect"||s.redirect_url)return At.redirectExternally(s);const e=window.G7Core;if(!e?.dispatch)return console.error("[IdentityGuardInterceptor] defaultLauncher: G7Core 가 초기화되지 않아 본인인증 흐름을 시작할 수 없습니다."),{status:"failed",failureCode:"G7_NOT_READY"};try{await e.dispatch({handler:"toast",params:{message:"본인 확인이 필요합니다.",variant:"warning"}})}catch{}const n=window.location.href,r={return_url:n,payload:s,stashed_at:Date.now()};try{window.sessionStorage?.setItem(Tf,JSON.stringify(r))}catch{}const i=`/identity/challenge?return=${encodeURIComponent(n)}`;try{await e.dispatch({handler:"navigate",params:{path:i}})}catch(l){wc.warn("navigate 실패 — window.location 으로 폴백",l),window.location.href=i}return new Promise(()=>{})},e_=pt("ApiClient");function kf(){return typeof window<"u"&&window.__G7_DEVTOOLS__?window.__G7_DEVTOOLS__:null}class t_{constructor(e={}){M(this,"client");M(this,"config");M(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=Qt.create({baseURL:this.config.baseURL,timeout:this.config.timeout,headers:{"Content-Type":"application/json",Accept:"application/json"},paramsSerializer:{serialize:n=>{const r=[];for(const[i,l]of Object.entries(n))if(l!=null)if(Array.isArray(l)){const c=i.endsWith("[]")?i:`${i}[]`;for(const d of l)r.push(`${encodeURIComponent(c)}=${encodeURIComponent(String(d))}`)}else r.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(l))}`);return r.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 n=this.getToken();if(n&&e.headers&&!this.isCrossOriginRequest(e.url)&&(e.headers.Authorization=`Bearer ${n}`),typeof window<"u"&&e.headers){const i=localStorage.getItem("g7_locale");i&&(e.headers["Accept-Language"]=i)}const r=kf();if(r?.isEnabled()){const i=this.buildFullUrl(e),l=(e.method||"GET").toUpperCase(),c=r.trackRequest(i,l,{requestBody:e.data});e._devToolsRequestId=c}return e},e=>Promise.reject(e)),this.client.interceptors.response.use(e=>{const n=e.config,r=n._devToolsRequestId;if(r){const i=kf();i?.isEnabled()&&i.completeRequest(r,e.status,e.data),n._devToolsRequestId=null}return e},async e=>{const n=e.config,r=n?.url||"",l=["/auth/","/layouts/"].some(c=>r.includes(c));if(e.response?.status===401&&!n?._retry&&!l){if(n._retry=!0,await Ar.getInstance().refreshToken()){const f=this.getToken();return f&&(n.headers.Authorization=`Bearer ${f}`),n._devToolsRequestId=null,this.client(n)}return this.completeDevToolsRequest(n,e),this.removeToken(),this.config.onUnauthorized&&this.config.onUnauthorized(),Promise.reject(e)}if(e.response?.status===401&&l)return this.completeDevToolsRequest(n,e),Promise.reject(e);if(At.isIdentityRequired(e.response?.status,e.response?.data)){this.completeDevToolsRequest(n,e);const c={},d=n?.headers??{};for(const[v,S]of Object.entries(d))typeof S=="string"&&(c[v]=S);let f;n?.data!==void 0&&n?.data!==null&&(f=typeof n.data=="string"?n.data:JSON.stringify(n.data),c["Content-Type"]=c["Content-Type"]??"application/json");const h=n?.identity_target,m=await At.handle(e.response.data,{headers:c,body:f,credentials:"same-origin"},h);if(!m)return Promise.reject(e);let y=null;try{y=await m.json()}catch{y=null}return m.ok?{...e.response,status:m.status,data:y}:Promise.reject(Object.assign(new Error("replay failed"),{response:{status:m.status,data:y}}))}return e.response?.status===403?(this.completeDevToolsRequest(n,e),this.callOnError(e),Promise.reject(e)):(this.completeDevToolsRequest(n,e),e.response&&this.callOnError(e),Promise.reject(e))})}async get(e,n){return(await this.client.get(e,n)).data}async post(e,n,r){return(await this.client.post(e,n,r)).data}async put(e,n,r){return(await this.client.put(e,n,r)).data}async patch(e,n,r){return(await this.client.patch(e,n,r)).data}async delete(e,n){return(await this.client.delete(e,n)).data}getInstance(){return this.client}setOnUnauthorized(e){this.config.onUnauthorized=e}setOnError(e){this.config.onError=e}completeDevToolsRequest(e,n){if(!e?._devToolsRequestId)return;const r=kf();if(!r?.isEnabled())return;const i=e._devToolsRequestId;e._devToolsRequestId=null,n.response?r.completeRequest(i,n.response.status,n.response.data):n.request?r.failRequest(i,n.message||"Network error"):r.failRequest(i,n.message||"Request error")}isCrossOriginRequest(e){if(!e||typeof window>"u"||!window.location||!/^(https?:)?\/\//i.test(e))return!1;try{return new URL(e,window.location.href).origin!==window.location.origin}catch{return!1}}buildFullUrl(e){let n=e.url||"";if(e.baseURL&&!n.startsWith("http")&&(n=`${e.baseURL}${n.startsWith("/")?"":"/"}${n}`),e.params&&typeof e.params=="object"){const r=e.params,i=[];for(const[l,c]of Object.entries(r))if(c!=null)if(Array.isArray(c)){const d=l.endsWith("[]")?l:`${l}[]`;for(const f of c)i.push(`${encodeURIComponent(d)}=${encodeURIComponent(String(f))}`)}else i.push(`${encodeURIComponent(l)}=${encodeURIComponent(String(c))}`);i.length>0&&(n+=(n.includes("?")?"&":"?")+i.join("&"))}return n}callOnError(e){if(!this.config.onError)return;const n={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(n)}catch(r){e_.error("Error in onError handler:",r)}}}let Rf=null;function qr(){return Rf||(Rf=new t_),Rf}const $o=pt("AuthManager");function ys(s,e,n,r){try{window.G7Core?.devTools?.trackAuthEvent?.(s,e,n,r)}catch{}}const Cc={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"}},Or=class Or{constructor(){M(this,"state");M(this,"config");M(this,"isRefreshing",!1);M(this,"refreshPromise",null);M(this,"eventHandlers",new Map);this.state={isAuthenticated:!1,user:null,type:null},this.config=new Map,this.config.set("admin",Cc.admin),this.config.set("user",Cc.user)}static getInstance(){return Or.instance||(Or.instance=new Or),Or.instance}on(e,n){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(n)}emit(e,...n){const r=this.eventHandlers.get(e);r&&r.forEach(i=>i(...n))}isAuthenticated(){return this.state.isAuthenticated}getUser(){return this.state.user}getAuthType(){return this.state.type}async checkAuth(e){const n=qr();if(!n.getToken())return this.clearState(),!1;const i=this.config.get(e);if(!i)return $o.error(`Unknown auth type: ${e}`),!1;try{const l=await n.get(i.userEndpoint);return l.success&&l.data?(this.state={isAuthenticated:!0,user:l.data,type:e},this.emit("authStateChange",this.state),!0):(this.clearState(),!1)}catch(l){return l.response?.status===401&&await this.refreshToken()?this.checkAuth(e):(this.clearState(),!1)}}async preloadAuth(e){try{return await this.checkAuth(e)}catch(n){return $o.warn(`Preload auth failed for type ${e}:`,n),!1}}async login(e,n,r){const i=qr();if(!this.config.get(e))throw new Error(`Unknown auth type: ${e}`);const c=e==="admin"?Cc.admin.loginEndpoint:Cc.user.loginEndpoint;try{const d=r?.headers?{headers:r.headers}:void 0,f=await i.post(c,n,d);if(f.success&&f.data){i.setToken(f.data.token);const h=f.data.user.language,m=localStorage.getItem(Or.LOCALE_STORAGE_KEY),y=h&&h!==m;if(h)try{localStorage.setItem(Or.LOCALE_STORAGE_KEY,h)}catch(v){$o.warn("Failed to save user language to localStorage:",v)}return this.state={isAuthenticated:!0,user:f.data.user,type:e},this.emit("login",this.state),this.emit("authStateChange",this.state),ys("login",!0,void 0,{userId:f.data.user.uuid,email:f.data.user.email,type:e}),y&&window.__templateApp&&window.__templateApp.changeLocale(h),f.data.user}throw new Error("Login failed")}catch(d){this.clearState();const f=d.response?.data?.message,h=new Error(f||d.message||"Login failed");throw h.response=d.response,h.status=d.response?.status,ys("login",!1,h.message,{type:e,status:d.response?.status}),h}}async logout(){const e=qr(),n=this.state.type?this.config.get(this.state.type):null;try{n&&await e.post(n.logoutEndpoint)}catch(r){$o.warn("Logout API call failed:",r)}finally{e.removeToken();const r={...this.state};if(this.clearState(),this.emit("logout",r),this.emit("authStateChange",this.state),ys("logout",!0,void 0,{previousType:r.type}),n&&r.type){const i=window.location.pathname+window.location.search;window.location.href=this.getLoginRedirectUrl(r.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 n=this.config.get(e);if(!n)return!1;const r=qr();try{const i=await r.post(n.refreshEndpoint);return i.success&&i.data?.token?(r.setToken(i.data.token),this.emit("tokenRefreshed"),ys("token-refresh",!0,void 0,{type:e}),!0):(ys("token-refresh",!1,"No token in response",{type:e}),!1)}catch(i){return $o.error("Token refresh failed:",i),ys("token-refresh",!1,i instanceof Error?i.message:"Unknown error",{type:e}),!1}}getLoginRedirectUrl(e,n,r){const i=this.config.get(e);if(!i)return"/login";const l=encodeURIComponent(n);let c=`${i.loginPath}?redirect=${l}`;return r&&(c+=`&reason=${encodeURIComponent(r)}`),c}updateConfig(e,n){if(n.loginPath!==void 0){const i=n.loginPath;if(!i.startsWith("/")||i.startsWith("//"))throw new Error(`AuthManager.updateConfig: loginPath must be a same-origin path starting with '/' (got: ${i})`)}const r=this.config.get(e);r&&this.config.set(e,{...r,...n})}getRedirectUrl(e){const r=this.config.get(e)?.defaultPath||"/",l=new URLSearchParams(window.location.search).get("redirect");if(l)try{const c=decodeURIComponent(l);if(c.startsWith("/"))return c}catch{}return r}getConfig(e){return this.config.get(e)}clearState(){this.state={isAuthenticated:!1,user:null,type:null}}static resetInstance(){Or.instance=null}};M(Or,"instance"),M(Or,"LOCALE_STORAGE_KEY","g7_locale");let Ar=Or;const hy={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}}"}}},sa={findHandler(s,e){if(s){if(s[e])return s[e];if(s[String(e)])return s[String(e)];if(s.default)return s.default}},normalizeOnError(s){return s?Array.isArray(s)?s:[s]:[]},injectErrorCode(s,e,n){if(s.handler!=="showErrorPage"||s.params?.errorCode!==void 0)return s;const r=typeof e=="string"?parseInt(e,10):e,i=isNaN(r)?n:r;return i===void 0?s:{...s,params:{...s.params,errorCode:i}}}},xr=pt("ErrorHandlingResolver"),Ua=class Ua{constructor(){M(this,"templateErrorHandling",null);M(this,"layoutErrorHandling",null);M(this,"executeAction",null)}static getInstance(){return Ua.instance||(Ua.instance=new Ua),Ua.instance}static resetInstance(){Ua.instance=null}setTemplateConfig(e){this.templateErrorHandling=e,xr.log("Template config set:",e)}setLayoutConfig(e){this.layoutErrorHandling=e,xr.log("Layout config set:",e)}setActionExecutor(e){this.executeAction=e}resolve(e,n={}){const{errorHandling:r,onError:i}=n;xr.log("Resolving error:",e,{hasActionErrorHandling:!!r,hasActionOnError:!!i,hasLayoutConfig:!!this.layoutErrorHandling,hasTemplateConfig:!!this.templateErrorHandling});let l=sa.findHandler(r,e);if(l){const c=this.getMatchedKey(r,e);return{handler:sa.injectErrorCode(l,c,e),level:"action",matchedKey:c}}if(i){const c=sa.normalizeOnError(i);if(c.length>0)return{handler:c.length===1?c[0]:{handler:"sequence",actions:c},level:"action",matchedKey:"onError"}}if(l=sa.findHandler(this.layoutErrorHandling||void 0,e),l){const c=this.getMatchedKey(this.layoutErrorHandling,e);return{handler:sa.injectErrorCode(l,c,e),level:"layout",matchedKey:c}}if(l=sa.findHandler(this.templateErrorHandling||void 0,e),l){const c=this.getMatchedKey(this.templateErrorHandling,e);return{handler:sa.injectErrorCode(l,c,e),level:"template",matchedKey:c}}if(l=sa.findHandler(hy,e),l){const c=this.getMatchedKey(hy,e);return{handler:sa.injectErrorCode(l,c,e),level:"system",matchedKey:c}}return{handler:null,level:null,matchedKey:null}}async execute(e,n){if(!this.executeAction){xr.error("Action executor is not set");return}xr.log("Executing handler:",e.handler,{errorContext:n});try{return await this.executeAction(e,{error:n})}catch(r){throw xr.error("Failed to execute handler:",r),r}}async resolveAndExecute(e,n,r={}){const i=this.resolve(e,r);if(xr.log("Resolve result:",{errorCode:e,handler:i.handler?.handler,level:i.level,matchedKey:i.matchedKey}),!i.handler)return xr.warn("No handler found for error:",e),{handled:!1};try{return{handled:!0,result:await this.execute(i.handler,n)}}catch(l){return xr.error("Handler execution failed:",l),{handled:!1}}}getMatchedKey(e,n){return e[n]?n:e[String(n)]?String(n):"default"}clearLayoutConfig(){this.layoutErrorHandling=null,xr.log("Layout config cleared")}clearAllConfig(){this.templateErrorHandling=null,this.layoutErrorHandling=null,xr.log("All config cleared")}getConfigStatus(){return{hasTemplate:this.templateErrorHandling!==null,hasLayout:this.layoutErrorHandling!==null,hasExecutor:this.executeAction!==null}}};M(Ua,"instance",null);let Df=Ua;function Tr(){return Df.getInstance()}function Mo(s,e){const n={...s};for(const r of Object.keys(e))r in n?n[r]!==null&&typeof n[r]=="object"&&!Array.isArray(n[r])&&e[r]!==null&&typeof e[r]=="object"&&!Array.isArray(e[r])&&(n[r]=Mo(n[r],e[r])):n[r]=e[r];return n}var Of={exports:{}},No={};var py;function n_(){if(py)return No;py=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(r,i,l){var c=null;if(l!==void 0&&(c=""+l),i.key!==void 0&&(c=""+i.key),"key"in i){l={};for(var d in i)d!=="key"&&(l[d]=i[d])}else l=i;return i=l.ref,{$$typeof:s,type:r,key:c,ref:i!==void 0?i:null,props:l}}return No.Fragment=e,No.jsx=n,No.jsxs=n,No}var gy;function r_(){return gy||(gy=1,Of.exports=n_()),Of.exports}var yt=r_();const a_=na({__proto__:null,default:ra(yt)},[yt]),Lf=pt("ParentContextProvider"),my=I.createContext(null);let Ec=null;function $f(){Ec?(Lf.log("[triggerModalParentUpdate] 모달 부모 컨텍스트 업데이트 트리거"),Ec()):Lf.warn("[triggerModalParentUpdate] Provider가 아직 마운트되지 않음")}const yy=({children:s})=>{const[e,n]=I.useState(0),r=I.useRef(!0),i=I.useCallback(()=>{const c=window.__g7LayoutContextStack||[];return c[c.length-1]?.dataContext},[]);I.useEffect(()=>(r.current=!0,Ec=()=>{r.current&&(n(c=>c+1),Lf.log("[ParentContextProvider] 버전 업데이트됨"))},()=>{r.current=!1,Ec=null}),[]);const l={version:e,getParentDataContext:i};return yt.jsx(my.Provider,{value:l,children:s})};function i_(){return I.useContext(my)}function by(s){return s.replace(/[\t\n\r]/g,"").replace(/\\/g,"/").replace(/^([a-z][a-z0-9+.\-]*:)?\/{2,}/i,"$1//")}function vy(s,e){try{const n=typeof window<"u"&&window.location?.protocol||"https:",r=e||(typeof window<"u"?window.location?.origin:void 0)||"https://localhost",i=s.startsWith("//")?`${n}${s}`:s,l=new URL(i,r);return l.protocol!=="http:"&&l.protocol!=="https:"?null:l.hostname.toLowerCase()}catch{return null}}function bs(){const s=typeof window<"u"?window.G7Config?.trustedScriptHosts:void 0;return Array.isArray(s)?s.map(e=>String(e).toLowerCase()):[]}function Io(s,e){if(typeof s!="string")return!1;const n=s.trim();if(n==="")return!1;const r=by(n),i=r.startsWith("//"),l=/^[a-z][a-z0-9+.-]*:/i.test(r);if(!i&&!l&&r.startsWith("/"))return!0;const c=vy(r),d=e??bs();return c!==null&&d.map(f=>String(f).toLowerCase()).includes(c)}const j=pt("ActionDispatcher");function s_(s,e,n,r){return n||(Wg(s)||Ud(s)?"$t:core.errors.network_request_failed":r||`Failed to execute action: ${e}`)}const Sy=new Set(["navigate","navigateBack","navigateForward","replaceUrl","refresh","logout"]),o_=new Set(["redirect"]);function Yn(){try{return window.G7Core?.devTools}catch{return}}class jt extends Error{constructor(n,r,i){super(n);M(this,"action");M(this,"originalError");M(this,"unknownHandler",!1);this.action=r,this.originalError=i,this.name="ActionError"}}const wy={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"},cn=class cn{constructor(e={},n,r){M(this,"bindingEngine");M(this,"translationEngine");M(this,"translationContext");M(this,"customHandlers",new Map);M(this,"defaultContext");M(this,"globalStateUpdater");M(this,"errorHandlingSetup",!1);M(this,"debounceTimers",new Map);M(this,"pendingDebounceFlushers",new Map);M(this,"debounceAccumulatedValues",new Map);M(this,"globalHeaders",[]);M(this,"namedActions",{});M(this,"previewMode",!1);M(this,"localMirrorDepth",0);M(this,"intervals",new Map);this.bindingEngine=new $n,this.translationEngine=n,this.translationContext=r,this.defaultContext=e,this.registerDefaultHandlers(),this.setupErrorHandling()}setGlobalHeaders(e){this.globalHeaders=e||[]}setNamedActions(e){this.namedActions=e||{};const n=Yn();n?.isEnabled?.()&&n.setNamedActionDefinitions?.(this.namedActions),j.log("[setNamedActions] registered:",Object.keys(this.namedActions))}getNamedActions(){return this.namedActions}setPreviewMode(e){this.previewMode=e,j.log("Preview mode:",e?"enabled":"disabled")}isPreviewMode(){return this.previewMode}static getPreviewSuppressedHandlers(){return Sy}static getPreviewSuppressedLayoutFeatures(){return o_}resolveActionRef(e){if(!e.actionRef)return e;const n=this.namedActions[e.actionRef];if(!n)return j.warn(`[resolveActionRef] named action not found: "${e.actionRef}"`),e;const r=Yn();r?.isEnabled?.()&&r.trackNamedActionRef?.({actionRefName:e.actionRef,resolvedHandler:n.handler,timestamp:Date.now()});const{actionRef:i,type:l,key:c,event:d,...f}=e,h={...n,...Object.fromEntries(Object.entries(f).filter(([,m])=>m!==void 0)),type:l??n.type};return c!==void 0&&(h.key=c),d!==void 0&&(h.event=d),h}matchesPattern(e,n){if(n==="*")return!0;const r=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(e)}getMatchingGlobalHeaders(e,n){const r={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,c])=>{const d=hs(c,n,{skipCache:!0});d!=null&&d!==""&&(r[l]=String(d))});return r}setupErrorHandling(){if(this.errorHandlingSetup)return;Tr().setActionExecutor(async(n,r)=>{const i={type:"click",handler:n.handler,target:n.target,params:n.params,actions:n.actions},l={data:{...this.defaultContext.data,error:r.error}};return await this.dispatchAction(i,l)}),this.errorHandlingSetup=!0}registerDefaultHandlers(){this.registerHandler("refetchDataSource",async(n,r)=>{const i=n.params?.dataSourceId,l=n.params?.sync;if(!i){j.warn("refetchDataSource: dataSourceId is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.refetch){const c=window.G7Core?.state?.get?.()||{},d={...r.state?._global,...c},f=window.G7Core?.state?.getLocal?.()||{},h=r.data?._local||r.state||{},m={...f,...h},y=r.isolatedContext?.state;j.log("[refetchDataSource] localStateOverride:",m),await window.G7Core.dataSource.refetch(i,{...l?{sync:!0}:{},...d?{globalStateOverride:d}:{},...m?{localStateOverride:m}:{},...y?{isolatedStateOverride:y}:{}})}else j.warn("refetchDataSource: G7Core.dataSource.refetch is not available")}),this.registerHandler("appendDataSource",async(n,r)=>{const{dataSourceId:i,dataPath:l,newData:c}=n.params||{};if(!i){j.warn("appendDataSource: dataSourceId is required");return}if(c===void 0){j.warn("appendDataSource: newData is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.updateData){if(!Array.isArray(c)){j.warn("appendDataSource: newData must be an array, got:",typeof c,c);return}await window.G7Core.dataSource.updateData(i,l||null,c,"append")}else j.warn("appendDataSource: G7Core.dataSource.updateData is not available")}),this.registerHandler("updateDataSource",async(n,r)=>{const{dataSourceId:i,data:l,merge:c=!1}=n.params||{};if(!i){j.warn("updateDataSource: dataSourceId is required");return}if(l===void 0){j.warn("updateDataSource: data is required");return}typeof window<"u"&&window.G7Core?.dataSource?.set?(j.log(`[updateDataSource] Updating dataSource '${i}' with:`,l),window.G7Core.dataSource.set(i,l,{merge:c})):j.warn("updateDataSource: G7Core.dataSource.set is not available")}),this.registerHandler("scrollIntoView",async(n,r)=>{const{selector:i,behavior:l="smooth",block:c="nearest",inline:d="nearest",waitForElement:f=!1,timeout:h=2e3,delay:m=0,retryCount:y=0,retryInterval:v=50,scrollContainer:S}=n.params||{};if(!i){j.warn("scrollIntoView: selector is required");return}if(typeof window>"u"||typeof document>"u"){j.warn("scrollIntoView: window/document is not available");return}let _=null;if(f){if(_=await new Promise(x=>{const A=document.querySelector(i);if(A){x(A);return}const D=setTimeout(()=>{O.disconnect(),x(null)},h),O=new MutationObserver(()=>{const k=document.querySelector(i);k&&(clearTimeout(D),O.disconnect(),x(k))});O.observe(document.body,{childList:!0,subtree:!0})}),!_){j.warn(`scrollIntoView: element not found for selector "${i}" after ${h}ms timeout`);return}}else{m>0&&await new Promise(A=>setTimeout(A,m)),_=document.querySelector(i);let x=0;for(;!_&&xsetTimeout(A,v)),_=document.querySelector(i),x++;if(!_){j.warn(`scrollIntoView: element not found for selector "${i}" after ${x+1} attempts`);return}}if(S){const x=document.querySelector(S);if(!x){j.warn(`scrollIntoView: container not found for selector "${S}"`);return}const A=_.getBoundingClientRect(),D=x.getBoundingClientRect(),O=A.top-D.top+x.scrollTop,k=O+A.height;let L;switch(c){case"start":L=O;break;case"center":L=O-x.clientHeight/2+A.height/2;break;case"end":L=k-x.clientHeight;break;default:const B=A.topD.bottom;if(B)L=O;else if(q)L=k-x.clientHeight;else return;break}x.scrollTo({top:Math.max(0,L),behavior:l});return}_.scrollIntoView({behavior:l,block:c,inline:d})}),this.registerHandler("reloadExtensions",async(n,r)=>{if(typeof window>"u"){j.warn("reloadExtensions: window is not available");return}const i=window.__templateApp;if(!i){j.warn("reloadExtensions: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState()}catch(d){throw j.error("reloadExtensions: reloadExtensionState failed",d),d}else j.warn("reloadExtensions: TemplateApp.reloadExtensionState unavailable");const{moduleInfo:l,pluginInfo:c}=n.params||{};if(l)try{await this.executeAction({handler:"reloadModuleHandlers",params:n.params},r)}catch(d){j.error("reloadExtensions: reloadModuleHandlers failed",d)}if(c)try{await this.executeAction({handler:"reloadPluginHandlers",params:n.params},r)}catch(d){j.error("reloadExtensions: reloadPluginHandlers failed",d)}j.log("reloadExtensions: done")}),this.registerHandler("reloadRoutes",async(n,r)=>{if(typeof window>"u"){j.warn("reloadRoutes: window is not available");return}const i=window.__templateApp;if(!i){j.warn("reloadRoutes: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),j.log("reloadRoutes: delegated to reloadExtensionState")}catch(l){throw j.error("reloadRoutes: Failed to reload routes",l),l}else{const l=i.getRouter?.();l&&(await l.loadRoutes(),j.log("reloadRoutes: Routes reloaded (legacy fallback)"))}}),this.registerHandler("refresh",async(n,r)=>{if(typeof window>"u"){j.warn("refresh: window is not available");return}const i=Number(n.params?.delayMs??0);i>0&&await new Promise(l=>setTimeout(l,i)),window.location.reload()}),this.registerHandler("remount",async(n,r)=>{const{componentId:i}=n.params||{};if(!i){j.warn("remount: componentId parameter is required");return}if(!this.globalStateUpdater){j.warn("remount: globalStateUpdater is not set");return}const d=(window.G7Core?.state?.get()||{})._global?._remountKeys||{},f=d[i]||0;this.globalStateUpdater({_remountKeys:{...d,[i]:f+1}}),j.log(`remount: ${i} key incremented to ${f+1}`)}),this.registerHandler("reloadTranslations",async(n,r)=>{if(typeof window>"u"){j.warn("reloadTranslations: window is not available");return}const i=window.__templateApp;if(!i){j.warn("reloadTranslations: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),j.log("reloadTranslations: delegated to reloadExtensionState")}catch(l){throw j.error("reloadTranslations: Failed to reload translations",l),l}}),this.registerHandler("reloadModuleHandlers",async(n,r)=>{if(typeof window>"u"){j.warn("reloadModuleHandlers: window is not available");return}const{moduleInfo:i,action:l}=n.params||{};if(!i){j.warn("reloadModuleHandlers: moduleInfo is required");return}const c=i.data||i;if(!c.identifier){j.warn("reloadModuleHandlers: moduleInfo with identifier is required");return}if(!l||l!=="add"&&l!=="remove"){j.warn('reloadModuleHandlers: action must be "add" or "remove"');return}const d=window.G7Config;if(!d){j.warn("reloadModuleHandlers: G7Config not available");return}const f=c.identifier;try{if(l==="add"){if(c.assets){if(d.moduleAssets=d.moduleAssets||{},d.moduleAssets[f]=c.assets,j.log(`reloadModuleHandlers: Added assets for ${f}`),c.assets.js){const h=c.assets.js,m=`module-${f}`;this.assertAllowedExtensionAssetUrl(h,`module script (${f})`,n),document.getElementById(m)?j.warn(`reloadModuleHandlers: Script ${m} already loaded`):(await Cr(h,{id:m},{label:`module-script:${f}`}),j.log(`reloadModuleHandlers: Script loaded successfully for ${f}`))}if(c.assets.css){const h=c.assets.css,m=`module-css-${f}`;this.assertAllowedExtensionAssetUrl(h,`module stylesheet (${f})`,n),document.getElementById(m)||(await ia(h,{id:m},{label:`module-css:${f}`}),j.log(`reloadModuleHandlers: CSS loaded for ${f}`))}}}else if(l==="remove"){d.moduleAssets&&d.moduleAssets[f]&&(delete d.moduleAssets[f],j.log(`reloadModuleHandlers: Removed assets for ${f}`));const h=`module-${f}`,m=document.getElementById(h);m&&(m.remove(),j.log(`reloadModuleHandlers: Removed script for ${f}`));const y=`module-css-${f}`,v=document.getElementById(y);v&&(v.remove(),j.log(`reloadModuleHandlers: Removed CSS for ${f}`))}}catch(h){throw j.error(`reloadModuleHandlers: Failed to ${l} module assets`,h),h}}),this.registerHandler("reloadPluginHandlers",async(n,r)=>{if(typeof window>"u"){j.warn("reloadPluginHandlers: window is not available");return}const{pluginInfo:i,action:l}=n.params||{};if(!i){j.warn("reloadPluginHandlers: pluginInfo is required");return}const c=i.data||i;if(!c.identifier){j.warn("reloadPluginHandlers: pluginInfo with identifier is required");return}if(!l||l!=="add"&&l!=="remove"){j.warn('reloadPluginHandlers: action must be "add" or "remove"');return}const d=window.G7Config;if(!d){j.warn("reloadPluginHandlers: G7Config not available");return}const f=c.identifier;try{if(l==="add"){if(c.assets){if(d.pluginAssets=d.pluginAssets||{},d.pluginAssets[f]=c.assets,j.log(`reloadPluginHandlers: Added assets for ${f}`),c.assets.js){const h=c.assets.js,m=`plugin-${f}`;this.assertAllowedExtensionAssetUrl(h,`plugin script (${f})`,n),document.getElementById(m)?j.warn(`reloadPluginHandlers: Script ${m} already loaded`):(await Cr(h,{id:m},{label:`plugin-script:${f}`}),j.log(`reloadPluginHandlers: Script loaded successfully for ${f}`))}if(c.assets.css){const h=c.assets.css,m=`plugin-css-${f}`;this.assertAllowedExtensionAssetUrl(h,`plugin stylesheet (${f})`,n),document.getElementById(m)||(await ia(h,{id:m},{label:`plugin-css:${f}`}),j.log(`reloadPluginHandlers: CSS loaded for ${f}`))}}}else if(l==="remove"){d.pluginAssets&&d.pluginAssets[f]&&(delete d.pluginAssets[f],j.log(`reloadPluginHandlers: Removed assets for ${f}`));const h=`plugin-${f}`,m=document.getElementById(h);m&&(m.remove(),j.log(`reloadPluginHandlers: Removed script for ${f}`));const y=`plugin-css-${f}`,v=document.getElementById(y);v&&(v.remove(),j.log(`reloadPluginHandlers: Removed CSS for ${f}`))}}catch(h){throw j.error(`reloadPluginHandlers: Failed to ${l} plugin assets`,h),h}});let e=!1;this.registerHandler("showErrorPage",async(n,r)=>{if(e){j.log("showErrorPage: Already active, skipping duplicate call");return}if(e=!0,typeof window>"u"){e=!1,j.warn("showErrorPage: window is not available");return}const i=window.__templateApp;if(!i){e=!1,j.warn("showErrorPage: TemplateApp not initialized");return}const l=i.getErrorPageHandler?.();if(!l){e=!1,j.warn("showErrorPage: ErrorPageHandler not available");return}const c=n.params?.errorCode||500,d=n.params?.target||"content";let f=n.params?.containerId;f||(f=d==="full"?"app":"main_content"),j.log("showErrorPage:",{errorCode:c,target:d,containerId:f});const h=(m,y=6e4)=>new Promise((v,S)=>{const _=document.getElementById(m);if(_){v(_);return}j.log(`showErrorPage: Waiting for container #${m}...`);let x;const A=new MutationObserver((D,O)=>{const k=document.getElementById(m);k&&(j.log(`showErrorPage: Container #${m} found`),O.disconnect(),clearTimeout(x),v(k))});A.observe(document.body,{childList:!0,subtree:!0}),x=setTimeout(()=>{A.disconnect(),S(new Error(`Container #${m} not found within ${y}ms`))},y)});try{await h(f);const m=Tr(),y=m.layoutErrorHandling;m.clearLayoutConfig();try{await l.renderError(c,f)||j.warn(`showErrorPage: Failed to render error page for code ${c}`)}finally{m.setLayoutConfig(y)}}catch(m){throw j.error("showErrorPage: Error rendering error page:",m),m}finally{e=!1}}),this.registerHandler("emitEvent",async(n,r)=>{const i=n.params?.event,l=n.params?.data;if(!i){j.warn("emitEvent: event parameter is required");return}if(typeof window>"u"){j.warn("emitEvent: window is not available");return}const c=window.G7Core;if(!c?.componentEvent?.emit){j.warn("emitEvent: G7Core.componentEvent is not available");return}try{j.log(`emitEvent: Emitting "${i}"`,l);const d={...l,_context:{data:r.data,state:r.state}},f=await c.componentEvent.emit(i,d);if(!f||f.length===0?j.warn(`emitEvent: No listeners found for "${i}"`):j.log(`emitEvent: Event "${i}" completed with ${f.length} listener(s)`,f),this.globalStateUpdater){const h=(c?.state?.get()||{})._local||{},m={event:i,success:!0,data:f.length===1?f[0]:f,listeners:f.length};this.globalStateUpdater({_local:{...h,_eventResult:m}});const y=r.state&&typeof r.state=="object"&&!Array.isArray(r.state)?r.state:h;window.__g7SequenceLocalSync={...y,_eventResult:m}}}catch(d){if(j.error(`emitEvent: Event "${i}" failed`,d),this.globalStateUpdater){const f=c?.state?.get()||{};this.globalStateUpdater({_local:{...f._local,_eventResult:{event:i,success:!1,error:d instanceof Error?d.message:String(d)}}})}throw d}}),this.registerHandler("updateProductField",async(n,r)=>{const{productId:i,field:l,value:c}=n.params||{};if(!i||!l){j.warn("updateProductField: productId and field are required");return}if(typeof window>"u"){j.warn("updateProductField: window is not available");return}const d=window.G7Core;if(!d?.state?.get||!this.globalStateUpdater){j.warn("updateProductField: G7Core.state or globalStateUpdater is not available");return}try{const f=d.state.get()||{},m=(f.products?.data?.data||[]).map(v=>v.id===i?{...v,[l]:c,_modified:!0}:v),y=new Set(f._local?.modifiedProductIds||[]);y.add(i),this.globalStateUpdater({products:{...f.products,data:{...f.products?.data,data:m}},_local:{...f._local,modifiedProductIds:Array.from(y)}}),j.log(`updateProductField: Updated product ${i}, field: ${l}, value:`,c)}catch(f){throw j.error("updateProductField: Error updating product field",f),f}}),this.registerHandler("updateOptionField",async(n,r)=>{const{productId:i,optionId:l,field:c,value:d}=n.params||{};if(!i||!l||!c){j.warn("updateOptionField: productId, optionId and field are required");return}if(typeof window>"u"){j.warn("updateOptionField: window is not available");return}const f=window.G7Core;if(!f?.state?.get||!this.globalStateUpdater){j.warn("updateOptionField: G7Core.state or globalStateUpdater is not available");return}try{const h=f.state.get()||{},y=(h.products?.data?.data||[]).map(S=>{if(S.id===i&&S.options){const _=S.options.map(x=>x.id===l?{...x,[c]:d,_modified:!0}:x);return{...S,options:_,_modified:!0}}return S}),v=new Set(h._local?.modifiedProductIds||[]);v.add(i),this.globalStateUpdater({products:{...h.products,data:{...h.products?.data,data:y}},_local:{...h._local,modifiedProductIds:Array.from(v)}}),j.log(`updateOptionField: Updated product ${i} option ${l}, field: ${c}, value:`,d)}catch(h){throw j.error("updateOptionField: Error updating option field",h),h}}),this.registerHandler("setLocale",async(n,r)=>{const i=n.target;if(!i||typeof i!="string"){j.warn("setLocale: Invalid locale:",i);return}const l=window.__templateApp;if(l&&typeof l.changeLocale=="function")try{await l.changeLocale(i),j.log("setLocale: Locale changed to",i)}catch(c){j.error("setLocale: Failed to change locale:",c),window.location.reload()}else{j.warn("setLocale: TemplateApp not found, falling back to page reload");try{localStorage.setItem("g7_locale",i)}catch{}window.location.reload()}}),this.registerHandler("suppress",async()=>{j.log("suppress: Error intentionally suppressed")}),this.registerBuiltInHandlerMetadata()}registerBuiltInHandlerMetadata(){const e=Yn();if(!e?.isEnabled())return;const n=[{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 r of n)e.trackHandlerRegistration(r.name,"built-in",r.description)}createHandler(e,n,r){j.log("createHandler called for:",e.handler,e.type);const i=window.__g7DevTools,l=Date.now(),c=r?.state?{...r.state}:null,d=`handler_${e.handler}_${l}`;return async f=>{if(j.log("Handler invoked for:",e.handler,"event:",f.type),i?.isEnabled?.()&&c){const m=window.G7Core?.state?.getLocal?.()??r?.state??{},y=Date.now()-l;for(const v of Object.keys(c)){const S=c[v],_=m[v];S!==_&&y>100&&(i.trackStaleClosureWarning?.({type:"event-handler-stale",location:`createHandler(${e.handler})`,capturedPath:`_local.${v}`,capturedValue:S,capturedAt:l,currentValue:_,actionId:d,stackTrace:new Error().stack}),j.warn(`[Stale Closure] _local.${v} changed after handler creation:`,`captured="${S}" → current="${_}" (${y}ms ago)`))}}try{f.type!=="change"&&f.preventDefault();let h={};if(f.type==="submit"&&f.target instanceof HTMLFormElement){const v=f.target;new FormData(v).forEach((_,x)=>{h[x]=_})}const m={...this.defaultContext,data:{...n,form:h,_local:r?.state||{},$event:f},event:f,...r&&{state:r.state,setState:r.setState},isolatedContext:r?.isolatedContext};if(e.confirm){let v=this.resolveValue(e.confirm,m.data);if(this.translationEngine&&this.translationContext&&v.startsWith("$t:")&&(v=this.translationEngine.resolveTranslations(v,this.translationContext,m.data)),!confirm(v))return}const y=window.__g7ActionContext;window.__g7ActionContext={...r,data:m.data};try{await this.executeAction(e,m)}finally{window.__g7ActionContext=y}}catch(h){if(j.error("Action execution failed:",h),e.onError){const m=h instanceof jt&&h.originalError?h.originalError:h,y={...this.defaultContext,data:{...n,error:m,_local:r?.state||{},$event:f},event:f,...r&&{state:r.state,setState:r.setState}},v=Array.isArray(e.onError)?e.onError:[e.onError];for(const S of v)await this.executeAction(S,y)}}}}generateActionId(e,n){const r=e.handler,i=n||"no-target",l=Date.now(),c=Math.random().toString(36).substring(2,9);return`${r}_${i.replace(/[^a-zA-Z0-9]/g,"_")}_${l}_${c}`}async executeAction(e,n){if(e=this.resolveActionRef(e),typeof e.handler=="string"&&e.handler.includes("{{")){const f=this.evaluateExpression(e.handler,n.data);e={...e,handler:f==null?"":String(f)}}const r=Yn(),i=r?.isEnabled()?`action_${Date.now()}_${Math.random().toString(36).substring(2,11)}`:void 0,l=performance.now();let c;if(i&&r&&r.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),context:this.sanitizeForDevTools({hasState:!!n.state,hasSetState:!!n.setState,dataKeys:n.data?Object.keys(n.data):[]}),startTime:l,status:"started"}),e.if!==void 0)try{const f=this.resolveValue(e.if,n.data),h=f===!0||f==="true"||f&&f!=="false"&&f!=="0"&&f!==!1;if(j.log("[executeAction] if condition result:",e.handler,h),!h)return i&&r&&r.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"success",result:{skipped:!0,reason:"if condition false"}}),{success:!0,data:void 0}}catch(f){return j.error("[executeAction] if condition error:",e.handler,f),i&&r&&r.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"error",error:{name:"ConditionEvaluationError",message:f instanceof Error?f.message:String(f),stack:f instanceof Error?f.stack:void 0}}),{success:!0,data:void 0}}let d;try{const f=this.resolveParams(e.params,n.data);i&&(c=this.sanitizeForDevTools(f));const h=e.target?this.resolveValue(e.target,n.data):void 0;if(e.handler==="apiCall"&&n.setState){d=this.generateActionId(e,h);const y=n.state?.loadingActions||{};n.setState({loadingActions:{...y,[d]:!0}})}if(this.previewMode&&Sy.has(e.handler))return j.warn(`Preview mode: "${e.handler}" suppressed`,h||f),i&&r&&r.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"skipped",metadata:{reason:"preview_mode_suppressed"}}),{success:!0,data:void 0};let m;switch(e.handler){case"ensureIdentityVerified":m=await this.handleEnsureIdentityVerified(f);break;case"resolveIdentityChallenge":m=this.handleResolveIdentityChallenge(f);break;case"navigate":const y=f.path||h;m=await this.handleNavigate(y,f,n);break;case"navigateBack":m=await this.handleNavigateBack();break;case"navigateForward":m=await this.handleNavigateForward();break;case"openWindow":{const _=f.path||h;m=await this.handleOpenWindow(_,f);break}case"replaceUrl":{const _=f.path||h||window.location.pathname;m=await this.handleReplaceUrl(_,f);break}case"apiCall":if(e.onSuccess&&r?.isEnabled()&&i){const _=window.G7Core,x={};if(_?.state?.get){const A=_.state.get();x._global=A}n.state&&(x._local=n.state),r.registerStateCaptureForHandler?.(i,["_global","_local"],x)}const v=e.auth_mode??(e.auth_required?"required":"none"),S=e.identity_target?this.resolveParams(e.identity_target,n.data):void 0;m=await this.handleApiCall(h,f,n,v,S);break;case"login":m=await this.handleLogin(h,f,n);break;case"logout":m=await this.handleLogout(h,n);break;case"setState":j.log("[executeAction] setState resolvedParams:",f),m=await this.handleSetState(e.render!==void 0?{...f,__render:e.render}:f,n);break;case"setError":m=await this.handleSetError(h,f,n);break;case"openModal":m=await this.handleOpenModal(h,n);break;case"closeModal":m=await this.handleCloseModal(n);break;case"showAlert":m=await this.handleShowAlert(h,n);break;case"toast":m=await this.handleToast(f,n);break;case"switch":m=await this.handleSwitch(e,n);break;case"conditions":m=await this.handleConditions(e,n);break;case"sequence":m=await this.handleSequence(e,n);break;case"parallel":m=await this.handleParallel(e,n);break;case"startInterval":m=this.handleStartInterval(f,n);break;case"stopInterval":m=this.handleStopInterval(f);break;case"loadScript":m=await this.handleLoadScript(f,e,n);break;case"callExternal":m=await this.handleCallExternal(f,e,n);break;case"callExternalEmbed":m=await this.handleCallExternalEmbed(f,e,n);break;case"saveToLocalStorage":m=await this.handleSaveToLocalStorage(f,n);break;case"loadFromLocalStorage":m=await this.handleLoadFromLocalStorage(f,n);break;default:m=await this.handleCustomAction({...e,target:h,params:f},n);break}if(e.resultTo&&m!==void 0){const{target:y,key:v,merge:S}=e.resultTo,_=this.resolveValue(v,n.data),x=S==="replace"?"replace":S==="shallow"?"shallow":"deep";if(y==="_local"&&n.setState){const A=this.buildNestedUpdate(_,m),D=x!=="deep"?{...A,__mergeMode:x}:A;this.writeLocalState(n,D),j.log(`[resultTo] Saved to _local.${_} (merge=${x}):`,m)}else if(y==="_local"&&this.globalStateUpdater){const O=(window.G7Core?.state?.get()||{})._local||{},k=this.buildNestedUpdate(_,m);let L;x==="replace"?L=k:x==="shallow"?L={...O,...k}:L=this.deepMergeWithState(k,O),this.globalStateUpdater({_local:L}),j.log(`[resultTo] Saved to _local.${_} via globalStateUpdater (merge=${x}):`,m)}else if(y==="_global"&&this.globalStateUpdater){const A=this.buildNestedUpdate(_,m);this.globalStateUpdater(A),j.log(`[resultTo] Saved to _global.${_}:`,m)}else if(y==="_isolated"&&n.isolatedContext){const A=this.buildNestedUpdate(_,m);n.isolatedContext.mergeState(A,x),j.log(`[resultTo] Saved to _isolated.${_} (merge=${x}):`,m)}else j.warn(`[resultTo] Cannot save result: target=${y}, setState=${!!n.setState}, globalStateUpdater=${!!this.globalStateUpdater}, isolatedContext=${!!n.isolatedContext}`)}if(e.onSuccess){if(r?.isEnabled()&&i&&e.handler==="apiCall"){const S=window.G7Core,_={};S?.state?.get&&(_._global=S.state.get()),n.state&&(_._local=n.state),r.detectStaleClosure?.(i,`${e.handler} → onSuccess`,_,"callback-state-capture",i)}const y={...n,data:{...n.data,result:m,response:m}},v=Array.isArray(e.onSuccess)?e.onSuccess:[e.onSuccess];v.length>1?await this.handleSequence({handler:"sequence",type:"click",actions:v},y):v.length===1&&await this.executeAction(v[0],y)}return i&&r&&r.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),resolvedParams:c,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"success",result:this.sanitizeForDevTools(m)}),{success:!0,data:m}}catch(f){const h=f instanceof jt?f:new jt(`Failed to execute action: ${e.handler}`,e,f instanceof Error?f:void 0),m=h.originalError?.response||{},y=m.data||{},v=h.originalError?.status||m.status||500;let S=s_(h.originalError??f,e.handler,y.message,h.message);this.translationEngine&&this.translationContext&&S.startsWith("$t:")&&(S=this.translationEngine.resolveTranslations(S,this.translationContext));const _={status:v,message:S,errors:y.errors||m.errors,data:y,statusText:h.originalError?.statusText,error_code:y.error_code??m.error_code};if(h.unknownHandler)throw j.warn(`Unknown action handler "${e.handler}" — skipped (extension not loaded?). Not surfaced to the user.`),h;const A=Tr().resolve(v,{errorHandling:e.errorHandling,onError:e.onError});if(A.handler){if(r?.isEnabled()&&i&&e.handler==="apiCall"){const O=window.G7Core,k={};O?.state?.get&&(k._global=O.state.get()),n.state&&(k._local=n.state),r.detectStaleClosure?.(i,`${e.handler} → onError`,k,"callback-state-capture",i)}const D={...n,data:{...n.data,error:_}};try{const O={type:"click",handler:A.handler.handler,target:A.handler.target,params:A.handler.params,actions:A.handler.actions};return await this.executeAction(O,D),{success:!1,error:h}}catch(O){return j.error("Error executing error handler:",O),{success:!1,error:h}}}throw i&&r&&r.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),resolvedParams:c,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"error",error:{name:h.name,message:h.message,stack:h.stack}}),h}finally{if(e.handler==="apiCall"&&n.setState&&d){const f=n.state?.loadingActions||{},{[d]:h,...m}=f;n.setState({loadingActions:m})}}}async handleNavigate(e,n,r){let i=e;if(n.query||n.mergeQuery===!0)if(n.mergeQuery===!0)i=this.buildMergedQueryPath(e,n.query??{});else{const c=new URLSearchParams;for(const[f,h]of Object.entries(n.query))if(h!=null&&h!=="")if(Array.isArray(h)){const m=f.endsWith("[]")?f:`${f}[]`;for(const y of h)y!=null&&y!==""&&c.append(m,String(y))}else c.set(f,String(h));const d=c.toString();d&&(i=`${e}?${d}`)}if(j.log("handleNavigate:",{target:e,params:n,finalPath:i,replace:n.replace,windowLocationSearch:window.location.search}),n.replace===!0){const c=window.G7Core;if(c?.updateQueryParams){const d=typeof n.transition_overlay_target=="string"?n.transition_overlay_target:void 0;await c.updateQueryParams(i,d?{transitionOverlayTarget:d}:void 0),j.log("handleNavigate: Used updateQueryParams for replace mode",d?{transitionOverlayTarget:d}:void 0),this.applyScrollOption(n.scroll,n.scrollBehavior,"top");return}j.warn("handleNavigate: G7Core.updateQueryParams not available, falling back to React Router")}const l=this.resolveNavigateFallbackAction(i,n);if(l){j.warn(`handleNavigate: No route matched, falling back to "${l.handler}"`),await this.dispatchAction({type:"click",handler:l.handler,params:l.params},r),this.applyScrollOption(n.scroll,n.scrollBehavior,"top");return}if(!r.navigate)throw new jt("Navigate function is not provided in context");r.navigate(i,{replace:n.replace===!0}),this.applyScrollOption(n.scroll,n.scrollBehavior,"top")}resolveNavigateFallbackAction(e,n){const r=n.fallback;if(r===!1||n.replace===!0)return null;const l=window.__templateApp?.getRouter?.();if(!l||typeof l.match!="function"||typeof l.getRoutes=="function"&&l.getRoutes().length===0)return null;const c=e.split("?")[0];return l.match(c)?null:this.resolveNavigateFallback(r,e,n)}resolveNavigateFallback(e,n,r){return e==null?{handler:"openWindow",params:{path:n,target:"_self"}}:typeof e=="string"?{handler:e,params:{path:n}}:typeof e=="object"&&typeof e.handler=="string"?{handler:e.handler,params:{path:n,...e.params||{}}}:(j.warn("resolveNavigateFallback: unrecognized fallback option, using openWindow",e),{handler:"openWindow",params:{path:n,target:"_blank"}})}applyScrollOption(e,n,r){const i=e===void 0?r:e;if(i==="preserve")return;const l=n==="smooth"?"smooth":"instant",c=y=>{if(typeof y!="object"||y===null)return!1;const v=y;return"container"in v||"to"in v||"block"in v||"offset"in v},d=(y,v,S=0)=>{y===window?window.scrollTo({top:v,left:S,behavior:l}):y.scrollTo({top:v,left:S,behavior:l})},f=(y,v,S,_)=>{if(v===window){y.scrollIntoView({behavior:l,block:S}),_&&window.scrollBy({top:-_,left:0,behavior:l});return}const x=v,A=y.getBoundingClientRect(),D=x.getBoundingClientRect(),O=x.scrollTop+(A.top-D.top);let k;S==="center"?k=O-(x.clientHeight-y.clientHeight)/2:S==="end"?k=O-(x.clientHeight-y.clientHeight):k=O,k-=_,x.scrollTo({top:Math.max(0,k),left:0,behavior:l})},h=()=>{window.scrollTo({top:0,left:0,behavior:l});const y=document.getElementById("app")??document.body;if(!y)return;y.querySelectorAll("*").forEach(S=>{if(S.scrollTop===0&&S.scrollLeft===0)return;const _=window.getComputedStyle(S),x=_.overflowY,A=_.overflowX;(x==="auto"||x==="scroll"||A==="auto"||A==="scroll")&&S.scrollTo({top:0,left:0,behavior:l})})},m=()=>{try{if(c(i)){const y=i,v=y.block??"start",S=typeof y.offset=="number"?y.offset:0;let _=window;if(typeof y.container=="string"&&y.container.length>0){const A=document.querySelector(y.container);if(!A){j.warn(`applyScrollOption: container not found: ${y.container}`);return}_=A}const x=y.to??"top";if(x==="top"){_===window?h():d(_,0);return}if(typeof x=="number"){d(_,x-S);return}if(typeof x=="object"&&x!==null&&("x"in x||"y"in x)){const{x:A=0,y:D=0}=x;d(_,D-S,A);return}if(typeof x=="string"&&(x.startsWith("#")||x.startsWith("."))){const A=document.querySelector(x);A?f(A,_,v,S):j.warn(`applyScrollOption: target element not found: ${x}`);return}j.warn('applyScrollOption: invalid "to" value in extended form',x);return}if(i==="top"){h();return}if(typeof i=="number"){window.scrollTo({top:i,left:0,behavior:l});return}if(typeof i=="object"&&i!==null&&("x"in i||"y"in i)){const{x:y=0,y:v=0}=i;window.scrollTo({top:v,left:y,behavior:l});return}if(typeof i=="string"&&(i.startsWith("#")||i.startsWith("."))){const y=document.querySelector(i);y&&y.scrollIntoView({behavior:l,block:"start"});return}}catch(y){j.warn("applyScrollOption: failed to apply scroll",y)}};typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(m):m()}async handleOpenWindow(e,n){let r=e;if(n.query){const l=new URLSearchParams;for(const[d,f]of Object.entries(n.query))f!=null&&f!==""&&l.set(d,String(f));const c=l.toString();c&&(r=`${e}?${c}`)}const i=n.target==="_self"?"_self":"_blank";j.log("handleOpenWindow:",{target:e,params:n,finalPath:r,windowTarget:i}),i==="_self"?window.location.assign(r):window.open(r,"_blank")}async handleNavigateBack(){j.log("handleNavigateBack"),window.history.back()}async handleNavigateForward(){j.log("handleNavigateForward"),window.history.forward()}async handleReplaceUrl(e,n){let r=e;if(n.query||n.mergeQuery===!0)if(n.mergeQuery===!0)r=this.buildMergedQueryPath(e,n.query??{});else{const i=new URLSearchParams;for(const[c,d]of Object.entries(n.query))if(d!=null&&d!=="")if(Array.isArray(d)){const f=c.endsWith("[]")?c:`${c}[]`;for(const h of d)h!=null&&h!==""&&i.append(f,String(h))}else i.set(c,String(d));const l=i.toString();l&&(r=`${e}?${l}`)}j.log("handleReplaceUrl:",{target:e,params:n,finalPath:r}),window.history.replaceState(null,"",r),this.applyScrollOption(n.scroll,n.scrollBehavior,"preserve")}buildMergedQueryPath(e,n){const r=new URLSearchParams(window.location.search);for(const[c,d]of Object.entries(n))if(d==null||d==="")r.delete(c);else if(Array.isArray(d)){const f=c.endsWith("[]")?c:`${c}[]`;r.delete(c),r.delete(f);for(const h of d)h!=null&&h!==""&&r.append(f,String(h))}else r.set(c,String(d));const i=r.toString(),l=e.split("?")[0];return i?`${l}?${i}`:l}async ensureCsrfToken(){try{await fetch("/sanctum/csrf-cookie",{credentials:"include"})}catch(e){throw new jt("Failed to fetch CSRF token",void 0,e instanceof Error?e:void 0)}}getCsrfTokenFromCookie(){const r=`; ${document.cookie}`.split("; XSRF-TOKEN=");if(r.length===2){const i=r.pop()?.split(";").shift();return i?decodeURIComponent(i):null}return null}buildQueryString(e){const n=new URLSearchParams;for(const[r,i]of Object.entries(e))if(!(i==null||i===""))if(Array.isArray(i))for(const l of i)l!=null&&l!==""&&n.append(`${r}[]`,String(l));else typeof i=="object"?n.append(r,JSON.stringify(i)):n.append(r,String(i));return n.toString()}async handleEnsureIdentityVerified(e){const n=typeof e.purpose=="string"?e.purpose:"sensitive_action",r=e.target&&typeof e.target=="object"?e.target:void 0;return await At.handle({success:!1,error_code:"identity_verification_required",message:"",verification:{policy_key:e.policy_key??"",purpose:n,provider_id:e.provider_id??null,render_hint:e.render_hint??null,return_request:null}},void 0,r)!==null}handleResolveIdentityChallenge(e){const n=typeof e.result=="string"?e.result:"cancelled";let r;switch(n){case"verified":{const i=typeof e.token=="string"?e.token:"";if(!i){j.warn("resolveIdentityChallenge: result=verified 인데 token 이 비어있습니다. failed 로 강등합니다."),r={status:"failed",failureCode:"MISSING_TOKEN"};break}r={status:"verified",token:i,providerData:e.providerData&&typeof e.providerData=="object"?e.providerData:void 0};break}case"pending":{const i=typeof e.pollUrl=="string"?e.pollUrl:"",l=typeof e.expiresAt=="string"?e.expiresAt:"";if(!i||!l){j.warn("resolveIdentityChallenge: result=pending 인데 pollUrl/expiresAt 누락 — failed 로 강등합니다."),r={status:"failed",failureCode:"MALFORMED_PENDING"};break}r={status:"pending",pollUrl:i,pollIntervalMs:typeof e.pollIntervalMs=="number"?e.pollIntervalMs:void 0,expiresAt:l};break}case"failed":r={status:"failed",failureCode:typeof e.failureCode=="string"?e.failureCode:"UNKNOWN",reason:typeof e.reason=="string"?e.reason:void 0};break;default:r={status:"cancelled"};break}return At.resolveDeferred(r),!0}async handleApiCall(e,n,r,i="none",l){const{method:c="GET",body:d,headers:f,contentType:h}=n;c!=="GET"&&c!=="HEAD"&&await this.ensureCsrfToken();const m=this.getCsrfTokenFromCookie();let y={};if(i==="required"||i==="optional"){const W=qr().getToken();W&&(y={Authorization:`Bearer ${W}`})}let v=e;const S=n.query||(c==="GET"?d:null);if(S&&typeof S=="object"){const z=this.buildQueryString(S);if(z){const W=e.includes("?")?"&":"?";v=`${e}${W}${z}`}}const _=window.G7Core?.state?.getGlobal?.()||r.state?._global||{},x=window.G7Core?.state?.getLocal?.()||r.state?._local||{},A={_global:_,_local:x},D=this.getMatchingGlobalHeaders(e,A),O={};if(typeof window<"u"){const z=localStorage.getItem("g7_locale");z&&(O["Accept-Language"]=z)}const k=h==="multipart/form-data",L={method:c,headers:{...k?{}:{"Content-Type":"application/json"},Accept:"application/json",...O,...m&&{"X-XSRF-TOKEN":m},...y,...D,...f},credentials:"include"};if(d&&c!=="GET")if(k){const z=new FormData;for(const[W,de]of Object.entries(d))de instanceof File||de instanceof Blob?z.append(W,de):de!=null&&z.append(W,typeof de=="object"?JSON.stringify(de):String(de));L.body=z}else L.body=JSON.stringify(d);const B=Yn();let q=null;B?.isEnabled()&&(q=B.trackRequest(v,c));try{let z=await fetch(v,L),W;try{W=await z.json()}catch{W=null}if(At.isIdentityRequired(z.status,W)){const de=await At.handle(W,{body:L.body,headers:L.headers,credentials:L.credentials},l);if(de){z=de;try{W=await z.json()}catch{W=null}}}if(q&&B?.isEnabled()&&(B.completeRequest(q,z.status,W),q=null),!z.ok){const de=W||{},_e=new Error(de.message||`API call failed: ${z.statusText}`);throw _e.response=de,_e.status=z.status,_e.statusText=z.statusText,new jt(de.message||`API call failed: ${z.statusText}`,void 0,_e)}return W}catch(z){throw q&&B?.isEnabled()&&B.failRequest(q,z instanceof Error?z.message:String(z)),z}}async handleLogin(e,n,r){const{body:i}=n;if(!i||!i.email||!i.password)throw new jt("Login requires email and password in body params");const l=e==="user"?"user":"admin",c=l==="admin"?"/api/auth/admin/login":"/api/auth/login",d=window.G7Core?.state?.getGlobal?.()||r.state?._global||{},f=window.G7Core?.state?.getLocal?.()||r.state?._local||{},h={_global:d,_local:f},m=this.getMatchingGlobalHeaders(c,h),y=Ar.getInstance();try{const v=Object.keys(m).length>0?{headers:m}:void 0;return{user:await y.login(l,{email:i.email,password:i.password},v)}}catch(v){const S=v.message||"Login failed",_=new Error(S);throw _.response=v.response?.data||{},_.status=v.status||v.response?.status||500,new jt(S,void 0,_)}}async handleLogout(e,n){await Ar.getInstance().logout()}async handleSetState(e,n){j.log("[handleSetState] START, params:",e);const{target:r="component",scope:i,merge:l,__render:c,...d}=e,f=Yn(),h=window.G7Core;if(typeof r=="string"&&(r.startsWith("$parent.")||r.startsWith("$root.")))return this.handleParentScopeSetState(r,d,l,n);const m=n.state&&Object.keys(n.state).length>0?n.state:h?.state?.get()||{},y=r==="global"?"_global":r.startsWith("_local.")?r:"_local",v=y==="_global"?m._global:y.startsWith("_local.")?this.getNestedProperty(m._local||{},y.slice(7)):m._local,S=f?.isEnabled()?f.startStateChange(y,v,d,{actionId:n.actionId,handlerType:"setState",source:`target=${r}`}):void 0,_=l==="replace"?"replace":l==="shallow"?"shallow":"deep",x=_!=="deep"?{...d,__mergeMode:_,...S?{__setStateId:S}:{}}:{...d,...S?{__setStateId:S}:{}};if(r==="global"){if(!this.globalStateUpdater){j.warn("Global state updater is not set"),S&&f&&f.completeStateChange(S);return}const A=h?.state?.get()||{},{__setStateId:D,__mergeMode:O,...k}=x,L=_==="deep"?this.deepMergeWithState(k,A):k,B={...L,...S?{__setStateId:S}:{},..._!=="deep"?{__mergeMode:_}:{}};return j.log("setState global:",B),this.globalStateUpdater(B,{render:c}),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"global",..._!=="deep"?{__mergeMode:_}:{},...L}}else if(r==="isolated"){const A=n.isolatedContext;if(A){const{__mergeMode:D,__setStateId:O,...k}=x;return A.mergeState(k,_),j.log("[handleSetState] isolated state updated:",k,"mergeMode:",_),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"isolated",...k}}else if(j.warn('[handleSetState] isolated target used but no IsolatedStateContext found. Make sure the component has "isolatedState" attribute. Falling back to local state.'),n.setState){const O=window.__g7PendingLocalState||n.state||{},k=_==="deep"?this.deepMergeWithState(x,O):x;return this.writeLocalState(n,k),S&&f&&setTimeout(()=>f.completeStateChange(S),0),k}else throw S&&f&&f.completeStateChange(S),new jt("isolated target used but no IsolatedStateContext found and no setState function in context")}else if(r==="local"||r==="component"||r==="_local"){if(i==="parent"||i==="root"){const D=window.__g7LayoutContextStack||[];if(D.length>0){const O=i==="parent"?D[D.length-1]:D[0];if(O?.setState){const{__mergeMode:k,__setStateId:L,...B}=x,q=_==="deep"?this.deepMergeWithState(B,O.state||{}):B;return j.log(`[handleSetState] scope=${i}: 타겟 컨텍스트에 상태 업데이트`,q),O.setState(q),S&&f&&setTimeout(()=>f.completeStateChange(S),0),q}}j.warn(`[handleSetState] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const A=n.setState&&!n._isDispatchFallbackContext;if(j.log("[handleSetState] isRealComponentContext:",A,"context.setState:",!!n.setState,"_isDispatchFallbackContext:",n._isDispatchFallbackContext),A){j.log("[handleSetState] Using COMPONENT setState path"),j.log("[handleSetState] resolvedPayload:",x),j.log("[handleSetState] context.state:",n.state),j.log("[handleSetState] mergeMode:",_);const O=window.__g7PendingLocalState||n.state||{},k=_==="deep"?this.deepMergeWithState(x,{}):x;j.log("[handleSetState] convertedPayload (변경 필드만, dot notation 변환):",k),n.setState(k);const L=_==="deep"?this.deepMergeWithState(x,O):_==="shallow"?{...n.state||{},...x}:x,{__mergeMode:B,__setStateId:q,...z}=L;window.__g7PendingLocalState=z,j.log("[handleSetState] __g7PendingLocalState updated:",z);const W=(window.__g7LayoutContextStack||[]).length;let de;if(this.globalStateUpdater){const ze=W===0?window.__templateApp?.getGlobalState?.()?._local:void 0;if(_!=="replace"&&!!ze&&typeof ze=="object"&&!Array.isArray(ze)){const ue=_==="deep"?this.deepMergeWithState(x,ze):{...ze,...x},{__mergeMode:De,__setStateId:ee,...me}=ue;de=me}else _!=="replace"&&j.log("[handleSetState] canonical _local 미사용 → 전체 스냅샷 폴백",{modalDepth:W,hasTemplateApp:!!window.__templateApp});const Q=de?Mo(de,z):z;this.globalStateUpdater({_local:Q},{render:!1}),j.log("[handleSetState] _global._local synced (render:false):",Q)}const{__mergeMode:_e,__setStateId:Se,...Ie}=x;if(_==="replace")window.__g7ForcedLocalFields=Ie;else{const ze=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=this.deepMergeWithState(Ie,ze)}return j.log("[handleSetState] __g7ForcedLocalFields updated:",Ie),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"local",...de?Mo(de,z):L,..._!=="deep"?{__mergeMode:_}:{}}}else if(this.globalStateUpdater){j.log("[handleSetState] Using GLOBAL STATE UPDATER path for _local");const O=window.__g7PendingLocalState||m._local||{};j.log("[handleSetState] currentLocal (with pending):",O);const k=_==="deep"?this.deepMergeWithState(x,O):x;return j.log("[handleSetState] finalLocal (merged):",k),this.globalStateUpdater({_local:k},{render:c}),window.__g7PendingLocalState=k,j.log("[handleSetState] __g7PendingLocalState updated for globalStateUpdater path"),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"local",...k}}else throw S&&f&&f.completeStateChange(S),new jt("setState function is not provided in context and globalStateUpdater is not set")}else if(r.startsWith("_local.")){const A=r.slice(7),{__mergeMode:D,__setStateId:O,...k}=x,L=k.value!==void 0?k.value:Object.values(k)[0];if(n.setState){const q=window.__g7PendingLocalState||n.state||{},z=this.createNestedUpdate(A,L,q),W={...q,...z};if(n.setState(z),this.globalStateUpdater&&i!=="parent"&&i!=="root"){const de=window.__templateApp?.getGlobalState?.()?._local,_e=de&&typeof de=="object"?{...de,...z}:W;this.globalStateUpdater({_local:_e},{render:!1}),j.log("[handleSetState] _global._local synced for dot notation (render:false):",_e)}return S&&f&&setTimeout(()=>f.completeStateChange(S),0),W}else throw S&&f&&f.completeStateChange(S),new jt("setState function is not provided in context")}else{if(!n.setState)throw S&&f&&f.completeStateChange(S),new jt("setState function is not provided in context");const D=window.__g7PendingLocalState||n.state||{},O=_==="deep"?this.deepMergeWithState(x,D):x;return this.writeLocalState(n,O,void 0,{scope:i}),S&&f&&setTimeout(()=>f.completeStateChange(S),0),O}}async handleParentScopeSetState(e,n,r,i){const l=Yn(),c=window.G7Core,d=r==="replace"?"replace":r==="shallow"?"shallow":"deep",f=e.startsWith("$parent."),h=f?"$parent.":"$root.",m=e.slice(h.length);let y,v;if(m==="_local"||m==="_global")y=m,v=void 0;else if(m.startsWith("_local."))y="_local",v=m.slice(7);else if(m.startsWith("_global."))y="_global",v=m.slice(8);else{j.warn(`[handleParentScopeSetState] 지원하지 않는 타겟 형식: ${e}. _local 또는 _global으로 시작해야 합니다.`);return}const S=window.__g7LayoutContextStack||[];if(S.length===0){j.warn(`[handleParentScopeSetState] 레이아웃 컨텍스트 스택이 비어있습니다. target=${e}`);return}const _=f?S[S.length-1]:S[0];if(!_){j.warn(`[handleParentScopeSetState] 타겟 컨텍스트를 찾을 수 없습니다. target=${e}`);return}const x=y==="_global"?_.state?._global:_.state?._local,A=l?.isEnabled()?l.startStateChange(e,x,n,{actionId:i.actionId,handlerType:"setState",source:`target=${e}`}):void 0,{__mergeMode:D,__setStateId:O,...k}=n;if(y==="_global"){if(!this.globalStateUpdater){j.warn("[handleParentScopeSetState] globalStateUpdater가 설정되지 않았습니다."),A&&l&&l.completeStateChange(A);return}const L=c?.state?.get()||{};if(v){const B=k.value!==void 0?k.value:Object.values(k)[0],q=this.createNestedUpdate(v,B,L),z={...L,...q};j.log(`[handleParentScopeSetState] ${e}: 전역 상태 중첩 경로 업데이트`,z),this.globalStateUpdater(z)}else{const B=d==="deep"?this.deepMergeWithState(k,L):k;j.log(`[handleParentScopeSetState] ${e}: 전역 상태 업데이트 (mergeMode=${d})`,B),this.globalStateUpdater(d!=="deep"?{...B,__mergeMode:d}:B)}return A&&l&&setTimeout(()=>l.completeStateChange(A),0),{__target:e,...k}}else{if(!_.setState){j.warn(`[handleParentScopeSetState] 타겟 컨텍스트에 setState가 없습니다. target=${e}`),A&&l&&l.completeStateChange(A);return}const L=_.state||{};if(v){const B=k.value!==void 0?k.value:Object.values(k)[0],q=this.createNestedUpdate(v,B,L),z={...L,...q};return j.log(`[handleParentScopeSetState] ${e}: 로컬 상태 중첩 경로 업데이트`,q),_.setState(q),_.state=z,_.dataContext&&(_.dataContext._local=z),$f(),A&&l&&setTimeout(()=>l.completeStateChange(A),0),z}else{const B=d!=="deep"?{...k,__mergeMode:d}:k,q=d==="replace"?k:d==="shallow"?{...L,...k}:this.deepMergeWithState(k,L);return j.log(`[handleParentScopeSetState] ${e}: 로컬 상태 업데이트 (mergeMode=${d})`,q),_.setState(B),_.state=q,_.dataContext&&(_.dataContext._local=q),$f(),A&&l&&setTimeout(()=>l.completeStateChange(A),0),q}}}deepMergeWithState(e,n){const r=["errors"];let i=e;if("..."in e){const c=e["..."];if(c&&typeof c=="object"&&!Array.isArray(c)){const{"...":d,...f}=e;i={...c,...f}}else{const{"...":d,...f}=e;i=f}}const l={...n};for(const[c,d]of Object.entries(i)){if(r.includes(c)){l[c]=d;continue}if(c.includes(".")&&c!=="..."){const f=this.createNestedUpdate(c,d,l);this.deepMergeInto(l,f,l);continue}if(d!==null&&typeof d=="object"&&!Array.isArray(d)&&Object.getPrototypeOf(d)!==Object.prototype&&Object.getPrototypeOf(d)!==null){l[c]=d;continue}d!==null&&typeof d=="object"&&!Array.isArray(d)&&n[c]!==null&&typeof n[c]=="object"&&!Array.isArray(n[c])?l[c]=this.deepMergeWithState(d,n[c]):l[c]=d}return l}deepMergeInto(e,n,r){for(const[i,l]of Object.entries(n)){if(l===null){e[i]=l;continue}if(e[i]===null){e[i]=l;continue}typeof l=="object"&&!Array.isArray(l)&&e[i]!==void 0&&e[i]!==null&&typeof e[i]=="object"&&!Array.isArray(e[i])?(e[i]===r[i]&&(e[i]={...e[i]}),this.deepMergeInto(e[i],l,r[i]||{})):typeof l=="object"&&!Array.isArray(l)&&e[i]===void 0&&r[i]!==null&&typeof r[i]=="object"&&!Array.isArray(r[i])?e[i]={...r[i],...l}:e[i]=l}}createNestedUpdate(e,n,r){const i=e.split(".");if(i.length===1)return{[i[0]]:n};const l={};let c=l,d=r;for(let f=0;f{this.globalStateUpdater({_local:S})};m.push({state:y,setState:v,dataContext:{_local:y||n.data?._local,_global:l?n.data?._global:n.data?._global||i?.state?.get?.(),_computed:n.data?._computed}}),window.__g7LayoutContextStack=m,j.log(`[handleOpenModal] 레이아웃 컨텍스트 스택에 push, 스택 크기: ${m.length}, state:`,y,l?"(direct)":"(fallback via G7Core)")}else j.warn(`[handleOpenModal] 컨텍스트 스택에 push 실패 - setState: ${!!n.setState}, state: ${n.state!==void 0}, G7Core: ${!!i?.state?.getLocal}`);const f=[...r,e];this.globalStateUpdater({modalStack:f,activeModal:e});const h=Yn();if(h?.isEnabled()){const m=r.length>0?r[r.length-1]:void 0;h.trackModalOpen?.({modalId:e,modalName:e,scopeType:"isolated",parentModalId:m,initialState:n.state?{...n.state}:{}})}}async handleCloseModal(e){if(!this.globalStateUpdater){j.warn("Global state updater is not set for closeModal");return}const n=e?.data?._global?.modalStack||[],r=n.length>0?n[n.length-1]:null,i=n.slice(0,-1),l=i.length>0?i[i.length-1]:null,c=window.__g7LayoutContextStack||[];if(c.length>0){const d=c[c.length-1];d&&(d.dataContext=void 0),c.pop(),window.__g7LayoutContextStack=c,j.log(`[handleCloseModal] 레이아웃 컨텍스트 스택에서 pop, 스택 크기: ${c.length}`)}if(r){const d=Yn();d?.isEnabled()&&d.trackModalClose?.(r,e?.state)}this.globalStateUpdater({modalStack:i,activeModal:l})}async handleShowAlert(e,n){let r=e;this.translationEngine&&this.translationContext&&e.startsWith("$t:")&&(r=this.translationEngine.resolveTranslations(e,this.translationContext,n.data)),alert(r)}async handleToast(e,n){const{type:r="info",message:i,icon:l,duration:c}=e;if(r==="error"){const f=n.data?.error;if((f?.error_code==="identity_verification_required"||f?.data?.error_code==="identity_verification_required")&&At.consumeDomainNoticeShown()){j.log("[Toast] IDV 도메인 안내 표출됨 — 중복 가드 토스트 1건 skip");return}}let d=i;if(this.translationEngine&&this.translationContext&&i?.startsWith("$t:")&&(d=this.translationEngine.resolveTranslations(i,this.translationContext,n.data)),this.globalStateUpdater){const h={id:`toast_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,type:r,message:d,...l&&{icon:l},...c&&{duration:c}},S=[...window.G7Core?.state?.get()?.toasts||[],h];this.globalStateUpdater({toasts:S})}else j.log(`[Toast ${r}] ${d}`)}async handleSwitch(e,n){const{cases:r}=e;if(!r){j.warn("switch handler requires cases property");return}const i=this.resolveParams(e.params,n.data);let l;if(i?.value!==void 0?(l=i.value,j.log("switch handler: using params.value as case key:",l)):(l=n.data?.$args?.[0],j.log("switch handler: using $args[0] as case key:",l)),l==null){if(r.default)return j.log("switch handler: case key is undefined, using default case"),await this.executeAction(r.default,n);j.warn("switch handler: case key is not defined and no default case");return}const c=String(l);let d=r[c];if(!d&&r.default&&(j.log(`switch handler: no case found for key "${c}", using default case`),d=r.default),!d){j.warn(`switch handler: no case found for key "${c}" and no default case`);return}return await this.executeAction(d,n)}async handleConditions(e,n){const{conditions:r}=e;if(!r||!Array.isArray(r)){j.warn("conditions handler requires conditions array");return}const i=n.data||{},l=fm(r,i,this.bindingEngine);if(!l.matched){j.log("conditions handler: no matching branch found");return}const c=r[l.branchIndex];if(j.log(`conditions handler: matched branch ${l.branchIndex}`),!c.then){j.warn('conditions handler: matched branch has no "then" action');return}return Array.isArray(c.then)?await this.handleSequence({...e,actions:c.then},n):await this.executeAction(c.then,n)}handleStartInterval(e,n){const r=typeof e.id=="string"?e.id:"",i=Number(e.intervalMs??1e3),l=Array.isArray(e.actions)?e.actions:[];if(r===""||!l.length||i<=0)return j.warn("startInterval requires non-empty id, positive intervalMs, and actions array"),{success:!1};const c=this.intervals.get(r);c&&(clearInterval(c),this.intervals.delete(r));const d=setInterval(()=>{for(const f of l)this.executeAction(f,n).catch(h=>{j.error(`[startInterval:${r}] tick action failed`,h)})},i);return this.intervals.set(r,d),{success:!0,id:r}}handleStopInterval(e){const n=typeof e.id=="string"?e.id:"";if(n==="")return j.warn("stopInterval requires id parameter"),{success:!1};const r=this.intervals.get(n);return r&&(clearInterval(r),this.intervals.delete(n)),{success:!0,id:n}}stopAllIntervals(){for(const e of this.intervals.values())clearInterval(e);this.intervals.clear()}async handleSequence(e,n){const r=e.actions||e.params?.actions;if(!r||!Array.isArray(r)||r.length===0)return j.warn("sequence handler requires non-empty actions array"),[];const i=Yn(),l=i?.isEnabled()&&i.startSequenceExecution?.({eventType:e.type})||"";window.__g7SequenceLocalSync=void 0;const c=[];let d,f=n.state?{...n.state}:{},h=n.isolatedContext?.state?{...n.isolatedContext.state}:{},m=n.data?._computed||{};const y=window.G7Core,v=()=>({_global:y?.state?.get()||{},_local:{...f},_isolated:Object.keys(h).length>0?{...h}:void 0});for(let S=0;S0){const k={},L={...n.data,_local:f,_computed:k,$computed:k,_isolated:h};for(const[B,q]of Object.entries(O))if(typeof q=="string"){const z=q.trim();if(z.startsWith("{{")&&z.endsWith("}}"))try{const W=z.slice(2,-2).trim();k[B]=Wn(W)?this.bindingEngine.evaluatePipeExpression(W,L,{skipCache:!0}):this.bindingEngine.evaluateExpression(W,L,{skipCache:!0})}catch{k[B]=m[B]}}m=k,j.log("[handleSequence] _computed recalculated after setState:",m)}}if(_.handler!=="setState"){const O=window.__g7SequenceLocalSync;if(O&&O!==f){f=O,window.__g7SequenceLocalSync=void 0,j.log("[handleSequence] currentState synchronized from __g7SequenceLocalSync after custom handler:",_.handler);const k=n.data?._computedDefinitions;if(k&&Object.keys(k).length>0){const L={},B={...n.data,_local:f,_computed:L,$computed:L,_isolated:h};for(const[q,z]of Object.entries(k))if(typeof z=="string"){const W=z.trim();if(W.startsWith("{{")&&W.endsWith("}}"))try{const de=W.slice(2,-2).trim();L[q]=Wn(de)?this.bindingEngine.evaluatePipeExpression(de,B,{skipCache:!0}):this.bindingEngine.evaluateExpression(de,B,{skipCache:!0})}catch{L[q]=m[q]}}m=L,j.log("[handleSequence] _computed recalculated after custom handler:",m)}}}l&&i?.isEnabled()&&i.captureSequenceActionAfter?.(l,S,v(),Date.now()-x,D.data)}catch(D){throw l&&i?.isEnabled()&&(i.captureSequenceActionAfter?.(l,S,v(),Date.now()-x,void 0,D),i.endSequenceExecution?.(l,D)),j.error(`sequence handler: action[${S}] failed:`,D),D}}return window.__g7SequenceLocalSync=void 0,l&&i?.isEnabled()&&i.endSequenceExecution?.(l),c}async handleParallel(e,n){const r=e.actions||e.params?.actions;if(!r||!Array.isArray(r)||r.length===0)return j.warn("parallel handler requires non-empty actions array"),[];j.log(`parallel handler: executing ${r.length} actions in parallel`);const i=n.isolatedContext?{...n.isolatedContext,state:{...n.isolatedContext.state}}:null,l=r.map((f,h)=>{const m={...n,isolatedContext:i};return this.executeAction(f,m).catch(y=>{throw j.error(`parallel handler: action[${h}] failed:`,y),y})}),c=await Promise.allSettled(l),d=c.filter(f=>f.status==="rejected").length;return d>0&&j.warn(`parallel handler: ${d}/${r.length} actions failed`),c}assertAllowedExtensionAssetUrl(e,n,r){if(!Io(e,bs()))throw j.error(`Blocked untrusted ${n} asset url: ${e}`),new jt(`Blocked untrusted ${n} url (same-origin path or declared trusted host required): ${e}`,r)}async handleLoadScript(e,n,r){const{src:i,id:l,async:c=!0,defer:d=!1}=e;if(!i)throw new jt('loadScript handler requires "src" parameter',n);if(!Io(i,bs()))throw j.warn(`loadScript: blocked untrusted script src (same-origin path or declared trusted host required): ${i}`),new jt(`Blocked untrusted script src (same-origin path or declared trusted host required): ${i}`,n);const f=l||`script_${i.replace(/[^a-zA-Z0-9]/g,"_")}`;if(cn.loadedScripts.has(f))return j.log(`loadScript: script already loaded, skipping: ${f}`),n.onLoad&&await this.executeAction(n.onLoad,r),!0;const h=cn.loadingScripts.get(f);if(h)return j.log(`loadScript: joining in-flight load: ${f}`),await h,n.onLoad&&await this.executeAction(n.onLoad,r),!0;if(document.getElementById(f))return j.log(`loadScript: script element already exists: ${f}`),cn.loadedScripts.add(f),n.onLoad&&await this.executeAction(n.onLoad,r),!0;j.log(`loadScript: loading script: ${i}`);const y=document.createElement("script");if(y.id=f,y.src=i,y.async=c,y.defer=d,y.hasAttribute("data-gdpr-blocked-src"))return j.warn(`loadScript: script blocked by consent manager (not loaded): ${i}`),!1;const v=new Promise((S,_)=>{y.onload=()=>{j.log(`loadScript: script loaded successfully: ${f}`),cn.loadedScripts.add(f),cn.loadingScripts.delete(f),S()},y.onerror=x=>{j.error(`loadScript: failed to load script: ${i}`,x),cn.loadingScripts.delete(f),_(new jt(`Failed to load script: ${i}`,n))},document.head.appendChild(y)});if(v.catch(()=>{}),cn.loadingScripts.set(f,v),await v,n.onLoad)try{await this.executeAction(n.onLoad,r)}catch(S){j.error("loadScript: onLoad action failed:",S)}return!0}async handleCallExternal(e,n,r){const i=e.constructor,l=e.args||{},c=e.method,d=e.methodArgs||[],f=e.callbackEvent,h=e.embedTarget,m=e.callbackSetState,y=e.callbackAction;if(!i)throw new jt('callExternal handler requires "constructor" parameter',n);const v=this.getNestedProperty(window,i);if(!v||typeof v!="function")throw new jt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first using loadScript handler.`,n);this.assertCallableExternalConstructor(v,i,n),j.log(`callExternal: calling constructor ${i}`);const S={...l};for(const[x,A]of Object.entries(l))A===!0&&(S[x]=D=>{if(j.log(`callExternal: callback triggered for ${x}`,D),f&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(f,D),m&&r.setState){const O=B=>{const q={};for(const[z,W]of Object.entries(B)){if(cn.isPrototypePathSegment(z)){j.warn(`callExternal: skipped prototype-polluting mapping key: ${z}`);continue}typeof W=="string"?q[z]=this.getNestedProperty(D,W):typeof W=="object"&&W!==null&&(q[z]=O(W))}return q},k=O(m);j.log("callExternal: callbackSetState mapping result",k);const L=this.deepMergeWithState(k,r.state||{});j.log("callExternal: merged with existing state",L),this.writeLocalState(r,L)}else f&&r.setState&&this.writeLocalState(r,{[`${f.replace(/:/g,"_")}_result`]:D});if(y){const O={...r,data:{...r.data,$event:D}},k=Array.isArray(y)?y:[y];for(const L of k)try{this.executeAction(L,O)}catch(B){j.error("callExternal: callbackAction failed:",B)}}});const _=new v(S);if(c&&typeof _[c]=="function"){if(j.log(`callExternal: calling method ${c}`),c==="embed"&&h){const x=document.querySelector(h);if(x)return _[c](x,...d);throw new jt(`Embed target element not found: ${h}`,n)}return _[c](...d)}return _}async handleCallExternalEmbed(e,n,r){const i=e.constructor,l=e.args||{},c=e.callbackSetState,d=e.callbackEvent,f=e.layerClassName,h=e.callbackAction;if(!i)throw new jt('callExternalEmbed handler requires "constructor" parameter',n);const m=this.getNestedProperty(window,i);if(!m||typeof m!="function")throw new jt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first.`,n);this.assertCallableExternalConstructor(m,i,n),j.log(`callExternalEmbed: creating layer for ${i}`);const{layer:y,closeLayer:v}=this.createEmbedLayer(f),S={...l};for(const[x,A]of Object.entries(l))A===!0&&(S[x]=D=>{if(j.log(`callExternalEmbed: callback triggered for ${x}`,D),v(),d&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(d,D),c&&r.setState){const O=B=>{const q={};for(const[z,W]of Object.entries(B)){if(cn.isPrototypePathSegment(z)){j.warn(`callExternal: skipped prototype-polluting mapping key: ${z}`);continue}typeof W=="string"?q[z]=this.getNestedProperty(D,W):typeof W=="object"&&W!==null&&(q[z]=O(W))}return q},k=O(c);j.log("callExternalEmbed: callbackSetState mapping result",k);const L=this.deepMergeWithState(k,r.state||{});j.log("callExternalEmbed: merged with existing state",L),this.writeLocalState(r,L)}if(h){const O={...r,data:{...r.data,$event:D}},k=Array.isArray(h)?h:[h];for(const L of k)try{this.executeAction(L,O)}catch(B){j.error("callExternalEmbed: callbackAction failed:",B)}}});const _=new m(S);if(typeof _.embed=="function")_.embed(y),j.log("callExternalEmbed: embedded in layer");else throw v(),new jt(`Constructor ${i} does not have embed method`,n);return _}isImeComposing(e){return e?.isComposing===!0||e?.keyCode===229}createEmbedLayer(e){const n=document.createElement("div");n.id="g7-embed-overlay",n.style.cssText=` +`+u.stack}}var En=Object.prototype.hasOwnProperty,dn=s.unstable_scheduleCallback,pn=s.unstable_cancelCallback,fr=s.unstable_shouldYield,er=s.unstable_requestPaint,Pt=s.unstable_now,St=s.unstable_getCurrentPriorityLevel,da=s.unstable_ImmediatePriority,In=s.unstable_UserBlockingPriority,kn=s.unstable_NormalPriority,Rn=s.unstable_LowPriority,jn=s.unstable_IdlePriority,gn=s.log,fa=s.unstable_setDisableYieldValue,zn=null,Vt=null;function _n(t){if(typeof gn=="function"&&fa(t),Vt&&typeof Vt.setStrictMode=="function")try{Vt.setStrictMode(zn,t)}catch{}}var an=Math.clz32?Math.clz32:ce,q=Math.log,oe=Math.LN2;function ce(t){return t>>>=0,t===0?32:31-(q(t)/oe|0)|0}var J=256,ve=262144,ue=4194304;function we(t){var a=t&42;if(a!==0)return a;switch(t&-t){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 t&261888;case 262144:case 524288:case 1048576:case 2097152:return t&3932160;case 4194304:case 8388608:case 16777216:case 33554432:return t&62914560;case 67108864:return 67108864;case 134217728:return 134217728;case 268435456:return 268435456;case 536870912:return 536870912;case 1073741824:return 0;default:return t}}function _e(t,a,o){var u=t.pendingLanes;if(u===0)return 0;var h=0,g=t.suspendedLanes,E=t.pingedLanes;t=t.warmLanes;var k=u&134217727;return k!==0?(u=k&~g,u!==0?h=we(u):(E&=k,E!==0?h=we(E):o||(o=k&~t,o!==0&&(h=we(o))))):(k=u&~g,k!==0?h=we(k):E!==0?h=we(E):o||(o=u&~t,o!==0&&(h=we(o)))),h===0?0:a!==0&&a!==h&&(a&g)===0&&(g=h&-h,o=a&-a,g>=o||g===32&&(o&4194048)!==0)?a:h}function qe(t,a){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&a)===0}function xe(t,a){switch(t){case 1:case 2:case 4:case 8:case 64:return a+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 a+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 De(){var t=ue;return ue<<=1,(ue&62914560)===0&&(ue=4194304),t}function Ae(t){for(var a=[],o=0;31>o;o++)a.push(t);return a}function tt(t,a){t.pendingLanes|=a,a!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function Ne(t,a,o,u,h,g){var E=t.pendingLanes;t.pendingLanes=o,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=o,t.entangledLanes&=o,t.errorRecoveryDisabledLanes&=o,t.shellSuspendCounter=0;var k=t.entanglements,H=t.expirationTimes,Y=t.hiddenUpdates;for(o=E&~o;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var Ni=/[\n"\\]/g;function Bn(t){return t.replace(Ni,function(a){return"\\"+a.charCodeAt(0).toString(16)+" "})}function ma(t,a,o,u,h,g,E,k){t.name="",E!=null&&typeof E!="function"&&typeof E!="symbol"&&typeof E!="boolean"?t.type=E:t.removeAttribute("type"),a!=null?E==="number"?(a===0&&t.value===""||t.value!=a)&&(t.value=""+Pn(a)):t.value!==""+Pn(a)&&(t.value=""+Pn(a)):E!=="submit"&&E!=="reset"||t.removeAttribute("value"),a!=null?rl(t,E,Pn(a)):o!=null?rl(t,E,Pn(o)):u!=null&&t.removeAttribute("value"),h==null&&g!=null&&(t.defaultChecked=!!g),h!=null&&(t.checked=h&&typeof h!="function"&&typeof h!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?t.name=""+Pn(k):t.removeAttribute("name")}function nu(t,a,o,u,h,g,E,k){if(g!=null&&typeof g!="function"&&typeof g!="symbol"&&typeof g!="boolean"&&(t.type=g),a!=null||o!=null){if(!(g!=="submit"&&g!=="reset"||a!=null)){tl(t);return}o=o!=null?""+Pn(o):"",a=a!=null?""+Pn(a):o,k||a===t.value||(t.value=a),t.defaultValue=a}u=u??h,u=typeof u!="function"&&typeof u!="symbol"&&!!u,t.checked=k?t.checked:!!u,t.defaultChecked=!!u,E!=null&&typeof E!="function"&&typeof E!="symbol"&&typeof E!="boolean"&&(t.name=E),tl(t)}function rl(t,a,o){a==="number"&&ga(t.ownerDocument)===t||t.defaultValue===""+o||(t.defaultValue=""+o)}function Va(t,a,o,u){if(t=t.options,a){a={};for(var h=0;h"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),ol=!1;if(Ir)try{var ji={};Object.defineProperty(ji,"passive",{get:function(){ol=!0}}),window.addEventListener("test",ji,ji),window.removeEventListener("test",ji,ji)}catch{ol=!1}var jr=null,ll=null,Ls=null;function Fe(){if(Ls)return Ls;var t,a=ll,o=a.length,u,h="value"in jr?jr.value:jr.textContent,g=h.length;for(t=0;t=ct),du=" ",pl=!1;function fu(t,a){switch(t){case"keyup":return Ve.indexOf(a.keyCode)!==-1;case"keydown":return a.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function gl(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Ja=!1;function hu(t,a){switch(t){case"compositionend":return gl(a);case"keypress":return a.which!==32?null:(pl=!0,du);case"textInput":return t=a.data,t===du&&pl?null:t;default:return null}}function Ch(t,a){if(Ja)return t==="compositionend"||!it&&fu(t,a)?(t=Fe(),Ls=ll=jr=null,Ja=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(a.ctrlKey||a.altKey||a.metaKey)||a.ctrlKey&&a.altKey){if(a.char&&1=a)return{node:o,offset:a-t};t=u}e:{for(;o;){if(o.nextSibling){o=o.nextSibling;break e}o=o.parentNode}o=void 0}o=yb(o)}}function vb(t,a){return t&&a?t===a?!0:t&&t.nodeType===3?!1:a&&a.nodeType===3?vb(t,a.parentNode):"contains"in t?t.contains(a):t.compareDocumentPosition?!!(t.compareDocumentPosition(a)&16):!1:!1}function Sb(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var a=ga(t.document);a instanceof t.HTMLIFrameElement;){try{var o=typeof a.contentWindow.location.href=="string"}catch{o=!1}if(o)t=a.contentWindow;else break;a=ga(t.document)}return a}function _h(t){var a=t&&t.nodeName&&t.nodeName.toLowerCase();return a&&(a==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||a==="textarea"||t.contentEditable==="true")}var Wx=Ir&&"documentMode"in document&&11>=document.documentMode,Is=null,Ah=null,El=null,xh=!1;function wb(t,a,o){var u=o.window===o?o.document:o.nodeType===9?o:o.ownerDocument;xh||Is==null||Is!==ga(u)||(u=Is,"selectionStart"in u&&_h(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}),El&&Cl(El,u)||(El=u,u=rd(Ah,"onSelect"),0>=E,h-=E,Zr=1<<32-an(a)+h|o<Qe?(ot=Le,Le=null):ot=Le.sibling;var pt=Q(V,Le,W[Qe],se);if(pt===null){Le===null&&(Le=ot);break}t&&Le&&pt.alternate===null&&a(V,Le),B=g(pt,B,Qe),ht===null?Ie=pt:ht.sibling=pt,ht=pt,Le=ot}if(Qe===W.length)return o(V,Le),ut&&Sa(V,Qe),Ie;if(Le===null){for(;QeQe?(ot=Le,Le=null):ot=Le.sibling;var Si=Q(V,Le,pt.value,se);if(Si===null){Le===null&&(Le=ot);break}t&&Le&&Si.alternate===null&&a(V,Le),B=g(Si,B,Qe),ht===null?Ie=Si:ht.sibling=Si,ht=Si,Le=ot}if(pt.done)return o(V,Le),ut&&Sa(V,Qe),Ie;if(Le===null){for(;!pt.done;Qe++,pt=W.next())pt=le(V,pt.value,se),pt!==null&&(B=g(pt,B,Qe),ht===null?Ie=pt:ht.sibling=pt,ht=pt);return ut&&Sa(V,Qe),Ie}for(Le=u(Le);!pt.done;Qe++,pt=W.next())pt=te(Le,V,Qe,pt.value,se),pt!==null&&(t&&pt.alternate!==null&&Le.delete(pt.key===null?Qe:pt.key),B=g(pt,B,Qe),ht===null?Ie=pt:ht.sibling=pt,ht=pt);return t&&Le.forEach(function(pk){return a(V,pk)}),ut&&Sa(V,Qe),Ie}function xt(V,B,W,se){if(typeof W=="object"&&W!==null&&W.type===x&&W.key===null&&(W=W.props.children),typeof W=="object"&&W!==null){switch(W.$$typeof){case S:e:{for(var Ie=W.key;B!==null;){if(B.key===Ie){if(Ie=W.type,Ie===x){if(B.tag===7){o(V,B.sibling),se=h(B,W.props.children),se.return=V,V=se;break e}}else if(B.elementType===Ie||typeof Ie=="object"&&Ie!==null&&Ie.$$typeof===K&&Yi(Ie)===B.type){o(V,B.sibling),se=h(B,W.props),Rl(se,W),se.return=V,V=se;break e}o(V,B);break}else a(V,B);B=B.sibling}W.type===x?(se=Gi(W.props.children,V.mode,se,W.key),se.return=V,V=se):(se=Su(W.type,W.key,W.props,null,V.mode,se),Rl(se,W),se.return=V,V=se)}return E(V);case v:e:{for(Ie=W.key;B!==null;){if(B.key===Ie)if(B.tag===4&&B.stateNode.containerInfo===W.containerInfo&&B.stateNode.implementation===W.implementation){o(V,B.sibling),se=h(B,W.children||[]),se.return=V,V=se;break e}else{o(V,B);break}else a(V,B);B=B.sibling}se=$h(W,V.mode,se),se.return=V,V=se}return E(V);case K:return W=Yi(W),xt(V,B,W,se)}if(bt(W))return Te(V,B,W,se);if(ze(W)){if(Ie=ze(W),typeof Ie!="function")throw Error(r(150));return W=Ie.call(W),Ue(V,B,W,se)}if(typeof W.then=="function")return xt(V,B,Tu(W),se);if(W.$$typeof===O)return xt(V,B,Eu(V,W),se);ku(V,W)}return typeof W=="string"&&W!==""||typeof W=="number"||typeof W=="bigint"?(W=""+W,B!==null&&B.tag===6?(o(V,B.sibling),se=h(B,W),se.return=V,V=se):(o(V,B),se=Lh(W,V.mode,se),se.return=V,V=se),E(V)):o(V,B)}return function(V,B,W,se){try{kl=0;var Ie=xt(V,B,W,se);return Ks=null,Ie}catch(Le){if(Le===Vs||Le===Au)throw Le;var ht=nr(29,Le,null,V.mode);return ht.lanes=se,ht.return=V,ht}finally{}}}var Ji=Gb(!0),Fb=Gb(!1),ri=!1;function Fh(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Vh(t,a){t=t.updateQueue,a.updateQueue===t&&(a.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function ai(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function ii(t,a,o){var u=t.updateQueue;if(u===null)return null;if(u=u.shared,(mt&2)!==0){var h=u.pending;return h===null?a.next=a:(a.next=h.next,h.next=a),u.pending=a,a=vu(t),kb(t,null,o),a}return bu(t,u,a,o),vu(t)}function Dl(t,a,o){if(a=a.updateQueue,a!==null&&(a=a.shared,(o&4194048)!==0)){var u=a.lanes;u&=t.pendingLanes,o|=u,a.lanes=o,Se(t,o)}}function Kh(t,a){var o=t.updateQueue,u=t.alternate;if(u!==null&&(u=u.updateQueue,o===u)){var h=null,g=null;if(o=o.firstBaseUpdate,o!==null){do{var E={lane:o.lane,tag:o.tag,payload:o.payload,callback:null,next:null};g===null?h=g=E:g=g.next=E,o=o.next}while(o!==null);g===null?h=g=a:g=g.next=a}else h=g=a;o={baseState:u.baseState,firstBaseUpdate:h,lastBaseUpdate:g,shared:u.shared,callbacks:u.callbacks},t.updateQueue=o;return}t=o.lastBaseUpdate,t===null?o.firstBaseUpdate=a:t.next=a,o.lastBaseUpdate=a}var Wh=!1;function Ol(){if(Wh){var t=Fs;if(t!==null)throw t}}function Ll(t,a,o,u){Wh=!1;var h=t.updateQueue;ri=!1;var g=h.firstBaseUpdate,E=h.lastBaseUpdate,k=h.shared.pending;if(k!==null){h.shared.pending=null;var H=k,Y=H.next;H.next=null,E===null?g=Y:E.next=Y,E=H;var ne=t.alternate;ne!==null&&(ne=ne.updateQueue,k=ne.lastBaseUpdate,k!==E&&(k===null?ne.firstBaseUpdate=Y:k.next=Y,ne.lastBaseUpdate=H))}if(g!==null){var le=h.baseState;E=0,ne=Y=H=null,k=g;do{var Q=k.lane&-536870913,te=Q!==k.lane;if(te?(st&Q)===Q:(u&Q)===Q){Q!==0&&Q===Gs&&(Wh=!0),ne!==null&&(ne=ne.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Te=t,Ue=k;Q=a;var xt=o;switch(Ue.tag){case 1:if(Te=Ue.payload,typeof Te=="function"){le=Te.call(xt,le,Q);break e}le=Te;break e;case 3:Te.flags=Te.flags&-65537|128;case 0:if(Te=Ue.payload,Q=typeof Te=="function"?Te.call(xt,le,Q):Te,Q==null)break e;le=y({},le,Q);break e;case 2:ri=!0}}Q=k.callback,Q!==null&&(t.flags|=64,te&&(t.flags|=8192),te=h.callbacks,te===null?h.callbacks=[Q]:te.push(Q))}else te={lane:Q,tag:k.tag,payload:k.payload,callback:k.callback,next:null},ne===null?(Y=ne=te,H=le):ne=ne.next=te,E|=Q;if(k=k.next,k===null){if(k=h.shared.pending,k===null)break;te=k,k=te.next,te.next=null,h.lastBaseUpdate=te,h.shared.pending=null}}while(!0);ne===null&&(H=le),h.baseState=H,h.firstBaseUpdate=Y,h.lastBaseUpdate=ne,g===null&&(h.shared.lanes=0),ui|=E,t.lanes=E,t.memoizedState=le}}function Vb(t,a){if(typeof t!="function")throw Error(r(191,t));t.call(a)}function Kb(t,a){var o=t.callbacks;if(o!==null)for(t.callbacks=null,t=0;tg?g:8;var E=X.T,k={};X.T=k,hp(t,!1,a,o);try{var H=h(),Y=X.S;if(Y!==null&&Y(k,H),H!==null&&typeof H=="object"&&typeof H.then=="function"){var ne=rT(H,u);Nl(t,a,ne,or(t))}else Nl(t,a,u,or(t))}catch(le){Nl(t,a,{then:function(){},status:"rejected",reason:le},or())}finally{de.p=g,E!==null&&k.types!==null&&(E.types=k.types),X.T=E}}function cT(){}function dp(t,a,o,u){if(t.tag!==5)throw Error(r(476));var h=Av(t).queue;_v(t,h,a,Ce,o===null?cT:function(){return xv(t),o(u)})}function Av(t){var a=t.memoizedState;if(a!==null)return a;a={memoizedState:Ce,baseState:Ce,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_a,lastRenderedState:Ce},next:null};var o={};return a.next={memoizedState:o,baseState:o,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:_a,lastRenderedState:o},next:null},t.memoizedState=a,t=t.alternate,t!==null&&(t.memoizedState=a),a}function xv(t){var a=Av(t);a.next===null&&(a=t.alternate.memoizedState),Nl(t,a.next.queue,{},or())}function fp(){return bn(Ql)}function Tv(){return Wt().memoizedState}function kv(){return Wt().memoizedState}function uT(t){for(var a=t.return;a!==null;){switch(a.tag){case 24:case 3:var o=or();t=ai(o);var u=ii(a,t,o);u!==null&&(Kn(u,a,o),Dl(u,a,o)),a={cache:Ph()},t.payload=a;return}a=a.return}}function dT(t,a,o){var u=or();o={lane:u,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null},zu(t)?Dv(a,o):(o=Dh(t,a,o,u),o!==null&&(Kn(o,t,u),Ov(o,a,u)))}function Rv(t,a,o){var u=or();Nl(t,a,o,u)}function Nl(t,a,o,u){var h={lane:u,revertLane:0,gesture:null,action:o,hasEagerState:!1,eagerState:null,next:null};if(zu(t))Dv(a,h);else{var g=t.alternate;if(t.lanes===0&&(g===null||g.lanes===0)&&(g=a.lastRenderedReducer,g!==null))try{var E=a.lastRenderedState,k=g(E,o);if(h.hasEagerState=!0,h.eagerState=k,tr(k,E))return bu(t,a,h,0),Rt===null&&yu(),!1}catch{}finally{}if(o=Dh(t,a,h,u),o!==null)return Kn(o,t,u),Ov(o,a,u),!0}return!1}function hp(t,a,o,u){if(u={lane:2,revertLane:Fp(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},zu(t)){if(a)throw Error(r(479))}else a=Dh(t,o,u,2),a!==null&&Kn(a,t,2)}function zu(t){var a=t.alternate;return t===Xe||a!==null&&a===Xe}function Dv(t,a){Ys=Ou=!0;var o=t.pending;o===null?a.next=a:(a.next=o.next,o.next=a),t.pending=a}function Ov(t,a,o){if((o&4194048)!==0){var u=a.lanes;u&=t.pendingLanes,o|=u,a.lanes=o,Se(t,o)}}var Il={readContext:bn,use:Mu,useCallback:qt,useContext:qt,useEffect:qt,useImperativeHandle:qt,useLayoutEffect:qt,useInsertionEffect:qt,useMemo:qt,useReducer:qt,useRef:qt,useState:qt,useDebugValue:qt,useDeferredValue:qt,useTransition:qt,useSyncExternalStore:qt,useId:qt,useHostTransitionStatus:qt,useFormState:qt,useActionState:qt,useOptimistic:qt,useMemoCache:qt,useCacheRefresh:qt};Il.useEffectEvent=qt;var Lv={readContext:bn,use:Mu,useCallback:function(t,a){return Dn().memoizedState=[t,a===void 0?null:a],t},useContext:bn,useEffect:gv,useImperativeHandle:function(t,a,o){o=o!=null?o.concat([t]):null,Iu(4194308,4,vv.bind(null,a,t),o)},useLayoutEffect:function(t,a){return Iu(4194308,4,t,a)},useInsertionEffect:function(t,a){Iu(4,2,t,a)},useMemo:function(t,a){var o=Dn();a=a===void 0?null:a;var u=t();if(Qi){_n(!0);try{t()}finally{_n(!1)}}return o.memoizedState=[u,a],u},useReducer:function(t,a,o){var u=Dn();if(o!==void 0){var h=o(a);if(Qi){_n(!0);try{o(a)}finally{_n(!1)}}}else h=a;return u.memoizedState=u.baseState=h,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:h},u.queue=t,t=t.dispatch=dT.bind(null,Xe,t),[u.memoizedState,t]},useRef:function(t){var a=Dn();return t={current:t},a.memoizedState=t},useState:function(t){t=sp(t);var a=t.queue,o=Rv.bind(null,Xe,a);return a.dispatch=o,[t.memoizedState,o]},useDebugValue:cp,useDeferredValue:function(t,a){var o=Dn();return up(o,t,a)},useTransition:function(){var t=sp(!1);return t=_v.bind(null,Xe,t.queue,!0,!1),Dn().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,a,o){var u=Xe,h=Dn();if(ut){if(o===void 0)throw Error(r(407));o=o()}else{if(o=a(),Rt===null)throw Error(r(349));(st&127)!==0||Zb(u,a,o)}h.memoizedState=o;var g={value:o,getSnapshot:a};return h.queue=g,gv(tv.bind(null,u,g,t),[t]),u.flags|=2048,Js(9,{destroy:void 0},ev.bind(null,u,g,o,a),null),o},useId:function(){var t=Dn(),a=Rt.identifierPrefix;if(ut){var o=ea,u=Zr;o=(u&~(1<<32-an(u)-1)).toString(32)+o,a="_"+a+"R_"+o,o=Lu++,0<\/script>",g=g.removeChild(g.firstChild);break;case"select":g=typeof u.is=="string"?E.createElement("select",{is:u.is}):E.createElement("select"),u.multiple?g.multiple=!0:u.size&&(g.size=u.size);break;default:g=typeof u.is=="string"?E.createElement(h,{is:u.is}):E.createElement(h)}}g[jt]=a,g[mn]=u;e:for(E=a.child;E!==null;){if(E.tag===5||E.tag===6)g.appendChild(E.stateNode);else if(E.tag!==4&&E.tag!==27&&E.child!==null){E.child.return=E,E=E.child;continue}if(E===a)break e;for(;E.sibling===null;){if(E.return===null||E.return===a)break e;E=E.return}E.sibling.return=E.return,E=E.sibling}a.stateNode=g;e:switch(Sn(g,h,u),h){case"button":case"input":case"select":case"textarea":u=!!u.autoFocus;break e;case"img":u=!0;break e;default:u=!1}u&&xa(a)}}return $t(a),Tp(a,a.type,t===null?null:t.memoizedProps,a.pendingProps,o),null;case 6:if(t&&a.stateNode!=null)t.memoizedProps!==u&&xa(a);else{if(typeof u!="string"&&a.stateNode===null)throw Error(r(166));if(t=ae.current,Bs(a)){if(t=a.stateNode,o=a.memoizedProps,u=null,h=yn,h!==null)switch(h.tag){case 27:case 5:u=h.memoizedProps}t[jt]=a,t=!!(t.nodeValue===o||u!==null&&u.suppressHydrationWarning===!0||JS(t.nodeValue,o)),t||ti(a,!0)}else t=ad(t).createTextNode(u),t[jt]=a,a.stateNode=t}return $t(a),null;case 31:if(o=a.memoizedState,t===null||t.memoizedState!==null){if(u=Bs(a),o!==null){if(t===null){if(!u)throw Error(r(318));if(t=a.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(r(557));t[jt]=a}else Fi(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;$t(a),t=!1}else o=jh(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=o),t=!0;if(!t)return a.flags&256?(ar(a),a):(ar(a),null);if((a.flags&128)!==0)throw Error(r(558))}return $t(a),null;case 13:if(u=a.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(h=Bs(a),u!==null&&u.dehydrated!==null){if(t===null){if(!h)throw Error(r(318));if(h=a.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(r(317));h[jt]=a}else Fi(),(a.flags&128)===0&&(a.memoizedState=null),a.flags|=4;$t(a),h=!1}else h=jh(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=h),h=!0;if(!h)return a.flags&256?(ar(a),a):(ar(a),null)}return ar(a),(a.flags&128)!==0?(a.lanes=o,a):(o=u!==null,t=t!==null&&t.memoizedState!==null,o&&(u=a.child,h=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(h=u.alternate.memoizedState.cachePool.pool),g=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(g=u.memoizedState.cachePool.pool),g!==h&&(u.flags|=2048)),o!==t&&o&&(a.child.flags|=8192),qu(a,a.updateQueue),$t(a),null);case 4:return Me(),t===null&&Yp(a.stateNode.containerInfo),$t(a),null;case 10:return Ca(a.type),$t(a),null;case 19:if(T(Kt),u=a.memoizedState,u===null)return $t(a),null;if(h=(a.flags&128)!==0,g=u.rendering,g===null)if(h)zl(u,!1);else{if(Gt!==0||t!==null&&(t.flags&128)!==0)for(t=a.child;t!==null;){if(g=Du(t),g!==null){for(a.flags|=128,zl(u,!1),t=g.updateQueue,a.updateQueue=t,qu(a,t),a.subtreeFlags=0,t=o,o=a.child;o!==null;)Rb(o,t),o=o.sibling;return pe(Kt,Kt.current&1|2),ut&&Sa(a,u.treeForkCount),a.child}t=t.sibling}u.tail!==null&&Pt()>Wu&&(a.flags|=128,h=!0,zl(u,!1),a.lanes=4194304)}else{if(!h)if(t=Du(g),t!==null){if(a.flags|=128,h=!0,t=t.updateQueue,a.updateQueue=t,qu(a,t),zl(u,!0),u.tail===null&&u.tailMode==="hidden"&&!g.alternate&&!ut)return $t(a),null}else 2*Pt()-u.renderingStartTime>Wu&&o!==536870912&&(a.flags|=128,h=!0,zl(u,!1),a.lanes=4194304);u.isBackwards?(g.sibling=a.child,a.child=g):(t=u.last,t!==null?t.sibling=g:a.child=g,u.last=g)}return u.tail!==null?(t=u.tail,u.rendering=t,u.tail=t.sibling,u.renderingStartTime=Pt(),t.sibling=null,o=Kt.current,pe(Kt,h?o&1|2:o&1),ut&&Sa(a,u.treeForkCount),t):($t(a),null);case 22:case 23:return ar(a),Xh(),u=a.memoizedState!==null,t!==null?t.memoizedState!==null!==u&&(a.flags|=8192):u&&(a.flags|=8192),u?(o&536870912)!==0&&(a.flags&128)===0&&($t(a),a.subtreeFlags&6&&(a.flags|=8192)):$t(a),o=a.updateQueue,o!==null&&qu(a,o.retryQueue),o=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(o=t.memoizedState.cachePool.pool),u=null,a.memoizedState!==null&&a.memoizedState.cachePool!==null&&(u=a.memoizedState.cachePool.pool),u!==o&&(a.flags|=2048),t!==null&&T(Wi),null;case 24:return o=null,t!==null&&(o=t.memoizedState.cache),a.memoizedState.cache!==o&&(a.flags|=2048),Ca(Qt),$t(a),null;case 25:return null;case 30:return null}throw Error(r(156,a.tag))}function mT(t,a){switch(Nh(a),a.tag){case 1:return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 3:return Ca(Qt),Me(),t=a.flags,(t&65536)!==0&&(t&128)===0?(a.flags=t&-65537|128,a):null;case 26:case 27:case 5:return kt(a),null;case 31:if(a.memoizedState!==null){if(ar(a),a.alternate===null)throw Error(r(340));Fi()}return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 13:if(ar(a),t=a.memoizedState,t!==null&&t.dehydrated!==null){if(a.alternate===null)throw Error(r(340));Fi()}return t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 19:return T(Kt),null;case 4:return Me(),null;case 10:return Ca(a.type),null;case 22:case 23:return ar(a),Xh(),t!==null&&T(Wi),t=a.flags,t&65536?(a.flags=t&-65537|128,a):null;case 24:return Ca(Qt),null;case 25:return null;default:return null}}function nS(t,a){switch(Nh(a),a.tag){case 3:Ca(Qt),Me();break;case 26:case 27:case 5:kt(a);break;case 4:Me();break;case 31:a.memoizedState!==null&&ar(a);break;case 13:ar(a);break;case 19:T(Kt);break;case 10:Ca(a.type);break;case 22:case 23:ar(a),Xh(),t!==null&&T(Wi);break;case 24:Ca(Qt)}}function Hl(t,a){try{var o=a.updateQueue,u=o!==null?o.lastEffect:null;if(u!==null){var h=u.next;o=h;do{if((o.tag&t)===t){u=void 0;var g=o.create,E=o.inst;u=g(),E.destroy=u}o=o.next}while(o!==h)}}catch(k){Ct(a,a.return,k)}}function li(t,a,o){try{var u=a.updateQueue,h=u!==null?u.lastEffect:null;if(h!==null){var g=h.next;u=g;do{if((u.tag&t)===t){var E=u.inst,k=E.destroy;if(k!==void 0){E.destroy=void 0,h=a;var H=o,Y=k;try{Y()}catch(ne){Ct(h,H,ne)}}}u=u.next}while(u!==g)}}catch(ne){Ct(a,a.return,ne)}}function rS(t){var a=t.updateQueue;if(a!==null){var o=t.stateNode;try{Kb(a,o)}catch(u){Ct(t,t.return,u)}}}function aS(t,a,o){o.props=Zi(t.type,t.memoizedProps),o.state=t.memoizedState;try{o.componentWillUnmount()}catch(u){Ct(t,a,u)}}function Ul(t,a){try{var o=t.ref;if(o!==null){switch(t.tag){case 26:case 27:case 5:var u=t.stateNode;break;case 30:u=t.stateNode;break;default:u=t.stateNode}typeof o=="function"?t.refCleanup=o(u):o.current=u}}catch(h){Ct(t,a,h)}}function ta(t,a){var o=t.ref,u=t.refCleanup;if(o!==null)if(typeof u=="function")try{u()}catch(h){Ct(t,a,h)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof o=="function")try{o(null)}catch(h){Ct(t,a,h)}else o.current=null}function iS(t){var a=t.type,o=t.memoizedProps,u=t.stateNode;try{e:switch(a){case"button":case"input":case"select":case"textarea":o.autoFocus&&u.focus();break e;case"img":o.src?u.src=o.src:o.srcSet&&(u.srcset=o.srcSet)}}catch(h){Ct(t,t.return,h)}}function kp(t,a,o){try{var u=t.stateNode;zT(u,t.type,o,a),u[mn]=a}catch(h){Ct(t,t.return,h)}}function sS(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&gi(t.type)||t.tag===4}function Rp(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||sS(t.return))return null;t=t.return}for(t.sibling.return=t.return,t=t.sibling;t.tag!==5&&t.tag!==6&&t.tag!==18;){if(t.tag===27&&gi(t.type)||t.flags&2||t.child===null||t.tag===4)continue e;t.child.return=t,t=t.child}if(!(t.flags&2))return t.stateNode}}function Dp(t,a,o){var u=t.tag;if(u===5||u===6)t=t.stateNode,a?(o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o).insertBefore(t,a):(a=o.nodeType===9?o.body:o.nodeName==="HTML"?o.ownerDocument.body:o,a.appendChild(t),o=o._reactRootContainer,o!=null||a.onclick!==null||(a.onclick=hr));else if(u!==4&&(u===27&&gi(t.type)&&(o=t.stateNode,a=null),t=t.child,t!==null))for(Dp(t,a,o),t=t.sibling;t!==null;)Dp(t,a,o),t=t.sibling}function Gu(t,a,o){var u=t.tag;if(u===5||u===6)t=t.stateNode,a?o.insertBefore(t,a):o.appendChild(t);else if(u!==4&&(u===27&&gi(t.type)&&(o=t.stateNode),t=t.child,t!==null))for(Gu(t,a,o),t=t.sibling;t!==null;)Gu(t,a,o),t=t.sibling}function oS(t){var a=t.stateNode,o=t.memoizedProps;try{for(var u=t.type,h=a.attributes;h.length;)a.removeAttributeNode(h[0]);Sn(a,u,o),a[jt]=t,a[mn]=o}catch(g){Ct(t,t.return,g)}}var Ta=!1,tn=!1,Op=!1,lS=typeof WeakSet=="function"?WeakSet:Set,fn=null;function yT(t,a){if(t=t.containerInfo,Qp=dd,t=Sb(t),_h(t)){if("selectionStart"in t)var o={start:t.selectionStart,end:t.selectionEnd};else e:{o=(o=t.ownerDocument)&&o.defaultView||window;var u=o.getSelection&&o.getSelection();if(u&&u.rangeCount!==0){o=u.anchorNode;var h=u.anchorOffset,g=u.focusNode;u=u.focusOffset;try{o.nodeType,g.nodeType}catch{o=null;break e}var E=0,k=-1,H=-1,Y=0,ne=0,le=t,Q=null;t:for(;;){for(var te;le!==o||h!==0&&le.nodeType!==3||(k=E+h),le!==g||u!==0&&le.nodeType!==3||(H=E+u),le.nodeType===3&&(E+=le.nodeValue.length),(te=le.firstChild)!==null;)Q=le,le=te;for(;;){if(le===t)break t;if(Q===o&&++Y===h&&(k=E),Q===g&&++ne===u&&(H=E),(te=le.nextSibling)!==null)break;le=Q,Q=le.parentNode}le=te}o=k===-1||H===-1?null:{start:k,end:H}}else o=null}o=o||{start:0,end:0}}else o=null;for(Zp={focusedElem:t,selectionRange:o},dd=!1,fn=a;fn!==null;)if(a=fn,t=a.child,(a.subtreeFlags&1028)!==0&&t!==null)t.return=a,fn=t;else for(;fn!==null;){switch(a=fn,g=a.alternate,t=a.flags,a.tag){case 0:if((t&4)!==0&&(t=a.updateQueue,t=t!==null?t.events:null,t!==null))for(o=0;o title"))),Sn(g,u,o),g[jt]=t,Jt(g),u=g;break e;case"link":var E=pw("link","href",h).get(u+(o.href||""));if(E){for(var k=0;kxt&&(E=xt,xt=Ue,Ue=E);var V=bb(k,Ue),B=bb(k,xt);if(V&&B&&(te.rangeCount!==1||te.anchorNode!==V.node||te.anchorOffset!==V.offset||te.focusNode!==B.node||te.focusOffset!==B.offset)){var W=le.createRange();W.setStart(V.node,V.offset),te.removeAllRanges(),Ue>xt?(te.addRange(W),te.extend(B.node,B.offset)):(W.setEnd(B.node,B.offset),te.addRange(W))}}}}for(le=[],te=k;te=te.parentNode;)te.nodeType===1&&le.push({element:te,left:te.scrollLeft,top:te.scrollTop});for(typeof k.focus=="function"&&k.focus(),k=0;ko?32:o,X.T=null,o=zp,zp=null;var g=fi,E=La;if(on=0,no=fi=null,La=0,(mt&6)!==0)throw Error(r(331));var k=mt;if(mt|=4,vS(g.current),mS(g,g.current,E,o),mt=k,Vl(0,!1),Vt&&typeof Vt.onPostCommitFiberRoot=="function")try{Vt.onPostCommitFiberRoot(zn,g)}catch{}return!0}finally{de.p=h,X.T=u,jS(t,a)}}function HS(t,a,o){a=gr(o,a),a=yp(t.stateNode,a,2),t=ii(t,a,2),t!==null&&(tt(t,2),na(t))}function Ct(t,a,o){if(t.tag===3)HS(t,t,o);else for(;a!==null;){if(a.tag===3){HS(a,t,o);break}else if(a.tag===1){var u=a.stateNode;if(typeof a.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(di===null||!di.has(u))){t=gr(o,t),o=Uv(2),u=ii(a,o,2),u!==null&&(Pv(o,u,a,t),tt(u,2),na(u));break}}a=a.return}}function Bp(t,a,o){var u=t.pingCache;if(u===null){u=t.pingCache=new ST;var h=new Set;u.set(a,h)}else h=u.get(a),h===void 0&&(h=new Set,u.set(a,h));h.has(o)||(Mp=!0,h.add(o),t=AT.bind(null,t,a,o),a.then(t,t))}function AT(t,a,o){var u=t.pingCache;u!==null&&u.delete(a),t.pingedLanes|=t.suspendedLanes&o,t.warmLanes&=~o,Rt===t&&(st&o)===o&&(Gt===4||Gt===3&&(st&62914560)===st&&300>Pt()-Ku?(mt&2)===0&&ro(t,0):Np|=o,to===st&&(to=0)),na(t)}function US(t,a){a===0&&(a=De()),t=qi(t,a),t!==null&&(tt(t,a),na(t))}function xT(t){var a=t.memoizedState,o=0;a!==null&&(o=a.retryLane),US(t,o)}function TT(t,a){var o=0;switch(t.tag){case 31:case 13:var u=t.stateNode,h=t.memoizedState;h!==null&&(o=h.retryLane);break;case 19:u=t.stateNode;break;case 22:u=t.stateNode._retryCache;break;default:throw Error(r(314))}u!==null&&u.delete(a),US(t,o)}function kT(t,a){return dn(t,a)}var ed=null,io=null,qp=!1,td=!1,Gp=!1,pi=0;function na(t){t!==io&&t.next===null&&(io===null?ed=io=t:io=io.next=t),td=!0,qp||(qp=!0,DT())}function Vl(t,a){if(!Gp&&td){Gp=!0;do for(var o=!1,u=ed;u!==null;){if(t!==0){var h=u.pendingLanes;if(h===0)var g=0;else{var E=u.suspendedLanes,k=u.pingedLanes;g=(1<<31-an(42|t)+1)-1,g&=h&~(E&~k),g=g&201326741?g&201326741|1:g?g|2:0}g!==0&&(o=!0,GS(u,g))}else g=st,g=_e(u,u===Rt?g:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(g&3)===0||qe(u,g)||(o=!0,GS(u,g));u=u.next}while(o);Gp=!1}}function RT(){PS()}function PS(){td=qp=!1;var t=0;pi!==0&&UT()&&(t=pi);for(var a=Pt(),o=null,u=ed;u!==null;){var h=u.next,g=BS(u,a);g===0?(u.next=null,o===null?ed=h:o.next=h,h===null&&(io=o)):(o=u,(t!==0||(g&3)!==0)&&(td=!0)),u=h}on!==0&&on!==5||Vl(t),pi!==0&&(pi=0)}function BS(t,a){for(var o=t.suspendedLanes,u=t.pingedLanes,h=t.expirationTimes,g=t.pendingLanes&-62914561;0k)break;var ne=H.transferSize,le=H.initiatorType;ne&&QS(le)&&(H=H.responseEnd,E+=ne*(H"u"?null:document;function uw(t,a,o){var u=so;if(u&&typeof a=="string"&&a){var h=Bn(a);h='link[rel="'+t+'"][href="'+h+'"]',typeof o=="string"&&(h+='[crossorigin="'+o+'"]'),cw.has(h)||(cw.add(h),t={rel:t,crossOrigin:o,href:a},u.querySelector(h)===null&&(a=u.createElement("link"),Sn(a,"link",t),Jt(a),u.head.appendChild(a)))}}function YT(t){$a.D(t),uw("dns-prefetch",t,null)}function XT(t,a){$a.C(t,a),uw("preconnect",t,a)}function JT(t,a,o){$a.L(t,a,o);var u=so;if(u&&t&&a){var h='link[rel="preload"][as="'+Bn(a)+'"]';a==="image"&&o&&o.imageSrcSet?(h+='[imagesrcset="'+Bn(o.imageSrcSet)+'"]',typeof o.imageSizes=="string"&&(h+='[imagesizes="'+Bn(o.imageSizes)+'"]')):h+='[href="'+Bn(t)+'"]';var g=h;switch(a){case"style":g=oo(t);break;case"script":g=lo(t)}wr.has(g)||(t=y({rel:"preload",href:a==="image"&&o&&o.imageSrcSet?void 0:t,as:a},o),wr.set(g,t),u.querySelector(h)!==null||a==="style"&&u.querySelector(Xl(g))||a==="script"&&u.querySelector(Jl(g))||(a=u.createElement("link"),Sn(a,"link",t),Jt(a),u.head.appendChild(a)))}}function QT(t,a){$a.m(t,a);var o=so;if(o&&t){var u=a&&typeof a.as=="string"?a.as:"script",h='link[rel="modulepreload"][as="'+Bn(u)+'"][href="'+Bn(t)+'"]',g=h;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":g=lo(t)}if(!wr.has(g)&&(t=y({rel:"modulepreload",href:t},a),wr.set(g,t),o.querySelector(h)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(o.querySelector(Jl(g)))return}u=o.createElement("link"),Sn(u,"link",t),Jt(u),o.head.appendChild(u)}}}function ZT(t,a,o){$a.S(t,a,o);var u=so;if(u&&t){var h=Yr(u).hoistableStyles,g=oo(t);a=a||"default";var E=h.get(g);if(!E){var k={loading:0,preload:null};if(E=u.querySelector(Xl(g)))k.loading=5;else{t=y({rel:"stylesheet",href:t,"data-precedence":a},o),(o=wr.get(g))&&sg(t,o);var H=E=u.createElement("link");Jt(H),Sn(H,"link",t),H._p=new Promise(function(Y,ne){H.onload=Y,H.onerror=ne}),H.addEventListener("load",function(){k.loading|=1}),H.addEventListener("error",function(){k.loading|=2}),k.loading|=4,sd(E,a,u)}E={type:"stylesheet",instance:E,count:1,state:k},h.set(g,E)}}}function ek(t,a){$a.X(t,a);var o=so;if(o&&t){var u=Yr(o).hoistableScripts,h=lo(t),g=u.get(h);g||(g=o.querySelector(Jl(h)),g||(t=y({src:t,async:!0},a),(a=wr.get(h))&&og(t,a),g=o.createElement("script"),Jt(g),Sn(g,"link",t),o.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(h,g))}}function tk(t,a){$a.M(t,a);var o=so;if(o&&t){var u=Yr(o).hoistableScripts,h=lo(t),g=u.get(h);g||(g=o.querySelector(Jl(h)),g||(t=y({src:t,async:!0,type:"module"},a),(a=wr.get(h))&&og(t,a),g=o.createElement("script"),Jt(g),Sn(g,"link",t),o.head.appendChild(g)),g={type:"script",instance:g,count:1,state:null},u.set(h,g))}}function dw(t,a,o,u){var h=(h=ae.current)?id(h):null;if(!h)throw Error(r(446));switch(t){case"meta":case"title":return null;case"style":return typeof o.precedence=="string"&&typeof o.href=="string"?(a=oo(o.href),o=Yr(h).hoistableStyles,u=o.get(a),u||(u={type:"style",instance:null,count:0,state:null},o.set(a,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(o.rel==="stylesheet"&&typeof o.href=="string"&&typeof o.precedence=="string"){t=oo(o.href);var g=Yr(h).hoistableStyles,E=g.get(t);if(E||(h=h.ownerDocument||h,E={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},g.set(t,E),(g=h.querySelector(Xl(t)))&&!g._p&&(E.instance=g,E.state.loading=5),wr.has(t)||(o={rel:"preload",as:"style",href:o.href,crossOrigin:o.crossOrigin,integrity:o.integrity,media:o.media,hrefLang:o.hrefLang,referrerPolicy:o.referrerPolicy},wr.set(t,o),g||nk(h,t,o,E.state))),a&&u===null)throw Error(r(528,""));return E}if(a&&u!==null)throw Error(r(529,""));return null;case"script":return a=o.async,o=o.src,typeof o=="string"&&a&&typeof a!="function"&&typeof a!="symbol"?(a=lo(o),o=Yr(h).hoistableScripts,u=o.get(a),u||(u={type:"script",instance:null,count:0,state:null},o.set(a,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(r(444,t))}}function oo(t){return'href="'+Bn(t)+'"'}function Xl(t){return'link[rel="stylesheet"]['+t+"]"}function fw(t){return y({},t,{"data-precedence":t.precedence,precedence:null})}function nk(t,a,o,u){t.querySelector('link[rel="preload"][as="style"]['+a+"]")?u.loading=1:(a=t.createElement("link"),u.preload=a,a.addEventListener("load",function(){return u.loading|=1}),a.addEventListener("error",function(){return u.loading|=2}),Sn(a,"link",o),Jt(a),t.head.appendChild(a))}function lo(t){return'[src="'+Bn(t)+'"]'}function Jl(t){return"script[async]"+t}function hw(t,a,o){if(a.count++,a.instance===null)switch(a.type){case"style":var u=t.querySelector('style[data-href~="'+Bn(o.href)+'"]');if(u)return a.instance=u,Jt(u),u;var h=y({},o,{"data-href":o.href,"data-precedence":o.precedence,href:null,precedence:null});return u=(t.ownerDocument||t).createElement("style"),Jt(u),Sn(u,"style",h),sd(u,o.precedence,t),a.instance=u;case"stylesheet":h=oo(o.href);var g=t.querySelector(Xl(h));if(g)return a.state.loading|=4,a.instance=g,Jt(g),g;u=fw(o),(h=wr.get(h))&&sg(u,h),g=(t.ownerDocument||t).createElement("link"),Jt(g);var E=g;return E._p=new Promise(function(k,H){E.onload=k,E.onerror=H}),Sn(g,"link",u),a.state.loading|=4,sd(g,o.precedence,t),a.instance=g;case"script":return g=lo(o.src),(h=t.querySelector(Jl(g)))?(a.instance=h,Jt(h),h):(u=o,(h=wr.get(g))&&(u=y({},o),og(u,h)),t=t.ownerDocument||t,h=t.createElement("script"),Jt(h),Sn(h,"link",u),t.head.appendChild(h),a.instance=h);case"void":return null;default:throw Error(r(443,a.type))}else a.type==="stylesheet"&&(a.state.loading&4)===0&&(u=a.instance,a.state.loading|=4,sd(u,o.precedence,t));return a.instance}function sd(t,a,o){for(var u=o.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),h=u.length?u[u.length-1]:null,g=h,E=0;E title"):null)}function rk(t,a,o){if(o===1||a.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof a.precedence!="string"||typeof a.href!="string"||a.href==="")break;return!0;case"link":if(typeof a.rel!="string"||typeof a.href!="string"||a.href===""||a.onLoad||a.onError)break;switch(a.rel){case"stylesheet":return t=a.disabled,typeof a.precedence=="string"&&t==null;default:return!0}case"script":if(a.async&&typeof a.async!="function"&&typeof a.async!="symbol"&&!a.onLoad&&!a.onError&&a.src&&typeof a.src=="string")return!0}return!1}function mw(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function ak(t,a,o,u){if(o.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(o.state.loading&4)===0){if(o.instance===null){var h=oo(u.href),g=a.querySelector(Xl(h));if(g){a=g._p,a!==null&&typeof a=="object"&&typeof a.then=="function"&&(t.count++,t=ld.bind(t),a.then(t,t)),o.state.loading|=4,o.instance=g,Jt(g);return}g=a.ownerDocument||a,u=fw(u),(h=wr.get(h))&&sg(u,h),g=g.createElement("link"),Jt(g);var E=g;E._p=new Promise(function(k,H){E.onload=k,E.onerror=H}),Sn(g,"link",u),o.instance=g}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(o,a),(a=o.state.preload)&&(o.state.loading&3)===0&&(t.count++,o=ld.bind(t),a.addEventListener("load",o),a.addEventListener("error",o))}}var lg=0;function ik(t,a){return t.stylesheets&&t.count===0&&ud(t,t.stylesheets),0lg?50:800)+a);return t.unsuspend=o,function(){t.unsuspend=null,clearTimeout(u),clearTimeout(h)}}:null}function ld(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)ud(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var cd=null;function ud(t,a){t.stylesheets=null,t.unsuspend!==null&&(t.count++,cd=new Map,a.forEach(sk,t),cd=null,ld.call(t))}function sk(t,a){if(!(a.state.loading&4)){var o=cd.get(t);if(o)var u=o.get(null);else{o=new Map,cd.set(t,o);for(var h=t.querySelectorAll("link[data-precedence],style[data-precedence]"),g=0;g"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(s)}catch(e){console.error(e)}}return s(),Sd.exports=Iw(),Sd.exports}var _d=jw();const Ad=aa(_d),fo=[],zw=50;let xd=!1;function _g(){try{return window.G7Core?.devTools}catch{return}}function ns(s,e,n){const r=_g();if(xd&&r?.isEnabled?.()){r.trackLog?.(s,e,n);return}xd||(s==="error"||s==="warn")&&fo.length{n.isDebugEnabled()&&console.log(e,...r),ns("log",s,r)},warn:(...r)=>{n.isDebugEnabled()&&console.warn(e,...r),ns("warn",s,r)},error:(...r)=>{n.isDebugEnabled()&&console.error(e,...r),ns("error",s,r)}}}ho.getInstance();const Ag="extension",rs="extensionless",xg="file";function Hw(){const s=globalThis?.G7Config;if(globalThis?.__g7AssetUrlMode===rs)return rs;const n=s?.assetUrlMode;return n===rs||n===Ag?n:s?.settings?.general?.asset_url_mode===rs?rs:Ag}function kd(){return Hw()===rs}function Uw(s,e,n){return Rd("templates",s,e,n)}function Pw(s,e){const n=e.replace(/^\/+/,"").replace(/\/+$/,""),r=encodeURIComponent(s),i=po(`templates/${s}/assets/${n}`);return i!==null?i:`/api/templates/assets/${r}/${n}`}function Bw(s,e,n){return Rd("modules",s,e,n)}function qw(s,e,n){return Rd("plugins",s,e,n)}function Rd(s,e,n,r){const i=n.replace(/^\/+/,""),l=encodeURIComponent(e);if(!kd())return`/api/${s}/assets/${l}/${i}${Vw(r)}`;let c=`${xg}=${encodeURIComponent(i)}`;return r!=null&&r!==""&&(c+=`&v=${r}`),`/api/${s}/assets/${l}?${c}`}function Pr(s,e,n,r){const i=s.replace(/\/+$/,""),l=e.replace(/^\.+/,""),c=kd()?i:`${i}.${l}`,d=[];return r&&d.push(r.replace(/^[?&]+/,"")),n!=null&&n!==""&&d.push(`v=${n}`),d.length>0?`${c}?${d.join("&")}`:c}function Tg(){const s=globalThis?.G7Config?.staticBase;return typeof s=="string"&&s!==""?s.replace(/\/+$/,""):null}function Gw(){const s=Tg();if(!s)return null;const e=s.match(/\/(\d+)$/);return e?Number(e[1]):null}function po(s,e){const n=Tg();if(!n)return null;const r=s.replace(/^\/+/,"");return e!==void 0&&e>0&&e!==Gw()?`${n.replace(/\/\d+$/,"")}/${e}/${r}`:`${n}/${r}`}function Dd(s){if(!s)return null;const e=globalThis?.location?.origin,r=(e&&s.startsWith(e)?s.slice(e.length):s).match(/^\/build\/ext\/(\d+)\/(.+)$/);if(!r)return null;const i=r[1],l=r[2].split("?")[0],c=l.match(/^(templates|modules|plugins)\/([^/]+)\/assets\/(.+)$/);if(c){const[,p,m,y]=c;return`/api/${p}/assets/${m}/${y}?v=${i}`}const d=l.match(/^bundles\/(modules|plugins)\.(js|css)$/);if(d)return`/api/${d[1]}/bundle.${d[2]}?v=${i}`;const f=l.match(/^templates\/([^/]+)\/(routes\.json|components\.json|lang\/([a-zA-Z-]+)\.json)$/);if(f){const[,p,m]=f,y=m.replace(/\.json$/,"");return`/api/templates/${p}/${y}.json?v=${i}`}return null}function xn(s){if(!s||!kd())return s;const e=globalThis?.location?.origin,n=e&&s.startsWith(e)?s.slice(e.length):s;if(!n.startsWith("/api/"))return s;const[r,i]=Fw(n),l=r.match(/^\/api\/(modules|plugins)\/bundle\.(js|css)$/);if(l)return kg(`/api/${l[1]}/bundle/${l[2]}`,i);const c=r.match(/^\/api\/(templates|modules|plugins)\/assets\/([^/]+)\/(.+)$/);if(c){const[,f,p,m]=c,y=`${xg}=${encodeURIComponent(decodeURIComponent(m))}`;return`/api/${f}/assets/${p}?${y}${i?`&${i}`:""}`}const d=r.match(/^(\/api\/.+)\.(json|js|css)$/);return d?kg(d[1],i):s}function Fw(s){const e=s.indexOf("?");return e===-1?[s,""]:[s.slice(0,e),s.slice(e+1)]}function kg(s,e){return e?`${s}?${e}`:s}function Vw(s){return s==null||s===""?"":`?v=${s}`}const ia=dt("networkResilience"),Od=2,Ld=300,$d=2e3,Kw=15e3;function Md(s){return s?.name==="AbortError"}function Rg(s){if(Md(s))return!1;if(s instanceof TypeError)return!0;const e=s?.code;return e==="ERR_NETWORK"||e==="ECONNABORTED"}let nc=!1,Dg=!1;function rc(){return nc}function Ww(){typeof window>"u"||Dg||(Dg=!0,window.addEventListener("pagehide",()=>{nc=!0}),window.addEventListener("pageshow",s=>{s.persisted&&(nc=!1)}),window.addEventListener("beforeunload",()=>{nc=!0}))}function Nd(s,e,n){const r=Math.min(e*Math.pow(2,s),n),i=r*.25*(Math.random()*2-1);return Math.max(0,Math.round(r+i))}function Id(s){return new Promise(e=>setTimeout(e,s))}async function ac(s,e={}){const{retries:n=Od,baseDelayMs:r=Ld,maxDelayMs:i=$d,timeoutMs:l=Kw,label:c=s,init:d}=e,f=n+1;let p;for(let m=0;m0?new AbortController:null;try{const v={...d};if(S){const w=d?.signal;w&&(w.aborted?S.abort():w.addEventListener("abort",()=>S.abort(),{once:!0})),v.signal=S.signal,C=setTimeout(()=>{y=!0,S.abort()},l)}return await fetch(s,v)}catch(v){if(p=v,Md(v)&&!y||!(y||Rg(v)))throw v;if(rc())throw ia.warn(`Document unloading, aborting retries: ${c}`),v;if(m===f-1)throw ia.warn(`All ${f} attempts failed: ${c}`,v),v;const R=Nd(m,r,i);ia.warn(`Network failure (attempt ${m+1}/${f}), retrying in ${R}ms: ${c}`),await Id(R)}finally{C!==void 0&&clearTimeout(C)}}throw p}async function Cr(s,e={},n={}){const{retries:r=Od,baseDelayMs:i=Ld,maxDelayMs:l=$d,label:c=s}=n,d=r+1;for(let f=0;f{const i=document.createElement("script");i.src=s,i.async=!1;for(const[l,c]of Object.entries(e))l==="id"?i.id=c:i.setAttribute(l,c);i.onload=()=>n(),i.onerror=()=>r(new Error(`Failed to load script: ${s}`)),document.head.appendChild(i)})}async function sa(s,e={},n={}){const{retries:r=Od,baseDelayMs:i=Ld,maxDelayMs:l=$d,label:c=s}=n,d=r+1;for(let f=0;f{s.onload=()=>e(),s.onerror=()=>n(new Error(`Failed to load stylesheet: ${s.href}`))})}async function ic(s,e,n={}){if(!s)return ac(e,n);try{const r=await fetch(s,n.init);if(r.ok){const i=await r.text();try{return JSON.parse(i),new Response(i,{status:r.status,statusText:r.statusText,headers:r.headers})}catch{return console.warn(`[fetchStaticFirst] Static fast path returned malformed JSON — falling back to API: ${s}`),ac(e,n)}}console.warn(`[fetchStaticFirst] Static fast path miss (${r.status}) — falling back to API: ${s}`)}catch(r){console.warn(`[fetchStaticFirst] Static fast path fetch failed — falling back to API: ${s}`,r)}return ac(e,n)}const Br=dt("ComponentRegistry");class ln extends Error{constructor(e,n,r){super(e),this.code=n,this.details=r,this.name="ComponentRegistryError"}}const Zn=class Zn{constructor(){$(this,"registry",{});$(this,"manifest",null);$(this,"cacheVersion",0);$(this,"loadingState","idle");$(this,"error",null);$(this,"templateId",null);$(this,"templateType",null)}static getInstance(){return Zn.instance||(Zn.instance=new Zn),Zn.instance}static createIsolatedInstance(){return new Zn}static resetInstance(){Zn.instance=null}async loadComponents(e,n,r=0){if(this.loadingState==="loading")throw new ln("Components are already being loaded","LOADING_IN_PROGRESS");if(this.loadingState==="loaded"&&this.templateId===e&&this.templateType===n){Br.log("Components already loaded for template:",e,n);return}this.loadingState="loading",this.templateId=e,this.templateType=n,this.cacheVersion=r,this.error=null;try{await this.loadManifest(),await this.loadComponentBundle(),this.loadingState="loaded",Br.log("Successfully loaded components:",Object.keys(this.registry).length)}catch(i){throw this.loadingState="error",this.error=i instanceof Error?i:new Error(String(i)),new ln(`Failed to load components: ${this.error.message}`,"LOAD_FAILED",{originalError:this.error})}}async loadManifest(){try{if(!this.templateId)throw new ln("Template ID not set","TEMPLATE_ID_NOT_SET");const e=`${this.templateId}:${this.templateType}:v${this.cacheVersion||0}`;if(Zn.manifestCache.has(e)){this.manifest=Zn.manifestCache.get(e),Br.log("Manifest loaded from cache:",this.manifest.templateId);return}const n=Pr(`/api/templates/${this.templateId}/components`,"json",this.cacheVersion>0?this.cacheVersion:null),r=await ic(this.cacheVersion>0?po(`templates/${this.templateId}/components.json`,this.cacheVersion):null,n,{label:"components.json"});if(!r.ok)throw new ln(`Failed to fetch manifest: ${r.status} ${r.statusText}`,"MANIFEST_FETCH_FAILED",{status:r.status,statusText:r.statusText});const i=await r.json();this.validateManifest(i),this.manifest=i,Zn.manifestCache.set(e,i),Br.log("Manifest loaded and cached:",i.templateId)}catch(e){throw e instanceof ln?e:new ln("Failed to load component manifest","MANIFEST_LOAD_FAILED",{originalError:e})}}validateManifest(e){if(!e.version)throw new ln("Manifest missing required field: version","MANIFEST_INVALID",{field:"version"});if(!e.templateId)throw new ln("Manifest missing required field: templateId","MANIFEST_INVALID",{field:"templateId"});if(!e.components||typeof e.components!="object")throw new ln("Manifest missing required field: components","MANIFEST_INVALID",{field:"components"});const n=["basic","composite","layout"];for(const r of n){if(!Array.isArray(e.components[r]))throw new ln(`Manifest field 'components.${r}' must be an array`,"MANIFEST_INVALID",{field:`components.${r}`,value:e.components[r]});e.components[r].forEach((i,l)=>{if(!i.name||typeof i.name!="string")throw new ln(`Invalid component metadata at ${r}[${l}]: missing or invalid 'name'`,"MANIFEST_INVALID",{type:r,index:l,metadata:i});if(!i.type||typeof i.type!="string")throw new ln(`Invalid component metadata at ${r}[${l}]: missing or invalid 'type'`,"MANIFEST_INVALID",{type:r,index:l,metadata:i})})}Br.log("Manifest validation passed")}async loadComponentBundle(){try{if(!this.templateId)throw new ln("Template ID not set","TEMPLATE_ID_NOT_SET");const e=this.getGlobalVariableName(),n=window[e];if(!n||typeof n!="object")throw new ln(`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(n),Br.log("Component bundle loaded from global variable:",e)}catch(e){throw e instanceof ln?e:new ln("Failed to load component bundle","BUNDLE_LOAD_FAILED",{originalError:e})}}getGlobalVariableName(){if(!this.templateId)throw new ln("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 ln("Manifest not loaded","MANIFEST_NOT_LOADED");const n=["basic","composite","layout"];for(const r of n){const i=this.manifest.components[r]||[];for(const l of i){const c=l.name,d=e[c];if(!d){Br.warn(`Component '${c}' not found in bundle`);continue}this.registerComponent(c,d,l)}}}registerComponent(e,n,r){this.registry[e]&&Br.warn(`Component '${e}' already registered, overwriting`);const i=We.memo(n);this.registry[e]={component:i,metadata:r},Br.log(`[ComponentRegistry] Registered component: ${e} (${r.type})`)}getComponent(e){const n=this.registry[e];return n?n.component:null}getMetadata(e){const n=this.registry[e];return n?n.metadata:null}hasComponent(e){return e in this.registry}getComponentsByType(e){return Object.entries(this.registry).filter(([n,r])=>r.metadata.type===e).map(([n,r])=>n)}getAllComponents(){return Object.keys(this.registry)}getComponentMap(){const e={};for(const[n,r]of Object.entries(this.registry))e[n]=r.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,Br.log("Registry cleared")}};$(Zn,"instance",null),$(Zn,"manifestCache",new Map);let Er=Zn;const as=dt("PipeRegistry");function Og(s,e){const n=s.getFullYear(),r=String(s.getMonth()+1).padStart(2,"0"),i=String(s.getDate()).padStart(2,"0"),l=String(s.getHours()).padStart(2,"0"),c=String(s.getMinutes()).padStart(2,"0"),d=String(s.getSeconds()).padStart(2,"0");return e.replace("YYYY",String(n)).replace("YY",String(n).slice(-2)).replace("MM",r).replace("M",String(s.getMonth()+1)).replace("DD",i).replace("D",String(s.getDate())).replace("HH",l).replace("H",String(s.getHours())).replace("mm",c).replace("m",String(s.getMinutes())).replace("ss",d).replace("s",String(s.getSeconds()))}function Qw(s,e="ko"){const r=new Date().getTime()-s.getTime(),i=Math.floor(r/1e3),l=Math.floor(i/60),c=Math.floor(l/60),d=Math.floor(c/24),f=Math.floor(d/7),p=Math.floor(d/30),m=Math.floor(d/365);return e==="ko"?i<60?"방금 전":l<60?`${l}분 전`:c<24?`${c}시간 전`:d<7?`${d}일 전`:f<4?`${f}주 전`:p<12?`${p}개월 전`:`${m}년 전`:i<60?"just now":l<60?`${l} minute${l===1?"":"s"} ago`:c<24?`${c} hour${c===1?"":"s"} ago`:d<7?`${d} day${d===1?"":"s"} ago`:f<4?`${f} week${f===1?"":"s"} ago`:p<12?`${p} month${p===1?"":"s"} ago`:`${m} year${m===1?"":"s"} ago`}function jd(s){if(s==null)return null;if(s instanceof Date)return s;if(typeof s=="number")return new Date(s);if(typeof s=="string"){const e=new Date(s);return isNaN(e.getTime())?null:e}return null}const go={date:{fn:(s,e="YYYY-MM-DD")=>{const n=jd(s);return n?Og(n,e):""},description:"날짜 포맷 (기본: YYYY-MM-DD)"},datetime:{fn:(s,e="YYYY-MM-DD HH:mm")=>{const n=jd(s);return n?Og(n,e):""},description:"날짜+시간 포맷 (기본: YYYY-MM-DD HH:mm)"},relativeTime:{fn:(s,e="ko")=>{const n=jd(s);return n?Qw(n,e):""},description:'상대 시간 표시 (예: "3분 전")'},number:{fn:(s,e)=>{const n=Number(s);if(isNaN(n))return String(s??"");const r={};return e!==void 0&&(r.minimumFractionDigits=e,r.maximumFractionDigits=e),n.toLocaleString(void 0,r)},description:"숫자 포맷 (천단위 구분, 선택적 소수점)"},truncate:{fn:(s,e=100,n="...")=>typeof s!="string"?String(s??""):s.length<=e?s:s.slice(0,e)+n,description:'문자열 자르기 (기본: 100자, 접미사: "...")'},uppercase:{fn:s=>typeof s!="string"?String(s??""):s.toUpperCase(),description:"대문자 변환"},lowercase:{fn:s=>typeof s!="string"?String(s??""):s.toLowerCase(),description:"소문자 변환"},stripHtml:{fn:s=>typeof s!="string"?String(s??""):s.replace(/<[^>]*>/g,""),description:"HTML 태그 제거"},default:{fn:(s,e="")=>s==null||s===""?e:s,description:"기본값 설정 (null, undefined, 빈문자열 시)"},fallback:{fn:(s,e)=>s??e,description:"폴백 값 설정 (null, undefined 시만)"},first:{fn:s=>{if(Array.isArray(s))return s[0]},description:"배열의 첫 번째 요소"},last:{fn:s=>{if(Array.isArray(s))return s[s.length-1]},description:"배열의 마지막 요소"},join:{fn:(s,e=", ")=>Array.isArray(s)?s.join(e):"",description:'배열을 문자열로 결합 (기본 구분자: ", ")'},length:{fn:s=>Array.isArray(s)||typeof s=="string"?s.length:0,description:"배열/문자열 길이"},filterBy:{fn:(s,e,n)=>Array.isArray(s)?Array.isArray(e)?s.filter(r=>{const i=n?r?.[n]:r;return e.includes(i)}):s:[],description:"배열 필터링 (allowList에 포함된 항목만 반환)"},keys:{fn:s=>s==null||typeof s!="object"?[]:Object.keys(s),description:"객체의 키 배열"},values:{fn:s=>s==null||typeof s!="object"?[]:Object.values(s),description:"객체의 값 배열"},json:{fn:(s,e)=>{try{return JSON.stringify(s,null,e)}catch{return""}},description:"JSON 문자열로 변환"},localized:{fn:(s,e)=>s==null?"":typeof s=="string"?s:typeof s!="object"?String(s):s[e||"ko"]||s.ko||s.en||Object.values(s)[0]||"",description:"다국어 객체에서 로케일에 맞는 값 추출"}},is=new Map,Li=class Li{static getInstance(){return Li.instance||(Li.instance=new Li),Li.instance}register(e,n,r){if(go[e]){as.warn(`[PipeRegistry] 내장 파이프를 덮어쓸 수 없습니다: ${e}`);return}is.set(e,{fn:n,description:r}),as.log(`[PipeRegistry] 커스텀 파이프 등록됨: ${e}`)}unregister(e){if(go[e])return as.warn(`[PipeRegistry] 내장 파이프는 해제할 수 없습니다: ${e}`),!1;const n=is.delete(e);return n&&as.log(`[PipeRegistry] 커스텀 파이프 해제됨: ${e}`),n}get(e){const n=go[e];return n?n.fn:is.get(e)?.fn}has(e){return!!go[e]||is.has(e)}execute(e,n,r=[]){const i=this.get(e);if(!i)return as.warn(`[PipeRegistry] 알 수 없는 파이프: ${e}`),n;try{return i(n,...r)}catch(l){return as.error(`[PipeRegistry] 파이프 실행 오류 (${e}):`,l),n}}list(){const e=[];for(const[n,r]of Object.entries(go))e.push({name:n,description:r.description,type:"built-in"});for(const[n,r]of is.entries())e.push({name:n,description:r.description,type:"custom"});return e.sort((n,r)=>n.name.localeCompare(r.name))}clearCustomPipes(){is.clear()}};$(Li,"instance",null);let sc=Li;sc.getInstance();function Zw(s){const e=s.trim(),n=e.indexOf("(");if(n===-1)return{name:e,args:[]};const r=e.slice(0,n).trim(),i=e.slice(n+1,-1);if(!i.trim())return{name:r,args:[]};const l=[];let c="",d=null,f=0;for(let p=0;p0?i[p-1]:"")==="\\"){c+=m;continue}if((m==='"'||m==="'")&&!d){d=m;continue}if(m===d){d=null;continue}if(d){c+=m;continue}if(m==="("||m==="["||m==="{"){f++,c+=m;continue}if(m===")"||m==="]"||m==="}"){f--,c+=m;continue}if(m===","&&f===0){l.push(Lg(c.trim())),c="";continue}c+=m}return c.trim()&&l.push(Lg(c.trim())),{name:r,args:l}}function Lg(s){if(s==="null")return null;if(s==="undefined")return;if(s==="true")return!0;if(s==="false")return!1;const e=Number(s);return!isNaN(e)&&s!==""?e:s}function e0(s){const e=[];let n="",r=null,i=0;for(let l=0;l0?s[l-1]:"",f=l0?s[r-1]:"",c=r",e),this.cacheVersion=e,this.cache.clear())}getCacheVersion(){return this.cacheVersion}async loadTranslations(e,n,r="/api",i=!1){const l=`${e}:${n}`;if(!i){const c=this.getFromCache(l);if(c)return this.translations.set(l,c),c}try{const c=[];i&&c.push(`_=${Date.now()}`);const d=Pr(`${r}/templates/${e}/lang/${n}`,"json",this.cacheVersion>0?this.cacheVersion:null,c.length>0?c.join("&"):void 0),f=!i&&this.cacheVersion>0?po(`templates/${e}/lang/${n}.json`,this.cacheVersion):null,p=f!==null?await ic(f,d,{label:`lang/${n}.json`}):await fetch(d);if(!p.ok)throw new Hd(`Failed to load translations: ${p.statusText}`,void 0,n);const y=await p.json();return this.saveToCache(l,y),this.translations.set(l,y),y}catch(c){throw new Hd(`Failed to fetch translations for ${n}: ${c instanceof Error?c.message:String(c)}`,void 0,n)}}resolveTranslations(e,n,r){let i=e;const l=5;let c=0;for(;c"="+this.translate(m,n,void 0,r)),i===d)break;c++}return i.replace(Nn.TRANSLATION_PATTERN,(d,f,p)=>{const{cleanedParams:m,trailing:y}=this.separateTrailingText(p);return this.translate(f,n,m,r)+y})}translate(e,n,r,i){const l=this.getTranslation(e,n),c=r&&this.cleanParamsStr(r);if(c){const d=this.parseParams(c,i);return this.replaceParams(l,d)}return l}getTranslation(e,n){const{templateId:r,locale:i}=n,l=`${r}:${i}`,c=this.translations.get(l);if(c){const d=this.getNestedValue(c,e);if(d!==null)return d}if(i!==this.options.fallbackLocale){const d=`${r}:${this.options.fallbackLocale}`,f=this.translations.get(d);if(f){const p=this.getNestedValue(f,e);if(p!==null)return p}}return e}getNestedValue(e,n){const r=n.split(".");let i=e;for(const l of r){if(i==null||typeof i!="object")return null;i=i[l]}return typeof i=="string"?i:null}setTranslationValue(e,n,r,i){const l=`${e}:${n}`,c=this.translations.get(l)??{},d=r.split(".");let f=c;for(let p=0;p(l.push(f),`__PLACEHOLDER_${l.length-1}__`)).matchAll(Nn.PARAM_PATTERN);for(const f of d){const[,p,m]=f,y=m.replace(/__PLACEHOLDER_(\d+)__/g,(C,S)=>l[parseInt(S,10)]);r[p.trim()]=this.resolveParamValue(y.trim(),n)}return r}resolveParamValue(e,n){if(e.startsWith("{{")&&e.endsWith("}}")){const r=e.slice(2,-2).trim();if(On(r)&&n)try{const l=uc.evaluatePipeExpression(r,n);return String(l??"")}catch(l){return zd.error("Pipe expression evaluation failed:",r,l),""}if(/[|&()[\]!?:+\-*/%<>=\s]/.test(r)&&n)try{const l=uc.evaluateExpression(r,n);return String(l??"")}catch(l){return zd.error("Expression evaluation failed:",r,l),""}else{const l=this.getNestedDataValue(n,r);return String(l??"")}}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 r=e.match(/(\s+[^\p{L}\w=|&\s][^\p{L}\w=]*\s*)$/u);return r?{cleanedParams:e.slice(0,-r[1].length),trailing:r[1]}:{cleanedParams:e,trailing:""}}cleanParamsStr(e){return this.separateTrailingText(e).cleanedParams||""}getNestedDataValue(e,n){if(!e)return;const r=n.split(".");let i=e;for(const l of r){if(i==null)return;i=i[l]}return i}replaceParams(e,n){let r=e;for(const[i,l]of Object.entries(n)){const c=new RegExp(`\\{\\{${i}\\}\\}`,"g");r=r.replace(c,String(l));const d=new RegExp(`\\{${i}\\}`,"g");r=r.replace(d,String(l))}return r}getFromCache(e){const n=this.cache.get(e);return n?Date.now()-n.timestamp>this.options.cacheTTL?(this.cache.delete(e),null):n.data:null}saveToCache(e,n){this.cache.set(e,{data:n,timestamp:Date.now()})}clearCache(){this.cache.clear(),this.translations.clear()}pruneCache(){const e=Date.now(),n=[];for(const[r,i]of this.cache.entries())e-i.timestamp>this.options.cacheTTL&&n.push(r);for(const r of n)this.cache.delete(r)}getCacheStats(){const e=Date.now();let n=0;for(const r of this.cache.values())e-r.timestamp>this.options.cacheTTL&&n++;return{size:this.cache.size,expired:n}}};$(Nn,"instance",null),$(Nn,"TRANSLATION_PATTERN",/\$t:(?:defer:)?([a-zA-Z0-9._-]+)(\|(?:(?!\$t:).)+)?/g),$(Nn,"NESTED_TRANSLATION_PARAM_PATTERN",/=(\$t:([a-zA-Z0-9._-]+))(?=[|&\s]|$)/g),$(Nn,"PARAM_PATTERN",/([^=|&]+)=([^|&]+)/g);let wi=Nn;const $g=Object.freeze(Object.defineProperty({__proto__:null,TranslationEngine:wi,TranslationError:Hd},Symbol.toStringTag,{value:"Module"})),Ud=new Map([["true",!0],["false",!1],["null",null],["undefined",void 0]]);function Ma(s){if(typeof s!="string"||!s.startsWith("{{")||!s.endsWith("}}")||s.length<4)return null;const e=s.slice(2,-2);let n=null,r=0;for(let i=0;i0){r--;continue}return null}}return r===0?e.trim():null}function n0(s){const e=[];if(typeof s!="string")return e;for(let n=0;n0){i--;continue}if(s[c+1]==="}"){l=c;break}break}}l!==-1&&(e.push({start:n,end:l+2,expr:s.slice(n+2,l)}),n=l+1)}return e}function mo(s){return/[?:|&!+\-*/<>=()[\]{}]/.test(s)}function Mg(s){const e=typeof s=="string"?s.trim():"";return e===""?"empty":Ud.has(e)?"literal":On(e)?"pipe":mo(e)?"expression":"path"}function Pd(s,e,n,r){const i=typeof s=="string"?s.trim():"",l=Mg(i),c=r?.skipCache?{skipCache:!0}:void 0;if(l==="empty"){r?.onEmpty?.(s);return}if(l==="literal")return Ud.get(i);try{return l==="pipe"?n.evaluatePipeExpression(i,e,c,r?.trackingInfo):l==="expression"?n.evaluateExpression(i,e,r?.trackingInfo):n.resolve(i,e,c,r?.trackingInfo)}catch(d){if(r?.onError)return r.onError(d,i);throw d}}const lr="raw:";function Ng(s){return s.startsWith(lr)?s.slice(lr.length):s}const yo="﷐",Ci="﷑",Na="﷒";function bo(s){return yo+s+Ci}function oc(s){return s.length>=2&&s.charCodeAt(0)===64976&&s.charCodeAt(s.length-1)===64977}function lc(s){return s.includes(yo)}function Bd(s){return s.slice(1,-1)}function ss(s){if(typeof s=="string")return bo(s);if(Array.isArray(s))return s.map(ss);if(s&&typeof s=="object"){const e={};for(const[n,r]of Object.entries(s))e[n]=ss(r);return e}return s}function Ia(s){if(typeof s=="string")return oc(s)?Bd(s):lc(s)||s.includes(Ci)?s.split(yo).join("").split(Ci).join(""):s;if(Array.isArray(s)){let e=!1;const n=s.map(r=>{const i=Ia(r);return i!==r&&(e=!0),i});return e?n:s}if(s&&typeof s=="object"){if(s.$$typeof!==void 0)return s;let e=!1;const n={};for(const[r,i]of Object.entries(s)){const l=Ia(i);l!==i&&(e=!0),n[r]=l}return e?n:s}return s}const vo=new Set(["constructor","__proto__","prototype","__lookupGetter__","__lookupSetter__","__defineGetter__","__defineSetter__"]),r0=new Set(["Function","eval","globalThis","window","self","document","require","module","process","Reflect","Proxy","WebAssembly","import","constructor"]);function Ig(s,e){if(s!==null&&(typeof s=="object"||typeof s=="function")&&jg.has(s))throw new Error(`Object.${e} on a built-in global object is not allowed`);return s}const a0=Object.freeze({keys:Object.keys,values:Object.values,entries:Object.entries,assign:(s,...e)=>{const n=Ig(s,"assign");for(const r of e)if(r!=null)for(const i of Object.keys(r)){if(vo.has(i))throw new Error(`Access to "${i}" is forbidden`);Xd(n,i,r[i])}return n},freeze:s=>Object.freeze(Ig(s,"freeze")),fromEntries:Object.fromEntries,create:Object.create,isFrozen:Object.isFrozen}),qd={Math,JSON,Date,Array,Object:a0,Number,String,Boolean,Set,Map,WeakSet,WeakMap,parseInt,parseFloat,isNaN,isFinite},Gd={Date,Set,Map,WeakSet,WeakMap,Array,Number,String,Boolean,Object},jg=new Set([...Object.values(qd),...Object.values(Gd)].filter(s=>s!==null&&(typeof s=="object"||typeof s=="function"))),cc=new Set(["function"]),_r=Symbol("short-circuit");class Fd{constructor(e){this.value=e}}class Vd{}class Kd{}function i0(s){return/[A-Za-z_$]/.test(s)}function s0(s){return/[A-Za-z0-9_$]/.test(s)}function Ei(s){return s>="0"&&s<="9"}function o0(s,e,n){let r=e+1;for(;r0;){const p=s[n];if(p==="{")f++,n++;else if(p==="}"){if(f--,f===0)break;n++}else p==='"'||p==="'"?n=o0(s,n,p):p==="`"?n=zg(s,n).end:n++}if(f!==0)throw new Error("Unterminated ${...} in template literal");i.push(s.slice(d,n)),n++;continue}l+=c,n++}throw new Error(`Unterminated template literal at position ${e}`)}function l0(s){const e=[];let n=0;const r=s.length,i=l=>n+l=r)throw new Error(`Unterminated string literal at position ${p}`);n++,e.push({type:"str",value:y,pos:p});continue}if(i0(l)){const p=n;for(n++;n"?(e.push({type:"punct",value:"=>",pos:c}),n+=2):i(1)==="="?i(2)==="="?(e.push({type:"punct",value:"===",pos:c}),n+=3):(e.push({type:"punct",value:"==",pos:c}),n+=2):(e.push({type:"punct",value:"=",pos:c}),n+=1);continue}case"!":{i(1)==="="?i(2)==="="?(e.push({type:"punct",value:"!==",pos:c}),n+=3):(e.push({type:"punct",value:"!=",pos:c}),n+=2):(e.push({type:"punct",value:"!",pos:c}),n+=1);continue}case"<":{if(i(1)==="=")e.push({type:"punct",value:"<=",pos:c}),n+=2;else{if(i(1)==="<")throw new Error("Bitwise/shift operators are not allowed");e.push({type:"punct",value:"<",pos:c}),n+=1}continue}case">":{if(i(1)==="=")e.push({type:"punct",value:">=",pos:c}),n+=2;else{if(i(1)===">")throw new Error("Bitwise/shift operators are not allowed");e.push({type:"punct",value:">",pos:c}),n+=1}continue}case"&":{if(i(1)==="&")e.push({type:"punct",value:"&&",pos:c}),n+=2;else throw new Error("Bitwise operators are not allowed");continue}case"|":{if(i(1)==="|")e.push({type:"punct",value:"||",pos:c}),n+=2;else throw new Error("Bitwise operators are not allowed");continue}case"?":{i(1)==="."&&!Ei(i(2))?(e.push({type:"punct",value:"?.",pos:c}),n+=2):i(1)==="?"?(e.push({type:"punct",value:"??",pos:c}),n+=2):(e.push({type:"punct",value:"?",pos:c}),n+=1);continue}case"+":{if(i(1)==="+")throw new Error("Increment operator is not allowed");if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"+",pos:c}),n+=1;continue}case"-":{if(i(1)==="-")throw new Error("Decrement operator is not allowed");if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"-",pos:c}),n+=1;continue}case"*":{if(i(1)==="=")throw new Error("Assignment operators are not allowed");if(i(1)==="*")throw new Error("Exponentiation operator is not supported");e.push({type:"punct",value:"*",pos:c}),n+=1;continue}case"/":{if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"/",pos:c}),n+=1;continue}case"%":{if(i(1)==="=")throw new Error("Assignment operators are not allowed");e.push({type:"punct",value:"%",pos:c}),n+=1;continue}case"~":case"^":throw new Error("Bitwise operators are not allowed");case".":case":":case"(":case")":case"[":case"]":case"{":case"}":case",":e.push({type:"punct",value:l,pos:c}),n+=1;continue;case";":e.push({type:"punct",value:";",pos:c}),n+=1;continue;default:throw new Error(`Unexpected character "${l}" at position ${c}`)}}return e}const c0={"??":1,"||":1,"&&":2,"===":3,"!==":3,"==":3,"!=":3,"<":4,">":4,"<=":4,">=":4,"+":5,"-":5,"*":6,"/":6,"%":6},u0=new Set(["??","||","&&"]);class d0{constructor(e){$(this,"tokens");$(this,"pos",0);this.tokens=e}atEnd(){return this.pos>=this.tokens.length}peek(e=0){const n=this.pos+e;return n"}"`);this.pos++}parseExpression(){const e=this.tryParseArrow();return e||this.parseTernary()}tryParseArrow(){const e=this.pos,n=this.peek();if(!n)return null;if(n.type==="ident"&&this.isPunct("=>",1)&&!cc.has(String(n.value))){this.pos+=1,this.pos+=1;const{body:r,isBlock:i}=this.parseArrowBody();return{type:"Arrow",params:[{name:String(n.value),default:null}],body:r,isBlock:i}}if(n.type==="punct"&&n.value==="("){this.pos+=1;const r=this.tryParseParamList();if(r&&this.isPunct(")")&&(this.pos+=1,this.isPunct("=>"))){this.pos+=1;const{body:i,isBlock:l}=this.parseArrowBody();return{type:"Arrow",params:r,body:i,isBlock:l}}return this.pos=e,null}return this.pos=e,null}tryParseParamList(){const e=[];if(this.isPunct(")"))return e;for(;;){const n=this.peek();let r=null,i;if(n&&n.type==="punct"&&n.value==="["){const c=this.tryParseArrayPattern();if(!c)return null;i=c}else if(n&&n.type==="ident"&&!cc.has(String(n.value)))r=String(n.value),this.pos+=1;else return null;let l=null;if(this.isPunct("=")&&(this.pos+=1,l=this.parseExpression()),e.push(i?{name:r,elements:i,default:l}:{name:r,default:l}),this.isPunct(",")){this.pos+=1;continue}break}return e}tryParseArrayPattern(){const e=this.pos;this.pos+=1;const n=[];for(;;){if(this.isPunct("]"))return this.pos+=1,n;if(this.isPunct(",")){n.push(null),this.pos+=1;continue}const r=this.peek();if(!r||r.type!=="ident"||cc.has(String(r.value)))return this.pos=e,null;if(n.push(String(r.value)),this.pos+=1,this.isPunct(",")){this.pos+=1;continue}return this.isPunct("]")?(this.pos+=1,n):(this.pos=e,null)}}parseArrowBody(){return this.isPunct("{")?{body:this.parseBlock(),isBlock:!0}:{body:this.parseExpression(),isBlock:!1}}parseBlock(){this.expectPunct("{");const e=[];for(;!this.isPunct("}");){if(this.atEnd())throw new Error("Unterminated block");e.push(this.parseStatement())}return this.expectPunct("}"),{type:"Block",body:e}}parseStatement(){const e=this.peek();if(!e)throw new Error("Unexpected end of statement");if(e.type==="punct"&&e.value==="{")return this.parseBlock();if(e.type==="punct"&&e.value===";")return this.pos+=1,{type:"Empty"};if(e.type==="ident")switch(String(e.value)){case"const":case"let":return this.parseVarDecl();case"if":return this.parseIf();case"for":return this.parseForOf();case"return":return this.parseReturn();case"try":return this.parseTry();case"break":return this.pos+=1,this.consumeSemicolon(),{type:"Break"};case"continue":return this.pos+=1,this.consumeSemicolon(),{type:"Continue"}}const n=this.parseExpression();return this.consumeSemicolon(),{type:"ExprStmt",expression:n}}consumeSemicolon(){this.isPunct(";")&&(this.pos+=1)}parseVarDecl(){this.pos+=1;const e=[];for(;;){const n=this.peek();if(!n||n.type!=="ident")throw new Error("Expected variable name in declaration");const r=String(n.value);this.pos+=1,this.expectPunct("=");const i=this.parseExpression();if(e.push({name:r,init:i}),this.isPunct(",")){this.pos+=1;continue}break}return this.consumeSemicolon(),{type:"VarDecl",declarations:e}}parseIf(){this.pos+=1,this.expectPunct("(");const e=this.parseExpression();this.expectPunct(")");const n=this.parseStatement();let r=null;const i=this.peek();return i&&i.type==="ident"&&i.value==="else"&&(this.pos+=1,r=this.parseStatement()),{type:"If",test:e,consequent:n,alternate:r}}parseForOf(){this.pos+=1,this.expectPunct("(");const e=this.peek();if(!e||e.type!=="ident"||e.value!=="const"&&e.value!=="let")throw new Error('Only "for (const x of …)" / "for (let x of …)" loops are supported');this.pos+=1;const n=this.peek();if(!n||n.type!=="ident")throw new Error("Expected loop variable name");const r=String(n.value);this.pos+=1;const i=this.peek();if(!i||i.type!=="ident"||i.value!=="of")throw new Error("Only for-of loops are supported (for-in / C-style for are not allowed)");this.pos+=1;const l=this.parseExpression();this.expectPunct(")");const c=this.parseStatement();return{type:"ForOf",name:r,iterable:l,body:c}}parseReturn(){if(this.pos+=1,this.isPunct(";")||this.isPunct("}")||this.atEnd())return this.consumeSemicolon(),{type:"Return",argument:null};const e=this.parseExpression();return this.consumeSemicolon(),{type:"Return",argument:e}}parseTry(){this.pos+=1;const e=this.parseBlock();let n=null,r=null,i=null;const l=this.peek();if(l&&l.type==="ident"&&l.value==="catch"){if(this.pos+=1,this.isPunct("(")){this.pos+=1;const d=this.peek();d&&d.type==="ident"&&(n=String(d.value),this.pos+=1),this.expectPunct(")")}r=this.parseBlock()}const c=this.peek();if(c&&c.type==="ident"&&c.value==="finally"&&(this.pos+=1,i=this.parseBlock()),!r&&!i)throw new Error("Missing catch or finally after try");return{type:"Try",block:e,handlerParam:n,handler:r,finalizer:i}}parseFunctionExpression(){this.pos+=1;let e=null;const n=this.peek();n&&n.type==="ident"&&n.value!==void 0&&!this.isPunct("(")&&(e=String(n.value),this.pos+=1),this.expectPunct("(");const r=this.tryParseParamList();if(!r)throw new Error("Invalid function parameter list");this.expectPunct(")");const i=this.parseBlock();return{type:"Function",name:e,params:r,body:i}}parseTernary(){const e=this.parseBinary(0);if(this.isPunct("?")){this.pos+=1;const n=this.parseExpression();this.expectPunct(":");const r=this.parseExpression();return{type:"Conditional",test:e,consequent:n,alternate:r}}return e}parseBinary(e){let n=this.parseUnary();for(;;){const r=this.peek();if(!r||r.type!=="punct")break;const i=String(r.value),l=c0[i];if(l===void 0||lHg(l));return{type:"Template",quasis:n,expressions:i}}if(e.type==="ident"&&e.value==="new")return this.parseNew();if(e.type==="ident"&&e.value==="function")return this.parseFunctionExpression();if(e.type==="ident"){const n=String(e.value);if(cc.has(n))throw new Error(`Keyword "${n}" is not allowed`);switch(this.pos+=1,n){case"true":return{type:"Literal",value:!0};case"false":return{type:"Literal",value:!1};case"null":return{type:"Literal",value:null};case"undefined":return{type:"Literal",value:void 0};default:return{type:"Identifier",name:n}}}if(e.type==="punct"){if(e.value==="("){this.pos+=1;const n=this.parseExpression();return this.expectPunct(")"),n}if(e.value==="[")return this.parseArrayLiteral();if(e.value==="{")return this.parseObjectLiteral()}throw new Error(`Unexpected token "${e.value}"`)}parseArrayLiteral(){this.expectPunct("[");const e=[];for(;!this.isPunct("]");){if(this.isPunct(",")){this.pos+=1,e.push({type:"Literal",value:void 0});continue}if(this.isPunct("...")?(this.pos+=1,e.push({type:"Spread",argument:this.parseExpression()})):e.push(this.parseExpression()),this.isPunct(",")){this.pos+=1;continue}break}return this.expectPunct("]"),{type:"Array",elements:e}}parseObjectLiteral(){this.expectPunct("{");const e=[];for(;!this.isPunct("}");){if(this.isPunct("..."))this.pos+=1,e.push({kind:"spread",value:this.parseExpression()});else{let n,r=!1;const i=this.peek();if(!i)throw new Error("Unexpected end of expression in object literal");if(i.type==="punct"&&i.value==="[")this.pos+=1,n=this.parseExpression(),this.expectPunct("]"),r=!0;else if(i.type==="str")this.pos+=1,n={type:"Literal",value:i.value};else if(i.type==="num")this.pos+=1,n={type:"Literal",value:String(i.value)};else if(i.type==="ident")this.pos+=1,n={type:"Literal",value:String(i.value)};else throw new Error(`Unexpected token "${i.value}" in object literal`);if(this.isPunct(":")){this.pos+=1;const l=this.parseExpression();e.push({kind:"init",key:n,computed:r,value:l})}else{if(r||n.type!=="Literal"||typeof n.value!="string")throw new Error("Invalid shorthand property in object literal");if(i.type!=="ident")throw new Error("Invalid shorthand property in object literal");e.push({kind:"init",key:n,computed:!1,value:{type:"Identifier",name:n.value}})}}if(this.isPunct(",")){this.pos+=1;continue}break}return this.expectPunct("}"),{type:"Object",properties:e}}}function Hg(s){const e=l0(s),n=new d0(e),r=n.parseExpression();if(!n.atEnd()){const i=n.peek();throw i&&i.type==="punct"&&i.value===","?new Error("The comma/sequence operator is not allowed"):new Error(`Unexpected token "${i?i.value:""}" after expression`)}return r}function f0(s,e){let n=e;for(;n;){if(Object.prototype.hasOwnProperty.call(n.vars,s))return n.vars[s];n=n.parent}if(Object.prototype.hasOwnProperty.call(qd,s))return qd[s];if(r0.has(s))throw new Error(`Reference to forbidden global "${s}" is not allowed`)}function Wd(s){const e=typeof s=="symbol"?s:String(s);if(typeof e=="string"&&vo.has(e))throw new Error(`Access to "${e}" is forbidden`);return e}function Yd(s,e){return s.type==="Member"?Ug(s,e):s.type==="Call"?Pg(s,e):Ze(s,e)}function Ug(s,e){const n=Yd(s.object,e);if(n===_r||s.optional&&n==null)return _r;let r;s.computed?r=Ze(s.property,e):r=s.property.value;const i=Wd(r);if(n!=null)return n[i]}function Pg(s,e){let n,r;if(s.callee.type==="Member"){const l=s.callee,c=Yd(l.object,e);if(c===_r||l.optional&&c==null)return _r;let d;l.computed?d=Ze(l.property,e):d=l.property.value;const f=Wd(d);c==null?n=void 0:(n=c[f],r=c)}else if(n=Yd(s.callee,e),n===_r)return _r;if(s.optional&&n==null)return _r;if(typeof n!="function")throw new Error("Attempted to call a non-function value");const i=Bg(s.args,e);return n.apply(r,i)}function Bg(s,e){const n=[];for(const r of s)if(r.type==="Spread"){const i=Ze(r.argument,e);if(i!=null)for(const l of i)n.push(l)}else n.push(Ze(r,e));return n}function qg(s,e,n){for(let r=0;r":return n>r;case"<=":return n<=r;case">=":return n>=r;default:throw new Error(`Unknown binary operator "${s.operator}"`)}}case"Logical":{const n=Ze(s.left,e);switch(s.operator){case"&&":return n&&Ze(s.right,e);case"||":return n||Ze(s.right,e);case"??":return n??Ze(s.right,e);default:throw new Error(`Unknown logical operator "${s.operator}"`)}}case"Conditional":return Ze(s.test,e)?Ze(s.consequent,e):Ze(s.alternate,e);case"Array":{const n=[];for(const r of s.elements)if(r.type==="Spread"){const i=Ze(r.argument,e);if(i!=null)for(const l of i)n.push(l)}else n.push(Ze(r,e));return n}case"Object":{const n={};for(const r of s.properties)if(r.kind==="spread"){const i=Ze(r.value,e);if(i!=null&&typeof i=="object")for(const l of Object.keys(i))Xd(n,l,i[l])}else{let i;r.computed?i=Ze(r.key,e):i=r.key.value;const l=Ze(r.value,e);Xd(n,String(i),l)}return n}case"Arrow":{const n=e,r=s.params,i=s.body,l=s.isBlock;return function(...d){const f={vars:{},parent:n};return qg(r,d,f),l?Gg(i,f):Ze(i,f)}}case"Function":{const n=e,r=s.params,i=s.body,l=s.name,c=function(...f){const p={vars:{},parent:n};return l&&(p.vars[l]=c),qg(r,f,p),Gg(i,p)};return c}case"Delete":{const n=s.argument,r=Ze(n.object,e);let i;n.computed?i=Ze(n.property,e):i=n.property.value;const l=Wd(i);if(r==null||typeof r!="object"&&typeof r!="function")return!0;if(jg.has(r))throw new Error("delete on a built-in global object is not allowed");return delete r[l]}case"Block":{const n={vars:{},parent:e};for(const r of s.body)Ze(r,n);return}case"VarDecl":{for(const n of s.declarations)e.vars[n.name]=Ze(n.init,e);return}case"If":{Ze(s.test,e)?Ze(s.consequent,e):s.alternate&&Ze(s.alternate,e);return}case"ForOf":{const n=Ze(s.iterable,e);if(n!=null)for(const r of n){const i={vars:{},parent:e};i.vars[s.name]=r;try{Ze(s.body,i)}catch(l){if(l instanceof Kd)continue;if(l instanceof Vd)break;throw l}}return}case"Return":throw new Fd(s.argument?Ze(s.argument,e):void 0);case"ExprStmt":Ze(s.expression,e);return;case"Break":throw new Vd;case"Continue":throw new Kd;case"Empty":return;case"Try":{try{try{Ze(s.block,e)}catch(n){if(n instanceof Fd||n instanceof Vd||n instanceof Kd)throw n;if(s.handler){const r={vars:{},parent:e};s.handlerParam&&(r.vars[s.handlerParam]=n),Ze(s.handler,r)}else throw n}}finally{s.finalizer&&Ze(s.finalizer,e)}return}case"New":{const n=Gd[s.ctor];if(typeof n!="function")throw new Error("new on non-whitelisted constructor");const r=Bg(s.args,e);return new n(...r)}case"Template":{let n=s.quasis[0]??"";for(let r=0;r0}getFromRenderCycleCache(e){if(this.isRenderCycleCacheActive())return this.renderCycleCache.get(e)}saveToRenderCycleCache(e,n){this.isRenderCycleCacheActive()&&this.renderCycleCache.set(e,n)}resolveBindings(e,n,r,i){const l={...this.defaultOptions,...r},c=So(),d=n._computed&&!n.$computed?{...n,$computed:n._computed}:n,f=(C,S)=>{const v=S.trim();let x=!1,w=v;if(v.startsWith(lr)&&(x=!0,w=v.slice(lr.length)),On(w))try{const P=this.evaluatePipeExpression(w,d,l,{...i,method:"resolveBindings",displayExpression:`{{${v}}}`}),K=this.formatValue(P);return x?bo(K):K}catch(P){return ja.error("Pipe expression evaluation failed:",w,P),C}if(mo(w)){const P=c?.isEnabled()?performance.now():0;try{let K,he=!1;if(l.skipCache)K=this.evaluateExpression(w,d);else{const ke=`expr:${w}`,ze=this.getFromRenderCycleCache(ke);ze!==void 0?(K=ze,he=!0):(K=this.evaluateExpression(w,d),this.saveToRenderCycleCache(ke,K))}if(c?.isEnabled()){const ke=performance.now()-P;c.trackExpressionEval({expression:`{{${v}}}`,result:this.sanitizeResultForTracking(K),resultType:this.getResultType(K),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:he,duration:ke,method:"resolveBindings",skipCache:l.skipCache})}const Ee=this.formatValue(K);return x?bo(Ee):Ee}catch(K){return ja.error("Expression evaluation failed:",w,K),C}}if(l.skipCache){const P=c?.isEnabled()?performance.now():0,K=this.resolvePath(w,d,l);if(c?.isEnabled()){const Ee=performance.now()-P;c.trackExpressionEval({expression:`{{${v}}}`,result:this.sanitizeResultForTracking(K),resultType:this.getResultType(K),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:Ee,method:"resolveBindings",skipCache:!0})}const he=this.formatValue(K);return x?bo(he):he}const L=w.startsWith("_global")||w.startsWith("_local")||w.startsWith("_isolated")||w.startsWith("$parent"),O=c?.isEnabled()?performance.now():0;let j,F=!1;if(L){const P=this.getFromRenderCycleCache(w);P!==void 0?(j=P,F=!0):(j=this.resolvePath(w,d,l),this.saveToRenderCycleCache(w,j))}else{const P=this.getFromCache(w);P!==void 0?(j=P,F=!0):(j=this.resolvePath(w,d,l),this.saveToCache(w,j))}if(c?.isEnabled()){const P=performance.now()-O;c.trackExpressionEval({expression:`{{${v}}}`,result:this.sanitizeResultForTracking(j),resultType:this.getResultType(j),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:F,duration:P,method:"resolveBindings",skipCache:l.skipCache})}const G=this.formatValue(j);return x?bo(G):G},p=n0(e);if(p.length===0)return e;let m="",y=0;for(const C of p)m+=e.slice(y,C.start),m+=f(e.slice(C.start,C.end),C.expr),y=C.end;return m+e.slice(y)}evaluatePipeExpression(e,n,r,i){const l={...this.defaultOptions,...r},c=So(),d=c?.isEnabled()?performance.now():0,f=n._computed&&!n.$computed?{...n,$computed:n._computed}:n,[p,m]=e0(e);let y,C=!1;const S=mo(p),v=p.startsWith("_global")||p.startsWith("_local")||p.startsWith("_isolated")||p.startsWith("$parent");if(l.skipCache)S?y=this.evaluateExpression(p,f):y=this.resolvePath(p,f,l);else if(S){const w=this.getFromRenderCycleCache(`expr:${p}`);w!==void 0?(y=w,C=!0):(y=this.evaluateExpression(p,f),this.saveToRenderCycleCache(`expr:${p}`,y))}else if(v){const w=this.getFromRenderCycleCache(p);w!==void 0?(y=w,C=!0):(y=this.resolvePath(p,f,l),this.saveToRenderCycleCache(p,y))}else{const w=this.getFromCache(p);w!==void 0?(y=w,C=!0):(y=this.resolvePath(p,f,l),this.saveToCache(p,y))}const x=t0(y,m);if(c?.isEnabled()){const w=performance.now()-d;c.trackExpressionEval({expression:i?.displayExpression??`{{${e}}}`,result:this.sanitizeResultForTracking(x),resultType:this.getResultType(x),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:C,duration:w,method:i?.method??"evaluatePipeExpression",skipCache:l.skipCache})}return x}resolve(e,n,r,i){const l={...this.defaultOptions,...r},c=So(),d=c?.isEnabled()?performance.now():0;if(l.skipCache){const y=this.resolvePath(e,n,l);return c?.isEnabled()&&c.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()-d,method:"resolve",skipCache:!0}),y}const f=e.startsWith("_global")||e.startsWith("_local")||e.startsWith("_isolated")||e.startsWith("$parent");let p=!1;if(f){const y=this.getFromRenderCycleCache(e);if(y!==void 0)return p=!0,c?.isEnabled()&&c.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()-d,method:"resolve",skipCache:l.skipCache}),y}else{const y=this.getFromCache(e);if(y!==void 0)return p=!0,c?.isEnabled()&&c.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()-d,method:"resolve",skipCache:l.skipCache}),y}const m=this.resolvePath(e,n,l);return f?this.saveToRenderCycleCache(e,m):this.saveToCache(e,m),c?.isEnabled()&&c.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(m),resultType:this.getResultType(m),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:p,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),m}resolvePath(e,n,r,i=0,l=new WeakSet){if(typeof e!="string"||e.trim()===""){ja.warn("resolvePath: 빈 경로가 전달되었습니다 — undefined 로 해석합니다.");return}if(r.maxDepth&&i>r.maxDepth){if(r.detectCircular)throw new Qd(`Maximum depth exceeded (${r.maxDepth}). Possible circular reference.`,e,n);return r.defaultValue}const c=this.parsePath(e);let d=n;for(let f=0;fua.CACHE_EXPIRY){this.cache.delete(e),r?.isEnabled()&&r.recordCacheMiss();return}return r?.isEnabled()&&r.recordCacheHit(),n.value}saveToCache(e,n){this.cache.set(e,{value:n,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,n,r){if(this.isSwitchExpression(e)){const d=e;return this.resolveSwitch(d,n,r)}if(this.isActionDefinition(e))return{...e};if("iteration"in e)return{...e};const i={},c=[...["cellChildren","expandChildren","expandContext","render"],...r?.skipBindingKeys||[]];for(const[d,f]of Object.entries(e)){if(c.includes(d)){i[d]=f;continue}try{this.resolveObjectEntry(i,d,f,n,r)}catch(p){ja.warn(`resolveObject: 값 해석 실패 (key: ${d}):`,p),i[d]=void 0}}return i}resolveObjectEntry(e,n,r,i,l){if(typeof r=="string"){const c=Ma(r);if(c!==null){const d=c.trim();let f=!1,p=d;d.startsWith(lr)&&(f=!0,p=d.slice(lr.length));let m;switch(Mg(p)){case"empty":ja.warn(`resolveObject: 빈 바인딩 \`{{}}\` (key: ${n}) — undefined 로 해석합니다.`),m=void 0;break;case"literal":m=Ud.get(p);break;case"pipe":m=this.evaluatePipeExpression(p,i,l);break;case"expression":m=this.evaluateExpression(p,i,l);break;default:m=this.resolve(p,i,l)}e[n]=f&&m!=null?ss(m):m}else e[n]=this.resolveBindings(r,i,l)}else Array.isArray(r)?e[n]=r.map(c=>typeof c=="string"?this.resolveBindings(c,i,l):typeof c=="object"&&c!==null?this.resolveObject(c,i,l):c):r&&typeof r=="object"?e[n]=this.resolveObject(r,i,l):e[n]=r}clearCache(){this.cache.clear()}invalidateCacheByKeys(e){for(const n of this.cache.keys())for(const r of e)if(n===r||n.startsWith(`${r}.`)||n.startsWith(`${r}[`)){this.cache.delete(n);break}}pruneCache(){const e=Date.now();for(const[n,r]of this.cache.entries())e-r.timestamp>ua.CACHE_EXPIRY&&this.cache.delete(n)}getCacheStats(){const e=Date.now();let n=0;for(const r of this.cache.values())e-r.timestamp>ua.CACHE_EXPIRY&&n++;return{size:this.cache.size,expired:n}}evaluateExpression(e,n,r){const i=So(),l=i?.isEnabled()?performance.now():0;i?.isEnabled()&&i.trackBindingEval();try{let c=this.preprocessOptionalChaining(e);c=this.preprocessTranslationTokens(c);const d=this.extractVariablesFromExpression(c),f={...n};for(const w of d)w in f||(f[w]=void 0);n._computed&&!f.$computed&&(f.$computed=n._computed);let p=n.$templateId,m=n.$locale;if(typeof window<"u"&&(!p||!m)){const w=window.__templateApp?.getConfig?.();p??(p=w?.templateId),m??(m=w?.locale)}const y=m||"ko";f.$localized=(w,R)=>{if(w==null&&!R)return"";if(typeof w=="string")return w;if(w&&typeof w=="object"&&w[y])return w[y];if(R&&typeof R=="string"){const L=f.$t?f.$t(R):R;if(L&&L!==R)return L}return w&&typeof w=="object"?w.ko||w.en||Object.values(w)[0]||"":w==null?"":String(w)};const C=typeof window<"u"?window.G7Core:void 0;f.$uuid=()=>C?.uuid?C.uuid():typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,w=>{const R=Math.random()*16|0;return(w==="x"?R:R&3|8).toString(16)});const S={templateId:p||"",locale:y};f.$t=w=>{if(!w||typeof w!="string")return"";try{return wi.getInstance().translate(w,S)}catch(R){return ja.warn("$t() translation failed for key:",w,R),w}},f.$get=(w,R,L=void 0)=>{if(w==null)return L;const O=Array.isArray(R)?R:[R];if(O.length===0)return w;let j=w;for(const F of O){if(j==null||F==null)return L;j=j[F]}return j??L};const v=!1,x=Jd(c,f);if(i?.isEnabled()){const w=performance.now()-l;i.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(x),resultType:this.getResultType(x),componentId:r?.componentId,componentName:r?.componentName,propName:r?.propName,fromCache:v,duration:w,method:"evaluateExpression",skipCache:r?.skipCache})}return x}catch(c){throw new Error(`Failed to evaluate expression "${e}": ${c instanceof Error?c.message:String(c)}`)}}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 n=Object.keys(e);return n.length>20?`{Object(${n.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,(n,r,i,l)=>`$t('${l}')`),e.replace(/(['"]\s*)?(\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*)(?!\s*['"])/g,(n,r,i)=>r?n:`"${i}"`)}preprocessOptionalChaining(e){const n=[];let r=e.replace(/(['"])(?:(?!\1|\\).|\\.)*\1/g,l=>(n.push(l),`__STRING_LITERAL_${n.length-1}__`));const i=[];return r=r.replace(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*(?:\|[^'"\s,)]+)?/g,l=>(i.push(l),`__TRANSLATION_TOKEN_${i.length-1}__`)),r=r.replace(/([a-zA-Z_$][a-zA-Z0-9_$]*)\.(?!\?)/g,"$1?."),r=r.replace(/__TRANSLATION_TOKEN_(\d+)__/g,(l,c)=>i[parseInt(c,10)]),r=r.replace(/__STRING_LITERAL_(\d+)__/g,(l,c)=>n[parseInt(c,10)]),r}extractVariablesFromExpression(e){const n=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","Set","Map","WeakSet","WeakMap","Symbol","Promise","BigInt","Error","parseInt","parseFloat","isNaN","isFinite","encodeURI","decodeURI","encodeURIComponent","decodeURIComponent"]),r=/(^|[^.\w$])([a-zA-Z_$][a-zA-Z0-9_$]*)/g,i=new Set;let l;for(;(l=r.exec(e))!==null;){const c=l[2];n.has(c)||i.add(c)}return Array.from(i)}isSwitchExpression(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"$switch"in e&&"$cases"in e}resolveSwitch(e,n,r){const i={...r,skipCache:!0};let l;try{l=this.resolveBindings(e.$switch,n,i)?.toString()?.trim()??""}catch(d){ja.warn("resolveSwitch: $switch 키 평가 실패:",e.$switch,d),l=""}let c;if(l&&e.$cases&&l in e.$cases)c=e.$cases[l];else if("$default"in e)c=e.$default;else return;return typeof c=="string"?c.includes("{{")?this.resolveBindings(c,n,i):c:c!==null&&typeof c=="object"?this.resolveObject(c,n,i):c}};$(ua,"PATH_SEGMENT_PATTERN",/([^.[\]]+)|\[(\d+)\]/g),$(ua,"CACHE_EXPIRY",3e4);let Tn=ua;const uc=new Tn,dc={mobile:{min:0,max:767},tablet:{min:768,max:1023},desktop:{min:1024,max:1/0},portable:{min:0,max:1023}},fc=new Map;function h0(s,e){let n=null;return((...r)=>{n!==null&&clearTimeout(n),n=setTimeout(()=>{s(...r)},e)})}class p0{constructor(){$(this,"subscribers",new Set);$(this,"currentWidth",1024);$(this,"debouncedHandler",null);$(this,"isInitialized",!1);this.initialize()}initialize(){typeof window>"u"||(this.currentWidth=window.innerWidth,this.isInitialized=!0,this.debouncedHandler=h0(()=>{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(fc.has(e))return fc.get(e)??null;let n=null;if(dc[e])n={...dc[e]};else{const r=e.match(/^(-?\d*)-(-?\d*)$/);if(r){const[,i,l]=r,c=i===""?0:parseInt(i,10),d=l===""?1/0:parseInt(l,10);!isNaN(c)&&!isNaN(d)&&c<=d&&(n={min:c,max:d})}}return fc.set(e,n),n}getMatchingKey(e,n){const r=[];for(const i of Object.keys(e)){const l=this.parseRange(i);l&&n>=l.min&&n<=l.max&&r.push({key:i,range:l,isPreset:!!dc[i]})}return r.length===0?null:(r.sort((i,l)=>{if(i.isPreset!==l.isPreset)return i.isPreset?1:-1;const c=i.range.max-i.range.min,d=l.range.max-l.range.min;return c-d}),r[0].key)}matches(e){const n=this.parseRange(e);return n?this.currentWidth>=n.min&&this.currentWidth<=n.max:!1}clearSubscribers(){this.subscribers.clear()}destroy(){this.debouncedHandler&&typeof window<"u"&&window.removeEventListener("resize",this.debouncedHandler),this.clearSubscribers(),fc.clear()}_setWidthForTesting(e){this.currentWidth=e,this.notifySubscribers()}}const _i=new p0,wo=dt("ConditionEvaluator");function g0(s,e,n,r){return Pd(Ng(s),e,n,{skipCache:!0,onEmpty:()=>{wo.warn(`${r}: 빈 바인딩 \`{{}}\` — undefined 로 해석합니다.`)}})}function Fg(s,e,n){if(!s)return!0;try{const r=Ma(s);let i;if(r!==null?i=g0(r,e,n,"evaluateStringCondition"):i=n.resolveBindings(s,e,{skipCache:!0}),typeof i=="string"){const l=i.toLowerCase().trim();if(l==="false"||l==="0"||l===""||l==="null"||l==="undefined")return!1}return!!i}catch(r){return wo.warn(`evaluateStringCondition: 조건 평가 실패: ${s}`,r),!1}}function hc(s,e,n){if(typeof s=="string")return Fg(s,e,n);if("and"in s){if(!Array.isArray(s.and)||s.and.length===0)return wo.warn("evaluateConditionExpression: AND 그룹이 비어있습니다"),!0;for(const r of s.and)if(!hc(r,e,n))return!1;return!0}if("or"in s){if(!Array.isArray(s.or)||s.or.length===0)return wo.warn("evaluateConditionExpression: OR 그룹이 비어있습니다"),!1;for(const r of s.or)if(hc(r,e,n))return!0;return!1}return wo.warn("evaluateConditionExpression: 알 수 없는 조건 형식",s),!1}function Vg(s,e,n){if(!Array.isArray(s)||s.length===0)return{matched:!1,branchIndex:-1};for(let r=0;r{cr.warn(`evaluateIfCondition: 빈 바인딩 \`{{}}\` (컴포넌트: ${r||"unknown"}) — undefined 로 해석합니다.`)}}):l=n.resolveBindings(s,e,{skipCache:!0}),typeof l=="string"){const c=l.toLowerCase().trim();if(c==="false"||c==="0"||c===""||c==="null"||c==="undefined")return!1}return!!l}catch(i){return cr.warn(`evaluateIfCondition: 조건 평가 실패 (컴포넌트: ${r||"unknown"}):`,i),!1}}function os(s,e,n,r){if(s.if!==void 0)return Xg(s.if,e,n,r);if(s.condition!==void 0)return Xg(s.condition,e,n,r);if(s.conditions===void 0)return!0;const i=s.conditions;try{return m0(i)?hc(i,e,n):y0(i)?Vg(i,e,n).matched:(cr.warn(`evaluateRenderCondition: 알 수 없는 conditions 형식 (컴포넌트: ${r||"unknown"})`),!0)}catch(l){return cr.warn(`evaluateRenderCondition: conditions 평가 실패 (컴포넌트: ${r||"unknown"}):`,l),!1}}function Jg(s){if(!s.responsive)return s;const e=_i.getWidth(),n=_i.getMatchingKey(s.responsive,e);if(!n)return s;const r=s.responsive[n];return{...s,props:{...s.props,...r.props},children:r.children??s.children,text:r.text??s.text,if:r.if??s.if,iteration:r.iteration??s.iteration}}function Co(s,e,n,r,i){if(!s||s.length===0)return[];const l=i?.bindingEngine??new Tn,c=i?.translationEngine??wi.getInstance(),d=i?.translationContext??{templateId:"",locale:"ko"},f=v0(e,i?.componentContext),p=(S,v)=>{if(typeof S=="string")return oc(S)||lc(S)||!/\$t:[a-zA-Z0-9._-]+/.test(S)?S:c.resolveTranslations(S,d,v);if(Array.isArray(S))return S.map(x=>p(x,v));if(S&&typeof S=="object"){const x={};for(const[w,R]of Object.entries(S))x[w]=p(R,v);return x}return S},m=(S,v)=>{if(typeof S=="string"){if(oc(S))return Bd(S);if(lc(S)){const w=[],R=S.replace(new RegExp(`${yo}([^${Ci}]*)${Ci}`,"g"),(O,j)=>(w.push(j),`${Na}${w.length-1}${Na}`));let L=R;return/\$t:[a-zA-Z0-9._-]+/.test(R)&&(L=c.resolveTranslations(R,d,v)),L.replace(new RegExp(`${Na}(\\d+)${Na}`,"g"),(O,j)=>w[parseInt(j)])}if(S.startsWith("$t:defer:")){const w="$t:"+S.slice(9);return c.resolveTranslations(w,d,v)}if(S.startsWith("$t:"))return c.resolveTranslations(S,d,v);if(/\$t:[a-zA-Z0-9._-]+/.test(S)){const w=S.trim();if(!(w.startsWith("{")&&w.endsWith("}")||w.startsWith("[")&&w.endsWith("]"))&&!S.includes("{{"))return c.resolveTranslations(S,d,v)}const x=Yg(S);if(x!==null){let w=!1,R=x;x.startsWith(lr)&&(w=!0,R=x.slice(lr.length));let L=!1,O=Pd(R,v,l,{skipCache:!0,onError:j=>{cr.warn("renderItemChildren: 표현식 평가 실패:",j),L=!0},onEmpty:()=>{cr.warn("renderItemChildren: 빈 바인딩 `{{}}` 은 해석하지 않습니다.")}});return L?void 0:(w||(O=p(O,v)),w&&O!=null?ss(O):O)}if(S.includes("{{")){const w=l.resolveBindings(S,v,{skipCache:!0});return typeof w=="string"&&/\$t:[a-zA-Z0-9._-]+/.test(w)?c.resolveTranslations(w,d,v):w}return S}if(Array.isArray(S))return S.map(x=>m(x,v));if(S&&typeof S=="object"){if(l.isSwitchExpression(S))return l.resolveSwitch(S,v,{skipCache:!0});if(l.isActionDefinition(S))return{...S};const x={};for(const[w,R]of Object.entries(S))x[w]=m(R,v);return x}return S},y=(S,v)=>{if(!S)return{};const x={};for(const[w,R]of Object.entries(S))x[w]=m(R,v);return x},C=(S,v,x)=>{const w=Jg(S),R=w.iteration;if(!R)return[];const L=Zd(R.source,x,l);if(!Array.isArray(L))return cr.warn(`renderItemChildren: iteration.source가 배열이 아닙니다: ${R.source}`),[];const O=Kg();if(O?.isEnabled()){const F=`${v}-iteration`;O.trackIteration(F,R.source,R.item_var,R.index_var,L.length)}const j=n[w.name];return j?L.flatMap((F,G)=>{const P={...x,[R.item_var]:F,[`${R.item_var}_index`]:G,...R.index_var?{[R.index_var]:G}:{}},K=os({if:w.if,condition:w.condition,conditions:w.conditions},P,l,w.id);if(w.if&&O?.isEnabled()){const bt=`${v}-iter-${G}-if`;O.trackIfCondition(bt,w.if,K,w.name)}if(!K)return[];const he=w.id?String(Ia(m(w.id,P))):void 0,Ee=`${v}-iter-${G}`,ke=i?.getRemountKey?i.getRemountKey(he,Ee):Ee,ze=y(w.props,P),Be=ef(ze,w.actions,P,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let je=null;return w.text!==void 0?je=m(w.text,P):w.children&&w.children.length>0&&(je=Co(w.children,P,n,ke,i)),O?.isEnabled()&&O.trackRender(w.name),[We.createElement(j,{key:ke,...Ia(Be)},Ia(je))]}):(cr.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${w.name}`),[])};return s.flatMap((S,v)=>{const x=Jg(S),w=x.id?String(Ia(m(x.id,f))):void 0,R=r?`${r}-${w||v}`:w||`child-${v}`,L=i?.getRemountKey?i.getRemountKey(w,R):R;if(x.iteration)return C(x,L,f);const O=os({if:x.if,condition:x.condition,conditions:x.conditions},f,l,x.id),j=Kg();if(x.if&&j?.isEnabled()){const he=`${L}-if`;j.trackIfCondition(he,x.if,O,x.name)}if(!O)return[];const F=n[x.name];if(!F)return cr.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${x.name}`),[];const G=y(x.props,f),P=ef(G,x.actions,f,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let K=null;return x.text!==void 0?K=m(x.text,f):x.children&&x.children.length>0&&(K=Co(x.children,f,n,L,i)),j?.isEnabled()&&j.trackRender(x.name),[We.createElement(F,{key:L,...Ia(P)},Ia(K))]})}function ls(s,e,n,r){let i,l;return n instanceof Tn?(i=n,l=r):(i=Wg,l=n),i.resolveBindings(s,e,l)}function S0(s,e,n,r){const i=n??Wg,l={skipCache:!0,...r};let c;try{c=i.resolveBindings(s.key,e,{skipCache:l.skipCache})?.toString()?.trim()??""}catch(p){cr.warn("resolveClassMap: key 평가 실패:",s.key,p),c=""}let d="";c&&s.variants&&c in s.variants?d=s.variants[c]:s.default&&(d=s.default);const f=[];return s.base?.trim()&&f.push(s.base.trim()),d?.trim()&&f.push(d.trim()),f.join(" ")}function Qg(s,e){return function(){return s.apply(e,arguments)}}const{toString:w0}=Object.prototype,{getPrototypeOf:tf}=Object,{iterator:pc,toStringTag:Zg}=Symbol,gc=(s=>e=>{const n=w0.call(e);return s[n]||(s[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),Ar=s=>(s=s.toLowerCase(),e=>gc(e)===s),mc=s=>e=>typeof e===s,{isArray:cs}=Array,us=mc("undefined");function Eo(s){return s!==null&&!us(s)&&s.constructor!==null&&!us(s.constructor)&&Ln(s.constructor.isBuffer)&&s.constructor.isBuffer(s)}const em=Ar("ArrayBuffer");function C0(s){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(s):e=s&&s.buffer&&em(s.buffer),e}const E0=mc("string"),Ln=mc("function"),tm=mc("number"),_o=s=>s!==null&&typeof s=="object",_0=s=>s===!0||s===!1,yc=s=>{if(gc(s)!=="object")return!1;const e=tf(s);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(Zg in s)&&!(pc in s)},A0=s=>{if(!_o(s)||Eo(s))return!1;try{return Object.keys(s).length===0&&Object.getPrototypeOf(s)===Object.prototype}catch{return!1}},x0=Ar("Date"),T0=Ar("File"),k0=Ar("Blob"),R0=Ar("FileList"),D0=s=>_o(s)&&Ln(s.pipe),O0=s=>{let e;return s&&(typeof FormData=="function"&&s instanceof FormData||Ln(s.append)&&((e=gc(s))==="formdata"||e==="object"&&Ln(s.toString)&&s.toString()==="[object FormData]"))},L0=Ar("URLSearchParams"),[$0,M0,N0,I0]=["ReadableStream","Request","Response","Headers"].map(Ar),j0=s=>s.trim?s.trim():s.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function Ao(s,e,{allOwnKeys:n=!1}={}){if(s===null||typeof s>"u")return;let r,i;if(typeof s!="object"&&(s=[s]),cs(s))for(r=0,i=s.length;r0;)if(i=n[r],e===i.toLowerCase())return i;return null}const Ai=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,rm=s=>!us(s)&&s!==Ai;function nf(){const{caseless:s,skipUndefined:e}=rm(this)&&this||{},n={},r=(i,l)=>{const c=s&&nm(n,l)||l;yc(n[c])&&yc(i)?n[c]=nf(n[c],i):yc(i)?n[c]=nf({},i):cs(i)?n[c]=i.slice():(!e||!us(i))&&(n[c]=i)};for(let i=0,l=arguments.length;i(Ao(e,(i,l)=>{n&&Ln(i)?s[l]=Qg(i,n):s[l]=i},{allOwnKeys:r}),s),H0=s=>(s.charCodeAt(0)===65279&&(s=s.slice(1)),s),U0=(s,e,n,r)=>{s.prototype=Object.create(e.prototype,r),s.prototype.constructor=s,Object.defineProperty(s,"super",{value:e.prototype}),n&&Object.assign(s.prototype,n)},P0=(s,e,n,r)=>{let i,l,c;const d={};if(e=e||{},s==null)return e;do{for(i=Object.getOwnPropertyNames(s),l=i.length;l-- >0;)c=i[l],(!r||r(c,s,e))&&!d[c]&&(e[c]=s[c],d[c]=!0);s=n!==!1&&tf(s)}while(s&&(!n||n(s,e))&&s!==Object.prototype);return e},B0=(s,e,n)=>{s=String(s),(n===void 0||n>s.length)&&(n=s.length),n-=e.length;const r=s.indexOf(e,n);return r!==-1&&r===n},q0=s=>{if(!s)return null;if(cs(s))return s;let e=s.length;if(!tm(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=s[e];return n},G0=(s=>e=>s&&e instanceof s)(typeof Uint8Array<"u"&&tf(Uint8Array)),F0=(s,e)=>{const r=(s&&s[pc]).call(s);let i;for(;(i=r.next())&&!i.done;){const l=i.value;e.call(s,l[0],l[1])}},V0=(s,e)=>{let n;const r=[];for(;(n=s.exec(e))!==null;)r.push(n);return r},K0=Ar("HTMLFormElement"),W0=s=>s.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,r,i){return r.toUpperCase()+i}),am=(({hasOwnProperty:s})=>(e,n)=>s.call(e,n))(Object.prototype),Y0=Ar("RegExp"),im=(s,e)=>{const n=Object.getOwnPropertyDescriptors(s),r={};Ao(n,(i,l)=>{let c;(c=e(i,l,s))!==!1&&(r[l]=c||i)}),Object.defineProperties(s,r)},X0=s=>{im(s,(e,n)=>{if(Ln(s)&&["arguments","caller","callee"].indexOf(n)!==-1)return!1;const r=s[n];if(Ln(r)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},J0=(s,e)=>{const n={},r=i=>{i.forEach(l=>{n[l]=!0})};return cs(s)?r(s):r(String(s).split(e)),n},Q0=()=>{},Z0=(s,e)=>s!=null&&Number.isFinite(s=+s)?s:e;function eC(s){return!!(s&&Ln(s.append)&&s[Zg]==="FormData"&&s[pc])}const tC=s=>{const e=new Array(10),n=(r,i)=>{if(_o(r)){if(e.indexOf(r)>=0)return;if(Eo(r))return r;if(!("toJSON"in r)){e[i]=r;const l=cs(r)?[]:{};return Ao(r,(c,d)=>{const f=n(c,i+1);!us(f)&&(l[d]=f)}),e[i]=void 0,l}}return r};return n(s,0)},nC=Ar("AsyncFunction"),rC=s=>s&&(_o(s)||Ln(s))&&Ln(s.then)&&Ln(s.catch),sm=((s,e)=>s?setImmediate:e?((n,r)=>(Ai.addEventListener("message",({source:i,data:l})=>{i===Ai&&l===n&&r.length&&r.shift()()},!1),i=>{r.push(i),Ai.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",Ln(Ai.postMessage)),aC=typeof queueMicrotask<"u"?queueMicrotask.bind(Ai):typeof process<"u"&&process.nextTick||sm,ee={isArray:cs,isArrayBuffer:em,isBuffer:Eo,isFormData:O0,isArrayBufferView:C0,isString:E0,isNumber:tm,isBoolean:_0,isObject:_o,isPlainObject:yc,isEmptyObject:A0,isReadableStream:$0,isRequest:M0,isResponse:N0,isHeaders:I0,isUndefined:us,isDate:x0,isFile:T0,isBlob:k0,isRegExp:Y0,isFunction:Ln,isStream:D0,isURLSearchParams:L0,isTypedArray:G0,isFileList:R0,forEach:Ao,merge:nf,extend:z0,trim:j0,stripBOM:H0,inherits:U0,toFlatObject:P0,kindOf:gc,kindOfTest:Ar,endsWith:B0,toArray:q0,forEachEntry:F0,matchAll:V0,isHTMLForm:K0,hasOwnProperty:am,hasOwnProp:am,reduceDescriptors:im,freezeMethods:X0,toObjectSet:J0,toCamelCase:W0,noop:Q0,toFiniteNumber:Z0,findKey:nm,global:Ai,isContextDefined:rm,isSpecCompliantForm:eC,toJSONObject:tC,isAsyncFn:nC,isThenable:rC,setImmediate:sm,asap:aC,isIterable:s=>s!=null&&Ln(s[pc])};function Ye(s,e,n,r,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=s,this.name="AxiosError",e&&(this.code=e),n&&(this.config=n),r&&(this.request=r),i&&(this.response=i,this.status=i.status?i.status:null)}ee.inherits(Ye,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:ee.toJSONObject(this.config),code:this.code,status:this.status}}});const om=Ye.prototype,lm={};["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(s=>{lm[s]={value:s}}),Object.defineProperties(Ye,lm),Object.defineProperty(om,"isAxiosError",{value:!0}),Ye.from=(s,e,n,r,i,l)=>{const c=Object.create(om);ee.toFlatObject(s,c,function(m){return m!==Error.prototype},p=>p!=="isAxiosError");const d=s&&s.message?s.message:"Error",f=e==null&&s?s.code:e;return Ye.call(c,d,f,n,r,i),s&&c.cause==null&&Object.defineProperty(c,"cause",{value:s,configurable:!0}),c.name=s&&s.name||"Error",l&&Object.assign(c,l),c};const iC=null;function rf(s){return ee.isPlainObject(s)||ee.isArray(s)}function cm(s){return ee.endsWith(s,"[]")?s.slice(0,-2):s}function um(s,e,n){return s?s.concat(e).map(function(i,l){return i=cm(i),!n&&l?"["+i+"]":i}).join(n?".":""):e}function sC(s){return ee.isArray(s)&&!s.some(rf)}const oC=ee.toFlatObject(ee,{},null,function(e){return/^is[A-Z]/.test(e)});function bc(s,e,n){if(!ee.isObject(s))throw new TypeError("target must be an object");e=e||new FormData,n=ee.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(x,w){return!ee.isUndefined(w[x])});const r=n.metaTokens,i=n.visitor||m,l=n.dots,c=n.indexes,f=(n.Blob||typeof Blob<"u"&&Blob)&&ee.isSpecCompliantForm(e);if(!ee.isFunction(i))throw new TypeError("visitor must be a function");function p(v){if(v===null)return"";if(ee.isDate(v))return v.toISOString();if(ee.isBoolean(v))return v.toString();if(!f&&ee.isBlob(v))throw new Ye("Blob is not supported. Use a Buffer instead.");return ee.isArrayBuffer(v)||ee.isTypedArray(v)?f&&typeof Blob=="function"?new Blob([v]):Buffer.from(v):v}function m(v,x,w){let R=v;if(v&&!w&&typeof v=="object"){if(ee.endsWith(x,"{}"))x=r?x:x.slice(0,-2),v=JSON.stringify(v);else if(ee.isArray(v)&&sC(v)||(ee.isFileList(v)||ee.endsWith(x,"[]"))&&(R=ee.toArray(v)))return x=cm(x),R.forEach(function(O,j){!(ee.isUndefined(O)||O===null)&&e.append(c===!0?um([x],j,l):c===null?x:x+"[]",p(O))}),!1}return rf(v)?!0:(e.append(um(w,x,l),p(v)),!1)}const y=[],C=Object.assign(oC,{defaultVisitor:m,convertValue:p,isVisitable:rf});function S(v,x){if(!ee.isUndefined(v)){if(y.indexOf(v)!==-1)throw Error("Circular reference detected in "+x.join("."));y.push(v),ee.forEach(v,function(R,L){(!(ee.isUndefined(R)||R===null)&&i.call(e,R,ee.isString(L)?L.trim():L,x,C))===!0&&S(R,x?x.concat(L):[L])}),y.pop()}}if(!ee.isObject(s))throw new TypeError("data must be an object");return S(s),e}function dm(s){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(s).replace(/[!'()~]|%20|%00/g,function(r){return e[r]})}function af(s,e){this._pairs=[],s&&bc(s,this,e)}const fm=af.prototype;fm.append=function(e,n){this._pairs.push([e,n])},fm.toString=function(e){const n=e?function(r){return e.call(this,r,dm)}:dm;return this._pairs.map(function(i){return n(i[0])+"="+n(i[1])},"").join("&")};function lC(s){return encodeURIComponent(s).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function hm(s,e,n){if(!e)return s;const r=n&&n.encode||lC;ee.isFunction(n)&&(n={serialize:n});const i=n&&n.serialize;let l;if(i?l=i(e,n):l=ee.isURLSearchParams(e)?e.toString():new af(e,n).toString(r),l){const c=s.indexOf("#");c!==-1&&(s=s.slice(0,c)),s+=(s.indexOf("?")===-1?"?":"&")+l}return s}class pm{constructor(){this.handlers=[]}use(e,n,r){return this.handlers.push({fulfilled:e,rejected:n,synchronous:r?r.synchronous:!1,runWhen:r?r.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){ee.forEach(this.handlers,function(r){r!==null&&e(r)})}}const gm={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},cC={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:af,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},sf=typeof window<"u"&&typeof document<"u",of=typeof navigator=="object"&&navigator||void 0,uC=sf&&(!of||["ReactNative","NativeScript","NS"].indexOf(of.product)<0),dC=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",fC=sf&&window.location.href||"http://localhost",Cn={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:sf,hasStandardBrowserEnv:uC,hasStandardBrowserWebWorkerEnv:dC,navigator:of,origin:fC},Symbol.toStringTag,{value:"Module"})),...cC};function hC(s,e){return bc(s,new Cn.classes.URLSearchParams,{visitor:function(n,r,i,l){return Cn.isNode&&ee.isBuffer(n)?(this.append(r,n.toString("base64")),!1):l.defaultVisitor.apply(this,arguments)},...e})}function pC(s){return ee.matchAll(/\w+|\[(\w*)]/g,s).map(e=>e[0]==="[]"?"":e[1]||e[0])}function gC(s){const e={},n=Object.keys(s);let r;const i=n.length;let l;for(r=0;r=n.length;return c=!c&&ee.isArray(i)?i.length:c,f?(ee.hasOwnProp(i,c)?i[c]=[i[c],r]:i[c]=r,!d):((!i[c]||!ee.isObject(i[c]))&&(i[c]=[]),e(n,r,i[c],l)&&ee.isArray(i[c])&&(i[c]=gC(i[c])),!d)}if(ee.isFormData(s)&&ee.isFunction(s.entries)){const n={};return ee.forEachEntry(s,(r,i)=>{e(pC(r),i,n,0)}),n}return null}function mC(s,e,n){if(ee.isString(s))try{return(e||JSON.parse)(s),ee.trim(s)}catch(r){if(r.name!=="SyntaxError")throw r}return(n||JSON.stringify)(s)}const xo={transitional:gm,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const r=n.getContentType()||"",i=r.indexOf("application/json")>-1,l=ee.isObject(e);if(l&&ee.isHTMLForm(e)&&(e=new FormData(e)),ee.isFormData(e))return i?JSON.stringify(mm(e)):e;if(ee.isArrayBuffer(e)||ee.isBuffer(e)||ee.isStream(e)||ee.isFile(e)||ee.isBlob(e)||ee.isReadableStream(e))return e;if(ee.isArrayBufferView(e))return e.buffer;if(ee.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let d;if(l){if(r.indexOf("application/x-www-form-urlencoded")>-1)return hC(e,this.formSerializer).toString();if((d=ee.isFileList(e))||r.indexOf("multipart/form-data")>-1){const f=this.env&&this.env.FormData;return bc(d?{"files[]":e}:e,f&&new f,this.formSerializer)}}return l||i?(n.setContentType("application/json",!1),mC(e)):e}],transformResponse:[function(e){const n=this.transitional||xo.transitional,r=n&&n.forcedJSONParsing,i=this.responseType==="json";if(ee.isResponse(e)||ee.isReadableStream(e))return e;if(e&&ee.isString(e)&&(r&&!this.responseType||i)){const c=!(n&&n.silentJSONParsing)&&i;try{return JSON.parse(e,this.parseReviver)}catch(d){if(c)throw d.name==="SyntaxError"?Ye.from(d,Ye.ERR_BAD_RESPONSE,this,null,this.response):d}}return e}],timeout:0,xsrfCookieName:"XSRF-TOKEN",xsrfHeaderName:"X-XSRF-TOKEN",maxContentLength:-1,maxBodyLength:-1,env:{FormData:Cn.classes.FormData,Blob:Cn.classes.Blob},validateStatus:function(e){return e>=200&&e<300},headers:{common:{Accept:"application/json, text/plain, */*","Content-Type":void 0}}};ee.forEach(["delete","get","head","post","put","patch"],s=>{xo.headers[s]={}});const yC=ee.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"]),bC=s=>{const e={};let n,r,i;return s&&s.split(` +`).forEach(function(c){i=c.indexOf(":"),n=c.substring(0,i).trim().toLowerCase(),r=c.substring(i+1).trim(),!(!n||e[n]&&yC[n])&&(n==="set-cookie"?e[n]?e[n].push(r):e[n]=[r]:e[n]=e[n]?e[n]+", "+r:r)}),e},ym=Symbol("internals");function To(s){return s&&String(s).trim().toLowerCase()}function vc(s){return s===!1||s==null?s:ee.isArray(s)?s.map(vc):String(s)}function vC(s){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let r;for(;r=n.exec(s);)e[r[1]]=r[2];return e}const SC=s=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(s.trim());function lf(s,e,n,r,i){if(ee.isFunction(r))return r.call(this,e,n);if(i&&(e=n),!!ee.isString(e)){if(ee.isString(r))return e.indexOf(r)!==-1;if(ee.isRegExp(r))return r.test(e)}}function wC(s){return s.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,r)=>n.toUpperCase()+r)}function CC(s,e){const n=ee.toCamelCase(" "+e);["get","set","has"].forEach(r=>{Object.defineProperty(s,r+n,{value:function(i,l,c){return this[r].call(this,e,i,l,c)},configurable:!0})})}let $n=class{constructor(e){e&&this.set(e)}set(e,n,r){const i=this;function l(d,f,p){const m=To(f);if(!m)throw new Error("header name must be a non-empty string");const y=ee.findKey(i,m);(!y||i[y]===void 0||p===!0||p===void 0&&i[y]!==!1)&&(i[y||f]=vc(d))}const c=(d,f)=>ee.forEach(d,(p,m)=>l(p,m,f));if(ee.isPlainObject(e)||e instanceof this.constructor)c(e,n);else if(ee.isString(e)&&(e=e.trim())&&!SC(e))c(bC(e),n);else if(ee.isObject(e)&&ee.isIterable(e)){let d={},f,p;for(const m of e){if(!ee.isArray(m))throw TypeError("Object iterator must return a key-value pair");d[p=m[0]]=(f=d[p])?ee.isArray(f)?[...f,m[1]]:[f,m[1]]:m[1]}c(d,n)}else e!=null&&l(n,e,r);return this}get(e,n){if(e=To(e),e){const r=ee.findKey(this,e);if(r){const i=this[r];if(!n)return i;if(n===!0)return vC(i);if(ee.isFunction(n))return n.call(this,i,r);if(ee.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=To(e),e){const r=ee.findKey(this,e);return!!(r&&this[r]!==void 0&&(!n||lf(this,this[r],r,n)))}return!1}delete(e,n){const r=this;let i=!1;function l(c){if(c=To(c),c){const d=ee.findKey(r,c);d&&(!n||lf(r,r[d],d,n))&&(delete r[d],i=!0)}}return ee.isArray(e)?e.forEach(l):l(e),i}clear(e){const n=Object.keys(this);let r=n.length,i=!1;for(;r--;){const l=n[r];(!e||lf(this,this[l],l,e,!0))&&(delete this[l],i=!0)}return i}normalize(e){const n=this,r={};return ee.forEach(this,(i,l)=>{const c=ee.findKey(r,l);if(c){n[c]=vc(i),delete n[l];return}const d=e?wC(l):String(l).trim();d!==l&&delete n[l],n[d]=vc(i),r[d]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return ee.forEach(this,(r,i)=>{r!=null&&r!==!1&&(n[i]=e&&ee.isArray(r)?r.join(", "):r)}),n}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,n])=>e+": "+n).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,...n){const r=new this(e);return n.forEach(i=>r.set(i)),r}static accessor(e){const r=(this[ym]=this[ym]={accessors:{}}).accessors,i=this.prototype;function l(c){const d=To(c);r[d]||(CC(i,c),r[d]=!0)}return ee.isArray(e)?e.forEach(l):l(e),this}};$n.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),ee.reduceDescriptors($n.prototype,({value:s},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>s,set(r){this[n]=r}}}),ee.freezeMethods($n);function cf(s,e){const n=this||xo,r=e||n,i=$n.from(r.headers);let l=r.data;return ee.forEach(s,function(d){l=d.call(n,l,i.normalize(),e?e.status:void 0)}),i.normalize(),l}function bm(s){return!!(s&&s.__CANCEL__)}function ds(s,e,n){Ye.call(this,s??"canceled",Ye.ERR_CANCELED,e,n),this.name="CanceledError"}ee.inherits(ds,Ye,{__CANCEL__:!0});function vm(s,e,n){const r=n.config.validateStatus;!n.status||!r||r(n.status)?s(n):e(new Ye("Request failed with status code "+n.status,[Ye.ERR_BAD_REQUEST,Ye.ERR_BAD_RESPONSE][Math.floor(n.status/100)-4],n.config,n.request,n))}function EC(s){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(s);return e&&e[1]||""}function _C(s,e){s=s||10;const n=new Array(s),r=new Array(s);let i=0,l=0,c;return e=e!==void 0?e:1e3,function(f){const p=Date.now(),m=r[l];c||(c=p),n[i]=f,r[i]=p;let y=l,C=0;for(;y!==i;)C+=n[y++],y=y%s;if(i=(i+1)%s,i===l&&(l=(l+1)%s),p-c{n=m,i=null,l&&(clearTimeout(l),l=null),s(...p)};return[(...p)=>{const m=Date.now(),y=m-n;y>=r?c(p,m):(i=p,l||(l=setTimeout(()=>{l=null,c(i)},r-y)))},()=>i&&c(i)]}const Sc=(s,e,n=3)=>{let r=0;const i=_C(50,250);return AC(l=>{const c=l.loaded,d=l.lengthComputable?l.total:void 0,f=c-r,p=i(f),m=c<=d;r=c;const y={loaded:c,total:d,progress:d?c/d:void 0,bytes:f,rate:p||void 0,estimated:p&&d&&m?(d-c)/p:void 0,event:l,lengthComputable:d!=null,[e?"download":"upload"]:!0};s(y)},n)},Sm=(s,e)=>{const n=s!=null;return[r=>e[0]({lengthComputable:n,total:s,loaded:r}),e[1]]},wm=s=>(...e)=>ee.asap(()=>s(...e)),xC=Cn.hasStandardBrowserEnv?((s,e)=>n=>(n=new URL(n,Cn.origin),s.protocol===n.protocol&&s.host===n.host&&(e||s.port===n.port)))(new URL(Cn.origin),Cn.navigator&&/(msie|trident)/i.test(Cn.navigator.userAgent)):()=>!0,TC=Cn.hasStandardBrowserEnv?{write(s,e,n,r,i,l){const c=[s+"="+encodeURIComponent(e)];ee.isNumber(n)&&c.push("expires="+new Date(n).toGMTString()),ee.isString(r)&&c.push("path="+r),ee.isString(i)&&c.push("domain="+i),l===!0&&c.push("secure"),document.cookie=c.join("; ")},read(s){const e=document.cookie.match(new RegExp("(^|;\\s*)("+s+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(s){this.write(s,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function kC(s){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(s)}function RC(s,e){return e?s.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):s}function Cm(s,e,n){let r=!kC(e);return s&&(r||n==!1)?RC(s,e):e}const Em=s=>s instanceof $n?{...s}:s;function xi(s,e){e=e||{};const n={};function r(p,m,y,C){return ee.isPlainObject(p)&&ee.isPlainObject(m)?ee.merge.call({caseless:C},p,m):ee.isPlainObject(m)?ee.merge({},m):ee.isArray(m)?m.slice():m}function i(p,m,y,C){if(ee.isUndefined(m)){if(!ee.isUndefined(p))return r(void 0,p,y,C)}else return r(p,m,y,C)}function l(p,m){if(!ee.isUndefined(m))return r(void 0,m)}function c(p,m){if(ee.isUndefined(m)){if(!ee.isUndefined(p))return r(void 0,p)}else return r(void 0,m)}function d(p,m,y){if(y in e)return r(p,m);if(y in s)return r(void 0,p)}const f={url:l,method:l,data:l,baseURL:c,transformRequest:c,transformResponse:c,paramsSerializer:c,timeout:c,timeoutMessage:c,withCredentials:c,withXSRFToken:c,adapter:c,responseType:c,xsrfCookieName:c,xsrfHeaderName:c,onUploadProgress:c,onDownloadProgress:c,decompress:c,maxContentLength:c,maxBodyLength:c,beforeRedirect:c,transport:c,httpAgent:c,httpsAgent:c,cancelToken:c,socketPath:c,responseEncoding:c,validateStatus:d,headers:(p,m,y)=>i(Em(p),Em(m),y,!0)};return ee.forEach(Object.keys({...s,...e}),function(m){const y=f[m]||i,C=y(s[m],e[m],m);ee.isUndefined(C)&&y!==d||(n[m]=C)}),n}const _m=s=>{const e=xi({},s);let{data:n,withXSRFToken:r,xsrfHeaderName:i,xsrfCookieName:l,headers:c,auth:d}=e;if(e.headers=c=$n.from(c),e.url=hm(Cm(e.baseURL,e.url,e.allowAbsoluteUrls),s.params,s.paramsSerializer),d&&c.set("Authorization","Basic "+btoa((d.username||"")+":"+(d.password?unescape(encodeURIComponent(d.password)):""))),ee.isFormData(n)){if(Cn.hasStandardBrowserEnv||Cn.hasStandardBrowserWebWorkerEnv)c.setContentType(void 0);else if(ee.isFunction(n.getHeaders)){const f=n.getHeaders(),p=["content-type","content-length"];Object.entries(f).forEach(([m,y])=>{p.includes(m.toLowerCase())&&c.set(m,y)})}}if(Cn.hasStandardBrowserEnv&&(r&&ee.isFunction(r)&&(r=r(e)),r||r!==!1&&xC(e.url))){const f=i&&l&&TC.read(l);f&&c.set(i,f)}return e},DC=typeof XMLHttpRequest<"u"&&function(s){return new Promise(function(n,r){const i=_m(s);let l=i.data;const c=$n.from(i.headers).normalize();let{responseType:d,onUploadProgress:f,onDownloadProgress:p}=i,m,y,C,S,v;function x(){S&&S(),v&&v(),i.cancelToken&&i.cancelToken.unsubscribe(m),i.signal&&i.signal.removeEventListener("abort",m)}let w=new XMLHttpRequest;w.open(i.method.toUpperCase(),i.url,!0),w.timeout=i.timeout;function R(){if(!w)return;const O=$n.from("getAllResponseHeaders"in w&&w.getAllResponseHeaders()),F={data:!d||d==="text"||d==="json"?w.responseText:w.response,status:w.status,statusText:w.statusText,headers:O,config:s,request:w};vm(function(P){n(P),x()},function(P){r(P),x()},F),w=null}"onloadend"in w?w.onloadend=R:w.onreadystatechange=function(){!w||w.readyState!==4||w.status===0&&!(w.responseURL&&w.responseURL.indexOf("file:")===0)||setTimeout(R)},w.onabort=function(){w&&(r(new Ye("Request aborted",Ye.ECONNABORTED,s,w)),w=null)},w.onerror=function(j){const F=j&&j.message?j.message:"Network Error",G=new Ye(F,Ye.ERR_NETWORK,s,w);G.event=j||null,r(G),w=null},w.ontimeout=function(){let j=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const F=i.transitional||gm;i.timeoutErrorMessage&&(j=i.timeoutErrorMessage),r(new Ye(j,F.clarifyTimeoutError?Ye.ETIMEDOUT:Ye.ECONNABORTED,s,w)),w=null},l===void 0&&c.setContentType(null),"setRequestHeader"in w&&ee.forEach(c.toJSON(),function(j,F){w.setRequestHeader(F,j)}),ee.isUndefined(i.withCredentials)||(w.withCredentials=!!i.withCredentials),d&&d!=="json"&&(w.responseType=i.responseType),p&&([C,v]=Sc(p,!0),w.addEventListener("progress",C)),f&&w.upload&&([y,S]=Sc(f),w.upload.addEventListener("progress",y),w.upload.addEventListener("loadend",S)),(i.cancelToken||i.signal)&&(m=O=>{w&&(r(!O||O.type?new ds(null,s,w):O),w.abort(),w=null)},i.cancelToken&&i.cancelToken.subscribe(m),i.signal&&(i.signal.aborted?m():i.signal.addEventListener("abort",m)));const L=EC(i.url);if(L&&Cn.protocols.indexOf(L)===-1){r(new Ye("Unsupported protocol "+L+":",Ye.ERR_BAD_REQUEST,s));return}w.send(l||null)})},OC=(s,e)=>{const{length:n}=s=s?s.filter(Boolean):[];if(e||n){let r=new AbortController,i;const l=function(p){if(!i){i=!0,d();const m=p instanceof Error?p:this.reason;r.abort(m instanceof Ye?m:new ds(m instanceof Error?m.message:m))}};let c=e&&setTimeout(()=>{c=null,l(new Ye(`timeout ${e} of ms exceeded`,Ye.ETIMEDOUT))},e);const d=()=>{s&&(c&&clearTimeout(c),c=null,s.forEach(p=>{p.unsubscribe?p.unsubscribe(l):p.removeEventListener("abort",l)}),s=null)};s.forEach(p=>p.addEventListener("abort",l));const{signal:f}=r;return f.unsubscribe=()=>ee.asap(d),f}},LC=function*(s,e){let n=s.byteLength;if(n{const i=$C(s,e);let l=0,c,d=f=>{c||(c=!0,r&&r(f))};return new ReadableStream({async pull(f){try{const{done:p,value:m}=await i.next();if(p){d(),f.close();return}let y=m.byteLength;if(n){let C=l+=y;n(C)}f.enqueue(new Uint8Array(m))}catch(p){throw d(p),p}},cancel(f){return d(f),i.return()}},{highWaterMark:2})},xm=64*1024,{isFunction:wc}=ee,NC=(({Request:s,Response:e})=>({Request:s,Response:e}))(ee.global),{ReadableStream:Tm,TextEncoder:km}=ee.global,Rm=(s,...e)=>{try{return!!s(...e)}catch{return!1}},IC=s=>{s=ee.merge.call({skipUndefined:!0},NC,s);const{fetch:e,Request:n,Response:r}=s,i=e?wc(e):typeof fetch=="function",l=wc(n),c=wc(r);if(!i)return!1;const d=i&&wc(Tm),f=i&&(typeof km=="function"?(v=>x=>v.encode(x))(new km):async v=>new Uint8Array(await new n(v).arrayBuffer())),p=l&&d&&Rm(()=>{let v=!1;const x=new n(Cn.origin,{body:new Tm,method:"POST",get duplex(){return v=!0,"half"}}).headers.has("Content-Type");return v&&!x}),m=c&&d&&Rm(()=>ee.isReadableStream(new r("").body)),y={stream:m&&(v=>v.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(v=>{!y[v]&&(y[v]=(x,w)=>{let R=x&&x[v];if(R)return R.call(x);throw new Ye(`Response type '${v}' is not supported`,Ye.ERR_NOT_SUPPORT,w)})});const C=async v=>{if(v==null)return 0;if(ee.isBlob(v))return v.size;if(ee.isSpecCompliantForm(v))return(await new n(Cn.origin,{method:"POST",body:v}).arrayBuffer()).byteLength;if(ee.isArrayBufferView(v)||ee.isArrayBuffer(v))return v.byteLength;if(ee.isURLSearchParams(v)&&(v=v+""),ee.isString(v))return(await f(v)).byteLength},S=async(v,x)=>{const w=ee.toFiniteNumber(v.getContentLength());return w??C(x)};return async v=>{let{url:x,method:w,data:R,signal:L,cancelToken:O,timeout:j,onDownloadProgress:F,onUploadProgress:G,responseType:P,headers:K,withCredentials:he="same-origin",fetchOptions:Ee}=_m(v),ke=e||fetch;P=P?(P+"").toLowerCase():"text";let ze=OC([L,O&&O.toAbortSignal()],j),Be=null;const je=ze&&ze.unsubscribe&&(()=>{ze.unsubscribe()});let bt;try{if(G&&p&&w!=="get"&&w!=="head"&&(bt=await S(K,R))!==0){let z=new n(x,{method:"POST",body:R,duplex:"half"}),T;if(ee.isFormData(R)&&(T=z.headers.get("content-type"))&&K.setContentType(T),z.body){const[pe,fe]=Sm(bt,Sc(wm(G)));R=Am(z.body,xm,pe,fe)}}ee.isString(he)||(he=he?"include":"omit");const X=l&&"credentials"in n.prototype,de={...Ee,signal:ze,method:w.toUpperCase(),headers:K.normalize().toJSON(),body:R,duplex:"half",credentials:X?he:void 0};Be=l&&new n(x,de);let Ce=await(l?ke(Be,Ee):ke(x,de));const Z=m&&(P==="stream"||P==="response");if(m&&(F||Z&&je)){const z={};["status","statusText","headers"].forEach(me=>{z[me]=Ce[me]});const T=ee.toFiniteNumber(Ce.headers.get("content-length")),[pe,fe]=F&&Sm(T,Sc(wm(F),!0))||[];Ce=new r(Am(Ce.body,xm,pe,()=>{fe&&fe(),je&&je()}),z)}P=P||"text";let ge=await y[ee.findKey(y,P)||"text"](Ce,v);return!Z&&je&&je(),await new Promise((z,T)=>{vm(z,T,{data:ge,headers:$n.from(Ce.headers),status:Ce.status,statusText:Ce.statusText,config:v,request:Be})})}catch(X){throw je&&je(),X&&X.name==="TypeError"&&/Load failed|fetch/i.test(X.message)?Object.assign(new Ye("Network Error",Ye.ERR_NETWORK,v,Be),{cause:X.cause||X}):Ye.from(X,X&&X.code,v,Be)}}},jC=new Map,Dm=s=>{let e=s?s.env:{};const{fetch:n,Request:r,Response:i}=e,l=[r,i,n];let c=l.length,d=c,f,p,m=jC;for(;d--;)f=l[d],p=m.get(f),p===void 0&&m.set(f,p=d?new Map:IC(e)),m=p;return p};Dm();const uf={http:iC,xhr:DC,fetch:{get:Dm}};ee.forEach(uf,(s,e)=>{if(s){try{Object.defineProperty(s,"name",{value:e})}catch{}Object.defineProperty(s,"adapterName",{value:e})}});const Om=s=>`- ${s}`,zC=s=>ee.isFunction(s)||s===null||s===!1,Lm={getAdapter:(s,e)=>{s=ee.isArray(s)?s:[s];const{length:n}=s;let r,i;const l={};for(let c=0;c`adapter ${f} `+(p===!1?"is not supported by the environment":"is not available in the build"));let d=n?c.length>1?`since : +`+c.map(Om).join(` +`):" "+Om(c[0]):"as no adapter specified";throw new Ye("There is no suitable adapter to dispatch the request "+d,"ERR_NOT_SUPPORT")}return i},adapters:uf};function df(s){if(s.cancelToken&&s.cancelToken.throwIfRequested(),s.signal&&s.signal.aborted)throw new ds(null,s)}function $m(s){return df(s),s.headers=$n.from(s.headers),s.data=cf.call(s,s.transformRequest),["post","put","patch"].indexOf(s.method)!==-1&&s.headers.setContentType("application/x-www-form-urlencoded",!1),Lm.getAdapter(s.adapter||xo.adapter,s)(s).then(function(r){return df(s),r.data=cf.call(s,s.transformResponse,r),r.headers=$n.from(r.headers),r},function(r){return bm(r)||(df(s),r&&r.response&&(r.response.data=cf.call(s,s.transformResponse,r.response),r.response.headers=$n.from(r.response.headers))),Promise.reject(r)})}const Mm="1.12.2",Cc={};["object","boolean","number","function","string","symbol"].forEach((s,e)=>{Cc[s]=function(r){return typeof r===s||"a"+(e<1?"n ":" ")+s}});const Nm={};Cc.transitional=function(e,n,r){function i(l,c){return"[Axios v"+Mm+"] Transitional option '"+l+"'"+c+(r?". "+r:"")}return(l,c,d)=>{if(e===!1)throw new Ye(i(c," has been removed"+(n?" in "+n:"")),Ye.ERR_DEPRECATED);return n&&!Nm[c]&&(Nm[c]=!0,console.warn(i(c," has been deprecated since v"+n+" and will be removed in the near future"))),e?e(l,c,d):!0}},Cc.spelling=function(e){return(n,r)=>(console.warn(`${r} is likely a misspelling of ${e}`),!0)};function HC(s,e,n){if(typeof s!="object")throw new Ye("options must be an object",Ye.ERR_BAD_OPTION_VALUE);const r=Object.keys(s);let i=r.length;for(;i-- >0;){const l=r[i],c=e[l];if(c){const d=s[l],f=d===void 0||c(d,l,s);if(f!==!0)throw new Ye("option "+l+" must be "+f,Ye.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Ye("Unknown option "+l,Ye.ERR_BAD_OPTION)}}const Ec={assertOptions:HC,validators:Cc},qr=Ec.validators;let Ti=class{constructor(e){this.defaults=e||{},this.interceptors={request:new pm,response:new pm}}async request(e,n){try{return await this._request(e,n)}catch(r){if(r instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const l=i.stack?i.stack.replace(/^.+\n/,""):"";try{r.stack?l&&!String(r.stack).endsWith(l.replace(/^.+\n.+\n/,""))&&(r.stack+=` +`+l):r.stack=l}catch{}}throw r}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=xi(this.defaults,n);const{transitional:r,paramsSerializer:i,headers:l}=n;r!==void 0&&Ec.assertOptions(r,{silentJSONParsing:qr.transitional(qr.boolean),forcedJSONParsing:qr.transitional(qr.boolean),clarifyTimeoutError:qr.transitional(qr.boolean)},!1),i!=null&&(ee.isFunction(i)?n.paramsSerializer={serialize:i}:Ec.assertOptions(i,{encode:qr.function,serialize:qr.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Ec.assertOptions(n,{baseUrl:qr.spelling("baseURL"),withXsrfToken:qr.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let c=l&&ee.merge(l.common,l[n.method]);l&&ee.forEach(["delete","get","head","post","put","patch","common"],v=>{delete l[v]}),n.headers=$n.concat(c,l);const d=[];let f=!0;this.interceptors.request.forEach(function(x){typeof x.runWhen=="function"&&x.runWhen(n)===!1||(f=f&&x.synchronous,d.unshift(x.fulfilled,x.rejected))});const p=[];this.interceptors.response.forEach(function(x){p.push(x.fulfilled,x.rejected)});let m,y=0,C;if(!f){const v=[$m.bind(this),void 0];for(v.unshift(...d),v.push(...p),C=v.length,m=Promise.resolve(n);y{if(!r._listeners)return;let l=r._listeners.length;for(;l-- >0;)r._listeners[l](i);r._listeners=null}),this.promise.then=i=>{let l;const c=new Promise(d=>{r.subscribe(d),l=d}).then(i);return c.cancel=function(){r.unsubscribe(l)},c},e(function(l,c,d){r.reason||(r.reason=new ds(l,c,d),n(r.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 n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=r=>{e.abort(r)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new Dw(function(i){e=i}),cancel:e}}};function PC(s){return function(n){return s.apply(null,n)}}function BC(s){return ee.isObject(s)&&s.isAxiosError===!0}const ff={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(ff).forEach(([s,e])=>{ff[e]=s});function Im(s){const e=new Ti(s),n=Qg(Ti.prototype.request,e);return ee.extend(n,Ti.prototype,e,{allOwnKeys:!0}),ee.extend(n,e,null,{allOwnKeys:!0}),n.create=function(i){return Im(xi(s,i))},n}const Ft=Im(xo);Ft.Axios=Ti,Ft.CanceledError=ds,Ft.CancelToken=UC,Ft.isCancel=bm,Ft.VERSION=Mm,Ft.toFormData=bc,Ft.AxiosError=Ye,Ft.Cancel=Ft.CanceledError,Ft.all=function(e){return Promise.all(e)},Ft.spread=PC,Ft.isAxiosError=BC,Ft.mergeConfig=xi,Ft.AxiosHeaders=$n,Ft.formToJSON=s=>mm(ee.isHTMLForm(s)?new FormData(s):s),Ft.getAdapter=Lm.getAdapter,Ft.HttpStatusCode=ff,Ft.default=Ft;const{Axios:Ek,AxiosError:_k,CanceledError:Ak,isCancel:xk,CancelToken:Tk,VERSION:kk,all:Rk,Cancel:Dk,isAxiosError:Ok,spread:Lk,toFormData:$k,AxiosHeaders:Mk,HttpStatusCode:Nk,formToJSON:Ik,getAdapter:jk,mergeConfig:zk}=Ft,hf="g7.identity.redirectStash",_c=dt("IdentityGuardInterceptor");class yt{static setLauncher(e){this.launcher=e}static hasLauncher(){return this.launcher!==null}static markDomainNoticeShown(){this.domainNoticeShown=!0}static consumeDomainNoticeShown(){const e=this.domainNoticeShown;return this.domainNoticeShown=!1,e}static resolveDeferred(e){const n=this.deferredResolver;if(!n){_c.warn("IdentityGuardInterceptor.resolveDeferred 호출됐지만 대기 중인 launcher 가 없습니다. 모달이 launcher 외부에서 열렸는지 확인하세요.");return}this.deferredResolver=null,n(e)}static createDeferred(){if(this.deferredResolver){const e=this.deferredResolver;this.deferredResolver=null,e({status:"cancelled"})}return new Promise(e=>{this.deferredResolver=e})}static isIdentityRequired(e,n){return e===428&&typeof n=="object"&&n!==null&&n.error_code==="identity_verification_required"}static async handle(e,n,r){this.domainNoticeShown=!1;const i=this.launcher??GC,c=!!(r&&(r.email||r.phone))?{...e.verification,target:r}:e.verification,d=await i(c);if(d.status!=="verified")return null;const f=c.return_request;if(!f)return null;const p=qC(f.url,d.token);return fetch(p,{method:f.method,headers:n?.headers??{Accept:"application/json","Content-Type":"application/json"},body:n?.body,credentials:n?.credentials??"same-origin"})}static redirectExternally(e){const n=e.redirect_url;if(!n)return _c.error("redirectExternally 호출 시 verification.redirect_url 이 없습니다. payload:",e),Promise.resolve({status:"failed",failureCode:"MISSING_REDIRECT_URL",reason:"verification.redirect_url is required for external_redirect flow"});if(typeof window<"u"){const r={return_url:window.location.href,payload:e,stashed_at:Date.now()};try{window.sessionStorage?.setItem(hf,JSON.stringify(r))}catch(i){_c.warn("sessionStorage 접근 실패 — stash 없이 redirect 합니다.",i)}window.location.href=n}return new Promise(()=>{})}static reset(){if(this.deferredResolver){const e=this.deferredResolver;this.deferredResolver=null;try{e({status:"cancelled"})}catch{}}this.launcher=null,this.domainNoticeShown=!1}}$(yt,"launcher",null),$(yt,"deferredResolver",null),$(yt,"domainNoticeShown",!1);function qC(s,e){if(!e)return s;try{const n=typeof window<"u"?window.location.origin:"http://localhost",r=new URL(s,n);return r.searchParams.set("verification_token",e),/^https?:\/\//i.test(s)?r.toString():`${r.pathname}${r.search}${r.hash}`}catch{const n=s.includes("?")?"&":"?";return`${s}${n}verification_token=${encodeURIComponent(e)}`}}const GC=async s=>{if(typeof window>"u")return{status:"cancelled"};if(s.render_hint==="external_redirect"||s.redirect_url)return yt.redirectExternally(s);const e=window.G7Core;if(!e?.dispatch)return console.error("[IdentityGuardInterceptor] defaultLauncher: G7Core 가 초기화되지 않아 본인인증 흐름을 시작할 수 없습니다."),{status:"failed",failureCode:"G7_NOT_READY"};try{await e.dispatch({handler:"toast",params:{message:"본인 확인이 필요합니다.",variant:"warning"}})}catch{}const n=window.location.href,r={return_url:n,payload:s,stashed_at:Date.now()};try{window.sessionStorage?.setItem(hf,JSON.stringify(r))}catch{}const i=`/identity/challenge?return=${encodeURIComponent(n)}`;try{await e.dispatch({handler:"navigate",params:{path:i}})}catch(l){_c.warn("navigate 실패 — window.location 으로 폴백",l),window.location.href=i}return new Promise(()=>{})},jm=dt("ApiClient");function pf(){return typeof window<"u"&&window.__G7_DEVTOOLS__?window.__G7_DEVTOOLS__:null}class FC{constructor(e={}){$(this,"client");$(this,"config");$(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=Ft.create({baseURL:this.config.baseURL,timeout:this.config.timeout,headers:{"Content-Type":"application/json",Accept:"application/json"},paramsSerializer:{serialize:n=>{const r=[];for(const[i,l]of Object.entries(n))if(l!=null)if(Array.isArray(l)){const c=i.endsWith("[]")?i:`${i}[]`;for(const d of l)r.push(`${encodeURIComponent(c)}=${encodeURIComponent(String(d))}`)}else r.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(l))}`);return r.join("&")}}}),this.setupInterceptors()}setToken(e){if(typeof e!="string"||e===""){jm.warn("Ignoring invalid auth token — token must be a non-empty string.");return}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 n=this.getToken();if(n&&e.headers&&!this.isCrossOriginRequest(e.url)&&(e.headers.Authorization=`Bearer ${n}`),typeof window<"u"&&e.headers){const i=localStorage.getItem("g7_locale");i&&(e.headers["Accept-Language"]=i)}const r=pf();if(r?.isEnabled()){const i=this.buildFullUrl(e),l=(e.method||"GET").toUpperCase(),c=r.trackRequest(i,l,{requestBody:e.data});e._devToolsRequestId=c}return e},e=>Promise.reject(e)),this.client.interceptors.response.use(e=>{const n=e.config,r=n._devToolsRequestId;if(r){const i=pf();i?.isEnabled()&&i.completeRequest(r,e.status,e.data),n._devToolsRequestId=null}return e},async e=>{const n=e.config,r=n?.url||"",l=["/auth/","/layouts/"].some(c=>r.includes(c));if(e.response?.status===401&&!n?._retry&&!l){if(n._retry=!0,await Yn.getInstance().refreshToken()){const f=this.getToken();return f&&(n.headers.Authorization=`Bearer ${f}`),n._devToolsRequestId=null,this.client(n)}return this.completeDevToolsRequest(n,e),this.removeToken(),this.config.onUnauthorized&&this.config.onUnauthorized(),Promise.reject(e)}if(e.response?.status===401&&l)return this.completeDevToolsRequest(n,e),Promise.reject(e);if(yt.isIdentityRequired(e.response?.status,e.response?.data)){this.completeDevToolsRequest(n,e);const c={},d=n?.headers??{};for(const[C,S]of Object.entries(d))typeof S=="string"&&(c[C]=S);let f;n?.data!==void 0&&n?.data!==null&&(f=typeof n.data=="string"?n.data:JSON.stringify(n.data),c["Content-Type"]=c["Content-Type"]??"application/json");const p=n?.identity_target,m=await yt.handle(e.response.data,{headers:c,body:f,credentials:"same-origin"},p);if(!m)return Promise.reject(e);let y=null;try{y=await m.json()}catch{y=null}return m.ok?{...e.response,status:m.status,data:y}:Promise.reject(Object.assign(new Error("replay failed"),{response:{status:m.status,data:y}}))}return e.response?.status===403?(this.completeDevToolsRequest(n,e),this.callOnError(e),Promise.reject(e)):(this.completeDevToolsRequest(n,e),e.response&&this.callOnError(e),Promise.reject(e))})}async get(e,n){return(await this.client.get(e,n)).data}async post(e,n,r){return(await this.client.post(e,n,r)).data}async put(e,n,r){return(await this.client.put(e,n,r)).data}async patch(e,n,r){return(await this.client.patch(e,n,r)).data}async delete(e,n){return(await this.client.delete(e,n)).data}getInstance(){return this.client}setOnUnauthorized(e){this.config.onUnauthorized=e}setOnError(e){this.config.onError=e}completeDevToolsRequest(e,n){if(!e?._devToolsRequestId)return;const r=pf();if(!r?.isEnabled())return;const i=e._devToolsRequestId;e._devToolsRequestId=null,n.response?r.completeRequest(i,n.response.status,n.response.data):n.request?r.failRequest(i,n.message||"Network error"):r.failRequest(i,n.message||"Request error")}isCrossOriginRequest(e){if(!e||typeof window>"u"||!window.location||!/^(https?:)?\/\//i.test(e))return!1;try{return new URL(e,window.location.href).origin!==window.location.origin}catch{return!1}}buildFullUrl(e){let n=e.url||"";if(e.baseURL&&!n.startsWith("http")&&(n=`${e.baseURL}${n.startsWith("/")?"":"/"}${n}`),e.params&&typeof e.params=="object"){const r=e.params,i=[];for(const[l,c]of Object.entries(r))if(c!=null)if(Array.isArray(c)){const d=l.endsWith("[]")?l:`${l}[]`;for(const f of c)i.push(`${encodeURIComponent(d)}=${encodeURIComponent(String(f))}`)}else i.push(`${encodeURIComponent(l)}=${encodeURIComponent(String(c))}`);i.length>0&&(n+=(n.includes("?")?"&":"?")+i.join("&"))}return n}callOnError(e){if(!this.config.onError)return;const n={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(n)}catch(r){jm.error("Error in onError handler:",r)}}}let gf=null;function Wn(){return gf||(gf=new FC),gf}const ko=dt("AuthManager");function ki(s,e,n,r){try{window.G7Core?.devTools?.trackAuthEvent?.(s,e,n,r)}catch{}}const zm={admin:{type:"admin",loginPath:"/admin/login",defaultPath:"/admin",userEndpoint:"/admin/auth/user",loginEndpoint:"/auth/admin/login",logoutEndpoint:"/admin/auth/logout",refreshEndpoint:"/admin/auth/refresh",twoFactorEndpoint:"/auth/admin/login/two-factor",twoFactorResendEndpoint:"/auth/admin/login/two-factor/resend"},user:{type:"user",loginPath:"/login",defaultPath:"/",userEndpoint:"/auth/user",loginEndpoint:"/auth/login",logoutEndpoint:"/auth/logout",refreshEndpoint:"/auth/refresh",twoFactorEndpoint:"/auth/login/two-factor",twoFactorResendEndpoint:"/auth/login/two-factor/resend"}},Or=class Or{constructor(){$(this,"state");$(this,"config");$(this,"isRefreshing",!1);$(this,"refreshPromise",null);$(this,"eventHandlers",new Map);this.state={isAuthenticated:!1,user:null,type:null},this.config=new Map,this.config.set("admin",zm.admin),this.config.set("user",zm.user)}static getInstance(){return Or.instance||(Or.instance=new Or),Or.instance}on(e,n){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(n)}emit(e,...n){const r=this.eventHandlers.get(e);r&&r.forEach(i=>i(...n))}isAuthenticated(){return this.state.isAuthenticated}getUser(){return this.state.user}getAuthType(){return this.state.type}async checkAuth(e){const n=Wn();if(!n.getToken())return this.clearState(),!1;const i=this.config.get(e);if(!i)return ko.error(`Unknown auth type: ${e}`),!1;try{const l=await n.get(i.userEndpoint);return l.success&&l.data?(this.state={isAuthenticated:!0,user:l.data,type:e},this.emit("authStateChange",this.state),!0):(this.clearState(),!1)}catch(l){return l.response?.status===401&&await this.refreshToken()?this.checkAuth(e):(this.clearState(),!1)}}async preloadAuth(e){try{return await this.checkAuth(e)}catch(n){return ko.warn(`Preload auth failed for type ${e}:`,n),!1}}async login(e,n,r){const i=Wn(),l=this.config.get(e);if(!l)throw new Error(`Unknown auth type: ${e}`);try{const c=r?.headers?{headers:r.headers}:void 0,d=await i.post(l.loginEndpoint,n,c);if(d.success&&d.data){if(d.data.two_factor_required===!0)return ki("login",!0,void 0,{type:e,two_factor:!0}),{status:"two_factor_required",challenge:{challengeId:String(d.data.challenge_id??""),providerId:String(d.data.provider_id??""),expiresAt:d.data.expires_at??null}};if(d.data.token&&d.data.user)return{status:"authenticated",user:this.establishSession(e,d.data.token,d.data.user)}}throw new Error("Login failed")}catch(c){throw this.clearState(),this.enhanceAuthError(c,e,"Login failed")}}async completeTwoFactor(e,n,r){const i=Wn(),l=this.config.get(e);if(!l)throw new Error(`Unknown auth type: ${e}`);try{const c=r?.headers?{headers:r.headers}:void 0,d=await i.post(l.twoFactorEndpoint,{challenge_id:n.challengeId,code:n.code},c);if(d.success&&d.data?.token&&d.data?.user)return this.establishSession(e,d.data.token,d.data.user);throw new Error("Login failed")}catch(c){throw this.clearState(),this.enhanceAuthError(c,e,"Login failed")}}async resendTwoFactor(e,n,r){const i=Wn(),l=this.config.get(e);if(!l)throw new Error(`Unknown auth type: ${e}`);try{const c=r?.headers?{headers:r.headers}:void 0,d=await i.post(l.twoFactorResendEndpoint,{challenge_id:n.challengeId},c);if(d.success&&d.data?.challenge_id)return{challengeId:String(d.data.challenge_id),providerId:String(d.data.provider_id??""),expiresAt:d.data.expires_at??null};throw new Error("Resend failed")}catch(c){throw this.enhanceAuthError(c,e,"Resend failed")}}establishSession(e,n,r){Wn().setToken(n);const l=r.language,c=localStorage.getItem(Or.LOCALE_STORAGE_KEY),d=l&&l!==c;if(l)try{localStorage.setItem(Or.LOCALE_STORAGE_KEY,l)}catch(f){ko.warn("Failed to save user language to localStorage:",f)}return this.state={isAuthenticated:!0,user:r,type:e},this.emit("login",this.state),this.emit("authStateChange",this.state),ki("login",!0,void 0,{userId:r.uuid,email:r.email,type:e}),d&&window.__templateApp&&window.__templateApp.changeLocale(l),r}enhanceAuthError(e,n,r){const i=e?.response?.data?.message,l=new Error(i||e?.message||r);return l.response=e?.response,l.status=e?.response?.status,l.code=e?.code,ki("login",!1,l.message,{type:n,status:e?.response?.status}),l}async logout(){const e=Wn(),n=this.state.type?this.config.get(this.state.type):null;try{n&&await e.post(n.logoutEndpoint)}catch(r){ko.warn("Logout API call failed:",r)}finally{e.removeToken();const r={...this.state};if(this.clearState(),this.emit("logout",r),this.emit("authStateChange",this.state),ki("logout",!0,void 0,{previousType:r.type}),n&&r.type){const i=window.location.pathname+window.location.search;window.location.href=this.getLoginRedirectUrl(r.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 n=this.config.get(e);if(!n)return!1;const r=Wn();try{const i=await r.post(n.refreshEndpoint);return i.success&&i.data?.token?(r.setToken(i.data.token),this.emit("tokenRefreshed"),ki("token-refresh",!0,void 0,{type:e}),!0):(ki("token-refresh",!1,"No token in response",{type:e}),!1)}catch(i){return ko.error("Token refresh failed:",i),ki("token-refresh",!1,i instanceof Error?i.message:"Unknown error",{type:e}),!1}}getLoginRedirectUrl(e,n,r){const i=this.config.get(e);if(!i)return"/login";const l=encodeURIComponent(n);let c=`${i.loginPath}?redirect=${l}`;return r&&(c+=`&reason=${encodeURIComponent(r)}`),c}updateConfig(e,n){if(n.loginPath!==void 0){const i=n.loginPath;if(!i.startsWith("/")||i.startsWith("//"))throw new Error(`AuthManager.updateConfig: loginPath must be a same-origin path starting with '/' (got: ${i})`)}const r=this.config.get(e);r&&this.config.set(e,{...r,...n})}getRedirectUrl(e){const r=this.config.get(e)?.defaultPath||"/",l=new URLSearchParams(window.location.search).get("redirect");if(l)try{const c=decodeURIComponent(l);if(c.startsWith("/"))return c}catch{}return r}getConfig(e){return this.config.get(e)}clearState(){this.state={isAuthenticated:!1,user:null,type:null}}static resetInstance(){Or.instance=null}};$(Or,"instance"),$(Or,"LOCALE_STORAGE_KEY","g7_locale");let Yn=Or;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}}"}}},oa={findHandler(s,e){if(s){if(s[e])return s[e];if(s[String(e)])return s[String(e)];if(s.default)return s.default}},normalizeOnError(s){return s?Array.isArray(s)?s:[s]:[]},injectErrorCode(s,e,n){if(s.handler!=="showErrorPage"||s.params?.errorCode!==void 0)return s;const r=typeof e=="string"?parseInt(e,10):e,i=isNaN(r)?n:r;return i===void 0?s:{...s,params:{...s.params,errorCode:i}}}},xr=dt("ErrorHandlingResolver"),Ba=class Ba{constructor(){$(this,"templateErrorHandling",null);$(this,"layoutErrorHandling",null);$(this,"executeAction",null)}static getInstance(){return Ba.instance||(Ba.instance=new Ba),Ba.instance}static resetInstance(){Ba.instance=null}setTemplateConfig(e){this.templateErrorHandling=e,xr.log("Template config set:",e)}setLayoutConfig(e){this.layoutErrorHandling=e,xr.log("Layout config set:",e)}setActionExecutor(e){this.executeAction=e}resolve(e,n={}){const{errorHandling:r,onError:i}=n;xr.log("Resolving error:",e,{hasActionErrorHandling:!!r,hasActionOnError:!!i,hasLayoutConfig:!!this.layoutErrorHandling,hasTemplateConfig:!!this.templateErrorHandling});let l=oa.findHandler(r,e);if(l){const c=this.getMatchedKey(r,e);return{handler:oa.injectErrorCode(l,c,e),level:"action",matchedKey:c}}if(i){const c=oa.normalizeOnError(i);if(c.length>0)return{handler:c.length===1?c[0]:{handler:"sequence",actions:c},level:"action",matchedKey:"onError"}}if(l=oa.findHandler(this.layoutErrorHandling||void 0,e),l){const c=this.getMatchedKey(this.layoutErrorHandling,e);return{handler:oa.injectErrorCode(l,c,e),level:"layout",matchedKey:c}}if(l=oa.findHandler(this.templateErrorHandling||void 0,e),l){const c=this.getMatchedKey(this.templateErrorHandling,e);return{handler:oa.injectErrorCode(l,c,e),level:"template",matchedKey:c}}if(l=oa.findHandler(Hm,e),l){const c=this.getMatchedKey(Hm,e);return{handler:oa.injectErrorCode(l,c,e),level:"system",matchedKey:c}}return{handler:null,level:null,matchedKey:null}}async execute(e,n){if(!this.executeAction){xr.error("Action executor is not set");return}xr.log("Executing handler:",e.handler,{errorContext:n});try{return await this.executeAction(e,{error:n})}catch(r){throw xr.error("Failed to execute handler:",r),r}}async resolveAndExecute(e,n,r={}){const i=this.resolve(e,r);if(xr.log("Resolve result:",{errorCode:e,handler:i.handler?.handler,level:i.level,matchedKey:i.matchedKey}),!i.handler)return xr.warn("No handler found for error:",e),{handled:!1};try{return{handled:!0,result:await this.execute(i.handler,n)}}catch(l){return xr.error("Handler execution failed:",l),{handled:!1}}}getMatchedKey(e,n){return e[n]?n:e[String(n)]?String(n):"default"}clearLayoutConfig(){this.layoutErrorHandling=null,xr.log("Layout config cleared")}clearAllConfig(){this.templateErrorHandling=null,this.layoutErrorHandling=null,xr.log("All config cleared")}getConfigStatus(){return{hasTemplate:this.templateErrorHandling!==null,hasLayout:this.layoutErrorHandling!==null,hasExecutor:this.executeAction!==null}}};$(Ba,"instance",null);let mf=Ba;function Tr(){return mf.getInstance()}function Ro(s,e){const n={...s};for(const r of Object.keys(e))r in n?n[r]!==null&&typeof n[r]=="object"&&!Array.isArray(n[r])&&e[r]!==null&&typeof e[r]=="object"&&!Array.isArray(e[r])&&(n[r]=Ro(n[r],e[r])):n[r]=e[r];return n}var yf={exports:{}},Do={};/** + * @license React + * react-jsx-runtime.production.js + * + * Copyright (c) Meta Platforms, Inc. and affiliates. + * + * This source code is licensed under the MIT license found in the + * LICENSE file in the root directory of this source tree. + */var Um;function VC(){if(Um)return Do;Um=1;var s=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(r,i,l){var c=null;if(l!==void 0&&(c=""+l),i.key!==void 0&&(c=""+i.key),"key"in i){l={};for(var d in i)d!=="key"&&(l[d]=i[d])}else l=i;return i=l.ref,{$$typeof:s,type:r,key:c,ref:i!==void 0?i:null,props:l}}return Do.Fragment=e,Do.jsx=n,Do.jsxs=n,Do}var Pm;function KC(){return Pm||(Pm=1,yf.exports=VC()),yf.exports}var ft=KC();const WC=ra({__proto__:null,default:aa(ft)},[ft]),bf=dt("ParentContextProvider"),Bm=M.createContext(null);let Ac=null;function vf(){Ac?(bf.log("[triggerModalParentUpdate] 모달 부모 컨텍스트 업데이트 트리거"),Ac()):bf.warn("[triggerModalParentUpdate] Provider가 아직 마운트되지 않음")}const qm=({children:s})=>{const[e,n]=M.useState(0),r=M.useRef(!0),i=M.useCallback(()=>{const c=window.__g7LayoutContextStack||[];return c[c.length-1]?.dataContext},[]);M.useEffect(()=>(r.current=!0,Ac=()=>{r.current&&(n(c=>c+1),bf.log("[ParentContextProvider] 버전 업데이트됨"))},()=>{r.current=!1,Ac=null}),[]);const l={version:e,getParentDataContext:i};return ft.jsx(Bm.Provider,{value:l,children:s})};function YC(){return M.useContext(Bm)}function Gm(s){return s.replace(/[\t\n\r]/g,"").replace(/\\/g,"/").replace(/^([a-z][a-z0-9+.\-]*:)?\/{2,}/i,"$1//")}function Fm(s,e){try{const n=typeof window<"u"&&window.location?.protocol||"https:",r=e||(typeof window<"u"?window.location?.origin:void 0)||"https://localhost",i=s.startsWith("//")?`${n}${s}`:s,l=new URL(i,r);return l.protocol!=="http:"&&l.protocol!=="https:"?null:l.hostname.toLowerCase()}catch{return null}}function fs(){const s=typeof window<"u"?window.G7Config?.trustedScriptHosts:void 0;return Array.isArray(s)?s.map(e=>String(e).toLowerCase()):[]}function Oo(s,e){if(typeof s!="string")return!1;const n=s.trim();if(n==="")return!1;const r=Gm(n),i=r.startsWith("//"),l=/^[a-z][a-z0-9+.-]*:/i.test(r);if(!i&&!l&&r.startsWith("/"))return!0;const c=Fm(r),d=e??fs();return c!==null&&d.map(f=>String(f).toLowerCase()).includes(c)}const N=dt("ActionDispatcher");function XC(s,e,n,r){return n||(Rg(s)||Md(s)?"$t:core.errors.network_request_failed":r||`Failed to execute action: ${e}`)}const Vm=new Set(["navigate","navigateBack","navigateForward","replaceUrl","refresh","logout"]),JC=new Set(["redirect"]);function Xn(){try{return window.G7Core?.devTools}catch{return}}class Tt extends Error{constructor(n,r,i){super(n);$(this,"unknownHandler",!1);this.action=r,this.originalError=i,this.name="ActionError"}}const Km={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"},rn=class rn{constructor(e={},n,r){$(this,"bindingEngine");$(this,"translationEngine");$(this,"translationContext");$(this,"customHandlers",new Map);$(this,"defaultContext");$(this,"globalStateUpdater");$(this,"errorHandlingSetup",!1);$(this,"debounceTimers",new Map);$(this,"pendingDebounceFlushers",new Map);$(this,"debounceAccumulatedValues",new Map);$(this,"globalHeaders",[]);$(this,"namedActions",{});$(this,"previewMode",!1);$(this,"localMirrorDepth",0);$(this,"intervals",new Map);this.bindingEngine=new Tn,this.translationEngine=n,this.translationContext=r,this.defaultContext=e,this.registerDefaultHandlers(),this.setupErrorHandling()}setGlobalHeaders(e){this.globalHeaders=e||[]}setNamedActions(e){this.namedActions=e||{};const n=Xn();n?.isEnabled?.()&&n.setNamedActionDefinitions?.(this.namedActions),N.log("[setNamedActions] registered:",Object.keys(this.namedActions))}getNamedActions(){return this.namedActions}setPreviewMode(e){this.previewMode=e,N.log("Preview mode:",e?"enabled":"disabled")}isPreviewMode(){return this.previewMode}static getPreviewSuppressedHandlers(){return Vm}static getPreviewSuppressedLayoutFeatures(){return JC}resolveActionRef(e){if(!e.actionRef)return e;const n=this.namedActions[e.actionRef];if(!n)return N.warn(`[resolveActionRef] named action not found: "${e.actionRef}"`),e;const r=Xn();r?.isEnabled?.()&&r.trackNamedActionRef?.({actionRefName:e.actionRef,resolvedHandler:n.handler,timestamp:Date.now()});const{actionRef:i,type:l,key:c,event:d,...f}=e,p={...n,...Object.fromEntries(Object.entries(f).filter(([,m])=>m!==void 0)),type:l??n.type};return c!==void 0&&(p.key=c),d!==void 0&&(p.event=d),p}matchesPattern(e,n){if(n==="*")return!0;const r=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(e)}getMatchingGlobalHeaders(e,n){const r={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,c])=>{const d=ls(c,n,{skipCache:!0});d!=null&&d!==""&&(r[l]=String(d))});return r}setupErrorHandling(){if(this.errorHandlingSetup)return;Tr().setActionExecutor(async(n,r)=>{const i={type:"click",handler:n.handler,target:n.target,params:n.params,actions:n.actions},l={data:{...this.defaultContext.data,error:r.error}};return await this.dispatchAction(i,l)}),this.errorHandlingSetup=!0}registerDefaultHandlers(){this.registerHandler("refetchDataSource",async(n,r)=>{const i=n.params?.dataSourceId,l=n.params?.sync;if(!i){N.warn("refetchDataSource: dataSourceId is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.refetch){const c=window.G7Core?.state?.get?.()||{},d={...r.state?._global,...c},f=window.G7Core?.state?.getLocal?.()||{},p=r.data?._local||r.state||{},m={...f,...p},y=r.isolatedContext?.state;N.log("[refetchDataSource] localStateOverride:",m),await window.G7Core.dataSource.refetch(i,{...l?{sync:!0}:{},...d?{globalStateOverride:d}:{},...m?{localStateOverride:m}:{},...y?{isolatedStateOverride:y}:{}})}else N.warn("refetchDataSource: G7Core.dataSource.refetch is not available")}),this.registerHandler("appendDataSource",async(n,r)=>{const{dataSourceId:i,dataPath:l,newData:c}=n.params||{};if(!i){N.warn("appendDataSource: dataSourceId is required");return}if(c===void 0){N.warn("appendDataSource: newData is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.updateData){if(!Array.isArray(c)){N.warn("appendDataSource: newData must be an array, got:",typeof c,c);return}await window.G7Core.dataSource.updateData(i,l||null,c,"append")}else N.warn("appendDataSource: G7Core.dataSource.updateData is not available")}),this.registerHandler("updateDataSource",async(n,r)=>{const{dataSourceId:i,data:l,merge:c=!1}=n.params||{};if(!i){N.warn("updateDataSource: dataSourceId is required");return}if(l===void 0){N.warn("updateDataSource: data is required");return}typeof window<"u"&&window.G7Core?.dataSource?.set?(N.log(`[updateDataSource] Updating dataSource '${i}' with:`,l),window.G7Core.dataSource.set(i,l,{merge:c})):N.warn("updateDataSource: G7Core.dataSource.set is not available")}),this.registerHandler("scrollIntoView",async(n,r)=>{const{selector:i,behavior:l="smooth",block:c="nearest",inline:d="nearest",waitForElement:f=!1,timeout:p=2e3,delay:m=0,retryCount:y=0,retryInterval:C=50,scrollContainer:S}=n.params||{};if(!i){N.warn("scrollIntoView: selector is required");return}if(typeof window>"u"||typeof document>"u"){N.warn("scrollIntoView: window/document is not available");return}let v=null;if(f){if(v=await new Promise(x=>{const w=document.querySelector(i);if(w){x(w);return}const R=setTimeout(()=>{L.disconnect(),x(null)},p),L=new MutationObserver(()=>{const O=document.querySelector(i);O&&(clearTimeout(R),L.disconnect(),x(O))});L.observe(document.body,{childList:!0,subtree:!0})}),!v){N.warn(`scrollIntoView: element not found for selector "${i}" after ${p}ms timeout`);return}}else{m>0&&await new Promise(w=>setTimeout(w,m)),v=document.querySelector(i);let x=0;for(;!v&&xsetTimeout(w,C)),v=document.querySelector(i),x++;if(!v){N.warn(`scrollIntoView: element not found for selector "${i}" after ${x+1} attempts`);return}}if(S){const x=document.querySelector(S);if(!x){N.warn(`scrollIntoView: container not found for selector "${S}"`);return}const w=v.getBoundingClientRect(),R=x.getBoundingClientRect(),L=w.top-R.top+x.scrollTop,O=L+w.height;let j;switch(c){case"start":j=L;break;case"center":j=L-x.clientHeight/2+w.height/2;break;case"end":j=O-x.clientHeight;break;case"nearest":default:const F=w.topR.bottom;if(F)j=L;else if(G)j=O-x.clientHeight;else return;break}x.scrollTo({top:Math.max(0,j),behavior:l});return}v.scrollIntoView({behavior:l,block:c,inline:d})}),this.registerHandler("reloadExtensions",async(n,r)=>{if(typeof window>"u"){N.warn("reloadExtensions: window is not available");return}const i=window.__templateApp;if(!i){N.warn("reloadExtensions: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState()}catch(d){throw N.error("reloadExtensions: reloadExtensionState failed",d),d}else N.warn("reloadExtensions: TemplateApp.reloadExtensionState unavailable");const{moduleInfo:l,pluginInfo:c}=n.params||{};if(l)try{await this.executeAction({handler:"reloadModuleHandlers",params:n.params},r)}catch(d){N.error("reloadExtensions: reloadModuleHandlers failed",d)}if(c)try{await this.executeAction({handler:"reloadPluginHandlers",params:n.params},r)}catch(d){N.error("reloadExtensions: reloadPluginHandlers failed",d)}N.log("reloadExtensions: done")}),this.registerHandler("reloadRoutes",async(n,r)=>{if(typeof window>"u"){N.warn("reloadRoutes: window is not available");return}const i=window.__templateApp;if(!i){N.warn("reloadRoutes: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),N.log("reloadRoutes: delegated to reloadExtensionState")}catch(l){throw N.error("reloadRoutes: Failed to reload routes",l),l}else{const l=i.getRouter?.();l&&(await l.loadRoutes(),N.log("reloadRoutes: Routes reloaded (legacy fallback)"))}}),this.registerHandler("refresh",async(n,r)=>{if(typeof window>"u"){N.warn("refresh: window is not available");return}const i=Number(n.params?.delayMs??0);i>0&&await new Promise(l=>setTimeout(l,i)),window.location.reload()}),this.registerHandler("remount",async(n,r)=>{const{componentId:i}=n.params||{};if(!i){N.warn("remount: componentId parameter is required");return}if(!this.globalStateUpdater){N.warn("remount: globalStateUpdater is not set");return}const d=(window.G7Core?.state?.get()||{})._global?._remountKeys||{},f=d[i]||0;this.globalStateUpdater({_remountKeys:{...d,[i]:f+1}}),N.log(`remount: ${i} key incremented to ${f+1}`)}),this.registerHandler("reloadTranslations",async(n,r)=>{if(typeof window>"u"){N.warn("reloadTranslations: window is not available");return}const i=window.__templateApp;if(!i){N.warn("reloadTranslations: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),N.log("reloadTranslations: delegated to reloadExtensionState")}catch(l){throw N.error("reloadTranslations: Failed to reload translations",l),l}}),this.registerHandler("reloadModuleHandlers",async(n,r)=>{if(typeof window>"u"){N.warn("reloadModuleHandlers: window is not available");return}const{moduleInfo:i,action:l}=n.params||{};if(!i){N.warn("reloadModuleHandlers: moduleInfo is required");return}const c=i.data||i;if(!c.identifier){N.warn("reloadModuleHandlers: moduleInfo with identifier is required");return}if(!l||l!=="add"&&l!=="remove"){N.warn('reloadModuleHandlers: action must be "add" or "remove"');return}const d=window.G7Config;if(!d){N.warn("reloadModuleHandlers: G7Config not available");return}const f=c.identifier;try{if(l==="add"){if(c.assets){if(d.moduleAssets=d.moduleAssets||{},d.moduleAssets[f]=c.assets,N.log(`reloadModuleHandlers: Added assets for ${f}`),c.assets.js){const p=c.assets.js,m=`module-${f}`;this.assertAllowedExtensionAssetUrl(p,`module script (${f})`,n),document.getElementById(m)?N.warn(`reloadModuleHandlers: Script ${m} already loaded`):(await Cr(p,{id:m},{label:`module-script:${f}`}),N.log(`reloadModuleHandlers: Script loaded successfully for ${f}`))}if(c.assets.css){const p=c.assets.css,m=`module-css-${f}`;this.assertAllowedExtensionAssetUrl(p,`module stylesheet (${f})`,n),document.getElementById(m)||(await sa(p,{id:m},{label:`module-css:${f}`}),N.log(`reloadModuleHandlers: CSS loaded for ${f}`))}}}else if(l==="remove"){d.moduleAssets&&d.moduleAssets[f]&&(delete d.moduleAssets[f],N.log(`reloadModuleHandlers: Removed assets for ${f}`));const p=`module-${f}`,m=document.getElementById(p);m&&(m.remove(),N.log(`reloadModuleHandlers: Removed script for ${f}`));const y=`module-css-${f}`,C=document.getElementById(y);C&&(C.remove(),N.log(`reloadModuleHandlers: Removed CSS for ${f}`))}}catch(p){throw N.error(`reloadModuleHandlers: Failed to ${l} module assets`,p),p}}),this.registerHandler("reloadPluginHandlers",async(n,r)=>{if(typeof window>"u"){N.warn("reloadPluginHandlers: window is not available");return}const{pluginInfo:i,action:l}=n.params||{};if(!i){N.warn("reloadPluginHandlers: pluginInfo is required");return}const c=i.data||i;if(!c.identifier){N.warn("reloadPluginHandlers: pluginInfo with identifier is required");return}if(!l||l!=="add"&&l!=="remove"){N.warn('reloadPluginHandlers: action must be "add" or "remove"');return}const d=window.G7Config;if(!d){N.warn("reloadPluginHandlers: G7Config not available");return}const f=c.identifier;try{if(l==="add"){if(c.assets){if(d.pluginAssets=d.pluginAssets||{},d.pluginAssets[f]=c.assets,N.log(`reloadPluginHandlers: Added assets for ${f}`),c.assets.js){const p=c.assets.js,m=`plugin-${f}`;this.assertAllowedExtensionAssetUrl(p,`plugin script (${f})`,n),document.getElementById(m)?N.warn(`reloadPluginHandlers: Script ${m} already loaded`):(await Cr(p,{id:m},{label:`plugin-script:${f}`}),N.log(`reloadPluginHandlers: Script loaded successfully for ${f}`))}if(c.assets.css){const p=c.assets.css,m=`plugin-css-${f}`;this.assertAllowedExtensionAssetUrl(p,`plugin stylesheet (${f})`,n),document.getElementById(m)||(await sa(p,{id:m},{label:`plugin-css:${f}`}),N.log(`reloadPluginHandlers: CSS loaded for ${f}`))}}}else if(l==="remove"){d.pluginAssets&&d.pluginAssets[f]&&(delete d.pluginAssets[f],N.log(`reloadPluginHandlers: Removed assets for ${f}`));const p=`plugin-${f}`,m=document.getElementById(p);m&&(m.remove(),N.log(`reloadPluginHandlers: Removed script for ${f}`));const y=`plugin-css-${f}`,C=document.getElementById(y);C&&(C.remove(),N.log(`reloadPluginHandlers: Removed CSS for ${f}`))}}catch(p){throw N.error(`reloadPluginHandlers: Failed to ${l} plugin assets`,p),p}});let e=!1;this.registerHandler("showErrorPage",async(n,r)=>{if(e){N.log("showErrorPage: Already active, skipping duplicate call");return}if(e=!0,typeof window>"u"){e=!1,N.warn("showErrorPage: window is not available");return}const i=window.__templateApp;if(!i){e=!1,N.warn("showErrorPage: TemplateApp not initialized");return}const l=i.getErrorPageHandler?.();if(!l){e=!1,N.warn("showErrorPage: ErrorPageHandler not available");return}const c=n.params?.errorCode||500,d=n.params?.target||"content";let f=n.params?.containerId;f||(f=d==="full"?"app":"main_content"),N.log("showErrorPage:",{errorCode:c,target:d,containerId:f});const p=(m,y=6e4)=>new Promise((C,S)=>{const v=document.getElementById(m);if(v){C(v);return}N.log(`showErrorPage: Waiting for container #${m}...`);let x;const w=new MutationObserver((R,L)=>{const O=document.getElementById(m);O&&(N.log(`showErrorPage: Container #${m} found`),L.disconnect(),clearTimeout(x),C(O))});w.observe(document.body,{childList:!0,subtree:!0}),x=setTimeout(()=>{w.disconnect(),S(new Error(`Container #${m} not found within ${y}ms`))},y)});try{await p(f);const m=Tr(),y=m.layoutErrorHandling;m.clearLayoutConfig();try{await l.renderError(c,f)||N.warn(`showErrorPage: Failed to render error page for code ${c}`)}finally{m.setLayoutConfig(y)}}catch(m){throw N.error("showErrorPage: Error rendering error page:",m),m}finally{e=!1}}),this.registerHandler("emitEvent",async(n,r)=>{const i=n.params?.event,l=n.params?.data;if(!i){N.warn("emitEvent: event parameter is required");return}if(typeof window>"u"){N.warn("emitEvent: window is not available");return}const c=window.G7Core;if(!c?.componentEvent?.emit){N.warn("emitEvent: G7Core.componentEvent is not available");return}try{N.log(`emitEvent: Emitting "${i}"`,l);const d={...l,_context:{data:r.data,state:r.state}},f=await c.componentEvent.emit(i,d);if(!f||f.length===0?N.warn(`emitEvent: No listeners found for "${i}"`):N.log(`emitEvent: Event "${i}" completed with ${f.length} listener(s)`,f),this.globalStateUpdater){const p=(c?.state?.get()||{})._local||{},m={event:i,success:!0,data:f.length===1?f[0]:f,listeners:f.length};this.globalStateUpdater({_local:{...p,_eventResult:m}});const y=r.state&&typeof r.state=="object"&&!Array.isArray(r.state)?r.state:p;window.__g7SequenceLocalSync={...y,_eventResult:m}}}catch(d){if(N.error(`emitEvent: Event "${i}" failed`,d),this.globalStateUpdater){const f=c?.state?.get()||{};this.globalStateUpdater({_local:{...f._local,_eventResult:{event:i,success:!1,error:d instanceof Error?d.message:String(d)}}})}throw d}}),this.registerHandler("updateProductField",async(n,r)=>{const{productId:i,field:l,value:c}=n.params||{};if(!i||!l){N.warn("updateProductField: productId and field are required");return}if(typeof window>"u"){N.warn("updateProductField: window is not available");return}const d=window.G7Core;if(!d?.state?.get||!this.globalStateUpdater){N.warn("updateProductField: G7Core.state or globalStateUpdater is not available");return}try{const f=d.state.get()||{},m=(f.products?.data?.data||[]).map(C=>C.id===i?{...C,[l]:c,_modified:!0}:C),y=new Set(f._local?.modifiedProductIds||[]);y.add(i),this.globalStateUpdater({products:{...f.products,data:{...f.products?.data,data:m}},_local:{...f._local,modifiedProductIds:Array.from(y)}}),N.log(`updateProductField: Updated product ${i}, field: ${l}, value:`,c)}catch(f){throw N.error("updateProductField: Error updating product field",f),f}}),this.registerHandler("updateOptionField",async(n,r)=>{const{productId:i,optionId:l,field:c,value:d}=n.params||{};if(!i||!l||!c){N.warn("updateOptionField: productId, optionId and field are required");return}if(typeof window>"u"){N.warn("updateOptionField: window is not available");return}const f=window.G7Core;if(!f?.state?.get||!this.globalStateUpdater){N.warn("updateOptionField: G7Core.state or globalStateUpdater is not available");return}try{const p=f.state.get()||{},y=(p.products?.data?.data||[]).map(S=>{if(S.id===i&&S.options){const v=S.options.map(x=>x.id===l?{...x,[c]:d,_modified:!0}:x);return{...S,options:v,_modified:!0}}return S}),C=new Set(p._local?.modifiedProductIds||[]);C.add(i),this.globalStateUpdater({products:{...p.products,data:{...p.products?.data,data:y}},_local:{...p._local,modifiedProductIds:Array.from(C)}}),N.log(`updateOptionField: Updated product ${i} option ${l}, field: ${c}, value:`,d)}catch(p){throw N.error("updateOptionField: Error updating option field",p),p}}),this.registerHandler("setLocale",async(n,r)=>{const i=n.target;if(!i||typeof i!="string"){N.warn("setLocale: Invalid locale:",i);return}const l=window.__templateApp;if(l&&typeof l.changeLocale=="function")try{await l.changeLocale(i),N.log("setLocale: Locale changed to",i)}catch(c){N.error("setLocale: Failed to change locale:",c),window.location.reload()}else{N.warn("setLocale: TemplateApp not found, falling back to page reload");try{localStorage.setItem("g7_locale",i)}catch{}window.location.reload()}}),this.registerHandler("suppress",async()=>{N.log("suppress: Error intentionally suppressed")}),this.registerBuiltInHandlerMetadata()}registerBuiltInHandlerMetadata(){const e=Xn();if(!e?.isEnabled())return;const n=[{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 r of n)e.trackHandlerRegistration(r.name,"built-in",r.description)}createHandler(e,n,r){N.log("createHandler called for:",e.handler,e.type);const i=window.__g7DevTools,l=Date.now(),c=r?.state?{...r.state}:null,d=`handler_${e.handler}_${l}`;return async f=>{if(N.log("Handler invoked for:",e.handler,"event:",f.type),i?.isEnabled?.()&&c){const m=window.G7Core?.state?.getLocal?.()??r?.state??{},y=Date.now()-l;for(const C of Object.keys(c)){const S=c[C],v=m[C];S!==v&&y>100&&(i.trackStaleClosureWarning?.({type:"event-handler-stale",location:`createHandler(${e.handler})`,capturedPath:`_local.${C}`,capturedValue:S,capturedAt:l,currentValue:v,actionId:d,stackTrace:new Error().stack}),N.warn(`[Stale Closure] _local.${C} changed after handler creation:`,`captured="${S}" → current="${v}" (${y}ms ago)`))}}try{f.type!=="change"&&f.preventDefault();let p={};if(f.type==="submit"&&f.target instanceof HTMLFormElement){const C=f.target;new FormData(C).forEach((v,x)=>{p[x]=v})}const m={...this.defaultContext,data:{...n,form:p,_local:r?.state||{},$event:f},event:f,...r&&{state:r.state,setState:r.setState},isolatedContext:r?.isolatedContext};if(e.confirm){let C=this.resolveValue(e.confirm,m.data);if(this.translationEngine&&this.translationContext&&C.startsWith("$t:")&&(C=this.translationEngine.resolveTranslations(C,this.translationContext,m.data)),!confirm(C))return}const y=window.__g7ActionContext;window.__g7ActionContext={...r,data:m.data};try{await this.executeAction(e,m)}finally{window.__g7ActionContext=y}}catch(p){if(N.error("Action execution failed:",p),e.onError){const m=p instanceof Tt&&p.originalError?p.originalError:p,y={...this.defaultContext,data:{...n,error:m,_local:r?.state||{},$event:f},event:f,...r&&{state:r.state,setState:r.setState}},C=Array.isArray(e.onError)?e.onError:[e.onError];for(const S of C)await this.executeAction(S,y)}}}}generateActionId(e,n){const r=e.handler,i=n||"no-target",l=Date.now(),c=Math.random().toString(36).substring(2,9);return`${r}_${i.replace(/[^a-zA-Z0-9]/g,"_")}_${l}_${c}`}async executeAction(e,n){if(e=this.resolveActionRef(e),typeof e.handler=="string"&&e.handler.includes("{{")){const f=this.evaluateExpression(e.handler,n.data);e={...e,handler:f==null?"":String(f)}}const r=Xn(),i=r?.isEnabled()?`action_${Date.now()}_${Math.random().toString(36).substring(2,11)}`:void 0,l=performance.now();let c;if(i&&r&&r.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),context:this.sanitizeForDevTools({hasState:!!n.state,hasSetState:!!n.setState,dataKeys:n.data?Object.keys(n.data):[]}),startTime:l,status:"started"}),e.if!==void 0)try{const f=this.resolveValue(e.if,n.data),p=f===!0||f==="true"||f&&f!=="false"&&f!=="0"&&f!==!1;if(N.log("[executeAction] if condition result:",e.handler,p),!p)return i&&r&&r.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"success",result:{skipped:!0,reason:"if condition false"}}),{success:!0,data:void 0}}catch(f){return N.error("[executeAction] if condition error:",e.handler,f),i&&r&&r.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"error",error:{name:"ConditionEvaluationError",message:f instanceof Error?f.message:String(f),stack:f instanceof Error?f.stack:void 0}}),{success:!0,data:void 0}}let d;try{const f=this.resolveParams(e.params,n.data);i&&(c=this.sanitizeForDevTools(f));const p=e.target?this.resolveValue(e.target,n.data):void 0;if(e.handler==="apiCall"&&n.setState){d=this.generateActionId(e,p);const y=n.state?.loadingActions||{};n.setState({loadingActions:{...y,[d]:!0}})}if(this.previewMode&&Vm.has(e.handler))return N.warn(`Preview mode: "${e.handler}" suppressed`,p||f),i&&r&&r.logAction({id:i,type:e.handler,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"skipped",metadata:{reason:"preview_mode_suppressed"}}),{success:!0,data:void 0};let m;switch(e.handler){case"ensureIdentityVerified":m=await this.handleEnsureIdentityVerified(f);break;case"resolveIdentityChallenge":m=this.handleResolveIdentityChallenge(f);break;case"navigate":const y=f.path||p;m=await this.handleNavigate(y,f,n);break;case"navigateBack":m=await this.handleNavigateBack();break;case"navigateForward":m=await this.handleNavigateForward();break;case"openWindow":{const v=f.path||p;m=await this.handleOpenWindow(v,f);break}case"replaceUrl":{const v=f.path||p||window.location.pathname;m=await this.handleReplaceUrl(v,f);break}case"apiCall":if(e.onSuccess&&r?.isEnabled()&&i){const v=window.G7Core,x={};if(v?.state?.get){const w=v.state.get();x._global=w}n.state&&(x._local=n.state),r.registerStateCaptureForHandler?.(i,["_global","_local"],x)}const C=e.auth_mode??(e.auth_required?"required":"none"),S=e.identity_target?this.resolveParams(e.identity_target,n.data):void 0;m=await this.handleApiCall(p,f,n,C,S);break;case"login":m=await this.handleLogin(p,f,n);break;case"loginTwoFactor":m=await this.handleLoginTwoFactor(p,f,n);break;case"loginTwoFactorResend":m=await this.handleLoginTwoFactorResend(p,f,n);break;case"logout":m=await this.handleLogout(p,n);break;case"setState":N.log("[executeAction] setState resolvedParams:",f),m=await this.handleSetState(e.render!==void 0?{...f,__render:e.render}:f,n);break;case"setError":m=await this.handleSetError(p,f,n);break;case"openModal":m=await this.handleOpenModal(p,n);break;case"closeModal":m=await this.handleCloseModal(n);break;case"showAlert":m=await this.handleShowAlert(p,n);break;case"toast":m=await this.handleToast(f,n);break;case"switch":m=await this.handleSwitch(e,n);break;case"conditions":m=await this.handleConditions(e,n);break;case"sequence":m=await this.handleSequence(e,n);break;case"parallel":m=await this.handleParallel(e,n);break;case"startInterval":m=this.handleStartInterval(f,n);break;case"stopInterval":m=this.handleStopInterval(f);break;case"loadScript":m=await this.handleLoadScript(f,e,n);break;case"callExternal":m=await this.handleCallExternal(f,e,n);break;case"callExternalEmbed":m=await this.handleCallExternalEmbed(f,e,n);break;case"saveToLocalStorage":m=await this.handleSaveToLocalStorage(f,n);break;case"loadFromLocalStorage":m=await this.handleLoadFromLocalStorage(f,n);break;default:m=await this.handleCustomAction({...e,target:p,params:f},n);break}if(e.resultTo&&m!==void 0){const{target:y,key:C,merge:S}=e.resultTo,v=this.resolveValue(C,n.data),x=S==="replace"?"replace":S==="shallow"?"shallow":"deep";if(y==="_local"&&n.setState){const w=this.buildNestedUpdate(v,m),R=x!=="deep"?{...w,__mergeMode:x}:w;this.writeLocalState(n,R),N.log(`[resultTo] Saved to _local.${v} (merge=${x}):`,m)}else if(y==="_local"&&this.globalStateUpdater){const L=(window.G7Core?.state?.get()||{})._local||{},O=this.buildNestedUpdate(v,m);let j;x==="replace"?j=O:x==="shallow"?j={...L,...O}:j=this.deepMergeWithState(O,L),this.globalStateUpdater({_local:j}),N.log(`[resultTo] Saved to _local.${v} via globalStateUpdater (merge=${x}):`,m)}else if(y==="_global"&&this.globalStateUpdater){const w=this.buildNestedUpdate(v,m);this.globalStateUpdater(w),N.log(`[resultTo] Saved to _global.${v}:`,m)}else if(y==="_isolated"&&n.isolatedContext){const w=this.buildNestedUpdate(v,m);n.isolatedContext.mergeState(w,x),N.log(`[resultTo] Saved to _isolated.${v} (merge=${x}):`,m)}else N.warn(`[resultTo] Cannot save result: target=${y}, setState=${!!n.setState}, globalStateUpdater=${!!this.globalStateUpdater}, isolatedContext=${!!n.isolatedContext}`)}if(e.onSuccess){if(r?.isEnabled()&&i&&e.handler==="apiCall"){const S=window.G7Core,v={};S?.state?.get&&(v._global=S.state.get()),n.state&&(v._local=n.state),r.detectStaleClosure?.(i,`${e.handler} → onSuccess`,v,"callback-state-capture",i)}const y={...n,data:{...n.data,result:m,response:m}},C=Array.isArray(e.onSuccess)?e.onSuccess:[e.onSuccess];C.length>1?await this.handleSequence({handler:"sequence",type:"click",actions:C},y):C.length===1&&await this.executeAction(C[0],y)}return i&&r&&r.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),resolvedParams:c,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"success",result:this.sanitizeForDevTools(m)}),{success:!0,data:m}}catch(f){const p=f instanceof Tt?f:new Tt(`Failed to execute action: ${e.handler}`,e,f instanceof Error?f:void 0),m=p.originalError?.response||{},y=m.data||{},C=p.originalError?.status||m.status||500;let S=XC(p.originalError??f,e.handler,y.message,p.message);this.translationEngine&&this.translationContext&&S.startsWith("$t:")&&(S=this.translationEngine.resolveTranslations(S,this.translationContext));const v={status:C,message:S,errors:y.errors||m.errors,data:y,statusText:p.originalError?.statusText,error_code:y.error_code??m.error_code};if(p.unknownHandler)throw N.warn(`Unknown action handler "${e.handler}" — skipped (extension not loaded?). Not surfaced to the user.`),p;const w=Tr().resolve(C,{errorHandling:e.errorHandling,onError:e.onError});if(w.handler){if(r?.isEnabled()&&i&&e.handler==="apiCall"){const L=window.G7Core,O={};L?.state?.get&&(O._global=L.state.get()),n.state&&(O._local=n.state),r.detectStaleClosure?.(i,`${e.handler} → onError`,O,"callback-state-capture",i)}const R={...n,data:{...n.data,error:v}};try{const L={type:"click",handler:w.handler.handler,target:w.handler.target,params:w.handler.params,actions:w.handler.actions};return await this.executeAction(L,R),{success:!1,error:p}}catch(L){return N.error("Error executing error handler:",L),{success:!1,error:p}}}throw i&&r&&r.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),resolvedParams:c,startTime:l,endTime:performance.now(),duration:performance.now()-l,status:"error",error:{name:p.name,message:p.message,stack:p.stack}}),p}finally{if(e.handler==="apiCall"&&n.setState&&d){const f=n.state?.loadingActions||{},{[d]:p,...m}=f;n.setState({loadingActions:m})}}}async handleNavigate(e,n,r){let i=e;if(n.query||n.mergeQuery===!0)if(n.mergeQuery===!0)i=this.buildMergedQueryPath(e,n.query??{});else{const c=new URLSearchParams;for(const[f,p]of Object.entries(n.query))if(p!=null&&p!=="")if(Array.isArray(p)){const m=f.endsWith("[]")?f:`${f}[]`;for(const y of p)y!=null&&y!==""&&c.append(m,String(y))}else c.set(f,String(p));const d=c.toString();d&&(i=`${e}?${d}`)}if(N.log("handleNavigate:",{target:e,params:n,finalPath:i,replace:n.replace,windowLocationSearch:window.location.search}),n.replace===!0){const c=window.G7Core;if(c?.updateQueryParams){const d=typeof n.transition_overlay_target=="string"?n.transition_overlay_target:void 0;await c.updateQueryParams(i,d?{transitionOverlayTarget:d}:void 0),N.log("handleNavigate: Used updateQueryParams for replace mode",d?{transitionOverlayTarget:d}:void 0),this.applyScrollOption(n.scroll,n.scrollBehavior,"top");return}N.warn("handleNavigate: G7Core.updateQueryParams not available, falling back to React Router")}const l=this.resolveNavigateFallbackAction(i,n);if(l){N.warn(`handleNavigate: No route matched, falling back to "${l.handler}"`),await this.dispatchAction({type:"click",handler:l.handler,params:l.params},r),this.applyScrollOption(n.scroll,n.scrollBehavior,"top");return}if(!r.navigate)throw new Tt("Navigate function is not provided in context");r.navigate(i,{replace:n.replace===!0}),this.applyScrollOption(n.scroll,n.scrollBehavior,"top")}resolveNavigateFallbackAction(e,n){const r=n.fallback;if(r===!1||n.replace===!0)return null;const l=window.__templateApp?.getRouter?.();if(!l||typeof l.match!="function"||typeof l.getRoutes=="function"&&l.getRoutes().length===0)return null;const c=e.split("?")[0];return l.match(c)?null:this.resolveNavigateFallback(r,e,n)}resolveNavigateFallback(e,n,r){return e==null?{handler:"openWindow",params:{path:n,target:"_self"}}:typeof e=="string"?{handler:e,params:{path:n}}:typeof e=="object"&&typeof e.handler=="string"?{handler:e.handler,params:{path:n,...e.params||{}}}:(N.warn("resolveNavigateFallback: unrecognized fallback option, using openWindow",e),{handler:"openWindow",params:{path:n,target:"_blank"}})}applyScrollOption(e,n,r){const i=e===void 0?r:e;if(i==="preserve")return;const l=n==="smooth"?"smooth":"instant",c=y=>{if(typeof y!="object"||y===null)return!1;const C=y;return"container"in C||"to"in C||"block"in C||"offset"in C},d=(y,C,S=0)=>{y===window?window.scrollTo({top:C,left:S,behavior:l}):y.scrollTo({top:C,left:S,behavior:l})},f=(y,C,S,v)=>{if(C===window){y.scrollIntoView({behavior:l,block:S}),v&&window.scrollBy({top:-v,left:0,behavior:l});return}const x=C,w=y.getBoundingClientRect(),R=x.getBoundingClientRect(),L=x.scrollTop+(w.top-R.top);let O;S==="center"?O=L-(x.clientHeight-y.clientHeight)/2:S==="end"?O=L-(x.clientHeight-y.clientHeight):O=L,O-=v,x.scrollTo({top:Math.max(0,O),left:0,behavior:l})},p=()=>{window.scrollTo({top:0,left:0,behavior:l});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),x=v.overflowY,w=v.overflowX;(x==="auto"||x==="scroll"||w==="auto"||w==="scroll")&&S.scrollTo({top:0,left:0,behavior:l})})},m=()=>{try{if(c(i)){const y=i,C=y.block??"start",S=typeof y.offset=="number"?y.offset:0;let v=window;if(typeof y.container=="string"&&y.container.length>0){const w=document.querySelector(y.container);if(!w){N.warn(`applyScrollOption: container not found: ${y.container}`);return}v=w}const x=y.to??"top";if(x==="top"){v===window?p():d(v,0);return}if(typeof x=="number"){d(v,x-S);return}if(typeof x=="object"&&x!==null&&("x"in x||"y"in x)){const{x:w=0,y:R=0}=x;d(v,R-S,w);return}if(typeof x=="string"&&(x.startsWith("#")||x.startsWith("."))){const w=document.querySelector(x);w?f(w,v,C,S):N.warn(`applyScrollOption: target element not found: ${x}`);return}N.warn('applyScrollOption: invalid "to" value in extended form',x);return}if(i==="top"){p();return}if(typeof i=="number"){window.scrollTo({top:i,left:0,behavior:l});return}if(typeof i=="object"&&i!==null&&("x"in i||"y"in i)){const{x:y=0,y:C=0}=i;window.scrollTo({top:C,left:y,behavior:l});return}if(typeof i=="string"&&(i.startsWith("#")||i.startsWith("."))){const y=document.querySelector(i);y&&y.scrollIntoView({behavior:l,block:"start"});return}}catch(y){N.warn("applyScrollOption: failed to apply scroll",y)}};typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(m):m()}async handleOpenWindow(e,n){let r=e;if(n.query){const l=new URLSearchParams;for(const[d,f]of Object.entries(n.query))f!=null&&f!==""&&l.set(d,String(f));const c=l.toString();c&&(r=`${e}?${c}`)}const i=n.target==="_self"?"_self":"_blank";N.log("handleOpenWindow:",{target:e,params:n,finalPath:r,windowTarget:i}),i==="_self"?window.location.assign(r):window.open(r,"_blank")}async handleNavigateBack(){N.log("handleNavigateBack"),window.history.back()}async handleNavigateForward(){N.log("handleNavigateForward"),window.history.forward()}async handleReplaceUrl(e,n){let r=e;if(n.query||n.mergeQuery===!0)if(n.mergeQuery===!0)r=this.buildMergedQueryPath(e,n.query??{});else{const i=new URLSearchParams;for(const[c,d]of Object.entries(n.query))if(d!=null&&d!=="")if(Array.isArray(d)){const f=c.endsWith("[]")?c:`${c}[]`;for(const p of d)p!=null&&p!==""&&i.append(f,String(p))}else i.set(c,String(d));const l=i.toString();l&&(r=`${e}?${l}`)}N.log("handleReplaceUrl:",{target:e,params:n,finalPath:r}),window.history.replaceState(null,"",r),this.applyScrollOption(n.scroll,n.scrollBehavior,"preserve")}buildMergedQueryPath(e,n){const r=new URLSearchParams(window.location.search);for(const[c,d]of Object.entries(n))if(d==null||d==="")r.delete(c);else if(Array.isArray(d)){const f=c.endsWith("[]")?c:`${c}[]`;r.delete(c),r.delete(f);for(const p of d)p!=null&&p!==""&&r.append(f,String(p))}else r.set(c,String(d));const i=r.toString(),l=e.split("?")[0];return i?`${l}?${i}`:l}async ensureCsrfToken(){try{await fetch("/sanctum/csrf-cookie",{credentials:"include"})}catch(e){throw new Tt("Failed to fetch CSRF token",void 0,e instanceof Error?e:void 0)}}getCsrfTokenFromCookie(){const r=`; ${document.cookie}`.split("; XSRF-TOKEN=");if(r.length===2){const i=r.pop()?.split(";").shift();return i?decodeURIComponent(i):null}return null}buildQueryString(e){const n=new URLSearchParams;for(const[r,i]of Object.entries(e))if(!(i==null||i===""))if(Array.isArray(i))for(const l of i)l!=null&&l!==""&&n.append(`${r}[]`,String(l));else typeof i=="object"?n.append(r,JSON.stringify(i)):n.append(r,String(i));return n.toString()}async handleEnsureIdentityVerified(e){const n=typeof e.purpose=="string"?e.purpose:"sensitive_action",r=e.target&&typeof e.target=="object"?e.target:void 0;return await yt.handle({success:!1,error_code:"identity_verification_required",message:"",verification:{policy_key:e.policy_key??"",purpose:n,provider_id:e.provider_id??null,render_hint:e.render_hint??null,return_request:null}},void 0,r)!==null}handleResolveIdentityChallenge(e){const n=typeof e.result=="string"?e.result:"cancelled";let r;switch(n){case"verified":{const i=typeof e.token=="string"?e.token:"";if(!i){N.warn("resolveIdentityChallenge: result=verified 인데 token 이 비어있습니다. failed 로 강등합니다."),r={status:"failed",failureCode:"MISSING_TOKEN"};break}r={status:"verified",token:i,providerData:e.providerData&&typeof e.providerData=="object"?e.providerData:void 0};break}case"pending":{const i=typeof e.pollUrl=="string"?e.pollUrl:"",l=typeof e.expiresAt=="string"?e.expiresAt:"";if(!i||!l){N.warn("resolveIdentityChallenge: result=pending 인데 pollUrl/expiresAt 누락 — failed 로 강등합니다."),r={status:"failed",failureCode:"MALFORMED_PENDING"};break}r={status:"pending",pollUrl:i,pollIntervalMs:typeof e.pollIntervalMs=="number"?e.pollIntervalMs:void 0,expiresAt:l};break}case"failed":r={status:"failed",failureCode:typeof e.failureCode=="string"?e.failureCode:"UNKNOWN",reason:typeof e.reason=="string"?e.reason:void 0};break;case"cancelled":default:r={status:"cancelled"};break}return yt.resolveDeferred(r),!0}async handleApiCall(e,n,r,i="none",l){const{method:c="GET",body:d,headers:f,contentType:p}=n;c!=="GET"&&c!=="HEAD"&&await this.ensureCsrfToken();const m=this.getCsrfTokenFromCookie();let y={};if(i==="required"||i==="optional"){const K=Wn().getToken();K&&(y={Authorization:`Bearer ${K}`})}let C=e;const S=n.query||(c==="GET"?d:null);if(S&&typeof S=="object"){const P=this.buildQueryString(S);if(P){const K=e.includes("?")?"&":"?";C=`${e}${K}${P}`}}const v=window.G7Core?.state?.getGlobal?.()||r.state?._global||{},x=window.G7Core?.state?.getLocal?.()||r.state?._local||{},w={_global:v,_local:x},R=this.getMatchingGlobalHeaders(e,w),L={};if(typeof window<"u"){const P=localStorage.getItem("g7_locale");P&&(L["Accept-Language"]=P)}const O=p==="multipart/form-data",j={method:c,headers:{...O?{}:{"Content-Type":"application/json"},Accept:"application/json",...L,...m&&{"X-XSRF-TOKEN":m},...y,...R,...f},credentials:"include"};if(d&&c!=="GET")if(O){const P=new FormData;for(const[K,he]of Object.entries(d))he instanceof File||he instanceof Blob?P.append(K,he):he!=null&&P.append(K,typeof he=="object"?JSON.stringify(he):String(he));j.body=P}else j.body=JSON.stringify(d);const F=Xn();let G=null;F?.isEnabled()&&(G=F.trackRequest(C,c));try{let P=await fetch(C,j),K;try{K=await P.json()}catch{K=null}if(yt.isIdentityRequired(P.status,K)){const he=await yt.handle(K,{body:j.body,headers:j.headers,credentials:j.credentials},l);if(he){P=he;try{K=await P.json()}catch{K=null}}}if(G&&F?.isEnabled()&&(F.completeRequest(G,P.status,K),G=null),!P.ok){const he=K||{},Ee=new Error(he.message||`API call failed: ${P.statusText}`);throw Ee.response=he,Ee.status=P.status,Ee.statusText=P.statusText,new Tt(he.message||`API call failed: ${P.statusText}`,void 0,Ee)}return K}catch(P){throw G&&F?.isEnabled()&&F.failRequest(G,P instanceof Error?P.message:String(P)),P}}async handleLogin(e,n,r){const{body:i}=n;if(!i||!i.email||!i.password)throw new Tt("Login requires email and password in body params");const l=this.resolveAuthType(e),c=l==="admin"?"/api/auth/admin/login":"/api/auth/login",d=Yn.getInstance();try{const f=await d.login(l,{email:i.email,password:i.password},this.buildAuthRequestOptions(c,r));return f.status==="two_factor_required"?{user:null,two_factor_required:!0,challenge_id:f.challenge.challengeId,provider_id:f.challenge.providerId,expires_at:f.challenge.expiresAt}:{user:f.user,two_factor_required:!1}}catch(f){throw this.toLoginActionError(f,"Login failed")}}async handleLoginTwoFactor(e,n,r){const{body:i}=n;if(!i||!i.challenge_id||!i.code)throw new Tt("loginTwoFactor requires challenge_id and code in body params");const l=this.resolveAuthType(e),c=l==="admin"?"/api/auth/admin/login/two-factor":"/api/auth/login/two-factor";try{return{user:await Yn.getInstance().completeTwoFactor(l,{challengeId:String(i.challenge_id),code:String(i.code)},this.buildAuthRequestOptions(c,r))}}catch(d){throw this.toLoginActionError(d,"Login failed")}}async handleLoginTwoFactorResend(e,n,r){const{body:i}=n;if(!i||!i.challenge_id)throw new Tt("loginTwoFactorResend requires challenge_id in body params");const l=this.resolveAuthType(e),c=l==="admin"?"/api/auth/admin/login/two-factor/resend":"/api/auth/login/two-factor/resend";try{const d=await Yn.getInstance().resendTwoFactor(l,{challengeId:String(i.challenge_id)},this.buildAuthRequestOptions(c,r));return{two_factor_required:!0,challenge_id:d.challengeId,provider_id:d.providerId,expires_at:d.expiresAt}}catch(d){throw this.toLoginActionError(d,"Resend failed")}}resolveAuthType(e){return e==="user"?"user":"admin"}buildAuthRequestOptions(e,n){const r=window.G7Core?.state?.getGlobal?.()||n.state?._global||{},i=window.G7Core?.state?.getLocal?.()||n.state?._local||{},l={_global:r,_local:i},c=this.getMatchingGlobalHeaders(e,l);return Object.keys(c).length>0?{headers:c}:void 0}toLoginActionError(e,n){const r=e?.message||n,i=new Error(r);return i.response=e?.response?.data||{},i.status=e?.status||e?.response?.status||500,i.code=e?.code,new Tt(r,void 0,i)}async handleLogout(e,n){await Yn.getInstance().logout()}async handleSetState(e,n){N.log("[handleSetState] START, params:",e);const{target:r="component",scope:i,merge:l,__render:c,...d}=e,f=Xn(),p=window.G7Core;if(typeof r=="string"&&(r.startsWith("$parent.")||r.startsWith("$root.")))return this.handleParentScopeSetState(r,d,l,n);const m=n.state&&Object.keys(n.state).length>0?n.state:p?.state?.get()||{},y=r==="global"?"_global":r.startsWith("_local.")?r:"_local",C=y==="_global"?m._global:y.startsWith("_local.")?this.getNestedProperty(m._local||{},y.slice(7)):m._local,S=f?.isEnabled()?f.startStateChange(y,C,d,{actionId:n.actionId,handlerType:"setState",source:`target=${r}`}):void 0,v=l==="replace"?"replace":l==="shallow"?"shallow":"deep",x=v!=="deep"?{...d,__mergeMode:v,...S?{__setStateId:S}:{}}:{...d,...S?{__setStateId:S}:{}};if(r==="global"){if(!this.globalStateUpdater){N.warn("Global state updater is not set"),S&&f&&f.completeStateChange(S);return}const w=p?.state?.get()||{},{__setStateId:R,__mergeMode:L,...O}=x,j=v==="deep"?this.deepMergeWithState(O,w):O,F={...j,...S?{__setStateId:S}:{},...v!=="deep"?{__mergeMode:v}:{}};return N.log("setState global:",F),this.globalStateUpdater(F,{render:c}),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"global",...v!=="deep"?{__mergeMode:v}:{},...j}}else if(r==="isolated"){const w=n.isolatedContext;if(w){const{__mergeMode:R,__setStateId:L,...O}=x;return w.mergeState(O,v),N.log("[handleSetState] isolated state updated:",O,"mergeMode:",v),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"isolated",...O}}else if(N.warn('[handleSetState] isolated target used but no IsolatedStateContext found. Make sure the component has "isolatedState" attribute. Falling back to local state.'),n.setState){const L=window.__g7PendingLocalState||n.state||{},O=v==="deep"?this.deepMergeWithState(x,L):x;return this.writeLocalState(n,O),S&&f&&setTimeout(()=>f.completeStateChange(S),0),O}else throw S&&f&&f.completeStateChange(S),new Tt("isolated target used but no IsolatedStateContext found and no setState function in context")}else if(r==="local"||r==="component"||r==="_local"){if(i==="parent"||i==="root"){const R=window.__g7LayoutContextStack||[];if(R.length>0){const L=i==="parent"?R[R.length-1]:R[0];if(L?.setState){const{__mergeMode:O,__setStateId:j,...F}=x,G=v==="deep"?this.deepMergeWithState(F,L.state||{}):F;return N.log(`[handleSetState] scope=${i}: 타겟 컨텍스트에 상태 업데이트`,G),L.setState(G),S&&f&&setTimeout(()=>f.completeStateChange(S),0),G}}N.warn(`[handleSetState] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const w=n.setState&&!n._isDispatchFallbackContext;if(N.log("[handleSetState] isRealComponentContext:",w,"context.setState:",!!n.setState,"_isDispatchFallbackContext:",n._isDispatchFallbackContext),w){N.log("[handleSetState] Using COMPONENT setState path"),N.log("[handleSetState] resolvedPayload:",x),N.log("[handleSetState] context.state:",n.state),N.log("[handleSetState] mergeMode:",v);const L=window.__g7PendingLocalState||n.state||{},O=v==="deep"?this.deepMergeWithState(x,{}):x;N.log("[handleSetState] convertedPayload (변경 필드만, dot notation 변환):",O),n.setState(O);const j=v==="deep"?this.deepMergeWithState(x,L):v==="shallow"?{...n.state||{},...x}:x,{__mergeMode:F,__setStateId:G,...P}=j;window.__g7PendingLocalState=P,N.log("[handleSetState] __g7PendingLocalState updated:",P);const K=(window.__g7LayoutContextStack||[]).length;let he;if(this.globalStateUpdater){const je=K===0?window.__templateApp?.getGlobalState?.()?._local:void 0;if(v!=="replace"&&!!je&&typeof je=="object"&&!Array.isArray(je)){const de=v==="deep"?this.deepMergeWithState(x,je):{...je,...x},{__mergeMode:Ce,__setStateId:Z,...ge}=de;he=ge}else v!=="replace"&&N.log("[handleSetState] canonical _local 미사용 → 전체 스냅샷 폴백",{modalDepth:K,hasTemplateApp:!!window.__templateApp});const X=he?Ro(he,P):P;this.globalStateUpdater({_local:X},{render:!1}),N.log("[handleSetState] _global._local synced (render:false):",X)}const{__mergeMode:Ee,__setStateId:ke,...ze}=x;if(v==="replace")window.__g7ForcedLocalFields=ze;else{const je=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=this.deepMergeWithState(ze,je)}return N.log("[handleSetState] __g7ForcedLocalFields updated:",ze),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"local",...he?Ro(he,P):j,...v!=="deep"?{__mergeMode:v}:{}}}else if(this.globalStateUpdater){N.log("[handleSetState] Using GLOBAL STATE UPDATER path for _local");const L=window.__g7PendingLocalState||m._local||{};N.log("[handleSetState] currentLocal (with pending):",L);const O=v==="deep"?this.deepMergeWithState(x,L):x;return N.log("[handleSetState] finalLocal (merged):",O),this.globalStateUpdater({_local:O},{render:c}),window.__g7PendingLocalState=O,N.log("[handleSetState] __g7PendingLocalState updated for globalStateUpdater path"),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"local",...O}}else throw S&&f&&f.completeStateChange(S),new Tt("setState function is not provided in context and globalStateUpdater is not set")}else if(r.startsWith("_local.")){const w=r.slice(7),{__mergeMode:R,__setStateId:L,...O}=x,j=O.value!==void 0?O.value:Object.values(O)[0];if(n.setState){const G=window.__g7PendingLocalState||n.state||{},P=this.createNestedUpdate(w,j,G),K={...G,...P};if(n.setState(P),this.globalStateUpdater&&i!=="parent"&&i!=="root"){const he=window.__templateApp?.getGlobalState?.()?._local,Ee=he&&typeof he=="object"?{...he,...P}:K;this.globalStateUpdater({_local:Ee},{render:!1}),N.log("[handleSetState] _global._local synced for dot notation (render:false):",Ee)}return S&&f&&setTimeout(()=>f.completeStateChange(S),0),K}else throw S&&f&&f.completeStateChange(S),new Tt("setState function is not provided in context")}else{if(!n.setState)throw S&&f&&f.completeStateChange(S),new Tt("setState function is not provided in context");const R=window.__g7PendingLocalState||n.state||{},L=v==="deep"?this.deepMergeWithState(x,R):x;return this.writeLocalState(n,L,void 0,{scope:i}),S&&f&&setTimeout(()=>f.completeStateChange(S),0),L}}async handleParentScopeSetState(e,n,r,i){const l=Xn(),c=window.G7Core,d=r==="replace"?"replace":r==="shallow"?"shallow":"deep",f=e.startsWith("$parent."),p=f?"$parent.":"$root.",m=e.slice(p.length);let y,C;if(m==="_local"||m==="_global")y=m,C=void 0;else if(m.startsWith("_local."))y="_local",C=m.slice(7);else if(m.startsWith("_global."))y="_global",C=m.slice(8);else{N.warn(`[handleParentScopeSetState] 지원하지 않는 타겟 형식: ${e}. _local 또는 _global으로 시작해야 합니다.`);return}const S=window.__g7LayoutContextStack||[];if(S.length===0){N.warn(`[handleParentScopeSetState] 레이아웃 컨텍스트 스택이 비어있습니다. target=${e}`);return}const v=f?S[S.length-1]:S[0];if(!v){N.warn(`[handleParentScopeSetState] 타겟 컨텍스트를 찾을 수 없습니다. target=${e}`);return}const x=y==="_global"?v.state?._global:v.state?._local,w=l?.isEnabled()?l.startStateChange(e,x,n,{actionId:i.actionId,handlerType:"setState",source:`target=${e}`}):void 0,{__mergeMode:R,__setStateId:L,...O}=n;if(y==="_global"){if(!this.globalStateUpdater){N.warn("[handleParentScopeSetState] globalStateUpdater가 설정되지 않았습니다."),w&&l&&l.completeStateChange(w);return}const j=c?.state?.get()||{};if(C){const F=O.value!==void 0?O.value:Object.values(O)[0],G=this.createNestedUpdate(C,F,j),P={...j,...G};N.log(`[handleParentScopeSetState] ${e}: 전역 상태 중첩 경로 업데이트`,P),this.globalStateUpdater(P)}else{const F=d==="deep"?this.deepMergeWithState(O,j):O;N.log(`[handleParentScopeSetState] ${e}: 전역 상태 업데이트 (mergeMode=${d})`,F),this.globalStateUpdater(d!=="deep"?{...F,__mergeMode:d}:F)}return w&&l&&setTimeout(()=>l.completeStateChange(w),0),{__target:e,...O}}else{if(!v.setState){N.warn(`[handleParentScopeSetState] 타겟 컨텍스트에 setState가 없습니다. target=${e}`),w&&l&&l.completeStateChange(w);return}const j=v.state||{};if(C){const F=O.value!==void 0?O.value:Object.values(O)[0],G=this.createNestedUpdate(C,F,j),P={...j,...G};return N.log(`[handleParentScopeSetState] ${e}: 로컬 상태 중첩 경로 업데이트`,G),v.setState(G),v.state=P,v.dataContext&&(v.dataContext._local=P),vf(),w&&l&&setTimeout(()=>l.completeStateChange(w),0),P}else{const F=d!=="deep"?{...O,__mergeMode:d}:O,G=d==="replace"?O:d==="shallow"?{...j,...O}:this.deepMergeWithState(O,j);return N.log(`[handleParentScopeSetState] ${e}: 로컬 상태 업데이트 (mergeMode=${d})`,G),v.setState(F),v.state=G,v.dataContext&&(v.dataContext._local=G),vf(),w&&l&&setTimeout(()=>l.completeStateChange(w),0),G}}}deepMergeWithState(e,n){const r=["errors"];let i=e;if("..."in e){const c=e["..."];if(c&&typeof c=="object"&&!Array.isArray(c)){const{"...":d,...f}=e;i={...c,...f}}else{const{"...":d,...f}=e;i=f}}const l={...n};for(const[c,d]of Object.entries(i)){if(r.includes(c)){l[c]=d;continue}if(c.includes(".")&&c!=="..."){const f=this.createNestedUpdate(c,d,l);this.deepMergeInto(l,f,l);continue}if(d!==null&&typeof d=="object"&&!Array.isArray(d)&&Object.getPrototypeOf(d)!==Object.prototype&&Object.getPrototypeOf(d)!==null){l[c]=d;continue}d!==null&&typeof d=="object"&&!Array.isArray(d)&&n[c]!==null&&typeof n[c]=="object"&&!Array.isArray(n[c])?l[c]=this.deepMergeWithState(d,n[c]):l[c]=d}return l}deepMergeInto(e,n,r){for(const[i,l]of Object.entries(n)){if(l===null){e[i]=l;continue}if(e[i]===null){e[i]=l;continue}typeof l=="object"&&!Array.isArray(l)&&e[i]!==void 0&&e[i]!==null&&typeof e[i]=="object"&&!Array.isArray(e[i])?(e[i]===r[i]&&(e[i]={...e[i]}),this.deepMergeInto(e[i],l,r[i]||{})):typeof l=="object"&&!Array.isArray(l)&&e[i]===void 0&&r[i]!==null&&typeof r[i]=="object"&&!Array.isArray(r[i])?e[i]={...r[i],...l}:e[i]=l}}createNestedUpdate(e,n,r){const i=e.split(".");if(i.length===1)return{[i[0]]:n};const l={};let c=l,d=r;for(let f=0;f{this.globalStateUpdater({_local:S})};m.push({state:y,setState:C,dataContext:{_local:y||n.data?._local,_global:l?n.data?._global:n.data?._global||i?.state?.get?.(),_computed:n.data?._computed}}),window.__g7LayoutContextStack=m,N.log(`[handleOpenModal] 레이아웃 컨텍스트 스택에 push, 스택 크기: ${m.length}, state:`,y,l?"(direct)":"(fallback via G7Core)")}else N.warn(`[handleOpenModal] 컨텍스트 스택에 push 실패 - setState: ${!!n.setState}, state: ${n.state!==void 0}, G7Core: ${!!i?.state?.getLocal}`);const f=[...r,e];this.globalStateUpdater({modalStack:f,activeModal:e});const p=Xn();if(p?.isEnabled()){const m=r.length>0?r[r.length-1]:void 0;p.trackModalOpen?.({modalId:e,modalName:e,scopeType:"isolated",parentModalId:m,initialState:n.state?{...n.state}:{}})}}async handleCloseModal(e){if(!this.globalStateUpdater){N.warn("Global state updater is not set for closeModal");return}const n=e?.data?._global?.modalStack||[],r=n.length>0?n[n.length-1]:null,i=n.slice(0,-1),l=i.length>0?i[i.length-1]:null,c=window.__g7LayoutContextStack||[];if(c.length>0){const d=c[c.length-1];d&&(d.dataContext=void 0),c.pop(),window.__g7LayoutContextStack=c,N.log(`[handleCloseModal] 레이아웃 컨텍스트 스택에서 pop, 스택 크기: ${c.length}`)}if(r){const d=Xn();d?.isEnabled()&&d.trackModalClose?.(r,e?.state)}this.globalStateUpdater({modalStack:i,activeModal:l})}async handleShowAlert(e,n){let r=e;this.translationEngine&&this.translationContext&&e.startsWith("$t:")&&(r=this.translationEngine.resolveTranslations(e,this.translationContext,n.data)),alert(r)}async handleToast(e,n){const{type:r="info",message:i,icon:l,duration:c}=e;if(r==="error"){const f=n.data?.error;if((f?.error_code==="identity_verification_required"||f?.data?.error_code==="identity_verification_required")&&yt.consumeDomainNoticeShown()){N.log("[Toast] IDV 도메인 안내 표출됨 — 중복 가드 토스트 1건 skip");return}}let d=i;if(this.translationEngine&&this.translationContext&&i?.startsWith("$t:")&&(d=this.translationEngine.resolveTranslations(i,this.translationContext,n.data)),this.globalStateUpdater){const p={id:`toast_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,type:r,message:d,...l&&{icon:l},...c&&{duration:c}},S=[...window.G7Core?.state?.get()?.toasts||[],p];this.globalStateUpdater({toasts:S})}else N.log(`[Toast ${r}] ${d}`)}async handleSwitch(e,n){const{cases:r}=e;if(!r){N.warn("switch handler requires cases property");return}const i=this.resolveParams(e.params,n.data);let l;if(i?.value!==void 0?(l=i.value,N.log("switch handler: using params.value as case key:",l)):(l=n.data?.$args?.[0],N.log("switch handler: using $args[0] as case key:",l)),l==null){if(r.default)return N.log("switch handler: case key is undefined, using default case"),await this.executeAction(r.default,n);N.warn("switch handler: case key is not defined and no default case");return}const c=String(l);let d=r[c];if(!d&&r.default&&(N.log(`switch handler: no case found for key "${c}", using default case`),d=r.default),!d){N.warn(`switch handler: no case found for key "${c}" and no default case`);return}return await this.executeAction(d,n)}async handleConditions(e,n){const{conditions:r}=e;if(!r||!Array.isArray(r)){N.warn("conditions handler requires conditions array");return}const i=n.data||{},l=Vg(r,i,this.bindingEngine);if(!l.matched){N.log("conditions handler: no matching branch found");return}const c=r[l.branchIndex];if(N.log(`conditions handler: matched branch ${l.branchIndex}`),!c.then){N.warn('conditions handler: matched branch has no "then" action');return}return Array.isArray(c.then)?await this.handleSequence({...e,actions:c.then},n):await this.executeAction(c.then,n)}handleStartInterval(e,n){const r=typeof e.id=="string"?e.id:"",i=Number(e.intervalMs??1e3),l=Array.isArray(e.actions)?e.actions:[];if(r===""||!l.length||i<=0)return N.warn("startInterval requires non-empty id, positive intervalMs, and actions array"),{success:!1};const c=this.intervals.get(r);c&&(clearInterval(c),this.intervals.delete(r));const d=setInterval(()=>{for(const f of l)this.executeAction(f,n).catch(p=>{N.error(`[startInterval:${r}] tick action failed`,p)})},i);return this.intervals.set(r,d),{success:!0,id:r}}handleStopInterval(e){const n=typeof e.id=="string"?e.id:"";if(n==="")return N.warn("stopInterval requires id parameter"),{success:!1};const r=this.intervals.get(n);return r&&(clearInterval(r),this.intervals.delete(n)),{success:!0,id:n}}stopAllIntervals(){for(const e of this.intervals.values())clearInterval(e);this.intervals.clear()}async handleSequence(e,n){const r=e.actions||e.params?.actions;if(!r||!Array.isArray(r)||r.length===0)return N.warn("sequence handler requires non-empty actions array"),[];const i=Xn(),l=i?.isEnabled()&&i.startSequenceExecution?.({eventType:e.type})||"";window.__g7SequenceLocalSync=void 0;const c=[];let d,f=n.state?{...n.state}:{},p=n.isolatedContext?.state?{...n.isolatedContext.state}:{},m=n.data?._computed||{};const y=window.G7Core,C=()=>({_global:y?.state?.get()||{},_local:{...f},_isolated:Object.keys(p).length>0?{...p}:void 0});for(let S=0;S0){const O={},j={...n.data,_local:f,_computed:O,$computed:O,_isolated:p};for(const[F,G]of Object.entries(L))if(typeof G=="string"){const P=G.trim();if(P.startsWith("{{")&&P.endsWith("}}"))try{const K=P.slice(2,-2).trim();O[F]=On(K)?this.bindingEngine.evaluatePipeExpression(K,j,{skipCache:!0}):this.bindingEngine.evaluateExpression(K,j,{skipCache:!0})}catch{O[F]=m[F]}}m=O,N.log("[handleSequence] _computed recalculated after setState:",m)}}if(v.handler!=="setState"){const L=window.__g7SequenceLocalSync;if(L&&L!==f){f=L,window.__g7SequenceLocalSync=void 0,N.log("[handleSequence] currentState synchronized from __g7SequenceLocalSync after custom handler:",v.handler);const O=n.data?._computedDefinitions;if(O&&Object.keys(O).length>0){const j={},F={...n.data,_local:f,_computed:j,$computed:j,_isolated:p};for(const[G,P]of Object.entries(O))if(typeof P=="string"){const K=P.trim();if(K.startsWith("{{")&&K.endsWith("}}"))try{const he=K.slice(2,-2).trim();j[G]=On(he)?this.bindingEngine.evaluatePipeExpression(he,F,{skipCache:!0}):this.bindingEngine.evaluateExpression(he,F,{skipCache:!0})}catch{j[G]=m[G]}}m=j,N.log("[handleSequence] _computed recalculated after custom handler:",m)}}}l&&i?.isEnabled()&&i.captureSequenceActionAfter?.(l,S,C(),Date.now()-x,R.data)}catch(R){throw l&&i?.isEnabled()&&(i.captureSequenceActionAfter?.(l,S,C(),Date.now()-x,void 0,R),i.endSequenceExecution?.(l,R)),N.error(`sequence handler: action[${S}] failed:`,R),R}}return window.__g7SequenceLocalSync=void 0,l&&i?.isEnabled()&&i.endSequenceExecution?.(l),c}async handleParallel(e,n){const r=e.actions||e.params?.actions;if(!r||!Array.isArray(r)||r.length===0)return N.warn("parallel handler requires non-empty actions array"),[];N.log(`parallel handler: executing ${r.length} actions in parallel`);const i=n.isolatedContext?{...n.isolatedContext,state:{...n.isolatedContext.state}}:null,l=r.map((f,p)=>{const m={...n,isolatedContext:i};return this.executeAction(f,m).catch(y=>{throw N.error(`parallel handler: action[${p}] failed:`,y),y})}),c=await Promise.allSettled(l),d=c.filter(f=>f.status==="rejected").length;return d>0&&N.warn(`parallel handler: ${d}/${r.length} actions failed`),c}assertAllowedExtensionAssetUrl(e,n,r){if(!Oo(e,fs()))throw N.error(`Blocked untrusted ${n} asset url: ${e}`),new Tt(`Blocked untrusted ${n} url (same-origin path or declared trusted host required): ${e}`,r)}async handleLoadScript(e,n,r){const{src:i,id:l,async:c=!0,defer:d=!1}=e;if(!i)throw new Tt('loadScript handler requires "src" parameter',n);if(!Oo(i,fs()))throw N.warn(`loadScript: blocked untrusted script src (same-origin path or declared trusted host required): ${i}`),new Tt(`Blocked untrusted script src (same-origin path or declared trusted host required): ${i}`,n);const f=l||`script_${i.replace(/[^a-zA-Z0-9]/g,"_")}`;if(rn.loadedScripts.has(f))return N.log(`loadScript: script already loaded, skipping: ${f}`),n.onLoad&&await this.executeAction(n.onLoad,r),!0;const p=rn.loadingScripts.get(f);if(p)return N.log(`loadScript: joining in-flight load: ${f}`),await p,n.onLoad&&await this.executeAction(n.onLoad,r),!0;if(document.getElementById(f))return N.log(`loadScript: script element already exists: ${f}`),rn.loadedScripts.add(f),n.onLoad&&await this.executeAction(n.onLoad,r),!0;N.log(`loadScript: loading script: ${i}`);const y=document.createElement("script");if(y.id=f,y.src=i,y.async=c,y.defer=d,y.hasAttribute("data-gdpr-blocked-src"))return N.warn(`loadScript: script blocked by consent manager (not loaded): ${i}`),!1;const C=new Promise((S,v)=>{y.onload=()=>{N.log(`loadScript: script loaded successfully: ${f}`),rn.loadedScripts.add(f),rn.loadingScripts.delete(f),S()},y.onerror=x=>{N.error(`loadScript: failed to load script: ${i}`,x),rn.loadingScripts.delete(f),v(new Tt(`Failed to load script: ${i}`,n))},document.head.appendChild(y)});if(C.catch(()=>{}),rn.loadingScripts.set(f,C),await C,n.onLoad)try{await this.executeAction(n.onLoad,r)}catch(S){N.error("loadScript: onLoad action failed:",S)}return!0}async handleCallExternal(e,n,r){const i=e.constructor,l=e.args||{},c=e.method,d=e.methodArgs||[],f=e.callbackEvent,p=e.embedTarget,m=e.callbackSetState,y=e.callbackAction;if(!i)throw new Tt('callExternal handler requires "constructor" parameter',n);const C=this.getNestedProperty(window,i);if(!C||typeof C!="function")throw new Tt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first using loadScript handler.`,n);this.assertCallableExternalConstructor(C,i,n),N.log(`callExternal: calling constructor ${i}`);const S={...l};for(const[x,w]of Object.entries(l))w===!0&&(S[x]=R=>{if(N.log(`callExternal: callback triggered for ${x}`,R),f&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(f,R),m&&r.setState){const L=F=>{const G={};for(const[P,K]of Object.entries(F)){if(rn.isPrototypePathSegment(P)){N.warn(`callExternal: skipped prototype-polluting mapping key: ${P}`);continue}typeof K=="string"?G[P]=this.getNestedProperty(R,K):typeof K=="object"&&K!==null&&(G[P]=L(K))}return G},O=L(m);N.log("callExternal: callbackSetState mapping result",O);const j=this.deepMergeWithState(O,r.state||{});N.log("callExternal: merged with existing state",j),this.writeLocalState(r,j)}else f&&r.setState&&this.writeLocalState(r,{[`${f.replace(/:/g,"_")}_result`]:R});if(y){const L={...r,data:{...r.data,$event:R}},O=Array.isArray(y)?y:[y];for(const j of O)try{this.executeAction(j,L)}catch(F){N.error("callExternal: callbackAction failed:",F)}}});const v=new C(S);if(c&&typeof v[c]=="function"){if(N.log(`callExternal: calling method ${c}`),c==="embed"&&p){const x=document.querySelector(p);if(x)return v[c](x,...d);throw new Tt(`Embed target element not found: ${p}`,n)}return v[c](...d)}return v}async handleCallExternalEmbed(e,n,r){const i=e.constructor,l=e.args||{},c=e.callbackSetState,d=e.callbackEvent,f=e.layerClassName,p=e.callbackAction;if(!i)throw new Tt('callExternalEmbed handler requires "constructor" parameter',n);const m=this.getNestedProperty(window,i);if(!m||typeof m!="function")throw new Tt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first.`,n);this.assertCallableExternalConstructor(m,i,n),N.log(`callExternalEmbed: creating layer for ${i}`);const{layer:y,closeLayer:C}=this.createEmbedLayer(f),S={...l};for(const[x,w]of Object.entries(l))w===!0&&(S[x]=R=>{if(N.log(`callExternalEmbed: callback triggered for ${x}`,R),C(),d&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(d,R),c&&r.setState){const L=F=>{const G={};for(const[P,K]of Object.entries(F)){if(rn.isPrototypePathSegment(P)){N.warn(`callExternal: skipped prototype-polluting mapping key: ${P}`);continue}typeof K=="string"?G[P]=this.getNestedProperty(R,K):typeof K=="object"&&K!==null&&(G[P]=L(K))}return G},O=L(c);N.log("callExternalEmbed: callbackSetState mapping result",O);const j=this.deepMergeWithState(O,r.state||{});N.log("callExternalEmbed: merged with existing state",j),this.writeLocalState(r,j)}if(p){const L={...r,data:{...r.data,$event:R}},O=Array.isArray(p)?p:[p];for(const j of O)try{this.executeAction(j,L)}catch(F){N.error("callExternalEmbed: callbackAction failed:",F)}}});const v=new m(S);if(typeof v.embed=="function")v.embed(y),N.log("callExternalEmbed: embedded in layer");else throw C(),new Tt(`Constructor ${i} does not have embed method`,n);return v}isImeComposing(e){return e?.isComposing===!0||e?.keyCode===229}createEmbedLayer(e){const n=document.createElement("div");n.id="g7-embed-overlay",n.style.cssText=` position: fixed; inset: 0; background-color: rgba(0, 0, 0, 0.5); @@ -50,11 +87,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 l=()=>{n.parentNode&&n.parentNode.removeChild(n)};i.onclick=l;const c=d=>{this.isImeComposing(d)||d.key==="Escape"&&(l(),document.removeEventListener("keydown",c))};return document.addEventListener("keydown",c),n.onclick=d=>{d.target===n&&l()},r.appendChild(i),n.appendChild(r),document.body.appendChild(n),{overlay:n,layer:r,closeLayer:l}}static isPrototypePathSegment(e){return cn.PROTOTYPE_PATH_SEGMENTS.includes(e)}getNestedProperty(e,n){return n.split(".").reduce((r,i)=>{if(!cn.isPrototypePathSegment(i))return r&&r[i]!==void 0?r[i]:void 0},e)}assertCallableExternalConstructor(e,n,r){if(typeof window>"u")return;if([window.Function,window.eval,window.setTimeout,window.setInterval].some(l=>l!==void 0&&l===e))throw j.error(`callExternal: blocked arbitrary code execution seam: ${n}`),new jt(`Blocked constructor (arbitrary code execution): ${n}`,r)}async handleSaveToLocalStorage(e,n){const{key:r,value:i}=e;if(!r)return j.error("saveToLocalStorage: key parameter is required"),!1;try{const l=typeof i=="string"?i:JSON.stringify(i);return localStorage.setItem(r,l),j.log(`saveToLocalStorage: saved ${r}`,i),!0}catch(l){return j.error("saveToLocalStorage: failed to save",{key:r,error:l}),!1}}async handleLoadFromLocalStorage(e,n){const{key:r,target:i,stateKey:l,defaultValue:c}=e;if(!r)return j.error("loadFromLocalStorage: key parameter is required"),c;try{const d=localStorage.getItem(r);if(d===null)return j.log(`loadFromLocalStorage: no value found for ${r}, using default`),l&&n.setState&&this.writeLocalState(n,{[l]:c}),c;let f;try{f=JSON.parse(d)}catch{f=d}return j.log(`loadFromLocalStorage: loaded ${r}`,f),l&&n.setState&&this.writeLocalState(n,{[l]:f}),f}catch(d){return j.error("loadFromLocalStorage: failed to load",{key:r,error:d}),c}}writeLocalState(e,n,r,i){const l=r||e.setState;if(!l)return;if(typeof n=="function"){j.warn("[writeLocalState] 함수형 업데이터는 저장소 B 미러 대상이 아닙니다 (payload 추출 불가). 저장소 A 만 갱신합니다."),l(n);return}if(i?.scope==="parent"||i?.scope==="root"){l(n);return}if(this.localMirrorDepth>0||l?.__g7CanonicalWriter){l(n);return}const c=n&&typeof n=="object"?n:{},d=c.__mergeMode;if(d==="replace"){l(n);return}const{__mergeMode:f,__setStateId:h,...m}=c;if("errors"in m||!cn.isMirrorSafePayload(m)){l(n);return}const y=window;if((y.__g7LayoutContextStack||[]).length>0){l(n);return}const v=y.G7Core?.state?.setLocal;if(!y.__templateApp||typeof v!="function"){l(n);return}const S=this.deepMergeWithState(m,{});this.localMirrorDepth++;try{v(S,{render:!1,merge:d??"deep"}),y.__g7ActionContext?.setState!==l&&l(n),d&&(y.__g7ForcedLocalFields={...y.__g7ForcedLocalFields||{},...S})}finally{this.localMirrorDepth--}}static isMirrorSafePayload(e,n=0){if(e===null||typeof e!="object"||n>=8)return!0;if(Array.isArray(e))return e.every(i=>cn.isMirrorSafePayload(i,n+1));const r=Object.getPrototypeOf(e);return r!==Object.prototype&&r!==null?!1:Object.values(e).every(i=>cn.isMirrorSafePayload(i,n+1))}makeLocalSetStateProxy(e){const n=e.setState;if(!n)return;if(n.__g7CanonicalWriter)return n;const r=i=>{this.writeLocalState(e,i,n)};return r.__g7CanonicalWriter=!0,r}async handleCustomAction(e,n){const r=this.customHandlers.get(e.handler);if(!r){if(this.previewMode){j.warn(`[Preview] Unknown action handler "${e.handler}" — skipped (preview mode)`);return}const c=new jt(`Unknown action handler: ${e.handler}`,e);throw c.unknownHandler=!0,c}const i=this.makeLocalSetStateProxy(n),l=i&&i!==n.setState?{...n,setState:i}:n;return await r(e,l)}resolveParams(e,n){if(!e)return{};const r={};for(const[i,l]of Object.entries(e))i.includes("{{")&&j.warn(`[resolveParams] setState params의 키에 표현식이 포함되어 있습니다: "${i}". 키는 해석되지 않습니다. 배열 항목 수정은 .map()/.filter() 패턴을 사용하세요.`),typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,n):typeof l=="string"?r[i]=l:Array.isArray(l)?r[i]=l.map(c=>typeof c=="string"&&c.includes("{{")?this.evaluateExpression(c,n):c):typeof l=="object"&&l!==null&&!Array.isArray(l)&&Object.getPrototypeOf(l)!==Object.prototype&&Object.getPrototypeOf(l)!==null?r[i]=l:typeof l=="object"&&l!==null?r[i]=this.resolveParams(l,n):r[i]=l;return r}resolveValue(e,n){return n?this.bindingEngine.resolveBindings(e,n,{skipCache:!0}):e}evaluateExpressions(e,n){let r={};for(const[i,l]of Object.entries(e))if(i==="..."){let c=l;typeof l=="string"&&l.includes("{{")&&(c=this.evaluateExpression(l,n)),c&&typeof c=="object"&&!Array.isArray(c)&&(r={...r,...c})}else typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,n):typeof l=="object"&&l!==null&&!Array.isArray(l)?r[i]=this.evaluateExpressions(l,n):r[i]=l;return r}evaluateExpressionsIfNeeded(e,n){const r={};for(const[i,l]of Object.entries(e))typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,n):r[i]=l;return r}evaluateExpression(e,n){if(!n)return e;const r=La(e);if(r===null){let c=n;if(e.includes("_global")){const f=window.G7Core?.state?.get()?._global;f&&(c={...n,_global:f})}if(e.includes("_computed")||e.includes("$computed")){const f=window.__g7ActionContext?.computedRef?.current;f&&Object.keys(f).length>0&&(c={...c,_computed:f,$computed:f})}return this.bindingEngine.resolveBindings(e,c,{skipCache:!0})}let i=r;i=i.replace(/\$args\.(\d+)/g,"$args[$1]");let l=n;if(i.includes("_global")){const d=window.G7Core?.state?.get()?._global;d&&(l={...n,_global:d})}if(i.includes("_computed")||i.includes("$computed")){const d=window.__g7ActionContext?.computedRef?.current;d&&Object.keys(d).length>0&&(l={...l,_computed:d,$computed:d})}i.includes("_global.modules")&&(j.log("[evaluateExpression] expression:",i),j.log("[evaluateExpression] dataContext._global:",l._global),j.log("[evaluateExpression] dataContext._global?.modules:",l._global?.modules));try{const c=Wn(i)?this.bindingEngine.evaluatePipeExpression(i,l,{skipCache:!0}):this.bindingEngine.evaluateExpression(i,l);return i.includes("_global.modules")&&j.log("[evaluateExpression] result:",c),typeof c=="string"&&c.startsWith("$t:")&&this.translationEngine&&this.translationContext?this.translationEngine.resolveTranslations(c,this.translationContext,n):c}catch(c){return j.error("Expression evaluation failed:",e,c),e}}setDefaultContext(e){this.defaultContext={...this.defaultContext,...e}}setGlobalStateUpdater(e){this.globalStateUpdater=e}getGlobalStateUpdater(){return this.globalStateUpdater}async dispatchAction(e,n){const r={...this.defaultContext,...n,data:{...this.defaultContext.data,...n?.data}};if(e.confirm){let i=this.resolveValue(e.confirm,r.data);if(this.translationEngine&&this.translationContext&&i.startsWith("$t:")&&(i=this.translationEngine.resolveTranslations(i,this.translationContext,r.data)),!confirm(i))return{success:!1}}try{return await this.executeAction(e,r)}catch(i){if(j.error("dispatchAction failed:",i),e.onError){const l=i instanceof jt&&i.originalError?{message:i.originalError.message,response:i.originalError.response}:{message:i instanceof Error?i.message:String(i)},c={...r,data:{...r.data,error:l}},d=Array.isArray(e.onError)?e.onError:[e.onError];for(const f of d)await this.executeAction(f,c)}return{success:!1,error:i instanceof Error?i:new Error(String(i))}}}registerHandler(e,n,r){this.customHandlers.set(e,n);const i=Yn();i?.isEnabled()&&i.trackHandlerRegistration(e,r?.category??"custom",r?.description,r?.source)}unregisterHandler(e){this.customHandlers.delete(e);const n=Yn();n?.isEnabled()&&n.trackHandlerUnregistration(e)}getRegisteredHandlers(){return Array.from(this.customHandlers.keys())}getHandler(e){return this.customHandlers.get(e)}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 n=e.target;if(n&&!("tagName"in n)){const l={type:e.type??"custom",target:{value:n.value,name:n.name??""}};return e._changedKeys&&(l._changedKeys=e._changedKeys),l}const i=n?{value:n.value,name:n.name??"",checked:n.checked??!1,type:n.type??"",tagName:n.tagName}:{};if(e.type==="scroll"&&n){const l=n;i.scrollHeight=l.scrollHeight??0,i.scrollTop=l.scrollTop??0,i.clientHeight=l.clientHeight??0,i.scrollLeft=l.scrollLeft??0,i.clientWidth=l.clientWidth??0,i.scrollWidth=l.scrollWidth??0}return{type:e.type,target:n?i:null}}executeDebouncedAction(e,n,r,i,l){const c={...r,$event:n,$args:l},d={type:n.type,target:n.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(e,c,i)(d)}handleDebouncedAction(e,n,r,i,l,c){const d=this.normalizeDebounceConfig(e.debounce),f=l||`default-${e.handler}-${Date.now()}`,h=this.extractEventData(n),m=h._changedKeys;if(m&&Array.isArray(m)&&h?.target?.value&&typeof h.target.value=="object"&&!Array.isArray(h.target.value)){const _=this.debounceAccumulatedValues.get(f);if(_){const x={..._};for(const A of m)x[A]=h.target.value[A];h.target.value=x}this.debounceAccumulatedValues.set(f,h.target.value)}const y=this.debounceTimers.get(f);y&&(clearTimeout(y),this.debounceTimers.delete(f));const v=Yn();v?.isEnabled()&&v.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"pending",params:e.params,debounce:{delay:d.delay,status:"pending",scheduledAt:Date.now()}});const S=!this.debounceTimers.has(f+"_leading");if(d.leading&&S&&(this.debounceTimers.set(f+"_leading",setTimeout(()=>{},0)),this.executeDebouncedAction(e,h,r,i,c),v?.isEnabled()&&v.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"success",params:e.params,debounce:{delay:d.delay,status:"executed",executedAt:Date.now(),mode:"leading"}})),d.trailing){const _=()=>{this.executeDebouncedAction(e,h,r,i,c),v?.isEnabled()&&v.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"success",params:e.params,debounce:{delay:d.delay,status:"executed",executedAt:Date.now(),mode:"trailing"}})},x=setTimeout(()=>{this.debounceTimers.delete(f),this.debounceTimers.delete(f+"_leading"),this.pendingDebounceFlushers.delete(f),this.debounceAccumulatedValues.delete(f),_()},d.delay);this.debounceTimers.set(f,x),this.pendingDebounceFlushers.set(f,_)}}clearDebounceTimers(e){if(e)for(const[n,r]of this.debounceTimers)n.startsWith(e+"-")&&(clearTimeout(r),this.debounceTimers.delete(n),this.pendingDebounceFlushers.delete(n),this.debounceAccumulatedValues.delete(n));else{for(const n of this.debounceTimers.values())clearTimeout(n);this.debounceTimers.clear(),this.pendingDebounceFlushers.clear(),this.debounceAccumulatedValues.clear()}}debouncedCall(e,n,r){const i=this.debounceTimers.get(e);i&&(clearTimeout(i),this.debounceTimers.delete(e));const l=setTimeout(()=>{this.debounceTimers.delete(e),this.pendingDebounceFlushers.delete(e),r()},n);this.debounceTimers.set(e,l),this.pendingDebounceFlushers.set(e,r)}flushPendingDebounceTimers(){if(this.pendingDebounceFlushers.size===0)return;const e=new Map(this.pendingDebounceFlushers);for(const[n,r]of e){const i=this.debounceTimers.get(n);i&&(clearTimeout(i),this.debounceTimers.delete(n)),this.debounceTimers.delete(n+"_leading"),this.pendingDebounceFlushers.delete(n),r()}this.globalStateUpdater&&this.globalStateUpdater({})}bindActionsToProps(e,n,r){const i={...e};if(e.actions&&Array.isArray(e.actions)){const l=new Map;for(const m of e.actions){const y=this.resolveActionRef(m),v=y.event?this.normalizeEventPropName(y.event):this.getEventHandlerName(y.type);l.has(v)||l.set(v,[]),l.get(v).push(y)}const c=e.name||e.id||"unknown",d=l.has("onDrop"),f=l.has("onDragOver"),h=l.has("onDragEnter");d&&!f&&(i.onDragOver=m=>{m.preventDefault()}),d&&!h&&(i.onDragEnter=m=>{m.preventDefault()});for(const[m,y]of l)i[m]=(...v)=>{for(const S of y){const _=v[0],x=_&&typeof _=="object"&&"preventDefault"in _;if(x&&(m==="onDragOver"||m==="onDrop")&&_.preventDefault(),x&&S.key&&"key"in _){if(this.isImeComposing(_)){j.log("Key filter skipped (IME composing):",S.key);continue}if(_.key!==S.key){j.log("Key filter not matched:",S.key,"actual:",_.key);continue}j.log("Key filter matched:",S.key)}if(S.debounce){const A=`${c}-${S.handler}-${m}`,D=_&&typeof _=="object"&&!("preventDefault"in _)&&"target"in _&&_.target!==null;let O;if(x)O=_;else if(D){const L={type:"custom",target:_.target,preventDefault:()=>{},stopPropagation:()=>{}};_._changedKeys&&(L._changedKeys=_._changedKeys),O=L}else O=new Event("custom");const k=S.event?{...n,$args:v}:n;this.handleDebouncedAction(S,O,k,r,A,v)}else if(this.flushPendingDebounceTimers(),S.event){const A={...n,$args:v},D=this.resolveEventForHandler(_,x);this.createHandler(S,A,r)(D)}else if(x)this.createHandler(S,n,r)(_);else if(_&&typeof _=="object"&&!("preventDefault"in _)&&"target"in _&&_.target!==null){const D={type:"custom",target:_.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(S,n,r)(D)}}}}return i}getEventHandlerName(e){return wy[e]||`on${e.charAt(0).toUpperCase()}${e.slice(1)}`}normalizeEventPropName(e){return wy[e]??e}resolveEventForHandler(e,n){if(n)return e;if(!(e&&typeof e=="object"&&!("preventDefault"in e)&&"target"in e&&e.target!==null))return new Event("custom");const i={type:"custom",target:e.target,preventDefault:()=>{},stopPropagation:()=>{}};return e._changedKeys&&(i._changedKeys=e._changedKeys),i}sanitizeForDevTools(e,n=5){const r=new WeakSet,i=(l,c)=>{if(l==null||typeof l=="string"||typeof l=="number"||typeof l=="boolean")return l;if(c>n)return"[Max Depth Exceeded]";if(typeof l=="function")return`[Function: ${l.name||"anonymous"}]`;if(l instanceof Element)return`[Element: ${l.tagName}${l.className?"."+l.className.split(" ").join("."):""}]`;if(l instanceof Event)return`[Event: ${l.type}]`;if(Array.isArray(l)){if(r.has(l))return"[Circular Array]";r.add(l);const d=l.slice(0,10).map(f=>i(f,c+1));return l.length>10&&d.push(`... ${l.length-10} more items`),d}if(typeof l=="object"){if(r.has(l))return"[Circular Reference]";r.add(l);const d={},f=Object.keys(l),h=f.slice(0,20);for(const m of h)try{d[m]=i(l[m],c+1)}catch{d[m]="[Error accessing property]"}return f.length>20&&(d["..."]=`${f.length-20} more properties`),d}return String(l)};return i(e,0)}};M(cn,"loadedScripts",new Set),M(cn,"loadingScripts",new Map),M(cn,"PROTOTYPE_PATH_SEGMENTS",["__proto__","prototype","constructor"]);let jo=cn,_c=null;function Cy(s){return _c||(_c=new jo(s)),_c}function l_(s){_c=s}const Ey=pt("TransitionManager");class c_{constructor(){M(this,"isPending",!1);M(this,"subscribers",new Set)}setPending(e){this.isPending!==e&&(Ey.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(){Ey.log("notifySubscribers:",{isPending:this.isPending,subscriberCount:this.subscribers.size}),this.subscribers.forEach(e=>{e(this.isPending)})}clearSubscribers(){this.subscribers.clear()}}const Gr=new c_,Ac=pt("TransitionContext"),_y=I.createContext({isTransitioning:!1}),Mf=({children:s})=>{const[e,n]=I.useState(()=>{const i=Gr.getIsPending();return Ac.log("Initial state:",i),i});I.useEffect(()=>{Ac.log("Subscribing to TransitionManager");const i=Gr.subscribe(l=>{Ac.log("Received isPending update:",l),n(l)});return()=>{Ac.log("Unsubscribing from TransitionManager"),i()}},[]);const r=I.useMemo(()=>({isTransitioning:e}),[e]);return yt.jsx(_y.Provider,{value:r,children:s})},Ay=()=>I.useContext(_y),xc="__g7LocalInitTracking";function Nf(){const s=globalThis;return s[xc]||(s[xc]={hash:"",timestamp:void 0,consumed:void 0}),s[xc]}function u_(){const s=globalThis;s[xc]={hash:"",timestamp:void 0,consumed:void 0}}function d_(s){Nf().consumed=s}function f_(s){return Nf().consumed===s}function h_(s){return s.globalTrackedKey!==s.trackingKey?"apply":s.instanceHandledKey===s.trackingKey?"skip":"prune"}function p_(s,e){return typeof s=="number"&&typeof e=="number"?Math.max(s,e):e??s}function g_(s,e){if(e===void 0)return s;if(!(s!==null&&typeof s=="object"&&e!==null&&typeof e=="object"&&!f_(s)))return e;const{_forceLocalInit:r,...i}=s,{_forceLocalInit:l,...c}=e,d={...i,...c},f=p_(r,l);return f!==void 0&&(d._forceLocalInit=f),d}function m_(s){return s<768?"mobile":s<1024?"tablet":"desktop"}function xy(s){const e=m_(s);return{width:s,isMobile:e==="mobile",isTablet:e==="tablet",isDesktop:e==="desktop",matchedPreset:e}}const If=I.createContext(xy(1024)),Tc=({children:s,overrideWidth:e})=>{const[n,r]=I.useState(()=>Ci.getWidth());I.useEffect(()=>{const c=Ci.subscribe(d=>{r(d)});return()=>{c()}},[]);const i=e??n,l=I.useMemo(()=>xy(i),[i]);return yt.jsx(If.Provider,{value:l,children:s})},jf=()=>I.useContext(If);window.G7Core?.createLogger?.("Core:State");function y_(s,e,n,r){const{syncOnControlledChange:i=!0,isEqual:l}=r??{},c=s!==void 0;I.useRef(c);const[d,f]=I.useState(s!==void 0?s:e),h=d,m=I.useRef(s),y=I.useRef(!1);I.useEffect(()=>{if(y.current){m.current=s;return}i&&c&&s!==m.current&&(l?!l(d,s):d!==s)&&f(s),m.current=s},[s,c,i,l,d]);const v=I.useCallback(S=>{const _=typeof S=="function"?S(h):S;(l?l(h,_):h===_)||(y.current=!0,f(_),n?.(_),requestAnimationFrame(()=>{y.current=!1}))},[h,c,n,l]);return[h,v]}function b_(s,e){return s===e?!0:s.length!==e.length?!1:s.every((n,r)=>n===e[r])}function Ty(s,e){if(s===e)return!0;const n=Object.keys(s),r=Object.keys(e);return n.length!==r.length?!1:n.every(i=>s[i]===e[i])}const ky=I.createContext({}),v_=({children:s,value:e})=>yt.jsx(ky.Provider,{value:e,children:s}),S_=()=>I.useContext(ky),w_=(s,e)=>{if(!s)return;const n=e.split(".");let r=s;for(const i of n){if(r==null)return;r=r[i]}return r},Ry=(s,e,n)=>{const r=e.split(".");if(r.length===1)return{...s,[r[0]]:n};const i={...s};let l=i;for(let c=0;c{vs.warn("IsolatedStateContext not available: setState called outside IsolatedStateProvider")},getState:()=>{},mergeState:()=>{vs.warn("IsolatedStateContext not available: mergeState called outside IsolatedStateProvider")},stateRef:{current:{}},scopeId:""},Dy=I.createContext(C_);let E_=0;function __(){return`isolated-${++E_}-${Date.now().toString(36)}`}function Oy(s,e){if(e==null)return s;if(typeof e!="object"||Array.isArray(e))return e;const n={...s};for(const r of Object.keys(e)){const i=e[r],l=s?.[r];i!==null&&typeof i=="object"&&!Array.isArray(i)&&l!==null&&typeof l=="object"&&!Array.isArray(l)?n[r]=Oy(l,i):n[r]=i}return n}function A_(s,e){return e?e.split(".").reduce((n,r)=>n?.[r],s):s}function x_(s,e,n){const r=e.split("."),i={...s};let l=i;for(let c=0;c{const i=I.useRef(e||__()).current,[l,c]=I.useState(s),d=I.useRef(l);d.current=l;const f=I.useCallback(S=>A_(d.current,S),[]),h=I.useCallback((S,_)=>{c(x=>{const A=x_(x,S,_);return vs.log(`[${i}] setState: ${S} =`,_),A})},[i]),m=I.useCallback((S,_="deep")=>{c(x=>{let A;return _==="replace"?A=S:_==="shallow"?A={...x,...S}:A=Oy(x,S),vs.log(`[${i}] mergeState (${_}):`,S),A})},[i]),y=I.useMemo(()=>({state:l,setState:h,getState:f,mergeState:m,stateRef:d,scopeId:i}),[l,h,f,m,i]),v=I.useMemo(()=>({state:d.current,setState:h,getState:f,mergeState:m}),[h,f,m]);return I.useEffect(()=>{const S=window.G7Core,_=window.__g7IsolatedStates||{};return window.__g7IsolatedStates||(window.__g7IsolatedStates=_),_[i]=v,S&&(S._isolatedStates||(S._isolatedStates={}),S._isolatedStates[i]=l),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:created",{id:i,state:l}),vs.log(`[${i}] IsolatedStateProvider mounted with initial state:`,l),()=>{delete _[i],S?._isolatedStates&&delete S._isolatedStates[i],S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:destroyed",{id:i}),vs.log(`[${i}] IsolatedStateProvider unmounted`)}},[i,v]),I.useEffect(()=>{const S=window.G7Core,_=window.__g7IsolatedStates;_?.[i]&&(_[i].state=l),S?._isolatedStates&&(S._isolatedStates[i]=l),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:updated",{id:i,state:l})},[l,i]),yt.jsx(Dy.Provider,{value:y,children:n})},k_=()=>{const s=I.useContext(Dy);return s.scopeId?s:null};var ja=Pg();function R_(){for(var s=arguments.length,e=new Array(s),n=0;nr=>{e.forEach(i=>i(r))},e)}const kc=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function Ss(s){const e=Object.prototype.toString.call(s);return e==="[object Window]"||e==="[object global]"}function Hf(s){return"nodeType"in s}function Hn(s){var e,n;return s?Ss(s)?s:Hf(s)&&(e=(n=s.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function zf(s){const{Document:e}=Hn(s);return s instanceof e}function Ho(s){return Ss(s)?!1:s instanceof Hn(s).HTMLElement}function Ly(s){return s instanceof Hn(s).SVGElement}function ws(s){return s?Ss(s)?s.document:Hf(s)?zf(s)?s:Ho(s)||Ly(s)?s.ownerDocument:document:document:document}const Fr=kc?I.useLayoutEffect:I.useEffect;function Pf(s){const e=I.useRef(s);return Fr(()=>{e.current=s}),I.useCallback(function(){for(var n=arguments.length,r=new Array(n),i=0;i{s.current=setInterval(r,i)},[]),n=I.useCallback(()=>{s.current!==null&&(clearInterval(s.current),s.current=null)},[]);return[e,n]}function zo(s,e){e===void 0&&(e=[s]);const n=I.useRef(s);return Fr(()=>{n.current!==s&&(n.current=s)},e),n}function Po(s,e){const n=I.useRef();return I.useMemo(()=>{const r=s(n.current);return n.current=r,r},[...e])}function Rc(s){const e=Pf(s),n=I.useRef(null),r=I.useCallback(i=>{i!==n.current&&e?.(i,n.current),n.current=i},[]);return[n,r]}function Uf(s){const e=I.useRef();return I.useEffect(()=>{e.current=s},[s]),e.current}let Bf={};function Uo(s,e){return I.useMemo(()=>{if(e)return e;const n=Bf[s]==null?0:Bf[s]+1;return Bf[s]=n,s+"-"+n},[s,e])}function $y(s){return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i{const d=Object.entries(c);for(const[f,h]of d){const m=l[f];m!=null&&(l[f]=m+s*h)}return l},{...e})}}const Cs=$y(1),Bo=$y(-1);function O_(s){return"clientX"in s&&"clientY"in s}function qf(s){if(!s)return!1;const{KeyboardEvent:e}=Hn(s.target);return e&&s instanceof e}function L_(s){if(!s)return!1;const{TouchEvent:e}=Hn(s.target);return e&&s instanceof e}function Gf(s){if(L_(s)){if(s.touches&&s.touches.length){const{clientX:e,clientY:n}=s.touches[0];return{x:e,y:n}}else if(s.changedTouches&&s.changedTouches.length){const{clientX:e,clientY:n}=s.changedTouches[0];return{x:e,y:n}}}return O_(s)?{x:s.clientX,y:s.clientY}:null}const qo=Object.freeze({Translate:{toString(s){if(!s)return;const{x:e,y:n}=s;return"translate3d("+(e?Math.round(e):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(s){if(!s)return;const{scaleX:e,scaleY:n}=s;return"scaleX("+e+") scaleY("+n+")"}},Transform:{toString(s){if(s)return[qo.Translate.toString(s),qo.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:e,duration:n,easing:r}=s;return e+" "+n+"ms "+r}}}),My="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function $_(s){return s.matches(My)?s:s.querySelector(My)}const M_={display:"none"};function N_(s){let{id:e,value:n}=s;return Xe.createElement("div",{id:e,style:M_},n)}function I_(s){let{id:e,announcement:n,ariaLiveType:r="assertive"}=s;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 Xe.createElement("div",{id:e,style:i,role:"status","aria-live":r,"aria-atomic":!0},n)}function j_(){const[s,e]=I.useState("");return{announce:I.useCallback(r=>{r!=null&&e(r)},[]),announcement:s}}const Ny=I.createContext(null);function H_(s){const e=I.useContext(Ny);I.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(s)},[s,e])}function z_(){const[s]=I.useState(()=>new Set),e=I.useCallback(r=>(s.add(r),()=>s.delete(r)),[s]);return[I.useCallback(r=>{let{type:i,event:l}=r;s.forEach(c=>{var d;return(d=c[i])==null?void 0:d.call(c,l)})},[s]),e]}const P_={draggable:` + `,i.onmouseenter=()=>{i.style.backgroundColor="rgba(0, 0, 0, 0.2)"},i.onmouseleave=()=>{i.style.backgroundColor="rgba(0, 0, 0, 0.1)"};const l=()=>{n.parentNode&&n.parentNode.removeChild(n)};i.onclick=l;const c=d=>{this.isImeComposing(d)||d.key==="Escape"&&(l(),document.removeEventListener("keydown",c))};return document.addEventListener("keydown",c),n.onclick=d=>{d.target===n&&l()},r.appendChild(i),n.appendChild(r),document.body.appendChild(n),{overlay:n,layer:r,closeLayer:l}}static isPrototypePathSegment(e){return rn.PROTOTYPE_PATH_SEGMENTS.includes(e)}getNestedProperty(e,n){return n.split(".").reduce((r,i)=>{if(!rn.isPrototypePathSegment(i))return r&&r[i]!==void 0?r[i]:void 0},e)}assertCallableExternalConstructor(e,n,r){if(typeof window>"u")return;if([window.Function,window.eval,window.setTimeout,window.setInterval].some(l=>l!==void 0&&l===e))throw N.error(`callExternal: blocked arbitrary code execution seam: ${n}`),new Tt(`Blocked constructor (arbitrary code execution): ${n}`,r)}async handleSaveToLocalStorage(e,n){const{key:r,value:i}=e;if(!r)return N.error("saveToLocalStorage: key parameter is required"),!1;try{const l=typeof i=="string"?i:JSON.stringify(i);return localStorage.setItem(r,l),N.log(`saveToLocalStorage: saved ${r}`,i),!0}catch(l){return N.error("saveToLocalStorage: failed to save",{key:r,error:l}),!1}}async handleLoadFromLocalStorage(e,n){const{key:r,target:i,stateKey:l,defaultValue:c}=e;if(!r)return N.error("loadFromLocalStorage: key parameter is required"),c;try{const d=localStorage.getItem(r);if(d===null)return N.log(`loadFromLocalStorage: no value found for ${r}, using default`),l&&n.setState&&this.writeLocalState(n,{[l]:c}),c;let f;try{f=JSON.parse(d)}catch{f=d}return N.log(`loadFromLocalStorage: loaded ${r}`,f),l&&n.setState&&this.writeLocalState(n,{[l]:f}),f}catch(d){return N.error("loadFromLocalStorage: failed to load",{key:r,error:d}),c}}writeLocalState(e,n,r,i){const l=r||e.setState;if(!l)return;if(typeof n=="function"){N.warn("[writeLocalState] 함수형 업데이터는 저장소 B 미러 대상이 아닙니다 (payload 추출 불가). 저장소 A 만 갱신합니다."),l(n);return}if(i?.scope==="parent"||i?.scope==="root"){l(n);return}if(this.localMirrorDepth>0||l?.__g7CanonicalWriter){l(n);return}const c=n&&typeof n=="object"?n:{},d=c.__mergeMode;if(d==="replace"){l(n);return}const{__mergeMode:f,__setStateId:p,...m}=c;if("errors"in m||!rn.isMirrorSafePayload(m)){l(n);return}const y=window;if((y.__g7LayoutContextStack||[]).length>0){l(n);return}const C=y.G7Core?.state?.setLocal;if(!y.__templateApp||typeof C!="function"){l(n);return}const S=this.deepMergeWithState(m,{});this.localMirrorDepth++;try{C(S,{render:!1,merge:d??"deep"}),y.__g7ActionContext?.setState!==l&&l(n),d&&(y.__g7ForcedLocalFields={...y.__g7ForcedLocalFields||{},...S})}finally{this.localMirrorDepth--}}static isMirrorSafePayload(e,n=0){if(e===null||typeof e!="object"||n>=8)return!0;if(Array.isArray(e))return e.every(i=>rn.isMirrorSafePayload(i,n+1));const r=Object.getPrototypeOf(e);return r!==Object.prototype&&r!==null?!1:Object.values(e).every(i=>rn.isMirrorSafePayload(i,n+1))}makeLocalSetStateProxy(e){const n=e.setState;if(!n)return;if(n.__g7CanonicalWriter)return n;const r=i=>{this.writeLocalState(e,i,n)};return r.__g7CanonicalWriter=!0,r}async handleCustomAction(e,n){const r=this.customHandlers.get(e.handler);if(!r){if(this.previewMode){N.warn(`[Preview] Unknown action handler "${e.handler}" — skipped (preview mode)`);return}const c=new Tt(`Unknown action handler: ${e.handler}`,e);throw c.unknownHandler=!0,c}const i=this.makeLocalSetStateProxy(n),l=i&&i!==n.setState?{...n,setState:i}:n;return await r(e,l)}resolveParams(e,n){if(!e)return{};const r={};for(const[i,l]of Object.entries(e))i.includes("{{")&&N.warn(`[resolveParams] setState params의 키에 표현식이 포함되어 있습니다: "${i}". 키는 해석되지 않습니다. 배열 항목 수정은 .map()/.filter() 패턴을 사용하세요.`),typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,n):typeof l=="string"?r[i]=l:Array.isArray(l)?r[i]=l.map(c=>typeof c=="string"&&c.includes("{{")?this.evaluateExpression(c,n):c):typeof l=="object"&&l!==null&&!Array.isArray(l)&&Object.getPrototypeOf(l)!==Object.prototype&&Object.getPrototypeOf(l)!==null?r[i]=l:typeof l=="object"&&l!==null?r[i]=this.resolveParams(l,n):r[i]=l;return r}resolveValue(e,n){return n?this.bindingEngine.resolveBindings(e,n,{skipCache:!0}):e}evaluateExpressions(e,n){let r={};for(const[i,l]of Object.entries(e))if(i==="..."){let c=l;typeof l=="string"&&l.includes("{{")&&(c=this.evaluateExpression(l,n)),c&&typeof c=="object"&&!Array.isArray(c)&&(r={...r,...c})}else typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,n):typeof l=="object"&&l!==null&&!Array.isArray(l)?r[i]=this.evaluateExpressions(l,n):r[i]=l;return r}evaluateExpressionsIfNeeded(e,n){const r={};for(const[i,l]of Object.entries(e))typeof l=="string"&&l.includes("{{")?r[i]=this.evaluateExpression(l,n):r[i]=l;return r}evaluateExpression(e,n){if(!n)return e;const r=Ma(e);if(r===null){let c=n;if(e.includes("_global")){const f=window.G7Core?.state?.get()?._global;f&&(c={...n,_global:f})}if(e.includes("_computed")||e.includes("$computed")){const f=window.__g7ActionContext?.computedRef?.current;f&&Object.keys(f).length>0&&(c={...c,_computed:f,$computed:f})}return this.bindingEngine.resolveBindings(e,c,{skipCache:!0})}let i=r;i=i.replace(/\$args\.(\d+)/g,"$args[$1]");let l=n;if(i.includes("_global")){const d=window.G7Core?.state?.get()?._global;d&&(l={...n,_global:d})}if(i.includes("_computed")||i.includes("$computed")){const d=window.__g7ActionContext?.computedRef?.current;d&&Object.keys(d).length>0&&(l={...l,_computed:d,$computed:d})}i.includes("_global.modules")&&(N.log("[evaluateExpression] expression:",i),N.log("[evaluateExpression] dataContext._global:",l._global),N.log("[evaluateExpression] dataContext._global?.modules:",l._global?.modules));try{const c=On(i)?this.bindingEngine.evaluatePipeExpression(i,l,{skipCache:!0}):this.bindingEngine.evaluateExpression(i,l);return i.includes("_global.modules")&&N.log("[evaluateExpression] result:",c),typeof c=="string"&&c.startsWith("$t:")&&this.translationEngine&&this.translationContext?this.translationEngine.resolveTranslations(c,this.translationContext,n):c}catch(c){return N.error("Expression evaluation failed:",e,c),e}}setDefaultContext(e){this.defaultContext={...this.defaultContext,...e}}setGlobalStateUpdater(e){this.globalStateUpdater=e}getGlobalStateUpdater(){return this.globalStateUpdater}async dispatchAction(e,n){const r={...this.defaultContext,...n,data:{...this.defaultContext.data,...n?.data}};if(e.confirm){let i=this.resolveValue(e.confirm,r.data);if(this.translationEngine&&this.translationContext&&i.startsWith("$t:")&&(i=this.translationEngine.resolveTranslations(i,this.translationContext,r.data)),!confirm(i))return{success:!1}}try{return await this.executeAction(e,r)}catch(i){if(N.error("dispatchAction failed:",i),e.onError){const l=i instanceof Tt&&i.originalError?{message:i.originalError.message,response:i.originalError.response}:{message:i instanceof Error?i.message:String(i)},c={...r,data:{...r.data,error:l}},d=Array.isArray(e.onError)?e.onError:[e.onError];for(const f of d)await this.executeAction(f,c)}return{success:!1,error:i instanceof Error?i:new Error(String(i))}}}registerHandler(e,n,r){this.customHandlers.set(e,n);const i=Xn();i?.isEnabled()&&i.trackHandlerRegistration(e,r?.category??"custom",r?.description,r?.source)}unregisterHandler(e){this.customHandlers.delete(e);const n=Xn();n?.isEnabled()&&n.trackHandlerUnregistration(e)}getRegisteredHandlers(){return Array.from(this.customHandlers.keys())}getHandler(e){return this.customHandlers.get(e)}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 n=e.target;if(n&&!("tagName"in n)){const l={type:e.type??"custom",target:{value:n.value,name:n.name??""}};return e._changedKeys&&(l._changedKeys=e._changedKeys),l}const i=n?{value:n.value,name:n.name??"",checked:n.checked??!1,type:n.type??"",tagName:n.tagName}:{};if(e.type==="scroll"&&n){const l=n;i.scrollHeight=l.scrollHeight??0,i.scrollTop=l.scrollTop??0,i.clientHeight=l.clientHeight??0,i.scrollLeft=l.scrollLeft??0,i.clientWidth=l.clientWidth??0,i.scrollWidth=l.scrollWidth??0}return{type:e.type,target:n?i:null}}executeDebouncedAction(e,n,r,i,l){const c={...r,$event:n,$args:l},d={type:n.type,target:n.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(e,c,i)(d)}handleDebouncedAction(e,n,r,i,l,c){const d=this.normalizeDebounceConfig(e.debounce),f=l||`default-${e.handler}-${Date.now()}`,p=this.extractEventData(n),m=p._changedKeys;if(m&&Array.isArray(m)&&p?.target?.value&&typeof p.target.value=="object"&&!Array.isArray(p.target.value)){const v=this.debounceAccumulatedValues.get(f);if(v){const x={...v};for(const w of m)x[w]=p.target.value[w];p.target.value=x}this.debounceAccumulatedValues.set(f,p.target.value)}const y=this.debounceTimers.get(f);y&&(clearTimeout(y),this.debounceTimers.delete(f));const C=Xn();C?.isEnabled()&&C.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"pending",params:e.params,debounce:{delay:d.delay,status:"pending",scheduledAt:Date.now()}});const S=!this.debounceTimers.has(f+"_leading");if(d.leading&&S&&(this.debounceTimers.set(f+"_leading",setTimeout(()=>{},0)),this.executeDebouncedAction(e,p,r,i,c),C?.isEnabled()&&C.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"success",params:e.params,debounce:{delay:d.delay,status:"executed",executedAt:Date.now(),mode:"leading"}})),d.trailing){const v=()=>{this.executeDebouncedAction(e,p,r,i,c),C?.isEnabled()&&C.trackAction({handler:typeof e.handler=="string"?e.handler:String(e.handler),type:e.type,status:"success",params:e.params,debounce:{delay:d.delay,status:"executed",executedAt:Date.now(),mode:"trailing"}})},x=setTimeout(()=>{this.debounceTimers.delete(f),this.debounceTimers.delete(f+"_leading"),this.pendingDebounceFlushers.delete(f),this.debounceAccumulatedValues.delete(f),v()},d.delay);this.debounceTimers.set(f,x),this.pendingDebounceFlushers.set(f,v)}}clearDebounceTimers(e){if(e)for(const[n,r]of this.debounceTimers)n.startsWith(e+"-")&&(clearTimeout(r),this.debounceTimers.delete(n),this.pendingDebounceFlushers.delete(n),this.debounceAccumulatedValues.delete(n));else{for(const n of this.debounceTimers.values())clearTimeout(n);this.debounceTimers.clear(),this.pendingDebounceFlushers.clear(),this.debounceAccumulatedValues.clear()}}debouncedCall(e,n,r){const i=this.debounceTimers.get(e);i&&(clearTimeout(i),this.debounceTimers.delete(e));const l=setTimeout(()=>{this.debounceTimers.delete(e),this.pendingDebounceFlushers.delete(e),r()},n);this.debounceTimers.set(e,l),this.pendingDebounceFlushers.set(e,r)}flushPendingDebounceTimers(){if(this.pendingDebounceFlushers.size===0)return;const e=new Map(this.pendingDebounceFlushers);for(const[n,r]of e){const i=this.debounceTimers.get(n);i&&(clearTimeout(i),this.debounceTimers.delete(n)),this.debounceTimers.delete(n+"_leading"),this.pendingDebounceFlushers.delete(n),r()}this.globalStateUpdater&&this.globalStateUpdater({})}bindActionsToProps(e,n,r){const i={...e};if(e.actions&&Array.isArray(e.actions)){const l=new Map;for(const m of e.actions){const y=this.resolveActionRef(m),C=y.event?this.normalizeEventPropName(y.event):this.getEventHandlerName(y.type);l.has(C)||l.set(C,[]),l.get(C).push(y)}const c=e.name||e.id||"unknown",d=l.has("onDrop"),f=l.has("onDragOver"),p=l.has("onDragEnter");d&&!f&&(i.onDragOver=m=>{m.preventDefault()}),d&&!p&&(i.onDragEnter=m=>{m.preventDefault()});for(const[m,y]of l)i[m]=(...C)=>{for(const S of y){const v=C[0],x=v&&typeof v=="object"&&"preventDefault"in v;if(x&&(m==="onDragOver"||m==="onDrop")&&v.preventDefault(),x&&S.key&&"key"in v){if(this.isImeComposing(v)){N.log("Key filter skipped (IME composing):",S.key);continue}if(v.key!==S.key){N.log("Key filter not matched:",S.key,"actual:",v.key);continue}N.log("Key filter matched:",S.key)}if(S.debounce){const w=`${c}-${S.handler}-${m}`,R=v&&typeof v=="object"&&!("preventDefault"in v)&&"target"in v&&v.target!==null;let L;if(x)L=v;else if(R){const j={type:"custom",target:v.target,preventDefault:()=>{},stopPropagation:()=>{}};v._changedKeys&&(j._changedKeys=v._changedKeys),L=j}else L=new Event("custom");const O=S.event?{...n,$args:C}:n;this.handleDebouncedAction(S,L,O,r,w,C)}else if(this.flushPendingDebounceTimers(),S.event){const w={...n,$args:C},R=this.resolveEventForHandler(v,x);this.createHandler(S,w,r)(R)}else if(x)this.createHandler(S,n,r)(v);else if(v&&typeof v=="object"&&!("preventDefault"in v)&&"target"in v&&v.target!==null){const R={type:"custom",target:v.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(S,n,r)(R)}}}}return i}getEventHandlerName(e){return Km[e]||`on${e.charAt(0).toUpperCase()}${e.slice(1)}`}normalizeEventPropName(e){return Km[e]??e}resolveEventForHandler(e,n){if(n)return e;if(!(e&&typeof e=="object"&&!("preventDefault"in e)&&"target"in e&&e.target!==null))return new Event("custom");const i={type:"custom",target:e.target,preventDefault:()=>{},stopPropagation:()=>{}};return e._changedKeys&&(i._changedKeys=e._changedKeys),i}sanitizeForDevTools(e,n=5){const r=new WeakSet,i=(l,c)=>{if(l==null||typeof l=="string"||typeof l=="number"||typeof l=="boolean")return l;if(c>n)return"[Max Depth Exceeded]";if(typeof l=="function")return`[Function: ${l.name||"anonymous"}]`;if(l instanceof Element)return`[Element: ${l.tagName}${l.className?"."+l.className.split(" ").join("."):""}]`;if(l instanceof Event)return`[Event: ${l.type}]`;if(Array.isArray(l)){if(r.has(l))return"[Circular Array]";r.add(l);const d=l.slice(0,10).map(f=>i(f,c+1));return l.length>10&&d.push(`... ${l.length-10} more items`),d}if(typeof l=="object"){if(r.has(l))return"[Circular Reference]";r.add(l);const d={},f=Object.keys(l),p=f.slice(0,20);for(const m of p)try{d[m]=i(l[m],c+1)}catch{d[m]="[Error accessing property]"}return f.length>20&&(d["..."]=`${f.length-20} more properties`),d}return String(l)};return i(e,0)}};$(rn,"loadedScripts",new Set),$(rn,"loadingScripts",new Map),$(rn,"PROTOTYPE_PATH_SEGMENTS",["__proto__","prototype","constructor"]);let Lo=rn,xc=null;function Wm(s){return xc||(xc=new Lo(s)),xc}function QC(s){xc=s}const Ym=dt("TransitionManager");class ZC{constructor(){$(this,"isPending",!1);$(this,"subscribers",new Set)}setPending(e){this.isPending!==e&&(Ym.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(){Ym.log("notifySubscribers:",{isPending:this.isPending,subscriberCount:this.subscribers.size}),this.subscribers.forEach(e=>{e(this.isPending)})}clearSubscribers(){this.subscribers.clear()}}const Gr=new ZC,Tc=dt("TransitionContext"),Xm=M.createContext({isTransitioning:!1}),Sf=({children:s})=>{const[e,n]=M.useState(()=>{const i=Gr.getIsPending();return Tc.log("Initial state:",i),i});M.useEffect(()=>{Tc.log("Subscribing to TransitionManager");const i=Gr.subscribe(l=>{Tc.log("Received isPending update:",l),n(l)});return()=>{Tc.log("Unsubscribing from TransitionManager"),i()}},[]);const r=M.useMemo(()=>({isTransitioning:e}),[e]);return ft.jsx(Xm.Provider,{value:r,children:s})},Jm=()=>M.useContext(Xm),kc="__g7LocalInitTracking";function wf(){const s=globalThis;return s[kc]||(s[kc]={hash:"",timestamp:void 0,consumed:void 0}),s[kc]}function eE(){const s=globalThis;s[kc]={hash:"",timestamp:void 0,consumed:void 0}}function tE(s){wf().consumed=s}function nE(s){return wf().consumed===s}function rE(s){return s.globalTrackedKey!==s.trackingKey?"apply":s.instanceHandledKey===s.trackingKey?"skip":"prune"}function aE(s,e){return typeof s=="number"&&typeof e=="number"?Math.max(s,e):e??s}function iE(s,e){if(e===void 0)return s;if(!(s!==null&&typeof s=="object"&&e!==null&&typeof e=="object"&&!nE(s)))return e;const{_forceLocalInit:r,...i}=s,{_forceLocalInit:l,...c}=e,d={...i,...c},f=aE(r,l);return f!==void 0&&(d._forceLocalInit=f),d}function sE(s){return s<768?"mobile":s<1024?"tablet":"desktop"}function Qm(s){const e=sE(s);return{width:s,isMobile:e==="mobile",isTablet:e==="tablet",isDesktop:e==="desktop",matchedPreset:e}}const Cf=M.createContext(Qm(1024)),Rc=({children:s,overrideWidth:e})=>{const[n,r]=M.useState(()=>_i.getWidth());M.useEffect(()=>{const c=_i.subscribe(d=>{r(d)});return()=>{c()}},[]);const i=e??n,l=M.useMemo(()=>Qm(i),[i]);return ft.jsx(Cf.Provider,{value:l,children:s})},Ef=()=>M.useContext(Cf);window.G7Core?.createLogger?.("Core:State");function oE(s,e,n,r){const{syncOnControlledChange:i=!0,isEqual:l}=r??{},c=s!==void 0;M.useRef(c);const[d,f]=M.useState(s!==void 0?s:e),p=d,m=M.useRef(s),y=M.useRef(!1);M.useEffect(()=>{if(y.current){m.current=s;return}i&&c&&s!==m.current&&(l?!l(d,s):d!==s)&&f(s),m.current=s},[s,c,i,l,d]);const C=M.useCallback(S=>{const v=typeof S=="function"?S(p):S;(l?l(p,v):p===v)||(y.current=!0,f(v),n?.(v),requestAnimationFrame(()=>{y.current=!1}))},[p,c,n,l]);return[p,C]}function lE(s,e){return s===e?!0:s.length!==e.length?!1:s.every((n,r)=>n===e[r])}function Zm(s,e){if(s===e)return!0;const n=Object.keys(s),r=Object.keys(e);return n.length!==r.length?!1:n.every(i=>s[i]===e[i])}const ey=M.createContext({}),cE=({children:s,value:e})=>ft.jsx(ey.Provider,{value:e,children:s}),uE=()=>M.useContext(ey),dE=(s,e)=>{if(!s)return;const n=e.split(".");let r=s;for(const i of n){if(r==null)return;r=r[i]}return r},ty=(s,e,n)=>{const r=e.split(".");if(r.length===1)return{...s,[r[0]]:n};const i={...s};let l=i;for(let c=0;c{hs.warn("IsolatedStateContext not available: setState called outside IsolatedStateProvider")},getState:()=>{},mergeState:()=>{hs.warn("IsolatedStateContext not available: mergeState called outside IsolatedStateProvider")},stateRef:{current:{}},scopeId:""},ny=M.createContext(fE);let hE=0;function pE(){return`isolated-${++hE}-${Date.now().toString(36)}`}function ry(s,e){if(e==null)return s;if(typeof e!="object"||Array.isArray(e))return e;const n={...s};for(const r of Object.keys(e)){const i=e[r],l=s?.[r];i!==null&&typeof i=="object"&&!Array.isArray(i)&&l!==null&&typeof l=="object"&&!Array.isArray(l)?n[r]=ry(l,i):n[r]=i}return n}function gE(s,e){return e?e.split(".").reduce((n,r)=>n?.[r],s):s}function mE(s,e,n){const r=e.split("."),i={...s};let l=i;for(let c=0;c{const i=M.useRef(e||pE()).current,[l,c]=M.useState(s),d=M.useRef(l);d.current=l;const f=M.useCallback(S=>gE(d.current,S),[]),p=M.useCallback((S,v)=>{c(x=>{const w=mE(x,S,v);return hs.log(`[${i}] setState: ${S} =`,v),w})},[i]),m=M.useCallback((S,v="deep")=>{c(x=>{let w;return v==="replace"?w=S:v==="shallow"?w={...x,...S}:w=ry(x,S),hs.log(`[${i}] mergeState (${v}):`,S),w})},[i]),y=M.useMemo(()=>({state:l,setState:p,getState:f,mergeState:m,stateRef:d,scopeId:i}),[l,p,f,m,i]),C=M.useMemo(()=>({state:d.current,setState:p,getState:f,mergeState:m}),[p,f,m]);return M.useEffect(()=>{const S=window.G7Core,v=window.__g7IsolatedStates||{};return window.__g7IsolatedStates||(window.__g7IsolatedStates=v),v[i]=C,S&&(S._isolatedStates||(S._isolatedStates={}),S._isolatedStates[i]=l),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:created",{id:i,state:l}),hs.log(`[${i}] IsolatedStateProvider mounted with initial state:`,l),()=>{delete v[i],S?._isolatedStates&&delete S._isolatedStates[i],S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:destroyed",{id:i}),hs.log(`[${i}] IsolatedStateProvider unmounted`)}},[i,C]),M.useEffect(()=>{const S=window.G7Core,v=window.__g7IsolatedStates;v?.[i]&&(v[i].state=l),S?._isolatedStates&&(S._isolatedStates[i]=l),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:updated",{id:i,state:l})},[l,i]),ft.jsx(ny.Provider,{value:y,children:n})},bE=()=>{const s=M.useContext(ny);return s.scopeId?s:null};var za=wg();function vE(){for(var s=arguments.length,e=new Array(s),n=0;nr=>{e.forEach(i=>i(r))},e)}const Dc=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function ps(s){const e=Object.prototype.toString.call(s);return e==="[object Window]"||e==="[object global]"}function _f(s){return"nodeType"in s}function Mn(s){var e,n;return s?ps(s)?s:_f(s)&&(e=(n=s.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function Af(s){const{Document:e}=Mn(s);return s instanceof e}function $o(s){return ps(s)?!1:s instanceof Mn(s).HTMLElement}function ay(s){return s instanceof Mn(s).SVGElement}function gs(s){return s?ps(s)?s.document:_f(s)?Af(s)?s:$o(s)||ay(s)?s.ownerDocument:document:document:document}const Fr=Dc?M.useLayoutEffect:M.useEffect;function xf(s){const e=M.useRef(s);return Fr(()=>{e.current=s}),M.useCallback(function(){for(var n=arguments.length,r=new Array(n),i=0;i{s.current=setInterval(r,i)},[]),n=M.useCallback(()=>{s.current!==null&&(clearInterval(s.current),s.current=null)},[]);return[e,n]}function Mo(s,e){e===void 0&&(e=[s]);const n=M.useRef(s);return Fr(()=>{n.current!==s&&(n.current=s)},e),n}function No(s,e){const n=M.useRef();return M.useMemo(()=>{const r=s(n.current);return n.current=r,r},[...e])}function Oc(s){const e=xf(s),n=M.useRef(null),r=M.useCallback(i=>{i!==n.current&&e?.(i,n.current),n.current=i},[]);return[n,r]}function Tf(s){const e=M.useRef();return M.useEffect(()=>{e.current=s},[s]),e.current}let kf={};function Io(s,e){return M.useMemo(()=>{if(e)return e;const n=kf[s]==null?0:kf[s]+1;return kf[s]=n,s+"-"+n},[s,e])}function iy(s){return function(e){for(var n=arguments.length,r=new Array(n>1?n-1:0),i=1;i{const d=Object.entries(c);for(const[f,p]of d){const m=l[f];m!=null&&(l[f]=m+s*p)}return l},{...e})}}const ms=iy(1),jo=iy(-1);function wE(s){return"clientX"in s&&"clientY"in s}function Rf(s){if(!s)return!1;const{KeyboardEvent:e}=Mn(s.target);return e&&s instanceof e}function CE(s){if(!s)return!1;const{TouchEvent:e}=Mn(s.target);return e&&s instanceof e}function Df(s){if(CE(s)){if(s.touches&&s.touches.length){const{clientX:e,clientY:n}=s.touches[0];return{x:e,y:n}}else if(s.changedTouches&&s.changedTouches.length){const{clientX:e,clientY:n}=s.changedTouches[0];return{x:e,y:n}}}return wE(s)?{x:s.clientX,y:s.clientY}:null}const zo=Object.freeze({Translate:{toString(s){if(!s)return;const{x:e,y:n}=s;return"translate3d("+(e?Math.round(e):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(s){if(!s)return;const{scaleX:e,scaleY:n}=s;return"scaleX("+e+") scaleY("+n+")"}},Transform:{toString(s){if(s)return[zo.Translate.toString(s),zo.Scale.toString(s)].join(" ")}},Transition:{toString(s){let{property:e,duration:n,easing:r}=s;return e+" "+n+"ms "+r}}}),sy="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function EE(s){return s.matches(sy)?s:s.querySelector(sy)}const _E={display:"none"};function AE(s){let{id:e,value:n}=s;return We.createElement("div",{id:e,style:_E},n)}function xE(s){let{id:e,announcement:n,ariaLiveType:r="assertive"}=s;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 We.createElement("div",{id:e,style:i,role:"status","aria-live":r,"aria-atomic":!0},n)}function TE(){const[s,e]=M.useState("");return{announce:M.useCallback(r=>{r!=null&&e(r)},[]),announcement:s}}const oy=M.createContext(null);function kE(s){const e=M.useContext(oy);M.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(s)},[s,e])}function RE(){const[s]=M.useState(()=>new Set),e=M.useCallback(r=>(s.add(r),()=>s.delete(r)),[s]);return[M.useCallback(r=>{let{type:i,event:l}=r;s.forEach(c=>{var d;return(d=c[i])==null?void 0:d.call(c,l)})},[s]),e]}const DE={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. - `},U_={onDragStart(s){let{active:e}=s;return"Picked up draggable item "+e.id+"."},onDragOver(s){let{active:e,over:n}=s;return n?"Draggable item "+e.id+" was moved over droppable area "+n.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(s){let{active:e,over:n}=s;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(s){let{active:e}=s;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function B_(s){let{announcements:e=U_,container:n,hiddenTextDescribedById:r,screenReaderInstructions:i=P_}=s;const{announce:l,announcement:c}=j_(),d=Uo("DndLiveRegion"),[f,h]=I.useState(!1);if(I.useEffect(()=>{h(!0)},[]),H_(I.useMemo(()=>({onDragStart(y){let{active:v}=y;l(e.onDragStart({active:v}))},onDragMove(y){let{active:v,over:S}=y;e.onDragMove&&l(e.onDragMove({active:v,over:S}))},onDragOver(y){let{active:v,over:S}=y;l(e.onDragOver({active:v,over:S}))},onDragEnd(y){let{active:v,over:S}=y;l(e.onDragEnd({active:v,over:S}))},onDragCancel(y){let{active:v,over:S}=y;l(e.onDragCancel({active:v,over:S}))}}),[l,e])),!f)return null;const m=Xe.createElement(Xe.Fragment,null,Xe.createElement(N_,{id:r,value:i.draggable}),Xe.createElement(I_,{id:d,announcement:c}));return n?ja.createPortal(m,n):m}var ln;(function(s){s.DragStart="dragStart",s.DragMove="dragMove",s.DragEnd="dragEnd",s.DragCancel="dragCancel",s.DragOver="dragOver",s.RegisterDroppable="registerDroppable",s.SetDroppableDisabled="setDroppableDisabled",s.UnregisterDroppable="unregisterDroppable"})(ln||(ln={}));function Dc(){}function Iy(s,e){return I.useMemo(()=>({sensor:s,options:e??{}}),[s,e])}function q_(){for(var s=arguments.length,e=new Array(s),n=0;n[...e].filter(r=>r!=null),[...e])}const kr=Object.freeze({x:0,y:0});function jy(s,e){return Math.sqrt(Math.pow(s.x-e.x,2)+Math.pow(s.y-e.y,2))}function Hy(s,e){let{data:{value:n}}=s,{data:{value:r}}=e;return n-r}function G_(s,e){let{data:{value:n}}=s,{data:{value:r}}=e;return r-n}function zy(s){let{left:e,top:n,height:r,width:i}=s;return[{x:e,y:n},{x:e+i,y:n},{x:e,y:n+r},{x:e+i,y:n+r}]}function Py(s,e){if(!s||s.length===0)return null;const[n]=s;return n[e]}function Uy(s,e,n){return e===void 0&&(e=s.left),n===void 0&&(n=s.top),{x:e+s.width*.5,y:n+s.height*.5}}const F_=s=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=s;const i=Uy(e,e.left,e.top),l=[];for(const c of r){const{id:d}=c,f=n.get(d);if(f){const h=jy(Uy(f),i);l.push({id:d,data:{droppableContainer:c,value:h}})}}return l.sort(Hy)},V_=s=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=s;const i=zy(e),l=[];for(const c of r){const{id:d}=c,f=n.get(d);if(f){const h=zy(f),m=i.reduce((v,S,_)=>v+jy(h[_],S),0),y=Number((m/4).toFixed(4));l.push({id:d,data:{droppableContainer:c,value:y}})}}return l.sort(Hy)};function K_(s,e){const n=Math.max(e.top,s.top),r=Math.max(e.left,s.left),i=Math.min(e.left+e.width,s.left+s.width),l=Math.min(e.top+e.height,s.top+s.height),c=i-r,d=l-n;if(r{let{collisionRect:e,droppableRects:n,droppableContainers:r}=s;const i=[];for(const l of r){const{id:c}=l,d=n.get(c);if(d){const f=K_(d,e);f>0&&i.push({id:c,data:{droppableContainer:l,value:f}})}}return i.sort(G_)};function Y_(s,e,n){return{...s,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function By(s,e){return s&&e?{x:s.left-e.left,y:s.top-e.top}:kr}function X_(s){return function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),l=1;l({...c,top:c.top+s*d.y,bottom:c.bottom+s*d.y,left:c.left+s*d.x,right:c.right+s*d.x}),{...n})}}const J_=X_(1);function Q_(s){if(s.startsWith("matrix3d(")){const e=s.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(s.startsWith("matrix(")){const e=s.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function Z_(s,e,n){const r=Q_(e);if(!r)return s;const{scaleX:i,scaleY:l,x:c,y:d}=r,f=s.left-c-(1-i)*parseFloat(n),h=s.top-d-(1-l)*parseFloat(n.slice(n.indexOf(" ")+1)),m=i?s.width/i:s.width,y=l?s.height/l:s.height;return{width:m,height:y,top:h,right:f+m,bottom:h+y,left:f}}const eA={ignoreTransform:!1};function Es(s,e){e===void 0&&(e=eA);let n=s.getBoundingClientRect();if(e.ignoreTransform){const{transform:h,transformOrigin:m}=Hn(s).getComputedStyle(s);h&&(n=Z_(n,h,m))}const{top:r,left:i,width:l,height:c,bottom:d,right:f}=n;return{top:r,left:i,width:l,height:c,bottom:d,right:f}}function qy(s){return Es(s,{ignoreTransform:!0})}function tA(s){const e=s.innerWidth,n=s.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function nA(s,e){return e===void 0&&(e=Hn(s).getComputedStyle(s)),e.position==="fixed"}function rA(s,e){e===void 0&&(e=Hn(s).getComputedStyle(s));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const l=e[i];return typeof l=="string"?n.test(l):!1})}function Oc(s,e){const n=[];function r(i){if(e!=null&&n.length>=e||!i)return n;if(zf(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!Ho(i)||Ly(i)||n.includes(i))return n;const l=Hn(s).getComputedStyle(i);return i!==s&&rA(i,l)&&n.push(i),nA(i,l)?n:r(i.parentNode)}return s?r(s):n}function Gy(s){const[e]=Oc(s,1);return e??null}function Ff(s){return!kc||!s?null:Ss(s)?s:Hf(s)?zf(s)||s===ws(s).scrollingElement?window:Ho(s)?s:null:null}function Fy(s){return Ss(s)?s.scrollX:s.scrollLeft}function Vy(s){return Ss(s)?s.scrollY:s.scrollTop}function Vf(s){return{x:Fy(s),y:Vy(s)}}var mn;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(mn||(mn={}));function Ky(s){return!kc||!s?!1:s===document.scrollingElement}function Wy(s){const e={x:0,y:0},n=Ky(s)?{height:window.innerHeight,width:window.innerWidth}:{height:s.clientHeight,width:s.clientWidth},r={x:s.scrollWidth-n.width,y:s.scrollHeight-n.height},i=s.scrollTop<=e.y,l=s.scrollLeft<=e.x,c=s.scrollTop>=r.y,d=s.scrollLeft>=r.x;return{isTop:i,isLeft:l,isBottom:c,isRight:d,maxScroll:r,minScroll:e}}const aA={x:.2,y:.2};function iA(s,e,n,r,i){let{top:l,left:c,right:d,bottom:f}=n;r===void 0&&(r=10),i===void 0&&(i=aA);const{isTop:h,isBottom:m,isLeft:y,isRight:v}=Wy(s),S={x:0,y:0},_={x:0,y:0},x={height:e.height*i.y,width:e.width*i.x};return!h&&l<=e.top+x.height?(S.y=mn.Backward,_.y=r*Math.abs((e.top+x.height-l)/x.height)):!m&&f>=e.bottom-x.height&&(S.y=mn.Forward,_.y=r*Math.abs((e.bottom-x.height-f)/x.height)),!v&&d>=e.right-x.width?(S.x=mn.Forward,_.x=r*Math.abs((e.right-x.width-d)/x.width)):!y&&c<=e.left+x.width&&(S.x=mn.Backward,_.x=r*Math.abs((e.left+x.width-c)/x.width)),{direction:S,speed:_}}function sA(s){if(s===document.scrollingElement){const{innerWidth:l,innerHeight:c}=window;return{top:0,left:0,right:l,bottom:c,width:l,height:c}}const{top:e,left:n,right:r,bottom:i}=s.getBoundingClientRect();return{top:e,left:n,right:r,bottom:i,width:s.clientWidth,height:s.clientHeight}}function Yy(s){return s.reduce((e,n)=>Cs(e,Vf(n)),kr)}function oA(s){return s.reduce((e,n)=>e+Fy(n),0)}function lA(s){return s.reduce((e,n)=>e+Vy(n),0)}function cA(s,e){if(e===void 0&&(e=Es),!s)return;const{top:n,left:r,bottom:i,right:l}=e(s);Gy(s)&&(i<=0||l<=0||n>=window.innerHeight||r>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const uA=[["x",["left","right"],oA],["y",["top","bottom"],lA]];class Kf{constructor(e,n){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 r=Oc(n),i=Yy(r);this.rect={...e},this.width=e.width,this.height=e.height;for(const[l,c,d]of uA)for(const f of c)Object.defineProperty(this,f,{get:()=>{const h=d(r),m=i[l]-h;return this.rect[f]+m},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Go{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=e}add(e,n,r){var i;(i=this.target)==null||i.addEventListener(e,n,r),this.listeners.push([e,n,r])}}function dA(s){const{EventTarget:e}=Hn(s);return s instanceof e?s:ws(s)}function Wf(s,e){const n=Math.abs(s.x),r=Math.abs(s.y);return typeof e=="number"?Math.sqrt(n**2+r**2)>e:"x"in e&&"y"in e?n>e.x&&r>e.y:"x"in e?n>e.x:"y"in e?r>e.y:!1}var cr;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(cr||(cr={}));function Xy(s){s.preventDefault()}function fA(s){s.stopPropagation()}var dt;(function(s){s.Space="Space",s.Down="ArrowDown",s.Right="ArrowRight",s.Left="ArrowLeft",s.Up="ArrowUp",s.Esc="Escape",s.Enter="Enter",s.Tab="Tab"})(dt||(dt={}));const Jy={start:[dt.Space,dt.Enter],cancel:[dt.Esc],end:[dt.Space,dt.Enter,dt.Tab]},hA=(s,e)=>{let{currentCoordinates:n}=e;switch(s.code){case dt.Right:return{...n,x:n.x+25};case dt.Left:return{...n,x:n.x-25};case dt.Down:return{...n,y:n.y+25};case dt.Up:return{...n,y:n.y-25}}};class Yf{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:n}}=e;this.props=e,this.listeners=new Go(ws(n)),this.windowListeners=new Go(Hn(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(cr.Resize,this.handleCancel),this.windowListeners.add(cr.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(cr.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,r=e.node.current;r&&cA(r),n(kr)}handleKeyDown(e){if(qf(e)){const{active:n,context:r,options:i}=this.props,{keyboardCodes:l=Jy,coordinateGetter:c=hA,scrollBehavior:d="smooth"}=i,{code:f}=e;if(l.end.includes(f)){this.handleEnd(e);return}if(l.cancel.includes(f)){this.handleCancel(e);return}const{collisionRect:h}=r.current,m=h?{x:h.left,y:h.top}:kr;this.referenceCoordinates||(this.referenceCoordinates=m);const y=c(e,{active:n,context:r.current,currentCoordinates:m});if(y){const v=Bo(y,m),S={x:0,y:0},{scrollableAncestors:_}=r.current;for(const x of _){const A=e.code,{isTop:D,isRight:O,isLeft:k,isBottom:L,maxScroll:B,minScroll:q}=Wy(x),z=sA(x),W={x:Math.min(A===dt.Right?z.right-z.width/2:z.right,Math.max(A===dt.Right?z.left:z.left+z.width/2,y.x)),y:Math.min(A===dt.Down?z.bottom-z.height/2:z.bottom,Math.max(A===dt.Down?z.top:z.top+z.height/2,y.y))},de=A===dt.Right&&!O||A===dt.Left&&!k,_e=A===dt.Down&&!L||A===dt.Up&&!D;if(de&&W.x!==y.x){const Se=x.scrollLeft+v.x,Ie=A===dt.Right&&Se<=B.x||A===dt.Left&&Se>=q.x;if(Ie&&!v.y){x.scrollTo({left:Se,behavior:d});return}Ie?S.x=x.scrollLeft-Se:S.x=A===dt.Right?x.scrollLeft-B.x:x.scrollLeft-q.x,S.x&&x.scrollBy({left:-S.x,behavior:d});break}else if(_e&&W.y!==y.y){const Se=x.scrollTop+v.y,Ie=A===dt.Down&&Se<=B.y||A===dt.Up&&Se>=q.y;if(Ie&&!v.x){x.scrollTo({top:Se,behavior:d});return}Ie?S.y=x.scrollTop-Se:S.y=A===dt.Down?x.scrollTop-B.y:x.scrollTop-q.y,S.y&&x.scrollBy({top:-S.y,behavior:d});break}}this.handleMove(e,Cs(Bo(y,this.referenceCoordinates),S))}}}handleMove(e,n){const{onMove:r}=this.props;e.preventDefault(),r(n)}handleEnd(e){const{onEnd:n}=this.props;e.preventDefault(),this.detach(),n()}handleCancel(e){const{onCancel:n}=this.props;e.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}Yf.activators=[{eventName:"onKeyDown",handler:(s,e,n)=>{let{keyboardCodes:r=Jy,onActivation:i}=e,{active:l}=n;const{code:c}=s.nativeEvent;if(r.start.includes(c)){const d=l.activatorNode.current;return d&&s.target!==d?!1:(s.preventDefault(),i?.({event:s.nativeEvent}),!0)}return!1}}];function Qy(s){return!!(s&&"distance"in s)}function Zy(s){return!!(s&&"delay"in s)}class Xf{constructor(e,n,r){var i;r===void 0&&(r=dA(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=n;const{event:l}=e,{target:c}=l;this.props=e,this.events=n,this.document=ws(c),this.documentListeners=new Go(this.document),this.listeners=new Go(r),this.windowListeners=new Go(Hn(c)),this.initialCoordinates=(i=Gf(l))!=null?i:kr,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:n,bypassActivationConstraint:r}}}=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(cr.Resize,this.handleCancel),this.windowListeners.add(cr.DragStart,Xy),this.windowListeners.add(cr.VisibilityChange,this.handleCancel),this.windowListeners.add(cr.ContextMenu,Xy),this.documentListeners.add(cr.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Zy(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(Qy(n)){this.handlePending(n);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,n){const{active:r,onPending:i}=this.props;i(r,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(cr.Click,fA,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(cr.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:r,initialCoordinates:i,props:l}=this,{onMove:c,options:{activationConstraint:d}}=l;if(!i)return;const f=(n=Gf(e))!=null?n:kr,h=Bo(i,f);if(!r&&d){if(Qy(d)){if(d.tolerance!=null&&Wf(h,d.tolerance))return this.handleCancel();if(Wf(h,d.distance))return this.handleStart()}if(Zy(d)&&Wf(h,d.tolerance))return this.handleCancel();this.handlePending(d,h);return}e.cancelable&&e.preventDefault(),c(f)}handleEnd(){const{onAbort:e,onEnd:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleCancel(){const{onAbort:e,onCancel:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleKeydown(e){e.code===dt.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const pA={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Jf extends Xf{constructor(e){const{event:n}=e,r=ws(n.target);super(e,pA,r)}}Jf.activators=[{eventName:"onPointerDown",handler:(s,e)=>{let{nativeEvent:n}=s,{onActivation:r}=e;return!n.isPrimary||n.button!==0?!1:(r?.({event:n}),!0)}}];const gA={move:{name:"mousemove"},end:{name:"mouseup"}};var Qf;(function(s){s[s.RightClick=2]="RightClick"})(Qf||(Qf={}));class mA extends Xf{constructor(e){super(e,gA,ws(e.event.target))}}mA.activators=[{eventName:"onMouseDown",handler:(s,e)=>{let{nativeEvent:n}=s,{onActivation:r}=e;return n.button===Qf.RightClick?!1:(r?.({event:n}),!0)}}];const Zf={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class yA extends Xf{constructor(e){super(e,Zf)}static setup(){return window.addEventListener(Zf.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(Zf.move.name,e)};function e(){}}}yA.activators=[{eventName:"onTouchStart",handler:(s,e)=>{let{nativeEvent:n}=s,{onActivation:r}=e;const{touches:i}=n;return i.length>1?!1:(r?.({event:n}),!0)}}];var Fo;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(Fo||(Fo={}));var Lc;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(Lc||(Lc={}));function bA(s){let{acceleration:e,activator:n=Fo.Pointer,canScroll:r,draggingRect:i,enabled:l,interval:c=5,order:d=Lc.TreeOrder,pointerCoordinates:f,scrollableAncestors:h,scrollableAncestorRects:m,delta:y,threshold:v}=s;const S=SA({delta:y,disabled:!l}),[_,x]=D_(),A=I.useRef({x:0,y:0}),D=I.useRef({x:0,y:0}),O=I.useMemo(()=>{switch(n){case Fo.Pointer:return f?{top:f.y,bottom:f.y,left:f.x,right:f.x}:null;case Fo.DraggableRect:return i}},[n,i,f]),k=I.useRef(null),L=I.useCallback(()=>{const q=k.current;if(!q)return;const z=A.current.x*D.current.x,W=A.current.y*D.current.y;q.scrollBy(z,W)},[]),B=I.useMemo(()=>d===Lc.TreeOrder?[...h].reverse():h,[d,h]);I.useEffect(()=>{if(!l||!h.length||!O){x();return}for(const q of B){if(r?.(q)===!1)continue;const z=h.indexOf(q),W=m[z];if(!W)continue;const{direction:de,speed:_e}=iA(q,W,O,e,v);for(const Se of["x","y"])S[Se][de[Se]]||(_e[Se]=0,de[Se]=0);if(_e.x>0||_e.y>0){x(),k.current=q,_(L,c),A.current=_e,D.current=de;return}}A.current={x:0,y:0},D.current={x:0,y:0},x()},[e,L,r,x,l,c,JSON.stringify(O),JSON.stringify(S),_,h,B,m,JSON.stringify(v)])}const vA={x:{[mn.Backward]:!1,[mn.Forward]:!1},y:{[mn.Backward]:!1,[mn.Forward]:!1}};function SA(s){let{delta:e,disabled:n}=s;const r=Uf(e);return Po(i=>{if(n||!r||!i)return vA;const l={x:Math.sign(e.x-r.x),y:Math.sign(e.y-r.y)};return{x:{[mn.Backward]:i.x[mn.Backward]||l.x===-1,[mn.Forward]:i.x[mn.Forward]||l.x===1},y:{[mn.Backward]:i.y[mn.Backward]||l.y===-1,[mn.Forward]:i.y[mn.Forward]||l.y===1}}},[n,e,r])}function wA(s,e){const n=e!=null?s.get(e):void 0,r=n?n.node.current:null;return Po(i=>{var l;return e==null?null:(l=r??i)!=null?l:null},[r,e])}function CA(s,e){return I.useMemo(()=>s.reduce((n,r)=>{const{sensor:i}=r,l=i.activators.map(c=>({eventName:c.eventName,handler:e(c.handler,r)}));return[...n,...l]},[]),[s,e])}var Vo;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(Vo||(Vo={}));var eh;(function(s){s.Optimized="optimized"})(eh||(eh={}));const eb=new Map;function EA(s,e){let{dragging:n,dependencies:r,config:i}=e;const[l,c]=I.useState(null),{frequency:d,measure:f,strategy:h}=i,m=I.useRef(s),y=A(),v=zo(y),S=I.useCallback(function(D){D===void 0&&(D=[]),!v.current&&c(O=>O===null?D:O.concat(D.filter(k=>!O.includes(k))))},[v]),_=I.useRef(null),x=Po(D=>{if(y&&!n)return eb;if(!D||D===eb||m.current!==s||l!=null){const O=new Map;for(let k of s){if(!k)continue;if(l&&l.length>0&&!l.includes(k.id)&&k.rect.current){O.set(k.id,k.rect.current);continue}const L=k.node.current,B=L?new Kf(f(L),L):null;k.rect.current=B,B&&O.set(k.id,B)}return O}return D},[s,l,n,y,f]);return I.useEffect(()=>{m.current=s},[s]),I.useEffect(()=>{y||S()},[n,y]),I.useEffect(()=>{l&&l.length>0&&c(null)},[JSON.stringify(l)]),I.useEffect(()=>{y||typeof d!="number"||_.current!==null||(_.current=setTimeout(()=>{S(),_.current=null},d))},[d,y,S,...r]),{droppableRects:x,measureDroppableContainers:S,measuringScheduled:l!=null};function A(){switch(h){case Vo.Always:return!1;case Vo.BeforeDragging:return n;default:return!n}}}function tb(s,e){return Po(n=>s?n||(typeof e=="function"?e(s):s):null,[e,s])}function _A(s,e){return tb(s,e)}function AA(s){let{callback:e,disabled:n}=s;const r=Pf(e),i=I.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:l}=window;return new l(r)},[r,n]);return I.useEffect(()=>()=>i?.disconnect(),[i]),i}function $c(s){let{callback:e,disabled:n}=s;const r=Pf(e),i=I.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:l}=window;return new l(r)},[n]);return I.useEffect(()=>()=>i?.disconnect(),[i]),i}function xA(s){return new Kf(Es(s),s)}function nb(s,e,n){e===void 0&&(e=xA);const[r,i]=I.useState(null);function l(){i(f=>{if(!s)return null;if(s.isConnected===!1){var h;return(h=f??n)!=null?h:null}const m=e(s);return JSON.stringify(f)===JSON.stringify(m)?f:m})}const c=AA({callback(f){if(s)for(const h of f){const{type:m,target:y}=h;if(m==="childList"&&y instanceof HTMLElement&&y.contains(s)){l();break}}}}),d=$c({callback:l});return Fr(()=>{l(),s?(d?.observe(s),c?.observe(document.body,{childList:!0,subtree:!0})):(d?.disconnect(),c?.disconnect())},[s]),r}function TA(s){const e=tb(s);return By(s,e)}const rb=[];function kA(s){const e=I.useRef(s),n=Po(r=>s?r&&r!==rb&&s&&e.current&&s.parentNode===e.current.parentNode?r:Oc(s):rb,[s]);return I.useEffect(()=>{e.current=s},[s]),n}function RA(s){const[e,n]=I.useState(null),r=I.useRef(s),i=I.useCallback(l=>{const c=Ff(l.target);c&&n(d=>d?(d.set(c,Vf(c)),new Map(d)):null)},[]);return I.useEffect(()=>{const l=r.current;if(s!==l){c(l);const d=s.map(f=>{const h=Ff(f);return h?(h.addEventListener("scroll",i,{passive:!0}),[h,Vf(h)]):null}).filter(f=>f!=null);n(d.length?new Map(d):null),r.current=s}return()=>{c(s),c(l)};function c(d){d.forEach(f=>{const h=Ff(f);h?.removeEventListener("scroll",i)})}},[i,s]),I.useMemo(()=>s.length?e?Array.from(e.values()).reduce((l,c)=>Cs(l,c),kr):Yy(s):kr,[s,e])}function ab(s,e){e===void 0&&(e=[]);const n=I.useRef(null);return I.useEffect(()=>{n.current=null},e),I.useEffect(()=>{const r=s!==kr;r&&!n.current&&(n.current=s),!r&&n.current&&(n.current=null)},[s]),n.current?Bo(s,n.current):kr}function DA(s){I.useEffect(()=>{if(!kc)return;const e=s.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of e)n?.()}},s.map(e=>{let{sensor:n}=e;return n}))}function OA(s,e){return I.useMemo(()=>s.reduce((n,r)=>{let{eventName:i,handler:l}=r;return n[i]=c=>{l(c,e)},n},{}),[s,e])}function ib(s){return I.useMemo(()=>s?tA(s):null,[s])}const sb=[];function LA(s,e){e===void 0&&(e=Es);const[n]=s,r=ib(n?Hn(n):null),[i,l]=I.useState(sb);function c(){l(()=>s.length?s.map(f=>Ky(f)?r:new Kf(e(f),f)):sb)}const d=$c({callback:c});return Fr(()=>{d?.disconnect(),c(),s.forEach(f=>d?.observe(f))},[s]),i}function $A(s){if(!s)return null;if(s.children.length>1)return s;const e=s.children[0];return Ho(e)?e:s}function MA(s){let{measure:e}=s;const[n,r]=I.useState(null),i=I.useCallback(h=>{for(const{target:m}of h)if(Ho(m)){r(y=>{const v=e(m);return y?{...y,width:v.width,height:v.height}:v});break}},[e]),l=$c({callback:i}),c=I.useCallback(h=>{const m=$A(h);l?.disconnect(),m&&l?.observe(m),r(m?e(m):null)},[e,l]),[d,f]=Rc(c);return I.useMemo(()=>({nodeRef:d,rect:n,setRef:f}),[n,d,f])}const NA=[{sensor:Jf,options:{}},{sensor:Yf,options:{}}],IA={current:{}},Mc={draggable:{measure:qy},droppable:{measure:qy,strategy:Vo.WhileDragging,frequency:eh.Optimized},dragOverlay:{measure:Es}};class Ko extends Map{get(e){var n;return e!=null&&(n=super.get(e))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:n}=e;return!n})}getNodeFor(e){var n,r;return(n=(r=this.get(e))==null?void 0:r.node.current)!=null?n:void 0}}const jA={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Ko,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Dc},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Mc,measureDroppableContainers:Dc,windowRect:null,measuringScheduled:!1},HA={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Dc,draggableNodes:new Map,over:null,measureDroppableContainers:Dc},Nc=I.createContext(HA),ob=I.createContext(jA);function zA(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Ko}}}function PA(s,e){switch(e.type){case ln.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case ln.DragMove:return s.draggable.active==null?s:{...s,draggable:{...s.draggable,translate:{x:e.coordinates.x-s.draggable.initialCoordinates.x,y:e.coordinates.y-s.draggable.initialCoordinates.y}}};case ln.DragEnd:case ln.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case ln.RegisterDroppable:{const{element:n}=e,{id:r}=n,i=new Ko(s.droppable.containers);return i.set(r,n),{...s,droppable:{...s.droppable,containers:i}}}case ln.SetDroppableDisabled:{const{id:n,key:r,disabled:i}=e,l=s.droppable.containers.get(n);if(!l||r!==l.key)return s;const c=new Ko(s.droppable.containers);return c.set(n,{...l,disabled:i}),{...s,droppable:{...s.droppable,containers:c}}}case ln.UnregisterDroppable:{const{id:n,key:r}=e,i=s.droppable.containers.get(n);if(!i||r!==i.key)return s;const l=new Ko(s.droppable.containers);return l.delete(n),{...s,droppable:{...s.droppable,containers:l}}}default:return s}}function UA(s){let{disabled:e}=s;const{active:n,activatorEvent:r,draggableNodes:i}=I.useContext(Nc),l=Uf(r),c=Uf(n?.id);return I.useEffect(()=>{if(!e&&!r&&l&&c!=null){if(!qf(l)||document.activeElement===l.target)return;const d=i.get(c);if(!d)return;const{activatorNode:f,node:h}=d;if(!f.current&&!h.current)return;requestAnimationFrame(()=>{for(const m of[f.current,h.current]){if(!m)continue;const y=$_(m);if(y){y.focus();break}}})}},[r,e,i,c,l]),null}function BA(s,e){let{transform:n,...r}=e;return s!=null&&s.length?s.reduce((i,l)=>l({transform:i,...r}),n):n}function qA(s){return I.useMemo(()=>({draggable:{...Mc.draggable,...s?.draggable},droppable:{...Mc.droppable,...s?.droppable},dragOverlay:{...Mc.dragOverlay,...s?.dragOverlay}}),[s?.draggable,s?.droppable,s?.dragOverlay])}function GA(s){let{activeNode:e,measure:n,initialRect:r,config:i=!0}=s;const l=I.useRef(!1),{x:c,y:d}=typeof i=="boolean"?{x:i,y:i}:i;Fr(()=>{if(!c&&!d||!e){l.current=!1;return}if(l.current||!r)return;const h=e?.node.current;if(!h||h.isConnected===!1)return;const m=n(h),y=By(m,r);if(c||(y.x=0),d||(y.y=0),l.current=!0,Math.abs(y.x)>0||Math.abs(y.y)>0){const v=Gy(h);v&&v.scrollBy({top:y.y,left:y.x})}},[e,c,d,r,n])}const lb=I.createContext({...kr,scaleX:1,scaleY:1});var Ha;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(Ha||(Ha={}));const FA=I.memo(function(e){var n,r,i,l;let{id:c,accessibility:d,autoScroll:f=!0,children:h,sensors:m=NA,collisionDetection:y=W_,measuring:v,modifiers:S,..._}=e;const x=I.useReducer(PA,void 0,zA),[A,D]=x,[O,k]=z_(),[L,B]=I.useState(Ha.Uninitialized),q=L===Ha.Initialized,{draggable:{active:z,nodes:W,translate:de},droppable:{containers:_e}}=A,Se=z!=null?W.get(z):null,Ie=I.useRef({initial:null,translated:null}),Fe=I.useMemo(()=>{var pe;return z!=null?{id:z,data:(pe=Se?.data)!=null?pe:IA,rect:Ie}:null},[z,Se]),ze=I.useRef(null),[Et,Q]=I.useState(null),[ue,De]=I.useState(null),ee=zo(_,Object.values(_)),me=Uo("DndDescribedBy",c),H=I.useMemo(()=>_e.getEnabled(),[_e]),T=qA(v),{droppableRects:fe,measureDroppableContainers:he,measuringScheduled:Ae}=EA(H,{dragging:q,dependencies:[de.x,de.y],config:T.droppable}),se=wA(W,z),ge=I.useMemo(()=>ue?Gf(ue):null,[ue]),$e=ve(),Te=_A(se,T.draggable.measure);GA({activeNode:z!=null?W.get(z):null,config:$e.layoutShiftCompensation,initialRect:Te,measure:T.draggable.measure});const je=nb(se,T.draggable.measure,Te),xt=nb(se?se.parentElement:null),rt=I.useRef({activatorEvent:null,active:null,activeNode:se,collisionRect:null,collisions:null,droppableRects:fe,draggableNodes:W,draggingNode:null,draggingNodeRect:null,droppableContainers:_e,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),gt=_e.getNodeFor((n=rt.current.over)==null?void 0:n.id),at=MA({measure:T.dragOverlay.measure}),Yt=(r=at.nodeRef.current)!=null?r:se,Ht=q?(i=at.rect)!=null?i:je:null,bt=!!(at.nodeRef.current&&at.rect),qe=TA(bt?null:je),mt=ib(Yt?Hn(Yt):null),Dt=kA(q?gt??se:null),zt=LA(Dt),kn=BA(S,{transform:{x:de.x-qe.x,y:de.y-qe.y,scaleX:1,scaleY:1},activatorEvent:ue,active:Fe,activeNodeRect:je,containerNodeRect:xt,draggingNodeRect:Ht,over:rt.current.over,overlayNodeRect:at.rect,scrollableAncestors:Dt,scrollableAncestorRects:zt,windowRect:mt}),dr=ge?Cs(ge,de):null,Ot=RA(Dt),$i=ab(Ot),ua=ab(Ot,[je]),bn=Cs(kn,$i),Mn=Ht?J_(Ht,kn):null,it=Fe&&Mn?y({active:Fe,collisionRect:Mn,droppableRects:fe,droppableContainers:H,pointerCoordinates:dr}):null,Pn=Py(it,"id"),[vn,da]=I.useState(null),fr=bt?kn:Cs(kn,ua),un=Y_(fr,(l=vn?.rect)!=null?l:null,je),Rn=I.useRef(null),dn=I.useCallback((pe,Ee)=>{let{sensor:xe,options:Ke}=Ee;if(ze.current==null)return;const ke=W.get(ze.current);if(!ke)return;const Me=pe.nativeEvent,Re=new xe({active:ze.current,activeNode:ke,event:Me,options:Ke,context:rt,onAbort(Pe){if(!W.get(Pe))return;const{onDragAbort:Ce}=ee.current,He={id:Pe};Ce?.(He),O({type:"onDragAbort",event:He})},onPending(Pe,Ve,Ce,He){if(!W.get(Pe))return;const{onDragPending:Lt}=ee.current,Bt={id:Pe,constraint:Ve,initialCoordinates:Ce,offset:He};Lt?.(Bt),O({type:"onDragPending",event:Bt})},onStart(Pe){const Ve=ze.current;if(Ve==null)return;const Ce=W.get(Ve);if(!Ce)return;const{onDragStart:He}=ee.current,nt={activatorEvent:Me,active:{id:Ve,data:Ce.data,rect:Ie}};ja.unstable_batchedUpdates(()=>{He?.(nt),B(Ha.Initializing),D({type:ln.DragStart,initialCoordinates:Pe,active:Ve}),O({type:"onDragStart",event:nt}),Q(Rn.current),De(Me)})},onMove(Pe){D({type:ln.DragMove,coordinates:Pe})},onEnd:tt(ln.DragEnd),onCancel:tt(ln.DragCancel)});Rn.current=Re;function tt(Pe){return async function(){const{active:Ce,collisions:He,over:nt,scrollAdjustedTranslate:Lt}=rt.current;let Bt=null;if(Ce&&Lt){const{cancelDrop:Nn}=ee.current;Bt={activatorEvent:Me,active:Ce,collisions:He,delta:Lt,over:nt},Pe===ln.DragEnd&&typeof Nn=="function"&&await Promise.resolve(Nn(Bt))&&(Pe=ln.DragCancel)}ze.current=null,ja.unstable_batchedUpdates(()=>{D({type:Pe}),B(Ha.Uninitialized),da(null),Q(null),De(null),Rn.current=null;const Nn=Pe===ln.DragEnd?"onDragEnd":"onDragCancel";if(Bt){const Gt=ee.current[Nn];Gt?.(Bt),O({type:Nn,event:Bt})}})}}},[W]),V=I.useCallback((pe,Ee)=>(xe,Ke)=>{const ke=xe.nativeEvent,Me=W.get(Ke);if(ze.current!==null||!Me||ke.dndKit||ke.defaultPrevented)return;const Re={active:Me};pe(xe,Ee.options,Re)===!0&&(ke.dndKit={capturedBy:Ee.sensor},ze.current=Ke,dn(xe,Ee))},[W,dn]),ie=CA(m,V);DA(m),Fr(()=>{je&&L===Ha.Initializing&&B(Ha.Initialized)},[je,L]),I.useEffect(()=>{const{onDragMove:pe}=ee.current,{active:Ee,activatorEvent:xe,collisions:Ke,over:ke}=rt.current;if(!Ee||!xe)return;const Me={active:Ee,activatorEvent:xe,collisions:Ke,delta:{x:bn.x,y:bn.y},over:ke};ja.unstable_batchedUpdates(()=>{pe?.(Me),O({type:"onDragMove",event:Me})})},[bn.x,bn.y]),I.useEffect(()=>{const{active:pe,activatorEvent:Ee,collisions:xe,droppableContainers:Ke,scrollAdjustedTranslate:ke}=rt.current;if(!pe||ze.current==null||!Ee||!ke)return;const{onDragOver:Me}=ee.current,Re=Ke.get(Pn),tt=Re&&Re.rect.current?{id:Re.id,rect:Re.rect.current,data:Re.data,disabled:Re.disabled}:null,Pe={active:pe,activatorEvent:Ee,collisions:xe,delta:{x:ke.x,y:ke.y},over:tt};ja.unstable_batchedUpdates(()=>{da(tt),Me?.(Pe),O({type:"onDragOver",event:Pe})})},[Pn]),Fr(()=>{rt.current={activatorEvent:ue,active:Fe,activeNode:se,collisionRect:Mn,collisions:it,droppableRects:fe,draggableNodes:W,draggingNode:Yt,draggingNodeRect:Ht,droppableContainers:_e,over:vn,scrollableAncestors:Dt,scrollAdjustedTranslate:bn},Ie.current={initial:Ht,translated:Mn}},[Fe,se,it,Mn,W,Yt,Ht,fe,_e,vn,Dt,bn]),bA({...$e,delta:de,draggingRect:Mn,pointerCoordinates:dr,scrollableAncestors:Dt,scrollableAncestorRects:zt});const ce=I.useMemo(()=>({active:Fe,activeNode:se,activeNodeRect:je,activatorEvent:ue,collisions:it,containerNodeRect:xt,dragOverlay:at,draggableNodes:W,droppableContainers:_e,droppableRects:fe,over:vn,measureDroppableContainers:he,scrollableAncestors:Dt,scrollableAncestorRects:zt,measuringConfiguration:T,measuringScheduled:Ae,windowRect:mt}),[Fe,se,je,ue,it,xt,at,W,_e,fe,vn,he,Dt,zt,T,Ae,mt]),Z=I.useMemo(()=>({activatorEvent:ue,activators:ie,active:Fe,activeNodeRect:je,ariaDescribedById:{draggable:me},dispatch:D,draggableNodes:W,over:vn,measureDroppableContainers:he}),[ue,ie,Fe,je,D,me,W,vn,he]);return Xe.createElement(Ny.Provider,{value:k},Xe.createElement(Nc.Provider,{value:Z},Xe.createElement(ob.Provider,{value:ce},Xe.createElement(lb.Provider,{value:un},h)),Xe.createElement(UA,{disabled:d?.restoreFocus===!1})),Xe.createElement(B_,{...d,hiddenTextDescribedById:me}));function ve(){const pe=Et?.autoScrollEnabled===!1,Ee=typeof f=="object"?f.enabled===!1:f===!1,xe=q&&!pe&&!Ee;return typeof f=="object"?{...f,enabled:xe}:{enabled:xe}}}),VA=I.createContext(null),cb="button",KA="Draggable";function WA(s){let{id:e,data:n,disabled:r=!1,attributes:i}=s;const l=Uo(KA),{activators:c,activatorEvent:d,active:f,activeNodeRect:h,ariaDescribedById:m,draggableNodes:y,over:v}=I.useContext(Nc),{role:S=cb,roleDescription:_="draggable",tabIndex:x=0}=i??{},A=f?.id===e,D=I.useContext(A?lb:VA),[O,k]=Rc(),[L,B]=Rc(),q=OA(c,e),z=zo(n);Fr(()=>(y.set(e,{id:e,key:l,node:O,activatorNode:L,data:z}),()=>{const de=y.get(e);de&&de.key===l&&y.delete(e)}),[y,e]);const W=I.useMemo(()=>({role:S,tabIndex:x,"aria-disabled":r,"aria-pressed":A&&S===cb?!0:void 0,"aria-roledescription":_,"aria-describedby":m.draggable}),[r,S,x,A,_,m.draggable]);return{active:f,activatorEvent:d,activeNodeRect:h,attributes:W,isDragging:A,listeners:r?void 0:q,node:O,over:v,setNodeRef:k,setActivatorNodeRef:B,transform:D}}function YA(){return I.useContext(ob)}const XA="Droppable",JA={timeout:25};function QA(s){let{data:e,disabled:n=!1,id:r,resizeObserverConfig:i}=s;const l=Uo(XA),{active:c,dispatch:d,over:f,measureDroppableContainers:h}=I.useContext(Nc),m=I.useRef({disabled:n}),y=I.useRef(!1),v=I.useRef(null),S=I.useRef(null),{disabled:_,updateMeasurementsFor:x,timeout:A}={...JA,...i},D=zo(x??r),O=I.useCallback(()=>{if(!y.current){y.current=!0;return}S.current!=null&&clearTimeout(S.current),S.current=setTimeout(()=>{h(Array.isArray(D.current)?D.current:[D.current]),S.current=null},A)},[A]),k=$c({callback:O,disabled:_||!c}),L=I.useCallback((W,de)=>{k&&(de&&(k.unobserve(de),y.current=!1),W&&k.observe(W))},[k]),[B,q]=Rc(L),z=zo(e);return I.useEffect(()=>{!k||!B.current||(k.disconnect(),y.current=!1,k.observe(B.current))},[B,k]),I.useEffect(()=>(d({type:ln.RegisterDroppable,element:{id:r,key:l,disabled:n,node:B,rect:v,data:z}}),()=>d({type:ln.UnregisterDroppable,key:l,id:r})),[r]),I.useEffect(()=>{n!==m.current.disabled&&(d({type:ln.SetDroppableDisabled,id:r,key:l,disabled:n}),m.current.disabled=n)},[r,l,n,d]),{active:c,rect:v,isOver:f?.id===r,node:B,over:f,setNodeRef:q}}function th(s,e,n){const r=s.slice();return r.splice(n<0?r.length+n:n,0,r.splice(e,1)[0]),r}function ZA(s,e){return s.reduce((n,r,i)=>{const l=e.get(r);return l&&(n[i]=l),n},Array(s.length))}function Ic(s){return s!==null&&s>=0}function ex(s,e){if(s===e)return!0;if(s.length!==e.length)return!1;for(let n=0;n{var e;let{rects:n,activeNodeRect:r,activeIndex:i,overIndex:l,index:c}=s;const d=(e=n[i])!=null?e:r;if(!d)return null;const f=rx(n,c,i);if(c===i){const h=n[l];return h?{x:ii&&c<=l?{x:-d.width-f,y:0,...jc}:c=l?{x:d.width+f,y:0,...jc}:{x:0,y:0,...jc}};function rx(s,e,n){const r=s[e],i=s[e-1],l=s[e+1];return!r||!i&&!l?0:n{let{rects:e,activeIndex:n,overIndex:r,index:i}=s;const l=th(e,r,n),c=e[i],d=l[i];return!d||!c?null:{x:d.left-c.left,y:d.top-c.top,scaleX:d.width/c.width,scaleY:d.height/c.height}},Hc={scaleX:1,scaleY:1},ax=s=>{var e;let{activeIndex:n,activeNodeRect:r,index:i,rects:l,overIndex:c}=s;const d=(e=l[n])!=null?e:r;if(!d)return null;if(i===n){const h=l[c];return h?{x:0,y:nn&&i<=c?{x:0,y:-d.height-f,...Hc}:i=c?{x:0,y:d.height+f,...Hc}:{x:0,y:0,...Hc}};function ix(s,e,n){const r=s[e],i=s[e-1],l=s[e+1];return r?nr.map(q=>typeof q=="object"&&"id"in q?q.id:q),[r]),_=c!=null,x=c?S.indexOf(c.id):-1,A=h?S.indexOf(h.id):-1,D=I.useRef(S),O=!ex(S,D.current),k=A!==-1&&x===-1||O,L=tx(l);Fr(()=>{O&&_&&m(S)},[O,S,_,m]),I.useEffect(()=>{D.current=S},[S]);const B=I.useMemo(()=>({activeIndex:x,containerId:y,disabled:L,disableTransforms:k,items:S,overIndex:A,useDragOverlay:v,sortedRects:ZA(S,f),strategy:i}),[x,y,L.draggable,L.droppable,k,S,A,f,v,i]);return Xe.createElement(db.Provider,{value:B},e)}const ox=s=>{let{id:e,items:n,activeIndex:r,overIndex:i}=s;return th(n,r,i).indexOf(e)},lx=s=>{let{containerId:e,isSorting:n,wasDragging:r,index:i,items:l,newIndex:c,previousItems:d,previousContainerId:f,transition:h}=s;return!h||!r||d!==l&&i===c?!1:n?!0:c!==i&&e===f},cx={duration:200,easing:"ease"},fb="transform",ux=qo.Transition.toString({property:fb,duration:0,easing:"linear"}),dx={roleDescription:"sortable"};function fx(s){let{disabled:e,index:n,node:r,rect:i}=s;const[l,c]=I.useState(null),d=I.useRef(n);return Fr(()=>{if(!e&&n!==d.current&&r.current){const f=i.current;if(f){const h=Es(r.current,{ignoreTransform:!0}),m={x:f.left-h.left,y:f.top-h.top,scaleX:f.width/h.width,scaleY:f.height/h.height};(m.x||m.y)&&c(m)}}n!==d.current&&(d.current=n)},[e,n,r,i]),I.useEffect(()=>{l&&c(null)},[l]),l}function hx(s){let{animateLayoutChanges:e=lx,attributes:n,disabled:r,data:i,getNewIndex:l=ox,id:c,strategy:d,resizeObserverConfig:f,transition:h=cx}=s;const{items:m,containerId:y,activeIndex:v,disabled:S,disableTransforms:_,sortedRects:x,overIndex:A,useDragOverlay:D,strategy:O}=I.useContext(db),k=px(r,S),L=m.indexOf(c),B=I.useMemo(()=>({sortable:{containerId:y,index:L,items:m},...i}),[y,i,L,m]),q=I.useMemo(()=>m.slice(m.indexOf(c)),[m,c]),{rect:z,node:W,isOver:de,setNodeRef:_e}=QA({id:c,data:B,disabled:k.droppable,resizeObserverConfig:{updateMeasurementsFor:q,...f}}),{active:Se,activatorEvent:Ie,activeNodeRect:Fe,attributes:ze,setNodeRef:Et,listeners:Q,isDragging:ue,over:De,setActivatorNodeRef:ee,transform:me}=WA({id:c,data:B,attributes:{...dx,...n},disabled:k.draggable}),H=R_(_e,Et),T=!!Se,fe=T&&!_&&Ic(v)&&Ic(A),he=!D&&ue,Ae=he&&fe?me:null,ge=fe?Ae??(d??O)({rects:x,activeNodeRect:Fe,activeIndex:v,overIndex:A,index:L}):null,$e=Ic(v)&&Ic(A)?l({id:c,items:m,activeIndex:v,overIndex:A}):L,Te=Se?.id,je=I.useRef({activeId:Te,items:m,newIndex:$e,containerId:y}),xt=m!==je.current.items,rt=e({active:Se,containerId:y,isDragging:ue,isSorting:T,id:c,index:L,items:m,newIndex:je.current.newIndex,previousItems:je.current.items,previousContainerId:je.current.containerId,transition:h,wasDragging:je.current.activeId!=null}),gt=fx({disabled:!rt,index:L,node:W,rect:z});return I.useEffect(()=>{T&&je.current.newIndex!==$e&&(je.current.newIndex=$e),y!==je.current.containerId&&(je.current.containerId=y),m!==je.current.items&&(je.current.items=m)},[T,$e,y,m]),I.useEffect(()=>{if(Te===je.current.activeId)return;if(Te!=null&&je.current.activeId==null){je.current.activeId=Te;return}const Yt=setTimeout(()=>{je.current.activeId=Te},50);return()=>clearTimeout(Yt)},[Te]),{active:Se,activeIndex:v,attributes:ze,data:B,rect:z,index:L,newIndex:$e,items:m,isOver:de,isSorting:T,isDragging:ue,listeners:Q,node:W,overIndex:A,over:De,setNodeRef:H,setActivatorNodeRef:ee,setDroppableNodeRef:_e,setDraggableNodeRef:Et,transform:gt??ge,transition:at()};function at(){if(gt||xt&&je.current.newIndex===L)return ux;if(!(he&&!qf(Ie)||!h)&&(T||rt))return qo.Transition.toString({...h,property:fb})}}function px(s,e){var n,r;return typeof s=="boolean"?{draggable:s,droppable:!1}:{draggable:(n=s?.draggable)!=null?n:e.draggable,droppable:(r=s?.droppable)!=null?r:e.droppable}}function zc(s){if(!s)return!1;const e=s.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}const gx=[dt.Down,dt.Right,dt.Up,dt.Left],mx=(s,e)=>{let{context:{active:n,collisionRect:r,droppableRects:i,droppableContainers:l,over:c,scrollableAncestors:d}}=e;if(gx.includes(s.code)){if(s.preventDefault(),!n||!r)return;const f=[];l.getEnabled().forEach(y=>{if(!y||y!=null&&y.disabled)return;const v=i.get(y.id);if(v)switch(s.code){case dt.Down:r.topv.top&&f.push(y);break;case dt.Left:r.left>v.left&&f.push(y);break;case dt.Right:r.left1&&(m=h[1].id),m!=null){const y=l.get(n.id),v=l.get(m),S=v?i.get(v.id):null,_=v?.node.current;if(_&&S&&y&&v){const A=Oc(_).some((q,z)=>d[z]!==q),D=hb(y,v),O=yx(y,v),k=A||!D?{x:0,y:0}:{x:O?r.width-S.width:0,y:O?r.height-S.height:0},L={x:S.left,y:S.top};return k.x&&k.y?L:Bo(L,k)}}}};function hb(s,e){return!zc(s)||!zc(e)?!1:s.data.current.sortable.containerId===e.data.current.sortable.containerId}function yx(s,e){return!zc(s)||!zc(e)||!hb(s,e)?!1:s.data.current.sortable.index{const d=I.useId(),f=I.useRef({inProgress:!1,lastSortTime:0,lastActiveId:null}),h=q_(Iy(Jf,{activationConstraint:{distance:5}}),Iy(Yf,{coordinateGetter:mx})),m=I.useCallback(S=>{f.current={inProgress:!0,lastSortTime:Date.now(),lastActiveId:S.active.id},l?.({activeId:S.active.id})},[l]),y=I.useCallback(S=>{const{active:_,over:x}=S,A=Date.now();if(!x||_.id===x.id){f.current.inProgress=!1;return}const{lastSortTime:D,lastActiveId:O,inProgress:k}=f.current;if(O===_.id&&A-D<500&&!k)return;f.current={inProgress:!1,lastSortTime:A,lastActiveId:_.id};const L=s.findIndex(q=>String(q[e])===String(_.id)),B=s.findIndex(q=>String(q[e])===String(x.id));if(L!==-1&&B!==-1&&L!==B){const q=th(s,L,B);i?.(q,{oldIndex:L,newIndex:B})}},[s,e,i]),v=s.map(S=>String(S[e]));return yt.jsx(FA,{id:d,sensors:h,collisionDetection:F_,onDragStart:m,onDragEnd:y,children:yt.jsx(sx,{items:v,strategy:bx[n],children:r})},c!==void 0?`${d}-v${c}`:d)},pb=I.createContext(null),Sx=({value:s,children:e})=>yt.jsx(pb.Provider,{value:s,children:e}),wx=()=>I.useContext(pb),Cx=({id:s,handle:e,as:n="div",children:r})=>{const{attributes:i,listeners:l,setNodeRef:c,transform:d,transition:f,isDragging:h}=hx({id:s}),m={transform:qo.Transform.toString(d),transition:f,opacity:h?.5:1,position:"relative"};return yt.jsx(n,{ref:c,style:m,...i,...e?{}:l,"data-sortable-item":!0,"data-sortable-id":String(s),"data-dragging":h,children:yt.jsx(Sx,{value:{listeners:l,handle:e,isDragging:h},children:r})})},lt=pt("DynamicRenderer");function oa(){try{return window.G7Core?.devTools}catch{return}}function rh(s,e,n,r){if(typeof s=="string"){if(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*/.test(s))try{return e.resolveTranslations(s,n,r)}catch{return s}return s}if(Array.isArray(s))return s.map(i=>rh(i,e,n,r));if(s&&typeof s=="object"){const i={};for(const[l,c]of Object.entries(s))i[l]=rh(c,e,n,r);return i}return s}function Ex(s){const e=Object.keys(s);return e.length>0&&e.every(n=>/^\d+$/.test(n))}const ur=(s,e)=>{const n=["errors"],r={...s};for(const i of Object.keys(e)){const l=e[i],c=s[i];if(l===null){r[i]=null;continue}if(n.includes(i)){r[i]=l;continue}if(Array.isArray(l)){r[i]=l;continue}if(Array.isArray(c)&&l!==null&&typeof l=="object"&&!Array.isArray(l)&&Ex(l)){const d=Object.keys(l).map(h=>parseInt(h,10));if((d.length>0?Math.max(...d):0)>=c.length+d.length+10)r[i]={...l};else{const h=[...c];for(const[m,y]of Object.entries(l)){const v=parseInt(m,10);v>=0&&v=h.length&&(h[v]=y)}r[i]=h}}else l!==null&&typeof l=="object"&&c!==null&&typeof c=="object"&&!Array.isArray(c)?r[i]=ur(c,l):r[i]=l}return r},_x=(s,e,n,r)=>{if(!e||typeof e!="object"||Array.isArray(e))return s;const i=ur(s,e);return Ry(i,n,r)},Pc=(s,e)=>{let n=null;const r=()=>(n===null&&(n={...s}),n);for(const i of Object.keys(e)){if(!(i in s))continue;const l=e[i],c=s[i];if(l!==null&&typeof l=="object"&&!Array.isArray(l)&&c!==null&&typeof c=="object"&&!Array.isArray(c)){const d=Pc(c,l);if(d===c)continue;Object.keys(d).length===0?delete r()[i]:r()[i]=d}else delete r()[i]}return n??s},Ax=s=>{const e={},n=s.split(";").filter(r=>r.trim());for(const r of n){const i=r.indexOf(":");if(i===-1)continue;const l=r.substring(0,i).trim(),c=r.substring(i+1).trim();if(l&&c){const d=l.replace(/-([a-z])/g,(f,h)=>h.toUpperCase());e[d]=c}}return e};class xx extends I.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,n){lt.error(`컴포넌트 렌더링 에러 (ID: ${this.props.componentId}, Name: ${this.props.componentName}):`,e,n)}render(){return this.state.hasError?this.props.fallback?this.props.fallback:yt.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:[yt.jsx("div",{className:"font-semibold mb-1",children:"컴포넌트 로드 실패"}),yt.jsxs("div",{className:"text-xs opacity-80",children:[this.props.componentName&&`[${this.props.componentName}] `,"데이터를 표시할 수 없습니다."]}),this.state.error&&yt.jsxs("details",{className:"mt-2",children:[yt.jsx("summary",{className:"cursor-pointer text-xs opacity-70 hover:opacity-100",children:"상세 정보"}),yt.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 Vr=I.memo(({componentDef:s,dataContext:e,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:d,parentFormContextProp:f,parentDataContext:h,isRootRenderer:m=!1,isInsideIteration:y=!1,isEditMode:v=!1,onComponentSelect:S,onComponentHover:_,onDragStart:x,onDragEnd:A,componentPath:D,layoutKey:O})=>{const[k,L]=I.useState({loadingActions:{}});I.useLayoutEffect(()=>{d||(i.startRenderCycle(),window.__g7SetLocalOverrideKeys||(window.__g7ForcedLocalFields=void 0),window.__g7PendingLocalState=null)});const B=I.useRef(null);I.useLayoutEffect(()=>{if(!d&&e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:V,_merge:ie,...ce}=e._localInit,Z=`${JSON.stringify(ce)}:${V||"no-force"}`;if(B.current!==Z){B.current=Z;const ve=ie||"shallow",Ee=window.G7Core?.state?.get?.()?._local||{},xe=window.__g7PendingLocalState||{},Ke={...Ee,...xe};ve==="replace"?window.__g7PendingLocalState={loadingActions:Ke.loadingActions||{},...ce,hasChanges:!1}:ve==="deep"?window.__g7PendingLocalState=ur(Ke,{...ce,hasChanges:!1}):window.__g7PendingLocalState={...Ke,...ce,hasChanges:!1};const ke=window.__g7SetLocalOverrideKeys;ke&&typeof ke=="object"&&(ve==="replace"?window.__g7SetLocalOverrideKeys={...ce,hasChanges:!1}:window.__g7SetLocalOverrideKeys=ur(ke,{...ce,hasChanges:!1}))}}}),I.useLayoutEffect(()=>{if(!d){const V=window.__g7SetLocalOverrideKeys;if(V){L(ve=>Pc(ve,V));const ie=V,ce=window.__g7ForcedLocalFields,Z=window.__g7LastSetLocalSnapshot;queueMicrotask(()=>{window.__g7SetLocalOverrideKeys===ie&&(window.__g7SetLocalOverrideKeys=void 0),window.__g7ForcedLocalFields===ce&&(window.__g7ForcedLocalFields=void 0),window.__g7LastSetLocalSnapshot===Z&&(window.__g7LastSetLocalSnapshot=void 0)})}}},[e._local]);const q=I.useRef(O);I.useEffect(()=>{s._fromBase&&O&&q.current!==O&&(q.current=O,L({loadingActions:{}}))},[O,s._fromBase]);const z=I.useRef(""),W=I.useRef(!1),de=I.useRef(null),_e=I.useRef(null),Se=I.useRef({}),Ie=I.useRef({}),Fe=I.useRef(h),ze=k_(),Et=i_(),Q=Et?.getParentDataContext()??h;I.useEffect(()=>{if(e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:V,...ie}=e._localInit,ce=JSON.stringify(ie),Z=V!==void 0,ve=Nf(),pe=`${ce}:${V||"no-force"}`,Ee=h_({globalTrackedKey:ve.hash,instanceHandledKey:_e.current,trackingKey:pe});if(Ee==="apply"){_e.current=pe,ve.hash=pe,ve.timestamp=V,z.current=ce,Z&&(W.current=!0);const{_merge:Ke,...ke}=ie,Me=Ke||"shallow";L(Re=>Me==="replace"?{loadingActions:Re.loadingActions||{},...ke,hasChanges:!1}:Me==="deep"?ur(Re,{...ke,hasChanges:!1}):{...Re,...ke,hasChanges:!1}),e._globalSetState&&e._globalSetState(Re=>{const tt=Re?._local||{};let Pe;return Me==="replace"?Pe={...ke,hasChanges:!1}:Me==="deep"?Pe=ur(tt,{...ke,hasChanges:!1}):Pe={...tt,...ke,hasChanges:!1},{...Re,_local:Pe}}),i.invalidateCacheByKeys(["_local"]),lt.log("_localInit applied (data changed):",Object.keys(ie))}else if(Ee==="prune"){_e.current=pe;const{_merge:Ke,...ke}=ie;L(Re=>Pc(Re,ke)),Pc(k,ke)!==k&&(i.invalidateCacheByKeys(["_local"]),lt.log("_localInit pruned (applied by another renderer):",Object.keys(ke)))}de.current=e._localInit,d_(e._localInit)}},[e._localInit,h,i]);const{isTransitioning:ue}=Ay(),De=S_(),ee=f??De,{width:me}=jf(),H=wx(),T=I.useMemo(()=>{let V=s;if(s.type==="iterator"&&s.data){const{data:Z,itemName:ve,indexName:pe,...Ee}=s;V={...Ee,iteration:{source:Z,item_var:ve||"item",index_var:pe}}}if(!V.responsive)return V;const ie=Ci.getMatchingKey(V.responsive,me);if(!ie)return V;const ce=V.responsive[ie];return{...V,props:{...V.props,...ce.props},children:ce.children??V.children,text:ce.text??V.text,if:ce.if??V.if,iteration:ce.iteration??V.iteration,__responsiveChildrenKey:ce.children!==void 0?ie:void 0}},[s,me]),fe=I.useCallback(V=>{const ie=V?.__setStateId;if(L(ce=>{const Z=window.__g7PendingLocalState,pe=window.__g7SetLocalOverrideKeys||Z,Ee=pe?ur(ce,pe):ce;if(typeof V=="function"){const Re=V(Ee);return ur(Ee,Re)}const{__mergeMode:xe,__setStateId:Ke,...ke}=V;let Me;if(xe==="replace"?Me=ke:xe==="shallow"?Me={...Ee,...ke}:Me=ur(Ee,ke),xe!==void 0){const Re=window.__g7ForcedLocalFields;Re&&(window.__g7ForcedLocalFields={...Re,...ke})}return Me}),ie){const ce=oa();if(ce?.isEnabled()){const Z=T.id||"unknown",ve=T.name||"Unknown";setTimeout(()=>{ce.trackComponentRender?.(Z,ve,0,["_local"],[]),ce.completeStateChange?.(ie)},0)}}},[T.id,T.name]),he=d?.state??k,Ae=d?.setState??fe,se=I.useMemo(()=>{const V=e._localInit&&e._localInit!==de.current;let ie;V&&e._local?ie=e._local:ie=e._local?ur(e._local,he):he;const ce=window.__g7ForcedLocalFields;ce&&(ie=ur(ie,ce));const Z={...e,_local:ie},ve=e._computedDefinitions;if(ve&&Object.keys(ve).length>0){const pe=new $n,Ee={...Z,...ze?{_isolated:ze.state}:{}},xe={},Ke=oa(),ke=Ke?.isEnabled()??!1;for(const[Me,Re]of Object.entries(ve)){const tt=ke?Date.now():0,Pe=ke?e._computed?.[Me]:void 0;let Ve;try{if(typeof Re=="string")if(Re.startsWith("{{")&&Re.endsWith("}}")){const Ce=Re.slice(2,-2).trim(),He=Wn(Ce)?pe.evaluatePipeExpression(Ce,Ee,{skipCache:!0}):pe.evaluateExpression(Ce,Ee,{skipCache:!0});xe[Me]=He}else xe[Me]=Re;else if(Re&&typeof Re=="object"&&"$switch"in Re){const Ce=pe.resolveSwitch(Re,Ee,{skipCache:!0});xe[Me]=Ce}}catch(Ce){lt.warn(`Failed to recalculate computed value: ${Me}`,Ce),xe[Me]=e._computed?.[Me],Ve=Ce instanceof Error?Ce.message:String(Ce)}if(ke&&(Ve||Pe!==xe[Me])){const He=Date.now()-tt;Ke.trackComputedProperty?.(Me,typeof Re=="string"?Re:JSON.stringify(Re),[{type:"_local",path:"_local",value:Z._local}],xe[Me],He,T.id,Ve),Pe!==xe[Me]&&Ke.trackComputedRecalc?.(Me,"dependency-change",Pe,xe[Me],He,{type:"_local",path:"_local"},T.id)}}Z._computed=xe}if(ze&&(Z._isolated=ze.state),Q&&(Z.$parent=Q),s.extensionPointProps){const pe=i.resolveObject(s.extensionPointProps,Z,y?{skipCache:!0}:void 0);Z.extensionPointProps=v&&l?rh(pe,l,n,Z):pe}return s.extensionPointCallbacks&&(Z.extensionPointCallbacks=s.extensionPointCallbacks),v&&(Z.$templateId===void 0&&n?.templateId&&(Z.$templateId=n.templateId),Z.$locale===void 0&&n?.locale&&(Z.$locale=n.locale)),Z},[e,he,ze?.state,Q,Et?.version,s.extensionPointProps,s.extensionPointCallbacks]);Se.current=se._local,Ie.current=se._computed||{},Fe.current=Q,I.useEffect(()=>{const V=oa();if(!V?.isEnabled())return;const ie=se._local;ie&&V.updateLocalState(ie);const ce=se._computed;ce&&V.updateComputedState(ce),Q&&V.updateParentContext?.(Q);const Z=T.id||`comp-${Date.now()}`,ve=T.name||"Unknown",pe={global:Object.keys(e._global||{}),local:Object.keys(ie||{}),context:d?Object.keys(d.state||{}):[]},Ee={type:d?"componentContext":"dynamicState",hasComponentContext:!!d,parentId:d?"parent":void 0};V.trackComponentStateSource?.(Z,ve,pe,Ee),he&&Object.keys(he).length>0&&V.trackDynamicState?.(Z,he);const xe=!!(T.expandChildren||T.props?.expandChildren);V.trackContextFlow?.(Z,ve,!!d,xe,!0)},[se._local,e,T.id,T.name,d,he,T.expandChildren,T.props?.expandChildren,Q]);const ge=I.useMemo(()=>({state:{...se._local},setState:Ae,stateRef:Se,computedRef:Ie,isolatedContext:ze,parentDataContext:se}),[se._local,Ae,k,ze,se]),$e=I.useMemo(()=>{const V=fs({if:T.if,condition:T.condition,conditions:T.conditions},se,i,T.id);if(T.if||T.condition!==void 0||T.conditions){const ce=oa();ce?.isEnabled()&&T.if&&ce.trackIfCondition(T.id||`if-${Date.now()}`,T.if,V)}return V},[T.if,T.conditions,se,i,T.id]),Te=I.useMemo(()=>{if(!T.slot)return null;const V=T.slot;if(V.startsWith("{{")&&V.endsWith("}}")){const ie=V.slice(2,-2).trim();try{const ce={componentId:T.id,componentName:T.name,propName:"slot"},Z=Wn(ie)?i.evaluatePipeExpression(ie,se,void 0,ce):i.evaluateExpression(ie,se,ce);return lt.log(`[Slot] 표현식 평가: "${ie}" => "${Z}" (컴포넌트: ${T.id})`),typeof Z=="string"?Z:null}catch(ce){return lt.warn(`slot 표현식 평가 실패 (컴포넌트: ${T.id}):`,ce),null}}return lt.log(`[Slot] 정적 슬롯 ID: "${V}" (컴포넌트: ${T.id})`),V},[T.slot,T.id,se,i]),je=I.useMemo(()=>!Te||!T.id?"":`${T.id}-${Te}-${JSON.stringify(T.slotOrder??0)}`,[Te,T.id,T.slotOrder]),xt=I.useRef(null);I.useEffect(()=>{const V=window.__slotContextValue,ie=V?.isEnabled??!1;if(T.slot&<.log(`[Slot Registration] 컴포넌트: ${T.id}, isSlotEnabled: ${ie}, shouldRender: ${$e}, resolvedSlotId: ${Te}`),!ie||!$e){T.slot&<.log(`[Slot Registration] 등록 스킵 - isSlotEnabled: ${ie}, shouldRender: ${$e}`),xt.current&&T.id&&V&&(V.unregisterFromSlot(xt.current,T.id),xt.current=null);return}if(!Te||!T.id){T.slot&<.log(`[Slot Registration] 등록 스킵 - resolvedSlotId: ${Te}, id: ${T.id}`),xt.current&&T.id&&V&&(V.unregisterFromSlot(xt.current,T.id),xt.current=null);return}xt.current&&xt.current!==Te&&V.unregisterFromSlot(xt.current,T.id);const ce={...T,slot:void 0,slotOrder:void 0};return V.registerToSlot(Te,T.id,{componentDef:ce,dataContext:e,order:T.slotOrder??0,parentFormContext:f??null,getParentComponentContext:()=>ge,translationContext:n,registrationKey:je}),xt.current=Te,()=>{const Z=window.__slotContextValue;Te&&T.id&&Z&&Z.unregisterFromSlot(Te,T.id)}},[$e,Te,T,e,f,ge,n,je]);const rt=I.useCallback(V=>{if(typeof V=="string"){if(ic(V))return Yd(V);if(sc(V)){const ie=[],ce=V.replace(new RegExp(`${bo}([^${Si}]*)${Si}`,"g"),(ve,pe)=>(ie.push(pe),`${$a}${ie.length-1}${$a}`));let Z=ce;return/\$t:[a-zA-Z0-9._-]+/.test(ce)&&(Z=l.resolveTranslations(ce,n,se)),Z.replace(new RegExp(`${$a}(\\d+)${$a}`,"g"),(ve,pe)=>ie[parseInt(pe)])}if(V.startsWith("$t:defer:"))return V;if(/\$t:[a-zA-Z0-9._-]+/.test(V)){const ie=V.trim();return ie.startsWith("{")&&ie.endsWith("}")||ie.startsWith("[")&&ie.endsWith("]")?V:l.resolveTranslations(V,n,se)}return V}if(Array.isArray(V))return V.map(ie=>rt(ie));if(V&&typeof V=="object"){const ie={};for(const[ce,Z]of Object.entries(V))ie[ce]=rt(Z);return ie}return V},[l,n,se]),gt=I.useCallback(V=>yo(V),[]),at=I.useCallback(V=>La(V),[]),Yt=I.useMemo(()=>{let V={...T.props||{}};const ie=["cellChildren","expandChildren","expandContext","render"],Z=r.getMetadata(T.name)?.skipBindingKeys||[],ve=[...new Set([...ie,...Z])],pe=y?{skipCache:!0}:void 0,Ee={...pe??{},skipBindingKeys:ve},xe=Ce=>{if(pe)return pe;if(Ce.startsWith("_computed")||Ce.startsWith("$computed"))return{skipCache:!0}};for(const[Ce,He]of Object.entries(V))if(!ve.includes(Ce))if(typeof He=="string"){const nt=at(He);if(nt!==null){let Lt=!1,Bt=nt;nt.startsWith(sr)&&(Lt=!0,Bt=nt.slice(sr.length));const Nn={componentId:T.id,componentName:T.name,propName:Ce};let Gt;if(Wn(Bt))try{Gt=i.evaluatePipeExpression(Bt,se,xe(Bt),Nn)}catch(Ft){lt.warn(`파이프 표현식 평가 실패 (컴포넌트: ${T.id}, prop: ${Ce}):`,Ft),Gt=void 0}else if(gt(Bt))try{Gt=i.evaluateExpression(Bt,se,Nn)}catch(Ft){lt.warn(`표현식 평가 실패 (컴포넌트: ${T.id}, prop: ${Ce}):`,Ft),Gt=void 0}else Gt=i.resolve(Bt,se,xe(Bt),Nn);V[Ce]=Lt&&Gt!=null?ds(Gt):Gt}else{const Lt={componentId:T.id,componentName:T.name,propName:Ce};V[Ce]=i.resolveBindings(He,se,pe,Lt)}}else Array.isArray(He)?V[Ce]=He.map(nt=>typeof nt=="string"?i.resolveBindings(nt,se,pe):typeof nt=="object"&&nt!==null?i.resolveObject(nt,se,Ee):nt):He&&typeof He=="object"&&(V[Ce]=i.resolveObject(He,se,Ee));for(const[Ce,He]of Object.entries(V))V[Ce]=rt(He);if(typeof V.style=="string"&&(V.style=Ax(V.style)),V=cf(V,v?void 0:T.actions,se,{componentContext:ge,actionDispatcher:c}),T.classMap){const Ce=K0(T.classMap,se,i,{skipCache:!0});if(Ce){const He=V.className||"";V.className=He?`${He} ${Ce}`:Ce}}T.style&&(V.style=T.style),T.actions&&T.actions.length>0&&T.type==="composite"&&Object.assign(V,he),T.component_layout&&(V.__componentLayoutDefs=T.component_layout);const Ke=T.expandChildren||T.props?.expandChildren,ke=T.props?.cellChildren,Me=T.children&&T.children.length>0,Re=T.component_layout,tt=T.slot,Pe=T.props?.modalId,Ve=T.type==="composite";return(Ke||ke||Me||Re||tt||Pe||Ve)&&(V.__componentContext=ge),V},[T.props,T.actions,T.style,T.classMap,T.id,se,n,i,l,ge,he,rt,gt,at,y]),Ht=I.useRef(null),bt=I.useMemo(()=>Ht.current&&Ty(Ht.current,Yt)?Ht.current:(Ht.current=Yt,Yt),[Yt]),qe=I.useMemo(()=>{const V=T.id;if(typeof V!="string"||!V.includes("{{"))return V;const ie=i.resolveBindings(V,se,{skipCache:!0});return typeof ie=="string"?ie:V},[T.id,se,i]),mt=I.useMemo(()=>{const V=T.dataKey,ie=T.trackChanges,ce=T.debounce;if(V){const Z=V.startsWith("_global."),ve=Z?V.slice(8):V,pe=Z?e._global:se._local;return{dataKey:ve,trackChanges:ie??!1,debounce:ce,setState:Z?xe=>{e._globalSetState?e._globalSetState(xe):lt.warn("_global.formData 사용 시 _globalSetState가 필요합니다.")}:Ae,state:pe??{},_isGlobal:Z}}if(ee.dataKey)return ee},[T.dataKey,T.trackChanges,T.debounce,T.id,Ae,se._local,e._global,e._globalSetState,ee]),Dt=I.useRef(new Set);I.useEffect(()=>{Dt.current.clear()},[e._global?._remountKeys]);const zt=I.useCallback((V,ie)=>{const ce=e._global?._remountKeys;return V&&ce?.[V]&&!Dt.current.has(V)?(Dt.current.add(V),`${V}-remount-${ce[V]}`):V||ie},[e._global?._remountKeys]),kn=I.useMemo(()=>{if(T.text!==void 0){if(typeof T.text=="string"){const V=T.text;let ie=V;const ce={componentId:T.id,componentName:T.name,propName:"text",skipCache:!0},Z=at(V);if(Z!==null){let ve=!1,pe=Z;if(Z.startsWith(sr)&&(ve=!0,pe=Z.slice(sr.length)),Wn(pe))try{ie=i.evaluatePipeExpression(pe,se,{skipCache:!0},ce)}catch(Ee){lt.warn(`text 파이프 표현식 평가 실패 (컴포넌트: ${T.id}):`,Ee),ie=""}else if(gt(pe))try{ie=i.evaluateExpression(pe,se,ce)}catch(Ee){lt.warn(`text 표현식 평가 실패 (컴포넌트: ${T.id}):`,Ee),ie=""}else ie=i.resolve(pe,se,{skipCache:!0},ce);ve&&ie!=null&&(ie=ds(ie))}else V.includes("{{")&&(ie=i.resolveBindings(V,se,{skipCache:!0},ce));return ie=rt(ie),ie??""}return T.text}return!T.children||T.children.length===0?null:T.children.map((V,ie)=>{if(typeof V=="string")return V;const ce=T.__responsiveChildrenKey,Z=ce?`responsive.${ce}.children`:"children",ve=D?`${D}.${Z}.${ie}`:`${ie}`,pe=V._fromBase?V.id||`child-${ie}`:zt(V.id,`child-${ie}`),Ee=!V._fromBase&&O?`${pe}_${O}`:pe;return yt.jsx(Vr,{componentDef:V,dataContext:se,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:ge,parentFormContextProp:mt,isInsideIteration:y,isEditMode:v,onComponentSelect:S,onComponentHover:_,componentPath:ve,onDragStart:x,onDragEnd:A,layoutKey:O},Ee)})},[T.text,T.children,T.id,e,se,n,r,i,l,c,ge,mt,at,gt,rt,zt,y,v,S,_,D,x,A,O]),dr=I.useMemo(()=>{if(!T.iteration)return null;try{const V=lf(T.iteration.source,se,i);if(!Array.isArray(V))return lt.warn(`iteration source가 배열이 아닙니다 (컴포넌트: ${T.id}):`,V),null;const ie=oa();return ie?.isEnabled()&&ie.trackIteration(T.id||`iteration-${Date.now()}`,T.iteration.source,T.iteration.item_var,T.iteration.index_var,V.length),V.map((ce,Z)=>{const ve={...se,[T.iteration.item_var]:ce,[`${T.iteration.item_var}_index`]:Z};T.iteration.index_var&&(ve[T.iteration.index_var]=Z);const pe=Z===0||Z===V.length-1;ie?.isEnabled()&&pe&&ie.trackNestedContext?.({componentId:`${T.id||"unknown"}-iter-${Z}`,componentType:"iteration",parentContext:{available:Object.keys(se),values:{}},ownContext:{added:[T.iteration.item_var,...T.iteration.index_var?[T.iteration.index_var]:[]],values:{[T.iteration.item_var]:ce,...T.iteration.index_var?{[T.iteration.index_var]:Z}:{}}},depth:1});const Ee={...T,iteration:void 0,responsive:void 0},xe=D?`${D}.iteration.${Z}`:`iteration.${Z}`,Ke=`${zt(T.id,"item")}-${Z}`;return yt.jsx(Vr,{componentDef:Ee,dataContext:ve,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:ge,parentFormContextProp:mt,isInsideIteration:!0,isEditMode:v,onComponentSelect:S,onComponentHover:_,componentPath:xe,onDragStart:x,onDragEnd:A,layoutKey:O},Ke)})}catch(V){return lt.error(`iteration 렌더링 실패 (컴포넌트: ${T.id}):`,V),null}},[T.iteration,T.children,T.id,e,se,n,r,i,l,c,ge,mt,zt,v,S,_,D,x,A,O]),[Ot,$i]=I.useState(0),ua=I.useMemo(()=>{if(!T.sortable||!T.itemTemplate)return null;const{sortable:V,itemTemplate:ie}=T;try{const ce=lf(V.source,se,i);if(!Array.isArray(ce))return lt.warn(`sortable source가 배열이 아닙니다 (컴포넌트: ${T.id}):`,ce),null;if(ce.length===0)return null;const Z=V.itemKey||"id",ve=V.strategy||"verticalList",pe=V.itemVar||"$item",Ee=V.indexVar||"$index",xe=V.handle,Ke=V.wrapperElement,ke=(tt,Pe)=>{const Ve=T.actions?.filter(Ce=>Ce.event==="onSortEnd"||Ce.type==="onSortEnd");if($i(Ce=>Ce+1),Ve&&Ve.length>0&&c){const Ce={...se,$sortedItems:tt,$sortEvent:Pe};Ve.forEach(He=>{try{const nt=c.createHandler(He,Ce,ge),Lt=new Event("sortend");nt(Lt)}catch(nt){lt.error(`onSortEnd action failed: ${He.handler}`,nt)}})}},Me=tt=>{const Pe=T.actions?.filter(Ve=>Ve.event==="onSortStart"||Ve.type==="onSortStart");if(Pe&&Pe.length>0&&c){const Ve={...se,$activeId:tt.activeId};Pe.forEach(Ce=>{try{const He=c.createHandler(Ce,Ve,ge),nt=new Event("sortstart");He(nt)}catch(He){lt.error(`onSortStart action failed: ${Ce.handler}`,He)}})}},Re=ce.map((tt,Pe)=>{const Ve=String(tt[Z]),Ce={...se,[pe]:tt,[Ee]:Pe},He=D?`${D}.sortable.${Pe}`:`sortable.${Pe}`,nt=`${zt(T.id,"sortable-item")}-v${Ot}-${Ve}`;return yt.jsx(Cx,{id:Ve,handle:xe,...Ke?{as:Ke}:{},children:(Ke&&ie.children?ie.children:[ie]).map((Lt,Bt)=>yt.jsx(Vr,{componentDef:Lt,dataContext:Ce,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:ge,parentFormContextProp:void 0,isInsideIteration:!0,isEditMode:v,onComponentSelect:S,onComponentHover:_,componentPath:He,onDragStart:x,onDragEnd:A,layoutKey:O},`${nt}-child-${Bt}`))},nt)});return yt.jsx(vx,{items:ce,itemKey:Z,strategy:ve,onSortEnd:ke,onSortStart:Me,sortVersion:Ot,children:Re})}catch(ce){return lt.error(`sortable 렌더링 실패 (컴포넌트: ${T.id}):`,ce),null}},[T.sortable,T.itemTemplate,T.actions,T.id,e,se,n,r,i,l,c,ge,zt,v,S,_,D,x,A,Ot,O]),bn=I.useRef(!1);I.useEffect(()=>{if(bn.current)return;bn.current=!0;const V=oa();if(V?.isEnabled()&&V.trackMount(s.id,{name:s.name,type:s.type||"component",props:bt}),s.lifecycle?.onMount&&s.lifecycle.onMount.length>0)for(const ce of s.lifecycle.onMount)try{const Z=c.createHandler(ce,se,ge),ve=new Event("mount");Z(ve),lt.log(`Lifecycle onMount executed: ${ce.handler} (Component: ${s.id})`)}catch(Z){lt.error(`Lifecycle onMount failed: ${ce.handler} (Component: ${s.id})`,Z)}const ie=[];if(s.onComponentEvent&&s.onComponentEvent.length>0){const ce=window.G7Core;if(ce?.componentEvent?.on)for(const Z of s.onComponentEvent){if(!Z.event){lt.warn(`onComponentEvent: event name is required (Component: ${s.id})`);continue}const ve=async Ee=>{try{const xe={...se,_eventData:Ee},ke=await c.createHandler({handler:Z.handler,params:Z.params,onSuccess:Z.onSuccess,onError:Z.onError},xe,ge)(new CustomEvent(Z.event,{detail:Ee}));return lt.log(`onComponentEvent "${Z.event}" handled: ${Z.handler} (Component: ${s.id})`,{eventData:Ee,result:ke}),ke}catch(xe){throw lt.error(`onComponentEvent "${Z.event}" failed: ${Z.handler} (Component: ${s.id})`,xe),xe}},pe=ce.componentEvent.on(Z.event,ve);ie.push(pe),lt.log(`onComponentEvent: Subscribed to "${Z.event}" (Component: ${s.id})`)}else lt.warn(`onComponentEvent: G7Core.componentEvent is not available (Component: ${s.id})`)}return()=>{const ce=oa();ce?.isEnabled()&&ce.trackUnmount(s.id);for(const Z of ie)try{Z()}catch(ve){lt.error(`onComponentEvent: Failed to unsubscribe (Component: ${s.id})`,ve)}if(ie.length>0&<.log(`onComponentEvent: Unsubscribed ${ie.length} event(s) (Component: ${s.id})`),s.lifecycle?.onUnmount&&s.lifecycle.onUnmount.length>0)for(const Z of s.lifecycle.onUnmount)try{const ve=c.createHandler(Z,se,ge),pe=new Event("unmount");ve(pe),lt.log(`Lifecycle onUnmount executed: ${Z.handler} (Component: ${s.id})`)}catch(ve){lt.error(`Lifecycle onUnmount failed: ${Z.handler} (Component: ${s.id})`,ve)}}},[]);const Mn=I.useMemo(()=>{const V=bt.dataKey,ie=bt.trackChanges,ce=bt.debounce;return V?{dataKey:V,trackChanges:ie??!1,debounce:ce,setState:Ae,state:he}:null},[bt.dataKey,bt.trackChanges,bt.debounce,Ae,he]);I.useEffect(()=>{const V=T.dataKey||bt.dataKey;if(!V)return;const ie=oa();if(!ie?.isEnabled())return;const ce=[],Z=pe=>{if(pe)for(const Ee of pe){const xe=Ee?.props?.name;if(xe&&ce.push({name:xe,type:Ee.name||Ee.type||"unknown"}),Ee?.children&&Z(Ee.children),Ee?.slots)for(const Ke of Object.values(Ee.slots))Array.isArray(Ke)&&Z(Ke)}};if(s.children&&Z(s.children),s.slots)for(const pe of Object.values(s.slots))Array.isArray(pe)&&Z(pe);const ve=s.id||`form-${V}`;return ie.trackForm(ve,V,ce),()=>{ie.untrackForm(ve)}},[T,bt.dataKey,s.id,s.children]);const it=I.useRef(null),Pn=I.useRef(void 0);I.useEffect(()=>{const V=bt?.name;if(!V||!ee.dataKey||!ee.setState||bt?.autoBinding===!1)return;const ie=`${ee.dataKey}.${V}`,ce=window.__g7AutoBindingPaths??new Map;return window.__g7AutoBindingPaths=ce,ce.set(ie,(ce.get(ie)??0)+1),()=>{const Z=ce.get(ie)??0;Z<=1?ce.delete(ie):ce.set(ie,Z-1)}},[bt?.name,bt?.autoBinding,ee.dataKey,ee.setState]);const vn=I.useMemo(()=>{const{dataKey:V,trackChanges:ie,debounce:ce,...Z}=bt,ve=Z.name;if(!ve||!ee.dataKey||!ee.setState)return Z;if(Z.autoBinding===!1){const{autoBinding:Ve,...Ce}=Z;return Ce}const pe=`${ee.dataKey}.${ve}`,Ee=w_(ee.state,pe),xe=Ee!==void 0?Ee:Z.value,ke=r.getMetadata(s.name)?.bindingType,Me=typeof xe=="boolean"&&(ke==="checked"||ke==="checkable"&&["checkbox","radio"].includes(Z?.type)),Re=ee.debounce,tt=Ve=>{const Ce=ee.state||{},He=Ry(Ce,pe,Ve);if(ee.trackChanges&&(He.hasChanges=!0),window.__g7PendingLocalState=_x(He,window.__g7ForcedLocalFields,pe,Ve),ee.setState(He),ee._isGlobal)return;const nt=window.G7Core,Lt={[pe]:Ve};ee.trackChanges&&(Lt.hasChanges=!0),nt?.state?.setLocal?.(Lt,{render:!1})},Pe=(Ve,Ce)=>{Re&&Re>0?(it.current&&clearTimeout(it.current),it.current=setTimeout(()=>{tt(Ve),it.current=null,Ce&&(Ce(),window.__g7PendingLocalState=null)},Re)):(tt(Ve),Ce&&(Ce(),window.__g7PendingLocalState=null))};if(Me)return{...Z,checked:xe,onChange:Ce=>{const He=Ce.target.checked;tt(He),Z.onChange&&Z.onChange(Ce)}};{const Ve=He=>{const nt=He?.target?.value!==void 0?He.target.value:He;Re&&Re>0&&(Pn.current=nt);const Lt=He?.target?{target:{value:nt,name:He.target.name,type:He.target.type,checked:He.target.checked},currentTarget:He.currentTarget?{value:nt,name:He.currentTarget.name}:void 0}:He;Pe(nt,()=>{Z.onChange&&Z.onChange(Lt)})};let Ce;return Pn.current!==void 0?it.current!==null?Ce=Pn.current:String(xe??"")===String(Pn.current)?(Pn.current=void 0,Ce=xe??""):Ce=Pn.current:Ce=xe??"",{...Z,value:Ce,onChange:Ve}}},[bt,ee,ee.state,ee.debounce]),da=I.useMemo(()=>{const V=oa();if(V?.isEnabled()&&V.trackRender(s.name),!$e)return T.iteration?dr:null;if(T.sortable&&T.itemTemplate)return ua;if(T.iteration)return dr;if(T.type==="extension_point"){const{layout:ke,columns:Me,gap:Re,className:tt,...Pe}=T.props||{};let Ve=tt||"";return ke==="grid"&&Me?Ve=`${Ve} grid grid-cols-${Me} gap-${Re||4}`.trim():ke==="flex"&&(Ve=`${Ve} flex flex-col gap-${Re||4}`.trim()),yt.jsx("div",{id:qe,className:Ve||void 0,...Pe,children:kn})}const ie=r.getComponent(T.name);if(!ie)return lt.error(`컴포넌트를 찾을 수 없습니다: ${T.name} (ID: ${T.id})`,"componentDef:",JSON.stringify(T,null,2)),null;const ce=e._global?._remountKeys,Z={...vn,id:vn.id??qe,...ce&&Object.keys(ce).length>0&&{__remountTrigger:JSON.stringify(ce)}};if(H?.listeners&&H.handle&&vn["data-drag-handle"]!==void 0&&(Object.assign(Z,H.listeners),Z.style={...Z.style,cursor:H.isDragging?"grabbing":"grab"}),v){const ke=T.id||`auto_${T.name||T.type||"unknown"}_${Math.random().toString(36).substring(2,8)}`,Me=Pe=>{typeof Pe.preventDefault=="function"&&Pe.preventDefault(),S&&(Pe.stopPropagation(),S(ke,Pe))},Re={"data-editor-id":ke,"data-editor-name":T.name,"data-editor-type":T.type,onClick:Me};D&&(Re["data-editor-path"]=D);const tt=T.__editorSlotName??T.slot;typeof tt=="string"&&(Re["data-editor-slot"]=tt),_&&(Re.onMouseMove=Pe=>{Pe.stopPropagation(),_(ke,Pe)},Re.onMouseLeave=Pe=>{_(null,Pe)}),Object.assign(Z,Re),Z.editorAttrs=Re}const ve=T.type==="basic",pe=T.type==="layout",xe=ve||pe?(()=>{const ke={};for(const[Me,Re]of Object.entries(Z))Me.startsWith("__")||Me==="editorAttrs"&&ve||(ke[Me]=Re);return ke})():Z;let Ke=yt.jsx(ie,{...xe,children:kn});if(mt&&(Ke=yt.jsx(v_,{value:mt,children:Ke})),T.isolatedState){const ke=typeof T.isolatedState=="object"?T.isolatedState:{},Me=e?._isolatedInit,Re=Me?{...ke,...Me}:ke;Ke=yt.jsx(T_,{initialState:Re,scopeId:T.isolatedScopeId,children:Ke})}return Ke},[$e,T.iteration,T.sortable,T.itemTemplate,T.type,T.name,T.id,T.props,T.isolatedState,T.isolatedScopeId,r,vn,kn,dr,ua,H,Mn,v,S,_,x,A,D,e._global?._remountKeys]),fr=I.useMemo(()=>{const V=T.blur_until_loaded;if(!V||e?._global?.__isPreview)return!1;if(typeof V=="string"){const Z=at(V);if(Z!==null)try{const ve={componentId:T.id,componentName:T.name,propName:"blur_until_loaded"};return!!i.evaluateExpression(Z,se,ve)}catch(ve){return lt.warn(`blur_until_loaded 표현식 평가 실패 (컴포넌트: ${T.id}):`,ve),!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(Ee=>e[Ee]===void 0);if(ue)return!0;const Z=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(pe=>!Z.includes(pe)&&!pe.startsWith("_")).some(pe=>e[pe]===void 0)}if(ue)return!0;const ie=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(Z=>!ie.includes(Z)&&!Z.startsWith("_")).some(Z=>e[Z]===void 0)},[T.blur_until_loaded,T.id,ue,e,se,i,at]);if(fr){const V=T.blur_until_loaded;if(typeof V=="object"&&V?.data_sources){const ce=(Array.isArray(V.data_sources)?V.data_sources:[V.data_sources]).reduce((ve,pe)=>(ve[pe]=e[pe]===void 0?"UNDEFINED":"LOADED",ve),{}),Z=Object.keys(e).filter(ve=>!ve.startsWith("_"));lt.log(`[BLUR APPLIED] Component: ${T.id}, data_sources status:`,ce,"Available keys:",Z)}else lt.log(`[BLUR APPLIED] Component: ${T.id}, blur_until_loaded:`,V)}const un=I.useMemo(()=>{if(!T.blur_until_loaded)return{wrapperClasses:"",innerClasses:""};const V=Yt?.className||"";if(!V)return{wrapperClasses:"",innerClasses:""};const ie=[/^(sm:|md:|lg:|xl:|2xl:)?(col-span-|row-span-|col-start-|col-end-|row-start-|row-end-)/,/^(sm:|md:|lg:|xl:|2xl:)?(self-|place-self-|order-)/,/^(sm:|md:|lg:|xl:|2xl:)?(flex-shrink|flex-grow|flex-\d|basis-)/],ce=V.split(/\s+/).filter(Boolean),Z=[],ve=[];for(const pe of ce)ie.some(xe=>xe.test(pe))?Z.push(pe):ve.push(pe);return{wrapperClasses:Z.join(" "),innerClasses:ve.join(" ")}},[T.blur_until_loaded,Yt?.className]),Rn=window.__slotContextValue;return Te&&Rn?.isEnabled?null:yt.jsx(xx,{componentId:s.id,componentName:s.name,children:T.blur_until_loaded?yt.jsx("div",{className:[un.wrapperClasses,fr?"opacity-50 blur-sm transition-all duration-300 pointer-events-none":void 0].filter(Boolean).join(" ")||void 0,children:da}):da})});Vr.displayName="DynamicRenderer",typeof window<"u"&&(window.__DynamicRenderer=Vr);function Tx(s){const e={};try{const r=new URL(s,typeof window<"u"?window.location.origin:"http://localhost").searchParams,i=new Set;for(const l of r.keys()){if(i.has(l))continue;i.add(l);const c=r.getAll(l);c.length>1||l.endsWith("[]")?e[l]=c:e[l]=c[0]}}catch{}return e}function kx(s){try{return new URL(s,typeof window<"u"?window.location.origin:"http://localhost").pathname}catch{return s.split("?")[0]}}const Li=class Li{constructor(){M(this,"config",{enabled:!1,maxHistorySize:100,logLevel:"info",serverEndpoint:"/_boost/g7-debug/dump-state",autoCapture:!0});M(this,"stateHistory",[]);M(this,"snapshotIdCounter",0);M(this,"stateWatchers",new Map);M(this,"currentLocalState",{});M(this,"currentComputedState",{});M(this,"currentParentContext");M(this,"actionHistory",[]);M(this,"actionWatchers",new Set);M(this,"cacheStats",{hits:0,misses:0,entries:0});M(this,"cacheDecisions",[]);M(this,"cacheDecisionIdCounter",0);M(this,"maxCacheDecisions",200);M(this,"currentRenderCycleId",null);M(this,"isInActionExecution",!1);M(this,"isInIteration",!1);M(this,"mountedComponents",new Map);M(this,"eventListeners",new Map);M(this,"mountWatchers",new Set);M(this,"unmountWatchers",new Set);M(this,"renderCounts",new Map);M(this,"bindingEvalCount",0);M(this,"profilingData",[]);M(this,"isProfiling",!1);M(this,"profilingStartTime",0);M(this,"activeRequests",new Map);M(this,"requestHistory",[]);M(this,"pendingDataSources",new Set);M(this,"requestWatchers",new Set);M(this,"wsConnections",new Map);M(this,"wsMessageHistory",[]);M(this,"wsMessageWatchers",new Set);M(this,"ifConditions",new Map);M(this,"iterations",new Map);M(this,"conditionWatchers",new Set);M(this,"forms",new Map);M(this,"formWatchers",new Set);M(this,"expressionHistory",[]);M(this,"expressionWatchers",new Set);M(this,"expressionIdCounter",0);M(this,"dataSources",new Map);M(this,"dataPathTransforms",[]);M(this,"maxDataPathTransforms",100);M(this,"nestedContexts",[]);M(this,"nestedContextIdCounter",0);M(this,"maxNestedContexts",100);M(this,"formBindingIssues",[]);M(this,"formBindingValidations",[]);M(this,"formBindingIssueIdCounter",0);M(this,"maxFormBindingIssues",100);M(this,"computedProperties",new Map);M(this,"computedRecalcLogs",[]);M(this,"computedRecalcIdCounter",0);M(this,"maxComputedRecalcLogs",100);M(this,"handlers",new Map);M(this,"componentEventSubscriptions",new Map);M(this,"componentEventEmitHistory",[]);M(this,"componentEventIdCounter",0);M(this,"maxComponentEventHistory",100);M(this,"stateRenderingLogs",[]);M(this,"currentStateChangeContext",null);M(this,"stateRenderingIdCounter",0);M(this,"componentRenderCounts",new Map);M(this,"stateToComponentMap",new Map);M(this,"maxStateRenderingLogs",100);M(this,"componentStateSources",new Map);M(this,"contextFlowNodes",new Map);M(this,"dynamicStates",new Map);M(this,"styleIssues",[]);M(this,"componentStyles",new Map);M(this,"authEvents",[]);M(this,"authHeaderHistory",[]);M(this,"authEventIdCounter",0);M(this,"maxAuthEventHistory",50);M(this,"logHistory",[]);M(this,"logIdCounter",0);M(this,"maxLogHistory",500);M(this,"currentLayout",null);M(this,"layoutHistory",[]);M(this,"layoutIdCounter",0);M(this,"layoutStats",{totalLoads:0,cacheHits:0,apiLoads:0});M(this,"maxLayoutHistory",50);M(this,"executionDetails",new Map);M(this,"stateChangeHistory",[]);M(this,"dataSourceChangeHistory",[]);M(this,"changeAlerts",[]);M(this,"changeExpectations",new Map);M(this,"executionIdCounter",0);M(this,"stateChangeIdCounter",0);M(this,"alertIdCounter",0);M(this,"maxExecutionDetails",100);M(this,"maxStateChangeHistory",200);M(this,"maxChangeAlerts",100);M(this,"sequenceExecutions",[]);M(this,"sequenceExecutionStack",[]);M(this,"sequenceIdCounter",0);M(this,"maxSequenceExecutions",50);M(this,"staleClosureWarnings",[]);M(this,"staleClosureIdCounter",0);M(this,"maxStaleClosureWarnings",100);M(this,"stateCaptureRegistry",new Map);M(this,"modalStates",new Map);M(this,"modalStateIssues",[]);M(this,"modalStateRelations",[]);M(this,"modalStateChangeLogs",[]);M(this,"modalStateIssueIdCounter",0);M(this,"modalStateChangeLogIdCounter",0);M(this,"maxModalStateIssues",100);M(this,"maxModalStateChangeLogs",200);M(this,"namedActionDefinitions",{});M(this,"namedActionRefLogs",[]);M(this,"namedActionRefIdCounter",0);M(this,"maxNamedActionRefLogs",200);M(this,"debounceActionHistory",[]);M(this,"dataSourceUpdateHistory",[]);M(this,"debounceActionIdCounter",0);M(this,"dataSourceUpdateIdCounter",0)}static getInstance(){return Li.instance||(Li.instance=new Li),Li.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 r=window.G7Core?.state?.get?.();return r?.settings?.advanced?.debug_mode===!0||r?._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 n={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(n),this.stateHistory.length>this.config.maxHistorySize&&this.stateHistory.shift(),this.notifyStateWatchers(n)}getState(){try{const e=window.G7Core,n=e?.state?.get?.()||{},r={};if(e?._isolatedStates&&typeof e._isolatedStates=="object")for(const[i,l]of Object.entries(e._isolatedStates))r[i]=this.sanitizeObject(l);return{_global:n._global||n,_local:this.currentLocalState,_computed:this.currentComputedState,_isolated:Object.keys(r).length>0?r: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 n={};try{n=(window.G7Core?.state?.get?.()||{})._local||{}}catch{n={}}const r=this.findMismatchedLeafPaths(e,n);return{hasMismatch:r.length>0,mismatchedPaths:r,storageA:e,storageB:n}}findMismatchedLeafPaths(e,n,r=""){const i=[],l=new Set([...Object.keys(e||{}),...Object.keys(n||{})]);for(const c of l){const d=r?`${r}.${c}`:c,f=e?.[c],h=n?.[c],m=f&&typeof f=="object"&&!Array.isArray(f),y=h&&typeof h=="object"&&!Array.isArray(h);if(m&&y)i.push(...this.findMismatchedLeafPaths(f,h,d));else{const v=f===void 0?"__undefined__":JSON.stringify(f),S=h===void 0?"__undefined__":JSON.stringify(h);v!==S&&i.push(d)}}return i}watchState(e,n){return this.stateWatchers.has(e)||this.stateWatchers.set(e,new Set),this.stateWatchers.get(e).add(n),()=>{this.stateWatchers.get(e)?.delete(n)}}notifyStateWatchers(e){if(this.stateWatchers.get("*")?.forEach(n=>{try{n(e.next,e.prev,"*")}catch(r){console.error("[G7DevTools] State watcher error:",r)}}),e.diff)for(const n of e.diff.changed)this.stateWatchers.get(n.path)?.forEach(r=>{try{r(n.newValue,n.oldValue,n.path)}catch(i){console.error("[G7DevTools] State watcher error:",i)}})}diffSnapshots(e,n){const r=this.stateHistory.find(l=>l.id===e),i=this.stateHistory.find(l=>l.id===n);return!r||!i?null:this.calculateDiff(r.next,i.next)}calculateDiff(e,n,r=""){const i={added:[],removed:[],changed:[]},l=new Set(Object.keys(e)),c=new Set(Object.keys(n));for(const d of c){const f=r?`${r}.${d}`:d;l.has(d)?JSON.stringify(e[d])!==JSON.stringify(n[d])&&i.changed.push({path:f,oldValue:e[d],newValue:n[d]}):i.added.push(f)}for(const d of l){const f=r?`${r}.${d}`:d;c.has(d)||i.removed.push(f)}return i}logAction(e){if(!this.config.enabled)return;const n=this.actionHistory.findIndex(r=>r.id===e.id);n>=0?this.actionHistory[n]={...this.actionHistory[n],...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(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Action watcher error:",r)}})}getActionMetrics(){const e=this.actionHistory.filter(l=>l.status==="success"),n=this.actionHistory.filter(l=>l.status==="error"),r={};for(const l of this.actionHistory)r[l.type]=(r[l.type]||0)+1;const i=e.reduce((l,c)=>l+(c.duration||0),0);return{totalActions:this.actionHistory.length,successCount:e.length,errorCount:n.length,averageDuration:e.length>0?i/e.length:0,actionsByType:r}}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 n={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(n),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 n=0,r=0,i=0,l=0;const c={},d={};for(const h of e)h.decision==="cache_hit"?n++:h.decision==="cache_miss"?r++:h.decision==="skip_cache"?i++:h.decision==="invalidate"&&l++,c[h.reason]=(c[h.reason]||0)+1,h.context.componentId&&(d[h.context.componentId]=(d[h.context.componentId]||0)+1);const f=n+r+i;return{totalDecisions:e.length,cacheHits:n,cacheMisses:r,skipCacheCount:i,invalidateCount:l,byReason:c,byComponent:d,avgHitRate:f>0?n/f:0}}getRecentCacheDecisions(e=20,n){let r=[...this.cacheDecisions];return n&&(r=r.filter(i=>i.decision===n)),r.slice(-e)}clearCacheDecisionData(){this.cacheDecisions=[],this.cacheDecisionIdCounter=0}summarizePropsForLifecycle(e){if(!e||typeof e!="object")return e;const n={},r=["children","ref","key"];for(const[i,l]of Object.entries(e))if(!r.includes(i))if(l==null)n[i]=l;else if(Array.isArray(l))n[i]=`[Array(${l.length})]`;else if(typeof l=="object"){const c=Object.keys(l);c.length<=3?n[i]=`{${c.join(", ")}}`:n[i]=`{${c.slice(0,3).join(", ")}, ... +${c.length-3}}`}else typeof l=="string"&&l.length>50?n[i]=l.substring(0,50)+"...":typeof l=="function"?n[i]="[Function]":n[i]=l;return n}trackMount(e,n){if(!this.config.enabled)return;const r=this.summarizePropsForLifecycle(n.props),i={...n,props:r,id:e,mountTime:Date.now()};this.mountedComponents.set(e,i),this.mountWatchers.forEach(l=>{try{l({componentId:e,componentName:n.name,timestamp:i.mountTime})}catch(c){console.error("[G7DevTools] Mount watcher error:",c)}})}trackUnmount(e){if(!this.config.enabled)return;const n=this.mountedComponents.get(e),r=this.eventListeners.get(e)||[];r.length>0&&console.warn(`[G7DevTools] 컴포넌트 ${e} 언마운트 시 ${r.length}개 리스너 미정리`),n&&this.unmountWatchers.forEach(i=>{try{i({componentId:e,componentName:n.name,timestamp:Date.now(),orphanedListeners:r.length})}catch(l){console.error("[G7DevTools] Unmount watcher error:",l)}}),this.mountedComponents.delete(e)}trackListener(e,n,r){if(!this.config.enabled)return;const i=this.eventListeners.get(e)||[];i.push({type:n,target:r,addedAt:Date.now()}),this.eventListeners.set(e,i)}removeListener(e,n){if(!this.config.enabled)return;const r=this.eventListeners.get(e)||[],i=r.findIndex(l=>l.type===n);i>=0&&r.splice(i,1)}getMountedComponents(){return Array.from(this.mountedComponents.values())}getOrphanedListeners(){const e=[];for(const[n,r]of this.eventListeners)this.mountedComponents.has(n)||e.push(...r.map(i=>({...i,componentId:n})));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 n=this.renderCounts.get(e)||0;this.renderCounts.set(e,n+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(),l=JSON.stringify(i).length;l>1e6&&e.push({type:"large-state",message:`상태 크기가 ${(l/1024/1024).toFixed(2)}MB입니다`,suggestion:"불필요한 데이터 정리 필요",severity:l>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 n=this.getOrphanedListeners().length;n>0&&e.push({type:"orphaned-listeners",message:`${n}개의 정리되지 않은 이벤트 리스너`,suggestion:"useEffect cleanup 또는 removeEventListener 확인",severity:n>10?"error":"warning"});const r=Array.from(this.renderCounts.entries()).filter(([,i])=>i>50);return r.length>0&&e.push({type:"excessive-renders",message:`${r.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,n=this.analyzeProfile(e);return console.log("[G7DevTools] 프로파일링 완료",n),n}analyzeProfile(e){const n=this.profilingData.filter(h=>h.type==="render"),r=this.profilingData.filter(h=>h.type==="binding"),i=this.profilingData.filter(h=>h.type==="action"),l={};for(const h of n)h.component&&(l[h.component]||(l[h.component]={count:0,durations:[]}),l[h.component].count++,h.duration&&l[h.component].durations.push(h.duration));const c=Object.entries(l).map(([h,m])=>({name:h,renderCount:m.count,avgDuration:m.durations.length>0?m.durations.reduce((y,v)=>y+v,0)/m.durations.length:0})).sort((h,m)=>m.renderCount-h.renderCount).slice(0,10),d={};for(const h of r)h.expression&&(d[h.expression]=(d[h.expression]||0)+1);const f=Object.entries(d).sort(([,h],[,m])=>m-h).slice(0,10).map(([h])=>h);return{duration:e,entries:this.profilingData,summary:{totalRenders:n.length,totalBindings:r.length,totalActions:i.length,slowestComponents:c,hotPaths:f}}}resetPerformanceStats(){this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[]}trackRequest(e,n,r){if(!this.config.enabled)return"";const i=this.generateId(),l=kx(e),c=Tx(e);return this.activeRequests.set(i,{id:i,url:l,fullUrl:e,queryParams:c,method:n,startTime:Date.now(),status:"pending",requestBody:r?.requestBody?this.sanitizeObject(r.requestBody):void 0,dataSourceId:r?.dataSourceId}),this.isProfiling&&this.profilingData.push({type:"network",timestamp:performance.now()}),i}completeRequest(e,n,r){if(!this.config.enabled)return;const i=this.activeRequests.get(e);if(!i)return;const l={...i,status:n>=200&&n<300?"success":"error",statusCode:n,duration:Date.now()-i.startTime,endTime:Date.now(),response:this.sanitizeObject(r)};this.requestHistory.push(l),this.activeRequests.delete(e),this.requestHistory.length>this.config.maxHistorySize&&this.requestHistory.shift(),this.notifyRequestWatchers(l)}failRequest(e,n){if(!this.config.enabled)return;const r=this.activeRequests.get(e);if(!r)return;const i={...r,status:"error",error:n,duration:Date.now()-r.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(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Request watcher error:",r)}})}trackWebSocketConnection(e,n,r){this.config.enabled&&this.wsConnections.set(e,{id:e,url:n,state:r,connectedAt:r==="open"?Date.now():void 0})}trackWebSocketMessage(e,n,r,i){if(!this.config.enabled)return;const l={id:this.generateId(),connectionId:e,direction:n,type:r,payload:this.sanitizeObject(i),timestamp:Date.now(),sequence:this.wsMessageHistory.length};this.wsMessageHistory.push(l),this.wsMessageHistory.length>this.config.maxHistorySize&&this.wsMessageHistory.shift(),this.notifyWebSocketWatchers(l)}getWebSocketConnections(){return Array.from(this.wsConnections.values())}getWebSocketMessageHistory(){return[...this.wsMessageHistory]}getWebSocketConnectionState(){const e=Array.from(this.wsConnections.values());return e.some(n=>n.state==="open")?"connected":e.some(n=>n.state==="connecting")?"reconnecting":"disconnected"}watchWebSocketMessage(e){return this.wsMessageWatchers.add(e),()=>{this.wsMessageWatchers.delete(e)}}notifyWebSocketWatchers(e){this.wsMessageWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] WebSocket watcher error:",r)}})}trackIfCondition(e,n,r){if(!this.config.enabled)return;const i=this.ifConditions.get(e),l=i?.evaluatedValue;this.ifConditions.set(e,{id:e,expression:n,evaluatedValue:r,evaluationCount:(i?.evaluationCount||0)+1,lastEvaluated:Date.now()}),i&&l!==r&&this.notifyConditionWatchers({id:e,expression:n,oldValue:l,newValue:r,timestamp:Date.now()})}trackIteration(e,n){this.config.enabled&&this.iterations.set(e,{id:e,...n,lastRendered:Date.now()})}getIfConditions(){return Array.from(this.ifConditions.values())}getIterations(){return Array.from(this.iterations.values())}getScopeChain(e){const n=[],r=this.getState();return n.push({name:"_global",value:r._global,source:"global"}),n.push({name:"_local",value:r._local,source:"local"}),n.push({name:"_computed",value:r._computed,source:"computed"}),n}watchConditionChange(e){return this.conditionWatchers.add(e),()=>{this.conditionWatchers.delete(e)}}notifyConditionWatchers(e){this.conditionWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Condition watcher error:",r)}})}trackForm(e,n,r){this.config.enabled&&this.forms.set(e,{id:e,dataKey:n,inputs:r,trackedAt:Date.now()})}trackFormChange(e,n,r){if(!this.config.enabled)return;const i={formId:e,inputName:n,value:r,timestamp:Date.now()};this.notifyFormWatchers(i)}untrackForm(e){this.forms.delete(e)}getForms(){return Array.from(this.forms.values())}getFormState(e){const n=this.getState();return this.getNestedValue(n,e)||{}}getBindingPath(e,n){return`${e}.${n}`}watchFormChange(e){return this.formWatchers.add(e),()=>{this.formWatchers.delete(e)}}notifyFormWatchers(e){this.formWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Form watcher error:",r)}})}trackFormBindingIssue(e,n,r){if(!this.config.enabled)return;const i={id:`form-issue-${++this.formBindingIssueIdCounter}`,timestamp:Date.now(),type:e,severity:n,formId:r.formId,formDataKey:r.formDataKey,inputInfo:r.inputInfo,contextInfo:r.contextInfo,description:r.description,suggestion:r.suggestion,docLink:r.docLink};this.formBindingIssues.push(i),this.formBindingIssues.length>this.maxFormBindingIssues&&this.formBindingIssues.shift()}validateFormBinding(e,n,r,i){const l=r.map(f=>{const h=[];let m=!0;return f.name||(h.push("Input에 name 속성이 없습니다"),m=!1,this.trackFormBindingIssue("missing-input-name","error",{formId:e,formDataKey:n,inputInfo:{name:f.name,type:f.type},description:"Input에 name 속성이 없어 자동 바인딩이 동작하지 않습니다",suggestion:"Input에 name 속성을 추가하세요",docLink:"troubleshooting-components-form.md"})),n||(h.push("Form에 dataKey가 없습니다"),m=!1),{inputName:f.name||"(unnamed)",inputType:f.type,bindingPath:n&&f.name?`${n}.${f.name}`:"-",isValid:m,currentValue:f.value,issues:h}});if(n||this.trackFormBindingIssue("missing-datakey","error",{formId:e,description:"Form에 dataKey가 설정되지 않아 자동 바인딩이 동작하지 않습니다",suggestion:"Form 컴포넌트에 dataKey props를 설정하세요",docLink:"troubleshooting-components-form.md"}),i.isContextBroken){const f=i.breakReason?.includes("sortable")?"sortable-context-break":i.breakReason?.includes("modal")?"modal-context-isolation":"context-not-propagated";this.trackFormBindingIssue(f,"warning",{formId:e,formDataKey:n,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 c={formId:e,dataKey:n,timestamp:Date.now(),contextPropagation:i,inputBindings:l,isValid:l.every(f=>f.isValid)&&!!n&&!i.isContextBroken,issueCount:l.filter(f=>!f.isValid).length+(n?0:1)+(i.isContextBroken?1:0)},d=this.formBindingValidations.findIndex(f=>f.formId===e);return d>=0?this.formBindingValidations[d]=c:this.formBindingValidations.push(c),c}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},n={info:0,warning:0,error:0};for(const i of this.formBindingIssues)e[i.type]++,n[i.severity]++;const r=Object.entries(e).filter(([,i])=>i>0).sort((i,l)=>l[1]-i[1]).slice(0,5).map(([i,l])=>({type:i,count:l,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:n,topIssues:r}}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,n,r,i,l,c,d){if(!this.config.enabled)return;const f=`computed-${e}-${c||"global"}`,h={id:f,name:e,expression:n,componentId:c,dependencies:r,currentValue:this.safeClone(i),lastComputedAt:Date.now(),computationTime:l,error:d};this.computedProperties.set(f,h)}trackComputedRecalc(e,n,r,i,l,c,d){if(!this.config.enabled)return;const f=`computed-${e}-${d||"global"}`,h=JSON.stringify(r)!==JSON.stringify(i),m={id:`recalc-${++this.computedRecalcIdCounter}`,computedId:f,computedName:e,timestamp:Date.now(),trigger:n,triggeredBy:c,previousValue:this.safeClone(r),newValue:this.safeClone(i),valueChanged:h,computationTime:l,cascadeCount:0};this.computedRecalcLogs.push(m),this.computedRecalcLogs.length>this.maxComputedRecalcLogs&&this.computedRecalcLogs.shift();const y=this.computedProperties.get(f);y&&(y.currentValue=this.safeClone(i),y.lastComputedAt=Date.now(),y.computationTime=l)}analyzeComputedDependencyChain(e,n){const r=new Set,i=[];let l=!1,c,d=0;const f=(m,y)=>{if(d=Math.max(d,y),r.has(m))return l=!0,c=[...i,m],{name:m,type:"computed",children:[],depth:y};r.add(m),i.push(m);const v=this.computedProperties.get(`computed-${m}-${n||"global"}`),S=[];if(v)for(const _ of v.dependencies)_.type==="computed"?S.push(f(_.path,y+1)):S.push({name:_.path,type:_.type,children:[],depth:y+1});return i.pop(),r.delete(m),{name:m,type:"computed",children:S,depth:y}},h=f(e,0);return{root:e,tree:h,hasCycle:l,cyclePath:c,maxDepth:d}}getComputedDependencyTrackingInfo(){const e=Array.from(this.computedProperties.values()),n=this.getComputedDependencyStats(),r=[];for(const i of e){const l=this.analyzeComputedDependencyChain(i.name,i.componentId);r.push(l)}return{properties:e,recalcLogs:[...this.computedRecalcLogs],dependencyChains:r,stats:n,timestamp:Date.now()}}getComputedDependencyStats(){const e={"state-change":0,"datasource-update":0,"dependency-change":0,manual:0,initial:0},n={},r={};let i=0,l=0;for(const h of this.computedRecalcLogs)e[h.trigger]++,h.valueChanged||l++,n[h.computedName]=(n[h.computedName]||0)+1,r[h.computedName]||(r[h.computedName]=[]),r[h.computedName].push(h.computationTime),i+=h.computationTime;const c=Object.entries(n).sort((h,m)=>m[1]-h[1]).slice(0,5).map(([h,m])=>({name:h,count:m})),d=Object.entries(r).map(([h,m])=>({name:h,avgTime:m.reduce((y,v)=>y+v,0)/m.length})).sort((h,m)=>m.avgTime-h.avgTime).slice(0,5);let f=0;for(const h of this.computedProperties.values())this.analyzeComputedDependencyChain(h.name,h.componentId).hasCycle&&f++;return{totalComputed:this.computedProperties.size,totalRecalculations:this.computedRecalcLogs.length,unnecessaryRecalculations:l,avgComputationTime:this.computedRecalcLogs.length>0?i/this.computedRecalcLogs.length:0,topRecalculated:c,slowestComputed:d,cycleDetectionCount:f,byTrigger:e}}clearComputedTracking(){this.computedProperties.clear(),this.computedRecalcLogs=[],this.computedRecalcIdCounter=0}trackModalOpen(e){if(!this.config.enabled)return;const n={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,n),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,n){if(!this.config.enabled)return;const r=this.modalStates.get(e);r&&(r.closedAt=Date.now(),n&&(r.currentState={...n}),this.detectStateLeakage(r))}validateModalDefinitionExists(e,n){const r=this.currentLayout;if(!r?.layoutJson)return;const i=r.layoutJson.modals;if(!i){this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:n,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 현재 레이아웃에 modals 섹션이 없습니다. 레이아웃 경로: ${r.layoutPath}`,affectedStateKeys:[],expectedValue:`modals 섹션에 id="${e}" 정의 존재`,actualValue:"modals 섹션 없음"});return}const l=Array.isArray(i)?i:Object.values(i);l.some(d=>d?.id===e||d?.props?.id===e)||this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:n,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 렌더링된 레이아웃의 modals 섹션에 해당 ID의 정의가 없습니다. partial 로딩 실패, 레이아웃 병합 문제, extends 상속 누락 등을 확인하세요. 레이아웃 경로: ${r.layoutPath}`,affectedStateKeys:[],expectedValue:`modals 배열에 id="${e}" 항목 존재`,actualValue:`modals 배열에 ${l.length}개 모달 정의 (${l.map(d=>d?.id||"unknown").join(", ")})`})}trackModalStateChange(e){if(!this.config.enabled)return;const n=this.modalStates.get(e.modalId);if(!n)return;n.stateChangeCount++,n.currentState[e.stateKey]=e.newValue;const r=this.checkIsolationViolation(n,e.stateKey),i={id:`modal-change-${++this.modalStateChangeLogIdCounter}`,modalId:e.modalId,modalName:n.modalName,timestamp:Date.now(),stateKey:e.stateKey,previousValue:e.previousValue,newValue:e.newValue,changeSource:e.changeSource||"user-action",violatesIsolation:r};this.modalStateChangeLogs.push(i),this.modalStateChangeLogs.length>this.maxModalStateChangeLogs&&this.modalStateChangeLogs.shift(),r&&this.recordModalStateIssue({type:"isolation-violation",modalId:e.modalId,modalName:n.modalName,severity:"warning",description:`모달 '${n.modalName}'에서 격리된 상태 키 '${e.stateKey}'가 변경됨`,affectedStateKeys:[e.stateKey]})}detectStateLeakage(e){if(e.scopeType==="isolated")for(const n of e.isolatedStateKeys){const r=e.initialState[n],i=e.currentState[n];if(r!==i&&e.parentModalId){const l=this.modalStates.get(e.parentModalId);l&&l.currentState.hasOwnProperty(n)&&this.recordModalStateIssue({type:"state-leakage",modalId:e.modalId,modalName:e.modalName,severity:"error",description:`모달 닫힘 후 상태 '${n}'가 부모 모달로 유출될 수 있음`,affectedStateKeys:[n],leakedValue:i,expectedValue:r})}}}checkIsolationViolation(e,n){return e.scopeType==="isolated",!1}recordModalStateIssue(e){const n={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(n),this.modalStateIssues.length>this.maxModalStateIssues&&this.modalStateIssues.shift()}getModalStateScopeTrackingInfo(){const e=Array.from(this.modalStates.values()),n=this.getModalStateScopeStats();return{modals:e,issues:[...this.modalStateIssues],relations:[...this.modalStateRelations],changeLogs:[...this.modalStateChangeLogs],stats:n,timestamp:Date.now()}}getModalStateScopeStats(){const e=Array.from(this.modalStates.values()),n={warning:0,error:0},r={"state-leakage":0,"isolation-violation":0,"parent-mutation":0,"orphaned-state":0,"scope-mismatch":0,"cleanup-failure":0,"missing-definition":0};for(const l of this.modalStateIssues)n[l.severity]++,r[l.type]++;const i={isolated:0,shared:0,inherited:0};for(const l of e)i[l.scopeType]++;return{totalModals:e.length,openModals:e.filter(l=>l.closedAt===null).length,nestedModals:e.filter(l=>l.parentModalId!==void 0).length,totalIssues:this.modalStateIssues.length,issuesBySeverity:n,issuesByType:r,byScope:i,leakageDetectionCount:r["state-leakage"],cleanupFailureCount:r["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 n={...e,id:`named_action_ref_${++this.namedActionRefIdCounter}`};this.namedActionRefLogs.push(n),this.namedActionRefLogs.length>this.maxNamedActionRefLogs&&(this.namedActionRefLogs=this.namedActionRefLogs.slice(-this.maxNamedActionRefLogs))}getNamedActionTrackingInfo(){const e={};for(const r of this.namedActionRefLogs)e[r.actionRefName]=(e[r.actionRefName]||0)+1;const n=Object.keys(this.namedActionDefinitions).filter(r=>!e[r]);return{definitions:this.namedActionDefinitions,refLogs:[...this.namedActionRefLogs],stats:{totalDefinitions:Object.keys(this.namedActionDefinitions).length,totalRefs:this.namedActionRefLogs.length,refCountByName:e,unusedDefinitions:n},timestamp:Date.now()}}clearNamedActionTracking(){this.namedActionDefinitions={},this.namedActionRefLogs=[],this.namedActionRefIdCounter=0}trackExpressionEval(e){if(!this.config.enabled)return;const n={...e,id:`expr-${++this.expressionIdCounter}`,timestamp:Date.now(),warning:this.detectExpressionWarning(e)};this.expressionHistory.push(n),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(n)}detectExpressionWarning(e){const{expression:n,result:r,resultType:i,method:l,duration:c}=e;if(i==="undefined"&&!n.includes("??")&&!n.includes("||")&&/^[a-zA-Z_$][a-zA-Z0-9_$.]*$/.test(n.replace(/{{|}}/g,"").trim()))return{type:"undefined-result",message:"표현식 결과가 undefined입니다",suggestion:`데이터가 로드되었는지 확인하거나 fallback 값을 추가하세요: ${n} ?? ''`};if(i==="null")return{type:"null-result",message:"표현식 결과가 null입니다",suggestion:`nullish coalescing 연산자를 사용하세요: ${n} ?? ''`};if(l==="resolveBindings"&&i==="string"){const d=String(r);if(d.includes("[object Object]")||/^\[.*\]$/.test(d))return{type:"array-to-string",message:"배열/객체가 문자열로 변환되었습니다",suggestion:"evaluateExpression()을 사용하여 원본 타입을 유지하세요"}}if(l==="resolveBindings"&&i==="string"&&String(r).includes("[object Object]"))return{type:"object-to-string",message:"객체가 [object Object]로 변환되었습니다",suggestion:"evaluateExpression()을 사용하거나 특정 속성에 접근하세요"};if(i==="undefined"&&n.includes(".")&&!n.includes("?.")){const d=n.replace(/{{|}}/g,"").trim().split(".");if(d.length>=2)return{type:"missing-optional-chain",message:"Optional chaining(?.) 누락 가능성",suggestion:`안전한 접근을 위해 ?. 사용을 고려하세요: ${d.join("?.")}`}}if((n.includes("{{item.")||n.includes("{{index}}"))&&Array.from(this.iterations.values()).some(h=>h.itemVar!=="item"))return{type:"wrong-iteration-var",message:"'item'/'index' 대신 iteration에서 정의한 변수명을 사용해야 합니다",suggestion:"iteration의 item_var/index_var에 정의된 변수명을 확인하세요"};if(c&&c>10)return{type:"slow-evaluation",message:`표현식 평가에 ${c.toFixed(2)}ms 소요됨`,suggestion:"복잡한 표현식을 단순화하거나 computed 값으로 분리하세요"}}getExpressions(){return[...this.expressionHistory]}getExpressionWarnings(){return this.expressionHistory.filter(e=>e.warning!=null)}searchExpressions(e){const n=e.toLowerCase();return this.expressionHistory.filter(r=>r.expression.toLowerCase().includes(n)||r.componentName?.toLowerCase().includes(n)||r.propName?.toLowerCase().includes(n))}getExpressionStats(){const e=this.expressionHistory,n=new Set(e.map(f=>f.expression)),r=e.filter(f=>f.warning!=null),i=e.filter(f=>f.fromCache),l=e.filter(f=>f.duration!=null).map(f=>f.duration),c={};for(const f of e)c[f.resultType]=(c[f.resultType]||0)+1;const d={};for(const f of r)f.warning&&(d[f.warning.type]=(d[f.warning.type]||0)+1);return{totalEvaluations:e.length,uniqueExpressions:n.size,warningCount:r.length,cacheHitRate:e.length>0?i.length/e.length:0,averageDuration:l.length>0?l.reduce((f,h)=>f+h,0)/l.length:0,byType:c,byWarning:d}}clearExpressions(){this.expressionHistory=[],this.expressionIdCounter=0}watchExpressions(e){return this.expressionWatchers.add(e),()=>{this.expressionWatchers.delete(e)}}notifyExpressionWatchers(e){this.expressionWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Expression watcher error:",r)}})}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,n=new WeakSet){if(e===null||typeof e!="object")return e;if(n.has(e))return"[Circular]";if(n.add(e),Array.isArray(e))return e.map(i=>this.sanitizeObject(i,n));const r={};for(const i of Object.keys(e))try{r[i]=this.sanitizeObject(e[i],n)}catch{r[i]="[Unable to serialize]"}return r}getNestedValue(e,n){if(!n)return e;const r=n.split(".");let i=e;for(const l of r){if(i==null)return;i=i[l]}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 n=[...this.stateHistory].reverse().find(r=>r.timestamp<=e);if(n)return{_global:n.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,n,r){if(!this.config.enabled)return;const i=r.map(c=>{if(typeof c=="string")return c;try{return JSON.stringify(c)}catch{return String(c)}}).join(" "),l={id:`log-${++this.logIdCounter}`,level:e,prefix:n,message:i,args:this.sanitizeObject(r),timestamp:Date.now(),stack:e==="error"?new Error().stack:void 0};this.logHistory.push(l),this.logHistory.length>this.maxLogHistory&&this.logHistory.shift()}trackAction(e){if(!this.config.enabled)return;const n={id:`debounce-action-${++this.debounceActionIdCounter}`,...e,timestamp:Date.now()};this.debounceActionHistory.push(n),this.debounceActionHistory.length>100&&this.debounceActionHistory.shift()}trackDataSourceUpdate(e){if(!this.config.enabled)return;const n={id:`ds-update-${++this.dataSourceUpdateIdCounter}`,...e};this.dataSourceUpdateHistory.push(n),this.dataSourceUpdateHistory.length>100&&this.dataSourceUpdateHistory.shift()}getDebounceActionHistory(e){let n=[...this.debounceActionHistory];return e?.handler&&(n=n.filter(r=>r.handler.includes(e.handler))),e?.status&&(n=n.filter(r=>r.status===e.status)),e?.limit&&(n=n.slice(-e.limit)),n}getDataSourceUpdateHistory(e){let n=[...this.dataSourceUpdateHistory];return e?.dataSourceId&&(n=n.filter(r=>r.dataSourceId===e.dataSourceId)),e?.updateType&&(n=n.filter(r=>r.updateType===e.updateType)),e?.limit&&(n=n.slice(-e.limit)),n}getLogs(e){let n=[...this.logHistory];if(e?.level){const r=Array.isArray(e.level)?e.level:[e.level];n=n.filter(i=>r.includes(i.level))}if(e?.prefix){const r=e.prefix.toLowerCase();n=n.filter(i=>i.prefix.toLowerCase().includes(r))}if(e?.search){const r=e.search.toLowerCase();n=n.filter(i=>i.message.toLowerCase().includes(r))}return e?.since&&(n=n.filter(r=>r.timestamp>=e.since)),e?.limit&&(n=n.slice(-e.limit)),n}getLogStats(){const n=Date.now()-6e4,r={log:0,warn:0,error:0,debug:0,info:0},i={};let l=0,c=0;for(const d of this.logHistory)r[d.level]++,i[d.prefix]=(i[d.prefix]||0)+1,d.timestamp>=n&&(d.level==="error"&&l++,d.level==="warn"&&c++);return{totalLogs:this.logHistory.length,byLevel:r,byPrefix:i,recentErrors:l,recentWarnings:c}}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 n=this.dataSources.get(e);n&&this.dataSources.set(e,{...n,status:"loading"})}trackDataSourceLoaded(e,n,r){if(!this.config.enabled)return;const i=this.dataSources.get(e);if(!i)return;let l,c,d=r;n&&(Array.isArray(n)?(l=n.length,c=n.length>0&&typeof n[0]=="object"?Object.keys(n[0]):void 0):typeof n=="object"&&(Array.isArray(n.data)?(d=d||"data",l=n.data.length,c=n.data.length>0&&typeof n.data[0]=="object"?Object.keys(n.data[0]):void 0):Array.isArray(n.items)?(d=d||"items",l=n.items.length,c=n.items.length>0&&typeof n.items[0]=="object"?Object.keys(n.items[0]):void 0):c=Object.keys(n))),this.dataSources.set(e,{...i,status:"loaded",dataPath:d,itemCount:l,keys:c,lastLoadedAt:Date.now(),error:void 0})}trackDataSourceError(e,n){if(!this.config.enabled)return;const r=this.dataSources.get(e);r&&this.dataSources.set(e,{...r,status:"error",error:n,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 n=this.dataPathTransforms.find(r=>r.dataSourceId===e.dataSourceId);n||(n={dataSourceId:e.dataSourceId,timestamp:Date.now(),transformSteps:[],warnings:[]},this.dataPathTransforms.push(n),this.dataPathTransforms.length>this.maxDataPathTransforms&&this.dataPathTransforms.shift()),n.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&&n.warnings.push(e.warning)}setDataPathFinalBinding(e,n){if(!this.config.enabled)return;const r=this.dataPathTransforms.find(i=>i.dataSourceId===e);r&&(r.finalBinding={expression:n.expression,resolvedPath:n.resolvedPath,value:this.safeClone(n.value)})}getDataPathTransformTrackingInfo(){const e=this.getDataPathTransformStats();return{transforms:[...this.dataPathTransforms],stats:e,timestamp:Date.now()}}getDataPathTransformStats(){const e=this.dataPathTransforms,n={};let r=0;const i={};for(const c of e){n[c.dataSourceId]=(n[c.dataSourceId]||0)+1,r+=c.warnings.length;for(const d of c.warnings)i[d]=(i[d]||0)+1}const l=Object.entries(i).map(([c,d])=>({warning:c,count:d})).sort((c,d)=>d.count-c.count).slice(0,10);return{totalTransforms:e.length,byDataSource:n,warningsCount:r,commonWarnings:l}}getDataPathTransformForDataSource(e){return this.dataPathTransforms.find(n=>n.dataSourceId===e)}clearDataPathTransforms(){this.dataPathTransforms=[]}trackNestedContext(e){if(!this.config.enabled)return"";const n=`nested-${++this.nestedContextIdCounter}`,r=[...new Set([...e.parentContext.available,...e.ownContext.added])],i={...e.parentContext.values,...e.ownContext.values},l={id:n,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:r,values:this.safeClone(i)},accessAttempts:[],depth:e.depth,parentId:e.parentId};return this.nestedContexts.push(l),this.nestedContexts.length>this.maxNestedContexts&&this.nestedContexts.shift(),n}trackNestedContextAccess(e,n){if(!this.config.enabled)return;const r=this.nestedContexts.find(i=>i.id===e);r&&r.accessAttempts.push({path:n.path,found:n.found,value:n.found?this.safeClone(n.value):void 0,error:n.error})}getNestedContextTrackingInfo(){const e=this.getNestedContextStats();return{contexts:[...this.nestedContexts],stats:e,timestamp:Date.now()}}getNestedContextStats(){const e=this.nestedContexts,n={expandChildren:0,cellChildren:0,iteration:0,modal:0,slot:0};let r=0,i=0;const l={};for(const d of e){n[d.componentType]++,d.depth>r&&(r=d.depth);for(const f of d.accessAttempts)f.found||(i++,l[f.path]=(l[f.path]||0)+1)}const c=Object.entries(l).map(([d,f])=>({path:d,count:f})).sort((d,f)=>f.count-d.count).slice(0,10);return{totalContexts:e.length,byType:n,maxDepth:r,failedAccessCount:i,commonFailedPaths:c}}getNestedContextForComponent(e){return this.nestedContexts.find(n=>n.componentId===e)}clearNestedContexts(){this.nestedContexts=[],this.nestedContextIdCounter=0}trackHandlerRegistration(e,n="custom",r,i){this.isEnabled&&this.handlers.set(e,{name:e,category:n,description:r,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(n=>n.category===e)}clearHandlers(){this.handlers.clear()}trackEventSubscribe(e){if(!this.isEnabled)return;const n=this.componentEventSubscriptions.get(e),r=Date.now();n?(n.subscriberCount++,n.lastSubscribedAt=r):this.componentEventSubscriptions.set(e,{eventName:e,subscriberCount:1,firstSubscribedAt:r,lastSubscribedAt:r})}trackEventUnsubscribe(e){if(!this.isEnabled)return;const n=this.componentEventSubscriptions.get(e);n&&(n.subscriberCount--,n.subscriberCount<=0&&this.componentEventSubscriptions.delete(e))}trackEventEmit(e,n,r,i,l){if(!this.isEnabled)return;const c={id:`evt_${++this.componentEventIdCounter}`,eventName:e,data:this.sanitizeForLogging(n),timestamp:Date.now(),listenerCount:r,results:i?this.sanitizeForLogging(i):void 0,hasError:!!l,errorMessage:l?.message};this.componentEventEmitHistory.push(c),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((n,r)=>n+r.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,n,r,i){if(!this.config.enabled)return"";const l=`setState_${++this.stateRenderingIdCounter}`;this.currentStateChangeContext={setStateId:l,startTime:performance.now(),changedPath:e,trigger:i||{},renderedComponents:[]};const c={id:`sr_${this.stateRenderingIdCounter}`,setStateId:l,statePath:e,oldValue:this.sanitizeForLogging(n),newValue:this.sanitizeForLogging(r),timestamp:Date.now(),triggeredBy:i||{},renderedComponents:[],totalRenderDuration:0,affectedBindingsCount:0};return this.stateRenderingLogs.push(c),this.stateRenderingLogs.length>this.maxStateRenderingLogs&&this.stateRenderingLogs.shift(),l}trackComponentRender(e,n,r,i=[],l=[],c){if(!this.config.enabled)return;const d=this.componentRenderCounts.get(n)||0;this.componentRenderCounts.set(n,d+1);for(const f of i)this.stateToComponentMap.has(f)||this.stateToComponentMap.set(f,new Set),this.stateToComponentMap.get(f).add(n);if(this.currentStateChangeContext){const f={componentId:e,componentName:n,renderDuration:r,accessedStatePaths:i,evaluatedBindings:l,renderOrder:this.currentStateChangeContext.renderedComponents.length,parentId:c};this.currentStateChangeContext.renderedComponents.push(f)}this.trackRender(n)}completeStateChange(e){if(!this.config.enabled||!this.currentStateChangeContext||this.currentStateChangeContext.setStateId!==e)return;const n=this.currentStateChangeContext,i=performance.now()-n.startTime,l=this.stateRenderingLogs.findIndex(c=>c.setStateId===e);if(l>=0){const c=this.stateRenderingLogs[l];c.renderedComponents=n.renderedComponents,c.totalRenderDuration=i,c.affectedBindingsCount=n.renderedComponents.reduce((d,f)=>d+f.evaluatedBindings.length,0)}this.currentStateChangeContext=null}getCurrentStateChangeContext(){return this.currentStateChangeContext}getStateRenderingLogs(){return[...this.stateRenderingLogs]}getStateRenderingInfo(){const e=this.stateRenderingLogs,n=Object.fromEntries(this.componentRenderCounts),r={};for(const[i,l]of this.stateToComponentMap)r[i]=Array.from(l);return{logs:e,componentRenderCounts:n,stateToComponentMap:r,stats:this.calculateStateRenderingStats()}}calculateStateRenderingStats(){const e=this.stateRenderingLogs;if(e.length===0)return{totalStateChanges:0,totalRenders:0,avgRenderDuration:0,avgComponentsPerChange:0,topRenderedComponents:[],topInfluentialPaths:[]};const n=e.reduce((d,f)=>d+f.renderedComponents.length,0),r=e.reduce((d,f)=>d+f.totalRenderDuration,0)/e.length,i=n/e.length,l=Array.from(this.componentRenderCounts.entries()).sort((d,f)=>f[1]-d[1]).slice(0,5).map(([d,f])=>({name:d,count:f})),c=Array.from(this.stateToComponentMap.entries()).sort((d,f)=>f[1].size-d[1].size).slice(0,5).map(([d,f])=>({path:d,affectedComponents:f.size}));return{totalStateChanges:e.length,totalRenders:n,avgRenderDuration:r,avgComponentsPerChange:i,topRenderedComponents:l,topInfluentialPaths:c}}getComponentsAffectedByState(e){const n=this.stateToComponentMap.get(e);return n?Array.from(n):[]}getComponentRenderHistory(e){return this.stateRenderingLogs.filter(n=>n.renderedComponents.some(r=>r.componentName===e))}clearStateRenderingLogs(){this.stateRenderingLogs=[],this.componentRenderCounts.clear(),this.stateToComponentMap.clear(),this.currentStateChangeContext=null,this.stateRenderingIdCounter=0}trackComponentStateSource(e,n,r,i){this.config.enabled&&this.componentStateSources.set(e,{componentId:e,componentName:n,stateSource:r,stateProvider:i})}trackDynamicState(e,n){this.config.enabled&&this.dynamicStates.set(e,n)}trackContextFlow(e,n,r,i,l,c){if(!this.config.enabled)return;const d={component:n,componentId:e,contextReceived:r,passedToChildren:i,usedInRender:l};if(this.contextFlowNodes.set(e,d),c){const f=this.contextFlowNodes.get(c);f&&(f.children||(f.children=[]),f.children.push(d))}}getStateHierarchyInfo(e=!0){const n=this.buildStateHierarchyLayers(),r=this.detectStateConflicts(n),i=Array.from(this.componentStateSources.values());return{layers:e?n.map(c=>({...c,values:this.summarizeValues(c.values,2)})):n,conflicts:r,componentStateSources:i,timestamp:Date.now()}}summarizeValues(e,n,r=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(r>=n){if(Array.isArray(e))return`[Array(${e.length})]`;const c=Object.keys(e);return`{${c.slice(0,5).join(", ")}${c.length>5?`, ... +${c.length-5}`:""}}`}if(Array.isArray(e))return e.length<=3?e.map(c=>this.summarizeValues(c,n,r+1)):{__type:"array",__length:e.length,__preview:e.slice(0,3).map(c=>this.summarizeValues(c,n,r+1))};const i={},l=Object.keys(e);for(const c of l)i[c]=this.summarizeValues(e[c],n,r+1);return i}buildStateHierarchyLayers(){const e=[];try{const r=window.G7Core?.state?.get?.();if(!r)return e;r._local&&e.push({name:"Global _local",type:"global",path:"_local",values:r._local,priority:1}),r._global&&e.push({name:"Global _global",type:"global",path:"_global",values:r._global,priority:1});for(const[l,c]of this.dynamicStates)c&&Object.keys(c).length>0&&e.push({name:`DynamicState (${l})`,type:"dynamicState",componentId:l,values:c,priority:2});const i=this.computeEffectiveState(r._local||{});e.push({name:"Effective _local (merged)",type:"effective",values:i,priority:3})}catch(n){console.warn("[G7DevTools] 상태 계층 빌드 실패:",n)}return e}computeEffectiveState(e){const n={...e};for(const[,r]of this.dynamicStates)r._local&&Object.assign(n,r._local);return n}detectStateConflicts(e){const n=[],r=e.find(l=>l.type==="global"&&l.path==="_local");if(!r)return n;const i=e.filter(l=>l.type==="dynamicState");for(const l of i){const c=l.values._local||l.values;for(const[d,f]of Object.entries(c)){const h=r.values[d];if(JSON.stringify(h)!==JSON.stringify(f)){const m=[],y=[];for(const v of this.componentStateSources.values())v.stateSource.local.some(_=>_===`_local.${d}`||_===d)&&(v.stateProvider.type==="dynamicState"?m.push(v.componentName):v.stateProvider.type==="globalState"&&y.push(v.componentName));n.push({path:`_local.${d}`,globalValue:h,dynamicStateValue:f,effectiveValue:f,usedBy:m,notUsedBy:y,severity:y.length>0?"warning":"info",description:y.length>0?`${y.join(", ")}은(는) globalState._local을 읽어 dynamicState 값을 사용하지 못함`:"dynamicState 값이 globalState와 다르지만 모든 컴포넌트가 dynamicState를 사용"})}}}return n}getContextFlowInfo(){const e=[],n=new Set(this.contextFlowNodes.keys());for(const r of this.contextFlowNodes.values())if(r.children)for(const i of r.children)n.delete(i.componentId);for(const r of n){const i=this.contextFlowNodes.get(r);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,n,r,i){if(!this.config.enabled)return;const l=this.analyzeTailwindClasses(r),c={componentId:e,componentName:n,classes:r,computedStyles:i,tailwindAnalysis:l};this.componentStyles.set(e,c),this.detectStyleIssues(c)}analyzeTailwindClasses(e){const n=[],r=[],i=[],l=[],c=["sm:","md:","lg:","xl:","2xl:"],d=[/bg-\w+-\d+/,/text-\w+-\d+/,/border-\w+-\d+/];for(const f of e){l.push(f),f.startsWith("dark:")&&n.push(f);for(const h of c)if(f.startsWith(h)){r.push(f);break}for(const h of d)if(h.test(f)){i.push(f);break}}return{usedClasses:l,darkClasses:n,responsiveClasses:r,dynamicClasses:i}}detectStyleIssues(e){const{componentId:n,componentName:r,computedStyles:i,tailwindAnalysis:l}=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:n,componentName:r,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 c=l.usedClasses.filter(f=>f.startsWith("bg-")&&!f.startsWith("dark:")),d=l.darkClasses.filter(f=>f.includes("bg-"));c.length>0&&d.length===0&&this.addStyleIssue({id:this.generateId(),type:"dark-mode-missing",componentId:n,componentName:r,property:"background-color",currentValue:c.join(", "),expectedValue:"dark:bg-* 클래스 필요",severity:"info",description:"다크 모드 배경색 클래스가 누락되었습니다.",suggestion:`${c[0]}에 대응하는 dark: 클래스를 추가하세요.`}),l.dynamicClasses.length>0&&this.addStyleIssue({id:this.generateId(),type:"tailwind-purging",componentId:n,componentName:r,property:"class",currentValue:l.dynamicClasses.join(", "),severity:"info",description:"동적으로 생성된 Tailwind 클래스가 있습니다.",suggestion:"tailwind.config.js의 safelist에 추가하거나 전체 클래스명을 상수로 정의하세요."})}addStyleIssue(e){this.styleIssues.some(r=>r.componentId===e.componentId&&r.type===e.type&&r.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(n=>n.type==="invisible-element").length,tailwindIssueCount:this.styleIssues.filter(n=>n.type==="tailwind-purging").length,darkModeIssueCount:this.styleIssues.filter(n=>n.type==="dark-mode-missing").length},timestamp:Date.now()}}clearStyleValidationData(){this.styleIssues=[],this.componentStyles.clear()}trackAuthEvent(e,n,r,i){if(!this.config.enabled)return;const l={id:`auth_${++this.authEventIdCounter}`,type:e,timestamp:Date.now(),success:n,error:r,details:i};this.authEvents.push(l),this.authEvents.length>this.maxAuthEventHistory&&(this.authEvents=this.authEvents.slice(-this.maxAuthEventHistory))}trackAuthHeader(e,n,r,i,l){if(!this.config.enabled)return;const c={url:e,hasAuthHeader:n,headerType:r,tokenValid:i??!1,responseStatus:l,timestamp:Date.now()};this.authHeaderHistory.push(c),this.authHeaderHistory.length>this.maxAuthEventHistory&&(this.authHeaderHistory=this.authHeaderHistory.slice(-this.maxAuthEventHistory)),l===401&&this.trackAuthEvent("api-unauthorized",!1,`401 Unauthorized: ${e}`,{url:e})}getAuthState(){try{const e=window.G7Core,n=e?.api;let r=e?.auth;!r&&e?.AuthManager?.getInstance&&(r=e.AuthManager.getInstance());const i=n?.getToken?.()||r?.getAccessToken?.()||localStorage.getItem("auth_token")||localStorage.getItem("access_token"),l=r?.getRefreshToken?.()||localStorage.getItem("refresh_token");let c="unknown",d=r?.getUser?.();if(d&&(c="AuthManager"),!d){const S=e?.state?.get?.();d=S?._global?.user||S?._global?.currentUser||S?.user||S?.currentUser,d&&(c="G7Core.state")}const f=r?.isAuthenticated?.()??!1;let h="memory";localStorage.getItem("auth_token")||localStorage.getItem("access_token")?h="localStorage":(sessionStorage.getItem("auth_token")||sessionStorage.getItem("access_token"))&&(h="sessionStorage");const m=!!i&&(!!d||f);let y;i&&typeof i=="string"&&i.length>20?y=`${i.substring(0,10)}...${i.substring(i.length-6)}`:i&&(y="***");const v=d?{id:d.id,email:d.email,name:d.name,roles:d.roles?.map(S=>typeof S=="string"?{name:S}:{id:S.id,name:S.name,guard_name:S.guard_name}),permissions:d.permissions?.map(S=>typeof S=="string"?{name:S}:{id:S.id,name:S.name,guard_name:S.guard_name}),avatar:d.avatar||d.profile_photo_url||d.profile_image,created_at:d.created_at,updated_at:d.updated_at,last_login_at:d.last_login_at,email_verified_at:d.email_verified_at,...d.phone&&{phone:d.phone},...d.nickname&&{nickname:d.nickname},...d.status&&{status:d.status},...d.locale&&{locale:d.locale}}:void 0;return{isAuthenticated:m,user:v,tokens:{hasAccessToken:!!i,hasRefreshToken:!!l,storage:h,accessTokenPreview:y},lastActivity:Date.now(),source:c}}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(n=>n.type==="login").length,successfulLogins:e.filter(n=>n.type==="login"&&n.success).length,failedLogins:e.filter(n=>n.type==="login"&&!n.success).length,tokenRefreshes:e.filter(n=>n.type==="token-refresh").length,unauthorizedResponses:e.filter(n=>n.type==="api-unauthorized").length},timestamp:Date.now()}}clearAuthData(){this.authEvents=[],this.authHeaderHistory=[],this.authEventIdCounter=0}trackLayoutLoad(e,n,r,i="api"){if(!this.config.enabled)return;const l=Date.now();this.currentLayout={layoutPath:e,templateId:n,layoutJson:this.sanitizeObject(r),loadedAt:l,version:r.version,layoutName:r.layout_name,source:i};const c={id:`layout-${++this.layoutIdCounter}`,layoutPath:e,templateId:n,loadedAt:l,source:i,version:r.version};this.layoutHistory.push(c),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 n=`exec_${++this.executionIdCounter}_${Date.now()}`,r={handlerName:e,executionId:n,startTime:Date.now(),stateChanges:[],dataSourceChanges:[],alerts:[]};if(this.executionDetails.set(n,r),this.executionDetails.size>this.maxExecutionDetails){const i=Array.from(this.executionDetails.keys());i.slice(0,i.length-this.maxExecutionDetails).forEach(c=>this.executionDetails.delete(c))}return n}endHandlerExecution(e,n,r,i){if(!this.config.enabled||!e)return;const l=this.executionDetails.get(e);if(!l)return;l.endTime=Date.now(),l.duration=l.endTime-l.startTime,l.exitReason=n,l.exitLocation=r,l.exitDescription=i;const c=this.changeExpectations.get(e);c&&(l.expectedChanges=c,this.checkExpectations(e,l,c),this.changeExpectations.delete(e)),n==="normal"&&l.stateChanges.length===0&&l.dataSourceChanges.length===0&&this.addChangeAlert(e,{type:"no-state-change",severity:"warning",message:`핸들러 "${l.handlerName}"이(가) 상태 변경 없이 완료됨`,description:"핸들러가 성공적으로 완료되었지만 상태나 데이터소스 변경이 없습니다. 의도한 동작인지 확인하세요.",handlerName:l.handlerName,suggestion:'핸들러 내부 조건문을 확인하거나 DevTools의 "변경감지" 탭에서 exitLocation을 확인하세요.',docLink:"troubleshooting-state.md"}),(n==="early-return-condition"||n==="early-return-validation")&&this.addChangeAlert(e,{type:"early-return-detected",severity:"info",message:`핸들러 "${l.handlerName}"이(가) early return으로 종료됨`,description:i||`종료 위치: ${r||"알 수 없음"}`,handlerName:l.handlerName,suggestion:n==="early-return-validation"?"검증 실패로 인한 early return입니다. 입력 데이터를 확인하세요.":"조건부 early return입니다. 조건문의 평가 결과를 확인하세요."})}recordExitReason(e,n,r,i){if(!this.config.enabled||!e)return;const l=this.executionDetails.get(e);l&&(l.exitReason=n,l.exitLocation=r,l.exitDescription=i)}recordStateChange(e,n,r,i,l){if(!this.config.enabled)return;const c={id:`sc_${++this.stateChangeIdCounter}`,path:n,changeType:r,oldValue:this.safeClone(i),newValue:this.safeClone(l),timestamp:Date.now(),comparison:this.compareValues(i,l),executionId:e};if(this.stateChangeHistory.push(c),e){const d=this.executionDetails.get(e);d&&d.stateChanges.push(c)}this.stateChangeHistory.length>this.maxStateChangeHistory&&this.stateChangeHistory.splice(0,this.stateChangeHistory.length-this.maxStateChangeHistory),c.comparison.isDeepEqual&&typeof i=="object"&&i!==null&&this.addChangeAlert(e||"",{type:"object-reference-same",severity:"warning",message:`상태 "${n}"가 변경되었으나 값이 동일함`,description:"객체 참조가 동일하거나 깊은 비교 결과 변경이 없습니다. 변경 감지가 실패할 수 있습니다.",handlerName:e&&this.executionDetails.get(e)?.handlerName||"unknown",statePath:n,suggestion:"불변성을 유지하여 새 객체를 생성하세요. 예: { ...oldObject, newField: value }",docLink:"troubleshooting-state.md#object-mutation"})}recordDataSourceChange(e,n,r,i,l){if(!this.config.enabled)return;const c={dataSourceId:n,changeType:r,timestamp:Date.now(),previousStatus:i,newStatus:l,executionId:e};if(this.dataSourceChangeHistory.push(c),e){const d=this.executionDetails.get(e);d&&d.dataSourceChanges.push(c)}this.dataSourceChangeHistory.length>this.maxStateChangeHistory&&this.dataSourceChangeHistory.splice(0,this.dataSourceChangeHistory.length-this.maxStateChangeHistory)}expectChange(e,n,r){if(!this.config.enabled||!e)return;const i=this.executionDetails.get(e);if(!i)return;const l={expectedStatePaths:n,expectedDataSources:r,setAt:Date.now(),source:i.handlerName};this.changeExpectations.set(e,l)}checkExpectations(e,n,r){const i=new Set(n.stateChanges.map(c=>c.path)),l=new Set(n.dataSourceChanges.map(c=>c.dataSourceId));for(const c of r.expectedStatePaths)i.has(c)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 상태 변경 "${c}"가 발생하지 않음`,description:`핸들러 "${n.handlerName}"이(가) "${c}" 변경을 예고했지만 실제로 변경되지 않았습니다.`,handlerName:n.handlerName,statePath:c,suggestion:"핸들러 내부 로직을 확인하세요. early return이나 조건부 분기로 인해 변경이 생략되었을 수 있습니다.",docLink:"troubleshooting-state.md"});for(const c of r.expectedDataSources)l.has(c)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 데이터소스 갱신 "${c}"가 발생하지 않음`,description:`핸들러 "${n.handlerName}"이(가) "${c}" 갱신을 예고했지만 실제로 갱신되지 않았습니다.`,handlerName:n.handlerName,dataSourceId:c,suggestion:"refetchDataSource 호출이 실행되었는지 확인하세요.",docLink:"data-sources.md"})}addChangeAlert(e,n){const r={...n,id:`alert_${++this.alertIdCounter}`,timestamp:Date.now()};if(this.changeAlerts.push(r),e){const i=this.executionDetails.get(e);i&&i.alerts.push(r)}this.changeAlerts.length>this.maxChangeAlerts&&this.changeAlerts.splice(0,this.changeAlerts.length-this.maxChangeAlerts)}compareValues(e,n){const r=this.getValueType(e),i=this.getValueType(n),l=r!==i;let c=!1,d;return!l&&(r==="object"||r==="array")?(c=this.deepEqual(e,n),!c&&r==="object"&&(d=this.getChangedKeys(e,n))):c=e===n,{typeChanged:l,oldType:r,newType:i,isDeepEqual:c,changedKeys:d}}getValueType(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}deepEqual(e,n){if(e===n)return!0;if(typeof e!=typeof n)return!1;if(e===null||n===null||typeof e!="object")return e===n;if(Array.isArray(e)!==Array.isArray(n))return!1;const r=Object.keys(e),i=Object.keys(n);if(r.length!==i.length)return!1;for(const l of r)if(!i.includes(l)||!this.deepEqual(e[l],n[l]))return!1;return!0}getChangedKeys(e,n){const r=[],i=new Set([...Object.keys(e),...Object.keys(n)]);for(const l of i)this.deepEqual(e[l],n[l])||r.push(l);return r}getChangeDetectionInfo(){const e=Array.from(this.executionDetails.values()),n={totalExecutions:e.length,executionsWithStateChange:e.filter(r=>r.stateChanges.length>0).length,executionsWithoutStateChange:e.filter(r=>r.stateChanges.length===0&&r.exitReason==="normal").length,earlyReturnCount:e.filter(r=>r.exitReason==="early-return-condition"||r.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:n,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 n of this.changeAlerts)e[n.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,n){let r=[...this.changeAlerts];return n&&(r=r.filter(i=>i.severity===n)),r.slice(-e)}getHandlerExecutions(e,n=10){return Array.from(this.executionDetails.values()).filter(i=>i.handlerName===e).slice(-n)}findExecutionInStack(e){return this.sequenceExecutionStack.find(n=>n.sequenceId===e)}startSequenceExecution(e){if(!this.config.enabled)return"";const n=`seq_${++this.sequenceIdCounter}_${Date.now()}`,r={sequenceId:n,startTime:Date.now(),totalDuration:0,trigger:e,actions:[],status:"running"};return this.sequenceExecutionStack.push(r),n}captureSequenceActionBefore(e,n,r,i,l){if(!this.config.enabled)return;const c=this.findExecutionInStack(e);if(!c)return;const d={index:n,handler:r,params:this.safeClone(i),stateBeforeAction:{_global:this.safeClone(l._global),_local:this.safeClone(l._local),_isolated:l._isolated?this.safeClone(l._isolated):void 0},stateAfterAction:{_global:{},_local:{}},duration:0,status:"success"};c.actions.push(d)}captureSequenceActionAfter(e,n,r,i,l,c){if(!this.config.enabled)return;const d=this.findExecutionInStack(e);if(!d)return;const f=d.actions.find(m=>m.index===n);if(!f)return;f.stateAfterAction={_global:this.safeClone(r._global),_local:this.safeClone(r._local),_isolated:r._isolated?this.safeClone(r._isolated):void 0},f.duration=i,f.result=this.safeClone(l),f.stateDiff={global:this.computeStateDiff(f.stateBeforeAction._global,f.stateAfterAction._global),local:this.computeStateDiff(f.stateBeforeAction._local,f.stateAfterAction._local)},f.stateBeforeAction._isolated&&f.stateAfterAction._isolated&&(f.stateDiff.isolated=this.computeStateDiff(f.stateBeforeAction._isolated,f.stateAfterAction._isolated));const h=window.__g7PendingLocalState;h&&(f.pendingState=this.safeClone(h)),c&&(f.status="error",f.error={name:c.name,message:c.message,stack:c.stack})}endSequenceExecution(e,n){if(!this.config.enabled)return;const r=this.sequenceExecutionStack.findIndex(l=>l.sequenceId===e);if(r===-1)return;const i=this.sequenceExecutionStack[r];if(i.endTime=Date.now(),i.totalDuration=i.endTime-i.startTime,n){i.status="error",i.error={name:n.name,message:n.message,stack:n.stack};const l=i.actions.find(c=>c.status==="error");l&&(i.failedAtIndex=l.index)}else i.status="success";this.sequenceExecutions.push(i),this.sequenceExecutions.length>this.maxSequenceExecutions&&this.sequenceExecutions.shift(),this.sequenceExecutionStack.splice(r,1)}computeStateDiff(e,n){const r=[],i=[],l=[],c=new Set(Object.keys(e)),d=new Set(Object.keys(n));for(const f of d)c.has(f)||r.push(f);for(const f of c)d.has(f)||i.push(f);for(const f of c)if(d.has(f)){const h=e[f],m=n[f];JSON.stringify(h)!==JSON.stringify(m)&&l.push({path:f,oldValue:h,newValue:m})}return{added:r,removed:i,changed:l}}getSequenceTrackingInfo(){const e=this.getSequenceStats(),n=this.sequenceExecutionStack.length>0?this.sequenceExecutionStack[this.sequenceExecutionStack.length-1]:void 0;return{executions:[...this.sequenceExecutions],currentExecution:n,stats:e}}getSequenceStats(){const e=this.sequenceExecutions,n=e.length,r=e.filter(h=>h.status==="success").length,i=e.filter(h=>h.status==="error").length,l=e.reduce((h,m)=>h+m.actions.length,0),c=n>0?e.reduce((h,m)=>h+m.totalDuration,0)/n:0,d={};for(const h of e)for(const m of h.actions)d[m.handler]=(d[m.handler]||0)+1;const f=Object.entries(d).sort(([,h],[,m])=>m-h).slice(0,5).map(([h,m])=>({handler:h,count:m}));return{totalExecutions:n,successCount:r,errorCount:i,totalActions:l,avgDuration:c,topHandlers:f}}clearSequenceData(){this.sequenceExecutions=[],this.sequenceExecutionStack=[],this.sequenceIdCounter=0}getSequenceExecution(e){const n=this.findExecutionInStack(e);return n||this.sequenceExecutions.find(r=>r.sequenceId===e)}getRecentSequences(e=10){return this.sequenceExecutions.slice(-e)}registerStateCaptureForHandler(e,n,r){if(!this.config.enabled)return;const i=new Map,l=Date.now();for(const c of n)i.set(c,{value:this.safeClone(r[c]),capturedAt:l});this.stateCaptureRegistry.set(e,i)}detectStaleClosure(e,n,r,i,l){if(!this.config.enabled)return[];const c=this.stateCaptureRegistry.get(e);if(!c)return[];const d=Date.now(),f=[];for(const[h,m]of c){const y=this.getValueByPath(r,h),v=d-m.capturedAt;if(!this.isDeepEqual(m.value,y)&&v>0){const S=this.createStaleClosureWarning(i,n,h,m.value,m.capturedAt,y,d,v,l);f.push(S),this.addStaleClosureWarning(S)}}return this.stateCaptureRegistry.delete(e),f}trackStaleClosureWarning(e){if(!this.config.enabled)return;const n=Date.now(),r=this.createStaleClosureWarning(e.type,e.location,e.capturedPath,e.capturedValue,e.capturedAt,e.currentValue,n,n-e.capturedAt,e.actionId,e.stackTrace);this.addStaleClosureWarning(r)}createStaleClosureWarning(e,n,r,i,l,c,d,f,h,m){const y=this.getStaleClosureSeverity(e,f),{description:v,suggestion:S,docLink:_}=this.getStaleClosureMessages(e,r,f);return{id:`stale_${++this.staleClosureIdCounter}_${Date.now()}`,timestamp:Date.now(),type:e,location:n,capturedState:{path:r,capturedValue:this.safeClone(i),capturedAt:l},currentState:{path:r,currentValue:this.safeClone(c),retrievedAt:d},timeDiff:f,severity:y,description:v,suggestion:S,docLink:_,actionId:h,stackTrace:m}}getStaleClosureSeverity(e,n){if(n>5e3)return"error";if(n>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,n,r){const i=r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`;switch(e){case"async-state-capture":return{description:`await 후 ${i} 경과 시점에 '${n}' 상태가 변경됨. 캡처된 상태 대신 최신 상태를 사용해야 함`,suggestion:"await 이후에는 G7Core.state.get()으로 최신 상태를 다시 조회하거나, useRef + getter 패턴을 사용하세요",docLink:"troubleshooting-state-closure.md"};case"callback-state-capture":return{description:`콜백에서 ${i} 전에 캡처된 '${n}' 상태를 사용 중. 최신 상태와 다름`,suggestion:"콜백에서 상태를 참조할 때는 stateRef.current 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};case"timeout-state-capture":return{description:`setTimeout/setInterval 콜백에서 '${n}' 상태가 ${i} 전 값 사용 중`,suggestion:"타이머 콜백 내에서는 G7Core.state.get()으로 최신 상태를 조회하세요",docLink:"troubleshooting-state-closure.md"};case"sequence-state-mismatch":return{description:`sequence 내 '${n}' 상태가 이전 액션 결과와 불일치. context.state 대신 캡처된 값 사용 의심`,suggestion:"sequence 내에서는 context.state 또는 $prev를 사용하여 최신 상태를 참조하세요",docLink:"troubleshooting-state-setstate.md"};case"event-handler-stale":return{description:`이벤트 핸들러에서 ${i} 전에 바인딩된 '${n}' 상태 사용 중`,suggestion:"이벤트 핸들러에서 상태를 참조할 때는 useRef 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};default:return{description:`'${n}' 상태에서 stale closure 감지됨 (${i} 경과)`,suggestion:"상태 참조 시 최신 값을 사용하는지 확인하세요"}}}addStaleClosureWarning(e){this.staleClosureWarnings.push(e),this.staleClosureWarnings.length>this.maxStaleClosureWarnings&&this.staleClosureWarnings.shift()}getValueByPath(e,n){const r=n.split(".");let i=e;for(const l of r){if(i==null)return;i=i[l]}return i}isDeepEqual(e,n){if(e===n)return!0;if(e===null||n===null)return e===n;if(typeof e!=typeof n)return!1;if(typeof e!="object")return e===n;try{return JSON.stringify(e)===JSON.stringify(n)}catch{return!1}}getStaleClosureTrackingInfo(){const e=this.getStaleClosureStats();return{warnings:[...this.staleClosureWarnings],stats:e,timestamp:Date.now()}}getStaleClosureStats(){const e=this.staleClosureWarnings,n={"async-state-capture":0,"callback-state-capture":0,"timeout-state-capture":0,"sequence-state-mismatch":0,"event-handler-stale":0};for(const f of e)n[f.type]++;const r={info:0,warning:0,error:0};for(const f of e)r[f.severity]++;const i={};for(const f of e)i[f.location]=(i[f.location]||0)+1;const l=Object.entries(i).sort(([,f],[,h])=>h-f).slice(0,5).map(([f,h])=>({location:f,count:h})),c={};for(const f of e)c[f.capturedState.path]=(c[f.capturedState.path]||0)+1;const d=Object.entries(c).sort(([,f],[,h])=>h-f).slice(0,5).map(([f,h])=>({path:f,count:h}));return{totalWarnings:e.length,warningsByType:n,warningsBySeverity:r,topLocations:l,topAffectedPaths:d}}clearStaleClosureData(){this.staleClosureWarnings=[],this.staleClosureIdCounter=0,this.stateCaptureRegistry.clear()}getRecentStaleClosureWarnings(e=10,n){let r=[...this.staleClosureWarnings];return n&&(r=r.filter(i=>i.severity===n)),r.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(r=>{try{return JSON.parse(JSON.stringify(r))}catch{return"[Unserializable]"}});const n={};for(const r of Object.keys(e))try{n[r]=JSON.parse(JSON.stringify(e[r]))}catch{n[r]="[Unserializable]"}return n}}};M(Li,"instance");let za=Li;const Xn=pt("LayoutLoader");class Rr extends Error{constructor(n,r,i){super(n);M(this,"code");M(this,"details");this.code=r,this.details=i,this.name="LayoutLoaderError"}}class ah{constructor(e){M(this,"componentRegistry");M(this,"currentLayout",null);M(this,"layoutCache",new Map);M(this,"cacheVersion",0);this.componentRegistry=e}setCacheVersion(e){this.cacheVersion!==e&&(Xn.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.layoutCache.clear())}getCacheVersion(){return this.cacheVersion}async loadLayout(e,n){const r=`${e}:${n}`;if(this.layoutCache.has(r)){Xn.log("Loading layout from cache:",n);const l=await this.layoutCache.get(r),c=JSON.parse(JSON.stringify(l));return this.currentLayout=c,za.getInstance().trackLayoutLoad(n,e,c,"cache"),c}const i=this.fetchLayout(e,n);return this.layoutCache.set(r,i),i.catch(()=>{this.layoutCache.get(r)===i&&this.layoutCache.delete(r)}),i}async fetchLayout(e,n,r=!1){try{const i=this.cacheVersion>0?this.cacheVersion:null;let l;if(n.startsWith("__preview__/")){const v=n.replace("__preview__/","");l=Ur(`/api/layouts/preview/${v}`,"json",i)}else l=Ur(`/api/layouts/${e}/${n}`,"json",i);Xn.log("Fetching layout from API:",l);const c=qr(),d=r?null:c.getToken(),f={Accept:"application/json"};d&&(f.Authorization=`Bearer ${d}`);const h=await nc(l,{init:{headers:f},label:`layout: ${n}`});let m;try{m=await h.json()}catch{m=null}if(!h.ok){if(h.status===401&&!r&&d){Xn.log("Token invalid, removing and retrying without token"),c.removeToken();try{return await this.fetchLayout(e,n,!0)}catch(S){throw S instanceof Rr&&S.details?.status===401?new Rr(S.message,S.code,{...S.details,hadToken:!0}):S}}const v=m?.message||m?.error;throw new Rr(`Failed to fetch layout: ${h.status} ${h.statusText}`,"FETCH_FAILED",{status:h.status,statusText:h.statusText,url:l,apiMessage:v})}const y=m.data||m;return this.validateLayoutData(y),this.currentLayout=y,za.getInstance().trackLayoutLoad(n,e,y,"api"),Xn.log("Layout fetched and cached successfully:",y.layout_name),y}catch(i){const l=`${e}:${n}`;throw this.layoutCache.delete(l),i instanceof Rr?i:new Rr("Failed to load layout","LOAD_FAILED",{originalError:i})}}prefetchLayout(e,n){return this.loadLayout(e,n)}validateLayoutData(e){if(!e.version)throw new Rr("Layout data missing required field: version","VALIDATION_FAILED",{field:"version"});if(!e.layout_name)throw new Rr("Layout data missing required field: layout_name","VALIDATION_FAILED",{field:"layout_name"});if(!Array.isArray(e.components))throw new Rr('Layout data field "components" must be an array',"VALIDATION_FAILED",{field:"components",value:e.components});Xn.log("Layout data validation passed")}renderLayout(e,n){try{const r=n||this.currentLayout;if(!r)throw new Rr("No layout data to render","NO_LAYOUT_DATA");Xn.log("Rendering layout:",r.layout_name),e.innerHTML="",this.renderComponents(e,r.components),Xn.log("Layout rendered successfully")}catch(r){Xn.error("Render error:",r),this.renderErrorState(e,r)}}renderComponents(e,n){for(const r of n){const i=this.renderComponent(r);i&&e.appendChild(i)}}renderComponent(e){try{if(!this.componentRegistry.getComponent(e.type))return Xn.warn(`Component not found: ${e.type}`),this.createPlaceholderElement(e.type);const r=document.createElement("div");return r.setAttribute("data-component",e.type),e.props&&Object.entries(e.props).forEach(([i,l])=>{r.setAttribute(`data-prop-${i}`,JSON.stringify(l))}),e.children&&e.children.length>0?this.renderComponents(r,e.children):e.text&&(r.textContent=e.text),r}catch(n){return Xn.error(`Error rendering component ${e.type}:`,n),this.createErrorElement(e.type,n)}}createPlaceholderElement(e){const n=document.createElement("div");return n.className="component-placeholder",n.setAttribute("data-component-type",e),n.innerHTML=` + `},OE={onDragStart(s){let{active:e}=s;return"Picked up draggable item "+e.id+"."},onDragOver(s){let{active:e,over:n}=s;return n?"Draggable item "+e.id+" was moved over droppable area "+n.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(s){let{active:e,over:n}=s;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(s){let{active:e}=s;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function LE(s){let{announcements:e=OE,container:n,hiddenTextDescribedById:r,screenReaderInstructions:i=DE}=s;const{announce:l,announcement:c}=TE(),d=Io("DndLiveRegion"),[f,p]=M.useState(!1);if(M.useEffect(()=>{p(!0)},[]),kE(M.useMemo(()=>({onDragStart(y){let{active:C}=y;l(e.onDragStart({active:C}))},onDragMove(y){let{active:C,over:S}=y;e.onDragMove&&l(e.onDragMove({active:C,over:S}))},onDragOver(y){let{active:C,over:S}=y;l(e.onDragOver({active:C,over:S}))},onDragEnd(y){let{active:C,over:S}=y;l(e.onDragEnd({active:C,over:S}))},onDragCancel(y){let{active:C,over:S}=y;l(e.onDragCancel({active:C,over:S}))}}),[l,e])),!f)return null;const m=We.createElement(We.Fragment,null,We.createElement(AE,{id:r,value:i.draggable}),We.createElement(xE,{id:d,announcement:c}));return n?za.createPortal(m,n):m}var nn;(function(s){s.DragStart="dragStart",s.DragMove="dragMove",s.DragEnd="dragEnd",s.DragCancel="dragCancel",s.DragOver="dragOver",s.RegisterDroppable="registerDroppable",s.SetDroppableDisabled="setDroppableDisabled",s.UnregisterDroppable="unregisterDroppable"})(nn||(nn={}));function Lc(){}function ly(s,e){return M.useMemo(()=>({sensor:s,options:e??{}}),[s,e])}function $E(){for(var s=arguments.length,e=new Array(s),n=0;n[...e].filter(r=>r!=null),[...e])}const kr=Object.freeze({x:0,y:0});function cy(s,e){return Math.sqrt(Math.pow(s.x-e.x,2)+Math.pow(s.y-e.y,2))}function uy(s,e){let{data:{value:n}}=s,{data:{value:r}}=e;return n-r}function ME(s,e){let{data:{value:n}}=s,{data:{value:r}}=e;return r-n}function dy(s){let{left:e,top:n,height:r,width:i}=s;return[{x:e,y:n},{x:e+i,y:n},{x:e,y:n+r},{x:e+i,y:n+r}]}function fy(s,e){if(!s||s.length===0)return null;const[n]=s;return n[e]}function hy(s,e,n){return e===void 0&&(e=s.left),n===void 0&&(n=s.top),{x:e+s.width*.5,y:n+s.height*.5}}const NE=s=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=s;const i=hy(e,e.left,e.top),l=[];for(const c of r){const{id:d}=c,f=n.get(d);if(f){const p=cy(hy(f),i);l.push({id:d,data:{droppableContainer:c,value:p}})}}return l.sort(uy)},IE=s=>{let{collisionRect:e,droppableRects:n,droppableContainers:r}=s;const i=dy(e),l=[];for(const c of r){const{id:d}=c,f=n.get(d);if(f){const p=dy(f),m=i.reduce((C,S,v)=>C+cy(p[v],S),0),y=Number((m/4).toFixed(4));l.push({id:d,data:{droppableContainer:c,value:y}})}}return l.sort(uy)};function jE(s,e){const n=Math.max(e.top,s.top),r=Math.max(e.left,s.left),i=Math.min(e.left+e.width,s.left+s.width),l=Math.min(e.top+e.height,s.top+s.height),c=i-r,d=l-n;if(r{let{collisionRect:e,droppableRects:n,droppableContainers:r}=s;const i=[];for(const l of r){const{id:c}=l,d=n.get(c);if(d){const f=jE(d,e);f>0&&i.push({id:c,data:{droppableContainer:l,value:f}})}}return i.sort(ME)};function HE(s,e,n){return{...s,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function py(s,e){return s&&e?{x:s.left-e.left,y:s.top-e.top}:kr}function UE(s){return function(n){for(var r=arguments.length,i=new Array(r>1?r-1:0),l=1;l({...c,top:c.top+s*d.y,bottom:c.bottom+s*d.y,left:c.left+s*d.x,right:c.right+s*d.x}),{...n})}}const PE=UE(1);function BE(s){if(s.startsWith("matrix3d(")){const e=s.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(s.startsWith("matrix(")){const e=s.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function qE(s,e,n){const r=BE(e);if(!r)return s;const{scaleX:i,scaleY:l,x:c,y:d}=r,f=s.left-c-(1-i)*parseFloat(n),p=s.top-d-(1-l)*parseFloat(n.slice(n.indexOf(" ")+1)),m=i?s.width/i:s.width,y=l?s.height/l:s.height;return{width:m,height:y,top:p,right:f+m,bottom:p+y,left:f}}const GE={ignoreTransform:!1};function ys(s,e){e===void 0&&(e=GE);let n=s.getBoundingClientRect();if(e.ignoreTransform){const{transform:p,transformOrigin:m}=Mn(s).getComputedStyle(s);p&&(n=qE(n,p,m))}const{top:r,left:i,width:l,height:c,bottom:d,right:f}=n;return{top:r,left:i,width:l,height:c,bottom:d,right:f}}function gy(s){return ys(s,{ignoreTransform:!0})}function FE(s){const e=s.innerWidth,n=s.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function VE(s,e){return e===void 0&&(e=Mn(s).getComputedStyle(s)),e.position==="fixed"}function KE(s,e){e===void 0&&(e=Mn(s).getComputedStyle(s));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const l=e[i];return typeof l=="string"?n.test(l):!1})}function $c(s,e){const n=[];function r(i){if(e!=null&&n.length>=e||!i)return n;if(Af(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!$o(i)||ay(i)||n.includes(i))return n;const l=Mn(s).getComputedStyle(i);return i!==s&&KE(i,l)&&n.push(i),VE(i,l)?n:r(i.parentNode)}return s?r(s):n}function my(s){const[e]=$c(s,1);return e??null}function Of(s){return!Dc||!s?null:ps(s)?s:_f(s)?Af(s)||s===gs(s).scrollingElement?window:$o(s)?s:null:null}function yy(s){return ps(s)?s.scrollX:s.scrollLeft}function by(s){return ps(s)?s.scrollY:s.scrollTop}function Lf(s){return{x:yy(s),y:by(s)}}var cn;(function(s){s[s.Forward=1]="Forward",s[s.Backward=-1]="Backward"})(cn||(cn={}));function vy(s){return!Dc||!s?!1:s===document.scrollingElement}function Sy(s){const e={x:0,y:0},n=vy(s)?{height:window.innerHeight,width:window.innerWidth}:{height:s.clientHeight,width:s.clientWidth},r={x:s.scrollWidth-n.width,y:s.scrollHeight-n.height},i=s.scrollTop<=e.y,l=s.scrollLeft<=e.x,c=s.scrollTop>=r.y,d=s.scrollLeft>=r.x;return{isTop:i,isLeft:l,isBottom:c,isRight:d,maxScroll:r,minScroll:e}}const WE={x:.2,y:.2};function YE(s,e,n,r,i){let{top:l,left:c,right:d,bottom:f}=n;r===void 0&&(r=10),i===void 0&&(i=WE);const{isTop:p,isBottom:m,isLeft:y,isRight:C}=Sy(s),S={x:0,y:0},v={x:0,y:0},x={height:e.height*i.y,width:e.width*i.x};return!p&&l<=e.top+x.height?(S.y=cn.Backward,v.y=r*Math.abs((e.top+x.height-l)/x.height)):!m&&f>=e.bottom-x.height&&(S.y=cn.Forward,v.y=r*Math.abs((e.bottom-x.height-f)/x.height)),!C&&d>=e.right-x.width?(S.x=cn.Forward,v.x=r*Math.abs((e.right-x.width-d)/x.width)):!y&&c<=e.left+x.width&&(S.x=cn.Backward,v.x=r*Math.abs((e.left+x.width-c)/x.width)),{direction:S,speed:v}}function XE(s){if(s===document.scrollingElement){const{innerWidth:l,innerHeight:c}=window;return{top:0,left:0,right:l,bottom:c,width:l,height:c}}const{top:e,left:n,right:r,bottom:i}=s.getBoundingClientRect();return{top:e,left:n,right:r,bottom:i,width:s.clientWidth,height:s.clientHeight}}function wy(s){return s.reduce((e,n)=>ms(e,Lf(n)),kr)}function JE(s){return s.reduce((e,n)=>e+yy(n),0)}function QE(s){return s.reduce((e,n)=>e+by(n),0)}function ZE(s,e){if(e===void 0&&(e=ys),!s)return;const{top:n,left:r,bottom:i,right:l}=e(s);my(s)&&(i<=0||l<=0||n>=window.innerHeight||r>=window.innerWidth)&&s.scrollIntoView({block:"center",inline:"center"})}const e_=[["x",["left","right"],JE],["y",["top","bottom"],QE]];class $f{constructor(e,n){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 r=$c(n),i=wy(r);this.rect={...e},this.width=e.width,this.height=e.height;for(const[l,c,d]of e_)for(const f of c)Object.defineProperty(this,f,{get:()=>{const p=d(r),m=i[l]-p;return this.rect[f]+m},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Ho{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var r;return(r=this.target)==null?void 0:r.removeEventListener(...n)})},this.target=e}add(e,n,r){var i;(i=this.target)==null||i.addEventListener(e,n,r),this.listeners.push([e,n,r])}}function t_(s){const{EventTarget:e}=Mn(s);return s instanceof e?s:gs(s)}function Mf(s,e){const n=Math.abs(s.x),r=Math.abs(s.y);return typeof e=="number"?Math.sqrt(n**2+r**2)>e:"x"in e&&"y"in e?n>e.x&&r>e.y:"x"in e?n>e.x:"y"in e?r>e.y:!1}var ur;(function(s){s.Click="click",s.DragStart="dragstart",s.Keydown="keydown",s.ContextMenu="contextmenu",s.Resize="resize",s.SelectionChange="selectionchange",s.VisibilityChange="visibilitychange"})(ur||(ur={}));function Cy(s){s.preventDefault()}function n_(s){s.stopPropagation()}var lt;(function(s){s.Space="Space",s.Down="ArrowDown",s.Right="ArrowRight",s.Left="ArrowLeft",s.Up="ArrowUp",s.Esc="Escape",s.Enter="Enter",s.Tab="Tab"})(lt||(lt={}));const Ey={start:[lt.Space,lt.Enter],cancel:[lt.Esc],end:[lt.Space,lt.Enter,lt.Tab]},r_=(s,e)=>{let{currentCoordinates:n}=e;switch(s.code){case lt.Right:return{...n,x:n.x+25};case lt.Left:return{...n,x:n.x-25};case lt.Down:return{...n,y:n.y+25};case lt.Up:return{...n,y:n.y-25}}};class Nf{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:n}}=e;this.props=e,this.listeners=new Ho(gs(n)),this.windowListeners=new Ho(Mn(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(ur.Resize,this.handleCancel),this.windowListeners.add(ur.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(ur.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,r=e.node.current;r&&ZE(r),n(kr)}handleKeyDown(e){if(Rf(e)){const{active:n,context:r,options:i}=this.props,{keyboardCodes:l=Ey,coordinateGetter:c=r_,scrollBehavior:d="smooth"}=i,{code:f}=e;if(l.end.includes(f)){this.handleEnd(e);return}if(l.cancel.includes(f)){this.handleCancel(e);return}const{collisionRect:p}=r.current,m=p?{x:p.left,y:p.top}:kr;this.referenceCoordinates||(this.referenceCoordinates=m);const y=c(e,{active:n,context:r.current,currentCoordinates:m});if(y){const C=jo(y,m),S={x:0,y:0},{scrollableAncestors:v}=r.current;for(const x of v){const w=e.code,{isTop:R,isRight:L,isLeft:O,isBottom:j,maxScroll:F,minScroll:G}=Sy(x),P=XE(x),K={x:Math.min(w===lt.Right?P.right-P.width/2:P.right,Math.max(w===lt.Right?P.left:P.left+P.width/2,y.x)),y:Math.min(w===lt.Down?P.bottom-P.height/2:P.bottom,Math.max(w===lt.Down?P.top:P.top+P.height/2,y.y))},he=w===lt.Right&&!L||w===lt.Left&&!O,Ee=w===lt.Down&&!j||w===lt.Up&&!R;if(he&&K.x!==y.x){const ke=x.scrollLeft+C.x,ze=w===lt.Right&&ke<=F.x||w===lt.Left&&ke>=G.x;if(ze&&!C.y){x.scrollTo({left:ke,behavior:d});return}ze?S.x=x.scrollLeft-ke:S.x=w===lt.Right?x.scrollLeft-F.x:x.scrollLeft-G.x,S.x&&x.scrollBy({left:-S.x,behavior:d});break}else if(Ee&&K.y!==y.y){const ke=x.scrollTop+C.y,ze=w===lt.Down&&ke<=F.y||w===lt.Up&&ke>=G.y;if(ze&&!C.x){x.scrollTo({top:ke,behavior:d});return}ze?S.y=x.scrollTop-ke:S.y=w===lt.Down?x.scrollTop-F.y:x.scrollTop-G.y,S.y&&x.scrollBy({top:-S.y,behavior:d});break}}this.handleMove(e,ms(jo(y,this.referenceCoordinates),S))}}}handleMove(e,n){const{onMove:r}=this.props;e.preventDefault(),r(n)}handleEnd(e){const{onEnd:n}=this.props;e.preventDefault(),this.detach(),n()}handleCancel(e){const{onCancel:n}=this.props;e.preventDefault(),this.detach(),n()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}Nf.activators=[{eventName:"onKeyDown",handler:(s,e,n)=>{let{keyboardCodes:r=Ey,onActivation:i}=e,{active:l}=n;const{code:c}=s.nativeEvent;if(r.start.includes(c)){const d=l.activatorNode.current;return d&&s.target!==d?!1:(s.preventDefault(),i?.({event:s.nativeEvent}),!0)}return!1}}];function _y(s){return!!(s&&"distance"in s)}function Ay(s){return!!(s&&"delay"in s)}class If{constructor(e,n,r){var i;r===void 0&&(r=t_(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=n;const{event:l}=e,{target:c}=l;this.props=e,this.events=n,this.document=gs(c),this.documentListeners=new Ho(this.document),this.listeners=new Ho(r),this.windowListeners=new Ho(Mn(c)),this.initialCoordinates=(i=Df(l))!=null?i:kr,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:n,bypassActivationConstraint:r}}}=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(ur.Resize,this.handleCancel),this.windowListeners.add(ur.DragStart,Cy),this.windowListeners.add(ur.VisibilityChange,this.handleCancel),this.windowListeners.add(ur.ContextMenu,Cy),this.documentListeners.add(ur.Keydown,this.handleKeydown),n){if(r!=null&&r({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Ay(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(_y(n)){this.handlePending(n);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,n){const{active:r,onPending:i}=this.props;i(r,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(ur.Click,n_,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(ur.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:r,initialCoordinates:i,props:l}=this,{onMove:c,options:{activationConstraint:d}}=l;if(!i)return;const f=(n=Df(e))!=null?n:kr,p=jo(i,f);if(!r&&d){if(_y(d)){if(d.tolerance!=null&&Mf(p,d.tolerance))return this.handleCancel();if(Mf(p,d.distance))return this.handleStart()}if(Ay(d)&&Mf(p,d.tolerance))return this.handleCancel();this.handlePending(d,p);return}e.cancelable&&e.preventDefault(),c(f)}handleEnd(){const{onAbort:e,onEnd:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleCancel(){const{onAbort:e,onCancel:n}=this.props;this.detach(),this.activated||e(this.props.active),n()}handleKeydown(e){e.code===lt.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const a_={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class jf extends If{constructor(e){const{event:n}=e,r=gs(n.target);super(e,a_,r)}}jf.activators=[{eventName:"onPointerDown",handler:(s,e)=>{let{nativeEvent:n}=s,{onActivation:r}=e;return!n.isPrimary||n.button!==0?!1:(r?.({event:n}),!0)}}];const i_={move:{name:"mousemove"},end:{name:"mouseup"}};var zf;(function(s){s[s.RightClick=2]="RightClick"})(zf||(zf={}));class s_ extends If{constructor(e){super(e,i_,gs(e.event.target))}}s_.activators=[{eventName:"onMouseDown",handler:(s,e)=>{let{nativeEvent:n}=s,{onActivation:r}=e;return n.button===zf.RightClick?!1:(r?.({event:n}),!0)}}];const Hf={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class o_ extends If{constructor(e){super(e,Hf)}static setup(){return window.addEventListener(Hf.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(Hf.move.name,e)};function e(){}}}o_.activators=[{eventName:"onTouchStart",handler:(s,e)=>{let{nativeEvent:n}=s,{onActivation:r}=e;const{touches:i}=n;return i.length>1?!1:(r?.({event:n}),!0)}}];var Uo;(function(s){s[s.Pointer=0]="Pointer",s[s.DraggableRect=1]="DraggableRect"})(Uo||(Uo={}));var Mc;(function(s){s[s.TreeOrder=0]="TreeOrder",s[s.ReversedTreeOrder=1]="ReversedTreeOrder"})(Mc||(Mc={}));function l_(s){let{acceleration:e,activator:n=Uo.Pointer,canScroll:r,draggingRect:i,enabled:l,interval:c=5,order:d=Mc.TreeOrder,pointerCoordinates:f,scrollableAncestors:p,scrollableAncestorRects:m,delta:y,threshold:C}=s;const S=u_({delta:y,disabled:!l}),[v,x]=SE(),w=M.useRef({x:0,y:0}),R=M.useRef({x:0,y:0}),L=M.useMemo(()=>{switch(n){case Uo.Pointer:return f?{top:f.y,bottom:f.y,left:f.x,right:f.x}:null;case Uo.DraggableRect:return i}},[n,i,f]),O=M.useRef(null),j=M.useCallback(()=>{const G=O.current;if(!G)return;const P=w.current.x*R.current.x,K=w.current.y*R.current.y;G.scrollBy(P,K)},[]),F=M.useMemo(()=>d===Mc.TreeOrder?[...p].reverse():p,[d,p]);M.useEffect(()=>{if(!l||!p.length||!L){x();return}for(const G of F){if(r?.(G)===!1)continue;const P=p.indexOf(G),K=m[P];if(!K)continue;const{direction:he,speed:Ee}=YE(G,K,L,e,C);for(const ke of["x","y"])S[ke][he[ke]]||(Ee[ke]=0,he[ke]=0);if(Ee.x>0||Ee.y>0){x(),O.current=G,v(j,c),w.current=Ee,R.current=he;return}}w.current={x:0,y:0},R.current={x:0,y:0},x()},[e,j,r,x,l,c,JSON.stringify(L),JSON.stringify(S),v,p,F,m,JSON.stringify(C)])}const c_={x:{[cn.Backward]:!1,[cn.Forward]:!1},y:{[cn.Backward]:!1,[cn.Forward]:!1}};function u_(s){let{delta:e,disabled:n}=s;const r=Tf(e);return No(i=>{if(n||!r||!i)return c_;const l={x:Math.sign(e.x-r.x),y:Math.sign(e.y-r.y)};return{x:{[cn.Backward]:i.x[cn.Backward]||l.x===-1,[cn.Forward]:i.x[cn.Forward]||l.x===1},y:{[cn.Backward]:i.y[cn.Backward]||l.y===-1,[cn.Forward]:i.y[cn.Forward]||l.y===1}}},[n,e,r])}function d_(s,e){const n=e!=null?s.get(e):void 0,r=n?n.node.current:null;return No(i=>{var l;return e==null?null:(l=r??i)!=null?l:null},[r,e])}function f_(s,e){return M.useMemo(()=>s.reduce((n,r)=>{const{sensor:i}=r,l=i.activators.map(c=>({eventName:c.eventName,handler:e(c.handler,r)}));return[...n,...l]},[]),[s,e])}var Po;(function(s){s[s.Always=0]="Always",s[s.BeforeDragging=1]="BeforeDragging",s[s.WhileDragging=2]="WhileDragging"})(Po||(Po={}));var Uf;(function(s){s.Optimized="optimized"})(Uf||(Uf={}));const xy=new Map;function h_(s,e){let{dragging:n,dependencies:r,config:i}=e;const[l,c]=M.useState(null),{frequency:d,measure:f,strategy:p}=i,m=M.useRef(s),y=w(),C=Mo(y),S=M.useCallback(function(R){R===void 0&&(R=[]),!C.current&&c(L=>L===null?R:L.concat(R.filter(O=>!L.includes(O))))},[C]),v=M.useRef(null),x=No(R=>{if(y&&!n)return xy;if(!R||R===xy||m.current!==s||l!=null){const L=new Map;for(let O of s){if(!O)continue;if(l&&l.length>0&&!l.includes(O.id)&&O.rect.current){L.set(O.id,O.rect.current);continue}const j=O.node.current,F=j?new $f(f(j),j):null;O.rect.current=F,F&&L.set(O.id,F)}return L}return R},[s,l,n,y,f]);return M.useEffect(()=>{m.current=s},[s]),M.useEffect(()=>{y||S()},[n,y]),M.useEffect(()=>{l&&l.length>0&&c(null)},[JSON.stringify(l)]),M.useEffect(()=>{y||typeof d!="number"||v.current!==null||(v.current=setTimeout(()=>{S(),v.current=null},d))},[d,y,S,...r]),{droppableRects:x,measureDroppableContainers:S,measuringScheduled:l!=null};function w(){switch(p){case Po.Always:return!1;case Po.BeforeDragging:return n;default:return!n}}}function Ty(s,e){return No(n=>s?n||(typeof e=="function"?e(s):s):null,[e,s])}function p_(s,e){return Ty(s,e)}function g_(s){let{callback:e,disabled:n}=s;const r=xf(e),i=M.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:l}=window;return new l(r)},[r,n]);return M.useEffect(()=>()=>i?.disconnect(),[i]),i}function Nc(s){let{callback:e,disabled:n}=s;const r=xf(e),i=M.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:l}=window;return new l(r)},[n]);return M.useEffect(()=>()=>i?.disconnect(),[i]),i}function m_(s){return new $f(ys(s),s)}function ky(s,e,n){e===void 0&&(e=m_);const[r,i]=M.useState(null);function l(){i(f=>{if(!s)return null;if(s.isConnected===!1){var p;return(p=f??n)!=null?p:null}const m=e(s);return JSON.stringify(f)===JSON.stringify(m)?f:m})}const c=g_({callback(f){if(s)for(const p of f){const{type:m,target:y}=p;if(m==="childList"&&y instanceof HTMLElement&&y.contains(s)){l();break}}}}),d=Nc({callback:l});return Fr(()=>{l(),s?(d?.observe(s),c?.observe(document.body,{childList:!0,subtree:!0})):(d?.disconnect(),c?.disconnect())},[s]),r}function y_(s){const e=Ty(s);return py(s,e)}const Ry=[];function b_(s){const e=M.useRef(s),n=No(r=>s?r&&r!==Ry&&s&&e.current&&s.parentNode===e.current.parentNode?r:$c(s):Ry,[s]);return M.useEffect(()=>{e.current=s},[s]),n}function v_(s){const[e,n]=M.useState(null),r=M.useRef(s),i=M.useCallback(l=>{const c=Of(l.target);c&&n(d=>d?(d.set(c,Lf(c)),new Map(d)):null)},[]);return M.useEffect(()=>{const l=r.current;if(s!==l){c(l);const d=s.map(f=>{const p=Of(f);return p?(p.addEventListener("scroll",i,{passive:!0}),[p,Lf(p)]):null}).filter(f=>f!=null);n(d.length?new Map(d):null),r.current=s}return()=>{c(s),c(l)};function c(d){d.forEach(f=>{const p=Of(f);p?.removeEventListener("scroll",i)})}},[i,s]),M.useMemo(()=>s.length?e?Array.from(e.values()).reduce((l,c)=>ms(l,c),kr):wy(s):kr,[s,e])}function Dy(s,e){e===void 0&&(e=[]);const n=M.useRef(null);return M.useEffect(()=>{n.current=null},e),M.useEffect(()=>{const r=s!==kr;r&&!n.current&&(n.current=s),!r&&n.current&&(n.current=null)},[s]),n.current?jo(s,n.current):kr}function S_(s){M.useEffect(()=>{if(!Dc)return;const e=s.map(n=>{let{sensor:r}=n;return r.setup==null?void 0:r.setup()});return()=>{for(const n of e)n?.()}},s.map(e=>{let{sensor:n}=e;return n}))}function w_(s,e){return M.useMemo(()=>s.reduce((n,r)=>{let{eventName:i,handler:l}=r;return n[i]=c=>{l(c,e)},n},{}),[s,e])}function Oy(s){return M.useMemo(()=>s?FE(s):null,[s])}const Ly=[];function C_(s,e){e===void 0&&(e=ys);const[n]=s,r=Oy(n?Mn(n):null),[i,l]=M.useState(Ly);function c(){l(()=>s.length?s.map(f=>vy(f)?r:new $f(e(f),f)):Ly)}const d=Nc({callback:c});return Fr(()=>{d?.disconnect(),c(),s.forEach(f=>d?.observe(f))},[s]),i}function E_(s){if(!s)return null;if(s.children.length>1)return s;const e=s.children[0];return $o(e)?e:s}function __(s){let{measure:e}=s;const[n,r]=M.useState(null),i=M.useCallback(p=>{for(const{target:m}of p)if($o(m)){r(y=>{const C=e(m);return y?{...y,width:C.width,height:C.height}:C});break}},[e]),l=Nc({callback:i}),c=M.useCallback(p=>{const m=E_(p);l?.disconnect(),m&&l?.observe(m),r(m?e(m):null)},[e,l]),[d,f]=Oc(c);return M.useMemo(()=>({nodeRef:d,rect:n,setRef:f}),[n,d,f])}const A_=[{sensor:jf,options:{}},{sensor:Nf,options:{}}],x_={current:{}},Ic={draggable:{measure:gy},droppable:{measure:gy,strategy:Po.WhileDragging,frequency:Uf.Optimized},dragOverlay:{measure:ys}};class Bo extends Map{get(e){var n;return e!=null&&(n=super.get(e))!=null?n:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:n}=e;return!n})}getNodeFor(e){var n,r;return(n=(r=this.get(e))==null?void 0:r.node.current)!=null?n:void 0}}const T_={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Bo,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:Lc},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:Ic,measureDroppableContainers:Lc,windowRect:null,measuringScheduled:!1},k_={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:Lc,draggableNodes:new Map,over:null,measureDroppableContainers:Lc},jc=M.createContext(k_),$y=M.createContext(T_);function R_(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Bo}}}function D_(s,e){switch(e.type){case nn.DragStart:return{...s,draggable:{...s.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case nn.DragMove:return s.draggable.active==null?s:{...s,draggable:{...s.draggable,translate:{x:e.coordinates.x-s.draggable.initialCoordinates.x,y:e.coordinates.y-s.draggable.initialCoordinates.y}}};case nn.DragEnd:case nn.DragCancel:return{...s,draggable:{...s.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case nn.RegisterDroppable:{const{element:n}=e,{id:r}=n,i=new Bo(s.droppable.containers);return i.set(r,n),{...s,droppable:{...s.droppable,containers:i}}}case nn.SetDroppableDisabled:{const{id:n,key:r,disabled:i}=e,l=s.droppable.containers.get(n);if(!l||r!==l.key)return s;const c=new Bo(s.droppable.containers);return c.set(n,{...l,disabled:i}),{...s,droppable:{...s.droppable,containers:c}}}case nn.UnregisterDroppable:{const{id:n,key:r}=e,i=s.droppable.containers.get(n);if(!i||r!==i.key)return s;const l=new Bo(s.droppable.containers);return l.delete(n),{...s,droppable:{...s.droppable,containers:l}}}default:return s}}function O_(s){let{disabled:e}=s;const{active:n,activatorEvent:r,draggableNodes:i}=M.useContext(jc),l=Tf(r),c=Tf(n?.id);return M.useEffect(()=>{if(!e&&!r&&l&&c!=null){if(!Rf(l)||document.activeElement===l.target)return;const d=i.get(c);if(!d)return;const{activatorNode:f,node:p}=d;if(!f.current&&!p.current)return;requestAnimationFrame(()=>{for(const m of[f.current,p.current]){if(!m)continue;const y=EE(m);if(y){y.focus();break}}})}},[r,e,i,c,l]),null}function L_(s,e){let{transform:n,...r}=e;return s!=null&&s.length?s.reduce((i,l)=>l({transform:i,...r}),n):n}function $_(s){return M.useMemo(()=>({draggable:{...Ic.draggable,...s?.draggable},droppable:{...Ic.droppable,...s?.droppable},dragOverlay:{...Ic.dragOverlay,...s?.dragOverlay}}),[s?.draggable,s?.droppable,s?.dragOverlay])}function M_(s){let{activeNode:e,measure:n,initialRect:r,config:i=!0}=s;const l=M.useRef(!1),{x:c,y:d}=typeof i=="boolean"?{x:i,y:i}:i;Fr(()=>{if(!c&&!d||!e){l.current=!1;return}if(l.current||!r)return;const p=e?.node.current;if(!p||p.isConnected===!1)return;const m=n(p),y=py(m,r);if(c||(y.x=0),d||(y.y=0),l.current=!0,Math.abs(y.x)>0||Math.abs(y.y)>0){const C=my(p);C&&C.scrollBy({top:y.y,left:y.x})}},[e,c,d,r,n])}const My=M.createContext({...kr,scaleX:1,scaleY:1});var Ha;(function(s){s[s.Uninitialized=0]="Uninitialized",s[s.Initializing=1]="Initializing",s[s.Initialized=2]="Initialized"})(Ha||(Ha={}));const N_=M.memo(function(e){var n,r,i,l;let{id:c,accessibility:d,autoScroll:f=!0,children:p,sensors:m=A_,collisionDetection:y=zE,measuring:C,modifiers:S,...v}=e;const x=M.useReducer(D_,void 0,R_),[w,R]=x,[L,O]=RE(),[j,F]=M.useState(Ha.Uninitialized),G=j===Ha.Initialized,{draggable:{active:P,nodes:K,translate:he},droppable:{containers:Ee}}=w,ke=P!=null?K.get(P):null,ze=M.useRef({initial:null,translated:null}),Be=M.useMemo(()=>{var ue;return P!=null?{id:P,data:(ue=ke?.data)!=null?ue:x_,rect:ze}:null},[P,ke]),je=M.useRef(null),[bt,X]=M.useState(null),[de,Ce]=M.useState(null),Z=Mo(v,Object.values(v)),ge=Io("DndDescribedBy",c),z=M.useMemo(()=>Ee.getEnabled(),[Ee]),T=$_(C),{droppableRects:pe,measureDroppableContainers:fe,measuringScheduled:me}=h_(z,{dragging:G,dependencies:[he.x,he.y],config:T.droppable}),ae=d_(K,P),Re=M.useMemo(()=>de?Df(de):null,[de]),Pe=ve(),Me=p_(ae,T.draggable.measure);M_({activeNode:P!=null?K.get(P):null,config:Pe.layoutShiftCompensation,initialRect:Me,measure:T.draggable.measure});const Ge=ky(ae,T.draggable.measure,Me),kt=ky(ae?ae.parentElement:null),vt=M.useRef({activatorEvent:null,active:null,activeNode:ae,collisionRect:null,collisions:null,droppableRects:pe,draggableNodes:K,draggingNode:null,draggingNodeRect:null,droppableContainers:Ee,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),hn=Ee.getNodeFor((n=vt.current.over)==null?void 0:n.id),Dt=__({measure:T.dragOverlay.measure}),Xt=(r=Dt.nodeRef.current)!=null?r:ae,un=G?(i=Dt.rect)!=null?i:Ge:null,Ut=!!(Dt.nodeRef.current&&Dt.rect),$r=y_(Ut?null:Ge),En=Oy(Xt?Mn(Xt):null),dn=b_(G?hn??ae:null),pn=C_(dn),fr=L_(S,{transform:{x:he.x-$r.x,y:he.y-$r.y,scaleX:1,scaleY:1},activatorEvent:de,active:Be,activeNodeRect:Ge,containerNodeRect:kt,draggingNodeRect:un,over:vt.current.over,overlayNodeRect:Dt.rect,scrollableAncestors:dn,scrollableAncestorRects:pn,windowRect:En}),er=Re?ms(Re,he):null,Pt=v_(dn),St=Dy(Pt),da=Dy(Pt,[Ge]),In=ms(fr,St),kn=un?PE(un,fr):null,Rn=Be&&kn?y({active:Be,collisionRect:kn,droppableRects:pe,droppableContainers:z,pointerCoordinates:er}):null,jn=fy(Rn,"id"),[gn,fa]=M.useState(null),zn=Ut?fr:ms(fr,da),Vt=HE(zn,(l=gn?.rect)!=null?l:null,Ge),_n=M.useRef(null),an=M.useCallback((ue,we)=>{let{sensor:_e,options:qe}=we;if(je.current==null)return;const xe=K.get(je.current);if(!xe)return;const De=ue.nativeEvent,Ae=new _e({active:je.current,activeNode:xe,event:De,options:qe,context:vt,onAbort(Ne){if(!K.get(Ne))return;const{onDragAbort:Se}=Z.current,$e={id:Ne};Se?.($e),L({type:"onDragAbort",event:$e})},onPending(Ne,He,Se,$e){if(!K.get(Ne))return;const{onDragPending:Ot}=Z.current,Mt={id:Ne,constraint:He,initialCoordinates:Se,offset:$e};Ot?.(Mt),L({type:"onDragPending",event:Mt})},onStart(Ne){const He=je.current;if(He==null)return;const Se=K.get(He);if(!Se)return;const{onDragStart:$e}=Z.current,et={activatorEvent:De,active:{id:He,data:Se.data,rect:ze}};za.unstable_batchedUpdates(()=>{$e?.(et),F(Ha.Initializing),R({type:nn.DragStart,initialCoordinates:Ne,active:He}),L({type:"onDragStart",event:et}),X(_n.current),Ce(De)})},onMove(Ne){R({type:nn.DragMove,coordinates:Ne})},onEnd:tt(nn.DragEnd),onCancel:tt(nn.DragCancel)});_n.current=Ae;function tt(Ne){return async function(){const{active:Se,collisions:$e,over:et,scrollAdjustedTranslate:Ot}=vt.current;let Mt=null;if(Se&&Ot){const{cancelDrop:Hn}=Z.current;Mt={activatorEvent:De,active:Se,collisions:$e,delta:Ot,over:et},Ne===nn.DragEnd&&typeof Hn=="function"&&await Promise.resolve(Hn(Mt))&&(Ne=nn.DragCancel)}je.current=null,za.unstable_batchedUpdates(()=>{R({type:Ne}),F(Ha.Uninitialized),fa(null),X(null),Ce(null),_n.current=null;const Hn=Ne===nn.DragEnd?"onDragEnd":"onDragCancel";if(Mt){const It=Z.current[Hn];It?.(Mt),L({type:Hn,event:Mt})}})}}},[K]),q=M.useCallback((ue,we)=>(_e,qe)=>{const xe=_e.nativeEvent,De=K.get(qe);if(je.current!==null||!De||xe.dndKit||xe.defaultPrevented)return;const Ae={active:De};ue(_e,we.options,Ae)===!0&&(xe.dndKit={capturedBy:we.sensor},je.current=qe,an(_e,we))},[K,an]),oe=f_(m,q);S_(m),Fr(()=>{Ge&&j===Ha.Initializing&&F(Ha.Initialized)},[Ge,j]),M.useEffect(()=>{const{onDragMove:ue}=Z.current,{active:we,activatorEvent:_e,collisions:qe,over:xe}=vt.current;if(!we||!_e)return;const De={active:we,activatorEvent:_e,collisions:qe,delta:{x:In.x,y:In.y},over:xe};za.unstable_batchedUpdates(()=>{ue?.(De),L({type:"onDragMove",event:De})})},[In.x,In.y]),M.useEffect(()=>{const{active:ue,activatorEvent:we,collisions:_e,droppableContainers:qe,scrollAdjustedTranslate:xe}=vt.current;if(!ue||je.current==null||!we||!xe)return;const{onDragOver:De}=Z.current,Ae=qe.get(jn),tt=Ae&&Ae.rect.current?{id:Ae.id,rect:Ae.rect.current,data:Ae.data,disabled:Ae.disabled}:null,Ne={active:ue,activatorEvent:we,collisions:_e,delta:{x:xe.x,y:xe.y},over:tt};za.unstable_batchedUpdates(()=>{fa(tt),De?.(Ne),L({type:"onDragOver",event:Ne})})},[jn]),Fr(()=>{vt.current={activatorEvent:de,active:Be,activeNode:ae,collisionRect:kn,collisions:Rn,droppableRects:pe,draggableNodes:K,draggingNode:Xt,draggingNodeRect:un,droppableContainers:Ee,over:gn,scrollableAncestors:dn,scrollAdjustedTranslate:In},ze.current={initial:un,translated:kn}},[Be,ae,Rn,kn,K,Xt,un,pe,Ee,gn,dn,In]),l_({...Pe,delta:he,draggingRect:kn,pointerCoordinates:er,scrollableAncestors:dn,scrollableAncestorRects:pn});const ce=M.useMemo(()=>({active:Be,activeNode:ae,activeNodeRect:Ge,activatorEvent:de,collisions:Rn,containerNodeRect:kt,dragOverlay:Dt,draggableNodes:K,droppableContainers:Ee,droppableRects:pe,over:gn,measureDroppableContainers:fe,scrollableAncestors:dn,scrollableAncestorRects:pn,measuringConfiguration:T,measuringScheduled:me,windowRect:En}),[Be,ae,Ge,de,Rn,kt,Dt,K,Ee,pe,gn,fe,dn,pn,T,me,En]),J=M.useMemo(()=>({activatorEvent:de,activators:oe,active:Be,activeNodeRect:Ge,ariaDescribedById:{draggable:ge},dispatch:R,draggableNodes:K,over:gn,measureDroppableContainers:fe}),[de,oe,Be,Ge,R,ge,K,gn,fe]);return We.createElement(oy.Provider,{value:O},We.createElement(jc.Provider,{value:J},We.createElement($y.Provider,{value:ce},We.createElement(My.Provider,{value:Vt},p)),We.createElement(O_,{disabled:d?.restoreFocus===!1})),We.createElement(LE,{...d,hiddenTextDescribedById:ge}));function ve(){const ue=bt?.autoScrollEnabled===!1,we=typeof f=="object"?f.enabled===!1:f===!1,_e=G&&!ue&&!we;return typeof f=="object"?{...f,enabled:_e}:{enabled:_e}}}),I_=M.createContext(null),Ny="button",j_="Draggable";function z_(s){let{id:e,data:n,disabled:r=!1,attributes:i}=s;const l=Io(j_),{activators:c,activatorEvent:d,active:f,activeNodeRect:p,ariaDescribedById:m,draggableNodes:y,over:C}=M.useContext(jc),{role:S=Ny,roleDescription:v="draggable",tabIndex:x=0}=i??{},w=f?.id===e,R=M.useContext(w?My:I_),[L,O]=Oc(),[j,F]=Oc(),G=w_(c,e),P=Mo(n);Fr(()=>(y.set(e,{id:e,key:l,node:L,activatorNode:j,data:P}),()=>{const he=y.get(e);he&&he.key===l&&y.delete(e)}),[y,e]);const K=M.useMemo(()=>({role:S,tabIndex:x,"aria-disabled":r,"aria-pressed":w&&S===Ny?!0:void 0,"aria-roledescription":v,"aria-describedby":m.draggable}),[r,S,x,w,v,m.draggable]);return{active:f,activatorEvent:d,activeNodeRect:p,attributes:K,isDragging:w,listeners:r?void 0:G,node:L,over:C,setNodeRef:O,setActivatorNodeRef:F,transform:R}}function H_(){return M.useContext($y)}const U_="Droppable",P_={timeout:25};function B_(s){let{data:e,disabled:n=!1,id:r,resizeObserverConfig:i}=s;const l=Io(U_),{active:c,dispatch:d,over:f,measureDroppableContainers:p}=M.useContext(jc),m=M.useRef({disabled:n}),y=M.useRef(!1),C=M.useRef(null),S=M.useRef(null),{disabled:v,updateMeasurementsFor:x,timeout:w}={...P_,...i},R=Mo(x??r),L=M.useCallback(()=>{if(!y.current){y.current=!0;return}S.current!=null&&clearTimeout(S.current),S.current=setTimeout(()=>{p(Array.isArray(R.current)?R.current:[R.current]),S.current=null},w)},[w]),O=Nc({callback:L,disabled:v||!c}),j=M.useCallback((K,he)=>{O&&(he&&(O.unobserve(he),y.current=!1),K&&O.observe(K))},[O]),[F,G]=Oc(j),P=Mo(e);return M.useEffect(()=>{!O||!F.current||(O.disconnect(),y.current=!1,O.observe(F.current))},[F,O]),M.useEffect(()=>(d({type:nn.RegisterDroppable,element:{id:r,key:l,disabled:n,node:F,rect:C,data:P}}),()=>d({type:nn.UnregisterDroppable,key:l,id:r})),[r]),M.useEffect(()=>{n!==m.current.disabled&&(d({type:nn.SetDroppableDisabled,id:r,key:l,disabled:n}),m.current.disabled=n)},[r,l,n,d]),{active:c,rect:C,isOver:f?.id===r,node:F,over:f,setNodeRef:G}}function Pf(s,e,n){const r=s.slice();return r.splice(n<0?r.length+n:n,0,r.splice(e,1)[0]),r}function q_(s,e){return s.reduce((n,r,i)=>{const l=e.get(r);return l&&(n[i]=l),n},Array(s.length))}function zc(s){return s!==null&&s>=0}function G_(s,e){if(s===e)return!0;if(s.length!==e.length)return!1;for(let n=0;n{var e;let{rects:n,activeNodeRect:r,activeIndex:i,overIndex:l,index:c}=s;const d=(e=n[i])!=null?e:r;if(!d)return null;const f=K_(n,c,i);if(c===i){const p=n[l];return p?{x:ii&&c<=l?{x:-d.width-f,y:0,...Hc}:c=l?{x:d.width+f,y:0,...Hc}:{x:0,y:0,...Hc}};function K_(s,e,n){const r=s[e],i=s[e-1],l=s[e+1];return!r||!i&&!l?0:n{let{rects:e,activeIndex:n,overIndex:r,index:i}=s;const l=Pf(e,r,n),c=e[i],d=l[i];return!d||!c?null:{x:d.left-c.left,y:d.top-c.top,scaleX:d.width/c.width,scaleY:d.height/c.height}},Uc={scaleX:1,scaleY:1},W_=s=>{var e;let{activeIndex:n,activeNodeRect:r,index:i,rects:l,overIndex:c}=s;const d=(e=l[n])!=null?e:r;if(!d)return null;if(i===n){const p=l[c];return p?{x:0,y:nn&&i<=c?{x:0,y:-d.height-f,...Uc}:i=c?{x:0,y:d.height+f,...Uc}:{x:0,y:0,...Uc}};function Y_(s,e,n){const r=s[e],i=s[e-1],l=s[e+1];return r?nr.map(G=>typeof G=="object"&&"id"in G?G.id:G),[r]),v=c!=null,x=c?S.indexOf(c.id):-1,w=p?S.indexOf(p.id):-1,R=M.useRef(S),L=!G_(S,R.current),O=w!==-1&&x===-1||L,j=F_(l);Fr(()=>{L&&v&&m(S)},[L,S,v,m]),M.useEffect(()=>{R.current=S},[S]);const F=M.useMemo(()=>({activeIndex:x,containerId:y,disabled:j,disableTransforms:O,items:S,overIndex:w,useDragOverlay:C,sortedRects:q_(S,f),strategy:i}),[x,y,j.draggable,j.droppable,O,S,w,f,C,i]);return We.createElement(jy.Provider,{value:F},e)}const J_=s=>{let{id:e,items:n,activeIndex:r,overIndex:i}=s;return Pf(n,r,i).indexOf(e)},Q_=s=>{let{containerId:e,isSorting:n,wasDragging:r,index:i,items:l,newIndex:c,previousItems:d,previousContainerId:f,transition:p}=s;return!p||!r||d!==l&&i===c?!1:n?!0:c!==i&&e===f},Z_={duration:200,easing:"ease"},zy="transform",eA=zo.Transition.toString({property:zy,duration:0,easing:"linear"}),tA={roleDescription:"sortable"};function nA(s){let{disabled:e,index:n,node:r,rect:i}=s;const[l,c]=M.useState(null),d=M.useRef(n);return Fr(()=>{if(!e&&n!==d.current&&r.current){const f=i.current;if(f){const p=ys(r.current,{ignoreTransform:!0}),m={x:f.left-p.left,y:f.top-p.top,scaleX:f.width/p.width,scaleY:f.height/p.height};(m.x||m.y)&&c(m)}}n!==d.current&&(d.current=n)},[e,n,r,i]),M.useEffect(()=>{l&&c(null)},[l]),l}function rA(s){let{animateLayoutChanges:e=Q_,attributes:n,disabled:r,data:i,getNewIndex:l=J_,id:c,strategy:d,resizeObserverConfig:f,transition:p=Z_}=s;const{items:m,containerId:y,activeIndex:C,disabled:S,disableTransforms:v,sortedRects:x,overIndex:w,useDragOverlay:R,strategy:L}=M.useContext(jy),O=aA(r,S),j=m.indexOf(c),F=M.useMemo(()=>({sortable:{containerId:y,index:j,items:m},...i}),[y,i,j,m]),G=M.useMemo(()=>m.slice(m.indexOf(c)),[m,c]),{rect:P,node:K,isOver:he,setNodeRef:Ee}=B_({id:c,data:F,disabled:O.droppable,resizeObserverConfig:{updateMeasurementsFor:G,...f}}),{active:ke,activatorEvent:ze,activeNodeRect:Be,attributes:je,setNodeRef:bt,listeners:X,isDragging:de,over:Ce,setActivatorNodeRef:Z,transform:ge}=z_({id:c,data:F,attributes:{...tA,...n},disabled:O.draggable}),z=vE(Ee,bt),T=!!ke,pe=T&&!v&&zc(C)&&zc(w),fe=!R&&de,me=fe&&pe?ge:null,Re=pe?me??(d??L)({rects:x,activeNodeRect:Be,activeIndex:C,overIndex:w,index:j}):null,Pe=zc(C)&&zc(w)?l({id:c,items:m,activeIndex:C,overIndex:w}):j,Me=ke?.id,Ge=M.useRef({activeId:Me,items:m,newIndex:Pe,containerId:y}),kt=m!==Ge.current.items,vt=e({active:ke,containerId:y,isDragging:de,isSorting:T,id:c,index:j,items:m,newIndex:Ge.current.newIndex,previousItems:Ge.current.items,previousContainerId:Ge.current.containerId,transition:p,wasDragging:Ge.current.activeId!=null}),hn=nA({disabled:!vt,index:j,node:K,rect:P});return M.useEffect(()=>{T&&Ge.current.newIndex!==Pe&&(Ge.current.newIndex=Pe),y!==Ge.current.containerId&&(Ge.current.containerId=y),m!==Ge.current.items&&(Ge.current.items=m)},[T,Pe,y,m]),M.useEffect(()=>{if(Me===Ge.current.activeId)return;if(Me!=null&&Ge.current.activeId==null){Ge.current.activeId=Me;return}const Xt=setTimeout(()=>{Ge.current.activeId=Me},50);return()=>clearTimeout(Xt)},[Me]),{active:ke,activeIndex:C,attributes:je,data:F,rect:P,index:j,newIndex:Pe,items:m,isOver:he,isSorting:T,isDragging:de,listeners:X,node:K,overIndex:w,over:Ce,setNodeRef:z,setActivatorNodeRef:Z,setDroppableNodeRef:Ee,setDraggableNodeRef:bt,transform:hn??Re,transition:Dt()};function Dt(){if(hn||kt&&Ge.current.newIndex===j)return eA;if(!(fe&&!Rf(ze)||!p)&&(T||vt))return zo.Transition.toString({...p,property:zy})}}function aA(s,e){var n,r;return typeof s=="boolean"?{draggable:s,droppable:!1}:{draggable:(n=s?.draggable)!=null?n:e.draggable,droppable:(r=s?.droppable)!=null?r:e.droppable}}function Pc(s){if(!s)return!1;const e=s.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}const iA=[lt.Down,lt.Right,lt.Up,lt.Left],sA=(s,e)=>{let{context:{active:n,collisionRect:r,droppableRects:i,droppableContainers:l,over:c,scrollableAncestors:d}}=e;if(iA.includes(s.code)){if(s.preventDefault(),!n||!r)return;const f=[];l.getEnabled().forEach(y=>{if(!y||y!=null&&y.disabled)return;const C=i.get(y.id);if(C)switch(s.code){case lt.Down:r.topC.top&&f.push(y);break;case lt.Left:r.left>C.left&&f.push(y);break;case lt.Right:r.left1&&(m=p[1].id),m!=null){const y=l.get(n.id),C=l.get(m),S=C?i.get(C.id):null,v=C?.node.current;if(v&&S&&y&&C){const w=$c(v).some((G,P)=>d[P]!==G),R=Hy(y,C),L=oA(y,C),O=w||!R?{x:0,y:0}:{x:L?r.width-S.width:0,y:L?r.height-S.height:0},j={x:S.left,y:S.top};return O.x&&O.y?j:jo(j,O)}}}};function Hy(s,e){return!Pc(s)||!Pc(e)?!1:s.data.current.sortable.containerId===e.data.current.sortable.containerId}function oA(s,e){return!Pc(s)||!Pc(e)||!Hy(s,e)?!1:s.data.current.sortable.index{const d=M.useId(),f=M.useRef({inProgress:!1,lastSortTime:0,lastActiveId:null}),p=$E(ly(jf,{activationConstraint:{distance:5}}),ly(Nf,{coordinateGetter:sA})),m=M.useCallback(S=>{f.current={inProgress:!0,lastSortTime:Date.now(),lastActiveId:S.active.id},l?.({activeId:S.active.id})},[l]),y=M.useCallback(S=>{const{active:v,over:x}=S,w=Date.now();if(!x||v.id===x.id){f.current.inProgress=!1;return}const{lastSortTime:R,lastActiveId:L,inProgress:O}=f.current;if(L===v.id&&w-R<500&&!O)return;f.current={inProgress:!1,lastSortTime:w,lastActiveId:v.id};const j=s.findIndex(G=>String(G[e])===String(v.id)),F=s.findIndex(G=>String(G[e])===String(x.id));if(j!==-1&&F!==-1&&j!==F){const G=Pf(s,j,F);i?.(G,{oldIndex:j,newIndex:F})}},[s,e,i]),C=s.map(S=>String(S[e]));return ft.jsx(N_,{id:d,sensors:p,collisionDetection:NE,onDragStart:m,onDragEnd:y,children:ft.jsx(X_,{items:C,strategy:lA[n],children:r})},c!==void 0?`${d}-v${c}`:d)},Uy=M.createContext(null),uA=({value:s,children:e})=>ft.jsx(Uy.Provider,{value:s,children:e}),dA=()=>M.useContext(Uy),fA=({id:s,handle:e,as:n="div",children:r})=>{const{attributes:i,listeners:l,setNodeRef:c,transform:d,transition:f,isDragging:p}=rA({id:s}),m={transform:zo.Transform.toString(d),transition:f,opacity:p?.5:1,position:"relative"};return ft.jsx(n,{ref:c,style:m,...i,...e?{}:l,"data-sortable-item":!0,"data-sortable-id":String(s),"data-dragging":p,children:ft.jsx(uA,{value:{listeners:l,handle:e,isDragging:p},children:r})})},at=dt("DynamicRenderer");function la(){try{return window.G7Core?.devTools}catch{return}}function qf(s,e,n,r){if(typeof s=="string"){if(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*/.test(s))try{return e.resolveTranslations(s,n,r)}catch{return s}return s}if(Array.isArray(s))return s.map(i=>qf(i,e,n,r));if(s&&typeof s=="object"){const i={};for(const[l,c]of Object.entries(s))i[l]=qf(c,e,n,r);return i}return s}function hA(s){const e=Object.keys(s);return e.length>0&&e.every(n=>/^\d+$/.test(n))}const dr=(s,e)=>{const n=["errors"],r={...s};for(const i of Object.keys(e)){const l=e[i],c=s[i];if(l===null){r[i]=null;continue}if(n.includes(i)){r[i]=l;continue}if(Array.isArray(l)){r[i]=l;continue}if(Array.isArray(c)&&l!==null&&typeof l=="object"&&!Array.isArray(l)&&hA(l)){const d=Object.keys(l).map(p=>parseInt(p,10));if((d.length>0?Math.max(...d):0)>=c.length+d.length+10)r[i]={...l};else{const p=[...c];for(const[m,y]of Object.entries(l)){const C=parseInt(m,10);C>=0&&C=p.length&&(p[C]=y)}r[i]=p}}else l!==null&&typeof l=="object"&&c!==null&&typeof c=="object"&&!Array.isArray(c)?r[i]=dr(c,l):r[i]=l}return r},pA=(s,e,n,r)=>{if(!e||typeof e!="object"||Array.isArray(e))return s;const i=dr(s,e);return ty(i,n,r)},Bc=(s,e)=>{let n=null;const r=()=>(n===null&&(n={...s}),n);for(const i of Object.keys(e)){if(!(i in s))continue;const l=e[i],c=s[i];if(l!==null&&typeof l=="object"&&!Array.isArray(l)&&c!==null&&typeof c=="object"&&!Array.isArray(c)){const d=Bc(c,l);if(d===c)continue;Object.keys(d).length===0?delete r()[i]:r()[i]=d}else delete r()[i]}return n??s},gA=s=>{const e={},n=s.split(";").filter(r=>r.trim());for(const r of n){const i=r.indexOf(":");if(i===-1)continue;const l=r.substring(0,i).trim(),c=r.substring(i+1).trim();if(l&&c){const d=l.replace(/-([a-z])/g,(f,p)=>p.toUpperCase());e[d]=c}}return e};class mA extends M.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,n){at.error(`컴포넌트 렌더링 에러 (ID: ${this.props.componentId}, Name: ${this.props.componentName}):`,e,n)}render(){return this.state.hasError?this.props.fallback?this.props.fallback:ft.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:[ft.jsx("div",{className:"font-semibold mb-1",children:"컴포넌트 로드 실패"}),ft.jsxs("div",{className:"text-xs opacity-80",children:[this.props.componentName&&`[${this.props.componentName}] `,"데이터를 표시할 수 없습니다."]}),this.state.error&&ft.jsxs("details",{className:"mt-2",children:[ft.jsx("summary",{className:"cursor-pointer text-xs opacity-70 hover:opacity-100",children:"상세 정보"}),ft.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 Vr=M.memo(({componentDef:s,dataContext:e,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:d,parentFormContextProp:f,parentDataContext:p,isRootRenderer:m=!1,isInsideIteration:y=!1,isEditMode:C=!1,onComponentSelect:S,onComponentHover:v,onDragStart:x,onDragEnd:w,componentPath:R,layoutKey:L})=>{const[O,j]=M.useState({loadingActions:{}});M.useLayoutEffect(()=>{d||(i.startRenderCycle(),window.__g7SetLocalOverrideKeys||(window.__g7ForcedLocalFields=void 0),window.__g7PendingLocalState=null)});const F=M.useRef(null);M.useLayoutEffect(()=>{if(!d&&e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:q,_merge:oe,...ce}=e._localInit,J=`${JSON.stringify(ce)}:${q||"no-force"}`;if(F.current!==J){F.current=J;const ve=oe||"shallow",we=window.G7Core?.state?.get?.()?._local||{},_e=window.__g7PendingLocalState||{},qe={...we,..._e};ve==="replace"?window.__g7PendingLocalState={loadingActions:qe.loadingActions||{},...ce,hasChanges:!1}:ve==="deep"?window.__g7PendingLocalState=dr(qe,{...ce,hasChanges:!1}):window.__g7PendingLocalState={...qe,...ce,hasChanges:!1};const xe=window.__g7SetLocalOverrideKeys;xe&&typeof xe=="object"&&(ve==="replace"?window.__g7SetLocalOverrideKeys={...ce,hasChanges:!1}:window.__g7SetLocalOverrideKeys=dr(xe,{...ce,hasChanges:!1}))}}}),M.useLayoutEffect(()=>{if(!d){const q=window.__g7SetLocalOverrideKeys;if(q){j(ve=>Bc(ve,q));const oe=q,ce=window.__g7ForcedLocalFields,J=window.__g7LastSetLocalSnapshot;queueMicrotask(()=>{window.__g7SetLocalOverrideKeys===oe&&(window.__g7SetLocalOverrideKeys=void 0),window.__g7ForcedLocalFields===ce&&(window.__g7ForcedLocalFields=void 0),window.__g7LastSetLocalSnapshot===J&&(window.__g7LastSetLocalSnapshot=void 0)})}}},[e._local]);const G=M.useRef(L);M.useEffect(()=>{s._fromBase&&L&&G.current!==L&&(G.current=L,j({loadingActions:{}}))},[L,s._fromBase]);const P=M.useRef(""),K=M.useRef(!1),he=M.useRef(null),Ee=M.useRef(null),ke=M.useRef({}),ze=M.useRef({}),Be=M.useRef(p),je=bE(),bt=YC(),X=bt?.getParentDataContext()??p;M.useEffect(()=>{if(e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:q,...oe}=e._localInit,ce=JSON.stringify(oe),J=q!==void 0,ve=wf(),ue=`${ce}:${q||"no-force"}`,we=rE({globalTrackedKey:ve.hash,instanceHandledKey:Ee.current,trackingKey:ue});if(we==="apply"){Ee.current=ue,ve.hash=ue,ve.timestamp=q,P.current=ce,J&&(K.current=!0);const{_merge:qe,...xe}=oe,De=qe||"shallow";j(Ae=>De==="replace"?{loadingActions:Ae.loadingActions||{},...xe,hasChanges:!1}:De==="deep"?dr(Ae,{...xe,hasChanges:!1}):{...Ae,...xe,hasChanges:!1}),e._globalSetState&&e._globalSetState(Ae=>{const tt=Ae?._local||{};let Ne;return De==="replace"?Ne={...xe,hasChanges:!1}:De==="deep"?Ne=dr(tt,{...xe,hasChanges:!1}):Ne={...tt,...xe,hasChanges:!1},{...Ae,_local:Ne}}),i.invalidateCacheByKeys(["_local"]),at.log("_localInit applied (data changed):",Object.keys(oe))}else if(we==="prune"){Ee.current=ue;const{_merge:qe,...xe}=oe;j(Ae=>Bc(Ae,xe)),Bc(O,xe)!==O&&(i.invalidateCacheByKeys(["_local"]),at.log("_localInit pruned (applied by another renderer):",Object.keys(xe)))}he.current=e._localInit,tE(e._localInit)}},[e._localInit,p,i]);const{isTransitioning:de}=Jm(),Ce=uE(),Z=f??Ce,{width:ge}=Ef(),z=dA(),T=M.useMemo(()=>{let q=s;if(s.type==="iterator"&&s.data){const{data:J,itemName:ve,indexName:ue,...we}=s;q={...we,iteration:{source:J,item_var:ve||"item",index_var:ue}}}if(!q.responsive)return q;const oe=_i.getMatchingKey(q.responsive,ge);if(!oe)return q;const ce=q.responsive[oe];return{...q,props:{...q.props,...ce.props},children:ce.children??q.children,text:ce.text??q.text,if:ce.if??q.if,iteration:ce.iteration??q.iteration,__responsiveChildrenKey:ce.children!==void 0?oe:void 0}},[s,ge]),pe=M.useCallback(q=>{const oe=q?.__setStateId;if(j(ce=>{const J=window.__g7PendingLocalState,ue=window.__g7SetLocalOverrideKeys||J,we=ue?dr(ce,ue):ce;if(typeof q=="function"){const Ae=q(we);return dr(we,Ae)}const{__mergeMode:_e,__setStateId:qe,...xe}=q;let De;if(_e==="replace"?De=xe:_e==="shallow"?De={...we,...xe}:De=dr(we,xe),_e!==void 0){const Ae=window.__g7ForcedLocalFields;Ae&&(window.__g7ForcedLocalFields={...Ae,...xe})}return De}),oe){const ce=la();if(ce?.isEnabled()){const J=T.id||"unknown",ve=T.name||"Unknown";setTimeout(()=>{ce.trackComponentRender?.(J,ve,0,["_local"],[]),ce.completeStateChange?.(oe)},0)}}},[T.id,T.name]),fe=d?.state??O,me=d?.setState??pe,ae=M.useMemo(()=>{const q=e._localInit&&e._localInit!==he.current;let oe;q&&e._local?oe=e._local:oe=e._local?dr(e._local,fe):fe;const ce=window.__g7ForcedLocalFields;ce&&(oe=dr(oe,ce));const J={...e,_local:oe},ve=e._computedDefinitions;if(ve&&Object.keys(ve).length>0){const ue=new Tn,we={...J,...je?{_isolated:je.state}:{}},_e={},qe=la(),xe=qe?.isEnabled()??!1;for(const[De,Ae]of Object.entries(ve)){const tt=xe?Date.now():0,Ne=xe?e._computed?.[De]:void 0;let He;try{if(typeof Ae=="string")if(Ae.startsWith("{{")&&Ae.endsWith("}}")){const Se=Ae.slice(2,-2).trim(),$e=On(Se)?ue.evaluatePipeExpression(Se,we,{skipCache:!0}):ue.evaluateExpression(Se,we,{skipCache:!0});_e[De]=$e}else _e[De]=Ae;else if(Ae&&typeof Ae=="object"&&"$switch"in Ae){const Se=ue.resolveSwitch(Ae,we,{skipCache:!0});_e[De]=Se}}catch(Se){at.warn(`Failed to recalculate computed value: ${De}`,Se),_e[De]=e._computed?.[De],He=Se instanceof Error?Se.message:String(Se)}if(xe&&(He||Ne!==_e[De])){const $e=Date.now()-tt;qe.trackComputedProperty?.(De,typeof Ae=="string"?Ae:JSON.stringify(Ae),[{type:"_local",path:"_local",value:J._local}],_e[De],$e,T.id,He),Ne!==_e[De]&&qe.trackComputedRecalc?.(De,"dependency-change",Ne,_e[De],$e,{type:"_local",path:"_local"},T.id)}}J._computed=_e}if(je&&(J._isolated=je.state),X&&(J.$parent=X),s.extensionPointProps){const ue=i.resolveObject(s.extensionPointProps,J,y?{skipCache:!0}:void 0);J.extensionPointProps=C&&l?qf(ue,l,n,J):ue}return s.extensionPointCallbacks&&(J.extensionPointCallbacks=s.extensionPointCallbacks),C&&(J.$templateId===void 0&&n?.templateId&&(J.$templateId=n.templateId),J.$locale===void 0&&n?.locale&&(J.$locale=n.locale)),J},[e,fe,je?.state,X,bt?.version,s.extensionPointProps,s.extensionPointCallbacks]);ke.current=ae._local,ze.current=ae._computed||{},Be.current=X,M.useEffect(()=>{const q=la();if(!q?.isEnabled())return;const oe=ae._local;oe&&q.updateLocalState(oe);const ce=ae._computed;ce&&q.updateComputedState(ce),X&&q.updateParentContext?.(X);const J=T.id||`comp-${Date.now()}`,ve=T.name||"Unknown",ue={global:Object.keys(e._global||{}),local:Object.keys(oe||{}),context:d?Object.keys(d.state||{}):[]},we={type:d?"componentContext":"dynamicState",hasComponentContext:!!d,parentId:d?"parent":void 0};q.trackComponentStateSource?.(J,ve,ue,we),fe&&Object.keys(fe).length>0&&q.trackDynamicState?.(J,fe);const _e=!!(T.expandChildren||T.props?.expandChildren);q.trackContextFlow?.(J,ve,!!d,_e,!0)},[ae._local,e,T.id,T.name,d,fe,T.expandChildren,T.props?.expandChildren,X]);const Re=M.useMemo(()=>({state:{...ae._local},setState:me,stateRef:ke,computedRef:ze,isolatedContext:je,parentDataContext:ae}),[ae._local,me,O,je,ae]),Pe=M.useMemo(()=>{const q=os({if:T.if,condition:T.condition,conditions:T.conditions},ae,i,T.id);if(T.if||T.condition!==void 0||T.conditions){const ce=la();ce?.isEnabled()&&T.if&&ce.trackIfCondition(T.id||`if-${Date.now()}`,T.if,q)}return q},[T.if,T.conditions,ae,i,T.id]),Me=M.useMemo(()=>{if(!T.slot)return null;const q=T.slot;if(q.startsWith("{{")&&q.endsWith("}}")){const oe=q.slice(2,-2).trim();try{const ce={componentId:T.id,componentName:T.name,propName:"slot"},J=On(oe)?i.evaluatePipeExpression(oe,ae,void 0,ce):i.evaluateExpression(oe,ae,ce);return at.log(`[Slot] 표현식 평가: "${oe}" => "${J}" (컴포넌트: ${T.id})`),typeof J=="string"?J:null}catch(ce){return at.warn(`slot 표현식 평가 실패 (컴포넌트: ${T.id}):`,ce),null}}return at.log(`[Slot] 정적 슬롯 ID: "${q}" (컴포넌트: ${T.id})`),q},[T.slot,T.id,ae,i]),Ge=M.useMemo(()=>!Me||!T.id?"":`${T.id}-${Me}-${JSON.stringify(T.slotOrder??0)}`,[Me,T.id,T.slotOrder]),kt=M.useRef(null);M.useEffect(()=>{const q=window.__slotContextValue,oe=q?.isEnabled??!1;if(T.slot&&at.log(`[Slot Registration] 컴포넌트: ${T.id}, isSlotEnabled: ${oe}, shouldRender: ${Pe}, resolvedSlotId: ${Me}`),!oe||!Pe){T.slot&&at.log(`[Slot Registration] 등록 스킵 - isSlotEnabled: ${oe}, shouldRender: ${Pe}`),kt.current&&T.id&&q&&(q.unregisterFromSlot(kt.current,T.id),kt.current=null);return}if(!Me||!T.id){T.slot&&at.log(`[Slot Registration] 등록 스킵 - resolvedSlotId: ${Me}, id: ${T.id}`),kt.current&&T.id&&q&&(q.unregisterFromSlot(kt.current,T.id),kt.current=null);return}kt.current&&kt.current!==Me&&q.unregisterFromSlot(kt.current,T.id);const ce={...T,slot:void 0,slotOrder:void 0};return q.registerToSlot(Me,T.id,{componentDef:ce,dataContext:e,order:T.slotOrder??0,parentFormContext:f??null,getParentComponentContext:()=>Re,translationContext:n,registrationKey:Ge}),kt.current=Me,()=>{const J=window.__slotContextValue;Me&&T.id&&J&&J.unregisterFromSlot(Me,T.id)}},[Pe,Me,T,e,f,Re,n,Ge]);const vt=M.useCallback(q=>{if(typeof q=="string"){if(oc(q))return Bd(q);if(lc(q)){const oe=[],ce=q.replace(new RegExp(`${yo}([^${Ci}]*)${Ci}`,"g"),(ve,ue)=>(oe.push(ue),`${Na}${oe.length-1}${Na}`));let J=ce;return/\$t:[a-zA-Z0-9._-]+/.test(ce)&&(J=l.resolveTranslations(ce,n,ae)),J.replace(new RegExp(`${Na}(\\d+)${Na}`,"g"),(ve,ue)=>oe[parseInt(ue)])}if(q.startsWith("$t:defer:"))return q;if(/\$t:[a-zA-Z0-9._-]+/.test(q)){const oe=q.trim();return oe.startsWith("{")&&oe.endsWith("}")||oe.startsWith("[")&&oe.endsWith("]")?q:l.resolveTranslations(q,n,ae)}return q}if(Array.isArray(q))return q.map(oe=>vt(oe));if(q&&typeof q=="object"){const oe={};for(const[ce,J]of Object.entries(q))oe[ce]=vt(J);return oe}return q},[l,n,ae]),hn=M.useCallback(q=>mo(q),[]),Dt=M.useCallback(q=>Ma(q),[]),Xt=M.useMemo(()=>{let q={...T.props||{}};const oe=["cellChildren","expandChildren","expandContext","render"],J=r.getMetadata(T.name)?.skipBindingKeys||[],ve=[...new Set([...oe,...J])],ue=y?{skipCache:!0}:void 0,we={...ue??{},skipBindingKeys:ve},_e=Se=>{if(ue)return ue;if(Se.startsWith("_computed")||Se.startsWith("$computed"))return{skipCache:!0}};for(const[Se,$e]of Object.entries(q))if(!ve.includes(Se))if(typeof $e=="string"){const et=Dt($e);if(et!==null){let Ot=!1,Mt=et;et.startsWith(lr)&&(Ot=!0,Mt=et.slice(lr.length));const Hn={componentId:T.id,componentName:T.name,propName:Se};let It;if(On(Mt))try{It=i.evaluatePipeExpression(Mt,ae,_e(Mt),Hn)}catch(jt){at.warn(`파이프 표현식 평가 실패 (컴포넌트: ${T.id}, prop: ${Se}):`,jt),It=void 0}else if(hn(Mt))try{It=i.evaluateExpression(Mt,ae,Hn)}catch(jt){at.warn(`표현식 평가 실패 (컴포넌트: ${T.id}, prop: ${Se}):`,jt),It=void 0}else It=i.resolve(Mt,ae,_e(Mt),Hn);q[Se]=Ot&&It!=null?ss(It):It}else{const Ot={componentId:T.id,componentName:T.name,propName:Se};q[Se]=i.resolveBindings($e,ae,ue,Ot)}}else Array.isArray($e)?q[Se]=$e.map(et=>typeof et=="string"?i.resolveBindings(et,ae,ue):typeof et=="object"&&et!==null?i.resolveObject(et,ae,we):et):$e&&typeof $e=="object"&&(q[Se]=i.resolveObject($e,ae,we));for(const[Se,$e]of Object.entries(q))q[Se]=vt($e);if(typeof q.style=="string"&&(q.style=gA(q.style)),q=ef(q,C?void 0:T.actions,ae,{componentContext:Re,actionDispatcher:c}),T.classMap){const Se=S0(T.classMap,ae,i,{skipCache:!0});if(Se){const $e=q.className||"";q.className=$e?`${$e} ${Se}`:Se}}T.style&&(q.style=T.style),T.actions&&T.actions.length>0&&T.type==="composite"&&Object.assign(q,fe),T.component_layout&&(q.__componentLayoutDefs=T.component_layout);const qe=T.expandChildren||T.props?.expandChildren,xe=T.props?.cellChildren,De=T.children&&T.children.length>0,Ae=T.component_layout,tt=T.slot,Ne=T.props?.modalId,He=T.type==="composite";return(qe||xe||De||Ae||tt||Ne||He)&&(q.__componentContext=Re),q},[T.props,T.actions,T.style,T.classMap,T.id,ae,n,i,l,Re,fe,vt,hn,Dt,y]),un=M.useRef(null),Ut=M.useMemo(()=>un.current&&Zm(un.current,Xt)?un.current:(un.current=Xt,Xt),[Xt]),$r=M.useMemo(()=>{const q=T.id;if(typeof q!="string"||!q.includes("{{"))return q;const oe=i.resolveBindings(q,ae,{skipCache:!0});return typeof oe=="string"?oe:q},[T.id,ae,i]),En=M.useMemo(()=>{const q=T.dataKey,oe=T.trackChanges,ce=T.debounce;if(q){const J=q.startsWith("_global."),ve=J?q.slice(8):q,ue=J?e._global:ae._local;return{dataKey:ve,trackChanges:oe??!1,debounce:ce,setState:J?_e=>{e._globalSetState?e._globalSetState(_e):at.warn("_global.formData 사용 시 _globalSetState가 필요합니다.")}:me,state:ue??{},_isGlobal:J}}if(Z.dataKey)return Z},[T.dataKey,T.trackChanges,T.debounce,T.id,me,ae._local,e._global,e._globalSetState,Z]),dn=M.useRef(new Set);M.useEffect(()=>{dn.current.clear()},[e._global?._remountKeys]);const pn=M.useCallback((q,oe)=>{const ce=e._global?._remountKeys;return q&&ce?.[q]&&!dn.current.has(q)?(dn.current.add(q),`${q}-remount-${ce[q]}`):q||oe},[e._global?._remountKeys]),fr=M.useMemo(()=>{if(T.text!==void 0){if(typeof T.text=="string"){const q=T.text;let oe=q;const ce={componentId:T.id,componentName:T.name,propName:"text",skipCache:!0},J=Dt(q);if(J!==null){let ve=!1,ue=J;if(J.startsWith(lr)&&(ve=!0,ue=J.slice(lr.length)),On(ue))try{oe=i.evaluatePipeExpression(ue,ae,{skipCache:!0},ce)}catch(we){at.warn(`text 파이프 표현식 평가 실패 (컴포넌트: ${T.id}):`,we),oe=""}else if(hn(ue))try{oe=i.evaluateExpression(ue,ae,ce)}catch(we){at.warn(`text 표현식 평가 실패 (컴포넌트: ${T.id}):`,we),oe=""}else oe=i.resolve(ue,ae,{skipCache:!0},ce);ve&&oe!=null&&(oe=ss(oe))}else q.includes("{{")&&(oe=i.resolveBindings(q,ae,{skipCache:!0},ce));return oe=vt(oe),oe??""}return T.text}return!T.children||T.children.length===0?null:T.children.map((q,oe)=>{if(typeof q=="string")return q;const ce=T.__responsiveChildrenKey,J=ce?`responsive.${ce}.children`:"children",ve=R?`${R}.${J}.${oe}`:`${oe}`,ue=q._fromBase?q.id||`child-${oe}`:pn(q.id,`child-${oe}`),we=!q._fromBase&&L?`${ue}_${L}`:ue;return ft.jsx(Vr,{componentDef:q,dataContext:ae,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:Re,parentFormContextProp:En,isInsideIteration:y,isEditMode:C,onComponentSelect:S,onComponentHover:v,componentPath:ve,onDragStart:x,onDragEnd:w,layoutKey:L},we)})},[T.text,T.children,T.id,e,ae,n,r,i,l,c,Re,En,Dt,hn,vt,pn,y,C,S,v,R,x,w,L]),er=M.useMemo(()=>{if(!T.iteration)return null;try{const q=Zd(T.iteration.source,ae,i);if(!Array.isArray(q))return at.warn(`iteration source가 배열이 아닙니다 (컴포넌트: ${T.id}):`,q),null;const oe=la();return oe?.isEnabled()&&oe.trackIteration(T.id||`iteration-${Date.now()}`,T.iteration.source,T.iteration.item_var,T.iteration.index_var,q.length),q.map((ce,J)=>{const ve={...ae,[T.iteration.item_var]:ce,[`${T.iteration.item_var}_index`]:J};T.iteration.index_var&&(ve[T.iteration.index_var]=J);const ue=J===0||J===q.length-1;oe?.isEnabled()&&ue&&oe.trackNestedContext?.({componentId:`${T.id||"unknown"}-iter-${J}`,componentType:"iteration",parentContext:{available:Object.keys(ae),values:{}},ownContext:{added:[T.iteration.item_var,...T.iteration.index_var?[T.iteration.index_var]:[]],values:{[T.iteration.item_var]:ce,...T.iteration.index_var?{[T.iteration.index_var]:J}:{}}},depth:1});const we={...T,iteration:void 0,responsive:void 0},_e=R?`${R}.iteration.${J}`:`iteration.${J}`,qe=`${pn(T.id,"item")}-${J}`;return ft.jsx(Vr,{componentDef:we,dataContext:ve,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:Re,parentFormContextProp:En,isInsideIteration:!0,isEditMode:C,onComponentSelect:S,onComponentHover:v,componentPath:_e,onDragStart:x,onDragEnd:w,layoutKey:L},qe)})}catch(q){return at.error(`iteration 렌더링 실패 (컴포넌트: ${T.id}):`,q),null}},[T.iteration,T.children,T.id,e,ae,n,r,i,l,c,Re,En,pn,C,S,v,R,x,w,L]),[Pt,St]=M.useState(0),da=M.useMemo(()=>{if(!T.sortable||!T.itemTemplate)return null;const{sortable:q,itemTemplate:oe}=T;try{const ce=Zd(q.source,ae,i);if(!Array.isArray(ce))return at.warn(`sortable source가 배열이 아닙니다 (컴포넌트: ${T.id}):`,ce),null;if(ce.length===0)return null;const J=q.itemKey||"id",ve=q.strategy||"verticalList",ue=q.itemVar||"$item",we=q.indexVar||"$index",_e=q.handle,qe=q.wrapperElement,xe=(tt,Ne)=>{const He=T.actions?.filter(Se=>Se.event==="onSortEnd"||Se.type==="onSortEnd");if(St(Se=>Se+1),He&&He.length>0&&c){const Se={...ae,$sortedItems:tt,$sortEvent:Ne};He.forEach($e=>{try{const et=c.createHandler($e,Se,Re),Ot=new Event("sortend");et(Ot)}catch(et){at.error(`onSortEnd action failed: ${$e.handler}`,et)}})}},De=tt=>{const Ne=T.actions?.filter(He=>He.event==="onSortStart"||He.type==="onSortStart");if(Ne&&Ne.length>0&&c){const He={...ae,$activeId:tt.activeId};Ne.forEach(Se=>{try{const $e=c.createHandler(Se,He,Re),et=new Event("sortstart");$e(et)}catch($e){at.error(`onSortStart action failed: ${Se.handler}`,$e)}})}},Ae=ce.map((tt,Ne)=>{const He=String(tt[J]),Se={...ae,[ue]:tt,[we]:Ne},$e=R?`${R}.sortable.${Ne}`:`sortable.${Ne}`,et=`${pn(T.id,"sortable-item")}-v${Pt}-${He}`;return ft.jsx(fA,{id:He,handle:_e,...qe?{as:qe}:{},children:(qe&&oe.children?oe.children:[oe]).map((Ot,Mt)=>ft.jsx(Vr,{componentDef:Ot,dataContext:Se,translationContext:n,registry:r,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:Re,parentFormContextProp:void 0,isInsideIteration:!0,isEditMode:C,onComponentSelect:S,onComponentHover:v,componentPath:$e,onDragStart:x,onDragEnd:w,layoutKey:L},`${et}-child-${Mt}`))},et)});return ft.jsx(cA,{items:ce,itemKey:J,strategy:ve,onSortEnd:xe,onSortStart:De,sortVersion:Pt,children:Ae})}catch(ce){return at.error(`sortable 렌더링 실패 (컴포넌트: ${T.id}):`,ce),null}},[T.sortable,T.itemTemplate,T.actions,T.id,e,ae,n,r,i,l,c,Re,pn,C,S,v,R,x,w,Pt,L]),In=M.useRef(!1);M.useEffect(()=>{if(In.current)return;In.current=!0;const q=la();if(q?.isEnabled()&&q.trackMount(s.id,{name:s.name,type:s.type||"component",props:Ut}),s.lifecycle?.onMount&&s.lifecycle.onMount.length>0)for(const ce of s.lifecycle.onMount)try{const J=c.createHandler(ce,ae,Re),ve=new Event("mount");J(ve),at.log(`Lifecycle onMount executed: ${ce.handler} (Component: ${s.id})`)}catch(J){at.error(`Lifecycle onMount failed: ${ce.handler} (Component: ${s.id})`,J)}const oe=[];if(s.onComponentEvent&&s.onComponentEvent.length>0){const ce=window.G7Core;if(ce?.componentEvent?.on)for(const J of s.onComponentEvent){if(!J.event){at.warn(`onComponentEvent: event name is required (Component: ${s.id})`);continue}const ve=async we=>{try{const _e={...ae,_eventData:we},xe=await c.createHandler({handler:J.handler,params:J.params,onSuccess:J.onSuccess,onError:J.onError},_e,Re)(new CustomEvent(J.event,{detail:we}));return at.log(`onComponentEvent "${J.event}" handled: ${J.handler} (Component: ${s.id})`,{eventData:we,result:xe}),xe}catch(_e){throw at.error(`onComponentEvent "${J.event}" failed: ${J.handler} (Component: ${s.id})`,_e),_e}},ue=ce.componentEvent.on(J.event,ve);oe.push(ue),at.log(`onComponentEvent: Subscribed to "${J.event}" (Component: ${s.id})`)}else at.warn(`onComponentEvent: G7Core.componentEvent is not available (Component: ${s.id})`)}return()=>{const ce=la();ce?.isEnabled()&&ce.trackUnmount(s.id);for(const J of oe)try{J()}catch(ve){at.error(`onComponentEvent: Failed to unsubscribe (Component: ${s.id})`,ve)}if(oe.length>0&&at.log(`onComponentEvent: Unsubscribed ${oe.length} event(s) (Component: ${s.id})`),s.lifecycle?.onUnmount&&s.lifecycle.onUnmount.length>0)for(const J of s.lifecycle.onUnmount)try{const ve=c.createHandler(J,ae,Re),ue=new Event("unmount");ve(ue),at.log(`Lifecycle onUnmount executed: ${J.handler} (Component: ${s.id})`)}catch(ve){at.error(`Lifecycle onUnmount failed: ${J.handler} (Component: ${s.id})`,ve)}}},[]);const kn=M.useMemo(()=>{const q=Ut.dataKey,oe=Ut.trackChanges,ce=Ut.debounce;return q?{dataKey:q,trackChanges:oe??!1,debounce:ce,setState:me,state:fe}:null},[Ut.dataKey,Ut.trackChanges,Ut.debounce,me,fe]);M.useEffect(()=>{const q=T.dataKey||Ut.dataKey;if(!q)return;const oe=la();if(!oe?.isEnabled())return;const ce=[],J=ue=>{if(ue)for(const we of ue){const _e=we?.props?.name;if(_e&&ce.push({name:_e,type:we.name||we.type||"unknown"}),we?.children&&J(we.children),we?.slots)for(const qe of Object.values(we.slots))Array.isArray(qe)&&J(qe)}};if(s.children&&J(s.children),s.slots)for(const ue of Object.values(s.slots))Array.isArray(ue)&&J(ue);const ve=s.id||`form-${q}`;return oe.trackForm(ve,q,ce),()=>{oe.untrackForm(ve)}},[T,Ut.dataKey,s.id,s.children]);const Rn=M.useRef(null),jn=M.useRef(void 0);M.useEffect(()=>{const q=Ut?.name;if(!q||!Z.dataKey||!Z.setState||Ut?.autoBinding===!1)return;const oe=`${Z.dataKey}.${q}`,ce=window.__g7AutoBindingPaths??new Map;return window.__g7AutoBindingPaths=ce,ce.set(oe,(ce.get(oe)??0)+1),()=>{const J=ce.get(oe)??0;J<=1?ce.delete(oe):ce.set(oe,J-1)}},[Ut?.name,Ut?.autoBinding,Z.dataKey,Z.setState]);const gn=M.useMemo(()=>{const{dataKey:q,trackChanges:oe,debounce:ce,...J}=Ut,ve=J.name;if(!ve||!Z.dataKey||!Z.setState)return J;if(J.autoBinding===!1){const{autoBinding:He,...Se}=J;return Se}const ue=`${Z.dataKey}.${ve}`,we=dE(Z.state,ue),_e=we!==void 0?we:J.value,xe=r.getMetadata(s.name)?.bindingType,De=typeof _e=="boolean"&&(xe==="checked"||xe==="checkable"&&["checkbox","radio"].includes(J?.type)),Ae=Z.debounce,tt=He=>{const Se=Z.state||{},$e=ty(Se,ue,He);if(Z.trackChanges&&($e.hasChanges=!0),window.__g7PendingLocalState=pA($e,window.__g7ForcedLocalFields,ue,He),Z.setState($e),Z._isGlobal)return;const et=window.G7Core,Ot={[ue]:He};Z.trackChanges&&(Ot.hasChanges=!0),et?.state?.setLocal?.(Ot,{render:!1})},Ne=(He,Se)=>{Ae&&Ae>0?(Rn.current&&clearTimeout(Rn.current),Rn.current=setTimeout(()=>{tt(He),Rn.current=null,Se&&(Se(),window.__g7PendingLocalState=null)},Ae)):(tt(He),Se&&(Se(),window.__g7PendingLocalState=null))};if(De)return{...J,checked:_e,onChange:Se=>{const $e=Se.target.checked;tt($e),J.onChange&&J.onChange(Se)}};{const He=$e=>{const et=$e?.target?.value!==void 0?$e.target.value:$e;Ae&&Ae>0&&(jn.current=et);const Ot=$e?.target?{target:{value:et,name:$e.target.name,type:$e.target.type,checked:$e.target.checked},currentTarget:$e.currentTarget?{value:et,name:$e.currentTarget.name}:void 0}:$e;Ne(et,()=>{J.onChange&&J.onChange(Ot)})};let Se;return jn.current!==void 0?Rn.current!==null?Se=jn.current:String(_e??"")===String(jn.current)?(jn.current=void 0,Se=_e??""):Se=jn.current:Se=_e??"",{...J,value:Se,onChange:He}}},[Ut,Z,Z.state,Z.debounce]),fa=M.useMemo(()=>{const q=la();if(q?.isEnabled()&&q.trackRender(s.name),!Pe)return T.iteration?er:null;if(T.sortable&&T.itemTemplate)return da;if(T.iteration)return er;if(T.type==="extension_point"){const{layout:xe,columns:De,gap:Ae,className:tt,...Ne}=T.props||{};let He=tt||"";return xe==="grid"&&De?He=`${He} grid grid-cols-${De} gap-${Ae||4}`.trim():xe==="flex"&&(He=`${He} flex flex-col gap-${Ae||4}`.trim()),ft.jsx("div",{id:$r,className:He||void 0,...Ne,children:fr})}const oe=r.getComponent(T.name);if(!oe)return at.error(`컴포넌트를 찾을 수 없습니다: ${T.name} (ID: ${T.id})`,"componentDef:",JSON.stringify(T,null,2)),null;const ce=e._global?._remountKeys,J={...gn,id:gn.id??$r,...ce&&Object.keys(ce).length>0&&{__remountTrigger:JSON.stringify(ce)}};if(z?.listeners&&z.handle&&gn["data-drag-handle"]!==void 0&&(Object.assign(J,z.listeners),J.style={...J.style,cursor:z.isDragging?"grabbing":"grab"}),C){const xe=T.id||`auto_${T.name||T.type||"unknown"}_${Math.random().toString(36).substring(2,8)}`,De=Ne=>{typeof Ne.preventDefault=="function"&&Ne.preventDefault(),S&&(Ne.stopPropagation(),S(xe,Ne))},Ae={"data-editor-id":xe,"data-editor-name":T.name,"data-editor-type":T.type,onClick:De};R&&(Ae["data-editor-path"]=R);const tt=T.__editorSlotName??T.slot;typeof tt=="string"&&(Ae["data-editor-slot"]=tt),v&&(Ae.onMouseMove=Ne=>{Ne.stopPropagation(),v(xe,Ne)},Ae.onMouseLeave=Ne=>{v(null,Ne)}),Object.assign(J,Ae),J.editorAttrs=Ae}const ve=T.type==="basic",ue=T.type==="layout",_e=ve||ue?(()=>{const xe={};for(const[De,Ae]of Object.entries(J))De.startsWith("__")||De==="editorAttrs"&&ve||(xe[De]=Ae);return xe})():J;let qe=ft.jsx(oe,{..._e,children:fr});if(En&&(qe=ft.jsx(cE,{value:En,children:qe})),T.isolatedState){const xe=typeof T.isolatedState=="object"?T.isolatedState:{},De=e?._isolatedInit,Ae=De?{...xe,...De}:xe;qe=ft.jsx(yE,{initialState:Ae,scopeId:T.isolatedScopeId,children:qe})}return qe},[Pe,T.iteration,T.sortable,T.itemTemplate,T.type,T.name,T.id,T.props,T.isolatedState,T.isolatedScopeId,r,gn,fr,er,da,z,kn,C,S,v,x,w,R,e._global?._remountKeys]),zn=M.useMemo(()=>{const q=T.blur_until_loaded;if(!q||e?._global?.__isPreview)return!1;if(typeof q=="string"){const J=Dt(q);if(J!==null)try{const ve={componentId:T.id,componentName:T.name,propName:"blur_until_loaded"};return!!i.evaluateExpression(J,ae,ve)}catch(ve){return at.warn(`blur_until_loaded 표현식 평가 실패 (컴포넌트: ${T.id}):`,ve),!1}return!1}if(typeof q=="object"&&q!==null){if(!q.enabled)return!1;if(q.data_sources)return(Array.isArray(q.data_sources)?q.data_sources:[q.data_sources]).some(we=>e[we]===void 0);if(de)return!0;const J=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(ue=>!J.includes(ue)&&!ue.startsWith("_")).some(ue=>e[ue]===void 0)}if(de)return!0;const oe=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(J=>!oe.includes(J)&&!J.startsWith("_")).some(J=>e[J]===void 0)},[T.blur_until_loaded,T.id,de,e,ae,i,Dt]);if(zn){const q=T.blur_until_loaded;if(typeof q=="object"&&q?.data_sources){const ce=(Array.isArray(q.data_sources)?q.data_sources:[q.data_sources]).reduce((ve,ue)=>(ve[ue]=e[ue]===void 0?"UNDEFINED":"LOADED",ve),{}),J=Object.keys(e).filter(ve=>!ve.startsWith("_"));at.log(`[BLUR APPLIED] Component: ${T.id}, data_sources status:`,ce,"Available keys:",J)}else at.log(`[BLUR APPLIED] Component: ${T.id}, blur_until_loaded:`,q)}const Vt=M.useMemo(()=>{if(!T.blur_until_loaded)return{wrapperClasses:"",innerClasses:""};const q=Xt?.className||"";if(!q)return{wrapperClasses:"",innerClasses:""};const oe=[/^(sm:|md:|lg:|xl:|2xl:)?(col-span-|row-span-|col-start-|col-end-|row-start-|row-end-)/,/^(sm:|md:|lg:|xl:|2xl:)?(self-|place-self-|order-)/,/^(sm:|md:|lg:|xl:|2xl:)?(flex-shrink|flex-grow|flex-\d|basis-)/],ce=q.split(/\s+/).filter(Boolean),J=[],ve=[];for(const ue of ce)oe.some(_e=>_e.test(ue))?J.push(ue):ve.push(ue);return{wrapperClasses:J.join(" "),innerClasses:ve.join(" ")}},[T.blur_until_loaded,Xt?.className]),_n=window.__slotContextValue;return Me&&_n?.isEnabled?null:ft.jsx(mA,{componentId:s.id,componentName:s.name,children:T.blur_until_loaded?ft.jsx("div",{className:[Vt.wrapperClasses,zn?"opacity-50 blur-sm transition-all duration-300 pointer-events-none":void 0].filter(Boolean).join(" ")||void 0,children:fa}):fa})});Vr.displayName="DynamicRenderer",typeof window<"u"&&(window.__DynamicRenderer=Vr);function yA(s){const e={};try{const r=new URL(s,typeof window<"u"?window.location.origin:"http://localhost").searchParams,i=new Set;for(const l of r.keys()){if(i.has(l))continue;i.add(l);const c=r.getAll(l);c.length>1||l.endsWith("[]")?e[l]=c:e[l]=c[0]}}catch{}return e}function bA(s){try{return new URL(s,typeof window<"u"?window.location.origin:"http://localhost").pathname}catch{return s.split("?")[0]}}const $i=class $i{constructor(){$(this,"config",{enabled:!1,maxHistorySize:100,logLevel:"info",serverEndpoint:"/_boost/g7-debug/dump-state",autoCapture:!0});$(this,"stateHistory",[]);$(this,"snapshotIdCounter",0);$(this,"stateWatchers",new Map);$(this,"currentLocalState",{});$(this,"currentComputedState",{});$(this,"currentParentContext");$(this,"actionHistory",[]);$(this,"actionWatchers",new Set);$(this,"cacheStats",{hits:0,misses:0,entries:0});$(this,"cacheDecisions",[]);$(this,"cacheDecisionIdCounter",0);$(this,"maxCacheDecisions",200);$(this,"currentRenderCycleId",null);$(this,"isInActionExecution",!1);$(this,"isInIteration",!1);$(this,"mountedComponents",new Map);$(this,"eventListeners",new Map);$(this,"mountWatchers",new Set);$(this,"unmountWatchers",new Set);$(this,"renderCounts",new Map);$(this,"bindingEvalCount",0);$(this,"profilingData",[]);$(this,"isProfiling",!1);$(this,"profilingStartTime",0);$(this,"activeRequests",new Map);$(this,"requestHistory",[]);$(this,"pendingDataSources",new Set);$(this,"requestWatchers",new Set);$(this,"wsConnections",new Map);$(this,"wsMessageHistory",[]);$(this,"wsMessageWatchers",new Set);$(this,"ifConditions",new Map);$(this,"iterations",new Map);$(this,"conditionWatchers",new Set);$(this,"forms",new Map);$(this,"formWatchers",new Set);$(this,"expressionHistory",[]);$(this,"expressionWatchers",new Set);$(this,"expressionIdCounter",0);$(this,"dataSources",new Map);$(this,"dataPathTransforms",[]);$(this,"maxDataPathTransforms",100);$(this,"nestedContexts",[]);$(this,"nestedContextIdCounter",0);$(this,"maxNestedContexts",100);$(this,"formBindingIssues",[]);$(this,"formBindingValidations",[]);$(this,"formBindingIssueIdCounter",0);$(this,"maxFormBindingIssues",100);$(this,"computedProperties",new Map);$(this,"computedRecalcLogs",[]);$(this,"computedRecalcIdCounter",0);$(this,"maxComputedRecalcLogs",100);$(this,"handlers",new Map);$(this,"componentEventSubscriptions",new Map);$(this,"componentEventEmitHistory",[]);$(this,"componentEventIdCounter",0);$(this,"maxComponentEventHistory",100);$(this,"stateRenderingLogs",[]);$(this,"currentStateChangeContext",null);$(this,"stateRenderingIdCounter",0);$(this,"componentRenderCounts",new Map);$(this,"stateToComponentMap",new Map);$(this,"maxStateRenderingLogs",100);$(this,"componentStateSources",new Map);$(this,"contextFlowNodes",new Map);$(this,"dynamicStates",new Map);$(this,"styleIssues",[]);$(this,"componentStyles",new Map);$(this,"authEvents",[]);$(this,"authHeaderHistory",[]);$(this,"authEventIdCounter",0);$(this,"maxAuthEventHistory",50);$(this,"logHistory",[]);$(this,"logIdCounter",0);$(this,"maxLogHistory",500);$(this,"currentLayout",null);$(this,"layoutHistory",[]);$(this,"layoutIdCounter",0);$(this,"layoutStats",{totalLoads:0,cacheHits:0,apiLoads:0});$(this,"maxLayoutHistory",50);$(this,"executionDetails",new Map);$(this,"stateChangeHistory",[]);$(this,"dataSourceChangeHistory",[]);$(this,"changeAlerts",[]);$(this,"changeExpectations",new Map);$(this,"executionIdCounter",0);$(this,"stateChangeIdCounter",0);$(this,"alertIdCounter",0);$(this,"maxExecutionDetails",100);$(this,"maxStateChangeHistory",200);$(this,"maxChangeAlerts",100);$(this,"sequenceExecutions",[]);$(this,"sequenceExecutionStack",[]);$(this,"sequenceIdCounter",0);$(this,"maxSequenceExecutions",50);$(this,"staleClosureWarnings",[]);$(this,"staleClosureIdCounter",0);$(this,"maxStaleClosureWarnings",100);$(this,"stateCaptureRegistry",new Map);$(this,"modalStates",new Map);$(this,"modalStateIssues",[]);$(this,"modalStateRelations",[]);$(this,"modalStateChangeLogs",[]);$(this,"modalStateIssueIdCounter",0);$(this,"modalStateChangeLogIdCounter",0);$(this,"maxModalStateIssues",100);$(this,"maxModalStateChangeLogs",200);$(this,"namedActionDefinitions",{});$(this,"namedActionRefLogs",[]);$(this,"namedActionRefIdCounter",0);$(this,"maxNamedActionRefLogs",200);$(this,"debounceActionHistory",[]);$(this,"dataSourceUpdateHistory",[]);$(this,"debounceActionIdCounter",0);$(this,"dataSourceUpdateIdCounter",0)}static getInstance(){return $i.instance||($i.instance=new $i),$i.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 r=window.G7Core?.state?.get?.();return r?.settings?.advanced?.debug_mode===!0||r?._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 n={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(n),this.stateHistory.length>this.config.maxHistorySize&&this.stateHistory.shift(),this.notifyStateWatchers(n)}getState(){try{const e=window.G7Core,n=e?.state?.get?.()||{},r={};if(e?._isolatedStates&&typeof e._isolatedStates=="object")for(const[i,l]of Object.entries(e._isolatedStates))r[i]=this.sanitizeObject(l);return{_global:n._global||n,_local:this.currentLocalState,_computed:this.currentComputedState,_isolated:Object.keys(r).length>0?r: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 n={};try{n=(window.G7Core?.state?.get?.()||{})._local||{}}catch{n={}}const r=this.findMismatchedLeafPaths(e,n);return{hasMismatch:r.length>0,mismatchedPaths:r,storageA:e,storageB:n}}findMismatchedLeafPaths(e,n,r=""){const i=[],l=new Set([...Object.keys(e||{}),...Object.keys(n||{})]);for(const c of l){const d=r?`${r}.${c}`:c,f=e?.[c],p=n?.[c],m=f&&typeof f=="object"&&!Array.isArray(f),y=p&&typeof p=="object"&&!Array.isArray(p);if(m&&y)i.push(...this.findMismatchedLeafPaths(f,p,d));else{const C=f===void 0?"__undefined__":JSON.stringify(f),S=p===void 0?"__undefined__":JSON.stringify(p);C!==S&&i.push(d)}}return i}watchState(e,n){return this.stateWatchers.has(e)||this.stateWatchers.set(e,new Set),this.stateWatchers.get(e).add(n),()=>{this.stateWatchers.get(e)?.delete(n)}}notifyStateWatchers(e){if(this.stateWatchers.get("*")?.forEach(n=>{try{n(e.next,e.prev,"*")}catch(r){console.error("[G7DevTools] State watcher error:",r)}}),e.diff)for(const n of e.diff.changed)this.stateWatchers.get(n.path)?.forEach(r=>{try{r(n.newValue,n.oldValue,n.path)}catch(i){console.error("[G7DevTools] State watcher error:",i)}})}diffSnapshots(e,n){const r=this.stateHistory.find(l=>l.id===e),i=this.stateHistory.find(l=>l.id===n);return!r||!i?null:this.calculateDiff(r.next,i.next)}calculateDiff(e,n,r=""){const i={added:[],removed:[],changed:[]},l=new Set(Object.keys(e)),c=new Set(Object.keys(n));for(const d of c){const f=r?`${r}.${d}`:d;l.has(d)?JSON.stringify(e[d])!==JSON.stringify(n[d])&&i.changed.push({path:f,oldValue:e[d],newValue:n[d]}):i.added.push(f)}for(const d of l){const f=r?`${r}.${d}`:d;c.has(d)||i.removed.push(f)}return i}logAction(e){if(!this.config.enabled)return;const n=this.actionHistory.findIndex(r=>r.id===e.id);n>=0?this.actionHistory[n]={...this.actionHistory[n],...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(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Action watcher error:",r)}})}getActionMetrics(){const e=this.actionHistory.filter(l=>l.status==="success"),n=this.actionHistory.filter(l=>l.status==="error"),r={};for(const l of this.actionHistory)r[l.type]=(r[l.type]||0)+1;const i=e.reduce((l,c)=>l+(c.duration||0),0);return{totalActions:this.actionHistory.length,successCount:e.length,errorCount:n.length,averageDuration:e.length>0?i/e.length:0,actionsByType:r}}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 n={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(n),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 n=0,r=0,i=0,l=0;const c={},d={};for(const p of e)p.decision==="cache_hit"?n++:p.decision==="cache_miss"?r++:p.decision==="skip_cache"?i++:p.decision==="invalidate"&&l++,c[p.reason]=(c[p.reason]||0)+1,p.context.componentId&&(d[p.context.componentId]=(d[p.context.componentId]||0)+1);const f=n+r+i;return{totalDecisions:e.length,cacheHits:n,cacheMisses:r,skipCacheCount:i,invalidateCount:l,byReason:c,byComponent:d,avgHitRate:f>0?n/f:0}}getRecentCacheDecisions(e=20,n){let r=[...this.cacheDecisions];return n&&(r=r.filter(i=>i.decision===n)),r.slice(-e)}clearCacheDecisionData(){this.cacheDecisions=[],this.cacheDecisionIdCounter=0}summarizePropsForLifecycle(e){if(!e||typeof e!="object")return e;const n={},r=["children","ref","key"];for(const[i,l]of Object.entries(e))if(!r.includes(i))if(l==null)n[i]=l;else if(Array.isArray(l))n[i]=`[Array(${l.length})]`;else if(typeof l=="object"){const c=Object.keys(l);c.length<=3?n[i]=`{${c.join(", ")}}`:n[i]=`{${c.slice(0,3).join(", ")}, ... +${c.length-3}}`}else typeof l=="string"&&l.length>50?n[i]=l.substring(0,50)+"...":typeof l=="function"?n[i]="[Function]":n[i]=l;return n}trackMount(e,n){if(!this.config.enabled)return;const r=this.summarizePropsForLifecycle(n.props),i={...n,props:r,id:e,mountTime:Date.now()};this.mountedComponents.set(e,i),this.mountWatchers.forEach(l=>{try{l({componentId:e,componentName:n.name,timestamp:i.mountTime})}catch(c){console.error("[G7DevTools] Mount watcher error:",c)}})}trackUnmount(e){if(!this.config.enabled)return;const n=this.mountedComponents.get(e),r=this.eventListeners.get(e)||[];r.length>0&&console.warn(`[G7DevTools] 컴포넌트 ${e} 언마운트 시 ${r.length}개 리스너 미정리`),n&&this.unmountWatchers.forEach(i=>{try{i({componentId:e,componentName:n.name,timestamp:Date.now(),orphanedListeners:r.length})}catch(l){console.error("[G7DevTools] Unmount watcher error:",l)}}),this.mountedComponents.delete(e)}trackListener(e,n,r){if(!this.config.enabled)return;const i=this.eventListeners.get(e)||[];i.push({type:n,target:r,addedAt:Date.now()}),this.eventListeners.set(e,i)}removeListener(e,n){if(!this.config.enabled)return;const r=this.eventListeners.get(e)||[],i=r.findIndex(l=>l.type===n);i>=0&&r.splice(i,1)}getMountedComponents(){return Array.from(this.mountedComponents.values())}getOrphanedListeners(){const e=[];for(const[n,r]of this.eventListeners)this.mountedComponents.has(n)||e.push(...r.map(i=>({...i,componentId:n})));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 n=this.renderCounts.get(e)||0;this.renderCounts.set(e,n+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(),l=JSON.stringify(i).length;l>1e6&&e.push({type:"large-state",message:`상태 크기가 ${(l/1024/1024).toFixed(2)}MB입니다`,suggestion:"불필요한 데이터 정리 필요",severity:l>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 n=this.getOrphanedListeners().length;n>0&&e.push({type:"orphaned-listeners",message:`${n}개의 정리되지 않은 이벤트 리스너`,suggestion:"useEffect cleanup 또는 removeEventListener 확인",severity:n>10?"error":"warning"});const r=Array.from(this.renderCounts.entries()).filter(([,i])=>i>50);return r.length>0&&e.push({type:"excessive-renders",message:`${r.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,n=this.analyzeProfile(e);return console.log("[G7DevTools] 프로파일링 완료",n),n}analyzeProfile(e){const n=this.profilingData.filter(p=>p.type==="render"),r=this.profilingData.filter(p=>p.type==="binding"),i=this.profilingData.filter(p=>p.type==="action"),l={};for(const p of n)p.component&&(l[p.component]||(l[p.component]={count:0,durations:[]}),l[p.component].count++,p.duration&&l[p.component].durations.push(p.duration));const c=Object.entries(l).map(([p,m])=>({name:p,renderCount:m.count,avgDuration:m.durations.length>0?m.durations.reduce((y,C)=>y+C,0)/m.durations.length:0})).sort((p,m)=>m.renderCount-p.renderCount).slice(0,10),d={};for(const p of r)p.expression&&(d[p.expression]=(d[p.expression]||0)+1);const f=Object.entries(d).sort(([,p],[,m])=>m-p).slice(0,10).map(([p])=>p);return{duration:e,entries:this.profilingData,summary:{totalRenders:n.length,totalBindings:r.length,totalActions:i.length,slowestComponents:c,hotPaths:f}}}resetPerformanceStats(){this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[]}trackRequest(e,n,r){if(!this.config.enabled)return"";const i=this.generateId(),l=bA(e),c=yA(e);return this.activeRequests.set(i,{id:i,url:l,fullUrl:e,queryParams:c,method:n,startTime:Date.now(),status:"pending",requestBody:r?.requestBody?this.sanitizeObject(r.requestBody):void 0,dataSourceId:r?.dataSourceId}),this.isProfiling&&this.profilingData.push({type:"network",timestamp:performance.now()}),i}completeRequest(e,n,r){if(!this.config.enabled)return;const i=this.activeRequests.get(e);if(!i)return;const l={...i,status:n>=200&&n<300?"success":"error",statusCode:n,duration:Date.now()-i.startTime,endTime:Date.now(),response:this.sanitizeObject(r)};this.requestHistory.push(l),this.activeRequests.delete(e),this.requestHistory.length>this.config.maxHistorySize&&this.requestHistory.shift(),this.notifyRequestWatchers(l)}failRequest(e,n){if(!this.config.enabled)return;const r=this.activeRequests.get(e);if(!r)return;const i={...r,status:"error",error:n,duration:Date.now()-r.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(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Request watcher error:",r)}})}trackWebSocketConnection(e,n,r){this.config.enabled&&this.wsConnections.set(e,{id:e,url:n,state:r,connectedAt:r==="open"?Date.now():void 0})}trackWebSocketMessage(e,n,r,i){if(!this.config.enabled)return;const l={id:this.generateId(),connectionId:e,direction:n,type:r,payload:this.sanitizeObject(i),timestamp:Date.now(),sequence:this.wsMessageHistory.length};this.wsMessageHistory.push(l),this.wsMessageHistory.length>this.config.maxHistorySize&&this.wsMessageHistory.shift(),this.notifyWebSocketWatchers(l)}getWebSocketConnections(){return Array.from(this.wsConnections.values())}getWebSocketMessageHistory(){return[...this.wsMessageHistory]}getWebSocketConnectionState(){const e=Array.from(this.wsConnections.values());return e.some(n=>n.state==="open")?"connected":e.some(n=>n.state==="connecting")?"reconnecting":"disconnected"}watchWebSocketMessage(e){return this.wsMessageWatchers.add(e),()=>{this.wsMessageWatchers.delete(e)}}notifyWebSocketWatchers(e){this.wsMessageWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] WebSocket watcher error:",r)}})}trackIfCondition(e,n,r){if(!this.config.enabled)return;const i=this.ifConditions.get(e),l=i?.evaluatedValue;this.ifConditions.set(e,{id:e,expression:n,evaluatedValue:r,evaluationCount:(i?.evaluationCount||0)+1,lastEvaluated:Date.now()}),i&&l!==r&&this.notifyConditionWatchers({id:e,expression:n,oldValue:l,newValue:r,timestamp:Date.now()})}trackIteration(e,n){this.config.enabled&&this.iterations.set(e,{id:e,...n,lastRendered:Date.now()})}getIfConditions(){return Array.from(this.ifConditions.values())}getIterations(){return Array.from(this.iterations.values())}getScopeChain(e){const n=[],r=this.getState();return n.push({name:"_global",value:r._global,source:"global"}),n.push({name:"_local",value:r._local,source:"local"}),n.push({name:"_computed",value:r._computed,source:"computed"}),n}watchConditionChange(e){return this.conditionWatchers.add(e),()=>{this.conditionWatchers.delete(e)}}notifyConditionWatchers(e){this.conditionWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Condition watcher error:",r)}})}trackForm(e,n,r){this.config.enabled&&this.forms.set(e,{id:e,dataKey:n,inputs:r,trackedAt:Date.now()})}trackFormChange(e,n,r){if(!this.config.enabled)return;const i={formId:e,inputName:n,value:r,timestamp:Date.now()};this.notifyFormWatchers(i)}untrackForm(e){this.forms.delete(e)}getForms(){return Array.from(this.forms.values())}getFormState(e){const n=this.getState();return this.getNestedValue(n,e)||{}}getBindingPath(e,n){return`${e}.${n}`}watchFormChange(e){return this.formWatchers.add(e),()=>{this.formWatchers.delete(e)}}notifyFormWatchers(e){this.formWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Form watcher error:",r)}})}trackFormBindingIssue(e,n,r){if(!this.config.enabled)return;const i={id:`form-issue-${++this.formBindingIssueIdCounter}`,timestamp:Date.now(),type:e,severity:n,formId:r.formId,formDataKey:r.formDataKey,inputInfo:r.inputInfo,contextInfo:r.contextInfo,description:r.description,suggestion:r.suggestion,docLink:r.docLink};this.formBindingIssues.push(i),this.formBindingIssues.length>this.maxFormBindingIssues&&this.formBindingIssues.shift()}validateFormBinding(e,n,r,i){const l=r.map(f=>{const p=[];let m=!0;return f.name||(p.push("Input에 name 속성이 없습니다"),m=!1,this.trackFormBindingIssue("missing-input-name","error",{formId:e,formDataKey:n,inputInfo:{name:f.name,type:f.type},description:"Input에 name 속성이 없어 자동 바인딩이 동작하지 않습니다",suggestion:"Input에 name 속성을 추가하세요",docLink:"troubleshooting-components-form.md"})),n||(p.push("Form에 dataKey가 없습니다"),m=!1),{inputName:f.name||"(unnamed)",inputType:f.type,bindingPath:n&&f.name?`${n}.${f.name}`:"-",isValid:m,currentValue:f.value,issues:p}});if(n||this.trackFormBindingIssue("missing-datakey","error",{formId:e,description:"Form에 dataKey가 설정되지 않아 자동 바인딩이 동작하지 않습니다",suggestion:"Form 컴포넌트에 dataKey props를 설정하세요",docLink:"troubleshooting-components-form.md"}),i.isContextBroken){const f=i.breakReason?.includes("sortable")?"sortable-context-break":i.breakReason?.includes("modal")?"modal-context-isolation":"context-not-propagated";this.trackFormBindingIssue(f,"warning",{formId:e,formDataKey:n,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 c={formId:e,dataKey:n,timestamp:Date.now(),contextPropagation:i,inputBindings:l,isValid:l.every(f=>f.isValid)&&!!n&&!i.isContextBroken,issueCount:l.filter(f=>!f.isValid).length+(n?0:1)+(i.isContextBroken?1:0)},d=this.formBindingValidations.findIndex(f=>f.formId===e);return d>=0?this.formBindingValidations[d]=c:this.formBindingValidations.push(c),c}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},n={info:0,warning:0,error:0};for(const i of this.formBindingIssues)e[i.type]++,n[i.severity]++;const r=Object.entries(e).filter(([,i])=>i>0).sort((i,l)=>l[1]-i[1]).slice(0,5).map(([i,l])=>({type:i,count:l,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:n,topIssues:r}}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,n,r,i,l,c,d){if(!this.config.enabled)return;const f=`computed-${e}-${c||"global"}`,p={id:f,name:e,expression:n,componentId:c,dependencies:r,currentValue:this.safeClone(i),lastComputedAt:Date.now(),computationTime:l,error:d};this.computedProperties.set(f,p)}trackComputedRecalc(e,n,r,i,l,c,d){if(!this.config.enabled)return;const f=`computed-${e}-${d||"global"}`,p=JSON.stringify(r)!==JSON.stringify(i),m={id:`recalc-${++this.computedRecalcIdCounter}`,computedId:f,computedName:e,timestamp:Date.now(),trigger:n,triggeredBy:c,previousValue:this.safeClone(r),newValue:this.safeClone(i),valueChanged:p,computationTime:l,cascadeCount:0};this.computedRecalcLogs.push(m),this.computedRecalcLogs.length>this.maxComputedRecalcLogs&&this.computedRecalcLogs.shift();const y=this.computedProperties.get(f);y&&(y.currentValue=this.safeClone(i),y.lastComputedAt=Date.now(),y.computationTime=l)}analyzeComputedDependencyChain(e,n){const r=new Set,i=[];let l=!1,c,d=0;const f=(m,y)=>{if(d=Math.max(d,y),r.has(m))return l=!0,c=[...i,m],{name:m,type:"computed",children:[],depth:y};r.add(m),i.push(m);const C=this.computedProperties.get(`computed-${m}-${n||"global"}`),S=[];if(C)for(const v of C.dependencies)v.type==="computed"?S.push(f(v.path,y+1)):S.push({name:v.path,type:v.type,children:[],depth:y+1});return i.pop(),r.delete(m),{name:m,type:"computed",children:S,depth:y}},p=f(e,0);return{root:e,tree:p,hasCycle:l,cyclePath:c,maxDepth:d}}getComputedDependencyTrackingInfo(){const e=Array.from(this.computedProperties.values()),n=this.getComputedDependencyStats(),r=[];for(const i of e){const l=this.analyzeComputedDependencyChain(i.name,i.componentId);r.push(l)}return{properties:e,recalcLogs:[...this.computedRecalcLogs],dependencyChains:r,stats:n,timestamp:Date.now()}}getComputedDependencyStats(){const e={"state-change":0,"datasource-update":0,"dependency-change":0,manual:0,initial:0},n={},r={};let i=0,l=0;for(const p of this.computedRecalcLogs)e[p.trigger]++,p.valueChanged||l++,n[p.computedName]=(n[p.computedName]||0)+1,r[p.computedName]||(r[p.computedName]=[]),r[p.computedName].push(p.computationTime),i+=p.computationTime;const c=Object.entries(n).sort((p,m)=>m[1]-p[1]).slice(0,5).map(([p,m])=>({name:p,count:m})),d=Object.entries(r).map(([p,m])=>({name:p,avgTime:m.reduce((y,C)=>y+C,0)/m.length})).sort((p,m)=>m.avgTime-p.avgTime).slice(0,5);let f=0;for(const p of this.computedProperties.values())this.analyzeComputedDependencyChain(p.name,p.componentId).hasCycle&&f++;return{totalComputed:this.computedProperties.size,totalRecalculations:this.computedRecalcLogs.length,unnecessaryRecalculations:l,avgComputationTime:this.computedRecalcLogs.length>0?i/this.computedRecalcLogs.length:0,topRecalculated:c,slowestComputed:d,cycleDetectionCount:f,byTrigger:e}}clearComputedTracking(){this.computedProperties.clear(),this.computedRecalcLogs=[],this.computedRecalcIdCounter=0}trackModalOpen(e){if(!this.config.enabled)return;const n={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,n),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,n){if(!this.config.enabled)return;const r=this.modalStates.get(e);r&&(r.closedAt=Date.now(),n&&(r.currentState={...n}),this.detectStateLeakage(r))}validateModalDefinitionExists(e,n){const r=this.currentLayout;if(!r?.layoutJson)return;const i=r.layoutJson.modals;if(!i){this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:n,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 현재 레이아웃에 modals 섹션이 없습니다. 레이아웃 경로: ${r.layoutPath}`,affectedStateKeys:[],expectedValue:`modals 섹션에 id="${e}" 정의 존재`,actualValue:"modals 섹션 없음"});return}const l=Array.isArray(i)?i:Object.values(i);l.some(d=>d?.id===e||d?.props?.id===e)||this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:n,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 렌더링된 레이아웃의 modals 섹션에 해당 ID의 정의가 없습니다. partial 로딩 실패, 레이아웃 병합 문제, extends 상속 누락 등을 확인하세요. 레이아웃 경로: ${r.layoutPath}`,affectedStateKeys:[],expectedValue:`modals 배열에 id="${e}" 항목 존재`,actualValue:`modals 배열에 ${l.length}개 모달 정의 (${l.map(d=>d?.id||"unknown").join(", ")})`})}trackModalStateChange(e){if(!this.config.enabled)return;const n=this.modalStates.get(e.modalId);if(!n)return;n.stateChangeCount++,n.currentState[e.stateKey]=e.newValue;const r=this.checkIsolationViolation(n,e.stateKey),i={id:`modal-change-${++this.modalStateChangeLogIdCounter}`,modalId:e.modalId,modalName:n.modalName,timestamp:Date.now(),stateKey:e.stateKey,previousValue:e.previousValue,newValue:e.newValue,changeSource:e.changeSource||"user-action",violatesIsolation:r};this.modalStateChangeLogs.push(i),this.modalStateChangeLogs.length>this.maxModalStateChangeLogs&&this.modalStateChangeLogs.shift(),r&&this.recordModalStateIssue({type:"isolation-violation",modalId:e.modalId,modalName:n.modalName,severity:"warning",description:`모달 '${n.modalName}'에서 격리된 상태 키 '${e.stateKey}'가 변경됨`,affectedStateKeys:[e.stateKey]})}detectStateLeakage(e){if(e.scopeType==="isolated")for(const n of e.isolatedStateKeys){const r=e.initialState[n],i=e.currentState[n];if(r!==i&&e.parentModalId){const l=this.modalStates.get(e.parentModalId);l&&l.currentState.hasOwnProperty(n)&&this.recordModalStateIssue({type:"state-leakage",modalId:e.modalId,modalName:e.modalName,severity:"error",description:`모달 닫힘 후 상태 '${n}'가 부모 모달로 유출될 수 있음`,affectedStateKeys:[n],leakedValue:i,expectedValue:r})}}}checkIsolationViolation(e,n){return e.scopeType==="isolated",!1}recordModalStateIssue(e){const n={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(n),this.modalStateIssues.length>this.maxModalStateIssues&&this.modalStateIssues.shift()}getModalStateScopeTrackingInfo(){const e=Array.from(this.modalStates.values()),n=this.getModalStateScopeStats();return{modals:e,issues:[...this.modalStateIssues],relations:[...this.modalStateRelations],changeLogs:[...this.modalStateChangeLogs],stats:n,timestamp:Date.now()}}getModalStateScopeStats(){const e=Array.from(this.modalStates.values()),n={warning:0,error:0},r={"state-leakage":0,"isolation-violation":0,"parent-mutation":0,"orphaned-state":0,"scope-mismatch":0,"cleanup-failure":0,"missing-definition":0};for(const l of this.modalStateIssues)n[l.severity]++,r[l.type]++;const i={isolated:0,shared:0,inherited:0};for(const l of e)i[l.scopeType]++;return{totalModals:e.length,openModals:e.filter(l=>l.closedAt===null).length,nestedModals:e.filter(l=>l.parentModalId!==void 0).length,totalIssues:this.modalStateIssues.length,issuesBySeverity:n,issuesByType:r,byScope:i,leakageDetectionCount:r["state-leakage"],cleanupFailureCount:r["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 n={...e,id:`named_action_ref_${++this.namedActionRefIdCounter}`};this.namedActionRefLogs.push(n),this.namedActionRefLogs.length>this.maxNamedActionRefLogs&&(this.namedActionRefLogs=this.namedActionRefLogs.slice(-this.maxNamedActionRefLogs))}getNamedActionTrackingInfo(){const e={};for(const r of this.namedActionRefLogs)e[r.actionRefName]=(e[r.actionRefName]||0)+1;const n=Object.keys(this.namedActionDefinitions).filter(r=>!e[r]);return{definitions:this.namedActionDefinitions,refLogs:[...this.namedActionRefLogs],stats:{totalDefinitions:Object.keys(this.namedActionDefinitions).length,totalRefs:this.namedActionRefLogs.length,refCountByName:e,unusedDefinitions:n},timestamp:Date.now()}}clearNamedActionTracking(){this.namedActionDefinitions={},this.namedActionRefLogs=[],this.namedActionRefIdCounter=0}trackExpressionEval(e){if(!this.config.enabled)return;const n={...e,id:`expr-${++this.expressionIdCounter}`,timestamp:Date.now(),warning:this.detectExpressionWarning(e)};this.expressionHistory.push(n),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(n)}detectExpressionWarning(e){const{expression:n,result:r,resultType:i,method:l,duration:c}=e;if(i==="undefined"&&!n.includes("??")&&!n.includes("||")&&/^[a-zA-Z_$][a-zA-Z0-9_$.]*$/.test(n.replace(/{{|}}/g,"").trim()))return{type:"undefined-result",message:"표현식 결과가 undefined입니다",suggestion:`데이터가 로드되었는지 확인하거나 fallback 값을 추가하세요: ${n} ?? ''`};if(i==="null")return{type:"null-result",message:"표현식 결과가 null입니다",suggestion:`nullish coalescing 연산자를 사용하세요: ${n} ?? ''`};if(l==="resolveBindings"&&i==="string"){const d=String(r);if(d.includes("[object Object]")||/^\[.*\]$/.test(d))return{type:"array-to-string",message:"배열/객체가 문자열로 변환되었습니다",suggestion:"evaluateExpression()을 사용하여 원본 타입을 유지하세요"}}if(l==="resolveBindings"&&i==="string"&&String(r).includes("[object Object]"))return{type:"object-to-string",message:"객체가 [object Object]로 변환되었습니다",suggestion:"evaluateExpression()을 사용하거나 특정 속성에 접근하세요"};if(i==="undefined"&&n.includes(".")&&!n.includes("?.")){const d=n.replace(/{{|}}/g,"").trim().split(".");if(d.length>=2)return{type:"missing-optional-chain",message:"Optional chaining(?.) 누락 가능성",suggestion:`안전한 접근을 위해 ?. 사용을 고려하세요: ${d.join("?.")}`}}if((n.includes("{{item.")||n.includes("{{index}}"))&&Array.from(this.iterations.values()).some(p=>p.itemVar!=="item"))return{type:"wrong-iteration-var",message:"'item'/'index' 대신 iteration에서 정의한 변수명을 사용해야 합니다",suggestion:"iteration의 item_var/index_var에 정의된 변수명을 확인하세요"};if(c&&c>10)return{type:"slow-evaluation",message:`표현식 평가에 ${c.toFixed(2)}ms 소요됨`,suggestion:"복잡한 표현식을 단순화하거나 computed 값으로 분리하세요"}}getExpressions(){return[...this.expressionHistory]}getExpressionWarnings(){return this.expressionHistory.filter(e=>e.warning!=null)}searchExpressions(e){const n=e.toLowerCase();return this.expressionHistory.filter(r=>r.expression.toLowerCase().includes(n)||r.componentName?.toLowerCase().includes(n)||r.propName?.toLowerCase().includes(n))}getExpressionStats(){const e=this.expressionHistory,n=new Set(e.map(f=>f.expression)),r=e.filter(f=>f.warning!=null),i=e.filter(f=>f.fromCache),l=e.filter(f=>f.duration!=null).map(f=>f.duration),c={};for(const f of e)c[f.resultType]=(c[f.resultType]||0)+1;const d={};for(const f of r)f.warning&&(d[f.warning.type]=(d[f.warning.type]||0)+1);return{totalEvaluations:e.length,uniqueExpressions:n.size,warningCount:r.length,cacheHitRate:e.length>0?i.length/e.length:0,averageDuration:l.length>0?l.reduce((f,p)=>f+p,0)/l.length:0,byType:c,byWarning:d}}clearExpressions(){this.expressionHistory=[],this.expressionIdCounter=0}watchExpressions(e){return this.expressionWatchers.add(e),()=>{this.expressionWatchers.delete(e)}}notifyExpressionWatchers(e){this.expressionWatchers.forEach(n=>{try{n(e)}catch(r){console.error("[G7DevTools] Expression watcher error:",r)}})}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,n=new WeakSet){if(e===null||typeof e!="object")return e;if(n.has(e))return"[Circular]";if(n.add(e),Array.isArray(e))return e.map(i=>this.sanitizeObject(i,n));const r={};for(const i of Object.keys(e))try{r[i]=this.sanitizeObject(e[i],n)}catch{r[i]="[Unable to serialize]"}return r}getNestedValue(e,n){if(!n)return e;const r=n.split(".");let i=e;for(const l of r){if(i==null)return;i=i[l]}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 n=[...this.stateHistory].reverse().find(r=>r.timestamp<=e);if(n)return{_global:n.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,n,r){if(!this.config.enabled)return;const i=r.map(c=>{if(typeof c=="string")return c;try{return JSON.stringify(c)}catch{return String(c)}}).join(" "),l={id:`log-${++this.logIdCounter}`,level:e,prefix:n,message:i,args:this.sanitizeObject(r),timestamp:Date.now(),stack:e==="error"?new Error().stack:void 0};this.logHistory.push(l),this.logHistory.length>this.maxLogHistory&&this.logHistory.shift()}trackAction(e){if(!this.config.enabled)return;const n={id:`debounce-action-${++this.debounceActionIdCounter}`,...e,timestamp:Date.now()};this.debounceActionHistory.push(n),this.debounceActionHistory.length>100&&this.debounceActionHistory.shift()}trackDataSourceUpdate(e){if(!this.config.enabled)return;const n={id:`ds-update-${++this.dataSourceUpdateIdCounter}`,...e};this.dataSourceUpdateHistory.push(n),this.dataSourceUpdateHistory.length>100&&this.dataSourceUpdateHistory.shift()}getDebounceActionHistory(e){let n=[...this.debounceActionHistory];return e?.handler&&(n=n.filter(r=>r.handler.includes(e.handler))),e?.status&&(n=n.filter(r=>r.status===e.status)),e?.limit&&(n=n.slice(-e.limit)),n}getDataSourceUpdateHistory(e){let n=[...this.dataSourceUpdateHistory];return e?.dataSourceId&&(n=n.filter(r=>r.dataSourceId===e.dataSourceId)),e?.updateType&&(n=n.filter(r=>r.updateType===e.updateType)),e?.limit&&(n=n.slice(-e.limit)),n}getLogs(e){let n=[...this.logHistory];if(e?.level){const r=Array.isArray(e.level)?e.level:[e.level];n=n.filter(i=>r.includes(i.level))}if(e?.prefix){const r=e.prefix.toLowerCase();n=n.filter(i=>i.prefix.toLowerCase().includes(r))}if(e?.search){const r=e.search.toLowerCase();n=n.filter(i=>i.message.toLowerCase().includes(r))}return e?.since&&(n=n.filter(r=>r.timestamp>=e.since)),e?.limit&&(n=n.slice(-e.limit)),n}getLogStats(){const n=Date.now()-6e4,r={log:0,warn:0,error:0,debug:0,info:0},i={};let l=0,c=0;for(const d of this.logHistory)r[d.level]++,i[d.prefix]=(i[d.prefix]||0)+1,d.timestamp>=n&&(d.level==="error"&&l++,d.level==="warn"&&c++);return{totalLogs:this.logHistory.length,byLevel:r,byPrefix:i,recentErrors:l,recentWarnings:c}}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 n=this.dataSources.get(e);n&&this.dataSources.set(e,{...n,status:"loading"})}trackDataSourceLoaded(e,n,r){if(!this.config.enabled)return;const i=this.dataSources.get(e);if(!i)return;let l,c,d=r;n&&(Array.isArray(n)?(l=n.length,c=n.length>0&&typeof n[0]=="object"?Object.keys(n[0]):void 0):typeof n=="object"&&(Array.isArray(n.data)?(d=d||"data",l=n.data.length,c=n.data.length>0&&typeof n.data[0]=="object"?Object.keys(n.data[0]):void 0):Array.isArray(n.items)?(d=d||"items",l=n.items.length,c=n.items.length>0&&typeof n.items[0]=="object"?Object.keys(n.items[0]):void 0):c=Object.keys(n))),this.dataSources.set(e,{...i,status:"loaded",dataPath:d,itemCount:l,keys:c,lastLoadedAt:Date.now(),error:void 0})}trackDataSourceError(e,n){if(!this.config.enabled)return;const r=this.dataSources.get(e);r&&this.dataSources.set(e,{...r,status:"error",error:n,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 n=this.dataPathTransforms.find(r=>r.dataSourceId===e.dataSourceId);n||(n={dataSourceId:e.dataSourceId,timestamp:Date.now(),transformSteps:[],warnings:[]},this.dataPathTransforms.push(n),this.dataPathTransforms.length>this.maxDataPathTransforms&&this.dataPathTransforms.shift()),n.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&&n.warnings.push(e.warning)}setDataPathFinalBinding(e,n){if(!this.config.enabled)return;const r=this.dataPathTransforms.find(i=>i.dataSourceId===e);r&&(r.finalBinding={expression:n.expression,resolvedPath:n.resolvedPath,value:this.safeClone(n.value)})}getDataPathTransformTrackingInfo(){const e=this.getDataPathTransformStats();return{transforms:[...this.dataPathTransforms],stats:e,timestamp:Date.now()}}getDataPathTransformStats(){const e=this.dataPathTransforms,n={};let r=0;const i={};for(const c of e){n[c.dataSourceId]=(n[c.dataSourceId]||0)+1,r+=c.warnings.length;for(const d of c.warnings)i[d]=(i[d]||0)+1}const l=Object.entries(i).map(([c,d])=>({warning:c,count:d})).sort((c,d)=>d.count-c.count).slice(0,10);return{totalTransforms:e.length,byDataSource:n,warningsCount:r,commonWarnings:l}}getDataPathTransformForDataSource(e){return this.dataPathTransforms.find(n=>n.dataSourceId===e)}clearDataPathTransforms(){this.dataPathTransforms=[]}trackNestedContext(e){if(!this.config.enabled)return"";const n=`nested-${++this.nestedContextIdCounter}`,r=[...new Set([...e.parentContext.available,...e.ownContext.added])],i={...e.parentContext.values,...e.ownContext.values},l={id:n,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:r,values:this.safeClone(i)},accessAttempts:[],depth:e.depth,parentId:e.parentId};return this.nestedContexts.push(l),this.nestedContexts.length>this.maxNestedContexts&&this.nestedContexts.shift(),n}trackNestedContextAccess(e,n){if(!this.config.enabled)return;const r=this.nestedContexts.find(i=>i.id===e);r&&r.accessAttempts.push({path:n.path,found:n.found,value:n.found?this.safeClone(n.value):void 0,error:n.error})}getNestedContextTrackingInfo(){const e=this.getNestedContextStats();return{contexts:[...this.nestedContexts],stats:e,timestamp:Date.now()}}getNestedContextStats(){const e=this.nestedContexts,n={expandChildren:0,cellChildren:0,iteration:0,modal:0,slot:0};let r=0,i=0;const l={};for(const d of e){n[d.componentType]++,d.depth>r&&(r=d.depth);for(const f of d.accessAttempts)f.found||(i++,l[f.path]=(l[f.path]||0)+1)}const c=Object.entries(l).map(([d,f])=>({path:d,count:f})).sort((d,f)=>f.count-d.count).slice(0,10);return{totalContexts:e.length,byType:n,maxDepth:r,failedAccessCount:i,commonFailedPaths:c}}getNestedContextForComponent(e){return this.nestedContexts.find(n=>n.componentId===e)}clearNestedContexts(){this.nestedContexts=[],this.nestedContextIdCounter=0}trackHandlerRegistration(e,n="custom",r,i){this.isEnabled&&this.handlers.set(e,{name:e,category:n,description:r,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(n=>n.category===e)}clearHandlers(){this.handlers.clear()}trackEventSubscribe(e){if(!this.isEnabled)return;const n=this.componentEventSubscriptions.get(e),r=Date.now();n?(n.subscriberCount++,n.lastSubscribedAt=r):this.componentEventSubscriptions.set(e,{eventName:e,subscriberCount:1,firstSubscribedAt:r,lastSubscribedAt:r})}trackEventUnsubscribe(e){if(!this.isEnabled)return;const n=this.componentEventSubscriptions.get(e);n&&(n.subscriberCount--,n.subscriberCount<=0&&this.componentEventSubscriptions.delete(e))}trackEventEmit(e,n,r,i,l){if(!this.isEnabled)return;const c={id:`evt_${++this.componentEventIdCounter}`,eventName:e,data:this.sanitizeForLogging(n),timestamp:Date.now(),listenerCount:r,results:i?this.sanitizeForLogging(i):void 0,hasError:!!l,errorMessage:l?.message};this.componentEventEmitHistory.push(c),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((n,r)=>n+r.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,n,r,i){if(!this.config.enabled)return"";const l=`setState_${++this.stateRenderingIdCounter}`;this.currentStateChangeContext={setStateId:l,startTime:performance.now(),changedPath:e,trigger:i||{},renderedComponents:[]};const c={id:`sr_${this.stateRenderingIdCounter}`,setStateId:l,statePath:e,oldValue:this.sanitizeForLogging(n),newValue:this.sanitizeForLogging(r),timestamp:Date.now(),triggeredBy:i||{},renderedComponents:[],totalRenderDuration:0,affectedBindingsCount:0};return this.stateRenderingLogs.push(c),this.stateRenderingLogs.length>this.maxStateRenderingLogs&&this.stateRenderingLogs.shift(),l}trackComponentRender(e,n,r,i=[],l=[],c){if(!this.config.enabled)return;const d=this.componentRenderCounts.get(n)||0;this.componentRenderCounts.set(n,d+1);for(const f of i)this.stateToComponentMap.has(f)||this.stateToComponentMap.set(f,new Set),this.stateToComponentMap.get(f).add(n);if(this.currentStateChangeContext){const f={componentId:e,componentName:n,renderDuration:r,accessedStatePaths:i,evaluatedBindings:l,renderOrder:this.currentStateChangeContext.renderedComponents.length,parentId:c};this.currentStateChangeContext.renderedComponents.push(f)}this.trackRender(n)}completeStateChange(e){if(!this.config.enabled||!this.currentStateChangeContext||this.currentStateChangeContext.setStateId!==e)return;const n=this.currentStateChangeContext,i=performance.now()-n.startTime,l=this.stateRenderingLogs.findIndex(c=>c.setStateId===e);if(l>=0){const c=this.stateRenderingLogs[l];c.renderedComponents=n.renderedComponents,c.totalRenderDuration=i,c.affectedBindingsCount=n.renderedComponents.reduce((d,f)=>d+f.evaluatedBindings.length,0)}this.currentStateChangeContext=null}getCurrentStateChangeContext(){return this.currentStateChangeContext}getStateRenderingLogs(){return[...this.stateRenderingLogs]}getStateRenderingInfo(){const e=this.stateRenderingLogs,n=Object.fromEntries(this.componentRenderCounts),r={};for(const[i,l]of this.stateToComponentMap)r[i]=Array.from(l);return{logs:e,componentRenderCounts:n,stateToComponentMap:r,stats:this.calculateStateRenderingStats()}}calculateStateRenderingStats(){const e=this.stateRenderingLogs;if(e.length===0)return{totalStateChanges:0,totalRenders:0,avgRenderDuration:0,avgComponentsPerChange:0,topRenderedComponents:[],topInfluentialPaths:[]};const n=e.reduce((d,f)=>d+f.renderedComponents.length,0),r=e.reduce((d,f)=>d+f.totalRenderDuration,0)/e.length,i=n/e.length,l=Array.from(this.componentRenderCounts.entries()).sort((d,f)=>f[1]-d[1]).slice(0,5).map(([d,f])=>({name:d,count:f})),c=Array.from(this.stateToComponentMap.entries()).sort((d,f)=>f[1].size-d[1].size).slice(0,5).map(([d,f])=>({path:d,affectedComponents:f.size}));return{totalStateChanges:e.length,totalRenders:n,avgRenderDuration:r,avgComponentsPerChange:i,topRenderedComponents:l,topInfluentialPaths:c}}getComponentsAffectedByState(e){const n=this.stateToComponentMap.get(e);return n?Array.from(n):[]}getComponentRenderHistory(e){return this.stateRenderingLogs.filter(n=>n.renderedComponents.some(r=>r.componentName===e))}clearStateRenderingLogs(){this.stateRenderingLogs=[],this.componentRenderCounts.clear(),this.stateToComponentMap.clear(),this.currentStateChangeContext=null,this.stateRenderingIdCounter=0}trackComponentStateSource(e,n,r,i){this.config.enabled&&this.componentStateSources.set(e,{componentId:e,componentName:n,stateSource:r,stateProvider:i})}trackDynamicState(e,n){this.config.enabled&&this.dynamicStates.set(e,n)}trackContextFlow(e,n,r,i,l,c){if(!this.config.enabled)return;const d={component:n,componentId:e,contextReceived:r,passedToChildren:i,usedInRender:l};if(this.contextFlowNodes.set(e,d),c){const f=this.contextFlowNodes.get(c);f&&(f.children||(f.children=[]),f.children.push(d))}}getStateHierarchyInfo(e=!0){const n=this.buildStateHierarchyLayers(),r=this.detectStateConflicts(n),i=Array.from(this.componentStateSources.values());return{layers:e?n.map(c=>({...c,values:this.summarizeValues(c.values,2)})):n,conflicts:r,componentStateSources:i,timestamp:Date.now()}}summarizeValues(e,n,r=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(r>=n){if(Array.isArray(e))return`[Array(${e.length})]`;const c=Object.keys(e);return`{${c.slice(0,5).join(", ")}${c.length>5?`, ... +${c.length-5}`:""}}`}if(Array.isArray(e))return e.length<=3?e.map(c=>this.summarizeValues(c,n,r+1)):{__type:"array",__length:e.length,__preview:e.slice(0,3).map(c=>this.summarizeValues(c,n,r+1))};const i={},l=Object.keys(e);for(const c of l)i[c]=this.summarizeValues(e[c],n,r+1);return i}buildStateHierarchyLayers(){const e=[];try{const r=window.G7Core?.state?.get?.();if(!r)return e;r._local&&e.push({name:"Global _local",type:"global",path:"_local",values:r._local,priority:1}),r._global&&e.push({name:"Global _global",type:"global",path:"_global",values:r._global,priority:1});for(const[l,c]of this.dynamicStates)c&&Object.keys(c).length>0&&e.push({name:`DynamicState (${l})`,type:"dynamicState",componentId:l,values:c,priority:2});const i=this.computeEffectiveState(r._local||{});e.push({name:"Effective _local (merged)",type:"effective",values:i,priority:3})}catch(n){console.warn("[G7DevTools] 상태 계층 빌드 실패:",n)}return e}computeEffectiveState(e){const n={...e};for(const[,r]of this.dynamicStates)r._local&&Object.assign(n,r._local);return n}detectStateConflicts(e){const n=[],r=e.find(l=>l.type==="global"&&l.path==="_local");if(!r)return n;const i=e.filter(l=>l.type==="dynamicState");for(const l of i){const c=l.values._local||l.values;for(const[d,f]of Object.entries(c)){const p=r.values[d];if(JSON.stringify(p)!==JSON.stringify(f)){const m=[],y=[];for(const C of this.componentStateSources.values())C.stateSource.local.some(v=>v===`_local.${d}`||v===d)&&(C.stateProvider.type==="dynamicState"?m.push(C.componentName):C.stateProvider.type==="globalState"&&y.push(C.componentName));n.push({path:`_local.${d}`,globalValue:p,dynamicStateValue:f,effectiveValue:f,usedBy:m,notUsedBy:y,severity:y.length>0?"warning":"info",description:y.length>0?`${y.join(", ")}은(는) globalState._local을 읽어 dynamicState 값을 사용하지 못함`:"dynamicState 값이 globalState와 다르지만 모든 컴포넌트가 dynamicState를 사용"})}}}return n}getContextFlowInfo(){const e=[],n=new Set(this.contextFlowNodes.keys());for(const r of this.contextFlowNodes.values())if(r.children)for(const i of r.children)n.delete(i.componentId);for(const r of n){const i=this.contextFlowNodes.get(r);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,n,r,i){if(!this.config.enabled)return;const l=this.analyzeTailwindClasses(r),c={componentId:e,componentName:n,classes:r,computedStyles:i,tailwindAnalysis:l};this.componentStyles.set(e,c),this.detectStyleIssues(c)}analyzeTailwindClasses(e){const n=[],r=[],i=[],l=[],c=["sm:","md:","lg:","xl:","2xl:"],d=[/bg-\w+-\d+/,/text-\w+-\d+/,/border-\w+-\d+/];for(const f of e){l.push(f),f.startsWith("dark:")&&n.push(f);for(const p of c)if(f.startsWith(p)){r.push(f);break}for(const p of d)if(p.test(f)){i.push(f);break}}return{usedClasses:l,darkClasses:n,responsiveClasses:r,dynamicClasses:i}}detectStyleIssues(e){const{componentId:n,componentName:r,computedStyles:i,tailwindAnalysis:l}=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:n,componentName:r,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 c=l.usedClasses.filter(f=>f.startsWith("bg-")&&!f.startsWith("dark:")),d=l.darkClasses.filter(f=>f.includes("bg-"));c.length>0&&d.length===0&&this.addStyleIssue({id:this.generateId(),type:"dark-mode-missing",componentId:n,componentName:r,property:"background-color",currentValue:c.join(", "),expectedValue:"dark:bg-* 클래스 필요",severity:"info",description:"다크 모드 배경색 클래스가 누락되었습니다.",suggestion:`${c[0]}에 대응하는 dark: 클래스를 추가하세요.`}),l.dynamicClasses.length>0&&this.addStyleIssue({id:this.generateId(),type:"tailwind-purging",componentId:n,componentName:r,property:"class",currentValue:l.dynamicClasses.join(", "),severity:"info",description:"동적으로 생성된 Tailwind 클래스가 있습니다.",suggestion:"tailwind.config.js의 safelist에 추가하거나 전체 클래스명을 상수로 정의하세요."})}addStyleIssue(e){this.styleIssues.some(r=>r.componentId===e.componentId&&r.type===e.type&&r.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(n=>n.type==="invisible-element").length,tailwindIssueCount:this.styleIssues.filter(n=>n.type==="tailwind-purging").length,darkModeIssueCount:this.styleIssues.filter(n=>n.type==="dark-mode-missing").length},timestamp:Date.now()}}clearStyleValidationData(){this.styleIssues=[],this.componentStyles.clear()}trackAuthEvent(e,n,r,i){if(!this.config.enabled)return;const l={id:`auth_${++this.authEventIdCounter}`,type:e,timestamp:Date.now(),success:n,error:r,details:i};this.authEvents.push(l),this.authEvents.length>this.maxAuthEventHistory&&(this.authEvents=this.authEvents.slice(-this.maxAuthEventHistory))}trackAuthHeader(e,n,r,i,l){if(!this.config.enabled)return;const c={url:e,hasAuthHeader:n,headerType:r,tokenValid:i??!1,responseStatus:l,timestamp:Date.now()};this.authHeaderHistory.push(c),this.authHeaderHistory.length>this.maxAuthEventHistory&&(this.authHeaderHistory=this.authHeaderHistory.slice(-this.maxAuthEventHistory)),l===401&&this.trackAuthEvent("api-unauthorized",!1,`401 Unauthorized: ${e}`,{url:e})}getAuthState(){try{const e=window.G7Core,n=e?.api;let r=e?.auth;!r&&e?.AuthManager?.getInstance&&(r=e.AuthManager.getInstance());const i=n?.getToken?.()||r?.getAccessToken?.()||localStorage.getItem("auth_token")||localStorage.getItem("access_token"),l=r?.getRefreshToken?.()||localStorage.getItem("refresh_token");let c="unknown",d=r?.getUser?.();if(d&&(c="AuthManager"),!d){const S=e?.state?.get?.();d=S?._global?.user||S?._global?.currentUser||S?.user||S?.currentUser,d&&(c="G7Core.state")}const f=r?.isAuthenticated?.()??!1;let p="memory";localStorage.getItem("auth_token")||localStorage.getItem("access_token")?p="localStorage":(sessionStorage.getItem("auth_token")||sessionStorage.getItem("access_token"))&&(p="sessionStorage");const m=!!i&&(!!d||f);let y;i&&typeof i=="string"&&i.length>20?y=`${i.substring(0,10)}...${i.substring(i.length-6)}`:i&&(y="***");const C=d?{id:d.id,email:d.email,name:d.name,roles:d.roles?.map(S=>typeof S=="string"?{name:S}:{id:S.id,name:S.name,guard_name:S.guard_name}),permissions:d.permissions?.map(S=>typeof S=="string"?{name:S}:{id:S.id,name:S.name,guard_name:S.guard_name}),avatar:d.avatar||d.profile_photo_url||d.profile_image,created_at:d.created_at,updated_at:d.updated_at,last_login_at:d.last_login_at,email_verified_at:d.email_verified_at,...d.phone&&{phone:d.phone},...d.nickname&&{nickname:d.nickname},...d.status&&{status:d.status},...d.locale&&{locale:d.locale}}:void 0;return{isAuthenticated:m,user:C,tokens:{hasAccessToken:!!i,hasRefreshToken:!!l,storage:p,accessTokenPreview:y},lastActivity:Date.now(),source:c}}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(n=>n.type==="login").length,successfulLogins:e.filter(n=>n.type==="login"&&n.success).length,failedLogins:e.filter(n=>n.type==="login"&&!n.success).length,tokenRefreshes:e.filter(n=>n.type==="token-refresh").length,unauthorizedResponses:e.filter(n=>n.type==="api-unauthorized").length},timestamp:Date.now()}}clearAuthData(){this.authEvents=[],this.authHeaderHistory=[],this.authEventIdCounter=0}trackLayoutLoad(e,n,r,i="api"){if(!this.config.enabled)return;const l=Date.now();this.currentLayout={layoutPath:e,templateId:n,layoutJson:this.sanitizeObject(r),loadedAt:l,version:r.version,layoutName:r.layout_name,source:i};const c={id:`layout-${++this.layoutIdCounter}`,layoutPath:e,templateId:n,loadedAt:l,source:i,version:r.version};this.layoutHistory.push(c),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 n=`exec_${++this.executionIdCounter}_${Date.now()}`,r={handlerName:e,executionId:n,startTime:Date.now(),stateChanges:[],dataSourceChanges:[],alerts:[]};if(this.executionDetails.set(n,r),this.executionDetails.size>this.maxExecutionDetails){const i=Array.from(this.executionDetails.keys());i.slice(0,i.length-this.maxExecutionDetails).forEach(c=>this.executionDetails.delete(c))}return n}endHandlerExecution(e,n,r,i){if(!this.config.enabled||!e)return;const l=this.executionDetails.get(e);if(!l)return;l.endTime=Date.now(),l.duration=l.endTime-l.startTime,l.exitReason=n,l.exitLocation=r,l.exitDescription=i;const c=this.changeExpectations.get(e);c&&(l.expectedChanges=c,this.checkExpectations(e,l,c),this.changeExpectations.delete(e)),n==="normal"&&l.stateChanges.length===0&&l.dataSourceChanges.length===0&&this.addChangeAlert(e,{type:"no-state-change",severity:"warning",message:`핸들러 "${l.handlerName}"이(가) 상태 변경 없이 완료됨`,description:"핸들러가 성공적으로 완료되었지만 상태나 데이터소스 변경이 없습니다. 의도한 동작인지 확인하세요.",handlerName:l.handlerName,suggestion:'핸들러 내부 조건문을 확인하거나 DevTools의 "변경감지" 탭에서 exitLocation을 확인하세요.',docLink:"troubleshooting-state.md"}),(n==="early-return-condition"||n==="early-return-validation")&&this.addChangeAlert(e,{type:"early-return-detected",severity:"info",message:`핸들러 "${l.handlerName}"이(가) early return으로 종료됨`,description:i||`종료 위치: ${r||"알 수 없음"}`,handlerName:l.handlerName,suggestion:n==="early-return-validation"?"검증 실패로 인한 early return입니다. 입력 데이터를 확인하세요.":"조건부 early return입니다. 조건문의 평가 결과를 확인하세요."})}recordExitReason(e,n,r,i){if(!this.config.enabled||!e)return;const l=this.executionDetails.get(e);l&&(l.exitReason=n,l.exitLocation=r,l.exitDescription=i)}recordStateChange(e,n,r,i,l){if(!this.config.enabled)return;const c={id:`sc_${++this.stateChangeIdCounter}`,path:n,changeType:r,oldValue:this.safeClone(i),newValue:this.safeClone(l),timestamp:Date.now(),comparison:this.compareValues(i,l),executionId:e};if(this.stateChangeHistory.push(c),e){const d=this.executionDetails.get(e);d&&d.stateChanges.push(c)}this.stateChangeHistory.length>this.maxStateChangeHistory&&this.stateChangeHistory.splice(0,this.stateChangeHistory.length-this.maxStateChangeHistory),c.comparison.isDeepEqual&&typeof i=="object"&&i!==null&&this.addChangeAlert(e||"",{type:"object-reference-same",severity:"warning",message:`상태 "${n}"가 변경되었으나 값이 동일함`,description:"객체 참조가 동일하거나 깊은 비교 결과 변경이 없습니다. 변경 감지가 실패할 수 있습니다.",handlerName:e&&this.executionDetails.get(e)?.handlerName||"unknown",statePath:n,suggestion:"불변성을 유지하여 새 객체를 생성하세요. 예: { ...oldObject, newField: value }",docLink:"troubleshooting-state.md#object-mutation"})}recordDataSourceChange(e,n,r,i,l){if(!this.config.enabled)return;const c={dataSourceId:n,changeType:r,timestamp:Date.now(),previousStatus:i,newStatus:l,executionId:e};if(this.dataSourceChangeHistory.push(c),e){const d=this.executionDetails.get(e);d&&d.dataSourceChanges.push(c)}this.dataSourceChangeHistory.length>this.maxStateChangeHistory&&this.dataSourceChangeHistory.splice(0,this.dataSourceChangeHistory.length-this.maxStateChangeHistory)}expectChange(e,n,r){if(!this.config.enabled||!e)return;const i=this.executionDetails.get(e);if(!i)return;const l={expectedStatePaths:n,expectedDataSources:r,setAt:Date.now(),source:i.handlerName};this.changeExpectations.set(e,l)}checkExpectations(e,n,r){const i=new Set(n.stateChanges.map(c=>c.path)),l=new Set(n.dataSourceChanges.map(c=>c.dataSourceId));for(const c of r.expectedStatePaths)i.has(c)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 상태 변경 "${c}"가 발생하지 않음`,description:`핸들러 "${n.handlerName}"이(가) "${c}" 변경을 예고했지만 실제로 변경되지 않았습니다.`,handlerName:n.handlerName,statePath:c,suggestion:"핸들러 내부 로직을 확인하세요. early return이나 조건부 분기로 인해 변경이 생략되었을 수 있습니다.",docLink:"troubleshooting-state.md"});for(const c of r.expectedDataSources)l.has(c)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 데이터소스 갱신 "${c}"가 발생하지 않음`,description:`핸들러 "${n.handlerName}"이(가) "${c}" 갱신을 예고했지만 실제로 갱신되지 않았습니다.`,handlerName:n.handlerName,dataSourceId:c,suggestion:"refetchDataSource 호출이 실행되었는지 확인하세요.",docLink:"data-sources.md"})}addChangeAlert(e,n){const r={...n,id:`alert_${++this.alertIdCounter}`,timestamp:Date.now()};if(this.changeAlerts.push(r),e){const i=this.executionDetails.get(e);i&&i.alerts.push(r)}this.changeAlerts.length>this.maxChangeAlerts&&this.changeAlerts.splice(0,this.changeAlerts.length-this.maxChangeAlerts)}compareValues(e,n){const r=this.getValueType(e),i=this.getValueType(n),l=r!==i;let c=!1,d;return!l&&(r==="object"||r==="array")?(c=this.deepEqual(e,n),!c&&r==="object"&&(d=this.getChangedKeys(e,n))):c=e===n,{typeChanged:l,oldType:r,newType:i,isDeepEqual:c,changedKeys:d}}getValueType(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}deepEqual(e,n){if(e===n)return!0;if(typeof e!=typeof n)return!1;if(e===null||n===null||typeof e!="object")return e===n;if(Array.isArray(e)!==Array.isArray(n))return!1;const r=Object.keys(e),i=Object.keys(n);if(r.length!==i.length)return!1;for(const l of r)if(!i.includes(l)||!this.deepEqual(e[l],n[l]))return!1;return!0}getChangedKeys(e,n){const r=[],i=new Set([...Object.keys(e),...Object.keys(n)]);for(const l of i)this.deepEqual(e[l],n[l])||r.push(l);return r}getChangeDetectionInfo(){const e=Array.from(this.executionDetails.values()),n={totalExecutions:e.length,executionsWithStateChange:e.filter(r=>r.stateChanges.length>0).length,executionsWithoutStateChange:e.filter(r=>r.stateChanges.length===0&&r.exitReason==="normal").length,earlyReturnCount:e.filter(r=>r.exitReason==="early-return-condition"||r.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:n,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 n of this.changeAlerts)e[n.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,n){let r=[...this.changeAlerts];return n&&(r=r.filter(i=>i.severity===n)),r.slice(-e)}getHandlerExecutions(e,n=10){return Array.from(this.executionDetails.values()).filter(i=>i.handlerName===e).slice(-n)}findExecutionInStack(e){return this.sequenceExecutionStack.find(n=>n.sequenceId===e)}startSequenceExecution(e){if(!this.config.enabled)return"";const n=`seq_${++this.sequenceIdCounter}_${Date.now()}`,r={sequenceId:n,startTime:Date.now(),totalDuration:0,trigger:e,actions:[],status:"running"};return this.sequenceExecutionStack.push(r),n}captureSequenceActionBefore(e,n,r,i,l){if(!this.config.enabled)return;const c=this.findExecutionInStack(e);if(!c)return;const d={index:n,handler:r,params:this.safeClone(i),stateBeforeAction:{_global:this.safeClone(l._global),_local:this.safeClone(l._local),_isolated:l._isolated?this.safeClone(l._isolated):void 0},stateAfterAction:{_global:{},_local:{}},duration:0,status:"success"};c.actions.push(d)}captureSequenceActionAfter(e,n,r,i,l,c){if(!this.config.enabled)return;const d=this.findExecutionInStack(e);if(!d)return;const f=d.actions.find(m=>m.index===n);if(!f)return;f.stateAfterAction={_global:this.safeClone(r._global),_local:this.safeClone(r._local),_isolated:r._isolated?this.safeClone(r._isolated):void 0},f.duration=i,f.result=this.safeClone(l),f.stateDiff={global:this.computeStateDiff(f.stateBeforeAction._global,f.stateAfterAction._global),local:this.computeStateDiff(f.stateBeforeAction._local,f.stateAfterAction._local)},f.stateBeforeAction._isolated&&f.stateAfterAction._isolated&&(f.stateDiff.isolated=this.computeStateDiff(f.stateBeforeAction._isolated,f.stateAfterAction._isolated));const p=window.__g7PendingLocalState;p&&(f.pendingState=this.safeClone(p)),c&&(f.status="error",f.error={name:c.name,message:c.message,stack:c.stack})}endSequenceExecution(e,n){if(!this.config.enabled)return;const r=this.sequenceExecutionStack.findIndex(l=>l.sequenceId===e);if(r===-1)return;const i=this.sequenceExecutionStack[r];if(i.endTime=Date.now(),i.totalDuration=i.endTime-i.startTime,n){i.status="error",i.error={name:n.name,message:n.message,stack:n.stack};const l=i.actions.find(c=>c.status==="error");l&&(i.failedAtIndex=l.index)}else i.status="success";this.sequenceExecutions.push(i),this.sequenceExecutions.length>this.maxSequenceExecutions&&this.sequenceExecutions.shift(),this.sequenceExecutionStack.splice(r,1)}computeStateDiff(e,n){const r=[],i=[],l=[],c=new Set(Object.keys(e)),d=new Set(Object.keys(n));for(const f of d)c.has(f)||r.push(f);for(const f of c)d.has(f)||i.push(f);for(const f of c)if(d.has(f)){const p=e[f],m=n[f];JSON.stringify(p)!==JSON.stringify(m)&&l.push({path:f,oldValue:p,newValue:m})}return{added:r,removed:i,changed:l}}getSequenceTrackingInfo(){const e=this.getSequenceStats(),n=this.sequenceExecutionStack.length>0?this.sequenceExecutionStack[this.sequenceExecutionStack.length-1]:void 0;return{executions:[...this.sequenceExecutions],currentExecution:n,stats:e}}getSequenceStats(){const e=this.sequenceExecutions,n=e.length,r=e.filter(p=>p.status==="success").length,i=e.filter(p=>p.status==="error").length,l=e.reduce((p,m)=>p+m.actions.length,0),c=n>0?e.reduce((p,m)=>p+m.totalDuration,0)/n:0,d={};for(const p of e)for(const m of p.actions)d[m.handler]=(d[m.handler]||0)+1;const f=Object.entries(d).sort(([,p],[,m])=>m-p).slice(0,5).map(([p,m])=>({handler:p,count:m}));return{totalExecutions:n,successCount:r,errorCount:i,totalActions:l,avgDuration:c,topHandlers:f}}clearSequenceData(){this.sequenceExecutions=[],this.sequenceExecutionStack=[],this.sequenceIdCounter=0}getSequenceExecution(e){const n=this.findExecutionInStack(e);return n||this.sequenceExecutions.find(r=>r.sequenceId===e)}getRecentSequences(e=10){return this.sequenceExecutions.slice(-e)}registerStateCaptureForHandler(e,n,r){if(!this.config.enabled)return;const i=new Map,l=Date.now();for(const c of n)i.set(c,{value:this.safeClone(r[c]),capturedAt:l});this.stateCaptureRegistry.set(e,i)}detectStaleClosure(e,n,r,i,l){if(!this.config.enabled)return[];const c=this.stateCaptureRegistry.get(e);if(!c)return[];const d=Date.now(),f=[];for(const[p,m]of c){const y=this.getValueByPath(r,p),C=d-m.capturedAt;if(!this.isDeepEqual(m.value,y)&&C>0){const S=this.createStaleClosureWarning(i,n,p,m.value,m.capturedAt,y,d,C,l);f.push(S),this.addStaleClosureWarning(S)}}return this.stateCaptureRegistry.delete(e),f}trackStaleClosureWarning(e){if(!this.config.enabled)return;const n=Date.now(),r=this.createStaleClosureWarning(e.type,e.location,e.capturedPath,e.capturedValue,e.capturedAt,e.currentValue,n,n-e.capturedAt,e.actionId,e.stackTrace);this.addStaleClosureWarning(r)}createStaleClosureWarning(e,n,r,i,l,c,d,f,p,m){const y=this.getStaleClosureSeverity(e,f),{description:C,suggestion:S,docLink:v}=this.getStaleClosureMessages(e,r,f);return{id:`stale_${++this.staleClosureIdCounter}_${Date.now()}`,timestamp:Date.now(),type:e,location:n,capturedState:{path:r,capturedValue:this.safeClone(i),capturedAt:l},currentState:{path:r,currentValue:this.safeClone(c),retrievedAt:d},timeDiff:f,severity:y,description:C,suggestion:S,docLink:v,actionId:p,stackTrace:m}}getStaleClosureSeverity(e,n){if(n>5e3)return"error";if(n>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,n,r){const i=r<1e3?`${r}ms`:`${(r/1e3).toFixed(1)}s`;switch(e){case"async-state-capture":return{description:`await 후 ${i} 경과 시점에 '${n}' 상태가 변경됨. 캡처된 상태 대신 최신 상태를 사용해야 함`,suggestion:"await 이후에는 G7Core.state.get()으로 최신 상태를 다시 조회하거나, useRef + getter 패턴을 사용하세요",docLink:"troubleshooting-state-closure.md"};case"callback-state-capture":return{description:`콜백에서 ${i} 전에 캡처된 '${n}' 상태를 사용 중. 최신 상태와 다름`,suggestion:"콜백에서 상태를 참조할 때는 stateRef.current 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};case"timeout-state-capture":return{description:`setTimeout/setInterval 콜백에서 '${n}' 상태가 ${i} 전 값 사용 중`,suggestion:"타이머 콜백 내에서는 G7Core.state.get()으로 최신 상태를 조회하세요",docLink:"troubleshooting-state-closure.md"};case"sequence-state-mismatch":return{description:`sequence 내 '${n}' 상태가 이전 액션 결과와 불일치. context.state 대신 캡처된 값 사용 의심`,suggestion:"sequence 내에서는 context.state 또는 $prev를 사용하여 최신 상태를 참조하세요",docLink:"troubleshooting-state-setstate.md"};case"event-handler-stale":return{description:`이벤트 핸들러에서 ${i} 전에 바인딩된 '${n}' 상태 사용 중`,suggestion:"이벤트 핸들러에서 상태를 참조할 때는 useRef 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};default:return{description:`'${n}' 상태에서 stale closure 감지됨 (${i} 경과)`,suggestion:"상태 참조 시 최신 값을 사용하는지 확인하세요"}}}addStaleClosureWarning(e){this.staleClosureWarnings.push(e),this.staleClosureWarnings.length>this.maxStaleClosureWarnings&&this.staleClosureWarnings.shift()}getValueByPath(e,n){const r=n.split(".");let i=e;for(const l of r){if(i==null)return;i=i[l]}return i}isDeepEqual(e,n){if(e===n)return!0;if(e===null||n===null)return e===n;if(typeof e!=typeof n)return!1;if(typeof e!="object")return e===n;try{return JSON.stringify(e)===JSON.stringify(n)}catch{return!1}}getStaleClosureTrackingInfo(){const e=this.getStaleClosureStats();return{warnings:[...this.staleClosureWarnings],stats:e,timestamp:Date.now()}}getStaleClosureStats(){const e=this.staleClosureWarnings,n={"async-state-capture":0,"callback-state-capture":0,"timeout-state-capture":0,"sequence-state-mismatch":0,"event-handler-stale":0};for(const f of e)n[f.type]++;const r={info:0,warning:0,error:0};for(const f of e)r[f.severity]++;const i={};for(const f of e)i[f.location]=(i[f.location]||0)+1;const l=Object.entries(i).sort(([,f],[,p])=>p-f).slice(0,5).map(([f,p])=>({location:f,count:p})),c={};for(const f of e)c[f.capturedState.path]=(c[f.capturedState.path]||0)+1;const d=Object.entries(c).sort(([,f],[,p])=>p-f).slice(0,5).map(([f,p])=>({path:f,count:p}));return{totalWarnings:e.length,warningsByType:n,warningsBySeverity:r,topLocations:l,topAffectedPaths:d}}clearStaleClosureData(){this.staleClosureWarnings=[],this.staleClosureIdCounter=0,this.stateCaptureRegistry.clear()}getRecentStaleClosureWarnings(e=10,n){let r=[...this.staleClosureWarnings];return n&&(r=r.filter(i=>i.severity===n)),r.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(r=>{try{return JSON.parse(JSON.stringify(r))}catch{return"[Unserializable]"}});const n={};for(const r of Object.keys(e))try{n[r]=JSON.parse(JSON.stringify(e[r]))}catch{n[r]="[Unserializable]"}return n}}};$($i,"instance");let Ua=$i;const Jn=dt("LayoutLoader");class Rr extends Error{constructor(e,n,r){super(e),this.code=n,this.details=r,this.name="LayoutLoaderError"}}class Gf{constructor(e){$(this,"componentRegistry");$(this,"currentLayout",null);$(this,"layoutCache",new Map);$(this,"cacheVersion",0);this.componentRegistry=e}setCacheVersion(e){this.cacheVersion!==e&&(Jn.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.layoutCache.clear())}getCacheVersion(){return this.cacheVersion}async loadLayout(e,n){const r=`${e}:${n}`;if(this.layoutCache.has(r)){Jn.log("Loading layout from cache:",n);const l=await this.layoutCache.get(r),c=JSON.parse(JSON.stringify(l));return this.currentLayout=c,Ua.getInstance().trackLayoutLoad(n,e,c,"cache"),c}const i=this.fetchLayout(e,n);return this.layoutCache.set(r,i),i.catch(()=>{this.layoutCache.get(r)===i&&this.layoutCache.delete(r)}),i}async fetchLayout(e,n,r=!1){try{const i=this.cacheVersion>0?this.cacheVersion:null;let l;if(n.startsWith("__preview__/")){const C=n.replace("__preview__/","");l=Pr(`/api/layouts/preview/${C}`,"json",i)}else l=Pr(`/api/layouts/${e}/${n}`,"json",i);Jn.log("Fetching layout from API:",l);const c=Wn(),d=r?null:c.getToken(),f={Accept:"application/json"};d&&(f.Authorization=`Bearer ${d}`);const p=await ac(l,{init:{headers:f},label:`layout: ${n}`});let m;try{m=await p.json()}catch{m=null}if(!p.ok){if(p.status===401&&!r&&d){Jn.log("Token invalid, removing and retrying without token"),c.removeToken();try{return await this.fetchLayout(e,n,!0)}catch(S){throw S instanceof Rr&&S.details?.status===401?new Rr(S.message,S.code,{...S.details,hadToken:!0}):S}}const C=m?.message||m?.error;throw new Rr(`Failed to fetch layout: ${p.status} ${p.statusText}`,"FETCH_FAILED",{status:p.status,statusText:p.statusText,url:l,apiMessage:C})}const y=m.data||m;return this.validateLayoutData(y),this.currentLayout=y,Ua.getInstance().trackLayoutLoad(n,e,y,"api"),Jn.log("Layout fetched and cached successfully:",y.layout_name),y}catch(i){const l=`${e}:${n}`;throw this.layoutCache.delete(l),i instanceof Rr?i:new Rr("Failed to load layout","LOAD_FAILED",{originalError:i})}}prefetchLayout(e,n){return this.loadLayout(e,n)}validateLayoutData(e){if(!e.version)throw new Rr("Layout data missing required field: version","VALIDATION_FAILED",{field:"version"});if(!e.layout_name)throw new Rr("Layout data missing required field: layout_name","VALIDATION_FAILED",{field:"layout_name"});if(!Array.isArray(e.components))throw new Rr('Layout data field "components" must be an array',"VALIDATION_FAILED",{field:"components",value:e.components});Jn.log("Layout data validation passed")}renderLayout(e,n){try{const r=n||this.currentLayout;if(!r)throw new Rr("No layout data to render","NO_LAYOUT_DATA");Jn.log("Rendering layout:",r.layout_name),e.innerHTML="",this.renderComponents(e,r.components),Jn.log("Layout rendered successfully")}catch(r){Jn.error("Render error:",r),this.renderErrorState(e,r)}}renderComponents(e,n){for(const r of n){const i=this.renderComponent(r);i&&e.appendChild(i)}}renderComponent(e){try{if(!this.componentRegistry.getComponent(e.type))return Jn.warn(`Component not found: ${e.type}`),this.createPlaceholderElement(e.type);const r=document.createElement("div");return r.setAttribute("data-component",e.type),e.props&&Object.entries(e.props).forEach(([i,l])=>{r.setAttribute(`data-prop-${i}`,JSON.stringify(l))}),e.children&&e.children.length>0?this.renderComponents(r,e.children):e.text&&(r.textContent=e.text),r}catch(n){return Jn.error(`Error rendering component ${e.type}:`,n),this.createErrorElement(e.type,n)}}createPlaceholderElement(e){const n=document.createElement("div");return n.className="component-placeholder",n.setAttribute("data-component-type",e),n.innerHTML=`

Component not found: ${e}

@@ -105,8 +142,14 @@ Error generating stack: `+u.message+` " >페이지 새로고침 - `,Xn.error("Error state rendered:",i,r)}getCurrentLayout(){return this.currentLayout}clear(){this.currentLayout=null,this.layoutCache.clear(),Xn.log("Layout data and cache cleared")}}const Rx=pt("TranslationContext"),ih=I.createContext(null),Uc=({children:s,translationEngine:e,translationContext:n})=>{const r=I.useMemo(()=>(l,c)=>{if(c){const d="|"+Object.entries(c).map(([f,h])=>`${f}=${h}`).join("|");return e.translate(l,n,d)}return e.translate(l,n)},[e,n]),i=I.useMemo(()=>({translationEngine:e,translationContext:n,t:r}),[e,n,r]);return yt.jsx(ih.Provider,{value:i,children:s})},gb=()=>{const s=I.useContext(ih);return s||(Rx.warn("TranslationProvider 외부에서 호출되었습니다. 키를 그대로 반환합니다."),{t:e=>e,translationEngine:null,translationContext:null})},Pa=pt("SlotContext"),Dx={registerToSlot:()=>{Pa.warn("SlotContext not available: registerToSlot called outside SlotProvider")},unregisterFromSlot:()=>{Pa.warn("SlotContext not available: unregisterFromSlot called outside SlotProvider")},getSlotComponents:()=>[],subscribeToSlot:()=>()=>{},clearAllSlots:()=>{},isEnabled:!1},Ox=I.createContext(Dx),sh=({children:s})=>{const e=I.useRef(new Map),n=I.useRef(new Map),r=I.useCallback(m=>{const y=n.current.get(m);y&&y.forEach(v=>{try{v()}catch(S){Pa.error(`Slot subscriber error (slotId: ${m}):`,S)}})},[]),i=I.useCallback((m,y,v)=>{if(!m||!y){Pa.warn("registerToSlot: slotId and componentId are required");return}e.current.has(m)||e.current.set(m,new Map);const S=e.current.get(m),_=S.get(y);_&&_.registrationKey===v.registrationKey||(S.set(y,v),Pa.log(`Component registered to slot: ${y} -> ${m} (order: ${v.order})`),r(m))},[r]),l=I.useCallback((m,y)=>{const v=e.current.get(m);v&&v.has(y)&&(v.delete(y),Pa.log(`Component unregistered from slot: ${y} <- ${m}`),v.size===0&&e.current.delete(m),r(m))},[r]),c=I.useCallback(m=>{const y=e.current.get(m);return y?Array.from(y.values()).sort((v,S)=>v.order-S.order):[]},[]),d=I.useCallback((m,y)=>{n.current.has(m)||n.current.set(m,new Set);const v=n.current.get(m);return v.add(y),()=>{v.delete(y),v.size===0&&n.current.delete(m)}},[]),f=I.useCallback(()=>{e.current.forEach((m,y)=>{r(y)}),e.current.clear(),n.current.clear(),Pa.log("All slots cleared")},[r]),h=I.useMemo(()=>({registerToSlot:i,unregisterFromSlot:l,getSlotComponents:c,subscribeToSlot:d,clearAllSlots:f,isEnabled:!0}),[i,l,c,d,f]);return I.useLayoutEffect(()=>{typeof window<"u"&&(window.__slotContextValue=h,Pa.log("SlotContext exposed to window.__slotContextValue"))},[h]),yt.jsx(Ox.Provider,{value:h,children:s})};class oh{constructor(){this.notificationCreatedEvent=".Illuminate\\Notifications\\Events\\BroadcastNotificationCreated"}listenForWhisper(e,n){return this.listen(".client-"+e,n)}notification(e){return this.listen(this.notificationCreatedEvent,e)}stopListeningForNotification(e){return this.stopListening(this.notificationCreatedEvent,e)}stopListeningForWhisper(e,n){return this.stopListening(".client-"+e,n)}}class mb{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 Lx(s){try{return Reflect.construct(String,[],s),!0}catch{return!1}}class lh extends oh{constructor(e,n,r){super(),this.name=n,this.pusher=e,this.options=r,this.eventFormatter=new mb(this.options.namespace),this.subscribe()}subscribe(){this.subscription=this.pusher.subscribe(this.name)}unsubscribe(){this.pusher.unsubscribe(this.name)}listen(e,n){return this.on(this.eventFormatter.format(e),n),this}listenToAll(e){return this.subscription.bind_global((n,r)=>{if(n.startsWith("pusher:"))return;let i=String(this.options.namespace??"").replace(/\./g,"\\"),l=n.startsWith(i)?n.substring(i.length+1):"."+n;e(l,r)}),this}stopListening(e,n){return n?this.subscription.unbind(this.eventFormatter.format(e),n):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",n=>{e(n)}),this}on(e,n){return this.subscription.bind(e,n),this}}class yb extends lh{whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}}class $x extends lh{whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}}class Mx extends yb{here(e){return this.on("pusher:subscription_succeeded",n=>{e(Object.keys(n.members).map(r=>n.members[r]))}),this}joining(e){return this.on("pusher:member_added",n=>{e(n.info)}),this}whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}leaving(e){return this.on("pusher:member_removed",n=>{e(n.info)}),this}}class bb extends oh{constructor(e,n,r){super(),this.events={},this.listeners={},this.name=n,this.socket=e,this.options=r,this.eventFormatter=new mb(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,n){return this.on(this.eventFormatter.format(e),n),this}stopListening(e,n){return this.unbindEvent(this.eventFormatter.format(e),n),this}subscribed(e){return this.on("connect",n=>{e(n)}),this}error(e){return this}on(e,n){return this.listeners[e]=this.listeners[e]||[],this.events[e]||(this.events[e]=(r,i)=>{this.name===r&&this.listeners[e]&&this.listeners[e].forEach(l=>l(i))},this.socket.on(e,this.events[e])),this.listeners[e].push(n),this}unbind(){Object.keys(this.events).forEach(e=>{this.unbindEvent(e)})}unbindEvent(e,n){this.listeners[e]=this.listeners[e]||[],n&&(this.listeners[e]=this.listeners[e].filter(r=>r!==n)),(!n||this.listeners[e].length===0)&&(this.events[e]&&(this.socket.removeListener(e,this.events[e]),delete this.events[e]),delete this.listeners[e])}}class vb extends bb{whisper(e,n){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:n}),this}}class Nx extends vb{here(e){return this.on("presence:subscribed",n=>{e(n.map(r=>r.user_info))}),this}joining(e){return this.on("presence:joining",n=>e(n.user_info)),this}whisper(e,n){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:n}),this}leaving(e){return this.on("presence:leaving",n=>e(n.user_info)),this}}class Bc extends oh{subscribe(){}unsubscribe(){}listen(e,n){return this}listenToAll(e){return this}stopListening(e,n){return this}subscribed(e){return this}error(e){return this}on(e,n){return this}}class Sb extends Bc{whisper(e,n){return this}}class Ix extends Bc{whisper(e,n){return this}}class jx extends Sb{here(e){return this}joining(e){return this}whisper(e,n){return this}leaving(e){return this}}const Jc=class Jc{constructor(e){this.setOptions(e),this.connect()}setOptions(e){this.options={...Jc._defaultOptions,...e,broadcaster:e.broadcaster};let n=this.csrfToken();n&&(this.options.auth.headers["X-CSRF-TOKEN"]=n,this.options.userAuthentication.headers["X-CSRF-TOKEN"]=n),n=this.options.bearerToken,n&&(this.options.auth.headers.Authorization="Bearer "+n,this.options.userAuthentication.headers.Authorization="Bearer "+n)}csrfToken(){return typeof window<"u"&&window.Laravel?.csrfToken?window.Laravel.csrfToken:this.options.csrfToken?this.options.csrfToken:typeof document<"u"&&typeof document.querySelector=="function"?document.querySelector('meta[name="csrf-token"]')?.getAttribute("content")??null:null}};Jc._defaultOptions={auth:{headers:{}},authEndpoint:"/broadcasting/auth",userAuthentication:{endpoint:"/broadcasting/user-auth",headers:{}},csrfToken:null,bearerToken:null,host:null,key:null,namespace:"App.Events"};let Wo=Jc;class qc extends Wo{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,n,r){return this.channel(e).listen(n,r)}channel(e){return this.channels[e]||(this.channels[e]=new lh(this.pusher,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new yb(this.pusher,"private-"+e,this.options)),this.channels["private-"+e]}encryptedPrivateChannel(e){return this.channels["private-encrypted-"+e]||(this.channels["private-encrypted-"+e]=new $x(this.pusher,"private-encrypted-"+e,this.options)),this.channels["private-encrypted-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new Mx(this.pusher,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"private-encrypted-"+e,"presence-"+e].forEach(n=>{this.leaveChannel(n)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.pusher.connection.socket_id}connectionStatus(){const e=this.pusher.connection.state;switch(e){case"connected":case"connecting":return e;case"failed":case"unavailable":return"failed";default:return"disconnected"}}onConnectionChange(e){const n=()=>{e(this.connectionStatus())},r=["state_change","connected","disconnected"];return r.forEach(i=>{this.pusher.connection.bind(i,n)}),()=>{r.forEach(i=>{this.pusher.connection.unbind(i,n)})}}disconnect(){this.pusher.disconnect()}}class Hx extends Wo{constructor(){super(...arguments),this.channels={}}connect(){const e=this.getSocketIO();this.socket=e(this.options.host??void 0,this.options),this.socket.io.on("reconnect",()=>{Object.values(this.channels).forEach(n=>{n.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,n,r){return this.channel(e).listen(n,r)}channel(e){return this.channels[e]||(this.channels[e]=new bb(this.socket,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new vb(this.socket,"private-"+e,this.options)),this.channels["private-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new Nx(this.socket,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"presence-"+e].forEach(n=>{this.leaveChannel(n)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.socket.id}connectionStatus(){return this.socket.connected?"connected":this.socket.io._reconnecting?"reconnecting":this.socket.id!==void 0?"disconnected":"connecting"}onConnectionChange(e){const n=()=>{e(this.connectionStatus())},r=["connect","disconnect","connect_error","reconnect_attempt","reconnect","reconnect_error","reconnect_failed"];return r.forEach(i=>{this.socket.on(i,n)}),()=>{r.forEach(i=>{this.socket.off(i,n)})}}disconnect(){this.socket.disconnect()}}class wb extends Wo{constructor(){super(...arguments),this.channels={}}connect(){}listen(e,n,r){return new Bc}channel(e){return new Bc}privateChannel(e){return new Sb}encryptedPrivateChannel(e){return new Ix}presenceChannel(e){return new jx}leave(e){}leaveChannel(e){}socketId(){return"fake-socket-id"}connectionStatus(){return"connected"}onConnectionChange(e){return()=>{}}disconnect(){}}class zx{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 qc({...this.options,cluster:""});else if(this.options.broadcaster==="pusher")this.connector=new qc(this.options);else if(this.options.broadcaster==="ably")this.connector=new qc({...this.options,cluster:"",broadcaster:"pusher"});else if(this.options.broadcaster==="socket.io")this.connector=new Hx(this.options);else if(this.options.broadcaster==="null")this.connector=new wb(this.options);else if(typeof this.options.broadcaster=="function"&&Lx(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,n,r){return this.connector.listen(e,n,r)}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 qc||e instanceof wb}socketId(){return this.connector.socketId()}connectionStatus(){return this.connector.connectionStatus()}registerInterceptors(){typeof Vue<"u"&&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,n)=>{this.socketId()&&e.headers.set("X-Socket-ID",this.socketId()),n()})}registerAxiosRequestInterceptor(){axios.interceptors.request.use(e=>(this.socketId()&&(e.headers["X-Socket-Id"]=this.socketId()),e))}registerjQueryAjaxSetup(){typeof jQuery.ajax<"u"&&jQuery.ajaxPrefilter((e,n,r)=>{this.socketId()&&r.setRequestHeader("X-Socket-Id",this.socketId())})}registerTurboRequestInterceptor(){document.addEventListener("turbo:before-fetch-request",e=>{e.detail.fetchOptions.headers["X-Socket-Id"]=this.socketId()})}}var ch={exports:{}};var Cb;function Px(){return Cb||(Cb=1,(function(s,e){(function(r,i){s.exports=i()})(self,()=>(()=>{var n={594(c,d){var f=this&&this.__extends||(function(){var O=function(k,L){return O=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(B,q){B.__proto__=q}||function(B,q){for(var z in q)q.hasOwnProperty(z)&&(B[z]=q[z])},O(k,L)};return function(k,L){O(k,L);function B(){this.constructor=k}k.prototype=L===null?Object.create(L):(B.prototype=L.prototype,new B)}})();Object.defineProperty(d,"__esModule",{value:!0});var h=256,m=(function(){function O(k){k===void 0&&(k="="),this._paddingCharacter=k}return O.prototype.encodedLength=function(k){return this._paddingCharacter?(k+2)/3*4|0:(k*8+5)/6|0},O.prototype.encode=function(k){for(var L="",B=0;B>>18&63),L+=this._encodeByte(q>>>12&63),L+=this._encodeByte(q>>>6&63),L+=this._encodeByte(q>>>0&63)}var z=k.length-B;if(z>0){var q=k[B]<<16|(z===2?k[B+1]<<8:0);L+=this._encodeByte(q>>>18&63),L+=this._encodeByte(q>>>12&63),z===2?L+=this._encodeByte(q>>>6&63):L+=this._paddingCharacter||"",L+=this._paddingCharacter||""}return L},O.prototype.maxDecodedLength=function(k){return this._paddingCharacter?k/4*3|0:(k*6+7)/8|0},O.prototype.decodedLength=function(k){return this.maxDecodedLength(k.length-this._getPaddingLength(k))},O.prototype.decode=function(k){if(k.length===0)return new Uint8Array(0);for(var L=this._getPaddingLength(k),B=k.length-L,q=new Uint8Array(this.maxDecodedLength(B)),z=0,W=0,de=0,_e=0,Se=0,Ie=0,Fe=0;W>>4,q[z++]=Se<<4|Ie>>>2,q[z++]=Ie<<6|Fe,de|=_e&h,de|=Se&h,de|=Ie&h,de|=Fe&h;if(W>>4,de|=_e&h,de|=Se&h),W>>2,de|=Ie&h),W>>8&6,L+=51-k>>>8&-75,L+=61-k>>>8&-15,L+=62-k>>>8&3,String.fromCharCode(L)},O.prototype._decodeChar=function(k){var L=h;return L+=(42-k&k-44)>>>8&-h+k-43+62,L+=(46-k&k-48)>>>8&-h+k-47+63,L+=(47-k&k-58)>>>8&-h+k-48+52,L+=(64-k&k-91)>>>8&-h+k-65+0,L+=(96-k&k-123)>>>8&-h+k-97+26,L},O.prototype._getPaddingLength=function(k){var L=0;if(this._paddingCharacter){for(var B=k.length-1;B>=0&&k[B]===this._paddingCharacter;B--)L++;if(k.length<4||L>2)throw new Error("Base64Coder: incorrect padding")}return L},O})();d.Coder=m;var y=new m;function v(O){return y.encode(O)}d.encode=v;function S(O){return y.decode(O)}d.decode=S;var _=(function(O){f(k,O);function k(){return O!==null&&O.apply(this,arguments)||this}return k.prototype._encodeByte=function(L){var B=L;return B+=65,B+=25-L>>>8&6,B+=51-L>>>8&-75,B+=61-L>>>8&-13,B+=62-L>>>8&49,String.fromCharCode(B)},k.prototype._decodeChar=function(L){var B=h;return B+=(44-L&L-46)>>>8&-h+L-45+62,B+=(94-L&L-96)>>>8&-h+L-95+63,B+=(47-L&L-58)>>>8&-h+L-48+52,B+=(64-L&L-91)>>>8&-h+L-65+0,B+=(96-L&L-123)>>>8&-h+L-97+26,B},k})(m);d.URLSafeCoder=_;var x=new _;function A(O){return x.encode(O)}d.encodeURLSafe=A;function D(O){return x.decode(O)}d.decodeURLSafe=D,d.encodedLength=function(O){return y.encodedLength(O)},d.maxDecodedLength=function(O){return y.maxDecodedLength(O)},d.decodedLength=function(O){return y.decodedLength(O)}},978(c,d){var f="utf8: invalid source encoding";function h(m){for(var y=[],v=0;v=m.length)throw new Error(f);var x=m[++v];if((x&192)!==128)throw new Error(f);S=(S&31)<<6|x&63,_=128}else if(S<240){if(v>=m.length-1)throw new Error(f);var x=m[++v],A=m[++v];if((x&192)!==128||(A&192)!==128)throw new Error(f);S=(S&15)<<12|(x&63)<<6|A&63,_=2048}else if(S<248){if(v>=m.length-2)throw new Error(f);var x=m[++v],A=m[++v],D=m[++v];if((x&192)!==128||(A&192)!==128||(D&192)!==128)throw new Error(f);S=(S&15)<<18|(x&63)<<12|(A&63)<<6|D&63,_=65536}else throw new Error(f);if(S<_||S>=55296&&S<=57343)throw new Error(f);if(S>=65536){if(S>1114111)throw new Error(f);S-=65536,y.push(String.fromCharCode(55296|S>>10)),S=56320|S&1023}}y.push(String.fromCharCode(S))}return y.join("")}d.D4=h},721(c,d,f){c.exports=f(207).default},207(c,d,f){f.d(d,{default:()=>Is});class h{constructor(b,w){this.lastId=0,this.prefix=b,this.name=w}create(b){this.lastId++;var w=this.lastId,$=this.prefix+w,N=this.name+"["+w+"]",ne=!1,ye=function(){ne||(b.apply(null,arguments),ne=!0)};return this[w]=ye,{number:w,id:$,name:N,callback:ye}}remove(b){delete this[b.number]}}var m=new h("_pusher_script_","Pusher.ScriptReceivers"),y={VERSION:"8.6.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:""};const v=y;class S{constructor(b){this.options=b,this.receivers=b.receivers||m,this.loading={}}load(b,w,$){var N=this;if(N.loading[b]&&N.loading[b].length>0)N.loading[b].push($);else{N.loading[b]=[$];var ne=Ue.createScriptRequest(N.getPath(b,w)),ye=N.receivers.create(function(Le){if(N.receivers.remove(ye),N.loading[b]){var We=N.loading[b];delete N.loading[b];for(var ft=function(Vt){Vt||ne.cleanup()},vt=0;vt>>6)+Q(128|b&63):Q(224|b>>>12&15)+Q(128|b>>>6&63)+Q(128|b&63)},ee=function(E){return E.replace(/[^\x00-\x7F]/g,De)},me=function(E){var b=[0,2,1][E.length%3],w=E.charCodeAt(0)<<16|(E.length>1?E.charCodeAt(1):0)<<8|(E.length>2?E.charCodeAt(2):0),$=[ue.charAt(w>>>18),ue.charAt(w>>>12&63),b>=2?"=":ue.charAt(w>>>6&63),b>=1?"=":ue.charAt(w&63)];return $.join("")},H=typeof window<"u"&&window.btoa||function(E){return E.replace(/[\s\S]{1,3}/g,me)};class T{constructor(b,w,$,N){this.clear=w,this.timer=b(()=>{this.timer&&(this.timer=N(this.timer))},$)}isRunning(){return this.timer!==null}ensureAborted(){this.timer&&(this.clear(this.timer),this.timer=null)}}const fe=T;function he(E){window.clearTimeout(E)}function Ae(E){window.clearInterval(E)}class se extends fe{constructor(b,w){super(setTimeout,he,b,function($){return w(),null})}}class ge extends fe{constructor(b,w){super(setInterval,Ae,b,function($){return w(),$})}}var $e={now(){return Date.now?Date.now():new Date().valueOf()},defer(E){return new se(0,E)},method(E,...b){var w=Array.prototype.slice.call(arguments,1);return function($){return $[E].apply($,w.concat(arguments))}}};const Te=$e;function je(E,...b){for(var w=0;w{window.console&&window.console.log&&window.console.log(b)}}debug(...b){this.log(this.globalLog,b)}warn(...b){this.log(this.globalLogWarn,b)}error(...b){this.log(this.globalLogError,b)}globalLogWarn(b){window.console&&window.console.warn?window.console.warn(b):this.globalLog(b)}globalLogError(b){window.console&&window.console.error?window.console.error(b):this.globalLogWarn(b)}log(b,...w){var $=xt.apply(this,arguments);Is.log?Is.log($):Is.logToConsole&&b.bind(this)($)}}const it=new Mn;var Pn=function(E,b,w,$,N){(w.headers!==void 0||w.headersProvider!=null)&&it.warn(`To send headers with the ${$.toString()} request, you must use AJAX, rather than JSONP.`);var ne=E.nextAuthCallbackID.toString();E.nextAuthCallbackID++;var ye=E.getDocument(),Le=ye.createElement("script");E.auth_callbacks[ne]=function(vt){N(null,vt)};var We="Pusher.auth_callbacks['"+ne+"']";Le.src=w.endpoint+"?callback="+encodeURIComponent(We)+"&"+b;var ft=ye.getElementsByTagName("head")[0]||ye.documentElement;ft.insertBefore(Le,ft.firstChild)};const vn=Pn;class da{constructor(b){this.src=b}send(b){var w=this,$="Error loading "+w.src;w.script=document.createElement("script"),w.script.id=b.id,w.script.src=w.src,w.script.type="text/javascript",w.script.charset="UTF-8",w.script.addEventListener?(w.script.onerror=function(){b.callback($)},w.script.onload=function(){b.callback(null)}):w.script.onreadystatechange=function(){(w.script.readyState==="loaded"||w.script.readyState==="complete")&&b.callback(null)},w.script.async===void 0&&document.attachEvent&&/opera/i.test(navigator.userAgent)?(w.errorScript=document.createElement("script"),w.errorScript.id=b.id+"_error",w.errorScript.text=b.name+"('"+$+"');",w.script.async=w.errorScript.async=!1):w.script.async=!0;var N=document.getElementsByTagName("head")[0];N.insertBefore(w.script,N.firstChild),w.errorScript&&N.insertBefore(w.errorScript,w.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 fr{constructor(b,w){this.url=b,this.data=w}send(b){if(!this.request){var w=$i(this.data),$=this.url+"/"+b.number+"?"+w;this.request=Ue.createScriptRequest($),this.request.send(b)}}cleanup(){this.request&&this.request.cleanup()}}var un=function(E,b){return function(w,$){var N="http"+(b?"s":"")+"://",ne=N+(E.host||E.options.host)+E.options.path,ye=Ue.createJSONPRequest(ne,w),Le=Ue.ScriptReceivers.create(function(We,ft){m.remove(Le),ye.cleanup(),ft&&ft.host&&(E.host=ft.host),$&&$(We,ft)});ye.send(Le)}},Rn={name:"jsonp",getAgent:un};const dn=Rn;function V(E,b,w){var $=E+(b.useTLS?"s":""),N=b.useTLS?b.hostTLS:b.hostNonTLS;return $+"://"+N+w}function ie(E,b){var w="/app/"+E,$="?protocol="+v.PROTOCOL+"&client=js&version="+v.VERSION+(b?"&"+b:"");return w+$}var ce={getInitial:function(E,b){var w=(b.httpPath||"")+ie(E,"flash=false");return V("ws",b,w)}},Z={getInitial:function(E,b){var w=(b.httpPath||"/pusher")+ie(E);return V("http",b,w)}},ve={getInitial:function(E,b){return V("http",b,b.httpPath||"/pusher")},getPath:function(E,b){return ie(E)}};class pe{constructor(){this._callbacks={}}get(b){return this._callbacks[Ee(b)]}add(b,w,$){var N=Ee(b);this._callbacks[N]=this._callbacks[N]||[],this._callbacks[N].push({fn:w,context:$})}remove(b,w,$){if(!b&&!w&&!$){this._callbacks={};return}var N=b?[Ee(b)]:at(this._callbacks);w||$?this.removeCallback(N,w,$):this.removeAllCallbacks(N)}removeCallback(b,w,$){Ht(b,function(N){this._callbacks[N]=mt(this._callbacks[N]||[],function(ne){return w&&w!==ne.fn||$&&$!==ne.context}),this._callbacks[N].length===0&&delete this._callbacks[N]},this)}removeAllCallbacks(b){Ht(b,function(w){delete this._callbacks[w]},this)}}function Ee(E){return"_"+E}class xe{constructor(b){this.callbacks=new pe,this.global_callbacks=[],this.failThrough=b}bind(b,w,$){return this.callbacks.add(b,w,$),this}bind_global(b){return this.global_callbacks.push(b),this}unbind(b,w,$){return this.callbacks.remove(b,w,$),this}unbind_global(b){return b?(this.global_callbacks=mt(this.global_callbacks||[],w=>w!==b),this):(this.global_callbacks=[],this)}unbind_all(){return this.unbind(),this.unbind_global(),this}emit(b,w,$){for(var N=0;N0)for(var N=0;N{this.onError(w),this.changeState("closed")}),!1}return this.bindListeners(),it.debug("Connecting",{transport:this.name,url:b}),this.changeState("connecting"),!0}close(){return this.socket?(this.socket.close(),!0):!1}send(b){return this.state==="open"?(Te.defer(()=>{this.socket&&this.socket.send(b)}),!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(b){this.emit("error",{type:"WebSocketError",error:b}),this.timeline.error(this.buildTimelineMessage({error:b.toString()}))}onClose(b){b?this.changeState("closed",{code:b.code,reason:b.reason,wasClean:b.wasClean}):this.changeState("closed"),this.unbindListeners(),this.socket=void 0}onMessage(b){this.emit("message",b)}onActivity(){this.emit("activity")}bindListeners(){this.socket.onopen=()=>{this.onOpen()},this.socket.onerror=b=>{this.onError(b)},this.socket.onclose=b=>{this.onClose(b)},this.socket.onmessage=b=>{this.onMessage(b)},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(b,w){this.state=b,this.timeline.info(this.buildTimelineMessage({state:b,params:w})),this.emit(b,w)}buildTimelineMessage(b){return je({cid:this.id},b)}}class ke{constructor(b){this.hooks=b}isSupported(b){return this.hooks.isSupported(b)}createConnection(b,w,$,N){return new Ke(this.hooks,b,w,$,N)}}var Me=new ke({urls:ce,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return!!Ue.getWebSocketAPI()},isSupported:function(){return!!Ue.getWebSocketAPI()},getSocket:function(E){return Ue.createWebSocket(E)}}),Re={urls:Z,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},tt=je({getSocket:function(E){return Ue.HTTPFactory.createStreamingSocket(E)}},Re),Pe=je({getSocket:function(E){return Ue.HTTPFactory.createPollingSocket(E)}},Re),Ve={isSupported:function(){return Ue.isXHRSupported()}},Ce=new ke(je({},tt,Ve)),He=new ke(je({},Pe,Ve)),nt={ws:Me,xhr_streaming:Ce,xhr_polling:He};const Lt=nt;var Bt=new ke({file:"sockjs",urls:ve,handlesActivityChecks:!0,supportsPing:!1,isSupported:function(){return!0},isInitialized:function(){return window.SockJS!==void 0},getSocket:function(E,b){return new window.SockJS(E,null,{js_path:x.getPath("sockjs",{useTLS:b.useTLS}),ignore_null_origin:b.ignoreNullOrigin})},beforeOpen:function(E,b){E.send(JSON.stringify({path:b}))}}),Nn={isSupported:function(E){var b=Ue.isXDRSupported(E.useTLS);return b}},Gt=new ke(je({},tt,Nn)),Ft=new ke(je({},Pe,Nn));Lt.xdr_streaming=Gt,Lt.xdr_polling=Ft,Lt.sockjs=Bt;const Dn=Lt;class Ba extends xe{constructor(){super();var b=this;typeof window<"u"&&window.addEventListener!==void 0&&(window.addEventListener("online",function(){b.emit("online")},!1),window.addEventListener("offline",function(){b.emit("offline")},!1))}isOnline(){return window.navigator.onLine===void 0?!0:window.navigator.onLine}}var rl=new Ba;class mh{constructor(b,w,$){this.manager=b,this.transport=w,this.minPingDelay=$.minPingDelay,this.maxPingDelay=$.maxPingDelay,this.pingDelay=void 0}createConnection(b,w,$,N){N=je({},N,{activityTimeout:this.pingDelay});var ne=this.transport.createConnection(b,w,$,N),ye=null,Le=function(){ne.unbind("open",Le),ne.bind("closed",We),ye=Te.now()},We=ft=>{if(ne.unbind("closed",We),ft.code===1002||ft.code===1003)this.manager.reportDeath();else if(!ft.wasClean&&ye){var vt=Te.now()-ye;vt<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(vt/2,this.minPingDelay))}};return ne.bind("open",Le),ne}isSupported(b){return this.manager.isAlive()&&this.transport.isSupported(b)}}const Zc={decodeMessage:function(E){try{var b=JSON.parse(E.data),w=b.data;if(typeof w=="string")try{w=JSON.parse(b.data)}catch{}var $={event:b.event,channel:b.channel,data:w};return b.user_id&&($.user_id=b.user_id),$}catch(N){throw{type:"MessageParseError",error:N,data:E.data}}},encodeMessage:function(E){return JSON.stringify(E)},processHandshake:function(E){var b=Zc.decodeMessage(E);if(b.event==="pusher:connection_established"){if(!b.data.activity_timeout)throw"No activity timeout specified in handshake";return{action:"connected",id:b.data.socket_id,activityTimeout:b.data.activity_timeout*1e3}}else{if(b.event==="pusher:error")return{action:this.getCloseAction(b.data),error:this.getCloseError(b.data)};throw"Invalid handshake"}},getCloseAction:function(E){return E.code<4e3?E.code>=1002&&E.code<=1004?"backoff":null:E.code===4e3?"tls_only":E.code<4100?"refused":E.code<4200?"backoff":E.code<4300?"retry":"refused"},getCloseError:function(E){return E.code!==1e3&&E.code!==1001?{type:"PusherError",data:{code:E.code,message:E.reason||E.message}}:null}},Yr=Zc;class Mi extends xe{constructor(b,w){super(),this.id=b,this.transport=w,this.activityTimeout=w.activityTimeout,this.bindListeners()}handlesActivityChecks(){return this.transport.handlesActivityChecks()}send(b){return this.transport.send(b)}send_event(b,w,$){var N={event:b,data:w};return $&&(N.channel=$),it.debug("Event sent",N),this.send(Yr.encodeMessage(N))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var b={message:$=>{var N;try{N=Yr.decodeMessage($)}catch(ne){this.emit("error",{type:"MessageParseError",error:ne,data:$.data})}if(N!==void 0){switch(it.debug("Event recd",N),N.event){case"pusher:error":this.emit("error",{type:"PusherError",data:N.data});break;case"pusher:ping":this.emit("ping");break;case"pusher:pong":this.emit("pong");break}this.emit("message",N)}},activity:()=>{this.emit("activity")},error:$=>{this.emit("error",$)},closed:$=>{w(),$&&$.code&&this.handleCloseEvent($),this.transport=null,this.emit("closed")}},w=()=>{gt(b,($,N)=>{this.transport.unbind(N,$)})};gt(b,($,N)=>{this.transport.bind(N,$)})}handleCloseEvent(b){var w=Yr.getCloseAction(b),$=Yr.getCloseError(b);$&&this.emit("error",$),w&&this.emit(w,{action:w,error:$})}}class al{constructor(b,w){this.transport=b,this.callback=w,this.bindListeners()}close(){this.unbindListeners(),this.transport.close()}bindListeners(){this.onMessage=b=>{this.unbindListeners();var w;try{w=Yr.processHandshake(b)}catch($){this.finish("error",{error:$}),this.transport.close();return}w.action==="connected"?this.finish("connected",{connection:new Mi(w.id,this.transport),activityTimeout:w.activityTimeout}):(this.finish(w.action,{error:w.error}),this.transport.close())},this.onClosed=b=>{this.unbindListeners();var w=Yr.getCloseAction(b)||"backoff",$=Yr.getCloseError(b);this.finish(w,{error:$})},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(b,w){this.callback(je({transport:this.transport,action:b},w))}}class qa{constructor(b,w){this.timeline=b,this.options=w||{}}send(b,w){this.timeline.isEmpty()||this.timeline.send(Ue.TimelineTransport.getAgent(this,b),w)}}class Xr extends xe{constructor(b,w){super(function($,N){it.debug("No callbacks on "+b+" for "+$)}),this.name=b,this.pusher=w,this.subscribed=!1,this.subscriptionPending=!1,this.subscriptionCancelled=!1}authorize(b,w){return w(null,{auth:""})}trigger(b,w){if(b.indexOf("client-")!==0)throw new L("Event '"+b+"' does not start with 'client-'");if(!this.subscribed){var $=O.buildLogSuffix("triggeringClientEvents");it.warn(`Client event triggered before channel 'subscription_succeeded' event . ${$}`)}return this.pusher.send_event(b,w,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(b){var w=b.event,$=b.data;if(w==="pusher_internal:subscription_succeeded")this.handleSubscriptionSucceededEvent(b);else if(w==="pusher_internal:subscription_count")this.handleSubscriptionCountEvent(b);else if(w.indexOf("pusher_internal:")!==0){var N={};this.emit(w,$,N)}}handleSubscriptionSucceededEvent(b){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):this.emit("pusher:subscription_succeeded",b.data)}handleSubscriptionCountEvent(b){b.data.subscription_count&&(this.subscriptionCount=b.data.subscription_count),this.emit("pusher:subscription_count",b.data)}subscribe(){this.subscribed||(this.subscriptionPending=!0,this.subscriptionCancelled=!1,this.authorize(this.pusher.connection.socket_id,(b,w)=>{b?(this.subscriptionPending=!1,it.error(b.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:b.message},b instanceof Ie?{status:b.status}:{}))):this.pusher.send_event("pusher:subscribe",{auth:w.auth,channel_data:w.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 fa extends Xr{authorize(b,w){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:b},w)}}class Ga{constructor(){this.reset()}get(b){return Object.prototype.hasOwnProperty.call(this.members,b)?{id:b,info:this.members[b]}:null}each(b){gt(this.members,(w,$)=>{b(this.get($))})}setMyID(b){this.myID=b}onSubscription(b){this.members=b.presence.hash,this.count=b.presence.count,this.me=this.get(this.myID)}addMember(b){return this.get(b.user_id)===null&&this.count++,this.members[b.user_id]=b.user_info,this.get(b.user_id)}removeMember(b){var w=this.get(b.user_id);return w&&(delete this.members[b.user_id],this.count--),w}reset(){this.members={},this.count=0,this.myID=null,this.me=null}}var nn=function(E,b,w,$){function N(ne){return ne instanceof w?ne:new w(function(ye){ye(ne)})}return new(w||(w=Promise))(function(ne,ye){function Le(vt){try{ft($.next(vt))}catch(Vt){ye(Vt)}}function We(vt){try{ft($.throw(vt))}catch(Vt){ye(Vt)}}function ft(vt){vt.done?ne(vt.value):N(vt.value).then(Le,We)}ft(($=$.apply(E,b||[])).next())})};class eu extends fa{constructor(b,w){super(b,w),this.members=new Ga}authorize(b,w){super.authorize(b,($,N)=>nn(this,void 0,void 0,function*(){if(!$)if(N=N,N.channel_data!=null){var ne=JSON.parse(N.channel_data);this.members.setMyID(ne.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 ye=O.buildLogSuffix("authorizationEndpoint");it.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${ye}, or the user should be signed in.`),w("Invalid auth response");return}w($,N)}))}handleEvent(b){var w=b.event;if(w.indexOf("pusher_internal:")===0)this.handleInternalEvent(b);else{var $=b.data,N={};b.user_id&&(N.user_id=b.user_id),this.emit(w,$,N)}}handleInternalEvent(b){var w=b.event,$=b.data;switch(w){case"pusher_internal:subscription_succeeded":this.handleSubscriptionSucceededEvent(b);break;case"pusher_internal:subscription_count":this.handleSubscriptionCountEvent(b);break;case"pusher_internal:member_added":var N=this.members.addMember($);this.emit("pusher:member_added",N);break;case"pusher_internal:member_removed":var ne=this.members.removeMember($);ne&&this.emit("pusher:member_removed",ne);break}}handleSubscriptionSucceededEvent(b){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):(this.members.onSubscription(b.data),this.emit("pusher:subscription_succeeded",this.members))}disconnect(){this.members.reset(),super.disconnect()}}var tu=f(978),$r=f(594);class Fa extends fa{constructor(b,w,$){super(b,w),this.key=null,this.nacl=$}authorize(b,w){super.authorize(b,($,N)=>{if($){w($,N);return}let ne=N.shared_secret;if(!ne){w(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null);return}this.key=(0,$r.decode)(ne),delete N.shared_secret,w(null,N)})}trigger(b,w){throw new de("Client events are not currently supported for encrypted channels")}handleEvent(b){var w=b.event,$=b.data;if(w.indexOf("pusher_internal:")===0||w.indexOf("pusher:")===0){super.handleEvent(b);return}this.handleEncryptedEvent(w,$)}handleEncryptedEvent(b,w){if(!this.key){it.debug("Received encrypted event before key has been retrieved from the authEndpoint");return}if(!w.ciphertext||!w.nonce){it.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+w);return}let $=(0,$r.decode)(w.ciphertext);if($.length{if(ye){it.error(`Failed to make a request to the authEndpoint: ${Le}. Unable to fetch new key, so dropping encrypted event`);return}if(ne=this.nacl.secretbox.open($,N,this.key),ne===null){it.error("Failed to decrypt event with new key. Dropping encrypted event");return}this.emit(b,this.getDataToEmit(ne))});return}this.emit(b,this.getDataToEmit(ne))}getDataToEmit(b){let w=(0,tu.D4)(b);try{return JSON.parse(w)}catch{return w}}}class yh extends xe{constructor(b,w){super(),this.state="initialized",this.connection=null,this.key=b,this.options=w,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 $=Ue.getNetwork();$.bind("online",()=>{this.timeline.info({netinfo:"online"}),(this.state==="connecting"||this.state==="unavailable")&&this.retryIn(0)}),$.bind("offline",()=>{this.timeline.info({netinfo:"offline"}),this.connection&&this.sendActivityCheck()}),this.updateStrategy()}switchCluster(b){this.key=b,this.updateStrategy(),this.retryIn(0)}connect(){if(!(this.connection||this.runner)){if(!this.strategy.isSupported()){this.updateState("failed");return}this.updateState("connecting"),this.startConnecting(),this.setUnavailableTimer()}}send(b){return this.connection?this.connection.send(b):!1}send_event(b,w,$){return this.connection?this.connection.send_event(b,w,$):!1}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var b=(w,$)=>{w?this.runner=this.strategy.connect(0,b):$.action==="error"?(this.emit("error",{type:"HandshakeError",error:$.error}),this.timeline.error({handshakeError:$.error})):(this.abortConnecting(),this.handshakeCallbacks[$.action]($))};this.runner=this.strategy.connect(0,b)}abortConnecting(){this.runner&&(this.runner.abort(),this.runner=null)}disconnectInternally(){if(this.abortConnecting(),this.clearRetryTimer(),this.clearUnavailableTimer(),this.connection){var b=this.abandonConnection();b.close()}}updateStrategy(){this.strategy=this.options.getStrategy({key:this.key,timeline:this.timeline,useTLS:this.usingTLS})}retryIn(b){this.timeline.info({action:"retry",delay:b}),b>0&&this.emit("connecting_in",Math.round(b/1e3)),this.retryTimer=new se(b||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new se(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new se(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 se(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(b){return je({},b,{message:w=>{this.resetActivityCheck(),this.emit("message",w)},ping:()=>{this.send_event("pusher:pong",{})},activity:()=>{this.resetActivityCheck()},error:w=>{this.emit("error",w)},closed:()=>{this.abandonConnection(),this.shouldRetry()&&this.retryIn(1e3)}})}buildHandshakeCallbacks(b){return je({},b,{connected:w=>{this.activityTimeout=Math.min(this.options.activityTimeout,w.activityTimeout,w.connection.activityTimeout||1/0),this.clearUnavailableTimer(),this.setConnection(w.connection),this.socket_id=this.connection.id,this.updateState("connected",{socket_id:this.socket_id})}})}buildErrorCallbacks(){let b=w=>$=>{$.error&&this.emit("error",{type:"WebSocketError",error:$.error}),w($)};return{tls_only:b(()=>{this.usingTLS=!0,this.updateStrategy(),this.retryIn(0)}),refused:b(()=>{this.disconnect()}),backoff:b(()=>{this.retryIn(1e3)}),retry:b(()=>{this.retryIn(0)})}}setConnection(b){this.connection=b;for(var w in this.connectionCallbacks)this.connection.bind(w,this.connectionCallbacks[w]);this.resetActivityCheck()}abandonConnection(){if(this.connection){this.stopActivityCheck();for(var b in this.connectionCallbacks)this.connection.unbind(b,this.connectionCallbacks[b]);var w=this.connection;return this.connection=null,w}}updateState(b,w){var $=this.state;if(this.state=b,$!==b){var N=b;N==="connected"&&(N+=" with new socket ID "+w.socket_id),it.debug("State changed",$+" -> "+N),this.timeline.info({state:b,params:w}),this.emit("state_change",{previous:$,current:b}),this.emit(b,w)}}shouldRetry(){return this.state==="connecting"||this.state==="connected"}}class nu{constructor(){this.channels={}}add(b,w){return this.channels[b]||(this.channels[b]=ru(b,w)),this.channels[b]}all(){return Yt(this.channels)}find(b){return this.channels[b]}remove(b){var w=this.channels[b];return delete this.channels[b],w}disconnect(){gt(this.channels,function(b){b.disconnect()})}}function ru(E,b){if(E.indexOf("private-encrypted-")===0){if(b.config.nacl)return Un.createEncryptedChannel(E,b,b.config.nacl);let w="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",$=O.buildLogSuffix("encryptedChannelSupport");throw new de(`${w}. ${$}`)}else{if(E.indexOf("private-")===0)return Un.createPrivateChannel(E,b);if(E.indexOf("presence-")===0)return Un.createPresenceChannel(E,b);if(E.indexOf("#")===0)throw new B('Cannot create a channel with name "'+E+'".');return Un.createChannel(E,b)}}var bh={createChannels(){return new nu},createConnectionManager(E,b){return new yh(E,b)},createChannel(E,b){return new Xr(E,b)},createPrivateChannel(E,b){return new fa(E,b)},createPresenceChannel(E,b){return new eu(E,b)},createEncryptedChannel(E,b,w){return new Fa(E,b,w)},createTimelineSender(E,b){return new qa(E,b)},createHandshake(E,b){return new al(E,b)},createAssistantToTheTransportManager(E,b,w){return new mh(E,b,w)}};const Un=bh;class Ni{constructor(b){this.options=b||{},this.livesLeft=this.options.lives||1/0}getAssistant(b){return Un.createAssistantToTheTransportManager(this,b,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class Sn{constructor(b,w){this.strategies=b,this.loop=!!w.loop,this.failFast=!!w.failFast,this.timeout=w.timeout,this.timeoutLimit=w.timeoutLimit}isSupported(){return kn(this.strategies,Te.method("isSupported"))}connect(b,w){var $=this.strategies,N=0,ne=this.timeout,ye=null,Le=(We,ft)=>{ft?w(null,ft):(N=N+1,this.loop&&(N=N%$.length),N<$.length?(ne&&(ne=ne*2,this.timeoutLimit&&(ne=Math.min(ne,this.timeoutLimit))),ye=this.tryStrategy($[N],b,{timeout:ne,failFast:this.failFast},Le)):w(!0))};return ye=this.tryStrategy($[N],b,{timeout:ne,failFast:this.failFast},Le),{abort:function(){ye.abort()},forceMinPriority:function(We){b=We,ye&&ye.forceMinPriority(We)}}}tryStrategy(b,w,$,N){var ne=null,ye=null;return $.timeout>0&&(ne=new se($.timeout,function(){ye.abort(),N(!0)})),ye=b.connect(w,function(Le,We){Le&&ne&&ne.isRunning()&&!$.failFast||(ne&&ne.ensureAborted(),N(Le,We))}),{abort:function(){ne&&ne.ensureAborted(),ye.abort()},forceMinPriority:function(Le){ye.forceMinPriority(Le)}}}}class On{constructor(b){this.strategies=b}isSupported(){return kn(this.strategies,Te.method("isSupported"))}connect(b,w){return au(this.strategies,b,function($,N){return function(ne,ye){if(N[$].error=ne,ne){vh(N)&&w(!0);return}Ht(N,function(Le){Le.forceMinPriority(ye.transport.priority)}),w(null,ye)}})}}function au(E,b,w){var $=bt(E,function(N,ne,ye,Le){return N.connect(b,w(ne,Le))});return{abort:function(){Ht($,il)},forceMinPriority:function(N){Ht($,function(ne){ne.forceMinPriority(N)})}}}function vh(E){return dr(E,function(b){return!!b.error})}function il(E){!E.error&&!E.aborted&&(E.abort(),E.aborted=!0)}class iu{constructor(b,w,$){this.strategy=b,this.transports=w,this.ttl=$.ttl||18e5,this.usingTLS=$.useTLS,this.timeline=$.timeline}isSupported(){return this.strategy.isSupported()}connect(b,w){var $=this.usingTLS,N=Sh($),ne=N&&N.cacheSkipCount?N.cacheSkipCount:0,ye=[this.strategy];if(N&&N.timestamp+this.ttl>=Te.now()){var Le=this.transports[N.transport];Le&&(["ws","wss"].includes(N.transport)||ne>3?(this.timeline.info({cached:!0,transport:N.transport,latency:N.latency}),ye.push(new Sn([Le],{timeout:N.latency*2+1e3,failFast:!0}))):ne++)}var We=Te.now(),ft=ye.pop().connect(b,function vt(Vt,jr){Vt?(Os($),ye.length>0?(We=Te.now(),ft=ye.pop().connect(b,vt)):w(Vt)):(Bn($,jr.transport.name,Te.now()-We,ne),w(null,jr))});return{abort:function(){ft.abort()},forceMinPriority:function(vt){b=vt,ft&&ft.forceMinPriority(vt)}}}}function Va(E){return"pusherTransport"+(E?"TLS":"NonTLS")}function Sh(E){var b=Ue.getLocalStorage();if(b)try{var w=b[Va(E)];if(w)return JSON.parse(w)}catch{Os(E)}return null}function Bn(E,b,w,$){var N=Ue.getLocalStorage();if(N)try{N[Va(E)]=bn({timestamp:Te.now(),transport:b,latency:w,cacheSkipCount:$})}catch{}}function Os(E){var b=Ue.getLocalStorage();if(b)try{delete b[Va(E)]}catch{}}class Ii{constructor(b,{delay:w}){this.strategy=b,this.options={delay:w}}isSupported(){return this.strategy.isSupported()}connect(b,w){var $=this.strategy,N,ne=new se(this.options.delay,function(){N=$.connect(b,w)});return{abort:function(){ne.ensureAborted(),N&&N.abort()},forceMinPriority:function(ye){b=ye,N&&N.forceMinPriority(ye)}}}}class ha{constructor(b,w,$){this.test=b,this.trueBranch=w,this.falseBranch=$}isSupported(){var b=this.test()?this.trueBranch:this.falseBranch;return b.isSupported()}connect(b,w){var $=this.test()?this.trueBranch:this.falseBranch;return $.connect(b,w)}}class Ka{constructor(b){this.strategy=b}isSupported(){return this.strategy.isSupported()}connect(b,w){var $=this.strategy.connect(b,function(N,ne){ne&&$.abort(),w(N,ne)});return $}}function Wa(E){return function(){return E.isSupported()}}var su=function(E,b,w){var $={};function N(vl,Su,wu,Uh,Bh){var Cu=w(E,vl,Su,wu,Uh,Bh);return $[vl]=Cu,Cu}var ne=Object.assign({},b,{hostNonTLS:E.wsHost+":"+E.wsPort,hostTLS:E.wsHost+":"+E.wssPort,httpPath:E.wsPath}),ye=Object.assign({},ne,{useTLS:!0}),Le=Object.assign({},b,{hostNonTLS:E.httpHost+":"+E.httpPort,hostTLS:E.httpHost+":"+E.httpsPort,httpPath:E.httpPath}),We={loop:!0,timeout:15e3,timeoutLimit:6e4},ft=new Ni({minPingDelay:1e4,maxPingDelay:E.activityTimeout}),vt=new Ni({lives:2,minPingDelay:1e4,maxPingDelay:E.activityTimeout}),Vt=N("ws","ws",3,ne,ft),jr=N("wss","ws",3,ye,ft),Hh=N("sockjs","sockjs",1,Le),bu=N("xhr_streaming","xhr_streaming",1,Le,vt),zh=N("xdr_streaming","xdr_streaming",1,Le,vt),ml=N("xhr_polling","xhr_polling",1,Le),vu=N("xdr_polling","xdr_polling",1,Le),Ja=new Sn([Vt],We),Bi=new Sn([jr],We),Ph=new Sn([Hh],We),qi=new Sn([new ha(Wa(bu),bu,zh)],We),yl=new Sn([new ha(Wa(ml),ml,vu)],We),bl=new Sn([new ha(Wa(qi),new On([qi,new Ii(yl,{delay:4e3})]),yl)],We),Gi=new ha(Wa(bl),bl,Ph),Fi;return b.useTLS?Fi=new On([Ja,new Ii(Gi,{delay:2e3})]):Fi=new On([Ja,new Ii(Bi,{delay:2e3}),new Ii(Gi,{delay:5e3})]),new iu(new Ka(new ha(Wa(Vt),Fi,Gi)),$,{ttl:18e5,timeline:b.timeline,useTLS:b.useTLS})};const Ya=su;function wh(){var E=this;E.timeline.info(E.buildTimelineMessage({transport:E.name+(E.options.useTLS?"s":"")})),E.hooks.isInitialized()?E.changeState("initialized"):E.hooks.file?(E.changeState("initializing"),x.load(E.hooks.file,{useTLS:E.options.useTLS},function(b,w){E.hooks.isInitialized()?(E.changeState("initialized"),w(!0)):(b&&E.onError(b),E.onClose(),w(!1))})):E.onClose()}var ou={getRequest:function(E){var b=new window.XDomainRequest;return b.ontimeout=function(){E.emit("error",new q),E.close()},b.onerror=function(w){E.emit("error",w),E.close()},b.onprogress=function(){b.responseText&&b.responseText.length>0&&E.onChunk(200,b.responseText)},b.onload=function(){b.responseText&&b.responseText.length>0&&E.onChunk(200,b.responseText),E.emit("finished",200),E.close()},b},abortRequest:function(E){E.ontimeout=E.onerror=E.onprogress=E.onload=null,E.abort()}};const lu=ou,sl=256*1024;class Ch extends xe{constructor(b,w,$){super(),this.hooks=b,this.method=w,this.url=$}start(b){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},Ue.addUnloadListener(this.unloader),this.xhr.open(this.method,this.url,!0),this.xhr.setRequestHeader&&this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.send(b)}close(){this.unloader&&(Ue.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(b,w){for(;;){var $=this.advanceBuffer(w);if($)this.emit("chunk",{status:b,data:$});else break}this.isBufferTooLong(w)&&this.emit("buffer_too_long")}advanceBuffer(b){var w=b.slice(this.position),$=w.indexOf(` -`);return $!==-1?(this.position+=$+1,w.slice(0,$)):null}isBufferTooLong(b){return this.position===b.length&&b.length>sl}}var ol;(function(E){E[E.CONNECTING=0]="CONNECTING",E[E.OPEN=1]="OPEN",E[E.CLOSED=3]="CLOSED"})(ol||(ol={}));const hr=ol;var Mr=1;class ll{constructor(b,w){this.hooks=b,this.session=Ls(1e3)+"/"+uu(8),this.location=cl(w),this.readyState=hr.CONNECTING,this.openStream()}send(b){return this.sendRaw(JSON.stringify([b]))}ping(){this.hooks.sendHeartbeat(this)}close(b,w){this.onClose(b,w,!0)}sendRaw(b){if(this.readyState===hr.OPEN)try{return Ue.createSocketRequest("POST",pa(Xa(this.location,this.session))).start(b),!0}catch{return!1}else return!1}reconnect(){this.closeStream(),this.openStream()}onClose(b,w,$){this.closeStream(),this.readyState=hr.CLOSED,this.onclose&&this.onclose({code:b,reason:w,wasClean:$})}onChunk(b){if(b.status===200){this.readyState===hr.OPEN&&this.onActivity();var w,$=b.data.slice(0,1);switch($){case"o":w=JSON.parse(b.data.slice(1)||"{}"),this.onOpen(w);break;case"a":w=JSON.parse(b.data.slice(1)||"[]");for(var N=0;N{this.onChunk(b)}),this.stream.bind("finished",b=>{this.hooks.onFinished(this,b)}),this.stream.bind("buffer_too_long",()=>{this.reconnect()});try{this.stream.start()}catch(b){Te.defer(()=>{this.onError(b),this.onClose(1006,"Could not start streaming",!1)})}}closeStream(){this.stream&&(this.stream.unbind_all(),this.stream.close(),this.stream=null)}}function cl(E){var b=/([^\?]*)\/*(\??.*)/.exec(E);return{base:b[1],queryString:b[2]}}function Xa(E,b){return E.base+"/"+b+"/xhr_send"}function pa(E){var b=E.indexOf("?")===-1?"?":"&";return E+b+"t="+ +new Date+"&n="+Mr++}function cu(E,b){var w=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(E);return w[1]+b+w[3]}function Ls(E){return Ue.randomInt(E)}function uu(E){for(var b=[],w=0;w0&&E.onChunk(w.status,w.responseText);break;case 4:w.responseText&&w.responseText.length>0&&E.onChunk(w.status,w.responseText),E.emit("finished",w.status),E.close();break}},w},abortRequest:function(E){E.onreadystatechange=null,E.abort()}};const $s=dl;var du={createStreamingSocket(E){return this.createSocket(ul,E)},createPollingSocket(E){return this.createSocket(Jr,E)},createSocket(E,b){return new ji(E,b)},createXHR(E,b){return this.createRequest($s,E,b)},createRequest(E,b,w){return new Ch(E,b,w)}};const zi=du;zi.createXDR=function(E,b){return this.createRequest(lu,E,b)};var fu={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:m,DependenciesReceivers:_,getDefaultStrategy:Ya,Transports:Dn,transportConnectionInitializer:wh,HTTPFactory:zi,TimelineTransport:dn,getXHRAPI(){return window.XMLHttpRequest},getWebSocketAPI(){return window.WebSocket||window.MozWebSocket},setup(E){if(typeof window<"u"){window.Pusher=E;var b=()=>{this.onDocumentBody(E.ready)};window.JSON?b():x.load("json2",{},b)}},getDocument(){return document},getProtocol(){return this.getDocument().location.protocol},getAuthorizers(){return{ajax:ze,jsonp:vn}},onDocumentBody(E){document.body?E():setTimeout(()=>{this.onDocumentBody(E)},0)},createJSONPRequest(E,b){return new fr(E,b)},createScriptRequest(E){return new da(E)},getLocalStorage(){try{return window.localStorage}catch{return}},createXHR(){return this.getXHRAPI()?this.createXMLHttpRequest():this.createMicrosoftXHR()},createXMLHttpRequest(){var E=this.getXHRAPI();return new E},createMicrosoftXHR(){return new ActiveXObject("Microsoft.XMLHTTP")},getNetwork(){return rl},createWebSocket(E){var b=this.getWebSocketAPI();return new b(E)},createSocketRequest(E,b){if(this.isXHRSupported())return this.HTTPFactory.createXHR(E,b);if(this.isXDRSupported(b.indexOf("https:")===0))return this.HTTPFactory.createXDR(E,b);throw"Cross-origin HTTP requests are not supported"},isXHRSupported(){var E=this.getXHRAPI();return!!E&&new E().withCredentials!==void 0},isXDRSupported(E){var b=E?"https:":"http:",w=this.getProtocol();return!!window.XDomainRequest&&w===b},addUnloadListener(E){window.addEventListener!==void 0?window.addEventListener("pagehide",E,!1):window.attachEvent!==void 0&&window.attachEvent("onunload",E)},removeUnloadListener(E){window.addEventListener!==void 0?window.removeEventListener("pagehide",E,!1):window.detachEvent!==void 0&&window.detachEvent("onunload",E)},randomInt(E){const b=window.crypto||window.msCrypto,w=Math.floor(Math.pow(2,32)/E)*E;let $;do $=b.getRandomValues(new Uint32Array(1))[0];while($>=w);return $%E}};const Ue=fu;var Ir;(function(E){E[E.ERROR=3]="ERROR",E[E.INFO=6]="INFO",E[E.DEBUG=7]="DEBUG"})(Ir||(Ir={}));const ga=Ir;class Pi{constructor(b,w,$){this.key=b,this.session=w,this.events=[],this.options=$||{},this.sent=0,this.uniqueID=0}log(b,w){b<=this.options.level&&(this.events.push(je({},w,{timestamp:Te.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(b){this.log(ga.ERROR,b)}info(b){this.log(ga.INFO,b)}debug(b){this.log(ga.DEBUG,b)}isEmpty(){return this.events.length===0}send(b,w){var $=je({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=[],b($,(N,ne)=>{N||this.sent++,w&&w(N,ne)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class Eh{constructor(b,w,$,N){this.name=b,this.priority=w,this.transport=$,this.options=N||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(b,w){if(this.isSupported()){if(this.priority{$||(vt(),ne?ne.close():N.close())},forceMinPriority:Vt=>{$||this.priority{var w="socket_id="+encodeURIComponent(E.socketId);for(var $ in b.params)w+="&"+encodeURIComponent($)+"="+encodeURIComponent(b.params[$]);if(b.paramsProvider!=null){let N=b.paramsProvider();for(var $ in N)w+="&"+encodeURIComponent($)+"="+encodeURIComponent(N[$])}return w},Ah=E=>{if(typeof Ue.getAuthorizers()[E.transport]>"u")throw`'${E.transport}' is not a recognized auth transport`;return(b,w)=>{const $=_h(b,E);Ue.getAuthorizers()[E.transport](Ue,$,E,k.UserAuthentication,w)}},pl=(E,b)=>{var w="socket_id="+encodeURIComponent(E.socketId);w+="&channel_name="+encodeURIComponent(E.channelName);for(var $ in b.params)w+="&"+encodeURIComponent($)+"="+encodeURIComponent(b.params[$]);if(b.paramsProvider!=null){let N=b.paramsProvider();for(var $ in N)w+="&"+encodeURIComponent($)+"="+encodeURIComponent(N[$])}return w},xh=E=>{if(typeof Ue.getAuthorizers()[E.transport]>"u")throw`'${E.transport}' is not a recognized auth transport`;return(b,w)=>{const $=pl(b,E);Ue.getAuthorizers()[E.transport](Ue,$,E,k.ChannelAuthorization,w)}},Th=(E,b,w)=>{const $={authTransport:b.transport,authEndpoint:b.endpoint,auth:{params:b.params,headers:b.headers}};return(N,ne)=>{const ye=E.channel(N.channelName);w(ye,$).authorize(N.socketId,ne)}};function pu(E,b){let w={activityTimeout:E.activityTimeout||v.activityTimeout,cluster:E.cluster,httpPath:E.httpPath||v.httpPath,httpPort:E.httpPort||v.httpPort,httpsPort:E.httpsPort||v.httpsPort,pongTimeout:E.pongTimeout||v.pongTimeout,statsHost:E.statsHost||v.stats_host,unavailableTimeout:E.unavailableTimeout||v.unavailableTimeout,wsPath:E.wsPath||v.wsPath,wsPort:E.wsPort||v.wsPort,wssPort:E.wssPort||v.wssPort,enableStats:Oh(E),httpHost:kh(E),useTLS:Dh(E),wsHost:gu(E),userAuthenticator:gl(E),channelAuthorizer:$h(E,b)};return"disabledTransports"in E&&(w.disabledTransports=E.disabledTransports),"enabledTransports"in E&&(w.enabledTransports=E.enabledTransports),"ignoreNullOrigin"in E&&(w.ignoreNullOrigin=E.ignoreNullOrigin),"timelineParams"in E&&(w.timelineParams=E.timelineParams),"nacl"in E&&(w.nacl=E.nacl),w}function kh(E){return E.httpHost?E.httpHost:E.cluster?`sockjs-${E.cluster}.pusher.com`:v.httpHost}function gu(E){return E.wsHost?E.wsHost:Rh(E.cluster)}function Rh(E){return`ws-${E}.pusher.com`}function Dh(E){return Ue.getProtocol()==="https:"?!0:E.forceTLS!==!1}function Oh(E){return"enableStats"in E?E.enableStats:"disableStats"in E?!E.disableStats:!1}const mu=E=>"customHandler"in E&&E.customHandler!=null;function gl(E){const b=Object.assign(Object.assign({},v.userAuthentication),E.userAuthentication);return mu(b)?b.customHandler:Ah(b)}function Lh(E,b){let w;return"channelAuthorization"in E?w=Object.assign(Object.assign({},v.channelAuthorization),E.channelAuthorization):(w={transport:E.authTransport||v.authTransport,endpoint:E.authEndpoint||v.authEndpoint},"auth"in E&&("params"in E.auth&&(w.params=E.auth.params),"headers"in E.auth&&(w.headers=E.auth.headers)),"authorizer"in E&&(w.customHandler=Th(b,w,E.authorizer))),w}function $h(E,b){const w=Lh(E,b);return mu(w)?w.customHandler:xh(w)}class Mh extends xe{constructor(b){super(function(w,$){it.debug(`No callbacks on watchlist events for ${w}`)}),this.pusher=b,this.bindWatchlistInternalEvent()}handleEvent(b){b.data.events.forEach(w=>{this.emit(w.name,w)})}bindWatchlistInternalEvent(){this.pusher.connection.bind("message",b=>{var w=b.event;w==="pusher_internal:watchlist_events"&&this.handleEvent(b)})}}function yu(){let E,b;return{promise:new Promise(($,N)=>{E=$,b=N}),resolve:E,reject:b}}const Nh=yu;class Ih extends xe{constructor(b){super(function(w,$){it.debug("No callbacks on user for "+w)}),this.signin_requested=!1,this.user_data=null,this.serverToUserChannel=null,this.signinDonePromise=null,this._signinDoneResolve=null,this._onAuthorize=(w,$)=>{if(w){it.warn(`Error during signin: ${w}`),this.emit("pusher:signin_error",Object.assign({},{type:"AuthError",error:w.message},w instanceof Ie?{status:w.status}:{})),this._cleanup();return}this.pusher.send_event("pusher:signin",{auth:$.auth,user_data:$.user_data})},this.pusher=b,this.pusher.connection.bind("state_change",({previous:w,current:$})=>{w!=="connected"&&$==="connected"&&this._signin(),w==="connected"&&$!=="connected"&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new Mh(b),this.pusher.connection.bind("message",w=>{var $=w.event;$==="pusher:signin_success"&&this._onSigninSuccess(w.data),this.serverToUserChannel&&this.serverToUserChannel.name===w.channel&&this.serverToUserChannel.handleEvent(w)})}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(b){try{this.user_data=JSON.parse(b.user_data)}catch{it.error(`Failed parsing user data after signin: ${b.user_data}`),this._cleanup();return}if(typeof this.user_data.id!="string"||this.user_data.id===""){it.error(`user_data doesn't contain an id. user_data: ${this.user_data}`),this._cleanup();return}this._signinDoneResolve(),this._subscribeChannels()}_subscribeChannels(){const b=w=>{w.subscriptionPending&&w.subscriptionCancelled?w.reinstateSubscription():!w.subscriptionPending&&this.pusher.connection.state==="connected"&&w.subscribe()};this.serverToUserChannel=new Xr(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((w,$)=>{w.indexOf("pusher_internal:")===0||w.indexOf("pusher:")===0||this.emit(w,$)}),b(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:b,resolve:w}=Nh();b.done=!1;const $=()=>{b.done=!0};b.then($).catch($),this.signinDonePromise=b,this._signinDoneResolve=w}}class fn{static ready(){fn.isReady=!0;for(var b=0,w=fn.instances.length;bUe.getDefaultStrategy(this.config,N,Ui);this.connection=Un.createConnectionManager(this.key,{getStrategy:$,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",N=>{var ne=N.event,ye=ne.indexOf("pusher_internal:")===0;if(N.channel){var Le=this.channel(N.channel);Le&&Le.handleEvent(N)}ye||this.global_emitter.emit(N.event,N.data)}),this.connection.bind("connecting",()=>{this.channels.disconnect()}),this.connection.bind("disconnected",()=>{this.channels.disconnect()}),this.connection.bind("error",N=>{it.warn(N)}),fn.instances.push(this),this.timeline.info({instances:fn.instances.length}),this.user=new Ih(this),fn.isReady&&this.connect()}switchCluster(b){const{appKey:w,cluster:$}=b;this.key=w,this.options=Object.assign(Object.assign({},this.options),{cluster:$}),this.config=pu(this.options,this),this.connection.switchCluster(this.key)}channel(b){return this.channels.find(b)}allChannels(){return this.channels.all()}connect(){if(this.connection.connect(),this.timelineSender&&!this.timelineSenderTimer){var b=this.connection.isUsingTLS(),w=this.timelineSender;this.timelineSenderTimer=new ge(6e4,function(){w.send(b)})}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(b,w,$){return this.global_emitter.bind(b,w,$),this}unbind(b,w,$){return this.global_emitter.unbind(b,w,$),this}bind_global(b){return this.global_emitter.bind_global(b),this}unbind_global(b){return this.global_emitter.unbind_global(b),this}unbind_all(b){return this.global_emitter.unbind_all(),this}subscribeAll(){var b;for(b in this.channels.channels)this.channels.channels.hasOwnProperty(b)&&this.subscribe(b)}subscribe(b){var w=this.channels.add(b,this);return w.subscriptionPending&&w.subscriptionCancelled?w.reinstateSubscription():!w.subscriptionPending&&this.connection.state==="connected"&&w.subscribe(),w}unsubscribe(b){var w=this.channels.find(b);w&&w.subscriptionPending?w.cancelSubscription():(w=this.channels.remove(b),w&&w.subscribed&&w.unsubscribe())}send_event(b,w,$){return this.connection.send_event(b,w,$)}shouldUseTLS(){return this.config.useTLS}signin(){this.user.signin()}}fn.instances=[],fn.isReady=!1,fn.logToConsole=!1,fn.Runtime=Ue,fn.ScriptReceivers=Ue.ScriptReceivers,fn.DependenciesReceivers=Ue.DependenciesReceivers,fn.auth_callbacks=Ue.auth_callbacks;const Is=fn;function jh(E){if(E==null)throw"You must pass your app key when you instantiate Pusher."}Ue.setup(fn)}},r={};function i(c){var d=r[c];if(d!==void 0)return d.exports;var f=r[c]={exports:{}};return n[c].call(f.exports,f,f.exports,i),f.exports}i.d=(c,d)=>{for(var f in d)i.o(d,f)&&!i.o(c,f)&&Object.defineProperty(c,f,{enumerable:!0,get:d[f]})},i.o=(c,d)=>Object.prototype.hasOwnProperty.call(c,d);var l=i(721);return l})())})(ch)),ch.exports}var Ux=Px();const Eb=ra(Ux),Kt=pt("WebSocketManager");class Bx{constructor(){M(this,"echo",null);M(this,"subscriptions",new Map);M(this,"initialized",!1);M(this,"config",null)}configure(e){if(this.initialized){Kt.warn("[WebSocketManager] 이미 초기화되어 설정을 변경할 수 없습니다.");return}this.config=e,Kt.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){Kt.warn("[WebSocketManager] WebSocket 설정이 없습니다. initTemplateApp에서 websocket 옵션을 전달해주세요.");return}const{appKey:e,host:n="localhost",port:r=80,scheme:i="https",authEndpoint:l="/api/broadcasting/auth"}=this.config,c=Number(r)||80,d=i==="https";Kt.log("[WebSocketManager] 연결 설정:",{host:n,port:c,scheme:i,useTLS:d,authEndpoint:l}),window.Pusher=Eb;const f=localStorage.getItem("auth_token"),h={wsHost:n,wsPort:c,wssPort:c,forceTLS:d,disableStats:!0,enabledTransports:["ws","wss"],cluster:"mt1",authEndpoint:l,auth:{headers:{Authorization:f?`Bearer ${f}`:"",Accept:"application/json"}}};Kt.log("[WebSocketManager] Pusher 옵션:",h);const m=new Eb(e,h);m.connection.bind("connecting",()=>{Kt.log("[WebSocketManager] 연결 시도 중...")}),m.connection.bind("connected",()=>{Kt.log("[WebSocketManager] 연결 성공! Socket ID:",m.connection.socket_id)}),m.connection.bind("failed",()=>{Kt.error("[WebSocketManager] 연결 실패 - WebSocket을 사용할 수 없습니다.")}),m.connection.bind("error",y=>{Kt.error("[WebSocketManager] 연결 오류:",y)}),m.connection.bind("state_change",y=>{Kt.log(`[WebSocketManager] 상태 변경: ${y.previous} → ${y.current}`)}),m.connection.bind("unavailable",()=>{Kt.error("[WebSocketManager] WebSocket 사용 불가 - 연결할 수 없습니다.")}),m.connection.bind("disconnected",()=>{Kt.warn("[WebSocketManager] 연결이 끊어졌습니다.")}),Kt.log("[WebSocketManager] 초기 연결 상태:",m.connection.state),this.echo=new zx({broadcaster:"reverb",client:m}),Kt.log("[WebSocketManager] 연결 시작 시도..."),m.connect(),window.Echo=this.echo,this.initialized=!0,Kt.log("[WebSocketManager] Echo 초기화 완료")}subscribe(e,n,r,i={}){if(this.initialize(),!this.echo)return Kt.warn("[WebSocketManager] Echo가 초기화되지 않았습니다."),"";const{channelType:l="private"}=i,c=`${e}:${n}`;if(this.subscriptions.has(c))return Kt.log(`[WebSocketManager] 이미 구독 중: ${c}`),c;let d;switch(l){case"public":d=this.echo.channel(e);break;case"presence":d=this.echo.join(e);break;default:d=this.echo.private(e)}return d.listen(`.${n}`,r),this.subscriptions.set(c,d),Kt.log(`[WebSocketManager] 구독 완료: ${c} (${l})`),c}unsubscribe(e){const n=this.subscriptions.get(e);if(!n)return;const r=e.lastIndexOf(":"),i=r>=0?e.substring(r+1):"";if(i)try{n.stopListening(`.${i}`)}catch(l){Kt.warn(`[WebSocketManager] stopListening 실패: ${e}`,l)}this.subscriptions.delete(e),Kt.log(`[WebSocketManager] 구독 해제: ${e}`)}leaveChannel(e){if(!this.echo)return;this.echo.leave(e);const n=[];this.subscriptions.forEach((r,i)=>{i.startsWith(`${e}:`)&&n.push(i)}),n.forEach(r=>this.subscriptions.delete(r)),Kt.log(`[WebSocketManager] 채널 구독 해제: ${e}`)}disconnect(){this.echo&&(this.echo.disconnect(),this.subscriptions.clear(),this.initialized=!1,Kt.log("[WebSocketManager] 연결 종료"))}getEcho(){return this.echo}isInitialized(){return this.initialized}isConfigured(){return this.config!==null&&!!this.config.appKey}getSubscriptionCount(){return this.subscriptions.size}}const Gc=new Bx,Ct=pt("DataSourceManager"),_b=new $n;function Fc(s,e){const n=La(s);if(n!==null)try{return Wn(n)?_b.evaluatePipeExpression(n,e,{skipCache:!0}):_b.evaluateExpression(n,e)}catch(r){return Ct.error("Failed to evaluate param expression:",n,r),s}return hs(s,e,{skipCache:!0})}function Ab(s){const e={};for(const n of s.keys()){if(n in e)continue;const r=s.getAll(n);r.length>1?e[n]=r:r.length===1&&(n.endsWith("[]")?e[n]=r:e[n]=r[0])}return e}function qx(){try{return window.G7Core?.devTools}catch{return}}const Qc=class Qc{constructor(e={}){M(this,"options");M(this,"dataCache",new Map);M(this,"bindingEngine");M(this,"globalHeaders",[]);this.options=e,this.bindingEngine=new $n}setGlobalHeaders(e){this.globalHeaders=e||[]}matchesPattern(e,n){if(n==="*")return!0;const r=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(e)}toFormData(e){const n=new FormData;for(const[r,i]of Object.entries(e))i instanceof File||i instanceof Blob?n.append(r,i):i!=null&&n.append(r,typeof i=="object"?JSON.stringify(i):String(i));return n}getMatchingGlobalHeaders(e,n){const r={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,c])=>{const d=Fc(c,n);d!=null&&d!==""&&(r[l]=String(d))});return r}filterByCondition(e,n={}){const r=new Set,i=[];for(const l of e){if(r.has(l.id))continue;if(!l.if&&!l.conditions){r.add(l.id),i.push(l);continue}fs({if:l.if,conditions:l.conditions},n,this.bindingEngine,`data_source:${l.id}`)&&(r.add(l.id),i.push(l))}return i}checkErrorCondition(e,n){if(!e.errorCondition?.if||e.errorCondition?.errorCode===void 0)return null;try{const r={response:n};if(fs({if:e.errorCondition.if},r,this.bindingEngine,`errorCondition:${e.id}`))return Ct.log(`errorCondition matched for ${e.id}, triggering error ${e.errorCondition.errorCode}`),e.errorCondition.errorCode}catch(r){Ct.error(`Failed to evaluate errorCondition for ${e.id}:`,r)}return null}async fetchDataSources(e,n={},r=new URLSearchParams,i,l){const c={},d=!!this.options.sampleProvider,f=e.filter(h=>(d||h.auto_fetch!==!1)&&h.type!=="websocket");return await Promise.all(f.map(async h=>{try{const m=await this.fetchDataSource(h,n,r,i,l);c[h.id]=m,this.dataCache.set(h.id,{data:m,timestamp:Date.now()});const y=this.checkErrorCondition(h,m);if(y!==null){const v={status:y,message:`Error condition matched for ${h.id}`,data:m},S=Tr(),_=S.resolve(y,{errorHandling:h.errorHandling,onError:h.onError});if(_.handler)try{await S.execute(_.handler,v)}catch(x){Ct.error(`Error executing errorCondition handler for ${h.id}:`,x)}h.fallback!==void 0&&(c[h.id]=h.fallback,this.dataCache.set(h.id,{data:h.fallback,timestamp:Date.now()}),Ct.log(`Using fallback data for ${h.id} (errorCondition)`));return}if(h.onSuccess)try{const v={data:m,sourceId:h.id};await this.executeOnSuccessHandler(h.onSuccess,v)}catch(v){Ct.error(`Error executing onSuccess handler for ${h.id}:`,v)}}catch(m){Ct.error(`Failed to fetch data source: ${h.id}`,m);const y=m?.response?.status||m?.status||500,v=m?.response?.data,S=v?.message||m.message||"Unknown error",_={status:y,message:S,errors:v?.errors,data:v,statusText:m?.response?.statusText},x=Tr(),A=x.resolve(y,{errorHandling:h.errorHandling,onError:h.onError});if(A.handler)try{await x.execute(A.handler,_)}catch(D){Ct.error(`Error executing error handler for ${h.id}:`,D)}h.fallback!==void 0&&(c[h.id]=h.fallback,this.dataCache.set(h.id,{data:h.fallback,timestamp:Date.now()}),Ct.log(`Using fallback data for ${h.id}`)),this.options.onError&&this.options.onError(m,h)}})),c}async fetchDataSourcesWithResults(e,n={},r=new URLSearchParams,i,l,c){if(e.some(m=>m.type==="websocket")){const m=e.filter(y=>y.type==="websocket").map(y=>y.id).join(", ");Ct.warn(`fetchDataSourcesWithResults received WebSocket sources (caller should filter them out before calling): ${m}. WebSocket sources are event listeners, not data providers — they should not be passed to fetch.`)}const f=c?.ignoreAutoFetch?e.filter(m=>m.type!=="websocket"):e.filter(m=>m.auto_fetch!==!1&&m.type!=="websocket");return await Promise.all(f.map(async m=>{try{const y=await this.fetchDataSource(m,n,r,i,l);this.dataCache.set(m.id,{data:y,timestamp:Date.now()});const v=this.checkErrorCondition(m,y);if(v!==null){const S={status:v,message:`Error condition matched for ${m.id}`,data:y},_=Tr(),x=_.resolve(v,{errorHandling:m.errorHandling,onError:m.onError});let A=!1;if(x.handler)if(m.loading_strategy==="blocking")_.execute(x.handler,S).catch(D=>{Ct.error(`Error executing errorCondition handler for ${m.id}:`,D)}),A=!0;else try{await _.execute(x.handler,S),A=!0}catch(D){Ct.error(`Error executing errorCondition handler for ${m.id}:`,D)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),Ct.log(`Using fallback data for ${m.id} (errorCondition)`),{id:m.id,state:"success",data:m.fallback}):{id:m.id,state:"error",error:new Error(`Error condition matched: ${v}`),errorCode:v,errorHandled:A}}if(m.onSuccess)try{const S={data:y,sourceId:m.id};await this.executeOnSuccessHandler(m.onSuccess,S)}catch(S){Ct.error(`Error executing onSuccess handler for ${m.id}:`,S)}return{id:m.id,state:"success",data:y}}catch(y){Ct.error(`Failed to fetch data source: ${m.id}`,y);const v=y?.response?.status||y?.status||500,S=y?.response?.data,_=S?.message||y.message||"Unknown error",x={status:v,message:_,errors:S?.errors,data:S,statusText:y?.response?.statusText},A=Tr(),D=A.resolve(v,{errorHandling:m.errorHandling,onError:m.onError});let O=!1;if(D.handler)if(m.loading_strategy==="blocking")A.execute(D.handler,x).catch(k=>{Ct.error(`Error executing error handler for ${m.id}:`,k)}),O=!0;else try{await A.execute(D.handler,x),O=!0}catch(k){Ct.error(`Error executing error handler for ${m.id}:`,k)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),Ct.log(`Using fallback data for ${m.id}`),{id:m.id,state:"success",data:m.fallback}):(this.options.onError&&this.options.onError(y,m),{id:m.id,state:"error",error:y,errorCode:v,errorHandled:O})}}))}fetchDataSourcesInBackground(e,n={},r=new URLSearchParams,i){e.filter(c=>c.auto_fetch!==!1&&c.loading_strategy==="background"&&c.type!=="websocket").forEach(c=>{this.fetchDataSource(c,n,r).then(async d=>{this.dataCache.set(c.id,{data:d,timestamp:Date.now()});const f=this.checkErrorCondition(c,d);if(f!==null){const h={status:f,message:`Error condition matched for ${c.id}`,data:d},m=Tr(),y=m.resolve(f,{errorHandling:c.errorHandling,onError:c.onError});if(y.handler)try{await m.execute(y.handler,h)}catch(v){Ct.error(`Error executing errorCondition handler for ${c.id}:`,v)}c.fallback!==void 0&&(this.dataCache.set(c.id,{data:c.fallback,timestamp:Date.now()}),Ct.log(`Using fallback data for ${c.id} (errorCondition)`),i&&i(c.id,c.fallback));return}if(c.onSuccess)try{const h={data:d,sourceId:c.id};await this.executeOnSuccessHandler(c.onSuccess,h)}catch(h){Ct.error(`Error executing onSuccess handler for ${c.id}:`,h)}i&&i(c.id,d)}).catch(async d=>{Ct.error(`Background fetch failed: ${c.id}`,d);const f=d?.response?.status||d?.status||500,h=d?.response?.data,m=h?.message||d.message||"Unknown error",y={status:f,message:m,errors:h?.errors,data:h,statusText:d?.response?.statusText},v=Tr(),S=v.resolve(f,{errorHandling:c.errorHandling,onError:c.onError});if(S.handler)try{await v.execute(S.handler,y)}catch(_){Ct.error(`Error executing error handler for ${c.id}:`,_)}if(c.fallback!==void 0){this.dataCache.set(c.id,{data:c.fallback,timestamp:Date.now()}),Ct.log(`Using fallback data for ${c.id}`),i&&i(c.id,c.fallback);return}this.options.onError&&this.options.onError(d,c)})})}async fetchDataSource(e,n,r,i,l){switch(e.type){case"api":return this.fetchApiDataSource(e,n,r,i,l);case"static":return e.data;case"route_params":return n;case"query_params":return Ab(r);default:throw new Error(`Unknown data source type: ${e.type}`)}}async fetchApiDataSource(e,n,r,i,l){if(this.options.sampleProvider?.has(e.id))return await Promise.resolve(this.options.sampleProvider.resolve(e));if(!e.endpoint)throw new Error(`API data source ${e.id} has no endpoint`);const c={route:n,query:Ab(r)};i&&(c._global=i),l&&(c._local=l);let d=hs(e.endpoint,c,{skipCache:!0});const f=e.method||"GET",m=(e.contentType?typeof e.contentType=="string"&&e.contentType.includes("{{")?hs(e.contentType,c,{skipCache:!0}):e.contentType:"application/json")==="multipart/form-data";let y=m?{...e.params||{}}:JSON.parse(JSON.stringify(e.params||{}));Object.entries(y).forEach(([_,x])=>{typeof x=="string"&&(y[_]=Fc(x,c))}),Object.keys(y).forEach(_=>{y[_]===""&&delete y[_]});const v=qx();let S=null;if(v?.isEnabled()){v.trackDataSourceDefinition({id:e.id,type:e.type,endpoint:d,method:f,autoFetch:e.auto_fetch,initLocal:e.initLocal,initGlobal:e.initGlobal});let _=d;if(f==="GET"&&Object.keys(y).length>0){const x=new URLSearchParams;Object.entries(y).forEach(([D,O])=>{Array.isArray(O)?O.forEach(k=>x.append(D,String(k))):O!=null&&x.append(D,String(O))});const A=x.toString();_=A?`${d}?${A}`:d}S=v.trackRequest(_,f,{requestBody:f!=="GET"?y:void 0,dataSourceId:e.id}),v.trackDataSourceLoading(e.id)}try{let _;const x=e.auth_mode??(e.auth_required===!0?"required":"none"),A=Ar.getInstance().isAuthenticated();if(x==="required"&&!A){Ct.log(`[DataSourceManager] Skipping ${e.id}: auth_mode is 'required' but no token available`),v?.isEnabled()&&(v.trackDataSourceError(e.id,"Skipped: auth_mode required but not authenticated"),S&&v.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 D=x==="required"||x==="optional"&&A;if(D){const O=qr(),k=d.startsWith("/api/")?d.substring(4):d.startsWith("/api")?d.substring(4)||"/":d;this.options.onError&&Ct.log(`[DataSourceManager] Normalized endpoint: ${d} -> ${k}`);const L=this.getMatchingGlobalHeaders(d,c),B={};e.headers&&Object.entries(e.headers).forEach(([de,_e])=>{const Se=Fc(_e,c);Se!=null&&Se!==""&&(B[de]=String(Se))});const q={...L,...B},z=Object.keys(q).length>0,W=m?this.toFormData(y):y;switch(f){case"GET":_=await O.get(k,{params:y,...z&&{headers:q}});break;case"POST":z?_=await O.post(k,W,{headers:q}):_=await O.post(k,W);break;case"PUT":z?_=await O.put(k,W,{headers:q}):_=await O.put(k,W);break;case"PATCH":z?_=await O.patch(k,W,{headers:q}):_=await O.patch(k,W);break;case"DELETE":_=await O.delete(k,{params:y,...z&&{headers:q}});break;default:throw new Error(`Unsupported HTTP method: ${f}`)}}else{let O=d;if(f==="GET"){const W=new URLSearchParams(y).toString();O=W?`${d}?${W}`:d}const k={...m?{}:{"Content-Type":"application/json"},Accept:"application/json"};if(typeof window<"u"){const W=localStorage.getItem("g7_locale");W&&(k["Accept-Language"]=W)}const L=this.getMatchingGlobalHeaders(d,c);Object.assign(k,L),e.headers&&Object.entries(e.headers).forEach(([W,de])=>{const _e=Fc(de,c);_e!=null&&_e!==""&&(k[W]=String(_e))});let B;f!=="GET"&&(m?(B=this.toFormData(y),delete k["Content-Type"]):B=JSON.stringify(y));const q=await fetch(O,{method:f,headers:k,body:B});let z;try{z=await q.json()}catch{z=null}if(S&&v?.isEnabled()&&(v.completeRequest(S,q.status,z),S=null),!q.ok){v?.isEnabled()&&v.trackDataSourceError(e.id,`HTTP ${q.status}: ${q.statusText}`);const W=new Error(`HTTP error! status: ${q.status}`);throw W.response={status:q.status,statusText:q.statusText,data:z},W.status=q.status,W}_=z,v?.isEnabled()&&v.trackDataSourceLoaded(e.id,_)}return D&&S&&v?.isEnabled()&&(v.completeRequest(S,200,_),v.trackDataSourceLoaded(e.id,_)),_}catch(_){if(S&&v?.isEnabled()){const x=_;x?.response?v.completeRequest(S,x.response.status,x.response.data):v.failRequest(S,_ instanceof Error?_.message:String(_)),v.trackDataSourceError(e.id,_ instanceof Error?_.message:String(_))}throw _}}getCachedData(e){const n=this.dataCache.get(e);if(!n)return;if(Date.now()-n.timestamp>Qc.DATA_CACHE_TTL){this.dataCache.delete(e);return}return n.data}clearCache(){this.dataCache.clear()}subscribeWebSockets(e,n,r={}){const i=[],l=e.filter(c=>c.type==="websocket");return l.length===0||l.forEach(c=>{if(!c.channel||!c.event){Ct.warn(`WebSocket source ${c.id} missing channel or event`);return}let d,f;try{d=hs(c.channel,r,{skipCache:!0}),f=hs(c.event,r,{skipCache:!0})}catch(y){Ct.error(`Failed to resolve WebSocket channel/event for source ${c.id}:`,y);return}const h=y=>!!(!y||y.trim()===""||y.includes("{{")||y.endsWith(".")||y.endsWith(":")||y.startsWith(".")||y.startsWith(":")||y.includes("..")||y.includes("::"));if(h(d)||h(f)){Ct.warn(`WebSocket source ${c.id} has invalid channel/event after expression resolution, skipping. Original channel="${c.channel}", resolved="${d}". Original event="${c.event}", resolved="${f}". Available context keys: [${Object.keys(r).join(", ")}]`);return}const m=Gc.subscribe(d,f,y=>{const v=c.target_source||c.id;this.dataCache.set(v,{data:y,timestamp:Date.now()}),n(v,y)},{channelType:c.channel_type||"private"});m&&i.push(m)}),i}unsubscribeWebSockets(e){e.length!==0&&e.forEach(n=>{Gc.unsubscribe(n)})}async executeOnSuccessHandler(e,n){const r=this.options.actionDispatcher??Cy();if(!r){Ct.warn("ActionDispatcher not available, skipping onSuccess handler");return}const i=Array.isArray(e)?e:[e];for(const l of i)try{await r.dispatchAction({type:"click",...l},{data:{response:n}})}catch(c){throw Ct.error("Failed to execute onSuccess handler:",c),c}}};M(Qc,"DATA_CACHE_TTL",3e5);let Dr=Qc;const Gx=new Dr,ki=pt("ModalDataSourceWrapper");function Fx(s,e){if(!s||!e)return s;const r=e.replace(/\?\./g,".").split(/\.(?![^\[]*\])/).flatMap(l=>{const c=l.match(/^([^\[]*)((?:\[\d+\])*)$/);if(c){const[,d,f]=c,h=[];d&&h.push(d);const m=f.match(/\[\d+\]/g);return m&&h.push(...m),h}return[l]}).filter(l=>l!=="");let i=s;for(const l of r){if(i==null)return;if(l.startsWith("[")&&l.endsWith("]")){const c=parseInt(l.slice(1,-1),10);i=i[c]}else i=i[l]}return i}const xb=({isOpen:s,modalId:e,dataSources:n,dataContext:r,globalStateUpdater:i,bindingEngine:l,debug:c=!1,children:d})=>{const[f,h]=I.useState(!1),[m,y]=I.useState(!1),v=I.useRef(!1),S=I.useRef(null);S.current||(S.current=new Dr);const _=I.useCallback(async()=>{if(!(!n||n.length===0)&&S.current){h(!0);try{const x=r.route||{},A=new URLSearchParams(window.location.search),D=n.map(k=>{let L={...k};if(k.endpoint&&l){const B=l.resolveBindings(k.endpoint,r,{skipCache:!0});L.endpoint=B}if(k.params&&l){const B={};Object.entries(k.params).forEach(([q,z])=>{typeof z=="string"?B[q]=l.resolveBindings(z,r,{skipCache:!0}):B[q]=z}),L.params=B}return L});c&&ki.log(`[ModalDataSourceWrapper] Modal "${e}" fetching data sources:`,D.map(k=>({id:k.id,endpoint:k.endpoint})));const O=await S.current.fetchDataSourcesWithResults(D,x,A);i&&O.forEach(k=>{if(k.state==="success"&&k.data!==void 0){const L=D.find(B=>B.id===k.id);if(L?.initGlobal){const B=k.data?.data??k.data,q=Array.isArray(L.initGlobal)?L.initGlobal:[L.initGlobal];for(const z of q)if(typeof z=="string")i({[z]:B}),c&&ki.log(`[ModalDataSourceWrapper] Modal "${e}" initGlobal: ${k.id}.data -> _global.${z}`);else if(typeof z=="object"&&z.key){const{key:W,path:de}=z,_e=de?Fx(B,de):B;i({[W]:_e}),c&&ki.log(`Modal "${e}" initGlobal: ${k.id}.data${de?"."+de:""} -> _global.${W}`)}}}else k.state==="error"&&ki.error(`Modal "${e}" data source error:`,k.id,k.error)}),c&&ki.log(`Modal "${e}" data sources fetched successfully`)}catch(x){ki.error(`Modal "${e}" data source fetch error:`,x)}finally{h(!1),y(!0)}}},[n,r,i,l,e,c]);return I.useEffect(()=>{if(!n||n.length===0)return;const x=window.__templateApp;return x?.registerModalDataSources&&x.registerModalDataSources(e,n),()=>{x?.unregisterModalDataSources&&x.unregisterModalDataSources(e)}},[e,n]),I.useEffect(()=>{!s&&v.current&&(y(!1),c&&ki.log(`[ModalDataSourceWrapper] Modal "${e}" closed, reset fetch state`)),s&&!v.current&&n&&n.length>0&&!m&&_(),v.current=s},[s,n,m,_,e,c]),yt.jsx(yt.Fragment,{children:d})};class Vc extends Error{constructor(n,r,i={}){super(r);M(this,"code");M(this,"userMessageKey");M(this,"showStack");M(this,"icon");M(this,"recoverable");this.name="TemplateEngineError",this.code=n,this.userMessageKey=r,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(n,r){if(!r||!n)return this.userMessageKey;try{return r.translate(this.userMessageKey,n)}catch{return this.userMessageKey}}}class Vx extends Vc{constructor(){super("TEMPLATE_NOT_FOUND","$t:core.errors.template_not_found",{showStack:!1,icon:"fa-paint-brush",recoverable:!1}),this.name="TemplateNotFoundError"}}function Tb(s){if(s instanceof Vc)return s;if(s instanceof Error){const e=new Vc("TEMPLATE_INIT_ERROR",s.message||"$t:core.errors.template_init_error",{showStack:!0,icon:"fa-circle-exclamation",recoverable:!0});return e.stack=s.stack,e}return new Vc("TEMPLATE_INIT_ERROR","$t:core.errors.template_init_error",{showStack:!1,icon:"fa-circle-exclamation",recoverable:!0})}const Kx=pt("ErrorDisplay");class uh{static render(e,n){const r=document.getElementById(e);if(!r){Kx.error(`Container #${e} not found`);return}const i=n.debug&&n.showStack&&n.stackTrace,l=window.matchMedia("(prefers-color-scheme: dark)").matches,c={container:` + `,Jn.error("Error state rendered:",i,r)}getCurrentLayout(){return this.currentLayout}clear(){this.currentLayout=null,this.layoutCache.clear(),Jn.log("Layout data and cache cleared")}}const vA=dt("TranslationContext"),Ff=M.createContext(null),qc=({children:s,translationEngine:e,translationContext:n})=>{const r=M.useMemo(()=>(l,c)=>{if(c){const d="|"+Object.entries(c).map(([f,p])=>`${f}=${p}`).join("|");return e.translate(l,n,d)}return e.translate(l,n)},[e,n]),i=M.useMemo(()=>({translationEngine:e,translationContext:n,t:r}),[e,n,r]);return ft.jsx(Ff.Provider,{value:i,children:s})},Py=()=>{const s=M.useContext(Ff);return s||(vA.warn("TranslationProvider 외부에서 호출되었습니다. 키를 그대로 반환합니다."),{t:e=>e,translationEngine:null,translationContext:null})},Pa=dt("SlotContext"),SA={registerToSlot:()=>{Pa.warn("SlotContext not available: registerToSlot called outside SlotProvider")},unregisterFromSlot:()=>{Pa.warn("SlotContext not available: unregisterFromSlot called outside SlotProvider")},getSlotComponents:()=>[],subscribeToSlot:()=>()=>{},clearAllSlots:()=>{},isEnabled:!1},wA=M.createContext(SA),Vf=({children:s})=>{const e=M.useRef(new Map),n=M.useRef(new Map),r=M.useCallback(m=>{const y=n.current.get(m);y&&y.forEach(C=>{try{C()}catch(S){Pa.error(`Slot subscriber error (slotId: ${m}):`,S)}})},[]),i=M.useCallback((m,y,C)=>{if(!m||!y){Pa.warn("registerToSlot: slotId and componentId are required");return}e.current.has(m)||e.current.set(m,new Map);const S=e.current.get(m),v=S.get(y);v&&v.registrationKey===C.registrationKey||(S.set(y,C),Pa.log(`Component registered to slot: ${y} -> ${m} (order: ${C.order})`),r(m))},[r]),l=M.useCallback((m,y)=>{const C=e.current.get(m);C&&C.has(y)&&(C.delete(y),Pa.log(`Component unregistered from slot: ${y} <- ${m}`),C.size===0&&e.current.delete(m),r(m))},[r]),c=M.useCallback(m=>{const y=e.current.get(m);return y?Array.from(y.values()).sort((C,S)=>C.order-S.order):[]},[]),d=M.useCallback((m,y)=>{n.current.has(m)||n.current.set(m,new Set);const C=n.current.get(m);return C.add(y),()=>{C.delete(y),C.size===0&&n.current.delete(m)}},[]),f=M.useCallback(()=>{e.current.forEach((m,y)=>{r(y)}),e.current.clear(),n.current.clear(),Pa.log("All slots cleared")},[r]),p=M.useMemo(()=>({registerToSlot:i,unregisterFromSlot:l,getSlotComponents:c,subscribeToSlot:d,clearAllSlots:f,isEnabled:!0}),[i,l,c,d,f]);return M.useLayoutEffect(()=>{typeof window<"u"&&(window.__slotContextValue=p,Pa.log("SlotContext exposed to window.__slotContextValue"))},[p]),ft.jsx(wA.Provider,{value:p,children:s})};class Kf{constructor(){this.notificationCreatedEvent=".Illuminate\\Notifications\\Events\\BroadcastNotificationCreated"}listenForWhisper(e,n){return this.listen(".client-"+e,n)}notification(e){return this.listen(this.notificationCreatedEvent,e)}stopListeningForNotification(e){return this.stopListening(this.notificationCreatedEvent,e)}stopListeningForWhisper(e,n){return this.stopListening(".client-"+e,n)}}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 CA(s){try{new s}catch(e){if(e instanceof Error&&e.message.includes("is not a constructor"))return!1}return!0}class Wf extends Kf{constructor(e,n,r){super(),this.name=n,this.pusher=e,this.options=r,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,n){return this.on(this.eventFormatter.format(e),n),this}listenToAll(e){return this.subscription.bind_global((n,r)=>{if(n.startsWith("pusher:"))return;let i=String(this.options.namespace??"").replace(/\./g,"\\"),l=n.startsWith(i)?n.substring(i.length+1):"."+n;e(l,r)}),this}stopListening(e,n){return n?this.subscription.unbind(this.eventFormatter.format(e),n):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",n=>{e(n)}),this}on(e,n){return this.subscription.bind(e,n),this}}class qy extends Wf{whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}}class EA extends Wf{whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}}class _A extends qy{here(e){return this.on("pusher:subscription_succeeded",n=>{e(Object.keys(n.members).map(r=>n.members[r]))}),this}joining(e){return this.on("pusher:member_added",n=>{e(n.info)}),this}whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}leaving(e){return this.on("pusher:member_removed",n=>{e(n.info)}),this}}class Gy extends Kf{constructor(e,n,r){super(),this.events={},this.listeners={},this.name=n,this.socket=e,this.options=r,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,n){return this.on(this.eventFormatter.format(e),n),this}stopListening(e,n){return this.unbindEvent(this.eventFormatter.format(e),n),this}subscribed(e){return this.on("connect",n=>{e(n)}),this}error(e){return this}on(e,n){return this.listeners[e]=this.listeners[e]||[],this.events[e]||(this.events[e]=(r,i)=>{this.name===r&&this.listeners[e]&&this.listeners[e].forEach(l=>l(i))},this.socket.on(e,this.events[e])),this.listeners[e].push(n),this}unbind(){Object.keys(this.events).forEach(e=>{this.unbindEvent(e)})}unbindEvent(e,n){this.listeners[e]=this.listeners[e]||[],n&&(this.listeners[e]=this.listeners[e].filter(r=>r!==n)),(!n||this.listeners[e].length===0)&&(this.events[e]&&(this.socket.removeListener(e,this.events[e]),delete this.events[e]),delete this.listeners[e])}}class Fy extends Gy{whisper(e,n){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:n}),this}}class AA extends Fy{here(e){return this.on("presence:subscribed",n=>{e(n.map(r=>r.user_info))}),this}joining(e){return this.on("presence:joining",n=>e(n.user_info)),this}whisper(e,n){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:n}),this}leaving(e){return this.on("presence:leaving",n=>e(n.user_info)),this}}class Gc extends Kf{subscribe(){}unsubscribe(){}listen(e,n){return this}listenToAll(e){return this}stopListening(e,n){return this}subscribed(e){return this}error(e){return this}on(e,n){return this}}class Vy extends Gc{whisper(e,n){return this}}class xA extends Gc{whisper(e,n){return this}}class TA extends Vy{here(e){return this}joining(e){return this}whisper(e,n){return this}leaving(e){return this}}const Ky=class Ow{constructor(e){this.setOptions(e),this.connect()}setOptions(e){this.options={...Ow._defaultOptions,...e,broadcaster:e.broadcaster};let n=this.csrfToken();n&&(this.options.auth.headers["X-CSRF-TOKEN"]=n,this.options.userAuthentication.headers["X-CSRF-TOKEN"]=n),n=this.options.bearerToken,n&&(this.options.auth.headers.Authorization="Bearer "+n,this.options.userAuthentication.headers.Authorization="Bearer "+n)}csrfToken(){var e,n;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"?((n=document.querySelector('meta[name="csrf-token"]'))==null?void 0:n.getAttribute("content"))??null:null}};Ky._defaultOptions={auth:{headers:{}},authEndpoint:"/broadcasting/auth",userAuthentication:{endpoint:"/broadcasting/user-auth",headers:{}},csrfToken:null,bearerToken:null,host:null,key:null,namespace:"App.Events"};let Yf=Ky;class Fc extends Yf{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,n,r){return this.channel(e).listen(n,r)}channel(e){return this.channels[e]||(this.channels[e]=new Wf(this.pusher,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new qy(this.pusher,"private-"+e,this.options)),this.channels["private-"+e]}encryptedPrivateChannel(e){return this.channels["private-encrypted-"+e]||(this.channels["private-encrypted-"+e]=new EA(this.pusher,"private-encrypted-"+e,this.options)),this.channels["private-encrypted-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new _A(this.pusher,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"private-encrypted-"+e,"presence-"+e].forEach(n=>{this.leaveChannel(n)})}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 kA extends Yf{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(n=>{n.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,n,r){return this.channel(e).listen(n,r)}channel(e){return this.channels[e]||(this.channels[e]=new Gy(this.socket,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new Fy(this.socket,"private-"+e,this.options)),this.channels["private-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new AA(this.socket,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"presence-"+e].forEach(n=>{this.leaveChannel(n)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.socket.id}disconnect(){this.socket.disconnect()}}class Wy extends Yf{constructor(){super(...arguments),this.channels={}}connect(){}listen(e,n,r){return new Gc}channel(e){return new Gc}privateChannel(e){return new Vy}encryptedPrivateChannel(e){return new xA}presenceChannel(e){return new TA}leave(e){}leaveChannel(e){}socketId(){return"fake-socket-id"}disconnect(){}}class RA{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 Fc({...this.options,cluster:""});else if(this.options.broadcaster==="pusher")this.connector=new Fc(this.options);else if(this.options.broadcaster==="ably")this.connector=new Fc({...this.options,cluster:"",broadcaster:"pusher"});else if(this.options.broadcaster==="socket.io")this.connector=new kA(this.options);else if(this.options.broadcaster==="null")this.connector=new Wy(this.options);else if(typeof this.options.broadcaster=="function"&&CA(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,n,r){return this.connector.listen(e,n,r)}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 Fc||e instanceof Wy}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,n)=>{this.socketId()&&e.headers.set("X-Socket-ID",this.socketId()),n()})}registerAxiosRequestInterceptor(){axios.interceptors.request.use(e=>(this.socketId()&&(e.headers["X-Socket-Id"]=this.socketId()),e))}registerjQueryAjaxSetup(){typeof jQuery.ajax<"u"&&jQuery.ajaxPrefilter((e,n,r)=>{this.socketId()&&r.setRequestHeader("X-Socket-Id",this.socketId())})}registerTurboRequestInterceptor(){document.addEventListener("turbo:before-fetch-request",e=>{e.detail.fetchOptions.headers["X-Socket-Id"]=this.socketId()})}}var Xf={exports:{}};/*! + * Pusher JavaScript Library v8.4.0 + * https://pusher.com/ + * + * Copyright 2020, Pusher + * Released under the MIT licence. + */var Yy;function DA(){return Yy||(Yy=1,(function(s,e){(function(r,i){s.exports=i()})(window,function(){return(function(n){var r={};function i(l){if(r[l])return r[l].exports;var c=r[l]={i:l,l:!1,exports:{}};return n[l].call(c.exports,c,c.exports,i),c.l=!0,c.exports}return i.m=n,i.c=r,i.d=function(l,c,d){i.o(l,c)||Object.defineProperty(l,c,{enumerable:!0,get:d})},i.r=function(l){typeof Symbol<"u"&&Symbol.toStringTag&&Object.defineProperty(l,Symbol.toStringTag,{value:"Module"}),Object.defineProperty(l,"__esModule",{value:!0})},i.t=function(l,c){if(c&1&&(l=i(l)),c&8||c&4&&typeof l=="object"&&l&&l.__esModule)return l;var d=Object.create(null);if(i.r(d),Object.defineProperty(d,"default",{enumerable:!0,value:l}),c&2&&typeof l!="string")for(var f in l)i.d(d,f,function(p){return l[p]}.bind(null,f));return d},i.n=function(l){var c=l&&l.__esModule?function(){return l.default}:function(){return l};return i.d(c,"a",c),c},i.o=function(l,c){return Object.prototype.hasOwnProperty.call(l,c)},i.p="",i(i.s=2)})([(function(n,r,i){var l=this&&this.__extends||(function(){var x=function(w,R){return x=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(L,O){L.__proto__=O}||function(L,O){for(var j in O)O.hasOwnProperty(j)&&(L[j]=O[j])},x(w,R)};return function(w,R){x(w,R);function L(){this.constructor=w}w.prototype=R===null?Object.create(R):(L.prototype=R.prototype,new L)}})();Object.defineProperty(r,"__esModule",{value:!0});var c=256,d=(function(){function x(w){w===void 0&&(w="="),this._paddingCharacter=w}return x.prototype.encodedLength=function(w){return this._paddingCharacter?(w+2)/3*4|0:(w*8+5)/6|0},x.prototype.encode=function(w){for(var R="",L=0;L>>18&63),R+=this._encodeByte(O>>>12&63),R+=this._encodeByte(O>>>6&63),R+=this._encodeByte(O>>>0&63)}var j=w.length-L;if(j>0){var O=w[L]<<16|(j===2?w[L+1]<<8:0);R+=this._encodeByte(O>>>18&63),R+=this._encodeByte(O>>>12&63),j===2?R+=this._encodeByte(O>>>6&63):R+=this._paddingCharacter||"",R+=this._paddingCharacter||""}return R},x.prototype.maxDecodedLength=function(w){return this._paddingCharacter?w/4*3|0:(w*6+7)/8|0},x.prototype.decodedLength=function(w){return this.maxDecodedLength(w.length-this._getPaddingLength(w))},x.prototype.decode=function(w){if(w.length===0)return new Uint8Array(0);for(var R=this._getPaddingLength(w),L=w.length-R,O=new Uint8Array(this.maxDecodedLength(L)),j=0,F=0,G=0,P=0,K=0,he=0,Ee=0;F>>4,O[j++]=K<<4|he>>>2,O[j++]=he<<6|Ee,G|=P&c,G|=K&c,G|=he&c,G|=Ee&c;if(F>>4,G|=P&c,G|=K&c),F>>2,G|=he&c),F>>8&6,R+=51-w>>>8&-75,R+=61-w>>>8&-15,R+=62-w>>>8&3,String.fromCharCode(R)},x.prototype._decodeChar=function(w){var R=c;return R+=(42-w&w-44)>>>8&-c+w-43+62,R+=(46-w&w-48)>>>8&-c+w-47+63,R+=(47-w&w-58)>>>8&-c+w-48+52,R+=(64-w&w-91)>>>8&-c+w-65+0,R+=(96-w&w-123)>>>8&-c+w-97+26,R},x.prototype._getPaddingLength=function(w){var R=0;if(this._paddingCharacter){for(var L=w.length-1;L>=0&&w[L]===this._paddingCharacter;L--)R++;if(w.length<4||R>2)throw new Error("Base64Coder: incorrect padding")}return R},x})();r.Coder=d;var f=new d;function p(x){return f.encode(x)}r.encode=p;function m(x){return f.decode(x)}r.decode=m;var y=(function(x){l(w,x);function w(){return x!==null&&x.apply(this,arguments)||this}return w.prototype._encodeByte=function(R){var L=R;return L+=65,L+=25-R>>>8&6,L+=51-R>>>8&-75,L+=61-R>>>8&-13,L+=62-R>>>8&49,String.fromCharCode(L)},w.prototype._decodeChar=function(R){var L=c;return L+=(44-R&R-46)>>>8&-c+R-45+62,L+=(94-R&R-96)>>>8&-c+R-95+63,L+=(47-R&R-58)>>>8&-c+R-48+52,L+=(64-R&R-91)>>>8&-c+R-65+0,L+=(96-R&R-123)>>>8&-c+R-97+26,L},w})(d);r.URLSafeCoder=y;var C=new y;function S(x){return C.encode(x)}r.encodeURLSafe=S;function v(x){return C.decode(x)}r.decodeURLSafe=v,r.encodedLength=function(x){return f.encodedLength(x)},r.maxDecodedLength=function(x){return f.maxDecodedLength(x)},r.decodedLength=function(x){return f.decodedLength(x)}}),(function(n,r,i){Object.defineProperty(r,"__esModule",{value:!0});var l="utf8: invalid string",c="utf8: invalid source encoding";function d(m){for(var y=new Uint8Array(f(m)),C=0,S=0;S>6,y[C++]=128|v&63):v<55296?(y[C++]=224|v>>12,y[C++]=128|v>>6&63,y[C++]=128|v&63):(S++,v=(v&1023)<<10,v|=m.charCodeAt(S)&1023,v+=65536,y[C++]=240|v>>18,y[C++]=128|v>>12&63,y[C++]=128|v>>6&63,y[C++]=128|v&63)}return y}r.encode=d;function f(m){for(var y=0,C=0;C=m.length-1)throw new Error(l);C++,y+=4}else throw new Error(l)}return y}r.encodedLength=f;function p(m){for(var y=[],C=0;C=m.length)throw new Error(c);var x=m[++C];if((x&192)!==128)throw new Error(c);S=(S&31)<<6|x&63,v=128}else if(S<240){if(C>=m.length-1)throw new Error(c);var x=m[++C],w=m[++C];if((x&192)!==128||(w&192)!==128)throw new Error(c);S=(S&15)<<12|(x&63)<<6|w&63,v=2048}else if(S<248){if(C>=m.length-2)throw new Error(c);var x=m[++C],w=m[++C],R=m[++C];if((x&192)!==128||(w&192)!==128||(R&192)!==128)throw new Error(c);S=(S&15)<<18|(x&63)<<12|(w&63)<<6|R&63,v=65536}else throw new Error(c);if(S=55296&&S<=57343)throw new Error(c);if(S>=65536){if(S>1114111)throw new Error(c);S-=65536,y.push(String.fromCharCode(55296|S>>10)),S=56320|S&1023}}y.push(String.fromCharCode(S))}return y.join("")}r.decode=p}),(function(n,r,i){n.exports=i(3).default}),(function(n,r,i){i.r(r);class l{constructor(b,_){this.lastId=0,this.prefix=b,this.name=_}create(b){this.lastId++;var _=this.lastId,D=this.prefix+_,I=this.name+"["+_+"]",ie=!1,ye=function(){ie||(b.apply(null,arguments),ie=!0)};return this[_]=ye,{number:_,id:D,name:I,callback:ye}}remove(b){delete this[b.number]}}var c=new l("_pusher_script_","Pusher.ScriptReceivers"),d={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:""},f=d;class p{constructor(b){this.options=b,this.receivers=b.receivers||c,this.loading={}}load(b,_,D){var I=this;if(I.loading[b]&&I.loading[b].length>0)I.loading[b].push(D);else{I.loading[b]=[D];var ie=Fe.createScriptRequest(I.getPath(b,_)),ye=I.receivers.create(function(Oe){if(I.receivers.remove(ye),I.loading[b]){var Ve=I.loading[b];delete I.loading[b];for(var it=function(Bt){Bt||ie.cleanup()},ct=0;ct>>6)+ze(128|b&63):ze(224|b>>>12&15)+ze(128|b>>>6&63)+ze(128|b&63)},bt=function(A){return A.replace(/[^\x00-\x7F]/g,je)},X=function(A){var b=[0,2,1][A.length%3],_=A.charCodeAt(0)<<16|(A.length>1?A.charCodeAt(1):0)<<8|(A.length>2?A.charCodeAt(2):0),D=[Be.charAt(_>>>18),Be.charAt(_>>>12&63),b>=2?"=":Be.charAt(_>>>6&63),b>=1?"=":Be.charAt(_&63)];return D.join("")},de=window.btoa||function(A){return A.replace(/[\s\S]{1,3}/g,X)};class Ce{constructor(b,_,D,I){this.clear=_,this.timer=b(()=>{this.timer&&(this.timer=I(this.timer))},D)}isRunning(){return this.timer!==null}ensureAborted(){this.timer&&(this.clear(this.timer),this.timer=null)}}var Z=Ce;function ge(A){window.clearTimeout(A)}function z(A){window.clearInterval(A)}class T extends Z{constructor(b,_){super(setTimeout,ge,b,function(D){return _(),null})}}class pe extends Z{constructor(b,_){super(setInterval,z,b,function(D){return _(),D})}}var fe={now(){return Date.now?Date.now():new Date().valueOf()},defer(A){return new T(0,A)},method(A,...b){var _=Array.prototype.slice.call(arguments,1);return function(D){return D[A].apply(D,_.concat(arguments))}}},me=fe;function ae(A,...b){for(var _=0;_{window.console&&window.console.log&&window.console.log(b)}}debug(...b){this.log(this.globalLog,b)}warn(...b){this.log(this.globalLogWarn,b)}error(...b){this.log(this.globalLogError,b)}globalLogWarn(b){window.console&&window.console.warn?window.console.warn(b):this.globalLog(b)}globalLogError(b){window.console&&window.console.error?window.console.error(b):this.globalLogWarn(b)}log(b,..._){var D=Re.apply(this,arguments);hl.log?hl.log(D):hl.logToConsole&&b.bind(this)(D)}}var St=new Pt,da=function(A,b,_,D,I){(_.headers!==void 0||_.headersProvider!=null)&&St.warn(`To send headers with the ${D.toString()} request, you must use AJAX, rather than JSONP.`);var ie=A.nextAuthCallbackID.toString();A.nextAuthCallbackID++;var ye=A.getDocument(),Oe=ye.createElement("script");A.auth_callbacks[ie]=function(ct){I(null,ct)};var Ve="Pusher.auth_callbacks['"+ie+"']";Oe.src=_.endpoint+"?callback="+encodeURIComponent(Ve)+"&"+b;var it=ye.getElementsByTagName("head")[0]||ye.documentElement;it.insertBefore(Oe,it.firstChild)},In=da;class kn{constructor(b){this.src=b}send(b){var _=this,D="Error loading "+_.src;_.script=document.createElement("script"),_.script.id=b.id,_.script.src=_.src,_.script.type="text/javascript",_.script.charset="UTF-8",_.script.addEventListener?(_.script.onerror=function(){b.callback(D)},_.script.onload=function(){b.callback(null)}):_.script.onreadystatechange=function(){(_.script.readyState==="loaded"||_.script.readyState==="complete")&&b.callback(null)},_.script.async===void 0&&document.attachEvent&&/opera/i.test(navigator.userAgent)?(_.errorScript=document.createElement("script"),_.errorScript.id=b.id+"_error",_.errorScript.text=b.name+"('"+D+"');",_.script.async=_.errorScript.async=!1):_.script.async=!0;var I=document.getElementsByTagName("head")[0];I.insertBefore(_.script,I.firstChild),_.errorScript&&I.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 Rn{constructor(b,_){this.url=b,this.data=_}send(b){if(!this.request){var _=pn(this.data),D=this.url+"/"+b.number+"?"+_;this.request=Fe.createScriptRequest(D),this.request.send(b)}}cleanup(){this.request&&this.request.cleanup()}}var jn=function(A,b){return function(_,D){var I="http"+(b?"s":"")+"://",ie=I+(A.host||A.options.host)+A.options.path,ye=Fe.createJSONPRequest(ie,_),Oe=Fe.ScriptReceivers.create(function(Ve,it){c.remove(Oe),ye.cleanup(),it&&it.host&&(A.host=it.host),D&&D(Ve,it)});ye.send(Oe)}},gn={name:"jsonp",getAgent:jn},fa=gn;function zn(A,b,_){var D=A+(b.useTLS?"s":""),I=b.useTLS?b.hostTLS:b.hostNonTLS;return D+"://"+I+_}function Vt(A,b){var _="/app/"+A,D="?protocol="+f.PROTOCOL+"&client=js&version="+f.VERSION+(b?"&"+b:"");return _+D}var _n={getInitial:function(A,b){var _=(b.httpPath||"")+Vt(A,"flash=false");return zn("ws",b,_)}},an={getInitial:function(A,b){var _=(b.httpPath||"/pusher")+Vt(A);return zn("http",b,_)}},q={getInitial:function(A,b){return zn("http",b,b.httpPath||"/pusher")},getPath:function(A,b){return Vt(A)}};class oe{constructor(){this._callbacks={}}get(b){return this._callbacks[ce(b)]}add(b,_,D){var I=ce(b);this._callbacks[I]=this._callbacks[I]||[],this._callbacks[I].push({fn:_,context:D})}remove(b,_,D){if(!b&&!_&&!D){this._callbacks={};return}var I=b?[ce(b)]:Ge(this._callbacks);_||D?this.removeCallback(I,_,D):this.removeAllCallbacks(I)}removeCallback(b,_,D){vt(b,function(I){this._callbacks[I]=Xt(this._callbacks[I]||[],function(ie){return _&&_!==ie.fn||D&&D!==ie.context}),this._callbacks[I].length===0&&delete this._callbacks[I]},this)}removeAllCallbacks(b){vt(b,function(_){delete this._callbacks[_]},this)}}function ce(A){return"_"+A}class J{constructor(b){this.callbacks=new oe,this.global_callbacks=[],this.failThrough=b}bind(b,_,D){return this.callbacks.add(b,_,D),this}bind_global(b){return this.global_callbacks.push(b),this}unbind(b,_,D){return this.callbacks.remove(b,_,D),this}unbind_global(b){return b?(this.global_callbacks=Xt(this.global_callbacks||[],_=>_!==b),this):(this.global_callbacks=[],this)}unbind_all(){return this.unbind(),this.unbind_global(),this}emit(b,_,D){for(var I=0;I0)for(var I=0;I{this.onError(_),this.changeState("closed")}),!1}return this.bindListeners(),St.debug("Connecting",{transport:this.name,url:b}),this.changeState("connecting"),!0}close(){return this.socket?(this.socket.close(),!0):!1}send(b){return this.state==="open"?(me.defer(()=>{this.socket&&this.socket.send(b)}),!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(b){this.emit("error",{type:"WebSocketError",error:b}),this.timeline.error(this.buildTimelineMessage({error:b.toString()}))}onClose(b){b?this.changeState("closed",{code:b.code,reason:b.reason,wasClean:b.wasClean}):this.changeState("closed"),this.unbindListeners(),this.socket=void 0}onMessage(b){this.emit("message",b)}onActivity(){this.emit("activity")}bindListeners(){this.socket.onopen=()=>{this.onOpen()},this.socket.onerror=b=>{this.onError(b)},this.socket.onclose=b=>{this.onClose(b)},this.socket.onmessage=b=>{this.onMessage(b)},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(b,_){this.state=b,this.timeline.info(this.buildTimelineMessage({state:b,params:_})),this.emit(b,_)}buildTimelineMessage(b){return ae({cid:this.id},b)}}class ue{constructor(b){this.hooks=b}isSupported(b){return this.hooks.isSupported(b)}createConnection(b,_,D,I){return new ve(this.hooks,b,_,D,I)}}var we=new ue({urls:_n,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return!!Fe.getWebSocketAPI()},isSupported:function(){return!!Fe.getWebSocketAPI()},getSocket:function(A){return Fe.createWebSocket(A)}}),_e={urls:an,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},qe=ae({getSocket:function(A){return Fe.HTTPFactory.createStreamingSocket(A)}},_e),xe=ae({getSocket:function(A){return Fe.HTTPFactory.createPollingSocket(A)}},_e),De={isSupported:function(){return Fe.isXHRSupported()}},Ae=new ue(ae({},qe,De)),tt=new ue(ae({},xe,De)),Ne={ws:we,xhr_streaming:Ae,xhr_polling:tt},He=Ne,Se=new ue({file:"sockjs",urls:q,handlesActivityChecks:!0,supportsPing:!1,isSupported:function(){return!0},isInitialized:function(){return window.SockJS!==void 0},getSocket:function(A,b){return new window.SockJS(A,null,{js_path:y.getPath("sockjs",{useTLS:b.useTLS}),ignore_null_origin:b.ignoreNullOrigin})},beforeOpen:function(A,b){A.send(JSON.stringify({path:b}))}}),$e={isSupported:function(A){var b=Fe.isXDRSupported(A.useTLS);return b}},et=new ue(ae({},qe,$e)),Ot=new ue(ae({},xe,$e));He.xdr_streaming=et,He.xdr_polling=Ot,He.sockjs=Se;var Mt=He;class Hn extends J{constructor(){super();var b=this;window.addEventListener!==void 0&&(window.addEventListener("online",function(){b.emit("online")},!1),window.addEventListener("offline",function(){b.emit("offline")},!1))}isOnline(){return window.navigator.onLine===void 0?!0:window.navigator.onLine}}var It=new Hn;class jt{constructor(b,_,D){this.manager=b,this.transport=_,this.minPingDelay=D.minPingDelay,this.maxPingDelay=D.maxPingDelay,this.pingDelay=void 0}createConnection(b,_,D,I){I=ae({},I,{activityTimeout:this.pingDelay});var ie=this.transport.createConnection(b,_,D,I),ye=null,Oe=function(){ie.unbind("open",Oe),ie.bind("closed",Ve),ye=me.now()},Ve=it=>{if(ie.unbind("closed",Ve),it.code===1002||it.code===1003)this.manager.reportDeath();else if(!it.wasClean&&ye){var ct=me.now()-ye;ct<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(ct/2,this.minPingDelay))}};return ie.bind("open",Oe),ie}isSupported(b){return this.manager.isAlive()&&this.transport.isSupported(b)}}const mn={decodeMessage:function(A){try{var b=JSON.parse(A.data),_=b.data;if(typeof _=="string")try{_=JSON.parse(b.data)}catch{}var D={event:b.event,channel:b.channel,data:_};return b.user_id&&(D.user_id=b.user_id),D}catch(I){throw{type:"MessageParseError",error:I,data:A.data}}},encodeMessage:function(A){return JSON.stringify(A)},processHandshake:function(A){var b=mn.decodeMessage(A);if(b.event==="pusher:connection_established"){if(!b.data.activity_timeout)throw"No activity timeout specified in handshake";return{action:"connected",id:b.data.socket_id,activityTimeout:b.data.activity_timeout*1e3}}else{if(b.event==="pusher:error")return{action:this.getCloseAction(b.data),error:this.getCloseError(b.data)};throw"Invalid handshake"}},getCloseAction:function(A){return A.code<4e3?A.code>=1002&&A.code<=1004?"backoff":null:A.code===4e3?"tls_only":A.code<4100?"refused":A.code<4200?"backoff":A.code<4300?"retry":"refused"},getCloseError:function(A){return A.code!==1e3&&A.code!==1001?{type:"PusherError",data:{code:A.code,message:A.reason||A.message}}:null}};var Un=mn;class Jo extends J{constructor(b,_){super(),this.id=b,this.transport=_,this.activityTimeout=_.activityTimeout,this.bindListeners()}handlesActivityChecks(){return this.transport.handlesActivityChecks()}send(b){return this.transport.send(b)}send_event(b,_,D){var I={event:b,data:_};return D&&(I.channel=D),St.debug("Event sent",I),this.send(Un.encodeMessage(I))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var b={message:D=>{var I;try{I=Un.decodeMessage(D)}catch(ie){this.emit("error",{type:"MessageParseError",error:ie,data:D.data})}if(I!==void 0){switch(St.debug("Event recd",I),I.event){case"pusher:error":this.emit("error",{type:"PusherError",data:I.data});break;case"pusher:ping":this.emit("ping");break;case"pusher:pong":this.emit("pong");break}this.emit("message",I)}},activity:()=>{this.emit("activity")},error:D=>{this.emit("error",D)},closed:D=>{_(),D&&D.code&&this.handleCloseEvent(D),this.transport=null,this.emit("closed")}},_=()=>{Me(b,(D,I)=>{this.transport.unbind(I,D)})};Me(b,(D,I)=>{this.transport.bind(I,D)})}handleCloseEvent(b){var _=Un.getCloseAction(b),D=Un.getCloseError(b);D&&this.emit("error",D),_&&this.emit(_,{action:_,error:D})}}class rh{constructor(b,_){this.transport=b,this.callback=_,this.bindListeners()}close(){this.unbindListeners(),this.transport.close()}bindListeners(){this.onMessage=b=>{this.unbindListeners();var _;try{_=Un.processHandshake(b)}catch(D){this.finish("error",{error:D}),this.transport.close();return}_.action==="connected"?this.finish("connected",{connection:new Jo(_.id,this.transport),activityTimeout:_.activityTimeout}):(this.finish(_.action,{error:_.error}),this.transport.close())},this.onClosed=b=>{this.unbindListeners();var _=Un.getCloseAction(b)||"backoff",D=Un.getCloseError(b);this.finish(_,{error:D})},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(b,_){this.callback(ae({transport:this.transport,action:b},_))}}class ah{constructor(b,_){this.timeline=b,this.options=_||{}}send(b,_){this.timeline.isEmpty()||this.timeline.send(Fe.TimelineTransport.getAgent(this,b),_)}}class As extends J{constructor(b,_){super(function(D,I){St.debug("No callbacks on "+b+" for "+D)}),this.name=b,this.pusher=_,this.subscribed=!1,this.subscriptionPending=!1,this.subscriptionCancelled=!1}authorize(b,_){return _(null,{auth:""})}trigger(b,_){if(b.indexOf("client-")!==0)throw new w("Event '"+b+"' does not start with 'client-'");if(!this.subscribed){var D=v.buildLogSuffix("triggeringClientEvents");St.warn(`Client event triggered before channel 'subscription_succeeded' event . ${D}`)}return this.pusher.send_event(b,_,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(b){var _=b.event,D=b.data;if(_==="pusher_internal:subscription_succeeded")this.handleSubscriptionSucceededEvent(b);else if(_==="pusher_internal:subscription_count")this.handleSubscriptionCountEvent(b);else if(_.indexOf("pusher_internal:")!==0){var I={};this.emit(_,D,I)}}handleSubscriptionSucceededEvent(b){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):this.emit("pusher:subscription_succeeded",b.data)}handleSubscriptionCountEvent(b){b.data.subscription_count&&(this.subscriptionCount=b.data.subscription_count),this.emit("pusher:subscription_count",b.data)}subscribe(){this.subscribed||(this.subscriptionPending=!0,this.subscriptionCancelled=!1,this.authorize(this.pusher.connection.socket_id,(b,_)=>{b?(this.subscriptionPending=!1,St.error(b.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:b.message},b instanceof K?{status:b.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 ha extends As{authorize(b,_){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:b},_)}}class Qo{constructor(){this.reset()}get(b){return Object.prototype.hasOwnProperty.call(this.members,b)?{id:b,info:this.members[b]}:null}each(b){Me(this.members,(_,D)=>{b(this.get(D))})}setMyID(b){this.myID=b}onSubscription(b){this.members=b.presence.hash,this.count=b.presence.count,this.me=this.get(this.myID)}addMember(b){return this.get(b.user_id)===null&&this.count++,this.members[b.user_id]=b.user_info,this.get(b.user_id)}removeMember(b){var _=this.get(b.user_id);return _&&(delete this.members[b.user_id],this.count--),_}reset(){this.members={},this.count=0,this.myID=null,this.me=null}}var qa=function(A,b,_,D){function I(ie){return ie instanceof _?ie:new _(function(ye){ye(ie)})}return new(_||(_=Promise))(function(ie,ye){function Oe(ct){try{it(D.next(ct))}catch(Bt){ye(Bt)}}function Ve(ct){try{it(D.throw(ct))}catch(Bt){ye(Bt)}}function it(ct){ct.done?ie(ct.value):I(ct.value).then(Oe,Ve)}it((D=D.apply(A,b||[])).next())})};class Ga extends ha{constructor(b,_){super(b,_),this.members=new Qo}authorize(b,_){super.authorize(b,(D,I)=>qa(this,void 0,void 0,function*(){if(!D)if(I=I,I.channel_data!=null){var ie=JSON.parse(I.channel_data);this.members.setMyID(ie.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 ye=v.buildLogSuffix("authorizationEndpoint");St.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${ye}, or the user should be signed in.`),_("Invalid auth response");return}_(D,I)}))}handleEvent(b){var _=b.event;if(_.indexOf("pusher_internal:")===0)this.handleInternalEvent(b);else{var D=b.data,I={};b.user_id&&(I.user_id=b.user_id),this.emit(_,D,I)}}handleInternalEvent(b){var _=b.event,D=b.data;switch(_){case"pusher_internal:subscription_succeeded":this.handleSubscriptionSucceededEvent(b);break;case"pusher_internal:subscription_count":this.handleSubscriptionCountEvent(b);break;case"pusher_internal:member_added":var I=this.members.addMember(D);this.emit("pusher:member_added",I);break;case"pusher_internal:member_removed":var ie=this.members.removeMember(D);ie&&this.emit("pusher:member_removed",ie);break}}handleSubscriptionSucceededEvent(b){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):(this.members.onSubscription(b.data),this.emit("pusher:subscription_succeeded",this.members))}disconnect(){this.members.reset(),super.disconnect()}}var Mi=i(1),Yr=i(0);class Jt extends ha{constructor(b,_,D){super(b,_),this.key=null,this.nacl=D}authorize(b,_){super.authorize(b,(D,I)=>{if(D){_(D,I);return}let ie=I.shared_secret;if(!ie){_(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null);return}this.key=Object(Yr.decode)(ie),delete I.shared_secret,_(null,I)})}trigger(b,_){throw new F("Client events are not currently supported for encrypted channels")}handleEvent(b){var _=b.event,D=b.data;if(_.indexOf("pusher_internal:")===0||_.indexOf("pusher:")===0){super.handleEvent(b);return}this.handleEncryptedEvent(_,D)}handleEncryptedEvent(b,_){if(!this.key){St.debug("Received encrypted event before key has been retrieved from the authEndpoint");return}if(!_.ciphertext||!_.nonce){St.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+_);return}let D=Object(Yr.decode)(_.ciphertext);if(D.length{if(ye){St.error(`Failed to make a request to the authEndpoint: ${Oe}. Unable to fetch new key, so dropping encrypted event`);return}if(ie=this.nacl.secretbox.open(D,I,this.key),ie===null){St.error("Failed to decrypt event with new key. Dropping encrypted event");return}this.emit(b,this.getDataToEmit(ie))});return}this.emit(b,this.getDataToEmit(ie))}getDataToEmit(b){let _=Object(Mi.decode)(b);try{return JSON.parse(_)}catch{return _}}}class eu extends J{constructor(b,_){super(),this.state="initialized",this.connection=null,this.key=b,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 D=Fe.getNetwork();D.bind("online",()=>{this.timeline.info({netinfo:"online"}),(this.state==="connecting"||this.state==="unavailable")&&this.retryIn(0)}),D.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(b){return this.connection?this.connection.send(b):!1}send_event(b,_,D){return this.connection?this.connection.send_event(b,_,D):!1}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var b=(_,D)=>{_?this.runner=this.strategy.connect(0,b):D.action==="error"?(this.emit("error",{type:"HandshakeError",error:D.error}),this.timeline.error({handshakeError:D.error})):(this.abortConnecting(),this.handshakeCallbacks[D.action](D))};this.runner=this.strategy.connect(0,b)}abortConnecting(){this.runner&&(this.runner.abort(),this.runner=null)}disconnectInternally(){if(this.abortConnecting(),this.clearRetryTimer(),this.clearUnavailableTimer(),this.connection){var b=this.abandonConnection();b.close()}}updateStrategy(){this.strategy=this.options.getStrategy({key:this.key,timeline:this.timeline,useTLS:this.usingTLS})}retryIn(b){this.timeline.info({action:"retry",delay:b}),b>0&&this.emit("connecting_in",Math.round(b/1e3)),this.retryTimer=new T(b||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new T(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new T(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 T(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(b){return ae({},b,{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(b){return ae({},b,{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 b=_=>D=>{D.error&&this.emit("error",{type:"WebSocketError",error:D.error}),_(D)};return{tls_only:b(()=>{this.usingTLS=!0,this.updateStrategy(),this.retryIn(0)}),refused:b(()=>{this.disconnect()}),backoff:b(()=>{this.retryIn(1e3)}),retry:b(()=>{this.retryIn(0)})}}setConnection(b){this.connection=b;for(var _ in this.connectionCallbacks)this.connection.bind(_,this.connectionCallbacks[_]);this.resetActivityCheck()}abandonConnection(){if(this.connection){this.stopActivityCheck();for(var b in this.connectionCallbacks)this.connection.unbind(b,this.connectionCallbacks[b]);var _=this.connection;return this.connection=null,_}}updateState(b,_){var D=this.state;if(this.state=b,D!==b){var I=b;I==="connected"&&(I+=" with new socket ID "+_.socket_id),St.debug("State changed",D+" -> "+I),this.timeline.info({state:b,params:_}),this.emit("state_change",{previous:D,current:b}),this.emit(b,_)}}shouldRetry(){return this.state==="connecting"||this.state==="connected"}}class tu{constructor(){this.channels={}}add(b,_){return this.channels[b]||(this.channels[b]=pa(b,_)),this.channels[b]}all(){return kt(this.channels)}find(b){return this.channels[b]}remove(b){var _=this.channels[b];return delete this.channels[b],_}disconnect(){Me(this.channels,function(b){b.disconnect()})}}function pa(A,b){if(A.indexOf("private-encrypted-")===0){if(b.config.nacl)return Mr.createEncryptedChannel(A,b,b.config.nacl);let _="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",D=v.buildLogSuffix("encryptedChannelSupport");throw new F(`${_}. ${D}`)}else{if(A.indexOf("private-")===0)return Mr.createPrivateChannel(A,b);if(A.indexOf("presence-")===0)return Mr.createPresenceChannel(A,b);if(A.indexOf("#")===0)throw new R('Cannot create a channel with name "'+A+'".');return Mr.createChannel(A,b)}}var Fa={createChannels(){return new tu},createConnectionManager(A,b){return new eu(A,b)},createChannel(A,b){return new As(A,b)},createPrivateChannel(A,b){return new ha(A,b)},createPresenceChannel(A,b){return new Ga(A,b)},createEncryptedChannel(A,b,_){return new Jt(A,b,_)},createTimelineSender(A,b){return new ah(A,b)},createHandshake(A,b){return new rh(A,b)},createAssistantToTheTransportManager(A,b,_){return new jt(A,b,_)}},Mr=Fa;class Zo{constructor(b){this.options=b||{},this.livesLeft=this.options.lives||1/0}getAssistant(b){return Mr.createAssistantToTheTransportManager(this,b,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class Xr{constructor(b,_){this.strategies=b,this.loop=!!_.loop,this.failFast=!!_.failFast,this.timeout=_.timeout,this.timeoutLimit=_.timeoutLimit}isSupported(){return $r(this.strategies,me.method("isSupported"))}connect(b,_){var D=this.strategies,I=0,ie=this.timeout,ye=null,Oe=(Ve,it)=>{it?_(null,it):(I=I+1,this.loop&&(I=I%D.length),I0&&(ie=new T(D.timeout,function(){ye.abort(),I(!0)})),ye=b.connect(_,function(Oe,Ve){Oe&&ie&&ie.isRunning()&&!D.failFast||(ie&&ie.ensureAborted(),I(Oe,Ve))}),{abort:function(){ie&&ie.ensureAborted(),ye.abort()},forceMinPriority:function(Oe){ye.forceMinPriority(Oe)}}}}class el{constructor(b){this.strategies=b}isSupported(){return $r(this.strategies,me.method("isSupported"))}connect(b,_){return xs(this.strategies,b,function(D,I){return function(ie,ye){if(I[D].error=ie,ie){Ts(I)&&_(!0);return}vt(I,function(Oe){Oe.forceMinPriority(ye.transport.priority)}),_(null,ye)}})}}function xs(A,b,_){var D=hn(A,function(I,ie,ye,Oe){return I.connect(b,_(ie,Oe))});return{abort:function(){vt(D,Nr)},forceMinPriority:function(I){vt(D,function(ie){ie.forceMinPriority(I)})}}}function Ts(A){return En(A,function(b){return!!b.error})}function Nr(A){!A.error&&!A.aborted&&(A.abort(),A.aborted=!0)}class Pn{constructor(b,_,D){this.strategy=b,this.transports=_,this.ttl=D.ttl||1800*1e3,this.usingTLS=D.useTLS,this.timeline=D.timeline}isSupported(){return this.strategy.isSupported()}connect(b,_){var D=this.usingTLS,I=ih(D),ie=I&&I.cacheSkipCount?I.cacheSkipCount:0,ye=[this.strategy];if(I&&I.timestamp+this.ttl>=me.now()){var Oe=this.transports[I.transport];Oe&&(["ws","wss"].includes(I.transport)||ie>3?(this.timeline.info({cached:!0,transport:I.transport,latency:I.latency}),ye.push(new Xr([Oe],{timeout:I.latency*2+1e3,failFast:!0}))):ie++)}var Ve=me.now(),it=ye.pop().connect(b,function ct(Bt,Hi){Bt?(nl(D),ye.length>0?(Ve=me.now(),it=ye.pop().connect(b,ct)):_(Bt)):(tl(D,Hi.transport.name,me.now()-Ve,ie),_(null,Hi))});return{abort:function(){it.abort()},forceMinPriority:function(ct){b=ct,it&&it.forceMinPriority(ct)}}}}function ks(A){return"pusherTransport"+(A?"TLS":"NonTLS")}function ih(A){var b=Fe.getLocalStorage();if(b)try{var _=b[ks(A)];if(_)return JSON.parse(_)}catch{nl(A)}return null}function tl(A,b,_,D){var I=Fe.getLocalStorage();if(I)try{I[ks(A)]=er({timestamp:me.now(),transport:b,latency:_,cacheSkipCount:D})}catch{}}function nl(A){var b=Fe.getLocalStorage();if(b)try{delete b[ks(A)]}catch{}}class ga{constructor(b,{delay:_}){this.strategy=b,this.options={delay:_}}isSupported(){return this.strategy.isSupported()}connect(b,_){var D=this.strategy,I,ie=new T(this.options.delay,function(){I=D.connect(b,_)});return{abort:function(){ie.ensureAborted(),I&&I.abort()},forceMinPriority:function(ye){b=ye,I&&I.forceMinPriority(ye)}}}}class Ni{constructor(b,_,D){this.test=b,this.trueBranch=_,this.falseBranch=D}isSupported(){var b=this.test()?this.trueBranch:this.falseBranch;return b.isSupported()}connect(b,_){var D=this.test()?this.trueBranch:this.falseBranch;return D.connect(b,_)}}class Bn{constructor(b){this.strategy=b}isSupported(){return this.strategy.isSupported()}connect(b,_){var D=this.strategy.connect(b,function(I,ie){ie&&D.abort(),_(I,ie)});return D}}function ma(A){return function(){return A.isSupported()}}var nu=function(A,b,_){var D={};function I(Ui,pu,gu,vl,Sl){var wl=_(A,Ui,pu,gu,vl,Sl);return D[Ui]=wl,wl}var ie=Object.assign({},b,{hostNonTLS:A.wsHost+":"+A.wsPort,hostTLS:A.wsHost+":"+A.wssPort,httpPath:A.wsPath}),ye=Object.assign({},ie,{useTLS:!0}),Oe=Object.assign({},b,{hostNonTLS:A.httpHost+":"+A.httpPort,hostTLS:A.httpHost+":"+A.httpsPort,httpPath:A.httpPath}),Ve={loop:!0,timeout:15e3,timeoutLimit:6e4},it=new Zo({minPingDelay:1e4,maxPingDelay:A.activityTimeout}),ct=new Zo({lives:2,minPingDelay:1e4,maxPingDelay:A.activityTimeout}),Bt=I("ws","ws",3,ie,it),Hi=I("wss","ws",3,ye,it),du=I("sockjs","sockjs",1,Oe),pl=I("xhr_streaming","xhr_streaming",1,Oe,ct),fu=I("xdr_streaming","xdr_streaming",1,Oe,ct),gl=I("xhr_polling","xhr_polling",1,Oe),Ja=I("xdr_polling","xdr_polling",1,Oe),hu=new Xr([Bt],Ve),Ch=new Xr([Hi],Ve),Eh=new Xr([du],Ve),ml=new Xr([new Ni(ma(pl),pl,fu)],Ve),yl=new Xr([new Ni(ma(gl),gl,Ja)],Ve),Qa=new Xr([new Ni(ma(ml),new el([ml,new ga(yl,{delay:4e3})]),yl)],Ve),ba=new Ni(ma(Qa),Qa,Eh),bl;return b.useTLS?bl=new el([hu,new ga(ba,{delay:2e3})]):bl=new el([hu,new ga(Ch,{delay:2e3}),new ga(ba,{delay:5e3})]),new Pn(new Bn(new Ni(ma(Bt),bl,ba)),D,{ttl:18e5,timeline:b.timeline,useTLS:b.useTLS})},rl=nu,Va=(function(){var A=this;A.timeline.info(A.buildTimelineMessage({transport:A.name+(A.options.useTLS?"s":"")})),A.hooks.isInitialized()?A.changeState("initialized"):A.hooks.file?(A.changeState("initializing"),y.load(A.hooks.file,{useTLS:A.options.useTLS},function(b,_){A.hooks.isInitialized()?(A.changeState("initialized"),_(!0)):(b&&A.onError(b),A.onClose(),_(!1))})):A.onClose()}),ru={getRequest:function(A){var b=new window.XDomainRequest;return b.ontimeout=function(){A.emit("error",new L),A.close()},b.onerror=function(_){A.emit("error",_),A.close()},b.onprogress=function(){b.responseText&&b.responseText.length>0&&A.onChunk(200,b.responseText)},b.onload=function(){b.responseText&&b.responseText.length>0&&A.onChunk(200,b.responseText),A.emit("finished",200),A.close()},b},abortRequest:function(A){A.ontimeout=A.onerror=A.onprogress=A.onload=null,A.abort()}},au=ru;const Ka=256*1024;class sh extends J{constructor(b,_,D){super(),this.hooks=b,this.method=_,this.url=D}start(b){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},Fe.addUnloadListener(this.unloader),this.xhr.open(this.method,this.url,!0),this.xhr.setRequestHeader&&this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.send(b)}close(){this.unloader&&(Fe.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(b,_){for(;;){var D=this.advanceBuffer(_);if(D)this.emit("chunk",{status:b,data:D});else break}this.isBufferTooLong(_)&&this.emit("buffer_too_long")}advanceBuffer(b){var _=b.slice(this.position),D=_.indexOf(` +`);return D!==-1?(this.position+=D+1,_.slice(0,D)):null}isBufferTooLong(b){return this.position===b.length&&b.length>Ka}}var Rs;(function(A){A[A.CONNECTING=0]="CONNECTING",A[A.OPEN=1]="OPEN",A[A.CLOSED=3]="CLOSED"})(Rs||(Rs={}));var Jr=Rs,al=1;class oh{constructor(b,_){this.hooks=b,this.session=Os(1e3)+"/"+Wa(8),this.location=lh(_),this.readyState=Jr.CONNECTING,this.openStream()}send(b){return this.sendRaw(JSON.stringify([b]))}ping(){this.hooks.sendHeartbeat(this)}close(b,_){this.onClose(b,_,!0)}sendRaw(b){if(this.readyState===Jr.OPEN)try{return Fe.createSocketRequest("POST",hr(Ds(this.location,this.session))).start(b),!0}catch{return!1}else return!1}reconnect(){this.closeStream(),this.openStream()}onClose(b,_,D){this.closeStream(),this.readyState=Jr.CLOSED,this.onclose&&this.onclose({code:b,reason:_,wasClean:D})}onChunk(b){if(b.status===200){this.readyState===Jr.OPEN&&this.onActivity();var _,D=b.data.slice(0,1);switch(D){case"o":_=JSON.parse(b.data.slice(1)||"{}"),this.onOpen(_);break;case"a":_=JSON.parse(b.data.slice(1)||"[]");for(var I=0;I<_.length;I++)this.onEvent(_[I]);break;case"m":_=JSON.parse(b.data.slice(1)||"null"),this.onEvent(_);break;case"h":this.hooks.onHeartbeat(this);break;case"c":_=JSON.parse(b.data.slice(1)||"[]"),this.onClose(_[0],_[1],!0);break}}}onOpen(b){this.readyState===Jr.CONNECTING?(b&&b.hostname&&(this.location.base=il(this.location.base,b.hostname)),this.readyState=Jr.OPEN,this.onopen&&this.onopen()):this.onClose(1006,"Server lost session",!0)}onEvent(b){this.readyState===Jr.OPEN&&this.onmessage&&this.onmessage({data:b})}onActivity(){this.onactivity&&this.onactivity()}onError(b){this.onerror&&this.onerror(b)}openStream(){this.stream=Fe.createSocketRequest("POST",hr(this.hooks.getReceiveURL(this.location,this.session))),this.stream.bind("chunk",b=>{this.onChunk(b)}),this.stream.bind("finished",b=>{this.hooks.onFinished(this,b)}),this.stream.bind("buffer_too_long",()=>{this.reconnect()});try{this.stream.start()}catch(b){me.defer(()=>{this.onError(b),this.onClose(1006,"Could not start streaming",!1)})}}closeStream(){this.stream&&(this.stream.unbind_all(),this.stream.close(),this.stream=null)}}function lh(A){var b=/([^\?]*)\/*(\??.*)/.exec(A);return{base:b[1],queryString:b[2]}}function Ds(A,b){return A.base+"/"+b+"/xhr_send"}function hr(A){var b=A.indexOf("?")===-1?"?":"&";return A+b+"t="+ +new Date+"&n="+al++}function il(A,b){var _=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(A);return _[1]+b+_[3]}function Os(A){return Fe.randomInt(A)}function Wa(A){for(var b=[],_=0;_0&&A.onChunk(_.status,_.responseText);break;case 4:_.responseText&&_.responseText.length>0&&A.onChunk(_.status,_.responseText),A.emit("finished",_.status),A.close();break}},_},abortRequest:function(A){A.onreadystatechange=null,A.abort()}},ol=Ir,ji={createStreamingSocket(A){return this.createSocket(sl,A)},createPollingSocket(A){return this.createSocket(Ii,A)},createSocket(A,b){return new Ya(A,b)},createXHR(A,b){return this.createRequest(ol,A,b)},createRequest(A,b,_){return new sh(A,b,_)}},jr=ji;jr.createXDR=function(A,b){return this.createRequest(au,A,b)};var ll=jr,Ls={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:c,DependenciesReceivers:m,getDefaultStrategy:rl,Transports:Mt,transportConnectionInitializer:Va,HTTPFactory:ll,TimelineTransport:fa,getXHRAPI(){return window.XMLHttpRequest},getWebSocketAPI(){return window.WebSocket||window.MozWebSocket},setup(A){window.Pusher=A;var b=()=>{this.onDocumentBody(A.ready)};window.JSON?b():y.load("json2",{},b)},getDocument(){return document},getProtocol(){return this.getDocument().location.protocol},getAuthorizers(){return{ajax:Ee,jsonp:In}},onDocumentBody(A){document.body?A():setTimeout(()=>{this.onDocumentBody(A)},0)},createJSONPRequest(A,b){return new Rn(A,b)},createScriptRequest(A){return new kn(A)},getLocalStorage(){try{return window.localStorage}catch{return}},createXHR(){return this.getXHRAPI()?this.createXMLHttpRequest():this.createMicrosoftXHR()},createXMLHttpRequest(){var A=this.getXHRAPI();return new A},createMicrosoftXHR(){return new ActiveXObject("Microsoft.XMLHTTP")},getNetwork(){return It},createWebSocket(A){var b=this.getWebSocketAPI();return new b(A)},createSocketRequest(A,b){if(this.isXHRSupported())return this.HTTPFactory.createXHR(A,b);if(this.isXDRSupported(b.indexOf("https:")===0))return this.HTTPFactory.createXDR(A,b);throw"Cross-origin HTTP requests are not supported"},isXHRSupported(){var A=this.getXHRAPI();return!!A&&new A().withCredentials!==void 0},isXDRSupported(A){var b=A?"https:":"http:",_=this.getProtocol();return!!window.XDomainRequest&&_===b},addUnloadListener(A){window.addEventListener!==void 0?window.addEventListener("unload",A,!1):window.attachEvent!==void 0&&window.attachEvent("onunload",A)},removeUnloadListener(A){window.addEventListener!==void 0?window.removeEventListener("unload",A,!1):window.detachEvent!==void 0&&window.detachEvent("onunload",A)},randomInt(A){return Math.floor(function(){return(window.crypto||window.msCrypto).getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}()*A)}},Fe=Ls,Xa;(function(A){A[A.ERROR=3]="ERROR",A[A.INFO=6]="INFO",A[A.DEBUG=7]="DEBUG"})(Xa||(Xa={}));var ya=Xa;class ou{constructor(b,_,D){this.key=b,this.session=_,this.events=[],this.options=D||{},this.sent=0,this.uniqueID=0}log(b,_){b<=this.options.level&&(this.events.push(ae({},_,{timestamp:me.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(b){this.log(ya.ERROR,b)}info(b){this.log(ya.INFO,b)}debug(b){this.log(ya.DEBUG,b)}isEmpty(){return this.events.length===0}send(b,_){var D=ae({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=[],b(D,(I,ie)=>{I||this.sent++,_&&_(I,ie)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class An{constructor(b,_,D,I){this.name=b,this.priority=_,this.transport=D,this.options=I||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(b,_){if(this.isSupported()){if(this.priority{D||(ct(),ie?ie.close():I.close())},forceMinPriority:Bt=>{D||this.priority{var _="socket_id="+encodeURIComponent(A.socketId);for(var D in b.params)_+="&"+encodeURIComponent(D)+"="+encodeURIComponent(b.params[D]);if(b.paramsProvider!=null){let I=b.paramsProvider();for(var D in I)_+="&"+encodeURIComponent(D)+"="+encodeURIComponent(I[D])}return _};var Ns=A=>{if(typeof Fe.getAuthorizers()[A.transport]>"u")throw`'${A.transport}' is not a recognized auth transport`;return(b,_)=>{const D=ul(b,A);Fe.getAuthorizers()[A.transport](Fe,D,A,x.UserAuthentication,_)}};const lu=(A,b)=>{var _="socket_id="+encodeURIComponent(A.socketId);_+="&channel_name="+encodeURIComponent(A.channelName);for(var D in b.params)_+="&"+encodeURIComponent(D)+"="+encodeURIComponent(b.params[D]);if(b.paramsProvider!=null){let I=b.paramsProvider();for(var D in I)_+="&"+encodeURIComponent(D)+"="+encodeURIComponent(I[D])}return _};var uh=A=>{if(typeof Fe.getAuthorizers()[A.transport]>"u")throw`'${A.transport}' is not a recognized auth transport`;return(b,_)=>{const D=lu(b,A);Fe.getAuthorizers()[A.transport](Fe,D,A,x.ChannelAuthorization,_)}};const dh=(A,b,_)=>{const D={authTransport:b.transport,authEndpoint:b.endpoint,auth:{params:b.params,headers:b.headers}};return(I,ie)=>{const ye=A.channel(I.channelName);_(ye,D).authorize(I.socketId,ie)}};function dl(A,b){let _={activityTimeout:A.activityTimeout||f.activityTimeout,cluster:A.cluster,httpPath:A.httpPath||f.httpPath,httpPort:A.httpPort||f.httpPort,httpsPort:A.httpsPort||f.httpsPort,pongTimeout:A.pongTimeout||f.pongTimeout,statsHost:A.statsHost||f.stats_host,unavailableTimeout:A.unavailableTimeout||f.unavailableTimeout,wsPath:A.wsPath||f.wsPath,wsPort:A.wsPort||f.wsPort,wssPort:A.wssPort||f.wssPort,enableStats:mh(A),httpHost:fh(A),useTLS:gh(A),wsHost:hh(A),userAuthenticator:cu(A),channelAuthorizer:bh(A,b)};return"disabledTransports"in A&&(_.disabledTransports=A.disabledTransports),"enabledTransports"in A&&(_.enabledTransports=A.enabledTransports),"ignoreNullOrigin"in A&&(_.ignoreNullOrigin=A.ignoreNullOrigin),"timelineParams"in A&&(_.timelineParams=A.timelineParams),"nacl"in A&&(_.nacl=A.nacl),_}function fh(A){return A.httpHost?A.httpHost:A.cluster?`sockjs-${A.cluster}.pusher.com`:f.httpHost}function hh(A){return A.wsHost?A.wsHost:ph(A.cluster)}function ph(A){return`ws-${A}.pusher.com`}function gh(A){return Fe.getProtocol()==="https:"?!0:A.forceTLS!==!1}function mh(A){return"enableStats"in A?A.enableStats:"disableStats"in A?!A.disableStats:!1}function cu(A){const b=Object.assign(Object.assign({},f.userAuthentication),A.userAuthentication);return"customHandler"in b&&b.customHandler!=null?b.customHandler:Ns(b)}function yh(A,b){let _;return"channelAuthorization"in A?_=Object.assign(Object.assign({},f.channelAuthorization),A.channelAuthorization):(_={transport:A.authTransport||f.authTransport,endpoint:A.authEndpoint||f.authEndpoint},"auth"in A&&("params"in A.auth&&(_.params=A.auth.params),"headers"in A.auth&&(_.headers=A.auth.headers)),"authorizer"in A&&(_.customHandler=dh(b,_,A.authorizer))),_}function bh(A,b){const _=yh(A,b);return"customHandler"in _&&_.customHandler!=null?_.customHandler:uh(_)}class vh extends J{constructor(b){super(function(_,D){St.debug(`No callbacks on watchlist events for ${_}`)}),this.pusher=b,this.bindWatchlistInternalEvent()}handleEvent(b){b.data.events.forEach(_=>{this.emit(_.name,_)})}bindWatchlistInternalEvent(){this.pusher.connection.bind("message",b=>{var _=b.event;_==="pusher_internal:watchlist_events"&&this.handleEvent(b)})}}function Sh(){let A,b;return{promise:new Promise((D,I)=>{A=D,b=I}),resolve:A,reject:b}}var fl=Sh;class wh extends J{constructor(b){super(function(_,D){St.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=(_,D)=>{if(_){St.warn(`Error during signin: ${_}`),this._cleanup();return}this.pusher.send_event("pusher:signin",{auth:D.auth,user_data:D.user_data})},this.pusher=b,this.pusher.connection.bind("state_change",({previous:_,current:D})=>{_!=="connected"&&D==="connected"&&this._signin(),_==="connected"&&D!=="connected"&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new vh(b),this.pusher.connection.bind("message",_=>{var D=_.event;D==="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(b){try{this.user_data=JSON.parse(b.user_data)}catch{St.error(`Failed parsing user data after signin: ${b.user_data}`),this._cleanup();return}if(typeof this.user_data.id!="string"||this.user_data.id===""){St.error(`user_data doesn't contain an id. user_data: ${this.user_data}`),this._cleanup();return}this._signinDoneResolve(),this._subscribeChannels()}_subscribeChannels(){const b=_=>{_.subscriptionPending&&_.subscriptionCancelled?_.reinstateSubscription():!_.subscriptionPending&&this.pusher.connection.state==="connected"&&_.subscribe()};this.serverToUserChannel=new As(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((_,D)=>{_.indexOf("pusher_internal:")===0||_.indexOf("pusher:")===0||this.emit(_,D)}),b(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:b,resolve:_}=fl();b.done=!1;const D=()=>{b.done=!0};b.then(D).catch(D),this.signinDonePromise=b,this._signinDoneResolve=_}}class sn{static ready(){sn.isReady=!0;for(var b=0,_=sn.instances.length;b<_;b++)sn.instances[b].connect()}static getClientFeatures(){return Ge(un({ws:Fe.Transports.ws},function(b){return b.isSupported({})}))}constructor(b,_){uu(b),cl(_),this.key=b,this.config=dl(_,this),this.channels=Mr.createChannels(),this.global_emitter=new J,this.sessionID=Fe.randomInt(1e9),this.timeline=new ou(this.key,this.sessionID,{cluster:this.config.cluster,features:sn.getClientFeatures(),params:this.config.timelineParams||{},limit:50,level:ya.INFO,version:f.VERSION}),this.config.enableStats&&(this.timelineSender=Mr.createTimelineSender(this.timeline,{host:this.config.statsHost,path:"/timeline/v2/"+Fe.TimelineTransport.name}));var D=I=>Fe.getDefaultStrategy(this.config,I,zi);this.connection=Mr.createConnectionManager(this.key,{getStrategy:D,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",I=>{var ie=I.event,ye=ie.indexOf("pusher_internal:")===0;if(I.channel){var Oe=this.channel(I.channel);Oe&&Oe.handleEvent(I)}ye||this.global_emitter.emit(I.event,I.data)}),this.connection.bind("connecting",()=>{this.channels.disconnect()}),this.connection.bind("disconnected",()=>{this.channels.disconnect()}),this.connection.bind("error",I=>{St.warn(I)}),sn.instances.push(this),this.timeline.info({instances:sn.instances.length}),this.user=new wh(this),sn.isReady&&this.connect()}channel(b){return this.channels.find(b)}allChannels(){return this.channels.all()}connect(){if(this.connection.connect(),this.timelineSender&&!this.timelineSenderTimer){var b=this.connection.isUsingTLS(),_=this.timelineSender;this.timelineSenderTimer=new pe(6e4,function(){_.send(b)})}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(b,_,D){return this.global_emitter.bind(b,_,D),this}unbind(b,_,D){return this.global_emitter.unbind(b,_,D),this}bind_global(b){return this.global_emitter.bind_global(b),this}unbind_global(b){return this.global_emitter.unbind_global(b),this}unbind_all(b){return this.global_emitter.unbind_all(),this}subscribeAll(){var b;for(b in this.channels.channels)this.channels.channels.hasOwnProperty(b)&&this.subscribe(b)}subscribe(b){var _=this.channels.add(b,this);return _.subscriptionPending&&_.subscriptionCancelled?_.reinstateSubscription():!_.subscriptionPending&&this.connection.state==="connected"&&_.subscribe(),_}unsubscribe(b){var _=this.channels.find(b);_&&_.subscriptionPending?_.cancelSubscription():(_=this.channels.remove(b),_&&_.subscribed&&_.unsubscribe())}send_event(b,_,D){return this.connection.send_event(b,_,D)}shouldUseTLS(){return this.config.useTLS}signin(){this.user.signin()}}sn.instances=[],sn.isReady=!1,sn.logToConsole=!1,sn.Runtime=Fe,sn.ScriptReceivers=Fe.ScriptReceivers,sn.DependenciesReceivers=Fe.DependenciesReceivers,sn.auth_callbacks=Fe.auth_callbacks;var hl=r.default=sn;function uu(A){if(A==null)throw"You must pass your app key when you instantiate Pusher."}Fe.setup(sn)})])})})(Xf)),Xf.exports}var OA=DA();const Xy=aa(OA),zt=dt("WebSocketManager");class LA{constructor(){$(this,"echo",null);$(this,"subscriptions",new Map);$(this,"initialized",!1);$(this,"config",null)}configure(e){if(this.initialized){zt.warn("[WebSocketManager] 이미 초기화되어 설정을 변경할 수 없습니다.");return}this.config=e,zt.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){zt.warn("[WebSocketManager] WebSocket 설정이 없습니다. initTemplateApp에서 websocket 옵션을 전달해주세요.");return}const{appKey:e,host:n="localhost",port:r=80,scheme:i="https",authEndpoint:l="/api/broadcasting/auth"}=this.config,c=Number(r)||80,d=i==="https";zt.log("[WebSocketManager] 연결 설정:",{host:n,port:c,scheme:i,useTLS:d,authEndpoint:l}),window.Pusher=Xy;const f=localStorage.getItem("auth_token"),p={wsHost:n,wsPort:c,wssPort:c,forceTLS:d,disableStats:!0,enabledTransports:["ws","wss"],cluster:"mt1",authEndpoint:l,auth:{headers:{Authorization:f?`Bearer ${f}`:"",Accept:"application/json"}}};zt.log("[WebSocketManager] Pusher 옵션:",p);const m=new Xy(e,p);m.connection.bind("connecting",()=>{zt.log("[WebSocketManager] 연결 시도 중...")}),m.connection.bind("connected",()=>{zt.log("[WebSocketManager] 연결 성공! Socket ID:",m.connection.socket_id)}),m.connection.bind("failed",()=>{zt.error("[WebSocketManager] 연결 실패 - WebSocket을 사용할 수 없습니다.")}),m.connection.bind("error",y=>{zt.error("[WebSocketManager] 연결 오류:",y)}),m.connection.bind("state_change",y=>{zt.log(`[WebSocketManager] 상태 변경: ${y.previous} → ${y.current}`)}),m.connection.bind("unavailable",()=>{zt.error("[WebSocketManager] WebSocket 사용 불가 - 연결할 수 없습니다.")}),m.connection.bind("disconnected",()=>{zt.warn("[WebSocketManager] 연결이 끊어졌습니다.")}),zt.log("[WebSocketManager] 초기 연결 상태:",m.connection.state),this.echo=new RA({broadcaster:"reverb",client:m}),zt.log("[WebSocketManager] 연결 시작 시도..."),m.connect(),window.Echo=this.echo,this.initialized=!0,zt.log("[WebSocketManager] Echo 초기화 완료")}subscribe(e,n,r,i={}){if(this.initialize(),!this.echo)return zt.warn("[WebSocketManager] Echo가 초기화되지 않았습니다."),"";const{channelType:l="private"}=i,c=`${e}:${n}`;if(this.subscriptions.has(c))return zt.log(`[WebSocketManager] 이미 구독 중: ${c}`),c;let d;switch(l){case"public":d=this.echo.channel(e);break;case"presence":d=this.echo.join(e);break;default:d=this.echo.private(e)}return d.listen(`.${n}`,r),this.subscriptions.set(c,d),zt.log(`[WebSocketManager] 구독 완료: ${c} (${l})`),c}unsubscribe(e){const n=this.subscriptions.get(e);if(!n)return;const r=e.lastIndexOf(":"),i=r>=0?e.substring(r+1):"";if(i)try{n.stopListening(`.${i}`)}catch(l){zt.warn(`[WebSocketManager] stopListening 실패: ${e}`,l)}this.subscriptions.delete(e),zt.log(`[WebSocketManager] 구독 해제: ${e}`)}leaveChannel(e){if(!this.echo)return;this.echo.leave(e);const n=[];this.subscriptions.forEach((r,i)=>{i.startsWith(`${e}:`)&&n.push(i)}),n.forEach(r=>this.subscriptions.delete(r)),zt.log(`[WebSocketManager] 채널 구독 해제: ${e}`)}disconnect(){this.echo&&(this.echo.disconnect(),this.subscriptions.clear(),this.initialized=!1,zt.log("[WebSocketManager] 연결 종료"))}getEcho(){return this.echo}isInitialized(){return this.initialized}isConfigured(){return this.config!==null&&!!this.config.appKey}getSubscriptionCount(){return this.subscriptions.size}}const Vc=new LA,gt=dt("DataSourceManager"),Jy=new Tn;function Kc(s,e){const n=Ma(s);if(n!==null)try{return On(n)?Jy.evaluatePipeExpression(n,e,{skipCache:!0}):Jy.evaluateExpression(n,e)}catch(r){return gt.error("Failed to evaluate param expression:",n,r),s}return ls(s,e,{skipCache:!0})}function Qy(s){const e={};for(const n of s.keys()){if(n in e)continue;const r=s.getAll(n);r.length>1?e[n]=r:r.length===1&&(n.endsWith("[]")?e[n]=r:e[n]=r[0])}return e}function $A(){try{return window.G7Core?.devTools}catch{return}}const Zc=class Zc{constructor(e={}){$(this,"options");$(this,"dataCache",new Map);$(this,"bindingEngine");$(this,"globalHeaders",[]);this.options=e,this.bindingEngine=new Tn}setGlobalHeaders(e){this.globalHeaders=e||[]}matchesPattern(e,n){if(n==="*")return!0;const r=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${r}$`).test(e)}toFormData(e){const n=new FormData;for(const[r,i]of Object.entries(e))i instanceof File||i instanceof Blob?n.append(r,i):i!=null&&n.append(r,typeof i=="object"?JSON.stringify(i):String(i));return n}getMatchingGlobalHeaders(e,n){const r={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,c])=>{const d=Kc(c,n);d!=null&&d!==""&&(r[l]=String(d))});return r}filterByCondition(e,n={}){const r=new Set,i=[];for(const l of e){if(r.has(l.id))continue;if(!l.if&&!l.conditions){r.add(l.id),i.push(l);continue}os({if:l.if,conditions:l.conditions},n,this.bindingEngine,`data_source:${l.id}`)&&(r.add(l.id),i.push(l))}return i}checkErrorCondition(e,n){if(!e.errorCondition?.if||e.errorCondition?.errorCode===void 0)return null;try{const r={response:n};if(os({if:e.errorCondition.if},r,this.bindingEngine,`errorCondition:${e.id}`))return gt.log(`errorCondition matched for ${e.id}, triggering error ${e.errorCondition.errorCode}`),e.errorCondition.errorCode}catch(r){gt.error(`Failed to evaluate errorCondition for ${e.id}:`,r)}return null}async fetchDataSources(e,n={},r=new URLSearchParams,i,l){const c={},d=!!this.options.sampleProvider,f=e.filter(p=>(d||p.auto_fetch!==!1)&&p.type!=="websocket");return await Promise.all(f.map(async p=>{try{const m=await this.fetchDataSource(p,n,r,i,l);c[p.id]=m,this.dataCache.set(p.id,{data:m,timestamp:Date.now()});const y=this.checkErrorCondition(p,m);if(y!==null){const C={status:y,message:`Error condition matched for ${p.id}`,data:m},S=Tr(),v=S.resolve(y,{errorHandling:p.errorHandling,onError:p.onError});if(v.handler)try{await S.execute(v.handler,C)}catch(x){gt.error(`Error executing errorCondition handler for ${p.id}:`,x)}p.fallback!==void 0&&(c[p.id]=p.fallback,this.dataCache.set(p.id,{data:p.fallback,timestamp:Date.now()}),gt.log(`Using fallback data for ${p.id} (errorCondition)`));return}if(p.onSuccess)try{const C={data:m,sourceId:p.id};await this.executeOnSuccessHandler(p.onSuccess,C)}catch(C){gt.error(`Error executing onSuccess handler for ${p.id}:`,C)}}catch(m){gt.error(`Failed to fetch data source: ${p.id}`,m);const y=m?.response?.status||m?.status||500,C=m?.response?.data,S=C?.message||m.message||"Unknown error",v={status:y,message:S,errors:C?.errors,data:C,statusText:m?.response?.statusText},x=Tr(),w=x.resolve(y,{errorHandling:p.errorHandling,onError:p.onError});if(w.handler)try{await x.execute(w.handler,v)}catch(R){gt.error(`Error executing error handler for ${p.id}:`,R)}p.fallback!==void 0&&(c[p.id]=p.fallback,this.dataCache.set(p.id,{data:p.fallback,timestamp:Date.now()}),gt.log(`Using fallback data for ${p.id}`)),this.options.onError&&this.options.onError(m,p)}})),c}async fetchDataSourcesWithResults(e,n={},r=new URLSearchParams,i,l,c){if(e.some(m=>m.type==="websocket")){const m=e.filter(y=>y.type==="websocket").map(y=>y.id).join(", ");gt.warn(`fetchDataSourcesWithResults received WebSocket sources (caller should filter them out before calling): ${m}. WebSocket sources are event listeners, not data providers — they should not be passed to fetch.`)}const f=c?.ignoreAutoFetch?e.filter(m=>m.type!=="websocket"):e.filter(m=>m.auto_fetch!==!1&&m.type!=="websocket");return await Promise.all(f.map(async m=>{try{const y=await this.fetchDataSource(m,n,r,i,l);this.dataCache.set(m.id,{data:y,timestamp:Date.now()});const C=this.checkErrorCondition(m,y);if(C!==null){const S={status:C,message:`Error condition matched for ${m.id}`,data:y},v=Tr(),x=v.resolve(C,{errorHandling:m.errorHandling,onError:m.onError});let w=!1;if(x.handler)if(m.loading_strategy==="blocking")v.execute(x.handler,S).catch(R=>{gt.error(`Error executing errorCondition handler for ${m.id}:`,R)}),w=!0;else try{await v.execute(x.handler,S),w=!0}catch(R){gt.error(`Error executing errorCondition handler for ${m.id}:`,R)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),gt.log(`Using fallback data for ${m.id} (errorCondition)`),{id:m.id,state:"success",data:m.fallback}):{id:m.id,state:"error",error:new Error(`Error condition matched: ${C}`),errorCode:C,errorHandled:w}}if(m.onSuccess)try{const S={data:y,sourceId:m.id};await this.executeOnSuccessHandler(m.onSuccess,S)}catch(S){gt.error(`Error executing onSuccess handler for ${m.id}:`,S)}return{id:m.id,state:"success",data:y}}catch(y){gt.error(`Failed to fetch data source: ${m.id}`,y);const C=y?.response?.status||y?.status||500,S=y?.response?.data,v=S?.message||y.message||"Unknown error",x={status:C,message:v,errors:S?.errors,data:S,statusText:y?.response?.statusText},w=Tr(),R=w.resolve(C,{errorHandling:m.errorHandling,onError:m.onError});let L=!1;if(R.handler)if(m.loading_strategy==="blocking")w.execute(R.handler,x).catch(O=>{gt.error(`Error executing error handler for ${m.id}:`,O)}),L=!0;else try{await w.execute(R.handler,x),L=!0}catch(O){gt.error(`Error executing error handler for ${m.id}:`,O)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),gt.log(`Using fallback data for ${m.id}`),{id:m.id,state:"success",data:m.fallback}):(this.options.onError&&this.options.onError(y,m),{id:m.id,state:"error",error:y,errorCode:C,errorHandled:L})}}))}fetchDataSourcesInBackground(e,n={},r=new URLSearchParams,i){e.filter(c=>c.auto_fetch!==!1&&c.loading_strategy==="background"&&c.type!=="websocket").forEach(c=>{this.fetchDataSource(c,n,r).then(async d=>{this.dataCache.set(c.id,{data:d,timestamp:Date.now()});const f=this.checkErrorCondition(c,d);if(f!==null){const p={status:f,message:`Error condition matched for ${c.id}`,data:d},m=Tr(),y=m.resolve(f,{errorHandling:c.errorHandling,onError:c.onError});if(y.handler)try{await m.execute(y.handler,p)}catch(C){gt.error(`Error executing errorCondition handler for ${c.id}:`,C)}c.fallback!==void 0&&(this.dataCache.set(c.id,{data:c.fallback,timestamp:Date.now()}),gt.log(`Using fallback data for ${c.id} (errorCondition)`),i&&i(c.id,c.fallback));return}if(c.onSuccess)try{const p={data:d,sourceId:c.id};await this.executeOnSuccessHandler(c.onSuccess,p)}catch(p){gt.error(`Error executing onSuccess handler for ${c.id}:`,p)}i&&i(c.id,d)}).catch(async d=>{gt.error(`Background fetch failed: ${c.id}`,d);const f=d?.response?.status||d?.status||500,p=d?.response?.data,m=p?.message||d.message||"Unknown error",y={status:f,message:m,errors:p?.errors,data:p,statusText:d?.response?.statusText},C=Tr(),S=C.resolve(f,{errorHandling:c.errorHandling,onError:c.onError});if(S.handler)try{await C.execute(S.handler,y)}catch(v){gt.error(`Error executing error handler for ${c.id}:`,v)}if(c.fallback!==void 0){this.dataCache.set(c.id,{data:c.fallback,timestamp:Date.now()}),gt.log(`Using fallback data for ${c.id}`),i&&i(c.id,c.fallback);return}this.options.onError&&this.options.onError(d,c)})})}async fetchDataSource(e,n,r,i,l){switch(e.type){case"api":return this.fetchApiDataSource(e,n,r,i,l);case"static":return e.data;case"route_params":return n;case"query_params":return Qy(r);default:throw new Error(`Unknown data source type: ${e.type}`)}}async fetchApiDataSource(e,n,r,i,l){if(this.options.sampleProvider?.has(e.id))return await Promise.resolve(this.options.sampleProvider.resolve(e));if(!e.endpoint)throw new Error(`API data source ${e.id} has no endpoint`);const c={route:n,query:Qy(r)};i&&(c._global=i),l&&(c._local=l);let d=ls(e.endpoint,c,{skipCache:!0});const f=e.method||"GET",m=(e.contentType?typeof e.contentType=="string"&&e.contentType.includes("{{")?ls(e.contentType,c,{skipCache:!0}):e.contentType:"application/json")==="multipart/form-data";let y=m?{...e.params||{}}:JSON.parse(JSON.stringify(e.params||{}));Object.entries(y).forEach(([v,x])=>{typeof x=="string"&&(y[v]=Kc(x,c))}),Object.keys(y).forEach(v=>{y[v]===""&&delete y[v]});const C=$A();let S=null;if(C?.isEnabled()){C.trackDataSourceDefinition({id:e.id,type:e.type,endpoint:d,method:f,autoFetch:e.auto_fetch,initLocal:e.initLocal,initGlobal:e.initGlobal});let v=d;if(f==="GET"&&Object.keys(y).length>0){const x=new URLSearchParams;Object.entries(y).forEach(([R,L])=>{Array.isArray(L)?L.forEach(O=>x.append(R,String(O))):L!=null&&x.append(R,String(L))});const w=x.toString();v=w?`${d}?${w}`:d}S=C.trackRequest(v,f,{requestBody:f!=="GET"?y:void 0,dataSourceId:e.id}),C.trackDataSourceLoading(e.id)}try{let v;const x=e.auth_mode??(e.auth_required===!0?"required":"none"),w=Yn.getInstance().isAuthenticated();if(x==="required"&&!w){gt.log(`[DataSourceManager] Skipping ${e.id}: auth_mode is 'required' but no token available`),C?.isEnabled()&&(C.trackDataSourceError(e.id,"Skipped: auth_mode required but not authenticated"),S&&C.failRequest(S,"Skipped: not authenticated"));const L=new Error("Auth required but not authenticated");throw L.response={status:401,statusText:"Unauthorized",data:null},L.status=401,L._authSkipped=!0,L}const R=x==="required"||x==="optional"&&w;if(R){const L=Wn(),O=d.startsWith("/api/")?d.substring(4):d.startsWith("/api")?d.substring(4)||"/":d;this.options.onError&>.log(`[DataSourceManager] Normalized endpoint: ${d} -> ${O}`);const j=this.getMatchingGlobalHeaders(d,c),F={};e.headers&&Object.entries(e.headers).forEach(([he,Ee])=>{const ke=Kc(Ee,c);ke!=null&&ke!==""&&(F[he]=String(ke))});const G={...j,...F},P=Object.keys(G).length>0,K=m?this.toFormData(y):y;switch(f){case"GET":v=await L.get(O,{params:y,...P&&{headers:G}});break;case"POST":P?v=await L.post(O,K,{headers:G}):v=await L.post(O,K);break;case"PUT":P?v=await L.put(O,K,{headers:G}):v=await L.put(O,K);break;case"PATCH":P?v=await L.patch(O,K,{headers:G}):v=await L.patch(O,K);break;case"DELETE":v=await L.delete(O,{params:y,...P&&{headers:G}});break;default:throw new Error(`Unsupported HTTP method: ${f}`)}}else{let L=d;if(f==="GET"){const K=new URLSearchParams(y).toString();L=K?`${d}?${K}`:d}const O={...m?{}:{"Content-Type":"application/json"},Accept:"application/json"};if(typeof window<"u"){const K=localStorage.getItem("g7_locale");K&&(O["Accept-Language"]=K)}const j=this.getMatchingGlobalHeaders(d,c);Object.assign(O,j),e.headers&&Object.entries(e.headers).forEach(([K,he])=>{const Ee=Kc(he,c);Ee!=null&&Ee!==""&&(O[K]=String(Ee))});let F;f!=="GET"&&(m?(F=this.toFormData(y),delete O["Content-Type"]):F=JSON.stringify(y));const G=await fetch(L,{method:f,headers:O,body:F});let P;try{P=await G.json()}catch{P=null}if(S&&C?.isEnabled()&&(C.completeRequest(S,G.status,P),S=null),!G.ok){C?.isEnabled()&&C.trackDataSourceError(e.id,`HTTP ${G.status}: ${G.statusText}`);const K=new Error(`HTTP error! status: ${G.status}`);throw K.response={status:G.status,statusText:G.statusText,data:P},K.status=G.status,K}v=P,C?.isEnabled()&&C.trackDataSourceLoaded(e.id,v)}return R&&S&&C?.isEnabled()&&(C.completeRequest(S,200,v),C.trackDataSourceLoaded(e.id,v)),v}catch(v){if(S&&C?.isEnabled()){const x=v;x?.response?C.completeRequest(S,x.response.status,x.response.data):C.failRequest(S,v instanceof Error?v.message:String(v)),C.trackDataSourceError(e.id,v instanceof Error?v.message:String(v))}throw v}}getCachedData(e){const n=this.dataCache.get(e);if(!n)return;if(Date.now()-n.timestamp>Zc.DATA_CACHE_TTL){this.dataCache.delete(e);return}return n.data}clearCache(){this.dataCache.clear()}subscribeWebSockets(e,n,r={}){const i=[],l=e.filter(c=>c.type==="websocket");return l.length===0||l.forEach(c=>{if(!c.channel||!c.event){gt.warn(`WebSocket source ${c.id} missing channel or event`);return}let d,f;try{d=ls(c.channel,r,{skipCache:!0}),f=ls(c.event,r,{skipCache:!0})}catch(y){gt.error(`Failed to resolve WebSocket channel/event for source ${c.id}:`,y);return}const p=y=>!!(!y||y.trim()===""||y.includes("{{")||y.endsWith(".")||y.endsWith(":")||y.startsWith(".")||y.startsWith(":")||y.includes("..")||y.includes("::"));if(p(d)||p(f)){gt.warn(`WebSocket source ${c.id} has invalid channel/event after expression resolution, skipping. Original channel="${c.channel}", resolved="${d}". Original event="${c.event}", resolved="${f}". Available context keys: [${Object.keys(r).join(", ")}]`);return}const m=Vc.subscribe(d,f,y=>{const C=c.target_source||c.id;this.dataCache.set(C,{data:y,timestamp:Date.now()}),n(C,y)},{channelType:c.channel_type||"private"});m&&i.push(m)}),i}unsubscribeWebSockets(e){e.length!==0&&e.forEach(n=>{Vc.unsubscribe(n)})}async executeOnSuccessHandler(e,n){const r=this.options.actionDispatcher??Wm();if(!r){gt.warn("ActionDispatcher not available, skipping onSuccess handler");return}const i=Array.isArray(e)?e:[e];for(const l of i)try{await r.dispatchAction({type:"click",...l},{data:{response:n}})}catch(c){throw gt.error("Failed to execute onSuccess handler:",c),c}}};$(Zc,"DATA_CACHE_TTL",3e5);let Dr=Zc;const MA=new Dr,Ri=dt("ModalDataSourceWrapper");function NA(s,e){if(!s||!e)return s;const r=e.replace(/\?\./g,".").split(/\.(?![^\[]*\])/).flatMap(l=>{const c=l.match(/^([^\[]*)((?:\[\d+\])*)$/);if(c){const[,d,f]=c,p=[];d&&p.push(d);const m=f.match(/\[\d+\]/g);return m&&p.push(...m),p}return[l]}).filter(l=>l!=="");let i=s;for(const l of r){if(i==null)return;if(l.startsWith("[")&&l.endsWith("]")){const c=parseInt(l.slice(1,-1),10);i=i[c]}else i=i[l]}return i}const Zy=({isOpen:s,modalId:e,dataSources:n,dataContext:r,globalStateUpdater:i,bindingEngine:l,debug:c=!1,children:d})=>{const[f,p]=M.useState(!1),[m,y]=M.useState(!1),C=M.useRef(!1),S=M.useRef(null);S.current||(S.current=new Dr);const v=M.useCallback(async()=>{if(!(!n||n.length===0)&&S.current){p(!0);try{const x=r.route||{},w=new URLSearchParams(window.location.search),R=n.map(O=>{let j={...O};if(O.endpoint&&l){const F=l.resolveBindings(O.endpoint,r,{skipCache:!0});j.endpoint=F}if(O.params&&l){const F={};Object.entries(O.params).forEach(([G,P])=>{typeof P=="string"?F[G]=l.resolveBindings(P,r,{skipCache:!0}):F[G]=P}),j.params=F}return j});c&&Ri.log(`[ModalDataSourceWrapper] Modal "${e}" fetching data sources:`,R.map(O=>({id:O.id,endpoint:O.endpoint})));const L=await S.current.fetchDataSourcesWithResults(R,x,w);i&&L.forEach(O=>{if(O.state==="success"&&O.data!==void 0){const j=R.find(F=>F.id===O.id);if(j?.initGlobal){const F=O.data?.data??O.data,G=Array.isArray(j.initGlobal)?j.initGlobal:[j.initGlobal];for(const P of G)if(typeof P=="string")i({[P]:F}),c&&Ri.log(`[ModalDataSourceWrapper] Modal "${e}" initGlobal: ${O.id}.data -> _global.${P}`);else if(typeof P=="object"&&P.key){const{key:K,path:he}=P,Ee=he?NA(F,he):F;i({[K]:Ee}),c&&Ri.log(`Modal "${e}" initGlobal: ${O.id}.data${he?"."+he:""} -> _global.${K}`)}}}else O.state==="error"&&Ri.error(`Modal "${e}" data source error:`,O.id,O.error)}),c&&Ri.log(`Modal "${e}" data sources fetched successfully`)}catch(x){Ri.error(`Modal "${e}" data source fetch error:`,x)}finally{p(!1),y(!0)}}},[n,r,i,l,e,c]);return M.useEffect(()=>{if(!n||n.length===0)return;const x=window.__templateApp;return x?.registerModalDataSources&&x.registerModalDataSources(e,n),()=>{x?.unregisterModalDataSources&&x.unregisterModalDataSources(e)}},[e,n]),M.useEffect(()=>{!s&&C.current&&(y(!1),c&&Ri.log(`[ModalDataSourceWrapper] Modal "${e}" closed, reset fetch state`)),s&&!C.current&&n&&n.length>0&&!m&&v(),C.current=s},[s,n,m,v,e,c]),ft.jsx(ft.Fragment,{children:d})};class Wc extends Error{constructor(n,r,i={}){super(r);$(this,"code");$(this,"userMessageKey");$(this,"showStack");$(this,"icon");$(this,"recoverable");this.name="TemplateEngineError",this.code=n,this.userMessageKey=r,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(n,r){if(!r||!n)return this.userMessageKey;try{return r.translate(this.userMessageKey,n)}catch{return this.userMessageKey}}}class IA extends Wc{constructor(){super("TEMPLATE_NOT_FOUND","$t:core.errors.template_not_found",{showStack:!1,icon:"fa-paint-brush",recoverable:!1}),this.name="TemplateNotFoundError"}}function eb(s){if(s instanceof Wc)return s;if(s instanceof Error){const e=new Wc("TEMPLATE_INIT_ERROR",s.message||"$t:core.errors.template_init_error",{showStack:!0,icon:"fa-circle-exclamation",recoverable:!0});return e.stack=s.stack,e}return new Wc("TEMPLATE_INIT_ERROR","$t:core.errors.template_init_error",{showStack:!1,icon:"fa-circle-exclamation",recoverable:!0})}const jA=dt("ErrorDisplay");class Jf{static render(e,n){const r=document.getElementById(e);if(!r){jA.error(`Container #${e} not found`);return}const i=n.debug&&n.showStack&&n.stackTrace,l=window.matchMedia("(prefers-color-scheme: dark)").matches,c={container:` display: flex; align-items: center; justify-content: center; @@ -227,4 +270,4 @@ Error generating stack: `+u.message+` `:""} - `}static renderFromError(e,n,r,i=!1,l,c,d){let f,h;if(n.userMessageKey.startsWith("$t:"))if(c&&l)try{f=c.translate(n.userMessageKey,l)}catch{f=n.userMessageKey.replace("$t:","")}else f=n.userMessageKey.replace("$t:","");else f=n.userMessageKey;if(d){const m=d;m.details?.apiMessage?h=m.details.apiMessage:m.response?.data?.message&&(h=m.response.data.message)}this.render(e,{title:r,message:f,detailMessage:h,icon:n.icon,showStack:n.showStack,stackTrace:n.stack,showReloadButton:n.recoverable,debug:i})}static escapeHtml(e){if(!e)return"";const n=document.createElement("div");return n.textContent=e,n.innerHTML}}const _s=pt("Router");class Wx{constructor(e){M(this,"routes",[]);M(this,"templateIdentifier");M(this,"eventHandlers",new Map);M(this,"pendingNavigation",null);M(this,"isNavigating",!1);M(this,"handlePopState",()=>{this.navigateToCurrentPath()});this.templateIdentifier=e,this.initPopstateListener()}initPopstateListener(){window.addEventListener("popstate",this.handlePopState)}on(e,n){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(n)}async emit(e,...n){const r=this.eventHandlers.get(e);r&&await Promise.all(r.map(i=>i(...n)))}async loadRoutes(e){try{const n=e!==void 0&&e>0?e:null,r=await fetch(Ur(`/api/templates/${this.templateIdentifier}/routes`,"json",n));if(!r.ok)throw new Error(`Failed to load routes: ${r.statusText}`);const i=await r.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,_s.log(`Loaded ${this.routes.length} routes${e?` (v=${e})`:""}`);else throw new Error("Invalid routes data format")}catch(n){throw _s.error("Error loading routes:",n),n}}setRoutes(e){this.routes=e,_s.log(`Set ${this.routes.length} routes`)}match(e){const n=this.normalizePathname(e);for(const r of this.routes){const i=this.matchPattern(r.path,n);if(i!==null)return{route:r,params:i}}return null}normalizePathname(e){return e.length>1&&e.endsWith("/")?e.replace(/\/+$/,"")||"/":e}matchPattern(e,n){const r=[];let i=e.replace(/:([^/]+)/g,(f,h)=>(r.push(h),"([^/]+)"));i.startsWith("*/")&&(i="(?:/[^/]+)?"+i.slice(1)),i=i.replace(/\//g,"\\/");const l=new RegExp(`^${i}$`),c=n.match(l);if(!c)return null;const d={};return r.forEach((f,h)=>{d[f]=c[h+1]}),d}getRoutes(){return[...this.routes]}getAuthType(e,n){return e.auth_type?e.auth_type:n.startsWith("/admin")?"admin":"user"}async navigateToCurrentPath(){const e=window.location.pathname,n=window.location.search,r=this.match(e);if(!r){_s.warn(`No route matched for path: ${e}`),this.emit("routeNotFound",e);return}if(r.route.redirect){_s.log(`Redirecting from ${e} to ${r.route.redirect}`),this.navigate(r.route.redirect);return}if(r.route.auth_required){const c=this.getAuthType(r.route,e),d=Ar.getInstance();let f=d.isAuthenticated()&&d.getAuthType()===c;if(f||(f=await d.checkAuth(c)),!f){const h=d.getLoginRedirectUrl(c,e+n);_s.log(`Not authenticated, redirecting to: ${h}`),window.location.href=h;return}}const i=new URLSearchParams(n),l={};for(const c of i.keys()){if(c in l)continue;const d=i.getAll(c);d.length>1?l[c]=d:d.length===1&&(c.endsWith("[]")?l[c]=d:l[c]=d[0])}await this.emit("routeChange",{path:e,layout:r.route.layout,endpoint:r.route.endpoint,params:{...r.route.params||{},...r.params},query:l,auth_required:r.route.auth_required,auth_type:r.route.auth_type,meta:r.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 n=this.pendingNavigation;this.executeNavigation(n)}}}}const Yx=/^\/admin\/layout-editor\/([^/?#]+)\/?$/;function kb(s){const e=Yx.exec(s);return e?{templateIdentifier:e[1]}:null}const Wt=pt("ErrorPageHandler");class Xx{constructor(e){M(this,"templateId");M(this,"layoutLoader");M(this,"locale");M(this,"debug");M(this,"renderFunction");M(this,"dataSourceManager");M(this,"globalState");M(this,"errorConfig",null);M(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(Ur(`/api/templates/${this.templateId}/config`,"json"));if(!e.ok)return this.debug&&Wt.warn("Failed to load template config:",e.statusText),this.configLoaded=!0,null;const n=await e.json();if(!n.success||!n.data)return this.debug&&Wt.warn("Invalid template config response"),this.configLoaded=!0,null;const r=n.data;return!r.error_config||!r.error_config.layouts?(this.debug&&Wt.warn("No error_config found in template.json"),this.configLoaded=!0,null):(this.errorConfig=r.error_config,this.configLoaded=!0,this.debug&&Wt.log("Error config loaded:",this.errorConfig),this.errorConfig)}catch(e){return Wt.error("Failed to load error config:",e),this.configLoaded=!0,null}}async renderError(e,n="app"){try{const r=await this.loadConfig();if(!r)return this.debug&&Wt.warn("No error config available, cannot render error page"),!1;const i=r.layouts[e]||r.layouts[String(e)];if(!i)return this.debug&&Wt.warn(`No layout defined for error code: ${e}`),!1;this.debug&&Wt.log(`Loading error layout: ${i} for code: ${e}`);const l=await this.layoutLoader.loadLayout(this.templateId,i);if(!l)return this.debug&&Wt.error(`Failed to load error layout: ${i}`),!1;this.debug&&Wt.log("Error layout loaded:",l);let c={};const d=l.data_sources||[];if(d.length>0){this.debug&&Wt.log("Fetching data sources:",d.map(S=>S.id));const m=d.filter(S=>S.loading_strategy==="blocking"),y=d.filter(S=>!S.loading_strategy||S.loading_strategy==="progressive"),v=[...m,...y];if(v.length>0)try{c=await this.dataSourceManager.fetchDataSources(v,{},new URLSearchParams),this.debug&&Wt.log("Data sources fetched:",Object.keys(c))}catch(S){Wt.error("Failed to fetch data sources:",S)}}const f={};d.length>0&&(this.processInitOptions(d,c,f),this.debug&&Wt.log("initOptions processed:",{globalKeys:Object.keys(this.globalState),localKeys:Object.keys(f)}));const h={...c,errorCode:e,_global:{...this.globalState},_local:{...f}};return await this.renderFunction({containerId:n,layoutJson:l,dataContext:h,translationContext:{templateId:this.templateId,locale:this.locale}}),this.debug&&Wt.log(`Error page ${e} rendered successfully`),!0}catch(r){return Wt.error(`Failed to render error page ${e}:`,r),!1}}processInitOptions(e,n,r){for(const i of e){const l=n[i.id];if(!l)continue;const c=l?.data??l;if(i.initLocal){if(typeof i.initLocal=="string")r[i.initLocal]=c,Wt.log(`initLocal: ${i.id}.data -> _local.${i.initLocal}`);else if(typeof i.initLocal=="object"&&"key"in i.initLocal){const{key:d,path:f}=i.initLocal;r[d]=f?this.getValueByPath(c,f):c,Wt.log(`initLocal: ${i.id}.data${f?"."+f:""} -> _local.${d}`)}}if(i.initGlobal){const d=Array.isArray(i.initGlobal)?i.initGlobal:[i.initGlobal];for(const f of d)if(typeof f=="string")this.globalState[f]=c,Wt.log(`initGlobal: ${i.id}.data -> _global.${f}`);else if(typeof f=="object"&&f!==null&&"key"in f){const{key:h,path:m}=f;this.globalState[h]=m?this.getValueByPath(c,m):c,Wt.log(`initGlobal: ${i.id}.data${m?"."+m:""} -> _global.${h}`)}}}}getValueByPath(e,n){return n.split(".").reduce((r,i)=>r?.[i],e)}updateGlobalState(e){this.globalState={...this.globalState,...e}}updateLocale(e){this.locale=e,this.debug&&Wt.log("Locale updated:",e)}isConfigLoaded(){return this.configLoaded}async hasErrorLayout(e){const n=await this.loadConfig();return n?!!(n.layouts[e]||n.layouts[String(e)]):!1}clearConfigCache(){this.errorConfig=null,this.configLoaded=!1,this.debug&&Wt.log("Config cache cleared")}}const Kc=pt("AssetFailureNotice"),Rb="g7-asset-failure-notice",Jx="g7-system-banners",Kr=new Map;let As=!1,Wc=!1,Yo=null;function Ri(s,e,n){try{const r=window?.G7Core?.t;if(typeof r=="function"){const i=r(s,n);if(typeof i=="string"&&i!==s&&!i.startsWith("core.assets."))return i}}catch{}return Qx(e,n)}function Qx(s,e){return e?Object.entries(e).reduce((n,[r,i])=>n.split("{"+r+"}").join(String(i)),s):s}function xs(s){!s||!s.id||(Kr.set(s.id,s),Wc=!1,Kc.warn(`Asset failure notified: ${s.id} (${s.label})`),Ts())}function Db(s){Kr.delete(s)&&(Kc.log(`Asset failure cleared: ${s}`),Ts())}function Ob(){Kr.size!==0&&(Kr.clear(),Ts())}function Zx(){return Array.from(Kr.values())}function Lb(s,e,n){return Ri(s,e,n)}async function $b(){if(As)return;As=!0,Wc=!1,Ts();const s=Array.from(Kr.values()).filter(n=>typeof n.retry=="function");let e=!1;for(const n of s)try{await n.retry(),Kr.delete(n.id)}catch(r){e=!0,Kc.warn(`Asset retry failed: ${n.id}`,r)}As=!1,Wc=e,Ts()}function eT(){try{return document.documentElement.classList.contains("dark")}catch{return!1}}function Ts(){if(typeof document>"u"||!document.body)return;const s=document.getElementById(Rb);if(Kr.size===0){s?.remove(),oT();return}const e=s??tT();nT(e),e.replaceChildren(rT()),sT()}function tT(){const s=document.createElement("div");return s.id=Rb,s.setAttribute("role","alert"),s.setAttribute("aria-live","polite"),document.body.appendChild(s),s}function nT(s){const n=document.getElementById(Jx)?.offsetHeight??0;s.style.cssText=["position:fixed",`top:${n}px`,"left:0","right:0","z-index:9998","display:flex","justify-content:center","pointer-events:none"].join(";")}function rT(){const s=eT(),e=Array.from(Kr.values()),n=typeof window<"u"&&window.innerWidth<768,r=document.createElement("div");return r.style.cssText=["pointer-events:auto","box-sizing:border-box","width:100%","max-width:960px","margin:8px","padding:12px 16px","border-radius:8px",`border:1px solid ${s?"#78350f":"#fcd34d"}`,`background:${s?"#451a03":"#fffbeb"}`,`color:${s?"#fef3c7":"#78350f"}`,"box-shadow:0 4px 12px rgba(0,0,0,0.12)","font-size:14px","line-height:1.5","display:flex",n?"flex-direction:column":"flex-direction:row",n?"align-items:stretch":"align-items:center","gap:12px"].join(";"),r.style.background=s?"#451a03":"#fffbeb",r.style.color=s?"#fef3c7":"#78350f",r.style.borderColor=s?"#78350f":"#fcd34d",r.appendChild(aT(e,n)),r.appendChild(iT(e,n,s)),r}function aT(s,e){const n=document.createElement("div");n.style.cssText=["flex:1 1 auto","min-width:0","display:flex","gap:8px"].join(";");const r=document.createElement("span");r.setAttribute("aria-hidden","true"),r.textContent="⚠",r.style.cssText="flex:0 0 auto;font-size:16px;line-height:1.4",n.appendChild(r);const i=document.createElement("div");if(i.style.cssText="flex:1 1 auto;min-width:0",s.length===1){const l=s[0],c=document.createElement("div");c.setAttribute("data-asset-failure-id",l.id),c.textContent=l.message??Ri("core.assets.load_failed","{label}을(를) 불러오지 못했습니다.",{label:l.label}),i.appendChild(c)}else{const l=document.createElement("div");l.style.cssText="font-weight:600",l.textContent=Ri("core.assets.load_failed_multiple","{count}개 항목을 불러오지 못했습니다.",{count:s.length}),i.appendChild(l);const c=document.createElement("div");c.style.cssText="margin-top:2px;opacity:0.9;word-break:break-word",c.textContent=s.map(d=>d.label).join(", "),i.appendChild(c)}if(Wc){const l=document.createElement("div");l.style.cssText="margin-top:4px;font-weight:600",l.textContent=Ri("core.assets.retry_failed","다시 시도했지만 실패했습니다. 잠시 후 다시 시도해 주세요."),i.appendChild(l)}return n.appendChild(i),e&&(n.style.alignItems="flex-start"),n}function iT(s,e,n){const r=document.createElement("div");if(r.style.cssText=["flex:0 0 auto","display:flex","gap:8px",e?"width:100%":"","align-items:center"].filter(Boolean).join(";"),s.some(c=>typeof c.retry=="function")){const c=document.createElement("button");c.type="button",c.dataset.action="retry",c.disabled=As,c.textContent=As?Ri("core.assets.retrying","다시 시도 중..."):Ri("core.assets.retry","다시 시도"),c.style.cssText=[e?"flex:1 1 auto":"","padding:6px 14px","border-radius:6px","font-size:14px","font-weight:600","cursor:pointer",`border:1px solid ${n?"#b45309":"#d97706"}`,`background:${n?"#b45309":"#f59e0b"}`,`color:${n?"#fffbeb":"#451a03"}`,As?"opacity:0.6":""].filter(Boolean).join(";"),c.addEventListener("click",()=>{$b()}),r.appendChild(c)}const l=document.createElement("button");return l.type="button",l.dataset.action="close",l.setAttribute("aria-label",Ri("core.assets.close","닫기")),l.textContent="✕",l.style.cssText=["padding:6px 10px","border-radius:6px","font-size:14px","cursor:pointer","border:1px solid transparent","background:transparent",`color:${n?"#fef3c7":"#78350f"}`].join(";"),l.addEventListener("click",()=>{Ob()}),r.appendChild(l),r}function sT(){Yo||typeof MutationObserver>"u"||(Yo=new MutationObserver(()=>{Kr.size>0&&Ts()}),Yo.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}))}function oT(){Yo?.disconnect(),Yo=null}function lT(){const s=window,e=r=>({id:String(r?.id??""),label:String(r?.label??r?.url??"asset"),retry:typeof r?.retry=="function"?r.retry:void 0}),n=Array.isArray(s.__g7ExternalAssetFailures)?s.__g7ExternalAssetFailures:[];n.forEach(r=>{r?.id&&xs(e(r))}),s.__g7ExternalAssetSink=r=>{r?.id&&xs(e(r))},Kc.log(`템플릿 externals 실패 대기열 ${n.length}건 반영`)}const Rt=pt("ModuleAssetLoader");function cT(s){return s==="plugin"?Lb("core.assets.plugin_styles","플러그인 스타일"):Lb("core.assets.module_styles","모듈 스타일")}class uT{constructor(){M(this,"loadedAssets",new Map);M(this,"loadingPromises",new Map);M(this,"failedJsAssets",new Set);M(this,"failedCssAssets",new Set)}getFailedCssAssets(){return[...this.failedCssAssets]}hasFailedJsAssets(){return this.failedJsAssets.size>0}getFailedJsAssets(){return[...this.failedJsAssets]}async loadActiveExtensionAssets(e){if(!e||e.length===0){Rt.log("No module assets to load");return}const n=[...e].sort((d,f)=>d.priority-f.priority);Rt.log("Loading module assets:",n.map(d=>d.identifier));const r=n.filter(d=>d.css).map(d=>this.loadCSS(d.identifier,d.css)),i=n.filter(d=>d.js).map(d=>this.loadJS(d.identifier,d.js)),l=await Promise.allSettled([...r,...i]),c=l.filter(d=>d.status==="rejected");if(c.length>0){Rt.warn(`Some module assets failed to load (${c.length}/${l.length}); continuing with the rest`,this.getFailedJsAssets());return}Rt.log("All module assets loaded successfully")}async loadBundle(e,n,r){const i=[];if(r&&i.push(this.loadBundleCss(e,r)),n&&i.push(this.loadBundleJs(e,n)),i.length===0){Rt.log(`No bundle assets to load for: ${e}`);return}await Promise.all(i)}async loadCustomAssets(){const e=dT();if(e.length!==0)for(const n of e){const r=`g7-custom-${n.type}-${fT(n.id)}`;if(document.getElementById(r))continue;const i=`${n.type==="style"?"custom CSS":"custom JS"}: ${n.id}`,l=(d,f)=>n.type==="style"?ia(Ln(d),{id:r},{label:i,retries:f}):Cr(Ln(d),{id:r},{label:i,retries:f}),c=jd(n.url);try{if(c!==null)try{await l(n.url,0)}catch{Rt.warn(`Custom asset static miss, falling back to API: ${n.id} (${n.url} -> ${c})`),await l(c)}else await l(n.url);Rt.log(`Custom asset loaded: ${n.id}`)}catch(d){Rt.warn(`Failed to load custom asset: ${n.id} (${n.url})`,d),xs({id:`custom-asset:${n.id}`,label:n.id.split(":").pop()??n.id,retry:async()=>{document.getElementById(r)?.remove(),await l(c??n.url)}})}}}async loadBundleCss(e,n){const r=`ext-bundle-css-${e}`;if(document.getElementById(r)){Rt.log(`Bundle CSS already loaded: ${e}`);return}const i=jd(n);try{if(i!==null)try{await ia(n,{id:r},{label:`bundle CSS: ${e}`,retries:0})}catch{Rt.warn(`Bundle CSS static miss, falling back to API: ${e} (${n} -> ${i})`),await ia(Ln(i),{id:r},{label:`bundle CSS: ${e}`})}else await ia(n,{id:r},{label:`bundle CSS: ${e}`});Rt.log(`Bundle CSS loaded: ${e}`);const l=document.getElementById(r);l&&this.registerLoadedAsset(`bundle-${e}`,{type:"css",element:l})}catch(l){this.surfaceCssFailure(`bundle-${e}`,cT(e),i!==null?Ln(i):n,l)}}async loadBundleJs(e,n){const r=`ext-bundle-js-${e}`;if(document.getElementById(r)){Rt.log(`Bundle JS already loaded: ${e}`);return}const i=this.loadingPromises.get(r);if(i)return Rt.log(`Bundle JS already loading: ${e}`),i;const l=jd(n),d=(l!==null?Cr(n,{id:r},{label:`bundle JS: ${e}`,retries:0}).catch(()=>(Rt.warn(`Bundle JS static miss, falling back to API: ${e} (${n} -> ${l})`),Cr(Ln(l),{id:r},{label:`bundle JS: ${e}`}))):Cr(n,{id:r},{label:`bundle JS: ${e}`})).then(()=>{Rt.log(`Bundle JS loaded: ${e}`);const f=document.getElementById(r);f&&this.registerLoadedAsset(`bundle-${e}`,{type:"js",element:f}),this.loadingPromises.delete(r)}).catch(f=>{throw Rt.warn(`Failed to load bundle JS: ${e} (${n})`,f),this.failedJsAssets.add(e),this.loadingPromises.delete(r),f});return this.loadingPromises.set(r,d),d}async loadCSS(e,n){const r=`module-css-${e}`;if(document.getElementById(r)){Rt.log(`CSS already loaded: ${e}`);return}const i=this.loadingPromises.get(r);if(i)return Rt.log(`CSS already loading: ${e}`),i;const l=ia(n,{id:r},{label:`CSS: ${e}`}).then(()=>{Rt.log(`CSS loaded: ${e}`);const c=document.getElementById(r);c&&this.registerLoadedAsset(e,{type:"css",element:c}),this.loadingPromises.delete(r)}).catch(c=>{this.loadingPromises.delete(r),this.surfaceCssFailure(e,e,n,c)});return this.loadingPromises.set(r,l),l}surfaceCssFailure(e,n,r,i){Rt.warn(`Failed to load CSS after retries: ${e} (${r})`,i),this.failedCssAssets.add(e),xs({id:`ext-css:${e}`,label:n,retry:async()=>{document.getElementById(`module-css-${e}`)?.remove(),document.getElementById(`ext-bundle-css-${e.replace(/^bundle-/,"")}`)?.remove(),await ia(r,{},{label:`CSS retry: ${e}`}),this.failedCssAssets.delete(e)}})}async loadJS(e,n){const r=`module-js-${e}`;if(document.getElementById(r)){Rt.log(`JS already loaded: ${e}`);return}const i=this.loadingPromises.get(e);if(i)return Rt.log(`JS already loading: ${e}`),i;const l=Cr(n,{id:r},{label:`JS: ${e}`}).then(()=>{Rt.log(`JS loaded: ${e}`);const c=document.getElementById(r);c&&this.registerLoadedAsset(e,{type:"js",element:c}),this.loadingPromises.delete(e)}).catch(c=>{throw Rt.warn(`Failed to load JS: ${e} (${n})`,c),this.failedJsAssets.add(e),this.loadingPromises.delete(e),c});return this.loadingPromises.set(e,l),l}registerLoadedAsset(e,n){const r=this.loadedAssets.get(e)||[];r.push(n),this.loadedAssets.set(e,r)}unloadExtensionAsset(e){const n=this.loadedAssets.get(e);if(!n||n.length===0){Rt.log(`No assets to unload for: ${e}`);return}n.forEach(r=>{r.element.parentNode&&(r.element.parentNode.removeChild(r.element),Rt.log(`${r.type.toUpperCase()} unloaded: ${e}`))}),this.loadedAssets.delete(e),Rt.log(`All assets unloaded for: ${e}`)}unloadAllAssets(){Array.from(this.loadedAssets.keys()).forEach(n=>{this.unloadExtensionAsset(n)}),Rt.log("All module assets unloaded")}isLoaded(e){return this.loadedAssets.has(e)}getLoadedModules(){return Array.from(this.loadedAssets.keys())}}let dh=null;function dT(){const s=window?.G7Config?.customAssets;return Array.isArray(s)?s.filter(e=>e&&typeof e.id=="string"&&typeof e.url=="string"&&(e.type==="style"||e.type==="script")):[]}function fT(s){return s.replace(/[^A-Za-z0-9_-]/g,"-")}function fh(){return dh||(dh=new uT),dh}function hT(){if(typeof window>"u")return[];const s=window.G7Config;if(!s?.moduleAssets)return[];const e=[];for(const[n,r]of Object.entries(s.moduleAssets)){const i=r;e.push({identifier:n,js:i.js?Ln(i.js):i.js,css:i.css?Ln(i.css):i.css,priority:i.priority,external:i.external})}return e}function pT(){if(typeof window>"u")return null;const s=window.G7Config;if(!s?.bundleUrls)return null;const e=s.bundleUrls;return{moduleJs:e.moduleJs?Ln(e.moduleJs):e.moduleJs,moduleCss:e.moduleCss?Ln(e.moduleCss):e.moduleCss,pluginJs:e.pluginJs?Ln(e.pluginJs):e.pluginJs,pluginCss:e.pluginCss?Ln(e.pluginCss):e.pluginCss}}function gT(){if(typeof window>"u")return[];const s=window.G7Config;if(!s?.pluginAssets)return[];const e=[];for(const[n,r]of Object.entries(s.pluginAssets)){const i=r;e.push({identifier:n,js:i.js?Ln(i.js):i.js,css:i.css?Ln(i.css):i.css,priority:i.priority,external:i.external})}return e}const hh=pt("SystemBannerManager");class Yc{static show(e){this.banners.set(e.id,e),this.render(),hh.log(`Banner shown: ${e.id}`)}static hide(e){this.banners.delete(e)&&(this.render(),hh.log(`Banner hidden: ${e}`))}static hideAll(){this.banners.clear(),this.render(),hh.log("All banners hidden")}static detectLocale(){try{const n=window.G7Core;if(n?.locale?.current)return n.locale.current()}catch{}return(navigator.language||"ko").split("-")[0]}static resolveMessage(e,n){return typeof e=="string"?e:e[n]||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 n=Array.from(this.banners.values()).sort((i,l)=>(i.order??0)-(l.order??0)),r=this.detectLocale();e.innerHTML=n.map(i=>{const l=this.resolveMessage(i.message,r),c=i.background||"#f59e0b",d=i.color||"white";return`
${l}
`}).join(""),requestAnimationFrame(()=>{e&&this.adjustAppPadding(e.offsetHeight)})}static adjustAppPadding(e){const n=document.getElementById("app");n&&(n.style.paddingTop=e>0?`${e}px`:"")}}M(Yc,"banners",new Map),M(Yc,"containerId","g7-system-banners");const U=pt("TemplateApp");function Mb(s){const e={};for(const n of s.keys()){if(n in e)continue;const r=s.getAll(n);r.length>1?e[n]=r:r.length===1&&(n.endsWith("[]")?e[n]=r:e[n]=r[0])}return e}const Lr=class Lr{constructor(e){M(this,"router",null);M(this,"layoutLoader",null);M(this,"errorPageHandler",null);M(this,"config");M(this,"globalState");M(this,"globalStateListeners",new Set);M(this,"currentRouteChangeId",0);M(this,"failedLayoutScripts",new Set);M(this,"currentDataSources",[]);M(this,"currentRawDataSources",[]);M(this,"currentRouteParams",{});M(this,"currentQueryParams",new URLSearchParams);M(this,"currentFetchedData",{});M(this,"currentLayoutName","");M(this,"templateErrorHandling",null);M(this,"currentWebSocketSubscriptions",[]);M(this,"extensionCacheVersion",0);M(this,"currentGlobalHeaders",[]);M(this,"transitionOverlayEl",null);M(this,"skeletonOverlayRoot",null);M(this,"skeletonOverlayContainer",null);M(this,"_spinnerState",null);M(this,"modalDataSources",new Map);this.globalState={sidebarOpen:!1},this.loadG7Config(),this.migrateLocaleStorage();const n=this.loadLocaleFromStorage(),r=n||e.locale||"ko";this.config={...e,locale:r},!n&&e.locale&&this.saveLocaleToStorage(e.locale)}loadG7Config(){if(typeof window<"u"&&window.G7Config){const e=window.G7Config;e.settings&&(this.globalState.settings=e.settings,U.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,U.log("Loaded plugin settings from G7Config:",Object.keys(e.plugins))),e.modules&&(this.globalState.modules=e.modules,U.log("Loaded module settings from G7Config:",Object.keys(e.modules))),e.appConfig&&(this.globalState.appConfig=e.appConfig,U.log("Loaded appConfig from G7Config:",Object.keys(e.appConfig)))}}resolveRouteExpressions(e){const n=new $n,r={_global:this.globalState};return e.map(i=>{const l={...i};if(l.path&&l.path.includes("{{")){const c=l.path;l.path=n.resolveBindings(l.path,r),l.path=l.path.replace(/\/\/+/g,"/")||"/",l.path.includes("{{")&&(U.warn("Route expression resolution failed, using fallback:",c),l.path=c.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}if(l.redirect&&l.redirect.includes("{{")){const c=l.redirect;l.redirect=n.resolveBindings(l.redirect,r),l.redirect=l.redirect.replace(/\/\/+/g,"/")||"/",l.redirect.includes("{{")&&(U.warn("Route redirect expression resolution failed:",c),l.redirect=c.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}return l})}migrateLocaleStorage(){const e=["locale","g7_template_locale"];for(const n of e)try{const r=localStorage.getItem(n);r&&r!==localStorage.getItem(Lr.LOCALE_STORAGE_KEY)&&(localStorage.setItem(Lr.LOCALE_STORAGE_KEY,r),U.log(`Migrated locale from '${n}' to '${Lr.LOCALE_STORAGE_KEY}'`)),localStorage.removeItem(n)}catch(r){U.warn(`Failed to migrate locale key '${n}':`,r)}}async init(){try{po.getInstance().setDebug(this.config.debug),U.log("Initializing with config:",this.config),S0();const e=Er.getInstance(),n=Ar.getInstance(),r=typeof window<"u"&&Number(window.G7Config?.cache_version)||0,i=r>0?r:this.loadCacheVersionFromStorage()||0,[l,c,d,f,h]=await Promise.all([tl({templateId:this.config.templateId,templateType:this.config.templateType,locale:this.config.locale,debug:this.config.debug,cacheVersion:i}),e.loadComponents(this.config.templateId,this.config.templateType,i),rc(i>0?go(`templates/${this.config.templateId}/routes.json`,i):null,Ur(`/api/templates/${this.config.templateId}/routes`,"json",i>0?i:null),{label:"routes.json"}).then(A=>{if(!A.ok)throw new Error(`Failed to load routes: ${A.statusText}`);return A.json()}).then(A=>{if(!A.success)throw new Error("Failed to load routes from API");return A.data}).catch(A=>{throw U.error("Error loading routes:",A),A}),n.preloadAuth(this.config.templateType==="admin"?"admin":"user"),fetch(Ur(`/api/templates/${this.config.templateId}/config`,"json")).then(A=>A.ok?A.json():null).then(A=>!A?.success||!A?.data?null:A.data).catch(A=>(U.warn("Error loading template config:",A),null))]);if(U.log("Template Engine initialized"),U.log("ComponentRegistry loaded"),U.log("Routes data loaded"),U.log("User info preloaded"),U.log("Template config loaded:",h),h?.cache_version!==void 0){const A=i>0?i:null;if(this.extensionCacheVersion=h.cache_version,this.saveCacheVersionToStorage(this.extensionCacheVersion),U.log("Extension cache version:",this.extensionCacheVersion),A!==null&&A!==this.extensionCacheVersion){U.log("Cache version changed, reloading routes...");const D=await rc(go(`templates/${this.config.templateId}/routes.json`,this.extensionCacheVersion),Ur(`/api/templates/${this.config.templateId}/routes`,"json",this.extensionCacheVersion),{label:"routes.json (reload)"}).then(O=>{if(!O.ok)throw new Error(`Failed to reload routes: ${O.statusText}`);return O.json()}).then(O=>{if(!O.success)throw new Error("Failed to reload routes from API");return O.data});Array.isArray(D.routes)&&(D.routes=this.resolveRouteExpressions(D.routes),Object.assign(d,D),U.log("Routes reloaded with new cache version"));try{const{TranslationEngine:O}=await Promise.resolve().then(()=>Jg),k=O.getInstance();k.setCacheVersion(this.extensionCacheVersion);const L=this.config.locale||"ko",B="en";await k.loadTranslations(this.config.templateId,L,"/api",!0),L!==B&&await k.loadTranslations(this.config.templateId,B,"/api",!0),U.log("Translations reloaded with new cache version")}catch(O){U.error("Failed to reload translations:",O)}}}h?.errorHandling&&(this.templateErrorHandling=h.errorHandling,Tr().setTemplateConfig(this.templateErrorHandling),U.log("Template errorHandling registered:",this.templateErrorHandling)),n.on("logout",()=>{U.log("User logged out")}),n.on("authStateChange",A=>{U.log("Auth state changed:",A)}),U.log("AuthManager event handlers registered");const m=qr(),y=this.config.templateType==="admin"?"admin":"user",v=n.getConfig(y);m.setOnUnauthorized(()=>{U.log("Unauthorized - redirecting to login page"),m.removeToken();const A=window.location.pathname+window.location.search,D=n.getLoginRedirectUrl(y,A,"session_expired");window.location.href=D}),U.log("ApiClient onUnauthorized callback registered"),this.layoutLoader=new ah(e),this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),U.log("LayoutLoader initialized:",this.layoutLoader);const S=new Dr({onUnauthorized:()=>{U.warn("Unauthorized request in error page")}});if(this.errorPageHandler=new Xx({templateId:this.config.templateId,layoutLoader:this.layoutLoader,locale:this.config.locale,debug:this.config.debug,renderFunction:Rs,dataSourceManager:S,globalState:this.globalState}),U.log("ErrorPageHandler initialized with DataSourceManager"),await this.handleServerError()){U.log("Server error handled, skipping normal initialization");return}if(this.router=new Wx(this.config.templateId),Array.isArray(d.routes)){const A=this.resolveRouteExpressions(d.routes);this.router.setRoutes(A)}else throw new Error("Invalid routes data format");U.log("Router initialized:",this.router),U.log("Routes set:",this.router.getRoutes());const{getActionDispatcher:_}=await Promise.resolve().then(()=>Wr),x=_();if(x&&(x.setDefaultContext({navigate:A=>this.router?.navigate(A)}),x.setGlobalStateUpdater((A,D)=>this.setGlobalState(A,D)),U.log("Navigate function and setGlobalState injected to ActionDispatcher")),await this.loadExtensionAssets(),this.reinitializeTemplateHandlers(),this.router.on("routeChange",A=>this.handleRouteChange(A)),this.router.on("routeNotFound",A=>this.handleRouteNotFound(A)),typeof window<"u"&&kb(window.location.pathname)){U.log("Layout editor mode detected — skipping router match"),await Rs({containerId:"app",layoutJson:{components:[]},dataContext:{},translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),U.log("Template App initialized in layout editor mode");return}this.router.navigateToCurrentPath(),U.log("Template App initialized successfully")}catch(e){U.error("Initialization failed:",e),this.showInitError(e)}}async loadExtensionAssets(){try{const e=fh(),n=pT();if(!n){await this.loadExtensionAssetsIndividually(),await e.loadCustomAssets();return}await e.loadBundle("module",n.moduleJs,n.moduleCss),await e.loadBundle("plugin",n.pluginJs,n.pluginCss),await e.loadCustomAssets(),U.log("Extension bundle assets loaded successfully")}catch(e){U.warn("Failed to load extension assets:",e)}}async loadExtensionAssetsIndividually(){const e=fh(),n=hT();n.length>0&&(U.log("Loading module assets (individual fallback):",n.map(i=>i.identifier)),await e.loadActiveExtensionAssets(n));const r=gT();r.length>0&&(U.log("Loading plugin assets (individual fallback):",r.map(i=>i.identifier)),await e.loadActiveExtensionAssets(r))}async handleRouteChange(e){const n=++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(U.log("Route changed:",e,"requestId:",n),!this.layoutLoader)throw new Error("LayoutLoader is not initialized");if(!e.layout)throw new Error("Route layout is not defined");let r=e.layout;const i=r==="__preview__";i&&e.params?.token&&(r=`__preview__/${e.params.token}`);const l=await this.layoutLoader.loadLayout(this.config.templateId,r);if(n!==this.currentRouteChangeId){U.log("Route change cancelled (newer request exists):",n);return}U.log("Layout loaded:",l);const c=Tr();l.errorHandling?(c.setLayoutConfig(l.errorHandling),U.log("Layout errorHandling registered:",l.errorHandling)):c.clearLayoutConfig();const d=l.data_sources||[],f=e.query||{},h=new URLSearchParams;for(const[ee,me]of Object.entries(f))if(Array.isArray(me))for(const H of me)h.append(ee,H);else h.set(ee,me);const m={route:e.params||{},query:f,_global:this.globalState};l.scripts&&Array.isArray(l.scripts)&&await this.loadLayoutScripts(l.scripts,m);const{DataSourceManager:y,getActionDispatcher:v}=await Promise.resolve().then(()=>Wr),S=new y;if(i){const ee=v();ee&&ee.setPreviewMode(!0),this.setGlobalState({__isPreview:!0}),Yc.show({id:"preview-mode",message:{ko:"⚠ 미리보기 모드 — 페이지 이동이 비활성화됩니다",en:"⚠ Preview Mode — Navigation is disabled"},background:"linear-gradient(90deg, #f59e0b, #d97706)",color:"white"}),U.log("Preview mode activated")}else{const ee=v();ee?.isPreviewMode()&&(ee.setPreviewMode(!1),Yc.hide("preview-mode"))}if(this.currentGlobalHeaders=l.globalHeaders||[],this.currentGlobalHeaders.length>0){S.setGlobalHeaders(this.currentGlobalHeaders);const ee=v();ee&&ee.setGlobalHeaders(this.currentGlobalHeaders),U.log("globalHeaders set:",this.currentGlobalHeaders.map(me=>me.pattern))}if(l.named_actions&&Object.keys(l.named_actions).length>0){const ee=v();ee&&ee.setNamedActions(l.named_actions)}const _=S.filterByCondition(d,m);d.length!==_.length&&U.log("Data sources filtered by condition:",{before:d.map(ee=>ee.id),after:_.map(ee=>ee.id)});const x=_.filter(ee=>ee.loading_strategy==="blocking"),A=_.filter(ee=>(ee.loading_strategy||"progressive")!=="blocking"&&ee.type!=="websocket"),D=Array.isArray(l.transition_overlay?.wait_for)?l.transition_overlay.wait_for:[],O=D.length>0&&_.some(ee=>D.includes(ee.id)&&ee.type!=="websocket"&&(ee.loading_strategy||"progressive")!=="background");if((x.length>0||O)&&l.transition_overlay){const ee=typeof l.transition_overlay=="boolean"?{enabled:l.transition_overlay,style:"opaque"}:l.transition_overlay;ee.enabled&&ee.style==="skeleton"&&ee.skeleton?.component&&ee.target?this.renderSkeletonOverlay(ee.target,ee.skeleton,l,ee.fallback_target):ee.enabled&&ee.style==="spinner"&&ee.target&&this.renderSpinnerOverlay(ee.target,ee.spinner,ee.fallback_target)}let k={},L={},B={},q={};this.currentWebSocketSubscriptions.length>0&&(U.log("Unsubscribing previous WebSocket subscriptions:",this.currentWebSocketSubscriptions),S.unsubscribeWebSockets(this.currentWebSocketSubscriptions),this.currentWebSocketSubscriptions=[]),this.currentDataSources=_,this.currentRawDataSources=d,this.currentRouteParams=e.params||{},this.currentQueryParams=h,U.log(`handleRouteChange #${n} - queryObject:`,f),U.log(`handleRouteChange #${n} - queryParams:`,h.toString()),x.length>0&&(U.log("Fetching blocking data sources:",x.map(me=>me.id)),(await S.fetchDataSourcesWithResults(x,e.params||{},h)).forEach(me=>{if(me.state==="success"&&me.data!==void 0)k[me.id]=me.data;else if(me.state==="error"&&me.error){const H=me.error,T=H.response?.data?.message;L[me.id]={message:T||me.error.message,status:H.response?.status||H.status}}}),this.processInitOptions(x,k,B,q),this.currentFetchedData={...k},U.log("Blocking data loaded:",Object.keys(k)),Object.keys(L).length>0&&U.log("Data source errors:",L),Object.keys(B).length>0&&U.log("Local state init (blocking):",Object.keys(B)),Object.keys(q).length>0&&U.log("Isolated state init (blocking):",Object.keys(q)));const z=A.length>0;if(z&&(Gr.setPending(!0),U.log("Transition started before rendering")),n!==this.currentRouteChangeId){U.log("Route change cancelled after blocking data (newer request exists):",n);return}const{getState:W}=await Promise.resolve().then(()=>Wr),de=W().currentDataContext||{},_e=A.map(ee=>ee.id),Se={};if(z){_e.forEach(me=>{de[me]!==void 0?Se[me]=de[me]:Se[me]=void 0});const ee=Object.keys(Se).filter(me=>Se[me]!==void 0);ee.length>0&&U.log("Preserving previous progressive data:",ee),U.log("Progressive data sources initialized:",_e)}const Ie=l.defines||{},Fe={...Se,...e.params,...k,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState},_globalSetState:ee=>this.setGlobalState(ee),_dataSourceErrors:Object.keys(L).length>0?L:void 0,_localInit:Object.keys(B).length>0?B:void 0,_isolatedInit:Object.keys(q).length>0?q:void 0,_defines:Object.keys(Ie).length>0?Ie:void 0};if(l.computed&&Object.keys(l.computed).length>0){const ee=this.calculateComputed(l.computed,Fe);Object.keys(ee).length>0&&(Fe._computed=ee,this.globalState._computed=ee,U.log("Computed values calculated:",Object.keys(ee))),Fe._computedDefinitions=l.computed}const ze=l.layout_name||e.layout;this.currentLayoutName!==""&&this.currentLayoutName!==ze&&(U.log("_local reset due to layout change:",{from:this.currentLayoutName,to:ze}),this.globalState._local={},u_()),this.currentLayoutName=ze;const Q=l.initLocal||l.state;if(Q&&Object.keys(Q).length>0){this.globalState._local||(this.globalState._local={});for(const[ee,me]of Object.entries(Q))this.globalState._local[ee]===void 0&&(this.globalState._local[ee]=JSON.parse(JSON.stringify(me)));Fe._local={...this.globalState._local},U.log("initLocal applied to _local:",Object.keys(Q))}if(l.initGlobal&&Object.keys(l.initGlobal).length>0){for(const[ee,me]of Object.entries(l.initGlobal))this.globalState[ee]===void 0&&(this.globalState[ee]=JSON.parse(JSON.stringify(me)));U.log("initGlobal applied to _global:",Object.keys(l.initGlobal))}if(l.initIsolated&&Object.keys(l.initIsolated).length>0){for(const[ee,me]of Object.entries(l.initIsolated))q[ee]===void 0&&(q[ee]=JSON.parse(JSON.stringify(me)));U.log("initIsolated applied:",Object.keys(l.initIsolated))}Fe._global={...this.globalState,layoutWarnings:l.warnings||[]};const ue=l.initActions||l.init_actions;if(ue&&ue.length>0){await this.executeInitActions(ue,Fe),U.log("initActions executed before render");const ee=this.globalState;if(ee._local){if(Object.keys(B).length>0){for(const[me,H]of Object.entries(B))ee._local[me]!==void 0?ee._local[me]=this.deepMerge(ee._local[me],H):ee._local[me]=H;U.log("localInit merged into _local after initActions:",Object.keys(B))}Fe._local=ee._local,U.log("_local merged into dataContext:",ee._local)}if(Fe._global={...this.globalState,layoutWarnings:l.warnings||[]},U.log("_global merged into dataContext after initActions"),l.computed&&Object.keys(l.computed).length>0){const me=this.calculateComputed(l.computed,Fe);Object.keys(me).length>0&&(Fe._computed=me,this.globalState._computed=me,U.log("Computed values recalculated after init_actions:",Object.keys(me)))}if(Object.keys(this.currentFetchedData).length>0){for(const[me,H]of Object.entries(this.currentFetchedData))Fe[me]=H;U.log("Fetched data sources merged into dataContext after initActions:",Object.keys(this.currentFetchedData))}}if(l.transition_overlay&&!this.skeletonOverlayContainer&&this.showTransitionOverlay(l.transition_overlay,l),await Rs({containerId:"app",layoutJson:l,dataContext:Fe,translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),U.log("Initial render complete with blocking data"),this.reattachSpinnerOverlay(),A.length>0){if(n!==this.currentRouteChangeId){U.log("Route change cancelled before progressive fetch (newer request exists):",n),Gr.setPending(!1),this.hideTransitionOverlay();return}U.log("Fetching progressive/background data sources:",A.map(H=>H.id));const{updateTemplateData:ee,getState:me}=await Promise.resolve().then(()=>Wr);try{const H=A.map(async T=>{try{const he=(await S.fetchDataSourcesWithResults([T],e.params||{},h,this.globalState))[0];if(!he){U.log(`Data source ${T.id} skipped (no fetch result)`);return}if(n!==this.currentRouteChangeId){U.log(`Data source ${T.id} fetch cancelled (newer request exists)`);return}if(he.state==="success"&&he.data!==void 0){U.log(`Progressive data source loaded: ${T.id}`),this.currentFetchedData[T.id]=he.data;const Ae={};this.processInitOptions([T],{[T.id]:he.data},Ae);const se=me();if(se.bindingEngine){const $e=[T.id];T.initGlobal&&$e.push("_global"),T.initLocal&&$e.push("_local"),se.bindingEngine.invalidateCacheByKeys($e)}const ge={[T.id]:he.data};Object.keys(Ae).length>0&&(ge._localInit=Ae,Object.assign(B,Ae)),T.initGlobal&&(ge._global={...this.globalState}),ee(ge)}else if(he.state==="error"&&he.error){const Ae=he.error,se=Ae.response?.data?.message;L[T.id]={message:se||he.error.message,status:Ae.response?.status||Ae.status},U.log(`Progressive data source error: ${T.id}`,L[T.id]),ee({[T.id]:null,_dataSourceErrors:{...L}})}}catch(fe){U.error(`Failed to fetch data source: ${T.id}`,fe)}});if(await Promise.all(H),n!==this.currentRouteChangeId){U.log("Route change cancelled after progressive fetch (newer request exists):",n);return}U.log("All progressive data sources loaded")}finally{Gr.setPending(!1),this.hideTransitionOverlay()}}else this.hideTransitionOverlay();const De=_.filter(ee=>ee.type==="websocket");if(De.length>0){U.log("Subscribing WebSocket data sources:",De.map(T=>T.id));const{updateTemplateData:ee,getState:me}=await Promise.resolve().then(()=>Wr),H={...this.currentFetchedData,...e.params,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState}};U.log("WebSocket binding context keys:",Object.keys(H)),this.currentWebSocketSubscriptions=S.subscribeWebSockets(_,(T,fe)=>{U.log(`WebSocket data received for: ${T}`,fe),this.currentFetchedData[T]=fe;const he=_.find($e=>$e.id===T),Ae=me();if(Ae.bindingEngine){const $e=[T];he?.initGlobal&&$e.push("_global"),he?.initLocal&&$e.push("_local"),Ae.bindingEngine.invalidateCacheByKeys($e)}ee({[T]:fe});const ge=_.find($e=>$e.type==="websocket"&&($e.target_source||$e.id)===T)?.onReceive;Array.isArray(ge)&&ge.length>0&&window.G7Core?.dispatch&&(async()=>{for(const Te of ge)try{const je=this.getActionDispatcher?.();je&&await je.dispatchAction(Te,{navigate:this.getRouter?.()?(xt,rt)=>this.getRouter().navigate(xt,rt):void 0,setState:xt=>this.setGlobalState(xt),state:this.globalState,data:{...this.globalState,$args:[fe],$event:fe},_isDispatchFallbackContext:!0})}catch(je){U.error(`WebSocket onReceive action failed for ${T}:`,je)}})()},H),U.log("WebSocket subscriptions established:",this.currentWebSocketSubscriptions)}U.log("Layout rendered successfully")}catch(r){U.error("Route change handling failed:",r),this.hideTransitionOverlay(),this.showRouteError(r)}}processInitOptions(e,n,r,i){e.some(c=>c.refetchOnMount===!0&&c.initLocal)&&(r._forceLocalInit=Date.now(),U.log("refetchOnMount detected, forcing local state init")),e.forEach(c=>{const d=n[c.id];if(!d)return;const f=d.data??d;if(c.initLocal){if(typeof c.initLocal=="string"){let h=f;if(c.initLocalDefaults&&typeof c.initLocalDefaults=="object"){const y=this.evaluateDefaults(c.initLocalDefaults,n);h={...y,...f},U.log(`initLocalDefaults applied for ${c.initLocal}:`,Object.keys(y))}const m=this.globalState._local?.[c.initLocal];m!==void 0&&typeof m=="object"&&typeof h=="object"?(r[c.initLocal]=this.deepMerge(m,h),U.log(`initLocal (merged): ${c.id}.data -> _local.${c.initLocal}`)):(r[c.initLocal]=h,U.log(`initLocal: ${c.id}.data -> _local.${c.initLocal}`))}else if(typeof c.initLocal=="object"&&c.initLocal.key){const{key:h,path:m}=c.initLocal;let y=m?this.extractValueByPathOrExpression(f,m,c.id):f;if(c.initLocalDefaults&&typeof c.initLocalDefaults=="object"){const S=this.evaluateDefaults(c.initLocalDefaults,n);y={...S,...y},U.log(`initLocalDefaults applied for ${h}:`,Object.keys(S))}const v=this.globalState._local?.[h];v!==void 0&&typeof v=="object"&&typeof y=="object"?(r[h]=this.deepMerge(v,y),U.log(`initLocal (merged): ${c.id}.data${m?"."+m:""} -> _local.${h}`)):(r[h]=y,U.log(`initLocal: ${c.id}.data${m?"."+m:""} -> _local.${h}`))}else if(typeof c.initLocal=="object"){const h=c.initLocal._merge||"deep",m=this.flattenNestedObjectToMappings(c.initLocal);for(const{targetPath:y,sourcePath:v}of m){const S=this.extractValueByPathOrExpression(f,v,c.id);if(y.includes(".")){const _=y.split(".")[0];r[_]===void 0&&this.globalState._local?.[_]!==void 0&&(r[_]=JSON.parse(JSON.stringify(this.globalState._local[_]))),this.setValueAtPath(r,y,S,h),U.log(`initLocal map (${h}): ${c.id} ${v} -> _local.${y}`)}else{const _=this.globalState._local?.[y];h==="replace"?(r[y]=S,U.log(`initLocal map (replace): ${c.id} ${v} -> _local.${y}`)):h==="shallow"?_!==void 0&&typeof _=="object"&&typeof S=="object"?(r[y]={..._,...S},U.log(`initLocal map (shallow): ${c.id} ${v} -> _local.${y}`)):(r[y]=S,U.log(`initLocal map: ${c.id} ${v} -> _local.${y}`)):_!==void 0&&typeof _=="object"&&typeof S=="object"?(r[y]=this.deepMerge(_,S),U.log(`initLocal map (deep): ${c.id} ${v} -> _local.${y}`)):(r[y]=S,U.log(`initLocal map: ${c.id} ${v} -> _local.${y}`))}}}}if(c.initGlobal)if(typeof c.initGlobal=="object"&&!Array.isArray(c.initGlobal)&&!("key"in c.initGlobal))for(const[m,y]of Object.entries(c.initGlobal)){if(typeof y!="string"){U.warn(`initGlobal map value must be string, got ${typeof y} for key ${m}`);continue}const v=this.extractValueByPathOrExpression(f,y,c.id),S=this.globalState[m];S!==void 0&&typeof S=="object"&&typeof v=="object"?(this.globalState[m]=this.deepMerge(S,v),U.log(`initGlobal map (merged): ${c.id} ${y} -> _global.${m}`)):(this.globalState[m]=v,U.log(`initGlobal map: ${c.id} ${y} -> _global.${m}`))}else{const m=Array.isArray(c.initGlobal)?c.initGlobal:[c.initGlobal];for(const y of m)if(typeof y=="string"){const v=this.globalState[y];v!==void 0&&typeof v=="object"&&typeof f=="object"?(this.globalState[y]=this.deepMerge(v,f),U.log(`initGlobal (merged): ${c.id}.data -> _global.${y}`)):(this.globalState[y]=f,U.log(`initGlobal: ${c.id}.data -> _global.${y}`))}else if(typeof y=="object"&&y.key){const{key:v,path:S}=y,_=S?this.extractValueByPathOrExpression(f,S,c.id):f,x=this.globalState[v];x!==void 0&&typeof x=="object"&&typeof _=="object"?(this.globalState[v]=this.deepMerge(x,_),U.log(`initGlobal (merged): ${c.id}.data${S?"."+S:""} -> _global.${v}`)):(this.globalState[v]=_,U.log(`initGlobal: ${c.id}.data${S?"."+S:""} -> _global.${v}`))}}if(i&&c.initIsolated){if(typeof c.initIsolated=="string"){const h=i[c.initIsolated];h!==void 0&&typeof h=="object"&&typeof f=="object"?(i[c.initIsolated]=this.deepMerge(h,f),U.log(`initIsolated (merged): ${c.id}.data -> _isolated.${c.initIsolated}`)):(i[c.initIsolated]=f,U.log(`initIsolated: ${c.id}.data -> _isolated.${c.initIsolated}`))}else if(typeof c.initIsolated=="object"&&c.initIsolated.key){const{key:h,path:m}=c.initIsolated,y=m?this.extractValueByPathOrExpression(f,m,c.id):f,v=i[h];v!==void 0&&typeof v=="object"&&typeof y=="object"?(i[h]=this.deepMerge(v,y),U.log(`initIsolated (merged): ${c.id}.data${m?"."+m:""} -> _isolated.${h}`)):(i[h]=y,U.log(`initIsolated: ${c.id}.data${m?"."+m:""} -> _isolated.${h}`))}else if(typeof c.initIsolated=="object")for(const[h,m]of Object.entries(c.initIsolated)){if(typeof m!="string"){U.warn(`initIsolated map value must be string, got ${typeof m} for key ${h}`);continue}const y=this.extractValueByPathOrExpression(f,m,c.id),v=i[h];v!==void 0&&typeof v=="object"&&typeof y=="object"?(i[h]=this.deepMerge(v,y),U.log(`initIsolated map (merged): ${c.id} ${m} -> _isolated.${h}`)):(i[h]=y,U.log(`initIsolated map: ${c.id} ${m} -> _isolated.${h}`))}}})}evaluateDefaults(e,n){const r={};for(const[i,l]of Object.entries(e))if(typeof l=="string"&&l.startsWith("{{")&&l.endsWith("}}")){const c=l.slice(2,-2).trim();r[i]=this.evaluateExpression(c,n)}else r[i]=l;return r}evaluateExpression(e,n){try{const r=e.split("??").map(i=>i.trim());for(const i of r){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 l=this.getNestedValue(n,i);if(l!=null)return l}return}catch(r){U.warn(`Expression evaluation failed: ${e}`,r);return}}getNestedValue(e,n){const r=n.replace(/\?\./g,".");let i=e;const l=r.split(/\.(?![^\[]*\])/).flatMap(c=>{const d=c.match(/^([^\[]*)((?:\[\d+\])*)$/);if(d){const[,f,h]=d,m=[];f&&m.push(f);const y=h.match(/\[\d+\]/g);return y&&m.push(...y),m}return[c]}).filter(c=>c!=="");for(const c of l){if(i==null)return;if(c.startsWith("[")&&c.endsWith("]")){const d=parseInt(c.slice(1,-1),10);i=i[d]}else i=i[c]}return i}extractValueByPathOrExpression(e,n,r){const i=La(n);if(i!==null){const l=new $n,c={data:e,_global:this.globalState,_local:this.globalState._local||{}};try{const d=Wn(i)?l.evaluatePipeExpression(i,c,{skipCache:!0}):l.evaluateExpression(i,c);return U.log(`initLocal/initGlobal expression evaluated: ${n} -> `,d),d}catch(d){U.warn(`initLocal/initGlobal expression evaluation failed for ${r}:`,n,d);return}}return this.getNestedValue(e,n)}async loadLayoutScripts(e,n){const r=[];for(const i of e){if((i.if!==void 0||i.conditions!==void 0)&&!fs({if:i.if,conditions:i.conditions},n,this.bindingEngine,`script:${i.id}`)){U.log(`Script skipped (condition not met): ${i.id}`);continue}if(document.getElementById(i.id)){U.log(`Script already loaded: ${i.id}`);continue}if(!this.isAllowedScriptSrc(i.src)){U.warn(`Blocked untrusted external script src (same-origin path or declared trusted host required): ${i.id} (${i.src})`);continue}r.push(this.loadLayoutScript(i))}r.length>0&&(await Promise.all(r),U.log(`All scripts loaded: ${e.filter(i=>!document.getElementById(i.id)||r.length>0).map(i=>i.id).join(", ")}`))}async loadLayoutScript(e){const n=e.src.startsWith("/")?Ln(e.src):e.src;try{await Cr(n,{id:e.id},{label:`layout-script:${e.id}`}),this.failedLayoutScripts.delete(e.id),Db(`layout-script:${e.id}`),U.log(`Script loaded successfully: ${e.id}`)}catch(r){this.failedLayoutScripts.add(e.id),U.warn(`Failed to load script after retries: ${e.id} (${n})`,r),xs({id:`layout-script:${e.id}`,label:e.id,retry:async()=>{document.getElementById(e.id)?.remove(),await Cr(n,{id:e.id},{label:`layout-script:${e.id}`}),this.failedLayoutScripts.delete(e.id)}})}}getFailedLayoutScripts(){return Array.from(this.failedLayoutScripts)}isAllowedScriptSrc(e){return Io(e)}static normalizeScriptSrcForOriginCheck(e){return by(e)}extractScriptHost(e){return vy(e)}getTrustedScriptHosts(){return bs()}evaluateScriptCondition(e,n){try{if(e.startsWith("{{")&&e.endsWith("}}")){const r=e.slice(2,-2).trim();return!!af(r,n)}return!!e}catch(r){return U.warn(`Failed to evaluate script condition: ${e}`,r),!1}}showInitError(e){if(tc()){U.warn("Init failed while document is unloading — skipping error screen",e);return}const n=Tb(e);uh.renderFromError("app",n,"초기화 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}showTransitionOverlay(e,n){const r=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(!r.enabled)return;if(this.hideTransitionOverlay(),r.style==="skeleton"&&r.skeleton?.component&&r.target&&n){this.renderSkeletonOverlay(r.target,r.skeleton,n,r.fallback_target);return}if(r.style==="spinner"&&r.target){this.renderSpinnerOverlay(r.target,r.spinner,r.fallback_target);return}const i=document.documentElement.classList.contains("dark");let l,c="";switch(r.style){case"blur":l=i?"rgba(17,24,39,0.3)":"rgba(255,255,255,0.3)",c="backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px);";break;case"fade":l=i?"rgba(17,24,39,0.8)":"rgba(255,255,255,0.8)";break;case"skeleton":l=i?"rgb(17,24,39)":"rgb(249,250,251)";break;default:l=i?"rgb(17,24,39)":"rgb(249,250,251)";break}if(r.target){const d=`#${CSS.escape(r.target)}`,f=document.createElement("style");f.id="g7-transition-overlay",f.textContent=`${d}{position:relative;z-index:0;}${d}::after{content:'';position:absolute;inset:0;background:${l};${c}z-index:2147483647;pointer-events:none;}`,document.head.appendChild(f),this.transitionOverlayEl=f}else{const d=document.createElement("div");d.id="g7-transition-overlay",d.setAttribute("aria-hidden","true"),d.style.position="fixed",d.style.inset="0",d.style.zIndex="9999",d.style.pointerEvents="none",d.style.background=l;for(const f of c.split(";")){const h=f.indexOf(":");h!==-1&&d.style.setProperty(f.slice(0,h).trim(),f.slice(h+1).trim())}document.body.appendChild(d),this.transitionOverlayEl=d}}hideTransitionOverlay(){this.transitionOverlayEl&&(this.transitionOverlayEl.remove(),this.transitionOverlayEl=null),this.hideSkeletonOverlay()}renderSkeletonOverlay(e,n,r,i){const c=Er.getInstance().getComponent(n.component);if(!c){U.log(`Skeleton component "${n.component}" not found in registry, falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}let d=document.getElementById(e),f="target";if(!d&&i&&(d=document.getElementById(i),f="fallback"),d||(d=document.getElementById("app"),f="fullpage"),!d){U.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 m=document.documentElement.classList.contains("dark")?"rgb(17,24,39)":"rgb(249,250,251)",y=f==="fullpage"?"app":f==="fallback"?i:e,v=`#${CSS.escape(y)}`,S=document.createElement("style");S.id="g7-skeleton-overlay-style",S.textContent=`${v}{position:relative;z-index:0;}${v}::after{content:'';position:absolute;inset:0;background:${m};z-index:2147483646;pointer-events:none;}`,document.head.appendChild(S),this.transitionOverlayEl=S;const _=document.createElement("div");if(_.id="g7-skeleton-overlay",_.setAttribute("role","status"),_.setAttribute("aria-busy","true"),_.setAttribute("aria-label","Loading..."),f==="fullpage")_.style.cssText=["position:fixed","inset:0","z-index:20","overflow:hidden","pointer-events:none",`background:${m}`].join(";")+";";else{const k=d.getBoundingClientRect(),L=window.scrollX||document.documentElement.scrollLeft,B=window.scrollY||document.documentElement.scrollTop;_.style.cssText=["position:absolute",`top:${k.top+B}px`,`left:${k.left+L}px`,`width:${k.width}px`,`height:${k.height}px`,"z-index:20","overflow:hidden","pointer-events:none",`background:${m}`].join(";")+";"}document.body.appendChild(_),this.skeletonOverlayContainer=_;const x=r.components||[];let A;if(f==="fullpage")A=x;else{const k=f==="fallback"?i:e;A=this.findComponentChildrenById(x,k)}const D=Od.createRoot(_);this.skeletonOverlayRoot=D,ja.flushSync(()=>{D.render(Xe.createElement(c,{components:A,options:{animation:n.animation||"pulse",iteration_count:n.iteration_count||5}}))});const O=f==="fullpage"?"fullpage (#app)":f==="fallback"?`fallback (#${i})`:`target (#${e})`;U.log(`Skeleton overlay rendered [${O}] with "${n.component}" (${A.length} components)`)}findComponentChildrenById(e,n){const r=i=>{for(const l of i){if(l.id===n)return l.children||[];if(l.children&&Array.isArray(l.children)){const c=r(l.children);if(c!==null)return c}}return null};return r(e)||e}renderSpinnerOverlay(e,n,r){let i=document.getElementById(e),l="target";if(!i&&r&&(i=document.getElementById(r),l="fallback"),i||(i=document.getElementById("app"),l="fullpage"),!i){U.log(`Spinner overlay: no target found (target="#${e}", fallback="${r||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const c=l==="fullpage"?"app":l==="fallback"?r:e,d=`#${CSS.escape(c)}`,f=document.createElement("style");f.id="g7-skeleton-overlay-style",f.textContent=[`${d}{position:relative;}`,"@keyframes g7-spin{to{transform:rotate(360deg)}}"].join(""),document.head.appendChild(f),this.transitionOverlayEl=f;const h=n?.text||window.G7Core?.t?.("nav.loading")||"";this._spinnerState={target:e,fallbackTarget:r,spinnerConfig:n,resolvedText:h},this._mountSpinnerInTarget(i);const m=l==="fullpage"?"fullpage (#app)":l==="fallback"?`fallback (#${r})`:`target (#${e})`,y=n?.component||"default spinner";U.log(`Spinner overlay rendered [${m}] with "${y}"`)}_mountSpinnerInTarget(e){if(!this._spinnerState)return;const{spinnerConfig:n,resolvedText:r}=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,n?.component){const c=Er.getInstance().getComponent(n.component);if(c){const d=Od.createRoot(i);this.skeletonOverlayRoot=d,ja.flushSync(()=>{d.render(Xe.createElement(c,{options:{text:r}}))});return}U.log(`Spinner component "${n.component}" not found in registry, using default spinner`)}i.innerHTML='
'}reattachSpinnerOverlay(){if(!this._spinnerState)return;const{target:e,fallbackTarget:n}=this._spinnerState;let r=document.getElementById(e);!r&&n&&(r=document.getElementById(n)),r||(r=document.getElementById("app")),r&&(this._mountSpinnerInTarget(r),U.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){if(e instanceof Rr&&e.details?.status===401){const r=this.config.templateId||"",i=window.location.pathname,l=r.includes("admin")||i.startsWith("/admin")?"admin":"user",c=i+window.location.search,d=!!qr().getToken()||e.details?.hadToken===!0,f=Ar.getInstance().getLoginRedirectUrl(l,c,d?"session_expired":void 0);window.location.href=f;return}const n=Tb(e);uh.renderFromError("app",n,"페이지 로딩 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}async handleServerError(){const e=window.G7Error;if(!e)return!1;U.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"))?(U.log(`${e.code} error page rendered successfully`),!0):(U.log(`Falling back to ErrorDisplay for ${e.code}`),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0)}catch(n){return U.error(`Failed to render ${e.code} page:`,n),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0}}async handleRouteNotFound(e){U.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"))){U.log("404 error page rendered successfully");return}U.log("Falling back to ErrorDisplay for 404"),this.showRouteError(new Error(`Page not found: ${e}`))}catch(n){U.error("Failed to render 404 page:",n),this.showRouteError(new Error(`Page not found: ${e}`))}}getRouter(){return this.router}getConfig(){return this.config}getLayoutLoader(){return this.layoutLoader}async reloadExtensionState(){U.log("reloadExtensionState: start");let e;try{const n=await fetch(Ur(`/api/templates/${this.config.templateId}/config`,"json",null,`_=${Date.now()}`));if(n.ok){const r=await n.json();r?.success&&r?.data?.cache_version!==void 0&&(e=r.data.cache_version)}}catch(n){U.warn("reloadExtensionState: failed to fetch config.json",n)}e!==void 0&&e!==this.extensionCacheVersion&&(U.log(`reloadExtensionState: cache version ${this.extensionCacheVersion} -> ${e}`),this.extensionCacheVersion=e,this.saveCacheVersionToStorage(e));try{this.router&&(await this.router.loadRoutes(this.extensionCacheVersion),U.log("reloadExtensionState: routes reloaded"))}catch(n){U.error("reloadExtensionState: routes reload failed",n)}try{this.layoutLoader&&(this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),this.layoutLoader.clear(),U.log("reloadExtensionState: layout cache cleared"))}catch(n){U.error("reloadExtensionState: layout cache clear failed",n)}try{const{TranslationEngine:n}=await Promise.resolve().then(()=>Jg),r=n.getInstance();this.extensionCacheVersion>0&&r.setCacheVersion(this.extensionCacheVersion);const i=this.config.locale||"ko",l="en";await r.loadTranslations(this.config.templateId,i,"/api",!0),i!==l&&await r.loadTranslations(this.config.templateId,l,"/api",!0),U.log("reloadExtensionState: translations reloaded")}catch(n){U.error("reloadExtensionState: translations reload failed",n)}try{const n=await fetch(`/api/locales/active?_=${Date.now()}`);if(n.ok){const i=(await n.json())?.data?.locales;if(Array.isArray(i)&&i.length>0){const l=this.globalState.appConfig??{};this.setGlobalState({appConfig:{...l,supportedLocales:i}}),U.log("reloadExtensionState: supportedLocales refreshed",i)}}}catch(n){U.warn("reloadExtensionState: supportedLocales refresh failed",n)}U.log("reloadExtensionState: done")}getActionDispatcher(){return la().actionDispatcher}async changeLocale(e){try{if(U.log("Changing locale to:",e),this.config.locale===e){U.log("Locale is already",e);return}this.config.locale=e,this.saveLocaleToStorage(e),await this.saveLocaleToDatabase(e),this.layoutLoader&&(this.layoutLoader.clear(),U.log("Layout cache cleared")),this.errorPageHandler&&(this.errorPageHandler.updateLocale(e),U.log("ErrorPageHandler locale updated")),Xc(),await tl({templateId:this.config.templateId,templateType:this.config.templateType,locale:e,debug:this.config.debug,cacheVersion:this.extensionCacheVersion}),U.log("Template Engine re-initialized with new locale");const{getActionDispatcher:n}=await Promise.resolve().then(()=>Wr),r=n();r&&(r.setDefaultContext({navigate:i=>this.router?.navigate(i)}),r.setGlobalStateUpdater((i,l)=>this.setGlobalState(i,l)),U.log("Navigate function and setGlobalState re-injected to ActionDispatcher")),this.reinitializeModuleHandlers(),U.log("Module handlers re-initialized"),this.reinitializeTemplateHandlers(),U.log("Template handlers re-initialized"),this.reinitializePluginHandlers(),U.log("Plugin handlers re-initialized"),this.router&&this.router.navigateToCurrentPath(),U.log("Locale changed successfully to",e)}catch(n){throw U.error("Failed to change locale:",n),n}}loadLocaleFromStorage(){try{return localStorage.getItem(Lr.LOCALE_STORAGE_KEY)}catch(e){return U.warn("Failed to load locale from storage:",e),null}}saveLocaleToStorage(e){try{localStorage.setItem(Lr.LOCALE_STORAGE_KEY,e)}catch(n){U.warn("Failed to save locale to storage:",n)}}async saveLocaleToDatabase(e){const n=localStorage.getItem("auth_token");if(!n){U.log("No auth token, skipping DB locale save");return}let r,i;if(this.config.localeApi)r=this.config.localeApi.endpoint,i=this.config.localeApi.method;else{const l=this.config.templateType==="admin";r=l?"/api/admin/users/me/language":"/api/user/profile/update-language",i=l?"PATCH":"POST"}try{const l=this.getXsrfToken(),c=await fetch(r,{method:i,headers:{"Content-Type":"application/json",Accept:"application/json",...l&&{"X-XSRF-TOKEN":l},Authorization:`Bearer ${n}`},credentials:"include",body:JSON.stringify({language:e})});c.ok?U.log("Locale saved to DB:",e):U.warn("Failed to save locale to DB (UI will still change):",c.statusText)}catch(l){U.warn("Failed to call locale API (UI will still change):",l)}}getXsrfToken(){if(typeof document>"u")return null;const n=`; ${document.cookie}`.split("; XSRF-TOKEN=");return n.length===2?decodeURIComponent(n.pop()?.split(";").shift()||""):null}loadCacheVersionFromStorage(){try{const e=localStorage.getItem(Lr.CACHE_VERSION_STORAGE_KEY);return e?parseInt(e,10):null}catch(e){return U.warn("Failed to load cache version from storage:",e),null}}saveCacheVersionToStorage(e){try{localStorage.setItem(Lr.CACHE_VERSION_STORAGE_KEY,String(e))}catch(n){U.warn("Failed to save cache version to storage:",n)}}reinitializeModuleHandlers(){if(typeof window>"u")return;const e="__",n=window;Object.keys(n).forEach(r=>{if(r.startsWith(e)&&typeof n[r]?.initModule=="function")try{n[r].initModule(),U.log(`Module handler re-initialized: ${r}`)}catch(i){U.warn(`Failed to re-initialize module handlers for ${r}:`,i)}})}reinitializeTemplateHandlers(){if(typeof window>"u")return;const e=window.G7TemplateHandlers;if(!e){U.warn("Template handlers not found on window.G7TemplateHandlers");return}const n=this.getActionDispatcher();if(!n){U.warn("ActionDispatcher not available for template handler registration");return}Object.entries(e).forEach(([r,i])=>{n.registerHandler(r,i)}),U.log(`${Object.keys(e).length} template handler(s) re-registered:`,Object.keys(e))}reinitializePluginHandlers(){if(typeof window>"u")return;const e="__",n=window;Object.keys(n).forEach(r=>{if(r.startsWith(e)&&typeof n[r]?.initPlugin=="function")try{n[r].initPlugin(),U.log(`Plugin handler re-initialized: ${r}`)}catch(i){U.warn(`Failed to re-initialize plugin handlers for ${r}:`,i)}})}getLocale(){return this.config.locale}getErrorPageHandler(){return this.errorPageHandler}getGlobalState(){return{...this.globalState}}setGlobalState(e,n){const r={...this.globalState};typeof e=="function"?this.globalState=e(this.globalState):this.globalState={...this.globalState,...e},U.log("Global state updated:",this.globalState),window.G7Core?.devTools?.captureStateSnapshot?.({source:"setGlobalState",prev:r,next:this.globalState}),this.globalStateListeners.forEach(l=>{l(this.globalState)}),n?.render!==!1&&Promise.resolve().then(()=>Wr).then(({updateTemplateData:l,getState:c})=>{const d=c();d.reactRoot&&d.currentLayoutJson&&l({_global:{...this.globalState},_local:this.globalState._local||{}})})}onGlobalStateChange(e){this.globalStateListeners.add(e)}offGlobalStateChange(e){this.globalStateListeners.delete(e)}async refetchDataSource(e,n){let r=this.currentDataSources.find(i=>i.id===e);if(!r)for(const[,i]of this.modalDataSources){const l=i.find(c=>c.id===e);if(l){r=l;break}}if(!r){U.warn(`Data source not found: ${e}`);return}U.log(`Refetching data source: ${e}`,n?.sync?"(sync mode)":"",n?.globalStateOverride?"(with global override)":"",n?.localStateOverride?"(with local override)":""),Gr.setPending(!0);try{const i=new Dr;this.currentGlobalHeaders.length>0&&i.setGlobalHeaders(this.currentGlobalHeaders);const l=la(),c=l.currentDataContext?._global||{},d=n?.globalStateOverride?{...c,...n.globalStateOverride}:c,f=l.currentDataContext?._local||{},h=n?.localStateOverride?{...f,...n.localStateOverride}:f,y=(await i.fetchDataSourcesWithResults([r],this.currentRouteParams,this.currentQueryParams,d,h,{ignoreAutoFetch:!0}))[0];if(y.state==="success"&&y.data!==void 0){this.currentFetchedData[e]=y.data;const v={};this.processInitOptions([r],{[e]:y.data},v);const S=la();if(S.bindingEngine){const x=[e];r.initGlobal&&x.push("_global"),r.initLocal&&x.push("_local"),S.bindingEngine.invalidateCacheByKeys(x)}const _={[e]:y.data};return Object.keys(v).length>0&&(_._localInit=v),r.initGlobal&&(_._global={...this.globalState}),Ds(_,n?.sync?{sync:!0}:void 0),U.log(`Data source refetched successfully: ${e}`),y.data}else if(y.state==="error"){U.error(`Failed to refetch data source: ${e}`,y.error);return}}catch(i){U.error(`Error refetching data source: ${e}`,i);return}finally{Gr.setPending(!1)}}registerModalDataSources(e,n){this.modalDataSources.set(e,n),U.log(`Modal data sources registered: ${e} (${n.length} sources)`)}unregisterModalDataSources(e){this.modalDataSources.delete(e),U.log(`Modal data sources unregistered: ${e}`)}getDataSource(e){return this.currentFetchedData[e]}setDataSource(e,n,r){if(!e){U.warn("setDataSource: dataSourceId is required");return}const{merge:i=!1,sync:l=!1}=r||{};i&&this.currentFetchedData[e]?this.currentFetchedData[e]={...this.currentFetchedData[e],...n}:this.currentFetchedData[e]=n,Promise.resolve().then(()=>Wr).then(({updateTemplateData:c})=>{c({[e]:this.currentFetchedData[e]},l?{sync:!0}:void 0)}),U.log(`setDataSource: Updated ${e}`,i?"(merged)":"(replaced)")}updateDataSourceItem(e,n,r,i,l){const{idField:c="id",merge:d=!0,skipRender:f=!1}=l||{},h=this.currentFetchedData[e];if(!h)return U.warn(`updateDataSourceItem: DataSource '${e}' not found`),!1;const m=this.parseItemPath(n);let y=h;for(const _ of m)if(y=y?.[_],y===void 0)return U.warn(`updateDataSourceItem: Path '${n}' not found in dataSource`),!1;if(!Array.isArray(y))return U.warn(`updateDataSourceItem: Target at '${n}' is not an array`),!1;const v=y.findIndex(_=>String(_[c])===String(r));if(v===-1)return U.warn(`updateDataSourceItem: Item with ${c}='${r}' not found`),!1;d?y[v]=this.deepMerge(y[v],i):y[v]={...y[v],...i};const S=window.G7Core?.devTools;return S?.isEnabled?.()&&S.trackDataSourceUpdate?.({dataSourceId:e,updateType:"partial",itemPath:n,itemId:r,updates:i,timestamp:Date.now()}),f||Promise.resolve().then(()=>Wr).then(({updateTemplateData:_})=>{_({[e]:this.currentFetchedData[e]},{sync:!1})}),U.log(`updateDataSourceItem: Updated ${e}.${n}[${c}=${r}]`),!0}parseItemPath(e){const n=[],r=/([^\.\[\]]+)|\[(\d+)\]/g;let i;for(;(i=r.exec(e))!==null;)i[1]!==void 0?n.push(i[1]):i[2]!==void 0&&n.push(parseInt(i[2],10));return n}deepMerge(e,n){if(n==null)return e;if(typeof n!="object"||Array.isArray(n))return n;const r={...e};for(const i of Object.keys(n))typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])?r[i]=this.deepMerge(r[i]||{},n[i]):r[i]=n[i];return r}setValueAtPath(e,n,r,i="deep"){const l=n.split(".");let c=e;for(let h=0;h0?l.filterByCondition(this.currentRawDataSources,d):this.currentDataSources;this.currentDataSources=f;const h=f.filter(x=>x.auto_fetch!==!1&&x.type!=="websocket");if(h.length===0){U.log("No auto_fetch data sources to refetch");return}U.log(`Refetching ${h.length} auto_fetch data sources`),Gr.setPending(!0);const m=la().currentLayoutJson,y=m?.transition_overlay,v=Array.isArray(y?.wait_for)?y.wait_for:[],S=h.some(x=>(x.loading_strategy||"progressive")==="blocking"),_=v.length>0&&h.some(x=>v.includes(x.id)&&x.type!=="websocket"&&(x.loading_strategy||"progressive")!=="background");if((S||_)&&y&&typeof y=="object"){const x=n?.transitionOverlayTarget||y.target;y.enabled&&y.style==="skeleton"&&y.skeleton?.component&&x?this.renderSkeletonOverlay(x,y.skeleton,m,y.fallback_target):y.enabled&&y.style==="spinner"&&x&&this.renderSpinnerOverlay(x,y.spinner,y.fallback_target)}try{const x=new Dr;this.currentGlobalHeaders.length>0&&x.setGlobalHeaders(this.currentGlobalHeaders);const A=la(),D=A.currentDataContext?._global||{},O=await x.fetchDataSourcesWithResults(h,this.currentRouteParams,this.currentQueryParams,D,void 0,{ignoreAutoFetch:!1}),k={},L={},B=new Map(h.map(q=>[q.id,q]));for(const q of O){const z=B.get(q.id);if(!z){U.warn(`Refetch result id not found in autoFetchDataSources: ${q.id}`);continue}const W=q.id;q.state==="success"&&q.data!==void 0?(this.currentFetchedData[W]=q.data,k[W]=q.data,this.processInitOptions([z],{[W]:q.data},L),U.log(`Data source refetched: ${W}`)):q.state==="error"&&U.error(`Failed to refetch data source: ${W}`,q.error)}if(A.bindingEngine){const q=Object.keys(k);q.push("query"),A.bindingEngine.invalidateCacheByKeys(q)}if(Object.keys(L).length>0&&(k._localInit=L),Object.keys(k).length>0){if(k.query=Mb(this.currentQueryParams),A.currentLayoutJson?.computed&&Object.keys(A.currentLayoutJson.computed).length>0){const q={...A.currentDataContext,...k,query:k.query},z=this.calculateComputed(A.currentLayoutJson.computed,q);Object.keys(z).length>0&&(k._computed=z,this.globalState._computed=z,U.log("Computed values recalculated in updateQueryParams:",Object.keys(z)))}Ds(k,{sync:!0}),U.log("Template data updated with new query params")}}catch(x){U.error("Error in updateQueryParams:",x)}finally{Gr.setPending(!1),this.hideTransitionOverlay()}}calculateComputed(e,n){const r={},i=new $n;for(const[l,c]of Object.entries(e))try{let d;if(this.isComputedSwitchDefinition(c))d=i.resolveSwitch(c,n,{skipCache:!0});else if(typeof c=="string")if(c.startsWith("{{")&&c.endsWith("}}")){const f=c.slice(2,-2).trim();d=this.evaluateComputedExpression(f,n)}else d=c;r[l]=d,U.log(`Computed ${l}:`,d)}catch(d){U.warn(`Failed to calculate computed value: ${l}`,d),r[l]=void 0}return r}isComputedSwitchDefinition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"$switch"in e&&"$cases"in e}evaluateComputedExpression(e,n){try{return af(e,n)}catch(r){U.warn(`Expression evaluation failed: ${e}`,r);return}}async executeInitActions(e,n={}){const{getActionDispatcher:r}=await Promise.resolve().then(()=>Wr),i=r();if(!i){U.warn("ActionDispatcher not available for init_actions");return}U.log("Executing init_actions:",e.map(d=>d.handler)),U.log("Init actions dataContext:",n),U.log("Init actions dataContext._global:",n._global);const l=e.map(d=>d.handler).filter(d=>d.includes("."));l.length>0&&await this.waitForHandlers(i,l);let c={...n};for(const d of e)try{const f={type:"click",handler:d.handler,target:d.target,params:d.params,resultTo:d.resultTo,onSuccess:d.onSuccess,onError:d.onError,if:d.if,conditions:d.conditions,auth_mode:d.auth_mode,auth_required:d.auth_required},h=i.createHandler(f,c),m=new Event("init");await h(m),U.log(`Init action executed: ${d.handler}`);const y=this.globalState;c={...c,_global:{...y},_local:y._local||c._local||{}},U.log(`Data context refreshed after ${d.handler}:`,{cartKey:c._global?.cartKey})}catch(f){U.error(`Failed to execute init action: ${d.handler}`,f)}}async waitForHandlers(e,n,r=5e3){const i=Date.now(),l=50,c=()=>n.every(f=>e.customHandlers?.has(f));if(c()){U.log("All module handlers already registered");return}const d=fh().getFailedJsAssets();if(d.length>0){const f=d.some(y=>y==="module"||y==="plugin"),h=n.filter(y=>!e.customHandlers?.has(y)),m=h.length>0&&h.every(y=>d.some(v=>y.startsWith(`${v}.`)));if(f||m){U.warn("Extension asset load failed — not waiting for handlers that will never register:",{pending:h,failedAssets:d});return}}return U.log("Waiting for module handlers:",n),new Promise(f=>{const h=()=>{if(c()){U.log("All module handlers now registered"),f();return}if(Date.now()-i>=r){const m=n.filter(y=>!e.customHandlers?.has(y));U.warn("Timeout waiting for handlers:",m),f();return}setTimeout(h,l)};h()})}};M(Lr,"LOCALE_STORAGE_KEY","g7_locale"),M(Lr,"CACHE_VERSION_STORAGE_KEY","g7_cache_version");let Xo=Lr;function ph(s){const e=new Xo(s);return s.websocket&&(Gc.configure(s.websocket),U.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=ph,window.G7Core.dataSource={refetch:async(s,e)=>{const n=window.__templateApp;if(!n){U.warn("TemplateApp not initialized (G7Core.dataSource.refetch)");return}return n.refetchDataSource(s,e)},get:s=>{const e=window.__templateApp;if(!e){U.warn("TemplateApp not initialized (G7Core.dataSource.get)");return}return e.getDataSource(s)}});function mT(s={}){const{checked:e,value:n,name:r,type:i="checkbox"}=s,c=n!==void 0?n:i==="checkbox"||i==="radio"?e??!1:String(e??""),d={checked:e??!1,value:c,name:r??"",type:i};return{target:d,currentTarget:d,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 yT(s={}){const{button:e=0,clientX:n=0,clientY:r=0}=s;return{button:e,clientX:n,clientY:r,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 bT(){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 vT(s,e="keydown"){return{key:s,code:s.length===1?`Key${s.toUpperCase()}`:s,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new KeyboardEvent(e,{key:s}),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 ST={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 Nb(s){const e=s.replace(/^(dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+/,"");for(const[n,r]of Object.entries(ST))if(r.test(e))return n;return null}function Ib(s){const e=s.match(/^((dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+)/);return e?e[1]:""}function wT(s,e){if(!e||e.trim()==="")return s;if(!s||s.trim()==="")return e;const n=s.split(/\s+/).filter(Boolean),r=e.split(/\s+/).filter(Boolean),i=new Map;for(const c of r){const d=Nb(c);if(d){const f=Ib(c),h=`${d}:${f}`;i.set(h,c)}}return[...n.filter(c=>{const d=Nb(c);if(!d)return!0;const f=Ib(c),h=`${d}:${f}`;return!i.has(h)}),...r].join(" ")}function CT(s){return Object.entries(s).filter(([,e])=>e).map(([e])=>e).join(" ")}function ET(...s){return s.filter(e=>typeof e=="string"&&e.length>0).join(" ")}const be=pt("G7CoreGlobals");function _T(){window.React=Xe,window.ReactDOM={...Ld,createPortal:ja.createPortal,unstable_batchedUpdates:s=>s()},window.ReactJSXRuntime=a_,be.log("전역 객체 window.React, window.ReactDOM, window.ReactJSXRuntime에 노출됨")}function AT(s){const e=new Map,n=za.getInstance();s.componentEvent={on:(r,i)=>(e.has(r)||e.set(r,new Set),e.get(r).add(i),n.trackEventSubscribe(r),()=>{e.get(r)?.delete(i),n.trackEventUnsubscribe(r)}),emit:async(r,i)=>{const l=e.get(r),c=l?.size??0;if(!l||l.size===0)return n.trackEventEmit(r,i,0),[];let d,f=[];try{f=await Promise.all(Array.from(l).map(async h=>{try{return await h(i)}catch(m){throw be.error(`componentEvent: Error in listener for "${r}":`,m),m}}))}catch(h){d=h instanceof Error?h:new Error(String(h))}if(n.trackEventEmit(r,i,c,f,d),d)throw d;return f},off:r=>{e.delete(r),n.trackEventOff(r)},clear:()=>{e.clear(),n.trackEventClear()}},be.log("전역 객체 window.G7Core.componentEvent에 노출됨")}function xT(s){s.__runtime||(s.__runtime={DynamicRenderer:Vr,ComponentRegistry:Er,TranslationEngine:Oa,DataSourceManager:Dr,dataSourceManager:Gx,DataBindingEngine:$n,dataBindingEngine:of,ActionDispatcher:jo,TranslationReactContext:ih,TranslationProvider:Uc,useTranslation:gb,ResponsiveContext:If,ResponsiveProvider:Tc,useResponsive:jf,responsiveManager:Ci,BREAKPOINT_PRESETS:lc,AuthManager:Ar,createLogger:pt,G7DevToolsCore:za},be.log("전역 객체 window.G7Core.__runtime(코어 런타임 표면)에 노출됨"))}function TT(s){if(s.layoutEditor&&s.layoutEditor.__isStub!==!0||s.layoutEditor&&s.layoutEditor.__isStub===!0)return;const e=[],n=[];s.layoutEditor={__isStub:!0,__queue:e,__readyCallbacks:n,registerWidget:(r,i)=>e.push(["widget",r,i]),registerNodeEditor:(r,i)=>e.push(["nodeEditor",r,i]),registerCanvasOverlay:(r,i)=>e.push(["canvasOverlay",r,i]),onReady:r=>{typeof r=="function"&&n.push(r)}},be.log("전역 객체 window.G7Core.layoutEditor 예약 접수함(stub) 노출됨")}function kT(s){s.asset={template:(e,n,r)=>f0(e,n,r),templateDir:(e,n)=>h0(e,n),module:(e,n,r)=>p0(e,n,r),plugin:(e,n,r)=>g0(e,n,r),convertToCurrentMode:e=>Ln(e),loadScript:(e,n,r)=>Io(e,bs())?Cr(e,n,r):Promise.reject(new Error(`Blocked untrusted script src (same-origin path or declared trusted host required): ${e}`)),isAllowedScriptSrc:e=>Io(e,bs()),loadStylesheet:(e,n,r)=>ia(e,n,r)},s.assets={notifyFailure:xs,clearFailure:Db,clearAll:Ob,getFailures:Zx,retryAll:$b},lT(),be.log("전역 객체 window.G7Core.asset / window.G7Core.assets 노출됨")}function RT(s,e){s.useTranslation=gb,s.t=(n,r)=>{const i=e.getState();if(!i.translationEngine||!i.translationContext)return n;if(r){const l="|"+Object.entries(r).map(([c,d])=>`${c}=${d}`).join("|");return i.translationEngine.translate(n,i.translationContext,l)}return i.translationEngine.translate(n,i.translationContext)},be.log("전역 객체 window.G7Core.useTranslation에 노출됨")}function DT(s,e){s.createChangeEvent=mT,s.createClickEvent=yT,s.createSubmitEvent=bT,s.createKeyboardEvent=vT,s.uuid=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const r=Math.random()*16|0;return(n==="x"?r:r&3|8).toString(16)}),s.createLogger=pt,be.log("전역 객체 window.G7Core.createLogger에 노출됨"),s.renderItemChildren=(n,r,i,l,c)=>{const d=e.getState(),m={_global:window.__templateApp?.getGlobalState?.()||{},_local:r._local||{},_computed:r._computed||{},...r},y=new Set,v=(_,x)=>{const A=m._global?._remountKeys;return _&&A?.[_]&&!y.has(_)?(y.add(_),`${_}-remount-${A[_]}`):_||x},S={translationContext:d.translationContext,translationEngine:d.translationEngine,bindingEngine:d.bindingEngine,actionDispatcher:d.actionDispatcher,getRemountKey:v,...c};return Eo(n,m,i,l,S)},s.evaluateCondition=(n,r)=>{if(!n)return!0;const i=e.getState(),c=window.__templateApp?.getGlobalState?.()||{},d={_global:c,_local:c._local||{},_computed:c._computed||{},...r||{}},f=i.bindingEngine??of;return dm(n,d,f)},s.getComponentMap=()=>Er.getInstance().getComponentMap(),s.renderComponentLayout=(n,r,i)=>{if(!n||!Array.isArray(n)||n.length===0)return null;const l=Er.getInstance().getComponentMap(),c=e.getState(),f=window.__templateApp?.getGlobalState?.()||{},h={_global:f._global||{},_local:f._local||{},_computed:f._computed||{},...r},m=new Set,y=(v,S)=>{const _=h._global?._remountKeys;return v&&_?.[v]&&!m.has(v)?(m.add(v),`${v}-remount-${_[v]}`):v||S};return Eo(n,h,l,i,{translationContext:c.translationContext,translationEngine:c.translationEngine,bindingEngine:c.bindingEngine,actionDispatcher:c.actionDispatcher,getRemountKey:y})},s.renderExpandContent=n=>{const{children:r,row:i,expandContext:l,componentContext:c,keyPrefix:d}=n;if(!r||!Array.isArray(r)||r.length===0)return null;const f=n.componentMap||Er.getInstance().getComponentMap(),h=e.getState(),m=s.state?.get?.()||{},y=c?.stateRef?.current??c?.state??{},v={...m._local||{},...y},S=c?.computedRef?.current??m._computed??{},_=h.bindingEngine??s.getDataBindingEngine?.(),x={...m,_local:v,_computed:S,row:i,item:i,$item:i};let A={};if(l&&typeof l=="object"&&_)try{for(const[L,B]of Object.entries(l))if(typeof B=="string"){const q=La(B);if(q!==null)try{A[L]=Wn(q)?_.evaluatePipeExpression(q,x,{skipCache:!0}):_.evaluateExpression(q,x,{skipCache:!0})}catch{A[L]=void 0}else A[L]=_.resolveBindings(B,x,{skipCache:!0})}else A[L]=B}catch(L){be.warn("renderExpandContent: expandContext 평가 오류:",L)}const D={row:i,item:i,$item:i,_local:v,_global:m._global||{},_computed:m._computed||{},...A},O=new Set,k=(L,B)=>{const q=D._global?._remountKeys;return L&&q?.[L]&&!O.has(L)?(O.add(L),`${L}-remount-${q[L]}`):L||B};return Eo(r,D,f,d,{translationContext:h.translationContext,translationEngine:h.translationEngine??void 0,bindingEngine:h.bindingEngine??void 0,actionDispatcher:h.actionDispatcher,componentContext:c,getRemountKey:k})},s.$get=function(r,i,l=void 0){if(r==null)return l;const c=Array.isArray(i)?i:[i];if(c.length===0)return r;let d=r;for(const f of c){if(d==null||f==null)return l;d=d[f]}return d??l},be.log("전역 객체 window.G7Core.renderItemChildren에 노출됨"),be.log("전역 객체 window.G7Core.renderComponentLayout에 노출됨"),be.log("전역 객체 window.G7Core.renderExpandContent에 노출됨"),be.log("전역 객체 window.G7Core.$get에 노출됨")}function OT(s){s.dispatch=async(e,n)=>{const r=window.__templateApp;if(!r)return be.warn("G7Core.dispatch: TemplateApp이 초기화되지 않았습니다."),{success:!1,error:new Error("TemplateApp이 초기화되지 않았습니다.")};const i=r.getActionDispatcher?.();if(!i)return be.warn("G7Core.dispatch: ActionDispatcher를 찾을 수 없습니다."),{success:!1,error:new Error("ActionDispatcher를 찾을 수 없습니다.")};const l=r.getRouter?.(),c=r.getGlobalState?.(),d=r.setGlobalState?.bind(r),h=n?.componentContext||window.__g7ActionContext,m=window.__g7PendingLocalState;let y=h?.state??c;m&&h&&(y=m,be.log("[dispatch] Using __g7PendingLocalState for context.state:",m));let v=h?.data??c;m&&h?.data?._local&&(v={...h.data,_local:m},be.log("[dispatch] Updated context.data._local with pendingLocalState"));const S={navigate:l?(_,x)=>l.navigate(_,x):void 0,setState:h?.setState??d,state:y,data:v,_isDispatchFallbackContext:!h?.setState};if(e.debounce){const _=e.debounceKey||`dispatch-${e.handler}`,x=typeof e.debounce=="number"?e.debounce:e.debounce.delay;return i.debouncedCall(_,x,()=>{const{debounce:A,debounceKey:D,...O}=e;i.dispatchAction(O,S)}),{success:!0,debounced:!0}}try{return await i.dispatchAction(e,S)}catch(_){return be.error("G7Core.dispatch: 액션 실행 오류:",_),{success:!1,error:_ instanceof Error?_:new Error(String(_))}}},be.log("전역 객체 window.G7Core.dispatch에 노출됨")}function Jo(s){const e={};for(const[n,r]of Object.entries(s))if(n.includes(".")){const i=n.split(".");let l=e;for(let c=0;c0&&e.every(n=>/^\d+$/.test(n))}function Jn(s,e){if(Array.isArray(s)&&!Array.isArray(e)&<(e)){const r=Object.keys(e).map(l=>parseInt(l,10));if(!((r.length>0?Math.max(...r):0)>=s.length+r.length+10)){const l=[...s];for(const[c,d]of Object.entries(e)){const f=parseInt(c,10);f>=0&&f=l.length&&(l[f]=d)}return l}}const n={...s};for(const[r,i]of Object.entries(e))i!==null&&typeof i=="object"&&!Array.isArray(i)?n[r]!==null&&typeof n[r]=="object"?n[r]=Jn(n[r],i):n[r]={...i}:n[r]=i;return n}function $T(s){s.state={get:()=>window.__templateApp?.getGlobalState?.()||{},set:(e,n)=>{const r=window.__templateApp;if(r?.setGlobalState&&r?.getGlobalState){const i=n?.merge||"deep",l=Jo(e);let c;if(i==="replace")c=l;else if(i==="shallow")c={...r.getGlobalState(),...l};else{const d=r.getGlobalState();c=Jn(d,l)}r.setGlobalState(c,{render:n?.render})}else be.warn("G7Core.state.set: TemplateApp이 초기화되지 않았습니다.")},setLocal:(e,n)=>{const r=window.__templateApp;if(n?.render===!1&&!n?.selfManaged){const A=window.__g7AutoBindingPaths;A&&A.size>0&&jb(Jo(e)).some(O=>A.has(O))&&(be.log("[setLocal] render:false + 자동바인딩 경로 겹침 감지 → render:true 자동 승격 (engine-v1.43.0)"),n={...n,render:!0})}if(n?.debounce){const A=r?.getActionDispatcher?.();if(A){const D=n.debounceKey||`setLocal-${Object.keys(e).join(",")}`,{debounce:O,debounceKey:k,...L}=n;A.debouncedCall(D,n.debounce,()=>{s.state.setLocal(e,L)});return}}const i=n?.scope??"current",l=n?.merge||"deep",c=window.__g7ActionContext,d=Jo(e);if(i==="parent"||i==="root"){const A=window.__g7LayoutContextStack||[];if(A.length>0){const D=i==="parent"?A[A.length-1]:A[0];if(D?.setState){D.setState(O=>l==="replace"?d:l==="shallow"?{...O||{},...d}:Jn(O||{},d)),be.log(`[setLocal] scope=${i}: 타겟 컨텍스트에 상태 업데이트 (mergeMode=${l})`,d);return}}be.warn(`[setLocal] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const f=window.__g7PendingLocalState,h=r?.getGlobalState?.()?._local||{},v=!((window.__g7LayoutContextStack||[]).length>0)&&c?.state?c.state:void 0,S=v?Mo(h,v):h,_=f||S;let x;if(l==="replace"?x=d:l==="shallow"?x={..._,...d}:x=Jn(_,d),r?.setGlobalState&&(r.setGlobalState({_local:x},{render:n?.render}),be.log(`[setLocal] globalLocal updated via setGlobalState (mergeMode=${l}, render=${n?.render??!0}):`,d)),window.__g7PendingLocalState=x,be.log("[setLocal] __g7PendingLocalState updated:",x),window.__g7SequenceLocalSync=x,window.__g7LastSetLocalSnapshot=x,l==="replace")window.__g7ForcedLocalFields=d;else{const A=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=Jn(A,d)}if(be.log("[setLocal] __g7ForcedLocalFields updated:",d),l==="replace")window.__g7SetLocalOverrideKeys=d;else{const A=window.__g7SetLocalOverrideKeys||{};window.__g7SetLocalOverrideKeys=Jn(A,d)}be.log("[setLocal] __g7SetLocalOverrideKeys updated:",d),c?.setState&&c.setState(A=>l==="replace"?d:l==="shallow"?{...A||{},...d}:Jn(A||{},d)),r?.setGlobalState||be.warn("G7Core.state.setLocal: TemplateApp이 없습니다.")},getLocal:()=>{const r=(window.__templateApp?.getGlobalState?.()||{})._local||{},i=window.__g7PendingLocalState;if(i)return Jn(r,i);const l=window.__g7LastSetLocalSnapshot;return l&&l!==r?Jn(r,l):r},update:e=>{const n=window.__templateApp;if(n?.getGlobalState&&n?.setGlobalState){const r=n.getGlobalState(),i=e(r);n.setGlobalState(i)}else be.warn("G7Core.state.update: TemplateApp이 초기화되지 않았습니다.")},subscribe:e=>{const n=window.__templateApp;return n?.onGlobalStateChange?n.onGlobalStateChange(e):(be.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,n,r)=>{let i,l,c;typeof e=="string"?(i=e,l=n||{},c=r):(l=e,c=n&&typeof n=="object"&&"merge"in n?n:r);const d=c?.merge||"deep",f=Jo(l);if(i){const y=window.__g7IsolatedStates?.[i];y?.mergeState?y.mergeState(f,d):be.warn(`G7Core.state.setIsolated: scopeId '${i}'를 찾을 수 없습니다.`);return}const h=window.__g7ActionContext;h?.isolatedContext?.mergeState?h.isolatedContext.mergeState(f,d):be.warn("G7Core.state.setIsolated: 액션 컨텍스트에 isolatedContext가 없습니다.")},getParent:()=>{const e=window.__g7LayoutContextStack||[];if(e.length===0)return be.log("[getParent] 레이아웃 컨텍스트 스택이 비어있습니다."),null;const n=e[e.length-1];if(!n)return null;const r=n.dataContext||{};return{_local:n.state||r._local||{},_global:r._global||s.state.get()||{},setState:n.setState}},setParentLocal:(e,n,r)=>{const i=window.__g7LayoutContextStack||[];if(i.length===0){be.warn("[setParentLocal] 레이아웃 컨텍스트 스택이 비어있습니다.");return}const l=i[i.length-1];if(!l?.setState){be.warn("[setParentLocal] 부모 컨텍스트에 setState가 없습니다.");return}let c,d;typeof e=="string"?(c={[e]:n},d=r):(c=e,d=n&&typeof n=="object"&&"merge"in n?n:r);const f=d?.merge||"deep",h=Jo(c),m=l.state?._local!==void 0,y=m?l.state._local:l.state||{};let v;f==="replace"?v=h:f==="shallow"?v={...y,...h}:v=Jn(y,h),window.__g7PendingLocalState=v;const S=window.__templateApp;if(S?.setGlobalState){const _=S.getGlobalState?.()?._local,A=f!=="replace"&&!!_&&typeof _=="object"&&!Array.isArray(_)?f==="shallow"?{..._,...h}:Jn(_,h):void 0;S.setGlobalState({_local:A?Mo(A,v):v})}if(l.setState(v),m?l.state._local=v:l.state=v,l.dataContext&&(l.dataContext._local=v),f==="replace")window.__g7ForcedLocalFields=h;else{const _=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=Jn(_,h)}$f()},setParentGlobal:(e,n)=>{let r;typeof e=="string"?r={[e]:n}:r=e,s.state.set(r),be.log("[setParentGlobal] 전역 상태 업데이트:",r)}},window.__g7IsolatedStates||(window.__g7IsolatedStates={}),s.state.getGlobal=s.state.get,s.state.setGlobal=s.state.set,be.log("전역 객체 window.G7Core.state에 노출됨")}function MT(s){s.dataSource={get:e=>window.__templateApp?.getDataSource?.(e),set:(e,n,r)=>{const i=window.__templateApp;i?.setDataSource?i.setDataSource(e,n,r):be.warn("G7Core.dataSource.set: TemplateApp이 초기화되지 않았습니다.")},refetch:async(e,n)=>{const r=window.__templateApp;if(r?.refetchDataSource)return r.refetchDataSource(e,n);be.warn("G7Core.dataSource.refetch: TemplateApp이 초기화되지 않았습니다.")},updateItem:(e,n,r,i,l)=>{const c=window.__templateApp;return c?.updateDataSourceItem?c.updateDataSourceItem(e,n,r,i,l):(be.warn("G7Core.dataSource.updateItem: TemplateApp이 초기화되지 않았습니다."),!1)},updateData:(e,n,r,i="append")=>{const l=window.__templateApp;if(!l?.getDataSource||!l?.setDataSource)return be.warn("G7Core.dataSource.updateData: TemplateApp이 초기화되지 않았습니다."),!1;const c=l.getDataSource(e);if(!c)return be.warn(`G7Core.dataSource.updateData: 데이터 소스 '${e}'를 찾을 수 없습니다.`),!1;let d,f=c,h=null;if(n){const y=n.split(".");h=y.pop();for(const v of y)if(f&&typeof f=="object"&&v in f)f=f[v];else return be.warn(`G7Core.dataSource.updateData: 경로 '${n}'를 찾을 수 없습니다.`),!1;d=f[h]}else d=c;if(!Array.isArray(d))return be.warn("G7Core.dataSource.updateData: 대상 경로의 데이터가 배열이 아닙니다."),!1;if(!Array.isArray(r))return be.warn("G7Core.dataSource.updateData: newData가 배열이 아닙니다."),!1;const m=i==="prepend"?[...r,...d]:[...d,...r];return n&&h?(f[h]=m,l.setDataSource(e,c,{merge:!1})):l.setDataSource(e,m,{merge:!1}),be.log(`G7Core.dataSource.updateData: '${e}'에 ${r.length}개 항목 ${i==="prepend"?"앞에":"뒤에"} 추가됨`),!0}},be.log("전역 객체 window.G7Core.dataSource에 노출됨")}function NT(s,e){s.locale={current:()=>window.__templateApp?.getLocale?.()||"ko",supported:()=>{const r=window.__templateApp?.globalState?.appConfig?.supportedLocales;return Array.isArray(r)&&r.length>0?r:e.getState().templateMetadata?.locales||["ko","en"]},change:async n=>{const r=window.__templateApp;r?.changeLocale?await r.changeLocale(n):be.warn("G7Core.locale.change: TemplateApp이 초기화되지 않았습니다.")}},be.log("전역 객체 window.G7Core.locale에 노출됨")}function IT(s){s.toast={show:(e,n)=>{s.dispatch({handler:"toast",params:{message:e,type:n?.type||"info",...n?.duration&&{duration:n.duration}}})},success:(e,n)=>{s.toast.show(e,{type:"success",duration:n})},error:(e,n)=>{s.toast.show(e,{type:"error",duration:n})},warning:(e,n)=>{s.toast.show(e,{type:"warning",duration:n})},info:(e,n)=>{s.toast.show(e,{type:"info",duration:n})}},be.log("전역 객체 window.G7Core.toast에 노출됨")}function jT(s){s.modal={open:e=>{s.dispatch({handler:"openModal",target:e})},close:e=>{s.dispatch({handler:"closeModal",...e&&{target:e}})},closeAll:()=>{s.dispatch({handler:"closeAllModals"})},isOpen:e=>{const n=s.state.get();return n._global?.activeModal===e||n._global?.modalStack?.includes(e)||!1},getStack:()=>s.state.get()._global?.modalStack||[]},be.log("전역 객체 window.G7Core.modal에 노출됨")}function HT(s){s.style={mergeClasses:wT,conditionalClass:CT,joinClasses:ET},be.log("전역 객체 window.G7Core.style에 노출됨")}function zT(s,e){const{webSocketManager:n}=e;s.websocket={manager:n,subscribe:(r,i,l,c)=>n.subscribe(r,i,l,c),unsubscribe:r=>n.unsubscribe(r),leaveChannel:r=>n.leaveChannel(r),disconnect:()=>n.disconnect(),isInitialized:()=>n.isInitialized(),getSubscriptionCount:()=>n.getSubscriptionCount()},be.log("전역 객체 window.G7Core.websocket에 노출됨")}function PT(s,e){const{transitionManager:n}=e;s.navigation={isPending:()=>n?.getIsPending?.()||!1,onComplete:r=>{if(!n)return r(),()=>{};let i=n.getIsPending();const l=n.subscribe(c=>{c?i=!0:i&&(r(),l())});return l}},be.log("전역 객체 window.G7Core.navigation에 노출됨")}function UT(s){s.plugin={getSettings:e=>window.G7Config?.plugins?.[e],get:(e,n,r)=>window.G7Config?.plugins?.[e]?.[n]??r,getAll:()=>window.G7Config?.plugins??{}},be.log("전역 객체 window.G7Core.plugin에 노출됨")}function BT(s){s.module={getSettings:e=>window.G7Config?.modules?.[e],get:(e,n,r)=>window.G7Config?.modules?.[e]?.[n]??r,getAll:()=>window.G7Config?.modules??{}},be.log("전역 객체 window.G7Core.module에 노출됨")}function qT(s,e){const{transitionManager:n,responsiveManager:r}=e;s.AuthManager=Ar,s.api=qr(),s.TransitionManager=n,s.useTransitionState=Ay,s.ResponsiveManager=r,s.useResponsive=jf,s.useControllableState=y_,s.shallowArrayEqual=b_,s.shallowObjectEqual=Ty,s.updateQueryParams=async(i,l)=>{const c=window.__templateApp;if(c?.updateQueryParams)return c.updateQueryParams(i,l);be.warn("G7Core.updateQueryParams: TemplateApp이 초기화되지 않았습니다.")},be.log("전역 객체 window.G7Core.AuthManager에 노출됨"),be.log("전역 객체 window.G7Core.api에 노출됨"),be.log("전역 객체 window.G7Core.ResponsiveManager에 노출됨"),be.log("전역 객체 window.G7Core.useResponsive에 노출됨"),be.log("전역 객체 window.G7Core.useControllableState에 노출됨"),be.log("전역 객체 window.G7Core.updateQueryParams에 노출됨")}function GT(s,e){s.getSlotContext=()=>window.__slotContextValue??null,s.getDynamicRenderer=()=>window.__DynamicRenderer??null,s.getComponentRegistry=()=>e.getComponentRegistry?.()??Er.getInstance(),s.getDataBindingEngine=()=>e.getDataBindingEngine?.()??e.getState().bindingEngine,s.getTranslationEngine=()=>e.getTranslationEngine?.()??e.getState().translationEngine,s.getActionDispatcher=()=>e.getActionDispatcher?.()??e.getState().actionDispatcher,be.log("전역 객체 window.G7Core 슬롯 API에 노출됨 (getSlotContext, getDynamicRenderer 등)")}function FT(s){s.identity={setLauncher:At.setLauncher.bind(At),handle:At.handle.bind(At),isIdentityRequired:At.isIdentityRequired.bind(At),hasLauncher:At.hasLauncher.bind(At),markDomainNoticeShown:At.markDomainNoticeShown.bind(At),redirectExternally:At.redirectExternally.bind(At),createDeferred:At.createDeferred.bind(At),resolveDeferred:At.resolveDeferred.bind(At),reset:At.reset.bind(At),redirectStashKey:Tf},be.log("전역 객체 window.G7Core 본인인증(IDV) API에 노출됨 (identity)")}function VT(s){if(typeof window>"u")return;_T(),window.G7Core||(window.G7Core={});const e=window.G7Core;xT(e),AT(e),TT(e),qT(e,s),kT(e),RT(e,s),DT(e,s),OT(e),$T(e),MT(e),NT(e,s),IT(e),jT(e),HT(e),zT(e,s),PT(e,s),UT(e),BT(e),GT(e,s),FT(e),be.log("G7Core 전역 객체 초기화 완료")}function KT(){const s=window.G7Core;if(!s){be.warn("G7Core가 초기화되지 않았습니다.");return}const e=()=>za.getInstance(),n={isEnabled:()=>{try{return e().isEnabled()}catch{return!1}},trackRender:r=>{try{e().isEnabled()&&e().trackRender(r)}catch{}},trackIteration:(r,i,l,c,d)=>{try{e().isEnabled()&&e().trackIteration(r,{source:i,itemVar:l,indexVar:c,sourceLength:d})}catch{}},trackIfCondition:(r,i,l,c)=>{try{e().isEnabled()&&e().trackIfCondition(r,i,l)}catch{}},trackMount:(r,i)=>{try{e().isEnabled()&&e().trackMount(r,{...i,id:r})}catch{}},trackUnmount:r=>{try{e().isEnabled()&&e().trackUnmount(r)}catch{}},trackExpressionEval:r=>{try{e().isEnabled()&&e().trackExpressionEval(r)}catch{}},trackBindingEval:r=>{try{e().isEnabled()&&e().trackBindingEval(r)}catch{}},recordCacheHit:()=>{try{e().isEnabled()&&e().recordCacheHit()}catch{}},recordCacheMiss:()=>{try{e().isEnabled()&&e().recordCacheMiss()}catch{}},trackHandlerRegistration:(r,i,l,c)=>{try{e().isEnabled()&&e().trackHandlerRegistration(r,i,l,c)}catch{}},trackHandlerUnregistration:r=>{try{e().isEnabled()&&e().trackHandlerUnregistration(r)}catch{}},logAction:r=>{try{e().isEnabled()&&e().logAction(r)}catch{}},trackRequest:(r,i)=>{try{return e().isEnabled()?e().trackRequest(r,i):""}catch{return""}},completeRequest:(r,i,l)=>{try{e().isEnabled()&&e().completeRequest(r,i,l)}catch{}},failRequest:(r,i)=>{try{e().isEnabled()&&e().failRequest(r,i)}catch{}},trackDataSourceDefinition:r=>{try{e().isEnabled()&&e().trackDataSourceDefinition(r)}catch{}},trackDataSourceLoading:r=>{try{e().isEnabled()&&e().trackDataSourceLoading(r)}catch{}},trackDataSourceLoaded:(r,i,l)=>{try{e().isEnabled()&&e().trackDataSourceLoaded(r,i,l)}catch{}},trackDataSourceError:(r,i)=>{try{e().isEnabled()&&e().trackDataSourceError(r,i)}catch{}},trackForm:(r,i,l)=>{try{e().isEnabled()&&e().trackForm(r,i,l)}catch{}},untrackForm:r=>{try{e().isEnabled()&&e().untrackForm(r)}catch{}},startStateChange:(r,i,l,c)=>{try{return e().isEnabled()?e().startStateChange(r,i,l,c):""}catch{return""}},completeStateChange:r=>{try{e().isEnabled()&&e().completeStateChange(r)}catch{}},trackComponentRender:(r,i,l,c,d,f)=>{try{e().isEnabled()&&e().trackComponentRender(r,i,l,c,d,f)}catch{}},updateLocalState:r=>{try{e().isEnabled()&&e().updateLocalState(r)}catch{}},updateComputedState:r=>{try{e().isEnabled()&&e().updateComputedState(r)}catch{}},updateParentContext:r=>{try{e().isEnabled()&&e().updateParentContext(r)}catch{}},trackComponentStateSource:(r,i,l,c)=>{try{e().isEnabled()&&e().trackComponentStateSource(r,i,l,c)}catch{}},trackDynamicState:(r,i)=>{try{e().isEnabled()&&e().trackDynamicState(r,i)}catch{}},trackContextFlow:(r,i,l,c,d,f)=>{try{e().isEnabled()&&e().trackContextFlow(r,i,l,c,d,f)}catch{}},trackComponentStyle:(r,i,l,c)=>{try{e().isEnabled()&&e().trackComponentStyle(r,i,l,c)}catch{}},trackAuthEvent:(r,i,l,c)=>{try{e().isEnabled()&&e().trackAuthEvent(r,i,l,c)}catch{}},trackAuthHeader:(r,i,l,c,d)=>{try{e().isEnabled()&&e().trackAuthHeader(r,i,l,c,d)}catch{}},trackLog:(r,i,l)=>{try{e().isEnabled()&&e().trackLog(r,i,l)}catch{}},trackAction:r=>{try{e().isEnabled()&&e().trackAction?.(r)}catch{}},trackDataSourceUpdate:r=>{try{e().isEnabled()&&e().trackDataSourceUpdate?.(r)}catch{}},startSequenceExecution:r=>{try{return e().isEnabled()?e().startSequenceExecution(r):""}catch{return""}},captureSequenceActionBefore:(r,i,l,c,d)=>{try{e().isEnabled()&&e().captureSequenceActionBefore(r,i,l,c,d)}catch{}},captureSequenceActionAfter:(r,i,l,c,d,f)=>{try{e().isEnabled()&&e().captureSequenceActionAfter(r,i,l,c,d,f)}catch{}},endSequenceExecution:(r,i)=>{try{e().isEnabled()&&e().endSequenceExecution(r,i)}catch{}},registerStateCaptureForHandler:(r,i,l)=>{try{e().isEnabled()&&e().registerStateCaptureForHandler(r,i,l)}catch{}},detectStaleClosure:(r,i,l,c,d)=>{try{return e().isEnabled()?e().detectStaleClosure(r,i,l,c,d):[]}catch{return[]}},trackStaleClosureWarning:r=>{try{e().isEnabled()&&e().trackStaleClosureWarning(r)}catch{}},trackModalOpen:r=>{try{e().isEnabled()&&e().trackModalOpen(r)}catch{}},trackModalClose:(r,i)=>{try{e().isEnabled()&&e().trackModalClose(r,i)}catch{}},trackModalStateChange:r=>{try{e().isEnabled()&&e().trackModalStateChange(r)}catch{}},trackNestedContext:r=>{try{return e().isEnabled()?e().trackNestedContext(r):""}catch{return""}},trackNestedContextAccess:(r,i)=>{try{e().isEnabled()&&e().trackNestedContextAccess(r,i)}catch{}},trackComputedProperty:(r,i,l,c,d,f,h)=>{try{e().isEnabled()&&e().trackComputedProperty(r,i,l,c,d,f,h)}catch{}},trackComputedRecalc:(r,i,l,c,d,f,h)=>{try{e().isEnabled()&&e().trackComputedRecalc(r,i,l,c,d,f,h)}catch{}},setNamedActionDefinitions:r=>{try{e().isEnabled()&&e().setNamedActionDefinitions(r)}catch{}},trackNamedActionRef:r=>{try{e().isEnabled()&&e().trackNamedActionRef(r)}catch{}}};s.devTools=n,be.log("G7Core.devTools 인터페이스 초기화 완료")}let Qo=null;function WT(){const s=window.G7Core;return s?.__devtools?Promise.resolve(s.__devtools):Qo||(Qo=new Promise((e,n)=>{const r=window.G7Config?.coreDevToolsAsset||"/build/core/devtools.min.js",i="g7-devtools-bundle",l=()=>{const f=window.G7Core?.__devtools;f?e(f):n(new Error("DevTools 번들 로드됨 — 그러나 __devtools 미노출"))};window.G7Core=window.G7Core||{},window.G7Core.__onDevToolsReady=l;const c=document.getElementById(i);if(c){c.addEventListener("load",l,{once:!0}),c.addEventListener("error",()=>n(new Error(`DevTools 번들 로드 실패: ${r}`)),{once:!0});return}const d=document.createElement("script");d.id=i,d.src=r,d.async=!1,d.addEventListener("load",l,{once:!0}),d.addEventListener("error",()=>{Qo=null,n(new Error(`DevTools 번들 로드 실패: ${r}`))},{once:!0}),document.head.appendChild(d)}),Qo)}function YT(){const s=window.G7Core;if(!s){be.warn("G7Core가 초기화되지 않았습니다.");return}const e=za.getInstance();if(e.initialize(),!e.isEnabled()){window.G7DevTools={isEnabled:()=>!1,enable:()=>{be.log("환경설정 > 고급 설정 > 디버그 모드를 켜세요")}},Md(),be.log("G7DevTools 비활성화됨 (디버그 모드 꺼짐)");return}XT(s,e)}async function XT(s,e){let n;try{n=await WT()}catch(h){be.warn("DevTools 번들 로드 실패 — 최소 API 로 폴백:",h),window.G7DevTools={isEnabled:()=>!1,enable:()=>{}},Md();return}const{DiagnosticEngine:r,getServerConnector:i,getStyleTracker:l}=n;KT(),Md();try{l().enable(),be.log("StyleTracker 활성화됨")}catch(h){be.warn("StyleTracker 활성화 실패:",h)}const c=new r,d=i(),f={isEnabled:()=>e.isEnabled(),state:{get:()=>e.getState(),getHistory:()=>e.getStateHistory(),watch:(h,m)=>e.watchState(h,m)},actions:{getHistory:()=>e.getActionHistory(),watch:h=>e.watchActions(h),getMetrics:()=>e.getActionMetrics()},binding:{evaluate:h=>{const m=s.getDataBindingEngine?.();if(!m){be.warn("DataBindingEngine이 없습니다.");return}return m.evaluateExpression(h,e.getState())},getCacheStats:()=>e.getCacheStats(),clearStats:()=>{e.resetCacheStats(),be.log("캐시 통계 초기화됨")}},diagnose:{analyze:h=>c.analyze(h),suggestFix:h=>c.suggestFix(h),getCommonIssues:()=>c.getCommonIssues(),getRulesByCategory:h=>c.getRulesByCategory(h)},server:{dumpState:h=>d.dumpState(h),sendLog:h=>d.sendLog(h),sendError:(h,m)=>d.sendError(h,m),isConnected:()=>d.isConnected(),testConnection:()=>d.testConnection()},config:{isDebugMode:()=>e.isEnabled(),setLogLevel:h=>e.setLogLevel(h),setMaxHistory:h=>e.setMaxHistory(h)},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=f,s.devtools=f,be.log("G7DevTools 전역 객체 초기화 완료 (window.G7DevTools)"),JT(n.DevToolsPanel)}function JT(s){if(document.getElementById("g7-devtools-root")){be.log("DevToolsPanel 이미 렌더링됨");return}const e=document.createElement("div");e.id="g7-devtools-root",document.body.appendChild(e);try{Ld.createRoot(e).render(Xe.createElement(s)),be.log("DevToolsPanel UI 렌더링 완료")}catch(n){be.error("DevToolsPanel UI 렌더링 실패:",n)}}const Qe=pt("TemplateEngine"),ae={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 Zo=!1;const el=[];async function QT(s){try{Qe.log("템플릿 메타데이터 로드 중...",s);const e=s.split("-").map(r=>r.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join("")).join(""),n=window[e];return n?.templateMetadata?(Qe.log("템플릿 메타데이터 로드 완료 (전역 변수)",n.templateMetadata),n.templateMetadata):(Qe.warn(`템플릿 번들에 메타데이터가 없습니다. 전역 변수: ${e}`),{identifier:s,locales:["ko","en"],name:{ko:s,en:s},description:{ko:"",en:""},version:"1.0.0",type:"admin"})}catch(e){return Qe.error("템플릿 메타데이터 로드 실패",e),{identifier:s,locales:["ko","en"],name:{ko:s,en:s},description:{ko:"",en:""},version:"1.0.0",type:"admin"}}}function Hb(){const e=(typeof window<"u"?window.__templateApp:void 0)?.globalState?.appConfig?.supportedLocales,n=ae.templateMetadata?.locales;return{$locale:ae.locale,$locales:Array.isArray(e)&&e.length>0?e:n||["ko","en"],$templateLocales:n||["ko","en"],$templateId:ae.templateId}}async function tl(s){try{if(Qe.log("템플릿 엔진 초기화 시작",s),ae.isInitialized)throw new Error("템플릿 엔진이 이미 초기화되었습니다. destroyTemplate()을 먼저 호출하세요.");if(!s.templateId)throw new Vx;Zo=s.debug??!1,typeof window<"u"&&(window.G7Config||(window.G7Config={}),window.G7Config.debug=Zo),YT(),ae.templateId=s.templateId,ae.locale=s.locale||"ko",Qe.log("엔진 인스턴스 생성 중..."),ae.registry=Er.getInstance(),ae.bindingEngine=new $n,ae.translationEngine=Oa.getInstance(),s.cacheVersion!==void 0&&s.cacheVersion>0&&ae.translationEngine.setCacheVersion(s.cacheVersion),ae.translationContext={templateId:s.templateId,locale:ae.locale},ae.actionDispatcher=new jo({},ae.translationEngine,ae.translationContext),l_(ae.actionDispatcher),Qe.log("다국어 파일 로드 중...",s.templateId,ae.locale);const e="en",n=[ae.translationEngine.loadTranslations(s.templateId,ae.locale).then(()=>{Qe.log(`다국어 파일 로드 완료: ${ae.locale}`)}).catch(r=>{Qe.warn(`다국어 파일 로드 실패 (${ae.locale}):`,r instanceof Error?r.message:r)})];ae.locale!==e&&n.push(ae.translationEngine.loadTranslations(s.templateId,e).then(()=>{Qe.log(`폴백 다국어 파일 로드 완료: ${e}`)}).catch(r=>{Qe.warn(`폴백 다국어 파일 로드 실패 (${e}):`,r instanceof Error?r.message:r)})),await Promise.allSettled(n),Qe.log("템플릿 메타데이터 로드 중...",s.templateId),ae.templateMetadata=await QT(s.templateId),ae.isInitialized=!0,Qe.log("템플릿 엔진 초기화 완료 (ComponentRegistry는 별도 로드)")}catch(e){throw Qe.error("템플릿 엔진 초기화 실패",e),ae.isInitialized=!1,ae.registry=null,ae.bindingEngine=null,ae.translationEngine=null,ae.actionDispatcher=null,e}}let ks=null;const zb="g7-layout-editor-bundle";function gh(){const s=window.G7Core;return s?.__LayoutEditorChrome?Promise.resolve(s.__LayoutEditorChrome):ks||(ks=(async()=>{const e=window.G7Config?.coreEditorAsset||"/build/core/layout-editor.min.js";document.getElementById(zb)?.remove(),window.G7Core=window.G7Core||{},window.G7Core.__onChromeReady=()=>{};try{await Cr(e,{id:zb},{label:"layout-editor bundle"})}catch(r){throw ks=null,Qe.error(`편집기 번들 로드 실패 (${e})`,r),new Error("편집기를 불러오지 못했습니다. 네트워크 상태를 확인한 뒤 다시 시도해 주세요.")}const n=window.G7Core?.__LayoutEditorChrome;if(!n)throw ks=null,Qe.error(`편집기 번들 로드됨 — 그러나 __LayoutEditorChrome 미노출 (${e})`),new Error("편집기를 불러왔으나 초기화하지 못했습니다. 페이지를 새로고침해 주세요.");return n})(),ks)}async function Rs(s){try{if(Qe.log("템플릿 렌더링 시작",s),!ae.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다. initTemplateEngine()을 먼저 호출하세요.");if(!s.containerId)throw new Error("containerId는 필수입니다.");if(!s.layoutJson)throw new Error("layoutJson은 필수입니다.");const e=document.getElementById(s.containerId);if(!e)throw new Error(`컨테이너를 찾을 수 없습니다: #${s.containerId}`);const n=Hb();if(ae.containerId=s.containerId,ae.currentLayoutJson=s.layoutJson,ae.currentDataContext={...n,...s.dataContext||{}},ae.translationContext=s.translationContext||{templateId:ae.templateId||"",locale:ae.locale},ae.reactRoot||(Qe.log("React Root 생성"),ae.reactRoot=Ld.createRoot(e)),typeof window<"u"){const l=kb(window.location.pathname);if(l){Qe.log("레이아웃 편집기 모드 진입",l);let c;try{c=await gh()}catch(f){Qe.error("레이아웃 편집기 번들 로드 실패",f),uh.render(s.containerId,{title:"레이아웃 편집기 로드 실패",message:f instanceof Error?f.message:"편집기 번들을 불러오지 못했습니다.",icon:"fas fa-triangle-exclamation",showStack:!1,showReloadButton:!0,debug:Zo});return}const d=Xe.createElement(c,{templateIdentifier:l.templateIdentifier,initialLocale:ae.locale});ae.reactRoot.render(Xe.createElement(Uc,{translationEngine:ae.translationEngine,translationContext:ae.translationContext,children:Xe.createElement(Mf,{children:Xe.createElement(Tc,{children:Xe.createElement(sh,{children:d})})})}));return}}const r=s.layoutJson.components||[];if(r.length===0){Qe.warn("렌더링할 컴포넌트가 없습니다.");return}const i=s.layoutJson.modals||[];if(Qe.log("modals 배열:",i),Qe.log("modals 개수:",i.length),Qe.log("DynamicRenderer로 렌더링 시작"),ae.reactRoot.render(Xe.createElement(Uc,{translationEngine:ae.translationEngine,translationContext:ae.translationContext},Xe.createElement(Mf,null,Xe.createElement(Tc,null,Xe.createElement(sh,null,[...r.map((l,c)=>{const d=ae.currentLayoutJson?.layout_name||"";return Xe.createElement(Vr,{key:d&&!l._fromBase?`${l.id}_${d}`:l.id,componentDef:l,dataContext:ae.currentDataContext,translationContext:ae.translationContext,registry:ae.registry,bindingEngine:ae.bindingEngine,translationEngine:ae.translationEngine,actionDispatcher:ae.actionDispatcher,isRootRenderer:c===0,layoutKey:d})}),Xe.createElement(yy,{key:"__modal_parent_context_provider"},i.map(l=>{const c=ae.currentDataContext._global?.modalStack||[],f=c.includes(l.id)||ae.currentDataContext._global?.activeModal===l.id,h=c.indexOf(l.id),m=h>=0?50+h:50,y=window.__g7LayoutContextStack||[],S=y[y.length-1]?.dataContext,_=Xe.createElement(Vr,{key:`modal_${l.id}_renderer`,componentDef:{...l,props:{...l.props,isOpen:f,style:{...l.props?.style,zIndex:m},onClose:ae.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},ae.currentDataContext)}},dataContext:ae.currentDataContext,translationContext:ae.translationContext,registry:ae.registry,bindingEngine:ae.bindingEngine,translationEngine:ae.translationEngine,actionDispatcher:ae.actionDispatcher,parentDataContext:S});return l.data_sources&&l.data_sources.length>0?Xe.createElement(xb,{key:`modal_${l.id}`,isOpen:f,modalId:l.id,dataSources:l.data_sources,dataContext:ae.currentDataContext,globalStateUpdater:ae.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:ae.bindingEngine,debug:Zo,children:_}):_}))]))))),Qe.log("템플릿 렌더링 완료"),el.length>0){Qe.log(`대기 중인 데이터 업데이트 ${el.length}건 적용`);const l=[...el];el.length=0;for(const{data:c,options:d}of l)Ds(c,d)}}catch(e){throw Qe.error("템플릿 렌더링 실패",e),e}}function Ds(s,e){try{if(Qe.log("템플릿 데이터 업데이트 시작",Object.keys(s)),!ae.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다.");if(!ae.reactRoot||!ae.currentLayoutJson){Qe.log("React 미준비 - 데이터 업데이트 큐잉:",Object.keys(s)),el.push({data:s,options:e});return}const n=Hb(),r={...ae.currentDataContext._global||{},...s._global||{}},i=g_(ae.currentDataContext._localInit,s._localInit);ae.currentDataContext={...n,...ae.currentDataContext,...s,_global:r,_localInit:i},r._local!==void 0&&(ae.currentDataContext._local=r._local),r._computed!==void 0&&(ae.currentDataContext._computed=r._computed);const l=ae.currentLayoutJson.components||[],c=ae.currentLayoutJson.modals||[];Qe.log("updateTemplateData - modals 배열:",c),Qe.log("updateTemplateData - modals 개수:",c.length),Qe.log("updateTemplateData - activeModal:",ae.currentDataContext._global?.activeModal);const d=()=>{ae.reactRoot.render(Xe.createElement(Uc,{translationEngine:ae.translationEngine,translationContext:ae.translationContext},Xe.createElement(Mf,null,Xe.createElement(Tc,null,Xe.createElement(sh,null,[...l.map((f,h)=>{const m=ae.currentLayoutJson?.layout_name||"";return Xe.createElement(Vr,{key:m&&!f._fromBase?`${f.id}_${m}`:f.id,componentDef:f,dataContext:ae.currentDataContext,translationContext:ae.translationContext,registry:ae.registry,bindingEngine:ae.bindingEngine,translationEngine:ae.translationEngine,actionDispatcher:ae.actionDispatcher,isRootRenderer:h===0,layoutKey:m})}),Xe.createElement(yy,{key:"__modal_parent_context_provider_update"},c.map(f=>{const h=ae.currentDataContext._global?.modalStack||[],y=h.includes(f.id)||ae.currentDataContext._global?.activeModal===f.id,v=h.indexOf(f.id),S=v>=0?50+v:50,_=window.__g7LayoutContextStack||[],A=_[_.length-1]?.dataContext,D=Xe.createElement(Vr,{key:`modal_${f.id}_renderer`,componentDef:{...f,props:{...f.props,isOpen:y,style:{...f.props?.style,zIndex:S},onClose:ae.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},ae.currentDataContext)}},dataContext:ae.currentDataContext,translationContext:ae.translationContext,registry:ae.registry,bindingEngine:ae.bindingEngine,translationEngine:ae.translationEngine,actionDispatcher:ae.actionDispatcher,parentDataContext:A});return f.data_sources&&f.data_sources.length>0?Xe.createElement(xb,{key:`modal_${f.id}`,isOpen:y,modalId:f.id,dataSources:f.data_sources,dataContext:ae.currentDataContext,globalStateUpdater:ae.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:ae.bindingEngine,debug:Zo,children:D}):D}))])))))};e?.sync?(Qe.log("재렌더링 시작 (sync mode - 즉시 렌더링)"),d()):(Qe.log("재렌더링 시작 (with startTransition)"),I.startTransition(()=>{d()})),Qe.log("템플릿 데이터 업데이트 완료")}catch(n){throw Qe.error("템플릿 데이터 업데이트 실패",n),n}}function Xc(){try{Qe.log("템플릿 정리 시작"),ae.reactRoot&&(Qe.log("React Root 언마운트"),ae.reactRoot.unmount(),ae.reactRoot=null),ae.templateId=null,ae.locale="ko",ae.isInitialized=!1,ae.containerId=null,ae.currentLayoutJson=null,ae.currentDataContext={},ae.translationContext={templateId:"",locale:"ko"},ae.registry=null,ae.bindingEngine=null,ae.translationEngine=null,ae.actionDispatcher=null,ae.templateMetadata=null,Qe.log("템플릿 정리 완료")}catch(s){throw Qe.error("템플릿 정리 실패",s),s}}function la(){return Object.freeze({...ae})}function Pb(){return ae.actionDispatcher}const nl={initTemplateEngine:tl,renderTemplate:Rs,updateTemplateData:Ds,destroyTemplate:Xc,getState:la};typeof window<"u"&&(window.G7Core||(window.G7Core={}),window.G7Core.TemplateEngine=nl,VT({getState:()=>({translationEngine:ae.translationEngine,translationContext:ae.translationContext,bindingEngine:ae.bindingEngine,actionDispatcher:ae.actionDispatcher,templateMetadata:ae.templateMetadata}),transitionManager:Gr,responsiveManager:Ci,webSocketManager:Gc}),Qe.log("전역 객체 window.G7Core.TemplateEngine에 노출됨"));const Wr=Object.freeze(Object.defineProperty({__proto__:null,DataSourceManager:Dr,LayoutLoader:ah,TemplateApp:Xo,TemplateEngine:nl,default:nl,destroyTemplate:Xc,getActionDispatcher:Pb,getState:la,initTemplateApp:ph,initTemplateEngine:tl,loadLayoutEditorBundle:gh,renderTemplate:Rs,updateTemplateData:Ds},Symbol.toStringTag,{value:"Module"}));tn.DataSourceManager=Dr,tn.LayoutLoader=ah,tn.TemplateApp=Xo,tn.TemplateEngine=nl,tn.default=nl,tn.destroyTemplate=Xc,tn.getActionDispatcher=Pb,tn.getState=la,tn.initTemplateApp=ph,tn.initTemplateEngine=tl,tn.loadLayoutEditorBundle=gh,tn.renderTemplate=Rs,tn.updateTemplateData=Ds,Object.defineProperties(tn,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})(this.G7Core=this.G7Core||{}); + `}static renderFromError(e,n,r,i=!1,l,c,d){let f,p;if(n.userMessageKey.startsWith("$t:"))if(c&&l)try{f=c.translate(n.userMessageKey,l)}catch{f=n.userMessageKey.replace("$t:","")}else f=n.userMessageKey.replace("$t:","");else f=n.userMessageKey;if(d){const m=d;m.details?.apiMessage?p=m.details.apiMessage:m.response?.data?.message&&(p=m.response.data.message)}this.render(e,{title:r,message:f,detailMessage:p,icon:n.icon,showStack:n.showStack,stackTrace:n.stack,showReloadButton:n.recoverable,debug:i})}static escapeHtml(e){if(!e)return"";const n=document.createElement("div");return n.textContent=e,n.innerHTML}}const bs=dt("Router");class zA{constructor(e){$(this,"routes",[]);$(this,"templateIdentifier");$(this,"eventHandlers",new Map);$(this,"pendingNavigation",null);$(this,"isNavigating",!1);$(this,"handlePopState",()=>{this.navigateToCurrentPath()});this.templateIdentifier=e,this.initPopstateListener()}initPopstateListener(){window.addEventListener("popstate",this.handlePopState)}on(e,n){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(n)}async emit(e,...n){const r=this.eventHandlers.get(e);r&&await Promise.all(r.map(i=>i(...n)))}async loadRoutes(e){try{const n=e!==void 0&&e>0?e:null,r=await fetch(Pr(`/api/templates/${this.templateIdentifier}/routes`,"json",n));if(!r.ok)throw new Error(`Failed to load routes: ${r.statusText}`);const i=await r.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,bs.log(`Loaded ${this.routes.length} routes${e?` (v=${e})`:""}`);else throw new Error("Invalid routes data format")}catch(n){throw bs.error("Error loading routes:",n),n}}setRoutes(e){this.routes=e,bs.log(`Set ${this.routes.length} routes`)}match(e){const n=this.normalizePathname(e);for(const r of this.routes){const i=this.matchPattern(r.path,n);if(i!==null)return{route:r,params:i}}return null}normalizePathname(e){return e.length>1&&e.endsWith("/")?e.replace(/\/+$/,"")||"/":e}matchPattern(e,n){const r=[];let i=e.replace(/:([^/]+)/g,(f,p)=>(r.push(p),"([^/]+)"));i.startsWith("*/")&&(i="(?:/[^/]+)?"+i.slice(1)),i=i.replace(/\//g,"\\/");const l=new RegExp(`^${i}$`),c=n.match(l);if(!c)return null;const d={};return r.forEach((f,p)=>{d[f]=c[p+1]}),d}getRoutes(){return[...this.routes]}getAuthType(e,n){return e.auth_type?e.auth_type:n.startsWith("/admin")?"admin":"user"}async navigateToCurrentPath(){const e=window.location.pathname,n=window.location.search,r=this.match(e);if(!r){bs.warn(`No route matched for path: ${e}`),this.emit("routeNotFound",e);return}if(r.route.redirect){bs.log(`Redirecting from ${e} to ${r.route.redirect}`),this.navigate(r.route.redirect);return}if(r.route.auth_required){const c=this.getAuthType(r.route,e),d=Yn.getInstance();let f=d.isAuthenticated()&&d.getAuthType()===c;if(f||(f=await d.checkAuth(c)),!f){const p=d.getLoginRedirectUrl(c,e+n);bs.log(`Not authenticated, redirecting to: ${p}`),window.location.href=p;return}}const i=new URLSearchParams(n),l={};for(const c of i.keys()){if(c in l)continue;const d=i.getAll(c);d.length>1?l[c]=d:d.length===1&&(c.endsWith("[]")?l[c]=d:l[c]=d[0])}await this.emit("routeChange",{path:e,layout:r.route.layout,endpoint:r.route.endpoint,params:{...r.route.params||{},...r.params},query:l,auth_required:r.route.auth_required,auth_type:r.route.auth_type,meta:r.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 n=this.pendingNavigation;this.executeNavigation(n)}}}}const HA=/^\/admin\/layout-editor\/([^/?#]+)\/?$/;function tb(s){const e=HA.exec(s);return e?{templateIdentifier:e[1]}:null}const Ht=dt("ErrorPageHandler");class UA{constructor(e){$(this,"templateId");$(this,"layoutLoader");$(this,"locale");$(this,"debug");$(this,"renderFunction");$(this,"dataSourceManager");$(this,"globalState");$(this,"errorConfig",null);$(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(Pr(`/api/templates/${this.templateId}/config`,"json"));if(!e.ok)return this.debug&&Ht.warn("Failed to load template config:",e.statusText),this.configLoaded=!0,null;const n=await e.json();if(!n.success||!n.data)return this.debug&&Ht.warn("Invalid template config response"),this.configLoaded=!0,null;const r=n.data;return!r.error_config||!r.error_config.layouts?(this.debug&&Ht.warn("No error_config found in template.json"),this.configLoaded=!0,null):(this.errorConfig=r.error_config,this.configLoaded=!0,this.debug&&Ht.log("Error config loaded:",this.errorConfig),this.errorConfig)}catch(e){return Ht.error("Failed to load error config:",e),this.configLoaded=!0,null}}async renderError(e,n="app"){try{const r=await this.loadConfig();if(!r)return this.debug&&Ht.warn("No error config available, cannot render error page"),!1;const i=r.layouts[e]||r.layouts[String(e)];if(!i)return this.debug&&Ht.warn(`No layout defined for error code: ${e}`),!1;this.debug&&Ht.log(`Loading error layout: ${i} for code: ${e}`);const l=await this.layoutLoader.loadLayout(this.templateId,i);if(!l)return this.debug&&Ht.error(`Failed to load error layout: ${i}`),!1;this.debug&&Ht.log("Error layout loaded:",l);let c={};const d=l.data_sources||[];if(d.length>0){this.debug&&Ht.log("Fetching data sources:",d.map(S=>S.id));const m=d.filter(S=>S.loading_strategy==="blocking"),y=d.filter(S=>!S.loading_strategy||S.loading_strategy==="progressive"),C=[...m,...y];if(C.length>0)try{c=await this.dataSourceManager.fetchDataSources(C,{},new URLSearchParams),this.debug&&Ht.log("Data sources fetched:",Object.keys(c))}catch(S){Ht.error("Failed to fetch data sources:",S)}}const f={};d.length>0&&(this.processInitOptions(d,c,f),this.debug&&Ht.log("initOptions processed:",{globalKeys:Object.keys(this.globalState),localKeys:Object.keys(f)}));const p={...c,errorCode:e,_global:{...this.globalState},_local:{...f}};return await this.renderFunction({containerId:n,layoutJson:l,dataContext:p,translationContext:{templateId:this.templateId,locale:this.locale}}),this.debug&&Ht.log(`Error page ${e} rendered successfully`),!0}catch(r){return Ht.error(`Failed to render error page ${e}:`,r),!1}}processInitOptions(e,n,r){for(const i of e){const l=n[i.id];if(!l)continue;const c=l?.data??l;if(i.initLocal){if(typeof i.initLocal=="string")r[i.initLocal]=c,Ht.log(`initLocal: ${i.id}.data -> _local.${i.initLocal}`);else if(typeof i.initLocal=="object"&&"key"in i.initLocal){const{key:d,path:f}=i.initLocal;r[d]=f?this.getValueByPath(c,f):c,Ht.log(`initLocal: ${i.id}.data${f?"."+f:""} -> _local.${d}`)}}if(i.initGlobal){const d=Array.isArray(i.initGlobal)?i.initGlobal:[i.initGlobal];for(const f of d)if(typeof f=="string")this.globalState[f]=c,Ht.log(`initGlobal: ${i.id}.data -> _global.${f}`);else if(typeof f=="object"&&f!==null&&"key"in f){const{key:p,path:m}=f;this.globalState[p]=m?this.getValueByPath(c,m):c,Ht.log(`initGlobal: ${i.id}.data${m?"."+m:""} -> _global.${p}`)}}}}getValueByPath(e,n){return n.split(".").reduce((r,i)=>r?.[i],e)}updateGlobalState(e){this.globalState={...this.globalState,...e}}updateLocale(e){this.locale=e,this.debug&&Ht.log("Locale updated:",e)}isConfigLoaded(){return this.configLoaded}async hasErrorLayout(e){const n=await this.loadConfig();return n?!!(n.layouts[e]||n.layouts[String(e)]):!1}clearConfigCache(){this.errorConfig=null,this.configLoaded=!1,this.debug&&Ht.log("Config cache cleared")}}const Yc=dt("AssetFailureNotice"),nb="g7-asset-failure-notice",PA="g7-system-banners",Kr=new Map;let vs=!1,Xc=!1,qo=null;function Di(s,e,n){try{const r=window?.G7Core?.t;if(typeof r=="function"){const i=r(s,n);if(typeof i=="string"&&i!==s&&!i.startsWith("core.assets."))return i}}catch{}return BA(e,n)}function BA(s,e){return e?Object.entries(e).reduce((n,[r,i])=>n.split("{"+r+"}").join(String(i)),s):s}function Ss(s){!s||!s.id||(Kr.set(s.id,s),Xc=!1,Yc.warn(`Asset failure notified: ${s.id} (${s.label})`),ws())}function rb(s){Kr.delete(s)&&(Yc.log(`Asset failure cleared: ${s}`),ws())}function ab(){Kr.size!==0&&(Kr.clear(),ws())}function qA(){return Array.from(Kr.values())}function ib(s,e,n){return Di(s,e,n)}async function sb(){if(vs)return;vs=!0,Xc=!1,ws();const s=Array.from(Kr.values()).filter(n=>typeof n.retry=="function");let e=!1;for(const n of s)try{await n.retry(),Kr.delete(n.id)}catch(r){e=!0,Yc.warn(`Asset retry failed: ${n.id}`,r)}vs=!1,Xc=e,ws()}function GA(){try{return document.documentElement.classList.contains("dark")}catch{return!1}}function ws(){if(typeof document>"u"||!document.body)return;const s=document.getElementById(nb);if(Kr.size===0){s?.remove(),JA();return}const e=s??FA();VA(e),e.replaceChildren(KA()),XA()}function FA(){const s=document.createElement("div");return s.id=nb,s.setAttribute("role","alert"),s.setAttribute("aria-live","polite"),document.body.appendChild(s),s}function VA(s){const n=document.getElementById(PA)?.offsetHeight??0;s.style.cssText=["position:fixed",`top:${n}px`,"left:0","right:0","z-index:9998","display:flex","justify-content:center","pointer-events:none"].join(";")}function KA(){const s=GA(),e=Array.from(Kr.values()),n=typeof window<"u"&&window.innerWidth<768,r=document.createElement("div");return r.style.cssText=["pointer-events:auto","box-sizing:border-box","width:100%","max-width:960px","margin:8px","padding:12px 16px","border-radius:8px",`border:1px solid ${s?"#78350f":"#fcd34d"}`,`background:${s?"#451a03":"#fffbeb"}`,`color:${s?"#fef3c7":"#78350f"}`,"box-shadow:0 4px 12px rgba(0,0,0,0.12)","font-size:14px","line-height:1.5","display:flex",n?"flex-direction:column":"flex-direction:row",n?"align-items:stretch":"align-items:center","gap:12px"].join(";"),r.style.background=s?"#451a03":"#fffbeb",r.style.color=s?"#fef3c7":"#78350f",r.style.borderColor=s?"#78350f":"#fcd34d",r.appendChild(WA(e,n)),r.appendChild(YA(e,n,s)),r}function WA(s,e){const n=document.createElement("div");n.style.cssText=["flex:1 1 auto","min-width:0","display:flex","gap:8px"].join(";");const r=document.createElement("span");r.setAttribute("aria-hidden","true"),r.textContent="⚠",r.style.cssText="flex:0 0 auto;font-size:16px;line-height:1.4",n.appendChild(r);const i=document.createElement("div");if(i.style.cssText="flex:1 1 auto;min-width:0",s.length===1){const l=s[0],c=document.createElement("div");c.setAttribute("data-asset-failure-id",l.id),c.textContent=l.message??Di("core.assets.load_failed","{label}을(를) 불러오지 못했습니다.",{label:l.label}),i.appendChild(c)}else{const l=document.createElement("div");l.style.cssText="font-weight:600",l.textContent=Di("core.assets.load_failed_multiple","{count}개 항목을 불러오지 못했습니다.",{count:s.length}),i.appendChild(l);const c=document.createElement("div");c.style.cssText="margin-top:2px;opacity:0.9;word-break:break-word",c.textContent=s.map(d=>d.label).join(", "),i.appendChild(c)}if(Xc){const l=document.createElement("div");l.style.cssText="margin-top:4px;font-weight:600",l.textContent=Di("core.assets.retry_failed","다시 시도했지만 실패했습니다. 잠시 후 다시 시도해 주세요."),i.appendChild(l)}return n.appendChild(i),e&&(n.style.alignItems="flex-start"),n}function YA(s,e,n){const r=document.createElement("div");if(r.style.cssText=["flex:0 0 auto","display:flex","gap:8px",e?"width:100%":"","align-items:center"].filter(Boolean).join(";"),s.some(c=>typeof c.retry=="function")){const c=document.createElement("button");c.type="button",c.dataset.action="retry",c.disabled=vs,c.textContent=vs?Di("core.assets.retrying","다시 시도 중..."):Di("core.assets.retry","다시 시도"),c.style.cssText=[e?"flex:1 1 auto":"","padding:6px 14px","border-radius:6px","font-size:14px","font-weight:600","cursor:pointer",`border:1px solid ${n?"#b45309":"#d97706"}`,`background:${n?"#b45309":"#f59e0b"}`,`color:${n?"#fffbeb":"#451a03"}`,vs?"opacity:0.6":""].filter(Boolean).join(";"),c.addEventListener("click",()=>{sb()}),r.appendChild(c)}const l=document.createElement("button");return l.type="button",l.dataset.action="close",l.setAttribute("aria-label",Di("core.assets.close","닫기")),l.textContent="✕",l.style.cssText=["padding:6px 10px","border-radius:6px","font-size:14px","cursor:pointer","border:1px solid transparent","background:transparent",`color:${n?"#fef3c7":"#78350f"}`].join(";"),l.addEventListener("click",()=>{ab()}),r.appendChild(l),r}function XA(){qo||typeof MutationObserver>"u"||(qo=new MutationObserver(()=>{Kr.size>0&&ws()}),qo.observe(document.documentElement,{attributes:!0,attributeFilter:["class"]}))}function JA(){qo?.disconnect(),qo=null}function QA(){const s=window,e=r=>({id:String(r?.id??""),label:String(r?.label??r?.url??"asset"),retry:typeof r?.retry=="function"?r.retry:void 0}),n=Array.isArray(s.__g7ExternalAssetFailures)?s.__g7ExternalAssetFailures:[];n.forEach(r=>{r?.id&&Ss(e(r))}),s.__g7ExternalAssetSink=r=>{r?.id&&Ss(e(r))},Yc.log(`템플릿 externals 실패 대기열 ${n.length}건 반영`)}const Et=dt("ModuleAssetLoader");function ZA(s){return s==="plugin"?ib("core.assets.plugin_styles","플러그인 스타일"):ib("core.assets.module_styles","모듈 스타일")}class ex{constructor(){$(this,"loadedAssets",new Map);$(this,"loadingPromises",new Map);$(this,"failedJsAssets",new Set);$(this,"failedCssAssets",new Set)}getFailedCssAssets(){return[...this.failedCssAssets]}hasFailedJsAssets(){return this.failedJsAssets.size>0}getFailedJsAssets(){return[...this.failedJsAssets]}async loadActiveExtensionAssets(e){if(!e||e.length===0){Et.log("No module assets to load");return}const n=[...e].sort((d,f)=>d.priority-f.priority);Et.log("Loading module assets:",n.map(d=>d.identifier));const r=n.filter(d=>d.css).map(d=>this.loadCSS(d.identifier,d.css)),i=n.filter(d=>d.js).map(d=>this.loadJS(d.identifier,d.js)),l=await Promise.allSettled([...r,...i]),c=l.filter(d=>d.status==="rejected");if(c.length>0){Et.warn(`Some module assets failed to load (${c.length}/${l.length}); continuing with the rest`,this.getFailedJsAssets());return}Et.log("All module assets loaded successfully")}async loadBundle(e,n,r){const i=[];if(r&&i.push(this.loadBundleCss(e,r)),n&&i.push(this.loadBundleJs(e,n)),i.length===0){Et.log(`No bundle assets to load for: ${e}`);return}await Promise.all(i)}async loadCustomAssets(){const e=tx();if(e.length!==0)for(const n of e){const r=`g7-custom-${n.type}-${nx(n.id)}`;if(document.getElementById(r))continue;const i=`${n.type==="style"?"custom CSS":"custom JS"}: ${n.id}`,l=(d,f)=>n.type==="style"?sa(xn(d),{id:r},{label:i,retries:f}):Cr(xn(d),{id:r},{label:i,retries:f}),c=Dd(n.url);try{if(c!==null)try{await l(n.url,0)}catch{Et.warn(`Custom asset static miss, falling back to API: ${n.id} (${n.url} -> ${c})`),await l(c)}else await l(n.url);Et.log(`Custom asset loaded: ${n.id}`)}catch(d){Et.warn(`Failed to load custom asset: ${n.id} (${n.url})`,d),Ss({id:`custom-asset:${n.id}`,label:n.id.split(":").pop()??n.id,retry:async()=>{document.getElementById(r)?.remove(),await l(c??n.url)}})}}}async loadBundleCss(e,n){const r=`ext-bundle-css-${e}`;if(document.getElementById(r)){Et.log(`Bundle CSS already loaded: ${e}`);return}const i=Dd(n);try{if(i!==null)try{await sa(n,{id:r},{label:`bundle CSS: ${e}`,retries:0})}catch{Et.warn(`Bundle CSS static miss, falling back to API: ${e} (${n} -> ${i})`),await sa(xn(i),{id:r},{label:`bundle CSS: ${e}`})}else await sa(n,{id:r},{label:`bundle CSS: ${e}`});Et.log(`Bundle CSS loaded: ${e}`);const l=document.getElementById(r);l&&this.registerLoadedAsset(`bundle-${e}`,{type:"css",element:l})}catch(l){this.surfaceCssFailure(`bundle-${e}`,ZA(e),i!==null?xn(i):n,l)}}async loadBundleJs(e,n){const r=`ext-bundle-js-${e}`;if(document.getElementById(r)){Et.log(`Bundle JS already loaded: ${e}`);return}const i=this.loadingPromises.get(r);if(i)return Et.log(`Bundle JS already loading: ${e}`),i;const l=Dd(n),d=(l!==null?Cr(n,{id:r},{label:`bundle JS: ${e}`,retries:0}).catch(()=>(Et.warn(`Bundle JS static miss, falling back to API: ${e} (${n} -> ${l})`),Cr(xn(l),{id:r},{label:`bundle JS: ${e}`}))):Cr(n,{id:r},{label:`bundle JS: ${e}`})).then(()=>{Et.log(`Bundle JS loaded: ${e}`);const f=document.getElementById(r);f&&this.registerLoadedAsset(`bundle-${e}`,{type:"js",element:f}),this.loadingPromises.delete(r)}).catch(f=>{throw Et.warn(`Failed to load bundle JS: ${e} (${n})`,f),this.failedJsAssets.add(e),this.loadingPromises.delete(r),f});return this.loadingPromises.set(r,d),d}async loadCSS(e,n){const r=`module-css-${e}`;if(document.getElementById(r)){Et.log(`CSS already loaded: ${e}`);return}const i=this.loadingPromises.get(r);if(i)return Et.log(`CSS already loading: ${e}`),i;const l=sa(n,{id:r},{label:`CSS: ${e}`}).then(()=>{Et.log(`CSS loaded: ${e}`);const c=document.getElementById(r);c&&this.registerLoadedAsset(e,{type:"css",element:c}),this.loadingPromises.delete(r)}).catch(c=>{this.loadingPromises.delete(r),this.surfaceCssFailure(e,e,n,c)});return this.loadingPromises.set(r,l),l}surfaceCssFailure(e,n,r,i){Et.warn(`Failed to load CSS after retries: ${e} (${r})`,i),this.failedCssAssets.add(e),Ss({id:`ext-css:${e}`,label:n,retry:async()=>{document.getElementById(`module-css-${e}`)?.remove(),document.getElementById(`ext-bundle-css-${e.replace(/^bundle-/,"")}`)?.remove(),await sa(r,{},{label:`CSS retry: ${e}`}),this.failedCssAssets.delete(e)}})}async loadJS(e,n){const r=`module-js-${e}`;if(document.getElementById(r)){Et.log(`JS already loaded: ${e}`);return}const i=this.loadingPromises.get(e);if(i)return Et.log(`JS already loading: ${e}`),i;const l=Cr(n,{id:r},{label:`JS: ${e}`}).then(()=>{Et.log(`JS loaded: ${e}`);const c=document.getElementById(r);c&&this.registerLoadedAsset(e,{type:"js",element:c}),this.loadingPromises.delete(e)}).catch(c=>{throw Et.warn(`Failed to load JS: ${e} (${n})`,c),this.failedJsAssets.add(e),this.loadingPromises.delete(e),c});return this.loadingPromises.set(e,l),l}registerLoadedAsset(e,n){const r=this.loadedAssets.get(e)||[];r.push(n),this.loadedAssets.set(e,r)}unloadExtensionAsset(e){const n=this.loadedAssets.get(e);if(!n||n.length===0){Et.log(`No assets to unload for: ${e}`);return}n.forEach(r=>{r.element.parentNode&&(r.element.parentNode.removeChild(r.element),Et.log(`${r.type.toUpperCase()} unloaded: ${e}`))}),this.loadedAssets.delete(e),Et.log(`All assets unloaded for: ${e}`)}unloadAllAssets(){Array.from(this.loadedAssets.keys()).forEach(n=>{this.unloadExtensionAsset(n)}),Et.log("All module assets unloaded")}isLoaded(e){return this.loadedAssets.has(e)}getLoadedModules(){return Array.from(this.loadedAssets.keys())}}let Qf=null;function tx(){const s=window?.G7Config?.customAssets;return Array.isArray(s)?s.filter(e=>e&&typeof e.id=="string"&&typeof e.url=="string"&&(e.type==="style"||e.type==="script")):[]}function nx(s){return s.replace(/[^A-Za-z0-9_-]/g,"-")}function Zf(){return Qf||(Qf=new ex),Qf}function rx(){if(typeof window>"u")return[];const s=window.G7Config;if(!s?.moduleAssets)return[];const e=[];for(const[n,r]of Object.entries(s.moduleAssets)){const i=r;e.push({identifier:n,js:i.js?xn(i.js):i.js,css:i.css?xn(i.css):i.css,priority:i.priority,external:i.external})}return e}function ax(){if(typeof window>"u")return null;const s=window.G7Config;if(!s?.bundleUrls)return null;const e=s.bundleUrls;return{moduleJs:e.moduleJs?xn(e.moduleJs):e.moduleJs,moduleCss:e.moduleCss?xn(e.moduleCss):e.moduleCss,pluginJs:e.pluginJs?xn(e.pluginJs):e.pluginJs,pluginCss:e.pluginCss?xn(e.pluginCss):e.pluginCss}}function ix(){if(typeof window>"u")return[];const s=window.G7Config;if(!s?.pluginAssets)return[];const e=[];for(const[n,r]of Object.entries(s.pluginAssets)){const i=r;e.push({identifier:n,js:i.js?xn(i.js):i.js,css:i.css?xn(i.css):i.css,priority:i.priority,external:i.external})}return e}const eh=dt("SystemBannerManager");class Jc{static show(e){this.banners.set(e.id,e),this.render(),eh.log(`Banner shown: ${e.id}`)}static hide(e){this.banners.delete(e)&&(this.render(),eh.log(`Banner hidden: ${e}`))}static hideAll(){this.banners.clear(),this.render(),eh.log("All banners hidden")}static detectLocale(){try{const n=window.G7Core;if(n?.locale?.current)return n.locale.current()}catch{}return(navigator.language||"ko").split("-")[0]}static resolveMessage(e,n){return typeof e=="string"?e:e[n]||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 n=Array.from(this.banners.values()).sort((i,l)=>(i.order??0)-(l.order??0)),r=this.detectLocale();e.innerHTML=n.map(i=>{const l=this.resolveMessage(i.message,r),c=i.background||"#f59e0b",d=i.color||"white";return`
${l}
`}).join(""),requestAnimationFrame(()=>{e&&this.adjustAppPadding(e.offsetHeight)})}static adjustAppPadding(e){const n=document.getElementById("app");n&&(n.style.paddingTop=e>0?`${e}px`:"")}}$(Jc,"banners",new Map),$(Jc,"containerId","g7-system-banners");const U=dt("TemplateApp");function ob(s){const e={};for(const n of s.keys()){if(n in e)continue;const r=s.getAll(n);r.length>1?e[n]=r:r.length===1&&(n.endsWith("[]")?e[n]=r:e[n]=r[0])}return e}const Lr=class Lr{constructor(e){$(this,"router",null);$(this,"layoutLoader",null);$(this,"errorPageHandler",null);$(this,"config");$(this,"globalState");$(this,"globalStateListeners",new Set);$(this,"currentRouteChangeId",0);$(this,"failedLayoutScripts",new Set);$(this,"currentDataSources",[]);$(this,"currentRawDataSources",[]);$(this,"currentRouteParams",{});$(this,"currentQueryParams",new URLSearchParams);$(this,"currentFetchedData",{});$(this,"currentLayoutName","");$(this,"templateErrorHandling",null);$(this,"currentWebSocketSubscriptions",[]);$(this,"extensionCacheVersion",0);$(this,"currentGlobalHeaders",[]);$(this,"transitionOverlayEl",null);$(this,"skeletonOverlayRoot",null);$(this,"skeletonOverlayContainer",null);$(this,"_spinnerState",null);$(this,"modalDataSources",new Map);this.globalState={sidebarOpen:!1},this.loadG7Config(),this.migrateLocaleStorage();const n=this.loadLocaleFromStorage(),r=n||e.locale||"ko";this.config={...e,locale:r},!n&&e.locale&&this.saveLocaleToStorage(e.locale)}loadG7Config(){if(typeof window<"u"&&window.G7Config){const e=window.G7Config;e.settings&&(this.globalState.settings=e.settings,U.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,U.log("Loaded plugin settings from G7Config:",Object.keys(e.plugins))),e.modules&&(this.globalState.modules=e.modules,U.log("Loaded module settings from G7Config:",Object.keys(e.modules))),e.appConfig&&(this.globalState.appConfig=e.appConfig,U.log("Loaded appConfig from G7Config:",Object.keys(e.appConfig)))}}resolveRouteExpressions(e){const n=new Tn,r={_global:this.globalState};return e.map(i=>{const l={...i};if(l.path&&l.path.includes("{{")){const c=l.path;l.path=n.resolveBindings(l.path,r),l.path=l.path.replace(/\/\/+/g,"/")||"/",l.path.includes("{{")&&(U.warn("Route expression resolution failed, using fallback:",c),l.path=c.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}if(l.redirect&&l.redirect.includes("{{")){const c=l.redirect;l.redirect=n.resolveBindings(l.redirect,r),l.redirect=l.redirect.replace(/\/\/+/g,"/")||"/",l.redirect.includes("{{")&&(U.warn("Route redirect expression resolution failed:",c),l.redirect=c.replace(/\{\{[^}]+\}\}/g,"").replace(/\/\/+/g,"/")||"/")}return l})}migrateLocaleStorage(){const e=["locale","g7_template_locale"];for(const n of e)try{const r=localStorage.getItem(n);r&&r!==localStorage.getItem(Lr.LOCALE_STORAGE_KEY)&&(localStorage.setItem(Lr.LOCALE_STORAGE_KEY,r),U.log(`Migrated locale from '${n}' to '${Lr.LOCALE_STORAGE_KEY}'`)),localStorage.removeItem(n)}catch(r){U.warn(`Failed to migrate locale key '${n}':`,r)}}async init(){try{ho.getInstance().setDebug(this.config.debug),U.log("Initializing with config:",this.config),Ww();const e=Er.getInstance(),n=Yn.getInstance(),r=typeof window<"u"&&Number(window.G7Config?.cache_version)||0,i=r>0?r:this.loadCacheVersionFromStorage()||0,[l,c,d,f,p]=await Promise.all([Yo({templateId:this.config.templateId,templateType:this.config.templateType,locale:this.config.locale,debug:this.config.debug,cacheVersion:i}),e.loadComponents(this.config.templateId,this.config.templateType,i),ic(i>0?po(`templates/${this.config.templateId}/routes.json`,i):null,Pr(`/api/templates/${this.config.templateId}/routes`,"json",i>0?i:null),{label:"routes.json"}).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 U.error("Error loading routes:",w),w}),n.preloadAuth(this.config.templateType==="admin"?"admin":"user"),fetch(Pr(`/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=>(U.warn("Error loading template config:",w),null))]);if(U.log("Template Engine initialized"),U.log("ComponentRegistry loaded"),U.log("Routes data loaded"),U.log("User info preloaded"),U.log("Template config loaded:",p),p?.cache_version!==void 0){const w=i>0?i:null;if(this.extensionCacheVersion=p.cache_version,this.saveCacheVersionToStorage(this.extensionCacheVersion),U.log("Extension cache version:",this.extensionCacheVersion),w!==null&&w!==this.extensionCacheVersion){U.log("Cache version changed, reloading routes...");const R=await ic(po(`templates/${this.config.templateId}/routes.json`,this.extensionCacheVersion),Pr(`/api/templates/${this.config.templateId}/routes`,"json",this.extensionCacheVersion),{label:"routes.json (reload)"}).then(L=>{if(!L.ok)throw new Error(`Failed to reload routes: ${L.statusText}`);return L.json()}).then(L=>{if(!L.success)throw new Error("Failed to reload routes from API");return L.data});Array.isArray(R.routes)&&(R.routes=this.resolveRouteExpressions(R.routes),Object.assign(d,R),U.log("Routes reloaded with new cache version"));try{const{TranslationEngine:L}=await Promise.resolve().then(()=>$g),O=L.getInstance();O.setCacheVersion(this.extensionCacheVersion);const j=this.config.locale||"ko",F="en";await O.loadTranslations(this.config.templateId,j,"/api",!0),j!==F&&await O.loadTranslations(this.config.templateId,F,"/api",!0),U.log("Translations reloaded with new cache version")}catch(L){U.error("Failed to reload translations:",L)}}}p?.errorHandling&&(this.templateErrorHandling=p.errorHandling,Tr().setTemplateConfig(this.templateErrorHandling),U.log("Template errorHandling registered:",this.templateErrorHandling)),n.on("logout",()=>{U.log("User logged out")}),n.on("authStateChange",w=>{U.log("Auth state changed:",w)}),U.log("AuthManager event handlers registered");const m=Wn(),y=this.config.templateType==="admin"?"admin":"user",C=n.getConfig(y);m.setOnUnauthorized(()=>{U.log("Unauthorized - redirecting to login page"),m.removeToken();const w=window.location.pathname+window.location.search,R=n.getLoginRedirectUrl(y,w,"session_expired");window.location.href=R}),U.log("ApiClient onUnauthorized callback registered"),this.layoutLoader=new Gf(e),this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),U.log("LayoutLoader initialized:",this.layoutLoader);const S=new Dr({onUnauthorized:()=>{U.warn("Unauthorized request in error page")}});if(this.errorPageHandler=new UA({templateId:this.config.templateId,layoutLoader:this.layoutLoader,locale:this.config.locale,debug:this.config.debug,renderFunction:Es,dataSourceManager:S,globalState:this.globalState}),U.log("ErrorPageHandler initialized with DataSourceManager"),await this.handleServerError()){U.log("Server error handled, skipping normal initialization");return}if(this.router=new zA(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");U.log("Router initialized:",this.router),U.log("Routes set:",this.router.getRoutes());const{getActionDispatcher:v}=await Promise.resolve().then(()=>Wr),x=v();if(x&&(x.setDefaultContext({navigate:w=>this.router?.navigate(w)}),x.setGlobalStateUpdater((w,R)=>this.setGlobalState(w,R)),U.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)),typeof window<"u"&&tb(window.location.pathname)){U.log("Layout editor mode detected — skipping router match"),await Es({containerId:"app",layoutJson:{components:[]},dataContext:{},translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),U.log("Template App initialized in layout editor mode");return}this.router.navigateToCurrentPath(),U.log("Template App initialized successfully")}catch(e){U.error("Initialization failed:",e),this.showInitError(e)}}async loadExtensionAssets(){try{const e=Zf(),n=ax();if(!n){await this.loadExtensionAssetsIndividually(),await e.loadCustomAssets();return}await e.loadBundle("module",n.moduleJs,n.moduleCss),await e.loadBundle("plugin",n.pluginJs,n.pluginCss),await e.loadCustomAssets(),U.log("Extension bundle assets loaded successfully")}catch(e){U.warn("Failed to load extension assets:",e)}}async loadExtensionAssetsIndividually(){const e=Zf(),n=rx();n.length>0&&(U.log("Loading module assets (individual fallback):",n.map(i=>i.identifier)),await e.loadActiveExtensionAssets(n));const r=ix();r.length>0&&(U.log("Loading plugin assets (individual fallback):",r.map(i=>i.identifier)),await e.loadActiveExtensionAssets(r))}async handleRouteChange(e){const n=++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(U.log("Route changed:",e,"requestId:",n),!this.layoutLoader)throw new Error("LayoutLoader is not initialized");if(!e.layout)throw new Error("Route layout is not defined");let r=e.layout;const i=r==="__preview__";i&&e.params?.token&&(r=`__preview__/${e.params.token}`);const l=await this.layoutLoader.loadLayout(this.config.templateId,r);if(n!==this.currentRouteChangeId){U.log("Route change cancelled (newer request exists):",n);return}U.log("Layout loaded:",l);const c=Tr();l.errorHandling?(c.setLayoutConfig(l.errorHandling),U.log("Layout errorHandling registered:",l.errorHandling)):c.clearLayoutConfig();const d=l.data_sources||[],f=e.query||{},p=new URLSearchParams;for(const[Z,ge]of Object.entries(f))if(Array.isArray(ge))for(const z of ge)p.append(Z,z);else p.set(Z,ge);const m={route:e.params||{},query:f,_global:this.globalState};l.scripts&&Array.isArray(l.scripts)&&await this.loadLayoutScripts(l.scripts,m);const{DataSourceManager:y,getActionDispatcher:C}=await Promise.resolve().then(()=>Wr),S=new y;if(i){const Z=C();Z&&Z.setPreviewMode(!0),this.setGlobalState({__isPreview:!0}),Jc.show({id:"preview-mode",message:{ko:"⚠ 미리보기 모드 — 페이지 이동이 비활성화됩니다",en:"⚠ Preview Mode — Navigation is disabled"},background:"linear-gradient(90deg, #f59e0b, #d97706)",color:"white"}),U.log("Preview mode activated")}else{const Z=C();Z?.isPreviewMode()&&(Z.setPreviewMode(!1),Jc.hide("preview-mode"))}if(this.currentGlobalHeaders=l.globalHeaders||[],this.currentGlobalHeaders.length>0){S.setGlobalHeaders(this.currentGlobalHeaders);const Z=C();Z&&Z.setGlobalHeaders(this.currentGlobalHeaders),U.log("globalHeaders set:",this.currentGlobalHeaders.map(ge=>ge.pattern))}if(l.named_actions&&Object.keys(l.named_actions).length>0){const Z=C();Z&&Z.setNamedActions(l.named_actions)}const v=S.filterByCondition(d,m);d.length!==v.length&&U.log("Data sources filtered by condition:",{before:d.map(Z=>Z.id),after:v.map(Z=>Z.id)});const x=v.filter(Z=>Z.loading_strategy==="blocking"),w=v.filter(Z=>(Z.loading_strategy||"progressive")!=="blocking"&&Z.type!=="websocket"),R=Array.isArray(l.transition_overlay?.wait_for)?l.transition_overlay.wait_for:[],L=R.length>0&&v.some(Z=>R.includes(Z.id)&&Z.type!=="websocket"&&(Z.loading_strategy||"progressive")!=="background");if((x.length>0||L)&&l.transition_overlay){const Z=typeof l.transition_overlay=="boolean"?{enabled:l.transition_overlay,style:"opaque"}:l.transition_overlay;Z.enabled&&Z.style==="skeleton"&&Z.skeleton?.component&&Z.target?this.renderSkeletonOverlay(Z.target,Z.skeleton,l,Z.fallback_target):Z.enabled&&Z.style==="spinner"&&Z.target&&this.renderSpinnerOverlay(Z.target,Z.spinner,Z.fallback_target)}let O={},j={},F={},G={};this.currentWebSocketSubscriptions.length>0&&(U.log("Unsubscribing previous WebSocket subscriptions:",this.currentWebSocketSubscriptions),S.unsubscribeWebSockets(this.currentWebSocketSubscriptions),this.currentWebSocketSubscriptions=[]),this.currentDataSources=v,this.currentRawDataSources=d,this.currentRouteParams=e.params||{},this.currentQueryParams=p,U.log(`handleRouteChange #${n} - queryObject:`,f),U.log(`handleRouteChange #${n} - queryParams:`,p.toString()),x.length>0&&(U.log("Fetching blocking data sources:",x.map(ge=>ge.id)),(await S.fetchDataSourcesWithResults(x,e.params||{},p)).forEach(ge=>{if(ge.state==="success"&&ge.data!==void 0)O[ge.id]=ge.data;else if(ge.state==="error"&&ge.error){const z=ge.error,T=z.response?.data?.message;j[ge.id]={message:T||ge.error.message,status:z.response?.status||z.status}}}),this.processInitOptions(x,O,F,G),this.currentFetchedData={...O},U.log("Blocking data loaded:",Object.keys(O)),Object.keys(j).length>0&&U.log("Data source errors:",j),Object.keys(F).length>0&&U.log("Local state init (blocking):",Object.keys(F)),Object.keys(G).length>0&&U.log("Isolated state init (blocking):",Object.keys(G)));const P=w.length>0;if(P&&(Gr.setPending(!0),U.log("Transition started before rendering")),n!==this.currentRouteChangeId){U.log("Route change cancelled after blocking data (newer request exists):",n);return}const{getState:K}=await Promise.resolve().then(()=>Wr),he=K().currentDataContext||{},Ee=w.map(Z=>Z.id),ke={};if(P){Ee.forEach(ge=>{he[ge]!==void 0?ke[ge]=he[ge]:ke[ge]=void 0});const Z=Object.keys(ke).filter(ge=>ke[ge]!==void 0);Z.length>0&&U.log("Preserving previous progressive data:",Z),U.log("Progressive data sources initialized:",Ee)}const ze=l.defines||{},Be={...ke,...e.params,...O,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState},_globalSetState:Z=>this.setGlobalState(Z),_dataSourceErrors:Object.keys(j).length>0?j:void 0,_localInit:Object.keys(F).length>0?F:void 0,_isolatedInit:Object.keys(G).length>0?G:void 0,_defines:Object.keys(ze).length>0?ze:void 0};if(l.computed&&Object.keys(l.computed).length>0){const Z=this.calculateComputed(l.computed,Be);Object.keys(Z).length>0&&(Be._computed=Z,this.globalState._computed=Z,U.log("Computed values calculated:",Object.keys(Z))),Be._computedDefinitions=l.computed}const je=l.layout_name||e.layout;this.currentLayoutName!==""&&this.currentLayoutName!==je&&(U.log("_local reset due to layout change:",{from:this.currentLayoutName,to:je}),this.globalState._local={},eE()),this.currentLayoutName=je;const X=l.initLocal||l.state;if(X&&Object.keys(X).length>0){this.globalState._local||(this.globalState._local={});for(const[Z,ge]of Object.entries(X))this.globalState._local[Z]===void 0&&(this.globalState._local[Z]=JSON.parse(JSON.stringify(ge)));Be._local={...this.globalState._local},U.log("initLocal applied to _local:",Object.keys(X))}if(l.initGlobal&&Object.keys(l.initGlobal).length>0){for(const[Z,ge]of Object.entries(l.initGlobal))this.globalState[Z]===void 0&&(this.globalState[Z]=JSON.parse(JSON.stringify(ge)));U.log("initGlobal applied to _global:",Object.keys(l.initGlobal))}if(l.initIsolated&&Object.keys(l.initIsolated).length>0){for(const[Z,ge]of Object.entries(l.initIsolated))G[Z]===void 0&&(G[Z]=JSON.parse(JSON.stringify(ge)));U.log("initIsolated applied:",Object.keys(l.initIsolated))}Be._global={...this.globalState,layoutWarnings:l.warnings||[]};const de=l.initActions||l.init_actions;if(de&&de.length>0){await this.executeInitActions(de,Be),U.log("initActions executed before render");const Z=this.globalState;if(Z._local){if(Object.keys(F).length>0){for(const[ge,z]of Object.entries(F))Z._local[ge]!==void 0?Z._local[ge]=this.deepMerge(Z._local[ge],z):Z._local[ge]=z;U.log("localInit merged into _local after initActions:",Object.keys(F))}Be._local=Z._local,U.log("_local merged into dataContext:",Z._local)}if(Be._global={...this.globalState,layoutWarnings:l.warnings||[]},U.log("_global merged into dataContext after initActions"),l.computed&&Object.keys(l.computed).length>0){const ge=this.calculateComputed(l.computed,Be);Object.keys(ge).length>0&&(Be._computed=ge,this.globalState._computed=ge,U.log("Computed values recalculated after init_actions:",Object.keys(ge)))}if(Object.keys(this.currentFetchedData).length>0){for(const[ge,z]of Object.entries(this.currentFetchedData))Be[ge]=z;U.log("Fetched data sources merged into dataContext after initActions:",Object.keys(this.currentFetchedData))}}if(l.transition_overlay&&!this.skeletonOverlayContainer&&this.showTransitionOverlay(l.transition_overlay,l),await Es({containerId:"app",layoutJson:l,dataContext:Be,translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),U.log("Initial render complete with blocking data"),this.reattachSpinnerOverlay(),w.length>0){if(n!==this.currentRouteChangeId){U.log("Route change cancelled before progressive fetch (newer request exists):",n),Gr.setPending(!1),this.hideTransitionOverlay();return}U.log("Fetching progressive/background data sources:",w.map(z=>z.id));const{updateTemplateData:Z,getState:ge}=await Promise.resolve().then(()=>Wr);try{const z=w.map(async T=>{try{const fe=(await S.fetchDataSourcesWithResults([T],e.params||{},p,this.globalState))[0];if(!fe){U.log(`Data source ${T.id} skipped (no fetch result)`);return}if(n!==this.currentRouteChangeId){U.log(`Data source ${T.id} fetch cancelled (newer request exists)`);return}if(fe.state==="success"&&fe.data!==void 0){U.log(`Progressive data source loaded: ${T.id}`),this.currentFetchedData[T.id]=fe.data;const me={};this.processInitOptions([T],{[T.id]:fe.data},me);const ae=ge();if(ae.bindingEngine){const Pe=[T.id];T.initGlobal&&Pe.push("_global"),T.initLocal&&Pe.push("_local"),ae.bindingEngine.invalidateCacheByKeys(Pe)}const Re={[T.id]:fe.data};Object.keys(me).length>0&&(Re._localInit=me,Object.assign(F,me)),T.initGlobal&&(Re._global={...this.globalState}),Z(Re)}else if(fe.state==="error"&&fe.error){const me=fe.error,ae=me.response?.data?.message;j[T.id]={message:ae||fe.error.message,status:me.response?.status||me.status},U.log(`Progressive data source error: ${T.id}`,j[T.id]),Z({[T.id]:null,_dataSourceErrors:{...j}})}}catch(pe){U.error(`Failed to fetch data source: ${T.id}`,pe)}});if(await Promise.all(z),n!==this.currentRouteChangeId){U.log("Route change cancelled after progressive fetch (newer request exists):",n);return}U.log("All progressive data sources loaded")}finally{Gr.setPending(!1),this.hideTransitionOverlay()}}else this.hideTransitionOverlay();const Ce=v.filter(Z=>Z.type==="websocket");if(Ce.length>0){U.log("Subscribing WebSocket data sources:",Ce.map(T=>T.id));const{updateTemplateData:Z,getState:ge}=await Promise.resolve().then(()=>Wr),z={...this.currentFetchedData,...e.params,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState}};U.log("WebSocket binding context keys:",Object.keys(z)),this.currentWebSocketSubscriptions=S.subscribeWebSockets(v,(T,pe)=>{U.log(`WebSocket data received for: ${T}`,pe),this.currentFetchedData[T]=pe;const fe=v.find(Pe=>Pe.id===T),me=ge();if(me.bindingEngine){const Pe=[T];fe?.initGlobal&&Pe.push("_global"),fe?.initLocal&&Pe.push("_local"),me.bindingEngine.invalidateCacheByKeys(Pe)}Z({[T]:pe});const Re=v.find(Pe=>Pe.type==="websocket"&&(Pe.target_source||Pe.id)===T)?.onReceive;Array.isArray(Re)&&Re.length>0&&window.G7Core?.dispatch&&(async()=>{for(const Me of Re)try{const Ge=this.getActionDispatcher?.();Ge&&await Ge.dispatchAction(Me,{navigate:this.getRouter?.()?(kt,vt)=>this.getRouter().navigate(kt,vt):void 0,setState:kt=>this.setGlobalState(kt),state:this.globalState,data:{...this.globalState,$args:[pe],$event:pe},_isDispatchFallbackContext:!0})}catch(Ge){U.error(`WebSocket onReceive action failed for ${T}:`,Ge)}})()},z),U.log("WebSocket subscriptions established:",this.currentWebSocketSubscriptions)}U.log("Layout rendered successfully")}catch(r){U.error("Route change handling failed:",r),this.hideTransitionOverlay(),this.showRouteError(r)}}processInitOptions(e,n,r,i){e.some(c=>c.refetchOnMount===!0&&c.initLocal)&&(r._forceLocalInit=Date.now(),U.log("refetchOnMount detected, forcing local state init")),e.forEach(c=>{const d=n[c.id];if(!d)return;const f=d.data??d;if(c.initLocal){if(typeof c.initLocal=="string"){let p=f;if(c.initLocalDefaults&&typeof c.initLocalDefaults=="object"){const y=this.evaluateDefaults(c.initLocalDefaults,n);p={...y,...f},U.log(`initLocalDefaults applied for ${c.initLocal}:`,Object.keys(y))}const m=this.globalState._local?.[c.initLocal];m!==void 0&&typeof m=="object"&&typeof p=="object"?(r[c.initLocal]=this.deepMerge(m,p),U.log(`initLocal (merged): ${c.id}.data -> _local.${c.initLocal}`)):(r[c.initLocal]=p,U.log(`initLocal: ${c.id}.data -> _local.${c.initLocal}`))}else if(typeof c.initLocal=="object"&&c.initLocal.key){const{key:p,path:m}=c.initLocal;let y=m?this.extractValueByPathOrExpression(f,m,c.id):f;if(c.initLocalDefaults&&typeof c.initLocalDefaults=="object"){const S=this.evaluateDefaults(c.initLocalDefaults,n);y={...S,...y},U.log(`initLocalDefaults applied for ${p}:`,Object.keys(S))}const C=this.globalState._local?.[p];C!==void 0&&typeof C=="object"&&typeof y=="object"?(r[p]=this.deepMerge(C,y),U.log(`initLocal (merged): ${c.id}.data${m?"."+m:""} -> _local.${p}`)):(r[p]=y,U.log(`initLocal: ${c.id}.data${m?"."+m:""} -> _local.${p}`))}else if(typeof c.initLocal=="object"){const p=c.initLocal._merge||"deep",m=this.flattenNestedObjectToMappings(c.initLocal);for(const{targetPath:y,sourcePath:C}of m){const S=this.extractValueByPathOrExpression(f,C,c.id);if(y.includes(".")){const v=y.split(".")[0];r[v]===void 0&&this.globalState._local?.[v]!==void 0&&(r[v]=JSON.parse(JSON.stringify(this.globalState._local[v]))),this.setValueAtPath(r,y,S,p),U.log(`initLocal map (${p}): ${c.id} ${C} -> _local.${y}`)}else{const v=this.globalState._local?.[y];p==="replace"?(r[y]=S,U.log(`initLocal map (replace): ${c.id} ${C} -> _local.${y}`)):p==="shallow"?v!==void 0&&typeof v=="object"&&typeof S=="object"?(r[y]={...v,...S},U.log(`initLocal map (shallow): ${c.id} ${C} -> _local.${y}`)):(r[y]=S,U.log(`initLocal map: ${c.id} ${C} -> _local.${y}`)):v!==void 0&&typeof v=="object"&&typeof S=="object"?(r[y]=this.deepMerge(v,S),U.log(`initLocal map (deep): ${c.id} ${C} -> _local.${y}`)):(r[y]=S,U.log(`initLocal map: ${c.id} ${C} -> _local.${y}`))}}}}if(c.initGlobal)if(typeof c.initGlobal=="object"&&!Array.isArray(c.initGlobal)&&!("key"in c.initGlobal))for(const[m,y]of Object.entries(c.initGlobal)){if(typeof y!="string"){U.warn(`initGlobal map value must be string, got ${typeof y} for key ${m}`);continue}const C=this.extractValueByPathOrExpression(f,y,c.id),S=this.globalState[m];S!==void 0&&typeof S=="object"&&typeof C=="object"?(this.globalState[m]=this.deepMerge(S,C),U.log(`initGlobal map (merged): ${c.id} ${y} -> _global.${m}`)):(this.globalState[m]=C,U.log(`initGlobal map: ${c.id} ${y} -> _global.${m}`))}else{const m=Array.isArray(c.initGlobal)?c.initGlobal:[c.initGlobal];for(const y of m)if(typeof y=="string"){const C=this.globalState[y];C!==void 0&&typeof C=="object"&&typeof f=="object"?(this.globalState[y]=this.deepMerge(C,f),U.log(`initGlobal (merged): ${c.id}.data -> _global.${y}`)):(this.globalState[y]=f,U.log(`initGlobal: ${c.id}.data -> _global.${y}`))}else if(typeof y=="object"&&y.key){const{key:C,path:S}=y,v=S?this.extractValueByPathOrExpression(f,S,c.id):f,x=this.globalState[C];x!==void 0&&typeof x=="object"&&typeof v=="object"?(this.globalState[C]=this.deepMerge(x,v),U.log(`initGlobal (merged): ${c.id}.data${S?"."+S:""} -> _global.${C}`)):(this.globalState[C]=v,U.log(`initGlobal: ${c.id}.data${S?"."+S:""} -> _global.${C}`))}}if(i&&c.initIsolated){if(typeof c.initIsolated=="string"){const p=i[c.initIsolated];p!==void 0&&typeof p=="object"&&typeof f=="object"?(i[c.initIsolated]=this.deepMerge(p,f),U.log(`initIsolated (merged): ${c.id}.data -> _isolated.${c.initIsolated}`)):(i[c.initIsolated]=f,U.log(`initIsolated: ${c.id}.data -> _isolated.${c.initIsolated}`))}else if(typeof c.initIsolated=="object"&&c.initIsolated.key){const{key:p,path:m}=c.initIsolated,y=m?this.extractValueByPathOrExpression(f,m,c.id):f,C=i[p];C!==void 0&&typeof C=="object"&&typeof y=="object"?(i[p]=this.deepMerge(C,y),U.log(`initIsolated (merged): ${c.id}.data${m?"."+m:""} -> _isolated.${p}`)):(i[p]=y,U.log(`initIsolated: ${c.id}.data${m?"."+m:""} -> _isolated.${p}`))}else if(typeof c.initIsolated=="object")for(const[p,m]of Object.entries(c.initIsolated)){if(typeof m!="string"){U.warn(`initIsolated map value must be string, got ${typeof m} for key ${p}`);continue}const y=this.extractValueByPathOrExpression(f,m,c.id),C=i[p];C!==void 0&&typeof C=="object"&&typeof y=="object"?(i[p]=this.deepMerge(C,y),U.log(`initIsolated map (merged): ${c.id} ${m} -> _isolated.${p}`)):(i[p]=y,U.log(`initIsolated map: ${c.id} ${m} -> _isolated.${p}`))}}})}evaluateDefaults(e,n){const r={};for(const[i,l]of Object.entries(e))if(typeof l=="string"&&l.startsWith("{{")&&l.endsWith("}}")){const c=l.slice(2,-2).trim();r[i]=this.evaluateExpression(c,n)}else r[i]=l;return r}evaluateExpression(e,n){try{const r=e.split("??").map(i=>i.trim());for(const i of r){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 l=this.getNestedValue(n,i);if(l!=null)return l}return}catch(r){U.warn(`Expression evaluation failed: ${e}`,r);return}}getNestedValue(e,n){const r=n.replace(/\?\./g,".");let i=e;const l=r.split(/\.(?![^\[]*\])/).flatMap(c=>{const d=c.match(/^([^\[]*)((?:\[\d+\])*)$/);if(d){const[,f,p]=d,m=[];f&&m.push(f);const y=p.match(/\[\d+\]/g);return y&&m.push(...y),m}return[c]}).filter(c=>c!=="");for(const c of l){if(i==null)return;if(c.startsWith("[")&&c.endsWith("]")){const d=parseInt(c.slice(1,-1),10);i=i[d]}else i=i[c]}return i}extractValueByPathOrExpression(e,n,r){const i=Ma(n);if(i!==null){const l=new Tn,c={data:e,_global:this.globalState,_local:this.globalState._local||{}};try{const d=On(i)?l.evaluatePipeExpression(i,c,{skipCache:!0}):l.evaluateExpression(i,c);return U.log(`initLocal/initGlobal expression evaluated: ${n} -> `,d),d}catch(d){U.warn(`initLocal/initGlobal expression evaluation failed for ${r}:`,n,d);return}}return this.getNestedValue(e,n)}async loadLayoutScripts(e,n){const r=[];for(const i of e){if((i.if!==void 0||i.conditions!==void 0)&&!os({if:i.if,conditions:i.conditions},n,this.bindingEngine,`script:${i.id}`)){U.log(`Script skipped (condition not met): ${i.id}`);continue}if(document.getElementById(i.id)){U.log(`Script already loaded: ${i.id}`);continue}if(!this.isAllowedScriptSrc(i.src)){U.warn(`Blocked untrusted external script src (same-origin path or declared trusted host required): ${i.id} (${i.src})`);continue}r.push(this.loadLayoutScript(i))}r.length>0&&(await Promise.all(r),U.log(`All scripts loaded: ${e.filter(i=>!document.getElementById(i.id)||r.length>0).map(i=>i.id).join(", ")}`))}async loadLayoutScript(e){const n=e.src.startsWith("/")?xn(e.src):e.src;try{await Cr(n,{id:e.id},{label:`layout-script:${e.id}`}),this.failedLayoutScripts.delete(e.id),rb(`layout-script:${e.id}`),U.log(`Script loaded successfully: ${e.id}`)}catch(r){this.failedLayoutScripts.add(e.id),U.warn(`Failed to load script after retries: ${e.id} (${n})`,r),Ss({id:`layout-script:${e.id}`,label:e.id,retry:async()=>{document.getElementById(e.id)?.remove(),await Cr(n,{id:e.id},{label:`layout-script:${e.id}`}),this.failedLayoutScripts.delete(e.id)}})}}getFailedLayoutScripts(){return Array.from(this.failedLayoutScripts)}isAllowedScriptSrc(e){return Oo(e)}static normalizeScriptSrcForOriginCheck(e){return Gm(e)}extractScriptHost(e){return Fm(e)}getTrustedScriptHosts(){return fs()}evaluateScriptCondition(e,n){try{if(e.startsWith("{{")&&e.endsWith("}}")){const r=e.slice(2,-2).trim();return!!Jd(r,n)}return!!e}catch(r){return U.warn(`Failed to evaluate script condition: ${e}`,r),!1}}showInitError(e){if(rc()){U.warn("Init failed while document is unloading — skipping error screen",e);return}const n=eb(e);Jf.renderFromError("app",n,"초기화 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}showTransitionOverlay(e,n){const r=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(!r.enabled)return;if(this.hideTransitionOverlay(),r.style==="skeleton"&&r.skeleton?.component&&r.target&&n){this.renderSkeletonOverlay(r.target,r.skeleton,n,r.fallback_target);return}if(r.style==="spinner"&&r.target){this.renderSpinnerOverlay(r.target,r.spinner,r.fallback_target);return}const i=document.documentElement.classList.contains("dark");let l,c="";switch(r.style){case"blur":l=i?"rgba(17,24,39,0.3)":"rgba(255,255,255,0.3)",c="backdrop-filter:blur(4px);-webkit-backdrop-filter:blur(4px);";break;case"fade":l=i?"rgba(17,24,39,0.8)":"rgba(255,255,255,0.8)";break;case"skeleton":l=i?"rgb(17,24,39)":"rgb(249,250,251)";break;case"opaque":default:l=i?"rgb(17,24,39)":"rgb(249,250,251)";break}if(r.target){const d=`#${CSS.escape(r.target)}`,f=document.createElement("style");f.id="g7-transition-overlay",f.textContent=`${d}{position:relative;z-index:0;}${d}::after{content:'';position:absolute;inset:0;background:${l};${c}z-index:2147483647;pointer-events:none;}`,document.head.appendChild(f),this.transitionOverlayEl=f}else{const d=document.createElement("div");d.id="g7-transition-overlay",d.setAttribute("aria-hidden","true"),d.style.position="fixed",d.style.inset="0",d.style.zIndex="9999",d.style.pointerEvents="none",d.style.background=l;for(const f of c.split(";")){const p=f.indexOf(":");p!==-1&&d.style.setProperty(f.slice(0,p).trim(),f.slice(p+1).trim())}document.body.appendChild(d),this.transitionOverlayEl=d}}hideTransitionOverlay(){this.transitionOverlayEl&&(this.transitionOverlayEl.remove(),this.transitionOverlayEl=null),this.hideSkeletonOverlay()}renderSkeletonOverlay(e,n,r,i){const c=Er.getInstance().getComponent(n.component);if(!c){U.log(`Skeleton component "${n.component}" not found in registry, falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}let d=document.getElementById(e),f="target";if(!d&&i&&(d=document.getElementById(i),f="fallback"),d||(d=document.getElementById("app"),f="fullpage"),!d){U.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 m=document.documentElement.classList.contains("dark")?"rgb(17,24,39)":"rgb(249,250,251)",y=f==="fullpage"?"app":f==="fallback"?i:e,C=`#${CSS.escape(y)}`,S=document.createElement("style");S.id="g7-skeleton-overlay-style",S.textContent=`${C}{position:relative;z-index:0;}${C}::after{content:'';position:absolute;inset:0;background:${m};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..."),f==="fullpage")v.style.cssText=["position:fixed","inset:0","z-index:20","overflow:hidden","pointer-events:none",`background:${m}`].join(";")+";";else{const O=d.getBoundingClientRect(),j=window.scrollX||document.documentElement.scrollLeft,F=window.scrollY||document.documentElement.scrollTop;v.style.cssText=["position:absolute",`top:${O.top+F}px`,`left:${O.left+j}px`,`width:${O.width}px`,`height:${O.height}px`,"z-index:20","overflow:hidden","pointer-events:none",`background:${m}`].join(";")+";"}document.body.appendChild(v),this.skeletonOverlayContainer=v;const x=r.components||[];let w;if(f==="fullpage")w=x;else{const O=f==="fallback"?i:e;w=this.findComponentChildrenById(x,O)}const R=_d.createRoot(v);this.skeletonOverlayRoot=R,za.flushSync(()=>{R.render(We.createElement(c,{components:w,options:{animation:n.animation||"pulse",iteration_count:n.iteration_count||5}}))});const L=f==="fullpage"?"fullpage (#app)":f==="fallback"?`fallback (#${i})`:`target (#${e})`;U.log(`Skeleton overlay rendered [${L}] with "${n.component}" (${w.length} components)`)}findComponentChildrenById(e,n){const r=i=>{for(const l of i){if(l.id===n)return l.children||[];if(l.children&&Array.isArray(l.children)){const c=r(l.children);if(c!==null)return c}}return null};return r(e)||e}renderSpinnerOverlay(e,n,r){let i=document.getElementById(e),l="target";if(!i&&r&&(i=document.getElementById(r),l="fallback"),i||(i=document.getElementById("app"),l="fullpage"),!i){U.log(`Spinner overlay: no target found (target="#${e}", fallback="${r||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const c=l==="fullpage"?"app":l==="fallback"?r:e,d=`#${CSS.escape(c)}`,f=document.createElement("style");f.id="g7-skeleton-overlay-style",f.textContent=[`${d}{position:relative;}`,"@keyframes g7-spin{to{transform:rotate(360deg)}}"].join(""),document.head.appendChild(f),this.transitionOverlayEl=f;const p=n?.text||window.G7Core?.t?.("nav.loading")||"";this._spinnerState={target:e,fallbackTarget:r,spinnerConfig:n,resolvedText:p},this._mountSpinnerInTarget(i);const m=l==="fullpage"?"fullpage (#app)":l==="fallback"?`fallback (#${r})`:`target (#${e})`,y=n?.component||"default spinner";U.log(`Spinner overlay rendered [${m}] with "${y}"`)}_mountSpinnerInTarget(e){if(!this._spinnerState)return;const{spinnerConfig:n,resolvedText:r}=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,n?.component){const c=Er.getInstance().getComponent(n.component);if(c){const d=_d.createRoot(i);this.skeletonOverlayRoot=d,za.flushSync(()=>{d.render(We.createElement(c,{options:{text:r}}))});return}U.log(`Spinner component "${n.component}" not found in registry, using default spinner`)}i.innerHTML='
'}reattachSpinnerOverlay(){if(!this._spinnerState)return;const{target:e,fallbackTarget:n}=this._spinnerState;let r=document.getElementById(e);!r&&n&&(r=document.getElementById(n)),r||(r=document.getElementById("app")),r&&(this._mountSpinnerInTarget(r),U.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){if(e instanceof Rr&&e.details?.status===401){const r=this.config.templateId||"",i=window.location.pathname,l=r.includes("admin")||i.startsWith("/admin")?"admin":"user",c=i+window.location.search,d=!!Wn().getToken()||e.details?.hadToken===!0,f=Yn.getInstance().getLoginRedirectUrl(l,c,d?"session_expired":void 0);window.location.href=f;return}const n=eb(e);Jf.renderFromError("app",n,"페이지 로딩 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}async handleServerError(){const e=window.G7Error;if(!e)return!1;U.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"))?(U.log(`${e.code} error page rendered successfully`),!0):(U.log(`Falling back to ErrorDisplay for ${e.code}`),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0)}catch(n){return U.error(`Failed to render ${e.code} page:`,n),this.showInitError(new Error(`Service unavailable (${e.code})`)),!0}}async handleRouteNotFound(e){U.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"))){U.log("404 error page rendered successfully");return}U.log("Falling back to ErrorDisplay for 404"),this.showRouteError(new Error(`Page not found: ${e}`))}catch(n){U.error("Failed to render 404 page:",n),this.showRouteError(new Error(`Page not found: ${e}`))}}getRouter(){return this.router}getConfig(){return this.config}getLayoutLoader(){return this.layoutLoader}async reloadExtensionState(){U.log("reloadExtensionState: start");let e;try{const n=await fetch(Pr(`/api/templates/${this.config.templateId}/config`,"json",null,`_=${Date.now()}`));if(n.ok){const r=await n.json();r?.success&&r?.data?.cache_version!==void 0&&(e=r.data.cache_version)}}catch(n){U.warn("reloadExtensionState: failed to fetch config.json",n)}e!==void 0&&e!==this.extensionCacheVersion&&(U.log(`reloadExtensionState: cache version ${this.extensionCacheVersion} -> ${e}`),this.extensionCacheVersion=e,this.saveCacheVersionToStorage(e));try{this.router&&(await this.router.loadRoutes(this.extensionCacheVersion),U.log("reloadExtensionState: routes reloaded"))}catch(n){U.error("reloadExtensionState: routes reload failed",n)}try{this.layoutLoader&&(this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),this.layoutLoader.clear(),U.log("reloadExtensionState: layout cache cleared"))}catch(n){U.error("reloadExtensionState: layout cache clear failed",n)}try{const{TranslationEngine:n}=await Promise.resolve().then(()=>$g),r=n.getInstance();this.extensionCacheVersion>0&&r.setCacheVersion(this.extensionCacheVersion);const i=this.config.locale||"ko",l="en";await r.loadTranslations(this.config.templateId,i,"/api",!0),i!==l&&await r.loadTranslations(this.config.templateId,l,"/api",!0),U.log("reloadExtensionState: translations reloaded")}catch(n){U.error("reloadExtensionState: translations reload failed",n)}try{const n=await fetch(`/api/locales/active?_=${Date.now()}`);if(n.ok){const i=(await n.json())?.data?.locales;if(Array.isArray(i)&&i.length>0){const l=this.globalState.appConfig??{};this.setGlobalState({appConfig:{...l,supportedLocales:i}}),U.log("reloadExtensionState: supportedLocales refreshed",i)}}}catch(n){U.warn("reloadExtensionState: supportedLocales refresh failed",n)}U.log("reloadExtensionState: done")}getActionDispatcher(){return ca().actionDispatcher}async changeLocale(e){try{if(U.log("Changing locale to:",e),this.config.locale===e){U.log("Locale is already",e);return}this.config.locale=e,this.saveLocaleToStorage(e),await this.saveLocaleToDatabase(e),this.layoutLoader&&(this.layoutLoader.clear(),U.log("Layout cache cleared")),this.errorPageHandler&&(this.errorPageHandler.updateLocale(e),U.log("ErrorPageHandler locale updated")),Qc(),await Yo({templateId:this.config.templateId,templateType:this.config.templateType,locale:e,debug:this.config.debug,cacheVersion:this.extensionCacheVersion}),U.log("Template Engine re-initialized with new locale");const{getActionDispatcher:n}=await Promise.resolve().then(()=>Wr),r=n();r&&(r.setDefaultContext({navigate:i=>this.router?.navigate(i)}),r.setGlobalStateUpdater((i,l)=>this.setGlobalState(i,l)),U.log("Navigate function and setGlobalState re-injected to ActionDispatcher")),this.reinitializeModuleHandlers(),U.log("Module handlers re-initialized"),this.reinitializeTemplateHandlers(),U.log("Template handlers re-initialized"),this.reinitializePluginHandlers(),U.log("Plugin handlers re-initialized"),this.router&&this.router.navigateToCurrentPath(),U.log("Locale changed successfully to",e)}catch(n){throw U.error("Failed to change locale:",n),n}}loadLocaleFromStorage(){try{return localStorage.getItem(Lr.LOCALE_STORAGE_KEY)}catch(e){return U.warn("Failed to load locale from storage:",e),null}}saveLocaleToStorage(e){try{localStorage.setItem(Lr.LOCALE_STORAGE_KEY,e)}catch(n){U.warn("Failed to save locale to storage:",n)}}async saveLocaleToDatabase(e){const n=localStorage.getItem("auth_token");if(!n){U.log("No auth token, skipping DB locale save");return}let r,i;if(this.config.localeApi)r=this.config.localeApi.endpoint,i=this.config.localeApi.method;else{const l=this.config.templateType==="admin";r=l?"/api/admin/users/me/language":"/api/user/profile/update-language",i=l?"PATCH":"POST"}try{const l=this.getXsrfToken(),c=await fetch(r,{method:i,headers:{"Content-Type":"application/json",Accept:"application/json",...l&&{"X-XSRF-TOKEN":l},Authorization:`Bearer ${n}`},credentials:"include",body:JSON.stringify({language:e})});c.ok?U.log("Locale saved to DB:",e):U.warn("Failed to save locale to DB (UI will still change):",c.statusText)}catch(l){U.warn("Failed to call locale API (UI will still change):",l)}}getXsrfToken(){if(typeof document>"u")return null;const n=`; ${document.cookie}`.split("; XSRF-TOKEN=");return n.length===2?decodeURIComponent(n.pop()?.split(";").shift()||""):null}loadCacheVersionFromStorage(){try{const e=localStorage.getItem(Lr.CACHE_VERSION_STORAGE_KEY);return e?parseInt(e,10):null}catch(e){return U.warn("Failed to load cache version from storage:",e),null}}saveCacheVersionToStorage(e){try{localStorage.setItem(Lr.CACHE_VERSION_STORAGE_KEY,String(e))}catch(n){U.warn("Failed to save cache version to storage:",n)}}reinitializeModuleHandlers(){if(typeof window>"u")return;const e="__",n=window;Object.keys(n).forEach(r=>{if(r.startsWith(e)&&typeof n[r]?.initModule=="function")try{n[r].initModule(),U.log(`Module handler re-initialized: ${r}`)}catch(i){U.warn(`Failed to re-initialize module handlers for ${r}:`,i)}})}reinitializeTemplateHandlers(){if(typeof window>"u")return;const e=window.G7TemplateHandlers;if(!e){U.warn("Template handlers not found on window.G7TemplateHandlers");return}const n=this.getActionDispatcher();if(!n){U.warn("ActionDispatcher not available for template handler registration");return}Object.entries(e).forEach(([r,i])=>{n.registerHandler(r,i)}),U.log(`${Object.keys(e).length} template handler(s) re-registered:`,Object.keys(e))}reinitializePluginHandlers(){if(typeof window>"u")return;const e="__",n=window;Object.keys(n).forEach(r=>{if(r.startsWith(e)&&typeof n[r]?.initPlugin=="function")try{n[r].initPlugin(),U.log(`Plugin handler re-initialized: ${r}`)}catch(i){U.warn(`Failed to re-initialize plugin handlers for ${r}:`,i)}})}getLocale(){return this.config.locale}getErrorPageHandler(){return this.errorPageHandler}getGlobalState(){return{...this.globalState}}setGlobalState(e,n){const r={...this.globalState};typeof e=="function"?this.globalState=e(this.globalState):this.globalState={...this.globalState,...e},U.log("Global state updated:",this.globalState),window.G7Core?.devTools?.captureStateSnapshot?.({source:"setGlobalState",prev:r,next:this.globalState}),this.globalStateListeners.forEach(l=>{l(this.globalState)}),n?.render!==!1&&Promise.resolve().then(()=>Wr).then(({updateTemplateData:l,getState:c})=>{const d=c();d.reactRoot&&d.currentLayoutJson&&l({_global:{...this.globalState},_local:this.globalState._local||{}})})}onGlobalStateChange(e){this.globalStateListeners.add(e)}offGlobalStateChange(e){this.globalStateListeners.delete(e)}async refetchDataSource(e,n){let r=this.currentDataSources.find(i=>i.id===e);if(!r)for(const[,i]of this.modalDataSources){const l=i.find(c=>c.id===e);if(l){r=l;break}}if(!r){U.warn(`Data source not found: ${e}`);return}U.log(`Refetching data source: ${e}`,n?.sync?"(sync mode)":"",n?.globalStateOverride?"(with global override)":"",n?.localStateOverride?"(with local override)":""),Gr.setPending(!0);try{const i=new Dr;this.currentGlobalHeaders.length>0&&i.setGlobalHeaders(this.currentGlobalHeaders);const l=ca(),c=l.currentDataContext?._global||{},d=n?.globalStateOverride?{...c,...n.globalStateOverride}:c,f=l.currentDataContext?._local||{},p=n?.localStateOverride?{...f,...n.localStateOverride}:f,y=(await i.fetchDataSourcesWithResults([r],this.currentRouteParams,this.currentQueryParams,d,p,{ignoreAutoFetch:!0}))[0];if(y.state==="success"&&y.data!==void 0){this.currentFetchedData[e]=y.data;const C={};this.processInitOptions([r],{[e]:y.data},C);const S=ca();if(S.bindingEngine){const x=[e];r.initGlobal&&x.push("_global"),r.initLocal&&x.push("_local"),S.bindingEngine.invalidateCacheByKeys(x)}const v={[e]:y.data};return Object.keys(C).length>0&&(v._localInit=C),r.initGlobal&&(v._global={...this.globalState}),_s(v,n?.sync?{sync:!0}:void 0),U.log(`Data source refetched successfully: ${e}`),y.data}else if(y.state==="error"){U.error(`Failed to refetch data source: ${e}`,y.error);return}}catch(i){U.error(`Error refetching data source: ${e}`,i);return}finally{Gr.setPending(!1)}}registerModalDataSources(e,n){this.modalDataSources.set(e,n),U.log(`Modal data sources registered: ${e} (${n.length} sources)`)}unregisterModalDataSources(e){this.modalDataSources.delete(e),U.log(`Modal data sources unregistered: ${e}`)}getDataSource(e){return this.currentFetchedData[e]}setDataSource(e,n,r){if(!e){U.warn("setDataSource: dataSourceId is required");return}const{merge:i=!1,sync:l=!1}=r||{};i&&this.currentFetchedData[e]?this.currentFetchedData[e]={...this.currentFetchedData[e],...n}:this.currentFetchedData[e]=n,Promise.resolve().then(()=>Wr).then(({updateTemplateData:c})=>{c({[e]:this.currentFetchedData[e]},l?{sync:!0}:void 0)}),U.log(`setDataSource: Updated ${e}`,i?"(merged)":"(replaced)")}updateDataSourceItem(e,n,r,i,l){const{idField:c="id",merge:d=!0,skipRender:f=!1}=l||{},p=this.currentFetchedData[e];if(!p)return U.warn(`updateDataSourceItem: DataSource '${e}' not found`),!1;const m=this.parseItemPath(n);let y=p;for(const v of m)if(y=y?.[v],y===void 0)return U.warn(`updateDataSourceItem: Path '${n}' not found in dataSource`),!1;if(!Array.isArray(y))return U.warn(`updateDataSourceItem: Target at '${n}' is not an array`),!1;const C=y.findIndex(v=>String(v[c])===String(r));if(C===-1)return U.warn(`updateDataSourceItem: Item with ${c}='${r}' not found`),!1;d?y[C]=this.deepMerge(y[C],i):y[C]={...y[C],...i};const S=window.G7Core?.devTools;return S?.isEnabled?.()&&S.trackDataSourceUpdate?.({dataSourceId:e,updateType:"partial",itemPath:n,itemId:r,updates:i,timestamp:Date.now()}),f||Promise.resolve().then(()=>Wr).then(({updateTemplateData:v})=>{v({[e]:this.currentFetchedData[e]},{sync:!1})}),U.log(`updateDataSourceItem: Updated ${e}.${n}[${c}=${r}]`),!0}parseItemPath(e){const n=[],r=/([^\.\[\]]+)|\[(\d+)\]/g;let i;for(;(i=r.exec(e))!==null;)i[1]!==void 0?n.push(i[1]):i[2]!==void 0&&n.push(parseInt(i[2],10));return n}deepMerge(e,n){if(n==null)return e;if(typeof n!="object"||Array.isArray(n))return n;const r={...e};for(const i of Object.keys(n))typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])?r[i]=this.deepMerge(r[i]||{},n[i]):r[i]=n[i];return r}setValueAtPath(e,n,r,i="deep"){const l=n.split(".");let c=e;for(let p=0;p0?l.filterByCondition(this.currentRawDataSources,d):this.currentDataSources;this.currentDataSources=f;const p=f.filter(x=>x.auto_fetch!==!1&&x.type!=="websocket");if(p.length===0){U.log("No auto_fetch data sources to refetch");return}U.log(`Refetching ${p.length} auto_fetch data sources`),Gr.setPending(!0);const m=ca().currentLayoutJson,y=m?.transition_overlay,C=Array.isArray(y?.wait_for)?y.wait_for:[],S=p.some(x=>(x.loading_strategy||"progressive")==="blocking"),v=C.length>0&&p.some(x=>C.includes(x.id)&&x.type!=="websocket"&&(x.loading_strategy||"progressive")!=="background");if((S||v)&&y&&typeof y=="object"){const x=n?.transitionOverlayTarget||y.target;y.enabled&&y.style==="skeleton"&&y.skeleton?.component&&x?this.renderSkeletonOverlay(x,y.skeleton,m,y.fallback_target):y.enabled&&y.style==="spinner"&&x&&this.renderSpinnerOverlay(x,y.spinner,y.fallback_target)}try{const x=new Dr;this.currentGlobalHeaders.length>0&&x.setGlobalHeaders(this.currentGlobalHeaders);const w=ca(),R=w.currentDataContext?._global||{},L=await x.fetchDataSourcesWithResults(p,this.currentRouteParams,this.currentQueryParams,R,void 0,{ignoreAutoFetch:!1}),O={},j={},F=new Map(p.map(G=>[G.id,G]));for(const G of L){const P=F.get(G.id);if(!P){U.warn(`Refetch result id not found in autoFetchDataSources: ${G.id}`);continue}const K=G.id;G.state==="success"&&G.data!==void 0?(this.currentFetchedData[K]=G.data,O[K]=G.data,this.processInitOptions([P],{[K]:G.data},j),U.log(`Data source refetched: ${K}`)):G.state==="error"&&U.error(`Failed to refetch data source: ${K}`,G.error)}if(w.bindingEngine){const G=Object.keys(O);G.push("query"),w.bindingEngine.invalidateCacheByKeys(G)}if(Object.keys(j).length>0&&(O._localInit=j),Object.keys(O).length>0){if(O.query=ob(this.currentQueryParams),w.currentLayoutJson?.computed&&Object.keys(w.currentLayoutJson.computed).length>0){const G={...w.currentDataContext,...O,query:O.query},P=this.calculateComputed(w.currentLayoutJson.computed,G);Object.keys(P).length>0&&(O._computed=P,this.globalState._computed=P,U.log("Computed values recalculated in updateQueryParams:",Object.keys(P)))}_s(O,{sync:!0}),U.log("Template data updated with new query params")}}catch(x){U.error("Error in updateQueryParams:",x)}finally{Gr.setPending(!1),this.hideTransitionOverlay()}}calculateComputed(e,n){const r={},i=new Tn;for(const[l,c]of Object.entries(e))try{let d;if(this.isComputedSwitchDefinition(c))d=i.resolveSwitch(c,n,{skipCache:!0});else if(typeof c=="string")if(c.startsWith("{{")&&c.endsWith("}}")){const f=c.slice(2,-2).trim();d=this.evaluateComputedExpression(f,n)}else d=c;r[l]=d,U.log(`Computed ${l}:`,d)}catch(d){U.warn(`Failed to calculate computed value: ${l}`,d),r[l]=void 0}return r}isComputedSwitchDefinition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"$switch"in e&&"$cases"in e}evaluateComputedExpression(e,n){try{return Jd(e,n)}catch(r){U.warn(`Expression evaluation failed: ${e}`,r);return}}async executeInitActions(e,n={}){const{getActionDispatcher:r}=await Promise.resolve().then(()=>Wr),i=r();if(!i){U.warn("ActionDispatcher not available for init_actions");return}U.log("Executing init_actions:",e.map(d=>d.handler)),U.log("Init actions dataContext:",n),U.log("Init actions dataContext._global:",n._global);const l=e.map(d=>d.handler).filter(d=>d.includes("."));l.length>0&&await this.waitForHandlers(i,l);let c={...n};for(const d of e)try{const f={type:"click",handler:d.handler,target:d.target,params:d.params,resultTo:d.resultTo,onSuccess:d.onSuccess,onError:d.onError,if:d.if,conditions:d.conditions,auth_mode:d.auth_mode,auth_required:d.auth_required},p=i.createHandler(f,c),m=new Event("init");await p(m),U.log(`Init action executed: ${d.handler}`);const y=this.globalState;c={...c,_global:{...y},_local:y._local||c._local||{}},U.log(`Data context refreshed after ${d.handler}:`,{cartKey:c._global?.cartKey})}catch(f){U.error(`Failed to execute init action: ${d.handler}`,f)}}async waitForHandlers(e,n,r=5e3){const i=Date.now(),l=50,c=()=>n.every(f=>e.customHandlers?.has(f));if(c()){U.log("All module handlers already registered");return}const d=Zf().getFailedJsAssets();if(d.length>0){const f=d.some(y=>y==="module"||y==="plugin"),p=n.filter(y=>!e.customHandlers?.has(y)),m=p.length>0&&p.every(y=>d.some(C=>y.startsWith(`${C}.`)));if(f||m){U.warn("Extension asset load failed — not waiting for handlers that will never register:",{pending:p,failedAssets:d});return}}return U.log("Waiting for module handlers:",n),new Promise(f=>{const p=()=>{if(c()){U.log("All module handlers now registered"),f();return}if(Date.now()-i>=r){const m=n.filter(y=>!e.customHandlers?.has(y));U.warn("Timeout waiting for handlers:",m),f();return}setTimeout(p,l)};p()})}};$(Lr,"LOCALE_STORAGE_KEY","g7_locale"),$(Lr,"CACHE_VERSION_STORAGE_KEY","g7_cache_version");let Go=Lr;function th(s){const e=new Go(s);return s.websocket&&(Vc.configure(s.websocket),U.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=th,window.G7Core.dataSource={refetch:async(s,e)=>{const n=window.__templateApp;if(!n){U.warn("TemplateApp not initialized (G7Core.dataSource.refetch)");return}return n.refetchDataSource(s,e)},get:s=>{const e=window.__templateApp;if(!e){U.warn("TemplateApp not initialized (G7Core.dataSource.get)");return}return e.getDataSource(s)}});function sx(s={}){const{checked:e,value:n,name:r,type:i="checkbox"}=s,c=n!==void 0?n:i==="checkbox"||i==="radio"?e??!1:String(e??""),d={checked:e??!1,value:c,name:r??"",type:i};return{target:d,currentTarget:d,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 ox(s={}){const{button:e=0,clientX:n=0,clientY:r=0}=s;return{button:e,clientX:n,clientY:r,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 lx(){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 cx(s,e="keydown"){return{key:s,code:s.length===1?`Key${s.toUpperCase()}`:s,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new KeyboardEvent(e,{key:s}),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 ux={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 lb(s){const e=s.replace(/^(dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+/,"");for(const[n,r]of Object.entries(ux))if(r.test(e))return n;return null}function cb(s){const e=s.match(/^((dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+)/);return e?e[1]:""}function dx(s,e){if(!e||e.trim()==="")return s;if(!s||s.trim()==="")return e;const n=s.split(/\s+/).filter(Boolean),r=e.split(/\s+/).filter(Boolean),i=new Map;for(const c of r){const d=lb(c);if(d){const f=cb(c),p=`${d}:${f}`;i.set(p,c)}}return[...n.filter(c=>{const d=lb(c);if(!d)return!0;const f=cb(c),p=`${d}:${f}`;return!i.has(p)}),...r].join(" ")}function fx(s){return Object.entries(s).filter(([,e])=>e).map(([e])=>e).join(" ")}function hx(...s){return s.filter(e=>typeof e=="string"&&e.length>0).join(" ")}const be=dt("G7CoreGlobals");function px(){window.React=We,window.ReactDOM={...Ad,createPortal:za.createPortal,unstable_batchedUpdates:s=>s()},window.ReactJSXRuntime=WC,be.log("전역 객체 window.React, window.ReactDOM, window.ReactJSXRuntime에 노출됨")}function gx(s){const e=new Map,n=Ua.getInstance();s.componentEvent={on:(r,i)=>(e.has(r)||e.set(r,new Set),e.get(r).add(i),n.trackEventSubscribe(r),()=>{e.get(r)?.delete(i),n.trackEventUnsubscribe(r)}),emit:async(r,i)=>{const l=e.get(r),c=l?.size??0;if(!l||l.size===0)return n.trackEventEmit(r,i,0),[];let d,f=[];try{f=await Promise.all(Array.from(l).map(async p=>{try{return await p(i)}catch(m){throw be.error(`componentEvent: Error in listener for "${r}":`,m),m}}))}catch(p){d=p instanceof Error?p:new Error(String(p))}if(n.trackEventEmit(r,i,c,f,d),d)throw d;return f},off:r=>{e.delete(r),n.trackEventOff(r)},clear:()=>{e.clear(),n.trackEventClear()}},be.log("전역 객체 window.G7Core.componentEvent에 노출됨")}function mx(s){s.__runtime||(s.__runtime={DynamicRenderer:Vr,ComponentRegistry:Er,TranslationEngine:wi,DataSourceManager:Dr,dataSourceManager:MA,DataBindingEngine:Tn,dataBindingEngine:uc,ActionDispatcher:Lo,TranslationReactContext:Ff,TranslationProvider:qc,useTranslation:Py,ResponsiveContext:Cf,ResponsiveProvider:Rc,useResponsive:Ef,responsiveManager:_i,BREAKPOINT_PRESETS:dc,AuthManager:Yn,createLogger:dt,G7DevToolsCore:Ua},be.log("전역 객체 window.G7Core.__runtime(코어 런타임 표면)에 노출됨"))}function yx(s){if(s.layoutEditor&&s.layoutEditor.__isStub!==!0||s.layoutEditor&&s.layoutEditor.__isStub===!0)return;const e=[],n=[];s.layoutEditor={__isStub:!0,__queue:e,__readyCallbacks:n,registerWidget:(r,i)=>e.push(["widget",r,i]),registerNodeEditor:(r,i)=>e.push(["nodeEditor",r,i]),registerCanvasOverlay:(r,i)=>e.push(["canvasOverlay",r,i]),onReady:r=>{typeof r=="function"&&n.push(r)}},be.log("전역 객체 window.G7Core.layoutEditor 예약 접수함(stub) 노출됨")}function bx(s){s.asset={template:(e,n,r)=>Uw(e,n,r),templateDir:(e,n)=>Pw(e,n),module:(e,n,r)=>Bw(e,n,r),plugin:(e,n,r)=>qw(e,n,r),convertToCurrentMode:e=>xn(e),loadScript:(e,n,r)=>Oo(e,fs())?Cr(e,n,r):Promise.reject(new Error(`Blocked untrusted script src (same-origin path or declared trusted host required): ${e}`)),isAllowedScriptSrc:e=>Oo(e,fs()),loadStylesheet:(e,n,r)=>sa(e,n,r)},s.assets={notifyFailure:Ss,clearFailure:rb,clearAll:ab,getFailures:qA,retryAll:sb},QA(),be.log("전역 객체 window.G7Core.asset / window.G7Core.assets 노출됨")}function vx(s,e){s.useTranslation=Py,s.t=(n,r)=>{const i=e.getState();if(!i.translationEngine||!i.translationContext)return n;if(r){const l="|"+Object.entries(r).map(([c,d])=>`${c}=${d}`).join("|");return i.translationEngine.translate(n,i.translationContext,l)}return i.translationEngine.translate(n,i.translationContext)},be.log("전역 객체 window.G7Core.useTranslation에 노출됨")}function Sx(s,e){s.createChangeEvent=sx,s.createClickEvent=ox,s.createSubmitEvent=lx,s.createKeyboardEvent=cx,s.uuid=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const r=Math.random()*16|0;return(n==="x"?r:r&3|8).toString(16)}),s.createLogger=dt,be.log("전역 객체 window.G7Core.createLogger에 노출됨"),s.renderItemChildren=(n,r,i,l,c)=>{const d=e.getState(),m={_global:window.__templateApp?.getGlobalState?.()||{},_local:r._local||{},_computed:r._computed||{},...r},y=new Set,C=(v,x)=>{const w=m._global?._remountKeys;return v&&w?.[v]&&!y.has(v)?(y.add(v),`${v}-remount-${w[v]}`):v||x},S={translationContext:d.translationContext,translationEngine:d.translationEngine,bindingEngine:d.bindingEngine,actionDispatcher:d.actionDispatcher,getRemountKey:C,...c};return Co(n,m,i,l,S)},s.evaluateCondition=(n,r)=>{if(!n)return!0;const i=e.getState(),c=window.__templateApp?.getGlobalState?.()||{},d={_global:c,_local:c._local||{},_computed:c._computed||{},...r||{}},f=i.bindingEngine??uc;return Fg(n,d,f)},s.getComponentMap=()=>Er.getInstance().getComponentMap(),s.renderComponentLayout=(n,r,i)=>{if(!n||!Array.isArray(n)||n.length===0)return null;const l=Er.getInstance().getComponentMap(),c=e.getState(),f=window.__templateApp?.getGlobalState?.()||{},p={_global:f._global||{},_local:f._local||{},_computed:f._computed||{},...r},m=new Set,y=(C,S)=>{const v=p._global?._remountKeys;return C&&v?.[C]&&!m.has(C)?(m.add(C),`${C}-remount-${v[C]}`):C||S};return Co(n,p,l,i,{translationContext:c.translationContext,translationEngine:c.translationEngine,bindingEngine:c.bindingEngine,actionDispatcher:c.actionDispatcher,getRemountKey:y})},s.renderExpandContent=n=>{const{children:r,row:i,expandContext:l,componentContext:c,keyPrefix:d}=n;if(!r||!Array.isArray(r)||r.length===0)return null;const f=n.componentMap||Er.getInstance().getComponentMap(),p=e.getState(),m=s.state?.get?.()||{},y=c?.stateRef?.current??c?.state??{},C={...m._local||{},...y},S=c?.computedRef?.current??m._computed??{},v=p.bindingEngine??s.getDataBindingEngine?.(),x={...m,_local:C,_computed:S,row:i,item:i,$item:i};let w={};if(l&&typeof l=="object"&&v)try{for(const[j,F]of Object.entries(l))if(typeof F=="string"){const G=Ma(F);if(G!==null)try{w[j]=On(G)?v.evaluatePipeExpression(G,x,{skipCache:!0}):v.evaluateExpression(G,x,{skipCache:!0})}catch{w[j]=void 0}else w[j]=v.resolveBindings(F,x,{skipCache:!0})}else w[j]=F}catch(j){be.warn("renderExpandContent: expandContext 평가 오류:",j)}const R={row:i,item:i,$item:i,_local:C,_global:m._global||{},_computed:m._computed||{},...w},L=new Set,O=(j,F)=>{const G=R._global?._remountKeys;return j&&G?.[j]&&!L.has(j)?(L.add(j),`${j}-remount-${G[j]}`):j||F};return Co(r,R,f,d,{translationContext:p.translationContext,translationEngine:p.translationEngine??void 0,bindingEngine:p.bindingEngine??void 0,actionDispatcher:p.actionDispatcher,componentContext:c,getRemountKey:O})},s.$get=function(r,i,l=void 0){if(r==null)return l;const c=Array.isArray(i)?i:[i];if(c.length===0)return r;let d=r;for(const f of c){if(d==null||f==null)return l;d=d[f]}return d??l},be.log("전역 객체 window.G7Core.renderItemChildren에 노출됨"),be.log("전역 객체 window.G7Core.renderComponentLayout에 노출됨"),be.log("전역 객체 window.G7Core.renderExpandContent에 노출됨"),be.log("전역 객체 window.G7Core.$get에 노출됨")}function wx(s){s.dispatch=async(e,n)=>{const r=window.__templateApp;if(!r)return be.warn("G7Core.dispatch: TemplateApp이 초기화되지 않았습니다."),{success:!1,error:new Error("TemplateApp이 초기화되지 않았습니다.")};const i=r.getActionDispatcher?.();if(!i)return be.warn("G7Core.dispatch: ActionDispatcher를 찾을 수 없습니다."),{success:!1,error:new Error("ActionDispatcher를 찾을 수 없습니다.")};const l=r.getRouter?.(),c=r.getGlobalState?.(),d=r.setGlobalState?.bind(r),p=n?.componentContext||window.__g7ActionContext,m=window.__g7PendingLocalState;let y=p?.state??c;m&&p&&(y=m,be.log("[dispatch] Using __g7PendingLocalState for context.state:",m));let C=p?.data??c;m&&p?.data?._local&&(C={...p.data,_local:m},be.log("[dispatch] Updated context.data._local with pendingLocalState"));const S={navigate:l?(v,x)=>l.navigate(v,x):void 0,setState:p?.setState??d,state:y,data:C,_isDispatchFallbackContext:!p?.setState};if(e.debounce){const v=e.debounceKey||`dispatch-${e.handler}`,x=typeof e.debounce=="number"?e.debounce:e.debounce.delay;return i.debouncedCall(v,x,()=>{const{debounce:w,debounceKey:R,...L}=e;i.dispatchAction(L,S)}),{success:!0,debounced:!0}}try{return await i.dispatchAction(e,S)}catch(v){return be.error("G7Core.dispatch: 액션 실행 오류:",v),{success:!1,error:v instanceof Error?v:new Error(String(v))}}},be.log("전역 객체 window.G7Core.dispatch에 노출됨")}function Fo(s){const e={};for(const[n,r]of Object.entries(s))if(n.includes(".")){const i=n.split(".");let l=e;for(let c=0;c0&&e.every(n=>/^\d+$/.test(n))}function Qn(s,e){if(Array.isArray(s)&&!Array.isArray(e)&&Cx(e)){const r=Object.keys(e).map(l=>parseInt(l,10));if(!((r.length>0?Math.max(...r):0)>=s.length+r.length+10)){const l=[...s];for(const[c,d]of Object.entries(e)){const f=parseInt(c,10);f>=0&&f=l.length&&(l[f]=d)}return l}}const n={...s};for(const[r,i]of Object.entries(e))i!==null&&typeof i=="object"&&!Array.isArray(i)?n[r]!==null&&typeof n[r]=="object"?n[r]=Qn(n[r],i):n[r]={...i}:n[r]=i;return n}function Ex(s){s.state={get:()=>window.__templateApp?.getGlobalState?.()||{},set:(e,n)=>{const r=window.__templateApp;if(r?.setGlobalState&&r?.getGlobalState){const i=n?.merge||"deep",l=Fo(e);let c;if(i==="replace")c=l;else if(i==="shallow")c={...r.getGlobalState(),...l};else{const d=r.getGlobalState();c=Qn(d,l)}r.setGlobalState(c,{render:n?.render})}else be.warn("G7Core.state.set: TemplateApp이 초기화되지 않았습니다.")},setLocal:(e,n)=>{const r=window.__templateApp;if(n?.render===!1&&!n?.selfManaged){const w=window.__g7AutoBindingPaths;w&&w.size>0&&ub(Fo(e)).some(L=>w.has(L))&&(be.log("[setLocal] render:false + 자동바인딩 경로 겹침 감지 → render:true 자동 승격 (engine-v1.43.0)"),n={...n,render:!0})}if(n?.debounce){const w=r?.getActionDispatcher?.();if(w){const R=n.debounceKey||`setLocal-${Object.keys(e).join(",")}`,{debounce:L,debounceKey:O,...j}=n;w.debouncedCall(R,n.debounce,()=>{s.state.setLocal(e,j)});return}}const i=n?.scope??"current",l=n?.merge||"deep",c=window.__g7ActionContext,d=Fo(e);if(i==="parent"||i==="root"){const w=window.__g7LayoutContextStack||[];if(w.length>0){const R=i==="parent"?w[w.length-1]:w[0];if(R?.setState){R.setState(L=>l==="replace"?d:l==="shallow"?{...L||{},...d}:Qn(L||{},d)),be.log(`[setLocal] scope=${i}: 타겟 컨텍스트에 상태 업데이트 (mergeMode=${l})`,d);return}}be.warn(`[setLocal] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const f=window.__g7PendingLocalState,p=r?.getGlobalState?.()?._local||{},C=!((window.__g7LayoutContextStack||[]).length>0)&&c?.state?c.state:void 0,S=C?Ro(p,C):p,v=f||S;let x;if(l==="replace"?x=d:l==="shallow"?x={...v,...d}:x=Qn(v,d),r?.setGlobalState&&(r.setGlobalState({_local:x},{render:n?.render}),be.log(`[setLocal] globalLocal updated via setGlobalState (mergeMode=${l}, render=${n?.render??!0}):`,d)),window.__g7PendingLocalState=x,be.log("[setLocal] __g7PendingLocalState updated:",x),window.__g7SequenceLocalSync=x,window.__g7LastSetLocalSnapshot=x,l==="replace")window.__g7ForcedLocalFields=d;else{const w=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=Qn(w,d)}if(be.log("[setLocal] __g7ForcedLocalFields updated:",d),l==="replace")window.__g7SetLocalOverrideKeys=d;else{const w=window.__g7SetLocalOverrideKeys||{};window.__g7SetLocalOverrideKeys=Qn(w,d)}be.log("[setLocal] __g7SetLocalOverrideKeys updated:",d),c?.setState&&c.setState(w=>l==="replace"?d:l==="shallow"?{...w||{},...d}:Qn(w||{},d)),r?.setGlobalState||be.warn("G7Core.state.setLocal: TemplateApp이 없습니다.")},getLocal:()=>{const r=(window.__templateApp?.getGlobalState?.()||{})._local||{},i=window.__g7PendingLocalState;if(i)return Qn(r,i);const l=window.__g7LastSetLocalSnapshot;return l&&l!==r?Qn(r,l):r},update:e=>{const n=window.__templateApp;if(n?.getGlobalState&&n?.setGlobalState){const r=n.getGlobalState(),i=e(r);n.setGlobalState(i)}else be.warn("G7Core.state.update: TemplateApp이 초기화되지 않았습니다.")},subscribe:e=>{const n=window.__templateApp;return n?.onGlobalStateChange?n.onGlobalStateChange(e):(be.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,n,r)=>{let i,l,c;typeof e=="string"?(i=e,l=n||{},c=r):(l=e,c=n&&typeof n=="object"&&"merge"in n?n:r);const d=c?.merge||"deep",f=Fo(l);if(i){const y=window.__g7IsolatedStates?.[i];y?.mergeState?y.mergeState(f,d):be.warn(`G7Core.state.setIsolated: scopeId '${i}'를 찾을 수 없습니다.`);return}const p=window.__g7ActionContext;p?.isolatedContext?.mergeState?p.isolatedContext.mergeState(f,d):be.warn("G7Core.state.setIsolated: 액션 컨텍스트에 isolatedContext가 없습니다.")},getParent:()=>{const e=window.__g7LayoutContextStack||[];if(e.length===0)return be.log("[getParent] 레이아웃 컨텍스트 스택이 비어있습니다."),null;const n=e[e.length-1];if(!n)return null;const r=n.dataContext||{};return{_local:n.state||r._local||{},_global:r._global||s.state.get()||{},setState:n.setState}},setParentLocal:(e,n,r)=>{const i=window.__g7LayoutContextStack||[];if(i.length===0){be.warn("[setParentLocal] 레이아웃 컨텍스트 스택이 비어있습니다.");return}const l=i[i.length-1];if(!l?.setState){be.warn("[setParentLocal] 부모 컨텍스트에 setState가 없습니다.");return}let c,d;typeof e=="string"?(c={[e]:n},d=r):(c=e,d=n&&typeof n=="object"&&"merge"in n?n:r);const f=d?.merge||"deep",p=Fo(c),m=l.state?._local!==void 0,y=m?l.state._local:l.state||{};let C;f==="replace"?C=p:f==="shallow"?C={...y,...p}:C=Qn(y,p),window.__g7PendingLocalState=C;const S=window.__templateApp;if(S?.setGlobalState){const v=S.getGlobalState?.()?._local,w=f!=="replace"&&!!v&&typeof v=="object"&&!Array.isArray(v)?f==="shallow"?{...v,...p}:Qn(v,p):void 0;S.setGlobalState({_local:w?Ro(w,C):C})}if(l.setState(C),m?l.state._local=C:l.state=C,l.dataContext&&(l.dataContext._local=C),f==="replace")window.__g7ForcedLocalFields=p;else{const v=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=Qn(v,p)}vf()},setParentGlobal:(e,n)=>{let r;typeof e=="string"?r={[e]:n}:r=e,s.state.set(r),be.log("[setParentGlobal] 전역 상태 업데이트:",r)}},window.__g7IsolatedStates||(window.__g7IsolatedStates={}),s.state.getGlobal=s.state.get,s.state.setGlobal=s.state.set,be.log("전역 객체 window.G7Core.state에 노출됨")}function _x(s){s.dataSource={get:e=>window.__templateApp?.getDataSource?.(e),set:(e,n,r)=>{const i=window.__templateApp;i?.setDataSource?i.setDataSource(e,n,r):be.warn("G7Core.dataSource.set: TemplateApp이 초기화되지 않았습니다.")},refetch:async(e,n)=>{const r=window.__templateApp;if(r?.refetchDataSource)return r.refetchDataSource(e,n);be.warn("G7Core.dataSource.refetch: TemplateApp이 초기화되지 않았습니다.")},updateItem:(e,n,r,i,l)=>{const c=window.__templateApp;return c?.updateDataSourceItem?c.updateDataSourceItem(e,n,r,i,l):(be.warn("G7Core.dataSource.updateItem: TemplateApp이 초기화되지 않았습니다."),!1)},updateData:(e,n,r,i="append")=>{const l=window.__templateApp;if(!l?.getDataSource||!l?.setDataSource)return be.warn("G7Core.dataSource.updateData: TemplateApp이 초기화되지 않았습니다."),!1;const c=l.getDataSource(e);if(!c)return be.warn(`G7Core.dataSource.updateData: 데이터 소스 '${e}'를 찾을 수 없습니다.`),!1;let d,f=c,p=null;if(n){const y=n.split(".");p=y.pop();for(const C of y)if(f&&typeof f=="object"&&C in f)f=f[C];else return be.warn(`G7Core.dataSource.updateData: 경로 '${n}'를 찾을 수 없습니다.`),!1;d=f[p]}else d=c;if(!Array.isArray(d))return be.warn("G7Core.dataSource.updateData: 대상 경로의 데이터가 배열이 아닙니다."),!1;if(!Array.isArray(r))return be.warn("G7Core.dataSource.updateData: newData가 배열이 아닙니다."),!1;const m=i==="prepend"?[...r,...d]:[...d,...r];return n&&p?(f[p]=m,l.setDataSource(e,c,{merge:!1})):l.setDataSource(e,m,{merge:!1}),be.log(`G7Core.dataSource.updateData: '${e}'에 ${r.length}개 항목 ${i==="prepend"?"앞에":"뒤에"} 추가됨`),!0}},be.log("전역 객체 window.G7Core.dataSource에 노출됨")}function Ax(s,e){s.locale={current:()=>window.__templateApp?.getLocale?.()||"ko",supported:()=>{const r=window.__templateApp?.globalState?.appConfig?.supportedLocales;return Array.isArray(r)&&r.length>0?r:e.getState().templateMetadata?.locales||["ko","en"]},change:async n=>{const r=window.__templateApp;r?.changeLocale?await r.changeLocale(n):be.warn("G7Core.locale.change: TemplateApp이 초기화되지 않았습니다.")}},be.log("전역 객체 window.G7Core.locale에 노출됨")}function xx(s){s.toast={show:(e,n)=>{s.dispatch({handler:"toast",params:{message:e,type:n?.type||"info",...n?.duration&&{duration:n.duration}}})},success:(e,n)=>{s.toast.show(e,{type:"success",duration:n})},error:(e,n)=>{s.toast.show(e,{type:"error",duration:n})},warning:(e,n)=>{s.toast.show(e,{type:"warning",duration:n})},info:(e,n)=>{s.toast.show(e,{type:"info",duration:n})}},be.log("전역 객체 window.G7Core.toast에 노출됨")}function Tx(s){s.modal={open:e=>{s.dispatch({handler:"openModal",target:e})},close:e=>{s.dispatch({handler:"closeModal",...e&&{target:e}})},closeAll:()=>{s.dispatch({handler:"closeAllModals"})},isOpen:e=>{const n=s.state.get();return n._global?.activeModal===e||n._global?.modalStack?.includes(e)||!1},getStack:()=>s.state.get()._global?.modalStack||[]},be.log("전역 객체 window.G7Core.modal에 노출됨")}function kx(s){s.style={mergeClasses:dx,conditionalClass:fx,joinClasses:hx},be.log("전역 객체 window.G7Core.style에 노출됨")}function Rx(s,e){const{webSocketManager:n}=e;s.websocket={manager:n,subscribe:(r,i,l,c)=>n.subscribe(r,i,l,c),unsubscribe:r=>n.unsubscribe(r),leaveChannel:r=>n.leaveChannel(r),disconnect:()=>n.disconnect(),isInitialized:()=>n.isInitialized(),getSubscriptionCount:()=>n.getSubscriptionCount()},be.log("전역 객체 window.G7Core.websocket에 노출됨")}function Dx(s,e){const{transitionManager:n}=e;s.navigation={isPending:()=>n?.getIsPending?.()||!1,onComplete:r=>{if(!n)return r(),()=>{};let i=n.getIsPending();const l=n.subscribe(c=>{c?i=!0:i&&(r(),l())});return l}},be.log("전역 객체 window.G7Core.navigation에 노출됨")}function Ox(s){s.plugin={getSettings:e=>window.G7Config?.plugins?.[e],get:(e,n,r)=>window.G7Config?.plugins?.[e]?.[n]??r,getAll:()=>window.G7Config?.plugins??{}},be.log("전역 객체 window.G7Core.plugin에 노출됨")}function Lx(s){s.module={getSettings:e=>window.G7Config?.modules?.[e],get:(e,n,r)=>window.G7Config?.modules?.[e]?.[n]??r,getAll:()=>window.G7Config?.modules??{}},be.log("전역 객체 window.G7Core.module에 노출됨")}function $x(s,e){const{transitionManager:n,responsiveManager:r}=e;s.AuthManager=Yn,s.api=Wn(),s.TransitionManager=n,s.useTransitionState=Jm,s.ResponsiveManager=r,s.useResponsive=Ef,s.useControllableState=oE,s.shallowArrayEqual=lE,s.shallowObjectEqual=Zm,s.updateQueryParams=async(i,l)=>{const c=window.__templateApp;if(c?.updateQueryParams)return c.updateQueryParams(i,l);be.warn("G7Core.updateQueryParams: TemplateApp이 초기화되지 않았습니다.")},be.log("전역 객체 window.G7Core.AuthManager에 노출됨"),be.log("전역 객체 window.G7Core.api에 노출됨"),be.log("전역 객체 window.G7Core.ResponsiveManager에 노출됨"),be.log("전역 객체 window.G7Core.useResponsive에 노출됨"),be.log("전역 객체 window.G7Core.useControllableState에 노출됨"),be.log("전역 객체 window.G7Core.updateQueryParams에 노출됨")}function Mx(s,e){s.getSlotContext=()=>window.__slotContextValue??null,s.getDynamicRenderer=()=>window.__DynamicRenderer??null,s.getComponentRegistry=()=>e.getComponentRegistry?.()??Er.getInstance(),s.getDataBindingEngine=()=>e.getDataBindingEngine?.()??e.getState().bindingEngine,s.getTranslationEngine=()=>e.getTranslationEngine?.()??e.getState().translationEngine,s.getActionDispatcher=()=>e.getActionDispatcher?.()??e.getState().actionDispatcher,be.log("전역 객체 window.G7Core 슬롯 API에 노출됨 (getSlotContext, getDynamicRenderer 등)")}function Nx(s){s.identity={setLauncher:yt.setLauncher.bind(yt),handle:yt.handle.bind(yt),isIdentityRequired:yt.isIdentityRequired.bind(yt),hasLauncher:yt.hasLauncher.bind(yt),markDomainNoticeShown:yt.markDomainNoticeShown.bind(yt),redirectExternally:yt.redirectExternally.bind(yt),createDeferred:yt.createDeferred.bind(yt),resolveDeferred:yt.resolveDeferred.bind(yt),reset:yt.reset.bind(yt),redirectStashKey:hf},be.log("전역 객체 window.G7Core 본인인증(IDV) API에 노출됨 (identity)")}function Ix(s){if(typeof window>"u")return;px(),window.G7Core||(window.G7Core={});const e=window.G7Core;mx(e),gx(e),yx(e),$x(e,s),bx(e),vx(e,s),Sx(e,s),wx(e),Ex(e),_x(e),Ax(e,s),xx(e),Tx(e),kx(e),Rx(e,s),Dx(e,s),Ox(e),Lx(e),Mx(e,s),Nx(e),be.log("G7Core 전역 객체 초기화 완료")}function jx(){const s=window.G7Core;if(!s){be.warn("G7Core가 초기화되지 않았습니다.");return}const e=()=>Ua.getInstance(),n={isEnabled:()=>{try{return e().isEnabled()}catch{return!1}},trackRender:r=>{try{e().isEnabled()&&e().trackRender(r)}catch{}},trackIteration:(r,i,l,c,d)=>{try{e().isEnabled()&&e().trackIteration(r,{source:i,itemVar:l,indexVar:c,sourceLength:d})}catch{}},trackIfCondition:(r,i,l,c)=>{try{e().isEnabled()&&e().trackIfCondition(r,i,l)}catch{}},trackMount:(r,i)=>{try{e().isEnabled()&&e().trackMount(r,{...i,id:r})}catch{}},trackUnmount:r=>{try{e().isEnabled()&&e().trackUnmount(r)}catch{}},trackExpressionEval:r=>{try{e().isEnabled()&&e().trackExpressionEval(r)}catch{}},trackBindingEval:r=>{try{e().isEnabled()&&e().trackBindingEval(r)}catch{}},recordCacheHit:()=>{try{e().isEnabled()&&e().recordCacheHit()}catch{}},recordCacheMiss:()=>{try{e().isEnabled()&&e().recordCacheMiss()}catch{}},trackHandlerRegistration:(r,i,l,c)=>{try{e().isEnabled()&&e().trackHandlerRegistration(r,i,l,c)}catch{}},trackHandlerUnregistration:r=>{try{e().isEnabled()&&e().trackHandlerUnregistration(r)}catch{}},logAction:r=>{try{e().isEnabled()&&e().logAction(r)}catch{}},trackRequest:(r,i)=>{try{return e().isEnabled()?e().trackRequest(r,i):""}catch{return""}},completeRequest:(r,i,l)=>{try{e().isEnabled()&&e().completeRequest(r,i,l)}catch{}},failRequest:(r,i)=>{try{e().isEnabled()&&e().failRequest(r,i)}catch{}},trackDataSourceDefinition:r=>{try{e().isEnabled()&&e().trackDataSourceDefinition(r)}catch{}},trackDataSourceLoading:r=>{try{e().isEnabled()&&e().trackDataSourceLoading(r)}catch{}},trackDataSourceLoaded:(r,i,l)=>{try{e().isEnabled()&&e().trackDataSourceLoaded(r,i,l)}catch{}},trackDataSourceError:(r,i)=>{try{e().isEnabled()&&e().trackDataSourceError(r,i)}catch{}},trackForm:(r,i,l)=>{try{e().isEnabled()&&e().trackForm(r,i,l)}catch{}},untrackForm:r=>{try{e().isEnabled()&&e().untrackForm(r)}catch{}},startStateChange:(r,i,l,c)=>{try{return e().isEnabled()?e().startStateChange(r,i,l,c):""}catch{return""}},completeStateChange:r=>{try{e().isEnabled()&&e().completeStateChange(r)}catch{}},trackComponentRender:(r,i,l,c,d,f)=>{try{e().isEnabled()&&e().trackComponentRender(r,i,l,c,d,f)}catch{}},updateLocalState:r=>{try{e().isEnabled()&&e().updateLocalState(r)}catch{}},updateComputedState:r=>{try{e().isEnabled()&&e().updateComputedState(r)}catch{}},updateParentContext:r=>{try{e().isEnabled()&&e().updateParentContext(r)}catch{}},trackComponentStateSource:(r,i,l,c)=>{try{e().isEnabled()&&e().trackComponentStateSource(r,i,l,c)}catch{}},trackDynamicState:(r,i)=>{try{e().isEnabled()&&e().trackDynamicState(r,i)}catch{}},trackContextFlow:(r,i,l,c,d,f)=>{try{e().isEnabled()&&e().trackContextFlow(r,i,l,c,d,f)}catch{}},trackComponentStyle:(r,i,l,c)=>{try{e().isEnabled()&&e().trackComponentStyle(r,i,l,c)}catch{}},trackAuthEvent:(r,i,l,c)=>{try{e().isEnabled()&&e().trackAuthEvent(r,i,l,c)}catch{}},trackAuthHeader:(r,i,l,c,d)=>{try{e().isEnabled()&&e().trackAuthHeader(r,i,l,c,d)}catch{}},trackLog:(r,i,l)=>{try{e().isEnabled()&&e().trackLog(r,i,l)}catch{}},trackAction:r=>{try{e().isEnabled()&&e().trackAction?.(r)}catch{}},trackDataSourceUpdate:r=>{try{e().isEnabled()&&e().trackDataSourceUpdate?.(r)}catch{}},startSequenceExecution:r=>{try{return e().isEnabled()?e().startSequenceExecution(r):""}catch{return""}},captureSequenceActionBefore:(r,i,l,c,d)=>{try{e().isEnabled()&&e().captureSequenceActionBefore(r,i,l,c,d)}catch{}},captureSequenceActionAfter:(r,i,l,c,d,f)=>{try{e().isEnabled()&&e().captureSequenceActionAfter(r,i,l,c,d,f)}catch{}},endSequenceExecution:(r,i)=>{try{e().isEnabled()&&e().endSequenceExecution(r,i)}catch{}},registerStateCaptureForHandler:(r,i,l)=>{try{e().isEnabled()&&e().registerStateCaptureForHandler(r,i,l)}catch{}},detectStaleClosure:(r,i,l,c,d)=>{try{return e().isEnabled()?e().detectStaleClosure(r,i,l,c,d):[]}catch{return[]}},trackStaleClosureWarning:r=>{try{e().isEnabled()&&e().trackStaleClosureWarning(r)}catch{}},trackModalOpen:r=>{try{e().isEnabled()&&e().trackModalOpen(r)}catch{}},trackModalClose:(r,i)=>{try{e().isEnabled()&&e().trackModalClose(r,i)}catch{}},trackModalStateChange:r=>{try{e().isEnabled()&&e().trackModalStateChange(r)}catch{}},trackNestedContext:r=>{try{return e().isEnabled()?e().trackNestedContext(r):""}catch{return""}},trackNestedContextAccess:(r,i)=>{try{e().isEnabled()&&e().trackNestedContextAccess(r,i)}catch{}},trackComputedProperty:(r,i,l,c,d,f,p)=>{try{e().isEnabled()&&e().trackComputedProperty(r,i,l,c,d,f,p)}catch{}},trackComputedRecalc:(r,i,l,c,d,f,p)=>{try{e().isEnabled()&&e().trackComputedRecalc(r,i,l,c,d,f,p)}catch{}},setNamedActionDefinitions:r=>{try{e().isEnabled()&&e().setNamedActionDefinitions(r)}catch{}},trackNamedActionRef:r=>{try{e().isEnabled()&&e().trackNamedActionRef(r)}catch{}}};s.devTools=n,be.log("G7Core.devTools 인터페이스 초기화 완료")}let Vo=null;function zx(){const s=window.G7Core;return s?.__devtools?Promise.resolve(s.__devtools):Vo||(Vo=new Promise((e,n)=>{const r=window.G7Config?.coreDevToolsAsset||"/build/core/devtools.min.js",i="g7-devtools-bundle",l=()=>{const f=window.G7Core?.__devtools;f?e(f):n(new Error("DevTools 번들 로드됨 — 그러나 __devtools 미노출"))};window.G7Core=window.G7Core||{},window.G7Core.__onDevToolsReady=l;const c=document.getElementById(i);if(c){c.addEventListener("load",l,{once:!0}),c.addEventListener("error",()=>n(new Error(`DevTools 번들 로드 실패: ${r}`)),{once:!0});return}const d=document.createElement("script");d.id=i,d.src=r,d.async=!1,d.addEventListener("load",l,{once:!0}),d.addEventListener("error",()=>{Vo=null,n(new Error(`DevTools 번들 로드 실패: ${r}`))},{once:!0}),document.head.appendChild(d)}),Vo)}function Hx(){const s=window.G7Core;if(!s){be.warn("G7Core가 초기화되지 않았습니다.");return}const e=Ua.getInstance();if(e.initialize(),!e.isEnabled()){window.G7DevTools={isEnabled:()=>!1,enable:()=>{be.log("환경설정 > 고급 설정 > 디버그 모드를 켜세요")}},Td(),be.log("G7DevTools 비활성화됨 (디버그 모드 꺼짐)");return}Ux(s,e)}async function Ux(s,e){let n;try{n=await zx()}catch(p){be.warn("DevTools 번들 로드 실패 — 최소 API 로 폴백:",p),window.G7DevTools={isEnabled:()=>!1,enable:()=>{}},Td();return}const{DiagnosticEngine:r,getServerConnector:i,getStyleTracker:l}=n;jx(),Td();try{l().enable(),be.log("StyleTracker 활성화됨")}catch(p){be.warn("StyleTracker 활성화 실패:",p)}const c=new r,d=i(),f={isEnabled:()=>e.isEnabled(),state:{get:()=>e.getState(),getHistory:()=>e.getStateHistory(),watch:(p,m)=>e.watchState(p,m)},actions:{getHistory:()=>e.getActionHistory(),watch:p=>e.watchActions(p),getMetrics:()=>e.getActionMetrics()},binding:{evaluate:p=>{const m=s.getDataBindingEngine?.();if(!m){be.warn("DataBindingEngine이 없습니다.");return}return m.evaluateExpression(p,e.getState())},getCacheStats:()=>e.getCacheStats(),clearStats:()=>{e.resetCacheStats(),be.log("캐시 통계 초기화됨")}},diagnose:{analyze:p=>c.analyze(p),suggestFix:p=>c.suggestFix(p),getCommonIssues:()=>c.getCommonIssues(),getRulesByCategory:p=>c.getRulesByCategory(p)},server:{dumpState:p=>d.dumpState(p),sendLog:p=>d.sendLog(p),sendError:(p,m)=>d.sendError(p,m),isConnected:()=>d.isConnected(),testConnection:()=>d.testConnection()},config:{isDebugMode:()=>e.isEnabled(),setLogLevel:p=>e.setLogLevel(p),setMaxHistory:p=>e.setMaxHistory(p)},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=f,s.devtools=f,be.log("G7DevTools 전역 객체 초기화 완료 (window.G7DevTools)"),Px(n.DevToolsPanel)}function Px(s){if(document.getElementById("g7-devtools-root")){be.log("DevToolsPanel 이미 렌더링됨");return}const e=document.createElement("div");e.id="g7-devtools-root",document.body.appendChild(e);try{Ad.createRoot(e).render(We.createElement(s)),be.log("DevToolsPanel UI 렌더링 완료")}catch(n){be.error("DevToolsPanel UI 렌더링 실패:",n)}}const Je=dt("TemplateEngine"),re={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 Ko=!1;const Wo=[];async function Bx(s){try{Je.log("템플릿 메타데이터 로드 중...",s);const e=s.split("-").map(r=>r.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join("")).join(""),n=window[e];return n?.templateMetadata?(Je.log("템플릿 메타데이터 로드 완료 (전역 변수)",n.templateMetadata),n.templateMetadata):(Je.warn(`템플릿 번들에 메타데이터가 없습니다. 전역 변수: ${e}`),{identifier:s,locales:["ko","en"],name:{ko:s,en:s},description:{ko:"",en:""},version:"1.0.0",type:"admin"})}catch(e){return Je.error("템플릿 메타데이터 로드 실패",e),{identifier:s,locales:["ko","en"],name:{ko:s,en:s},description:{ko:"",en:""},version:"1.0.0",type:"admin"}}}function db(){const e=(typeof window<"u"?window.__templateApp:void 0)?.globalState?.appConfig?.supportedLocales,n=re.templateMetadata?.locales;return{$locale:re.locale,$locales:Array.isArray(e)&&e.length>0?e:n||["ko","en"],$templateLocales:n||["ko","en"],$templateId:re.templateId}}async function Yo(s){try{if(Je.log("템플릿 엔진 초기화 시작",s),re.isInitialized)throw new Error("템플릿 엔진이 이미 초기화되었습니다. destroyTemplate()을 먼저 호출하세요.");if(!s.templateId)throw new IA;Ko=s.debug??!1,typeof window<"u"&&(window.G7Config||(window.G7Config={}),window.G7Config.debug=Ko),Hx(),re.templateId=s.templateId,re.locale=s.locale||"ko",Je.log("엔진 인스턴스 생성 중..."),re.registry=Er.getInstance(),re.bindingEngine=new Tn,re.translationEngine=wi.getInstance(),s.cacheVersion!==void 0&&s.cacheVersion>0&&re.translationEngine.setCacheVersion(s.cacheVersion),re.translationContext={templateId:s.templateId,locale:re.locale},re.actionDispatcher=new Lo({},re.translationEngine,re.translationContext),QC(re.actionDispatcher),Je.log("다국어 파일 로드 중...",s.templateId,re.locale);const e="en",n=[re.translationEngine.loadTranslations(s.templateId,re.locale).then(()=>{Je.log(`다국어 파일 로드 완료: ${re.locale}`)}).catch(r=>{Je.warn(`다국어 파일 로드 실패 (${re.locale}):`,r instanceof Error?r.message:r)})];re.locale!==e&&n.push(re.translationEngine.loadTranslations(s.templateId,e).then(()=>{Je.log(`폴백 다국어 파일 로드 완료: ${e}`)}).catch(r=>{Je.warn(`폴백 다국어 파일 로드 실패 (${e}):`,r instanceof Error?r.message:r)})),await Promise.allSettled(n),Je.log("템플릿 메타데이터 로드 중...",s.templateId),re.templateMetadata=await Bx(s.templateId),re.isInitialized=!0,Je.log("템플릿 엔진 초기화 완료 (ComponentRegistry는 별도 로드)")}catch(e){throw Je.error("템플릿 엔진 초기화 실패",e),re.isInitialized=!1,re.registry=null,re.bindingEngine=null,re.translationEngine=null,re.actionDispatcher=null,e}}let Cs=null;const fb="g7-layout-editor-bundle";function nh(){const s=window.G7Core;return s?.__LayoutEditorChrome?Promise.resolve(s.__LayoutEditorChrome):Cs||(Cs=(async()=>{const e=window.G7Config?.coreEditorAsset||"/build/core/layout-editor.min.js";document.getElementById(fb)?.remove(),window.G7Core=window.G7Core||{},window.G7Core.__onChromeReady=()=>{};try{await Cr(e,{id:fb},{label:"layout-editor bundle"})}catch(r){throw Cs=null,Je.error(`편집기 번들 로드 실패 (${e})`,r),new Error("편집기를 불러오지 못했습니다. 네트워크 상태를 확인한 뒤 다시 시도해 주세요.")}const n=window.G7Core?.__LayoutEditorChrome;if(!n)throw Cs=null,Je.error(`편집기 번들 로드됨 — 그러나 __LayoutEditorChrome 미노출 (${e})`),new Error("편집기를 불러왔으나 초기화하지 못했습니다. 페이지를 새로고침해 주세요.");return n})(),Cs)}async function Es(s){try{if(Je.log("템플릿 렌더링 시작",s),!re.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다. initTemplateEngine()을 먼저 호출하세요.");if(!s.containerId)throw new Error("containerId는 필수입니다.");if(!s.layoutJson)throw new Error("layoutJson은 필수입니다.");const e=document.getElementById(s.containerId);if(!e)throw new Error(`컨테이너를 찾을 수 없습니다: #${s.containerId}`);const n=db();if(re.containerId=s.containerId,re.currentLayoutJson=s.layoutJson,re.currentDataContext={...n,...s.dataContext||{}},re.translationContext=s.translationContext||{templateId:re.templateId||"",locale:re.locale},re.reactRoot||(Je.log("React Root 생성"),re.reactRoot=Ad.createRoot(e)),typeof window<"u"){const l=tb(window.location.pathname);if(l){Je.log("레이아웃 편집기 모드 진입",l);let c;try{c=await nh()}catch(f){Je.error("레이아웃 편집기 번들 로드 실패",f),Jf.render(s.containerId,{title:"레이아웃 편집기 로드 실패",message:f instanceof Error?f.message:"편집기 번들을 불러오지 못했습니다.",icon:"fas fa-triangle-exclamation",showStack:!1,showReloadButton:!0,debug:Ko});return}const d=We.createElement(c,{templateIdentifier:l.templateIdentifier,initialLocale:re.locale});re.reactRoot.render(We.createElement(qc,{translationEngine:re.translationEngine,translationContext:re.translationContext,children:We.createElement(Sf,{children:We.createElement(Rc,{children:We.createElement(Vf,{children:d})})})}));return}}const r=s.layoutJson.components||[];if(r.length===0){Je.warn("렌더링할 컴포넌트가 없습니다.");return}const i=s.layoutJson.modals||[];if(Je.log("modals 배열:",i),Je.log("modals 개수:",i.length),Je.log("DynamicRenderer로 렌더링 시작"),re.reactRoot.render(We.createElement(qc,{translationEngine:re.translationEngine,translationContext:re.translationContext},We.createElement(Sf,null,We.createElement(Rc,null,We.createElement(Vf,null,[...r.map((l,c)=>{const d=re.currentLayoutJson?.layout_name||"";return We.createElement(Vr,{key:d&&!l._fromBase?`${l.id}_${d}`:l.id,componentDef:l,dataContext:re.currentDataContext,translationContext:re.translationContext,registry:re.registry,bindingEngine:re.bindingEngine,translationEngine:re.translationEngine,actionDispatcher:re.actionDispatcher,isRootRenderer:c===0,layoutKey:d})}),We.createElement(qm,{key:"__modal_parent_context_provider"},i.map(l=>{const c=re.currentDataContext._global?.modalStack||[],f=c.includes(l.id)||re.currentDataContext._global?.activeModal===l.id,p=c.indexOf(l.id),m=p>=0?50+p:50,y=window.__g7LayoutContextStack||[],S=y[y.length-1]?.dataContext,v=We.createElement(Vr,{key:`modal_${l.id}_renderer`,componentDef:{...l,props:{...l.props,isOpen:f,style:{...l.props?.style,zIndex:m},onClose:re.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},re.currentDataContext)}},dataContext:re.currentDataContext,translationContext:re.translationContext,registry:re.registry,bindingEngine:re.bindingEngine,translationEngine:re.translationEngine,actionDispatcher:re.actionDispatcher,parentDataContext:S});return l.data_sources&&l.data_sources.length>0?We.createElement(Zy,{key:`modal_${l.id}`,isOpen:f,modalId:l.id,dataSources:l.data_sources,dataContext:re.currentDataContext,globalStateUpdater:re.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:re.bindingEngine,debug:Ko,children:v}):v}))]))))),Je.log("템플릿 렌더링 완료"),Wo.length>0){Je.log(`대기 중인 데이터 업데이트 ${Wo.length}건 적용`);const l=[...Wo];Wo.length=0;for(const{data:c,options:d}of l)_s(c,d)}}catch(e){throw Je.error("템플릿 렌더링 실패",e),e}}function _s(s,e){try{if(Je.log("템플릿 데이터 업데이트 시작",Object.keys(s)),!re.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다.");if(!re.reactRoot||!re.currentLayoutJson){Je.log("React 미준비 - 데이터 업데이트 큐잉:",Object.keys(s)),Wo.push({data:s,options:e});return}const n=db(),r={...re.currentDataContext._global||{},...s._global||{}},i=iE(re.currentDataContext._localInit,s._localInit);re.currentDataContext={...n,...re.currentDataContext,...s,_global:r,_localInit:i},r._local!==void 0&&(re.currentDataContext._local=r._local),r._computed!==void 0&&(re.currentDataContext._computed=r._computed);const l=re.currentLayoutJson.components||[],c=re.currentLayoutJson.modals||[];Je.log("updateTemplateData - modals 배열:",c),Je.log("updateTemplateData - modals 개수:",c.length),Je.log("updateTemplateData - activeModal:",re.currentDataContext._global?.activeModal);const d=()=>{re.reactRoot.render(We.createElement(qc,{translationEngine:re.translationEngine,translationContext:re.translationContext},We.createElement(Sf,null,We.createElement(Rc,null,We.createElement(Vf,null,[...l.map((f,p)=>{const m=re.currentLayoutJson?.layout_name||"";return We.createElement(Vr,{key:m&&!f._fromBase?`${f.id}_${m}`:f.id,componentDef:f,dataContext:re.currentDataContext,translationContext:re.translationContext,registry:re.registry,bindingEngine:re.bindingEngine,translationEngine:re.translationEngine,actionDispatcher:re.actionDispatcher,isRootRenderer:p===0,layoutKey:m})}),We.createElement(qm,{key:"__modal_parent_context_provider_update"},c.map(f=>{const p=re.currentDataContext._global?.modalStack||[],y=p.includes(f.id)||re.currentDataContext._global?.activeModal===f.id,C=p.indexOf(f.id),S=C>=0?50+C:50,v=window.__g7LayoutContextStack||[],w=v[v.length-1]?.dataContext,R=We.createElement(Vr,{key:`modal_${f.id}_renderer`,componentDef:{...f,props:{...f.props,isOpen:y,style:{...f.props?.style,zIndex:S},onClose:re.actionDispatcher?.createHandler({type:"click",handler:"closeModal"},re.currentDataContext)}},dataContext:re.currentDataContext,translationContext:re.translationContext,registry:re.registry,bindingEngine:re.bindingEngine,translationEngine:re.translationEngine,actionDispatcher:re.actionDispatcher,parentDataContext:w});return f.data_sources&&f.data_sources.length>0?We.createElement(Zy,{key:`modal_${f.id}`,isOpen:y,modalId:f.id,dataSources:f.data_sources,dataContext:re.currentDataContext,globalStateUpdater:re.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:re.bindingEngine,debug:Ko,children:R}):R}))])))))};e?.sync?(Je.log("재렌더링 시작 (sync mode - 즉시 렌더링)"),d()):(Je.log("재렌더링 시작 (with startTransition)"),M.startTransition(()=>{d()})),Je.log("템플릿 데이터 업데이트 완료")}catch(n){throw Je.error("템플릿 데이터 업데이트 실패",n),n}}function Qc(){try{Je.log("템플릿 정리 시작"),re.reactRoot&&(Je.log("React Root 언마운트"),re.reactRoot.unmount(),re.reactRoot=null),re.templateId=null,re.locale="ko",re.isInitialized=!1,re.containerId=null,re.currentLayoutJson=null,re.currentDataContext={},re.translationContext={templateId:"",locale:"ko"},re.registry=null,re.bindingEngine=null,re.translationEngine=null,re.actionDispatcher=null,re.templateMetadata=null,Je.log("템플릿 정리 완료")}catch(s){throw Je.error("템플릿 정리 실패",s),s}}function ca(){return Object.freeze({...re})}function hb(){return re.actionDispatcher}const Xo={initTemplateEngine:Yo,renderTemplate:Es,updateTemplateData:_s,destroyTemplate:Qc,getState:ca};typeof window<"u"&&(window.G7Core||(window.G7Core={}),window.G7Core.TemplateEngine=Xo,Ix({getState:()=>({translationEngine:re.translationEngine,translationContext:re.translationContext,bindingEngine:re.bindingEngine,actionDispatcher:re.actionDispatcher,templateMetadata:re.templateMetadata}),transitionManager:Gr,responsiveManager:_i,webSocketManager:Vc}),Je.log("전역 객체 window.G7Core.TemplateEngine에 노출됨"));const Wr=Object.freeze(Object.defineProperty({__proto__:null,DataSourceManager:Dr,LayoutLoader:Gf,TemplateApp:Go,TemplateEngine:Xo,default:Xo,destroyTemplate:Qc,getActionDispatcher:hb,getState:ca,initTemplateApp:th,initTemplateEngine:Yo,loadLayoutEditorBundle:nh,renderTemplate:Es,updateTemplateData:_s},Symbol.toStringTag,{value:"Module"}));Yt.DataSourceManager=Dr,Yt.LayoutLoader=Gf,Yt.TemplateApp=Go,Yt.TemplateEngine=Xo,Yt.default=Xo,Yt.destroyTemplate=Qc,Yt.getActionDispatcher=hb,Yt.getState=ca,Yt.initTemplateApp=th,Yt.initTemplateEngine=Yo,Yt.loadLayoutEditorBundle=nh,Yt.renderTemplate=Es,Yt.updateTemplateData=_s,Object.defineProperties(Yt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})(this.G7Core=this.G7Core||{}); diff --git a/resources/js/core/api/ApiClient.ts b/resources/js/core/api/ApiClient.ts index bf96dab7..6a4e4a70 100644 --- a/resources/js/core/api/ApiClient.ts +++ b/resources/js/core/api/ApiClient.ts @@ -117,8 +117,20 @@ class ApiClient { /** * 토큰 저장 + * + * 문자열이 아닌 값은 저장하지 않는다. `localStorage` 는 무엇을 넣든 문자열로 바꿔 + * 저장하므로 `undefined` 를 넘기면 `"undefined"` 라는 truthy 문자열이 남고, 이후 + * 모든 요청이 `Bearer undefined` 로 나가 401 로 튕긴다 — 화면에는 "세션이 만료되었습니다" + * 로 보여 원인을 추적할 단서가 남지 않는다. + * + * @since engine-v1.65.0 */ setToken(token: string): void { + if (typeof token !== 'string' || token === '') { + logger.warn('Ignoring invalid auth token — token must be a non-empty string.'); + return; + } + if (typeof window !== 'undefined') { localStorage.setItem(this.TOKEN_KEY, token); } diff --git a/resources/js/core/api/__tests__/ApiClient.test.ts b/resources/js/core/api/__tests__/ApiClient.test.ts index 1b57c900..e878147f 100644 --- a/resources/js/core/api/__tests__/ApiClient.test.ts +++ b/resources/js/core/api/__tests__/ApiClient.test.ts @@ -98,6 +98,28 @@ describe('ApiClient', () => { it('토큰이 없으면 null을 반환해야 함', () => { expect(apiClient.getToken()).toBeNull(); }); + + it('문자열이 아닌 토큰은 저장하지 않아야 함', () => { + // localStorage 는 무엇을 넣든 문자열로 바꾼다 — undefined 를 넘기면 "undefined" 라는 + // truthy 문자열이 남아 이후 모든 요청이 Bearer undefined 로 나가고 401 로 튕긴다. + apiClient.setToken(undefined as unknown as string); + + expect(localStorage.getItem('auth_token')).toBeNull(); + expect(apiClient.getToken()).toBeNull(); + }); + + it('빈 문자열 토큰도 저장하지 않아야 함', () => { + apiClient.setToken(''); + + expect(localStorage.getItem('auth_token')).toBeNull(); + }); + + it('기존 토큰이 있어도 잘못된 값으로 덮어쓰지 않아야 함', () => { + apiClient.setToken('valid-token'); + apiClient.setToken(null as unknown as string); + + expect(apiClient.getToken()).toBe('valid-token'); + }); }); describe('HTTP 메서드', () => { diff --git a/resources/js/core/auth/AuthManager.ts b/resources/js/core/auth/AuthManager.ts index 36142339..75b1af1c 100644 --- a/resources/js/core/auth/AuthManager.ts +++ b/resources/js/core/auth/AuthManager.ts @@ -36,8 +36,38 @@ export interface AuthConfig { loginEndpoint: string; logoutEndpoint: string; refreshEndpoint: string; + /** 2단계 인증 코드 확인 엔드포인트 */ + twoFactorEndpoint: string; + /** 2단계 인증 코드 재발송 엔드포인트 */ + twoFactorResendEndpoint: string; } +/** + * 2단계 인증 challenge 정보 + * + * 비밀번호 확인만 통과한 상태다 — 토큰은 아직 발급되지 않았고, 코드 확인에 성공해야 + * 세션이 열린다. + * + * @since engine-v1.65.0 + */ +export interface TwoFactorChallenge { + challengeId: string; + providerId: string; + expiresAt: string | null; +} + +/** + * 로그인 결과 + * + * 서버는 보안 환경설정에 따라 **두 가지 형태의 200** 을 돌려준다. 한 형태만 가정하면 + * 다른 형태에서 토큰·사용자 필드가 없어 화면이 알 수 없는 오류로 멈춘다. + * + * @since engine-v1.65.0 + */ +export type LoginResult = + | { status: 'authenticated'; user: AuthUser } + | { status: 'two_factor_required'; challenge: TwoFactorChallenge }; + /** * 인증된 사용자 정보 */ @@ -62,6 +92,20 @@ export interface AuthState { */ type EventHandler = (...args: any[]) => void; +/** + * 로그인·2단계 인증 응답의 data 페이로드 + * + * 두 형태(토큰 발급 / challenge 발급)가 같은 자리에 오므로 전부 선택 필드다. + */ +interface LoginResponseData { + token?: string; + user?: AuthUser; + two_factor_required?: boolean; + challenge_id?: string; + provider_id?: string; + expires_at?: string | null; +} + /** * 기본 인증 설정 */ @@ -74,6 +118,8 @@ const defaultConfigs: Record = { loginEndpoint: '/auth/admin/login', logoutEndpoint: '/admin/auth/logout', refreshEndpoint: '/admin/auth/refresh', + twoFactorEndpoint: '/auth/admin/login/two-factor', + twoFactorResendEndpoint: '/auth/admin/login/two-factor/resend', }, user: { type: 'user', @@ -83,6 +129,8 @@ const defaultConfigs: Record = { loginEndpoint: '/auth/login', logoutEndpoint: '/auth/logout', refreshEndpoint: '/auth/refresh', + twoFactorEndpoint: '/auth/login/two-factor', + twoFactorResendEndpoint: '/auth/login/two-factor/resend', }, }; @@ -238,15 +286,83 @@ export class AuthManager { /** * 로그인 처리 * + * 서버는 두 가지 형태의 200 을 돌려준다 — 토큰과 사용자가 실린 정상 응답, 그리고 + * 2단계 인증이 켜져 있을 때의 challenge 응답이다. 후자에는 토큰도 사용자도 없으므로 + * 세션을 열지 않고 challenge 만 돌려준다. + * * @param type - 인증 타입 * @param credentials - 로그인 자격 증명 * @param options - 추가 옵션 (headers 등) - * @returns 인증된 사용자 정보 + * @returns 인증 완료 또는 2단계 인증 요구 + * @since engine-v1.65.0 반환 타입이 `AuthUser` 에서 `LoginResult` 로 바뀌었습니다. */ async login( type: AuthType, credentials: { email: string; password: string }, options?: { headers?: Record } + ): Promise { + const apiClient = getApiClient(); + const config = this.config.get(type); + + if (!config) { + throw new Error(`Unknown auth type: ${type}`); + } + + try { + // 추가 헤더 설정 (globalHeaders 지원) + const requestConfig = options?.headers ? { headers: options.headers } : undefined; + + const response = await apiClient.post<{ + success: boolean; + data: LoginResponseData; + }>(config.loginEndpoint, credentials, requestConfig); + + if (response.success && response.data) { + // 2단계 인증 요구 — 토큰이 없으므로 상태를 건드리지 않는다. + if (response.data.two_factor_required === true) { + trackAuthEvent('login', true, undefined, { type, two_factor: true }); + + return { + status: 'two_factor_required', + challenge: { + challengeId: String(response.data.challenge_id ?? ''), + providerId: String(response.data.provider_id ?? ''), + expiresAt: response.data.expires_at ?? null, + }, + }; + } + + // 두 필드가 모두 있을 때만 세션을 연다 — 한쪽만 보고 진행하면 undefined 토큰이 + // 저장되어 이후 모든 요청이 401 이 된다. + if (response.data.token && response.data.user) { + return { + status: 'authenticated', + user: this.establishSession(type, response.data.token, response.data.user), + }; + } + } + + throw new Error('Login failed'); + } catch (error: any) { + this.clearState(); + + throw this.enhanceAuthError(error, type, 'Login failed'); + } + } + + /** + * 2단계 인증 코드를 확인하고 로그인을 완료합니다. + * + * @param type - 인증 타입 + * @param payload - challenge 식별자와 사용자가 받은 인증번호 + * @param options - 추가 옵션 (headers 등) + * @returns 인증된 사용자 정보 + * @since engine-v1.65.0 + */ + async completeTwoFactor( + type: AuthType, + payload: { challengeId: string; code: string }, + options?: { headers?: Record } ): Promise { const apiClient = getApiClient(); const config = this.config.get(type); @@ -255,88 +371,167 @@ export class AuthManager { throw new Error(`Unknown auth type: ${type}`); } - // 로그인 엔드포인트 결정 - const loginEndpoint = type === 'admin' - ? defaultConfigs.admin.loginEndpoint - : defaultConfigs.user.loginEndpoint; - try { - // 추가 헤더 설정 (globalHeaders 지원) const requestConfig = options?.headers ? { headers: options.headers } : undefined; const response = await apiClient.post<{ success: boolean; - data: { - token: string; - user: AuthUser; - }; - }>(loginEndpoint, credentials, requestConfig); + data: LoginResponseData; + }>( + config.twoFactorEndpoint, + { challenge_id: payload.challengeId, code: payload.code }, + requestConfig + ); - if (response.success && response.data) { - // 토큰 저장 - apiClient.setToken(response.data.token); - - // 사용자의 language 설정 확인 및 로케일 변경 처리 - const userLanguage = response.data.user.language; - const currentLocale = localStorage.getItem(AuthManager.LOCALE_STORAGE_KEY); - const localeChanged = userLanguage && userLanguage !== currentLocale; - - if (userLanguage) { - try { - localStorage.setItem(AuthManager.LOCALE_STORAGE_KEY, userLanguage); - } catch (error) { - logger.warn('Failed to save user language to localStorage:', error); - } - } - - // 상태 업데이트 - this.state = { - isAuthenticated: true, - user: response.data.user, - type: type, - }; - - this.emit('login', this.state); - this.emit('authStateChange', this.state); - - // DevTools 추적 - trackAuthEvent('login', true, undefined, { - userId: response.data.user.uuid, - email: response.data.user.email, - type, - }); - - // 로케일이 변경된 경우 TemplateApp 재초기화 - if (localeChanged && (window as any).__templateApp) { - // changeLocale은 비동기이므로 await 하지 않고 실행 - // navigate가 먼저 실행되고, changeLocale이 완료되면 UI가 업데이트됨 - (window as any).__templateApp.changeLocale(userLanguage); - } - - return response.data.user; + if (response.success && response.data?.token && response.data?.user) { + return this.establishSession(type, response.data.token, response.data.user); } throw new Error('Login failed'); } catch (error: any) { this.clearState(); - // Axios 에러에서 API 응답 메시지 추출 - // error.response.data.message가 실제 서버 응답 메시지 - const apiMessage = error.response?.data?.message; - const enhancedError: any = new Error(apiMessage || error.message || 'Login failed'); - enhancedError.response = error.response; - enhancedError.status = error.response?.status; - - // DevTools 추적 - trackAuthEvent('login', false, enhancedError.message, { - type, - status: error.response?.status, - }); - - throw enhancedError; + throw this.enhanceAuthError(error, type, 'Login failed'); } } + /** + * 2단계 인증 코드를 재발송합니다. + * + * 서버가 기존 challenge 를 취소하고 새로 발행하므로, 앞서 받은 인증번호는 더 이상 + * 통하지 않습니다 — 호출자는 반드시 새 challenge 로 교체해야 합니다. + * + * @param type - 인증 타입 + * @param payload - 재발송할 challenge 식별자 + * @param options - 추가 옵션 (headers 등) + * @returns 새 challenge 정보 + * @since engine-v1.65.0 + */ + async resendTwoFactor( + type: AuthType, + payload: { challengeId: string }, + options?: { headers?: Record } + ): Promise { + const apiClient = getApiClient(); + const config = this.config.get(type); + + if (!config) { + throw new Error(`Unknown auth type: ${type}`); + } + + try { + const requestConfig = options?.headers ? { headers: options.headers } : undefined; + + const response = await apiClient.post<{ + success: boolean; + data: LoginResponseData; + }>( + config.twoFactorResendEndpoint, + { challenge_id: payload.challengeId }, + requestConfig + ); + + if (response.success && response.data?.challenge_id) { + return { + challengeId: String(response.data.challenge_id), + providerId: String(response.data.provider_id ?? ''), + expiresAt: response.data.expires_at ?? null, + }; + } + + throw new Error('Resend failed'); + } catch (error: any) { + // 재발송 실패는 세션 상태와 무관하다 — 이미 열린 세션이 없으므로 상태를 지우지 않는다. + throw this.enhanceAuthError(error, type, 'Resend failed'); + } + } + + /** + * 토큰을 저장하고 인증 상태·로케일을 확정합니다. + * + * 정상 로그인과 2단계 인증 완료가 같은 후처리를 공유하도록 단일 지점에 둔다 — + * 갈라지면 한쪽 경로에서만 로케일 전환이나 이벤트 발행이 빠진다. + * + * @param type - 인증 타입 + * @param token - 발급된 토큰 + * @param user - 인증된 사용자 + * @returns 인증된 사용자 정보 + */ + private establishSession(type: AuthType, token: string, user: AuthUser): AuthUser { + const apiClient = getApiClient(); + + // 토큰 저장 + apiClient.setToken(token); + + // 사용자의 language 설정 확인 및 로케일 변경 처리 + const userLanguage = user.language; + const currentLocale = localStorage.getItem(AuthManager.LOCALE_STORAGE_KEY); + const localeChanged = userLanguage && userLanguage !== currentLocale; + + if (userLanguage) { + try { + localStorage.setItem(AuthManager.LOCALE_STORAGE_KEY, userLanguage); + } catch (error) { + logger.warn('Failed to save user language to localStorage:', error); + } + } + + // 상태 업데이트 + this.state = { + isAuthenticated: true, + user, + type, + }; + + this.emit('login', this.state); + this.emit('authStateChange', this.state); + + // DevTools 추적 + trackAuthEvent('login', true, undefined, { + userId: user.uuid, + email: user.email, + type, + }); + + // 로케일이 변경된 경우 TemplateApp 재초기화 + if (localeChanged && (window as any).__templateApp) { + // changeLocale은 비동기이므로 await 하지 않고 실행 + // navigate가 먼저 실행되고, changeLocale이 완료되면 UI가 업데이트됨 + (window as any).__templateApp.changeLocale(userLanguage); + } + + return user; + } + + /** + * 인증 실패 오류에 서버 응답 정보를 실어 다시 던질 오류를 만듭니다. + * + * `code` 를 보존해야 호출자가 네트워크 실패(`ERR_NETWORK` 등)와 HTTP 오류를 구분해 + * 다국어 문구로 안내할 수 있다 — axios 오류는 `TypeError` 가 아니다. + * + * @param error - 원본 오류 + * @param type - 인증 타입 + * @param fallbackMessage - 서버 메시지가 없을 때 쓸 기본 문구 + * @returns 보강된 오류 + */ + private enhanceAuthError(error: any, type: AuthType, fallbackMessage: string): any { + // Axios 에러에서 API 응답 메시지 추출 + // error.response.data.message가 실제 서버 응답 메시지 + const apiMessage = error?.response?.data?.message; + const enhancedError: any = new Error(apiMessage || error?.message || fallbackMessage); + enhancedError.response = error?.response; + enhancedError.status = error?.response?.status; + enhancedError.code = error?.code; + + // DevTools 추적 + trackAuthEvent('login', false, enhancedError.message, { + type, + status: error?.response?.status, + }); + + return enhancedError; + } + /** * 로그아웃 처리 */ diff --git a/resources/js/core/auth/__tests__/AuthManager.test.ts b/resources/js/core/auth/__tests__/AuthManager.test.ts index e4b3d179..8d5c66ce 100644 --- a/resources/js/core/auth/__tests__/AuthManager.test.ts +++ b/resources/js/core/auth/__tests__/AuthManager.test.ts @@ -308,7 +308,7 @@ describe('AuthManager', () => { password: 'password', }); - expect(result).toEqual(mockUser); + expect(result).toEqual({ status: 'authenticated', user: mockUser }); expect(mockApiClient.setToken).toHaveBeenCalledWith('new-token'); expect(authManager.isAuthenticated()).toBe(true); expect(authManager.getUser()).toEqual(mockUser); @@ -381,5 +381,155 @@ describe('AuthManager', () => { undefined ); }); + + it('2단계 인증 응답에서는 토큰을 저장하지 않고 challenge 를 돌려줘야 합니다', async () => { + mockApiClient.post.mockResolvedValue({ + success: true, + data: { + two_factor_required: true, + challenge_id: 'challenge-uuid', + provider_id: 'g7:core.mail', + expires_at: '2026-09-07T14:03:00+09:00', + }, + }); + + const result = await authManager.login('user', { + email: 'test@example.com', + password: 'password', + }); + + expect(result).toEqual({ + status: 'two_factor_required', + challenge: { + challengeId: 'challenge-uuid', + providerId: 'g7:core.mail', + expiresAt: '2026-09-07T14:03:00+09:00', + }, + }); + // 토큰도 사용자도 없는 응답이다 — 저장하면 이후 모든 요청이 Bearer undefined 로 나간다. + expect(mockApiClient.setToken).not.toHaveBeenCalled(); + expect(authManager.isAuthenticated()).toBe(false); + }); + + it('updateConfig 로 바꾼 loginEndpoint 를 사용해야 합니다', async () => { + mockApiClient.post.mockResolvedValue({ + success: true, + data: { token: 'new-token', user: { id: 1, name: 'T', email: 't@e.com' } }, + }); + + authManager.updateConfig('user', { loginEndpoint: '/auth/custom-login' }); + + await authManager.login('user', { email: 'test@example.com', password: 'password' }); + + expect(mockApiClient.post).toHaveBeenCalledWith( + '/auth/custom-login', + { email: 'test@example.com', password: 'password' }, + undefined + ); + }); + + it('네트워크 오류의 code 를 보존해야 합니다', async () => { + const networkError: any = new Error('Network Error'); + networkError.code = 'ERR_NETWORK'; + mockApiClient.post.mockRejectedValue(networkError); + + // TypeError 가 아니므로 code 가 사라지면 네트워크 실패 판정이 불가능해진다. + await expect( + authManager.login('user', { email: 'test@example.com', password: 'password' }) + ).rejects.toMatchObject({ code: 'ERR_NETWORK' }); + }); + }); + + describe('completeTwoFactor', () => { + it('코드 확인에 성공하면 토큰을 저장하고 로그인 상태가 되어야 합니다', async () => { + const mockUser: AuthUser = { + id: 1, + name: 'Test User', + email: 'test@example.com', + }; + + mockApiClient.post.mockResolvedValue({ + success: true, + data: { token: 'two-factor-token', user: mockUser }, + }); + + const loginHandler = vi.fn(); + authManager.on('login', loginHandler); + + const result = await authManager.completeTwoFactor('user', { + challengeId: 'challenge-uuid', + code: '135790', + }); + + expect(result).toEqual(mockUser); + expect(mockApiClient.post).toHaveBeenCalledWith( + '/auth/login/two-factor', + { challenge_id: 'challenge-uuid', code: '135790' }, + undefined + ); + expect(mockApiClient.setToken).toHaveBeenCalledWith('two-factor-token'); + expect(authManager.isAuthenticated()).toBe(true); + expect(loginHandler).toHaveBeenCalled(); + }); + + it('관리자 타입은 관리자 전용 엔드포인트를 사용해야 합니다', async () => { + mockApiClient.post.mockResolvedValue({ + success: true, + data: { token: 't', user: { id: 1, name: 'T', email: 't@e.com' } }, + }); + + await authManager.completeTwoFactor('admin', { + challengeId: 'challenge-uuid', + code: '135790', + }); + + expect(mockApiClient.post).toHaveBeenCalledWith( + '/auth/admin/login/two-factor', + { challenge_id: 'challenge-uuid', code: '135790' }, + undefined + ); + }); + + it('실패 시 서버 메시지를 실은 에러를 throw 해야 합니다', async () => { + const error: any = new Error('Request failed'); + error.response = { status: 401, data: { message: '인증번호가 올바르지 않습니다.' } }; + mockApiClient.post.mockRejectedValue(error); + + await expect( + authManager.completeTwoFactor('user', { challengeId: 'c', code: '000000' }) + ).rejects.toThrow('인증번호가 올바르지 않습니다.'); + + expect(authManager.isAuthenticated()).toBe(false); + }); + }); + + describe('resendTwoFactor', () => { + it('새 challenge 를 돌려주고 토큰은 건드리지 않아야 합니다', async () => { + mockApiClient.post.mockResolvedValue({ + success: true, + data: { + two_factor_required: true, + challenge_id: 'new-challenge', + provider_id: 'g7:core.mail', + expires_at: null, + }, + }); + + const result = await authManager.resendTwoFactor('user', { + challengeId: 'old-challenge', + }); + + expect(result).toEqual({ + challengeId: 'new-challenge', + providerId: 'g7:core.mail', + expiresAt: null, + }); + expect(mockApiClient.post).toHaveBeenCalledWith( + '/auth/login/two-factor/resend', + { challenge_id: 'old-challenge' }, + undefined + ); + expect(mockApiClient.setToken).not.toHaveBeenCalled(); + }); }); }); diff --git a/resources/js/core/auth/index.ts b/resources/js/core/auth/index.ts index 6d7959d8..c133b655 100644 --- a/resources/js/core/auth/index.ts +++ b/resources/js/core/auth/index.ts @@ -4,4 +4,6 @@ export { type AuthConfig, type AuthUser, type AuthState, + type TwoFactorChallenge, + type LoginResult, } from './AuthManager'; \ No newline at end of file diff --git a/resources/js/core/template-engine/ActionDispatcher.ts b/resources/js/core/template-engine/ActionDispatcher.ts index 05c1c803..14f06b18 100644 --- a/resources/js/core/template-engine/ActionDispatcher.ts +++ b/resources/js/core/template-engine/ActionDispatcher.ts @@ -132,6 +132,8 @@ export type ActionType = | 'replaceUrl' // URL만 변경 (데이터소스 refetch 없음) | 'apiCall' // API 호출 | 'login' // 로그인 (토큰 저장 포함) + | 'loginTwoFactor' // 2단계 인증 코드 확인 (로그인 완료) + | 'loginTwoFactorResend' // 2단계 인증 코드 재발송 | 'logout' // 로그아웃 | 'setState' // 상태 변경 | 'setError' // 에러 상태 설정 @@ -2464,6 +2466,22 @@ export class ActionDispatcher { ); break; + case 'loginTwoFactor': + result = await this.handleLoginTwoFactor( + resolvedTarget!, + resolvedParams, + context + ); + break; + + case 'loginTwoFactorResend': + result = await this.handleLoginTwoFactorResend( + resolvedTarget!, + resolvedParams, + context + ); + break; + case 'logout': result = await this.handleLogout(resolvedTarget!, context); break; @@ -3828,8 +3846,7 @@ export class ActionDispatcher { ); } - // target을 인증 타입으로 사용 (admin 또는 user) - const authType: AuthType = target === 'user' ? 'user' : 'admin'; + const authType = this.resolveAuthType(target); // 로그인 엔드포인트 결정 (globalHeaders 패턴 매칭용) // ApiClient는 baseURL이 '/api'이므로 실제 요청 경로에 '/api' prefix 추가 @@ -3837,49 +3854,184 @@ export class ActionDispatcher { ? '/api/auth/admin/login' : '/api/auth/login'; - // globalHeaders에서 패턴 매칭되는 헤더 추출 - // Stale Closure 방지: G7Core.state.getGlobal/getLocal()로 최신 상태 조회 - // (cartKey 재발급 등 중간에 상태가 변경된 경우에도 최신 값 사용) - const currentGlobalState = (window as any).G7Core?.state?.getGlobal?.() || _context.state?._global || {}; - const currentLocalState = (window as any).G7Core?.state?.getLocal?.() || _context.state?._local || {}; - - const expressionContext: Record = { - _global: currentGlobalState, - _local: currentLocalState, - }; - const globalHeadersResolved = this.getMatchingGlobalHeaders(loginEndpoint, expressionContext); - const authManager = AuthManager.getInstance(); try { // AuthManager.login()을 통해 로그인 및 토큰 저장 // globalHeaders가 있으면 options.headers로 전달 - const loginOptions = Object.keys(globalHeadersResolved).length > 0 - ? { headers: globalHeadersResolved } - : undefined; - - const user = await authManager.login( + const result = await authManager.login( authType, { email: body.email, password: body.password }, - loginOptions + this.buildAuthRequestOptions(loginEndpoint, _context) + ); + + // 2단계 인증이 켜진 사이트에서는 아직 로그인이 끝나지 않았다. 레이아웃이 그 사실을 + // 알 통로가 없으면 인증번호 입력 단계로 넘어갈 방법이 없다. + if (result.status === 'two_factor_required') { + return { + user: null, + two_factor_required: true, + challenge_id: result.challenge.challengeId, + provider_id: result.challenge.providerId, + expires_at: result.challenge.expiresAt, + }; + } + + // `user` 는 종전 계약 그대로 유지한다 — 기존 레이아웃이 `response.user` 를 읽는다. + return { user: result.user, two_factor_required: false }; + } catch (error: any) { + throw this.toLoginActionError(error, 'Login failed'); + } + } + + /** + * loginTwoFactor 액션을 처리합니다. + * + * 비밀번호 확인 단계가 돌려준 challenge 와 사용자가 받은 인증번호로 로그인을 완료합니다. + * + * @param target 인증 타입 (admin 또는 user) + * @param params 요청 파라미터 (body에 challenge_id, code 포함) + * @param context 액션 컨텍스트 + * @since engine-v1.65.0 + */ + private async handleLoginTwoFactor( + target: string, + params: Record, + context: ActionContext + ): Promise { + const { body } = params; + + if (!body || !body.challenge_id || !body.code) { + throw new ActionError( + 'loginTwoFactor requires challenge_id and code in body params' + ); + } + + const authType = this.resolveAuthType(target); + const endpoint = authType === 'admin' + ? '/api/auth/admin/login/two-factor' + : '/api/auth/login/two-factor'; + + try { + const user = await AuthManager.getInstance().completeTwoFactor( + authType, + { challengeId: String(body.challenge_id), code: String(body.code) }, + this.buildAuthRequestOptions(endpoint, context) ); return { user }; } catch (error: any) { - // AuthManager에서 이미 API 응답 메시지를 추출한 에러를 throw하므로 - // error.message에 실제 서버 응답 메시지가 들어있음 - const errorMessage = error.message || 'Login failed'; + throw this.toLoginActionError(error, 'Login failed'); + } + } - const apiError: any = new Error(errorMessage); - apiError.response = error.response?.data || {}; - apiError.status = error.status || error.response?.status || 500; + /** + * loginTwoFactorResend 액션을 처리합니다. + * + * 서버가 기존 challenge 를 취소하고 새로 발행하므로, 레이아웃은 반환된 새 + * `challenge_id` 로 반드시 교체해야 합니다. + * + * @param target 인증 타입 (admin 또는 user) + * @param params 요청 파라미터 (body에 challenge_id 포함) + * @param context 액션 컨텍스트 + * @since engine-v1.65.0 + */ + private async handleLoginTwoFactorResend( + target: string, + params: Record, + context: ActionContext + ): Promise { + const { body } = params; + if (!body || !body.challenge_id) { throw new ActionError( - errorMessage, - undefined, - apiError + 'loginTwoFactorResend requires challenge_id in body params' ); } + + const authType = this.resolveAuthType(target); + const endpoint = authType === 'admin' + ? '/api/auth/admin/login/two-factor/resend' + : '/api/auth/login/two-factor/resend'; + + try { + const challenge = await AuthManager.getInstance().resendTwoFactor( + authType, + { challengeId: String(body.challenge_id) }, + this.buildAuthRequestOptions(endpoint, context) + ); + + return { + two_factor_required: true, + challenge_id: challenge.challengeId, + provider_id: challenge.providerId, + expires_at: challenge.expiresAt, + }; + } catch (error: any) { + throw this.toLoginActionError(error, 'Resend failed'); + } + } + + /** + * 액션 target 을 인증 타입으로 해석합니다. + * + * @param target 액션 target + * @returns 인증 타입 + */ + private resolveAuthType(target: string): AuthType { + return target === 'user' ? 'user' : 'admin'; + } + + /** + * 인증 요청에 실을 globalHeaders 옵션을 만듭니다. + * + * 세 인증 핸들러가 같은 규칙을 공유하도록 단일 지점에 둔다 — 갈라지면 한 경로에만 + * 공통 헤더가 빠져 그 요청만 조용히 다르게 나간다. + * + * @param endpoint 요청 경로 (globalHeaders 패턴 매칭용, '/api' prefix 포함) + * @param context 액션 컨텍스트 + * @returns headers 옵션 (매칭된 헤더가 없으면 undefined) + */ + private buildAuthRequestOptions( + endpoint: string, + context: ActionContext + ): { headers: Record } | undefined { + // Stale Closure 방지: G7Core.state.getGlobal/getLocal()로 최신 상태 조회 + // (cartKey 재발급 등 중간에 상태가 변경된 경우에도 최신 값 사용) + const currentGlobalState = (window as any).G7Core?.state?.getGlobal?.() || context.state?._global || {}; + const currentLocalState = (window as any).G7Core?.state?.getLocal?.() || context.state?._local || {}; + + const expressionContext: Record = { + _global: currentGlobalState, + _local: currentLocalState, + }; + + const resolved = this.getMatchingGlobalHeaders(endpoint, expressionContext); + + return Object.keys(resolved).length > 0 ? { headers: resolved } : undefined; + } + + /** + * AuthManager 오류를 액션 오류로 재포장합니다. + * + * `code` 를 보존해야 호출자가 네트워크 실패와 HTTP 오류를 구분해 다국어 문구로 + * 안내할 수 있다 — axios 오류는 `TypeError` 가 아니다. + * + * @param error 원본 오류 + * @param fallbackMessage 서버 메시지가 없을 때 쓸 기본 문구 + * @returns 액션 오류 + */ + private toLoginActionError(error: any, fallbackMessage: string): ActionError { + // AuthManager에서 이미 API 응답 메시지를 추출한 에러를 throw하므로 + // error.message에 실제 서버 응답 메시지가 들어있음 + const errorMessage = error?.message || fallbackMessage; + + const apiError: any = new Error(errorMessage); + apiError.response = error?.response?.data || {}; + apiError.status = error?.status || error?.response?.status || 500; + apiError.code = error?.code; + + return new ActionError(errorMessage, undefined, apiError); } /** diff --git a/resources/js/core/template-engine/CHANGELOG.md b/resources/js/core/template-engine/CHANGELOG.md index 8afe53a5..8cedf9ac 100644 --- a/resources/js/core/template-engine/CHANGELOG.md +++ b/resources/js/core/template-engine/CHANGELOG.md @@ -5,6 +5,27 @@ > > 형식: [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/) +## [engine-v1.65.0] - 2026-09-07 + +### Added + +#### 2단계 인증 로그인 단계 지원 +- 로그인 응답을 `LoginResult` 판별 유니온으로 표현 — 정상 로그인과 인증번호 요구(challenge)를 타입으로 구분 (AuthManager.ts) +- `completeTwoFactor()` / `resendTwoFactor()` 추가 — 인증번호 확인·재발송 (AuthManager.ts) +- `AuthConfig` 에 `twoFactorEndpoint` / `twoFactorResendEndpoint` 추가 (AuthManager.ts) +- 액션 핸들러 `loginTwoFactor` / `loginTwoFactorResend` 추가 — 레이아웃에서 인증번호 확인·재발송 (ActionDispatcher.ts) +- `login` 핸들러 반환에 `two_factor_required` / `challenge_id` / `provider_id` / `expires_at` 추가 (기존 `user` 필드 유지) (ActionDispatcher.ts) +- 레이아웃 편집기 [화면 동작] 탭에 두 핸들러 등록 (coreActionRecipes.ts, ActionAddPicker.tsx) + +### Fixed + +#### 2단계 인증이 켜진 사이트에서 로그인 화면이 영문 오류로 멈추던 문제 +- 로그인 응답 형태를 하나로 가정해 인증번호 요구 응답에서 `TypeError` 원문이 오류 박스에 노출되던 문제 (AuthManager.ts) +- 문자열이 아닌 토큰이 저장되어 이후 모든 요청이 401 로 튕기던 문제 (ApiClient.ts) +- `updateConfig({ loginEndpoint })` 로 지정한 엔드포인트가 무시되던 문제 (AuthManager.ts) +- axios 네트워크 오류가 네트워크 실패로 판정되지 않아 영문 원문이 노출되던 문제 (networkResilience.ts, ActionDispatcher.ts) +- 다국어 파라미터 값의 파이프 필터(`$t:key|until={{x | datetime}}`)가 평가되지 않아 문장에서 값만 사라지던 문제 (TranslationEngine.ts) + ## [engine-v1.64.7] - 2026-09-04 ### Fixed diff --git a/resources/js/core/template-engine/TranslationEngine.ts b/resources/js/core/template-engine/TranslationEngine.ts index ad0c3279..350b864d 100644 --- a/resources/js/core/template-engine/TranslationEngine.ts +++ b/resources/js/core/template-engine/TranslationEngine.ts @@ -19,6 +19,7 @@ import { fetchStaticFirst } from '../support/fetchStaticFirst'; // 양쪽 모두 모듈 평가 시점이 아니라 메서드 실행 시점에만 서로를 참조하므로 // live binding 이 채워진 뒤에 사용된다. import { dataBindingEngine } from './DataBindingEngine'; +import { hasPipes } from './PipeRegistry'; const logger = createLogger('TranslationEngine'); @@ -505,6 +506,20 @@ export class TranslationEngine { if (value.startsWith('{{') && value.endsWith('}}')) { const expression = value.slice(2, -2).trim(); + // 파이프 필터(`{{x | datetime}}`)는 표현식 평가기가 모른다 — `|` 를 비트 연산자로 + // 읽어 평가에 실패하고, 아래 catch 가 빈 문자열을 돌려주므로 문장에서 값만 조용히 + // 사라진다("유효시간 까지"). 파이프 전용 평가기로 먼저 처리한다. + // @since engine-v1.65.0 + if (hasPipes(expression) && dataContext) { + try { + const piped = dataBindingEngine.evaluatePipeExpression(expression, dataContext); + return String(piped ?? ''); + } catch (error) { + logger.error('Pipe expression evaluation failed:', expression, error); + return ''; + } + } + // 복잡한 표현식인지 확인 (연산자, 괄호, 메서드 호출 등 포함) // 산술 연산자(+, -, *, /, %), 비교 연산자(<, >, =), 논리 연산자, 공백(피연산자 분리)도 포함 const isComplexExpression = /[|&()[\]!?:+\-*/%<>=\s]/.test(expression); diff --git a/resources/js/core/template-engine/__tests__/ActionDispatcher.globalHeaders.test.ts b/resources/js/core/template-engine/__tests__/ActionDispatcher.globalHeaders.test.ts index 92f8d544..b796afad 100644 --- a/resources/js/core/template-engine/__tests__/ActionDispatcher.globalHeaders.test.ts +++ b/resources/js/core/template-engine/__tests__/ActionDispatcher.globalHeaders.test.ts @@ -10,7 +10,7 @@ import { GlobalHeaderRule } from '../LayoutLoader'; import { Logger } from '../../utils/Logger'; // AuthManager mock - login 호출 시 전달된 인자 추적 -const mockLogin = vi.fn().mockResolvedValue({ id: 1, name: 'Test User' }); +const mockLogin = vi.fn().mockResolvedValue({ status: 'authenticated', user: { id: 1, name: 'Test User' } }); const mockLogout = vi.fn().mockResolvedValue(undefined); vi.mock('../../auth/AuthManager', () => ({ @@ -40,7 +40,7 @@ describe('ActionDispatcher - globalHeaders', () => { mockNavigate = vi.fn(); mockGetToken.mockReset(); mockLogin.mockReset(); - mockLogin.mockResolvedValue({ id: 1, name: 'Test User' }); + mockLogin.mockResolvedValue({ status: 'authenticated', user: { id: 1, name: 'Test User' } }); dispatcher = new ActionDispatcher({ navigate: mockNavigate }); Logger.getInstance().setDebug(false); diff --git a/resources/js/core/template-engine/__tests__/ActionDispatcher.loginTwoFactor.test.ts b/resources/js/core/template-engine/__tests__/ActionDispatcher.loginTwoFactor.test.ts new file mode 100644 index 00000000..986bd04e --- /dev/null +++ b/resources/js/core/template-engine/__tests__/ActionDispatcher.loginTwoFactor.test.ts @@ -0,0 +1,218 @@ +/** + * ActionDispatcher 2단계 인증 핸들러 테스트 + * + * 서버는 보안 환경설정에 따라 로그인에 **두 가지 형태의 200** 을 돌려준다. 레이아웃이 + * 그 사실을 알 통로가 없으면 인증번호 입력 단계로 넘어갈 방법이 없고, 화면은 알 수 없는 + * 오류로 멈춘다(공개 #133). + * + * @since engine-v1.65.0 + */ + +import { describe, it, expect, beforeEach, afterEach, vi } from 'vitest'; +import { ActionDispatcher, ActionDefinition } from '../ActionDispatcher'; +import { Logger } from '../../utils/Logger'; + +const mockLogin = vi.fn(); +const mockCompleteTwoFactor = vi.fn(); +const mockResendTwoFactor = vi.fn(); +const mockLogout = vi.fn().mockResolvedValue(undefined); + +vi.mock('../../auth/AuthManager', () => ({ + AuthManager: { + getInstance: vi.fn(() => ({ + login: mockLogin, + logout: mockLogout, + completeTwoFactor: mockCompleteTwoFactor, + resendTwoFactor: mockResendTwoFactor, + })), + }, +})); + +vi.mock('../../api/ApiClient', () => ({ + getApiClient: vi.fn(() => ({ + getToken: vi.fn(), + })), +})); + +describe('ActionDispatcher - 2단계 인증', () => { + let dispatcher: ActionDispatcher; + + beforeEach(() => { + mockLogin.mockReset(); + mockCompleteTwoFactor.mockReset(); + mockResendTwoFactor.mockReset(); + dispatcher = new ActionDispatcher({ navigate: vi.fn() }); + Logger.getInstance().setDebug(false); + }); + + afterEach(() => { + Logger.getInstance().setDebug(false); + }); + + const context = () => ({ state: { _global: {}, _local: {} } }); + + const run = async (action: ActionDefinition) => { + const result = await dispatcher.dispatchAction(action, context() as any); + + if (!result.success) { + throw result.error ?? new Error('action failed'); + } + + return result.data; + }; + + describe('login', () => { + it('challenge 응답을 레이아웃이 읽을 수 있는 형태로 돌려준다', async () => { + mockLogin.mockResolvedValue({ + status: 'two_factor_required', + challenge: { + challengeId: 'challenge-uuid', + providerId: 'g7:core.mail', + expiresAt: '2026-09-07T14:03:00+09:00', + }, + }); + + const result = await run({ + type: 'click', + handler: 'login', + target: 'user', + params: { body: { email: 'a@b.c', password: 'pw' } }, + }); + + expect(result).toMatchObject({ + user: null, + two_factor_required: true, + challenge_id: 'challenge-uuid', + provider_id: 'g7:core.mail', + expires_at: '2026-09-07T14:03:00+09:00', + }); + }); + + it('정상 로그인은 종전대로 user 를 돌려준다', async () => { + const user = { id: 1, name: 'Test User' }; + mockLogin.mockResolvedValue({ status: 'authenticated', user }); + + const result = await run({ + type: 'click', + handler: 'login', + target: 'user', + params: { body: { email: 'a@b.c', password: 'pw' } }, + }); + + // 기존 레이아웃이 `response.user` 를 읽으므로 이 계약은 유지되어야 한다. + expect(result).toMatchObject({ user, two_factor_required: false }); + }); + }); + + describe('loginTwoFactor', () => { + it('challenge_id 와 code 로 로그인을 완료한다', async () => { + const user = { id: 1, name: 'Test User' }; + mockCompleteTwoFactor.mockResolvedValue(user); + + const result = await run({ + type: 'click', + handler: 'loginTwoFactor', + target: 'user', + params: { body: { challenge_id: 'challenge-uuid', code: '135790' } }, + }); + + expect(mockCompleteTwoFactor).toHaveBeenCalledWith( + 'user', + { challengeId: 'challenge-uuid', code: '135790' }, + undefined + ); + expect(result).toEqual({ user }); + }); + + it('globalHeaders 패턴이 관리자 확인 요청에도 적용된다', async () => { + mockCompleteTwoFactor.mockResolvedValue({ id: 1 }); + dispatcher.setGlobalHeaders([ + { pattern: '/api/auth/*', headers: { 'X-Cart-Key': 'ck_admin456' } }, + ]); + + await run({ + type: 'click', + handler: 'loginTwoFactor', + target: 'admin', + params: { body: { challenge_id: 'c', code: '135790' } }, + }); + + expect(mockCompleteTwoFactor).toHaveBeenCalledWith( + 'admin', + { challengeId: 'c', code: '135790' }, + { headers: { 'X-Cart-Key': 'ck_admin456' } } + ); + }); + + it('code 가 없으면 요청을 보내지 않는다', async () => { + await expect( + run({ + type: 'click', + handler: 'loginTwoFactor', + target: 'user', + params: { body: { challenge_id: 'c' } }, + }) + ).rejects.toThrow(); + + expect(mockCompleteTwoFactor).not.toHaveBeenCalled(); + }); + + it('서버 오류 메시지를 그대로 실어 재포장한다', async () => { + const error: any = new Error('인증번호가 올바르지 않거나 유효시간이 지났습니다.'); + error.response = { status: 401, data: { message: '인증번호가 올바르지 않거나 유효시간이 지났습니다.' } }; + error.status = 401; + mockCompleteTwoFactor.mockRejectedValue(error); + + await expect( + run({ + type: 'click', + handler: 'loginTwoFactor', + target: 'user', + params: { body: { challenge_id: 'c', code: '000000' } }, + }) + ).rejects.toThrow('인증번호가 올바르지 않거나 유효시간이 지났습니다.'); + }); + }); + + describe('loginTwoFactorResend', () => { + it('새 challenge 를 돌려준다', async () => { + mockResendTwoFactor.mockResolvedValue({ + challengeId: 'new-challenge', + providerId: 'g7:core.mail', + expiresAt: null, + }); + + const result = await run({ + type: 'click', + handler: 'loginTwoFactorResend', + target: 'user', + params: { body: { challenge_id: 'old-challenge' } }, + }); + + expect(mockResendTwoFactor).toHaveBeenCalledWith( + 'user', + { challengeId: 'old-challenge' }, + undefined + ); + expect(result).toEqual({ + two_factor_required: true, + challenge_id: 'new-challenge', + provider_id: 'g7:core.mail', + expires_at: null, + }); + }); + + it('challenge_id 가 없으면 요청을 보내지 않는다', async () => { + await expect( + run({ + type: 'click', + handler: 'loginTwoFactorResend', + target: 'user', + params: { body: {} }, + }) + ).rejects.toThrow(); + + expect(mockResendTwoFactor).not.toHaveBeenCalled(); + }); + }); +}); diff --git a/resources/js/core/template-engine/__tests__/TranslationEngine.test.ts b/resources/js/core/template-engine/__tests__/TranslationEngine.test.ts index 4334fe80..7369a0a8 100644 --- a/resources/js/core/template-engine/__tests__/TranslationEngine.test.ts +++ b/resources/js/core/template-engine/__tests__/TranslationEngine.test.ts @@ -594,6 +594,9 @@ describe('TranslationEngine', () => { complex: { message: '{{user}}님이 {{action}}을 수행했습니다 ({{count}}건)', }, + auth: { + valid_until: '유효시간 {{until}} 까지', + }, }; (global.fetch as any).mockResolvedValueOnce({ @@ -710,6 +713,32 @@ describe('TranslationEngine', () => { ); expect(result).toBe('총 100명 중 1-10명 표시'); }); + + // 파라미터 값 안의 파이프는 **필터**다. 표현식 평가기는 `|` 를 비트 연산자로 읽어 + // 평가에 실패하고 빈 문자열을 돌려주므로, 문장에서 값만 조용히 사라진다 + // ("유효시간 까지"). 오류도 경고도 남지 않아 화면을 보지 않으면 드러나지 않는다. + // @since engine-v1.65.0 + it('파라미터 값의 파이프 필터가 적용된다', () => { + const result = engine.translate( + 'auth.valid_until', + context, + '|until={{expires_at | datetime}}', + { expires_at: '2026-09-07T14:03:00' } + ); + + expect(result).toBe('유효시간 2026-09-07 14:03 까지'); + }); + + it('resolveTranslations 에서도 파라미터 파이프 필터가 적용된다', () => { + const result = engine.resolveTranslations( + '$t:auth.valid_until', + context, + { expires_at: '2026-09-07T14:03:00' } + ); + + // 파라미터가 없으면 자리표시자는 그대로 둔다 (기존 동작 유지) + expect(result).toContain('유효시간'); + }); }); describe('resolveTranslations 재귀 처리', () => { diff --git a/resources/js/core/template-engine/__tests__/actionDispatcherNetworkFailureMessage.test.ts b/resources/js/core/template-engine/__tests__/actionDispatcherNetworkFailureMessage.test.ts index 7e75bb56..d72f4327 100644 --- a/resources/js/core/template-engine/__tests__/actionDispatcherNetworkFailureMessage.test.ts +++ b/resources/js/core/template-engine/__tests__/actionDispatcherNetworkFailureMessage.test.ts @@ -33,6 +33,26 @@ describe('resolveActionFailureMessage', () => { ); }); + it('axios 네트워크 오류도 네트워크 계열로 안내한다', () => { + // axios 는 TypeError 가 아니라 AxiosError 로 reject 하며 종류는 code 에만 남는다. + // TypeError 만 보면 로그인 화면에 영문 원문(Network Error)이 그대로 노출된다. + const axiosError: any = new Error('Network Error'); + axiosError.code = 'ERR_NETWORK'; + + expect(resolveActionFailureMessage(axiosError, 'login', undefined)).toBe( + '$t:core.errors.network_request_failed' + ); + }); + + it('요청 시간 초과도 네트워크 계열로 안내한다', () => { + const timeout: any = new Error('timeout of 30000ms exceeded'); + timeout.code = 'ECONNABORTED'; + + expect(resolveActionFailureMessage(timeout, 'login', undefined)).toBe( + '$t:core.errors.network_request_failed' + ); + }); + it('서버가 메시지를 주면 그대로 쓴다', () => { expect( resolveActionFailureMessage(new Error('boom'), 'apiCall', '유효하지 않은 레이아웃 전략입니다.') diff --git a/resources/js/core/template-engine/layout-editor/__tests__/spec/coreActionRecipes.test.ts b/resources/js/core/template-engine/layout-editor/__tests__/spec/coreActionRecipes.test.ts index 98d04b32..b92bd30d 100644 --- a/resources/js/core/template-engine/layout-editor/__tests__/spec/coreActionRecipes.test.ts +++ b/resources/js/core/template-engine/layout-editor/__tests__/spec/coreActionRecipes.test.ts @@ -24,7 +24,7 @@ const EXPECTED_HANDLERS = [ // C14~C16 데이터 'refetchDataSource', 'appendDataSource', 'updateDataSource', // C17~C22 기타 - 'scrollIntoView', 'login', 'logout', 'setLocale', 'emitEvent', 'apiCall', + 'scrollIntoView', 'login', 'loginTwoFactor', 'loginTwoFactorResend', 'logout', 'setLocale', 'emitEvent', 'apiCall', // C24~C27 제어흐름(C23 top-level if 는 엔진 처리 — 카탈로그 비포함) + C29 conditions 'conditions', 'sequence', 'parallel', 'switch', 'suppress', // 결제 진입(requestPgPayment)은 코어 카탈로그에서 제외됨 — 결제는 커머스 도메인이라 diff --git a/resources/js/core/template-engine/layout-editor/components/page-settings/ActionAddPicker.tsx b/resources/js/core/template-engine/layout-editor/components/page-settings/ActionAddPicker.tsx index f7e8cd31..b7f0e45d 100644 --- a/resources/js/core/template-engine/layout-editor/components/page-settings/ActionAddPicker.tsx +++ b/resources/js/core/template-engine/layout-editor/components/page-settings/ActionAddPicker.tsx @@ -58,6 +58,8 @@ const GROUP_OF: Record = { apiCall: 'data', scrollIntoView: 'etc', login: 'etc', + loginTwoFactor: 'etc', + loginTwoFactorResend: 'etc', logout: 'etc', setLocale: 'locale', emitEvent: 'etc', diff --git a/resources/js/core/template-engine/layout-editor/spec/coreActionRecipes.ts b/resources/js/core/template-engine/layout-editor/spec/coreActionRecipes.ts index f4575be7..fccf9560 100644 --- a/resources/js/core/template-engine/layout-editor/spec/coreActionRecipes.ts +++ b/resources/js/core/template-engine/layout-editor/spec/coreActionRecipes.ts @@ -285,6 +285,18 @@ export const CORE_ACTION_RECIPES: Record = { params: [{ key: 'body', label: `$t:${L}.login.param_body`, widget: 'key-value' }], build: { handler: 'login', params: { body: '{{body}}' } }, }, + // C18-1 2단계 인증 코드 확인 (로그인 완료) + loginTwoFactor: { + label: `$t:${L}.login_two_factor.label`, + params: [{ key: 'body', label: `$t:${L}.login_two_factor.param_body`, widget: 'key-value' }], + build: { handler: 'loginTwoFactor', params: { body: '{{body}}' } }, + }, + // C18-2 2단계 인증 코드 재발송 + loginTwoFactorResend: { + label: `$t:${L}.login_two_factor_resend.label`, + params: [{ key: 'body', label: `$t:${L}.login_two_factor_resend.param_body`, widget: 'key-value' }], + build: { handler: 'loginTwoFactorResend', params: { body: '{{body}}' } }, + }, // C19 로그아웃 처리 logout: { label: `$t:${L}.logout.label`, diff --git a/resources/js/core/template-engine/networkResilience.ts b/resources/js/core/template-engine/networkResilience.ts index 4ee0a907..c2c1c47e 100644 --- a/resources/js/core/template-engine/networkResilience.ts +++ b/resources/js/core/template-engine/networkResilience.ts @@ -59,13 +59,22 @@ export function isAbortError(error: unknown): boolean { * fetch 스펙상 네트워크 오류는 TypeError 로 reject 된다. 취소(AbortError)는 * 호출부의 의도이므로 재시도 대상이 아니다. * + * axios 경로(로그인 등 ApiClient 를 쓰는 요청)는 TypeError 가 아니라 `AxiosError` 로 + * reject 되며 종류는 `code` 에만 남는다. TypeError 만 보면 그 경로의 네트워크 실패가 + * 판정에서 빠져 영문 원문(`Network Error`)이 그대로 화면에 노출된다. + * * @param error 검사할 에러 * @return bool 재시도할 가치가 있는 네트워크 실패이면 true * @since engine-v1.53.0 + * @since engine-v1.65.0 axios 네트워크 오류 코드(ERR_NETWORK/ECONNABORTED) 인식 */ export function isNetworkFailure(error: unknown): boolean { if (isAbortError(error)) return false; - return error instanceof TypeError; + if (error instanceof TypeError) return true; + + const code = (error as { code?: string } | null)?.code; + + return code === 'ERR_NETWORK' || code === 'ECONNABORTED'; } let unloading = false; diff --git a/routes/api.php b/routes/api.php index e66ab10f..e207d8dc 100644 --- a/routes/api.php +++ b/routes/api.php @@ -256,6 +256,9 @@ Route::prefix('auth')->group(function () { // 로그인과 같은 제한을 적용해 코드 대입 시도를 함께 억제한다. Route::post('login/two-factor', [UserAuthController::class, 'verifyTwoFactor']) ->name('api.auth.login.two-factor'); + // 인증번호 재발송 — 기존 challenge 를 취소하고 새로 발행한다. + Route::post('login/two-factor/resend', [UserAuthController::class, 'resendTwoFactor']) + ->name('api.auth.login.two-factor.resend'); }); // 공개 인증 라우트 (세션 불필요) @@ -280,6 +283,13 @@ Route::prefix('auth')->group(function () { Route::post('login', [AdminAuthController::class, 'login']) ->middleware(['throttle:auth-login', 'start.api.session']) ->name('api.auth.admin.login'); + // 관리자 2단계 인증 확인·재발송 — 사용자 경로와 같은 제한을 적용한다. + Route::post('login/two-factor', [AdminAuthController::class, 'verifyTwoFactor']) + ->middleware(['throttle:auth-login', 'start.api.session']) + ->name('api.auth.admin.login.two-factor'); + Route::post('login/two-factor/resend', [AdminAuthController::class, 'resendTwoFactor']) + ->middleware(['throttle:auth-login', 'start.api.session']) + ->name('api.auth.admin.login.two-factor.resend'); }); }); diff --git a/templates/_bundled/sirsoft-admin_basic/AGENTS.md b/templates/_bundled/sirsoft-admin_basic/AGENTS.md index c90cc81e..8dd77c2c 100644 --- a/templates/_bundled/sirsoft-admin_basic/AGENTS.md +++ b/templates/_bundled/sirsoft-admin_basic/AGENTS.md @@ -104,6 +104,7 @@ admin/`)이 이 템플릿의 베이스(`_admin_base`)를 extends 하고 이 템 - [ ] `_admin_base.json` 슬롯 구조(`content` 슬롯 등) 변경 시 그 슬롯에 의존하는 모든 화면(145개 레이아웃 대다수) 영향 검토 - [ ] AdminSidebar 의 `MenuItem`/`AdminSidebarProps` 인터페이스 확장 시 이 문서의 §docs/components.md "AdminSidebar 상세" 동기화 - [ ] 레이아웃·컴포넌트·`data_source` 를 건드렸다면 [`docs/editor-spec.md`](docs/editor-spec.md) 의 동반 의무 표를 따라 `editor-spec/` 블록을 함께 갱신 — 컴포넌트는 팔레트·역량·중첩 **넷 다** 손대야 편집기에서 온전히 동작하고, 하나만 빠지면 절반만 동작한다. 반영은 `php artisan template:update sirsoft-admin_basic --force` (편집기는 활성 디렉토리만 읽는다) +- [ ] 로그인 화면의 2단계 인증 단계를 고쳤다면 1단계·2단계 `if` 의 상보성과 `login`/`loginTwoFactor` 의 상호배타 `if` 를 함께 확인 — 한쪽이 빠지면 인증번호 단계에서 Enter 가 새 challenge 를 발급한다 ## 6. 금지 패턴 @@ -114,6 +115,7 @@ admin/`)이 이 템플릿의 베이스(`_admin_base`)를 extends 하고 이 템 | 필수 컴포넌트 목록 밖의 이 템플릿 전용 컴포넌트를 모듈 레이아웃에서 사용 | 필수 컴포넌트(config/template.php) 만 사용 | 다른 admin 템플릿으로 교체 시 그 화면만 깨진다 | | 사이드바 접힘 상태를 레이아웃 `init_actions` 로 매번 복원 | 템플릿 부트스트랩(`src/index.ts`)에서 1회 복원 | `init_actions` 는 화면 진입마다 재실행되어 불필요한 반복 처리가 된다 | | `_admin_base` 를 상속하는데 로그인 화면처럼 `initTheme`/메뉴 초기화를 다시 호출 | `_admin_base` 상속 화면은 이미 초기화된 전역 상태를 그대로 사용 | 중복 호출은 낭비이며, 두 초기화 지점의 결과가 어긋나면 화면 간 상태 불일치가 생긴다 | +| `onSuccess`·시퀀스 안에서 방금 저장한 상태(`_global.*`/`_local.*`)를 형제 액션의 `if`·값으로 재독 | 그 자리에서는 `{{response.*}}` 만 읽는다 | 그 시점 컨텍스트는 아직 갱신 전이라 stale 값으로 조용히 분기한다 | ## 7. 테스트 실행 @@ -122,9 +124,9 @@ admin/`)이 이 템플릿의 베이스(`_admin_base`)를 extends 하고 이 템 | 종류 | 개수 | 위치 | |---|---|---| | PHPUnit | 0개 | — | -| Vitest | 208개 | `vitest.config.ts` | +| Vitest | 210개 | `vitest.config.ts` | | Playwright | 9개 | `tests/Playwright` | -| 시나리오 매니페스트 | 2개 | `tests/scenarios` | +| 시나리오 매니페스트 | 3개 | `tests/scenarios` | ```bash # Vitest (확장 디렉토리에서) (PowerShell) diff --git a/templates/_bundled/sirsoft-admin_basic/CHANGELOG.md b/templates/_bundled/sirsoft-admin_basic/CHANGELOG.md index f801de95..e81d5e5a 100644 --- a/templates/_bundled/sirsoft-admin_basic/CHANGELOG.md +++ b/templates/_bundled/sirsoft-admin_basic/CHANGELOG.md @@ -4,6 +4,20 @@ 형식은 [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/)를 따르며, [Semantic Versioning](https://semver.org/lang/ko/)을 준수합니다. +## [1.0.9] - 2026-09-07 + +### Added + +- 2단계 인증을 켠 사이트의 로그인 화면에 인증번호 입력 단계가 추가되었습니다. 비밀번호를 확인하면 같은 카드 안에서 인증번호 입력으로 넘어가고, 「인증번호 다시 받기」로 새 번호를 받거나 「처음부터」로 되돌아갈 수 있습니다. 인증번호의 유효 시각도 함께 표시됩니다. (#133 @keidichoi-gif 님께서 제보해주셨습니다.) + +### Changed + +- 코어 최소 요구 버전을 7.0.11 로 상향했습니다. + +### Fixed + +- 로그인 시도 초과로 계정이 잠겼을 때 해제 시각이 화면에 표시되지 않던 문제를 수정했습니다. 언제 다시 시도할 수 있는지 알 수 없어 계속 눌러 보게 되었습니다. + ## [1.0.8] - 2026-09-06 ### Added diff --git a/templates/_bundled/sirsoft-admin_basic/README.md b/templates/_bundled/sirsoft-admin_basic/README.md index 1696b342..3eb77f98 100644 --- a/templates/_bundled/sirsoft-admin_basic/README.md +++ b/templates/_bundled/sirsoft-admin_basic/README.md @@ -5,9 +5,9 @@

- version 1.0.8 + version 1.0.9 type 템플릿 - 그누보드7 >=7.0.10 + 그누보드7 >=7.0.11 license MIT

@@ -68,7 +68,7 @@ flowchart TD | 항목 | 값 | |---|---| -| 그누보드7 코어 | `>=7.0.10` | +| 그누보드7 코어 | `>=7.0.11` | | PHP | `^8.2` | diff --git a/templates/_bundled/sirsoft-admin_basic/__tests__/layouts/admin-login-two-factor-render.test.tsx b/templates/_bundled/sirsoft-admin_basic/__tests__/layouts/admin-login-two-factor-render.test.tsx new file mode 100644 index 00000000..5f4c0123 --- /dev/null +++ b/templates/_bundled/sirsoft-admin_basic/__tests__/layouts/admin-login-two-factor-render.test.tsx @@ -0,0 +1,337 @@ +/** + * @file admin-login-two-factor-render.test.tsx + * @description 관리자 로그인 2단계 인증 단계 **렌더링** 회귀 테스트 (sirsoft-admin_basic) + * + * 형제 파일 `admin-login-two-factor-step.test.tsx` 는 레이아웃 JSON 의 구조를 단언한다. + * 이 파일은 그 JSON 을 실제로 렌더해 화면에 무엇이 나타나는지를 단언한다. + * + * 관리자가 들어갈 수 없으면 설정을 되돌릴 수단까지 사라지므로 사용자 화면보다 파급이 크다 + * (공개 #133). + * + * @vitest-environment jsdom + * @since engine-v1.65.0 + */ + +import React from 'react'; +import { describe, it, expect, beforeEach, vi } from 'vitest'; +import { createLayoutTest } from '@/core/template-engine/__tests__/utils/layoutTestUtils'; +import { ComponentRegistry } from '@/core/template-engine/ComponentRegistry'; + +import adminLogin from '../../layouts/admin_login.json'; + +// 공개 #133 의 원인은 레이아웃이 아니라 **응답 형태를 하나로 가정한 코어**였다. 상태를 직접 +// 주입해 그린 화면만 단언하면 그 경로를 한 번도 태우지 않으므로, 코어가 다시 challenge 응답에서 +// 던지더라도 이 파일은 초록으로 남는다. API 를 모킹해 login 액션을 실제로 통과시킨다. +const apiPost = vi.fn(); + +vi.mock('@core/api/ApiClient', async () => { + const actual = await vi.importActual( + '@core/api/ApiClient' + ); + const stub = { + post: (...args: unknown[]) => apiPost(...args), + get: vi.fn(), + put: vi.fn(), + delete: vi.fn(), + getToken: vi.fn(() => null), + setToken: vi.fn(), + removeToken: vi.fn(), + setLocale: vi.fn(), + }; + return { ...actual, getApiClient: () => stub, createApiClient: () => stub }; +}); + +type Common = { + className?: string; + children?: React.ReactNode; + text?: string; +}; + +const TestDiv: React.FC = ({ className, children, role }) => ( +
{children}
+); +const TestSpan: React.FC = ({ className, children, text }) => ( + {children || text} +); +const TestP: React.FC = ({ className, children, text, role }) => ( +

{children || text}

+); +const TestH1: React.FC = ({ className, children, text }) => ( +

{children || text}

+); +const TestLabel: React.FC = ({ className, children, text, htmlFor }) => ( + +); +const TestForm: React.FC void }> = ({ + className, + children, + onSubmit, +}) =>
{children}
; +const TestButton: React.FC = ({ + type, + className, + disabled, + children, + text, +}) => ( + +); +const TestInput: React.FC<{ + id?: string; + type?: string; + name?: string; + value?: string; + placeholder?: string; + disabled?: boolean; + className?: string; + inputMode?: string; + autoComplete?: string; + maxLength?: number; +}> = ({ id, type, name, value, placeholder, disabled, className, inputMode, autoComplete, maxLength }) => ( + +); +const TestSelect: React.FC<{ className?: string; value?: string }> = ({ className }) => ( + +); + +const TestPasswordInput: React.FC<{ name?: string; disabled?: boolean; className?: string }> = ({ + name, + disabled, + className, +}) => ; + +const TestFragment: React.FC<{ children?: React.ReactNode }> = ({ children }) => <>{children}; + +function setupRegistry(): ComponentRegistry { + const registry = ComponentRegistry.getInstance(); + + (registry as any).registry = { + Div: { component: TestDiv, metadata: { name: 'Div', type: 'basic' } }, + Span: { component: TestSpan, metadata: { name: 'Span', type: 'basic' } }, + P: { component: TestP, metadata: { name: 'P', type: 'basic' } }, + Label: { component: TestLabel, metadata: { name: 'Label', type: 'basic' } }, + Form: { component: TestForm, metadata: { name: 'Form', type: 'basic' } }, + Button: { component: TestButton, metadata: { name: 'Button', type: 'basic' } }, + Input: { component: TestInput, metadata: { name: 'Input', type: 'basic' } }, + PasswordInput: { component: TestPasswordInput, metadata: { name: 'PasswordInput', type: 'basic' } }, + Fragment: { component: TestFragment, metadata: { name: 'Fragment', type: 'layout' } }, + }; + + return registry; +} + +/** 실제 파셜을 단독 레이아웃으로 감싼다 — 컴포넌트 트리는 그대로다. */ +const layout = { + version: '1.0.0', + layout_name: 'auth/login', + components: [loginForm as any], +}; + +/** 챌린지를 받은 뒤의 전역 상태 */ +const CHALLENGE_STATE = { + _global: { + twoFactor: { + required: true, + challenge_id: '9f1c2f2e-0b3a-4f0a-9a1e-5c1b7f9d2c40', + provider_id: 'g7:core.mail', + expires_at: '2026-09-07T14:03:00+09:00', + code: '', + error: null, + verifying: false, + resending: false, + resent: false, + }, + }, +}; + +describe('sirsoft-basic 로그인 폼 렌더링 — 2단계 인증', () => { + beforeEach(() => { + setupRegistry(); + }); + + /** + * @scenario step=credentials, response=ok, action=submit + * + * @effects credential_step_hidden_on_challenge + */ + it('초기 상태에서는 이메일·비밀번호만 보이고 인증번호 입력은 없다', async () => { + const t = createLayoutTest(layout, { componentRegistry: setupRegistry() }); + await t.render(); + + expect(document.querySelector('input[name="email"]')).not.toBeNull(); + expect(document.querySelector('input[name="password"]')).not.toBeNull(); + expect(document.querySelector('input[name="two_factor_code"]')).toBeNull(); + + t.cleanup(); + }); + + /** + * @scenario step=code, response=challenge, action=submit + * + * @effects code_step_rendered_on_challenge, credential_step_hidden_on_challenge + */ + it('challenge 를 받으면 인증번호 입력으로 바뀌고 자격 증명 입력은 사라진다', async () => { + const t = createLayoutTest(layout, { + componentRegistry: setupRegistry(), + initialState: CHALLENGE_STATE, + }); + await t.render(); + + const code = document.querySelector('input[name="two_factor_code"]'); + expect(code, '챌린지 상태인데 인증번호 입력이 렌더되지 않았습니다').not.toBeNull(); + expect(code?.getAttribute('inputmode')).toBe('numeric'); + expect(code?.getAttribute('autocomplete')).toBe('one-time-code'); + + // 두 단계가 함께 보이면 사용자가 어느 쪽을 채워야 하는지 알 수 없다. + expect(document.querySelector('input[name="email"]')).toBeNull(); + expect(document.querySelector('input[name="password"]')).toBeNull(); + + t.cleanup(); + }); + + /** + * @scenario step=code, response=401, action=submit + * + * @effects no_raw_typeerror_text + */ + it('오류 문구 자리에 영문 TypeError 원문이 나타나지 않는다', async () => { + const t = createLayoutTest(layout, { + componentRegistry: setupRegistry(), + initialState: { + _global: { + ...CHALLENGE_STATE._global, + twoFactor: { + ...CHALLENGE_STATE._global.twoFactor, + error: '인증번호가 올바르지 않거나 유효시간이 지났습니다.', + }, + }, + }, + }); + await t.render(); + + const body = document.body.textContent ?? ''; + + expect(body).toContain('인증번호가 올바르지 않거나 유효시간이 지났습니다.'); + // 공개 #133 의 증상 — 응답 형태를 하나로 가정했을 때 화면에 그대로 실리던 문구다. + expect(body).not.toContain('Cannot read properties of undefined'); + expect(body).not.toContain('undefined is not an object'); + + t.cleanup(); + }); + + /** + * @scenario step=credentials, response=423, action=submit + * + * @effects locked_until_rendered + */ + it('계정이 잠기면 해제 시각 줄이 함께 렌더된다', async () => { + const t = createLayoutTest(layout, { + componentRegistry: setupRegistry(), + initialState: { + _global: { + loginError: '로그인 시도 횟수 초과로 계정이 잠겼습니다.', + loginErrors: { locked_until: '2026-09-07T14:05:00+09:00', permanent: false }, + }, + }, + }); + await t.render(); + + // 잠금 안내와 별개로 해제 시각 줄이 존재해야 한다 (문구 자체는 다국어 키 해석 대상). + const paragraphs = Array.from(document.querySelectorAll('p')); + expect(paragraphs.length).toBeGreaterThanOrEqual(2); + expect(document.body.textContent ?? '').toContain('로그인 시도 횟수 초과로 계정이 잠겼습니다.'); + + t.cleanup(); + }); + + /** + * 상태 주입이 아니라 **서버 응답**에서 출발한다. 이 레이아웃의 login 액션을 그대로 실행해 + * 코어(AuthManager → 액션 반환값 → onSuccess 매핑)를 통과시킨 뒤 화면을 본다. + * + * 자격 증명 값만 리터럴로 바꾼다 — 폼 입력 값(`{{form.*}}`)은 렌더러가 들고 있고 이 하네스가 + * 관측하지 못하는 유일한 조각이기 때문이다. 그 밖의 경로는 전부 실물이다. + * + * @scenario step=credentials, response=challenge, action=submit + * + * @effects code_step_rendered_on_challenge, credential_step_hidden_on_challenge, no_raw_typeerror_text + */ + it('challenge 응답을 실제로 받으면 2단계로 넘어가고 오류 원문이 남지 않는다', async () => { + apiPost.mockReset(); + apiPost.mockResolvedValue({ + success: true, + data: { + two_factor_required: true, + challenge_id: '11111111-2222-3333-4444-555555555555', + provider_id: 'g7:core.mail', + expires_at: '2026-09-07T14:03:00+09:00', + }, + }); + + const t = createLayoutTest(layout, { componentRegistry: setupRegistry() }); + await t.render(); + + // 이 레이아웃이 실제로 선언한 login 액션 — 자격 증명만 리터럴로 채운다. + const submitSequence = (loginForm as any).actions[0]; + const loginAction = submitSequence.actions.find( + (a: any) => a.handler === 'login' + ); + expect(loginAction, 'login 액션이 제출 시퀀스에서 사라졌습니다').toBeDefined(); + + await t.triggerAction({ + ...loginAction, + if: undefined, + params: { body: { email: 'user@example.com', password: 'pw' } }, + }); + + // 코어가 challenge 응답에서 던지면(=#133) 여기까지 오지 못한다. + expect(apiPost).toHaveBeenCalled(); + const twoFactor = t.getState()._global?.twoFactor; + expect(twoFactor?.required, 'challenge 응답인데 2단계 상태가 서지 않았습니다').toBe(true); + expect(twoFactor?.challenge_id).toBe('11111111-2222-3333-4444-555555555555'); + expect(twoFactor?.code).toBe(''); + + await t.rerender(); + + expect(document.querySelector('input[name="two_factor_code"]')).not.toBeNull(); + expect(document.querySelector('input[name="email"]')).toBeNull(); + + const body = document.body.textContent ?? ''; + expect(body).not.toContain('Cannot read properties of undefined'); + + t.cleanup(); + }); + + /** + * 응답이 아예 없었던 실패(네트워크 끊김)는 HTTP 오류가 아니다. 그 자리에서 axios 오류 원문이나 + * 내부 식별 문구(`Failed to execute action: login`)가 새면 오류 박스에 영문이 그대로 실린다. + * 로그인 화면의 오류 문구는 사용자가 읽는 유일한 안내라 그 판정이 곧 화면 품질이다. + * + * @scenario step=credentials, response=network, action=submit + * + * @effects network_message_translated + */ + it('네트워크 실패는 영문 원문이 아니라 다국어 안내로 오류 박스에 실린다', async () => { + apiPost.mockReset(); + apiPost.mockRejectedValue(Object.assign(new Error('Network Error'), { + code: 'ERR_NETWORK', + })); + + const t = createLayoutTest(layout, { componentRegistry: setupRegistry() }); + await t.render(); + + const loginAction = (loginForm as any).actions[0].actions.find( + (a: any) => a.handler === 'login' + ); + + await t.triggerAction({ + ...loginAction, + if: undefined, + params: { body: { email: 'user@example.com', password: 'pw' } }, + }); + + const loginError = String(t.getState()._global?.loginError ?? ''); + + // 다국어 안내로 해석되는 값이어야 한다 — 번역기가 붙지 않은 하네스에서는 그 키가 남는다. + expect(loginError).toContain('core.errors.network_request_failed'); + // 판정이 무너지면 이 두 형태 중 하나가 그대로 화면에 실린다. + expect(loginError).not.toContain('Failed to execute action'); + expect(loginError).not.toBe('Network Error'); + + t.cleanup(); + }); +}); diff --git a/templates/_bundled/sirsoft-basic/__tests__/layouts/login-two-factor-step.test.tsx b/templates/_bundled/sirsoft-basic/__tests__/layouts/login-two-factor-step.test.tsx new file mode 100644 index 00000000..37628ac7 --- /dev/null +++ b/templates/_bundled/sirsoft-basic/__tests__/layouts/login-two-factor-step.test.tsx @@ -0,0 +1,211 @@ +/** + * @file login-two-factor-step.test.tsx + * @description 로그인 2단계 인증 단계 구조 회귀 테스트 (sirsoft-basic) + * + * 2단계 인증이 켜진 사이트에서 서버는 로그인에 **두 가지 형태의 200** 을 돌려준다. + * 화면이 한 형태만 가정하면 인증번호 요구 응답에서 영문 오류가 노출되고 로그인이 + * 불가능해진다(공개 #133). + * + * 검증 대상: + * 1. 1단계·2단계 블록의 `if` 가 상보적이다 (동시 노출 금지) + * 2. 인증번호 입력이 controlled — `value` + `onChange` 쌍, `events:{}` 래퍼 없음 + * 3. `login` 과 `loginTwoFactor` 가 상호배타 `if` 를 갖는다 + * 4. 재발송 onSuccess 가 새 challenge 로 교체하고 입력값을 비운다 + * 5. `login` 의 성공 후속 액션이 challenge 응답에서는 실행되지 않는다 + * 6. 로그인 화면 진입 시 2단계 상태가 초기화된다 + * + * @since engine-v1.65.0 + */ + +import { describe, it, expect } from 'vitest'; + +import loginForm from '../../layouts/partials/auth/_login_form.json'; +import loginPage from '../../layouts/auth/login.json'; + +type Action = { + event?: string; + type?: string; + handler?: string; + target?: string; + if?: string; + params?: Record; + actions?: Action[]; + onSuccess?: Action[]; + onError?: Action[]; +}; + +type Node = { + id?: string; + name?: string; + if?: string; + props?: Record; + children?: Node[] | string; + text?: string; + events?: Record; + actions?: Action[]; +}; + +/** 트리를 평탄화한다. */ +function flatten(node: Node | Node[] | undefined): Node[] { + if (!node) return []; + if (Array.isArray(node)) return node.flatMap(flatten); + const children = Array.isArray(node.children) ? node.children.flatMap(flatten) : []; + return [node, ...children]; +} + +/** 시퀀스를 평탄화해 모든 액션을 모은다. */ +function flattenActions(actions: Action[] | undefined): Action[] { + if (!actions) return []; + return actions.flatMap((a) => [ + a, + ...flattenActions(a.actions), + ...flattenActions(a.onSuccess), + ...flattenActions(a.onError), + ]); +} + +const nodes = flatten(loginForm as unknown as Node); +const allActions = flattenActions((loginForm as unknown as Node).actions); + +describe('sirsoft-basic 로그인 2단계 인증 단계', () => { + /** + * @scenario step=code, response=challenge, action=submit + * + * @effects code_step_rendered_on_challenge, credential_step_hidden_on_challenge + */ + it('1단계 입력과 2단계 블록의 조건이 상보적이다', () => { + // 두 블록이 같은 조건을 쓰면 인증번호 단계에서 이메일·비밀번호가 함께 보인다. + const stepOne = nodes.filter((n) => n.if === '{{!_global.twoFactor?.required}}'); + const stepTwo = nodes.filter((n) => n.if === '{{_global.twoFactor?.required}}'); + + expect(stepOne.length).toBeGreaterThanOrEqual(3); + expect(stepTwo.length).toBe(1); + }); + + /** + * @scenario step=code, response=challenge, action=submit + * + * @effects code_input_is_controlled_without_events_wrapper + */ + it('인증번호 입력이 controlled 이고 events 래퍼를 쓰지 않는다', () => { + const codeInput = nodes.find((n) => n.props?.name === 'two_factor_code'); + + expect(codeInput).toBeDefined(); + expect(codeInput?.props?.value).toBe("{{_global.twoFactor?.code ?? ''}}"); + expect(codeInput?.props?.autoComplete).toBe('one-time-code'); + expect(codeInput?.props?.inputMode).toBe('numeric'); + // 값의 소유자가 상태여야 재발송 시 입력값을 비울 수 있다. + expect(codeInput?.events).toBeUndefined(); + + const onChange = codeInput?.actions?.find((a) => a.event === 'onChange'); + expect(onChange?.handler).toBe('setState'); + expect(onChange?.params?.['twoFactor.code']).toBe('{{$event.target.value}}'); + }); + + /** + * @scenario step=code, response=ok, action=enter_key + * + * @effects login_and_verify_are_mutually_exclusive + */ + it('login 과 loginTwoFactor 가 상호배타 조건을 갖는다', () => { + const login = allActions.find((a) => a.handler === 'login'); + const verify = allActions.find((a) => a.handler === 'loginTwoFactor'); + + expect(login?.if).toBe('{{!_global.twoFactor?.required}}'); + expect(verify?.if).toBe('{{_global.twoFactor?.required}}'); + // 조건이 빠지면 인증번호 단계에서 Enter 를 누를 때 새 challenge 가 발급된다. + expect(login?.target).toBe('user'); + expect(verify?.target).toBe('user'); + }); + + /** + * @scenario step=code, response=ok, action=submit + * + * @effects no_raw_typeerror_text + */ + it('loginTwoFactor 가 challenge_id 와 code 를 함께 보낸다', () => { + const verify = allActions.find((a) => a.handler === 'loginTwoFactor'); + + expect(verify?.params?.body?.challenge_id).toBe('{{_global.twoFactor?.challenge_id}}'); + expect(verify?.params?.body?.code).toBe('{{_global.twoFactor?.code}}'); + }); + + /** + * @scenario step=credentials, response=challenge, action=submit + * + * @effects credential_step_hidden_on_challenge + */ + it('login 의 성공 후속 액션이 challenge 응답에서는 실행되지 않는다', () => { + const login = allActions.find((a) => a.handler === 'login'); + const onSuccess = login?.onSuccess ?? []; + + expect(onSuccess.length).toBeGreaterThan(0); + for (const action of onSuccess) { + // 조건이 없는 후속 액션이 하나라도 남으면 인증 전에 홈으로 이동하거나 + // 빈 사용자 정보가 전역 상태에 실린다. + expect(action.if, `후속 액션 ${action.handler} 에 조건이 없습니다`).toBeDefined(); + } + + const challengeBranch = onSuccess.find((a) => a.if === '{{response.two_factor_required}}'); + expect(challengeBranch?.params?.twoFactor?.challenge_id).toBe('{{response.challenge_id}}'); + // 같은 시퀀스 안에서는 _global 이 아직 갱신 전이므로 응답 값만 읽어야 한다. + expect(JSON.stringify(challengeBranch?.params)).not.toContain('_global.twoFactor'); + }); + + /** + * @scenario step=code, response=ok, action=resend + * + * @effects resend_clears_code_and_replaces_challenge + */ + it('재발송 성공 시 새 challenge 로 교체하고 입력값을 비운다', () => { + const resend = allActions.find((a) => a.handler === 'loginTwoFactorResend'); + expect(resend).toBeUndefined(); + + // 재발송은 버튼 노드의 액션에 있다 — 폼 submit 시퀀스가 아니다. + const resendButton = nodes.find((n) => + flattenActions(n.actions).some((a) => a.handler === 'loginTwoFactorResend') + ); + const resendAction = flattenActions(resendButton?.actions).find( + (a) => a.handler === 'loginTwoFactorResend' + ); + + expect(resendAction?.target).toBe('user'); + expect(resendAction?.params?.body?.challenge_id).toBe('{{_global.twoFactor?.challenge_id}}'); + + const success = resendAction?.onSuccess?.[0]; + expect(success?.params?.twoFactor?.challenge_id).toBe('{{response.challenge_id}}'); + // 이전 코드가 남아 있으면 새 코드를 받았는데 옛 코드로 제출된다. + expect(success?.params?.twoFactor?.code).toBe(''); + expect(success?.params?.twoFactor?.resent).toBe(true); + }); + + /** + * @scenario step=credentials, response=ok, action=restart + * + * @effects init_actions_reset_two_factor_state, restart_resets_to_credential_step + */ + it('로그인 화면 진입 시 2단계 상태를 초기화한다', () => { + // 전역 상태라 화면을 떠나도 남는다 — 리셋이 없으면 다시 들어왔을 때 1단계가 보이지 않는다. + const init = (loginPage as any).init_actions as Action[]; + const reset = init.find( + (a) => a.handler === 'setState' && a.params?.target === 'global' && 'twoFactor' in (a.params ?? {}) + ); + + expect(reset).toBeDefined(); + expect(reset?.params?.twoFactor).toBeNull(); + expect(reset?.if).toBeUndefined(); + }); + + /** + * @scenario step=credentials, response=423, action=submit + * + * @effects locked_until_rendered + */ + it('계정 잠금 해제 시각을 렌더하는 지점이 있다', () => { + const lockedUntil = nodes.find((n) => n.if === '{{_global.loginErrors?.locked_until}}'); + const permanent = nodes.find((n) => n.if === '{{_global.loginErrors?.permanent === true}}'); + + expect(lockedUntil?.text).toContain('$t:auth.locked_until'); + expect(permanent?.text).toBe('$t:auth.locked_permanent'); + }); +}); diff --git a/templates/_bundled/sirsoft-basic/docs/layouts.md b/templates/_bundled/sirsoft-basic/docs/layouts.md index f30f4c8d..2cc596ec 100644 --- a/templates/_bundled/sirsoft-basic/docs/layouts.md +++ b/templates/_bundled/sirsoft-basic/docs/layouts.md @@ -572,6 +572,30 @@ slots.content: - `navigate` — 성공 후 홈/대시보드로 이동 - `setState` — 폼 에러, 로딩 상태 +**2단계 인증(인증번호) 단계** + +관리자가 보안 설정에서 2단계 인증을 켠 사이트에서는 로그인 응답이 두 형태로 갈립니다 — +정상 로그인과 인증번호 요구(challenge)입니다. `_login_form.json` 은 그 둘을 **같은 카드 안에서** +단계 전환으로 처리합니다. + +- 1단계(이메일·비밀번호) 블록은 `if: "{{!_global.twoFactor?.required}}"`, 2단계(인증번호) 블록은 + 그 부정형을 답니다. 두 `if` 는 언제나 상보여야 합니다 — 한쪽만 고치면 두 단계가 겹쳐 보이거나 + 둘 다 사라집니다. +- 제출 시퀀스의 `login` 과 `loginTwoFactor` 도 같은 쌍으로 상호배타입니다. `loginTwoFactor` 쪽 + `if` 가 빠지면 인증번호 단계에서 Enter 를 눌렀을 때 새 challenge 가 발급되어 흐름이 끊깁니다. +- 인증번호 입력은 controlled 입니다(`value` + `onChange` 의 `setState` 쌍). `events: {}` 래퍼는 + 쓰지 않습니다. +- 화면 진입 시 `auth/login.json` 의 `init_actions` 첫 액션이 `twoFactor` 를 `null` 로 되돌립니다. + 전역 상태라 화면을 떠나도 남기 때문에, 이 리셋이 없으면 다시 들어왔을 때 1단계가 보이지 않습니다. +- 만료 시각은 정적 표기입니다(`| datetime`). 카운트다운을 쓰지 않습니다 — `startInterval` 은 등록 + 시점 컨텍스트를 고정하고 정지 호출처가 없어 화면을 떠난 뒤에도 남습니다. + +**금지 — 같은 시퀀스·onSuccess 안에서 방금 저장한 상태를 다시 읽지 않습니다** + +`setState target:global` 직후 형제 액션의 `if` 나 값으로 `_global.*` 를 재독하면 갱신 이전 값을 +읽습니다(시퀀스 처리기는 `_local` 만 갱신합니다). 그 자리에서는 `{{response.*}}` 만 씁니다. +오류도 경고도 남지 않고 분기만 조용히 어긋나므로 화면을 보지 않으면 드러나지 않습니다. + --- #### 게시판 패턴 diff --git a/templates/_bundled/sirsoft-basic/lang/partial/en/auth.json b/templates/_bundled/sirsoft-basic/lang/partial/en/auth.json index 9b4687d0..354f5bec 100644 --- a/templates/_bundled/sirsoft-basic/lang/partial/en/auth.json +++ b/templates/_bundled/sirsoft-basic/lang/partial/en/auth.json @@ -150,5 +150,18 @@ "minTypes": "At least {{count}} types (uppercase, lowercase, number, special)" } }, + "two_factor": { + "sent": "We sent a verification code. Enter it to finish signing in.", + "resent": "We sent a new verification code. Enter the new code.", + "code_label": "Verification code", + "code_placeholder": "Enter the code you received", + "valid_until": "Valid until {{until}}", + "verify": "Verify code", + "verifying": "Verifying...", + "resend": "Resend code", + "restart": "Start over" + }, + "locked_until": "Unlocks at {{until}}", + "locked_permanent": "Contact an administrator to unlock your account.", "session_expired_toast": "Your session has expired. Please log in again." } \ No newline at end of file diff --git a/templates/_bundled/sirsoft-basic/lang/partial/ko/auth.json b/templates/_bundled/sirsoft-basic/lang/partial/ko/auth.json index e27eb8e2..badf5889 100644 --- a/templates/_bundled/sirsoft-basic/lang/partial/ko/auth.json +++ b/templates/_bundled/sirsoft-basic/lang/partial/ko/auth.json @@ -150,5 +150,18 @@ "minTypes": "{{count}}가지 이상 조합 (대/소문자, 숫자, 특수문자)" } }, + "two_factor": { + "sent": "인증번호를 보냈습니다. 받은 번호를 입력해 로그인을 완료해주세요.", + "resent": "인증번호를 다시 보냈습니다. 새로 받은 번호를 입력해주세요.", + "code_label": "인증번호", + "code_placeholder": "받은 인증번호를 입력하세요", + "valid_until": "유효시간 {{until}} 까지", + "verify": "인증번호 확인", + "verifying": "확인 중...", + "resend": "인증번호 다시 받기", + "restart": "처음부터" + }, + "locked_until": "해제 예정: {{until}}", + "locked_permanent": "관리자에게 문의해 잠금을 해제해주세요.", "session_expired_toast": "세션이 만료되었습니다. 다시 로그인해 주세요." } \ No newline at end of file diff --git a/templates/_bundled/sirsoft-basic/layouts/auth/login.json b/templates/_bundled/sirsoft-basic/layouts/auth/login.json index 10a6400d..026acbca 100644 --- a/templates/_bundled/sirsoft-basic/layouts/auth/login.json +++ b/templates/_bundled/sirsoft-basic/layouts/auth/login.json @@ -7,6 +7,11 @@ "guest_only": true }, "init_actions": [ + { + "_comment": "2단계 인증 단계 상태는 전역이라 화면을 떠나도 남는다 — 진입할 때마다 1단계로 되돌린다.", + "handler": "setState", + "params": { "target": "global", "twoFactor": null } + }, { "if": "{{query?.reason === 'session_expired'}}", "handler": "toast", diff --git a/templates/_bundled/sirsoft-basic/layouts/partials/auth/_login_form.json b/templates/_bundled/sirsoft-basic/layouts/partials/auth/_login_form.json index 95eb1353..6eb15234 100644 --- a/templates/_bundled/sirsoft-basic/layouts/partials/auth/_login_form.json +++ b/templates/_bundled/sirsoft-basic/layouts/partials/auth/_login_form.json @@ -1,7 +1,7 @@ { "meta": { "is_partial": true, - "description": "로그인 폼 (이메일/비밀번호)" + "description": "로그인 폼 (1단계 이메일/비밀번호 → 2단계 인증번호)" }, "type": "basic", "name": "Form", @@ -21,13 +21,29 @@ "name": "P", "props": { "className": "text-sm text-red-600 dark:text-red-400" }, "text": "{{_global.loginError}}" + }, + { + "comment": "계정 잠금 해제 시각 — 언제 다시 시도할 수 있는지 알려주지 않으면 사용자는 계속 눌러 보게 된다", + "type": "basic", + "name": "P", + "if": "{{_global.loginErrors?.locked_until}}", + "props": { "className": "mt-1 text-sm text-red-600 dark:text-red-400" }, + "text": "$t:auth.locked_until|until={{_global.loginErrors?.locked_until | datetime}}" + }, + { + "type": "basic", + "name": "P", + "if": "{{_global.loginErrors?.permanent === true}}", + "props": { "className": "mt-1 text-sm text-red-600 dark:text-red-400" }, + "text": "$t:auth.locked_permanent" } ] }, { - "comment": "이메일 입력 필드", + "comment": "이메일 입력 필드 (1단계)", "type": "basic", "name": "Div", + "if": "{{!_global.twoFactor?.required}}", "children": [ { "type": "basic", @@ -58,9 +74,10 @@ ] }, { - "comment": "비밀번호 입력 필드", + "comment": "비밀번호 입력 필드 (1단계)", "type": "basic", "name": "Div", + "if": "{{!_global.twoFactor?.required}}", "children": [ { "type": "basic", @@ -84,8 +101,10 @@ ] }, { + "comment": "로그인 버튼 (1단계)", "type": "basic", "name": "Button", + "if": "{{!_global.twoFactor?.required}}", "props": { "type": "submit", "className": "w-full py-3 mt-12 bg-gray-900 dark:bg-white text-white dark:text-gray-900 rounded-lg font-medium hover:bg-gray-800 dark:hover:bg-gray-100 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2", @@ -112,6 +131,223 @@ "text": "$t:auth.login_processing" } ] + }, + { + "comment": "2단계 인증 — 비밀번호 확인만 통과한 상태다. 인증번호를 확인해야 로그인이 완료된다.", + "type": "basic", + "name": "Div", + "if": "{{_global.twoFactor?.required}}", + "props": { "className": "space-y-6" }, + "children": [ + { + "type": "basic", + "name": "Div", + "props": { + "className": "p-4 rounded-lg bg-blue-50 dark:bg-blue-900/20 border border-blue-200 dark:border-blue-800", + "role": "status", + "aria-live": "polite" + }, + "children": [ + { + "type": "basic", + "name": "P", + "if": "{{!_global.twoFactor?.resent}}", + "props": { "className": "text-sm text-blue-700 dark:text-blue-300" }, + "text": "$t:auth.two_factor.sent" + }, + { + "type": "basic", + "name": "P", + "if": "{{_global.twoFactor?.resent}}", + "props": { "className": "text-sm text-blue-700 dark:text-blue-300" }, + "text": "$t:auth.two_factor.resent" + } + ] + }, + { + "comment": "인증번호 오류", + "type": "basic", + "name": "Div", + "if": "{{_global.twoFactor?.error}}", + "props": { + "className": "p-4 rounded-lg bg-red-50 dark:bg-red-900/20 border border-red-200 dark:border-red-800", + "role": "alert" + }, + "children": [ + { + "type": "basic", + "name": "P", + "props": { "className": "text-sm text-red-600 dark:text-red-400" }, + "text": "{{_global.twoFactor?.error ?? ''}}" + } + ] + }, + { + "type": "basic", + "name": "Div", + "children": [ + { + "type": "basic", + "name": "Label", + "props": { "className": "block text-sm font-medium text-gray-700 dark:text-gray-300 mb-3" }, + "text": "$t:auth.two_factor.code_label" + }, + { + "comment": "자동바인딩을 쓰지 않는다 — 재발송 시 입력값을 비워야 하므로 상태가 값을 소유한다", + "type": "basic", + "name": "Input", + "props": { + "type": "text", + "name": "two_factor_code", + "value": "{{_global.twoFactor?.code ?? ''}}", + "inputMode": "numeric", + "autoComplete": "one-time-code", + "maxLength": 10, + "placeholder": "$t:auth.two_factor.code_placeholder", + "className": "w-full px-4 py-3 text-center text-xl tracking-widest font-mono border border-gray-300 dark:border-gray-600 rounded-lg bg-white dark:bg-gray-700 text-gray-900 dark:text-white focus:ring-2 focus:ring-blue-500 focus:border-blue-500 disabled:opacity-50 disabled:cursor-not-allowed transition-colors duration-200", + "disabled": "{{_global.isLoggingIn}}" + }, + "actions": [ + { + "event": "onChange", + "handler": "setState", + "params": { + "target": "global", + "twoFactor.code": "{{$event.target.value}}", + "twoFactor.error": null + } + } + ] + }, + { + "comment": "유효시각 정적 표기 — 남은 시간 카운트다운은 SPA 이탈 후에도 타이머가 남아 쓰지 않는다", + "type": "basic", + "name": "P", + "if": "{{_global.twoFactor?.expires_at}}", + "props": { "className": "mt-2 text-xs text-gray-500 dark:text-gray-400" }, + "text": "$t:auth.two_factor.valid_until|until={{_global.twoFactor?.expires_at | datetime}}" + } + ] + }, + { + "comment": "인증번호 확인 — submit 이라 Enter 키로도 제출된다", + "type": "basic", + "name": "Button", + "props": { + "type": "submit", + "className": "w-full py-3 bg-gray-900 dark:bg-white text-white dark:text-gray-900 rounded-lg font-medium hover:bg-gray-800 dark:hover:bg-gray-100 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2", + "disabled": "{{!_global.twoFactor?.code || _global.twoFactor.code.length < 4 || _global.isLoggingIn}}" + }, + "children": [ + { + "type": "basic", + "name": "Div", + "if": "{{_global.isLoggingIn}}", + "props": { "className": "w-5 h-5 border-2 border-white/30 border-t-white rounded-full animate-spin" } + }, + { + "type": "basic", + "name": "Span", + "if": "{{!_global.isLoggingIn}}", + "text": "$t:auth.two_factor.verify" + }, + { + "type": "basic", + "name": "Span", + "if": "{{_global.isLoggingIn}}", + "text": "$t:auth.two_factor.verifying" + } + ] + }, + { + "type": "basic", + "name": "Div", + "props": { "className": "flex flex-col sm:flex-row gap-2" }, + "children": [ + { + "type": "basic", + "name": "Button", + "props": { + "type": "button", + "className": "flex-1 py-3 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg font-medium hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer", + "disabled": "{{_global.twoFactor?.resending || _global.isLoggingIn}}" + }, + "text": "$t:auth.two_factor.resend", + "actions": [ + { + "type": "click", + "handler": "sequence", + "actions": [ + { + "handler": "setState", + "params": { "target": "global", "twoFactor.resending": true, "twoFactor.error": null } + }, + { + "handler": "loginTwoFactorResend", + "target": "user", + "params": { + "body": { "challenge_id": "{{_global.twoFactor?.challenge_id}}" } + }, + "onSuccess": [ + { + "_comment": "같은 시퀀스 안에서는 _global 이 아직 갱신 전이므로 응답 값만 읽는다.", + "handler": "setState", + "params": { + "target": "global", + "twoFactor": { + "required": true, + "challenge_id": "{{response.challenge_id}}", + "provider_id": "{{response.provider_id}}", + "expires_at": "{{response.expires_at}}", + "code": "", + "error": null, + "verifying": false, + "resending": false, + "resent": true + } + } + } + ], + "onError": [ + { + "handler": "setState", + "params": { + "target": "global", + "twoFactor.resending": false, + "twoFactor.error": "{{error.message}}" + } + } + ] + } + ] + } + ] + }, + { + "type": "basic", + "name": "Button", + "props": { + "type": "button", + "className": "flex-1 py-3 border border-gray-300 dark:border-gray-600 text-gray-700 dark:text-gray-300 rounded-lg font-medium hover:bg-gray-50 dark:hover:bg-gray-700 transition-colors disabled:opacity-50 disabled:cursor-not-allowed cursor-pointer", + "disabled": "{{_global.isLoggingIn}}" + }, + "text": "$t:auth.two_factor.restart", + "actions": [ + { + "type": "click", + "handler": "setState", + "params": { + "target": "global", + "twoFactor": null, + "loginError": null, + "loginErrors": null + } + } + ] + } + ] + } + ] } ], "actions": [ @@ -136,8 +372,10 @@ } }, { + "_comment": "1·2단계는 상호배타다. if 는 시퀀스 시작 시점 스냅샷으로 평가되므로 한 제출에 정확히 하나만 실행된다 — 이 if 가 빠지면 인증번호 단계에서 Enter 를 누를 때 새 challenge 가 발급되어 흐름이 깨진다.", "handler": "login", "target": "user", + "if": "{{!_global.twoFactor?.required}}", "params": { "body": { "email": "{{form.email}}", @@ -145,17 +383,67 @@ } }, "onSuccess": [ - { "handler": "setState", "params": { "target": "global", "currentUser": "{{response.user}}" } }, - { "handler": "setState", "params": { "target": "global", "isLoggingIn": false } }, + { + "_comment": "2단계 인증이 켜진 사이트는 아직 로그인이 끝나지 않았다 — 토큰도 사용자도 없다.", + "handler": "setState", + "if": "{{response.two_factor_required}}", + "params": { + "target": "global", + "twoFactor": { + "required": true, + "challenge_id": "{{response.challenge_id}}", + "provider_id": "{{response.provider_id}}", + "expires_at": "{{response.expires_at}}", + "code": "", + "error": null, + "verifying": false, + "resending": false, + "resent": false + }, + "isLoggingIn": false + } + }, + { "handler": "setState", "if": "{{!response.two_factor_required}}", "params": { "target": "global", "currentUser": "{{response.user}}" } }, + { "handler": "setState", "if": "{{!response.two_factor_required}}", "params": { "target": "global", "isLoggingIn": false } }, { "_comment": "로그인 직전에 비회원으로 발급받은 주문 조회 토큰은 회원 컨텍스트에 무효 — 잔존 시 동일 브라우저로 회원/비회원 페이지 동시 열람 가능. sessionStorage 3개 키 (token/orderNumber/expiresAt) 와 _global.guestOrderToken 을 한 번에 정리하는 모듈 커스텀 핸들러 사용.", - "handler": "clearGuestOrderToken" + "handler": "clearGuestOrderToken", + "if": "{{!response.two_factor_required}}" }, + { "handler": "toast", "if": "{{!response.two_factor_required}}", "params": { "type": "success", "message": "$t:auth.login_success" } }, + { "handler": "navigate", "if": "{{!response.two_factor_required}}", "params": { "path": "{{query.redirect ?? '/'}}" } } + ], + "onError": [ + { "handler": "setState", "params": { "target": "global", "isLoggingIn": false, "loginError": "{{error.message}}", "loginErrors": "{{error.errors}}" } } + ] + }, + { + "handler": "loginTwoFactor", + "target": "user", + "if": "{{_global.twoFactor?.required}}", + "params": { + "body": { + "challenge_id": "{{_global.twoFactor?.challenge_id}}", + "code": "{{_global.twoFactor?.code}}" + } + }, + "onSuccess": [ + { "handler": "setState", "params": { "target": "global", "currentUser": "{{response.user}}", "isLoggingIn": false, "twoFactor": null } }, + { "handler": "clearGuestOrderToken" }, { "handler": "toast", "params": { "type": "success", "message": "$t:auth.login_success" } }, { "handler": "navigate", "params": { "path": "{{query.redirect ?? '/'}}" } } ], "onError": [ - { "handler": "setState", "params": { "target": "global", "isLoggingIn": false, "loginError": "{{error.message}}", "loginErrors": "{{error.errors}}" } } + { + "_comment": "423 잠금은 1단계와 같은 문구 규칙을 따르도록 loginErrors 도 함께 싣는다.", + "handler": "setState", + "params": { + "target": "global", + "isLoggingIn": false, + "twoFactor.error": "{{error.message}}", + "loginErrors": "{{error.errors}}" + } + } ] } ] diff --git a/templates/_bundled/sirsoft-basic/package-lock.json b/templates/_bundled/sirsoft-basic/package-lock.json index 63f94c1a..5704373e 100644 --- a/templates/_bundled/sirsoft-basic/package-lock.json +++ b/templates/_bundled/sirsoft-basic/package-lock.json @@ -1,12 +1,12 @@ { "name": "sirsoft-basic", - "version": "1.1.3", + "version": "1.1.4", "lockfileVersion": 3, "requires": true, "packages": { "": { "name": "sirsoft-basic", - "version": "1.1.3", + "version": "1.1.4", "license": "MIT", "dependencies": { "@dnd-kit/core": "^6.3.1", diff --git a/templates/_bundled/sirsoft-basic/package.json b/templates/_bundled/sirsoft-basic/package.json index 786b3832..e69b9cd1 100644 --- a/templates/_bundled/sirsoft-basic/package.json +++ b/templates/_bundled/sirsoft-basic/package.json @@ -1,6 +1,6 @@ { "name": "sirsoft-basic", - "version": "1.1.3", + "version": "1.1.4", "description": "Gnuboard7 Basic User Template Components - Nexibase Style", "type": "module", "main": "dist/components.js", diff --git a/templates/_bundled/sirsoft-basic/src/__tests__/layouts/login.test.tsx b/templates/_bundled/sirsoft-basic/src/__tests__/layouts/login.test.tsx index f4744cbc..fa73484a 100644 --- a/templates/_bundled/sirsoft-basic/src/__tests__/layouts/login.test.tsx +++ b/templates/_bundled/sirsoft-basic/src/__tests__/layouts/login.test.tsx @@ -166,10 +166,12 @@ const loginFormFixture = { ], }, // 이메일 입력 필드 + // 2단계 인증이 요구되면 자격 증명 입력은 숨는다 — 실제 `_login_form.json` 과 같은 조건. { id: 'email-field', type: 'basic', name: 'Div', + if: '{{!_global.twoFactor?.required}}', props: { 'data-testid': 'email-field' }, children: [ { @@ -197,6 +199,7 @@ const loginFormFixture = { id: 'password-field', type: 'basic', name: 'Div', + if: '{{!_global.twoFactor?.required}}', props: { 'data-testid': 'password-field' }, children: [ { @@ -224,6 +227,7 @@ const loginFormFixture = { id: 'submit-button', type: 'basic', name: 'Button', + if: '{{!_global.twoFactor?.required}}', props: { type: 'submit', className: 'w-full py-3 mt-12 bg-gray-900 dark:bg-white text-white dark:text-gray-900 rounded-lg font-medium hover:bg-gray-800 dark:hover:bg-gray-100 transition-colors disabled:opacity-50 disabled:cursor-not-allowed flex items-center justify-center gap-2', @@ -457,4 +461,48 @@ describe('로그인 폼 레이아웃 렌더링 (Issue #72)', () => { testUtils.cleanup(); }); }); + + // 2단계 인증이 켜진 사이트에서는 로그인 응답이 인증번호 요구로 갈린다. 그때 자격 증명 입력이 + // 남아 있으면 두 단계가 겹쳐 보이고, 사용자가 이메일·비밀번호를 다시 제출해 새 challenge 를 + // 발급받는다. 이 fixture 의 `if` 는 실제 `_login_form.json` 과 같은 조건이므로, 한쪽이 바뀌면 + // 이 케이스가 red 가 된다. + describe('2단계 인증 단계 전환', () => { + it('twoFactor 가 없으면 자격 증명 입력이 보인다', async () => { + // Given + const testUtils = createLayoutTest(loginFormFixture, { + componentRegistry: registry, + initialState: { _global: {} }, + }); + + // When + await testUtils.render(); + + // Then + expect(screen.getByTestId('email-field')).toBeInTheDocument(); + expect(screen.getByTestId('password-field')).toBeInTheDocument(); + expect(screen.getByTestId('login-submit-btn')).toBeInTheDocument(); + + testUtils.cleanup(); + }); + + it('인증번호가 요구되면 자격 증명 입력과 제출 버튼이 사라진다', async () => { + // Given + const testUtils = createLayoutTest(loginFormFixture, { + componentRegistry: registry, + initialState: { + _global: { twoFactor: { required: true, challenge_id: 'c-1', code: '' } }, + }, + }); + + // When + await testUtils.render(); + + // Then + expect(screen.queryByTestId('email-field')).not.toBeInTheDocument(); + expect(screen.queryByTestId('password-field')).not.toBeInTheDocument(); + expect(screen.queryByTestId('login-submit-btn')).not.toBeInTheDocument(); + + testUtils.cleanup(); + }); + }); }); diff --git a/templates/_bundled/sirsoft-basic/template.json b/templates/_bundled/sirsoft-basic/template.json index e157030c..4bacbf5c 100644 --- a/templates/_bundled/sirsoft-basic/template.json +++ b/templates/_bundled/sirsoft-basic/template.json @@ -5,7 +5,7 @@ "ko": "Basic", "en": "Basic" }, - "version": "1.1.3", + "version": "1.1.4", "license": "MIT", "description": { "ko": "그누보드7 기본 사용자 템플릿", @@ -22,7 +22,7 @@ "url": "https://sirsoft.com" }, "release_date": "2026-01-07", - "g7_version": ">=7.0.10", + "g7_version": ">=7.0.11", "dependencies": { "modules": { "sirsoft-board": ">=1.0.0", diff --git a/templates/_bundled/sirsoft-basic/tests/scenarios/login-two-factor-step.yaml b/templates/_bundled/sirsoft-basic/tests/scenarios/login-two-factor-step.yaml new file mode 100644 index 00000000..e13ac504 --- /dev/null +++ b/templates/_bundled/sirsoft-basic/tests/scenarios/login-two-factor-step.yaml @@ -0,0 +1,45 @@ +# audit:allow test-scenario-coverage reason: response 축(ok/challenge/401/403/423/429/503/network)은 서버 응답 +# 종류를 열거한 것이라 레이아웃 구조 테스트가 케이스별로 나눠 단언할 실체가 아니다 — 구조 테스트는 화면이 +# 그 응답들을 받을 수 있는 형태인지(상보 조건·controlled 입력·상호배타 액션)를 본다. 실제 회귀 가드는 +# effects 이며 전부 @effects 로 귀속되어 있다(미검증 0건). 응답별 화면 실측은 Playwright spec 이 담당한다. + +feature: 로그인 화면 2단계 인증 단계 (sirsoft-basic) + +description: | + 2단계 인증이 켜진 사이트에서 로그인 화면은 비밀번호 단계와 인증번호 단계를 같은 카드 안에서 + 전환한다. 서버가 두 가지 형태의 200 을 돌려주므로, 화면이 한 형태만 가정하면 영문 오류가 + 노출되고 로그인이 불가능해진다(공개 #133). + + 핵심 동작: + - 1단계 블록과 2단계 블록의 조건이 상보적이다 (동시 노출 금지). + - 제출 시퀀스의 login 과 loginTwoFactor 가 상호배타 조건을 갖는다. 조건이 빠지면 + 인증번호 단계에서 Enter 를 누를 때 새 challenge 가 발급되어 흐름이 깨진다. + - 인증번호 입력은 상태가 값을 소유한다 (재발송 시 입력을 비워야 하므로). + - 인증 단계 상태는 전역이라 화면 진입 시 초기화한다. + +axes: + step: [credentials, code] + response: [ok, challenge, 401, 423, 429, 503, network] + action: [submit, resend, restart, enter_key] + +exclusions: + - { step: credentials, action: resend, reason: "재발송 버튼은 인증번호 단계에만 있다" } + - { step: credentials, action: restart, reason: "동일" } + - { step: code, response: challenge, reason: "challenge 는 비밀번호 단계의 응답이다" } + +effects: + - no_raw_typeerror_text + - code_step_rendered_on_challenge + - credential_step_hidden_on_challenge + - login_and_verify_are_mutually_exclusive + - code_input_is_controlled_without_events_wrapper + - resend_clears_code_and_replaces_challenge + - restart_resets_to_credential_step + - locked_until_rendered + - init_actions_reset_two_factor_state + - network_message_translated + +test_files: + - templates/_bundled/sirsoft-basic/__tests__/layouts/login-two-factor-step.test.tsx + - templates/_bundled/sirsoft-basic/__tests__/layouts/login-two-factor-render.test.tsx + - tests/Playwright/specs/auth/two-factor-login.spec.ts diff --git a/tests/Feature/Auth/LoginThrottleTest.php b/tests/Feature/Auth/LoginThrottleTest.php index 88161b2c..ecc28f33 100644 --- a/tests/Feature/Auth/LoginThrottleTest.php +++ b/tests/Feature/Auth/LoginThrottleTest.php @@ -127,7 +127,7 @@ class LoginThrottleTest extends TestCase /** * @test */ - public function login_attempt_enabled_가_OFF_이면_무제한_시도_허용된다(): void + public function login_attempt_enabled_가_off_이면_무제한_시도_허용된다(): void { $this->setSecuritySettings([ 'login_attempt_enabled' => false, @@ -190,7 +190,7 @@ class LoginThrottleTest extends TestCase /** * @test */ - public function 존재하지_않는_이메일은_DB에_카운트_저장되지_않는다(): void + public function 존재하지_않는_이메일은_db에_카운트_저장되지_않는다(): void { $response = $this->postJson('/api/auth/login', [ 'email' => 'ghost@example.com', @@ -202,6 +202,41 @@ class LoginThrottleTest extends TestCase $this->assertDatabaseMissing('users', ['email' => 'ghost@example.com']); } + /** + * @test + * + * @scenario two_factor=off, controller=user, delivery=sent + * + * @effects too_many_attempts_message_translated + */ + public function 분당_요청_상한을_넘으면_다국어_문구로_응답한다(): void + { + // 기본 응답은 영문 "Too Many Attempts." 이다 — 로그인 화면이 그 문구를 그대로 + // 노출하므로, 한국어 사이트에서 영문 원문이 오류 박스에 뜬다. + $limit = max(30, 3 * 6); + + for ($i = 0; $i <= $limit; $i++) { + $response = $this->postJson('/api/auth/login', [ + 'email' => 'ghost@example.com', + 'password' => 'wrong-password', + ]); + + if ($response->getStatusCode() === 429) { + break; + } + } + + $response->assertStatus(429); + $this->assertNotSame('Too Many Attempts.', $response->json('message')); + $this->assertStringNotContainsString(':seconds', (string) $response->json('message')); + $this->assertSame( + __('auth.too_many_attempts', ['seconds' => (int) $response->headers->get('Retry-After')]), + $response->json('message') + ); + // 재시도 시점 안내는 그대로 유지되어야 한다. + $this->assertNotNull($response->headers->get('Retry-After')); + } + private function setSecuritySettings(array $values): void { $existing = (array) config('g7_settings.core.security', []); diff --git a/tests/Feature/Auth/TwoFactorAuthTest.php b/tests/Feature/Auth/TwoFactorAuthTest.php index 3da1924e..8bbd936b 100644 --- a/tests/Feature/Auth/TwoFactorAuthTest.php +++ b/tests/Feature/Auth/TwoFactorAuthTest.php @@ -3,11 +3,14 @@ namespace Tests\Feature\Auth; use App\Enums\IdentityVerificationPurpose; +use App\Enums\IdentityVerificationStatus; use App\Enums\UserStatus; use App\Models\IdentityVerificationLog; +use App\Models\Role; use App\Models\User; use App\Services\IdentityVerificationService; use Database\Seeders\IdentityMessageDefinitionSeeder; +use Database\Seeders\RolePermissionSeeder; use Illuminate\Foundation\Testing\RefreshDatabase; use Illuminate\Support\Facades\Hash; use Illuminate\Support\Facades\Mail; @@ -71,6 +74,9 @@ class TwoFactorAuthTest extends TestCase ]); } + /** + * @scenario two_factor=off, controller=user + */ #[Test] public function login_issues_a_token_directly_when_two_factor_is_off(): void { @@ -82,6 +88,11 @@ class TwoFactorAuthTest extends TestCase $this->assertNotEmpty($response->json('data.token'), '2단계 인증이 꺼져 있으면 종전대로 바로 로그인되어야 합니다.'); } + /** + * @scenario two_factor=on, controller=user, delivery=sent + * + * @effects challenge_response_has_no_token, challenge_response_has_no_user + */ #[Test] public function login_withholds_the_token_when_two_factor_is_on(): void { @@ -102,6 +113,9 @@ class TwoFactorAuthTest extends TestCase $this->assertNotEmpty($response->json('data.challenge_id')); } + /** + * @scenario two_factor=on, controller=user, code=valid + */ #[Test] public function verifying_the_challenge_completes_the_login(): void { @@ -119,6 +133,9 @@ class TwoFactorAuthTest extends TestCase $this->assertSame('two-factor@test.com', $response->json('data.user.email')); } + /** + * @scenario two_factor=on, controller=user, code=invalid + */ #[Test] public function a_wrong_code_does_not_issue_a_token(): void { @@ -135,6 +152,9 @@ class TwoFactorAuthTest extends TestCase $this->assertNull($response->json('data.token')); } + /** + * @scenario two_factor=on, controller=user, code=invalid + */ #[Test] public function a_challenge_issued_for_another_purpose_cannot_be_used_to_log_in(): void { @@ -157,6 +177,11 @@ class TwoFactorAuthTest extends TestCase $this->assertNull($response->json('data.token')); } + /** + * @scenario two_factor=on, controller=user, delivery=failed + * + * @effects delivery_failure_503_with_reason + */ #[Test] public function login_fails_clearly_when_the_code_cannot_be_delivered(): void { @@ -169,13 +194,289 @@ class TwoFactorAuthTest extends TestCase $response = $this->login(); - $response->assertStatus(401); + // 자격 증명은 올바르다 — 401 로 답하면 사용자는 비밀번호를 의심하며 같은 실패를 + // 반복하고, 운영자는 메일 설정이 깨진 사실을 알 방법이 없다. + $response->assertStatus(503); + $this->assertSame(__('auth.two_factor_delivery_failed'), $response->json('message')); $this->assertNull( $response->json('data.token'), '발송 실패 시 2단계 인증을 건너뛰고 로그인시키면 보안 통제가 조용히 열립니다.' ); } + /** + * @scenario two_factor=on, controller=admin, actor=admin, delivery=sent + * + * @effects admin_login_returns_challenge_not_500 + */ + #[Test] + public function admin_login_returns_a_challenge_instead_of_failing(): void + { + $this->setTwoFactor(true); + $this->makeAdmin($this->user); + + $response = $this->postJson('/api/auth/admin/login', [ + 'email' => 'two-factor@test.com', + 'password' => 'Passw0rd!2fa', + ]); + + // 관리자 로그인이 2단계 인증에서 500 이 되면 설정을 되돌릴 수단까지 사라진다. + $response->assertStatus(200); + $this->assertTrue((bool) $response->json('data.two_factor_required')); + $this->assertNull($response->json('data.token')); + $this->assertNotEmpty($response->json('data.challenge_id')); + } + + /** + * @scenario two_factor=on, controller=admin, actor=admin, code=valid + * + * @effects admin_two_factor_issues_token_for_admin + */ + #[Test] + public function admin_two_factor_completes_the_login(): void + { + $this->setTwoFactor(true); + $this->makeAdmin($this->user); + + $challengeId = $this->postJson('/api/auth/admin/login', [ + 'email' => 'two-factor@test.com', + 'password' => 'Passw0rd!2fa', + ])->json('data.challenge_id'); + + $response = $this->postJson('/api/auth/admin/login/two-factor', [ + 'challenge_id' => $challengeId, + 'code' => $this->issuedCode($challengeId), + ]); + + $response->assertStatus(200); + $this->assertNotEmpty($response->json('data.token')); + } + + /** + * @scenario two_factor=on, controller=admin, actor=non_admin, code=valid + * + * @effects non_admin_two_factor_revokes_token + */ + #[Test] + public function a_non_admin_completing_admin_two_factor_keeps_no_token(): void + { + $this->setTwoFactor(true); + + $challengeId = $this->postJson('/api/auth/admin/login', [ + 'email' => 'two-factor@test.com', + 'password' => 'Passw0rd!2fa', + ])->json('data.challenge_id'); + + $response = $this->postJson('/api/auth/admin/login/two-factor', [ + 'challenge_id' => $challengeId, + 'code' => $this->issuedCode($challengeId), + ]); + + $response->assertStatus(403); + // 코드 확인 시점에 토큰이 이미 발급된다 — 회수하지 않으면 관리자가 아닌 사용자가 + // 응답만 403 을 받을 뿐 유효한 세션을 손에 쥔다. + $this->assertSame(0, $this->user->tokens()->count()); + } + + /** + * @scenario two_factor=off, controller=admin, actor=non_admin + * + * @effects non_admin_admin_login_revokes_token + */ + #[Test] + public function a_non_admin_rejected_at_admin_login_keeps_no_token(): void + { + $this->setTwoFactor(false); + + $response = $this->postJson('/api/auth/admin/login', [ + 'email' => 'two-factor@test.com', + 'password' => 'Passw0rd!2fa', + ]); + + $response->assertStatus(403); + $this->assertSame(0, $this->user->tokens()->count()); + } + + /** + * @scenario two_factor=on, controller=user, resend=active + * + * @effects resend_cancels_previous_challenge + */ + #[Test] + public function resending_cancels_the_previous_challenge_and_issues_a_new_one(): void + { + $this->setTwoFactor(true); + + $first = $this->login()->json('data.challenge_id'); + + $response = $this->postJson('/api/auth/login/two-factor/resend', [ + 'challenge_id' => $first, + ]); + + $response->assertStatus(200); + $second = $response->json('data.challenge_id'); + + $this->assertNotEmpty($second); + $this->assertNotSame($first, $second, '재발송이 같은 challenge 를 돌려주면 새 코드가 발송되지 않은 것입니다.'); + $this->assertNull($response->json('data.token')); + + // 앞선 코드가 계속 통하면 유효한 코드가 여러 개 살아 있어 대입 시도의 표적이 넓어진다. + $this->assertSame( + IdentityVerificationStatus::Cancelled->value, + IdentityVerificationLog::find($first)->status->value + ); + } + + /** + * @scenario two_factor=on, controller=user, resend=verified + * + * @effects resend_rejects_verified_challenge + */ + #[Test] + public function a_verified_challenge_cannot_be_resent(): void + { + $this->setTwoFactor(true); + + $challengeId = $this->login()->json('data.challenge_id'); + + $this->postJson('/api/auth/login/two-factor', [ + 'challenge_id' => $challengeId, + 'code' => $this->issuedCode($challengeId), + ])->assertStatus(200); + + $this->postJson('/api/auth/login/two-factor/resend', [ + 'challenge_id' => $challengeId, + ])->assertStatus(422); + } + + /** + * @scenario two_factor=on, controller=user, resend=expired + * + * @effects resend_rejects_expired_challenge + */ + #[Test] + public function an_expired_challenge_cannot_be_resent(): void + { + $this->setTwoFactor(true); + + $challengeId = $this->login()->json('data.challenge_id'); + + $log = IdentityVerificationLog::find($challengeId); + $log->expires_at = now()->subMinute(); + $log->save(); + + $this->postJson('/api/auth/login/two-factor/resend', [ + 'challenge_id' => $challengeId, + ])->assertStatus(422); + } + + /** + * @scenario two_factor=on, controller=user, resend=cancelled + * + * @effects resend_rejects_cancelled_challenge + */ + #[Test] + public function a_cancelled_challenge_cannot_be_resent(): void + { + $this->setTwoFactor(true); + + $challengeId = $this->login()->json('data.challenge_id'); + + app(IdentityVerificationService::class)->cancel($challengeId); + + $this->postJson('/api/auth/login/two-factor/resend', [ + 'challenge_id' => $challengeId, + ])->assertStatus(422); + } + + /** + * @scenario two_factor=on, controller=user, resend=active, lock_state=active + * + * @effects resend_refused_while_locked + */ + #[Test] + public function resending_is_refused_while_the_account_is_locked(): void + { + $this->setTwoFactor(true); + + $challengeId = $this->login()->json('data.challenge_id'); + + // challenge 를 받아 둔 뒤 잠긴 계정에는 새 코드를 보내지 않는다. + $this->user->forceFill(['locked_until' => now()->addMinutes(10)])->save(); + + $this->postJson('/api/auth/login/two-factor/resend', [ + 'challenge_id' => $challengeId, + ])->assertStatus(423); + } + + /** + * @scenario two_factor=on, controller=admin, actor=admin, resend=active + * + * @effects admin_resend_returns_new_challenge + */ + #[Test] + public function an_admin_can_resend_through_the_admin_endpoint(): void + { + $this->setTwoFactor(true); + $this->makeAdmin($this->user); + + $challengeId = $this->postJson('/api/auth/admin/login', [ + 'email' => 'two-factor@test.com', + 'password' => 'Passw0rd!2fa', + ])->json('data.challenge_id'); + + $response = $this->postJson('/api/auth/admin/login/two-factor/resend', [ + 'challenge_id' => $challengeId, + ]); + + $response->assertStatus(200); + $this->assertNotEmpty($response->json('data.challenge_id')); + $this->assertNotSame($challengeId, $response->json('data.challenge_id')); + $this->assertNull($response->json('data.token')); + // 해석된 사용자는 관리자 등급 판정에만 쓰고 응답에는 실지 않는다. + $this->assertNull($response->json('data.user')); + } + + /** + * @scenario two_factor=on, controller=admin, actor=non_admin, resend=active + * + * @effects admin_resend_refuses_non_admin + */ + #[Test] + public function a_non_admin_cannot_resend_through_the_admin_endpoint(): void + { + $this->setTwoFactor(true); + + $challengeId = $this->postJson('/api/auth/admin/login', [ + 'email' => 'two-factor@test.com', + 'password' => 'Passw0rd!2fa', + ])->json('data.challenge_id'); + + // 완료할 수 없는 상대에게 새 인증번호를 계속 보내지 않는다. + $this->postJson('/api/auth/admin/login/two-factor/resend', [ + 'challenge_id' => $challengeId, + ])->assertStatus(403); + + $this->assertSame(0, $this->user->tokens()->count()); + } + + /** + * 사용자에게 admin 역할을 부여합니다. + * + * @param User $user 대상 사용자 + */ + private function makeAdmin(User $user): void + { + // isAdmin() 은 역할 존재가 아니라 admin 타입 권한 보유로 판정한다 — + // 역할만 만들어 붙이면 관리자로 인정되지 않아 403 을 측정하게 된다. + $this->seed(RolePermissionSeeder::class); + + $role = Role::where('identifier', 'admin')->firstOrFail(); + + $user->roles()->syncWithoutDetaching([$role->id => ['assigned_at' => now(), 'assigned_by' => null]]); + $user->refresh(); + } + /** * challenge 에 알려진 인증 코드를 심고 그 값을 돌려줍니다. * diff --git a/tests/Feature/Identity/IdentityLoginPurposeGateTest.php b/tests/Feature/Identity/IdentityLoginPurposeGateTest.php new file mode 100644 index 00000000..b44a3faa --- /dev/null +++ b/tests/Feature/Identity/IdentityLoginPurposeGateTest.php @@ -0,0 +1,162 @@ +seed(RolePermissionSeeder::class); + $this->seed(IdentityMessageDefinitionSeeder::class); + + $this->user = User::factory()->create([ + 'email' => 'purpose-gate@test.com', + 'password' => Hash::make('Passw0rd!2fa'), + 'status' => UserStatus::Active->value, + ]); + + config(['g7_settings.core.security.two_factor_auth' => true]); + } + + /** + * @scenario two_factor=on, controller=user, code=consumed_by_public_verify + * + * @effects public_verify_rejects_login_purpose + */ + #[Test] + public function the_public_verify_endpoint_refuses_a_login_challenge(): void + { + $challengeId = $this->startLoginChallenge(); + + $response = $this->postJson("/api/identity/challenges/{$challengeId}/verify", [ + 'code' => $this->issuedCode($challengeId), + ]); + + $response->assertStatus(403); + $this->assertSame('PURPOSE_NOT_ALLOWED', $response->json('errors.failure_code')); + } + + /** + * @scenario two_factor=on, controller=user, code=consumed_by_public_verify + * + * @effects public_cancel_rejects_login_purpose + */ + #[Test] + public function the_public_cancel_endpoint_refuses_a_login_challenge(): void + { + $challengeId = $this->startLoginChallenge(); + + $this->postJson("/api/identity/challenges/{$challengeId}/cancel") + ->assertStatus(403); + } + + /** + * @scenario two_factor=on, controller=user, code=valid + * + * @effects login_completes_after_public_endpoints_refuse + */ + #[Test] + public function a_login_challenge_still_completes_after_the_public_endpoints_refuse_it(): void + { + $challengeId = $this->startLoginChallenge(); + $code = $this->issuedCode($challengeId); + + $this->postJson("/api/identity/challenges/{$challengeId}/verify", ['code' => $code]); + $this->postJson("/api/identity/challenges/{$challengeId}/cancel"); + + // 게이트가 상태를 전혀 바꾸지 않아야 로그인이 그대로 완료된다. + $response = $this->postJson('/api/auth/login/two-factor', [ + 'challenge_id' => $challengeId, + 'code' => $code, + ]); + + $response->assertStatus(200); + $this->assertNotEmpty($response->json('data.token')); + } + + /** + * @scenario two_factor=on, controller=user, code=valid + * + * @effects signup_purpose_unaffected_by_login_gate + */ + #[Test] + public function a_signup_challenge_is_unaffected_by_the_gate(): void + { + // 대조군 — 게이트가 로그인 이외 목적까지 막으면 가입·비밀번호 재설정 화면이 통째로 멈춘다. + $challenge = app(IdentityVerificationService::class)->start( + IdentityVerificationPurpose::Signup->value, + $this->user, + ['origin_type' => 'route', 'origin_identifier' => 'test'] + ); + + $response = $this->postJson("/api/identity/challenges/{$challenge->id}/verify", [ + 'code' => $this->issuedCode($challenge->id), + ]); + + $this->assertNotSame(403, $response->getStatusCode(), '로그인 이외 목적까지 막으면 가입 흐름이 멈춥니다.'); + } + + /** + * 로그인 2단계 인증 challenge 를 발급하고 그 id 를 돌려줍니다. + * + * @return string challenge UUID + */ + private function startLoginChallenge(): string + { + return $this->postJson('/api/auth/login', [ + 'email' => 'purpose-gate@test.com', + 'password' => 'Passw0rd!2fa', + ])->json('data.challenge_id'); + } + + /** + * challenge 에 알려진 인증 코드를 심고 그 값을 돌려줍니다. + * + * @param string $challengeId challenge UUID + * @return string 심어 둔 인증 코드 + */ + private function issuedCode(string $challengeId): string + { + $code = '135790'; + + $log = IdentityVerificationLog::find($challengeId); + $metadata = $log->metadata ?? []; + $metadata['code_hash'] = Hash::make($code); + + $log->metadata = $metadata; + $log->save(); + + return $code; + } +} diff --git a/tests/Playwright/fixtures/smtp-sink.ts b/tests/Playwright/fixtures/smtp-sink.ts new file mode 100644 index 00000000..10590b9a --- /dev/null +++ b/tests/Playwright/fixtures/smtp-sink.ts @@ -0,0 +1,131 @@ +/** + * 최소 SMTP 싱크 (테스트 전용). + * + * 2단계 인증 실측은 **인증번호 발송이 성공해야** 코드 입력 단계까지 갈 수 있다. 발송이 + * 실패하면 서버가 로그인을 503 으로 끊기 때문이다(그것도 정당한 동작이라 PHPUnit 이 따로 잰다). + * + * 그래서 실제 메일을 보내는 대신 받아서 버리는 SMTP 서버를 잠깐 띄우고 사이트의 메일 설정을 + * 그쪽으로 돌린다. `log` 메일러를 쓰지 않는 이유는 그것이 이 제품의 설정 스키마에 없어서다 — + * 등록된 메일 드라이버(smtp·mailgun·ses) 밖의 값은 저장 검증에서 거부되고, 파일을 직접 고쳐도 + * 드라이버 해석 단계에서 smtp 로 되돌아간다. + * + * 의존성을 늘리지 않으려고 Node 기본 `net` 만 쓴다. 받은 메일은 어디에도 남기지 않는다. + */ +import { createServer, type Server, type Socket } from 'node:net'; + +/** 띄운 싱크의 핸들 */ +export type SmtpSink = { + port: number; + /** 받은 메시지 수 (진단용) */ + received(): number; + close(): Promise; +}; + +/** + * 한 연결의 SMTP 대화를 처리한다. + * + * 인증도 TLS 도 요구하지 않는다 — 테스트 전용이며 127.0.0.1 에만 바인딩한다. + * + * @param socket 클라이언트 소켓 + * @param onMessage 메시지 1건 수신 시 호출 + */ +function handleConnection(socket: Socket, onMessage: () => void): void { + let inData = false; + let buffer = ''; + + socket.setEncoding('utf-8'); + socket.write('220 g7-test-sink ESMTP\r\n'); + + socket.on('data', (chunk: string) => { + buffer += chunk; + + // 본문 수신 중에는 종료 표식(.)만 본다. + if (inData) { + const terminator = buffer.indexOf('\r\n.\r\n'); + if (terminator === -1) return; + + buffer = buffer.slice(terminator + 5); + inData = false; + onMessage(); + socket.write('250 2.0.0 Ok: queued\r\n'); + } + + let newline = buffer.indexOf('\r\n'); + while (! inData && newline !== -1) { + const line = buffer.slice(0, newline); + buffer = buffer.slice(newline + 2); + + const verb = line.split(' ')[0].toUpperCase(); + + if (verb === 'EHLO' || verb === 'HELO') { + // 마지막 줄만 하이픈 없이 — 그래야 클라이언트가 목록의 끝을 안다. + socket.write('250-g7-test-sink\r\n250 SIZE 10485760\r\n'); + } else if (verb === 'DATA') { + socket.write('354 End data with .\r\n'); + inData = true; + } else if (verb === 'QUIT') { + socket.write('221 2.0.0 Bye\r\n'); + socket.end(); + return; + } else { + // MAIL FROM / RCPT TO / RSET / NOOP 등 — 전부 수락한다. + socket.write('250 2.0.0 Ok\r\n'); + } + + newline = buffer.indexOf('\r\n'); + } + }); + + socket.on('error', () => { + // 클라이언트가 먼저 끊는 것은 정상이다 — 테스트를 실패시키지 않는다. + }); +} + +/** + * SMTP 싱크를 띄운다. + * + * @param preferredPort 우선 시도할 포트 (사용 중이면 다음 포트로) + * @returns 싱크 핸들 + */ +export async function startSmtpSink(preferredPort = 2525): Promise { + let count = 0; + + const server: Server = createServer((socket) => { + handleConnection(socket, () => { + count += 1; + }); + }); + + const port = await new Promise((resolvePort, rejectPort) => { + let attempt = 0; + + const tryListen = (candidate: number): void => { + server.once('error', (error: NodeJS.ErrnoException) => { + if (error.code === 'EADDRINUSE' && attempt < 20) { + attempt += 1; + tryListen(candidate + 1); + return; + } + rejectPort(error); + }); + + server.listen(candidate, '127.0.0.1', () => { + const address = server.address(); + resolvePort(typeof address === 'object' && address ? address.port : candidate); + }); + }; + + tryListen(preferredPort); + }); + + return { + port, + received: () => count, + close: () => + new Promise((resolveClose) => { + server.close(() => resolveClose()); + // 열려 있는 연결이 남아도 테스트 종료를 막지 않는다. + server.unref(); + }), + }; +} diff --git a/tests/Playwright/fixtures/two-factor.ts b/tests/Playwright/fixtures/two-factor.ts new file mode 100644 index 00000000..a5a8f02b --- /dev/null +++ b/tests/Playwright/fixtures/two-factor.ts @@ -0,0 +1,283 @@ +/** + * Playwright 2단계 인증 fixture (코어 영역). + * + * 로그인 2단계 인증은 **사이트 설정과 메일 발송**에 의존한다. 브라우저만으로는 재현할 수 없으므로 + * 이 fixture 가 세 가지를 가역적으로 준비한다. + * + * ① 보안 환경설정 `security.two_factor_auth` 를 켜고, 끝나면 원래 값으로 되돌린다. + * ② 메일을 받아서 버리는 로컬 SMTP 싱크를 띄우고 메일 설정을 그쪽으로 돌린다. 끝나면 + * 원래 값으로 되돌린다. (실제 메일을 보내면 테스트가 외부 상태를 바꾼다) + * `log` 메일러를 쓰지 않는 이유는 `smtp-sink.ts` 머리말 참조. + * ③ 인증번호는 해시로만 저장되어 되읽을 수 없으므로, 알려진 코드를 심는다 + * (`php artisan playwright:seed-two-factor --plant=…`). + * + * 보안 설정은 **관리자 설정 API** 로 바꾼다 — 운영자가 화면에서 하는 것과 같은 경로다. + * 메일 설정만 파일을 직접 다룬다: 원래 값(빈 SMTP 호스트)은 저장 검증을 통과하지 못해 + * API 로는 **되돌릴 수 없기 때문**이다. 파일은 바이트 단위로 백업했다가 그대로 복원한다. + * + * 원복은 실패해도 조용히 넘기지 않는다 — 되돌리지 못한 채 끝나면 사이트가 2단계 인증이 켜진 + * 상태로 남아 이후 모든 로그인이 막힌다. + */ +import type { APIRequestContext } from '@playwright/test'; +import { startSmtpSink, type SmtpSink } from './smtp-sink'; +import { execSync } from 'node:child_process'; +import { copyFileSync, existsSync, readFileSync, rmSync, writeFileSync } from 'node:fs'; +import { dirname, resolve } from 'node:path'; +import { fileURLToPath } from 'node:url'; + +const __dirname = dirname(fileURLToPath(import.meta.url)); + +/** artisan 이 있는 코어 루트 */ +function coreRoot(): string { + return process.env.G7_ROOT || resolve(__dirname, '../../../'); +} + +/** + * 관리자 설정 API 경로. + * + * 절대 URL 을 만들지 않는다 — Playwright 의 `request` 컨텍스트가 `baseURL` 과 + * `ignoreHTTPSErrors` 를 이미 갖고 있다. Node 의 `fetch` 를 쓰면 자체 서명 인증서를 쓰는 + * 개발 호스트에서 TLS 로 막히고, 그것을 우회하려면 이 파일이 TLS 검증을 끄게 된다. + */ +const SETTINGS_PATH = '/api/admin/settings'; + +/** + * `playwright:seed-two-factor` 를 실행하고 마지막 출력 줄을 돌려준다. + * + * @param args 커맨드 인자 (예: ['--plant=', '--code=135790']) + * @returns stdout 의 마지막 비어있지 않은 줄 + */ +export function runSeedTwoFactor(args: string[]): string { + const command = `php artisan playwright:seed-two-factor ${args.join(' ')}`.trim(); + + let lastError: unknown; + for (let attempt = 0; attempt < 3; attempt += 1) { + try { + const stdout = execSync(command, { + cwd: coreRoot(), + encoding: 'utf-8', + env: { ...process.env, G7_PLAYWRIGHT_BYPASS: '1' }, + }); + const lines = stdout.split(/\r?\n/).filter((line) => line.trim().length > 0); + if (lines.length === 0) { + throw new Error(`playwright:seed-two-factor 가 빈 응답을 반환했습니다: ${command}`); + } + return lines[lines.length - 1].trim(); + } catch (error) { + lastError = error; + if (attempt < 2) { + Atomics.wait(new Int32Array(new SharedArrayBuffer(4)), 0, 0, 400); + } + } + } + throw lastError instanceof Error ? lastError : new Error(String(lastError)); +} + +/** + * 알려진 인증번호를 challenge 에 심는다. + * + * @param challengeId 로그인 응답이 돌려준 challenge UUID + * @param code 심을 인증번호 (기본 135790) + * @returns 심어 둔 인증번호 + */ +export function plantTwoFactorCode(challengeId: string, code = '135790'): string { + return runSeedTwoFactor([`--plant=${challengeId}`, `--code=${code}`, '--gc-hours=0']); +} + +/** + * 실측이 만든 테스트 계정을 전부 제거한다. + * + * 이 계정들은 알려진 비밀번호를 갖고, 관리자용은 관리자 역할까지 갖는다 — 나이 기준 정리를 + * 기다리면 그 사이가 그대로 열린 문이다. 실측이 끝나면 즉시 지운다. + * + * @returns 커맨드의 마지막 출력 줄 + */ +export function purgeTwoFactorUsers(): string { + return runSeedTwoFactor(['--purge-users', '--gc-hours=0']); +} + +/** + * 알려진 비밀번호를 가진 Active 테스트 계정을 준비한다. + * + * @param suffix 계정 구분 접미사 (예: 'user' / 'nonadmin') + * @param options admin 역할 부여 여부와 비밀번호 + * @returns 준비된 계정 이메일 + */ +export function ensureTwoFactorUser( + suffix: string, + options: { admin?: boolean; password?: string } = {} +): string { + const args = [`--ensure-user=${suffix}`, `--password=${options.password ?? 'Passw0rd!2fa'}`]; + if (options.admin) args.push('--admin'); + return runSeedTwoFactor(args); +} + +/** 되돌리기 위해 보관하는 상태 */ +type TwoFactorFixtureState = { + /** 보안 탭 전체 값 (API 로 그대로 되쓴다) */ + security: Record; + /** 메일 설정 파일 백업 경로 (없으면 파일 자체가 없던 설치) */ + mailBackupPath: string | null; + sink: SmtpSink; +}; + +/** 메일 설정 파일 경로 */ +function mailSettingsPath(): string { + return resolve(coreRoot(), 'storage/app/settings/mail.json'); +} + +/** + * 메일 설정을 SMTP 싱크로 돌린다. + * + * 값 3개만 줄 단위로 치환한다 — 재직렬화하면 운영자 파일의 서식이 통째로 바뀐다. + * `encryption` 을 비우는 이유는 싱크가 STARTTLS 를 제공하지 않기 때문이다. + * + * @param port 싱크 포트 + * @returns 백업 파일 경로 (설정 파일이 없으면 null) + */ +function redirectMailToSink(port: number): string | null { + const path = mailSettingsPath(); + if (! existsSync(path)) { + return null; + } + + const backupPath = `${path}.bak-playwright-2fa`; + copyFileSync(path, backupPath); + + const original = readFileSync(path, 'utf-8'); + const swapped = original + .replace(/"host"(\s*):(\s*)"[^"]*"/, `"host"$1:$2"127.0.0.1"`) + .replace(/"port"(\s*):(\s*)\d+/, `"port"$1:$2${port}`) + .replace(/"encryption"(\s*):(\s*)("[^"]*"|null)/, '"encryption"$1:$2""'); + + writeFileSync(path, swapped, 'utf-8'); + + return backupPath; +} + +/** + * 설정 탭 하나를 통째로 저장한다. + * + * @param request Playwright API 요청 컨텍스트 + * @param token 관리자 Sanctum 토큰 + * @param tab 설정 탭 + * @param values 저장할 탭 전체 값 + */ +async function writeSettingsTab( + request: APIRequestContext, + token: string, + tab: string, + values: Record +): Promise { + const write = await request.post(SETTINGS_PATH, { + headers: { + Accept: 'application/json', + 'Content-Type': 'application/json', + Authorization: `Bearer ${token}`, + }, + data: { _tab: tab, [tab]: values }, + }); + + if (!write.ok()) { + throw new Error(`${tab} 설정 저장 실패: HTTP ${write.status()} — ${await write.text()}`); + } +} + +/** + * 설정 탭 하나를 읽고, 지정한 키만 바꿔 저장한다. + * + * 저장 페이로드는 `{ _tab, <탭>: { ... } }` 형태이고 탭 **전체**가 검증되므로, 바꿀 키만 + * 보내면 나머지 필수 항목이 422 로 거부된다. 현재 값을 그대로 되돌려 보내 다른 설정은 + * 건드리지 않는다. + * + * @param request Playwright API 요청 컨텍스트 (baseURL·ignoreHTTPSErrors 상속) + * @param token 관리자 Sanctum 토큰 + * @param tab 설정 탭 (`security` · `mail` 등) + * @param patch 바꿀 키-값 + * @returns 바꾸기 전의 탭 전체 값 (원복에 그대로 쓴다) + */ +async function patchSettingsTab( + request: APIRequestContext, + token: string, + tab: string, + patch: Record +): Promise> { + const read = await request.get(`${SETTINGS_PATH}?tab=${tab}`, { + headers: { + Accept: 'application/json', + Authorization: `Bearer ${token}`, + }, + }); + + if (!read.ok()) { + throw new Error(`${tab} 설정 조회 실패: HTTP ${read.status()}`); + } + + const body = await read.json(); + const current = (body?.data?.[tab] ?? {}) as Record; + + // `_meta` 같은 내부 키는 저장 페이로드에서 제외한다. + const previous = Object.fromEntries( + Object.entries(current).filter(([key]) => !key.startsWith('_')) + ); + + await writeSettingsTab(request, token, tab, { ...previous, ...patch }); + + return previous; +} + +/** + * 2단계 인증 실측 환경을 준비한다. + * + * @param request Playwright API 요청 컨텍스트 + * @param token 관리자 Sanctum 토큰 (`core.settings.read` · `core.settings.update`) + * @returns 되돌리기에 필요한 상태 + */ +export async function enableTwoFactorFixture( + request: APIRequestContext, + token: string +): Promise { + // 메일 경로를 먼저 돌린다 — 2단계 인증을 켠 뒤에 코드가 발행되면 실제 메일이 나간다. + const sink = await startSmtpSink(); + const mailBackupPath = redirectMailToSink(sink.port); + + const security = await patchSettingsTab(request, token, 'security', { two_factor_auth: true }); + + return { security, mailBackupPath, sink }; +} + +/** + * 실측 환경을 되돌린다. + * + * 되돌리지 못한 채 끝나면 사이트가 2단계 인증이 켜진 상태로 남아 이후 모든 로그인이 막힌다 — + * 실패는 삼키지 않고 그대로 던진다. 보안 설정을 먼저 되돌리고, 그 실패가 메일 설정 복원을 + * 가리지 않도록 둘 다 시도한 뒤에 던진다. + * + * @param request Playwright API 요청 컨텍스트 + * @param token 관리자 Sanctum 토큰 + * @param state `enableTwoFactorFixture` 가 돌려준 상태 + */ +export async function restoreTwoFactorFixture( + request: APIRequestContext, + token: string, + state: TwoFactorFixtureState +): Promise { + let firstError: unknown; + + try { + await writeSettingsTab(request, token, 'security', state.security); + } catch (error) { + firstError = error; + } + + if (state.mailBackupPath && existsSync(state.mailBackupPath)) { + copyFileSync(state.mailBackupPath, mailSettingsPath()); + rmSync(state.mailBackupPath, { force: true }); + } + + await state.sink.close(); + + if (firstError) { + throw firstError; + } +} diff --git a/tests/Playwright/specs/auth/two-factor-login.spec.ts b/tests/Playwright/specs/auth/two-factor-login.spec.ts new file mode 100644 index 00000000..e28783cb --- /dev/null +++ b/tests/Playwright/specs/auth/two-factor-login.spec.ts @@ -0,0 +1,520 @@ +/** + * 로그인 2단계 인증 종단 검증 (공개 #133). + * + * 2단계 인증을 켜면 서버가 로그인에 **두 가지 형태의 200** 을 돌려준다. 화면이 한 형태만 + * 가정하면 영문 오류(`Cannot read properties of undefined`)가 뜨고 로그인이 불가능해지며, + * 관리자 로그인은 서버 오류가 되어 설정을 되돌릴 수단까지 사라진다. + * + * 이 spec 은 사이트 설정과 메일 설정을 **가역적으로** 바꾼다 — `test.afterAll` 이 실패해도 + * 되돌아가도록 fixture 가 원복을 담당한다. 되돌리지 못하면 이후 모든 로그인이 막히므로 + * 반드시 `mode: 'serial'` 로 한 워커에서만 실행한다. + * + * // @scenario controller=user,admin | two_factor=on | code=valid,invalid | resend=active + * // @effects challenge_response_has_no_token, code_step_rendered_on_challenge, no_raw_typeerror_text, resend_cancels_previous_challenge, non_admin_two_factor_revokes_token + */ +import { test, expect, issueToken } from '../../fixtures/auth'; +import { + enableTwoFactorFixture, + ensureTwoFactorUser, + plantTwoFactorCode, + purgeTwoFactorUsers, + restoreTwoFactorFixture, +} from '../../fixtures/two-factor'; + +test.describe.configure({ mode: 'serial' }); + +const PASSWORD = 'Passw0rd!2fa'; + +let adminToken: string; +let fixtureRequest: import('@playwright/test').APIRequestContext | undefined; +let fixtureState: Awaited>; +let memberEmail: string; +let adminEmail: string; +let nonAdminEmail: string; + +test.beforeAll(async ({ playwright }) => { + adminToken = issueToken('core.settings.read', 'core.settings.update'); + + memberEmail = ensureTwoFactorUser('user', { password: PASSWORD }); + adminEmail = ensureTwoFactorUser('admin', { admin: true, password: PASSWORD }); + nonAdminEmail = ensureTwoFactorUser('nonadmin', { password: PASSWORD }); + + // worker 범위 request 컨텍스트 — baseURL·ignoreHTTPSErrors 는 설정에서 온다. + fixtureRequest = await playwright.request.newContext({ + baseURL: process.env.PLAYWRIGHT_BASE_URL, + ignoreHTTPSErrors: true, + }); + + fixtureState = await enableTwoFactorFixture(fixtureRequest, adminToken); +}); + +test.afterAll(async () => { + // 되돌리지 못한 채 끝나면 사이트의 모든 로그인이 2단계 인증을 요구하게 된다. + if (fixtureState && fixtureRequest) { + await restoreTwoFactorFixture(fixtureRequest, adminToken, fixtureState); + } + + await fixtureRequest?.dispose(); + + // 알려진 비밀번호를 가진 계정(관리자 포함)을 남기지 않는다. + purgeTwoFactorUsers(); +}); + +/** + * 로그인 응답에서 challenge_id 를 읽는다. + * + * @param page Playwright 페이지 + * @param urlPart 대기할 요청 경로 조각 + * @param submit 제출을 수행하는 함수 + */ +async function submitAndReadChallenge( + page: import('@playwright/test').Page, + urlPart: string, + submit: () => Promise +): Promise { + const [response] = await Promise.all([ + page.waitForResponse((r) => r.url().includes(urlPart) && r.request().method() === 'POST'), + submit(), + ]); + + const body = await response.json(); + expect(response.status(), '2단계 인증이 켜져 있으면 로그인은 200 챌린지를 돌려준다').toBe(200); + expect(body?.data?.two_factor_required).toBe(true); + // 코드 확인 전에 토큰이 실리면 2단계 인증이 없는 것과 같다. + expect(body?.data?.token, '코드 확인 전에 토큰이 발급되었습니다').toBeFalsy(); + + return String(body.data.challenge_id); +} + +test('사용자 로그인 — 인증번호 단계로 전환되고 코드 확인 후 로그인된다', async ({ page }) => { + await page.goto('/login'); + await page.waitForLoadState('domcontentloaded', { timeout: 30_000 }); + + const challengeId = await submitAndReadChallenge(page, '/api/auth/login', async () => { + await page.fill('input[name="email"]', memberEmail); + await page.fill('input[name="password"]', PASSWORD); + await page.click('form button[type="submit"]'); + }); + + // 2단계 입력이 나타나고 1단계 입력은 사라진다. + const codeInput = page.locator('input[name="two_factor_code"]'); + await expect(codeInput).toBeVisible({ timeout: 10_000 }); + await expect(page.locator('input[name="email"]')).toHaveCount(0); + + // 영문 TypeError 원문이 화면에 남으면 안 된다. + await expect(page.locator('body')).not.toContainText('Cannot read properties of undefined'); + + // 오답 → 오류 문구, 로그인 미완료 + await codeInput.fill('000000'); + await page.click('form button[type="submit"]'); + await expect(page.locator('[role="alert"]')).toBeVisible({ timeout: 10_000 }); + expect(page.url()).toContain('/login'); + + // 정답 → 홈 이동 + const code = plantTwoFactorCode(challengeId); + await codeInput.fill(code); + await page.click('form button[type="submit"]'); + + await page.waitForFunction(() => !window.location.pathname.startsWith('/login'), { + timeout: 15_000, + }); + const token = await page.evaluate(() => localStorage.getItem('auth_token')); + expect(token, '로그인 완료 후 토큰이 저장되어야 합니다').toBeTruthy(); + expect(token).not.toBe('undefined'); +}); + +test('사용자 로그인 — 인증번호 다시 받기는 새 challenge 를 발급하고 입력을 비운다', async ({ page }) => { + await page.goto('/login'); + await page.waitForLoadState('domcontentloaded', { timeout: 30_000 }); + + const first = await submitAndReadChallenge(page, '/api/auth/login', async () => { + await page.fill('input[name="email"]', memberEmail); + await page.fill('input[name="password"]', PASSWORD); + await page.click('form button[type="submit"]'); + }); + + const codeInput = page.locator('input[name="two_factor_code"]'); + await expect(codeInput).toBeVisible({ timeout: 10_000 }); + await codeInput.fill('111111'); + + const [resendResponse] = await Promise.all([ + page.waitForResponse((r) => r.url().includes('/two-factor/resend') && r.request().method() === 'POST'), + page.getByRole('button', { name: /다시|Resend|再送/ }).click(), + ]); + + const resendBody = await resendResponse.json(); + expect(resendResponse.status()).toBe(200); + const second = String(resendBody.data.challenge_id); + expect(second, '재발송이 같은 challenge 를 돌려주면 새 코드가 발송되지 않은 것입니다').not.toBe(first); + + // 앞서 입력한 값이 남아 있으면 새 코드를 받았는데 옛 값으로 제출된다. + await expect(codeInput).toHaveValue(''); + + const code = plantTwoFactorCode(second); + await codeInput.fill(code); + await page.click('form button[type="submit"]'); + + await page.waitForFunction(() => !window.location.pathname.startsWith('/login'), { + timeout: 15_000, + }); +}); + +/** + * 인증 단계 상태는 전역이라 화면을 떠나도 남는다. 그래서 되돌리는 통로가 셋 다 살아 있어야 한다 — + * 「처음부터」 버튼 · 새로고침 · 다른 화면으로 나갔다 돌아오기. 하나라도 빠지면 사용자가 1단계로 + * 돌아오지 못한 채 이미 만료된 challenge 앞에 갇힌다. + * + * 새로고침 축은 잘못 저장된 토큰(`"undefined"`) 회귀도 함께 잡는다 — 그 값이 남으면 이후 요청이 + * 전부 401 이 되어 `/login?reason=session_expired` 로 튕겼다(공개 #133 의 두 번째 증상). + * + * // @scenario controller=user | two_factor=on | action=restart + * // @effects restart_resets_to_credential_step, init_actions_reset_two_factor_state + */ +test('인증번호 단계 — 처음부터·새로고침·재진입 모두 1단계로 돌아온다', async ({ page }) => { + await page.goto('/login'); + await page.waitForLoadState('domcontentloaded', { timeout: 30_000 }); + + const enterCodeStep = async () => { + await submitAndReadChallenge(page, '/api/auth/login', async () => { + await page.fill('input[name="email"]', memberEmail); + await page.fill('input[name="password"]', PASSWORD); + await page.click('form button[type="submit"]'); + }); + await expect(page.locator('input[name="two_factor_code"]')).toBeVisible({ timeout: 10_000 }); + }; + + const expectCredentialStep = async () => { + await expect(page.locator('input[name="email"]')).toBeVisible({ timeout: 10_000 }); + await expect(page.locator('input[name="two_factor_code"]')).toHaveCount(0); + }; + + // ① 「처음부터」 버튼 + await enterCodeStep(); + await page.getByRole('button', { name: /처음부터|Start over|最初から/ }).click(); + await expectCredentialStep(); + + // ② 새로고침 — 잘못된 토큰이 남았다면 여기서 session_expired 로 튕긴다. + await enterCodeStep(); + await page.reload({ waitUntil: 'domcontentloaded' }); + expect(page.url(), '새로고침이 만료 안내로 튕기면 토큰이 잘못 저장된 것입니다').not.toContain( + 'reason=session_expired' + ); + const staleToken = await page.evaluate(() => localStorage.getItem('auth_token')); + expect(staleToken, '코드 확인 전에는 토큰이 저장되면 안 됩니다').not.toBe('undefined'); + await expectCredentialStep(); + + // ③ 다른 화면으로 나갔다 돌아오기 — init_actions 리셋이 없으면 2단계가 그대로 남는다. + await enterCodeStep(); + await page.goto('/register'); + await page.waitForLoadState('domcontentloaded', { timeout: 30_000 }); + await page.goto('/login'); + await page.waitForLoadState('domcontentloaded', { timeout: 30_000 }); + await expectCredentialStep(); +}); + +test('관리자 로그인 — 챌린지 응답이 서버 오류가 아니고 코드 확인 후 관리자 화면으로 간다', async ({ page }) => { + await page.goto('/admin/login'); + await page.waitForLoadState('domcontentloaded', { timeout: 30_000 }); + + const challengeId = await submitAndReadChallenge(page, '/api/auth/admin/login', async () => { + await page.fill('input[name="email"]', adminEmail); + await page.fill('input[name="password"]', PASSWORD); + await page.click('#login_submit_button'); + }); + + const codeInput = page.locator('#two_factor_code'); + await expect(codeInput).toBeVisible({ timeout: 10_000 }); + await expect(page.locator('body')).not.toContainText('Cannot read properties of undefined'); + + await codeInput.fill(plantTwoFactorCode(challengeId)); + await page.locator('#login_two_factor_submit').click(); + + await page.waitForFunction(() => !window.location.pathname.startsWith('/admin/login'), { + timeout: 15_000, + }); +}); + +test('관리자 로그인 — 관리자가 아닌 계정은 코드 확인에 성공해도 거부되고 토큰이 남지 않는다', async ({ page }) => { + await page.goto('/admin/login'); + await page.waitForLoadState('domcontentloaded', { timeout: 30_000 }); + + const challengeId = await submitAndReadChallenge(page, '/api/auth/admin/login', async () => { + await page.fill('input[name="email"]', nonAdminEmail); + await page.fill('input[name="password"]', PASSWORD); + await page.click('#login_submit_button'); + }); + + const codeInput = page.locator('#two_factor_code'); + await expect(codeInput).toBeVisible({ timeout: 10_000 }); + await codeInput.fill(plantTwoFactorCode(challengeId)); + + const [verifyResponse] = await Promise.all([ + page.waitForResponse((r) => r.url().includes('/admin/login/two-factor') && r.request().method() === 'POST'), + page.locator('#login_two_factor_submit').click(), + ]); + + expect(verifyResponse.status()).toBe(403); + + // 코드 확인 시점에 발급된 토큰이 회수되지 않으면 유효한 세션이 남는다. + const token = await page.evaluate(() => localStorage.getItem('auth_token')); + expect(token, '거부된 로그인이 토큰을 남겼습니다').toBeFalsy(); + expect(page.url()).toContain('/admin/login'); +}); + +test('인증번호 단계 — Enter 키는 확인만 보내고 새 challenge 를 발급하지 않는다', async ({ page }) => { + await page.goto('/login'); + await page.waitForLoadState('domcontentloaded', { timeout: 30_000 }); + + const challengeId = await submitAndReadChallenge(page, '/api/auth/login', async () => { + await page.fill('input[name="email"]', memberEmail); + await page.fill('input[name="password"]', PASSWORD); + await page.click('form button[type="submit"]'); + }); + + const codeInput = page.locator('input[name="two_factor_code"]'); + await expect(codeInput).toBeVisible({ timeout: 10_000 }); + + // 세 자리까지는 확인 버튼이 눌리지 않는다. + await codeInput.fill('123'); + const verifyButton = page.locator('form button[type="submit"]'); + await expect(verifyButton).toBeDisabled(); + + await codeInput.fill(plantTwoFactorCode(challengeId)); + await expect(verifyButton).toBeEnabled(); + + const posts: string[] = []; + page.on('request', (req) => { + if (req.method() === 'POST' && req.url().includes('/api/auth/')) posts.push(req.url()); + }); + + await codeInput.press('Enter'); + await page.waitForFunction(() => !window.location.pathname.startsWith('/login'), { + timeout: 15_000, + }); + + const verifyCalls = posts.filter((u) => u.includes('/login/two-factor')).length; + const loginCalls = posts.filter((u) => u.endsWith('/api/auth/login')).length; + + expect(verifyCalls, 'Enter 가 인증번호 확인을 보내지 않았습니다').toBe(1); + // 상호배타 조건이 빠지면 Enter 가 새 challenge 를 발급해 흐름이 깨진다. + expect(loginCalls, 'Enter 가 비밀번호 단계를 다시 호출했습니다').toBe(0); +}); + +test('인증번호 단계 — 모바일 폭과 일본어 로케일에서 문구·배치가 깨지지 않는다', async ({ page }) => { + await page.setViewportSize({ width: 375, height: 812 }); + await page.addInitScript(() => localStorage.setItem('g7_locale', 'ja')); + + await page.goto('/login'); + await page.waitForLoadState('domcontentloaded', { timeout: 30_000 }); + + await submitAndReadChallenge(page, '/api/auth/login', async () => { + await page.fill('input[name="email"]', memberEmail); + await page.fill('input[name="password"]', PASSWORD); + await page.click('form button[type="submit"]'); + }); + + await expect(page.locator('input[name="two_factor_code"]')).toBeVisible({ timeout: 10_000 }); + + // 다국어 키가 해석되지 않으면 `$t:` 토큰이 그대로 화면에 남는다. + const body = (await page.locator('body').innerText()) ?? ''; + expect(body).not.toContain('$t:'); + expect(body).not.toContain('auth.two_factor'); + + // 다시 받기·처음부터 두 버튼이 좁은 폭에서도 컨테이너를 넘지 않는다. + const buttons = page.locator('form button[type="button"]'); + const count = await buttons.count(); + expect(count).toBeGreaterThanOrEqual(2); + + for (let i = 0; i < count; i += 1) { + const box = await buttons.nth(i).boundingBox(); + if (box) { + expect(box.width, '버튼이 375px 화면을 넘칩니다').toBeLessThanOrEqual(375); + } + } +}); + +test('공개 본인인증 화면으로는 로그인 challenge 를 소진할 수 없다', async ({ page }) => { + await page.goto('/login'); + await page.waitForLoadState('domcontentloaded', { timeout: 30_000 }); + + const challengeId = await submitAndReadChallenge(page, '/api/auth/login', async () => { + await page.fill('input[name="email"]', memberEmail); + await page.fill('input[name="password"]', PASSWORD); + await page.click('form button[type="submit"]'); + }); + + const code = plantTwoFactorCode(challengeId); + + const status = await page.evaluate(async (id) => { + const res = await fetch(`/api/identity/challenges/${id}/verify`, { + method: 'POST', + headers: { 'Content-Type': 'application/json', Accept: 'application/json' }, + body: JSON.stringify({ code: '135790' }), + }); + return res.status; + }, challengeId); + + expect(status, '로그인 challenge 가 공개 본인인증 경로로 소진되었습니다').toBe(403); + + // 거부는 상태를 바꾸지 않으므로 로그인은 그대로 완료된다. + await page.locator('input[name="two_factor_code"]').fill(code); + await page.click('form button[type="submit"]'); + await page.waitForFunction(() => !window.location.pathname.startsWith('/login'), { + timeout: 15_000, + }); +}); + +/** + * 인증번호를 여러 번 틀려도 그 challenge 로 계속 시도할 수 있어야 한다. + * + * 오답 때마다 입력을 비우면 오타 한 글자를 고치려던 사용자가 전체를 다시 친다 — + * 입력을 남기는 것이 확정된 동작이다(레이아웃의 `loginTwoFactor` onError 는 code 를 + * 건드리지 않는다). 비우도록 바뀌면 아래 `toHaveValue` 가 red 가 된다. + * + * // @scenario controller=user | two_factor=on | code=invalid,valid + * // @effects invalid_code_retries_until_success + */ +test('인증번호 단계 — 세 번 틀려도 입력이 남고 네 번째 정답으로 로그인된다', async ({ page }) => { + await page.goto('/login'); + await page.waitForLoadState('domcontentloaded', { timeout: 30_000 }); + + const challengeId = await submitAndReadChallenge(page, '/api/auth/login', async () => { + await page.fill('input[name="email"]', memberEmail); + await page.fill('input[name="password"]', PASSWORD); + await page.click('form button[type="submit"]'); + }); + + const codeInput = page.locator('input[name="two_factor_code"]'); + await expect(codeInput).toBeVisible({ timeout: 10_000 }); + + // 본인인증 정책 상한(max_attempts=5) 안이라 세 번까지는 challenge 가 살아 있다. + for (let attempt = 1; attempt <= 3; attempt += 1) { + await codeInput.fill('000000'); + + const [response] = await Promise.all([ + page.waitForResponse( + (r) => + r.url().includes('/api/auth/login/two-factor') && + !r.url().includes('/resend') && + r.request().method() === 'POST' + ), + page.click('form button[type="submit"]'), + ]); + + expect(response.status(), `${attempt}회째 오답이 거부되지 않았습니다`).toBe(401); + await expect(page.locator('[role="alert"]')).toBeVisible({ timeout: 10_000 }); + + // 오답 뒤에도 입력은 남는다. + await expect(codeInput).toHaveValue('000000'); + expect(page.url()).toContain('/login'); + } + + await codeInput.fill(plantTwoFactorCode(challengeId)); + await page.click('form button[type="submit"]'); + + await page.waitForFunction(() => !window.location.pathname.startsWith('/login'), { + timeout: 15_000, + }); +}); + +/** + * 로그인이 끝난 직후의 상태 — 2단계 흔적이 남으면 다음에 로그인 화면을 열었을 때 + * 비밀번호 단계가 아니라 코드 단계가 뜬다. + * + * // @scenario controller=user | two_factor=on | code=valid + * // @effects session_state_cleared_after_two_factor_success + */ +test('인증 완료 직후 — 2단계 상태가 지워지고 사용자·토큰이 자리 잡는다', async ({ page }) => { + await page.goto('/login'); + await page.waitForLoadState('domcontentloaded', { timeout: 30_000 }); + + const challengeId = await submitAndReadChallenge(page, '/api/auth/login', async () => { + await page.fill('input[name="email"]', memberEmail); + await page.fill('input[name="password"]', PASSWORD); + await page.click('form button[type="submit"]'); + }); + + await page.locator('input[name="two_factor_code"]').fill(plantTwoFactorCode(challengeId)); + await page.click('form button[type="submit"]'); + await page.waitForFunction(() => !window.location.pathname.startsWith('/login'), { + timeout: 15_000, + }); + + const state = await page.evaluate(() => { + const w = window as unknown as Record; + const globalState = w.__templateApp?.getGlobalState?.() ?? w.G7Core?.state?.get?.() ?? {}; + + return { + twoFactor: globalState.twoFactor ?? null, + isLoggingIn: globalState.isLoggingIn ?? null, + uuid: String(globalState.currentUser?.uuid ?? ''), + email: String(globalState.currentUser?.email ?? ''), + token: String(localStorage.getItem('auth_token') ?? ''), + }; + }); + + expect(state.twoFactor, '로그인이 끝났는데 2단계 상태가 남아 있습니다').toBeNull(); + expect(state.isLoggingIn, '로딩 표시가 켜진 채 남았습니다').toBe(false); + expect(state.uuid.length, '로그인한 사용자가 전역 상태에 실리지 않았습니다').toBeGreaterThan(0); + expect(state.email).toBe(memberEmail); + // `"undefined"` 가 저장되던 결함(#133)은 길이 9 라 존재 검사만으로는 통과한다. + expect(state.token.length, '저장된 토큰이 실제 토큰이 아닙니다').toBeGreaterThan(20); +}); + +/** + * 확인 버튼을 빠르게 두 번 눌러도 인증 요청은 한 번만 나가야 한다. + * + * 두 번 나가면 두 번째가 이미 소진된 challenge 를 확인하려다 실패해, 로그인은 됐는데 + * 오류 문구가 함께 뜨는 상태가 된다. + * + * // @scenario controller=user | two_factor=on | code=valid + * // @effects double_submit_sends_single_verify_request + */ +test('인증번호 단계 — 확인 버튼을 두 번 눌러도 확인 요청은 한 번만 나간다', async ({ page }) => { + await page.goto('/login'); + await page.waitForLoadState('domcontentloaded', { timeout: 30_000 }); + + const challengeId = await submitAndReadChallenge(page, '/api/auth/login', async () => { + await page.fill('input[name="email"]', memberEmail); + await page.fill('input[name="password"]', PASSWORD); + await page.click('form button[type="submit"]'); + }); + + const codeInput = page.locator('input[name="two_factor_code"]'); + await expect(codeInput).toBeVisible({ timeout: 10_000 }); + await codeInput.fill(plantTwoFactorCode(challengeId)); + + const verifyCalls: string[] = []; + page.on('request', (req) => { + if ( + req.method() === 'POST' && + req.url().includes('/api/auth/login/two-factor') && + !req.url().includes('/resend') + ) { + verifyCalls.push(req.url()); + } + }); + + const verifyButton = page.locator('form button[type="submit"]'); + const startedAt = Date.now(); + await verifyButton.click(); + + // 두 번째 클릭이 도달하기 전에 버튼이 잠겨야 한다. 잠금은 제출 시퀀스가 세우는 + // `isLoggingIn` 이 화면에 반영될 때 걸리므로, 그 반영이 사람의 두 번째 클릭보다 + // 빨라야 한다는 뜻이다. + await expect(verifyButton).toBeDisabled({ timeout: 1_000 }); + const lockedAfterMs = Date.now() - startedAt; + expect( + lockedAfterMs, + `확인 버튼이 잠기기까지 ${lockedAfterMs}ms 가 걸렸습니다 — 사람의 두 번째 클릭이 그 사이에 들어옵니다` + ).toBeLessThan(200); + + // 잠긴 뒤의 두 번째 클릭은 브라우저가 비활성 버튼에 전달하지 않는다. + await verifyButton.click({ force: true, timeout: 2_000 }).catch(() => undefined); + + await page.waitForFunction(() => !window.location.pathname.startsWith('/login'), { + timeout: 15_000, + }); + + expect(verifyCalls.length, '확인 요청이 두 번 나갔습니다').toBe(1); +}); diff --git a/tests/TestCase.php b/tests/TestCase.php index 917c5b07..4052046e 100644 --- a/tests/TestCase.php +++ b/tests/TestCase.php @@ -104,11 +104,21 @@ abstract class TestCase extends BaseTestCase * 기본 모드를 전제한 테스트(자산 URL 생성·blade 렌더)가 그 환경에서만 무더기로 깨진다. * 실제로 이 환경에서 8건이 그렇게 실패했다. * - * 다른 모드를 검증해야 하는 테스트는 `AssetUrl::forceMode()` 로 자기 전제를 명시한다. + * `security.two_factor_auth` 도 같다. 켜 둔 사이트에서는 `/api/auth/login` 이 토큰이 + * 아니라 인증 요청(challenge)을 돌려주므로, 로그인 성공을 전제한 테스트가 그 환경에서만 + * 깨진다. 게다가 테스트 메일러로는 인증번호를 보낼 수 없어 503 이 되므로 실패 메시지가 + * 원인을 가리키지도 않는다. 실제로 이 환경에서 3건이 그렇게 실패했다. + * + * 다른 모드를 검증해야 하는 테스트는 `AssetUrl::forceMode()` 로, 2단계 인증을 켜야 하는 + * 테스트는 `config(['g7_settings.core.security.two_factor_auth' => true])` 로 자기 전제를 + * 명시한다 (자식 `setUp()` 은 `parent::setUp()` 뒤에 실행되므로 그 지정이 이긴다). */ private function pinEnvironmentDependentSettings(): void { - config(['g7_settings.core.general.asset_url_mode' => AssetUrl::MODE_EXTENSION]); + config([ + 'g7_settings.core.general.asset_url_mode' => AssetUrl::MODE_EXTENSION, + 'g7_settings.core.security.two_factor_auth' => false, + ]); } /** diff --git a/tests/scenarios/auth-two-factor-login.yaml b/tests/scenarios/auth-two-factor-login.yaml new file mode 100644 index 00000000..da9f1ad3 --- /dev/null +++ b/tests/scenarios/auth-two-factor-login.yaml @@ -0,0 +1,94 @@ +# audit:allow test-scenario-coverage reason: 7축 cross product 는 조건부 축(actor 는 controller=admin 에서만, +# lock_state 는 세션을 여는 단계에서만, delivery 는 비밀번호 단계에서만 의미가 있다)을 곱해 낸 명목상 조합이라 +# 개별 케이스에 docblock 을 매핑할 실체가 없다. 실제 회귀 가드는 effects 22건이며 전부 test_files 의 +# PHPUnit·Playwright 테스트에 @effects 로 귀속되어 있다(미검증 0건). + +feature: 로그인 2단계 인증 (인증번호 확인·재발송) + +description: | + 보안 환경설정의 「2단계 인증」이 켜져 있으면 비밀번호가 맞아도 토큰을 발급하지 않고 + 인증 요청(challenge)만 돌려준다. 즉 로그인 응답은 **두 가지 형태의 200** 이다. + + 핵심 동작: + - 사용자·관리자 두 경로가 같은 규칙으로 challenge 를 발급한다. 관리자 판정은 + 코드 확인에 성공한 뒤에 수행한다 (그 전에는 사용자도 토큰도 없다). + - 코드 확인 시점에 토큰이 발급되므로, 그 뒤 관리자 판정으로 거부하는 경로는 + 발급분을 반드시 회수한다. + - 재발송은 기존 challenge 를 취소하고 새로 발행한다 — 유효한 코드를 여러 개 + 살려 두면 대입 시도의 표적이 넓어진다. + - 인증번호를 보내지 못하면 401 이 아니라 503 으로 답한다. 자격 증명은 올바른데 + 401 로 뭉개면 사용자는 비밀번호를 의심하고 운영자는 원인을 알 수 없다. + - 로그인 challenge 는 공개 본인인증 경로(verify/cancel)로 소진할 수 없다. + 소진되면 그 challenge 로 영영 로그인할 수 없게 된다(자기 DoS). + +axes: + controller: [user, admin] + two_factor: [on, off] + delivery: [sent, failed] + code: [valid, invalid, expired, consumed_by_public_verify] + resend: [none, active, expired, verified, cancelled] + actor: [admin, non_admin] + lock_state: [none, active] + +exclusions: + - { two_factor: off, code: valid, reason: "2단계 인증이 꺼져 있으면 코드 확인 단계가 없다" } + - { two_factor: off, code: invalid, reason: "동일" } + - { two_factor: off, code: expired, reason: "동일" } + - { two_factor: off, code: consumed_by_public_verify, reason: "동일" } + - { two_factor: off, resend: active, reason: "challenge 자체가 발급되지 않는다" } + - { two_factor: off, resend: expired, reason: "동일" } + - { two_factor: off, resend: verified, reason: "동일" } + - { two_factor: off, resend: cancelled, reason: "동일" } + - { two_factor: off, delivery: failed, reason: "발송 경로를 타지 않는다" } + - { delivery: failed, code: valid, reason: "발송에 실패하면 확인할 코드가 없다" } + - { delivery: failed, code: invalid, reason: "동일" } + - { delivery: failed, code: expired, reason: "동일" } + - { delivery: failed, code: consumed_by_public_verify, reason: "동일" } + - { delivery: failed, resend: active, reason: "동일 — 재발송할 challenge 가 없다" } + - { delivery: failed, resend: expired, reason: "동일" } + - { delivery: failed, resend: verified, reason: "동일" } + - { delivery: failed, resend: cancelled, reason: "동일" } + - { controller: user, actor: non_admin, reason: "사용자 경로는 관리자 판정을 하지 않는다" } + - { resend: active, code: invalid, reason: "재발송은 코드 확인 이전 단계라 코드 상태와 직교하지 않는다" } + - { resend: active, code: expired, reason: "동일" } + - { resend: active, code: consumed_by_public_verify, reason: "동일" } + - { resend: expired, code: invalid, reason: "동일" } + - { resend: expired, code: expired, reason: "동일" } + - { resend: expired, code: consumed_by_public_verify, reason: "동일" } + - { resend: verified, code: invalid, reason: "동일" } + - { resend: verified, code: expired, reason: "동일" } + - { resend: verified, code: consumed_by_public_verify, reason: "동일" } + - { resend: cancelled, code: invalid, reason: "동일" } + - { resend: cancelled, code: expired, reason: "동일" } + - { resend: cancelled, code: consumed_by_public_verify, reason: "동일" } + +effects: + - challenge_response_has_no_token + - challenge_response_has_no_user + - delivery_failure_503_with_reason + - admin_login_returns_challenge_not_500 + - admin_two_factor_issues_token_for_admin + - non_admin_two_factor_revokes_token + - non_admin_admin_login_revokes_token + - public_verify_rejects_login_purpose + - public_cancel_rejects_login_purpose + - login_completes_after_public_endpoints_refuse + - signup_purpose_unaffected_by_login_gate + - resend_cancels_previous_challenge + - resend_rejects_verified_challenge + - resend_rejects_expired_challenge + - resend_rejects_cancelled_challenge + - resend_refused_while_locked + - admin_resend_returns_new_challenge + - admin_resend_refuses_non_admin + - too_many_attempts_message_translated + - invalid_code_retries_until_success + - session_state_cleared_after_two_factor_success + - double_submit_sends_single_verify_request + +test_files: + - tests/Feature/Auth/TwoFactorAuthTest.php + - tests/Feature/Auth/TwoFactorAccountLockTest.php + - tests/Feature/Auth/LoginThrottleTest.php + - tests/Feature/Identity/IdentityLoginPurposeGateTest.php + - tests/Playwright/specs/auth/two-factor-login.spec.ts