From 30ad72a3a124a1d76297180a6ab1be680cf51d91 Mon Sep 17 00:00:00 2001 From: HeuJung Date: Mon, 10 Aug 2026 15:43:27 +0900 Subject: [PATCH] =?UTF-8?q?fix(core,ecommerce,tosspayments):=20=EA=B0=84?= =?UTF-8?q?=ED=8E=B8=EA=B2=B0=EC=A0=9C=20=EC=84=A0=ED=83=9D=EA=B0=92=20?= =?UTF-8?q?=EC=9C=A0=EC=8B=A4=C2=B7=EA=B8=B0=EB=B3=B8=ED=86=B5=ED=99=94=20?= =?UTF-8?q?=EC=A4=91=EB=B3=B5=C2=B7=EA=B3=A0=EC=95=84=20=EA=B2=B0=EC=A0=9C?= =?UTF-8?q?=EC=88=98=EB=8B=A8=20=EB=85=B8=EC=B6=9C=20=EC=88=98=EC=A0=95?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 엔진 - dot notation setState(target:"_local.xxx")가 canonical _global._local 을 동기화하지 않아, 화면에는 선택 표시가 되는데 확장 커스텀 핸들러의 getLocal 에는 값이 보이지 않던 비대칭을 해소했다(engine-v1.58.2). 예외도 경고도 없이 값만 비어 발견이 늦다. 동기화 기준을 전체 스냅샷이 아니라 live _global._local + 변경 키로 잡아, 부분 상태가 base 가 되어 다른 키를 잃거나 앞선 setLocal 을 되돌리는 기존 회귀 경로를 피했다. 토스페이먼츠 - 간편결제 자체창 직행 지정을 top-level easyPay 로 넘겨 SDK 가 통째로 무시하던 것을 card.flowMode DIRECT + card.easyPay 정본 계약으로 교정했다. 이커머스 - defaults 에서 보충된 통화가 옛 is_default 를 들여와 기본 통화가 둘이 되면서 환율이 1.0 으로 박제돼 PG 청구액이 1/100 로 나갔다. 병합 직후 재동기화하고, 표시 계층의 기본 통화 해석을 default_currency 우선으로 통일해 환산 계층과 일치시켰다. - 공급 확장이 더 이상 제공하지 않는 고아 결제수단이 주문서에 노출되던 것을 공개 API 단일 지점에서 차단했다. 관리자 응답은 운영자가 확인·삭제해야 하므로 그대로 둔다. - 관리자 주문설정에서 Select 에 준 폭 클래스가 컴포넌트 기본 w-full 에 밀려 죽는 구조라, 폭 책임을 셀렉트에서 열 컨테이너로 옮겼다. - 고아 행에서 마일리지 차감 시점 열만 가드가 빠져 노출되던 사전 결함을 함께 고쳤다. 열을 열거하는 대신 조상 체인의 가드 유무를 스캔해, 이후 추가되는 열도 자동으로 검사 대상이 되도록 회귀 테스트를 구성했다. 개발 도구 - dev-dashboard 인스톨러 초기화에 환경설정/첨부파일 삭제 토글을 추가했다. 컨테이너 디렉토리를 보존해 재생성 시 소유권이 바뀌지 않게 하고, 두 옵션이 같은 경로를 다뤄도 서로 간섭하지 않도록 분리했다. 규정 - 저장값과 확장 훅 카탈로그가 병합되는 설정에서 공개 응답이 카탈로그 소속까지 판정해야 한다는 규칙을 문서화하고, 정적 판정이 불가한 근거와 함께 coverage 에 등록했다. --- AGENTS.md | 16 ++ CHANGELOG.md | 1 + docs/extension/module-settings.md | 70 ++++++- .../_bundled/sirsoft-ecommerce/CHANGELOG.md | 5 + .../sirsoft-ecommerce/docs/api/settings.md | 36 +++- .../adminEcommerceSettingsOrder.test.tsx | 153 ++++++++++++++ .../_payment_methods_list.json | 13 +- .../Public/EcommerceSettingsController.php | 2 +- .../Traits/HasMultiCurrencyPrices.php | 21 +- .../src/Services/EcommerceSettingsService.php | 22 +- .../PaymentSettingsOrphanedMethodTest.php | 96 +++++++++ .../admin/payment-method-pg-locked.spec.ts | 75 +++++++ ...ommerceSettingsCurrencyDefaultFlagTest.php | 195 ++++++++++++++++++ .../EcommerceSettingsOrderSettingsTest.php | 51 +++++ .../dist/js/plugin.iife.js | 3 +- .../__tests__/handlers/requestPayment.test.ts | 19 +- .../resources/js/handlers/requestPayment.ts | 7 +- public/build/core/layout-editor.min.js | 8 +- public/build/core/template-engine.min.js | 107 +++++++--- .../core/template-engine/ActionDispatcher.ts | 35 ++++ .../js/core/template-engine/CHANGELOG.md | 14 ++ .../troubleshooting-state-setstate.test.ts | 118 +++++++++++ resources/views/dev-dashboard.blade.php | 190 ++++++++++++++++- ...setstate-dot-path-local-store-sync.spec.ts | 124 +++++++++++ 24 files changed, 1318 insertions(+), 63 deletions(-) create mode 100644 modules/_bundled/sirsoft-ecommerce/tests/Feature/Http/Controllers/Public/PaymentSettingsOrphanedMethodTest.php create mode 100644 modules/_bundled/sirsoft-ecommerce/tests/Unit/Services/EcommerceSettingsCurrencyDefaultFlagTest.php create mode 100644 tests/Playwright/specs/setstate-dot-path-local-store-sync.spec.ts diff --git a/AGENTS.md b/AGENTS.md index c2153b12..37b3d34b 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -387,6 +387,22 @@ Icon 은 `` 글리프라 박스 크기가 곧 `font-size` 다. `w-N h-N` 은 > 상세: [api-resources.md](docs/backend/api-resources.md), [service-repository.md](docs/backend/service-repository.md) +### 저장값 + 확장 카탈로그 병합 설정의 공개 응답 + +설정 항목이 "운영자 저장값 + 확장이 훅으로 등록한 카탈로그" 의 병합으로 만들어지면, 저장값은 남아 있는데 카탈로그에서 항목이 사라지는 상태가 생긴다 — 그 확장을 삭제·비활성화했거나, 확장이 자기 기능 토글을 껐을 때다. 병합부는 이를 고아 항목으로 표시하지만 저장값의 `is_active` 는 참 그대로 남는다. + +| 금지 | 올바른 사용 | +|------|------------| +| 공개 응답이 저장값 플래그(`is_active`)만 보고 항목을 내보냄 | 카탈로그 소속(`_orphaned`)을 함께 판정 — 공급 확장이 더 이상 제공하지 않는 항목은 공개 응답에서 제거 | +| 고아 항목을 관리자 응답에서도 제거 | 관리자 응답은 유지 — 운영자가 확인하고 지워야 할 대상이다 | +| 소비 화면(레이아웃 JSON)마다 필터를 넣어 차단 | 공개 API 단일 지점에서 차단 — 화면마다 복제하면 템플릿 하나만 빠져도 같은 결함이 남는다 | +| 같은 데이터를 내보내는 공개 엔드포인트가 서로 다른 게터를 사용 | 전 엔드포인트가 같은 공개 게터를 경유 — 한쪽이 raw `getSettings()` 를 쓰면 그 경로만 조용히 뚫린다 | +| 항목 제거 후 배열 인덱스를 그대로 둠 | `array_values()` 로 재정렬 — 비연속 키는 JSON 객체로 직렬화되어 화면 반복이 깨진다 | + +이 결함은 예외도 경고도 로그도 남기지 않는다. 이미 제공 불가한 항목이 사용자 화면에서 선택 가능한 상태로 남아 있는 것이 유일한 증상이고, 관리자 화면은 고아 표시로 정상 차단하고 있어 양쪽을 나란히 보지 않으면 드러나지 않는다. + +> 상세: [module-settings.md](docs/extension/module-settings.md) "카탈로그 병합 설정의 공개 응답" + ### 목록 조회 컬럼 프루닝과 지연 조인 | 금지 | 올바른 사용 | diff --git a/CHANGELOG.md b/CHANGELOG.md index 84dfdbce..473dee6f 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -110,6 +110,7 @@ #### 화면 동작 - 화면에서 선택·클릭 같은 동작에 반응하도록 지정한 항목이 아무 반응도 하지 않던 문제를 수정했습니다. 오류나 경고 없이 조용히 동작하지 않아 원인을 찾기 어려웠습니다. 게시판 글쓰기의 분류 선택이 이에 해당해, 분류를 골라도 글에 반영되지 않았습니다. 함께, 반응은 하되 선택한 값만 비어 저장되던 경우도 수정했습니다. +- 화면에서 고른 값이 모듈·플러그인이 제공하는 동작에는 전달되지 않던 문제를 수정했습니다. 값을 저장하는 방식이 두 가지인데 그중 한 가지로 저장하면 화면에는 선택한 것으로 표시되지만 확장 기능은 그 값을 읽지 못했고, 오류나 경고가 남지 않아 화면만 봐서는 알 수 없었습니다. 이제 어느 방식으로 저장하든 같은 값이 전달됩니다. #### 레이아웃 코드 편집 diff --git a/docs/extension/module-settings.md b/docs/extension/module-settings.md index 6aff4f9c..1e965f83 100644 --- a/docs/extension/module-settings.md +++ b/docs/extension/module-settings.md @@ -14,7 +14,8 @@ 6. [API 라우트 설정](#6-api-라우트-설정) 7. [레이아웃 연동](#7-레이아웃-연동) 8. [백엔드에서 설정 조회](#8-백엔드에서-설정-조회) -9. [관련 문서](#9-관련-문서) +9. [카탈로그 병합 설정의 공개 응답](#9-카탈로그-병합-설정의-공개-응답) +10. [관련 문서](#10-관련-문서) --- @@ -527,7 +528,72 @@ $timing = $this->settingsService->getStockDeductionTiming($method); --- -## 9. 관련 문서 +## 9. 카탈로그 병합 설정의 공개 응답 + +설정 항목의 목록을 다른 확장이 훅으로 등록하는 경우(결제수단, 배송사, 발급 제공자 등), 저장된 값은 그 카탈로그와 병합되어 응답에 실린다. 운영자가 저장한 값(`is_active`, 정렬 순서 등)과 확장이 제공하는 정의(이름, 아이콘, 지원 범위)가 항목마다 합쳐지는 구조다. + +### 9.1 고아 항목이 생기는 조건 + +병합의 두 입력은 생명주기가 다르다. 저장값은 파일에 남지만 카탈로그는 요청 시점에 훅으로 다시 만들어지므로, 다음 상황에서 **저장값만 남고 카탈로그에서는 사라진 항목**이 생긴다. + +- 공급 확장을 삭제했다 +- 공급 확장을 비활성화했다 +- 확장이 살아 있지만 자기 기능 토글을 꺼서 해당 항목 등록을 중단했다 + +병합부는 이런 항목에 `_orphaned` 표시를 붙여 돌려준다. 이때 저장값의 `is_active` 는 참 그대로 남아 있다 — 운영자가 끈 적이 없기 때문이다. + +### 9.2 관리자 응답과 공개 응답의 처리가 다르다 + +| 응답 | 고아 항목 | 이유 | +| --- | --- | --- | +| 관리자 설정 조회 | **포함** | 운영자가 그 항목이 남아 있음을 확인하고 지울 수 있어야 한다. 화면은 `_orphaned` 를 읽어 편집 불가로 표시한다 | +| 공개(소비) 조회 | **제거** | 공급 확장이 더 이상 제공하지 않는 항목이다. 내보내면 사용자가 선택할 수 있게 된다 | + +```php +public function getPublicPaymentSettings(): array +{ + $orderSettings = $this->getSettings('order_settings'); + + if (isset($orderSettings['payment_methods']) && is_array($orderSettings['payment_methods'])) { + $orderSettings['payment_methods'] = array_values(array_filter( + $orderSettings['payment_methods'], + fn ($method) => ! ($method['_orphaned'] ?? false) + )); + } + + return $orderSettings; +} +``` + +`array_values()` 로 인덱스를 재정렬한다. 중간 항목을 지우면 키가 비연속이 되고, 그 배열은 JSON 객체로 직렬화되어 화면의 반복 렌더가 깨진다. + +### 9.3 차단 지점은 공개 API 한 곳이다 + +소비 화면(레이아웃 JSON)의 필터에 맡기지 않는다. 같은 데이터를 그리는 템플릿이 여러 개면 필터가 화면 수만큼 복제되고, 한 곳만 빠져도 같은 결함이 그 화면에서만 남는다. + +같은 데이터를 내보내는 공개 엔드포인트가 둘 이상이면 **전부 같은 공개 게터를 경유**해야 한다. 한쪽이 raw `getSettings()` 를 쓰면 그 경로만 조용히 뚫린다. + +```php +// ❌ 엔드포인트마다 다른 게터 — checkout 경로만 고아 항목이 새어 나간다 +$orderSettings = $this->settingsService->getSettings('order_settings'); + +// ✅ 공개 엔드포인트는 모두 공개 게터를 경유 +$orderSettings = $this->settingsService->getPublicPaymentSettings(); +``` + +### 9.4 진단 + +이 결함은 예외도 경고도 로그도 남기지 않는다. 관리자 화면은 고아 표시로 정상 차단하고 있어, 관리자 응답과 공개 응답을 나란히 놓고 항목 수를 비교하기 전에는 드러나지 않는다. + +```bash +# 두 응답의 항목 id 목록이 다르면, 그 차이가 고아 항목이다 +GET /api/modules/{id}/admin/settings # 고아 포함 (정상) +GET /api/modules/{id}/settings/payment # 고아 제외 (정상) +``` + +--- + +## 10. 관련 문서 - [모듈 기초](module-basics.md) - 모듈 구조, AbstractModule - [모듈 라우트](module-routing.md) - API 라우트 규칙 diff --git a/modules/_bundled/sirsoft-ecommerce/CHANGELOG.md b/modules/_bundled/sirsoft-ecommerce/CHANGELOG.md index 5fcaf85b..c0d36991 100644 --- a/modules/_bundled/sirsoft-ecommerce/CHANGELOG.md +++ b/modules/_bundled/sirsoft-ecommerce/CHANGELOG.md @@ -97,6 +97,11 @@ ### Fixed +- 기본 통화를 바꾼 뒤 통화 설정을 저장한 상점에서, 결제창에 청구되는 금액이 주문서에 표시된 금액과 다르게 넘어가던 문제를 수정했습니다. 이전 기본 통화가 기본 통화 표시를 계속 유지해 상점에 기본 통화가 둘로 인식됐고, 그 통화의 환율이 1로 간주되어 환산 없이 청구됐습니다. 예를 들어 기본 통화를 엔화로 바꾼 상점에서 23,000엔 주문이 결제창에는 230원으로 넘어갔습니다. 이제 환율을 입력하지 않은 통화로는 결제가 진행되지 않고 미지원 통화로 안내됩니다. +- 같은 화면에서 상품별 금액과 총액의 다른 통화 표기가 서로 다른 기준으로 환산되던 문제를 함께 수정했습니다. 위 문제와 원인이 같으며, 주문서의 상품 금액과 총 결제금액의 외화 표기가 어긋나 보였습니다. +- 결제대행사 플러그인이 더 이상 제공하지 않는 결제수단이 주문서에 계속 노출되던 문제를 수정했습니다. 예를 들어 토스페이먼츠의 주문서형 결제를 끄면 관리자 환경설정에서는 해당 결제수단이 즉시 사용 불가로 바뀌는데, 주문서에서는 그대로 선택할 수 있었습니다. 플러그인을 삭제하거나 비활성화한 경우에도 동일했습니다. 이제 관리자 화면과 주문서가 같은 기준으로 판단합니다. +- 이커머스 환경설정 주문설정의 결제수단 목록에서, 결제대행사를 아직 고르지 않은 줄의 선택 상자가 지나치게 좁게 표시되던 문제를 수정했습니다. 선택 상자 폭이 선택된 값의 글자 수를 따라가 줄마다 항목 위치도 어긋나 있었습니다. 이제 결제대행사·재고 차감 시점·마일리지 차감 시점이 모든 줄에서 같은 폭으로 정렬됩니다. +- 같은 목록에서 더 이상 사용할 수 없는 결제수단(공급 플러그인을 지웠거나 끈 경우) 줄에 "마일리지 차감 시점" 항목만 남아 표시되던 문제를 수정했습니다. 다른 설정 항목은 모두 감춰지는데 이 항목만 남아 엉뚱한 위치에 보였고, 마일리지 기능을 사용하는 상점에서는 이미 쓸 수 없는 결제수단의 값을 바꿔 저장할 수도 있었습니다. 화면을 좁게 볼 때는 정상적으로 감춰지고 있어 넓은 화면에서만 나타났습니다. - 기본 통화가 원화가 아닌 상점에서 금액에 원화 단위가 붙던 문제를 수정했습니다. 마일리지 적립·사용·복원·소멸 내역, 결제금액 불일치 안내, 상품 일괄수정 요약, 할인코드 안내가 이제 상점에 설정된 통화의 단위로 표시됩니다. - 통합 검색 결과의 상품 가격이 상점 기본 통화가 아닌 원화 단위로 표기되던 문제를 수정했습니다. - 관리자에게 발송되는 신규 주문 알림의 금액이 구매자 알림과 달리 원화로 고정되던 문제를 수정했습니다. 이제 두 알림 모두 결제 통화로 표시됩니다. diff --git a/modules/_bundled/sirsoft-ecommerce/docs/api/settings.md b/modules/_bundled/sirsoft-ecommerce/docs/api/settings.md index 829e0abc..16fa1143 100644 --- a/modules/_bundled/sirsoft-ecommerce/docs/api/settings.md +++ b/modules/_bundled/sirsoft-ecommerce/docs/api/settings.md @@ -55,7 +55,7 @@ _단건 응답: `data` 객체의 필드._ | available_pg_providers | array | `[{"id":"kginicis","name_key":"sirsoft-pay_kginicis::provi…` | 설치된 PG 플러그인이 훅으로 등록한 PG 제공자 목록 (id·name_key·지원 결제수단) | | available_cash_receipt_providers | array | `[]` | 설치된 플러그인이 훅으로 등록한 현금영수증 발급 제공자 목록 (id·name_key — 미등록 시 빈 배열이며 신청 폼이 노출되지 않음) | | abilities | object | `{"can_update":true}` | 현재 사용자가 이 리소스에 수행 가능한 작업 불리언 맵 (can_update, can_delete 등 — 권한 맵 기반) | -| _meta | object | `{"limits":{"auto_cancel_days_min":1,"auto_cancel_days_max…` | | +| _meta | object | `{"limits":{"auto_cancel_days_min":1,"auto_cancel_days_max…` | 설정 화면 전용 메타. `limits` 는 숫자 입력의 경계값 맵(`config('sirsoft-ecommerce.limits')`)으로, 저장 규칙(FormRequest)과 같은 출처다 — 화면이 리터럴 경계를 들면 규칙 변경을 따라가지 못해 "화면은 받는데 저장은 422" 가 되므로 입력 min/max 는 이 값을 바인딩한다 | **응답 예시** @@ -1447,11 +1447,37 @@ Authorization: Bearer {YOUR_TOKEN} **응답 필드** (`data` 내부) - +_단건 응답: `data` 객체의 필드._ + +| 필드 | 타입 | 실측 예시값 | 용도/설명 | +| --- | --- | --- | --- | +| category | string | `"basic_info"` | 조회한 설정 카테고리 (path 파라미터를 그대로 반향) | +| settings | object | `{"shop_name":"","route_path":"shop","no_route":false}` | 해당 카테고리의 설정값. 구조는 카테고리마다 다르며 index 응답의 동명 최상위 키와 동일하다 (`order_settings` 조회 시 결제수단은 병합된 목록 — 공급 확장이 빠진 고아 항목 포함) | +| abilities | object | `{"can_update":true}` | 현재 사용자가 이 리소스에 수행 가능한 작업 불리언 맵 (can_update — 권한 맵 기반) | **응답 예시** - +```http +HTTP/1.1 200 +``` + +```json +{ + "success": true, + "message": "설정을 조회했습니다.", + "data": { + "category": "basic_info", + "settings": { + "shop_name": "", + "route_path": "shop", + "no_route": false + }, + "abilities": { + "can_update": true + } + } +} +``` **에러 응답** @@ -1491,7 +1517,7 @@ _단건 응답: `data` 객체의 필드._ | 필드 | 타입 | 실측 예시값 | 용도/설명 | | --- | --- | --- | --- | | shipping | object | `{"default_country":"KR","available_countries":[{"code":"K…` | 체크아웃용 배송 설정 (기본 국가·배송 가능 국가·무료배송·배송유형 등) | -| order_settings | object | `{"default_pg_provider":null,"cash_receipt_provider":"toss…` | 체크아웃용 주문/결제 설정 (기본 PG·활성 결제수단·무통장 계좌 등) | +| order_settings | object | `{"default_pg_provider":null,"cash_receipt_provider":"toss…` | 체크아웃용 주문/결제 설정 (기본 PG·활성 결제수단·무통장 계좌 등). `payment_methods` 는 현재 제공 가능한 결제수단만 포함하며, 공급 확장이 더 이상 제공하지 않는 결제수단(관리자 화면의 고아 항목)은 `is_active` 가 참이어도 제외된다 | **응답 예시** @@ -1626,7 +1652,7 @@ _단건 응답: `data` 객체의 필드._ | 필드 | 타입 | 실측 예시값 | 용도/설명 | | --- | --- | --- | --- | -| order_settings | object | `{"default_pg_provider":null,"cash_receipt_provider":"toss…` | 공개 가능한 결제 설정 (활성 결제수단·무통장 은행명 매핑 포함, 민감 정보 제외) | +| order_settings | object | `{"default_pg_provider":null,"cash_receipt_provider":"toss…` | 공개 가능한 결제 설정 (활성 결제수단·무통장 은행명 매핑 포함, 민감 정보 제외). `payment_methods` 는 현재 제공 가능한 결제수단만 포함하며, 공급 확장이 더 이상 제공하지 않는 결제수단(관리자 화면의 고아 항목)은 `is_active` 가 참이어도 제외된다 | **응답 예시** diff --git a/modules/_bundled/sirsoft-ecommerce/resources/js/__tests__/layouts/adminEcommerceSettingsOrder.test.tsx b/modules/_bundled/sirsoft-ecommerce/resources/js/__tests__/layouts/adminEcommerceSettingsOrder.test.tsx index 102ce34c..5509a6f9 100644 --- a/modules/_bundled/sirsoft-ecommerce/resources/js/__tests__/layouts/adminEcommerceSettingsOrder.test.tsx +++ b/modules/_bundled/sirsoft-ecommerce/resources/js/__tests__/layouts/adminEcommerceSettingsOrder.test.tsx @@ -426,6 +426,74 @@ describe('결제수단 Sortable 리스트 구조 검증 (_payment_methods_list.j expect(action.params['form.order_settings.payment_methods']).toContain('is_active'); }); + // ─── 필드 열 고정폭 (PG 셀렉트 폭 붕괴 회귀 차단) ─── + // 배경: Select 는 커스텀 드롭다운이라 className 이 내부 Button 에 붙는데, 컴포넌트 + // 기본 클래스의 w-full 이 CSS 출력 순서상 w-N 보다 뒤라 셀렉트에 직접 준 폭 토큰은 + // 무효가 된다(같은 특이도 → 후순위 승리). 그 결과 폭이 내용 폭을 따라가, PG 미선택 + // 상태('---')에서 74px 로 붕괴하고 선택값 길이에 따라 행마다 열 위치가 어긋났다. + // 폭은 열 컨테이너가 책임진다. + const FIELD_COLUMN_LABELS = [ + 'payment_methods.pg_provider', + 'payment_methods.stock_deduction_timing', + 'payment_methods.mileage_deduction_timing', + ]; + + /** 라벨 i18n 키로 필드 열 컨테이너를 찾는다. */ + const findFieldColumn = (labelKey: string) => + findFirst(tpl, (n: any) => + typeof n?.props?.className === 'string' + && n.props.className.includes('row-stack') + && Array.isArray(n?.children) + && n.children.some((c: any) => typeof c?.text === 'string' && c.text.includes(labelKey)), + ); + + it.each(FIELD_COLUMN_LABELS)('필드 열(%s)이 고정폭을 가져야 한다', (labelKey) => { + const column = findFieldColumn(labelKey); + expect(column).not.toBeNull(); + expect( + column.props.className, + `${labelKey} 열에 고정폭이 없으면 셀렉트 폭이 내용 폭을 따라가 미선택 상태에서 붕괴한다`, + ).toMatch(/\bw-\d+\b/); + }); + + it('세 필드 열이 동일한 폭 토큰을 사용해야 한다 (행 간 열 정렬)', () => { + const widths = FIELD_COLUMN_LABELS.map((labelKey) => { + const column = findFieldColumn(labelKey); + return (column.props.className.match(/\bw-\d+\b/) ?? [])[0]; + }); + expect(new Set(widths).size, `열 폭이 서로 다르면 행 간 열이 어긋난다: ${widths.join(', ')}`).toBe(1); + }); + + it('필드 열이 축소 가능해야 한다 (좁은 폭에서 행 넘침 차단)', () => { + // shrink-0 을 붙이면 고정폭 3열(총 432px)이 줄어들지 않아 좁은 뷰포트에서 + // 이름 열이 0 까지 붕괴하고도 행이 넘친다 (1100px 실측 17px 초과). + for (const labelKey of FIELD_COLUMN_LABELS) { + const column = findFieldColumn(labelKey); + expect(column.props.className, `${labelKey} 열`).not.toContain('shrink-0'); + } + }); + + it('필드 열의 Select 에는 폭 클래스를 주지 않아야 한다 (컴포넌트 기본 w-full 에 덮여 무효)', () => { + const selects = [ + 'pg_provider', + 'stock_deduction_timing', + 'mileage_deduction_timing', + ].map((field) => + findFirst(tpl, (n: any) => + n?.name === 'Select' && typeof n?.props?.value === 'string' + && n.props.value.includes(field), + ), + ); + + for (const select of selects) { + expect(select).not.toBeNull(); + expect( + select.props.className ?? '', + 'Select 에 준 w-N 은 컴포넌트 기본 w-full 에 덮여 무효 — 죽은 클래스가 폭을 지정한 것처럼 오해를 준다', + ).not.toMatch(/\bw-\d+\b/); + } + }); + it('고아 항목 삭제 버튼이 _orphaned 조건에서만 표시되어야 한다', () => { const deleteBtn = findFirst(tpl, (n: any) => n?.name === 'Button' && typeof n?.if === 'string' @@ -825,6 +893,91 @@ describe('마일리지 차감 시점 결제수단별 컨트롤', () => { }); }); +// ─── 고아 항목의 편집 컨트롤 차단 ─── + +describe('고아 결제수단 행의 편집 컨트롤 차단', () => { + // 고아 항목 = 저장값은 남아 있으나 공급 확장이 더 이상 제공하지 않는 결제수단 + // (플러그인 삭제·비활성, 또는 그 확장이 자기 기능 토글을 끈 경우). + // 이 행은 "지우세요" 만 제시해야 하므로 편집 컨트롤이 하나도 노출되면 안 된다. + // 삭제 버튼(Button)은 반대로 고아일 때만 나오는 것이 정상이라 대상에서 제외한다. + // + // 회귀 배경: 리스트 파셜의 마일리지 차감 시점 열만 가드가 빠져 있었다. 다른 열이 + // 사라지면서 그 열이 오른쪽으로 밀려 최소 주문금액 자리에 표시됐고, 마일리지 기능을 + // 켠 상점에서는 이미 사라진 결제수단의 값을 바꿔 저장할 수 있었다. 같은 화면의 + // 카드 파셜은 편집 영역을 하나의 가드 컨테이너로 감싸 정상 차단하고 있었다. + const EDIT_CONTROL_NAMES = ['Select', 'Input', 'Toggle', 'Checkbox', 'Textarea']; + + const ORPHAN_GUARD = '!$method._orphaned'; + + /** + * 편집 컨트롤마다 (조상 체인에 고아 가드가 있는가) 를 판정해 수집한다. + * + * 가드가 어느 깊이에 걸려 있든 통과시킨다 — 리스트는 열 컨테이너마다, 카드는 + * 편집 영역 전체를 감싼 컨테이너 한 곳에 걸려 있어 구조가 서로 다르기 때문이다. + * 열 목록을 손으로 열거하지 않으므로 이후 추가되는 열도 자동으로 검사 대상이 된다. + */ + function collectEditControls(node: any, guarded = false, acc: any[] = []): any[] { + if (!node || typeof node !== 'object') return acc; + + const nowGuarded = guarded + || (typeof node.if === 'string' && node.if.includes(ORPHAN_GUARD)); + + if (EDIT_CONTROL_NAMES.includes(node.name)) { + acc.push({ node, guarded: nowGuarded }); + } + + for (const child of node.children ?? []) { + collectEditControls(child, nowGuarded, acc); + } + if (node.itemTemplate) { + collectEditControls(node.itemTemplate, nowGuarded, acc); + } + return acc; + } + + /** 컨트롤을 사람이 읽을 수 있게 식별한다 (실패 메시지용). */ + function describeControl(entry: any): string { + const value = entry.node.props?.value ?? entry.node.props?.checked ?? ''; + return `${entry.node.name}(${String(value).slice(0, 60) || 'no-value'})`; + } + + it.each([ + ['리스트 파셜', paymentMethodsList], + ['카드 파셜', paymentMethodsCards], + ])('%s — 모든 편집 컨트롤이 고아 가드 아래에 있어야 한다', (_label, partial) => { + const controls = collectEditControls(partial); + + // 컨트롤을 하나도 못 찾았다면 탐색이 실패한 것이다 (부재 단언의 거짓 통과 차단) + expect(controls.length).toBeGreaterThan(0); + + const unguarded = controls.filter((c) => !c.guarded).map(describeControl); + expect( + unguarded, + `고아 행에 편집 컨트롤이 노출된다: ${unguarded.join(', ')} — 조상 체인 어딘가에 if "${ORPHAN_GUARD}" 가 필요하다`, + ).toEqual([]); + }); + + it('두 파셜이 같은 수의 편집 컨트롤을 가드해야 한다 (표시 방식 간 동작 일치)', () => { + const listGuarded = collectEditControls(paymentMethodsList).filter((c) => c.guarded); + const cardsGuarded = collectEditControls(paymentMethodsCards).filter((c) => c.guarded); + + // 넓은 화면(리스트)과 좁은 화면(카드)은 같은 데이터를 그린다. 한쪽만 가드가 빠지면 + // 창 너비에 따라 편집 가능 여부가 달라진다. + expect(listGuarded.length).toBeGreaterThan(0); + expect(cardsGuarded.length).toBeGreaterThan(0); + }); + + it('삭제 버튼은 고아일 때만 나오므로 편집 컨트롤 가드 대상이 아니다', () => { + const deleteBtn = findFirst(paymentMethodsList, (n: any) => + n?.name === 'Button' && typeof n?.if === 'string' + && n.if.includes('$method._orphaned') + && !n.if.includes(ORPHAN_GUARD), + ); + expect(deleteBtn).not.toBeNull(); + expect(EDIT_CONTROL_NAMES).not.toContain('Button'); + }); +}); + // ─── 다국어 키 종합 검증 ─── describe('다국어 키 종합 검증', () => { diff --git a/modules/_bundled/sirsoft-ecommerce/resources/layouts/admin/partials/admin_ecommerce_settings/_payment_methods_list.json b/modules/_bundled/sirsoft-ecommerce/resources/layouts/admin/partials/admin_ecommerce_settings/_payment_methods_list.json index c271da32..308a7764 100644 --- a/modules/_bundled/sirsoft-ecommerce/resources/layouts/admin/partials/admin_ecommerce_settings/_payment_methods_list.json +++ b/modules/_bundled/sirsoft-ecommerce/resources/layouts/admin/partials/admin_ecommerce_settings/_payment_methods_list.json @@ -111,11 +111,12 @@ ] }, { + "comment": "PG 열 고정폭 — Select 는 커스텀 드롭다운이라 className 이 내부 Button 에 붙는데, 컴포넌트 기본 클래스의 w-full 이 CSS 출력 순서상 w-N 보다 뒤라 셀렉트에 직접 준 폭은 무효가 된다. 폭은 열 컨테이너가 책임진다 (미선택 '---' 상태에서 74px 로 붕괴하던 회귀 차단 + 선택값 길이에 따라 행마다 열 위치가 어긋나던 문제 해소).", "type": "basic", "name": "Div", "if": "{{!$method._orphaned}}", "props": { - "className": "row-stack" + "className": "row-stack w-36" }, "children": [ { @@ -133,7 +134,7 @@ "if": "{{$method.pg_locked}}", "props": { "data-testid": "{{'pg-locked-badge-' + $method.id}}", - "className": "inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300" + "className": "inline-flex items-center px-2.5 py-0.5 rounded-full text-xs font-medium bg-gray-100 text-gray-600 dark:bg-gray-700 dark:text-gray-300 truncate" }, "text": "{{$t('sirsoft-ecommerce.admin.settings.order_settings.payment_methods.pg_fixed') + ' · ' + (((_local.form?.available_pg_providers ?? []).find(p => p.id === $method.pg_provider))?.name ? $localized(((_local.form?.available_pg_providers ?? []).find(p => p.id === $method.pg_provider)).name) : ($method.pg_provider ?? ''))}}" }, @@ -144,7 +145,6 @@ "props": { "data-testid": "{{'pg-select-' + $method.id}}", "value": "{{$method.pg_provider ?? ''}}", - "className": "w-36", "options": "{{[{value: '', label: '---'}].concat((_local.form?.available_pg_providers ?? []).filter(p => (p.supported_methods ?? []).includes($method.id)).map(p => ({value: p.id, label: $localized(p.name)})))}}", "disabled": "{{_computed.isReadOnly}}" }, @@ -187,7 +187,7 @@ "name": "Div", "if": "{{!$method._orphaned}}", "props": { - "className": "row-stack" + "className": "row-stack w-36" }, "children": [ { @@ -203,7 +203,6 @@ "name": "Select", "props": { "value": "{{$method.stock_deduction_timing ?? 'payment_complete'}}", - "className": "w-36", "options": [ { "value": "order_placed", @@ -237,8 +236,9 @@ { "type": "basic", "name": "Div", + "if": "{{!$method._orphaned}}", "props": { - "className": "row-stack" + "className": "row-stack w-36" }, "children": [ { @@ -254,7 +254,6 @@ "name": "Select", "props": { "value": "{{$method.mileage_deduction_timing ?? 'payment_complete'}}", - "className": "w-36", "options": [ { "value": "order_placed", diff --git a/modules/_bundled/sirsoft-ecommerce/src/Http/Controllers/Public/EcommerceSettingsController.php b/modules/_bundled/sirsoft-ecommerce/src/Http/Controllers/Public/EcommerceSettingsController.php index 2a5a1ce1..38d50d74 100644 --- a/modules/_bundled/sirsoft-ecommerce/src/Http/Controllers/Public/EcommerceSettingsController.php +++ b/modules/_bundled/sirsoft-ecommerce/src/Http/Controllers/Public/EcommerceSettingsController.php @@ -132,7 +132,7 @@ class EcommerceSettingsController extends PublicBaseController $this->logApiUsage('settings.checkout'); $shippingSettings = $this->settingsService->getSettings('shipping'); - $orderSettings = $this->settingsService->getSettings('order_settings'); + $orderSettings = $this->settingsService->getPublicPaymentSettings(); return ResponseHelper::moduleSuccess( 'sirsoft-ecommerce', diff --git a/modules/_bundled/sirsoft-ecommerce/src/Http/Resources/Traits/HasMultiCurrencyPrices.php b/modules/_bundled/sirsoft-ecommerce/src/Http/Resources/Traits/HasMultiCurrencyPrices.php index 5fde2e8c..f0eb37be 100644 --- a/modules/_bundled/sirsoft-ecommerce/src/Http/Resources/Traits/HasMultiCurrencyPrices.php +++ b/modules/_bundled/sirsoft-ecommerce/src/Http/Resources/Traits/HasMultiCurrencyPrices.php @@ -132,11 +132,27 @@ trait HasMultiCurrencyPrices /** * 기본 통화 코드를 반환합니다. * + * 기본 통화의 SSoT 는 설정의 `default_currency` 값이고 통화 항목의 `is_default` 는 그 파생입니다. + * 표시 계층이 `is_default` 를 먼저 훑으면, 저장본에 없어 defaults 에서 보충된 통화가 옛 플래그를 + * 달고 들어왔을 때 환산 계층(CurrencyConversionService::getDefaultCurrency)과 서로 다른 통화를 + * 기본으로 잡습니다. 같은 화면의 금액이 통화별로 어긋나므로 `default_currency` 를 먼저 해석합니다. + * * @return string 기본 통화 코드 (예: 'KRW') */ protected function getDefaultCurrencyCode(): string { $currencies = $this->getCurrencySettings(); + $settings = g7_module_settings('sirsoft-ecommerce', 'language_currency'); + $declared = $settings['default_currency'] ?? null; + + // 선언된 기본 통화가 통화 목록에 실재할 때만 채택 (삭제된 통화를 가리키는 설정 방어) + if ($declared !== null) { + foreach ($currencies as $currency) { + if (($currency['code'] ?? null) === $declared) { + return $declared; + } + } + } foreach ($currencies as $currency) { if ($currency['is_default'] ?? false) { @@ -144,10 +160,7 @@ trait HasMultiCurrencyPrices } } - // 설정이 없는 경우 모듈 설정에서 직접 조회 - $settings = g7_module_settings('sirsoft-ecommerce', 'language_currency'); - - return $settings['default_currency'] ?? 'KRW'; + return $declared ?? 'KRW'; } /** diff --git a/modules/_bundled/sirsoft-ecommerce/src/Services/EcommerceSettingsService.php b/modules/_bundled/sirsoft-ecommerce/src/Services/EcommerceSettingsService.php index 9590ab0f..246fd7d5 100644 --- a/modules/_bundled/sirsoft-ecommerce/src/Services/EcommerceSettingsService.php +++ b/modules/_bundled/sirsoft-ecommerce/src/Services/EcommerceSettingsService.php @@ -126,6 +126,12 @@ class EcommerceSettingsService implements ModuleSettingsInterface ); } + // 보충된 통화가 defaults 의 is_default 를 그대로 들여오면 기본 통화가 복수가 된다. + // is_default 의 SSoT 는 default_currency 이므로 병합 직후 전 항목을 재동기화한다. + if (isset($settings['language_currency'])) { + $settings['language_currency'] = $this->syncCurrencyDefaults($settings['language_currency']); + } + // 결제수단 병합 (기본 + 플러그인 필터 + 사용자 저장 설정) if (isset($settings['order_settings'])) { $settings['order_settings']['payment_methods'] = $this->getMergedPaymentMethods( @@ -188,14 +194,26 @@ class EcommerceSettingsService implements ModuleSettingsInterface } /** - * 공개 결제 설정 조회 (bank_accounts에 은행명 매핑 포함) + * 공개 결제 설정 조회 (고아 결제수단 제외 + bank_accounts에 은행명 매핑 포함) * - * @return array 은행명이 포함된 결제 설정 + * 고아 결제수단(저장은 되어 있으나 현재 available 카탈로그에 없는 항목)은 + * 공급 확장이 사라졌거나 그 확장이 해당 수단 제공을 중단한 상태다. 저장값의 + * is_active 는 그대로 남아 있으므로 걸러내지 않으면 체크아웃이 선택 가능한 + * 결제수단으로 계속 노출한다(관리자 화면은 _orphaned 를 읽어 이미 차단). + * + * @return array 고아 항목이 제거되고 은행명이 포함된 결제 설정 */ public function getPublicPaymentSettings(): array { $orderSettings = $this->getSettings('order_settings'); + if (isset($orderSettings['payment_methods']) && is_array($orderSettings['payment_methods'])) { + $orderSettings['payment_methods'] = array_values(array_filter( + $orderSettings['payment_methods'], + fn ($method) => ! ($method['_orphaned'] ?? false) + )); + } + if (isset($orderSettings['bank_accounts'], $orderSettings['banks'])) { $banks = collect($orderSettings['banks']); $orderSettings['bank_accounts'] = array_map(function ($account) use ($banks) { diff --git a/modules/_bundled/sirsoft-ecommerce/tests/Feature/Http/Controllers/Public/PaymentSettingsOrphanedMethodTest.php b/modules/_bundled/sirsoft-ecommerce/tests/Feature/Http/Controllers/Public/PaymentSettingsOrphanedMethodTest.php new file mode 100644 index 00000000..e1cc7e1d --- /dev/null +++ b/modules/_bundled/sirsoft-ecommerce/tests/Feature/Http/Controllers/Public/PaymentSettingsOrphanedMethodTest.php @@ -0,0 +1,96 @@ +storagePath = storage_path('framework/testing/modules/sirsoft-ecommerce/settings'); + + $this->saveOrderSettings([ + 'payment_methods' => [ + ['id' => 'card', 'sort_order' => 1, 'is_active' => true, 'min_order_amount' => 0, 'stock_deduction_timing' => 'payment_complete'], + ['id' => 'dbank', 'sort_order' => 3, 'is_active' => true, 'min_order_amount' => 0, 'stock_deduction_timing' => 'order_placed'], + [ + // 공급 플러그인이 더 이상 제공하지 않는 결제수단 (필터 미등록 → available 부재) + 'id' => self::ORPHANED_ID, + 'sort_order' => 121, + 'is_active' => true, + 'min_order_amount' => 0, + 'stock_deduction_timing' => 'payment_complete', + '_cached_name' => ['ko' => '카카오페이 (토스페이먼츠)', 'en' => 'KakaoPay (TossPayments)'], + '_cached_icon' => 'wallet', + '_cached_source' => 'plugin:sirsoft-tosspayments', + ], + ], + ]); + } + + protected function tearDown(): void + { + if (File::isDirectory($this->storagePath)) { + File::cleanDirectory($this->storagePath); + } + + parent::tearDown(); + } + + public function test_payment_endpoint_excludes_orphaned_method(): void + { + $response = $this->getJson(self::PAYMENT_ENDPOINT); + + $response->assertOk(); + $ids = array_column($response->json('data.order_settings.payment_methods'), 'id'); + + $this->assertNotContains(self::ORPHANED_ID, $ids); + $this->assertContains('card', $ids); + $this->assertContains('dbank', $ids); + } + + public function test_checkout_endpoint_excludes_orphaned_method(): void + { + $response = $this->getJson(self::CHECKOUT_ENDPOINT); + + $response->assertOk(); + $ids = array_column($response->json('data.order_settings.payment_methods'), 'id'); + + $this->assertNotContains(self::ORPHANED_ID, $ids); + $this->assertContains('card', $ids); + } + + /** + * order_settings.json 을 테스트 격리 경로에 기록합니다. + * + * @param array $settings 저장할 주문설정 배열 + */ + private function saveOrderSettings(array $settings): void + { + File::ensureDirectoryExists($this->storagePath); + File::put( + $this->storagePath.'/order_settings.json', + json_encode($settings, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) + ); + } +} diff --git a/modules/_bundled/sirsoft-ecommerce/tests/Playwright/specs/admin/payment-method-pg-locked.spec.ts b/modules/_bundled/sirsoft-ecommerce/tests/Playwright/specs/admin/payment-method-pg-locked.spec.ts index 3f307250..f0afb958 100644 --- a/modules/_bundled/sirsoft-ecommerce/tests/Playwright/specs/admin/payment-method-pg-locked.spec.ts +++ b/modules/_bundled/sirsoft-ecommerce/tests/Playwright/specs/admin/payment-method-pg-locked.spec.ts @@ -173,6 +173,81 @@ test.describe('@sirsoft-ecommerce 주문설정 결제수단 — PG 고정 표시 } }); + // @scenario extension_payment_method:pg_select_for_unlocked + // @effects admin_shows_pg_select_for_unlocked + test('PG 셀렉트는 미선택 상태에서도 형제 필드 열과 같은 폭으로 렌더된다', async ({ + page, + settingsToken, + }) => { + // 배경: Select 는 커스텀 드롭다운이라 레이아웃이 준 className 이 내부 button 에 붙는데, + // 컴포넌트 기본 클래스의 w-full 이 CSS 출력 순서상 w-N 보다 뒤라 폭 토큰이 무효가 됐다. + // 그 결과 폭이 내용 폭을 따라가 미선택('---') 상태에서 74px 로 붕괴했고, 선택값 길이에 + // 따라 행마다 열 위치가 어긋났다. 폭은 열 컨테이너가 책임진다. + // + // 측정 규율: 절대 픽셀값을 기대치로 박지 않는다 (폰트·테마·PG 구성에 따라 달라진다). + // 같은 행의 형제 필드 열과 **상대 비교**하고, 행 간 열 폭이 일치하는지를 본다. + await gotoOrderSettings(page, settingsToken); + + // 고정폭이 유지되는 넓은 뷰포트에서 측정한다. 좁은 폭에서는 세 필드 열이 함께 + // 비례 축소되므로(행 넘침 차단) 폭의 절대 일치가 성립하지 않는다. + await page.setViewportSize({ width: 1600, height: 1000 }); + + // 카탈로그 시드(gotoOrderSettings)와 DOM 렌더는 별개다 — 렌더를 기다리지 않으면 + // 측정 결과가 비어 skip 되고, 그 skip 이 거짓 통과가 된다. + await expect( + page.locator('[data-testid^="pg-select-"]').first(), + 'PG 선택 셀렉트가 렌더되지 않아 폭을 측정할 수 없다', + ).toBeVisible({ timeout: 30_000 }); + + const measured = await page.evaluate(() => { + const selects = Array.from(document.querySelectorAll('[data-testid^="pg-select-"]')); + const rows = selects + .map((el) => (el.parentElement as HTMLElement | null)?.parentElement ?? null) + .filter((r): r is HTMLElement => r !== null); + + return rows.map((row) => { + const columns = Array.from(row.children).filter((c) => + c.className.includes('row-stack'), + ) as HTMLElement[]; + const pgSelect = row.querySelector('[data-testid^="pg-select-"]'); + return { + id: pgSelect?.getAttribute('data-testid') ?? '', + label: (pgSelect?.querySelector('button') as HTMLElement | null)?.innerText.trim() ?? '', + columnWidths: columns.map((c) => Math.round(c.getBoundingClientRect().width)), + columnLefts: columns.map((c) => Math.round(c.getBoundingClientRect().left)), + }; + }); + }); + + // 여기까지 왔으면 셀렉트는 렌더된 상태다. 측정이 비었다면 DOM 탐색이 깨진 것이므로 + // skip 이 아니라 실패로 드러내야 한다 (skip 은 거짓 통과가 된다). + expect(measured.length, 'PG 셀렉트를 담은 행을 찾지 못했다 — 측정 경로가 깨졌다').toBeGreaterThan(0); + + for (const row of measured) { + const [pgWidth, ...siblingWidths] = row.columnWidths; + expect( + siblingWidths.length, + `${row.id} 행에서 비교할 형제 필드 열을 찾지 못했다 — 측정 경로가 깨졌다`, + ).toBeGreaterThan(0); + + // 셀렉트 열이 형제 필드 열보다 좁으면 내용 폭으로 붕괴한 것이다. + // (미선택 '---' 은 글자 폭이 가장 작아 회귀가 여기서 가장 크게 드러난다.) + const widest = Math.max(...siblingWidths); + expect( + pgWidth, + `${row.id}("${row.label}") 의 PG 열(${pgWidth}px)이 형제 필드 열(${widest}px)보다 좁다 — 셀렉트 폭이 내용 폭을 따라간 회귀`, + ).toBeGreaterThanOrEqual(widest); + } + + // 행마다 PG 열 폭이 다르면 선택값 길이가 레이아웃을 좌우한 것이다 + // (미선택 행만 좁아지거나, 긴 PG 명을 고른 행만 넓어진다). + const pgWidths = new Set(measured.map((r) => r.columnWidths[0])); + expect( + pgWidths.size, + `행마다 PG 열 폭이 다르다 (${[...pgWidths].join(' / ')}px) — 선택값 길이가 열 폭을 좌우하는 회귀`, + ).toBe(1); + }); + // @scenario extension_payment_method:no_pg_required // @effects admin_shows_pg_select_for_unlocked test('PG 불필요 수단(무통장·포인트 등)은 셀렉트도 배지도 없이 "PG 불필요"로 남는다', async ({ diff --git a/modules/_bundled/sirsoft-ecommerce/tests/Unit/Services/EcommerceSettingsCurrencyDefaultFlagTest.php b/modules/_bundled/sirsoft-ecommerce/tests/Unit/Services/EcommerceSettingsCurrencyDefaultFlagTest.php new file mode 100644 index 00000000..f5bac2db --- /dev/null +++ b/modules/_bundled/sirsoft-ecommerce/tests/Unit/Services/EcommerceSettingsCurrencyDefaultFlagTest.php @@ -0,0 +1,195 @@ +storagePath = storage_path('framework/testing/modules/sirsoft-ecommerce/settings'); + + if (File::isDirectory($this->storagePath)) { + File::cleanDirectory($this->storagePath); + } + + $this->service = new EcommerceSettingsService; + } + + protected function tearDown(): void + { + if (File::isDirectory($this->storagePath)) { + File::cleanDirectory($this->storagePath); + } + + parent::tearDown(); + } + + /** + * language_currency.json 을 직접 생성하여 저장된 통화 설정을 시뮬레이션합니다. + */ + private function saveLanguageCurrency(array $settings): void + { + File::ensureDirectoryExists($this->storagePath); + File::put( + $this->storagePath.'/language_currency.json', + json_encode($settings, JSON_PRETTY_PRINT | JSON_UNESCAPED_UNICODE) + ); + } + + /** + * 병합 결과에서 is_default 가 true 인 통화 코드 목록을 반환합니다. + */ + private function defaultCodes(): array + { + $this->service->clearCache(); + $lc = $this->service->getSettings('language_currency'); + + return collect($lc['currencies']) + ->filter(fn ($c) => ($c['is_default'] ?? false) === true) + ->pluck('code') + ->values() + ->all(); + } + + /** + * 병합 결과를 런타임과 동일하게 config 로 발행합니다. + * + * 실제 요청에서는 CoreServiceProvider 가 부팅 시 getAllSettings() 결과를 + * `g7_settings.modules.{id}` 에 넣고, 표시/환산 계층은 그 config 만 읽습니다. + * 테스트는 파일을 직접 쓰므로 같은 발행 단계를 재현해야 합니다. + */ + private function publishSettingsToConfig(): void + { + $this->service->clearCache(); + CurrencySettingsCache::clear(); + + Config::set( + 'g7_settings.modules.sirsoft-ecommerce.language_currency', + $this->service->getSettings('language_currency') + ); + } + + /** + * 운영 재현 저장본: 기본 통화를 JPY 로 바꾸고 JPY/USD 두 건만 저장한 상태. + */ + private function saveJpyBaseSubset(): void + { + $this->saveLanguageCurrency([ + 'default_currency' => 'JPY', + 'currencies' => [ + ['code' => 'JPY', 'name' => ['ja' => '円'], 'is_default' => true, 'decimal_places' => 0, 'base_unit' => 100, 'exchange_rate' => null], + ['code' => 'USD', 'name' => ['en' => 'Dollar'], 'is_default' => false, 'decimal_places' => 2, 'base_unit' => 1, 'exchange_rate' => 0.85], + ], + ]); + } + + // ────────────────────────────────────────────── + // 보충 통화의 is_default 기각 + // ────────────────────────────────────────────── + + public function test_backfilled_currency_default_flag_is_rejected(): void + { + // defaults 의 KRW 는 is_default: true 이며 저장본에 없어 보충 대상이 된다. + $this->saveJpyBaseSubset(); + + $this->assertSame(['JPY'], $this->defaultCodes(), '보충된 통화의 is_default 가 기각되지 않아 기본 통화가 복수입니다.'); + } + + public function test_default_currency_is_unique_across_all_saved_shapes(): void + { + $this->saveJpyBaseSubset(); + + $this->service->clearCache(); + $lc = $this->service->getSettings('language_currency'); + + $flags = collect($lc['currencies'])->map(fn ($c) => (bool) ($c['is_default'] ?? false)); + + $this->assertSame(1, $flags->filter()->count(), '기본 통화 플래그는 정확히 1개여야 합니다.'); + $this->assertSame('JPY', $lc['default_currency']); + } + + public function test_default_currency_absent_from_saved_list_is_promoted_when_backfilled(): void + { + // 기본 통화(CNY)가 저장본 currencies 에는 없어 보충 대상이 되는 경우 — + // 보충 항목의 플래그를 기각만 하면 기본 통화가 0개가 된다. + $this->saveLanguageCurrency([ + 'default_currency' => 'CNY', + 'currencies' => [ + ['code' => 'USD', 'name' => ['en' => 'Dollar'], 'is_default' => false, 'decimal_places' => 2, 'base_unit' => 1, 'exchange_rate' => 0.85], + ], + ]); + + $this->assertSame(['CNY'], $this->defaultCodes(), '보충된 기본 통화가 승격되지 않아 기본 통화가 사라졌습니다.'); + } + + public function test_nothing_saved_keeps_defaults_base_currency(): void + { + // 저장본 없음(신규 설치) → defaults 의 default_currency(KRW) 유지 + $this->assertSame(['KRW'], $this->defaultCodes()); + } + + // ────────────────────────────────────────────── + // 기본 통화 해석 SSoT (표시 계층 ↔ 환산 계층 일치) + // ────────────────────────────────────────────── + + public function test_display_layer_resolves_same_base_currency_as_conversion_layer(): void + { + $this->saveJpyBaseSubset(); + $this->publishSettingsToConfig(); + + $resource = new class + { + use HasMultiCurrencyPrices { + getDefaultCurrencyCode as public exposedDefaultCurrencyCode; + getDefaultBaseUnit as public exposedDefaultBaseUnit; + } + }; + + $resource::clearCurrencySettingsCache(); + $conversion = new CurrencyConversionService; + + $this->assertSame('JPY', $resource->exposedDefaultCurrencyCode(), '표시 계층이 기본 통화를 오인했습니다.'); + $this->assertSame('JPY', $conversion->getDefaultCurrency()); + $this->assertSame(100, $resource->exposedDefaultBaseUnit(), '표시 계층의 환산 분모가 기본 통화 base_unit 과 다릅니다.'); + $this->assertSame(100, $conversion->getDefaultBaseUnit()); + } + + public function test_unconfigured_exchange_rate_currency_is_not_treated_as_base(): void + { + // KRW 는 환율 미입력(null) 상태로 보충된다. 기본 통화로 오인되면 환율이 1.0 으로 + // 박제되어 PG 청구가 base 금액의 1/base_unit 으로 나간다(#543). + $this->saveJpyBaseSubset(); + $this->service->clearCache(); + + $lc = $this->service->getSettings('language_currency'); + $krw = collect($lc['currencies'])->firstWhere('code', 'KRW'); + + $this->assertFalse((bool) ($krw['is_default'] ?? false)); + $this->assertNull($krw['exchange_rate'], '환율 미입력 통화는 null 로 남아 미지원 통화 차단에 걸려야 합니다.'); + } +} diff --git a/modules/_bundled/sirsoft-ecommerce/tests/Unit/Services/EcommerceSettingsOrderSettingsTest.php b/modules/_bundled/sirsoft-ecommerce/tests/Unit/Services/EcommerceSettingsOrderSettingsTest.php index 99b46c3f..b729ab92 100644 --- a/modules/_bundled/sirsoft-ecommerce/tests/Unit/Services/EcommerceSettingsOrderSettingsTest.php +++ b/modules/_bundled/sirsoft-ecommerce/tests/Unit/Services/EcommerceSettingsOrderSettingsTest.php @@ -473,6 +473,57 @@ class EcommerceSettingsOrderSettingsTest extends ModuleTestCase $this->assertEquals('tosspayments', $lastMethod['id']); } + /** + * 공개 결제 설정에서는 고아 결제수단이 제거되어야 한다. + * + * 회귀 배경: 토스페이먼츠 플러그인의 주문서형 결제를 끄면 toss_* 결제수단이 + * available 카탈로그에서 빠지지만 저장값의 is_active 는 true 로 남는다. + * 관리자 화면은 _orphaned 를 읽어 차단하는데 체크아웃은 is_active 만 보므로, + * 서버가 걸러주지 않으면 비활성화된 결제수단이 그대로 선택 가능했다. + */ + public function test_public_payment_settings_exclude_orphaned_methods(): void + { + $savedSettings = [ + 'payment_methods' => [ + ['id' => 'card', 'sort_order' => 1, 'is_active' => true, 'min_order_amount' => 0, 'stock_deduction_timing' => 'payment_complete'], + ['id' => 'dbank', 'sort_order' => 3, 'is_active' => true, 'min_order_amount' => 0, 'stock_deduction_timing' => 'order_placed'], + [ + 'id' => 'toss_kakaopay', + 'sort_order' => 121, + 'is_active' => true, + 'min_order_amount' => 0, + 'stock_deduction_timing' => 'payment_complete', + '_cached_name' => ['ko' => '카카오페이 (토스페이먼츠)', 'en' => 'KakaoPay (TossPayments)'], + '_cached_icon' => 'wallet', + '_cached_source' => 'plugin:sirsoft-tosspayments', + ], + ], + ]; + + $this->saveOrderSettings($savedSettings); + $this->service->clearCache(); + + // 플러그인 필터 미등록 → toss_kakaopay 는 available 에 없다(주문서형 결제 OFF 와 동일 상태) + $adminMethods = $this->service->getSettings('order_settings')['payment_methods']; + $adminToss = collect($adminMethods)->firstWhere('id', 'toss_kakaopay'); + $this->assertNotNull($adminToss, '관리자 응답에는 고아 항목이 남아 있어야 한다(삭제 UI 필요)'); + $this->assertTrue($adminToss['_orphaned'] ?? false); + + $publicMethods = $this->service->getPublicPaymentSettings()['payment_methods']; + $publicIds = array_column($publicMethods, 'id'); + + $this->assertNotContains('toss_kakaopay', $publicIds); + $this->assertContains('card', $publicIds); + $this->assertContains('dbank', $publicIds); + + // 리스트 인덱스가 재정렬되어야 한다 (JSON 직렬화 시 객체가 되지 않도록) + $this->assertSame(range(0, count($publicMethods) - 1), array_keys($publicMethods)); + + foreach ($publicMethods as $method) { + $this->assertArrayNotHasKey('_orphaned', $method); + } + } + // ────────────────────────────────────────────── // _cached_* 메타데이터 스냅샷 // ────────────────────────────────────────────── diff --git a/plugins/_bundled/sirsoft-tosspayments/dist/js/plugin.iife.js b/plugins/_bundled/sirsoft-tosspayments/dist/js/plugin.iife.js index c5d1054a..9a213a4d 100644 --- a/plugins/_bundled/sirsoft-tosspayments/dist/js/plugin.iife.js +++ b/plugins/_bundled/sirsoft-tosspayments/dist/js/plugin.iife.js @@ -1 +1,2 @@ -(function(){"use strict";function b(t){return new Promise((r,o)=>{if(document.querySelector(`script[src="${t}"]`)){r();return}const e=document.createElement("script");e.src=t,e.async=!0,e.onload=()=>r(),e.onerror=()=>o(new Error(`Failed to load script: ${t}`)),document.head.appendChild(e)})}function C(t,r){if(!t.order_sheet_mode||!r)return{method:"CARD",easyPay:null};const o=(t.enabled_methods??[]).find(e=>e.id===r);return o?{method:o.method,easyPay:o.easy_pay_provider}:{method:"CARD",easyPay:null}}function p(t){if(t==="on")return!0;if(t==="off")return!1}function E(t,r){const o={validHours:t.vbank?.valid_hours??24},e=t.vbank?.cash_receipt_type??"";e&&(o.cashReceipt={type:e});const s=p(t.use_escrow);return s!==void 0&&(o.useEscrow=s),o}function w(t,r,o){if(r.use_escrow==="off")return;const e=o.escrow_products??[];e.length>0&&(t.escrowProducts=e)}async function A(t,r){const o=t.params||{},{pgPaymentData:e}=o;if(!e){console.error("[sirsoft-tosspayments] pgPaymentData is required");return}const s=window.G7Core,l=o.paymentMethod??s?.state?.getLocal?.()?.paymentMethod;try{const n=await s.api.get("/modules/sirsoft-ecommerce/payments/client-config/tosspayments");if(!n.data){console.error("[sirsoft-tosspayments] Failed to fetch client config",n);return}const a=n.data;if(window.TossPayments||await b(a.sdk_url),window.TossPayments||await new Promise(u=>setTimeout(u,100)),!window.TossPayments){console.error("[sirsoft-tosspayments] TossPayments SDK not available");return}const R=window.TossPayments(a.client_key).payment({customerKey:e.customer_key??window.TossPayments.ANONYMOUS}),f=e.currency??"KRW",{method:d,easyPay:y}=C(a,l);if(f!=="KRW"&&(d!=="CARD"||y!==null)){console.warn("[sirsoft-tosspayments] non-KRW currency supports card only",{currency:f,method:d}),s?.state?.setLocal?.({paymentErrorMessage:s?.t?.("sirsoft-tosspayments.errors.non_krw_method")??"This payment method is available for KRW only.",isSubmittingOrder:!1}),s?.modal?.open?.("tosspayments_payment_error_modal");return}const v=window.location.origin,c={method:d,amount:{currency:f,value:e.amount},orderId:e.order_number,orderName:e.order_name,successUrl:v+a.callback_urls.success,failUrl:v+a.callback_urls.fail,customerEmail:e.customer_email??void 0,customerName:e.customer_name??void 0,customerMobilePhone:e.customer_phone??void 0};if(d==="CARD")c.card={flowMode:"DEFAULT",useCardPoint:!1,useAppCardOnly:!1},y&&(c.easyPay={provider:y});else if(d==="VIRTUAL_ACCOUNT")c.virtualAccount=E(a,e),w(c,a,e);else if(d==="TRANSFER"){const u=p(a.use_escrow);u!==void 0&&(c.transfer={useEscrow:u}),w(c,a,e)}await R.requestPayment(c)}catch(n){if(console.error("[sirsoft-tosspayments] requestPayment error",n),n?.code==="USER_CANCEL"){console.info("[sirsoft-tosspayments] Payment cancelled by user");try{await s.api.post(`/modules/sirsoft-ecommerce/orders/${e.order_number}/cancel-payment`,{cancel_code:n.code,cancel_message:n.message})}catch(P){console.warn("[sirsoft-tosspayments] Failed to record cancellation",P)}s?.state?.setLocal?.({isSubmittingOrder:!1}),s?.modal?.open?.("tosspayments_payment_cancel_modal");return}const a=n?.message??"Unknown error";s?.state?.setLocal?.({paymentErrorMessage:a,isSubmittingOrder:!1}),s?.modal?.open?.("tosspayments_payment_error_modal")}}const _={requestPayment:A},i="sirsoft-tosspayments",m={info:(...t)=>console.info(`[${i}]`,...t),warn:(...t)=>console.warn(`[${i}]`,...t),error:(...t)=>console.error(`[${i}]`,...t)};function h(){const t=window.G7Core;if(!t)return 0;const r=t.getActionDispatcher;if(typeof r!="function")return 0;const o=r();if(!o||typeof o.registerHandler!="function")return 0;let e=0;for(const[s,l]of Object.entries(_)){const n=`${i}.${s}`;o.registerHandler(n,l,{category:"plugin",source:i}),e++}return e}function g(){const t=()=>{const r=h();if(r>0){m.info(`${r} handler(s) registered`);return}let o=0;const e=50,s=setInterval(()=>{o++;const l=h();if(l>0){clearInterval(s),m.info(`${l} handler(s) registered (after ${o} retries)`);return}o>=e&&(clearInterval(s),m.warn("ActionDispatcher not available after timeout"))},100)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",t):t()}g(),window.__SirsoftTosspayments={identifier:i,handlers:Object.keys(_),initPlugin:g}})(); +(function(){"use strict";function b(t){return new Promise((r,o)=>{if(document.querySelector(`script[src="${t}"]`)){r();return}const e=document.createElement("script");e.src=t,e.async=!0,e.onload=()=>r(),e.onerror=()=>o(new Error(`Failed to load script: ${t}`)),document.head.appendChild(e)})}function C(t,r){if(!t.order_sheet_mode||!r)return{method:"CARD",easyPay:null};const o=(t.enabled_methods??[]).find(e=>e.id===r);return o?{method:o.method,easyPay:o.easy_pay_provider}:{method:"CARD",easyPay:null}}function p(t){if(t==="on")return!0;if(t==="off")return!1}function E(t,r){const o={validHours:t.vbank?.valid_hours??24},e=t.vbank?.cash_receipt_type??"";e&&(o.cashReceipt={type:e});const s=p(t.use_escrow);return s!==void 0&&(o.useEscrow=s),o}function w(t,r,o){if(r.use_escrow==="off")return;const e=o.escrow_products??[];e.length>0&&(t.escrowProducts=e)}async function R(t,r){const o=t.params||{},{pgPaymentData:e}=o;if(!e){console.error("[sirsoft-tosspayments] pgPaymentData is required");return}const s=window.G7Core,l=o.paymentMethod??s?.state?.getLocal?.()?.paymentMethod;try{const n=await s.api.get("/modules/sirsoft-ecommerce/payments/client-config/tosspayments");if(!n.data){console.error("[sirsoft-tosspayments] Failed to fetch client config",n);return}const a=n.data;if(window.TossPayments||await b(a.sdk_url),window.TossPayments||await new Promise(u=>setTimeout(u,100)),!window.TossPayments){console.error("[sirsoft-tosspayments] TossPayments SDK not available");return}const T=window.TossPayments(a.client_key).payment({customerKey:e.customer_key??window.TossPayments.ANONYMOUS}),f=e.currency??"KRW",{method:d,easyPay:y}=C(a,l);if(f!=="KRW"&&(d!=="CARD"||y!==null)){console.warn("[sirsoft-tosspayments] non-KRW currency supports card only",{currency:f,method:d}),s?.state?.setLocal?.({paymentErrorMessage:s?.t?.("sirsoft-tosspayments.errors.non_krw_method")??"This payment method is available for KRW only.",isSubmittingOrder:!1}),s?.modal?.open?.("tosspayments_payment_error_modal");return}const v=window.location.origin,c={method:d,amount:{currency:f,value:e.amount},orderId:e.order_number,orderName:e.order_name,successUrl:v+a.callback_urls.success,failUrl:v+a.callback_urls.fail,customerEmail:e.customer_email??void 0,customerName:e.customer_name??void 0,customerMobilePhone:e.customer_phone??void 0};if(d==="CARD")c.card={flowMode:"DEFAULT",useCardPoint:!1,useAppCardOnly:!1},y&&(c.card.flowMode="DIRECT",c.card.easyPay=y);else if(d==="VIRTUAL_ACCOUNT")c.virtualAccount=E(a,e),w(c,a,e);else if(d==="TRANSFER"){const u=p(a.use_escrow);u!==void 0&&(c.transfer={useEscrow:u}),w(c,a,e)}await T.requestPayment(c)}catch(n){if(console.error("[sirsoft-tosspayments] requestPayment error",n),n?.code==="USER_CANCEL"){console.info("[sirsoft-tosspayments] Payment cancelled by user");try{await s.api.post(`/modules/sirsoft-ecommerce/orders/${e.order_number}/cancel-payment`,{cancel_code:n.code,cancel_message:n.message})}catch(P){console.warn("[sirsoft-tosspayments] Failed to record cancellation",P)}s?.state?.setLocal?.({isSubmittingOrder:!1}),s?.modal?.open?.("tosspayments_payment_cancel_modal");return}const a=n?.message??"Unknown error";s?.state?.setLocal?.({paymentErrorMessage:a,isSubmittingOrder:!1}),s?.modal?.open?.("tosspayments_payment_error_modal")}}const _={requestPayment:R},i="sirsoft-tosspayments",m={info:(...t)=>console.info(`[${i}]`,...t),warn:(...t)=>console.warn(`[${i}]`,...t),error:(...t)=>console.error(`[${i}]`,...t)};function h(){const t=window.G7Core;if(!t)return 0;const r=t.getActionDispatcher;if(typeof r!="function")return 0;const o=r();if(!o||typeof o.registerHandler!="function")return 0;let e=0;for(const[s,l]of Object.entries(_)){const n=`${i}.${s}`;o.registerHandler(n,l,{category:"plugin",source:i}),e++}return e}function g(){const t=()=>{const r=h();if(r>0){m.info(`${r} handler(s) registered`);return}let o=0;const e=50,s=setInterval(()=>{o++;const l=h();if(l>0){clearInterval(s),m.info(`${l} handler(s) registered (after ${o} retries)`);return}o>=e&&(clearInterval(s),m.warn("ActionDispatcher not available after timeout"))},100)};document.readyState==="loading"?document.addEventListener("DOMContentLoaded",t):t()}g(),window.__SirsoftTosspayments={identifier:i,handlers:Object.keys(_),initPlugin:g}})(); +//# sourceMappingURL=plugin.iife.js.map diff --git a/plugins/_bundled/sirsoft-tosspayments/resources/js/__tests__/handlers/requestPayment.test.ts b/plugins/_bundled/sirsoft-tosspayments/resources/js/__tests__/handlers/requestPayment.test.ts index 78ffea7b..545eafa4 100644 --- a/plugins/_bundled/sirsoft-tosspayments/resources/js/__tests__/handlers/requestPayment.test.ts +++ b/plugins/_bundled/sirsoft-tosspayments/resources/js/__tests__/handlers/requestPayment.test.ts @@ -261,13 +261,28 @@ describe('requestPaymentHandler', () => { expect(capturedPayload.virtualAccount.cashReceipt).toEqual({ type: '소득공제' }); }); - it('간편결제 선택 시 CARD + easyPay provider', async () => { + it('간편결제 선택 시 CARD + card.easyPay 자체창 직행 (flowMode DIRECT)', async () => { setupSdk(baseConfig()); await requestPaymentHandler({ params: { pgPaymentData: pgData(), paymentMethod: 'toss_kakaopay' } }); + // 토스 v2 결제창 계약: 간편결제 자체창은 card 객체 안의 easyPay + flowMode DIRECT. + // top-level easyPay 키는 SDK 가 읽지 않아 통합결제창이 열린다 (회귀 pin). expect(capturedPayload.method).toBe('CARD'); - expect(capturedPayload.easyPay).toEqual({ provider: '카카오페이' }); + expect(capturedPayload.card.flowMode).toBe('DIRECT'); + expect(capturedPayload.card.easyPay).toBe('카카오페이'); + expect(capturedPayload.easyPay).toBeUndefined(); + }); + + it('일반 카드 선택 시 flowMode DEFAULT + easyPay 부재 (통합결제창)', async () => { + setupSdk(baseConfig()); + + await requestPaymentHandler({ params: { pgPaymentData: pgData(), paymentMethod: 'toss_card' } }); + + expect(capturedPayload.method).toBe('CARD'); + expect(capturedPayload.card.flowMode).toBe('DEFAULT'); + expect('easyPay' in capturedPayload.card).toBe(false); + expect(capturedPayload.easyPay).toBeUndefined(); }); it('에스크로 on 이면 가상계좌 useEscrow=true', async () => { diff --git a/plugins/_bundled/sirsoft-tosspayments/resources/js/handlers/requestPayment.ts b/plugins/_bundled/sirsoft-tosspayments/resources/js/handlers/requestPayment.ts index 85bb5cab..2b65c7f6 100644 --- a/plugins/_bundled/sirsoft-tosspayments/resources/js/handlers/requestPayment.ts +++ b/plugins/_bundled/sirsoft-tosspayments/resources/js/handlers/requestPayment.ts @@ -275,9 +275,12 @@ export async function requestPaymentHandler(action: any, _context?: any): Promis useCardPoint: false, useAppCardOnly: false, }; - // 간편결제(easyPay)는 CARD method 에 easyPay provider 를 실어 호출한다. + // 간편결제는 card 객체 안에 easyPay(간편결제사 코드) + flowMode DIRECT 로 + // 자체창을 직행 호출한다 (토스 v2 결제창 계약 — 카드사/간편결제 자체창 연동). + // top-level easyPay 키는 SDK 파라미터가 아니라서 무시되고 통합결제창이 열린다. if (easyPay) { - requestPayload.easyPay = { provider: easyPay }; + requestPayload.card.flowMode = 'DIRECT'; + requestPayload.card.easyPay = easyPay; } } else if (method === 'VIRTUAL_ACCOUNT') { // 가상계좌 — 에스크로 적용 대상 (escrowProducts 는 에스크로 사용 시 필수) diff --git a/public/build/core/layout-editor.min.js b/public/build/core/layout-editor.min.js index bb4e0c1a..56b70347 100644 --- a/public/build/core/layout-editor.min.js +++ b/public/build/core/layout-editor.min.js @@ -1,14 +1,14 @@ -var dM=Object.defineProperty;var cM=(dn,i,u)=>i in dn?dM(dn,i,{enumerable:!0,configurable:!0,writable:!0,value:u}):dn[i]=u;var Ti=(dn,i,u)=>cM(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 Di=Lt();Di.TranslationProvider;const tt=Di.useTranslation;Di.TranslationReactContext;function rt(){return typeof window>"u"?null:window.__g7Devtools??null}function Sl(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 Vh(){const e=rt();if(e?.clearEditorStateData)try{e.clearEditorStateData()}catch{}}function Uh(e){const t=rt();if(t?.trackEditorSampleMatch)try{t.trackEditorSampleMatch(e)}catch{}}function qh(){const e=rt();if(e?.clearEditorSampleData)try{e.clearEditorSampleData()}catch{}}function Gh(e){const t=rt();if(t?.trackEditorHistoryEntry)try{t.trackEditorHistoryEntry(e)}catch{}}function Yh(){const e=rt();if(e?.clearEditorHistoryData)try{e.clearEditorHistoryData()}catch{}}function Cl(e){const t=rt();if(t?.trackEditorSelection)try{t.trackEditorSelection(e)}catch{}}function Xh(){const e=rt();if(e?.clearEditorSelectionData)try{e.clearEditorSelectionData()}catch{}}function sr(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 Jh(){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 Zh(){const e=rt();if(e?.clearEditorDocumentData)try{e.clearEditorDocumentData()}catch{}}function Qh(e){const t=rt();if(t?.trackEditorSpecMerge)try{t.trackEditorSpecMerge(e)}catch{}}function Rh(){const e=rt();if(e?.clearEditorSpecMergeData)try{e.clearEditorSpecMergeData()}catch{}}function Ni(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 ey(){const e=rt();if(e?.clearEditorI18nData)try{e.clearEditorI18nData()}catch{}}function $l(e){const t=rt();if(t?.trackPageState)try{t.trackPageState(e)}catch{}}function ty(){const e=rt();if(e?.clearPageStateData)try{e.clearPageStateData()}catch{}}const El="g7le.routeTree.collapsed";function ny(){if(typeof window>"u")return!1;try{return window.localStorage?.getItem(El)==="1"}catch{return!1}}function oy(e){if(!(typeof window>"u"))try{window.localStorage?.setItem(El,e?"1":"0")}catch{}}function ry(e,t){return{templateIdentifier:e,routeTree:[],routesError:null,selectedRoute:null,isRouteTreeCollapsed:ny(),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 iy(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 sy(e,t){const n=iy(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 Il=u.createContext(null);function ay(e,t){const n=sy(e,t);return Sl(n,t.type),n}function ly({templateIdentifier:e,initialLocale:t,children:n}){const[o,r]=u.useReducer(ay,void 0,()=>{const a=ry(e,t);return Sl(a,void 0),a});u.useEffect(()=>{oy(o.isRouteTreeCollapsed)},[o.isRouteTreeCollapsed]);const s=u.useMemo(()=>({state:o,dispatch:r}),[o]);return u.createElement(Il.Provider,{value:s},n)}function Je(){const e=u.useContext(Il);if(!e)throw new Error("useLayoutEditor must be used within LayoutEditorProvider");return e}const Al=u.createContext(null);function dy({value:e,children:t}){return u.createElement(Al.Provider,{value:e},t)}function Ft(){return u.useContext(Al)}const zi=u.createContext(null);let cy=1;function uy({children:e,t}){const[n,o]=u.useState([]),r=u.useRef([]),[s,a]=u.useState({}),l=u.useCallback(b=>{const x=b.id??`editor-modal-${cy++}`,k={id:x,content:b.content,ariaLabel:b.ariaLabel??"",closeOnBackdrop:b.closeOnBackdrop??!0,closeOnEscape:b.closeOnEscape??!0,width:b.width??"auto",height:b.height??"auto",maxHeightRatio:b.maxHeightRatio??.85,draggable:b.draggable??!1,avoidRect:b.avoidRect,onClose:b.onClose};return o(w=>{const C=[...w.filter(E=>E.id!==x),k];return r.current=C,C}),x},[]),d=u.useCallback(b=>{o(x=>{const k=x.find(_=>_.id===b),w=x.filter(_=>_.id!==b);return r.current=w,k?.onClose&&queueMicrotask(()=>k.onClose?.()),w})},[]),c=u.useCallback(()=>{const b=r.current[r.current.length-1];b&&d(b.id)},[d]),p=u.useCallback(()=>{o(b=>{for(let x=b.length-1;x>=0;x--){const k=b[x];k?.onClose&&queueMicrotask(()=>k.onClose?.())}return r.current=[],[]})},[]),f=u.useCallback((b,x)=>{a(k=>{const w=r.current.find(C=>C.id===b),_=x??w?.ariaLabel??"";return{...k,[b]:_}})},[]),y=u.useCallback(b=>{a(x=>{if(!(b in x))return x;const k={...x};return delete k[b],k})},[]),g=u.useCallback(b=>{y(b),d(b)},[y,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:y,minimizedStack:h}),[l,g,c,m,n,f,y,h]);return u.createElement(zi.Provider,{value:v},e,u.createElement(fy,{minimized:s,onRestore:y,t,key:"__min_bar"}))}function yo(){const e=u.useContext(zi);if(!e)throw new Error("useEditorModal must be used within EditorModalProvider");return e}function py(){const e=u.useContext(zi);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(hy,{entry:s,depth:a,hidden:r.has(s.id),onClose:()=>n(s.id)},s.id))})}function fy({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 gy(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 Tl="clamp(16px, 6vh, 56px)";function hy({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 - (${Tl}) * 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 b=v.getBoundingClientRect(),x=gy(e.avoidRect,b.width,b.height);x&&d(x)},[e.id,e.draggable]);const f=u.useCallback(v=>{if(!e.draggable)return;const b=v.target;if(!b.closest("[data-modal-drag-handle]")||b.closest("button, a, input, textarea, select"))return;const k=c.current,w=k?.getBoundingClientRect(),_=l?.left??w?.left??0,C=l?.top??w?.top??0;p.current={startX:v.clientX,startY:v.clientY,baseLeft:_,baseTop:C};const E=T=>{const $=p.current;if(!$)return;const A=window.innerWidth,z=window.innerHeight,D=k?.offsetWidth??0,O=k?.offsetHeight??0;let M=$.baseLeft+(T.clientX-$.startX),B=$.baseTop+(T.clientY-$.startY);M=Math.min(Math.max(0,M),Math.max(0,A-D)),B=Math.min(Math.max(0,B),Math.max(0,z-O)),d({left:M,top:B})},S=()=>{p.current=null,window.removeEventListener("pointermove",E),window.removeEventListener("pointerup",S)};window.addEventListener("pointermove",E),window.addEventListener("pointerup",S)},[e.draggable,l]),y=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:Tl,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:y,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 wt({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 yy({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=x=>{p.current&&!p.current.contains(x.target)&&l(!1)},b=x=>{x.key==="Escape"&&l(!1)};return document.addEventListener("mousedown",v),document.addEventListener("keydown",b),()=>{document.removeEventListener("mousedown",v),document.removeEventListener("keydown",b)}},[a]);const f=o??[],y=f.some(v=>v.identifier!==e),g=!!r&&y,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 b=v.identifier===e;return i.jsxs("button",{type:"button",role:"option","aria-selected":b,"aria-current":b?"true":void 0,className:"g7le-toolbar__template-menu-item","data-testid":"g7le-toolbar-template-menu-item","data-identifier":v.identifier,"data-current":b?"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:b?"#eff6ff":"transparent",border:"none",borderRadius:6,cursor:b?"default":"pointer",textAlign:"left",outline:"none"},onMouseEnter:x=>{b||(x.currentTarget.style.background="#f1f5f9")},onMouseLeave:x=>{x.currentTarget.style.background=b?"#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:b?"✓":""}),i.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:2,minWidth:0},children:[i.jsx("span",{style:{fontWeight:600,color:b?"#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 by(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:y,templateVersion:g,templateList:m,onSwitchTemplate:h}=e,[v,b]=u.useState(!1),[x,k]=u.useState(!1),{t:w}=tt(),{state:_,dispatch:C}=Je(),[E,S]=u.useState(null);u.useEffect(()=>{const I=()=>{const F=window.__g7LayoutEditorHistory;S(F?{undo:F.undo,redo:F.redo,canUndo:!!F.canUndo,canRedo:!!F.canRedo}:null)};I();const P=window.setInterval(I,250);return()=>window.clearInterval(P)},[]);const T=()=>{C({type:"TOGGLE_ROUTE_TREE"})},$=()=>_.editMode==="base"?w("layout_editor.chrome.toolbar.mode_badge.base"):_.editMode==="modal"?w("layout_editor.chrome.toolbar.mode_badge.modal"):_.editMode==="extension"?w("layout_editor.chrome.toolbar.mode_badge.extension"):_.editMode==="iteration_item"?w("layout_editor.chrome.toolbar.mode_badge.iteration_item"):null,A=()=>{_.editMode==="base"?C({type:"EXIT_BASE_EDIT"}):_.editMode==="modal"?C({type:"EXIT_MODAL_EDIT"}):_.editMode==="extension"?C({type:"EXIT_EXTENSION_EDIT"}):_.editMode==="iteration_item"&&C({type:"EXIT_ITERATION_ITEM_EDIT"})},z=$(),D=_.editMode!=="route",O={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"},M={...O,backgroundColor:"#2563eb",color:"#ffffff",borderColor:"#2563eb",fontWeight:600},B={...O,borderColor:"#e2e8f0",backgroundColor:"#ffffff",color:"#0f172a"},N={backgroundColor:"#f1f5f9",color:"#0f172a",borderColor:"#cbd5e1"},H={backgroundColor:"#1d4ed8",borderColor:"#1d4ed8"},L={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":w("layout_editor.chrome.toolbar.toggle_route_tree"),title:w("layout_editor.chrome.toolbar.toggle_route_tree"),onClick:T,style:{...O,outline:"none",padding:"6px 10px",fontSize:16,lineHeight:1,color:"#64748b"},children:"☰"}),i.jsx(yy,{templateIdentifier:_.templateIdentifier,templateName:y,templateVersion:g,templateList:m,onSwitch:h}),z&&i.jsx("span",{className:"g7le-toolbar__mode-badge","data-testid":"g7le-toolbar-mode-badge","data-mode":_.editMode,style:{padding:"2px 8px",borderRadius:999,background:"#fef3c7",color:"#92400e",fontSize:11,fontWeight:600,border:"1px solid #fde68a"},children:z}),i.jsx("div",{style:{flex:1}}),i.jsxs(i.Fragment,{children:[i.jsx(wt,{"data-testid":"g7le-toolbar-undo","aria-label":w("layout_editor.chrome.toolbar.undo"),title:w("layout_editor.chrome.toolbar.undo"),disabled:!E?.canUndo,onClick:()=>E?.undo?.(),baseStyle:O,hoverStyle:N,style:{opacity:E?.canUndo?1:.4},children:"↶"}),i.jsx(wt,{"data-testid":"g7le-toolbar-redo","aria-label":w("layout_editor.chrome.toolbar.redo"),title:w("layout_editor.chrome.toolbar.redo"),disabled:!E?.canRedo,onClick:()=>E?.redo?.(),baseStyle:O,hoverStyle:N,style:{opacity:E?.canRedo?1:.4},children:"↷"}),i.jsxs(wt,{"data-testid":"g7le-toolbar-add-element","data-open":_.isPaletteOpen?"true":"false",disabled:!_.selectedRoute,onClick:()=>C({type:"TOGGLE_PALETTE"}),"aria-pressed":_.isPaletteOpen,baseStyle:O,hoverStyle:N,style:_.isPaletteOpen?{backgroundColor:"#eff6ff",color:"#1d4ed8",borderColor:"#93c5fd"}:void 0,children:["+ ",w("layout_editor.chrome.toolbar.add_element")]}),i.jsx(wt,{"data-testid":"g7le-toolbar-preview","data-previewing":x?"true":"false",disabled:!p||!_.selectedRoute?.layoutName||x,onClick:()=>{const I=p?.();I&&typeof I.then=="function"&&(k(!0),I.finally(()=>k(!1)))},baseStyle:O,hoverStyle:N,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"}}),w("layout_editor.chrome.toolbar.previewing")]}):i.jsxs(i.Fragment,{children:["👁 ",w("layout_editor.chrome.toolbar.preview")]})}),i.jsxs(wt,{"data-testid":"g7le-toolbar-versions",disabled:!f||!(_.selectedRoute?.layoutName||_.selectedRoute?.path?.startsWith("__extension__/")),onClick:()=>f?.(),"aria-label":w("layout_editor.chrome.toolbar.version_history"),title:w("layout_editor.chrome.toolbar.version_history"),baseStyle:O,hoverStyle:N,children:["🕘 ",w("layout_editor.chrome.toolbar.version_history")]}),i.jsxs(wt,{"data-testid":"g7le-toolbar-edit-code",disabled:!r,onClick:()=>r?.(),baseStyle:O,hoverStyle:N,children:["⟨/⟩ ",w("layout_editor.chrome.toolbar.edit_code")]}),i.jsxs(wt,{"data-testid":"g7le-toolbar-images",disabled:!s||!_.selectedRoute,onClick:()=>s?.(),baseStyle:O,hoverStyle:N,children:["🖼 ",w("layout_editor.chrome.toolbar.images")]}),i.jsxs(wt,{"data-testid":"g7le-toolbar-translations",disabled:!a||!_.selectedRoute,onClick:()=>a?.(),baseStyle:O,hoverStyle:N,children:["🌐 ",w("layout_editor.chrome.toolbar.translations")]}),i.jsxs(wt,{"data-testid":"g7le-toolbar-page-settings",disabled:!l||!_.selectedRoute||_.editMode==="extension"||_.editMode==="iteration_item",onClick:()=>l?.(),baseStyle:O,hoverStyle:N,children:["⚙ ",w("layout_editor.chrome.toolbar.page_settings")]}),i.jsxs(wt,{"data-testid":"g7le-toolbar-reset",disabled:!d||!n,onClick:()=>d?.(),"aria-label":w("layout_editor.chrome.toolbar.reset"),title:w("layout_editor.chrome.toolbar.reset"),baseStyle:O,hoverStyle:N,style:{opacity:n?1:.4},children:["↺ ",w("layout_editor.chrome.toolbar.reset")]}),i.jsx(wt,{"data-testid":"g7le-toolbar-save","data-dirty":n?"true":"false","data-saving":v?"true":"false",disabled:!t||v,onClick:()=>{const I=t?.();I&&typeof I.then=="function"&&(b(!0),I.finally(()=>b(!1)))},baseStyle:M,hoverStyle:H,style:{opacity:v?.7:n?1:.7},children:v?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"}}),w("layout_editor.chrome.toolbar.saving")]}):i.jsxs(i.Fragment,{children:["💾 ",w("layout_editor.chrome.toolbar.save")]})}),i.jsx(wt,{"data-testid":"g7le-toolbar-shortcuts",disabled:!c,onClick:()=>c?.(),"aria-label":w("layout_editor.shortcuts.title"),title:w("layout_editor.shortcuts.title"),baseStyle:O,hoverStyle:N,children:"⌨"}),i.jsxs(wt,{"data-testid":"g7le-toolbar-exit",disabled:!o,onClick:()=>o?.(),baseStyle:B,hoverStyle:L,children:["✕ ",w("layout_editor.chrome.toolbar.exit")]})]}),D&&i.jsxs(wt,{"data-testid":"g7le-toolbar-exit-alt-mode",onClick:A,baseStyle:B,hoverStyle:L,children:["← ",_.editMode==="base"&&w("layout_editor.chrome.toolbar.exit_base_edit"),_.editMode==="modal"&&w("layout_editor.chrome.toolbar.exit_modal_edit"),_.editMode==="extension"&&w("layout_editor.chrome.toolbar.exit_extension_edit"),_.editMode==="iteration_item"&&w("layout_editor.chrome.toolbar.exit_iteration_item_edit")]})]})}function ar(){if(typeof window>"u")return null;try{return window.localStorage?.getItem("auth_token")??null}catch{return null}}function je(e){const t={Accept:"application/json",...e??{}},n=ar();return n&&(t.Authorization=`Bearer ${n}`),t}function Mi(e){return encodeURIComponent(e)}async function Dl(e,t){const n=`/api/admin/templates/${Mi(e)}/layout-attachments?layout_name=${encodeURIComponent(t)}`;try{const o=await fetch(n,{method:"GET",headers:je(),credentials:"same-origin"}),r=await o.json().catch(()=>null);return!o.ok||!r?.success?{ok:!1,status:o.status,message:Li(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 Nl(e,t,n){const o=`/api/admin/templates/${Mi(e)}/layout-attachments`,r=new FormData;r.append("file",n),r.append("layout_name",t);try{const s=await fetch(o,{method:"POST",headers:je(),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:Li(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 zl(e){const t=`/api/admin/templates/layout-attachments/${Mi(String(e))}`;try{const n=await fetch(t,{method:"DELETE",headers:je(),credentials:"same-origin"}),o=await n.json().catch(()=>null);return!n.ok||o&&o.success===!1?{ok:!1,status:n.status,message:Li(o,n.status)}:{ok:!0,data:!0}}catch(n){return{ok:!1,status:0,message:n instanceof Error?n.message:"network error"}}}function Li(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 my(e){return e<1024?`${e} B`:e<1024*1024?`${Math.round(e/1024)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function vy(e){if(!e)return"";const t=e.match(/^(\d{4})-(\d{2})-(\d{2})/);return t?`${t[2]}-${t[3]}`:""}function Ml({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),[y,g]=u.useState(null),m=u.useRef(null),h=u.useCallback(async()=>{c("loading"),g(null);const x=await Dl(e,t);x.ok?(l(x.data),c("idle")):(g(x.message),c("error"))},[e,t]);u.useEffect(()=>{h()},[h]);const v=async x=>{const k=x.target.files?.[0];if(!k)return;f(!0),g(null);const w=await Nl(e,t,k);w.ok?(l(_=>[w.data,..._.filter(C=>C.id!==w.data.id)]),r?.()):g(w.message),f(!1),m.current&&(m.current.value="")},b=async x=>{if(!(typeof window<"u"&&typeof window.confirm=="function"?window.confirm(n("layout_editor.attachment_manager.delete_confirm")):!0))return;const w=await zl(x.id);w.ok?(l(_=>_.filter(C=>C.id!==x.id)),r?.()):g(w.message)};return i.jsxs("div",{className:"g7le-attachment-manager","data-testid":"g7le-attachment-manager",style:_y,children:[i.jsxs("div",{"data-modal-drag-handle":!0,style:xy,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:wy,"data-testid":"g7le-attachment-manager-close",children:"✕"})]}),i.jsx("div",{style:ky,children:i.jsxs("label",{style:Sy,"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"})]})}),y&&i.jsx("div",{style:Cy,"data-testid":"g7le-attachment-manager-error",children:y}),i.jsx("div",{style:$y,children:d==="loading"?i.jsx("div",{style:Ll,"data-testid":"g7le-attachment-manager-loading",children:n("layout_editor.attachment_manager.loading")}):a.length===0&&d!=="error"?i.jsx("div",{style:Ll,"data-testid":"g7le-attachment-manager-empty",children:n("layout_editor.attachment_manager.empty")}):i.jsx("div",{style:Ey,"data-testid":"g7le-attachment-grid",children:a.map(x=>i.jsxs("div",{style:Iy,"data-testid":`g7le-attachment-card-${x.id}`,children:[i.jsx("div",{style:{...Ay,backgroundImage:`url(${x.url})`}}),i.jsx("div",{style:Ty,title:x.original_name,children:x.original_name}),i.jsxs("div",{style:Dy,children:[my(x.size),x.created_at?` · ${vy(x.created_at)}`:""]}),i.jsxs("div",{style:Ny,children:[o&&i.jsx("button",{type:"button",onClick:()=>o(x.url),style:zy,"data-testid":`g7le-attachment-use-${x.id}`,children:n("layout_editor.attachment_manager.use_as_bg")}),i.jsx("button",{type:"button",onClick:()=>b(x),style:My,"data-testid":`g7le-attachment-delete-${x.id}`,children:"🗑"})]})]},x.id))})}),i.jsx("div",{style:Ly,children:i.jsx("button",{type:"button",onClick:s,style:Py,"data-testid":"g7le-attachment-manager-footer-close",children:n("layout_editor.attachment_manager.close")})})]})}const _y={display:"flex",flexDirection:"column",minHeight:0,flex:1},xy={display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #e2e8f0"},wy={border:"none",background:"transparent",fontSize:16,color:"#94a3b8",cursor:"pointer"},ky={padding:"10px 16px",borderBottom:"1px solid #f1f5f9",display:"flex",gap:8},Sy={padding:"6px 12px",fontSize:13,border:"1px solid #2563eb",borderRadius:6,background:"#fff",color:"#2563eb",cursor:"pointer",display:"inline-flex",alignItems:"center"},Cy={padding:"8px 16px",fontSize:12,color:"#b91c1c",background:"#fef2f2"},$y={padding:16,overflow:"auto",flex:1,minHeight:120},Ll={fontSize:13,color:"#94a3b8",textAlign:"center",padding:"32px 0"},Ey={display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(140px, 1fr))",gap:12},Iy={display:"flex",flexDirection:"column",gap:4,border:"1px solid #e2e8f0",borderRadius:8,padding:8},Ay={width:"100%",height:88,borderRadius:6,border:"1px solid #cbd5e1",backgroundSize:"cover",backgroundPosition:"center",backgroundColor:"#f8fafc"},Ty={fontSize:12,fontWeight:600,color:"#0f172a",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},Dy={fontSize:11,color:"#64748b"},Ny={display:"flex",gap:6,marginTop:2},zy={flex:1,padding:"4px 6px",fontSize:11,border:"1px solid #2563eb",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"},My={padding:"4px 8px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},Ly={padding:"10px 16px",borderTop:"1px solid #e2e8f0",display:"flex",justifyContent:"flex-end"},Py={padding:"6px 14px",fontSize:13,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"};function lr(e){return encodeURIComponent(e)}async function Oy(e,t,n){const o=new URLSearchParams;t&&o.set("layout_name",t);const r=o.toString(),s=`/api/admin/templates/${lr(e)}/custom-translations`+(r?`?${r}`:"");try{const a=await fetch(s,{method:"GET",headers:je(),credentials:"same-origin"}),l=await a.json().catch(()=>null);return!a.ok||!l?.success?{ok:!1,status:a.status,message:dr(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 By(e,t,n,o){const r=`/api/admin/templates/${lr(e)}/custom-translations/${t}`;try{const s=await fetch(r,{method:"PUT",headers:je({"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:dr(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 Wy(e,t){const n=`/api/admin/templates/${lr(e)}/custom-translations/${t}`;try{const o=await fetch(n,{method:"DELETE",headers:je(),credentials:"same-origin"}),r=await o.json().catch(()=>null);return!o.ok||r&&r.success===!1?{ok:!1,status:o.status,message:dr(r,o.status)}:{ok:!0,data:!0}}catch(o){return{ok:!1,status:0,message:o instanceof Error?o.message:"network error"}}}async function jy(e,t){const n=`/api/admin/templates/${lr(e)}/custom-translations`;try{const o=await fetch(n,{method:"DELETE",headers:je({"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:dr(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 Pl=/\$t:(custom\.[A-Za-z0-9_\-]+\.\d+)/g;function Hy(e){const t=new Set,n=o=>{if(typeof o=="string"){if(o.includes("$t:custom.")){let r;for(Pl.lastIndex=0;(r=Pl.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 dr(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,bo=Lt().createLogger,Pi=bo("EditorSpecLoader"),Fy=["controls","componentCapabilities","actionRecipes","conditionRecipes","pageSettings","initActionRecipes","errorRecipes","computedRecipes","loadingComponents"],Ky=["actionRecipes","initActionRecipes","errorRecipes","computedRecipes","loadingComponents"];function Ol(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 Vy(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&&Pi.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 Pi.warn("fetchOneSpec: fetch failed",s,a),null}}function Uy(e){return Ky.includes(e)}function qy(e,t){return e==null||typeof e!="object"?e:{...e,__source:t}}function Gy(e,t,n,o){const r=t[n];if(!r||typeof r!="object")return;const s=e[n]??{};if(o&&Uy(n)){const a={};for(const[l,d]of Object.entries(r))a[l]=qy(d,o);e[n]={...s,...a};return}e[n]={...s,...r}}function Yy(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 Xy(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 Jy(e,t){if(!t.states)return;const n=e.states??{},o=[...n.groups??[],...t.states.groups??[]];n.groups=o,e.states=n}function Zy(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 Qy(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 Ry(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 Bl(e,t,n){for(const o of Fy)Gy(e,t,o,n);Yy(e,t),Xy(e,t),Jy(e,t),Zy(e,t),Qy(e,t),Ry(e,t),t.version&&(e.version=t.version)}async function eb(e){const t=e.apiBaseUrl??"/api",n=e.fetcher??(typeof fetch<"u"?fetch:void 0);if(!n)return Pi.warn("loadEditorSpecBundle: fetch unavailable, returning null spec"),{spec:null,sampleGlobalSources:[]};const o=e.activeModuleIdentifiers??Ol("activeModules"),r=e.activePluginIdentifiers??Ol("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=>Vy(p.kind,p.id,t,n)));let l=null;const d=[],c={};if(e.coreSeed&&(l={},Bl(l,e.coreSeed,{kind:"core"})),s.forEach((p,f)=>{const y=a[f];if(!y)return;y.sampleGlobal&&typeof y.sampleGlobal=="object"&&d.push({id:p.id,kind:p.kind,sampleGlobal:y.sampleGlobal});const g=y.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={}),Bl(l,y,{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 Oi(e,t){return e?.componentCapabilities?.[t]??null}function Ct(e,t){return e?.controls?.[t]??null}function tb(e){return e?.initActionRecipes??{}}function nb(e){return e?.computedRecipes??{}}function ob(e){return e?.errorRecipes??{}}function rb(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 ib(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 Bi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function sb(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 ab(e){const t=e.find(n=>Bi(n));if(Bi(t))return Object.keys(t).slice(0,8)}function lb(e){return Object.keys(e).slice(0,8)}function db(e){const t=Object.entries(e);return t.length===0?!1:t.some(([,n])=>n===null||typeof n!="object")}function Wi(e,t,n,o,r){if(Array.isArray(e)){r(t,"array",`[${e.length}]`,ab(e));return}if(Bi(e)){if(t&&db(e)){const s=lb(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;Wi(a,l,n+1,o,r)}return}r(t,"scalar",sb(e))}function cb(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(Wl(d))||[];o.push({name:l.item_var,kind:"item",itemFields:c})}}return o}function Wl(e){return e.replace(/^\{\{|\}\}$/g,"").trim()}function ub(e){const t=new Map;for(const n of e)n.shape==="array"&&n.itemFields&&n.itemFields.length>0&&t.set(Wl(n.expression),n.itemFields);return t}function ji(e){const t=e.maxDepth??4,n=[];for(const o of e.dataSources??[])!o||typeof o.id!="string"||o.id.length===0||Wi(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"||Wi(o.tree,"",0,t,(r,s,a,l)=>{if(!r)return;const d=ib(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 pb=["$localized"];function fb(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(!pb.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 Ki(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 jl(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 Vi=/\{\{(?:[^}]|\}(?!\}))*\}\}/g;function In(e){const t=[];if(typeof e!="string"||e.length===0)return t;let n=0,o=0;const r=new RegExp(Vi.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 Ui(e){return typeof e!="string"?!1:new RegExp(Vi.source).test(e)}function hb(e){const t=new Set(e.map(o=>o.trim()));let n=0;for(;t.has(`p${n}`);)n+=1;return`p${n}`}function Hl(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 qi(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 Fl(e){return cr(e).map(t=>({bindingIndex:t.bindingIndex??0,expression:t.raw,parsed:t.parsed??null,isComplex:(t.parsed??null)===null}))}function ur(e){return typeof e!="string"?"":e.replace(new RegExp(Vi.source,"g")," ").replace(/\s+/g," ").trim()}const yb=/\$t:([a-zA-Z0-9._-]+)/g,Kl="custom.";function Gi(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(yb,(o,r)=>{if(r.startsWith(Kl))return o;const s=t(r);return s&&s!==r?s:o})).join(""):e}const Kn="(?:(?!\\|[a-zA-Z0-9_]+=).)*",bb=new RegExp(`^\\s*\\$t:([a-zA-Z0-9._-]+)((?:\\|[a-zA-Z0-9_]+=${Kn})*)`),mb=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 Vl=/\$(?:core|module|plugin)_settings:[a-zA-Z0-9._:-]+/g;function Ul(e){return typeof e=="string"&&new RegExp(Vl.source).test(e)}function vb(e){return typeof e!="string"?"":e.replace(/^\$(?:core|module|plugin)_settings:/,"").split(/[.:]/).filter(Boolean).pop()||e}function ql(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(Vl.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:vb(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=bb.exec(e);if(d&&!d[1].startsWith(Kl)){const g=d[1],m=d[2]??"",h=e.slice(d[0].length),v=new Map,b=new RegExp(mb.source,"g");let x;for(;(x=b.exec(m))!==null;)x[2]&&x[2].includes("{{")&&v.set(x[1],x[2]);const k=t?t(g):"";if(k&&k!==g&&!k.startsWith("$t:"))l=k.replace(/\{\{?([a-zA-Z0-9_]+)\}?\}/g,(w,_)=>{const C=v.get(_);return C?s(C):w});else return n;a=h}const c=Gi(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 Gl(e,t){return t.bindings.length?e+t.bindings.map((n,o)=>`|p${o}=${n}`).join(""):e}function Yl(e,t){const n=cr(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 Xl(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 Jl=new RegExp(`^\\s*\\$t:([a-zA-Z0-9._-]+)((?:\\|[a-zA-Z0-9_]+=${Kn})+)\\s*$`),xb=new RegExp(`\\|([a-zA-Z0-9_]+)=(${Kn})`,"g");function mt(e){if(typeof e!="string")return null;const t=Jl.exec(e);if(!t)return null;const n=t[1],o=t[2],r=[],s=new RegExp(xb.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 Zl(e){return typeof e=="string"&&Jl.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 wb(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 mo(e,t){if(typeof e!="string")return e;const n=new RegExp(`\\|${t}=${Kn}`);return e.replace(n,"")}function Ql(e,t){return typeof e!="string"?e:e.replace(new RegExp(`\\s*\\{\\{?${t}\\}?\\}\\s*`,"g")," ").replace(/\s+/g," ").trim()}function kb(e,t){const n=s=>cr(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 Rl(e){return e.__source?.kind==="base"}function ed(e){return e.__source?.kind==="partial"}function Sb(e){return e.__source?.kind==="route"}function pr(e,t){return e.__source?.kind!=="extension"?!1:t==null?!0:e.__source.extensionId!==t}function td(e){return e.type==="extension_point"}function Xi(e=[]){for(const t of e)if(t.iteration&&t.iteration.source!==void 0)return!0;return!1}function Cb(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:nd(e)}function nd(e){if(typeof e.text=="string"&&od(e.text)&&!$b(e.text))return!0;if(e.props&&typeof e.props=="object"){for(const t of Object.values(e.props))if(typeof t=="string"&&od(t))return!0}return!1}function od(e){return/\{\{[\s\S]*?\}\}/.test(e)}function $b(e){const t=mt(e);return t!==null&&t.key.startsWith("custom.")}function Eb(e,t){return e??t??null}function Ji(e,t,n){if(td(e))return!0;switch(t){case"route":return Rl(e)||ed(e)||pr(e);case"base":return pr(e);case"modal":return pr(e);case"extension":return pr(e,n)?!0:Rl(e)||Sb(e)||ed(e);default:return!1}}function et(e){return typeof e=="object"&&e!==null&&typeof e.responsive=="string"}function fr(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 gr(e,t){const n=e.responsive?.[t];return n&&Array.isArray(n.children)?n.children:[]}function We(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=gr(n,r.responsive);continue}if(r<0||r>=o.length||(n=o[r],!n))return null;o=Qt(n)}return n}function Ib(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=We(e,t.slice(0,-2));return a?{owner:a,children:gr(a,r.responsive),branchKey:r.responsive,index:o}:null}const s=We(e,t.slice(0,-1));return s?{owner:s,children:Qt(s),index:o}:null}function Zi(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 Qi(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=We(r,t.slice(0,-1));if(!p)return r;const f=gr(p,s.responsive),y=Math.max(0,Math.min(n,f.length)),g=[...f];return g.splice(y,0,o),Zi({owner:p,branchKey:s.responsive},g),r}const a=We(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 Ri(e,t){if(t.length===0)return e;const n=Rt(e),o=rd(n,t);if(!o||o.index<0||o.index>=o.children.length)return n;const r=[...o.children];return r.splice(o.index,1),Zi(o,r),n}function Ab(e,t,n,o){if(t.length===0||!n||et(t[t.length-1]))return e;const r=Rt(e),s=We(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 Tb(e,t,n){if(t.length===0||!n||et(t[t.length-1]))return e;const o=Rt(e),r=We(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 Db(e,t,n,o){if(t.length===0)return e;const r=We(e,t);if(!r||Nb(t,n))return e;const s=Rt(r),a=Ri(e,t),l=id(n,t);let d=o;const c=t.slice(0,-1);if(sd(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 sd(e,t){if(e.length!==t.length)return!1;for(let n=0;ne.length||sd(e,t)}function es(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}_${zb()}`}const n=Qt(e);return n.length>0&&(t.children=n.map(es)),t}function Ot(e,t,n){if(t.length===0)return n(e);const o=Rt(e),r=We(o,t);if(!r)return o;const s=n(r),a=rd(o,t);if(!a||a.index<0||a.index>=a.children.length)return o;const l=[...a.children];return l[a.index]=s,Zi(a,l),o}function zb(){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=Mb(n);o.length>0&&t.push(...o)}return t}function Mb(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 vo(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[y,g]of Object.entries(c))f[y]=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[y,g]of Object.entries(c))f[y]=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 ad="extension",Un="extensionless";function Lb(){const e=globalThis?.G7Config;if(globalThis?.__g7AssetUrlMode===Un)return Un;const n=e?.assetUrlMode;return n===Un||n===ad?n:e?.settings?.general?.asset_url_mode===Un?Un:ad}function Pb(){return Lb()===Un}function en(e,t,n,o){const r=e.replace(/\/+$/,""),s=t.replace(/^\.+/,""),a=Pb()?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 ld=/^\s*\$t:([a-zA-Z0-9._-]+)\s*$/,hr="custom.",Ob=/\{\{.*?\}\}/;function Bb(e){return!!(!e||e.iteration&&typeof e.iteration=="object")}function dd(e,t){const n=e?.text,o=typeof n=="string"?n:"";if(Bb(e)||typeof n!="string")return{sourceState:"plain_text",editable:!1,customKey:null,displayValue:o};const r=mt(o);if(r&&r.key.startsWith(hr)){const a=t?t(r.key):r.key;return{sourceState:"custom_key",editable:!0,customKey:r.key,displayValue:a,isParamKey:!0}}const s=ld.exec(o);if(s){const a=s[1];if(a.startsWith(hr)){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(Ob.test(o)){const a=ur(o),l=ld.exec(a);if(l&&l[1].startsWith(hr)){const f=l[1],y=t?t(f):f;return{sourceState:"custom_key",editable:!0,customKey:f,displayValue:y}}const d=Gi(o,t),c=ur(d),p=/\$t:[a-zA-Z0-9._-]+/.test(c);if(c.length>0){const f=Yi(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 Wb(){const{state:e}=Je(),t=Ft(),n=e.templateIdentifier,o=e.locale,r=e.selectedRoute?.layoutName??null,s=u.useCallback(p=>{try{const y=Pt.getInstance().translate(p,{templateId:n,locale:o});return y&&y!==p?y:""}catch{return""}},[n,o]),a=u.useCallback(p=>dd(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=We(g,p),h=dd(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};_o(n,o,h.customKey,f);const E=await yr(n,h.customKey,o,f);return E.kind==="error"?{kind:"error",message:E.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:Ni(f),timestamp:Date.now()}),{kind:"updated",translationKey:h.customKey})}const v=typeof m?.text=="string"?m.text:"",b=h.sourceState==="plain_with_binding",x=Gi(v,s),k=b?Xl(x):f,w=E=>b?Yl(E,v):E;t.patchLayout(E=>Ot({children:E},p,$=>({...$,text:f})).children??[]);const _=await qn(n,r,o,k);if(_.kind==="error"||!_.resource)return{kind:"error",message:_.message};const C=_.resource.translation_key;return _o(n,o,C,k),t.patchLayout(E=>Ot({children:E},p,$=>({...$,text:w(`$t:${C}`)})).children??[]),await tn(n,o),Et({op:"inline_edit_create_key",sourceState:h.sourceState,componentPath:at(p),translationKey:C,toLocale:o,valueLength:f.length,valueHash:Ni(f),timestamp:Date.now()}),{kind:"created",translationKey:C,id:_.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=We(g,p),h=typeof m?.text=="string"?m.text:"",v=mt(h);if(v&&v.key.startsWith(hr))return br(n,v.key,o,f),_o(n,o,v.key,f),t.markDirty?.(),{kind:"updated",translationKey:v.key};const b=Yi(h,s),x=ur(f.replace(/\{\{?p\d+\}?\}/g," ")).replace(/\s+/g," ").trim(),k=await qn(n,r,o,x);if(k.kind==="error"||!k.resource)return{kind:"error",message:k.message};const w=k.resource.translation_key,_=An(f),C=k.resource.values??{},E={[o]:f};for(const S of Object.keys(C)){if(S===o)continue;let T=C[S]??"";for(const $ of _)T=qi(T,$);E[S]=T}return xo(n,w,E),_o(n,o,w,f),t.patchLayout(S=>Ot({children:S},p,A=>({...A,text:Gl(`$t:${w}`,b)})).children??[]),t.markDirty?.(),await tn(n,o),_o(n,o,w,f),Et({op:"inline_edit_create_key",sourceState:"plain_with_binding",componentPath:at(p),translationKey:w,toLocale:o,valueLength:f.length,valueHash:Ni(f),timestamp:Date.now()}),{kind:"created",translationKey:w}},[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:je({"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 yr(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:je({"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:je()});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 _o(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 br(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 xo(e,t,n){for(const[o,r]of Object.entries(n))br(e,t,o,r)}function It(e,t){return nn.get(e)?.[t]}function jb(e){const t=nn.get(e);return t?{...t}:void 0}function Hb(){return nn.size>0}function cd(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 Fb(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:je({"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 ud(){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 Kb({locales:e}={}){const{t}=tt(),{state:n,dispatch:o}=Je();u.useEffect(()=>{window.__g7EditorContentLocale=n.locale},[n.locale]);const r=e??ud(),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 Vb=/\{\{?(p\d+)\}?\}/g;function Ub(e){const t=[];if(typeof e!="string"||e.length===0)return t;const n=new RegExp(Vb.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 Gb(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 mr({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(()=>qb(e),[e]),f=u.useRef(null),[y,g]=u.useState(null),[m,h]=u.useState(null),[v,b]=u.useState(null),x=u.useMemo(()=>p.map(B=>B.kind==="chip"?`c:${B.paramName}`:"t").join("|"),[p]),k=u.useRef(null),w=u.useRef([]),_=u.useRef(!1);u.useLayoutEffect(()=>{const B=_.current;_.current=!1,!(!B&&k.current===x)&&(k.current=x,p.forEach((N,H)=>{if(N.kind!=="text")return;const L=w.current[H];L&&L.textContent!==(N.text??"")&&(L.textContent=N.text??"")}))},[x,p,e]);const C=()=>{const B=f.current;if(!B)return e;const N=[];for(const H of Array.from(B.querySelectorAll("[data-seg]")))H.dataset.seg==="chip"?N.push(`{${H.dataset.param??""}}`):N.push(H.textContent??"");return N.join("")},E=()=>{l||t(C())},S=u.useRef(null),T=u.useRef(!1),$=(B,N)=>{if(!l){B.preventDefault(),B.stopPropagation(),S.current={param:N,pointerId:B.pointerId},T.current=!1,g(N);try{B.currentTarget.setPointerCapture(B.pointerId)}catch{}}},A=B=>{const N=S.current;if(!N||B.pointerId!==N.pointerId)return;T.current=!0;const H=O(B.clientX,B.clientY);H&&(h({slotIdx:H.slotIdx,offset:H.offset}),b(Xb(f.current,H.slotIdx,H.offset)))},z=(B,N)=>{if(B.stopPropagation(),T.current){T.current=!1;return}s?.(N)},D=B=>{const N=S.current;if(!N||B.pointerId!==N.pointerId)return;try{B.currentTarget.releasePointerCapture(B.pointerId)}catch{}S.current=null,T.current&&typeof setTimeout=="function"&&setTimeout(()=>{T.current=!1},0);const H=O(B.clientX,B.clientY);if(g(null),h(null),b(null),!H)return;const L=f.current;if(!L)return;const P=Array.from(L.querySelectorAll("[data-seg]")).map(G=>G.dataset.seg==="chip"?{kind:"chip",paramName:G.dataset.param??""}:{kind:"text",text:G.textContent??""}),F=Gb(P,N.param,H.slotIdx,H.offset);F!==e&&(_.current=!0,t(F))},O=(B,N)=>{const H=f.current;if(!H)return null;const L=Array.from(H.querySelectorAll("[data-seg]")),I=H.ownerDocument,P=I.elementFromPoint(B,N);let F=P?.closest('[data-seg="text"]');if(F)return{slotIdx:L.indexOf(F),offset:Yb(I,F,B,N)};const G=P?.closest('[data-seg="chip"]');if(G){const Y=L.indexOf(G),Z=G.getBoundingClientRect();if(B=0){const se=L[Y-1];return{slotIdx:Y-1,offset:(se.textContent??"").length}}if(Y+1({s:Y,i:Z})).filter(Y=>Y.s.dataset.seg==="text").pop();return V?{slotIdx:V.i,offset:(V.s.textContent??"").length}:null},M=()=>{l||!r||r(pd(f.current,e.length))};return u.useEffect(()=>{if(c)return c.current=()=>pd(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:Jb,children:[p.map((B,N)=>B.kind==="chip"?i.jsxs("span",{"data-seg":"chip","data-param":B.paramName,"data-testid":`g7le-chip-${a}-${B.paramName}`,contentEditable:!1,onPointerDown:H=>$(H,B.paramName??""),onPointerMove:A,onPointerUp:D,title:n("layout_editor.translation.placeholder_locked"),style:{...em,...y===B.paramName?tm:null,touchAction:"none"},children:[i.jsx("span",{"aria-hidden":"true",style:nm,children:"⠿"}),i.jsx("span",{"aria-hidden":"true",style:{marginRight:3},children:"🔗"}),i.jsx("span",{style:om,children:o?.[B.paramName??""]??B.paramName}),s&&!l&&i.jsx("button",{type:"button","data-testid":`g7le-chip-remove-${a}-${B.paramName}`,"aria-label":n("layout_editor.inline_binding.clear"),title:n("layout_editor.inline_binding.clear"),onPointerDown:H=>{H.stopPropagation(),H.preventDefault()},onClick:H=>z(H,B.paramName??""),style:rm,children:"✕"})]},`chip-${B.paramName}`):i.jsx("span",{ref:H=>{w.current[N]=H},"data-seg":"text",contentEditable:!l,suppressContentEditableWarning:!0,onInput:E,"data-testid":`g7le-chip-text-${a}-${N}`,style:{...Zb,...y?Qb:null,...m?.slotIdx===N?Rb:null}},`text-slot-${N}`)),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:im,children:["+ ",n("layout_editor.inline_binding.insert_data")]}),i.jsx("span",{style:sm,children:n("layout_editor.translation.placeholder_locked")})]})]})}function Yb(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 Xb(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 y=p.getClientRects(),g=y.length>0?y[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 pd(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 Jb={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},Zb={outline:"none",minWidth:8,minHeight:"1.2em",whiteSpace:"pre-wrap",color:"#0f172a",display:"inline-block"},Qb={boxShadow:"inset 0 -2px 0 #93c5fd",background:"#eff6ff",borderRadius:2},Rb={background:"#dbeafe",boxShadow:"inset 0 -2px 0 #2563eb"},em={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"},tm={opacity:.5,borderStyle:"solid",cursor:"grabbing"},nm={color:"#2563eb",opacity:.7,fontSize:11,marginRight:1,cursor:"grab"},om={textDecoration:"none"},rm={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"},im={fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#334155",padding:"3px 10px",cursor:"pointer"},sm={fontSize:10,color:"#94a3b8"};function fd(e){e&&(e.style.height="auto",e.style.height=`${Math.max(e.scrollHeight,28)}px`)}function am(e){fd(e)}function lm(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 dm({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,y]=u.useState("all"),[g,m]=u.useState(new Set),[h,v]=u.useState({}),[b,x]=u.useState(null),[k,w]=u.useState({}),_=u.useCallback(async()=>{d("loading"),p(null);const N=await Oy(e,t);N.ok?(a(N.data),v({}),m(new Set),w({}),d("idle")):(p(N.message),d("error"))},[e,t]);u.useEffect(()=>{_()},[_]);const C=u.useMemo(()=>lm(s),[s]),E=u.useMemo(()=>s.filter(N=>f==="all"?!0:N.status===f).slice().sort((N,H)=>{const L=N.updated_at?Date.parse(N.updated_at):0,I=H.updated_at?Date.parse(H.updated_at):0;return I!==L?I-L:H.id-N.id}),[s,f]),S=u.useMemo(()=>s.filter(N=>N.status==="orphaned"),[s]),T=u.useCallback(N=>{const H={...N.values??{}};for(const L of Object.keys(H)){const I=It(N.translation_key,L);I!==void 0&&(H[L]=I)}return H},[]),$=u.useCallback(N=>h[N.id]??T(N),[h,T]),A=u.useCallback((N,H,L)=>{v(I=>{const P=I[N]??s.find(F=>F.id===N)?.values??{};return{...I,[N]:{...P,[H]:L}}})},[s]),z=u.useCallback(async N=>{x(N.id),w(I=>({...I,[N.id]:""}));const H=$(N),L=await By(e,N.id,H,N.lock_version);if(L.ok)a(I=>I.map(P=>P.id===N.id?L.data:P)),v(I=>{const P={...I};return delete P[N.id],P});else{const I=L.status===409?n("layout_editor.translation_manager.conflict"):L.message;w(P=>({...P,[N.id]:I}))}x(null)},[e,$,n]),D=u.useCallback(N=>typeof window<"u"&&typeof window.confirm=="function"?window.confirm(n("layout_editor.translation_manager.delete_confirm",{count:N})):!0,[n]),O=u.useCallback(async N=>{if(!D(1))return;const H=await Wy(e,N.id);H.ok?(a(L=>L.filter(I=>I.id!==N.id)),m(L=>{const I=new Set(L);return I.delete(N.id),I})):p(H.message)},[e,D]),M=u.useCallback(async N=>{if(N.length===0||!D(N.length))return;const H=await jy(e,N);if(H.ok){const L=new Set(N);a(I=>I.filter(P=>!L.has(P.id))),m(new Set)}else p(H.message)},[e,D]),B=u.useCallback(N=>{m(H=>{const L=new Set(H);return L.has(N)?L.delete(N):L.add(N),L})},[]);return i.jsxs("div",{className:"g7le-translation-manager","data-testid":"g7le-translation-manager",style:cm,children:[i.jsxs("div",{"data-modal-drag-handle":!0,style:um,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:pm,"data-testid":"g7le-translation-manager-close",children:"✕"})]}),i.jsxs("div",{style:fm,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(N=>i.jsx("button",{type:"button",role:"tab","aria-selected":f===N,"data-active":f===N?"true":"false",onClick:()=>y(N),style:f===N?gm:gd,"data-testid":`g7le-translation-filter-${N}`,children:n(`layout_editor.translation_manager.filter_${N}`)},N))}),i.jsx("div",{style:{flex:1}}),g.size>0&&i.jsxs("button",{type:"button",onClick:()=>{M(Array.from(g))},style:hd,"data-testid":"g7le-translation-bulk-delete",children:["🗑 ",n("layout_editor.translation_manager.delete_selected",{count:g.size})]}),S.length>0&&i.jsxs("button",{type:"button",onClick:()=>{M(S.map(N=>N.id))},style:hd,"data-testid":"g7le-translation-purge-orphaned",children:["🧹 ",n("layout_editor.translation_manager.purge_orphaned",{count:S.length})]})]}),c&&i.jsx("div",{style:hm,"data-testid":"g7le-translation-manager-error",children:c}),i.jsx("div",{style:ym,children:l==="loading"?i.jsx("div",{style:yd,"data-testid":"g7le-translation-manager-loading",children:n("layout_editor.translation_manager.loading")}):E.length===0&&l!=="error"?i.jsx("div",{style:yd,"data-testid":"g7le-translation-manager-empty",children:n("layout_editor.translation_manager.empty")}):i.jsx("div",{"data-testid":"g7le-translation-list",style:bm,children:E.map(N=>{const H=$(N),L=N.status==="orphaned",I=o?o.has(N.translation_key):null;return i.jsxs("div",{style:mm,"data-testid":`g7le-translation-row-${N.id}`,children:[i.jsxs("div",{style:vm,children:[i.jsx("input",{type:"checkbox",checked:g.has(N.id),onChange:()=>B(N.id),"aria-label":n("layout_editor.translation_manager.select_aria",{key:N.translation_key}),"data-testid":`g7le-translation-select-${N.id}`}),i.jsx("code",{style:_m,children:N.translation_key}),L&&i.jsx("span",{style:xm,"data-testid":`g7le-translation-badge-orphaned-${N.id}`,children:n("layout_editor.translation_manager.badge_orphaned")}),I===!0&&i.jsx("span",{style:wm,"data-testid":`g7le-translation-badge-live-inuse-${N.id}`,children:n("layout_editor.translation_manager.badge_live_in_use")}),I===!1&&i.jsx("span",{style:km,"data-testid":`g7le-translation-badge-live-unused-${N.id}`,children:n("layout_editor.translation_manager.badge_live_unused")}),i.jsx("div",{style:{flex:1}}),i.jsx("button",{type:"button",onClick:()=>{O(N)},style:Tm,"data-testid":`g7le-translation-delete-${N.id}`,children:"🗑"})]}),i.jsxs("div",{style:Sm,children:[C.map(P=>{const F=H[P]??"",G=An(F).length>0;return i.jsxs("div",{style:Cm,"data-testid":`g7le-translation-field-${N.id}-${P}`,children:[i.jsxs("label",{style:$m,title:P,children:[Gn(P,n),i.jsxs("span",{style:Em,children:["(",P,")"]})]}),G?i.jsx("div",{style:{flex:1},"data-testid":`g7le-translation-chip-${N.id}-${P}`,children:i.jsx(mr,{value:F,onChange:V=>A(N.id,P,V),t:n,testIdSuffix:`${N.id}-${P}`})}):i.jsx("textarea",{value:F,rows:1,ref:am,onChange:V=>{A(N.id,P,V.currentTarget.value),fd(V.currentTarget)},style:Im,"data-testid":`g7le-translation-input-${N.id}-${P}`})]},P)}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("button",{type:"button",disabled:b===N.id,onClick:()=>{z(N)},style:Am,"data-testid":`g7le-translation-save-${N.id}`,children:b===N.id?n("layout_editor.translation_manager.saving"):n("layout_editor.translation_manager.save")}),k[N.id]?i.jsx("span",{style:{fontSize:11,color:"#dc2626"},"data-testid":`g7le-translation-row-error-${N.id}`,children:k[N.id]}):null]})]})]},N.id)})})}),i.jsx("div",{style:Dm,children:i.jsx("button",{type:"button",onClick:r,style:Nm,"data-testid":"g7le-translation-manager-footer-close",children:n("layout_editor.translation_manager.close")})})]})}const cm={display:"flex",flexDirection:"column",minHeight:0,flex:1},um={display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #e2e8f0"},pm={border:"none",background:"transparent",fontSize:16,color:"#94a3b8",cursor:"pointer"},fm={padding:"10px 16px",borderBottom:"1px solid #f1f5f9",display:"flex",gap:8,alignItems:"center"},gd={padding:"4px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},gm={...gd,borderColor:"#2563eb",background:"#eff6ff",color:"#1d4ed8",fontWeight:600},hd={padding:"4px 10px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},hm={padding:"8px 16px",fontSize:12,color:"#b91c1c",background:"#fef2f2"},ym={padding:16,overflow:"auto",flex:1,minHeight:120,display:"flex",flexDirection:"column",gap:12},yd={fontSize:13,color:"#94a3b8",textAlign:"center",padding:"32px 0"},bm={display:"flex",flexDirection:"column",gap:20},mm={border:"1px solid #e2e8f0",borderRadius:8,padding:10,display:"flex",flexDirection:"column",gap:6},vm={display:"flex",alignItems:"center",gap:8},_m={fontSize:11,background:"#f1f5f9",padding:"2px 6px",borderRadius:4,color:"#0f172a"},xm={fontSize:10,color:"#b45309",background:"#fef3c7",padding:"1px 6px",borderRadius:4,fontWeight:600},wm={fontSize:10,color:"#15803d",background:"#dcfce7",padding:"1px 6px",borderRadius:4,fontWeight:600},km={fontSize:10,color:"#9f1239",background:"#ffe4e6",padding:"1px 6px",borderRadius:4,fontWeight:600},Sm={display:"flex",flexDirection:"column",gap:6},Cm={display:"flex",alignItems:"flex-start",gap:8},$m={fontSize:12,color:"#475569",minWidth:88,fontWeight:600,paddingTop:4,display:"flex",flexDirection:"column",lineHeight:1.2},Em={fontSize:10,color:"#94a3b8",fontWeight:400},Im={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"},Am={padding:"5px 12px",fontSize:12,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"},Tm={padding:"4px 8px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},Dm={padding:"10px 16px",borderTop:"1px solid #e2e8f0",display:"flex",justifyContent:"flex-end"},Nm={padding:"6px 14px",fontSize:13,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"};function zm(){const e=Ft(),{state:t}=Je(),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?yr(o,c,p,f):null,[o]);return{raw:n,getValue:s,patch:a,createI18nKey:l,updateI18nKeyValue:d}}function Mm(e){const t=e.__source;return t&&(t.kind==="module"||t.kind==="plugin")&&t.identifier?`${t.kind}:${t.identifier}`:"template"}function bd(e,t){if(!t)return null;const n=Mm(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(Lm(r,s))return{value:a,match:{dataSourceId:e.id,resolvedBy:"spec_byEndpoint"}}}return null}function ts(e,t){const n=bd(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 Lm(e,t){const n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(e)}function Pm(e={}){const{spec:t,overrideSpec:n,onMatch:o}=e;return{has(r){return!0},resolve(r){const s=n?bd(r,n):null,{value:a,match:l}=s??ts(r,t);if(o)try{o(l)}catch{}return a}}}const md=Lt(),vd=md.DataBindingEngine,_d=md.dataBindingEngine;bo("PipeRegistry");function Om(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 vr(e){const t=e.trim(),n=/^\{\{([\s\S]*)\}\}$/.exec(t);return n?n[1].trim():t}function wd(e){const t=e.trim();return/^\{\{[\s\S]*\}\}$/.test(t)?t:`{{ ${t} }}`}function kd(e,t){const n={};for(const[r,s]of Object.entries(t))n[r]=typeof s=="string"?vr(s):s;const o=Wm(e.expr,n);return wd(o)}function jm(e,t){if(typeof e!="string")return null;const n=Sd(vr(e));for(const o of t){const r=Hm(n,o.expr,o.params);if(r)return{recipeId:o.id,params:r}}return null}function Sd(e){return e.replace(/\s+/g," ").trim()}function Cd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Hm(e,t,n){const o=[],r=new Set;let s="";const a=/\{(\w+)(\*?)\}(\s*\?\?\s*)?/g;let l=0,d;const c=Sd(t);for(;(d=a.exec(c))!==null;){const g=c.slice(l,d.index);s+=Cd(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+=Cd(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 y={};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(", ")),y[g]=h}),n.length>0){const g=new Set(n.map(m=>m.key));for(const m of Object.keys(y))g.has(m)||delete y[m]}return y}function Fm(e){const t=`x.${e.field}`,n=Km(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 Km(e){const t=e.trim();return t==="true"||t==="false"||t!==""&&!Number.isNaN(Number(t))||/^['"].*['"]$/.test(t)||/[.([{]/.test(t)?t:`'${t.replace(/'/g,"\\'")}'`}function ns(e){return!e||e.length===0?"true":e.map(Fm).join(" && ")}function Vm(e){const n=`(${(e.source??"").trim()||"[]"} ?? [])`;let o;switch(e.op){case"count":o=`${n}.filter(x => ${ns(e.conditions)}).length`;break;case"sum":{const r=(e.sumField??"").trim()||"value";o=`${n}.filter(x => ${ns(e.conditions)}).reduce((s, x) => s + (x.${r} ?? 0), 0)`;break}case"filter":o=`${n}.filter(x => ${ns(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 wd(o)}function Um(e){if(typeof e!="string")return null;const t=vr(e).trim();let n=/^\((.+?)\s*\?\?\s*\[\]\)\.filter\(x => (.+)\)\.length$/.exec(t);return n?{key:"",op:"count",source:n[1].trim(),conditions:os(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:os(n[2]),sumField:n[3]}:(n=/^\((.+?)\s*\?\?\s*\[\]\)\.filter\(x => (.+)\)$/.exec(t),n?{key:"",op:"filter",source:n[1].trim(),conditions:os(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 os(e){const t=e.trim();if(t==="true")return[];const n=[];for(const o of qm(t)){const r=Gm(o.trim());r&&n.push(r)}return n}function qm(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:$d(t[3])}}return null}function $d(e){const t=e.trim(),n=/^'(.*)'$/.exec(t)||/^"(.*)"$/.exec(t);return n?n[1]:t}function Ed(e,t){const n=jm(e,t);if(n)return{kind:"preset",recipeId:n.recipeId,params:n.params};const o=Um(e);return o?{kind:"custom",model:o}:{kind:"advanced"}}function Ym(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 Id(e,t){if(typeof e!="string"||e.trim()==="")return{ok:!1,reason:"empty"};const n=vr(e);try{const o=Om(n)?_d.evaluatePipeExpression(n,t??{},{skipCache:!0}):_d.evaluateExpression(n,t??{},{skipCache:!0});return{ok:!0,value:o,type:Ym(o)}}catch(o){return{ok:!1,reason:o instanceof Error?o.message:String(o)}}}function Ad(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}=ts(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 Td(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 Dd(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=Id(s,n);o[r]=a.ok?a.value:s}return o}function Xm(e,t){const n=Ad(e,t),o=Td(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]=Dd(s.tree,o):r[s.scope]=s.tree;return r}function Nd(e){const{raw:t,spec:n,evaluateComputed:o}=e;return u.useMemo(()=>{const r=Ad(t,n),s=Td(t,n);if(o){const a=s.findIndex(l=>l.scope==="_computed");if(a>=0){const l=Dd(s[a].tree,s);s[a]={scope:"_computed",tree:l}}}return ji({dataSources:r,states:s,spec:n??void 0})},[t,n,o])}function Jm(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}=ts(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=ji({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 zd(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 Md(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 rs(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 is(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 Zm(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:rs(a,t),source:is(a,n)}))}return r}function Ld(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 Qm(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:Rm(s,a,t)}))}return o}function Rm(e,t,n){const r=e?.meta?.editor_label;if(typeof r=="string"&&r.length>0)return Pd(r,n);const s=e?.title;return typeof s=="string"&&s.length>0?Pd(s,n):t}function Pd(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 Od=bo("ActionRecipeEngine"),ev={api:"apiCall",nav:"navigate",showToast:"toast",setLocalState:"setState"},tv=new Set(["comment"]);function wo(e){if(!e||typeof e!="object")return[];const t=[];for(const[n,o]of Object.entries(e)){if(tv.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 _r="...";function nv(e,t){return e.replace(/\{\{\s*([\w.]+)\s*\}\}/g,(n,o)=>{const r=t[o];return r==null?"":String(r)})}function ss(e,t){if(typeof e=="string"){const n=on(e);return n!==null?n in t?t[n]:void 0:e.includes("{{")?nv(e,t):e}if(Array.isArray(e))return e.map(n=>ss(n,t)).filter(n=>n!==void 0);if(e&&typeof e=="object"){const n={};for(const[o,r]of Object.entries(e)){if(o===_r&&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=ss(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 ov(e){const t=e.handler;if(typeof t!="string")return e;const n=ev[t];if(n)return Od.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&&Od.warn(`action recipe build placed "${r}" inside params for handler "${t}" — should be top-level (core handler rules)`)}return e}function xr(e,t){const n=ss(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&&Bd(e.build,n,o)}return ov(n)}function Bd(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;Bd(a,r[s],n)}}}function rv(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&&!iv(s.build,e))continue;const l=sv(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 iv(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 sv(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[_r],d=typeof l=="string"?on(l):null,c=new Set(Object.keys(r).filter(p=>p!==_r));for(const[p,f]of Object.entries(r))if(p!==_r){if(typeof f=="string"&&on(f)!==null){const y=on(f);p in a&&(n[y]=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,y]of Object.entries(a))c.has(f)||(p[f]=y);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=rv(e,t);return o?{kind:"preset",recipeId:o.recipeId,values:o.values,handler:n}:{kind:"advanced",handler:n}}function Wd(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=av(d);if(c!==""&&(s.push(c),s.length>=2))break}return s.length===0?r:`${r} (${s.join(", ")})`}function av(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`[${e.length}]`:e&&typeof e=="object"?"{…}":""}function jd(e,t){const n={...e};return typeof t=="string"&&t.trim().length>0?n.if=t.trim():delete n.if,n}function as(e){const t=e?.if;return typeof t=="string"&&t.trim().length>0?t:null}const lv=/^\s*\$t:(custom\.[a-zA-Z0-9._-]+)\s*$/,dv=/^\s*\$t:([a-zA-Z0-9._-]+)\s*$/,cv=/\{\{.*?\}\}/;function Hd(e,t){const n=typeof e=="string"?e:"",o=lv.exec(n);if(o){const a=o[1],l=t?t(a):"";return{customKey:a,binding:!1,paramKey:!1,displayValue:l}}const r=mt(n);if(r&&r.key.startsWith("custom.")){const a=t?t(r.key):"";return{customKey:r.key,binding:!1,paramKey:!0,displayValue:a}}if(cv.test(n))return{customKey:null,binding:!0,paramKey:!1,displayValue:n};const s=dv.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 uv(){const{state:e}=Je(),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=>Hd(l,r),[r]),a=u.useCallback(async(l,d)=>{const c=Hd(l,r);if(c.binding)return{kind:"blocked"};if(c.customKey){if(d===c.displayValue)return{kind:"noop",customKey:c.customKey};const y=await yr(t,c.customKey,n,d);return y.kind==="error"?{kind:"error",message:y.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 ls(e,t,n,o,r,s,a,l,d,c){const p=c?Yi(o,c):null,f=!!(p&&p.keyifiable),y=d?d(o):o,g=f?p.chipValue:Xl(y),h=`p${f?p.bindings.length:cr(y).length}`,v=Math.max(0,Math.min(r,g.length)),b=Hl(g,v,h),x=ur(b).replace(/\{\{?p\d+\}?\}/g," ").replace(/\s+/g," ").trim(),k=x.length>0?x:b,w=await qn(e,t,n,k);if(w.kind==="error"||!w.resource)return{kind:"error",message:w.message};const _=w.resource.translation_key,C=An(b),E=w.resource.values??{},S={[n]:b};for(const z of Object.keys(E)){if(z===n)continue;let D=E[z]??"";for(const O of C)D=qi(D,O);S[z]=D}xo(e,_,S);const T=En(s,a,l);return{kind:"ok",text:`${f?Gl(`$t:${_}`,p):Yl(`$t:${_}`,y)}|${h}=${T}`,key:_}}async function wr(e,t,n,o,r,s,a){let l=mt(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=hb(l.params.map(h=>h.name)),c=En(r,s,a),p=`${n.trim()}|${d}=${c}`,f=await cn(e,l.key),y=jb(l.key)??{},g=new Set([...Object.keys(f?.values??{}),...Object.keys(y),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?Hl(v,o,d):qi(v,d)}return xo(e,l.key,m),{kind:"ok",text:p,paramName:d}}async function ko(e,t,n,o){return br(e,t,n,o),{kind:"ok"}}async function pv(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)}xo(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 Fd(e,t,n){return pv(e,t,o=>Ql(o,n))}function Kd(e,t){if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:e,locale:t}}))}catch{}}async function kr(e,t,n,o){const r=await Fd(e,t,n);return Kd(e,o),r}const fv=/^\s*\$t:(custom\.[a-zA-Z0-9._-]+)\s*$/;function gv(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 Vd(e){const t=e.text;if(typeof t!="string")return null;const n=fv.exec(t);if(n)return n[1];const o=mt(t);return o&&o.key.startsWith("custom.")?o.key:null}function ds(e){const t={},n=mt(typeof e=="string"?e:"");for(const o of n?.params??[])t[o.name]=Vt(o.expression);return t}function hv(e){return ds(typeof e.text=="string"?e.text:"")}function Ud({customKey:e,templateIdentifier:t,t:n,paramLabels:o,locales:r,onRemoveParam:s}){const a=r??ud(),l=Ft(),d=o??{},[c,p]=u.useState({status:"idle",values:{}}),[f,y]=u.useState(!1),[g,m]=u.useState(!1),[h,v]=u.useState(null),b=u.useRef({});u.useEffect(()=>{let $=!1;if(!e){p({status:"not_a_key",values:{}});return}return p({status:"loading",values:{}}),(async()=>{const A=await cn(t,e);if($)return;if(!A){p({status:"error",values:{}});return}const z={...A.values??{}};for(const D of Object.keys(z)){const O=It(e,D);O!==void 0&&(z[D]=O)}for(const D of a){const O=It(e,D);O!==void 0&&(z[D]=O)}b.current={...z},p({status:"loaded",id:A.id,lockVersion:A.lock_version,values:z})})(),()=>{$=!0}},[e,t]),u.useEffect(()=>{if(typeof window>"u"||!e)return;const $=A=>{const z=A.detail;z?.templateIdentifier&&z.templateIdentifier!==t||p(D=>{if(D.status!=="loaded")return D;let O=!1;const M={...D.values};for(const B of Object.keys(M)){const N=It(e,B);N!==void 0&&N!==M[B]&&(M[B]=N,O=!0)}return O?(b.current={...b.current,...M},{...D,values:M}):D})};return window.addEventListener(kt,$),()=>window.removeEventListener(kt,$)},[e,t]);const x=u.useCallback(($,A)=>{p(z=>{const D=z.values[$]??"",O={...z,values:{...z.values,[$]:A}};return e&&gv(D,A)&&(br(t,e,$,A),b.current={...b.current,[$]:A},l?.markDirty?.(),Kd(t,$)),O})},[e,t,l]),k=u.useCallback($=>{p(A=>{const z={};for(const[D,O]of Object.entries(A.values))z[D]=Ql(O,$);return b.current={...z},{...A,values:z}}),s?.($)},[s]),w=u.useMemo(()=>[...Object.values(c.values),...Object.values(b.current)].some(A=>An(A).length>0),[c.values]),_=u.useRef(null),C=u.useCallback(()=>{m(!0),_.current&&clearTimeout(_.current),_.current=setTimeout(()=>m(!1),1500)},[]);u.useEffect(()=>()=>{_.current&&clearTimeout(_.current)},[]);const E=u.useCallback(async()=>{if(m(!1),c.status!=="loaded"||c.id===void 0)return;const $=b.current;for(const[z,D]of Object.entries(c.values)){const O=$[z]??"";if(w){const M=An(O);if(M.length===0)continue;const B=An(D);if(!(M.length===B.length&&M.every((H,L)=>H===B[L]))){v(n("layout_editor.translation.placeholder_mismatch"));return}continue}if(Ui(O)&&!kb(O,D)){v(n("layout_editor.translation.token_mismatch"));return}}if(y(!0),v(null),w){xo(t,e??"",c.values),b.current={...c.values},l?.markDirty?.(),Et({op:"translation_field_update",translationKey:e,changedLocales:Object.keys(c.values),timestamp:Date.now()}),await new Promise(z=>setTimeout(z,0)),y(!1),C();return}const A=`/api/admin/templates/${encodeURIComponent(t)}/custom-translations/${c.id}`;try{const z=await fetch(A,{method:"PUT",credentials:"same-origin",headers:je({"Content-Type":"application/json"}),body:JSON.stringify({values:c.values,expected_lock_version:c.lockVersion??0})}),D=await z.json().catch(()=>null);if(z.status===409){v(n("layout_editor.translation.conflict"));return}if(!z.ok){v(D?.message??n("layout_editor.translation.save_failed"));return}const O=typeof D?.data?.lock_version=="number"?D.data.lock_version:(c.lockVersion??0)+1;p(M=>({...M,lockVersion:O})),b.current={...c.values},await tn(t),Et({op:"translation_field_update",translationKey:e,changedLocales:Object.keys(c.values),timestamp:Date.now()}),C()}catch(z){v(z instanceof Error?z.message:n("layout_editor.translation.save_failed"))}finally{y(!1)}},[c,t,e,n]);if(c.status==="not_a_key"||!e)return i.jsx("div",{"data-testid":"g7le-translation-not-a-key",style:cs,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:cs,children:n("layout_editor.translation.loading")});if(c.status==="error")return i.jsx("div",{"data-testid":"g7le-translation-error",style:cs,children:n("layout_editor.translation.load_failed")});const S=new Set([...a,...Object.keys(c.values)]),T=Array.from(S);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:yv,children:[n("layout_editor.translation.key_label"),": ",i.jsx("code",{style:bv,children:e})]}),T.map($=>{const A=c.values[$]??"",z=A.trim().length===0;return i.jsxs("div",{className:"g7le-translation-row","data-testid":`g7le-translation-row-${$}`,style:mv,children:[i.jsxs("label",{htmlFor:`g7le-translation-input-${$}`,style:{fontSize:12,color:"#475569",minWidth:72,display:"inline-flex",alignItems:"center",gap:4},children:[Gn($,n),z&&i.jsx("span",{"data-testid":`g7le-translation-missing-${$}`,style:vv,children:n("layout_editor.translation.needs_translation")})]}),w?i.jsx("div",{style:{flex:1},"data-testid":`g7le-translation-chip-${$}`,children:i.jsx(mr,{value:A,onChange:D=>x($,D),t:n,paramLabels:d,testIdSuffix:$,onRemoveChip:s?k:void 0})}):i.jsx("input",{id:`g7le-translation-input-${$}`,type:"text","data-testid":`g7le-translation-input-${$}`,value:A,placeholder:z?n("layout_editor.translation.needs_translation"):"",onChange:D=>x($,D.currentTarget.value),onBlur:E,style:{flex:1,padding:"4px 8px",fontSize:13,border:"1px solid #cbd5e1",borderRadius:4,color:z?"#94a3b8":"#0f172a"}})]},$)}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("button",{type:"button","data-testid":"g7le-translation-save",disabled:f,onClick:E,style:_v,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 cs={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},yv={fontSize:12,color:"#475569"},bv={fontSize:11,background:"#f1f5f9",padding:"1px 4px",borderRadius:3,color:"#0f172a"},mv={display:"flex",alignItems:"center",gap:8},vv={fontSize:10,color:"#b45309",background:"#fef3c7",padding:"0 4px",borderRadius:3},_v={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),y=u.useCallback(()=>{const m=e.current,h=c.current;if(!m||!h)return;const v=m.getBoundingClientRect(),b=window.innerWidth,x=window.innerHeight,k=h.getBoundingClientRect(),w=Math.min(Math.max(k.width,s),a),_=k.height;let C=v.left;C+w+l>b&&(C=v.right-w),C=Math.min(Math.max(C,l),b-w-l);const E=x-v.bottom-l,S=v.top-l;let T,$;const A=r==="bottom",z=E>=Math.min(_,160),D=S>=Math.min(_,160);A&&z||A&&!D?(T=v.bottom+4,$=E):!A&&D||D?(T=v.top-4-Math.min(_,S),$=S):E>=S?(T=v.bottom+4,$=E):(T=l,$=S),f({left:C,top:T,maxHeight:Math.max($,120)})},[e,r,s,a,l]);if(u.useLayoutEffect(()=>{if(!t){f(null);return}y()},[t,y]),u.useEffect(()=>{if(!t)return;const m=()=>y();window.addEventListener("resize",m),window.addEventListener("scroll",m,!0);const h=b=>{const x=c.current,k=e.current,w=b.target;x?.contains(w)||k?.contains(w)||n()},v=b=>{b.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,y,n,e]),!t)return null;const g={...xv,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 xv={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 qd(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(()=>Fi(e,"scalar").map(h=>({...h,resolvedLabel:qd(t,h.labelKey,h.path||h.sourceId)})),[e,t]),y=u.useMemo(()=>Ki(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:Cv}),i.jsx("div",{style:$v,children:y.length===0?i.jsx("div",{style:Ev,children:t("layout_editor.inline_binding.no_results")}):y.map(m=>i.jsxs("button",{type:"button","data-testid":`g7le-inline-binding-candidate-${m.expression}`,onClick:()=>{n(m),l(!1),c("")},style:Iv,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:Av,children:[qd(t,m.groupLabelKey,m.sourceId)," · ",m.path||m.sourceId]})]}),i.jsx("span",{style:Tv,children:m.preview})]},m.expression))})]});return i.jsxs("div",{style:s?Sv:{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:wv,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:kv,children:g})]})}const wv={fontSize:13,lineHeight:1,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#334155",padding:"4px 8px",cursor:"pointer",textAlign:"center",whiteSpace:"nowrap"},kv={marginTop:4,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",padding:6},Sv={display:"inline-block"},Cv={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},$v={marginTop:4,maxHeight:200,overflowY:"auto",display:"flex",flexDirection:"column",gap:2},Ev={fontSize:11,color:"#94a3b8",padding:"8px 0",textAlign:"center"},Iv={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,border:"none",background:"transparent",cursor:"pointer",padding:"6px 8px",borderRadius:4,textAlign:"left"},Av={fontSize:10,color:"#94a3b8"},Tv={fontSize:10,color:"#64748b",fontFamily:"monospace",whiteSpace:"nowrap"},Dv=["$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 So(e,t,n,o){switch(e.kind){case"leaf":Yd(e.text,t,n,o);return;case"conditional":So(e.then,t,n,o),o.push({kind:"ellipsis",text:"⋯"});return;case"fallback":So(e.primary,t,n,o);return;case"concat":e.parts.forEach(r=>So(r,t,n,o));return;default:o.push({kind:"text",text:e.source});return}}function Yd(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 us(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);So(l.node,t,n,o)}else Yd(a,t,n,o);return o}const s=un(e);return So(s.node,t,n,o),o}function Nv(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=Hv(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==="??"&&zv(r.primary)&&Mv(r.fallback))return{node:{kind:"leaf",text:t},decomposed:!1,original:t};const s=Zn(r,!0);return qv(o,s)?{node:r,decomposed:!0,original:t}:{node:{kind:"raw",source:o},decomposed:!1,original:t}}function Zn(e,t=!1){const n=Jd(e);return t?n:e.kind==="leaf"?e.text:`{{${n}}}`}function Co(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 ps(e){return Zn({kind:"fallback",op:"??",primary:{kind:"leaf",text:typeof e=="string"?e:""},fallback:{kind:"leaf",text:""}},!1)}function $o(e){switch(e.kind){case"leaf":return e.text;case"conditional":return $o(e.then);case"fallback":return $o(e.primary);case"concat":return e.parts.map($o).join("");default:return e.kind==="raw"?`{{${e.source}}}`:""}}function uM(e){return e}function Sr(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)?$o(un(n).node):n;return""}return $o(un(e).node)}function zv(e){if(e.kind!=="leaf")return!1;const t=/^\{\{([\s\S]*)\}\}$/.exec(e.text.trim());return t?Qn(t[1].trim()):!1}function Mv(e){if(e.kind!=="leaf")return!1;const t=e.text.trim();return!(/\{\{/.test(t)||t.startsWith("$t:"))}function Cr(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}function Lv(e){const t=[];let n=0,o=0;const r=e.length;for(;on&&t.push(Cr(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 nEo(t,"concat")).join(" + ");case"fallback":return`${Eo(e.primary,"fallback")} ${e.op} ${Eo(e.fallback,"fallback")}`;case"conditional":return`${Ov(e.condition)} ? ${Eo(e.then,"conditional")} : ${Eo(e.else,"conditional")}`;default:return""}}function Eo(e,t){const n=Jd(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 Wv=["===","!==","??","||","&&","==","!=",">=","<="];function Zd(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:Rd(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"&&Dv.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 Hv(e){return new jv(e).parse()}const Fv=["===","!==","==","!=",">=","<=",">","<"];function Kv(e,t){const n=e.trim();if(n==="")return{kind:"raw",source:n};if(n===Xd)return{kind:"simple",left:"",op:"truthy",right:""};if(n.startsWith("!")){const s=n.slice(1).trim(),a=Qd(s);return Qn(a)?{kind:"simple",left:a,op:"falsy",right:""}:{kind:"raw",source:n}}const o=Vv(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)&&Uv(c)?{kind:"simple",left:d,op:a,right:c}:{kind:"raw",source:n}}const r=Qd(n);return Qn(r)?{kind:"simple",left:r,op:"truthy",right:""}:{kind:"raw",source:n}}function Vv(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 qv(e,t){try{return $r(e)===$r(t)}catch{return!1}}function $r(e){const t=Jn(e);return t!==null?$r(t):Zd(e).map(o=>{if(o.kind==="string")return`S:${Rd(o.value)}`;if(o.kind==="binding"){const r=/^\{\{([\s\S]*)\}\}$/.exec(o.value);return`B:${r?$r(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?Yv:Gv})}const Gv={height:0,margin:0,transition:"height 80ms"},Yv={height:3,margin:"1px 0",borderRadius:2,background:"#2563eb",boxShadow:"0 0 0 1px #93c5fd"};function fs(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]),y=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:y,isDropTarget:g}}const Xv={text:"",expression:"{{false ? '' : ''}}",fallback:"{{'' ?? ''}}",data:""};function ec(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 gs({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 k=ec(e,a.current);return a.current=k.nextSeq,k.segs},[]),[c,p]=u.useState(d),[f,y]=u.useState(!1);if(e!==l.current){l.current=e;const k=c.map(w=>w.value).join("");if(e!==k){const w=ec(e,a.current);a.current=w.nextSeq,p(w.segs)}}const g=u.useCallback(k=>{p(k);const w=k.map(_=>_.value).join("");l.current=w,t(w)},[t]),m=u.useCallback((k,w)=>{g(c.map(_=>_.id===k?{..._,value:w??""}:_))},[c,g]),h=u.useCallback(k=>{const w=c.filter(_=>_.id!==k);g(w.length>0?w:[{id:a.current++,kind:"text",value:""}])},[c,g]),v=u.useCallback(k=>{g([...c,{id:a.current++,kind:k,value:Xv[k]}])},[c,g]),b=u.useCallback((k,w)=>{if(k===w||k<0||w<0||k>=c.length||w>=c.length)return;const _=c.slice(),[C]=_.splice(k,1);_.splice(w,0,C),g(_)},[c,g]),x=fs({length:c.length,onMove:b});return i.jsxs("div",{"data-testid":r,style:Qv,children:[i.jsx("div",{style:Rv,children:n("layout_editor.value_tree.segmented_hint")}),c.map((k,w)=>i.jsxs(u.Fragment,{children:[i.jsx(Rn,{active:x.isDropTarget(w),testid:`${r}-dropline-${w}`}),i.jsx(Zv,{seg:k,index:w,t:n,candidates:o,testidPrefix:r,renderLeafInput:s,onValueChange:_=>m(k.id,_),onRemove:()=>h(k.id),dragging:x.dragIndex===w,onDragStartCard:()=>x.onDragStart(w),onDragEndCard:x.onDragEnd,onDragOverCard:_=>x.onDragOverItem(w,_),onDropCard:x.onDrop})]},k.id)),i.jsx(Rn,{active:x.isDropTarget(c.length),testid:`${r}-dropline-end`}),i.jsxs("div",{style:i_,"data-testid":`${r}-add-row`,children:[i.jsxs("button",{type:"button","data-testid":`${r}-add-text`,onClick:()=>v("text"),style:Er,children:["+ ",n("layout_editor.value_tree.segment.text")]}),i.jsxs("button",{type:"button","data-testid":`${r}-add-expression`,onClick:()=>v("expression"),style:Er,children:["+ ",n("layout_editor.value_tree.segment.expression")]}),i.jsxs("button",{type:"button","data-testid":`${r}-add-fallback`,onClick:()=>v("fallback"),style:Er,children:["+ ",n("layout_editor.value_tree.segment.fallback")]}),i.jsxs("button",{type:"button","data-testid":`${r}-add-data`,onClick:()=>v("data"),style:Er,children:["+ ",n("layout_editor.value_tree.segment.data")]})]}),i.jsxs("div",{style:l_,children:[i.jsxs("button",{type:"button","data-testid":`${r}-source-toggle`,"aria-expanded":f,onClick:()=>y(k=>!k),style:d_,children:[""," ",n("layout_editor.value_tree.show_source")," ",f?"▴":"▾"]}),f&&i.jsx("code",{"data-testid":`${r}-source-code`,style:c_,children:c.map(k=>k.value).join("")})]})]})}function Jv({t:e,candidates:t,onPick:n,testidPrefix:o}){return!t||t.length===0?i.jsx("div",{"data-testid":`${o}-data-empty`,style:a_,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:s_,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 Zv({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:y}){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?{...tc,opacity:.5}:tc,onDragOver:m=>{m.preventDefault();const h=m.currentTarget.getBoundingClientRect();f(m.clientY{m.preventDefault(),y()},children:[i.jsxs("div",{style:e_,children:[i.jsx("span",{"data-testid":`${r}-drag-${t}`,style:o_,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:t_,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:r_,children:"✕"})]}),i.jsx("div",{style:n_,children:e.kind==="data"&&e.value.trim()===""?i.jsx(Jv,{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(vt,{value:e.value,onChange:a,t:n,candidates:o,testidPrefix:`${r}-field-${t}`,enableExpressionTree:!0,expressionSourceToggle:!1})})]})}const Qv={display:"flex",flexDirection:"column",gap:6,width:"100%",minWidth:0},Rv={fontSize:11,color:"#64748b"},tc={display:"flex",flexDirection:"column",gap:4,padding:"6px 8px",border:"1px solid #e2e8f0",borderLeft:"3px solid #6366f1",borderRadius:6,background:"#f8fafc",minWidth:0},e_={display:"flex",alignItems:"center",gap:6,minWidth:0},t_={fontSize:10,fontWeight:600,color:"#6366f1",flex:1,minWidth:0},n_={minWidth:0},o_={color:"#94a3b8",cursor:"grab",fontSize:14,userSelect:"none"},r_={border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12,padding:2,flexShrink:0},i_={display:"flex",flexWrap:"wrap",gap:6,marginTop:2},s_={fontSize:11,color:"#64748b",marginBottom:2},a_={fontSize:11,color:"#94a3b8",padding:"4px 0"},Er={padding:"4px 10px",fontSize:11,border:"1px dashed #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},l_={display:"flex",flexDirection:"column",gap:4,marginTop:2},d_={alignSelf:"flex-start",padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",fontFamily:"monospace"},c_={fontSize:11,background:"#0f172a",color:"#e2e8f0",padding:"6px 8px",borderRadius:4,wordBreak:"break-all",fontFamily:"monospace"},u_=[{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 nc({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:rc,children:[f,i.jsxs("div",{style:D_,children:[i.jsxs("button",{type:"button","data-testid":`${r}-source-toggle`,"aria-expanded":d,onClick:()=>c(y=>!y),style:N_,children:[""," ",n("layout_editor.value_tree.show_source")," ",d?"▴":"▾"]}),d&&i.jsx("code",{"data-testid":`${r}-source-code`,style:z_,children:Zn(e,!1)})]})]}):i.jsx("div",{"data-testid":r,style:rc,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(gs,{value:e.text,onChange:l=>t({kind:"leaf",text:l}),t:n,candidates:o,testidPrefix:`${r}-leaf`,renderLeafInput:a});case"conditional":return i.jsx(p_,{node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a});case"fallback":return i.jsx(f_,{node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a});case"concat":return i.jsx(h_,{node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a});default:return i.jsxs("div",{"data-testid":`${r}-raw`,style:M_,children:[i.jsx("code",{style:ac,children:e.source??""}),i.jsxs("span",{style:lc,children:["🔒 ",n("layout_editor.value_tree.raw_code_only")]})]})}}function p_({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:hs(s),children:[i.jsx(y_,{condition:e.condition,onChange:l,t:n,candidates:o,testidPrefix:r}),i.jsx(Ir,{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(Ir,{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 f_({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:hs(s),children:[i.jsx(Ir,{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(Ir,{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 g_={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 h_({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,g_[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]),y=fs({length:e.parts.length,onMove:f});return i.jsxs("div",{"data-testid":`${r}-concat`,style:hs(s),children:[i.jsx("div",{style:C_,children:n("layout_editor.value_tree.concat.hint")}),e.parts.map((g,m)=>i.jsxs(u.Fragment,{children:[i.jsx(Rn,{active:y.isDropTarget(m),testid:`${r}-part-dropline-${m}`}),i.jsxs("div",{"data-testid":`${r}-part-card-${m}`,style:y.dragIndex===m?{...sc,opacity:.5}:sc,onDragOver:h=>{h.preventDefault();const v=h.currentTarget.getBoundingClientRect();y.onDragOverItem(m,h.clientY{h.preventDefault(),y.onDrop()},children:[i.jsxs("div",{style:$_,children:[i.jsx("span",{"data-testid":`${r}-part-handle-${m}`,style:A_,draggable:!0,onDragStart:()=>y.onDragStart(m),onDragEnd:y.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:E_,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:T_,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:y.isDropTarget(e.parts.length),testid:`${r}-part-dropline-end`}),i.jsxs("div",{style:I_,"data-testid":`${r}-part-add-row`,children:[i.jsxs("button",{type:"button","data-testid":`${r}-part-add-text`,onClick:()=>p("text"),style:Ar,children:["+ ",n("layout_editor.value_tree.segment.text")]}),i.jsxs("button",{type:"button","data-testid":`${r}-part-add-expression`,onClick:()=>p("expression"),style:Ar,children:["+ ",n("layout_editor.value_tree.segment.expression")]}),i.jsxs("button",{type:"button","data-testid":`${r}-part-add-fallback`,onClick:()=>p("fallback"),style:Ar,children:["+ ",n("layout_editor.value_tree.segment.fallback")]}),i.jsxs("button",{type:"button","data-testid":`${r}-part-add-data`,onClick:()=>p("data"),style:Ar,children:["+ ",n("layout_editor.value_tree.segment.data")]})]})]})}function y_({condition:e,onChange:t,t:n,candidates:o,testidPrefix:r}){if(e.kind==="raw")return i.jsxs("div",{"data-testid":`${r}-cond-raw`,style:x_,children:[i.jsx("span",{style:ic,children:n("layout_editor.value_tree.cond.label")}),i.jsx("code",{style:ac,children:e.source}),i.jsxs("span",{style:lc,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:__,children:[i.jsx("span",{style:ic,children:n("layout_editor.value_tree.cond.label")}),i.jsx(oc,{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:S_,children:u_.map(l=>i.jsx("option",{value:l.value,children:n(l.labelKey)},l.value))}),a&&i.jsx(oc,{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 oc({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=(y,g)=>{const m=En(y,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:w_,children:[i.jsx("input",{type:"text","data-testid":e,value:c,onChange:y=>d(y.target.value),onBlur:p,onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),p())},placeholder:o,style:k_}),r&&r.length>0&&s&&i.jsx($t,{candidates:r,t:s,onSelect:y=>f(y.sourceId,y.path),testIdSuffix:`${e}-data`,floating:!0})]})}function Ir({label:e,testid:t,children:n}){return i.jsxs("div",{"data-testid":t,style:b_,children:[i.jsx("span",{style:m_,children:e}),i.jsx("div",{style:v_,children:n})]})}const rc={display:"flex",flexDirection:"column",gap:6,width:"100%",minWidth:0},hs=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}),b_={display:"flex",flexDirection:"column",gap:3,minWidth:0},m_={fontSize:11,fontWeight:600,color:"#475569"},v_={paddingLeft:8,minWidth:0},__={display:"flex",flexWrap:"wrap",gap:4,alignItems:"center",minWidth:0},x_={display:"flex",flexWrap:"wrap",gap:4,alignItems:"center",minWidth:0},ic={fontSize:11,fontWeight:600,color:"#0f172a",whiteSpace:"nowrap"},w_={display:"inline-flex",alignItems:"flex-start",gap:2,flex:"1 1 80px",minWidth:60},k_={flex:"1 1 80px",minWidth:60,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},S_={padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff"},C_={fontSize:11,color:"#94a3b8"},sc={display:"flex",flexDirection:"column",gap:4,padding:"6px 8px",border:"1px solid #e2e8f0",borderLeft:"3px solid #6366f1",borderRadius:6,background:"#fff",minWidth:0},$_={display:"flex",alignItems:"center",gap:6,minWidth:0},E_={fontSize:10,fontWeight:600,color:"#6366f1",flex:1,minWidth:0},I_={display:"flex",flexWrap:"wrap",gap:6,marginTop:2},A_={color:"#94a3b8",cursor:"grab",fontSize:14,userSelect:"none"},T_={border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12,padding:2,flexShrink:0},Ar={padding:"4px 10px",fontSize:11,border:"1px dashed #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},D_={display:"flex",flexDirection:"column",gap:4,marginTop:2},N_={alignSelf:"flex-start",padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",fontFamily:"monospace"},z_={fontSize:11,background:"#0f172a",color:"#e2e8f0",padding:"6px 8px",borderRadius:4,wordBreak:"break-all",fontFamily:"monospace"},M_={display:"flex",flexDirection:"column",gap:2,minWidth:0},ac={fontSize:11,background:"#f1f5f9",padding:"3px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all",fontFamily:"monospace"},lc={fontSize:10,color:"#64748b"};function vt({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:y,classify:g,translate:m}=uv(),[h,v]=u.useState(null),[b,x]=u.useState(!1),[k,w]=u.useState(!1),[_,C]=u.useState(!1),[E,S]=u.useState(!1),[T,$]=u.useState(!1),[,A]=u.useState(0);u.useEffect(()=>{if(typeof window>"u")return;const N=H=>{const L=H.detail;L?.templateIdentifier&&L.templateIdentifier!==f||A(I=>I+1)};return window.addEventListener(kt,N),()=>window.removeEventListener(kt,N)},[f]);const z=g(e);u.useEffect(()=>{v(null),$(!1)},[p,e]);const D=h!==null?h:z.displayValue,O=u.useCallback(async()=>{if(h!==null){if(h===z.displayValue){v(null);return}x(!0);try{const N=await y(e,h);N.kind==="created"&&N.token?(t(N.token),Et({op:"prop_i18n_create_key",sourceState:"plain_text",translationKey:N.customKey,toLocale:p,valueLength:h.length,timestamp:Date.now()})):N.kind==="updated"&&Et({op:"prop_i18n_update_value",sourceState:"custom_key",translationKey:N.customKey,toLocale:p,valueLength:h.length,timestamp:Date.now()})}finally{x(!1),v(null)}}},[h,z.displayValue,y,e,t,p]),M=u.useCallback(N=>{typeof e=="string"&&(t(mo(e,N)),z.customKey&&kr(f,z.customKey,N,p))},[e,t,z.customKey,f,p]);if(z.binding){if(l&&typeof e=="string"){const N=Gd(e),H=un(e),L=!N&&Kt(e)!==null,I=(N||H.decomposed)&&!L;if(I&&d&&!_)return i.jsx(O_,{value:e,t:n,translate:m,onEdit:()=>C(!0),testidPrefix:`${r}-preview`});const F=I&&(d||N)?i.jsx(gs,{value:e,onChange:G=>t(G),t:n,candidates:a,testidPrefix:`${r}-seg`}):H.decomposed?i.jsx(nc,{node:H.node,onChange:G=>t(Zn(G,!1)),t:n,candidates:a,testidPrefix:`${r}-tree`,showSourceToggle:c}):null;if(F){if(!d)return F;const G=Sr(e),V=G?us(G,Y=>{const Z=m(Y);return Z&&Z!==Y&&!Z.startsWith("$t:")?Z:""},Y=>Vt(Y)):[];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:()=>S(!0),style:V_,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:()=>C(!1),style:uc,title:n("layout_editor.value_tree.collapse"),"aria-label":n("layout_editor.value_tree.collapse"),children:["▴ ",n("layout_editor.value_tree.collapse")]})]}),E&&i.jsxs("div",{"data-testid":`${r}-to-plain-confirm`,style:U_,children:[i.jsx("p",{style:q_,children:n("layout_editor.value_tree.to_plain_lead")}),i.jsx("div",{style:G_,children:V.length===0?i.jsx("span",{style:{color:"#94a3b8"},children:n("layout_editor.prop_i18n.placeholder")}):V.map((Y,Z)=>Y.kind==="chip"?i.jsxs("span",{style:dc,children:["🔗 ",Y.text]},Z):i.jsx("span",{style:Y.kind==="ellipsis"?cc:void 0,children:Y.text},Z))}),i.jsxs("p",{style:Y_,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:()=>S(!1),style:uc,children:n("layout_editor.value_tree.to_plain_cancel")}),i.jsx("button",{type:"button","data-testid":`${r}-to-plain-confirm-ok`,onClick:()=>{S(!1),C(!1),t(Sr(e)||void 0)},style:X_,children:n("layout_editor.value_tree.to_plain_ok")})]})]}),F]})}}return l&&typeof e=="string"&&a&&a.length>0&&Kt(e)!==null?i.jsx(B_,{value:e,onChange:t,t:n,candidates:a,testidPrefix:`${r}-data`}):i.jsxs("div",{"data-testid":`${r}-binding`,style:tx,children:[i.jsx("code",{style:nx,children:typeof e=="string"?e:""}),i.jsxs("span",{style:ox,children:["🔗 ",n("layout_editor.prop_i18n.bound_code_only")]})]})}if(!T&&typeof e=="string"&&Ul(e)){const N=ql(e);return i.jsxs("div",{"data-testid":`${r}-settings-ref`,style:Q_,children:[i.jsx("div",{"data-testid":`${r}-settings-ref-chips`,style:R_,children:N.map((H,L)=>H.kind==="chip"?i.jsxs("span",{style:ex,children:["🔗 ",H.label]},L):i.jsx("span",{children:H.label},L))}),i.jsxs("button",{type:"button","data-testid":`${r}-settings-ref-edit`,onClick:()=>$(!0),style:pc,title:n("layout_editor.value_tree.edit"),"aria-label":n("layout_editor.value_tree.edit"),children:["✎ ",n("layout_editor.value_tree.edit")]})]})}const B=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":k,onClick:()=>w(N=>!N),style:pc,children:["🌐 ",z.customKey?k?"⌃":"⌄":"+"]});return i.jsxs("div",{"data-testid":r,style:{display:"flex",flexDirection:"column",gap:4,width:"100%"},children:[i.jsx("div",{style:J_,children:z.paramKey&&z.customKey?i.jsx(L_,{customKey:z.customKey,value:typeof e=="string"?e:"",onChange:t,t:n,candidates:a,testidPrefix:r,showExprButton:l&&d,onToExpression:()=>{C(!0),t(Co(typeof e=="string"?e:""))},langToggle:B}):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:N=>v(N.target.value),onBlur:()=>{O(),T&&$(!1)},disabled:b,style:Z_}),a&&a.length>0&&i.jsx(P_,{value:typeof e=="string"?e:"",customKey:z.customKey,onChange:t,t:n,candidates:a,testidPrefix:r}),l&&d&&i.jsx("button",{type:"button","data-testid":`${r}-to-expr`,onClick:()=>{C(!0),t(Co(typeof e=="string"?e:""))},title:n("layout_editor.value_tree.to_expression"),"aria-label":n("layout_editor.value_tree.to_expression"),style:Io,children:"ƒx"}),B]})}),k&&(z.customKey?i.jsx(Ud,{customKey:z.customKey,templateIdentifier:f,t:n,paramLabels:ds(e),locales:s,onRemoveParam:M},z.customKey):i.jsx("div",{"data-testid":`${r}-expand-hint`,style:rx,children:n("layout_editor.prop_i18n.create_first")}))]})}function L_({customKey:e,value:t,onChange:n,t:o,candidates:r,testidPrefix:s,showExprButton:a=!1,onToExpression:l,langToggle:d}){const{state:c}=Je(),p=c.templateIdentifier,f=c.locale,y=Ft(),[g,m]=u.useState(null),h=u.useRef(""),v=u.useRef(null),b=u.useRef(null),x=u.useRef(null),[k,w]=u.useState(null),[_,C]=u.useState(!1),E=ds(t),S=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 O=It(e,f);if(O!==void 0){D||(h.current=O,m(O));return}const M=await cn(p,e);if(D)return;const B=M?.values?.[f]??"";h.current=B,m(B)})(),()=>{D=!0}},[e,p,f]),u.useEffect(()=>{if(typeof window>"u")return;const D=O=>{const M=O.detail;if(M?.templateIdentifier&&M.templateIdentifier!==p)return;const B=It(e,f);B!==void 0&&B!==g&&(h.current=B,m(B))};return window.addEventListener(kt,D),()=>window.removeEventListener(kt,D)},[e,p,f,g]);const T=u.useCallback(D=>{m(D),ko(p,e,f,D).then(()=>{y?.markDirty?.()})},[p,e,f,y]),$=u.useCallback(D=>{n(mo(t,D)),kr(p,e,D,f).then(()=>{S(),y?.markDirty?.()})},[t,n,p,e,f,S,y]),A=u.useCallback(async D=>{if(!(k===null||_)){C(!0);try{g!==null&&g!==h.current&&(await ko(p,e,f,g),h.current=g);const O=await wr(p,f,t,k,D.sourceId,D.path,"scalar");O.kind==="ok"&&(n(O.text),await S(),y?.markDirty?.())}finally{C(!1),w(null)}}},[k,_,g,t,p,e,f,n,S,y]),z=!!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(mr,{value:g,onChange:T,t:o,paramLabels:E,testIdSuffix:`${s}-field`,onRequestInsert:z?D=>w(D):void 0,onRemoveChip:$,hideInsertButton:!0,caretRef:x})}),z&&i.jsx("button",{ref:b,type:"button","data-testid":`${s}-plus-data-btn`,onClick:()=>w(x.current?x.current():g?.length??0),title:o("layout_editor.inline_binding.insert_data"),"aria-label":o("layout_editor.inline_binding.insert_data"),style:Io,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:Io,children:"ƒx"}),d,z&&i.jsx(Xn,{anchorRef:b,open:k!==null,onClose:()=>w(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 P_({value:e,customKey:t,onChange:n,t:o,candidates:r,testidPrefix:s}){const{state:a}=Je(),l=a.templateIdentifier,d=a.selectedRoute?.layoutName??null,c=a.locale,p=Ft(),[f,y]=u.useState(!1),[g,m]=u.useState(!1),h=u.useRef(null),v=u.useCallback(k=>{const w=o(k);return w&&w!==k&&!w.startsWith("$t:")?w:""},[o]),b=u.useCallback(k=>k.replace(/\$t:[a-zA-Z0-9._-]+/g,w=>v(w.slice(3))).replace(/\s+/g," ").trim(),[v]),x=u.useCallback(async k=>{if(!g){m(!0);try{if(t){const w=await wr(l,c,e,Number.MAX_SAFE_INTEGER,k.sourceId,k.path,"scalar");w.kind==="ok"&&(n(w.text),p?.markDirty?.())}else{const w=await ls(l,d,c,e,e.length,k.sourceId,k.path,"scalar",b,_=>o(_));w.kind==="ok"&&(n(w.text),p?.markDirty?.())}}finally{m(!1),y(!1)}}},[g,t,l,d,c,e,n,p,o,b]);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:()=>y(k=>!k),title:o("layout_editor.inline_binding.insert_data"),"aria-label":o("layout_editor.inline_binding.insert_data"),style:Io,children:"+"}),i.jsx(Xn,{anchorRef:h,open:f,onClose:()=>y(!1),children:i.jsx($t,{candidates:r,t:o,onSelect:k=>{x(k)},testIdSuffix:`${s}-plus-insert`,defaultOpen:!0,floating:!1})})]})}function O_({value:e,t,translate:n,onEdit:o,testidPrefix:r}){const s=us(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:H_,children:[i.jsx("div",{"data-testid":`${r}-text`,style:F_,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:dc,children:["🔗 ",a.text]},l):i.jsx("span",{style:a.kind==="ellipsis"?cc:void 0,children:a.text},l))}),i.jsxs("button",{type:"button","data-testid":`${r}-edit`,onClick:o,style:K_,title:t("layout_editor.value_tree.edit"),"aria-label":t("layout_editor.value_tree.edit"),children:["✎ ",t("layout_editor.value_tree.edit")]})]})}function B_({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:W_,children:[i.jsxs("span",{"data-testid":`${r}-chip`,style:j_,children:["🔗 ",d]}),i.jsx("button",{ref:l,type:"button","data-testid":`${r}-change`,onClick:()=>a(c=>!c),style:Io,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 W_={display:"flex",alignItems:"center",gap:6,width:"100%",minWidth:0,flexWrap:"wrap"},j_={fontSize:11,background:"#eef2ff",color:"#4338ca",padding:"3px 8px",borderRadius:12,wordBreak:"break-all"},H_={display:"flex",alignItems:"center",gap:8,width:"100%",minWidth:0},F_={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"},dc={fontSize:11,background:"#eef2ff",color:"#4338ca",padding:"1px 6px",borderRadius:10,whiteSpace:"nowrap"},cc={color:"#94a3b8"},K_={padding:"4px 10px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#2563eb",cursor:"pointer",whiteSpace:"nowrap",flexShrink:0},uc={padding:"3px 10px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},V_={padding:"3px 10px",fontSize:11,border:"1px solid #fca5a5",borderRadius:6,background:"#fef2f2",color:"#b91c1c",cursor:"pointer",whiteSpace:"nowrap"},U_={display:"flex",flexDirection:"column",gap:6,padding:10,border:"1px solid #fca5a5",borderRadius:8,background:"#fffbeb"},q_={margin:0,fontSize:12,color:"#334155"},G_={padding:"5px 8px",fontSize:12,color:"#0f172a",background:"#fff",border:"1px solid #e2e8f0",borderRadius:6,wordBreak:"break-all"},Y_={margin:0,fontSize:11,color:"#b45309"},X_={padding:"3px 12px",fontSize:11,border:"1px solid #dc2626",borderRadius:6,background:"#dc2626",color:"#fff",cursor:"pointer",whiteSpace:"nowrap"},J_={display:"flex",gap:4,alignItems:"center",width:"100%",minWidth:0},Z_={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:0,width:"100%"},pc={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},Io={padding:"4px 8px",fontSize:13,lineHeight:1,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},Q_={display:"flex",alignItems:"center",gap:6,width:"100%",minWidth:0,flexWrap:"wrap"},R_={flex:1,minWidth:0,display:"flex",flexWrap:"wrap",alignItems:"center",gap:4,fontSize:12,color:"#334155"},ex={fontSize:11,background:"#eef2ff",color:"#4338ca",padding:"2px 8px",borderRadius:12,whiteSpace:"nowrap"},tx={display:"flex",flexDirection:"column",gap:2,width:"100%"},nx={fontSize:11,background:"#f1f5f9",padding:"3px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all"},ox={fontSize:10,color:"#64748b"},rx={fontSize:11,color:"#94a3b8",padding:"6px 8px",border:"1px dashed #cbd5e1",borderRadius:6,background:"#f8fafc"};function ys({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))},y=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:ix,children:[i.jsxs("div",{style:sx,children:[r.map(g=>i.jsxs("span",{"data-testid":`g7le-tag-chip-${g}`,style:ax,children:[i.jsx("span",{style:lx,children:d(g)}),c(g)&&i.jsx("code",{"data-testid":`g7le-tag-chip-id-${g}`,style:dx,children:g}),i.jsx("button",{type:"button","aria-label":`remove ${g}`,"data-testid":`g7le-tag-remove-${g}`,onClick:()=>p(g),style:cx,children:"✕"})]},g)),i.jsx("button",{type:"button","data-testid":"g7le-tag-add",onClick:()=>l(g=>!g),disabled:y.length===0,style:ux,children:o("layout_editor.control.tag_add")})]}),a&&y.length>0&&i.jsx("div",{"data-testid":"g7le-tag-candidates",style:px,children:y.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:fx,children:[i.jsx("span",{style:gx,children:g.label}),m&&i.jsx("code",{"data-testid":`g7le-tag-candidate-id-${g.value}`,style:hx,children:g.value})]},g.value)})})]})}const ix={display:"flex",flexDirection:"column",gap:6},sx={display:"flex",flexWrap:"wrap",gap:4,alignItems:"center"},ax={display:"inline-flex",alignItems:"center",gap:4,padding:"2px 6px",fontSize:12,background:"#e0e7ff",color:"#1d4ed8",borderRadius:12},lx={fontSize:12},dx={fontSize:10,color:"#4f46e5",background:"#c7d2fe",borderRadius:4,padding:"0 4px",fontFamily:"monospace"},cx={border:"none",background:"transparent",color:"#1d4ed8",cursor:"pointer",fontSize:10,padding:0,lineHeight:1},ux={padding:"2px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:12,background:"#fff",cursor:"pointer",color:"#475569"},px={display:"flex",flexDirection:"column",maxHeight:180,overflowY:"auto",border:"1px solid #cbd5e1",borderRadius:6,background:"#fff"},fx={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"},gx={fontSize:12,color:"#0f172a"},hx={fontSize:10,color:"#64748b",fontFamily:"monospace"},fc=new Map;function Xe(e,t){fc.set(e,t)}function Tn(e){return e?fc.get(e)??null:null}function Tr(e,t){const o=e("meta",{})?.[t];return typeof o=="string"?o:""}function yx({getValue:e,patch:t,t:n,fieldT:o,spec:r,permissionCandidates:s,bindingCandidates:a}){const l=o??n,d=Tr(e,"title"),c=Tr(e,"description"),p=Tr(e,"icon"),f=Tr(e,"editor_label"),y=e("permissions",[]),g=u.useCallback((b,x)=>{const k={...e("meta",{})??{}};x===void 0||x===""?delete k[b]:k[b]=x,t("meta",k)},[e,t]),m=u.useCallback(b=>{const x=Array.isArray(b)?b:[];x.length===0?t("permissions",void 0):t("permissions",x)},[t]),h=Tn("icon-picker"),v=Ct(r,"icon-picker")??Ct(r,"icon")??(r?.controls?Object.values(r.controls).find(b=>b&&typeof b=="object"&&b.widget==="icon-picker")??null:null);return i.jsxs("div",{className:"g7le-meta-form","data-testid":"g7le-meta-form",style:mx,children:[i.jsx(Ao,{label:n("layout_editor.page_settings.meta.title"),children:i.jsx(vt,{value:d,onChange:b=>g("title",b),t:l,testidPrefix:"g7le-meta-title",candidates:a,enableExpressionTree:!0,expressionTreeCollapsible:!0})}),i.jsx(Ao,{label:n("layout_editor.page_settings.meta.description"),children:i.jsx(vt,{value:c,onChange:b=>g("description",b),t:l,testidPrefix:"g7le-meta-description",candidates:a,enableExpressionTree:!0,expressionTreeCollapsible:!0})}),i.jsx(Ao,{label:n("layout_editor.page_settings.meta.icon"),children:h?i.jsx(bx,{icon:p,t:n,onChange:b=>g("icon",typeof b=="string"?b: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:b=>g("icon",b.target.value),style:wx})}),i.jsx(Ao,{label:n("layout_editor.page_settings.meta.editor_label"),hint:n("layout_editor.page_settings.meta.editor_label_hint"),children:i.jsx(vt,{value:f,onChange:b=>g("editor_label",b),t:l,testidPrefix:"g7le-meta-editor-label",candidates:a,enableExpressionTree:!0,expressionTreeCollapsible:!0})}),i.jsx(Ao,{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(ys,{control:{widget:"tag-input"},value:y,onChange:m,t:n,candidates:s})})})]})}function Ao({label:e,hint:t,children:n}){return i.jsxs("div",{className:"g7le-meta-field",style:vx,children:[i.jsx("label",{style:_x,children:e}),n,t?i.jsxs("p",{style:xx,children:["ⓘ ",t]}):null]})}function bx({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 mx={display:"flex",flexDirection:"column",gap:16,minWidth:0},vx={display:"flex",flexDirection:"column",gap:6,minWidth:0},_x={fontSize:13,fontWeight:600,color:"#0f172a"},xx={margin:0,fontSize:11,color:"#94a3b8"},wx={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:0,width:"100%"};function Dr({checked:e,onChange:t,label:n,testid:o,ariaLabel:r,disabled:s=!1}){return i.jsxs("label",{style:{...Ex,...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:Ix(e,s),children:i.jsx("span",{style:Ax(e)})}),n!=null?i.jsx("span",{style:Tx(s),children:n}):null]})}function Nr({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 kx({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:Sx,children:[s,l?i.jsxs("button",{type:"button","data-testid":a?`${a}-revert`:void 0,onClick:n,title:r??o,"aria-label":o,style:$x,children:["↩ ",o]}):d?i.jsx("span",{"data-testid":a?`${a}-source`:void 0,title:r,style:Cx,children:t}):null]})}const Sx={position:"relative",minWidth:0,width:"100%"},Cx={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"},$x={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"},Ex={display:"inline-flex",alignItems:"center",gap:8,cursor:"pointer"},Ix=(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"}),Ax=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"}),Tx=e=>({fontSize:13,fontWeight:600,color:e?"#94a3b8":"#0f172a"}),Dx=/\$(?:core|module|plugin)_settings:[a-zA-Z0-9._:-]+/;function Nx(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 zx(e))s.kind==="text"?o(s.raw):r(s.raw,s.label,s.removable);return n||o(""),t}function zx(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=Dx.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 Mx(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 Lx(e,t,n){const o=Math.max(0,Math.min(t,e.length));return e.slice(0,o)+n+e.slice(o)}function Px(e,t){const n=e.indexOf(t);return n<0?e:e.slice(0,n)+e.slice(n+t.length)}function bs({value:e,onChange:t,t:n,candidates:o,onDone:r,testidPrefix:s="g7le-binding-chip-text",disabled:a=!1}){const l=u.useMemo(()=>Nx(e),[e]),d=u.useRef(null),c=!!o&&o.length>0,[p,f]=u.useState(null),[y,g]=u.useState(null),[m,h]=u.useState(null),[v,b]=u.useState(!1),x=u.useRef(0),k=u.useRef(null),w=u.useMemo(()=>l.map(L=>L.kind==="chip"?`c:${L.raw}`:"t").join("|"),[l]),_=u.useRef(null),C=u.useRef([]),E=u.useRef(!1);u.useLayoutEffect(()=>{const L=E.current;E.current=!1,!(!L&&_.current===w)&&(_.current=w,l.forEach((I,P)=>{if(I.kind!=="text")return;const F=C.current[P];F&&F.textContent!==(I.text??"")&&(F.textContent=I.text??"")}))},[w,l,e]);const S=u.useCallback(()=>{const L=d.current;if(!L)return e;const I=[];for(const P of Array.from(L.querySelectorAll("[data-seg]")))P.dataset.seg==="chip"?I.push(P.dataset.raw??""):I.push(P.textContent??"");return I.join("")},[e]),T=u.useCallback(()=>{a||t(S())},[a,t,S]),$=u.useRef(null),A=u.useRef(!1),z=(L,I)=>{if(!a){L.preventDefault(),L.stopPropagation(),$.current={raw:I,pointerId:L.pointerId},A.current=!1,f(I);try{L.currentTarget.setPointerCapture(L.pointerId)}catch{}}},D=L=>{const I=$.current;if(!I||L.pointerId!==I.pointerId)return;A.current=!0;const P=B(L.clientX,L.clientY);P&&(g({slotIdx:P.slotIdx,offset:P.offset}),h(Bx(d.current,P.slotIdx,P.offset)))},O=(L,I)=>{if(L.stopPropagation(),A.current){A.current=!1;return}E.current=!0,t(Px(e,I))},M=L=>{const I=$.current;if(!I||L.pointerId!==I.pointerId)return;try{L.currentTarget.releasePointerCapture(L.pointerId)}catch{}$.current=null,A.current&&typeof setTimeout=="function"&&setTimeout(()=>{A.current=!1},0);const P=B(L.clientX,L.clientY);if(f(null),g(null),h(null),!P)return;const F=d.current;if(!F)return;const V=Array.from(F.querySelectorAll("[data-seg]")).map(Z=>Z.dataset.seg==="chip"?{kind:"chip",raw:Z.dataset.raw??""}:{kind:"text",text:Z.textContent??""}),Y=Mx(V,I.raw,P.slotIdx,P.offset);Y!==e&&(E.current=!0,t(Y))},B=(L,I)=>{const P=d.current;if(!P)return null;const F=Array.from(P.querySelectorAll("[data-seg]")),G=P.ownerDocument,V=G.elementFromPoint(L,I),Y=V?.closest('[data-seg="text"]');if(Y)return{slotIdx:F.indexOf(Y),offset:Ox(G,Y,L,I)};const Z=V?.closest('[data-seg="chip"]');if(Z){const re=F.indexOf(Z),U=Z.getBoundingClientRect();if(L=0){const ee=F[re-1];return{slotIdx:re-1,offset:(ee.textContent??"").length}}if(re+1({s:re,i:U})).filter(re=>re.s.dataset.seg==="text").pop();return se?{slotIdx:se.i,offset:(se.s.textContent??"").length}:null},N=()=>{a||!c||(x.current=Wx(d.current,e.length),b(L=>!L))},H=L=>{const I=L.path?L.path.split(".").filter(Boolean):[],P=[L.sourceId,...I].join("?.");E.current=!0,t(Lx(e,x.current,`{{${P}}}`)),b(!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:jx,children:[l.map((L,I)=>L.kind==="chip"?i.jsxs("span",{"data-seg":"chip","data-raw":L.raw,"data-testid":`${s}-chip-${I}`,contentEditable:!1,onPointerDown:P=>z(P,L.raw??""),onPointerMove:D,onPointerUp:M,title:L.removable?n("layout_editor.value_tree.change_data"):n("layout_editor.prop_i18n.bound_code_only"),style:{...Vx,...p===L.raw?Ux:null,touchAction:"none"},children:[i.jsx("span",{"aria-hidden":"true",style:qx,children:"⠿"}),i.jsx("span",{"aria-hidden":"true",style:{marginRight:3},children:"🔗"}),i.jsx("span",{children:L.text}),L.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:P=>{P.stopPropagation(),P.preventDefault()},onClick:P=>O(P,L.raw??""),style:Gx,children:"✕"})]},`chip-${L.raw}-${I}`):i.jsx("span",{ref:P=>{C.current[I]=P},"data-seg":"text",contentEditable:!a,suppressContentEditableWarning:!0,onInput:T,"data-testid":`${s}-text-${I}`,style:{...Hx,...p?Fx:null,...y?.slotIdx===I?Kx: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:gc,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:k,type:"button","data-testid":`${s}-insert`,onClick:N,disabled:a,style:gc,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:k,open:v,onClose:()=>b(!1),children:i.jsx($t,{candidates:o,t:n,onSelect:H,testIdSuffix:`${s}-insert`,defaultOpen:!0,floating:!1})})]}),i.jsx("span",{style:Yx,children:n("layout_editor.translation.placeholder_locked")})]})]})}function Ox(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 Bx(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 y=p.getClientRects(),g=y.length>0?y[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 Wx(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 jx={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"},Hx={outline:"none",minWidth:8,minHeight:"1.2em",whiteSpace:"pre-wrap",color:"#0f172a",display:"inline-block",wordBreak:"break-all"},Fx={boxShadow:"inset 0 -2px 0 #93c5fd",background:"#eff6ff",borderRadius:2},Kx={background:"#dbeafe",boxShadow:"inset 0 -2px 0 #2563eb"},Vx={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"},Ux={opacity:.5,borderStyle:"solid",cursor:"grabbing"},qx={color:"#2563eb",opacity:.7,fontSize:11,marginRight:1,cursor:"grab"},Gx={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"},gc={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},Yx={fontSize:10,color:"#94a3b8"},Xx=ql;function ms(e){return _b(e)}function Ve({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),[y,g]=u.useState(!1),[m,h]=u.useState(!1),v=u.useCallback(E=>i.jsx(Ve,{value:E.value,onChange:S=>E.onChange(S),t:E.t,candidates:E.candidates,testidPrefix:E.testidPrefix,enableExpressionTree:!0}),[]),b=()=>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:E=>t(E.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"}})}),x=u.useCallback(E=>{const S=d?`${d} ${E.expression}`:E.expression;t(S)},[d,t]);if(!l||a)return i.jsxs("div",{"data-testid":s,style:pn,children:[b(),!a&&c&&i.jsx($t,{candidates:o,t:n,onSelect:x,testIdSuffix:`${s}-pick`})]});const k=Nv(d),w=Gd(d),_=Kt(d),C=E=>{const S=Sr(d),T=S?us(S,()=>"",$=>Vt($)):[];return i.jsxs(i.Fragment,{children:[i.jsx("div",{style:{display:"flex",justifyContent:"flex-start"},children:i.jsxs("button",{type:"button","data-testid":`${E}-to-plain`,onClick:()=>h(!0),style:Rx,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":`${E}-to-plain-confirm`,style:e0,children:[i.jsx("p",{style:t0,children:n("layout_editor.value_tree.to_plain_lead")}),i.jsx("div",{style:n0,children:T.length===0?i.jsx("span",{style:{color:"#94a3b8"},children:n("layout_editor.page_settings.seo.value_placeholder")}):T.map(($,A)=>$.kind==="chip"?i.jsxs("span",{style:vs,children:["🔗 ",$.text]},A):i.jsx("span",{style:$.kind==="ellipsis"?{color:"#94a3b8"}:void 0,children:$.text},A))}),i.jsxs("p",{style:o0,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":`${E}-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":`${E}-to-plain-confirm-ok`,onClick:()=>{h(!1),t(Sr(d)||"")},style:r0,children:n("layout_editor.value_tree.to_plain_ok")})]})]})]})};if(!p&&(k==="expression"||w)){if(w)return i.jsxs("div",{"data-testid":s,style:pn,children:[!a&&C(`${s}-seg`),i.jsx(gs,{value:d,onChange:S=>t(S),t:n,candidates:o,testidPrefix:`${s}-seg`,renderLeafInput:v})]});const E=un(d);return i.jsxs("div",{"data-testid":s,style:pn,children:[!a&&C(`${s}-tree`),i.jsx(nc,{node:E.node,onChange:S=>t(Zn(S,!1)),t:n,candidates:o,testidPrefix:`${s}-tree`,renderLeafInput:v})]})}if(_&&!p&&!y)return i.jsx(Jx,{value:d,onChange:t,t:n,candidates:o,testidPrefix:s,onEditRaw:()=>g(!0)});if(!p&&!y&&ms(d)){const E=Xx(d);return i.jsx("div",{"data-testid":s,style:pn,children:i.jsxs("div",{style:hc,children:[i.jsx("div",{"data-testid":`${s}-chips`,style:Zx,children:E.map((S,T)=>S.kind==="chip"?i.jsxs("span",{style:vs,children:["🔗 ",S.label]},T):i.jsx("span",{children:S.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 y&&ms(d)?i.jsxs("div",{"data-testid":s,style:pn,children:[i.jsx(bs,{value:d,onChange:t,t:n,candidates:o,disabled:a,onDone:()=>g(!1),testidPrefix:`${s}-chipedit`}),!a&&k!=="raw"&&i.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:[i.jsxs("button",{type:"button","data-testid":`${s}-to-expr`,onClick:()=>t(Co(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(ps(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")]})]}),k==="raw"&&i.jsxs("p",{"data-testid":`${s}-raw-hint`,style:_s,children:["ⓘ ",n("layout_editor.value_tree.raw_expression_hint")]})]}):!p&&ms(d)?i.jsxs("div",{"data-testid":s,style:pn,children:[i.jsx(bs,{value:d,onChange:t,t:n,candidates:o,disabled:a,onDone:()=>{g(!1),f(!1)},testidPrefix:`${s}-chipedit`}),!a&&k!=="raw"&&i.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:[i.jsxs("button",{type:"button","data-testid":`${s}-to-expr`,onClick:()=>t(Co(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(ps(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")]})]}),k==="raw"&&i.jsxs("p",{"data-testid":`${s}-raw-hint`,style:_s,children:["ⓘ ",n("layout_editor.value_tree.raw_expression_hint")]})]}):i.jsxs("div",{"data-testid":s,style:pn,children:[b(),i.jsxs("div",{style:Qx,children:[c&&i.jsx($t,{candidates:o,t:n,onSelect:x,testIdSuffix:`${s}-pick`}),k!=="raw"&&i.jsxs("div",{style:{display:"flex",gap:4},children:[i.jsxs("button",{type:"button","data-testid":`${s}-to-expr`,onClick:()=>t(Co(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(ps(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")]})]})]}),k==="raw"&&!p&&i.jsxs("p",{"data-testid":`${s}-raw-hint`,style:_s,children:["ⓘ ",n("layout_editor.value_tree.raw_expression_hint")]})]})}function Jx({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:hc,children:[i.jsxs("span",{"data-testid":`${r}-chip`,style:vs,children:["🔗 ",c]}),p&&i.jsx("button",{ref:d,type:"button","data-testid":`${r}-change`,onClick:()=>l(y=>!y),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:y=>{if(f){const h=[y.sourceId,...y.path?y.path.split(".").filter(Boolean):[]].join(".");t(`{{${f}(${h})}}`),l(!1);return}const g=y.path?y.path.split(".").filter(Boolean):[],m=[y.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},hc={display:"flex",alignItems:"center",gap:6,width:"100%",minWidth:0,flexWrap:"wrap"},Zx={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"},vs={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"},Qx={display:"flex",flexWrap:"wrap",alignItems:"center",gap:6},_s={margin:"2px 0 0",fontSize:11,color:"#94a3b8",lineHeight:1.4},Rx={padding:"3px 10px",fontSize:11,border:"1px solid #fca5a5",borderRadius:6,background:"#fef2f2",color:"#b91c1c",cursor:"pointer",whiteSpace:"nowrap"},e0={display:"flex",flexDirection:"column",gap:6,padding:10,border:"1px solid #fca5a5",borderRadius:8,background:"#fffbeb"},t0={margin:0,fontSize:12,color:"#334155"},n0={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"},o0={margin:0,fontSize:11,color:"#b45309"},r0={padding:"3px 12px",fontSize:11,border:"1px solid #dc2626",borderRadius:6,background:"#dc2626",color:"#fff",cursor:"pointer",whiteSpace:"nowrap"};let yc=0;function zr({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(k=>({id:yc++,k:typeof k[n]=="string"?k[n]:"",v:typeof k[o]=="string"?k[o]:""})),[]),[y,g]=u.useState(f),m=u.useCallback(k=>{g(k);const w=k.filter(_=>_.k.trim()!=="").map(_=>({[n]:_.k,[o]:_.v}));t(w)},[n,o,t]),h=u.useCallback(()=>{m([...y,{id:yc++,k:"",v:""}])},[y,m]),v=u.useCallback(k=>{m(y.filter(w=>w.id!==k))},[y,m]),b=u.useCallback((k,w)=>{m(y.map(_=>_.id===k?{..._,k:w}:_))},[y,m]),x=u.useCallback((k,w)=>{m(y.map(_=>_.id===k?{..._,v:w}:_))},[y,m]);return i.jsxs("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:6},children:[y.map(k=>i.jsxs("div",{"data-testid":`${a}-row-${k.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:k.k,onChange:w=>b(k.id,w),testid:`${a}-key-${k.id}`,placeholder:l??r(`layout_editor.page_settings.seo.extra_${n}`)})}):i.jsx("input",{type:"text","data-testid":`${a}-key-${k.id}`,value:k.k,placeholder:l??r(`layout_editor.page_settings.seo.extra_${n}`),onChange:w=>b(k.id,w.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(Ve,{value:k.v,onChange:w=>x(k.id,w),t:r,candidates:s,placeholder:d??r("layout_editor.page_settings.seo.extra_content"),testidPrefix:`${a}-value-${k.id}`})})]}),i.jsx("button",{type:"button","data-testid":`${a}-remove-${k.id}`,onClick:()=>v(k.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:"✕"})]},k.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 i0=["website","article","product","profile"],s0=["summary","summary_large_image","app","player"];function a0(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 bc(e){const t={};for(const n of e??[])t[n.key]=n;return t}function mc(e,t){return!!e&&t&&typeof e.sourceExpr=="string"&&e.sourceExpr!==""&&!e.overriddenByLayout&&!e.lockedByFilter}function vc({label:e,sourceExpr:t,onReplace:n,t:o,testid:r}){return i.jsxs("div",{"data-testid":r,style:b0,children:[i.jsxs("span",{"data-testid":`${r}-chip`,style:m0,title:t,children:["🔗 ",e||t]}),i.jsx("span",{"data-testid":`${r}-badge`,style:v0,children:o("layout_editor.page_settings.seo.auto_chip_source")}),i.jsx("button",{type:"button","data-testid":`${r}-replace`,onClick:n,style:_0,children:o("layout_editor.page_settings.seo.auto_chip_replace")})]})}function l0({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:{},[y,g]=u.useState(p.image_height!=null||p.image_type!=null||p.image_secure_url!=null),m=bc(r),h=bc(s),v=u.useCallback((T,$)=>{const A={...p};$===void 0||$===""||$===null?delete A[T]:A[T]=$,n(A)},[p,n]),b=u.useCallback((T,$)=>{const A={...f};$===void 0||$===""||$===null?delete A[T]:A[T]=$,o(A)},[f,o]),x=(T,$,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-${$}`,style:g0,children:["🔒 ",d("layout_editor.page_settings.seo.og_locked")]})}),k=T=>{if(!T||!a||T.lockedByFilter||T.overriddenByLayout)return;const $=a0(T.source);return $?d($):void 0},w=(T,$)=>T&&a?T.overriddenByLayout===!0:$!=="",_=(T,$,A,z,D,O)=>{const M=O[$],B=!!M?.lockedByFilter,N=typeof z[$]=="string"?z[$]:"";return i.jsxs("div",{"data-testid":`${T}-${$}`,style:Dn,children:[i.jsx("label",{style:to,children:d(A)}),B?i.jsx("div",{"data-testid":`${T}-locked-value-${$}`,style:f0,children:String(M?.effectiveValue??"")}):mc(M,a)?i.jsx(vc,{label:M.label??"",sourceExpr:M.sourceExpr,onReplace:()=>D($,M.sourceExpr),t:d,testid:`${T}-${$}-auto`}):i.jsx(vt,{value:N,onChange:H=>D($,H??""),t:d,candidates:l,placeholder:a&&M?.effectiveValue!=null?String(M.effectiveValue):void 0,testidPrefix:`${T}-${$}-field`,enableExpressionTree:!0,expressionTreeCollapsible:!0}),x(T,$,M)]})},C=(T,$,A,z,D,O)=>{const M=O[$],B=!!M?.lockedByFilter,N=typeof z[$]=="string"?z[$]:"";return i.jsxs("div",{"data-testid":`${T}-${$}`,style:Dn,children:[i.jsx("label",{style:to,children:d(A)}),mc(M,a)?i.jsx(vc,{label:M.label??"",sourceExpr:M.sourceExpr,onReplace:()=>D($,M.sourceExpr),t:d,testid:`${T}-${$}-auto`}):i.jsx(Ve,{value:N,onChange:H=>D($,H),t:d,candidates:l,readOnly:B,placeholder:a&&M?.effectiveValue!=null?String(M.effectiveValue):void 0,testidPrefix:`${T}-${$}-field`}),x(T,$,M)]})},E=(T,$,A,z,D,O)=>{const M=O[$],B=!!M?.lockedByFilter,N=typeof z[$]=="string"?z[$]:"",H=w(M,N),L=H?N:"";return i.jsxs("div",{"data-testid":`${T}-${$}`,style:Dn,children:[i.jsx("label",{style:to,children:d(A)}),i.jsx(kx,{filled:H,sourceLabel:k(M),onRevert:B?void 0:()=>D($,void 0),revertLabel:d("layout_editor.page_settings.seo.revert_default"),testid:`${T}-${$}-overlay`,children:i.jsx("div",{"data-testid":`${T}-${$}-input`,style:{minWidth:0},children:i.jsx(Ve,{value:L,onChange:I=>D($,I),t:d,candidates:l,readOnly:B,placeholder:a&&M?.effectiveValue!=null?String(M.effectiveValue):void 0,testidPrefix:`${T}-${$}-chip`})})}),x(T,$,M)]})},S=(T,$,A,z,D,O,M)=>{const B=M[$],N=typeof D[$]=="string"?D[$]:"",H=w(B,N),L=k(B),I=H?N:"";return i.jsxs("div",{"data-testid":`${T}-${$}`,style:Dn,children:[i.jsxs("div",{style:c0,children:[i.jsx("label",{style:to,children:d(A)}),L?i.jsxs("span",{"data-testid":`${T}-${$}-source-inline`,style:u0,children:["· ",L]}):null]}),i.jsxs("select",{"data-testid":`${T}-${$}-select`,value:I,onChange:P=>O($,P.target.value),style:p0,children:[i.jsx("option",{value:"",children:a&&B?.effectiveValue!=null&&B.effectiveValue!==""?`${d("layout_editor.page_settings.seo.use_default")} (${String(B.effectiveValue)})`:d("layout_editor.page_settings.seo.use_default")}),z.map(P=>i.jsx("option",{value:P,children:P},P))]}),x(T,$,B)]})};return i.jsxs("div",{"data-testid":c,style:{display:"flex",flexDirection:"column",gap:12},children:[i.jsxs("div",{"data-testid":`${c}-og-section`,style:_c,children:[i.jsx("div",{style:xc,children:d("layout_editor.page_settings.seo.og_section")}),i.jsxs("p",{"data-testid":`${c}-intro`,style:d0,children:["ⓘ ",d("layout_editor.page_settings.seo.og_intro")]}),S(c,"type","layout_editor.page_settings.seo.og_type",i0,p,v,m),_(c,"title","layout_editor.page_settings.seo.og_title",p,v,m),_(c,"description","layout_editor.page_settings.seo.og_description",p,v,m),C(c,"image","layout_editor.page_settings.seo.og_image",p,v,m),_(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":y,onClick:()=>g(T=>!T),style:h0,children:[y?"▾":"▸"," ",d("layout_editor.page_settings.seo.og_image_adv")]}),y?i.jsxs("div",{"data-testid":`${c}-image-adv`,style:y0,children:[E(c,"image_height","layout_editor.page_settings.seo.og_image_height",p,v,m),E(c,"image_type","layout_editor.page_settings.seo.og_image_type",p,v,m),E(c,"image_secure_url","layout_editor.page_settings.seo.og_image_secure_url",p,v,m)]}):null]}),E(c,"site_name","layout_editor.page_settings.seo.og_site_name",p,v,m),E(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(zr,{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:_c,children:[i.jsx("div",{style:xc,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")}),S("g7le-seo-tw","card","layout_editor.page_settings.seo.tw_card",s0,f,b,h),E("g7le-seo-tw","site","layout_editor.page_settings.seo.tw_site",f,b,h),E("g7le-seo-tw","creator","layout_editor.page_settings.seo.tw_creator",f,b,h),_("g7le-seo-tw","title","layout_editor.page_settings.seo.tw_title",f,b,h),_("g7le-seo-tw","description","layout_editor.page_settings.seo.tw_description",f,b,h),C("g7le-seo-tw","image","layout_editor.page_settings.seo.tw_image",f,b,h),_("g7le-seo-tw","image_alt","layout_editor.page_settings.seo.tw_image_alt",f,b,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(zr,{value:Array.isArray(f.extra)?f.extra:[],onChange:T=>b("extra",T.length>0?T:void 0),keyField:"name",t:d,candidates:l,testidPrefix:"g7le-seo-tw-extra-editor"})]})]})]})}const _c={border:"1px solid #e2e8f0",borderRadius:8,padding:12,display:"flex",flexDirection:"column",gap:10},xc={fontSize:13,fontWeight:600,color:"#0f172a"},d0={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"},c0={display:"flex",alignItems:"center",gap:6},u0={fontSize:11,color:"#94a3b8"},p0={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",minWidth:0,boxSizing:"border-box"},f0={padding:"5px 8px",fontSize:12,border:"1px solid #e2e8f0",borderRadius:6,background:"#f1f5f9",color:"#64748b"},g0={fontSize:11,color:"#7c3aed"},h0={alignSelf:"flex-start",padding:"2px 0",fontSize:12,fontWeight:600,color:"#475569",background:"transparent",border:"none",cursor:"pointer"},y0={display:"flex",flexDirection:"column",gap:8,paddingLeft:14,marginTop:4,minWidth:0},b0={display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",minWidth:0},m0={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"},v0={fontSize:11,color:"#94a3b8"},_0={padding:"2px 8px",fontSize:11,color:"#475569",background:"#fff",border:"1px solid #cbd5e1",borderRadius:6,cursor:"pointer"},x0=["WebPage","WebSite","ItemList","BreadcrumbList","Organization","Person","CollectionPage","AboutPage","ContactPage","SearchAction"];function Mr(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 wc(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?Mr(e).map(D=>({id:xs++,...D})):[]),x=u.useCallback((D,O)=>{h(D),b(O),t(wc(D,O.map(M=>({key:M.key,value:M.value}))))},[t]),k=u.useCallback(()=>{const D=n,O=typeof D["@type"]=="string"?D["@type"]:m,M=Mr(D).map(B=>({id:xs++,key:B.key,value:o?.[B.key]?.expr??B.value}));return{type:O,rows:M}},[n,o,m]),w=u.useCallback(D=>{if(y(D),D){if(v.length===0&&n&&typeof n=="object"){const O=k();x(O.type,O.rows);return}t(wc(m,v.map(O=>({key:O.key,value:O.value}))))}else t(null)},[m,v,n,k,x,t]),_=u.useCallback(()=>{if(!n)return;const D=k();x(D.type,D.rows)},[n,k,x]),C=u.useCallback(()=>{x(m,[...v,{id:xs++,key:"",value:""}])},[m,v,x]),E=u.useCallback(D=>{x(m,v.filter(O=>O.id!==D))},[m,v,x]),S=u.useCallback((D,O)=>{x(m,v.map(M=>M.id===D?{...M,key:O}:M))},[m,v,x]),T=u.useCallback((D,O)=>{x(m,v.map(M=>M.id===D?{...M,value:O}:M))},[m,v,x]),$=u.useMemo(()=>n?Mr(n):[],[n]),A=u.useMemo(()=>s?Mr(s):[],[s]),z=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:kc,children:[i.jsxs("div",{style:Sc,children:[i.jsx("span",{style:k0,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:S0,children:d("layout_editor.page_settings.seo.sd_filter_locked")})]}),i.jsxs("div",{"data-testid":`${c}-locked`,style:C0,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(O=>i.jsxs("div",{"data-testid":`${c}-filtered-row-${O.key}`,style:Cc,children:[i.jsx("code",{style:$c,children:O.key}),i.jsx("span",{style:Ec,children:O.value})]},O.key))]})]})]})}return i.jsxs("div",{"data-testid":c,style:kc,children:[i.jsx("div",{style:Sc,children:i.jsx(Dr,{checked:f,onChange:w,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:$0,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]}),$.length===0?i.jsx("p",{style:{margin:0,fontSize:12,color:"#94a3b8"},children:d("layout_editor.page_settings.seo.sd_auto_empty")}):$.map(D=>{const O=o?.[D.key];return i.jsxs("div",{"data-testid":`${c}-auto-row-${D.key}`,style:Cc,children:[i.jsx("code",{style:$c,children:D.key}),O?i.jsxs("span",{"data-testid":`${c}-auto-chip-${D.key}`,style:E0,title:O.expr,children:["🔗 ",O.label||O.expr]}):i.jsx("span",{style:Ec,children:D.value})]},D.key)})]}),i.jsxs("p",{"data-testid":`${c}-replace-warn`,style:I0,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:A0,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=>x(D.target.value,v),style:T0}),i.jsx("datalist",{id:`${c}-type-options`,children:x0.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:D0,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:O=>S(D.id,O.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(Ve,{value:D.value,onChange:O=>T(D.id,O),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:()=>E(D.id),title:d("layout_editor.page_settings.seo.remove"),"aria-label":d("layout_editor.page_settings.seo.remove"),style:N0,children:"✕"})]},D.id))}),i.jsxs("div",{style:{marginTop:8,display:"flex",gap:8},children:[i.jsxs("button",{type:"button","data-testid":`${c}-add`,onClick:C,style:Ic,children:["+ ",d("layout_editor.page_settings.seo.sd_add_prop")]}),n?i.jsxs("button",{type:"button","data-testid":`${c}-seed-from-module`,onClick:_,style:Ic,children:["↩ ",d("layout_editor.page_settings.seo.sd_seed_from_module")]}):null]}),i.jsxs("p",{"data-testid":`${c}-empty-note`,style:z0,children:["ⓘ ",d("layout_editor.page_settings.seo.sd_empty_note"),z?i.jsxs("span",{style:{color:"#b45309"},children:[" ",d("layout_editor.page_settings.seo.sd_has_empty")]}):null]})]})]})}const kc={display:"flex",flexDirection:"column"},Sc={display:"flex",alignItems:"center",gap:8},k0={fontSize:14},S0={fontSize:11,padding:"2px 6px",borderRadius:4,background:"#f1f5f9",color:"#64748b"},C0={marginTop:8,border:"1px solid #fcd34d",borderRadius:8,padding:10,background:"#fffbeb"},$0={border:"1px solid #e2e8f0",borderRadius:8,padding:10,background:"#f8fafc"},Cc={display:"flex",gap:8,alignItems:"center",padding:"2px 0"},$c={fontSize:11,color:"#475569",background:"#fff",padding:"2px 6px",borderRadius:4,minWidth:120},Ec={fontSize:11,color:"#0f172a",fontFamily:"monospace",wordBreak:"break-all"},E0={display:"inline-flex",alignItems:"center",padding:"2px 8px",fontSize:11,color:"#1d4ed8",background:"#eff6ff",border:"1px solid #bfdbfe",borderRadius:6},I0={margin:"6px 0 0",fontSize:12,color:"#64748b"},A0={margin:"0 0 8px",fontSize:12,color:"#b45309",background:"#fffbeb",border:"1px solid #fcd34d",borderRadius:6,padding:"6px 8px"},T0={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",minWidth:0},D0={display:"flex",gap:6,alignItems:"flex-start",border:"1px solid #e2e8f0",borderRadius:8,padding:8},N0={padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"},Ic={padding:"5px 10px",fontSize:12,border:"1px dashed #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},z0={margin:"8px 0 0",fontSize:11,color:"#94a3b8"},Ac=new Set(["core_setting","setting","query","route"]);function M0({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(_=>Ac.has(_.source)):[],[d,o]),p=u.useMemo(()=>o?d.filter(_=>_.source==="data"):[],[d,o]);u.useMemo(()=>new Set(c.map(_=>_.name)),[c]);const f=u.useMemo(()=>new Set(p.map(_=>_.name)),[p]),y=u.useMemo(()=>{const _=new Set;for(const C of d)Ac.has(C.source)&&_.add(C.name);return _},[d]),g=u.useMemo(()=>Object.keys(l).filter(_=>!f.has(_)),[l,f]),m=u.useCallback((_,C)=>{const E={...l};C===void 0?delete E[_]:E[_]=C,t(E)},[l,t]),[h,v]=u.useState(""),b=h.trim()!==""&&y.has(h.trim()),x=h.trim()!==""&&Object.prototype.hasOwnProperty.call(l,h.trim()),k=h.trim()!==""&&!b&&!x&&!f.has(h.trim()),w=u.useCallback(()=>{const _=h.trim();_===""||y.has(_)||Object.prototype.hasOwnProperty.call(l,_)||(t({...l,[_]:""}),v(""))},[h,y,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:L0,children:["⚠ ",s("layout_editor.page_settings.seo.vars_precondition")]}),c.length>0&&i.jsxs("div",{"data-testid":`${a}-auto-group`,style:ws,children:[i.jsx("div",{style:ks,children:s("layout_editor.page_settings.seo.vars_auto_group")}),c.map(_=>i.jsxs("div",{"data-testid":`g7le-seo-var-auto-${_.name}`,style:P0,children:[i.jsx("span",{style:O0,children:"🔒"}),i.jsx("code",{style:Ss,children:_.name}),i.jsxs("span",{style:B0,children:["〔",s("layout_editor.page_settings.seo.vars_auto"),"·",_.source,"〕"]}),_.owner?.name?i.jsx("span",{style:W0,children:_.owner.name}):null]},_.name))]}),p.length>0&&i.jsxs("div",{"data-testid":`${a}-data-group`,style:ws,children:[i.jsx("div",{style:ks,children:s("layout_editor.page_settings.seo.vars_data_group")}),p.map(_=>{const C=l[_.name]??"",E=C.trim()==="";return i.jsxs("div",{"data-testid":`g7le-seo-var-data-${_.name}`,style:Tc,children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[i.jsx("code",{style:Ss,children:_.name}),_.required?i.jsx("span",{"data-testid":`g7le-seo-var-required-${_.name}`,style:j0,children:"*"}):null]}),i.jsx(Ve,{value:C,onChange:S=>m(_.name,S??""),t:s,candidates:r,testidPrefix:`g7le-seo-var-data-field-${_.name}`}),_.required&&E?i.jsxs("p",{"data-testid":`g7le-seo-var-empty-warn-${_.name}`,style:Cs,children:["⚠ ",s("layout_editor.page_settings.seo.vars_required_empty")]}):null]},_.name)})]}),i.jsxs("div",{"data-testid":`${a}-custom-group`,style:ws,children:[i.jsx("div",{style:ks,children:s("layout_editor.page_settings.seo.vars_custom_group")}),g.map(_=>i.jsxs("div",{"data-testid":`g7le-seo-var-custom-${_}`,style:Tc,children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[i.jsx("code",{style:Ss,children:_}),i.jsx("button",{type:"button","data-testid":`g7le-seo-var-custom-remove-${_}`,onClick:()=>m(_,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(Ve,{value:l[_]??"",onChange:C=>m(_,C??""),t:s,candidates:r,testidPrefix:`g7le-seo-var-custom-field-${_}`})]},_)),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:_=>v(_.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:w,disabled:h.trim()===""||b||x,style:H0,children:["+ ",s("layout_editor.page_settings.seo.vars_add")]})]}),b?i.jsxs("p",{"data-testid":"g7le-seo-var-add-reserved-warn",style:Cs,children:["⚠ ",s("layout_editor.page_settings.seo.vars_name_reserved",{name:h.trim()})]}):null,x&&!b?i.jsxs("p",{"data-testid":"g7le-seo-var-add-duplicate-warn",style:Cs,children:["⚠ ",s("layout_editor.page_settings.seo.vars_name_duplicate",{name:h.trim()})]}):null,k?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 L0={fontSize:12,color:"#b45309",background:"#fffbeb",border:"1px solid #fcd34d",borderRadius:6,padding:"6px 8px"},ws={border:"1px solid #e2e8f0",borderRadius:8,padding:10,display:"flex",flexDirection:"column",gap:6},ks={fontSize:12,fontWeight:600,color:"#475569"},P0={display:"flex",alignItems:"center",gap:6,padding:"2px 0"},Tc={display:"flex",flexDirection:"column",border:"1px solid #f1f5f9",borderRadius:6,padding:8},O0={fontSize:13},Ss={fontSize:12,color:"#0f172a",background:"#f1f5f9",padding:"2px 6px",borderRadius:4},B0={fontSize:11,color:"#64748b"},W0={fontSize:11,color:"#94a3b8"},j0={color:"#dc2626",fontWeight:700},Cs={margin:"4px 0 0",fontSize:11,color:"#b45309"},H0={padding:"5px 10px",fontSize:12,border:"1px dashed #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"};function F0({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,y]=u.useState(!0),[g,m]=u.useState(null),[h,v]=u.useState(!1),[b,x]=u.useState(null),k=u.useRef(null),w=u.useRef({templateIdentifier:e,layout:t,url:n,locale:o,seedContext:r,routeParams:s});w.current={templateIdentifier:e,layout:t,url:n,locale:o,seedContext:r,routeParams:s};const _=u.useCallback(async()=>{const T=c??(typeof fetch<"u"?fetch:void 0);if(!T)return;const{templateIdentifier:$,layout:A,url:z,locale:D,seedContext:O,routeParams:M}=w.current;v(!0),x(null);try{const B=`/api/admin/templates/${encodeURIComponent($)}/editor/seo-bot-preview`,N=await T(B,{method:"POST",credentials:"same-origin",headers:je({"Content-Type":"application/json"}),body:JSON.stringify({layout:A,url:z,locale:D,seed_context:O??{},route_params:M??{}})}),H=await N.json().catch(()=>null);if(!N.ok){x(H?.message??`HTTP ${N.status}`);return}const L=H?.data??null;m(L)}catch(B){x(B instanceof Error?B.message:String(B))}finally{v(!1)}},[c]);u.useEffect(()=>{if(f)return k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{_()},d),()=>{k.current&&clearTimeout(k.current)}},[a,f,d,_]);const C=u.useCallback(()=>{k.current&&clearTimeout(k.current),_()},[_]),E=g?.html??null,S=g?.enabled??!0;return i.jsxs("div",{"data-testid":p,style:K0,children:[i.jsxs("div",{style:V0,children:[i.jsxs("button",{type:"button","data-testid":`${p}-toggle`,onClick:()=>y(T=>!T),"aria-expanded":f,style:U0,children:[f?"▾":"▸"," ",l("layout_editor.page_settings.seo.bot_preview_title")]}),f?i.jsxs("button",{type:"button","data-testid":`${p}-refresh`,onClick:C,disabled:h,style:q0,children:["⟳ ",l("layout_editor.page_settings.seo.bot_preview_refresh")]}):null]}),f&&i.jsxs("div",{style:{marginTop:8},children:[g&&!S?i.jsxs("p",{"data-testid":`${p}-disabled`,style:G0,children:["ⓘ ",l("layout_editor.page_settings.seo.bot_preview_disabled")]}):i.jsx("div",{"data-testid":`${p}-body`,style:Y0,children:h&&!E?i.jsx("p",{style:$s,children:l("layout_editor.translation.loading")}):b?i.jsx("p",{"data-testid":`${p}-error`,style:{...$s,color:"#dc2626"},children:b}):E==null?i.jsx("p",{style:$s,children:l("layout_editor.page_settings.seo.bot_preview_empty")}):i.jsx("pre",{"data-testid":`${p}-code`,style:X0,children:E})}),i.jsxs("p",{"data-testid":`${p}-sample-note`,style:J0,children:["ⓘ ",l("layout_editor.page_settings.seo.bot_preview_sample_note")]})]})]})}const K0={borderTop:"1px solid #e2e8f0",paddingTop:10,marginTop:12},V0={display:"flex",alignItems:"center",gap:8},U0={background:"none",border:"none",cursor:"pointer",fontSize:13,fontWeight:600,color:"#0f172a",padding:0},q0={marginLeft:"auto",padding:"4px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},G0={margin:0,fontSize:12,color:"#64748b",background:"#f8fafc",border:"1px solid #e2e8f0",borderRadius:6,padding:"8px 10px"},Y0={border:"1px solid #e2e8f0",borderRadius:8,background:"#0b1020",padding:0,minHeight:80,overflow:"hidden"},X0={margin:0,padding:12,fontSize:11,lineHeight:1.5,color:"#d1fae5",fontFamily:"monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto"},$s={margin:0,padding:12,fontSize:12,color:"#94a3b8"},J0={margin:"8px 0 0",fontSize:11,color:"#94a3b8"};function Dc({option:e,testIdPrefix:t}){const{id:n,friendly:o,source:r}=e;return i.jsxs("span",{style:Z0,children:[i.jsx("span",{"data-testid":t?`${t}-title`:void 0,style:Q0,children:o??n}),o?i.jsx("span",{"data-testid":t?`${t}-id`:void 0,style:R0,children:n}):null,r?i.jsx("span",{"data-testid":t?`${t}-source`:void 0,style:ew,children:r}):null]})}const Z0={display:"inline-flex",alignItems:"baseline",gap:4,flexWrap:"wrap",minWidth:0},Q0={fontSize:12,color:"#0f172a"},R0={fontSize:10,color:"#94a3b8",fontFamily:"ui-monospace, monospace"},ew={fontSize:9,fontWeight:600,color:"#7c3aed",background:"#f5f3ff",border:"1px solid #ddd6fe",borderRadius:4,padding:"0 5px",whiteSpace:"nowrap"},tw=["always","hourly","daily","weekly","monthly","yearly","never"];function nw({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:y,testidPrefix:g="g7le-seo"}){const m=e("meta",{}).seo,h=m&&typeof m=="object"?m:{},v=u.useCallback((K,ne)=>{const me={...e("meta",{})},Ce={...me.seo??{}};ne==null||ne===""?delete Ce[K]:Ce[K]=ne,me.seo=Ce,t("meta",me)},[e,t]),b=h.enabled===!0,x=typeof h.page_type=="string"?h.page_type:"",k=Array.isArray(h.extensions)?h.extensions:[],w=Array.isArray(h.data_sources)?h.data_sources:[],_=k.length>0&&x!=="",[C,E]=u.useState(null),[S,T]=u.useState(null),$=u.useCallback(async(K,ne)=>{if(p)return p(K,ne);if(typeof fetch>"u")return null;const me=new URLSearchParams;K&&me.set("page_type",K),Array.isArray(ne)&&ne.length>0&&me.set("extensions",JSON.stringify(ne.map(qe=>({type:qe.type,id:qe.id}))));const Ce=me.toString()?`?${me.toString()}`:"",ze=await fetch(en(`/api/admin/templates/${encodeURIComponent(o)}/editor/seo-candidates`,"json",null,Ce.replace(/^[?&]+/,"")),{credentials:"same-origin",headers:je()}),Se=await ze.json().catch(()=>null);return ze.ok?Se?.data??null:null},[p,o]),A=u.useMemo(()=>{const me=(e("__editor",{})??{}).original?.meta?.seo;return me&&typeof me=="object"?me:void 0},[e]),z=u.useRef(A);z.current=A;const D=u.useCallback(async K=>{if(f)return f(K);if(typeof fetch>"u")return null;const ne=await fetch(`/api/admin/templates/${encodeURIComponent(o)}/editor/seo-og-preview`,{method:"POST",credentials:"same-origin",headers:je({"Content-Type":"application/json"}),body:JSON.stringify({seo:K,own_seo:z.current??null,seed_context:c??{},route_params:{}})}),me=await ne.json().catch(()=>null);return ne.ok?me?.data??null:null},[f,o,c]),O=u.useMemo(()=>JSON.stringify(k),[k]),M=u.useRef(h);M.current=h,u.useEffect(()=>{let K=!1;return(async()=>{const ne=await $(x,k);K||E(ne)})(),()=>{K=!0}},[x,O]);const B=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]),N=u.useRef(!1);u.useEffect(()=>{let K=!1;const ne=()=>{(async()=>{const Ce=await D(M.current);K||T(Ce)})()};if(!N.current)return N.current=!0,ne(),()=>{K=!0};const me=setTimeout(ne,180);return()=>{K=!0,clearTimeout(me)}},[x,O,B]);const H=C?.page_types??[],L=C?.toggle_settings??[],I=C?.vars??[],P=u.useMemo(()=>JSON.stringify(h),[h]),F=u.useMemo(()=>e("meta")?{meta:e("meta"),components:e("components",[])}:{meta:{},components:[]},[e]),G=u.useCallback(K=>{k.some(ne=>ne.type===K.type&&ne.id===K.id)||v("extensions",[...k,{type:K.type,id:K.id}])},[k,v]),V=u.useCallback(K=>{const ne=k.filter(me=>!(me.type===K.type&&me.id===K.id));v("extensions",ne.length>0?ne:void 0)},[k,v]),[Y,Z]=u.useState(!1),[se,re]=u.useState(""),U=u.useMemo(()=>{const K=se.trim().toLowerCase();return K?L.filter(ne=>`${ne.ref} ${ne.label??""}`.toLowerCase().includes(K)):L},[L,se]),ee=typeof h.toggle_setting=="string"?h.toggle_setting:"",fe=u.useCallback(K=>{const me=w.includes(K)?w.filter(Ce=>Ce!==K):[...w,K];v("data_sources",me.length>0?me:void 0)},[w,v]);return i.jsxs("div",{"data-testid":g,style:{display:"flex",flexDirection:"column",gap:14},children:[i.jsxs("div",{style:Bt,children:[i.jsx(Dr,{checked:b,onChange:K=>v("enabled",K),testid:`${g}-enabled`,label:n("layout_editor.page_settings.seo.enabled")}),b?null:i.jsxs("p",{"data-testid":`${g}-disabled-note`,style:no,children:["ⓘ ",n("layout_editor.page_settings.seo.disabled_note")]})]}),i.jsx(Nr,{disabled:!b,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:x,onChange:K=>v("page_type",K.target.value),style:Lr,children:[i.jsx("option",{value:"",children:n("layout_editor.page_settings.seo.page_type_none")}),H.map(K=>i.jsxs("option",{value:K.value,children:[K.label??K.value,K.owner?.name?` (${K.owner.name})`:""]},K.value))]}):i.jsxs(i.Fragment,{children:[i.jsx("input",{type:"text","data-testid":`${g}-page-type-free`,value:x,placeholder:n("layout_editor.page_settings.seo.page_type_free_placeholder"),onChange:K=>v("page_type",K.target.value),style:Lr}),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:[k.map(K=>i.jsxs("span",{"data-testid":`${g}-extension-${K.type}-${K.id}`,style:Nc,children:[K.name??`${K.type}:${K.id}`,i.jsx("button",{type:"button","data-testid":`${g}-extension-remove-${K.type}-${K.id}`,onClick:()=>V(K),style:zc,children:"✕"})]},`${K.type}:${K.id}`)),i.jsxs("button",{type:"button","data-testid":`${g}-extension-add`,onClick:()=>Z(K=>!K),style:iw,children:["+ ",n("layout_editor.page_settings.seo.add_extension")]})]}),Y&&i.jsx("div",{"data-testid":`${g}-extension-picker`,style:Mc,children:s.length===0?i.jsx("p",{style:no,children:n("layout_editor.page_settings.seo.no_extension_candidate")}):s.map(K=>i.jsx("button",{type:"button","data-testid":`${g}-extension-option-${K.type}-${K.id}`,onClick:()=>{G(K),Z(!1)},style:Lc,children:K.name??`${K.type}:${K.id}`},`${K.type}:${K.id}`))})]}),!_&&i.jsxs("div",{"data-testid":`${g}-defaults-precondition`,style:rw,children:["⚠ ",n("layout_editor.page_settings.seo.defaults_precondition"),i.jsxs("div",{"data-testid":`${g}-defaults-missing`,style:{fontSize:11,marginTop:4},children:[k.length===0?n("layout_editor.page_settings.seo.missing_extensions"):"",x===""?` ${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:Nc,children:ee}),i.jsx("button",{type:"button","data-testid":`${g}-toggle-setting-clear`,onClick:()=>v("toggle_setting",void 0),style:zc,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:K=>re(K.target.value),style:Lr}),se.trim()!==""&&i.jsx("div",{"data-testid":`${g}-toggle-setting-results`,style:Mc,children:U.length===0?i.jsx("p",{style:no,children:n("layout_editor.inline_binding.no_results")}):U.map(K=>i.jsx("button",{type:"button","data-testid":`${g}-toggle-setting-option-${K.ref}`,onClick:()=>{v("toggle_setting",K.ref),re("")},style:Lc,children:K.label??K.ref},K.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(K=>{const ne=w.includes(K.id);return i.jsxs("label",{"data-testid":`${g}-data-source-${K.id}`,style:ow(ne),children:[i.jsx("input",{type:"checkbox","data-testid":`${g}-data-source-check-${K.id}`,checked:ne,onChange:()=>fe(K.id)}),i.jsx(Dc,{option:K,testIdPrefix:`${g}-data-source-${K.id}`})]},K.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:K=>v("priority",Number(K.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:K=>v("changefreq",K.target.value),style:Lr,children:[i.jsx("option",{value:"",children:n("layout_editor.page_settings.seo.use_default")}),tw.map(K=>i.jsx("option",{value:K,children:K},K))]})]}),i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.title")}),i.jsx(vt,{value:typeof h.title=="string"?h.title:"",onChange:K=>v("title",K??""),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(vt,{value:typeof h.description=="string"?h.description:"",onChange:K=>v("description",K??""),t:n,candidates:r,testidPrefix:`${g}-description`,enableExpressionTree:!0,expressionTreeCollapsible:!0})]}),i.jsx(l0,{og:h.og,twitter:h.twitter,onChangeOg:K=>v("og",Object.keys(K).length>0?K:void 0),onChangeTwitter:K=>v("twitter",Object.keys(K).length>0?K:void 0),ogPreview:S?.og,twitterPreview:S?.twitter,defaultsAvailable:S?.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(w0,{value:h.structured_data,onChange:K=>v("structured_data",K??void 0),autoBlock:S?.structured?.autoBlock,autoMeta:S?.structured?.autoMeta,lockedByFilter:S?.structured?.lockedByFilter,filteredBlock:S?.structured?.filteredBlock,pageType:x,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(M0,{vars:h.vars,onChange:K=>v("vars",Object.keys(K).length>0?K:void 0),varCandidates:I,gatingMet:_,candidates:r,t:n})]}),i.jsx(F0,{templateIdentifier:o,layout:F,url:l,locale:d,seedContext:c,settingsSignature:P,t:n,fetchImpl:y})]})})]})}const Bt={display:"flex",flexDirection:"column",gap:4},qt={fontSize:12,fontWeight:600,color:"#334155"},Lr={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"},ow=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}),rw={fontSize:12,color:"#b45309",background:"#fffbeb",border:"1px solid #fcd34d",borderRadius:6,padding:"8px 10px"},Nc={display:"inline-flex",alignItems:"center",gap:4,fontSize:11,padding:"3px 8px",borderRadius:999,background:"#eef2ff",color:"#3730a3"},zc={border:"none",background:"transparent",cursor:"pointer",color:"#6366f1",fontSize:11,padding:0},iw={fontSize:11,padding:"3px 10px",borderRadius:999,border:"1px dashed #cbd5e1",background:"#f8fafc",color:"#475569",cursor:"pointer"},Mc={marginTop:4,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",padding:6,display:"flex",flexDirection:"column",gap:2},Lc={textAlign:"left",border:"none",background:"transparent",cursor:"pointer",padding:"5px 8px",borderRadius:4,fontSize:12,color:"#0f172a"},sw={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"},aw={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"},lw={init:["state","data","notify","nav","locale","etc","flow","error","extension"],component:["nav","notify","data","state","locale","etc","flow","error","extension"]};function dw(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 cw(e,t){return!e||e.kind==="core"?t("layout_editor.action.source_core"):e.id??t(`layout_editor.action.source_${e.kind}`)}function Pc(e,t,n){return typeof e!="string"?n:e.startsWith("$t:")?t(e.slice(3)):e}function uw({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(()=>wo(e),[e]),p=u.useMemo(()=>{const f=lw[o],y=new Map;for(const m of c){const h=dw(e,m.id),b=h!=null&&h.kind!=="core"?"extension":sw[m.id]??"etc",x=y.get(b)??[];x.push({recipe:m,source:h}),y.set(b,x)}const g=l.trim().toLowerCase();return f.map(m=>{let h=y.get(m)??[];return g&&(h=h.filter(({recipe:v})=>Pc(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:xw,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:pw,children:[t("layout_editor.action.add_action")," ▾"]}),s?i.jsxs("div",{"data-testid":`${r}-list`,style:fw,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:gw}),p.map(({groupKey:f,items:y})=>i.jsxs("div",{"data-testid":`${r}-group-${f}`,children:[i.jsxs("div",{style:hw,children:["━━ ",t(aw[f]??f)," ━━"]}),y.map(({recipe:g,source:m})=>i.jsxs("button",{type:"button","data-testid":`g7le-init-action-spec-${g.id}`,onClick:()=>{n(xr(g,{})),a(!1),d("")},style:yw,children:[i.jsx("span",{style:bw,children:Pc(g.label,t,g.id)}),i.jsxs("span",{"data-testid":`g7le-init-action-spec-source-${g.id}`,style:mw,children:["〔",cw(m,t),"〕"]}),i.jsx("code",{style:vw,children:g.build.handler})]},g.id))]},f)),p.length===0?i.jsx("div",{"data-testid":`${r}-no-match`,style:_w,children:t("layout_editor.action.add_no_match")}):null]}):null]})}const pw={padding:"6px 12px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},fw={marginTop:6,border:"1px solid #cbd5e1",borderRadius:8,background:"#fff",maxHeight:320,overflowY:"auto",padding:8},gw={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,marginBottom:6,boxSizing:"border-box"},hw={fontSize:11,fontWeight:700,color:"#94a3b8",padding:"6px 4px 2px"},yw={display:"flex",alignItems:"center",gap:6,width:"100%",textAlign:"left",padding:"6px 8px",fontSize:12,border:"none",background:"transparent",cursor:"pointer",borderRadius:6},bw={flex:1,minWidth:0,color:"#0f172a"},mw={fontSize:10,color:"#64748b",whiteSpace:"nowrap"},vw={fontSize:10,color:"#cbd5e1",fontFamily:"monospace",whiteSpace:"nowrap"},_w={fontSize:12,color:"#94a3b8",padding:"8px 4px"},xw={fontSize:12,color:"#94a3b8",padding:"8px 0"};function ww(e,t){return t.startsWith("$t:")?e(t.slice(3)):t}function kw({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?Wd(t,n,p=>ww(o,p)):typeof e.handler=="string"?e.handler:o("layout_editor.action.advanced_action");return i.jsxs("div",{className:a,"data-testid":a,style:Sw,children:[r?i.jsxs("span",{"data-testid":`${a}-missing`,style:$w,children:["⚠ ",o("layout_editor.action.summary_missing_required")]}):i.jsx("span",{"data-testid":`${a}-summary`,style:Cw,children:c}),s?i.jsx("button",{type:"button","data-testid":`${a}-code-toggle`,onClick:()=>d(p=>!p),style:Ew,"aria-expanded":l,"aria-label":o("layout_editor.action.view_code"),children:""}):null,s&&l?i.jsx("pre",{"data-testid":`${a}-code`,style:Iw,children:JSON.stringify(e,null,2)}):null]})}const Sw={display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,minWidth:0},Cw={flex:1,minWidth:0,fontSize:12,color:"#475569"},$w={flex:1,minWidth:0,fontSize:12,color:"#b45309"},Ew={border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",fontSize:11,padding:"2px 6px",whiteSpace:"nowrap"},Iw={flexBasis:"100%",margin:"6px 0 0",padding:8,background:"#0f172a",color:"#e2e8f0",borderRadius:6,fontSize:11,overflow:"auto"},Oc="__g7le_custom__";function Pr({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(y=>y.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:Hc,children:[i.jsxs("select",{className:"g7le-widget g7le-widget--picker","data-testid":r,value:c?l:"",onChange:y=>{const g=y.target.value;if(g===Oc){f(!0);return}t(g===""?void 0:g)},style:{...Wc,flex:1,minWidth:0},children:[i.jsx("option",{value:"",children:s("layout_editor.control.default")}),n.map(y=>i.jsx("option",{value:y.value,children:y.label},y.value)),i.jsx("option",{value:Oc,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:Fc,children:"✎"})]}):i.jsxs("div",{style:Hc,children:[i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(Ve,{value:l,onChange:y=>t(y===""?void 0:y),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:Fc,children:"≡"})]})}function Aw({value:e,onChange:t,candidates:n,t:o,bindingCandidates:r}){return i.jsx(Pr,{value:e,onChange:t,candidates:n,placeholder:o("layout_editor.recipe.page_placeholder"),testid:"g7le-widget-page-picker",t:o,bindingCandidates:r})}function Bc({value:e,onChange:t,candidates:n,t:o,bindingCandidates:r}){return i.jsx(Pr,{value:e,onChange:t,candidates:n,placeholder:o("layout_editor.recipe.datasource_placeholder"),testid:"g7le-widget-datasource-picker",t:o,bindingCandidates:r})}function Es({value:e,onChange:t,candidates:n,t:o,bindingCandidates:r}){return i.jsx(Pr,{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 Tw({value:e,onChange:t,candidates:n,t:o,bindingCandidates:r}){return i.jsx(Pr,{value:e,onChange:t,candidates:n,placeholder:o("layout_editor.recipe.modal_placeholder"),testid:"g7le-widget-modal-picker",t:o,bindingCandidates:r})}function Dw({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(vt,{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 Nw({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:jc}),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:{...Wc,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 zw({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:jc})}const Wc={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",minWidth:140,width:"100%"},jc={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:100,width:"100%"},Hc={display:"flex",gap:4,alignItems:"flex-start",width:"100%"},Fc={padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"};function Mw(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 Kc(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 Is(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}function Lw(e,t,n){return t.includes(n)?"self":e.includes(n)?"inherited":"self"}function Pw(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 Vc=[{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 Nn({value:e,onChange:t,t:n,path:o,scope:r,depth:s=0,renderStringLeaf:a}){const l=Mw(e),d=c=>{t(Kc(c))};return i.jsxs("div",{className:"g7le-initstate-value",style:{paddingLeft:s>0?12:0,minWidth:0},children:[i.jsxs("div",{style:Bw,children:[i.jsx("select",{"data-testid":`g7le-initstate-type-${o}`,value:l,onChange:c=>d(c.target.value),style:Uc,children:Vc.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:qc}):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:qc}):l==="boolean"?i.jsx(Dr,{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:Ww,children:"null"}):null]}),l==="list"?i.jsxs("div",{style:Gc,children:[e.map((c,p)=>i.jsxs("div",{style:jw,children:[i.jsxs("span",{style:Hw,children:["[",p,"]"]}),i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(Nn,{value:c,onChange:f=>{const y=e.slice();y[p]=f,t(y)},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,y)=>y!==p)),style:Yc,children:"✕"})]},p)),i.jsxs("button",{type:"button","data-testid":`g7le-initstate-item-add-${o}`,onClick:()=>t([...e,""]),style:Xc,children:["+ ",n("layout_editor.initstate.add_item")]})]}):null,l==="object"?i.jsx(Ow,{value:e,onChange:t,t:n,path:o,scope:r,depth:s+1,renderStringLeaf:a}):null]})}function Ow({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,y]=u.useState(null),g=Object.entries(e),m=()=>{const h=l.trim();if(!h){y(n("layout_editor.initstate.name_required"));return}if(!Is(h)){y(n("layout_editor.initstate.name_invalid"));return}if(h in e){y(n("layout_editor.initstate.name_duplicate"));return}t({...e,[h]:Kc(c)}),d(""),y(null)};return i.jsxs("div",{style:Gc,children:[g.map(([h,v])=>i.jsxs("div",{style:Fw,children:[i.jsx("code",{style:Kw,children:h}),i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(Nn,{value:v,onChange:b=>t({...e,[h]:b}),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 b={...e};delete b[h],t(b)},style:Yc,children:"✕"})]},h)),i.jsxs("div",{style:Vw,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&&y(null)},onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),m())},"aria-invalid":f?!0:void 0,style:{...Uw,...f?qw: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:Uc,children:Vc.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:Xc,children:["+ ",n("layout_editor.initstate.add_subkey")]})]}),f?i.jsx("p",{"data-testid":`g7le-initstate-subkey-error-${o}`,style:Gw,children:f}):null]})}const Bw={display:"flex",gap:6,alignItems:"center",minWidth:0},Uc={padding:"4px 6px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,color:"#64748b"},qc={flex:1,minWidth:0,padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},Ww={fontSize:12,color:"#94a3b8",fontFamily:"monospace"},Gc={display:"flex",flexDirection:"column",gap:6,marginTop:6,paddingLeft:8,borderLeft:"2px solid #e2e8f0"},jw={display:"flex",gap:6,alignItems:"flex-start",minWidth:0},Hw={fontSize:11,color:"#94a3b8",minWidth:28,paddingTop:4},Fw={display:"flex",gap:6,alignItems:"flex-start",minWidth:0},Kw={fontSize:11,color:"#475569",fontFamily:"monospace",minWidth:72,paddingTop:4},Yc={border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12},Xc={alignSelf:"flex-start",padding:"2px 8px",fontSize:11,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},Vw={display:"flex",gap:6,alignItems:"center"},Uw={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6},qw={border:"1px solid #dc2626"},Gw={margin:"2px 0 0",fontSize:11,color:"#dc2626"},Yw=new Set(["text","data-chip","number"]),Xw=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 Jw(e,t,n){return typeof e!="string"?n:e.startsWith("$t:")?t(e.slice(3)):e}function Zw(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 Qw({param:e,value:t,t:n,pools:o,onChange:r,testIdPrefix:s,renderActionList:a,siblingValues:l}){const d=Jw(e.label,n,e.key);if(e.advanced)return i.jsxs("div",{"data-testid":`${s}-locked-${e.key}`,style:lk,children:[i.jsx("span",{style:dk,children:d}),i.jsxs("span",{style:ck,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(y=>!!y&&typeof y=="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,y=>r(y.length===0?void 0:y),`${s}-${e.key}`,e.key)]})}if(e.widget==="branch-list"&&a){const f=Array.isArray(t)?t.filter(y=>!!y&&typeof y=="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(Rw,{branches:f,onChange:y=>r(y.length===0?void 0:y),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(rk,{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(ik,{value:t,onChange:r,t:n,candidates:o.bindingCandidates,stateKeyCandidates:o.stateKeyCandidates,param:e,siblingTarget:l?.target,testIdPrefix:`${s}-skv-${e.key}`})]});if(Yw.has(e.widget??"")||!Xw.has(e.widget??""))return i.jsxs("div",{"data-testid":`${s}-param-${e.key}`,style:Zc,children:[i.jsx("span",{style:oo,children:d}),i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(Ve,{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:Zc,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:Zw(e.widget,o),bindingCandidates:o.bindingCandidates}):i.jsx(Ve,{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 Rw({branches:e,onChange:t,t:n,pools:o,renderActionList:r,testIdPrefix:s}){const a=y=>Array.isArray(y)?y.filter(g=>!!g&&typeof g=="object"):y&&typeof y=="object"?[y]:[],l=y=>{if(y.length!==0)return y.length===1?y[0]:y},d=(y,g)=>{const m=e.slice();m[y]=g,t(m)},c=y=>{t(e.filter((g,m)=>m!==y))},p=(y,g)=>{if(g<0||g>=e.length)return;const m=e.slice(),[h]=m.splice(y,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((y,g)=>{const m=typeof y.if=="string"?y.if:"",h=a(y.then);return i.jsxs("div",{"data-testid":`${s}-branch-${g}`,style:ek,children:[i.jsxs("div",{style:tk,children:[i.jsxs("span",{style:nk,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:As,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:As,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:As,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:Jc,children:n("layout_editor.action_recipe.conditions.param_if")}),i.jsx(Ve,{value:m,onChange:v=>d(g,{...y,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:Jc,children:n("layout_editor.action_recipe.conditions.param_then")}),r(h,v=>d(g,{...y,then:l(v)}),`${s}-branch-${g}-then`)]})]},g)}),i.jsxs("button",{type:"button","data-testid":`${s}-add-branch`,onClick:f,style:ok,children:["+ ",n("layout_editor.action_recipe.conditions.add_branch")]})]})}const ek={border:"1px solid #e2e8f0",borderRadius:6,padding:8,display:"flex",flexDirection:"column",gap:6,background:"#f8fafc"},tk={display:"flex",justifyContent:"space-between",alignItems:"center"},nk={fontSize:12,fontWeight:700,color:"#475569"},Jc={fontSize:11,color:"#64748b"},As={border:"1px solid #cbd5e1",background:"#fff",borderRadius:4,width:22,height:22,cursor:"pointer",fontSize:12,lineHeight:"1",color:"#475569"},ok={border:"1px dashed #94a3b8",background:"#fff",borderRadius:6,padding:"6px 10px",cursor:"pointer",fontSize:12,color:"#475569",alignSelf:"flex-start"};function rk({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(zr,{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 ik({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 b=d[0][1];return i.jsx("div",{"data-testid":`${l}-path-value`,style:{display:"flex",flexDirection:"column",gap:4},children:i.jsx(Nn,{value:b,onChange:x=>t(x===void 0?void 0:{value:x}),t:n,path:"value",scope:`${l}-path-value-val`,renderStringLeaf:x=>i.jsx(Ve,{value:x.value,onChange:x.onChange,t:n,candidates:o,testidPrefix:x.testidPrefix})})})}const y=(b,x)=>{const k={};for(const[w,_]of d)k[w]=w===b?x:_;t(Object.keys(k).length===0?void 0:k)},g=b=>{const x={};for(const[k,w]of d)k!==b&&(x[k]=w);t(Object.keys(x).length===0?void 0:x)},[m,h]=u.useState(""),v=()=>{const b=m.trim();if(b===""||d.some(([k])=>k===b))return;const x={};for(const[k,w]of d)x[k]=w;x[b]="",t(x),h("")};return i.jsxs("div",{"data-testid":l,style:{display:"flex",flexDirection:"column",gap:6},children:[d.map(([b,x])=>i.jsxs("div",{"data-testid":`${l}-row-${b}`,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(Es,{control:{...s},value:b,onChange:k=>{const w=k==null?"":String(k);if(w===""||w===b||d.some(([C])=>C===w))return;const _={};for(const[C,E]of d)_[C===b?w:C]=E;t(_)},t:n,candidates:r})}),i.jsx("div",{style:{minWidth:0},children:i.jsx(Nn,{value:x,onChange:k=>y(b,k),t:n,path:b,scope:`${l}-val`,renderStringLeaf:k=>i.jsx(Ve,{value:k.value,onChange:k.onChange,t:n,candidates:o,testidPrefix:k.testidPrefix})})})]}),i.jsx("button",{type:"button","data-testid":`${l}-remove-${b}`,onClick:()=>g(b),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:"✕"})]},b)),i.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(Es,{control:{...s},value:m,onChange:b=>h(b==null?"":String(b)),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 Ts({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},y=xr(t,f),g=as(e);s(g?jd(y,g):y)};return i.jsx(i.Fragment,{children:t.params.filter(c=>sk(c,n)).map(c=>i.jsx(Qw,{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 sk(e,t){const n=e.dependsOn;return!n||typeof n!="object"||typeof n.param!="string"?!0:t[n.param]===n.equals}function ak({raw:e,t,onChange:n,testIdPrefix:o,candidates:r}){const[s,a]=u.useState(!1);return i.jsxs("div",{"data-testid":`${o}-if`,style:uk,children:[i.jsxs("button",{type:"button",onClick:()=>a(l=>!l),style:pk,children:["▸ ",t("layout_editor.init_actions.if_label")]}),s?i.jsx("div",{"data-testid":`${o}-if-input`,style:{minWidth:0},children:i.jsx(Ve,{value:as(e)??"",onChange:l=>n(jd(e,l)),t,candidates:r,placeholder:t("layout_editor.init_actions.if_placeholder"),testidPrefix:`${o}-if-chip`})}):null]})}const Zc={display:"flex",alignItems:"center",gap:8,minWidth:0},oo={fontSize:11,color:"#64748b",minWidth:80},lk={display:"flex",alignItems:"center",gap:8,padding:"4px 0"},dk={fontSize:11,color:"#64748b",minWidth:80},ck={fontSize:11,color:"#92400e"},uk={display:"flex",flexDirection:"column",gap:4},pk={textAlign:"left",border:"none",background:"transparent",color:"#475569",cursor:"pointer",fontSize:11,padding:0};function fk(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 gk(e,t,n){const o=Yn(e,t);if(o.kind==="preset"){const r=t.find(s=>s.id===o.recipeId);return Wd(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:y,isLocked:g,hideAddPicker:m=!1,testIdPrefix:h="g7le-action-list"}){const v=u.useMemo(()=>wo(o),[o]),b=u.useMemo(()=>{if(r==null||r==="init")return c;const O=jl(r,n,s??null);if(O.length===0)return c;const M=c??{},B=new Set((M.bindingCandidates??[]).map(H=>H.expression)),N=O.filter(H=>!B.has(H.expression));return N.length===0?c:{...M,bindingCandidates:[...N,...M.bindingCandidates??[]]}},[r,s,c,n]),[x,k]=u.useState(null),[w,_]=u.useState(null),C=u.useCallback((O,M)=>{if(O===M||O<0||M<0||O>=e.length||M>=e.length)return;const B=e.slice(),[N]=B.splice(O,1);B.splice(M,0,N),t(B)},[e,t]),E=fs({length:e.length,onMove:C,canDrag:f,canDropAt:y}),S=u.useCallback(O=>{t(e.filter((M,B)=>B!==O))},[e,t]),T=u.useCallback((O,M)=>{const B=e.slice();B[O]=M,t(B)},[e,t]),$=u.useCallback(O=>{t([...e,O])},[e,t]),A=u.useCallback((O,M)=>{const B=Yn(O,v),N=B.kind==="preset"?v.find(L=>L.id===B.recipeId)??null:null;if(!N)return null;const H=B.kind==="preset"?B.values:{};return i.jsxs("div",{style:mk,children:[i.jsx(Ts,{raw:O,recipe:N,values:H,t:n,pools:b??{},onChange:M,testIdPrefix:`${h}-edit`,renderActionList:(L,I,P,F)=>{const G=F==="onSuccess"?"response":F==="onError"?"error":void 0;return i.jsx(Gt,{actions:L,onChange:I,t:n,recipes:o,chipContext:G,actionChipCandidates:G?s:void 0,candidatePools:G?c:b,addContext:a,showSourceBadge:p,testIdPrefix:P})}}),i.jsx(ak,{raw:O,t:n,onChange:M,testIdPrefix:`${h}-edit`,candidates:b?.bindingCandidates})]})},[v,n,b,c,s,h,o,a,p]),z=d??(o?A:void 0),D=m?null:l?l($):o?i.jsx(uw,{recipes:o,t:n,onAdd:$,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((O,M)=>{const B=Yn(O,v),N=B.kind==="preset"?B.recipeId:null,H=N?v.find(G=>G.id===N)??null:null,L=H===null,I=g?.(M)??!1,P=as(O)!==null,F=z?z(O,G=>T(M,G)):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:E.isDropTarget(M),testid:`${h}-dropline-${M}`})}),i.jsxs("li",{"data-testid":`${h}-item-${M}`,"data-drag-source":E.dragIndex===M?"true":void 0,style:{border:"1px solid #e2e8f0",borderRadius:8,padding:"8px 10px",...E.dragIndex===M?{opacity:.5}:{}},onDragOver:E.dragging&&!I?G=>{G.preventDefault();const V=G.currentTarget.getBoundingClientRect();E.onDragOverItem(M,G.clientY{G.preventDefault(),E.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:()=>E.onDragStart(M),onDragEnd:E.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:gk(O,v,n)}),p?i.jsxs("span",{"data-testid":`${h}-source-${M}`,style:hk,children:["〔",fk(o,N,n),"〕"]}):null,P?i.jsxs("span",{"data-testid":`${h}-cond-badge-${M}`,style:yk,children:["〔",n("layout_editor.init_actions.cond_badge"),"〕"]}):null,L?i.jsxs("span",{"data-testid":`${h}-advanced-${M}`,style:bk,children:["[",n("layout_editor.action.advanced"),"]"]}):null,!I&&F?i.jsxs("button",{type:"button","data-testid":`${h}-edit-${M}`,onClick:()=>_(w===M?null:M),"aria-label":n("layout_editor.init_actions.edit"),title:n("layout_editor.init_actions.edit"),style:w===M?vk:Qc,children:["✎ ",n("layout_editor.init_actions.edit")]}):null,i.jsx("button",{type:"button","data-testid":`${h}-code-${M}`,onClick:()=>k(x===M?null:M),"aria-label":n("layout_editor.action_list.view_code"),title:n("layout_editor.action_list.view_code"),style:x===M?_k:Ds,children:""}),I?null:i.jsx("button",{type:"button","data-testid":`${h}-remove-${M}`,onClick:()=>S(M),"aria-label":n("layout_editor.action_list.remove"),title:n("layout_editor.action_list.remove"),style:xk,children:"✕"})]}),H?i.jsx(kw,{action:O,recipe:H,values:B.kind==="preset"?B.values:{},t:n,showCodeButton:!1,testIdPrefix:`${h}-preview-${M}`}):null,w===M&&!I&&F?i.jsx("div",{"data-testid":`${h}-edit-body-${M}`,children:F}):null,d&&w!==M?d(O,G=>T(M,G)):null,x===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(O,null,2)}):null]})]},M)}),i.jsx("li",{"aria-hidden":"true",style:{listStyle:"none",margin:0,padding:0},children:i.jsx(Rn,{active:E.isDropTarget(e.length),testid:`${h}-dropline-end`})})]}),D?i.jsx("div",{style:{marginTop:8},children:D}):null]})}const hk={fontSize:10,color:"#64748b",whiteSpace:"nowrap"},yk={fontSize:10,color:"#7c3aed",whiteSpace:"nowrap"},bk={fontSize:10,color:"#92400e",whiteSpace:"nowrap"},mk={display:"flex",flexDirection:"column",gap:6,paddingTop:6,borderTop:"1px dashed #e2e8f0",marginTop:6},Qc={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},vk={...Qc,background:"#eff6ff",borderColor:"#bfdbfe",color:"#2563eb"},Ds={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"},_k={...Ds,background:"#0f172a",borderColor:"#0f172a",color:"#e2e8f0"},xk={...Ds,color:"#dc2626",borderColor:"#fecaca",fontFamily:"inherit"};function Rc(e){const t=e.__source;return t&&typeof t=="object"?t:null}function wk({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=>Rc(h)?.kind==="base"),[e]),f=u.useMemo(()=>e.filter(h=>Rc(h)?.kind!=="base"),[e]),y=p.length>0,g=u.useCallback(h=>{t(y?[...p,...h]:h)},[t,y,p]),m=u.useCallback(()=>{},[]);return i.jsxs("div",{className:"g7le-init-actions-form","data-testid":"g7le-init-actions-form",style:kk,children:[i.jsx("p",{style:Sk,children:o("layout_editor.page_settings.init_actions.heading")}),y?i.jsxs(i.Fragment,{children:[i.jsxs("div",{"data-testid":"g7le-init-action-group-base",style:eu,children:[i.jsx("div",{style:tu,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:Ck,children:["ⓘ ",o("layout_editor.init_actions.base_readonly_hint")]})]}),i.jsxs("div",{"data-testid":"g7le-init-action-group-self",style:eu,children:[i.jsx("div",{style:tu,children:o("layout_editor.init_actions.group_self")}),f.length===0?i.jsx("p",{style:nu,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:$k,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:nu,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 kk={display:"flex",flexDirection:"column",gap:12,minWidth:0},Sk={margin:0,fontSize:13,fontWeight:700,color:"#0f172a"},eu={border:"1px solid #e2e8f0",borderRadius:10,padding:10,display:"flex",flexDirection:"column",gap:8},tu={fontSize:12,fontWeight:700,color:"#475569"},Ck={margin:0,fontSize:11,color:"#64748b"},nu={margin:0,fontSize:12,color:"#94a3b8"},$k={margin:0,fontSize:11,color:"#64748b"};function Ek(e){return e==="spinner"?new Set(["spinner","page"]):new Set(["skeleton"])}function ou(e,t,n){return typeof e!="string"?n:e.startsWith("$t:")?t(e.slice(3)):e}function ru({candidates:e,value:t,onSelect:n,styleKind:o,t:r,testIdPrefix:s="g7le-loading-component-picker"}){const a=yo(),l=()=>{const d=a.open({ariaLabel:r("layout_editor.overlay.loading_picker.select"),width:520,maxHeightRatio:.7,content:i.jsx(Ik,{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:Ak,children:[i.jsx("span",{"data-testid":`${s}-current`,style:Tk,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:Dk,children:["🔍 ",r("layout_editor.overlay.loading_picker.select")]})]})})}function Ik({candidates:e,value:t,styleKind:n,t:o,testIdPrefix:r,onPick:s,onClose:a}){const[l,d]=u.useState(""),c=Ek(n),p=u.useMemo(()=>{const f=l.trim().toLowerCase();return e.filter(y=>c.has(y.role)).filter(y=>f?ou(y.label,o,y.name).toLowerCase().includes(f)||y.name.toLowerCase().includes(f):!0)},[e,n,l,o]);return i.jsxs("div",{"data-testid":`${r}-modal`,style:Nk,children:[i.jsxs("div",{style:zk,children:[i.jsxs("span",{style:Mk,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:Lk,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:Pk,autoFocus:!0}),p.length===0?i.jsx("p",{"data-testid":`${r}-empty`,style:Kk,children:o("layout_editor.overlay.loading_picker.empty")}):i.jsx("ul",{style:Ok,children:p.map(f=>i.jsx("li",{children:i.jsxs("button",{type:"button","data-testid":`${r}-item-${f.name}`,onClick:()=>s(f.name),style:{...Bk,...t===f.name?Wk:{}},children:[i.jsx("span",{style:jk,children:ou(f.label,o,f.name)}),i.jsx("code",{style:Hk,children:f.name}),i.jsx("span",{style:Fk,children:f.role})]})},f.name))})]})}const Ak={display:"flex",alignItems:"center",gap:6,minWidth:0},Tk={flex:1,minWidth:0,fontSize:12,color:"#0f172a",fontFamily:"monospace"},Dk={padding:"4px 10px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},Nk={display:"flex",flexDirection:"column",minHeight:0,padding:16,boxSizing:"border-box",fontFamily:"system-ui, -apple-system, sans-serif"},zk={display:"flex",alignItems:"center",gap:8,paddingBottom:8,borderBottom:"1px solid #e2e8f0",marginBottom:10},Mk={flex:1,fontSize:14,fontWeight:700,color:"#0f172a",minWidth:0},Lk={border:"none",background:"transparent",color:"#64748b",cursor:"pointer",fontSize:15,lineHeight:1,padding:4},Pk={width:"100%",padding:"6px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,marginBottom:8,boxSizing:"border-box"},Ok={listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:2,overflowY:"auto",minHeight:0},Bk={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},Wk={border:"1px solid #3b82f6",background:"#eff6ff"},jk={flex:1,minWidth:0,color:"#0f172a"},Hk={fontSize:10,color:"#94a3b8",fontFamily:"monospace"},Fk={fontSize:10,color:"#64748b",background:"#f1f5f9",borderRadius:4,padding:"0 4px"},Kk={margin:0,fontSize:12,color:"#94a3b8",padding:"8px 4px"};function iu(e){return e===!0?{enabled:!0}:e===!1||e===void 0?{}:e}const Vk=["opaque","blur","fade","skeleton","spinner"];function Uk({value:e,patch:t,t:n,baseValue:o,ownValue:r,loadingComponents:s=[],progressiveDataSources:a=[],bindingCandidates:l}){const d=iu(e),c=d.enabled??!1,p=!!o&&Object.keys(o).length>0,f=Tn("component-target-picker"),[y,g]=u.useState((d.wait_for??[]).length>0),m=u.useCallback(w=>{const _={...iu(e)};w(_),t(_)},[e,t]),h=r&&typeof r=="object"?r:e&&typeof e=="object"?e:{},v=u.useCallback(w=>p&&o!==void 0&&w in o&&!(w in h),[p,o,h]),b=u.useCallback(w=>{o&&m(_=>{_[w]=o[w]})},[o,m]),x=u.useCallback(w=>m(_=>{_.enabled=w}),[m]),k=d.target!==void 0?"region":"full";return i.jsxs("div",{className:"g7le-overlay-form","data-testid":"g7le-overlay-form",style:qk,children:[p?i.jsxs("p",{"data-testid":"g7le-overlay-inherit-banner",style:Gk,children:["ⓘ ",n("layout_editor.overlay.inherit_banner")]}):null,i.jsxs("div",{style:Br,children:[i.jsx(Ns,{label:n("layout_editor.overlay.enabled_label"),inherited:v("enabled"),hasInheritance:p,onOverride:()=>b("enabled"),testidKey:"enabled",t:n}),i.jsx(Nr,{disabled:v("enabled"),children:i.jsx(Dr,{checked:c,onChange:x,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:Wr,children:["ⓘ ",n("layout_editor.overlay.enabled_hint")]})]}),i.jsx(Nr,{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:Br,children:[i.jsx(Ns,{label:n("layout_editor.overlay.scope_label"),inherited:v("target"),hasInheritance:p,onOverride:()=>b("target"),testidKey:"target",t:n}),i.jsxs("div",{"data-testid":"g7le-overlay-scope",style:zs,children:[i.jsx(Or,{active:k==="full",onClick:()=>m(w=>{delete w.target,delete w.fallback_target}),testid:"g7le-overlay-scope-full",children:n("layout_editor.overlay.scope_full")}),i.jsx(Or,{active:k==="region",onClick:()=>m(w=>{w.target=w.target??""}),testid:"g7le-overlay-scope-region",children:n("layout_editor.overlay.scope_region")})]}),i.jsx(Nr,{disabled:k!=="region",testid:"g7le-overlay-region-box",style:Zk,children:i.jsxs(i.Fragment,{children:[i.jsx(zn,{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:w=>m(_=>{_.target=typeof w=="string"?w:""}),t:n}):i.jsx("input",{type:"text","data-testid":"g7le-overlay-target-input",value:d.target??"",onChange:w=>m(_=>{_.target=w.target.value}),style:e1})})}),i.jsx(zn,{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:w=>m(_=>{const C=typeof w=="string"?w:"";C===""?delete _.fallback_target:_.fallback_target=C}),t:n}):null})}),i.jsxs("p",{style:Wr,children:["ⓘ ",n("layout_editor.overlay.fallback_hint")]})]})})]}),i.jsxs("div",{style:Br,children:[i.jsx(Ns,{label:n("layout_editor.overlay.style_label"),inherited:v("style"),hasInheritance:p,onOverride:()=>b("style"),testidKey:"style",t:n}),i.jsx("div",{"data-testid":"g7le-overlay-style",style:zs,children:Vk.map(w=>i.jsx(Or,{active:(d.style??"opaque")===w,onClick:()=>m(_=>{_.style=w}),testid:`g7le-overlay-style-${w}`,children:n(`layout_editor.overlay.style_${w}`)},w))}),d.style==="skeleton"?i.jsxs("div",{style:su,children:[i.jsx(zn,{label:n("layout_editor.overlay.skeleton_component"),children:i.jsx(ru,{candidates:s,value:d.skeleton?.component,styleKind:"skeleton",onSelect:w=>m(_=>{_.skeleton={..._.skeleton,component:w}}),t:n,testIdPrefix:"g7le-overlay-skeleton-component"})}),i.jsx(zn,{label:n("layout_editor.overlay.skeleton_animation"),children:i.jsx("div",{"data-testid":"g7le-overlay-skeleton-anim",style:zs,children:["wave","pulse","none"].map(w=>i.jsx(Or,{active:(d.skeleton?.animation??"wave")===w,onClick:()=>m(_=>{_.skeleton={..._.skeleton,animation:w}}),testid:`g7le-overlay-skeleton-anim-${w}`,children:n(`layout_editor.overlay.anim_${w}`)},w))})}),i.jsx(zn,{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:w=>m(_=>{const C=parseInt(w.target.value,10);_.skeleton={..._.skeleton,iteration_count:Number.isNaN(C)?void 0:C}}),style:t1})})]}):null,d.style==="spinner"?i.jsxs("div",{style:su,children:[i.jsx(zn,{label:n("layout_editor.overlay.spinner_component"),children:i.jsx(ru,{candidates:s,value:d.spinner?.component,styleKind:"spinner",onSelect:w=>m(_=>{_.spinner={..._.spinner,component:w}}),t:n,testIdPrefix:"g7le-overlay-spinner-component"})}),i.jsx(zn,{label:n("layout_editor.overlay.spinner_text"),children:i.jsx("div",{"data-testid":"g7le-overlay-spinner-text",style:{minWidth:0},children:i.jsx(vt,{value:d.spinner?.text??"",onChange:w=>m(_=>{_.spinner={..._.spinner,text:w===void 0||w===""?void 0:w}}),t:n,candidates:l,enableExpressionTree:!0,expressionTreeCollapsible:!0,testidPrefix:"g7le-overlay-spinner-text-field"})})})]}):null]}),i.jsxs("div",{style:Br,children:[i.jsxs("button",{type:"button","data-testid":"g7le-overlay-waitfor-toggle","aria-expanded":y,onClick:()=>g(w=>!w),style:r1,children:[y?"▾":"▸"," ",n("layout_editor.overlay.waitfor_label")]}),y?i.jsxs("div",{"data-testid":"g7le-overlay-waitfor-body",style:i1,children:[i.jsxs("p",{"data-testid":"g7le-overlay-waitfor-hint",style:Wr,children:["ⓘ ",n("layout_editor.overlay.waitfor_hint")]}),a.length===0?i.jsx("p",{"data-testid":"g7le-overlay-waitfor-empty",style:Wr,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(w=>{const _=(d.wait_for??[]).includes(w.id);return i.jsxs("label",{"data-testid":`g7le-overlay-waitfor-${w.id}`,style:n1(_),children:[i.jsx("input",{type:"checkbox",checked:_,onChange:()=>m(C=>{const E=new Set(C.wait_for??[]);E.has(w.id)?E.delete(w.id):E.add(w.id);const S=Array.from(E);S.length===0?delete C.wait_for:C.wait_for=S})}),i.jsx(Dc,{option:w,testIdPrefix:`g7le-overlay-waitfor-${w.id}`})]},w.id)})})]}):null]}),p?i.jsxs("button",{type:"button","data-testid":"g7le-overlay-reset-inherit",onClick:()=>t(void 0),style:o1,children:["⟲ ",n("layout_editor.overlay.reset_inherit")]}):null]})})]})}function Or({active:e,onClick:t,children:n,testid:o}){return i.jsx("button",{type:"button","data-testid":o,"aria-pressed":e,onClick:t,style:{...Xk,...e?Jk:{}},children:n})}function Ns({label:e,inherited:t,hasInheritance:n,onOverride:o,testidKey:r,t:s}){return i.jsxs("div",{style:s1,children:[i.jsx("label",{style:Yk,children:e}),n?t?i.jsxs(i.Fragment,{children:[i.jsxs("span",{"data-testid":`g7le-overlay-inherited-${r}`,style:a1,children:["〔",s("layout_editor.overlay.inherited_badge"),"〕"]}),i.jsx("button",{type:"button","data-testid":`g7le-overlay-override-${r}`,onClick:o,style:d1,children:s("layout_editor.overlay.override_field")})]}):i.jsxs("span",{"data-testid":`g7le-overlay-overridden-${r}`,style:l1,children:["〔",s("layout_editor.overlay.overridden_badge"),"〕"]}):null]})}function zn({label:e,children:t}){return i.jsxs("div",{style:Qk,children:[i.jsx("span",{style:Rk,children:e}),i.jsx("div",{style:{flex:1,minWidth:0},children:t})]})}const qk={display:"flex",flexDirection:"column",gap:16,minWidth:0},Gk={margin:0,fontSize:12,color:"#1d4ed8",background:"#eff6ff",padding:"8px 10px",borderRadius:6},Br={display:"flex",flexDirection:"column",gap:6,minWidth:0},Yk={fontSize:13,fontWeight:600,color:"#0f172a"},Wr={margin:0,fontSize:11,color:"#94a3b8"},zs={display:"flex",gap:4,flexWrap:"wrap"},Xk={padding:"4px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},Jk={border:"1px solid #3b82f6",background:"#eff6ff",color:"#1d4ed8"},Zk={display:"flex",flexDirection:"column",gap:8,padding:8,border:"1px dashed #e2e8f0",borderRadius:8},su={display:"flex",flexDirection:"column",gap:8,padding:8,border:"1px dashed #e2e8f0",borderRadius:8},Qk={display:"flex",alignItems:"center",gap:8,minWidth:0},Rk={fontSize:11,color:"#64748b",minWidth:90},e1={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},t1={width:80,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},n1=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"}),o1={alignSelf:"flex-start",padding:"6px 12px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},r1={alignSelf:"flex-start",padding:"4px 0",fontSize:13,fontWeight:600,color:"#0f172a",background:"transparent",border:"none",cursor:"pointer"},i1={display:"flex",flexDirection:"column",gap:6,paddingLeft:14,minWidth:0},s1={display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",minWidth:0},a1={fontSize:11,color:"#64748b",background:"#f1f5f9",borderRadius:4,padding:"1px 6px"},l1={fontSize:11,color:"#0369a1",background:"#e0f2fe",borderRadius:4,padding:"1px 6px"},d1={padding:"2px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},c1="g7le:computed-effect-preview",u1={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 p1(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 au({expr:e,computedKey:t,sampleContext:n,t:o,isEffect:r=!1,testIdPrefix:s="g7le-computed-preview"}){const a=Id(e,n),l=()=>{typeof window>"u"||!t||window.dispatchEvent(new CustomEvent(c1,{detail:{key:t}}))};return a.ok?i.jsxs("div",{className:s,"data-testid":s,style:f1,children:[i.jsx("span",{style:g1,children:o("layout_editor.computed.preview_label")}),i.jsx("span",{"data-testid":`${s}-value`,style:h1,children:p1(a.value,a.type,o)}),i.jsxs("span",{"data-testid":`${s}-type`,style:y1,children:["(",o(u1[a.type]),")"]}),r&&a.type==="boolean"?i.jsxs("button",{type:"button","data-testid":`${s}-effect`,onClick:l,style:b1,children:["▷ ",o("layout_editor.computed.effect_preview")]}):null]}):i.jsxs("div",{"data-testid":`${s}-error`,style:m1,children:["⚠ ",o("layout_editor.computed.preview_error")]})}const f1={display:"flex",alignItems:"center",flexWrap:"wrap",gap:6,minWidth:0},g1={fontSize:11,color:"#94a3b8"},h1={fontSize:12,color:"#0f172a",fontFamily:"monospace",wordBreak:"break-all"},y1={fontSize:10,color:"#64748b"},b1={padding:"2px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},m1={fontSize:12,color:"#b45309"},v1=[{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"}],_1=["=","!=",">","<",">=","<=","includes"],x1=new Set(["count","sum","filter"]);function lu({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(),b={...v[g]};m(b),v[g]=b,h.conditions=v}),y=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:w1,children:[i.jsx(Ms,{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(Ms,{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:v1.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(Ve,{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(Ve,{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(Ve,{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(Ve,{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(Ve,{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(Ve,{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,x1.has(e.op)?i.jsxs("div",{style:$1,children:[l.map((g,m)=>i.jsxs("div",{"data-testid":`g7le-computed-custom-cond-${m}`,style:E1,children:[i.jsx("div",{"data-testid":`g7le-computed-custom-cond-field-${m}`,style:{flex:1,minWidth:0},children:i.jsx(Ve,{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:I1,children:_1.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(Ve,{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:()=>y(m),style:A1,children:"✕"})]},m)),i.jsxs("button",{type:"button","data-testid":"g7le-computed-custom-cond-add",onClick:p,style:T1,children:["+ ",n("layout_editor.computed.cond_add")]})]}):null]}),i.jsxs(Ms,{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?C1:{}}}),c?i.jsxs("p",{"data-testid":"g7le-computed-custom-key-dup",style:D1,children:["⚠ ",n("layout_editor.computed.key_duplicate")]}):null]})]})}function Ms({label:e,children:t}){return i.jsxs("div",{style:k1,children:[i.jsx("div",{style:S1,children:e}),i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0},children:t})]})}function Ls(e){return Vm(e)}const w1={display:"flex",flexDirection:"column",gap:12,padding:10,border:"1px solid #cbd5e1",borderRadius:8,background:"#fff"},k1={display:"flex",flexDirection:"column",gap:4,minWidth:0},S1={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"},C1={border:"1px solid #ef4444"},$1={display:"flex",flexDirection:"column",gap:6,marginTop:4},E1={display:"flex",gap:4,alignItems:"center",minWidth:0},I1={padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},A1={border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12},T1={alignSelf:"flex-start",padding:"2px 8px",fontSize:11,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},D1={margin:0,fontSize:11,color:"#b45309"};function Ps(e,t,n){return typeof e!="string"?n:e.startsWith("$t:")?t(e.slice(3)):e}function N1(e){if(e&&typeof e=="object"){const t=e.__source;if(t&&typeof t=="object")return t}return null}function z1({computed:e,onChange:t,recipes:n,t:o,sampleContext:r,dataSourceCandidates:s,bindingCandidates:a,computedSource:l={},effectKeys:d=[],onRevert:c}){const p=u.useMemo(()=>xd(n),[n]),[f,y]=u.useState(!1),[g,m]=u.useState(null),h=Object.keys(e),v=u.useCallback((_,C)=>{t({...e,[_]:C})},[e,t]),b=u.useCallback(_=>{const C={...e};delete C[_],t(C)},[e,t]),x=u.useCallback((_,C,E)=>{const S={...e};_&&_!==C&&delete S[_],S[C]=E,t(S)},[e,t]),k=u.useCallback(_=>{const C=kd(_,{});let E=_.id,S=1;for(;E in e;)E=`${_.id}${++S}`;t({...e,[E]:C}),y(!1)},[e,t]),w=u.useCallback(()=>{!g||!g.key||(t({...e,[g.key]:Ls(g)}),m(null),y(!1))},[g,e,t]);return i.jsxs("div",{className:"g7le-computed-form","data-testid":"g7le-computed-form",style:O1,children:[i.jsx("p",{style:B1,children:o("layout_editor.page_settings.computed.heading")}),h.length>0?h.map(_=>i.jsx(M1,{computedKey:_,expr:e[_],recipes:p,rawRecipes:n,t:o,sampleContext:r,dataSourceCandidates:s,bindingCandidates:a,source:l[_],isEffect:d.includes(_),existingKeys:h,onPatchExpr:C=>v(_,C),onRename:(C,E)=>x(_,C,E),onRemove:()=>b(_),onRevert:c?()=>c(_):void 0},_)):i.jsx("p",{"data-testid":"g7le-computed-empty",style:aS,children:o("layout_editor.computed.empty")}),i.jsxs("div",{style:{minWidth:0},children:[i.jsxs("button",{type:"button","data-testid":"g7le-computed-add",onClick:()=>y(_=>!_),style:R1,children:["+ ",o("layout_editor.computed.add")," ▾"]}),f?i.jsxs("div",{"data-testid":"g7le-computed-add-list",style:eS,children:[["common","more"].map(_=>{const C=p.filter(E=>(E.group??"more")===_);return C.length===0?null:i.jsxs("div",{children:[i.jsxs("div",{style:tS,children:["━━ ",o(`layout_editor.computed.group_${_}`)," ━━"]}),C.map(E=>{const S=N1(n?.[E.id]);return i.jsxs("button",{type:"button","data-testid":`g7le-computed-preset-${E.id}`,onClick:()=>k(E),style:nS,children:[i.jsx("span",{style:oS,children:Ps(E.label,o,E.id)}),S&&S.kind!=="core"?i.jsxs("span",{"data-testid":`g7le-computed-preset-source-${E.id}`,style:rS,children:["〔",S.id??S.kind,"〕"]}):null]},E.id)})]},_)}),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:iS,children:["⚙ ",o("layout_editor.computed.custom_open")," ▾"]}),g?i.jsxs("div",{style:{marginTop:6},children:[i.jsx(lu,{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(au,{expr:Ls(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:w,style:sS,children:o("layout_editor.computed.custom_add")})]}):null]})]}):null]})]})}function M1({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:y,onRemove:g,onRevert:m}){const[h,v]=u.useState(!1),[b,x]=u.useState(!1),k=u.useMemo(()=>Ed(t,n),[t,n]),w=d==="base",_=d==="route-override",C=k.kind==="advanced",E=k.kind==="preset"?n.find($=>$.id===k.recipeId)??null:null,S=E?Ps(E.label,r,e):e,T=($,A)=>{if(k.kind!=="preset"||!E)return;const z={...k.params,[$]:A};f(kd(E,z))};return i.jsxs("div",{"data-testid":`g7le-computed-item-${e}`,style:W1,children:[i.jsxs("div",{style:j1,children:[i.jsx("span",{style:H1,children:S}),i.jsx("code",{style:F1,children:e}),w?i.jsxs("span",{"data-testid":`g7le-computed-source-${e}`,style:K1,children:["〔",r("layout_editor.computed.source_base"),"〕"]}):null,_?i.jsxs("span",{"data-testid":`g7le-computed-overridden-${e}`,style:V1,children:["〔",r("layout_editor.computed.source_overridden"),"〕"]}):null,C?i.jsxs("span",{"data-testid":"g7le-computed-advanced",style:U1,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:()=>x($=>!$),style:Os,"aria-label":r("layout_editor.value_tree.show_source"),title:r("layout_editor.value_tree.show_source"),children:""}),C?null:i.jsx("button",{type:"button","data-testid":`g7le-computed-edit-${e}`,onClick:()=>v($=>!$),style:Os,children:r("layout_editor.init_actions.edit")}),i.jsx("button",{type:"button","data-testid":`g7le-computed-remove-${e}`,onClick:g,style:Os,"aria-label":r("layout_editor.init_actions.remove"),children:"✕"})]}),b?i.jsx("pre",{"data-testid":`g7le-computed-code-block-${e}`,style:lS,children:t}):null,i.jsx("div",{"data-testid":`g7le-computed-preview-${e}`,children:i.jsx(au,{expr:t,computedKey:e,sampleContext:s,t:r,isEffect:c,testIdPrefix:`g7le-computed-preview-${e}-eval`})}),_&&m?i.jsxs("div",{style:q1,children:[i.jsxs("span",{style:G1,children:["ⓘ ",r("layout_editor.computed.overridden_hint")]}),i.jsx("button",{type:"button","data-testid":`g7le-computed-revert-${e}`,onClick:m,style:Y1,children:r("layout_editor.computed.revert")})]}):null,h&&!C?i.jsxs("div",{style:X1,children:[w?i.jsxs("p",{"data-testid":`g7le-computed-override-notice-${e}`,style:J1,children:["⚠ ",r("layout_editor.computed.override_notice")]}):null,k.kind==="preset"&&E?i.jsx(i.Fragment,{children:E.params.map($=>i.jsx(P1,{param:$,value:k.params[$.key]??"",t:r,dataSourceCandidates:a,bindingCandidates:l,onChange:A=>T($.key,A)},$.key))}):k.kind==="custom"?i.jsx(lu,{model:{...k.model,key:e},onChange:$=>y($.key,Ls($)),t:r,dataSourceCandidates:a,bindingCandidates:l,existingKeys:p.filter($=>$!==e)}):null]}):null]})}const L1=new Set(["datasource-picker","binding-picker","select","toggle","state-key-picker","page-picker"]);function P1({param:e,value:t,t:n,dataSourceCandidates:o,bindingCandidates:r,onChange:s}){const a=Ps(e.label,n,e.key),l=e.widget??"",c=L1.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:Z1,children:[i.jsx("span",{style:Q1,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(Ve,{value:t,onChange:f=>s(f),t:n,candidates:r,testidPrefix:`g7le-computed-param-${e.key}-chip`})})]})}const O1={display:"flex",flexDirection:"column",gap:12,minWidth:0},B1={margin:0,fontSize:13,fontWeight:700,color:"#0f172a"},W1={border:"1px solid #e2e8f0",borderRadius:8,padding:"8px 10px",display:"flex",flexDirection:"column",gap:6,background:"#f8fafc"},j1={display:"flex",alignItems:"center",gap:6},H1={fontSize:13,fontWeight:600,color:"#0f172a"},F1={fontSize:10,color:"#64748b",fontFamily:"monospace"},K1={fontSize:10,color:"#0891b2",whiteSpace:"nowrap"},V1={fontSize:10,color:"#7c3aed",whiteSpace:"nowrap"},U1={fontSize:10,color:"#92400e",whiteSpace:"nowrap"},q1={display:"flex",alignItems:"center",gap:8,marginTop:4,minWidth:0},G1={fontSize:11,color:"#7c3aed",flex:1,minWidth:0},Y1={border:"1px solid #c4b5fd",borderRadius:6,background:"#f5f3ff",color:"#6d28d9",cursor:"pointer",fontSize:11,padding:"2px 8px",whiteSpace:"nowrap"},Os={border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",fontSize:11,padding:"2px 6px"},X1={display:"flex",flexDirection:"column",gap:6,paddingTop:6,borderTop:"1px dashed #e2e8f0"},J1={margin:0,fontSize:11,color:"#b45309",background:"#fef3c7",padding:"6px 8px",borderRadius:6},Z1={display:"flex",alignItems:"center",gap:8,minWidth:0},Q1={fontSize:11,color:"#64748b",minWidth:90},R1={padding:"6px 12px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},eS={marginTop:6,border:"1px solid #cbd5e1",borderRadius:8,background:"#fff",padding:8,maxHeight:380,overflowY:"auto"},tS={fontSize:11,fontWeight:700,color:"#94a3b8",padding:"6px 4px 2px"},nS={display:"flex",alignItems:"center",gap:6,width:"100%",textAlign:"left",padding:"6px 8px",fontSize:12,border:"none",background:"transparent",cursor:"pointer",borderRadius:6},oS={flex:1,minWidth:0,color:"#0f172a"},rS={fontSize:10,color:"#64748b",whiteSpace:"nowrap"},iS={padding:"6px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},sS={marginTop:6,padding:"6px 12px",fontSize:12,border:"1px solid #3b82f6",borderRadius:6,background:"#3b82f6",color:"#fff",cursor:"pointer"},aS={margin:0,fontSize:12,color:"#94a3b8"},lS={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 dS(e,t){return t==="any"?!0:e===null||typeof e!="object"?!1:t==="object"?!Array.isArray(e):!0}function Bs({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:y,validate:g}){const[m,h]=u.useState(()=>jr(e)),[v,b]=u.useState(null),x=u.useRef(!1),k=u.useRef(e);u.useEffect(()=>{if(!x.current&&!Object.is(e,k.current)){if(jr(e)===jr(k.current)){k.current=e;return}h(jr(e)),b(null),k.current=e,n?.(!0)}},[e]);const w=_=>{if(x.current=!0,h(_),_.trim()===""){b(null),k.current=s,n?.(!0),t(s);return}let C;try{C=JSON.parse(_)}catch{b(o(p??"layout_editor.json_block.invalid")),n?.(!1);return}if(!dS(C,r)){b(o(c??"layout_editor.json_block.invalid")),n?.(!1);return}const E=g?.(C)??null;if(E){b(E),n?.(!1);return}b(null),k.current=C,n?.(!0),t(C)};return i.jsxs("div",{className:"g7le-json-block",style:cS,children:[i.jsx("textarea",{id:y,"data-testid":d,style:{...uS,minHeight:l},value:m,spellCheck:!1,"aria-label":f,"aria-invalid":v?!0:void 0,placeholder:a,onChange:_=>w(_.target.value),onBlur:()=>{x.current=!1}}),v?i.jsx("div",{"data-testid":`${d}-error`,style:pS,children:v}):null]})}function jr(e){if(e===void 0)return"";try{return JSON.stringify(e,null,2)??""}catch{return""}}const cS={display:"flex",flexDirection:"column",gap:4,minWidth:0},uS={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"},pS={fontSize:11,color:"#dc2626"},fS=[{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"}],Ws={local:"initLocal",global:"initGlobal",isolated:"initIsolated"};function gS({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,y=e?.state&&typeof e.state=="object"?e.state:void 0;if(!(!f&&!y))return{...y??{},...f??{}}},[t,e]),{initLocal:a,migrated:l}=u.useMemo(()=>Pw({initLocal:e?.initLocal,state:s}),[e,s]),d=f=>{if(f==="local")return a;const y=e?.[Ws[f]];return y&&typeof y=="object"?y:{}},c=f=>{if(f==="local"){const y=t?.initLocal??{},g=s?Object.keys(s):[];return Array.from(new Set([...Object.keys(y),...g]))}return Object.keys(t?.[Ws[f]]??{})},p=u.useCallback((f,y)=>{const g=Ws[f];f==="local"&&l&&n("state",void 0),n(g,Object.keys(y).length===0?void 0:y)},[n,l]);return i.jsxs("div",{className:"g7le-initstate-form","data-testid":"g7le-initstate-form",style:yS,children:[i.jsx("p",{style:bS,children:o("layout_editor.page_settings.initstate.heading")}),l?i.jsxs("p",{"data-testid":"g7le-initstate-legacy-state",style:mS,children:["ⓘ ",o("layout_editor.initstate.legacy_state")]}):null,i.jsx(js,{scope:"local",label:o("layout_editor.initstate.section_local"),value:d("local"),ownKeys:c("local"),patchSection:p,t:o}),i.jsx(js,{scope:"global",label:o("layout_editor.initstate.section_global"),value:d("global"),ownKeys:c("global"),patchSection:p,t:o}),i.jsx(js,{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:PS,children:["ⓘ ",o("layout_editor.initstate.isolated_dynamic_hint")]})]})}function js({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"),[y,g]=u.useState(null),[m,h]=u.useState(!1),v=Object.keys(o),b=v,x=(_,C)=>{s(e,{...o,[_]:C})},k=_=>{const C={...o};delete C[_],s(e,C)},w=()=>{const _=d.trim();if(!_){g(a("layout_editor.initstate.name_required"));return}if(!Is(_)){g(a("layout_editor.initstate.name_invalid"));return}if(_ in o){g(a("layout_editor.initstate.name_duplicate"));return}const C={string:"",number:0,boolean:!1,null:null,list:[],object:{}};s(e,{...o,[_]:C[p]}),c(""),g(null)};return i.jsxs("div",{"data-testid":`g7le-initstate-section-${e}`,style:vS,children:[i.jsxs("div",{style:_S,children:[i.jsx("div",{style:xS,children:t}),i.jsx("button",{type:"button","data-testid":`g7le-initstate-${e}-mode-toggle`,onClick:()=>h(_=>!_),style:kS,children:a(m?"layout_editor.json_block.mode_block":"layout_editor.json_block.mode_code")})]}),n?i.jsxs("p",{style:wS,children:["ⓘ ",n]}):null,m?i.jsx(Bs,{value:o,shape:"object",emptyValue:{},onChange:_=>s(e,_??{}),t:a,testidPrefix:`g7le-initstate-${e}-code`,placeholder:`{ +var dM=Object.defineProperty;var cM=(dn,i,u)=>i in dn?dM(dn,i,{enumerable:!0,configurable:!0,writable:!0,value:u}):dn[i]=u;var Ti=(dn,i,u)=>cM(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 Di=Lt();Di.TranslationProvider;const tt=Di.useTranslation;Di.TranslationReactContext;function rt(){return typeof window>"u"?null:window.__g7Devtools??null}function Sl(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 Vh(){const e=rt();if(e?.clearEditorStateData)try{e.clearEditorStateData()}catch{}}function Uh(e){const t=rt();if(t?.trackEditorSampleMatch)try{t.trackEditorSampleMatch(e)}catch{}}function qh(){const e=rt();if(e?.clearEditorSampleData)try{e.clearEditorSampleData()}catch{}}function Gh(e){const t=rt();if(t?.trackEditorHistoryEntry)try{t.trackEditorHistoryEntry(e)}catch{}}function Yh(){const e=rt();if(e?.clearEditorHistoryData)try{e.clearEditorHistoryData()}catch{}}function Cl(e){const t=rt();if(t?.trackEditorSelection)try{t.trackEditorSelection(e)}catch{}}function Xh(){const e=rt();if(e?.clearEditorSelectionData)try{e.clearEditorSelectionData()}catch{}}function sr(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 Jh(){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 Zh(){const e=rt();if(e?.clearEditorDocumentData)try{e.clearEditorDocumentData()}catch{}}function Qh(e){const t=rt();if(t?.trackEditorSpecMerge)try{t.trackEditorSpecMerge(e)}catch{}}function Rh(){const e=rt();if(e?.clearEditorSpecMergeData)try{e.clearEditorSpecMergeData()}catch{}}function Ni(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 ey(){const e=rt();if(e?.clearEditorI18nData)try{e.clearEditorI18nData()}catch{}}function $l(e){const t=rt();if(t?.trackPageState)try{t.trackPageState(e)}catch{}}function ty(){const e=rt();if(e?.clearPageStateData)try{e.clearPageStateData()}catch{}}const El="g7le.routeTree.collapsed";function ny(){if(typeof window>"u")return!1;try{return window.localStorage?.getItem(El)==="1"}catch{return!1}}function oy(e){if(!(typeof window>"u"))try{window.localStorage?.setItem(El,e?"1":"0")}catch{}}function ry(e,t){return{templateIdentifier:e,routeTree:[],routesError:null,selectedRoute:null,isRouteTreeCollapsed:ny(),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 iy(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 sy(e,t){const n=iy(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 Il=u.createContext(null);function ay(e,t){const n=sy(e,t);return Sl(n,t.type),n}function ly({templateIdentifier:e,initialLocale:t,children:n}){const[o,r]=u.useReducer(ay,void 0,()=>{const a=ry(e,t);return Sl(a,void 0),a});u.useEffect(()=>{oy(o.isRouteTreeCollapsed)},[o.isRouteTreeCollapsed]);const s=u.useMemo(()=>({state:o,dispatch:r}),[o]);return u.createElement(Il.Provider,{value:s},n)}function Je(){const e=u.useContext(Il);if(!e)throw new Error("useLayoutEditor must be used within LayoutEditorProvider");return e}const Al=u.createContext(null);function dy({value:e,children:t}){return u.createElement(Al.Provider,{value:e},t)}function Ft(){return u.useContext(Al)}const zi=u.createContext(null);let cy=1;function uy({children:e,t}){const[n,o]=u.useState([]),r=u.useRef([]),[s,a]=u.useState({}),l=u.useCallback(b=>{const x=b.id??`editor-modal-${cy++}`,k={id:x,content:b.content,ariaLabel:b.ariaLabel??"",closeOnBackdrop:b.closeOnBackdrop??!0,closeOnEscape:b.closeOnEscape??!0,width:b.width??"auto",height:b.height??"auto",maxHeightRatio:b.maxHeightRatio??.85,draggable:b.draggable??!1,avoidRect:b.avoidRect,onClose:b.onClose};return o(w=>{const C=[...w.filter(E=>E.id!==x),k];return r.current=C,C}),x},[]),d=u.useCallback(b=>{o(x=>{const k=x.find(_=>_.id===b),w=x.filter(_=>_.id!==b);return r.current=w,k?.onClose&&queueMicrotask(()=>k.onClose?.()),w})},[]),c=u.useCallback(()=>{const b=r.current[r.current.length-1];b&&d(b.id)},[d]),p=u.useCallback(()=>{o(b=>{for(let x=b.length-1;x>=0;x--){const k=b[x];k?.onClose&&queueMicrotask(()=>k.onClose?.())}return r.current=[],[]})},[]),f=u.useCallback((b,x)=>{a(k=>{const w=r.current.find(C=>C.id===b),_=x??w?.ariaLabel??"";return{...k,[b]:_}})},[]),y=u.useCallback(b=>{a(x=>{if(!(b in x))return x;const k={...x};return delete k[b],k})},[]),g=u.useCallback(b=>{y(b),d(b)},[y,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:y,minimizedStack:h}),[l,g,c,m,n,f,y,h]);return u.createElement(zi.Provider,{value:v},e,u.createElement(fy,{minimized:s,onRestore:y,t,key:"__min_bar"}))}function yo(){const e=u.useContext(zi);if(!e)throw new Error("useEditorModal must be used within EditorModalProvider");return e}function py(){const e=u.useContext(zi);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(hy,{entry:s,depth:a,hidden:r.has(s.id),onClose:()=>n(s.id)},s.id))})}function fy({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 gy(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 Tl="clamp(16px, 6vh, 56px)";function hy({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 - (${Tl}) * 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 b=v.getBoundingClientRect(),x=gy(e.avoidRect,b.width,b.height);x&&d(x)},[e.id,e.draggable]);const f=u.useCallback(v=>{if(!e.draggable)return;const b=v.target;if(!b.closest("[data-modal-drag-handle]")||b.closest("button, a, input, textarea, select"))return;const k=c.current,w=k?.getBoundingClientRect(),_=l?.left??w?.left??0,C=l?.top??w?.top??0;p.current={startX:v.clientX,startY:v.clientY,baseLeft:_,baseTop:C};const E=T=>{const $=p.current;if(!$)return;const A=window.innerWidth,z=window.innerHeight,D=k?.offsetWidth??0,O=k?.offsetHeight??0;let M=$.baseLeft+(T.clientX-$.startX),B=$.baseTop+(T.clientY-$.startY);M=Math.min(Math.max(0,M),Math.max(0,A-D)),B=Math.min(Math.max(0,B),Math.max(0,z-O)),d({left:M,top:B})},S=()=>{p.current=null,window.removeEventListener("pointermove",E),window.removeEventListener("pointerup",S)};window.addEventListener("pointermove",E),window.addEventListener("pointerup",S)},[e.draggable,l]),y=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:Tl,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:y,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 wt({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 yy({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=x=>{p.current&&!p.current.contains(x.target)&&l(!1)},b=x=>{x.key==="Escape"&&l(!1)};return document.addEventListener("mousedown",v),document.addEventListener("keydown",b),()=>{document.removeEventListener("mousedown",v),document.removeEventListener("keydown",b)}},[a]);const f=o??[],y=f.some(v=>v.identifier!==e),g=!!r&&y,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 b=v.identifier===e;return i.jsxs("button",{type:"button",role:"option","aria-selected":b,"aria-current":b?"true":void 0,className:"g7le-toolbar__template-menu-item","data-testid":"g7le-toolbar-template-menu-item","data-identifier":v.identifier,"data-current":b?"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:b?"#eff6ff":"transparent",border:"none",borderRadius:6,cursor:b?"default":"pointer",textAlign:"left",outline:"none"},onMouseEnter:x=>{b||(x.currentTarget.style.background="#f1f5f9")},onMouseLeave:x=>{x.currentTarget.style.background=b?"#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:b?"✓":""}),i.jsxs("span",{style:{display:"flex",flexDirection:"column",gap:2,minWidth:0},children:[i.jsx("span",{style:{fontWeight:600,color:b?"#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 by(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:y,templateVersion:g,templateList:m,onSwitchTemplate:h}=e,[v,b]=u.useState(!1),[x,k]=u.useState(!1),{t:w}=tt(),{state:_,dispatch:C}=Je(),[E,S]=u.useState(null);u.useEffect(()=>{const I=()=>{const F=window.__g7LayoutEditorHistory;S(F?{undo:F.undo,redo:F.redo,canUndo:!!F.canUndo,canRedo:!!F.canRedo}:null)};I();const P=window.setInterval(I,250);return()=>window.clearInterval(P)},[]);const T=()=>{C({type:"TOGGLE_ROUTE_TREE"})},$=()=>_.editMode==="base"?w("layout_editor.chrome.toolbar.mode_badge.base"):_.editMode==="modal"?w("layout_editor.chrome.toolbar.mode_badge.modal"):_.editMode==="extension"?w("layout_editor.chrome.toolbar.mode_badge.extension"):_.editMode==="iteration_item"?w("layout_editor.chrome.toolbar.mode_badge.iteration_item"):null,A=()=>{_.editMode==="base"?C({type:"EXIT_BASE_EDIT"}):_.editMode==="modal"?C({type:"EXIT_MODAL_EDIT"}):_.editMode==="extension"?C({type:"EXIT_EXTENSION_EDIT"}):_.editMode==="iteration_item"&&C({type:"EXIT_ITERATION_ITEM_EDIT"})},z=$(),D=_.editMode!=="route",O={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"},M={...O,backgroundColor:"#2563eb",color:"#ffffff",borderColor:"#2563eb",fontWeight:600},B={...O,borderColor:"#e2e8f0",backgroundColor:"#ffffff",color:"#0f172a"},N={backgroundColor:"#f1f5f9",color:"#0f172a",borderColor:"#cbd5e1"},H={backgroundColor:"#1d4ed8",borderColor:"#1d4ed8"},L={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":w("layout_editor.chrome.toolbar.toggle_route_tree"),title:w("layout_editor.chrome.toolbar.toggle_route_tree"),onClick:T,style:{...O,outline:"none",padding:"6px 10px",fontSize:16,lineHeight:1,color:"#64748b"},children:"☰"}),i.jsx(yy,{templateIdentifier:_.templateIdentifier,templateName:y,templateVersion:g,templateList:m,onSwitch:h}),z&&i.jsx("span",{className:"g7le-toolbar__mode-badge","data-testid":"g7le-toolbar-mode-badge","data-mode":_.editMode,style:{padding:"2px 8px",borderRadius:999,background:"#fef3c7",color:"#92400e",fontSize:11,fontWeight:600,border:"1px solid #fde68a"},children:z}),i.jsx("div",{style:{flex:1}}),i.jsxs(i.Fragment,{children:[i.jsx(wt,{"data-testid":"g7le-toolbar-undo","aria-label":w("layout_editor.chrome.toolbar.undo"),title:w("layout_editor.chrome.toolbar.undo"),disabled:!E?.canUndo,onClick:()=>E?.undo?.(),baseStyle:O,hoverStyle:N,style:{opacity:E?.canUndo?1:.4},children:"↶"}),i.jsx(wt,{"data-testid":"g7le-toolbar-redo","aria-label":w("layout_editor.chrome.toolbar.redo"),title:w("layout_editor.chrome.toolbar.redo"),disabled:!E?.canRedo,onClick:()=>E?.redo?.(),baseStyle:O,hoverStyle:N,style:{opacity:E?.canRedo?1:.4},children:"↷"}),i.jsxs(wt,{"data-testid":"g7le-toolbar-add-element","data-open":_.isPaletteOpen?"true":"false",disabled:!_.selectedRoute,onClick:()=>C({type:"TOGGLE_PALETTE"}),"aria-pressed":_.isPaletteOpen,baseStyle:O,hoverStyle:N,style:_.isPaletteOpen?{backgroundColor:"#eff6ff",color:"#1d4ed8",borderColor:"#93c5fd"}:void 0,children:["+ ",w("layout_editor.chrome.toolbar.add_element")]}),i.jsx(wt,{"data-testid":"g7le-toolbar-preview","data-previewing":x?"true":"false",disabled:!p||!_.selectedRoute?.layoutName||x,onClick:()=>{const I=p?.();I&&typeof I.then=="function"&&(k(!0),I.finally(()=>k(!1)))},baseStyle:O,hoverStyle:N,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"}}),w("layout_editor.chrome.toolbar.previewing")]}):i.jsxs(i.Fragment,{children:["👁 ",w("layout_editor.chrome.toolbar.preview")]})}),i.jsxs(wt,{"data-testid":"g7le-toolbar-versions",disabled:!f||!(_.selectedRoute?.layoutName||_.selectedRoute?.path?.startsWith("__extension__/")),onClick:()=>f?.(),"aria-label":w("layout_editor.chrome.toolbar.version_history"),title:w("layout_editor.chrome.toolbar.version_history"),baseStyle:O,hoverStyle:N,children:["🕘 ",w("layout_editor.chrome.toolbar.version_history")]}),i.jsxs(wt,{"data-testid":"g7le-toolbar-edit-code",disabled:!r,onClick:()=>r?.(),baseStyle:O,hoverStyle:N,children:["⟨/⟩ ",w("layout_editor.chrome.toolbar.edit_code")]}),i.jsxs(wt,{"data-testid":"g7le-toolbar-images",disabled:!s||!_.selectedRoute,onClick:()=>s?.(),baseStyle:O,hoverStyle:N,children:["🖼 ",w("layout_editor.chrome.toolbar.images")]}),i.jsxs(wt,{"data-testid":"g7le-toolbar-translations",disabled:!a||!_.selectedRoute,onClick:()=>a?.(),baseStyle:O,hoverStyle:N,children:["🌐 ",w("layout_editor.chrome.toolbar.translations")]}),i.jsxs(wt,{"data-testid":"g7le-toolbar-page-settings",disabled:!l||!_.selectedRoute||_.editMode==="extension"||_.editMode==="iteration_item",onClick:()=>l?.(),baseStyle:O,hoverStyle:N,children:["⚙ ",w("layout_editor.chrome.toolbar.page_settings")]}),i.jsxs(wt,{"data-testid":"g7le-toolbar-reset",disabled:!d||!n,onClick:()=>d?.(),"aria-label":w("layout_editor.chrome.toolbar.reset"),title:w("layout_editor.chrome.toolbar.reset"),baseStyle:O,hoverStyle:N,style:{opacity:n?1:.4},children:["↺ ",w("layout_editor.chrome.toolbar.reset")]}),i.jsx(wt,{"data-testid":"g7le-toolbar-save","data-dirty":n?"true":"false","data-saving":v?"true":"false",disabled:!t||v,onClick:()=>{const I=t?.();I&&typeof I.then=="function"&&(b(!0),I.finally(()=>b(!1)))},baseStyle:M,hoverStyle:H,style:{opacity:v?.7:n?1:.7},children:v?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"}}),w("layout_editor.chrome.toolbar.saving")]}):i.jsxs(i.Fragment,{children:["💾 ",w("layout_editor.chrome.toolbar.save")]})}),i.jsx(wt,{"data-testid":"g7le-toolbar-shortcuts",disabled:!c,onClick:()=>c?.(),"aria-label":w("layout_editor.shortcuts.title"),title:w("layout_editor.shortcuts.title"),baseStyle:O,hoverStyle:N,children:"⌨"}),i.jsxs(wt,{"data-testid":"g7le-toolbar-exit",disabled:!o,onClick:()=>o?.(),baseStyle:B,hoverStyle:L,children:["✕ ",w("layout_editor.chrome.toolbar.exit")]})]}),D&&i.jsxs(wt,{"data-testid":"g7le-toolbar-exit-alt-mode",onClick:A,baseStyle:B,hoverStyle:L,children:["← ",_.editMode==="base"&&w("layout_editor.chrome.toolbar.exit_base_edit"),_.editMode==="modal"&&w("layout_editor.chrome.toolbar.exit_modal_edit"),_.editMode==="extension"&&w("layout_editor.chrome.toolbar.exit_extension_edit"),_.editMode==="iteration_item"&&w("layout_editor.chrome.toolbar.exit_iteration_item_edit")]})]})}function ar(){if(typeof window>"u")return null;try{return window.localStorage?.getItem("auth_token")??null}catch{return null}}function je(e){const t={Accept:"application/json",...e??{}},n=ar();return n&&(t.Authorization=`Bearer ${n}`),t}function Mi(e){return encodeURIComponent(e)}async function Dl(e,t){const n=`/api/admin/templates/${Mi(e)}/layout-attachments?layout_name=${encodeURIComponent(t)}`;try{const o=await fetch(n,{method:"GET",headers:je(),credentials:"same-origin"}),r=await o.json().catch(()=>null);return!o.ok||!r?.success?{ok:!1,status:o.status,message:Li(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 Nl(e,t,n){const o=`/api/admin/templates/${Mi(e)}/layout-attachments`,r=new FormData;r.append("file",n),r.append("layout_name",t);try{const s=await fetch(o,{method:"POST",headers:je(),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:Li(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 zl(e){const t=`/api/admin/templates/layout-attachments/${Mi(String(e))}`;try{const n=await fetch(t,{method:"DELETE",headers:je(),credentials:"same-origin"}),o=await n.json().catch(()=>null);return!n.ok||o&&o.success===!1?{ok:!1,status:n.status,message:Li(o,n.status)}:{ok:!0,data:!0}}catch(n){return{ok:!1,status:0,message:n instanceof Error?n.message:"network error"}}}function Li(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 my(e){return e<1024?`${e} B`:e<1024*1024?`${Math.round(e/1024)} KB`:`${(e/(1024*1024)).toFixed(1)} MB`}function vy(e){if(!e)return"";const t=e.match(/^(\d{4})-(\d{2})-(\d{2})/);return t?`${t[2]}-${t[3]}`:""}function Ml({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),[y,g]=u.useState(null),m=u.useRef(null),h=u.useCallback(async()=>{c("loading"),g(null);const x=await Dl(e,t);x.ok?(l(x.data),c("idle")):(g(x.message),c("error"))},[e,t]);u.useEffect(()=>{h()},[h]);const v=async x=>{const k=x.target.files?.[0];if(!k)return;f(!0),g(null);const w=await Nl(e,t,k);w.ok?(l(_=>[w.data,..._.filter(C=>C.id!==w.data.id)]),r?.()):g(w.message),f(!1),m.current&&(m.current.value="")},b=async x=>{if(!(typeof window<"u"&&typeof window.confirm=="function"?window.confirm(n("layout_editor.attachment_manager.delete_confirm")):!0))return;const w=await zl(x.id);w.ok?(l(_=>_.filter(C=>C.id!==x.id)),r?.()):g(w.message)};return i.jsxs("div",{className:"g7le-attachment-manager","data-testid":"g7le-attachment-manager",style:_y,children:[i.jsxs("div",{"data-modal-drag-handle":!0,style:xy,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:wy,"data-testid":"g7le-attachment-manager-close",children:"✕"})]}),i.jsx("div",{style:ky,children:i.jsxs("label",{style:Sy,"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"})]})}),y&&i.jsx("div",{style:Cy,"data-testid":"g7le-attachment-manager-error",children:y}),i.jsx("div",{style:$y,children:d==="loading"?i.jsx("div",{style:Ll,"data-testid":"g7le-attachment-manager-loading",children:n("layout_editor.attachment_manager.loading")}):a.length===0&&d!=="error"?i.jsx("div",{style:Ll,"data-testid":"g7le-attachment-manager-empty",children:n("layout_editor.attachment_manager.empty")}):i.jsx("div",{style:Ey,"data-testid":"g7le-attachment-grid",children:a.map(x=>i.jsxs("div",{style:Iy,"data-testid":`g7le-attachment-card-${x.id}`,children:[i.jsx("div",{style:{...Ay,backgroundImage:`url(${x.url})`}}),i.jsx("div",{style:Ty,title:x.original_name,children:x.original_name}),i.jsxs("div",{style:Dy,children:[my(x.size),x.created_at?` · ${vy(x.created_at)}`:""]}),i.jsxs("div",{style:Ny,children:[o&&i.jsx("button",{type:"button",onClick:()=>o(x.url),style:zy,"data-testid":`g7le-attachment-use-${x.id}`,children:n("layout_editor.attachment_manager.use_as_bg")}),i.jsx("button",{type:"button",onClick:()=>b(x),style:My,"data-testid":`g7le-attachment-delete-${x.id}`,children:"🗑"})]})]},x.id))})}),i.jsx("div",{style:Ly,children:i.jsx("button",{type:"button",onClick:s,style:Py,"data-testid":"g7le-attachment-manager-footer-close",children:n("layout_editor.attachment_manager.close")})})]})}const _y={display:"flex",flexDirection:"column",minHeight:0,flex:1},xy={display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #e2e8f0"},wy={border:"none",background:"transparent",fontSize:16,color:"#94a3b8",cursor:"pointer"},ky={padding:"10px 16px",borderBottom:"1px solid #f1f5f9",display:"flex",gap:8},Sy={padding:"6px 12px",fontSize:13,border:"1px solid #2563eb",borderRadius:6,background:"#fff",color:"#2563eb",cursor:"pointer",display:"inline-flex",alignItems:"center"},Cy={padding:"8px 16px",fontSize:12,color:"#b91c1c",background:"#fef2f2"},$y={padding:16,overflow:"auto",flex:1,minHeight:120},Ll={fontSize:13,color:"#94a3b8",textAlign:"center",padding:"32px 0"},Ey={display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(140px, 1fr))",gap:12},Iy={display:"flex",flexDirection:"column",gap:4,border:"1px solid #e2e8f0",borderRadius:8,padding:8},Ay={width:"100%",height:88,borderRadius:6,border:"1px solid #cbd5e1",backgroundSize:"cover",backgroundPosition:"center",backgroundColor:"#f8fafc"},Ty={fontSize:12,fontWeight:600,color:"#0f172a",whiteSpace:"nowrap",overflow:"hidden",textOverflow:"ellipsis"},Dy={fontSize:11,color:"#64748b"},Ny={display:"flex",gap:6,marginTop:2},zy={flex:1,padding:"4px 6px",fontSize:11,border:"1px solid #2563eb",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"},My={padding:"4px 8px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},Ly={padding:"10px 16px",borderTop:"1px solid #e2e8f0",display:"flex",justifyContent:"flex-end"},Py={padding:"6px 14px",fontSize:13,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"};function lr(e){return encodeURIComponent(e)}async function Oy(e,t,n){const o=new URLSearchParams;t&&o.set("layout_name",t);const r=o.toString(),s=`/api/admin/templates/${lr(e)}/custom-translations`+(r?`?${r}`:"");try{const a=await fetch(s,{method:"GET",headers:je(),credentials:"same-origin"}),l=await a.json().catch(()=>null);return!a.ok||!l?.success?{ok:!1,status:a.status,message:dr(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 By(e,t,n,o){const r=`/api/admin/templates/${lr(e)}/custom-translations/${t}`;try{const s=await fetch(r,{method:"PUT",headers:je({"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:dr(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 Wy(e,t){const n=`/api/admin/templates/${lr(e)}/custom-translations/${t}`;try{const o=await fetch(n,{method:"DELETE",headers:je(),credentials:"same-origin"}),r=await o.json().catch(()=>null);return!o.ok||r&&r.success===!1?{ok:!1,status:o.status,message:dr(r,o.status)}:{ok:!0,data:!0}}catch(o){return{ok:!1,status:0,message:o instanceof Error?o.message:"network error"}}}async function jy(e,t){const n=`/api/admin/templates/${lr(e)}/custom-translations`;try{const o=await fetch(n,{method:"DELETE",headers:je({"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:dr(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 Pl=/\$t:(custom\.[A-Za-z0-9_\-]+\.\d+)/g;function Hy(e){const t=new Set,n=o=>{if(typeof o=="string"){if(o.includes("$t:custom.")){let r;for(Pl.lastIndex=0;(r=Pl.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 dr(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,bo=Lt().createLogger,Pi=bo("EditorSpecLoader"),Fy=["controls","componentCapabilities","actionRecipes","conditionRecipes","pageSettings","initActionRecipes","errorRecipes","computedRecipes","loadingComponents"],Ky=["actionRecipes","initActionRecipes","errorRecipes","computedRecipes","loadingComponents"];function Ol(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 Vy(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&&Pi.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 Pi.warn("fetchOneSpec: fetch failed",s,a),null}}function Uy(e){return Ky.includes(e)}function qy(e,t){return e==null||typeof e!="object"?e:{...e,__source:t}}function Gy(e,t,n,o){const r=t[n];if(!r||typeof r!="object")return;const s=e[n]??{};if(o&&Uy(n)){const a={};for(const[l,d]of Object.entries(r))a[l]=qy(d,o);e[n]={...s,...a};return}e[n]={...s,...r}}function Yy(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 Xy(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 Jy(e,t){if(!t.states)return;const n=e.states??{},o=[...n.groups??[],...t.states.groups??[]];n.groups=o,e.states=n}function Zy(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 Qy(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 Ry(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 Bl(e,t,n){for(const o of Fy)Gy(e,t,o,n);Yy(e,t),Xy(e,t),Jy(e,t),Zy(e,t),Qy(e,t),Ry(e,t),t.version&&(e.version=t.version)}async function eb(e){const t=e.apiBaseUrl??"/api",n=e.fetcher??(typeof fetch<"u"?fetch:void 0);if(!n)return Pi.warn("loadEditorSpecBundle: fetch unavailable, returning null spec"),{spec:null,sampleGlobalSources:[]};const o=e.activeModuleIdentifiers??Ol("activeModules"),r=e.activePluginIdentifiers??Ol("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=>Vy(p.kind,p.id,t,n)));let l=null;const d=[],c={};if(e.coreSeed&&(l={},Bl(l,e.coreSeed,{kind:"core"})),s.forEach((p,f)=>{const y=a[f];if(!y)return;y.sampleGlobal&&typeof y.sampleGlobal=="object"&&d.push({id:p.id,kind:p.kind,sampleGlobal:y.sampleGlobal});const g=y.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={}),Bl(l,y,{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 Oi(e,t){return e?.componentCapabilities?.[t]??null}function Ct(e,t){return e?.controls?.[t]??null}function tb(e){return e?.initActionRecipes??{}}function nb(e){return e?.computedRecipes??{}}function ob(e){return e?.errorRecipes??{}}function rb(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 ib(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 Bi(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)}function sb(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 ab(e){const t=e.find(n=>Bi(n));if(Bi(t))return Object.keys(t).slice(0,8)}function lb(e){return Object.keys(e).slice(0,8)}function db(e){const t=Object.entries(e);return t.length===0?!1:t.some(([,n])=>n===null||typeof n!="object")}function Wi(e,t,n,o,r){if(Array.isArray(e)){r(t,"array",`[${e.length}]`,ab(e));return}if(Bi(e)){if(t&&db(e)){const s=lb(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;Wi(a,l,n+1,o,r)}return}r(t,"scalar",sb(e))}function cb(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(Wl(d))||[];o.push({name:l.item_var,kind:"item",itemFields:c})}}return o}function Wl(e){return e.replace(/^\{\{|\}\}$/g,"").trim()}function ub(e){const t=new Map;for(const n of e)n.shape==="array"&&n.itemFields&&n.itemFields.length>0&&t.set(Wl(n.expression),n.itemFields);return t}function ji(e){const t=e.maxDepth??4,n=[];for(const o of e.dataSources??[])!o||typeof o.id!="string"||o.id.length===0||Wi(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"||Wi(o.tree,"",0,t,(r,s,a,l)=>{if(!r)return;const d=ib(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 pb=["$localized"];function fb(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(!pb.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 Ki(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 jl(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 Vi=/\{\{(?:[^}]|\}(?!\}))*\}\}/g;function In(e){const t=[];if(typeof e!="string"||e.length===0)return t;let n=0,o=0;const r=new RegExp(Vi.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 Ui(e){return typeof e!="string"?!1:new RegExp(Vi.source).test(e)}function hb(e){const t=new Set(e.map(o=>o.trim()));let n=0;for(;t.has(`p${n}`);)n+=1;return`p${n}`}function Hl(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 qi(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 Fl(e){return cr(e).map(t=>({bindingIndex:t.bindingIndex??0,expression:t.raw,parsed:t.parsed??null,isComplex:(t.parsed??null)===null}))}function ur(e){return typeof e!="string"?"":e.replace(new RegExp(Vi.source,"g")," ").replace(/\s+/g," ").trim()}const yb=/\$t:([a-zA-Z0-9._-]+)/g,Kl="custom.";function Gi(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(yb,(o,r)=>{if(r.startsWith(Kl))return o;const s=t(r);return s&&s!==r?s:o})).join(""):e}const Kn="(?:(?!\\|[a-zA-Z0-9_]+=).)*",bb=new RegExp(`^\\s*\\$t:([a-zA-Z0-9._-]+)((?:\\|[a-zA-Z0-9_]+=${Kn})*)`),mb=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 Vl=/\$(?:core|module|plugin)_settings:[a-zA-Z0-9._:-]+/g;function Ul(e){return typeof e=="string"&&new RegExp(Vl.source).test(e)}function vb(e){return typeof e!="string"?"":e.replace(/^\$(?:core|module|plugin)_settings:/,"").split(/[.:]/).filter(Boolean).pop()||e}function ql(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(Vl.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:vb(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=bb.exec(e);if(d&&!d[1].startsWith(Kl)){const g=d[1],m=d[2]??"",h=e.slice(d[0].length),v=new Map,b=new RegExp(mb.source,"g");let x;for(;(x=b.exec(m))!==null;)x[2]&&x[2].includes("{{")&&v.set(x[1],x[2]);const k=t?t(g):"";if(k&&k!==g&&!k.startsWith("$t:"))l=k.replace(/\{\{?([a-zA-Z0-9_]+)\}?\}/g,(w,_)=>{const C=v.get(_);return C?s(C):w});else return n;a=h}const c=Gi(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 Gl(e,t){return t.bindings.length?e+t.bindings.map((n,o)=>`|p${o}=${n}`).join(""):e}function Yl(e,t){const n=cr(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 Xl(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 Jl=new RegExp(`^\\s*\\$t:([a-zA-Z0-9._-]+)((?:\\|[a-zA-Z0-9_]+=${Kn})+)\\s*$`),xb=new RegExp(`\\|([a-zA-Z0-9_]+)=(${Kn})`,"g");function mt(e){if(typeof e!="string")return null;const t=Jl.exec(e);if(!t)return null;const n=t[1],o=t[2],r=[],s=new RegExp(xb.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 Zl(e){return typeof e=="string"&&Jl.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 wb(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 mo(e,t){if(typeof e!="string")return e;const n=new RegExp(`\\|${t}=${Kn}`);return e.replace(n,"")}function Ql(e,t){return typeof e!="string"?e:e.replace(new RegExp(`\\s*\\{\\{?${t}\\}?\\}\\s*`,"g")," ").replace(/\s+/g," ").trim()}function kb(e,t){const n=s=>cr(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 Rl(e){return e.__source?.kind==="base"}function ed(e){return e.__source?.kind==="partial"}function Sb(e){return e.__source?.kind==="route"}function pr(e,t){return e.__source?.kind!=="extension"?!1:t==null?!0:e.__source.extensionId!==t}function td(e){return e.type==="extension_point"}function Xi(e=[]){for(const t of e)if(t.iteration&&t.iteration.source!==void 0)return!0;return!1}function Cb(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:nd(e)}function nd(e){if(typeof e.text=="string"&&od(e.text)&&!$b(e.text))return!0;if(e.props&&typeof e.props=="object"){for(const t of Object.values(e.props))if(typeof t=="string"&&od(t))return!0}return!1}function od(e){return/\{\{[\s\S]*?\}\}/.test(e)}function $b(e){const t=mt(e);return t!==null&&t.key.startsWith("custom.")}function Eb(e,t){return e??t??null}function Ji(e,t,n){if(td(e))return!0;switch(t){case"route":return Rl(e)||ed(e)||pr(e);case"base":return pr(e);case"modal":return pr(e);case"extension":return pr(e,n)?!0:Rl(e)||Sb(e)||ed(e);default:return!1}}function et(e){return typeof e=="object"&&e!==null&&typeof e.responsive=="string"}function fr(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 gr(e,t){const n=e.responsive?.[t];return n&&Array.isArray(n.children)?n.children:[]}function We(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=gr(n,r.responsive);continue}if(r<0||r>=o.length||(n=o[r],!n))return null;o=Qt(n)}return n}function Ib(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=We(e,t.slice(0,-2));return a?{owner:a,children:gr(a,r.responsive),branchKey:r.responsive,index:o}:null}const s=We(e,t.slice(0,-1));return s?{owner:s,children:Qt(s),index:o}:null}function Zi(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 Qi(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=We(r,t.slice(0,-1));if(!p)return r;const f=gr(p,s.responsive),y=Math.max(0,Math.min(n,f.length)),g=[...f];return g.splice(y,0,o),Zi({owner:p,branchKey:s.responsive},g),r}const a=We(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 Ri(e,t){if(t.length===0)return e;const n=Rt(e),o=rd(n,t);if(!o||o.index<0||o.index>=o.children.length)return n;const r=[...o.children];return r.splice(o.index,1),Zi(o,r),n}function Ab(e,t,n,o){if(t.length===0||!n||et(t[t.length-1]))return e;const r=Rt(e),s=We(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 Tb(e,t,n){if(t.length===0||!n||et(t[t.length-1]))return e;const o=Rt(e),r=We(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 Db(e,t,n,o){if(t.length===0)return e;const r=We(e,t);if(!r||Nb(t,n))return e;const s=Rt(r),a=Ri(e,t),l=id(n,t);let d=o;const c=t.slice(0,-1);if(sd(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 sd(e,t){if(e.length!==t.length)return!1;for(let n=0;ne.length||sd(e,t)}function es(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}_${zb()}`}const n=Qt(e);return n.length>0&&(t.children=n.map(es)),t}function Ot(e,t,n){if(t.length===0)return n(e);const o=Rt(e),r=We(o,t);if(!r)return o;const s=n(r),a=rd(o,t);if(!a||a.index<0||a.index>=a.children.length)return o;const l=[...a.children];return l[a.index]=s,Zi(a,l),o}function zb(){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=Mb(n);o.length>0&&t.push(...o)}return t}function Mb(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 vo(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[y,g]of Object.entries(c))f[y]=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[y,g]of Object.entries(c))f[y]=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 ad="extension",Un="extensionless";function Lb(){const e=globalThis?.G7Config;if(globalThis?.__g7AssetUrlMode===Un)return Un;const n=e?.assetUrlMode;return n===Un||n===ad?n:e?.settings?.general?.asset_url_mode===Un?Un:ad}function Pb(){return Lb()===Un}function en(e,t,n,o){const r=e.replace(/\/+$/,""),s=t.replace(/^\.+/,""),a=Pb()?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 ld=/^\s*\$t:([a-zA-Z0-9._-]+)\s*$/,hr="custom.",Ob=/\{\{.*?\}\}/;function Bb(e){return!!(!e||e.iteration&&typeof e.iteration=="object")}function dd(e,t){const n=e?.text,o=typeof n=="string"?n:"";if(Bb(e)||typeof n!="string")return{sourceState:"plain_text",editable:!1,customKey:null,displayValue:o};const r=mt(o);if(r&&r.key.startsWith(hr)){const a=t?t(r.key):r.key;return{sourceState:"custom_key",editable:!0,customKey:r.key,displayValue:a,isParamKey:!0}}const s=ld.exec(o);if(s){const a=s[1];if(a.startsWith(hr)){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(Ob.test(o)){const a=ur(o),l=ld.exec(a);if(l&&l[1].startsWith(hr)){const f=l[1],y=t?t(f):f;return{sourceState:"custom_key",editable:!0,customKey:f,displayValue:y}}const d=Gi(o,t),c=ur(d),p=/\$t:[a-zA-Z0-9._-]+/.test(c);if(c.length>0){const f=Yi(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 Wb(){const{state:e}=Je(),t=Ft(),n=e.templateIdentifier,o=e.locale,r=e.selectedRoute?.layoutName??null,s=u.useCallback(p=>{try{const y=Pt.getInstance().translate(p,{templateId:n,locale:o});return y&&y!==p?y:""}catch{return""}},[n,o]),a=u.useCallback(p=>dd(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=We(g,p),h=dd(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};_o(n,o,h.customKey,f);const E=await yr(n,h.customKey,o,f);return E.kind==="error"?{kind:"error",message:E.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:Ni(f),timestamp:Date.now()}),{kind:"updated",translationKey:h.customKey})}const v=typeof m?.text=="string"?m.text:"",b=h.sourceState==="plain_with_binding",x=Gi(v,s),k=b?Xl(x):f,w=E=>b?Yl(E,v):E;t.patchLayout(E=>Ot({children:E},p,$=>({...$,text:f})).children??[]);const _=await qn(n,r,o,k);if(_.kind==="error"||!_.resource)return{kind:"error",message:_.message};const C=_.resource.translation_key;return _o(n,o,C,k),t.patchLayout(E=>Ot({children:E},p,$=>({...$,text:w(`$t:${C}`)})).children??[]),await tn(n,o),Et({op:"inline_edit_create_key",sourceState:h.sourceState,componentPath:at(p),translationKey:C,toLocale:o,valueLength:f.length,valueHash:Ni(f),timestamp:Date.now()}),{kind:"created",translationKey:C,id:_.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=We(g,p),h=typeof m?.text=="string"?m.text:"",v=mt(h);if(v&&v.key.startsWith(hr))return br(n,v.key,o,f),_o(n,o,v.key,f),t.markDirty?.(),{kind:"updated",translationKey:v.key};const b=Yi(h,s),x=ur(f.replace(/\{\{?p\d+\}?\}/g," ")).replace(/\s+/g," ").trim(),k=await qn(n,r,o,x);if(k.kind==="error"||!k.resource)return{kind:"error",message:k.message};const w=k.resource.translation_key,_=An(f),C=k.resource.values??{},E={[o]:f};for(const S of Object.keys(C)){if(S===o)continue;let T=C[S]??"";for(const $ of _)T=qi(T,$);E[S]=T}return xo(n,w,E),_o(n,o,w,f),t.patchLayout(S=>Ot({children:S},p,A=>({...A,text:Gl(`$t:${w}`,b)})).children??[]),t.markDirty?.(),await tn(n,o),_o(n,o,w,f),Et({op:"inline_edit_create_key",sourceState:"plain_with_binding",componentPath:at(p),translationKey:w,toLocale:o,valueLength:f.length,valueHash:Ni(f),timestamp:Date.now()}),{kind:"created",translationKey:w}},[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:je({"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 yr(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:je({"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:je()});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 _o(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 br(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 xo(e,t,n){for(const[o,r]of Object.entries(n))br(e,t,o,r)}function It(e,t){return nn.get(e)?.[t]}function jb(e){const t=nn.get(e);return t?{...t}:void 0}function Hb(){return nn.size>0}function cd(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 Fb(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:je({"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 ud(){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 Kb({locales:e}={}){const{t}=tt(),{state:n,dispatch:o}=Je();u.useEffect(()=>{window.__g7EditorContentLocale=n.locale},[n.locale]);const r=e??ud(),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 Vb=/\{\{?(p\d+)\}?\}/g;function Ub(e){const t=[];if(typeof e!="string"||e.length===0)return t;const n=new RegExp(Vb.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 Gb(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 mr({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(()=>qb(e),[e]),f=u.useRef(null),[y,g]=u.useState(null),[m,h]=u.useState(null),[v,b]=u.useState(null),x=u.useMemo(()=>p.map(B=>B.kind==="chip"?`c:${B.paramName}`:"t").join("|"),[p]),k=u.useRef(null),w=u.useRef([]),_=u.useRef(!1);u.useLayoutEffect(()=>{const B=_.current;_.current=!1,!(!B&&k.current===x)&&(k.current=x,p.forEach((N,H)=>{if(N.kind!=="text")return;const L=w.current[H];L&&L.textContent!==(N.text??"")&&(L.textContent=N.text??"")}))},[x,p,e]);const C=()=>{const B=f.current;if(!B)return e;const N=[];for(const H of Array.from(B.querySelectorAll("[data-seg]")))H.dataset.seg==="chip"?N.push(`{${H.dataset.param??""}}`):N.push(H.textContent??"");return N.join("")},E=()=>{l||t(C())},S=u.useRef(null),T=u.useRef(!1),$=(B,N)=>{if(!l){B.preventDefault(),B.stopPropagation(),S.current={param:N,pointerId:B.pointerId},T.current=!1,g(N);try{B.currentTarget.setPointerCapture(B.pointerId)}catch{}}},A=B=>{const N=S.current;if(!N||B.pointerId!==N.pointerId)return;T.current=!0;const H=O(B.clientX,B.clientY);H&&(h({slotIdx:H.slotIdx,offset:H.offset}),b(Xb(f.current,H.slotIdx,H.offset)))},z=(B,N)=>{if(B.stopPropagation(),T.current){T.current=!1;return}s?.(N)},D=B=>{const N=S.current;if(!N||B.pointerId!==N.pointerId)return;try{B.currentTarget.releasePointerCapture(B.pointerId)}catch{}S.current=null,T.current&&typeof setTimeout=="function"&&setTimeout(()=>{T.current=!1},0);const H=O(B.clientX,B.clientY);if(g(null),h(null),b(null),!H)return;const L=f.current;if(!L)return;const P=Array.from(L.querySelectorAll("[data-seg]")).map(G=>G.dataset.seg==="chip"?{kind:"chip",paramName:G.dataset.param??""}:{kind:"text",text:G.textContent??""}),F=Gb(P,N.param,H.slotIdx,H.offset);F!==e&&(_.current=!0,t(F))},O=(B,N)=>{const H=f.current;if(!H)return null;const L=Array.from(H.querySelectorAll("[data-seg]")),I=H.ownerDocument,P=I.elementFromPoint(B,N);let F=P?.closest('[data-seg="text"]');if(F)return{slotIdx:L.indexOf(F),offset:Yb(I,F,B,N)};const G=P?.closest('[data-seg="chip"]');if(G){const Y=L.indexOf(G),Z=G.getBoundingClientRect();if(B=0){const se=L[Y-1];return{slotIdx:Y-1,offset:(se.textContent??"").length}}if(Y+1({s:Y,i:Z})).filter(Y=>Y.s.dataset.seg==="text").pop();return V?{slotIdx:V.i,offset:(V.s.textContent??"").length}:null},M=()=>{l||!r||r(pd(f.current,e.length))};return u.useEffect(()=>{if(c)return c.current=()=>pd(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:Jb,children:[p.map((B,N)=>B.kind==="chip"?i.jsxs("span",{"data-seg":"chip","data-param":B.paramName,"data-testid":`g7le-chip-${a}-${B.paramName}`,contentEditable:!1,onPointerDown:H=>$(H,B.paramName??""),onPointerMove:A,onPointerUp:D,title:n("layout_editor.translation.placeholder_locked"),style:{...em,...y===B.paramName?tm:null,touchAction:"none"},children:[i.jsx("span",{"aria-hidden":"true",style:nm,children:"⠿"}),i.jsx("span",{"aria-hidden":"true",style:{marginRight:3},children:"🔗"}),i.jsx("span",{style:om,children:o?.[B.paramName??""]??B.paramName}),s&&!l&&i.jsx("button",{type:"button","data-testid":`g7le-chip-remove-${a}-${B.paramName}`,"aria-label":n("layout_editor.inline_binding.clear"),title:n("layout_editor.inline_binding.clear"),onPointerDown:H=>{H.stopPropagation(),H.preventDefault()},onClick:H=>z(H,B.paramName??""),style:rm,children:"✕"})]},`chip-${B.paramName}`):i.jsx("span",{ref:H=>{w.current[N]=H},"data-seg":"text",contentEditable:!l,suppressContentEditableWarning:!0,onInput:E,"data-testid":`g7le-chip-text-${a}-${N}`,style:{...Zb,...y?Qb:null,...m?.slotIdx===N?Rb:null}},`text-slot-${N}`)),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:im,children:["+ ",n("layout_editor.inline_binding.insert_data")]}),i.jsx("span",{style:sm,children:n("layout_editor.translation.placeholder_locked")})]})]})}function Yb(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 Xb(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 y=p.getClientRects(),g=y.length>0?y[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 pd(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 Jb={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},Zb={outline:"none",minWidth:8,minHeight:"1.2em",whiteSpace:"pre-wrap",color:"#0f172a",display:"inline-block"},Qb={boxShadow:"inset 0 -2px 0 #93c5fd",background:"#eff6ff",borderRadius:2},Rb={background:"#dbeafe",boxShadow:"inset 0 -2px 0 #2563eb"},em={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"},tm={opacity:.5,borderStyle:"solid",cursor:"grabbing"},nm={color:"#2563eb",opacity:.7,fontSize:11,marginRight:1,cursor:"grab"},om={textDecoration:"none"},rm={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"},im={fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#334155",padding:"3px 10px",cursor:"pointer"},sm={fontSize:10,color:"#94a3b8"};function fd(e){e&&(e.style.height="auto",e.style.height=`${Math.max(e.scrollHeight,28)}px`)}function am(e){fd(e)}function lm(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 dm({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,y]=u.useState("all"),[g,m]=u.useState(new Set),[h,v]=u.useState({}),[b,x]=u.useState(null),[k,w]=u.useState({}),_=u.useCallback(async()=>{d("loading"),p(null);const N=await Oy(e,t);N.ok?(a(N.data),v({}),m(new Set),w({}),d("idle")):(p(N.message),d("error"))},[e,t]);u.useEffect(()=>{_()},[_]);const C=u.useMemo(()=>lm(s),[s]),E=u.useMemo(()=>s.filter(N=>f==="all"?!0:N.status===f).slice().sort((N,H)=>{const L=N.updated_at?Date.parse(N.updated_at):0,I=H.updated_at?Date.parse(H.updated_at):0;return I!==L?I-L:H.id-N.id}),[s,f]),S=u.useMemo(()=>s.filter(N=>N.status==="orphaned"),[s]),T=u.useCallback(N=>{const H={...N.values??{}};for(const L of Object.keys(H)){const I=It(N.translation_key,L);I!==void 0&&(H[L]=I)}return H},[]),$=u.useCallback(N=>h[N.id]??T(N),[h,T]),A=u.useCallback((N,H,L)=>{v(I=>{const P=I[N]??s.find(F=>F.id===N)?.values??{};return{...I,[N]:{...P,[H]:L}}})},[s]),z=u.useCallback(async N=>{x(N.id),w(I=>({...I,[N.id]:""}));const H=$(N),L=await By(e,N.id,H,N.lock_version);if(L.ok)a(I=>I.map(P=>P.id===N.id?L.data:P)),v(I=>{const P={...I};return delete P[N.id],P});else{const I=L.status===409?n("layout_editor.translation_manager.conflict"):L.message;w(P=>({...P,[N.id]:I}))}x(null)},[e,$,n]),D=u.useCallback(N=>typeof window<"u"&&typeof window.confirm=="function"?window.confirm(n("layout_editor.translation_manager.delete_confirm",{count:N})):!0,[n]),O=u.useCallback(async N=>{if(!D(1))return;const H=await Wy(e,N.id);H.ok?(a(L=>L.filter(I=>I.id!==N.id)),m(L=>{const I=new Set(L);return I.delete(N.id),I})):p(H.message)},[e,D]),M=u.useCallback(async N=>{if(N.length===0||!D(N.length))return;const H=await jy(e,N);if(H.ok){const L=new Set(N);a(I=>I.filter(P=>!L.has(P.id))),m(new Set)}else p(H.message)},[e,D]),B=u.useCallback(N=>{m(H=>{const L=new Set(H);return L.has(N)?L.delete(N):L.add(N),L})},[]);return i.jsxs("div",{className:"g7le-translation-manager","data-testid":"g7le-translation-manager",style:cm,children:[i.jsxs("div",{"data-modal-drag-handle":!0,style:um,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:pm,"data-testid":"g7le-translation-manager-close",children:"✕"})]}),i.jsxs("div",{style:fm,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(N=>i.jsx("button",{type:"button",role:"tab","aria-selected":f===N,"data-active":f===N?"true":"false",onClick:()=>y(N),style:f===N?gm:gd,"data-testid":`g7le-translation-filter-${N}`,children:n(`layout_editor.translation_manager.filter_${N}`)},N))}),i.jsx("div",{style:{flex:1}}),g.size>0&&i.jsxs("button",{type:"button",onClick:()=>void M(Array.from(g)),style:hd,"data-testid":"g7le-translation-bulk-delete",children:["🗑 ",n("layout_editor.translation_manager.delete_selected",{count:g.size})]}),S.length>0&&i.jsxs("button",{type:"button",onClick:()=>void M(S.map(N=>N.id)),style:hd,"data-testid":"g7le-translation-purge-orphaned",children:["🧹 ",n("layout_editor.translation_manager.purge_orphaned",{count:S.length})]})]}),c&&i.jsx("div",{style:hm,"data-testid":"g7le-translation-manager-error",children:c}),i.jsx("div",{style:ym,children:l==="loading"?i.jsx("div",{style:yd,"data-testid":"g7le-translation-manager-loading",children:n("layout_editor.translation_manager.loading")}):E.length===0&&l!=="error"?i.jsx("div",{style:yd,"data-testid":"g7le-translation-manager-empty",children:n("layout_editor.translation_manager.empty")}):i.jsx("div",{"data-testid":"g7le-translation-list",style:bm,children:E.map(N=>{const H=$(N),L=N.status==="orphaned",I=o?o.has(N.translation_key):null;return i.jsxs("div",{style:mm,"data-testid":`g7le-translation-row-${N.id}`,children:[i.jsxs("div",{style:vm,children:[i.jsx("input",{type:"checkbox",checked:g.has(N.id),onChange:()=>B(N.id),"aria-label":n("layout_editor.translation_manager.select_aria",{key:N.translation_key}),"data-testid":`g7le-translation-select-${N.id}`}),i.jsx("code",{style:_m,children:N.translation_key}),L&&i.jsx("span",{style:xm,"data-testid":`g7le-translation-badge-orphaned-${N.id}`,children:n("layout_editor.translation_manager.badge_orphaned")}),I===!0&&i.jsx("span",{style:wm,"data-testid":`g7le-translation-badge-live-inuse-${N.id}`,children:n("layout_editor.translation_manager.badge_live_in_use")}),I===!1&&i.jsx("span",{style:km,"data-testid":`g7le-translation-badge-live-unused-${N.id}`,children:n("layout_editor.translation_manager.badge_live_unused")}),i.jsx("div",{style:{flex:1}}),i.jsx("button",{type:"button",onClick:()=>void O(N),style:Tm,"data-testid":`g7le-translation-delete-${N.id}`,children:"🗑"})]}),i.jsxs("div",{style:Sm,children:[C.map(P=>{const F=H[P]??"",G=An(F).length>0;return i.jsxs("div",{style:Cm,"data-testid":`g7le-translation-field-${N.id}-${P}`,children:[i.jsxs("label",{style:$m,title:P,children:[Gn(P,n),i.jsxs("span",{style:Em,children:["(",P,")"]})]}),G?i.jsx("div",{style:{flex:1},"data-testid":`g7le-translation-chip-${N.id}-${P}`,children:i.jsx(mr,{value:F,onChange:V=>A(N.id,P,V),t:n,testIdSuffix:`${N.id}-${P}`})}):i.jsx("textarea",{value:F,rows:1,ref:am,onChange:V=>{A(N.id,P,V.currentTarget.value),fd(V.currentTarget)},style:Im,"data-testid":`g7le-translation-input-${N.id}-${P}`})]},P)}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("button",{type:"button",disabled:b===N.id,onClick:()=>void z(N),style:Am,"data-testid":`g7le-translation-save-${N.id}`,children:b===N.id?n("layout_editor.translation_manager.saving"):n("layout_editor.translation_manager.save")}),k[N.id]?i.jsx("span",{style:{fontSize:11,color:"#dc2626"},"data-testid":`g7le-translation-row-error-${N.id}`,children:k[N.id]}):null]})]})]},N.id)})})}),i.jsx("div",{style:Dm,children:i.jsx("button",{type:"button",onClick:r,style:Nm,"data-testid":"g7le-translation-manager-footer-close",children:n("layout_editor.translation_manager.close")})})]})}const cm={display:"flex",flexDirection:"column",minHeight:0,flex:1},um={display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #e2e8f0"},pm={border:"none",background:"transparent",fontSize:16,color:"#94a3b8",cursor:"pointer"},fm={padding:"10px 16px",borderBottom:"1px solid #f1f5f9",display:"flex",gap:8,alignItems:"center"},gd={padding:"4px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},gm={...gd,borderColor:"#2563eb",background:"#eff6ff",color:"#1d4ed8",fontWeight:600},hd={padding:"4px 10px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},hm={padding:"8px 16px",fontSize:12,color:"#b91c1c",background:"#fef2f2"},ym={padding:16,overflow:"auto",flex:1,minHeight:120,display:"flex",flexDirection:"column",gap:12},yd={fontSize:13,color:"#94a3b8",textAlign:"center",padding:"32px 0"},bm={display:"flex",flexDirection:"column",gap:20},mm={border:"1px solid #e2e8f0",borderRadius:8,padding:10,display:"flex",flexDirection:"column",gap:6},vm={display:"flex",alignItems:"center",gap:8},_m={fontSize:11,background:"#f1f5f9",padding:"2px 6px",borderRadius:4,color:"#0f172a"},xm={fontSize:10,color:"#b45309",background:"#fef3c7",padding:"1px 6px",borderRadius:4,fontWeight:600},wm={fontSize:10,color:"#15803d",background:"#dcfce7",padding:"1px 6px",borderRadius:4,fontWeight:600},km={fontSize:10,color:"#9f1239",background:"#ffe4e6",padding:"1px 6px",borderRadius:4,fontWeight:600},Sm={display:"flex",flexDirection:"column",gap:6},Cm={display:"flex",alignItems:"flex-start",gap:8},$m={fontSize:12,color:"#475569",minWidth:88,fontWeight:600,paddingTop:4,display:"flex",flexDirection:"column",lineHeight:1.2},Em={fontSize:10,color:"#94a3b8",fontWeight:400},Im={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"},Am={padding:"5px 12px",fontSize:12,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"},Tm={padding:"4px 8px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},Dm={padding:"10px 16px",borderTop:"1px solid #e2e8f0",display:"flex",justifyContent:"flex-end"},Nm={padding:"6px 14px",fontSize:13,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"};function zm(){const e=Ft(),{state:t}=Je(),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?yr(o,c,p,f):null,[o]);return{raw:n,getValue:s,patch:a,createI18nKey:l,updateI18nKeyValue:d}}function Mm(e){const t=e.__source;return t&&(t.kind==="module"||t.kind==="plugin")&&t.identifier?`${t.kind}:${t.identifier}`:"template"}function bd(e,t){if(!t)return null;const n=Mm(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(Lm(r,s))return{value:a,match:{dataSourceId:e.id,resolvedBy:"spec_byEndpoint"}}}return null}function ts(e,t){const n=bd(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 Lm(e,t){const n=t.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${n}$`).test(e)}function Pm(e={}){const{spec:t,overrideSpec:n,onMatch:o}=e;return{has(r){return!0},resolve(r){const s=n?bd(r,n):null,{value:a,match:l}=s??ts(r,t);if(o)try{o(l)}catch{}return a}}}const md=Lt(),vd=md.DataBindingEngine,_d=md.dataBindingEngine;bo("PipeRegistry");function Om(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 vr(e){const t=e.trim(),n=/^\{\{([\s\S]*)\}\}$/.exec(t);return n?n[1].trim():t}function wd(e){const t=e.trim();return/^\{\{[\s\S]*\}\}$/.test(t)?t:`{{ ${t} }}`}function kd(e,t){const n={};for(const[r,s]of Object.entries(t))n[r]=typeof s=="string"?vr(s):s;const o=Wm(e.expr,n);return wd(o)}function jm(e,t){if(typeof e!="string")return null;const n=Sd(vr(e));for(const o of t){const r=Hm(n,o.expr,o.params);if(r)return{recipeId:o.id,params:r}}return null}function Sd(e){return e.replace(/\s+/g," ").trim()}function Cd(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Hm(e,t,n){const o=[],r=new Set;let s="";const a=/\{(\w+)(\*?)\}(\s*\?\?\s*)?/g;let l=0,d;const c=Sd(t);for(;(d=a.exec(c))!==null;){const g=c.slice(l,d.index);s+=Cd(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+=Cd(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 y={};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(", ")),y[g]=h}),n.length>0){const g=new Set(n.map(m=>m.key));for(const m of Object.keys(y))g.has(m)||delete y[m]}return y}function Fm(e){const t=`x.${e.field}`,n=Km(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 Km(e){const t=e.trim();return t==="true"||t==="false"||t!==""&&!Number.isNaN(Number(t))||/^['"].*['"]$/.test(t)||/[.([{]/.test(t)?t:`'${t.replace(/'/g,"\\'")}'`}function ns(e){return!e||e.length===0?"true":e.map(Fm).join(" && ")}function Vm(e){const n=`(${(e.source??"").trim()||"[]"} ?? [])`;let o;switch(e.op){case"count":o=`${n}.filter(x => ${ns(e.conditions)}).length`;break;case"sum":{const r=(e.sumField??"").trim()||"value";o=`${n}.filter(x => ${ns(e.conditions)}).reduce((s, x) => s + (x.${r} ?? 0), 0)`;break}case"filter":o=`${n}.filter(x => ${ns(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 wd(o)}function Um(e){if(typeof e!="string")return null;const t=vr(e).trim();let n=/^\((.+?)\s*\?\?\s*\[\]\)\.filter\(x => (.+)\)\.length$/.exec(t);return n?{key:"",op:"count",source:n[1].trim(),conditions:os(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:os(n[2]),sumField:n[3]}:(n=/^\((.+?)\s*\?\?\s*\[\]\)\.filter\(x => (.+)\)$/.exec(t),n?{key:"",op:"filter",source:n[1].trim(),conditions:os(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 os(e){const t=e.trim();if(t==="true")return[];const n=[];for(const o of qm(t)){const r=Gm(o.trim());r&&n.push(r)}return n}function qm(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:$d(t[3])}}return null}function $d(e){const t=e.trim(),n=/^'(.*)'$/.exec(t)||/^"(.*)"$/.exec(t);return n?n[1]:t}function Ed(e,t){const n=jm(e,t);if(n)return{kind:"preset",recipeId:n.recipeId,params:n.params};const o=Um(e);return o?{kind:"custom",model:o}:{kind:"advanced"}}function Ym(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 Id(e,t){if(typeof e!="string"||e.trim()==="")return{ok:!1,reason:"empty"};const n=vr(e);try{const o=Om(n)?_d.evaluatePipeExpression(n,t??{},{skipCache:!0}):_d.evaluateExpression(n,t??{},{skipCache:!0});return{ok:!0,value:o,type:Ym(o)}}catch(o){return{ok:!1,reason:o instanceof Error?o.message:String(o)}}}function Ad(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}=ts(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 Td(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 Dd(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=Id(s,n);o[r]=a.ok?a.value:s}return o}function Xm(e,t){const n=Ad(e,t),o=Td(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]=Dd(s.tree,o):r[s.scope]=s.tree;return r}function Nd(e){const{raw:t,spec:n,evaluateComputed:o}=e;return u.useMemo(()=>{const r=Ad(t,n),s=Td(t,n);if(o){const a=s.findIndex(l=>l.scope==="_computed");if(a>=0){const l=Dd(s[a].tree,s);s[a]={scope:"_computed",tree:l}}}return ji({dataSources:r,states:s,spec:n??void 0})},[t,n,o])}function Jm(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}=ts(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=ji({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 zd(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 Md(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 rs(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 is(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 Zm(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:rs(a,t),source:is(a,n)}))}return r}function Ld(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 Qm(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:Rm(s,a,t)}))}return o}function Rm(e,t,n){const r=e?.meta?.editor_label;if(typeof r=="string"&&r.length>0)return Pd(r,n);const s=e?.title;return typeof s=="string"&&s.length>0?Pd(s,n):t}function Pd(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 Od=bo("ActionRecipeEngine"),ev={api:"apiCall",nav:"navigate",showToast:"toast",setLocalState:"setState"},tv=new Set(["comment"]);function wo(e){if(!e||typeof e!="object")return[];const t=[];for(const[n,o]of Object.entries(e)){if(tv.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 _r="...";function nv(e,t){return e.replace(/\{\{\s*([\w.]+)\s*\}\}/g,(n,o)=>{const r=t[o];return r==null?"":String(r)})}function ss(e,t){if(typeof e=="string"){const n=on(e);return n!==null?n in t?t[n]:void 0:e.includes("{{")?nv(e,t):e}if(Array.isArray(e))return e.map(n=>ss(n,t)).filter(n=>n!==void 0);if(e&&typeof e=="object"){const n={};for(const[o,r]of Object.entries(e)){if(o===_r&&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=ss(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 ov(e){const t=e.handler;if(typeof t!="string")return e;const n=ev[t];if(n)return Od.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&&Od.warn(`action recipe build placed "${r}" inside params for handler "${t}" — should be top-level (core handler rules)`)}return e}function xr(e,t){const n=ss(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&&Bd(e.build,n,o)}return ov(n)}function Bd(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;Bd(a,r[s],n)}}}function rv(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&&!iv(s.build,e))continue;const l=sv(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 iv(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 sv(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[_r],d=typeof l=="string"?on(l):null,c=new Set(Object.keys(r).filter(p=>p!==_r));for(const[p,f]of Object.entries(r))if(p!==_r){if(typeof f=="string"&&on(f)!==null){const y=on(f);p in a&&(n[y]=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,y]of Object.entries(a))c.has(f)||(p[f]=y);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=rv(e,t);return o?{kind:"preset",recipeId:o.recipeId,values:o.values,handler:n}:{kind:"advanced",handler:n}}function Wd(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=av(d);if(c!==""&&(s.push(c),s.length>=2))break}return s.length===0?r:`${r} (${s.join(", ")})`}function av(e){return typeof e=="string"?e:typeof e=="number"||typeof e=="boolean"?String(e):Array.isArray(e)?`[${e.length}]`:e&&typeof e=="object"?"{…}":""}function jd(e,t){const n={...e};return typeof t=="string"&&t.trim().length>0?n.if=t.trim():delete n.if,n}function as(e){const t=e?.if;return typeof t=="string"&&t.trim().length>0?t:null}const lv=/^\s*\$t:(custom\.[a-zA-Z0-9._-]+)\s*$/,dv=/^\s*\$t:([a-zA-Z0-9._-]+)\s*$/,cv=/\{\{.*?\}\}/;function Hd(e,t){const n=typeof e=="string"?e:"",o=lv.exec(n);if(o){const a=o[1],l=t?t(a):"";return{customKey:a,binding:!1,paramKey:!1,displayValue:l}}const r=mt(n);if(r&&r.key.startsWith("custom.")){const a=t?t(r.key):"";return{customKey:r.key,binding:!1,paramKey:!0,displayValue:a}}if(cv.test(n))return{customKey:null,binding:!0,paramKey:!1,displayValue:n};const s=dv.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 uv(){const{state:e}=Je(),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=>Hd(l,r),[r]),a=u.useCallback(async(l,d)=>{const c=Hd(l,r);if(c.binding)return{kind:"blocked"};if(c.customKey){if(d===c.displayValue)return{kind:"noop",customKey:c.customKey};const y=await yr(t,c.customKey,n,d);return y.kind==="error"?{kind:"error",message:y.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 ls(e,t,n,o,r,s,a,l,d,c){const p=c?Yi(o,c):null,f=!!(p&&p.keyifiable),y=d?d(o):o,g=f?p.chipValue:Xl(y),h=`p${f?p.bindings.length:cr(y).length}`,v=Math.max(0,Math.min(r,g.length)),b=Hl(g,v,h),x=ur(b).replace(/\{\{?p\d+\}?\}/g," ").replace(/\s+/g," ").trim(),k=x.length>0?x:b,w=await qn(e,t,n,k);if(w.kind==="error"||!w.resource)return{kind:"error",message:w.message};const _=w.resource.translation_key,C=An(b),E=w.resource.values??{},S={[n]:b};for(const z of Object.keys(E)){if(z===n)continue;let D=E[z]??"";for(const O of C)D=qi(D,O);S[z]=D}xo(e,_,S);const T=En(s,a,l);return{kind:"ok",text:`${f?Gl(`$t:${_}`,p):Yl(`$t:${_}`,y)}|${h}=${T}`,key:_}}async function wr(e,t,n,o,r,s,a){let l=mt(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=hb(l.params.map(h=>h.name)),c=En(r,s,a),p=`${n.trim()}|${d}=${c}`,f=await cn(e,l.key),y=jb(l.key)??{},g=new Set([...Object.keys(f?.values??{}),...Object.keys(y),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?Hl(v,o,d):qi(v,d)}return xo(e,l.key,m),{kind:"ok",text:p,paramName:d}}async function ko(e,t,n,o){return br(e,t,n,o),{kind:"ok"}}async function pv(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)}xo(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 Fd(e,t,n){return pv(e,t,o=>Ql(o,n))}function Kd(e,t){if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:e,locale:t}}))}catch{}}async function kr(e,t,n,o){const r=await Fd(e,t,n);return Kd(e,o),r}const fv=/^\s*\$t:(custom\.[a-zA-Z0-9._-]+)\s*$/;function gv(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 Vd(e){const t=e.text;if(typeof t!="string")return null;const n=fv.exec(t);if(n)return n[1];const o=mt(t);return o&&o.key.startsWith("custom.")?o.key:null}function ds(e){const t={},n=mt(typeof e=="string"?e:"");for(const o of n?.params??[])t[o.name]=Vt(o.expression);return t}function hv(e){return ds(typeof e.text=="string"?e.text:"")}function Ud({customKey:e,templateIdentifier:t,t:n,paramLabels:o,locales:r,onRemoveParam:s}){const a=r??ud(),l=Ft(),d=o??{},[c,p]=u.useState({status:"idle",values:{}}),[f,y]=u.useState(!1),[g,m]=u.useState(!1),[h,v]=u.useState(null),b=u.useRef({});u.useEffect(()=>{let $=!1;if(!e){p({status:"not_a_key",values:{}});return}return p({status:"loading",values:{}}),(async()=>{const A=await cn(t,e);if($)return;if(!A){p({status:"error",values:{}});return}const z={...A.values??{}};for(const D of Object.keys(z)){const O=It(e,D);O!==void 0&&(z[D]=O)}for(const D of a){const O=It(e,D);O!==void 0&&(z[D]=O)}b.current={...z},p({status:"loaded",id:A.id,lockVersion:A.lock_version,values:z})})(),()=>{$=!0}},[e,t]),u.useEffect(()=>{if(typeof window>"u"||!e)return;const $=A=>{const z=A.detail;z?.templateIdentifier&&z.templateIdentifier!==t||p(D=>{if(D.status!=="loaded")return D;let O=!1;const M={...D.values};for(const B of Object.keys(M)){const N=It(e,B);N!==void 0&&N!==M[B]&&(M[B]=N,O=!0)}return O?(b.current={...b.current,...M},{...D,values:M}):D})};return window.addEventListener(kt,$),()=>window.removeEventListener(kt,$)},[e,t]);const x=u.useCallback(($,A)=>{p(z=>{const D=z.values[$]??"",O={...z,values:{...z.values,[$]:A}};return e&&gv(D,A)&&(br(t,e,$,A),b.current={...b.current,[$]:A},l?.markDirty?.(),Kd(t,$)),O})},[e,t,l]),k=u.useCallback($=>{p(A=>{const z={};for(const[D,O]of Object.entries(A.values))z[D]=Ql(O,$);return b.current={...z},{...A,values:z}}),s?.($)},[s]),w=u.useMemo(()=>[...Object.values(c.values),...Object.values(b.current)].some(A=>An(A).length>0),[c.values]),_=u.useRef(null),C=u.useCallback(()=>{m(!0),_.current&&clearTimeout(_.current),_.current=setTimeout(()=>m(!1),1500)},[]);u.useEffect(()=>()=>{_.current&&clearTimeout(_.current)},[]);const E=u.useCallback(async()=>{if(m(!1),c.status!=="loaded"||c.id===void 0)return;const $=b.current;for(const[z,D]of Object.entries(c.values)){const O=$[z]??"";if(w){const M=An(O);if(M.length===0)continue;const B=An(D);if(!(M.length===B.length&&M.every((H,L)=>H===B[L]))){v(n("layout_editor.translation.placeholder_mismatch"));return}continue}if(Ui(O)&&!kb(O,D)){v(n("layout_editor.translation.token_mismatch"));return}}if(y(!0),v(null),w){xo(t,e??"",c.values),b.current={...c.values},l?.markDirty?.(),Et({op:"translation_field_update",translationKey:e,changedLocales:Object.keys(c.values),timestamp:Date.now()}),await new Promise(z=>setTimeout(z,0)),y(!1),C();return}const A=`/api/admin/templates/${encodeURIComponent(t)}/custom-translations/${c.id}`;try{const z=await fetch(A,{method:"PUT",credentials:"same-origin",headers:je({"Content-Type":"application/json"}),body:JSON.stringify({values:c.values,expected_lock_version:c.lockVersion??0})}),D=await z.json().catch(()=>null);if(z.status===409){v(n("layout_editor.translation.conflict"));return}if(!z.ok){v(D?.message??n("layout_editor.translation.save_failed"));return}const O=typeof D?.data?.lock_version=="number"?D.data.lock_version:(c.lockVersion??0)+1;p(M=>({...M,lockVersion:O})),b.current={...c.values},await tn(t),Et({op:"translation_field_update",translationKey:e,changedLocales:Object.keys(c.values),timestamp:Date.now()}),C()}catch(z){v(z instanceof Error?z.message:n("layout_editor.translation.save_failed"))}finally{y(!1)}},[c,t,e,n]);if(c.status==="not_a_key"||!e)return i.jsx("div",{"data-testid":"g7le-translation-not-a-key",style:cs,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:cs,children:n("layout_editor.translation.loading")});if(c.status==="error")return i.jsx("div",{"data-testid":"g7le-translation-error",style:cs,children:n("layout_editor.translation.load_failed")});const S=new Set([...a,...Object.keys(c.values)]),T=Array.from(S);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:yv,children:[n("layout_editor.translation.key_label"),": ",i.jsx("code",{style:bv,children:e})]}),T.map($=>{const A=c.values[$]??"",z=A.trim().length===0;return i.jsxs("div",{className:"g7le-translation-row","data-testid":`g7le-translation-row-${$}`,style:mv,children:[i.jsxs("label",{htmlFor:`g7le-translation-input-${$}`,style:{fontSize:12,color:"#475569",minWidth:72,display:"inline-flex",alignItems:"center",gap:4},children:[Gn($,n),z&&i.jsx("span",{"data-testid":`g7le-translation-missing-${$}`,style:vv,children:n("layout_editor.translation.needs_translation")})]}),w?i.jsx("div",{style:{flex:1},"data-testid":`g7le-translation-chip-${$}`,children:i.jsx(mr,{value:A,onChange:D=>x($,D),t:n,paramLabels:d,testIdSuffix:$,onRemoveChip:s?k:void 0})}):i.jsx("input",{id:`g7le-translation-input-${$}`,type:"text","data-testid":`g7le-translation-input-${$}`,value:A,placeholder:z?n("layout_editor.translation.needs_translation"):"",onChange:D=>x($,D.currentTarget.value),onBlur:E,style:{flex:1,padding:"4px 8px",fontSize:13,border:"1px solid #cbd5e1",borderRadius:4,color:z?"#94a3b8":"#0f172a"}})]},$)}),i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[i.jsx("button",{type:"button","data-testid":"g7le-translation-save",disabled:f,onClick:E,style:_v,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 cs={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},yv={fontSize:12,color:"#475569"},bv={fontSize:11,background:"#f1f5f9",padding:"1px 4px",borderRadius:3,color:"#0f172a"},mv={display:"flex",alignItems:"center",gap:8},vv={fontSize:10,color:"#b45309",background:"#fef3c7",padding:"0 4px",borderRadius:3},_v={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),y=u.useCallback(()=>{const m=e.current,h=c.current;if(!m||!h)return;const v=m.getBoundingClientRect(),b=window.innerWidth,x=window.innerHeight,k=h.getBoundingClientRect(),w=Math.min(Math.max(k.width,s),a),_=k.height;let C=v.left;C+w+l>b&&(C=v.right-w),C=Math.min(Math.max(C,l),b-w-l);const E=x-v.bottom-l,S=v.top-l;let T,$;const A=r==="bottom",z=E>=Math.min(_,160),D=S>=Math.min(_,160);A&&z||A&&!D?(T=v.bottom+4,$=E):!A&&D||D?(T=v.top-4-Math.min(_,S),$=S):E>=S?(T=v.bottom+4,$=E):(T=l,$=S),f({left:C,top:T,maxHeight:Math.max($,120)})},[e,r,s,a,l]);if(u.useLayoutEffect(()=>{if(!t){f(null);return}y()},[t,y]),u.useEffect(()=>{if(!t)return;const m=()=>y();window.addEventListener("resize",m),window.addEventListener("scroll",m,!0);const h=b=>{const x=c.current,k=e.current,w=b.target;x?.contains(w)||k?.contains(w)||n()},v=b=>{b.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,y,n,e]),!t)return null;const g={...xv,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 xv={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 qd(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(()=>Fi(e,"scalar").map(h=>({...h,resolvedLabel:qd(t,h.labelKey,h.path||h.sourceId)})),[e,t]),y=u.useMemo(()=>Ki(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:Cv}),i.jsx("div",{style:$v,children:y.length===0?i.jsx("div",{style:Ev,children:t("layout_editor.inline_binding.no_results")}):y.map(m=>i.jsxs("button",{type:"button","data-testid":`g7le-inline-binding-candidate-${m.expression}`,onClick:()=>{n(m),l(!1),c("")},style:Iv,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:Av,children:[qd(t,m.groupLabelKey,m.sourceId)," · ",m.path||m.sourceId]})]}),i.jsx("span",{style:Tv,children:m.preview})]},m.expression))})]});return i.jsxs("div",{style:s?Sv:{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:wv,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:kv,children:g})]})}const wv={fontSize:13,lineHeight:1,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#334155",padding:"4px 8px",cursor:"pointer",textAlign:"center",whiteSpace:"nowrap"},kv={marginTop:4,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",padding:6},Sv={display:"inline-block"},Cv={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},$v={marginTop:4,maxHeight:200,overflowY:"auto",display:"flex",flexDirection:"column",gap:2},Ev={fontSize:11,color:"#94a3b8",padding:"8px 0",textAlign:"center"},Iv={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,border:"none",background:"transparent",cursor:"pointer",padding:"6px 8px",borderRadius:4,textAlign:"left"},Av={fontSize:10,color:"#94a3b8"},Tv={fontSize:10,color:"#64748b",fontFamily:"monospace",whiteSpace:"nowrap"},Dv=["$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 So(e,t,n,o){switch(e.kind){case"leaf":Yd(e.text,t,n,o);return;case"conditional":So(e.then,t,n,o),o.push({kind:"ellipsis",text:"⋯"});return;case"fallback":So(e.primary,t,n,o);return;case"concat":e.parts.forEach(r=>So(r,t,n,o));return;case"raw":default:o.push({kind:"text",text:e.source});return}}function Yd(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 us(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);So(l.node,t,n,o)}else Yd(a,t,n,o);return o}const s=un(e);return So(s.node,t,n,o),o}function Nv(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=Hv(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==="??"&&zv(r.primary)&&Mv(r.fallback))return{node:{kind:"leaf",text:t},decomposed:!1,original:t};const s=Zn(r,!0);return qv(o,s)?{node:r,decomposed:!0,original:t}:{node:{kind:"raw",source:o},decomposed:!1,original:t}}function Zn(e,t=!1){const n=Jd(e);return t?n:e.kind==="leaf"?e.text:`{{${n}}}`}function Co(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 ps(e){return Zn({kind:"fallback",op:"??",primary:{kind:"leaf",text:typeof e=="string"?e:""},fallback:{kind:"leaf",text:""}},!1)}function $o(e){switch(e.kind){case"leaf":return e.text;case"conditional":return $o(e.then);case"fallback":return $o(e.primary);case"concat":return e.parts.map($o).join("");case"raw":default:return e.kind==="raw"?`{{${e.source}}}`:""}}function uM(e){return e}function Sr(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)?$o(un(n).node):n;return""}return $o(un(e).node)}function zv(e){if(e.kind!=="leaf")return!1;const t=/^\{\{([\s\S]*)\}\}$/.exec(e.text.trim());return t?Qn(t[1].trim()):!1}function Mv(e){if(e.kind!=="leaf")return!1;const t=e.text.trim();return!(/\{\{/.test(t)||t.startsWith("$t:"))}function Cr(e){return`'${e.replace(/\\/g,"\\\\").replace(/'/g,"\\'")}'`}function Lv(e){const t=[];let n=0,o=0;const r=e.length;for(;on&&t.push(Cr(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 nEo(t,"concat")).join(" + ");case"fallback":return`${Eo(e.primary,"fallback")} ${e.op} ${Eo(e.fallback,"fallback")}`;case"conditional":return`${Ov(e.condition)} ? ${Eo(e.then,"conditional")} : ${Eo(e.else,"conditional")}`;default:return""}}function Eo(e,t){const n=Jd(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 Wv=["===","!==","??","||","&&","==","!=",">=","<="];function Zd(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:Rd(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"&&Dv.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 Hv(e){return new jv(e).parse()}const Fv=["===","!==","==","!=",">=","<=",">","<"];function Kv(e,t){const n=e.trim();if(n==="")return{kind:"raw",source:n};if(n===Xd)return{kind:"simple",left:"",op:"truthy",right:""};if(n.startsWith("!")){const s=n.slice(1).trim(),a=Qd(s);return Qn(a)?{kind:"simple",left:a,op:"falsy",right:""}:{kind:"raw",source:n}}const o=Vv(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)&&Uv(c)?{kind:"simple",left:d,op:a,right:c}:{kind:"raw",source:n}}const r=Qd(n);return Qn(r)?{kind:"simple",left:r,op:"truthy",right:""}:{kind:"raw",source:n}}function Vv(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 qv(e,t){try{return $r(e)===$r(t)}catch{return!1}}function $r(e){const t=Jn(e);return t!==null?$r(t):Zd(e).map(o=>{if(o.kind==="string")return`S:${Rd(o.value)}`;if(o.kind==="binding"){const r=/^\{\{([\s\S]*)\}\}$/.exec(o.value);return`B:${r?$r(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?Yv:Gv})}const Gv={height:0,margin:0,transition:"height 80ms"},Yv={height:3,margin:"1px 0",borderRadius:2,background:"#2563eb",boxShadow:"0 0 0 1px #93c5fd"};function fs(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]),y=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:y,isDropTarget:g}}const Xv={text:"",expression:"{{false ? '' : ''}}",fallback:"{{'' ?? ''}}",data:""};function ec(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 gs({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 k=ec(e,a.current);return a.current=k.nextSeq,k.segs},[]),[c,p]=u.useState(d),[f,y]=u.useState(!1);if(e!==l.current){l.current=e;const k=c.map(w=>w.value).join("");if(e!==k){const w=ec(e,a.current);a.current=w.nextSeq,p(w.segs)}}const g=u.useCallback(k=>{p(k);const w=k.map(_=>_.value).join("");l.current=w,t(w)},[t]),m=u.useCallback((k,w)=>{g(c.map(_=>_.id===k?{..._,value:w??""}:_))},[c,g]),h=u.useCallback(k=>{const w=c.filter(_=>_.id!==k);g(w.length>0?w:[{id:a.current++,kind:"text",value:""}])},[c,g]),v=u.useCallback(k=>{g([...c,{id:a.current++,kind:k,value:Xv[k]}])},[c,g]),b=u.useCallback((k,w)=>{if(k===w||k<0||w<0||k>=c.length||w>=c.length)return;const _=c.slice(),[C]=_.splice(k,1);_.splice(w,0,C),g(_)},[c,g]),x=fs({length:c.length,onMove:b});return i.jsxs("div",{"data-testid":r,style:Qv,children:[i.jsx("div",{style:Rv,children:n("layout_editor.value_tree.segmented_hint")}),c.map((k,w)=>i.jsxs(u.Fragment,{children:[i.jsx(Rn,{active:x.isDropTarget(w),testid:`${r}-dropline-${w}`}),i.jsx(Zv,{seg:k,index:w,t:n,candidates:o,testidPrefix:r,renderLeafInput:s,onValueChange:_=>m(k.id,_),onRemove:()=>h(k.id),dragging:x.dragIndex===w,onDragStartCard:()=>x.onDragStart(w),onDragEndCard:x.onDragEnd,onDragOverCard:_=>x.onDragOverItem(w,_),onDropCard:x.onDrop})]},k.id)),i.jsx(Rn,{active:x.isDropTarget(c.length),testid:`${r}-dropline-end`}),i.jsxs("div",{style:i_,"data-testid":`${r}-add-row`,children:[i.jsxs("button",{type:"button","data-testid":`${r}-add-text`,onClick:()=>v("text"),style:Er,children:["+ ",n("layout_editor.value_tree.segment.text")]}),i.jsxs("button",{type:"button","data-testid":`${r}-add-expression`,onClick:()=>v("expression"),style:Er,children:["+ ",n("layout_editor.value_tree.segment.expression")]}),i.jsxs("button",{type:"button","data-testid":`${r}-add-fallback`,onClick:()=>v("fallback"),style:Er,children:["+ ",n("layout_editor.value_tree.segment.fallback")]}),i.jsxs("button",{type:"button","data-testid":`${r}-add-data`,onClick:()=>v("data"),style:Er,children:["+ ",n("layout_editor.value_tree.segment.data")]})]}),i.jsxs("div",{style:l_,children:[i.jsxs("button",{type:"button","data-testid":`${r}-source-toggle`,"aria-expanded":f,onClick:()=>y(k=>!k),style:d_,children:[""," ",n("layout_editor.value_tree.show_source")," ",f?"▴":"▾"]}),f&&i.jsx("code",{"data-testid":`${r}-source-code`,style:c_,children:c.map(k=>k.value).join("")})]})]})}function Jv({t:e,candidates:t,onPick:n,testidPrefix:o}){return!t||t.length===0?i.jsx("div",{"data-testid":`${o}-data-empty`,style:a_,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:s_,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 Zv({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:y}){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?{...tc,opacity:.5}:tc,onDragOver:m=>{m.preventDefault();const h=m.currentTarget.getBoundingClientRect();f(m.clientY{m.preventDefault(),y()},children:[i.jsxs("div",{style:e_,children:[i.jsx("span",{"data-testid":`${r}-drag-${t}`,style:o_,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:t_,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:r_,children:"✕"})]}),i.jsx("div",{style:n_,children:e.kind==="data"&&e.value.trim()===""?i.jsx(Jv,{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(vt,{value:e.value,onChange:a,t:n,candidates:o,testidPrefix:`${r}-field-${t}`,enableExpressionTree:!0,expressionSourceToggle:!1})})]})}const Qv={display:"flex",flexDirection:"column",gap:6,width:"100%",minWidth:0},Rv={fontSize:11,color:"#64748b"},tc={display:"flex",flexDirection:"column",gap:4,padding:"6px 8px",border:"1px solid #e2e8f0",borderLeft:"3px solid #6366f1",borderRadius:6,background:"#f8fafc",minWidth:0},e_={display:"flex",alignItems:"center",gap:6,minWidth:0},t_={fontSize:10,fontWeight:600,color:"#6366f1",flex:1,minWidth:0},n_={minWidth:0},o_={color:"#94a3b8",cursor:"grab",fontSize:14,userSelect:"none"},r_={border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12,padding:2,flexShrink:0},i_={display:"flex",flexWrap:"wrap",gap:6,marginTop:2},s_={fontSize:11,color:"#64748b",marginBottom:2},a_={fontSize:11,color:"#94a3b8",padding:"4px 0"},Er={padding:"4px 10px",fontSize:11,border:"1px dashed #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},l_={display:"flex",flexDirection:"column",gap:4,marginTop:2},d_={alignSelf:"flex-start",padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",fontFamily:"monospace"},c_={fontSize:11,background:"#0f172a",color:"#e2e8f0",padding:"6px 8px",borderRadius:4,wordBreak:"break-all",fontFamily:"monospace"},u_=[{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 nc({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:rc,children:[f,i.jsxs("div",{style:D_,children:[i.jsxs("button",{type:"button","data-testid":`${r}-source-toggle`,"aria-expanded":d,onClick:()=>c(y=>!y),style:N_,children:[""," ",n("layout_editor.value_tree.show_source")," ",d?"▴":"▾"]}),d&&i.jsx("code",{"data-testid":`${r}-source-code`,style:z_,children:Zn(e,!1)})]})]}):i.jsx("div",{"data-testid":r,style:rc,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(gs,{value:e.text,onChange:l=>t({kind:"leaf",text:l}),t:n,candidates:o,testidPrefix:`${r}-leaf`,renderLeafInput:a});case"conditional":return i.jsx(p_,{node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a});case"fallback":return i.jsx(f_,{node:e,onChange:t,t:n,candidates:o,testidPrefix:r,depth:s,renderLeafInput:a});case"concat":return i.jsx(h_,{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:M_,children:[i.jsx("code",{style:ac,children:e.source??""}),i.jsxs("span",{style:lc,children:["🔒 ",n("layout_editor.value_tree.raw_code_only")]})]})}}function p_({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:hs(s),children:[i.jsx(y_,{condition:e.condition,onChange:l,t:n,candidates:o,testidPrefix:r}),i.jsx(Ir,{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(Ir,{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 f_({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:hs(s),children:[i.jsx(Ir,{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(Ir,{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 g_={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 h_({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,g_[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]),y=fs({length:e.parts.length,onMove:f});return i.jsxs("div",{"data-testid":`${r}-concat`,style:hs(s),children:[i.jsx("div",{style:C_,children:n("layout_editor.value_tree.concat.hint")}),e.parts.map((g,m)=>i.jsxs(u.Fragment,{children:[i.jsx(Rn,{active:y.isDropTarget(m),testid:`${r}-part-dropline-${m}`}),i.jsxs("div",{"data-testid":`${r}-part-card-${m}`,style:y.dragIndex===m?{...sc,opacity:.5}:sc,onDragOver:h=>{h.preventDefault();const v=h.currentTarget.getBoundingClientRect();y.onDragOverItem(m,h.clientY{h.preventDefault(),y.onDrop()},children:[i.jsxs("div",{style:$_,children:[i.jsx("span",{"data-testid":`${r}-part-handle-${m}`,style:A_,draggable:!0,onDragStart:()=>y.onDragStart(m),onDragEnd:y.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:E_,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:T_,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:y.isDropTarget(e.parts.length),testid:`${r}-part-dropline-end`}),i.jsxs("div",{style:I_,"data-testid":`${r}-part-add-row`,children:[i.jsxs("button",{type:"button","data-testid":`${r}-part-add-text`,onClick:()=>p("text"),style:Ar,children:["+ ",n("layout_editor.value_tree.segment.text")]}),i.jsxs("button",{type:"button","data-testid":`${r}-part-add-expression`,onClick:()=>p("expression"),style:Ar,children:["+ ",n("layout_editor.value_tree.segment.expression")]}),i.jsxs("button",{type:"button","data-testid":`${r}-part-add-fallback`,onClick:()=>p("fallback"),style:Ar,children:["+ ",n("layout_editor.value_tree.segment.fallback")]}),i.jsxs("button",{type:"button","data-testid":`${r}-part-add-data`,onClick:()=>p("data"),style:Ar,children:["+ ",n("layout_editor.value_tree.segment.data")]})]})]})}function y_({condition:e,onChange:t,t:n,candidates:o,testidPrefix:r}){if(e.kind==="raw")return i.jsxs("div",{"data-testid":`${r}-cond-raw`,style:x_,children:[i.jsx("span",{style:ic,children:n("layout_editor.value_tree.cond.label")}),i.jsx("code",{style:ac,children:e.source}),i.jsxs("span",{style:lc,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:__,children:[i.jsx("span",{style:ic,children:n("layout_editor.value_tree.cond.label")}),i.jsx(oc,{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:S_,children:u_.map(l=>i.jsx("option",{value:l.value,children:n(l.labelKey)},l.value))}),a&&i.jsx(oc,{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 oc({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=(y,g)=>{const m=En(y,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:w_,children:[i.jsx("input",{type:"text","data-testid":e,value:c,onChange:y=>d(y.target.value),onBlur:p,onKeyDown:y=>{y.key==="Enter"&&(y.preventDefault(),p())},placeholder:o,style:k_}),r&&r.length>0&&s&&i.jsx($t,{candidates:r,t:s,onSelect:y=>f(y.sourceId,y.path),testIdSuffix:`${e}-data`,floating:!0})]})}function Ir({label:e,testid:t,children:n}){return i.jsxs("div",{"data-testid":t,style:b_,children:[i.jsx("span",{style:m_,children:e}),i.jsx("div",{style:v_,children:n})]})}const rc={display:"flex",flexDirection:"column",gap:6,width:"100%",minWidth:0},hs=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}),b_={display:"flex",flexDirection:"column",gap:3,minWidth:0},m_={fontSize:11,fontWeight:600,color:"#475569"},v_={paddingLeft:8,minWidth:0},__={display:"flex",flexWrap:"wrap",gap:4,alignItems:"center",minWidth:0},x_={display:"flex",flexWrap:"wrap",gap:4,alignItems:"center",minWidth:0},ic={fontSize:11,fontWeight:600,color:"#0f172a",whiteSpace:"nowrap"},w_={display:"inline-flex",alignItems:"flex-start",gap:2,flex:"1 1 80px",minWidth:60},k_={flex:"1 1 80px",minWidth:60,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},S_={padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff"},C_={fontSize:11,color:"#94a3b8"},sc={display:"flex",flexDirection:"column",gap:4,padding:"6px 8px",border:"1px solid #e2e8f0",borderLeft:"3px solid #6366f1",borderRadius:6,background:"#fff",minWidth:0},$_={display:"flex",alignItems:"center",gap:6,minWidth:0},E_={fontSize:10,fontWeight:600,color:"#6366f1",flex:1,minWidth:0},I_={display:"flex",flexWrap:"wrap",gap:6,marginTop:2},A_={color:"#94a3b8",cursor:"grab",fontSize:14,userSelect:"none"},T_={border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12,padding:2,flexShrink:0},Ar={padding:"4px 10px",fontSize:11,border:"1px dashed #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},D_={display:"flex",flexDirection:"column",gap:4,marginTop:2},N_={alignSelf:"flex-start",padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",fontFamily:"monospace"},z_={fontSize:11,background:"#0f172a",color:"#e2e8f0",padding:"6px 8px",borderRadius:4,wordBreak:"break-all",fontFamily:"monospace"},M_={display:"flex",flexDirection:"column",gap:2,minWidth:0},ac={fontSize:11,background:"#f1f5f9",padding:"3px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all",fontFamily:"monospace"},lc={fontSize:10,color:"#64748b"};function vt({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:y,classify:g,translate:m}=uv(),[h,v]=u.useState(null),[b,x]=u.useState(!1),[k,w]=u.useState(!1),[_,C]=u.useState(!1),[E,S]=u.useState(!1),[T,$]=u.useState(!1),[,A]=u.useState(0);u.useEffect(()=>{if(typeof window>"u")return;const N=H=>{const L=H.detail;L?.templateIdentifier&&L.templateIdentifier!==f||A(I=>I+1)};return window.addEventListener(kt,N),()=>window.removeEventListener(kt,N)},[f]);const z=g(e);u.useEffect(()=>{v(null),$(!1)},[p,e]);const D=h!==null?h:z.displayValue,O=u.useCallback(async()=>{if(h!==null){if(h===z.displayValue){v(null);return}x(!0);try{const N=await y(e,h);N.kind==="created"&&N.token?(t(N.token),Et({op:"prop_i18n_create_key",sourceState:"plain_text",translationKey:N.customKey,toLocale:p,valueLength:h.length,timestamp:Date.now()})):N.kind==="updated"&&Et({op:"prop_i18n_update_value",sourceState:"custom_key",translationKey:N.customKey,toLocale:p,valueLength:h.length,timestamp:Date.now()})}finally{x(!1),v(null)}}},[h,z.displayValue,y,e,t,p]),M=u.useCallback(N=>{typeof e=="string"&&(t(mo(e,N)),z.customKey&&kr(f,z.customKey,N,p))},[e,t,z.customKey,f,p]);if(z.binding){if(l&&typeof e=="string"){const N=Gd(e),H=un(e),L=!N&&Kt(e)!==null,I=(N||H.decomposed)&&!L;if(I&&d&&!_)return i.jsx(O_,{value:e,t:n,translate:m,onEdit:()=>C(!0),testidPrefix:`${r}-preview`});const F=I&&(d||N)?i.jsx(gs,{value:e,onChange:G=>t(G),t:n,candidates:a,testidPrefix:`${r}-seg`}):H.decomposed?i.jsx(nc,{node:H.node,onChange:G=>t(Zn(G,!1)),t:n,candidates:a,testidPrefix:`${r}-tree`,showSourceToggle:c}):null;if(F){if(!d)return F;const G=Sr(e),V=G?us(G,Y=>{const Z=m(Y);return Z&&Z!==Y&&!Z.startsWith("$t:")?Z:""},Y=>Vt(Y)):[];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:()=>S(!0),style:V_,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:()=>C(!1),style:uc,title:n("layout_editor.value_tree.collapse"),"aria-label":n("layout_editor.value_tree.collapse"),children:["▴ ",n("layout_editor.value_tree.collapse")]})]}),E&&i.jsxs("div",{"data-testid":`${r}-to-plain-confirm`,style:U_,children:[i.jsx("p",{style:q_,children:n("layout_editor.value_tree.to_plain_lead")}),i.jsx("div",{style:G_,children:V.length===0?i.jsx("span",{style:{color:"#94a3b8"},children:n("layout_editor.prop_i18n.placeholder")}):V.map((Y,Z)=>Y.kind==="chip"?i.jsxs("span",{style:dc,children:["🔗 ",Y.text]},Z):i.jsx("span",{style:Y.kind==="ellipsis"?cc:void 0,children:Y.text},Z))}),i.jsxs("p",{style:Y_,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:()=>S(!1),style:uc,children:n("layout_editor.value_tree.to_plain_cancel")}),i.jsx("button",{type:"button","data-testid":`${r}-to-plain-confirm-ok`,onClick:()=>{S(!1),C(!1),t(Sr(e)||void 0)},style:X_,children:n("layout_editor.value_tree.to_plain_ok")})]})]}),F]})}}return l&&typeof e=="string"&&a&&a.length>0&&Kt(e)!==null?i.jsx(B_,{value:e,onChange:t,t:n,candidates:a,testidPrefix:`${r}-data`}):i.jsxs("div",{"data-testid":`${r}-binding`,style:tx,children:[i.jsx("code",{style:nx,children:typeof e=="string"?e:""}),i.jsxs("span",{style:ox,children:["🔗 ",n("layout_editor.prop_i18n.bound_code_only")]})]})}if(!T&&typeof e=="string"&&Ul(e)){const N=ql(e);return i.jsxs("div",{"data-testid":`${r}-settings-ref`,style:Q_,children:[i.jsx("div",{"data-testid":`${r}-settings-ref-chips`,style:R_,children:N.map((H,L)=>H.kind==="chip"?i.jsxs("span",{style:ex,children:["🔗 ",H.label]},L):i.jsx("span",{children:H.label},L))}),i.jsxs("button",{type:"button","data-testid":`${r}-settings-ref-edit`,onClick:()=>$(!0),style:pc,title:n("layout_editor.value_tree.edit"),"aria-label":n("layout_editor.value_tree.edit"),children:["✎ ",n("layout_editor.value_tree.edit")]})]})}const B=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":k,onClick:()=>w(N=>!N),style:pc,children:["🌐 ",z.customKey?k?"⌃":"⌄":"+"]});return i.jsxs("div",{"data-testid":r,style:{display:"flex",flexDirection:"column",gap:4,width:"100%"},children:[i.jsx("div",{style:J_,children:z.paramKey&&z.customKey?i.jsx(L_,{customKey:z.customKey,value:typeof e=="string"?e:"",onChange:t,t:n,candidates:a,testidPrefix:r,showExprButton:l&&d,onToExpression:()=>{C(!0),t(Co(typeof e=="string"?e:""))},langToggle:B}):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:N=>v(N.target.value),onBlur:()=>{O(),T&&$(!1)},disabled:b,style:Z_}),a&&a.length>0&&i.jsx(P_,{value:typeof e=="string"?e:"",customKey:z.customKey,onChange:t,t:n,candidates:a,testidPrefix:r}),l&&d&&i.jsx("button",{type:"button","data-testid":`${r}-to-expr`,onClick:()=>{C(!0),t(Co(typeof e=="string"?e:""))},title:n("layout_editor.value_tree.to_expression"),"aria-label":n("layout_editor.value_tree.to_expression"),style:Io,children:"ƒx"}),B]})}),k&&(z.customKey?i.jsx(Ud,{customKey:z.customKey,templateIdentifier:f,t:n,paramLabels:ds(e),locales:s,onRemoveParam:M},z.customKey):i.jsx("div",{"data-testid":`${r}-expand-hint`,style:rx,children:n("layout_editor.prop_i18n.create_first")}))]})}function L_({customKey:e,value:t,onChange:n,t:o,candidates:r,testidPrefix:s,showExprButton:a=!1,onToExpression:l,langToggle:d}){const{state:c}=Je(),p=c.templateIdentifier,f=c.locale,y=Ft(),[g,m]=u.useState(null),h=u.useRef(""),v=u.useRef(null),b=u.useRef(null),x=u.useRef(null),[k,w]=u.useState(null),[_,C]=u.useState(!1),E=ds(t),S=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 O=It(e,f);if(O!==void 0){D||(h.current=O,m(O));return}const M=await cn(p,e);if(D)return;const B=M?.values?.[f]??"";h.current=B,m(B)})(),()=>{D=!0}},[e,p,f]),u.useEffect(()=>{if(typeof window>"u")return;const D=O=>{const M=O.detail;if(M?.templateIdentifier&&M.templateIdentifier!==p)return;const B=It(e,f);B!==void 0&&B!==g&&(h.current=B,m(B))};return window.addEventListener(kt,D),()=>window.removeEventListener(kt,D)},[e,p,f,g]);const T=u.useCallback(D=>{m(D),ko(p,e,f,D).then(()=>{y?.markDirty?.()})},[p,e,f,y]),$=u.useCallback(D=>{n(mo(t,D)),kr(p,e,D,f).then(()=>{S(),y?.markDirty?.()})},[t,n,p,e,f,S,y]),A=u.useCallback(async D=>{if(!(k===null||_)){C(!0);try{g!==null&&g!==h.current&&(await ko(p,e,f,g),h.current=g);const O=await wr(p,f,t,k,D.sourceId,D.path,"scalar");O.kind==="ok"&&(n(O.text),await S(),y?.markDirty?.())}finally{C(!1),w(null)}}},[k,_,g,t,p,e,f,n,S,y]),z=!!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(mr,{value:g,onChange:T,t:o,paramLabels:E,testIdSuffix:`${s}-field`,onRequestInsert:z?D=>w(D):void 0,onRemoveChip:$,hideInsertButton:!0,caretRef:x})}),z&&i.jsx("button",{ref:b,type:"button","data-testid":`${s}-plus-data-btn`,onClick:()=>w(x.current?x.current():g?.length??0),title:o("layout_editor.inline_binding.insert_data"),"aria-label":o("layout_editor.inline_binding.insert_data"),style:Io,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:Io,children:"ƒx"}),d,z&&i.jsx(Xn,{anchorRef:b,open:k!==null,onClose:()=>w(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 P_({value:e,customKey:t,onChange:n,t:o,candidates:r,testidPrefix:s}){const{state:a}=Je(),l=a.templateIdentifier,d=a.selectedRoute?.layoutName??null,c=a.locale,p=Ft(),[f,y]=u.useState(!1),[g,m]=u.useState(!1),h=u.useRef(null),v=u.useCallback(k=>{const w=o(k);return w&&w!==k&&!w.startsWith("$t:")?w:""},[o]),b=u.useCallback(k=>k.replace(/\$t:[a-zA-Z0-9._-]+/g,w=>v(w.slice(3))).replace(/\s+/g," ").trim(),[v]),x=u.useCallback(async k=>{if(!g){m(!0);try{if(t){const w=await wr(l,c,e,Number.MAX_SAFE_INTEGER,k.sourceId,k.path,"scalar");w.kind==="ok"&&(n(w.text),p?.markDirty?.())}else{const w=await ls(l,d,c,e,e.length,k.sourceId,k.path,"scalar",b,_=>o(_));w.kind==="ok"&&(n(w.text),p?.markDirty?.())}}finally{m(!1),y(!1)}}},[g,t,l,d,c,e,n,p,o,b]);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:()=>y(k=>!k),title:o("layout_editor.inline_binding.insert_data"),"aria-label":o("layout_editor.inline_binding.insert_data"),style:Io,children:"+"}),i.jsx(Xn,{anchorRef:h,open:f,onClose:()=>y(!1),children:i.jsx($t,{candidates:r,t:o,onSelect:k=>void x(k),testIdSuffix:`${s}-plus-insert`,defaultOpen:!0,floating:!1})})]})}function O_({value:e,t,translate:n,onEdit:o,testidPrefix:r}){const s=us(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:H_,children:[i.jsx("div",{"data-testid":`${r}-text`,style:F_,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:dc,children:["🔗 ",a.text]},l):i.jsx("span",{style:a.kind==="ellipsis"?cc:void 0,children:a.text},l))}),i.jsxs("button",{type:"button","data-testid":`${r}-edit`,onClick:o,style:K_,title:t("layout_editor.value_tree.edit"),"aria-label":t("layout_editor.value_tree.edit"),children:["✎ ",t("layout_editor.value_tree.edit")]})]})}function B_({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:W_,children:[i.jsxs("span",{"data-testid":`${r}-chip`,style:j_,children:["🔗 ",d]}),i.jsx("button",{ref:l,type:"button","data-testid":`${r}-change`,onClick:()=>a(c=>!c),style:Io,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 W_={display:"flex",alignItems:"center",gap:6,width:"100%",minWidth:0,flexWrap:"wrap"},j_={fontSize:11,background:"#eef2ff",color:"#4338ca",padding:"3px 8px",borderRadius:12,wordBreak:"break-all"},H_={display:"flex",alignItems:"center",gap:8,width:"100%",minWidth:0},F_={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"},dc={fontSize:11,background:"#eef2ff",color:"#4338ca",padding:"1px 6px",borderRadius:10,whiteSpace:"nowrap"},cc={color:"#94a3b8"},K_={padding:"4px 10px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#2563eb",cursor:"pointer",whiteSpace:"nowrap",flexShrink:0},uc={padding:"3px 10px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},V_={padding:"3px 10px",fontSize:11,border:"1px solid #fca5a5",borderRadius:6,background:"#fef2f2",color:"#b91c1c",cursor:"pointer",whiteSpace:"nowrap"},U_={display:"flex",flexDirection:"column",gap:6,padding:10,border:"1px solid #fca5a5",borderRadius:8,background:"#fffbeb"},q_={margin:0,fontSize:12,color:"#334155"},G_={padding:"5px 8px",fontSize:12,color:"#0f172a",background:"#fff",border:"1px solid #e2e8f0",borderRadius:6,wordBreak:"break-all"},Y_={margin:0,fontSize:11,color:"#b45309"},X_={padding:"3px 12px",fontSize:11,border:"1px solid #dc2626",borderRadius:6,background:"#dc2626",color:"#fff",cursor:"pointer",whiteSpace:"nowrap"},J_={display:"flex",gap:4,alignItems:"center",width:"100%",minWidth:0},Z_={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:0,width:"100%"},pc={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},Io={padding:"4px 8px",fontSize:13,lineHeight:1,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},Q_={display:"flex",alignItems:"center",gap:6,width:"100%",minWidth:0,flexWrap:"wrap"},R_={flex:1,minWidth:0,display:"flex",flexWrap:"wrap",alignItems:"center",gap:4,fontSize:12,color:"#334155"},ex={fontSize:11,background:"#eef2ff",color:"#4338ca",padding:"2px 8px",borderRadius:12,whiteSpace:"nowrap"},tx={display:"flex",flexDirection:"column",gap:2,width:"100%"},nx={fontSize:11,background:"#f1f5f9",padding:"3px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all"},ox={fontSize:10,color:"#64748b"},rx={fontSize:11,color:"#94a3b8",padding:"6px 8px",border:"1px dashed #cbd5e1",borderRadius:6,background:"#f8fafc"};function ys({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))},y=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:ix,children:[i.jsxs("div",{style:sx,children:[r.map(g=>i.jsxs("span",{"data-testid":`g7le-tag-chip-${g}`,style:ax,children:[i.jsx("span",{style:lx,children:d(g)}),c(g)&&i.jsx("code",{"data-testid":`g7le-tag-chip-id-${g}`,style:dx,children:g}),i.jsx("button",{type:"button","aria-label":`remove ${g}`,"data-testid":`g7le-tag-remove-${g}`,onClick:()=>p(g),style:cx,children:"✕"})]},g)),i.jsx("button",{type:"button","data-testid":"g7le-tag-add",onClick:()=>l(g=>!g),disabled:y.length===0,style:ux,children:o("layout_editor.control.tag_add")})]}),a&&y.length>0&&i.jsx("div",{"data-testid":"g7le-tag-candidates",style:px,children:y.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:fx,children:[i.jsx("span",{style:gx,children:g.label}),m&&i.jsx("code",{"data-testid":`g7le-tag-candidate-id-${g.value}`,style:hx,children:g.value})]},g.value)})})]})}const ix={display:"flex",flexDirection:"column",gap:6},sx={display:"flex",flexWrap:"wrap",gap:4,alignItems:"center"},ax={display:"inline-flex",alignItems:"center",gap:4,padding:"2px 6px",fontSize:12,background:"#e0e7ff",color:"#1d4ed8",borderRadius:12},lx={fontSize:12},dx={fontSize:10,color:"#4f46e5",background:"#c7d2fe",borderRadius:4,padding:"0 4px",fontFamily:"monospace"},cx={border:"none",background:"transparent",color:"#1d4ed8",cursor:"pointer",fontSize:10,padding:0,lineHeight:1},ux={padding:"2px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:12,background:"#fff",cursor:"pointer",color:"#475569"},px={display:"flex",flexDirection:"column",maxHeight:180,overflowY:"auto",border:"1px solid #cbd5e1",borderRadius:6,background:"#fff"},fx={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"},gx={fontSize:12,color:"#0f172a"},hx={fontSize:10,color:"#64748b",fontFamily:"monospace"},fc=new Map;function Xe(e,t){fc.set(e,t)}function Tn(e){return e?fc.get(e)??null:null}function Tr(e,t){const o=e("meta",{})?.[t];return typeof o=="string"?o:""}function yx({getValue:e,patch:t,t:n,fieldT:o,spec:r,permissionCandidates:s,bindingCandidates:a}){const l=o??n,d=Tr(e,"title"),c=Tr(e,"description"),p=Tr(e,"icon"),f=Tr(e,"editor_label"),y=e("permissions",[]),g=u.useCallback((b,x)=>{const k={...e("meta",{})??{}};x===void 0||x===""?delete k[b]:k[b]=x,t("meta",k)},[e,t]),m=u.useCallback(b=>{const x=Array.isArray(b)?b:[];x.length===0?t("permissions",void 0):t("permissions",x)},[t]),h=Tn("icon-picker"),v=Ct(r,"icon-picker")??Ct(r,"icon")??(r?.controls?Object.values(r.controls).find(b=>b&&typeof b=="object"&&b.widget==="icon-picker")??null:null);return i.jsxs("div",{className:"g7le-meta-form","data-testid":"g7le-meta-form",style:mx,children:[i.jsx(Ao,{label:n("layout_editor.page_settings.meta.title"),children:i.jsx(vt,{value:d,onChange:b=>g("title",b),t:l,testidPrefix:"g7le-meta-title",candidates:a,enableExpressionTree:!0,expressionTreeCollapsible:!0})}),i.jsx(Ao,{label:n("layout_editor.page_settings.meta.description"),children:i.jsx(vt,{value:c,onChange:b=>g("description",b),t:l,testidPrefix:"g7le-meta-description",candidates:a,enableExpressionTree:!0,expressionTreeCollapsible:!0})}),i.jsx(Ao,{label:n("layout_editor.page_settings.meta.icon"),children:h?i.jsx(bx,{icon:p,t:n,onChange:b=>g("icon",typeof b=="string"?b: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:b=>g("icon",b.target.value),style:wx})}),i.jsx(Ao,{label:n("layout_editor.page_settings.meta.editor_label"),hint:n("layout_editor.page_settings.meta.editor_label_hint"),children:i.jsx(vt,{value:f,onChange:b=>g("editor_label",b),t:l,testidPrefix:"g7le-meta-editor-label",candidates:a,enableExpressionTree:!0,expressionTreeCollapsible:!0})}),i.jsx(Ao,{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(ys,{control:{widget:"tag-input"},value:y,onChange:m,t:n,candidates:s})})})]})}function Ao({label:e,hint:t,children:n}){return i.jsxs("div",{className:"g7le-meta-field",style:vx,children:[i.jsx("label",{style:_x,children:e}),n,t?i.jsxs("p",{style:xx,children:["ⓘ ",t]}):null]})}function bx({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 mx={display:"flex",flexDirection:"column",gap:16,minWidth:0},vx={display:"flex",flexDirection:"column",gap:6,minWidth:0},_x={fontSize:13,fontWeight:600,color:"#0f172a"},xx={margin:0,fontSize:11,color:"#94a3b8"},wx={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:0,width:"100%"};function Dr({checked:e,onChange:t,label:n,testid:o,ariaLabel:r,disabled:s=!1}){return i.jsxs("label",{style:{...Ex,...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:Ix(e,s),children:i.jsx("span",{style:Ax(e)})}),n!=null?i.jsx("span",{style:Tx(s),children:n}):null]})}function Nr({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 kx({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:Sx,children:[s,l?i.jsxs("button",{type:"button","data-testid":a?`${a}-revert`:void 0,onClick:n,title:r??o,"aria-label":o,style:$x,children:["↩ ",o]}):d?i.jsx("span",{"data-testid":a?`${a}-source`:void 0,title:r,style:Cx,children:t}):null]})}const Sx={position:"relative",minWidth:0,width:"100%"},Cx={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"},$x={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"},Ex={display:"inline-flex",alignItems:"center",gap:8,cursor:"pointer"},Ix=(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"}),Ax=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"}),Tx=e=>({fontSize:13,fontWeight:600,color:e?"#94a3b8":"#0f172a"}),Dx=/\$(?:core|module|plugin)_settings:[a-zA-Z0-9._:-]+/;function Nx(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 zx(e))s.kind==="text"?o(s.raw):r(s.raw,s.label,s.removable);return n||o(""),t}function zx(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=Dx.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 Mx(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 Lx(e,t,n){const o=Math.max(0,Math.min(t,e.length));return e.slice(0,o)+n+e.slice(o)}function Px(e,t){const n=e.indexOf(t);return n<0?e:e.slice(0,n)+e.slice(n+t.length)}function bs({value:e,onChange:t,t:n,candidates:o,onDone:r,testidPrefix:s="g7le-binding-chip-text",disabled:a=!1}){const l=u.useMemo(()=>Nx(e),[e]),d=u.useRef(null),c=!!o&&o.length>0,[p,f]=u.useState(null),[y,g]=u.useState(null),[m,h]=u.useState(null),[v,b]=u.useState(!1),x=u.useRef(0),k=u.useRef(null),w=u.useMemo(()=>l.map(L=>L.kind==="chip"?`c:${L.raw}`:"t").join("|"),[l]),_=u.useRef(null),C=u.useRef([]),E=u.useRef(!1);u.useLayoutEffect(()=>{const L=E.current;E.current=!1,!(!L&&_.current===w)&&(_.current=w,l.forEach((I,P)=>{if(I.kind!=="text")return;const F=C.current[P];F&&F.textContent!==(I.text??"")&&(F.textContent=I.text??"")}))},[w,l,e]);const S=u.useCallback(()=>{const L=d.current;if(!L)return e;const I=[];for(const P of Array.from(L.querySelectorAll("[data-seg]")))P.dataset.seg==="chip"?I.push(P.dataset.raw??""):I.push(P.textContent??"");return I.join("")},[e]),T=u.useCallback(()=>{a||t(S())},[a,t,S]),$=u.useRef(null),A=u.useRef(!1),z=(L,I)=>{if(!a){L.preventDefault(),L.stopPropagation(),$.current={raw:I,pointerId:L.pointerId},A.current=!1,f(I);try{L.currentTarget.setPointerCapture(L.pointerId)}catch{}}},D=L=>{const I=$.current;if(!I||L.pointerId!==I.pointerId)return;A.current=!0;const P=B(L.clientX,L.clientY);P&&(g({slotIdx:P.slotIdx,offset:P.offset}),h(Bx(d.current,P.slotIdx,P.offset)))},O=(L,I)=>{if(L.stopPropagation(),A.current){A.current=!1;return}E.current=!0,t(Px(e,I))},M=L=>{const I=$.current;if(!I||L.pointerId!==I.pointerId)return;try{L.currentTarget.releasePointerCapture(L.pointerId)}catch{}$.current=null,A.current&&typeof setTimeout=="function"&&setTimeout(()=>{A.current=!1},0);const P=B(L.clientX,L.clientY);if(f(null),g(null),h(null),!P)return;const F=d.current;if(!F)return;const V=Array.from(F.querySelectorAll("[data-seg]")).map(Z=>Z.dataset.seg==="chip"?{kind:"chip",raw:Z.dataset.raw??""}:{kind:"text",text:Z.textContent??""}),Y=Mx(V,I.raw,P.slotIdx,P.offset);Y!==e&&(E.current=!0,t(Y))},B=(L,I)=>{const P=d.current;if(!P)return null;const F=Array.from(P.querySelectorAll("[data-seg]")),G=P.ownerDocument,V=G.elementFromPoint(L,I),Y=V?.closest('[data-seg="text"]');if(Y)return{slotIdx:F.indexOf(Y),offset:Ox(G,Y,L,I)};const Z=V?.closest('[data-seg="chip"]');if(Z){const re=F.indexOf(Z),U=Z.getBoundingClientRect();if(L=0){const ee=F[re-1];return{slotIdx:re-1,offset:(ee.textContent??"").length}}if(re+1({s:re,i:U})).filter(re=>re.s.dataset.seg==="text").pop();return se?{slotIdx:se.i,offset:(se.s.textContent??"").length}:null},N=()=>{a||!c||(x.current=Wx(d.current,e.length),b(L=>!L))},H=L=>{const I=L.path?L.path.split(".").filter(Boolean):[],P=[L.sourceId,...I].join("?.");E.current=!0,t(Lx(e,x.current,`{{${P}}}`)),b(!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:jx,children:[l.map((L,I)=>L.kind==="chip"?i.jsxs("span",{"data-seg":"chip","data-raw":L.raw,"data-testid":`${s}-chip-${I}`,contentEditable:!1,onPointerDown:P=>z(P,L.raw??""),onPointerMove:D,onPointerUp:M,title:L.removable?n("layout_editor.value_tree.change_data"):n("layout_editor.prop_i18n.bound_code_only"),style:{...Vx,...p===L.raw?Ux:null,touchAction:"none"},children:[i.jsx("span",{"aria-hidden":"true",style:qx,children:"⠿"}),i.jsx("span",{"aria-hidden":"true",style:{marginRight:3},children:"🔗"}),i.jsx("span",{children:L.text}),L.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:P=>{P.stopPropagation(),P.preventDefault()},onClick:P=>O(P,L.raw??""),style:Gx,children:"✕"})]},`chip-${L.raw}-${I}`):i.jsx("span",{ref:P=>{C.current[I]=P},"data-seg":"text",contentEditable:!a,suppressContentEditableWarning:!0,onInput:T,"data-testid":`${s}-text-${I}`,style:{...Hx,...p?Fx:null,...y?.slotIdx===I?Kx: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:gc,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:k,type:"button","data-testid":`${s}-insert`,onClick:N,disabled:a,style:gc,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:k,open:v,onClose:()=>b(!1),children:i.jsx($t,{candidates:o,t:n,onSelect:H,testIdSuffix:`${s}-insert`,defaultOpen:!0,floating:!1})})]}),i.jsx("span",{style:Yx,children:n("layout_editor.translation.placeholder_locked")})]})]})}function Ox(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 Bx(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 y=p.getClientRects(),g=y.length>0?y[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 Wx(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 jx={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"},Hx={outline:"none",minWidth:8,minHeight:"1.2em",whiteSpace:"pre-wrap",color:"#0f172a",display:"inline-block",wordBreak:"break-all"},Fx={boxShadow:"inset 0 -2px 0 #93c5fd",background:"#eff6ff",borderRadius:2},Kx={background:"#dbeafe",boxShadow:"inset 0 -2px 0 #2563eb"},Vx={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"},Ux={opacity:.5,borderStyle:"solid",cursor:"grabbing"},qx={color:"#2563eb",opacity:.7,fontSize:11,marginRight:1,cursor:"grab"},Gx={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"},gc={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},Yx={fontSize:10,color:"#94a3b8"},Xx=ql;function ms(e){return _b(e)}function Ve({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),[y,g]=u.useState(!1),[m,h]=u.useState(!1),v=u.useCallback(E=>i.jsx(Ve,{value:E.value,onChange:S=>E.onChange(S),t:E.t,candidates:E.candidates,testidPrefix:E.testidPrefix,enableExpressionTree:!0}),[]),b=()=>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:E=>t(E.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"}})}),x=u.useCallback(E=>{const S=d?`${d} ${E.expression}`:E.expression;t(S)},[d,t]);if(!l||a)return i.jsxs("div",{"data-testid":s,style:pn,children:[b(),!a&&c&&i.jsx($t,{candidates:o,t:n,onSelect:x,testIdSuffix:`${s}-pick`})]});const k=Nv(d),w=Gd(d),_=Kt(d),C=E=>{const S=Sr(d),T=S?us(S,()=>"",$=>Vt($)):[];return i.jsxs(i.Fragment,{children:[i.jsx("div",{style:{display:"flex",justifyContent:"flex-start"},children:i.jsxs("button",{type:"button","data-testid":`${E}-to-plain`,onClick:()=>h(!0),style:Rx,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":`${E}-to-plain-confirm`,style:e0,children:[i.jsx("p",{style:t0,children:n("layout_editor.value_tree.to_plain_lead")}),i.jsx("div",{style:n0,children:T.length===0?i.jsx("span",{style:{color:"#94a3b8"},children:n("layout_editor.page_settings.seo.value_placeholder")}):T.map(($,A)=>$.kind==="chip"?i.jsxs("span",{style:vs,children:["🔗 ",$.text]},A):i.jsx("span",{style:$.kind==="ellipsis"?{color:"#94a3b8"}:void 0,children:$.text},A))}),i.jsxs("p",{style:o0,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":`${E}-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":`${E}-to-plain-confirm-ok`,onClick:()=>{h(!1),t(Sr(d)||"")},style:r0,children:n("layout_editor.value_tree.to_plain_ok")})]})]})]})};if(!p&&(k==="expression"||w)){if(w)return i.jsxs("div",{"data-testid":s,style:pn,children:[!a&&C(`${s}-seg`),i.jsx(gs,{value:d,onChange:S=>t(S),t:n,candidates:o,testidPrefix:`${s}-seg`,renderLeafInput:v})]});const E=un(d);return i.jsxs("div",{"data-testid":s,style:pn,children:[!a&&C(`${s}-tree`),i.jsx(nc,{node:E.node,onChange:S=>t(Zn(S,!1)),t:n,candidates:o,testidPrefix:`${s}-tree`,renderLeafInput:v})]})}if(_&&!p&&!y)return i.jsx(Jx,{value:d,onChange:t,t:n,candidates:o,testidPrefix:s,onEditRaw:()=>g(!0)});if(!p&&!y&&ms(d)){const E=Xx(d);return i.jsx("div",{"data-testid":s,style:pn,children:i.jsxs("div",{style:hc,children:[i.jsx("div",{"data-testid":`${s}-chips`,style:Zx,children:E.map((S,T)=>S.kind==="chip"?i.jsxs("span",{style:vs,children:["🔗 ",S.label]},T):i.jsx("span",{children:S.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 y&&ms(d)?i.jsxs("div",{"data-testid":s,style:pn,children:[i.jsx(bs,{value:d,onChange:t,t:n,candidates:o,disabled:a,onDone:()=>g(!1),testidPrefix:`${s}-chipedit`}),!a&&k!=="raw"&&i.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:[i.jsxs("button",{type:"button","data-testid":`${s}-to-expr`,onClick:()=>t(Co(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(ps(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")]})]}),k==="raw"&&i.jsxs("p",{"data-testid":`${s}-raw-hint`,style:_s,children:["ⓘ ",n("layout_editor.value_tree.raw_expression_hint")]})]}):!p&&ms(d)?i.jsxs("div",{"data-testid":s,style:pn,children:[i.jsx(bs,{value:d,onChange:t,t:n,candidates:o,disabled:a,onDone:()=>{g(!1),f(!1)},testidPrefix:`${s}-chipedit`}),!a&&k!=="raw"&&i.jsxs("div",{style:{display:"flex",gap:4,flexWrap:"wrap"},children:[i.jsxs("button",{type:"button","data-testid":`${s}-to-expr`,onClick:()=>t(Co(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(ps(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")]})]}),k==="raw"&&i.jsxs("p",{"data-testid":`${s}-raw-hint`,style:_s,children:["ⓘ ",n("layout_editor.value_tree.raw_expression_hint")]})]}):i.jsxs("div",{"data-testid":s,style:pn,children:[b(),i.jsxs("div",{style:Qx,children:[c&&i.jsx($t,{candidates:o,t:n,onSelect:x,testIdSuffix:`${s}-pick`}),k!=="raw"&&i.jsxs("div",{style:{display:"flex",gap:4},children:[i.jsxs("button",{type:"button","data-testid":`${s}-to-expr`,onClick:()=>t(Co(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(ps(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")]})]})]}),k==="raw"&&!p&&i.jsxs("p",{"data-testid":`${s}-raw-hint`,style:_s,children:["ⓘ ",n("layout_editor.value_tree.raw_expression_hint")]})]})}function Jx({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:hc,children:[i.jsxs("span",{"data-testid":`${r}-chip`,style:vs,children:["🔗 ",c]}),p&&i.jsx("button",{ref:d,type:"button","data-testid":`${r}-change`,onClick:()=>l(y=>!y),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:y=>{if(f){const h=[y.sourceId,...y.path?y.path.split(".").filter(Boolean):[]].join(".");t(`{{${f}(${h})}}`),l(!1);return}const g=y.path?y.path.split(".").filter(Boolean):[],m=[y.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},hc={display:"flex",alignItems:"center",gap:6,width:"100%",minWidth:0,flexWrap:"wrap"},Zx={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"},vs={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"},Qx={display:"flex",flexWrap:"wrap",alignItems:"center",gap:6},_s={margin:"2px 0 0",fontSize:11,color:"#94a3b8",lineHeight:1.4},Rx={padding:"3px 10px",fontSize:11,border:"1px solid #fca5a5",borderRadius:6,background:"#fef2f2",color:"#b91c1c",cursor:"pointer",whiteSpace:"nowrap"},e0={display:"flex",flexDirection:"column",gap:6,padding:10,border:"1px solid #fca5a5",borderRadius:8,background:"#fffbeb"},t0={margin:0,fontSize:12,color:"#334155"},n0={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"},o0={margin:0,fontSize:11,color:"#b45309"},r0={padding:"3px 12px",fontSize:11,border:"1px solid #dc2626",borderRadius:6,background:"#dc2626",color:"#fff",cursor:"pointer",whiteSpace:"nowrap"};let yc=0;function zr({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(k=>({id:yc++,k:typeof k[n]=="string"?k[n]:"",v:typeof k[o]=="string"?k[o]:""})),[]),[y,g]=u.useState(f),m=u.useCallback(k=>{g(k);const w=k.filter(_=>_.k.trim()!=="").map(_=>({[n]:_.k,[o]:_.v}));t(w)},[n,o,t]),h=u.useCallback(()=>{m([...y,{id:yc++,k:"",v:""}])},[y,m]),v=u.useCallback(k=>{m(y.filter(w=>w.id!==k))},[y,m]),b=u.useCallback((k,w)=>{m(y.map(_=>_.id===k?{..._,k:w}:_))},[y,m]),x=u.useCallback((k,w)=>{m(y.map(_=>_.id===k?{..._,v:w}:_))},[y,m]);return i.jsxs("div",{"data-testid":a,style:{display:"flex",flexDirection:"column",gap:6},children:[y.map(k=>i.jsxs("div",{"data-testid":`${a}-row-${k.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:k.k,onChange:w=>b(k.id,w),testid:`${a}-key-${k.id}`,placeholder:l??r(`layout_editor.page_settings.seo.extra_${n}`)})}):i.jsx("input",{type:"text","data-testid":`${a}-key-${k.id}`,value:k.k,placeholder:l??r(`layout_editor.page_settings.seo.extra_${n}`),onChange:w=>b(k.id,w.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(Ve,{value:k.v,onChange:w=>x(k.id,w),t:r,candidates:s,placeholder:d??r("layout_editor.page_settings.seo.extra_content"),testidPrefix:`${a}-value-${k.id}`})})]}),i.jsx("button",{type:"button","data-testid":`${a}-remove-${k.id}`,onClick:()=>v(k.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:"✕"})]},k.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 i0=["website","article","product","profile"],s0=["summary","summary_large_image","app","player"];function a0(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 bc(e){const t={};for(const n of e??[])t[n.key]=n;return t}function mc(e,t){return!!e&&t&&typeof e.sourceExpr=="string"&&e.sourceExpr!==""&&!e.overriddenByLayout&&!e.lockedByFilter}function vc({label:e,sourceExpr:t,onReplace:n,t:o,testid:r}){return i.jsxs("div",{"data-testid":r,style:b0,children:[i.jsxs("span",{"data-testid":`${r}-chip`,style:m0,title:t,children:["🔗 ",e||t]}),i.jsx("span",{"data-testid":`${r}-badge`,style:v0,children:o("layout_editor.page_settings.seo.auto_chip_source")}),i.jsx("button",{type:"button","data-testid":`${r}-replace`,onClick:n,style:_0,children:o("layout_editor.page_settings.seo.auto_chip_replace")})]})}function l0({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:{},[y,g]=u.useState(p.image_height!=null||p.image_type!=null||p.image_secure_url!=null),m=bc(r),h=bc(s),v=u.useCallback((T,$)=>{const A={...p};$===void 0||$===""||$===null?delete A[T]:A[T]=$,n(A)},[p,n]),b=u.useCallback((T,$)=>{const A={...f};$===void 0||$===""||$===null?delete A[T]:A[T]=$,o(A)},[f,o]),x=(T,$,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-${$}`,style:g0,children:["🔒 ",d("layout_editor.page_settings.seo.og_locked")]})}),k=T=>{if(!T||!a||T.lockedByFilter||T.overriddenByLayout)return;const $=a0(T.source);return $?d($):void 0},w=(T,$)=>T&&a?T.overriddenByLayout===!0:$!=="",_=(T,$,A,z,D,O)=>{const M=O[$],B=!!M?.lockedByFilter,N=typeof z[$]=="string"?z[$]:"";return i.jsxs("div",{"data-testid":`${T}-${$}`,style:Dn,children:[i.jsx("label",{style:to,children:d(A)}),B?i.jsx("div",{"data-testid":`${T}-locked-value-${$}`,style:f0,children:String(M?.effectiveValue??"")}):mc(M,a)?i.jsx(vc,{label:M.label??"",sourceExpr:M.sourceExpr,onReplace:()=>D($,M.sourceExpr),t:d,testid:`${T}-${$}-auto`}):i.jsx(vt,{value:N,onChange:H=>D($,H??""),t:d,candidates:l,placeholder:a&&M?.effectiveValue!=null?String(M.effectiveValue):void 0,testidPrefix:`${T}-${$}-field`,enableExpressionTree:!0,expressionTreeCollapsible:!0}),x(T,$,M)]})},C=(T,$,A,z,D,O)=>{const M=O[$],B=!!M?.lockedByFilter,N=typeof z[$]=="string"?z[$]:"";return i.jsxs("div",{"data-testid":`${T}-${$}`,style:Dn,children:[i.jsx("label",{style:to,children:d(A)}),mc(M,a)?i.jsx(vc,{label:M.label??"",sourceExpr:M.sourceExpr,onReplace:()=>D($,M.sourceExpr),t:d,testid:`${T}-${$}-auto`}):i.jsx(Ve,{value:N,onChange:H=>D($,H),t:d,candidates:l,readOnly:B,placeholder:a&&M?.effectiveValue!=null?String(M.effectiveValue):void 0,testidPrefix:`${T}-${$}-field`}),x(T,$,M)]})},E=(T,$,A,z,D,O)=>{const M=O[$],B=!!M?.lockedByFilter,N=typeof z[$]=="string"?z[$]:"",H=w(M,N),L=H?N:"";return i.jsxs("div",{"data-testid":`${T}-${$}`,style:Dn,children:[i.jsx("label",{style:to,children:d(A)}),i.jsx(kx,{filled:H,sourceLabel:k(M),onRevert:B?void 0:()=>D($,void 0),revertLabel:d("layout_editor.page_settings.seo.revert_default"),testid:`${T}-${$}-overlay`,children:i.jsx("div",{"data-testid":`${T}-${$}-input`,style:{minWidth:0},children:i.jsx(Ve,{value:L,onChange:I=>D($,I),t:d,candidates:l,readOnly:B,placeholder:a&&M?.effectiveValue!=null?String(M.effectiveValue):void 0,testidPrefix:`${T}-${$}-chip`})})}),x(T,$,M)]})},S=(T,$,A,z,D,O,M)=>{const B=M[$],N=typeof D[$]=="string"?D[$]:"",H=w(B,N),L=k(B),I=H?N:"";return i.jsxs("div",{"data-testid":`${T}-${$}`,style:Dn,children:[i.jsxs("div",{style:c0,children:[i.jsx("label",{style:to,children:d(A)}),L?i.jsxs("span",{"data-testid":`${T}-${$}-source-inline`,style:u0,children:["· ",L]}):null]}),i.jsxs("select",{"data-testid":`${T}-${$}-select`,value:I,onChange:P=>O($,P.target.value),style:p0,children:[i.jsx("option",{value:"",children:a&&B?.effectiveValue!=null&&B.effectiveValue!==""?`${d("layout_editor.page_settings.seo.use_default")} (${String(B.effectiveValue)})`:d("layout_editor.page_settings.seo.use_default")}),z.map(P=>i.jsx("option",{value:P,children:P},P))]}),x(T,$,B)]})};return i.jsxs("div",{"data-testid":c,style:{display:"flex",flexDirection:"column",gap:12},children:[i.jsxs("div",{"data-testid":`${c}-og-section`,style:_c,children:[i.jsx("div",{style:xc,children:d("layout_editor.page_settings.seo.og_section")}),i.jsxs("p",{"data-testid":`${c}-intro`,style:d0,children:["ⓘ ",d("layout_editor.page_settings.seo.og_intro")]}),S(c,"type","layout_editor.page_settings.seo.og_type",i0,p,v,m),_(c,"title","layout_editor.page_settings.seo.og_title",p,v,m),_(c,"description","layout_editor.page_settings.seo.og_description",p,v,m),C(c,"image","layout_editor.page_settings.seo.og_image",p,v,m),_(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":y,onClick:()=>g(T=>!T),style:h0,children:[y?"▾":"▸"," ",d("layout_editor.page_settings.seo.og_image_adv")]}),y?i.jsxs("div",{"data-testid":`${c}-image-adv`,style:y0,children:[E(c,"image_height","layout_editor.page_settings.seo.og_image_height",p,v,m),E(c,"image_type","layout_editor.page_settings.seo.og_image_type",p,v,m),E(c,"image_secure_url","layout_editor.page_settings.seo.og_image_secure_url",p,v,m)]}):null]}),E(c,"site_name","layout_editor.page_settings.seo.og_site_name",p,v,m),E(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(zr,{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:_c,children:[i.jsx("div",{style:xc,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")}),S("g7le-seo-tw","card","layout_editor.page_settings.seo.tw_card",s0,f,b,h),E("g7le-seo-tw","site","layout_editor.page_settings.seo.tw_site",f,b,h),E("g7le-seo-tw","creator","layout_editor.page_settings.seo.tw_creator",f,b,h),_("g7le-seo-tw","title","layout_editor.page_settings.seo.tw_title",f,b,h),_("g7le-seo-tw","description","layout_editor.page_settings.seo.tw_description",f,b,h),C("g7le-seo-tw","image","layout_editor.page_settings.seo.tw_image",f,b,h),_("g7le-seo-tw","image_alt","layout_editor.page_settings.seo.tw_image_alt",f,b,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(zr,{value:Array.isArray(f.extra)?f.extra:[],onChange:T=>b("extra",T.length>0?T:void 0),keyField:"name",t:d,candidates:l,testidPrefix:"g7le-seo-tw-extra-editor"})]})]})]})}const _c={border:"1px solid #e2e8f0",borderRadius:8,padding:12,display:"flex",flexDirection:"column",gap:10},xc={fontSize:13,fontWeight:600,color:"#0f172a"},d0={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"},c0={display:"flex",alignItems:"center",gap:6},u0={fontSize:11,color:"#94a3b8"},p0={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",minWidth:0,boxSizing:"border-box"},f0={padding:"5px 8px",fontSize:12,border:"1px solid #e2e8f0",borderRadius:6,background:"#f1f5f9",color:"#64748b"},g0={fontSize:11,color:"#7c3aed"},h0={alignSelf:"flex-start",padding:"2px 0",fontSize:12,fontWeight:600,color:"#475569",background:"transparent",border:"none",cursor:"pointer"},y0={display:"flex",flexDirection:"column",gap:8,paddingLeft:14,marginTop:4,minWidth:0},b0={display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",minWidth:0},m0={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"},v0={fontSize:11,color:"#94a3b8"},_0={padding:"2px 8px",fontSize:11,color:"#475569",background:"#fff",border:"1px solid #cbd5e1",borderRadius:6,cursor:"pointer"},x0=["WebPage","WebSite","ItemList","BreadcrumbList","Organization","Person","CollectionPage","AboutPage","ContactPage","SearchAction"];function Mr(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 wc(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?Mr(e).map(D=>({id:xs++,...D})):[]),x=u.useCallback((D,O)=>{h(D),b(O),t(wc(D,O.map(M=>({key:M.key,value:M.value}))))},[t]),k=u.useCallback(()=>{const D=n,O=typeof D["@type"]=="string"?D["@type"]:m,M=Mr(D).map(B=>({id:xs++,key:B.key,value:o?.[B.key]?.expr??B.value}));return{type:O,rows:M}},[n,o,m]),w=u.useCallback(D=>{if(y(D),D){if(v.length===0&&n&&typeof n=="object"){const O=k();x(O.type,O.rows);return}t(wc(m,v.map(O=>({key:O.key,value:O.value}))))}else t(null)},[m,v,n,k,x,t]),_=u.useCallback(()=>{if(!n)return;const D=k();x(D.type,D.rows)},[n,k,x]),C=u.useCallback(()=>{x(m,[...v,{id:xs++,key:"",value:""}])},[m,v,x]),E=u.useCallback(D=>{x(m,v.filter(O=>O.id!==D))},[m,v,x]),S=u.useCallback((D,O)=>{x(m,v.map(M=>M.id===D?{...M,key:O}:M))},[m,v,x]),T=u.useCallback((D,O)=>{x(m,v.map(M=>M.id===D?{...M,value:O}:M))},[m,v,x]),$=u.useMemo(()=>n?Mr(n):[],[n]),A=u.useMemo(()=>s?Mr(s):[],[s]),z=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:kc,children:[i.jsxs("div",{style:Sc,children:[i.jsx("span",{style:k0,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:S0,children:d("layout_editor.page_settings.seo.sd_filter_locked")})]}),i.jsxs("div",{"data-testid":`${c}-locked`,style:C0,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(O=>i.jsxs("div",{"data-testid":`${c}-filtered-row-${O.key}`,style:Cc,children:[i.jsx("code",{style:$c,children:O.key}),i.jsx("span",{style:Ec,children:O.value})]},O.key))]})]})]})}return i.jsxs("div",{"data-testid":c,style:kc,children:[i.jsx("div",{style:Sc,children:i.jsx(Dr,{checked:f,onChange:w,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:$0,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]}),$.length===0?i.jsx("p",{style:{margin:0,fontSize:12,color:"#94a3b8"},children:d("layout_editor.page_settings.seo.sd_auto_empty")}):$.map(D=>{const O=o?.[D.key];return i.jsxs("div",{"data-testid":`${c}-auto-row-${D.key}`,style:Cc,children:[i.jsx("code",{style:$c,children:D.key}),O?i.jsxs("span",{"data-testid":`${c}-auto-chip-${D.key}`,style:E0,title:O.expr,children:["🔗 ",O.label||O.expr]}):i.jsx("span",{style:Ec,children:D.value})]},D.key)})]}),i.jsxs("p",{"data-testid":`${c}-replace-warn`,style:I0,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:A0,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=>x(D.target.value,v),style:T0}),i.jsx("datalist",{id:`${c}-type-options`,children:x0.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:D0,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:O=>S(D.id,O.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(Ve,{value:D.value,onChange:O=>T(D.id,O),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:()=>E(D.id),title:d("layout_editor.page_settings.seo.remove"),"aria-label":d("layout_editor.page_settings.seo.remove"),style:N0,children:"✕"})]},D.id))}),i.jsxs("div",{style:{marginTop:8,display:"flex",gap:8},children:[i.jsxs("button",{type:"button","data-testid":`${c}-add`,onClick:C,style:Ic,children:["+ ",d("layout_editor.page_settings.seo.sd_add_prop")]}),n?i.jsxs("button",{type:"button","data-testid":`${c}-seed-from-module`,onClick:_,style:Ic,children:["↩ ",d("layout_editor.page_settings.seo.sd_seed_from_module")]}):null]}),i.jsxs("p",{"data-testid":`${c}-empty-note`,style:z0,children:["ⓘ ",d("layout_editor.page_settings.seo.sd_empty_note"),z?i.jsxs("span",{style:{color:"#b45309"},children:[" ",d("layout_editor.page_settings.seo.sd_has_empty")]}):null]})]})]})}const kc={display:"flex",flexDirection:"column"},Sc={display:"flex",alignItems:"center",gap:8},k0={fontSize:14},S0={fontSize:11,padding:"2px 6px",borderRadius:4,background:"#f1f5f9",color:"#64748b"},C0={marginTop:8,border:"1px solid #fcd34d",borderRadius:8,padding:10,background:"#fffbeb"},$0={border:"1px solid #e2e8f0",borderRadius:8,padding:10,background:"#f8fafc"},Cc={display:"flex",gap:8,alignItems:"center",padding:"2px 0"},$c={fontSize:11,color:"#475569",background:"#fff",padding:"2px 6px",borderRadius:4,minWidth:120},Ec={fontSize:11,color:"#0f172a",fontFamily:"monospace",wordBreak:"break-all"},E0={display:"inline-flex",alignItems:"center",padding:"2px 8px",fontSize:11,color:"#1d4ed8",background:"#eff6ff",border:"1px solid #bfdbfe",borderRadius:6},I0={margin:"6px 0 0",fontSize:12,color:"#64748b"},A0={margin:"0 0 8px",fontSize:12,color:"#b45309",background:"#fffbeb",border:"1px solid #fcd34d",borderRadius:6,padding:"6px 8px"},T0={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",minWidth:0},D0={display:"flex",gap:6,alignItems:"flex-start",border:"1px solid #e2e8f0",borderRadius:8,padding:8},N0={padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"},Ic={padding:"5px 10px",fontSize:12,border:"1px dashed #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},z0={margin:"8px 0 0",fontSize:11,color:"#94a3b8"},Ac=new Set(["core_setting","setting","query","route"]);function M0({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(_=>Ac.has(_.source)):[],[d,o]),p=u.useMemo(()=>o?d.filter(_=>_.source==="data"):[],[d,o]);u.useMemo(()=>new Set(c.map(_=>_.name)),[c]);const f=u.useMemo(()=>new Set(p.map(_=>_.name)),[p]),y=u.useMemo(()=>{const _=new Set;for(const C of d)Ac.has(C.source)&&_.add(C.name);return _},[d]),g=u.useMemo(()=>Object.keys(l).filter(_=>!f.has(_)),[l,f]),m=u.useCallback((_,C)=>{const E={...l};C===void 0?delete E[_]:E[_]=C,t(E)},[l,t]),[h,v]=u.useState(""),b=h.trim()!==""&&y.has(h.trim()),x=h.trim()!==""&&Object.prototype.hasOwnProperty.call(l,h.trim()),k=h.trim()!==""&&!b&&!x&&!f.has(h.trim()),w=u.useCallback(()=>{const _=h.trim();_===""||y.has(_)||Object.prototype.hasOwnProperty.call(l,_)||(t({...l,[_]:""}),v(""))},[h,y,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:L0,children:["⚠ ",s("layout_editor.page_settings.seo.vars_precondition")]}),c.length>0&&i.jsxs("div",{"data-testid":`${a}-auto-group`,style:ws,children:[i.jsx("div",{style:ks,children:s("layout_editor.page_settings.seo.vars_auto_group")}),c.map(_=>i.jsxs("div",{"data-testid":`g7le-seo-var-auto-${_.name}`,style:P0,children:[i.jsx("span",{style:O0,children:"🔒"}),i.jsx("code",{style:Ss,children:_.name}),i.jsxs("span",{style:B0,children:["〔",s("layout_editor.page_settings.seo.vars_auto"),"·",_.source,"〕"]}),_.owner?.name?i.jsx("span",{style:W0,children:_.owner.name}):null]},_.name))]}),p.length>0&&i.jsxs("div",{"data-testid":`${a}-data-group`,style:ws,children:[i.jsx("div",{style:ks,children:s("layout_editor.page_settings.seo.vars_data_group")}),p.map(_=>{const C=l[_.name]??"",E=C.trim()==="";return i.jsxs("div",{"data-testid":`g7le-seo-var-data-${_.name}`,style:Tc,children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[i.jsx("code",{style:Ss,children:_.name}),_.required?i.jsx("span",{"data-testid":`g7le-seo-var-required-${_.name}`,style:j0,children:"*"}):null]}),i.jsx(Ve,{value:C,onChange:S=>m(_.name,S??""),t:s,candidates:r,testidPrefix:`g7le-seo-var-data-field-${_.name}`}),_.required&&E?i.jsxs("p",{"data-testid":`g7le-seo-var-empty-warn-${_.name}`,style:Cs,children:["⚠ ",s("layout_editor.page_settings.seo.vars_required_empty")]}):null]},_.name)})]}),i.jsxs("div",{"data-testid":`${a}-custom-group`,style:ws,children:[i.jsx("div",{style:ks,children:s("layout_editor.page_settings.seo.vars_custom_group")}),g.map(_=>i.jsxs("div",{"data-testid":`g7le-seo-var-custom-${_}`,style:Tc,children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,marginBottom:4},children:[i.jsx("code",{style:Ss,children:_}),i.jsx("button",{type:"button","data-testid":`g7le-seo-var-custom-remove-${_}`,onClick:()=>m(_,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(Ve,{value:l[_]??"",onChange:C=>m(_,C??""),t:s,candidates:r,testidPrefix:`g7le-seo-var-custom-field-${_}`})]},_)),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:_=>v(_.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:w,disabled:h.trim()===""||b||x,style:H0,children:["+ ",s("layout_editor.page_settings.seo.vars_add")]})]}),b?i.jsxs("p",{"data-testid":"g7le-seo-var-add-reserved-warn",style:Cs,children:["⚠ ",s("layout_editor.page_settings.seo.vars_name_reserved",{name:h.trim()})]}):null,x&&!b?i.jsxs("p",{"data-testid":"g7le-seo-var-add-duplicate-warn",style:Cs,children:["⚠ ",s("layout_editor.page_settings.seo.vars_name_duplicate",{name:h.trim()})]}):null,k?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 L0={fontSize:12,color:"#b45309",background:"#fffbeb",border:"1px solid #fcd34d",borderRadius:6,padding:"6px 8px"},ws={border:"1px solid #e2e8f0",borderRadius:8,padding:10,display:"flex",flexDirection:"column",gap:6},ks={fontSize:12,fontWeight:600,color:"#475569"},P0={display:"flex",alignItems:"center",gap:6,padding:"2px 0"},Tc={display:"flex",flexDirection:"column",border:"1px solid #f1f5f9",borderRadius:6,padding:8},O0={fontSize:13},Ss={fontSize:12,color:"#0f172a",background:"#f1f5f9",padding:"2px 6px",borderRadius:4},B0={fontSize:11,color:"#64748b"},W0={fontSize:11,color:"#94a3b8"},j0={color:"#dc2626",fontWeight:700},Cs={margin:"4px 0 0",fontSize:11,color:"#b45309"},H0={padding:"5px 10px",fontSize:12,border:"1px dashed #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"};function F0({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,y]=u.useState(!0),[g,m]=u.useState(null),[h,v]=u.useState(!1),[b,x]=u.useState(null),k=u.useRef(null),w=u.useRef({templateIdentifier:e,layout:t,url:n,locale:o,seedContext:r,routeParams:s});w.current={templateIdentifier:e,layout:t,url:n,locale:o,seedContext:r,routeParams:s};const _=u.useCallback(async()=>{const T=c??(typeof fetch<"u"?fetch:void 0);if(!T)return;const{templateIdentifier:$,layout:A,url:z,locale:D,seedContext:O,routeParams:M}=w.current;v(!0),x(null);try{const B=`/api/admin/templates/${encodeURIComponent($)}/editor/seo-bot-preview`,N=await T(B,{method:"POST",credentials:"same-origin",headers:je({"Content-Type":"application/json"}),body:JSON.stringify({layout:A,url:z,locale:D,seed_context:O??{},route_params:M??{}})}),H=await N.json().catch(()=>null);if(!N.ok){x(H?.message??`HTTP ${N.status}`);return}const L=H?.data??null;m(L)}catch(B){x(B instanceof Error?B.message:String(B))}finally{v(!1)}},[c]);u.useEffect(()=>{if(f)return k.current&&clearTimeout(k.current),k.current=setTimeout(()=>{_()},d),()=>{k.current&&clearTimeout(k.current)}},[a,f,d,_]);const C=u.useCallback(()=>{k.current&&clearTimeout(k.current),_()},[_]),E=g?.html??null,S=g?.enabled??!0;return i.jsxs("div",{"data-testid":p,style:K0,children:[i.jsxs("div",{style:V0,children:[i.jsxs("button",{type:"button","data-testid":`${p}-toggle`,onClick:()=>y(T=>!T),"aria-expanded":f,style:U0,children:[f?"▾":"▸"," ",l("layout_editor.page_settings.seo.bot_preview_title")]}),f?i.jsxs("button",{type:"button","data-testid":`${p}-refresh`,onClick:C,disabled:h,style:q0,children:["⟳ ",l("layout_editor.page_settings.seo.bot_preview_refresh")]}):null]}),f&&i.jsxs("div",{style:{marginTop:8},children:[g&&!S?i.jsxs("p",{"data-testid":`${p}-disabled`,style:G0,children:["ⓘ ",l("layout_editor.page_settings.seo.bot_preview_disabled")]}):i.jsx("div",{"data-testid":`${p}-body`,style:Y0,children:h&&!E?i.jsx("p",{style:$s,children:l("layout_editor.translation.loading")}):b?i.jsx("p",{"data-testid":`${p}-error`,style:{...$s,color:"#dc2626"},children:b}):E==null?i.jsx("p",{style:$s,children:l("layout_editor.page_settings.seo.bot_preview_empty")}):i.jsx("pre",{"data-testid":`${p}-code`,style:X0,children:E})}),i.jsxs("p",{"data-testid":`${p}-sample-note`,style:J0,children:["ⓘ ",l("layout_editor.page_settings.seo.bot_preview_sample_note")]})]})]})}const K0={borderTop:"1px solid #e2e8f0",paddingTop:10,marginTop:12},V0={display:"flex",alignItems:"center",gap:8},U0={background:"none",border:"none",cursor:"pointer",fontSize:13,fontWeight:600,color:"#0f172a",padding:0},q0={marginLeft:"auto",padding:"4px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},G0={margin:0,fontSize:12,color:"#64748b",background:"#f8fafc",border:"1px solid #e2e8f0",borderRadius:6,padding:"8px 10px"},Y0={border:"1px solid #e2e8f0",borderRadius:8,background:"#0b1020",padding:0,minHeight:80,overflow:"hidden"},X0={margin:0,padding:12,fontSize:11,lineHeight:1.5,color:"#d1fae5",fontFamily:"monospace",whiteSpace:"pre-wrap",wordBreak:"break-word",maxHeight:360,overflow:"auto"},$s={margin:0,padding:12,fontSize:12,color:"#94a3b8"},J0={margin:"8px 0 0",fontSize:11,color:"#94a3b8"};function Dc({option:e,testIdPrefix:t}){const{id:n,friendly:o,source:r}=e;return i.jsxs("span",{style:Z0,children:[i.jsx("span",{"data-testid":t?`${t}-title`:void 0,style:Q0,children:o??n}),o?i.jsx("span",{"data-testid":t?`${t}-id`:void 0,style:R0,children:n}):null,r?i.jsx("span",{"data-testid":t?`${t}-source`:void 0,style:ew,children:r}):null]})}const Z0={display:"inline-flex",alignItems:"baseline",gap:4,flexWrap:"wrap",minWidth:0},Q0={fontSize:12,color:"#0f172a"},R0={fontSize:10,color:"#94a3b8",fontFamily:"ui-monospace, monospace"},ew={fontSize:9,fontWeight:600,color:"#7c3aed",background:"#f5f3ff",border:"1px solid #ddd6fe",borderRadius:4,padding:"0 5px",whiteSpace:"nowrap"},tw=["always","hourly","daily","weekly","monthly","yearly","never"];function nw({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:y,testidPrefix:g="g7le-seo"}){const m=e("meta",{}).seo,h=m&&typeof m=="object"?m:{},v=u.useCallback((K,ne)=>{const me={...e("meta",{})},Ce={...me.seo??{}};ne==null||ne===""?delete Ce[K]:Ce[K]=ne,me.seo=Ce,t("meta",me)},[e,t]),b=h.enabled===!0,x=typeof h.page_type=="string"?h.page_type:"",k=Array.isArray(h.extensions)?h.extensions:[],w=Array.isArray(h.data_sources)?h.data_sources:[],_=k.length>0&&x!=="",[C,E]=u.useState(null),[S,T]=u.useState(null),$=u.useCallback(async(K,ne)=>{if(p)return p(K,ne);if(typeof fetch>"u")return null;const me=new URLSearchParams;K&&me.set("page_type",K),Array.isArray(ne)&&ne.length>0&&me.set("extensions",JSON.stringify(ne.map(qe=>({type:qe.type,id:qe.id}))));const Ce=me.toString()?`?${me.toString()}`:"",ze=await fetch(en(`/api/admin/templates/${encodeURIComponent(o)}/editor/seo-candidates`,"json",null,Ce.replace(/^[?&]+/,"")),{credentials:"same-origin",headers:je()}),Se=await ze.json().catch(()=>null);return ze.ok?Se?.data??null:null},[p,o]),A=u.useMemo(()=>{const me=(e("__editor",{})??{}).original?.meta?.seo;return me&&typeof me=="object"?me:void 0},[e]),z=u.useRef(A);z.current=A;const D=u.useCallback(async K=>{if(f)return f(K);if(typeof fetch>"u")return null;const ne=await fetch(`/api/admin/templates/${encodeURIComponent(o)}/editor/seo-og-preview`,{method:"POST",credentials:"same-origin",headers:je({"Content-Type":"application/json"}),body:JSON.stringify({seo:K,own_seo:z.current??null,seed_context:c??{},route_params:{}})}),me=await ne.json().catch(()=>null);return ne.ok?me?.data??null:null},[f,o,c]),O=u.useMemo(()=>JSON.stringify(k),[k]),M=u.useRef(h);M.current=h,u.useEffect(()=>{let K=!1;return(async()=>{const ne=await $(x,k);K||E(ne)})(),()=>{K=!0}},[x,O]);const B=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]),N=u.useRef(!1);u.useEffect(()=>{let K=!1;const ne=()=>{(async()=>{const Ce=await D(M.current);K||T(Ce)})()};if(!N.current)return N.current=!0,ne(),()=>{K=!0};const me=setTimeout(ne,180);return()=>{K=!0,clearTimeout(me)}},[x,O,B]);const H=C?.page_types??[],L=C?.toggle_settings??[],I=C?.vars??[],P=u.useMemo(()=>JSON.stringify(h),[h]),F=u.useMemo(()=>e("meta")?{meta:e("meta"),components:e("components",[])}:{meta:{},components:[]},[e]),G=u.useCallback(K=>{k.some(ne=>ne.type===K.type&&ne.id===K.id)||v("extensions",[...k,{type:K.type,id:K.id}])},[k,v]),V=u.useCallback(K=>{const ne=k.filter(me=>!(me.type===K.type&&me.id===K.id));v("extensions",ne.length>0?ne:void 0)},[k,v]),[Y,Z]=u.useState(!1),[se,re]=u.useState(""),U=u.useMemo(()=>{const K=se.trim().toLowerCase();return K?L.filter(ne=>`${ne.ref} ${ne.label??""}`.toLowerCase().includes(K)):L},[L,se]),ee=typeof h.toggle_setting=="string"?h.toggle_setting:"",fe=u.useCallback(K=>{const me=w.includes(K)?w.filter(Ce=>Ce!==K):[...w,K];v("data_sources",me.length>0?me:void 0)},[w,v]);return i.jsxs("div",{"data-testid":g,style:{display:"flex",flexDirection:"column",gap:14},children:[i.jsxs("div",{style:Bt,children:[i.jsx(Dr,{checked:b,onChange:K=>v("enabled",K),testid:`${g}-enabled`,label:n("layout_editor.page_settings.seo.enabled")}),b?null:i.jsxs("p",{"data-testid":`${g}-disabled-note`,style:no,children:["ⓘ ",n("layout_editor.page_settings.seo.disabled_note")]})]}),i.jsx(Nr,{disabled:!b,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:x,onChange:K=>v("page_type",K.target.value),style:Lr,children:[i.jsx("option",{value:"",children:n("layout_editor.page_settings.seo.page_type_none")}),H.map(K=>i.jsxs("option",{value:K.value,children:[K.label??K.value,K.owner?.name?` (${K.owner.name})`:""]},K.value))]}):i.jsxs(i.Fragment,{children:[i.jsx("input",{type:"text","data-testid":`${g}-page-type-free`,value:x,placeholder:n("layout_editor.page_settings.seo.page_type_free_placeholder"),onChange:K=>v("page_type",K.target.value),style:Lr}),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:[k.map(K=>i.jsxs("span",{"data-testid":`${g}-extension-${K.type}-${K.id}`,style:Nc,children:[K.name??`${K.type}:${K.id}`,i.jsx("button",{type:"button","data-testid":`${g}-extension-remove-${K.type}-${K.id}`,onClick:()=>V(K),style:zc,children:"✕"})]},`${K.type}:${K.id}`)),i.jsxs("button",{type:"button","data-testid":`${g}-extension-add`,onClick:()=>Z(K=>!K),style:iw,children:["+ ",n("layout_editor.page_settings.seo.add_extension")]})]}),Y&&i.jsx("div",{"data-testid":`${g}-extension-picker`,style:Mc,children:s.length===0?i.jsx("p",{style:no,children:n("layout_editor.page_settings.seo.no_extension_candidate")}):s.map(K=>i.jsx("button",{type:"button","data-testid":`${g}-extension-option-${K.type}-${K.id}`,onClick:()=>{G(K),Z(!1)},style:Lc,children:K.name??`${K.type}:${K.id}`},`${K.type}:${K.id}`))})]}),!_&&i.jsxs("div",{"data-testid":`${g}-defaults-precondition`,style:rw,children:["⚠ ",n("layout_editor.page_settings.seo.defaults_precondition"),i.jsxs("div",{"data-testid":`${g}-defaults-missing`,style:{fontSize:11,marginTop:4},children:[k.length===0?n("layout_editor.page_settings.seo.missing_extensions"):"",x===""?` ${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:Nc,children:ee}),i.jsx("button",{type:"button","data-testid":`${g}-toggle-setting-clear`,onClick:()=>v("toggle_setting",void 0),style:zc,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:K=>re(K.target.value),style:Lr}),se.trim()!==""&&i.jsx("div",{"data-testid":`${g}-toggle-setting-results`,style:Mc,children:U.length===0?i.jsx("p",{style:no,children:n("layout_editor.inline_binding.no_results")}):U.map(K=>i.jsx("button",{type:"button","data-testid":`${g}-toggle-setting-option-${K.ref}`,onClick:()=>{v("toggle_setting",K.ref),re("")},style:Lc,children:K.label??K.ref},K.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(K=>{const ne=w.includes(K.id);return i.jsxs("label",{"data-testid":`${g}-data-source-${K.id}`,style:ow(ne),children:[i.jsx("input",{type:"checkbox","data-testid":`${g}-data-source-check-${K.id}`,checked:ne,onChange:()=>fe(K.id)}),i.jsx(Dc,{option:K,testIdPrefix:`${g}-data-source-${K.id}`})]},K.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:K=>v("priority",Number(K.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:K=>v("changefreq",K.target.value),style:Lr,children:[i.jsx("option",{value:"",children:n("layout_editor.page_settings.seo.use_default")}),tw.map(K=>i.jsx("option",{value:K,children:K},K))]})]}),i.jsxs("div",{style:Bt,children:[i.jsx("label",{style:qt,children:n("layout_editor.page_settings.seo.title")}),i.jsx(vt,{value:typeof h.title=="string"?h.title:"",onChange:K=>v("title",K??""),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(vt,{value:typeof h.description=="string"?h.description:"",onChange:K=>v("description",K??""),t:n,candidates:r,testidPrefix:`${g}-description`,enableExpressionTree:!0,expressionTreeCollapsible:!0})]}),i.jsx(l0,{og:h.og,twitter:h.twitter,onChangeOg:K=>v("og",Object.keys(K).length>0?K:void 0),onChangeTwitter:K=>v("twitter",Object.keys(K).length>0?K:void 0),ogPreview:S?.og,twitterPreview:S?.twitter,defaultsAvailable:S?.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(w0,{value:h.structured_data,onChange:K=>v("structured_data",K??void 0),autoBlock:S?.structured?.autoBlock,autoMeta:S?.structured?.autoMeta,lockedByFilter:S?.structured?.lockedByFilter,filteredBlock:S?.structured?.filteredBlock,pageType:x,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(M0,{vars:h.vars,onChange:K=>v("vars",Object.keys(K).length>0?K:void 0),varCandidates:I,gatingMet:_,candidates:r,t:n})]}),i.jsx(F0,{templateIdentifier:o,layout:F,url:l,locale:d,seedContext:c,settingsSignature:P,t:n,fetchImpl:y})]})})]})}const Bt={display:"flex",flexDirection:"column",gap:4},qt={fontSize:12,fontWeight:600,color:"#334155"},Lr={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"},ow=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}),rw={fontSize:12,color:"#b45309",background:"#fffbeb",border:"1px solid #fcd34d",borderRadius:6,padding:"8px 10px"},Nc={display:"inline-flex",alignItems:"center",gap:4,fontSize:11,padding:"3px 8px",borderRadius:999,background:"#eef2ff",color:"#3730a3"},zc={border:"none",background:"transparent",cursor:"pointer",color:"#6366f1",fontSize:11,padding:0},iw={fontSize:11,padding:"3px 10px",borderRadius:999,border:"1px dashed #cbd5e1",background:"#f8fafc",color:"#475569",cursor:"pointer"},Mc={marginTop:4,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",padding:6,display:"flex",flexDirection:"column",gap:2},Lc={textAlign:"left",border:"none",background:"transparent",cursor:"pointer",padding:"5px 8px",borderRadius:4,fontSize:12,color:"#0f172a"},sw={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"},aw={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"},lw={init:["state","data","notify","nav","locale","etc","flow","error","extension"],component:["nav","notify","data","state","locale","etc","flow","error","extension"]};function dw(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 cw(e,t){return!e||e.kind==="core"?t("layout_editor.action.source_core"):e.id??t(`layout_editor.action.source_${e.kind}`)}function Pc(e,t,n){return typeof e!="string"?n:e.startsWith("$t:")?t(e.slice(3)):e}function uw({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(()=>wo(e),[e]),p=u.useMemo(()=>{const f=lw[o],y=new Map;for(const m of c){const h=dw(e,m.id),b=h!=null&&h.kind!=="core"?"extension":sw[m.id]??"etc",x=y.get(b)??[];x.push({recipe:m,source:h}),y.set(b,x)}const g=l.trim().toLowerCase();return f.map(m=>{let h=y.get(m)??[];return g&&(h=h.filter(({recipe:v})=>Pc(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:xw,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:pw,children:[t("layout_editor.action.add_action")," ▾"]}),s?i.jsxs("div",{"data-testid":`${r}-list`,style:fw,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:gw}),p.map(({groupKey:f,items:y})=>i.jsxs("div",{"data-testid":`${r}-group-${f}`,children:[i.jsxs("div",{style:hw,children:["━━ ",t(aw[f]??f)," ━━"]}),y.map(({recipe:g,source:m})=>i.jsxs("button",{type:"button","data-testid":`g7le-init-action-spec-${g.id}`,onClick:()=>{n(xr(g,{})),a(!1),d("")},style:yw,children:[i.jsx("span",{style:bw,children:Pc(g.label,t,g.id)}),i.jsxs("span",{"data-testid":`g7le-init-action-spec-source-${g.id}`,style:mw,children:["〔",cw(m,t),"〕"]}),i.jsx("code",{style:vw,children:g.build.handler})]},g.id))]},f)),p.length===0?i.jsx("div",{"data-testid":`${r}-no-match`,style:_w,children:t("layout_editor.action.add_no_match")}):null]}):null]})}const pw={padding:"6px 12px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},fw={marginTop:6,border:"1px solid #cbd5e1",borderRadius:8,background:"#fff",maxHeight:320,overflowY:"auto",padding:8},gw={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,marginBottom:6,boxSizing:"border-box"},hw={fontSize:11,fontWeight:700,color:"#94a3b8",padding:"6px 4px 2px"},yw={display:"flex",alignItems:"center",gap:6,width:"100%",textAlign:"left",padding:"6px 8px",fontSize:12,border:"none",background:"transparent",cursor:"pointer",borderRadius:6},bw={flex:1,minWidth:0,color:"#0f172a"},mw={fontSize:10,color:"#64748b",whiteSpace:"nowrap"},vw={fontSize:10,color:"#cbd5e1",fontFamily:"monospace",whiteSpace:"nowrap"},_w={fontSize:12,color:"#94a3b8",padding:"8px 4px"},xw={fontSize:12,color:"#94a3b8",padding:"8px 0"};function ww(e,t){return t.startsWith("$t:")?e(t.slice(3)):t}function kw({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?Wd(t,n,p=>ww(o,p)):typeof e.handler=="string"?e.handler:o("layout_editor.action.advanced_action");return i.jsxs("div",{className:a,"data-testid":a,style:Sw,children:[r?i.jsxs("span",{"data-testid":`${a}-missing`,style:$w,children:["⚠ ",o("layout_editor.action.summary_missing_required")]}):i.jsx("span",{"data-testid":`${a}-summary`,style:Cw,children:c}),s?i.jsx("button",{type:"button","data-testid":`${a}-code-toggle`,onClick:()=>d(p=>!p),style:Ew,"aria-expanded":l,"aria-label":o("layout_editor.action.view_code"),children:""}):null,s&&l?i.jsx("pre",{"data-testid":`${a}-code`,style:Iw,children:JSON.stringify(e,null,2)}):null]})}const Sw={display:"flex",flexWrap:"wrap",alignItems:"center",gap:6,minWidth:0},Cw={flex:1,minWidth:0,fontSize:12,color:"#475569"},$w={flex:1,minWidth:0,fontSize:12,color:"#b45309"},Ew={border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",fontSize:11,padding:"2px 6px",whiteSpace:"nowrap"},Iw={flexBasis:"100%",margin:"6px 0 0",padding:8,background:"#0f172a",color:"#e2e8f0",borderRadius:6,fontSize:11,overflow:"auto"},Oc="__g7le_custom__";function Pr({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(y=>y.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:Hc,children:[i.jsxs("select",{className:"g7le-widget g7le-widget--picker","data-testid":r,value:c?l:"",onChange:y=>{const g=y.target.value;if(g===Oc){f(!0);return}t(g===""?void 0:g)},style:{...Wc,flex:1,minWidth:0},children:[i.jsx("option",{value:"",children:s("layout_editor.control.default")}),n.map(y=>i.jsx("option",{value:y.value,children:y.label},y.value)),i.jsx("option",{value:Oc,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:Fc,children:"✎"})]}):i.jsxs("div",{style:Hc,children:[i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(Ve,{value:l,onChange:y=>t(y===""?void 0:y),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:Fc,children:"≡"})]})}function Aw({value:e,onChange:t,candidates:n,t:o,bindingCandidates:r}){return i.jsx(Pr,{value:e,onChange:t,candidates:n,placeholder:o("layout_editor.recipe.page_placeholder"),testid:"g7le-widget-page-picker",t:o,bindingCandidates:r})}function Bc({value:e,onChange:t,candidates:n,t:o,bindingCandidates:r}){return i.jsx(Pr,{value:e,onChange:t,candidates:n,placeholder:o("layout_editor.recipe.datasource_placeholder"),testid:"g7le-widget-datasource-picker",t:o,bindingCandidates:r})}function Es({value:e,onChange:t,candidates:n,t:o,bindingCandidates:r}){return i.jsx(Pr,{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 Tw({value:e,onChange:t,candidates:n,t:o,bindingCandidates:r}){return i.jsx(Pr,{value:e,onChange:t,candidates:n,placeholder:o("layout_editor.recipe.modal_placeholder"),testid:"g7le-widget-modal-picker",t:o,bindingCandidates:r})}function Dw({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(vt,{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 Nw({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:jc}),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:{...Wc,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 zw({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:jc})}const Wc={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",minWidth:140,width:"100%"},jc={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:100,width:"100%"},Hc={display:"flex",gap:4,alignItems:"flex-start",width:"100%"},Fc={padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"};function Mw(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 Kc(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 Is(e){return/^[A-Za-z_$][A-Za-z0-9_$]*$/.test(e)}function Lw(e,t,n){return t.includes(n)?"self":e.includes(n)?"inherited":"self"}function Pw(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 Vc=[{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 Nn({value:e,onChange:t,t:n,path:o,scope:r,depth:s=0,renderStringLeaf:a}){const l=Mw(e),d=c=>{t(Kc(c))};return i.jsxs("div",{className:"g7le-initstate-value",style:{paddingLeft:s>0?12:0,minWidth:0},children:[i.jsxs("div",{style:Bw,children:[i.jsx("select",{"data-testid":`g7le-initstate-type-${o}`,value:l,onChange:c=>d(c.target.value),style:Uc,children:Vc.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:qc}):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:qc}):l==="boolean"?i.jsx(Dr,{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:Ww,children:"null"}):null]}),l==="list"?i.jsxs("div",{style:Gc,children:[e.map((c,p)=>i.jsxs("div",{style:jw,children:[i.jsxs("span",{style:Hw,children:["[",p,"]"]}),i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(Nn,{value:c,onChange:f=>{const y=e.slice();y[p]=f,t(y)},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,y)=>y!==p)),style:Yc,children:"✕"})]},p)),i.jsxs("button",{type:"button","data-testid":`g7le-initstate-item-add-${o}`,onClick:()=>t([...e,""]),style:Xc,children:["+ ",n("layout_editor.initstate.add_item")]})]}):null,l==="object"?i.jsx(Ow,{value:e,onChange:t,t:n,path:o,scope:r,depth:s+1,renderStringLeaf:a}):null]})}function Ow({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,y]=u.useState(null),g=Object.entries(e),m=()=>{const h=l.trim();if(!h){y(n("layout_editor.initstate.name_required"));return}if(!Is(h)){y(n("layout_editor.initstate.name_invalid"));return}if(h in e){y(n("layout_editor.initstate.name_duplicate"));return}t({...e,[h]:Kc(c)}),d(""),y(null)};return i.jsxs("div",{style:Gc,children:[g.map(([h,v])=>i.jsxs("div",{style:Fw,children:[i.jsx("code",{style:Kw,children:h}),i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(Nn,{value:v,onChange:b=>t({...e,[h]:b}),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 b={...e};delete b[h],t(b)},style:Yc,children:"✕"})]},h)),i.jsxs("div",{style:Vw,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&&y(null)},onKeyDown:h=>{h.key==="Enter"&&(h.preventDefault(),m())},"aria-invalid":f?!0:void 0,style:{...Uw,...f?qw: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:Uc,children:Vc.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:Xc,children:["+ ",n("layout_editor.initstate.add_subkey")]})]}),f?i.jsx("p",{"data-testid":`g7le-initstate-subkey-error-${o}`,style:Gw,children:f}):null]})}const Bw={display:"flex",gap:6,alignItems:"center",minWidth:0},Uc={padding:"4px 6px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,color:"#64748b"},qc={flex:1,minWidth:0,padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},Ww={fontSize:12,color:"#94a3b8",fontFamily:"monospace"},Gc={display:"flex",flexDirection:"column",gap:6,marginTop:6,paddingLeft:8,borderLeft:"2px solid #e2e8f0"},jw={display:"flex",gap:6,alignItems:"flex-start",minWidth:0},Hw={fontSize:11,color:"#94a3b8",minWidth:28,paddingTop:4},Fw={display:"flex",gap:6,alignItems:"flex-start",minWidth:0},Kw={fontSize:11,color:"#475569",fontFamily:"monospace",minWidth:72,paddingTop:4},Yc={border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12},Xc={alignSelf:"flex-start",padding:"2px 8px",fontSize:11,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},Vw={display:"flex",gap:6,alignItems:"center"},Uw={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6},qw={border:"1px solid #dc2626"},Gw={margin:"2px 0 0",fontSize:11,color:"#dc2626"},Yw=new Set(["text","data-chip","number"]),Xw=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 Jw(e,t,n){return typeof e!="string"?n:e.startsWith("$t:")?t(e.slice(3)):e}function Zw(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 Qw({param:e,value:t,t:n,pools:o,onChange:r,testIdPrefix:s,renderActionList:a,siblingValues:l}){const d=Jw(e.label,n,e.key);if(e.advanced)return i.jsxs("div",{"data-testid":`${s}-locked-${e.key}`,style:lk,children:[i.jsx("span",{style:dk,children:d}),i.jsxs("span",{style:ck,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(y=>!!y&&typeof y=="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,y=>r(y.length===0?void 0:y),`${s}-${e.key}`,e.key)]})}if(e.widget==="branch-list"&&a){const f=Array.isArray(t)?t.filter(y=>!!y&&typeof y=="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(Rw,{branches:f,onChange:y=>r(y.length===0?void 0:y),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(rk,{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(ik,{value:t,onChange:r,t:n,candidates:o.bindingCandidates,stateKeyCandidates:o.stateKeyCandidates,param:e,siblingTarget:l?.target,testIdPrefix:`${s}-skv-${e.key}`})]});if(Yw.has(e.widget??"")||!Xw.has(e.widget??""))return i.jsxs("div",{"data-testid":`${s}-param-${e.key}`,style:Zc,children:[i.jsx("span",{style:oo,children:d}),i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(Ve,{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:Zc,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:Zw(e.widget,o),bindingCandidates:o.bindingCandidates}):i.jsx(Ve,{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 Rw({branches:e,onChange:t,t:n,pools:o,renderActionList:r,testIdPrefix:s}){const a=y=>Array.isArray(y)?y.filter(g=>!!g&&typeof g=="object"):y&&typeof y=="object"?[y]:[],l=y=>{if(y.length!==0)return y.length===1?y[0]:y},d=(y,g)=>{const m=e.slice();m[y]=g,t(m)},c=y=>{t(e.filter((g,m)=>m!==y))},p=(y,g)=>{if(g<0||g>=e.length)return;const m=e.slice(),[h]=m.splice(y,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((y,g)=>{const m=typeof y.if=="string"?y.if:"",h=a(y.then);return i.jsxs("div",{"data-testid":`${s}-branch-${g}`,style:ek,children:[i.jsxs("div",{style:tk,children:[i.jsxs("span",{style:nk,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:As,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:As,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:As,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:Jc,children:n("layout_editor.action_recipe.conditions.param_if")}),i.jsx(Ve,{value:m,onChange:v=>d(g,{...y,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:Jc,children:n("layout_editor.action_recipe.conditions.param_then")}),r(h,v=>d(g,{...y,then:l(v)}),`${s}-branch-${g}-then`)]})]},g)}),i.jsxs("button",{type:"button","data-testid":`${s}-add-branch`,onClick:f,style:ok,children:["+ ",n("layout_editor.action_recipe.conditions.add_branch")]})]})}const ek={border:"1px solid #e2e8f0",borderRadius:6,padding:8,display:"flex",flexDirection:"column",gap:6,background:"#f8fafc"},tk={display:"flex",justifyContent:"space-between",alignItems:"center"},nk={fontSize:12,fontWeight:700,color:"#475569"},Jc={fontSize:11,color:"#64748b"},As={border:"1px solid #cbd5e1",background:"#fff",borderRadius:4,width:22,height:22,cursor:"pointer",fontSize:12,lineHeight:"1",color:"#475569"},ok={border:"1px dashed #94a3b8",background:"#fff",borderRadius:6,padding:"6px 10px",cursor:"pointer",fontSize:12,color:"#475569",alignSelf:"flex-start"};function rk({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(zr,{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 ik({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 b=d[0][1];return i.jsx("div",{"data-testid":`${l}-path-value`,style:{display:"flex",flexDirection:"column",gap:4},children:i.jsx(Nn,{value:b,onChange:x=>t(x===void 0?void 0:{value:x}),t:n,path:"value",scope:`${l}-path-value-val`,renderStringLeaf:x=>i.jsx(Ve,{value:x.value,onChange:x.onChange,t:n,candidates:o,testidPrefix:x.testidPrefix})})})}const y=(b,x)=>{const k={};for(const[w,_]of d)k[w]=w===b?x:_;t(Object.keys(k).length===0?void 0:k)},g=b=>{const x={};for(const[k,w]of d)k!==b&&(x[k]=w);t(Object.keys(x).length===0?void 0:x)},[m,h]=u.useState(""),v=()=>{const b=m.trim();if(b===""||d.some(([k])=>k===b))return;const x={};for(const[k,w]of d)x[k]=w;x[b]="",t(x),h("")};return i.jsxs("div",{"data-testid":l,style:{display:"flex",flexDirection:"column",gap:6},children:[d.map(([b,x])=>i.jsxs("div",{"data-testid":`${l}-row-${b}`,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(Es,{control:{...s},value:b,onChange:k=>{const w=k==null?"":String(k);if(w===""||w===b||d.some(([C])=>C===w))return;const _={};for(const[C,E]of d)_[C===b?w:C]=E;t(_)},t:n,candidates:r})}),i.jsx("div",{style:{minWidth:0},children:i.jsx(Nn,{value:x,onChange:k=>y(b,k),t:n,path:b,scope:`${l}-val`,renderStringLeaf:k=>i.jsx(Ve,{value:k.value,onChange:k.onChange,t:n,candidates:o,testidPrefix:k.testidPrefix})})})]}),i.jsx("button",{type:"button","data-testid":`${l}-remove-${b}`,onClick:()=>g(b),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:"✕"})]},b)),i.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[i.jsx("div",{style:{flex:1,minWidth:0},children:i.jsx(Es,{control:{...s},value:m,onChange:b=>h(b==null?"":String(b)),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 Ts({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},y=xr(t,f),g=as(e);s(g?jd(y,g):y)};return i.jsx(i.Fragment,{children:t.params.filter(c=>sk(c,n)).map(c=>i.jsx(Qw,{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 sk(e,t){const n=e.dependsOn;return!n||typeof n!="object"||typeof n.param!="string"?!0:t[n.param]===n.equals}function ak({raw:e,t,onChange:n,testIdPrefix:o,candidates:r}){const[s,a]=u.useState(!1);return i.jsxs("div",{"data-testid":`${o}-if`,style:uk,children:[i.jsxs("button",{type:"button",onClick:()=>a(l=>!l),style:pk,children:["▸ ",t("layout_editor.init_actions.if_label")]}),s?i.jsx("div",{"data-testid":`${o}-if-input`,style:{minWidth:0},children:i.jsx(Ve,{value:as(e)??"",onChange:l=>n(jd(e,l)),t,candidates:r,placeholder:t("layout_editor.init_actions.if_placeholder"),testidPrefix:`${o}-if-chip`})}):null]})}const Zc={display:"flex",alignItems:"center",gap:8,minWidth:0},oo={fontSize:11,color:"#64748b",minWidth:80},lk={display:"flex",alignItems:"center",gap:8,padding:"4px 0"},dk={fontSize:11,color:"#64748b",minWidth:80},ck={fontSize:11,color:"#92400e"},uk={display:"flex",flexDirection:"column",gap:4},pk={textAlign:"left",border:"none",background:"transparent",color:"#475569",cursor:"pointer",fontSize:11,padding:0};function fk(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 gk(e,t,n){const o=Yn(e,t);if(o.kind==="preset"){const r=t.find(s=>s.id===o.recipeId);return Wd(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:y,isLocked:g,hideAddPicker:m=!1,testIdPrefix:h="g7le-action-list"}){const v=u.useMemo(()=>wo(o),[o]),b=u.useMemo(()=>{if(r==null||r==="init")return c;const O=jl(r,n,s??null);if(O.length===0)return c;const M=c??{},B=new Set((M.bindingCandidates??[]).map(H=>H.expression)),N=O.filter(H=>!B.has(H.expression));return N.length===0?c:{...M,bindingCandidates:[...N,...M.bindingCandidates??[]]}},[r,s,c,n]),[x,k]=u.useState(null),[w,_]=u.useState(null),C=u.useCallback((O,M)=>{if(O===M||O<0||M<0||O>=e.length||M>=e.length)return;const B=e.slice(),[N]=B.splice(O,1);B.splice(M,0,N),t(B)},[e,t]),E=fs({length:e.length,onMove:C,canDrag:f,canDropAt:y}),S=u.useCallback(O=>{t(e.filter((M,B)=>B!==O))},[e,t]),T=u.useCallback((O,M)=>{const B=e.slice();B[O]=M,t(B)},[e,t]),$=u.useCallback(O=>{t([...e,O])},[e,t]),A=u.useCallback((O,M)=>{const B=Yn(O,v),N=B.kind==="preset"?v.find(L=>L.id===B.recipeId)??null:null;if(!N)return null;const H=B.kind==="preset"?B.values:{};return i.jsxs("div",{style:mk,children:[i.jsx(Ts,{raw:O,recipe:N,values:H,t:n,pools:b??{},onChange:M,testIdPrefix:`${h}-edit`,renderActionList:(L,I,P,F)=>{const G=F==="onSuccess"?"response":F==="onError"?"error":void 0;return i.jsx(Gt,{actions:L,onChange:I,t:n,recipes:o,chipContext:G,actionChipCandidates:G?s:void 0,candidatePools:G?c:b,addContext:a,showSourceBadge:p,testIdPrefix:P})}}),i.jsx(ak,{raw:O,t:n,onChange:M,testIdPrefix:`${h}-edit`,candidates:b?.bindingCandidates})]})},[v,n,b,c,s,h,o,a,p]),z=d??(o?A:void 0),D=m?null:l?l($):o?i.jsx(uw,{recipes:o,t:n,onAdd:$,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((O,M)=>{const B=Yn(O,v),N=B.kind==="preset"?B.recipeId:null,H=N?v.find(G=>G.id===N)??null:null,L=H===null,I=g?.(M)??!1,P=as(O)!==null,F=z?z(O,G=>T(M,G)):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:E.isDropTarget(M),testid:`${h}-dropline-${M}`})}),i.jsxs("li",{"data-testid":`${h}-item-${M}`,"data-drag-source":E.dragIndex===M?"true":void 0,style:{border:"1px solid #e2e8f0",borderRadius:8,padding:"8px 10px",...E.dragIndex===M?{opacity:.5}:{}},onDragOver:E.dragging&&!I?G=>{G.preventDefault();const V=G.currentTarget.getBoundingClientRect();E.onDragOverItem(M,G.clientY{G.preventDefault(),E.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:()=>E.onDragStart(M),onDragEnd:E.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:gk(O,v,n)}),p?i.jsxs("span",{"data-testid":`${h}-source-${M}`,style:hk,children:["〔",fk(o,N,n),"〕"]}):null,P?i.jsxs("span",{"data-testid":`${h}-cond-badge-${M}`,style:yk,children:["〔",n("layout_editor.init_actions.cond_badge"),"〕"]}):null,L?i.jsxs("span",{"data-testid":`${h}-advanced-${M}`,style:bk,children:["[",n("layout_editor.action.advanced"),"]"]}):null,!I&&F?i.jsxs("button",{type:"button","data-testid":`${h}-edit-${M}`,onClick:()=>_(w===M?null:M),"aria-label":n("layout_editor.init_actions.edit"),title:n("layout_editor.init_actions.edit"),style:w===M?vk:Qc,children:["✎ ",n("layout_editor.init_actions.edit")]}):null,i.jsx("button",{type:"button","data-testid":`${h}-code-${M}`,onClick:()=>k(x===M?null:M),"aria-label":n("layout_editor.action_list.view_code"),title:n("layout_editor.action_list.view_code"),style:x===M?_k:Ds,children:""}),I?null:i.jsx("button",{type:"button","data-testid":`${h}-remove-${M}`,onClick:()=>S(M),"aria-label":n("layout_editor.action_list.remove"),title:n("layout_editor.action_list.remove"),style:xk,children:"✕"})]}),H?i.jsx(kw,{action:O,recipe:H,values:B.kind==="preset"?B.values:{},t:n,showCodeButton:!1,testIdPrefix:`${h}-preview-${M}`}):null,w===M&&!I&&F?i.jsx("div",{"data-testid":`${h}-edit-body-${M}`,children:F}):null,d&&w!==M?d(O,G=>T(M,G)):null,x===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(O,null,2)}):null]})]},M)}),i.jsx("li",{"aria-hidden":"true",style:{listStyle:"none",margin:0,padding:0},children:i.jsx(Rn,{active:E.isDropTarget(e.length),testid:`${h}-dropline-end`})})]}),D?i.jsx("div",{style:{marginTop:8},children:D}):null]})}const hk={fontSize:10,color:"#64748b",whiteSpace:"nowrap"},yk={fontSize:10,color:"#7c3aed",whiteSpace:"nowrap"},bk={fontSize:10,color:"#92400e",whiteSpace:"nowrap"},mk={display:"flex",flexDirection:"column",gap:6,paddingTop:6,borderTop:"1px dashed #e2e8f0",marginTop:6},Qc={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},vk={...Qc,background:"#eff6ff",borderColor:"#bfdbfe",color:"#2563eb"},Ds={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"},_k={...Ds,background:"#0f172a",borderColor:"#0f172a",color:"#e2e8f0"},xk={...Ds,color:"#dc2626",borderColor:"#fecaca",fontFamily:"inherit"};function Rc(e){const t=e.__source;return t&&typeof t=="object"?t:null}function wk({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=>Rc(h)?.kind==="base"),[e]),f=u.useMemo(()=>e.filter(h=>Rc(h)?.kind!=="base"),[e]),y=p.length>0,g=u.useCallback(h=>{t(y?[...p,...h]:h)},[t,y,p]),m=u.useCallback(()=>{},[]);return i.jsxs("div",{className:"g7le-init-actions-form","data-testid":"g7le-init-actions-form",style:kk,children:[i.jsx("p",{style:Sk,children:o("layout_editor.page_settings.init_actions.heading")}),y?i.jsxs(i.Fragment,{children:[i.jsxs("div",{"data-testid":"g7le-init-action-group-base",style:eu,children:[i.jsx("div",{style:tu,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:Ck,children:["ⓘ ",o("layout_editor.init_actions.base_readonly_hint")]})]}),i.jsxs("div",{"data-testid":"g7le-init-action-group-self",style:eu,children:[i.jsx("div",{style:tu,children:o("layout_editor.init_actions.group_self")}),f.length===0?i.jsx("p",{style:nu,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:$k,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:nu,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 kk={display:"flex",flexDirection:"column",gap:12,minWidth:0},Sk={margin:0,fontSize:13,fontWeight:700,color:"#0f172a"},eu={border:"1px solid #e2e8f0",borderRadius:10,padding:10,display:"flex",flexDirection:"column",gap:8},tu={fontSize:12,fontWeight:700,color:"#475569"},Ck={margin:0,fontSize:11,color:"#64748b"},nu={margin:0,fontSize:12,color:"#94a3b8"},$k={margin:0,fontSize:11,color:"#64748b"};function Ek(e){return e==="spinner"?new Set(["spinner","page"]):new Set(["skeleton"])}function ou(e,t,n){return typeof e!="string"?n:e.startsWith("$t:")?t(e.slice(3)):e}function ru({candidates:e,value:t,onSelect:n,styleKind:o,t:r,testIdPrefix:s="g7le-loading-component-picker"}){const a=yo(),l=()=>{const d=a.open({ariaLabel:r("layout_editor.overlay.loading_picker.select"),width:520,maxHeightRatio:.7,content:i.jsx(Ik,{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:Ak,children:[i.jsx("span",{"data-testid":`${s}-current`,style:Tk,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:Dk,children:["🔍 ",r("layout_editor.overlay.loading_picker.select")]})]})})}function Ik({candidates:e,value:t,styleKind:n,t:o,testIdPrefix:r,onPick:s,onClose:a}){const[l,d]=u.useState(""),c=Ek(n),p=u.useMemo(()=>{const f=l.trim().toLowerCase();return e.filter(y=>c.has(y.role)).filter(y=>f?ou(y.label,o,y.name).toLowerCase().includes(f)||y.name.toLowerCase().includes(f):!0)},[e,n,l,o]);return i.jsxs("div",{"data-testid":`${r}-modal`,style:Nk,children:[i.jsxs("div",{style:zk,children:[i.jsxs("span",{style:Mk,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:Lk,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:Pk,autoFocus:!0}),p.length===0?i.jsx("p",{"data-testid":`${r}-empty`,style:Kk,children:o("layout_editor.overlay.loading_picker.empty")}):i.jsx("ul",{style:Ok,children:p.map(f=>i.jsx("li",{children:i.jsxs("button",{type:"button","data-testid":`${r}-item-${f.name}`,onClick:()=>s(f.name),style:{...Bk,...t===f.name?Wk:{}},children:[i.jsx("span",{style:jk,children:ou(f.label,o,f.name)}),i.jsx("code",{style:Hk,children:f.name}),i.jsx("span",{style:Fk,children:f.role})]})},f.name))})]})}const Ak={display:"flex",alignItems:"center",gap:6,minWidth:0},Tk={flex:1,minWidth:0,fontSize:12,color:"#0f172a",fontFamily:"monospace"},Dk={padding:"4px 10px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer",whiteSpace:"nowrap"},Nk={display:"flex",flexDirection:"column",minHeight:0,padding:16,boxSizing:"border-box",fontFamily:"system-ui, -apple-system, sans-serif"},zk={display:"flex",alignItems:"center",gap:8,paddingBottom:8,borderBottom:"1px solid #e2e8f0",marginBottom:10},Mk={flex:1,fontSize:14,fontWeight:700,color:"#0f172a",minWidth:0},Lk={border:"none",background:"transparent",color:"#64748b",cursor:"pointer",fontSize:15,lineHeight:1,padding:4},Pk={width:"100%",padding:"6px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,marginBottom:8,boxSizing:"border-box"},Ok={listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:2,overflowY:"auto",minHeight:0},Bk={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},Wk={border:"1px solid #3b82f6",background:"#eff6ff"},jk={flex:1,minWidth:0,color:"#0f172a"},Hk={fontSize:10,color:"#94a3b8",fontFamily:"monospace"},Fk={fontSize:10,color:"#64748b",background:"#f1f5f9",borderRadius:4,padding:"0 4px"},Kk={margin:0,fontSize:12,color:"#94a3b8",padding:"8px 4px"};function iu(e){return e===!0?{enabled:!0}:e===!1||e===void 0?{}:e}const Vk=["opaque","blur","fade","skeleton","spinner"];function Uk({value:e,patch:t,t:n,baseValue:o,ownValue:r,loadingComponents:s=[],progressiveDataSources:a=[],bindingCandidates:l}){const d=iu(e),c=d.enabled??!1,p=!!o&&Object.keys(o).length>0,f=Tn("component-target-picker"),[y,g]=u.useState((d.wait_for??[]).length>0),m=u.useCallback(w=>{const _={...iu(e)};w(_),t(_)},[e,t]),h=r&&typeof r=="object"?r:e&&typeof e=="object"?e:{},v=u.useCallback(w=>p&&o!==void 0&&w in o&&!(w in h),[p,o,h]),b=u.useCallback(w=>{o&&m(_=>{_[w]=o[w]})},[o,m]),x=u.useCallback(w=>m(_=>{_.enabled=w}),[m]),k=d.target!==void 0?"region":"full";return i.jsxs("div",{className:"g7le-overlay-form","data-testid":"g7le-overlay-form",style:qk,children:[p?i.jsxs("p",{"data-testid":"g7le-overlay-inherit-banner",style:Gk,children:["ⓘ ",n("layout_editor.overlay.inherit_banner")]}):null,i.jsxs("div",{style:Br,children:[i.jsx(Ns,{label:n("layout_editor.overlay.enabled_label"),inherited:v("enabled"),hasInheritance:p,onOverride:()=>b("enabled"),testidKey:"enabled",t:n}),i.jsx(Nr,{disabled:v("enabled"),children:i.jsx(Dr,{checked:c,onChange:x,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:Wr,children:["ⓘ ",n("layout_editor.overlay.enabled_hint")]})]}),i.jsx(Nr,{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:Br,children:[i.jsx(Ns,{label:n("layout_editor.overlay.scope_label"),inherited:v("target"),hasInheritance:p,onOverride:()=>b("target"),testidKey:"target",t:n}),i.jsxs("div",{"data-testid":"g7le-overlay-scope",style:zs,children:[i.jsx(Or,{active:k==="full",onClick:()=>m(w=>{delete w.target,delete w.fallback_target}),testid:"g7le-overlay-scope-full",children:n("layout_editor.overlay.scope_full")}),i.jsx(Or,{active:k==="region",onClick:()=>m(w=>{w.target=w.target??""}),testid:"g7le-overlay-scope-region",children:n("layout_editor.overlay.scope_region")})]}),i.jsx(Nr,{disabled:k!=="region",testid:"g7le-overlay-region-box",style:Zk,children:i.jsxs(i.Fragment,{children:[i.jsx(zn,{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:w=>m(_=>{_.target=typeof w=="string"?w:""}),t:n}):i.jsx("input",{type:"text","data-testid":"g7le-overlay-target-input",value:d.target??"",onChange:w=>m(_=>{_.target=w.target.value}),style:e1})})}),i.jsx(zn,{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:w=>m(_=>{const C=typeof w=="string"?w:"";C===""?delete _.fallback_target:_.fallback_target=C}),t:n}):null})}),i.jsxs("p",{style:Wr,children:["ⓘ ",n("layout_editor.overlay.fallback_hint")]})]})})]}),i.jsxs("div",{style:Br,children:[i.jsx(Ns,{label:n("layout_editor.overlay.style_label"),inherited:v("style"),hasInheritance:p,onOverride:()=>b("style"),testidKey:"style",t:n}),i.jsx("div",{"data-testid":"g7le-overlay-style",style:zs,children:Vk.map(w=>i.jsx(Or,{active:(d.style??"opaque")===w,onClick:()=>m(_=>{_.style=w}),testid:`g7le-overlay-style-${w}`,children:n(`layout_editor.overlay.style_${w}`)},w))}),d.style==="skeleton"?i.jsxs("div",{style:su,children:[i.jsx(zn,{label:n("layout_editor.overlay.skeleton_component"),children:i.jsx(ru,{candidates:s,value:d.skeleton?.component,styleKind:"skeleton",onSelect:w=>m(_=>{_.skeleton={..._.skeleton,component:w}}),t:n,testIdPrefix:"g7le-overlay-skeleton-component"})}),i.jsx(zn,{label:n("layout_editor.overlay.skeleton_animation"),children:i.jsx("div",{"data-testid":"g7le-overlay-skeleton-anim",style:zs,children:["wave","pulse","none"].map(w=>i.jsx(Or,{active:(d.skeleton?.animation??"wave")===w,onClick:()=>m(_=>{_.skeleton={..._.skeleton,animation:w}}),testid:`g7le-overlay-skeleton-anim-${w}`,children:n(`layout_editor.overlay.anim_${w}`)},w))})}),i.jsx(zn,{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:w=>m(_=>{const C=parseInt(w.target.value,10);_.skeleton={..._.skeleton,iteration_count:Number.isNaN(C)?void 0:C}}),style:t1})})]}):null,d.style==="spinner"?i.jsxs("div",{style:su,children:[i.jsx(zn,{label:n("layout_editor.overlay.spinner_component"),children:i.jsx(ru,{candidates:s,value:d.spinner?.component,styleKind:"spinner",onSelect:w=>m(_=>{_.spinner={..._.spinner,component:w}}),t:n,testIdPrefix:"g7le-overlay-spinner-component"})}),i.jsx(zn,{label:n("layout_editor.overlay.spinner_text"),children:i.jsx("div",{"data-testid":"g7le-overlay-spinner-text",style:{minWidth:0},children:i.jsx(vt,{value:d.spinner?.text??"",onChange:w=>m(_=>{_.spinner={..._.spinner,text:w===void 0||w===""?void 0:w}}),t:n,candidates:l,enableExpressionTree:!0,expressionTreeCollapsible:!0,testidPrefix:"g7le-overlay-spinner-text-field"})})})]}):null]}),i.jsxs("div",{style:Br,children:[i.jsxs("button",{type:"button","data-testid":"g7le-overlay-waitfor-toggle","aria-expanded":y,onClick:()=>g(w=>!w),style:r1,children:[y?"▾":"▸"," ",n("layout_editor.overlay.waitfor_label")]}),y?i.jsxs("div",{"data-testid":"g7le-overlay-waitfor-body",style:i1,children:[i.jsxs("p",{"data-testid":"g7le-overlay-waitfor-hint",style:Wr,children:["ⓘ ",n("layout_editor.overlay.waitfor_hint")]}),a.length===0?i.jsx("p",{"data-testid":"g7le-overlay-waitfor-empty",style:Wr,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(w=>{const _=(d.wait_for??[]).includes(w.id);return i.jsxs("label",{"data-testid":`g7le-overlay-waitfor-${w.id}`,style:n1(_),children:[i.jsx("input",{type:"checkbox",checked:_,onChange:()=>m(C=>{const E=new Set(C.wait_for??[]);E.has(w.id)?E.delete(w.id):E.add(w.id);const S=Array.from(E);S.length===0?delete C.wait_for:C.wait_for=S})}),i.jsx(Dc,{option:w,testIdPrefix:`g7le-overlay-waitfor-${w.id}`})]},w.id)})})]}):null]}),p?i.jsxs("button",{type:"button","data-testid":"g7le-overlay-reset-inherit",onClick:()=>t(void 0),style:o1,children:["⟲ ",n("layout_editor.overlay.reset_inherit")]}):null]})})]})}function Or({active:e,onClick:t,children:n,testid:o}){return i.jsx("button",{type:"button","data-testid":o,"aria-pressed":e,onClick:t,style:{...Xk,...e?Jk:{}},children:n})}function Ns({label:e,inherited:t,hasInheritance:n,onOverride:o,testidKey:r,t:s}){return i.jsxs("div",{style:s1,children:[i.jsx("label",{style:Yk,children:e}),n?t?i.jsxs(i.Fragment,{children:[i.jsxs("span",{"data-testid":`g7le-overlay-inherited-${r}`,style:a1,children:["〔",s("layout_editor.overlay.inherited_badge"),"〕"]}),i.jsx("button",{type:"button","data-testid":`g7le-overlay-override-${r}`,onClick:o,style:d1,children:s("layout_editor.overlay.override_field")})]}):i.jsxs("span",{"data-testid":`g7le-overlay-overridden-${r}`,style:l1,children:["〔",s("layout_editor.overlay.overridden_badge"),"〕"]}):null]})}function zn({label:e,children:t}){return i.jsxs("div",{style:Qk,children:[i.jsx("span",{style:Rk,children:e}),i.jsx("div",{style:{flex:1,minWidth:0},children:t})]})}const qk={display:"flex",flexDirection:"column",gap:16,minWidth:0},Gk={margin:0,fontSize:12,color:"#1d4ed8",background:"#eff6ff",padding:"8px 10px",borderRadius:6},Br={display:"flex",flexDirection:"column",gap:6,minWidth:0},Yk={fontSize:13,fontWeight:600,color:"#0f172a"},Wr={margin:0,fontSize:11,color:"#94a3b8"},zs={display:"flex",gap:4,flexWrap:"wrap"},Xk={padding:"4px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},Jk={border:"1px solid #3b82f6",background:"#eff6ff",color:"#1d4ed8"},Zk={display:"flex",flexDirection:"column",gap:8,padding:8,border:"1px dashed #e2e8f0",borderRadius:8},su={display:"flex",flexDirection:"column",gap:8,padding:8,border:"1px dashed #e2e8f0",borderRadius:8},Qk={display:"flex",alignItems:"center",gap:8,minWidth:0},Rk={fontSize:11,color:"#64748b",minWidth:90},e1={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},t1={width:80,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},n1=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"}),o1={alignSelf:"flex-start",padding:"6px 12px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},r1={alignSelf:"flex-start",padding:"4px 0",fontSize:13,fontWeight:600,color:"#0f172a",background:"transparent",border:"none",cursor:"pointer"},i1={display:"flex",flexDirection:"column",gap:6,paddingLeft:14,minWidth:0},s1={display:"flex",alignItems:"center",gap:8,flexWrap:"wrap",minWidth:0},a1={fontSize:11,color:"#64748b",background:"#f1f5f9",borderRadius:4,padding:"1px 6px"},l1={fontSize:11,color:"#0369a1",background:"#e0f2fe",borderRadius:4,padding:"1px 6px"},d1={padding:"2px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},c1="g7le:computed-effect-preview",u1={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 p1(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 au({expr:e,computedKey:t,sampleContext:n,t:o,isEffect:r=!1,testIdPrefix:s="g7le-computed-preview"}){const a=Id(e,n),l=()=>{typeof window>"u"||!t||window.dispatchEvent(new CustomEvent(c1,{detail:{key:t}}))};return a.ok?i.jsxs("div",{className:s,"data-testid":s,style:f1,children:[i.jsx("span",{style:g1,children:o("layout_editor.computed.preview_label")}),i.jsx("span",{"data-testid":`${s}-value`,style:h1,children:p1(a.value,a.type,o)}),i.jsxs("span",{"data-testid":`${s}-type`,style:y1,children:["(",o(u1[a.type]),")"]}),r&&a.type==="boolean"?i.jsxs("button",{type:"button","data-testid":`${s}-effect`,onClick:l,style:b1,children:["▷ ",o("layout_editor.computed.effect_preview")]}):null]}):i.jsxs("div",{"data-testid":`${s}-error`,style:m1,children:["⚠ ",o("layout_editor.computed.preview_error")]})}const f1={display:"flex",alignItems:"center",flexWrap:"wrap",gap:6,minWidth:0},g1={fontSize:11,color:"#94a3b8"},h1={fontSize:12,color:"#0f172a",fontFamily:"monospace",wordBreak:"break-all"},y1={fontSize:10,color:"#64748b"},b1={padding:"2px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},m1={fontSize:12,color:"#b45309"},v1=[{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"}],_1=["=","!=",">","<",">=","<=","includes"],x1=new Set(["count","sum","filter"]);function lu({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(),b={...v[g]};m(b),v[g]=b,h.conditions=v}),y=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:w1,children:[i.jsx(Ms,{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(Ms,{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:v1.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(Ve,{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(Ve,{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(Ve,{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(Ve,{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(Ve,{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(Ve,{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,x1.has(e.op)?i.jsxs("div",{style:$1,children:[l.map((g,m)=>i.jsxs("div",{"data-testid":`g7le-computed-custom-cond-${m}`,style:E1,children:[i.jsx("div",{"data-testid":`g7le-computed-custom-cond-field-${m}`,style:{flex:1,minWidth:0},children:i.jsx(Ve,{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:I1,children:_1.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(Ve,{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:()=>y(m),style:A1,children:"✕"})]},m)),i.jsxs("button",{type:"button","data-testid":"g7le-computed-custom-cond-add",onClick:p,style:T1,children:["+ ",n("layout_editor.computed.cond_add")]})]}):null]}),i.jsxs(Ms,{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?C1:{}}}),c?i.jsxs("p",{"data-testid":"g7le-computed-custom-key-dup",style:D1,children:["⚠ ",n("layout_editor.computed.key_duplicate")]}):null]})]})}function Ms({label:e,children:t}){return i.jsxs("div",{style:k1,children:[i.jsx("div",{style:S1,children:e}),i.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6,minWidth:0},children:t})]})}function Ls(e){return Vm(e)}const w1={display:"flex",flexDirection:"column",gap:12,padding:10,border:"1px solid #cbd5e1",borderRadius:8,background:"#fff"},k1={display:"flex",flexDirection:"column",gap:4,minWidth:0},S1={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"},C1={border:"1px solid #ef4444"},$1={display:"flex",flexDirection:"column",gap:6,marginTop:4},E1={display:"flex",gap:4,alignItems:"center",minWidth:0},I1={padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},A1={border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12},T1={alignSelf:"flex-start",padding:"2px 8px",fontSize:11,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},D1={margin:0,fontSize:11,color:"#b45309"};function Ps(e,t,n){return typeof e!="string"?n:e.startsWith("$t:")?t(e.slice(3)):e}function N1(e){if(e&&typeof e=="object"){const t=e.__source;if(t&&typeof t=="object")return t}return null}function z1({computed:e,onChange:t,recipes:n,t:o,sampleContext:r,dataSourceCandidates:s,bindingCandidates:a,computedSource:l={},effectKeys:d=[],onRevert:c}){const p=u.useMemo(()=>xd(n),[n]),[f,y]=u.useState(!1),[g,m]=u.useState(null),h=Object.keys(e),v=u.useCallback((_,C)=>{t({...e,[_]:C})},[e,t]),b=u.useCallback(_=>{const C={...e};delete C[_],t(C)},[e,t]),x=u.useCallback((_,C,E)=>{const S={...e};_&&_!==C&&delete S[_],S[C]=E,t(S)},[e,t]),k=u.useCallback(_=>{const C=kd(_,{});let E=_.id,S=1;for(;E in e;)E=`${_.id}${++S}`;t({...e,[E]:C}),y(!1)},[e,t]),w=u.useCallback(()=>{!g||!g.key||(t({...e,[g.key]:Ls(g)}),m(null),y(!1))},[g,e,t]);return i.jsxs("div",{className:"g7le-computed-form","data-testid":"g7le-computed-form",style:O1,children:[i.jsx("p",{style:B1,children:o("layout_editor.page_settings.computed.heading")}),h.length>0?h.map(_=>i.jsx(M1,{computedKey:_,expr:e[_],recipes:p,rawRecipes:n,t:o,sampleContext:r,dataSourceCandidates:s,bindingCandidates:a,source:l[_],isEffect:d.includes(_),existingKeys:h,onPatchExpr:C=>v(_,C),onRename:(C,E)=>x(_,C,E),onRemove:()=>b(_),onRevert:c?()=>c(_):void 0},_)):i.jsx("p",{"data-testid":"g7le-computed-empty",style:aS,children:o("layout_editor.computed.empty")}),i.jsxs("div",{style:{minWidth:0},children:[i.jsxs("button",{type:"button","data-testid":"g7le-computed-add",onClick:()=>y(_=>!_),style:R1,children:["+ ",o("layout_editor.computed.add")," ▾"]}),f?i.jsxs("div",{"data-testid":"g7le-computed-add-list",style:eS,children:[["common","more"].map(_=>{const C=p.filter(E=>(E.group??"more")===_);return C.length===0?null:i.jsxs("div",{children:[i.jsxs("div",{style:tS,children:["━━ ",o(`layout_editor.computed.group_${_}`)," ━━"]}),C.map(E=>{const S=N1(n?.[E.id]);return i.jsxs("button",{type:"button","data-testid":`g7le-computed-preset-${E.id}`,onClick:()=>k(E),style:nS,children:[i.jsx("span",{style:oS,children:Ps(E.label,o,E.id)}),S&&S.kind!=="core"?i.jsxs("span",{"data-testid":`g7le-computed-preset-source-${E.id}`,style:rS,children:["〔",S.id??S.kind,"〕"]}):null]},E.id)})]},_)}),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:iS,children:["⚙ ",o("layout_editor.computed.custom_open")," ▾"]}),g?i.jsxs("div",{style:{marginTop:6},children:[i.jsx(lu,{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(au,{expr:Ls(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:w,style:sS,children:o("layout_editor.computed.custom_add")})]}):null]})]}):null]})]})}function M1({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:y,onRemove:g,onRevert:m}){const[h,v]=u.useState(!1),[b,x]=u.useState(!1),k=u.useMemo(()=>Ed(t,n),[t,n]),w=d==="base",_=d==="route-override",C=k.kind==="advanced",E=k.kind==="preset"?n.find($=>$.id===k.recipeId)??null:null,S=E?Ps(E.label,r,e):e,T=($,A)=>{if(k.kind!=="preset"||!E)return;const z={...k.params,[$]:A};f(kd(E,z))};return i.jsxs("div",{"data-testid":`g7le-computed-item-${e}`,style:W1,children:[i.jsxs("div",{style:j1,children:[i.jsx("span",{style:H1,children:S}),i.jsx("code",{style:F1,children:e}),w?i.jsxs("span",{"data-testid":`g7le-computed-source-${e}`,style:K1,children:["〔",r("layout_editor.computed.source_base"),"〕"]}):null,_?i.jsxs("span",{"data-testid":`g7le-computed-overridden-${e}`,style:V1,children:["〔",r("layout_editor.computed.source_overridden"),"〕"]}):null,C?i.jsxs("span",{"data-testid":"g7le-computed-advanced",style:U1,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:()=>x($=>!$),style:Os,"aria-label":r("layout_editor.value_tree.show_source"),title:r("layout_editor.value_tree.show_source"),children:""}),C?null:i.jsx("button",{type:"button","data-testid":`g7le-computed-edit-${e}`,onClick:()=>v($=>!$),style:Os,children:r("layout_editor.init_actions.edit")}),i.jsx("button",{type:"button","data-testid":`g7le-computed-remove-${e}`,onClick:g,style:Os,"aria-label":r("layout_editor.init_actions.remove"),children:"✕"})]}),b?i.jsx("pre",{"data-testid":`g7le-computed-code-block-${e}`,style:lS,children:t}):null,i.jsx("div",{"data-testid":`g7le-computed-preview-${e}`,children:i.jsx(au,{expr:t,computedKey:e,sampleContext:s,t:r,isEffect:c,testIdPrefix:`g7le-computed-preview-${e}-eval`})}),_&&m?i.jsxs("div",{style:q1,children:[i.jsxs("span",{style:G1,children:["ⓘ ",r("layout_editor.computed.overridden_hint")]}),i.jsx("button",{type:"button","data-testid":`g7le-computed-revert-${e}`,onClick:m,style:Y1,children:r("layout_editor.computed.revert")})]}):null,h&&!C?i.jsxs("div",{style:X1,children:[w?i.jsxs("p",{"data-testid":`g7le-computed-override-notice-${e}`,style:J1,children:["⚠ ",r("layout_editor.computed.override_notice")]}):null,k.kind==="preset"&&E?i.jsx(i.Fragment,{children:E.params.map($=>i.jsx(P1,{param:$,value:k.params[$.key]??"",t:r,dataSourceCandidates:a,bindingCandidates:l,onChange:A=>T($.key,A)},$.key))}):k.kind==="custom"?i.jsx(lu,{model:{...k.model,key:e},onChange:$=>y($.key,Ls($)),t:r,dataSourceCandidates:a,bindingCandidates:l,existingKeys:p.filter($=>$!==e)}):null]}):null]})}const L1=new Set(["datasource-picker","binding-picker","select","toggle","state-key-picker","page-picker"]);function P1({param:e,value:t,t:n,dataSourceCandidates:o,bindingCandidates:r,onChange:s}){const a=Ps(e.label,n,e.key),l=e.widget??"",c=L1.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:Z1,children:[i.jsx("span",{style:Q1,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(Ve,{value:t,onChange:f=>s(f),t:n,candidates:r,testidPrefix:`g7le-computed-param-${e.key}-chip`})})]})}const O1={display:"flex",flexDirection:"column",gap:12,minWidth:0},B1={margin:0,fontSize:13,fontWeight:700,color:"#0f172a"},W1={border:"1px solid #e2e8f0",borderRadius:8,padding:"8px 10px",display:"flex",flexDirection:"column",gap:6,background:"#f8fafc"},j1={display:"flex",alignItems:"center",gap:6},H1={fontSize:13,fontWeight:600,color:"#0f172a"},F1={fontSize:10,color:"#64748b",fontFamily:"monospace"},K1={fontSize:10,color:"#0891b2",whiteSpace:"nowrap"},V1={fontSize:10,color:"#7c3aed",whiteSpace:"nowrap"},U1={fontSize:10,color:"#92400e",whiteSpace:"nowrap"},q1={display:"flex",alignItems:"center",gap:8,marginTop:4,minWidth:0},G1={fontSize:11,color:"#7c3aed",flex:1,minWidth:0},Y1={border:"1px solid #c4b5fd",borderRadius:6,background:"#f5f3ff",color:"#6d28d9",cursor:"pointer",fontSize:11,padding:"2px 8px",whiteSpace:"nowrap"},Os={border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",fontSize:11,padding:"2px 6px"},X1={display:"flex",flexDirection:"column",gap:6,paddingTop:6,borderTop:"1px dashed #e2e8f0"},J1={margin:0,fontSize:11,color:"#b45309",background:"#fef3c7",padding:"6px 8px",borderRadius:6},Z1={display:"flex",alignItems:"center",gap:8,minWidth:0},Q1={fontSize:11,color:"#64748b",minWidth:90},R1={padding:"6px 12px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},eS={marginTop:6,border:"1px solid #cbd5e1",borderRadius:8,background:"#fff",padding:8,maxHeight:380,overflowY:"auto"},tS={fontSize:11,fontWeight:700,color:"#94a3b8",padding:"6px 4px 2px"},nS={display:"flex",alignItems:"center",gap:6,width:"100%",textAlign:"left",padding:"6px 8px",fontSize:12,border:"none",background:"transparent",cursor:"pointer",borderRadius:6},oS={flex:1,minWidth:0,color:"#0f172a"},rS={fontSize:10,color:"#64748b",whiteSpace:"nowrap"},iS={padding:"6px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},sS={marginTop:6,padding:"6px 12px",fontSize:12,border:"1px solid #3b82f6",borderRadius:6,background:"#3b82f6",color:"#fff",cursor:"pointer"},aS={margin:0,fontSize:12,color:"#94a3b8"},lS={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 dS(e,t){return t==="any"?!0:e===null||typeof e!="object"?!1:t==="object"?!Array.isArray(e):!0}function Bs({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:y,validate:g}){const[m,h]=u.useState(()=>jr(e)),[v,b]=u.useState(null),x=u.useRef(!1),k=u.useRef(e);u.useEffect(()=>{if(!x.current&&!Object.is(e,k.current)){if(jr(e)===jr(k.current)){k.current=e;return}h(jr(e)),b(null),k.current=e,n?.(!0)}},[e]);const w=_=>{if(x.current=!0,h(_),_.trim()===""){b(null),k.current=s,n?.(!0),t(s);return}let C;try{C=JSON.parse(_)}catch{b(o(p??"layout_editor.json_block.invalid")),n?.(!1);return}if(!dS(C,r)){b(o(c??"layout_editor.json_block.invalid")),n?.(!1);return}const E=g?.(C)??null;if(E){b(E),n?.(!1);return}b(null),k.current=C,n?.(!0),t(C)};return i.jsxs("div",{className:"g7le-json-block",style:cS,children:[i.jsx("textarea",{id:y,"data-testid":d,style:{...uS,minHeight:l},value:m,spellCheck:!1,"aria-label":f,"aria-invalid":v?!0:void 0,placeholder:a,onChange:_=>w(_.target.value),onBlur:()=>{x.current=!1}}),v?i.jsx("div",{"data-testid":`${d}-error`,style:pS,children:v}):null]})}function jr(e){if(e===void 0)return"";try{return JSON.stringify(e,null,2)??""}catch{return""}}const cS={display:"flex",flexDirection:"column",gap:4,minWidth:0},uS={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"},pS={fontSize:11,color:"#dc2626"},fS=[{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"}],Ws={local:"initLocal",global:"initGlobal",isolated:"initIsolated"};function gS({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,y=e?.state&&typeof e.state=="object"?e.state:void 0;if(!(!f&&!y))return{...y??{},...f??{}}},[t,e]),{initLocal:a,migrated:l}=u.useMemo(()=>Pw({initLocal:e?.initLocal,state:s}),[e,s]),d=f=>{if(f==="local")return a;const y=e?.[Ws[f]];return y&&typeof y=="object"?y:{}},c=f=>{if(f==="local"){const y=t?.initLocal??{},g=s?Object.keys(s):[];return Array.from(new Set([...Object.keys(y),...g]))}return Object.keys(t?.[Ws[f]]??{})},p=u.useCallback((f,y)=>{const g=Ws[f];f==="local"&&l&&n("state",void 0),n(g,Object.keys(y).length===0?void 0:y)},[n,l]);return i.jsxs("div",{className:"g7le-initstate-form","data-testid":"g7le-initstate-form",style:yS,children:[i.jsx("p",{style:bS,children:o("layout_editor.page_settings.initstate.heading")}),l?i.jsxs("p",{"data-testid":"g7le-initstate-legacy-state",style:mS,children:["ⓘ ",o("layout_editor.initstate.legacy_state")]}):null,i.jsx(js,{scope:"local",label:o("layout_editor.initstate.section_local"),value:d("local"),ownKeys:c("local"),patchSection:p,t:o}),i.jsx(js,{scope:"global",label:o("layout_editor.initstate.section_global"),value:d("global"),ownKeys:c("global"),patchSection:p,t:o}),i.jsx(js,{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:PS,children:["ⓘ ",o("layout_editor.initstate.isolated_dynamic_hint")]})]})}function js({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"),[y,g]=u.useState(null),[m,h]=u.useState(!1),v=Object.keys(o),b=v,x=(_,C)=>{s(e,{...o,[_]:C})},k=_=>{const C={...o};delete C[_],s(e,C)},w=()=>{const _=d.trim();if(!_){g(a("layout_editor.initstate.name_required"));return}if(!Is(_)){g(a("layout_editor.initstate.name_invalid"));return}if(_ in o){g(a("layout_editor.initstate.name_duplicate"));return}const C={string:"",number:0,boolean:!1,null:null,list:[],object:{}};s(e,{...o,[_]:C[p]}),c(""),g(null)};return i.jsxs("div",{"data-testid":`g7le-initstate-section-${e}`,style:vS,children:[i.jsxs("div",{style:_S,children:[i.jsx("div",{style:xS,children:t}),i.jsx("button",{type:"button","data-testid":`g7le-initstate-${e}-mode-toggle`,onClick:()=>h(_=>!_),style:kS,children:a(m?"layout_editor.json_block.mode_block":"layout_editor.json_block.mode_code")})]}),n?i.jsxs("p",{style:wS,children:["ⓘ ",n]}):null,m?i.jsx(Bs,{value:o,shape:"object",emptyValue:{},onChange:_=>s(e,_??{}),t:a,testidPrefix:`g7le-initstate-${e}-code`,placeholder:`{ "keyword": "", "page": 1 }`,shapeErrorKey:"layout_editor.json_block.must_be_object",validate:_=>{const C=Object.keys(_??{}).filter(E=>!Is(E));return C.length?a("layout_editor.json_block.invalid_keys",{keys:C.join(", ")}):null}}):i.jsxs(i.Fragment,{children:[v.length===0?i.jsx("p",{"data-testid":`g7le-initstate-${e}-empty`,style:LS,children:a("layout_editor.initstate.no_values")}):v.map(_=>{const E=Lw(b,r,_)==="inherited",S=e==="isolated"&&l[_];return i.jsx(hS,{scope:e,itemKey:_,value:o[_],inherited:E,isOrphan:!!S,onChangeValue:T=>x(_,T),onRemove:()=>k(_),t:a},_)}),i.jsxs("div",{style:AS,children:[i.jsx("input",{type:"text","data-testid":`g7le-initstate-${e}-add-name`,value:d,placeholder:a("layout_editor.initstate.value_name"),onChange:_=>{c(_.target.value),y&&g(null)},onKeyDown:_=>{_.key==="Enter"&&(_.preventDefault(),w())},"aria-invalid":y?!0:void 0,style:{...TS,...y?DS:null}}),i.jsx("select",{"data-testid":`g7le-initstate-${e}-add-kind`,value:p,onChange:_=>f(_.target.value),"aria-label":a("layout_editor.initstate.value_kind"),style:zS,children:fS.map(_=>i.jsx("option",{value:_.kind,children:a(_.labelKey)},_.kind))}),i.jsxs("button",{type:"button","data-testid":`g7le-initstate-${e}-add`,onClick:w,style:MS,children:["+ ",a("layout_editor.initstate.add_value")]})]}),y?i.jsx("p",{"data-testid":`g7le-initstate-${e}-add-error`,style:NS,children:y}):null]})]})}function hS({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:SS,children:[i.jsxs("div",{style:CS,children:[o?i.jsx("span",{"data-testid":`g7le-initstate-inherited-${t}`,style:$S,children:"🔗"}):null,i.jsx("code",{style:ES,children:t}),i.jsx("span",{style:{flex:1}}),i.jsx("button",{type:"button","data-testid":`g7le-initstate-code-${t}`,onClick:()=>c(f=>!f),style:Hs,"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:Hs,children:l("layout_editor.initstate.revert")}):i.jsx("button",{type:"button","data-testid":`g7le-initstate-remove-${t}`,onClick:a,style:Hs,"aria-label":l("layout_editor.init_actions.remove"),children:"✕"})]}),d?i.jsx("pre",{"data-testid":`g7le-initstate-code-block-${t}`,style:OS,children:p}):null,i.jsx(Nn,{value:n,onChange:s,t:l,path:t,scope:e}),r?i.jsxs("p",{"data-testid":`g7le-initstate-isolated-orphan-${t}`,style:IS,children:["⚠ ",l("layout_editor.initstate.isolated_orphan")]}):null]})}const yS={display:"flex",flexDirection:"column",gap:14,minWidth:0},bS={margin:0,fontSize:13,fontWeight:700,color:"#0f172a"},mS={margin:0,fontSize:11,color:"#1d4ed8",background:"#eff6ff",padding:"6px 8px",borderRadius:6},vS={display:"flex",flexDirection:"column",gap:8,padding:10,border:"1px solid #e2e8f0",borderRadius:10,minWidth:0},_S={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},xS={fontSize:12,fontWeight:700,color:"#475569"},wS={margin:0,fontSize:11,color:"#94a3b8"},kS={padding:"2px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},SS={display:"flex",flexDirection:"column",gap:4,padding:"6px 8px",border:"1px solid #f1f5f9",borderRadius:6,minWidth:0},CS={display:"flex",alignItems:"center",gap:6},$S={fontSize:12},ES={fontSize:12,color:"#0f172a",fontFamily:"monospace"},Hs={border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",fontSize:11,padding:"2px 6px"},IS={margin:0,fontSize:11,color:"#b45309",background:"#fef3c7",padding:"4px 6px",borderRadius:6},AS={display:"flex",gap:6,alignItems:"center"},TS={padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},DS={border:"1px solid #dc2626"},NS={margin:0,fontSize:11,color:"#dc2626"},zS={padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#0f172a"},MS={padding:"2px 10px",fontSize:11,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},LS={margin:0,fontSize:12,color:"#94a3b8"},PS={margin:0,fontSize:11,color:"#94a3b8"},OS={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"},BS={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 Fs({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,y)=>{t({...e,[f]:y})},[e,t]),p=u.useCallback(f=>{const y={...e};delete y[f],t(y)},[e,t]);return i.jsx("div",{className:l,"data-testid":l,children:d.map(f=>{const y=e[f],g=y!==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(BS[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,y,h=>c(f,h)):i.jsx("pre",{"data-testid":`${l}-json-${f}`,style:{margin:0,fontSize:12,color:"#475569"},children:g?JSON.stringify(y):""})})]},f)})})}function WS(e){return[...e.filter(n=>n!=="maintenance"),"default"]}function jS({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(()=>wo(a),[a]),y=u.useMemo(()=>WS(o),[o]),g=f.length>0,m=u.useMemo(()=>jl("error",n),[n]),h=u.useMemo(()=>({pageCandidates:l,dataSourceCandidates:c,stateKeyCandidates:p,modalCandidates:d,bindingCandidates:m}),[l,c,p,d,m]),v=u.useCallback(b=>r.includes(b)?"self":b in e?"inherited":s.includes(b)?"template":"none",[r,e,s]);return g?i.jsxs("div",{className:"g7le-error-form","data-testid":"g7le-error-form",style:du,children:[i.jsx("p",{style:cu,children:n("layout_editor.page_settings.error.heading")}),i.jsxs("p",{style:FS,children:["ⓘ ",n("layout_editor.error.intro")]}),i.jsx(Fs,{value:e,onChange:t,t:n,codes:y,mode:"badge",sourceOf:v,testIdPrefix:"g7le-error-rows",renderActionList:(b,x,k)=>i.jsx(HS,{code:b,action:x,recipes:a,normalized:f,t:n,pools:h,onPatch:k})})]}):i.jsxs("div",{className:"g7le-error-form","data-testid":"g7le-error-form",style:du,children:[i.jsx("p",{style:cu,children:n("layout_editor.page_settings.error.heading")}),i.jsxs("p",{"data-testid":"g7le-error-degrade",style:KS,children:["ⓘ ",n("layout_editor.error.degrade")]}),i.jsx(Fs,{value:e,onChange:t,t:n,codes:y,mode:"badge",sourceOf:v,testIdPrefix:"g7le-error-rows"})]})}function HS({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(x=>x.id===p)??null,y=c?Yn(c,o):null,g=y?.kind==="preset"?y.values:{},m=p==="sequence"||p==="parallel",h=x=>{if(x===""){a({});return}const k=o.find(w=>w.id===x);k&&a(xr(k,{}))},v=["","showErrorPage","navigate","openModal","toast","setState","sequence","parallel"],b=m&&c?Array.isArray(c.params?.actions)?c.params.actions:[]:[];return i.jsxs("div",{"data-testid":`g7le-error-action-${e}`,style:VS,children:[i.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6},children:[i.jsx("select",{"data-testid":`g7le-error-handler-${e}`,value:p,onChange:x=>h(x.target.value),style:{...US,flex:1},children:v.map(x=>i.jsx("option",{value:x,children:r(x===""?"layout_editor.error.handler_none":`layout_editor.error.handler_${x}`)},x))}),p!==""?i.jsx("button",{type:"button","data-testid":`g7le-error-code-${e}`,onClick:()=>d(x=>!x),"aria-label":r("layout_editor.action_list.view_code"),title:r("layout_editor.action_list.view_code"),style:l?qS:uu,children:""}):null]}),m?i.jsx("div",{"data-testid":`g7le-error-actions-${e}`,children:i.jsx(Gt,{actions:b,onChange:x=>a({handler:p,params:{actions:x}}),t:r,recipes:n,candidatePools:s,chipContext:"error",testIdPrefix:`g7le-error-seq-${e}`})}):f&&c?i.jsx(Ts,{raw:c,recipe:f,values:g,t:r,pools:s,onChange:x=>a(x),testIdPrefix:`g7le-error-action-${e}-edit`}):null,l&&c?i.jsx("pre",{"data-testid":`g7le-error-code-view-${e}`,style:GS,children:JSON.stringify(t,null,2)}):null]})}const du={display:"flex",flexDirection:"column",gap:12,minWidth:0},cu={margin:0,fontSize:13,fontWeight:700,color:"#0f172a"},FS={margin:0,fontSize:11,color:"#94a3b8"},KS={margin:0,fontSize:12,color:"#b45309",background:"#fef3c7",padding:"8px 10px",borderRadius:6},VS={display:"flex",flexDirection:"column",gap:6,minWidth:0},US={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},uu={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"},qS={...uu,background:"#0f172a",borderColor:"#0f172a",color:"#e2e8f0"},GS={margin:"4px 0 0",padding:8,background:"#0f172a",color:"#e2e8f0",borderRadius:6,fontSize:12,overflow:"auto",fontFamily:"ui-monospace, monospace"};function Hr(e){const t=e.trim(),n=/^\{\{([\s\S]*)\}\}$/.exec(t);return n?n[1].trim():t}function YS(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:Hr(o.expr),aliases:pu(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:Hr(s.expr),aliases:pu(s.aliases)})}return n}function pu(e){if(!Array.isArray(e))return[];const t=[];for(const n of e){if(typeof n!="string")continue;const o=Hr(n);o.trim().length>0&&t.push(o)}return t}function JS(e){const t=e.params.length*1e3;return Fr(e.expr).replace(/\{\w+\}/g,"").length-t}function ZS(e){return e.map((t,n)=>({op:t,idx:n,score:JS(t)})).sort((t,n)=>n.score-t.score||t.idx-n.idx).map(t=>t.op)}function QS(e,t){return e.replace(/\{(\w+)\}/g,(n,o)=>{const r=t[o];return r===void 0?n:r})}function RS(e,t){const n=t.find(o=>o.value===e.operator);return n?QS(n.expr,e.params??{}):null}function fu(e,t,n){const o=e.map(a=>RS(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 gu(e,t){const n=Fr(e);for(const o of ZS(t)){if(o.params.length===0){for(const r of[o.expr,...o.aliases])if(Fr(r)===n)return{operator:o.value,params:{}};continue}for(const r of[o.expr,...o.aliases]){const s=eC(o,r,n);if(s)return s}}return null}function eC(e,t,n){const o=t.trim(),r=[];let s="",a=0;for(;a=|<=|>|<|\?|:|\(|\)|!/.test(y))return null;return{operator:e.value,params:c}}function tC(e){const t=new Set,n=/(['"])\{(\w+)\}\1/g;let o;for(;(o=n.exec(e))!==null;)t.add(o[2]);return t}function nC(e,t){if(typeof e!="string"||e.trim()==="")return null;const n=Hr(e),o=gu(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=gu(c.trim(),t);if(!p)return null;d.push(p)}return{clauses:d,combinator:r}}const hu=Lt(),Mn=hu.responsiveManager,To=hu.BREAKPOINT_PRESETS;function yu(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 bu(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 Kr(e){return typeof e!="string"?[]:e.split(/\s+/).filter(t=>t.length>0)}function mu(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=qs(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 oC(e,t,n,o,r=!1){const s=mu(t,r),a=Kr(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(Su):l,c=[...a,...d];c.length===0?delete e.className:e.className=c.join(" ")}const Ks={url:"backgroundImage",size:"backgroundSize",repeat:"backgroundRepeat",position:"backgroundPosition"};function rC(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.keys(Ks).some(t=>t in e)}function iC(e){return/^url\(/i.test(e.trim())?e:`url(${e})`}function vu(e){const t=/^url\(\s*(['"]?)(.*?)\1\s*\)$/i.exec(e.trim());return t?t[2]:e}function sC(e){return e.includes("backgroundImage")}function Vs(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 aC(e){const t=e.backgroundImage,n=Vs(e.backgroundSize,"size"),o=Vs(e.backgroundRepeat,"repeat"),r=Vs(e.backgroundPosition,"position");let s;if(typeof t=="string"?s=vu(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"?vu(s):s),n!==void 0&&(a.size=n),o!==void 0&&(a.repeat=o),r!==void 0&&(a.position=r),a}function lC(e,t,n){const o=(r,s)=>{s==null||s===""?delete e[r]:e[r]=s};if(Array.isArray(t.props)){if(!t.values&&rC(n)){for(const r of t.props){const s=Object.keys(Ks).find(d=>Ks[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!==""?iC(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 dC(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 cC(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=yu(t),s=o.colorScheme==="dark";let a,l=!1;if(r.options){const y=r.options.find(g=>g.value===n);l=y!==void 0,a=y?.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(y=>y.apply?.type==="classToken")??!1);if(s&&!p)return e;const f=o.breakpoint!=="base"&&p?(()=>{const y=e.props??{};return typeof y.className=="string"?y.className:void 0})():void 0;return ku(e,o,(y,g)=>{if(f!==void 0&&typeof y.className!="string"&&(y.className=f),d){const m=mu(r,s),h=Kr(y.className).filter(v=>!m(v));if(h.length===0?delete y.className:y.className=h.join(" "),!s&&r.apply){const v=r.apply;if(v.type==="styleProp")for(const b of v.props??(v.prop?[v.prop]:[]))delete g[b];else v.type==="cssVar"&&v.varName?delete g[v.varName]:v.type==="propValue"&&v.propKey&&delete y[v.propKey]}}else if(a)switch(a.type){case"classToken":oC(y,r,a,n,s);break;case"styleProp":lC(g,a,n);break;case"cssVar":dC(g,a,n);break;case"propValue":cC(y,a,n);break}})}function Vr(e,t){const n=Kr(e);return t?n.filter(Yt).map(qs):n.filter(o=>!Yt(o))}function uC(e,t,n,o){const r=new Set(t.filter(l=>typeof l=="string"&&l.length>0)),s=l=>o?Yt(l)?r.has(qs(l)):!1:Yt(l)?!1:r.has(l),a=Kr(e).filter(l=>!s(l));return n&&n.length>0&&a.push(o?Su(n):n),a.join(" ").trim()}function _u(e,t,n,o){if(e.options&&e.options.some(s=>s.apply)){const s=Vr(t.className,o),a=[];for(const l of e.options)l.apply&&fC(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)&&sC(r.props)){const l=aC(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=Vr(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 xu(e){return e.style&&typeof e.style=="object"&&!Array.isArray(e.style)?e.style:{}}function Do(e,t,n=Wt){const o=yu(t),r=n.colorScheme==="dark";if(r&&!Us(o.apply)&&!o.options?.some(m=>Us(m.apply)))return{value:void 0,matched:!1,darkReadonly:!0};const s=mC(e,n),a=xu(s),l=_u(o,s,a,r);if(n.breakpoint==="base")return l;const d=l.matched?l.value:void 0,c=e.props??{},p=xu(c),f=_u(o,c,p,r),y=l.matched&&l.value!==void 0,g=y&&!pC(l.value,f.value);return{value:y?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 pC(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 fC(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 gC(e){return e==="base"?!0:Mn.parseRange(e)!==null}function wu(e){return e in To}function Ur(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 hC(e){return!!e&&typeof e=="object"&&Array.isArray(e.children)}function yC(e,t,n){let o,r,s;if(e!=="custom"&&e in To){o=e;const l=To[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(!hC(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 xC(e,t){if(t.colorScheme==="dark")return ku(e,t,l=>{const d=qr(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 Gs(e,t){if(t.colorScheme==="dark"){const c=t.breakpoint==="base"?e.props:e.responsive?.[t.breakpoint]?.props;return qr(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(qr(e.props?.className).filter(c=>!Yt(c))),d=qr(r.className).filter(c=>!Yt(c));return d.length!==l.size?!0:d.some(c=>!l.has(c))}function Cu(e,t,n=""){return typeof e!="string"?n:e.startsWith("$t:")?t(e.slice(3)):e}function $u(e,t,n){if(n.breakpoint!=="base")return _C(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 Eu({node:e,spec:t,t:n,onPatchNode:o,dataSourceCandidates:r,stateKeyCandidates:s,scope:a=Wt}){const l=u.useMemo(()=>XS(t?.conditionRecipes),[t]),d=a.breakpoint!=="base"?vC(e,a):e.if??e.props?.if,c=u.useMemo(()=>nC(d,l),[d,l]),p=c?.clauses??[],f=c?.combinator??"and",y=typeof d=="string"&&d.trim()!==""&&c===null;if(l.length===0)return i.jsx("div",{"data-testid":"g7le-condition-no-recipes",style:wC,children:n("layout_editor.visibility.no_recipes")});const g=(k,w)=>{o($u(e,fu(k,w,l),a))},m=(k,w)=>{g(p.map((_,C)=>C===k?w:_),f)},h=k=>{g(p.filter((w,_)=>_!==k),f)},v=k=>{const w=l[0];g([...p,{operator:w.value,params:{}}],k)},b=k=>{if(k==="datasource-picker")return r;if(k==="state-key-picker")return s};if(y)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:DC,children:n("layout_editor.visibility.advanced_preserved")}),i.jsx("code",{"data-testid":"g7le-condition-advanced-expr",style:Au,children:String(d)}),i.jsx("button",{type:"button","data-testid":"g7le-condition-clear-advanced",onClick:()=>o($u(e,"",a)),style:NC,children:n("layout_editor.visibility.clear")})]});const x=fu(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:kC,children:n("layout_editor.visibility.show_when")}),p.map((k,w)=>{const _=l.find(C=>C.value===k.operator)??l[0];return i.jsxs("div",{className:"g7le-condition-clause","data-testid":`g7le-condition-clause-${w}`,style:SC,children:[i.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center"},children:[w>0&&i.jsx("span",{"data-testid":`g7le-condition-combinator-${w}`,style:$C,children:n(f==="or"?"layout_editor.visibility.or":"layout_editor.visibility.and")}),i.jsx("select",{"data-testid":`g7le-condition-select-${w}`,value:k.operator,onChange:C=>m(w,{operator:C.target.value,params:{}}),style:CC,children:l.map(C=>i.jsx("option",{value:C.value,children:Cu(C.label,n,C.value)},C.value))}),i.jsx("button",{type:"button","data-testid":`g7le-condition-remove-${w}`,"aria-label":n("layout_editor.visibility.remove"),onClick:()=>h(w),style:EC,children:"✕"})]}),_.params.map(C=>{const E=Tn(C.widget);return i.jsxs("div",{className:"g7le-condition-param","data-testid":`g7le-condition-param-${w}-${C.key}`,style:IC,children:[i.jsx("span",{style:AC,children:Cu(C.label,n,C.key)}),i.jsx("div",{style:{flex:1},children:E?i.jsx(E,{control:{...C},value:k.params[C.key],onChange:S=>m(w,{operator:k.operator,params:{...k.params,[C.key]:S===void 0?"":String(S)}}),t:n,candidates:b(C.widget)}):i.jsx("span",{style:{fontSize:11,color:"#94a3b8"},children:n("layout_editor.property_modal.unsupported_widget")})})]},C.key)})]},w)}),i.jsxs("div",{style:{display:"flex",gap:6},children:[i.jsxs("button",{type:"button","data-testid":"g7le-condition-add-and",onClick:()=>v("and"),style:Iu,children:["+ ",n("layout_editor.visibility.and")]}),i.jsxs("button",{type:"button","data-testid":"g7le-condition-add-or",onClick:()=>v("or"),style:Iu,children:["+ ",n("layout_editor.visibility.or")]})]}),x!==""&&i.jsxs("div",{"data-testid":"g7le-condition-preview",style:TC,children:[i.jsx("span",{style:{fontSize:11,color:"#64748b"},children:n("layout_editor.visibility.preview")}),i.jsx("code",{style:Au,children:x})]})]})}const wC={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},kC={fontSize:12,fontWeight:600,color:"#0f172a"},SC={border:"1px solid #e2e8f0",borderRadius:8,padding:10,display:"flex",flexDirection:"column",gap:8,background:"#f8fafc"},CC={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff"},$C={fontSize:11,fontWeight:700,color:"#2563eb",background:"#dbeafe",padding:"2px 8px",borderRadius:999},EC={border:"none",background:"transparent",color:"#94a3b8",cursor:"pointer",fontSize:12},Iu={padding:"5px 12px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},IC={display:"flex",alignItems:"center",gap:8},AC={fontSize:11,color:"#64748b",minWidth:64},TC={display:"flex",flexDirection:"column",gap:4,padding:10,background:"#f1f5f9",borderRadius:6},Au={fontSize:11,color:"#0f172a",fontFamily:"monospace",wordBreak:"break-all"},DC={fontSize:11,color:"#92400e",background:"#fef3c7",padding:"6px 8px",borderRadius:6},NC={padding:"5px 12px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer",alignSelf:"flex-start"};function zC(e){return typeof e=="string"?e:e===void 0?"":JSON.stringify(e)}function MC(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 Tu(e){return!e||typeof e!="object"||Array.isArray(e)?[]:Object.entries(e).map(([t,n])=>({key:t,value:zC(n)}))}function Ys(e){const t={};for(const n of e){const o=n.key.trim();o!==""&&(t[o]=MC(n.value))}return t}function Du(e){return!e||typeof e!="object"||Array.isArray(e)?!1:Object.values(e).some(t=>t!==null&&typeof t=="object")}function LC(e){const t={};return typeof e.if=="string"&&e.if.trim().length>0&&(t.if=e.if),t}function PC(e,t){const n={...t},o=e.if;return typeof o=="string"&&o.trim().length>0?n.if=o:delete n.if,n}const OC=["api","static","route_params","query_params","websocket"],BC=["GET","POST","PUT","PATCH","DELETE"],WC=["none","optional","required"],jC=["progressive","blocking","background"],HC=["application/json","multipart/form-data"],FC=["public","private","presence"];function KC(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 VC(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:Tu(e.params),paramsRaw:Du(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 UC(){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 qC(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=Ys(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"},Nu={...rn,background:"#2563eb",borderColor:"#2563eb",color:"#ffffff",fontWeight:600},zo={marginTop:12,padding:10,border:"1px solid #e2e8f0",borderRadius:8,background:"#f8fafc"},Mo={fontSize:12,fontWeight:700,color:"#475569",marginBottom:8},GC={margin:"0 0 6px",fontSize:11,color:"#94a3b8"},zu={marginTop:8},Mu={alignSelf:"flex-start",padding:"2px 0",fontSize:11,border:"none",background:"none",color:"#64748b",cursor:"pointer"},Lu={margin:0,padding:8,background:"#0f172a",color:"#e2e8f0",borderRadius:6,fontSize:11,lineHeight:1.5,overflow:"auto",fontFamily:"ui-monospace, monospace"};function YC({code:e,action:t,recipes:n,pools:o,t:r,onPatch:s}){const[a,l]=u.useState(!1),d=u.useMemo(()=>wo(n),[n]),c=Array.isArray(t)?t[0]:t,p=typeof c?.handler=="string"?c.handler:"",f=d.find(x=>x.id===p)??null,y=c?Yn(c,d):null,g=y?.kind==="preset"?y.values:{},m=p==="sequence"||p==="parallel",h=["","showErrorPage","navigate","openModal","toast","setState","sequence","parallel"],v=x=>{if(x===""){s({});return}const k=d.find(w=>w.id===x);s(k?xr(k,{}):{handler:x})},b=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:x=>v(x.target.value),children:h.map(x=>i.jsx("option",{value:x,children:r(x===""?"layout_editor.error.handler_none":`layout_editor.error.handler_${x}`)},x))}),p!==""?i.jsx("button",{type:"button","data-testid":`g7le-ds-eh-code-${e}`,onClick:()=>l(x=>!x),"aria-label":r("layout_editor.action_list.view_code"),title:r("layout_editor.action_list.view_code"),style:a?XC:Pu,children:""}):null]}),m?i.jsx("div",{"data-testid":`g7le-ds-eh-actions-${e}`,children:i.jsx(Gt,{actions:b,onChange:x=>s({handler:p,params:{actions:x}}),t:r,recipes:n,candidatePools:o,chipContext:"error",testIdPrefix:`g7le-ds-eh-seq-${e}`})}):f&&c?i.jsx(Ts,{raw:c,recipe:f,values:g,t:r,pools:o,onChange:x=>s(x),testIdPrefix:`g7le-ds-eh-action-${e}-edit`}):null,a&&c?i.jsx("pre",{"data-testid":`g7le-ds-eh-code-view-${e}`,style:JC,children:JSON.stringify(t,null,2)}):null]})}const Pu={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"},XC={...Pu,background:"#0f172a",borderColor:"#0f172a",color:"#e2e8f0"},JC={margin:"4px 0 0",padding:8,background:"#0f172a",color:"#e2e8f0",borderRadius:6,fontSize:12,overflow:"auto",fontFamily:"ui-monospace, monospace"};function ZC({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 y=o??n,g=u.useMemo(()=>KC(e),[e]),m=g.inherited,[h,v]=u.useState(g.own),[b,x]=u.useState(null),[k,w]=u.useState(null),[_,C]=u.useState(!1),[E,S]=u.useState(!1),[T,$]=u.useState(()=>new Set),A=u.useCallback(I=>{$(P=>{const F=new Set(P);return F.has(I)?F.delete(I):F.add(I),F})},[]),z=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]),O=u.useCallback(()=>{w(null),x(UC())},[]),M=u.useCallback((I,P)=>{w(null),x(VC(I,P))},[]),B=u.useCallback(I=>{const P=h.filter((F,G)=>G!==I);D(P)},[h,D]),N=u.useCallback(()=>{x(null),w(null)},[]),H=u.useCallback(()=>{if(!b)return;const I=new Set;h.forEach((V,Y)=>{Y!==b.index&&typeof V.id=="string"&&I.add(V.id)}),m.forEach(V=>{typeof V.id=="string"&&I.add(V.id)});const P=b.index>=0?h[b.index]??null:null,F=qC(b,P,I,n);if("error"in F){w(F.error);return}const G=b.index>=0?h.map((V,Y)=>Y===b.index?F.entry:V):[...h,F.entry];D(G),x(null),w(null)},[b,h,m,D,n]),L=b?.type==="api"||b?.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:[b&&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:b.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:b.id,onChange:I=>x({...b,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(vt,{value:b.label_key,onChange:I=>x({...b,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:b.type,onChange:I=>x({...b,type:I.target.value}),children:OC.map(I=>i.jsx("option",{value:I,children:n(`layout_editor.data_sources.ds_type.${I}`)},I))})]}),L&&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(Ve,{value:b.endpoint,onChange:I=>x({...b,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:b.method,onChange:I=>x({...b,method:I.target.value}),children:BC.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:b.auth_mode,onChange:I=>x({...b,auth_mode:I.target.value}),children:WC.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:b.loading_strategy,onChange:I=>x({...b,loading_strategy:I.target.value}),children:jC.map(I=>i.jsx("option",{value:I,children:n(`layout_editor.data_sources.loading_strategy.${I}`)},I))})]}),b.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:b.contentType||"application/json",onChange:I=>x({...b,contentType:I.target.value}),children:HC.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:b.auto_fetch,onChange:I=>x({...b,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:b.refetchOnMount,onChange:I=>x({...b,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(b.paramsRaw){if(b.paramsRawValid){const I=b.paramsRawValue;I&&typeof I=="object"&&!Array.isArray(I)&&!Du(I)&&x({...b,paramsRaw:!1,paramRows:Tu(I)})}}else{const I=Ys(b.paramRows);x({...b,paramsRaw:!0,paramsRawValue:I,paramsRawValid:!0})}},style:{...rn,padding:"2px 8px",fontSize:11},children:b.paramsRaw?n("layout_editor.data_sources.field.params_mode_block"):n("layout_editor.data_sources.field.params_mode_code")})]}),b.paramsRaw?i.jsx(Bs,{id:"g7le-ds-params",value:b.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=>x(P=>P&&{...P,paramsRawValue:I??{},paramsRawValid:!0}),onValidityChange:I=>x(P=>P&&{...P,paramsRawValid:I})}):i.jsxs("div",{"data-testid":"g7le-data-sources-field-params",children:[b.paramRows.length===0&&i.jsx("p",{"data-testid":"g7le-ds-params-empty",style:GC,children:n("layout_editor.data_sources.field.params_empty")}),i.jsx(zr,{value:b.paramRows.map(I=>({key:I.key,value:I.value})),onChange:I=>x({...b,paramRows:I.map(P=>({key:P.key??"",value:P.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=Ys(b.paramRows);return Object.keys(I).length===0?null:i.jsxs("div",{style:zu,children:[i.jsxs("button",{type:"button","data-testid":"g7le-ds-params-preview-toggle","aria-expanded":_,onClick:()=>C(P=>!P),style:Mu,children:[_?"▴":"▾"," ",n("layout_editor.data_sources.field.params_preview")]}),_&&i.jsx("pre",{"data-testid":"g7le-ds-params-preview",style:{...Lu,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")}),b.fallbackEnabled?i.jsxs("div",{"data-testid":"g7le-data-sources-field-fallback",style:{display:"flex",flexDirection:"column",gap:6},children:[i.jsx(Nn,{value:b.fallbackValue===void 0?{}:b.fallbackValue,onChange:I=>x({...b,fallbackValue:I}),t:n,path:"fallback",scope:"ds-fallback",renderStringLeaf:I=>i.jsx(Ve,{value:I.value,onChange:I.onChange,t:n,candidates:d,testidPrefix:I.testidPrefix})}),(()=>{const I=b.fallbackValue===void 0?{}:b.fallbackValue;return i.jsxs("div",{style:zu,children:[i.jsxs("button",{type:"button","data-testid":"g7le-ds-fallback-preview-toggle","aria-expanded":E,onClick:()=>S(P=>!P),style:Mu,children:[E?"▴":"▾"," ",n("layout_editor.data_sources.field.fallback_preview")]}),E&&i.jsx("pre",{"data-testid":"g7le-ds-fallback-preview",style:{...Lu,marginTop:4},children:JSON.stringify(I,null,2)})]})})(),i.jsx("button",{type:"button","data-testid":"g7le-data-sources-field-fallback-clear",onClick:()=>x({...b,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:()=>x({...b,fallbackEnabled:!0,fallbackValue:{}}),style:{...rn,padding:"4px 10px",display:"block"},children:["+ ",n("layout_editor.data_sources.field.fallback_add")]})]}),b.type==="websocket"&&i.jsxs("div",{"data-testid":"g7le-ds-ws-section",style:zo,children:[i.jsx("div",{style:Mo,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:b.channel,onChange:I=>x({...b,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:b.event,onChange:I=>x({...b,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:b.channel_type,onChange:I=>x({...b,channel_type:I.target.value}),children:FC.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:b.target_source,onChange:I=>x({...b,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!==b.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:b.onReceive,onChange:I=>x({...b,onReceive:I}),t:n,recipes:s,candidatePools:z,chipContext:"payload",actionChipCandidates:l?.actionChipCandidates??null,testIdPrefix:"g7le-ds-onreceive-list"})})]})]}),i.jsxs("div",{style:zo,children:[i.jsx("div",{style:Mo,children:n("layout_editor.data_sources.section.on_success")}),i.jsx("div",{"data-testid":"g7le-ds-onsuccess",children:i.jsx(Gt,{actions:b.onSuccess,onChange:I=>x({...b,onSuccess:I}),t:n,recipes:s,candidatePools:z,chipContext:"response",actionChipCandidates:l?.actionChipCandidates??null,testIdPrefix:"g7le-ds-onsuccess-list"})})]}),i.jsxs("div",{style:zo,children:[i.jsx("div",{style:Mo,children:n("layout_editor.data_sources.section.on_error")}),i.jsx("div",{"data-testid":"g7le-ds-onerror",children:i.jsx(Gt,{actions:b.onError,onChange:I=>x({...b,onError:I}),t:n,recipes:s,candidatePools:z,chipContext:"error",actionChipCandidates:l?.actionChipCandidates??null,testIdPrefix:"g7le-ds-onerror-list"})})]}),i.jsxs("div",{style:zo,children:[i.jsx("div",{style:Mo,children:n("layout_editor.data_sources.section.error_handling")}),i.jsxs("div",{"data-testid":"g7le-ds-errorhandling",children:[i.jsx(Fs,{value:b.errorHandling,onChange:I=>x({...b,errorHandling:I}),t:n,mode:"local",testIdPrefix:"g7le-ds-eh",renderActionList:(I,P,F)=>i.jsx(YC,{code:I,action:P,recipes:a,pools:z,t:n,onPatch:F})}),i.jsxs("button",{type:"button","data-testid":"g7le-ds-errorhandling-add",onClick:()=>{const I=Object.keys(b.errorHandling),P=["403","404","500","422","default"].find(F=>!I.includes(F))??"default";x({...b,errorHandling:{...b.errorHandling,[P]:{handler:"toast"}}})},style:{...rn,padding:"4px 10px",marginTop:6},children:["+ ",n("layout_editor.data_sources.add_error_code")]})]})]}),i.jsxs("div",{style:zo,children:[i.jsx("div",{style:Mo,children:n("layout_editor.data_sources.section.load_condition")}),i.jsx("div",{"data-testid":"g7le-ds-loadcondition",children:i.jsx(Eu,{node:LC({if:b.if||void 0}),spec:l??null,t:n,dataSourceCandidates:p,stateKeyCandidates:f,onPatchNode:I=>{const P=PC(I,{});x({...b,if:typeof P.if=="string"?P.if:""})}})})]})]}),!b&&i.jsxs("button",{type:"button","data-testid":"g7le-data-sources-add",onClick:O,style:{...Nu,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&&!b&&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,P)=>{const F=typeof I.id=="string"?I.id:`#${P}`,G=typeof I.endpoint=="string"?I.endpoint:"",V=typeof I.label_key=="string"?I.label_key:"",Y=rs(I,y);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:Y??F}),Y&&i.jsx("span",{"data-testid":"g7le-data-sources-item-id",style:{fontSize:11,fontWeight:400,color:"#94a3b8"},children:F}),(()=>{const Z=is(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})()]}),G&&i.jsx("div",{style:{fontSize:11,color:"#94a3b8",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:G}),!V&&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,P),style:{...rn,padding:"4px 10px"},children:n("layout_editor.data_sources.edit")}),i.jsx("button",{type:"button","data-testid":"g7le-data-sources-remove",onClick:()=>B(P),style:{...rn,padding:"4px 10px",color:"#dc2626",borderColor:"#fecaca"},children:n("layout_editor.data_sources.remove")})]},`${F}-${P}`)})]}),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,P)=>{const F=typeof I.id=="string"?I.id:`#${P}`,G=T.has(F),V=[],Y=(Z,se)=>{const re=I[Z];re!=null&&V.push([se,typeof re=="object"?JSON.stringify(re):String(re)])};return Y("type",n("layout_editor.data_sources.field.type")),Y("endpoint",n("layout_editor.data_sources.field.endpoint")),Y("method",n("layout_editor.data_sources.field.method")),Y("auth_mode",n("layout_editor.data_sources.field.auth_mode")),Y("loading_strategy",n("layout_editor.data_sources.field.loading_strategy")),Y("auto_fetch",n("layout_editor.data_sources.field.auto_fetch")),Y("params",n("layout_editor.data_sources.field.params")),i.jsxs("div",{"data-testid":"g7le-data-sources-inherited-item","data-ds-id":F,"data-expanded":G?"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":G,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:G?"rotate(90deg)":"none"},children:"▶"}),(()=>{const Z=rs(I,y),se=is(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})]})})()]}),G&&i.jsxs("div",{"data-testid":"g7le-data-sources-inherited-info",style:{padding:"0 12px 10px 32px",display:"flex",flexDirection:"column",gap:3},children:[V.length===0&&i.jsx("span",{style:{color:"#94a3b8"},children:"—"}),V.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}-${P}`)})})]})]}),b&&i.jsxs("div",{className:"g7le-data-sources__footer",style:{flex:"0 0 auto",padding:"12px 16px",borderTop:"1px solid #e2e8f0",background:"#ffffff"},children:[k&&i.jsx("div",{"data-testid":"g7le-data-sources-form-error",role:"alert",style:{fontSize:12,color:"#dc2626",marginBottom:10},children:k}),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:N,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:Nu,children:n("layout_editor.data_sources.form.save")})]})]})]})}function QC(e){const t=e?.globalHeaders;return Array.isArray(t)?t:[]}function RC(e){const t=e?.scripts;return Array.isArray(t)?t:[]}function e$(e){const t=QC(e.raw),n=RC(e.raw);return i.jsxs("div",{className:"g7le-data-source-tab","data-testid":"g7le-data-source-tab",style:t$,children:[i.jsx(ZC,{...e}),i.jsxs("div",{style:Ou,"data-testid":"g7le-global-headers",children:[i.jsx("div",{style:Bu,children:e.t("layout_editor.data_sources.global_headers")}),t.length===0?i.jsx("p",{"data-testid":"g7le-global-header-empty",style:Ku,children:e.t("layout_editor.data_sources.global_headers_empty")}):t.map((o,r)=>i.jsxs("div",{"data-testid":`g7le-global-header-${r}`,style:Wu,children:[i.jsx("code",{style:ju,children:o.pattern??"*"}),i.jsx("span",{style:n$,children:"→"}),i.jsx("span",{style:Hu,children:Object.keys(o.headers??{}).join(", ")})]},r)),i.jsxs("p",{style:Fu,children:["ⓘ ",e.t("layout_editor.data_sources.global_headers_hint")]})]}),i.jsxs("div",{style:Ou,"data-testid":"g7le-scripts",children:[i.jsx("div",{style:Bu,children:e.t("layout_editor.data_sources.scripts")}),n.length===0?i.jsx("p",{"data-testid":"g7le-script-empty",style:Ku,children:e.t("layout_editor.data_sources.scripts_empty")}):n.map((o,r)=>i.jsxs("div",{"data-testid":`g7le-script-${o.id??r}`,style:Wu,children:[i.jsx("code",{style:ju,children:o.id??`#${r}`}),i.jsx("span",{style:Hu,children:o.src??""}),o.loading?i.jsx("span",{style:o$,children:o.loading}):null]},o.id??r)),i.jsxs("p",{style:Fu,children:["ⓘ ",e.t("layout_editor.data_sources.scripts_hint")]})]})]})}const t$={display:"flex",flexDirection:"column",gap:16,minWidth:0},Ou={borderTop:"1px solid #e2e8f0",paddingTop:12,display:"flex",flexDirection:"column",gap:6},Bu={fontSize:12,fontWeight:700,color:"#475569"},Wu={display:"flex",alignItems:"center",gap:8,fontSize:12,padding:"4px 8px",border:"1px solid #f1f5f9",borderRadius:6},ju={fontSize:11,color:"#0f172a",fontFamily:"monospace"},n$={color:"#94a3b8"},Hu={flex:1,minWidth:0,color:"#475569",wordBreak:"break-all"},o$={fontSize:10,color:"#64748b",background:"#f1f5f9",borderRadius:4,padding:"0 4px"},Fu={margin:0,fontSize:11,color:"#94a3b8"},Ku={margin:0,fontSize:12,color:"#94a3b8"},r$=["meta","seo","init","overlay","computed","state","error","data"],i$=["401","403","404","500","503"],s$={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 a$(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:je()});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 l$(e,t){let n=0;for(const o of e)Yn(o,t).kind==="advanced"&&(n+=1);return n}function d$(e,t){let n=0;for(const o of Object.keys(e))Ed(e[o],t).kind==="advanced"&&(n+=1);return n}function c$(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 u$({templateIdentifier:e,spec:t,t:n,resolveLabel:o,permissionCandidates:r,onClose:s,initialTab:a="meta",extensionsFetcher:l}){const{state:d}=Je(),{raw:c,getValue:p,patch:f}=zm(),[y,g]=u.useState(a),m=d.selectedRoute?.path??"",h=u.useMemo(()=>zd(d.routeTree,o),[d.routeTree,o]),v=u.useMemo(()=>Md(c),[c]),b=u.useMemo(()=>Ld(t),[t]),x=u.useMemo(()=>Qm(c,o),[c,o]),k=Nd({raw:c,spec:t}),w=u.useMemo(()=>tb(t),[t]),_=u.useMemo(()=>nb(t),[t]),C=u.useMemo(()=>ob(t),[t]),E=u.useMemo(()=>rb(t),[t]),S=u.useMemo(()=>wo(w),[w]),T=u.useMemo(()=>xd(_),[_]),$=p("init_actions",void 0)??p("initActions",[]),A=p("computed",{}),z=p("__computedSource",{}),D=p("errorHandling",{}),O=p("transition_overlay",void 0),M=(p("__editor",{})??{}).original,B=u.useMemo(()=>{if(M===void 0)return;const U=M.transition_overlay;return U&&typeof U=="object"&&!Array.isArray(U)?U:{}},[M]),N=u.useMemo(()=>{const U=O;if(!U||typeof U!="object"||Array.isArray(U))return;const ee=B??{},fe={};for(const[K,ne]of Object.entries(U))K in ee||(fe[K]=ne);return Object.keys(fe).length>0?fe:void 0},[O,B]),[H,L]=u.useState([]);u.useEffect(()=>{let U=!1;const ee=l??a$;return(async()=>{const fe=await ee(e);U||L(fe)})(),()=>{U=!0}},[e,l]);const I=(p("meta",{})??{}).seo?.page_type,P=Jm({raw:c,spec:t,pageType:typeof I=="string"?I:null}),F=u.useMemo(()=>Xm(c,t),[c,t]),G=u.useMemo(()=>({meta:0,seo:0,init:l$($,S),overlay:0,computed:d$(A,T),state:0,error:0,data:0}),[$,S,A,T]),V=u.useMemo(()=>Object.values(G).reduce((U,ee)=>U+ee,0),[G]),Y=u.useMemo(()=>Zm(c,o,n),[c,o,n]),Z=u.useCallback(U=>{const fe={...M?.computed??{}};delete fe[U];const K={...A};delete K[U],f("computed",K,Object.keys(fe).length===0?void 0:fe)},[M,A,f]),se=c$(p,m,n),re=()=>{switch(y){case"meta":return i.jsx(yx,{getValue:p,patch:f,t:n,fieldT:o,spec:t,permissionCandidates:r,bindingCandidates:k});case"seo":return i.jsx(nw,{getValue:p,patch:f,t:n,templateIdentifier:e,candidates:P,availableExtensions:H,dataSourceOptions:Y,previewUrl:m||"/",seedContext:F});case"init":return i.jsx(wk,{actions:$,onChange:U=>f("init_actions",U),recipes:w,t:o,bindingCandidates:k,pageCandidates:h,dataSourceCandidates:v,stateKeyCandidates:b,modalCandidates:x});case"overlay":return i.jsx(Uk,{value:O,ownValue:B,baseValue:N,patch:U=>f("transition_overlay",U),t:o,loadingComponents:E,progressiveDataSources:Y,bindingCandidates:k});case"computed":return i.jsx(z1,{computed:A,onChange:U=>f("computed",U),recipes:_,t:o,sampleContext:F,dataSourceCandidates:v,bindingCandidates:k,computedSource:z,onRevert:Z});case"state":return i.jsx(gS,{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(jS,{value:D,onChange:U=>f("errorHandling",U),t:o,errorConfigCodes:i$,templateCodes:Object.keys(D),ownCodes:Object.keys(M?.errorHandling??{}),recipes:C,pageCandidates:h,modalCandidates:x,dataSourceCandidates:v,stateKeyCandidates:b});case"data":return i.jsx(e$,{raw:c,t:n,resolveLabel:o,onChange:(U,ee)=>f("data_sources",U,ee),onClose:s,actionRecipes:w,errorRecipes:C,conditionSpec:t,bindingCandidates:k,pageCandidates:h,dataSourceCandidates:v,stateKeyCandidates:b});default:return i.jsx("div",{})}};return i.jsxs("div",{className:"g7le-page-settings","data-testid":"g7le-page-settings",style:p$,children:[i.jsxs("div",{style:f$,children:[i.jsx("span",{"data-testid":"g7le-page-settings-title",style:g$,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:h$,children:"✕"})]}),i.jsx("div",{role:"tablist",style:y$,children:r$.map(U=>{const ee=G[U];return i.jsxs("button",{type:"button",role:"tab","aria-selected":y===U,"data-testid":`g7le-page-settings-tab-${U}`,"data-active":y===U?"true":"false",onClick:()=>g(U),style:y===U?b$:Vu,children:[n(s$[U]),ee>0?i.jsxs("span",{"data-testid":`g7le-page-settings-tab-badge-${U}`,style:m$,children:["(",ee,")"]}):null]},U)})}),V>0?i.jsxs("p",{"data-testid":"g7le-page-settings-advanced-summary",style:v$,children:["⚠ ",n("layout_editor.page_settings.advanced_summary",{count:V})," ⓘ"]}):null,i.jsx("div",{"data-testid":"g7le-page-settings-panel",style:_$,children:re()}),i.jsx("div",{style:x$,children:i.jsx("button",{type:"button","data-testid":"g7le-page-settings-close",onClick:s,style:w$,children:n("layout_editor.page_settings.close")})})]})}const p$={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"},f$={display:"flex",alignItems:"center",gap:8,paddingBottom:8,borderBottom:"1px solid #e2e8f0"},g$={flex:1,fontSize:15,fontWeight:700,color:"#0f172a",minWidth:0},h$={border:"none",background:"transparent",color:"#64748b",cursor:"pointer",fontSize:16,lineHeight:1,padding:4},y$={display:"flex",gap:2,paddingTop:8,borderBottom:"1px solid #e2e8f0",flexWrap:"nowrap",overflowX:"auto",overflowY:"hidden",flexShrink:0,minWidth:0},Vu={border:"none",borderBottomWidth:"2px",borderBottomStyle:"solid",borderBottomColor:"transparent",background:"transparent",color:"#64748b",cursor:"pointer",fontSize:12,padding:"6px 10px",whiteSpace:"nowrap"},b$={...Vu,color:"#2563eb",borderBottomColor:"#2563eb",fontWeight:600},m$={marginLeft:4,fontSize:10,color:"#b45309"},v$={margin:0,marginTop:8,fontSize:11,color:"#b45309",background:"#fffbeb",padding:"6px 8px",borderRadius:6},_$={flex:1,overflowY:"auto",paddingTop:12,minWidth:0,minHeight:0},x$={display:"flex",justifyContent:"flex-end",paddingTop:8,borderTop:"1px solid #e2e8f0"},w$={border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",fontSize:13,padding:"6px 16px"};function Xs(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 Uu=100,qu=500;function k$(e,t,n){const[o,r]=u.useState([]),[s,a]=u.useState(!1),[l,d]=u.useState(!1),[c,p]=u.useState(null),[f,y]=u.useState(null),[g,m]=u.useState(Uu),[h,v]=u.useState(!1),b=u.useCallback(async(C,E)=>{if(!t){r([]),p(null),v(!1);return}E==="more"?d(!0):a(!0),p(null);try{const S=`${Xs(e,t)}?limit=${C}`,T=await fetch(S,{credentials:"same-origin",headers:je()}),$=await T.json().catch(()=>null);if(!T.ok){p($?.message??`HTTP ${T.status}`),E==="reload"&&r([]);return}const A=$?.data,z=Array.isArray(A)?A:[];r(z),v(z.length>=C&&C{await b(g,"reload")},[b,g]),k=u.useCallback(async()=>{const C=Math.min(g+Uu,qu);if(C<=g){v(!1);return}await b(C,"more")},[b,g]),w=u.useCallback(async C=>{if(!t)return{kind:"not_found"};y(C);try{const E=`${Xs(e,t)}/${C}/restore`,S=await fetch(E,{method:"POST",credentials:"same-origin",headers:je({"Content-Type":"application/json"})}),T=await S.json().catch(()=>null);if(S.status===404)return{kind:"not_found"};if(!S.ok)return{kind:"network_error",message:T?.message??`HTTP ${S.status}`};const $=typeof T?.data?.version=="number"?T.data.version:-1;return await n?.($>=0?$:void 0),{kind:"success",newVersion:$}}catch(E){return{kind:"network_error",message:E instanceof Error?E.message:"network error"}}finally{y(null)}},[e,t,n]),_=u.useCallback(async C=>{if(!t)return{kind:"not_found"};try{const E=`${Xs(e,t)}/${C}`,S=await fetch(E,{credentials:"same-origin",headers:je()}),T=await S.json().catch(()=>null);if(S.status===404)return{kind:"not_found"};if(!S.ok)return{kind:"network_error",message:T?.message??`HTTP ${S.status}`};const $=T?.data;if(!$)return{kind:"not_found"};if(t.kind==="extension"&&!$.full_content){const A=$.content;if(typeof A=="string")try{const z=JSON.parse(A);z&&typeof z=="object"&&($.full_content=z)}catch{}}return{kind:"success",detail:$}}catch(E){return{kind:"network_error",message:E instanceof Error?E.message:"network error"}}},[e,t]);return{versions:o,isLoading:s,isLoadingMore:l,error:c,restoringId:f,hasMore:h,loadVersions:x,loadMore:k,restore:w,loadVersionDetail:_}}function S$(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 C$(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 Yu=4e3;function $$(e,t,n=3){const o=Gu(e),r=Gu(t);let s=0;const a=Math.min(o.length,r.length);for(;sYu||p.length>Yu)return{hunks:[],addedCount:-1,removedCount:-1,identical:!1};const f=S$(c,p),y=C$(c,p,f),g=[];let m=s,h=s,v=0,b=0;for(let w=0;w{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 Xu(e){return JSON.stringify(Js(e),null,2)}function Js(e){if(Array.isArray(e))return e.map(Js);if(e&&typeof e=="object"){const t=e,n={};for(const o of Object.keys(t).sort())n[o]=Js(t[o]);return n}return e}const I$={display:"flex",flexDirection:"column",height:"100%",minHeight:0},A$={display:"flex",alignItems:"center",gap:8,padding:"12px 16px",borderBottom:"1px solid #e2e8f0",background:"#f8fafc"},T$={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"},D$={marginLeft:"auto",border:"none",background:"transparent",fontSize:16,color:"#64748b",cursor:"pointer",outline:"none"},N$={display:"flex",alignItems:"center",gap:12,padding:"8px 16px",borderBottom:"1px solid #e2e8f0",background:"#ffffff",fontSize:12,fontWeight:600},z$={flex:1,minHeight:0,overflow:"auto",background:"#ffffff",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace',fontSize:12,lineHeight:1.5},Ju={padding:"24px 12px",textAlign:"center",color:"#94a3b8",fontSize:13},M$={padding:"2px 12px",background:"#f1f5f9",color:"#64748b",borderTop:"1px solid #e2e8f0",borderBottom:"1px solid #e2e8f0",userSelect:"none"};function L$(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 Zu={display:"inline-block",width:44,textAlign:"right",padding:"0 6px",color:"#94a3b8",userSelect:"none",borderRight:"1px solid #e2e8f0",whiteSpace:"nowrap"};function P$({oldVersion:e,newVersion:t,oldContent:n,newContent:o,t:r,onBack:s,onClose:a}){const l=u.useMemo(()=>{const c=Xu(n),p=Xu(o);return $$(c,p)},[n,o]),d=l.addedCount<0;return i.jsxs("div",{className:"g7le-version-diff","data-testid":"g7le-version-diff",style:I$,children:[i.jsxs("div",{"data-modal-drag-handle":!0,style:A$,children:[i.jsxs("button",{type:"button",onClick:s,style:T$,"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:D$,"data-testid":"g7le-version-diff-close",children:"✕"})]}),!d&&i.jsxs("div",{style:N$,"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:z$,children:d?i.jsx("div",{style:Ju,"data-testid":"g7le-version-diff-too-large",children:r("layout_editor.version_history.diff_too_large")}):l.identical?i.jsx("div",{style:Ju,"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:M$,"data-testid":`g7le-version-diff-hunk-header-${p}`,children:c.header}),c.lines.map((f,y)=>{const g=L$(f.kind);return i.jsxs("div",{style:{display:"flex",alignItems:"stretch",...g.row},"data-kind":f.kind,"data-testid":`g7le-version-diff-line-${p}-${y}`,children:[i.jsx("span",{style:{...Zu,...g.gutter},"aria-hidden":"true",children:f.oldLine??""}),i.jsx("span",{style:{...Zu,...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})]},y)})]},p))})]})}const O$={display:"flex",flexDirection:"column",height:"100%",minHeight:0},B$={display:"flex",alignItems:"center",gap:8,padding:"12px 16px",borderBottom:"1px solid #e2e8f0",background:"#f8fafc"},W$={marginLeft:"auto",border:"none",background:"transparent",fontSize:16,color:"#64748b",cursor:"pointer",outline:"none"},j$={flex:1,minHeight:0,overflowY:"auto",padding:12},Qu={padding:"24px 12px",textAlign:"center",color:"#94a3b8",fontSize:13},H$={margin:"8px 16px 0",padding:"8px 12px",borderRadius:6,background:"#fef2f2",color:"#b91c1c",fontSize:12,border:"1px solid #fecaca"},F$={display:"flex",flexDirection:"column",gap:8},K$={display:"flex",alignItems:"center",gap:12,padding:"10px 12px",borderRadius:8,border:"1px solid #e2e8f0",background:"#ffffff"},V$={display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:44,padding:"2px 8px",borderRadius:999,background:"#eff6ff",color:"#1d4ed8",fontSize:12,fontWeight:700},U$={display:"inline-flex",alignItems:"center",padding:"1px 8px",borderRadius:999,background:"#0f172a",color:"#ffffff",fontSize:10,fontWeight:700,letterSpacing:.3},q$={display:"flex",alignItems:"center",gap:10,fontSize:11,fontWeight:600},G$={display:"flex",flexDirection:"column",gap:2,minWidth:0,flex:1},Ru={padding:"6px 12px",borderRadius:6,border:"1px solid #cbd5e1",background:"#ffffff",color:"#0f172a",fontSize:12,fontWeight:600,cursor:"pointer",outline:"none",whiteSpace:"nowrap"};function ep(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 Y$(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 X$({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:y,restore:g,loadVersionDetail:m}=k$(e,t,o),[h,v]=u.useState(null),[b,x]=u.useState(null),[k,w]=u.useState(null);u.useEffect(()=>{f()},[f]);const _=u.useCallback(async S=>{v(null),w(S.version);try{const T=await m(S.version);if(T.kind!=="success"){v(T.kind==="not_found"?n("layout_editor.version_history.restore_not_found"):T.message);return}const $=S.version-1,A=s.some(D=>D.version===$);let z={};if(A){const D=await m($);if(D.kind==="success")z=ep(D.detail);else if(D.kind==="network_error"){v(D.message);return}}x({oldVersion:A?$:0,newVersion:S.version,oldContent:z,newContent:ep(T.detail)})}finally{w(null)}},[m,s,n]),C=u.useCallback(async S=>{v(null);const T=n("layout_editor.version_history.restore_confirm");if(!(typeof window<"u"?window.confirm(T):!0))return;const A=await g(S);A.kind==="success"?r():A.kind==="not_found"?v(n("layout_editor.version_history.restore_not_found")):v(A.message)},[g,r,n]),E=h??d;return b?i.jsx(P$,{oldVersion:b.oldVersion,newVersion:b.newVersion,oldContent:b.oldContent,newContent:b.newContent,t:n,onBack:()=>x(null),onClose:r}):i.jsxs("div",{className:"g7le-version-history","data-testid":"g7le-version-history",style:O$,children:[i.jsxs("div",{"data-modal-drag-handle":!0,style:B$,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:W$,"data-testid":"g7le-version-history-close",children:"✕"})]}),E&&i.jsx("div",{style:H$,"data-testid":"g7le-version-history-error",children:E}),i.jsx("div",{style:j$,children:a?i.jsx("div",{style:Qu,"data-testid":"g7le-version-history-loading",children:n("layout_editor.version_history.loading")}):s.length===0?i.jsx("div",{style:Qu,"data-testid":"g7le-version-history-empty",children:n("layout_editor.version_history.empty")}):i.jsxs("div",{"data-testid":"g7le-version-history-list",style:F$,children:[s.map((S,T)=>{const $=S.changes_summary,A=$?.added_count??0,z=$?.removed_count??0,D=$?.char_diff??0,O=Y$(S.created_at),M=c===S.id,B=T===0;return i.jsxs("div",{style:K$,"data-testid":`g7le-version-row-${S.id}`,children:[i.jsxs("span",{style:V$,"data-testid":`g7le-version-badge-${S.id}`,children:["v",S.version]}),i.jsxs("div",{style:G$,children:[i.jsxs("span",{style:{display:"flex",alignItems:"center",gap:8},children:[O&&i.jsx("span",{style:{fontSize:12,color:"#475569",fontWeight:600},children:O}),B&&i.jsx("span",{style:U$,"data-testid":`g7le-version-latest-${S.id}`,children:n("layout_editor.version_history.latest")})]}),i.jsxs("span",{style:q$,"data-testid":`g7le-version-summary-${S.id}`,children:[i.jsx("span",{style:{color:"#16a34a"},"data-testid":`g7le-version-added-${S.id}`,children:n("layout_editor.version_history.added",{count:A})}),i.jsx("span",{style:{color:"#dc2626"},"data-testid":`g7le-version-removed-${S.id}`,children:n("layout_editor.version_history.removed",{count:z})}),i.jsx("span",{style:{color:"#94a3b8",fontWeight:500},"data-testid":`g7le-version-chars-${S.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-${S.id}`,children:n("layout_editor.version_history.saved_by",{name:S.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:()=>{_(S)},disabled:k!==null,style:{...Ru,background:"#f8fafc",opacity:k!==null?.6:1},"data-testid":`g7le-version-compare-${S.id}`,children:k===S.version?n("layout_editor.version_history.comparing"):n("layout_editor.version_history.compare")}),!B&&i.jsx("button",{type:"button",onClick:()=>{C(S.id)},disabled:M||c!==null,style:{...Ru,opacity:M||c!==null?.6:1},"data-testid":`g7le-version-restore-${S.id}`,children:n(M?"layout_editor.version_history.restoring":"layout_editor.version_history.restore")})]})]},S.id)}),p&&i.jsx("button",{type:"button","data-testid":"g7le-version-history-load-more",style:J$,disabled:l,onClick:()=>{y()},children:n(l?"layout_editor.version_history.loading":"layout_editor.version_history.load_more")})]})})]})}const J$={width:"100%",marginTop:8,padding:"8px 12px",fontSize:12,color:"#475569",background:"#f8fafc",border:"1px solid #e2e8f0",borderRadius:6,cursor:"pointer"},tp=[{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 Z$(e){return{key:(e.key||"").toLowerCase(),mod:e.ctrlKey||e.metaKey,shift:e.shiftKey,alt:e.altKey}}function Q$(e,t){return e.key===t.key&&!!e.mod==!!t.mod&&!!e.shift==!!t.shift&&!!e.alt==!!t.alt}function R$(e){for(const t of tp)if(t.combos.some(n=>Q$(n,e)))return t;return null}function eE(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(tE(e.key)),n.join(" + ")}function tE(e){return{arrowup:"↑",arrowdown:"↓",arrowleft:"←",arrowright:"→",enter:"Enter",escape:"Esc",delete:"Delete",backspace:"Backspace"," ":"Space"}[e]??(e.length===1?e.toUpperCase():e)}const nE=["clipboard","element","history","view","document"],oE={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 rE(){return typeof navigator>"u"?!1:/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent||"")}function iE({t:e,onClose:t,isMac:n}){const o=n??rE(),r=u.useMemo(()=>{const s=new Map;for(const a of tp){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:sE,children:[i.jsxs("div",{style:aE,children:[i.jsx("span",{style:lE,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:dE,children:"✕"})]}),i.jsx("div",{style:cE,children:nE.map(s=>{const a=r.get(s);return!a||a.length===0?null:i.jsxs("div",{style:uE,"data-testid":`g7le-shortcut-group-${s}`,children:[i.jsx("div",{style:pE,children:e(oE[s])}),i.jsx("table",{style:fE,children:i.jsx("tbody",{children:a.map(l=>i.jsxs("tr",{"data-testid":`g7le-shortcut-row-${l.id}`,children:[i.jsx("td",{style:gE,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:bE,children:e("layout_editor.shortcuts.or")}),i.jsx("kbd",{style:yE,children:eE(d,o)})]},c))})]},l.id))})})]},s)})}),i.jsx("div",{style:mE,children:e("layout_editor.shortcuts.footnote")})]})}const sE={display:"flex",flexDirection:"column",padding:20,gap:16,width:"100%",boxSizing:"border-box"},aE={display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:12,borderBottom:"1px solid #e2e8f0"},lE={fontSize:15,fontWeight:700,color:"#0f172a"},dE={width:28,height:28,border:"none",background:"transparent",color:"#64748b",cursor:"pointer",fontSize:14,borderRadius:6},cE={display:"grid",gridTemplateColumns:"1fr 1fr",columnGap:28,rowGap:18,alignItems:"start"},uE={display:"flex",flexDirection:"column",gap:6},pE={fontSize:12,fontWeight:700,color:"#2563eb"},fE={width:"100%",borderCollapse:"collapse"},gE={padding:"4px 0",fontSize:12.5,color:"#334155",textAlign:"left",whiteSpace:"nowrap",verticalAlign:"middle"},hE={padding:"4px 0",paddingLeft:12,textAlign:"right",verticalAlign:"middle"},yE={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"},bE={fontSize:11,color:"#94a3b8",margin:"0 4px"},mE={fontSize:11,color:"#94a3b8",paddingTop:12,borderTop:"1px solid #f1f5f9"};function vE(e){if(!e||!(e instanceof HTMLElement))return!1;const t=e.tagName;return!!(t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable)}function _E(){return typeof document>"u"?!1:!!document.querySelector(".g7le-modal-backdrop, .g7le-modal")}function np(e){const{handlers:t,hasSelection:n,enabled:o=!0}=e;u.useEffect(()=>{if(!o||typeof window>"u")return;const r=s=>{if(vE(s.target))return;const a=Z$(s),l=R$(a);if(!l||_E()||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 xE(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(Lo,{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(Lo,{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:op,"data-testid":"g7le-save-banner-validation-errors",children:l.map(([d,c])=>i.jsxs("li",{children:[i.jsx("code",{style:rp,children:d}),": ",c.join(", ")]},d))})]})}return t.kind==="blocked_inactive_extension"?i.jsxs(Lo,{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:op,"data-testid":"g7le-save-banner-blocked-paths",children:t.blockedPaths.map(a=>i.jsx("li",{children:i.jsx("code",{style:rp,children:a})},a))})]}):t.kind==="network_error"?i.jsxs(Lo,{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(Lo,{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:CE,children:i.jsxs("div",{style:$E,children:[i.jsx("h2",{style:EE,children:s("layout_editor.save.concurrent.title")}),i.jsx("p",{style:IE,children:s("layout_editor.save.concurrent.message")}),i.jsx("div",{style:AE,children:s("layout_editor.save.concurrent.version_info",{current:String(t.currentVersion),yours:String(t.yourVersion)})}),i.jsxs("div",{style:TE,children:[i.jsx("button",{type:"button","data-testid":"g7le-save-banner-concurrent-load-latest",onClick:()=>{o?.(),n()},style:DE,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:NE,children:s("layout_editor.save.concurrent.view_my_changes")}),i.jsx("button",{type:"button","data-testid":"g7le-save-banner-concurrent-cancel",onClick:n,style:zE,children:s("layout_editor.save.concurrent.cancel")})]})]})})}function Lo(e){const{tone:t,testId:n,onDismiss:o,children:r}=e,s=wE[t];return i.jsxs("div",{role:"status","data-testid":n,style:{...kE,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:SE,children:"×"})]})}const wE={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"}},kE={display:"flex",alignItems:"flex-start",gap:12,padding:"12px 16px",border:"1px solid",borderRadius:0,fontSize:13,lineHeight:1.5},SE={background:"transparent",border:"none",fontSize:18,cursor:"pointer",lineHeight:1,color:"inherit",padding:"0 4px",flexShrink:0},op={margin:"8px 0 0",paddingLeft:20,fontSize:12},rp={background:"rgba(0, 0, 0, 0.06)",padding:"1px 4px",borderRadius:3,fontFamily:"monospace"},CE={position:"fixed",inset:0,background:"rgba(15, 23, 42, 0.6)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e4},$E={background:"#fff",borderRadius:8,padding:24,width:"min(480px, 90vw)",boxShadow:"0 10px 25px rgba(0,0,0,0.15)"},EE={margin:"0 0 8px",fontSize:16,fontWeight:600,color:"#0f172a"},IE={margin:"0 0 12px",color:"#334155",fontSize:13,lineHeight:1.5},AE={marginBottom:16,padding:"8px 12px",background:"#f8fafc",borderRadius:6,fontSize:12,color:"#64748b",fontFamily:"monospace"},TE={display:"flex",gap:8,justifyContent:"flex-end"},DE={padding:"8px 14px",background:"#2563eb",color:"#fff",border:"none",borderRadius:6,fontSize:13,fontWeight:600,cursor:"pointer"},NE={padding:"8px 14px",background:"#fff",color:"#334155",border:"1px solid #cbd5e1",borderRadius:6,fontSize:13,fontWeight:500,cursor:"pointer"},zE={padding:"8px 14px",background:"transparent",color:"#64748b",border:"none",borderRadius:6,fontSize:13,cursor:"pointer"};function ip(e){if(!e)return null;const n=new URLSearchParams(e).get("route");return n&&n.length>0?n:null}function Zs(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 sp(e){if(!e)return null;const n=new URLSearchParams(e).get("host");return n&&n.length>0?n:null}function ap(e){if(!e)return null;const n=new URLSearchParams(e).get("edit");return n&&n.length>0&&n.startsWith("__")?n:null}function ME(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 LE="g7le-editor-route",PE=new Set;function Qs(e){return e.path.startsWith("__group__/")||e.path.startsWith("__conngroup__/")}function lp(e,t){const{t:n,translationEngine:o,translationContext:r,templateIdentifier:s}=t,a=Qs(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 y of l.slice(d+1).split("|")){const g=y.indexOf("=");g!==-1&&(p[y.slice(0,g)]=y.slice(g+1))}if((e.kind==="route"||e.kind==="modal")&&!a&&o&&r&&s!==r.templateId){const y={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,y,g);if(m!==c)return m}const f=n(c,p);if(f===c&&typeof window<"u"){const y=window.G7Core?.t;if(typeof y=="function")try{const g=y(c,p);if(g!==c)return g}catch{}}if(f===c&&e.kind==="route"&&!a){const y=e.path;if(y&&y!=="/"){const g=y.split("/").filter(Boolean);return g[g.length-1]??y}return y==="/"?"/":c}return f}function OE(e){return e.trim().toLocaleLowerCase()}function dp(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 N=f.selectedRoute?.path??"";return N.startsWith("__extension__/")||N.startsWith("__modal__/")?N.slice(N.lastIndexOf("/")+1):null},[f.selectedRoute?.path]),h=u.useMemo(()=>!g||!m?!1:(e.children??[]).some(N=>N.kind==="extension"&&N.extensionId===m||N.kind==="modal"&&N.modalId===m),[g,m,e.children]),[v,b]=u.useState(!0);u.useEffect(()=>{h&&b(!1)},[h]);const x=f.editMode==="extension"?f.selectedRoute?.layoutName??null:null,k=e.kind==="extension"?up(e,f.routeTree)??null:null,w=e.kind==="extension"&&o===e.path&&(x===null||k===null||x===k),_=f.editMode==="modal"&&o?.startsWith("__modal__/")?o.slice(o.lastIndexOf("/")+1):null,C=f.editMode==="modal"?f.selectedRoute?.layoutName??null:null,E=e.kind==="modal"&&!!_&&e.modalId===_&&(C===null||e.modalHostLayout==null||C===e.modalHostLayout),S=e.kind!=="extension"&&e.kind!=="modal"&&o===e.path||w||E||e.kind==="route"&&!y&&r===e.path,$=(e.children?.length??0)>0&&(!g||l||!v),A=!y&&!!e.layoutName&&s.has(e.layoutName),z=y?void 0:e.kind==="extension"?e.extensionId?f.extensionVersions[e.extensionId]:void 0:e.layoutName?f.layoutVersions[e.layoutName]:void 0,D=()=>{if(g){b(N=>!N);return}y||n(e)},O=lp(e,{t:d,translationEngine:c,translationContext:p,templateIdentifier:f.templateIdentifier}),M=y?null:BE(e),B={paddingLeft:12+t*14,paddingRight:12,paddingTop:4,paddingBottom:4,opacity:e.isHidden?.55:1,cursor:g?"pointer":y?"default":"pointer",background:S?"#eff6ff":"transparent",borderLeft:S?"2px solid #2563eb":"2px solid transparent",fontWeight:y||S?600:400,fontSize:y?11:13,color:y?"#64748b":S?"#1d4ed8":"#1e293b",textTransform:y?"uppercase":"none",letterSpacing:y?.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":y?"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||!y?"button":void 0,tabIndex:g||!y?0:void 0,"aria-expanded":g?l?!0:!v:void 0,onClick:D,onKeyDown:N=>{g&&(N.key==="Enter"||N.key===" ")?(N.preventDefault(),b(H=>!H)):!y&&(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),n(e))},style:B,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"}}),y?O:dp(O,a),typeof z=="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(z)}),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",z]}),i.jsx(WE,{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:dp(M,a)})]}),$&&i.jsx("ul",{style:{listStyle:"none",margin:0,padding:0},children:e.children.map(N=>i.jsx(cp,{node:N,depth:t+1,onSelect:n,selectedRoutePath:o,activeHostRoutePath:r,dirtyLayoutNames:s,query:a,forceExpand:l},N.path))})]})}function jE(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 up(e,t){if(e.connectedHostRoutePath){const n=pp(t,e.connectedHostRoutePath);if(n?.layoutName)return n.layoutName}if(e.extensionType==="overlay"&&e.extensionTargetName)return e.extensionTargetName}function pp(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=pp(n.children,t);if(o)return o}}return null}function fp(e,t,n){const o=[];for(const r of e){const s=Qs(r),a=r.children&&r.children.length>0?fp(r.children,t,n):[];if(s){a.length>0&&o.push({...r,children:a});continue}const l=lp(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 HE(){const{t:e,translationEngine:t,translationContext:n}=tt(),{state:o,dispatch:r}=Je(),a=Ft()?.dirtyLayoutNames??PE,[l,d]=u.useState(""),c=OE(l),p=u.useMemo(()=>c?fp(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=up(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=Zs(o.templateIdentifier,h.path);`${window.location.pathname}${window.location.search}`!==v&&window.history.pushState({source:LE,routePath:h.path},"",v)}},y=o.selectedRoute?.path??null,g=u.useMemo(()=>jE(o.routeTree,y),[o.routeTree,y]);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(cp,{node:h,depth:0,onSelect:f,selectedRoutePath:y,activeHostRoutePath:g,dirtyLayoutNames:a,query:c,forceExpand:!!c},h.path))})})]})}const FE=Lt().DynamicRenderer,Rs=Lt(),KE=Rs.ResponsiveProvider;Rs.useResponsive,Rs.ResponsiveContext;const VE=Lt().ActionDispatcher,gp=Lt(),UE=gp.DataSourceManager;gp.dataSourceManager;function Gr(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 io(e,t){return{kind:"network",status:0,message:e instanceof Error?e.message:String(e??"Unknown network error"),source:t}}function hp(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 Ze(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 qE(e,t){if(!e)return{affordance:"none",targetPath:null};const n=GE(e);return n?YE(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 GE(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 YE(e){return/\{\{[\s\S]*?\}\}/.test(e)}function XE(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 JE(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=QE(o);if(a!==null)return a}const r=[];if(typeof e.text=="string"&&r.push(...yp(e.text)),e.props&&typeof e.props=="object")for(const a of Object.values(e.props))typeof a=="string"&&r.push(...yp(a));return r.length===0?null:r.find(a=>!ZE.has(a))??r[0]}const ZE=new Set(["_local","_global","_computed","route","query","props","item","index","event","$event","$response","response"]);function yp(e){const t=[],n=/\{\{([\s\S]*?)\}\}/g;let o;for(;(o=n.exec(e))!==null;){const r=bp(o[1]);r!==null&&t.push(r)}return t}function QE(e){const t=e.replace(/\{\{|\}\}/g,"");return bp(t)}function bp(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(td(e)||typeof e.slot=="string"||typeof e.__editorSlotName=="string")return"extension_point";if(t!=="route"&&Ji(e,t,n)){const s=e.__source?.kind;return s==="base"?"base":s==="partial"?"partial":s==="extension"?"extension":"base"}if(Cb(e,o))return"data_bound";if(!Ji(e,t,n))return"none";const r=e.__source?.kind;return r==="base"?"base":r==="partial"?"partial":r==="extension"?"extension":"none"}function mp(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 RE(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 vp(e,t,n,o){if(!e||!t)return t;const r=n(t),s=Ib(e,r,o);return s.length===r.length?t:RE(t,s.length)}function _p(e){return e==="none"||e==="data_bound"}function e7(e){const{rootNode:t,editMode:n,currentExtensionId:o,editableRootPath:r,pathParser:s=Ze,resolveRouteMatch:a}=e,[l,d]=u.useState(null),[c,p]=u.useState(null),f=u.useCallback(x=>{if(x===null||n==="route")return!0;if(n==="iteration_item"||n==="modal"){if(!r||r.length===0)return!0;const C=s(x);return xp(C,r)}const k=ea(t,x,s);if(!k)return!0;const w=ta(t,x,s),_=gn(k,n,o,w);return _==="none"||_==="data_bound"},[t,s,n,o,r]),y=u.useCallback((x,k)=>{const _=(k?.currentTarget?.dataset??k?.dataset)?.editorPath??null,C=vp(t,_,s,o);f(C)&&d(C)},[t,s,o,f]),g=u.useCallback((x,k)=>{if(x===null){p(null);return}const _=(k?.currentTarget?.dataset??k?.dataset)?.editorPath??null,C=vp(t,_,s,o);if(!f(C)){p(null);return}p(C)},[t,s,o,f]),m=u.useCallback(()=>{d(null)},[]),h=u.useMemo(()=>{const x=ea(t,l,s),k=ea(t,c,s),w=x?ta(t,l,s):[];let _=gn(x,n,o,w);(n==="iteration_item"||n==="modal")&&l!==null&&x&&r&&r.length>0&&xp(s(l),r)&&(nd(x)?_="data_bound":_==="data_bound"&&(_="none"));const{affordance:C,targetPath:E}=qE(x,a),S=_==="base"&&typeof x?.__source?.layout=="string"?x.__source.layout:null,T=_==="data_bound"&&x?JE(x,w):null,{isIteration:$,iterationSourcePath:A}=_==="data_bound"&&x?XE(x,w,l):{isIteration:!1,iterationSourcePath:null};return{selectedNode:x,hoverNode:k,selectedLockKind:_,selectedNavAffordance:C,selectedNavTargetPath:E,selectedBaseLayout:S,selectedDataSourceId:T,selectedIsIteration:$,selectedIterationSourcePath:A}},[t,l,c,n,o,r,s,a]),v=u.useRef(void 0);v.current!==l&&(v.current=l,Cl({op:l===null?"clear":"select",componentPath:l,componentName:wp(h.selectedNode),lockKind:h.selectedLockKind,navAffordance:h.selectedNavAffordance,sourceExtensionId:mp(h.selectedNode),timestamp:Date.now()}));const b=u.useRef(void 0);return b.current!==c&&(b.current=c,c!==null&&Cl({op:"hover",componentPath:c,componentName:wp(h.hoverNode),lockKind:gn(h.hoverNode,n,o,ta(t,c,s)),navAffordance:"none",sourceExtensionId:mp(h.hoverNode),timestamp:Date.now()})),{selectedPath:l,hoverPath:c,...h,handleSelect:y,handleHover:g,clearSelection:m}}function ea(e,t,n){if(!e||!t)return null;const o=n(t);return We(e,o)}function xp(e,t){if(e.length0?e.name:typeof e.type=="string"&&e.type.length>0?e.type:null:null}let kp=0;function Sp(){return kp}function na(){kp+=1}function t7(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 n7(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 Cp(){const{state:e}=Je(),t=e.templateIdentifier,n=e.selectedRoute?.layoutName??null,o=e.editMode,r=o==="modal"?t7(e.selectedRoute?.path):null,s=o==="iteration_item"?n7(e.selectedRoute?.path):null,[a,l]=u.useState(null),[d,c]=u.useState(!1),[p,f]=u.useState(null),[y,g]=u.useState(!1),[m,h]=u.useState(0),[v,b]=u.useState(0),x=u.useRef(new Map),[k,w]=u.useState(()=>new Set),_=u.useCallback((L,I)=>`${L}|${I??""}`,[]),C=u.useRef(null);u.useEffect(()=>{C.current=a},[a]);const E=u.useCallback((L,I)=>{const P=_(o,n);x.current.set(P,{raw:L,lockVersion:I}),w(F=>{if(F.has(P))return F;const G=new Set(F);return G.add(P),G})},[_,o,n]),S=u.useCallback(L=>{x.current.delete(L),w(I=>{if(!I.has(L))return I;const P=new Set(I);return P.delete(L),P})},[]),T=u.useCallback(L=>{const I=`|${L??""}`,P=[];for(const F of x.current.keys())F.endsWith(I)&&P.push(F);for(const F of P)x.current.delete(F);P.length>0&&w(F=>{let G=!1;const V=new Set(F);for(const Y of P)V.delete(Y)&&(G=!0);return G?V:F})},[]),$=u.useCallback(async()=>{if(!n){l(null),f(null),g(!1);return}const L=_(o,n),I=x.current.get(L);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 P=window.G7Config?.cache_version??0,F=en(`/api/layouts/${encodeURIComponent(t)}/${n}`,"json",`${P}.${Sp()}`,"with_source_meta=1"),G=ar(),V={Accept:"application/json"};G&&(V.Authorization=`Bearer ${G}`);const Y=await fetch(F,{headers:V,credentials:"same-origin"}),Z=await Y.json().catch(()=>null);if(!Y.ok){f(Gr(Y.status,Z,"layout")),l(null),g(!1);return}const se=(Z&&(Z.data||Z))??{},re=typeof se.lock_version=="number"?se.lock_version:0;if(o==="modal"&&r){const ee=se,fe=Array.isArray(ee.modals)?ee.modals:[],K=fe.findIndex(ne=>ne&&(ne.id===r||ne.modal_id===r));if(K>=0){const ne=fe[K],me={...ne,props:{...ne.props??{},isOpen:!0}},ze=[...Array.isArray(ee.components)?ee.components:[],me],Se=[ze.length-1];l({layoutName:n,raw:{...ee,components:ze},lockVersion:re,modalContext:{modalId:r,modalIndex:K,hostRaw:ee,originalModalNode:ne,editIndexPath:Se}}),g(!1),st({op:"load",layoutName:n,editMode:o,statusCode:Y.status,timestamp:Date.now()});return}}if(o==="iteration_item"&&s){const ee=se,fe=Ze(s),K={children:ee.components??[]},ne=We(K,fe);if(ne&&Array.isArray(ne.children)){l({layoutName:n,raw:ee,lockVersion:re,iterationContext:{sourcePath:s,sourceIndexPath:fe,hostRaw:ee}}),g(!1),st({op:"load",layoutName:n,editMode:o,statusCode:Y.status,timestamp:Date.now()});return}}l({layoutName:n,raw:se,lockVersion:re}),g(!1),st({op:"load",layoutName:n,editMode:o,statusCode:Y.status,timestamp:Date.now()})}catch(P){f(io(P,"layout")),l(null),g(!1)}finally{c(!1)}},[t,n,o,r,s,_]);u.useEffect(()=>{$()},[$]);const A=u.useCallback(async()=>{S(_(o,n)),na(),b(L=>L+1),await $()},[S,_,o,n,$]),z=u.useCallback(()=>{S(_(o,n))},[S,_,o,n]),D=u.useCallback(L=>{l(I=>{if(!I)return I;const P=I.raw.components??[],F=L(P),G={...I.raw,components:F};return E(G,I.lockVersion),{...I,raw:G}}),g(!0),st({op:"patch",layoutName:n,editMode:o,isDirty:!0,timestamp:Date.now()})},[n,o,E]),O=u.useCallback(()=>{g(!0),st({op:"patch",layoutName:n,editMode:o,isDirty:!0,timestamp:Date.now()})},[n,o]),M=u.useCallback(L=>{l(I=>{if(!I)return I;const P={...I.raw,components:L};return E(P,I.lockVersion),{...I,raw:P}}),g(!0),st({op:"patch",layoutName:n,editMode:o,isDirty:!0,timestamp:Date.now()})},[n,o,E]),B=u.useCallback((L,I,...P)=>{const F=P.length>=1?P[0]:I;l(G=>{if(!G)return G;const V={...G.raw,[L]:I},Y=G.raw.__editor;if(Y&&typeof Y=="object"&&!Array.isArray(Y)){const Z=Y,se=Z.original;se&&typeof se=="object"&&!Array.isArray(se)&&(V.__editor={...Z,original:{...se,[L]:F}})}return E(V,G.lockVersion),{...G,raw:V}}),g(!0),st({op:"patch",layoutName:n,editMode:o,isDirty:!0,timestamp:Date.now()})},[n,o,E]),N=u.useCallback(async L=>{const I=C.current;if(!I)return st({op:"save_guard_result",layoutName:n,editMode:o,guardBlocked:!1,timestamp:Date.now()}),{kind:"guard_no_document"};if(L?.resolveActiveExtensions&&L.sessionAddedPaths?.length)try{const fe=await L.resolveActiveExtensions(),K=o7(I.raw.components,L.sessionAddedPaths,fe);if(K.length>0)return st({op:"save_guard_result",layoutName:n,editMode:o,guardBlocked:!0,guardBlockedPaths:K,timestamp:Date.now()}),{kind:"blocked_inactive_extension",blockedPaths:K}}catch{}if(Hb())try{await Fb(t)}catch{}const P=`/api/admin/templates/${encodeURIComponent(t)}/layouts/${I.layoutName}`,F=ar(),G={Accept:"application/json","Content-Type":"application/json"};F&&(G.Authorization=`Bearer ${F}`);const V=!!I.modalContext,Y=!!I.iterationContext,Z=V||Y?"host_layout_modal_patch":"layout";st({op:"save",layoutName:I.layoutName,editMode:o,saveTarget:Z,endpoint:P,isDirty:y,timestamp:Date.now()});let se;if(V&&I.modalContext){const{modalIndex:fe,hostRaw:K,originalModalNode:ne,editIndexPath:me}=I.modalContext,Ce=Array.isArray(K.modals)?[...K.modals]:[],ze=Array.isArray(I.raw.components)?I.raw.components:[],Se=me&&me.length===1?me[0]:0,qe=ze.length>Se?ze[Se]:void 0,De=qe?Vn([qe]):[],Pe=De.length>0?{...De[0]}:void 0;if(fe>=0&&fe({...Me,children:ze})).children??[];se={...Se,components:Qe}}else se=vo(I.raw);const re=se;let U;try{U=await fetch(P,{method:"PUT",headers:G,credentials:"same-origin",body:JSON.stringify({content:JSON.stringify(re),expected_lock_version:I.lockVersion})})}catch(fe){const K=fe instanceof Error?fe.message:"network error";return st({op:"save_response",layoutName:I.layoutName,editMode:o,endpoint:P,statusCode:0,timestamp:Date.now()}),{kind:"network_error",message:K}}const ee=await U.json().catch(()=>null);if(st({op:"save_response",layoutName:I.layoutName,editMode:o,endpoint:P,statusCode:U.status,conflict:U.status===409?{currentVersion:ee?.current_version,yourVersion:ee?.your_version}:void 0,timestamp:Date.now()}),U.ok){const fe=typeof ee?.data?.lock_version=="number"?ee.data.lock_version:I.lockVersion+1;l({...I,lockVersion:fe}),g(!1),S(_(o,I.layoutName)),T(I.layoutName),na(),h(ne=>ne+1);const K=typeof ee?.data?.current_version=="number"?ee.data.current_version:void 0;return{kind:"success",newLockVersion:fe,newContentVersion:K,savedLayoutName:I.layoutName}}return U.status===409?{kind:"concurrent_modification",currentVersion:ee?.current_version??-1,yourVersion:ee?.your_version??I.lockVersion}:U.status===422?{kind:"validation_failed",status:422,errors:ee?.errors??null}:{kind:"network_error",message:ee?.message??`HTTP ${U.status}`}},[t,n,o,y,S,T,_,r,s]),H=u.useMemo(()=>{const L=new Set,I="route|";for(const P of k)if(P.startsWith(I)){const F=P.slice(I.length);F&&L.add(F)}return L},[k]);return{document:a,isLoading:d,error:p,isDirty:y,saveSuccessCounter:m,reloadCounter:v,dirtyKeys:k,dirtyLayoutNames:H,invalidateCurrentCache:z,reload:A,patchLayout:D,setLayoutComponents:M,patchDocumentRaw:B,save:N,markDirty:O}}function o7(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=r7(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 r7(e,t){const n=Ze(t);return n.length===0?null:We({children:e},n)}function so(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 ao(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 $p(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 Ep=44;function Ip(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 y=f.map(h=>h.getBoundingClientRect()),g=new Set(y.map(h=>Math.round(h.top))),m=new Set(y.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 s7(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??Dp(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=a7(s,o,a,l);if(p)return{points:p,flow:s}}return{points:l7(s,a,l),flow:s}},[t,n,o,r])}function a7(e,t,n,o){let r=t.parentElement;for(;r&&Np(r)==="contents";)r=r.parentElement;if(!r)return null;const s=[];if(zp(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 b=v.rect,x=b.top+b.height/2,k=Math.min(a.bottom,b.bottom)-Math.max(a.top,b.top),w=Math.min(a.height,b.height)||1;k/w>.4?d.push({rect:b,path:v.path}):xv.rect.left-b.rect.left),c.sort((v,b)=>v.rect.top-b.rect.top),p.sort((v,b)=>v.rect.top-b.rect.top);const f=d.findIndex(v=>Math.abs(v.rect.left-a.left)<1&&Math.abs(v.rect.top-a.top)<1),y={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],b=Xr(v.path);b&&(m.disabled=!1,m.insertion=b)}else if(d.length>0){const v=d[0],b=Yr(v.path);b&&(m.disabled=!1,m.insertion=b)}if(f>=0&&f0){const v=d[d.length-1],b=Xr(v.path);b&&(h.disabled=!1,h.insertion=b)}if(c.length>0){const v=c[c.length-1],b=Xr(v.path);b&&(y.disabled=!1,y.insertion=b)}else if(s.length>0){const v=s[0],b=Yr(v.path);b&&(y.disabled=!1,y.insertion=b)}if(p.length>0){const v=p[0],b=Yr(v.path);b&&(g.disabled=!1,g.insertion=b)}else if(s.length>0){const v=s[s.length-1],b=Xr(v.path);b&&(g.disabled=!1,g.insertion=b)}else g.disabled=!1,g.insertion={parentPath:n,index:o+1};return y.disabled&&g.disabled&&m.disabled&&h.disabled?null:[y,g,m,h]}function Np(e){return typeof window>"u"?"":(window.getComputedStyle(e).display??"").toLowerCase()}function zp(e,t){const n=Array.from(e.children);for(const o of n){if(Np(o)==="contents"){zp(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:Ze(s)})}}function Yr(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 Xr(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 l7(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 d7(e=50){const t=u.useRef([]),n=u.useRef(-1),[,o]=u.useState(0),r=()=>{o(p=>(p+1)%1e6)},s=(p,f)=>{const y=t.current.length,g=n.current;Gh({op:p,actionKind:f?.actionKind,label:f?.label,stackSize:y,cursor:g,canUndo:g>0,canRedo:g>=0&&g{const y=t.current.slice(0,n.current+1);for(y.push(p);y.length>e;)y.shift();t.current=y,n.current=y.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(c7(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 p7=20,Mp=50,f7=90,Ln=120,g7=130,Lp=80,h7=9e3,Pp=1e4;function y7(e){const t=e<0?0:e>Mp?Mp:e;return p7+t}function b7(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(),[y,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=y===h.index,b=h.danger?"#dc2626":"#0f172a",x=h.danger?"#fee2e2":"#e0e7ff",k=h.danger?"#b91c1c":"#1d4ed8";return i.jsx("button",{type:"button",role:"menuitem","data-testid":h.testid,title:h.hint,onClick:w=>{w.stopPropagation(),h.onSelect(),g(null),o()},onMouseEnter:()=>g(h.index),onFocus:()=>g(h.index),style:{...m7,color:v?k:b,background:v?x:"transparent"},children:h.label},h.testid)})})}const m7={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 v7(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:y,onJumpToDevice:g,onLinkEditDestination:m,onEditBase:h,onEditExtension:v,extensionLabel:b,baseLayoutLabel:x,dataSourceLabel:k,branchLabel:w,onEditIteration:_,resizeEnabledAxes:C,onResizeHandlePointerDown:E,selectedName:S,onSelectParent:T}=e,{t:$}=tt(),[A,z]=u.useState(!1),D=_p(o),O=A&&D,M=Ip(n),B=M==="outside",N=B&&n?Tp(n):null,H=N?{left:N.right.left,top:N.above.top}:{right:-30,top:-30},L={top:-28,left:0},P=B&&!!S?{top:-50,left:0}:L,F=N?{top:N.below.top+28,left:0}:{top:"auto",bottom:-28},G=N?{top:N.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:[w?i.jsxs("span",{"data-testid":"g7le-overlay-branch-badge",style:x7,children:["📱 ",w]}):null,S&&(T?i.jsxs("button",{type:"button","data-testid":"g7le-overlay-type-label","data-placement":B?"outside":"inside",title:$("layout_editor.overlay.select_parent"),"aria-label":$("layout_editor.overlay.select_parent"),onClick:V=>{V.preventDefault(),V.stopPropagation(),T()},style:B?k7:w7,children:[i.jsx("span",{"aria-hidden":!0,style:{marginRight:3,opacity:.85},children:"↑"}),S]}):i.jsx("span",{"data-testid":"g7le-overlay-type-label","data-placement":B?"outside":"inside",style:B?Bp:Op,children:S})),D&&i.jsx("button",{type:"button","data-testid":"g7le-overlay-info-button","aria-label":"info",onClick:V=>{V.stopPropagation(),z(Y=>!Y)},"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(_7,{enabledAxes:C,onHandlePointerDown:E}),o==="base"&&h&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-edit-base",onClick:V=>{V.stopPropagation(),h()},style:{...Po,...L},children:["🔒 ",$("layout_editor.overlay.edit_common_layout"),x?i.jsx("span",{"data-testid":"g7le-overlay-base-layout-label",style:ra,children:x}):null]}),o==="extension"&&v&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-edit-extension",onClick:V=>{V.stopPropagation(),v()},style:{...Po,...L},children:["🔒 ",$("layout_editor.overlay.edit_extension"),b?i.jsx("span",{"data-testid":"g7le-overlay-extension-label",style:ra,children:b}):null]}),o==="data_bound"&&i.jsxs("span",{"data-testid":"g7le-overlay-data-bound-notice",style:{...Po,...P,pointerEvents:"none",cursor:"default"},children:[$("layout_editor.overlay.locked_data_bound"),k?i.jsx("span",{"data-testid":"g7le-overlay-data-source-label",style:ra,children:k}):null]}),o==="data_bound"&&_&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-edit-iteration",onClick:V=>{V.stopPropagation(),_()},style:{...Po,...F},children:["↳ ",$("layout_editor.overlay.edit_iteration_item")]}),r==="route_in_tree"&&i.jsx("button",{type:"button","data-testid":"g7le-overlay-link-edit-destination",onClick:V=>{V.stopPropagation(),m()},style:{...Po,...F},children:$("layout_editor.overlay.edit_destination_route")}),(d||p||g&&(y??[]).length>0)&&i.jsxs("div",{"data-testid":"g7le-overlay-branch-affordances",style:{position:"absolute",...G,display:"flex",flexDirection:"column",alignItems:"flex-start",gap:4,pointerEvents:"none"},children:[g&&(y??[]).map(V=>i.jsxs("button",{type:"button","data-testid":`g7le-overlay-jump-device-${V.key}`,title:$("layout_editor.overlay.jump_device_hint",{device:V.label}),onClick:Y=>{Y.stopPropagation(),g(V.key)},style:oa,children:["↗ ",$("layout_editor.overlay.jump_device",{device:V.label})]},V.key)),d&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-separate-branch",title:$("layout_editor.context_menu.separate_branch_hint"),onClick:V=>{V.stopPropagation(),d()},style:oa,children:["📱 ",c??$("layout_editor.context_menu.separate_branch")]}),p&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-merge-branch",title:$("layout_editor.context_menu.merge_branch_hint"),onClick:V=>{V.stopPropagation(),p()},style:oa,children:["↩️ ",f??$("layout_editor.context_menu.merge_branch")]})]})]}),i.jsx(b7,{anchor:n&&O?{left:n.left+n.width+8,top:n.top-4}:null,open:O,onClose:()=>z(!1),onEditProps:s,onDuplicate:a,onDelete:l,onSeparateBranch:d,separateBranchLabel:c,onMergeBranch:p,mergeBranchLabel:f})]})}function _7(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 Po={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},oa={background:"#fff",border:"1px solid #2563eb",color:"#2563eb",padding:"2px 6px",fontSize:11,borderRadius:4,cursor:"pointer",pointerEvents:"auto",whiteSpace:"nowrap",zIndex:Ln},ra={marginLeft:6,padding:"0 5px",borderRadius:3,background:"#eef2ff",border:"1px solid #c7d2fe",fontSize:10,fontWeight:600,color:"#3730a3"},x7={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"},Op={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"},Bp={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"},w7={...Op,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},k7={...Bp,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},S7={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 C7(e){const{selectedBox:t,points:n,onAddRequest:o}=e,{t:r}=tt();if(!t||n.length===0)return null;const s=Ip(t),l=s==="outside"?Tp(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}:S7[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 Jr=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function lo(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function ia(e){return"nodeType"in e}function _t(e){var t,n;return e?lo(e)?e:ia(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function sa(e){const{Document:t}=_t(e);return e instanceof t}function Oo(e){return lo(e)?!1:e instanceof _t(e).HTMLElement}function Wp(e){return e instanceof _t(e).SVGElement}function co(e){return e?lo(e)?e.document:ia(e)?sa(e)?e:Oo(e)||Wp(e)?e.ownerDocument:document:document:document}const sn=Jr?u.useLayoutEffect:u.useEffect;function Zr(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 Bo(e,t){t===void 0&&(t=[e]);const n=u.useRef(e);return sn(()=>{n.current!==e&&(n.current=e)},t),n}function Wo(e,t){const n=u.useRef();return u.useMemo(()=>{const o=e(n.current);return n.current=o,o},[...t])}function Qr(e){const t=Zr(e),n=u.useRef(null),o=u.useCallback(r=>{r!==n.current&&t?.(r,n.current),n.current=r},[]);return[n,o]}function Rr(e){const t=u.useRef();return u.useEffect(()=>{t.current=e},[e]),t.current}let aa={};function ei(e,t){return u.useMemo(()=>{if(t)return t;const n=aa[e]==null?0:aa[e]+1;return aa[e]=n,e+"-"+n},[e,t])}function jp(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 uo=jp(1),ti=jp(-1);function E7(e){return"clientX"in e&&"clientY"in e}function la(e){if(!e)return!1;const{KeyboardEvent:t}=_t(e.target);return t&&e instanceof t}function I7(e){if(!e)return!1;const{TouchEvent:t}=_t(e.target);return t&&e instanceof t}function ni(e){if(I7(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 E7(e)?{x:e.clientX,y:e.clientY}:null}const jo=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[jo.Translate.toString(e),jo.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:o}=e;return t+" "+n+"ms "+o}}}),Hp="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function A7(e){return e.matches(Hp)?e:e.querySelector(Hp)}const T7={display:"none"};function D7(e){let{id:t,value:n}=e;return u.createElement("div",{id:t,style:T7},n)}function N7(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 z7(){const[e,t]=u.useState("");return{announce:u.useCallback(o=>{o!=null&&t(o)},[]),announcement:e}}const Fp=u.createContext(null);function M7(e){const t=u.useContext(Fp);u.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(e)},[e,t])}function L7(){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 P7={draggable:` +`);return t.length>0&&t[t.length-1]===""&&t.pop(),t}const Yu=4e3;function $$(e,t,n=3){const o=Gu(e),r=Gu(t);let s=0;const a=Math.min(o.length,r.length);for(;sYu||p.length>Yu)return{hunks:[],addedCount:-1,removedCount:-1,identical:!1};const f=S$(c,p),y=C$(c,p,f),g=[];let m=s,h=s,v=0,b=0;for(let w=0;w{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 Xu(e){return JSON.stringify(Js(e),null,2)}function Js(e){if(Array.isArray(e))return e.map(Js);if(e&&typeof e=="object"){const t=e,n={};for(const o of Object.keys(t).sort())n[o]=Js(t[o]);return n}return e}const I$={display:"flex",flexDirection:"column",height:"100%",minHeight:0},A$={display:"flex",alignItems:"center",gap:8,padding:"12px 16px",borderBottom:"1px solid #e2e8f0",background:"#f8fafc"},T$={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"},D$={marginLeft:"auto",border:"none",background:"transparent",fontSize:16,color:"#64748b",cursor:"pointer",outline:"none"},N$={display:"flex",alignItems:"center",gap:12,padding:"8px 16px",borderBottom:"1px solid #e2e8f0",background:"#ffffff",fontSize:12,fontWeight:600},z$={flex:1,minHeight:0,overflow:"auto",background:"#ffffff",fontFamily:'ui-monospace, SFMono-Regular, Menlo, Monaco, Consolas, "Liberation Mono", monospace',fontSize:12,lineHeight:1.5},Ju={padding:"24px 12px",textAlign:"center",color:"#94a3b8",fontSize:13},M$={padding:"2px 12px",background:"#f1f5f9",color:"#64748b",borderTop:"1px solid #e2e8f0",borderBottom:"1px solid #e2e8f0",userSelect:"none"};function L$(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 Zu={display:"inline-block",width:44,textAlign:"right",padding:"0 6px",color:"#94a3b8",userSelect:"none",borderRight:"1px solid #e2e8f0",whiteSpace:"nowrap"};function P$({oldVersion:e,newVersion:t,oldContent:n,newContent:o,t:r,onBack:s,onClose:a}){const l=u.useMemo(()=>{const c=Xu(n),p=Xu(o);return $$(c,p)},[n,o]),d=l.addedCount<0;return i.jsxs("div",{className:"g7le-version-diff","data-testid":"g7le-version-diff",style:I$,children:[i.jsxs("div",{"data-modal-drag-handle":!0,style:A$,children:[i.jsxs("button",{type:"button",onClick:s,style:T$,"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:D$,"data-testid":"g7le-version-diff-close",children:"✕"})]}),!d&&i.jsxs("div",{style:N$,"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:z$,children:d?i.jsx("div",{style:Ju,"data-testid":"g7le-version-diff-too-large",children:r("layout_editor.version_history.diff_too_large")}):l.identical?i.jsx("div",{style:Ju,"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:M$,"data-testid":`g7le-version-diff-hunk-header-${p}`,children:c.header}),c.lines.map((f,y)=>{const g=L$(f.kind);return i.jsxs("div",{style:{display:"flex",alignItems:"stretch",...g.row},"data-kind":f.kind,"data-testid":`g7le-version-diff-line-${p}-${y}`,children:[i.jsx("span",{style:{...Zu,...g.gutter},"aria-hidden":"true",children:f.oldLine??""}),i.jsx("span",{style:{...Zu,...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})]},y)})]},p))})]})}const O$={display:"flex",flexDirection:"column",height:"100%",minHeight:0},B$={display:"flex",alignItems:"center",gap:8,padding:"12px 16px",borderBottom:"1px solid #e2e8f0",background:"#f8fafc"},W$={marginLeft:"auto",border:"none",background:"transparent",fontSize:16,color:"#64748b",cursor:"pointer",outline:"none"},j$={flex:1,minHeight:0,overflowY:"auto",padding:12},Qu={padding:"24px 12px",textAlign:"center",color:"#94a3b8",fontSize:13},H$={margin:"8px 16px 0",padding:"8px 12px",borderRadius:6,background:"#fef2f2",color:"#b91c1c",fontSize:12,border:"1px solid #fecaca"},F$={display:"flex",flexDirection:"column",gap:8},K$={display:"flex",alignItems:"center",gap:12,padding:"10px 12px",borderRadius:8,border:"1px solid #e2e8f0",background:"#ffffff"},V$={display:"inline-flex",alignItems:"center",justifyContent:"center",minWidth:44,padding:"2px 8px",borderRadius:999,background:"#eff6ff",color:"#1d4ed8",fontSize:12,fontWeight:700},U$={display:"inline-flex",alignItems:"center",padding:"1px 8px",borderRadius:999,background:"#0f172a",color:"#ffffff",fontSize:10,fontWeight:700,letterSpacing:.3},q$={display:"flex",alignItems:"center",gap:10,fontSize:11,fontWeight:600},G$={display:"flex",flexDirection:"column",gap:2,minWidth:0,flex:1},Ru={padding:"6px 12px",borderRadius:6,border:"1px solid #cbd5e1",background:"#ffffff",color:"#0f172a",fontSize:12,fontWeight:600,cursor:"pointer",outline:"none",whiteSpace:"nowrap"};function ep(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 Y$(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 X$({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:y,restore:g,loadVersionDetail:m}=k$(e,t,o),[h,v]=u.useState(null),[b,x]=u.useState(null),[k,w]=u.useState(null);u.useEffect(()=>{f()},[f]);const _=u.useCallback(async S=>{v(null),w(S.version);try{const T=await m(S.version);if(T.kind!=="success"){v(T.kind==="not_found"?n("layout_editor.version_history.restore_not_found"):T.message);return}const $=S.version-1,A=s.some(D=>D.version===$);let z={};if(A){const D=await m($);if(D.kind==="success")z=ep(D.detail);else if(D.kind==="network_error"){v(D.message);return}}x({oldVersion:A?$:0,newVersion:S.version,oldContent:z,newContent:ep(T.detail)})}finally{w(null)}},[m,s,n]),C=u.useCallback(async S=>{v(null);const T=n("layout_editor.version_history.restore_confirm");if(!(typeof window<"u"?window.confirm(T):!0))return;const A=await g(S);A.kind==="success"?r():A.kind==="not_found"?v(n("layout_editor.version_history.restore_not_found")):v(A.message)},[g,r,n]),E=h??d;return b?i.jsx(P$,{oldVersion:b.oldVersion,newVersion:b.newVersion,oldContent:b.oldContent,newContent:b.newContent,t:n,onBack:()=>x(null),onClose:r}):i.jsxs("div",{className:"g7le-version-history","data-testid":"g7le-version-history",style:O$,children:[i.jsxs("div",{"data-modal-drag-handle":!0,style:B$,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:W$,"data-testid":"g7le-version-history-close",children:"✕"})]}),E&&i.jsx("div",{style:H$,"data-testid":"g7le-version-history-error",children:E}),i.jsx("div",{style:j$,children:a?i.jsx("div",{style:Qu,"data-testid":"g7le-version-history-loading",children:n("layout_editor.version_history.loading")}):s.length===0?i.jsx("div",{style:Qu,"data-testid":"g7le-version-history-empty",children:n("layout_editor.version_history.empty")}):i.jsxs("div",{"data-testid":"g7le-version-history-list",style:F$,children:[s.map((S,T)=>{const $=S.changes_summary,A=$?.added_count??0,z=$?.removed_count??0,D=$?.char_diff??0,O=Y$(S.created_at),M=c===S.id,B=T===0;return i.jsxs("div",{style:K$,"data-testid":`g7le-version-row-${S.id}`,children:[i.jsxs("span",{style:V$,"data-testid":`g7le-version-badge-${S.id}`,children:["v",S.version]}),i.jsxs("div",{style:G$,children:[i.jsxs("span",{style:{display:"flex",alignItems:"center",gap:8},children:[O&&i.jsx("span",{style:{fontSize:12,color:"#475569",fontWeight:600},children:O}),B&&i.jsx("span",{style:U$,"data-testid":`g7le-version-latest-${S.id}`,children:n("layout_editor.version_history.latest")})]}),i.jsxs("span",{style:q$,"data-testid":`g7le-version-summary-${S.id}`,children:[i.jsx("span",{style:{color:"#16a34a"},"data-testid":`g7le-version-added-${S.id}`,children:n("layout_editor.version_history.added",{count:A})}),i.jsx("span",{style:{color:"#dc2626"},"data-testid":`g7le-version-removed-${S.id}`,children:n("layout_editor.version_history.removed",{count:z})}),i.jsx("span",{style:{color:"#94a3b8",fontWeight:500},"data-testid":`g7le-version-chars-${S.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-${S.id}`,children:n("layout_editor.version_history.saved_by",{name:S.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 _(S),disabled:k!==null,style:{...Ru,background:"#f8fafc",opacity:k!==null?.6:1},"data-testid":`g7le-version-compare-${S.id}`,children:k===S.version?n("layout_editor.version_history.comparing"):n("layout_editor.version_history.compare")}),!B&&i.jsx("button",{type:"button",onClick:()=>void C(S.id),disabled:M||c!==null,style:{...Ru,opacity:M||c!==null?.6:1},"data-testid":`g7le-version-restore-${S.id}`,children:n(M?"layout_editor.version_history.restoring":"layout_editor.version_history.restore")})]})]},S.id)}),p&&i.jsx("button",{type:"button","data-testid":"g7le-version-history-load-more",style:J$,disabled:l,onClick:()=>{y()},children:n(l?"layout_editor.version_history.loading":"layout_editor.version_history.load_more")})]})})]})}const J$={width:"100%",marginTop:8,padding:"8px 12px",fontSize:12,color:"#475569",background:"#f8fafc",border:"1px solid #e2e8f0",borderRadius:6,cursor:"pointer"},tp=[{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 Z$(e){return{key:(e.key||"").toLowerCase(),mod:e.ctrlKey||e.metaKey,shift:e.shiftKey,alt:e.altKey}}function Q$(e,t){return e.key===t.key&&!!e.mod==!!t.mod&&!!e.shift==!!t.shift&&!!e.alt==!!t.alt}function R$(e){for(const t of tp)if(t.combos.some(n=>Q$(n,e)))return t;return null}function eE(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(tE(e.key)),n.join(" + ")}function tE(e){return{arrowup:"↑",arrowdown:"↓",arrowleft:"←",arrowright:"→",enter:"Enter",escape:"Esc",delete:"Delete",backspace:"Backspace"," ":"Space"}[e]??(e.length===1?e.toUpperCase():e)}const nE=["clipboard","element","history","view","document"],oE={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 rE(){return typeof navigator>"u"?!1:/mac|iphone|ipad|ipod/i.test(navigator.platform||navigator.userAgent||"")}function iE({t:e,onClose:t,isMac:n}){const o=n??rE(),r=u.useMemo(()=>{const s=new Map;for(const a of tp){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:sE,children:[i.jsxs("div",{style:aE,children:[i.jsx("span",{style:lE,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:dE,children:"✕"})]}),i.jsx("div",{style:cE,children:nE.map(s=>{const a=r.get(s);return!a||a.length===0?null:i.jsxs("div",{style:uE,"data-testid":`g7le-shortcut-group-${s}`,children:[i.jsx("div",{style:pE,children:e(oE[s])}),i.jsx("table",{style:fE,children:i.jsx("tbody",{children:a.map(l=>i.jsxs("tr",{"data-testid":`g7le-shortcut-row-${l.id}`,children:[i.jsx("td",{style:gE,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:bE,children:e("layout_editor.shortcuts.or")}),i.jsx("kbd",{style:yE,children:eE(d,o)})]},c))})]},l.id))})})]},s)})}),i.jsx("div",{style:mE,children:e("layout_editor.shortcuts.footnote")})]})}const sE={display:"flex",flexDirection:"column",padding:20,gap:16,width:"100%",boxSizing:"border-box"},aE={display:"flex",alignItems:"center",justifyContent:"space-between",paddingBottom:12,borderBottom:"1px solid #e2e8f0"},lE={fontSize:15,fontWeight:700,color:"#0f172a"},dE={width:28,height:28,border:"none",background:"transparent",color:"#64748b",cursor:"pointer",fontSize:14,borderRadius:6},cE={display:"grid",gridTemplateColumns:"1fr 1fr",columnGap:28,rowGap:18,alignItems:"start"},uE={display:"flex",flexDirection:"column",gap:6},pE={fontSize:12,fontWeight:700,color:"#2563eb"},fE={width:"100%",borderCollapse:"collapse"},gE={padding:"4px 0",fontSize:12.5,color:"#334155",textAlign:"left",whiteSpace:"nowrap",verticalAlign:"middle"},hE={padding:"4px 0",paddingLeft:12,textAlign:"right",verticalAlign:"middle"},yE={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"},bE={fontSize:11,color:"#94a3b8",margin:"0 4px"},mE={fontSize:11,color:"#94a3b8",paddingTop:12,borderTop:"1px solid #f1f5f9"};function vE(e){if(!e||!(e instanceof HTMLElement))return!1;const t=e.tagName;return!!(t==="INPUT"||t==="TEXTAREA"||t==="SELECT"||e.isContentEditable)}function _E(){return typeof document>"u"?!1:!!document.querySelector(".g7le-modal-backdrop, .g7le-modal")}function np(e){const{handlers:t,hasSelection:n,enabled:o=!0}=e;u.useEffect(()=>{if(!o||typeof window>"u")return;const r=s=>{if(vE(s.target))return;const a=Z$(s),l=R$(a);if(!l||_E()||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 xE(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(Lo,{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(Lo,{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:op,"data-testid":"g7le-save-banner-validation-errors",children:l.map(([d,c])=>i.jsxs("li",{children:[i.jsx("code",{style:rp,children:d}),": ",c.join(", ")]},d))})]})}return t.kind==="blocked_inactive_extension"?i.jsxs(Lo,{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:op,"data-testid":"g7le-save-banner-blocked-paths",children:t.blockedPaths.map(a=>i.jsx("li",{children:i.jsx("code",{style:rp,children:a})},a))})]}):t.kind==="network_error"?i.jsxs(Lo,{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(Lo,{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:CE,children:i.jsxs("div",{style:$E,children:[i.jsx("h2",{style:EE,children:s("layout_editor.save.concurrent.title")}),i.jsx("p",{style:IE,children:s("layout_editor.save.concurrent.message")}),i.jsx("div",{style:AE,children:s("layout_editor.save.concurrent.version_info",{current:String(t.currentVersion),yours:String(t.yourVersion)})}),i.jsxs("div",{style:TE,children:[i.jsx("button",{type:"button","data-testid":"g7le-save-banner-concurrent-load-latest",onClick:()=>{o?.(),n()},style:DE,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:NE,children:s("layout_editor.save.concurrent.view_my_changes")}),i.jsx("button",{type:"button","data-testid":"g7le-save-banner-concurrent-cancel",onClick:n,style:zE,children:s("layout_editor.save.concurrent.cancel")})]})]})})}function Lo(e){const{tone:t,testId:n,onDismiss:o,children:r}=e,s=wE[t];return i.jsxs("div",{role:"status","data-testid":n,style:{...kE,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:SE,children:"×"})]})}const wE={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"}},kE={display:"flex",alignItems:"flex-start",gap:12,padding:"12px 16px",border:"1px solid",borderRadius:0,fontSize:13,lineHeight:1.5},SE={background:"transparent",border:"none",fontSize:18,cursor:"pointer",lineHeight:1,color:"inherit",padding:"0 4px",flexShrink:0},op={margin:"8px 0 0",paddingLeft:20,fontSize:12},rp={background:"rgba(0, 0, 0, 0.06)",padding:"1px 4px",borderRadius:3,fontFamily:"monospace"},CE={position:"fixed",inset:0,background:"rgba(15, 23, 42, 0.6)",display:"flex",alignItems:"center",justifyContent:"center",zIndex:1e4},$E={background:"#fff",borderRadius:8,padding:24,width:"min(480px, 90vw)",boxShadow:"0 10px 25px rgba(0,0,0,0.15)"},EE={margin:"0 0 8px",fontSize:16,fontWeight:600,color:"#0f172a"},IE={margin:"0 0 12px",color:"#334155",fontSize:13,lineHeight:1.5},AE={marginBottom:16,padding:"8px 12px",background:"#f8fafc",borderRadius:6,fontSize:12,color:"#64748b",fontFamily:"monospace"},TE={display:"flex",gap:8,justifyContent:"flex-end"},DE={padding:"8px 14px",background:"#2563eb",color:"#fff",border:"none",borderRadius:6,fontSize:13,fontWeight:600,cursor:"pointer"},NE={padding:"8px 14px",background:"#fff",color:"#334155",border:"1px solid #cbd5e1",borderRadius:6,fontSize:13,fontWeight:500,cursor:"pointer"},zE={padding:"8px 14px",background:"transparent",color:"#64748b",border:"none",borderRadius:6,fontSize:13,cursor:"pointer"};function ip(e){if(!e)return null;const n=new URLSearchParams(e).get("route");return n&&n.length>0?n:null}function Zs(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 sp(e){if(!e)return null;const n=new URLSearchParams(e).get("host");return n&&n.length>0?n:null}function ap(e){if(!e)return null;const n=new URLSearchParams(e).get("edit");return n&&n.length>0&&n.startsWith("__")?n:null}function ME(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 LE="g7le-editor-route",PE=new Set;function Qs(e){return e.path.startsWith("__group__/")||e.path.startsWith("__conngroup__/")}function lp(e,t){const{t:n,translationEngine:o,translationContext:r,templateIdentifier:s}=t,a=Qs(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 y of l.slice(d+1).split("|")){const g=y.indexOf("=");g!==-1&&(p[y.slice(0,g)]=y.slice(g+1))}if((e.kind==="route"||e.kind==="modal")&&!a&&o&&r&&s!==r.templateId){const y={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,y,g);if(m!==c)return m}const f=n(c,p);if(f===c&&typeof window<"u"){const y=window.G7Core?.t;if(typeof y=="function")try{const g=y(c,p);if(g!==c)return g}catch{}}if(f===c&&e.kind==="route"&&!a){const y=e.path;if(y&&y!=="/"){const g=y.split("/").filter(Boolean);return g[g.length-1]??y}return y==="/"?"/":c}return f}function OE(e){return e.trim().toLocaleLowerCase()}function dp(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 N=f.selectedRoute?.path??"";return N.startsWith("__extension__/")||N.startsWith("__modal__/")?N.slice(N.lastIndexOf("/")+1):null},[f.selectedRoute?.path]),h=u.useMemo(()=>!g||!m?!1:(e.children??[]).some(N=>N.kind==="extension"&&N.extensionId===m||N.kind==="modal"&&N.modalId===m),[g,m,e.children]),[v,b]=u.useState(!0);u.useEffect(()=>{h&&b(!1)},[h]);const x=f.editMode==="extension"?f.selectedRoute?.layoutName??null:null,k=e.kind==="extension"?up(e,f.routeTree)??null:null,w=e.kind==="extension"&&o===e.path&&(x===null||k===null||x===k),_=f.editMode==="modal"&&o?.startsWith("__modal__/")?o.slice(o.lastIndexOf("/")+1):null,C=f.editMode==="modal"?f.selectedRoute?.layoutName??null:null,E=e.kind==="modal"&&!!_&&e.modalId===_&&(C===null||e.modalHostLayout==null||C===e.modalHostLayout),S=e.kind!=="extension"&&e.kind!=="modal"&&o===e.path||w||E||e.kind==="route"&&!y&&r===e.path,$=(e.children?.length??0)>0&&(!g||l||!v),A=!y&&!!e.layoutName&&s.has(e.layoutName),z=y?void 0:e.kind==="extension"?e.extensionId?f.extensionVersions[e.extensionId]:void 0:e.layoutName?f.layoutVersions[e.layoutName]:void 0,D=()=>{if(g){b(N=>!N);return}y||n(e)},O=lp(e,{t:d,translationEngine:c,translationContext:p,templateIdentifier:f.templateIdentifier}),M=y?null:BE(e),B={paddingLeft:12+t*14,paddingRight:12,paddingTop:4,paddingBottom:4,opacity:e.isHidden?.55:1,cursor:g?"pointer":y?"default":"pointer",background:S?"#eff6ff":"transparent",borderLeft:S?"2px solid #2563eb":"2px solid transparent",fontWeight:y||S?600:400,fontSize:y?11:13,color:y?"#64748b":S?"#1d4ed8":"#1e293b",textTransform:y?"uppercase":"none",letterSpacing:y?.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":y?"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||!y?"button":void 0,tabIndex:g||!y?0:void 0,"aria-expanded":g?l?!0:!v:void 0,onClick:D,onKeyDown:N=>{g&&(N.key==="Enter"||N.key===" ")?(N.preventDefault(),b(H=>!H)):!y&&(N.key==="Enter"||N.key===" ")&&(N.preventDefault(),n(e))},style:B,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"}}),y?O:dp(O,a),typeof z=="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(z)}),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",z]}),i.jsx(WE,{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:dp(M,a)})]}),$&&i.jsx("ul",{style:{listStyle:"none",margin:0,padding:0},children:e.children.map(N=>i.jsx(cp,{node:N,depth:t+1,onSelect:n,selectedRoutePath:o,activeHostRoutePath:r,dirtyLayoutNames:s,query:a,forceExpand:l},N.path))})]})}function jE(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 up(e,t){if(e.connectedHostRoutePath){const n=pp(t,e.connectedHostRoutePath);if(n?.layoutName)return n.layoutName}if(e.extensionType==="overlay"&&e.extensionTargetName)return e.extensionTargetName}function pp(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=pp(n.children,t);if(o)return o}}return null}function fp(e,t,n){const o=[];for(const r of e){const s=Qs(r),a=r.children&&r.children.length>0?fp(r.children,t,n):[];if(s){a.length>0&&o.push({...r,children:a});continue}const l=lp(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 HE(){const{t:e,translationEngine:t,translationContext:n}=tt(),{state:o,dispatch:r}=Je(),a=Ft()?.dirtyLayoutNames??PE,[l,d]=u.useState(""),c=OE(l),p=u.useMemo(()=>c?fp(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=up(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=Zs(o.templateIdentifier,h.path);`${window.location.pathname}${window.location.search}`!==v&&window.history.pushState({source:LE,routePath:h.path},"",v)}},y=o.selectedRoute?.path??null,g=u.useMemo(()=>jE(o.routeTree,y),[o.routeTree,y]);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(cp,{node:h,depth:0,onSelect:f,selectedRoutePath:y,activeHostRoutePath:g,dirtyLayoutNames:a,query:c,forceExpand:!!c},h.path))})})]})}const FE=Lt().DynamicRenderer,Rs=Lt(),KE=Rs.ResponsiveProvider;Rs.useResponsive,Rs.ResponsiveContext;const VE=Lt().ActionDispatcher,gp=Lt(),UE=gp.DataSourceManager;gp.dataSourceManager;function Gr(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 io(e,t){return{kind:"network",status:0,message:e instanceof Error?e.message:String(e??"Unknown network error"),source:t}}function hp(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 Ze(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 qE(e,t){if(!e)return{affordance:"none",targetPath:null};const n=GE(e);return n?YE(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 GE(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 YE(e){return/\{\{[\s\S]*?\}\}/.test(e)}function XE(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 JE(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=QE(o);if(a!==null)return a}const r=[];if(typeof e.text=="string"&&r.push(...yp(e.text)),e.props&&typeof e.props=="object")for(const a of Object.values(e.props))typeof a=="string"&&r.push(...yp(a));return r.length===0?null:r.find(a=>!ZE.has(a))??r[0]}const ZE=new Set(["_local","_global","_computed","route","query","props","item","index","event","$event","$response","response"]);function yp(e){const t=[],n=/\{\{([\s\S]*?)\}\}/g;let o;for(;(o=n.exec(e))!==null;){const r=bp(o[1]);r!==null&&t.push(r)}return t}function QE(e){const t=e.replace(/\{\{|\}\}/g,"");return bp(t)}function bp(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(td(e)||typeof e.slot=="string"||typeof e.__editorSlotName=="string")return"extension_point";if(t!=="route"&&Ji(e,t,n)){const s=e.__source?.kind;return s==="base"?"base":s==="partial"?"partial":s==="extension"?"extension":"base"}if(Cb(e,o))return"data_bound";if(!Ji(e,t,n))return"none";const r=e.__source?.kind;return r==="base"?"base":r==="partial"?"partial":r==="extension"?"extension":"none"}function mp(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 RE(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 vp(e,t,n,o){if(!e||!t)return t;const r=n(t),s=Ib(e,r,o);return s.length===r.length?t:RE(t,s.length)}function _p(e){return e==="none"||e==="data_bound"}function e7(e){const{rootNode:t,editMode:n,currentExtensionId:o,editableRootPath:r,pathParser:s=Ze,resolveRouteMatch:a}=e,[l,d]=u.useState(null),[c,p]=u.useState(null),f=u.useCallback(x=>{if(x===null||n==="route")return!0;if(n==="iteration_item"||n==="modal"){if(!r||r.length===0)return!0;const C=s(x);return xp(C,r)}const k=ea(t,x,s);if(!k)return!0;const w=ta(t,x,s),_=gn(k,n,o,w);return _==="none"||_==="data_bound"},[t,s,n,o,r]),y=u.useCallback((x,k)=>{const _=(k?.currentTarget?.dataset??k?.dataset)?.editorPath??null,C=vp(t,_,s,o);f(C)&&d(C)},[t,s,o,f]),g=u.useCallback((x,k)=>{if(x===null){p(null);return}const _=(k?.currentTarget?.dataset??k?.dataset)?.editorPath??null,C=vp(t,_,s,o);if(!f(C)){p(null);return}p(C)},[t,s,o,f]),m=u.useCallback(()=>{d(null)},[]),h=u.useMemo(()=>{const x=ea(t,l,s),k=ea(t,c,s),w=x?ta(t,l,s):[];let _=gn(x,n,o,w);(n==="iteration_item"||n==="modal")&&l!==null&&x&&r&&r.length>0&&xp(s(l),r)&&(nd(x)?_="data_bound":_==="data_bound"&&(_="none"));const{affordance:C,targetPath:E}=qE(x,a),S=_==="base"&&typeof x?.__source?.layout=="string"?x.__source.layout:null,T=_==="data_bound"&&x?JE(x,w):null,{isIteration:$,iterationSourcePath:A}=_==="data_bound"&&x?XE(x,w,l):{isIteration:!1,iterationSourcePath:null};return{selectedNode:x,hoverNode:k,selectedLockKind:_,selectedNavAffordance:C,selectedNavTargetPath:E,selectedBaseLayout:S,selectedDataSourceId:T,selectedIsIteration:$,selectedIterationSourcePath:A}},[t,l,c,n,o,r,s,a]),v=u.useRef(void 0);v.current!==l&&(v.current=l,Cl({op:l===null?"clear":"select",componentPath:l,componentName:wp(h.selectedNode),lockKind:h.selectedLockKind,navAffordance:h.selectedNavAffordance,sourceExtensionId:mp(h.selectedNode),timestamp:Date.now()}));const b=u.useRef(void 0);return b.current!==c&&(b.current=c,c!==null&&Cl({op:"hover",componentPath:c,componentName:wp(h.hoverNode),lockKind:gn(h.hoverNode,n,o,ta(t,c,s)),navAffordance:"none",sourceExtensionId:mp(h.hoverNode),timestamp:Date.now()})),{selectedPath:l,hoverPath:c,...h,handleSelect:y,handleHover:g,clearSelection:m}}function ea(e,t,n){if(!e||!t)return null;const o=n(t);return We(e,o)}function xp(e,t){if(e.length0?e.name:typeof e.type=="string"&&e.type.length>0?e.type:null:null}let kp=0;function Sp(){return kp}function na(){kp+=1}function t7(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 n7(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 Cp(){const{state:e}=Je(),t=e.templateIdentifier,n=e.selectedRoute?.layoutName??null,o=e.editMode,r=o==="modal"?t7(e.selectedRoute?.path):null,s=o==="iteration_item"?n7(e.selectedRoute?.path):null,[a,l]=u.useState(null),[d,c]=u.useState(!1),[p,f]=u.useState(null),[y,g]=u.useState(!1),[m,h]=u.useState(0),[v,b]=u.useState(0),x=u.useRef(new Map),[k,w]=u.useState(()=>new Set),_=u.useCallback((L,I)=>`${L}|${I??""}`,[]),C=u.useRef(null);u.useEffect(()=>{C.current=a},[a]);const E=u.useCallback((L,I)=>{const P=_(o,n);x.current.set(P,{raw:L,lockVersion:I}),w(F=>{if(F.has(P))return F;const G=new Set(F);return G.add(P),G})},[_,o,n]),S=u.useCallback(L=>{x.current.delete(L),w(I=>{if(!I.has(L))return I;const P=new Set(I);return P.delete(L),P})},[]),T=u.useCallback(L=>{const I=`|${L??""}`,P=[];for(const F of x.current.keys())F.endsWith(I)&&P.push(F);for(const F of P)x.current.delete(F);P.length>0&&w(F=>{let G=!1;const V=new Set(F);for(const Y of P)V.delete(Y)&&(G=!0);return G?V:F})},[]),$=u.useCallback(async()=>{if(!n){l(null),f(null),g(!1);return}const L=_(o,n),I=x.current.get(L);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 P=window.G7Config?.cache_version??0,F=en(`/api/layouts/${encodeURIComponent(t)}/${n}`,"json",`${P}.${Sp()}`,"with_source_meta=1"),G=ar(),V={Accept:"application/json"};G&&(V.Authorization=`Bearer ${G}`);const Y=await fetch(F,{headers:V,credentials:"same-origin"}),Z=await Y.json().catch(()=>null);if(!Y.ok){f(Gr(Y.status,Z,"layout")),l(null),g(!1);return}const se=(Z&&(Z.data||Z))??{},re=typeof se.lock_version=="number"?se.lock_version:0;if(o==="modal"&&r){const ee=se,fe=Array.isArray(ee.modals)?ee.modals:[],K=fe.findIndex(ne=>ne&&(ne.id===r||ne.modal_id===r));if(K>=0){const ne=fe[K],me={...ne,props:{...ne.props??{},isOpen:!0}},ze=[...Array.isArray(ee.components)?ee.components:[],me],Se=[ze.length-1];l({layoutName:n,raw:{...ee,components:ze},lockVersion:re,modalContext:{modalId:r,modalIndex:K,hostRaw:ee,originalModalNode:ne,editIndexPath:Se}}),g(!1),st({op:"load",layoutName:n,editMode:o,statusCode:Y.status,timestamp:Date.now()});return}}if(o==="iteration_item"&&s){const ee=se,fe=Ze(s),K={children:ee.components??[]},ne=We(K,fe);if(ne&&Array.isArray(ne.children)){l({layoutName:n,raw:ee,lockVersion:re,iterationContext:{sourcePath:s,sourceIndexPath:fe,hostRaw:ee}}),g(!1),st({op:"load",layoutName:n,editMode:o,statusCode:Y.status,timestamp:Date.now()});return}}l({layoutName:n,raw:se,lockVersion:re}),g(!1),st({op:"load",layoutName:n,editMode:o,statusCode:Y.status,timestamp:Date.now()})}catch(P){f(io(P,"layout")),l(null),g(!1)}finally{c(!1)}},[t,n,o,r,s,_]);u.useEffect(()=>{$()},[$]);const A=u.useCallback(async()=>{S(_(o,n)),na(),b(L=>L+1),await $()},[S,_,o,n,$]),z=u.useCallback(()=>{S(_(o,n))},[S,_,o,n]),D=u.useCallback(L=>{l(I=>{if(!I)return I;const P=I.raw.components??[],F=L(P),G={...I.raw,components:F};return E(G,I.lockVersion),{...I,raw:G}}),g(!0),st({op:"patch",layoutName:n,editMode:o,isDirty:!0,timestamp:Date.now()})},[n,o,E]),O=u.useCallback(()=>{g(!0),st({op:"patch",layoutName:n,editMode:o,isDirty:!0,timestamp:Date.now()})},[n,o]),M=u.useCallback(L=>{l(I=>{if(!I)return I;const P={...I.raw,components:L};return E(P,I.lockVersion),{...I,raw:P}}),g(!0),st({op:"patch",layoutName:n,editMode:o,isDirty:!0,timestamp:Date.now()})},[n,o,E]),B=u.useCallback((L,I,...P)=>{const F=P.length>=1?P[0]:I;l(G=>{if(!G)return G;const V={...G.raw,[L]:I},Y=G.raw.__editor;if(Y&&typeof Y=="object"&&!Array.isArray(Y)){const Z=Y,se=Z.original;se&&typeof se=="object"&&!Array.isArray(se)&&(V.__editor={...Z,original:{...se,[L]:F}})}return E(V,G.lockVersion),{...G,raw:V}}),g(!0),st({op:"patch",layoutName:n,editMode:o,isDirty:!0,timestamp:Date.now()})},[n,o,E]),N=u.useCallback(async L=>{const I=C.current;if(!I)return st({op:"save_guard_result",layoutName:n,editMode:o,guardBlocked:!1,timestamp:Date.now()}),{kind:"guard_no_document"};if(L?.resolveActiveExtensions&&L.sessionAddedPaths?.length)try{const fe=await L.resolveActiveExtensions(),K=o7(I.raw.components,L.sessionAddedPaths,fe);if(K.length>0)return st({op:"save_guard_result",layoutName:n,editMode:o,guardBlocked:!0,guardBlockedPaths:K,timestamp:Date.now()}),{kind:"blocked_inactive_extension",blockedPaths:K}}catch{}if(Hb())try{await Fb(t)}catch{}const P=`/api/admin/templates/${encodeURIComponent(t)}/layouts/${I.layoutName}`,F=ar(),G={Accept:"application/json","Content-Type":"application/json"};F&&(G.Authorization=`Bearer ${F}`);const V=!!I.modalContext,Y=!!I.iterationContext,Z=V||Y?"host_layout_modal_patch":"layout";st({op:"save",layoutName:I.layoutName,editMode:o,saveTarget:Z,endpoint:P,isDirty:y,timestamp:Date.now()});let se;if(V&&I.modalContext){const{modalIndex:fe,hostRaw:K,originalModalNode:ne,editIndexPath:me}=I.modalContext,Ce=Array.isArray(K.modals)?[...K.modals]:[],ze=Array.isArray(I.raw.components)?I.raw.components:[],Se=me&&me.length===1?me[0]:0,qe=ze.length>Se?ze[Se]:void 0,De=qe?Vn([qe]):[],Pe=De.length>0?{...De[0]}:void 0;if(fe>=0&&fe({...Me,children:ze})).children??[];se={...Se,components:Qe}}else se=vo(I.raw);const re=se;let U;try{U=await fetch(P,{method:"PUT",headers:G,credentials:"same-origin",body:JSON.stringify({content:JSON.stringify(re),expected_lock_version:I.lockVersion})})}catch(fe){const K=fe instanceof Error?fe.message:"network error";return st({op:"save_response",layoutName:I.layoutName,editMode:o,endpoint:P,statusCode:0,timestamp:Date.now()}),{kind:"network_error",message:K}}const ee=await U.json().catch(()=>null);if(st({op:"save_response",layoutName:I.layoutName,editMode:o,endpoint:P,statusCode:U.status,conflict:U.status===409?{currentVersion:ee?.current_version,yourVersion:ee?.your_version}:void 0,timestamp:Date.now()}),U.ok){const fe=typeof ee?.data?.lock_version=="number"?ee.data.lock_version:I.lockVersion+1;l({...I,lockVersion:fe}),g(!1),S(_(o,I.layoutName)),T(I.layoutName),na(),h(ne=>ne+1);const K=typeof ee?.data?.current_version=="number"?ee.data.current_version:void 0;return{kind:"success",newLockVersion:fe,newContentVersion:K,savedLayoutName:I.layoutName}}return U.status===409?{kind:"concurrent_modification",currentVersion:ee?.current_version??-1,yourVersion:ee?.your_version??I.lockVersion}:U.status===422?{kind:"validation_failed",status:422,errors:ee?.errors??null}:{kind:"network_error",message:ee?.message??`HTTP ${U.status}`}},[t,n,o,y,S,T,_,r,s]),H=u.useMemo(()=>{const L=new Set,I="route|";for(const P of k)if(P.startsWith(I)){const F=P.slice(I.length);F&&L.add(F)}return L},[k]);return{document:a,isLoading:d,error:p,isDirty:y,saveSuccessCounter:m,reloadCounter:v,dirtyKeys:k,dirtyLayoutNames:H,invalidateCurrentCache:z,reload:A,patchLayout:D,setLayoutComponents:M,patchDocumentRaw:B,save:N,markDirty:O}}function o7(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=r7(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 r7(e,t){const n=Ze(t);return n.length===0?null:We({children:e},n)}function so(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 ao(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 $p(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 Ep=44;function Ip(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 y=f.map(h=>h.getBoundingClientRect()),g=new Set(y.map(h=>Math.round(h.top))),m=new Set(y.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 s7(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??Dp(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=a7(s,o,a,l);if(p)return{points:p,flow:s}}return{points:l7(s,a,l),flow:s}},[t,n,o,r])}function a7(e,t,n,o){let r=t.parentElement;for(;r&&Np(r)==="contents";)r=r.parentElement;if(!r)return null;const s=[];if(zp(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 b=v.rect,x=b.top+b.height/2,k=Math.min(a.bottom,b.bottom)-Math.max(a.top,b.top),w=Math.min(a.height,b.height)||1;k/w>.4?d.push({rect:b,path:v.path}):xv.rect.left-b.rect.left),c.sort((v,b)=>v.rect.top-b.rect.top),p.sort((v,b)=>v.rect.top-b.rect.top);const f=d.findIndex(v=>Math.abs(v.rect.left-a.left)<1&&Math.abs(v.rect.top-a.top)<1),y={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],b=Xr(v.path);b&&(m.disabled=!1,m.insertion=b)}else if(d.length>0){const v=d[0],b=Yr(v.path);b&&(m.disabled=!1,m.insertion=b)}if(f>=0&&f0){const v=d[d.length-1],b=Xr(v.path);b&&(h.disabled=!1,h.insertion=b)}if(c.length>0){const v=c[c.length-1],b=Xr(v.path);b&&(y.disabled=!1,y.insertion=b)}else if(s.length>0){const v=s[0],b=Yr(v.path);b&&(y.disabled=!1,y.insertion=b)}if(p.length>0){const v=p[0],b=Yr(v.path);b&&(g.disabled=!1,g.insertion=b)}else if(s.length>0){const v=s[s.length-1],b=Xr(v.path);b&&(g.disabled=!1,g.insertion=b)}else g.disabled=!1,g.insertion={parentPath:n,index:o+1};return y.disabled&&g.disabled&&m.disabled&&h.disabled?null:[y,g,m,h]}function Np(e){return typeof window>"u"?"":(window.getComputedStyle(e).display??"").toLowerCase()}function zp(e,t){const n=Array.from(e.children);for(const o of n){if(Np(o)==="contents"){zp(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:Ze(s)})}}function Yr(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 Xr(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 l7(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 d7(e=50){const t=u.useRef([]),n=u.useRef(-1),[,o]=u.useState(0),r=()=>{o(p=>(p+1)%1e6)},s=(p,f)=>{const y=t.current.length,g=n.current;Gh({op:p,actionKind:f?.actionKind,label:f?.label,stackSize:y,cursor:g,canUndo:g>0,canRedo:g>=0&&g{const y=t.current.slice(0,n.current+1);for(y.push(p);y.length>e;)y.shift();t.current=y,n.current=y.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(c7(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 p7=20,Mp=50,f7=90,Ln=120,g7=130,Lp=80,h7=9e3,Pp=1e4;function y7(e){const t=e<0?0:e>Mp?Mp:e;return p7+t}function b7(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(),[y,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=y===h.index,b=h.danger?"#dc2626":"#0f172a",x=h.danger?"#fee2e2":"#e0e7ff",k=h.danger?"#b91c1c":"#1d4ed8";return i.jsx("button",{type:"button",role:"menuitem","data-testid":h.testid,title:h.hint,onClick:w=>{w.stopPropagation(),h.onSelect(),g(null),o()},onMouseEnter:()=>g(h.index),onFocus:()=>g(h.index),style:{...m7,color:v?k:b,background:v?x:"transparent"},children:h.label},h.testid)})})}const m7={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 v7(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:y,onJumpToDevice:g,onLinkEditDestination:m,onEditBase:h,onEditExtension:v,extensionLabel:b,baseLayoutLabel:x,dataSourceLabel:k,branchLabel:w,onEditIteration:_,resizeEnabledAxes:C,onResizeHandlePointerDown:E,selectedName:S,onSelectParent:T}=e,{t:$}=tt(),[A,z]=u.useState(!1),D=_p(o),O=A&&D,M=Ip(n),B=M==="outside",N=B&&n?Tp(n):null,H=N?{left:N.right.left,top:N.above.top}:{right:-30,top:-30},L={top:-28,left:0},P=B&&!!S?{top:-50,left:0}:L,F=N?{top:N.below.top+28,left:0}:{top:"auto",bottom:-28},G=N?{top:N.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:[w?i.jsxs("span",{"data-testid":"g7le-overlay-branch-badge",style:x7,children:["📱 ",w]}):null,S&&(T?i.jsxs("button",{type:"button","data-testid":"g7le-overlay-type-label","data-placement":B?"outside":"inside",title:$("layout_editor.overlay.select_parent"),"aria-label":$("layout_editor.overlay.select_parent"),onClick:V=>{V.preventDefault(),V.stopPropagation(),T()},style:B?k7:w7,children:[i.jsx("span",{"aria-hidden":!0,style:{marginRight:3,opacity:.85},children:"↑"}),S]}):i.jsx("span",{"data-testid":"g7le-overlay-type-label","data-placement":B?"outside":"inside",style:B?Bp:Op,children:S})),D&&i.jsx("button",{type:"button","data-testid":"g7le-overlay-info-button","aria-label":"info",onClick:V=>{V.stopPropagation(),z(Y=>!Y)},"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(_7,{enabledAxes:C,onHandlePointerDown:E}),o==="base"&&h&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-edit-base",onClick:V=>{V.stopPropagation(),h()},style:{...Po,...L},children:["🔒 ",$("layout_editor.overlay.edit_common_layout"),x?i.jsx("span",{"data-testid":"g7le-overlay-base-layout-label",style:ra,children:x}):null]}),o==="extension"&&v&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-edit-extension",onClick:V=>{V.stopPropagation(),v()},style:{...Po,...L},children:["🔒 ",$("layout_editor.overlay.edit_extension"),b?i.jsx("span",{"data-testid":"g7le-overlay-extension-label",style:ra,children:b}):null]}),o==="data_bound"&&i.jsxs("span",{"data-testid":"g7le-overlay-data-bound-notice",style:{...Po,...P,pointerEvents:"none",cursor:"default"},children:[$("layout_editor.overlay.locked_data_bound"),k?i.jsx("span",{"data-testid":"g7le-overlay-data-source-label",style:ra,children:k}):null]}),o==="data_bound"&&_&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-edit-iteration",onClick:V=>{V.stopPropagation(),_()},style:{...Po,...F},children:["↳ ",$("layout_editor.overlay.edit_iteration_item")]}),r==="route_in_tree"&&i.jsx("button",{type:"button","data-testid":"g7le-overlay-link-edit-destination",onClick:V=>{V.stopPropagation(),m()},style:{...Po,...F},children:$("layout_editor.overlay.edit_destination_route")}),(d||p||g&&(y??[]).length>0)&&i.jsxs("div",{"data-testid":"g7le-overlay-branch-affordances",style:{position:"absolute",...G,display:"flex",flexDirection:"column",alignItems:"flex-start",gap:4,pointerEvents:"none"},children:[g&&(y??[]).map(V=>i.jsxs("button",{type:"button","data-testid":`g7le-overlay-jump-device-${V.key}`,title:$("layout_editor.overlay.jump_device_hint",{device:V.label}),onClick:Y=>{Y.stopPropagation(),g(V.key)},style:oa,children:["↗ ",$("layout_editor.overlay.jump_device",{device:V.label})]},V.key)),d&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-separate-branch",title:$("layout_editor.context_menu.separate_branch_hint"),onClick:V=>{V.stopPropagation(),d()},style:oa,children:["📱 ",c??$("layout_editor.context_menu.separate_branch")]}),p&&i.jsxs("button",{type:"button","data-testid":"g7le-overlay-merge-branch",title:$("layout_editor.context_menu.merge_branch_hint"),onClick:V=>{V.stopPropagation(),p()},style:oa,children:["↩️ ",f??$("layout_editor.context_menu.merge_branch")]})]})]}),i.jsx(b7,{anchor:n&&O?{left:n.left+n.width+8,top:n.top-4}:null,open:O,onClose:()=>z(!1),onEditProps:s,onDuplicate:a,onDelete:l,onSeparateBranch:d,separateBranchLabel:c,onMergeBranch:p,mergeBranchLabel:f})]})}function _7(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 Po={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},oa={background:"#fff",border:"1px solid #2563eb",color:"#2563eb",padding:"2px 6px",fontSize:11,borderRadius:4,cursor:"pointer",pointerEvents:"auto",whiteSpace:"nowrap",zIndex:Ln},ra={marginLeft:6,padding:"0 5px",borderRadius:3,background:"#eef2ff",border:"1px solid #c7d2fe",fontSize:10,fontWeight:600,color:"#3730a3"},x7={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"},Op={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"},Bp={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"},w7={...Op,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},k7={...Bp,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},S7={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 C7(e){const{selectedBox:t,points:n,onAddRequest:o}=e,{t:r}=tt();if(!t||n.length===0)return null;const s=Ip(t),l=s==="outside"?Tp(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}:S7[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 Jr=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function lo(e){const t=Object.prototype.toString.call(e);return t==="[object Window]"||t==="[object global]"}function ia(e){return"nodeType"in e}function _t(e){var t,n;return e?lo(e)?e:ia(e)&&(t=(n=e.ownerDocument)==null?void 0:n.defaultView)!=null?t:window:window}function sa(e){const{Document:t}=_t(e);return e instanceof t}function Oo(e){return lo(e)?!1:e instanceof _t(e).HTMLElement}function Wp(e){return e instanceof _t(e).SVGElement}function co(e){return e?lo(e)?e.document:ia(e)?sa(e)?e:Oo(e)||Wp(e)?e.ownerDocument:document:document:document}const sn=Jr?u.useLayoutEffect:u.useEffect;function Zr(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 Bo(e,t){t===void 0&&(t=[e]);const n=u.useRef(e);return sn(()=>{n.current!==e&&(n.current=e)},t),n}function Wo(e,t){const n=u.useRef();return u.useMemo(()=>{const o=e(n.current);return n.current=o,o},[...t])}function Qr(e){const t=Zr(e),n=u.useRef(null),o=u.useCallback(r=>{r!==n.current&&t?.(r,n.current),n.current=r},[]);return[n,o]}function Rr(e){const t=u.useRef();return u.useEffect(()=>{t.current=e},[e]),t.current}let aa={};function ei(e,t){return u.useMemo(()=>{if(t)return t;const n=aa[e]==null?0:aa[e]+1;return aa[e]=n,e+"-"+n},[e,t])}function jp(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 uo=jp(1),ti=jp(-1);function E7(e){return"clientX"in e&&"clientY"in e}function la(e){if(!e)return!1;const{KeyboardEvent:t}=_t(e.target);return t&&e instanceof t}function I7(e){if(!e)return!1;const{TouchEvent:t}=_t(e.target);return t&&e instanceof t}function ni(e){if(I7(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 E7(e)?{x:e.clientX,y:e.clientY}:null}const jo=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[jo.Translate.toString(e),jo.Scale.toString(e)].join(" ")}},Transition:{toString(e){let{property:t,duration:n,easing:o}=e;return t+" "+n+"ms "+o}}}),Hp="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function A7(e){return e.matches(Hp)?e:e.querySelector(Hp)}const T7={display:"none"};function D7(e){let{id:t,value:n}=e;return u.createElement("div",{id:t,style:T7},n)}function N7(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 z7(){const[e,t]=u.useState("");return{announce:u.useCallback(o=>{o!=null&&t(o)},[]),announcement:e}}const Fp=u.createContext(null);function M7(e){const t=u.useContext(Fp);u.useEffect(()=>{if(!t)throw new Error("useDndMonitor must be used within a children of ");return t(e)},[e,t])}function L7(){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 P7={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. - `},O7={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 B7(e){let{announcements:t=O7,container:n,hiddenTextDescribedById:o,screenReaderInstructions:r=P7}=e;const{announce:s,announcement:a}=z7(),l=ei("DndLiveRegion"),[d,c]=u.useState(!1);if(u.useEffect(()=>{c(!0)},[]),M7(u.useMemo(()=>({onDragStart(f){let{active:y}=f;s(t.onDragStart({active:y}))},onDragMove(f){let{active:y,over:g}=f;t.onDragMove&&s(t.onDragMove({active:y,over:g}))},onDragOver(f){let{active:y,over:g}=f;s(t.onDragOver({active:y,over:g}))},onDragEnd(f){let{active:y,over:g}=f;s(t.onDragEnd({active:y,over:g}))},onDragCancel(f){let{active:y,over:g}=f;s(t.onDragCancel({active:y,over:g}))}}),[s,t])),!d)return null;const p=u.createElement(u.Fragment,null,u.createElement(D7,{id:o,value:r.draggable}),u.createElement(N7,{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 oi(){}function W7(e,t){return u.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function j7(){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 H7(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function F7(e,t){const n=ni(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 K7(e,t){let{data:{value:n}}=e,{data:{value:o}}=t;return n-o}function V7(e,t){let{data:{value:n}}=e,{data:{value:o}}=t;return o-n}function U7(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 q7(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function G7(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=G7(l,t);d>0&&r.push({id:a,data:{droppableContainer:s,value:d}})}}return r.sort(V7)};function X7(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 J7=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&&X7(o,l)){const c=U7(l).reduce((f,y)=>f+H7(o,y),0),p=Number((c/4).toFixed(4));r.push({id:a,data:{droppableContainer:s,value:p}})}}return r.sort(K7)};function Z7(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function Kp(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:Ht}function Q7(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 R7=Q7(1);function Vp(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 e2(e,t,n){const o=Vp(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 t2={ignoreTransform:!1};function Ho(e,t){t===void 0&&(t=t2);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:c,transformOrigin:p}=_t(e).getComputedStyle(e);c&&(n=e2(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 Up(e){return Ho(e,{ignoreTransform:!0})}function n2(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function o2(e,t){return t===void 0&&(t=_t(e).getComputedStyle(e)),t.position==="fixed"}function r2(e,t){t===void 0&&(t=_t(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 da(e,t){const n=[];function o(r){if(t!=null&&n.length>=t||!r)return n;if(sa(r)&&r.scrollingElement!=null&&!n.includes(r.scrollingElement))return n.push(r.scrollingElement),n;if(!Oo(r)||Wp(r)||n.includes(r))return n;const s=_t(e).getComputedStyle(r);return r!==e&&r2(r,s)&&n.push(r),o2(r,s)?n:o(r.parentNode)}return e?o(e):n}function qp(e){const[t]=da(e,1);return t??null}function ca(e){return!Jr||!e?null:lo(e)?e:ia(e)?sa(e)||e===co(e).scrollingElement?window:Oo(e)?e:null:null}function Gp(e){return lo(e)?e.scrollX:e.scrollLeft}function Yp(e){return lo(e)?e.scrollY:e.scrollTop}function ua(e){return{x:Gp(e),y:Yp(e)}}var lt;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(lt||(lt={}));function Xp(e){return!Jr||!e?!1:e===document.scrollingElement}function Jp(e){const t={x:0,y:0},n=Xp(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 i2={x:.2,y:.2};function s2(e,t,n,o,r){let{top:s,left:a,right:l,bottom:d}=n;o===void 0&&(o=10),r===void 0&&(r=i2);const{isTop:c,isBottom:p,isLeft:f,isRight:y}=Jp(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)),!y&&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 a2(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 Zp(e){return e.reduce((t,n)=>uo(t,ua(n)),Ht)}function l2(e){return e.reduce((t,n)=>t+Gp(n),0)}function d2(e){return e.reduce((t,n)=>t+Yp(n),0)}function Qp(e,t){if(t===void 0&&(t=Ho),!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 c2=[["x",["left","right"],l2],["y",["top","bottom"],d2]];class pa{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=da(n),r=Zp(o);this.rect={...t},this.width=t.width,this.height=t.height;for(const[s,a,l]of c2)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 Fo{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 u2(e){const{EventTarget:t}=_t(e);return e instanceof t?e:co(e)}function fa(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 Rp(e){e.preventDefault()}function p2(e){e.stopPropagation()}var Ke;(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"})(Ke||(Ke={}));const ef={start:[Ke.Space,Ke.Enter],cancel:[Ke.Esc],end:[Ke.Space,Ke.Enter,Ke.Tab]},f2=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case Ke.Right:return{...n,x:n.x+25};case Ke.Left:return{...n,x:n.x-25};case Ke.Down:return{...n,y:n.y+25};case Ke.Up:return{...n,y:n.y-25}}};class tf{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 Fo(co(n)),this.windowListeners=new Fo(_t(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&&Qp(o),n(Ht)}handleKeyDown(t){if(la(t)){const{active:n,context:o,options:r}=this.props,{keyboardCodes:s=ef,coordinateGetter:a=f2,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 y=ti(f,p),g={x:0,y:0},{scrollableAncestors:m}=o.current;for(const h of m){const v=t.code,{isTop:b,isRight:x,isLeft:k,isBottom:w,maxScroll:_,minScroll:C}=Jp(h),E=a2(h),S={x:Math.min(v===Ke.Right?E.right-E.width/2:E.right,Math.max(v===Ke.Right?E.left:E.left+E.width/2,f.x)),y:Math.min(v===Ke.Down?E.bottom-E.height/2:E.bottom,Math.max(v===Ke.Down?E.top:E.top+E.height/2,f.y))},T=v===Ke.Right&&!x||v===Ke.Left&&!k,$=v===Ke.Down&&!w||v===Ke.Up&&!b;if(T&&S.x!==f.x){const A=h.scrollLeft+y.x,z=v===Ke.Right&&A<=_.x||v===Ke.Left&&A>=C.x;if(z&&!y.y){h.scrollTo({left:A,behavior:l});return}z?g.x=h.scrollLeft-A:g.x=v===Ke.Right?h.scrollLeft-_.x:h.scrollLeft-C.x,g.x&&h.scrollBy({left:-g.x,behavior:l});break}else if($&&S.y!==f.y){const A=h.scrollTop+y.y,z=v===Ke.Down&&A<=_.y||v===Ke.Up&&A>=C.y;if(z&&!y.x){h.scrollTo({top:A,behavior:l});return}z?g.y=h.scrollTop-A:g.y=v===Ke.Down?h.scrollTop-_.y:h.scrollTop-C.y,g.y&&h.scrollBy({top:-g.y,behavior:l});break}}this.handleMove(t,uo(ti(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()}}tf.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:o=ef,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 nf(e){return!!(e&&"distance"in e)}function of(e){return!!(e&&"delay"in e)}class ga{constructor(t,n,o){var r;o===void 0&&(o=u2(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=co(a),this.documentListeners=new Fo(this.document),this.listeners=new Fo(o),this.windowListeners=new Fo(_t(a)),this.initialCoordinates=(r=ni(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,Rp),this.windowListeners.add(At.VisibilityChange,this.handleCancel),this.windowListeners.add(At.ContextMenu,Rp),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(of(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(nf(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,p2,{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=ni(t))!=null?n:Ht,c=ti(r,d);if(!o&&l){if(nf(l)){if(l.tolerance!=null&&fa(c,l.tolerance))return this.handleCancel();if(fa(c,l.distance))return this.handleStart()}if(of(l)&&fa(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===Ke.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const g2={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class ha extends ga{constructor(t){const{event:n}=t,o=co(n.target);super(t,g2,o)}}ha.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 ya;(function(e){e[e.RightClick=2]="RightClick"})(ya||(ya={}));class y2 extends ga{constructor(t){super(t,h2,co(t.event.target))}}y2.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:o}=t;return n.button===ya.RightClick?!1:(o?.({event:n}),!0)}}];const ba={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class b2 extends ga{constructor(t){super(t,ba)}static setup(){return window.addEventListener(ba.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(ba.move.name,t)};function t(){}}}b2.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 Ko;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(Ko||(Ko={}));var ri;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(ri||(ri={}));function m2(e){let{acceleration:t,activator:n=Ko.Pointer,canScroll:o,draggingRect:r,enabled:s,interval:a=5,order:l=ri.TreeOrder,pointerCoordinates:d,scrollableAncestors:c,scrollableAncestorRects:p,delta:f,threshold:y}=e;const g=_2({delta:f,disabled:!s}),[m,h]=$7(),v=u.useRef({x:0,y:0}),b=u.useRef({x:0,y:0}),x=u.useMemo(()=>{switch(n){case Ko.Pointer:return d?{top:d.y,bottom:d.y,left:d.x,right:d.x}:null;case Ko.DraggableRect:return r}},[n,r,d]),k=u.useRef(null),w=u.useCallback(()=>{const C=k.current;if(!C)return;const E=v.current.x*b.current.x,S=v.current.y*b.current.y;C.scrollBy(E,S)},[]),_=u.useMemo(()=>l===ri.TreeOrder?[...c].reverse():c,[l,c]);u.useEffect(()=>{if(!s||!c.length||!x){h();return}for(const C of _){if(o?.(C)===!1)continue;const E=c.indexOf(C),S=p[E];if(!S)continue;const{direction:T,speed:$}=s2(C,S,x,t,y);for(const A of["x","y"])g[A][T[A]]||($[A]=0,T[A]=0);if($.x>0||$.y>0){h(),k.current=C,m(w,a),v.current=$,b.current=T;return}}v.current={x:0,y:0},b.current={x:0,y:0},h()},[t,w,o,h,s,a,JSON.stringify(x),JSON.stringify(g),m,c,_,p,JSON.stringify(y)])}const v2={x:{[lt.Backward]:!1,[lt.Forward]:!1},y:{[lt.Backward]:!1,[lt.Forward]:!1}};function _2(e){let{delta:t,disabled:n}=e;const o=Rr(t);return Wo(r=>{if(n||!o||!r)return v2;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 x2(e,t){const n=t!=null?e.get(t):void 0,o=n?n.node.current:null;return Wo(r=>{var s;return t==null?null:(s=o??r)!=null?s:null},[o,t])}function w2(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 Vo;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Vo||(Vo={}));var ma;(function(e){e.Optimized="optimized"})(ma||(ma={}));const rf=new Map;function k2(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(),y=Bo(f),g=u.useCallback(function(b){b===void 0&&(b=[]),!y.current&&a(x=>x===null?b:x.concat(b.filter(k=>!x.includes(k))))},[y]),m=u.useRef(null),h=Wo(b=>{if(f&&!n)return rf;if(!b||b===rf||p.current!==e||s!=null){const x=new Map;for(let k of e){if(!k)continue;if(s&&s.length>0&&!s.includes(k.id)&&k.rect.current){x.set(k.id,k.rect.current);continue}const w=k.node.current,_=w?new pa(d(w),w):null;k.rect.current=_,_&&x.set(k.id,_)}return x}return b},[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 Vo.Always:return!1;case Vo.BeforeDragging:return n;default:return!n}}}function va(e,t){return Wo(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function S2(e,t){return va(e,t)}function C2(e){let{callback:t,disabled:n}=e;const o=Zr(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 ii(e){let{callback:t,disabled:n}=e;const o=Zr(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 $2(e){return new pa(Ho(e),e)}function sf(e,t,n){t===void 0&&(t=$2);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=C2({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=ii({callback:s});return sn(()=>{s(),e?(l?.observe(e),a?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),a?.disconnect())},[e]),o}function E2(e){const t=va(e);return Kp(e,t)}const af=[];function I2(e){const t=u.useRef(e),n=Wo(o=>e?o&&o!==af&&e&&t.current&&e.parentNode===t.current.parentNode?o:da(e):af,[e]);return u.useEffect(()=>{t.current=e},[e]),n}function A2(e){const[t,n]=u.useState(null),o=u.useRef(e),r=u.useCallback(s=>{const a=ca(s.target);a&&n(l=>l?(l.set(a,ua(a)),new Map(l)):null)},[]);return u.useEffect(()=>{const s=o.current;if(e!==s){a(s);const l=e.map(d=>{const c=ca(d);return c?(c.addEventListener("scroll",r,{passive:!0}),[c,ua(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=ca(d);c?.removeEventListener("scroll",r)})}},[r,e]),u.useMemo(()=>e.length?t?Array.from(t.values()).reduce((s,a)=>uo(s,a),Ht):Zp(e):Ht,[e,t])}function lf(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?ti(e,n.current):Ht}function T2(e){u.useEffect(()=>{if(!Jr)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 D2(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 df(e){return u.useMemo(()=>e?n2(e):null,[e])}const cf=[];function N2(e,t){t===void 0&&(t=Ho);const[n]=e,o=df(n?_t(n):null),[r,s]=u.useState(cf);function a(){s(()=>e.length?e.map(d=>Xp(d)?o:new pa(t(d),d)):cf)}const l=ii({callback:a});return sn(()=>{l?.disconnect(),a(),e.forEach(d=>l?.observe(d))},[e]),r}function uf(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return Oo(t)?t:e}function z2(e){let{measure:t}=e;const[n,o]=u.useState(null),r=u.useCallback(c=>{for(const{target:p}of c)if(Oo(p)){o(f=>{const y=t(p);return f?{...f,width:y.width,height:y.height}:y});break}},[t]),s=ii({callback:r}),a=u.useCallback(c=>{const p=uf(c);s?.disconnect(),p&&s?.observe(p),o(p?t(p):null)},[t,s]),[l,d]=Qr(a);return u.useMemo(()=>({nodeRef:l,rect:n,setRef:d}),[n,l,d])}const M2=[{sensor:ha,options:{}},{sensor:tf,options:{}}],L2={current:{}},si={draggable:{measure:Up},droppable:{measure:Up,strategy:Vo.WhileDragging,frequency:ma.Optimized},dragOverlay:{measure:Ho}};class Uo 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 P2={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Uo,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:oi},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:si,measureDroppableContainers:oi,windowRect:null,measuringScheduled:!1},pf={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:oi,draggableNodes:new Map,over:null,measureDroppableContainers:oi},qo=u.createContext(pf),ff=u.createContext(P2);function O2(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Uo}}}function B2(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 Uo(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 Uo(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 Uo(e.droppable.containers);return s.delete(n),{...e,droppable:{...e.droppable,containers:s}}}default:return e}}function W2(e){let{disabled:t}=e;const{active:n,activatorEvent:o,draggableNodes:r}=u.useContext(qo),s=Rr(o),a=Rr(n?.id);return u.useEffect(()=>{if(!t&&!o&&s&&a!=null){if(!la(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=A7(p);if(f){f.focus();break}}})}},[o,t,r,a,s]),null}function gf(e,t){let{transform:n,...o}=t;return e!=null&&e.length?e.reduce((r,s)=>s({transform:r,...o}),n):n}function j2(e){return u.useMemo(()=>({draggable:{...si.draggable,...e?.draggable},droppable:{...si.droppable,...e?.droppable},dragOverlay:{...si.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function H2(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=Kp(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 y=qp(c);y&&y.scrollBy({top:f.y,left:f.x})}},[t,a,l,o,n])}const ai=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 F2=u.memo(function(t){var n,o,r,s;let{id:a,accessibility:l,autoScroll:d=!0,children:c,sensors:p=M2,collisionDetection:f=Y7,measuring:y,modifiers:g,...m}=t;const h=u.useReducer(B2,void 0,O2),[v,b]=h,[x,k]=L7(),[w,_]=u.useState(hn.Uninitialized),C=w===hn.Initialized,{draggable:{active:E,nodes:S,translate:T},droppable:{containers:$}}=v,A=E!=null?S.get(E):null,z=u.useRef({initial:null,translated:null}),D=u.useMemo(()=>{var J;return E!=null?{id:E,data:(J=A?.data)!=null?J:L2,rect:z}:null},[E,A]),O=u.useRef(null),[M,B]=u.useState(null),[N,H]=u.useState(null),L=Bo(m,Object.values(m)),I=ei("DndDescribedBy",a),P=u.useMemo(()=>$.getEnabled(),[$]),F=j2(y),{droppableRects:G,measureDroppableContainers:V,measuringScheduled:Y}=k2(P,{dragging:C,dependencies:[T.x,T.y],config:F.droppable}),Z=x2(S,E),se=u.useMemo(()=>N?ni(N):null,[N]),re=ue(),U=S2(Z,F.draggable.measure);H2({activeNode:E!=null?S.get(E):null,config:re.layoutShiftCompensation,initialRect:U,measure:F.draggable.measure});const ee=sf(Z,F.draggable.measure,U),fe=sf(Z?Z.parentElement:null),K=u.useRef({activatorEvent:null,active:null,activeNode:Z,collisionRect:null,collisions:null,droppableRects:G,draggableNodes:S,draggingNode:null,draggingNodeRect:null,droppableContainers:$,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),ne=$.getNodeFor((n=K.current.over)==null?void 0:n.id),me=z2({measure:F.dragOverlay.measure}),Ce=(o=me.nodeRef.current)!=null?o:Z,ze=C?(r=me.rect)!=null?r:ee:null,Se=!!(me.nodeRef.current&&me.rect),qe=E2(Se?null:ee),De=df(Ce?_t(Ce):null),Pe=I2(C?ne??Z:null),Qe=N2(Pe),Me=gf(g,{transform:{x:T.x-qe.x,y:T.y-qe.y,scaleX:1,scaleY:1},activatorEvent:N,active:D,activeNodeRect:ee,containerNodeRect:fe,draggingNodeRect:ze,over:K.current.over,overlayNodeRect:me.rect,scrollableAncestors:Pe,scrollableAncestorRects:Qe,windowRect:De}),Re=se?uo(se,T):null,ve=A2(Pe),te=lf(ve),he=lf(ve,[ee]),Q=uo(Me,te),ie=ze?R7(ze,Me):null,_e=D&&ie?f({active:D,collisionRect:ie,droppableRects:G,droppableContainers:P,pointerCoordinates:Re}):null,ge=q7(_e,"id"),[Ae,Ne]=u.useState(null),Le=Se?Me:uo(Me,he),q=Z7(Le,(s=Ae?.rect)!=null?s:null,ee),ae=u.useRef(null),pe=u.useCallback((J,le)=>{let{sensor:Ie,options:dt}=le;if(O.current==null)return;const pt=S.get(O.current);if(!pt)return;const ot=J.nativeEvent,Oe=new Ie({active:O.current,activeNode:pt,event:ot,options:dt,context:K,onAbort(Ye){if(!S.get(Ye))return;const{onDragAbort:Dt}=L.current,Nt={id:Ye};Dt?.(Nt),x({type:"onDragAbort",event:Nt})},onPending(Ye,Tt,Dt,Nt){if(!S.get(Ye))return;const{onDragPending:wn}=L.current,Zt={id:Ye,constraint:Tt,initialCoordinates:Dt,offset:Nt};wn?.(Zt),x({type:"onDragPending",event:Zt})},onStart(Ye){const Tt=O.current;if(Tt==null)return;const Dt=S.get(Tt);if(!Dt)return;const{onDragStart:Nt}=L.current,xn={activatorEvent:ot,active:{id:Tt,data:Dt.data,rect:z}};Cn.unstable_batchedUpdates(()=>{Nt?.(xn),_(hn.Initializing),b({type:it.DragStart,initialCoordinates:Ye,active:Tt}),x({type:"onDragStart",event:xn}),B(ae.current),H(ot)})},onMove(Ye){b({type:it.DragMove,coordinates:Ye})},onEnd:He(it.DragEnd),onCancel:He(it.DragCancel)});ae.current=Oe;function He(Ye){return async function(){const{active:Dt,collisions:Nt,over:xn,scrollAdjustedTranslate:wn}=K.current;let Zt=null;if(Dt&&wn){const{cancelDrop:Hn}=L.current;Zt={activatorEvent:ot,active:Dt,collisions:Nt,delta:wn,over:xn},Ye===it.DragEnd&&typeof Hn=="function"&&await Promise.resolve(Hn(Zt))&&(Ye=it.DragCancel)}O.current=null,Cn.unstable_batchedUpdates(()=>{b({type:Ye}),_(hn.Uninitialized),Ne(null),B(null),H(null),ae.current=null;const Hn=Ye===it.DragEnd?"onDragEnd":"onDragCancel";if(Zt){const ln=L.current[Hn];ln?.(Zt),x({type:Hn,event:Zt})}})}}},[S]),$e=u.useCallback((J,le)=>(Ie,dt)=>{const pt=Ie.nativeEvent,ot=S.get(dt);if(O.current!==null||!ot||pt.dndKit||pt.defaultPrevented)return;const Oe={active:ot};J(Ie,le.options,Oe)===!0&&(pt.dndKit={capturedBy:le.sensor},O.current=dt,pe(Ie,le))},[S,pe]),be=w2(p,$e);T2(p),sn(()=>{ee&&w===hn.Initializing&&_(hn.Initialized)},[ee,w]),u.useEffect(()=>{const{onDragMove:J}=L.current,{active:le,activatorEvent:Ie,collisions:dt,over:pt}=K.current;if(!le||!Ie)return;const ot={active:le,activatorEvent:Ie,collisions:dt,delta:{x:Q.x,y:Q.y},over:pt};Cn.unstable_batchedUpdates(()=>{J?.(ot),x({type:"onDragMove",event:ot})})},[Q.x,Q.y]),u.useEffect(()=>{const{active:J,activatorEvent:le,collisions:Ie,droppableContainers:dt,scrollAdjustedTranslate:pt}=K.current;if(!J||O.current==null||!le||!pt)return;const{onDragOver:ot}=L.current,Oe=dt.get(ge),He=Oe&&Oe.rect.current?{id:Oe.id,rect:Oe.rect.current,data:Oe.data,disabled:Oe.disabled}:null,Ye={active:J,activatorEvent:le,collisions:Ie,delta:{x:pt.x,y:pt.y},over:He};Cn.unstable_batchedUpdates(()=>{Ne(He),ot?.(Ye),x({type:"onDragOver",event:Ye})})},[ge]),sn(()=>{K.current={activatorEvent:N,active:D,activeNode:Z,collisionRect:ie,collisions:_e,droppableRects:G,draggableNodes:S,draggingNode:Ce,draggingNodeRect:ze,droppableContainers:$,over:Ae,scrollableAncestors:Pe,scrollAdjustedTranslate:Q},z.current={initial:ze,translated:ie}},[D,Z,_e,ie,S,Ce,ze,G,$,Ae,Pe,Q]),m2({...re,delta:T,draggingRect:ie,pointerCoordinates:Re,scrollableAncestors:Pe,scrollableAncestorRects:Qe});const j=u.useMemo(()=>({active:D,activeNode:Z,activeNodeRect:ee,activatorEvent:N,collisions:_e,containerNodeRect:fe,dragOverlay:me,draggableNodes:S,droppableContainers:$,droppableRects:G,over:Ae,measureDroppableContainers:V,scrollableAncestors:Pe,scrollableAncestorRects:Qe,measuringConfiguration:F,measuringScheduled:Y,windowRect:De}),[D,Z,ee,N,_e,fe,me,S,$,G,Ae,V,Pe,Qe,F,Y,De]),oe=u.useMemo(()=>({activatorEvent:N,activators:be,active:D,activeNodeRect:ee,ariaDescribedById:{draggable:I},dispatch:b,draggableNodes:S,over:Ae,measureDroppableContainers:V}),[N,be,D,ee,b,I,S,Ae,V]);return u.createElement(Fp.Provider,{value:k},u.createElement(qo.Provider,{value:oe},u.createElement(ff.Provider,{value:j},u.createElement(ai.Provider,{value:q},c)),u.createElement(W2,{disabled:l?.restoreFocus===!1})),u.createElement(B7,{...l,hiddenTextDescribedById:I}));function ue(){const J=M?.autoScrollEnabled===!1,le=typeof d=="object"?d.enabled===!1:d===!1,Ie=C&&!J&&!le;return typeof d=="object"?{...d,enabled:Ie}:{enabled:Ie}}}),K2=u.createContext(null),hf="button",V2="Draggable";function U2(e){let{id:t,data:n,disabled:o=!1,attributes:r}=e;const s=ei(V2),{activators:a,activatorEvent:l,active:d,activeNodeRect:c,ariaDescribedById:p,draggableNodes:f,over:y}=u.useContext(qo),{role:g=hf,roleDescription:m="draggable",tabIndex:h=0}=r??{},v=d?.id===t,b=u.useContext(v?ai:K2),[x,k]=Qr(),[w,_]=Qr(),C=D2(a,t),E=Bo(n);sn(()=>(f.set(t,{id:t,key:s,node:x,activatorNode:w,data:E}),()=>{const T=f.get(t);T&&T.key===s&&f.delete(t)}),[f,t]);const S=u.useMemo(()=>({role:g,tabIndex:h,"aria-disabled":o,"aria-pressed":v&&g===hf?!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:S,isDragging:v,listeners:o?void 0:C,node:x,over:y,setNodeRef:k,setActivatorNodeRef:_,transform:b}}function q2(){return u.useContext(ff)}const G2="Droppable",Y2={timeout:25};function X2(e){let{data:t,disabled:n=!1,id:o,resizeObserverConfig:r}=e;const s=ei(G2),{active:a,dispatch:l,over:d,measureDroppableContainers:c}=u.useContext(qo),p=u.useRef({disabled:n}),f=u.useRef(!1),y=u.useRef(null),g=u.useRef(null),{disabled:m,updateMeasurementsFor:h,timeout:v}={...Y2,...r},b=Bo(h??o),x=u.useCallback(()=>{if(!f.current){f.current=!0;return}g.current!=null&&clearTimeout(g.current),g.current=setTimeout(()=>{c(Array.isArray(b.current)?b.current:[b.current]),g.current=null},v)},[v]),k=ii({callback:x,disabled:m||!a}),w=u.useCallback((S,T)=>{k&&(T&&(k.unobserve(T),f.current=!1),S&&k.observe(S))},[k]),[_,C]=Qr(w),E=Bo(t);return u.useEffect(()=>{!k||!_.current||(k.disconnect(),f.current=!1,k.observe(_.current))},[_,k]),u.useEffect(()=>(l({type:it.RegisterDroppable,element:{id:o,key:s,disabled:n,node:_,rect:y,data:E}}),()=>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:y,isOver:d?.id===o,node:_,over:d,setNodeRef:C}}function J2(e){let{animation:t,children:n}=e;const[o,r]=u.useState(null),[s,a]=u.useState(null),l=Rr(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 Z2={x:0,y:0,scaleX:1,scaleY:1};function Q2(e){let{children:t}=e;return u.createElement(qo.Provider,{value:pf},u.createElement(ai.Provider,{value:Z2},t))}const R2={position:"fixed",touchAction:"none"},eI=e=>la(e)?"transform 250ms ease":void 0,tI=u.forwardRef((e,t)=>{let{as:n,activatorEvent:o,adjustScale:r,children:s,className:a,rect:l,style:d,transform:c,transition:p=eI}=e;if(!l)return null;const f=r?c:{...c,scaleX:1,scaleY:1},y={...R2,width:l.width,height:l.height,top:l.top,left:l.left,transform:jo.Transform.toString(f),transformOrigin:r&&o?F7(o,l):void 0,transition:typeof p=="function"?p(o):p,...d};return u.createElement(n,{className:a,style:y,ref:t},s)}),nI={duration:250,easing:"ease",keyframes:e=>{let{transform:{initial:t,final:n}}=e;return[{transform:jo.Transform.toString(t)},{transform:jo.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 oI(e){let{config:t,draggableNodes:n,droppableContainers:o,measuringConfiguration:r}=e;return Zr((s,a)=>{if(t===null)return;const l=n.get(s);if(!l)return;const d=l.node.current;if(!d)return;const c=uf(a);if(!c)return;const{transform:p}=_t(a).getComputedStyle(a),f=Vp(p);if(!f)return;const y=typeof t=="function"?t:rI(t);return Qp(d,r.draggable.measure),y({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 rI(e){const{duration:t,easing:n,sideEffects:o,keyframes:r}={...nI,...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},y={x:d.x-p.x,y:d.y-p.y,...f},g=r({...c,active:a,dragOverlay:l,transform:{initial:d,final:y}}),[m]=g,h=g[g.length-1];if(JSON.stringify(m)===JSON.stringify(h))return;const v=o?.({active:a,dragOverlay:l,...c}),b=l.node.animate(g,{duration:t,easing:n,fill:"forwards"});return new Promise(x=>{b.onfinish=()=>{v?.(),x()}})}}let yf=0;function iI(e){return u.useMemo(()=>{if(e!=null)return yf++,yf},[e])}const sI=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:y,containerNodeRect:g,draggableNodes:m,droppableContainers:h,dragOverlay:v,over:b,measuringConfiguration:x,scrollableAncestors:k,scrollableAncestorRects:w,windowRect:_}=q2(),C=u.useContext(ai),E=iI(f?.id),S=gf(a,{activatorEvent:p,active:f,activeNodeRect:y,containerNodeRect:g,draggingNodeRect:v.rect,over:b,overlayNodeRect:v.rect,scrollableAncestors:k,scrollableAncestorRects:w,transform:C,windowRect:_}),T=va(y),$=oI({config:o,draggableNodes:m,droppableContainers:h,measuringConfiguration:x}),A=T?v.setRef:void 0;return u.createElement(Q2,null,u.createElement(J2,{animation:$},f&&E?u.createElement(tI,{key:E,id:f.id,ref:A,as:l,activatorEvent:p,adjustScale:t,className:d,transition:s,rect:T,style:{zIndex:c,...r},transform:S},n):null))});function Go(e,t){return!t||!Array.isArray(t.draggable)?!1:t.draggable.includes(e)}function aI({draggedComponentName:e,targetContainerName:t,nesting:n}){if(!n||!Go(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 bf(e,t){if(!t?.containers)return!1;const n=t.containers[e];return!!(n&&Array.isArray(n.accepts)&&n.accepts.length>0)}function lI(e,t,n,o,r){if(!n||n.length===0)return{parentPath:[],index:r};if(e&&bf(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 mf(e,t){return e===t||e.startsWith(`${t}.`)}function vf(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 dI(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 cI=16;function uI(e){const{frameEl:t,draggedPath:n,acceptsContainer:o,allowsNestSlot:r,includeContainer:s}=e,a=e.normalizeContainerPath??(g=>g),l=t.getBoundingClientRect(),d=dI(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=fI(g.path);m!==null&&f.add(m)}for(const g of d)f.add(g.path);const y=[];for(const g of f){const m=g==="",h=m?null:c.get(g)??g,v=m?t:t.querySelector(`[data-editor-path="${wf(h)}"]`);if(!v&&!m||!m&&mf(g,p))continue;const b=g;if(!m&&s&&!s(b))continue;const x=C=>{const E=c.get(C);if(!E||typeof window>"u")return!1;const S=t.querySelector(`[data-editor-path="${wf(E)}"]`);return S?(window.getComputedStyle(S).display??"").toLowerCase()==="contents":!1},k=d.filter(C=>vf(g,C.path)!==null).filter(C=>!mf(C.path,p)).filter(C=>!x(C.path)).map(C=>({origIndex:vf(g,C.path),rect:pI(C.rect,C.path,d)})).filter(C=>C.rect.width>0||C.rect.height>0).sort((C,E)=>C.origIndex-E.origIndex),w=Dp(m?t:v).kind,_=w==="flex_row_single"||w==="flex_row_wrap"||w==="grid_single_row"||w==="grid_2d";if(k.length>0){if(o(b)){k.forEach(E=>{y.push(_f(b,E.origIndex,E.rect,l,_,"before"))});const C=k[k.length-1];y.push(_f(b,C.origIndex+1,C.rect,l,_,"after"))}}else if(!m&&r(b)&&v){const C=v.getBoundingClientRect();C.width>0&&C.height>0&&y.push({id:`slot:${b}:0`,kind:"nest",containerPath:b,index:0,box:xf(C,l),orientation:"area"})}else m&&y.push({id:"slot::0",kind:"gap",containerPath:"",index:0,box:xf(l,l),orientation:"area"})}return y.filter(g=>ao(g.box,t))}function _f(e,t,n,o,r,s){const a=cI;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 pI(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 xf(e,t){return{left:e.left-t.left,top:e.top-t.top,width:e.width,height:e.height,scale:1}}function fI(e){if(e==="")return null;const t=e.lastIndexOf(".children.");return t<0?"":e.slice(0,t)}function gI(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 wf(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/[^a-zA-Z0-9_\-.]/g,t=>`\\${t}`)}function _a(e){return typeof e=="string"&&e.length>0?e:null}function xa(e,t){return t&&e.startsWith(`${t}.`)?t:e}function kf(e){if(typeof e!="string")return null;const t=gI(e);return t?{containerPath:t.containerPath,index:t.index}:null}function wa(e,t){return t?e.startsWith(`${t}.iteration.`):!1}function ka(e,t,n){return t?n==="iteration_item"?wa(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,y=(o==="iteration_item"||o==="modal")&&s&&s.length>0?at(s):null,[g,m]=u.useState(null),[h,v]=u.useState(null),[b,x]=u.useState(null),k=u.useRef({components:a,nesting:n,editMode:o,currentExtensionId:r,selectedPath:p,editableRootSourcePath:y});k.current={components:a,nesting:n,editMode:o,currentExtensionId:r,selectedPath:p,editableRootSourcePath:y};const w=u.useRef(null),_=u.useCallback(M=>({children:M}),[]),C=u.useCallback((M,B)=>{const N=We(_(M),B);return N?typeof N.name=="string"?N.name:typeof N.type=="string"?N.type:null:null},[_]),E=u.useCallback(M=>B=>{const N=k.current;if(B==="")return Go(M,N.nesting);const H=Ze(B),L=We(_(N.components),H);if(!L)return!1;const I=typeof L.name=="string"?L.name:typeof L.type=="string"?L.type:"";if(!I)return!1;const P=!!N.editableRootSourcePath&&(B===N.editableRootSourcePath||B.startsWith(`${N.editableRootSourcePath}.`));if(N.editableRootSourcePath&&!P)return!1;if(!P){const F=Sa(_(N.components),H);if(gn(L,N.editMode,N.currentExtensionId,F)!=="none")return!1}return bf(I,N.nesting)?aI({draggedComponentName:M,targetContainerName:I,nesting:N.nesting}):!1},[_]),S=u.useCallback(M=>{if(M==="")return!0;const B=k.current,N=Ze(M),H=w.current;if(H&&H.length>0){const P=H.slice(0,-1);if(li(N,P))return!0}const L=We(_(B.components),N);return L?(typeof L.name=="string"?L.name:typeof L.type=="string"?L.type:"").length>0:!1},[_]),T=u.useCallback(M=>{const B=E(M),N=k.current,H=w.current,L=H?H.slice(0,-1):null,I=new Set;if(L)for(let V=L.length;V>=0;V--)I.add(di(L.slice(0,V)));const P=di(H??[]),F=V=>!!H&&(V===P||V.startsWith(`${P}.`)),G=(V,Y)=>{for(let Z=0;ZV===""?!0:F(V)?!1:I.has(V),allowsNestSlot:V=>{if(!B(V))return!1;if(L){const Y=Ze(V);if(li(Y,L))return!1}return S(V)}}},[E,S,_]),$=u.useCallback(M=>{const B=_a(M.active.id),N=k.current;if(!B)return;const H=xa(B,N.selectedPath),L=Ze(H),I=We(_(N.components),L),P=I&&typeof I.name=="string"?I.name:I&&typeof I.type=="string"?I.type:null;m(H),v(P),x(null),w.current=I?L:null;let F="allowed";if(!P||!Go(P,N.nesting))F="denied_no_draggable";else if(I){const G=Sa(_(N.components),L),V=gn(I,N.editMode,N.currentExtensionId,G);N.editableRootSourcePath&&!ka(H,N.editableRootSourcePath,N.editMode)||Xi(G)&&!wa(H,N.editableRootSourcePath)?F="denied_data_bound":V==="base"||V==="partial"?F="denied_base_locked":(V==="extension"||V==="extension_point")&&(F="denied_extension_locked")}$n({source:"drag",draggedComponentName:P,targetContainerName:null,targetContainerPath:null,decision:F,result:F==="allowed"?"completed":"denied",timestamp:Date.now()})},[_]),A=u.useCallback(M=>{if(!t)return;const B=_a(M.active.id);if(!B)return;const N=h;if(!N){x(null);return}const H=k.current,L=xa(B,H.selectedPath),I=Ze(L),P=We(_(H.components),I);if(!P||!Go(N,H.nesting)){x(null);return}const F=Sa(_(H.components),I);if(H.editableRootSourcePath&&!ka(L,H.editableRootSourcePath,H.editMode)){x(null);return}const G=gn(P,H.editMode,H.currentExtensionId,F),V=wa(L,H.editableRootSourcePath);if(Xi(F)&&!V||G!=="none"&&G!=="data_bound"&&!V){x(null);return}x(kf(M.over?.id))},[t,h,_]),z=u.useCallback(()=>{m(null),v(null),x(null),w.current=null},[]),D=u.useCallback(M=>{const B=_a(M.active.id),N=h,H=k.current,L=B?xa(B,H.selectedPath):null;if(!t||!L||!N){z();return}const I=kf(M.over?.id),P=Ze(L);if(!I){$n({source:"drag",draggedComponentName:N,targetContainerName:null,targetContainerPath:null,decision:"denied_no_accepts",result:"cancelled",timestamp:Date.now()}),z();return}const F=I.containerPath===""?[]:Ze(I.containerPath),G=I.containerPath===""?null:C(H.components,F);if(!yI(P.slice(0,-1),F)){$n({source:"drag",draggedComponentName:N,targetContainerName:G,targetContainerPath:I.containerPath||null,decision:"denied_responsive_branch_boundary",result:"denied",timestamp:Date.now()}),f?.(),z();return}if(H.editableRootSourcePath&&!ka(I.containerPath,H.editableRootSourcePath,H.editMode)){$n({source:"drag",draggedComponentName:N,targetContainerName:G,targetContainerPath:I.containerPath||null,decision:"denied_data_bound",result:"denied",timestamp:Date.now()}),z();return}const V=P.slice(0,-1),Y=P[P.length-1]??-1;if(li(V,F)&&(I.index===Y||I.index===Y+1)){$n({source:"drag",draggedComponentName:N,targetContainerName:G,targetContainerPath:I.containerPath||null,decision:"allowed",insertionIndex:I.index,result:"cancelled",timestamp:Date.now()}),z();return}const re=li(V,F),U=I.index;let ee=[];l(me=>{const Se=Db({children:me},P,F,U).children??[];return ee=Se,Se}),d(ee,`move ${N}`);const fe=id(F,P),K=re&&Y{z()},[z]);return{activeDragPath:g,activeDragName:h,activeDropZone:b,onDragStart:$,onDragMove:A,onDragEnd:D,onDragCancel:O,buildSlotPredicates:T}}function Sa(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),b=u.useRef(null),x=u.useCallback(()=>{v(!0),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>v(!1),2600)},[]);u.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const k=hI({frameEl:t,nesting:n,editMode:o,currentExtensionId:r,editableRootPath:s,components:a,patchLayout:l,pushHistory:d,onMovePath:p,selectedPath:y,showBranchBoundaryHint:x}),w=j7(W7(ha,{activationConstraint:{distance:8}})),[_,C]=u.useState([]),E=u.useCallback(()=>{if(!t){C([]);return}if(k.activeDragPath!==null)return;const L={children:a},I=t.querySelectorAll("[data-editor-path]"),P=[],F=new Map;I.forEach(G=>{const V=G.dataset.editorPath;if(typeof V!="string"||o!=="iteration_item"&&g&&!vI(V,g,o))return;const Y=bI(V);if(Y!==null&&!Yo(V,g)){if(/\.iteration\.\d+$/.test(V)){const K=so(G,t);if(K&&ao(K,t)){const ne=F.get(Y)??[];ne.push(K),F.set(Y,ne)}}return}if(Yo(V,g)&&/\.iteration\.\d+$/.test(V))return;const Z=Ze(V),se=We(L,Z);if(!se||se.iteration&&se.iteration.source!==void 0)return;const re=typeof se.name=="string"?se.name:typeof se.type=="string"?se.type:null;if(!re||!Go(re,n))return;const U=Cf(L,Z);if(Xi(U)&&!Yo(V,g))return;const ee=gn(se,o,r,U);if(ee!=="none"&&ee!=="data_bound"&&!Yo(V,g))return;const fe=so(G,t);fe&&ao(fe,t)&&P.push({path:V,name:re,box:fe})});for(const[G,V]of F){const Y=Ze(G),Z=We(L,Y);if(!Z)continue;const se=typeof Z.name=="string"?Z.name:typeof Z.type=="string"?Z.type:null;if(!se)continue;const re=Cf(L,Y),U=gn(Z,o,r,re);if(U!=="none"&&U!=="data_bound")continue;const ee=_I(V);ee&&ao(ee,t)&&P.push({path:G,name:se,box:ee,isIterationGroup:!0})}C(P)},[t,a,n,o,r,g,k.activeDragPath]);u.useEffect(()=>{E()},[E]),u.useEffect(()=>{if(t)return $p(E,t)},[t,E]);const S=k.activeDragPath!==null,T=k.activeDragName,$=k.activeDragPath,[A,z]=u.useState(null),D=u.useRef(null);u.useEffect(()=>{if(!$||!t){$||(D.current=null,z(null));return}if(D.current===$)return;D.current=$;const L=t.querySelector(`[data-editor-path="${Sf($)}"]`);if(L){const re=L.getBoundingClientRect();z({node:L.cloneNode(!0),width:re.width,height:re.height});return}const I=Array.from(t.querySelectorAll(`[data-editor-path^="${Sf($)}.iteration."]`)).filter(re=>/\.iteration\.\d+$/.test(re.dataset.editorPath??""));if(I.length===0){z(null);return}let P=1/0,F=1/0,G=-1/0,V=-1/0;for(const re of I){const U=re.getBoundingClientRect();P=Math.min(P,U.left),F=Math.min(F,U.top),G=Math.max(G,U.right),V=Math.max(V,U.bottom)}const Y=G-P,Z=V-F,se=document.createElement("div");se.style.position="relative",se.style.width=`${Y}px`,se.style.height=`${Z}px`;for(const re of I){const U=re.getBoundingClientRect(),ee=re.cloneNode(!0);ee.style.position="absolute",ee.style.left=`${U.left-P}px`,ee.style.top=`${U.top-F}px`,ee.style.width=`${U.width}px`,ee.style.height=`${U.height}px`,ee.style.margin="0",se.appendChild(ee)}z({node:se,width:Y,height:Z})},[$,t]);const[O,M]=u.useState([]),B=u.useRef(null),N=u.useRef(k.buildSlotPredicates);if(N.current=k.buildSlotPredicates,u.useEffect(()=>{if(!$||!T||!t){B.current=null,M(F=>F.length===0?F:[]);return}if(B.current===$)return;B.current=$;const{acceptsContainer:L,allowsNestSlot:I,includeContainer:P}=N.current(T);M(uI({frameEl:t,draggedPath:$,acceptsContainer:L,allowsNestSlot:I,includeContainer:P,normalizeContainerPath:F=>mI(F)}))},[$,T,t]),!t)return null;const H=k.activeDropZone?`slot:${k.activeDropZone.containerPath}:${k.activeDropZone.index}`:null;return i.jsxs(F2,{sensors:w,collisionDetection:J7,onDragStart:k.onDragStart,onDragMove:k.onDragMove,onDragEnd:k.onDragEnd,onDragCancel:k.onDragCancel,children:[_.map(L=>i.jsx(SI,{path:L.path,name:L.name,box:L.box,dimmed:S&&k.activeDragPath!==L.path,isIterationGroup:L.isIterationGroup,onSelect:c,onRequestInlineEdit:f},L.path)),S&&O.map(L=>i.jsx(kI,{slot:L,active:L.id===H},L.id)),Cn.createPortal(i.jsx(sI,{dropAnimation:null,zIndex:Pp,children:T?A?i.jsx(wI,{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:Pp},children:["⚠️ ",m("layout_editor.overlay.branch_boundary_denied")]}),t)]})}function wI(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 kI(e){const{slot:t,active:n}=e,{setNodeRef:o}=X2({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 Sf(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/[^a-zA-Z0-9_\-.]/g,t=>`\\${t}`)}function SI(e){const{path:t,box:n,dimmed:o,isIterationGroup:r,onSelect:s,onRequestInlineEdit:a}=e,{attributes:l,listeners:d,setNodeRef:c,isDragging:p}=U2({id:t}),f=(t.match(/\.children\./g)||[]).length,y=y7(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 b=h.closest?.("[data-editor-path]")?.dataset?.editorPath;if(typeof b=="string"&&(b===t||b.startsWith(`${t}.`))){s(b);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:y,touchAction:"none"}})}function Cf(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(!Ji(d,t,n)){r.push(p);return}const y=Array.isArray(d.children)?d.children:[];y.length>0&&s(y,p)})};return s(e,[]),r}function $I(e){return at(e)}function ci(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}function EI({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 x=CI(t,n,o,r);if(x.length===0){a(null);return}const k=e.getBoundingClientRect(),w={left:0,top:0,width:k.width,height:k.height},_=[];for(const C of x){const E=$I(C),S=e.querySelector(`[data-editor-path="${ci(E)}"]`);let T=null;if(S){const $=S.getBoundingClientRect();$.width>0&&$.height>0&&(T={left:$.left,top:$.top,width:$.width,height:$.height})}if(!T){const $=Array.from(e.querySelectorAll(`[data-editor-path^="${ci(E)}.iteration."], [data-editor-path^="${ci(E)}.sortable."], [data-editor-path^="${ci(E)}.children."]`));let A=1/0,z=1/0,D=-1/0,O=-1/0;for(const M of $){const B=M.getBoundingClientRect();B.width<=0||B.height<=0||(A=Math.min(A,B.left),z=Math.min(z,B.top),D=Math.max(D,B.right),O=Math.max(O,B.bottom))}if(D>A&&O>z&&(T={left:A,top:z,width:D-A,height:O-z}),T&&$.length>0){const M=$[0].closest('[role="dialog"]');if(M&&e.contains(M)){const B=M.getBoundingClientRect();B.width>0&&B.height>0&&(T={left:B.left,top:B.top,width:B.width,height:B.height})}}}T&&_.push({left:T.left-k.left,top:T.top-k.top,width:T.width,height:T.height})}if(_.length===0){a(null);return}a({frame:w,holes:_})},h=()=>{g&&cancelAnimationFrame(g),g=requestAnimationFrame(m)};h();const v=typeof ResizeObserver<"u"?new ResizeObserver(h):null;v?.observe(e);const b=typeof MutationObserver<"u"?new MutationObserver(h):null;return b?.observe(e,{childList:!0,subtree:!0,attributes:!0}),window.addEventListener("scroll",h,!0),window.addEventListener("resize",h),()=>{g&&cancelAnimationFrame(g),v?.disconnect(),b?.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 C of c)g=Math.min(g,C.left),m=Math.min(m,C.top),h=Math.max(h,C.left+C.width),v=Math.max(v,C.top+C.height);const b=(C,E,S)=>Math.max(E,Math.min(S,C)),x=b(g,0,d.width),k=b(m,0,d.height),w=b(h,0,d.width),_=b(v,0,d.height);f=[{left:0,top:0,width:d.width,height:k},{left:0,top:_,width:d.width,height:d.height-_},{left:0,top:k,width:x,height:_-k},{left:w,top:k,width:d.width-w,height:_-k}].filter(C=>C.width>0&&C.height>0)}const y=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:y,onPointerDownCapture:y,onMouseDownCapture:y,onDragStartCapture:y,style:{position:"absolute",left:g.left,top:g.top,width:g.width,height:g.height,zIndex:Lp,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:Lp,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 $f(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 II(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 AI(e,t,n,o,r){const s=II(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 TI(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 y of p.components??[]){const g=a.get(y);g&&(f.push(g),l.add(y))}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 Ef(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:y}=tt(),g=u.useMemo(()=>{if(!c||!y)return f;const A=p??null;return z=>{const D={templateId:c,locale:A??"ko"},O=y.translate(z,D);return O!==z?O:f(z)}},[c,p,y,f]),[m,h]=u.useState(""),[v,b]=u.useState("all"),x=o?.entries??null,k=u.useMemo(()=>A=>{const z=x?.[A.name];return z?.label?ui(z.label,g):A.description??A.name},[x,g]),w=u.useMemo(()=>AI(t,n,s,m,k),[t,n,s,m,k]),_=u.useMemo(()=>TI(w,o??null),[w,o]),C=_.find(A=>A.key===v)??_[0]??null,E=!n||!n.draggable&&!n.containers,S=w.length===0,T=C?.entries??[],$=A=>{const z=x?.[A.name],D=!!z?.defaultNode&&typeof z.defaultNode=="object";if(z?.requiresDefaultNode&&!D)return;const O=D?JSON.parse(JSON.stringify(z.defaultNode)):$f(A),M=r??[];a(O,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:MI,children:[i.jsxs("div",{style:LI,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:PI,children:"×"})]}),i.jsxs("div",{style:OI,children:[i.jsx("aside",{style:BI,"data-testid":"g7le-palette-sidebar",children:i.jsx("nav",{children:i.jsx("ul",{style:WI,children:_.map(A=>{const z=C?.key===A.key,D=A.isI18nKey?ui(A.label,g):A.label;return i.jsx("li",{children:i.jsxs("button",{type:"button","data-testid":`g7le-palette-category-${A.key}`,"data-active":z?"true":"false",onClick:()=>b(A.key),style:{...jI,background:z?"#eff6ff":"transparent",color:z?"#1d4ed8":"#334155",fontWeight:z?600:500},children:[i.jsx("span",{children:D}),i.jsx("span",{style:VI,children:A.entries.length})]})},A.key)})})})}),i.jsxs("main",{style:HI,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:FI}),i.jsx("div",{style:KI,children:E?i.jsx("div",{style:If,"data-testid":"g7le-palette-spec-missing",children:f("layout_editor.palette.spec_missing")}):S||T.length===0?i.jsx("div",{style:If,"data-testid":"g7le-palette-empty",children:f("layout_editor.palette.empty")}):i.jsx("div",{"data-testid":`g7le-palette-group-${C?.key??"all"}`,style:{marginBottom:16},children:i.jsx("div",{style:UI,children:T.map(A=>i.jsx(DI,{entry:A,entrySpec:x?.[A.name]??null,onClick:$,t:f,entryT:g},A.name))})})})]})]})]})}function DI(e){const{entry:t,entrySpec:n,onClick:o,t:r,entryT:s}=e,a=n?.label?ui(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,y=p?r("layout_editor.palette.requires_default_node_missing"):n?.label?ui(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:y,style:p?GI:qI,children:[i.jsx("div",{style:XI,"aria-hidden":"true",children:zI(t)}),i.jsx("div",{style:JI,children:a}),i.jsx("div",{"data-testid":`g7le-palette-item-${t.name}-tag`,style:ZI,children:`<${t.name}>`}),d&&i.jsx("div",{"data-testid":`g7le-palette-item-${t.name}-badge`,style:NI(l),children:l}),f&&i.jsx("div",{"data-testid":`g7le-palette-item-${t.name}-default-missing-badge`,style:YI,children:r("layout_editor.palette.default_node_missing_badge")})]})}function ui(e,t){return e.startsWith("$t:")?t(e.slice(3)):t(e)}function NI(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 zI(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 MI={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'},LI={display:"flex",justifyContent:"space-between",alignItems:"center",padding:"14px 20px",borderBottom:"1px solid #e2e8f0",flexShrink:0},PI={background:"transparent",border:"none",fontSize:24,cursor:"pointer",lineHeight:1,color:"#64748b",padding:"0 4px"},OI={display:"flex",flex:1,minHeight:0},BI={width:180,flexShrink:0,borderRight:"1px solid #e2e8f0",padding:"14px 8px",background:"#f8fafc",overflowY:"auto"},WI={listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:4},jI={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"},HI={flex:1,display:"flex",flexDirection:"column",minHeight:0,padding:"14px 20px"},FI={width:"100%",padding:"8px 10px",border:"1px solid #cbd5e1",borderRadius:6,marginBottom:12,fontSize:13,flexShrink:0,boxSizing:"border-box"},KI={flex:1,overflowY:"auto",minHeight:0},VI={fontSize:11,color:"#94a3b8",marginLeft:8,fontWeight:500},UI={display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(96px, 1fr))",gap:10},qI={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"},GI={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},YI={fontSize:9,fontWeight:600,color:"#92400e",background:"#fef3c7",padding:"1px 6px",borderRadius:999,textTransform:"none",letterSpacing:0,lineHeight:1.6},XI={fontSize:22,lineHeight:1,color:"#475569"},JI={fontSize:12,fontWeight:500,color:"#0f172a",textAlign:"center",wordBreak:"break-word"},ZI={fontFamily:'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace',fontSize:10,color:"#64748b",textAlign:"center",wordBreak:"break-all"},If={padding:24,color:"#64748b",fontSize:13,textAlign:"center"};function QI(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 Af(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 QI(o))n(a)};if(Array.isArray(e))for(const o of e)o&&typeof o=="object"&&n(o);return t}const RI=["scroll","selector","wizard","slider"];function eA(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 RI)n.add(`${o}-${r}`)}return Array.from(n)}function tA(e,t,n){const o=t.label;return typeof o=="string"?o.startsWith("$t:")?n(o.slice(3)):o:e}function pi({controlKey:e,control:t,node:n,t:o,onPatch:r,candidates:s,bindingCandidates:a,scope:l=Wt}){const d=Tn(t.widget),c=tA(e,t,o),p=u.useMemo(()=>Do(n,t,l),[n,t,l]),f=t.widget==="i18n-text"&&t.apply?.type==="propValue",y=t.widget==="text"&&t.apply?.type==="propValue",g=p.darkReadonly===!0||l.colorScheme==="dark"&&t.apply!==void 0&&!Us(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,b=u.useCallback(x=>{if(g)return;const k=fn(n,t,x,l);r(k)},[n,t,r,l,g]);return i.jsxs("div",{className:"g7le-control-row","data-testid":`g7le-control-${e}`,style:nA,children:[i.jsxs("span",{className:"g7le-control-label",style:oA,children:[c,p.conflict&&i.jsx("span",{"data-testid":`g7le-control-conflict-${e}`,title:o("layout_editor.property_modal.value_conflict"),style:rA,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(vt,{value:typeof p.value=="string"?p.value:"",onChange:x=>b(x),t:o,testidPrefix:`g7le-prop-i18n-${e}`,candidates:a,enableExpressionTree:!0,expressionTreeCollapsible:!0}):y?i.jsx(Ve,{value:typeof p.value=="string"?p.value:"",onChange:x=>b(x===""?void 0:x),t:o,testidPrefix:`g7le-prop-value-${e}`,candidates:a}):g?i.jsx("span",{"data-testid":`g7le-control-dark-readonly-${e}`,style:sA,children:o("layout_editor.property_modal.dark_code_only")}):d?i.jsx(d,{control:t,value:p.value,onChange:b,t:o,candidates:s,bindingCandidates:a,freeValueDisabled:h}):i.jsx("span",{"data-testid":`g7le-control-unsupported-${e}`,style:iA,children:o("layout_editor.property_modal.unsupported_widget")})})]})}const nA={display:"flex",alignItems:"center",gap:12,padding:"6px 0",minHeight:32,minWidth:0},oA={fontSize:12,color:"#475569",minWidth:88,display:"inline-flex",alignItems:"center",gap:4},rA={display:"inline-flex",width:14,height:14,borderRadius:7,background:"#f59e0b",color:"#fff",fontSize:10,alignItems:"center",justifyContent:"center",fontWeight:700},iA={fontSize:11,color:"#94a3b8",fontStyle:"italic"},sA={fontSize:11,color:"#94a3b8",fontStyle:"italic"};function fi(e,t,n){return typeof e=="string"?e.startsWith("$t:")?n(e.slice(3)):e:t}function aA(e,t){const n=e.props??{};return t.key in n?n[t.key]:t.default}function lA({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:cA,children:r.map((s,a)=>i.jsxs("div",{className:"g7le-settings-group",style:uA,children:[i.jsx("div",{style:pA,children:fi(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:fA,children:[i.jsx("span",{style:gA,children:fi(l.label,l.key,n)}),i.jsx("div",{style:{flex:1},children:dA(l,t,n,o)})]},l.key))]},a))})}function dA(e,t,n,o){const r=aA(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:Ca});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:Ca});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:yA,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)}}),fi(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:Ca,children:[i.jsx("option",{value:"",children:"—"}),(e.options??[]).map(s=>i.jsx("option",{value:String(s.value),children:fi(s.label,String(s.value),n)},String(s.value)))]})}}const cA={display:"flex",flexDirection:"column",gap:16},uA={display:"flex",flexDirection:"column",gap:6},pA={fontSize:12,fontWeight:700,color:"#0f172a",borderBottom:"1px solid #e2e8f0",paddingBottom:4},fA={display:"flex",alignItems:"center",gap:12,minHeight:30},gA={fontSize:12,color:"#475569",minWidth:96},Ca={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",boxSizing:"border-box"},hA={display:"flex",flexWrap:"wrap",gap:10},yA={display:"inline-flex",alignItems:"center",gap:4,fontSize:12,color:"#0f172a"},bA=["data_binding","isolatedScopeId","parentFormContextProp","skipBindingKeys","isolatedState","component_layout","sortable","itemTemplate"],mA=/\{\{|\$switch|\$get|\|\s*(date|number|truncate|currency|relative)\b/;function gi(e,t=0){return t>6?!1:typeof e=="string"?mA.test(e):Array.isArray(e)?e.some(n=>gi(n,t+1)):e&&typeof e=="object"?Object.values(e).some(n=>gi(n,t+1)):!1}function vA(e){if(Zl(e))return!1;const t=Fl(e);return t.length===0?!1:t.some(n=>n.isComplex)}function Tf(e){const t=[],n=e.props??{};for(const o of bA)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"?vA(e.text)&&t.push({key:"text",kind:"complex_expression"}):gi(e.text)&&t.push({key:"text",kind:"complex_expression"});for(const[o,r]of Object.entries(n))o==="style"||o==="className"||gi(r)&&t.push({key:`props.${o}`,kind:"complex_expression"});return t}function _A(e){return Tf(e).length>0}const xA=new Set(["permissions","blur_until_loaded","comment"]);function wA({node:e,advanced:t,t:n,onPatch:o,permissionCandidates:r}){const s=u.useMemo(()=>Tf(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:kA,children:[t.map(l=>{if(!xA.has(l))return i.jsxs("div",{"data-testid":`g7le-advanced-deferred-${l}`,style:CA,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:$a,children:[i.jsx("div",{style:Ea,children:n("layout_editor.property_modal.advanced.permissions")}),i.jsx(ys,{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:$a,children:[i.jsx("div",{style:Ea,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:$a,children:[i.jsx("div",{style:Ea,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:SA})]},l)}),s.length>0&&i.jsxs("div",{className:"g7le-advanced-preserved","data-testid":"g7le-advanced-preserved",style:$A,children:[i.jsx("div",{style:EA,children:n("layout_editor.property_modal.advanced_preserved_title",{count:s.length})}),i.jsx("ul",{style:IA,children:s.map(l=>i.jsxs("li",{"data-testid":`g7le-advanced-preserved-${l.key}`,style:AA,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 kA={display:"flex",flexDirection:"column",gap:14},$a={display:"flex",flexDirection:"column",gap:6},Ea={fontSize:12,fontWeight:700,color:"#0f172a"},SA={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",boxSizing:"border-box"},CA={fontSize:11,color:"#94a3b8",fontStyle:"italic"},$A={borderTop:"1px dashed #cbd5e1",paddingTop:10,marginTop:4},EA={fontSize:11,color:"#b45309",marginBottom:6},IA={listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:4},AA={display:"flex",justifyContent:"space-between",gap:8,padding:"3px 0"},TA={onClick:"click",onHover:"mouseenter",onChange:"change",onSubmit:"submit",onMount:"mount",onUnmount:"unmount",onFocus:"focus",onBlur:"blur"};function Ia(e){return TA[e]??e.replace(/^on/,"").toLowerCase()}function Df(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=Ia(s);for(const d of a)d&&typeof d=="object"&&r.push("type"in d?d:{type:l,...d})}return r}return[]}function DA(e,t){const n=Ia(t);return Df(e).filter(o=>o.type===n||t==="onClick"&&o.type===void 0)}function NA(e,t,n){const o=Ia(t),r=Df(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 zA({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:Nf,children:o("layout_editor.action.no_events")}):!c||Object.keys(c).length===0?i.jsx("div",{"data-testid":"g7le-action-no-recipes",style:Nf,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(y=>i.jsxs("div",{className:"g7le-action-event-slot","data-testid":`g7le-action-event-${y}`,children:[i.jsx("div",{style:MA,children:o(`layout_editor.action.event.${y}`)}),i.jsx(Gt,{actions:DA(e,y),onChange:g=>r(NA(e,y,g)),t:o,recipes:c,candidatePools:p,actionChipCandidates:t?.actionChipCandidates??null,addContext:"component",showSourceBadge:!0,testIdPrefix:`g7le-action-slot-${y}`})]},y))})}const Nf={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},MA={fontSize:12,fontWeight:700,color:"#475569",marginBottom:6};function Aa(e,t,n){if(!t)return n;const o=e(t);return!o||o===t||o.startsWith("$t:")?n:o}function LA(e,t){return Aa(t,e.labelKey,e.path||e.sourceId)}function PA({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),[y,g]=u.useState(""),m=Aa(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(()=>Fi(n,t.shape).map(_=>({..._,resolvedLabel:LA(_,o)})),[n,t.shape,o]),b=u.useMemo(()=>Ki(v,y),[v,y]),x=w=>{const _={...e.props??{}};w===void 0?delete _[t.propKey]:_[t.propKey]=w,r({...e,props:_})},k=w=>{x(En(w.sourceId,w.path,t.shape)),f(!1),g("")};return i.jsxs("div",{"data-testid":`g7le-binding-row-${t.propKey}`,style:jA,children:[i.jsxs("div",{style:HA,children:[i.jsx("span",{style:{fontWeight:600,fontSize:12},children:m}),i.jsx("span",{style:FA,children:h}),t.required&&i.jsx("span",{"data-testid":`g7le-binding-required-${t.propKey}`,style:KA,children:o("layout_editor.binding.required")})]}),c?i.jsxs("div",{"data-testid":`g7le-binding-complex-${t.propKey}`,style:GA,children:[o("layout_editor.binding.complex"),i.jsx("code",{style:zf,children:l})]}):d?i.jsxs("div",{style:VA,children:[i.jsx("code",{"data-testid":`g7le-binding-expr-${t.propKey}`,style:zf,children:l}),i.jsx("button",{type:"button","data-testid":`g7le-binding-clear-${t.propKey}`,onClick:()=>x(void 0),style:qA,children:o("layout_editor.binding.clear")})]}):i.jsx("div",{"data-testid":`g7le-binding-empty-${t.propKey}`,style:UA,children:o("layout_editor.binding.not_connected")}),d&&(t.shape==="array"||t.shape==="object")&&t.itemFields&&t.itemFields.length>0&&i.jsxs("div",{style:YA,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(w=>!w),style:XA,children:["🔍 ",o("layout_editor.binding.search")]}),p&&i.jsxs("div",{"data-testid":`g7le-binding-picker-${t.propKey}`,style:JA,children:[i.jsx("input",{type:"text",autoFocus:!0,"data-testid":`g7le-binding-search-input-${t.propKey}`,value:y,placeholder:o("layout_editor.binding.search_placeholder"),onChange:w=>g(w.target.value),style:ZA}),i.jsx("div",{style:QA,children:b.length===0?i.jsx("div",{style:RA,children:o("layout_editor.binding.no_results")}):b.map(w=>i.jsxs("button",{type:"button","data-testid":`g7le-binding-candidate-${w.expression}`,onClick:()=>k(w),style:e6,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:t6,children:[Aa(o,w.groupLabelKey,w.sourceId)," · ",w.path||w.sourceId]})]}),i.jsx("span",{style:n6,children:w.preview})]},w.expression))})]})]})]})}function OA({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:BA,children:[i.jsxs("div",{style:WA,children:["🔗 ",o("layout_editor.binding.section_title")]}),t.map(s=>i.jsx(PA,{node:e,spec:s,candidates:n,t:o,onPatchNode:r},s.propKey)),i.jsx("div",{style:o6})]})}const BA={display:"flex",flexDirection:"column",marginBottom:8},WA={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:6},jA={display:"flex",flexDirection:"column",gap:4,padding:"8px 0"},HA={display:"flex",alignItems:"center",gap:6},FA={fontSize:10,padding:"1px 6px",borderRadius:4,background:"#e0e7ff",color:"#3730a3"},KA={fontSize:10,padding:"1px 6px",borderRadius:4,background:"#fef3c7",color:"#92400e"},VA={display:"flex",alignItems:"center",gap:6},UA={fontSize:11,color:"#94a3b8"},zf={fontSize:11,fontFamily:"monospace",background:"#f1f5f9",padding:"2px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all"},qA={fontSize:11,border:"1px solid #e2e8f0",borderRadius:4,background:"#fff",color:"#dc2626",padding:"2px 8px",cursor:"pointer"},GA={display:"flex",flexDirection:"column",gap:2,fontSize:11,color:"#64748b"},YA={fontSize:10,color:"#94a3b8"},XA={fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#334155",padding:"4px 10px",cursor:"pointer",textAlign:"left",width:"100%"},JA={marginTop:4,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",padding:6},ZA={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},QA={marginTop:4,maxHeight:200,overflowY:"auto",display:"flex",flexDirection:"column",gap:2},RA={fontSize:11,color:"#94a3b8",padding:"8px 0",textAlign:"center"},e6={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,border:"none",background:"transparent",cursor:"pointer",padding:"6px 8px",borderRadius:4,textAlign:"left"},t6={fontSize:10,color:"#94a3b8"},n6={fontSize:10,color:"#64748b",fontFamily:"monospace",whiteSpace:"nowrap"},o6={borderTop:"1px solid #e2e8f0",marginTop:4};function r6({node:e,candidates:t,t:n,onPatchNode:o,templateIdentifier:r}){const s=typeof e.text=="string"?e.text:"",{state:a}=Je(),l=r??a.templateIdentifier,d=a.selectedRoute?.layoutName??null,c=a.locale,[p,f]=u.useState(!1),y=/^\s*\$t:custom\.[A-Za-z0-9._-]+\s*$/.test(s),m=Zl(s)&&(mt(s)?.key.startsWith("custom.")??!1)||y,h=u.useMemo(()=>m?mt(s):null,[m,s]),v=u.useMemo(()=>m?[]:Fl(s),[m,s]),b=T=>{o({...e,text:T})},x=()=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:l,locale:c}}))}catch{}},k=(T,$)=>{const A=En($.sourceId,$.path,"scalar");b(wb(s,T,A))},w=T=>{const $=mt(s);b(mo(s,T));const A=$?.key;l&&A&&Fd(l,A,T).then(x)},_=T=>{const $=n(T);return $&&$!==T&&!$.startsWith("$t:")?$:""},C=T=>T.replace(/\$t:[a-zA-Z0-9._-]+/g,$=>_($.slice(3))).replace(/\s+/g," ").trim(),E=T=>{p||(f(!0),ls(l,d,c,s,s.length,T.sourceId,T.path,"scalar",C,$=>n($)).then($=>{$.kind==="ok"&&(b($.text),x())}).finally(()=>f(!1)))},S=T=>{p||!h&&!y||(f(!0),wr(l,c,s,Number.MAX_SAFE_INTEGER,T.sourceId,T.path,"scalar").then($=>{$.kind==="ok"&&(b($.text),x())}).finally(()=>f(!1)))};if(m){const T=h?.params??[];return i.jsxs("div",{"data-testid":"g7le-inline-binding-section",style:Mf,children:[i.jsxs("div",{style:Lf,children:["🔗 ",n("layout_editor.inline_binding.section_title")]}),T.length===0?i.jsx("div",{"data-testid":"g7le-inline-binding-none",style:Bf,children:n("layout_editor.inline_binding.none")}):T.map($=>i.jsx("div",{"data-testid":`g7le-inline-binding-param-${$.name}`,style:Pf,children:$.parsed===null?i.jsxs("div",{"data-testid":`g7le-inline-binding-param-complex-${$.name}`,style:s6,children:[n("layout_editor.inline_binding.complex"),i.jsx("code",{style:Ta,children:$.expression})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:Of,children:[i.jsx("code",{"data-testid":`g7le-inline-binding-param-expr-${$.name}`,style:Ta,children:$.expression}),i.jsx("button",{type:"button","data-testid":`g7le-inline-binding-param-clear-${$.name}`,onClick:()=>w($.name),style:i6,children:n("layout_editor.inline_binding.clear")})]}),i.jsx($t,{candidates:t,t:n,onSelect:A=>k($.name,A),testIdSuffix:`param-${$.name}`})]})},$.name)),i.jsxs("div",{"data-testid":"g7le-inline-binding-param-append",style:Wf,children:[i.jsx("div",{style:Da,children:n("layout_editor.inline_binding.append_hint")}),i.jsx($t,{candidates:t,t:n,onSelect:S,testIdSuffix:"param-append"})]}),i.jsx("div",{"data-testid":"g7le-inline-binding-param-hint",style:Da,children:n("layout_editor.inline_binding.param_hint")}),i.jsx("div",{style:jf})]})}return i.jsxs("div",{"data-testid":"g7le-inline-binding-section",style:Mf,children:[i.jsxs("div",{style:Lf,children:["🔗 ",n("layout_editor.inline_binding.section_title")]}),v.length===0?i.jsx("div",{"data-testid":"g7le-inline-binding-none",style:Bf,children:n("layout_editor.inline_binding.none")}):v.map(T=>i.jsx("div",{"data-testid":`g7le-inline-binding-row-${T.bindingIndex}`,style:Pf,children:i.jsx("div",{style:Of,children:i.jsx("code",{"data-testid":`g7le-inline-binding-expr-${T.bindingIndex}`,style:Ta,children:T.expression})})},T.bindingIndex)),i.jsxs("div",{"data-testid":"g7le-inline-binding-append",style:Wf,children:[i.jsx("div",{style:Da,children:n("layout_editor.inline_binding.append_hint")}),i.jsx($t,{candidates:t,t:n,onSelect:E,testIdSuffix:"append"})]}),i.jsx("div",{style:jf})]})}const Mf={display:"flex",flexDirection:"column",marginBottom:8},Lf={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:6},Pf={display:"flex",flexDirection:"column",gap:4,padding:"8px 0"},Of={display:"flex",alignItems:"center",gap:6},Bf={fontSize:11,color:"#94a3b8"},Ta={fontSize:11,fontFamily:"monospace",background:"#f1f5f9",padding:"2px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all"},i6={fontSize:11,border:"1px solid #e2e8f0",borderRadius:4,background:"#fff",color:"#dc2626",padding:"2px 8px",cursor:"pointer"},s6={display:"flex",flexDirection:"column",gap:2,fontSize:11,color:"#64748b"},Wf={display:"flex",flexDirection:"column",gap:2,padding:"8px 0 0"},Da={fontSize:11,color:"#475569",fontWeight:600},jf={borderTop:"1px solid #e2e8f0",marginTop:4};function Hf(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 Hf(t,e.labelKey,e.path||e.sourceId)}function l6(e){const t=e.iteration;return t&&typeof t=="object"?t:null}function d6({node:e,candidates:t,t:n,onPatchNode:o}){const r=l6(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,y]=u.useState(""),g=u.useMemo(()=>Fi(t,"array").map(w=>({...w,resolvedLabel:a6(w,n)})),[t,n]),m=u.useMemo(()=>Ki(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,b=k=>{const w={...r};k===void 0?delete w.source:w.source=k,o({...e,iteration:w})},x=k=>{b(En(k.sourceId,k.path,"array")),p(!1),y("")};return i.jsxs("div",{"data-testid":"g7le-iteration-binding-section",style:c6,children:[i.jsxs("div",{style:u6,children:["🔁 ",n("layout_editor.binding.iteration_title")]}),i.jsx("div",{style:p6,children:n("layout_editor.binding.iteration_hint")}),i.jsxs("div",{style:f6,children:[i.jsxs("div",{style:g6,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:v6,children:[n("layout_editor.binding.complex"),i.jsx("code",{style:Ff,children:a})]}):l?i.jsxs("div",{style:y6,children:[i.jsx("code",{"data-testid":"g7le-iteration-binding-expr",style:Ff,children:a}),i.jsx("button",{type:"button","data-testid":"g7le-iteration-binding-clear",onClick:()=>b(void 0),style:m6,children:n("layout_editor.binding.clear")})]}):i.jsx("div",{"data-testid":"g7le-iteration-binding-empty",style:b6,children:n("layout_editor.binding.not_connected")}),(h||v)&&i.jsxs("div",{"data-testid":"g7le-iteration-vars",style:_6,children:[h&&i.jsxs("span",{children:[n("layout_editor.binding.iteration_item_var"),": ",i.jsx("code",{style:Kf,children:h})]}),v&&i.jsxs("span",{children:[n("layout_editor.binding.iteration_index_var"),": ",i.jsx("code",{style:Kf,children:v})]})]}),!d&&i.jsxs("div",{style:{marginTop:4},children:[i.jsxs("button",{type:"button","data-testid":"g7le-iteration-binding-search-toggle",onClick:()=>p(k=>!k),style:x6,children:["🔍 ",n("layout_editor.binding.search")]}),c&&i.jsxs("div",{"data-testid":"g7le-iteration-binding-picker",style:w6,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:k=>y(k.target.value),style:k6}),i.jsx("div",{style:S6,children:m.length===0?i.jsx("div",{style:C6,children:n("layout_editor.binding.no_results")}):m.map(k=>i.jsxs("button",{type:"button","data-testid":`g7le-iteration-binding-candidate-${k.expression}`,onClick:()=>x(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:[Hf(n,k.groupLabelKey,k.sourceId)," · ",k.path||k.sourceId]})]}),i.jsx("span",{style:I6,children:k.preview})]},k.expression))})]})]})]}),i.jsx("div",{style:A6})]})}const c6={display:"flex",flexDirection:"column",marginBottom:8},u6={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:4},p6={fontSize:10,color:"#94a3b8",marginBottom:6,lineHeight:1.4},f6={display:"flex",flexDirection:"column",gap:4,padding:"8px 0"},g6={display:"flex",alignItems:"center",gap:6},h6={fontSize:10,padding:"1px 6px",borderRadius:4,background:"#e0e7ff",color:"#3730a3"},y6={display:"flex",alignItems:"center",gap:6},b6={fontSize:11,color:"#94a3b8"},Ff={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={display:"flex",gap:12,fontSize:10,color:"#94a3b8",marginTop:2},Kf={fontSize:10,fontFamily:"monospace",background:"#f1f5f9",padding:"1px 4px",borderRadius:3,color:"#475569"},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},T6=new Set(["Span","P","H1","H2","H3","H4","H5","H6","A","Button","Li","Label"]);function D6(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 T6.has(o)?!0:typeof e.text=="string"}const yn={direction:"flexDirection",justify:"flexJustify",align:"flexAlign",wrap:"flexWrap",gap:"flexGap",enable:"flexEnable"},hi={grow:"flexItemGrow",selfAlign:"flexItemAlign",order:"flexItemOrder"};function Vf(e){const t=e?.flexEditor;return t==="container"||t==="item"||t==="auto"?t:null}function N6(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 z6(e,t,n=Wt){if(!e||!t)return!1;const o=Do(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 M6(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:N6(t))?{showContainer:!0,showEnableButton:!1,showDisableButton:o}:{showContainer:!1,showEnableButton:!0,showDisableButton:!1}}return{showContainer:!1,showEnableButton:!1,showDisableButton:!1}}const L6={[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"},P6={[hi.grow]:"layout_editor.flex.item_grow",[hi.selfAlign]:"layout_editor.flex.item_align",[hi.order]:"layout_editor.flex.item_order"};function O6({node:e,spec:t,capability:n,t:o,onPatchNode:r,liveElement:s,scope:a=Wt}){const l=Vf(n),d=Ct(t,yn.enable),c=z6(e,d,a),{showContainer:p,showEnableButton:f,showDisableButton:y}=M6(l,s,c,!!d,a),g=Object.values(yn).filter(_=>_!==yn.enable&&Ct(t,_)),m=Object.values(hi).filter(_=>Ct(t,_)),h=d?.options,v=d?.onValue??h?.[0]?.value??!0,b=Array.isArray(h)&&h.length>=2?h[1].value:void 0,x=()=>{if(!d)return;const _=fn(e,d,v,a);r(_)},k=()=>{if(!d)return;const _=a.breakpoint!=="base"&&b!==void 0?b:void 0,C=fn(e,d,_,a);r(C)},w=(_,C,E)=>i.jsx("div",{"data-testid":E,style:{display:"flex",flexDirection:"column"},children:_.map(S=>{const T=Ct(t,S);if(!T)return null;const $=T.label?T:{...T,label:`$t:${C[S]}`};return i.jsx(pi,{controlKey:S,control:$,node:e,t:o,onPatch:r,scope:a},S)})});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:x,style:B6,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:Uf,children:o("layout_editor.flex.container_title")}),w(g,L6,"g7le-flex-container-controls"),y&&i.jsx("button",{type:"button","data-testid":"g7le-flex-disable",onClick:k,style:W6,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:Uf,children:o("layout_editor.flex.item_title")}),w(m,P6,"g7le-flex-item-controls")]}),!p&&!f&&l!=="item"&&i.jsx("div",{"data-testid":"g7le-flex-empty",style:j6,children:o("layout_editor.flex.not_flex")})]})}const Uf={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:6},B6={padding:"8px 12px",fontSize:12,border:"1px dashed #2563eb",borderRadius:6,background:"#eff6ff",color:"#2563eb",cursor:"pointer"},W6={marginTop:8,padding:"6px 10px",fontSize:12,border:"1px solid #e2e8f0",borderRadius:6,background:"#f8fafc",color:"#64748b",cursor:"pointer"},j6={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},qf=["desktop","tablet","mobile","portable"],Na=1280,H6=820,F6=390,K6=1920,V6=320;function U6(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 q6(e){const t=[...qf],n=new Set(qf);for(const o of U6(e))!n.has(o)&&!t.includes(o)&&t.push(o);return t}function G6(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 Y6(e){switch(e){case"desktop":return Na;case"tablet":return H6;case"mobile":return F6}const t=e in To?To[e]:Mn.parseRange(e);return!t||!Number.isFinite(t.max)?Na:Math.round(Math.max(V6,Math.min(K6,t.max)))}function Gf(){const t=Ft()?.document?.raw?.components;return u.useMemo(()=>q6(t??null),[t])}const X6={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"},J6=[{key:"base",labelKey:"layout_editor.property_modal.scope.scheme_light"},{key:"dark",labelKey:"layout_editor.property_modal.scope.scheme_dark"}];function Yf({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(""),[y,g]=u.useState(null),m=Gf(),h=u.useMemo(()=>{const k=["base",...m],w=new Set(k);for(const _ of Object.keys(n.responsive??{}))_!=="base"&&!w.has(_)&&(w.add(_),k.push(_));return e.breakpoint!=="base"&&!w.has(e.breakpoint)&&k.push(e.breakpoint),k},[m,n.responsive,e.breakpoint]),v=k=>t({...e,colorScheme:k}),b=k=>t({...e,breakpoint:k}),x=()=>{const k=d.trim(),w=p.trim();if(k===""&&w===""){g(o("layout_editor.property_modal.scope.custom_invalid"));return}const _=`${k}-${w}`;if(!gC(_)){g(o("layout_editor.property_modal.scope.custom_invalid"));return}g(null),l(!1),c(""),f(""),b(_)};return i.jsxs("div",{className:"g7le-style-scope-tabs","data-testid":"g7le-style-scope-tabs",style:Z6,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:Xf,children:J6.map(k=>{const w=e.colorScheme===k.key;return i.jsxs("button",{type:"button",role:"tab","aria-selected":w,"data-testid":`g7le-style-scheme-${k.key}`,"data-active":w?"true":"false",onClick:()=>v(k.key),style:Jf(w),children:[o(k.labelKey),k.key==="dark"&&Gs(n,{colorScheme:"dark",breakpoint:e.breakpoint})&&i.jsx("span",{"data-testid":"g7le-style-scheme-dark-dot",style:Zf})]},k.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:Xf,children:[h.map(k=>{const w=e.breakpoint===k,_=k==="base"||wu(k),C=k==="base"?"layout_editor.property_modal.scope.device_base":X6[k],E=C?o(C):k,S=_?`g7le-style-bp-${k}`:`g7le-style-bp-custom-${k}`;return i.jsxs("button",{type:"button",role:"tab","aria-selected":w,"data-testid":S,"data-active":w?"true":"false",onClick:()=>b(k),style:Jf(w),children:[E,Gs(n,{colorScheme:"base",breakpoint:k})&&i.jsx("span",{"data-testid":`${S}-dot`,style:Zf})]},String(k))}),i.jsxs("button",{type:"button","data-testid":"g7le-style-bp-add-custom",onClick:()=>l(k=>!k),style:eT,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:Q6,children:[i.jsx("input",{type:"number","data-testid":"g7le-style-custom-min",placeholder:o("layout_editor.property_modal.scope.custom_min"),value:d,onChange:k=>c(k.target.value),style:Qf}),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:k=>f(k.target.value),style:Qf}),i.jsx("button",{type:"button","data-testid":"g7le-style-custom-confirm",onClick:x,style:tT,children:o("layout_editor.property_modal.scope.add_custom")})]}),y&&i.jsx("div",{"data-testid":"g7le-style-custom-error",style:nT,children:y}),e.breakpoint!=="base"&&!wu(e.breakpoint)&&i.jsx("div",{"data-testid":"g7le-style-custom-priority-note",style:oT,children:o("layout_editor.property_modal.scope.custom_priority_note")}),s&&Gs(n,e)&&i.jsxs("button",{type:"button","data-testid":"g7le-style-scope-reset",onClick:s,style:R6,children:["↺ ",o("layout_editor.property_modal.scope.reset_to_base")]})]})}const Z6={display:"flex",flexDirection:"column",gap:0,padding:"0 0 8px",borderBottom:"1px solid #e2e8f0",marginBottom:8},Q6={display:"flex",gap:6,alignItems:"center",marginTop:4},Xf={display:"flex",gap:2,flexWrap:"wrap",borderBottom:"1px solid #e2e8f0",margin:"0 -16px",padding:"0 12px"};function Jf(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 Zf={display:"inline-block",width:5,height:5,borderRadius:3,background:"#f59e0b"},R6={alignSelf:"flex-start",marginTop:2,padding:"3px 8px",fontSize:10,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},eT={padding:"6px 12px",fontSize:11,border:"none",borderBottom:"2px dashed #cbd5e1",background:"transparent",color:"#475569",cursor:"pointer",marginBottom:-1},Qf={width:70,padding:"4px 6px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6},tT={padding:"4px 10px",fontSize:11,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"},nT={fontSize:11,color:"#dc2626"},oT={fontSize:10,color:"#94a3b8"},Rf=new Map;function Pn(e,t){Rf.set(e,t)}function rT(e){return e?Rf.get(e)??null:null}const za={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"}}},iT=["id"];function sT(e){return e===!1?[]:Array.isArray(e)?e.filter(t=>t in za):[...iT]}function eg(e){const t=e.props?.id??e.id;return typeof t=="string"&&t.length>0?`${t}-scope`:"scope"}function aT({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=eg(e)),t(h)},f=h=>{const v={...e};v.isolatedScopeId=h.trim()===""?eg(e):h,t(v)},y=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:lT,children:[i.jsx("div",{style:dT,children:n("layout_editor.core_props.isolatedState.label")}),i.jsxs("div",{style:cT,children:[i.jsx("button",{type:"button","data-testid":"g7le-isolated-toggle",role:"switch","aria-checked":a,onClick:p,style:uT(a),children:n(a?"layout_editor.overlay.on":"layout_editor.overlay.off")}),a?null:i.jsx("span",{"data-testid":"g7le-isolated-off-hint",style:pT,children:n("layout_editor.core_props.isolatedState.off_hint")})]}),a?i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:tg,children:[i.jsx("label",{style:ng,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:fT}),g.length>0?i.jsxs("div",{"data-testid":"g7le-isolated-scopeid-picker",style:gT,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:yT,children:g.map(h=>i.jsx("button",{type:"button","data-testid":`g7le-isolated-scopeid-candidate-${h}`,onClick:()=>{f(h),c("")},style:bT,children:h},h))})]}):null,m?i.jsxs("p",{"data-testid":"g7le-isolated-scopeid-dup",style:mT,children:["ⓘ ",n("layout_editor.core_props.isolatedScopeId.duplicate")]}):null]}),i.jsxs("div",{style:tg,children:[i.jsx("label",{style:ng,children:n("layout_editor.core_props.isolatedState.initial_label")}),i.jsx("div",{"data-testid":"g7le-isolated-initial-value",children:i.jsx(Nn,{value:s.isolatedState??{},onChange:y,t:n,path:"isolatedState",scope:"isolated-node"})})]})]}):null]})}const lT={display:"flex",flexDirection:"column",gap:8,padding:10,border:"1px solid #e2e8f0",borderRadius:8,minWidth:0},dT={fontSize:12,fontWeight:700,color:"#0f172a"},cT={display:"flex",gap:8,alignItems:"center"},uT=e=>({padding:"4px 12px",fontSize:11,border:`1px solid ${e?"#3b82f6":"#cbd5e1"}`,borderRadius:14,background:e?"#eff6ff":"#fff",color:e?"#1d4ed8":"#64748b",cursor:"pointer"}),pT={fontSize:11,color:"#94a3b8"},tg={display:"flex",flexDirection:"column",gap:4,minWidth:0},ng={fontSize:11,color:"#64748b"},fT={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box",width:"100%"},gT={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"},yT={display:"flex",flexDirection:"column",maxHeight:120,overflowY:"auto"},bT={textAlign:"left",padding:"4px 6px",fontSize:12,border:"none",background:"transparent",cursor:"pointer",borderRadius:4,color:"#0f172a"},mT={margin:0,fontSize:11,color:"#64748b"},vT={borderTop:"2px solid #c7d2fe",background:"#eef2ff",padding:"10px 12px",display:"flex",flexDirection:"column",gap:8},og={fontSize:13,fontWeight:700,color:"#3730a3",display:"flex",alignItems:"center",gap:6},_T={fontSize:11,fontWeight:600,color:"#4338ca",background:"#e0e7ff",border:"1px solid #c7d2fe",borderRadius:4,padding:"1px 6px"},Ma={fontSize:11,color:"#6366f1"},xT={alignSelf:"flex-start",fontSize:12,fontWeight:600,color:"#fff",background:"#4f46e5",border:"none",borderRadius:4,padding:"4px 10px",cursor:"pointer"},wT={opacity:.5,cursor:"not-allowed"},kT={fontSize:11,color:"#dc2626"};function ST({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,y]=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),y(!1);try{await n(o),y(!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:og,children:i.jsx("span",{style:_T,"data-testid":"g7le-injected-props-origin-badge",children:t("layout_editor.property_modal.injected_props.origin",{source:g})})}),i.jsx(Bs,{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??{}),y(!1)},onValidityChange:h=>{a(h),h&&d(null),y(!1)}}),l&&i.jsx("div",{style:kT,"data-testid":"g7le-injected-props-error",children:l}),f&&i.jsx("div",{style:{...Ma,color:"#16a34a"},"data-testid":"g7le-injected-props-saved",children:t("layout_editor.property_modal.injected_props.saved")}),i.jsx("div",{style:Ma,children:t("layout_editor.property_modal.injected_props.save_target")}),i.jsx("button",{type:"button","data-testid":"g7le-injected-props-save",style:{...xT,...c||!s?wT: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 CT({injectedProps:e,t,onSaveInjectedProps:n}){return!Array.isArray(e)||e.length===0?null:i.jsxs("div",{style:vT,"data-testid":"g7le-injected-props-section",children:[i.jsxs("div",{style:og,children:["🧩 ",t("layout_editor.property_modal.injected_props.title")]}),i.jsx("div",{style:Ma,children:t("layout_editor.property_modal.injected_props.help")}),e.map(o=>i.jsx(ST,{entry:o,t,onSave:r=>n(o.extensionId,r)},o.extensionId))]})}function $T(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 ET({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:y,scope:g=Wt,onScopeChange:m,templateIdentifier:h,initialTab:v,onSaveInjectedProps:b,branchLabel:x,isolatedScopeIdCandidates:k,usedScopeIds:w}){const _=e.__injectedProps,C=Array.isArray(_)&&_.length>0&&!!b,E=ve=>{m?.(ve)},S=()=>{r(xC(e,g))},T=typeof e.name=="string"?e.name:"",$=Oi(t,T),z=$T(n,T)?.settings,D=!!(z?.groups&&z.groups.length>0),O=Array.isArray($?.propControls)?$.propControls:[],M=sT($?.coreProps),B=new Set(M.map(ve=>za[ve].apply?.propKey)),N=O.filter(ve=>{const he=Ct(t,ve)?.apply?.propKey;return!(he!==void 0&&B.has(he))}),H=typeof $?.nodeEditor?.kind=="string"?$.nodeEditor.kind:void 0,L=$?.nodeEditor?.params,I=H?rT(H):null,P=!!I,F=Array.isArray($?.dataProps)?$.dataProps:[],G=F.length>0,V=!!(e.iteration&&typeof e.iteration=="object"),Y=D6(e,$),Z=M.length>0||N.length>0||P||G||Y||V,se=Array.isArray($?.styleControls)?$.styleControls:[],re=Array.isArray($?.advanced)?$.advanced:[],ee=(Array.isArray($?.events)?$.events:[]).length>0,fe=Vf($),K=se.length>0||fe!==null,me=!($?.visibilityCondition===!1)&&(Z||K||ee||D||re.length>0),Ce=u.useMemo(()=>{const ve=[];return D&&ve.push("settings"),Z&&ve.push("props"),K&&ve.push("style"),ee&&ve.push("action"),me&&ve.push("visibility"),ve.push("translation"),re.length>0&&ve.push("advanced"),ve},[D,Z,K,ee,me,re.length]),ze=N.length>0||P||G||V,[Se,qe]=u.useState(v&&Ce.includes(v)?v:D?"settings":ze?"props":K?"style":Z?"props":Ce[0]??"style"),De=_A(e),Pe=!Z&&!K&&!D&&!ee&&!me&&re.length===0,Qe=$?.label?$.label.startsWith("$t:")?o($.label.slice(3)):$.label:T||o("layout_editor.property_modal.element"),Me=(ve,te)=>{const he={...e.props??{}};te===void 0?delete he[ve]:he[ve]=te,r({...e,props:he})},Re={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:IT,children:[i.jsxs("div",{"data-modal-drag-handle":!0,"data-testid":"g7le-property-modal-header",style:AT,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:Qe}):o("layout_editor.property_modal.title",{name:Qe})}),i.jsx("button",{type:"button","data-testid":"g7le-property-modal-close","aria-label":"close",onClick:s,style:TT,children:"✕"})]}),De&&i.jsx("div",{"data-testid":"g7le-property-modal-advanced-badge",style:DT,children:o("layout_editor.property_modal.advanced_badge")}),x&&i.jsx("div",{"data-testid":"g7le-property-modal-branch-badge",style:NT,children:o("layout_editor.property_modal.branch_badge",{device:x})}),i.jsx("div",{style:zT,role:"tablist",children:Ce.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:()=>qe(ve),style:{...MT,color:Se===ve?"#2563eb":"#64748b",borderBottomColor:Se===ve?"#2563eb":"transparent"},children:Re[ve]},ve))}),i.jsxs("div",{style:LT,"data-testid":"g7le-property-modal-body",children:[Pe&&!C&&i.jsx("div",{"data-testid":"g7le-property-modal-no-editable",style:ig,children:o("layout_editor.property_modal.no_editable_props")}),C&&i.jsx(CT,{injectedProps:_,t:o,onSaveInjectedProps:b}),Se==="settings"&&z&&i.jsx(lA,{spec:z,node:e,t:o,onPatchProp:Me}),Se==="props"&&i.jsxs("div",{"data-testid":"g7le-property-props-tab",style:{display:"flex",flexDirection:"column"},children:[V&&i.jsx(d6,{node:e,candidates:f??[],t:o,onPatchNode:r}),G&&i.jsx(OA,{node:e,dataProps:F,candidates:f??[],t:o,onPatchNode:r}),Y&&i.jsx(r6,{node:e,candidates:f??[],t:o,onPatchNode:r,templateIdentifier:h}),P&&I&&i.jsx(I,{node:e,params:L,spec:t,manifest:n,t:o,onPatchNode:r,templateIdentifier:h,candidates:f}),M.map(ve=>i.jsx(pi,{controlKey:`core-${ve}`,control:za[ve],node:e,t:o,onPatch:r,scope:Wt,bindingCandidates:f},`core-${ve}`)),N.map(ve=>{const te=Ct(t,ve);return te?i.jsx(pi,{controlKey:ve,control:te,node:e,t:o,onPatch:r,scope:Wt,bindingCandidates:f},ve):null}),i.jsx(aT,{node:e,onPatchNode:r,t:o,scopeIdCandidates:k,usedScopeIds:w})]}),Se==="style"&&i.jsxs("div",{"data-testid":"g7le-property-style-tab",style:{display:"flex",flexDirection:"column"},children:[i.jsx("div",{style:rg,children:i.jsx(Yf,{scope:g,onChange:E,node:e,t:o,onClearScope:S})}),fe!==null&&i.jsx(O6,{node:e,spec:t,capability:$,t:o,onPatchNode:r,liveElement:y,scope:g}),se.map(ve=>{const te=Ct(t,ve);return te?i.jsx(pi,{controlKey:ve,control:te,node:e,t:o,onPatch:r,scope:g},ve):null})]}),Se==="action"&&i.jsx(zA,{node:e,spec:t,capability:$,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:rg,children:i.jsx(Yf,{scope:g,onChange:E,node:e,t:o,showColorScheme:!1})}),i.jsx(Eu,{node:e,spec:t,t:o,onPatchNode:r,dataSourceCandidates:c,stateKeyCandidates:p,scope:g})]}),Se==="translation"&&(h?i.jsx(Ud,{customKey:Vd(e),templateIdentifier:h,t:o,paramLabels:hv(e),onRemoveParam:ve=>{const te=typeof e.text=="string"?e.text:"";r({...e,text:mo(te,ve)});const he=Vd(e);h&&he&&kr(h,he,ve)}}):i.jsx("div",{"data-testid":"g7le-property-translation-deferred",style:ig,children:o("layout_editor.translation.not_a_key")})),Se==="advanced"&&i.jsx(wA,{node:e,advanced:re,t:o,onPatch:r,permissionCandidates:l})]}),i.jsxs("div",{style:PT,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:OT,children:o("layout_editor.property_modal.delete_element")}),i.jsx("button",{type:"button","data-testid":"g7le-property-modal-done",onClick:s,style:BT,children:o("layout_editor.property_modal.close")})]})]})]})}const IT={display:"flex",flexDirection:"column",width:420,maxWidth:"92vw"},AT={display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #e2e8f0",cursor:"move",userSelect:"none"},TT={border:"none",background:"transparent",fontSize:14,cursor:"pointer",color:"#64748b"},DT={margin:"8px 16px 0",padding:"6px 10px",fontSize:11,background:"#fef3c7",color:"#92400e",borderRadius:6},NT={margin:"8px 16px 0",padding:"6px 10px",fontSize:11,background:"#dbeafe",color:"#1e40af",borderRadius:6},zT={display:"flex",gap:2,padding:"0 12px",borderBottom:"1px solid #e2e8f0",overflowX:"auto"},MT={padding:"8px 10px",fontSize:12,border:"none",borderBottom:"2px solid transparent",background:"transparent",cursor:"pointer",whiteSpace:"nowrap"},LT={padding:16,overflowY:"auto",maxHeight:"60vh"},rg={position:"sticky",top:-16,zIndex:2,background:"#fff",margin:"-16px -16px 0",padding:"6px 16px 0"},ig={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},PT={display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderTop:"1px solid #e2e8f0"},OT={padding:"6px 12px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},BT={padding:"6px 12px",fontSize:12,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"},La="g7le:component-target-picked",Pa="g7le:component-target-pick-request";let WT=1;function jT({value:e,onChange:t,t:n,control:o}){const r=yo(),s=e==null?"":String(e),a=o?.allowManualInput!==!1,l=u.useCallback(()=>{if(typeof window>"u")return;const d=`pick-${WT++}`,p=r.stack[r.stack.length-1]?.id;p&&r.minimize(p,n("layout_editor.target_picker.minimized_hint"));const f=y=>{const g=y.detail;g?.requestId===d&&(window.removeEventListener(La,f),p&&r.restore(p),!g.cancelled&&typeof g.id=="string"&&t(g.id))};window.addEventListener(La,f),window.dispatchEvent(new CustomEvent(Pa,{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 HT(e,t,n,o,r=fetch){const s=`/api/admin/templates/${encodeURIComponent(e)}/layout-extensions/${t}`;let a;try{a=await r(s,{headers:je(),credentials:"same-origin"})}catch(b){return{kind:"error",message:b instanceof Error?b.message:String(b)}}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,y=Array.isArray(c.injections)?[...c.injections]:[],g=y.findIndex(b=>b&&b.position==="inject_props"&&b.target_id===n);if(g<0)return{kind:"injection_not_found"};y[g]={...y[g],props:o};const m={...c,injections:y};let h;try{h=await r(s,{method:"PUT",headers:je({"Content-Type":"application/json"}),credentials:"same-origin",body:JSON.stringify({content:m,expected_lock_version:f})})}catch(b){return{kind:"error",message:b instanceof Error?b.message:String(b)}}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 sg=new Map;function Oa(e,t){sg.set(e,t)}function FT(e){return e?sg.get(e)??null:null}const ag="g7le.clipboard";function lg(){try{return typeof window>"u"||!window.sessionStorage?null:window.sessionStorage}catch{return null}}function KT(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 dg(e,t=0){const n=lg();if(!n)return!1;try{const o={node:KT(e),copiedAt:t};return n.setItem(ag,JSON.stringify(o)),!0}catch{return!1}}function VT(){const e=lg();if(!e)return null;try{const t=e.getItem(ag);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 Xo={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 Ba(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 UT(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=Ba(l)??d*40,p=Math.abs(c-t);p{if(!t)return;const m=Xo[y];if(m.width!==0&&!n||m.height!==0&&!o)return;const h=t.props?.style??{},v=s?.()??null,b=Ba(h.width)??(v?Math.round(v.width):0),x=Ba(h.height)??(v?Math.round(v.height):0);p.current={handle:y,startX:g.clientX,startY:g.clientY,startW:b,startH:x,node:t};const k=m.width!==0&&m.height!==0?"both":m.width!==0?"width":"height";d?.(k);let w=null;const _=E=>{const S=p.current;if(!S)return;const T=r||1,$=(E.clientX-S.startX)/T*Xo[S.handle].width,A=(E.clientY-S.startY)/T*Xo[S.handle].height;let z=S.node;if(Xo[S.handle].width!==0&&n){const D=cg(n,S.startW+$);z=fn(z,n,D)}if(Xo[S.handle].height!==0&&o){const D=cg(o,S.startH+A);z=fn(z,o,D)}w=z,a(z,k)},C=()=>{p.current=null,d?.(null),window.removeEventListener("pointermove",_),window.removeEventListener("pointerup",C),w&&l?.(w,k)};window.addEventListener("pointermove",_),window.addEventListener("pointerup",C)},[t,n,o,r,a,l,d]);return{enabledAxes:c,onHandlePointerDown:f}}const ug=320,pg=1920,YT=1024;function Wa(e){return Number.isFinite(e)?Math.round(Math.max(ug,Math.min(pg,e))):YT}function ja(e={}){const{state:t,dispatch:n}=Je(),{previewDevice:o,previewZoom:r,previewCustomWidth:s,previewColorScheme:a}=t,l=o==="custom"?Wa(s):Y6(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:Wa(g)})},[n]),y=u.useCallback(g=>{n({type:"SET_PREVIEW_COLOR_SCHEME",scheme:g})},[n]);return{device:o,deviceWidth:l,zoom:r,scale:d,customWidth:Wa(s),setDevice:c,setZoom:p,setCustomWidth:f,colorScheme:a,setColorScheme:y}}const yi="g7le-dnd-handle-";function XT(e){if(typeof e!="string"||!e.startsWith(yi))return null;const t=e.slice(yi.length);return t.length>0?t:null}function JT(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\\]]/g,"\\$&")}function ZT(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(yi))return null;if(r){const l=e.closest(`[data-testid^="${yi}"]`);if(l&&t){const d=XT(l.getAttribute("data-testid"));if(d){const c=t.querySelector(`[data-editor-path="${JT(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 QT(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 RT="#ffffff",e4="#0f172a";function t4(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 n4(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=t4(e);if(!n)return!1;const[o,r,s]=n;return .299*o+.587*r+.114*s>=180}function o4(e,t,n){const o=typeof n?.color=="string"?n.color:null;return n4(e??o??t)?e4:RT}function r4({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),[y,g]=u.useState(t.trim().length>0),[m,h]=u.useState(null);u.useEffect(()=>{const w=p.current;if(w){w.textContent=t,w.focus();try{const _=window.document.createRange();_.selectNodeContents(w);const C=window.getSelection();C?.removeAllRanges(),C?.addRange(_)}catch{}f.current=!1}},[t]),u.useEffect(()=>{const w=p.current;if(!w||typeof window.getComputedStyle!="function"){h(null);return}try{h(window.getComputedStyle(w).color||null)}catch{h(null)}},[a,l]);const v=()=>(p.current?.textContent??"").trim(),b=()=>{f.current||(f.current=!0,r(v()))},x=()=>{f.current||(f.current=!0,s())},k=w=>{w.key==="Enter"&&!w.shiftKey?(w.preventDefault(),b()):w.key==="Escape"&&(w.preventDefault(),x())};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:k,onBlur:b,style:{outline:"2px solid #2563eb",outlineOffset:1,borderRadius:3,background:o4(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??{},...QT(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:w=>w.preventDefault(),onClick:w=>{w.preventDefault(),w.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")]})}),!y&&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 i4({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:y,onCancel:g}){const[m,h]=u.useState(null),v=u.useRef(""),[b,x]=u.useState(!1),k=u.useRef(!1),w=u.useRef(null),_=Ft(),C=u.useRef(()=>{}),[E,S]=u.useState(null),[T,$]=u.useState(!1),A=u.useRef(n??null);u.useEffect(()=>{n&&A.current!==n&&(A.current=n)},[n]);const z=u.useMemo(()=>{if(!n&&r)return r;const L={},I=mt(typeof t.text=="string"?t.text:"");for(const P of I?.params??[])L[P.name]=Vt(P.expression);return L},[t.text,n,r]);u.useEffect(()=>{let L=!1;if(!n){const I=o??"";return v.current=I,h(I),()=>{L=!0}}return(async()=>{const I=It(n,l);if(I!==void 0){v.current=I,h(I);return}const P=await cn(a,n);if(L)return;const F=P?.values?.[l]??"";v.current=F,h(F)})(),()=>{L=!0}},[a,n,l,o]);const D=async()=>{if(k.current)return;k.current=!0;const L=m??"";if(L===v.current){y();return}x(!0);let I=A.current;if(!I){if(!s){x(!1),k.current=!1;return}if(I=await s(L),x(!1),!I){k.current=!1;return}A.current=I,y();return}const P=await ko(a,I,l,L);if(x(!1),P.kind==="error"){k.current=!1;return}_?.markDirty?.(),y()},O=()=>{k.current||(k.current=!0,g())},M=L=>{S(L)},B=async L=>{if(!(E===null||!p||T)){$(!0);try{const I=A.current;I&&m!==null&&m!==v.current&&(await ko(a,I,l,m),v.current=m);const P=await p(E,L);P!==null&&(h(P),v.current=P,_?.markDirty?.())}finally{$(!1),S(null)}}},N=async L=>{if(!(!f||T)){$(!0);try{const I=A.current;I&&m!==null&&m!==v.current&&(await ko(a,I,l,m),v.current=m);const P=await f(L);P!==null&&(h(P),v.current=P,_?.markDirty?.())}finally{$(!1)}}},H=L=>{L.key==="Enter"&&!L.shiftKey?(L.preventDefault(),D()):L.key==="Escape"&&(L.preventDefault(),O())};return C.current=()=>{D()},u.useEffect(()=>{const L=P=>{const F=w.current;if(!F)return;const G=P.target;if(G&&F.contains(G))return;const V=G;V&&V.closest&&V.closest('[data-testid="g7le-inline-toolbar"], .g7le-inline-toolbar')||C.current()},I=w.current?.ownerDocument??document;return I.addEventListener("pointerdown",L,!0),()=>I.removeEventListener("pointerdown",L,!0)},[]),i.jsxs("div",{ref:w,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(mr,{value:m,onChange:h,t:d,paramLabels:z,testIdSuffix:"inline",onRequestInsert:p?M:void 0,onRemoveChip:f?L=>{N(L)}:void 0}),E!==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:L=>{B(L)},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:b,onMouseDown:L=>L.preventDefault(),onClick:()=>{D()},style:{fontSize:11,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",padding:"4px 12px",cursor:"pointer"},children:d(b?"layout_editor.translation.saving":"layout_editor.translation.save")}),i.jsx("span",{style:{fontSize:10,color:"#94a3b8"},children:d("layout_editor.translation.placeholder_locked")})]})]})}const s4=["fontWeight","fontBold","fontStyle","fontItalic","textDecoration","textUnderline","textAlign","fontSize","textColor"],a4={fontWeight:"B",fontBold:"B",fontStyle:"I",fontItalic:"I",textDecoration:"U",textUnderline:"U",textAlign:"≡",fontSize:"T",textColor:"A"},l4=[["fontWeight","fontBold"],["fontItalic","fontStyle"],["textUnderline","textDecoration"]];function fg({node:e,spec:t,t:n,onApplyControl:o,box:r,scope:s=Wt}){const a=typeof e.name=="string"?e.name:"",l=Oi(t,a),d=Array.isArray(l?.styleControls)?l.styleControls:[];let c=s4.filter(p=>d.includes(p)&&Ct(t,p)!==null);for(const p of l4){const f=p.filter(y=>c.includes(y));if(f.length>1){const y=f[0];c=c.filter(g=>!p.includes(g)||g===y)}}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(c4,{controlKey:p,node:e,spec:t,t:n,scope:s,onApplyControl:o},p))})}const d4={fontWeight:"bold",fontBold:"bold",fontStyle:"italic",fontItalic:"italic",textDecoration:"underline",textUnderline:"underline"};function gg(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 c4({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=Do(t,d,r),y=d4[e],g=y&&Array.isArray(c)?gg(c,y):void 0,m=!y,h=g!==void 0?f.value===g:p&&f.matched&&f.value!==void 0&&f.value!=="",v=o(`layout_editor.inline_edit.format.${e}`),b=_=>typeof _.label=="string"?_.label.startsWith("$t:")?o(_.label.slice(3)):_.label:String(_.value??""),x=()=>{s(e,_=>{const C=Do(_,d,r),E=Array.isArray(c)?gg(c,y):void 0,S=E!==void 0&&C.value===E?void 0:E;return fn(_,d,S,r)})},k=_=>{s(e,C=>{const S=Do(C,d,r).value===_?void 0:_;return fn(C,d,S,r)}),l(!1)},w=_=>{if(_.preventDefault(),_.stopPropagation(),!m&&Array.isArray(c)){x();return}l(C=>!C)};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:_=>_.preventDefault(),onClick:w,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:a4[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:_=>_.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((_,C)=>{const E=f.value===_.value;return i.jsxs("button",{type:"button",role:"option","aria-selected":E,"data-testid":`g7le-inline-option-${e}-${String(_.value??C)}`,onMouseDown:S=>S.preventDefault(),onClick:S=>{S.preventDefault(),S.stopPropagation(),k(_.value)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",fontSize:12,textAlign:"left",border:"none",borderRadius:5,cursor:"pointer",background:E?"#2563eb":"transparent",color:"#ffffff"},children:[typeof _.swatch=="string"&&i.jsx("span",{"aria-hidden":"true",style:{width:14,height:14,borderRadius:3,background:_.swatch,border:"1px solid rgba(255,255,255,0.3)"}}),i.jsx("span",{children:b(_)}),E&&i.jsx("span",{"aria-hidden":"true",style:{marginLeft:"auto"},children:"✓"})]},String(_.value??C))}):i.jsx(u4,{testid:`g7le-inline-freeinput-${e}`,placeholder:o(`layout_editor.inline_edit.prompt.${e}`),initial:typeof f.value=="string"?f.value:"",onSubmit:_=>{s(e,C=>fn(C,d,_,r)),l(!1)}})})]})}function u4({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 p4(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:y}=Je(),{t:g}=tt(),m=ja(),h=u.useCallback((W,X)=>{const R=window.G7Core;if(R&&typeof R.t=="function"){const de=R.t(W,X);if(de&&de!==W&&!de.startsWith("$t:"))return de}return g(W,X)},[g]),v=Ft(),b=d7(50),x=yo(),k=u.useRef([]),w=u.useMemo(()=>v?.document?.raw?.components??[],[v?.document?.raw?.components]),_=u.useMemo(()=>w.length===0?null:{children:w},[w]),C=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]),E=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]),S=e7({rootNode:_,editMode:f.editMode,currentExtensionId:C,editableRootPath:E,pathParser:Ze,resolveRouteMatch:l}),[T,$]=u.useState(null),[A,z]=u.useState(null),[D,O]=u.useState(null),M=u.useRef(null);M.current=D;const[B,N]=u.useState(null),H=u.useRef(null),L=u.useRef(null);L.current=S.selectedPath;const I=Wb(),[P,F]=u.useState(null),G=u.useCallback(W=>{if(!t)return;const X=Ze(W);if(!X)return;const R={children:Me.current.components},de=We(R,X),ye=I.classify(de);if(!ye.editable){Et({op:"inline_edit_blocked_binding",sourceState:ye.sourceState,componentPath:at(X),timestamp:Date.now()});return}const we=po(t,W);if(!we)return;const Te=de?.props??{},ke=yg(t,W);F({path:X,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(X),timestamp:Date.now()})},[t,I]),V=u.useCallback(()=>{if(!t){$(null),z(null);return}z(po(t,S.selectedPath)),$(po(t,S.hoverPath))},[t,S.selectedPath,S.hoverPath,w]);u.useEffect(()=>{if(V(),typeof window<"u"&&typeof window.requestAnimationFrame=="function"){const W=window.requestAnimationFrame(()=>V());return()=>window.cancelAnimationFrame(W)}},[V]),u.useEffect(()=>{if(t)return $p(V,t)},[t,V]);const Y=u.useCallback((W,X)=>{if(typeof window>"u")return;window.dispatchEvent(new CustomEvent(La,{detail:X===null?{requestId:W,cancelled:!0}:{requestId:W,id:X}})),O(null),N(null);const R=H.current;R?S.handleSelect("",{dataset:{editorPath:R}}):S.clearSelection(),H.current=null},[S]);u.useEffect(()=>{if(typeof window>"u")return;const W=X=>{const R=X.detail;if(typeof R?.requestId!="string")return;const de=M.current;de&&de!==R.requestId&&Y(de,null),H.current=L.current,O(R.requestId)};return window.addEventListener(Pa,W),()=>window.removeEventListener(Pa,W)},[Y]),u.useEffect(()=>{if(!D)return;const W=X=>{X.key==="Escape"&&(X.preventDefault(),Y(D,null))};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[D,Y]),u.useEffect(()=>{if(!t)return;const W=f.editMode==="iteration_item"||f.editMode==="modal",X=(xe,Ee)=>ZT(xe,t,Ee?{x:Ee.clientX,y:Ee.clientY}:void 0,{handleFallback:W}),R=xe=>{const Ee=xe.dataset.editorPath??"",Fe=Ee?Ze(Ee):null,zt={children:Me.current.components},gt=Fe?We(zt,Fe):null,Mt=gt&&typeof gt.props?.id=="string"?gt.props.id:typeof gt?.id=="string"?gt.id:"";return Mt.startsWith("auto_")?"":Mt},de=xe=>{const Ee=X(xe.target,xe);if(!Ee)return;const Fe=M.current;if(Fe){xe.preventDefault(),xe.stopPropagation();const zt=R(Ee);zt&&Y(Fe,zt);return}xe.preventDefault(),xe.stopPropagation(),S.handleSelect(Ee.dataset.editorId??"",{currentTarget:Ee,dataset:Ee.dataset})},ye=xe=>{const Ee=X(xe.target,xe);if(M.current){if(!Ee){N(null);return}const Fe=po(t,Ee.dataset.editorPath??null);if(!Fe){N(null);return}N({box:Fe,hasId:R(Ee)!==""});return}if(!Ee){S.handleHover(null,{});return}S.handleHover(Ee.dataset.editorId??"",{currentTarget:Ee,dataset:Ee.dataset})},we=()=>{if(M.current){N(null);return}S.handleHover(null,{})},Te=xe=>{const Ee=X(xe.target,xe);if(!Ee)return;const Fe=Ee.dataset.editorPath??"";Fe&&(xe.preventDefault(),xe.stopPropagation(),G(Fe))},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,S,G,f.editMode,Y]);const Z=u.useMemo(()=>{const W=S.selectedPath;if(!W)return null;const X=W.match(/^(.*)\.children\.\d+$/);return X?X[1]:null},[S.selectedPath]),se=u.useCallback(()=>{Z&&S.handleSelect("",{dataset:{editorPath:Z}})},[Z,S]),re=u.useMemo(()=>!t||!S.selectedPath?null:t.querySelector(`[data-editor-path="${an(S.selectedPath)}"]`),[t,S.selectedPath]),U=u.useMemo(()=>S.selectedPath?Ze(S.selectedPath):null,[S.selectedPath]),ee=u.useMemo(()=>{if(!U)return null;const W=U.find(et);if(!W)return null;const{i18nKey:X,raw:R}=bC(W.responsive);return X?g(X):g("layout_editor.overlay.branch_custom",{range:R})},[U,g]),fe=u.useMemo(()=>S.selectedPath?S.selectedIsIteration&&S.selectedIterationSourcePath?S.selectedIterationSourcePath:S.selectedPath:null,[S.selectedPath,S.selectedIsIteration,S.selectedIterationSourcePath]),K=u.useMemo(()=>fe?Ze(fe):null,[fe]),ne=u.useMemo(()=>!t||!fe?null:t.querySelector(`[data-editor-path="${an(fe)}"]`),[t,fe]),me=u.useMemo(()=>{if(ne?.parentElement)return ne.parentElement;if(!t||!fe)return null;const W=fe.match(/^(.*)\.children\.\d+$/);return W?t.querySelector(`[data-editor-path="${an(W[1])}"]`):null},[ne,t,fe]),Ce=u.useMemo(()=>{const W=S.selectedNode;return W&&(typeof W.name=="string"?W.name:typeof W.type=="string"?W.type:"")||null},[S.selectedNode]),ze=u.useMemo(()=>{if(S.selectedLockKind!=="extension")return null;const W=S.selectedNode?.__source;if(!W||W.kind!=="extension")return null;const X=W.extensionName?.trim(),R=W.extensionIdentifier?.trim();return X&&R?`${X} (${R})`:X||R||W.extensionSourceType||null},[S.selectedLockKind,S.selectedNode]),Se=s7({parentEl:me,selectedPath:K,selectedEl:ne}),qe=u.useMemo(()=>!t||!fe||fe===S.selectedPath?A:po(t,fe),[t,fe,A,S.selectedPath,w]),De=u.useRef(null),Pe=u.useCallback(()=>{const W=De.current;W&&(x.close(W),De.current=null)},[x]),Qe=u.useRef(()=>{}),Me=u.useRef({manifest:n,nesting:o,componentPalette:r,components:w});Me.current={manifest:n,nesting:o,componentPalette:r,components:w};const Re=u.useCallback(W=>{const X=W.insertion?.parentPath??[],R=W.insertion?.index??0,de=Me.current,ye=hg(de.components,X);Pe();const we=x.open({ariaLabel:h("layout_editor.palette.title"),width:880,maxHeightRatio:.82,content:u.createElement(Ef,{manifest:de.manifest,nesting:de.nesting,componentPalette:de.componentPalette??null,targetParentPath:X,targetContainerName:ye,onInsert:(Te,ke,xe)=>{Qe.current(Te,ke,xe)},insertionIndex:R,onClose:()=>Pe(),editorTemplateId:f.templateIdentifier,editorLocale:f.locale}),onClose:()=>{De.current=null}});De.current=we},[x,Pe]),ve=u.useMemo(()=>{if(!f.isPaletteOpen)return null;if(!U)return{parentPath:[],index:w.length};if(S.selectedLockKind!=="none"){const de=K;return!de||de.length===0?{parentPath:[],index:w.length}:{parentPath:de.slice(0,-1),index:(de[de.length-1]??0)+1}}const X=S.selectedNode,R=Array.isArray(X?.children)?X.children.length:0;return lI(X?.name,R,U,o,w.length)},[f.isPaletteOpen,U,K,S.selectedLockKind,S.selectedNode,w.length,o]),te=u.useCallback(()=>{y({type:"SET_PALETTE_OPEN",open:!1})},[y]),he=u.useRef(null);u.useEffect(()=>{if(!f.isPaletteOpen){const ye=he.current;ye&&(x.close(ye),he.current=null);return}if(!ve||he.current)return;const W=ve,X=Me.current,R=hg(X.components,W.parentPath),de=x.open({ariaLabel:h("layout_editor.palette.title"),width:880,maxHeightRatio:.82,content:u.createElement(Ef,{manifest:X.manifest,nesting:X.nesting,componentPalette:X.componentPalette??null,targetParentPath:W.parentPath,targetContainerName:R,onInsert:(ye,we,Te)=>{Qe.current(ye,we,Te),te()},insertionIndex:W.index,onClose:()=>te(),editorTemplateId:f.templateIdentifier,editorLocale:f.locale}),onClose:()=>{he.current=null,y({type:"SET_PALETTE_OPEN",open:!1})}});he.current=de},[f.isPaletteOpen,ve,x,te,y]);const Q=u.useRef({layoutName:null,pushed:!1});u.useEffect(()=>{const W=v?.document?.layoutName??null;if(!W){Q.current={layoutName:null,pushed:!1};return}Q.current.layoutName!==W&&(b.clear(),b.push({actionKind:"inline_text_edit",label:"baseline",snapshot:w}),Q.current={layoutName:W,pushed:!0})},[v?.document?.layoutName,w,b]);const ie=u.useRef(0);u.useEffect(()=>{const W=v?.saveSuccessCounter??0;W!==ie.current&&(ie.current=W,W!==0&&(b.clear(),b.push({actionKind:"inline_text_edit",label:"save_baseline",snapshot:w}),k.current=[],c?.([])))},[v?.saveSuccessCounter,w,b,c]);const _e=u.useRef(0);u.useEffect(()=>{const W=v?.reloadCounter??0;W!==_e.current&&(_e.current=W,W!==0&&(Q.current={layoutName:null,pushed:!1},k.current=[],c?.([])))},[v?.reloadCounter,c]);const ge=u.useCallback((W,X,R)=>{if(!v)return;let de=[];v.patchLayout(ke=>{const xe={children:ke},Ee=Ha(xe,X),Fe=R<0?Array.isArray(Ee?.children)?Ee.children.length:0:R,gt=Qi(xe,X,Fe,W).children??[];return de=gt,gt}),b.push({actionKind:"insert",label:`insert ${W.name??W.type??""}`,snapshot:de});const ye=Ha({children:de},X),we=R<0?Array.isArray(ye?.children)?ye.children.length-1:0:R,Te=at([...X,we]);if(k.current=[...k.current,Te],c?.(k.current),t){const ke=`[data-editor-path="${an(Te)}"]`,xe=()=>{const Ee=t.querySelector(ke);Ee&&typeof Ee.scrollIntoView=="function"&&Ee.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"})};typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(()=>window.requestAnimationFrame(xe)):setTimeout(xe,32)}},[v,b,c,t]);Qe.current=ge;const Ae=u.useCallback(()=>{if(!v||!S.selectedNode||!U)return;const W=es(S.selectedNode);let X=[];v.patchLayout(R=>{const de={children:R},ye=U.slice(0,-1),we=U[U.length-1]??0,ke=Qi(de,ye,we+1,W).children??[];return X=ke,ke}),b.push({actionKind:"insert",label:"duplicate",snapshot:X})},[v,S.selectedNode,U,b]),Ne=u.useCallback(()=>{if(!v||!U)return;let W=[];v.patchLayout(X=>{const ye=Ri({children:X},U).children??[];return W=ye,ye}),b.push({actionKind:"remove",label:"remove",snapshot:W}),S.clearSelection()},[v,U,b,S]),Le=u.useMemo(()=>{if(!S.selectedNode||!U||U.some(et))return null;const W=S.selectedNode;if(!Array.isArray(W.children))return null;const X=yC(f.previewDevice,W,f.previewCustomWidth);return{mode:X.mode,key:X.key,sourceKey:X.sourceKey}},[S.selectedNode,U,f.previewDevice,f.previewCustomWidth]),q=u.useCallback(()=>{if(!v||!U||Le?.mode!=="separate")return;const W=Le.key,X=Le.sourceKey;let R=[];v.patchLayout(de=>(R=Ab({children:de},U,W,X).children??[],R)),b.push({actionKind:"insert",label:"separate_branch",snapshot:R})},[v,U,Le,b]),ae=u.useCallback(()=>{if(!v||!U||Le?.mode!=="merge")return;const W=Le.key;let X=[];v.patchLayout(R=>(X=Tb({children:R},U,W).children??[],X)),b.push({actionKind:"remove",label:"merge_branch",snapshot:X})},[v,U,Le,b]),pe=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]),$e=u.useMemo(()=>{if(!Le)return null;const W=pe(Le.key);return{separate:g("layout_editor.context_menu.separate_branch_device",{device:W}),merge:g("layout_editor.context_menu.merge_branch_device",{device:W})}},[Le,g,pe]),be=u.useMemo(()=>{if(!S.selectedNode||!U)return[];if(U.some(et))return[];const W=Ur(f.previewDevice,S.selectedNode,f.previewCustomWidth);return G6(S.selectedNode,W).map(X=>({key:X,label:pe(X)}))},[S.selectedNode,U,f.previewDevice,f.previewCustomWidth,pe]),j=u.useCallback(W=>{if(W==="desktop"||W==="tablet"||W==="mobile"||W==="portable"){m.setDevice(W);return}m.setDevice(W)},[m]),oe=u.useCallback(()=>{S.selectedNode&&dg(S.selectedNode)},[S.selectedNode]),ue=u.useCallback(()=>{S.selectedNode&&(dg(S.selectedNode),Ne())},[S.selectedNode,Ne]),J=u.useCallback(()=>{if(!v)return;const W=VT();if(!W)return;const X=es(W);if(U&&U.length>0){const R=U.slice(0,-1),de=(U[U.length-1]??0)+1;ge(X,R,de)}else ge(X,[],w.length)},[v,U,ge,w.length]),le=u.useCallback((W,X)=>{b.push({actionKind:"move",label:X,snapshot:W})},[b]),Ie=u.useCallback(()=>{if(S.selectedNavAffordance==="route_in_tree"&&S.selectedNavTargetPath){if(d){d(S.selectedNavTargetPath);return}y({type:"SELECT_ROUTE",route:{path:S.selectedNavTargetPath,layoutName:null}})}},[S.selectedNavAffordance,S.selectedNavTargetPath,d,y]),dt=u.useCallback(()=>{const W=Eb(S.selectedBaseLayout,f.selectedRoute?.layoutName);W&&y({type:"ENTER_BASE_EDIT",layoutName:W})},[S.selectedBaseLayout,f.selectedRoute?.layoutName,y]),pt=u.useCallback(()=>{const W=S.selectedNode?.__source?.extensionId;W!=null&&y({type:"ENTER_EXTENSION_EDIT",extensionId:String(W)})},[S.selectedNode,y]),ot=u.useCallback(()=>{const W=S.selectedIterationSourcePath;W&&y({type:"ENTER_ITERATION_ITEM_EDIT",sourcePath:W})},[S.selectedIterationSourcePath,y]),Oe=u.useRef(null),He=u.useRef(null),Ye=u.useRef(null),Tt=u.useRef({colorScheme:"base",breakpoint:"base"}),Dt=Oe.current!==null?x.stack.some(W=>W.id===Oe.current):!1,Nt=u.useMemo(()=>zd(f.routeTree,h),[f.routeTree,h]),xn=u.useMemo(()=>Md(v?.document?.raw),[v?.document?.raw]),wn=u.useMemo(()=>Ld(s),[s?.states]),Zt=u.useMemo(()=>{const W=v?.document?.raw,X=Af(W?.components),R=W?.initIsolated,de=R&&typeof R=="object"&&!Array.isArray(R)?Object.keys(R):[];return eA(X,de)},[v?.document?.raw]),Hn=u.useMemo(()=>{const W=v?.document?.raw;return Af(W?.components).map(X=>X.scopeId).filter(X=>typeof X=="string"&&X.length>0)},[v?.document?.raw]),ln=Nd({raw:v?.document?.raw,spec:s}),Ii=u.useCallback((W,X)=>{if(!v)return;const R={children:Me.current.components},de=We(R,W);if(!de)return;Tt.current={colorScheme:f.previewColorScheme==="dark"?"dark":"base",breakpoint:Ur(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=re,ke=W.find(et),xe=ke?pe(ke.responsive):null,Ee=W.filter(kn=>typeof kn=="number"),Fe=cb({children:Me.current.components},Ee,ub(ln)),zt=Fe.length>0?[...ji({iterationVars:Fe}),...ln]:ln,gt=(kn,lM)=>u.createElement(ET,{key:`pem-${at(He.current??[])}`,node:kn,spec:s,manifest:Me.current.manifest,t:h,permissionCandidates:a,pageCandidates:Nt,dataSourceCandidates:xn,stateKeyCandidates:wn,bindingCandidates:zt,liveElement:Te,templateIdentifier:f.templateIdentifier,initialTab:lM,branchLabel:xe,isolatedScopeIdCandidates:Zt,usedScopeIds:Hn,onSaveInjectedProps:async(bt,Sn)=>{const Ai=typeof kn.id=="string"?kn.id:"",Fn=await HT(f.templateIdentifier,bt,Ai,Sn);if(st({op:"save",layoutName:`extension:${bt}`,editMode:f.editMode,saveTarget:"layout_extension",endpoint:`/api/admin/templates/${f.templateIdentifier}/layout-extensions/${bt}`,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:bt=>{Tt.current=bt;const Sn=Oe.current;Sn&&x.open({id:Sn,ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(kn),onClose:()=>{Oe.current=null,He.current=null}})},onPatchNode:bt=>{let Sn=[];v.patchLayout(Fn=>(Sn=Ot({children:Fn},W,()=>bt).children??[],Sn)),b.push({actionKind:"inline_text_edit",label:"edit_props",snapshot:Sn}),sr({source:"style_control",componentPath:at(W),componentName:typeof bt.name=="string"?bt.name:null,patchKey:null,timestamp:Date.now()});const Ai=Oe.current;Ai&&x.open({id:Ai,ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(bt),onClose:()=>{Oe.current=null,He.current=null}})},onDelete:()=>{const bt=Oe.current;bt&&x.close(bt),Ne()},onClose:()=>{const bt=Oe.current;bt&&x.close(bt)}});He.current=W;const Mt=x.open({ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(de,X),onClose:()=>{Oe.current=null,He.current=null,Ye.current=null}});Oe.current=Mt,Ye.current=kn=>{x.open({id:Mt,ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(kn),onClose:()=>{Oe.current=null,He.current=null,Ye.current=null}})}},[v,s,h,a,Nt,xn,wn,ln,re,b,x,Ne,t,A,f.previewColorScheme,f.previewDevice,f.previewCustomWidth,pe]);u.useEffect(()=>{const W=Ye.current,X=He.current;if(!W||!X)return;const R={children:Me.current.components},de=We(R,X);de?W(de):Oe.current&&x.close(Oe.current)},[w]);const Uz=()=>{if(!Dt)return null;const X={position:"absolute",background:"rgba(15, 23, 42, 0.45)",pointerEvents:"auto",zIndex:f7},R=ke=>{ke.preventDefault(),ke.stopPropagation()};if(!A)return i.jsx("div",{"data-testid":"g7le-edit-lock-full",onClick:R,onMouseMove:R,style:{...X,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:{...X,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:{...X,left:0,top:ye+Te,right:0,bottom:0}}),i.jsx("div",{"data-testid":"g7le-edit-lock-left",onClick:R,onMouseMove:R,style:{...X,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:{...X,left:de+we,top:ye,right:0,height:Te}})]})},ml=u.useCallback(()=>{if(U&&_p(S.selectedLockKind)){if(p&&S.selectedPath){p(S.selectedPath);return}Ii(U)}},[U,S.selectedPath,S.selectedLockKind,p,Ii]),{scale:vl}=m,_l=typeof S.selectedNode?.name=="string"?S.selectedNode.name:"",Bh=s?.componentCapabilities?.[_l]??null,Wh=Array.isArray(Bh?.styleControls)?Bh.styleControls:[],qz=Wh.includes("width")?Ct(s,"width"):null,Gz=Wh.includes("height")?Ct(s,"height"):null,Yz=u.useCallback((W,X)=>{if(!v||!U)return;let R=[];v.patchLayout(de=>(R=Ot({children:de},U,()=>W).children??[],R)),sr({source:"resize",componentPath:at(U),componentName:_l||null,patchKey:X==="height"?"height":"width",resizeAxis:X,timestamp:Date.now()})},[v,U,_l]),Xz=u.useCallback((W,X)=>{if(!v||!U)return;let R=[];v.patchLayout(de=>(R=Ot({children:de},U,()=>W).children??[],R)),b.push({actionKind:"inline_text_edit",label:`resize ${X}`,snapshot:R})},[v,U,b]),Jz=u.useCallback(()=>{if(!re)return null;const W=re.getBoundingClientRect(),X=vl||1;return{width:W.width/X,height:W.height/X}},[re,vl]),ir=GT({node:S.selectedNode,widthControl:qz,heightControl:Gz,scale:vl,measureStartSize:Jz,onResize:Yz,onResizeEnd:Xz}),Zz=u.useCallback((W,X)=>{ir.onHandlePointerDown(W,X)},[ir]),xl=u.useCallback(()=>{const W=b.undo();!W||!v||v.setLayoutComponents(W.snapshot)},[b,v]),wl=u.useCallback(()=>{const W=b.redo();!W||!v||v.setLayoutComponents(W.snapshot)},[b,v]);u7({onUndo:xl,onRedo:wl});const Qz=u.useMemo(()=>({copy:oe,cut:ue,paste:J,delete:Ne,openProps:ml,selectParent:Z?se:void 0,deselect:S.clearSelection}),[oe,ue,J,Ne,ml,Z,se,S.clearSelection]);np({handlers:Qz,hasSelection:!!S.selectedPath}),u.useEffect(()=>(window.__g7LayoutEditorHasSelection=!!S.selectedPath,()=>{try{delete window.__g7LayoutEditorHasSelection}catch{}}),[S.selectedPath]),u.useEffect(()=>(window.__g7LayoutEditorHistory={undo:xl,redo:wl,canUndo:b.canUndo,canRedo:b.canRedo},()=>{try{delete window.__g7LayoutEditorHistory}catch{}}),[xl,wl,b.canUndo,b.canRedo]);const Rz=u.useCallback(W=>{const X=P;F(null),X&&(async()=>{if((await I.commit(X.path,W)).kind==="created"&&v){const de=v.document?.raw?.components??[];b.push({actionKind:"inline_text_edit",label:"inline_create_key",snapshot:de})}})()},[P,I,v,b]),jh=u.useCallback(()=>{const W=P;F(null),I.trackCancel(W?.path??null)},[P,I]),eM=u.useCallback(()=>{F(null)},[]),tM=u.useCallback(async W=>{const X=P;if(!X)return null;const R=await I.keyifyChipValue(X.path,W);if(R.kind!=="created"||!R.translationKey)return null;const de=v?.document?.raw?.components??[];return b.push({actionKind:"inline_text_edit",label:"inline_keyify_chip",snapshot:de}),R.translationKey},[P,I,v,b]),nM=u.useCallback(()=>{const W=P;W&&(F(null),S.handleSelect("",{dataset:{editorPath:W.domPath}}),Ii(W.path,"translation"))},[P,S,Ii]),xt=u.useMemo(()=>{if(!P)return null;const W=v?.document?.raw?.components??w;return We({children:W},P.path)},[P,v?.document,w]),oM=u.useCallback(async(W,X)=>{const R=P;if(!v||!R)return null;const de=typeof xt?.text=="string"?xt.text:"";let ye;if(R.isParamKey)ye=await wr(f.templateIdentifier,f.locale,de,W,X.sourceId,X.path,"scalar");else{const Fe=zt=>zt.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 ls(f.templateIdentifier,f.selectedRoute?.layoutName??null,f.locale,de,W,X.sourceId,X.path,"scalar",Fe,h)}if(ye.kind==="error")return null;const we=R.path;let Te=[];v.patchLayout(Fe=>(Te=Ot({children:Fe},we,Mt=>({...Mt,text:ye.text})).children??[],Te)),b.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(Fe=>Fe&&Fe.path===we?{...Fe,isParamKey:!0,customKey:ke,chipValue:void 0,chipParamLabels:void 0}:Fe);try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:f.templateIdentifier,locale:f.locale}}))}catch{}const xe=mt(ye.text),Ee=R.customKey??xe?.key??"";return Ee?It(Ee,f.locale)??null:null},[v,P,xt,f.templateIdentifier,f.locale,f.selectedRoute,b,h]),rM=u.useCallback(async W=>{const X=P;if(!v||!X)return null;const R=typeof xt?.text=="string"?xt.text:"",de=mt(R),ye=X.customKey??de?.key??null,we=mo(R,W),Te=X.path;let ke=[];return v.patchLayout(xe=>(ke=Ot({children:xe},Te,zt=>({...zt,text:we})).children??[],ke)),b.push({actionKind:"inline_text_edit",label:"inline_remove_binding",snapshot:ke}),ye&&await kr(f.templateIdentifier,ye,W,f.locale),ye?It(ye,f.locale)??null:null},[v,P,xt,f.templateIdentifier,f.locale,b]),[kl,Hh]=u.useState({}),iM=["fontSize","color","fontStyle","textDecoration","textAlign","letterSpacing","lineHeight","fontFamily"];u.useEffect(()=>{if(!P||!t||typeof MutationObserver>"u"){Hh({});return}const W=`[data-editor-path="${an(P.domPath)}"]`,X=()=>{const ye=t.querySelector(W);if(!ye)return;const we={};for(const ke of iM){const xe=ye.style.getPropertyValue(ke.replace(/([A-Z])/g,"-$1").toLowerCase());xe&&(we[ke]=xe)}const Te=yg(t,P.domPath)??void 0;Hh({className:ye.className,style:we,effectiveColor:Te})};X();const R=t.querySelector(W);if(!R)return;const de=new MutationObserver(X);return de.observe(R,{attributes:!0,attributeFilter:["class","style"]}),de.observe(t,{childList:!0,subtree:!0}),()=>de.disconnect()},[P?.path?at(P.path):null,t]);const Fh=u.useCallback((W,X)=>{if(!v||!P)return;const R=P.path;let de=[],ye=null;v.patchLayout(we=>(de=Ot({children:we},R,xe=>{const Ee=X(xe);return ye=typeof Ee.name=="string"?Ee.name:null,Ee}).children??[],de)),b.push({actionKind:"inline_text_edit",label:`inline_format ${W}`,snapshot:de}),sr({source:"style_control",componentPath:at(R),componentName:ye,patchKey:W,timestamp:Date.now()})},[v,P,b]),ft=u.useMemo(()=>{const W=S.selectedPath;if(!W||!_)return null;const X=[];let R=W;for(;R;){X.push(R);const de=R.match(/^(.*)\.children\.\d+$/);R=de?de[1]:null}for(const de of X){const ye=Ze(de);if(!ye)continue;const we=We(_,ye),Te=typeof we?.name=="string"?we.name:null;if(!Te)continue;const ke=Oi(s,Te),xe=ke?.canvasOverlay?.kind;if(typeof xe!="string"||!xe||!we)continue;const Ee=ke.canvasOverlay.params&&typeof ke.canvasOverlay.params=="object"?ke.canvasOverlay.params:void 0,Fe=de===W?null:W.slice(de.length+1);return{kind:xe,params:Ee,tablePath:de,tableNode:we,selectedCellRel:Fe}}return null},[S.selectedPath,_,s]),ho=ft?FT(ft.kind):null,Kh=u.useMemo(()=>!ho||!t||!ft?null:po(t,ft.tablePath),[ho,t,ft,A,w]),sM=u.useMemo(()=>{if(!ho||!t||!ft)return[];const W=ft.tablePath,X=an(W),R=[];return t.querySelectorAll(`[data-editor-path^="${X}.children."]`).forEach(we=>{const Te=we.dataset.editorPath??"";if(!Te.startsWith(W+"."))return;const ke=Te.slice(W.length+1),xe=so(we,t);xe&&R.push({path:ke,top:xe.top,left:xe.left,width:xe.width,height:xe.height})}),t.querySelectorAll(`[data-editor-item-path^="${X}."]`).forEach(we=>{const Te=we.dataset.editorItemPath??"";if(!Te.startsWith(W+"."))return;const ke=Te.slice(W.length+1),xe=so(we,t);xe&&R.push({path:ke,top:xe.top,left:xe.left,width:xe.width,height:xe.height})}),R},[ho,t,ft,A,w]),aM=u.useCallback(W=>{const X=ft?Ze(ft.tablePath):null;if(!v||!X)return;let R=[];v.patchLayout(de=>(R=Ot({children:de},X,()=>W).children??[],R)),b.push({actionKind:"inline_text_edit",label:"inplace_edit",snapshot:R}),sr({source:"style_control",componentPath:ft?.tablePath??"",componentName:typeof W.name=="string"?W.name:null,patchKey:"canvas_inplace",timestamp:Date.now()})},[v,U,b]);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&&Uz(),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:()=>Y(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(EI,{frameEl:t,components:w,editMode:f.editMode,currentExtensionId:C,editableRootPath:E}),P&&((P.isParamKey&&P.customKey||P.chipValue)&&xt?i.jsxs(i.Fragment,{children:[xt&&i.jsx(fg,{node:xt,spec:s,t:h,onApplyControl:Fh,box:P.box,scope:{colorScheme:f.previewColorScheme==="dark"?"dark":"base",breakpoint:Ur(f.previewDevice,xt,f.previewCustomWidth)}}),i.jsx(i4,{box:P.box,node:xt,customKey:P.customKey??null,initialChipValue:P.chipValue,chipParamLabels:P.chipParamLabels,onKeyify:tM,templateIdentifier:f.templateIdentifier,locale:f.locale,t:h,candidates:ln,onInsertBinding:oM,onRemoveBinding:rM,onCommit:eM,onCancel:jh})]}):i.jsxs(i.Fragment,{children:[xt&&i.jsx(fg,{node:xt,spec:s,t:h,onApplyControl:Fh,box:P.box,scope:{colorScheme:f.previewColorScheme==="dark"?"dark":"base",breakpoint:xt?Ur(f.previewDevice,xt,f.previewCustomWidth):"base"}}),i.jsx(r4,{box:P.box,initialValue:P.initialValue,isCustomKey:P.isCustomKey,t:h,onCommit:Rz,onCancel:jh,mirrorClassName:kl.className,mirrorStyle:kl.style,nodeEffectiveColor:kl.effectiveColor??P.nodeEffectiveColor,onOpenTranslations:nM})]})),!D&&i.jsx(v7,{hoverBox:T,selectedBox:A,lockKind:S.selectedLockKind,navAffordance:S.selectedNavAffordance,onEditProps:ml,onDuplicate:Ae,onDelete:Ne,onSeparateBranch:Le?.mode==="separate"?q:void 0,separateBranchLabel:$e?.separate,onMergeBranch:Le?.mode==="merge"?ae:void 0,mergeBranchLabel:$e?.merge,definedDeviceBranches:be,onJumpToDevice:be.length>0?j:void 0,onLinkEditDestination:Ie,onEditBase:dt,onEditExtension:pt,extensionLabel:ze,baseLayoutLabel:S.selectedBaseLayout,dataSourceLabel:S.selectedDataSourceId,branchLabel:ee,onEditIteration:S.selectedIsIteration&&f.editMode!=="iteration_item"?ot:void 0,resizeEnabledAxes:ir.enabledAxes,onResizeHandlePointerDown:ir.enabledAxes.width||ir.enabledAxes.height?Zz:void 0,selectedName:Ce,onSelectParent:Z?se:void 0}),D&&B&&i.jsx("div",{"data-testid":"g7le-canvas-pick-hover","data-pick-has-id":B.hasId?"true":"false",style:{position:"absolute",left:B.box.left,top:B.box.top,width:B.box.width,height:B.box.height,pointerEvents:"none",zIndex:9998,boxSizing:"border-box",border:B.hasId?"2px solid #2563eb":"2px dashed #94a3b8",background:B.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:B.hasId?"pointer":"not-allowed"},children:!B.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(C7,{selectedBox:qe,points:Se.points,onAddRequest:Re}),ho&&ft&&Kh&&S.selectedLockKind==="none"&&i.jsx(ho,{node:ft.tableNode,params:ft.params,nodeBox:Kh,cellBoxes:sM,selectedCellPath:ft.selectedCellRel??void 0,colorScheme:f.previewColorScheme==="dark"?"dark":"light",t:h,onPatchNode:aM,onInsertChild:ge,onRemoveChild:W=>{const X=Ze(W);if(!v||!X)return;let R=[];v.patchLayout(de=>(R=Ri({children:de},X).children??[],R)),b.push({actionKind:"remove",label:"inplace_remove",snapshot:R})},onRequestInlineEdit:W=>{ft&&G(`${ft.tablePath}.${W}`)}}),v&&i.jsx(xI,{frameEl:t,nesting:o,editMode:f.editMode,currentExtensionId:C,editableRootPath:E,components:w,patchLayout:v.patchLayout,pushHistory:le,selectedPath:S.selectedPath,onSelectPath:W=>S.handleSelect("",{dataset:{editorPath:W}}),onMovePath:W=>S.handleSelect("",{dataset:{editorPath:W}}),onRequestInlineEdit:G})]}):null}function hg(e,t){if(t.length===0)return null;const o=Ha({children:e},t);return o&&typeof o.name=="string"?o.name:null}function Ha(e,t){return We(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 yg(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 po(e,t){if(!t)return null;const n=e.querySelector(`[data-editor-path="${an(t)}"]`);if(n){const c=so(n,e);return c&&ao(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=so(c,e);f&&ao(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 f4({isEditMode:e,editorSpec:t,sampleOverride:n}){const o=t?.sampleData;return u.useMemo(()=>Pm({spec:o,overrideSpec:n,onMatch:r=>{Uh(r)}}),[e,o,n])}const g4=Lt().ComponentRegistry;function h4(e){return e.split(/[-_]/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}async function y4(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 Gr(o.status,s,"assets")}const r=await o.json();return r.data||r}async function b4(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 m4(e){return new Promise((t,n)=>{if(typeof document>"u"){n(new Error("document undefined"));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 v4(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 _4(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 y4(e);if(s)return;for(const y of a.css??[])if(await v4(y),s)return;const l=h4(e);if(!(typeof window<"u"&&typeof window[l]=="object")){for(const y of a.js??[])if(await m4(y),s)return}const c=g4.createIsolatedInstance();if(await c.loadComponents(e,n),s)return;const p=await b4(e);if(s)return;const f=new Pt({defaultLocale:t});if(p>0&&f.setCacheVersion(p),await f.loadTranslations(e,t),s)return;cd(f,e);try{const y=Pt.getInstance();p>y.getCacheVersion()&&y.setCacheVersion(p),await y.loadTranslations(e,t),cd(y,e)}catch{}if(s)return;r({componentRegistry:c,translationEngine:f,isReady:!0,error:null})}catch(a){if(s)return;const l=hp(a)?a:io(a,"assets");r({componentRegistry:null,translationEngine:null,isReady:!1,error:l})}})(),()=>{s=!0}},[e,t,n]),o}const bg=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 w4={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 k4({error:e}){return u.useEffect(()=>{if(e.kind!=="unauthorized"||typeof window>"u")return;const t=bg.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 Fa({error:e}){const{t}=tt(),n=x4(e.kind),o=w4[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=bg.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(k4,{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:Ka,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:Ka,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:Ka,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:S4,children:t("layout_editor.access_error.action.go_admin_home")})]})]})]})}const Ka={padding:"8px 16px",background:"#2563eb",color:"#fff",border:"1px solid #1d4ed8",borderRadius:6,fontSize:13,fontWeight:600,cursor:"pointer"},S4={padding:"8px 16px",background:"#fff",color:"#475569",border:"1px solid #cbd5e1",borderRadius:6,fontSize:13,fontWeight:500,cursor:"pointer"};function C4(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 $4=new Set(["id","userId","postId","orderId","productId","categoryId","commentId","noticeId","inquiryId","addressId","wishlistId","notificationId","roleId","menuId"]);function E4(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]=I4(r)}return t}function I4(e){return $4.has(e)||/Id$|_id$/.test(e)?"1":"sample"}const A4=bo("LayoutEditor");function Jo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bi(e){if(Array.isArray(e))return e.map(t=>bi(t));if(Jo(e)){const t={};for(const[n,o]of Object.entries(e))t[n]=bi(o);return t}return e}function mg(e,t="",n=new Set){for(const[o,r]of Object.entries(e)){const s=t?`${t}.${o}`:o;Jo(r)?mg(r,s,n):n.add(s)}return n}function vg(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];Jo(l)&&Jo(c)?vg(c,l,n,o,r,d):e[a]=bi(l)}}function Va(e){const t=e.warn??(r=>A4.warn(r)),n=bi(e.coreSeed??{});e.isGuestOnly&&"currentUser"in n&&delete n.currentUser;const o=mg(n);for(const r of e.sources)Jo(r.sampleGlobal)&&vg(n,r.sampleGlobal,o,r.id,t);return e.isGuestOnly&&"currentUser"in n&&delete n.currentUser,n}function T4(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 D4(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 N4(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 z4(e,t){const n=N4(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 mi(e,t){for(const[n,o]of Object.entries(t)){const r=e[n];St(o)&&St(r)?mi(r,o):e[n]=Xt(o)}}function P4(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 Ua(e,t,n){const o=P4(t);if(o.length===0)return;let r=e;for(let s=0;s0?t:void 0}const Ga="g7le:editor-t-ready",wg="data-g7le-vh-expanded";function B4(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(wg,"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(wg,"1"))})}const W4=[];function j4(e={}){const{manifest:t=null,nesting:n=null,componentPalette:o=null,spec:r=null,permissionCandidates:s,sampleGlobalSources:a=W4,resolveRouteMatch:l,onNavigateToDestination:d,onSessionAddedPathsChange:c}=e,{state:p}=Je(),f=Ft(),y=Cp(),{document:g,isLoading:m,error:h}=f??y,v=u.useRef(null),[b,x]=u.useState(null),{deviceWidth:k,scale:w,colorScheme:_}=ja(),C=u.useMemo(()=>p.activeStateId?p.availableStates.find(Q=>Q.id===p.activeStateId)??null:null,[p.activeStateId,p.availableStates]),E=u.useMemo(()=>xg(C),[C]),S=f4({isEditMode:!0,editorSpec:r??void 0,sampleOverride:E}),{t:T}=tt(),{componentRegistry:$,translationEngine:A,isReady:z,error:D}=_4(p.templateIdentifier,p.locale),O=u.useRef(null);O.current===null&&(O.current=new vd);const M=u.useRef(null);if(M.current===null){M.current=new VE({navigate:()=>{}}),M.current.setPreviewMode(!0);try{const ie=window.__templateApp?.getActionDispatcher?.();if(ie&&typeof ie.getRegisteredHandlers=="function"){const _e=ie.getRegisteredHandlers();for(const ge of _e){if(!ge.includes("."))continue;const Ae=typeof ie.getHandler=="function"?ie.getHandler(ge):void 0;typeof Ae=="function"&&M.current.registerHandler(ge,Ae,{category:"plugin",source:"preview-canvas-cloned-from-host"})}}}catch{}}u.useEffect(()=>{if(!z)return;const Q=M.current;if(Q)try{const ie=window.G7Core?.getActionDispatcher?.();if(!ie||typeof ie.getRegisteredHandlers!="function")return;const _e=ie.getRegisteredHandlers();for(const ge of _e){if(!ge.includes(".")||typeof Q.getHandler=="function"&&Q.getHandler(ge))continue;const Ae=typeof ie.getHandler=="function"?ie.getHandler(ge):void 0;typeof Ae=="function"&&Q.registerHandler(ge,Ae,{category:"plugin",source:"preview-canvas-iife-reclone"})}}catch{}},[z]);const B=u.useMemo(()=>new UE({sampleProvider:S,actionDispatcher:M.current}),[S]),N=u.useMemo(()=>g?.raw?.meta?.guest_only===!0,[g]),H=u.useMemo(()=>Va({sources:a,isGuestOnly:N}),[a,N]),L=u.useMemo(()=>{const Q=H4(qa(C),A,{templateId:p.templateIdentifier,locale:p.locale}),ie=H._local,{global:_e,local:ge}=O4({globalBaseline:H,localBaseline:ie??{},patch:C?.initialState??null,formErrors:Q});return{..._e,_local:ge}},[H,C,A,p.templateIdentifier,p.locale]),I=u.useMemo(()=>!C||!(!!C.initialState?.local||!!qa(C))?null:{...L._local??{},_forceLocalInit:C.id,_merge:"deep"},[C,L]),P=Q=>typeof Q=="object"&&Q!==null&&!Array.isArray(Q),F=u.useMemo(()=>P(C?.initialState?.query)?C.initialState.query:null,[C]),G=u.useMemo(()=>P(C?.initialState?.route)?C.initialState.route:null,[C]),[V,Y]=u.useState(()=>Va({sources:[],isGuestOnly:!1})),Z=u.useRef(null);u.useEffect(()=>{const Q={...L},ie=C4({actionDispatcher:M.current,locale:p.locale,initialGlobalState:Q,onChange:ge=>{Y(ge.globalState)}});Z.current=ie;const _e=window.__templateApp;return _e?.setGlobalState&&M.current.setGlobalStateUpdater((ge,Ae)=>{_e.setGlobalState(ge,Ae)}),Y(Q),$l({kind:"applyPatch",activeStateId:p.activeStateId,routePath:p.selectedRoute?.path??null,hasInitialPatch:!!C?.initialState,hasFormErrors:!!qa(C),hasSampleOverride:!!xg(C)}),()=>{ie.restore(),Z.current=null}},[p.locale,L]),u.useEffect(()=>{if(!A)return;const Q=window.G7Core;if(!Q||typeof Q.t!="function")return;const ie=Q.t,_e=p.templateIdentifier,ge=p.locale;return Q.t=(Ae,Ne)=>{try{const Le=Ne?"|"+Object.entries(Ne).map(([ae,pe])=>`${ae}=${pe}`).join("|"):void 0,q=A.translate(Ae,{templateId:_e,locale:ge},Le);if(q!==Ae&&!q.startsWith("$t:"))return q}catch{}return ie(Ae,Ne)},typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ga)),()=>{window.G7Core?.t&&window.G7Core.t!==ie&&(window.G7Core.t=ie)}},[A,p.templateIdentifier,p.locale]);const se=u.useMemo(()=>{const Q=g?.raw?.components??[];return p.editMode!=="base"?Q:L4(Q)},[g,p.editMode]),re=g?.raw?.__editability,U=g?.raw?.__extensionId,ee=u.useMemo(()=>p.editMode!=="extension"||re!=="ok"?[]:typeof U!="number"?[]:F4(se,U),[p.editMode,re,U,se]),[fe,K]=u.useState(null),[ne,me]=u.useState(!1),Ce=g?.layoutName??null,ze=u.useMemo(()=>{const Q=g?.raw?.scripts??[];return Array.isArray(Q)?Q.map(ie=>ie&&typeof ie.src=="string"?ie.src:"").join("|"):""},[g]);u.useEffect(()=>{me(!1)},[Ce,ze]),u.useEffect(()=>{let Q=!1;const ie=g?.raw?.scripts??[];if(!Array.isArray(ie)||ie.length===0){me(!0);return}const _e=[];for(const ge of ie){if(!ge?.src||typeof ge.src!="string")continue;const Ae=ge.id?`script#${CSS.escape(ge.id)}, script[data-g7le-canvas-script="${ge.src}"]`:`script[data-g7le-canvas-script="${ge.src}"], script[src="${ge.src}"]`,Ne=window.document.querySelector(Ae);if(Ne){const Le=Ne.hasAttribute("data-g7le-canvas-script");if(Ne.hasAttribute("data-g7le-script-loaded")||!Le)continue;_e.push(new Promise(ae=>{if(Ne.hasAttribute("data-g7le-script-loaded")){ae();return}Ne.addEventListener("load",()=>ae()),Ne.addEventListener("error",()=>ae())}));continue}_e.push(new Promise(Le=>{const q=window.document.createElement("script");q.src=ge.src,q.async=!1,ge.id&&(q.id=ge.id),q.setAttribute("data-g7le-canvas-script",ge.src);const ae=()=>{q.setAttribute("data-g7le-script-loaded","1"),Le()};q.addEventListener("load",ae),q.addEventListener("error",ae),window.document.head.appendChild(q)}))}if(_e.length===0){me(!0);return}return Promise.all(_e).then(()=>{Q||requestAnimationFrame(()=>{requestAnimationFrame(()=>{Q||me(!0)})})}),()=>{Q=!0}},[g]);const Se=u.useMemo(()=>g?.raw?.data_sources??[],[g]),qe=u.useMemo(()=>g?.raw?.computed??{},[g]),[De,Pe]=u.useState({}),Qe=u.useMemo(()=>{if(p.editMode!=="iteration_item")return De;const Q=g?.iterationContext;if(!Q)return De;const ie=g?.raw?.components??[],_e=We({children:ie},Q.sourceIndexPath),ge=_e&&_e.iteration&&typeof _e.iteration.source=="string"?_e.iteration.source:null;return ge?z4(De,ge):De},[p.editMode,De,g]),[Me,Re]=u.useState(0);u.useEffect(()=>{if(typeof window>"u")return;const Q=()=>Re(ie=>ie+1);return window.addEventListener(kt,Q),()=>window.removeEventListener(kt,Q)},[]);const ve=u.useMemo(()=>E4(p.selectedRoute?.path??null),[p.selectedRoute?.path]);if(u.useEffect(()=>{let Q=!1;return(async()=>{if(Se.length===0){Q||Pe({});return}try{const ie=await B.fetchDataSources(Se,ve,new URLSearchParams,void 0,void 0);Q||Pe(ie)}catch{Q||Pe({})}})(),()=>{Q=!0}},[Se,B,ve]),u.useEffect(()=>{const Q=b;if(!Q||typeof window>"u")return;let ie=0,_e=0,ge=0;const Ae=()=>B4(Q,window.innerHeight);ie=window.requestAnimationFrame(()=>{_e=window.requestAnimationFrame(Ae)});let Ne=null;return typeof MutationObserver<"u"&&(Ne=new MutationObserver(()=>{ge||(ge=window.requestAnimationFrame(()=>{ge=0,Ae()}))}),Ne.observe(Q,{childList:!0,subtree:!0})),()=>{window.cancelAnimationFrame(ie),window.cancelAnimationFrame(_e),ge&&window.cancelAnimationFrame(ge),Ne&&Ne.disconnect()}},[b,se,ne,k,De]),u.useEffect(()=>{const Q=b;if(!Q||typeof window>"u"||p.editMode!=="extension"||re!=="ok"||ee.length===0){K(null);return}let ie=0,_e=0;const ge=ae=>{if(!ae)return!1;const pe=ae.getBoundingClientRect();return pe.width>0&&pe.height>0},Ae=ae=>{const pe=Q.querySelector(`[data-editor-path="${ae}"]`);if(ge(pe))return!0;const $e=Q.querySelectorAll(`[data-editor-path^="${ae}.children."]`);for(const be of Array.from($e))if(ge(be))return!0;return!1},Ne=()=>{K(ee.some(Ae))};ie=window.requestAnimationFrame(()=>{_e=window.requestAnimationFrame(Ne)});let Le=null,q=0;return typeof MutationObserver<"u"&&(Le=new MutationObserver(()=>{q||(q=window.requestAnimationFrame(()=>{q=0,Ne()}))}),Le.observe(Q,{childList:!0,subtree:!0})),()=>{window.cancelAnimationFrame(ie),window.cancelAnimationFrame(_e),q&&window.cancelAnimationFrame(q),Le&&Le.disconnect()}},[b,p.editMode,re,ee,ne,De]),u.useEffect(()=>{if(typeof window>"u"||p.editMode!=="base")return;const Q=window.document,ie="g7le-base-slot-style";if(Q.getElementById(ie))return;const _e=Q.createElement("style");_e.id=ie;const ge=T("layout_editor.preview.slot_area_label");return _e.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:'${ge.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;}`,Q.head.appendChild(_e),()=>{Q.getElementById(ie)?.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:Zo,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:Zo,children:T("layout_editor.preview.loading")});if(h)return i.jsx(Fa,{error:h});if(D)return i.jsx(Fa,{error:D});if(!z||$===null||A===null)return i.jsx("div",{className:"g7le-preview-canvas g7le-preview-canvas--assets-loading","data-testid":"g7le-preview-assets-loading",style:Zo,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:Zo,children:T("layout_editor.preview.empty_layout")});const he=p.editMode==="extension"?re==="no-injection"?"no-injection":re==="ok"&&ee.length>0&&fe!==!0?"gated-no-state":null:null;return ne?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:k,transform:`scale(${w})`,transformOrigin:"top center"},children:[i.jsx("div",{className:_==="dark"?"g7le-preview-frame g7le-preview-dark":"g7le-preview-frame","data-testid":"g7le-preview-frame","data-color-scheme":_,ref:Q=>{v.current=Q,x(Q)},style:{width:k,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(KE,{overrideWidth:k,children:se.map((Q,ie)=>i.jsx(FE,{componentDef:Q,dataContext:{...Qe,...T4(V),_global:D4(V),_computedDefinitions:qe,...I?{_localInit:I,_local:{...De._local??{},...V._local??{}}}:{},route:K4({...De.route??{},...ve,path:p.selectedRoute?.path??""},G),query:{...De.query??{},...F??{}}},translationContext:{templateId:p.templateIdentifier,locale:p.locale},registry:$,bindingEngine:O.current,translationEngine:Pt.getInstance(),actionDispatcher:M.current,isEditMode:!0,isRootRenderer:ie===0,componentPath:`${ie}`,onComponentSelect:(_e,ge)=>{},onComponentHover:(_e,ge)=>{}},`${Q.id??`preview-${ie}`}:t${Me}${p.editMode==="extension"?`:s${ne?1:0}`:""}`))})}),i.jsx("div",{className:"g7le-overlay-layer","data-testid":"g7le-overlay-layer",style:{position:"absolute",left:0,top:0,width:k,height:b?b.getBoundingClientRect().height/(w||1):"100%",overflow:"visible",pointerEvents:"none"},children:i.jsx(p4,{frameEl:b,manifest:t,nesting:n,componentPalette:o,spec:r,permissionCandidates:s,resolveRouteMatch:l,onNavigateToDestination:d,onSessionAddedPathsChange:c})}),he!==null&&i.jsx("div",{className:"g7le-preview-canvas--extension-fallback","data-testid":"g7le-preview-extension-fallback","data-fallback-reason":he,style:{position:"absolute",left:0,top:0,right:0,bottom:0,minHeight:b?b.getBoundingClientRect().height/(w||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(he==="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:he==="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:Zo,children:T("layout_editor.preview.loading")})}function H4(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 F4(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 K4(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 Zo={flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"#f1f5f9",color:"#64748b",fontSize:13},V4={desktop:"layout_editor.device.desktop",tablet:"layout_editor.device.tablet",mobile:"layout_editor.device.mobile",portable:"layout_editor.device.portable"};function U4(){const{device:e,zoom:t,customWidth:n,setDevice:o,setZoom:r,setCustomWidth:s,colorScheme:a,setColorScheme:l}=ja(),{t:d}=tt(),c=Gf();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,y=V4[p],g=y?d(y):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:ug,max:pg,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(Kb,{})]})}function q4(){const{t:e}=tt(),{state:t,dispatch:n}=Je(),{availableStates:o,activeStateId:r}=t,[,s]=u.useState(0);u.useEffect(()=>{if(typeof window>"u")return;const p=()=>s(y=>y+1),f=window.requestAnimationFrame(p);return window.addEventListener(Ga,p),()=>{window.cancelAnimationFrame(f),window.removeEventListener(Ga,p)}},[]);const a=u.useCallback((p,f)=>{if(!p)return f;if(!p.startsWith("$t:"))return p;const y=p.slice(3),g=window.G7Core;if(g&&typeof g.t=="function"){const h=g.t(y);if(h&&h!==y&&!h.startsWith("$t:"))return h}const m=e(y);return m&&m!==y?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}),$l({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 G4(e,t,n){if(e==="extension"){if(typeof n=="string"&&n.length>0){const o=Ya(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=Ya(t,"__base__/");return o?{kind:"base",match:o}:null}case"modal":{const o=Ya(t,"__modal__/");return o?{kind:"modal",match:o}:null}default:return null}}function Y4(e,t){if(!t||!Array.isArray(e)||e.length===0)return[];const n=[];for(const o of e)if(J4(o.scope,t))for(const r of o.items??[])r&&typeof r.id=="string"&&r.id.length>0&&n.push(r);return n}function X4(e){if(e.length===0)return null;const t=e.find(n=>n.default===!0);return t?t.id:e[0].id}function J4(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"?Z4(t.match,n):n===t.match}function Z4(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 Ya(e,t){return e.startsWith(t)?e.slice(t.length):""}const Q4="__conngroup__/modals/",R4="__conngroup__/extensions/";function eD(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 tD(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 nD(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 oD(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 rD(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 iD(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 sD(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 aD(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 kg(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:`${Q4}${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=>sD(a,e.path))});const s=n.get(e.layoutName)??[];s.length>0&&o.push({path:`${R4}${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=>aD(a,e.path))}),o.length>0&&(e.children=[...o,...e.children??[]])}function lD(e){const t=[],n=new Set(e.routes.map(o=>o.path));for(const o of e.routes){const r=tD(o);if(!r)continue;const{label:s,labelSource:a}=eD(o),l=nD(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 dD(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 cD(e,t){oD(e.routes);const n=rD(e.modals),o=iD(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),y=p(c);return f!==y?f-y: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)kg(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 y of c)p.set(y.node.path,y);const f=[];for(const y of c)if(y.parentKey&&p.has(y.parentKey)){const g=p.get(y.parentKey);g.node.children=g.node.children??[],g.node.children.push(y.node)}else f.push(y.node);for(const y of c)kg(y.node,n,o);a.push({path:`__group__/${d}`,layoutName:null,label:dD(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(y=>({path:`__extension__/${y.id}`,layoutName:null,label:`${c.sourceLabel} · ${y.targetName}`,labelSource:"path",source:{kind:c.sourceType,identifier:c.sourceIdentifier},kind:"extension",extensionId:String(y.id),extensionType:y.extensionType,extensionPriority:y.priority,extensionTargetName:y.targetName,isModified:y.isModified,isInactive:!y.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 uD(e){const t=lD(e);return cD(e,t)}const On=bo("useEditorRoutes");function pD(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 Sg(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]=pD(s.display_name,t)??s.identifier);return n}function fD(e){const t=new vd,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 gD(e){const{dispatch:t}=Je(),{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(),y=(()=>{if(typeof fetch!="function")return Promise.reject(io(new Error("fetch unavailable"),"routes"));try{const h=fetch(c,{credentials:"same-origin",headers:je()});return!h||typeof h.then!="function"?Promise.reject(io(new Error("fetch returned non-Promise (test stub?)"),"routes")):h.then(async v=>{if(!v.ok){const b=await v.json().catch(()=>null);throw Gr(v.status,b,"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:je()});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([y,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 b=fD(h.data.routes),x=Sg("activeModules",p),k=Sg("activePlugins",p),w=(h.data.base_layouts??[]).map(A=>({layoutName:A.layout_name,label:A.label??void 0})),_=(h.data.modals??[]).map(A=>({modalId:A.modal_id,hostLayout:A.host_layout,label:A.label??void 0})),C=(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(z=>({id:z.id,extensionType:z.extension_type,targetName:z.target_name,priority:z.priority,isActive:z.is_active,isModified:z.is_modified,hostLayouts:Array.isArray(z.host_layouts)?z.host_layouts:[],currentVersion:typeof z.current_version=="number"?z.current_version:void 0}))})),E=uD({routes:b,modals:_,baseLayouts:w,extensionGroups:C,moduleDisplayNames:x,pluginDisplayNames:k});t({type:"SET_ROUTE_TREE",tree:E});const S=h.data.layout_versions,T={};if(S&&typeof S=="object"&&!Array.isArray(S))for(const[A,z]of Object.entries(S))typeof z=="number"&&Number.isFinite(z)&&(T[A]=z);t({type:"SET_LAYOUT_VERSIONS",versions:T});const $={};for(const A of C)for(const z of A.extensions){const D=z.currentVersion;typeof D=="number"&&Number.isFinite(D)&&($[String(z.id)]=D)}t({type:"SET_EXTENSION_VERSIONS",versions:$}),On.log("routes 로드 완료",{count:b.length,groups:E.length})}).catch(h=>{if(a)return;On.error("routes 로드 실패",h);const v=hp(h)?h:io(h,"routes");t({type:"SET_ROUTES_ERROR",error:v})}),()=>{a=!0}},[r,s,t,n,o?.locale,o?.templateId])}function Cg(e,t,n,o=[]){const r=t?$g(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 $g(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=$g(n.children,t);if(o)return o}}return null}function Xa(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=Xa(n.children,t);if(o)return o}}return null}function hD(e){const{state:t,dispatch:n}=Je(),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=ap(window.location.search);if(a){const c=sp(window.location.search),p=Cg(a,c,n,t.routeTree);if(o.current=!0,p)return}const l=ip(window.location.search);if(!l){o.current=!0;return}const d=Xa(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=ap(window.location.search);if(l){const p=sp(window.location.search);if(Cg(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=ip(window.location.search);if(!d){n({type:"SELECT_ROUTE",route:null});return}const c=Xa(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=Zs(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 yD(){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 bD(){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 mD(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 vD(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 _D(e,t){if(Array.isArray(e.components)){const n=t.map(o=>Ja(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&&rJa(n))),t}function Eg(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 Ig(e,t){const o=Eg(e,t)[0]?.__source;return o&&o.kind==="extension"&&o.extensionId===t?o:{kind:"extension",extensionId:t}}function Za(e,t){for(const n of e){const o=n?.__source;if(o?.kind==="extension"&&o.extensionId===t||Array.isArray(n.children)&&Za(n.children,t))return!0}return!1}function xD(){const{state:e}=Je(),t=e.templateIdentifier,n=e.editMode==="extension"?mD(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),[y,g]=u.useState(0),[m,h]=u.useState(null),v=u.useRef({}),b=u.useRef({kind:"extension",extensionId:0}),x=u.useRef(null);u.useEffect(()=>{x.current=r},[r]),u.useEffect(()=>{h(null)},[n]);const k=u.useCallback(async A=>{const z=window.G7Config?.cache_version??0,D=en(`/api/layouts/${encodeURIComponent(t)}/${A}`,"json",`${z}.${Sp()}`,"with_source_meta=1"),O=ar(),M={Accept:"application/json"};O&&(M.Authorization=`Bearer ${O}`);const B=await fetch(D,{headers:M,credentials:"same-origin"});if(!B.ok)return null;const N=await B.json().catch(()=>null);return(N&&(N.data||N))??{}},[t]),w=u.useCallback(async()=>{if(!n){s(null),c(null),f(!1);return}l(!0),c(null);try{const A=window.G7Config?.cache_version??0,z=`/api/admin/templates/${encodeURIComponent(t)}/layout-extensions/${encodeURIComponent(n)}?v=${A}`,D=await fetch(z,{headers:je(),credentials:"same-origin"}),O=await D.json().catch(()=>null);if(!D.ok){c(Gr(D.status,O,"layout")),s(null),f(!1);return}const M=(O&&(O.data||O))??{};let B={};const N=M.content;if(typeof N=="string")try{B=JSON.parse(N)}catch{B={}}else N&&typeof N=="object"&&(B=N);const H=M.extension_type==="overlay"?"overlay":"extension_point",L=typeof M.lock_version=="number"?M.lock_version:0,I=Array.isArray(M?.host_layouts)?M.host_layouts.filter(re=>typeof re=="string"):[],P=o??(I.length===1?I[0]:m&&I.includes(m)?m:null),F=Number(n);v.current=B;let V=vD(B),Y={},Z="pending";const se={kind:"extension",extensionId:F};if(b.current=se,P){const re=await k(P);if(re){Y=re;const U=Array.isArray(re.components)?re.components:[],ee=Ig(U,F);if(b.current=ee,Za(U,F))V=U,Z="ok";else{const K=(Array.isArray(re.modals)?re.modals:[]).filter(ne=>ne&&typeof ne=="object"&&Za([ne],F));if(K.length>0){const ne=K.map(me=>({...me,props:{...me.props??{},isOpen:!0}}));V=[...U,...ne],b.current=Ig(K,F),Z="ok"}else V=U,Z="no-injection"}}}s({extensionId:F,content:B,extensionType:H,components:V,lockVersion:L,hostLayouts:I,hostLayoutName:P,hostRaw:Y,editability:Z}),f(!1),st({op:"load",layoutName:`extension:${n}`,editMode:"extension",statusCode:D.status,timestamp:Date.now()})}catch(A){c(io(A,"layout")),s(null),f(!1)}finally{l(!1)}},[t,n,m,o,k]);u.useEffect(()=>{w()},[w]);const _=u.useCallback(A=>{h(A)},[]),C=u.useCallback(A=>{s(z=>z&&{...z,components:A}),f(!0),st({op:"patch",layoutName:`extension:${x.current?.extensionId??""}`,editMode:"extension",isDirty:!0,timestamp:Date.now()})},[]),E=u.useCallback(A=>{s(z=>z&&{...z,components:A(z.components)}),f(!0)},[]),S=u.useCallback(async()=>{const A=x.current;if(!A)return{kind:"guard_no_document"};const z=`/api/admin/templates/${encodeURIComponent(t)}/layout-extensions/${A.extensionId}`,D=Eg(A.components,A.extensionId),O=D.length>0?D:A.components,M=_D(v.current,O);st({op:"save",layoutName:`extension:${A.extensionId}`,editMode:"extension",saveTarget:"layout_extension",endpoint:z,isDirty:p,timestamp:Date.now()});let B;try{B=await fetch(z,{method:"PUT",headers:je({"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 N=await B.json().catch(()=>null);if(st({op:"save_response",layoutName:`extension:${A.extensionId}`,editMode:"extension",endpoint:z,statusCode:B.status,conflict:B.status===409?{currentVersion:N?.errors?.current_version??N?.current_version,yourVersion:N?.errors?.your_version??N?.your_version}:void 0,timestamp:Date.now()}),B.ok){const H=N?.data??{},L=typeof H.lock_version=="number"?H.lock_version:A.lockVersion+1;s(P=>P&&{...P,lockVersion:L}),f(!1),g(P=>P+1);const I=typeof H.current_version=="number"?H.current_version:void 0;return{kind:"success",newLockVersion:L,newContentVersion:I,savedExtensionId:String(A.extensionId)}}return B.status===409?{kind:"concurrent_modification",currentVersion:N?.current_version??-1,yourVersion:N?.your_version??A.lockVersion}:B.status===422?{kind:"validation_failed",status:422,errors:N?.errors??null}:{kind:"network_error",message:N?.message??`HTTP ${B.status}`}},[t,p]),T=u.useCallback(async()=>{na(),await w()},[w]),$=!!r&&r.hostLayouts.length>1&&r.hostLayoutName===null;return{document:r,isLoading:a,error:d,isDirty:p,saveSuccessCounter:y,setLayoutComponents:C,patchLayout:E,save:S,reload:T,needsHostPicker:$,selectHost:_}}const Ag=new Set;function wD(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 kD(e){return{document:e.document?{layoutName:`extension:${e.document.extensionId}`,raw:{...wD(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:Ag,dirtyLayoutNames:Ag,invalidateCurrentCache:()=>{},reloadCounter:0,save:()=>e.save(),markDirty:()=>{}}}function SD({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 CD(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=vo(l),c=`/api/admin/templates/${encodeURIComponent(e)}/layouts/${t}/preview`,p=await fetch(c,{method:"POST",credentials:"same-origin",headers:je({"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 y=f?.data,g=typeof y?.token=="string"?y.token:"",m=typeof y?.preview_url=="string"&&y.preview_url?y.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 ce="layout_editor.action_recipe",bn={setState:{label:`$t:${ce}.set_state.label`,params:[{key:"target",label:`$t:${ce}.set_state.param_target`,widget:"select",options:[{value:"local"},{value:"global"}]},{key:"state",label:`$t:${ce}.set_state.param_state`,widget:"state-key-value"},{key:"merge",label:`$t:${ce}.set_state.param_merge`,widget:"toggle"}],build:{handler:"setState",params:{target:"{{target}}",merge:"{{merge}}","...":"{{state}}"}}},loadFromLocalStorage:{label:`$t:${ce}.load_local.label`,params:[{key:"key",label:`$t:${ce}.load_local.param_key`,widget:"text",required:!0},{key:"stateKey",label:`$t:${ce}.load_local.param_state_key`,widget:"state-key-picker"},{key:"defaultValue",label:`$t:${ce}.load_local.param_default`,widget:"text"}],build:{handler:"loadFromLocalStorage",params:{key:"{{key}}",stateKey:"{{stateKey}}",defaultValue:"{{defaultValue}}"}}},saveToLocalStorage:{label:`$t:${ce}.save_local.label`,params:[{key:"key",label:`$t:${ce}.save_local.param_key`,widget:"text",required:!0},{key:"value",label:`$t:${ce}.save_local.param_value`,widget:"data-chip"}],build:{handler:"saveToLocalStorage",params:{key:"{{key}}",value:"{{value}}"}}},navigate:{label:`$t:${ce}.navigate.label`,params:[{key:"path",label:`$t:${ce}.navigate.param_path`,widget:"page-picker",required:!0},{key:"query",label:`$t:${ce}.navigate.param_query`,widget:"key-value"},{key:"mergeQuery",label:`$t:${ce}.navigate.param_merge_query`,widget:"toggle"},{key:"scroll",label:`$t:${ce}.navigate.param_scroll`,widget:"select",options:[{value:"top"},{value:"preserve"},{value:"none"}]},{key:"replace",label:`$t:${ce}.navigate.param_replace`,widget:"toggle"},{key:"transition_overlay_target",label:`$t:${ce}.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:${ce}.open_window.label`,params:[{key:"target",label:`$t:${ce}.open_window.param_target`,widget:"page-picker",required:!0},{key:"windowTarget",label:`$t:${ce}.open_window.param_window_target`,widget:"select",options:[{value:"_blank"},{value:"_self"}]}],build:{handler:"openWindow",target:"{{target}}",params:{windowTarget:"{{windowTarget}}"}}},navigateBack:{label:`$t:${ce}.navigate_back.label`,params:[],build:{handler:"navigateBack"}},navigateForward:{label:`$t:${ce}.navigate_forward.label`,params:[],build:{handler:"navigateForward"}},replaceUrl:{label:`$t:${ce}.replace_url.label`,params:[{key:"path",label:`$t:${ce}.replace_url.param_path`,widget:"page-picker"},{key:"query",label:`$t:${ce}.replace_url.param_query`,widget:"key-value"}],build:{handler:"replaceUrl",params:{path:"{{path}}",query:"{{query}}"}}},toast:{label:`$t:${ce}.toast.label`,params:[{key:"message",label:`$t:${ce}.toast.param_message`,widget:"i18n-text",required:!0},{key:"type",label:`$t:${ce}.toast.param_type`,widget:"select",options:[{value:"info"},{value:"success"},{value:"warning"},{value:"error"}]},{key:"duration",label:`$t:${ce}.toast.param_duration`,widget:"number"},{key:"icon",label:`$t:${ce}.toast.param_icon`,widget:"text"}],build:{handler:"toast",params:{message:"{{message}}",type:"{{type}}",duration:"{{duration}}",icon:"{{icon}}"}}},openModal:{label:`$t:${ce}.open_modal.label`,params:[{key:"target",label:`$t:${ce}.open_modal.param_target`,widget:"modal-picker",required:!0}],build:{handler:"openModal",target:"{{target}}"}},closeModal:{label:`$t:${ce}.close_modal.label`,params:[],build:{handler:"closeModal"}},showAlert:{label:`$t:${ce}.show_alert.label`,params:[{key:"target",label:`$t:${ce}.show_alert.param_message`,widget:"i18n-text",required:!0}],build:{handler:"showAlert",target:"{{target}}"}},setError:{label:`$t:${ce}.set_error.label`,params:[{key:"target",label:`$t:${ce}.set_error.param_message`,widget:"i18n-text"},{key:"stateTarget",label:`$t:${ce}.set_error.param_state_target`,widget:"select",options:[{value:"local"},{value:"global"}]}],build:{handler:"setError",target:"{{target}}",params:{stateTarget:"{{stateTarget}}"}}},refetchDataSource:{label:`$t:${ce}.refetch.label`,params:[{key:"dataSourceId",label:`$t:${ce}.refetch.param_data_source`,widget:"datasource-picker",required:!0},{key:"sync",label:`$t:${ce}.refetch.param_sync`,widget:"toggle"}],build:{handler:"refetchDataSource",params:{dataSourceId:"{{dataSourceId}}",sync:"{{sync}}"}}},appendDataSource:{label:`$t:${ce}.append_data.label`,params:[{key:"dataSourceId",label:`$t:${ce}.append_data.param_data_source`,widget:"datasource-picker",required:!0},{key:"dataPath",label:`$t:${ce}.append_data.param_data_path`,widget:"text"},{key:"newData",label:`$t:${ce}.append_data.param_new_data`,widget:"data-chip"}],build:{handler:"appendDataSource",params:{dataSourceId:"{{dataSourceId}}",dataPath:"{{dataPath}}",newData:"{{newData}}"}}},updateDataSource:{label:`$t:${ce}.update_data.label`,params:[{key:"dataSourceId",label:`$t:${ce}.update_data.param_data_source`,widget:"datasource-picker",required:!0},{key:"data",label:`$t:${ce}.update_data.param_data`,widget:"data-chip"},{key:"merge",label:`$t:${ce}.update_data.param_merge`,widget:"toggle"}],build:{handler:"updateDataSource",params:{dataSourceId:"{{dataSourceId}}",data:"{{data}}",merge:"{{merge}}"}}},scrollIntoView:{label:`$t:${ce}.scroll.label`,params:[{key:"selector",label:`$t:${ce}.scroll.param_selector`,widget:"text",required:!0},{key:"behavior",label:`$t:${ce}.scroll.param_behavior`,widget:"select",options:[{value:"smooth"},{value:"auto"}]},{key:"block",label:`$t:${ce}.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:${ce}.login.label`,params:[{key:"body",label:`$t:${ce}.login.param_body`,widget:"key-value"}],build:{handler:"login",params:{body:"{{body}}"}}},logout:{label:`$t:${ce}.logout.label`,params:[{key:"target",label:`$t:${ce}.logout.param_target`,widget:"text"}],build:{handler:"logout",target:"{{target}}"}},setLocale:{label:`$t:${ce}.set_locale.label`,params:[{key:"target",label:`$t:${ce}.set_locale.param_target`,widget:"locale-picker",required:!0}],build:{handler:"setLocale",target:"{{target}}"}},emitEvent:{label:`$t:${ce}.emit_event.label`,params:[{key:"event",label:`$t:${ce}.emit_event.param_event`,widget:"text",required:!0},{key:"data",label:`$t:${ce}.emit_event.param_data`,widget:"data-chip"}],build:{handler:"emitEvent",params:{event:"{{event}}",data:"{{data}}"}}},apiCall:{label:`$t:${ce}.api_call.label`,params:[{key:"target",label:`$t:${ce}.api_call.param_target`,widget:"page-picker",required:!0},{key:"method",label:`$t:${ce}.api_call.param_method`,widget:"select",options:[{value:"GET"},{value:"POST"},{value:"PUT"},{value:"PATCH"},{value:"DELETE"}]},{key:"body",label:`$t:${ce}.api_call.param_body`,widget:"key-value"},{key:"query",label:`$t:${ce}.api_call.param_query`,widget:"key-value"},{key:"identity_target_email",label:`$t:${ce}.api_call.param_identity_target_email`,widget:"data-chip"},{key:"identity_target_phone",label:`$t:${ce}.api_call.param_identity_target_phone`,widget:"data-chip"},{key:"onSuccess",label:`$t:${ce}.api_call.param_on_success`,widget:"action-list"},{key:"onError",label:`$t:${ce}.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:${ce}.conditions.label`,params:[{key:"branches",label:`$t:${ce}.conditions.param_branches`,widget:"branch-list"}],build:{handler:"conditions",conditions:"{{branches}}"}},sequence:{label:`$t:${ce}.sequence.label`,params:[{key:"actions",label:`$t:${ce}.sequence.param_actions`,widget:"action-list"}],build:{handler:"sequence",params:{actions:"{{actions}}"}}},parallel:{label:`$t:${ce}.parallel.label`,params:[{key:"actions",label:`$t:${ce}.parallel.param_actions`,widget:"action-list"}],build:{handler:"parallel",params:{actions:"{{actions}}"}}},switch:{label:`$t:${ce}.switch.label`,params:[{key:"value",label:`$t:${ce}.switch.param_value`,widget:"data-chip"},{key:"cases",label:`$t:${ce}.switch.param_cases`,widget:"action-list",advanced:!0}],build:{handler:"switch",params:{value:"{{value}}",cases:"{{cases}}"}}},suppress:{label:`$t:${ce}.suppress.label`,params:[],build:{handler:"suppress"}}};function $D(){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:${ce}.show_error_page.label`,params:[{key:"target",label:`$t:${ce}.show_error_page.param_target`,widget:"select",options:[{value:"content"},{value:"full"}]}],build:{handler:"showErrorPage",params:{target:"{{target}}"}}}}}}function Qa(e,t){return typeof e.label=="string"?e.label.startsWith("$t:")?t(e.label.slice(3)):e.label:String(e.value)}function vi(e){return Array.isArray(e.options)?e.options:[]}function ED({control:e,value:t,onChange:n,t:o}){const r=vi(e);return i.jsx("div",{className:"g7le-widget g7le-widget--segmented","data-testid":"g7le-widget-segmented",style:WD,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:{...GD,background:a?"#2563eb":"#fff",color:a?"#fff":"#0f172a",borderColor:a?"#2563eb":"#cbd5e1"},children:Qa(s,o)},String(s.value))})})}function ID({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:Dg,children:[i.jsxs("label",{style:Ra,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 AD({control:e,value:t,onChange:n,t:o}){const r=vi(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:YD,children:[i.jsx("option",{value:"",children:o("layout_editor.control.default")}),r.map(s=>i.jsx("option",{value:String(s.value),children:Qa(s,o)},String(s.value)))]})}function TD({control:e,value:t,onChange:n}){const o=vi(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:{...XD,background:a?"#2563eb":"#cbd5e1"},children:i.jsx("span",{style:{...JD,transform:a?"translateX(18px)":"translateX(0)"}})})}function DD({control:e,value:t,onChange:n,t:o,freeValueDisabled:r}){const s=vi(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:jD,children:[r?i.jsx("div",{"data-testid":"g7le-dimension-free-disabled",style:UD,children:o("layout_editor.property_modal.dark_preset_only")}):i.jsxs("div",{style:HD,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:FD}),i.jsx("button",{type:"button","data-testid":"g7le-dimension-clear",title:o("layout_editor.control.default"),onClick:()=>{d(""),n(void 0)},style:KD,children:o("layout_editor.control.default")})]}),s.length>0&&i.jsx("div",{style:VD,"data-testid":"g7le-dimension-chips",children:s.map(p=>{const f=String(p.value),y=f===a;return i.jsx("button",{type:"button","data-testid":`g7le-dimension-chip-${f}`,"data-active":y?"true":"false",onClick:()=>{d(f),n(f)},style:{...qD,background:y?"#2563eb":"#fff",color:y?"#fff":"#0f172a",borderColor:y?"#2563eb":"#cbd5e1"},children:Qa(p,o)},f)})})]})}function ND(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 zD(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 MD({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(b=>String(b)),a=ND(r),l=zD(t,r,a,s),d=Object.values(l.sides).some(b=>b>=0),c=l.all>=0||d,[p,f]=u.useState(d);u.useEffect(()=>{d&&f(!0)},[d]);const y=Math.min(4,Math.max(0,s.length-1)),g=b=>{const x=[];for(const k of a){const w=b[k.key];w!==void 0&&w>=0&&x.push(`${k.infix}${s[w]}`)}n(x.length>0?x.join(" "):void 0)},m=b=>{n(b>=0?`${r}-${s[Math.max(0,Math.min(b,s.length-1))]}`:void 0)},h=()=>({...l.sides}),v=(b,x,k,w,_)=>{const C=k>=0;return i.jsxs("div",{style:BD,"data-testid":b,children:[i.jsxs("label",{style:{...Ra,minWidth:64},children:[i.jsx("input",{type:"checkbox","data-testid":`${b}-enabled`,checked:C,onChange:E=>_(E.target.checked)}),i.jsx("span",{style:{fontSize:12,color:"#0f172a"},children:o(x)})]}),i.jsx("input",{type:"range","data-testid":`${b}-range`,min:0,max:Math.max(0,s.length-1),step:1,disabled:!C||s.length===0,value:k<0?0:k,onChange:E=>w(Number(E.target.value)),style:{flex:1}}),i.jsx("span",{"data-testid":`${b}-value`,style:{fontSize:12,color:C?"#0f172a":"#94a3b8",minWidth:28,textAlign:"right"},children:C?s[k]:"–"})]},b)};return i.jsxs("div",{className:"g7le-widget g7le-widget--spacing","data-testid":"g7le-widget-spacing",style:LD,children:[i.jsxs("div",{style:PD,children:[i.jsxs("div",{style:OD,"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:{...Tg,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 b={};for(const x of a)b[x.key]=l.all;g(b)}},style:{...Tg,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(b=>v(`g7le-spacing-side-${b.key}`,b.labelKey,l.sides[b.key]??-1,x=>{const k=h();k[b.key]=x,g(k)},x=>{const k=h();x?k[b.key]=l.sides[b.key]>=0?l.sides[b.key]:y:delete k[b.key],g(k)}))}):i.jsxs("div",{style:Dg,children:[i.jsxs("label",{style:{...Ra,minWidth:64},children:[i.jsx("input",{type:"checkbox","data-testid":"g7le-spacing-all-enabled",checked:l.all>=0,onChange:b=>m(b.target.checked?y:-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:b=>m(Number(b.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 LD={display:"flex",flexDirection:"column",gap:6,width:"100%"},PD={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},OD={display:"inline-flex",gap:0,border:"1px solid #cbd5e1",borderRadius:6,overflow:"hidden"},Tg={padding:"3px 10px",fontSize:11,border:"none",borderRight:"1px solid #e2e8f0",cursor:"pointer"},BD={display:"flex",alignItems:"center",gap:8,width:"100%"},WD={display:"inline-flex",gap:0,border:"1px solid #cbd5e1",borderRadius:6,overflow:"hidden"},jD={display:"flex",flexDirection:"column",gap:6,width:"100%"},HD={display:"flex",gap:6,alignItems:"center"},FD={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:80},KD={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer",whiteSpace:"nowrap"},VD={display:"flex",flexWrap:"wrap",gap:4},UD={fontSize:11,color:"#94a3b8",fontStyle:"italic",padding:"2px 0"},qD={padding:"3px 9px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:999,background:"#fff",cursor:"pointer"},GD={padding:"4px 10px",fontSize:12,border:"none",borderRight:"1px solid #e2e8f0",cursor:"pointer"},Dg={display:"flex",alignItems:"center",gap:8,width:"100%"},Ra={display:"inline-flex",alignItems:"center",gap:4},YD={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",minWidth:120},XD={position:"relative",width:38,height:20,borderRadius:10,border:"none",cursor:"pointer",padding:2,display:"inline-flex",alignItems:"center",transition:"background 120ms ease"},JD={display:"block",width:16,height:16,borderRadius:8,background:"#fff",transition:"transform 120ms ease"},ZD=["#0f172a","#334155","#64748b","#94a3b8","#e2e8f0","#ffffff","#dc2626","#ea580c","#d97706","#16a34a","#0891b2","#2563eb","#7c3aed","#db2777"],Ng=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function QD(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 RD({control:e,value:t,onChange:n,t:o,freeValueDisabled:r}){const s=QD(e),a=s.length>0,l=typeof t=="string"&&s.some(g=>g.value===t)?t:"",d=typeof t=="string"&&Ng.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}`;Ng.test(h)&&n(h)},y=ZD;return i.jsxs("div",{className:"g7le-widget g7le-widget--color","data-testid":"g7le-widget-color",style:eN,children:[r?i.jsx("div",{"data-testid":"g7le-color-free-disabled",style:sN,children:o("layout_editor.property_modal.dark_preset_only")}):i.jsxs("div",{style:tN,children:[i.jsxs("label",{style:nN,children:[i.jsx("span",{"data-testid":"g7le-color-swatch",style:{...oN,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:rN}),i.jsx("button",{type:"button","data-testid":"g7le-color-clear",onClick:()=>n(void 0),style:iN,children:o("layout_editor.control.default")})]}),a?i.jsx("div",{style:zg,"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:{...Mg,background:g.swatch||"#e2e8f0",outline:m?"2px solid #2563eb":"none"}},g.value)})}):!r&&i.jsx("div",{style:zg,"data-testid":"g7le-color-presets",children:y.map(g=>i.jsx("button",{type:"button","aria-label":g,"data-testid":`g7le-color-preset-${g}`,onClick:()=>n(g),style:{...Mg,background:g,outline:d.toLowerCase()===g.toLowerCase()?"2px solid #2563eb":"none"}},g))})]})}const eN={display:"flex",flexDirection:"column",gap:8},tN={display:"flex",alignItems:"center",gap:6},nN={position:"relative",display:"inline-flex",cursor:"pointer"},oN={width:24,height:24,borderRadius:4,border:"1px solid #cbd5e1",display:"inline-block"},rN={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,fontFamily:"monospace"},iN={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",cursor:"pointer",color:"#64748b"},zg={display:"grid",gridTemplateColumns:"repeat(7, 1fr)",gap:4},Mg={width:"100%",height:18,borderRadius:4,border:"1px solid #cbd5e1",cursor:"pointer",padding:0},sN={fontSize:11,color:"#94a3b8",fontStyle:"italic",padding:"2px 0"},Qo=[{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 aN(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Lg(e){return Qo.find(n=>n.size===e.size&&n.repeat===e.repeat)?.value??"fill"}function lN({value:e,onChange:t,t:n}){const o=aN(e),{state:r}=Je(),s=yo(),[a,l]=u.useState(!1),[d,c]=u.useState(null),[p,f]=u.useState(o.url??""),[y,g]=u.useState([]),m=u.useRef(null),h=r.templateIdentifier,v=r.selectedRoute?.layoutName??"";u.useEffect(()=>{f(o.url??"")},[o.url]);const b=u.useCallback(async()=>{if(!h||!v){g([]);return}const E=await Dl(h,v);E.ok&&g(E.data)},[h,v]);u.useEffect(()=>{b()},[b]);const x=E=>{if(!E){t(void 0);return}const S=Qo.find(T=>T.value===Lg(o))??Qo[0];t({url:E,size:o.size??S.size,repeat:o.repeat??S.repeat,position:o.position??"center"})},k=E=>{const S=Qo.find(T=>T.value===E);!S||!o.url||t({url:o.url,size:S.size,repeat:S.repeat,position:o.position??"center"})},w=async E=>{const S=E.target.files?.[0];if(!S)return;l(!0),c(null);const T=await Nl(h,v,S);T.ok?(x(T.data.url),b()):c(n("layout_editor.control.background_image.upload_failed")),l(!1),m.current&&(m.current.value="")},_=async E=>{(await zl(E.id)).ok&&g(T=>T.filter($=>$.id!==E.id))},C=()=>{const E=s.open({ariaLabel:n("layout_editor.attachment_manager.title"),width:720,maxHeightRatio:.82,content:u.createElement(Ml,{templateIdentifier:h,layoutName:v,t:n,onSelect:S=>{x(S),s.close(E)},onChanged:()=>{b()},onClose:()=>s.close(E)})})};return i.jsxs("div",{className:"g7le-widget g7le-widget--image","data-testid":"g7le-widget-image",style:dN,children:[o.url&&i.jsx("div",{"data-testid":"g7le-image-preview",style:{...cN,backgroundImage:`url(${o.url})`,backgroundSize:o.size??"cover",backgroundRepeat:o.repeat??"no-repeat",backgroundPosition:o.position??"center"}}),i.jsxs("div",{style:uN,children:[i.jsxs("label",{style:pN,children:[a?"…":n("layout_editor.control.background_image.upload"),i.jsx("input",{ref:m,type:"file",accept:"image/*","data-testid":"g7le-image-file",onChange:w,disabled:a,style:{display:"none"}})]}),i.jsx("button",{type:"button","data-testid":"g7le-image-clear",onClick:()=>t(void 0),style:fN,children:n("layout_editor.control.background_image.clear")})]}),i.jsx("input",{type:"text","data-testid":"g7le-image-url",placeholder:"https://… / URL",value:p,onChange:E=>f(E.target.value),onBlur:E=>x(E.target.value.trim()||void 0),style:gN}),i.jsx("div",{style:hN,"data-testid":"g7le-image-modes",children:Qo.map(E=>{const S=Lg(o)===E.value;return i.jsx("button",{type:"button","data-testid":`g7le-image-mode-${E.value}`,"data-active":S?"true":"false",disabled:!o.url,onClick:()=>k(E.value),style:{...yN,background:S&&o.url?"#2563eb":"#fff",color:S&&o.url?"#fff":"#0f172a"},children:n(E.labelKey)},E.value)})}),i.jsxs("div",{style:bN,"data-testid":"g7le-image-gallery",children:[i.jsxs("div",{style:mN,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:C,style:vN,children:["🖼 ",n("layout_editor.attachment_manager.manage_link")]})]}),y.length>0?i.jsx("div",{style:_N,"data-testid":"g7le-image-thumbs",children:y.slice(0,8).map(E=>i.jsxs("div",{style:xN,"data-testid":`g7le-image-thumb-${E.id}`,children:[i.jsx("button",{type:"button",title:E.original_name,onClick:()=>x(E.url),style:{...wN,backgroundImage:`url(${E.url})`},"data-testid":`g7le-image-thumb-use-${E.id}`}),i.jsx("button",{type:"button",title:n("layout_editor.attachment_manager.delete"),onClick:()=>_(E),style:kN,"data-testid":`g7le-image-thumb-del-${E.id}`,children:"✕"})]},E.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 dN={display:"flex",flexDirection:"column",gap:6},cN={width:"100%",height:80,borderRadius:6,border:"1px solid #cbd5e1"},uN={display:"flex",gap:6},pN={padding:"5px 10px",fontSize:12,border:"1px solid #2563eb",borderRadius:6,background:"#fff",color:"#2563eb",cursor:"pointer",display:"inline-flex",alignItems:"center"},fN={padding:"5px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"},gN={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},hN={display:"inline-flex",border:"1px solid #cbd5e1",borderRadius:6,overflow:"hidden"},yN={padding:"4px 10px",fontSize:12,border:"none",borderRight:"1px solid #e2e8f0",cursor:"pointer"},bN={display:"flex",flexDirection:"column",gap:4,border:"1px solid #e2e8f0",borderRadius:6,padding:6,marginTop:2},mN={display:"flex",alignItems:"center",justifyContent:"space-between"},vN={fontSize:11,color:"#2563eb",background:"transparent",border:"none",cursor:"pointer",padding:0},_N={display:"flex",gap:6,flexWrap:"wrap"},xN={position:"relative",width:44,height:44},wN={width:44,height:44,borderRadius:6,border:"1px solid #cbd5e1",backgroundSize:"cover",backgroundPosition:"center",cursor:"pointer",padding:0},kN={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 SN(e){return Array.isArray(e)&&e.every(t=>t!==null&&typeof t=="object"&&!Array.isArray(t))}function CN(e){return typeof e=="string"&&/\{\{.*\}\}/.test(e)}function $N({value:e,onChange:t,t:n,bindingCandidates:o}){if(CN(e))return i.jsx("div",{className:"g7le-widget g7le-widget--options-list","data-testid":"g7le-widget-options-list-bound",style:MN,children:n("layout_editor.list_editor.bound_degraded")});const r=SN(e)?e:[],s=y=>{t(y.length===0?void 0:y)},a=(y,g)=>{const m=r.map((h,v)=>v===y?{...h,...g}:h);s(m)},l=y=>{s(r.filter((g,m)=>m!==y))},d=(y,g)=>{const m=y+g;if(m<0||m>=r.length)return;const h=[...r];[h[y],h[m]]=[h[m],h[y]],s(h)},c=()=>{s([...r,{value:"",label:""}])},p=y=>typeof y.label=="string"?y.label:y.label==null?"":String(y.label),f=y=>y.value===void 0||y.value===null?"":String(y.value);return i.jsxs("div",{className:"g7le-widget g7le-widget--options-list","data-testid":"g7le-widget-options-list",style:EN,children:[r.length===0&&i.jsx("div",{"data-testid":"g7le-options-empty",style:zN,children:n("layout_editor.list_editor.empty")}),r.map((y,g)=>i.jsxs("div",{"data-testid":`g7le-options-row-${g}`,style:IN,children:[i.jsxs("div",{style:Pg,children:[i.jsx("span",{style:Og,children:n("layout_editor.list_editor.option_value")}),i.jsx("input",{type:"text","data-testid":`g7le-options-value-${g}`,value:f(y),placeholder:n("layout_editor.list_editor.option_value"),onChange:m=>a(g,{value:m.target.value}),style:TN})]}),i.jsxs("div",{style:Pg,children:[i.jsx("span",{style:Og,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(vt,{value:p(y),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:AN,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:Bg,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:Bg,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-options-remove-${g}`,title:n("layout_editor.list_editor.remove"),onClick:()=>l(g),style:DN,children:"✕"})]})]},g)),i.jsx("button",{type:"button","data-testid":"g7le-options-add",onClick:c,style:NN,children:n("layout_editor.list_editor.add")})]})}const EN={display:"flex",flexDirection:"column",gap:8,width:"100%"},IN={display:"flex",flexDirection:"column",gap:4,width:"100%",minWidth:0,paddingBottom:6,borderBottom:"1px solid #f1f5f9"},Pg={display:"flex",gap:6,alignItems:"center",width:"100%",minWidth:0},Og={flexShrink:0,width:36,fontSize:11,color:"#94a3b8",textAlign:"right"},AN={display:"flex",gap:4,alignItems:"center",justifyContent:"flex-end"},TN={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},Bg={padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},DN={padding:"2px 6px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},NN={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},zN={fontSize:11,color:"#94a3b8",fontStyle:"italic"},MN={fontSize:11,color:"#b45309",fontStyle:"italic",padding:"4px 2px"},Wg=/[^A-Za-z0-9\-_:.]/g;function LN(e){return typeof e=="string"&&Ui(e)}function jg(e){return Ui(e)?In(e).map(t=>t.kind==="binding"?t.raw:t.raw.replace(Wg,"")).join(""):e.replace(Wg,"")}const PN={width:"100%",padding:"6px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:4,fontFamily:"monospace"},ON={marginTop:4,fontSize:11,color:"#94a3b8"},BN={display:"flex",gap:6,alignItems:"center"},WN={flexShrink:0,padding:"5px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:4,background:"#f8fafc",cursor:"pointer",whiteSpace:"nowrap"};function jN({value:e,onChange:t,t:n,bindingCandidates:o}){const r=e==null?"":String(e),s=LN(e),a=!!o&&o.length>0,[l,d]=u.useState(!1),c=p=>{const f=jg(p);t(f===""?void 0:f)};return s||l?i.jsxs("div",{"data-testid":"g7le-core-id-chip",children:[i.jsx(bs,{value:r,onChange:c,t:n,candidates:o,onDone:()=>d(!1),testidPrefix:"g7le-core-id-chip-input"}),i.jsx("div",{style:ON,children:n("layout_editor.core_props.id.binding_hint")})]}):i.jsx("div",{children:i.jsxs("div",{style:BN,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=jg(p.target.value);t(f===""?void 0:f)},spellCheck:!1,autoComplete:"off",style:PN}),a&&i.jsxs("button",{type:"button","data-testid":"g7le-core-id-add-data",onClick:()=>d(!0),style:WN,title:n("layout_editor.core_props.id.add_data"),children:["🔗 ",n("layout_editor.core_props.id.add_data")]})]})})}const HN=/[^A-Za-z0-9.\-_]/g;function FN(e){return typeof e=="string"&&/\{\{[\s\S]*?\}\}/.test(e)}function KN(e){return e.replace(HN,"")}const Hg={width:"100%",padding:"6px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:4,fontFamily:"monospace",boxSizing:"border-box"},VN={...Hg,background:"#f1f5f9",color:"#64748b",cursor:"not-allowed"},Fg={marginTop:4,fontSize:11,color:"#94a3b8"};function UN({value:e,onChange:t,t:n}){const o=e==null?"":String(e);return FN(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:VN}),i.jsx("div",{style:Fg,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=KN(s.target.value);t(a===""?void 0:a)},spellCheck:!1,autoComplete:"off",style:Hg}),i.jsx("div",{style:Fg,children:n("layout_editor.core_props.dataKey.hint")})]})}let Kg=!1;function qN(){Kg||(Xe("segmented",ED),Xe("slider",ID),Xe("select",AD),Xe("dimension",DD),Xe("spacing",MD),Xe("toggle",TD),Xe("color",RD),Xe("image",lN),Xe("tag-input",ys),Xe("page-picker",Aw),Xe("datasource-picker",Bc),Xe("binding-picker",Bc),Xe("binding-list",Nw),Xe("state-key-picker",Es),Xe("modal-picker",Tw),Xe("i18n-text",Dw),Xe("text",zw),Xe("options-list",$N),Xe("core-id",jN),Xe("core-datakey",UN),Xe("component-target-picker",jT),Kg=!0)}function Ro(e){return Array.isArray(e.children)?e.children:[]}function er(e){if(typeof e.text=="string")return[];let t=null;const n=(o,r)=>{const s=Ro(o);for(let a=0;ad===o?tr(l,r,n):l);return{...e,children:a}}function Vg(e,t){const n=r=>typeof r.props?.[t]=="string";if(n(e))return[];const o=(r,s)=>{const a=Ro(r);for(let l=0;lc===r?Ug(d,s,n,o):d);return{...e,children:l}}function GN(e){return Array.isArray(e.children)?e.children:[]}function YN(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 el(e,t){if(!(typeof e!="string"||e.length===0))return e.startsWith("$t:")?t(e.slice(3)):e}function qg({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=YN(t),f=el(typeof t?.childLabel=="string"?t.childLabel:void 0,r)??d??"",y=GN(e),g=u.useCallback(_=>{s({...e,children:_})},[e,s]),m=u.useCallback(()=>{if(c)return JSON.parse(JSON.stringify(c));if(!d)return null;const _=n?.componentPalette?.entries?.[d];if(_?.defaultNode&&typeof _.defaultNode=="object")return JSON.parse(JSON.stringify(_.defaultNode));const C=o?.components??{};let E=null;for(const S of Object.values(C))if(Array.isArray(S)){const T=S.find($=>$.name===d);if(T){E=T;break}}return E?$f(E):{type:"basic",name:d}},[c,d,n,o]),h=u.useCallback(()=>{const _=m();if(_){if(_.text==="")_.text=r("layout_editor.list_editor.new_item");else{const C=er(_);if(C!==null&&C.length>0){const E=_i(_,C);if(E&&E.text===""){const S=tr(_,C,r("layout_editor.list_editor.new_item"));g([...y,S]);return}}}g([...y,_])}},[m,g,y,r]),v=u.useCallback(_=>{g(y.filter((C,E)=>E!==_))},[g,y]),b=u.useCallback((_,C)=>{const E=_+C;if(E<0||E>=y.length)return;const S=[...y];[S[_],S[E]]=[S[E],S[_]],g(S)},[g,y]),x=u.useCallback((_,C)=>{if(typeof C!="string"||C.length===0)return;const E=y[_];if(!E)return;const S=er(E);if(S===null)return;const T=y.map(($,A)=>A===_?tr($,S,C):$);g(T)},[y,g]),k=u.useCallback((_,C,E)=>{if(typeof E!="string"||E.length===0)return;const S=y[_];if(!S)return;const T=Vg(S,C);if(T===null)return;const $=y.map((A,z)=>z===_?Ug(A,T,C,E):A);g($)},[y,g]);if(!d&&!c)return i.jsx("div",{className:"g7le-node-editor g7le-node-editor--children","data-testid":"g7le-children-editor-misconfigured",style:Xg,children:r("layout_editor.list_editor.no_child_component")});const w=p.length>1||p.some(_=>_.label);return i.jsxs("div",{className:"g7le-node-editor g7le-node-editor--children","data-testid":"g7le-children-editor",style:XN,children:[i.jsx("div",{style:JN,children:r("layout_editor.list_editor.items_title")}),y.length===0&&i.jsx("div",{"data-testid":"g7le-children-empty",style:Xg,children:r("layout_editor.list_editor.empty")}),y.map((_,C)=>{const E=[];for(const T of p)if(T.kind==="text"){const $=er(_),A=$!==null?_i(_,$):null;A&&typeof A.text=="string"&&E.push({key:"text",caption:el(T.label,r)??(w?r("layout_editor.list_editor.item_label"):void 0),value:A.text,onChange:z=>x(C,z),testid:`g7le-children-i18n-${C}`})}else if(T.kind==="prop"&&T.prop){const $=Vg(_,T.prop);if($!==null){const z=_i(_,$)?.props?.[T.prop];E.push({key:`prop-${T.prop}`,caption:el(T.label,r)??T.prop,value:typeof z=="string"?z:"",onChange:D=>k(C,T.prop,D),testid:`g7le-children-prop-${T.prop}-${C}`})}}const S=typeof _?.name=="string"?_.name:r("layout_editor.list_editor.item");return i.jsxs("div",{"data-testid":`g7le-children-row-${C}`,style:ZN,children:[E.length>0?E.map(T=>i.jsx("div",{style:Gg,children:i.jsxs("div",{"data-testid":T.key==="text"?`g7le-children-text-${C}`:`g7le-children-field-${T.key}-${C}`,style:QN,children:[T.caption!==void 0&&i.jsx("div",{"data-testid":`g7le-children-caption-${T.key}-${C}`,style:RN,children:T.caption}),i.jsx(vt,{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:Gg,children:i.jsx("span",{"data-testid":`g7le-children-label-${C}`,style:t8,children:S})}),i.jsxs("div",{style:e8,children:[i.jsx("button",{type:"button","data-testid":`g7le-children-up-${C}`,title:r("layout_editor.list_editor.move_up"),disabled:C===0,onClick:()=>b(C,-1),style:Yg,children:"↑"}),i.jsx("button",{type:"button","data-testid":`g7le-children-down-${C}`,title:r("layout_editor.list_editor.move_down"),disabled:C===y.length-1,onClick:()=>b(C,1),style:Yg,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-children-remove-${C}`,title:r("layout_editor.list_editor.remove"),onClick:()=>v(C),style:n8,children:"✕"})]})]},C)}),i.jsx("button",{type:"button","data-testid":"g7le-children-add",onClick:h,style:o8,children:r("layout_editor.list_editor.add_child",{component:f})})]})}const XN={display:"flex",flexDirection:"column",gap:6,width:"100%",marginBottom:12},JN={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:2},ZN={display:"flex",flexDirection:"column",gap:4,width:"100%",minWidth:0,paddingBottom:6,borderBottom:"1px solid #f1f5f9"},Gg={display:"flex",gap:4,alignItems:"flex-start",width:"100%",minWidth:0},QN={flex:1,minWidth:0},RN={fontSize:11,color:"#64748b",marginBottom:2},e8={display:"flex",gap:4,alignItems:"center",justifyContent:"flex-end"},t8={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,color:"#475569",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},Yg={padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},n8={padding:"2px 6px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},o8={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},Xg={fontSize:11,color:"#94a3b8",fontStyle:"italic"},fo={rowContainer:"Tbody",row:"Tr",cell:"Td",headerCell:"Th",colSpanProp:"colSpan",rowSpanProp:"rowSpan"};function ht(e){return{rowContainer:e?.rowContainer??fo.rowContainer,row:e?.row??fo.row,cell:e?.cell??fo.cell,headerCell:e?.headerCell??fo.headerCell,colSpanProp:e?.colSpanProp??fo.colSpanProp,rowSpanProp:e?.rowSpanProp??fo.rowSpanProp}}function Bn(e){return e?Array.isArray(e.children)?e.children:[]:[]}function Jg(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 Be(e,t){const n=ht(t),o=[],r=Bn(e),s=[];r.forEach((f,y)=>{(Bn(f).some(h=>h.name===n.row)||f.name===n.rowContainer||f.name==="Thead"||f.name==="Tfoot")&&s.push({container:f,containerIndex:y,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,y)=>{Bn(f.container).filter(m=>m.name===n.row).forEach((m,h)=>{const v=[],b=p(d);let x=0;Bn(m).filter(w=>w.name===n.cell||w.name===n.headerCell).forEach((w,_)=>{for(;b[x];)x++;const C=Jg(w,n.colSpanProp),E=Jg(w,n.rowSpanProp),S={cell:w,sectionIndex:y,rowIndexInSection:h,cellIndexInRow:_,gridRow:d,gridCol:x,colSpan:C,rowSpan:E,isHeader:w.name===n.headerCell};v.push(S);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 wi(e,t,n){const o=Zg(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 ki(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 nr(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 yt(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 Si(e,t,n){let o=-1;const r=Ge(e);for(let s=0;s0?nt(e,r,r.sections.length-1,x=>({...x,children:[...Ge(x),b]})):{...e,children:[...Ge(e),b]}}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=[],y=[];let g=0;for(;g0?Ue(r,d-1,g):null;b&&b.gridRow+b.rowSpan>d&&b.rowSpan>1?(y.push(b),g+=b.colSpan):(f.push(ki(o)),g+=1)}let m=e;for(const b of y)m=nt(m,r,b.sectionIndex,x=>yt(x,o.row,b.rowIndexInSection,k=>({...k,children:Ge(k).map((w,_)=>_===b.cellIndexInRow?mn(w,o.rowSpanProp,b.rowSpan+1):w)})));const h={type:"basic",name:o.row,children:f},v=Be(m,t);return m=nt(m,v,c,b=>{const x=Ge(b);let k=0,w=x.length;for(let _=0;_=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;pyt(y,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=Be(l,t);return l=nt(l,c,s.sectionIndex,p=>{let f=-1;const y=Ge(p).filter(g=>g.name===o.row?(f++,f!==s.rowIndexInSection):!0);return{...p,children:y}}),l}function eh(e,t,n,o){const r=ht(t),s=Be(e,t);if(!xi(s,n,o).ok)return e;const a=Qg(s),l=a.findIndex(h=>n>=h.start&&ns.rows.filter(v=>{const b=v.cells[0]?.gridRow??-1;return v.sectionIndex===f&&b>=h.start&&bv.rowIndexInSection),g=y(c),m=y(p);return g.length===0||m.length===0?e:nt(e,s,f,h=>{const v=[...Ge(h)],b=[];v.forEach((M,B)=>{M.name===r.row&&b.push(B)});const x=g.map(M=>b[M]).filter(M=>M!==void 0),k=m.map(M=>b[M]).filter(M=>M!==void 0);if(x.length===0||k.length===0)return h;const w=x.map(M=>v[M]),_=k.map(M=>v[M]),C=Math.min(...x)n>=m.start&&nw.gridCol>=f.start&&w.gridColw.gridCol>=y.start&&w.gridColw.cellIndexInRow),x=v.map(w=>w.cellIndexInRow),k=Be(g,t);g=nt(g,k,m.sectionIndex,w=>yt(w,r.row,m.rowIndexInSection,_=>{const C=[...Ge(_)],E=b.map(M=>Si(_,r,M)).filter(M=>M>=0),S=x.map(M=>Si(_,r,M)).filter(M=>M>=0);if(E.length===0||S.length===0)return _;const T=E.map(M=>C[M]),$=S.map(M=>C[M]),A=Math.min(...E,...S),z=Math.max(...E,...S),D=[...$,...T],O=[...C.slice(0,A),...D,...C.slice(z+1)];return{..._,children:O}}))}return g}function nh(e,t,n){const o=ht(t),r=Be(e,t);if(r.rows.length===0||r.colCount===0)return nl(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?Ue(r,c,s-1):null,f=s1){if(!l.has(p.cell)){l.add(p.cell);const h=Be(a,t);a=nt(a,h,p.sectionIndex,v=>yt(v,o.row,p.rowIndexInSection,b=>({...b,children:Ge(b).map((x,k)=>k===p.cellIndexInRow?mn(x,o.colSpanProp,p.colSpan+1):x)})))}continue}if(p&&p.gridRow0&&d.cells.every(h=>h.isHeader),m=Be(a,t);a=nt(a,m,d.sectionIndex,h=>yt(h,o.row,d.rowIndexInSection,v=>{const b=[...Ge(v)];let x;if(y<0)x=b.findIndex(k=>nr(k,o)),x<0&&(x=b.length);else{const k=Si(v,o,y);x=k<0?b.length:k+1}return b.splice(x,0,ki(o,void 0,g)),{...v,children:b}}))}return a}function oh(e,t,n){const o=ht(t),r=Be(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=Ue(r,d,n);if(!(!c||a.has(c.cell)||c.gridRow1){const p=Be(s,t);s=nt(s,p,c.sectionIndex,f=>yt(f,o.row,c.rowIndexInSection,y=>({...y,children:Ge(y).map((g,m)=>m===c.cellIndexInRow?mn(g,o.colSpanProp,c.colSpan-1):g)})))}else{const p=Be(s,t);s=nt(s,p,c.sectionIndex,f=>yt(f,o.row,c.rowIndexInSection,y=>{let g=-1;const m=Ge(y).filter(h=>nr(h,o)?(g++,g!==c.cellIndexInRow):!0);return{...y,children:m}}))}}return s}function ol(e,t,n,o,r,s){const a=ht(t),l=Be(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 y=new Set;for(let b=d;b<=c;b++)for(let x=p;x<=f;x++){const k=Ue(l,b,x);if(!k)return{table:e,ok:!1,reason:"hole"};if(k.gridRowc||k.gridCol+k.colSpan-1>f)return{table:e,ok:!1,reason:"not-rectangular"};y.add(k)}const g=Ue(l,d,p),m=Array.from(y).filter(b=>b!==g);let h=nt(e,l,g.sectionIndex,b=>yt(b,a.row,g.rowIndexInSection,x=>({...x,children:Ge(x).map((k,w)=>{if(w!==g.cellIndexInRow)return k;let _=mn(k,a.colSpanProp,f-p+1);return _=mn(_,a.rowSpanProp,c-d+1),_})})));const v=new Map;for(const b of m){const x=`${b.sectionIndex}:${b.rowIndexInSection}`,k=v.get(x)??[];k.push(b),v.set(x,k)}for(const[b,x]of v){const k=parseInt(b.split(":")[0],10),w=x[0].rowIndexInSection,_=new Set(x.map(E=>E.cellIndexInRow)),C=Be(h,t);h=nt(h,C,k,E=>yt(E,a.row,w,S=>{let T=-1;const $=Ge(S).filter(A=>nr(A,a)?(T++,!_.has(T)):!0);return{...S,children:$}}))}return{table:h,ok:!0}}function rh(e,t,n,o){const r=ht(t),s=Be(e,t),a=Ue(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,y=typeof a.cell.props?.className=="string"?a.cell.props.className:void 0;let g=nt(e,s,a.sectionIndex,m=>yt(m,r.row,a.rowIndexInSection,h=>({...h,children:Ge(h).map((v,b)=>{if(b!==a.cellIndexInRow)return v;let x=mn(v,r.colSpanProp,1);return x=mn(x,r.rowSpanProp,1),x})})));for(let m=l;m<=c;m++)for(let h=d;h<=p;h++){if(m===l&&h===d)continue;const v=Be(g,t),b=v.rows.find(w=>w.cells.some(_=>_.gridRow===m))??v.rows[m];if(!b)continue;let x=-1;for(const w of b.cells)w.gridRow===m&&w.gridColyt(w,r.row,b.rowIndexInSection,_=>{const C=[...Ge(_)];let E;if(x<0)E=C.findIndex(S=>nr(S,r)),E<0&&(E=C.length);else{const S=Si(_,r,x);E=S<0?C.length:S+1}return C.splice(E,0,ki(r,k,f)),{..._,children:C}}))}return g}function Ci(e,t,n,o,r){const s=ht(t),a=Be(e,t),l=Ue(a,n,o);return l?nt(e,a,l.sectionIndex,d=>yt(d,s.row,l.rowIndexInSection,c=>({...c,children:Ge(c).map((p,f)=>{if(f!==l.cellIndexInRow)return p;const y={...p.props??{}};r.trim()===""?delete y.className:y.className=r;const g={...p,props:y};return Object.keys(y).length===0&&delete g.props,g})}))):e}function Jt(e,t,n,o,r,s){const a=ht(t),l=Be(e,t),d=Ue(l,n,o);return d?nt(e,l,d.sectionIndex,c=>yt(c,a.row,d.rowIndexInSection,p=>({...p,children:Ge(p).map((f,y)=>{if(y!==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 go(e,t,n,o,r,s,a){const l=ht(t),d=Be(e,t),c=Ue(d,n,o);if(!c)return e;const p=a==="dark";return nt(e,d,c.sectionIndex,f=>yt(f,l.row,c.rowIndexInSection,y=>({...y,children:Ge(y).map((g,m)=>{if(m!==c.cellIndexInRow)return g;const h={...g.props??{}},v=typeof h.className=="string"?h.className:"",b=uC(v,s,r,p);b===""?delete h.className:h.className=b;const x={...g,props:h};return Object.keys(h).length===0&&delete x.props,x})})))}function ih(e,t,n,o,r){const s=ht(t),a=Be(e,t),l=Ue(a,n,o);return l?nt(e,a,l.sectionIndex,d=>yt(d,s.row,l.rowIndexInSection,c=>({...c,children:Ge(c).map((p,f)=>f===l.cellIndexInRow?{...p,text:r}:p)}))):e}function sh(e,t,n,o,r){const s=ht(t),a=Be(e,t),l=Ue(a,n,o);return l?nt(e,a,l.sectionIndex,d=>yt(d,s.row,l.rowIndexInSection,c=>({...c,children:Ge(c).map((p,f)=>f===l.cellIndexInRow?r:p)}))):e}const ah=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function r8(e){return e.split(/\s+/).filter(Boolean)}function lh(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 dh({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??[],y=r==="dark",g=u.useMemo(()=>c.map($=>$.prefix),[c]),m=u.useMemo(()=>new Set(f.map($=>$.token)),[f]),h=u.useMemo(()=>r8(e),[e]),v=u.useMemo(()=>Vr(e,y),[e,y]),b=u.useMemo(()=>v.find($=>m.has($))??null,[v,m]),x=u.useMemo(()=>{const $=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)))&&$.add(A.value);return $},[h,c]),k=u.useMemo(()=>{const $=h.find(z=>lh(z,g));if(!$)return"none";const A=p.filter(z=>z.value!=="none");for(const z of c){if($===z.prefix)return A.find(D=>(D.suffix??"")==="")?.value??"thin";if($.startsWith(z.prefix+"-")){const D=$.slice(z.prefix.length),O=A.find(M=>(M.suffix??"")===D);if(O)return O.value}}return"thin"},[h,g,c,p]);if(!t||c.length===0||p.length===0)return null;function w($){return $.filter(A=>!lh(A,g))}function _($,A){const z=w(h),D=p.find(B=>B.value===A);if(!D||A==="none"||$.size===0)return z.join(" ").trim();const O=D.suffix??"",M=[...z];for(const B of c)$.has(B.value)&&M.push(O?`${B.prefix}${O}`:B.prefix);return M.join(" ").trim()}const C=$=>{const A=new Set(x);A.has($)?A.delete($):($==="all"?A.clear():A.delete("all"),A.add($));const z=k==="none"?p.find(D=>D.value!=="none")?.value??"thin":k;o(_(A,z))},E=$=>{const A=x.size===0?new Set(["all"]):x;o(_(A,$))},S=$=>{s?.($)},T=($,A)=>$&&$.startsWith("$t:")?n($.slice(3)):$||A;return i.jsxs("div",{className:"g7le-cell-border","data-testid":"g7le-cell-border",style:i8,children:[i.jsx("div",{style:s8,children:i.jsx("span",{style:a8,children:n("layout_editor.table_editor.cell_border")})}),i.jsx("div",{style:rl,"data-testid":"g7le-cell-border-widths",children:p.map($=>i.jsx("button",{type:"button",disabled:d,"data-testid":`g7le-cell-border-width-${$.value}`,"aria-pressed":k===$.value,onClick:()=>E($.value),style:k===$.value?ch:il,children:T($.label,$.value)},$.value))}),k!=="none"&&i.jsx("div",{style:rl,"data-testid":"g7le-cell-border-sides",children:c.map($=>i.jsx("button",{type:"button",disabled:d,"data-testid":`g7le-cell-border-side-${$.value}`,"aria-pressed":x.has($.value),onClick:()=>C($.value),style:x.has($.value)?ch:il,children:T($.label,$.value)},$.value))}),k!=="none"&&(f.length>0||l)&&i.jsx(i.Fragment,{children:i.jsxs("div",{style:rl,"data-testid":"g7le-cell-border-colors",children:[f.map($=>{const A=b===$.token;return i.jsx("button",{type:"button",disabled:d,title:T($.label,$.value),"data-testid":`g7le-cell-border-color-${$.value}`,"aria-pressed":A,onClick:()=>S($.token),style:{...uh,background:$.swatch??"#fff",outline:A?"2px solid #2563eb":"1px solid #cbd5e1"}},$.value)}),l&&(()=>{const $=!!a&&f.some(z=>z.swatch&&z.swatch.toLowerCase()===a.toLowerCase()),A=!y&&!!a&&!$;return i.jsx("label",{title:n(y?"layout_editor.table_editor.dark_free_color_hint":"layout_editor.table_inplace.custom_color"),"data-testid":"g7le-cell-border-color-custom",style:{...uh,position:"relative",overflow:"hidden",display:"inline-flex",alignItems:"center",justifyContent:"center",background:A&&ah.test(a)?a:"conic-gradient(red, yellow, lime, aqua, blue, magenta, red)",outline:A?"2px solid #2563eb":"1px solid #cbd5e1",opacity:y?.4:1,cursor:y?"not-allowed":"pointer"},children:i.jsx("input",{type:"color",disabled:d||y,"data-testid":"g7le-cell-border-color-picker",value:a&&ah.test(a)?a:"#000000",onChange:z=>l(z.target.value),style:{position:"absolute",width:0,height:0,opacity:0}})})})()]})})]})}const i8={display:"flex",flexDirection:"column",gap:6},s8={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},a8={fontSize:12,fontWeight:600,color:"#475569"},rl={display:"flex",gap:4,flexWrap:"wrap",alignItems:"center"},il={padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},ch={...il,border:"1px solid #2563eb",background:"#eff6ff",color:"#1d4ed8",fontWeight:600},uh={width:22,height:22,borderRadius:5,padding:0,cursor:"pointer",boxSizing:"border-box"},ph=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function fh({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??"",y=Vr(t??"",p),g=c.find(x=>x.token&&y.includes(x.token))?.token??null,m=(x,k)=>x&&x.startsWith("$t:")?o(x.slice(3)):x||k,h=!g&&(p||f.trim()===""),v=!!f&&c.some(x=>x.swatch&&x.swatch.toLowerCase()===f.toLowerCase()),b=!p&&!!f&&!v;return i.jsxs("div",{className:"g7le-cell-fill","data-testid":"g7le-cell-fill",style:l8,children:[i.jsx("div",{style:d8,children:i.jsx("span",{style:c8,children:o("layout_editor.table_editor.cell_fill")})}),i.jsxs("div",{style:u8,"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:{...sl,background:"repeating-conic-gradient(#e2e8f0 0% 25%, #ffffff 0% 50%) 50% / 10px 10px",outline:h?"2px solid #2563eb":"1px solid #cbd5e1"}}),c.map(x=>{const k=!!x.token&&g===x.token,w=!p&&!!x.swatch&&f.toLowerCase()===(x.swatch??"").toLowerCase(),_=k||w,C=d||p&&!x.token;return i.jsx("button",{type:"button",disabled:C,title:m(x.label,x.value),"data-testid":`g7le-cell-fill-color-${x.value}`,"aria-pressed":_,onClick:()=>{x.token&&s?s(x.token):!p&&x.swatch&&a&&a(x.swatch)},style:{...sl,background:x.swatch??"#fff",outline:_?"2px solid #2563eb":"1px solid #cbd5e1",opacity:C?.4:1,cursor:C?"not-allowed":"pointer"}},x.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:{...sl,position:"relative",overflow:"hidden",display:"inline-flex",alignItems:"center",justifyContent:"center",background:b&&ph.test(f)?f:"conic-gradient(red, yellow, lime, aqua, blue, magenta, red)",outline:b?"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&&ph.test(f)?f:"#ffffff",onChange:x=>a(x.target.value),style:{position:"absolute",width:0,height:0,opacity:0}})})]})]})}const l8={display:"flex",flexDirection:"column",gap:6},d8={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},c8={fontSize:12,fontWeight:600,color:"#475569"},u8={display:"flex",gap:4,flexWrap:"wrap",alignItems:"center"},sl={width:22,height:22,borderRadius:5,padding:0,cursor:"pointer",boxSizing:"border-box"};function p8(e){const t=/^(\d+)px$/.exec(e.trim());return t?parseInt(t[1],10):null}function gh({paddingStyle:e,catalog:t,t:n,onChange:o,disabled:r}){const s=t?.steps??[],a=e??"",l=p8(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,y]=u.useState(p);u.useEffect(()=>{y(p)},[e]);const g=h=>{o(h&&h>0?`${h}px`:""),y("")},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:f8,children:[i.jsx("div",{style:g8,children:n("layout_editor.table_editor.cell_padding")}),i.jsxs("div",{style:h8,"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?y8:hh,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=>y(h.target.value),onBlur:()=>f.trim()!==""&&m(f),onKeyDown:h=>{h.key==="Enter"&&f.trim()!==""&&m(f)},style:b8}),i.jsx("span",{style:{fontSize:11,color:"#94a3b8"},children:"px"})]})]})]})}const f8={display:"flex",flexDirection:"column",gap:6},g8={fontSize:12,fontWeight:600,color:"#475569"},h8={display:"flex",gap:4,flexWrap:"wrap",alignItems:"center"},hh={padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},y8={...hh,border:"1px solid #2563eb",background:"#eff6ff",color:"#1d4ed8",fontWeight:600},b8={width:48,padding:"3px 5px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"};function yh({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:m8,children:[i.jsxs("div",{style:v8,children:[i.jsx("span",{style:_8,children:n("layout_editor.table_editor.cell_color")}),i.jsxs("div",{style:x8,children:[i.jsx("button",{type:"button",disabled:o,"data-testid":"g7le-color-scheme-light","aria-pressed":!r,onClick:()=>t("light"),style:r?al:bh,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?bh:al,children:n("layout_editor.property_modal.scope.scheme_dark")})]})]}),r&&i.jsx("div",{style:w8,"data-testid":"g7le-color-scheme-dark-hint",children:n("layout_editor.table_editor.dark_free_color_hint")})]})}const m8={display:"flex",flexDirection:"column",gap:3},v8={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},_8={fontSize:12,fontWeight:700,color:"#0f172a"},x8={display:"flex",gap:2},al={padding:"2px 9px",fontSize:11,border:"none",borderBottom:"2px solid transparent",background:"transparent",color:"#94a3b8",cursor:"pointer"},bh={...al,color:"#1d4ed8",borderBottom:"2px solid #2563eb",fontWeight:600},w8={fontSize:10,color:"#94a3b8",fontStyle:"italic"},ll="dark:";function mh(e){return typeof e=="string"?e.split(/\s+/).filter(Boolean):[]}function vh(e,t){return t==="dark"?e.filter(n=>n.startsWith(ll)).map(n=>n.slice(ll.length)):e.filter(n=>!n.startsWith(ll))}const k8={none:0,thin:1,medium:2,thick:4},_h={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"}},xh=["top","bottom","left","right"];function S8(e,t,n="light"){if(!e||!t)return{};const o=t.sides??[],r=t.widths??[],s=t.colors??[],a=mh(e.props?.className);if(a.length===0&&!e.props?.style)return{};const l=[...r].filter(b=>b.value!=="none").sort((b,x)=>(x.suffix??"").length-(b.suffix??"").length),d={};for(const b of o)for(const x of l){const k=x.suffix?`${b.prefix}${x.suffix}`:b.prefix;if(a.includes(k)){d[b.value]=x.value;break}}const c=e.props?.style??{},p=vh(a,n),f=s.find(b=>p.includes(b.token))?.swatch??"",g=(n==="light"&&typeof c.borderColor=="string"?c.borderColor:"")||f||"#94a3b8",m=b=>{const x=_h[b]?.c,k=x?c[x]:void 0;return typeof k=="string"&&k?k:g},h={},v=(b,x)=>{const k=_h[b];if(!k)return;const w=k8[x]??1;h[k.w]=`${w}px`,h[k.s]=w>0?"solid":"none",w>0&&(h[k.c]=m(b))};if(d.all)for(const b of xh)v(b,d.all);for(const b of xh)d[b]&&v(b,d[b]);return h}function C8(e,t,n="light"){if(!e?.props)return{};const o=e.props.style??{},r={},s=mh(e.props.className),a=t?.colors?.find(c=>c.token&&vh(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 $8=/^\s*\$t:(custom\.[a-zA-Z0-9._-]+)\s*$/,E8=/^\s*\$t:([a-zA-Z0-9._-]+)\s*$/,I8=/\{\{.*?\}\}/;function wh(e,t,n){const o=e?.text;if(typeof o!="string")return{display:"",editable:!1,isKey:!1};const r=mt(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(I8.test(o))return{display:o,editable:!1,isKey:!1};const s=E8.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 dl(e){const t=er(e);return t===null?{node:null,path:null}:{node:_i(e,t),path:t}}function A8(e){if(!e||typeof e.text!="string")return null;const t=$8.exec(e.text);if(t)return t[1];const n=mt(e.text);return n&&n.key.startsWith("custom.")?n.key:null}function T8({node:e,params:t,t:n,onPatchNode:o,templateIdentifier:r,candidates:s}){const{state:a}=Je(),l=a.selectedRoute?.layoutName??null,d=a.locale,c=r??a.templateIdentifier,p=u.useMemo(()=>t&&typeof t=="object"?t:null,[t]);u.useMemo(()=>ht(p),[p]);const f=u.useMemo(()=>Be(e,p),[e,p]),y=u.useMemo(()=>{const q=p?.cellBorder;return q&&typeof q=="object"?q:null},[p]),g=u.useMemo(()=>{const q=p?.cellBackground;return q&&typeof q=="object"?q:null},[p]),m=u.useMemo(()=>{const q=p?.cellPadding;return q&&typeof q=="object"?q:null},[p]),[h,v]=u.useState(null),[b,x]=u.useState(null),[k,w]=u.useState({}),[_,C]=u.useState(!1),[E,S]=u.useState(null),[T,$]=u.useState(null),[A,z]=u.useState("light"),D=u.useCallback(q=>o(q),[o]),O=u.useMemo(()=>h?Ue(f,h.r,h.c):null,[f,h]),M=T!==null?T:h?.c??null,B=E!==null?E:h?.r??null,N=u.useMemo(()=>{const q=(y?.sides??[]).find($e=>$e.value==="all")??(y?.sides??[])[0],ae=(y?.widths??[]).find($e=>$e.value!=="none");if(!q||!ae)return[];const pe=ae.suffix??"";return[pe?`${q.prefix}${pe}`:q.prefix]},[y]),H=u.useCallback((q,ae,pe)=>{if(N.length===0)return q;const $e=(y?.sides??[]).map(J=>J.prefix),be=Ue(Be(q,p),ae,pe),oe=(typeof be?.cell?.props?.className=="string"?be.cell.props.className:"").split(/\s+/).filter(Boolean);return oe.some(J=>$e.some(le=>J===le||J.startsWith(le+"-")&&/^-?\d+$/.test(J.slice(le.length+1))))?q:Ci(q,p,ae,pe,[...oe,...N].join(" ").trim())},[N,y,p]),L=u.useCallback(q=>{if(!h)return;const ae=Math.min(h.r,b?.r??h.r),pe=Math.max(h.r,b?.r??h.r),$e=Math.min(h.c,b?.c??h.c),be=Math.max(h.c,b?.c??h.c),j=new Set,oe=[];for(let J=ae;J<=pe;J++)for(let le=$e;le<=be;le++)j.add(`${J}:${le}`),oe.push({r:J,c:le});let ue=e;for(const J of oe){if(ue=H(ue,J.r,J.c),ue=Jt(ue,p,J.r,J.c,"borderColor",q),J.r>0&&!j.has(`${J.r-1}:${J.c}`)){const le=Ue(Be(ue,p),J.r-1,J.c);le&&(ue=Jt(ue,p,le.gridRow,le.gridCol,"borderBottomColor",q))}if(J.c>0&&!j.has(`${J.r}:${J.c-1}`)){const le=Ue(Be(ue,p),J.r,J.c-1);le&&(ue=Jt(ue,p,le.gridRow,le.gridCol,"borderRightColor",q))}}D(ue)},[h,b,e,p,D,H]),I=u.useCallback(q=>L(q),[L]),P=u.useMemo(()=>(y?.colors??[]).map(q=>q.token).filter(Boolean),[y]),F=u.useCallback(q=>{if(!h||P.length===0)return;const ae=Math.min(h.r,b?.r??h.r),pe=Math.max(h.r,b?.r??h.r),$e=Math.min(h.c,b?.c??h.c),be=Math.max(h.c,b?.c??h.c);let j=e;for(let oe=ae;oe<=pe;oe++)for(let ue=$e;ue<=be;ue++)j=H(j,oe,ue),j=go(j,p,oe,ue,q,P,A);D(j)},[h,b,e,p,D,H,P,A]),G=u.useMemo(()=>{if(A==="dark")return"";const q=O?.cell.props?.style;return typeof q?.borderColor=="string"?q.borderColor:""},[O,A]),V=u.useCallback((q,ae)=>{if(!h)return;const pe=Math.min(h.r,b?.r??h.r),$e=Math.max(h.r,b?.r??h.r),be=Math.min(h.c,b?.c??h.c),j=Math.max(h.c,b?.c??h.c);let oe=e;for(let ue=pe;ue<=$e;ue++)for(let J=be;J<=j;J++)oe=Jt(oe,p,ue,J,q,ae);D(oe)},[h,b,e,p,D]),Y=u.useMemo(()=>(g?.colors??[]).map(q=>q.token).filter(q=>!!q),[g]),Z=u.useCallback(()=>h?{r0:Math.min(h.r,b?.r??h.r),r1:Math.max(h.r,b?.r??h.r),c0:Math.min(h.c,b?.c??h.c),c1:Math.max(h.c,b?.c??h.c)}:null,[h,b]),se=u.useCallback(q=>{const ae=Z();if(!ae||Y.length===0)return;let pe=e;for(let $e=ae.r0;$e<=ae.r1;$e++)for(let be=ae.c0;be<=ae.c1;be++)pe=go(pe,p,$e,be,q,Y,A);D(pe)},[Z,e,p,D,Y,A]),re=u.useCallback(q=>V("backgroundColor",q),[V]),U=u.useCallback(()=>{const q=Z();if(!q)return;let ae=e;for(let pe=q.r0;pe<=q.r1;pe++)for(let $e=q.c0;$e<=q.c1;$e++)ae=go(ae,p,pe,$e,void 0,Y,A),A==="light"&&(ae=Jt(ae,p,pe,$e,"backgroundColor",void 0));D(ae)},[Z,e,p,D,Y,A]),ee=u.useCallback(q=>V("padding",q),[V]),fe=u.useMemo(()=>{if(A==="dark")return"";const q=O?.cell.props?.style;return typeof q?.backgroundColor=="string"?q.backgroundColor:""},[O,A]),K=u.useMemo(()=>typeof O?.cell.props?.className=="string"?O.cell.props.className:"",[O]),ne=u.useMemo(()=>{const q=O?.cell.props?.style;return typeof q?.padding=="string"?q.padding:""},[O]),me=u.useCallback(q=>q==="section"?n("layout_editor.table_editor.move_blocked_section"):"",[n]),Ce=u.useCallback((q,ae)=>xi(f,q,ae),[f]),ze=u.useCallback((q,ae)=>wi(f,q,ae),[f]),Se=u.useCallback(q=>D(nl(e,p,q)),[e,p,D]),qe=u.useCallback(q=>{D(Rg(e,p,q)),v(null),x(null)},[e,p,D]),De=u.useCallback((q,ae)=>D(eh(e,p,q,ae)),[e,p,D]),Pe=u.useCallback(q=>D(nh(e,p,q)),[e,p,D]),Qe=u.useCallback(q=>{D(oh(e,p,q)),v(null),x(null)},[e,p,D]),Me=u.useCallback((q,ae)=>D(th(e,p,q,ae)),[e,p,D]),Re=u.useCallback(()=>{if(!h||!b)return;const q=ol(e,p,h.r,h.c,b.r,b.c);q.ok&&(D(q.table),v({r:Math.min(h.r,b.r),c:Math.min(h.c,b.c)}),x(null))},[e,p,h,b,D]),ve=u.useCallback(()=>{h&&(D(rh(e,p,h.r,h.c)),x(null))},[e,p,h,D]),te=u.useCallback(q=>{if(!h)return;const ae=Math.min(h.r,b?.r??h.r),pe=Math.max(h.r,b?.r??h.r),$e=Math.min(h.c,b?.c??h.c),be=Math.max(h.c,b?.c??h.c);let j=e;for(let oe=ae;oe<=pe;oe++)for(let ue=$e;ue<=be;ue++)j=Ci(j,p,oe,ue,q);D(j)},[e,p,h,b,D]),he=u.useCallback(async(q,ae)=>{const pe=`${q}:${ae}`,$e=k[pe];if($e===void 0)return;const be=Ue(f,q,ae);if(!be)return;const{node:j,path:oe}=dl(be.cell);if(oe===null)return;const ue=wh(j,c,d);if(ue.editable){if($e===ue.display){w(J=>{const le={...J};return delete le[pe],le});return}C(!0);try{const J=A8(j);if(J)await yr(c,J,d,$e),await tn(c,d);else{const le=await qn(c,l,d,$e);if(le.kind==="ok"&&le.resource){const Ie=`$t:${le.resource.translation_key}`;if(oe.length===0)D(ih(e,p,q,ae,Ie));else{const dt=tr(be.cell,oe,Ie);D(sh(e,p,q,ae,dt))}await tn(c,d)}}}finally{C(!1),w(J=>{const le={...J};return delete le[pe],le})}}},[k,f,c,d,l,e,p,D]),Q=u.useMemo(()=>{if(!O)return null;const{node:q,path:ae}=dl(O.cell);return ae===null?null:{value:typeof q?.text=="string"?q.text:"",editable:!0}},[O]),ie=u.useCallback(q=>{if(typeof q!="string"||q.length===0||!h)return;const ae=Ue(f,h.r,h.c);if(!ae)return;const pe=er(ae.cell);if(pe!==null)if(pe.length===0)D(ih(e,p,h.r,h.c,q));else{const $e=tr(ae.cell,pe,q);D(sh(e,p,h.r,h.c,$e))}},[h,f,e,p,D]),_e=u.useCallback((q,ae,pe)=>{pe?x({r:q,c:ae}):(v({r:q,c:ae}),x(null))},[]),ge=u.useMemo(()=>Array.from({length:f.colCount},(q,ae)=>ae),[f.colCount]),Ae=!!(h&&b&&(h.r!==b.r||h.c!==b.c)),Ne=!!(O&&(O.colSpan>1||O.rowSpan>1)),Le=O&&typeof O.cell.props?.className=="string"?O.cell.props.className:"";return i.jsxs("div",{className:"g7le-node-editor g7le-node-editor--table","data-testid":"g7le-table-editor",style:D8,children:[i.jsx("div",{style:N8,children:n("layout_editor.table_editor.title")}),i.jsx("div",{style:{overflowX:"auto"},children:i.jsxs("table",{"data-testid":"g7le-table-editor-grid",style:z8,children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{style:M8}),ge.map(q=>{const ae=ze(q,-1),pe=ze(q,1),$e=M===q;return i.jsx("th",{style:L8,"data-testid":`g7le-table-colgutter-${q}`,onMouseEnter:()=>$(q),onMouseLeave:()=>$(be=>be===q?null:be),children:i.jsxs("div",{style:{...O8,visibility:$e?"visible":"hidden"},children:[i.jsx("button",{type:"button",title:ae.ok?n("layout_editor.table_editor.move_col_left"):me(ae.reason)||n("layout_editor.table_editor.move_col_left"),disabled:!ae.ok||_,onClick:()=>Me(q,-1),"data-testid":`g7le-table-col-left-${q}`,style:ae.ok?vn:$i,children:"←"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.add_col"),disabled:_,onClick:()=>Pe(q),"data-testid":`g7le-table-col-add-${q}`,style:vn,children:"+"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.remove_col"),disabled:f.colCount<=1||_,onClick:()=>Qe(q),"data-testid":`g7le-table-col-remove-${q}`,style:kh,children:"✕"}),i.jsx("button",{type:"button",title:pe.ok?n("layout_editor.table_editor.move_col_right"):me(pe.reason)||n("layout_editor.table_editor.move_col_right"),disabled:!pe.ok||_,onClick:()=>Me(q,1),"data-testid":`g7le-table-col-right-${q}`,style:pe.ok?vn:$i,children:"→"})]})},q)})]})}),i.jsx("tbody",{children:f.rows.map((q,ae)=>{const pe=q.cells[0]?.gridRow??ae,$e=B===pe;return i.jsxs("tr",{"data-testid":`g7le-table-row-${pe}`,onMouseEnter:()=>S(pe),onMouseLeave:()=>S(be=>be===pe?null:be),children:[i.jsx("td",{style:P8,"data-testid":`g7le-table-rowgutter-${pe}`,children:(()=>{const be=Ce(pe,-1),j=Ce(pe,1);return i.jsxs("div",{style:{...B8,visibility:$e?"visible":"hidden"},children:[i.jsx("button",{type:"button",title:be.ok?n("layout_editor.table_editor.move_row_up"):me(be.reason)||n("layout_editor.table_editor.move_row_up"),disabled:!be.ok||_,onClick:()=>De(pe,-1),"data-testid":`g7le-table-row-up-${pe}`,style:be.ok?vn:$i,children:"↑"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.add_row"),disabled:_,onClick:()=>Se(pe),"data-testid":`g7le-table-row-add-${pe}`,style:vn,children:"+"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.remove_row"),disabled:f.rows.length<=1||_,onClick:()=>qe(pe),"data-testid":`g7le-table-row-remove-${pe}`,style:kh,children:"✕"}),i.jsx("button",{type:"button",title:j.ok?n("layout_editor.table_editor.move_row_down"):me(j.reason)||n("layout_editor.table_editor.move_row_down"),disabled:!j.ok||_,onClick:()=>De(pe,1),"data-testid":`g7le-table-row-down-${pe}`,style:j.ok?vn:$i,children:"↓"})]})})()}),q.cells.map(be=>{const j=`${be.gridRow}:${be.gridCol}`,{node:oe,path:ue}=dl(be.cell),J=wh(oe,c,d),le=ue!==null&&J.editable,Ie=ue===null,dt=k[j],pt=dt!==void 0?dt:J.display,ot=h&&h.r===be.gridRow&&h.c===be.gridCol,Oe=h&&b&&be.gridRow>=Math.min(h.r,b.r)&&be.gridRow<=Math.max(h.r,b.r)&&be.gridCol>=Math.min(h.c,b.c)&&be.gridCol<=Math.max(h.c,b.c);return i.jsx("td",{colSpan:be.colSpan,rowSpan:be.rowSpan,"data-testid":`g7le-table-cell-${be.gridRow}-${be.gridCol}`,onClick:He=>_e(be.gridRow,be.gridCol,He.shiftKey),style:{...W8,...S8(be.cell,y,A),...C8(be.cell,g,A),...be.isHeader?j8:{},...ot?H8:{},...Oe&&!ot?F8:{}},children:le?i.jsx("input",{type:"text","data-testid":`g7le-table-cell-input-${be.gridRow}-${be.gridCol}`,value:pt,placeholder:n("layout_editor.table_editor.cell_text"),disabled:_,onMouseDown:He=>{He.shiftKey&&He.preventDefault(),_e(be.gridRow,be.gridCol,He.shiftKey)},onClick:He=>He.stopPropagation(),onChange:He=>w(Ye=>({...Ye,[j]:He.target.value})),onBlur:()=>{he(be.gridRow,be.gridCol)},style:K8}):Ie?i.jsx("span",{"data-testid":`g7le-table-cell-struct-${be.gridRow}-${be.gridCol}`,style:Sh,children:n("layout_editor.table_editor.structural_cell")}):i.jsx("span",{style:Sh,children:J.display})},j)})]},ae)})})]})}),i.jsxs("button",{type:"button","data-testid":"g7le-table-add-row-bottom",onClick:()=>Se(f.rows.length-1),disabled:_,style:V8,children:["+ ",n("layout_editor.table_editor.add_row")]}),i.jsxs("div",{style:U8,"data-testid":"g7le-table-cell-tools",children:[i.jsx("button",{type:"button","data-testid":"g7le-table-merge",onClick:Re,disabled:!Ae||_,style:Ch,children:n("layout_editor.table_editor.merge_cells")}),i.jsx("button",{type:"button","data-testid":"g7le-table-unmerge",onClick:ve,disabled:!Ne||_,style:Ch,children:n("layout_editor.table_editor.unmerge_cells")})]}),O&&Q&&i.jsxs("div",{style:G8,"data-testid":"g7le-table-cell-i18n-section",children:[i.jsx("div",{style:Y8,children:n("layout_editor.table_editor.cell_i18n_label")}),i.jsx(vt,{value:Q.value,onChange:ie,t:n,placeholder:n("layout_editor.table_editor.cell_text"),testidPrefix:"g7le-table-cell-i18n",candidates:s,enableExpressionTree:!0,expressionTreeCollapsible:!0})]}),O&&i.jsxs("div",{style:q8,"data-testid":"g7le-table-cell-color-section",children:[i.jsx(yh,{colorScheme:A,onChange:z,t:n,disabled:_}),y&&i.jsx("div",{style:cl,"data-testid":"g7le-table-cell-border-row",children:i.jsx(dh,{className:Le,catalog:y,t:n,onChange:te,colorScheme:A,onPresetToken:F,colorStyle:G,onColorStyle:I,disabled:_})}),i.jsx("div",{style:cl,"data-testid":"g7le-table-cell-fill-row",children:i.jsx(fh,{colorStyle:fe,className:K,catalog:g,t:n,colorScheme:A,onPresetToken:se,onCustomColor:re,onClear:U,disabled:_})})]}),O&&i.jsx("div",{style:cl,"data-testid":"g7le-table-cell-padding-row",children:i.jsx(gh,{paddingStyle:ne,catalog:m,t:n,onChange:ee,disabled:_})}),O&&!y&&i.jsxs("label",{style:X8,"data-testid":"g7le-table-cell-border-row",children:[i.jsx("span",{style:J8,children:n("layout_editor.table_editor.cell_border")}),i.jsx("input",{type:"text","data-testid":"g7le-table-cell-border-input",value:Le,placeholder:n("layout_editor.table_editor.cell_class_placeholder"),onChange:q=>te(q.target.value),disabled:_,style:Z8})]}),!f.valid&&i.jsx("div",{"data-testid":"g7le-table-grid-warning",style:Q8,children:n("layout_editor.table_editor.grid_invalid")}),i.jsx("div",{style:R8,children:n("layout_editor.table_editor.select_hint")})]})}const D8={display:"flex",flexDirection:"column",gap:8,width:"100%",marginBottom:12},N8={fontSize:12,fontWeight:700,color:"#0f172a"},z8={borderCollapse:"collapse",width:"auto"},M8={width:28,background:"transparent",border:"none"},L8={padding:2,border:"none",background:"transparent"},P8={padding:2,border:"none",background:"transparent",verticalAlign:"middle"},O8={display:"flex",gap:2,justifyContent:"center"},B8={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"},kh={...vn,border:"1px solid #fecaca",color:"#dc2626"},$i={...vn,cursor:"not-allowed",opacity:.4,color:"#94a3b8",borderColor:"#e2e8f0"},W8={border:"1px solid #cbd5e1",padding:0,width:64,minWidth:64,maxWidth:120,height:24,background:"#fff",cursor:"pointer"},j8={background:"#f1f5f9",fontWeight:600},H8={outline:"2px solid #2563eb",outlineOffset:-2},F8={background:"#dbeafe"},K8={width:"100%",boxSizing:"border-box",padding:"2px 5px",fontSize:11,height:22,lineHeight:"18px",border:"none",background:"transparent",outline:"none"},Sh={display:"block",padding:"2px 5px",fontSize:10,color:"#64748b",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:110},V8={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},U8={display:"flex",gap:6},Ch={padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},q8={display:"flex",flexDirection:"column",gap:8,borderTop:"1px solid #f1f5f9",paddingTop:8},G8={display:"flex",flexDirection:"column",gap:6,borderTop:"1px solid #f1f5f9",paddingTop:8},Y8={fontSize:12,fontWeight:700,color:"#0f172a"},cl={display:"flex",flexDirection:"column",gap:6},X8={display:"flex",alignItems:"center",gap:6},J8={fontSize:12,color:"#475569",minWidth:60},Z8={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},Q8={fontSize:11,color:"#b45309",background:"#fffbeb",border:"1px solid #fde68a",borderRadius:6,padding:"4px 6px"},R8={fontSize:11,color:"#94a3b8"},ez=/\{\{.*?\}\}/;function tz(e,t,n){const r=(e.props??{})[t];return Array.isArray(r)?r:r===void 0&&n?JSON.parse(JSON.stringify(n)):[]}function nz(e){return typeof e=="string"&&ez.test(e)}function ul(e,t,n){return e?e.startsWith("$t:")?t(e.slice(3)):e:n}function oz(e,t,n){return typeof e=="object"&&e!==null?e[t.key]:n?e:void 0}function rz(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 $h({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=ul(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,y=(l.find(C=>C.primary)??l[0])?.key,g=(e.props??{})[a??""],m=Array.isArray(t?.defaultItems)?t.defaultItems:null,h=a?tz(e,a,m):[],v=u.useCallback(C=>{if(!a)return;const E={...e.props??{}};E[a]=C,o({...e,props:E})},[a,e,o]),b=u.useCallback(()=>{if(p)return JSON.parse(JSON.stringify(p));if(f!==null)return f;const C={};for(const E of l)(E.widget??"text")==="boolean"?C[E.key]=!1:C[E.key]="";return C},[p,f,l]),x=u.useCallback(()=>{v([...h,b()])},[v,h,b]),k=u.useCallback(C=>{v(h.filter((E,S)=>S!==C))},[v,h]),w=u.useCallback((C,E)=>{const S=C+E;if(S<0||S>=h.length)return;const T=[...h];[T[C],T[S]]=[T[S],T[C]],v(T)},[v,h]),_=u.useCallback((C,E,S)=>{const T=E.key===y,$=h.map((A,z)=>z===C?rz(A,E,T,S):A);v($)},[h,v,y]);return a?nz(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:fz,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:iz,children:[i.jsx("div",{style:sz,children:n("layout_editor.array_editor.items_title")}),h.length===0&&i.jsx("div",{"data-testid":"g7le-array-empty",style:Ih,children:n("layout_editor.array_editor.empty")}),h.map((C,E)=>i.jsxs("div",{"data-testid":`g7le-array-row-${E}`,style:az,children:[i.jsxs("div",{style:lz,children:[i.jsxs("span",{style:dz,children:["#",E+1]}),i.jsx("div",{style:{flex:1}}),i.jsx("button",{type:"button","data-testid":`g7le-array-up-${E}`,title:n("layout_editor.array_editor.move_up"),disabled:E===0,onClick:()=>w(E,-1),style:Eh,children:"↑"}),i.jsx("button",{type:"button","data-testid":`g7le-array-down-${E}`,title:n("layout_editor.array_editor.move_down"),disabled:E===h.length-1,onClick:()=>w(E,1),style:Eh,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-array-remove-${E}`,title:n("layout_editor.array_editor.remove"),onClick:()=>k(E),style:uz,children:"✕"})]}),l.map(S=>{const T=S.widget??"text",$=S.key===y,A=ul(S.label,n,S.key),z=oz(C,S,$),D=`g7le-array-field-${E}-${S.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:z===!0,onChange:M=>_(E,S,M.target.checked)})]},S.key);if(T==="select"){const M=Array.isArray(S.options)?S.options:[];return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsxs("select",{"data-testid":D,value:z==null?"":String(z),onChange:B=>_(E,S,B.target.value===""?void 0:B.target.value),style:or,children:[i.jsx("option",{value:"",children:"—"}),M.map((B,N)=>i.jsx("option",{value:String(B.value),children:ul(B.label,n,String(B.value))},N))]})]},S.key)}if(T==="i18n-text"){const M=typeof z=="string"?z:z==null?"":String(z);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(vt,{value:M,onChange:B=>_(E,S,B===""?void 0:B),t:n,placeholder:A,testidPrefix:`${D}-i18n`,candidates:s,enableExpressionTree:!0,expressionTreeCollapsible:!0})})]},S.key)}if(T==="number"){const M=z==null?"":String(z);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:B=>{const N=B.target.value;_(E,S,N===""?void 0:Number(N))},style:or})]},S.key)}if(T==="color"){const M=typeof z=="string"?z:"",B=/^#[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:B,onChange:N=>_(E,S,N.target.value),style:cz}),i.jsx("input",{type:"text","data-testid":D,value:M,placeholder:"#7C3AED",onChange:N=>_(E,S,N.target.value===""?void 0:N.target.value),style:or})]},S.key)}if(T==="number-list"){const M=Array.isArray(z)?z.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:B=>{const N=B.target.value.split(",").map(H=>H.trim()).filter(H=>H!=="").map(H=>Number(H)).filter(H=>!Number.isNaN(H));_(E,S,N)},style:or})]},S.key)}const O=z==null?"":String(z);return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("input",{type:"text","data-testid":D,value:O,placeholder:T==="icon"?n("layout_editor.array_editor.icon_placeholder"):A,onChange:M=>_(E,S,M.target.value===""?void 0:M.target.value),style:or})]},S.key)})]},E)),i.jsx("button",{type:"button","data-testid":"g7le-array-add",onClick:x,style:pz,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:Ih,children:n("layout_editor.array_editor.no_array_prop")})}const iz={display:"flex",flexDirection:"column",gap:8,width:"100%",marginBottom:12},sz={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:2},az={display:"flex",flexDirection:"column",gap:4,padding:8,border:"1px solid #e2e8f0",borderRadius:8,background:"#f8fafc"},lz={display:"flex",gap:4,alignItems:"center"},dz={fontSize:11,fontWeight:700,color:"#64748b"},Wn={display:"flex",flexWrap:"wrap",gap:6,alignItems:"center"},jn={fontSize:11,color:"#475569",minWidth:64,flexShrink:0},or={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},cz={width:32,height:28,padding:0,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",cursor:"pointer",flexShrink:0},Eh={padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},uz={padding:"2px 6px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},pz={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},Ih={fontSize:11,color:"#94a3b8",fontStyle:"italic"},fz={fontSize:11,color:"#b45309",fontStyle:"italic",padding:"4px 2px"};function gz(e,t){return e?e.startsWith("$t:")?t(e.slice(3)):e:null}function hz(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:vz,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:yz,children:o.map((r,s)=>{const a=gz(r.title,n),{title:l,...d}=r;return i.jsxs("div",{"data-testid":`g7le-array-group-${r.arrayProp??s}`,style:bz,children:[a&&i.jsx("div",{style:mz,children:a}),i.jsx($h,{...e,params:d})]},r.arrayProp??s)})})}const yz={display:"flex",flexDirection:"column",gap:16,width:"100%",marginBottom:12},bz={display:"flex",flexDirection:"column",gap:4},mz={fontSize:12,fontWeight:700,color:"#1e293b",borderBottom:"1px solid #e2e8f0",paddingBottom:4},vz={fontSize:11,color:"#94a3b8",fontStyle:"italic"},_z=/\{\{.*?\}\}/;function xz(e){return typeof e=="string"&&_z.test(e)}function wz(e,t,n){return e?e.startsWith("$t:")?t(e.slice(3)):e:n}function kz(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=wz(typeof n?.itemLabel=="string"?n.itemLabel:void 0,o,o("layout_editor.array_editor.item")),[p,f]=u.useState(null),y=s?(t.props??{})[s]:void 0,g=Array.isArray(y)?y:[],m=u.useCallback(C=>{if(!s)return;const E={...t.props??{}};E[s]=C,r({...t,props:E})},[s,t,r]),h=u.useCallback(()=>{const C=n?.newItem;return C&&typeof C=="object"?JSON.parse(JSON.stringify(C)):{[a]:"",[l]:[]}},[n,a,l]),v=u.useCallback(()=>{m([...g,h()])},[m,g,h]),b=u.useCallback(C=>{m(g.filter((E,S)=>S!==C)),f(null)},[m,g]),x=u.useCallback((C,E)=>{const S=C+E;if(S<0||S>=g.length)return;const T=[...g];[T[C],T[S]]=[T[S],T[C]],m(T)},[m,g]),k=u.useCallback((C,E)=>{const S=g.map((T,$)=>$===C?{...T,[a]:E}:T);m(S)},[g,m,a]),w=u.useCallback(C=>({type:"composite",name:"CardGridCell",children:Array.isArray(C[l])?C[l]:[]}),[l]),_=u.useCallback(C=>E=>{const S=Array.isArray(E.children)?E.children:[],T=g.map(($,A)=>A===C?{...$,[l]:S}:$);m(T)},[g,m,l]);return s?xz(y)||y!==void 0&&!Array.isArray(y)?i.jsx("div",{className:"g7le-node-editor g7le-node-editor--cell-tree","data-testid":"g7le-cell-tree-bound",style:Mz,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:Sz,children:[i.jsx("div",{style:Cz,children:o("layout_editor.cell_tree_editor.columns_title")}),g.length===0&&i.jsx("div",{"data-testid":"g7le-cell-tree-empty",style:Th,children:o("layout_editor.array_editor.empty")}),g.map((C,E)=>{const S=typeof C[a]=="string"?C[a]:"",T=p===E;return i.jsxs("div",{"data-testid":`g7le-cell-tree-row-${E}`,style:$z,children:[i.jsxs("div",{style:Ez,children:[i.jsxs("span",{style:Iz,children:["#",E+1]}),i.jsx("input",{type:"text","data-testid":`g7le-cell-tree-id-${E}`,value:S,placeholder:o("layout_editor.cell_tree_editor.id_placeholder"),onChange:$=>k(E,$.target.value),style:Az}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-up-${E}`,title:o("layout_editor.array_editor.move_up"),disabled:E===0,onClick:()=>x(E,-1),style:Ah,children:"↑"}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-down-${E}`,title:o("layout_editor.array_editor.move_down"),disabled:E===g.length-1,onClick:()=>x(E,1),style:Ah,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-remove-${E}`,title:o("layout_editor.array_editor.remove"),onClick:()=>b(E),style:Tz,children:"✕"})]}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-toggle-${E}`,onClick:()=>f(T?null:E),style:Dz,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-${E}`,style:Nz,children:i.jsx(qg,{...e,node:w(C),params:{childComponent:d},onPatchNode:_(E)})})]},E)}),i.jsx("button",{type:"button","data-testid":"g7le-cell-tree-add",onClick:v,style:zz,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:Th,children:o("layout_editor.array_editor.no_array_prop")})}const Sz={display:"flex",flexDirection:"column",gap:8,width:"100%",marginBottom:12},Cz={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:2},$z={display:"flex",flexDirection:"column",gap:6,padding:8,border:"1px solid #e2e8f0",borderRadius:8,background:"#f8fafc"},Ez={display:"flex",gap:4,alignItems:"center"},Iz={fontSize:11,fontWeight:700,color:"#64748b",flexShrink:0},Az={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},Ah={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:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#2563eb",cursor:"pointer",alignSelf:"flex-start"},Nz={paddingLeft:8,borderLeft:"2px solid #e2e8f0"},zz={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},Th={fontSize:11,color:"#94a3b8",fontStyle:"italic"},Mz={fontSize:11,color:"#b45309",fontStyle:"italic",padding:"4px 2px"};function Lz(e,t,n){const o=Be(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=tl(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 pl=26,fl=50,gl=6,Dh=44,Nh=18,zh="g7le-table-inplace-empty-cell-style";function Pz(){if(typeof document>"u"||document.getElementById(zh))return;const e=document.createElement("style");e.id=zh,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 Oz({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(()=>Lz(e,c,o),[e,c,o]),[y,g]=u.useState(null),[m,h]=u.useState(null),v=u.useMemo(()=>{if(!r)return null;for(const j of f.rows)for(const oe of j.cells){const ue=tl(e,oe,c).map(J=>`children.${J}`).join(".");if(r===ue||r.startsWith(ue+"."))return{r:oe.gridRow,c:oe.gridCol}}return null},[r,f,e,c]),b=u.useMemo(()=>y&&Ue(f,y.r,y.c)?y:v,[y,v,f]),[x,k]=u.useState(!1),[w,_]=u.useState(s==="dark"?"dark":"light"),[C,E]=u.useState(null),[S,T]=u.useState(null),$=u.useRef(null),A=u.useCallback(()=>{$.current!==null&&(clearTimeout($.current),$.current=null)},[]),z=u.useCallback(()=>{A(),$.current=setTimeout(()=>{E(null),T(null),$.current=null},240)},[A]);u.useEffect(()=>()=>A(),[A]),u.useEffect(()=>{Pz()},[]);const D=u.useCallback(j=>l(j),[l]),O=u.useMemo(()=>b?Ue(f,b.r,b.c):null,[f,b]),M=u.useMemo(()=>O&&typeof O.cell.props?.className=="string"?O.cell.props.className:"",[O]),B=u.useCallback(j=>D(nl(e,c,j)),[e,c,D]),N=u.useCallback(j=>D(Rg(e,c,j)),[e,c,D]),H=u.useCallback((j,oe)=>D(eh(e,c,j,oe)),[e,c,D]),L=u.useCallback(j=>D(nh(e,c,j)),[e,c,D]),I=u.useCallback(j=>D(oh(e,c,j)),[e,c,D]),P=u.useCallback((j,oe)=>D(th(e,c,j,oe)),[e,c,D]),F=u.useCallback(j=>{if(!O)return;const oe=O.gridRow,ue=O.gridCol,J=j==="down"?oe+O.rowSpan:oe+O.rowSpan-1,le=j==="right"?ue+O.colSpan:ue+O.colSpan-1;if(J>=f.rows.length||le>=f.colCount)return;const Ie=ol(e,c,oe,ue,J,le);Ie.ok&&D(Ie.table)},[O,f,e,c,D]),G=!!(O&&O.gridCol+O.colSpan!b||!m||!Ue(f,m.r,m.c)?null:{r0:Math.min(b.r,m.r),c0:Math.min(b.c,m.c),r1:Math.max(b.r,m.r),c1:Math.max(b.c,m.c)},[b,m,f]),Z=u.useMemo(()=>{if(!Y)return[];const j=new Set,oe=[];for(const ue of f.rows)for(const J of ue.cells)if(J.gridRow>=Y.r0&&J.gridRow<=Y.r1&&J.gridCol>=Y.c0&&J.gridCol<=Y.c1){const le=`${J.gridRow}:${J.gridCol}`;j.has(le)||(j.add(le),oe.push({r:J.gridRow,c:J.gridCol}))}return oe},[Y,f]),se=Z.length>1,re=u.useCallback(()=>{if(!Y)return;const j=ol(e,c,Y.r0,Y.c0,Y.r1,Y.c1);j.ok&&(D(j.table),h(null))},[Y,e,c,D]),U=u.useCallback(()=>{b&&D(rh(e,c,b.r,b.c))},[e,c,b,D]),ee=u.useMemo(()=>{const j=c?.cellBorder;return j&&typeof j=="object"?j:null},[c]),fe=u.useMemo(()=>{const j=c?.cellBackground;return j&&typeof j=="object"?j:null},[c]),K=u.useMemo(()=>{const j=c?.cellPadding;return j&&typeof j=="object"?j:null},[c]),ne=u.useMemo(()=>{if(x){const j=new Set,oe=[];for(const ue of f.rows)for(const J of ue.cells){const le=`${J.gridRow}:${J.gridCol}`;j.has(le)||(j.add(le),oe.push({r:J.gridRow,c:J.gridCol}))}return oe}return se?Z:b?[{r:b.r,c:b.c}]:[]},[x,se,Z,b,f]),me=u.useCallback(j=>{if(ne.length===0)return;let oe=e;for(const ue of ne){const J=(ee?.colors??[]).map(Ie=>Ie.token),le=j.split(/\s+/).filter(Ie=>Ie&&!J.includes(Ie)).join(" ");oe=Ci(oe,c,ue.r,ue.c,le)}D(oe)},[e,c,ne,ee,D]),Ce=u.useMemo(()=>{const j=(ee?.sides??[]).find(J=>J.value==="all")??(ee?.sides??[])[0],oe=(ee?.widths??[]).find(J=>J.value!=="none");if(!j||!oe)return[];const ue=oe.suffix??"";return[ue?`${j.prefix}${ue}`:j.prefix]},[ee]),ze=u.useCallback((j,oe,ue)=>{if(Ce.length===0)return j;const J=(ee?.sides??[]).map(Oe=>Oe.prefix),le=Ue(Be(j,c),oe,ue),dt=(typeof le?.cell?.props?.className=="string"?le.cell.props.className:"").split(/\s+/).filter(Boolean);if(dt.some(Oe=>J.some(He=>Oe===He||Oe.startsWith(He+"-")&&/^-?\d+$/.test(Oe.slice(He.length+1)))))return j;const ot=[...dt,...Ce].join(" ").trim();return Ci(j,c,oe,ue,ot)},[Ce,ee,c]),Se=u.useCallback((j,oe)=>{if(j.length===0)return;const ue=new Set(j.map(le=>`${le.r}:${le.c}`));let J=e;for(const le of j){if(J=ze(J,le.r,le.c),J=Jt(J,c,le.r,le.c,"borderColor",oe),le.r>0&&!ue.has(`${le.r-1}:${le.c}`)){const Ie=Ue(Be(J,c),le.r-1,le.c);Ie&&(J=Jt(J,c,Ie.gridRow,Ie.gridCol,"borderBottomColor",oe))}if(le.c>0&&!ue.has(`${le.r}:${le.c-1}`)){const Ie=Ue(Be(J,c),le.r,le.c-1);Ie&&(J=Jt(J,c,Ie.gridRow,Ie.gridCol,"borderRightColor",oe))}}D(J)},[e,c,D,ze]),qe=u.useMemo(()=>(ee?.colors??[]).map(j=>j.token).filter(Boolean),[ee]),De=u.useCallback(j=>{if(ne.length===0||qe.length===0)return;let oe=e;for(const ue of ne)oe=ze(oe,ue.r,ue.c),oe=go(oe,c,ue.r,ue.c,j,qe,w);D(oe)},[ne,e,c,D,ze,qe,w]),Pe=u.useCallback(j=>Se(ne,j),[Se,ne]),Qe=u.useMemo(()=>{if(w==="dark")return"";const j=O?.cell.props?.style;return typeof j?.borderColor=="string"?j.borderColor:""},[O,w]),Me=u.useCallback((j,oe)=>{if(ne.length===0)return;let ue=e;for(const J of ne)ue=Jt(ue,c,J.r,J.c,j,oe);D(ue)},[ne,e,c,D]),Re=u.useMemo(()=>(fe?.colors??[]).map(j=>j.token).filter(j=>!!j),[fe]),ve=u.useCallback(j=>{if(ne.length===0||Re.length===0)return;let oe=e;for(const ue of ne)oe=go(oe,c,ue.r,ue.c,j,Re,w);D(oe)},[ne,e,c,D,Re,w]),te=u.useCallback(j=>Me("backgroundColor",j),[Me]),he=u.useCallback(()=>{if(ne.length===0)return;let j=e;for(const oe of ne)j=go(j,c,oe.r,oe.c,void 0,Re,w),w==="light"&&(j=Jt(j,c,oe.r,oe.c,"backgroundColor",void 0));D(j)},[ne,e,c,D,Re,w]),Q=u.useCallback(j=>Me("padding",j),[Me]),ie=u.useMemo(()=>{if(w==="dark")return"";const j=O?.cell.props?.style;return typeof j?.backgroundColor=="string"?j.backgroundColor:""},[O,w]),_e=u.useMemo(()=>typeof O?.cell.props?.className=="string"?O.cell.props.className:"",[O]),ge=u.useMemo(()=>{const j=O?.cell.props?.style;return typeof j?.padding=="string"?j.padding:""},[O]),Ae=u.useCallback(j=>{const oe=j.currentTarget,ue=oe.style.pointerEvents;oe.style.pointerEvents="none";const J=document.elementFromPoint(j.clientX,j.clientY);oe.style.pointerEvents=ue;const le=J?.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}))},[]),Ne=u.useMemo(()=>{const j=new Map;for(const oe of p)j.has(oe.ref.gridCol)||j.set(oe.ref.gridCol,oe.box);return j},[p]),Le=u.useMemo(()=>{const j=new Map;for(const oe of p)j.has(oe.ref.gridRow)||j.set(oe.ref.gridRow,oe.box);return j},[p]);if(p.length===0)return null;const q=!!(O&&(O.colSpan>1||O.rowSpan>1)),ae=S!==null?S:b?.c??null,pe=C!==null?C:b?.r??null,$e=n.top-pl-gl-Dh,be=n.left-fl-gl-Dh;return i.jsxs("div",{className:"g7le-table-inplace","data-testid":"g7le-table-inplace",style:{position:"absolute",inset:0,pointerEvents:"none",zIndex:g7},children:[p.map(j=>{const oe=b&&b.r===j.ref.gridRow&&b.c===j.ref.gridCol,ue=Y&&j.ref.gridRow>=Y.r0&&j.ref.gridRow<=Y.r1&&j.ref.gridCol>=Y.c0&&j.ref.gridCol<=Y.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(),E(j.ref.gridRow),T(j.ref.gridCol)},onMouseLeave:()=>{z()},onPointerDown:J=>Ae(J),onClick:J=>{if(J.stopPropagation(),J.shiftKey&&(y||b))h({r:j.ref.gridRow,c:j.ref.gridCol});else{g({r:j.ref.gridRow,c:j.ref.gridCol}),h(null);const le=tl(e,j.ref,c).map(Ie=>`children.${Ie}`).join(".");d?.(le)}},style:{position:"absolute",top:j.box.top,left:j.box.left,width:j.box.width,height:j.box.height,minWidth:Nh,minHeight:Nh,boxSizing:"border-box",pointerEvents:"auto",cursor:"pointer",outline:oe?"2px solid #2563eb":"none",outlineOffset:-2,background:ue&&!oe?"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:z,style:{position:"absolute",top:$e,left:n.left,width:n.width,height:pl,pointerEvents:"none"},children:ae!==null&&Ne.has(ae)&&(()=>{const j=ae,oe=Ne.get(j),ue=wi(f,j,-1),J=wi(f,j,1),le=oe.left-n.left;return i.jsxs("div",{"data-testid":`g7le-inplace-colgutter-${j}`,onMouseEnter:()=>{A(),T(j)},onMouseLeave:z,style:{position:"absolute",top:0,left:le,width:oe.width,minWidth:96,height:pl,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:!ue.ok,onClick:()=>P(j,-1),"data-testid":`g7le-inplace-col-left-${j}`,style:ue.ok?_n:Ei,children:"←"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.add_col"),onClick:()=>L(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:Mh,children:"✕"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.move_col_right"),disabled:!J.ok,onClick:()=>P(j,1),"data-testid":`g7le-inplace-col-right-${j}`,style:J.ok?_n:Ei,children:"→"})]},`colgut-${j}`)})()}),i.jsx("div",{"data-testid":"g7le-inplace-row-rail",style:{position:"absolute",top:n.top,left:be,width:fl,height:n.height,pointerEvents:"none"},children:pe!==null&&Le.has(pe)&&(()=>{const j=pe,oe=Le.get(j),ue=xi(f,j,-1),J=xi(f,j,1),le=oe.top-n.top;return i.jsxs("div",{"data-testid":`g7le-inplace-rowgutter-${j}`,onMouseEnter:()=>{A(),E(j)},onMouseLeave:z,style:{position:"absolute",top:le,left:0,width:fl,height:oe.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:!ue.ok,onClick:()=>H(j,-1),"data-testid":`g7le-inplace-row-up-${j}`,style:ue.ok?_n:Ei,children:"↑"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.add_row"),onClick:()=>B(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:()=>N(j),"data-testid":`g7le-inplace-row-remove-${j}`,style:Mh,children:"✕"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.move_row_down"),disabled:!J.ok,onClick:()=>H(j,1),"data-testid":`g7le-inplace-row-down-${j}`,style:J.ok?_n:Ei,children:"↓"})]},`rowgut-${j}`)})()}),i.jsxs("div",{"data-testid":"g7le-inplace-corner-add",style:{position:"absolute",top:n.top+n.height+gl,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:()=>B(f.rows.length-1),style:Lh,children:["+ ",a("layout_editor.table_inplace.add_row")]}),i.jsxs("button",{type:"button","data-testid":"g7le-inplace-add-col-right",onClick:()=>L(f.colCount-1),style:Lh,children:["+ ",a("layout_editor.table_inplace.add_col")]})]}),!b&&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")}),b&&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:re,style:rr,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:!G,onClick:()=>F("right"),style:G?rr:hl,children:a("layout_editor.table_inplace.merge_right")}),i.jsx("button",{type:"button","data-testid":"g7le-inplace-merge-down",disabled:!V,onClick:()=>F("down"),style:V?rr:hl,children:a("layout_editor.table_inplace.merge_down")})]}),i.jsx("button",{type:"button","data-testid":"g7le-inplace-unmerge",disabled:!q,onClick:U,style:q?rr:hl,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:x,onChange:j=>k(j.target.checked)}),a("layout_editor.table_inplace.border_apply_all")]}),i.jsx(yh,{colorScheme:w,onChange:_,t:a}),ee&&i.jsx("div",{"data-testid":"g7le-inplace-cell-border",children:i.jsx(dh,{className:x?"":M,catalog:ee,t:a,onChange:me,colorScheme:w,onPresetToken:De,colorStyle:x?"":Qe,onColorStyle:Pe})}),i.jsx("div",{"data-testid":"g7le-inplace-cell-fill",children:i.jsx(fh,{colorStyle:x?"":ie,className:x?"":_e,catalog:fe,t:a,colorScheme:w,onPresetToken:ve,onCustomColor:te,onClear:he})})]}),i.jsx("div",{"data-testid":"g7le-inplace-cell-padding",style:{borderTop:"1px solid #f1f5f9",paddingTop:6},children:i.jsx(gh,{paddingStyle:x?"":ge,catalog:K,t:a,onChange:Q})})]})]})]})}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)"},Mh={..._n,border:"1px solid #fecaca",color:"#dc2626"},Ei={..._n,cursor:"not-allowed",opacity:.4,color:"#94a3b8",borderColor:"#e2e8f0"},rr={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)"},hl={...rr,cursor:"not-allowed",opacity:.4},Lh={padding:"3px 8px",fontSize:11,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"};let Ph=!1;function Bz(){Ph||(Pn("children",qg),Pn("table",T8),Pn("array",$h),Pn("array-group",hz),Pn("array-cell-tree",kz),Oa("table",Oz),Ph=!0)}function Wz(){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:Xe,registerNodeEditor:Pn,registerCanvasOverlay:Oa,onReady:r=>{typeof r=="function"&&r()}};for(const r of n){const[s,...a]=r;try{s==="widget"?Xe(a[0],a[1]):s==="nodeEditor"?Pn(a[0],a[1]):s==="canvasOverlay"&&Oa(a[0],a[1])}catch{}}for(const r of o)try{r()}catch{}}const jz=1280;qN(),Bz(),Wz();async function Hz(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:je()});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 Fz({templateIdentifier:e}){gD({templateIdentifier:e}),hD(e);const{state:t,dispatch:n}=Je(),{t:o}=tt(),r=yo(),s=Cp(),a=xD(),l=t.selectedRoute?.layoutName??null,d=CD(e,l),c=t.editMode==="extension",p=u.useMemo(()=>c?kD(a):s,[c,a,s]),[f,y]=u.useState(null),[g,m]=u.useState(null),[h,v]=u.useState([]),[b,x]=u.useState("user"),[k,w]=u.useState(null),[_,C]=u.useState(null),[E,S]=u.useState([]);u.useEffect(()=>{let te=!1;return(async()=>{try{const he=await fetch(en(`/api/templates/${encodeURIComponent(e)}/components`,"json"),{credentials:"same-origin",headers:{Accept:"application/json"}});if(!he.ok)return;const Q=await he.json().catch(()=>null);!te&&Q&&typeof Q=="object"&&y(Q)}catch{}})(),()=>{te=!0}},[e]),u.useEffect(()=>{let te=!1;return(async()=>{const{spec:he,sampleGlobalSources:Q}=await eb({templateIdentifier:e,coreSeed:$D()});te||(m(he),v(Q),Vz(e,he,Q))})(),()=>{te=!0}},[e]),u.useEffect(()=>{let te=!1;return(async()=>{if(typeof fetch=="function")try{const he=await fetch(`/api/admin/templates/${encodeURIComponent(e)}`,{credentials:"same-origin",headers:je()});if(!he.ok)return;const ie=(await he.json().catch(()=>null))?.data,_e=ie?.type;te||((_e==="admin"||_e==="user")&&x(_e),typeof ie?.name=="string"&&ie.name&&w(ie.name),typeof ie?.version=="string"&&ie.version&&C(ie.version))}catch{}})(),()=>{te=!0}},[e]),u.useEffect(()=>{let te=!1;return(async()=>{if(typeof fetch=="function")try{const he=await fetch("/api/admin/templates/?per_page=100&page=1",{credentials:"same-origin",headers:je()});if(!he.ok)return;const ie=(await he.json().catch(()=>null))?.data?.data;if(!te&&Array.isArray(ie)){const _e=[];for(const ge of ie){if(!ge||typeof ge!="object")continue;const Ae=ge.identifier;if(typeof Ae!="string"||!Ae||ge.is_pending===!0)continue;const Le=ge.type==="admin"?"admin":"user",q=ge.name,ae=ge.version;_e.push({identifier:Ae,name:typeof q=="string"?q:Ae,version:typeof ae=="string"?ae:"",type:Le})}S(_e)}}catch{}})(),()=>{te=!0}},[e]);const T=g?.nesting??null,$=t.selectedRoute?.path??null,A=t.editMode,z=t.selectedRoute?.layoutName??(c?a.document?.hostLayoutName??null:null),D=t.routeTree,O=u.useMemo(()=>{if(A!=="extension"||!z)return null;const te=bl(D,z);return te||`__base__/${z}`},[A,z,D]),M=c&&t.returnRoute===null&&!!z;u.useEffect(()=>{if(!M||!z)return;const te=bl(D,z);te&&n({type:"SET_RETURN_ROUTE",route:{path:te,layoutName:z}})},[M,z,D,n]),u.useEffect(()=>{const te=G4(A,$,O),he=Y4(g?.states?.groups,te);n({type:"SET_AVAILABLE_STATES",states:he,activeStateId:X4(he)})},[g,A,$,O,n]);const[B,N]=u.useState([]);u.useEffect(()=>{let te=!1;return(async()=>{const he=await Hz(e);te||N(he)})(),()=>{te=!0}},[e]),yD(),bD();const H=u.useCallback(te=>{const he=t.routeTree,Q=te.split("?")[0]?.split("#")[0]??te;return Kz(he,Q)?"route_in_tree":"route_not_in_tree"},[t.routeTree]),L=u.useCallback(te=>{const he=te.split("?")[0]?.split("#")[0]??te,Q=yl(t.routeTree,he);Q&&(p.isDirty&&!(!(typeof window<"u")||window.confirm(o("layout_editor.chrome.dirty_guard.message")))||n({type:"SELECT_ROUTE",route:{path:Q.path,layoutName:Q.layoutName}}))},[t.routeTree,p.isDirty,n]),I=u.useRef([]),P=u.useCallback(te=>{I.current=te},[]),[F,G]=u.useState(null),V=u.useCallback(()=>G(null),[]),Y=u.useRef(null),Z=u.useRef(null);u.useEffect(()=>{const te=Z.current,he=Y.current;if(!te||!he||typeof ResizeObserver>"u")return;const Q=()=>{he.style.setProperty("--g7le-header-h",`${Math.round(te.getBoundingClientRect().height)}px`)};Q();const ie=new ResizeObserver(Q);return ie.observe(te),()=>ie.disconnect()},[]);const se=u.useCallback(()=>{p.reload()},[p]),re=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/${b}`,target:"_self"}})},[p.isDirty,o,b]),U=u.useCallback(te=>{if(!te||te===e||p.isDirty&&!(typeof window<"u"?window.confirm(o("layout_editor.chrome.dirty_guard.message")):!0))return;const he=Zs(te);window.G7Core?.dispatch?.({handler:"openWindow",params:{path:he,target:"_self"}})},[e,p.isDirty,o]),ee=u.useCallback(()=>{const te=ME(e,t.selectedRoute?.path??null);window.G7Core?.dispatch?.({handler:"openWindow",params:{path:te}})},[e,t.selectedRoute]),fe=u.useCallback(()=>{const te=t.selectedRoute?.layoutName??"";if(!te)return;const he=r.open({ariaLabel:o("layout_editor.attachment_manager.title"),width:720,maxHeightRatio:.82,content:u.createElement(Ml,{templateIdentifier:e,layoutName:te,t:o,onClose:()=>r.close(he)})})},[r,e,t.selectedRoute,o]),K=u.useCallback(()=>{const te=t.selectedRoute?.layoutName??"";if(!te)return;const he=Hy(s.document?.raw??{}),Q=r.open({ariaLabel:o("layout_editor.translation_manager.title"),width:720,maxHeightRatio:.82,content:u.createElement(dm,{templateIdentifier:e,layoutName:te,t:o,referencedKeys:he,onClose:()=>r.close(Q)})})},[r,e,t.selectedRoute,o,s.document]),ne=u.useCallback((te,he)=>{const Q=window.G7Core;if(Q&&typeof Q.t=="function"){const ie=Q.t(te,he);if(ie&&ie!==te&&!ie.startsWith("$t:"))return ie}return o(te,he)},[o]),me=u.useCallback(()=>{if(!t.selectedRoute||t.editMode==="extension"||t.editMode==="iteration_item")return;const te=r.open({ariaLabel:o("layout_editor.page_settings.title",{name:t.selectedRoute.path??""}),width:1080,maxHeightRatio:.88,closeOnEscape:!1,content:u.createElement(u$,{templateIdentifier:e,spec:g,t:o,resolveLabel:ne,permissionCandidates:B,onClose:()=>r.close(te)})})},[r,t.selectedRoute,t.editMode,o,ne,e,g,B]),Ce=u.useCallback(async()=>{const te=await d.createPreview(s.document?.raw??null);if(te.kind!=="success"){const he=te.kind==="network_error"?te.message:o("layout_editor.preview_action.no_document");typeof window<"u"&&window.alert(he)}},[d,s.document,o]),ze=u.useCallback(()=>{const te=t.selectedRoute?.layoutName??"",he=t.selectedRoute?.path??"",Q=t.editMode==="extension"&&he.startsWith("__extension__/")?he.slice(14):null,ie=Q?{kind:"extension",extensionId:Q}:te?{kind:"layout",layoutName:te}:null;if(!ie)return;const _e=r.open({ariaLabel:o("layout_editor.version_history.title"),width:640,maxHeightRatio:.82,content:u.createElement(X$,{templateIdentifier:e,target:ie,t:o,onRestored:async ge=>{typeof ge=="number"&&(ie.kind==="extension"?n({type:"SET_EXTENSION_VERSION",extensionId:ie.extensionId,version:ge}):n({type:"SET_LAYOUT_VERSION",layoutName:ie.layoutName,version:ge})),await p.reload()},onClose:()=>r.close(_e)})})},[r,e,t.selectedRoute,t.editMode,o,p,n]),Se=p.dirtyKeys.size>0||p.isDirty;u.useEffect(()=>{if(!Se)return;const te=he=>{he.preventDefault(),he.returnValue=""};return window.addEventListener("beforeunload",te),()=>window.removeEventListener("beforeunload",te)},[Se]);const qe=u.useCallback(()=>{!p.isDirty||!(!(typeof window<"u")||window.confirm(o("layout_editor.chrome.reset_guard.message")))||p.reload()},[p,o]),De=u.useCallback(async()=>{const te=await p.save({sessionAddedPaths:I.current});G(te),te.kind==="success"&&typeof te.newContentVersion=="number"&&(te.savedExtensionId?n({type:"SET_EXTENSION_VERSION",extensionId:te.savedExtensionId,version:te.newContentVersion}):te.savedLayoutName&&n({type:"SET_LAYOUT_VERSION",layoutName:te.savedLayoutName,version:te.newContentVersion}))},[p,n]),Pe=u.useCallback(()=>{const te=r.open({ariaLabel:o("layout_editor.shortcuts.title"),width:560,maxHeightRatio:.85,content:u.createElement(iE,{t:o,onClose:()=>r.close(te)})})},[r,o]),Qe=u.useMemo(()=>({save:()=>{De()},exit:re,editCode:ee,reset:qe,translations:K,addElement:()=>{t.selectedRoute&&n({type:"TOGGLE_PALETTE"})},help:Pe,preview:()=>{t.selectedRoute?.layoutName&&Ce()}}),[De,re,ee,qe,K,t.selectedRoute,n,Pe,Ce]),[Me,Re]=u.useState(!1);u.useEffect(()=>{const te=window.setInterval(()=>{Re(!!window.__g7LayoutEditorHasSelection)},200);return()=>window.clearInterval(te)},[]),np({handlers:Qe,hasSelection:Me});const ve=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(Fa,{error:t.routesError})}):i.jsx("div",{className:"g7le-chrome","data-testid":"g7le-chrome",ref:Y,style:{position:"static",minHeight:"100vh",minWidth:jz,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(dy,{value:ve,children:[c&&a.needsHostPicker&&a.document&&i.jsx(SD,{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(by,{onSave:()=>{De()},isDirty:p.isDirty,onExit:re,onEditCode:ee,onManageImages:fe,onManageTranslations:K,onPageSettings:me,onReset:qe,onShowShortcuts:Pe,onPreview:Ce,onShowVersions:ze,templateName:k,templateVersion:_,templateList:E,onSwitchTemplate:U}),i.jsx(xE,{result:F,onDismiss:V,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(U4,{}),i.jsx(q4,{})]})]}),i.jsxs("div",{className:"g7le-chrome__body",style:{display:"grid",gridTemplateColumns:"auto 1fr",alignItems:"stretch"},children:[i.jsx(HE,{}),i.jsx(j4,{manifest:f,nesting:T,componentPalette:g?.componentPalette??null,spec:g,permissionCandidates:B,sampleGlobalSources:h,resolveRouteMatch:H,onNavigateToDestination:L,onSessionAddedPathsChange:P})]}),i.jsx(py,{})]})})}function yl(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=yl(n.children,t);if(o)return o}}return null}function Kz(e,t){return yl(e,t)!==null}function bl(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=bl(n.children,t);if(o)return o}}return null}function Vz(e,t,n){const o=[];Va({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;Qh({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 Oh({templateIdentifier:e,initialLocale:t}){return u.useEffect(()=>()=>{Vh(),qh(),Yh(),Xh(),Jh(),Zh(),Rh(),ey(),ty()},[]),i.jsx(ly,{templateIdentifier:e,initialLocale:t,children:i.jsx(uy,{children:i.jsx(Fz,{templateIdentifier:e})})})}if(typeof window<"u"){const e=window.G7Core||(window.G7Core={});if(e.__LayoutEditorChrome=Oh,typeof e.__onChromeReady=="function")try{e.__onChromeReady()}catch{}}dn.LayoutEditorChrome=Oh,Object.defineProperty(dn,Symbol.toStringTag,{value:"Module"})})(this.G7LayoutEditor=this.G7LayoutEditor||{},ReactJSXRuntime,React,ReactDOM); + `},O7={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 B7(e){let{announcements:t=O7,container:n,hiddenTextDescribedById:o,screenReaderInstructions:r=P7}=e;const{announce:s,announcement:a}=z7(),l=ei("DndLiveRegion"),[d,c]=u.useState(!1);if(u.useEffect(()=>{c(!0)},[]),M7(u.useMemo(()=>({onDragStart(f){let{active:y}=f;s(t.onDragStart({active:y}))},onDragMove(f){let{active:y,over:g}=f;t.onDragMove&&s(t.onDragMove({active:y,over:g}))},onDragOver(f){let{active:y,over:g}=f;s(t.onDragOver({active:y,over:g}))},onDragEnd(f){let{active:y,over:g}=f;s(t.onDragEnd({active:y,over:g}))},onDragCancel(f){let{active:y,over:g}=f;s(t.onDragCancel({active:y,over:g}))}}),[s,t])),!d)return null;const p=u.createElement(u.Fragment,null,u.createElement(D7,{id:o,value:r.draggable}),u.createElement(N7,{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 oi(){}function W7(e,t){return u.useMemo(()=>({sensor:e,options:t??{}}),[e,t])}function j7(){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 H7(e,t){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function F7(e,t){const n=ni(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 K7(e,t){let{data:{value:n}}=e,{data:{value:o}}=t;return n-o}function V7(e,t){let{data:{value:n}}=e,{data:{value:o}}=t;return o-n}function U7(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 q7(e,t){if(!e||e.length===0)return null;const[n]=e;return n[t]}function G7(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=G7(l,t);d>0&&r.push({id:a,data:{droppableContainer:s,value:d}})}}return r.sort(V7)};function X7(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 J7=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&&X7(o,l)){const c=U7(l).reduce((f,y)=>f+H7(o,y),0),p=Number((c/4).toFixed(4));r.push({id:a,data:{droppableContainer:s,value:p}})}}return r.sort(K7)};function Z7(e,t,n){return{...e,scaleX:t&&n?t.width/n.width:1,scaleY:t&&n?t.height/n.height:1}}function Kp(e,t){return e&&t?{x:e.left-t.left,y:e.top-t.top}:Ht}function Q7(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 R7=Q7(1);function Vp(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 e2(e,t,n){const o=Vp(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 t2={ignoreTransform:!1};function Ho(e,t){t===void 0&&(t=t2);let n=e.getBoundingClientRect();if(t.ignoreTransform){const{transform:c,transformOrigin:p}=_t(e).getComputedStyle(e);c&&(n=e2(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 Up(e){return Ho(e,{ignoreTransform:!0})}function n2(e){const t=e.innerWidth,n=e.innerHeight;return{top:0,left:0,right:t,bottom:n,width:t,height:n}}function o2(e,t){return t===void 0&&(t=_t(e).getComputedStyle(e)),t.position==="fixed"}function r2(e,t){t===void 0&&(t=_t(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 da(e,t){const n=[];function o(r){if(t!=null&&n.length>=t||!r)return n;if(sa(r)&&r.scrollingElement!=null&&!n.includes(r.scrollingElement))return n.push(r.scrollingElement),n;if(!Oo(r)||Wp(r)||n.includes(r))return n;const s=_t(e).getComputedStyle(r);return r!==e&&r2(r,s)&&n.push(r),o2(r,s)?n:o(r.parentNode)}return e?o(e):n}function qp(e){const[t]=da(e,1);return t??null}function ca(e){return!Jr||!e?null:lo(e)?e:ia(e)?sa(e)||e===co(e).scrollingElement?window:Oo(e)?e:null:null}function Gp(e){return lo(e)?e.scrollX:e.scrollLeft}function Yp(e){return lo(e)?e.scrollY:e.scrollTop}function ua(e){return{x:Gp(e),y:Yp(e)}}var lt;(function(e){e[e.Forward=1]="Forward",e[e.Backward=-1]="Backward"})(lt||(lt={}));function Xp(e){return!Jr||!e?!1:e===document.scrollingElement}function Jp(e){const t={x:0,y:0},n=Xp(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 i2={x:.2,y:.2};function s2(e,t,n,o,r){let{top:s,left:a,right:l,bottom:d}=n;o===void 0&&(o=10),r===void 0&&(r=i2);const{isTop:c,isBottom:p,isLeft:f,isRight:y}=Jp(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)),!y&&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 a2(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 Zp(e){return e.reduce((t,n)=>uo(t,ua(n)),Ht)}function l2(e){return e.reduce((t,n)=>t+Gp(n),0)}function d2(e){return e.reduce((t,n)=>t+Yp(n),0)}function Qp(e,t){if(t===void 0&&(t=Ho),!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 c2=[["x",["left","right"],l2],["y",["top","bottom"],d2]];class pa{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=da(n),r=Zp(o);this.rect={...t},this.width=t.width,this.height=t.height;for(const[s,a,l]of c2)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 Fo{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 u2(e){const{EventTarget:t}=_t(e);return e instanceof t?e:co(e)}function fa(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 Rp(e){e.preventDefault()}function p2(e){e.stopPropagation()}var Ke;(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"})(Ke||(Ke={}));const ef={start:[Ke.Space,Ke.Enter],cancel:[Ke.Esc],end:[Ke.Space,Ke.Enter,Ke.Tab]},f2=(e,t)=>{let{currentCoordinates:n}=t;switch(e.code){case Ke.Right:return{...n,x:n.x+25};case Ke.Left:return{...n,x:n.x-25};case Ke.Down:return{...n,y:n.y+25};case Ke.Up:return{...n,y:n.y-25}}};class tf{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 Fo(co(n)),this.windowListeners=new Fo(_t(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&&Qp(o),n(Ht)}handleKeyDown(t){if(la(t)){const{active:n,context:o,options:r}=this.props,{keyboardCodes:s=ef,coordinateGetter:a=f2,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 y=ti(f,p),g={x:0,y:0},{scrollableAncestors:m}=o.current;for(const h of m){const v=t.code,{isTop:b,isRight:x,isLeft:k,isBottom:w,maxScroll:_,minScroll:C}=Jp(h),E=a2(h),S={x:Math.min(v===Ke.Right?E.right-E.width/2:E.right,Math.max(v===Ke.Right?E.left:E.left+E.width/2,f.x)),y:Math.min(v===Ke.Down?E.bottom-E.height/2:E.bottom,Math.max(v===Ke.Down?E.top:E.top+E.height/2,f.y))},T=v===Ke.Right&&!x||v===Ke.Left&&!k,$=v===Ke.Down&&!w||v===Ke.Up&&!b;if(T&&S.x!==f.x){const A=h.scrollLeft+y.x,z=v===Ke.Right&&A<=_.x||v===Ke.Left&&A>=C.x;if(z&&!y.y){h.scrollTo({left:A,behavior:l});return}z?g.x=h.scrollLeft-A:g.x=v===Ke.Right?h.scrollLeft-_.x:h.scrollLeft-C.x,g.x&&h.scrollBy({left:-g.x,behavior:l});break}else if($&&S.y!==f.y){const A=h.scrollTop+y.y,z=v===Ke.Down&&A<=_.y||v===Ke.Up&&A>=C.y;if(z&&!y.x){h.scrollTo({top:A,behavior:l});return}z?g.y=h.scrollTop-A:g.y=v===Ke.Down?h.scrollTop-_.y:h.scrollTop-C.y,g.y&&h.scrollBy({top:-g.y,behavior:l});break}}this.handleMove(t,uo(ti(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()}}tf.activators=[{eventName:"onKeyDown",handler:(e,t,n)=>{let{keyboardCodes:o=ef,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 nf(e){return!!(e&&"distance"in e)}function of(e){return!!(e&&"delay"in e)}class ga{constructor(t,n,o){var r;o===void 0&&(o=u2(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=co(a),this.documentListeners=new Fo(this.document),this.listeners=new Fo(o),this.windowListeners=new Fo(_t(a)),this.initialCoordinates=(r=ni(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,Rp),this.windowListeners.add(At.VisibilityChange,this.handleCancel),this.windowListeners.add(At.ContextMenu,Rp),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(of(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(nf(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,p2,{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=ni(t))!=null?n:Ht,c=ti(r,d);if(!o&&l){if(nf(l)){if(l.tolerance!=null&&fa(c,l.tolerance))return this.handleCancel();if(fa(c,l.distance))return this.handleStart()}if(of(l)&&fa(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===Ke.Esc&&this.handleCancel()}removeTextSelection(){var t;(t=this.document.getSelection())==null||t.removeAllRanges()}}const g2={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class ha extends ga{constructor(t){const{event:n}=t,o=co(n.target);super(t,g2,o)}}ha.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 ya;(function(e){e[e.RightClick=2]="RightClick"})(ya||(ya={}));class y2 extends ga{constructor(t){super(t,h2,co(t.event.target))}}y2.activators=[{eventName:"onMouseDown",handler:(e,t)=>{let{nativeEvent:n}=e,{onActivation:o}=t;return n.button===ya.RightClick?!1:(o?.({event:n}),!0)}}];const ba={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class b2 extends ga{constructor(t){super(t,ba)}static setup(){return window.addEventListener(ba.move.name,t,{capture:!1,passive:!1}),function(){window.removeEventListener(ba.move.name,t)};function t(){}}}b2.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 Ko;(function(e){e[e.Pointer=0]="Pointer",e[e.DraggableRect=1]="DraggableRect"})(Ko||(Ko={}));var ri;(function(e){e[e.TreeOrder=0]="TreeOrder",e[e.ReversedTreeOrder=1]="ReversedTreeOrder"})(ri||(ri={}));function m2(e){let{acceleration:t,activator:n=Ko.Pointer,canScroll:o,draggingRect:r,enabled:s,interval:a=5,order:l=ri.TreeOrder,pointerCoordinates:d,scrollableAncestors:c,scrollableAncestorRects:p,delta:f,threshold:y}=e;const g=_2({delta:f,disabled:!s}),[m,h]=$7(),v=u.useRef({x:0,y:0}),b=u.useRef({x:0,y:0}),x=u.useMemo(()=>{switch(n){case Ko.Pointer:return d?{top:d.y,bottom:d.y,left:d.x,right:d.x}:null;case Ko.DraggableRect:return r}},[n,r,d]),k=u.useRef(null),w=u.useCallback(()=>{const C=k.current;if(!C)return;const E=v.current.x*b.current.x,S=v.current.y*b.current.y;C.scrollBy(E,S)},[]),_=u.useMemo(()=>l===ri.TreeOrder?[...c].reverse():c,[l,c]);u.useEffect(()=>{if(!s||!c.length||!x){h();return}for(const C of _){if(o?.(C)===!1)continue;const E=c.indexOf(C),S=p[E];if(!S)continue;const{direction:T,speed:$}=s2(C,S,x,t,y);for(const A of["x","y"])g[A][T[A]]||($[A]=0,T[A]=0);if($.x>0||$.y>0){h(),k.current=C,m(w,a),v.current=$,b.current=T;return}}v.current={x:0,y:0},b.current={x:0,y:0},h()},[t,w,o,h,s,a,JSON.stringify(x),JSON.stringify(g),m,c,_,p,JSON.stringify(y)])}const v2={x:{[lt.Backward]:!1,[lt.Forward]:!1},y:{[lt.Backward]:!1,[lt.Forward]:!1}};function _2(e){let{delta:t,disabled:n}=e;const o=Rr(t);return Wo(r=>{if(n||!o||!r)return v2;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 x2(e,t){const n=t!=null?e.get(t):void 0,o=n?n.node.current:null;return Wo(r=>{var s;return t==null?null:(s=o??r)!=null?s:null},[o,t])}function w2(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 Vo;(function(e){e[e.Always=0]="Always",e[e.BeforeDragging=1]="BeforeDragging",e[e.WhileDragging=2]="WhileDragging"})(Vo||(Vo={}));var ma;(function(e){e.Optimized="optimized"})(ma||(ma={}));const rf=new Map;function k2(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(),y=Bo(f),g=u.useCallback(function(b){b===void 0&&(b=[]),!y.current&&a(x=>x===null?b:x.concat(b.filter(k=>!x.includes(k))))},[y]),m=u.useRef(null),h=Wo(b=>{if(f&&!n)return rf;if(!b||b===rf||p.current!==e||s!=null){const x=new Map;for(let k of e){if(!k)continue;if(s&&s.length>0&&!s.includes(k.id)&&k.rect.current){x.set(k.id,k.rect.current);continue}const w=k.node.current,_=w?new pa(d(w),w):null;k.rect.current=_,_&&x.set(k.id,_)}return x}return b},[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 Vo.Always:return!1;case Vo.BeforeDragging:return n;default:return!n}}}function va(e,t){return Wo(n=>e?n||(typeof t=="function"?t(e):e):null,[t,e])}function S2(e,t){return va(e,t)}function C2(e){let{callback:t,disabled:n}=e;const o=Zr(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 ii(e){let{callback:t,disabled:n}=e;const o=Zr(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 $2(e){return new pa(Ho(e),e)}function sf(e,t,n){t===void 0&&(t=$2);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=C2({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=ii({callback:s});return sn(()=>{s(),e?(l?.observe(e),a?.observe(document.body,{childList:!0,subtree:!0})):(l?.disconnect(),a?.disconnect())},[e]),o}function E2(e){const t=va(e);return Kp(e,t)}const af=[];function I2(e){const t=u.useRef(e),n=Wo(o=>e?o&&o!==af&&e&&t.current&&e.parentNode===t.current.parentNode?o:da(e):af,[e]);return u.useEffect(()=>{t.current=e},[e]),n}function A2(e){const[t,n]=u.useState(null),o=u.useRef(e),r=u.useCallback(s=>{const a=ca(s.target);a&&n(l=>l?(l.set(a,ua(a)),new Map(l)):null)},[]);return u.useEffect(()=>{const s=o.current;if(e!==s){a(s);const l=e.map(d=>{const c=ca(d);return c?(c.addEventListener("scroll",r,{passive:!0}),[c,ua(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=ca(d);c?.removeEventListener("scroll",r)})}},[r,e]),u.useMemo(()=>e.length?t?Array.from(t.values()).reduce((s,a)=>uo(s,a),Ht):Zp(e):Ht,[e,t])}function lf(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?ti(e,n.current):Ht}function T2(e){u.useEffect(()=>{if(!Jr)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 D2(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 df(e){return u.useMemo(()=>e?n2(e):null,[e])}const cf=[];function N2(e,t){t===void 0&&(t=Ho);const[n]=e,o=df(n?_t(n):null),[r,s]=u.useState(cf);function a(){s(()=>e.length?e.map(d=>Xp(d)?o:new pa(t(d),d)):cf)}const l=ii({callback:a});return sn(()=>{l?.disconnect(),a(),e.forEach(d=>l?.observe(d))},[e]),r}function uf(e){if(!e)return null;if(e.children.length>1)return e;const t=e.children[0];return Oo(t)?t:e}function z2(e){let{measure:t}=e;const[n,o]=u.useState(null),r=u.useCallback(c=>{for(const{target:p}of c)if(Oo(p)){o(f=>{const y=t(p);return f?{...f,width:y.width,height:y.height}:y});break}},[t]),s=ii({callback:r}),a=u.useCallback(c=>{const p=uf(c);s?.disconnect(),p&&s?.observe(p),o(p?t(p):null)},[t,s]),[l,d]=Qr(a);return u.useMemo(()=>({nodeRef:l,rect:n,setRef:d}),[n,l,d])}const M2=[{sensor:ha,options:{}},{sensor:tf,options:{}}],L2={current:{}},si={draggable:{measure:Up},droppable:{measure:Up,strategy:Vo.WhileDragging,frequency:ma.Optimized},dragOverlay:{measure:Ho}};class Uo 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 P2={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Uo,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:oi},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:si,measureDroppableContainers:oi,windowRect:null,measuringScheduled:!1},pf={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:oi,draggableNodes:new Map,over:null,measureDroppableContainers:oi},qo=u.createContext(pf),ff=u.createContext(P2);function O2(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Uo}}}function B2(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 Uo(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 Uo(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 Uo(e.droppable.containers);return s.delete(n),{...e,droppable:{...e.droppable,containers:s}}}default:return e}}function W2(e){let{disabled:t}=e;const{active:n,activatorEvent:o,draggableNodes:r}=u.useContext(qo),s=Rr(o),a=Rr(n?.id);return u.useEffect(()=>{if(!t&&!o&&s&&a!=null){if(!la(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=A7(p);if(f){f.focus();break}}})}},[o,t,r,a,s]),null}function gf(e,t){let{transform:n,...o}=t;return e!=null&&e.length?e.reduce((r,s)=>s({transform:r,...o}),n):n}function j2(e){return u.useMemo(()=>({draggable:{...si.draggable,...e?.draggable},droppable:{...si.droppable,...e?.droppable},dragOverlay:{...si.dragOverlay,...e?.dragOverlay}}),[e?.draggable,e?.droppable,e?.dragOverlay])}function H2(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=Kp(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 y=qp(c);y&&y.scrollBy({top:f.y,left:f.x})}},[t,a,l,o,n])}const ai=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 F2=u.memo(function(t){var n,o,r,s;let{id:a,accessibility:l,autoScroll:d=!0,children:c,sensors:p=M2,collisionDetection:f=Y7,measuring:y,modifiers:g,...m}=t;const h=u.useReducer(B2,void 0,O2),[v,b]=h,[x,k]=L7(),[w,_]=u.useState(hn.Uninitialized),C=w===hn.Initialized,{draggable:{active:E,nodes:S,translate:T},droppable:{containers:$}}=v,A=E!=null?S.get(E):null,z=u.useRef({initial:null,translated:null}),D=u.useMemo(()=>{var J;return E!=null?{id:E,data:(J=A?.data)!=null?J:L2,rect:z}:null},[E,A]),O=u.useRef(null),[M,B]=u.useState(null),[N,H]=u.useState(null),L=Bo(m,Object.values(m)),I=ei("DndDescribedBy",a),P=u.useMemo(()=>$.getEnabled(),[$]),F=j2(y),{droppableRects:G,measureDroppableContainers:V,measuringScheduled:Y}=k2(P,{dragging:C,dependencies:[T.x,T.y],config:F.droppable}),Z=x2(S,E),se=u.useMemo(()=>N?ni(N):null,[N]),re=ue(),U=S2(Z,F.draggable.measure);H2({activeNode:E!=null?S.get(E):null,config:re.layoutShiftCompensation,initialRect:U,measure:F.draggable.measure});const ee=sf(Z,F.draggable.measure,U),fe=sf(Z?Z.parentElement:null),K=u.useRef({activatorEvent:null,active:null,activeNode:Z,collisionRect:null,collisions:null,droppableRects:G,draggableNodes:S,draggingNode:null,draggingNodeRect:null,droppableContainers:$,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),ne=$.getNodeFor((n=K.current.over)==null?void 0:n.id),me=z2({measure:F.dragOverlay.measure}),Ce=(o=me.nodeRef.current)!=null?o:Z,ze=C?(r=me.rect)!=null?r:ee:null,Se=!!(me.nodeRef.current&&me.rect),qe=E2(Se?null:ee),De=df(Ce?_t(Ce):null),Pe=I2(C?ne??Z:null),Qe=N2(Pe),Me=gf(g,{transform:{x:T.x-qe.x,y:T.y-qe.y,scaleX:1,scaleY:1},activatorEvent:N,active:D,activeNodeRect:ee,containerNodeRect:fe,draggingNodeRect:ze,over:K.current.over,overlayNodeRect:me.rect,scrollableAncestors:Pe,scrollableAncestorRects:Qe,windowRect:De}),Re=se?uo(se,T):null,ve=A2(Pe),te=lf(ve),he=lf(ve,[ee]),Q=uo(Me,te),ie=ze?R7(ze,Me):null,_e=D&&ie?f({active:D,collisionRect:ie,droppableRects:G,droppableContainers:P,pointerCoordinates:Re}):null,ge=q7(_e,"id"),[Ae,Ne]=u.useState(null),Le=Se?Me:uo(Me,he),q=Z7(Le,(s=Ae?.rect)!=null?s:null,ee),ae=u.useRef(null),pe=u.useCallback((J,le)=>{let{sensor:Ie,options:dt}=le;if(O.current==null)return;const pt=S.get(O.current);if(!pt)return;const ot=J.nativeEvent,Oe=new Ie({active:O.current,activeNode:pt,event:ot,options:dt,context:K,onAbort(Ye){if(!S.get(Ye))return;const{onDragAbort:Dt}=L.current,Nt={id:Ye};Dt?.(Nt),x({type:"onDragAbort",event:Nt})},onPending(Ye,Tt,Dt,Nt){if(!S.get(Ye))return;const{onDragPending:wn}=L.current,Zt={id:Ye,constraint:Tt,initialCoordinates:Dt,offset:Nt};wn?.(Zt),x({type:"onDragPending",event:Zt})},onStart(Ye){const Tt=O.current;if(Tt==null)return;const Dt=S.get(Tt);if(!Dt)return;const{onDragStart:Nt}=L.current,xn={activatorEvent:ot,active:{id:Tt,data:Dt.data,rect:z}};Cn.unstable_batchedUpdates(()=>{Nt?.(xn),_(hn.Initializing),b({type:it.DragStart,initialCoordinates:Ye,active:Tt}),x({type:"onDragStart",event:xn}),B(ae.current),H(ot)})},onMove(Ye){b({type:it.DragMove,coordinates:Ye})},onEnd:He(it.DragEnd),onCancel:He(it.DragCancel)});ae.current=Oe;function He(Ye){return async function(){const{active:Dt,collisions:Nt,over:xn,scrollAdjustedTranslate:wn}=K.current;let Zt=null;if(Dt&&wn){const{cancelDrop:Hn}=L.current;Zt={activatorEvent:ot,active:Dt,collisions:Nt,delta:wn,over:xn},Ye===it.DragEnd&&typeof Hn=="function"&&await Promise.resolve(Hn(Zt))&&(Ye=it.DragCancel)}O.current=null,Cn.unstable_batchedUpdates(()=>{b({type:Ye}),_(hn.Uninitialized),Ne(null),B(null),H(null),ae.current=null;const Hn=Ye===it.DragEnd?"onDragEnd":"onDragCancel";if(Zt){const ln=L.current[Hn];ln?.(Zt),x({type:Hn,event:Zt})}})}}},[S]),$e=u.useCallback((J,le)=>(Ie,dt)=>{const pt=Ie.nativeEvent,ot=S.get(dt);if(O.current!==null||!ot||pt.dndKit||pt.defaultPrevented)return;const Oe={active:ot};J(Ie,le.options,Oe)===!0&&(pt.dndKit={capturedBy:le.sensor},O.current=dt,pe(Ie,le))},[S,pe]),be=w2(p,$e);T2(p),sn(()=>{ee&&w===hn.Initializing&&_(hn.Initialized)},[ee,w]),u.useEffect(()=>{const{onDragMove:J}=L.current,{active:le,activatorEvent:Ie,collisions:dt,over:pt}=K.current;if(!le||!Ie)return;const ot={active:le,activatorEvent:Ie,collisions:dt,delta:{x:Q.x,y:Q.y},over:pt};Cn.unstable_batchedUpdates(()=>{J?.(ot),x({type:"onDragMove",event:ot})})},[Q.x,Q.y]),u.useEffect(()=>{const{active:J,activatorEvent:le,collisions:Ie,droppableContainers:dt,scrollAdjustedTranslate:pt}=K.current;if(!J||O.current==null||!le||!pt)return;const{onDragOver:ot}=L.current,Oe=dt.get(ge),He=Oe&&Oe.rect.current?{id:Oe.id,rect:Oe.rect.current,data:Oe.data,disabled:Oe.disabled}:null,Ye={active:J,activatorEvent:le,collisions:Ie,delta:{x:pt.x,y:pt.y},over:He};Cn.unstable_batchedUpdates(()=>{Ne(He),ot?.(Ye),x({type:"onDragOver",event:Ye})})},[ge]),sn(()=>{K.current={activatorEvent:N,active:D,activeNode:Z,collisionRect:ie,collisions:_e,droppableRects:G,draggableNodes:S,draggingNode:Ce,draggingNodeRect:ze,droppableContainers:$,over:Ae,scrollableAncestors:Pe,scrollAdjustedTranslate:Q},z.current={initial:ze,translated:ie}},[D,Z,_e,ie,S,Ce,ze,G,$,Ae,Pe,Q]),m2({...re,delta:T,draggingRect:ie,pointerCoordinates:Re,scrollableAncestors:Pe,scrollableAncestorRects:Qe});const j=u.useMemo(()=>({active:D,activeNode:Z,activeNodeRect:ee,activatorEvent:N,collisions:_e,containerNodeRect:fe,dragOverlay:me,draggableNodes:S,droppableContainers:$,droppableRects:G,over:Ae,measureDroppableContainers:V,scrollableAncestors:Pe,scrollableAncestorRects:Qe,measuringConfiguration:F,measuringScheduled:Y,windowRect:De}),[D,Z,ee,N,_e,fe,me,S,$,G,Ae,V,Pe,Qe,F,Y,De]),oe=u.useMemo(()=>({activatorEvent:N,activators:be,active:D,activeNodeRect:ee,ariaDescribedById:{draggable:I},dispatch:b,draggableNodes:S,over:Ae,measureDroppableContainers:V}),[N,be,D,ee,b,I,S,Ae,V]);return u.createElement(Fp.Provider,{value:k},u.createElement(qo.Provider,{value:oe},u.createElement(ff.Provider,{value:j},u.createElement(ai.Provider,{value:q},c)),u.createElement(W2,{disabled:l?.restoreFocus===!1})),u.createElement(B7,{...l,hiddenTextDescribedById:I}));function ue(){const J=M?.autoScrollEnabled===!1,le=typeof d=="object"?d.enabled===!1:d===!1,Ie=C&&!J&&!le;return typeof d=="object"?{...d,enabled:Ie}:{enabled:Ie}}}),K2=u.createContext(null),hf="button",V2="Draggable";function U2(e){let{id:t,data:n,disabled:o=!1,attributes:r}=e;const s=ei(V2),{activators:a,activatorEvent:l,active:d,activeNodeRect:c,ariaDescribedById:p,draggableNodes:f,over:y}=u.useContext(qo),{role:g=hf,roleDescription:m="draggable",tabIndex:h=0}=r??{},v=d?.id===t,b=u.useContext(v?ai:K2),[x,k]=Qr(),[w,_]=Qr(),C=D2(a,t),E=Bo(n);sn(()=>(f.set(t,{id:t,key:s,node:x,activatorNode:w,data:E}),()=>{const T=f.get(t);T&&T.key===s&&f.delete(t)}),[f,t]);const S=u.useMemo(()=>({role:g,tabIndex:h,"aria-disabled":o,"aria-pressed":v&&g===hf?!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:S,isDragging:v,listeners:o?void 0:C,node:x,over:y,setNodeRef:k,setActivatorNodeRef:_,transform:b}}function q2(){return u.useContext(ff)}const G2="Droppable",Y2={timeout:25};function X2(e){let{data:t,disabled:n=!1,id:o,resizeObserverConfig:r}=e;const s=ei(G2),{active:a,dispatch:l,over:d,measureDroppableContainers:c}=u.useContext(qo),p=u.useRef({disabled:n}),f=u.useRef(!1),y=u.useRef(null),g=u.useRef(null),{disabled:m,updateMeasurementsFor:h,timeout:v}={...Y2,...r},b=Bo(h??o),x=u.useCallback(()=>{if(!f.current){f.current=!0;return}g.current!=null&&clearTimeout(g.current),g.current=setTimeout(()=>{c(Array.isArray(b.current)?b.current:[b.current]),g.current=null},v)},[v]),k=ii({callback:x,disabled:m||!a}),w=u.useCallback((S,T)=>{k&&(T&&(k.unobserve(T),f.current=!1),S&&k.observe(S))},[k]),[_,C]=Qr(w),E=Bo(t);return u.useEffect(()=>{!k||!_.current||(k.disconnect(),f.current=!1,k.observe(_.current))},[_,k]),u.useEffect(()=>(l({type:it.RegisterDroppable,element:{id:o,key:s,disabled:n,node:_,rect:y,data:E}}),()=>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:y,isOver:d?.id===o,node:_,over:d,setNodeRef:C}}function J2(e){let{animation:t,children:n}=e;const[o,r]=u.useState(null),[s,a]=u.useState(null),l=Rr(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 Z2={x:0,y:0,scaleX:1,scaleY:1};function Q2(e){let{children:t}=e;return u.createElement(qo.Provider,{value:pf},u.createElement(ai.Provider,{value:Z2},t))}const R2={position:"fixed",touchAction:"none"},eI=e=>la(e)?"transform 250ms ease":void 0,tI=u.forwardRef((e,t)=>{let{as:n,activatorEvent:o,adjustScale:r,children:s,className:a,rect:l,style:d,transform:c,transition:p=eI}=e;if(!l)return null;const f=r?c:{...c,scaleX:1,scaleY:1},y={...R2,width:l.width,height:l.height,top:l.top,left:l.left,transform:jo.Transform.toString(f),transformOrigin:r&&o?F7(o,l):void 0,transition:typeof p=="function"?p(o):p,...d};return u.createElement(n,{className:a,style:y,ref:t},s)}),nI={duration:250,easing:"ease",keyframes:e=>{let{transform:{initial:t,final:n}}=e;return[{transform:jo.Transform.toString(t)},{transform:jo.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 oI(e){let{config:t,draggableNodes:n,droppableContainers:o,measuringConfiguration:r}=e;return Zr((s,a)=>{if(t===null)return;const l=n.get(s);if(!l)return;const d=l.node.current;if(!d)return;const c=uf(a);if(!c)return;const{transform:p}=_t(a).getComputedStyle(a),f=Vp(p);if(!f)return;const y=typeof t=="function"?t:rI(t);return Qp(d,r.draggable.measure),y({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 rI(e){const{duration:t,easing:n,sideEffects:o,keyframes:r}={...nI,...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},y={x:d.x-p.x,y:d.y-p.y,...f},g=r({...c,active:a,dragOverlay:l,transform:{initial:d,final:y}}),[m]=g,h=g[g.length-1];if(JSON.stringify(m)===JSON.stringify(h))return;const v=o?.({active:a,dragOverlay:l,...c}),b=l.node.animate(g,{duration:t,easing:n,fill:"forwards"});return new Promise(x=>{b.onfinish=()=>{v?.(),x()}})}}let yf=0;function iI(e){return u.useMemo(()=>{if(e!=null)return yf++,yf},[e])}const sI=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:y,containerNodeRect:g,draggableNodes:m,droppableContainers:h,dragOverlay:v,over:b,measuringConfiguration:x,scrollableAncestors:k,scrollableAncestorRects:w,windowRect:_}=q2(),C=u.useContext(ai),E=iI(f?.id),S=gf(a,{activatorEvent:p,active:f,activeNodeRect:y,containerNodeRect:g,draggingNodeRect:v.rect,over:b,overlayNodeRect:v.rect,scrollableAncestors:k,scrollableAncestorRects:w,transform:C,windowRect:_}),T=va(y),$=oI({config:o,draggableNodes:m,droppableContainers:h,measuringConfiguration:x}),A=T?v.setRef:void 0;return u.createElement(Q2,null,u.createElement(J2,{animation:$},f&&E?u.createElement(tI,{key:E,id:f.id,ref:A,as:l,activatorEvent:p,adjustScale:t,className:d,transition:s,rect:T,style:{zIndex:c,...r},transform:S},n):null))});function Go(e,t){return!t||!Array.isArray(t.draggable)?!1:t.draggable.includes(e)}function aI({draggedComponentName:e,targetContainerName:t,nesting:n}){if(!n||!Go(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 bf(e,t){if(!t?.containers)return!1;const n=t.containers[e];return!!(n&&Array.isArray(n.accepts)&&n.accepts.length>0)}function lI(e,t,n,o,r){if(!n||n.length===0)return{parentPath:[],index:r};if(e&&bf(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 mf(e,t){return e===t||e.startsWith(`${t}.`)}function vf(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 dI(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 cI=16;function uI(e){const{frameEl:t,draggedPath:n,acceptsContainer:o,allowsNestSlot:r,includeContainer:s}=e,a=e.normalizeContainerPath??(g=>g),l=t.getBoundingClientRect(),d=dI(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=fI(g.path);m!==null&&f.add(m)}for(const g of d)f.add(g.path);const y=[];for(const g of f){const m=g==="",h=m?null:c.get(g)??g,v=m?t:t.querySelector(`[data-editor-path="${wf(h)}"]`);if(!v&&!m||!m&&mf(g,p))continue;const b=g;if(!m&&s&&!s(b))continue;const x=C=>{const E=c.get(C);if(!E||typeof window>"u")return!1;const S=t.querySelector(`[data-editor-path="${wf(E)}"]`);return S?(window.getComputedStyle(S).display??"").toLowerCase()==="contents":!1},k=d.filter(C=>vf(g,C.path)!==null).filter(C=>!mf(C.path,p)).filter(C=>!x(C.path)).map(C=>({origIndex:vf(g,C.path),rect:pI(C.rect,C.path,d)})).filter(C=>C.rect.width>0||C.rect.height>0).sort((C,E)=>C.origIndex-E.origIndex),w=Dp(m?t:v).kind,_=w==="flex_row_single"||w==="flex_row_wrap"||w==="grid_single_row"||w==="grid_2d";if(k.length>0){if(o(b)){k.forEach(E=>{y.push(_f(b,E.origIndex,E.rect,l,_,"before"))});const C=k[k.length-1];y.push(_f(b,C.origIndex+1,C.rect,l,_,"after"))}}else if(!m&&r(b)&&v){const C=v.getBoundingClientRect();C.width>0&&C.height>0&&y.push({id:`slot:${b}:0`,kind:"nest",containerPath:b,index:0,box:xf(C,l),orientation:"area"})}else m&&y.push({id:"slot::0",kind:"gap",containerPath:"",index:0,box:xf(l,l),orientation:"area"})}return y.filter(g=>ao(g.box,t))}function _f(e,t,n,o,r,s){const a=cI;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 pI(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 xf(e,t){return{left:e.left-t.left,top:e.top-t.top,width:e.width,height:e.height,scale:1}}function fI(e){if(e==="")return null;const t=e.lastIndexOf(".children.");return t<0?"":e.slice(0,t)}function gI(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 wf(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/[^a-zA-Z0-9_\-.]/g,t=>`\\${t}`)}function _a(e){return typeof e=="string"&&e.length>0?e:null}function xa(e,t){return t&&e.startsWith(`${t}.`)?t:e}function kf(e){if(typeof e!="string")return null;const t=gI(e);return t?{containerPath:t.containerPath,index:t.index}:null}function wa(e,t){return t?e.startsWith(`${t}.iteration.`):!1}function ka(e,t,n){return t?n==="iteration_item"?wa(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,y=(o==="iteration_item"||o==="modal")&&s&&s.length>0?at(s):null,[g,m]=u.useState(null),[h,v]=u.useState(null),[b,x]=u.useState(null),k=u.useRef({components:a,nesting:n,editMode:o,currentExtensionId:r,selectedPath:p,editableRootSourcePath:y});k.current={components:a,nesting:n,editMode:o,currentExtensionId:r,selectedPath:p,editableRootSourcePath:y};const w=u.useRef(null),_=u.useCallback(M=>({children:M}),[]),C=u.useCallback((M,B)=>{const N=We(_(M),B);return N?typeof N.name=="string"?N.name:typeof N.type=="string"?N.type:null:null},[_]),E=u.useCallback(M=>B=>{const N=k.current;if(B==="")return Go(M,N.nesting);const H=Ze(B),L=We(_(N.components),H);if(!L)return!1;const I=typeof L.name=="string"?L.name:typeof L.type=="string"?L.type:"";if(!I)return!1;const P=!!N.editableRootSourcePath&&(B===N.editableRootSourcePath||B.startsWith(`${N.editableRootSourcePath}.`));if(N.editableRootSourcePath&&!P)return!1;if(!P){const F=Sa(_(N.components),H);if(gn(L,N.editMode,N.currentExtensionId,F)!=="none")return!1}return bf(I,N.nesting)?aI({draggedComponentName:M,targetContainerName:I,nesting:N.nesting}):!1},[_]),S=u.useCallback(M=>{if(M==="")return!0;const B=k.current,N=Ze(M),H=w.current;if(H&&H.length>0){const P=H.slice(0,-1);if(li(N,P))return!0}const L=We(_(B.components),N);return L?(typeof L.name=="string"?L.name:typeof L.type=="string"?L.type:"").length>0:!1},[_]),T=u.useCallback(M=>{const B=E(M),N=k.current,H=w.current,L=H?H.slice(0,-1):null,I=new Set;if(L)for(let V=L.length;V>=0;V--)I.add(di(L.slice(0,V)));const P=di(H??[]),F=V=>!!H&&(V===P||V.startsWith(`${P}.`)),G=(V,Y)=>{for(let Z=0;ZV===""?!0:F(V)?!1:I.has(V),allowsNestSlot:V=>{if(!B(V))return!1;if(L){const Y=Ze(V);if(li(Y,L))return!1}return S(V)}}},[E,S,_]),$=u.useCallback(M=>{const B=_a(M.active.id),N=k.current;if(!B)return;const H=xa(B,N.selectedPath),L=Ze(H),I=We(_(N.components),L),P=I&&typeof I.name=="string"?I.name:I&&typeof I.type=="string"?I.type:null;m(H),v(P),x(null),w.current=I?L:null;let F="allowed";if(!P||!Go(P,N.nesting))F="denied_no_draggable";else if(I){const G=Sa(_(N.components),L),V=gn(I,N.editMode,N.currentExtensionId,G);N.editableRootSourcePath&&!ka(H,N.editableRootSourcePath,N.editMode)||Xi(G)&&!wa(H,N.editableRootSourcePath)?F="denied_data_bound":V==="base"||V==="partial"?F="denied_base_locked":(V==="extension"||V==="extension_point")&&(F="denied_extension_locked")}$n({source:"drag",draggedComponentName:P,targetContainerName:null,targetContainerPath:null,decision:F,result:F==="allowed"?"completed":"denied",timestamp:Date.now()})},[_]),A=u.useCallback(M=>{if(!t)return;const B=_a(M.active.id);if(!B)return;const N=h;if(!N){x(null);return}const H=k.current,L=xa(B,H.selectedPath),I=Ze(L),P=We(_(H.components),I);if(!P||!Go(N,H.nesting)){x(null);return}const F=Sa(_(H.components),I);if(H.editableRootSourcePath&&!ka(L,H.editableRootSourcePath,H.editMode)){x(null);return}const G=gn(P,H.editMode,H.currentExtensionId,F),V=wa(L,H.editableRootSourcePath);if(Xi(F)&&!V||G!=="none"&&G!=="data_bound"&&!V){x(null);return}x(kf(M.over?.id))},[t,h,_]),z=u.useCallback(()=>{m(null),v(null),x(null),w.current=null},[]),D=u.useCallback(M=>{const B=_a(M.active.id),N=h,H=k.current,L=B?xa(B,H.selectedPath):null;if(!t||!L||!N){z();return}const I=kf(M.over?.id),P=Ze(L);if(!I){$n({source:"drag",draggedComponentName:N,targetContainerName:null,targetContainerPath:null,decision:"denied_no_accepts",result:"cancelled",timestamp:Date.now()}),z();return}const F=I.containerPath===""?[]:Ze(I.containerPath),G=I.containerPath===""?null:C(H.components,F);if(!yI(P.slice(0,-1),F)){$n({source:"drag",draggedComponentName:N,targetContainerName:G,targetContainerPath:I.containerPath||null,decision:"denied_responsive_branch_boundary",result:"denied",timestamp:Date.now()}),f?.(),z();return}if(H.editableRootSourcePath&&!ka(I.containerPath,H.editableRootSourcePath,H.editMode)){$n({source:"drag",draggedComponentName:N,targetContainerName:G,targetContainerPath:I.containerPath||null,decision:"denied_data_bound",result:"denied",timestamp:Date.now()}),z();return}const V=P.slice(0,-1),Y=P[P.length-1]??-1;if(li(V,F)&&(I.index===Y||I.index===Y+1)){$n({source:"drag",draggedComponentName:N,targetContainerName:G,targetContainerPath:I.containerPath||null,decision:"allowed",insertionIndex:I.index,result:"cancelled",timestamp:Date.now()}),z();return}const re=li(V,F),U=I.index;let ee=[];l(me=>{const Se=Db({children:me},P,F,U).children??[];return ee=Se,Se}),d(ee,`move ${N}`);const fe=id(F,P),K=re&&Y{z()},[z]);return{activeDragPath:g,activeDragName:h,activeDropZone:b,onDragStart:$,onDragMove:A,onDragEnd:D,onDragCancel:O,buildSlotPredicates:T}}function Sa(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),b=u.useRef(null),x=u.useCallback(()=>{v(!0),b.current&&clearTimeout(b.current),b.current=setTimeout(()=>v(!1),2600)},[]);u.useEffect(()=>()=>{b.current&&clearTimeout(b.current)},[]);const k=hI({frameEl:t,nesting:n,editMode:o,currentExtensionId:r,editableRootPath:s,components:a,patchLayout:l,pushHistory:d,onMovePath:p,selectedPath:y,showBranchBoundaryHint:x}),w=j7(W7(ha,{activationConstraint:{distance:8}})),[_,C]=u.useState([]),E=u.useCallback(()=>{if(!t){C([]);return}if(k.activeDragPath!==null)return;const L={children:a},I=t.querySelectorAll("[data-editor-path]"),P=[],F=new Map;I.forEach(G=>{const V=G.dataset.editorPath;if(typeof V!="string"||o!=="iteration_item"&&g&&!vI(V,g,o))return;const Y=bI(V);if(Y!==null&&!Yo(V,g)){if(/\.iteration\.\d+$/.test(V)){const K=so(G,t);if(K&&ao(K,t)){const ne=F.get(Y)??[];ne.push(K),F.set(Y,ne)}}return}if(Yo(V,g)&&/\.iteration\.\d+$/.test(V))return;const Z=Ze(V),se=We(L,Z);if(!se||se.iteration&&se.iteration.source!==void 0)return;const re=typeof se.name=="string"?se.name:typeof se.type=="string"?se.type:null;if(!re||!Go(re,n))return;const U=Cf(L,Z);if(Xi(U)&&!Yo(V,g))return;const ee=gn(se,o,r,U);if(ee!=="none"&&ee!=="data_bound"&&!Yo(V,g))return;const fe=so(G,t);fe&&ao(fe,t)&&P.push({path:V,name:re,box:fe})});for(const[G,V]of F){const Y=Ze(G),Z=We(L,Y);if(!Z)continue;const se=typeof Z.name=="string"?Z.name:typeof Z.type=="string"?Z.type:null;if(!se)continue;const re=Cf(L,Y),U=gn(Z,o,r,re);if(U!=="none"&&U!=="data_bound")continue;const ee=_I(V);ee&&ao(ee,t)&&P.push({path:G,name:se,box:ee,isIterationGroup:!0})}C(P)},[t,a,n,o,r,g,k.activeDragPath]);u.useEffect(()=>{E()},[E]),u.useEffect(()=>{if(t)return $p(E,t)},[t,E]);const S=k.activeDragPath!==null,T=k.activeDragName,$=k.activeDragPath,[A,z]=u.useState(null),D=u.useRef(null);u.useEffect(()=>{if(!$||!t){$||(D.current=null,z(null));return}if(D.current===$)return;D.current=$;const L=t.querySelector(`[data-editor-path="${Sf($)}"]`);if(L){const re=L.getBoundingClientRect();z({node:L.cloneNode(!0),width:re.width,height:re.height});return}const I=Array.from(t.querySelectorAll(`[data-editor-path^="${Sf($)}.iteration."]`)).filter(re=>/\.iteration\.\d+$/.test(re.dataset.editorPath??""));if(I.length===0){z(null);return}let P=1/0,F=1/0,G=-1/0,V=-1/0;for(const re of I){const U=re.getBoundingClientRect();P=Math.min(P,U.left),F=Math.min(F,U.top),G=Math.max(G,U.right),V=Math.max(V,U.bottom)}const Y=G-P,Z=V-F,se=document.createElement("div");se.style.position="relative",se.style.width=`${Y}px`,se.style.height=`${Z}px`;for(const re of I){const U=re.getBoundingClientRect(),ee=re.cloneNode(!0);ee.style.position="absolute",ee.style.left=`${U.left-P}px`,ee.style.top=`${U.top-F}px`,ee.style.width=`${U.width}px`,ee.style.height=`${U.height}px`,ee.style.margin="0",se.appendChild(ee)}z({node:se,width:Y,height:Z})},[$,t]);const[O,M]=u.useState([]),B=u.useRef(null),N=u.useRef(k.buildSlotPredicates);if(N.current=k.buildSlotPredicates,u.useEffect(()=>{if(!$||!T||!t){B.current=null,M(F=>F.length===0?F:[]);return}if(B.current===$)return;B.current=$;const{acceptsContainer:L,allowsNestSlot:I,includeContainer:P}=N.current(T);M(uI({frameEl:t,draggedPath:$,acceptsContainer:L,allowsNestSlot:I,includeContainer:P,normalizeContainerPath:F=>mI(F)}))},[$,T,t]),!t)return null;const H=k.activeDropZone?`slot:${k.activeDropZone.containerPath}:${k.activeDropZone.index}`:null;return i.jsxs(F2,{sensors:w,collisionDetection:J7,onDragStart:k.onDragStart,onDragMove:k.onDragMove,onDragEnd:k.onDragEnd,onDragCancel:k.onDragCancel,children:[_.map(L=>i.jsx(SI,{path:L.path,name:L.name,box:L.box,dimmed:S&&k.activeDragPath!==L.path,isIterationGroup:L.isIterationGroup,onSelect:c,onRequestInlineEdit:f},L.path)),S&&O.map(L=>i.jsx(kI,{slot:L,active:L.id===H},L.id)),Cn.createPortal(i.jsx(sI,{dropAnimation:null,zIndex:Pp,children:T?A?i.jsx(wI,{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:Pp},children:["⚠️ ",m("layout_editor.overlay.branch_boundary_denied")]}),t)]})}function wI(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 kI(e){const{slot:t,active:n}=e,{setNodeRef:o}=X2({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 Sf(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/[^a-zA-Z0-9_\-.]/g,t=>`\\${t}`)}function SI(e){const{path:t,box:n,dimmed:o,isIterationGroup:r,onSelect:s,onRequestInlineEdit:a}=e,{attributes:l,listeners:d,setNodeRef:c,isDragging:p}=U2({id:t}),f=(t.match(/\.children\./g)||[]).length,y=y7(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 b=h.closest?.("[data-editor-path]")?.dataset?.editorPath;if(typeof b=="string"&&(b===t||b.startsWith(`${t}.`))){s(b);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:y,touchAction:"none"}})}function Cf(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(!Ji(d,t,n)){r.push(p);return}const y=Array.isArray(d.children)?d.children:[];y.length>0&&s(y,p)})};return s(e,[]),r}function $I(e){return at(e)}function ci(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\]/g,"\\$&")}function EI({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 x=CI(t,n,o,r);if(x.length===0){a(null);return}const k=e.getBoundingClientRect(),w={left:0,top:0,width:k.width,height:k.height},_=[];for(const C of x){const E=$I(C),S=e.querySelector(`[data-editor-path="${ci(E)}"]`);let T=null;if(S){const $=S.getBoundingClientRect();$.width>0&&$.height>0&&(T={left:$.left,top:$.top,width:$.width,height:$.height})}if(!T){const $=Array.from(e.querySelectorAll(`[data-editor-path^="${ci(E)}.iteration."], [data-editor-path^="${ci(E)}.sortable."], [data-editor-path^="${ci(E)}.children."]`));let A=1/0,z=1/0,D=-1/0,O=-1/0;for(const M of $){const B=M.getBoundingClientRect();B.width<=0||B.height<=0||(A=Math.min(A,B.left),z=Math.min(z,B.top),D=Math.max(D,B.right),O=Math.max(O,B.bottom))}if(D>A&&O>z&&(T={left:A,top:z,width:D-A,height:O-z}),T&&$.length>0){const M=$[0].closest('[role="dialog"]');if(M&&e.contains(M)){const B=M.getBoundingClientRect();B.width>0&&B.height>0&&(T={left:B.left,top:B.top,width:B.width,height:B.height})}}}T&&_.push({left:T.left-k.left,top:T.top-k.top,width:T.width,height:T.height})}if(_.length===0){a(null);return}a({frame:w,holes:_})},h=()=>{g&&cancelAnimationFrame(g),g=requestAnimationFrame(m)};h();const v=typeof ResizeObserver<"u"?new ResizeObserver(h):null;v?.observe(e);const b=typeof MutationObserver<"u"?new MutationObserver(h):null;return b?.observe(e,{childList:!0,subtree:!0,attributes:!0}),window.addEventListener("scroll",h,!0),window.addEventListener("resize",h),()=>{g&&cancelAnimationFrame(g),v?.disconnect(),b?.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 C of c)g=Math.min(g,C.left),m=Math.min(m,C.top),h=Math.max(h,C.left+C.width),v=Math.max(v,C.top+C.height);const b=(C,E,S)=>Math.max(E,Math.min(S,C)),x=b(g,0,d.width),k=b(m,0,d.height),w=b(h,0,d.width),_=b(v,0,d.height);f=[{left:0,top:0,width:d.width,height:k},{left:0,top:_,width:d.width,height:d.height-_},{left:0,top:k,width:x,height:_-k},{left:w,top:k,width:d.width-w,height:_-k}].filter(C=>C.width>0&&C.height>0)}const y=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:y,onPointerDownCapture:y,onMouseDownCapture:y,onDragStartCapture:y,style:{position:"absolute",left:g.left,top:g.top,width:g.width,height:g.height,zIndex:Lp,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:Lp,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 $f(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 II(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 AI(e,t,n,o,r){const s=II(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 TI(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 y of p.components??[]){const g=a.get(y);g&&(f.push(g),l.add(y))}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 Ef(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:y}=tt(),g=u.useMemo(()=>{if(!c||!y)return f;const A=p??null;return z=>{const D={templateId:c,locale:A??"ko"},O=y.translate(z,D);return O!==z?O:f(z)}},[c,p,y,f]),[m,h]=u.useState(""),[v,b]=u.useState("all"),x=o?.entries??null,k=u.useMemo(()=>A=>{const z=x?.[A.name];return z?.label?ui(z.label,g):A.description??A.name},[x,g]),w=u.useMemo(()=>AI(t,n,s,m,k),[t,n,s,m,k]),_=u.useMemo(()=>TI(w,o??null),[w,o]),C=_.find(A=>A.key===v)??_[0]??null,E=!n||!n.draggable&&!n.containers,S=w.length===0,T=C?.entries??[],$=A=>{const z=x?.[A.name],D=!!z?.defaultNode&&typeof z.defaultNode=="object";if(z?.requiresDefaultNode&&!D)return;const O=D?JSON.parse(JSON.stringify(z.defaultNode)):$f(A),M=r??[];a(O,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:MI,children:[i.jsxs("div",{style:LI,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:PI,children:"×"})]}),i.jsxs("div",{style:OI,children:[i.jsx("aside",{style:BI,"data-testid":"g7le-palette-sidebar",children:i.jsx("nav",{children:i.jsx("ul",{style:WI,children:_.map(A=>{const z=C?.key===A.key,D=A.isI18nKey?ui(A.label,g):A.label;return i.jsx("li",{children:i.jsxs("button",{type:"button","data-testid":`g7le-palette-category-${A.key}`,"data-active":z?"true":"false",onClick:()=>b(A.key),style:{...jI,background:z?"#eff6ff":"transparent",color:z?"#1d4ed8":"#334155",fontWeight:z?600:500},children:[i.jsx("span",{children:D}),i.jsx("span",{style:VI,children:A.entries.length})]})},A.key)})})})}),i.jsxs("main",{style:HI,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:FI}),i.jsx("div",{style:KI,children:E?i.jsx("div",{style:If,"data-testid":"g7le-palette-spec-missing",children:f("layout_editor.palette.spec_missing")}):S||T.length===0?i.jsx("div",{style:If,"data-testid":"g7le-palette-empty",children:f("layout_editor.palette.empty")}):i.jsx("div",{"data-testid":`g7le-palette-group-${C?.key??"all"}`,style:{marginBottom:16},children:i.jsx("div",{style:UI,children:T.map(A=>i.jsx(DI,{entry:A,entrySpec:x?.[A.name]??null,onClick:$,t:f,entryT:g},A.name))})})})]})]})]})}function DI(e){const{entry:t,entrySpec:n,onClick:o,t:r,entryT:s}=e,a=n?.label?ui(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,y=p?r("layout_editor.palette.requires_default_node_missing"):n?.label?ui(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:y,style:p?GI:qI,children:[i.jsx("div",{style:XI,"aria-hidden":"true",children:zI(t)}),i.jsx("div",{style:JI,children:a}),i.jsx("div",{"data-testid":`g7le-palette-item-${t.name}-tag`,style:ZI,children:`<${t.name}>`}),d&&i.jsx("div",{"data-testid":`g7le-palette-item-${t.name}-badge`,style:NI(l),children:l}),f&&i.jsx("div",{"data-testid":`g7le-palette-item-${t.name}-default-missing-badge`,style:YI,children:r("layout_editor.palette.default_node_missing_badge")})]})}function ui(e,t){return e.startsWith("$t:")?t(e.slice(3)):t(e)}function NI(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 zI(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 MI={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'},LI={display:"flex",justifyContent:"space-between",alignItems:"center",padding:"14px 20px",borderBottom:"1px solid #e2e8f0",flexShrink:0},PI={background:"transparent",border:"none",fontSize:24,cursor:"pointer",lineHeight:1,color:"#64748b",padding:"0 4px"},OI={display:"flex",flex:1,minHeight:0},BI={width:180,flexShrink:0,borderRight:"1px solid #e2e8f0",padding:"14px 8px",background:"#f8fafc",overflowY:"auto"},WI={listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:4},jI={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"},HI={flex:1,display:"flex",flexDirection:"column",minHeight:0,padding:"14px 20px"},FI={width:"100%",padding:"8px 10px",border:"1px solid #cbd5e1",borderRadius:6,marginBottom:12,fontSize:13,flexShrink:0,boxSizing:"border-box"},KI={flex:1,overflowY:"auto",minHeight:0},VI={fontSize:11,color:"#94a3b8",marginLeft:8,fontWeight:500},UI={display:"grid",gridTemplateColumns:"repeat(auto-fill, minmax(96px, 1fr))",gap:10},qI={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"},GI={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},YI={fontSize:9,fontWeight:600,color:"#92400e",background:"#fef3c7",padding:"1px 6px",borderRadius:999,textTransform:"none",letterSpacing:0,lineHeight:1.6},XI={fontSize:22,lineHeight:1,color:"#475569"},JI={fontSize:12,fontWeight:500,color:"#0f172a",textAlign:"center",wordBreak:"break-word"},ZI={fontFamily:'ui-monospace, SFMono-Regular, Menlo, Consolas, "Liberation Mono", monospace',fontSize:10,color:"#64748b",textAlign:"center",wordBreak:"break-all"},If={padding:24,color:"#64748b",fontSize:13,textAlign:"center"};function QI(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 Af(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 QI(o))n(a)};if(Array.isArray(e))for(const o of e)o&&typeof o=="object"&&n(o);return t}const RI=["scroll","selector","wizard","slider"];function eA(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 RI)n.add(`${o}-${r}`)}return Array.from(n)}function tA(e,t,n){const o=t.label;return typeof o=="string"?o.startsWith("$t:")?n(o.slice(3)):o:e}function pi({controlKey:e,control:t,node:n,t:o,onPatch:r,candidates:s,bindingCandidates:a,scope:l=Wt}){const d=Tn(t.widget),c=tA(e,t,o),p=u.useMemo(()=>Do(n,t,l),[n,t,l]),f=t.widget==="i18n-text"&&t.apply?.type==="propValue",y=t.widget==="text"&&t.apply?.type==="propValue",g=p.darkReadonly===!0||l.colorScheme==="dark"&&t.apply!==void 0&&!Us(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,b=u.useCallback(x=>{if(g)return;const k=fn(n,t,x,l);r(k)},[n,t,r,l,g]);return i.jsxs("div",{className:"g7le-control-row","data-testid":`g7le-control-${e}`,style:nA,children:[i.jsxs("span",{className:"g7le-control-label",style:oA,children:[c,p.conflict&&i.jsx("span",{"data-testid":`g7le-control-conflict-${e}`,title:o("layout_editor.property_modal.value_conflict"),style:rA,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(vt,{value:typeof p.value=="string"?p.value:"",onChange:x=>b(x),t:o,testidPrefix:`g7le-prop-i18n-${e}`,candidates:a,enableExpressionTree:!0,expressionTreeCollapsible:!0}):y?i.jsx(Ve,{value:typeof p.value=="string"?p.value:"",onChange:x=>b(x===""?void 0:x),t:o,testidPrefix:`g7le-prop-value-${e}`,candidates:a}):g?i.jsx("span",{"data-testid":`g7le-control-dark-readonly-${e}`,style:sA,children:o("layout_editor.property_modal.dark_code_only")}):d?i.jsx(d,{control:t,value:p.value,onChange:b,t:o,candidates:s,bindingCandidates:a,freeValueDisabled:h}):i.jsx("span",{"data-testid":`g7le-control-unsupported-${e}`,style:iA,children:o("layout_editor.property_modal.unsupported_widget")})})]})}const nA={display:"flex",alignItems:"center",gap:12,padding:"6px 0",minHeight:32,minWidth:0},oA={fontSize:12,color:"#475569",minWidth:88,display:"inline-flex",alignItems:"center",gap:4},rA={display:"inline-flex",width:14,height:14,borderRadius:7,background:"#f59e0b",color:"#fff",fontSize:10,alignItems:"center",justifyContent:"center",fontWeight:700},iA={fontSize:11,color:"#94a3b8",fontStyle:"italic"},sA={fontSize:11,color:"#94a3b8",fontStyle:"italic"};function fi(e,t,n){return typeof e=="string"?e.startsWith("$t:")?n(e.slice(3)):e:t}function aA(e,t){const n=e.props??{};return t.key in n?n[t.key]:t.default}function lA({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:cA,children:r.map((s,a)=>i.jsxs("div",{className:"g7le-settings-group",style:uA,children:[i.jsx("div",{style:pA,children:fi(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:fA,children:[i.jsx("span",{style:gA,children:fi(l.label,l.key,n)}),i.jsx("div",{style:{flex:1},children:dA(l,t,n,o)})]},l.key))]},a))})}function dA(e,t,n,o){const r=aA(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:Ca});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:Ca});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:yA,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)}}),fi(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:Ca,children:[i.jsx("option",{value:"",children:"—"}),(e.options??[]).map(s=>i.jsx("option",{value:String(s.value),children:fi(s.label,String(s.value),n)},String(s.value)))]})}}const cA={display:"flex",flexDirection:"column",gap:16},uA={display:"flex",flexDirection:"column",gap:6},pA={fontSize:12,fontWeight:700,color:"#0f172a",borderBottom:"1px solid #e2e8f0",paddingBottom:4},fA={display:"flex",alignItems:"center",gap:12,minHeight:30},gA={fontSize:12,color:"#475569",minWidth:96},Ca={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",boxSizing:"border-box"},hA={display:"flex",flexWrap:"wrap",gap:10},yA={display:"inline-flex",alignItems:"center",gap:4,fontSize:12,color:"#0f172a"},bA=["data_binding","isolatedScopeId","parentFormContextProp","skipBindingKeys","isolatedState","component_layout","sortable","itemTemplate"],mA=/\{\{|\$switch|\$get|\|\s*(date|number|truncate|currency|relative)\b/;function gi(e,t=0){return t>6?!1:typeof e=="string"?mA.test(e):Array.isArray(e)?e.some(n=>gi(n,t+1)):e&&typeof e=="object"?Object.values(e).some(n=>gi(n,t+1)):!1}function vA(e){if(Zl(e))return!1;const t=Fl(e);return t.length===0?!1:t.some(n=>n.isComplex)}function Tf(e){const t=[],n=e.props??{};for(const o of bA)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"?vA(e.text)&&t.push({key:"text",kind:"complex_expression"}):gi(e.text)&&t.push({key:"text",kind:"complex_expression"});for(const[o,r]of Object.entries(n))o==="style"||o==="className"||gi(r)&&t.push({key:`props.${o}`,kind:"complex_expression"});return t}function _A(e){return Tf(e).length>0}const xA=new Set(["permissions","blur_until_loaded","comment"]);function wA({node:e,advanced:t,t:n,onPatch:o,permissionCandidates:r}){const s=u.useMemo(()=>Tf(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:kA,children:[t.map(l=>{if(!xA.has(l))return i.jsxs("div",{"data-testid":`g7le-advanced-deferred-${l}`,style:CA,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:$a,children:[i.jsx("div",{style:Ea,children:n("layout_editor.property_modal.advanced.permissions")}),i.jsx(ys,{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:$a,children:[i.jsx("div",{style:Ea,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:$a,children:[i.jsx("div",{style:Ea,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:SA})]},l)}),s.length>0&&i.jsxs("div",{className:"g7le-advanced-preserved","data-testid":"g7le-advanced-preserved",style:$A,children:[i.jsx("div",{style:EA,children:n("layout_editor.property_modal.advanced_preserved_title",{count:s.length})}),i.jsx("ul",{style:IA,children:s.map(l=>i.jsxs("li",{"data-testid":`g7le-advanced-preserved-${l.key}`,style:AA,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 kA={display:"flex",flexDirection:"column",gap:14},$a={display:"flex",flexDirection:"column",gap:6},Ea={fontSize:12,fontWeight:700,color:"#0f172a"},SA={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,width:"100%",boxSizing:"border-box"},CA={fontSize:11,color:"#94a3b8",fontStyle:"italic"},$A={borderTop:"1px dashed #cbd5e1",paddingTop:10,marginTop:4},EA={fontSize:11,color:"#b45309",marginBottom:6},IA={listStyle:"none",margin:0,padding:0,display:"flex",flexDirection:"column",gap:4},AA={display:"flex",justifyContent:"space-between",gap:8,padding:"3px 0"},TA={onClick:"click",onHover:"mouseenter",onChange:"change",onSubmit:"submit",onMount:"mount",onUnmount:"unmount",onFocus:"focus",onBlur:"blur"};function Ia(e){return TA[e]??e.replace(/^on/,"").toLowerCase()}function Df(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=Ia(s);for(const d of a)d&&typeof d=="object"&&r.push("type"in d?d:{type:l,...d})}return r}return[]}function DA(e,t){const n=Ia(t);return Df(e).filter(o=>o.type===n||t==="onClick"&&o.type===void 0)}function NA(e,t,n){const o=Ia(t),r=Df(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 zA({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:Nf,children:o("layout_editor.action.no_events")}):!c||Object.keys(c).length===0?i.jsx("div",{"data-testid":"g7le-action-no-recipes",style:Nf,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(y=>i.jsxs("div",{className:"g7le-action-event-slot","data-testid":`g7le-action-event-${y}`,children:[i.jsx("div",{style:MA,children:o(`layout_editor.action.event.${y}`)}),i.jsx(Gt,{actions:DA(e,y),onChange:g=>r(NA(e,y,g)),t:o,recipes:c,candidatePools:p,actionChipCandidates:t?.actionChipCandidates??null,addContext:"component",showSourceBadge:!0,testIdPrefix:`g7le-action-slot-${y}`})]},y))})}const Nf={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},MA={fontSize:12,fontWeight:700,color:"#475569",marginBottom:6};function Aa(e,t,n){if(!t)return n;const o=e(t);return!o||o===t||o.startsWith("$t:")?n:o}function LA(e,t){return Aa(t,e.labelKey,e.path||e.sourceId)}function PA({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),[y,g]=u.useState(""),m=Aa(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(()=>Fi(n,t.shape).map(_=>({..._,resolvedLabel:LA(_,o)})),[n,t.shape,o]),b=u.useMemo(()=>Ki(v,y),[v,y]),x=w=>{const _={...e.props??{}};w===void 0?delete _[t.propKey]:_[t.propKey]=w,r({...e,props:_})},k=w=>{x(En(w.sourceId,w.path,t.shape)),f(!1),g("")};return i.jsxs("div",{"data-testid":`g7le-binding-row-${t.propKey}`,style:jA,children:[i.jsxs("div",{style:HA,children:[i.jsx("span",{style:{fontWeight:600,fontSize:12},children:m}),i.jsx("span",{style:FA,children:h}),t.required&&i.jsx("span",{"data-testid":`g7le-binding-required-${t.propKey}`,style:KA,children:o("layout_editor.binding.required")})]}),c?i.jsxs("div",{"data-testid":`g7le-binding-complex-${t.propKey}`,style:GA,children:[o("layout_editor.binding.complex"),i.jsx("code",{style:zf,children:l})]}):d?i.jsxs("div",{style:VA,children:[i.jsx("code",{"data-testid":`g7le-binding-expr-${t.propKey}`,style:zf,children:l}),i.jsx("button",{type:"button","data-testid":`g7le-binding-clear-${t.propKey}`,onClick:()=>x(void 0),style:qA,children:o("layout_editor.binding.clear")})]}):i.jsx("div",{"data-testid":`g7le-binding-empty-${t.propKey}`,style:UA,children:o("layout_editor.binding.not_connected")}),d&&(t.shape==="array"||t.shape==="object")&&t.itemFields&&t.itemFields.length>0&&i.jsxs("div",{style:YA,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(w=>!w),style:XA,children:["🔍 ",o("layout_editor.binding.search")]}),p&&i.jsxs("div",{"data-testid":`g7le-binding-picker-${t.propKey}`,style:JA,children:[i.jsx("input",{type:"text",autoFocus:!0,"data-testid":`g7le-binding-search-input-${t.propKey}`,value:y,placeholder:o("layout_editor.binding.search_placeholder"),onChange:w=>g(w.target.value),style:ZA}),i.jsx("div",{style:QA,children:b.length===0?i.jsx("div",{style:RA,children:o("layout_editor.binding.no_results")}):b.map(w=>i.jsxs("button",{type:"button","data-testid":`g7le-binding-candidate-${w.expression}`,onClick:()=>k(w),style:e6,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:t6,children:[Aa(o,w.groupLabelKey,w.sourceId)," · ",w.path||w.sourceId]})]}),i.jsx("span",{style:n6,children:w.preview})]},w.expression))})]})]})]})}function OA({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:BA,children:[i.jsxs("div",{style:WA,children:["🔗 ",o("layout_editor.binding.section_title")]}),t.map(s=>i.jsx(PA,{node:e,spec:s,candidates:n,t:o,onPatchNode:r},s.propKey)),i.jsx("div",{style:o6})]})}const BA={display:"flex",flexDirection:"column",marginBottom:8},WA={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:6},jA={display:"flex",flexDirection:"column",gap:4,padding:"8px 0"},HA={display:"flex",alignItems:"center",gap:6},FA={fontSize:10,padding:"1px 6px",borderRadius:4,background:"#e0e7ff",color:"#3730a3"},KA={fontSize:10,padding:"1px 6px",borderRadius:4,background:"#fef3c7",color:"#92400e"},VA={display:"flex",alignItems:"center",gap:6},UA={fontSize:11,color:"#94a3b8"},zf={fontSize:11,fontFamily:"monospace",background:"#f1f5f9",padding:"2px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all"},qA={fontSize:11,border:"1px solid #e2e8f0",borderRadius:4,background:"#fff",color:"#dc2626",padding:"2px 8px",cursor:"pointer"},GA={display:"flex",flexDirection:"column",gap:2,fontSize:11,color:"#64748b"},YA={fontSize:10,color:"#94a3b8"},XA={fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#334155",padding:"4px 10px",cursor:"pointer",textAlign:"left",width:"100%"},JA={marginTop:4,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",padding:6},ZA={width:"100%",padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"},QA={marginTop:4,maxHeight:200,overflowY:"auto",display:"flex",flexDirection:"column",gap:2},RA={fontSize:11,color:"#94a3b8",padding:"8px 0",textAlign:"center"},e6={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8,border:"none",background:"transparent",cursor:"pointer",padding:"6px 8px",borderRadius:4,textAlign:"left"},t6={fontSize:10,color:"#94a3b8"},n6={fontSize:10,color:"#64748b",fontFamily:"monospace",whiteSpace:"nowrap"},o6={borderTop:"1px solid #e2e8f0",marginTop:4};function r6({node:e,candidates:t,t:n,onPatchNode:o,templateIdentifier:r}){const s=typeof e.text=="string"?e.text:"",{state:a}=Je(),l=r??a.templateIdentifier,d=a.selectedRoute?.layoutName??null,c=a.locale,[p,f]=u.useState(!1),y=/^\s*\$t:custom\.[A-Za-z0-9._-]+\s*$/.test(s),m=Zl(s)&&(mt(s)?.key.startsWith("custom.")??!1)||y,h=u.useMemo(()=>m?mt(s):null,[m,s]),v=u.useMemo(()=>m?[]:Fl(s),[m,s]),b=T=>{o({...e,text:T})},x=()=>{if(!(typeof window>"u"))try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:l,locale:c}}))}catch{}},k=(T,$)=>{const A=En($.sourceId,$.path,"scalar");b(wb(s,T,A))},w=T=>{const $=mt(s);b(mo(s,T));const A=$?.key;l&&A&&Fd(l,A,T).then(x)},_=T=>{const $=n(T);return $&&$!==T&&!$.startsWith("$t:")?$:""},C=T=>T.replace(/\$t:[a-zA-Z0-9._-]+/g,$=>_($.slice(3))).replace(/\s+/g," ").trim(),E=T=>{p||(f(!0),ls(l,d,c,s,s.length,T.sourceId,T.path,"scalar",C,$=>n($)).then($=>{$.kind==="ok"&&(b($.text),x())}).finally(()=>f(!1)))},S=T=>{p||!h&&!y||(f(!0),wr(l,c,s,Number.MAX_SAFE_INTEGER,T.sourceId,T.path,"scalar").then($=>{$.kind==="ok"&&(b($.text),x())}).finally(()=>f(!1)))};if(m){const T=h?.params??[];return i.jsxs("div",{"data-testid":"g7le-inline-binding-section",style:Mf,children:[i.jsxs("div",{style:Lf,children:["🔗 ",n("layout_editor.inline_binding.section_title")]}),T.length===0?i.jsx("div",{"data-testid":"g7le-inline-binding-none",style:Bf,children:n("layout_editor.inline_binding.none")}):T.map($=>i.jsx("div",{"data-testid":`g7le-inline-binding-param-${$.name}`,style:Pf,children:$.parsed===null?i.jsxs("div",{"data-testid":`g7le-inline-binding-param-complex-${$.name}`,style:s6,children:[n("layout_editor.inline_binding.complex"),i.jsx("code",{style:Ta,children:$.expression})]}):i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:Of,children:[i.jsx("code",{"data-testid":`g7le-inline-binding-param-expr-${$.name}`,style:Ta,children:$.expression}),i.jsx("button",{type:"button","data-testid":`g7le-inline-binding-param-clear-${$.name}`,onClick:()=>w($.name),style:i6,children:n("layout_editor.inline_binding.clear")})]}),i.jsx($t,{candidates:t,t:n,onSelect:A=>k($.name,A),testIdSuffix:`param-${$.name}`})]})},$.name)),i.jsxs("div",{"data-testid":"g7le-inline-binding-param-append",style:Wf,children:[i.jsx("div",{style:Da,children:n("layout_editor.inline_binding.append_hint")}),i.jsx($t,{candidates:t,t:n,onSelect:S,testIdSuffix:"param-append"})]}),i.jsx("div",{"data-testid":"g7le-inline-binding-param-hint",style:Da,children:n("layout_editor.inline_binding.param_hint")}),i.jsx("div",{style:jf})]})}return i.jsxs("div",{"data-testid":"g7le-inline-binding-section",style:Mf,children:[i.jsxs("div",{style:Lf,children:["🔗 ",n("layout_editor.inline_binding.section_title")]}),v.length===0?i.jsx("div",{"data-testid":"g7le-inline-binding-none",style:Bf,children:n("layout_editor.inline_binding.none")}):v.map(T=>i.jsx("div",{"data-testid":`g7le-inline-binding-row-${T.bindingIndex}`,style:Pf,children:i.jsx("div",{style:Of,children:i.jsx("code",{"data-testid":`g7le-inline-binding-expr-${T.bindingIndex}`,style:Ta,children:T.expression})})},T.bindingIndex)),i.jsxs("div",{"data-testid":"g7le-inline-binding-append",style:Wf,children:[i.jsx("div",{style:Da,children:n("layout_editor.inline_binding.append_hint")}),i.jsx($t,{candidates:t,t:n,onSelect:E,testIdSuffix:"append"})]}),i.jsx("div",{style:jf})]})}const Mf={display:"flex",flexDirection:"column",marginBottom:8},Lf={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:6},Pf={display:"flex",flexDirection:"column",gap:4,padding:"8px 0"},Of={display:"flex",alignItems:"center",gap:6},Bf={fontSize:11,color:"#94a3b8"},Ta={fontSize:11,fontFamily:"monospace",background:"#f1f5f9",padding:"2px 6px",borderRadius:4,color:"#0f172a",wordBreak:"break-all"},i6={fontSize:11,border:"1px solid #e2e8f0",borderRadius:4,background:"#fff",color:"#dc2626",padding:"2px 8px",cursor:"pointer"},s6={display:"flex",flexDirection:"column",gap:2,fontSize:11,color:"#64748b"},Wf={display:"flex",flexDirection:"column",gap:2,padding:"8px 0 0"},Da={fontSize:11,color:"#475569",fontWeight:600},jf={borderTop:"1px solid #e2e8f0",marginTop:4};function Hf(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 Hf(t,e.labelKey,e.path||e.sourceId)}function l6(e){const t=e.iteration;return t&&typeof t=="object"?t:null}function d6({node:e,candidates:t,t:n,onPatchNode:o}){const r=l6(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,y]=u.useState(""),g=u.useMemo(()=>Fi(t,"array").map(w=>({...w,resolvedLabel:a6(w,n)})),[t,n]),m=u.useMemo(()=>Ki(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,b=k=>{const w={...r};k===void 0?delete w.source:w.source=k,o({...e,iteration:w})},x=k=>{b(En(k.sourceId,k.path,"array")),p(!1),y("")};return i.jsxs("div",{"data-testid":"g7le-iteration-binding-section",style:c6,children:[i.jsxs("div",{style:u6,children:["🔁 ",n("layout_editor.binding.iteration_title")]}),i.jsx("div",{style:p6,children:n("layout_editor.binding.iteration_hint")}),i.jsxs("div",{style:f6,children:[i.jsxs("div",{style:g6,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:v6,children:[n("layout_editor.binding.complex"),i.jsx("code",{style:Ff,children:a})]}):l?i.jsxs("div",{style:y6,children:[i.jsx("code",{"data-testid":"g7le-iteration-binding-expr",style:Ff,children:a}),i.jsx("button",{type:"button","data-testid":"g7le-iteration-binding-clear",onClick:()=>b(void 0),style:m6,children:n("layout_editor.binding.clear")})]}):i.jsx("div",{"data-testid":"g7le-iteration-binding-empty",style:b6,children:n("layout_editor.binding.not_connected")}),(h||v)&&i.jsxs("div",{"data-testid":"g7le-iteration-vars",style:_6,children:[h&&i.jsxs("span",{children:[n("layout_editor.binding.iteration_item_var"),": ",i.jsx("code",{style:Kf,children:h})]}),v&&i.jsxs("span",{children:[n("layout_editor.binding.iteration_index_var"),": ",i.jsx("code",{style:Kf,children:v})]})]}),!d&&i.jsxs("div",{style:{marginTop:4},children:[i.jsxs("button",{type:"button","data-testid":"g7le-iteration-binding-search-toggle",onClick:()=>p(k=>!k),style:x6,children:["🔍 ",n("layout_editor.binding.search")]}),c&&i.jsxs("div",{"data-testid":"g7le-iteration-binding-picker",style:w6,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:k=>y(k.target.value),style:k6}),i.jsx("div",{style:S6,children:m.length===0?i.jsx("div",{style:C6,children:n("layout_editor.binding.no_results")}):m.map(k=>i.jsxs("button",{type:"button","data-testid":`g7le-iteration-binding-candidate-${k.expression}`,onClick:()=>x(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:[Hf(n,k.groupLabelKey,k.sourceId)," · ",k.path||k.sourceId]})]}),i.jsx("span",{style:I6,children:k.preview})]},k.expression))})]})]})]}),i.jsx("div",{style:A6})]})}const c6={display:"flex",flexDirection:"column",marginBottom:8},u6={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:4},p6={fontSize:10,color:"#94a3b8",marginBottom:6,lineHeight:1.4},f6={display:"flex",flexDirection:"column",gap:4,padding:"8px 0"},g6={display:"flex",alignItems:"center",gap:6},h6={fontSize:10,padding:"1px 6px",borderRadius:4,background:"#e0e7ff",color:"#3730a3"},y6={display:"flex",alignItems:"center",gap:6},b6={fontSize:11,color:"#94a3b8"},Ff={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={display:"flex",gap:12,fontSize:10,color:"#94a3b8",marginTop:2},Kf={fontSize:10,fontFamily:"monospace",background:"#f1f5f9",padding:"1px 4px",borderRadius:3,color:"#475569"},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},T6=new Set(["Span","P","H1","H2","H3","H4","H5","H6","A","Button","Li","Label"]);function D6(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 T6.has(o)?!0:typeof e.text=="string"}const yn={direction:"flexDirection",justify:"flexJustify",align:"flexAlign",wrap:"flexWrap",gap:"flexGap",enable:"flexEnable"},hi={grow:"flexItemGrow",selfAlign:"flexItemAlign",order:"flexItemOrder"};function Vf(e){const t=e?.flexEditor;return t==="container"||t==="item"||t==="auto"?t:null}function N6(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 z6(e,t,n=Wt){if(!e||!t)return!1;const o=Do(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 M6(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:N6(t))?{showContainer:!0,showEnableButton:!1,showDisableButton:o}:{showContainer:!1,showEnableButton:!0,showDisableButton:!1}}return{showContainer:!1,showEnableButton:!1,showDisableButton:!1}}const L6={[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"},P6={[hi.grow]:"layout_editor.flex.item_grow",[hi.selfAlign]:"layout_editor.flex.item_align",[hi.order]:"layout_editor.flex.item_order"};function O6({node:e,spec:t,capability:n,t:o,onPatchNode:r,liveElement:s,scope:a=Wt}){const l=Vf(n),d=Ct(t,yn.enable),c=z6(e,d,a),{showContainer:p,showEnableButton:f,showDisableButton:y}=M6(l,s,c,!!d,a),g=Object.values(yn).filter(_=>_!==yn.enable&&Ct(t,_)),m=Object.values(hi).filter(_=>Ct(t,_)),h=d?.options,v=d?.onValue??h?.[0]?.value??!0,b=Array.isArray(h)&&h.length>=2?h[1].value:void 0,x=()=>{if(!d)return;const _=fn(e,d,v,a);r(_)},k=()=>{if(!d)return;const _=a.breakpoint!=="base"&&b!==void 0?b:void 0,C=fn(e,d,_,a);r(C)},w=(_,C,E)=>i.jsx("div",{"data-testid":E,style:{display:"flex",flexDirection:"column"},children:_.map(S=>{const T=Ct(t,S);if(!T)return null;const $=T.label?T:{...T,label:`$t:${C[S]}`};return i.jsx(pi,{controlKey:S,control:$,node:e,t:o,onPatch:r,scope:a},S)})});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:x,style:B6,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:Uf,children:o("layout_editor.flex.container_title")}),w(g,L6,"g7le-flex-container-controls"),y&&i.jsx("button",{type:"button","data-testid":"g7le-flex-disable",onClick:k,style:W6,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:Uf,children:o("layout_editor.flex.item_title")}),w(m,P6,"g7le-flex-item-controls")]}),!p&&!f&&l!=="item"&&i.jsx("div",{"data-testid":"g7le-flex-empty",style:j6,children:o("layout_editor.flex.not_flex")})]})}const Uf={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:6},B6={padding:"8px 12px",fontSize:12,border:"1px dashed #2563eb",borderRadius:6,background:"#eff6ff",color:"#2563eb",cursor:"pointer"},W6={marginTop:8,padding:"6px 10px",fontSize:12,border:"1px solid #e2e8f0",borderRadius:6,background:"#f8fafc",color:"#64748b",cursor:"pointer"},j6={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},qf=["desktop","tablet","mobile","portable"],Na=1280,H6=820,F6=390,K6=1920,V6=320;function U6(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 q6(e){const t=[...qf],n=new Set(qf);for(const o of U6(e))!n.has(o)&&!t.includes(o)&&t.push(o);return t}function G6(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 Y6(e){switch(e){case"desktop":return Na;case"tablet":return H6;case"mobile":return F6}const t=e in To?To[e]:Mn.parseRange(e);return!t||!Number.isFinite(t.max)?Na:Math.round(Math.max(V6,Math.min(K6,t.max)))}function Gf(){const t=Ft()?.document?.raw?.components;return u.useMemo(()=>q6(t??null),[t])}const X6={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"},J6=[{key:"base",labelKey:"layout_editor.property_modal.scope.scheme_light"},{key:"dark",labelKey:"layout_editor.property_modal.scope.scheme_dark"}];function Yf({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(""),[y,g]=u.useState(null),m=Gf(),h=u.useMemo(()=>{const k=["base",...m],w=new Set(k);for(const _ of Object.keys(n.responsive??{}))_!=="base"&&!w.has(_)&&(w.add(_),k.push(_));return e.breakpoint!=="base"&&!w.has(e.breakpoint)&&k.push(e.breakpoint),k},[m,n.responsive,e.breakpoint]),v=k=>t({...e,colorScheme:k}),b=k=>t({...e,breakpoint:k}),x=()=>{const k=d.trim(),w=p.trim();if(k===""&&w===""){g(o("layout_editor.property_modal.scope.custom_invalid"));return}const _=`${k}-${w}`;if(!gC(_)){g(o("layout_editor.property_modal.scope.custom_invalid"));return}g(null),l(!1),c(""),f(""),b(_)};return i.jsxs("div",{className:"g7le-style-scope-tabs","data-testid":"g7le-style-scope-tabs",style:Z6,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:Xf,children:J6.map(k=>{const w=e.colorScheme===k.key;return i.jsxs("button",{type:"button",role:"tab","aria-selected":w,"data-testid":`g7le-style-scheme-${k.key}`,"data-active":w?"true":"false",onClick:()=>v(k.key),style:Jf(w),children:[o(k.labelKey),k.key==="dark"&&Gs(n,{colorScheme:"dark",breakpoint:e.breakpoint})&&i.jsx("span",{"data-testid":"g7le-style-scheme-dark-dot",style:Zf})]},k.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:Xf,children:[h.map(k=>{const w=e.breakpoint===k,_=k==="base"||wu(k),C=k==="base"?"layout_editor.property_modal.scope.device_base":X6[k],E=C?o(C):k,S=_?`g7le-style-bp-${k}`:`g7le-style-bp-custom-${k}`;return i.jsxs("button",{type:"button",role:"tab","aria-selected":w,"data-testid":S,"data-active":w?"true":"false",onClick:()=>b(k),style:Jf(w),children:[E,Gs(n,{colorScheme:"base",breakpoint:k})&&i.jsx("span",{"data-testid":`${S}-dot`,style:Zf})]},String(k))}),i.jsxs("button",{type:"button","data-testid":"g7le-style-bp-add-custom",onClick:()=>l(k=>!k),style:eT,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:Q6,children:[i.jsx("input",{type:"number","data-testid":"g7le-style-custom-min",placeholder:o("layout_editor.property_modal.scope.custom_min"),value:d,onChange:k=>c(k.target.value),style:Qf}),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:k=>f(k.target.value),style:Qf}),i.jsx("button",{type:"button","data-testid":"g7le-style-custom-confirm",onClick:x,style:tT,children:o("layout_editor.property_modal.scope.add_custom")})]}),y&&i.jsx("div",{"data-testid":"g7le-style-custom-error",style:nT,children:y}),e.breakpoint!=="base"&&!wu(e.breakpoint)&&i.jsx("div",{"data-testid":"g7le-style-custom-priority-note",style:oT,children:o("layout_editor.property_modal.scope.custom_priority_note")}),s&&Gs(n,e)&&i.jsxs("button",{type:"button","data-testid":"g7le-style-scope-reset",onClick:s,style:R6,children:["↺ ",o("layout_editor.property_modal.scope.reset_to_base")]})]})}const Z6={display:"flex",flexDirection:"column",gap:0,padding:"0 0 8px",borderBottom:"1px solid #e2e8f0",marginBottom:8},Q6={display:"flex",gap:6,alignItems:"center",marginTop:4},Xf={display:"flex",gap:2,flexWrap:"wrap",borderBottom:"1px solid #e2e8f0",margin:"0 -16px",padding:"0 12px"};function Jf(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 Zf={display:"inline-block",width:5,height:5,borderRadius:3,background:"#f59e0b"},R6={alignSelf:"flex-start",marginTop:2,padding:"3px 8px",fontSize:10,border:"1px solid #cbd5e1",borderRadius:6,background:"#f8fafc",color:"#475569",cursor:"pointer"},eT={padding:"6px 12px",fontSize:11,border:"none",borderBottom:"2px dashed #cbd5e1",background:"transparent",color:"#475569",cursor:"pointer",marginBottom:-1},Qf={width:70,padding:"4px 6px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6},tT={padding:"4px 10px",fontSize:11,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"},nT={fontSize:11,color:"#dc2626"},oT={fontSize:10,color:"#94a3b8"},Rf=new Map;function Pn(e,t){Rf.set(e,t)}function rT(e){return e?Rf.get(e)??null:null}const za={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"}}},iT=["id"];function sT(e){return e===!1?[]:Array.isArray(e)?e.filter(t=>t in za):[...iT]}function eg(e){const t=e.props?.id??e.id;return typeof t=="string"&&t.length>0?`${t}-scope`:"scope"}function aT({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=eg(e)),t(h)},f=h=>{const v={...e};v.isolatedScopeId=h.trim()===""?eg(e):h,t(v)},y=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:lT,children:[i.jsx("div",{style:dT,children:n("layout_editor.core_props.isolatedState.label")}),i.jsxs("div",{style:cT,children:[i.jsx("button",{type:"button","data-testid":"g7le-isolated-toggle",role:"switch","aria-checked":a,onClick:p,style:uT(a),children:n(a?"layout_editor.overlay.on":"layout_editor.overlay.off")}),a?null:i.jsx("span",{"data-testid":"g7le-isolated-off-hint",style:pT,children:n("layout_editor.core_props.isolatedState.off_hint")})]}),a?i.jsxs(i.Fragment,{children:[i.jsxs("div",{style:tg,children:[i.jsx("label",{style:ng,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:fT}),g.length>0?i.jsxs("div",{"data-testid":"g7le-isolated-scopeid-picker",style:gT,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:yT,children:g.map(h=>i.jsx("button",{type:"button","data-testid":`g7le-isolated-scopeid-candidate-${h}`,onClick:()=>{f(h),c("")},style:bT,children:h},h))})]}):null,m?i.jsxs("p",{"data-testid":"g7le-isolated-scopeid-dup",style:mT,children:["ⓘ ",n("layout_editor.core_props.isolatedScopeId.duplicate")]}):null]}),i.jsxs("div",{style:tg,children:[i.jsx("label",{style:ng,children:n("layout_editor.core_props.isolatedState.initial_label")}),i.jsx("div",{"data-testid":"g7le-isolated-initial-value",children:i.jsx(Nn,{value:s.isolatedState??{},onChange:y,t:n,path:"isolatedState",scope:"isolated-node"})})]})]}):null]})}const lT={display:"flex",flexDirection:"column",gap:8,padding:10,border:"1px solid #e2e8f0",borderRadius:8,minWidth:0},dT={fontSize:12,fontWeight:700,color:"#0f172a"},cT={display:"flex",gap:8,alignItems:"center"},uT=e=>({padding:"4px 12px",fontSize:11,border:`1px solid ${e?"#3b82f6":"#cbd5e1"}`,borderRadius:14,background:e?"#eff6ff":"#fff",color:e?"#1d4ed8":"#64748b",cursor:"pointer"}),pT={fontSize:11,color:"#94a3b8"},tg={display:"flex",flexDirection:"column",gap:4,minWidth:0},ng={fontSize:11,color:"#64748b"},fT={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box",width:"100%"},gT={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"},yT={display:"flex",flexDirection:"column",maxHeight:120,overflowY:"auto"},bT={textAlign:"left",padding:"4px 6px",fontSize:12,border:"none",background:"transparent",cursor:"pointer",borderRadius:4,color:"#0f172a"},mT={margin:0,fontSize:11,color:"#64748b"},vT={borderTop:"2px solid #c7d2fe",background:"#eef2ff",padding:"10px 12px",display:"flex",flexDirection:"column",gap:8},og={fontSize:13,fontWeight:700,color:"#3730a3",display:"flex",alignItems:"center",gap:6},_T={fontSize:11,fontWeight:600,color:"#4338ca",background:"#e0e7ff",border:"1px solid #c7d2fe",borderRadius:4,padding:"1px 6px"},Ma={fontSize:11,color:"#6366f1"},xT={alignSelf:"flex-start",fontSize:12,fontWeight:600,color:"#fff",background:"#4f46e5",border:"none",borderRadius:4,padding:"4px 10px",cursor:"pointer"},wT={opacity:.5,cursor:"not-allowed"},kT={fontSize:11,color:"#dc2626"};function ST({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,y]=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),y(!1);try{await n(o),y(!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:og,children:i.jsx("span",{style:_T,"data-testid":"g7le-injected-props-origin-badge",children:t("layout_editor.property_modal.injected_props.origin",{source:g})})}),i.jsx(Bs,{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??{}),y(!1)},onValidityChange:h=>{a(h),h&&d(null),y(!1)}}),l&&i.jsx("div",{style:kT,"data-testid":"g7le-injected-props-error",children:l}),f&&i.jsx("div",{style:{...Ma,color:"#16a34a"},"data-testid":"g7le-injected-props-saved",children:t("layout_editor.property_modal.injected_props.saved")}),i.jsx("div",{style:Ma,children:t("layout_editor.property_modal.injected_props.save_target")}),i.jsx("button",{type:"button","data-testid":"g7le-injected-props-save",style:{...xT,...c||!s?wT: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 CT({injectedProps:e,t,onSaveInjectedProps:n}){return!Array.isArray(e)||e.length===0?null:i.jsxs("div",{style:vT,"data-testid":"g7le-injected-props-section",children:[i.jsxs("div",{style:og,children:["🧩 ",t("layout_editor.property_modal.injected_props.title")]}),i.jsx("div",{style:Ma,children:t("layout_editor.property_modal.injected_props.help")}),e.map(o=>i.jsx(ST,{entry:o,t,onSave:r=>n(o.extensionId,r)},o.extensionId))]})}function $T(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 ET({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:y,scope:g=Wt,onScopeChange:m,templateIdentifier:h,initialTab:v,onSaveInjectedProps:b,branchLabel:x,isolatedScopeIdCandidates:k,usedScopeIds:w}){const _=e.__injectedProps,C=Array.isArray(_)&&_.length>0&&!!b,E=ve=>{m?.(ve)},S=()=>{r(xC(e,g))},T=typeof e.name=="string"?e.name:"",$=Oi(t,T),z=$T(n,T)?.settings,D=!!(z?.groups&&z.groups.length>0),O=Array.isArray($?.propControls)?$.propControls:[],M=sT($?.coreProps),B=new Set(M.map(ve=>za[ve].apply?.propKey)),N=O.filter(ve=>{const he=Ct(t,ve)?.apply?.propKey;return!(he!==void 0&&B.has(he))}),H=typeof $?.nodeEditor?.kind=="string"?$.nodeEditor.kind:void 0,L=$?.nodeEditor?.params,I=H?rT(H):null,P=!!I,F=Array.isArray($?.dataProps)?$.dataProps:[],G=F.length>0,V=!!(e.iteration&&typeof e.iteration=="object"),Y=D6(e,$),Z=M.length>0||N.length>0||P||G||Y||V,se=Array.isArray($?.styleControls)?$.styleControls:[],re=Array.isArray($?.advanced)?$.advanced:[],ee=(Array.isArray($?.events)?$.events:[]).length>0,fe=Vf($),K=se.length>0||fe!==null,me=!($?.visibilityCondition===!1)&&(Z||K||ee||D||re.length>0),Ce=u.useMemo(()=>{const ve=[];return D&&ve.push("settings"),Z&&ve.push("props"),K&&ve.push("style"),ee&&ve.push("action"),me&&ve.push("visibility"),ve.push("translation"),re.length>0&&ve.push("advanced"),ve},[D,Z,K,ee,me,re.length]),ze=N.length>0||P||G||V,[Se,qe]=u.useState(v&&Ce.includes(v)?v:D?"settings":ze?"props":K?"style":Z?"props":Ce[0]??"style"),De=_A(e),Pe=!Z&&!K&&!D&&!ee&&!me&&re.length===0,Qe=$?.label?$.label.startsWith("$t:")?o($.label.slice(3)):$.label:T||o("layout_editor.property_modal.element"),Me=(ve,te)=>{const he={...e.props??{}};te===void 0?delete he[ve]:he[ve]=te,r({...e,props:he})},Re={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:IT,children:[i.jsxs("div",{"data-modal-drag-handle":!0,"data-testid":"g7le-property-modal-header",style:AT,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:Qe}):o("layout_editor.property_modal.title",{name:Qe})}),i.jsx("button",{type:"button","data-testid":"g7le-property-modal-close","aria-label":"close",onClick:s,style:TT,children:"✕"})]}),De&&i.jsx("div",{"data-testid":"g7le-property-modal-advanced-badge",style:DT,children:o("layout_editor.property_modal.advanced_badge")}),x&&i.jsx("div",{"data-testid":"g7le-property-modal-branch-badge",style:NT,children:o("layout_editor.property_modal.branch_badge",{device:x})}),i.jsx("div",{style:zT,role:"tablist",children:Ce.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:()=>qe(ve),style:{...MT,color:Se===ve?"#2563eb":"#64748b",borderBottomColor:Se===ve?"#2563eb":"transparent"},children:Re[ve]},ve))}),i.jsxs("div",{style:LT,"data-testid":"g7le-property-modal-body",children:[Pe&&!C&&i.jsx("div",{"data-testid":"g7le-property-modal-no-editable",style:ig,children:o("layout_editor.property_modal.no_editable_props")}),C&&i.jsx(CT,{injectedProps:_,t:o,onSaveInjectedProps:b}),Se==="settings"&&z&&i.jsx(lA,{spec:z,node:e,t:o,onPatchProp:Me}),Se==="props"&&i.jsxs("div",{"data-testid":"g7le-property-props-tab",style:{display:"flex",flexDirection:"column"},children:[V&&i.jsx(d6,{node:e,candidates:f??[],t:o,onPatchNode:r}),G&&i.jsx(OA,{node:e,dataProps:F,candidates:f??[],t:o,onPatchNode:r}),Y&&i.jsx(r6,{node:e,candidates:f??[],t:o,onPatchNode:r,templateIdentifier:h}),P&&I&&i.jsx(I,{node:e,params:L,spec:t,manifest:n,t:o,onPatchNode:r,templateIdentifier:h,candidates:f}),M.map(ve=>i.jsx(pi,{controlKey:`core-${ve}`,control:za[ve],node:e,t:o,onPatch:r,scope:Wt,bindingCandidates:f},`core-${ve}`)),N.map(ve=>{const te=Ct(t,ve);return te?i.jsx(pi,{controlKey:ve,control:te,node:e,t:o,onPatch:r,scope:Wt,bindingCandidates:f},ve):null}),i.jsx(aT,{node:e,onPatchNode:r,t:o,scopeIdCandidates:k,usedScopeIds:w})]}),Se==="style"&&i.jsxs("div",{"data-testid":"g7le-property-style-tab",style:{display:"flex",flexDirection:"column"},children:[i.jsx("div",{style:rg,children:i.jsx(Yf,{scope:g,onChange:E,node:e,t:o,onClearScope:S})}),fe!==null&&i.jsx(O6,{node:e,spec:t,capability:$,t:o,onPatchNode:r,liveElement:y,scope:g}),se.map(ve=>{const te=Ct(t,ve);return te?i.jsx(pi,{controlKey:ve,control:te,node:e,t:o,onPatch:r,scope:g},ve):null})]}),Se==="action"&&i.jsx(zA,{node:e,spec:t,capability:$,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:rg,children:i.jsx(Yf,{scope:g,onChange:E,node:e,t:o,showColorScheme:!1})}),i.jsx(Eu,{node:e,spec:t,t:o,onPatchNode:r,dataSourceCandidates:c,stateKeyCandidates:p,scope:g})]}),Se==="translation"&&(h?i.jsx(Ud,{customKey:Vd(e),templateIdentifier:h,t:o,paramLabels:hv(e),onRemoveParam:ve=>{const te=typeof e.text=="string"?e.text:"";r({...e,text:mo(te,ve)});const he=Vd(e);h&&he&&kr(h,he,ve)}}):i.jsx("div",{"data-testid":"g7le-property-translation-deferred",style:ig,children:o("layout_editor.translation.not_a_key")})),Se==="advanced"&&i.jsx(wA,{node:e,advanced:re,t:o,onPatch:r,permissionCandidates:l})]}),i.jsxs("div",{style:PT,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:OT,children:o("layout_editor.property_modal.delete_element")}),i.jsx("button",{type:"button","data-testid":"g7le-property-modal-done",onClick:s,style:BT,children:o("layout_editor.property_modal.close")})]})]})]})}const IT={display:"flex",flexDirection:"column",width:420,maxWidth:"92vw"},AT={display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderBottom:"1px solid #e2e8f0",cursor:"move",userSelect:"none"},TT={border:"none",background:"transparent",fontSize:14,cursor:"pointer",color:"#64748b"},DT={margin:"8px 16px 0",padding:"6px 10px",fontSize:11,background:"#fef3c7",color:"#92400e",borderRadius:6},NT={margin:"8px 16px 0",padding:"6px 10px",fontSize:11,background:"#dbeafe",color:"#1e40af",borderRadius:6},zT={display:"flex",gap:2,padding:"0 12px",borderBottom:"1px solid #e2e8f0",overflowX:"auto"},MT={padding:"8px 10px",fontSize:12,border:"none",borderBottom:"2px solid transparent",background:"transparent",cursor:"pointer",whiteSpace:"nowrap"},LT={padding:16,overflowY:"auto",maxHeight:"60vh"},rg={position:"sticky",top:-16,zIndex:2,background:"#fff",margin:"-16px -16px 0",padding:"6px 16px 0"},ig={fontSize:12,color:"#94a3b8",padding:"16px 0",textAlign:"center"},PT={display:"flex",alignItems:"center",justifyContent:"space-between",padding:"12px 16px",borderTop:"1px solid #e2e8f0"},OT={padding:"6px 12px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},BT={padding:"6px 12px",fontSize:12,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",cursor:"pointer"},La="g7le:component-target-picked",Pa="g7le:component-target-pick-request";let WT=1;function jT({value:e,onChange:t,t:n,control:o}){const r=yo(),s=e==null?"":String(e),a=o?.allowManualInput!==!1,l=u.useCallback(()=>{if(typeof window>"u")return;const d=`pick-${WT++}`,p=r.stack[r.stack.length-1]?.id;p&&r.minimize(p,n("layout_editor.target_picker.minimized_hint"));const f=y=>{const g=y.detail;g?.requestId===d&&(window.removeEventListener(La,f),p&&r.restore(p),!g.cancelled&&typeof g.id=="string"&&t(g.id))};window.addEventListener(La,f),window.dispatchEvent(new CustomEvent(Pa,{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 HT(e,t,n,o,r=fetch){const s=`/api/admin/templates/${encodeURIComponent(e)}/layout-extensions/${t}`;let a;try{a=await r(s,{headers:je(),credentials:"same-origin"})}catch(b){return{kind:"error",message:b instanceof Error?b.message:String(b)}}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,y=Array.isArray(c.injections)?[...c.injections]:[],g=y.findIndex(b=>b&&b.position==="inject_props"&&b.target_id===n);if(g<0)return{kind:"injection_not_found"};y[g]={...y[g],props:o};const m={...c,injections:y};let h;try{h=await r(s,{method:"PUT",headers:je({"Content-Type":"application/json"}),credentials:"same-origin",body:JSON.stringify({content:m,expected_lock_version:f})})}catch(b){return{kind:"error",message:b instanceof Error?b.message:String(b)}}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 sg=new Map;function Oa(e,t){sg.set(e,t)}function FT(e){return e?sg.get(e)??null:null}const ag="g7le.clipboard";function lg(){try{return typeof window>"u"||!window.sessionStorage?null:window.sessionStorage}catch{return null}}function KT(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 dg(e,t=0){const n=lg();if(!n)return!1;try{const o={node:KT(e),copiedAt:t};return n.setItem(ag,JSON.stringify(o)),!0}catch{return!1}}function VT(){const e=lg();if(!e)return null;try{const t=e.getItem(ag);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 Xo={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 Ba(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 UT(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=Ba(l)??d*40,p=Math.abs(c-t);p{if(!t)return;const m=Xo[y];if(m.width!==0&&!n||m.height!==0&&!o)return;const h=t.props?.style??{},v=s?.()??null,b=Ba(h.width)??(v?Math.round(v.width):0),x=Ba(h.height)??(v?Math.round(v.height):0);p.current={handle:y,startX:g.clientX,startY:g.clientY,startW:b,startH:x,node:t};const k=m.width!==0&&m.height!==0?"both":m.width!==0?"width":"height";d?.(k);let w=null;const _=E=>{const S=p.current;if(!S)return;const T=r||1,$=(E.clientX-S.startX)/T*Xo[S.handle].width,A=(E.clientY-S.startY)/T*Xo[S.handle].height;let z=S.node;if(Xo[S.handle].width!==0&&n){const D=cg(n,S.startW+$);z=fn(z,n,D)}if(Xo[S.handle].height!==0&&o){const D=cg(o,S.startH+A);z=fn(z,o,D)}w=z,a(z,k)},C=()=>{p.current=null,d?.(null),window.removeEventListener("pointermove",_),window.removeEventListener("pointerup",C),w&&l?.(w,k)};window.addEventListener("pointermove",_),window.addEventListener("pointerup",C)},[t,n,o,r,a,l,d]);return{enabledAxes:c,onHandlePointerDown:f}}const ug=320,pg=1920,YT=1024;function Wa(e){return Number.isFinite(e)?Math.round(Math.max(ug,Math.min(pg,e))):YT}function ja(e={}){const{state:t,dispatch:n}=Je(),{previewDevice:o,previewZoom:r,previewCustomWidth:s,previewColorScheme:a}=t,l=o==="custom"?Wa(s):Y6(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:Wa(g)})},[n]),y=u.useCallback(g=>{n({type:"SET_PREVIEW_COLOR_SCHEME",scheme:g})},[n]);return{device:o,deviceWidth:l,zoom:r,scale:d,customWidth:Wa(s),setDevice:c,setZoom:p,setCustomWidth:f,colorScheme:a,setColorScheme:y}}const yi="g7le-dnd-handle-";function XT(e){if(typeof e!="string"||!e.startsWith(yi))return null;const t=e.slice(yi.length);return t.length>0?t:null}function JT(e){return typeof CSS<"u"&&typeof CSS.escape=="function"?CSS.escape(e):e.replace(/["\\\]]/g,"\\$&")}function ZT(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(yi))return null;if(r){const l=e.closest(`[data-testid^="${yi}"]`);if(l&&t){const d=XT(l.getAttribute("data-testid"));if(d){const c=t.querySelector(`[data-editor-path="${JT(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 QT(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 RT="#ffffff",e4="#0f172a";function t4(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 n4(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=t4(e);if(!n)return!1;const[o,r,s]=n;return .299*o+.587*r+.114*s>=180}function o4(e,t,n){const o=typeof n?.color=="string"?n.color:null;return n4(e??o??t)?e4:RT}function r4({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),[y,g]=u.useState(t.trim().length>0),[m,h]=u.useState(null);u.useEffect(()=>{const w=p.current;if(w){w.textContent=t,w.focus();try{const _=window.document.createRange();_.selectNodeContents(w);const C=window.getSelection();C?.removeAllRanges(),C?.addRange(_)}catch{}f.current=!1}},[t]),u.useEffect(()=>{const w=p.current;if(!w||typeof window.getComputedStyle!="function"){h(null);return}try{h(window.getComputedStyle(w).color||null)}catch{h(null)}},[a,l]);const v=()=>(p.current?.textContent??"").trim(),b=()=>{f.current||(f.current=!0,r(v()))},x=()=>{f.current||(f.current=!0,s())},k=w=>{w.key==="Enter"&&!w.shiftKey?(w.preventDefault(),b()):w.key==="Escape"&&(w.preventDefault(),x())};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:k,onBlur:b,style:{outline:"2px solid #2563eb",outlineOffset:1,borderRadius:3,background:o4(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??{},...QT(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:w=>w.preventDefault(),onClick:w=>{w.preventDefault(),w.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")]})}),!y&&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 i4({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:y,onCancel:g}){const[m,h]=u.useState(null),v=u.useRef(""),[b,x]=u.useState(!1),k=u.useRef(!1),w=u.useRef(null),_=Ft(),C=u.useRef(()=>{}),[E,S]=u.useState(null),[T,$]=u.useState(!1),A=u.useRef(n??null);u.useEffect(()=>{n&&A.current!==n&&(A.current=n)},[n]);const z=u.useMemo(()=>{if(!n&&r)return r;const L={},I=mt(typeof t.text=="string"?t.text:"");for(const P of I?.params??[])L[P.name]=Vt(P.expression);return L},[t.text,n,r]);u.useEffect(()=>{let L=!1;if(!n){const I=o??"";return v.current=I,h(I),()=>{L=!0}}return(async()=>{const I=It(n,l);if(I!==void 0){v.current=I,h(I);return}const P=await cn(a,n);if(L)return;const F=P?.values?.[l]??"";v.current=F,h(F)})(),()=>{L=!0}},[a,n,l,o]);const D=async()=>{if(k.current)return;k.current=!0;const L=m??"";if(L===v.current){y();return}x(!0);let I=A.current;if(!I){if(!s){x(!1),k.current=!1;return}if(I=await s(L),x(!1),!I){k.current=!1;return}A.current=I,y();return}const P=await ko(a,I,l,L);if(x(!1),P.kind==="error"){k.current=!1;return}_?.markDirty?.(),y()},O=()=>{k.current||(k.current=!0,g())},M=L=>{S(L)},B=async L=>{if(!(E===null||!p||T)){$(!0);try{const I=A.current;I&&m!==null&&m!==v.current&&(await ko(a,I,l,m),v.current=m);const P=await p(E,L);P!==null&&(h(P),v.current=P,_?.markDirty?.())}finally{$(!1),S(null)}}},N=async L=>{if(!(!f||T)){$(!0);try{const I=A.current;I&&m!==null&&m!==v.current&&(await ko(a,I,l,m),v.current=m);const P=await f(L);P!==null&&(h(P),v.current=P,_?.markDirty?.())}finally{$(!1)}}},H=L=>{L.key==="Enter"&&!L.shiftKey?(L.preventDefault(),D()):L.key==="Escape"&&(L.preventDefault(),O())};return C.current=()=>{D()},u.useEffect(()=>{const L=P=>{const F=w.current;if(!F)return;const G=P.target;if(G&&F.contains(G))return;const V=G;V&&V.closest&&V.closest('[data-testid="g7le-inline-toolbar"], .g7le-inline-toolbar')||C.current()},I=w.current?.ownerDocument??document;return I.addEventListener("pointerdown",L,!0),()=>I.removeEventListener("pointerdown",L,!0)},[]),i.jsxs("div",{ref:w,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(mr,{value:m,onChange:h,t:d,paramLabels:z,testIdSuffix:"inline",onRequestInsert:p?M:void 0,onRemoveChip:f?L=>void N(L):void 0}),E!==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:L=>void B(L),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:b,onMouseDown:L=>L.preventDefault(),onClick:()=>void D(),style:{fontSize:11,border:"none",borderRadius:6,background:"#2563eb",color:"#fff",padding:"4px 12px",cursor:"pointer"},children:d(b?"layout_editor.translation.saving":"layout_editor.translation.save")}),i.jsx("span",{style:{fontSize:10,color:"#94a3b8"},children:d("layout_editor.translation.placeholder_locked")})]})]})}const s4=["fontWeight","fontBold","fontStyle","fontItalic","textDecoration","textUnderline","textAlign","fontSize","textColor"],a4={fontWeight:"B",fontBold:"B",fontStyle:"I",fontItalic:"I",textDecoration:"U",textUnderline:"U",textAlign:"≡",fontSize:"T",textColor:"A"},l4=[["fontWeight","fontBold"],["fontItalic","fontStyle"],["textUnderline","textDecoration"]];function fg({node:e,spec:t,t:n,onApplyControl:o,box:r,scope:s=Wt}){const a=typeof e.name=="string"?e.name:"",l=Oi(t,a),d=Array.isArray(l?.styleControls)?l.styleControls:[];let c=s4.filter(p=>d.includes(p)&&Ct(t,p)!==null);for(const p of l4){const f=p.filter(y=>c.includes(y));if(f.length>1){const y=f[0];c=c.filter(g=>!p.includes(g)||g===y)}}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(c4,{controlKey:p,node:e,spec:t,t:n,scope:s,onApplyControl:o},p))})}const d4={fontWeight:"bold",fontBold:"bold",fontStyle:"italic",fontItalic:"italic",textDecoration:"underline",textUnderline:"underline"};function gg(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 c4({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=Do(t,d,r),y=d4[e],g=y&&Array.isArray(c)?gg(c,y):void 0,m=!y,h=g!==void 0?f.value===g:p&&f.matched&&f.value!==void 0&&f.value!=="",v=o(`layout_editor.inline_edit.format.${e}`),b=_=>typeof _.label=="string"?_.label.startsWith("$t:")?o(_.label.slice(3)):_.label:String(_.value??""),x=()=>{s(e,_=>{const C=Do(_,d,r),E=Array.isArray(c)?gg(c,y):void 0,S=E!==void 0&&C.value===E?void 0:E;return fn(_,d,S,r)})},k=_=>{s(e,C=>{const S=Do(C,d,r).value===_?void 0:_;return fn(C,d,S,r)}),l(!1)},w=_=>{if(_.preventDefault(),_.stopPropagation(),!m&&Array.isArray(c)){x();return}l(C=>!C)};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:_=>_.preventDefault(),onClick:w,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:a4[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:_=>_.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((_,C)=>{const E=f.value===_.value;return i.jsxs("button",{type:"button",role:"option","aria-selected":E,"data-testid":`g7le-inline-option-${e}-${String(_.value??C)}`,onMouseDown:S=>S.preventDefault(),onClick:S=>{S.preventDefault(),S.stopPropagation(),k(_.value)},style:{display:"flex",alignItems:"center",gap:8,width:"100%",padding:"6px 8px",fontSize:12,textAlign:"left",border:"none",borderRadius:5,cursor:"pointer",background:E?"#2563eb":"transparent",color:"#ffffff"},children:[typeof _.swatch=="string"&&i.jsx("span",{"aria-hidden":"true",style:{width:14,height:14,borderRadius:3,background:_.swatch,border:"1px solid rgba(255,255,255,0.3)"}}),i.jsx("span",{children:b(_)}),E&&i.jsx("span",{"aria-hidden":"true",style:{marginLeft:"auto"},children:"✓"})]},String(_.value??C))}):i.jsx(u4,{testid:`g7le-inline-freeinput-${e}`,placeholder:o(`layout_editor.inline_edit.prompt.${e}`),initial:typeof f.value=="string"?f.value:"",onSubmit:_=>{s(e,C=>fn(C,d,_,r)),l(!1)}})})]})}function u4({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 p4(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:y}=Je(),{t:g}=tt(),m=ja(),h=u.useCallback((W,X)=>{const R=window.G7Core;if(R&&typeof R.t=="function"){const de=R.t(W,X);if(de&&de!==W&&!de.startsWith("$t:"))return de}return g(W,X)},[g]),v=Ft(),b=d7(50),x=yo(),k=u.useRef([]),w=u.useMemo(()=>v?.document?.raw?.components??[],[v?.document?.raw?.components]),_=u.useMemo(()=>w.length===0?null:{children:w},[w]),C=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]),E=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]),S=e7({rootNode:_,editMode:f.editMode,currentExtensionId:C,editableRootPath:E,pathParser:Ze,resolveRouteMatch:l}),[T,$]=u.useState(null),[A,z]=u.useState(null),[D,O]=u.useState(null),M=u.useRef(null);M.current=D;const[B,N]=u.useState(null),H=u.useRef(null),L=u.useRef(null);L.current=S.selectedPath;const I=Wb(),[P,F]=u.useState(null),G=u.useCallback(W=>{if(!t)return;const X=Ze(W);if(!X)return;const R={children:Me.current.components},de=We(R,X),ye=I.classify(de);if(!ye.editable){Et({op:"inline_edit_blocked_binding",sourceState:ye.sourceState,componentPath:at(X),timestamp:Date.now()});return}const we=po(t,W);if(!we)return;const Te=de?.props??{},ke=yg(t,W);F({path:X,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(X),timestamp:Date.now()})},[t,I]),V=u.useCallback(()=>{if(!t){$(null),z(null);return}z(po(t,S.selectedPath)),$(po(t,S.hoverPath))},[t,S.selectedPath,S.hoverPath,w]);u.useEffect(()=>{if(V(),typeof window<"u"&&typeof window.requestAnimationFrame=="function"){const W=window.requestAnimationFrame(()=>V());return()=>window.cancelAnimationFrame(W)}},[V]),u.useEffect(()=>{if(t)return $p(V,t)},[t,V]);const Y=u.useCallback((W,X)=>{if(typeof window>"u")return;window.dispatchEvent(new CustomEvent(La,{detail:X===null?{requestId:W,cancelled:!0}:{requestId:W,id:X}})),O(null),N(null);const R=H.current;R?S.handleSelect("",{dataset:{editorPath:R}}):S.clearSelection(),H.current=null},[S]);u.useEffect(()=>{if(typeof window>"u")return;const W=X=>{const R=X.detail;if(typeof R?.requestId!="string")return;const de=M.current;de&&de!==R.requestId&&Y(de,null),H.current=L.current,O(R.requestId)};return window.addEventListener(Pa,W),()=>window.removeEventListener(Pa,W)},[Y]),u.useEffect(()=>{if(!D)return;const W=X=>{X.key==="Escape"&&(X.preventDefault(),Y(D,null))};return window.addEventListener("keydown",W,!0),()=>window.removeEventListener("keydown",W,!0)},[D,Y]),u.useEffect(()=>{if(!t)return;const W=f.editMode==="iteration_item"||f.editMode==="modal",X=(xe,Ee)=>ZT(xe,t,Ee?{x:Ee.clientX,y:Ee.clientY}:void 0,{handleFallback:W}),R=xe=>{const Ee=xe.dataset.editorPath??"",Fe=Ee?Ze(Ee):null,zt={children:Me.current.components},gt=Fe?We(zt,Fe):null,Mt=gt&&typeof gt.props?.id=="string"?gt.props.id:typeof gt?.id=="string"?gt.id:"";return Mt.startsWith("auto_")?"":Mt},de=xe=>{const Ee=X(xe.target,xe);if(!Ee)return;const Fe=M.current;if(Fe){xe.preventDefault(),xe.stopPropagation();const zt=R(Ee);zt&&Y(Fe,zt);return}xe.preventDefault(),xe.stopPropagation(),S.handleSelect(Ee.dataset.editorId??"",{currentTarget:Ee,dataset:Ee.dataset})},ye=xe=>{const Ee=X(xe.target,xe);if(M.current){if(!Ee){N(null);return}const Fe=po(t,Ee.dataset.editorPath??null);if(!Fe){N(null);return}N({box:Fe,hasId:R(Ee)!==""});return}if(!Ee){S.handleHover(null,{});return}S.handleHover(Ee.dataset.editorId??"",{currentTarget:Ee,dataset:Ee.dataset})},we=()=>{if(M.current){N(null);return}S.handleHover(null,{})},Te=xe=>{const Ee=X(xe.target,xe);if(!Ee)return;const Fe=Ee.dataset.editorPath??"";Fe&&(xe.preventDefault(),xe.stopPropagation(),G(Fe))},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,S,G,f.editMode,Y]);const Z=u.useMemo(()=>{const W=S.selectedPath;if(!W)return null;const X=W.match(/^(.*)\.children\.\d+$/);return X?X[1]:null},[S.selectedPath]),se=u.useCallback(()=>{Z&&S.handleSelect("",{dataset:{editorPath:Z}})},[Z,S]),re=u.useMemo(()=>!t||!S.selectedPath?null:t.querySelector(`[data-editor-path="${an(S.selectedPath)}"]`),[t,S.selectedPath]),U=u.useMemo(()=>S.selectedPath?Ze(S.selectedPath):null,[S.selectedPath]),ee=u.useMemo(()=>{if(!U)return null;const W=U.find(et);if(!W)return null;const{i18nKey:X,raw:R}=bC(W.responsive);return X?g(X):g("layout_editor.overlay.branch_custom",{range:R})},[U,g]),fe=u.useMemo(()=>S.selectedPath?S.selectedIsIteration&&S.selectedIterationSourcePath?S.selectedIterationSourcePath:S.selectedPath:null,[S.selectedPath,S.selectedIsIteration,S.selectedIterationSourcePath]),K=u.useMemo(()=>fe?Ze(fe):null,[fe]),ne=u.useMemo(()=>!t||!fe?null:t.querySelector(`[data-editor-path="${an(fe)}"]`),[t,fe]),me=u.useMemo(()=>{if(ne?.parentElement)return ne.parentElement;if(!t||!fe)return null;const W=fe.match(/^(.*)\.children\.\d+$/);return W?t.querySelector(`[data-editor-path="${an(W[1])}"]`):null},[ne,t,fe]),Ce=u.useMemo(()=>{const W=S.selectedNode;return W&&(typeof W.name=="string"?W.name:typeof W.type=="string"?W.type:"")||null},[S.selectedNode]),ze=u.useMemo(()=>{if(S.selectedLockKind!=="extension")return null;const W=S.selectedNode?.__source;if(!W||W.kind!=="extension")return null;const X=W.extensionName?.trim(),R=W.extensionIdentifier?.trim();return X&&R?`${X} (${R})`:X||R||W.extensionSourceType||null},[S.selectedLockKind,S.selectedNode]),Se=s7({parentEl:me,selectedPath:K,selectedEl:ne}),qe=u.useMemo(()=>!t||!fe||fe===S.selectedPath?A:po(t,fe),[t,fe,A,S.selectedPath,w]),De=u.useRef(null),Pe=u.useCallback(()=>{const W=De.current;W&&(x.close(W),De.current=null)},[x]),Qe=u.useRef(()=>{}),Me=u.useRef({manifest:n,nesting:o,componentPalette:r,components:w});Me.current={manifest:n,nesting:o,componentPalette:r,components:w};const Re=u.useCallback(W=>{const X=W.insertion?.parentPath??[],R=W.insertion?.index??0,de=Me.current,ye=hg(de.components,X);Pe();const we=x.open({ariaLabel:h("layout_editor.palette.title"),width:880,maxHeightRatio:.82,content:u.createElement(Ef,{manifest:de.manifest,nesting:de.nesting,componentPalette:de.componentPalette??null,targetParentPath:X,targetContainerName:ye,onInsert:(Te,ke,xe)=>{Qe.current(Te,ke,xe)},insertionIndex:R,onClose:()=>Pe(),editorTemplateId:f.templateIdentifier,editorLocale:f.locale}),onClose:()=>{De.current=null}});De.current=we},[x,Pe]),ve=u.useMemo(()=>{if(!f.isPaletteOpen)return null;if(!U)return{parentPath:[],index:w.length};if(S.selectedLockKind!=="none"){const de=K;return!de||de.length===0?{parentPath:[],index:w.length}:{parentPath:de.slice(0,-1),index:(de[de.length-1]??0)+1}}const X=S.selectedNode,R=Array.isArray(X?.children)?X.children.length:0;return lI(X?.name,R,U,o,w.length)},[f.isPaletteOpen,U,K,S.selectedLockKind,S.selectedNode,w.length,o]),te=u.useCallback(()=>{y({type:"SET_PALETTE_OPEN",open:!1})},[y]),he=u.useRef(null);u.useEffect(()=>{if(!f.isPaletteOpen){const ye=he.current;ye&&(x.close(ye),he.current=null);return}if(!ve||he.current)return;const W=ve,X=Me.current,R=hg(X.components,W.parentPath),de=x.open({ariaLabel:h("layout_editor.palette.title"),width:880,maxHeightRatio:.82,content:u.createElement(Ef,{manifest:X.manifest,nesting:X.nesting,componentPalette:X.componentPalette??null,targetParentPath:W.parentPath,targetContainerName:R,onInsert:(ye,we,Te)=>{Qe.current(ye,we,Te),te()},insertionIndex:W.index,onClose:()=>te(),editorTemplateId:f.templateIdentifier,editorLocale:f.locale}),onClose:()=>{he.current=null,y({type:"SET_PALETTE_OPEN",open:!1})}});he.current=de},[f.isPaletteOpen,ve,x,te,y]);const Q=u.useRef({layoutName:null,pushed:!1});u.useEffect(()=>{const W=v?.document?.layoutName??null;if(!W){Q.current={layoutName:null,pushed:!1};return}Q.current.layoutName!==W&&(b.clear(),b.push({actionKind:"inline_text_edit",label:"baseline",snapshot:w}),Q.current={layoutName:W,pushed:!0})},[v?.document?.layoutName,w,b]);const ie=u.useRef(0);u.useEffect(()=>{const W=v?.saveSuccessCounter??0;W!==ie.current&&(ie.current=W,W!==0&&(b.clear(),b.push({actionKind:"inline_text_edit",label:"save_baseline",snapshot:w}),k.current=[],c?.([])))},[v?.saveSuccessCounter,w,b,c]);const _e=u.useRef(0);u.useEffect(()=>{const W=v?.reloadCounter??0;W!==_e.current&&(_e.current=W,W!==0&&(Q.current={layoutName:null,pushed:!1},k.current=[],c?.([])))},[v?.reloadCounter,c]);const ge=u.useCallback((W,X,R)=>{if(!v)return;let de=[];v.patchLayout(ke=>{const xe={children:ke},Ee=Ha(xe,X),Fe=R<0?Array.isArray(Ee?.children)?Ee.children.length:0:R,gt=Qi(xe,X,Fe,W).children??[];return de=gt,gt}),b.push({actionKind:"insert",label:`insert ${W.name??W.type??""}`,snapshot:de});const ye=Ha({children:de},X),we=R<0?Array.isArray(ye?.children)?ye.children.length-1:0:R,Te=at([...X,we]);if(k.current=[...k.current,Te],c?.(k.current),t){const ke=`[data-editor-path="${an(Te)}"]`,xe=()=>{const Ee=t.querySelector(ke);Ee&&typeof Ee.scrollIntoView=="function"&&Ee.scrollIntoView({behavior:"smooth",block:"center",inline:"nearest"})};typeof window<"u"&&typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(()=>window.requestAnimationFrame(xe)):setTimeout(xe,32)}},[v,b,c,t]);Qe.current=ge;const Ae=u.useCallback(()=>{if(!v||!S.selectedNode||!U)return;const W=es(S.selectedNode);let X=[];v.patchLayout(R=>{const de={children:R},ye=U.slice(0,-1),we=U[U.length-1]??0,ke=Qi(de,ye,we+1,W).children??[];return X=ke,ke}),b.push({actionKind:"insert",label:"duplicate",snapshot:X})},[v,S.selectedNode,U,b]),Ne=u.useCallback(()=>{if(!v||!U)return;let W=[];v.patchLayout(X=>{const ye=Ri({children:X},U).children??[];return W=ye,ye}),b.push({actionKind:"remove",label:"remove",snapshot:W}),S.clearSelection()},[v,U,b,S]),Le=u.useMemo(()=>{if(!S.selectedNode||!U||U.some(et))return null;const W=S.selectedNode;if(!Array.isArray(W.children))return null;const X=yC(f.previewDevice,W,f.previewCustomWidth);return{mode:X.mode,key:X.key,sourceKey:X.sourceKey}},[S.selectedNode,U,f.previewDevice,f.previewCustomWidth]),q=u.useCallback(()=>{if(!v||!U||Le?.mode!=="separate")return;const W=Le.key,X=Le.sourceKey;let R=[];v.patchLayout(de=>(R=Ab({children:de},U,W,X).children??[],R)),b.push({actionKind:"insert",label:"separate_branch",snapshot:R})},[v,U,Le,b]),ae=u.useCallback(()=>{if(!v||!U||Le?.mode!=="merge")return;const W=Le.key;let X=[];v.patchLayout(R=>(X=Tb({children:R},U,W).children??[],X)),b.push({actionKind:"remove",label:"merge_branch",snapshot:X})},[v,U,Le,b]),pe=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]),$e=u.useMemo(()=>{if(!Le)return null;const W=pe(Le.key);return{separate:g("layout_editor.context_menu.separate_branch_device",{device:W}),merge:g("layout_editor.context_menu.merge_branch_device",{device:W})}},[Le,g,pe]),be=u.useMemo(()=>{if(!S.selectedNode||!U)return[];if(U.some(et))return[];const W=Ur(f.previewDevice,S.selectedNode,f.previewCustomWidth);return G6(S.selectedNode,W).map(X=>({key:X,label:pe(X)}))},[S.selectedNode,U,f.previewDevice,f.previewCustomWidth,pe]),j=u.useCallback(W=>{if(W==="desktop"||W==="tablet"||W==="mobile"||W==="portable"){m.setDevice(W);return}m.setDevice(W)},[m]),oe=u.useCallback(()=>{S.selectedNode&&dg(S.selectedNode)},[S.selectedNode]),ue=u.useCallback(()=>{S.selectedNode&&(dg(S.selectedNode),Ne())},[S.selectedNode,Ne]),J=u.useCallback(()=>{if(!v)return;const W=VT();if(!W)return;const X=es(W);if(U&&U.length>0){const R=U.slice(0,-1),de=(U[U.length-1]??0)+1;ge(X,R,de)}else ge(X,[],w.length)},[v,U,ge,w.length]),le=u.useCallback((W,X)=>{b.push({actionKind:"move",label:X,snapshot:W})},[b]),Ie=u.useCallback(()=>{if(S.selectedNavAffordance==="route_in_tree"&&S.selectedNavTargetPath){if(d){d(S.selectedNavTargetPath);return}y({type:"SELECT_ROUTE",route:{path:S.selectedNavTargetPath,layoutName:null}})}},[S.selectedNavAffordance,S.selectedNavTargetPath,d,y]),dt=u.useCallback(()=>{const W=Eb(S.selectedBaseLayout,f.selectedRoute?.layoutName);W&&y({type:"ENTER_BASE_EDIT",layoutName:W})},[S.selectedBaseLayout,f.selectedRoute?.layoutName,y]),pt=u.useCallback(()=>{const W=S.selectedNode?.__source?.extensionId;W!=null&&y({type:"ENTER_EXTENSION_EDIT",extensionId:String(W)})},[S.selectedNode,y]),ot=u.useCallback(()=>{const W=S.selectedIterationSourcePath;W&&y({type:"ENTER_ITERATION_ITEM_EDIT",sourcePath:W})},[S.selectedIterationSourcePath,y]),Oe=u.useRef(null),He=u.useRef(null),Ye=u.useRef(null),Tt=u.useRef({colorScheme:"base",breakpoint:"base"}),Dt=Oe.current!==null?x.stack.some(W=>W.id===Oe.current):!1,Nt=u.useMemo(()=>zd(f.routeTree,h),[f.routeTree,h]),xn=u.useMemo(()=>Md(v?.document?.raw),[v?.document?.raw]),wn=u.useMemo(()=>Ld(s),[s?.states]),Zt=u.useMemo(()=>{const W=v?.document?.raw,X=Af(W?.components),R=W?.initIsolated,de=R&&typeof R=="object"&&!Array.isArray(R)?Object.keys(R):[];return eA(X,de)},[v?.document?.raw]),Hn=u.useMemo(()=>{const W=v?.document?.raw;return Af(W?.components).map(X=>X.scopeId).filter(X=>typeof X=="string"&&X.length>0)},[v?.document?.raw]),ln=Nd({raw:v?.document?.raw,spec:s}),Ii=u.useCallback((W,X)=>{if(!v)return;const R={children:Me.current.components},de=We(R,W);if(!de)return;Tt.current={colorScheme:f.previewColorScheme==="dark"?"dark":"base",breakpoint:Ur(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=re,ke=W.find(et),xe=ke?pe(ke.responsive):null,Ee=W.filter(kn=>typeof kn=="number"),Fe=cb({children:Me.current.components},Ee,ub(ln)),zt=Fe.length>0?[...ji({iterationVars:Fe}),...ln]:ln,gt=(kn,lM)=>u.createElement(ET,{key:`pem-${at(He.current??[])}`,node:kn,spec:s,manifest:Me.current.manifest,t:h,permissionCandidates:a,pageCandidates:Nt,dataSourceCandidates:xn,stateKeyCandidates:wn,bindingCandidates:zt,liveElement:Te,templateIdentifier:f.templateIdentifier,initialTab:lM,branchLabel:xe,isolatedScopeIdCandidates:Zt,usedScopeIds:Hn,onSaveInjectedProps:async(bt,Sn)=>{const Ai=typeof kn.id=="string"?kn.id:"",Fn=await HT(f.templateIdentifier,bt,Ai,Sn);if(st({op:"save",layoutName:`extension:${bt}`,editMode:f.editMode,saveTarget:"layout_extension",endpoint:`/api/admin/templates/${f.templateIdentifier}/layout-extensions/${bt}`,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:bt=>{Tt.current=bt;const Sn=Oe.current;Sn&&x.open({id:Sn,ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(kn),onClose:()=>{Oe.current=null,He.current=null}})},onPatchNode:bt=>{let Sn=[];v.patchLayout(Fn=>(Sn=Ot({children:Fn},W,()=>bt).children??[],Sn)),b.push({actionKind:"inline_text_edit",label:"edit_props",snapshot:Sn}),sr({source:"style_control",componentPath:at(W),componentName:typeof bt.name=="string"?bt.name:null,patchKey:null,timestamp:Date.now()});const Ai=Oe.current;Ai&&x.open({id:Ai,ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(bt),onClose:()=>{Oe.current=null,He.current=null}})},onDelete:()=>{const bt=Oe.current;bt&&x.close(bt),Ne()},onClose:()=>{const bt=Oe.current;bt&&x.close(bt)}});He.current=W;const Mt=x.open({ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(de,X),onClose:()=>{Oe.current=null,He.current=null,Ye.current=null}});Oe.current=Mt,Ye.current=kn=>{x.open({id:Mt,ariaLabel:h("layout_editor.property_modal.title"),width:420,draggable:!0,avoidRect:we,content:gt(kn),onClose:()=>{Oe.current=null,He.current=null,Ye.current=null}})}},[v,s,h,a,Nt,xn,wn,ln,re,b,x,Ne,t,A,f.previewColorScheme,f.previewDevice,f.previewCustomWidth,pe]);u.useEffect(()=>{const W=Ye.current,X=He.current;if(!W||!X)return;const R={children:Me.current.components},de=We(R,X);de?W(de):Oe.current&&x.close(Oe.current)},[w]);const Uz=()=>{if(!Dt)return null;const X={position:"absolute",background:"rgba(15, 23, 42, 0.45)",pointerEvents:"auto",zIndex:f7},R=ke=>{ke.preventDefault(),ke.stopPropagation()};if(!A)return i.jsx("div",{"data-testid":"g7le-edit-lock-full",onClick:R,onMouseMove:R,style:{...X,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:{...X,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:{...X,left:0,top:ye+Te,right:0,bottom:0}}),i.jsx("div",{"data-testid":"g7le-edit-lock-left",onClick:R,onMouseMove:R,style:{...X,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:{...X,left:de+we,top:ye,right:0,height:Te}})]})},ml=u.useCallback(()=>{if(U&&_p(S.selectedLockKind)){if(p&&S.selectedPath){p(S.selectedPath);return}Ii(U)}},[U,S.selectedPath,S.selectedLockKind,p,Ii]),{scale:vl}=m,_l=typeof S.selectedNode?.name=="string"?S.selectedNode.name:"",Bh=s?.componentCapabilities?.[_l]??null,Wh=Array.isArray(Bh?.styleControls)?Bh.styleControls:[],qz=Wh.includes("width")?Ct(s,"width"):null,Gz=Wh.includes("height")?Ct(s,"height"):null,Yz=u.useCallback((W,X)=>{if(!v||!U)return;let R=[];v.patchLayout(de=>(R=Ot({children:de},U,()=>W).children??[],R)),sr({source:"resize",componentPath:at(U),componentName:_l||null,patchKey:X==="height"?"height":"width",resizeAxis:X,timestamp:Date.now()})},[v,U,_l]),Xz=u.useCallback((W,X)=>{if(!v||!U)return;let R=[];v.patchLayout(de=>(R=Ot({children:de},U,()=>W).children??[],R)),b.push({actionKind:"inline_text_edit",label:`resize ${X}`,snapshot:R})},[v,U,b]),Jz=u.useCallback(()=>{if(!re)return null;const W=re.getBoundingClientRect(),X=vl||1;return{width:W.width/X,height:W.height/X}},[re,vl]),ir=GT({node:S.selectedNode,widthControl:qz,heightControl:Gz,scale:vl,measureStartSize:Jz,onResize:Yz,onResizeEnd:Xz}),Zz=u.useCallback((W,X)=>{ir.onHandlePointerDown(W,X)},[ir]),xl=u.useCallback(()=>{const W=b.undo();!W||!v||v.setLayoutComponents(W.snapshot)},[b,v]),wl=u.useCallback(()=>{const W=b.redo();!W||!v||v.setLayoutComponents(W.snapshot)},[b,v]);u7({onUndo:xl,onRedo:wl});const Qz=u.useMemo(()=>({copy:oe,cut:ue,paste:J,delete:Ne,openProps:ml,selectParent:Z?se:void 0,deselect:S.clearSelection}),[oe,ue,J,Ne,ml,Z,se,S.clearSelection]);np({handlers:Qz,hasSelection:!!S.selectedPath}),u.useEffect(()=>(window.__g7LayoutEditorHasSelection=!!S.selectedPath,()=>{try{delete window.__g7LayoutEditorHasSelection}catch{}}),[S.selectedPath]),u.useEffect(()=>(window.__g7LayoutEditorHistory={undo:xl,redo:wl,canUndo:b.canUndo,canRedo:b.canRedo},()=>{try{delete window.__g7LayoutEditorHistory}catch{}}),[xl,wl,b.canUndo,b.canRedo]);const Rz=u.useCallback(W=>{const X=P;F(null),X&&(async()=>{if((await I.commit(X.path,W)).kind==="created"&&v){const de=v.document?.raw?.components??[];b.push({actionKind:"inline_text_edit",label:"inline_create_key",snapshot:de})}})()},[P,I,v,b]),jh=u.useCallback(()=>{const W=P;F(null),I.trackCancel(W?.path??null)},[P,I]),eM=u.useCallback(()=>{F(null)},[]),tM=u.useCallback(async W=>{const X=P;if(!X)return null;const R=await I.keyifyChipValue(X.path,W);if(R.kind!=="created"||!R.translationKey)return null;const de=v?.document?.raw?.components??[];return b.push({actionKind:"inline_text_edit",label:"inline_keyify_chip",snapshot:de}),R.translationKey},[P,I,v,b]),nM=u.useCallback(()=>{const W=P;W&&(F(null),S.handleSelect("",{dataset:{editorPath:W.domPath}}),Ii(W.path,"translation"))},[P,S,Ii]),xt=u.useMemo(()=>{if(!P)return null;const W=v?.document?.raw?.components??w;return We({children:W},P.path)},[P,v?.document,w]),oM=u.useCallback(async(W,X)=>{const R=P;if(!v||!R)return null;const de=typeof xt?.text=="string"?xt.text:"";let ye;if(R.isParamKey)ye=await wr(f.templateIdentifier,f.locale,de,W,X.sourceId,X.path,"scalar");else{const Fe=zt=>zt.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 ls(f.templateIdentifier,f.selectedRoute?.layoutName??null,f.locale,de,W,X.sourceId,X.path,"scalar",Fe,h)}if(ye.kind==="error")return null;const we=R.path;let Te=[];v.patchLayout(Fe=>(Te=Ot({children:Fe},we,Mt=>({...Mt,text:ye.text})).children??[],Te)),b.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(Fe=>Fe&&Fe.path===we?{...Fe,isParamKey:!0,customKey:ke,chipValue:void 0,chipParamLabels:void 0}:Fe);try{window.dispatchEvent(new CustomEvent(kt,{detail:{templateIdentifier:f.templateIdentifier,locale:f.locale}}))}catch{}const xe=mt(ye.text),Ee=R.customKey??xe?.key??"";return Ee?It(Ee,f.locale)??null:null},[v,P,xt,f.templateIdentifier,f.locale,f.selectedRoute,b,h]),rM=u.useCallback(async W=>{const X=P;if(!v||!X)return null;const R=typeof xt?.text=="string"?xt.text:"",de=mt(R),ye=X.customKey??de?.key??null,we=mo(R,W),Te=X.path;let ke=[];return v.patchLayout(xe=>(ke=Ot({children:xe},Te,zt=>({...zt,text:we})).children??[],ke)),b.push({actionKind:"inline_text_edit",label:"inline_remove_binding",snapshot:ke}),ye&&await kr(f.templateIdentifier,ye,W,f.locale),ye?It(ye,f.locale)??null:null},[v,P,xt,f.templateIdentifier,f.locale,b]),[kl,Hh]=u.useState({}),iM=["fontSize","color","fontStyle","textDecoration","textAlign","letterSpacing","lineHeight","fontFamily"];u.useEffect(()=>{if(!P||!t||typeof MutationObserver>"u"){Hh({});return}const W=`[data-editor-path="${an(P.domPath)}"]`,X=()=>{const ye=t.querySelector(W);if(!ye)return;const we={};for(const ke of iM){const xe=ye.style.getPropertyValue(ke.replace(/([A-Z])/g,"-$1").toLowerCase());xe&&(we[ke]=xe)}const Te=yg(t,P.domPath)??void 0;Hh({className:ye.className,style:we,effectiveColor:Te})};X();const R=t.querySelector(W);if(!R)return;const de=new MutationObserver(X);return de.observe(R,{attributes:!0,attributeFilter:["class","style"]}),de.observe(t,{childList:!0,subtree:!0}),()=>de.disconnect()},[P?.path?at(P.path):null,t]);const Fh=u.useCallback((W,X)=>{if(!v||!P)return;const R=P.path;let de=[],ye=null;v.patchLayout(we=>(de=Ot({children:we},R,xe=>{const Ee=X(xe);return ye=typeof Ee.name=="string"?Ee.name:null,Ee}).children??[],de)),b.push({actionKind:"inline_text_edit",label:`inline_format ${W}`,snapshot:de}),sr({source:"style_control",componentPath:at(R),componentName:ye,patchKey:W,timestamp:Date.now()})},[v,P,b]),ft=u.useMemo(()=>{const W=S.selectedPath;if(!W||!_)return null;const X=[];let R=W;for(;R;){X.push(R);const de=R.match(/^(.*)\.children\.\d+$/);R=de?de[1]:null}for(const de of X){const ye=Ze(de);if(!ye)continue;const we=We(_,ye),Te=typeof we?.name=="string"?we.name:null;if(!Te)continue;const ke=Oi(s,Te),xe=ke?.canvasOverlay?.kind;if(typeof xe!="string"||!xe||!we)continue;const Ee=ke.canvasOverlay.params&&typeof ke.canvasOverlay.params=="object"?ke.canvasOverlay.params:void 0,Fe=de===W?null:W.slice(de.length+1);return{kind:xe,params:Ee,tablePath:de,tableNode:we,selectedCellRel:Fe}}return null},[S.selectedPath,_,s]),ho=ft?FT(ft.kind):null,Kh=u.useMemo(()=>!ho||!t||!ft?null:po(t,ft.tablePath),[ho,t,ft,A,w]),sM=u.useMemo(()=>{if(!ho||!t||!ft)return[];const W=ft.tablePath,X=an(W),R=[];return t.querySelectorAll(`[data-editor-path^="${X}.children."]`).forEach(we=>{const Te=we.dataset.editorPath??"";if(!Te.startsWith(W+"."))return;const ke=Te.slice(W.length+1),xe=so(we,t);xe&&R.push({path:ke,top:xe.top,left:xe.left,width:xe.width,height:xe.height})}),t.querySelectorAll(`[data-editor-item-path^="${X}."]`).forEach(we=>{const Te=we.dataset.editorItemPath??"";if(!Te.startsWith(W+"."))return;const ke=Te.slice(W.length+1),xe=so(we,t);xe&&R.push({path:ke,top:xe.top,left:xe.left,width:xe.width,height:xe.height})}),R},[ho,t,ft,A,w]),aM=u.useCallback(W=>{const X=ft?Ze(ft.tablePath):null;if(!v||!X)return;let R=[];v.patchLayout(de=>(R=Ot({children:de},X,()=>W).children??[],R)),b.push({actionKind:"inline_text_edit",label:"inplace_edit",snapshot:R}),sr({source:"style_control",componentPath:ft?.tablePath??"",componentName:typeof W.name=="string"?W.name:null,patchKey:"canvas_inplace",timestamp:Date.now()})},[v,U,b]);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&&Uz(),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:()=>Y(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(EI,{frameEl:t,components:w,editMode:f.editMode,currentExtensionId:C,editableRootPath:E}),P&&((P.isParamKey&&P.customKey||P.chipValue)&&xt?i.jsxs(i.Fragment,{children:[xt&&i.jsx(fg,{node:xt,spec:s,t:h,onApplyControl:Fh,box:P.box,scope:{colorScheme:f.previewColorScheme==="dark"?"dark":"base",breakpoint:Ur(f.previewDevice,xt,f.previewCustomWidth)}}),i.jsx(i4,{box:P.box,node:xt,customKey:P.customKey??null,initialChipValue:P.chipValue,chipParamLabels:P.chipParamLabels,onKeyify:tM,templateIdentifier:f.templateIdentifier,locale:f.locale,t:h,candidates:ln,onInsertBinding:oM,onRemoveBinding:rM,onCommit:eM,onCancel:jh})]}):i.jsxs(i.Fragment,{children:[xt&&i.jsx(fg,{node:xt,spec:s,t:h,onApplyControl:Fh,box:P.box,scope:{colorScheme:f.previewColorScheme==="dark"?"dark":"base",breakpoint:xt?Ur(f.previewDevice,xt,f.previewCustomWidth):"base"}}),i.jsx(r4,{box:P.box,initialValue:P.initialValue,isCustomKey:P.isCustomKey,t:h,onCommit:Rz,onCancel:jh,mirrorClassName:kl.className,mirrorStyle:kl.style,nodeEffectiveColor:kl.effectiveColor??P.nodeEffectiveColor,onOpenTranslations:nM})]})),!D&&i.jsx(v7,{hoverBox:T,selectedBox:A,lockKind:S.selectedLockKind,navAffordance:S.selectedNavAffordance,onEditProps:ml,onDuplicate:Ae,onDelete:Ne,onSeparateBranch:Le?.mode==="separate"?q:void 0,separateBranchLabel:$e?.separate,onMergeBranch:Le?.mode==="merge"?ae:void 0,mergeBranchLabel:$e?.merge,definedDeviceBranches:be,onJumpToDevice:be.length>0?j:void 0,onLinkEditDestination:Ie,onEditBase:dt,onEditExtension:pt,extensionLabel:ze,baseLayoutLabel:S.selectedBaseLayout,dataSourceLabel:S.selectedDataSourceId,branchLabel:ee,onEditIteration:S.selectedIsIteration&&f.editMode!=="iteration_item"?ot:void 0,resizeEnabledAxes:ir.enabledAxes,onResizeHandlePointerDown:ir.enabledAxes.width||ir.enabledAxes.height?Zz:void 0,selectedName:Ce,onSelectParent:Z?se:void 0}),D&&B&&i.jsx("div",{"data-testid":"g7le-canvas-pick-hover","data-pick-has-id":B.hasId?"true":"false",style:{position:"absolute",left:B.box.left,top:B.box.top,width:B.box.width,height:B.box.height,pointerEvents:"none",zIndex:9998,boxSizing:"border-box",border:B.hasId?"2px solid #2563eb":"2px dashed #94a3b8",background:B.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:B.hasId?"pointer":"not-allowed"},children:!B.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(C7,{selectedBox:qe,points:Se.points,onAddRequest:Re}),ho&&ft&&Kh&&S.selectedLockKind==="none"&&i.jsx(ho,{node:ft.tableNode,params:ft.params,nodeBox:Kh,cellBoxes:sM,selectedCellPath:ft.selectedCellRel??void 0,colorScheme:f.previewColorScheme==="dark"?"dark":"light",t:h,onPatchNode:aM,onInsertChild:ge,onRemoveChild:W=>{const X=Ze(W);if(!v||!X)return;let R=[];v.patchLayout(de=>(R=Ri({children:de},X).children??[],R)),b.push({actionKind:"remove",label:"inplace_remove",snapshot:R})},onRequestInlineEdit:W=>{ft&&G(`${ft.tablePath}.${W}`)}}),v&&i.jsx(xI,{frameEl:t,nesting:o,editMode:f.editMode,currentExtensionId:C,editableRootPath:E,components:w,patchLayout:v.patchLayout,pushHistory:le,selectedPath:S.selectedPath,onSelectPath:W=>S.handleSelect("",{dataset:{editorPath:W}}),onMovePath:W=>S.handleSelect("",{dataset:{editorPath:W}}),onRequestInlineEdit:G})]}):null}function hg(e,t){if(t.length===0)return null;const o=Ha({children:e},t);return o&&typeof o.name=="string"?o.name:null}function Ha(e,t){return We(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 yg(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 po(e,t){if(!t)return null;const n=e.querySelector(`[data-editor-path="${an(t)}"]`);if(n){const c=so(n,e);return c&&ao(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=so(c,e);f&&ao(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 f4({isEditMode:e,editorSpec:t,sampleOverride:n}){const o=t?.sampleData;return u.useMemo(()=>Pm({spec:o,overrideSpec:n,onMatch:r=>{Uh(r)}}),[e,o,n])}const g4=Lt().ComponentRegistry;function h4(e){return e.split(/[-_]/).map(t=>t.charAt(0).toUpperCase()+t.slice(1).toLowerCase()).join("")}async function y4(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 Gr(o.status,s,"assets")}const r=await o.json();return r.data||r}async function b4(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 m4(e){return new Promise((t,n)=>{if(typeof document>"u"){n(new Error("document undefined"));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 v4(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 _4(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 y4(e);if(s)return;for(const y of a.css??[])if(await v4(y),s)return;const l=h4(e);if(!(typeof window<"u"&&typeof window[l]=="object")){for(const y of a.js??[])if(await m4(y),s)return}const c=g4.createIsolatedInstance();if(await c.loadComponents(e,n),s)return;const p=await b4(e);if(s)return;const f=new Pt({defaultLocale:t});if(p>0&&f.setCacheVersion(p),await f.loadTranslations(e,t),s)return;cd(f,e);try{const y=Pt.getInstance();p>y.getCacheVersion()&&y.setCacheVersion(p),await y.loadTranslations(e,t),cd(y,e)}catch{}if(s)return;r({componentRegistry:c,translationEngine:f,isReady:!0,error:null})}catch(a){if(s)return;const l=hp(a)?a:io(a,"assets");r({componentRegistry:null,translationEngine:null,isReady:!1,error:l})}})(),()=>{s=!0}},[e,t,n]),o}const bg=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 w4={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 k4({error:e}){return u.useEffect(()=>{if(e.kind!=="unauthorized"||typeof window>"u")return;const t=bg.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 Fa({error:e}){const{t}=tt(),n=x4(e.kind),o=w4[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=bg.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(k4,{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:Ka,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:Ka,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:Ka,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:S4,children:t("layout_editor.access_error.action.go_admin_home")})]})]})]})}const Ka={padding:"8px 16px",background:"#2563eb",color:"#fff",border:"1px solid #1d4ed8",borderRadius:6,fontSize:13,fontWeight:600,cursor:"pointer"},S4={padding:"8px 16px",background:"#fff",color:"#475569",border:"1px solid #cbd5e1",borderRadius:6,fontSize:13,fontWeight:500,cursor:"pointer"};function C4(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 $4=new Set(["id","userId","postId","orderId","productId","categoryId","commentId","noticeId","inquiryId","addressId","wishlistId","notificationId","roleId","menuId"]);function E4(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]=I4(r)}return t}function I4(e){return $4.has(e)||/Id$|_id$/.test(e)?"1":"sample"}const A4=bo("LayoutEditor");function Jo(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function bi(e){if(Array.isArray(e))return e.map(t=>bi(t));if(Jo(e)){const t={};for(const[n,o]of Object.entries(e))t[n]=bi(o);return t}return e}function mg(e,t="",n=new Set){for(const[o,r]of Object.entries(e)){const s=t?`${t}.${o}`:o;Jo(r)?mg(r,s,n):n.add(s)}return n}function vg(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];Jo(l)&&Jo(c)?vg(c,l,n,o,r,d):e[a]=bi(l)}}function Va(e){const t=e.warn??(r=>A4.warn(r)),n=bi(e.coreSeed??{});e.isGuestOnly&&"currentUser"in n&&delete n.currentUser;const o=mg(n);for(const r of e.sources)Jo(r.sampleGlobal)&&vg(n,r.sampleGlobal,o,r.id,t);return e.isGuestOnly&&"currentUser"in n&&delete n.currentUser,n}function T4(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 D4(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 N4(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 z4(e,t){const n=N4(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 mi(e,t){for(const[n,o]of Object.entries(t)){const r=e[n];St(o)&&St(r)?mi(r,o):e[n]=Xt(o)}}function P4(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 Ua(e,t,n){const o=P4(t);if(o.length===0)return;let r=e;for(let s=0;s0?t:void 0}const Ga="g7le:editor-t-ready",wg="data-g7le-vh-expanded";function B4(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(wg,"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(wg,"1"))})}const W4=[];function j4(e={}){const{manifest:t=null,nesting:n=null,componentPalette:o=null,spec:r=null,permissionCandidates:s,sampleGlobalSources:a=W4,resolveRouteMatch:l,onNavigateToDestination:d,onSessionAddedPathsChange:c}=e,{state:p}=Je(),f=Ft(),y=Cp(),{document:g,isLoading:m,error:h}=f??y,v=u.useRef(null),[b,x]=u.useState(null),{deviceWidth:k,scale:w,colorScheme:_}=ja(),C=u.useMemo(()=>p.activeStateId?p.availableStates.find(Q=>Q.id===p.activeStateId)??null:null,[p.activeStateId,p.availableStates]),E=u.useMemo(()=>xg(C),[C]),S=f4({isEditMode:!0,editorSpec:r??void 0,sampleOverride:E}),{t:T}=tt(),{componentRegistry:$,translationEngine:A,isReady:z,error:D}=_4(p.templateIdentifier,p.locale),O=u.useRef(null);O.current===null&&(O.current=new vd);const M=u.useRef(null);if(M.current===null){M.current=new VE({navigate:()=>{}}),M.current.setPreviewMode(!0);try{const ie=window.__templateApp?.getActionDispatcher?.();if(ie&&typeof ie.getRegisteredHandlers=="function"){const _e=ie.getRegisteredHandlers();for(const ge of _e){if(!ge.includes("."))continue;const Ae=typeof ie.getHandler=="function"?ie.getHandler(ge):void 0;typeof Ae=="function"&&M.current.registerHandler(ge,Ae,{category:"plugin",source:"preview-canvas-cloned-from-host"})}}}catch{}}u.useEffect(()=>{if(!z)return;const Q=M.current;if(Q)try{const ie=window.G7Core?.getActionDispatcher?.();if(!ie||typeof ie.getRegisteredHandlers!="function")return;const _e=ie.getRegisteredHandlers();for(const ge of _e){if(!ge.includes(".")||typeof Q.getHandler=="function"&&Q.getHandler(ge))continue;const Ae=typeof ie.getHandler=="function"?ie.getHandler(ge):void 0;typeof Ae=="function"&&Q.registerHandler(ge,Ae,{category:"plugin",source:"preview-canvas-iife-reclone"})}}catch{}},[z]);const B=u.useMemo(()=>new UE({sampleProvider:S,actionDispatcher:M.current}),[S]),N=u.useMemo(()=>g?.raw?.meta?.guest_only===!0,[g]),H=u.useMemo(()=>Va({sources:a,isGuestOnly:N}),[a,N]),L=u.useMemo(()=>{const Q=H4(qa(C),A,{templateId:p.templateIdentifier,locale:p.locale}),ie=H._local,{global:_e,local:ge}=O4({globalBaseline:H,localBaseline:ie??{},patch:C?.initialState??null,formErrors:Q});return{..._e,_local:ge}},[H,C,A,p.templateIdentifier,p.locale]),I=u.useMemo(()=>!C||!(!!C.initialState?.local||!!qa(C))?null:{...L._local??{},_forceLocalInit:C.id,_merge:"deep"},[C,L]),P=Q=>typeof Q=="object"&&Q!==null&&!Array.isArray(Q),F=u.useMemo(()=>P(C?.initialState?.query)?C.initialState.query:null,[C]),G=u.useMemo(()=>P(C?.initialState?.route)?C.initialState.route:null,[C]),[V,Y]=u.useState(()=>Va({sources:[],isGuestOnly:!1})),Z=u.useRef(null);u.useEffect(()=>{const Q={...L},ie=C4({actionDispatcher:M.current,locale:p.locale,initialGlobalState:Q,onChange:ge=>{Y(ge.globalState)}});Z.current=ie;const _e=window.__templateApp;return _e?.setGlobalState&&M.current.setGlobalStateUpdater((ge,Ae)=>{_e.setGlobalState(ge,Ae)}),Y(Q),$l({kind:"applyPatch",activeStateId:p.activeStateId,routePath:p.selectedRoute?.path??null,hasInitialPatch:!!C?.initialState,hasFormErrors:!!qa(C),hasSampleOverride:!!xg(C)}),()=>{ie.restore(),Z.current=null}},[p.locale,L]),u.useEffect(()=>{if(!A)return;const Q=window.G7Core;if(!Q||typeof Q.t!="function")return;const ie=Q.t,_e=p.templateIdentifier,ge=p.locale;return Q.t=(Ae,Ne)=>{try{const Le=Ne?"|"+Object.entries(Ne).map(([ae,pe])=>`${ae}=${pe}`).join("|"):void 0,q=A.translate(Ae,{templateId:_e,locale:ge},Le);if(q!==Ae&&!q.startsWith("$t:"))return q}catch{}return ie(Ae,Ne)},typeof window<"u"&&window.dispatchEvent(new CustomEvent(Ga)),()=>{window.G7Core?.t&&window.G7Core.t!==ie&&(window.G7Core.t=ie)}},[A,p.templateIdentifier,p.locale]);const se=u.useMemo(()=>{const Q=g?.raw?.components??[];return p.editMode!=="base"?Q:L4(Q)},[g,p.editMode]),re=g?.raw?.__editability,U=g?.raw?.__extensionId,ee=u.useMemo(()=>p.editMode!=="extension"||re!=="ok"?[]:typeof U!="number"?[]:F4(se,U),[p.editMode,re,U,se]),[fe,K]=u.useState(null),[ne,me]=u.useState(!1),Ce=g?.layoutName??null,ze=u.useMemo(()=>{const Q=g?.raw?.scripts??[];return Array.isArray(Q)?Q.map(ie=>ie&&typeof ie.src=="string"?ie.src:"").join("|"):""},[g]);u.useEffect(()=>{me(!1)},[Ce,ze]),u.useEffect(()=>{let Q=!1;const ie=g?.raw?.scripts??[];if(!Array.isArray(ie)||ie.length===0){me(!0);return}const _e=[];for(const ge of ie){if(!ge?.src||typeof ge.src!="string")continue;const Ae=ge.id?`script#${CSS.escape(ge.id)}, script[data-g7le-canvas-script="${ge.src}"]`:`script[data-g7le-canvas-script="${ge.src}"], script[src="${ge.src}"]`,Ne=window.document.querySelector(Ae);if(Ne){const Le=Ne.hasAttribute("data-g7le-canvas-script");if(Ne.hasAttribute("data-g7le-script-loaded")||!Le)continue;_e.push(new Promise(ae=>{if(Ne.hasAttribute("data-g7le-script-loaded")){ae();return}Ne.addEventListener("load",()=>ae()),Ne.addEventListener("error",()=>ae())}));continue}_e.push(new Promise(Le=>{const q=window.document.createElement("script");q.src=ge.src,q.async=!1,ge.id&&(q.id=ge.id),q.setAttribute("data-g7le-canvas-script",ge.src);const ae=()=>{q.setAttribute("data-g7le-script-loaded","1"),Le()};q.addEventListener("load",ae),q.addEventListener("error",ae),window.document.head.appendChild(q)}))}if(_e.length===0){me(!0);return}return Promise.all(_e).then(()=>{Q||requestAnimationFrame(()=>{requestAnimationFrame(()=>{Q||me(!0)})})}),()=>{Q=!0}},[g]);const Se=u.useMemo(()=>g?.raw?.data_sources??[],[g]),qe=u.useMemo(()=>g?.raw?.computed??{},[g]),[De,Pe]=u.useState({}),Qe=u.useMemo(()=>{if(p.editMode!=="iteration_item")return De;const Q=g?.iterationContext;if(!Q)return De;const ie=g?.raw?.components??[],_e=We({children:ie},Q.sourceIndexPath),ge=_e&&_e.iteration&&typeof _e.iteration.source=="string"?_e.iteration.source:null;return ge?z4(De,ge):De},[p.editMode,De,g]),[Me,Re]=u.useState(0);u.useEffect(()=>{if(typeof window>"u")return;const Q=()=>Re(ie=>ie+1);return window.addEventListener(kt,Q),()=>window.removeEventListener(kt,Q)},[]);const ve=u.useMemo(()=>E4(p.selectedRoute?.path??null),[p.selectedRoute?.path]);if(u.useEffect(()=>{let Q=!1;return(async()=>{if(Se.length===0){Q||Pe({});return}try{const ie=await B.fetchDataSources(Se,ve,new URLSearchParams,void 0,void 0);Q||Pe(ie)}catch{Q||Pe({})}})(),()=>{Q=!0}},[Se,B,ve]),u.useEffect(()=>{const Q=b;if(!Q||typeof window>"u")return;let ie=0,_e=0,ge=0;const Ae=()=>B4(Q,window.innerHeight);ie=window.requestAnimationFrame(()=>{_e=window.requestAnimationFrame(Ae)});let Ne=null;return typeof MutationObserver<"u"&&(Ne=new MutationObserver(()=>{ge||(ge=window.requestAnimationFrame(()=>{ge=0,Ae()}))}),Ne.observe(Q,{childList:!0,subtree:!0})),()=>{window.cancelAnimationFrame(ie),window.cancelAnimationFrame(_e),ge&&window.cancelAnimationFrame(ge),Ne&&Ne.disconnect()}},[b,se,ne,k,De]),u.useEffect(()=>{const Q=b;if(!Q||typeof window>"u"||p.editMode!=="extension"||re!=="ok"||ee.length===0){K(null);return}let ie=0,_e=0;const ge=ae=>{if(!ae)return!1;const pe=ae.getBoundingClientRect();return pe.width>0&&pe.height>0},Ae=ae=>{const pe=Q.querySelector(`[data-editor-path="${ae}"]`);if(ge(pe))return!0;const $e=Q.querySelectorAll(`[data-editor-path^="${ae}.children."]`);for(const be of Array.from($e))if(ge(be))return!0;return!1},Ne=()=>{K(ee.some(Ae))};ie=window.requestAnimationFrame(()=>{_e=window.requestAnimationFrame(Ne)});let Le=null,q=0;return typeof MutationObserver<"u"&&(Le=new MutationObserver(()=>{q||(q=window.requestAnimationFrame(()=>{q=0,Ne()}))}),Le.observe(Q,{childList:!0,subtree:!0})),()=>{window.cancelAnimationFrame(ie),window.cancelAnimationFrame(_e),q&&window.cancelAnimationFrame(q),Le&&Le.disconnect()}},[b,p.editMode,re,ee,ne,De]),u.useEffect(()=>{if(typeof window>"u"||p.editMode!=="base")return;const Q=window.document,ie="g7le-base-slot-style";if(Q.getElementById(ie))return;const _e=Q.createElement("style");_e.id=ie;const ge=T("layout_editor.preview.slot_area_label");return _e.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:'${ge.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;}`,Q.head.appendChild(_e),()=>{Q.getElementById(ie)?.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:Zo,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:Zo,children:T("layout_editor.preview.loading")});if(h)return i.jsx(Fa,{error:h});if(D)return i.jsx(Fa,{error:D});if(!z||$===null||A===null)return i.jsx("div",{className:"g7le-preview-canvas g7le-preview-canvas--assets-loading","data-testid":"g7le-preview-assets-loading",style:Zo,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:Zo,children:T("layout_editor.preview.empty_layout")});const he=p.editMode==="extension"?re==="no-injection"?"no-injection":re==="ok"&&ee.length>0&&fe!==!0?"gated-no-state":null:null;return ne?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:k,transform:`scale(${w})`,transformOrigin:"top center"},children:[i.jsx("div",{className:_==="dark"?"g7le-preview-frame g7le-preview-dark":"g7le-preview-frame","data-testid":"g7le-preview-frame","data-color-scheme":_,ref:Q=>{v.current=Q,x(Q)},style:{width:k,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(KE,{overrideWidth:k,children:se.map((Q,ie)=>i.jsx(FE,{componentDef:Q,dataContext:{...Qe,...T4(V),_global:D4(V),_computedDefinitions:qe,...I?{_localInit:I,_local:{...De._local??{},...V._local??{}}}:{},route:K4({...De.route??{},...ve,path:p.selectedRoute?.path??""},G),query:{...De.query??{},...F??{}}},translationContext:{templateId:p.templateIdentifier,locale:p.locale},registry:$,bindingEngine:O.current,translationEngine:Pt.getInstance(),actionDispatcher:M.current,isEditMode:!0,isRootRenderer:ie===0,componentPath:`${ie}`,onComponentSelect:(_e,ge)=>{},onComponentHover:(_e,ge)=>{}},`${Q.id??`preview-${ie}`}:t${Me}${p.editMode==="extension"?`:s${ne?1:0}`:""}`))})}),i.jsx("div",{className:"g7le-overlay-layer","data-testid":"g7le-overlay-layer",style:{position:"absolute",left:0,top:0,width:k,height:b?b.getBoundingClientRect().height/(w||1):"100%",overflow:"visible",pointerEvents:"none"},children:i.jsx(p4,{frameEl:b,manifest:t,nesting:n,componentPalette:o,spec:r,permissionCandidates:s,resolveRouteMatch:l,onNavigateToDestination:d,onSessionAddedPathsChange:c})}),he!==null&&i.jsx("div",{className:"g7le-preview-canvas--extension-fallback","data-testid":"g7le-preview-extension-fallback","data-fallback-reason":he,style:{position:"absolute",left:0,top:0,right:0,bottom:0,minHeight:b?b.getBoundingClientRect().height/(w||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(he==="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:he==="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:Zo,children:T("layout_editor.preview.loading")})}function H4(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 F4(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 K4(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 Zo={flex:1,display:"flex",alignItems:"center",justifyContent:"center",padding:24,background:"#f1f5f9",color:"#64748b",fontSize:13},V4={desktop:"layout_editor.device.desktop",tablet:"layout_editor.device.tablet",mobile:"layout_editor.device.mobile",portable:"layout_editor.device.portable"};function U4(){const{device:e,zoom:t,customWidth:n,setDevice:o,setZoom:r,setCustomWidth:s,colorScheme:a,setColorScheme:l}=ja(),{t:d}=tt(),c=Gf();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,y=V4[p],g=y?d(y):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:ug,max:pg,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(Kb,{})]})}function q4(){const{t:e}=tt(),{state:t,dispatch:n}=Je(),{availableStates:o,activeStateId:r}=t,[,s]=u.useState(0);u.useEffect(()=>{if(typeof window>"u")return;const p=()=>s(y=>y+1),f=window.requestAnimationFrame(p);return window.addEventListener(Ga,p),()=>{window.cancelAnimationFrame(f),window.removeEventListener(Ga,p)}},[]);const a=u.useCallback((p,f)=>{if(!p)return f;if(!p.startsWith("$t:"))return p;const y=p.slice(3),g=window.G7Core;if(g&&typeof g.t=="function"){const h=g.t(y);if(h&&h!==y&&!h.startsWith("$t:"))return h}const m=e(y);return m&&m!==y?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}),$l({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 G4(e,t,n){if(e==="extension"){if(typeof n=="string"&&n.length>0){const o=Ya(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=Ya(t,"__base__/");return o?{kind:"base",match:o}:null}case"modal":{const o=Ya(t,"__modal__/");return o?{kind:"modal",match:o}:null}default:return null}}function Y4(e,t){if(!t||!Array.isArray(e)||e.length===0)return[];const n=[];for(const o of e)if(J4(o.scope,t))for(const r of o.items??[])r&&typeof r.id=="string"&&r.id.length>0&&n.push(r);return n}function X4(e){if(e.length===0)return null;const t=e.find(n=>n.default===!0);return t?t.id:e[0].id}function J4(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"?Z4(t.match,n):n===t.match}function Z4(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 Ya(e,t){return e.startsWith(t)?e.slice(t.length):""}const Q4="__conngroup__/modals/",R4="__conngroup__/extensions/";function eD(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 tD(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 nD(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 oD(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 rD(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 iD(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 sD(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 aD(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 kg(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:`${Q4}${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=>sD(a,e.path))});const s=n.get(e.layoutName)??[];s.length>0&&o.push({path:`${R4}${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=>aD(a,e.path))}),o.length>0&&(e.children=[...o,...e.children??[]])}function lD(e){const t=[],n=new Set(e.routes.map(o=>o.path));for(const o of e.routes){const r=tD(o);if(!r)continue;const{label:s,labelSource:a}=eD(o),l=nD(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 dD(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 cD(e,t){oD(e.routes);const n=rD(e.modals),o=iD(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),y=p(c);return f!==y?f-y: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)kg(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 y of c)p.set(y.node.path,y);const f=[];for(const y of c)if(y.parentKey&&p.has(y.parentKey)){const g=p.get(y.parentKey);g.node.children=g.node.children??[],g.node.children.push(y.node)}else f.push(y.node);for(const y of c)kg(y.node,n,o);a.push({path:`__group__/${d}`,layoutName:null,label:dD(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(y=>({path:`__extension__/${y.id}`,layoutName:null,label:`${c.sourceLabel} · ${y.targetName}`,labelSource:"path",source:{kind:c.sourceType,identifier:c.sourceIdentifier},kind:"extension",extensionId:String(y.id),extensionType:y.extensionType,extensionPriority:y.priority,extensionTargetName:y.targetName,isModified:y.isModified,isInactive:!y.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 uD(e){const t=lD(e);return cD(e,t)}const On=bo("useEditorRoutes");function pD(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 Sg(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]=pD(s.display_name,t)??s.identifier);return n}function fD(e){const t=new vd,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 gD(e){const{dispatch:t}=Je(),{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(),y=(()=>{if(typeof fetch!="function")return Promise.reject(io(new Error("fetch unavailable"),"routes"));try{const h=fetch(c,{credentials:"same-origin",headers:je()});return!h||typeof h.then!="function"?Promise.reject(io(new Error("fetch returned non-Promise (test stub?)"),"routes")):h.then(async v=>{if(!v.ok){const b=await v.json().catch(()=>null);throw Gr(v.status,b,"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:je()});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([y,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 b=fD(h.data.routes),x=Sg("activeModules",p),k=Sg("activePlugins",p),w=(h.data.base_layouts??[]).map(A=>({layoutName:A.layout_name,label:A.label??void 0})),_=(h.data.modals??[]).map(A=>({modalId:A.modal_id,hostLayout:A.host_layout,label:A.label??void 0})),C=(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(z=>({id:z.id,extensionType:z.extension_type,targetName:z.target_name,priority:z.priority,isActive:z.is_active,isModified:z.is_modified,hostLayouts:Array.isArray(z.host_layouts)?z.host_layouts:[],currentVersion:typeof z.current_version=="number"?z.current_version:void 0}))})),E=uD({routes:b,modals:_,baseLayouts:w,extensionGroups:C,moduleDisplayNames:x,pluginDisplayNames:k});t({type:"SET_ROUTE_TREE",tree:E});const S=h.data.layout_versions,T={};if(S&&typeof S=="object"&&!Array.isArray(S))for(const[A,z]of Object.entries(S))typeof z=="number"&&Number.isFinite(z)&&(T[A]=z);t({type:"SET_LAYOUT_VERSIONS",versions:T});const $={};for(const A of C)for(const z of A.extensions){const D=z.currentVersion;typeof D=="number"&&Number.isFinite(D)&&($[String(z.id)]=D)}t({type:"SET_EXTENSION_VERSIONS",versions:$}),On.log("routes 로드 완료",{count:b.length,groups:E.length})}).catch(h=>{if(a)return;On.error("routes 로드 실패",h);const v=hp(h)?h:io(h,"routes");t({type:"SET_ROUTES_ERROR",error:v})}),()=>{a=!0}},[r,s,t,n,o?.locale,o?.templateId])}function Cg(e,t,n,o=[]){const r=t?$g(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 $g(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=$g(n.children,t);if(o)return o}}return null}function Xa(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=Xa(n.children,t);if(o)return o}}return null}function hD(e){const{state:t,dispatch:n}=Je(),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=ap(window.location.search);if(a){const c=sp(window.location.search),p=Cg(a,c,n,t.routeTree);if(o.current=!0,p)return}const l=ip(window.location.search);if(!l){o.current=!0;return}const d=Xa(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=ap(window.location.search);if(l){const p=sp(window.location.search);if(Cg(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=ip(window.location.search);if(!d){n({type:"SELECT_ROUTE",route:null});return}const c=Xa(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=Zs(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 yD(){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 bD(){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 mD(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 vD(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 _D(e,t){if(Array.isArray(e.components)){const n=t.map(o=>Ja(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&&rJa(n))),t}function Eg(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 Ig(e,t){const o=Eg(e,t)[0]?.__source;return o&&o.kind==="extension"&&o.extensionId===t?o:{kind:"extension",extensionId:t}}function Za(e,t){for(const n of e){const o=n?.__source;if(o?.kind==="extension"&&o.extensionId===t||Array.isArray(n.children)&&Za(n.children,t))return!0}return!1}function xD(){const{state:e}=Je(),t=e.templateIdentifier,n=e.editMode==="extension"?mD(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),[y,g]=u.useState(0),[m,h]=u.useState(null),v=u.useRef({}),b=u.useRef({kind:"extension",extensionId:0}),x=u.useRef(null);u.useEffect(()=>{x.current=r},[r]),u.useEffect(()=>{h(null)},[n]);const k=u.useCallback(async A=>{const z=window.G7Config?.cache_version??0,D=en(`/api/layouts/${encodeURIComponent(t)}/${A}`,"json",`${z}.${Sp()}`,"with_source_meta=1"),O=ar(),M={Accept:"application/json"};O&&(M.Authorization=`Bearer ${O}`);const B=await fetch(D,{headers:M,credentials:"same-origin"});if(!B.ok)return null;const N=await B.json().catch(()=>null);return(N&&(N.data||N))??{}},[t]),w=u.useCallback(async()=>{if(!n){s(null),c(null),f(!1);return}l(!0),c(null);try{const A=window.G7Config?.cache_version??0,z=`/api/admin/templates/${encodeURIComponent(t)}/layout-extensions/${encodeURIComponent(n)}?v=${A}`,D=await fetch(z,{headers:je(),credentials:"same-origin"}),O=await D.json().catch(()=>null);if(!D.ok){c(Gr(D.status,O,"layout")),s(null),f(!1);return}const M=(O&&(O.data||O))??{};let B={};const N=M.content;if(typeof N=="string")try{B=JSON.parse(N)}catch{B={}}else N&&typeof N=="object"&&(B=N);const H=M.extension_type==="overlay"?"overlay":"extension_point",L=typeof M.lock_version=="number"?M.lock_version:0,I=Array.isArray(M?.host_layouts)?M.host_layouts.filter(re=>typeof re=="string"):[],P=o??(I.length===1?I[0]:m&&I.includes(m)?m:null),F=Number(n);v.current=B;let V=vD(B),Y={},Z="pending";const se={kind:"extension",extensionId:F};if(b.current=se,P){const re=await k(P);if(re){Y=re;const U=Array.isArray(re.components)?re.components:[],ee=Ig(U,F);if(b.current=ee,Za(U,F))V=U,Z="ok";else{const K=(Array.isArray(re.modals)?re.modals:[]).filter(ne=>ne&&typeof ne=="object"&&Za([ne],F));if(K.length>0){const ne=K.map(me=>({...me,props:{...me.props??{},isOpen:!0}}));V=[...U,...ne],b.current=Ig(K,F),Z="ok"}else V=U,Z="no-injection"}}}s({extensionId:F,content:B,extensionType:H,components:V,lockVersion:L,hostLayouts:I,hostLayoutName:P,hostRaw:Y,editability:Z}),f(!1),st({op:"load",layoutName:`extension:${n}`,editMode:"extension",statusCode:D.status,timestamp:Date.now()})}catch(A){c(io(A,"layout")),s(null),f(!1)}finally{l(!1)}},[t,n,m,o,k]);u.useEffect(()=>{w()},[w]);const _=u.useCallback(A=>{h(A)},[]),C=u.useCallback(A=>{s(z=>z&&{...z,components:A}),f(!0),st({op:"patch",layoutName:`extension:${x.current?.extensionId??""}`,editMode:"extension",isDirty:!0,timestamp:Date.now()})},[]),E=u.useCallback(A=>{s(z=>z&&{...z,components:A(z.components)}),f(!0)},[]),S=u.useCallback(async()=>{const A=x.current;if(!A)return{kind:"guard_no_document"};const z=`/api/admin/templates/${encodeURIComponent(t)}/layout-extensions/${A.extensionId}`,D=Eg(A.components,A.extensionId),O=D.length>0?D:A.components,M=_D(v.current,O);st({op:"save",layoutName:`extension:${A.extensionId}`,editMode:"extension",saveTarget:"layout_extension",endpoint:z,isDirty:p,timestamp:Date.now()});let B;try{B=await fetch(z,{method:"PUT",headers:je({"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 N=await B.json().catch(()=>null);if(st({op:"save_response",layoutName:`extension:${A.extensionId}`,editMode:"extension",endpoint:z,statusCode:B.status,conflict:B.status===409?{currentVersion:N?.errors?.current_version??N?.current_version,yourVersion:N?.errors?.your_version??N?.your_version}:void 0,timestamp:Date.now()}),B.ok){const H=N?.data??{},L=typeof H.lock_version=="number"?H.lock_version:A.lockVersion+1;s(P=>P&&{...P,lockVersion:L}),f(!1),g(P=>P+1);const I=typeof H.current_version=="number"?H.current_version:void 0;return{kind:"success",newLockVersion:L,newContentVersion:I,savedExtensionId:String(A.extensionId)}}return B.status===409?{kind:"concurrent_modification",currentVersion:N?.current_version??-1,yourVersion:N?.your_version??A.lockVersion}:B.status===422?{kind:"validation_failed",status:422,errors:N?.errors??null}:{kind:"network_error",message:N?.message??`HTTP ${B.status}`}},[t,p]),T=u.useCallback(async()=>{na(),await w()},[w]),$=!!r&&r.hostLayouts.length>1&&r.hostLayoutName===null;return{document:r,isLoading:a,error:d,isDirty:p,saveSuccessCounter:y,setLayoutComponents:C,patchLayout:E,save:S,reload:T,needsHostPicker:$,selectHost:_}}const Ag=new Set;function wD(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 kD(e){return{document:e.document?{layoutName:`extension:${e.document.extensionId}`,raw:{...wD(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:Ag,dirtyLayoutNames:Ag,invalidateCurrentCache:()=>{},reloadCounter:0,save:()=>e.save(),markDirty:()=>{}}}function SD({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 CD(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=vo(l),c=`/api/admin/templates/${encodeURIComponent(e)}/layouts/${t}/preview`,p=await fetch(c,{method:"POST",credentials:"same-origin",headers:je({"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 y=f?.data,g=typeof y?.token=="string"?y.token:"",m=typeof y?.preview_url=="string"&&y.preview_url?y.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 ce="layout_editor.action_recipe",bn={setState:{label:`$t:${ce}.set_state.label`,params:[{key:"target",label:`$t:${ce}.set_state.param_target`,widget:"select",options:[{value:"local"},{value:"global"}]},{key:"state",label:`$t:${ce}.set_state.param_state`,widget:"state-key-value"},{key:"merge",label:`$t:${ce}.set_state.param_merge`,widget:"toggle"}],build:{handler:"setState",params:{target:"{{target}}",merge:"{{merge}}","...":"{{state}}"}}},loadFromLocalStorage:{label:`$t:${ce}.load_local.label`,params:[{key:"key",label:`$t:${ce}.load_local.param_key`,widget:"text",required:!0},{key:"stateKey",label:`$t:${ce}.load_local.param_state_key`,widget:"state-key-picker"},{key:"defaultValue",label:`$t:${ce}.load_local.param_default`,widget:"text"}],build:{handler:"loadFromLocalStorage",params:{key:"{{key}}",stateKey:"{{stateKey}}",defaultValue:"{{defaultValue}}"}}},saveToLocalStorage:{label:`$t:${ce}.save_local.label`,params:[{key:"key",label:`$t:${ce}.save_local.param_key`,widget:"text",required:!0},{key:"value",label:`$t:${ce}.save_local.param_value`,widget:"data-chip"}],build:{handler:"saveToLocalStorage",params:{key:"{{key}}",value:"{{value}}"}}},navigate:{label:`$t:${ce}.navigate.label`,params:[{key:"path",label:`$t:${ce}.navigate.param_path`,widget:"page-picker",required:!0},{key:"query",label:`$t:${ce}.navigate.param_query`,widget:"key-value"},{key:"mergeQuery",label:`$t:${ce}.navigate.param_merge_query`,widget:"toggle"},{key:"scroll",label:`$t:${ce}.navigate.param_scroll`,widget:"select",options:[{value:"top"},{value:"preserve"},{value:"none"}]},{key:"replace",label:`$t:${ce}.navigate.param_replace`,widget:"toggle"},{key:"transition_overlay_target",label:`$t:${ce}.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:${ce}.open_window.label`,params:[{key:"target",label:`$t:${ce}.open_window.param_target`,widget:"page-picker",required:!0},{key:"windowTarget",label:`$t:${ce}.open_window.param_window_target`,widget:"select",options:[{value:"_blank"},{value:"_self"}]}],build:{handler:"openWindow",target:"{{target}}",params:{windowTarget:"{{windowTarget}}"}}},navigateBack:{label:`$t:${ce}.navigate_back.label`,params:[],build:{handler:"navigateBack"}},navigateForward:{label:`$t:${ce}.navigate_forward.label`,params:[],build:{handler:"navigateForward"}},replaceUrl:{label:`$t:${ce}.replace_url.label`,params:[{key:"path",label:`$t:${ce}.replace_url.param_path`,widget:"page-picker"},{key:"query",label:`$t:${ce}.replace_url.param_query`,widget:"key-value"}],build:{handler:"replaceUrl",params:{path:"{{path}}",query:"{{query}}"}}},toast:{label:`$t:${ce}.toast.label`,params:[{key:"message",label:`$t:${ce}.toast.param_message`,widget:"i18n-text",required:!0},{key:"type",label:`$t:${ce}.toast.param_type`,widget:"select",options:[{value:"info"},{value:"success"},{value:"warning"},{value:"error"}]},{key:"duration",label:`$t:${ce}.toast.param_duration`,widget:"number"},{key:"icon",label:`$t:${ce}.toast.param_icon`,widget:"text"}],build:{handler:"toast",params:{message:"{{message}}",type:"{{type}}",duration:"{{duration}}",icon:"{{icon}}"}}},openModal:{label:`$t:${ce}.open_modal.label`,params:[{key:"target",label:`$t:${ce}.open_modal.param_target`,widget:"modal-picker",required:!0}],build:{handler:"openModal",target:"{{target}}"}},closeModal:{label:`$t:${ce}.close_modal.label`,params:[],build:{handler:"closeModal"}},showAlert:{label:`$t:${ce}.show_alert.label`,params:[{key:"target",label:`$t:${ce}.show_alert.param_message`,widget:"i18n-text",required:!0}],build:{handler:"showAlert",target:"{{target}}"}},setError:{label:`$t:${ce}.set_error.label`,params:[{key:"target",label:`$t:${ce}.set_error.param_message`,widget:"i18n-text"},{key:"stateTarget",label:`$t:${ce}.set_error.param_state_target`,widget:"select",options:[{value:"local"},{value:"global"}]}],build:{handler:"setError",target:"{{target}}",params:{stateTarget:"{{stateTarget}}"}}},refetchDataSource:{label:`$t:${ce}.refetch.label`,params:[{key:"dataSourceId",label:`$t:${ce}.refetch.param_data_source`,widget:"datasource-picker",required:!0},{key:"sync",label:`$t:${ce}.refetch.param_sync`,widget:"toggle"}],build:{handler:"refetchDataSource",params:{dataSourceId:"{{dataSourceId}}",sync:"{{sync}}"}}},appendDataSource:{label:`$t:${ce}.append_data.label`,params:[{key:"dataSourceId",label:`$t:${ce}.append_data.param_data_source`,widget:"datasource-picker",required:!0},{key:"dataPath",label:`$t:${ce}.append_data.param_data_path`,widget:"text"},{key:"newData",label:`$t:${ce}.append_data.param_new_data`,widget:"data-chip"}],build:{handler:"appendDataSource",params:{dataSourceId:"{{dataSourceId}}",dataPath:"{{dataPath}}",newData:"{{newData}}"}}},updateDataSource:{label:`$t:${ce}.update_data.label`,params:[{key:"dataSourceId",label:`$t:${ce}.update_data.param_data_source`,widget:"datasource-picker",required:!0},{key:"data",label:`$t:${ce}.update_data.param_data`,widget:"data-chip"},{key:"merge",label:`$t:${ce}.update_data.param_merge`,widget:"toggle"}],build:{handler:"updateDataSource",params:{dataSourceId:"{{dataSourceId}}",data:"{{data}}",merge:"{{merge}}"}}},scrollIntoView:{label:`$t:${ce}.scroll.label`,params:[{key:"selector",label:`$t:${ce}.scroll.param_selector`,widget:"text",required:!0},{key:"behavior",label:`$t:${ce}.scroll.param_behavior`,widget:"select",options:[{value:"smooth"},{value:"auto"}]},{key:"block",label:`$t:${ce}.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:${ce}.login.label`,params:[{key:"body",label:`$t:${ce}.login.param_body`,widget:"key-value"}],build:{handler:"login",params:{body:"{{body}}"}}},logout:{label:`$t:${ce}.logout.label`,params:[{key:"target",label:`$t:${ce}.logout.param_target`,widget:"text"}],build:{handler:"logout",target:"{{target}}"}},setLocale:{label:`$t:${ce}.set_locale.label`,params:[{key:"target",label:`$t:${ce}.set_locale.param_target`,widget:"locale-picker",required:!0}],build:{handler:"setLocale",target:"{{target}}"}},emitEvent:{label:`$t:${ce}.emit_event.label`,params:[{key:"event",label:`$t:${ce}.emit_event.param_event`,widget:"text",required:!0},{key:"data",label:`$t:${ce}.emit_event.param_data`,widget:"data-chip"}],build:{handler:"emitEvent",params:{event:"{{event}}",data:"{{data}}"}}},apiCall:{label:`$t:${ce}.api_call.label`,params:[{key:"target",label:`$t:${ce}.api_call.param_target`,widget:"page-picker",required:!0},{key:"method",label:`$t:${ce}.api_call.param_method`,widget:"select",options:[{value:"GET"},{value:"POST"},{value:"PUT"},{value:"PATCH"},{value:"DELETE"}]},{key:"body",label:`$t:${ce}.api_call.param_body`,widget:"key-value"},{key:"query",label:`$t:${ce}.api_call.param_query`,widget:"key-value"},{key:"identity_target_email",label:`$t:${ce}.api_call.param_identity_target_email`,widget:"data-chip"},{key:"identity_target_phone",label:`$t:${ce}.api_call.param_identity_target_phone`,widget:"data-chip"},{key:"onSuccess",label:`$t:${ce}.api_call.param_on_success`,widget:"action-list"},{key:"onError",label:`$t:${ce}.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:${ce}.conditions.label`,params:[{key:"branches",label:`$t:${ce}.conditions.param_branches`,widget:"branch-list"}],build:{handler:"conditions",conditions:"{{branches}}"}},sequence:{label:`$t:${ce}.sequence.label`,params:[{key:"actions",label:`$t:${ce}.sequence.param_actions`,widget:"action-list"}],build:{handler:"sequence",params:{actions:"{{actions}}"}}},parallel:{label:`$t:${ce}.parallel.label`,params:[{key:"actions",label:`$t:${ce}.parallel.param_actions`,widget:"action-list"}],build:{handler:"parallel",params:{actions:"{{actions}}"}}},switch:{label:`$t:${ce}.switch.label`,params:[{key:"value",label:`$t:${ce}.switch.param_value`,widget:"data-chip"},{key:"cases",label:`$t:${ce}.switch.param_cases`,widget:"action-list",advanced:!0}],build:{handler:"switch",params:{value:"{{value}}",cases:"{{cases}}"}}},suppress:{label:`$t:${ce}.suppress.label`,params:[],build:{handler:"suppress"}}};function $D(){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:${ce}.show_error_page.label`,params:[{key:"target",label:`$t:${ce}.show_error_page.param_target`,widget:"select",options:[{value:"content"},{value:"full"}]}],build:{handler:"showErrorPage",params:{target:"{{target}}"}}}}}}function Qa(e,t){return typeof e.label=="string"?e.label.startsWith("$t:")?t(e.label.slice(3)):e.label:String(e.value)}function vi(e){return Array.isArray(e.options)?e.options:[]}function ED({control:e,value:t,onChange:n,t:o}){const r=vi(e);return i.jsx("div",{className:"g7le-widget g7le-widget--segmented","data-testid":"g7le-widget-segmented",style:WD,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:{...GD,background:a?"#2563eb":"#fff",color:a?"#fff":"#0f172a",borderColor:a?"#2563eb":"#cbd5e1"},children:Qa(s,o)},String(s.value))})})}function ID({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:Dg,children:[i.jsxs("label",{style:Ra,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 AD({control:e,value:t,onChange:n,t:o}){const r=vi(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:YD,children:[i.jsx("option",{value:"",children:o("layout_editor.control.default")}),r.map(s=>i.jsx("option",{value:String(s.value),children:Qa(s,o)},String(s.value)))]})}function TD({control:e,value:t,onChange:n}){const o=vi(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:{...XD,background:a?"#2563eb":"#cbd5e1"},children:i.jsx("span",{style:{...JD,transform:a?"translateX(18px)":"translateX(0)"}})})}function DD({control:e,value:t,onChange:n,t:o,freeValueDisabled:r}){const s=vi(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:jD,children:[r?i.jsx("div",{"data-testid":"g7le-dimension-free-disabled",style:UD,children:o("layout_editor.property_modal.dark_preset_only")}):i.jsxs("div",{style:HD,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:FD}),i.jsx("button",{type:"button","data-testid":"g7le-dimension-clear",title:o("layout_editor.control.default"),onClick:()=>{d(""),n(void 0)},style:KD,children:o("layout_editor.control.default")})]}),s.length>0&&i.jsx("div",{style:VD,"data-testid":"g7le-dimension-chips",children:s.map(p=>{const f=String(p.value),y=f===a;return i.jsx("button",{type:"button","data-testid":`g7le-dimension-chip-${f}`,"data-active":y?"true":"false",onClick:()=>{d(f),n(f)},style:{...qD,background:y?"#2563eb":"#fff",color:y?"#fff":"#0f172a",borderColor:y?"#2563eb":"#cbd5e1"},children:Qa(p,o)},f)})})]})}function ND(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 zD(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 MD({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(b=>String(b)),a=ND(r),l=zD(t,r,a,s),d=Object.values(l.sides).some(b=>b>=0),c=l.all>=0||d,[p,f]=u.useState(d);u.useEffect(()=>{d&&f(!0)},[d]);const y=Math.min(4,Math.max(0,s.length-1)),g=b=>{const x=[];for(const k of a){const w=b[k.key];w!==void 0&&w>=0&&x.push(`${k.infix}${s[w]}`)}n(x.length>0?x.join(" "):void 0)},m=b=>{n(b>=0?`${r}-${s[Math.max(0,Math.min(b,s.length-1))]}`:void 0)},h=()=>({...l.sides}),v=(b,x,k,w,_)=>{const C=k>=0;return i.jsxs("div",{style:BD,"data-testid":b,children:[i.jsxs("label",{style:{...Ra,minWidth:64},children:[i.jsx("input",{type:"checkbox","data-testid":`${b}-enabled`,checked:C,onChange:E=>_(E.target.checked)}),i.jsx("span",{style:{fontSize:12,color:"#0f172a"},children:o(x)})]}),i.jsx("input",{type:"range","data-testid":`${b}-range`,min:0,max:Math.max(0,s.length-1),step:1,disabled:!C||s.length===0,value:k<0?0:k,onChange:E=>w(Number(E.target.value)),style:{flex:1}}),i.jsx("span",{"data-testid":`${b}-value`,style:{fontSize:12,color:C?"#0f172a":"#94a3b8",minWidth:28,textAlign:"right"},children:C?s[k]:"–"})]},b)};return i.jsxs("div",{className:"g7le-widget g7le-widget--spacing","data-testid":"g7le-widget-spacing",style:LD,children:[i.jsxs("div",{style:PD,children:[i.jsxs("div",{style:OD,"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:{...Tg,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 b={};for(const x of a)b[x.key]=l.all;g(b)}},style:{...Tg,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(b=>v(`g7le-spacing-side-${b.key}`,b.labelKey,l.sides[b.key]??-1,x=>{const k=h();k[b.key]=x,g(k)},x=>{const k=h();x?k[b.key]=l.sides[b.key]>=0?l.sides[b.key]:y:delete k[b.key],g(k)}))}):i.jsxs("div",{style:Dg,children:[i.jsxs("label",{style:{...Ra,minWidth:64},children:[i.jsx("input",{type:"checkbox","data-testid":"g7le-spacing-all-enabled",checked:l.all>=0,onChange:b=>m(b.target.checked?y:-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:b=>m(Number(b.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 LD={display:"flex",flexDirection:"column",gap:6,width:"100%"},PD={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},OD={display:"inline-flex",gap:0,border:"1px solid #cbd5e1",borderRadius:6,overflow:"hidden"},Tg={padding:"3px 10px",fontSize:11,border:"none",borderRight:"1px solid #e2e8f0",cursor:"pointer"},BD={display:"flex",alignItems:"center",gap:8,width:"100%"},WD={display:"inline-flex",gap:0,border:"1px solid #cbd5e1",borderRadius:6,overflow:"hidden"},jD={display:"flex",flexDirection:"column",gap:6,width:"100%"},HD={display:"flex",gap:6,alignItems:"center"},FD={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,minWidth:80},KD={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer",whiteSpace:"nowrap"},VD={display:"flex",flexWrap:"wrap",gap:4},UD={fontSize:11,color:"#94a3b8",fontStyle:"italic",padding:"2px 0"},qD={padding:"3px 9px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:999,background:"#fff",cursor:"pointer"},GD={padding:"4px 10px",fontSize:12,border:"none",borderRight:"1px solid #e2e8f0",cursor:"pointer"},Dg={display:"flex",alignItems:"center",gap:8,width:"100%"},Ra={display:"inline-flex",alignItems:"center",gap:4},YD={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",minWidth:120},XD={position:"relative",width:38,height:20,borderRadius:10,border:"none",cursor:"pointer",padding:2,display:"inline-flex",alignItems:"center",transition:"background 120ms ease"},JD={display:"block",width:16,height:16,borderRadius:8,background:"#fff",transition:"transform 120ms ease"},ZD=["#0f172a","#334155","#64748b","#94a3b8","#e2e8f0","#ffffff","#dc2626","#ea580c","#d97706","#16a34a","#0891b2","#2563eb","#7c3aed","#db2777"],Ng=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function QD(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 RD({control:e,value:t,onChange:n,t:o,freeValueDisabled:r}){const s=QD(e),a=s.length>0,l=typeof t=="string"&&s.some(g=>g.value===t)?t:"",d=typeof t=="string"&&Ng.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}`;Ng.test(h)&&n(h)},y=ZD;return i.jsxs("div",{className:"g7le-widget g7le-widget--color","data-testid":"g7le-widget-color",style:eN,children:[r?i.jsx("div",{"data-testid":"g7le-color-free-disabled",style:sN,children:o("layout_editor.property_modal.dark_preset_only")}):i.jsxs("div",{style:tN,children:[i.jsxs("label",{style:nN,children:[i.jsx("span",{"data-testid":"g7le-color-swatch",style:{...oN,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:rN}),i.jsx("button",{type:"button","data-testid":"g7le-color-clear",onClick:()=>n(void 0),style:iN,children:o("layout_editor.control.default")})]}),a?i.jsx("div",{style:zg,"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:{...Mg,background:g.swatch||"#e2e8f0",outline:m?"2px solid #2563eb":"none"}},g.value)})}):!r&&i.jsx("div",{style:zg,"data-testid":"g7le-color-presets",children:y.map(g=>i.jsx("button",{type:"button","aria-label":g,"data-testid":`g7le-color-preset-${g}`,onClick:()=>n(g),style:{...Mg,background:g,outline:d.toLowerCase()===g.toLowerCase()?"2px solid #2563eb":"none"}},g))})]})}const eN={display:"flex",flexDirection:"column",gap:8},tN={display:"flex",alignItems:"center",gap:6},nN={position:"relative",display:"inline-flex",cursor:"pointer"},oN={width:24,height:24,borderRadius:4,border:"1px solid #cbd5e1",display:"inline-block"},rN={flex:1,padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,fontFamily:"monospace"},iN={padding:"4px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",cursor:"pointer",color:"#64748b"},zg={display:"grid",gridTemplateColumns:"repeat(7, 1fr)",gap:4},Mg={width:"100%",height:18,borderRadius:4,border:"1px solid #cbd5e1",cursor:"pointer",padding:0},sN={fontSize:11,color:"#94a3b8",fontStyle:"italic",padding:"2px 0"},Qo=[{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 aN(e){return e&&typeof e=="object"&&!Array.isArray(e)?e:{}}function Lg(e){return Qo.find(n=>n.size===e.size&&n.repeat===e.repeat)?.value??"fill"}function lN({value:e,onChange:t,t:n}){const o=aN(e),{state:r}=Je(),s=yo(),[a,l]=u.useState(!1),[d,c]=u.useState(null),[p,f]=u.useState(o.url??""),[y,g]=u.useState([]),m=u.useRef(null),h=r.templateIdentifier,v=r.selectedRoute?.layoutName??"";u.useEffect(()=>{f(o.url??"")},[o.url]);const b=u.useCallback(async()=>{if(!h||!v){g([]);return}const E=await Dl(h,v);E.ok&&g(E.data)},[h,v]);u.useEffect(()=>{b()},[b]);const x=E=>{if(!E){t(void 0);return}const S=Qo.find(T=>T.value===Lg(o))??Qo[0];t({url:E,size:o.size??S.size,repeat:o.repeat??S.repeat,position:o.position??"center"})},k=E=>{const S=Qo.find(T=>T.value===E);!S||!o.url||t({url:o.url,size:S.size,repeat:S.repeat,position:o.position??"center"})},w=async E=>{const S=E.target.files?.[0];if(!S)return;l(!0),c(null);const T=await Nl(h,v,S);T.ok?(x(T.data.url),b()):c(n("layout_editor.control.background_image.upload_failed")),l(!1),m.current&&(m.current.value="")},_=async E=>{(await zl(E.id)).ok&&g(T=>T.filter($=>$.id!==E.id))},C=()=>{const E=s.open({ariaLabel:n("layout_editor.attachment_manager.title"),width:720,maxHeightRatio:.82,content:u.createElement(Ml,{templateIdentifier:h,layoutName:v,t:n,onSelect:S=>{x(S),s.close(E)},onChanged:()=>{b()},onClose:()=>s.close(E)})})};return i.jsxs("div",{className:"g7le-widget g7le-widget--image","data-testid":"g7le-widget-image",style:dN,children:[o.url&&i.jsx("div",{"data-testid":"g7le-image-preview",style:{...cN,backgroundImage:`url(${o.url})`,backgroundSize:o.size??"cover",backgroundRepeat:o.repeat??"no-repeat",backgroundPosition:o.position??"center"}}),i.jsxs("div",{style:uN,children:[i.jsxs("label",{style:pN,children:[a?"…":n("layout_editor.control.background_image.upload"),i.jsx("input",{ref:m,type:"file",accept:"image/*","data-testid":"g7le-image-file",onChange:w,disabled:a,style:{display:"none"}})]}),i.jsx("button",{type:"button","data-testid":"g7le-image-clear",onClick:()=>t(void 0),style:fN,children:n("layout_editor.control.background_image.clear")})]}),i.jsx("input",{type:"text","data-testid":"g7le-image-url",placeholder:"https://… / URL",value:p,onChange:E=>f(E.target.value),onBlur:E=>x(E.target.value.trim()||void 0),style:gN}),i.jsx("div",{style:hN,"data-testid":"g7le-image-modes",children:Qo.map(E=>{const S=Lg(o)===E.value;return i.jsx("button",{type:"button","data-testid":`g7le-image-mode-${E.value}`,"data-active":S?"true":"false",disabled:!o.url,onClick:()=>k(E.value),style:{...yN,background:S&&o.url?"#2563eb":"#fff",color:S&&o.url?"#fff":"#0f172a"},children:n(E.labelKey)},E.value)})}),i.jsxs("div",{style:bN,"data-testid":"g7le-image-gallery",children:[i.jsxs("div",{style:mN,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:C,style:vN,children:["🖼 ",n("layout_editor.attachment_manager.manage_link")]})]}),y.length>0?i.jsx("div",{style:_N,"data-testid":"g7le-image-thumbs",children:y.slice(0,8).map(E=>i.jsxs("div",{style:xN,"data-testid":`g7le-image-thumb-${E.id}`,children:[i.jsx("button",{type:"button",title:E.original_name,onClick:()=>x(E.url),style:{...wN,backgroundImage:`url(${E.url})`},"data-testid":`g7le-image-thumb-use-${E.id}`}),i.jsx("button",{type:"button",title:n("layout_editor.attachment_manager.delete"),onClick:()=>_(E),style:kN,"data-testid":`g7le-image-thumb-del-${E.id}`,children:"✕"})]},E.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 dN={display:"flex",flexDirection:"column",gap:6},cN={width:"100%",height:80,borderRadius:6,border:"1px solid #cbd5e1"},uN={display:"flex",gap:6},pN={padding:"5px 10px",fontSize:12,border:"1px solid #2563eb",borderRadius:6,background:"#fff",color:"#2563eb",cursor:"pointer",display:"inline-flex",alignItems:"center"},fN={padding:"5px 10px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#64748b",cursor:"pointer"},gN={padding:"5px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},hN={display:"inline-flex",border:"1px solid #cbd5e1",borderRadius:6,overflow:"hidden"},yN={padding:"4px 10px",fontSize:12,border:"none",borderRight:"1px solid #e2e8f0",cursor:"pointer"},bN={display:"flex",flexDirection:"column",gap:4,border:"1px solid #e2e8f0",borderRadius:6,padding:6,marginTop:2},mN={display:"flex",alignItems:"center",justifyContent:"space-between"},vN={fontSize:11,color:"#2563eb",background:"transparent",border:"none",cursor:"pointer",padding:0},_N={display:"flex",gap:6,flexWrap:"wrap"},xN={position:"relative",width:44,height:44},wN={width:44,height:44,borderRadius:6,border:"1px solid #cbd5e1",backgroundSize:"cover",backgroundPosition:"center",cursor:"pointer",padding:0},kN={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 SN(e){return Array.isArray(e)&&e.every(t=>t!==null&&typeof t=="object"&&!Array.isArray(t))}function CN(e){return typeof e=="string"&&/\{\{.*\}\}/.test(e)}function $N({value:e,onChange:t,t:n,bindingCandidates:o}){if(CN(e))return i.jsx("div",{className:"g7le-widget g7le-widget--options-list","data-testid":"g7le-widget-options-list-bound",style:MN,children:n("layout_editor.list_editor.bound_degraded")});const r=SN(e)?e:[],s=y=>{t(y.length===0?void 0:y)},a=(y,g)=>{const m=r.map((h,v)=>v===y?{...h,...g}:h);s(m)},l=y=>{s(r.filter((g,m)=>m!==y))},d=(y,g)=>{const m=y+g;if(m<0||m>=r.length)return;const h=[...r];[h[y],h[m]]=[h[m],h[y]],s(h)},c=()=>{s([...r,{value:"",label:""}])},p=y=>typeof y.label=="string"?y.label:y.label==null?"":String(y.label),f=y=>y.value===void 0||y.value===null?"":String(y.value);return i.jsxs("div",{className:"g7le-widget g7le-widget--options-list","data-testid":"g7le-widget-options-list",style:EN,children:[r.length===0&&i.jsx("div",{"data-testid":"g7le-options-empty",style:zN,children:n("layout_editor.list_editor.empty")}),r.map((y,g)=>i.jsxs("div",{"data-testid":`g7le-options-row-${g}`,style:IN,children:[i.jsxs("div",{style:Pg,children:[i.jsx("span",{style:Og,children:n("layout_editor.list_editor.option_value")}),i.jsx("input",{type:"text","data-testid":`g7le-options-value-${g}`,value:f(y),placeholder:n("layout_editor.list_editor.option_value"),onChange:m=>a(g,{value:m.target.value}),style:TN})]}),i.jsxs("div",{style:Pg,children:[i.jsx("span",{style:Og,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(vt,{value:p(y),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:AN,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:Bg,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:Bg,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-options-remove-${g}`,title:n("layout_editor.list_editor.remove"),onClick:()=>l(g),style:DN,children:"✕"})]})]},g)),i.jsx("button",{type:"button","data-testid":"g7le-options-add",onClick:c,style:NN,children:n("layout_editor.list_editor.add")})]})}const EN={display:"flex",flexDirection:"column",gap:8,width:"100%"},IN={display:"flex",flexDirection:"column",gap:4,width:"100%",minWidth:0,paddingBottom:6,borderBottom:"1px solid #f1f5f9"},Pg={display:"flex",gap:6,alignItems:"center",width:"100%",minWidth:0},Og={flexShrink:0,width:36,fontSize:11,color:"#94a3b8",textAlign:"right"},AN={display:"flex",gap:4,alignItems:"center",justifyContent:"flex-end"},TN={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},Bg={padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},DN={padding:"2px 6px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},NN={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},zN={fontSize:11,color:"#94a3b8",fontStyle:"italic"},MN={fontSize:11,color:"#b45309",fontStyle:"italic",padding:"4px 2px"},Wg=/[^A-Za-z0-9\-_:.]/g;function LN(e){return typeof e=="string"&&Ui(e)}function jg(e){return Ui(e)?In(e).map(t=>t.kind==="binding"?t.raw:t.raw.replace(Wg,"")).join(""):e.replace(Wg,"")}const PN={width:"100%",padding:"6px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:4,fontFamily:"monospace"},ON={marginTop:4,fontSize:11,color:"#94a3b8"},BN={display:"flex",gap:6,alignItems:"center"},WN={flexShrink:0,padding:"5px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:4,background:"#f8fafc",cursor:"pointer",whiteSpace:"nowrap"};function jN({value:e,onChange:t,t:n,bindingCandidates:o}){const r=e==null?"":String(e),s=LN(e),a=!!o&&o.length>0,[l,d]=u.useState(!1),c=p=>{const f=jg(p);t(f===""?void 0:f)};return s||l?i.jsxs("div",{"data-testid":"g7le-core-id-chip",children:[i.jsx(bs,{value:r,onChange:c,t:n,candidates:o,onDone:()=>d(!1),testidPrefix:"g7le-core-id-chip-input"}),i.jsx("div",{style:ON,children:n("layout_editor.core_props.id.binding_hint")})]}):i.jsx("div",{children:i.jsxs("div",{style:BN,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=jg(p.target.value);t(f===""?void 0:f)},spellCheck:!1,autoComplete:"off",style:PN}),a&&i.jsxs("button",{type:"button","data-testid":"g7le-core-id-add-data",onClick:()=>d(!0),style:WN,title:n("layout_editor.core_props.id.add_data"),children:["🔗 ",n("layout_editor.core_props.id.add_data")]})]})})}const HN=/[^A-Za-z0-9.\-_]/g;function FN(e){return typeof e=="string"&&/\{\{[\s\S]*?\}\}/.test(e)}function KN(e){return e.replace(HN,"")}const Hg={width:"100%",padding:"6px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:4,fontFamily:"monospace",boxSizing:"border-box"},VN={...Hg,background:"#f1f5f9",color:"#64748b",cursor:"not-allowed"},Fg={marginTop:4,fontSize:11,color:"#94a3b8"};function UN({value:e,onChange:t,t:n}){const o=e==null?"":String(e);return FN(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:VN}),i.jsx("div",{style:Fg,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=KN(s.target.value);t(a===""?void 0:a)},spellCheck:!1,autoComplete:"off",style:Hg}),i.jsx("div",{style:Fg,children:n("layout_editor.core_props.dataKey.hint")})]})}let Kg=!1;function qN(){Kg||(Xe("segmented",ED),Xe("slider",ID),Xe("select",AD),Xe("dimension",DD),Xe("spacing",MD),Xe("toggle",TD),Xe("color",RD),Xe("image",lN),Xe("tag-input",ys),Xe("page-picker",Aw),Xe("datasource-picker",Bc),Xe("binding-picker",Bc),Xe("binding-list",Nw),Xe("state-key-picker",Es),Xe("modal-picker",Tw),Xe("i18n-text",Dw),Xe("text",zw),Xe("options-list",$N),Xe("core-id",jN),Xe("core-datakey",UN),Xe("component-target-picker",jT),Kg=!0)}function Ro(e){return Array.isArray(e.children)?e.children:[]}function er(e){if(typeof e.text=="string")return[];let t=null;const n=(o,r)=>{const s=Ro(o);for(let a=0;ad===o?tr(l,r,n):l);return{...e,children:a}}function Vg(e,t){const n=r=>typeof r.props?.[t]=="string";if(n(e))return[];const o=(r,s)=>{const a=Ro(r);for(let l=0;lc===r?Ug(d,s,n,o):d);return{...e,children:l}}function GN(e){return Array.isArray(e.children)?e.children:[]}function YN(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 el(e,t){if(!(typeof e!="string"||e.length===0))return e.startsWith("$t:")?t(e.slice(3)):e}function qg({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=YN(t),f=el(typeof t?.childLabel=="string"?t.childLabel:void 0,r)??d??"",y=GN(e),g=u.useCallback(_=>{s({...e,children:_})},[e,s]),m=u.useCallback(()=>{if(c)return JSON.parse(JSON.stringify(c));if(!d)return null;const _=n?.componentPalette?.entries?.[d];if(_?.defaultNode&&typeof _.defaultNode=="object")return JSON.parse(JSON.stringify(_.defaultNode));const C=o?.components??{};let E=null;for(const S of Object.values(C))if(Array.isArray(S)){const T=S.find($=>$.name===d);if(T){E=T;break}}return E?$f(E):{type:"basic",name:d}},[c,d,n,o]),h=u.useCallback(()=>{const _=m();if(_){if(_.text==="")_.text=r("layout_editor.list_editor.new_item");else{const C=er(_);if(C!==null&&C.length>0){const E=_i(_,C);if(E&&E.text===""){const S=tr(_,C,r("layout_editor.list_editor.new_item"));g([...y,S]);return}}}g([...y,_])}},[m,g,y,r]),v=u.useCallback(_=>{g(y.filter((C,E)=>E!==_))},[g,y]),b=u.useCallback((_,C)=>{const E=_+C;if(E<0||E>=y.length)return;const S=[...y];[S[_],S[E]]=[S[E],S[_]],g(S)},[g,y]),x=u.useCallback((_,C)=>{if(typeof C!="string"||C.length===0)return;const E=y[_];if(!E)return;const S=er(E);if(S===null)return;const T=y.map(($,A)=>A===_?tr($,S,C):$);g(T)},[y,g]),k=u.useCallback((_,C,E)=>{if(typeof E!="string"||E.length===0)return;const S=y[_];if(!S)return;const T=Vg(S,C);if(T===null)return;const $=y.map((A,z)=>z===_?Ug(A,T,C,E):A);g($)},[y,g]);if(!d&&!c)return i.jsx("div",{className:"g7le-node-editor g7le-node-editor--children","data-testid":"g7le-children-editor-misconfigured",style:Xg,children:r("layout_editor.list_editor.no_child_component")});const w=p.length>1||p.some(_=>_.label);return i.jsxs("div",{className:"g7le-node-editor g7le-node-editor--children","data-testid":"g7le-children-editor",style:XN,children:[i.jsx("div",{style:JN,children:r("layout_editor.list_editor.items_title")}),y.length===0&&i.jsx("div",{"data-testid":"g7le-children-empty",style:Xg,children:r("layout_editor.list_editor.empty")}),y.map((_,C)=>{const E=[];for(const T of p)if(T.kind==="text"){const $=er(_),A=$!==null?_i(_,$):null;A&&typeof A.text=="string"&&E.push({key:"text",caption:el(T.label,r)??(w?r("layout_editor.list_editor.item_label"):void 0),value:A.text,onChange:z=>x(C,z),testid:`g7le-children-i18n-${C}`})}else if(T.kind==="prop"&&T.prop){const $=Vg(_,T.prop);if($!==null){const z=_i(_,$)?.props?.[T.prop];E.push({key:`prop-${T.prop}`,caption:el(T.label,r)??T.prop,value:typeof z=="string"?z:"",onChange:D=>k(C,T.prop,D),testid:`g7le-children-prop-${T.prop}-${C}`})}}const S=typeof _?.name=="string"?_.name:r("layout_editor.list_editor.item");return i.jsxs("div",{"data-testid":`g7le-children-row-${C}`,style:ZN,children:[E.length>0?E.map(T=>i.jsx("div",{style:Gg,children:i.jsxs("div",{"data-testid":T.key==="text"?`g7le-children-text-${C}`:`g7le-children-field-${T.key}-${C}`,style:QN,children:[T.caption!==void 0&&i.jsx("div",{"data-testid":`g7le-children-caption-${T.key}-${C}`,style:RN,children:T.caption}),i.jsx(vt,{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:Gg,children:i.jsx("span",{"data-testid":`g7le-children-label-${C}`,style:t8,children:S})}),i.jsxs("div",{style:e8,children:[i.jsx("button",{type:"button","data-testid":`g7le-children-up-${C}`,title:r("layout_editor.list_editor.move_up"),disabled:C===0,onClick:()=>b(C,-1),style:Yg,children:"↑"}),i.jsx("button",{type:"button","data-testid":`g7le-children-down-${C}`,title:r("layout_editor.list_editor.move_down"),disabled:C===y.length-1,onClick:()=>b(C,1),style:Yg,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-children-remove-${C}`,title:r("layout_editor.list_editor.remove"),onClick:()=>v(C),style:n8,children:"✕"})]})]},C)}),i.jsx("button",{type:"button","data-testid":"g7le-children-add",onClick:h,style:o8,children:r("layout_editor.list_editor.add_child",{component:f})})]})}const XN={display:"flex",flexDirection:"column",gap:6,width:"100%",marginBottom:12},JN={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:2},ZN={display:"flex",flexDirection:"column",gap:4,width:"100%",minWidth:0,paddingBottom:6,borderBottom:"1px solid #f1f5f9"},Gg={display:"flex",gap:4,alignItems:"flex-start",width:"100%",minWidth:0},QN={flex:1,minWidth:0},RN={fontSize:11,color:"#64748b",marginBottom:2},e8={display:"flex",gap:4,alignItems:"center",justifyContent:"flex-end"},t8={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,color:"#475569",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},Yg={padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},n8={padding:"2px 6px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},o8={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},Xg={fontSize:11,color:"#94a3b8",fontStyle:"italic"},fo={rowContainer:"Tbody",row:"Tr",cell:"Td",headerCell:"Th",colSpanProp:"colSpan",rowSpanProp:"rowSpan"};function ht(e){return{rowContainer:e?.rowContainer??fo.rowContainer,row:e?.row??fo.row,cell:e?.cell??fo.cell,headerCell:e?.headerCell??fo.headerCell,colSpanProp:e?.colSpanProp??fo.colSpanProp,rowSpanProp:e?.rowSpanProp??fo.rowSpanProp}}function Bn(e){return e?Array.isArray(e.children)?e.children:[]:[]}function Jg(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 Be(e,t){const n=ht(t),o=[],r=Bn(e),s=[];r.forEach((f,y)=>{(Bn(f).some(h=>h.name===n.row)||f.name===n.rowContainer||f.name==="Thead"||f.name==="Tfoot")&&s.push({container:f,containerIndex:y,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,y)=>{Bn(f.container).filter(m=>m.name===n.row).forEach((m,h)=>{const v=[],b=p(d);let x=0;Bn(m).filter(w=>w.name===n.cell||w.name===n.headerCell).forEach((w,_)=>{for(;b[x];)x++;const C=Jg(w,n.colSpanProp),E=Jg(w,n.rowSpanProp),S={cell:w,sectionIndex:y,rowIndexInSection:h,cellIndexInRow:_,gridRow:d,gridCol:x,colSpan:C,rowSpan:E,isHeader:w.name===n.headerCell};v.push(S);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 wi(e,t,n){const o=Zg(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 ki(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 nr(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 yt(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 Si(e,t,n){let o=-1;const r=Ge(e);for(let s=0;s0?nt(e,r,r.sections.length-1,x=>({...x,children:[...Ge(x),b]})):{...e,children:[...Ge(e),b]}}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=[],y=[];let g=0;for(;g0?Ue(r,d-1,g):null;b&&b.gridRow+b.rowSpan>d&&b.rowSpan>1?(y.push(b),g+=b.colSpan):(f.push(ki(o)),g+=1)}let m=e;for(const b of y)m=nt(m,r,b.sectionIndex,x=>yt(x,o.row,b.rowIndexInSection,k=>({...k,children:Ge(k).map((w,_)=>_===b.cellIndexInRow?mn(w,o.rowSpanProp,b.rowSpan+1):w)})));const h={type:"basic",name:o.row,children:f},v=Be(m,t);return m=nt(m,v,c,b=>{const x=Ge(b);let k=0,w=x.length;for(let _=0;_=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;pyt(y,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=Be(l,t);return l=nt(l,c,s.sectionIndex,p=>{let f=-1;const y=Ge(p).filter(g=>g.name===o.row?(f++,f!==s.rowIndexInSection):!0);return{...p,children:y}}),l}function eh(e,t,n,o){const r=ht(t),s=Be(e,t);if(!xi(s,n,o).ok)return e;const a=Qg(s),l=a.findIndex(h=>n>=h.start&&ns.rows.filter(v=>{const b=v.cells[0]?.gridRow??-1;return v.sectionIndex===f&&b>=h.start&&bv.rowIndexInSection),g=y(c),m=y(p);return g.length===0||m.length===0?e:nt(e,s,f,h=>{const v=[...Ge(h)],b=[];v.forEach((M,B)=>{M.name===r.row&&b.push(B)});const x=g.map(M=>b[M]).filter(M=>M!==void 0),k=m.map(M=>b[M]).filter(M=>M!==void 0);if(x.length===0||k.length===0)return h;const w=x.map(M=>v[M]),_=k.map(M=>v[M]),C=Math.min(...x)n>=m.start&&nw.gridCol>=f.start&&w.gridColw.gridCol>=y.start&&w.gridColw.cellIndexInRow),x=v.map(w=>w.cellIndexInRow),k=Be(g,t);g=nt(g,k,m.sectionIndex,w=>yt(w,r.row,m.rowIndexInSection,_=>{const C=[...Ge(_)],E=b.map(M=>Si(_,r,M)).filter(M=>M>=0),S=x.map(M=>Si(_,r,M)).filter(M=>M>=0);if(E.length===0||S.length===0)return _;const T=E.map(M=>C[M]),$=S.map(M=>C[M]),A=Math.min(...E,...S),z=Math.max(...E,...S),D=[...$,...T],O=[...C.slice(0,A),...D,...C.slice(z+1)];return{..._,children:O}}))}return g}function nh(e,t,n){const o=ht(t),r=Be(e,t);if(r.rows.length===0||r.colCount===0)return nl(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?Ue(r,c,s-1):null,f=s1){if(!l.has(p.cell)){l.add(p.cell);const h=Be(a,t);a=nt(a,h,p.sectionIndex,v=>yt(v,o.row,p.rowIndexInSection,b=>({...b,children:Ge(b).map((x,k)=>k===p.cellIndexInRow?mn(x,o.colSpanProp,p.colSpan+1):x)})))}continue}if(p&&p.gridRow0&&d.cells.every(h=>h.isHeader),m=Be(a,t);a=nt(a,m,d.sectionIndex,h=>yt(h,o.row,d.rowIndexInSection,v=>{const b=[...Ge(v)];let x;if(y<0)x=b.findIndex(k=>nr(k,o)),x<0&&(x=b.length);else{const k=Si(v,o,y);x=k<0?b.length:k+1}return b.splice(x,0,ki(o,void 0,g)),{...v,children:b}}))}return a}function oh(e,t,n){const o=ht(t),r=Be(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=Ue(r,d,n);if(!(!c||a.has(c.cell)||c.gridRow1){const p=Be(s,t);s=nt(s,p,c.sectionIndex,f=>yt(f,o.row,c.rowIndexInSection,y=>({...y,children:Ge(y).map((g,m)=>m===c.cellIndexInRow?mn(g,o.colSpanProp,c.colSpan-1):g)})))}else{const p=Be(s,t);s=nt(s,p,c.sectionIndex,f=>yt(f,o.row,c.rowIndexInSection,y=>{let g=-1;const m=Ge(y).filter(h=>nr(h,o)?(g++,g!==c.cellIndexInRow):!0);return{...y,children:m}}))}}return s}function ol(e,t,n,o,r,s){const a=ht(t),l=Be(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 y=new Set;for(let b=d;b<=c;b++)for(let x=p;x<=f;x++){const k=Ue(l,b,x);if(!k)return{table:e,ok:!1,reason:"hole"};if(k.gridRowc||k.gridCol+k.colSpan-1>f)return{table:e,ok:!1,reason:"not-rectangular"};y.add(k)}const g=Ue(l,d,p),m=Array.from(y).filter(b=>b!==g);let h=nt(e,l,g.sectionIndex,b=>yt(b,a.row,g.rowIndexInSection,x=>({...x,children:Ge(x).map((k,w)=>{if(w!==g.cellIndexInRow)return k;let _=mn(k,a.colSpanProp,f-p+1);return _=mn(_,a.rowSpanProp,c-d+1),_})})));const v=new Map;for(const b of m){const x=`${b.sectionIndex}:${b.rowIndexInSection}`,k=v.get(x)??[];k.push(b),v.set(x,k)}for(const[b,x]of v){const k=parseInt(b.split(":")[0],10),w=x[0].rowIndexInSection,_=new Set(x.map(E=>E.cellIndexInRow)),C=Be(h,t);h=nt(h,C,k,E=>yt(E,a.row,w,S=>{let T=-1;const $=Ge(S).filter(A=>nr(A,a)?(T++,!_.has(T)):!0);return{...S,children:$}}))}return{table:h,ok:!0}}function rh(e,t,n,o){const r=ht(t),s=Be(e,t),a=Ue(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,y=typeof a.cell.props?.className=="string"?a.cell.props.className:void 0;let g=nt(e,s,a.sectionIndex,m=>yt(m,r.row,a.rowIndexInSection,h=>({...h,children:Ge(h).map((v,b)=>{if(b!==a.cellIndexInRow)return v;let x=mn(v,r.colSpanProp,1);return x=mn(x,r.rowSpanProp,1),x})})));for(let m=l;m<=c;m++)for(let h=d;h<=p;h++){if(m===l&&h===d)continue;const v=Be(g,t),b=v.rows.find(w=>w.cells.some(_=>_.gridRow===m))??v.rows[m];if(!b)continue;let x=-1;for(const w of b.cells)w.gridRow===m&&w.gridColyt(w,r.row,b.rowIndexInSection,_=>{const C=[...Ge(_)];let E;if(x<0)E=C.findIndex(S=>nr(S,r)),E<0&&(E=C.length);else{const S=Si(_,r,x);E=S<0?C.length:S+1}return C.splice(E,0,ki(r,k,f)),{..._,children:C}}))}return g}function Ci(e,t,n,o,r){const s=ht(t),a=Be(e,t),l=Ue(a,n,o);return l?nt(e,a,l.sectionIndex,d=>yt(d,s.row,l.rowIndexInSection,c=>({...c,children:Ge(c).map((p,f)=>{if(f!==l.cellIndexInRow)return p;const y={...p.props??{}};r.trim()===""?delete y.className:y.className=r;const g={...p,props:y};return Object.keys(y).length===0&&delete g.props,g})}))):e}function Jt(e,t,n,o,r,s){const a=ht(t),l=Be(e,t),d=Ue(l,n,o);return d?nt(e,l,d.sectionIndex,c=>yt(c,a.row,d.rowIndexInSection,p=>({...p,children:Ge(p).map((f,y)=>{if(y!==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 go(e,t,n,o,r,s,a){const l=ht(t),d=Be(e,t),c=Ue(d,n,o);if(!c)return e;const p=a==="dark";return nt(e,d,c.sectionIndex,f=>yt(f,l.row,c.rowIndexInSection,y=>({...y,children:Ge(y).map((g,m)=>{if(m!==c.cellIndexInRow)return g;const h={...g.props??{}},v=typeof h.className=="string"?h.className:"",b=uC(v,s,r,p);b===""?delete h.className:h.className=b;const x={...g,props:h};return Object.keys(h).length===0&&delete x.props,x})})))}function ih(e,t,n,o,r){const s=ht(t),a=Be(e,t),l=Ue(a,n,o);return l?nt(e,a,l.sectionIndex,d=>yt(d,s.row,l.rowIndexInSection,c=>({...c,children:Ge(c).map((p,f)=>f===l.cellIndexInRow?{...p,text:r}:p)}))):e}function sh(e,t,n,o,r){const s=ht(t),a=Be(e,t),l=Ue(a,n,o);return l?nt(e,a,l.sectionIndex,d=>yt(d,s.row,l.rowIndexInSection,c=>({...c,children:Ge(c).map((p,f)=>f===l.cellIndexInRow?r:p)}))):e}const ah=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function r8(e){return e.split(/\s+/).filter(Boolean)}function lh(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 dh({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??[],y=r==="dark",g=u.useMemo(()=>c.map($=>$.prefix),[c]),m=u.useMemo(()=>new Set(f.map($=>$.token)),[f]),h=u.useMemo(()=>r8(e),[e]),v=u.useMemo(()=>Vr(e,y),[e,y]),b=u.useMemo(()=>v.find($=>m.has($))??null,[v,m]),x=u.useMemo(()=>{const $=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)))&&$.add(A.value);return $},[h,c]),k=u.useMemo(()=>{const $=h.find(z=>lh(z,g));if(!$)return"none";const A=p.filter(z=>z.value!=="none");for(const z of c){if($===z.prefix)return A.find(D=>(D.suffix??"")==="")?.value??"thin";if($.startsWith(z.prefix+"-")){const D=$.slice(z.prefix.length),O=A.find(M=>(M.suffix??"")===D);if(O)return O.value}}return"thin"},[h,g,c,p]);if(!t||c.length===0||p.length===0)return null;function w($){return $.filter(A=>!lh(A,g))}function _($,A){const z=w(h),D=p.find(B=>B.value===A);if(!D||A==="none"||$.size===0)return z.join(" ").trim();const O=D.suffix??"",M=[...z];for(const B of c)$.has(B.value)&&M.push(O?`${B.prefix}${O}`:B.prefix);return M.join(" ").trim()}const C=$=>{const A=new Set(x);A.has($)?A.delete($):($==="all"?A.clear():A.delete("all"),A.add($));const z=k==="none"?p.find(D=>D.value!=="none")?.value??"thin":k;o(_(A,z))},E=$=>{const A=x.size===0?new Set(["all"]):x;o(_(A,$))},S=$=>{s?.($)},T=($,A)=>$&&$.startsWith("$t:")?n($.slice(3)):$||A;return i.jsxs("div",{className:"g7le-cell-border","data-testid":"g7le-cell-border",style:i8,children:[i.jsx("div",{style:s8,children:i.jsx("span",{style:a8,children:n("layout_editor.table_editor.cell_border")})}),i.jsx("div",{style:rl,"data-testid":"g7le-cell-border-widths",children:p.map($=>i.jsx("button",{type:"button",disabled:d,"data-testid":`g7le-cell-border-width-${$.value}`,"aria-pressed":k===$.value,onClick:()=>E($.value),style:k===$.value?ch:il,children:T($.label,$.value)},$.value))}),k!=="none"&&i.jsx("div",{style:rl,"data-testid":"g7le-cell-border-sides",children:c.map($=>i.jsx("button",{type:"button",disabled:d,"data-testid":`g7le-cell-border-side-${$.value}`,"aria-pressed":x.has($.value),onClick:()=>C($.value),style:x.has($.value)?ch:il,children:T($.label,$.value)},$.value))}),k!=="none"&&(f.length>0||l)&&i.jsx(i.Fragment,{children:i.jsxs("div",{style:rl,"data-testid":"g7le-cell-border-colors",children:[f.map($=>{const A=b===$.token;return i.jsx("button",{type:"button",disabled:d,title:T($.label,$.value),"data-testid":`g7le-cell-border-color-${$.value}`,"aria-pressed":A,onClick:()=>S($.token),style:{...uh,background:$.swatch??"#fff",outline:A?"2px solid #2563eb":"1px solid #cbd5e1"}},$.value)}),l&&(()=>{const $=!!a&&f.some(z=>z.swatch&&z.swatch.toLowerCase()===a.toLowerCase()),A=!y&&!!a&&!$;return i.jsx("label",{title:n(y?"layout_editor.table_editor.dark_free_color_hint":"layout_editor.table_inplace.custom_color"),"data-testid":"g7le-cell-border-color-custom",style:{...uh,position:"relative",overflow:"hidden",display:"inline-flex",alignItems:"center",justifyContent:"center",background:A&&ah.test(a)?a:"conic-gradient(red, yellow, lime, aqua, blue, magenta, red)",outline:A?"2px solid #2563eb":"1px solid #cbd5e1",opacity:y?.4:1,cursor:y?"not-allowed":"pointer"},children:i.jsx("input",{type:"color",disabled:d||y,"data-testid":"g7le-cell-border-color-picker",value:a&&ah.test(a)?a:"#000000",onChange:z=>l(z.target.value),style:{position:"absolute",width:0,height:0,opacity:0}})})})()]})})]})}const i8={display:"flex",flexDirection:"column",gap:6},s8={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},a8={fontSize:12,fontWeight:600,color:"#475569"},rl={display:"flex",gap:4,flexWrap:"wrap",alignItems:"center"},il={padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},ch={...il,border:"1px solid #2563eb",background:"#eff6ff",color:"#1d4ed8",fontWeight:600},uh={width:22,height:22,borderRadius:5,padding:0,cursor:"pointer",boxSizing:"border-box"},ph=/^#([0-9a-fA-F]{3}|[0-9a-fA-F]{6})$/;function fh({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??"",y=Vr(t??"",p),g=c.find(x=>x.token&&y.includes(x.token))?.token??null,m=(x,k)=>x&&x.startsWith("$t:")?o(x.slice(3)):x||k,h=!g&&(p||f.trim()===""),v=!!f&&c.some(x=>x.swatch&&x.swatch.toLowerCase()===f.toLowerCase()),b=!p&&!!f&&!v;return i.jsxs("div",{className:"g7le-cell-fill","data-testid":"g7le-cell-fill",style:l8,children:[i.jsx("div",{style:d8,children:i.jsx("span",{style:c8,children:o("layout_editor.table_editor.cell_fill")})}),i.jsxs("div",{style:u8,"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:{...sl,background:"repeating-conic-gradient(#e2e8f0 0% 25%, #ffffff 0% 50%) 50% / 10px 10px",outline:h?"2px solid #2563eb":"1px solid #cbd5e1"}}),c.map(x=>{const k=!!x.token&&g===x.token,w=!p&&!!x.swatch&&f.toLowerCase()===(x.swatch??"").toLowerCase(),_=k||w,C=d||p&&!x.token;return i.jsx("button",{type:"button",disabled:C,title:m(x.label,x.value),"data-testid":`g7le-cell-fill-color-${x.value}`,"aria-pressed":_,onClick:()=>{x.token&&s?s(x.token):!p&&x.swatch&&a&&a(x.swatch)},style:{...sl,background:x.swatch??"#fff",outline:_?"2px solid #2563eb":"1px solid #cbd5e1",opacity:C?.4:1,cursor:C?"not-allowed":"pointer"}},x.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:{...sl,position:"relative",overflow:"hidden",display:"inline-flex",alignItems:"center",justifyContent:"center",background:b&&ph.test(f)?f:"conic-gradient(red, yellow, lime, aqua, blue, magenta, red)",outline:b?"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&&ph.test(f)?f:"#ffffff",onChange:x=>a(x.target.value),style:{position:"absolute",width:0,height:0,opacity:0}})})]})]})}const l8={display:"flex",flexDirection:"column",gap:6},d8={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},c8={fontSize:12,fontWeight:600,color:"#475569"},u8={display:"flex",gap:4,flexWrap:"wrap",alignItems:"center"},sl={width:22,height:22,borderRadius:5,padding:0,cursor:"pointer",boxSizing:"border-box"};function p8(e){const t=/^(\d+)px$/.exec(e.trim());return t?parseInt(t[1],10):null}function gh({paddingStyle:e,catalog:t,t:n,onChange:o,disabled:r}){const s=t?.steps??[],a=e??"",l=p8(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,y]=u.useState(p);u.useEffect(()=>{y(p)},[e]);const g=h=>{o(h&&h>0?`${h}px`:""),y("")},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:f8,children:[i.jsx("div",{style:g8,children:n("layout_editor.table_editor.cell_padding")}),i.jsxs("div",{style:h8,"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?y8:hh,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=>y(h.target.value),onBlur:()=>f.trim()!==""&&m(f),onKeyDown:h=>{h.key==="Enter"&&f.trim()!==""&&m(f)},style:b8}),i.jsx("span",{style:{fontSize:11,color:"#94a3b8"},children:"px"})]})]})]})}const f8={display:"flex",flexDirection:"column",gap:6},g8={fontSize:12,fontWeight:600,color:"#475569"},h8={display:"flex",gap:4,flexWrap:"wrap",alignItems:"center"},hh={padding:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},y8={...hh,border:"1px solid #2563eb",background:"#eff6ff",color:"#1d4ed8",fontWeight:600},b8={width:48,padding:"3px 5px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,boxSizing:"border-box"};function yh({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:m8,children:[i.jsxs("div",{style:v8,children:[i.jsx("span",{style:_8,children:n("layout_editor.table_editor.cell_color")}),i.jsxs("div",{style:x8,children:[i.jsx("button",{type:"button",disabled:o,"data-testid":"g7le-color-scheme-light","aria-pressed":!r,onClick:()=>t("light"),style:r?al:bh,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?bh:al,children:n("layout_editor.property_modal.scope.scheme_dark")})]})]}),r&&i.jsx("div",{style:w8,"data-testid":"g7le-color-scheme-dark-hint",children:n("layout_editor.table_editor.dark_free_color_hint")})]})}const m8={display:"flex",flexDirection:"column",gap:3},v8={display:"flex",alignItems:"center",justifyContent:"space-between",gap:8},_8={fontSize:12,fontWeight:700,color:"#0f172a"},x8={display:"flex",gap:2},al={padding:"2px 9px",fontSize:11,border:"none",borderBottom:"2px solid transparent",background:"transparent",color:"#94a3b8",cursor:"pointer"},bh={...al,color:"#1d4ed8",borderBottom:"2px solid #2563eb",fontWeight:600},w8={fontSize:10,color:"#94a3b8",fontStyle:"italic"},ll="dark:";function mh(e){return typeof e=="string"?e.split(/\s+/).filter(Boolean):[]}function vh(e,t){return t==="dark"?e.filter(n=>n.startsWith(ll)).map(n=>n.slice(ll.length)):e.filter(n=>!n.startsWith(ll))}const k8={none:0,thin:1,medium:2,thick:4},_h={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"}},xh=["top","bottom","left","right"];function S8(e,t,n="light"){if(!e||!t)return{};const o=t.sides??[],r=t.widths??[],s=t.colors??[],a=mh(e.props?.className);if(a.length===0&&!e.props?.style)return{};const l=[...r].filter(b=>b.value!=="none").sort((b,x)=>(x.suffix??"").length-(b.suffix??"").length),d={};for(const b of o)for(const x of l){const k=x.suffix?`${b.prefix}${x.suffix}`:b.prefix;if(a.includes(k)){d[b.value]=x.value;break}}const c=e.props?.style??{},p=vh(a,n),f=s.find(b=>p.includes(b.token))?.swatch??"",g=(n==="light"&&typeof c.borderColor=="string"?c.borderColor:"")||f||"#94a3b8",m=b=>{const x=_h[b]?.c,k=x?c[x]:void 0;return typeof k=="string"&&k?k:g},h={},v=(b,x)=>{const k=_h[b];if(!k)return;const w=k8[x]??1;h[k.w]=`${w}px`,h[k.s]=w>0?"solid":"none",w>0&&(h[k.c]=m(b))};if(d.all)for(const b of xh)v(b,d.all);for(const b of xh)d[b]&&v(b,d[b]);return h}function C8(e,t,n="light"){if(!e?.props)return{};const o=e.props.style??{},r={},s=mh(e.props.className),a=t?.colors?.find(c=>c.token&&vh(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 $8=/^\s*\$t:(custom\.[a-zA-Z0-9._-]+)\s*$/,E8=/^\s*\$t:([a-zA-Z0-9._-]+)\s*$/,I8=/\{\{.*?\}\}/;function wh(e,t,n){const o=e?.text;if(typeof o!="string")return{display:"",editable:!1,isKey:!1};const r=mt(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(I8.test(o))return{display:o,editable:!1,isKey:!1};const s=E8.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 dl(e){const t=er(e);return t===null?{node:null,path:null}:{node:_i(e,t),path:t}}function A8(e){if(!e||typeof e.text!="string")return null;const t=$8.exec(e.text);if(t)return t[1];const n=mt(e.text);return n&&n.key.startsWith("custom.")?n.key:null}function T8({node:e,params:t,t:n,onPatchNode:o,templateIdentifier:r,candidates:s}){const{state:a}=Je(),l=a.selectedRoute?.layoutName??null,d=a.locale,c=r??a.templateIdentifier,p=u.useMemo(()=>t&&typeof t=="object"?t:null,[t]);u.useMemo(()=>ht(p),[p]);const f=u.useMemo(()=>Be(e,p),[e,p]),y=u.useMemo(()=>{const q=p?.cellBorder;return q&&typeof q=="object"?q:null},[p]),g=u.useMemo(()=>{const q=p?.cellBackground;return q&&typeof q=="object"?q:null},[p]),m=u.useMemo(()=>{const q=p?.cellPadding;return q&&typeof q=="object"?q:null},[p]),[h,v]=u.useState(null),[b,x]=u.useState(null),[k,w]=u.useState({}),[_,C]=u.useState(!1),[E,S]=u.useState(null),[T,$]=u.useState(null),[A,z]=u.useState("light"),D=u.useCallback(q=>o(q),[o]),O=u.useMemo(()=>h?Ue(f,h.r,h.c):null,[f,h]),M=T!==null?T:h?.c??null,B=E!==null?E:h?.r??null,N=u.useMemo(()=>{const q=(y?.sides??[]).find($e=>$e.value==="all")??(y?.sides??[])[0],ae=(y?.widths??[]).find($e=>$e.value!=="none");if(!q||!ae)return[];const pe=ae.suffix??"";return[pe?`${q.prefix}${pe}`:q.prefix]},[y]),H=u.useCallback((q,ae,pe)=>{if(N.length===0)return q;const $e=(y?.sides??[]).map(J=>J.prefix),be=Ue(Be(q,p),ae,pe),oe=(typeof be?.cell?.props?.className=="string"?be.cell.props.className:"").split(/\s+/).filter(Boolean);return oe.some(J=>$e.some(le=>J===le||J.startsWith(le+"-")&&/^-?\d+$/.test(J.slice(le.length+1))))?q:Ci(q,p,ae,pe,[...oe,...N].join(" ").trim())},[N,y,p]),L=u.useCallback(q=>{if(!h)return;const ae=Math.min(h.r,b?.r??h.r),pe=Math.max(h.r,b?.r??h.r),$e=Math.min(h.c,b?.c??h.c),be=Math.max(h.c,b?.c??h.c),j=new Set,oe=[];for(let J=ae;J<=pe;J++)for(let le=$e;le<=be;le++)j.add(`${J}:${le}`),oe.push({r:J,c:le});let ue=e;for(const J of oe){if(ue=H(ue,J.r,J.c),ue=Jt(ue,p,J.r,J.c,"borderColor",q),J.r>0&&!j.has(`${J.r-1}:${J.c}`)){const le=Ue(Be(ue,p),J.r-1,J.c);le&&(ue=Jt(ue,p,le.gridRow,le.gridCol,"borderBottomColor",q))}if(J.c>0&&!j.has(`${J.r}:${J.c-1}`)){const le=Ue(Be(ue,p),J.r,J.c-1);le&&(ue=Jt(ue,p,le.gridRow,le.gridCol,"borderRightColor",q))}}D(ue)},[h,b,e,p,D,H]),I=u.useCallback(q=>L(q),[L]),P=u.useMemo(()=>(y?.colors??[]).map(q=>q.token).filter(Boolean),[y]),F=u.useCallback(q=>{if(!h||P.length===0)return;const ae=Math.min(h.r,b?.r??h.r),pe=Math.max(h.r,b?.r??h.r),$e=Math.min(h.c,b?.c??h.c),be=Math.max(h.c,b?.c??h.c);let j=e;for(let oe=ae;oe<=pe;oe++)for(let ue=$e;ue<=be;ue++)j=H(j,oe,ue),j=go(j,p,oe,ue,q,P,A);D(j)},[h,b,e,p,D,H,P,A]),G=u.useMemo(()=>{if(A==="dark")return"";const q=O?.cell.props?.style;return typeof q?.borderColor=="string"?q.borderColor:""},[O,A]),V=u.useCallback((q,ae)=>{if(!h)return;const pe=Math.min(h.r,b?.r??h.r),$e=Math.max(h.r,b?.r??h.r),be=Math.min(h.c,b?.c??h.c),j=Math.max(h.c,b?.c??h.c);let oe=e;for(let ue=pe;ue<=$e;ue++)for(let J=be;J<=j;J++)oe=Jt(oe,p,ue,J,q,ae);D(oe)},[h,b,e,p,D]),Y=u.useMemo(()=>(g?.colors??[]).map(q=>q.token).filter(q=>!!q),[g]),Z=u.useCallback(()=>h?{r0:Math.min(h.r,b?.r??h.r),r1:Math.max(h.r,b?.r??h.r),c0:Math.min(h.c,b?.c??h.c),c1:Math.max(h.c,b?.c??h.c)}:null,[h,b]),se=u.useCallback(q=>{const ae=Z();if(!ae||Y.length===0)return;let pe=e;for(let $e=ae.r0;$e<=ae.r1;$e++)for(let be=ae.c0;be<=ae.c1;be++)pe=go(pe,p,$e,be,q,Y,A);D(pe)},[Z,e,p,D,Y,A]),re=u.useCallback(q=>V("backgroundColor",q),[V]),U=u.useCallback(()=>{const q=Z();if(!q)return;let ae=e;for(let pe=q.r0;pe<=q.r1;pe++)for(let $e=q.c0;$e<=q.c1;$e++)ae=go(ae,p,pe,$e,void 0,Y,A),A==="light"&&(ae=Jt(ae,p,pe,$e,"backgroundColor",void 0));D(ae)},[Z,e,p,D,Y,A]),ee=u.useCallback(q=>V("padding",q),[V]),fe=u.useMemo(()=>{if(A==="dark")return"";const q=O?.cell.props?.style;return typeof q?.backgroundColor=="string"?q.backgroundColor:""},[O,A]),K=u.useMemo(()=>typeof O?.cell.props?.className=="string"?O.cell.props.className:"",[O]),ne=u.useMemo(()=>{const q=O?.cell.props?.style;return typeof q?.padding=="string"?q.padding:""},[O]),me=u.useCallback(q=>q==="section"?n("layout_editor.table_editor.move_blocked_section"):"",[n]),Ce=u.useCallback((q,ae)=>xi(f,q,ae),[f]),ze=u.useCallback((q,ae)=>wi(f,q,ae),[f]),Se=u.useCallback(q=>D(nl(e,p,q)),[e,p,D]),qe=u.useCallback(q=>{D(Rg(e,p,q)),v(null),x(null)},[e,p,D]),De=u.useCallback((q,ae)=>D(eh(e,p,q,ae)),[e,p,D]),Pe=u.useCallback(q=>D(nh(e,p,q)),[e,p,D]),Qe=u.useCallback(q=>{D(oh(e,p,q)),v(null),x(null)},[e,p,D]),Me=u.useCallback((q,ae)=>D(th(e,p,q,ae)),[e,p,D]),Re=u.useCallback(()=>{if(!h||!b)return;const q=ol(e,p,h.r,h.c,b.r,b.c);q.ok&&(D(q.table),v({r:Math.min(h.r,b.r),c:Math.min(h.c,b.c)}),x(null))},[e,p,h,b,D]),ve=u.useCallback(()=>{h&&(D(rh(e,p,h.r,h.c)),x(null))},[e,p,h,D]),te=u.useCallback(q=>{if(!h)return;const ae=Math.min(h.r,b?.r??h.r),pe=Math.max(h.r,b?.r??h.r),$e=Math.min(h.c,b?.c??h.c),be=Math.max(h.c,b?.c??h.c);let j=e;for(let oe=ae;oe<=pe;oe++)for(let ue=$e;ue<=be;ue++)j=Ci(j,p,oe,ue,q);D(j)},[e,p,h,b,D]),he=u.useCallback(async(q,ae)=>{const pe=`${q}:${ae}`,$e=k[pe];if($e===void 0)return;const be=Ue(f,q,ae);if(!be)return;const{node:j,path:oe}=dl(be.cell);if(oe===null)return;const ue=wh(j,c,d);if(ue.editable){if($e===ue.display){w(J=>{const le={...J};return delete le[pe],le});return}C(!0);try{const J=A8(j);if(J)await yr(c,J,d,$e),await tn(c,d);else{const le=await qn(c,l,d,$e);if(le.kind==="ok"&&le.resource){const Ie=`$t:${le.resource.translation_key}`;if(oe.length===0)D(ih(e,p,q,ae,Ie));else{const dt=tr(be.cell,oe,Ie);D(sh(e,p,q,ae,dt))}await tn(c,d)}}}finally{C(!1),w(J=>{const le={...J};return delete le[pe],le})}}},[k,f,c,d,l,e,p,D]),Q=u.useMemo(()=>{if(!O)return null;const{node:q,path:ae}=dl(O.cell);return ae===null?null:{value:typeof q?.text=="string"?q.text:"",editable:!0}},[O]),ie=u.useCallback(q=>{if(typeof q!="string"||q.length===0||!h)return;const ae=Ue(f,h.r,h.c);if(!ae)return;const pe=er(ae.cell);if(pe!==null)if(pe.length===0)D(ih(e,p,h.r,h.c,q));else{const $e=tr(ae.cell,pe,q);D(sh(e,p,h.r,h.c,$e))}},[h,f,e,p,D]),_e=u.useCallback((q,ae,pe)=>{pe?x({r:q,c:ae}):(v({r:q,c:ae}),x(null))},[]),ge=u.useMemo(()=>Array.from({length:f.colCount},(q,ae)=>ae),[f.colCount]),Ae=!!(h&&b&&(h.r!==b.r||h.c!==b.c)),Ne=!!(O&&(O.colSpan>1||O.rowSpan>1)),Le=O&&typeof O.cell.props?.className=="string"?O.cell.props.className:"";return i.jsxs("div",{className:"g7le-node-editor g7le-node-editor--table","data-testid":"g7le-table-editor",style:D8,children:[i.jsx("div",{style:N8,children:n("layout_editor.table_editor.title")}),i.jsx("div",{style:{overflowX:"auto"},children:i.jsxs("table",{"data-testid":"g7le-table-editor-grid",style:z8,children:[i.jsx("thead",{children:i.jsxs("tr",{children:[i.jsx("th",{style:M8}),ge.map(q=>{const ae=ze(q,-1),pe=ze(q,1),$e=M===q;return i.jsx("th",{style:L8,"data-testid":`g7le-table-colgutter-${q}`,onMouseEnter:()=>$(q),onMouseLeave:()=>$(be=>be===q?null:be),children:i.jsxs("div",{style:{...O8,visibility:$e?"visible":"hidden"},children:[i.jsx("button",{type:"button",title:ae.ok?n("layout_editor.table_editor.move_col_left"):me(ae.reason)||n("layout_editor.table_editor.move_col_left"),disabled:!ae.ok||_,onClick:()=>Me(q,-1),"data-testid":`g7le-table-col-left-${q}`,style:ae.ok?vn:$i,children:"←"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.add_col"),disabled:_,onClick:()=>Pe(q),"data-testid":`g7le-table-col-add-${q}`,style:vn,children:"+"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.remove_col"),disabled:f.colCount<=1||_,onClick:()=>Qe(q),"data-testid":`g7le-table-col-remove-${q}`,style:kh,children:"✕"}),i.jsx("button",{type:"button",title:pe.ok?n("layout_editor.table_editor.move_col_right"):me(pe.reason)||n("layout_editor.table_editor.move_col_right"),disabled:!pe.ok||_,onClick:()=>Me(q,1),"data-testid":`g7le-table-col-right-${q}`,style:pe.ok?vn:$i,children:"→"})]})},q)})]})}),i.jsx("tbody",{children:f.rows.map((q,ae)=>{const pe=q.cells[0]?.gridRow??ae,$e=B===pe;return i.jsxs("tr",{"data-testid":`g7le-table-row-${pe}`,onMouseEnter:()=>S(pe),onMouseLeave:()=>S(be=>be===pe?null:be),children:[i.jsx("td",{style:P8,"data-testid":`g7le-table-rowgutter-${pe}`,children:(()=>{const be=Ce(pe,-1),j=Ce(pe,1);return i.jsxs("div",{style:{...B8,visibility:$e?"visible":"hidden"},children:[i.jsx("button",{type:"button",title:be.ok?n("layout_editor.table_editor.move_row_up"):me(be.reason)||n("layout_editor.table_editor.move_row_up"),disabled:!be.ok||_,onClick:()=>De(pe,-1),"data-testid":`g7le-table-row-up-${pe}`,style:be.ok?vn:$i,children:"↑"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.add_row"),disabled:_,onClick:()=>Se(pe),"data-testid":`g7le-table-row-add-${pe}`,style:vn,children:"+"}),i.jsx("button",{type:"button",title:n("layout_editor.table_editor.remove_row"),disabled:f.rows.length<=1||_,onClick:()=>qe(pe),"data-testid":`g7le-table-row-remove-${pe}`,style:kh,children:"✕"}),i.jsx("button",{type:"button",title:j.ok?n("layout_editor.table_editor.move_row_down"):me(j.reason)||n("layout_editor.table_editor.move_row_down"),disabled:!j.ok||_,onClick:()=>De(pe,1),"data-testid":`g7le-table-row-down-${pe}`,style:j.ok?vn:$i,children:"↓"})]})})()}),q.cells.map(be=>{const j=`${be.gridRow}:${be.gridCol}`,{node:oe,path:ue}=dl(be.cell),J=wh(oe,c,d),le=ue!==null&&J.editable,Ie=ue===null,dt=k[j],pt=dt!==void 0?dt:J.display,ot=h&&h.r===be.gridRow&&h.c===be.gridCol,Oe=h&&b&&be.gridRow>=Math.min(h.r,b.r)&&be.gridRow<=Math.max(h.r,b.r)&&be.gridCol>=Math.min(h.c,b.c)&&be.gridCol<=Math.max(h.c,b.c);return i.jsx("td",{colSpan:be.colSpan,rowSpan:be.rowSpan,"data-testid":`g7le-table-cell-${be.gridRow}-${be.gridCol}`,onClick:He=>_e(be.gridRow,be.gridCol,He.shiftKey),style:{...W8,...S8(be.cell,y,A),...C8(be.cell,g,A),...be.isHeader?j8:{},...ot?H8:{},...Oe&&!ot?F8:{}},children:le?i.jsx("input",{type:"text","data-testid":`g7le-table-cell-input-${be.gridRow}-${be.gridCol}`,value:pt,placeholder:n("layout_editor.table_editor.cell_text"),disabled:_,onMouseDown:He=>{He.shiftKey&&He.preventDefault(),_e(be.gridRow,be.gridCol,He.shiftKey)},onClick:He=>He.stopPropagation(),onChange:He=>w(Ye=>({...Ye,[j]:He.target.value})),onBlur:()=>void he(be.gridRow,be.gridCol),style:K8}):Ie?i.jsx("span",{"data-testid":`g7le-table-cell-struct-${be.gridRow}-${be.gridCol}`,style:Sh,children:n("layout_editor.table_editor.structural_cell")}):i.jsx("span",{style:Sh,children:J.display})},j)})]},ae)})})]})}),i.jsxs("button",{type:"button","data-testid":"g7le-table-add-row-bottom",onClick:()=>Se(f.rows.length-1),disabled:_,style:V8,children:["+ ",n("layout_editor.table_editor.add_row")]}),i.jsxs("div",{style:U8,"data-testid":"g7le-table-cell-tools",children:[i.jsx("button",{type:"button","data-testid":"g7le-table-merge",onClick:Re,disabled:!Ae||_,style:Ch,children:n("layout_editor.table_editor.merge_cells")}),i.jsx("button",{type:"button","data-testid":"g7le-table-unmerge",onClick:ve,disabled:!Ne||_,style:Ch,children:n("layout_editor.table_editor.unmerge_cells")})]}),O&&Q&&i.jsxs("div",{style:G8,"data-testid":"g7le-table-cell-i18n-section",children:[i.jsx("div",{style:Y8,children:n("layout_editor.table_editor.cell_i18n_label")}),i.jsx(vt,{value:Q.value,onChange:ie,t:n,placeholder:n("layout_editor.table_editor.cell_text"),testidPrefix:"g7le-table-cell-i18n",candidates:s,enableExpressionTree:!0,expressionTreeCollapsible:!0})]}),O&&i.jsxs("div",{style:q8,"data-testid":"g7le-table-cell-color-section",children:[i.jsx(yh,{colorScheme:A,onChange:z,t:n,disabled:_}),y&&i.jsx("div",{style:cl,"data-testid":"g7le-table-cell-border-row",children:i.jsx(dh,{className:Le,catalog:y,t:n,onChange:te,colorScheme:A,onPresetToken:F,colorStyle:G,onColorStyle:I,disabled:_})}),i.jsx("div",{style:cl,"data-testid":"g7le-table-cell-fill-row",children:i.jsx(fh,{colorStyle:fe,className:K,catalog:g,t:n,colorScheme:A,onPresetToken:se,onCustomColor:re,onClear:U,disabled:_})})]}),O&&i.jsx("div",{style:cl,"data-testid":"g7le-table-cell-padding-row",children:i.jsx(gh,{paddingStyle:ne,catalog:m,t:n,onChange:ee,disabled:_})}),O&&!y&&i.jsxs("label",{style:X8,"data-testid":"g7le-table-cell-border-row",children:[i.jsx("span",{style:J8,children:n("layout_editor.table_editor.cell_border")}),i.jsx("input",{type:"text","data-testid":"g7le-table-cell-border-input",value:Le,placeholder:n("layout_editor.table_editor.cell_class_placeholder"),onChange:q=>te(q.target.value),disabled:_,style:Z8})]}),!f.valid&&i.jsx("div",{"data-testid":"g7le-table-grid-warning",style:Q8,children:n("layout_editor.table_editor.grid_invalid")}),i.jsx("div",{style:R8,children:n("layout_editor.table_editor.select_hint")})]})}const D8={display:"flex",flexDirection:"column",gap:8,width:"100%",marginBottom:12},N8={fontSize:12,fontWeight:700,color:"#0f172a"},z8={borderCollapse:"collapse",width:"auto"},M8={width:28,background:"transparent",border:"none"},L8={padding:2,border:"none",background:"transparent"},P8={padding:2,border:"none",background:"transparent",verticalAlign:"middle"},O8={display:"flex",gap:2,justifyContent:"center"},B8={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"},kh={...vn,border:"1px solid #fecaca",color:"#dc2626"},$i={...vn,cursor:"not-allowed",opacity:.4,color:"#94a3b8",borderColor:"#e2e8f0"},W8={border:"1px solid #cbd5e1",padding:0,width:64,minWidth:64,maxWidth:120,height:24,background:"#fff",cursor:"pointer"},j8={background:"#f1f5f9",fontWeight:600},H8={outline:"2px solid #2563eb",outlineOffset:-2},F8={background:"#dbeafe"},K8={width:"100%",boxSizing:"border-box",padding:"2px 5px",fontSize:11,height:22,lineHeight:"18px",border:"none",background:"transparent",outline:"none"},Sh={display:"block",padding:"2px 5px",fontSize:10,color:"#64748b",fontStyle:"italic",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap",maxWidth:110},V8={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},U8={display:"flex",gap:6},Ch={padding:"4px 8px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},q8={display:"flex",flexDirection:"column",gap:8,borderTop:"1px solid #f1f5f9",paddingTop:8},G8={display:"flex",flexDirection:"column",gap:6,borderTop:"1px solid #f1f5f9",paddingTop:8},Y8={fontSize:12,fontWeight:700,color:"#0f172a"},cl={display:"flex",flexDirection:"column",gap:6},X8={display:"flex",alignItems:"center",gap:6},J8={fontSize:12,color:"#475569",minWidth:60},Z8={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},Q8={fontSize:11,color:"#b45309",background:"#fffbeb",border:"1px solid #fde68a",borderRadius:6,padding:"4px 6px"},R8={fontSize:11,color:"#94a3b8"},ez=/\{\{.*?\}\}/;function tz(e,t,n){const r=(e.props??{})[t];return Array.isArray(r)?r:r===void 0&&n?JSON.parse(JSON.stringify(n)):[]}function nz(e){return typeof e=="string"&&ez.test(e)}function ul(e,t,n){return e?e.startsWith("$t:")?t(e.slice(3)):e:n}function oz(e,t,n){return typeof e=="object"&&e!==null?e[t.key]:n?e:void 0}function rz(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 $h({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=ul(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,y=(l.find(C=>C.primary)??l[0])?.key,g=(e.props??{})[a??""],m=Array.isArray(t?.defaultItems)?t.defaultItems:null,h=a?tz(e,a,m):[],v=u.useCallback(C=>{if(!a)return;const E={...e.props??{}};E[a]=C,o({...e,props:E})},[a,e,o]),b=u.useCallback(()=>{if(p)return JSON.parse(JSON.stringify(p));if(f!==null)return f;const C={};for(const E of l)(E.widget??"text")==="boolean"?C[E.key]=!1:C[E.key]="";return C},[p,f,l]),x=u.useCallback(()=>{v([...h,b()])},[v,h,b]),k=u.useCallback(C=>{v(h.filter((E,S)=>S!==C))},[v,h]),w=u.useCallback((C,E)=>{const S=C+E;if(S<0||S>=h.length)return;const T=[...h];[T[C],T[S]]=[T[S],T[C]],v(T)},[v,h]),_=u.useCallback((C,E,S)=>{const T=E.key===y,$=h.map((A,z)=>z===C?rz(A,E,T,S):A);v($)},[h,v,y]);return a?nz(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:fz,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:iz,children:[i.jsx("div",{style:sz,children:n("layout_editor.array_editor.items_title")}),h.length===0&&i.jsx("div",{"data-testid":"g7le-array-empty",style:Ih,children:n("layout_editor.array_editor.empty")}),h.map((C,E)=>i.jsxs("div",{"data-testid":`g7le-array-row-${E}`,style:az,children:[i.jsxs("div",{style:lz,children:[i.jsxs("span",{style:dz,children:["#",E+1]}),i.jsx("div",{style:{flex:1}}),i.jsx("button",{type:"button","data-testid":`g7le-array-up-${E}`,title:n("layout_editor.array_editor.move_up"),disabled:E===0,onClick:()=>w(E,-1),style:Eh,children:"↑"}),i.jsx("button",{type:"button","data-testid":`g7le-array-down-${E}`,title:n("layout_editor.array_editor.move_down"),disabled:E===h.length-1,onClick:()=>w(E,1),style:Eh,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-array-remove-${E}`,title:n("layout_editor.array_editor.remove"),onClick:()=>k(E),style:uz,children:"✕"})]}),l.map(S=>{const T=S.widget??"text",$=S.key===y,A=ul(S.label,n,S.key),z=oz(C,S,$),D=`g7le-array-field-${E}-${S.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:z===!0,onChange:M=>_(E,S,M.target.checked)})]},S.key);if(T==="select"){const M=Array.isArray(S.options)?S.options:[];return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsxs("select",{"data-testid":D,value:z==null?"":String(z),onChange:B=>_(E,S,B.target.value===""?void 0:B.target.value),style:or,children:[i.jsx("option",{value:"",children:"—"}),M.map((B,N)=>i.jsx("option",{value:String(B.value),children:ul(B.label,n,String(B.value))},N))]})]},S.key)}if(T==="i18n-text"){const M=typeof z=="string"?z:z==null?"":String(z);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(vt,{value:M,onChange:B=>_(E,S,B===""?void 0:B),t:n,placeholder:A,testidPrefix:`${D}-i18n`,candidates:s,enableExpressionTree:!0,expressionTreeCollapsible:!0})})]},S.key)}if(T==="number"){const M=z==null?"":String(z);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:B=>{const N=B.target.value;_(E,S,N===""?void 0:Number(N))},style:or})]},S.key)}if(T==="color"){const M=typeof z=="string"?z:"",B=/^#[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:B,onChange:N=>_(E,S,N.target.value),style:cz}),i.jsx("input",{type:"text","data-testid":D,value:M,placeholder:"#7C3AED",onChange:N=>_(E,S,N.target.value===""?void 0:N.target.value),style:or})]},S.key)}if(T==="number-list"){const M=Array.isArray(z)?z.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:B=>{const N=B.target.value.split(",").map(H=>H.trim()).filter(H=>H!=="").map(H=>Number(H)).filter(H=>!Number.isNaN(H));_(E,S,N)},style:or})]},S.key)}const O=z==null?"":String(z);return i.jsxs("label",{style:Wn,children:[i.jsx("span",{style:jn,children:A}),i.jsx("input",{type:"text","data-testid":D,value:O,placeholder:T==="icon"?n("layout_editor.array_editor.icon_placeholder"):A,onChange:M=>_(E,S,M.target.value===""?void 0:M.target.value),style:or})]},S.key)})]},E)),i.jsx("button",{type:"button","data-testid":"g7le-array-add",onClick:x,style:pz,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:Ih,children:n("layout_editor.array_editor.no_array_prop")})}const iz={display:"flex",flexDirection:"column",gap:8,width:"100%",marginBottom:12},sz={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:2},az={display:"flex",flexDirection:"column",gap:4,padding:8,border:"1px solid #e2e8f0",borderRadius:8,background:"#f8fafc"},lz={display:"flex",gap:4,alignItems:"center"},dz={fontSize:11,fontWeight:700,color:"#64748b"},Wn={display:"flex",flexWrap:"wrap",gap:6,alignItems:"center"},jn={fontSize:11,color:"#475569",minWidth:64,flexShrink:0},or={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},cz={width:32,height:28,padding:0,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",cursor:"pointer",flexShrink:0},Eh={padding:"2px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"},uz={padding:"2px 6px",fontSize:12,border:"1px solid #fecaca",borderRadius:6,background:"#fff",color:"#dc2626",cursor:"pointer"},pz={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},Ih={fontSize:11,color:"#94a3b8",fontStyle:"italic"},fz={fontSize:11,color:"#b45309",fontStyle:"italic",padding:"4px 2px"};function gz(e,t){return e?e.startsWith("$t:")?t(e.slice(3)):e:null}function hz(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:vz,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:yz,children:o.map((r,s)=>{const a=gz(r.title,n),{title:l,...d}=r;return i.jsxs("div",{"data-testid":`g7le-array-group-${r.arrayProp??s}`,style:bz,children:[a&&i.jsx("div",{style:mz,children:a}),i.jsx($h,{...e,params:d})]},r.arrayProp??s)})})}const yz={display:"flex",flexDirection:"column",gap:16,width:"100%",marginBottom:12},bz={display:"flex",flexDirection:"column",gap:4},mz={fontSize:12,fontWeight:700,color:"#1e293b",borderBottom:"1px solid #e2e8f0",paddingBottom:4},vz={fontSize:11,color:"#94a3b8",fontStyle:"italic"},_z=/\{\{.*?\}\}/;function xz(e){return typeof e=="string"&&_z.test(e)}function wz(e,t,n){return e?e.startsWith("$t:")?t(e.slice(3)):e:n}function kz(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=wz(typeof n?.itemLabel=="string"?n.itemLabel:void 0,o,o("layout_editor.array_editor.item")),[p,f]=u.useState(null),y=s?(t.props??{})[s]:void 0,g=Array.isArray(y)?y:[],m=u.useCallback(C=>{if(!s)return;const E={...t.props??{}};E[s]=C,r({...t,props:E})},[s,t,r]),h=u.useCallback(()=>{const C=n?.newItem;return C&&typeof C=="object"?JSON.parse(JSON.stringify(C)):{[a]:"",[l]:[]}},[n,a,l]),v=u.useCallback(()=>{m([...g,h()])},[m,g,h]),b=u.useCallback(C=>{m(g.filter((E,S)=>S!==C)),f(null)},[m,g]),x=u.useCallback((C,E)=>{const S=C+E;if(S<0||S>=g.length)return;const T=[...g];[T[C],T[S]]=[T[S],T[C]],m(T)},[m,g]),k=u.useCallback((C,E)=>{const S=g.map((T,$)=>$===C?{...T,[a]:E}:T);m(S)},[g,m,a]),w=u.useCallback(C=>({type:"composite",name:"CardGridCell",children:Array.isArray(C[l])?C[l]:[]}),[l]),_=u.useCallback(C=>E=>{const S=Array.isArray(E.children)?E.children:[],T=g.map(($,A)=>A===C?{...$,[l]:S}:$);m(T)},[g,m,l]);return s?xz(y)||y!==void 0&&!Array.isArray(y)?i.jsx("div",{className:"g7le-node-editor g7le-node-editor--cell-tree","data-testid":"g7le-cell-tree-bound",style:Mz,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:Sz,children:[i.jsx("div",{style:Cz,children:o("layout_editor.cell_tree_editor.columns_title")}),g.length===0&&i.jsx("div",{"data-testid":"g7le-cell-tree-empty",style:Th,children:o("layout_editor.array_editor.empty")}),g.map((C,E)=>{const S=typeof C[a]=="string"?C[a]:"",T=p===E;return i.jsxs("div",{"data-testid":`g7le-cell-tree-row-${E}`,style:$z,children:[i.jsxs("div",{style:Ez,children:[i.jsxs("span",{style:Iz,children:["#",E+1]}),i.jsx("input",{type:"text","data-testid":`g7le-cell-tree-id-${E}`,value:S,placeholder:o("layout_editor.cell_tree_editor.id_placeholder"),onChange:$=>k(E,$.target.value),style:Az}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-up-${E}`,title:o("layout_editor.array_editor.move_up"),disabled:E===0,onClick:()=>x(E,-1),style:Ah,children:"↑"}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-down-${E}`,title:o("layout_editor.array_editor.move_down"),disabled:E===g.length-1,onClick:()=>x(E,1),style:Ah,children:"↓"}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-remove-${E}`,title:o("layout_editor.array_editor.remove"),onClick:()=>b(E),style:Tz,children:"✕"})]}),i.jsx("button",{type:"button","data-testid":`g7le-cell-tree-toggle-${E}`,onClick:()=>f(T?null:E),style:Dz,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-${E}`,style:Nz,children:i.jsx(qg,{...e,node:w(C),params:{childComponent:d},onPatchNode:_(E)})})]},E)}),i.jsx("button",{type:"button","data-testid":"g7le-cell-tree-add",onClick:v,style:zz,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:Th,children:o("layout_editor.array_editor.no_array_prop")})}const Sz={display:"flex",flexDirection:"column",gap:8,width:"100%",marginBottom:12},Cz={fontSize:12,fontWeight:700,color:"#0f172a",marginBottom:2},$z={display:"flex",flexDirection:"column",gap:6,padding:8,border:"1px solid #e2e8f0",borderRadius:8,background:"#f8fafc"},Ez={display:"flex",gap:4,alignItems:"center"},Iz={fontSize:11,fontWeight:700,color:"#64748b",flexShrink:0},Az={flex:1,minWidth:0,padding:"4px 6px",fontSize:12,border:"1px solid #cbd5e1",borderRadius:6},Ah={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:"3px 8px",fontSize:11,border:"1px solid #cbd5e1",borderRadius:6,background:"#fff",color:"#2563eb",cursor:"pointer",alignSelf:"flex-start"},Nz={paddingLeft:8,borderLeft:"2px solid #e2e8f0"},zz={padding:"4px 8px",fontSize:12,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer",alignSelf:"flex-start"},Th={fontSize:11,color:"#94a3b8",fontStyle:"italic"},Mz={fontSize:11,color:"#b45309",fontStyle:"italic",padding:"4px 2px"};function Lz(e,t,n){const o=Be(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=tl(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 pl=26,fl=50,gl=6,Dh=44,Nh=18,zh="g7le-table-inplace-empty-cell-style";function Pz(){if(typeof document>"u"||document.getElementById(zh))return;const e=document.createElement("style");e.id=zh,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 Oz({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(()=>Lz(e,c,o),[e,c,o]),[y,g]=u.useState(null),[m,h]=u.useState(null),v=u.useMemo(()=>{if(!r)return null;for(const j of f.rows)for(const oe of j.cells){const ue=tl(e,oe,c).map(J=>`children.${J}`).join(".");if(r===ue||r.startsWith(ue+"."))return{r:oe.gridRow,c:oe.gridCol}}return null},[r,f,e,c]),b=u.useMemo(()=>y&&Ue(f,y.r,y.c)?y:v,[y,v,f]),[x,k]=u.useState(!1),[w,_]=u.useState(s==="dark"?"dark":"light"),[C,E]=u.useState(null),[S,T]=u.useState(null),$=u.useRef(null),A=u.useCallback(()=>{$.current!==null&&(clearTimeout($.current),$.current=null)},[]),z=u.useCallback(()=>{A(),$.current=setTimeout(()=>{E(null),T(null),$.current=null},240)},[A]);u.useEffect(()=>()=>A(),[A]),u.useEffect(()=>{Pz()},[]);const D=u.useCallback(j=>l(j),[l]),O=u.useMemo(()=>b?Ue(f,b.r,b.c):null,[f,b]),M=u.useMemo(()=>O&&typeof O.cell.props?.className=="string"?O.cell.props.className:"",[O]),B=u.useCallback(j=>D(nl(e,c,j)),[e,c,D]),N=u.useCallback(j=>D(Rg(e,c,j)),[e,c,D]),H=u.useCallback((j,oe)=>D(eh(e,c,j,oe)),[e,c,D]),L=u.useCallback(j=>D(nh(e,c,j)),[e,c,D]),I=u.useCallback(j=>D(oh(e,c,j)),[e,c,D]),P=u.useCallback((j,oe)=>D(th(e,c,j,oe)),[e,c,D]),F=u.useCallback(j=>{if(!O)return;const oe=O.gridRow,ue=O.gridCol,J=j==="down"?oe+O.rowSpan:oe+O.rowSpan-1,le=j==="right"?ue+O.colSpan:ue+O.colSpan-1;if(J>=f.rows.length||le>=f.colCount)return;const Ie=ol(e,c,oe,ue,J,le);Ie.ok&&D(Ie.table)},[O,f,e,c,D]),G=!!(O&&O.gridCol+O.colSpan!b||!m||!Ue(f,m.r,m.c)?null:{r0:Math.min(b.r,m.r),c0:Math.min(b.c,m.c),r1:Math.max(b.r,m.r),c1:Math.max(b.c,m.c)},[b,m,f]),Z=u.useMemo(()=>{if(!Y)return[];const j=new Set,oe=[];for(const ue of f.rows)for(const J of ue.cells)if(J.gridRow>=Y.r0&&J.gridRow<=Y.r1&&J.gridCol>=Y.c0&&J.gridCol<=Y.c1){const le=`${J.gridRow}:${J.gridCol}`;j.has(le)||(j.add(le),oe.push({r:J.gridRow,c:J.gridCol}))}return oe},[Y,f]),se=Z.length>1,re=u.useCallback(()=>{if(!Y)return;const j=ol(e,c,Y.r0,Y.c0,Y.r1,Y.c1);j.ok&&(D(j.table),h(null))},[Y,e,c,D]),U=u.useCallback(()=>{b&&D(rh(e,c,b.r,b.c))},[e,c,b,D]),ee=u.useMemo(()=>{const j=c?.cellBorder;return j&&typeof j=="object"?j:null},[c]),fe=u.useMemo(()=>{const j=c?.cellBackground;return j&&typeof j=="object"?j:null},[c]),K=u.useMemo(()=>{const j=c?.cellPadding;return j&&typeof j=="object"?j:null},[c]),ne=u.useMemo(()=>{if(x){const j=new Set,oe=[];for(const ue of f.rows)for(const J of ue.cells){const le=`${J.gridRow}:${J.gridCol}`;j.has(le)||(j.add(le),oe.push({r:J.gridRow,c:J.gridCol}))}return oe}return se?Z:b?[{r:b.r,c:b.c}]:[]},[x,se,Z,b,f]),me=u.useCallback(j=>{if(ne.length===0)return;let oe=e;for(const ue of ne){const J=(ee?.colors??[]).map(Ie=>Ie.token),le=j.split(/\s+/).filter(Ie=>Ie&&!J.includes(Ie)).join(" ");oe=Ci(oe,c,ue.r,ue.c,le)}D(oe)},[e,c,ne,ee,D]),Ce=u.useMemo(()=>{const j=(ee?.sides??[]).find(J=>J.value==="all")??(ee?.sides??[])[0],oe=(ee?.widths??[]).find(J=>J.value!=="none");if(!j||!oe)return[];const ue=oe.suffix??"";return[ue?`${j.prefix}${ue}`:j.prefix]},[ee]),ze=u.useCallback((j,oe,ue)=>{if(Ce.length===0)return j;const J=(ee?.sides??[]).map(Oe=>Oe.prefix),le=Ue(Be(j,c),oe,ue),dt=(typeof le?.cell?.props?.className=="string"?le.cell.props.className:"").split(/\s+/).filter(Boolean);if(dt.some(Oe=>J.some(He=>Oe===He||Oe.startsWith(He+"-")&&/^-?\d+$/.test(Oe.slice(He.length+1)))))return j;const ot=[...dt,...Ce].join(" ").trim();return Ci(j,c,oe,ue,ot)},[Ce,ee,c]),Se=u.useCallback((j,oe)=>{if(j.length===0)return;const ue=new Set(j.map(le=>`${le.r}:${le.c}`));let J=e;for(const le of j){if(J=ze(J,le.r,le.c),J=Jt(J,c,le.r,le.c,"borderColor",oe),le.r>0&&!ue.has(`${le.r-1}:${le.c}`)){const Ie=Ue(Be(J,c),le.r-1,le.c);Ie&&(J=Jt(J,c,Ie.gridRow,Ie.gridCol,"borderBottomColor",oe))}if(le.c>0&&!ue.has(`${le.r}:${le.c-1}`)){const Ie=Ue(Be(J,c),le.r,le.c-1);Ie&&(J=Jt(J,c,Ie.gridRow,Ie.gridCol,"borderRightColor",oe))}}D(J)},[e,c,D,ze]),qe=u.useMemo(()=>(ee?.colors??[]).map(j=>j.token).filter(Boolean),[ee]),De=u.useCallback(j=>{if(ne.length===0||qe.length===0)return;let oe=e;for(const ue of ne)oe=ze(oe,ue.r,ue.c),oe=go(oe,c,ue.r,ue.c,j,qe,w);D(oe)},[ne,e,c,D,ze,qe,w]),Pe=u.useCallback(j=>Se(ne,j),[Se,ne]),Qe=u.useMemo(()=>{if(w==="dark")return"";const j=O?.cell.props?.style;return typeof j?.borderColor=="string"?j.borderColor:""},[O,w]),Me=u.useCallback((j,oe)=>{if(ne.length===0)return;let ue=e;for(const J of ne)ue=Jt(ue,c,J.r,J.c,j,oe);D(ue)},[ne,e,c,D]),Re=u.useMemo(()=>(fe?.colors??[]).map(j=>j.token).filter(j=>!!j),[fe]),ve=u.useCallback(j=>{if(ne.length===0||Re.length===0)return;let oe=e;for(const ue of ne)oe=go(oe,c,ue.r,ue.c,j,Re,w);D(oe)},[ne,e,c,D,Re,w]),te=u.useCallback(j=>Me("backgroundColor",j),[Me]),he=u.useCallback(()=>{if(ne.length===0)return;let j=e;for(const oe of ne)j=go(j,c,oe.r,oe.c,void 0,Re,w),w==="light"&&(j=Jt(j,c,oe.r,oe.c,"backgroundColor",void 0));D(j)},[ne,e,c,D,Re,w]),Q=u.useCallback(j=>Me("padding",j),[Me]),ie=u.useMemo(()=>{if(w==="dark")return"";const j=O?.cell.props?.style;return typeof j?.backgroundColor=="string"?j.backgroundColor:""},[O,w]),_e=u.useMemo(()=>typeof O?.cell.props?.className=="string"?O.cell.props.className:"",[O]),ge=u.useMemo(()=>{const j=O?.cell.props?.style;return typeof j?.padding=="string"?j.padding:""},[O]),Ae=u.useCallback(j=>{const oe=j.currentTarget,ue=oe.style.pointerEvents;oe.style.pointerEvents="none";const J=document.elementFromPoint(j.clientX,j.clientY);oe.style.pointerEvents=ue;const le=J?.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}))},[]),Ne=u.useMemo(()=>{const j=new Map;for(const oe of p)j.has(oe.ref.gridCol)||j.set(oe.ref.gridCol,oe.box);return j},[p]),Le=u.useMemo(()=>{const j=new Map;for(const oe of p)j.has(oe.ref.gridRow)||j.set(oe.ref.gridRow,oe.box);return j},[p]);if(p.length===0)return null;const q=!!(O&&(O.colSpan>1||O.rowSpan>1)),ae=S!==null?S:b?.c??null,pe=C!==null?C:b?.r??null,$e=n.top-pl-gl-Dh,be=n.left-fl-gl-Dh;return i.jsxs("div",{className:"g7le-table-inplace","data-testid":"g7le-table-inplace",style:{position:"absolute",inset:0,pointerEvents:"none",zIndex:g7},children:[p.map(j=>{const oe=b&&b.r===j.ref.gridRow&&b.c===j.ref.gridCol,ue=Y&&j.ref.gridRow>=Y.r0&&j.ref.gridRow<=Y.r1&&j.ref.gridCol>=Y.c0&&j.ref.gridCol<=Y.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(),E(j.ref.gridRow),T(j.ref.gridCol)},onMouseLeave:()=>{z()},onPointerDown:J=>Ae(J),onClick:J=>{if(J.stopPropagation(),J.shiftKey&&(y||b))h({r:j.ref.gridRow,c:j.ref.gridCol});else{g({r:j.ref.gridRow,c:j.ref.gridCol}),h(null);const le=tl(e,j.ref,c).map(Ie=>`children.${Ie}`).join(".");d?.(le)}},style:{position:"absolute",top:j.box.top,left:j.box.left,width:j.box.width,height:j.box.height,minWidth:Nh,minHeight:Nh,boxSizing:"border-box",pointerEvents:"auto",cursor:"pointer",outline:oe?"2px solid #2563eb":"none",outlineOffset:-2,background:ue&&!oe?"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:z,style:{position:"absolute",top:$e,left:n.left,width:n.width,height:pl,pointerEvents:"none"},children:ae!==null&&Ne.has(ae)&&(()=>{const j=ae,oe=Ne.get(j),ue=wi(f,j,-1),J=wi(f,j,1),le=oe.left-n.left;return i.jsxs("div",{"data-testid":`g7le-inplace-colgutter-${j}`,onMouseEnter:()=>{A(),T(j)},onMouseLeave:z,style:{position:"absolute",top:0,left:le,width:oe.width,minWidth:96,height:pl,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:!ue.ok,onClick:()=>P(j,-1),"data-testid":`g7le-inplace-col-left-${j}`,style:ue.ok?_n:Ei,children:"←"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.add_col"),onClick:()=>L(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:Mh,children:"✕"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.move_col_right"),disabled:!J.ok,onClick:()=>P(j,1),"data-testid":`g7le-inplace-col-right-${j}`,style:J.ok?_n:Ei,children:"→"})]},`colgut-${j}`)})()}),i.jsx("div",{"data-testid":"g7le-inplace-row-rail",style:{position:"absolute",top:n.top,left:be,width:fl,height:n.height,pointerEvents:"none"},children:pe!==null&&Le.has(pe)&&(()=>{const j=pe,oe=Le.get(j),ue=xi(f,j,-1),J=xi(f,j,1),le=oe.top-n.top;return i.jsxs("div",{"data-testid":`g7le-inplace-rowgutter-${j}`,onMouseEnter:()=>{A(),E(j)},onMouseLeave:z,style:{position:"absolute",top:le,left:0,width:fl,height:oe.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:!ue.ok,onClick:()=>H(j,-1),"data-testid":`g7le-inplace-row-up-${j}`,style:ue.ok?_n:Ei,children:"↑"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.add_row"),onClick:()=>B(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:()=>N(j),"data-testid":`g7le-inplace-row-remove-${j}`,style:Mh,children:"✕"}),i.jsx("button",{type:"button",title:a("layout_editor.table_inplace.move_row_down"),disabled:!J.ok,onClick:()=>H(j,1),"data-testid":`g7le-inplace-row-down-${j}`,style:J.ok?_n:Ei,children:"↓"})]},`rowgut-${j}`)})()}),i.jsxs("div",{"data-testid":"g7le-inplace-corner-add",style:{position:"absolute",top:n.top+n.height+gl,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:()=>B(f.rows.length-1),style:Lh,children:["+ ",a("layout_editor.table_inplace.add_row")]}),i.jsxs("button",{type:"button","data-testid":"g7le-inplace-add-col-right",onClick:()=>L(f.colCount-1),style:Lh,children:["+ ",a("layout_editor.table_inplace.add_col")]})]}),!b&&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")}),b&&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:re,style:rr,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:!G,onClick:()=>F("right"),style:G?rr:hl,children:a("layout_editor.table_inplace.merge_right")}),i.jsx("button",{type:"button","data-testid":"g7le-inplace-merge-down",disabled:!V,onClick:()=>F("down"),style:V?rr:hl,children:a("layout_editor.table_inplace.merge_down")})]}),i.jsx("button",{type:"button","data-testid":"g7le-inplace-unmerge",disabled:!q,onClick:U,style:q?rr:hl,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:x,onChange:j=>k(j.target.checked)}),a("layout_editor.table_inplace.border_apply_all")]}),i.jsx(yh,{colorScheme:w,onChange:_,t:a}),ee&&i.jsx("div",{"data-testid":"g7le-inplace-cell-border",children:i.jsx(dh,{className:x?"":M,catalog:ee,t:a,onChange:me,colorScheme:w,onPresetToken:De,colorStyle:x?"":Qe,onColorStyle:Pe})}),i.jsx("div",{"data-testid":"g7le-inplace-cell-fill",children:i.jsx(fh,{colorStyle:x?"":ie,className:x?"":_e,catalog:fe,t:a,colorScheme:w,onPresetToken:ve,onCustomColor:te,onClear:he})})]}),i.jsx("div",{"data-testid":"g7le-inplace-cell-padding",style:{borderTop:"1px solid #f1f5f9",paddingTop:6},children:i.jsx(gh,{paddingStyle:x?"":ge,catalog:K,t:a,onChange:Q})})]})]})]})}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)"},Mh={..._n,border:"1px solid #fecaca",color:"#dc2626"},Ei={..._n,cursor:"not-allowed",opacity:.4,color:"#94a3b8",borderColor:"#e2e8f0"},rr={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)"},hl={...rr,cursor:"not-allowed",opacity:.4},Lh={padding:"3px 8px",fontSize:11,border:"1px dashed #94a3b8",borderRadius:6,background:"#fff",color:"#475569",cursor:"pointer"};let Ph=!1;function Bz(){Ph||(Pn("children",qg),Pn("table",T8),Pn("array",$h),Pn("array-group",hz),Pn("array-cell-tree",kz),Oa("table",Oz),Ph=!0)}function Wz(){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:Xe,registerNodeEditor:Pn,registerCanvasOverlay:Oa,onReady:r=>{typeof r=="function"&&r()}};for(const r of n){const[s,...a]=r;try{s==="widget"?Xe(a[0],a[1]):s==="nodeEditor"?Pn(a[0],a[1]):s==="canvasOverlay"&&Oa(a[0],a[1])}catch{}}for(const r of o)try{r()}catch{}}const jz=1280;qN(),Bz(),Wz();async function Hz(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:je()});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 Fz({templateIdentifier:e}){gD({templateIdentifier:e}),hD(e);const{state:t,dispatch:n}=Je(),{t:o}=tt(),r=yo(),s=Cp(),a=xD(),l=t.selectedRoute?.layoutName??null,d=CD(e,l),c=t.editMode==="extension",p=u.useMemo(()=>c?kD(a):s,[c,a,s]),[f,y]=u.useState(null),[g,m]=u.useState(null),[h,v]=u.useState([]),[b,x]=u.useState("user"),[k,w]=u.useState(null),[_,C]=u.useState(null),[E,S]=u.useState([]);u.useEffect(()=>{let te=!1;return(async()=>{try{const he=await fetch(en(`/api/templates/${encodeURIComponent(e)}/components`,"json"),{credentials:"same-origin",headers:{Accept:"application/json"}});if(!he.ok)return;const Q=await he.json().catch(()=>null);!te&&Q&&typeof Q=="object"&&y(Q)}catch{}})(),()=>{te=!0}},[e]),u.useEffect(()=>{let te=!1;return(async()=>{const{spec:he,sampleGlobalSources:Q}=await eb({templateIdentifier:e,coreSeed:$D()});te||(m(he),v(Q),Vz(e,he,Q))})(),()=>{te=!0}},[e]),u.useEffect(()=>{let te=!1;return(async()=>{if(typeof fetch=="function")try{const he=await fetch(`/api/admin/templates/${encodeURIComponent(e)}`,{credentials:"same-origin",headers:je()});if(!he.ok)return;const ie=(await he.json().catch(()=>null))?.data,_e=ie?.type;te||((_e==="admin"||_e==="user")&&x(_e),typeof ie?.name=="string"&&ie.name&&w(ie.name),typeof ie?.version=="string"&&ie.version&&C(ie.version))}catch{}})(),()=>{te=!0}},[e]),u.useEffect(()=>{let te=!1;return(async()=>{if(typeof fetch=="function")try{const he=await fetch("/api/admin/templates/?per_page=100&page=1",{credentials:"same-origin",headers:je()});if(!he.ok)return;const ie=(await he.json().catch(()=>null))?.data?.data;if(!te&&Array.isArray(ie)){const _e=[];for(const ge of ie){if(!ge||typeof ge!="object")continue;const Ae=ge.identifier;if(typeof Ae!="string"||!Ae||ge.is_pending===!0)continue;const Le=ge.type==="admin"?"admin":"user",q=ge.name,ae=ge.version;_e.push({identifier:Ae,name:typeof q=="string"?q:Ae,version:typeof ae=="string"?ae:"",type:Le})}S(_e)}}catch{}})(),()=>{te=!0}},[e]);const T=g?.nesting??null,$=t.selectedRoute?.path??null,A=t.editMode,z=t.selectedRoute?.layoutName??(c?a.document?.hostLayoutName??null:null),D=t.routeTree,O=u.useMemo(()=>{if(A!=="extension"||!z)return null;const te=bl(D,z);return te||`__base__/${z}`},[A,z,D]),M=c&&t.returnRoute===null&&!!z;u.useEffect(()=>{if(!M||!z)return;const te=bl(D,z);te&&n({type:"SET_RETURN_ROUTE",route:{path:te,layoutName:z}})},[M,z,D,n]),u.useEffect(()=>{const te=G4(A,$,O),he=Y4(g?.states?.groups,te);n({type:"SET_AVAILABLE_STATES",states:he,activeStateId:X4(he)})},[g,A,$,O,n]);const[B,N]=u.useState([]);u.useEffect(()=>{let te=!1;return(async()=>{const he=await Hz(e);te||N(he)})(),()=>{te=!0}},[e]),yD(),bD();const H=u.useCallback(te=>{const he=t.routeTree,Q=te.split("?")[0]?.split("#")[0]??te;return Kz(he,Q)?"route_in_tree":"route_not_in_tree"},[t.routeTree]),L=u.useCallback(te=>{const he=te.split("?")[0]?.split("#")[0]??te,Q=yl(t.routeTree,he);Q&&(p.isDirty&&!(!(typeof window<"u")||window.confirm(o("layout_editor.chrome.dirty_guard.message")))||n({type:"SELECT_ROUTE",route:{path:Q.path,layoutName:Q.layoutName}}))},[t.routeTree,p.isDirty,n]),I=u.useRef([]),P=u.useCallback(te=>{I.current=te},[]),[F,G]=u.useState(null),V=u.useCallback(()=>G(null),[]),Y=u.useRef(null),Z=u.useRef(null);u.useEffect(()=>{const te=Z.current,he=Y.current;if(!te||!he||typeof ResizeObserver>"u")return;const Q=()=>{he.style.setProperty("--g7le-header-h",`${Math.round(te.getBoundingClientRect().height)}px`)};Q();const ie=new ResizeObserver(Q);return ie.observe(te),()=>ie.disconnect()},[]);const se=u.useCallback(()=>{p.reload()},[p]),re=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/${b}`,target:"_self"}})},[p.isDirty,o,b]),U=u.useCallback(te=>{if(!te||te===e||p.isDirty&&!(typeof window<"u"?window.confirm(o("layout_editor.chrome.dirty_guard.message")):!0))return;const he=Zs(te);window.G7Core?.dispatch?.({handler:"openWindow",params:{path:he,target:"_self"}})},[e,p.isDirty,o]),ee=u.useCallback(()=>{const te=ME(e,t.selectedRoute?.path??null);window.G7Core?.dispatch?.({handler:"openWindow",params:{path:te}})},[e,t.selectedRoute]),fe=u.useCallback(()=>{const te=t.selectedRoute?.layoutName??"";if(!te)return;const he=r.open({ariaLabel:o("layout_editor.attachment_manager.title"),width:720,maxHeightRatio:.82,content:u.createElement(Ml,{templateIdentifier:e,layoutName:te,t:o,onClose:()=>r.close(he)})})},[r,e,t.selectedRoute,o]),K=u.useCallback(()=>{const te=t.selectedRoute?.layoutName??"";if(!te)return;const he=Hy(s.document?.raw??{}),Q=r.open({ariaLabel:o("layout_editor.translation_manager.title"),width:720,maxHeightRatio:.82,content:u.createElement(dm,{templateIdentifier:e,layoutName:te,t:o,referencedKeys:he,onClose:()=>r.close(Q)})})},[r,e,t.selectedRoute,o,s.document]),ne=u.useCallback((te,he)=>{const Q=window.G7Core;if(Q&&typeof Q.t=="function"){const ie=Q.t(te,he);if(ie&&ie!==te&&!ie.startsWith("$t:"))return ie}return o(te,he)},[o]),me=u.useCallback(()=>{if(!t.selectedRoute||t.editMode==="extension"||t.editMode==="iteration_item")return;const te=r.open({ariaLabel:o("layout_editor.page_settings.title",{name:t.selectedRoute.path??""}),width:1080,maxHeightRatio:.88,closeOnEscape:!1,content:u.createElement(u$,{templateIdentifier:e,spec:g,t:o,resolveLabel:ne,permissionCandidates:B,onClose:()=>r.close(te)})})},[r,t.selectedRoute,t.editMode,o,ne,e,g,B]),Ce=u.useCallback(async()=>{const te=await d.createPreview(s.document?.raw??null);if(te.kind!=="success"){const he=te.kind==="network_error"?te.message:o("layout_editor.preview_action.no_document");typeof window<"u"&&window.alert(he)}},[d,s.document,o]),ze=u.useCallback(()=>{const te=t.selectedRoute?.layoutName??"",he=t.selectedRoute?.path??"",Q=t.editMode==="extension"&&he.startsWith("__extension__/")?he.slice(14):null,ie=Q?{kind:"extension",extensionId:Q}:te?{kind:"layout",layoutName:te}:null;if(!ie)return;const _e=r.open({ariaLabel:o("layout_editor.version_history.title"),width:640,maxHeightRatio:.82,content:u.createElement(X$,{templateIdentifier:e,target:ie,t:o,onRestored:async ge=>{typeof ge=="number"&&(ie.kind==="extension"?n({type:"SET_EXTENSION_VERSION",extensionId:ie.extensionId,version:ge}):n({type:"SET_LAYOUT_VERSION",layoutName:ie.layoutName,version:ge})),await p.reload()},onClose:()=>r.close(_e)})})},[r,e,t.selectedRoute,t.editMode,o,p,n]),Se=p.dirtyKeys.size>0||p.isDirty;u.useEffect(()=>{if(!Se)return;const te=he=>{he.preventDefault(),he.returnValue=""};return window.addEventListener("beforeunload",te),()=>window.removeEventListener("beforeunload",te)},[Se]);const qe=u.useCallback(()=>{!p.isDirty||!(!(typeof window<"u")||window.confirm(o("layout_editor.chrome.reset_guard.message")))||p.reload()},[p,o]),De=u.useCallback(async()=>{const te=await p.save({sessionAddedPaths:I.current});G(te),te.kind==="success"&&typeof te.newContentVersion=="number"&&(te.savedExtensionId?n({type:"SET_EXTENSION_VERSION",extensionId:te.savedExtensionId,version:te.newContentVersion}):te.savedLayoutName&&n({type:"SET_LAYOUT_VERSION",layoutName:te.savedLayoutName,version:te.newContentVersion}))},[p,n]),Pe=u.useCallback(()=>{const te=r.open({ariaLabel:o("layout_editor.shortcuts.title"),width:560,maxHeightRatio:.85,content:u.createElement(iE,{t:o,onClose:()=>r.close(te)})})},[r,o]),Qe=u.useMemo(()=>({save:()=>{De()},exit:re,editCode:ee,reset:qe,translations:K,addElement:()=>{t.selectedRoute&&n({type:"TOGGLE_PALETTE"})},help:Pe,preview:()=>{t.selectedRoute?.layoutName&&Ce()}}),[De,re,ee,qe,K,t.selectedRoute,n,Pe,Ce]),[Me,Re]=u.useState(!1);u.useEffect(()=>{const te=window.setInterval(()=>{Re(!!window.__g7LayoutEditorHasSelection)},200);return()=>window.clearInterval(te)},[]),np({handlers:Qe,hasSelection:Me});const ve=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(Fa,{error:t.routesError})}):i.jsx("div",{className:"g7le-chrome","data-testid":"g7le-chrome",ref:Y,style:{position:"static",minHeight:"100vh",minWidth:jz,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(dy,{value:ve,children:[c&&a.needsHostPicker&&a.document&&i.jsx(SD,{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(by,{onSave:()=>{De()},isDirty:p.isDirty,onExit:re,onEditCode:ee,onManageImages:fe,onManageTranslations:K,onPageSettings:me,onReset:qe,onShowShortcuts:Pe,onPreview:Ce,onShowVersions:ze,templateName:k,templateVersion:_,templateList:E,onSwitchTemplate:U}),i.jsx(xE,{result:F,onDismiss:V,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(U4,{}),i.jsx(q4,{})]})]}),i.jsxs("div",{className:"g7le-chrome__body",style:{display:"grid",gridTemplateColumns:"auto 1fr",alignItems:"stretch"},children:[i.jsx(HE,{}),i.jsx(j4,{manifest:f,nesting:T,componentPalette:g?.componentPalette??null,spec:g,permissionCandidates:B,sampleGlobalSources:h,resolveRouteMatch:H,onNavigateToDestination:L,onSessionAddedPathsChange:P})]}),i.jsx(py,{})]})})}function yl(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=yl(n.children,t);if(o)return o}}return null}function Kz(e,t){return yl(e,t)!==null}function bl(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=bl(n.children,t);if(o)return o}}return null}function Vz(e,t,n){const o=[];Va({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;Qh({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 Oh({templateIdentifier:e,initialLocale:t}){return u.useEffect(()=>()=>{Vh(),qh(),Yh(),Xh(),Jh(),Zh(),Rh(),ey(),ty()},[]),i.jsx(ly,{templateIdentifier:e,initialLocale:t,children:i.jsx(uy,{children:i.jsx(Fz,{templateIdentifier:e})})})}if(typeof window<"u"){const e=window.G7Core||(window.G7Core={});if(e.__LayoutEditorChrome=Oh,typeof e.__onChromeReady=="function")try{e.__onChromeReady()}catch{}}dn.LayoutEditorChrome=Oh,Object.defineProperty(dn,Symbol.toStringTag,{value:"Module"})})(this.G7LayoutEditor=this.G7LayoutEditor||{},ReactJSXRuntime,React,ReactDOM); //# sourceMappingURL=layout-editor.min.js.map diff --git a/public/build/core/template-engine.min.js b/public/build/core/template-engine.min.js index 2ed3c647..06a956a5 100644 --- a/public/build/core/template-engine.min.js +++ b/public/build/core/template-engine.min.js @@ -1,20 +1,57 @@ -var lT=Object.defineProperty;var cT=(Yt,Xr,Jr)=>Xr in Yt?lT(Yt,Xr,{enumerable:!0,configurable:!0,writable:!0,value:Jr}):Yt[Xr]=Jr;var $=(Yt,Xr,Jr)=>cT(Yt,typeof Xr!="symbol"?Xr+"":Xr,Jr);(function(Yt){"use strict";function Xr(o,e){for(var n=0;na[i]})}}}return Object.freeze(Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}))}function Jr(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}var Ju={exports:{}},We={};var qg;function PS(){if(qg)return We;qg=1;var o=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),n=Symbol.for("react.fragment"),a=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"),g=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),b=Symbol.for("react.activity"),S=Symbol.iterator;function v(H){return H===null||typeof H!="object"?null:(H=S&&H[S]||H["@@iterator"],typeof H=="function"?H:null)}var _={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},A=Object.assign,x={};function L(H,T,ce){this.props=H,this.context=T,this.refs=x,this.updater=ce||_}L.prototype.isReactComponent={},L.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")},L.prototype.forceUpdate=function(H){this.updater.enqueueForceUpdate(this,H,"forceUpdate")};function M(){}M.prototype=L.prototype;function R(H,T,ce){this.props=H,this.context=T,this.refs=x,this.updater=ce||_}var D=R.prototype=new M;D.constructor=R,A(D,L.prototype),D.isPureReactComponent=!0;var B=Array.isArray;function q(){}var P={H:null,A:null,T:null,S:null},K=Object.prototype.hasOwnProperty;function ge(H,T,ce){var de=ce.ref;return{$$typeof:o,type:H,key:T,ref:de!==void 0?de:null,props:ce}}function Ee(H,T){return ge(H.type,T,H.props)}function Se(H){return typeof H=="object"&&H!==null&&H.$$typeof===o}function Ue(H){var T={"=":"=0",":":"=2"};return"$"+H.replace(/[=:]/g,function(ce){return T[ce]})}var Ve=/\/+/g;function qe(H,T){return typeof H=="object"&&H!==null&&H.key!=null?Ue(""+H.key):T.toString(36)}function St(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 J(H,T,ce,de,ye){var ie=typeof H;(ie==="undefined"||ie==="boolean")&&(H=null);var xe=!1;if(H===null)xe=!0;else switch(ie){case"bigint":case"string":case"number":xe=!0;break;case"object":switch(H.$$typeof){case o:case e:xe=!0;break;case m:return xe=H._init,J(xe(H._payload),T,ce,de,ye)}}if(xe)return ye=ye(H),xe=de===""?"."+qe(H,0):de,B(ye)?(ce="",xe!=null&&(ce=xe.replace(Ve,"$&/")+"/"),J(ye,T,ce,"",function($e){return $e})):ye!=null&&(Se(ye)&&(ye=Ee(ye,ce+(ye.key==null||H&&H.key===ye.key?"":(""+ye.key).replace(Ve,"$&/")+"/")+xe)),T.push(ye)),1;xe=0;var _e=de===""?".":de+":";if(B(H))for(var Te=0;Te>>1,pe=J[Z];if(0>>1;Zi(ce,Le))dei(ye,ce)?(J[Z]=ye,J[de]=Le,Z=de):(J[Z]=ce,J[T]=Le,Z=T);else if(dei(ye,Le))J[Z]=ye,J[de]=Le,Z=de;else break e}}return fe}function i(J,fe){var Le=J.sortIndex-fe.sortIndex;return Le!==0?Le:J.id-fe.id}if(o.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;o.unstable_now=function(){return l.now()}}else{var c=Date,d=c.now();o.unstable_now=function(){return c.now()-d}}var f=[],g=[],m=1,b=null,S=3,v=!1,_=!1,A=!1,x=!1,L=typeof setTimeout=="function"?setTimeout:null,M=typeof clearTimeout=="function"?clearTimeout:null,R=typeof setImmediate<"u"?setImmediate:null;function D(J){for(var fe=n(g);fe!==null;){if(fe.callback===null)a(g);else if(fe.startTime<=J)a(g),fe.sortIndex=fe.expirationTime,e(f,fe);else break;fe=n(g)}}function B(J){if(A=!1,D(J),!_)if(n(f)!==null)_=!0,q||(q=!0,Ue());else{var fe=n(g);fe!==null&&St(B,fe.startTime-J)}}var q=!1,P=-1,K=5,ge=-1;function Ee(){return x?!0:!(o.unstable_now()-geJ&&Ee());){var Z=b.callback;if(typeof Z=="function"){b.callback=null,S=b.priorityLevel;var pe=Z(b.expirationTime<=J);if(J=o.unstable_now(),typeof pe=="function"){b.callback=pe,D(J),fe=!0;break t}b===n(f)&&a(f),D(J)}else a(f);b=n(f)}if(b!==null)fe=!0;else{var H=n(g);H!==null&&St(B,H.startTime-J),fe=!1}}break e}finally{b=null,S=Le,v=!1}fe=void 0}}finally{fe?Ue():q=!1}}}var Ue;if(typeof R=="function")Ue=function(){R(Se)};else if(typeof MessageChannel<"u"){var Ve=new MessageChannel,qe=Ve.port2;Ve.port1.onmessage=Se,Ue=function(){qe.postMessage(null)}}else Ue=function(){L(Se,0)};function St(J,fe){P=L(function(){J(o.unstable_now())},fe)}o.unstable_IdlePriority=5,o.unstable_ImmediatePriority=1,o.unstable_LowPriority=4,o.unstable_NormalPriority=3,o.unstable_Profiling=null,o.unstable_UserBlockingPriority=2,o.unstable_cancelCallback=function(J){J.callback=null},o.unstable_forceFrameRate=function(J){0>J||125Z?(J.sortIndex=Le,e(g,J),n(f)===null&&J===n(g)&&(A?(M(P),P=-1):A=!0,St(B,Le-Z))):(J.sortIndex=pe,e(f,J),_||v||(_=!0,q||(q=!0,Ue()))),J},o.unstable_shouldYield=Ee,o.unstable_wrapCallback=function(J){var fe=S;return function(){var Le=S;S=fe;try{return J.apply(this,arguments)}finally{S=Le}}}})(td)),td}var Fg;function GS(){return Fg||(Fg=1,ed.exports=qS()),ed.exports}var nd={exports:{}},wn={};var Kg;function VS(){if(Kg)return wn;Kg=1;var o=Qu();function e(f){var g="https://react.dev/errors/"+f;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(o)}catch(e){console.error(e)}}return o(),nd.exports=VS(),nd.exports}var Xg;function FS(){if(Xg)return Xs;Xg=1;var o=GS(),e=Qu(),n=Yg();function a(t){var r="https://react.dev/errors/"+t;if(1pe||(t.current=Z[pe],Z[pe]=null,pe--)}function ce(t,r){pe++,Z[pe]=t.current,t.current=r}var de=H(null),ye=H(null),ie=H(null),xe=H(null);function _e(t,r){switch(ce(ie,r),ce(ye,t),ce(de,null),r.nodeType){case 9:case 11:t=(t=r.documentElement)&&(t=t.namespaceURI)?lS(t):0;break;default:if(t=r.tagName,r=r.namespaceURI)r=lS(r),t=cS(r,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}T(de),ce(de,t)}function Te(){T(de),T(ye),T(ie)}function $e(t){t.memoizedState!==null&&ce(xe,t);var r=de.current,s=cS(r,t.type);r!==s&&(ce(ye,t),ce(de,s))}function ht(t){ye.current===t&&(T(de),T(ye)),xe.current===t&&(T(xe),Tl._currentValue=Le)}var wt,kt;function ft(t){if(wt===void 0)try{throw Error()}catch(s){var r=s.stack.trim().match(/\n( *(at )?)/);wt=r&&r[1]||"",kt=-1Jr in Wt?qx(Wt,Jr,{enumerable:!0,configurable:!0,writable:!0,value:Qr}):Wt[Jr]=Qr;var $=(Wt,Jr,Qr)=>Gx(Wt,typeof Jr!="symbol"?Jr+"":Jr,Qr);(function(Wt){"use strict";function Jr(o,e){for(var r=0;ra[i]})}}}return Object.freeze(Object.defineProperty(o,Symbol.toStringTag,{value:"Module"}))}function Qr(o){return o&&o.__esModule&&Object.prototype.hasOwnProperty.call(o,"default")?o.default:o}var Ju={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 Lg;function IS(){if(Lg)return Ke;Lg=1;var o=Symbol.for("react.transitional.element"),e=Symbol.for("react.portal"),r=Symbol.for("react.fragment"),a=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"),g=Symbol.for("react.memo"),m=Symbol.for("react.lazy"),y=Symbol.for("react.activity"),w=Symbol.iterator;function S(H){return H===null||typeof H!="object"?null:(H=w&&H[w]||H["@@iterator"],typeof H=="function"?H:null)}var v={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},A=Object.assign,x={};function R(H,T,ge){this.props=H,this.context=T,this.refs=x,this.updater=ge||v}R.prototype.isReactComponent={},R.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")},R.prototype.forceUpdate=function(H){this.updater.enqueueForceUpdate(this,H,"forceUpdate")};function M(){}M.prototype=R.prototype;function O(H,T,ge){this.props=H,this.context=T,this.refs=x,this.updater=ge||v}var L=O.prototype=new M;L.constructor=O,A(L,R.prototype),L.isPureReactComponent=!0;var q=Array.isArray;function G(){}var B={H:null,A:null,T:null,S:null},K=Object.prototype.hasOwnProperty;function fe(H,T,ge){var de=ge.ref;return{$$typeof:o,type:H,key:T,ref:de!==void 0?de:null,props:ge}}function Ce(H,T){return fe(H.type,T,H.props)}function ke(H){return typeof H=="object"&&H!==null&&H.$$typeof===o}function Ue(H){var T={"=":"=0",":":"=2"};return"$"+H.replace(/[=:]/g,function(ge){return T[ge]})}var Pe=/\/+/g;function qe(H,T){return typeof H=="object"&&H!==null&&H.key!=null?Ue(""+H.key):T.toString(36)}function wt(H){switch(H.status){case"fulfilled":return H.value;case"rejected":throw H.reason;default:switch(typeof H.status=="string"?H.then(G,G):(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 J(H,T,ge,de,me){var ae=typeof H;(ae==="undefined"||ae==="boolean")&&(H=null);var Re=!1;if(H===null)Re=!0;else switch(ae){case"bigint":case"string":case"number":Re=!0;break;case"object":switch(H.$$typeof){case o:case e:Re=!0;break;case m:return Re=H._init,J(Re(H._payload),T,ge,de,me)}}if(Re)return me=me(H),Re=de===""?"."+qe(H,0):de,q(me)?(ge="",Re!=null&&(ge=Re.replace(Pe,"$&/")+"/"),J(me,T,ge,"",function(Ge){return Ge})):me!=null&&(ke(me)&&(me=Ce(me,ge+(me.key==null||H&&H.key===me.key?"":(""+me.key).replace(Pe,"$&/")+"/")+Re)),T.push(me)),1;Re=0;var ze=de===""?".":de+":";if(q(H))for(var $e=0;$e>>1,pe=J[Z];if(0>>1;Zi(ge,Ee))dei(me,ge)?(J[Z]=me,J[de]=Ee,Z=de):(J[Z]=ge,J[T]=Ee,Z=T);else if(dei(me,Ee))J[Z]=me,J[de]=Ee,Z=de;else break e}}return he}function i(J,he){var Ee=J.sortIndex-he.sortIndex;return Ee!==0?Ee:J.id-he.id}if(o.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var l=performance;o.unstable_now=function(){return l.now()}}else{var c=Date,d=c.now();o.unstable_now=function(){return c.now()-d}}var f=[],g=[],m=1,y=null,w=3,S=!1,v=!1,A=!1,x=!1,R=typeof setTimeout=="function"?setTimeout:null,M=typeof clearTimeout=="function"?clearTimeout:null,O=typeof setImmediate<"u"?setImmediate:null;function L(J){for(var he=r(g);he!==null;){if(he.callback===null)a(g);else if(he.startTime<=J)a(g),he.sortIndex=he.expirationTime,e(f,he);else break;he=r(g)}}function q(J){if(A=!1,L(J),!v)if(r(f)!==null)v=!0,G||(G=!0,Ue());else{var he=r(g);he!==null&&wt(q,he.startTime-J)}}var G=!1,B=-1,K=5,fe=-1;function Ce(){return x?!0:!(o.unstable_now()-feJ&&Ce());){var Z=y.callback;if(typeof Z=="function"){y.callback=null,w=y.priorityLevel;var pe=Z(y.expirationTime<=J);if(J=o.unstable_now(),typeof pe=="function"){y.callback=pe,L(J),he=!0;break t}y===r(f)&&a(f),L(J)}else a(f);y=r(f)}if(y!==null)he=!0;else{var H=r(g);H!==null&&wt(q,H.startTime-J),he=!1}}break e}finally{y=null,w=Ee,S=!1}he=void 0}}finally{he?Ue():G=!1}}}var Ue;if(typeof O=="function")Ue=function(){O(ke)};else if(typeof MessageChannel<"u"){var Pe=new MessageChannel,qe=Pe.port2;Pe.port1.onmessage=ke,Ue=function(){qe.postMessage(null)}}else Ue=function(){R(ke,0)};function wt(J,he){B=R(function(){J(o.unstable_now())},he)}o.unstable_IdlePriority=5,o.unstable_ImmediatePriority=1,o.unstable_LowPriority=4,o.unstable_NormalPriority=3,o.unstable_Profiling=null,o.unstable_UserBlockingPriority=2,o.unstable_cancelCallback=function(J){J.callback=null},o.unstable_forceFrameRate=function(J){0>J||125Z?(J.sortIndex=Ee,e(g,J),r(f)===null&&J===r(g)&&(A?(M(B),B=-1):A=!0,wt(q,Ee-Z))):(J.sortIndex=pe,e(f,J),v||S||(v=!0,G||(G=!0,Ue()))),J},o.unstable_shouldYield=Ce,o.unstable_wrapCallback=function(J){var he=w;return function(){var Ee=w;w=he;try{return J.apply(this,arguments)}finally{w=Ee}}}})(td)),td}var Ng;function jS(){return Ng||(Ng=1,ed.exports=HS()),ed.exports}var nd={exports:{}},vn={};/** + * @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 Ig;function zS(){if(Ig)return vn;Ig=1;var o=Qu();function e(f){var g="https://react.dev/errors/"+f;if(1"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(o)}catch(e){console.error(e)}}return o(),nd.exports=zS(),nd.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 zg;function US(){if(zg)return Qs;zg=1;var o=jS(),e=Qu(),r=jg();function a(t){var n="https://react.dev/errors/"+t;if(1pe||(t.current=Z[pe],Z[pe]=null,pe--)}function ge(t,n){pe++,Z[pe]=t.current,t.current=n}var de=H(null),me=H(null),ae=H(null),Re=H(null);function ze(t,n){switch(ge(ae,n),ge(me,t),ge(de,null),n.nodeType){case 9:case 11:t=(t=n.documentElement)&&(t=t.namespaceURI)?rS(t):0;break;default:if(t=n.tagName,n=n.namespaceURI)n=rS(n),t=aS(n,t);else switch(t){case"svg":t=1;break;case"math":t=2;break;default:t=0}}T(de),ge(de,t)}function $e(){T(de),T(me),T(ae)}function Ge(t){t.memoizedState!==null&&ge(Re,t);var n=de.current,s=aS(n,t.type);n!==s&&(ge(me,t),ge(de,s))}function At(t){me.current===t&&(T(de),T(me)),Re.current===t&&(T(Re),Il._currentValue=Ee)}var yt,dn;function Tt(t){if(yt===void 0)try{throw Error()}catch(s){var n=s.stack.trim().match(/\n( *(at )?)/);yt=n&&n[1]||"",dn=-1)":-1h||j[u]!==X[h]){var re=` -`+j[u].replace(" at new "," at ");return t.displayName&&re.includes("")&&(re=re.replace("",t.displayName)),re}while(1<=u&&0<=h);break}}}finally{nn=!1,Error.prepareStackTrace=s}return(s=t?t.displayName||t.name:"")?ft(s):""}function Nt(t,r){switch(t.tag){case 26:case 27:case 5:return ft(t.type);case 16:return ft("Lazy");case 13:return t.child!==r&&r!==null?ft("Suspense Fallback"):ft("Suspense");case 19:return ft("SuspenseList");case 0:case 15:return Ft(t.type,!1);case 11:return Ft(t.type.render,!1);case 1:return Ft(t.type,!0);case 31:return ft("Activity");default:return""}}function Br(t){try{var r="",s=null;do r+=Nt(t,s),s=t,t=t.return;while(t);return r}catch(u){return` +`+yt+t+dn}var Yt=!1;function ln(t,n){if(!t||Yt)return"";Yt=!0;var s=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var u={DetermineComponentFrameRoot:function(){try{if(n){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 p=u.DetermineComponentFrameRoot(),C=p[0],k=p[1];if(C&&k){var z=C.split(` +`),Y=k.split(` +`);for(h=u=0;uh||z[u]!==Y[h]){var ne=` +`+z[u].replace(" at new "," at ");return t.displayName&&ne.includes("")&&(ne=ne.replace("",t.displayName)),ne}while(1<=u&&0<=h);break}}}finally{Yt=!1,Error.prepareStackTrace=s}return(s=t?t.displayName||t.name:"")?Tt(s):""}function zt(t,n){switch(t.tag){case 26:case 27:case 5:return Tt(t.type);case 16:return Tt("Lazy");case 13:return t.child!==n&&n!==null?Tt("Suspense Fallback"):Tt("Suspense");case 19:return Tt("SuspenseList");case 0:case 15:return ln(t.type,!1);case 11:return ln(t.type.render,!1);case 1:return ln(t.type,!0);case 31:return Tt("Activity");default:return""}}function Tr(t){try{var n="",s=null;do n+=zt(t,s),s=t,t=t.return;while(t);return n}catch(u){return` Error generating stack: `+u.message+` -`+u.stack}}var fn=Object.prototype.hasOwnProperty,rn=o.unstable_scheduleCallback,hn=o.unstable_cancelCallback,Fn=o.unstable_shouldYield,Pr=o.unstable_requestPaint,Pt=o.unstable_now,wi=o.unstable_getCurrentPriorityLevel,na=o.unstable_ImmediatePriority,gn=o.unstable_UserBlockingPriority,Rn=o.unstable_NormalPriority,tt=o.unstable_LowPriority,$n=o.unstable_IdlePriority,pn=o.log,ra=o.unstable_setDisableYieldValue,ir=null,an=null;function En(t){if(typeof pn=="function"&&ra(t),an&&typeof an.setStrictMode=="function")try{an.setStrictMode(ir,t)}catch{}}var sn=Math.clz32?Math.clz32:ue,V=Math.log,se=Math.LN2;function ue(t){return t>>>=0,t===0?32:31-(V(t)/se|0)|0}var ee=256,ve=262144,he=4194304;function Ce(t){var r=t&42;if(r!==0)return r;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 Ae(t,r,s){var u=t.pendingLanes;if(u===0)return 0;var h=0,p=t.suspendedLanes,w=t.pingedLanes;t=t.warmLanes;var k=u&134217727;return k!==0?(u=k&~p,u!==0?h=Ce(u):(w&=k,w!==0?h=Ce(w):s||(s=k&~t,s!==0&&(h=Ce(s))))):(k=u&~p,k!==0?h=Ce(k):w!==0?h=Ce(w):s||(s=u&~t,s!==0&&(h=Ce(s)))),h===0?0:r!==0&&r!==h&&(r&p)===0&&(p=h&-h,s=r&-r,p>=s||p===32&&(s&4194048)!==0)?r:h}function Fe(t,r){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&r)===0}function Re(t,r){switch(t){case 1:case 2:case 4:case 8:case 64:return r+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 r+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 Ne(){var t=he;return he<<=1,(he&62914560)===0&&(he=4194304),t}function ke(t){for(var r=[],s=0;31>s;s++)r.push(t);return r}function Ze(t,r){t.pendingLanes|=r,r!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function ze(t,r,s,u,h,p){var w=t.pendingLanes;t.pendingLanes=s,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=s,t.entangledLanes&=s,t.errorRecoveryDisabledLanes&=s,t.shellSuspendCounter=0;var k=t.entanglements,j=t.expirationTimes,X=t.hiddenUpdates;for(s=w&~s;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var kf=/[\n"\\]/g;function In(t){return t.replace(kf,function(r){return"\\"+r.charCodeAt(0).toString(16)+" "})}function ms(t,r,s,u,h,p,w,k){t.name="",w!=null&&typeof w!="function"&&typeof w!="symbol"&&typeof w!="boolean"?t.type=w:t.removeAttribute("type"),r!=null?w==="number"?(r===0&&t.value===""||t.value!=r)&&(t.value=""+An(r)):t.value!==""+An(r)&&(t.value=""+An(r)):w!=="submit"&&w!=="reset"||t.removeAttribute("value"),r!=null?ia(t,w,An(r)):s!=null?ia(t,w,An(s)):u!=null&&t.removeAttribute("value"),h==null&&p!=null&&(t.defaultChecked=!!p),h!=null&&(t.checked=h&&typeof h!="function"&&typeof h!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?t.name=""+An(k):t.removeAttribute("name")}function _i(t,r,s,u,h,p,w,k){if(p!=null&&typeof p!="function"&&typeof p!="symbol"&&typeof p!="boolean"&&(t.type=p),r!=null||s!=null){if(!(p!=="submit"&&p!=="reset"||r!=null)){Io(t);return}s=s!=null?""+An(s):"",r=r!=null?""+An(r):s,k||r===t.value||(t.value=r),t.defaultValue=r}u=u??h,u=typeof u!="function"&&typeof u!="symbol"&&!!u,t.checked=k?t.checked:!!u,t.defaultChecked=!!u,w!=null&&typeof w!="function"&&typeof w!="symbol"&&typeof w!="boolean"&&(t.name=w),Io(t)}function ia(t,r,s){r==="number"&&za(t.ownerDocument)===t||t.defaultValue===""+s||(t.defaultValue=""+s)}function ja(t,r,s,u){if(t=t.options,r){r={};for(var h=0;h"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Bo=!1;if(Rr)try{var xi={};Object.defineProperty(xi,"passive",{get:function(){Bo=!0}}),window.addEventListener("test",xi,xi),window.removeEventListener("test",xi,xi)}catch{Bo=!1}var Vr=null,Po=null,bs=null;function Hc(){if(bs)return bs;var t,r=Po,s=r.length,u,h="value"in Vr?Vr.value:Vr.textContent,p=h.length;for(t=0;t=ne),Ke=" ",lt=!1;function gt(t,r){switch(t){case"keyup":return O.indexOf(r.keyCode)!==-1;case"keydown":return r.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function zt(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Dr=!1;function Kf(t,r){switch(t){case"compositionend":return zt(r);case"keypress":return r.which!==32?null:(lt=!0,Ke);case"textInput":return t=r.data,t===Ke&<?null:t;default:return null}}function Gc(t,r){if(Dr)return t==="compositionend"||!I&>(t,r)?(t=Hc(),bs=Po=Vr=null,Dr=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(r.ctrlKey||r.altKey||r.metaKey)||r.ctrlKey&&r.altKey){if(r.char&&1=r)return{node:s,offset:r-t};t=u}e:{for(;s;){if(s.nextSibling){s=s.nextSibling;break e}s=s.parentNode}s=void 0}s=xy(s)}}function Ry(t,r){return t&&r?t===r?!0:t&&t.nodeType===3?!1:r&&r.nodeType===3?Ry(t,r.parentNode):"contains"in t?t.contains(r):t.compareDocumentPosition?!!(t.compareDocumentPosition(r)&16):!1:!1}function ky(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var r=za(t.document);r instanceof t.HTMLIFrameElement;){try{var s=typeof r.contentWindow.location.href=="string"}catch{s=!1}if(s)t=r.contentWindow;else break;r=za(t.document)}return r}function Qf(t){var r=t&&t.nodeName&&t.nodeName.toLowerCase();return r&&(r==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||r==="textarea"||t.contentEditable==="true")}var BA=Rr&&"documentMode"in document&&11>=document.documentMode,Cs=null,Zf=null,Qo=null,eh=!1;function Dy(t,r,s){var u=s.window===s?s.document:s.nodeType===9?s:s.ownerDocument;eh||Cs==null||Cs!==za(u)||(u=Cs,"selectionStart"in u&&Qf(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}),Qo&&Jo(Qo,u)||(Qo=u,u=Iu(Zf,"onSelect"),0>=w,h-=w,Fr=1<<32-sn(r)+h|s<Je?(st=Ie,Ie=null):st=Ie.sibling;var mt=Q(F,Ie,Y[Je],oe);if(mt===null){Ie===null&&(Ie=st);break}t&&Ie&&mt.alternate===null&&r(F,Ie),G=p(mt,G,Je),pt===null?Be=mt:pt.sibling=mt,pt=mt,Ie=st}if(Je===Y.length)return s(F,Ie),ct&&ca(F,Je),Be;if(Ie===null){for(;JeJe?(st=Ie,Ie=null):st=Ie.sibling;var di=Q(F,Ie,mt.value,oe);if(di===null){Ie===null&&(Ie=st);break}t&&Ie&&di.alternate===null&&r(F,Ie),G=p(di,G,Je),pt===null?Be=di:pt.sibling=di,pt=di,Ie=st}if(mt.done)return s(F,Ie),ct&&ca(F,Je),Be;if(Ie===null){for(;!mt.done;Je++,mt=Y.next())mt=le(F,mt.value,oe),mt!==null&&(G=p(mt,G,Je),pt===null?Be=mt:pt.sibling=mt,pt=mt);return ct&&ca(F,Je),Be}for(Ie=u(Ie);!mt.done;Je++,mt=Y.next())mt=te(Ie,F,Je,mt.value,oe),mt!==null&&(t&&mt.alternate!==null&&Ie.delete(mt.key===null?Je:mt.key),G=p(mt,G,Je),pt===null?Be=mt:pt.sibling=mt,pt=mt);return t&&Ie.forEach(function(oT){return r(F,oT)}),ct&&ca(F,Je),Be}function Tt(F,G,Y,oe){if(typeof Y=="object"&&Y!==null&&Y.type===A&&Y.key===null&&(Y=Y.props.children),typeof Y=="object"&&Y!==null){switch(Y.$$typeof){case v:e:{for(var Be=Y.key;G!==null;){if(G.key===Be){if(Be=Y.type,Be===A){if(G.tag===7){s(F,G.sibling),oe=h(G,Y.props.children),oe.return=F,F=oe;break e}}else if(G.elementType===Be||typeof Be=="object"&&Be!==null&&Be.$$typeof===K&&Pi(Be)===G.type){s(F,G.sibling),oe=h(G,Y.props),al(oe,Y),oe.return=F,F=oe;break e}s(F,G);break}else r(F,G);G=G.sibling}Y.type===A?(oe=Hi(Y.props.children,F.mode,oe,Y.key),oe.return=F,F=oe):(oe=Zc(Y.type,Y.key,Y.props,null,F.mode,oe),al(oe,Y),oe.return=F,F=oe)}return w(F);case _:e:{for(Be=Y.key;G!==null;){if(G.key===Be)if(G.tag===4&&G.stateNode.containerInfo===Y.containerInfo&&G.stateNode.implementation===Y.implementation){s(F,G.sibling),oe=h(G,Y.children||[]),oe.return=F,F=oe;break e}else{s(F,G);break}else r(F,G);G=G.sibling}oe=oh(Y,F.mode,oe),oe.return=F,F=oe}return w(F);case K:return Y=Pi(Y),Tt(F,G,Y,oe)}if(St(Y))return De(F,G,Y,oe);if(Ue(Y)){if(Be=Ue(Y),typeof Be!="function")throw Error(a(150));return Y=Be.call(Y),Pe(F,G,Y,oe)}if(typeof Y.then=="function")return Tt(F,G,su(Y),oe);if(Y.$$typeof===R)return Tt(F,G,nu(F,Y),oe);ou(F,Y)}return typeof Y=="string"&&Y!==""||typeof Y=="number"||typeof Y=="bigint"?(Y=""+Y,G!==null&&G.tag===6?(s(F,G.sibling),oe=h(G,Y),oe.return=F,F=oe):(s(F,G),oe=sh(Y,F.mode,oe),oe.return=F,F=oe),w(F)):s(F,G)}return function(F,G,Y,oe){try{rl=0;var Be=Tt(F,G,Y,oe);return Ms=null,Be}catch(Ie){if(Ie===Ls||Ie===au)throw Ie;var pt=Wn(29,Ie,null,F.mode);return pt.lanes=oe,pt.return=F,pt}}}var Gi=Zy(!0),eb=Zy(!1),Wa=!1;function vh(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function Sh(t,r){t=t.updateQueue,r.updateQueue===t&&(r.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function Ya(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function Xa(t,r,s){var u=t.updateQueue;if(u===null)return null;if(u=u.shared,(bt&2)!==0){var h=u.pending;return h===null?r.next=r:(r.next=h.next,h.next=r),u.pending=r,r=Qc(t),Hy(t,null,s),r}return Jc(t,u,r,s),Qc(t)}function il(t,r,s){if(r=r.updateQueue,r!==null&&(r=r.shared,(s&4194048)!==0)){var u=r.lanes;u&=t.pendingLanes,s|=u,r.lanes=s,we(t,s)}}function wh(t,r){var s=t.updateQueue,u=t.alternate;if(u!==null&&(u=u.updateQueue,s===u)){var h=null,p=null;if(s=s.firstBaseUpdate,s!==null){do{var w={lane:s.lane,tag:s.tag,payload:s.payload,callback:null,next:null};p===null?h=p=w:p=p.next=w,s=s.next}while(s!==null);p===null?h=p=r:p=p.next=r}else h=p=r;s={baseState:u.baseState,firstBaseUpdate:h,lastBaseUpdate:p,shared:u.shared,callbacks:u.callbacks},t.updateQueue=s;return}t=s.lastBaseUpdate,t===null?s.firstBaseUpdate=r:t.next=r,s.lastBaseUpdate=r}var Ch=!1;function sl(){if(Ch){var t=Os;if(t!==null)throw t}}function ol(t,r,s,u){Ch=!1;var h=t.updateQueue;Wa=!1;var p=h.firstBaseUpdate,w=h.lastBaseUpdate,k=h.shared.pending;if(k!==null){h.shared.pending=null;var j=k,X=j.next;j.next=null,w===null?p=X:w.next=X,w=j;var re=t.alternate;re!==null&&(re=re.updateQueue,k=re.lastBaseUpdate,k!==w&&(k===null?re.firstBaseUpdate=X:k.next=X,re.lastBaseUpdate=j))}if(p!==null){var le=h.baseState;w=0,re=X=j=null,k=p;do{var Q=k.lane&-536870913,te=Q!==k.lane;if(te?(it&Q)===Q:(u&Q)===Q){Q!==0&&Q===Ds&&(Ch=!0),re!==null&&(re=re.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var De=t,Pe=k;Q=r;var Tt=s;switch(Pe.tag){case 1:if(De=Pe.payload,typeof De=="function"){le=De.call(Tt,le,Q);break e}le=De;break e;case 3:De.flags=De.flags&-65537|128;case 0:if(De=Pe.payload,Q=typeof De=="function"?De.call(Tt,le,Q):De,Q==null)break e;le=b({},le,Q);break e;case 2:Wa=!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},re===null?(X=re=te,j=le):re=re.next=te,w|=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);re===null&&(j=le),h.baseState=j,h.firstBaseUpdate=X,h.lastBaseUpdate=re,p===null&&(h.shared.lanes=0),ti|=w,t.lanes=w,t.memoizedState=le}}function tb(t,r){if(typeof t!="function")throw Error(a(191,t));t.call(r)}function nb(t,r){var s=t.callbacks;if(s!==null)for(t.callbacks=null,t=0;tp?p:8;var w=J.T,k={};J.T=k,Bh(t,!1,r,s);try{var j=h(),X=J.S;if(X!==null&&X(k,j),j!==null&&typeof j=="object"&&typeof j.then=="function"){var re=XA(j,u);ul(t,r,re,Zn(t))}else ul(t,r,u,Zn(t))}catch(le){ul(t,r,{then:function(){},status:"rejected",reason:le},Zn())}finally{fe.p=p,w!==null&&k.types!==null&&(w.types=k.types),J.T=w}}function nx(){}function jh(t,r,s,u){if(t.tag!==5)throw Error(a(476));var h=$b(t).queue;Mb(t,h,r,Le,s===null?nx:function(){return Nb(t),s(u)})}function $b(t){var r=t.memoizedState;if(r!==null)return r;r={memoizedState:Le,baseState:Le,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ha,lastRenderedState:Le},next:null};var s={};return r.next={memoizedState:s,baseState:s,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ha,lastRenderedState:s},next:null},t.memoizedState=r,t=t.alternate,t!==null&&(t.memoizedState=r),r}function Nb(t){var r=$b(t);r.next===null&&(r=t.alternate.memoizedState),ul(t,r.next.queue,{},Zn())}function Uh(){return bn(Tl)}function Ib(){return Wt().memoizedState}function Hb(){return Wt().memoizedState}function rx(t){for(var r=t.return;r!==null;){switch(r.tag){case 24:case 3:var s=Zn();t=Ya(s);var u=Xa(r,t,s);u!==null&&(Bn(u,r,s),il(u,r,s)),r={cache:ph()},t.payload=r;return}r=r.return}}function ax(t,r,s){var u=Zn();s={lane:u,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null},yu(t)?jb(r,s):(s=ah(t,r,s,u),s!==null&&(Bn(s,t,u),Ub(s,r,u)))}function zb(t,r,s){var u=Zn();ul(t,r,s,u)}function ul(t,r,s,u){var h={lane:u,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null};if(yu(t))jb(r,h);else{var p=t.alternate;if(t.lanes===0&&(p===null||p.lanes===0)&&(p=r.lastRenderedReducer,p!==null))try{var w=r.lastRenderedState,k=p(w,s);if(h.hasEagerState=!0,h.eagerState=k,Kn(k,w))return Jc(t,r,h,0),Rt===null&&Xc(),!1}catch{}if(s=ah(t,r,h,u),s!==null)return Bn(s,t,u),Ub(s,r,u),!0}return!1}function Bh(t,r,s,u){if(u={lane:2,revertLane:vg(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},yu(t)){if(r)throw Error(a(479))}else r=ah(t,s,u,2),r!==null&&Bn(r,t,2)}function yu(t){var r=t.alternate;return t===Xe||r!==null&&r===Xe}function jb(t,r){Ns=uu=!0;var s=t.pending;s===null?r.next=r:(r.next=s.next,s.next=r),t.pending=r}function Ub(t,r,s){if((s&4194048)!==0){var u=r.lanes;u&=t.pendingLanes,s|=u,r.lanes=s,we(t,s)}}var dl={readContext:bn,use:hu,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};dl.useEffectEvent=qt;var Bb={readContext:bn,use:hu,useCallback:function(t,r){return Dn().memoizedState=[t,r===void 0?null:r],t},useContext:bn,useEffect:_b,useImperativeHandle:function(t,r,s){s=s!=null?s.concat([t]):null,pu(4194308,4,Rb.bind(null,r,t),s)},useLayoutEffect:function(t,r){return pu(4194308,4,t,r)},useInsertionEffect:function(t,r){pu(4,2,t,r)},useMemo:function(t,r){var s=Dn();r=r===void 0?null:r;var u=t();if(Vi){En(!0);try{t()}finally{En(!1)}}return s.memoizedState=[u,r],u},useReducer:function(t,r,s){var u=Dn();if(s!==void 0){var h=s(r);if(Vi){En(!0);try{s(r)}finally{En(!1)}}}else h=r;return u.memoizedState=u.baseState=h,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:h},u.queue=t,t=t.dispatch=ax.bind(null,Xe,t),[u.memoizedState,t]},useRef:function(t){var r=Dn();return t={current:t},r.memoizedState=t},useState:function(t){t=$h(t);var r=t.queue,s=zb.bind(null,Xe,r);return r.dispatch=s,[t.memoizedState,s]},useDebugValue:Hh,useDeferredValue:function(t,r){var s=Dn();return zh(s,t,r)},useTransition:function(){var t=$h(!1);return t=Mb.bind(null,Xe,t.queue,!0,!1),Dn().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,r,s){var u=Xe,h=Dn();if(ct){if(s===void 0)throw Error(a(407));s=s()}else{if(s=r(),Rt===null)throw Error(a(349));(it&127)!==0||lb(u,r,s)}h.memoizedState=s;var p={value:s,getSnapshot:r};return h.queue=p,_b(ub.bind(null,u,p,t),[t]),u.flags|=2048,Hs(9,{destroy:void 0},cb.bind(null,u,p,s,r),null),s},useId:function(){var t=Dn(),r=Rt.identifierPrefix;if(ct){var s=Kr,u=Fr;s=(u&~(1<<32-sn(u)-1)).toString(32)+s,r="_"+r+"R_"+s,s=du++,0<\/script>",p=p.removeChild(p.firstChild);break;case"select":p=typeof u.is=="string"?w.createElement("select",{is:u.is}):w.createElement("select"),u.multiple?p.multiple=!0:u.size&&(p.size=u.size);break;default:p=typeof u.is=="string"?w.createElement(h,{is:u.is}):w.createElement(h)}}p[Ht]=r,p[_n]=u;e:for(w=r.child;w!==null;){if(w.tag===5||w.tag===6)p.appendChild(w.stateNode);else if(w.tag!==4&&w.tag!==27&&w.child!==null){w.child.return=w,w=w.child;continue}if(w===r)break e;for(;w.sibling===null;){if(w.return===null||w.return===r)break e;w=w.return}w.sibling.return=w.return,w=w.sibling}r.stateNode=p;e:switch(Sn(p,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&&pa(r)}}return Ot(r),tg(r,r.type,t===null?null:t.memoizedProps,r.pendingProps,s),null;case 6:if(t&&r.stateNode!=null)t.memoizedProps!==u&&pa(r);else{if(typeof u!="string"&&r.stateNode===null)throw Error(a(166));if(t=ie.current,Rs(r)){if(t=r.stateNode,s=r.memoizedProps,u=null,h=yn,h!==null)switch(h.tag){case 27:case 5:u=h.memoizedProps}t[Ht]=r,t=!!(t.nodeValue===s||u!==null&&u.suppressHydrationWarning===!0||sS(t.nodeValue,s)),t||Fa(r,!0)}else t=Hu(t).createTextNode(u),t[Ht]=r,r.stateNode=t}return Ot(r),null;case 31:if(s=r.memoizedState,t===null||t.memoizedState!==null){if(u=Rs(r),s!==null){if(t===null){if(!u)throw Error(a(318));if(t=r.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(a(557));t[Ht]=r}else zi(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Ot(r),t=!1}else s=dh(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=s),t=!0;if(!t)return r.flags&256?(Xn(r),r):(Xn(r),null);if((r.flags&128)!==0)throw Error(a(558))}return Ot(r),null;case 13:if(u=r.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(h=Rs(r),u!==null&&u.dehydrated!==null){if(t===null){if(!h)throw Error(a(318));if(h=r.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(a(317));h[Ht]=r}else zi(),(r.flags&128)===0&&(r.memoizedState=null),r.flags|=4;Ot(r),h=!1}else h=dh(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=h),h=!0;if(!h)return r.flags&256?(Xn(r),r):(Xn(r),null)}return Xn(r),(r.flags&128)!==0?(r.lanes=s,r):(s=u!==null,t=t!==null&&t.memoizedState!==null,s&&(u=r.child,h=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(h=u.alternate.memoizedState.cachePool.pool),p=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(p=u.memoizedState.cachePool.pool),p!==h&&(u.flags|=2048)),s!==t&&s&&(r.child.flags|=8192),Cu(r,r.updateQueue),Ot(r),null);case 4:return Te(),t===null&&Eg(r.stateNode.containerInfo),Ot(r),null;case 10:return da(r.type),Ot(r),null;case 19:if(T(Kt),u=r.memoizedState,u===null)return Ot(r),null;if(h=(r.flags&128)!==0,p=u.rendering,p===null)if(h)hl(u,!1);else{if(Gt!==0||t!==null&&(t.flags&128)!==0)for(t=r.child;t!==null;){if(p=cu(t),p!==null){for(r.flags|=128,hl(u,!1),t=p.updateQueue,r.updateQueue=t,Cu(r,t),r.subtreeFlags=0,t=s,s=r.child;s!==null;)zy(s,t),s=s.sibling;return ce(Kt,Kt.current&1|2),ct&&ca(r,u.treeForkCount),r.child}t=t.sibling}u.tail!==null&&Pt()>Tu&&(r.flags|=128,h=!0,hl(u,!1),r.lanes=4194304)}else{if(!h)if(t=cu(p),t!==null){if(r.flags|=128,h=!0,t=t.updateQueue,r.updateQueue=t,Cu(r,t),hl(u,!0),u.tail===null&&u.tailMode==="hidden"&&!p.alternate&&!ct)return Ot(r),null}else 2*Pt()-u.renderingStartTime>Tu&&s!==536870912&&(r.flags|=128,h=!0,hl(u,!1),r.lanes=4194304);u.isBackwards?(p.sibling=r.child,r.child=p):(t=u.last,t!==null?t.sibling=p:r.child=p,u.last=p)}return u.tail!==null?(t=u.tail,u.rendering=t,u.tail=t.sibling,u.renderingStartTime=Pt(),t.sibling=null,s=Kt.current,ce(Kt,h?s&1|2:s&1),ct&&ca(r,u.treeForkCount),t):(Ot(r),null);case 22:case 23:return Xn(r),_h(),u=r.memoizedState!==null,t!==null?t.memoizedState!==null!==u&&(r.flags|=8192):u&&(r.flags|=8192),u?(s&536870912)!==0&&(r.flags&128)===0&&(Ot(r),r.subtreeFlags&6&&(r.flags|=8192)):Ot(r),s=r.updateQueue,s!==null&&Cu(r,s.retryQueue),s=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(s=t.memoizedState.cachePool.pool),u=null,r.memoizedState!==null&&r.memoizedState.cachePool!==null&&(u=r.memoizedState.cachePool.pool),u!==s&&(r.flags|=2048),t!==null&&T(Bi),null;case 24:return s=null,t!==null&&(s=t.memoizedState.cache),r.memoizedState.cache!==s&&(r.flags|=2048),da(Jt),Ot(r),null;case 25:return null;case 30:return null}throw Error(a(156,r.tag))}function cx(t,r){switch(ch(r),r.tag){case 1:return t=r.flags,t&65536?(r.flags=t&-65537|128,r):null;case 3:return da(Jt),Te(),t=r.flags,(t&65536)!==0&&(t&128)===0?(r.flags=t&-65537|128,r):null;case 26:case 27:case 5:return ht(r),null;case 31:if(r.memoizedState!==null){if(Xn(r),r.alternate===null)throw Error(a(340));zi()}return t=r.flags,t&65536?(r.flags=t&-65537|128,r):null;case 13:if(Xn(r),t=r.memoizedState,t!==null&&t.dehydrated!==null){if(r.alternate===null)throw Error(a(340));zi()}return t=r.flags,t&65536?(r.flags=t&-65537|128,r):null;case 19:return T(Kt),null;case 4:return Te(),null;case 10:return da(r.type),null;case 22:case 23:return Xn(r),_h(),t!==null&&T(Bi),t=r.flags,t&65536?(r.flags=t&-65537|128,r):null;case 24:return da(Jt),null;case 25:return null;default:return null}}function dv(t,r){switch(ch(r),r.tag){case 3:da(Jt),Te();break;case 26:case 27:case 5:ht(r);break;case 4:Te();break;case 31:r.memoizedState!==null&&Xn(r);break;case 13:Xn(r);break;case 19:T(Kt);break;case 10:da(r.type);break;case 22:case 23:Xn(r),_h(),t!==null&&T(Bi);break;case 24:da(Jt)}}function gl(t,r){try{var s=r.updateQueue,u=s!==null?s.lastEffect:null;if(u!==null){var h=u.next;s=h;do{if((s.tag&t)===t){u=void 0;var p=s.create,w=s.inst;u=p(),w.destroy=u}s=s.next}while(s!==h)}}catch(k){Et(r,r.return,k)}}function Za(t,r,s){try{var u=r.updateQueue,h=u!==null?u.lastEffect:null;if(h!==null){var p=h.next;u=p;do{if((u.tag&t)===t){var w=u.inst,k=w.destroy;if(k!==void 0){w.destroy=void 0,h=r;var j=s,X=k;try{X()}catch(re){Et(h,j,re)}}}u=u.next}while(u!==p)}}catch(re){Et(r,r.return,re)}}function fv(t){var r=t.updateQueue;if(r!==null){var s=t.stateNode;try{nb(r,s)}catch(u){Et(t,t.return,u)}}}function hv(t,r,s){s.props=Fi(t.type,t.memoizedProps),s.state=t.memoizedState;try{s.componentWillUnmount()}catch(u){Et(t,r,u)}}function pl(t,r){try{var s=t.ref;if(s!==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 s=="function"?t.refCleanup=s(u):s.current=u}}catch(h){Et(t,r,h)}}function Wr(t,r){var s=t.ref,u=t.refCleanup;if(s!==null)if(typeof u=="function")try{u()}catch(h){Et(t,r,h)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof s=="function")try{s(null)}catch(h){Et(t,r,h)}else s.current=null}function gv(t){var r=t.type,s=t.memoizedProps,u=t.stateNode;try{e:switch(r){case"button":case"input":case"select":case"textarea":s.autoFocus&&u.focus();break e;case"img":s.src?u.src=s.src:s.srcSet&&(u.srcset=s.srcSet)}}catch(h){Et(t,t.return,h)}}function ng(t,r,s){try{var u=t.stateNode;Ox(u,t.type,s,r),u[_n]=r}catch(h){Et(t,t.return,h)}}function pv(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&si(t.type)||t.tag===4}function rg(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||pv(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&&si(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 ag(t,r,s){var u=t.tag;if(u===5||u===6)t=t.stateNode,r?(s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s).insertBefore(t,r):(r=s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s,r.appendChild(t),s=s._reactRootContainer,s!=null||r.onclick!==null||(r.onclick=Tr));else if(u!==4&&(u===27&&si(t.type)&&(s=t.stateNode,r=null),t=t.child,t!==null))for(ag(t,r,s),t=t.sibling;t!==null;)ag(t,r,s),t=t.sibling}function Eu(t,r,s){var u=t.tag;if(u===5||u===6)t=t.stateNode,r?s.insertBefore(t,r):s.appendChild(t);else if(u!==4&&(u===27&&si(t.type)&&(s=t.stateNode),t=t.child,t!==null))for(Eu(t,r,s),t=t.sibling;t!==null;)Eu(t,r,s),t=t.sibling}function mv(t){var r=t.stateNode,s=t.memoizedProps;try{for(var u=t.type,h=r.attributes;h.length;)r.removeAttributeNode(h[0]);Sn(r,u,s),r[Ht]=t,r[_n]=s}catch(p){Et(t,t.return,p)}}var ma=!1,en=!1,ig=!1,yv=typeof WeakSet=="function"?WeakSet:Set,dn=null;function ux(t,r){if(t=t.containerInfo,xg=Gu,t=ky(t),Qf(t)){if("selectionStart"in t)var s={start:t.selectionStart,end:t.selectionEnd};else e:{s=(s=t.ownerDocument)&&s.defaultView||window;var u=s.getSelection&&s.getSelection();if(u&&u.rangeCount!==0){s=u.anchorNode;var h=u.anchorOffset,p=u.focusNode;u=u.focusOffset;try{s.nodeType,p.nodeType}catch{s=null;break e}var w=0,k=-1,j=-1,X=0,re=0,le=t,Q=null;t:for(;;){for(var te;le!==s||h!==0&&le.nodeType!==3||(k=w+h),le!==p||u!==0&&le.nodeType!==3||(j=w+u),le.nodeType===3&&(w+=le.nodeValue.length),(te=le.firstChild)!==null;)Q=le,le=te;for(;;){if(le===t)break t;if(Q===s&&++X===h&&(k=w),Q===p&&++re===u&&(j=w),(te=le.nextSibling)!==null)break;le=Q,Q=le.parentNode}le=te}s=k===-1||j===-1?null:{start:k,end:j}}else s=null}s=s||{start:0,end:0}}else s=null;for(Tg={focusedElem:t,selectionRange:s},Gu=!1,dn=r;dn!==null;)if(r=dn,t=r.child,(r.subtreeFlags&1028)!==0&&t!==null)t.return=r,dn=t;else for(;dn!==null;){switch(r=dn,p=r.alternate,t=r.flags,r.tag){case 0:if((t&4)!==0&&(t=r.updateQueue,t=t!==null?t.events:null,t!==null))for(s=0;s title"))),Sn(p,u,s),p[Ht]=t,Xt(p),u=p;break e;case"link":var w=ES("link","href",h).get(u+(s.href||""));if(w){for(var k=0;kTt&&(w=Tt,Tt=Pe,Pe=w);var F=Ty(k,Pe),G=Ty(k,Tt);if(F&&G&&(te.rangeCount!==1||te.anchorNode!==F.node||te.anchorOffset!==F.offset||te.focusNode!==G.node||te.focusOffset!==G.offset)){var Y=le.createRange();Y.setStart(F.node,F.offset),te.removeAllRanges(),Pe>Tt?(te.addRange(Y),te.extend(G.node,G.offset)):(Y.setEnd(G.node,G.offset),te.addRange(Y))}}}}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;ks?32:s,J.T=null,s=fg,fg=null;var p=ri,w=wa;if(ln=0,Ps=ri=null,wa=0,(bt&6)!==0)throw Error(a(331));var k=bt;if(bt|=4,Rv(p.current),Av(p,p.current,w,s),bt=k,wl(0,!1),an&&typeof an.onPostCommitFiberRoot=="function")try{an.onPostCommitFiberRoot(ir,p)}catch{}return!0}finally{fe.p=h,J.T=u,Fv(t,r)}}function Wv(t,r,s){r=lr(s,r),r=Vh(t.stateNode,r,2),t=Xa(t,r,2),t!==null&&(Ze(t,2),Yr(t))}function Et(t,r,s){if(t.tag===3)Wv(t,t,s);else for(;r!==null;){if(r.tag===3){Wv(r,t,s);break}else if(r.tag===1){var u=r.stateNode;if(typeof r.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ni===null||!ni.has(u))){t=lr(s,t),s=Yb(2),u=Xa(r,s,2),u!==null&&(Xb(s,u,r,t),Ze(u,2),Yr(u));break}}r=r.return}}function mg(t,r,s){var u=t.pingCache;if(u===null){u=t.pingCache=new hx;var h=new Set;u.set(r,h)}else h=u.get(r),h===void 0&&(h=new Set,u.set(r,h));h.has(s)||(lg=!0,h.add(s),t=bx.bind(null,t,r,s),r.then(t,t))}function bx(t,r,s){var u=t.pingCache;u!==null&&u.delete(r),t.pingedLanes|=t.suspendedLanes&s,t.warmLanes&=~s,Rt===t&&(it&s)===s&&(Gt===4||Gt===3&&(it&62914560)===it&&300>Pt()-xu?(bt&2)===0&&qs(t,0):cg|=s,Bs===it&&(Bs=0)),Yr(t)}function Yv(t,r){r===0&&(r=Ne()),t=Ii(t,r),t!==null&&(Ze(t,r),Yr(t))}function vx(t){var r=t.memoizedState,s=0;r!==null&&(s=r.retryLane),Yv(t,s)}function Sx(t,r){var s=0;switch(t.tag){case 31:case 13:var u=t.stateNode,h=t.memoizedState;h!==null&&(s=h.retryLane);break;case 19:u=t.stateNode;break;case 22:u=t.stateNode._retryCache;break;default:throw Error(a(314))}u!==null&&u.delete(r),Yv(t,s)}function wx(t,r){return rn(t,r)}var Mu=null,Vs=null,yg=!1,$u=!1,bg=!1,ii=0;function Yr(t){t!==Vs&&t.next===null&&(Vs===null?Mu=Vs=t:Vs=Vs.next=t),$u=!0,yg||(yg=!0,Ex())}function wl(t,r){if(!bg&&$u){bg=!0;do for(var s=!1,u=Mu;u!==null;){if(t!==0){var h=u.pendingLanes;if(h===0)var p=0;else{var w=u.suspendedLanes,k=u.pingedLanes;p=(1<<31-sn(42|t)+1)-1,p&=h&~(w&~k),p=p&201326741?p&201326741|1:p?p|2:0}p!==0&&(s=!0,Zv(u,p))}else p=it,p=Ae(u,u===Rt?p:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(p&3)===0||Fe(u,p)||(s=!0,Zv(u,p));u=u.next}while(s);bg=!1}}function Cx(){Xv()}function Xv(){$u=yg=!1;var t=0;ii!==0&&Mx()&&(t=ii);for(var r=Pt(),s=null,u=Mu;u!==null;){var h=u.next,p=Jv(u,r);p===0?(u.next=null,s===null?Mu=h:s.next=h,h===null&&(Vs=s)):(s=u,(t!==0||(p&3)!==0)&&($u=!0)),u=h}ln!==0&&ln!==5||wl(t),ii!==0&&(ii=0)}function Jv(t,r){for(var s=t.suspendedLanes,u=t.pingedLanes,h=t.expirationTimes,p=t.pendingLanes&-62914561;0k)break;var re=j.transferSize,le=j.initiatorType;re&&oS(le)&&(j=j.responseEnd,w+=re*(j"u"?null:document;function vS(t,r,s){var u=Fs;if(u&&typeof r=="string"&&r){var h=In(r);h='link[rel="'+t+'"][href="'+h+'"]',typeof s=="string"&&(h+='[crossorigin="'+s+'"]'),bS.has(h)||(bS.add(h),t={rel:t,crossOrigin:s,href:r},u.querySelector(h)===null&&(r=u.createElement("link"),Sn(r,"link",t),Xt(r),u.head.appendChild(r)))}}function Px(t){Ca.D(t),vS("dns-prefetch",t,null)}function qx(t,r){Ca.C(t,r),vS("preconnect",t,r)}function Gx(t,r,s){Ca.L(t,r,s);var u=Fs;if(u&&t&&r){var h='link[rel="preload"][as="'+In(r)+'"]';r==="image"&&s&&s.imageSrcSet?(h+='[imagesrcset="'+In(s.imageSrcSet)+'"]',typeof s.imageSizes=="string"&&(h+='[imagesizes="'+In(s.imageSizes)+'"]')):h+='[href="'+In(t)+'"]';var p=h;switch(r){case"style":p=Ks(t);break;case"script":p=Ws(t)}gr.has(p)||(t=b({rel:"preload",href:r==="image"&&s&&s.imageSrcSet?void 0:t,as:r},s),gr.set(p,t),u.querySelector(h)!==null||r==="style"&&u.querySelector(Al(p))||r==="script"&&u.querySelector(xl(p))||(r=u.createElement("link"),Sn(r,"link",t),Xt(r),u.head.appendChild(r)))}}function Vx(t,r){Ca.m(t,r);var s=Fs;if(s&&t){var u=r&&typeof r.as=="string"?r.as:"script",h='link[rel="modulepreload"][as="'+In(u)+'"][href="'+In(t)+'"]',p=h;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":p=Ws(t)}if(!gr.has(p)&&(t=b({rel:"modulepreload",href:t},r),gr.set(p,t),s.querySelector(h)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(s.querySelector(xl(p)))return}u=s.createElement("link"),Sn(u,"link",t),Xt(u),s.head.appendChild(u)}}}function Fx(t,r,s){Ca.S(t,r,s);var u=Fs;if(u&&t){var h=Ia(u).hoistableStyles,p=Ks(t);r=r||"default";var w=h.get(p);if(!w){var k={loading:0,preload:null};if(w=u.querySelector(Al(p)))k.loading=5;else{t=b({rel:"stylesheet",href:t,"data-precedence":r},s),(s=gr.get(p))&&$g(t,s);var j=w=u.createElement("link");Xt(j),Sn(j,"link",t),j._p=new Promise(function(X,re){j.onload=X,j.onerror=re}),j.addEventListener("load",function(){k.loading|=1}),j.addEventListener("error",function(){k.loading|=2}),k.loading|=4,ju(w,r,u)}w={type:"stylesheet",instance:w,count:1,state:k},h.set(p,w)}}}function Kx(t,r){Ca.X(t,r);var s=Fs;if(s&&t){var u=Ia(s).hoistableScripts,h=Ws(t),p=u.get(h);p||(p=s.querySelector(xl(h)),p||(t=b({src:t,async:!0},r),(r=gr.get(h))&&Ng(t,r),p=s.createElement("script"),Xt(p),Sn(p,"link",t),s.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},u.set(h,p))}}function Wx(t,r){Ca.M(t,r);var s=Fs;if(s&&t){var u=Ia(s).hoistableScripts,h=Ws(t),p=u.get(h);p||(p=s.querySelector(xl(h)),p||(t=b({src:t,async:!0,type:"module"},r),(r=gr.get(h))&&Ng(t,r),p=s.createElement("script"),Xt(p),Sn(p,"link",t),s.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},u.set(h,p))}}function SS(t,r,s,u){var h=(h=ie.current)?zu(h):null;if(!h)throw Error(a(446));switch(t){case"meta":case"title":return null;case"style":return typeof s.precedence=="string"&&typeof s.href=="string"?(r=Ks(s.href),s=Ia(h).hoistableStyles,u=s.get(r),u||(u={type:"style",instance:null,count:0,state:null},s.set(r,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(s.rel==="stylesheet"&&typeof s.href=="string"&&typeof s.precedence=="string"){t=Ks(s.href);var p=Ia(h).hoistableStyles,w=p.get(t);if(w||(h=h.ownerDocument||h,w={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},p.set(t,w),(p=h.querySelector(Al(t)))&&!p._p&&(w.instance=p,w.state.loading=5),gr.has(t)||(s={rel:"preload",as:"style",href:s.href,crossOrigin:s.crossOrigin,integrity:s.integrity,media:s.media,hrefLang:s.hrefLang,referrerPolicy:s.referrerPolicy},gr.set(t,s),p||Yx(h,t,s,w.state))),r&&u===null)throw Error(a(528,""));return w}if(r&&u!==null)throw Error(a(529,""));return null;case"script":return r=s.async,s=s.src,typeof s=="string"&&r&&typeof r!="function"&&typeof r!="symbol"?(r=Ws(s),s=Ia(h).hoistableScripts,u=s.get(r),u||(u={type:"script",instance:null,count:0,state:null},s.set(r,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(a(444,t))}}function Ks(t){return'href="'+In(t)+'"'}function Al(t){return'link[rel="stylesheet"]['+t+"]"}function wS(t){return b({},t,{"data-precedence":t.precedence,precedence:null})}function Yx(t,r,s,u){t.querySelector('link[rel="preload"][as="style"]['+r+"]")?u.loading=1:(r=t.createElement("link"),u.preload=r,r.addEventListener("load",function(){return u.loading|=1}),r.addEventListener("error",function(){return u.loading|=2}),Sn(r,"link",s),Xt(r),t.head.appendChild(r))}function Ws(t){return'[src="'+In(t)+'"]'}function xl(t){return"script[async]"+t}function CS(t,r,s){if(r.count++,r.instance===null)switch(r.type){case"style":var u=t.querySelector('style[data-href~="'+In(s.href)+'"]');if(u)return r.instance=u,Xt(u),u;var h=b({},s,{"data-href":s.href,"data-precedence":s.precedence,href:null,precedence:null});return u=(t.ownerDocument||t).createElement("style"),Xt(u),Sn(u,"style",h),ju(u,s.precedence,t),r.instance=u;case"stylesheet":h=Ks(s.href);var p=t.querySelector(Al(h));if(p)return r.state.loading|=4,r.instance=p,Xt(p),p;u=wS(s),(h=gr.get(h))&&$g(u,h),p=(t.ownerDocument||t).createElement("link"),Xt(p);var w=p;return w._p=new Promise(function(k,j){w.onload=k,w.onerror=j}),Sn(p,"link",u),r.state.loading|=4,ju(p,s.precedence,t),r.instance=p;case"script":return p=Ws(s.src),(h=t.querySelector(xl(p)))?(r.instance=h,Xt(h),h):(u=s,(h=gr.get(p))&&(u=b({},s),Ng(u,h)),t=t.ownerDocument||t,h=t.createElement("script"),Xt(h),Sn(h,"link",u),t.head.appendChild(h),r.instance=h);case"void":return null;default:throw Error(a(443,r.type))}else r.type==="stylesheet"&&(r.state.loading&4)===0&&(u=r.instance,r.state.loading|=4,ju(u,s.precedence,t));return r.instance}function ju(t,r,s){for(var u=s.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),h=u.length?u[u.length-1]:null,p=h,w=0;w title"):null)}function Xx(t,r,s){if(s===1||r.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof r.precedence!="string"||typeof r.href!="string"||r.href==="")break;return!0;case"link":if(typeof r.rel!="string"||typeof r.href!="string"||r.href===""||r.onLoad||r.onError)break;return r.rel==="stylesheet"?(t=r.disabled,typeof r.precedence=="string"&&t==null):!0;case"script":if(r.async&&typeof r.async!="function"&&typeof r.async!="symbol"&&!r.onLoad&&!r.onError&&r.src&&typeof r.src=="string")return!0}return!1}function AS(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function Jx(t,r,s,u){if(s.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(s.state.loading&4)===0){if(s.instance===null){var h=Ks(u.href),p=r.querySelector(Al(h));if(p){r=p._p,r!==null&&typeof r=="object"&&typeof r.then=="function"&&(t.count++,t=Bu.bind(t),r.then(t,t)),s.state.loading|=4,s.instance=p,Xt(p);return}p=r.ownerDocument||r,u=wS(u),(h=gr.get(h))&&$g(u,h),p=p.createElement("link"),Xt(p);var w=p;w._p=new Promise(function(k,j){w.onload=k,w.onerror=j}),Sn(p,"link",u),s.instance=p}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(s,r),(r=s.state.preload)&&(s.state.loading&3)===0&&(t.count++,s=Bu.bind(t),r.addEventListener("load",s),r.addEventListener("error",s))}}var Ig=0;function Qx(t,r){return t.stylesheets&&t.count===0&&qu(t,t.stylesheets),0Ig?50:800)+r);return t.unsuspend=s,function(){t.unsuspend=null,clearTimeout(u),clearTimeout(h)}}:null}function Bu(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)qu(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var Pu=null;function qu(t,r){t.stylesheets=null,t.unsuspend!==null&&(t.count++,Pu=new Map,r.forEach(Zx,t),Pu=null,Bu.call(t))}function Zx(t,r){if(!(r.state.loading&4)){var s=Pu.get(t);if(s)var u=s.get(null);else{s=new Map,Pu.set(t,s);for(var h=t.querySelectorAll("link[data-precedence],style[data-precedence]"),p=0;p"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(o)}catch(e){console.error(e)}}return o(),Zu.exports=FS(),Zu.exports}var rd=KS();const ad=Jr(rd),Js=[],WS=50;let id=!1;function Qg(){try{return window.G7Core?.devTools}catch{return}}function Yi(o,e,n){const a=Qg();if(id&&a?.isEnabled?.()){a.trackLog?.(o,e,n);return}id||(o==="error"||o==="warn")&&Js.length{n.isDebugEnabled()&&console.log(e,...a),Yi("log",o,a)},warn:(...a)=>{n.isDebugEnabled()&&console.warn(e,...a),Yi("warn",o,a)},error:(...a)=>{n.isDebugEnabled()&&console.error(e,...a),Yi("error",o,a)}}}Qs.getInstance();const Xi=ut("networkResilience"),Zg=2,ep=300,tp=2e3,YS=15e3;function od(o){return o?.name==="AbortError"}function np(o){return od(o)?!1:o instanceof TypeError}let Ol=!1,rp=!1;function ld(){return Ol}function XS(){typeof window>"u"||rp||(rp=!0,window.addEventListener("pagehide",()=>{Ol=!0}),window.addEventListener("pageshow",o=>{o.persisted&&(Ol=!1)}),window.addEventListener("beforeunload",()=>{Ol=!0}))}function ap(o,e,n){const a=Math.min(e*Math.pow(2,o),n),i=a*.25*(Math.random()*2-1);return Math.max(0,Math.round(a+i))}function ip(o){return new Promise(e=>setTimeout(e,o))}async function Ll(o,e={}){const{retries:n=Zg,baseDelayMs:a=ep,maxDelayMs:i=tp,timeoutMs:l=YS,label:c=o,init:d}=e,f=n+1;let g;for(let m=0;m0?new AbortController:null;try{const _={...d};if(v){const x=d?.signal;x&&(x.aborted?v.abort():x.addEventListener("abort",()=>v.abort(),{once:!0})),_.signal=v.signal,S=setTimeout(()=>{b=!0,v.abort()},l)}return await fetch(o,_)}catch(_){if(g=_,od(_)&&!b||!(b||np(_)))throw _;if(ld())throw Xi.warn(`Document unloading, aborting retries: ${c}`),_;if(m===f-1)throw Xi.warn(`All ${f} attempts failed: ${c}`,_),_;const L=ap(m,a,i);Xi.warn(`Network failure (attempt ${m+1}/${f}), retrying in ${L}ms: ${c}`),await ip(L)}finally{S!==void 0&&clearTimeout(S)}}throw g}async function sp(o,e={},n={}){const{retries:a=Zg,baseDelayMs:i=ep,maxDelayMs:l=tp,label:c=o}=n,d=a+1;for(let f=0;f{const i=document.createElement("script");i.src=o,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=()=>a(new Error(`Failed to load script: ${o}`)),document.head.appendChild(i)})}const op="extension",Ji="extensionless",QS="file";function ZS(){const o=globalThis?.G7Config;if(globalThis?.__g7AssetUrlMode===Ji)return Ji;const n=o?.assetUrlMode;return n===Ji||n===op?n:o?.settings?.general?.asset_url_mode===Ji?Ji:op}function lp(){return ZS()===Ji}function $r(o,e,n,a){const i=o.replace(/\/+$/,""),l=e.replace(/^\.+/,""),c=lp()?i:`${i}.${l}`,d=[];return a&&d.push(a.replace(/^[?&]+/,"")),n!=null&&n!==""&&d.push(`v=${n}`),d.length>0?`${c}?${d.join("&")}`:c}function Ea(o){if(!o||!lp())return o;const e=globalThis?.location?.origin,n=e&&o.startsWith(e)?o.slice(e.length):o;if(!n.startsWith("/api/"))return o;const[a,i]=ew(n),l=a.match(/^\/api\/(modules|plugins)\/bundle\.(js|css)$/);if(l)return cp(`/api/${l[1]}/bundle/${l[2]}`,i);const c=a.match(/^\/api\/(templates|modules|plugins)\/assets\/([^/]+)\/(.+)$/);if(c){const[,f,g,m]=c,b=`${QS}=${encodeURIComponent(decodeURIComponent(m))}`;return`/api/${f}/assets/${g}?${b}${i?`&${i}`:""}`}const d=a.match(/^(\/api\/.+)\.(json|js|css)$/);return d?cp(d[1],i):o}function ew(o){const e=o.indexOf("?");return e===-1?[o,""]:[o.slice(0,e),o.slice(e+1)]}function cp(o,e){return e?`${o}?${e}`:o}const Nr=ut("ComponentRegistry");class cn extends Error{constructor(n,a,i){super(n);$(this,"code");$(this,"details");this.code=a,this.details=i,this.name="ComponentRegistryError"}}const Vn=class Vn{constructor(){$(this,"registry",{});$(this,"manifest",null);$(this,"loadingState","idle");$(this,"error",null);$(this,"templateId",null);$(this,"templateType",null)}static getInstance(){return Vn.instance||(Vn.instance=new Vn),Vn.instance}static createIsolatedInstance(){return new Vn}static resetInstance(){Vn.instance=null}async loadComponents(e,n){if(this.loadingState==="loading")throw new cn("Components are already being loaded","LOADING_IN_PROGRESS");if(this.loadingState==="loaded"&&this.templateId===e&&this.templateType===n){Nr.log("Components already loaded for template:",e,n);return}this.loadingState="loading",this.templateId=e,this.templateType=n,this.error=null;try{await this.loadManifest(),await this.loadComponentBundle(),this.loadingState="loaded",Nr.log("Successfully loaded components:",Object.keys(this.registry).length)}catch(a){throw this.loadingState="error",this.error=a instanceof Error?a:new Error(String(a)),new cn(`Failed to load components: ${this.error.message}`,"LOAD_FAILED",{originalError:this.error})}}async loadManifest(){try{if(!this.templateId)throw new cn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=`${this.templateId}:${this.templateType}`;if(Vn.manifestCache.has(e)){this.manifest=Vn.manifestCache.get(e),Nr.log("Manifest loaded from cache:",this.manifest.templateId);return}const n=$r(`/api/templates/${this.templateId}/components`,"json"),a=await Ll(n,{label:"components.json"});if(!a.ok)throw new cn(`Failed to fetch manifest: ${a.status} ${a.statusText}`,"MANIFEST_FETCH_FAILED",{status:a.status,statusText:a.statusText});const i=await a.json();this.validateManifest(i),this.manifest=i,Vn.manifestCache.set(e,i),Nr.log("Manifest loaded and cached:",i.templateId)}catch(e){throw e instanceof cn?e:new cn("Failed to load component manifest","MANIFEST_LOAD_FAILED",{originalError:e})}}validateManifest(e){if(!e.version)throw new cn("Manifest missing required field: version","MANIFEST_INVALID",{field:"version"});if(!e.templateId)throw new cn("Manifest missing required field: templateId","MANIFEST_INVALID",{field:"templateId"});if(!e.components||typeof e.components!="object")throw new cn("Manifest missing required field: components","MANIFEST_INVALID",{field:"components"});const n=["basic","composite","layout"];for(const a of n){if(!Array.isArray(e.components[a]))throw new cn(`Manifest field 'components.${a}' must be an array`,"MANIFEST_INVALID",{field:`components.${a}`,value:e.components[a]});e.components[a].forEach((i,l)=>{if(!i.name||typeof i.name!="string")throw new cn(`Invalid component metadata at ${a}[${l}]: missing or invalid 'name'`,"MANIFEST_INVALID",{type:a,index:l,metadata:i});if(!i.type||typeof i.type!="string")throw new cn(`Invalid component metadata at ${a}[${l}]: missing or invalid 'type'`,"MANIFEST_INVALID",{type:a,index:l,metadata:i})})}Nr.log("Manifest validation passed")}async loadComponentBundle(){try{if(!this.templateId)throw new cn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=this.getGlobalVariableName(),n=window[e];if(!n||typeof n!="object")throw new cn(`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),Nr.log("Component bundle loaded from global variable:",e)}catch(e){throw e instanceof cn?e:new cn("Failed to load component bundle","BUNDLE_LOAD_FAILED",{originalError:e})}}getGlobalVariableName(){if(!this.templateId)throw new cn("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 cn("Manifest not loaded","MANIFEST_NOT_LOADED");const n=["basic","composite","layout"];for(const a of n){const i=this.manifest.components[a]||[];for(const l of i){const c=l.name,d=e[c];if(!d){Nr.warn(`Component '${c}' not found in bundle`);continue}this.registerComponent(c,d,l)}}}registerComponent(e,n,a){this.registry[e]&&Nr.warn(`Component '${e}' already registered, overwriting`);const i=Ye.memo(n);this.registry[e]={component:i,metadata:a},Nr.log(`[ComponentRegistry] Registered component: ${e} (${a.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,a])=>a.metadata.type===e).map(([n,a])=>n)}getAllComponents(){return Object.keys(this.registry)}getComponentMap(){const e={};for(const[n,a]of Object.entries(this.registry))e[n]=a.component;return e}getLoadingState(){return this.loadingState}getError(){return this.error}getTemplateId(){return this.templateId}getManifest(){return this.manifest}clear(){this.registry={},this.manifest=null,this.loadingState="idle",this.error=null,this.templateId=null,this.templateType=null,Nr.log("Registry cleared")}};$(Vn,"instance",null),$(Vn,"manifestCache",new Map);let pr=Vn;const up=ut("TranslationEngine");class cd extends Error{constructor(n,a,i){super(n);$(this,"key");$(this,"locale");this.key=a,this.locale=i,this.name="TranslationError"}}const Mn=class Mn{constructor(e={}){$(this,"cache",new Map);$(this,"translations",new Map);$(this,"options");$(this,"cacheVersion",0);this.options={defaultLocale:e.defaultLocale||"ko",fallbackLocale:e.fallbackLocale||"en",cacheTTL:e.cacheTTL||3e5}}static getInstance(e={}){return Mn.instance||(Mn.instance=new Mn(e)),Mn.instance}static resetInstance(){Mn.instance=null}setCacheVersion(e){this.cacheVersion!==e&&(up.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.cache.clear())}getCacheVersion(){return this.cacheVersion}async loadTranslations(e,n,a="/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=$r(`${a}/templates/${e}/lang/${n}`,"json",this.cacheVersion>0?this.cacheVersion:null,c.length>0?c.join("&"):void 0),f=await fetch(d);if(!f.ok)throw new cd(`Failed to load translations: ${f.statusText}`,void 0,n);const m=await f.json();return this.saveToCache(l,m),this.translations.set(l,m),m}catch(c){throw new cd(`Failed to fetch translations for ${n}: ${c instanceof Error?c.message:String(c)}`,void 0,n)}}resolveTranslations(e,n,a){let i=e;const l=5;let c=0;for(;c"="+this.translate(m,n,void 0,a)),i===d)break;c++}return i.replace(Mn.TRANSLATION_PATTERN,(d,f,g)=>{const{cleanedParams:m,trailing:b}=this.separateTrailingText(g);return this.translate(f,n,m,a)+b})}translate(e,n,a,i){const l=this.getTranslation(e,n),c=a&&this.cleanParamsStr(a);if(c){const d=this.parseParams(c,i);return this.replaceParams(l,d)}return l}getTranslation(e,n){const{templateId:a,locale:i}=n,l=`${a}:${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=`${a}:${this.options.fallbackLocale}`,f=this.translations.get(d);if(f){const g=this.getNestedValue(f,e);if(g!==null)return g}}return e}getNestedValue(e,n){const a=n.split(".");let i=e;for(const l of a){if(i==null||typeof i!="object")return null;i=i[l]}return typeof i=="string"?i:null}setTranslationValue(e,n,a,i){const l=`${e}:${n}`,c=this.translations.get(l)??{},d=a.split(".");let f=c;for(let g=0;g(l.push(f),`__PLACEHOLDER_${l.length-1}__`)).matchAll(Mn.PARAM_PATTERN);for(const f of d){const[,g,m]=f,b=m.replace(/__PLACEHOLDER_(\d+)__/g,(S,v)=>l[parseInt(v,10)]);a[g.trim()]=this.resolveParamValue(b.trim(),n)}return a}resolveParamValue(e,n){if(e.startsWith("{{")&&e.endsWith("}}")){const a=e.slice(2,-2).trim();if(/[|&()[\]!?:+\-*/%<>=\s]/.test(a)&&n)try{const l=md.evaluateExpression(a,n);return String(l??"")}catch(l){return up.error("Expression evaluation failed:",a,l),""}else{const l=this.getNestedDataValue(n,a);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 a=e.match(/(\s+[^\p{L}\w=|&\s][^\p{L}\w=]*\s*)$/u);return a?{cleanedParams:e.slice(0,-a[1].length),trailing:a[1]}:{cleanedParams:e,trailing:""}}cleanParamsStr(e){return this.separateTrailingText(e).cleanedParams||""}getNestedDataValue(e,n){if(!e)return;const a=n.split(".");let i=e;for(const l of a){if(i==null)return;i=i[l]}return i}replaceParams(e,n){let a=e;for(const[i,l]of Object.entries(n)){const c=new RegExp(`\\{\\{${i}\\}\\}`,"g");a=a.replace(c,String(l));const d=new RegExp(`\\{${i}\\}`,"g");a=a.replace(d,String(l))}return a}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[a,i]of this.cache.entries())e-i.timestamp>this.options.cacheTTL&&n.push(a);for(const a of n)this.cache.delete(a)}getCacheStats(){const e=Date.now();let n=0;for(const a of this.cache.values())e-a.timestamp>this.options.cacheTTL&&n++;return{size:this.cache.size,expired:n}}};$(Mn,"instance",null),$(Mn,"TRANSLATION_PATTERN",/\$t:(?:defer:)?([a-zA-Z0-9._-]+)(\|(?:(?!\$t:).)+)?/g),$(Mn,"NESTED_TRANSLATION_PARAM_PATTERN",/=(\$t:([a-zA-Z0-9._-]+))(?=[|&\s]|$)/g),$(Mn,"PARAM_PATTERN",/([^=|&]+)=([^|&]+)/g);let _a=Mn,ud=null;function tw(o){return ud||(ud=new _a(o)),ud}const dp=Object.freeze(Object.defineProperty({__proto__:null,TranslationEngine:_a,TranslationError:cd,getTranslationEngine:tw},Symbol.toStringTag,{value:"Module"})),Qi=ut("PipeRegistry");function fp(o,e){const n=o.getFullYear(),a=String(o.getMonth()+1).padStart(2,"0"),i=String(o.getDate()).padStart(2,"0"),l=String(o.getHours()).padStart(2,"0"),c=String(o.getMinutes()).padStart(2,"0"),d=String(o.getSeconds()).padStart(2,"0");return e.replace("YYYY",String(n)).replace("YY",String(n).slice(-2)).replace("MM",a).replace("M",String(o.getMonth()+1)).replace("DD",i).replace("D",String(o.getDate())).replace("HH",l).replace("H",String(o.getHours())).replace("mm",c).replace("m",String(o.getMinutes())).replace("ss",d).replace("s",String(o.getSeconds()))}function nw(o,e="ko"){const a=new Date().getTime()-o.getTime(),i=Math.floor(a/1e3),l=Math.floor(i/60),c=Math.floor(l/60),d=Math.floor(c/24),f=Math.floor(d/7),g=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}주 전`:g<12?`${g}개월 전`:`${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`:g<12?`${g} month${g===1?"":"s"} ago`:`${m} year${m===1?"":"s"} ago`}function dd(o){if(o==null)return null;if(o instanceof Date)return o;if(typeof o=="number")return new Date(o);if(typeof o=="string"){const e=new Date(o);return isNaN(e.getTime())?null:e}return null}const Zs={date:{fn:(o,e="YYYY-MM-DD")=>{const n=dd(o);return n?fp(n,e):""},description:"날짜 포맷 (기본: YYYY-MM-DD)"},datetime:{fn:(o,e="YYYY-MM-DD HH:mm")=>{const n=dd(o);return n?fp(n,e):""},description:"날짜+시간 포맷 (기본: YYYY-MM-DD HH:mm)"},relativeTime:{fn:(o,e="ko")=>{const n=dd(o);return n?nw(n,e):""},description:'상대 시간 표시 (예: "3분 전")'},number:{fn:(o,e)=>{const n=Number(o);if(isNaN(n))return String(o??"");const a={};return e!==void 0&&(a.minimumFractionDigits=e,a.maximumFractionDigits=e),n.toLocaleString(void 0,a)},description:"숫자 포맷 (천단위 구분, 선택적 소수점)"},truncate:{fn:(o,e=100,n="...")=>typeof o!="string"?String(o??""):o.length<=e?o:o.slice(0,e)+n,description:'문자열 자르기 (기본: 100자, 접미사: "...")'},uppercase:{fn:o=>typeof o!="string"?String(o??""):o.toUpperCase(),description:"대문자 변환"},lowercase:{fn:o=>typeof o!="string"?String(o??""):o.toLowerCase(),description:"소문자 변환"},stripHtml:{fn:o=>typeof o!="string"?String(o??""):o.replace(/<[^>]*>/g,""),description:"HTML 태그 제거"},default:{fn:(o,e="")=>o==null||o===""?e:o,description:"기본값 설정 (null, undefined, 빈문자열 시)"},fallback:{fn:(o,e)=>o??e,description:"폴백 값 설정 (null, undefined 시만)"},first:{fn:o=>{if(Array.isArray(o))return o[0]},description:"배열의 첫 번째 요소"},last:{fn:o=>{if(Array.isArray(o))return o[o.length-1]},description:"배열의 마지막 요소"},join:{fn:(o,e=", ")=>Array.isArray(o)?o.join(e):"",description:'배열을 문자열로 결합 (기본 구분자: ", ")'},length:{fn:o=>Array.isArray(o)||typeof o=="string"?o.length:0,description:"배열/문자열 길이"},filterBy:{fn:(o,e,n)=>Array.isArray(o)?Array.isArray(e)?o.filter(a=>{const i=n?a?.[n]:a;return e.includes(i)}):o:[],description:"배열 필터링 (allowList에 포함된 항목만 반환)"},keys:{fn:o=>o==null||typeof o!="object"?[]:Object.keys(o),description:"객체의 키 배열"},values:{fn:o=>o==null||typeof o!="object"?[]:Object.values(o),description:"객체의 값 배열"},json:{fn:(o,e)=>{try{return JSON.stringify(o,null,e)}catch{return""}},description:"JSON 문자열로 변환"},localized:{fn:(o,e)=>o==null?"":typeof o=="string"?o:typeof o!="object"?String(o):o[e||"ko"]||o.ko||o.en||Object.values(o)[0]||"",description:"다국어 객체에서 로케일에 맞는 값 추출"}},Zi=new Map,vi=class vi{static getInstance(){return vi.instance||(vi.instance=new vi),vi.instance}register(e,n,a){if(Zs[e]){Qi.warn(`[PipeRegistry] 내장 파이프를 덮어쓸 수 없습니다: ${e}`);return}Zi.set(e,{fn:n,description:a}),Qi.log(`[PipeRegistry] 커스텀 파이프 등록됨: ${e}`)}unregister(e){if(Zs[e])return Qi.warn(`[PipeRegistry] 내장 파이프는 해제할 수 없습니다: ${e}`),!1;const n=Zi.delete(e);return n&&Qi.log(`[PipeRegistry] 커스텀 파이프 해제됨: ${e}`),n}get(e){const n=Zs[e];return n?n.fn:Zi.get(e)?.fn}has(e){return!!Zs[e]||Zi.has(e)}execute(e,n,a=[]){const i=this.get(e);if(!i)return Qi.warn(`[PipeRegistry] 알 수 없는 파이프: ${e}`),n;try{return i(n,...a)}catch(l){return Qi.error(`[PipeRegistry] 파이프 실행 오류 (${e}):`,l),n}}list(){const e=[];for(const[n,a]of Object.entries(Zs))e.push({name:n,description:a.description,type:"built-in"});for(const[n,a]of Zi.entries())e.push({name:n,description:a.description,type:"custom"});return e.sort((n,a)=>n.name.localeCompare(a.name))}clearCustomPipes(){Zi.clear()}};$(vi,"instance",null);let Ml=vi;Ml.getInstance();function rw(o){const e=o.trim(),n=e.indexOf("(");if(n===-1)return{name:e,args:[]};const a=e.slice(0,n).trim(),i=e.slice(n+1,-1);if(!i.trim())return{name:a,args:[]};const l=[];let c="",d=null,f=0;for(let g=0;g0?i[g-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(hp(c.trim())),c="";continue}c+=m}return c.trim()&&l.push(hp(c.trim())),{name:a,args:l}}function hp(o){if(o==="null")return null;if(o==="undefined")return;if(o==="true")return!0;if(o==="false")return!1;const e=Number(o);return!isNaN(e)&&o!==""?e:o}function aw(o){const e=[];let n="",a=null,i=0;for(let l=0;l0?o[l-1]:"",f=l0?o[a-1]:"",c=a0){a--;continue}return null}}return a===0?e.trim():null}function sw(o){const e=[];if(typeof o!="string")return e;for(let n=0;n0){i--;continue}if(o[c+1]==="}"){l=c;break}break}}l!==-1&&(e.push({start:n,end:l+2,expr:o.slice(n+2,l)}),n=l+1)}return e}function eo(o){return/[?:|&!+\-*/<>=()[\]{}]/.test(o)}function gp(o){const e=typeof o=="string"?o.trim():"";return e===""?"empty":fd.has(e)?"literal":Pn(e)?"pipe":eo(e)?"expression":"path"}function hd(o,e,n,a){const i=typeof o=="string"?o.trim():"",l=gp(i),c=a?.skipCache?{skipCache:!0}:void 0;if(l==="empty"){a?.onEmpty?.(o);return}if(l==="literal")return fd.get(i);try{return l==="pipe"?n.evaluatePipeExpression(i,e,c,a?.trackingInfo):l==="expression"?n.evaluateExpression(i,e,a?.trackingInfo):n.resolve(i,e,c,a?.trackingInfo)}catch(d){if(a?.onError)return a.onError(d,i);throw d}}const er="raw:";function pp(o){return o.startsWith(er)?o.slice(er.length):o}const to="﷐",fi="﷑",xa="﷒";function no(o){return to+o+fi}function $l(o){return o.length>=2&&o.charCodeAt(0)===64976&&o.charCodeAt(o.length-1)===64977}function Nl(o){return o.includes(to)}function gd(o){return o.slice(1,-1)}function es(o){if(typeof o=="string")return no(o);if(Array.isArray(o))return o.map(es);if(o&&typeof o=="object"){const e={};for(const[n,a]of Object.entries(o))e[n]=es(a);return e}return o}function Ta(o){if(typeof o=="string")return $l(o)?gd(o):Nl(o)||o.includes(fi)?o.split(to).join("").split(fi).join(""):o;if(Array.isArray(o)){let e=!1;const n=o.map(a=>{const i=Ta(a);return i!==a&&(e=!0),i});return e?n:o}if(o&&typeof o=="object"){if(o.$$typeof!==void 0)return o;let e=!1;const n={};for(const[a,i]of Object.entries(o)){const l=Ta(i);l!==i&&(e=!0),n[a]=l}return e?n:o}return o}const Ra=ut("DataBindingEngine"),ow=/^[$A-Za-z_][$A-Za-z0-9_]*$/,lw=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield","arguments","eval"]);function ro(){try{return window.G7Core?.devTools}catch{return}}class pd extends Error{constructor(n,a,i){super(n);$(this,"path");$(this,"context");this.path=a,this.context=i,this.name="DataBindingError"}}const ta=class ta{constructor(e){$(this,"cache",new Map);$(this,"expressionFnCache",new Map);$(this,"renderCycleCache",new Map);$(this,"currentRenderCycleId",0);$(this,"defaultOptions",{defaultValue:void 0,nullSafe:!0,detectCircular:!0,maxDepth:10});e&&(this.defaultOptions={...this.defaultOptions,...e})}startRenderCycle(){this.currentRenderCycleId++,this.renderCycleCache.clear()}isRenderCycleCacheActive(){return this.currentRenderCycleId>0}getFromRenderCycleCache(e){if(this.isRenderCycleCacheActive())return this.renderCycleCache.get(e)}saveToRenderCycleCache(e,n){this.isRenderCycleCacheActive()&&this.renderCycleCache.set(e,n)}resolveBindings(e,n,a,i){const l={...this.defaultOptions,...a},c=ro(),d=n._computed&&!n.$computed?{...n,$computed:n._computed}:n,f=(S,v)=>{const _=v.trim();let A=!1,x=_;if(_.startsWith(er)&&(A=!0,x=_.slice(er.length)),Pn(x))try{const P=this.evaluatePipeExpression(x,d,l,{...i,method:"resolveBindings",displayExpression:`{{${_}}}`}),K=this.formatValue(P);return A?no(K):K}catch(P){return Ra.error("Pipe expression evaluation failed:",x,P),S}if(eo(x)){const P=c?.isEnabled()?performance.now():0;try{let K,ge=!1;if(l.skipCache)K=this.evaluateExpression(x,d);else{const Se=`expr:${x}`,Ue=this.getFromRenderCycleCache(Se);Ue!==void 0?(K=Ue,ge=!0):(K=this.evaluateExpression(x,d),this.saveToRenderCycleCache(Se,K))}if(c?.isEnabled()){const Se=performance.now()-P;c.trackExpressionEval({expression:`{{${_}}}`,result:this.sanitizeResultForTracking(K),resultType:this.getResultType(K),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:ge,duration:Se,method:"resolveBindings",skipCache:l.skipCache})}const Ee=this.formatValue(K);return A?no(Ee):Ee}catch(K){return Ra.error("Expression evaluation failed:",x,K),S}}if(l.skipCache){const P=c?.isEnabled()?performance.now():0,K=this.resolvePath(x,d,l);if(c?.isEnabled()){const Ee=performance.now()-P;c.trackExpressionEval({expression:`{{${_}}}`,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 ge=this.formatValue(K);return A?no(ge):ge}const M=x.startsWith("_global")||x.startsWith("_local")||x.startsWith("_isolated")||x.startsWith("$parent"),R=c?.isEnabled()?performance.now():0;let D,B=!1;if(M){const P=this.getFromRenderCycleCache(x);P!==void 0?(D=P,B=!0):(D=this.resolvePath(x,d,l),this.saveToRenderCycleCache(x,D))}else{const P=this.getFromCache(x);P!==void 0?(D=P,B=!0):(D=this.resolvePath(x,d,l),this.saveToCache(x,D))}if(c?.isEnabled()){const P=performance.now()-R;c.trackExpressionEval({expression:`{{${_}}}`,result:this.sanitizeResultForTracking(D),resultType:this.getResultType(D),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:B,duration:P,method:"resolveBindings",skipCache:l.skipCache})}const q=this.formatValue(D);return A?no(q):q},g=sw(e);if(g.length===0)return e;let m="",b=0;for(const S of g)m+=e.slice(b,S.start),m+=f(e.slice(S.start,S.end),S.expr),b=S.end;return m+e.slice(b)}evaluatePipeExpression(e,n,a,i){const l={...this.defaultOptions,...a},c=ro(),d=c?.isEnabled()?performance.now():0,f=n._computed&&!n.$computed?{...n,$computed:n._computed}:n,[g,m]=aw(e);let b,S=!1;const v=eo(g),_=g.startsWith("_global")||g.startsWith("_local")||g.startsWith("_isolated")||g.startsWith("$parent");if(l.skipCache)v?b=this.evaluateExpression(g,f):b=this.resolvePath(g,f,l);else if(v){const x=this.getFromRenderCycleCache(`expr:${g}`);x!==void 0?(b=x,S=!0):(b=this.evaluateExpression(g,f),this.saveToRenderCycleCache(`expr:${g}`,b))}else if(_){const x=this.getFromRenderCycleCache(g);x!==void 0?(b=x,S=!0):(b=this.resolvePath(g,f,l),this.saveToRenderCycleCache(g,b))}else{const x=this.getFromCache(g);x!==void 0?(b=x,S=!0):(b=this.resolvePath(g,f,l),this.saveToCache(g,b))}const A=iw(b,m);if(c?.isEnabled()){const x=performance.now()-d;c.trackExpressionEval({expression:i?.displayExpression??`{{${e}}}`,result:this.sanitizeResultForTracking(A),resultType:this.getResultType(A),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:S,duration:x,method:i?.method??"evaluatePipeExpression",skipCache:l.skipCache})}return A}resolve(e,n,a,i){const l={...this.defaultOptions,...a},c=ro(),d=c?.isEnabled()?performance.now():0;if(l.skipCache){const b=this.resolvePath(e,n,l);return c?.isEnabled()&&c.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(b),resultType:this.getResultType(b),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:performance.now()-d,method:"resolve",skipCache:!0}),b}const f=e.startsWith("_global")||e.startsWith("_local")||e.startsWith("_isolated")||e.startsWith("$parent");let g=!1;if(f){const b=this.getFromRenderCycleCache(e);if(b!==void 0)return g=!0,c?.isEnabled()&&c.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(b),resultType:this.getResultType(b),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!0,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),b}else{const b=this.getFromCache(e);if(b!==void 0)return g=!0,c?.isEnabled()&&c.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(b),resultType:this.getResultType(b),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!0,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),b}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:g,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),m}resolvePath(e,n,a,i=0,l=new WeakSet){if(typeof e!="string"||e.trim()===""){Ra.warn("resolvePath: 빈 경로가 전달되었습니다 — undefined 로 해석합니다.");return}if(a.maxDepth&&i>a.maxDepth){if(a.detectCircular)throw new pd(`Maximum depth exceeded (${a.maxDepth}). Possible circular reference.`,e,n);return a.defaultValue}const c=this.parsePath(e);let d=n;for(let f=0;fta.CACHE_EXPIRY){this.cache.delete(e),a?.isEnabled()&&a.recordCacheMiss();return}return a?.isEnabled()&&a.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,a){if(this.isSwitchExpression(e)){const d=e;return this.resolveSwitch(d,n,a)}if(this.isActionDefinition(e))return{...e};if("iteration"in e)return{...e};const i={},c=[...["cellChildren","expandChildren","expandContext","render"],...a?.skipBindingKeys||[]];for(const[d,f]of Object.entries(e)){if(c.includes(d)){i[d]=f;continue}try{this.resolveObjectEntry(i,d,f,n,a)}catch(g){Ra.warn(`resolveObject: 값 해석 실패 (key: ${d}):`,g),i[d]=void 0}}return i}resolveObjectEntry(e,n,a,i,l){if(typeof a=="string"){const c=Aa(a);if(c!==null){const d=c.trim();let f=!1,g=d;d.startsWith(er)&&(f=!0,g=d.slice(er.length));let m;switch(gp(g)){case"empty":Ra.warn(`resolveObject: 빈 바인딩 \`{{}}\` (key: ${n}) — undefined 로 해석합니다.`),m=void 0;break;case"literal":m=fd.get(g);break;case"pipe":m=this.evaluatePipeExpression(g,i,l);break;case"expression":m=this.evaluateExpression(g,i,l);break;default:m=this.resolve(g,i,l)}e[n]=f&&m!=null?es(m):m}else e[n]=this.resolveBindings(a,i,l)}else Array.isArray(a)?e[n]=a.map(c=>typeof c=="string"?this.resolveBindings(c,i,l):typeof c=="object"&&c!==null?this.resolveObject(c,i,l):c):a&&typeof a=="object"?e[n]=this.resolveObject(a,i,l):e[n]=a}clearCache(){this.cache.clear(),this.expressionFnCache.clear()}invalidateCacheByKeys(e){for(const n of this.cache.keys())for(const a of e)if(n===a||n.startsWith(`${a}.`)||n.startsWith(`${a}[`)){this.cache.delete(n);break}}pruneCache(){const e=Date.now();for(const[n,a]of this.cache.entries())e-a.timestamp>ta.CACHE_EXPIRY&&this.cache.delete(n)}getCacheStats(){const e=Date.now();let n=0;for(const a of this.cache.values())e-a.timestamp>ta.CACHE_EXPIRY&&n++;return{size:this.cache.size,expired:n}}evaluateExpression(e,n,a){const i=ro(),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 D of d)D in f||(f[D]=void 0);n._computed&&!f.$computed&&(f.$computed=n._computed);let g=n.$templateId,m=n.$locale;if(typeof window<"u"&&(!g||!m)){const D=window.__templateApp?.getConfig?.();g??(g=D?.templateId),m??(m=D?.locale)}const b=m||"ko";f.$localized=(D,B)=>{if(D==null&&!B)return"";if(typeof D=="string")return D;if(D&&typeof D=="object"&&D[b])return D[b];if(B&&typeof B=="string"){const q=f.$t?f.$t(B):B;if(q&&q!==B)return q}return D&&typeof D=="object"?D.ko||D.en||Object.values(D)[0]||"":D==null?"":String(D)};const S=typeof window<"u"?window.G7Core:void 0;f.$uuid=()=>S?.uuid?S.uuid():typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,D=>{const B=Math.random()*16|0;return(D==="x"?B:B&3|8).toString(16)});const v={templateId:g||"",locale:b};f.$t=D=>{if(!D||typeof D!="string")return"";try{return _a.getInstance().translate(D,v)}catch(B){return Ra.warn("$t() translation failed for key:",D,B),D}},f.$get=(D,B,q=void 0)=>{if(D==null)return q;const P=Array.isArray(B)?B:[B];if(P.length===0)return D;let K=D;for(const ge of P){if(K==null||ge==null)return q;K=K[ge]}return K??q};const _=[],A=[];for(const[D,B]of Object.entries(f))!ow.test(D)||lw.has(D)||(_.push(D),A.push(B));const x=`${c}|${_.join(",")}`;let L=this.expressionFnCache.get(x);const M=!!L;L||(L=new Function(..._,`return (${c});`),this.expressionFnCache.set(x,L));const R=L(...A);if(i?.isEnabled()){const D=performance.now()-l;i.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(R),resultType:this.getResultType(R),componentId:a?.componentId,componentName:a?.componentName,propName:a?.propName,fromCache:M,duration:D,method:"evaluateExpression",skipCache:a?.skipCache})}return R}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,a,i,l)=>`$t('${l}')`),e.replace(/(?(n.push(l),`__STRING_LITERAL_${n.length-1}__`));const i=[];return a=a.replace(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*(?:\|[^'"\s,)]+)?/g,l=>(i.push(l),`__TRANSLATION_TOKEN_${i.length-1}__`)),a=a.replace(/([a-zA-Z_$][a-zA-Z0-9_$]*)\.(?!\?)/g,"$1?."),a=a.replace(/__TRANSLATION_TOKEN_(\d+)__/g,(l,c)=>i[parseInt(c,10)]),a=a.replace(/__STRING_LITERAL_(\d+)__/g,(l,c)=>n[parseInt(c,10)]),a}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"]),a=/(?{n!==null&&clearTimeout(n),n=setTimeout(()=>{o(...a)},e)})}class uw{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=cw(()=>{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(Hl.has(e))return Hl.get(e)??null;let n=null;if(Il[e])n={...Il[e]};else{const a=e.match(/^(-?\d*)-(-?\d*)$/);if(a){const[,i,l]=a,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 Hl.set(e,n),n}getMatchingKey(e,n){const a=[];for(const i of Object.keys(e)){const l=this.parseRange(i);l&&n>=l.min&&n<=l.max&&a.push({key:i,range:l,isPreset:!!Il[i]})}return a.length===0?null:(a.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}),a[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(),Hl.clear()}_setWidthForTesting(e){this.currentWidth=e,this.notifySubscribers()}}const hi=new uw,ao=ut("ConditionEvaluator");function dw(o,e,n,a){return hd(pp(o),e,n,{skipCache:!0,onEmpty:()=>{ao.warn(`${a}: 빈 바인딩 \`{{}}\` — undefined 로 해석합니다.`)}})}function mp(o,e,n){if(!o)return!0;try{const a=Aa(o);let i;if(a!==null?i=dw(a,e,n,"evaluateStringCondition"):i=n.resolveBindings(o,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(a){return ao.warn(`evaluateStringCondition: 조건 평가 실패: ${o}`,a),!1}}function zl(o,e,n){if(typeof o=="string")return mp(o,e,n);if("and"in o){if(!Array.isArray(o.and)||o.and.length===0)return ao.warn("evaluateConditionExpression: AND 그룹이 비어있습니다"),!0;for(const a of o.and)if(!zl(a,e,n))return!1;return!0}if("or"in o){if(!Array.isArray(o.or)||o.or.length===0)return ao.warn("evaluateConditionExpression: OR 그룹이 비어있습니다"),!1;for(const a of o.or)if(zl(a,e,n))return!0;return!1}return ao.warn("evaluateConditionExpression: 알 수 없는 조건 형식",o),!1}function yp(o,e,n){if(!Array.isArray(o)||o.length===0)return{matched:!1,branchIndex:-1};for(let a=0;a{tr.warn(`evaluateIfCondition: 빈 바인딩 \`{{}}\` (컴포넌트: ${a||"unknown"}) — undefined 로 해석합니다.`)}}):l=n.resolveBindings(o,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 tr.warn(`evaluateIfCondition: 조건 평가 실패 (컴포넌트: ${a||"unknown"}):`,i),!1}}function ts(o,e,n,a){if(o.if!==void 0)return wp(o.if,e,n,a);if(o.condition!==void 0)return wp(o.condition,e,n,a);if(o.conditions===void 0)return!0;const i=o.conditions;try{return fw(i)?zl(i,e,n):hw(i)?yp(i,e,n).matched:(tr.warn(`evaluateRenderCondition: 알 수 없는 conditions 형식 (컴포넌트: ${a||"unknown"})`),!0)}catch(l){return tr.warn(`evaluateRenderCondition: conditions 평가 실패 (컴포넌트: ${a||"unknown"}):`,l),!1}}function Cp(o){if(!o.responsive)return o;const e=hi.getWidth(),n=hi.getMatchingKey(o.responsive,e);if(!n)return o;const a=o.responsive[n];return{...o,props:{...o.props,...a.props},children:a.children??o.children,text:a.text??o.text,if:a.if??o.if,iteration:a.iteration??o.iteration}}function io(o,e,n,a,i){if(!o||o.length===0)return[];const l=i?.bindingEngine??new xn,c=i?.translationEngine??_a.getInstance(),d=i?.translationContext??{templateId:"",locale:"ko"},f=pw(e,i?.componentContext),g=(v,_)=>{if(typeof v=="string")return $l(v)||Nl(v)||!/\$t:[a-zA-Z0-9._-]+/.test(v)?v:c.resolveTranslations(v,d,_);if(Array.isArray(v))return v.map(A=>g(A,_));if(v&&typeof v=="object"){const A={};for(const[x,L]of Object.entries(v))A[x]=g(L,_);return A}return v},m=(v,_)=>{if(typeof v=="string"){if($l(v))return gd(v);if(Nl(v)){const x=[],L=v.replace(new RegExp(`${to}([^${fi}]*)${fi}`,"g"),(R,D)=>(x.push(D),`${xa}${x.length-1}${xa}`));let M=L;return/\$t:[a-zA-Z0-9._-]+/.test(L)&&(M=c.resolveTranslations(L,d,_)),M.replace(new RegExp(`${xa}(\\d+)${xa}`,"g"),(R,D)=>x[parseInt(D)])}if(v.startsWith("$t:defer:")){const x="$t:"+v.slice(9);return c.resolveTranslations(x,d,_)}if(v.startsWith("$t:"))return c.resolveTranslations(v,d,_);if(/\$t:[a-zA-Z0-9._-]+/.test(v)){const x=v.trim();if(!(x.startsWith("{")&&x.endsWith("}")||x.startsWith("[")&&x.endsWith("]"))&&!v.includes("{{"))return c.resolveTranslations(v,d,_)}const A=Sp(v);if(A!==null){let x=!1,L=A;A.startsWith(er)&&(x=!0,L=A.slice(er.length));let M=!1,R=hd(L,_,l,{skipCache:!0,onError:D=>{tr.warn("renderItemChildren: 표현식 평가 실패:",D),M=!0},onEmpty:()=>{tr.warn("renderItemChildren: 빈 바인딩 `{{}}` 은 해석하지 않습니다.")}});return M?void 0:(x||(R=g(R,_)),x&&R!=null?es(R):R)}if(v.includes("{{")){const x=l.resolveBindings(v,_,{skipCache:!0});return typeof x=="string"&&/\$t:[a-zA-Z0-9._-]+/.test(x)?c.resolveTranslations(x,d,_):x}return v}if(Array.isArray(v))return v.map(A=>m(A,_));if(v&&typeof v=="object"){if(l.isSwitchExpression(v))return l.resolveSwitch(v,_,{skipCache:!0});if(l.isActionDefinition(v))return{...v};const A={};for(const[x,L]of Object.entries(v))A[x]=m(L,_);return A}return v},b=(v,_)=>{if(!v)return{};const A={};for(const[x,L]of Object.entries(v))A[x]=m(L,_);return A},S=(v,_,A)=>{const x=Cp(v),L=x.iteration;if(!L)return[];const M=yd(L.source,A,l);if(!Array.isArray(M))return tr.warn(`renderItemChildren: iteration.source가 배열이 아닙니다: ${L.source}`),[];const R=bp();if(R?.isEnabled()){const B=`${_}-iteration`;R.trackIteration(B,L.source,L.item_var,L.index_var,M.length)}const D=n[x.name];return D?M.flatMap((B,q)=>{const P={...A,[L.item_var]:B,[`${L.item_var}_index`]:q,...L.index_var?{[L.index_var]:q}:{}},K=ts({if:x.if,condition:x.condition,conditions:x.conditions},P,l,x.id);if(x.if&&R?.isEnabled()){const St=`${_}-iter-${q}-if`;R.trackIfCondition(St,x.if,K,x.name)}if(!K)return[];const ge=x.id?String(Ta(m(x.id,P))):void 0,Ee=`${_}-iter-${q}`,Se=i?.getRemountKey?i.getRemountKey(ge,Ee):Ee,Ue=b(x.props,P),Ve=bd(Ue,x.actions,P,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let qe=null;return x.text!==void 0?qe=m(x.text,P):x.children&&x.children.length>0&&(qe=io(x.children,P,n,Se,i)),R?.isEnabled()&&R.trackRender(x.name),[Ye.createElement(D,{key:Se,...Ta(Ve)},Ta(qe))]}):(tr.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${x.name}`),[])};return o.flatMap((v,_)=>{const A=Cp(v),x=A.id?String(Ta(m(A.id,f))):void 0,L=a?`${a}-${x||_}`:x||`child-${_}`,M=i?.getRemountKey?i.getRemountKey(x,L):L;if(A.iteration)return S(A,M,f);const R=ts({if:A.if,condition:A.condition,conditions:A.conditions},f,l,A.id),D=bp();if(A.if&&D?.isEnabled()){const ge=`${M}-if`;D.trackIfCondition(ge,A.if,R,A.name)}if(!R)return[];const B=n[A.name];if(!B)return tr.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${A.name}`),[];const q=b(A.props,f),P=bd(q,A.actions,f,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let K=null;return A.text!==void 0?K=m(A.text,f):A.children&&A.children.length>0&&(K=io(A.children,f,n,M,i)),D?.isEnabled()&&D.trackRender(A.name),[Ye.createElement(B,{key:M,...Ta(P)},Ta(K))]})}function ns(o,e,n,a){let i,l;return n instanceof xn?(i=n,l=a):(i=vp,l=n),i.resolveBindings(o,e,l)}function mw(o,e,n,a){const i=n??vp,l={skipCache:!0,...a};let c;try{c=i.resolveBindings(o.key,e,{skipCache:l.skipCache})?.toString()?.trim()??""}catch(g){tr.warn("resolveClassMap: key 평가 실패:",o.key,g),c=""}let d="";c&&o.variants&&c in o.variants?d=o.variants[c]:o.default&&(d=o.default);const f=[];return o.base?.trim()&&f.push(o.base.trim()),d?.trim()&&f.push(d.trim()),f.join(" ")}function Ep(o,e){return function(){return o.apply(e,arguments)}}const{toString:yw}=Object.prototype,{getPrototypeOf:jl}=Object,{iterator:Ul,toStringTag:_p}=Symbol,Bl=(o=>e=>{const n=yw.call(e);return o[n]||(o[n]=n.slice(8,-1).toLowerCase())})(Object.create(null)),mr=o=>(o=o.toLowerCase(),e=>Bl(e)===o),Pl=o=>e=>typeof e===o,{isArray:rs}=Array,as=Pl("undefined");function so(o){return o!==null&&!as(o)&&o.constructor!==null&&!as(o.constructor)&&On(o.constructor.isBuffer)&&o.constructor.isBuffer(o)}const Ap=mr("ArrayBuffer");function bw(o){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(o):e=o&&o.buffer&&Ap(o.buffer),e}const vw=Pl("string"),On=Pl("function"),xp=Pl("number"),oo=o=>o!==null&&typeof o=="object",Sw=o=>o===!0||o===!1,ql=o=>{if(Bl(o)!=="object")return!1;const e=jl(o);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(_p in o)&&!(Ul in o)},ww=o=>{if(!oo(o)||so(o))return!1;try{return Object.keys(o).length===0&&Object.getPrototypeOf(o)===Object.prototype}catch{return!1}},Cw=mr("Date"),Ew=mr("File"),_w=o=>!!(o&&typeof o.uri<"u"),Aw=o=>o&&typeof o.getParts<"u",xw=mr("Blob"),Tw=mr("FileList"),Rw=o=>oo(o)&&On(o.pipe);function kw(){return typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:typeof global<"u"?global:{}}const Tp=kw(),Rp=typeof Tp.FormData<"u"?Tp.FormData:void 0,Dw=o=>{if(!o)return!1;if(Rp&&o instanceof Rp)return!0;const e=jl(o);if(!e||e===Object.prototype||!On(o.append))return!1;const n=Bl(o);return n==="formdata"||n==="object"&&On(o.toString)&&o.toString()==="[object FormData]"},Ow=mr("URLSearchParams"),[Lw,Mw,$w,Nw]=["ReadableStream","Request","Response","Headers"].map(mr),Iw=o=>o.trim?o.trim():o.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function lo(o,e,{allOwnKeys:n=!1}={}){if(o===null||typeof o>"u")return;let a,i;if(typeof o!="object"&&(o=[o]),rs(o))for(a=0,i=o.length;a0;)if(i=n[a],e===i.toLowerCase())return i;return null}const gi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,Dp=o=>!as(o)&&o!==gi;function vd(...o){const{caseless:e,skipUndefined:n}=Dp(this)&&this||{},a={},i=(l,c)=>{if(c==="__proto__"||c==="constructor"||c==="prototype")return;const d=e&&kp(a,c)||c,f=Sd(a,d)?a[d]:void 0;ql(f)&&ql(l)?a[d]=vd(f,l):ql(l)?a[d]=vd({},l):rs(l)?a[d]=l.slice():(!n||!as(l))&&(a[d]=l)};for(let l=0,c=o.length;l(lo(e,(i,l)=>{n&&On(i)?Object.defineProperty(o,l,{__proto__:null,value:Ep(i,n),writable:!0,enumerable:!0,configurable:!0}):Object.defineProperty(o,l,{__proto__:null,value:i,writable:!0,enumerable:!0,configurable:!0})},{allOwnKeys:a}),o),zw=o=>(o.charCodeAt(0)===65279&&(o=o.slice(1)),o),jw=(o,e,n,a)=>{o.prototype=Object.create(e.prototype,a),Object.defineProperty(o.prototype,"constructor",{__proto__:null,value:o,writable:!0,enumerable:!1,configurable:!0}),Object.defineProperty(o,"super",{__proto__:null,value:e.prototype}),n&&Object.assign(o.prototype,n)},Uw=(o,e,n,a)=>{let i,l,c;const d={};if(e=e||{},o==null)return e;do{for(i=Object.getOwnPropertyNames(o),l=i.length;l-- >0;)c=i[l],(!a||a(c,o,e))&&!d[c]&&(e[c]=o[c],d[c]=!0);o=n!==!1&&jl(o)}while(o&&(!n||n(o,e))&&o!==Object.prototype);return e},Bw=(o,e,n)=>{o=String(o),(n===void 0||n>o.length)&&(n=o.length),n-=e.length;const a=o.indexOf(e,n);return a!==-1&&a===n},Pw=o=>{if(!o)return null;if(rs(o))return o;let e=o.length;if(!xp(e))return null;const n=new Array(e);for(;e-- >0;)n[e]=o[e];return n},qw=(o=>e=>o&&e instanceof o)(typeof Uint8Array<"u"&&jl(Uint8Array)),Gw=(o,e)=>{const a=(o&&o[Ul]).call(o);let i;for(;(i=a.next())&&!i.done;){const l=i.value;e.call(o,l[0],l[1])}},Vw=(o,e)=>{let n;const a=[];for(;(n=o.exec(e))!==null;)a.push(n);return a},Fw=mr("HTMLFormElement"),Kw=o=>o.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(n,a,i){return a.toUpperCase()+i}),Sd=(({hasOwnProperty:o})=>(e,n)=>o.call(e,n))(Object.prototype),Ww=mr("RegExp"),Op=(o,e)=>{const n=Object.getOwnPropertyDescriptors(o),a={};lo(n,(i,l)=>{let c;(c=e(i,l,o))!==!1&&(a[l]=c||i)}),Object.defineProperties(o,a)},Yw=o=>{Op(o,(e,n)=>{if(On(o)&&["arguments","caller","callee"].includes(n))return!1;const a=o[n];if(On(a)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+n+"'")})}})},Xw=(o,e)=>{const n={},a=i=>{i.forEach(l=>{n[l]=!0})};return rs(o)?a(o):a(String(o).split(e)),n},Jw=()=>{},Qw=(o,e)=>o!=null&&Number.isFinite(o=+o)?o:e;function Zw(o){return!!(o&&On(o.append)&&o[_p]==="FormData"&&o[Ul])}const e0=o=>{const e=new WeakSet,n=a=>{if(oo(a)){if(e.has(a))return;if(so(a))return a;if(!("toJSON"in a)){e.add(a);const i=rs(a)?[]:{};return lo(a,(l,c)=>{const d=n(l);!as(d)&&(i[c]=d)}),e.delete(a),i}}return a};return n(o)},t0=mr("AsyncFunction"),n0=o=>o&&(oo(o)||On(o))&&On(o.then)&&On(o.catch),Lp=((o,e)=>o?setImmediate:e?((n,a)=>(gi.addEventListener("message",({source:i,data:l})=>{i===gi&&l===n&&a.length&&a.shift()()},!1),i=>{a.push(i),gi.postMessage(n,"*")}))(`axios@${Math.random()}`,[]):n=>setTimeout(n))(typeof setImmediate=="function",On(gi.postMessage)),r0=typeof queueMicrotask<"u"?queueMicrotask.bind(gi):typeof process<"u"&&process.nextTick||Lp,W={isArray:rs,isArrayBuffer:Ap,isBuffer:so,isFormData:Dw,isArrayBufferView:bw,isString:vw,isNumber:xp,isBoolean:Sw,isObject:oo,isPlainObject:ql,isEmptyObject:ww,isReadableStream:Lw,isRequest:Mw,isResponse:$w,isHeaders:Nw,isUndefined:as,isDate:Cw,isFile:Ew,isReactNativeBlob:_w,isReactNative:Aw,isBlob:xw,isRegExp:Ww,isFunction:On,isStream:Rw,isURLSearchParams:Ow,isTypedArray:qw,isFileList:Tw,forEach:lo,merge:vd,extend:Hw,trim:Iw,stripBOM:zw,inherits:jw,toFlatObject:Uw,kindOf:Bl,kindOfTest:mr,endsWith:Bw,toArray:Pw,forEachEntry:Gw,matchAll:Vw,isHTMLForm:Fw,hasOwnProperty:Sd,hasOwnProp:Sd,reduceDescriptors:Op,freezeMethods:Yw,toObjectSet:Xw,toCamelCase:Kw,noop:Jw,toFiniteNumber:Qw,findKey:kp,global:gi,isContextDefined:Dp,isSpecCompliantForm:Zw,toJSONObject:e0,isAsyncFn:t0,isThenable:n0,setImmediate:Lp,asap:r0,isIterable:o=>o!=null&&On(o[Ul])},a0=W.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"]),i0=o=>{const e={};let n,a,i;return o&&o.split(` -`).forEach(function(c){i=c.indexOf(":"),n=c.substring(0,i).trim().toLowerCase(),a=c.substring(i+1).trim(),!(!n||e[n]&&a0[n])&&(n==="set-cookie"?e[n]?e[n].push(a):e[n]=[a]:e[n]=e[n]?e[n]+", "+a:a)}),e};function s0(o){let e=0,n=o.length;for(;ee;){const a=o.charCodeAt(n-1);if(a!==9&&a!==32)break;n-=1}return e===0&&n===o.length?o:o.slice(e,n)}const o0=new RegExp("[\\u0000-\\u0008\\u000a-\\u001f\\u007f]+","g"),l0=new RegExp("[^\\u0009\\u0020-\\u007e\\u0080-\\u00ff]+","g");function wd(o,e){return W.isArray(o)?o.map(n=>wd(n,e)):s0(String(o).replace(e,""))}const c0=o=>wd(o,o0),u0=o=>wd(o,l0);function Mp(o){const e=Object.create(null);return W.forEach(o.toJSON(),(n,a)=>{e[a]=u0(n)}),e}const $p=Symbol("internals");function co(o){return o&&String(o).trim().toLowerCase()}function Gl(o){return o===!1||o==null?o:W.isArray(o)?o.map(Gl):c0(String(o))}function d0(o){const e=Object.create(null),n=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let a;for(;a=n.exec(o);)e[a[1]]=a[2];return e}const f0=o=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(o.trim());function Cd(o,e,n,a,i){if(W.isFunction(a))return a.call(this,e,n);if(i&&(e=n),!!W.isString(e)){if(W.isString(a))return e.indexOf(a)!==-1;if(W.isRegExp(a))return a.test(e)}}function h0(o){return o.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,n,a)=>n.toUpperCase()+a)}function g0(o,e){const n=W.toCamelCase(" "+e);["get","set","has"].forEach(a=>{Object.defineProperty(o,a+n,{__proto__:null,value:function(i,l,c){return this[a].call(this,e,i,l,c)},configurable:!0})})}let Tn=class{constructor(e){e&&this.set(e)}set(e,n,a){const i=this;function l(d,f,g){const m=co(f);if(!m)throw new Error("header name must be a non-empty string");const b=W.findKey(i,m);(!b||i[b]===void 0||g===!0||g===void 0&&i[b]!==!1)&&(i[b||f]=Gl(d))}const c=(d,f)=>W.forEach(d,(g,m)=>l(g,m,f));if(W.isPlainObject(e)||e instanceof this.constructor)c(e,n);else if(W.isString(e)&&(e=e.trim())&&!f0(e))c(i0(e),n);else if(W.isObject(e)&&W.isIterable(e)){let d={},f,g;for(const m of e){if(!W.isArray(m))throw TypeError("Object iterator must return a key-value pair");d[g=m[0]]=(f=d[g])?W.isArray(f)?[...f,m[1]]:[f,m[1]]:m[1]}c(d,n)}else e!=null&&l(n,e,a);return this}get(e,n){if(e=co(e),e){const a=W.findKey(this,e);if(a){const i=this[a];if(!n)return i;if(n===!0)return d0(i);if(W.isFunction(n))return n.call(this,i,a);if(W.isRegExp(n))return n.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,n){if(e=co(e),e){const a=W.findKey(this,e);return!!(a&&this[a]!==void 0&&(!n||Cd(this,this[a],a,n)))}return!1}delete(e,n){const a=this;let i=!1;function l(c){if(c=co(c),c){const d=W.findKey(a,c);d&&(!n||Cd(a,a[d],d,n))&&(delete a[d],i=!0)}}return W.isArray(e)?e.forEach(l):l(e),i}clear(e){const n=Object.keys(this);let a=n.length,i=!1;for(;a--;){const l=n[a];(!e||Cd(this,this[l],l,e,!0))&&(delete this[l],i=!0)}return i}normalize(e){const n=this,a={};return W.forEach(this,(i,l)=>{const c=W.findKey(a,l);if(c){n[c]=Gl(i),delete n[l];return}const d=e?h0(l):String(l).trim();d!==l&&delete n[l],n[d]=Gl(i),a[d]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const n=Object.create(null);return W.forEach(this,(a,i)=>{a!=null&&a!==!1&&(n[i]=e&&W.isArray(a)?a.join(", "):a)}),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 a=new this(e);return n.forEach(i=>a.set(i)),a}static accessor(e){const a=(this[$p]=this[$p]={accessors:{}}).accessors,i=this.prototype;function l(c){const d=co(c);a[d]||(g0(i,c),a[d]=!0)}return W.isArray(e)?e.forEach(l):l(e),this}};Tn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),W.reduceDescriptors(Tn.prototype,({value:o},e)=>{let n=e[0].toUpperCase()+e.slice(1);return{get:()=>o,set(a){this[n]=a}}}),W.freezeMethods(Tn);const p0="[REDACTED ****]";function m0(o){if(W.hasOwnProp(o,"toJSON"))return!0;let e=Object.getPrototypeOf(o);for(;e&&e!==Object.prototype;){if(W.hasOwnProp(e,"toJSON"))return!0;e=Object.getPrototypeOf(e)}return!1}function y0(o,e){const n=new Set(e.map(l=>String(l).toLowerCase())),a=[],i=l=>{if(l===null||typeof l!="object"||W.isBuffer(l))return l;if(a.indexOf(l)!==-1)return;l instanceof Tn&&(l=l.toJSON()),a.push(l);let c;if(W.isArray(l))c=[],l.forEach((d,f)=>{const g=i(d);W.isUndefined(g)||(c[f]=g)});else{if(!W.isPlainObject(l)&&m0(l))return a.pop(),l;c=Object.create(null);for(const[d,f]of Object.entries(l)){const g=n.has(d.toLowerCase())?p0:i(f);W.isUndefined(g)||(c[d]=g)}}return a.pop(),c};return i(o)}let Oe=class jS extends Error{static from(e,n,a,i,l,c){const d=new jS(e.message,n||e.code,a,i,l);return d.cause=e,d.name=e.name,e.status!=null&&d.status==null&&(d.status=e.status),c&&Object.assign(d,c),d}constructor(e,n,a,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),a&&(this.config=a),i&&(this.request=i),l&&(this.response=l,this.status=l.status)}toJSON(){const e=this.config,n=e&&W.hasOwnProp(e,"redact")?e.redact:void 0,a=W.isArray(n)&&n.length>0?y0(e,n):W.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:a,code:this.code,status:this.status}}};Oe.ERR_BAD_OPTION_VALUE="ERR_BAD_OPTION_VALUE",Oe.ERR_BAD_OPTION="ERR_BAD_OPTION",Oe.ECONNABORTED="ECONNABORTED",Oe.ETIMEDOUT="ETIMEDOUT",Oe.ECONNREFUSED="ECONNREFUSED",Oe.ERR_NETWORK="ERR_NETWORK",Oe.ERR_FR_TOO_MANY_REDIRECTS="ERR_FR_TOO_MANY_REDIRECTS",Oe.ERR_DEPRECATED="ERR_DEPRECATED",Oe.ERR_BAD_RESPONSE="ERR_BAD_RESPONSE",Oe.ERR_BAD_REQUEST="ERR_BAD_REQUEST",Oe.ERR_CANCELED="ERR_CANCELED",Oe.ERR_NOT_SUPPORT="ERR_NOT_SUPPORT",Oe.ERR_INVALID_URL="ERR_INVALID_URL",Oe.ERR_FORM_DATA_DEPTH_EXCEEDED="ERR_FORM_DATA_DEPTH_EXCEEDED";const b0=null;function Ed(o){return W.isPlainObject(o)||W.isArray(o)}function Np(o){return W.endsWith(o,"[]")?o.slice(0,-2):o}function _d(o,e,n){return o?o.concat(e).map(function(i,l){return i=Np(i),!n&&l?"["+i+"]":i}).join(n?".":""):e}function v0(o){return W.isArray(o)&&!o.some(Ed)}const S0=W.toFlatObject(W,{},null,function(e){return/^is[A-Z]/.test(e)});function Vl(o,e,n){if(!W.isObject(o))throw new TypeError("target must be an object");e=e||new FormData,n=W.toFlatObject(n,{metaTokens:!0,dots:!1,indexes:!1},!1,function(x,L){return!W.isUndefined(L[x])});const a=n.metaTokens,i=n.visitor||b,l=n.dots,c=n.indexes,d=n.Blob||typeof Blob<"u"&&Blob,f=n.maxDepth===void 0?100:n.maxDepth,g=d&&W.isSpecCompliantForm(e);if(!W.isFunction(i))throw new TypeError("visitor must be a function");function m(A){if(A===null)return"";if(W.isDate(A))return A.toISOString();if(W.isBoolean(A))return A.toString();if(!g&&W.isBlob(A))throw new Oe("Blob is not supported. Use a Buffer instead.");return W.isArrayBuffer(A)||W.isTypedArray(A)?g&&typeof Blob=="function"?new Blob([A]):Buffer.from(A):A}function b(A,x,L){let M=A;if(W.isReactNative(e)&&W.isReactNativeBlob(A))return e.append(_d(L,x,l),m(A)),!1;if(A&&!L&&typeof A=="object"){if(W.endsWith(x,"{}"))x=a?x:x.slice(0,-2),A=JSON.stringify(A);else if(W.isArray(A)&&v0(A)||(W.isFileList(A)||W.endsWith(x,"[]"))&&(M=W.toArray(A)))return x=Np(x),M.forEach(function(D,B){!(W.isUndefined(D)||D===null)&&e.append(c===!0?_d([x],B,l):c===null?x:x+"[]",m(D))}),!1}return Ed(A)?!0:(e.append(_d(L,x,l),m(A)),!1)}const S=[],v=Object.assign(S0,{defaultVisitor:b,convertValue:m,isVisitable:Ed});function _(A,x,L=0){if(!W.isUndefined(A)){if(L>f)throw new Oe("Object is too deeply nested ("+L+" levels). Max depth: "+f,Oe.ERR_FORM_DATA_DEPTH_EXCEEDED);if(S.indexOf(A)!==-1)throw Error("Circular reference detected in "+x.join("."));S.push(A),W.forEach(A,function(R,D){(!(W.isUndefined(R)||R===null)&&i.call(e,R,W.isString(D)?D.trim():D,x,v))===!0&&_(R,x?x.concat(D):[D],L+1)}),S.pop()}}if(!W.isObject(o))throw new TypeError("data must be an object");return _(o),e}function Ip(o){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+"};return encodeURIComponent(o).replace(/[!'()~]|%20/g,function(a){return e[a]})}function Ad(o,e){this._pairs=[],o&&Vl(o,this,e)}const Hp=Ad.prototype;Hp.append=function(e,n){this._pairs.push([e,n])},Hp.toString=function(e){const n=e?function(a){return e.call(this,a,Ip)}:Ip;return this._pairs.map(function(i){return n(i[0])+"="+n(i[1])},"").join("&")};function w0(o){return encodeURIComponent(o).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function zp(o,e,n){if(!e)return o;const a=n&&n.encode||w0,i=W.isFunction(n)?{serialize:n}:n,l=i&&i.serialize;let c;if(l?c=l(e,i):c=W.isURLSearchParams(e)?e.toString():new Ad(e,i).toString(a),c){const d=o.indexOf("#");d!==-1&&(o=o.slice(0,d)),o+=(o.indexOf("?")===-1?"?":"&")+c}return o}class jp{constructor(){this.handlers=[]}use(e,n,a){return this.handlers.push({fulfilled:e,rejected:n,synchronous:a?a.synchronous:!1,runWhen:a?a.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){W.forEach(this.handlers,function(a){a!==null&&e(a)})}}const xd={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1,legacyInterceptorReqResOrdering:!0},C0={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:Ad,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},Td=typeof window<"u"&&typeof document<"u",Rd=typeof navigator=="object"&&navigator||void 0,E0=Td&&(!Rd||["ReactNative","NativeScript","NS"].indexOf(Rd.product)<0),_0=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",A0=Td&&window.location.href||"http://localhost",Cn={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Td,hasStandardBrowserEnv:E0,hasStandardBrowserWebWorkerEnv:_0,navigator:Rd,origin:A0},Symbol.toStringTag,{value:"Module"})),...C0};function x0(o,e){return Vl(o,new Cn.classes.URLSearchParams,{visitor:function(n,a,i,l){return Cn.isNode&&W.isBuffer(n)?(this.append(a,n.toString("base64")),!1):l.defaultVisitor.apply(this,arguments)},...e})}function T0(o){return W.matchAll(/\w+|\[(\w*)]/g,o).map(e=>e[0]==="[]"?"":e[1]||e[0])}function R0(o){const e={},n=Object.keys(o);let a;const i=n.length;let l;for(a=0;a=n.length;return c=!c&&W.isArray(i)?i.length:c,f?(W.hasOwnProp(i,c)?i[c]=W.isArray(i[c])?i[c].concat(a):[i[c],a]:i[c]=a,!d):((!W.hasOwnProp(i,c)||!W.isObject(i[c]))&&(i[c]=[]),e(n,a,i[c],l)&&W.isArray(i[c])&&(i[c]=R0(i[c])),!d)}if(W.isFormData(o)&&W.isFunction(o.entries)){const n={};return W.forEachEntry(o,(a,i)=>{e(T0(a),i,n,0)}),n}return null}const is=(o,e)=>o!=null&&W.hasOwnProp(o,e)?o[e]:void 0;function k0(o,e,n){if(W.isString(o))try{return(e||JSON.parse)(o),W.trim(o)}catch(a){if(a.name!=="SyntaxError")throw a}return(n||JSON.stringify)(o)}const uo={transitional:xd,adapter:["xhr","http","fetch"],transformRequest:[function(e,n){const a=n.getContentType()||"",i=a.indexOf("application/json")>-1,l=W.isObject(e);if(l&&W.isHTMLForm(e)&&(e=new FormData(e)),W.isFormData(e))return i?JSON.stringify(Up(e)):e;if(W.isArrayBuffer(e)||W.isBuffer(e)||W.isStream(e)||W.isFile(e)||W.isBlob(e)||W.isReadableStream(e))return e;if(W.isArrayBufferView(e))return e.buffer;if(W.isURLSearchParams(e))return n.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let d;if(l){const f=is(this,"formSerializer");if(a.indexOf("application/x-www-form-urlencoded")>-1)return x0(e,f).toString();if((d=W.isFileList(e))||a.indexOf("multipart/form-data")>-1){const g=is(this,"env"),m=g&&g.FormData;return Vl(d?{"files[]":e}:e,m&&new m,f)}}return l||i?(n.setContentType("application/json",!1),k0(e)):e}],transformResponse:[function(e){const n=is(this,"transitional")||uo.transitional,a=n&&n.forcedJSONParsing,i=is(this,"responseType"),l=i==="json";if(W.isResponse(e)||W.isReadableStream(e))return e;if(e&&W.isString(e)&&(a&&!i||l)){const d=!(n&&n.silentJSONParsing)&&l;try{return JSON.parse(e,is(this,"parseReviver"))}catch(f){if(d)throw f.name==="SyntaxError"?Oe.from(f,Oe.ERR_BAD_RESPONSE,this,null,is(this,"response")):f}}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}}};W.forEach(["delete","get","head","post","put","patch","query"],o=>{uo.headers[o]={}});function kd(o,e){const n=this||uo,a=e||n,i=Tn.from(a.headers);let l=a.data;return W.forEach(o,function(d){l=d.call(n,l,i.normalize(),e?e.status:void 0)}),i.normalize(),l}function Bp(o){return!!(o&&o.__CANCEL__)}let fo=class extends Oe{constructor(e,n,a){super(e??"canceled",Oe.ERR_CANCELED,n,a),this.name="CanceledError",this.__CANCEL__=!0}};function Pp(o,e,n){const a=n.config.validateStatus;!n.status||!a||a(n.status)?o(n):e(new Oe("Request failed with status code "+n.status,n.status>=400&&n.status<500?Oe.ERR_BAD_REQUEST:Oe.ERR_BAD_RESPONSE,n.config,n.request,n))}function D0(o){const e=/^([-+\w]{1,25}):(?:\/\/)?/.exec(o);return e&&e[1]||""}function O0(o,e){o=o||10;const n=new Array(o),a=new Array(o);let i=0,l=0,c;return e=e!==void 0?e:1e3,function(f){const g=Date.now(),m=a[l];c||(c=g),n[i]=f,a[i]=g;let b=l,S=0;for(;b!==i;)S+=n[b++],b=b%o;if(i=(i+1)%o,i===l&&(l=(l+1)%o),g-c{n=m,i=null,l&&(clearTimeout(l),l=null),o(...g)};return[(...g)=>{const m=Date.now(),b=m-n;b>=a?c(g,m):(i=g,l||(l=setTimeout(()=>{l=null,c(i)},a-b)))},()=>i&&c(i)]}const Fl=(o,e,n=3)=>{let a=0;const i=O0(50,250);return L0(l=>{if(!l||typeof l.loaded!="number")return;const c=l.loaded,d=l.lengthComputable?l.total:void 0,f=d!=null?Math.min(c,d):c,g=Math.max(0,f-a),m=i(g);a=Math.max(a,f);const b={loaded:f,total:d,progress:d?f/d:void 0,bytes:g,rate:m||void 0,estimated:m&&d?(d-f)/m:void 0,event:l,lengthComputable:d!=null,[e?"download":"upload"]:!0};o(b)},n)},qp=(o,e)=>{const n=o!=null;return[a=>e[0]({lengthComputable:n,total:o,loaded:a}),e[1]]},Gp=o=>(...e)=>W.asap(()=>o(...e)),M0=Cn.hasStandardBrowserEnv?((o,e)=>n=>(n=new URL(n,Cn.origin),o.protocol===n.protocol&&o.host===n.host&&(e||o.port===n.port)))(new URL(Cn.origin),Cn.navigator&&/(msie|trident)/i.test(Cn.navigator.userAgent)):()=>!0,$0=Cn.hasStandardBrowserEnv?{write(o,e,n,a,i,l,c){if(typeof document>"u")return;const d=[`${o}=${encodeURIComponent(e)}`];W.isNumber(n)&&d.push(`expires=${new Date(n).toUTCString()}`),W.isString(a)&&d.push(`path=${a}`),W.isString(i)&&d.push(`domain=${i}`),l===!0&&d.push("secure"),W.isString(c)&&d.push(`SameSite=${c}`),document.cookie=d.join("; ")},read(o){if(typeof document>"u")return null;const e=document.cookie.split(";");for(let n=0;no instanceof Tn?{...o}:o;function pi(o,e){e=e||{};const n=Object.create(null);Object.defineProperty(n,"hasOwnProperty",{__proto__:null,value:Object.prototype.hasOwnProperty,enumerable:!1,writable:!0,configurable:!0});function a(g,m,b,S){return W.isPlainObject(g)&&W.isPlainObject(m)?W.merge.call({caseless:S},g,m):W.isPlainObject(m)?W.merge({},m):W.isArray(m)?m.slice():m}function i(g,m,b,S){if(W.isUndefined(m)){if(!W.isUndefined(g))return a(void 0,g,b,S)}else return a(g,m,b,S)}function l(g,m){if(!W.isUndefined(m))return a(void 0,m)}function c(g,m){if(W.isUndefined(m)){if(!W.isUndefined(g))return a(void 0,g)}else return a(void 0,m)}function d(g,m,b){if(W.hasOwnProp(e,b))return a(g,m);if(W.hasOwnProp(o,b))return a(void 0,g)}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,allowedSocketPaths:c,responseEncoding:c,validateStatus:d,headers:(g,m,b)=>i(Fp(g),Fp(m),b,!0)};return W.forEach(Object.keys({...o,...e}),function(m){if(m==="__proto__"||m==="constructor"||m==="prototype")return;const b=W.hasOwnProp(f,m)?f[m]:i,S=W.hasOwnProp(o,m)?o[m]:void 0,v=W.hasOwnProp(e,m)?e[m]:void 0,_=b(S,v,m);W.isUndefined(_)&&b!==d||(n[m]=_)}),n}const H0=["content-type","content-length"];function z0(o,e,n){if(n!=="content-only"){o.set(e);return}Object.entries(e).forEach(([a,i])=>{H0.includes(a.toLowerCase())&&o.set(a,i)})}const j0=o=>encodeURIComponent(o).replace(/%([0-9A-F]{2})/gi,(e,n)=>String.fromCharCode(parseInt(n,16))),Kp=o=>{const e=pi({},o),n=S=>W.hasOwnProp(e,S)?e[S]:void 0,a=n("data");let i=n("withXSRFToken");const l=n("xsrfHeaderName"),c=n("xsrfCookieName");let d=n("headers");const f=n("auth"),g=n("baseURL"),m=n("allowAbsoluteUrls"),b=n("url");if(e.headers=d=Tn.from(d),e.url=zp(Vp(g,b,m),o.params,o.paramsSerializer),f&&d.set("Authorization","Basic "+btoa((f.username||"")+":"+(f.password?j0(f.password):""))),W.isFormData(a)&&(Cn.hasStandardBrowserEnv||Cn.hasStandardBrowserWebWorkerEnv?d.setContentType(void 0):W.isFunction(a.getHeaders)&&z0(d,a.getHeaders(),n("formDataHeaderPolicy"))),Cn.hasStandardBrowserEnv&&(W.isFunction(i)&&(i=i(e)),i===!0||i==null&&M0(e.url))){const v=l&&c&&$0.read(c);v&&d.set(l,v)}return e},U0=typeof XMLHttpRequest<"u"&&function(o){return new Promise(function(n,a){const i=Kp(o);let l=i.data;const c=Tn.from(i.headers).normalize();let{responseType:d,onUploadProgress:f,onDownloadProgress:g}=i,m,b,S,v,_;function A(){v&&v(),_&&_(),i.cancelToken&&i.cancelToken.unsubscribe(m),i.signal&&i.signal.removeEventListener("abort",m)}let x=new XMLHttpRequest;x.open(i.method.toUpperCase(),i.url,!0),x.timeout=i.timeout;function L(){if(!x)return;const R=Tn.from("getAllResponseHeaders"in x&&x.getAllResponseHeaders()),B={data:!d||d==="text"||d==="json"?x.responseText:x.response,status:x.status,statusText:x.statusText,headers:R,config:o,request:x};Pp(function(P){n(P),A()},function(P){a(P),A()},B),x=null}"onloadend"in x?x.onloadend=L:x.onreadystatechange=function(){!x||x.readyState!==4||x.status===0&&!(x.responseURL&&x.responseURL.startsWith("file:"))||setTimeout(L)},x.onabort=function(){x&&(a(new Oe("Request aborted",Oe.ECONNABORTED,o,x)),A(),x=null)},x.onerror=function(D){const B=D&&D.message?D.message:"Network Error",q=new Oe(B,Oe.ERR_NETWORK,o,x);q.event=D||null,a(q),A(),x=null},x.ontimeout=function(){let D=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const B=i.transitional||xd;i.timeoutErrorMessage&&(D=i.timeoutErrorMessage),a(new Oe(D,B.clarifyTimeoutError?Oe.ETIMEDOUT:Oe.ECONNABORTED,o,x)),A(),x=null},l===void 0&&c.setContentType(null),"setRequestHeader"in x&&W.forEach(Mp(c),function(D,B){x.setRequestHeader(B,D)}),W.isUndefined(i.withCredentials)||(x.withCredentials=!!i.withCredentials),d&&d!=="json"&&(x.responseType=i.responseType),g&&([S,_]=Fl(g,!0),x.addEventListener("progress",S)),f&&x.upload&&([b,v]=Fl(f),x.upload.addEventListener("progress",b),x.upload.addEventListener("loadend",v)),(i.cancelToken||i.signal)&&(m=R=>{x&&(a(!R||R.type?new fo(null,o,x):R),x.abort(),A(),x=null)},i.cancelToken&&i.cancelToken.subscribe(m),i.signal&&(i.signal.aborted?m():i.signal.addEventListener("abort",m)));const M=D0(i.url);if(M&&!Cn.protocols.includes(M)){a(new Oe("Unsupported protocol "+M+":",Oe.ERR_BAD_REQUEST,o));return}x.send(l||null)})},B0=(o,e)=>{if(o=o?o.filter(Boolean):[],!e&&!o.length)return;const n=new AbortController;let a=!1;const i=function(f){if(!a){a=!0,c();const g=f instanceof Error?f:this.reason;n.abort(g instanceof Oe?g:new fo(g instanceof Error?g.message:g))}};let l=e&&setTimeout(()=>{l=null,i(new Oe(`timeout of ${e}ms exceeded`,Oe.ETIMEDOUT))},e);const c=()=>{o&&(l&&clearTimeout(l),l=null,o.forEach(f=>{f.unsubscribe?f.unsubscribe(i):f.removeEventListener("abort",i)}),o=null)};o.forEach(f=>f.addEventListener("abort",i));const{signal:d}=n;return d.unsubscribe=()=>W.asap(c),d},P0=function*(o,e){let n=o.byteLength;if(n{const i=q0(o,e);let l=0,c,d=f=>{c||(c=!0,a&&a(f))};return new ReadableStream({async pull(f){try{const{done:g,value:m}=await i.next();if(g){d(),f.close();return}let b=m.byteLength;if(n){let S=l+=b;n(S)}f.enqueue(new Uint8Array(m))}catch(g){throw d(g),g}},cancel(f){return d(f),i.return()}},{highWaterMark:2})};function V0(o){if(!o||typeof o!="string"||!o.startsWith("data:"))return 0;const e=o.indexOf(",");if(e<0)return 0;const n=o.slice(5,e),a=o.slice(e+1);if(/;base64/i.test(n)){let c=a.length;const d=a.length;for(let v=0;v=48&&_<=57||_>=65&&_<=70||_>=97&&_<=102)&&(A>=48&&A<=57||A>=65&&A<=70||A>=97&&A<=102)&&(c-=2,v+=2)}let f=0,g=d-1;const m=v=>v>=2&&a.charCodeAt(v-2)===37&&a.charCodeAt(v-1)===51&&(a.charCodeAt(v)===68||a.charCodeAt(v)===100);g>=0&&(a.charCodeAt(g)===61?(f++,g--):m(g)&&(f++,g-=3)),f===1&&g>=0&&(a.charCodeAt(g)===61||m(g))&&f++;const S=Math.floor(c/4)*3-(f||0);return S>0?S:0}if(typeof Buffer<"u"&&typeof Buffer.byteLength=="function")return Buffer.byteLength(a,"utf8");let l=0;for(let c=0,d=a.length;c=55296&&f<=56319&&c+1=56320&&g<=57343?(l+=4,c++):l+=3}else l+=3}return l}const Dd="1.16.1",Yp=64*1024,{isFunction:Kl}=W,Xp=(o,...e)=>{try{return!!o(...e)}catch{return!1}},F0=o=>{const e=W.global!==void 0&&W.global!==null?W.global:globalThis,{ReadableStream:n,TextEncoder:a}=e;o=W.merge.call({skipUndefined:!0},{Request:e.Request,Response:e.Response},o);const{fetch:i,Request:l,Response:c}=o,d=i?Kl(i):typeof fetch=="function",f=Kl(l),g=Kl(c);if(!d)return!1;const m=d&&Kl(n),b=d&&(typeof a=="function"?(L=>M=>L.encode(M))(new a):async L=>new Uint8Array(await new l(L).arrayBuffer())),S=f&&m&&Xp(()=>{let L=!1;const M=new l(Cn.origin,{body:new n,method:"POST",get duplex(){return L=!0,"half"}}),R=M.headers.has("Content-Type");return M.body!=null&&M.body.cancel(),L&&!R}),v=g&&m&&Xp(()=>W.isReadableStream(new c("").body)),_={stream:v&&(L=>L.body)};d&&["text","arrayBuffer","blob","formData","stream"].forEach(L=>{!_[L]&&(_[L]=(M,R)=>{let D=M&&M[L];if(D)return D.call(M);throw new Oe(`Response type '${L}' is not supported`,Oe.ERR_NOT_SUPPORT,R)})});const A=async L=>{if(L==null)return 0;if(W.isBlob(L))return L.size;if(W.isSpecCompliantForm(L))return(await new l(Cn.origin,{method:"POST",body:L}).arrayBuffer()).byteLength;if(W.isArrayBufferView(L)||W.isArrayBuffer(L))return L.byteLength;if(W.isURLSearchParams(L)&&(L=L+""),W.isString(L))return(await b(L)).byteLength},x=async(L,M)=>{const R=W.toFiniteNumber(L.getContentLength());return R??A(M)};return async L=>{let{url:M,method:R,data:D,signal:B,cancelToken:q,timeout:P,onDownloadProgress:K,onUploadProgress:ge,responseType:Ee,headers:Se,withCredentials:Ue="same-origin",fetchOptions:Ve,maxContentLength:qe,maxBodyLength:St}=Kp(L);const J=W.isNumber(qe)&&qe>-1,fe=W.isNumber(St)&&St>-1;let Le=i||fetch;Ee=Ee?(Ee+"").toLowerCase():"text";let Z=B0([B,q&&q.toAbortSignal()],P),pe=null;const H=Z&&Z.unsubscribe&&(()=>{Z.unsubscribe()});let T;try{if(J&&typeof M=="string"&&M.startsWith("data:")&&V0(M)>qe)throw new Oe("maxContentLength size of "+qe+" exceeded",Oe.ERR_BAD_RESPONSE,L,pe);if(fe&&R!=="get"&&R!=="head"){const _e=await x(Se,D);if(typeof _e=="number"&&isFinite(_e)&&_e>St)throw new Oe("Request body larger than maxBodyLength limit",Oe.ERR_BAD_REQUEST,L,pe)}if(ge&&S&&R!=="get"&&R!=="head"&&(T=await x(Se,D))!==0){let _e=new l(M,{method:"POST",body:D,duplex:"half"}),Te;if(W.isFormData(D)&&(Te=_e.headers.get("content-type"))&&Se.setContentType(Te),_e.body){const[$e,ht]=qp(T,Fl(Gp(ge)));D=Wp(_e.body,Yp,$e,ht)}}W.isString(Ue)||(Ue=Ue?"include":"omit");const ce=f&&"credentials"in l.prototype;if(W.isFormData(D)){const _e=Se.getContentType();_e&&/^multipart\/form-data/i.test(_e)&&!/boundary=/i.test(_e)&&Se.delete("content-type")}Se.set("User-Agent","axios/"+Dd,!1);const de={...Ve,signal:Z,method:R.toUpperCase(),headers:Mp(Se.normalize()),body:D,duplex:"half",credentials:ce?Ue:void 0};pe=f&&new l(M,de);let ye=await(f?Le(pe,Ve):Le(M,de));if(J){const _e=W.toFiniteNumber(ye.headers.get("content-length"));if(_e!=null&&_e>qe)throw new Oe("maxContentLength size of "+qe+" exceeded",Oe.ERR_BAD_RESPONSE,L,pe)}const ie=v&&(Ee==="stream"||Ee==="response");if(v&&ye.body&&(K||J||ie&&H)){const _e={};["status","statusText","headers"].forEach(ft=>{_e[ft]=ye[ft]});const Te=W.toFiniteNumber(ye.headers.get("content-length")),[$e,ht]=K&&qp(Te,Fl(Gp(K),!0))||[];let wt=0;const kt=ft=>{if(J&&(wt=ft,wt>qe))throw new Oe("maxContentLength size of "+qe+" exceeded",Oe.ERR_BAD_RESPONSE,L,pe);$e&&$e(ft)};ye=new c(Wp(ye.body,Yp,kt,()=>{ht&&ht(),H&&H()}),_e)}Ee=Ee||"text";let xe=await _[W.findKey(_,Ee)||"text"](ye,L);if(J&&!v&&!ie){let _e;if(xe!=null&&(typeof xe.byteLength=="number"?_e=xe.byteLength:typeof xe.size=="number"?_e=xe.size:typeof xe=="string"&&(_e=typeof a=="function"?new a().encode(xe).byteLength:xe.length)),typeof _e=="number"&&_e>qe)throw new Oe("maxContentLength size of "+qe+" exceeded",Oe.ERR_BAD_RESPONSE,L,pe)}return!ie&&H&&H(),await new Promise((_e,Te)=>{Pp(_e,Te,{data:xe,headers:Tn.from(ye.headers),status:ye.status,statusText:ye.statusText,config:L,request:pe})})}catch(ce){if(H&&H(),Z&&Z.aborted&&Z.reason instanceof Oe){const de=Z.reason;throw de.config=L,pe&&(de.request=pe),ce!==de&&(de.cause=ce),de}throw ce&&ce.name==="TypeError"&&/Load failed|fetch/i.test(ce.message)?Object.assign(new Oe("Network Error",Oe.ERR_NETWORK,L,pe,ce&&ce.response),{cause:ce.cause||ce}):Oe.from(ce,ce&&ce.code,L,pe,ce&&ce.response)}}},K0=new Map,Jp=o=>{let e=o&&o.env||{};const{fetch:n,Request:a,Response:i}=e,l=[a,i,n];let c=l.length,d=c,f,g,m=K0;for(;d--;)f=l[d],g=m.get(f),g===void 0&&m.set(f,g=d?new Map:F0(e)),m=g;return g};Jp();const Od={http:b0,xhr:U0,fetch:{get:Jp}};W.forEach(Od,(o,e)=>{if(o){try{Object.defineProperty(o,"name",{__proto__:null,value:e})}catch{}Object.defineProperty(o,"adapterName",{__proto__:null,value:e})}});const Qp=o=>`- ${o}`,W0=o=>W.isFunction(o)||o===null||o===!1;function Y0(o,e){o=W.isArray(o)?o:[o];const{length:n}=o;let a,i;const l={};for(let c=0;c`adapter ${f} `+(g===!1?"is not supported by the environment":"is not available in the build"));let d=n?c.length>1?`since : -`+c.map(Qp).join(` -`):" "+Qp(c[0]):"as no adapter specified";throw new Oe("There is no suitable adapter to dispatch the request "+d,"ERR_NOT_SUPPORT")}return i}const Zp={getAdapter:Y0,adapters:Od};function Ld(o){if(o.cancelToken&&o.cancelToken.throwIfRequested(),o.signal&&o.signal.aborted)throw new fo(null,o)}function em(o){return Ld(o),o.headers=Tn.from(o.headers),o.data=kd.call(o,o.transformRequest),["post","put","patch"].indexOf(o.method)!==-1&&o.headers.setContentType("application/x-www-form-urlencoded",!1),Zp.getAdapter(o.adapter||uo.adapter,o)(o).then(function(a){Ld(o),o.response=a;try{a.data=kd.call(o,o.transformResponse,a)}finally{delete o.response}return a.headers=Tn.from(a.headers),a},function(a){if(!Bp(a)&&(Ld(o),a&&a.response)){o.response=a.response;try{a.response.data=kd.call(o,o.transformResponse,a.response)}finally{delete o.response}a.response.headers=Tn.from(a.response.headers)}return Promise.reject(a)})}const Wl={};["object","boolean","number","function","string","symbol"].forEach((o,e)=>{Wl[o]=function(a){return typeof a===o||"a"+(e<1?"n ":" ")+o}});const tm={};Wl.transitional=function(e,n,a){function i(l,c){return"[Axios v"+Dd+"] Transitional option '"+l+"'"+c+(a?". "+a:"")}return(l,c,d)=>{if(e===!1)throw new Oe(i(c," has been removed"+(n?" in "+n:"")),Oe.ERR_DEPRECATED);return n&&!tm[c]&&(tm[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}},Wl.spelling=function(e){return(n,a)=>(console.warn(`${a} is likely a misspelling of ${e}`),!0)};function X0(o,e,n){if(typeof o!="object")throw new Oe("options must be an object",Oe.ERR_BAD_OPTION_VALUE);const a=Object.keys(o);let i=a.length;for(;i-- >0;){const l=a[i],c=Object.prototype.hasOwnProperty.call(e,l)?e[l]:void 0;if(c){const d=o[l],f=d===void 0||c(d,l,o);if(f!==!0)throw new Oe("option "+l+" must be "+f,Oe.ERR_BAD_OPTION_VALUE);continue}if(n!==!0)throw new Oe("Unknown option "+l,Oe.ERR_BAD_OPTION)}}const Yl={assertOptions:X0,validators:Wl},nr=Yl.validators;let mi=class{constructor(e){this.defaults=e||{},this.interceptors={request:new jp,response:new jp}}async request(e,n){try{return await this._request(e,n)}catch(a){if(a instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const l=(()=>{if(!i.stack)return"";const c=i.stack.indexOf(` -`);return c===-1?"":i.stack.slice(c+1)})();try{if(!a.stack)a.stack=l;else if(l){const c=l.indexOf(` -`),d=c===-1?-1:l.indexOf(` -`,c+1),f=d===-1?"":l.slice(d+1);String(a.stack).endsWith(f)||(a.stack+=` -`+l)}}catch{}}throw a}}_request(e,n){typeof e=="string"?(n=n||{},n.url=e):n=e||{},n=pi(this.defaults,n);const{transitional:a,paramsSerializer:i,headers:l}=n;a!==void 0&&Yl.assertOptions(a,{silentJSONParsing:nr.transitional(nr.boolean),forcedJSONParsing:nr.transitional(nr.boolean),clarifyTimeoutError:nr.transitional(nr.boolean),legacyInterceptorReqResOrdering:nr.transitional(nr.boolean)},!1),i!=null&&(W.isFunction(i)?n.paramsSerializer={serialize:i}:Yl.assertOptions(i,{encode:nr.function,serialize:nr.function},!0)),n.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?n.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:n.allowAbsoluteUrls=!0),Yl.assertOptions(n,{baseUrl:nr.spelling("baseURL"),withXsrfToken:nr.spelling("withXSRFToken")},!0),n.method=(n.method||this.defaults.method||"get").toLowerCase();let c=l&&W.merge(l.common,l[n.method]);l&&W.forEach(["delete","get","head","post","put","patch","query","common"],_=>{delete l[_]}),n.headers=Tn.concat(c,l);const d=[];let f=!0;this.interceptors.request.forEach(function(A){if(typeof A.runWhen=="function"&&A.runWhen(n)===!1)return;f=f&&A.synchronous;const x=n.transitional||xd;x&&x.legacyInterceptorReqResOrdering?d.unshift(A.fulfilled,A.rejected):d.push(A.fulfilled,A.rejected)});const g=[];this.interceptors.response.forEach(function(A){g.push(A.fulfilled,A.rejected)});let m,b=0,S;if(!f){const _=[em.bind(this),void 0];for(_.unshift(...d),_.push(...g),S=_.length,m=Promise.resolve(n);b{if(!a._listeners)return;let l=a._listeners.length;for(;l-- >0;)a._listeners[l](i);a._listeners=null}),this.promise.then=i=>{let l;const c=new Promise(d=>{a.subscribe(d),l=d}).then(i);return c.cancel=function(){a.unsubscribe(l)},c},e(function(l,c,d){a.reason||(a.reason=new fo(l,c,d),n(a.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const n=this._listeners.indexOf(e);n!==-1&&this._listeners.splice(n,1)}toAbortSignal(){const e=new AbortController,n=a=>{e.abort(a)};return this.subscribe(n),e.signal.unsubscribe=()=>this.unsubscribe(n),e.signal}static source(){let e;return{token:new US(function(i){e=i}),cancel:e}}};function Q0(o){return function(n){return o.apply(null,n)}}function Z0(o){return W.isObject(o)&&o.isAxiosError===!0}const Md={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,WebServerIsDown:521,ConnectionTimedOut:522,OriginIsUnreachable:523,TimeoutOccurred:524,SslHandshakeFailed:525,InvalidSslCertificate:526};Object.entries(Md).forEach(([o,e])=>{Md[e]=o});function nm(o){const e=new mi(o),n=Ep(mi.prototype.request,e);return W.extend(n,mi.prototype,e,{allOwnKeys:!0}),W.extend(n,e,null,{allOwnKeys:!0}),n.create=function(i){return nm(pi(o,i))},n}const Vt=nm(uo);Vt.Axios=mi,Vt.CanceledError=fo,Vt.CancelToken=J0,Vt.isCancel=Bp,Vt.VERSION=Dd,Vt.toFormData=Vl,Vt.AxiosError=Oe,Vt.Cancel=Vt.CanceledError,Vt.all=function(e){return Promise.all(e)},Vt.spread=Q0,Vt.isAxiosError=Z0,Vt.mergeConfig=pi,Vt.AxiosHeaders=Tn,Vt.formToJSON=o=>Up(W.isHTMLForm(o)?new FormData(o):o),Vt.getAdapter=Zp.getAdapter,Vt.HttpStatusCode=Md,Vt.default=Vt;const{Axios:mT,AxiosError:yT,CanceledError:bT,isCancel:vT,CancelToken:ST,VERSION:wT,all:CT,Cancel:ET,isAxiosError:_T,spread:AT,toFormData:xT,AxiosHeaders:TT,HttpStatusCode:RT,formToJSON:kT,getAdapter:DT,mergeConfig:OT,create:LT}=Vt,$d="g7.identity.redirectStash",Xl=ut("IdentityGuardInterceptor");class vt{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){Xl.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,a){this.domainNoticeShown=!1;const i=this.launcher??tC,c=!!(a&&(a.email||a.phone))?{...e.verification,target:a}:e.verification,d=await i(c);if(d.status!=="verified")return null;const f=c.return_request;if(!f)return null;const g=eC(f.url,d.token);return fetch(g,{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 Xl.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 a={return_url:window.location.href,payload:e,stashed_at:Date.now()};try{window.sessionStorage?.setItem($d,JSON.stringify(a))}catch(i){Xl.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}}$(vt,"launcher",null),$(vt,"deferredResolver",null),$(vt,"domainNoticeShown",!1);function eC(o,e){if(!e)return o;try{const n=typeof window<"u"?window.location.origin:"http://localhost",a=new URL(o,n);return a.searchParams.set("verification_token",e),/^https?:\/\//i.test(o)?a.toString():`${a.pathname}${a.search}${a.hash}`}catch{const n=o.includes("?")?"&":"?";return`${o}${n}verification_token=${encodeURIComponent(e)}`}}const tC=async o=>{if(typeof window>"u")return{status:"cancelled"};if(o.render_hint==="external_redirect"||o.redirect_url)return vt.redirectExternally(o);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,a={return_url:n,payload:o,stashed_at:Date.now()};try{window.sessionStorage?.setItem($d,JSON.stringify(a))}catch{}const i=`/identity/challenge?return=${encodeURIComponent(n)}`;try{await e.dispatch({handler:"navigate",params:{path:i}})}catch(l){Xl.warn("navigate 실패 — window.location 으로 폴백",l),window.location.href=i}return new Promise(()=>{})},nC=ut("ApiClient");function Nd(){return typeof window<"u"&&window.__G7_DEVTOOLS__?window.__G7_DEVTOOLS__:null}class rC{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=Vt.create({baseURL:this.config.baseURL,timeout:this.config.timeout,headers:{"Content-Type":"application/json",Accept:"application/json"},paramsSerializer:{serialize:n=>{const a=[];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)a.push(`${encodeURIComponent(c)}=${encodeURIComponent(String(d))}`)}else a.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(l))}`);return a.join("&")}}}),this.setupInterceptors()}setToken(e){typeof window<"u"&&localStorage.setItem(this.TOKEN_KEY,e)}getToken(){return typeof window<"u"?localStorage.getItem(this.TOKEN_KEY):null}removeToken(){typeof window<"u"&&localStorage.removeItem(this.TOKEN_KEY)}setupInterceptors(){this.client.interceptors.request.use(e=>{e.url?.startsWith("/api")&&e.baseURL==="/api"&&(e.baseURL="");const n=this.getToken();if(n&&e.headers&&(e.headers.Authorization=`Bearer ${n}`),typeof window<"u"&&e.headers){const i=localStorage.getItem("g7_locale");i&&(e.headers["Accept-Language"]=i)}const a=Nd();if(a?.isEnabled()){const i=this.buildFullUrl(e),l=(e.method||"GET").toUpperCase(),c=a.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,a=n._devToolsRequestId;if(a){const i=Nd();i?.isEnabled()&&i.completeRequest(a,e.status,e.data),n._devToolsRequestId=null}return e},async e=>{const n=e.config,a=n?.url||"",l=["/auth/","/layouts/"].some(c=>a.includes(c));if(e.response?.status===401&&!n?._retry&&!l){if(n._retry=!0,await yr.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(vt.isIdentityRequired(e.response?.status,e.response?.data)){this.completeDevToolsRequest(n,e);const c={},d=n?.headers??{};for(const[S,v]of Object.entries(d))typeof v=="string"&&(c[S]=v);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 g=n?.identity_target,m=await vt.handle(e.response.data,{headers:c,body:f,credentials:"same-origin"},g);if(!m)return Promise.reject(e);let b=null;try{b=await m.json()}catch{b=null}return m.ok?{...e.response,status:m.status,data:b}:Promise.reject(Object.assign(new Error("replay failed"),{response:{status:m.status,data:b}}))}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,a){return(await this.client.post(e,n,a)).data}async put(e,n,a){return(await this.client.put(e,n,a)).data}async patch(e,n,a){return(await this.client.patch(e,n,a)).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 a=Nd();if(!a?.isEnabled())return;const i=e._devToolsRequestId;e._devToolsRequestId=null,n.response?a.completeRequest(i,n.response.status,n.response.data):n.request?a.failRequest(i,n.message||"Network error"):a.failRequest(i,n.message||"Request error")}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 a=e.params,i=[];for(const[l,c]of Object.entries(a))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(a){nC.error("Error in onError handler:",a)}}}let Id=null;function Ir(){return Id||(Id=new rC),Id}const ho=ut("AuthManager");function ss(o,e,n,a){try{window.G7Core?.devTools?.trackAuthEvent?.(o,e,n,a)}catch{}}const Jl={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"}},_r=class _r{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",Jl.admin),this.config.set("user",Jl.user)}static getInstance(){return _r.instance||(_r.instance=new _r),_r.instance}on(e,n){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(n)}emit(e,...n){const a=this.eventHandlers.get(e);a&&a.forEach(i=>i(...n))}isAuthenticated(){return this.state.isAuthenticated}getUser(){return this.state.user}getAuthType(){return this.state.type}async checkAuth(e){const n=Ir();if(!n.getToken())return this.clearState(),!1;const i=this.config.get(e);if(!i)return ho.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 ho.warn(`Preload auth failed for type ${e}:`,n),!1}}async login(e,n,a){const i=Ir();if(!this.config.get(e))throw new Error(`Unknown auth type: ${e}`);const c=e==="admin"?Jl.admin.loginEndpoint:Jl.user.loginEndpoint;try{const d=a?.headers?{headers:a.headers}:void 0,f=await i.post(c,n,d);if(f.success&&f.data){i.setToken(f.data.token);const g=f.data.user.language,m=localStorage.getItem(_r.LOCALE_STORAGE_KEY),b=g&&g!==m;if(g)try{localStorage.setItem(_r.LOCALE_STORAGE_KEY,g)}catch(S){ho.warn("Failed to save user language to localStorage:",S)}return this.state={isAuthenticated:!0,user:f.data.user,type:e},this.emit("login",this.state),this.emit("authStateChange",this.state),ss("login",!0,void 0,{userId:f.data.user.uuid,email:f.data.user.email,type:e}),b&&window.__templateApp&&window.__templateApp.changeLocale(g),f.data.user}throw new Error("Login failed")}catch(d){this.clearState();const f=d.response?.data?.message,g=new Error(f||d.message||"Login failed");throw g.response=d.response,g.status=d.response?.status,ss("login",!1,g.message,{type:e,status:d.response?.status}),g}}async logout(){const e=Ir(),n=this.state.type?this.config.get(this.state.type):null;try{n&&await e.post(n.logoutEndpoint)}catch(a){ho.warn("Logout API call failed:",a)}finally{e.removeToken();const a={...this.state};if(this.clearState(),this.emit("logout",a),this.emit("authStateChange",this.state),ss("logout",!0,void 0,{previousType:a.type}),n&&a.type){const i=window.location.pathname+window.location.search;window.location.href=this.getLoginRedirectUrl(a.type,i)}}}async refreshToken(){if(this.isRefreshing&&this.refreshPromise)return this.refreshPromise;this.isRefreshing=!0,this.refreshPromise=this.doRefreshToken();try{return await this.refreshPromise}finally{this.isRefreshing=!1,this.refreshPromise=null}}async doRefreshToken(){const e=this.state.type;if(!e)return!1;const n=this.config.get(e);if(!n)return!1;const a=Ir();try{const i=await a.post(n.refreshEndpoint);return i.success&&i.data?.token?(a.setToken(i.data.token),this.emit("tokenRefreshed"),ss("token-refresh",!0,void 0,{type:e}),!0):(ss("token-refresh",!1,"No token in response",{type:e}),!1)}catch(i){return ho.error("Token refresh failed:",i),ss("token-refresh",!1,i instanceof Error?i.message:"Unknown error",{type:e}),!1}}getLoginRedirectUrl(e,n,a){const i=this.config.get(e);if(!i)return"/login";const l=encodeURIComponent(n);let c=`${i.loginPath}?redirect=${l}`;return a&&(c+=`&reason=${encodeURIComponent(a)}`),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 a=this.config.get(e);a&&this.config.set(e,{...a,...n})}getRedirectUrl(e){const a=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 a}getConfig(e){return this.config.get(e)}clearState(){this.state={isAuthenticated:!1,user:null,type:null}}static resetInstance(){_r.instance=null}};$(_r,"instance"),$(_r,"LOCALE_STORAGE_KEY","g7_locale");let yr=_r;const rm={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}}"}}},Qr={findHandler(o,e){if(o){if(o[e])return o[e];if(o[String(e)])return o[String(e)];if(o.default)return o.default}},normalizeOnError(o){return o?Array.isArray(o)?o:[o]:[]},injectErrorCode(o,e,n){if(o.handler!=="showErrorPage"||o.params?.errorCode!==void 0)return o;const a=typeof e=="string"?parseInt(e,10):e,i=isNaN(a)?n:a;return i===void 0?o:{...o,params:{...o.params,errorCode:i}}}},br=ut("ErrorHandlingResolver"),Ma=class Ma{constructor(){$(this,"templateErrorHandling",null);$(this,"layoutErrorHandling",null);$(this,"executeAction",null)}static getInstance(){return Ma.instance||(Ma.instance=new Ma),Ma.instance}static resetInstance(){Ma.instance=null}setTemplateConfig(e){this.templateErrorHandling=e,br.log("Template config set:",e)}setLayoutConfig(e){this.layoutErrorHandling=e,br.log("Layout config set:",e)}setActionExecutor(e){this.executeAction=e}resolve(e,n={}){const{errorHandling:a,onError:i}=n;br.log("Resolving error:",e,{hasActionErrorHandling:!!a,hasActionOnError:!!i,hasLayoutConfig:!!this.layoutErrorHandling,hasTemplateConfig:!!this.templateErrorHandling});let l=Qr.findHandler(a,e);if(l){const c=this.getMatchedKey(a,e);return{handler:Qr.injectErrorCode(l,c,e),level:"action",matchedKey:c}}if(i){const c=Qr.normalizeOnError(i);if(c.length>0)return{handler:c.length===1?c[0]:{handler:"sequence",actions:c},level:"action",matchedKey:"onError"}}if(l=Qr.findHandler(this.layoutErrorHandling||void 0,e),l){const c=this.getMatchedKey(this.layoutErrorHandling,e);return{handler:Qr.injectErrorCode(l,c,e),level:"layout",matchedKey:c}}if(l=Qr.findHandler(this.templateErrorHandling||void 0,e),l){const c=this.getMatchedKey(this.templateErrorHandling,e);return{handler:Qr.injectErrorCode(l,c,e),level:"template",matchedKey:c}}if(l=Qr.findHandler(rm,e),l){const c=this.getMatchedKey(rm,e);return{handler:Qr.injectErrorCode(l,c,e),level:"system",matchedKey:c}}return{handler:null,level:null,matchedKey:null}}async execute(e,n){if(!this.executeAction){br.error("Action executor is not set");return}br.log("Executing handler:",e.handler,{errorContext:n});try{return await this.executeAction(e,{error:n})}catch(a){throw br.error("Failed to execute handler:",a),a}}async resolveAndExecute(e,n,a={}){const i=this.resolve(e,a);if(br.log("Resolve result:",{errorCode:e,handler:i.handler?.handler,level:i.level,matchedKey:i.matchedKey}),!i.handler)return br.warn("No handler found for error:",e),{handled:!1};try{return{handled:!0,result:await this.execute(i.handler,n)}}catch(l){return br.error("Handler execution failed:",l),{handled:!1}}}getMatchedKey(e,n){return e[n]?n:e[String(n)]?String(n):"default"}clearLayoutConfig(){this.layoutErrorHandling=null,br.log("Layout config cleared")}clearAllConfig(){this.templateErrorHandling=null,this.layoutErrorHandling=null,br.log("All config cleared")}getConfigStatus(){return{hasTemplate:this.templateErrorHandling!==null,hasLayout:this.layoutErrorHandling!==null,hasExecutor:this.executeAction!==null}}};$(Ma,"instance",null);let Hd=Ma;function vr(){return Hd.getInstance()}var zd={exports:{}},go={};var am;function aC(){if(am)return go;am=1;var o=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function n(a,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:o,type:a,key:c,ref:i!==void 0?i:null,props:l}}return go.Fragment=e,go.jsx=n,go.jsxs=n,go}var im;function iC(){return im||(im=1,zd.exports=aC()),zd.exports}var dt=iC();const sC=Xr({__proto__:null,default:Jr(dt)},[dt]),jd=ut("ParentContextProvider"),sm=N.createContext(null);let Ql=null;function Ud(){Ql?(jd.log("[triggerModalParentUpdate] 모달 부모 컨텍스트 업데이트 트리거"),Ql()):jd.warn("[triggerModalParentUpdate] Provider가 아직 마운트되지 않음")}const om=({children:o})=>{const[e,n]=N.useState(0),a=N.useRef(!0),i=N.useCallback(()=>{const c=window.__g7LayoutContextStack||[];return c[c.length-1]?.dataContext},[]);N.useEffect(()=>(a.current=!0,Ql=()=>{a.current&&(n(c=>c+1),jd.log("[ParentContextProvider] 버전 업데이트됨"))},()=>{a.current=!1,Ql=null}),[]);const l={version:e,getParentDataContext:i};return dt.jsx(sm.Provider,{value:l,children:o})};function oC(){return N.useContext(sm)}const z=ut("ActionDispatcher");function lC(o,e,n,a){return n||(np(o)||od(o)?"$t:core.errors.network_request_failed":a||`Failed to execute action: ${e}`)}const lm=new Set(["navigate","navigateBack","navigateForward","replaceUrl","refresh","logout"]),cC=new Set(["redirect"]);function qn(){try{return window.G7Core?.devTools}catch{return}}class jt extends Error{constructor(n,a,i){super(n);$(this,"action");$(this,"originalError");$(this,"unknownHandler",!1);this.action=a,this.originalError=i,this.name="ActionError"}}const cm={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"},ps=class ps{constructor(e={},n,a){$(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,"intervals",new Map);this.bindingEngine=new xn,this.translationEngine=n,this.translationContext=a,this.defaultContext=e,this.registerDefaultHandlers(),this.setupErrorHandling()}setGlobalHeaders(e){this.globalHeaders=e||[]}setNamedActions(e){this.namedActions=e||{};const n=qn();n?.isEnabled?.()&&n.setNamedActionDefinitions?.(this.namedActions),z.log("[setNamedActions] registered:",Object.keys(this.namedActions))}getNamedActions(){return this.namedActions}setPreviewMode(e){this.previewMode=e,z.log("Preview mode:",e?"enabled":"disabled")}isPreviewMode(){return this.previewMode}static getPreviewSuppressedHandlers(){return lm}static getPreviewSuppressedLayoutFeatures(){return cC}resolveActionRef(e){if(!e.actionRef)return e;const n=this.namedActions[e.actionRef];if(!n)return z.warn(`[resolveActionRef] named action not found: "${e.actionRef}"`),e;const a=qn();a?.isEnabled?.()&&a.trackNamedActionRef?.({actionRefName:e.actionRef,resolvedHandler:n.handler,timestamp:Date.now()});const{actionRef:i,type:l,key:c,event:d,...f}=e,g={...n,...Object.fromEntries(Object.entries(f).filter(([,m])=>m!==void 0)),type:l??n.type};return c!==void 0&&(g.key=c),d!==void 0&&(g.event=d),g}matchesPattern(e,n){if(n==="*")return!0;const a=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${a}$`).test(e)}getMatchingGlobalHeaders(e,n){const a={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,c])=>{const d=ns(c,n,{skipCache:!0});d!=null&&d!==""&&(a[l]=String(d))});return a}setupErrorHandling(){if(this.errorHandlingSetup)return;vr().setActionExecutor(async(n,a)=>{const i={type:"click",handler:n.handler,target:n.target,params:n.params,actions:n.actions},l={data:{...this.defaultContext.data,error:a.error}};return await this.dispatchAction(i,l)}),this.errorHandlingSetup=!0}registerDefaultHandlers(){this.registerHandler("refetchDataSource",async(n,a)=>{const i=n.params?.dataSourceId,l=n.params?.sync;if(!i){z.warn("refetchDataSource: dataSourceId is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.refetch){const c=window.G7Core?.state?.get?.()||{},d={...a.state?._global,...c},f=window.G7Core?.state?.getLocal?.()||{},g=a.data?._local||a.state||{},m={...f,...g},b=a.isolatedContext?.state;z.log("[refetchDataSource] localStateOverride:",m),await window.G7Core.dataSource.refetch(i,{...l?{sync:!0}:{},...d?{globalStateOverride:d}:{},...m?{localStateOverride:m}:{},...b?{isolatedStateOverride:b}:{}})}else z.warn("refetchDataSource: G7Core.dataSource.refetch is not available")}),this.registerHandler("appendDataSource",async(n,a)=>{const{dataSourceId:i,dataPath:l,newData:c}=n.params||{};if(!i){z.warn("appendDataSource: dataSourceId is required");return}if(c===void 0){z.warn("appendDataSource: newData is required");return}if(typeof window<"u"&&window.G7Core?.dataSource?.updateData){if(!Array.isArray(c)){z.warn("appendDataSource: newData must be an array, got:",typeof c,c);return}await window.G7Core.dataSource.updateData(i,l||null,c,"append")}else z.warn("appendDataSource: G7Core.dataSource.updateData is not available")}),this.registerHandler("updateDataSource",async(n,a)=>{const{dataSourceId:i,data:l,merge:c=!1}=n.params||{};if(!i){z.warn("updateDataSource: dataSourceId is required");return}if(l===void 0){z.warn("updateDataSource: data is required");return}typeof window<"u"&&window.G7Core?.dataSource?.set?(z.log(`[updateDataSource] Updating dataSource '${i}' with:`,l),window.G7Core.dataSource.set(i,l,{merge:c})):z.warn("updateDataSource: G7Core.dataSource.set is not available")}),this.registerHandler("scrollIntoView",async(n,a)=>{const{selector:i,behavior:l="smooth",block:c="nearest",inline:d="nearest",waitForElement:f=!1,timeout:g=2e3,delay:m=0,retryCount:b=0,retryInterval:S=50,scrollContainer:v}=n.params||{};if(!i){z.warn("scrollIntoView: selector is required");return}if(typeof window>"u"||typeof document>"u"){z.warn("scrollIntoView: window/document is not available");return}let _=null;if(f){if(_=await new Promise(A=>{const x=document.querySelector(i);if(x){A(x);return}const L=setTimeout(()=>{M.disconnect(),A(null)},g),M=new MutationObserver(()=>{const R=document.querySelector(i);R&&(clearTimeout(L),M.disconnect(),A(R))});M.observe(document.body,{childList:!0,subtree:!0})}),!_){z.warn(`scrollIntoView: element not found for selector "${i}" after ${g}ms timeout`);return}}else{m>0&&await new Promise(x=>setTimeout(x,m)),_=document.querySelector(i);let A=0;for(;!_&&AsetTimeout(x,S)),_=document.querySelector(i),A++;if(!_){z.warn(`scrollIntoView: element not found for selector "${i}" after ${A+1} attempts`);return}}if(v){const A=document.querySelector(v);if(!A){z.warn(`scrollIntoView: container not found for selector "${v}"`);return}const x=_.getBoundingClientRect(),L=A.getBoundingClientRect(),M=x.top-L.top+A.scrollTop,R=M+x.height;let D;switch(c){case"start":D=M;break;case"center":D=M-A.clientHeight/2+x.height/2;break;case"end":D=R-A.clientHeight;break;default:const B=x.topL.bottom;if(B)D=M;else if(q)D=R-A.clientHeight;else return;break}A.scrollTo({top:Math.max(0,D),behavior:l});return}_.scrollIntoView({behavior:l,block:c,inline:d})}),this.registerHandler("reloadExtensions",async(n,a)=>{if(typeof window>"u"){z.warn("reloadExtensions: window is not available");return}const i=window.__templateApp;if(!i){z.warn("reloadExtensions: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState()}catch(d){throw z.error("reloadExtensions: reloadExtensionState failed",d),d}else z.warn("reloadExtensions: TemplateApp.reloadExtensionState unavailable");const{moduleInfo:l,pluginInfo:c}=n.params||{};if(l)try{await this.executeAction({handler:"reloadModuleHandlers",params:n.params},a)}catch(d){z.error("reloadExtensions: reloadModuleHandlers failed",d)}if(c)try{await this.executeAction({handler:"reloadPluginHandlers",params:n.params},a)}catch(d){z.error("reloadExtensions: reloadPluginHandlers failed",d)}z.log("reloadExtensions: done")}),this.registerHandler("reloadRoutes",async(n,a)=>{if(typeof window>"u"){z.warn("reloadRoutes: window is not available");return}const i=window.__templateApp;if(!i){z.warn("reloadRoutes: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),z.log("reloadRoutes: delegated to reloadExtensionState")}catch(l){throw z.error("reloadRoutes: Failed to reload routes",l),l}else{const l=i.getRouter?.();l&&(await l.loadRoutes(),z.log("reloadRoutes: Routes reloaded (legacy fallback)"))}}),this.registerHandler("refresh",async(n,a)=>{if(typeof window>"u"){z.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,a)=>{const{componentId:i}=n.params||{};if(!i){z.warn("remount: componentId parameter is required");return}if(!this.globalStateUpdater){z.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}}),z.log(`remount: ${i} key incremented to ${f+1}`)}),this.registerHandler("reloadTranslations",async(n,a)=>{if(typeof window>"u"){z.warn("reloadTranslations: window is not available");return}const i=window.__templateApp;if(!i){z.warn("reloadTranslations: TemplateApp not initialized");return}if(typeof i.reloadExtensionState=="function")try{await i.reloadExtensionState(),z.log("reloadTranslations: delegated to reloadExtensionState")}catch(l){throw z.error("reloadTranslations: Failed to reload translations",l),l}}),this.registerHandler("reloadModuleHandlers",async(n,a)=>{if(typeof window>"u"){z.warn("reloadModuleHandlers: window is not available");return}const{moduleInfo:i,action:l}=n.params||{};if(!i){z.warn("reloadModuleHandlers: moduleInfo is required");return}const c=i.data||i;if(!c.identifier){z.warn("reloadModuleHandlers: moduleInfo with identifier is required");return}if(!l||l!=="add"&&l!=="remove"){z.warn('reloadModuleHandlers: action must be "add" or "remove"');return}const d=window.G7Config;if(!d){z.warn("reloadModuleHandlers: G7Config not available");return}const f=c.identifier;try{if(l==="add"){if(c.assets&&(d.moduleAssets=d.moduleAssets||{},d.moduleAssets[f]=c.assets,z.log(`reloadModuleHandlers: Added assets for ${f}`),c.assets.js)){const g=c.assets.js,m=`module-${f}`;if(document.getElementById(m)){z.warn(`reloadModuleHandlers: Script ${m} already loaded`);return}const b=document.createElement("script");if(b.id=m,b.src=g,b.async=!0,await new Promise((S,v)=>{b.onload=()=>{z.log(`reloadModuleHandlers: Script loaded successfully for ${f}`),S()},b.onerror=()=>{z.error(`reloadModuleHandlers: Failed to load script for ${f}`),v(new Error(`Failed to load module script: ${g}`))},document.head.appendChild(b)}),c.assets.css){const S=c.assets.css,v=`module-css-${f}`;if(!document.getElementById(v)){const _=document.createElement("link");_.id=v,_.rel="stylesheet",_.href=S,document.head.appendChild(_),z.log(`reloadModuleHandlers: CSS loaded for ${f}`)}}}}else if(l==="remove"){d.moduleAssets&&d.moduleAssets[f]&&(delete d.moduleAssets[f],z.log(`reloadModuleHandlers: Removed assets for ${f}`));const g=`module-${f}`,m=document.getElementById(g);m&&(m.remove(),z.log(`reloadModuleHandlers: Removed script for ${f}`));const b=`module-css-${f}`,S=document.getElementById(b);S&&(S.remove(),z.log(`reloadModuleHandlers: Removed CSS for ${f}`))}}catch(g){throw z.error(`reloadModuleHandlers: Failed to ${l} module assets`,g),g}}),this.registerHandler("reloadPluginHandlers",async(n,a)=>{if(typeof window>"u"){z.warn("reloadPluginHandlers: window is not available");return}const{pluginInfo:i,action:l}=n.params||{};if(!i){z.warn("reloadPluginHandlers: pluginInfo is required");return}const c=i.data||i;if(!c.identifier){z.warn("reloadPluginHandlers: pluginInfo with identifier is required");return}if(!l||l!=="add"&&l!=="remove"){z.warn('reloadPluginHandlers: action must be "add" or "remove"');return}const d=window.G7Config;if(!d){z.warn("reloadPluginHandlers: G7Config not available");return}const f=c.identifier;try{if(l==="add"){if(c.assets&&(d.pluginAssets=d.pluginAssets||{},d.pluginAssets[f]=c.assets,z.log(`reloadPluginHandlers: Added assets for ${f}`),c.assets.js)){const g=c.assets.js,m=`plugin-${f}`;if(document.getElementById(m)){z.warn(`reloadPluginHandlers: Script ${m} already loaded`);return}const b=document.createElement("script");if(b.id=m,b.src=g,b.async=!0,await new Promise((S,v)=>{b.onload=()=>{z.log(`reloadPluginHandlers: Script loaded successfully for ${f}`),S()},b.onerror=()=>{z.error(`reloadPluginHandlers: Failed to load script for ${f}`),v(new Error(`Failed to load plugin script: ${g}`))},document.head.appendChild(b)}),c.assets.css){const S=c.assets.css,v=`plugin-css-${f}`;if(!document.getElementById(v)){const _=document.createElement("link");_.id=v,_.rel="stylesheet",_.href=S,document.head.appendChild(_),z.log(`reloadPluginHandlers: CSS loaded for ${f}`)}}}}else if(l==="remove"){d.pluginAssets&&d.pluginAssets[f]&&(delete d.pluginAssets[f],z.log(`reloadPluginHandlers: Removed assets for ${f}`));const g=`plugin-${f}`,m=document.getElementById(g);m&&(m.remove(),z.log(`reloadPluginHandlers: Removed script for ${f}`));const b=`plugin-css-${f}`,S=document.getElementById(b);S&&(S.remove(),z.log(`reloadPluginHandlers: Removed CSS for ${f}`))}}catch(g){throw z.error(`reloadPluginHandlers: Failed to ${l} plugin assets`,g),g}});let e=!1;this.registerHandler("showErrorPage",async(n,a)=>{if(e){z.log("showErrorPage: Already active, skipping duplicate call");return}if(e=!0,typeof window>"u"){e=!1,z.warn("showErrorPage: window is not available");return}const i=window.__templateApp;if(!i){e=!1,z.warn("showErrorPage: TemplateApp not initialized");return}const l=i.getErrorPageHandler?.();if(!l){e=!1,z.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"),z.log("showErrorPage:",{errorCode:c,target:d,containerId:f});const g=(m,b=6e4)=>new Promise((S,v)=>{const _=document.getElementById(m);if(_){S(_);return}z.log(`showErrorPage: Waiting for container #${m}...`);let A;const x=new MutationObserver((L,M)=>{const R=document.getElementById(m);R&&(z.log(`showErrorPage: Container #${m} found`),M.disconnect(),clearTimeout(A),S(R))});x.observe(document.body,{childList:!0,subtree:!0}),A=setTimeout(()=>{x.disconnect(),v(new Error(`Container #${m} not found within ${b}ms`))},b)});try{await g(f);const m=vr(),b=m.layoutErrorHandling;m.clearLayoutConfig();try{await l.renderError(c,f)||z.warn(`showErrorPage: Failed to render error page for code ${c}`)}finally{m.setLayoutConfig(b)}}catch(m){throw z.error("showErrorPage: Error rendering error page:",m),m}finally{e=!1}}),this.registerHandler("emitEvent",async(n,a)=>{const i=n.params?.event,l=n.params?.data;if(!i){z.warn("emitEvent: event parameter is required");return}if(typeof window>"u"){z.warn("emitEvent: window is not available");return}const c=window.G7Core;if(!c?.componentEvent?.emit){z.warn("emitEvent: G7Core.componentEvent is not available");return}try{z.log(`emitEvent: Emitting "${i}"`,l);const d={...l,_context:{data:a.data,state:a.state}},f=await c.componentEvent.emit(i,d);if(!f||f.length===0?z.warn(`emitEvent: No listeners found for "${i}"`):z.log(`emitEvent: Event "${i}" completed with ${f.length} listener(s)`,f),this.globalStateUpdater){const g=(c?.state?.get()||{})._local||{},m={event:i,success:!0,data:f.length===1?f[0]:f,listeners:f.length};this.globalStateUpdater({_local:{...g,_eventResult:m}});const b=a.state&&typeof a.state=="object"&&!Array.isArray(a.state)?a.state:g;window.__g7SequenceLocalSync={...b,_eventResult:m}}}catch(d){if(z.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,a)=>{const{productId:i,field:l,value:c}=n.params||{};if(!i||!l){z.warn("updateProductField: productId and field are required");return}if(typeof window>"u"){z.warn("updateProductField: window is not available");return}const d=window.G7Core;if(!d?.state?.get||!this.globalStateUpdater){z.warn("updateProductField: G7Core.state or globalStateUpdater is not available");return}try{const f=d.state.get()||{},m=(f.products?.data?.data||[]).map(S=>S.id===i?{...S,[l]:c,_modified:!0}:S),b=new Set(f._local?.modifiedProductIds||[]);b.add(i),this.globalStateUpdater({products:{...f.products,data:{...f.products?.data,data:m}},_local:{...f._local,modifiedProductIds:Array.from(b)}}),z.log(`updateProductField: Updated product ${i}, field: ${l}, value:`,c)}catch(f){throw z.error("updateProductField: Error updating product field",f),f}}),this.registerHandler("updateOptionField",async(n,a)=>{const{productId:i,optionId:l,field:c,value:d}=n.params||{};if(!i||!l||!c){z.warn("updateOptionField: productId, optionId and field are required");return}if(typeof window>"u"){z.warn("updateOptionField: window is not available");return}const f=window.G7Core;if(!f?.state?.get||!this.globalStateUpdater){z.warn("updateOptionField: G7Core.state or globalStateUpdater is not available");return}try{const g=f.state.get()||{},b=(g.products?.data?.data||[]).map(v=>{if(v.id===i&&v.options){const _=v.options.map(A=>A.id===l?{...A,[c]:d,_modified:!0}:A);return{...v,options:_,_modified:!0}}return v}),S=new Set(g._local?.modifiedProductIds||[]);S.add(i),this.globalStateUpdater({products:{...g.products,data:{...g.products?.data,data:b}},_local:{...g._local,modifiedProductIds:Array.from(S)}}),z.log(`updateOptionField: Updated product ${i} option ${l}, field: ${c}, value:`,d)}catch(g){throw z.error("updateOptionField: Error updating option field",g),g}}),this.registerHandler("setLocale",async(n,a)=>{const i=n.target;if(!i||typeof i!="string"){z.warn("setLocale: Invalid locale:",i);return}const l=window.__templateApp;if(l&&typeof l.changeLocale=="function")try{await l.changeLocale(i),z.log("setLocale: Locale changed to",i)}catch(c){z.error("setLocale: Failed to change locale:",c),window.location.reload()}else{z.warn("setLocale: TemplateApp not found, falling back to page reload");try{localStorage.setItem("g7_locale",i)}catch{}window.location.reload()}}),this.registerHandler("suppress",async()=>{z.log("suppress: Error intentionally suppressed")}),this.registerBuiltInHandlerMetadata()}registerBuiltInHandlerMetadata(){const e=qn();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 a of n)e.trackHandlerRegistration(a.name,"built-in",a.description)}createHandler(e,n,a){z.log("createHandler called for:",e.handler,e.type);const i=window.__g7DevTools,l=Date.now(),c=a?.state?{...a.state}:null,d=`handler_${e.handler}_${l}`;return async f=>{if(z.log("Handler invoked for:",e.handler,"event:",f.type),i?.isEnabled?.()&&c){const m=window.G7Core?.state?.getLocal?.()??a?.state??{},b=Date.now()-l;for(const S of Object.keys(c)){const v=c[S],_=m[S];v!==_&&b>100&&(i.trackStaleClosureWarning?.({type:"event-handler-stale",location:`createHandler(${e.handler})`,capturedPath:`_local.${S}`,capturedValue:v,capturedAt:l,currentValue:_,actionId:d,stackTrace:new Error().stack}),z.warn(`[Stale Closure] _local.${S} changed after handler creation:`,`captured="${v}" → current="${_}" (${b}ms ago)`))}}try{f.type!=="change"&&f.preventDefault();let g={};if(f.type==="submit"&&f.target instanceof HTMLFormElement){const S=f.target;new FormData(S).forEach((_,A)=>{g[A]=_})}const m={...this.defaultContext,data:{...n,form:g,_local:a?.state||{},$event:f},event:f,...a&&{state:a.state,setState:a.setState},isolatedContext:a?.isolatedContext};if(e.confirm){let S=this.resolveValue(e.confirm,m.data);if(this.translationEngine&&this.translationContext&&S.startsWith("$t:")&&(S=this.translationEngine.resolveTranslations(S,this.translationContext,m.data)),!confirm(S))return}const b=window.__g7ActionContext;window.__g7ActionContext={...a,data:m.data};try{await this.executeAction(e,m)}finally{window.__g7ActionContext=b}}catch(g){if(z.error("Action execution failed:",g),e.onError){const m=g instanceof jt&&g.originalError?g.originalError:g,b={...this.defaultContext,data:{...n,error:m,_local:a?.state||{},$event:f},event:f,...a&&{state:a.state,setState:a.setState}},S=Array.isArray(e.onError)?e.onError:[e.onError];for(const v of S)await this.executeAction(v,b)}}}}generateActionId(e,n){const a=e.handler,i=n||"no-target",l=Date.now(),c=Math.random().toString(36).substring(2,9);return`${a}_${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 a=qn(),i=a?.isEnabled()?`action_${Date.now()}_${Math.random().toString(36).substring(2,11)}`:void 0,l=performance.now();let c;if(i&&a&&a.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),g=f===!0||f==="true"||f&&f!=="false"&&f!=="0"&&f!==!1;if(z.log("[executeAction] if condition result:",e.handler,g),!g)return i&&a&&a.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 z.error("[executeAction] if condition error:",e.handler,f),i&&a&&a.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 g=e.target?this.resolveValue(e.target,n.data):void 0;if(e.handler==="apiCall"&&n.setState){d=this.generateActionId(e,g);const b=n.state?.loadingActions||{};n.setState({loadingActions:{...b,[d]:!0}})}if(this.previewMode&&lm.has(e.handler))return z.warn(`Preview mode: "${e.handler}" suppressed`,g||f),i&&a&&a.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 b=f.path||g;m=await this.handleNavigate(b,f,n);break;case"navigateBack":m=await this.handleNavigateBack();break;case"navigateForward":m=await this.handleNavigateForward();break;case"openWindow":{const _=f.path||g;m=await this.handleOpenWindow(_,f);break}case"replaceUrl":{const _=f.path||g||window.location.pathname;m=await this.handleReplaceUrl(_,f);break}case"apiCall":if(e.onSuccess&&a?.isEnabled()&&i){const _=window.G7Core,A={};if(_?.state?.get){const x=_.state.get();A._global=x}n.state&&(A._local=n.state),a.registerStateCaptureForHandler?.(i,["_global","_local"],A)}const S=e.auth_mode??(e.auth_required?"required":"none"),v=e.identity_target?this.resolveParams(e.identity_target,n.data):void 0;m=await this.handleApiCall(g,f,n,S,v);break;case"login":m=await this.handleLogin(g,f,n);break;case"logout":m=await this.handleLogout(g,n);break;case"setState":z.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(g,f,n);break;case"openModal":m=await this.handleOpenModal(g,n);break;case"closeModal":m=await this.handleCloseModal(n);break;case"showAlert":m=await this.handleShowAlert(g,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:g,params:f},n);break}if(e.resultTo&&m!==void 0){const{target:b,key:S,merge:v}=e.resultTo,_=this.resolveValue(S,n.data),A=v==="replace"?"replace":v==="shallow"?"shallow":"deep";if(b==="_local"&&n.setState){const x=this.buildNestedUpdate(_,m),L=A!=="deep"?{...x,__mergeMode:A}:x;n.setState(L),z.log(`[resultTo] Saved to _local.${_} (merge=${A}):`,m)}else if(b==="_local"&&this.globalStateUpdater){const M=(window.G7Core?.state?.get()||{})._local||{},R=this.buildNestedUpdate(_,m);let D;A==="replace"?D=R:A==="shallow"?D={...M,...R}:D=this.deepMergeWithState(R,M),this.globalStateUpdater({_local:D}),z.log(`[resultTo] Saved to _local.${_} via globalStateUpdater (merge=${A}):`,m)}else if(b==="_global"&&this.globalStateUpdater){const x=this.buildNestedUpdate(_,m);this.globalStateUpdater(x),z.log(`[resultTo] Saved to _global.${_}:`,m)}else if(b==="_isolated"&&n.isolatedContext){const x=this.buildNestedUpdate(_,m);n.isolatedContext.mergeState(x,A),z.log(`[resultTo] Saved to _isolated.${_} (merge=${A}):`,m)}else z.warn(`[resultTo] Cannot save result: target=${b}, setState=${!!n.setState}, globalStateUpdater=${!!this.globalStateUpdater}, isolatedContext=${!!n.isolatedContext}`)}if(e.onSuccess){if(a?.isEnabled()&&i&&e.handler==="apiCall"){const v=window.G7Core,_={};v?.state?.get&&(_._global=v.state.get()),n.state&&(_._local=n.state),a.detectStaleClosure?.(i,`${e.handler} → onSuccess`,_,"callback-state-capture",i)}const b={...n,data:{...n.data,result:m,response:m}},S=Array.isArray(e.onSuccess)?e.onSuccess:[e.onSuccess];S.length>1?await this.handleSequence({handler:"sequence",type:"click",actions:S},b):S.length===1&&await this.executeAction(S[0],b)}return i&&a&&a.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 g=f instanceof jt?f:new jt(`Failed to execute action: ${e.handler}`,e,f instanceof Error?f:void 0),m=g.originalError?.response||{},b=m.data||{},S=g.originalError?.status||m.status||500;let v=lC(g.originalError??f,e.handler,b.message,g.message);this.translationEngine&&this.translationContext&&v.startsWith("$t:")&&(v=this.translationEngine.resolveTranslations(v,this.translationContext));const _={status:S,message:v,errors:b.errors||m.errors,data:b,statusText:g.originalError?.statusText,error_code:b.error_code??m.error_code};if(g.unknownHandler)throw z.warn(`Unknown action handler "${e.handler}" — skipped (extension not loaded?). Not surfaced to the user.`),g;const x=vr().resolve(S,{errorHandling:e.errorHandling,onError:e.onError});if(x.handler){if(a?.isEnabled()&&i&&e.handler==="apiCall"){const M=window.G7Core,R={};M?.state?.get&&(R._global=M.state.get()),n.state&&(R._local=n.state),a.detectStaleClosure?.(i,`${e.handler} → onError`,R,"callback-state-capture",i)}const L={...n,data:{...n.data,error:_}};try{const M={type:"click",handler:x.handler.handler,target:x.handler.target,params:x.handler.params,actions:x.handler.actions};return await this.executeAction(M,L),{success:!1,error:g}}catch(M){return z.error("Error executing error handler:",M),{success:!1,error:g}}}throw i&&a&&a.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:g.name,message:g.message,stack:g.stack}}),g}finally{if(e.handler==="apiCall"&&n.setState&&d){const f=n.state?.loadingActions||{},{[d]:g,...m}=f;n.setState({loadingActions:m})}}}async handleNavigate(e,n,a){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,g]of Object.entries(n.query))if(g!=null&&g!=="")if(Array.isArray(g)){const m=f.endsWith("[]")?f:`${f}[]`;for(const b of g)b!=null&&b!==""&&c.append(m,String(b))}else c.set(f,String(g));const d=c.toString();d&&(i=`${e}?${d}`)}if(z.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),z.log("handleNavigate: Used updateQueryParams for replace mode",d?{transitionOverlayTarget:d}:void 0),this.applyScrollOption(n.scroll,n.scrollBehavior,"top");return}z.warn("handleNavigate: G7Core.updateQueryParams not available, falling back to React Router")}const l=this.resolveNavigateFallbackAction(i,n);if(l){z.warn(`handleNavigate: No route matched, falling back to "${l.handler}"`),await this.dispatchAction({type:"click",handler:l.handler,params:l.params},a),this.applyScrollOption(n.scroll,n.scrollBehavior,"top");return}if(!a.navigate)throw new jt("Navigate function is not provided in context");a.navigate(i,{replace:n.replace===!0}),this.applyScrollOption(n.scroll,n.scrollBehavior,"top")}resolveNavigateFallbackAction(e,n){const a=n.fallback;if(a===!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(a,e,n)}resolveNavigateFallback(e,n,a){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||{}}}:(z.warn("resolveNavigateFallback: unrecognized fallback option, using openWindow",e),{handler:"openWindow",params:{path:n,target:"_blank"}})}applyScrollOption(e,n,a){const i=e===void 0?a:e;if(i==="preserve")return;const l=n==="smooth"?"smooth":"instant",c=b=>{if(typeof b!="object"||b===null)return!1;const S=b;return"container"in S||"to"in S||"block"in S||"offset"in S},d=(b,S,v=0)=>{b===window?window.scrollTo({top:S,left:v,behavior:l}):b.scrollTo({top:S,left:v,behavior:l})},f=(b,S,v,_)=>{if(S===window){b.scrollIntoView({behavior:l,block:v}),_&&window.scrollBy({top:-_,left:0,behavior:l});return}const A=S,x=b.getBoundingClientRect(),L=A.getBoundingClientRect(),M=A.scrollTop+(x.top-L.top);let R;v==="center"?R=M-(A.clientHeight-b.clientHeight)/2:v==="end"?R=M-(A.clientHeight-b.clientHeight):R=M,R-=_,A.scrollTo({top:Math.max(0,R),left:0,behavior:l})},g=()=>{window.scrollTo({top:0,left:0,behavior:l});const b=document.getElementById("app")??document.body;if(!b)return;b.querySelectorAll("*").forEach(v=>{if(v.scrollTop===0&&v.scrollLeft===0)return;const _=window.getComputedStyle(v),A=_.overflowY,x=_.overflowX;(A==="auto"||A==="scroll"||x==="auto"||x==="scroll")&&v.scrollTo({top:0,left:0,behavior:l})})},m=()=>{try{if(c(i)){const b=i,S=b.block??"start",v=typeof b.offset=="number"?b.offset:0;let _=window;if(typeof b.container=="string"&&b.container.length>0){const x=document.querySelector(b.container);if(!x){z.warn(`applyScrollOption: container not found: ${b.container}`);return}_=x}const A=b.to??"top";if(A==="top"){_===window?g():d(_,0);return}if(typeof A=="number"){d(_,A-v);return}if(typeof A=="object"&&A!==null&&("x"in A||"y"in A)){const{x=0,y:L=0}=A;d(_,L-v,x);return}if(typeof A=="string"&&(A.startsWith("#")||A.startsWith("."))){const x=document.querySelector(A);x?f(x,_,S,v):z.warn(`applyScrollOption: target element not found: ${A}`);return}z.warn('applyScrollOption: invalid "to" value in extended form',A);return}if(i==="top"){g();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:b=0,y:S=0}=i;window.scrollTo({top:S,left:b,behavior:l});return}if(typeof i=="string"&&(i.startsWith("#")||i.startsWith("."))){const b=document.querySelector(i);b&&b.scrollIntoView({behavior:l,block:"start"});return}}catch(b){z.warn("applyScrollOption: failed to apply scroll",b)}};typeof window.requestAnimationFrame=="function"?window.requestAnimationFrame(m):m()}async handleOpenWindow(e,n){let a=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&&(a=`${e}?${c}`)}const i=n.target==="_self"?"_self":"_blank";z.log("handleOpenWindow:",{target:e,params:n,finalPath:a,windowTarget:i}),i==="_self"?window.location.assign(a):window.open(a,"_blank")}async handleNavigateBack(){z.log("handleNavigateBack"),window.history.back()}async handleNavigateForward(){z.log("handleNavigateForward"),window.history.forward()}async handleReplaceUrl(e,n){let a=e;if(n.query||n.mergeQuery===!0)if(n.mergeQuery===!0)a=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 g of d)g!=null&&g!==""&&i.append(f,String(g))}else i.set(c,String(d));const l=i.toString();l&&(a=`${e}?${l}`)}z.log("handleReplaceUrl:",{target:e,params:n,finalPath:a}),window.history.replaceState(null,"",a),this.applyScrollOption(n.scroll,n.scrollBehavior,"preserve")}buildMergedQueryPath(e,n){const a=new URLSearchParams(window.location.search);for(const[c,d]of Object.entries(n))if(d==null||d==="")a.delete(c);else if(Array.isArray(d)){const f=c.endsWith("[]")?c:`${c}[]`;a.delete(c),a.delete(f);for(const g of d)g!=null&&g!==""&&a.append(f,String(g))}else a.set(c,String(d));const i=a.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 a=`; ${document.cookie}`.split("; XSRF-TOKEN=");if(a.length===2){const i=a.pop()?.split(";").shift();return i?decodeURIComponent(i):null}return null}buildQueryString(e){const n=new URLSearchParams;for(const[a,i]of Object.entries(e))if(!(i==null||i===""))if(Array.isArray(i))for(const l of i)l!=null&&l!==""&&n.append(`${a}[]`,String(l));else typeof i=="object"?n.append(a,JSON.stringify(i)):n.append(a,String(i));return n.toString()}async handleEnsureIdentityVerified(e){const n=typeof e.purpose=="string"?e.purpose:"sensitive_action",a=e.target&&typeof e.target=="object"?e.target:void 0;return await vt.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,a)!==null}handleResolveIdentityChallenge(e){const n=typeof e.result=="string"?e.result:"cancelled";let a;switch(n){case"verified":{const i=typeof e.token=="string"?e.token:"";if(!i){z.warn("resolveIdentityChallenge: result=verified 인데 token 이 비어있습니다. failed 로 강등합니다."),a={status:"failed",failureCode:"MISSING_TOKEN"};break}a={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){z.warn("resolveIdentityChallenge: result=pending 인데 pollUrl/expiresAt 누락 — failed 로 강등합니다."),a={status:"failed",failureCode:"MALFORMED_PENDING"};break}a={status:"pending",pollUrl:i,pollIntervalMs:typeof e.pollIntervalMs=="number"?e.pollIntervalMs:void 0,expiresAt:l};break}case"failed":a={status:"failed",failureCode:typeof e.failureCode=="string"?e.failureCode:"UNKNOWN",reason:typeof e.reason=="string"?e.reason:void 0};break;default:a={status:"cancelled"};break}return vt.resolveDeferred(a),!0}async handleApiCall(e,n,a,i="none",l){const{method:c="GET",body:d,headers:f,contentType:g}=n;c!=="GET"&&c!=="HEAD"&&await this.ensureCsrfToken();const m=this.getCsrfTokenFromCookie();let b={};if(i==="required"||i==="optional"){const K=Ir().getToken();K&&(b={Authorization:`Bearer ${K}`})}let S=e;const v=n.query||(c==="GET"?d:null);if(v&&typeof v=="object"){const P=this.buildQueryString(v);if(P){const K=e.includes("?")?"&":"?";S=`${e}${K}${P}`}}const _=window.G7Core?.state?.getGlobal?.()||a.state?._global||{},A=window.G7Core?.state?.getLocal?.()||a.state?._local||{},x={_global:_,_local:A},L=this.getMatchingGlobalHeaders(e,x),M={};if(typeof window<"u"){const P=localStorage.getItem("g7_locale");P&&(M["Accept-Language"]=P)}const R=g==="multipart/form-data",D={method:c,headers:{...R?{}:{"Content-Type":"application/json"},Accept:"application/json",...M,...m&&{"X-XSRF-TOKEN":m},...b,...L,...f},credentials:"include"};if(d&&c!=="GET")if(R){const P=new FormData;for(const[K,ge]of Object.entries(d))ge instanceof File||ge instanceof Blob?P.append(K,ge):ge!=null&&P.append(K,typeof ge=="object"?JSON.stringify(ge):String(ge));D.body=P}else D.body=JSON.stringify(d);const B=qn();let q=null;B?.isEnabled()&&(q=B.trackRequest(S,c));try{let P=await fetch(S,D),K;try{K=await P.json()}catch{K=null}if(vt.isIdentityRequired(P.status,K)){const ge=await vt.handle(K,{body:D.body,headers:D.headers,credentials:D.credentials},l);if(ge){P=ge;try{K=await P.json()}catch{K=null}}}if(q&&B?.isEnabled()&&(B.completeRequest(q,P.status,K),q=null),!P.ok){const ge=K||{},Ee=new Error(ge.message||`API call failed: ${P.statusText}`);throw Ee.response=ge,Ee.status=P.status,Ee.statusText=P.statusText,new jt(ge.message||`API call failed: ${P.statusText}`,void 0,Ee)}return K}catch(P){throw q&&B?.isEnabled()&&B.failRequest(q,P instanceof Error?P.message:String(P)),P}}async handleLogin(e,n,a){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?.()||a.state?._global||{},f=window.G7Core?.state?.getLocal?.()||a.state?._local||{},g={_global:d,_local:f},m=this.getMatchingGlobalHeaders(c,g),b=yr.getInstance();try{const S=Object.keys(m).length>0?{headers:m}:void 0;return{user:await b.login(l,{email:i.email,password:i.password},S)}}catch(S){const v=S.message||"Login failed",_=new Error(v);throw _.response=S.response?.data||{},_.status=S.status||S.response?.status||500,new jt(v,void 0,_)}}async handleLogout(e,n){await yr.getInstance().logout()}async handleSetState(e,n){z.log("[handleSetState] START, params:",e);const{target:a="component",scope:i,merge:l,__render:c,...d}=e,f=qn(),g=window.G7Core;if(typeof a=="string"&&(a.startsWith("$parent.")||a.startsWith("$root.")))return this.handleParentScopeSetState(a,d,l,n);const m=n.state&&Object.keys(n.state).length>0?n.state:g?.state?.get()||{},b=a==="global"?"_global":a.startsWith("_local.")?a:"_local",S=b==="_global"?m._global:b.startsWith("_local.")?this.getNestedProperty(m._local||{},b.slice(7)):m._local,v=f?.isEnabled()?f.startStateChange(b,S,d,{actionId:n.actionId,handlerType:"setState",source:`target=${a}`}):void 0,_=l==="replace"?"replace":l==="shallow"?"shallow":"deep",A=_!=="deep"?{...d,__mergeMode:_,...v?{__setStateId:v}:{}}:{...d,...v?{__setStateId:v}:{}};if(a==="global"){if(!this.globalStateUpdater){z.warn("Global state updater is not set"),v&&f&&f.completeStateChange(v);return}const x=g?.state?.get()||{},{__setStateId:L,__mergeMode:M,...R}=A,D=_==="deep"?this.deepMergeWithState(R,x):R,B={...D,...v?{__setStateId:v}:{},..._!=="deep"?{__mergeMode:_}:{}};return z.log("setState global:",B),this.globalStateUpdater(B,{render:c}),v&&f&&setTimeout(()=>f.completeStateChange(v),0),{__target:"global",..._!=="deep"?{__mergeMode:_}:{},...D}}else if(a==="isolated"){const x=n.isolatedContext;if(x){const{__mergeMode:L,__setStateId:M,...R}=A;return x.mergeState(R,_),z.log("[handleSetState] isolated state updated:",R,"mergeMode:",_),v&&f&&setTimeout(()=>f.completeStateChange(v),0),{__target:"isolated",...R}}else if(z.warn('[handleSetState] isolated target used but no IsolatedStateContext found. Make sure the component has "isolatedState" attribute. Falling back to local state.'),n.setState){const M=window.__g7PendingLocalState||n.state||{},R=_==="deep"?this.deepMergeWithState(A,M):A;return n.setState(R),v&&f&&setTimeout(()=>f.completeStateChange(v),0),R}else throw v&&f&&f.completeStateChange(v),new jt("isolated target used but no IsolatedStateContext found and no setState function in context")}else if(a==="local"||a==="component"||a==="_local"){if(i==="parent"||i==="root"){const L=window.__g7LayoutContextStack||[];if(L.length>0){const M=i==="parent"?L[L.length-1]:L[0];if(M?.setState){const{__mergeMode:R,__setStateId:D,...B}=A,q=_==="deep"?this.deepMergeWithState(B,M.state||{}):B;return z.log(`[handleSetState] scope=${i}: 타겟 컨텍스트에 상태 업데이트`,q),M.setState(q),v&&f&&setTimeout(()=>f.completeStateChange(v),0),q}}z.warn(`[handleSetState] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const x=n.setState&&!n._isDispatchFallbackContext;if(z.log("[handleSetState] isRealComponentContext:",x,"context.setState:",!!n.setState,"_isDispatchFallbackContext:",n._isDispatchFallbackContext),x){z.log("[handleSetState] Using COMPONENT setState path"),z.log("[handleSetState] resolvedPayload:",A),z.log("[handleSetState] context.state:",n.state),z.log("[handleSetState] mergeMode:",_);const M=window.__g7PendingLocalState||n.state||{},R=_==="deep"?this.deepMergeWithState(A,{}):A;z.log("[handleSetState] convertedPayload (변경 필드만, dot notation 변환):",R),n.setState(R);const D=_==="deep"?this.deepMergeWithState(A,M):_==="shallow"?{...n.state||{},...A}:A,{__mergeMode:B,__setStateId:q,...P}=D;window.__g7PendingLocalState=P,z.log("[handleSetState] __g7PendingLocalState updated:",P),this.globalStateUpdater&&(this.globalStateUpdater({_local:P},{render:!1}),z.log("[handleSetState] _global._local synced (render:false):",P));const{__mergeMode:K,__setStateId:ge,...Ee}=A;if(_==="replace")window.__g7ForcedLocalFields=Ee;else{const Se=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=this.deepMergeWithState(Ee,Se)}return z.log("[handleSetState] __g7ForcedLocalFields updated:",Ee),v&&f&&setTimeout(()=>f.completeStateChange(v),0),{__target:"local",...D}}else if(this.globalStateUpdater){z.log("[handleSetState] Using GLOBAL STATE UPDATER path for _local");const M=window.__g7PendingLocalState||m._local||{};z.log("[handleSetState] currentLocal (with pending):",M);const R=_==="deep"?this.deepMergeWithState(A,M):A;return z.log("[handleSetState] finalLocal (merged):",R),this.globalStateUpdater({_local:R},{render:c}),window.__g7PendingLocalState=R,z.log("[handleSetState] __g7PendingLocalState updated for globalStateUpdater path"),v&&f&&setTimeout(()=>f.completeStateChange(v),0),{__target:"local",...R}}else throw v&&f&&f.completeStateChange(v),new jt("setState function is not provided in context and globalStateUpdater is not set")}else if(a.startsWith("_local.")){const x=a.slice(7),{__mergeMode:L,__setStateId:M,...R}=A,D=R.value!==void 0?R.value:Object.values(R)[0];if(n.setState){const q=window.__g7PendingLocalState||n.state||{},P=this.createNestedUpdate(x,D,q),K={...q,...P};return n.setState(P),v&&f&&setTimeout(()=>f.completeStateChange(v),0),K}else throw v&&f&&f.completeStateChange(v),new jt("setState function is not provided in context")}else{if(!n.setState)throw v&&f&&f.completeStateChange(v),new jt("setState function is not provided in context");const L=window.__g7PendingLocalState||n.state||{},M=_==="deep"?this.deepMergeWithState(A,L):A;return n.setState(M),v&&f&&setTimeout(()=>f.completeStateChange(v),0),M}}async handleParentScopeSetState(e,n,a,i){const l=qn(),c=window.G7Core,d=a==="replace"?"replace":a==="shallow"?"shallow":"deep",f=e.startsWith("$parent."),g=f?"$parent.":"$root.",m=e.slice(g.length);let b,S;if(m==="_local"||m==="_global")b=m,S=void 0;else if(m.startsWith("_local."))b="_local",S=m.slice(7);else if(m.startsWith("_global."))b="_global",S=m.slice(8);else{z.warn(`[handleParentScopeSetState] 지원하지 않는 타겟 형식: ${e}. _local 또는 _global으로 시작해야 합니다.`);return}const v=window.__g7LayoutContextStack||[];if(v.length===0){z.warn(`[handleParentScopeSetState] 레이아웃 컨텍스트 스택이 비어있습니다. target=${e}`);return}const _=f?v[v.length-1]:v[0];if(!_){z.warn(`[handleParentScopeSetState] 타겟 컨텍스트를 찾을 수 없습니다. target=${e}`);return}const A=b==="_global"?_.state?._global:_.state?._local,x=l?.isEnabled()?l.startStateChange(e,A,n,{actionId:i.actionId,handlerType:"setState",source:`target=${e}`}):void 0,{__mergeMode:L,__setStateId:M,...R}=n;if(b==="_global"){if(!this.globalStateUpdater){z.warn("[handleParentScopeSetState] globalStateUpdater가 설정되지 않았습니다."),x&&l&&l.completeStateChange(x);return}const D=c?.state?.get()||{};if(S){const B=R.value!==void 0?R.value:Object.values(R)[0],q=this.createNestedUpdate(S,B,D),P={...D,...q};z.log(`[handleParentScopeSetState] ${e}: 전역 상태 중첩 경로 업데이트`,P),this.globalStateUpdater(P)}else{const B=d==="deep"?this.deepMergeWithState(R,D):R;z.log(`[handleParentScopeSetState] ${e}: 전역 상태 업데이트 (mergeMode=${d})`,B),this.globalStateUpdater(d!=="deep"?{...B,__mergeMode:d}:B)}return x&&l&&setTimeout(()=>l.completeStateChange(x),0),{__target:e,...R}}else{if(!_.setState){z.warn(`[handleParentScopeSetState] 타겟 컨텍스트에 setState가 없습니다. target=${e}`),x&&l&&l.completeStateChange(x);return}const D=_.state||{};if(S){const B=R.value!==void 0?R.value:Object.values(R)[0],q=this.createNestedUpdate(S,B,D),P={...D,...q};return z.log(`[handleParentScopeSetState] ${e}: 로컬 상태 중첩 경로 업데이트`,q),_.setState(q),_.state=P,_.dataContext&&(_.dataContext._local=P),Ud(),x&&l&&setTimeout(()=>l.completeStateChange(x),0),P}else{const B=d!=="deep"?{...R,__mergeMode:d}:R,q=d==="replace"?R:d==="shallow"?{...D,...R}:this.deepMergeWithState(R,D);return z.log(`[handleParentScopeSetState] ${e}: 로컬 상태 업데이트 (mergeMode=${d})`,q),_.setState(B),_.state=q,_.dataContext&&(_.dataContext._local=q),Ud(),x&&l&&setTimeout(()=>l.completeStateChange(x),0),q}}}deepMergeWithState(e,n){const a=["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(a.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,a){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]===a[i]&&(e[i]={...e[i]}),this.deepMergeInto(e[i],l,a[i]||{})):typeof l=="object"&&!Array.isArray(l)&&e[i]===void 0&&a[i]!==null&&typeof a[i]=="object"&&!Array.isArray(a[i])?e[i]={...a[i],...l}:e[i]=l}}createNestedUpdate(e,n,a){const i=e.split(".");if(i.length===1)return{[i[0]]:n};const l={};let c=l,d=a;for(let f=0;f{this.globalStateUpdater({_local:v})};m.push({state:b,setState:S,dataContext:{_local:b||n.data?._local,_global:l?n.data?._global:n.data?._global||i?.state?.get?.(),_computed:n.data?._computed}}),window.__g7LayoutContextStack=m,z.log(`[handleOpenModal] 레이아웃 컨텍스트 스택에 push, 스택 크기: ${m.length}, state:`,b,l?"(direct)":"(fallback via G7Core)")}else z.warn(`[handleOpenModal] 컨텍스트 스택에 push 실패 - setState: ${!!n.setState}, state: ${n.state!==void 0}, G7Core: ${!!i?.state?.getLocal}`);const f=[...a,e];this.globalStateUpdater({modalStack:f,activeModal:e});const g=qn();if(g?.isEnabled()){const m=a.length>0?a[a.length-1]:void 0;g.trackModalOpen?.({modalId:e,modalName:e,scopeType:"isolated",parentModalId:m,initialState:n.state?{...n.state}:{}})}}async handleCloseModal(e){if(!this.globalStateUpdater){z.warn("Global state updater is not set for closeModal");return}const n=e?.data?._global?.modalStack||[],a=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,z.log(`[handleCloseModal] 레이아웃 컨텍스트 스택에서 pop, 스택 크기: ${c.length}`)}if(a){const d=qn();d?.isEnabled()&&d.trackModalClose?.(a,e?.state)}this.globalStateUpdater({modalStack:i,activeModal:l})}async handleShowAlert(e,n){let a=e;this.translationEngine&&this.translationContext&&e.startsWith("$t:")&&(a=this.translationEngine.resolveTranslations(e,this.translationContext,n.data)),alert(a)}async handleToast(e,n){const{type:a="info",message:i,icon:l,duration:c}=e;if(a==="error"){const f=n.data?.error;if((f?.error_code==="identity_verification_required"||f?.data?.error_code==="identity_verification_required")&&vt.consumeDomainNoticeShown()){z.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 g={id:`toast_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,type:a,message:d,...l&&{icon:l},...c&&{duration:c}},v=[...window.G7Core?.state?.get()?.toasts||[],g];this.globalStateUpdater({toasts:v})}else z.log(`[Toast ${a}] ${d}`)}async handleSwitch(e,n){const{cases:a}=e;if(!a){z.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,z.log("switch handler: using params.value as case key:",l)):(l=n.data?.$args?.[0],z.log("switch handler: using $args[0] as case key:",l)),l==null){if(a.default)return z.log("switch handler: case key is undefined, using default case"),await this.executeAction(a.default,n);z.warn("switch handler: case key is not defined and no default case");return}const c=String(l);let d=a[c];if(!d&&a.default&&(z.log(`switch handler: no case found for key "${c}", using default case`),d=a.default),!d){z.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:a}=e;if(!a||!Array.isArray(a)){z.warn("conditions handler requires conditions array");return}const i=n.data||{},l=yp(a,i,this.bindingEngine);if(!l.matched){z.log("conditions handler: no matching branch found");return}const c=a[l.branchIndex];if(z.log(`conditions handler: matched branch ${l.branchIndex}`),!c.then){z.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 a=typeof e.id=="string"?e.id:"",i=Number(e.intervalMs??1e3),l=Array.isArray(e.actions)?e.actions:[];if(a===""||!l.length||i<=0)return z.warn("startInterval requires non-empty id, positive intervalMs, and actions array"),{success:!1};const c=this.intervals.get(a);c&&(clearInterval(c),this.intervals.delete(a));const d=setInterval(()=>{for(const f of l)this.executeAction(f,n).catch(g=>{z.error(`[startInterval:${a}] tick action failed`,g)})},i);return this.intervals.set(a,d),{success:!0,id:a}}handleStopInterval(e){const n=typeof e.id=="string"?e.id:"";if(n==="")return z.warn("stopInterval requires id parameter"),{success:!1};const a=this.intervals.get(n);return a&&(clearInterval(a),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 a=e.actions||e.params?.actions;if(!a||!Array.isArray(a)||a.length===0)return z.warn("sequence handler requires non-empty actions array"),[];const i=qn(),l=i?.isEnabled()&&i.startSequenceExecution?.({eventType:e.type})||"";window.__g7SequenceLocalSync=void 0;const c=[];let d,f=n.state?{...n.state}:{},g=n.isolatedContext?.state?{...n.isolatedContext.state}:{},m=n.data?._computed||{};const b=window.G7Core,S=()=>({_global:b?.state?.get()||{},_local:{...f},_isolated:Object.keys(g).length>0?{...g}:void 0});for(let v=0;v0){const R={},D={...n.data,_local:f,_computed:R,$computed:R,_isolated:g};for(const[B,q]of Object.entries(M))if(typeof q=="string"){const P=q.trim();if(P.startsWith("{{")&&P.endsWith("}}"))try{const K=P.slice(2,-2).trim();R[B]=Pn(K)?this.bindingEngine.evaluatePipeExpression(K,D,{skipCache:!0}):this.bindingEngine.evaluateExpression(K,D,{skipCache:!0})}catch{R[B]=m[B]}}m=R,z.log("[handleSequence] _computed recalculated after setState:",m)}}if(_.handler!=="setState"){const M=window.__g7SequenceLocalSync;if(M&&M!==f){f=M,window.__g7SequenceLocalSync=void 0,z.log("[handleSequence] currentState synchronized from __g7SequenceLocalSync after custom handler:",_.handler);const R=n.data?._computedDefinitions;if(R&&Object.keys(R).length>0){const D={},B={...n.data,_local:f,_computed:D,$computed:D,_isolated:g};for(const[q,P]of Object.entries(R))if(typeof P=="string"){const K=P.trim();if(K.startsWith("{{")&&K.endsWith("}}"))try{const ge=K.slice(2,-2).trim();D[q]=Pn(ge)?this.bindingEngine.evaluatePipeExpression(ge,B,{skipCache:!0}):this.bindingEngine.evaluateExpression(ge,B,{skipCache:!0})}catch{D[q]=m[q]}}m=D,z.log("[handleSequence] _computed recalculated after custom handler:",m)}}}l&&i?.isEnabled()&&i.captureSequenceActionAfter?.(l,v,S(),Date.now()-A,L.data)}catch(L){throw l&&i?.isEnabled()&&(i.captureSequenceActionAfter?.(l,v,S(),Date.now()-A,void 0,L),i.endSequenceExecution?.(l,L)),z.error(`sequence handler: action[${v}] failed:`,L),L}}return window.__g7SequenceLocalSync=void 0,l&&i?.isEnabled()&&i.endSequenceExecution?.(l),c}async handleParallel(e,n){const a=e.actions||e.params?.actions;if(!a||!Array.isArray(a)||a.length===0)return z.warn("parallel handler requires non-empty actions array"),[];z.log(`parallel handler: executing ${a.length} actions in parallel`);const i=n.isolatedContext?{...n.isolatedContext,state:{...n.isolatedContext.state}}:null,l=a.map((f,g)=>{const m={...n,isolatedContext:i};return this.executeAction(f,m).catch(b=>{throw z.error(`parallel handler: action[${g}] failed:`,b),b})}),c=await Promise.allSettled(l),d=c.filter(f=>f.status==="rejected").length;return d>0&&z.warn(`parallel handler: ${d}/${a.length} actions failed`),c}async handleLoadScript(e,n,a){const{src:i,id:l,async:c=!0,defer:d=!1}=e;if(!i)throw new jt('loadScript handler requires "src" parameter',n);const f=l||`script_${i.replace(/[^a-zA-Z0-9]/g,"_")}`;return ps.loadedScripts.has(f)?(z.log(`loadScript: script already loaded, skipping: ${f}`),n.onLoad&&await this.executeAction(n.onLoad,a),!0):document.getElementById(f)?(z.log(`loadScript: script element already exists: ${f}`),ps.loadedScripts.add(f),n.onLoad&&await this.executeAction(n.onLoad,a),!0):(z.log(`loadScript: loading script: ${i}`),new Promise((m,b)=>{const S=document.createElement("script");S.id=f,S.src=i,S.async=c,S.defer=d,S.onload=async()=>{if(z.log(`loadScript: script loaded successfully: ${f}`),ps.loadedScripts.add(f),n.onLoad)try{await this.executeAction(n.onLoad,a)}catch(v){z.error("loadScript: onLoad action failed:",v)}m(!0)},S.onerror=v=>{z.error(`loadScript: failed to load script: ${i}`,v),b(new jt(`Failed to load script: ${i}`,n))},document.head.appendChild(S)}))}async handleCallExternal(e,n,a){const i=e.constructor,l=e.args||{},c=e.method,d=e.methodArgs||[],f=e.callbackEvent,g=e.embedTarget,m=e.callbackSetState,b=e.callbackAction;if(!i)throw new jt('callExternal handler requires "constructor" parameter',n);const S=this.getNestedProperty(window,i);if(!S||typeof S!="function")throw new jt(`Constructor not found or not a function: ${i}. Make sure the script is loaded first using loadScript handler.`,n);z.log(`callExternal: calling constructor ${i}`);const v={...l};for(const[A,x]of Object.entries(l))x===!0&&(v[A]=L=>{if(z.log(`callExternal: callback triggered for ${A}`,L),f&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(f,L),m&&a.setState){const M=B=>{const q={};for(const[P,K]of Object.entries(B))typeof K=="string"?q[P]=this.getNestedProperty(L,K):typeof K=="object"&&K!==null&&(q[P]=M(K));return q},R=M(m);z.log("callExternal: callbackSetState mapping result",R);const D=this.deepMergeWithState(R,a.state||{});z.log("callExternal: merged with existing state",D),a.setState(D)}else f&&a.setState&&a.setState({[`${f.replace(/:/g,"_")}_result`]:L});if(b){const M={...a,data:{...a.data,$event:L}},R=Array.isArray(b)?b:[b];for(const D of R)try{this.executeAction(D,M)}catch(B){z.error("callExternal: callbackAction failed:",B)}}});const _=new S(v);if(c&&typeof _[c]=="function"){if(z.log(`callExternal: calling method ${c}`),c==="embed"&&g){const A=document.querySelector(g);if(A)return _[c](A,...d);throw new jt(`Embed target element not found: ${g}`,n)}return _[c](...d)}return _}async handleCallExternalEmbed(e,n,a){const i=e.constructor,l=e.args||{},c=e.callbackSetState,d=e.callbackEvent,f=e.layerClassName,g=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);z.log(`callExternalEmbed: creating layer for ${i}`);const{layer:b,closeLayer:S}=this.createEmbedLayer(f),v={...l};for(const[A,x]of Object.entries(l))x===!0&&(v[A]=L=>{if(z.log(`callExternalEmbed: callback triggered for ${A}`,L),S(),d&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(d,L),c&&a.setState){const M=B=>{const q={};for(const[P,K]of Object.entries(B))typeof K=="string"?q[P]=this.getNestedProperty(L,K):typeof K=="object"&&K!==null&&(q[P]=M(K));return q},R=M(c);z.log("callExternalEmbed: callbackSetState mapping result",R);const D=this.deepMergeWithState(R,a.state||{});z.log("callExternalEmbed: merged with existing state",D),a.setState(D)}if(g){const M={...a,data:{...a.data,$event:L}},R=Array.isArray(g)?g:[g];for(const D of R)try{this.executeAction(D,M)}catch(B){z.error("callExternalEmbed: callbackAction failed:",B)}}});const _=new m(v);if(typeof _.embed=="function")_.embed(b),z.log("callExternalEmbed: embedded in layer");else throw S(),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 wn=Object.prototype.hasOwnProperty,cn=o.unstable_scheduleCallback,fn=o.unstable_cancelCallback,sr=o.unstable_shouldYield,Wn=o.unstable_requestPaint,Ut=o.unstable_now,bt=o.unstable_getCurrentPriorityLevel,ra=o.unstable_ImmediatePriority,Ln=o.unstable_UserBlockingPriority,An=o.unstable_NormalPriority,xn=o.unstable_LowPriority,Mn=o.unstable_IdlePriority,hn=o.log,aa=o.unstable_setDisableYieldValue,$n=null,Vt=null;function Cn(t){if(typeof hn=="function"&&aa(t),Vt&&typeof Vt.setStrictMode=="function")try{Vt.setStrictMode($n,t)}catch{}}var nn=Math.clz32?Math.clz32:ce,V=Math.log,oe=Math.LN2;function ce(t){return t>>>=0,t===0?32:31-(V(t)/oe|0)|0}var X=256,ve=262144,ue=4194304;function we(t){var n=t&42;if(n!==0)return n;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,n,s){var u=t.pendingLanes;if(u===0)return 0;var h=0,p=t.suspendedLanes,C=t.pingedLanes;t=t.warmLanes;var k=u&134217727;return k!==0?(u=k&~p,u!==0?h=we(u):(C&=k,C!==0?h=we(C):s||(s=k&~t,s!==0&&(h=we(s))))):(k=u&~p,k!==0?h=we(k):C!==0?h=we(C):s||(s=u&~t,s!==0&&(h=we(s)))),h===0?0:n!==0&&n!==h&&(n&p)===0&&(p=h&-h,s=n&-n,p>=s||p===32&&(s&4194048)!==0)?n:h}function Be(t,n){return(t.pendingLanes&~(t.suspendedLanes&~t.pingedLanes)&n)===0}function xe(t,n){switch(t){case 1:case 2:case 4:case 8:case 64:return n+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 n+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 n=[],s=0;31>s;s++)n.push(t);return n}function et(t,n){t.pendingLanes|=n,n!==268435456&&(t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0)}function Ne(t,n,s,u,h,p){var C=t.pendingLanes;t.pendingLanes=s,t.suspendedLanes=0,t.pingedLanes=0,t.warmLanes=0,t.expiredLanes&=s,t.entangledLanes&=s,t.errorRecoveryDisabledLanes&=s,t.shellSuspendCounter=0;var k=t.entanglements,z=t.expirationTimes,Y=t.hiddenUpdates;for(s=C&~s;0"u")return null;try{return t.activeElement||t.body}catch{return t.body}}var Ai=/[\n"\\]/g;function jn(t){return t.replace(Ai,function(n){return"\\"+n.charCodeAt(0).toString(16)+" "})}function la(t,n,s,u,h,p,C,k){t.name="",C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"?t.type=C:t.removeAttribute("type"),n!=null?C==="number"?(n===0&&t.value===""||t.value!=n)&&(t.value=""+Hn(n)):t.value!==""+Hn(n)&&(t.value=""+Hn(n)):C!=="submit"&&C!=="reset"||t.removeAttribute("value"),n!=null?Bo(t,C,Hn(n)):s!=null?Bo(t,C,Hn(s)):u!=null&&t.removeAttribute("value"),h==null&&p!=null&&(t.defaultChecked=!!p),h!=null&&(t.checked=h&&typeof h!="function"&&typeof h!="symbol"),k!=null&&typeof k!="function"&&typeof k!="symbol"&&typeof k!="boolean"?t.name=""+Hn(k):t.removeAttribute("name")}function Nc(t,n,s,u,h,p,C,k){if(p!=null&&typeof p!="function"&&typeof p!="symbol"&&typeof p!="boolean"&&(t.type=p),n!=null||s!=null){if(!(p!=="submit"&&p!=="reset"||n!=null)){zo(t);return}s=s!=null?""+Hn(s):"",n=n!=null?""+Hn(n):s,k||n===t.value||(t.value=n),t.defaultValue=n}u=u??h,u=typeof u!="function"&&typeof u!="symbol"&&!!u,t.checked=k?t.checked:!!u,t.defaultChecked=!!u,C!=null&&typeof C!="function"&&typeof C!="symbol"&&typeof C!="boolean"&&(t.name=C),zo(t)}function Bo(t,n,s){n==="number"&&oa(t.ownerDocument)===t||t.defaultValue===""+s||(t.defaultValue=""+s)}function za(t,n,s,u){if(t=t.options,n){n={};for(var h=0;h"u"||typeof window.document>"u"||typeof window.document.createElement>"u"),Vo=!1;if(Dr)try{var Ti={};Object.defineProperty(Ti,"passive",{get:function(){Vo=!0}}),window.addEventListener("test",Ti,Ti),window.removeEventListener("test",Ti,Ti)}catch{Vo=!1}var Or=null,Fo=null,Ss=null;function Ve(){if(Ss)return Ss;var t,n=Fo,s=n.length,u,h="value"in Or?Or.value:Or.textContent,p=h.length;for(t=0;t=lt),Gc=" ",Qo=!1;function Vc(t,n){switch(t){case"keyup":return Fe.indexOf(n.keyCode)!==-1;case"keydown":return n.keyCode!==229;case"keypress":case"mousedown":case"focusout":return!0;default:return!1}}function Zo(t){return t=t.detail,typeof t=="object"&&"data"in t?t.data:null}var Ga=!1;function Fc(t,n){switch(t){case"compositionend":return Zo(n);case"keypress":return n.which!==32?null:(Qo=!0,Gc);case"textInput":return t=n.data,t===Gc&&Qo?null:t;default:return null}}function zf(t,n){if(Ga)return t==="compositionend"||!at&&Vc(t,n)?(t=Ve(),Ss=Fo=Or=null,Ga=!1,t):null;switch(t){case"paste":return null;case"keypress":if(!(n.ctrlKey||n.altKey||n.metaKey)||n.ctrlKey&&n.altKey){if(n.char&&1=n)return{node:s,offset:n-t};t=u}e:{for(;s;){if(s.nextSibling){s=s.nextSibling;break e}s=s.parentNode}s=void 0}s=wy(s)}}function Ey(t,n){return t&&n?t===n?!0:t&&t.nodeType===3?!1:n&&n.nodeType===3?Ey(t,n.parentNode):"contains"in t?t.contains(n):t.compareDocumentPosition?!!(t.compareDocumentPosition(n)&16):!1:!1}function _y(t){t=t!=null&&t.ownerDocument!=null&&t.ownerDocument.defaultView!=null?t.ownerDocument.defaultView:window;for(var n=oa(t.document);n instanceof t.HTMLIFrameElement;){try{var s=typeof n.contentWindow.location.href=="string"}catch{s=!1}if(s)t=n.contentWindow;else break;n=oa(t.document)}return n}function Bf(t){var n=t&&t.nodeName&&t.nodeName.toLowerCase();return n&&(n==="input"&&(t.type==="text"||t.type==="search"||t.type==="tel"||t.type==="url"||t.type==="password")||n==="textarea"||t.contentEditable==="true")}var CA=Dr&&"documentMode"in document&&11>=document.documentMode,_s=null,Pf=null,ol=null,qf=!1;function Ay(t,n,s){var u=s.window===s?s.document:s.nodeType===9?s:s.ownerDocument;qf||_s==null||_s!==oa(u)||(u=_s,"selectionStart"in u&&Bf(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}),ol&&sl(ol,u)||(ol=u,u=Iu(Pf,"onSelect"),0>=C,h-=C,Kr=1<<32-nn(n)+h|s<Je?(st=Le,Le=null):st=Le.sibling;var ht=Q(F,Le,W[Je],se);if(ht===null){Le===null&&(Le=st);break}t&&Le&&ht.alternate===null&&n(F,Le),P=p(ht,P,Je),ft===null?Ie=ht:ft.sibling=ht,ft=ht,Le=st}if(Je===W.length)return s(F,Le),ct&&fa(F,Je),Ie;if(Le===null){for(;JeJe?(st=Le,Le=null):st=Le.sibling;var hi=Q(F,Le,ht.value,se);if(hi===null){Le===null&&(Le=st);break}t&&Le&&hi.alternate===null&&n(F,Le),P=p(hi,P,Je),ft===null?Ie=hi:ft.sibling=hi,ft=hi,Le=st}if(ht.done)return s(F,Le),ct&&fa(F,Je),Ie;if(Le===null){for(;!ht.done;Je++,ht=W.next())ht=le(F,ht.value,se),ht!==null&&(P=p(ht,P,Je),ft===null?Ie=ht:ft.sibling=ht,ft=ht);return ct&&fa(F,Je),Ie}for(Le=u(Le);!ht.done;Je++,ht=W.next())ht=te(Le,F,Je,ht.value,se),ht!==null&&(t&&ht.alternate!==null&&Le.delete(ht.key===null?Je:ht.key),P=p(ht,P,Je),ft===null?Ie=ht:ft.sibling=ht,ft=ht);return t&&Le.forEach(function(Px){return n(F,Px)}),ct&&fa(F,Je),Ie}function _t(F,P,W,se){if(typeof W=="object"&&W!==null&&W.type===A&&W.key===null&&(W=W.props.children),typeof W=="object"&&W!==null){switch(W.$$typeof){case S:e:{for(var Ie=W.key;P!==null;){if(P.key===Ie){if(Ie=W.type,Ie===A){if(P.tag===7){s(F,P.sibling),se=h(P,W.props.children),se.return=F,F=se;break e}}else if(P.elementType===Ie||typeof Ie=="object"&&Ie!==null&&Ie.$$typeof===K&&zi(Ie)===P.type){s(F,P.sibling),se=h(P,W.props),hl(se,W),se.return=F,F=se;break e}s(F,P);break}else n(F,P);P=P.sibling}W.type===A?(se=$i(W.props.children,F.mode,se,W.key),se.return=F,F=se):(se=Zc(W.type,W.key,W.props,null,F.mode,se),hl(se,W),se.return=F,F=se)}return C(F);case v:e:{for(Ie=W.key;P!==null;){if(P.key===Ie)if(P.tag===4&&P.stateNode.containerInfo===W.containerInfo&&P.stateNode.implementation===W.implementation){s(F,P.sibling),se=h(P,W.children||[]),se.return=F,F=se;break e}else{s(F,P);break}else n(F,P);P=P.sibling}se=Xf(W,F.mode,se),se.return=F,F=se}return C(F);case K:return W=zi(W),_t(F,P,W,se)}if(wt(W))return Te(F,P,W,se);if(Ue(W)){if(Ie=Ue(W),typeof Ie!="function")throw Error(a(150));return W=Ie.call(W),He(F,P,W,se)}if(typeof W.then=="function")return _t(F,P,su(W),se);if(W.$$typeof===O)return _t(F,P,nu(F,W),se);ou(F,W)}return typeof W=="string"&&W!==""||typeof W=="number"||typeof W=="bigint"?(W=""+W,P!==null&&P.tag===6?(s(F,P.sibling),se=h(P,W),se.return=F,F=se):(s(F,P),se=Yf(W,F.mode,se),se.return=F,F=se),C(F)):s(F,P)}return function(F,P,W,se){try{fl=0;var Ie=_t(F,P,W,se);return Ns=null,Ie}catch(Le){if(Le===$s||Le===au)throw Le;var ft=Xn(29,Le,null,F.mode);return ft.lanes=se,ft.return=F,ft}finally{}}}var Bi=Wy(!0),Yy=Wy(!1),Xa=!1;function lh(t){t.updateQueue={baseState:t.memoizedState,firstBaseUpdate:null,lastBaseUpdate:null,shared:{pending:null,lanes:0,hiddenCallbacks:null},callbacks:null}}function ch(t,n){t=t.updateQueue,n.updateQueue===t&&(n.updateQueue={baseState:t.baseState,firstBaseUpdate:t.firstBaseUpdate,lastBaseUpdate:t.lastBaseUpdate,shared:t.shared,callbacks:null})}function Ja(t){return{lane:t,tag:0,payload:null,callback:null,next:null}}function Qa(t,n,s){var u=t.updateQueue;if(u===null)return null;if(u=u.shared,(pt&2)!==0){var h=u.pending;return h===null?n.next=n:(n.next=h.next,h.next=n),u.pending=n,n=Qc(t),Ly(t,null,s),n}return Jc(t,u,n,s),Qc(t)}function gl(t,n,s){if(n=n.updateQueue,n!==null&&(n=n.shared,(s&4194048)!==0)){var u=n.lanes;u&=t.pendingLanes,s|=u,n.lanes=s,Se(t,s)}}function uh(t,n){var s=t.updateQueue,u=t.alternate;if(u!==null&&(u=u.updateQueue,s===u)){var h=null,p=null;if(s=s.firstBaseUpdate,s!==null){do{var C={lane:s.lane,tag:s.tag,payload:s.payload,callback:null,next:null};p===null?h=p=C:p=p.next=C,s=s.next}while(s!==null);p===null?h=p=n:p=p.next=n}else h=p=n;s={baseState:u.baseState,firstBaseUpdate:h,lastBaseUpdate:p,shared:u.shared,callbacks:u.callbacks},t.updateQueue=s;return}t=s.lastBaseUpdate,t===null?s.firstBaseUpdate=n:t.next=n,s.lastBaseUpdate=n}var dh=!1;function pl(){if(dh){var t=Ms;if(t!==null)throw t}}function ml(t,n,s,u){dh=!1;var h=t.updateQueue;Xa=!1;var p=h.firstBaseUpdate,C=h.lastBaseUpdate,k=h.shared.pending;if(k!==null){h.shared.pending=null;var z=k,Y=z.next;z.next=null,C===null?p=Y:C.next=Y,C=z;var ne=t.alternate;ne!==null&&(ne=ne.updateQueue,k=ne.lastBaseUpdate,k!==C&&(k===null?ne.firstBaseUpdate=Y:k.next=Y,ne.lastBaseUpdate=z))}if(p!==null){var le=h.baseState;C=0,ne=Y=z=null,k=p;do{var Q=k.lane&-536870913,te=Q!==k.lane;if(te?(it&Q)===Q:(u&Q)===Q){Q!==0&&Q===Ls&&(dh=!0),ne!==null&&(ne=ne.next={lane:0,tag:k.tag,payload:k.payload,callback:null,next:null});e:{var Te=t,He=k;Q=n;var _t=s;switch(He.tag){case 1:if(Te=He.payload,typeof Te=="function"){le=Te.call(_t,le,Q);break e}le=Te;break e;case 3:Te.flags=Te.flags&-65537|128;case 0:if(Te=He.payload,Q=typeof Te=="function"?Te.call(_t,le,Q):Te,Q==null)break e;le=y({},le,Q);break e;case 2:Xa=!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,z=le):ne=ne.next=te,C|=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&&(z=le),h.baseState=z,h.firstBaseUpdate=Y,h.lastBaseUpdate=ne,p===null&&(h.shared.lanes=0),ri|=C,t.lanes=C,t.memoizedState=le}}function Xy(t,n){if(typeof t!="function")throw Error(a(191,t));t.call(n)}function Jy(t,n){var s=t.callbacks;if(s!==null)for(t.callbacks=null,t=0;tp?p:8;var C=J.T,k={};J.T=k,Dh(t,!1,n,s);try{var z=h(),Y=J.S;if(Y!==null&&Y(k,z),z!==null&&typeof z=="object"&&typeof z.then=="function"){var ne=OA(z,u);vl(t,n,ne,tr(t))}else vl(t,n,u,tr(t))}catch(le){vl(t,n,{then:function(){},status:"rejected",reason:le},tr())}finally{he.p=p,C!==null&&k.types!==null&&(C.types=k.types),J.T=C}}function HA(){}function kh(t,n,s,u){if(t.tag!==5)throw Error(a(476));var h=Rb(t).queue;kb(t,h,n,Ee,s===null?HA:function(){return Db(t),s(u)})}function Rb(t){var n=t.memoizedState;if(n!==null)return n;n={memoizedState:Ee,baseState:Ee,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ma,lastRenderedState:Ee},next:null};var s={};return n.next={memoizedState:s,baseState:s,baseQueue:null,queue:{pending:null,lanes:0,dispatch:null,lastRenderedReducer:ma,lastRenderedState:s},next:null},t.memoizedState=n,t=t.alternate,t!==null&&(t.memoizedState=n),n}function Db(t){var n=Rb(t);n.next===null&&(n=t.alternate.memoizedState),vl(t,n.next.queue,{},tr())}function Rh(){return mn(Il)}function Ob(){return Kt().memoizedState}function Lb(){return Kt().memoizedState}function jA(t){for(var n=t.return;n!==null;){switch(n.tag){case 24:case 3:var s=tr();t=Ja(s);var u=Qa(n,t,s);u!==null&&(qn(u,n,s),gl(u,n,s)),n={cache:ah()},t.payload=n;return}n=n.return}}function zA(t,n,s){var u=tr();s={lane:u,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null},yu(t)?$b(n,s):(s=Kf(t,n,s,u),s!==null&&(qn(s,t,u),Nb(s,n,u)))}function Mb(t,n,s){var u=tr();vl(t,n,s,u)}function vl(t,n,s,u){var h={lane:u,revertLane:0,gesture:null,action:s,hasEagerState:!1,eagerState:null,next:null};if(yu(t))$b(n,h);else{var p=t.alternate;if(t.lanes===0&&(p===null||p.lanes===0)&&(p=n.lastRenderedReducer,p!==null))try{var C=n.lastRenderedState,k=p(C,s);if(h.hasEagerState=!0,h.eagerState=k,Yn(k,C))return Jc(t,n,h,0),xt===null&&Xc(),!1}catch{}finally{}if(s=Kf(t,n,h,u),s!==null)return qn(s,t,u),Nb(s,n,u),!0}return!1}function Dh(t,n,s,u){if(u={lane:2,revertLane:lg(),gesture:null,action:u,hasEagerState:!1,eagerState:null,next:null},yu(t)){if(n)throw Error(a(479))}else n=Kf(t,s,u,2),n!==null&&qn(n,t,2)}function yu(t){var n=t.alternate;return t===Xe||n!==null&&n===Xe}function $b(t,n){Hs=uu=!0;var s=t.pending;s===null?n.next=n:(n.next=s.next,s.next=n),t.pending=n}function Nb(t,n,s){if((s&4194048)!==0){var u=n.lanes;u&=t.pendingLanes,s|=u,n.lanes=s,Se(t,s)}}var Sl={readContext:mn,use:hu,useCallback:Pt,useContext:Pt,useEffect:Pt,useImperativeHandle:Pt,useLayoutEffect:Pt,useInsertionEffect:Pt,useMemo:Pt,useReducer:Pt,useRef:Pt,useState:Pt,useDebugValue:Pt,useDeferredValue:Pt,useTransition:Pt,useSyncExternalStore:Pt,useId:Pt,useHostTransitionStatus:Pt,useFormState:Pt,useActionState:Pt,useOptimistic:Pt,useMemoCache:Pt,useCacheRefresh:Pt};Sl.useEffectEvent=Pt;var Ib={readContext:mn,use:hu,useCallback:function(t,n){return Tn().memoizedState=[t,n===void 0?null:n],t},useContext:mn,useEffect:vb,useImperativeHandle:function(t,n,s){s=s!=null?s.concat([t]):null,pu(4194308,4,Eb.bind(null,n,t),s)},useLayoutEffect:function(t,n){return pu(4194308,4,t,n)},useInsertionEffect:function(t,n){pu(4,2,t,n)},useMemo:function(t,n){var s=Tn();n=n===void 0?null:n;var u=t();if(Pi){Cn(!0);try{t()}finally{Cn(!1)}}return s.memoizedState=[u,n],u},useReducer:function(t,n,s){var u=Tn();if(s!==void 0){var h=s(n);if(Pi){Cn(!0);try{s(n)}finally{Cn(!1)}}}else h=n;return u.memoizedState=u.baseState=h,t={pending:null,lanes:0,dispatch:null,lastRenderedReducer:t,lastRenderedState:h},u.queue=t,t=t.dispatch=zA.bind(null,Xe,t),[u.memoizedState,t]},useRef:function(t){var n=Tn();return t={current:t},n.memoizedState=t},useState:function(t){t=Eh(t);var n=t.queue,s=Mb.bind(null,Xe,n);return n.dispatch=s,[t.memoizedState,s]},useDebugValue:xh,useDeferredValue:function(t,n){var s=Tn();return Th(s,t,n)},useTransition:function(){var t=Eh(!1);return t=kb.bind(null,Xe,t.queue,!0,!1),Tn().memoizedState=t,[!1,t]},useSyncExternalStore:function(t,n,s){var u=Xe,h=Tn();if(ct){if(s===void 0)throw Error(a(407));s=s()}else{if(s=n(),xt===null)throw Error(a(349));(it&127)!==0||rb(u,n,s)}h.memoizedState=s;var p={value:s,getSnapshot:n};return h.queue=p,vb(ib.bind(null,u,p,t),[t]),u.flags|=2048,zs(9,{destroy:void 0},ab.bind(null,u,p,s,n),null),s},useId:function(){var t=Tn(),n=xt.identifierPrefix;if(ct){var s=Wr,u=Kr;s=(u&~(1<<32-nn(u)-1)).toString(32)+s,n="_"+n+"R_"+s,s=du++,0<\/script>",p=p.removeChild(p.firstChild);break;case"select":p=typeof u.is=="string"?C.createElement("select",{is:u.is}):C.createElement("select"),u.multiple?p.multiple=!0:u.size&&(p.size=u.size);break;default:p=typeof u.is=="string"?C.createElement(h,{is:u.is}):C.createElement(h)}}p[Nt]=n,p[gn]=u;e:for(C=n.child;C!==null;){if(C.tag===5||C.tag===6)p.appendChild(C.stateNode);else if(C.tag!==4&&C.tag!==27&&C.child!==null){C.child.return=C,C=C.child;continue}if(C===n)break e;for(;C.sibling===null;){if(C.return===null||C.return===n)break e;C=C.return}C.sibling.return=C.return,C=C.sibling}n.stateNode=p;e:switch(bn(p,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&&ba(n)}}return Dt(n),Gh(n,n.type,t===null?null:t.memoizedProps,n.pendingProps,s),null;case 6:if(t&&n.stateNode!=null)t.memoizedProps!==u&&ba(n);else{if(typeof u!="string"&&n.stateNode===null)throw Error(a(166));if(t=ae.current,Ds(n)){if(t=n.stateNode,s=n.memoizedProps,u=null,h=pn,h!==null)switch(h.tag){case 27:case 5:u=h.memoizedProps}t[Nt]=n,t=!!(t.nodeValue===s||u!==null&&u.suppressHydrationWarning===!0||tS(t.nodeValue,s)),t||Wa(n,!0)}else t=Hu(t).createTextNode(u),t[Nt]=n,n.stateNode=t}return Dt(n),null;case 31:if(s=n.memoizedState,t===null||t.memoizedState!==null){if(u=Ds(n),s!==null){if(t===null){if(!u)throw Error(a(318));if(t=n.memoizedState,t=t!==null?t.dehydrated:null,!t)throw Error(a(557));t[Nt]=n}else Ni(),(n.flags&128)===0&&(n.memoizedState=null),n.flags|=4;Dt(n),t=!1}else s=eh(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=s),t=!0;if(!t)return n.flags&256?(Qn(n),n):(Qn(n),null);if((n.flags&128)!==0)throw Error(a(558))}return Dt(n),null;case 13:if(u=n.memoizedState,t===null||t.memoizedState!==null&&t.memoizedState.dehydrated!==null){if(h=Ds(n),u!==null&&u.dehydrated!==null){if(t===null){if(!h)throw Error(a(318));if(h=n.memoizedState,h=h!==null?h.dehydrated:null,!h)throw Error(a(317));h[Nt]=n}else Ni(),(n.flags&128)===0&&(n.memoizedState=null),n.flags|=4;Dt(n),h=!1}else h=eh(),t!==null&&t.memoizedState!==null&&(t.memoizedState.hydrationErrors=h),h=!0;if(!h)return n.flags&256?(Qn(n),n):(Qn(n),null)}return Qn(n),(n.flags&128)!==0?(n.lanes=s,n):(s=u!==null,t=t!==null&&t.memoizedState!==null,s&&(u=n.child,h=null,u.alternate!==null&&u.alternate.memoizedState!==null&&u.alternate.memoizedState.cachePool!==null&&(h=u.alternate.memoizedState.cachePool.pool),p=null,u.memoizedState!==null&&u.memoizedState.cachePool!==null&&(p=u.memoizedState.cachePool.pool),p!==h&&(u.flags|=2048)),s!==t&&s&&(n.child.flags|=8192),Cu(n,n.updateQueue),Dt(n),null);case 4:return $e(),t===null&&fg(n.stateNode.containerInfo),Dt(n),null;case 10:return ga(n.type),Dt(n),null;case 19:if(T(Ft),u=n.memoizedState,u===null)return Dt(n),null;if(h=(n.flags&128)!==0,p=u.rendering,p===null)if(h)Cl(u,!1);else{if(qt!==0||t!==null&&(t.flags&128)!==0)for(t=n.child;t!==null;){if(p=cu(t),p!==null){for(n.flags|=128,Cl(u,!1),t=p.updateQueue,n.updateQueue=t,Cu(n,t),n.subtreeFlags=0,t=s,s=n.child;s!==null;)My(s,t),s=s.sibling;return ge(Ft,Ft.current&1|2),ct&&fa(n,u.treeForkCount),n.child}t=t.sibling}u.tail!==null&&Ut()>Tu&&(n.flags|=128,h=!0,Cl(u,!1),n.lanes=4194304)}else{if(!h)if(t=cu(p),t!==null){if(n.flags|=128,h=!0,t=t.updateQueue,n.updateQueue=t,Cu(n,t),Cl(u,!0),u.tail===null&&u.tailMode==="hidden"&&!p.alternate&&!ct)return Dt(n),null}else 2*Ut()-u.renderingStartTime>Tu&&s!==536870912&&(n.flags|=128,h=!0,Cl(u,!1),n.lanes=4194304);u.isBackwards?(p.sibling=n.child,n.child=p):(t=u.last,t!==null?t.sibling=p:n.child=p,u.last=p)}return u.tail!==null?(t=u.tail,u.rendering=t,u.tail=t.sibling,u.renderingStartTime=Ut(),t.sibling=null,s=Ft.current,ge(Ft,h?s&1|2:s&1),ct&&fa(n,u.treeForkCount),t):(Dt(n),null);case 22:case 23:return Qn(n),hh(),u=n.memoizedState!==null,t!==null?t.memoizedState!==null!==u&&(n.flags|=8192):u&&(n.flags|=8192),u?(s&536870912)!==0&&(n.flags&128)===0&&(Dt(n),n.subtreeFlags&6&&(n.flags|=8192)):Dt(n),s=n.updateQueue,s!==null&&Cu(n,s.retryQueue),s=null,t!==null&&t.memoizedState!==null&&t.memoizedState.cachePool!==null&&(s=t.memoizedState.cachePool.pool),u=null,n.memoizedState!==null&&n.memoizedState.cachePool!==null&&(u=n.memoizedState.cachePool.pool),u!==s&&(n.flags|=2048),t!==null&&T(ji),null;case 24:return s=null,t!==null&&(s=t.memoizedState.cache),n.memoizedState.cache!==s&&(n.flags|=2048),ga(Jt),Dt(n),null;case 25:return null;case 30:return null}throw Error(a(156,n.tag))}function GA(t,n){switch(Qf(n),n.tag){case 1:return t=n.flags,t&65536?(n.flags=t&-65537|128,n):null;case 3:return ga(Jt),$e(),t=n.flags,(t&65536)!==0&&(t&128)===0?(n.flags=t&-65537|128,n):null;case 26:case 27:case 5:return At(n),null;case 31:if(n.memoizedState!==null){if(Qn(n),n.alternate===null)throw Error(a(340));Ni()}return t=n.flags,t&65536?(n.flags=t&-65537|128,n):null;case 13:if(Qn(n),t=n.memoizedState,t!==null&&t.dehydrated!==null){if(n.alternate===null)throw Error(a(340));Ni()}return t=n.flags,t&65536?(n.flags=t&-65537|128,n):null;case 19:return T(Ft),null;case 4:return $e(),null;case 10:return ga(n.type),null;case 22:case 23:return Qn(n),hh(),t!==null&&T(ji),t=n.flags,t&65536?(n.flags=t&-65537|128,n):null;case 24:return ga(Jt),null;case 25:return null;default:return null}}function sv(t,n){switch(Qf(n),n.tag){case 3:ga(Jt),$e();break;case 26:case 27:case 5:At(n);break;case 4:$e();break;case 31:n.memoizedState!==null&&Qn(n);break;case 13:Qn(n);break;case 19:T(Ft);break;case 10:ga(n.type);break;case 22:case 23:Qn(n),hh(),t!==null&&T(ji);break;case 24:ga(Jt)}}function El(t,n){try{var s=n.updateQueue,u=s!==null?s.lastEffect:null;if(u!==null){var h=u.next;s=h;do{if((s.tag&t)===t){u=void 0;var p=s.create,C=s.inst;u=p(),C.destroy=u}s=s.next}while(s!==h)}}catch(k){St(n,n.return,k)}}function ti(t,n,s){try{var u=n.updateQueue,h=u!==null?u.lastEffect:null;if(h!==null){var p=h.next;u=p;do{if((u.tag&t)===t){var C=u.inst,k=C.destroy;if(k!==void 0){C.destroy=void 0,h=n;var z=s,Y=k;try{Y()}catch(ne){St(h,z,ne)}}}u=u.next}while(u!==p)}}catch(ne){St(n,n.return,ne)}}function ov(t){var n=t.updateQueue;if(n!==null){var s=t.stateNode;try{Jy(n,s)}catch(u){St(t,t.return,u)}}}function lv(t,n,s){s.props=qi(t.type,t.memoizedProps),s.state=t.memoizedState;try{s.componentWillUnmount()}catch(u){St(t,n,u)}}function _l(t,n){try{var s=t.ref;if(s!==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 s=="function"?t.refCleanup=s(u):s.current=u}}catch(h){St(t,n,h)}}function Yr(t,n){var s=t.ref,u=t.refCleanup;if(s!==null)if(typeof u=="function")try{u()}catch(h){St(t,n,h)}finally{t.refCleanup=null,t=t.alternate,t!=null&&(t.refCleanup=null)}else if(typeof s=="function")try{s(null)}catch(h){St(t,n,h)}else s.current=null}function cv(t){var n=t.type,s=t.memoizedProps,u=t.stateNode;try{e:switch(n){case"button":case"input":case"select":case"textarea":s.autoFocus&&u.focus();break e;case"img":s.src?u.src=s.src:s.srcSet&&(u.srcset=s.srcSet)}}catch(h){St(t,t.return,h)}}function Vh(t,n,s){try{var u=t.stateNode;fx(u,t.type,s,n),u[gn]=n}catch(h){St(t,t.return,h)}}function uv(t){return t.tag===5||t.tag===3||t.tag===26||t.tag===27&&li(t.type)||t.tag===4}function Fh(t){e:for(;;){for(;t.sibling===null;){if(t.return===null||uv(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&&li(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 Kh(t,n,s){var u=t.tag;if(u===5||u===6)t=t.stateNode,n?(s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s).insertBefore(t,n):(n=s.nodeType===9?s.body:s.nodeName==="HTML"?s.ownerDocument.body:s,n.appendChild(t),s=s._reactRootContainer,s!=null||n.onclick!==null||(n.onclick=or));else if(u!==4&&(u===27&&li(t.type)&&(s=t.stateNode,n=null),t=t.child,t!==null))for(Kh(t,n,s),t=t.sibling;t!==null;)Kh(t,n,s),t=t.sibling}function Eu(t,n,s){var u=t.tag;if(u===5||u===6)t=t.stateNode,n?s.insertBefore(t,n):s.appendChild(t);else if(u!==4&&(u===27&&li(t.type)&&(s=t.stateNode),t=t.child,t!==null))for(Eu(t,n,s),t=t.sibling;t!==null;)Eu(t,n,s),t=t.sibling}function dv(t){var n=t.stateNode,s=t.memoizedProps;try{for(var u=t.type,h=n.attributes;h.length;)n.removeAttributeNode(h[0]);bn(n,u,s),n[Nt]=t,n[gn]=s}catch(p){St(t,t.return,p)}}var va=!1,en=!1,Wh=!1,fv=typeof WeakSet=="function"?WeakSet:Set,un=null;function VA(t,n){if(t=t.containerInfo,pg=Gu,t=_y(t),Bf(t)){if("selectionStart"in t)var s={start:t.selectionStart,end:t.selectionEnd};else e:{s=(s=t.ownerDocument)&&s.defaultView||window;var u=s.getSelection&&s.getSelection();if(u&&u.rangeCount!==0){s=u.anchorNode;var h=u.anchorOffset,p=u.focusNode;u=u.focusOffset;try{s.nodeType,p.nodeType}catch{s=null;break e}var C=0,k=-1,z=-1,Y=0,ne=0,le=t,Q=null;t:for(;;){for(var te;le!==s||h!==0&&le.nodeType!==3||(k=C+h),le!==p||u!==0&&le.nodeType!==3||(z=C+u),le.nodeType===3&&(C+=le.nodeValue.length),(te=le.firstChild)!==null;)Q=le,le=te;for(;;){if(le===t)break t;if(Q===s&&++Y===h&&(k=C),Q===p&&++ne===u&&(z=C),(te=le.nextSibling)!==null)break;le=Q,Q=le.parentNode}le=te}s=k===-1||z===-1?null:{start:k,end:z}}else s=null}s=s||{start:0,end:0}}else s=null;for(mg={focusedElem:t,selectionRange:s},Gu=!1,un=n;un!==null;)if(n=un,t=n.child,(n.subtreeFlags&1028)!==0&&t!==null)t.return=n,un=t;else for(;un!==null;){switch(n=un,p=n.alternate,t=n.flags,n.tag){case 0:if((t&4)!==0&&(t=n.updateQueue,t=t!==null?t.events:null,t!==null))for(s=0;s title"))),bn(p,u,s),p[Nt]=t,Xt(p),u=p;break e;case"link":var C=bS("link","href",h).get(u+(s.href||""));if(C){for(var k=0;k_t&&(C=_t,_t=He,He=C);var F=Cy(k,He),P=Cy(k,_t);if(F&&P&&(te.rangeCount!==1||te.anchorNode!==F.node||te.anchorOffset!==F.offset||te.focusNode!==P.node||te.focusOffset!==P.offset)){var W=le.createRange();W.setStart(F.node,F.offset),te.removeAllRanges(),He>_t?(te.addRange(W),te.extend(P.node,P.offset)):(W.setEnd(P.node,P.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;ks?32:s,J.T=null,s=tg,tg=null;var p=ii,C=_a;if(an=0,Gs=ii=null,_a=0,(pt&6)!==0)throw Error(a(331));var k=pt;if(pt|=4,Ev(p.current),Sv(p,p.current,C,s),pt=k,Dl(0,!1),Vt&&typeof Vt.onPostCommitFiberRoot=="function")try{Vt.onPostCommitFiberRoot($n,p)}catch{}return!0}finally{he.p=h,J.T=u,Bv(t,n)}}function qv(t,n,s){n=cr(s,n),n=$h(t.stateNode,n,2),t=Qa(t,n,2),t!==null&&(et(t,2),Xr(t))}function St(t,n,s){if(t.tag===3)qv(t,t,s);else for(;n!==null;){if(n.tag===3){qv(n,t,s);break}else if(n.tag===1){var u=n.stateNode;if(typeof n.type.getDerivedStateFromError=="function"||typeof u.componentDidCatch=="function"&&(ai===null||!ai.has(u))){t=cr(s,t),s=Gb(2),u=Qa(n,s,2),u!==null&&(Vb(s,u,n,t),et(u,2),Xr(u));break}}n=n.return}}function ig(t,n,s){var u=t.pingCache;if(u===null){u=t.pingCache=new WA;var h=new Set;u.set(n,h)}else h=u.get(n),h===void 0&&(h=new Set,u.set(n,h));h.has(s)||(Jh=!0,h.add(s),t=ZA.bind(null,t,n,s),n.then(t,t))}function ZA(t,n,s){var u=t.pingCache;u!==null&&u.delete(n),t.pingedLanes|=t.suspendedLanes&s,t.warmLanes&=~s,xt===t&&(it&s)===s&&(qt===4||qt===3&&(it&62914560)===it&&300>Ut()-xu?(pt&2)===0&&Vs(t,0):Qh|=s,qs===it&&(qs=0)),Xr(t)}function Gv(t,n){n===0&&(n=De()),t=Mi(t,n),t!==null&&(et(t,n),Xr(t))}function ex(t){var n=t.memoizedState,s=0;n!==null&&(s=n.retryLane),Gv(t,s)}function tx(t,n){var s=0;switch(t.tag){case 31:case 13:var u=t.stateNode,h=t.memoizedState;h!==null&&(s=h.retryLane);break;case 19:u=t.stateNode;break;case 22:u=t.stateNode._retryCache;break;default:throw Error(a(314))}u!==null&&u.delete(n),Gv(t,s)}function nx(t,n){return cn(t,n)}var Mu=null,Ks=null,sg=!1,$u=!1,og=!1,oi=0;function Xr(t){t!==Ks&&t.next===null&&(Ks===null?Mu=Ks=t:Ks=Ks.next=t),$u=!0,sg||(sg=!0,ax())}function Dl(t,n){if(!og&&$u){og=!0;do for(var s=!1,u=Mu;u!==null;){if(t!==0){var h=u.pendingLanes;if(h===0)var p=0;else{var C=u.suspendedLanes,k=u.pingedLanes;p=(1<<31-nn(42|t)+1)-1,p&=h&~(C&~k),p=p&201326741?p&201326741|1:p?p|2:0}p!==0&&(s=!0,Wv(u,p))}else p=it,p=_e(u,u===xt?p:0,u.cancelPendingCommit!==null||u.timeoutHandle!==-1),(p&3)===0||Be(u,p)||(s=!0,Wv(u,p));u=u.next}while(s);og=!1}}function rx(){Vv()}function Vv(){$u=sg=!1;var t=0;oi!==0&&gx()&&(t=oi);for(var n=Ut(),s=null,u=Mu;u!==null;){var h=u.next,p=Fv(u,n);p===0?(u.next=null,s===null?Mu=h:s.next=h,h===null&&(Ks=s)):(s=u,(t!==0||(p&3)!==0)&&($u=!0)),u=h}an!==0&&an!==5||Dl(t),oi!==0&&(oi=0)}function Fv(t,n){for(var s=t.suspendedLanes,u=t.pingedLanes,h=t.expirationTimes,p=t.pendingLanes&-62914561;0k)break;var ne=z.transferSize,le=z.initiatorType;ne&&nS(le)&&(z=z.responseEnd,C+=ne*(z"u"?null:document;function gS(t,n,s){var u=Ws;if(u&&typeof n=="string"&&n){var h=jn(n);h='link[rel="'+t+'"][href="'+h+'"]',typeof s=="string"&&(h+='[crossorigin="'+s+'"]'),hS.has(h)||(hS.add(h),t={rel:t,crossOrigin:s,href:n},u.querySelector(h)===null&&(n=u.createElement("link"),bn(n,"link",t),Xt(n),u.head.appendChild(n)))}}function Ex(t){Aa.D(t),gS("dns-prefetch",t,null)}function _x(t,n){Aa.C(t,n),gS("preconnect",t,n)}function Ax(t,n,s){Aa.L(t,n,s);var u=Ws;if(u&&t&&n){var h='link[rel="preload"][as="'+jn(n)+'"]';n==="image"&&s&&s.imageSrcSet?(h+='[imagesrcset="'+jn(s.imageSrcSet)+'"]',typeof s.imageSizes=="string"&&(h+='[imagesizes="'+jn(s.imageSizes)+'"]')):h+='[href="'+jn(t)+'"]';var p=h;switch(n){case"style":p=Ys(t);break;case"script":p=Xs(t)}pr.has(p)||(t=y({rel:"preload",href:n==="image"&&s&&s.imageSrcSet?void 0:t,as:n},s),pr.set(p,t),u.querySelector(h)!==null||n==="style"&&u.querySelector($l(p))||n==="script"&&u.querySelector(Nl(p))||(n=u.createElement("link"),bn(n,"link",t),Xt(n),u.head.appendChild(n)))}}function xx(t,n){Aa.m(t,n);var s=Ws;if(s&&t){var u=n&&typeof n.as=="string"?n.as:"script",h='link[rel="modulepreload"][as="'+jn(u)+'"][href="'+jn(t)+'"]',p=h;switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":p=Xs(t)}if(!pr.has(p)&&(t=y({rel:"modulepreload",href:t},n),pr.set(p,t),s.querySelector(h)===null)){switch(u){case"audioworklet":case"paintworklet":case"serviceworker":case"sharedworker":case"worker":case"script":if(s.querySelector(Nl(p)))return}u=s.createElement("link"),bn(u,"link",t),Xt(u),s.head.appendChild(u)}}}function Tx(t,n,s){Aa.S(t,n,s);var u=Ws;if(u&&t){var h=qr(u).hoistableStyles,p=Ys(t);n=n||"default";var C=h.get(p);if(!C){var k={loading:0,preload:null};if(C=u.querySelector($l(p)))k.loading=5;else{t=y({rel:"stylesheet",href:t,"data-precedence":n},s),(s=pr.get(p))&&Eg(t,s);var z=C=u.createElement("link");Xt(z),bn(z,"link",t),z._p=new Promise(function(Y,ne){z.onload=Y,z.onerror=ne}),z.addEventListener("load",function(){k.loading|=1}),z.addEventListener("error",function(){k.loading|=2}),k.loading|=4,zu(C,n,u)}C={type:"stylesheet",instance:C,count:1,state:k},h.set(p,C)}}}function kx(t,n){Aa.X(t,n);var s=Ws;if(s&&t){var u=qr(s).hoistableScripts,h=Xs(t),p=u.get(h);p||(p=s.querySelector(Nl(h)),p||(t=y({src:t,async:!0},n),(n=pr.get(h))&&_g(t,n),p=s.createElement("script"),Xt(p),bn(p,"link",t),s.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},u.set(h,p))}}function Rx(t,n){Aa.M(t,n);var s=Ws;if(s&&t){var u=qr(s).hoistableScripts,h=Xs(t),p=u.get(h);p||(p=s.querySelector(Nl(h)),p||(t=y({src:t,async:!0,type:"module"},n),(n=pr.get(h))&&_g(t,n),p=s.createElement("script"),Xt(p),bn(p,"link",t),s.head.appendChild(p)),p={type:"script",instance:p,count:1,state:null},u.set(h,p))}}function pS(t,n,s,u){var h=(h=ae.current)?ju(h):null;if(!h)throw Error(a(446));switch(t){case"meta":case"title":return null;case"style":return typeof s.precedence=="string"&&typeof s.href=="string"?(n=Ys(s.href),s=qr(h).hoistableStyles,u=s.get(n),u||(u={type:"style",instance:null,count:0,state:null},s.set(n,u)),u):{type:"void",instance:null,count:0,state:null};case"link":if(s.rel==="stylesheet"&&typeof s.href=="string"&&typeof s.precedence=="string"){t=Ys(s.href);var p=qr(h).hoistableStyles,C=p.get(t);if(C||(h=h.ownerDocument||h,C={type:"stylesheet",instance:null,count:0,state:{loading:0,preload:null}},p.set(t,C),(p=h.querySelector($l(t)))&&!p._p&&(C.instance=p,C.state.loading=5),pr.has(t)||(s={rel:"preload",as:"style",href:s.href,crossOrigin:s.crossOrigin,integrity:s.integrity,media:s.media,hrefLang:s.hrefLang,referrerPolicy:s.referrerPolicy},pr.set(t,s),p||Dx(h,t,s,C.state))),n&&u===null)throw Error(a(528,""));return C}if(n&&u!==null)throw Error(a(529,""));return null;case"script":return n=s.async,s=s.src,typeof s=="string"&&n&&typeof n!="function"&&typeof n!="symbol"?(n=Xs(s),s=qr(h).hoistableScripts,u=s.get(n),u||(u={type:"script",instance:null,count:0,state:null},s.set(n,u)),u):{type:"void",instance:null,count:0,state:null};default:throw Error(a(444,t))}}function Ys(t){return'href="'+jn(t)+'"'}function $l(t){return'link[rel="stylesheet"]['+t+"]"}function mS(t){return y({},t,{"data-precedence":t.precedence,precedence:null})}function Dx(t,n,s,u){t.querySelector('link[rel="preload"][as="style"]['+n+"]")?u.loading=1:(n=t.createElement("link"),u.preload=n,n.addEventListener("load",function(){return u.loading|=1}),n.addEventListener("error",function(){return u.loading|=2}),bn(n,"link",s),Xt(n),t.head.appendChild(n))}function Xs(t){return'[src="'+jn(t)+'"]'}function Nl(t){return"script[async]"+t}function yS(t,n,s){if(n.count++,n.instance===null)switch(n.type){case"style":var u=t.querySelector('style[data-href~="'+jn(s.href)+'"]');if(u)return n.instance=u,Xt(u),u;var h=y({},s,{"data-href":s.href,"data-precedence":s.precedence,href:null,precedence:null});return u=(t.ownerDocument||t).createElement("style"),Xt(u),bn(u,"style",h),zu(u,s.precedence,t),n.instance=u;case"stylesheet":h=Ys(s.href);var p=t.querySelector($l(h));if(p)return n.state.loading|=4,n.instance=p,Xt(p),p;u=mS(s),(h=pr.get(h))&&Eg(u,h),p=(t.ownerDocument||t).createElement("link"),Xt(p);var C=p;return C._p=new Promise(function(k,z){C.onload=k,C.onerror=z}),bn(p,"link",u),n.state.loading|=4,zu(p,s.precedence,t),n.instance=p;case"script":return p=Xs(s.src),(h=t.querySelector(Nl(p)))?(n.instance=h,Xt(h),h):(u=s,(h=pr.get(p))&&(u=y({},s),_g(u,h)),t=t.ownerDocument||t,h=t.createElement("script"),Xt(h),bn(h,"link",u),t.head.appendChild(h),n.instance=h);case"void":return null;default:throw Error(a(443,n.type))}else n.type==="stylesheet"&&(n.state.loading&4)===0&&(u=n.instance,n.state.loading|=4,zu(u,s.precedence,t));return n.instance}function zu(t,n,s){for(var u=s.querySelectorAll('link[rel="stylesheet"][data-precedence],style[data-precedence]'),h=u.length?u[u.length-1]:null,p=h,C=0;C title"):null)}function Ox(t,n,s){if(s===1||n.itemProp!=null)return!1;switch(t){case"meta":case"title":return!0;case"style":if(typeof n.precedence!="string"||typeof n.href!="string"||n.href==="")break;return!0;case"link":if(typeof n.rel!="string"||typeof n.href!="string"||n.href===""||n.onLoad||n.onError)break;switch(n.rel){case"stylesheet":return t=n.disabled,typeof n.precedence=="string"&&t==null;default:return!0}case"script":if(n.async&&typeof n.async!="function"&&typeof n.async!="symbol"&&!n.onLoad&&!n.onError&&n.src&&typeof n.src=="string")return!0}return!1}function SS(t){return!(t.type==="stylesheet"&&(t.state.loading&3)===0)}function Lx(t,n,s,u){if(s.type==="stylesheet"&&(typeof u.media!="string"||matchMedia(u.media).matches!==!1)&&(s.state.loading&4)===0){if(s.instance===null){var h=Ys(u.href),p=n.querySelector($l(h));if(p){n=p._p,n!==null&&typeof n=="object"&&typeof n.then=="function"&&(t.count++,t=Bu.bind(t),n.then(t,t)),s.state.loading|=4,s.instance=p,Xt(p);return}p=n.ownerDocument||n,u=mS(u),(h=pr.get(h))&&Eg(u,h),p=p.createElement("link"),Xt(p);var C=p;C._p=new Promise(function(k,z){C.onload=k,C.onerror=z}),bn(p,"link",u),s.instance=p}t.stylesheets===null&&(t.stylesheets=new Map),t.stylesheets.set(s,n),(n=s.state.preload)&&(s.state.loading&3)===0&&(t.count++,s=Bu.bind(t),n.addEventListener("load",s),n.addEventListener("error",s))}}var Ag=0;function Mx(t,n){return t.stylesheets&&t.count===0&&qu(t,t.stylesheets),0Ag?50:800)+n);return t.unsuspend=s,function(){t.unsuspend=null,clearTimeout(u),clearTimeout(h)}}:null}function Bu(){if(this.count--,this.count===0&&(this.imgCount===0||!this.waitingForImages)){if(this.stylesheets)qu(this,this.stylesheets);else if(this.unsuspend){var t=this.unsuspend;this.unsuspend=null,t()}}}var Pu=null;function qu(t,n){t.stylesheets=null,t.unsuspend!==null&&(t.count++,Pu=new Map,n.forEach($x,t),Pu=null,Bu.call(t))}function $x(t,n){if(!(n.state.loading&4)){var s=Pu.get(t);if(s)var u=s.get(null);else{s=new Map,Pu.set(t,s);for(var h=t.querySelectorAll("link[data-precedence],style[data-precedence]"),p=0;p"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(o)}catch(e){console.error(e)}}return o(),Zu.exports=US(),Zu.exports}var rd=BS();const ad=Qr(rd),Zs=[],PS=50;let id=!1;function Bg(){try{return window.G7Core?.devTools}catch{return}}function Fi(o,e,r){const a=Bg();if(id&&a?.isEnabled?.()){a.trackLog?.(o,e,r);return}id||(o==="error"||o==="warn")&&Zs.length{r.isDebugEnabled()&&console.log(e,...a),Fi("log",o,a)},warn:(...a)=>{r.isDebugEnabled()&&console.warn(e,...a),Fi("warn",o,a)},error:(...a)=>{r.isDebugEnabled()&&console.error(e,...a),Fi("error",o,a)}}}eo.getInstance();const Ki=ut("networkResilience"),Pg=2,qg=300,Gg=2e3,qS=15e3;function od(o){return o?.name==="AbortError"}function Vg(o){return od(o)?!1:o instanceof TypeError}let Ul=!1,Fg=!1;function ld(){return Ul}function GS(){typeof window>"u"||Fg||(Fg=!0,window.addEventListener("pagehide",()=>{Ul=!0}),window.addEventListener("pageshow",o=>{o.persisted&&(Ul=!1)}),window.addEventListener("beforeunload",()=>{Ul=!0}))}function Kg(o,e,r){const a=Math.min(e*Math.pow(2,o),r),i=a*.25*(Math.random()*2-1);return Math.max(0,Math.round(a+i))}function Wg(o){return new Promise(e=>setTimeout(e,o))}async function Bl(o,e={}){const{retries:r=Pg,baseDelayMs:a=qg,maxDelayMs:i=Gg,timeoutMs:l=qS,label:c=o,init:d}=e,f=r+1;let g;for(let m=0;m0?new AbortController:null;try{const v={...d};if(S){const x=d?.signal;x&&(x.aborted?S.abort():x.addEventListener("abort",()=>S.abort(),{once:!0})),v.signal=S.signal,w=setTimeout(()=>{y=!0,S.abort()},l)}return await fetch(o,v)}catch(v){if(g=v,od(v)&&!y||!(y||Vg(v)))throw v;if(ld())throw Ki.warn(`Document unloading, aborting retries: ${c}`),v;if(m===f-1)throw Ki.warn(`All ${f} attempts failed: ${c}`,v),v;const R=Kg(m,a,i);Ki.warn(`Network failure (attempt ${m+1}/${f}), retrying in ${R}ms: ${c}`),await Wg(R)}finally{w!==void 0&&clearTimeout(w)}}throw g}async function Yg(o,e={},r={}){const{retries:a=Pg,baseDelayMs:i=qg,maxDelayMs:l=Gg,label:c=o}=r,d=a+1;for(let f=0;f{const i=document.createElement("script");i.src=o,i.async=!1;for(const[l,c]of Object.entries(e))l==="id"?i.id=c:i.setAttribute(l,c);i.onload=()=>r(),i.onerror=()=>a(new Error(`Failed to load script: ${o}`)),document.head.appendChild(i)})}const Xg="extension",Wi="extensionless",FS="file";function KS(){const o=globalThis?.G7Config;if(globalThis?.__g7AssetUrlMode===Wi)return Wi;const r=o?.assetUrlMode;return r===Wi||r===Xg?r:o?.settings?.general?.asset_url_mode===Wi?Wi:Xg}function Jg(){return KS()===Wi}function Nr(o,e,r,a){const i=o.replace(/\/+$/,""),l=e.replace(/^\.+/,""),c=Jg()?i:`${i}.${l}`,d=[];return a&&d.push(a.replace(/^[?&]+/,"")),r!=null&&r!==""&&d.push(`v=${r}`),d.length>0?`${c}?${d.join("&")}`:c}function xa(o){if(!o||!Jg())return o;const e=globalThis?.location?.origin,r=e&&o.startsWith(e)?o.slice(e.length):o;if(!r.startsWith("/api/"))return o;const[a,i]=WS(r),l=a.match(/^\/api\/(modules|plugins)\/bundle\.(js|css)$/);if(l)return Qg(`/api/${l[1]}/bundle/${l[2]}`,i);const c=a.match(/^\/api\/(templates|modules|plugins)\/assets\/([^/]+)\/(.+)$/);if(c){const[,f,g,m]=c,y=`${FS}=${encodeURIComponent(decodeURIComponent(m))}`;return`/api/${f}/assets/${g}?${y}${i?`&${i}`:""}`}const d=a.match(/^(\/api\/.+)\.(json|js|css)$/);return d?Qg(d[1],i):o}function WS(o){const e=o.indexOf("?");return e===-1?[o,""]:[o.slice(0,e),o.slice(e+1)]}function Qg(o,e){return e?`${o}?${e}`:o}const Ir=ut("ComponentRegistry");class sn extends Error{constructor(e,r,a){super(e),this.code=r,this.details=a,this.name="ComponentRegistryError"}}const Kn=class Kn{constructor(){$(this,"registry",{});$(this,"manifest",null);$(this,"loadingState","idle");$(this,"error",null);$(this,"templateId",null);$(this,"templateType",null)}static getInstance(){return Kn.instance||(Kn.instance=new Kn),Kn.instance}static createIsolatedInstance(){return new Kn}static resetInstance(){Kn.instance=null}async loadComponents(e,r){if(this.loadingState==="loading")throw new sn("Components are already being loaded","LOADING_IN_PROGRESS");if(this.loadingState==="loaded"&&this.templateId===e&&this.templateType===r){Ir.log("Components already loaded for template:",e,r);return}this.loadingState="loading",this.templateId=e,this.templateType=r,this.error=null;try{await this.loadManifest(),await this.loadComponentBundle(),this.loadingState="loaded",Ir.log("Successfully loaded components:",Object.keys(this.registry).length)}catch(a){throw this.loadingState="error",this.error=a instanceof Error?a:new Error(String(a)),new sn(`Failed to load components: ${this.error.message}`,"LOAD_FAILED",{originalError:this.error})}}async loadManifest(){try{if(!this.templateId)throw new sn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=`${this.templateId}:${this.templateType}`;if(Kn.manifestCache.has(e)){this.manifest=Kn.manifestCache.get(e),Ir.log("Manifest loaded from cache:",this.manifest.templateId);return}const r=Nr(`/api/templates/${this.templateId}/components`,"json"),a=await Bl(r,{label:"components.json"});if(!a.ok)throw new sn(`Failed to fetch manifest: ${a.status} ${a.statusText}`,"MANIFEST_FETCH_FAILED",{status:a.status,statusText:a.statusText});const i=await a.json();this.validateManifest(i),this.manifest=i,Kn.manifestCache.set(e,i),Ir.log("Manifest loaded and cached:",i.templateId)}catch(e){throw e instanceof sn?e:new sn("Failed to load component manifest","MANIFEST_LOAD_FAILED",{originalError:e})}}validateManifest(e){if(!e.version)throw new sn("Manifest missing required field: version","MANIFEST_INVALID",{field:"version"});if(!e.templateId)throw new sn("Manifest missing required field: templateId","MANIFEST_INVALID",{field:"templateId"});if(!e.components||typeof e.components!="object")throw new sn("Manifest missing required field: components","MANIFEST_INVALID",{field:"components"});const r=["basic","composite","layout"];for(const a of r){if(!Array.isArray(e.components[a]))throw new sn(`Manifest field 'components.${a}' must be an array`,"MANIFEST_INVALID",{field:`components.${a}`,value:e.components[a]});e.components[a].forEach((i,l)=>{if(!i.name||typeof i.name!="string")throw new sn(`Invalid component metadata at ${a}[${l}]: missing or invalid 'name'`,"MANIFEST_INVALID",{type:a,index:l,metadata:i});if(!i.type||typeof i.type!="string")throw new sn(`Invalid component metadata at ${a}[${l}]: missing or invalid 'type'`,"MANIFEST_INVALID",{type:a,index:l,metadata:i})})}Ir.log("Manifest validation passed")}async loadComponentBundle(){try{if(!this.templateId)throw new sn("Template ID not set","TEMPLATE_ID_NOT_SET");const e=this.getGlobalVariableName(),r=window[e];if(!r||typeof r!="object")throw new sn(`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(r),Ir.log("Component bundle loaded from global variable:",e)}catch(e){throw e instanceof sn?e:new sn("Failed to load component bundle","BUNDLE_LOAD_FAILED",{originalError:e})}}getGlobalVariableName(){if(!this.templateId)throw new sn("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 sn("Manifest not loaded","MANIFEST_NOT_LOADED");const r=["basic","composite","layout"];for(const a of r){const i=this.manifest.components[a]||[];for(const l of i){const c=l.name,d=e[c];if(!d){Ir.warn(`Component '${c}' not found in bundle`);continue}this.registerComponent(c,d,l)}}}registerComponent(e,r,a){this.registry[e]&&Ir.warn(`Component '${e}' already registered, overwriting`);const i=We.memo(r);this.registry[e]={component:i,metadata:a},Ir.log(`[ComponentRegistry] Registered component: ${e} (${a.type})`)}getComponent(e){const r=this.registry[e];return r?r.component:null}getMetadata(e){const r=this.registry[e];return r?r.metadata:null}hasComponent(e){return e in this.registry}getComponentsByType(e){return Object.entries(this.registry).filter(([r,a])=>a.metadata.type===e).map(([r,a])=>r)}getAllComponents(){return Object.keys(this.registry)}getComponentMap(){const e={};for(const[r,a]of Object.entries(this.registry))e[r]=a.component;return e}getLoadingState(){return this.loadingState}getError(){return this.error}getTemplateId(){return this.templateId}getManifest(){return this.manifest}clear(){this.registry={},this.manifest=null,this.loadingState="idle",this.error=null,this.templateId=null,this.templateType=null,Ir.log("Registry cleared")}};$(Kn,"instance",null),$(Kn,"manifestCache",new Map);let mr=Kn;const Zg=ut("TranslationEngine");class cd extends Error{constructor(e,r,a){super(e),this.key=r,this.locale=a,this.name="TranslationError"}}const On=class On{constructor(e={}){$(this,"cache",new Map);$(this,"translations",new Map);$(this,"options");$(this,"cacheVersion",0);this.options={defaultLocale:e.defaultLocale||"ko",fallbackLocale:e.fallbackLocale||"en",cacheTTL:e.cacheTTL||3e5}}static getInstance(e={}){return On.instance||(On.instance=new On(e)),On.instance}static resetInstance(){On.instance=null}setCacheVersion(e){this.cacheVersion!==e&&(Zg.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.cache.clear())}getCacheVersion(){return this.cacheVersion}async loadTranslations(e,r,a="/api",i=!1){const l=`${e}:${r}`;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=Nr(`${a}/templates/${e}/lang/${r}`,"json",this.cacheVersion>0?this.cacheVersion:null,c.length>0?c.join("&"):void 0),f=await fetch(d);if(!f.ok)throw new cd(`Failed to load translations: ${f.statusText}`,void 0,r);const m=await f.json();return this.saveToCache(l,m),this.translations.set(l,m),m}catch(c){throw new cd(`Failed to fetch translations for ${r}: ${c instanceof Error?c.message:String(c)}`,void 0,r)}}resolveTranslations(e,r,a){let i=e;const l=5;let c=0;for(;c"="+this.translate(m,r,void 0,a)),i===d)break;c++}return i.replace(On.TRANSLATION_PATTERN,(d,f,g)=>{const{cleanedParams:m,trailing:y}=this.separateTrailingText(g);return this.translate(f,r,m,a)+y})}translate(e,r,a,i){const l=this.getTranslation(e,r),c=a&&this.cleanParamsStr(a);if(c){const d=this.parseParams(c,i);return this.replaceParams(l,d)}return l}getTranslation(e,r){const{templateId:a,locale:i}=r,l=`${a}:${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=`${a}:${this.options.fallbackLocale}`,f=this.translations.get(d);if(f){const g=this.getNestedValue(f,e);if(g!==null)return g}}return e}getNestedValue(e,r){const a=r.split(".");let i=e;for(const l of a){if(i==null||typeof i!="object")return null;i=i[l]}return typeof i=="string"?i:null}setTranslationValue(e,r,a,i){const l=`${e}:${r}`,c=this.translations.get(l)??{},d=a.split(".");let f=c;for(let g=0;g(l.push(f),`__PLACEHOLDER_${l.length-1}__`)).matchAll(On.PARAM_PATTERN);for(const f of d){const[,g,m]=f,y=m.replace(/__PLACEHOLDER_(\d+)__/g,(w,S)=>l[parseInt(S,10)]);a[g.trim()]=this.resolveParamValue(y.trim(),r)}return a}resolveParamValue(e,r){if(e.startsWith("{{")&&e.endsWith("}}")){const a=e.slice(2,-2).trim();if(/[|&()[\]!?:+\-*/%<>=\s]/.test(a)&&r)try{const l=pd.evaluateExpression(a,r);return String(l??"")}catch(l){return Zg.error("Expression evaluation failed:",a,l),""}else{const l=this.getNestedDataValue(r,a);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 a=e.match(/(\s+[^\p{L}\w=|&\s][^\p{L}\w=]*\s*)$/u);return a?{cleanedParams:e.slice(0,-a[1].length),trailing:a[1]}:{cleanedParams:e,trailing:""}}cleanParamsStr(e){return this.separateTrailingText(e).cleanedParams||""}getNestedDataValue(e,r){if(!e)return;const a=r.split(".");let i=e;for(const l of a){if(i==null)return;i=i[l]}return i}replaceParams(e,r){let a=e;for(const[i,l]of Object.entries(r)){const c=new RegExp(`\\{\\{${i}\\}\\}`,"g");a=a.replace(c,String(l));const d=new RegExp(`\\{${i}\\}`,"g");a=a.replace(d,String(l))}return a}getFromCache(e){const r=this.cache.get(e);return r?Date.now()-r.timestamp>this.options.cacheTTL?(this.cache.delete(e),null):r.data:null}saveToCache(e,r){this.cache.set(e,{data:r,timestamp:Date.now()})}clearCache(){this.cache.clear(),this.translations.clear()}pruneCache(){const e=Date.now(),r=[];for(const[a,i]of this.cache.entries())e-i.timestamp>this.options.cacheTTL&&r.push(a);for(const a of r)this.cache.delete(a)}getCacheStats(){const e=Date.now();let r=0;for(const a of this.cache.values())e-a.timestamp>this.options.cacheTTL&&r++;return{size:this.cache.size,expired:r}}};$(On,"instance",null),$(On,"TRANSLATION_PATTERN",/\$t:(?:defer:)?([a-zA-Z0-9._-]+)(\|(?:(?!\$t:).)+)?/g),$(On,"NESTED_TRANSLATION_PARAM_PATTERN",/=(\$t:([a-zA-Z0-9._-]+))(?=[|&\s]|$)/g),$(On,"PARAM_PATTERN",/([^=|&]+)=([^|&]+)/g);let gi=On;const ep=Object.freeze(Object.defineProperty({__proto__:null,TranslationEngine:gi,TranslationError:cd},Symbol.toStringTag,{value:"Module"})),Yi=ut("PipeRegistry");function tp(o,e){const r=o.getFullYear(),a=String(o.getMonth()+1).padStart(2,"0"),i=String(o.getDate()).padStart(2,"0"),l=String(o.getHours()).padStart(2,"0"),c=String(o.getMinutes()).padStart(2,"0"),d=String(o.getSeconds()).padStart(2,"0");return e.replace("YYYY",String(r)).replace("YY",String(r).slice(-2)).replace("MM",a).replace("M",String(o.getMonth()+1)).replace("DD",i).replace("D",String(o.getDate())).replace("HH",l).replace("H",String(o.getHours())).replace("mm",c).replace("m",String(o.getMinutes())).replace("ss",d).replace("s",String(o.getSeconds()))}function YS(o,e="ko"){const a=new Date().getTime()-o.getTime(),i=Math.floor(a/1e3),l=Math.floor(i/60),c=Math.floor(l/60),d=Math.floor(c/24),f=Math.floor(d/7),g=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}주 전`:g<12?`${g}개월 전`:`${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`:g<12?`${g} month${g===1?"":"s"} ago`:`${m} year${m===1?"":"s"} ago`}function ud(o){if(o==null)return null;if(o instanceof Date)return o;if(typeof o=="number")return new Date(o);if(typeof o=="string"){const e=new Date(o);return isNaN(e.getTime())?null:e}return null}const to={date:{fn:(o,e="YYYY-MM-DD")=>{const r=ud(o);return r?tp(r,e):""},description:"날짜 포맷 (기본: YYYY-MM-DD)"},datetime:{fn:(o,e="YYYY-MM-DD HH:mm")=>{const r=ud(o);return r?tp(r,e):""},description:"날짜+시간 포맷 (기본: YYYY-MM-DD HH:mm)"},relativeTime:{fn:(o,e="ko")=>{const r=ud(o);return r?YS(r,e):""},description:'상대 시간 표시 (예: "3분 전")'},number:{fn:(o,e)=>{const r=Number(o);if(isNaN(r))return String(o??"");const a={};return e!==void 0&&(a.minimumFractionDigits=e,a.maximumFractionDigits=e),r.toLocaleString(void 0,a)},description:"숫자 포맷 (천단위 구분, 선택적 소수점)"},truncate:{fn:(o,e=100,r="...")=>typeof o!="string"?String(o??""):o.length<=e?o:o.slice(0,e)+r,description:'문자열 자르기 (기본: 100자, 접미사: "...")'},uppercase:{fn:o=>typeof o!="string"?String(o??""):o.toUpperCase(),description:"대문자 변환"},lowercase:{fn:o=>typeof o!="string"?String(o??""):o.toLowerCase(),description:"소문자 변환"},stripHtml:{fn:o=>typeof o!="string"?String(o??""):o.replace(/<[^>]*>/g,""),description:"HTML 태그 제거"},default:{fn:(o,e="")=>o==null||o===""?e:o,description:"기본값 설정 (null, undefined, 빈문자열 시)"},fallback:{fn:(o,e)=>o??e,description:"폴백 값 설정 (null, undefined 시만)"},first:{fn:o=>{if(Array.isArray(o))return o[0]},description:"배열의 첫 번째 요소"},last:{fn:o=>{if(Array.isArray(o))return o[o.length-1]},description:"배열의 마지막 요소"},join:{fn:(o,e=", ")=>Array.isArray(o)?o.join(e):"",description:'배열을 문자열로 결합 (기본 구분자: ", ")'},length:{fn:o=>Array.isArray(o)||typeof o=="string"?o.length:0,description:"배열/문자열 길이"},filterBy:{fn:(o,e,r)=>Array.isArray(o)?Array.isArray(e)?o.filter(a=>{const i=r?a?.[r]:a;return e.includes(i)}):o:[],description:"배열 필터링 (allowList에 포함된 항목만 반환)"},keys:{fn:o=>o==null||typeof o!="object"?[]:Object.keys(o),description:"객체의 키 배열"},values:{fn:o=>o==null||typeof o!="object"?[]:Object.values(o),description:"객체의 값 배열"},json:{fn:(o,e)=>{try{return JSON.stringify(o,null,e)}catch{return""}},description:"JSON 문자열로 변환"},localized:{fn:(o,e)=>o==null?"":typeof o=="string"?o:typeof o!="object"?String(o):o[e||"ko"]||o.ko||o.en||Object.values(o)[0]||"",description:"다국어 객체에서 로케일에 맞는 값 추출"}},Xi=new Map,Ci=class Ci{static getInstance(){return Ci.instance||(Ci.instance=new Ci),Ci.instance}register(e,r,a){if(to[e]){Yi.warn(`[PipeRegistry] 내장 파이프를 덮어쓸 수 없습니다: ${e}`);return}Xi.set(e,{fn:r,description:a}),Yi.log(`[PipeRegistry] 커스텀 파이프 등록됨: ${e}`)}unregister(e){if(to[e])return Yi.warn(`[PipeRegistry] 내장 파이프는 해제할 수 없습니다: ${e}`),!1;const r=Xi.delete(e);return r&&Yi.log(`[PipeRegistry] 커스텀 파이프 해제됨: ${e}`),r}get(e){const r=to[e];return r?r.fn:Xi.get(e)?.fn}has(e){return!!to[e]||Xi.has(e)}execute(e,r,a=[]){const i=this.get(e);if(!i)return Yi.warn(`[PipeRegistry] 알 수 없는 파이프: ${e}`),r;try{return i(r,...a)}catch(l){return Yi.error(`[PipeRegistry] 파이프 실행 오류 (${e}):`,l),r}}list(){const e=[];for(const[r,a]of Object.entries(to))e.push({name:r,description:a.description,type:"built-in"});for(const[r,a]of Xi.entries())e.push({name:r,description:a.description,type:"custom"});return e.sort((r,a)=>r.name.localeCompare(a.name))}clearCustomPipes(){Xi.clear()}};$(Ci,"instance",null);let Pl=Ci;Pl.getInstance();function XS(o){const e=o.trim(),r=e.indexOf("(");if(r===-1)return{name:e,args:[]};const a=e.slice(0,r).trim(),i=e.slice(r+1,-1);if(!i.trim())return{name:a,args:[]};const l=[];let c="",d=null,f=0;for(let g=0;g0?i[g-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(np(c.trim())),c="";continue}c+=m}return c.trim()&&l.push(np(c.trim())),{name:a,args:l}}function np(o){if(o==="null")return null;if(o==="undefined")return;if(o==="true")return!0;if(o==="false")return!1;const e=Number(o);return!isNaN(e)&&o!==""?e:o}function JS(o){const e=[];let r="",a=null,i=0;for(let l=0;l0?o[l-1]:"",f=l0?o[a-1]:"",c=a0){a--;continue}return null}}return a===0?e.trim():null}function ZS(o){const e=[];if(typeof o!="string")return e;for(let r=0;r0){i--;continue}if(o[c+1]==="}"){l=c;break}break}}l!==-1&&(e.push({start:r,end:l+2,expr:o.slice(r+2,l)}),r=l+1)}return e}function no(o){return/[?:|&!+\-*/<>=()[\]{}]/.test(o)}function rp(o){const e=typeof o=="string"?o.trim():"";return e===""?"empty":dd.has(e)?"literal":Gn(e)?"pipe":no(e)?"expression":"path"}function fd(o,e,r,a){const i=typeof o=="string"?o.trim():"",l=rp(i),c=a?.skipCache?{skipCache:!0}:void 0;if(l==="empty"){a?.onEmpty?.(o);return}if(l==="literal")return dd.get(i);try{return l==="pipe"?r.evaluatePipeExpression(i,e,c,a?.trackingInfo):l==="expression"?r.evaluateExpression(i,e,a?.trackingInfo):r.resolve(i,e,c,a?.trackingInfo)}catch(d){if(a?.onError)return a.onError(d,i);throw d}}const nr="raw:";function ap(o){return o.startsWith(nr)?o.slice(nr.length):o}const ro="﷐",pi="﷑",ka="﷒";function ao(o){return ro+o+pi}function ql(o){return o.length>=2&&o.charCodeAt(0)===64976&&o.charCodeAt(o.length-1)===64977}function Gl(o){return o.includes(ro)}function hd(o){return o.slice(1,-1)}function Ji(o){if(typeof o=="string")return ao(o);if(Array.isArray(o))return o.map(Ji);if(o&&typeof o=="object"){const e={};for(const[r,a]of Object.entries(o))e[r]=Ji(a);return e}return o}function Ra(o){if(typeof o=="string")return ql(o)?hd(o):Gl(o)||o.includes(pi)?o.split(ro).join("").split(pi).join(""):o;if(Array.isArray(o)){let e=!1;const r=o.map(a=>{const i=Ra(a);return i!==a&&(e=!0),i});return e?r:o}if(o&&typeof o=="object"){if(o.$$typeof!==void 0)return o;let e=!1;const r={};for(const[a,i]of Object.entries(o)){const l=Ra(i);l!==i&&(e=!0),r[a]=l}return e?r:o}return o}const Da=ut("DataBindingEngine"),ew=/^[$A-Za-z_][$A-Za-z0-9_]*$/,tw=new Set(["break","case","catch","class","const","continue","debugger","default","delete","do","else","enum","export","extends","false","finally","for","function","if","implements","import","in","instanceof","interface","let","new","null","package","private","protected","public","return","static","super","switch","this","throw","true","try","typeof","var","void","while","with","yield","arguments","eval"]);function io(){try{return window.G7Core?.devTools}catch{return}}class gd extends Error{constructor(e,r,a){super(e),this.path=r,this.context=a,this.name="DataBindingError"}}const na=class na{constructor(e){$(this,"cache",new Map);$(this,"expressionFnCache",new Map);$(this,"renderCycleCache",new Map);$(this,"currentRenderCycleId",0);$(this,"defaultOptions",{defaultValue:void 0,nullSafe:!0,detectCircular:!0,maxDepth:10});e&&(this.defaultOptions={...this.defaultOptions,...e})}startRenderCycle(){this.currentRenderCycleId++,this.renderCycleCache.clear()}isRenderCycleCacheActive(){return this.currentRenderCycleId>0}getFromRenderCycleCache(e){if(this.isRenderCycleCacheActive())return this.renderCycleCache.get(e)}saveToRenderCycleCache(e,r){this.isRenderCycleCacheActive()&&this.renderCycleCache.set(e,r)}resolveBindings(e,r,a,i){const l={...this.defaultOptions,...a},c=io(),d=r._computed&&!r.$computed?{...r,$computed:r._computed}:r,f=(w,S)=>{const v=S.trim();let A=!1,x=v;if(v.startsWith(nr)&&(A=!0,x=v.slice(nr.length)),Gn(x))try{const B=this.evaluatePipeExpression(x,d,l,{...i,method:"resolveBindings",displayExpression:`{{${v}}}`}),K=this.formatValue(B);return A?ao(K):K}catch(B){return Da.error("Pipe expression evaluation failed:",x,B),w}if(no(x)){const B=c?.isEnabled()?performance.now():0;try{let K,fe=!1;if(l.skipCache)K=this.evaluateExpression(x,d);else{const ke=`expr:${x}`,Ue=this.getFromRenderCycleCache(ke);Ue!==void 0?(K=Ue,fe=!0):(K=this.evaluateExpression(x,d),this.saveToRenderCycleCache(ke,K))}if(c?.isEnabled()){const ke=performance.now()-B;c.trackExpressionEval({expression:`{{${v}}}`,result:this.sanitizeResultForTracking(K),resultType:this.getResultType(K),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:fe,duration:ke,method:"resolveBindings",skipCache:l.skipCache})}const Ce=this.formatValue(K);return A?ao(Ce):Ce}catch(K){return Da.error("Expression evaluation failed:",x,K),w}}if(l.skipCache){const B=c?.isEnabled()?performance.now():0,K=this.resolvePath(x,d,l);if(c?.isEnabled()){const Ce=performance.now()-B;c.trackExpressionEval({expression:`{{${v}}}`,result:this.sanitizeResultForTracking(K),resultType:this.getResultType(K),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:!1,duration:Ce,method:"resolveBindings",skipCache:!0})}const fe=this.formatValue(K);return A?ao(fe):fe}const M=x.startsWith("_global")||x.startsWith("_local")||x.startsWith("_isolated")||x.startsWith("$parent"),O=c?.isEnabled()?performance.now():0;let L,q=!1;if(M){const B=this.getFromRenderCycleCache(x);B!==void 0?(L=B,q=!0):(L=this.resolvePath(x,d,l),this.saveToRenderCycleCache(x,L))}else{const B=this.getFromCache(x);B!==void 0?(L=B,q=!0):(L=this.resolvePath(x,d,l),this.saveToCache(x,L))}if(c?.isEnabled()){const B=performance.now()-O;c.trackExpressionEval({expression:`{{${v}}}`,result:this.sanitizeResultForTracking(L),resultType:this.getResultType(L),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:q,duration:B,method:"resolveBindings",skipCache:l.skipCache})}const G=this.formatValue(L);return A?ao(G):G},g=ZS(e);if(g.length===0)return e;let m="",y=0;for(const w of g)m+=e.slice(y,w.start),m+=f(e.slice(w.start,w.end),w.expr),y=w.end;return m+e.slice(y)}evaluatePipeExpression(e,r,a,i){const l={...this.defaultOptions,...a},c=io(),d=c?.isEnabled()?performance.now():0,f=r._computed&&!r.$computed?{...r,$computed:r._computed}:r,[g,m]=JS(e);let y,w=!1;const S=no(g),v=g.startsWith("_global")||g.startsWith("_local")||g.startsWith("_isolated")||g.startsWith("$parent");if(l.skipCache)S?y=this.evaluateExpression(g,f):y=this.resolvePath(g,f,l);else if(S){const x=this.getFromRenderCycleCache(`expr:${g}`);x!==void 0?(y=x,w=!0):(y=this.evaluateExpression(g,f),this.saveToRenderCycleCache(`expr:${g}`,y))}else if(v){const x=this.getFromRenderCycleCache(g);x!==void 0?(y=x,w=!0):(y=this.resolvePath(g,f,l),this.saveToRenderCycleCache(g,y))}else{const x=this.getFromCache(g);x!==void 0?(y=x,w=!0):(y=this.resolvePath(g,f,l),this.saveToCache(g,y))}const A=QS(y,m);if(c?.isEnabled()){const x=performance.now()-d;c.trackExpressionEval({expression:i?.displayExpression??`{{${e}}}`,result:this.sanitizeResultForTracking(A),resultType:this.getResultType(A),componentId:i?.componentId,componentName:i?.componentName,propName:i?.propName,fromCache:w,duration:x,method:i?.method??"evaluatePipeExpression",skipCache:l.skipCache})}return A}resolve(e,r,a,i){const l={...this.defaultOptions,...a},c=io(),d=c?.isEnabled()?performance.now():0;if(l.skipCache){const y=this.resolvePath(e,r,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 g=!1;if(f){const y=this.getFromRenderCycleCache(e);if(y!==void 0)return g=!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 g=!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,r,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:g,duration:performance.now()-d,method:"resolve",skipCache:l.skipCache}),m}resolvePath(e,r,a,i=0,l=new WeakSet){if(typeof e!="string"||e.trim()===""){Da.warn("resolvePath: 빈 경로가 전달되었습니다 — undefined 로 해석합니다.");return}if(a.maxDepth&&i>a.maxDepth){if(a.detectCircular)throw new gd(`Maximum depth exceeded (${a.maxDepth}). Possible circular reference.`,e,r);return a.defaultValue}const c=this.parsePath(e);let d=r;for(let f=0;fna.CACHE_EXPIRY){this.cache.delete(e),a?.isEnabled()&&a.recordCacheMiss();return}return a?.isEnabled()&&a.recordCacheHit(),r.value}saveToCache(e,r){this.cache.set(e,{value:r,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,r,a){if(this.isSwitchExpression(e)){const d=e;return this.resolveSwitch(d,r,a)}if(this.isActionDefinition(e))return{...e};if("iteration"in e)return{...e};const i={},c=[...["cellChildren","expandChildren","expandContext","render"],...a?.skipBindingKeys||[]];for(const[d,f]of Object.entries(e)){if(c.includes(d)){i[d]=f;continue}try{this.resolveObjectEntry(i,d,f,r,a)}catch(g){Da.warn(`resolveObject: 값 해석 실패 (key: ${d}):`,g),i[d]=void 0}}return i}resolveObjectEntry(e,r,a,i,l){if(typeof a=="string"){const c=Ta(a);if(c!==null){const d=c.trim();let f=!1,g=d;d.startsWith(nr)&&(f=!0,g=d.slice(nr.length));let m;switch(rp(g)){case"empty":Da.warn(`resolveObject: 빈 바인딩 \`{{}}\` (key: ${r}) — undefined 로 해석합니다.`),m=void 0;break;case"literal":m=dd.get(g);break;case"pipe":m=this.evaluatePipeExpression(g,i,l);break;case"expression":m=this.evaluateExpression(g,i,l);break;default:m=this.resolve(g,i,l)}e[r]=f&&m!=null?Ji(m):m}else e[r]=this.resolveBindings(a,i,l)}else Array.isArray(a)?e[r]=a.map(c=>typeof c=="string"?this.resolveBindings(c,i,l):typeof c=="object"&&c!==null?this.resolveObject(c,i,l):c):a&&typeof a=="object"?e[r]=this.resolveObject(a,i,l):e[r]=a}clearCache(){this.cache.clear(),this.expressionFnCache.clear()}invalidateCacheByKeys(e){for(const r of this.cache.keys())for(const a of e)if(r===a||r.startsWith(`${a}.`)||r.startsWith(`${a}[`)){this.cache.delete(r);break}}pruneCache(){const e=Date.now();for(const[r,a]of this.cache.entries())e-a.timestamp>na.CACHE_EXPIRY&&this.cache.delete(r)}getCacheStats(){const e=Date.now();let r=0;for(const a of this.cache.values())e-a.timestamp>na.CACHE_EXPIRY&&r++;return{size:this.cache.size,expired:r}}evaluateExpression(e,r,a){const i=io(),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={...r};for(const L of d)L in f||(f[L]=void 0);r._computed&&!f.$computed&&(f.$computed=r._computed);let g=r.$templateId,m=r.$locale;if(typeof window<"u"&&(!g||!m)){const L=window.__templateApp?.getConfig?.();g??(g=L?.templateId),m??(m=L?.locale)}const y=m||"ko";f.$localized=(L,q)=>{if(L==null&&!q)return"";if(typeof L=="string")return L;if(L&&typeof L=="object"&&L[y])return L[y];if(q&&typeof q=="string"){const G=f.$t?f.$t(q):q;if(G&&G!==q)return G}return L&&typeof L=="object"?L.ko||L.en||Object.values(L)[0]||"":L==null?"":String(L)};const w=typeof window<"u"?window.G7Core:void 0;f.$uuid=()=>w?.uuid?w.uuid():typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,L=>{const q=Math.random()*16|0;return(L==="x"?q:q&3|8).toString(16)});const S={templateId:g||"",locale:y};f.$t=L=>{if(!L||typeof L!="string")return"";try{return gi.getInstance().translate(L,S)}catch(q){return Da.warn("$t() translation failed for key:",L,q),L}},f.$get=(L,q,G=void 0)=>{if(L==null)return G;const B=Array.isArray(q)?q:[q];if(B.length===0)return L;let K=L;for(const fe of B){if(K==null||fe==null)return G;K=K[fe]}return K??G};const v=[],A=[];for(const[L,q]of Object.entries(f))!ew.test(L)||tw.has(L)||(v.push(L),A.push(q));const x=`${c}|${v.join(",")}`;let R=this.expressionFnCache.get(x);const M=!!R;R||(R=new Function(...v,`return (${c});`),this.expressionFnCache.set(x,R));const O=R(...A);if(i?.isEnabled()){const L=performance.now()-l;i.trackExpressionEval({expression:e,result:this.sanitizeResultForTracking(O),resultType:this.getResultType(O),componentId:a?.componentId,componentName:a?.componentName,propName:a?.propName,fromCache:M,duration:L,method:"evaluateExpression",skipCache:a?.skipCache})}return O}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 r=Object.keys(e);return r.length>20?`{Object(${r.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,(r,a,i,l)=>`$t('${l}')`),e.replace(/(?(r.push(l),`__STRING_LITERAL_${r.length-1}__`));const i=[];return a=a.replace(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*(?:\|[^'"\s,)]+)?/g,l=>(i.push(l),`__TRANSLATION_TOKEN_${i.length-1}__`)),a=a.replace(/([a-zA-Z_$][a-zA-Z0-9_$]*)\.(?!\?)/g,"$1?."),a=a.replace(/__TRANSLATION_TOKEN_(\d+)__/g,(l,c)=>i[parseInt(c,10)]),a=a.replace(/__STRING_LITERAL_(\d+)__/g,(l,c)=>r[parseInt(c,10)]),a}extractVariablesFromExpression(e){const r=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"]),a=/(?{r!==null&&clearTimeout(r),r=setTimeout(()=>{o(...a)},e)})}class rw{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=nw(()=>{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(Fl.has(e))return Fl.get(e)??null;let r=null;if(Vl[e])r={...Vl[e]};else{const a=e.match(/^(-?\d*)-(-?\d*)$/);if(a){const[,i,l]=a,c=i===""?0:parseInt(i,10),d=l===""?1/0:parseInt(l,10);!isNaN(c)&&!isNaN(d)&&c<=d&&(r={min:c,max:d})}}return Fl.set(e,r),r}getMatchingKey(e,r){const a=[];for(const i of Object.keys(e)){const l=this.parseRange(i);l&&r>=l.min&&r<=l.max&&a.push({key:i,range:l,isPreset:!!Vl[i]})}return a.length===0?null:(a.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}),a[0].key)}matches(e){const r=this.parseRange(e);return r?this.currentWidth>=r.min&&this.currentWidth<=r.max:!1}clearSubscribers(){this.subscribers.clear()}destroy(){this.debouncedHandler&&typeof window<"u"&&window.removeEventListener("resize",this.debouncedHandler),this.clearSubscribers(),Fl.clear()}_setWidthForTesting(e){this.currentWidth=e,this.notifySubscribers()}}const mi=new rw,so=ut("ConditionEvaluator");function aw(o,e,r,a){return fd(ap(o),e,r,{skipCache:!0,onEmpty:()=>{so.warn(`${a}: 빈 바인딩 \`{{}}\` — undefined 로 해석합니다.`)}})}function ip(o,e,r){if(!o)return!0;try{const a=Ta(o);let i;if(a!==null?i=aw(a,e,r,"evaluateStringCondition"):i=r.resolveBindings(o,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(a){return so.warn(`evaluateStringCondition: 조건 평가 실패: ${o}`,a),!1}}function Kl(o,e,r){if(typeof o=="string")return ip(o,e,r);if("and"in o){if(!Array.isArray(o.and)||o.and.length===0)return so.warn("evaluateConditionExpression: AND 그룹이 비어있습니다"),!0;for(const a of o.and)if(!Kl(a,e,r))return!1;return!0}if("or"in o){if(!Array.isArray(o.or)||o.or.length===0)return so.warn("evaluateConditionExpression: OR 그룹이 비어있습니다"),!1;for(const a of o.or)if(Kl(a,e,r))return!0;return!1}return so.warn("evaluateConditionExpression: 알 수 없는 조건 형식",o),!1}function sp(o,e,r){if(!Array.isArray(o)||o.length===0)return{matched:!1,branchIndex:-1};for(let a=0;a{rr.warn(`evaluateIfCondition: 빈 바인딩 \`{{}}\` (컴포넌트: ${a||"unknown"}) — undefined 로 해석합니다.`)}}):l=r.resolveBindings(o,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 rr.warn(`evaluateIfCondition: 조건 평가 실패 (컴포넌트: ${a||"unknown"}):`,i),!1}}function Qi(o,e,r,a){if(o.if!==void 0)return up(o.if,e,r,a);if(o.condition!==void 0)return up(o.condition,e,r,a);if(o.conditions===void 0)return!0;const i=o.conditions;try{return iw(i)?Kl(i,e,r):sw(i)?sp(i,e,r).matched:(rr.warn(`evaluateRenderCondition: 알 수 없는 conditions 형식 (컴포넌트: ${a||"unknown"})`),!0)}catch(l){return rr.warn(`evaluateRenderCondition: conditions 평가 실패 (컴포넌트: ${a||"unknown"}):`,l),!1}}function dp(o){if(!o.responsive)return o;const e=mi.getWidth(),r=mi.getMatchingKey(o.responsive,e);if(!r)return o;const a=o.responsive[r];return{...o,props:{...o.props,...a.props},children:a.children??o.children,text:a.text??o.text,if:a.if??o.if,iteration:a.iteration??o.iteration}}function oo(o,e,r,a,i){if(!o||o.length===0)return[];const l=i?.bindingEngine??new _n,c=i?.translationEngine??gi.getInstance(),d=i?.translationContext??{templateId:"",locale:"ko"},f=lw(e,i?.componentContext),g=(S,v)=>{if(typeof S=="string")return ql(S)||Gl(S)||!/\$t:[a-zA-Z0-9._-]+/.test(S)?S:c.resolveTranslations(S,d,v);if(Array.isArray(S))return S.map(A=>g(A,v));if(S&&typeof S=="object"){const A={};for(const[x,R]of Object.entries(S))A[x]=g(R,v);return A}return S},m=(S,v)=>{if(typeof S=="string"){if(ql(S))return hd(S);if(Gl(S)){const x=[],R=S.replace(new RegExp(`${ro}([^${pi}]*)${pi}`,"g"),(O,L)=>(x.push(L),`${ka}${x.length-1}${ka}`));let M=R;return/\$t:[a-zA-Z0-9._-]+/.test(R)&&(M=c.resolveTranslations(R,d,v)),M.replace(new RegExp(`${ka}(\\d+)${ka}`,"g"),(O,L)=>x[parseInt(L)])}if(S.startsWith("$t:defer:")){const x="$t:"+S.slice(9);return c.resolveTranslations(x,d,v)}if(S.startsWith("$t:"))return c.resolveTranslations(S,d,v);if(/\$t:[a-zA-Z0-9._-]+/.test(S)){const x=S.trim();if(!(x.startsWith("{")&&x.endsWith("}")||x.startsWith("[")&&x.endsWith("]"))&&!S.includes("{{"))return c.resolveTranslations(S,d,v)}const A=cp(S);if(A!==null){let x=!1,R=A;A.startsWith(nr)&&(x=!0,R=A.slice(nr.length));let M=!1,O=fd(R,v,l,{skipCache:!0,onError:L=>{rr.warn("renderItemChildren: 표현식 평가 실패:",L),M=!0},onEmpty:()=>{rr.warn("renderItemChildren: 빈 바인딩 `{{}}` 은 해석하지 않습니다.")}});return M?void 0:(x||(O=g(O,v)),x&&O!=null?Ji(O):O)}if(S.includes("{{")){const x=l.resolveBindings(S,v,{skipCache:!0});return typeof x=="string"&&/\$t:[a-zA-Z0-9._-]+/.test(x)?c.resolveTranslations(x,d,v):x}return S}if(Array.isArray(S))return S.map(A=>m(A,v));if(S&&typeof S=="object"){if(l.isSwitchExpression(S))return l.resolveSwitch(S,v,{skipCache:!0});if(l.isActionDefinition(S))return{...S};const A={};for(const[x,R]of Object.entries(S))A[x]=m(R,v);return A}return S},y=(S,v)=>{if(!S)return{};const A={};for(const[x,R]of Object.entries(S))A[x]=m(R,v);return A},w=(S,v,A)=>{const x=dp(S),R=x.iteration;if(!R)return[];const M=md(R.source,A,l);if(!Array.isArray(M))return rr.warn(`renderItemChildren: iteration.source가 배열이 아닙니다: ${R.source}`),[];const O=op();if(O?.isEnabled()){const q=`${v}-iteration`;O.trackIteration(q,R.source,R.item_var,R.index_var,M.length)}const L=r[x.name];return L?M.flatMap((q,G)=>{const B={...A,[R.item_var]:q,[`${R.item_var}_index`]:G,...R.index_var?{[R.index_var]:G}:{}},K=Qi({if:x.if,condition:x.condition,conditions:x.conditions},B,l,x.id);if(x.if&&O?.isEnabled()){const wt=`${v}-iter-${G}-if`;O.trackIfCondition(wt,x.if,K,x.name)}if(!K)return[];const fe=x.id?String(Ra(m(x.id,B))):void 0,Ce=`${v}-iter-${G}`,ke=i?.getRemountKey?i.getRemountKey(fe,Ce):Ce,Ue=y(x.props,B),Pe=yd(Ue,x.actions,B,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let qe=null;return x.text!==void 0?qe=m(x.text,B):x.children&&x.children.length>0&&(qe=oo(x.children,B,r,ke,i)),O?.isEnabled()&&O.trackRender(x.name),[We.createElement(L,{key:ke,...Ra(Pe)},Ra(qe))]}):(rr.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${x.name}`),[])};return o.flatMap((S,v)=>{const A=dp(S),x=A.id?String(Ra(m(A.id,f))):void 0,R=a?`${a}-${x||v}`:x||`child-${v}`,M=i?.getRemountKey?i.getRemountKey(x,R):R;if(A.iteration)return w(A,M,f);const O=Qi({if:A.if,condition:A.condition,conditions:A.conditions},f,l,A.id),L=op();if(A.if&&L?.isEnabled()){const fe=`${M}-if`;L.trackIfCondition(fe,A.if,O,A.name)}if(!O)return[];const q=r[A.name];if(!q)return rr.warn(`renderItemChildren: 컴포넌트를 찾을 수 없습니다: ${A.name}`),[];const G=y(A.props,f),B=yd(G,A.actions,f,{actionDispatcher:i?.actionDispatcher,componentContext:i?.componentContext});let K=null;return A.text!==void 0?K=m(A.text,f):A.children&&A.children.length>0&&(K=oo(A.children,f,r,M,i)),L?.isEnabled()&&L.trackRender(A.name),[We.createElement(q,{key:M,...Ra(B)},Ra(K))]})}function Zi(o,e,r,a){let i,l;return r instanceof _n?(i=r,l=a):(i=lp,l=r),i.resolveBindings(o,e,l)}function cw(o,e,r,a){const i=r??lp,l={skipCache:!0,...a};let c;try{c=i.resolveBindings(o.key,e,{skipCache:l.skipCache})?.toString()?.trim()??""}catch(g){rr.warn("resolveClassMap: key 평가 실패:",o.key,g),c=""}let d="";c&&o.variants&&c in o.variants?d=o.variants[c]:o.default&&(d=o.default);const f=[];return o.base?.trim()&&f.push(o.base.trim()),d?.trim()&&f.push(d.trim()),f.join(" ")}function fp(o,e){return function(){return o.apply(e,arguments)}}const{toString:uw}=Object.prototype,{getPrototypeOf:bd}=Object,{iterator:Wl,toStringTag:hp}=Symbol,Yl=(o=>e=>{const r=uw.call(e);return o[r]||(o[r]=r.slice(8,-1).toLowerCase())})(Object.create(null)),yr=o=>(o=o.toLowerCase(),e=>Yl(e)===o),Xl=o=>e=>typeof e===o,{isArray:es}=Array,ts=Xl("undefined");function lo(o){return o!==null&&!ts(o)&&o.constructor!==null&&!ts(o.constructor)&&kn(o.constructor.isBuffer)&&o.constructor.isBuffer(o)}const gp=yr("ArrayBuffer");function dw(o){let e;return typeof ArrayBuffer<"u"&&ArrayBuffer.isView?e=ArrayBuffer.isView(o):e=o&&o.buffer&&gp(o.buffer),e}const fw=Xl("string"),kn=Xl("function"),pp=Xl("number"),co=o=>o!==null&&typeof o=="object",hw=o=>o===!0||o===!1,Jl=o=>{if(Yl(o)!=="object")return!1;const e=bd(o);return(e===null||e===Object.prototype||Object.getPrototypeOf(e)===null)&&!(hp in o)&&!(Wl in o)},gw=o=>{if(!co(o)||lo(o))return!1;try{return Object.keys(o).length===0&&Object.getPrototypeOf(o)===Object.prototype}catch{return!1}},pw=yr("Date"),mw=yr("File"),yw=yr("Blob"),bw=yr("FileList"),vw=o=>co(o)&&kn(o.pipe),Sw=o=>{let e;return o&&(typeof FormData=="function"&&o instanceof FormData||kn(o.append)&&((e=Yl(o))==="formdata"||e==="object"&&kn(o.toString)&&o.toString()==="[object FormData]"))},ww=yr("URLSearchParams"),[Cw,Ew,_w,Aw]=["ReadableStream","Request","Response","Headers"].map(yr),xw=o=>o.trim?o.trim():o.replace(/^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g,"");function uo(o,e,{allOwnKeys:r=!1}={}){if(o===null||typeof o>"u")return;let a,i;if(typeof o!="object"&&(o=[o]),es(o))for(a=0,i=o.length;a0;)if(i=r[a],e===i.toLowerCase())return i;return null}const yi=typeof globalThis<"u"?globalThis:typeof self<"u"?self:typeof window<"u"?window:global,yp=o=>!ts(o)&&o!==yi;function vd(){const{caseless:o,skipUndefined:e}=yp(this)&&this||{},r={},a=(i,l)=>{const c=o&&mp(r,l)||l;Jl(r[c])&&Jl(i)?r[c]=vd(r[c],i):Jl(i)?r[c]=vd({},i):es(i)?r[c]=i.slice():(!e||!ts(i))&&(r[c]=i)};for(let i=0,l=arguments.length;i(uo(e,(i,l)=>{r&&kn(i)?o[l]=fp(i,r):o[l]=i},{allOwnKeys:a}),o),kw=o=>(o.charCodeAt(0)===65279&&(o=o.slice(1)),o),Rw=(o,e,r,a)=>{o.prototype=Object.create(e.prototype,a),o.prototype.constructor=o,Object.defineProperty(o,"super",{value:e.prototype}),r&&Object.assign(o.prototype,r)},Dw=(o,e,r,a)=>{let i,l,c;const d={};if(e=e||{},o==null)return e;do{for(i=Object.getOwnPropertyNames(o),l=i.length;l-- >0;)c=i[l],(!a||a(c,o,e))&&!d[c]&&(e[c]=o[c],d[c]=!0);o=r!==!1&&bd(o)}while(o&&(!r||r(o,e))&&o!==Object.prototype);return e},Ow=(o,e,r)=>{o=String(o),(r===void 0||r>o.length)&&(r=o.length),r-=e.length;const a=o.indexOf(e,r);return a!==-1&&a===r},Lw=o=>{if(!o)return null;if(es(o))return o;let e=o.length;if(!pp(e))return null;const r=new Array(e);for(;e-- >0;)r[e]=o[e];return r},Mw=(o=>e=>o&&e instanceof o)(typeof Uint8Array<"u"&&bd(Uint8Array)),$w=(o,e)=>{const a=(o&&o[Wl]).call(o);let i;for(;(i=a.next())&&!i.done;){const l=i.value;e.call(o,l[0],l[1])}},Nw=(o,e)=>{let r;const a=[];for(;(r=o.exec(e))!==null;)a.push(r);return a},Iw=yr("HTMLFormElement"),Hw=o=>o.toLowerCase().replace(/[-_\s]([a-z\d])(\w*)/g,function(r,a,i){return a.toUpperCase()+i}),bp=(({hasOwnProperty:o})=>(e,r)=>o.call(e,r))(Object.prototype),jw=yr("RegExp"),vp=(o,e)=>{const r=Object.getOwnPropertyDescriptors(o),a={};uo(r,(i,l)=>{let c;(c=e(i,l,o))!==!1&&(a[l]=c||i)}),Object.defineProperties(o,a)},zw=o=>{vp(o,(e,r)=>{if(kn(o)&&["arguments","caller","callee"].indexOf(r)!==-1)return!1;const a=o[r];if(kn(a)){if(e.enumerable=!1,"writable"in e){e.writable=!1;return}e.set||(e.set=()=>{throw Error("Can not rewrite read-only method '"+r+"'")})}})},Uw=(o,e)=>{const r={},a=i=>{i.forEach(l=>{r[l]=!0})};return es(o)?a(o):a(String(o).split(e)),r},Bw=()=>{},Pw=(o,e)=>o!=null&&Number.isFinite(o=+o)?o:e;function qw(o){return!!(o&&kn(o.append)&&o[hp]==="FormData"&&o[Wl])}const Gw=o=>{const e=new Array(10),r=(a,i)=>{if(co(a)){if(e.indexOf(a)>=0)return;if(lo(a))return a;if(!("toJSON"in a)){e[i]=a;const l=es(a)?[]:{};return uo(a,(c,d)=>{const f=r(c,i+1);!ts(f)&&(l[d]=f)}),e[i]=void 0,l}}return a};return r(o,0)},Vw=yr("AsyncFunction"),Fw=o=>o&&(co(o)||kn(o))&&kn(o.then)&&kn(o.catch),Sp=((o,e)=>o?setImmediate:e?((r,a)=>(yi.addEventListener("message",({source:i,data:l})=>{i===yi&&l===r&&a.length&&a.shift()()},!1),i=>{a.push(i),yi.postMessage(r,"*")}))(`axios@${Math.random()}`,[]):r=>setTimeout(r))(typeof setImmediate=="function",kn(yi.postMessage)),Kw=typeof queueMicrotask<"u"?queueMicrotask.bind(yi):typeof process<"u"&&process.nextTick||Sp,ee={isArray:es,isArrayBuffer:gp,isBuffer:lo,isFormData:Sw,isArrayBufferView:dw,isString:fw,isNumber:pp,isBoolean:hw,isObject:co,isPlainObject:Jl,isEmptyObject:gw,isReadableStream:Cw,isRequest:Ew,isResponse:_w,isHeaders:Aw,isUndefined:ts,isDate:pw,isFile:mw,isBlob:yw,isRegExp:jw,isFunction:kn,isStream:vw,isURLSearchParams:ww,isTypedArray:Mw,isFileList:bw,forEach:uo,merge:vd,extend:Tw,trim:xw,stripBOM:kw,inherits:Rw,toFlatObject:Dw,kindOf:Yl,kindOfTest:yr,endsWith:Ow,toArray:Lw,forEachEntry:$w,matchAll:Nw,isHTMLForm:Iw,hasOwnProperty:bp,hasOwnProp:bp,reduceDescriptors:vp,freezeMethods:zw,toObjectSet:Uw,toCamelCase:Hw,noop:Bw,toFiniteNumber:Pw,findKey:mp,global:yi,isContextDefined:yp,isSpecCompliantForm:qw,toJSONObject:Gw,isAsyncFn:Vw,isThenable:Fw,setImmediate:Sp,asap:Kw,isIterable:o=>o!=null&&kn(o[Wl])};function Ye(o,e,r,a,i){Error.call(this),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):this.stack=new Error().stack,this.message=o,this.name="AxiosError",e&&(this.code=e),r&&(this.config=r),a&&(this.request=a),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 wp=Ye.prototype,Cp={};["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(o=>{Cp[o]={value:o}}),Object.defineProperties(Ye,Cp),Object.defineProperty(wp,"isAxiosError",{value:!0}),Ye.from=(o,e,r,a,i,l)=>{const c=Object.create(wp);ee.toFlatObject(o,c,function(m){return m!==Error.prototype},g=>g!=="isAxiosError");const d=o&&o.message?o.message:"Error",f=e==null&&o?o.code:e;return Ye.call(c,d,f,r,a,i),o&&c.cause==null&&Object.defineProperty(c,"cause",{value:o,configurable:!0}),c.name=o&&o.name||"Error",l&&Object.assign(c,l),c};const Ww=null;function Sd(o){return ee.isPlainObject(o)||ee.isArray(o)}function Ep(o){return ee.endsWith(o,"[]")?o.slice(0,-2):o}function _p(o,e,r){return o?o.concat(e).map(function(i,l){return i=Ep(i),!r&&l?"["+i+"]":i}).join(r?".":""):e}function Yw(o){return ee.isArray(o)&&!o.some(Sd)}const Xw=ee.toFlatObject(ee,{},null,function(e){return/^is[A-Z]/.test(e)});function Ql(o,e,r){if(!ee.isObject(o))throw new TypeError("target must be an object");e=e||new FormData,r=ee.toFlatObject(r,{metaTokens:!0,dots:!1,indexes:!1},!1,function(A,x){return!ee.isUndefined(x[A])});const a=r.metaTokens,i=r.visitor||m,l=r.dots,c=r.indexes,f=(r.Blob||typeof Blob<"u"&&Blob)&&ee.isSpecCompliantForm(e);if(!ee.isFunction(i))throw new TypeError("visitor must be a function");function g(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,A,x){let R=v;if(v&&!x&&typeof v=="object"){if(ee.endsWith(A,"{}"))A=a?A:A.slice(0,-2),v=JSON.stringify(v);else if(ee.isArray(v)&&Yw(v)||(ee.isFileList(v)||ee.endsWith(A,"[]"))&&(R=ee.toArray(v)))return A=Ep(A),R.forEach(function(O,L){!(ee.isUndefined(O)||O===null)&&e.append(c===!0?_p([A],L,l):c===null?A:A+"[]",g(O))}),!1}return Sd(v)?!0:(e.append(_p(x,A,l),g(v)),!1)}const y=[],w=Object.assign(Xw,{defaultVisitor:m,convertValue:g,isVisitable:Sd});function S(v,A){if(!ee.isUndefined(v)){if(y.indexOf(v)!==-1)throw Error("Circular reference detected in "+A.join("."));y.push(v),ee.forEach(v,function(R,M){(!(ee.isUndefined(R)||R===null)&&i.call(e,R,ee.isString(M)?M.trim():M,A,w))===!0&&S(R,A?A.concat(M):[M])}),y.pop()}}if(!ee.isObject(o))throw new TypeError("data must be an object");return S(o),e}function Ap(o){const e={"!":"%21","'":"%27","(":"%28",")":"%29","~":"%7E","%20":"+","%00":"\0"};return encodeURIComponent(o).replace(/[!'()~]|%20|%00/g,function(a){return e[a]})}function wd(o,e){this._pairs=[],o&&Ql(o,this,e)}const xp=wd.prototype;xp.append=function(e,r){this._pairs.push([e,r])},xp.toString=function(e){const r=e?function(a){return e.call(this,a,Ap)}:Ap;return this._pairs.map(function(i){return r(i[0])+"="+r(i[1])},"").join("&")};function Jw(o){return encodeURIComponent(o).replace(/%3A/gi,":").replace(/%24/g,"$").replace(/%2C/gi,",").replace(/%20/g,"+")}function Tp(o,e,r){if(!e)return o;const a=r&&r.encode||Jw;ee.isFunction(r)&&(r={serialize:r});const i=r&&r.serialize;let l;if(i?l=i(e,r):l=ee.isURLSearchParams(e)?e.toString():new wd(e,r).toString(a),l){const c=o.indexOf("#");c!==-1&&(o=o.slice(0,c)),o+=(o.indexOf("?")===-1?"?":"&")+l}return o}class kp{constructor(){this.handlers=[]}use(e,r,a){return this.handlers.push({fulfilled:e,rejected:r,synchronous:a?a.synchronous:!1,runWhen:a?a.runWhen:null}),this.handlers.length-1}eject(e){this.handlers[e]&&(this.handlers[e]=null)}clear(){this.handlers&&(this.handlers=[])}forEach(e){ee.forEach(this.handlers,function(a){a!==null&&e(a)})}}const Rp={silentJSONParsing:!0,forcedJSONParsing:!0,clarifyTimeoutError:!1},Qw={isBrowser:!0,classes:{URLSearchParams:typeof URLSearchParams<"u"?URLSearchParams:wd,FormData:typeof FormData<"u"?FormData:null,Blob:typeof Blob<"u"?Blob:null},protocols:["http","https","file","blob","url","data"]},Cd=typeof window<"u"&&typeof document<"u",Ed=typeof navigator=="object"&&navigator||void 0,Zw=Cd&&(!Ed||["ReactNative","NativeScript","NS"].indexOf(Ed.product)<0),e0=typeof WorkerGlobalScope<"u"&&self instanceof WorkerGlobalScope&&typeof self.importScripts=="function",t0=Cd&&window.location.href||"http://localhost",Sn={...Object.freeze(Object.defineProperty({__proto__:null,hasBrowserEnv:Cd,hasStandardBrowserEnv:Zw,hasStandardBrowserWebWorkerEnv:e0,navigator:Ed,origin:t0},Symbol.toStringTag,{value:"Module"})),...Qw};function n0(o,e){return Ql(o,new Sn.classes.URLSearchParams,{visitor:function(r,a,i,l){return Sn.isNode&&ee.isBuffer(r)?(this.append(a,r.toString("base64")),!1):l.defaultVisitor.apply(this,arguments)},...e})}function r0(o){return ee.matchAll(/\w+|\[(\w*)]/g,o).map(e=>e[0]==="[]"?"":e[1]||e[0])}function a0(o){const e={},r=Object.keys(o);let a;const i=r.length;let l;for(a=0;a=r.length;return c=!c&&ee.isArray(i)?i.length:c,f?(ee.hasOwnProp(i,c)?i[c]=[i[c],a]:i[c]=a,!d):((!i[c]||!ee.isObject(i[c]))&&(i[c]=[]),e(r,a,i[c],l)&&ee.isArray(i[c])&&(i[c]=a0(i[c])),!d)}if(ee.isFormData(o)&&ee.isFunction(o.entries)){const r={};return ee.forEachEntry(o,(a,i)=>{e(r0(a),i,r,0)}),r}return null}function i0(o,e,r){if(ee.isString(o))try{return(e||JSON.parse)(o),ee.trim(o)}catch(a){if(a.name!=="SyntaxError")throw a}return(r||JSON.stringify)(o)}const fo={transitional:Rp,adapter:["xhr","http","fetch"],transformRequest:[function(e,r){const a=r.getContentType()||"",i=a.indexOf("application/json")>-1,l=ee.isObject(e);if(l&&ee.isHTMLForm(e)&&(e=new FormData(e)),ee.isFormData(e))return i?JSON.stringify(Dp(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 r.setContentType("application/x-www-form-urlencoded;charset=utf-8",!1),e.toString();let d;if(l){if(a.indexOf("application/x-www-form-urlencoded")>-1)return n0(e,this.formSerializer).toString();if((d=ee.isFileList(e))||a.indexOf("multipart/form-data")>-1){const f=this.env&&this.env.FormData;return Ql(d?{"files[]":e}:e,f&&new f,this.formSerializer)}}return l||i?(r.setContentType("application/json",!1),i0(e)):e}],transformResponse:[function(e){const r=this.transitional||fo.transitional,a=r&&r.forcedJSONParsing,i=this.responseType==="json";if(ee.isResponse(e)||ee.isReadableStream(e))return e;if(e&&ee.isString(e)&&(a&&!this.responseType||i)){const c=!(r&&r.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:Sn.classes.FormData,Blob:Sn.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"],o=>{fo.headers[o]={}});const s0=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"]),o0=o=>{const e={};let r,a,i;return o&&o.split(` +`).forEach(function(c){i=c.indexOf(":"),r=c.substring(0,i).trim().toLowerCase(),a=c.substring(i+1).trim(),!(!r||e[r]&&s0[r])&&(r==="set-cookie"?e[r]?e[r].push(a):e[r]=[a]:e[r]=e[r]?e[r]+", "+a:a)}),e},Op=Symbol("internals");function ho(o){return o&&String(o).trim().toLowerCase()}function Zl(o){return o===!1||o==null?o:ee.isArray(o)?o.map(Zl):String(o)}function l0(o){const e=Object.create(null),r=/([^\s,;=]+)\s*(?:=\s*([^,;]+))?/g;let a;for(;a=r.exec(o);)e[a[1]]=a[2];return e}const c0=o=>/^[-_a-zA-Z0-9^`|~,!#$%&'*+.]+$/.test(o.trim());function _d(o,e,r,a,i){if(ee.isFunction(a))return a.call(this,e,r);if(i&&(e=r),!!ee.isString(e)){if(ee.isString(a))return e.indexOf(a)!==-1;if(ee.isRegExp(a))return a.test(e)}}function u0(o){return o.trim().toLowerCase().replace(/([a-z\d])(\w*)/g,(e,r,a)=>r.toUpperCase()+a)}function d0(o,e){const r=ee.toCamelCase(" "+e);["get","set","has"].forEach(a=>{Object.defineProperty(o,a+r,{value:function(i,l,c){return this[a].call(this,e,i,l,c)},configurable:!0})})}let Rn=class{constructor(e){e&&this.set(e)}set(e,r,a){const i=this;function l(d,f,g){const m=ho(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||g===!0||g===void 0&&i[y]!==!1)&&(i[y||f]=Zl(d))}const c=(d,f)=>ee.forEach(d,(g,m)=>l(g,m,f));if(ee.isPlainObject(e)||e instanceof this.constructor)c(e,r);else if(ee.isString(e)&&(e=e.trim())&&!c0(e))c(o0(e),r);else if(ee.isObject(e)&&ee.isIterable(e)){let d={},f,g;for(const m of e){if(!ee.isArray(m))throw TypeError("Object iterator must return a key-value pair");d[g=m[0]]=(f=d[g])?ee.isArray(f)?[...f,m[1]]:[f,m[1]]:m[1]}c(d,r)}else e!=null&&l(r,e,a);return this}get(e,r){if(e=ho(e),e){const a=ee.findKey(this,e);if(a){const i=this[a];if(!r)return i;if(r===!0)return l0(i);if(ee.isFunction(r))return r.call(this,i,a);if(ee.isRegExp(r))return r.exec(i);throw new TypeError("parser must be boolean|regexp|function")}}}has(e,r){if(e=ho(e),e){const a=ee.findKey(this,e);return!!(a&&this[a]!==void 0&&(!r||_d(this,this[a],a,r)))}return!1}delete(e,r){const a=this;let i=!1;function l(c){if(c=ho(c),c){const d=ee.findKey(a,c);d&&(!r||_d(a,a[d],d,r))&&(delete a[d],i=!0)}}return ee.isArray(e)?e.forEach(l):l(e),i}clear(e){const r=Object.keys(this);let a=r.length,i=!1;for(;a--;){const l=r[a];(!e||_d(this,this[l],l,e,!0))&&(delete this[l],i=!0)}return i}normalize(e){const r=this,a={};return ee.forEach(this,(i,l)=>{const c=ee.findKey(a,l);if(c){r[c]=Zl(i),delete r[l];return}const d=e?u0(l):String(l).trim();d!==l&&delete r[l],r[d]=Zl(i),a[d]=!0}),this}concat(...e){return this.constructor.concat(this,...e)}toJSON(e){const r=Object.create(null);return ee.forEach(this,(a,i)=>{a!=null&&a!==!1&&(r[i]=e&&ee.isArray(a)?a.join(", "):a)}),r}[Symbol.iterator](){return Object.entries(this.toJSON())[Symbol.iterator]()}toString(){return Object.entries(this.toJSON()).map(([e,r])=>e+": "+r).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,...r){const a=new this(e);return r.forEach(i=>a.set(i)),a}static accessor(e){const a=(this[Op]=this[Op]={accessors:{}}).accessors,i=this.prototype;function l(c){const d=ho(c);a[d]||(d0(i,c),a[d]=!0)}return ee.isArray(e)?e.forEach(l):l(e),this}};Rn.accessor(["Content-Type","Content-Length","Accept","Accept-Encoding","User-Agent","Authorization"]),ee.reduceDescriptors(Rn.prototype,({value:o},e)=>{let r=e[0].toUpperCase()+e.slice(1);return{get:()=>o,set(a){this[r]=a}}}),ee.freezeMethods(Rn);function Ad(o,e){const r=this||fo,a=e||r,i=Rn.from(a.headers);let l=a.data;return ee.forEach(o,function(d){l=d.call(r,l,i.normalize(),e?e.status:void 0)}),i.normalize(),l}function Lp(o){return!!(o&&o.__CANCEL__)}function ns(o,e,r){Ye.call(this,o??"canceled",Ye.ERR_CANCELED,e,r),this.name="CanceledError"}ee.inherits(ns,Ye,{__CANCEL__:!0});function Mp(o,e,r){const a=r.config.validateStatus;!r.status||!a||a(r.status)?o(r):e(new Ye("Request failed with status code "+r.status,[Ye.ERR_BAD_REQUEST,Ye.ERR_BAD_RESPONSE][Math.floor(r.status/100)-4],r.config,r.request,r))}function f0(o){const e=/^([-+\w]{1,25})(:?\/\/|:)/.exec(o);return e&&e[1]||""}function h0(o,e){o=o||10;const r=new Array(o),a=new Array(o);let i=0,l=0,c;return e=e!==void 0?e:1e3,function(f){const g=Date.now(),m=a[l];c||(c=g),r[i]=f,a[i]=g;let y=l,w=0;for(;y!==i;)w+=r[y++],y=y%o;if(i=(i+1)%o,i===l&&(l=(l+1)%o),g-c{r=m,i=null,l&&(clearTimeout(l),l=null),o(...g)};return[(...g)=>{const m=Date.now(),y=m-r;y>=a?c(g,m):(i=g,l||(l=setTimeout(()=>{l=null,c(i)},a-y)))},()=>i&&c(i)]}const ec=(o,e,r=3)=>{let a=0;const i=h0(50,250);return g0(l=>{const c=l.loaded,d=l.lengthComputable?l.total:void 0,f=c-a,g=i(f),m=c<=d;a=c;const y={loaded:c,total:d,progress:d?c/d:void 0,bytes:f,rate:g||void 0,estimated:g&&d&&m?(d-c)/g:void 0,event:l,lengthComputable:d!=null,[e?"download":"upload"]:!0};o(y)},r)},$p=(o,e)=>{const r=o!=null;return[a=>e[0]({lengthComputable:r,total:o,loaded:a}),e[1]]},Np=o=>(...e)=>ee.asap(()=>o(...e)),p0=Sn.hasStandardBrowserEnv?((o,e)=>r=>(r=new URL(r,Sn.origin),o.protocol===r.protocol&&o.host===r.host&&(e||o.port===r.port)))(new URL(Sn.origin),Sn.navigator&&/(msie|trident)/i.test(Sn.navigator.userAgent)):()=>!0,m0=Sn.hasStandardBrowserEnv?{write(o,e,r,a,i,l){const c=[o+"="+encodeURIComponent(e)];ee.isNumber(r)&&c.push("expires="+new Date(r).toGMTString()),ee.isString(a)&&c.push("path="+a),ee.isString(i)&&c.push("domain="+i),l===!0&&c.push("secure"),document.cookie=c.join("; ")},read(o){const e=document.cookie.match(new RegExp("(^|;\\s*)("+o+")=([^;]*)"));return e?decodeURIComponent(e[3]):null},remove(o){this.write(o,"",Date.now()-864e5)}}:{write(){},read(){return null},remove(){}};function y0(o){return/^([a-z][a-z\d+\-.]*:)?\/\//i.test(o)}function b0(o,e){return e?o.replace(/\/?\/$/,"")+"/"+e.replace(/^\/+/,""):o}function Ip(o,e,r){let a=!y0(e);return o&&(a||r==!1)?b0(o,e):e}const Hp=o=>o instanceof Rn?{...o}:o;function bi(o,e){e=e||{};const r={};function a(g,m,y,w){return ee.isPlainObject(g)&&ee.isPlainObject(m)?ee.merge.call({caseless:w},g,m):ee.isPlainObject(m)?ee.merge({},m):ee.isArray(m)?m.slice():m}function i(g,m,y,w){if(ee.isUndefined(m)){if(!ee.isUndefined(g))return a(void 0,g,y,w)}else return a(g,m,y,w)}function l(g,m){if(!ee.isUndefined(m))return a(void 0,m)}function c(g,m){if(ee.isUndefined(m)){if(!ee.isUndefined(g))return a(void 0,g)}else return a(void 0,m)}function d(g,m,y){if(y in e)return a(g,m);if(y in o)return a(void 0,g)}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:(g,m,y)=>i(Hp(g),Hp(m),y,!0)};return ee.forEach(Object.keys({...o,...e}),function(m){const y=f[m]||i,w=y(o[m],e[m],m);ee.isUndefined(w)&&y!==d||(r[m]=w)}),r}const jp=o=>{const e=bi({},o);let{data:r,withXSRFToken:a,xsrfHeaderName:i,xsrfCookieName:l,headers:c,auth:d}=e;if(e.headers=c=Rn.from(c),e.url=Tp(Ip(e.baseURL,e.url,e.allowAbsoluteUrls),o.params,o.paramsSerializer),d&&c.set("Authorization","Basic "+btoa((d.username||"")+":"+(d.password?unescape(encodeURIComponent(d.password)):""))),ee.isFormData(r)){if(Sn.hasStandardBrowserEnv||Sn.hasStandardBrowserWebWorkerEnv)c.setContentType(void 0);else if(ee.isFunction(r.getHeaders)){const f=r.getHeaders(),g=["content-type","content-length"];Object.entries(f).forEach(([m,y])=>{g.includes(m.toLowerCase())&&c.set(m,y)})}}if(Sn.hasStandardBrowserEnv&&(a&&ee.isFunction(a)&&(a=a(e)),a||a!==!1&&p0(e.url))){const f=i&&l&&m0.read(l);f&&c.set(i,f)}return e},v0=typeof XMLHttpRequest<"u"&&function(o){return new Promise(function(r,a){const i=jp(o);let l=i.data;const c=Rn.from(i.headers).normalize();let{responseType:d,onUploadProgress:f,onDownloadProgress:g}=i,m,y,w,S,v;function A(){S&&S(),v&&v(),i.cancelToken&&i.cancelToken.unsubscribe(m),i.signal&&i.signal.removeEventListener("abort",m)}let x=new XMLHttpRequest;x.open(i.method.toUpperCase(),i.url,!0),x.timeout=i.timeout;function R(){if(!x)return;const O=Rn.from("getAllResponseHeaders"in x&&x.getAllResponseHeaders()),q={data:!d||d==="text"||d==="json"?x.responseText:x.response,status:x.status,statusText:x.statusText,headers:O,config:o,request:x};Mp(function(B){r(B),A()},function(B){a(B),A()},q),x=null}"onloadend"in x?x.onloadend=R:x.onreadystatechange=function(){!x||x.readyState!==4||x.status===0&&!(x.responseURL&&x.responseURL.indexOf("file:")===0)||setTimeout(R)},x.onabort=function(){x&&(a(new Ye("Request aborted",Ye.ECONNABORTED,o,x)),x=null)},x.onerror=function(L){const q=L&&L.message?L.message:"Network Error",G=new Ye(q,Ye.ERR_NETWORK,o,x);G.event=L||null,a(G),x=null},x.ontimeout=function(){let L=i.timeout?"timeout of "+i.timeout+"ms exceeded":"timeout exceeded";const q=i.transitional||Rp;i.timeoutErrorMessage&&(L=i.timeoutErrorMessage),a(new Ye(L,q.clarifyTimeoutError?Ye.ETIMEDOUT:Ye.ECONNABORTED,o,x)),x=null},l===void 0&&c.setContentType(null),"setRequestHeader"in x&&ee.forEach(c.toJSON(),function(L,q){x.setRequestHeader(q,L)}),ee.isUndefined(i.withCredentials)||(x.withCredentials=!!i.withCredentials),d&&d!=="json"&&(x.responseType=i.responseType),g&&([w,v]=ec(g,!0),x.addEventListener("progress",w)),f&&x.upload&&([y,S]=ec(f),x.upload.addEventListener("progress",y),x.upload.addEventListener("loadend",S)),(i.cancelToken||i.signal)&&(m=O=>{x&&(a(!O||O.type?new ns(null,o,x):O),x.abort(),x=null)},i.cancelToken&&i.cancelToken.subscribe(m),i.signal&&(i.signal.aborted?m():i.signal.addEventListener("abort",m)));const M=f0(i.url);if(M&&Sn.protocols.indexOf(M)===-1){a(new Ye("Unsupported protocol "+M+":",Ye.ERR_BAD_REQUEST,o));return}x.send(l||null)})},S0=(o,e)=>{const{length:r}=o=o?o.filter(Boolean):[];if(e||r){let a=new AbortController,i;const l=function(g){if(!i){i=!0,d();const m=g instanceof Error?g:this.reason;a.abort(m instanceof Ye?m:new ns(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=()=>{o&&(c&&clearTimeout(c),c=null,o.forEach(g=>{g.unsubscribe?g.unsubscribe(l):g.removeEventListener("abort",l)}),o=null)};o.forEach(g=>g.addEventListener("abort",l));const{signal:f}=a;return f.unsubscribe=()=>ee.asap(d),f}},w0=function*(o,e){let r=o.byteLength;if(r{const i=C0(o,e);let l=0,c,d=f=>{c||(c=!0,a&&a(f))};return new ReadableStream({async pull(f){try{const{done:g,value:m}=await i.next();if(g){d(),f.close();return}let y=m.byteLength;if(r){let w=l+=y;r(w)}f.enqueue(new Uint8Array(m))}catch(g){throw d(g),g}},cancel(f){return d(f),i.return()}},{highWaterMark:2})},Up=64*1024,{isFunction:tc}=ee,_0=(({Request:o,Response:e})=>({Request:o,Response:e}))(ee.global),{ReadableStream:Bp,TextEncoder:Pp}=ee.global,qp=(o,...e)=>{try{return!!o(...e)}catch{return!1}},A0=o=>{o=ee.merge.call({skipUndefined:!0},_0,o);const{fetch:e,Request:r,Response:a}=o,i=e?tc(e):typeof fetch=="function",l=tc(r),c=tc(a);if(!i)return!1;const d=i&&tc(Bp),f=i&&(typeof Pp=="function"?(v=>A=>v.encode(A))(new Pp):async v=>new Uint8Array(await new r(v).arrayBuffer())),g=l&&d&&qp(()=>{let v=!1;const A=new r(Sn.origin,{body:new Bp,method:"POST",get duplex(){return v=!0,"half"}}).headers.has("Content-Type");return v&&!A}),m=c&&d&&qp(()=>ee.isReadableStream(new a("").body)),y={stream:m&&(v=>v.body)};i&&["text","arrayBuffer","blob","formData","stream"].forEach(v=>{!y[v]&&(y[v]=(A,x)=>{let R=A&&A[v];if(R)return R.call(A);throw new Ye(`Response type '${v}' is not supported`,Ye.ERR_NOT_SUPPORT,x)})});const w=async v=>{if(v==null)return 0;if(ee.isBlob(v))return v.size;if(ee.isSpecCompliantForm(v))return(await new r(Sn.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,A)=>{const x=ee.toFiniteNumber(v.getContentLength());return x??w(A)};return async v=>{let{url:A,method:x,data:R,signal:M,cancelToken:O,timeout:L,onDownloadProgress:q,onUploadProgress:G,responseType:B,headers:K,withCredentials:fe="same-origin",fetchOptions:Ce}=jp(v),ke=e||fetch;B=B?(B+"").toLowerCase():"text";let Ue=S0([M,O&&O.toAbortSignal()],L),Pe=null;const qe=Ue&&Ue.unsubscribe&&(()=>{Ue.unsubscribe()});let wt;try{if(G&&g&&x!=="get"&&x!=="head"&&(wt=await S(K,R))!==0){let H=new r(A,{method:"POST",body:R,duplex:"half"}),T;if(ee.isFormData(R)&&(T=H.headers.get("content-type"))&&K.setContentType(T),H.body){const[ge,de]=$p(wt,ec(Np(G)));R=zp(H.body,Up,ge,de)}}ee.isString(fe)||(fe=fe?"include":"omit");const J=l&&"credentials"in r.prototype,he={...Ce,signal:Ue,method:x.toUpperCase(),headers:K.normalize().toJSON(),body:R,duplex:"half",credentials:J?fe:void 0};Pe=l&&new r(A,he);let Ee=await(l?ke(Pe,Ce):ke(A,he));const Z=m&&(B==="stream"||B==="response");if(m&&(q||Z&&qe)){const H={};["status","statusText","headers"].forEach(me=>{H[me]=Ee[me]});const T=ee.toFiniteNumber(Ee.headers.get("content-length")),[ge,de]=q&&$p(T,ec(Np(q),!0))||[];Ee=new a(zp(Ee.body,Up,ge,()=>{de&&de(),qe&&qe()}),H)}B=B||"text";let pe=await y[ee.findKey(y,B)||"text"](Ee,v);return!Z&&qe&&qe(),await new Promise((H,T)=>{Mp(H,T,{data:pe,headers:Rn.from(Ee.headers),status:Ee.status,statusText:Ee.statusText,config:v,request:Pe})})}catch(J){throw qe&&qe(),J&&J.name==="TypeError"&&/Load failed|fetch/i.test(J.message)?Object.assign(new Ye("Network Error",Ye.ERR_NETWORK,v,Pe),{cause:J.cause||J}):Ye.from(J,J&&J.code,v,Pe)}}},x0=new Map,Gp=o=>{let e=o?o.env:{};const{fetch:r,Request:a,Response:i}=e,l=[a,i,r];let c=l.length,d=c,f,g,m=x0;for(;d--;)f=l[d],g=m.get(f),g===void 0&&m.set(f,g=d?new Map:A0(e)),m=g;return g};Gp();const xd={http:Ww,xhr:v0,fetch:{get:Gp}};ee.forEach(xd,(o,e)=>{if(o){try{Object.defineProperty(o,"name",{value:e})}catch{}Object.defineProperty(o,"adapterName",{value:e})}});const Vp=o=>`- ${o}`,T0=o=>ee.isFunction(o)||o===null||o===!1,Fp={getAdapter:(o,e)=>{o=ee.isArray(o)?o:[o];const{length:r}=o;let a,i;const l={};for(let c=0;c`adapter ${f} `+(g===!1?"is not supported by the environment":"is not available in the build"));let d=r?c.length>1?`since : +`+c.map(Vp).join(` +`):" "+Vp(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:xd};function Td(o){if(o.cancelToken&&o.cancelToken.throwIfRequested(),o.signal&&o.signal.aborted)throw new ns(null,o)}function Kp(o){return Td(o),o.headers=Rn.from(o.headers),o.data=Ad.call(o,o.transformRequest),["post","put","patch"].indexOf(o.method)!==-1&&o.headers.setContentType("application/x-www-form-urlencoded",!1),Fp.getAdapter(o.adapter||fo.adapter,o)(o).then(function(a){return Td(o),a.data=Ad.call(o,o.transformResponse,a),a.headers=Rn.from(a.headers),a},function(a){return Lp(a)||(Td(o),a&&a.response&&(a.response.data=Ad.call(o,o.transformResponse,a.response),a.response.headers=Rn.from(a.response.headers))),Promise.reject(a)})}const Wp="1.12.2",nc={};["object","boolean","number","function","string","symbol"].forEach((o,e)=>{nc[o]=function(a){return typeof a===o||"a"+(e<1?"n ":" ")+o}});const Yp={};nc.transitional=function(e,r,a){function i(l,c){return"[Axios v"+Wp+"] Transitional option '"+l+"'"+c+(a?". "+a:"")}return(l,c,d)=>{if(e===!1)throw new Ye(i(c," has been removed"+(r?" in "+r:"")),Ye.ERR_DEPRECATED);return r&&!Yp[c]&&(Yp[c]=!0,console.warn(i(c," has been deprecated since v"+r+" and will be removed in the near future"))),e?e(l,c,d):!0}},nc.spelling=function(e){return(r,a)=>(console.warn(`${a} is likely a misspelling of ${e}`),!0)};function k0(o,e,r){if(typeof o!="object")throw new Ye("options must be an object",Ye.ERR_BAD_OPTION_VALUE);const a=Object.keys(o);let i=a.length;for(;i-- >0;){const l=a[i],c=e[l];if(c){const d=o[l],f=d===void 0||c(d,l,o);if(f!==!0)throw new Ye("option "+l+" must be "+f,Ye.ERR_BAD_OPTION_VALUE);continue}if(r!==!0)throw new Ye("Unknown option "+l,Ye.ERR_BAD_OPTION)}}const rc={assertOptions:k0,validators:nc},Hr=rc.validators;let vi=class{constructor(e){this.defaults=e||{},this.interceptors={request:new kp,response:new kp}}async request(e,r){try{return await this._request(e,r)}catch(a){if(a instanceof Error){let i={};Error.captureStackTrace?Error.captureStackTrace(i):i=new Error;const l=i.stack?i.stack.replace(/^.+\n/,""):"";try{a.stack?l&&!String(a.stack).endsWith(l.replace(/^.+\n.+\n/,""))&&(a.stack+=` +`+l):a.stack=l}catch{}}throw a}}_request(e,r){typeof e=="string"?(r=r||{},r.url=e):r=e||{},r=bi(this.defaults,r);const{transitional:a,paramsSerializer:i,headers:l}=r;a!==void 0&&rc.assertOptions(a,{silentJSONParsing:Hr.transitional(Hr.boolean),forcedJSONParsing:Hr.transitional(Hr.boolean),clarifyTimeoutError:Hr.transitional(Hr.boolean)},!1),i!=null&&(ee.isFunction(i)?r.paramsSerializer={serialize:i}:rc.assertOptions(i,{encode:Hr.function,serialize:Hr.function},!0)),r.allowAbsoluteUrls!==void 0||(this.defaults.allowAbsoluteUrls!==void 0?r.allowAbsoluteUrls=this.defaults.allowAbsoluteUrls:r.allowAbsoluteUrls=!0),rc.assertOptions(r,{baseUrl:Hr.spelling("baseURL"),withXsrfToken:Hr.spelling("withXSRFToken")},!0),r.method=(r.method||this.defaults.method||"get").toLowerCase();let c=l&&ee.merge(l.common,l[r.method]);l&&ee.forEach(["delete","get","head","post","put","patch","common"],v=>{delete l[v]}),r.headers=Rn.concat(c,l);const d=[];let f=!0;this.interceptors.request.forEach(function(A){typeof A.runWhen=="function"&&A.runWhen(r)===!1||(f=f&&A.synchronous,d.unshift(A.fulfilled,A.rejected))});const g=[];this.interceptors.response.forEach(function(A){g.push(A.fulfilled,A.rejected)});let m,y=0,w;if(!f){const v=[Kp.bind(this),void 0];for(v.unshift(...d),v.push(...g),w=v.length,m=Promise.resolve(r);y{if(!a._listeners)return;let l=a._listeners.length;for(;l-- >0;)a._listeners[l](i);a._listeners=null}),this.promise.then=i=>{let l;const c=new Promise(d=>{a.subscribe(d),l=d}).then(i);return c.cancel=function(){a.unsubscribe(l)},c},e(function(l,c,d){a.reason||(a.reason=new ns(l,c,d),r(a.reason))})}throwIfRequested(){if(this.reason)throw this.reason}subscribe(e){if(this.reason){e(this.reason);return}this._listeners?this._listeners.push(e):this._listeners=[e]}unsubscribe(e){if(!this._listeners)return;const r=this._listeners.indexOf(e);r!==-1&&this._listeners.splice(r,1)}toAbortSignal(){const e=new AbortController,r=a=>{e.abort(a)};return this.subscribe(r),e.signal.unsubscribe=()=>this.unsubscribe(r),e.signal}static source(){let e;return{token:new $S(function(i){e=i}),cancel:e}}};function D0(o){return function(r){return o.apply(null,r)}}function O0(o){return ee.isObject(o)&&o.isAxiosError===!0}const kd={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(kd).forEach(([o,e])=>{kd[e]=o});function Xp(o){const e=new vi(o),r=fp(vi.prototype.request,e);return ee.extend(r,vi.prototype,e,{allOwnKeys:!0}),ee.extend(r,e,null,{allOwnKeys:!0}),r.create=function(i){return Xp(bi(o,i))},r}const Gt=Xp(fo);Gt.Axios=vi,Gt.CanceledError=ns,Gt.CancelToken=R0,Gt.isCancel=Lp,Gt.VERSION=Wp,Gt.toFormData=Ql,Gt.AxiosError=Ye,Gt.Cancel=Gt.CanceledError,Gt.all=function(e){return Promise.all(e)},Gt.spread=D0,Gt.isAxiosError=O0,Gt.mergeConfig=bi,Gt.AxiosHeaders=Rn,Gt.formToJSON=o=>Dp(ee.isHTMLForm(o)?new FormData(o):o),Gt.getAdapter=Fp.getAdapter,Gt.HttpStatusCode=kd,Gt.default=Gt;const{Axios:Jx,AxiosError:Qx,CanceledError:Zx,isCancel:eT,CancelToken:tT,VERSION:nT,all:rT,Cancel:aT,isAxiosError:iT,spread:sT,toFormData:oT,AxiosHeaders:lT,HttpStatusCode:cT,formToJSON:uT,getAdapter:dT,mergeConfig:fT}=Gt,Rd="g7.identity.redirectStash",ac=ut("IdentityGuardInterceptor");class mt{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 r=this.deferredResolver;if(!r){ac.warn("IdentityGuardInterceptor.resolveDeferred 호출됐지만 대기 중인 launcher 가 없습니다. 모달이 launcher 외부에서 열렸는지 확인하세요.");return}this.deferredResolver=null,r(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,r){return e===428&&typeof r=="object"&&r!==null&&r.error_code==="identity_verification_required"}static async handle(e,r,a){this.domainNoticeShown=!1;const i=this.launcher??M0,c=!!(a&&(a.email||a.phone))?{...e.verification,target:a}:e.verification,d=await i(c);if(d.status!=="verified")return null;const f=c.return_request;if(!f)return null;const g=L0(f.url,d.token);return fetch(g,{method:f.method,headers:r?.headers??{Accept:"application/json","Content-Type":"application/json"},body:r?.body,credentials:r?.credentials??"same-origin"})}static redirectExternally(e){const r=e.redirect_url;if(!r)return ac.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 a={return_url:window.location.href,payload:e,stashed_at:Date.now()};try{window.sessionStorage?.setItem(Rd,JSON.stringify(a))}catch(i){ac.warn("sessionStorage 접근 실패 — stash 없이 redirect 합니다.",i)}window.location.href=r}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}}$(mt,"launcher",null),$(mt,"deferredResolver",null),$(mt,"domainNoticeShown",!1);function L0(o,e){if(!e)return o;try{const r=typeof window<"u"?window.location.origin:"http://localhost",a=new URL(o,r);return a.searchParams.set("verification_token",e),/^https?:\/\//i.test(o)?a.toString():`${a.pathname}${a.search}${a.hash}`}catch{const r=o.includes("?")?"&":"?";return`${o}${r}verification_token=${encodeURIComponent(e)}`}}const M0=async o=>{if(typeof window>"u")return{status:"cancelled"};if(o.render_hint==="external_redirect"||o.redirect_url)return mt.redirectExternally(o);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 r=window.location.href,a={return_url:r,payload:o,stashed_at:Date.now()};try{window.sessionStorage?.setItem(Rd,JSON.stringify(a))}catch{}const i=`/identity/challenge?return=${encodeURIComponent(r)}`;try{await e.dispatch({handler:"navigate",params:{path:i}})}catch(l){ac.warn("navigate 실패 — window.location 으로 폴백",l),window.location.href=i}return new Promise(()=>{})},$0=ut("ApiClient");function Dd(){return typeof window<"u"&&window.__G7_DEVTOOLS__?window.__G7_DEVTOOLS__:null}class N0{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=Gt.create({baseURL:this.config.baseURL,timeout:this.config.timeout,headers:{"Content-Type":"application/json",Accept:"application/json"},paramsSerializer:{serialize:r=>{const a=[];for(const[i,l]of Object.entries(r))if(l!=null)if(Array.isArray(l)){const c=i.endsWith("[]")?i:`${i}[]`;for(const d of l)a.push(`${encodeURIComponent(c)}=${encodeURIComponent(String(d))}`)}else a.push(`${encodeURIComponent(i)}=${encodeURIComponent(String(l))}`);return a.join("&")}}}),this.setupInterceptors()}setToken(e){typeof window<"u"&&localStorage.setItem(this.TOKEN_KEY,e)}getToken(){return typeof window<"u"?localStorage.getItem(this.TOKEN_KEY):null}removeToken(){typeof window<"u"&&localStorage.removeItem(this.TOKEN_KEY)}setupInterceptors(){this.client.interceptors.request.use(e=>{e.url?.startsWith("/api")&&e.baseURL==="/api"&&(e.baseURL="");const r=this.getToken();if(r&&e.headers&&(e.headers.Authorization=`Bearer ${r}`),typeof window<"u"&&e.headers){const i=localStorage.getItem("g7_locale");i&&(e.headers["Accept-Language"]=i)}const a=Dd();if(a?.isEnabled()){const i=this.buildFullUrl(e),l=(e.method||"GET").toUpperCase(),c=a.trackRequest(i,l,{requestBody:e.data});e._devToolsRequestId=c}return e},e=>Promise.reject(e)),this.client.interceptors.response.use(e=>{const r=e.config,a=r._devToolsRequestId;if(a){const i=Dd();i?.isEnabled()&&i.completeRequest(a,e.status,e.data),r._devToolsRequestId=null}return e},async e=>{const r=e.config,a=r?.url||"",l=["/auth/","/layouts/"].some(c=>a.includes(c));if(e.response?.status===401&&!r?._retry&&!l){if(r._retry=!0,await br.getInstance().refreshToken()){const f=this.getToken();return f&&(r.headers.Authorization=`Bearer ${f}`),r._devToolsRequestId=null,this.client(r)}return this.completeDevToolsRequest(r,e),this.removeToken(),this.config.onUnauthorized&&this.config.onUnauthorized(),Promise.reject(e)}if(e.response?.status===401&&l)return this.completeDevToolsRequest(r,e),Promise.reject(e);if(mt.isIdentityRequired(e.response?.status,e.response?.data)){this.completeDevToolsRequest(r,e);const c={},d=r?.headers??{};for(const[w,S]of Object.entries(d))typeof S=="string"&&(c[w]=S);let f;r?.data!==void 0&&r?.data!==null&&(f=typeof r.data=="string"?r.data:JSON.stringify(r.data),c["Content-Type"]=c["Content-Type"]??"application/json");const g=r?.identity_target,m=await mt.handle(e.response.data,{headers:c,body:f,credentials:"same-origin"},g);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(r,e),this.callOnError(e),Promise.reject(e)):(this.completeDevToolsRequest(r,e),e.response&&this.callOnError(e),Promise.reject(e))})}async get(e,r){return(await this.client.get(e,r)).data}async post(e,r,a){return(await this.client.post(e,r,a)).data}async put(e,r,a){return(await this.client.put(e,r,a)).data}async patch(e,r,a){return(await this.client.patch(e,r,a)).data}async delete(e,r){return(await this.client.delete(e,r)).data}getInstance(){return this.client}setOnUnauthorized(e){this.config.onUnauthorized=e}setOnError(e){this.config.onError=e}completeDevToolsRequest(e,r){if(!e?._devToolsRequestId)return;const a=Dd();if(!a?.isEnabled())return;const i=e._devToolsRequestId;e._devToolsRequestId=null,r.response?a.completeRequest(i,r.response.status,r.response.data):r.request?a.failRequest(i,r.message||"Network error"):a.failRequest(i,r.message||"Request error")}buildFullUrl(e){let r=e.url||"";if(e.baseURL&&!r.startsWith("http")&&(r=`${e.baseURL}${r.startsWith("/")?"":"/"}${r}`),e.params&&typeof e.params=="object"){const a=e.params,i=[];for(const[l,c]of Object.entries(a))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&&(r+=(r.includes("?")?"&":"?")+i.join("&"))}return r}callOnError(e){if(!this.config.onError)return;const r={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(r)}catch(a){$0.error("Error in onError handler:",a)}}}let Od=null;function jr(){return Od||(Od=new N0),Od}const go=ut("AuthManager");function rs(o,e,r,a){try{window.G7Core?.devTools?.trackAuthEvent?.(o,e,r,a)}catch{}}const ic={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"}},Ar=class Ar{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",ic.admin),this.config.set("user",ic.user)}static getInstance(){return Ar.instance||(Ar.instance=new Ar),Ar.instance}on(e,r){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(r)}emit(e,...r){const a=this.eventHandlers.get(e);a&&a.forEach(i=>i(...r))}isAuthenticated(){return this.state.isAuthenticated}getUser(){return this.state.user}getAuthType(){return this.state.type}async checkAuth(e){const r=jr();if(!r.getToken())return this.clearState(),!1;const i=this.config.get(e);if(!i)return go.error(`Unknown auth type: ${e}`),!1;try{const l=await r.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(r){return go.warn(`Preload auth failed for type ${e}:`,r),!1}}async login(e,r,a){const i=jr();if(!this.config.get(e))throw new Error(`Unknown auth type: ${e}`);const c=e==="admin"?ic.admin.loginEndpoint:ic.user.loginEndpoint;try{const d=a?.headers?{headers:a.headers}:void 0,f=await i.post(c,r,d);if(f.success&&f.data){i.setToken(f.data.token);const g=f.data.user.language,m=localStorage.getItem(Ar.LOCALE_STORAGE_KEY),y=g&&g!==m;if(g)try{localStorage.setItem(Ar.LOCALE_STORAGE_KEY,g)}catch(w){go.warn("Failed to save user language to localStorage:",w)}return this.state={isAuthenticated:!0,user:f.data.user,type:e},this.emit("login",this.state),this.emit("authStateChange",this.state),rs("login",!0,void 0,{userId:f.data.user.uuid,email:f.data.user.email,type:e}),y&&window.__templateApp&&window.__templateApp.changeLocale(g),f.data.user}throw new Error("Login failed")}catch(d){this.clearState();const f=d.response?.data?.message,g=new Error(f||d.message||"Login failed");throw g.response=d.response,g.status=d.response?.status,rs("login",!1,g.message,{type:e,status:d.response?.status}),g}}async logout(){const e=jr(),r=this.state.type?this.config.get(this.state.type):null;try{r&&await e.post(r.logoutEndpoint)}catch(a){go.warn("Logout API call failed:",a)}finally{e.removeToken();const a={...this.state};if(this.clearState(),this.emit("logout",a),this.emit("authStateChange",this.state),rs("logout",!0,void 0,{previousType:a.type}),r&&a.type){const i=window.location.pathname+window.location.search;window.location.href=this.getLoginRedirectUrl(a.type,i)}}}async refreshToken(){if(this.isRefreshing&&this.refreshPromise)return this.refreshPromise;this.isRefreshing=!0,this.refreshPromise=this.doRefreshToken();try{return await this.refreshPromise}finally{this.isRefreshing=!1,this.refreshPromise=null}}async doRefreshToken(){const e=this.state.type;if(!e)return!1;const r=this.config.get(e);if(!r)return!1;const a=jr();try{const i=await a.post(r.refreshEndpoint);return i.success&&i.data?.token?(a.setToken(i.data.token),this.emit("tokenRefreshed"),rs("token-refresh",!0,void 0,{type:e}),!0):(rs("token-refresh",!1,"No token in response",{type:e}),!1)}catch(i){return go.error("Token refresh failed:",i),rs("token-refresh",!1,i instanceof Error?i.message:"Unknown error",{type:e}),!1}}getLoginRedirectUrl(e,r,a){const i=this.config.get(e);if(!i)return"/login";const l=encodeURIComponent(r);let c=`${i.loginPath}?redirect=${l}`;return a&&(c+=`&reason=${encodeURIComponent(a)}`),c}updateConfig(e,r){if(r.loginPath!==void 0){const i=r.loginPath;if(!i.startsWith("/")||i.startsWith("//"))throw new Error(`AuthManager.updateConfig: loginPath must be a same-origin path starting with '/' (got: ${i})`)}const a=this.config.get(e);a&&this.config.set(e,{...a,...r})}getRedirectUrl(e){const a=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 a}getConfig(e){return this.config.get(e)}clearState(){this.state={isAuthenticated:!1,user:null,type:null}}static resetInstance(){Ar.instance=null}};$(Ar,"instance"),$(Ar,"LOCALE_STORAGE_KEY","g7_locale");let br=Ar;const Jp={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}}"}}},Zr={findHandler(o,e){if(o){if(o[e])return o[e];if(o[String(e)])return o[String(e)];if(o.default)return o.default}},normalizeOnError(o){return o?Array.isArray(o)?o:[o]:[]},injectErrorCode(o,e,r){if(o.handler!=="showErrorPage"||o.params?.errorCode!==void 0)return o;const a=typeof e=="string"?parseInt(e,10):e,i=isNaN(a)?r:a;return i===void 0?o:{...o,params:{...o.params,errorCode:i}}}},vr=ut("ErrorHandlingResolver"),Na=class Na{constructor(){$(this,"templateErrorHandling",null);$(this,"layoutErrorHandling",null);$(this,"executeAction",null)}static getInstance(){return Na.instance||(Na.instance=new Na),Na.instance}static resetInstance(){Na.instance=null}setTemplateConfig(e){this.templateErrorHandling=e,vr.log("Template config set:",e)}setLayoutConfig(e){this.layoutErrorHandling=e,vr.log("Layout config set:",e)}setActionExecutor(e){this.executeAction=e}resolve(e,r={}){const{errorHandling:a,onError:i}=r;vr.log("Resolving error:",e,{hasActionErrorHandling:!!a,hasActionOnError:!!i,hasLayoutConfig:!!this.layoutErrorHandling,hasTemplateConfig:!!this.templateErrorHandling});let l=Zr.findHandler(a,e);if(l){const c=this.getMatchedKey(a,e);return{handler:Zr.injectErrorCode(l,c,e),level:"action",matchedKey:c}}if(i){const c=Zr.normalizeOnError(i);if(c.length>0)return{handler:c.length===1?c[0]:{handler:"sequence",actions:c},level:"action",matchedKey:"onError"}}if(l=Zr.findHandler(this.layoutErrorHandling||void 0,e),l){const c=this.getMatchedKey(this.layoutErrorHandling,e);return{handler:Zr.injectErrorCode(l,c,e),level:"layout",matchedKey:c}}if(l=Zr.findHandler(this.templateErrorHandling||void 0,e),l){const c=this.getMatchedKey(this.templateErrorHandling,e);return{handler:Zr.injectErrorCode(l,c,e),level:"template",matchedKey:c}}if(l=Zr.findHandler(Jp,e),l){const c=this.getMatchedKey(Jp,e);return{handler:Zr.injectErrorCode(l,c,e),level:"system",matchedKey:c}}return{handler:null,level:null,matchedKey:null}}async execute(e,r){if(!this.executeAction){vr.error("Action executor is not set");return}vr.log("Executing handler:",e.handler,{errorContext:r});try{return await this.executeAction(e,{error:r})}catch(a){throw vr.error("Failed to execute handler:",a),a}}async resolveAndExecute(e,r,a={}){const i=this.resolve(e,a);if(vr.log("Resolve result:",{errorCode:e,handler:i.handler?.handler,level:i.level,matchedKey:i.matchedKey}),!i.handler)return vr.warn("No handler found for error:",e),{handled:!1};try{return{handled:!0,result:await this.execute(i.handler,r)}}catch(l){return vr.error("Handler execution failed:",l),{handled:!1}}}getMatchedKey(e,r){return e[r]?r:e[String(r)]?String(r):"default"}clearLayoutConfig(){this.layoutErrorHandling=null,vr.log("Layout config cleared")}clearAllConfig(){this.templateErrorHandling=null,this.layoutErrorHandling=null,vr.log("All config cleared")}getConfigStatus(){return{hasTemplate:this.templateErrorHandling!==null,hasLayout:this.layoutErrorHandling!==null,hasExecutor:this.executeAction!==null}}};$(Na,"instance",null);let Ld=Na;function Sr(){return Ld.getInstance()}var Md={exports:{}},po={};/** + * @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 Qp;function I0(){if(Qp)return po;Qp=1;var o=Symbol.for("react.transitional.element"),e=Symbol.for("react.fragment");function r(a,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:o,type:a,key:c,ref:i!==void 0?i:null,props:l}}return po.Fragment=e,po.jsx=r,po.jsxs=r,po}var Zp;function H0(){return Zp||(Zp=1,Md.exports=I0()),Md.exports}var dt=H0();const j0=Jr({__proto__:null,default:Qr(dt)},[dt]),$d=ut("ParentContextProvider"),em=N.createContext(null);let sc=null;function Nd(){sc?($d.log("[triggerModalParentUpdate] 모달 부모 컨텍스트 업데이트 트리거"),sc()):$d.warn("[triggerModalParentUpdate] Provider가 아직 마운트되지 않음")}const tm=({children:o})=>{const[e,r]=N.useState(0),a=N.useRef(!0),i=N.useCallback(()=>{const c=window.__g7LayoutContextStack||[];return c[c.length-1]?.dataContext},[]);N.useEffect(()=>(a.current=!0,sc=()=>{a.current&&(r(c=>c+1),$d.log("[ParentContextProvider] 버전 업데이트됨"))},()=>{a.current=!1,sc=null}),[]);const l={version:e,getParentDataContext:i};return dt.jsx(em.Provider,{value:l,children:o})};function z0(){return N.useContext(em)}const j=ut("ActionDispatcher");function U0(o,e,r,a){return r||(Vg(o)||od(o)?"$t:core.errors.network_request_failed":a||`Failed to execute action: ${e}`)}const nm=new Set(["navigate","navigateBack","navigateForward","replaceUrl","refresh","logout"]),B0=new Set(["redirect"]);function Vn(){try{return window.G7Core?.devTools}catch{return}}class It extends Error{constructor(r,a,i){super(r);$(this,"unknownHandler",!1);this.action=a,this.originalError=i,this.name="ActionError"}}const rm={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"},fs=class fs{constructor(e={},r,a){$(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,"intervals",new Map);this.bindingEngine=new _n,this.translationEngine=r,this.translationContext=a,this.defaultContext=e,this.registerDefaultHandlers(),this.setupErrorHandling()}setGlobalHeaders(e){this.globalHeaders=e||[]}setNamedActions(e){this.namedActions=e||{};const r=Vn();r?.isEnabled?.()&&r.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 nm}static getPreviewSuppressedLayoutFeatures(){return B0}resolveActionRef(e){if(!e.actionRef)return e;const r=this.namedActions[e.actionRef];if(!r)return j.warn(`[resolveActionRef] named action not found: "${e.actionRef}"`),e;const a=Vn();a?.isEnabled?.()&&a.trackNamedActionRef?.({actionRefName:e.actionRef,resolvedHandler:r.handler,timestamp:Date.now()});const{actionRef:i,type:l,key:c,event:d,...f}=e,g={...r,...Object.fromEntries(Object.entries(f).filter(([,m])=>m!==void 0)),type:l??r.type};return c!==void 0&&(g.key=c),d!==void 0&&(g.event=d),g}matchesPattern(e,r){if(r==="*")return!0;const a=r.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${a}$`).test(e)}getMatchingGlobalHeaders(e,r){const a={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,c])=>{const d=Zi(c,r,{skipCache:!0});d!=null&&d!==""&&(a[l]=String(d))});return a}setupErrorHandling(){if(this.errorHandlingSetup)return;Sr().setActionExecutor(async(r,a)=>{const i={type:"click",handler:r.handler,target:r.target,params:r.params,actions:r.actions},l={data:{...this.defaultContext.data,error:a.error}};return await this.dispatchAction(i,l)}),this.errorHandlingSetup=!0}registerDefaultHandlers(){this.registerHandler("refetchDataSource",async(r,a)=>{const i=r.params?.dataSourceId,l=r.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={...a.state?._global,...c},f=window.G7Core?.state?.getLocal?.()||{},g=a.data?._local||a.state||{},m={...f,...g},y=a.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(r,a)=>{const{dataSourceId:i,dataPath:l,newData:c}=r.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(r,a)=>{const{dataSourceId:i,data:l,merge:c=!1}=r.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(r,a)=>{const{selector:i,behavior:l="smooth",block:c="nearest",inline:d="nearest",waitForElement:f=!1,timeout:g=2e3,delay:m=0,retryCount:y=0,retryInterval:w=50,scrollContainer:S}=r.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 v=null;if(f){if(v=await new Promise(A=>{const x=document.querySelector(i);if(x){A(x);return}const R=setTimeout(()=>{M.disconnect(),A(null)},g),M=new MutationObserver(()=>{const O=document.querySelector(i);O&&(clearTimeout(R),M.disconnect(),A(O))});M.observe(document.body,{childList:!0,subtree:!0})}),!v){j.warn(`scrollIntoView: element not found for selector "${i}" after ${g}ms timeout`);return}}else{m>0&&await new Promise(x=>setTimeout(x,m)),v=document.querySelector(i);let A=0;for(;!v&&AsetTimeout(x,w)),v=document.querySelector(i),A++;if(!v){j.warn(`scrollIntoView: element not found for selector "${i}" after ${A+1} attempts`);return}}if(S){const A=document.querySelector(S);if(!A){j.warn(`scrollIntoView: container not found for selector "${S}"`);return}const x=v.getBoundingClientRect(),R=A.getBoundingClientRect(),M=x.top-R.top+A.scrollTop,O=M+x.height;let L;switch(c){case"start":L=M;break;case"center":L=M-A.clientHeight/2+x.height/2;break;case"end":L=O-A.clientHeight;break;case"nearest":default:const q=x.topR.bottom;if(q)L=M;else if(G)L=O-A.clientHeight;else return;break}A.scrollTo({top:Math.max(0,L),behavior:l});return}v.scrollIntoView({behavior:l,block:c,inline:d})}),this.registerHandler("reloadExtensions",async(r,a)=>{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}=r.params||{};if(l)try{await this.executeAction({handler:"reloadModuleHandlers",params:r.params},a)}catch(d){j.error("reloadExtensions: reloadModuleHandlers failed",d)}if(c)try{await this.executeAction({handler:"reloadPluginHandlers",params:r.params},a)}catch(d){j.error("reloadExtensions: reloadPluginHandlers failed",d)}j.log("reloadExtensions: done")}),this.registerHandler("reloadRoutes",async(r,a)=>{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(r,a)=>{if(typeof window>"u"){j.warn("refresh: window is not available");return}const i=Number(r.params?.delayMs??0);i>0&&await new Promise(l=>setTimeout(l,i)),window.location.reload()}),this.registerHandler("remount",async(r,a)=>{const{componentId:i}=r.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(r,a)=>{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(r,a)=>{if(typeof window>"u"){j.warn("reloadModuleHandlers: window is not available");return}const{moduleInfo:i,action:l}=r.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&&(d.moduleAssets=d.moduleAssets||{},d.moduleAssets[f]=c.assets,j.log(`reloadModuleHandlers: Added assets for ${f}`),c.assets.js)){const g=c.assets.js,m=`module-${f}`;if(document.getElementById(m)){j.warn(`reloadModuleHandlers: Script ${m} already loaded`);return}const y=document.createElement("script");if(y.id=m,y.src=g,y.async=!0,await new Promise((w,S)=>{y.onload=()=>{j.log(`reloadModuleHandlers: Script loaded successfully for ${f}`),w()},y.onerror=()=>{j.error(`reloadModuleHandlers: Failed to load script for ${f}`),S(new Error(`Failed to load module script: ${g}`))},document.head.appendChild(y)}),c.assets.css){const w=c.assets.css,S=`module-css-${f}`;if(!document.getElementById(S)){const v=document.createElement("link");v.id=S,v.rel="stylesheet",v.href=w,document.head.appendChild(v),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 g=`module-${f}`,m=document.getElementById(g);m&&(m.remove(),j.log(`reloadModuleHandlers: Removed script for ${f}`));const y=`module-css-${f}`,w=document.getElementById(y);w&&(w.remove(),j.log(`reloadModuleHandlers: Removed CSS for ${f}`))}}catch(g){throw j.error(`reloadModuleHandlers: Failed to ${l} module assets`,g),g}}),this.registerHandler("reloadPluginHandlers",async(r,a)=>{if(typeof window>"u"){j.warn("reloadPluginHandlers: window is not available");return}const{pluginInfo:i,action:l}=r.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&&(d.pluginAssets=d.pluginAssets||{},d.pluginAssets[f]=c.assets,j.log(`reloadPluginHandlers: Added assets for ${f}`),c.assets.js)){const g=c.assets.js,m=`plugin-${f}`;if(document.getElementById(m)){j.warn(`reloadPluginHandlers: Script ${m} already loaded`);return}const y=document.createElement("script");if(y.id=m,y.src=g,y.async=!0,await new Promise((w,S)=>{y.onload=()=>{j.log(`reloadPluginHandlers: Script loaded successfully for ${f}`),w()},y.onerror=()=>{j.error(`reloadPluginHandlers: Failed to load script for ${f}`),S(new Error(`Failed to load plugin script: ${g}`))},document.head.appendChild(y)}),c.assets.css){const w=c.assets.css,S=`plugin-css-${f}`;if(!document.getElementById(S)){const v=document.createElement("link");v.id=S,v.rel="stylesheet",v.href=w,document.head.appendChild(v),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 g=`plugin-${f}`,m=document.getElementById(g);m&&(m.remove(),j.log(`reloadPluginHandlers: Removed script for ${f}`));const y=`plugin-css-${f}`,w=document.getElementById(y);w&&(w.remove(),j.log(`reloadPluginHandlers: Removed CSS for ${f}`))}}catch(g){throw j.error(`reloadPluginHandlers: Failed to ${l} plugin assets`,g),g}});let e=!1;this.registerHandler("showErrorPage",async(r,a)=>{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=r.params?.errorCode||500,d=r.params?.target||"content";let f=r.params?.containerId;f||(f=d==="full"?"app":"main_content"),j.log("showErrorPage:",{errorCode:c,target:d,containerId:f});const g=(m,y=6e4)=>new Promise((w,S)=>{const v=document.getElementById(m);if(v){w(v);return}j.log(`showErrorPage: Waiting for container #${m}...`);let A;const x=new MutationObserver((R,M)=>{const O=document.getElementById(m);O&&(j.log(`showErrorPage: Container #${m} found`),M.disconnect(),clearTimeout(A),w(O))});x.observe(document.body,{childList:!0,subtree:!0}),A=setTimeout(()=>{x.disconnect(),S(new Error(`Container #${m} not found within ${y}ms`))},y)});try{await g(f);const m=Sr(),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(r,a)=>{const i=r.params?.event,l=r.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:a.data,state:a.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 g=(c?.state?.get()||{})._local||{},m={event:i,success:!0,data:f.length===1?f[0]:f,listeners:f.length};this.globalStateUpdater({_local:{...g,_eventResult:m}});const y=a.state&&typeof a.state=="object"&&!Array.isArray(a.state)?a.state:g;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(r,a)=>{const{productId:i,field:l,value:c}=r.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(w=>w.id===i?{...w,[l]:c,_modified:!0}:w),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(r,a)=>{const{productId:i,optionId:l,field:c,value:d}=r.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 g=f.state.get()||{},y=(g.products?.data?.data||[]).map(S=>{if(S.id===i&&S.options){const v=S.options.map(A=>A.id===l?{...A,[c]:d,_modified:!0}:A);return{...S,options:v,_modified:!0}}return S}),w=new Set(g._local?.modifiedProductIds||[]);w.add(i),this.globalStateUpdater({products:{...g.products,data:{...g.products?.data,data:y}},_local:{...g._local,modifiedProductIds:Array.from(w)}}),j.log(`updateOptionField: Updated product ${i} option ${l}, field: ${c}, value:`,d)}catch(g){throw j.error("updateOptionField: Error updating option field",g),g}}),this.registerHandler("setLocale",async(r,a)=>{const i=r.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=Vn();if(!e?.isEnabled())return;const r=[{name:"refetchDataSource",description:"데이터 소스를 다시 fetch합니다"},{name:"appendDataSource",description:"데이터 소스에 새 데이터를 병합합니다 (무한 스크롤용)"},{name:"updateDataSource",description:"API 응답으로 데이터 소스를 직접 업데이트합니다 (refetch 대체)"},{name:"reloadRoutes",description:"라우트를 다시 로드합니다"},{name:"refresh",description:"현재 페이지를 새로고침합니다"},{name:"remount",description:"컴포넌트를 리마운트합니다"},{name:"reloadTranslations",description:"다국어 파일을 다시 로드합니다"},{name:"showErrorPage",description:"에러 페이지를 표시합니다"},{name:"emitEvent",description:"이벤트를 발생시킵니다"},{name:"updateProductField",description:"상품 필드를 인라인 수정합니다"},{name:"updateOptionField",description:"상품 옵션 필드를 인라인 수정합니다"},{name:"setLocale",description:"언어를 변경합니다 (DB 저장 + UI 리렌더링)"}];for(const a of r)e.trackHandlerRegistration(a.name,"built-in",a.description)}createHandler(e,r,a){j.log("createHandler called for:",e.handler,e.type);const i=window.__g7DevTools,l=Date.now(),c=a?.state?{...a.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?.()??a?.state??{},y=Date.now()-l;for(const w of Object.keys(c)){const S=c[w],v=m[w];S!==v&&y>100&&(i.trackStaleClosureWarning?.({type:"event-handler-stale",location:`createHandler(${e.handler})`,capturedPath:`_local.${w}`,capturedValue:S,capturedAt:l,currentValue:v,actionId:d,stackTrace:new Error().stack}),j.warn(`[Stale Closure] _local.${w} changed after handler creation:`,`captured="${S}" → current="${v}" (${y}ms ago)`))}}try{f.type!=="change"&&f.preventDefault();let g={};if(f.type==="submit"&&f.target instanceof HTMLFormElement){const w=f.target;new FormData(w).forEach((v,A)=>{g[A]=v})}const m={...this.defaultContext,data:{...r,form:g,_local:a?.state||{},$event:f},event:f,...a&&{state:a.state,setState:a.setState},isolatedContext:a?.isolatedContext};if(e.confirm){let w=this.resolveValue(e.confirm,m.data);if(this.translationEngine&&this.translationContext&&w.startsWith("$t:")&&(w=this.translationEngine.resolveTranslations(w,this.translationContext,m.data)),!confirm(w))return}const y=window.__g7ActionContext;window.__g7ActionContext={...a,data:m.data};try{await this.executeAction(e,m)}finally{window.__g7ActionContext=y}}catch(g){if(j.error("Action execution failed:",g),e.onError){const m=g instanceof It&&g.originalError?g.originalError:g,y={...this.defaultContext,data:{...r,error:m,_local:a?.state||{},$event:f},event:f,...a&&{state:a.state,setState:a.setState}},w=Array.isArray(e.onError)?e.onError:[e.onError];for(const S of w)await this.executeAction(S,y)}}}}generateActionId(e,r){const a=e.handler,i=r||"no-target",l=Date.now(),c=Math.random().toString(36).substring(2,9);return`${a}_${i.replace(/[^a-zA-Z0-9]/g,"_")}_${l}_${c}`}async executeAction(e,r){if(e=this.resolveActionRef(e),typeof e.handler=="string"&&e.handler.includes("{{")){const f=this.evaluateExpression(e.handler,r.data);e={...e,handler:f==null?"":String(f)}}const a=Vn(),i=a?.isEnabled()?`action_${Date.now()}_${Math.random().toString(36).substring(2,11)}`:void 0,l=performance.now();let c;if(i&&a&&a.logAction({id:i,type:e.handler,params:this.sanitizeForDevTools(e.params),context:this.sanitizeForDevTools({hasState:!!r.state,hasSetState:!!r.setState,dataKeys:r.data?Object.keys(r.data):[]}),startTime:l,status:"started"}),e.if!==void 0)try{const f=this.resolveValue(e.if,r.data),g=f===!0||f==="true"||f&&f!=="false"&&f!=="0"&&f!==!1;if(j.log("[executeAction] if condition result:",e.handler,g),!g)return i&&a&&a.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&&a&&a.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,r.data);i&&(c=this.sanitizeForDevTools(f));const g=e.target?this.resolveValue(e.target,r.data):void 0;if(e.handler==="apiCall"&&r.setState){d=this.generateActionId(e,g);const y=r.state?.loadingActions||{};r.setState({loadingActions:{...y,[d]:!0}})}if(this.previewMode&&nm.has(e.handler))return j.warn(`Preview mode: "${e.handler}" suppressed`,g||f),i&&a&&a.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||g;m=await this.handleNavigate(y,f,r);break;case"navigateBack":m=await this.handleNavigateBack();break;case"navigateForward":m=await this.handleNavigateForward();break;case"openWindow":{const v=f.path||g;m=await this.handleOpenWindow(v,f);break}case"replaceUrl":{const v=f.path||g||window.location.pathname;m=await this.handleReplaceUrl(v,f);break}case"apiCall":if(e.onSuccess&&a?.isEnabled()&&i){const v=window.G7Core,A={};if(v?.state?.get){const x=v.state.get();A._global=x}r.state&&(A._local=r.state),a.registerStateCaptureForHandler?.(i,["_global","_local"],A)}const w=e.auth_mode??(e.auth_required?"required":"none"),S=e.identity_target?this.resolveParams(e.identity_target,r.data):void 0;m=await this.handleApiCall(g,f,r,w,S);break;case"login":m=await this.handleLogin(g,f,r);break;case"logout":m=await this.handleLogout(g,r);break;case"setState":j.log("[executeAction] setState resolvedParams:",f),m=await this.handleSetState(e.render!==void 0?{...f,__render:e.render}:f,r);break;case"setError":m=await this.handleSetError(g,f,r);break;case"openModal":m=await this.handleOpenModal(g,r);break;case"closeModal":m=await this.handleCloseModal(r);break;case"showAlert":m=await this.handleShowAlert(g,r);break;case"toast":m=await this.handleToast(f,r);break;case"switch":m=await this.handleSwitch(e,r);break;case"conditions":m=await this.handleConditions(e,r);break;case"sequence":m=await this.handleSequence(e,r);break;case"parallel":m=await this.handleParallel(e,r);break;case"startInterval":m=this.handleStartInterval(f,r);break;case"stopInterval":m=this.handleStopInterval(f);break;case"loadScript":m=await this.handleLoadScript(f,e,r);break;case"callExternal":m=await this.handleCallExternal(f,e,r);break;case"callExternalEmbed":m=await this.handleCallExternalEmbed(f,e,r);break;case"saveToLocalStorage":m=await this.handleSaveToLocalStorage(f,r);break;case"loadFromLocalStorage":m=await this.handleLoadFromLocalStorage(f,r);break;default:m=await this.handleCustomAction({...e,target:g,params:f},r);break}if(e.resultTo&&m!==void 0){const{target:y,key:w,merge:S}=e.resultTo,v=this.resolveValue(w,r.data),A=S==="replace"?"replace":S==="shallow"?"shallow":"deep";if(y==="_local"&&r.setState){const x=this.buildNestedUpdate(v,m),R=A!=="deep"?{...x,__mergeMode:A}:x;r.setState(R),j.log(`[resultTo] Saved to _local.${v} (merge=${A}):`,m)}else if(y==="_local"&&this.globalStateUpdater){const M=(window.G7Core?.state?.get()||{})._local||{},O=this.buildNestedUpdate(v,m);let L;A==="replace"?L=O:A==="shallow"?L={...M,...O}:L=this.deepMergeWithState(O,M),this.globalStateUpdater({_local:L}),j.log(`[resultTo] Saved to _local.${v} via globalStateUpdater (merge=${A}):`,m)}else if(y==="_global"&&this.globalStateUpdater){const x=this.buildNestedUpdate(v,m);this.globalStateUpdater(x),j.log(`[resultTo] Saved to _global.${v}:`,m)}else if(y==="_isolated"&&r.isolatedContext){const x=this.buildNestedUpdate(v,m);r.isolatedContext.mergeState(x,A),j.log(`[resultTo] Saved to _isolated.${v} (merge=${A}):`,m)}else j.warn(`[resultTo] Cannot save result: target=${y}, setState=${!!r.setState}, globalStateUpdater=${!!this.globalStateUpdater}, isolatedContext=${!!r.isolatedContext}`)}if(e.onSuccess){if(a?.isEnabled()&&i&&e.handler==="apiCall"){const S=window.G7Core,v={};S?.state?.get&&(v._global=S.state.get()),r.state&&(v._local=r.state),a.detectStaleClosure?.(i,`${e.handler} → onSuccess`,v,"callback-state-capture",i)}const y={...r,data:{...r.data,result:m,response:m}},w=Array.isArray(e.onSuccess)?e.onSuccess:[e.onSuccess];w.length>1?await this.handleSequence({handler:"sequence",type:"click",actions:w},y):w.length===1&&await this.executeAction(w[0],y)}return i&&a&&a.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 g=f instanceof It?f:new It(`Failed to execute action: ${e.handler}`,e,f instanceof Error?f:void 0),m=g.originalError?.response||{},y=m.data||{},w=g.originalError?.status||m.status||500;let S=U0(g.originalError??f,e.handler,y.message,g.message);this.translationEngine&&this.translationContext&&S.startsWith("$t:")&&(S=this.translationEngine.resolveTranslations(S,this.translationContext));const v={status:w,message:S,errors:y.errors||m.errors,data:y,statusText:g.originalError?.statusText,error_code:y.error_code??m.error_code};if(g.unknownHandler)throw j.warn(`Unknown action handler "${e.handler}" — skipped (extension not loaded?). Not surfaced to the user.`),g;const x=Sr().resolve(w,{errorHandling:e.errorHandling,onError:e.onError});if(x.handler){if(a?.isEnabled()&&i&&e.handler==="apiCall"){const M=window.G7Core,O={};M?.state?.get&&(O._global=M.state.get()),r.state&&(O._local=r.state),a.detectStaleClosure?.(i,`${e.handler} → onError`,O,"callback-state-capture",i)}const R={...r,data:{...r.data,error:v}};try{const M={type:"click",handler:x.handler.handler,target:x.handler.target,params:x.handler.params,actions:x.handler.actions};return await this.executeAction(M,R),{success:!1,error:g}}catch(M){return j.error("Error executing error handler:",M),{success:!1,error:g}}}throw i&&a&&a.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:g.name,message:g.message,stack:g.stack}}),g}finally{if(e.handler==="apiCall"&&r.setState&&d){const f=r.state?.loadingActions||{},{[d]:g,...m}=f;r.setState({loadingActions:m})}}}async handleNavigate(e,r,a){let i=e;if(r.query||r.mergeQuery===!0)if(r.mergeQuery===!0)i=this.buildMergedQueryPath(e,r.query??{});else{const c=new URLSearchParams;for(const[f,g]of Object.entries(r.query))if(g!=null&&g!=="")if(Array.isArray(g)){const m=f.endsWith("[]")?f:`${f}[]`;for(const y of g)y!=null&&y!==""&&c.append(m,String(y))}else c.set(f,String(g));const d=c.toString();d&&(i=`${e}?${d}`)}if(j.log("handleNavigate:",{target:e,params:r,finalPath:i,replace:r.replace,windowLocationSearch:window.location.search}),r.replace===!0){const c=window.G7Core;if(c?.updateQueryParams){const d=typeof r.transition_overlay_target=="string"?r.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(r.scroll,r.scrollBehavior,"top");return}j.warn("handleNavigate: G7Core.updateQueryParams not available, falling back to React Router")}const l=this.resolveNavigateFallbackAction(i,r);if(l){j.warn(`handleNavigate: No route matched, falling back to "${l.handler}"`),await this.dispatchAction({type:"click",handler:l.handler,params:l.params},a),this.applyScrollOption(r.scroll,r.scrollBehavior,"top");return}if(!a.navigate)throw new It("Navigate function is not provided in context");a.navigate(i,{replace:r.replace===!0}),this.applyScrollOption(r.scroll,r.scrollBehavior,"top")}resolveNavigateFallbackAction(e,r){const a=r.fallback;if(a===!1||r.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(a,e,r)}resolveNavigateFallback(e,r,a){return e==null?{handler:"openWindow",params:{path:r,target:"_self"}}:typeof e=="string"?{handler:e,params:{path:r}}:typeof e=="object"&&typeof e.handler=="string"?{handler:e.handler,params:{path:r,...e.params||{}}}:(j.warn("resolveNavigateFallback: unrecognized fallback option, using openWindow",e),{handler:"openWindow",params:{path:r,target:"_blank"}})}applyScrollOption(e,r,a){const i=e===void 0?a:e;if(i==="preserve")return;const l=r==="smooth"?"smooth":"instant",c=y=>{if(typeof y!="object"||y===null)return!1;const w=y;return"container"in w||"to"in w||"block"in w||"offset"in w},d=(y,w,S=0)=>{y===window?window.scrollTo({top:w,left:S,behavior:l}):y.scrollTo({top:w,left:S,behavior:l})},f=(y,w,S,v)=>{if(w===window){y.scrollIntoView({behavior:l,block:S}),v&&window.scrollBy({top:-v,left:0,behavior:l});return}const A=w,x=y.getBoundingClientRect(),R=A.getBoundingClientRect(),M=A.scrollTop+(x.top-R.top);let O;S==="center"?O=M-(A.clientHeight-y.clientHeight)/2:S==="end"?O=M-(A.clientHeight-y.clientHeight):O=M,O-=v,A.scrollTo({top:Math.max(0,O),left:0,behavior:l})},g=()=>{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),A=v.overflowY,x=v.overflowX;(A==="auto"||A==="scroll"||x==="auto"||x==="scroll")&&S.scrollTo({top:0,left:0,behavior:l})})},m=()=>{try{if(c(i)){const y=i,w=y.block??"start",S=typeof y.offset=="number"?y.offset:0;let v=window;if(typeof y.container=="string"&&y.container.length>0){const x=document.querySelector(y.container);if(!x){j.warn(`applyScrollOption: container not found: ${y.container}`);return}v=x}const A=y.to??"top";if(A==="top"){v===window?g():d(v,0);return}if(typeof A=="number"){d(v,A-S);return}if(typeof A=="object"&&A!==null&&("x"in A||"y"in A)){const{x=0,y:R=0}=A;d(v,R-S,x);return}if(typeof A=="string"&&(A.startsWith("#")||A.startsWith("."))){const x=document.querySelector(A);x?f(x,v,w,S):j.warn(`applyScrollOption: target element not found: ${A}`);return}j.warn('applyScrollOption: invalid "to" value in extended form',A);return}if(i==="top"){g();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:w=0}=i;window.scrollTo({top:w,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,r){let a=e;if(r.query){const l=new URLSearchParams;for(const[d,f]of Object.entries(r.query))f!=null&&f!==""&&l.set(d,String(f));const c=l.toString();c&&(a=`${e}?${c}`)}const i=r.target==="_self"?"_self":"_blank";j.log("handleOpenWindow:",{target:e,params:r,finalPath:a,windowTarget:i}),i==="_self"?window.location.assign(a):window.open(a,"_blank")}async handleNavigateBack(){j.log("handleNavigateBack"),window.history.back()}async handleNavigateForward(){j.log("handleNavigateForward"),window.history.forward()}async handleReplaceUrl(e,r){let a=e;if(r.query||r.mergeQuery===!0)if(r.mergeQuery===!0)a=this.buildMergedQueryPath(e,r.query??{});else{const i=new URLSearchParams;for(const[c,d]of Object.entries(r.query))if(d!=null&&d!=="")if(Array.isArray(d)){const f=c.endsWith("[]")?c:`${c}[]`;for(const g of d)g!=null&&g!==""&&i.append(f,String(g))}else i.set(c,String(d));const l=i.toString();l&&(a=`${e}?${l}`)}j.log("handleReplaceUrl:",{target:e,params:r,finalPath:a}),window.history.replaceState(null,"",a),this.applyScrollOption(r.scroll,r.scrollBehavior,"preserve")}buildMergedQueryPath(e,r){const a=new URLSearchParams(window.location.search);for(const[c,d]of Object.entries(r))if(d==null||d==="")a.delete(c);else if(Array.isArray(d)){const f=c.endsWith("[]")?c:`${c}[]`;a.delete(c),a.delete(f);for(const g of d)g!=null&&g!==""&&a.append(f,String(g))}else a.set(c,String(d));const i=a.toString(),l=e.split("?")[0];return i?`${l}?${i}`:l}async ensureCsrfToken(){try{await fetch("/sanctum/csrf-cookie",{credentials:"include"})}catch(e){throw new It("Failed to fetch CSRF token",void 0,e instanceof Error?e:void 0)}}getCsrfTokenFromCookie(){const a=`; ${document.cookie}`.split("; XSRF-TOKEN=");if(a.length===2){const i=a.pop()?.split(";").shift();return i?decodeURIComponent(i):null}return null}buildQueryString(e){const r=new URLSearchParams;for(const[a,i]of Object.entries(e))if(!(i==null||i===""))if(Array.isArray(i))for(const l of i)l!=null&&l!==""&&r.append(`${a}[]`,String(l));else typeof i=="object"?r.append(a,JSON.stringify(i)):r.append(a,String(i));return r.toString()}async handleEnsureIdentityVerified(e){const r=typeof e.purpose=="string"?e.purpose:"sensitive_action",a=e.target&&typeof e.target=="object"?e.target:void 0;return await mt.handle({success:!1,error_code:"identity_verification_required",message:"",verification:{policy_key:e.policy_key??"",purpose:r,provider_id:e.provider_id??null,render_hint:e.render_hint??null,return_request:null}},void 0,a)!==null}handleResolveIdentityChallenge(e){const r=typeof e.result=="string"?e.result:"cancelled";let a;switch(r){case"verified":{const i=typeof e.token=="string"?e.token:"";if(!i){j.warn("resolveIdentityChallenge: result=verified 인데 token 이 비어있습니다. failed 로 강등합니다."),a={status:"failed",failureCode:"MISSING_TOKEN"};break}a={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 로 강등합니다."),a={status:"failed",failureCode:"MALFORMED_PENDING"};break}a={status:"pending",pollUrl:i,pollIntervalMs:typeof e.pollIntervalMs=="number"?e.pollIntervalMs:void 0,expiresAt:l};break}case"failed":a={status:"failed",failureCode:typeof e.failureCode=="string"?e.failureCode:"UNKNOWN",reason:typeof e.reason=="string"?e.reason:void 0};break;case"cancelled":default:a={status:"cancelled"};break}return mt.resolveDeferred(a),!0}async handleApiCall(e,r,a,i="none",l){const{method:c="GET",body:d,headers:f,contentType:g}=r;c!=="GET"&&c!=="HEAD"&&await this.ensureCsrfToken();const m=this.getCsrfTokenFromCookie();let y={};if(i==="required"||i==="optional"){const K=jr().getToken();K&&(y={Authorization:`Bearer ${K}`})}let w=e;const S=r.query||(c==="GET"?d:null);if(S&&typeof S=="object"){const B=this.buildQueryString(S);if(B){const K=e.includes("?")?"&":"?";w=`${e}${K}${B}`}}const v=window.G7Core?.state?.getGlobal?.()||a.state?._global||{},A=window.G7Core?.state?.getLocal?.()||a.state?._local||{},x={_global:v,_local:A},R=this.getMatchingGlobalHeaders(e,x),M={};if(typeof window<"u"){const B=localStorage.getItem("g7_locale");B&&(M["Accept-Language"]=B)}const O=g==="multipart/form-data",L={method:c,headers:{...O?{}:{"Content-Type":"application/json"},Accept:"application/json",...M,...m&&{"X-XSRF-TOKEN":m},...y,...R,...f},credentials:"include"};if(d&&c!=="GET")if(O){const B=new FormData;for(const[K,fe]of Object.entries(d))fe instanceof File||fe instanceof Blob?B.append(K,fe):fe!=null&&B.append(K,typeof fe=="object"?JSON.stringify(fe):String(fe));L.body=B}else L.body=JSON.stringify(d);const q=Vn();let G=null;q?.isEnabled()&&(G=q.trackRequest(w,c));try{let B=await fetch(w,L),K;try{K=await B.json()}catch{K=null}if(mt.isIdentityRequired(B.status,K)){const fe=await mt.handle(K,{body:L.body,headers:L.headers,credentials:L.credentials},l);if(fe){B=fe;try{K=await B.json()}catch{K=null}}}if(G&&q?.isEnabled()&&(q.completeRequest(G,B.status,K),G=null),!B.ok){const fe=K||{},Ce=new Error(fe.message||`API call failed: ${B.statusText}`);throw Ce.response=fe,Ce.status=B.status,Ce.statusText=B.statusText,new It(fe.message||`API call failed: ${B.statusText}`,void 0,Ce)}return K}catch(B){throw G&&q?.isEnabled()&&q.failRequest(G,B instanceof Error?B.message:String(B)),B}}async handleLogin(e,r,a){const{body:i}=r;if(!i||!i.email||!i.password)throw new It("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?.()||a.state?._global||{},f=window.G7Core?.state?.getLocal?.()||a.state?._local||{},g={_global:d,_local:f},m=this.getMatchingGlobalHeaders(c,g),y=br.getInstance();try{const w=Object.keys(m).length>0?{headers:m}:void 0;return{user:await y.login(l,{email:i.email,password:i.password},w)}}catch(w){const S=w.message||"Login failed",v=new Error(S);throw v.response=w.response?.data||{},v.status=w.status||w.response?.status||500,new It(S,void 0,v)}}async handleLogout(e,r){await br.getInstance().logout()}async handleSetState(e,r){j.log("[handleSetState] START, params:",e);const{target:a="component",scope:i,merge:l,__render:c,...d}=e,f=Vn(),g=window.G7Core;if(typeof a=="string"&&(a.startsWith("$parent.")||a.startsWith("$root.")))return this.handleParentScopeSetState(a,d,l,r);const m=r.state&&Object.keys(r.state).length>0?r.state:g?.state?.get()||{},y=a==="global"?"_global":a.startsWith("_local.")?a:"_local",w=y==="_global"?m._global:y.startsWith("_local.")?this.getNestedProperty(m._local||{},y.slice(7)):m._local,S=f?.isEnabled()?f.startStateChange(y,w,d,{actionId:r.actionId,handlerType:"setState",source:`target=${a}`}):void 0,v=l==="replace"?"replace":l==="shallow"?"shallow":"deep",A=v!=="deep"?{...d,__mergeMode:v,...S?{__setStateId:S}:{}}:{...d,...S?{__setStateId:S}:{}};if(a==="global"){if(!this.globalStateUpdater){j.warn("Global state updater is not set"),S&&f&&f.completeStateChange(S);return}const x=g?.state?.get()||{},{__setStateId:R,__mergeMode:M,...O}=A,L=v==="deep"?this.deepMergeWithState(O,x):O,q={...L,...S?{__setStateId:S}:{},...v!=="deep"?{__mergeMode:v}:{}};return j.log("setState global:",q),this.globalStateUpdater(q,{render:c}),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"global",...v!=="deep"?{__mergeMode:v}:{},...L}}else if(a==="isolated"){const x=r.isolatedContext;if(x){const{__mergeMode:R,__setStateId:M,...O}=A;return x.mergeState(O,v),j.log("[handleSetState] isolated state updated:",O,"mergeMode:",v),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"isolated",...O}}else if(j.warn('[handleSetState] isolated target used but no IsolatedStateContext found. Make sure the component has "isolatedState" attribute. Falling back to local state.'),r.setState){const M=window.__g7PendingLocalState||r.state||{},O=v==="deep"?this.deepMergeWithState(A,M):A;return r.setState(O),S&&f&&setTimeout(()=>f.completeStateChange(S),0),O}else throw S&&f&&f.completeStateChange(S),new It("isolated target used but no IsolatedStateContext found and no setState function in context")}else if(a==="local"||a==="component"||a==="_local"){if(i==="parent"||i==="root"){const R=window.__g7LayoutContextStack||[];if(R.length>0){const M=i==="parent"?R[R.length-1]:R[0];if(M?.setState){const{__mergeMode:O,__setStateId:L,...q}=A,G=v==="deep"?this.deepMergeWithState(q,M.state||{}):q;return j.log(`[handleSetState] scope=${i}: 타겟 컨텍스트에 상태 업데이트`,G),M.setState(G),S&&f&&setTimeout(()=>f.completeStateChange(S),0),G}}j.warn(`[handleSetState] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const x=r.setState&&!r._isDispatchFallbackContext;if(j.log("[handleSetState] isRealComponentContext:",x,"context.setState:",!!r.setState,"_isDispatchFallbackContext:",r._isDispatchFallbackContext),x){j.log("[handleSetState] Using COMPONENT setState path"),j.log("[handleSetState] resolvedPayload:",A),j.log("[handleSetState] context.state:",r.state),j.log("[handleSetState] mergeMode:",v);const M=window.__g7PendingLocalState||r.state||{},O=v==="deep"?this.deepMergeWithState(A,{}):A;j.log("[handleSetState] convertedPayload (변경 필드만, dot notation 변환):",O),r.setState(O);const L=v==="deep"?this.deepMergeWithState(A,M):v==="shallow"?{...r.state||{},...A}:A,{__mergeMode:q,__setStateId:G,...B}=L;window.__g7PendingLocalState=B,j.log("[handleSetState] __g7PendingLocalState updated:",B),this.globalStateUpdater&&(this.globalStateUpdater({_local:B},{render:!1}),j.log("[handleSetState] _global._local synced (render:false):",B));const{__mergeMode:K,__setStateId:fe,...Ce}=A;if(v==="replace")window.__g7ForcedLocalFields=Ce;else{const ke=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=this.deepMergeWithState(Ce,ke)}return j.log("[handleSetState] __g7ForcedLocalFields updated:",Ce),S&&f&&setTimeout(()=>f.completeStateChange(S),0),{__target:"local",...L}}else if(this.globalStateUpdater){j.log("[handleSetState] Using GLOBAL STATE UPDATER path for _local");const M=window.__g7PendingLocalState||m._local||{};j.log("[handleSetState] currentLocal (with pending):",M);const O=v==="deep"?this.deepMergeWithState(A,M):A;return j.log("[handleSetState] finalLocal (merged):",O),this.globalStateUpdater({_local:O},{render:c}),window.__g7PendingLocalState=O,j.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 It("setState function is not provided in context and globalStateUpdater is not set")}else if(a.startsWith("_local.")){const x=a.slice(7),{__mergeMode:R,__setStateId:M,...O}=A,L=O.value!==void 0?O.value:Object.values(O)[0];if(r.setState){const G=window.__g7PendingLocalState||r.state||{},B=this.createNestedUpdate(x,L,G),K={...G,...B};if(r.setState(B),this.globalStateUpdater&&i!=="parent"&&i!=="root"){const fe=window.__templateApp?.getGlobalState?.()?._local,Ce=fe&&typeof fe=="object"?{...fe,...B}:K;this.globalStateUpdater({_local:Ce},{render:!1}),j.log("[handleSetState] _global._local synced for dot notation (render:false):",Ce)}return S&&f&&setTimeout(()=>f.completeStateChange(S),0),K}else throw S&&f&&f.completeStateChange(S),new It("setState function is not provided in context")}else{if(!r.setState)throw S&&f&&f.completeStateChange(S),new It("setState function is not provided in context");const R=window.__g7PendingLocalState||r.state||{},M=v==="deep"?this.deepMergeWithState(A,R):A;return r.setState(M),S&&f&&setTimeout(()=>f.completeStateChange(S),0),M}}async handleParentScopeSetState(e,r,a,i){const l=Vn(),c=window.G7Core,d=a==="replace"?"replace":a==="shallow"?"shallow":"deep",f=e.startsWith("$parent."),g=f?"$parent.":"$root.",m=e.slice(g.length);let y,w;if(m==="_local"||m==="_global")y=m,w=void 0;else if(m.startsWith("_local."))y="_local",w=m.slice(7);else if(m.startsWith("_global."))y="_global",w=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 v=f?S[S.length-1]:S[0];if(!v){j.warn(`[handleParentScopeSetState] 타겟 컨텍스트를 찾을 수 없습니다. target=${e}`);return}const A=y==="_global"?v.state?._global:v.state?._local,x=l?.isEnabled()?l.startStateChange(e,A,r,{actionId:i.actionId,handlerType:"setState",source:`target=${e}`}):void 0,{__mergeMode:R,__setStateId:M,...O}=r;if(y==="_global"){if(!this.globalStateUpdater){j.warn("[handleParentScopeSetState] globalStateUpdater가 설정되지 않았습니다."),x&&l&&l.completeStateChange(x);return}const L=c?.state?.get()||{};if(w){const q=O.value!==void 0?O.value:Object.values(O)[0],G=this.createNestedUpdate(w,q,L),B={...L,...G};j.log(`[handleParentScopeSetState] ${e}: 전역 상태 중첩 경로 업데이트`,B),this.globalStateUpdater(B)}else{const q=d==="deep"?this.deepMergeWithState(O,L):O;j.log(`[handleParentScopeSetState] ${e}: 전역 상태 업데이트 (mergeMode=${d})`,q),this.globalStateUpdater(d!=="deep"?{...q,__mergeMode:d}:q)}return x&&l&&setTimeout(()=>l.completeStateChange(x),0),{__target:e,...O}}else{if(!v.setState){j.warn(`[handleParentScopeSetState] 타겟 컨텍스트에 setState가 없습니다. target=${e}`),x&&l&&l.completeStateChange(x);return}const L=v.state||{};if(w){const q=O.value!==void 0?O.value:Object.values(O)[0],G=this.createNestedUpdate(w,q,L),B={...L,...G};return j.log(`[handleParentScopeSetState] ${e}: 로컬 상태 중첩 경로 업데이트`,G),v.setState(G),v.state=B,v.dataContext&&(v.dataContext._local=B),Nd(),x&&l&&setTimeout(()=>l.completeStateChange(x),0),B}else{const q=d!=="deep"?{...O,__mergeMode:d}:O,G=d==="replace"?O:d==="shallow"?{...L,...O}:this.deepMergeWithState(O,L);return j.log(`[handleParentScopeSetState] ${e}: 로컬 상태 업데이트 (mergeMode=${d})`,G),v.setState(q),v.state=G,v.dataContext&&(v.dataContext._local=G),Nd(),x&&l&&setTimeout(()=>l.completeStateChange(x),0),G}}}deepMergeWithState(e,r){const a=["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={...r};for(const[c,d]of Object.entries(i)){if(a.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)&&r[c]!==null&&typeof r[c]=="object"&&!Array.isArray(r[c])?l[c]=this.deepMergeWithState(d,r[c]):l[c]=d}return l}deepMergeInto(e,r,a){for(const[i,l]of Object.entries(r)){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]===a[i]&&(e[i]={...e[i]}),this.deepMergeInto(e[i],l,a[i]||{})):typeof l=="object"&&!Array.isArray(l)&&e[i]===void 0&&a[i]!==null&&typeof a[i]=="object"&&!Array.isArray(a[i])?e[i]={...a[i],...l}:e[i]=l}}createNestedUpdate(e,r,a){const i=e.split(".");if(i.length===1)return{[i[0]]:r};const l={};let c=l,d=a;for(let f=0;f{this.globalStateUpdater({_local:S})};m.push({state:y,setState:w,dataContext:{_local:y||r.data?._local,_global:l?r.data?._global:r.data?._global||i?.state?.get?.(),_computed:r.data?._computed}}),window.__g7LayoutContextStack=m,j.log(`[handleOpenModal] 레이아웃 컨텍스트 스택에 push, 스택 크기: ${m.length}, state:`,y,l?"(direct)":"(fallback via G7Core)")}else j.warn(`[handleOpenModal] 컨텍스트 스택에 push 실패 - setState: ${!!r.setState}, state: ${r.state!==void 0}, G7Core: ${!!i?.state?.getLocal}`);const f=[...a,e];this.globalStateUpdater({modalStack:f,activeModal:e});const g=Vn();if(g?.isEnabled()){const m=a.length>0?a[a.length-1]:void 0;g.trackModalOpen?.({modalId:e,modalName:e,scopeType:"isolated",parentModalId:m,initialState:r.state?{...r.state}:{}})}}async handleCloseModal(e){if(!this.globalStateUpdater){j.warn("Global state updater is not set for closeModal");return}const r=e?.data?._global?.modalStack||[],a=r.length>0?r[r.length-1]:null,i=r.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(a){const d=Vn();d?.isEnabled()&&d.trackModalClose?.(a,e?.state)}this.globalStateUpdater({modalStack:i,activeModal:l})}async handleShowAlert(e,r){let a=e;this.translationEngine&&this.translationContext&&e.startsWith("$t:")&&(a=this.translationEngine.resolveTranslations(e,this.translationContext,r.data)),alert(a)}async handleToast(e,r){const{type:a="info",message:i,icon:l,duration:c}=e;if(a==="error"){const f=r.data?.error;if((f?.error_code==="identity_verification_required"||f?.data?.error_code==="identity_verification_required")&&mt.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,r.data)),this.globalStateUpdater){const g={id:`toast_${Date.now()}_${Math.random().toString(36).substring(2,9)}`,type:a,message:d,...l&&{icon:l},...c&&{duration:c}},S=[...window.G7Core?.state?.get()?.toasts||[],g];this.globalStateUpdater({toasts:S})}else j.log(`[Toast ${a}] ${d}`)}async handleSwitch(e,r){const{cases:a}=e;if(!a){j.warn("switch handler requires cases property");return}const i=this.resolveParams(e.params,r.data);let l;if(i?.value!==void 0?(l=i.value,j.log("switch handler: using params.value as case key:",l)):(l=r.data?.$args?.[0],j.log("switch handler: using $args[0] as case key:",l)),l==null){if(a.default)return j.log("switch handler: case key is undefined, using default case"),await this.executeAction(a.default,r);j.warn("switch handler: case key is not defined and no default case");return}const c=String(l);let d=a[c];if(!d&&a.default&&(j.log(`switch handler: no case found for key "${c}", using default case`),d=a.default),!d){j.warn(`switch handler: no case found for key "${c}" and no default case`);return}return await this.executeAction(d,r)}async handleConditions(e,r){const{conditions:a}=e;if(!a||!Array.isArray(a)){j.warn("conditions handler requires conditions array");return}const i=r.data||{},l=sp(a,i,this.bindingEngine);if(!l.matched){j.log("conditions handler: no matching branch found");return}const c=a[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},r):await this.executeAction(c.then,r)}handleStartInterval(e,r){const a=typeof e.id=="string"?e.id:"",i=Number(e.intervalMs??1e3),l=Array.isArray(e.actions)?e.actions:[];if(a===""||!l.length||i<=0)return j.warn("startInterval requires non-empty id, positive intervalMs, and actions array"),{success:!1};const c=this.intervals.get(a);c&&(clearInterval(c),this.intervals.delete(a));const d=setInterval(()=>{for(const f of l)this.executeAction(f,r).catch(g=>{j.error(`[startInterval:${a}] tick action failed`,g)})},i);return this.intervals.set(a,d),{success:!0,id:a}}handleStopInterval(e){const r=typeof e.id=="string"?e.id:"";if(r==="")return j.warn("stopInterval requires id parameter"),{success:!1};const a=this.intervals.get(r);return a&&(clearInterval(a),this.intervals.delete(r)),{success:!0,id:r}}stopAllIntervals(){for(const e of this.intervals.values())clearInterval(e);this.intervals.clear()}async handleSequence(e,r){const a=e.actions||e.params?.actions;if(!a||!Array.isArray(a)||a.length===0)return j.warn("sequence handler requires non-empty actions array"),[];const i=Vn(),l=i?.isEnabled()&&i.startSequenceExecution?.({eventType:e.type})||"";window.__g7SequenceLocalSync=void 0;const c=[];let d,f=r.state?{...r.state}:{},g=r.isolatedContext?.state?{...r.isolatedContext.state}:{},m=r.data?._computed||{};const y=window.G7Core,w=()=>({_global:y?.state?.get()||{},_local:{...f},_isolated:Object.keys(g).length>0?{...g}:void 0});for(let S=0;S0){const O={},L={...r.data,_local:f,_computed:O,$computed:O,_isolated:g};for(const[q,G]of Object.entries(M))if(typeof G=="string"){const B=G.trim();if(B.startsWith("{{")&&B.endsWith("}}"))try{const K=B.slice(2,-2).trim();O[q]=Gn(K)?this.bindingEngine.evaluatePipeExpression(K,L,{skipCache:!0}):this.bindingEngine.evaluateExpression(K,L,{skipCache:!0})}catch{O[q]=m[q]}}m=O,j.log("[handleSequence] _computed recalculated after setState:",m)}}if(v.handler!=="setState"){const M=window.__g7SequenceLocalSync;if(M&&M!==f){f=M,window.__g7SequenceLocalSync=void 0,j.log("[handleSequence] currentState synchronized from __g7SequenceLocalSync after custom handler:",v.handler);const O=r.data?._computedDefinitions;if(O&&Object.keys(O).length>0){const L={},q={...r.data,_local:f,_computed:L,$computed:L,_isolated:g};for(const[G,B]of Object.entries(O))if(typeof B=="string"){const K=B.trim();if(K.startsWith("{{")&&K.endsWith("}}"))try{const fe=K.slice(2,-2).trim();L[G]=Gn(fe)?this.bindingEngine.evaluatePipeExpression(fe,q,{skipCache:!0}):this.bindingEngine.evaluateExpression(fe,q,{skipCache:!0})}catch{L[G]=m[G]}}m=L,j.log("[handleSequence] _computed recalculated after custom handler:",m)}}}l&&i?.isEnabled()&&i.captureSequenceActionAfter?.(l,S,w(),Date.now()-A,R.data)}catch(R){throw l&&i?.isEnabled()&&(i.captureSequenceActionAfter?.(l,S,w(),Date.now()-A,void 0,R),i.endSequenceExecution?.(l,R)),j.error(`sequence handler: action[${S}] failed:`,R),R}}return window.__g7SequenceLocalSync=void 0,l&&i?.isEnabled()&&i.endSequenceExecution?.(l),c}async handleParallel(e,r){const a=e.actions||e.params?.actions;if(!a||!Array.isArray(a)||a.length===0)return j.warn("parallel handler requires non-empty actions array"),[];j.log(`parallel handler: executing ${a.length} actions in parallel`);const i=r.isolatedContext?{...r.isolatedContext,state:{...r.isolatedContext.state}}:null,l=a.map((f,g)=>{const m={...r,isolatedContext:i};return this.executeAction(f,m).catch(y=>{throw j.error(`parallel handler: action[${g}] failed:`,y),y})}),c=await Promise.allSettled(l),d=c.filter(f=>f.status==="rejected").length;return d>0&&j.warn(`parallel handler: ${d}/${a.length} actions failed`),c}async handleLoadScript(e,r,a){const{src:i,id:l,async:c=!0,defer:d=!1}=e;if(!i)throw new It('loadScript handler requires "src" parameter',r);const f=l||`script_${i.replace(/[^a-zA-Z0-9]/g,"_")}`;return fs.loadedScripts.has(f)?(j.log(`loadScript: script already loaded, skipping: ${f}`),r.onLoad&&await this.executeAction(r.onLoad,a),!0):document.getElementById(f)?(j.log(`loadScript: script element already exists: ${f}`),fs.loadedScripts.add(f),r.onLoad&&await this.executeAction(r.onLoad,a),!0):(j.log(`loadScript: loading script: ${i}`),new Promise((m,y)=>{const w=document.createElement("script");w.id=f,w.src=i,w.async=c,w.defer=d,w.onload=async()=>{if(j.log(`loadScript: script loaded successfully: ${f}`),fs.loadedScripts.add(f),r.onLoad)try{await this.executeAction(r.onLoad,a)}catch(S){j.error("loadScript: onLoad action failed:",S)}m(!0)},w.onerror=S=>{j.error(`loadScript: failed to load script: ${i}`,S),y(new It(`Failed to load script: ${i}`,r))},document.head.appendChild(w)}))}async handleCallExternal(e,r,a){const i=e.constructor,l=e.args||{},c=e.method,d=e.methodArgs||[],f=e.callbackEvent,g=e.embedTarget,m=e.callbackSetState,y=e.callbackAction;if(!i)throw new It('callExternal handler requires "constructor" parameter',r);const w=this.getNestedProperty(window,i);if(!w||typeof w!="function")throw new It(`Constructor not found or not a function: ${i}. Make sure the script is loaded first using loadScript handler.`,r);j.log(`callExternal: calling constructor ${i}`);const S={...l};for(const[A,x]of Object.entries(l))x===!0&&(S[A]=R=>{if(j.log(`callExternal: callback triggered for ${A}`,R),f&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(f,R),m&&a.setState){const M=q=>{const G={};for(const[B,K]of Object.entries(q))typeof K=="string"?G[B]=this.getNestedProperty(R,K):typeof K=="object"&&K!==null&&(G[B]=M(K));return G},O=M(m);j.log("callExternal: callbackSetState mapping result",O);const L=this.deepMergeWithState(O,a.state||{});j.log("callExternal: merged with existing state",L),a.setState(L)}else f&&a.setState&&a.setState({[`${f.replace(/:/g,"_")}_result`]:R});if(y){const M={...a,data:{...a.data,$event:R}},O=Array.isArray(y)?y:[y];for(const L of O)try{this.executeAction(L,M)}catch(q){j.error("callExternal: callbackAction failed:",q)}}});const v=new w(S);if(c&&typeof v[c]=="function"){if(j.log(`callExternal: calling method ${c}`),c==="embed"&&g){const A=document.querySelector(g);if(A)return v[c](A,...d);throw new It(`Embed target element not found: ${g}`,r)}return v[c](...d)}return v}async handleCallExternalEmbed(e,r,a){const i=e.constructor,l=e.args||{},c=e.callbackSetState,d=e.callbackEvent,f=e.layerClassName,g=e.callbackAction;if(!i)throw new It('callExternalEmbed handler requires "constructor" parameter',r);const m=this.getNestedProperty(window,i);if(!m||typeof m!="function")throw new It(`Constructor not found or not a function: ${i}. Make sure the script is loaded first.`,r);j.log(`callExternalEmbed: creating layer for ${i}`);const{layer:y,closeLayer:w}=this.createEmbedLayer(f),S={...l};for(const[A,x]of Object.entries(l))x===!0&&(S[A]=R=>{if(j.log(`callExternalEmbed: callback triggered for ${A}`,R),w(),d&&typeof window<"u"&&window.G7Core?.componentEvent&&window.G7Core.componentEvent.emit(d,R),c&&a.setState){const M=q=>{const G={};for(const[B,K]of Object.entries(q))typeof K=="string"?G[B]=this.getNestedProperty(R,K):typeof K=="object"&&K!==null&&(G[B]=M(K));return G},O=M(c);j.log("callExternalEmbed: callbackSetState mapping result",O);const L=this.deepMergeWithState(O,a.state||{});j.log("callExternalEmbed: merged with existing state",L),a.setState(L)}if(g){const M={...a,data:{...a.data,$event:R}},O=Array.isArray(g)?g:[g];for(const L of O)try{this.executeAction(L,M)}catch(q){j.error("callExternalEmbed: callbackAction failed:",q)}}});const v=new m(S);if(typeof v.embed=="function")v.embed(y),j.log("callExternalEmbed: embedded in layer");else throw w(),new It(`Constructor ${i} does not have embed method`,r);return v}isImeComposing(e){return e?.isComposing===!0||e?.keyCode===229}createEmbedLayer(e){const r=document.createElement("div");r.id="g7-embed-overlay",r.style.cssText=` position: fixed; inset: 0; background-color: rgba(0, 0, 0, 0.5); @@ -47,20 +84,20 @@ 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()},a.appendChild(i),n.appendChild(a),document.body.appendChild(n),{overlay:n,layer:a,closeLayer:l}}getNestedProperty(e,n){return n.split(".").reduce((a,i)=>a&&a[i]!==void 0?a[i]:void 0,e)}async handleSaveToLocalStorage(e,n){const{key:a,value:i}=e;if(!a)return z.error("saveToLocalStorage: key parameter is required"),!1;try{const l=typeof i=="string"?i:JSON.stringify(i);return localStorage.setItem(a,l),z.log(`saveToLocalStorage: saved ${a}`,i),!0}catch(l){return z.error("saveToLocalStorage: failed to save",{key:a,error:l}),!1}}async handleLoadFromLocalStorage(e,n){const{key:a,target:i,stateKey:l,defaultValue:c}=e;if(!a)return z.error("loadFromLocalStorage: key parameter is required"),c;try{const d=localStorage.getItem(a);if(d===null)return z.log(`loadFromLocalStorage: no value found for ${a}, using default`),l&&n.setState&&n.setState({[l]:c}),c;let f;try{f=JSON.parse(d)}catch{f=d}return z.log(`loadFromLocalStorage: loaded ${a}`,f),l&&n.setState&&n.setState({[l]:f}),f}catch(d){return z.error("loadFromLocalStorage: failed to load",{key:a,error:d}),c}}async handleCustomAction(e,n){const a=this.customHandlers.get(e.handler);if(!a){if(this.previewMode){z.warn(`[Preview] Unknown action handler "${e.handler}" — skipped (preview mode)`);return}const i=new jt(`Unknown action handler: ${e.handler}`,e);throw i.unknownHandler=!0,i}return await a(e,n)}resolveParams(e,n){if(!e)return{};const a={};for(const[i,l]of Object.entries(e))i.includes("{{")&&z.warn(`[resolveParams] setState params의 키에 표현식이 포함되어 있습니다: "${i}". 키는 해석되지 않습니다. 배열 항목 수정은 .map()/.filter() 패턴을 사용하세요.`),typeof l=="string"&&l.includes("{{")?a[i]=this.evaluateExpression(l,n):typeof l=="string"?a[i]=l:Array.isArray(l)?a[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?a[i]=l:typeof l=="object"&&l!==null?a[i]=this.resolveParams(l,n):a[i]=l;return a}resolveValue(e,n){return n?this.bindingEngine.resolveBindings(e,n,{skipCache:!0}):e}evaluateExpressions(e,n){let a={};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)&&(a={...a,...c})}else typeof l=="string"&&l.includes("{{")?a[i]=this.evaluateExpression(l,n):typeof l=="object"&&l!==null&&!Array.isArray(l)?a[i]=this.evaluateExpressions(l,n):a[i]=l;return a}evaluateExpressionsIfNeeded(e,n){const a={};for(const[i,l]of Object.entries(e))typeof l=="string"&&l.includes("{{")?a[i]=this.evaluateExpression(l,n):a[i]=l;return a}evaluateExpression(e,n){if(!n)return e;const a=Aa(e);if(a===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=a;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")&&(z.log("[evaluateExpression] expression:",i),z.log("[evaluateExpression] dataContext._global:",l._global),z.log("[evaluateExpression] dataContext._global?.modules:",l._global?.modules));try{const c=Pn(i)?this.bindingEngine.evaluatePipeExpression(i,l,{skipCache:!0}):this.bindingEngine.evaluateExpression(i,l);return i.includes("_global.modules")&&z.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 z.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 a={...this.defaultContext,...n,data:{...this.defaultContext.data,...n?.data}};if(e.confirm){let i=this.resolveValue(e.confirm,a.data);if(this.translationEngine&&this.translationContext&&i.startsWith("$t:")&&(i=this.translationEngine.resolveTranslations(i,this.translationContext,a.data)),!confirm(i))return{success:!1}}try{return await this.executeAction(e,a)}catch(i){if(z.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={...a,data:{...a.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,a){this.customHandlers.set(e,n);const i=qn();i?.isEnabled()&&i.trackHandlerRegistration(e,a?.category??"custom",a?.description,a?.source)}unregisterHandler(e){this.customHandlers.delete(e);const n=qn();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,a,i,l){const c={...a,$event:n,$args:l},d={type:n.type,target:n.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(e,c,i)(d)}handleDebouncedAction(e,n,a,i,l,c){const d=this.normalizeDebounceConfig(e.debounce),f=l||`default-${e.handler}-${Date.now()}`,g=this.extractEventData(n),m=g._changedKeys;if(m&&Array.isArray(m)&&g?.target?.value&&typeof g.target.value=="object"&&!Array.isArray(g.target.value)){const _=this.debounceAccumulatedValues.get(f);if(_){const A={..._};for(const x of m)A[x]=g.target.value[x];g.target.value=A}this.debounceAccumulatedValues.set(f,g.target.value)}const b=this.debounceTimers.get(f);b&&(clearTimeout(b),this.debounceTimers.delete(f));const S=qn();S?.isEnabled()&&S.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 v=!this.debounceTimers.has(f+"_leading");if(d.leading&&v&&(this.debounceTimers.set(f+"_leading",setTimeout(()=>{},0)),this.executeDebouncedAction(e,g,a,i,c),S?.isEnabled()&&S.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,g,a,i,c),S?.isEnabled()&&S.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"}})},A=setTimeout(()=>{this.debounceTimers.delete(f),this.debounceTimers.delete(f+"_leading"),this.pendingDebounceFlushers.delete(f),this.debounceAccumulatedValues.delete(f),_()},d.delay);this.debounceTimers.set(f,A),this.pendingDebounceFlushers.set(f,_)}}clearDebounceTimers(e){if(e)for(const[n,a]of this.debounceTimers)n.startsWith(e+"-")&&(clearTimeout(a),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,a){const i=this.debounceTimers.get(e);i&&(clearTimeout(i),this.debounceTimers.delete(e));const l=setTimeout(()=>{this.debounceTimers.delete(e),this.pendingDebounceFlushers.delete(e),a()},n);this.debounceTimers.set(e,l),this.pendingDebounceFlushers.set(e,a)}flushPendingDebounceTimers(){if(this.pendingDebounceFlushers.size===0)return;const e=new Map(this.pendingDebounceFlushers);for(const[n,a]of e){const i=this.debounceTimers.get(n);i&&(clearTimeout(i),this.debounceTimers.delete(n)),this.debounceTimers.delete(n+"_leading"),this.pendingDebounceFlushers.delete(n),a()}this.globalStateUpdater&&this.globalStateUpdater({})}bindActionsToProps(e,n,a){const i={...e};if(e.actions&&Array.isArray(e.actions)){const l=new Map;for(const m of e.actions){const b=this.resolveActionRef(m),S=b.event?this.normalizeEventPropName(b.event):this.getEventHandlerName(b.type);l.has(S)||l.set(S,[]),l.get(S).push(b)}const c=e.name||e.id||"unknown",d=l.has("onDrop"),f=l.has("onDragOver"),g=l.has("onDragEnter");d&&!f&&(i.onDragOver=m=>{m.preventDefault()}),d&&!g&&(i.onDragEnter=m=>{m.preventDefault()});for(const[m,b]of l)i[m]=(...S)=>{for(const v of b){const _=S[0],A=_&&typeof _=="object"&&"preventDefault"in _;if(A&&(m==="onDragOver"||m==="onDrop")&&_.preventDefault(),A&&v.key&&"key"in _){if(this.isImeComposing(_)){z.log("Key filter skipped (IME composing):",v.key);continue}if(_.key!==v.key){z.log("Key filter not matched:",v.key,"actual:",_.key);continue}z.log("Key filter matched:",v.key)}if(v.debounce){const x=`${c}-${v.handler}-${m}`,L=_&&typeof _=="object"&&!("preventDefault"in _)&&"target"in _&&_.target!==null;let M;if(A)M=_;else if(L){const D={type:"custom",target:_.target,preventDefault:()=>{},stopPropagation:()=>{}};_._changedKeys&&(D._changedKeys=_._changedKeys),M=D}else M=new Event("custom");const R=v.event?{...n,$args:S}:n;this.handleDebouncedAction(v,M,R,a,x,S)}else if(this.flushPendingDebounceTimers(),v.event){const x={...n,$args:S},L=this.resolveEventForHandler(_,A);this.createHandler(v,x,a)(L)}else if(A)this.createHandler(v,n,a)(_);else if(_&&typeof _=="object"&&!("preventDefault"in _)&&"target"in _&&_.target!==null){const L={type:"custom",target:_.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(v,n,a)(L)}}}}return i}getEventHandlerName(e){return cm[e]||`on${e.charAt(0).toUpperCase()}${e.slice(1)}`}normalizeEventPropName(e){return cm[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 a=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(a.has(l))return"[Circular Array]";a.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(a.has(l))return"[Circular Reference]";a.add(l);const d={},f=Object.keys(l),g=f.slice(0,20);for(const m of g)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)}};$(ps,"loadedScripts",new Set);let po=ps,Zl=null;function um(o){return Zl||(Zl=new po(o)),Zl}function uC(o){Zl=o}const dm=ut("TransitionManager");class dC{constructor(){$(this,"isPending",!1);$(this,"subscribers",new Set)}setPending(e){this.isPending!==e&&(dm.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(){dm.log("notifySubscribers:",{isPending:this.isPending,subscriberCount:this.subscribers.size}),this.subscribers.forEach(e=>{e(this.isPending)})}clearSubscribers(){this.subscribers.clear()}}const Hr=new dC,ec=ut("TransitionContext"),fm=N.createContext({isTransitioning:!1}),Bd=({children:o})=>{const[e,n]=N.useState(()=>{const i=Hr.getIsPending();return ec.log("Initial state:",i),i});N.useEffect(()=>{ec.log("Subscribing to TransitionManager");const i=Hr.subscribe(l=>{ec.log("Received isPending update:",l),n(l)});return()=>{ec.log("Unsubscribing from TransitionManager"),i()}},[]);const a=N.useMemo(()=>({isTransitioning:e}),[e]);return dt.jsx(fm.Provider,{value:a,children:o})},hm=()=>N.useContext(fm),tc="__g7LocalInitTracking";function Pd(){const o=globalThis;return o[tc]||(o[tc]={hash:"",timestamp:void 0,consumed:void 0}),o[tc]}function fC(){const o=globalThis;o[tc]={hash:"",timestamp:void 0,consumed:void 0}}function hC(o){Pd().consumed=o}function gC(o){return Pd().consumed===o}function pC(o){return o.globalTrackedKey!==o.trackingKey?"apply":o.instanceHandledKey===o.trackingKey?"skip":"prune"}function mC(o,e){return typeof o=="number"&&typeof e=="number"?Math.max(o,e):e??o}function yC(o,e){if(e===void 0)return o;if(!(o!==null&&typeof o=="object"&&e!==null&&typeof e=="object"&&!gC(o)))return e;const{_forceLocalInit:a,...i}=o,{_forceLocalInit:l,...c}=e,d={...i,...c},f=mC(a,l);return f!==void 0&&(d._forceLocalInit=f),d}function bC(o){return o<768?"mobile":o<1024?"tablet":"desktop"}function gm(o){const e=bC(o);return{width:o,isMobile:e==="mobile",isTablet:e==="tablet",isDesktop:e==="desktop",matchedPreset:e}}const qd=N.createContext(gm(1024)),nc=({children:o,overrideWidth:e})=>{const[n,a]=N.useState(()=>hi.getWidth());N.useEffect(()=>{const c=hi.subscribe(d=>{a(d)});return()=>{c()}},[]);const i=e??n,l=N.useMemo(()=>gm(i),[i]);return dt.jsx(qd.Provider,{value:l,children:o})},Gd=()=>N.useContext(qd);window.G7Core?.createLogger?.("Core:State");function vC(o,e,n,a){const{syncOnControlledChange:i=!0,isEqual:l}=a??{},c=o!==void 0;N.useRef(c);const[d,f]=N.useState(o!==void 0?o:e),g=d,m=N.useRef(o),b=N.useRef(!1);N.useEffect(()=>{if(b.current){m.current=o;return}i&&c&&o!==m.current&&(l?!l(d,o):d!==o)&&f(o),m.current=o},[o,c,i,l,d]);const S=N.useCallback(v=>{const _=typeof v=="function"?v(g):v;(l?l(g,_):g===_)||(b.current=!0,f(_),n?.(_),requestAnimationFrame(()=>{b.current=!1}))},[g,c,n,l]);return[g,S]}function SC(o,e){return o===e?!0:o.length!==e.length?!1:o.every((n,a)=>n===e[a])}function pm(o,e){if(o===e)return!0;const n=Object.keys(o),a=Object.keys(e);return n.length!==a.length?!1:n.every(i=>o[i]===e[i])}const mm=N.createContext({}),wC=({children:o,value:e})=>dt.jsx(mm.Provider,{value:e,children:o}),CC=()=>N.useContext(mm),EC=(o,e)=>{if(!o)return;const n=e.split(".");let a=o;for(const i of n){if(a==null)return;a=a[i]}return a},_C=(o,e,n)=>{const a=e.split(".");if(a.length===1)return{...o,[a[0]]:n};const i={...o};let l=i;for(let c=0;c{os.warn("IsolatedStateContext not available: setState called outside IsolatedStateProvider")},getState:()=>{},mergeState:()=>{os.warn("IsolatedStateContext not available: mergeState called outside IsolatedStateProvider")},stateRef:{current:{}},scopeId:""},ym=N.createContext(AC);let xC=0;function TC(){return`isolated-${++xC}-${Date.now().toString(36)}`}function bm(o,e){if(e==null)return o;if(typeof e!="object"||Array.isArray(e))return e;const n={...o};for(const a of Object.keys(e)){const i=e[a],l=o?.[a];i!==null&&typeof i=="object"&&!Array.isArray(i)&&l!==null&&typeof l=="object"&&!Array.isArray(l)?n[a]=bm(l,i):n[a]=i}return n}function RC(o,e){return e?e.split(".").reduce((n,a)=>n?.[a],o):o}function kC(o,e,n){const a=e.split("."),i={...o};let l=i;for(let c=0;c{const i=N.useRef(e||TC()).current,[l,c]=N.useState(o),d=N.useRef(l);d.current=l;const f=N.useCallback(v=>RC(d.current,v),[]),g=N.useCallback((v,_)=>{c(A=>{const x=kC(A,v,_);return os.log(`[${i}] setState: ${v} =`,_),x})},[i]),m=N.useCallback((v,_="deep")=>{c(A=>{let x;return _==="replace"?x=v:_==="shallow"?x={...A,...v}:x=bm(A,v),os.log(`[${i}] mergeState (${_}):`,v),x})},[i]),b=N.useMemo(()=>({state:l,setState:g,getState:f,mergeState:m,stateRef:d,scopeId:i}),[l,g,f,m,i]),S=N.useMemo(()=>({state:d.current,setState:g,getState:f,mergeState:m}),[g,f,m]);return N.useEffect(()=>{const v=window.G7Core,_=window.__g7IsolatedStates||{};return window.__g7IsolatedStates||(window.__g7IsolatedStates=_),_[i]=S,v&&(v._isolatedStates||(v._isolatedStates={}),v._isolatedStates[i]=l),v?.devTools?.isEnabled?.()&&v.devTools.emit?.("isolated:created",{id:i,state:l}),os.log(`[${i}] IsolatedStateProvider mounted with initial state:`,l),()=>{delete _[i],v?._isolatedStates&&delete v._isolatedStates[i],v?.devTools?.isEnabled?.()&&v.devTools.emit?.("isolated:destroyed",{id:i}),os.log(`[${i}] IsolatedStateProvider unmounted`)}},[i,S]),N.useEffect(()=>{const v=window.G7Core,_=window.__g7IsolatedStates;_?.[i]&&(_[i].state=l),v?._isolatedStates&&(v._isolatedStates[i]=l),v?.devTools?.isEnabled?.()&&v.devTools.emit?.("isolated:updated",{id:i,state:l})},[l,i]),dt.jsx(ym.Provider,{value:b,children:n})},OC=()=>{const o=N.useContext(ym);return o.scopeId?o:null};var ka=Yg();function LC(){for(var o=arguments.length,e=new Array(o),n=0;na=>{e.forEach(i=>i(a))},e)}const rc=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function ls(o){const e=Object.prototype.toString.call(o);return e==="[object Window]"||e==="[object global]"}function Vd(o){return"nodeType"in o}function Ln(o){var e,n;return o?ls(o)?o:Vd(o)&&(e=(n=o.ownerDocument)==null?void 0:n.defaultView)!=null?e:window:window}function Fd(o){const{Document:e}=Ln(o);return o instanceof e}function mo(o){return ls(o)?!1:o instanceof Ln(o).HTMLElement}function vm(o){return o instanceof Ln(o).SVGElement}function cs(o){return o?ls(o)?o.document:Vd(o)?Fd(o)?o:mo(o)||vm(o)?o.ownerDocument:document:document:document}const zr=rc?N.useLayoutEffect:N.useEffect;function Kd(o){const e=N.useRef(o);return zr(()=>{e.current=o}),N.useCallback(function(){for(var n=arguments.length,a=new Array(n),i=0;i{o.current=setInterval(a,i)},[]),n=N.useCallback(()=>{o.current!==null&&(clearInterval(o.current),o.current=null)},[]);return[e,n]}function yo(o,e){e===void 0&&(e=[o]);const n=N.useRef(o);return zr(()=>{n.current!==o&&(n.current=o)},e),n}function bo(o,e){const n=N.useRef();return N.useMemo(()=>{const a=o(n.current);return n.current=a,a},[...e])}function ac(o){const e=Kd(o),n=N.useRef(null),a=N.useCallback(i=>{i!==n.current&&e?.(i,n.current),n.current=i},[]);return[n,a]}function Wd(o){const e=N.useRef();return N.useEffect(()=>{e.current=o},[o]),e.current}let Yd={};function vo(o,e){return N.useMemo(()=>{if(e)return e;const n=Yd[o]==null?0:Yd[o]+1;return Yd[o]=n,o+"-"+n},[o,e])}function Sm(o){return function(e){for(var n=arguments.length,a=new Array(n>1?n-1:0),i=1;i{const d=Object.entries(c);for(const[f,g]of d){const m=l[f];m!=null&&(l[f]=m+o*g)}return l},{...e})}}const us=Sm(1),So=Sm(-1);function $C(o){return"clientX"in o&&"clientY"in o}function Xd(o){if(!o)return!1;const{KeyboardEvent:e}=Ln(o.target);return e&&o instanceof e}function NC(o){if(!o)return!1;const{TouchEvent:e}=Ln(o.target);return e&&o instanceof e}function Jd(o){if(NC(o)){if(o.touches&&o.touches.length){const{clientX:e,clientY:n}=o.touches[0];return{x:e,y:n}}else if(o.changedTouches&&o.changedTouches.length){const{clientX:e,clientY:n}=o.changedTouches[0];return{x:e,y:n}}}return $C(o)?{x:o.clientX,y:o.clientY}:null}const wo=Object.freeze({Translate:{toString(o){if(!o)return;const{x:e,y:n}=o;return"translate3d("+(e?Math.round(e):0)+"px, "+(n?Math.round(n):0)+"px, 0)"}},Scale:{toString(o){if(!o)return;const{scaleX:e,scaleY:n}=o;return"scaleX("+e+") scaleY("+n+")"}},Transform:{toString(o){if(o)return[wo.Translate.toString(o),wo.Scale.toString(o)].join(" ")}},Transition:{toString(o){let{property:e,duration:n,easing:a}=o;return e+" "+n+"ms "+a}}}),wm="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function IC(o){return o.matches(wm)?o:o.querySelector(wm)}const HC={display:"none"};function zC(o){let{id:e,value:n}=o;return Ye.createElement("div",{id:e,style:HC},n)}function jC(o){let{id:e,announcement:n,ariaLiveType:a="assertive"}=o;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 Ye.createElement("div",{id:e,style:i,role:"status","aria-live":a,"aria-atomic":!0},n)}function UC(){const[o,e]=N.useState("");return{announce:N.useCallback(a=>{a!=null&&e(a)},[]),announcement:o}}const Cm=N.createContext(null);function BC(o){const e=N.useContext(Cm);N.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(o)},[o,e])}function PC(){const[o]=N.useState(()=>new Set),e=N.useCallback(a=>(o.add(a),()=>o.delete(a)),[o]);return[N.useCallback(a=>{let{type:i,event:l}=a;o.forEach(c=>{var d;return(d=c[i])==null?void 0:d.call(c,l)})},[o]),e]}const qC={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=()=>{r.parentNode&&r.parentNode.removeChild(r)};i.onclick=l;const c=d=>{this.isImeComposing(d)||d.key==="Escape"&&(l(),document.removeEventListener("keydown",c))};return document.addEventListener("keydown",c),r.onclick=d=>{d.target===r&&l()},a.appendChild(i),r.appendChild(a),document.body.appendChild(r),{overlay:r,layer:a,closeLayer:l}}getNestedProperty(e,r){return r.split(".").reduce((a,i)=>a&&a[i]!==void 0?a[i]:void 0,e)}async handleSaveToLocalStorage(e,r){const{key:a,value:i}=e;if(!a)return j.error("saveToLocalStorage: key parameter is required"),!1;try{const l=typeof i=="string"?i:JSON.stringify(i);return localStorage.setItem(a,l),j.log(`saveToLocalStorage: saved ${a}`,i),!0}catch(l){return j.error("saveToLocalStorage: failed to save",{key:a,error:l}),!1}}async handleLoadFromLocalStorage(e,r){const{key:a,target:i,stateKey:l,defaultValue:c}=e;if(!a)return j.error("loadFromLocalStorage: key parameter is required"),c;try{const d=localStorage.getItem(a);if(d===null)return j.log(`loadFromLocalStorage: no value found for ${a}, using default`),l&&r.setState&&r.setState({[l]:c}),c;let f;try{f=JSON.parse(d)}catch{f=d}return j.log(`loadFromLocalStorage: loaded ${a}`,f),l&&r.setState&&r.setState({[l]:f}),f}catch(d){return j.error("loadFromLocalStorage: failed to load",{key:a,error:d}),c}}async handleCustomAction(e,r){const a=this.customHandlers.get(e.handler);if(!a){if(this.previewMode){j.warn(`[Preview] Unknown action handler "${e.handler}" — skipped (preview mode)`);return}const i=new It(`Unknown action handler: ${e.handler}`,e);throw i.unknownHandler=!0,i}return await a(e,r)}resolveParams(e,r){if(!e)return{};const a={};for(const[i,l]of Object.entries(e))i.includes("{{")&&j.warn(`[resolveParams] setState params의 키에 표현식이 포함되어 있습니다: "${i}". 키는 해석되지 않습니다. 배열 항목 수정은 .map()/.filter() 패턴을 사용하세요.`),typeof l=="string"&&l.includes("{{")?a[i]=this.evaluateExpression(l,r):typeof l=="string"?a[i]=l:Array.isArray(l)?a[i]=l.map(c=>typeof c=="string"&&c.includes("{{")?this.evaluateExpression(c,r):c):typeof l=="object"&&l!==null&&!Array.isArray(l)&&Object.getPrototypeOf(l)!==Object.prototype&&Object.getPrototypeOf(l)!==null?a[i]=l:typeof l=="object"&&l!==null?a[i]=this.resolveParams(l,r):a[i]=l;return a}resolveValue(e,r){return r?this.bindingEngine.resolveBindings(e,r,{skipCache:!0}):e}evaluateExpressions(e,r){let a={};for(const[i,l]of Object.entries(e))if(i==="..."){let c=l;typeof l=="string"&&l.includes("{{")&&(c=this.evaluateExpression(l,r)),c&&typeof c=="object"&&!Array.isArray(c)&&(a={...a,...c})}else typeof l=="string"&&l.includes("{{")?a[i]=this.evaluateExpression(l,r):typeof l=="object"&&l!==null&&!Array.isArray(l)?a[i]=this.evaluateExpressions(l,r):a[i]=l;return a}evaluateExpressionsIfNeeded(e,r){const a={};for(const[i,l]of Object.entries(e))typeof l=="string"&&l.includes("{{")?a[i]=this.evaluateExpression(l,r):a[i]=l;return a}evaluateExpression(e,r){if(!r)return e;const a=Ta(e);if(a===null){let c=r;if(e.includes("_global")){const f=window.G7Core?.state?.get()?._global;f&&(c={...r,_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=a;i=i.replace(/\$args\.(\d+)/g,"$args[$1]");let l=r;if(i.includes("_global")){const d=window.G7Core?.state?.get()?._global;d&&(l={...r,_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=Gn(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,r):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,r){const a={...this.defaultContext,...r,data:{...this.defaultContext.data,...r?.data}};if(e.confirm){let i=this.resolveValue(e.confirm,a.data);if(this.translationEngine&&this.translationContext&&i.startsWith("$t:")&&(i=this.translationEngine.resolveTranslations(i,this.translationContext,a.data)),!confirm(i))return{success:!1}}try{return await this.executeAction(e,a)}catch(i){if(j.error("dispatchAction failed:",i),e.onError){const l=i instanceof It&&i.originalError?{message:i.originalError.message,response:i.originalError.response}:{message:i instanceof Error?i.message:String(i)},c={...a,data:{...a.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,r,a){this.customHandlers.set(e,r);const i=Vn();i?.isEnabled()&&i.trackHandlerRegistration(e,a?.category??"custom",a?.description,a?.source)}unregisterHandler(e){this.customHandlers.delete(e);const r=Vn();r?.isEnabled()&&r.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 r=e.target;if(r&&!("tagName"in r)){const l={type:e.type??"custom",target:{value:r.value,name:r.name??""}};return e._changedKeys&&(l._changedKeys=e._changedKeys),l}const i=r?{value:r.value,name:r.name??"",checked:r.checked??!1,type:r.type??"",tagName:r.tagName}:{};if(e.type==="scroll"&&r){const l=r;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:r?i:null}}executeDebouncedAction(e,r,a,i,l){const c={...a,$event:r,$args:l},d={type:r.type,target:r.target,preventDefault:()=>{},stopPropagation:()=>{}};this.createHandler(e,c,i)(d)}handleDebouncedAction(e,r,a,i,l,c){const d=this.normalizeDebounceConfig(e.debounce),f=l||`default-${e.handler}-${Date.now()}`,g=this.extractEventData(r),m=g._changedKeys;if(m&&Array.isArray(m)&&g?.target?.value&&typeof g.target.value=="object"&&!Array.isArray(g.target.value)){const v=this.debounceAccumulatedValues.get(f);if(v){const A={...v};for(const x of m)A[x]=g.target.value[x];g.target.value=A}this.debounceAccumulatedValues.set(f,g.target.value)}const y=this.debounceTimers.get(f);y&&(clearTimeout(y),this.debounceTimers.delete(f));const w=Vn();w?.isEnabled()&&w.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,g,a,i,c),w?.isEnabled()&&w.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,g,a,i,c),w?.isEnabled()&&w.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"}})},A=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,A),this.pendingDebounceFlushers.set(f,v)}}clearDebounceTimers(e){if(e)for(const[r,a]of this.debounceTimers)r.startsWith(e+"-")&&(clearTimeout(a),this.debounceTimers.delete(r),this.pendingDebounceFlushers.delete(r),this.debounceAccumulatedValues.delete(r));else{for(const r of this.debounceTimers.values())clearTimeout(r);this.debounceTimers.clear(),this.pendingDebounceFlushers.clear(),this.debounceAccumulatedValues.clear()}}debouncedCall(e,r,a){const i=this.debounceTimers.get(e);i&&(clearTimeout(i),this.debounceTimers.delete(e));const l=setTimeout(()=>{this.debounceTimers.delete(e),this.pendingDebounceFlushers.delete(e),a()},r);this.debounceTimers.set(e,l),this.pendingDebounceFlushers.set(e,a)}flushPendingDebounceTimers(){if(this.pendingDebounceFlushers.size===0)return;const e=new Map(this.pendingDebounceFlushers);for(const[r,a]of e){const i=this.debounceTimers.get(r);i&&(clearTimeout(i),this.debounceTimers.delete(r)),this.debounceTimers.delete(r+"_leading"),this.pendingDebounceFlushers.delete(r),a()}this.globalStateUpdater&&this.globalStateUpdater({})}bindActionsToProps(e,r,a){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),w=y.event?this.normalizeEventPropName(y.event):this.getEventHandlerName(y.type);l.has(w)||l.set(w,[]),l.get(w).push(y)}const c=e.name||e.id||"unknown",d=l.has("onDrop"),f=l.has("onDragOver"),g=l.has("onDragEnter");d&&!f&&(i.onDragOver=m=>{m.preventDefault()}),d&&!g&&(i.onDragEnter=m=>{m.preventDefault()});for(const[m,y]of l)i[m]=(...w)=>{for(const S of y){const v=w[0],A=v&&typeof v=="object"&&"preventDefault"in v;if(A&&(m==="onDragOver"||m==="onDrop")&&v.preventDefault(),A&&S.key&&"key"in v){if(this.isImeComposing(v)){j.log("Key filter skipped (IME composing):",S.key);continue}if(v.key!==S.key){j.log("Key filter not matched:",S.key,"actual:",v.key);continue}j.log("Key filter matched:",S.key)}if(S.debounce){const x=`${c}-${S.handler}-${m}`,R=v&&typeof v=="object"&&!("preventDefault"in v)&&"target"in v&&v.target!==null;let M;if(A)M=v;else if(R){const L={type:"custom",target:v.target,preventDefault:()=>{},stopPropagation:()=>{}};v._changedKeys&&(L._changedKeys=v._changedKeys),M=L}else M=new Event("custom");const O=S.event?{...r,$args:w}:r;this.handleDebouncedAction(S,M,O,a,x,w)}else if(this.flushPendingDebounceTimers(),S.event){const x={...r,$args:w},R=this.resolveEventForHandler(v,A);this.createHandler(S,x,a)(R)}else if(A)this.createHandler(S,r,a)(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,r,a)(R)}}}}return i}getEventHandlerName(e){return rm[e]||`on${e.charAt(0).toUpperCase()}${e.slice(1)}`}normalizeEventPropName(e){return rm[e]??e}resolveEventForHandler(e,r){if(r)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,r=5){const a=new WeakSet,i=(l,c)=>{if(l==null||typeof l=="string"||typeof l=="number"||typeof l=="boolean")return l;if(c>r)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(a.has(l))return"[Circular Array]";a.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(a.has(l))return"[Circular Reference]";a.add(l);const d={},f=Object.keys(l),g=f.slice(0,20);for(const m of g)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)}};$(fs,"loadedScripts",new Set);let mo=fs,oc=null;function am(o){return oc||(oc=new mo(o)),oc}function P0(o){oc=o}const im=ut("TransitionManager");class q0{constructor(){$(this,"isPending",!1);$(this,"subscribers",new Set)}setPending(e){this.isPending!==e&&(im.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(){im.log("notifySubscribers:",{isPending:this.isPending,subscriberCount:this.subscribers.size}),this.subscribers.forEach(e=>{e(this.isPending)})}clearSubscribers(){this.subscribers.clear()}}const zr=new q0,lc=ut("TransitionContext"),sm=N.createContext({isTransitioning:!1}),Id=({children:o})=>{const[e,r]=N.useState(()=>{const i=zr.getIsPending();return lc.log("Initial state:",i),i});N.useEffect(()=>{lc.log("Subscribing to TransitionManager");const i=zr.subscribe(l=>{lc.log("Received isPending update:",l),r(l)});return()=>{lc.log("Unsubscribing from TransitionManager"),i()}},[]);const a=N.useMemo(()=>({isTransitioning:e}),[e]);return dt.jsx(sm.Provider,{value:a,children:o})},om=()=>N.useContext(sm),cc="__g7LocalInitTracking";function Hd(){const o=globalThis;return o[cc]||(o[cc]={hash:"",timestamp:void 0,consumed:void 0}),o[cc]}function G0(){const o=globalThis;o[cc]={hash:"",timestamp:void 0,consumed:void 0}}function V0(o){Hd().consumed=o}function F0(o){return Hd().consumed===o}function K0(o){return o.globalTrackedKey!==o.trackingKey?"apply":o.instanceHandledKey===o.trackingKey?"skip":"prune"}function W0(o,e){return typeof o=="number"&&typeof e=="number"?Math.max(o,e):e??o}function Y0(o,e){if(e===void 0)return o;if(!(o!==null&&typeof o=="object"&&e!==null&&typeof e=="object"&&!F0(o)))return e;const{_forceLocalInit:a,...i}=o,{_forceLocalInit:l,...c}=e,d={...i,...c},f=W0(a,l);return f!==void 0&&(d._forceLocalInit=f),d}function X0(o){return o<768?"mobile":o<1024?"tablet":"desktop"}function lm(o){const e=X0(o);return{width:o,isMobile:e==="mobile",isTablet:e==="tablet",isDesktop:e==="desktop",matchedPreset:e}}const jd=N.createContext(lm(1024)),uc=({children:o,overrideWidth:e})=>{const[r,a]=N.useState(()=>mi.getWidth());N.useEffect(()=>{const c=mi.subscribe(d=>{a(d)});return()=>{c()}},[]);const i=e??r,l=N.useMemo(()=>lm(i),[i]);return dt.jsx(jd.Provider,{value:l,children:o})},zd=()=>N.useContext(jd);window.G7Core?.createLogger?.("Core:State");function J0(o,e,r,a){const{syncOnControlledChange:i=!0,isEqual:l}=a??{},c=o!==void 0;N.useRef(c);const[d,f]=N.useState(o!==void 0?o:e),g=d,m=N.useRef(o),y=N.useRef(!1);N.useEffect(()=>{if(y.current){m.current=o;return}i&&c&&o!==m.current&&(l?!l(d,o):d!==o)&&f(o),m.current=o},[o,c,i,l,d]);const w=N.useCallback(S=>{const v=typeof S=="function"?S(g):S;(l?l(g,v):g===v)||(y.current=!0,f(v),r?.(v),requestAnimationFrame(()=>{y.current=!1}))},[g,c,r,l]);return[g,w]}function Q0(o,e){return o===e?!0:o.length!==e.length?!1:o.every((r,a)=>r===e[a])}function cm(o,e){if(o===e)return!0;const r=Object.keys(o),a=Object.keys(e);return r.length!==a.length?!1:r.every(i=>o[i]===e[i])}const um=N.createContext({}),Z0=({children:o,value:e})=>dt.jsx(um.Provider,{value:e,children:o}),eC=()=>N.useContext(um),tC=(o,e)=>{if(!o)return;const r=e.split(".");let a=o;for(const i of r){if(a==null)return;a=a[i]}return a},nC=(o,e,r)=>{const a=e.split(".");if(a.length===1)return{...o,[a[0]]:r};const i={...o};let l=i;for(let c=0;c{as.warn("IsolatedStateContext not available: setState called outside IsolatedStateProvider")},getState:()=>{},mergeState:()=>{as.warn("IsolatedStateContext not available: mergeState called outside IsolatedStateProvider")},stateRef:{current:{}},scopeId:""},dm=N.createContext(rC);let aC=0;function iC(){return`isolated-${++aC}-${Date.now().toString(36)}`}function fm(o,e){if(e==null)return o;if(typeof e!="object"||Array.isArray(e))return e;const r={...o};for(const a of Object.keys(e)){const i=e[a],l=o?.[a];i!==null&&typeof i=="object"&&!Array.isArray(i)&&l!==null&&typeof l=="object"&&!Array.isArray(l)?r[a]=fm(l,i):r[a]=i}return r}function sC(o,e){return e?e.split(".").reduce((r,a)=>r?.[a],o):o}function oC(o,e,r){const a=e.split("."),i={...o};let l=i;for(let c=0;c{const i=N.useRef(e||iC()).current,[l,c]=N.useState(o),d=N.useRef(l);d.current=l;const f=N.useCallback(S=>sC(d.current,S),[]),g=N.useCallback((S,v)=>{c(A=>{const x=oC(A,S,v);return as.log(`[${i}] setState: ${S} =`,v),x})},[i]),m=N.useCallback((S,v="deep")=>{c(A=>{let x;return v==="replace"?x=S:v==="shallow"?x={...A,...S}:x=fm(A,S),as.log(`[${i}] mergeState (${v}):`,S),x})},[i]),y=N.useMemo(()=>({state:l,setState:g,getState:f,mergeState:m,stateRef:d,scopeId:i}),[l,g,f,m,i]),w=N.useMemo(()=>({state:d.current,setState:g,getState:f,mergeState:m}),[g,f,m]);return N.useEffect(()=>{const S=window.G7Core,v=window.__g7IsolatedStates||{};return window.__g7IsolatedStates||(window.__g7IsolatedStates=v),v[i]=w,S&&(S._isolatedStates||(S._isolatedStates={}),S._isolatedStates[i]=l),S?.devTools?.isEnabled?.()&&S.devTools.emit?.("isolated:created",{id:i,state:l}),as.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}),as.log(`[${i}] IsolatedStateProvider unmounted`)}},[i,w]),N.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]),dt.jsx(dm.Provider,{value:y,children:r})},cC=()=>{const o=N.useContext(dm);return o.scopeId?o:null};var Oa=jg();function uC(){for(var o=arguments.length,e=new Array(o),r=0;ra=>{e.forEach(i=>i(a))},e)}const dc=typeof window<"u"&&typeof window.document<"u"&&typeof window.document.createElement<"u";function is(o){const e=Object.prototype.toString.call(o);return e==="[object Window]"||e==="[object global]"}function Ud(o){return"nodeType"in o}function Dn(o){var e,r;return o?is(o)?o:Ud(o)&&(e=(r=o.ownerDocument)==null?void 0:r.defaultView)!=null?e:window:window}function Bd(o){const{Document:e}=Dn(o);return o instanceof e}function yo(o){return is(o)?!1:o instanceof Dn(o).HTMLElement}function hm(o){return o instanceof Dn(o).SVGElement}function ss(o){return o?is(o)?o.document:Ud(o)?Bd(o)?o:yo(o)||hm(o)?o.ownerDocument:document:document:document}const Ur=dc?N.useLayoutEffect:N.useEffect;function Pd(o){const e=N.useRef(o);return Ur(()=>{e.current=o}),N.useCallback(function(){for(var r=arguments.length,a=new Array(r),i=0;i{o.current=setInterval(a,i)},[]),r=N.useCallback(()=>{o.current!==null&&(clearInterval(o.current),o.current=null)},[]);return[e,r]}function bo(o,e){e===void 0&&(e=[o]);const r=N.useRef(o);return Ur(()=>{r.current!==o&&(r.current=o)},e),r}function vo(o,e){const r=N.useRef();return N.useMemo(()=>{const a=o(r.current);return r.current=a,a},[...e])}function fc(o){const e=Pd(o),r=N.useRef(null),a=N.useCallback(i=>{i!==r.current&&e?.(i,r.current),r.current=i},[]);return[r,a]}function qd(o){const e=N.useRef();return N.useEffect(()=>{e.current=o},[o]),e.current}let Gd={};function So(o,e){return N.useMemo(()=>{if(e)return e;const r=Gd[o]==null?0:Gd[o]+1;return Gd[o]=r,o+"-"+r},[o,e])}function gm(o){return function(e){for(var r=arguments.length,a=new Array(r>1?r-1:0),i=1;i{const d=Object.entries(c);for(const[f,g]of d){const m=l[f];m!=null&&(l[f]=m+o*g)}return l},{...e})}}const os=gm(1),wo=gm(-1);function fC(o){return"clientX"in o&&"clientY"in o}function Vd(o){if(!o)return!1;const{KeyboardEvent:e}=Dn(o.target);return e&&o instanceof e}function hC(o){if(!o)return!1;const{TouchEvent:e}=Dn(o.target);return e&&o instanceof e}function Fd(o){if(hC(o)){if(o.touches&&o.touches.length){const{clientX:e,clientY:r}=o.touches[0];return{x:e,y:r}}else if(o.changedTouches&&o.changedTouches.length){const{clientX:e,clientY:r}=o.changedTouches[0];return{x:e,y:r}}}return fC(o)?{x:o.clientX,y:o.clientY}:null}const Co=Object.freeze({Translate:{toString(o){if(!o)return;const{x:e,y:r}=o;return"translate3d("+(e?Math.round(e):0)+"px, "+(r?Math.round(r):0)+"px, 0)"}},Scale:{toString(o){if(!o)return;const{scaleX:e,scaleY:r}=o;return"scaleX("+e+") scaleY("+r+")"}},Transform:{toString(o){if(o)return[Co.Translate.toString(o),Co.Scale.toString(o)].join(" ")}},Transition:{toString(o){let{property:e,duration:r,easing:a}=o;return e+" "+r+"ms "+a}}}),pm="a,frame,iframe,input:not([type=hidden]):not(:disabled),select:not(:disabled),textarea:not(:disabled),button:not(:disabled),*[tabindex]";function gC(o){return o.matches(pm)?o:o.querySelector(pm)}const pC={display:"none"};function mC(o){let{id:e,value:r}=o;return We.createElement("div",{id:e,style:pC},r)}function yC(o){let{id:e,announcement:r,ariaLiveType:a="assertive"}=o;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":a,"aria-atomic":!0},r)}function bC(){const[o,e]=N.useState("");return{announce:N.useCallback(a=>{a!=null&&e(a)},[]),announcement:o}}const mm=N.createContext(null);function vC(o){const e=N.useContext(mm);N.useEffect(()=>{if(!e)throw new Error("useDndMonitor must be used within a children of ");return e(o)},[o,e])}function SC(){const[o]=N.useState(()=>new Set),e=N.useCallback(a=>(o.add(a),()=>o.delete(a)),[o]);return[N.useCallback(a=>{let{type:i,event:l}=a;o.forEach(c=>{var d;return(d=c[i])==null?void 0:d.call(c,l)})},[o]),e]}const wC={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. - `},GC={onDragStart(o){let{active:e}=o;return"Picked up draggable item "+e.id+"."},onDragOver(o){let{active:e,over:n}=o;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(o){let{active:e,over:n}=o;return n?"Draggable item "+e.id+" was dropped over droppable area "+n.id:"Draggable item "+e.id+" was dropped."},onDragCancel(o){let{active:e}=o;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function VC(o){let{announcements:e=GC,container:n,hiddenTextDescribedById:a,screenReaderInstructions:i=qC}=o;const{announce:l,announcement:c}=UC(),d=vo("DndLiveRegion"),[f,g]=N.useState(!1);if(N.useEffect(()=>{g(!0)},[]),BC(N.useMemo(()=>({onDragStart(b){let{active:S}=b;l(e.onDragStart({active:S}))},onDragMove(b){let{active:S,over:v}=b;e.onDragMove&&l(e.onDragMove({active:S,over:v}))},onDragOver(b){let{active:S,over:v}=b;l(e.onDragOver({active:S,over:v}))},onDragEnd(b){let{active:S,over:v}=b;l(e.onDragEnd({active:S,over:v}))},onDragCancel(b){let{active:S,over:v}=b;l(e.onDragCancel({active:S,over:v}))}}),[l,e])),!f)return null;const m=Ye.createElement(Ye.Fragment,null,Ye.createElement(zC,{id:a,value:i.draggable}),Ye.createElement(jC,{id:d,announcement:c}));return n?ka.createPortal(m,n):m}var tn;(function(o){o.DragStart="dragStart",o.DragMove="dragMove",o.DragEnd="dragEnd",o.DragCancel="dragCancel",o.DragOver="dragOver",o.RegisterDroppable="registerDroppable",o.SetDroppableDisabled="setDroppableDisabled",o.UnregisterDroppable="unregisterDroppable"})(tn||(tn={}));function ic(){}function Em(o,e){return N.useMemo(()=>({sensor:o,options:e??{}}),[o,e])}function FC(){for(var o=arguments.length,e=new Array(o),n=0;n[...e].filter(a=>a!=null),[...e])}const Sr=Object.freeze({x:0,y:0});function _m(o,e){return Math.sqrt(Math.pow(o.x-e.x,2)+Math.pow(o.y-e.y,2))}function Am(o,e){let{data:{value:n}}=o,{data:{value:a}}=e;return n-a}function KC(o,e){let{data:{value:n}}=o,{data:{value:a}}=e;return a-n}function xm(o){let{left:e,top:n,height:a,width:i}=o;return[{x:e,y:n},{x:e+i,y:n},{x:e,y:n+a},{x:e+i,y:n+a}]}function Tm(o,e){if(!o||o.length===0)return null;const[n]=o;return n[e]}function Rm(o,e,n){return e===void 0&&(e=o.left),n===void 0&&(n=o.top),{x:e+o.width*.5,y:n+o.height*.5}}const WC=o=>{let{collisionRect:e,droppableRects:n,droppableContainers:a}=o;const i=Rm(e,e.left,e.top),l=[];for(const c of a){const{id:d}=c,f=n.get(d);if(f){const g=_m(Rm(f),i);l.push({id:d,data:{droppableContainer:c,value:g}})}}return l.sort(Am)},YC=o=>{let{collisionRect:e,droppableRects:n,droppableContainers:a}=o;const i=xm(e),l=[];for(const c of a){const{id:d}=c,f=n.get(d);if(f){const g=xm(f),m=i.reduce((S,v,_)=>S+_m(g[_],v),0),b=Number((m/4).toFixed(4));l.push({id:d,data:{droppableContainer:c,value:b}})}}return l.sort(Am)};function XC(o,e){const n=Math.max(e.top,o.top),a=Math.max(e.left,o.left),i=Math.min(e.left+e.width,o.left+o.width),l=Math.min(e.top+e.height,o.top+o.height),c=i-a,d=l-n;if(a{let{collisionRect:e,droppableRects:n,droppableContainers:a}=o;const i=[];for(const l of a){const{id:c}=l,d=n.get(c);if(d){const f=XC(d,e);f>0&&i.push({id:c,data:{droppableContainer:l,value:f}})}}return i.sort(KC)};function QC(o,e,n){return{...o,scaleX:e&&n?e.width/n.width:1,scaleY:e&&n?e.height/n.height:1}}function km(o,e){return o&&e?{x:o.left-e.left,y:o.top-e.top}:Sr}function ZC(o){return function(n){for(var a=arguments.length,i=new Array(a>1?a-1:0),l=1;l({...c,top:c.top+o*d.y,bottom:c.bottom+o*d.y,left:c.left+o*d.x,right:c.right+o*d.x}),{...n})}}const eE=ZC(1);function tE(o){if(o.startsWith("matrix3d(")){const e=o.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(o.startsWith("matrix(")){const e=o.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function nE(o,e,n){const a=tE(e);if(!a)return o;const{scaleX:i,scaleY:l,x:c,y:d}=a,f=o.left-c-(1-i)*parseFloat(n),g=o.top-d-(1-l)*parseFloat(n.slice(n.indexOf(" ")+1)),m=i?o.width/i:o.width,b=l?o.height/l:o.height;return{width:m,height:b,top:g,right:f+m,bottom:g+b,left:f}}const rE={ignoreTransform:!1};function ds(o,e){e===void 0&&(e=rE);let n=o.getBoundingClientRect();if(e.ignoreTransform){const{transform:g,transformOrigin:m}=Ln(o).getComputedStyle(o);g&&(n=nE(n,g,m))}const{top:a,left:i,width:l,height:c,bottom:d,right:f}=n;return{top:a,left:i,width:l,height:c,bottom:d,right:f}}function Dm(o){return ds(o,{ignoreTransform:!0})}function aE(o){const e=o.innerWidth,n=o.innerHeight;return{top:0,left:0,right:e,bottom:n,width:e,height:n}}function iE(o,e){return e===void 0&&(e=Ln(o).getComputedStyle(o)),e.position==="fixed"}function sE(o,e){e===void 0&&(e=Ln(o).getComputedStyle(o));const n=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const l=e[i];return typeof l=="string"?n.test(l):!1})}function sc(o,e){const n=[];function a(i){if(e!=null&&n.length>=e||!i)return n;if(Fd(i)&&i.scrollingElement!=null&&!n.includes(i.scrollingElement))return n.push(i.scrollingElement),n;if(!mo(i)||vm(i)||n.includes(i))return n;const l=Ln(o).getComputedStyle(i);return i!==o&&sE(i,l)&&n.push(i),iE(i,l)?n:a(i.parentNode)}return o?a(o):n}function Om(o){const[e]=sc(o,1);return e??null}function Qd(o){return!rc||!o?null:ls(o)?o:Vd(o)?Fd(o)||o===cs(o).scrollingElement?window:mo(o)?o:null:null}function Lm(o){return ls(o)?o.scrollX:o.scrollLeft}function Mm(o){return ls(o)?o.scrollY:o.scrollTop}function Zd(o){return{x:Lm(o),y:Mm(o)}}var un;(function(o){o[o.Forward=1]="Forward",o[o.Backward=-1]="Backward"})(un||(un={}));function $m(o){return!rc||!o?!1:o===document.scrollingElement}function Nm(o){const e={x:0,y:0},n=$m(o)?{height:window.innerHeight,width:window.innerWidth}:{height:o.clientHeight,width:o.clientWidth},a={x:o.scrollWidth-n.width,y:o.scrollHeight-n.height},i=o.scrollTop<=e.y,l=o.scrollLeft<=e.x,c=o.scrollTop>=a.y,d=o.scrollLeft>=a.x;return{isTop:i,isLeft:l,isBottom:c,isRight:d,maxScroll:a,minScroll:e}}const oE={x:.2,y:.2};function lE(o,e,n,a,i){let{top:l,left:c,right:d,bottom:f}=n;a===void 0&&(a=10),i===void 0&&(i=oE);const{isTop:g,isBottom:m,isLeft:b,isRight:S}=Nm(o),v={x:0,y:0},_={x:0,y:0},A={height:e.height*i.y,width:e.width*i.x};return!g&&l<=e.top+A.height?(v.y=un.Backward,_.y=a*Math.abs((e.top+A.height-l)/A.height)):!m&&f>=e.bottom-A.height&&(v.y=un.Forward,_.y=a*Math.abs((e.bottom-A.height-f)/A.height)),!S&&d>=e.right-A.width?(v.x=un.Forward,_.x=a*Math.abs((e.right-A.width-d)/A.width)):!b&&c<=e.left+A.width&&(v.x=un.Backward,_.x=a*Math.abs((e.left+A.width-c)/A.width)),{direction:v,speed:_}}function cE(o){if(o===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:a,bottom:i}=o.getBoundingClientRect();return{top:e,left:n,right:a,bottom:i,width:o.clientWidth,height:o.clientHeight}}function Im(o){return o.reduce((e,n)=>us(e,Zd(n)),Sr)}function uE(o){return o.reduce((e,n)=>e+Lm(n),0)}function dE(o){return o.reduce((e,n)=>e+Mm(n),0)}function fE(o,e){if(e===void 0&&(e=ds),!o)return;const{top:n,left:a,bottom:i,right:l}=e(o);Om(o)&&(i<=0||l<=0||n>=window.innerHeight||a>=window.innerWidth)&&o.scrollIntoView({block:"center",inline:"center"})}const hE=[["x",["left","right"],uE],["y",["top","bottom"],dE]];class ef{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 a=sc(n),i=Im(a);this.rect={...e},this.width=e.width,this.height=e.height;for(const[l,c,d]of hE)for(const f of c)Object.defineProperty(this,f,{get:()=>{const g=d(a),m=i[l]-g;return this.rect[f]+m},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Co{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(n=>{var a;return(a=this.target)==null?void 0:a.removeEventListener(...n)})},this.target=e}add(e,n,a){var i;(i=this.target)==null||i.addEventListener(e,n,a),this.listeners.push([e,n,a])}}function gE(o){const{EventTarget:e}=Ln(o);return o instanceof e?o:cs(o)}function tf(o,e){const n=Math.abs(o.x),a=Math.abs(o.y);return typeof e=="number"?Math.sqrt(n**2+a**2)>e:"x"in e&&"y"in e?n>e.x&&a>e.y:"x"in e?n>e.x:"y"in e?a>e.y:!1}var rr;(function(o){o.Click="click",o.DragStart="dragstart",o.Keydown="keydown",o.ContextMenu="contextmenu",o.Resize="resize",o.SelectionChange="selectionchange",o.VisibilityChange="visibilitychange"})(rr||(rr={}));function Hm(o){o.preventDefault()}function pE(o){o.stopPropagation()}var ot;(function(o){o.Space="Space",o.Down="ArrowDown",o.Right="ArrowRight",o.Left="ArrowLeft",o.Up="ArrowUp",o.Esc="Escape",o.Enter="Enter",o.Tab="Tab"})(ot||(ot={}));const zm={start:[ot.Space,ot.Enter],cancel:[ot.Esc],end:[ot.Space,ot.Enter,ot.Tab]},mE=(o,e)=>{let{currentCoordinates:n}=e;switch(o.code){case ot.Right:return{...n,x:n.x+25};case ot.Left:return{...n,x:n.x-25};case ot.Down:return{...n,y:n.y+25};case ot.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 Co(cs(n)),this.windowListeners=new Co(Ln(n)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(rr.Resize,this.handleCancel),this.windowListeners.add(rr.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(rr.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:n}=this.props,a=e.node.current;a&&fE(a),n(Sr)}handleKeyDown(e){if(Xd(e)){const{active:n,context:a,options:i}=this.props,{keyboardCodes:l=zm,coordinateGetter:c=mE,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:g}=a.current,m=g?{x:g.left,y:g.top}:Sr;this.referenceCoordinates||(this.referenceCoordinates=m);const b=c(e,{active:n,context:a.current,currentCoordinates:m});if(b){const S=So(b,m),v={x:0,y:0},{scrollableAncestors:_}=a.current;for(const A of _){const x=e.code,{isTop:L,isRight:M,isLeft:R,isBottom:D,maxScroll:B,minScroll:q}=Nm(A),P=cE(A),K={x:Math.min(x===ot.Right?P.right-P.width/2:P.right,Math.max(x===ot.Right?P.left:P.left+P.width/2,b.x)),y:Math.min(x===ot.Down?P.bottom-P.height/2:P.bottom,Math.max(x===ot.Down?P.top:P.top+P.height/2,b.y))},ge=x===ot.Right&&!M||x===ot.Left&&!R,Ee=x===ot.Down&&!D||x===ot.Up&&!L;if(ge&&K.x!==b.x){const Se=A.scrollLeft+S.x,Ue=x===ot.Right&&Se<=B.x||x===ot.Left&&Se>=q.x;if(Ue&&!S.y){A.scrollTo({left:Se,behavior:d});return}Ue?v.x=A.scrollLeft-Se:v.x=x===ot.Right?A.scrollLeft-B.x:A.scrollLeft-q.x,v.x&&A.scrollBy({left:-v.x,behavior:d});break}else if(Ee&&K.y!==b.y){const Se=A.scrollTop+S.y,Ue=x===ot.Down&&Se<=B.y||x===ot.Up&&Se>=q.y;if(Ue&&!S.x){A.scrollTo({top:Se,behavior:d});return}Ue?v.y=A.scrollTop-Se:v.y=x===ot.Down?A.scrollTop-B.y:A.scrollTop-q.y,v.y&&A.scrollBy({top:-v.y,behavior:d});break}}this.handleMove(e,us(So(b,this.referenceCoordinates),v))}}}handleMove(e,n){const{onMove:a}=this.props;e.preventDefault(),a(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:(o,e,n)=>{let{keyboardCodes:a=zm,onActivation:i}=e,{active:l}=n;const{code:c}=o.nativeEvent;if(a.start.includes(c)){const d=l.activatorNode.current;return d&&o.target!==d?!1:(o.preventDefault(),i?.({event:o.nativeEvent}),!0)}return!1}}];function jm(o){return!!(o&&"distance"in o)}function Um(o){return!!(o&&"delay"in o)}class rf{constructor(e,n,a){var i;a===void 0&&(a=gE(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=cs(c),this.documentListeners=new Co(this.document),this.listeners=new Co(a),this.windowListeners=new Co(Ln(c)),this.initialCoordinates=(i=Jd(l))!=null?i:Sr,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:a}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(rr.Resize,this.handleCancel),this.windowListeners.add(rr.DragStart,Hm),this.windowListeners.add(rr.VisibilityChange,this.handleCancel),this.windowListeners.add(rr.ContextMenu,Hm),this.documentListeners.add(rr.Keydown,this.handleKeydown),n){if(a!=null&&a({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if(Um(n)){this.timeoutId=setTimeout(this.handleStart,n.delay),this.handlePending(n);return}if(jm(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:a,onPending:i}=this.props;i(a,e,this.initialCoordinates,n)}handleStart(){const{initialCoordinates:e}=this,{onStart:n}=this.props;e&&(this.activated=!0,this.documentListeners.add(rr.Click,pE,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(rr.SelectionChange,this.removeTextSelection),n(e))}handleMove(e){var n;const{activated:a,initialCoordinates:i,props:l}=this,{onMove:c,options:{activationConstraint:d}}=l;if(!i)return;const f=(n=Jd(e))!=null?n:Sr,g=So(i,f);if(!a&&d){if(jm(d)){if(d.tolerance!=null&&tf(g,d.tolerance))return this.handleCancel();if(tf(g,d.distance))return this.handleStart()}if(Um(d)&&tf(g,d.tolerance))return this.handleCancel();this.handlePending(d,g);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===ot.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const yE={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class af extends rf{constructor(e){const{event:n}=e,a=cs(n.target);super(e,yE,a)}}af.activators=[{eventName:"onPointerDown",handler:(o,e)=>{let{nativeEvent:n}=o,{onActivation:a}=e;return!n.isPrimary||n.button!==0?!1:(a?.({event:n}),!0)}}];const bE={move:{name:"mousemove"},end:{name:"mouseup"}};var sf;(function(o){o[o.RightClick=2]="RightClick"})(sf||(sf={}));class vE extends rf{constructor(e){super(e,bE,cs(e.event.target))}}vE.activators=[{eventName:"onMouseDown",handler:(o,e)=>{let{nativeEvent:n}=o,{onActivation:a}=e;return n.button===sf.RightClick?!1:(a?.({event:n}),!0)}}];const of={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class SE extends rf{constructor(e){super(e,of)}static setup(){return window.addEventListener(of.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(of.move.name,e)};function e(){}}}SE.activators=[{eventName:"onTouchStart",handler:(o,e)=>{let{nativeEvent:n}=o,{onActivation:a}=e;const{touches:i}=n;return i.length>1?!1:(a?.({event:n}),!0)}}];var Eo;(function(o){o[o.Pointer=0]="Pointer",o[o.DraggableRect=1]="DraggableRect"})(Eo||(Eo={}));var oc;(function(o){o[o.TreeOrder=0]="TreeOrder",o[o.ReversedTreeOrder=1]="ReversedTreeOrder"})(oc||(oc={}));function wE(o){let{acceleration:e,activator:n=Eo.Pointer,canScroll:a,draggingRect:i,enabled:l,interval:c=5,order:d=oc.TreeOrder,pointerCoordinates:f,scrollableAncestors:g,scrollableAncestorRects:m,delta:b,threshold:S}=o;const v=EE({delta:b,disabled:!l}),[_,A]=MC(),x=N.useRef({x:0,y:0}),L=N.useRef({x:0,y:0}),M=N.useMemo(()=>{switch(n){case Eo.Pointer:return f?{top:f.y,bottom:f.y,left:f.x,right:f.x}:null;case Eo.DraggableRect:return i}},[n,i,f]),R=N.useRef(null),D=N.useCallback(()=>{const q=R.current;if(!q)return;const P=x.current.x*L.current.x,K=x.current.y*L.current.y;q.scrollBy(P,K)},[]),B=N.useMemo(()=>d===oc.TreeOrder?[...g].reverse():g,[d,g]);N.useEffect(()=>{if(!l||!g.length||!M){A();return}for(const q of B){if(a?.(q)===!1)continue;const P=g.indexOf(q),K=m[P];if(!K)continue;const{direction:ge,speed:Ee}=lE(q,K,M,e,S);for(const Se of["x","y"])v[Se][ge[Se]]||(Ee[Se]=0,ge[Se]=0);if(Ee.x>0||Ee.y>0){A(),R.current=q,_(D,c),x.current=Ee,L.current=ge;return}}x.current={x:0,y:0},L.current={x:0,y:0},A()},[e,D,a,A,l,c,JSON.stringify(M),JSON.stringify(v),_,g,B,m,JSON.stringify(S)])}const CE={x:{[un.Backward]:!1,[un.Forward]:!1},y:{[un.Backward]:!1,[un.Forward]:!1}};function EE(o){let{delta:e,disabled:n}=o;const a=Wd(e);return bo(i=>{if(n||!a||!i)return CE;const l={x:Math.sign(e.x-a.x),y:Math.sign(e.y-a.y)};return{x:{[un.Backward]:i.x[un.Backward]||l.x===-1,[un.Forward]:i.x[un.Forward]||l.x===1},y:{[un.Backward]:i.y[un.Backward]||l.y===-1,[un.Forward]:i.y[un.Forward]||l.y===1}}},[n,e,a])}function _E(o,e){const n=e!=null?o.get(e):void 0,a=n?n.node.current:null;return bo(i=>{var l;return e==null?null:(l=a??i)!=null?l:null},[a,e])}function AE(o,e){return N.useMemo(()=>o.reduce((n,a)=>{const{sensor:i}=a,l=i.activators.map(c=>({eventName:c.eventName,handler:e(c.handler,a)}));return[...n,...l]},[]),[o,e])}var _o;(function(o){o[o.Always=0]="Always",o[o.BeforeDragging=1]="BeforeDragging",o[o.WhileDragging=2]="WhileDragging"})(_o||(_o={}));var lf;(function(o){o.Optimized="optimized"})(lf||(lf={}));const Bm=new Map;function xE(o,e){let{dragging:n,dependencies:a,config:i}=e;const[l,c]=N.useState(null),{frequency:d,measure:f,strategy:g}=i,m=N.useRef(o),b=x(),S=yo(b),v=N.useCallback(function(L){L===void 0&&(L=[]),!S.current&&c(M=>M===null?L:M.concat(L.filter(R=>!M.includes(R))))},[S]),_=N.useRef(null),A=bo(L=>{if(b&&!n)return Bm;if(!L||L===Bm||m.current!==o||l!=null){const M=new Map;for(let R of o){if(!R)continue;if(l&&l.length>0&&!l.includes(R.id)&&R.rect.current){M.set(R.id,R.rect.current);continue}const D=R.node.current,B=D?new ef(f(D),D):null;R.rect.current=B,B&&M.set(R.id,B)}return M}return L},[o,l,n,b,f]);return N.useEffect(()=>{m.current=o},[o]),N.useEffect(()=>{b||v()},[n,b]),N.useEffect(()=>{l&&l.length>0&&c(null)},[JSON.stringify(l)]),N.useEffect(()=>{b||typeof d!="number"||_.current!==null||(_.current=setTimeout(()=>{v(),_.current=null},d))},[d,b,v,...a]),{droppableRects:A,measureDroppableContainers:v,measuringScheduled:l!=null};function x(){switch(g){case _o.Always:return!1;case _o.BeforeDragging:return n;default:return!n}}}function Pm(o,e){return bo(n=>o?n||(typeof e=="function"?e(o):o):null,[e,o])}function TE(o,e){return Pm(o,e)}function RE(o){let{callback:e,disabled:n}=o;const a=Kd(e),i=N.useMemo(()=>{if(n||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:l}=window;return new l(a)},[a,n]);return N.useEffect(()=>()=>i?.disconnect(),[i]),i}function lc(o){let{callback:e,disabled:n}=o;const a=Kd(e),i=N.useMemo(()=>{if(n||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:l}=window;return new l(a)},[n]);return N.useEffect(()=>()=>i?.disconnect(),[i]),i}function kE(o){return new ef(ds(o),o)}function qm(o,e,n){e===void 0&&(e=kE);const[a,i]=N.useState(null);function l(){i(f=>{if(!o)return null;if(o.isConnected===!1){var g;return(g=f??n)!=null?g:null}const m=e(o);return JSON.stringify(f)===JSON.stringify(m)?f:m})}const c=RE({callback(f){if(o)for(const g of f){const{type:m,target:b}=g;if(m==="childList"&&b instanceof HTMLElement&&b.contains(o)){l();break}}}}),d=lc({callback:l});return zr(()=>{l(),o?(d?.observe(o),c?.observe(document.body,{childList:!0,subtree:!0})):(d?.disconnect(),c?.disconnect())},[o]),a}function DE(o){const e=Pm(o);return km(o,e)}const Gm=[];function OE(o){const e=N.useRef(o),n=bo(a=>o?a&&a!==Gm&&o&&e.current&&o.parentNode===e.current.parentNode?a:sc(o):Gm,[o]);return N.useEffect(()=>{e.current=o},[o]),n}function LE(o){const[e,n]=N.useState(null),a=N.useRef(o),i=N.useCallback(l=>{const c=Qd(l.target);c&&n(d=>d?(d.set(c,Zd(c)),new Map(d)):null)},[]);return N.useEffect(()=>{const l=a.current;if(o!==l){c(l);const d=o.map(f=>{const g=Qd(f);return g?(g.addEventListener("scroll",i,{passive:!0}),[g,Zd(g)]):null}).filter(f=>f!=null);n(d.length?new Map(d):null),a.current=o}return()=>{c(o),c(l)};function c(d){d.forEach(f=>{const g=Qd(f);g?.removeEventListener("scroll",i)})}},[i,o]),N.useMemo(()=>o.length?e?Array.from(e.values()).reduce((l,c)=>us(l,c),Sr):Im(o):Sr,[o,e])}function Vm(o,e){e===void 0&&(e=[]);const n=N.useRef(null);return N.useEffect(()=>{n.current=null},e),N.useEffect(()=>{const a=o!==Sr;a&&!n.current&&(n.current=o),!a&&n.current&&(n.current=null)},[o]),n.current?So(o,n.current):Sr}function ME(o){N.useEffect(()=>{if(!rc)return;const e=o.map(n=>{let{sensor:a}=n;return a.setup==null?void 0:a.setup()});return()=>{for(const n of e)n?.()}},o.map(e=>{let{sensor:n}=e;return n}))}function $E(o,e){return N.useMemo(()=>o.reduce((n,a)=>{let{eventName:i,handler:l}=a;return n[i]=c=>{l(c,e)},n},{}),[o,e])}function Fm(o){return N.useMemo(()=>o?aE(o):null,[o])}const Km=[];function NE(o,e){e===void 0&&(e=ds);const[n]=o,a=Fm(n?Ln(n):null),[i,l]=N.useState(Km);function c(){l(()=>o.length?o.map(f=>$m(f)?a:new ef(e(f),f)):Km)}const d=lc({callback:c});return zr(()=>{d?.disconnect(),c(),o.forEach(f=>d?.observe(f))},[o]),i}function IE(o){if(!o)return null;if(o.children.length>1)return o;const e=o.children[0];return mo(e)?e:o}function HE(o){let{measure:e}=o;const[n,a]=N.useState(null),i=N.useCallback(g=>{for(const{target:m}of g)if(mo(m)){a(b=>{const S=e(m);return b?{...b,width:S.width,height:S.height}:S});break}},[e]),l=lc({callback:i}),c=N.useCallback(g=>{const m=IE(g);l?.disconnect(),m&&l?.observe(m),a(m?e(m):null)},[e,l]),[d,f]=ac(c);return N.useMemo(()=>({nodeRef:d,rect:n,setRef:f}),[n,d,f])}const zE=[{sensor:af,options:{}},{sensor:nf,options:{}}],jE={current:{}},cc={draggable:{measure:Dm},droppable:{measure:Dm,strategy:_o.WhileDragging,frequency:lf.Optimized},dragOverlay:{measure:ds}};class Ao 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,a;return(n=(a=this.get(e))==null?void 0:a.node.current)!=null?n:void 0}}const UE={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new Ao,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:ic},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:cc,measureDroppableContainers:ic,windowRect:null,measuringScheduled:!1},BE={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:ic,draggableNodes:new Map,over:null,measureDroppableContainers:ic},uc=N.createContext(BE),Wm=N.createContext(UE);function PE(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new Ao}}}function qE(o,e){switch(e.type){case tn.DragStart:return{...o,draggable:{...o.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case tn.DragMove:return o.draggable.active==null?o:{...o,draggable:{...o.draggable,translate:{x:e.coordinates.x-o.draggable.initialCoordinates.x,y:e.coordinates.y-o.draggable.initialCoordinates.y}}};case tn.DragEnd:case tn.DragCancel:return{...o,draggable:{...o.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case tn.RegisterDroppable:{const{element:n}=e,{id:a}=n,i=new Ao(o.droppable.containers);return i.set(a,n),{...o,droppable:{...o.droppable,containers:i}}}case tn.SetDroppableDisabled:{const{id:n,key:a,disabled:i}=e,l=o.droppable.containers.get(n);if(!l||a!==l.key)return o;const c=new Ao(o.droppable.containers);return c.set(n,{...l,disabled:i}),{...o,droppable:{...o.droppable,containers:c}}}case tn.UnregisterDroppable:{const{id:n,key:a}=e,i=o.droppable.containers.get(n);if(!i||a!==i.key)return o;const l=new Ao(o.droppable.containers);return l.delete(n),{...o,droppable:{...o.droppable,containers:l}}}default:return o}}function GE(o){let{disabled:e}=o;const{active:n,activatorEvent:a,draggableNodes:i}=N.useContext(uc),l=Wd(a),c=Wd(n?.id);return N.useEffect(()=>{if(!e&&!a&&l&&c!=null){if(!Xd(l)||document.activeElement===l.target)return;const d=i.get(c);if(!d)return;const{activatorNode:f,node:g}=d;if(!f.current&&!g.current)return;requestAnimationFrame(()=>{for(const m of[f.current,g.current]){if(!m)continue;const b=IC(m);if(b){b.focus();break}}})}},[a,e,i,c,l]),null}function VE(o,e){let{transform:n,...a}=e;return o!=null&&o.length?o.reduce((i,l)=>l({transform:i,...a}),n):n}function FE(o){return N.useMemo(()=>({draggable:{...cc.draggable,...o?.draggable},droppable:{...cc.droppable,...o?.droppable},dragOverlay:{...cc.dragOverlay,...o?.dragOverlay}}),[o?.draggable,o?.droppable,o?.dragOverlay])}function KE(o){let{activeNode:e,measure:n,initialRect:a,config:i=!0}=o;const l=N.useRef(!1),{x:c,y:d}=typeof i=="boolean"?{x:i,y:i}:i;zr(()=>{if(!c&&!d||!e){l.current=!1;return}if(l.current||!a)return;const g=e?.node.current;if(!g||g.isConnected===!1)return;const m=n(g),b=km(m,a);if(c||(b.x=0),d||(b.y=0),l.current=!0,Math.abs(b.x)>0||Math.abs(b.y)>0){const S=Om(g);S&&S.scrollBy({top:b.y,left:b.x})}},[e,c,d,a,n])}const Ym=N.createContext({...Sr,scaleX:1,scaleY:1});var Da;(function(o){o[o.Uninitialized=0]="Uninitialized",o[o.Initializing=1]="Initializing",o[o.Initialized=2]="Initialized"})(Da||(Da={}));const WE=N.memo(function(e){var n,a,i,l;let{id:c,accessibility:d,autoScroll:f=!0,children:g,sensors:m=zE,collisionDetection:b=JC,measuring:S,modifiers:v,..._}=e;const A=N.useReducer(qE,void 0,PE),[x,L]=A,[M,R]=PC(),[D,B]=N.useState(Da.Uninitialized),q=D===Da.Initialized,{draggable:{active:P,nodes:K,translate:ge},droppable:{containers:Ee}}=x,Se=P!=null?K.get(P):null,Ue=N.useRef({initial:null,translated:null}),Ve=N.useMemo(()=>{var he;return P!=null?{id:P,data:(he=Se?.data)!=null?he:jE,rect:Ue}:null},[P,Se]),qe=N.useRef(null),[St,J]=N.useState(null),[fe,Le]=N.useState(null),Z=yo(_,Object.values(_)),pe=vo("DndDescribedBy",c),H=N.useMemo(()=>Ee.getEnabled(),[Ee]),T=FE(S),{droppableRects:ce,measureDroppableContainers:de,measuringScheduled:ye}=xE(H,{dragging:q,dependencies:[ge.x,ge.y],config:T.droppable}),ie=_E(K,P),xe=N.useMemo(()=>fe?Jd(fe):null,[fe]),_e=ve(),Te=TE(ie,T.draggable.measure);KE({activeNode:P!=null?K.get(P):null,config:_e.layoutShiftCompensation,initialRect:Te,measure:T.draggable.measure});const $e=qm(ie,T.draggable.measure,Te),ht=qm(ie?ie.parentElement:null),wt=N.useRef({activatorEvent:null,active:null,activeNode:ie,collisionRect:null,collisions:null,droppableRects:ce,draggableNodes:K,draggingNode:null,draggingNodeRect:null,droppableContainers:Ee,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),kt=Ee.getNodeFor((n=wt.current.over)==null?void 0:n.id),ft=HE({measure:T.dragOverlay.measure}),nn=(a=ft.nodeRef.current)!=null?a:ie,Ft=q?(i=ft.rect)!=null?i:$e:null,Nt=!!(ft.nodeRef.current&&ft.rect),Br=DE(Nt?null:$e),fn=Fm(nn?Ln(nn):null),rn=OE(q?kt??ie:null),hn=NE(rn),Fn=VE(v,{transform:{x:ge.x-Br.x,y:ge.y-Br.y,scaleX:1,scaleY:1},activatorEvent:fe,active:Ve,activeNodeRect:$e,containerNodeRect:ht,draggingNodeRect:Ft,over:wt.current.over,overlayNodeRect:ft.rect,scrollableAncestors:rn,scrollableAncestorRects:hn,windowRect:fn}),Pr=xe?us(xe,ge):null,Pt=LE(rn),wi=Vm(Pt),na=Vm(Pt,[$e]),gn=us(Fn,wi),Rn=Ft?eE(Ft,Fn):null,tt=Ve&&Rn?b({active:Ve,collisionRect:Rn,droppableRects:ce,droppableContainers:H,pointerCoordinates:Pr}):null,$n=Tm(tt,"id"),[pn,ra]=N.useState(null),ir=Nt?Fn:us(Fn,na),an=QC(ir,(l=pn?.rect)!=null?l:null,$e),En=N.useRef(null),sn=N.useCallback((he,Ce)=>{let{sensor:Ae,options:Fe}=Ce;if(qe.current==null)return;const Re=K.get(qe.current);if(!Re)return;const Ne=he.nativeEvent,ke=new Ae({active:qe.current,activeNode:Re,event:Ne,options:Fe,context:wt,onAbort(ze){if(!K.get(ze))return;const{onDragAbort:we}=Z.current,He={id:ze};we?.(He),M({type:"onDragAbort",event:He})},onPending(ze,Ge,we,He){if(!K.get(ze))return;const{onDragPending:_t}=Z.current,Lt={id:ze,constraint:Ge,initialCoordinates:we,offset:He};_t?.(Lt),M({type:"onDragPending",event:Lt})},onStart(ze){const Ge=qe.current;if(Ge==null)return;const we=K.get(Ge);if(!we)return;const{onDragStart:He}=Z.current,et={activatorEvent:Ne,active:{id:Ge,data:we.data,rect:Ue}};ka.unstable_batchedUpdates(()=>{He?.(et),B(Da.Initializing),L({type:tn.DragStart,initialCoordinates:ze,active:Ge}),M({type:"onDragStart",event:et}),J(En.current),Le(Ne)})},onMove(ze){L({type:tn.DragMove,coordinates:ze})},onEnd:Ze(tn.DragEnd),onCancel:Ze(tn.DragCancel)});En.current=ke;function Ze(ze){return async function(){const{active:we,collisions:He,over:et,scrollAdjustedTranslate:_t}=wt.current;let Lt=null;if(we&&_t){const{cancelDrop:kn}=Z.current;Lt={activatorEvent:Ne,active:we,collisions:He,delta:_t,over:et},ze===tn.DragEnd&&typeof kn=="function"&&await Promise.resolve(kn(Lt))&&(ze=tn.DragCancel)}qe.current=null,ka.unstable_batchedUpdates(()=>{L({type:ze}),B(Da.Uninitialized),ra(null),J(null),Le(null),En.current=null;const kn=ze===tn.DragEnd?"onDragEnd":"onDragCancel";if(Lt){const It=Z.current[kn];It?.(Lt),M({type:kn,event:Lt})}})}}},[K]),V=N.useCallback((he,Ce)=>(Ae,Fe)=>{const Re=Ae.nativeEvent,Ne=K.get(Fe);if(qe.current!==null||!Ne||Re.dndKit||Re.defaultPrevented)return;const ke={active:Ne};he(Ae,Ce.options,ke)===!0&&(Re.dndKit={capturedBy:Ce.sensor},qe.current=Fe,sn(Ae,Ce))},[K,sn]),se=AE(m,V);ME(m),zr(()=>{$e&&D===Da.Initializing&&B(Da.Initialized)},[$e,D]),N.useEffect(()=>{const{onDragMove:he}=Z.current,{active:Ce,activatorEvent:Ae,collisions:Fe,over:Re}=wt.current;if(!Ce||!Ae)return;const Ne={active:Ce,activatorEvent:Ae,collisions:Fe,delta:{x:gn.x,y:gn.y},over:Re};ka.unstable_batchedUpdates(()=>{he?.(Ne),M({type:"onDragMove",event:Ne})})},[gn.x,gn.y]),N.useEffect(()=>{const{active:he,activatorEvent:Ce,collisions:Ae,droppableContainers:Fe,scrollAdjustedTranslate:Re}=wt.current;if(!he||qe.current==null||!Ce||!Re)return;const{onDragOver:Ne}=Z.current,ke=Fe.get($n),Ze=ke&&ke.rect.current?{id:ke.id,rect:ke.rect.current,data:ke.data,disabled:ke.disabled}:null,ze={active:he,activatorEvent:Ce,collisions:Ae,delta:{x:Re.x,y:Re.y},over:Ze};ka.unstable_batchedUpdates(()=>{ra(Ze),Ne?.(ze),M({type:"onDragOver",event:ze})})},[$n]),zr(()=>{wt.current={activatorEvent:fe,active:Ve,activeNode:ie,collisionRect:Rn,collisions:tt,droppableRects:ce,draggableNodes:K,draggingNode:nn,draggingNodeRect:Ft,droppableContainers:Ee,over:pn,scrollableAncestors:rn,scrollAdjustedTranslate:gn},Ue.current={initial:Ft,translated:Rn}},[Ve,ie,tt,Rn,K,nn,Ft,ce,Ee,pn,rn,gn]),wE({..._e,delta:ge,draggingRect:Rn,pointerCoordinates:Pr,scrollableAncestors:rn,scrollableAncestorRects:hn});const ue=N.useMemo(()=>({active:Ve,activeNode:ie,activeNodeRect:$e,activatorEvent:fe,collisions:tt,containerNodeRect:ht,dragOverlay:ft,draggableNodes:K,droppableContainers:Ee,droppableRects:ce,over:pn,measureDroppableContainers:de,scrollableAncestors:rn,scrollableAncestorRects:hn,measuringConfiguration:T,measuringScheduled:ye,windowRect:fn}),[Ve,ie,$e,fe,tt,ht,ft,K,Ee,ce,pn,de,rn,hn,T,ye,fn]),ee=N.useMemo(()=>({activatorEvent:fe,activators:se,active:Ve,activeNodeRect:$e,ariaDescribedById:{draggable:pe},dispatch:L,draggableNodes:K,over:pn,measureDroppableContainers:de}),[fe,se,Ve,$e,L,pe,K,pn,de]);return Ye.createElement(Cm.Provider,{value:R},Ye.createElement(uc.Provider,{value:ee},Ye.createElement(Wm.Provider,{value:ue},Ye.createElement(Ym.Provider,{value:an},g)),Ye.createElement(GE,{disabled:d?.restoreFocus===!1})),Ye.createElement(VC,{...d,hiddenTextDescribedById:pe}));function ve(){const he=St?.autoScrollEnabled===!1,Ce=typeof f=="object"?f.enabled===!1:f===!1,Ae=q&&!he&&!Ce;return typeof f=="object"?{...f,enabled:Ae}:{enabled:Ae}}}),YE=N.createContext(null),Xm="button",XE="Draggable";function JE(o){let{id:e,data:n,disabled:a=!1,attributes:i}=o;const l=vo(XE),{activators:c,activatorEvent:d,active:f,activeNodeRect:g,ariaDescribedById:m,draggableNodes:b,over:S}=N.useContext(uc),{role:v=Xm,roleDescription:_="draggable",tabIndex:A=0}=i??{},x=f?.id===e,L=N.useContext(x?Ym:YE),[M,R]=ac(),[D,B]=ac(),q=$E(c,e),P=yo(n);zr(()=>(b.set(e,{id:e,key:l,node:M,activatorNode:D,data:P}),()=>{const ge=b.get(e);ge&&ge.key===l&&b.delete(e)}),[b,e]);const K=N.useMemo(()=>({role:v,tabIndex:A,"aria-disabled":a,"aria-pressed":x&&v===Xm?!0:void 0,"aria-roledescription":_,"aria-describedby":m.draggable}),[a,v,A,x,_,m.draggable]);return{active:f,activatorEvent:d,activeNodeRect:g,attributes:K,isDragging:x,listeners:a?void 0:q,node:M,over:S,setNodeRef:R,setActivatorNodeRef:B,transform:L}}function QE(){return N.useContext(Wm)}const ZE="Droppable",e_={timeout:25};function t_(o){let{data:e,disabled:n=!1,id:a,resizeObserverConfig:i}=o;const l=vo(ZE),{active:c,dispatch:d,over:f,measureDroppableContainers:g}=N.useContext(uc),m=N.useRef({disabled:n}),b=N.useRef(!1),S=N.useRef(null),v=N.useRef(null),{disabled:_,updateMeasurementsFor:A,timeout:x}={...e_,...i},L=yo(A??a),M=N.useCallback(()=>{if(!b.current){b.current=!0;return}v.current!=null&&clearTimeout(v.current),v.current=setTimeout(()=>{g(Array.isArray(L.current)?L.current:[L.current]),v.current=null},x)},[x]),R=lc({callback:M,disabled:_||!c}),D=N.useCallback((K,ge)=>{R&&(ge&&(R.unobserve(ge),b.current=!1),K&&R.observe(K))},[R]),[B,q]=ac(D),P=yo(e);return N.useEffect(()=>{!R||!B.current||(R.disconnect(),b.current=!1,R.observe(B.current))},[B,R]),N.useEffect(()=>(d({type:tn.RegisterDroppable,element:{id:a,key:l,disabled:n,node:B,rect:S,data:P}}),()=>d({type:tn.UnregisterDroppable,key:l,id:a})),[a]),N.useEffect(()=>{n!==m.current.disabled&&(d({type:tn.SetDroppableDisabled,id:a,key:l,disabled:n}),m.current.disabled=n)},[a,l,n,d]),{active:c,rect:S,isOver:f?.id===a,node:B,over:f,setNodeRef:q}}function cf(o,e,n){const a=o.slice();return a.splice(n<0?a.length+n:n,0,a.splice(e,1)[0]),a}function n_(o,e){return o.reduce((n,a,i)=>{const l=e.get(a);return l&&(n[i]=l),n},Array(o.length))}function dc(o){return o!==null&&o>=0}function r_(o,e){if(o===e)return!0;if(o.length!==e.length)return!1;for(let n=0;n{var e;let{rects:n,activeNodeRect:a,activeIndex:i,overIndex:l,index:c}=o;const d=(e=n[i])!=null?e:a;if(!d)return null;const f=s_(n,c,i);if(c===i){const g=n[l];return g?{x:ii&&c<=l?{x:-d.width-f,y:0,...fc}:c=l?{x:d.width+f,y:0,...fc}:{x:0,y:0,...fc}};function s_(o,e,n){const a=o[e],i=o[e-1],l=o[e+1];return!a||!i&&!l?0:n{let{rects:e,activeIndex:n,overIndex:a,index:i}=o;const l=cf(e,a,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},o_=o=>{var e;let{activeIndex:n,activeNodeRect:a,index:i,rects:l,overIndex:c}=o;const d=(e=l[n])!=null?e:a;if(!d)return null;if(i===n){const g=l[c];return g?{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 l_(o,e,n){const a=o[e],i=o[e-1],l=o[e+1];return a?na.map(q=>typeof q=="object"&&"id"in q?q.id:q),[a]),_=c!=null,A=c?v.indexOf(c.id):-1,x=g?v.indexOf(g.id):-1,L=N.useRef(v),M=!r_(v,L.current),R=x!==-1&&A===-1||M,D=a_(l);zr(()=>{M&&_&&m(v)},[M,v,_,m]),N.useEffect(()=>{L.current=v},[v]);const B=N.useMemo(()=>({activeIndex:A,containerId:b,disabled:D,disableTransforms:R,items:v,overIndex:x,useDragOverlay:S,sortedRects:n_(v,f),strategy:i}),[A,b,D.draggable,D.droppable,R,v,x,f,S,i]);return Ye.createElement(Qm.Provider,{value:B},e)}const u_=o=>{let{id:e,items:n,activeIndex:a,overIndex:i}=o;return cf(n,a,i).indexOf(e)},d_=o=>{let{containerId:e,isSorting:n,wasDragging:a,index:i,items:l,newIndex:c,previousItems:d,previousContainerId:f,transition:g}=o;return!g||!a||d!==l&&i===c?!1:n?!0:c!==i&&e===f},f_={duration:200,easing:"ease"},Zm="transform",h_=wo.Transition.toString({property:Zm,duration:0,easing:"linear"}),g_={roleDescription:"sortable"};function p_(o){let{disabled:e,index:n,node:a,rect:i}=o;const[l,c]=N.useState(null),d=N.useRef(n);return zr(()=>{if(!e&&n!==d.current&&a.current){const f=i.current;if(f){const g=ds(a.current,{ignoreTransform:!0}),m={x:f.left-g.left,y:f.top-g.top,scaleX:f.width/g.width,scaleY:f.height/g.height};(m.x||m.y)&&c(m)}}n!==d.current&&(d.current=n)},[e,n,a,i]),N.useEffect(()=>{l&&c(null)},[l]),l}function m_(o){let{animateLayoutChanges:e=d_,attributes:n,disabled:a,data:i,getNewIndex:l=u_,id:c,strategy:d,resizeObserverConfig:f,transition:g=f_}=o;const{items:m,containerId:b,activeIndex:S,disabled:v,disableTransforms:_,sortedRects:A,overIndex:x,useDragOverlay:L,strategy:M}=N.useContext(Qm),R=y_(a,v),D=m.indexOf(c),B=N.useMemo(()=>({sortable:{containerId:b,index:D,items:m},...i}),[b,i,D,m]),q=N.useMemo(()=>m.slice(m.indexOf(c)),[m,c]),{rect:P,node:K,isOver:ge,setNodeRef:Ee}=t_({id:c,data:B,disabled:R.droppable,resizeObserverConfig:{updateMeasurementsFor:q,...f}}),{active:Se,activatorEvent:Ue,activeNodeRect:Ve,attributes:qe,setNodeRef:St,listeners:J,isDragging:fe,over:Le,setActivatorNodeRef:Z,transform:pe}=JE({id:c,data:B,attributes:{...g_,...n},disabled:R.draggable}),H=LC(Ee,St),T=!!Se,ce=T&&!_&&dc(S)&&dc(x),de=!L&&fe,ye=de&&ce?pe:null,xe=ce?ye??(d??M)({rects:A,activeNodeRect:Ve,activeIndex:S,overIndex:x,index:D}):null,_e=dc(S)&&dc(x)?l({id:c,items:m,activeIndex:S,overIndex:x}):D,Te=Se?.id,$e=N.useRef({activeId:Te,items:m,newIndex:_e,containerId:b}),ht=m!==$e.current.items,wt=e({active:Se,containerId:b,isDragging:fe,isSorting:T,id:c,index:D,items:m,newIndex:$e.current.newIndex,previousItems:$e.current.items,previousContainerId:$e.current.containerId,transition:g,wasDragging:$e.current.activeId!=null}),kt=p_({disabled:!wt,index:D,node:K,rect:P});return N.useEffect(()=>{T&&$e.current.newIndex!==_e&&($e.current.newIndex=_e),b!==$e.current.containerId&&($e.current.containerId=b),m!==$e.current.items&&($e.current.items=m)},[T,_e,b,m]),N.useEffect(()=>{if(Te===$e.current.activeId)return;if(Te!=null&&$e.current.activeId==null){$e.current.activeId=Te;return}const nn=setTimeout(()=>{$e.current.activeId=Te},50);return()=>clearTimeout(nn)},[Te]),{active:Se,activeIndex:S,attributes:qe,data:B,rect:P,index:D,newIndex:_e,items:m,isOver:ge,isSorting:T,isDragging:fe,listeners:J,node:K,overIndex:x,over:Le,setNodeRef:H,setActivatorNodeRef:Z,setDroppableNodeRef:Ee,setDraggableNodeRef:St,transform:kt??xe,transition:ft()};function ft(){if(kt||ht&&$e.current.newIndex===D)return h_;if(!(de&&!Xd(Ue)||!g)&&(T||wt))return wo.Transition.toString({...g,property:Zm})}}function y_(o,e){var n,a;return typeof o=="boolean"?{draggable:o,droppable:!1}:{draggable:(n=o?.draggable)!=null?n:e.draggable,droppable:(a=o?.droppable)!=null?a:e.droppable}}function gc(o){if(!o)return!1;const e=o.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}const b_=[ot.Down,ot.Right,ot.Up,ot.Left],v_=(o,e)=>{let{context:{active:n,collisionRect:a,droppableRects:i,droppableContainers:l,over:c,scrollableAncestors:d}}=e;if(b_.includes(o.code)){if(o.preventDefault(),!n||!a)return;const f=[];l.getEnabled().forEach(b=>{if(!b||b!=null&&b.disabled)return;const S=i.get(b.id);if(S)switch(o.code){case ot.Down:a.topS.top&&f.push(b);break;case ot.Left:a.left>S.left&&f.push(b);break;case ot.Right:a.left1&&(m=g[1].id),m!=null){const b=l.get(n.id),S=l.get(m),v=S?i.get(S.id):null,_=S?.node.current;if(_&&v&&b&&S){const x=sc(_).some((q,P)=>d[P]!==q),L=ey(b,S),M=S_(b,S),R=x||!L?{x:0,y:0}:{x:M?a.width-v.width:0,y:M?a.height-v.height:0},D={x:v.left,y:v.top};return R.x&&R.y?D:So(D,R)}}}};function ey(o,e){return!gc(o)||!gc(e)?!1:o.data.current.sortable.containerId===e.data.current.sortable.containerId}function S_(o,e){return!gc(o)||!gc(e)||!ey(o,e)?!1:o.data.current.sortable.index{const d=N.useId(),f=N.useRef({inProgress:!1,lastSortTime:0,lastActiveId:null}),g=FC(Em(af,{activationConstraint:{distance:5}}),Em(nf,{coordinateGetter:v_})),m=N.useCallback(v=>{f.current={inProgress:!0,lastSortTime:Date.now(),lastActiveId:v.active.id},l?.({activeId:v.active.id})},[l]),b=N.useCallback(v=>{const{active:_,over:A}=v,x=Date.now();if(!A||_.id===A.id){f.current.inProgress=!1;return}const{lastSortTime:L,lastActiveId:M,inProgress:R}=f.current;if(M===_.id&&x-L<500&&!R)return;f.current={inProgress:!1,lastSortTime:x,lastActiveId:_.id};const D=o.findIndex(q=>String(q[e])===String(_.id)),B=o.findIndex(q=>String(q[e])===String(A.id));if(D!==-1&&B!==-1&&D!==B){const q=cf(o,D,B);i?.(q,{oldIndex:D,newIndex:B})}},[o,e,i]),S=o.map(v=>String(v[e]));return dt.jsx(WE,{id:d,sensors:g,collisionDetection:WC,onDragStart:m,onDragEnd:b,children:dt.jsx(c_,{items:S,strategy:w_[n],children:a})},c!==void 0?`${d}-v${c}`:d)},ty=N.createContext(null),E_=({value:o,children:e})=>dt.jsx(ty.Provider,{value:o,children:e}),__=()=>N.useContext(ty),A_=({id:o,handle:e,as:n="div",children:a})=>{const{attributes:i,listeners:l,setNodeRef:c,transform:d,transition:f,isDragging:g}=m_({id:o}),m={transform:wo.Transform.toString(d),transition:f,opacity:g?.5:1,position:"relative"};return dt.jsx(n,{ref:c,style:m,...i,...e?{}:l,"data-sortable-item":!0,"data-sortable-id":String(o),"data-dragging":g,children:dt.jsx(E_,{value:{listeners:l,handle:e,isDragging:g},children:a})})},at=ut("DynamicRenderer");function Zr(){try{return window.G7Core?.devTools}catch{return}}function df(o,e,n,a){if(typeof o=="string"){if(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*/.test(o))try{return e.resolveTranslations(o,n,a)}catch{return o}return o}if(Array.isArray(o))return o.map(i=>df(i,e,n,a));if(o&&typeof o=="object"){const i={};for(const[l,c]of Object.entries(o))i[l]=df(c,e,n,a);return i}return o}function x_(o){const e=Object.keys(o);return e.length>0&&e.every(n=>/^\d+$/.test(n))}const wr=(o,e)=>{const n=["errors"],a={...o};for(const i of Object.keys(e)){const l=e[i],c=o[i];if(l===null){a[i]=null;continue}if(n.includes(i)){a[i]=l;continue}if(Array.isArray(l)){a[i]=l;continue}if(Array.isArray(c)&&l!==null&&typeof l=="object"&&!Array.isArray(l)&&x_(l)){const d=Object.keys(l).map(g=>parseInt(g,10));if((d.length>0?Math.max(...d):0)>=c.length+d.length+10)a[i]={...l};else{const g=[...c];for(const[m,b]of Object.entries(l)){const S=parseInt(m,10);S>=0&&S=g.length&&(g[S]=b)}a[i]=g}}else l!==null&&typeof l=="object"&&c!==null&&typeof c=="object"&&!Array.isArray(c)?a[i]=wr(c,l):a[i]=l}return a},pc=(o,e)=>{let n=null;const a=()=>(n===null&&(n={...o}),n);for(const i of Object.keys(e)){if(!(i in o))continue;const l=e[i],c=o[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 a()[i]:a()[i]=d}else delete a()[i]}return n??o},T_=o=>{const e={},n=o.split(";").filter(a=>a.trim());for(const a of n){const i=a.indexOf(":");if(i===-1)continue;const l=a.substring(0,i).trim(),c=a.substring(i+1).trim();if(l&&c){const d=l.replace(/-([a-z])/g,(f,g)=>g.toUpperCase());e[d]=c}}return e};class R_ extends N.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:dt.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:[dt.jsx("div",{className:"font-semibold mb-1",children:"컴포넌트 로드 실패"}),dt.jsxs("div",{className:"text-xs opacity-80",children:[this.props.componentName&&`[${this.props.componentName}] `,"데이터를 표시할 수 없습니다."]}),this.state.error&&dt.jsxs("details",{className:"mt-2",children:[dt.jsx("summary",{className:"cursor-pointer text-xs opacity-70 hover:opacity-100",children:"상세 정보"}),dt.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 jr=N.memo(({componentDef:o,dataContext:e,translationContext:n,registry:a,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:d,parentFormContextProp:f,parentDataContext:g,isRootRenderer:m=!1,isInsideIteration:b=!1,isEditMode:S=!1,onComponentSelect:v,onComponentHover:_,onDragStart:A,onDragEnd:x,componentPath:L,layoutKey:M})=>{const[R,D]=N.useState({loadingActions:{}});N.useLayoutEffect(()=>{d||(i.startRenderCycle(),window.__g7SetLocalOverrideKeys||(window.__g7ForcedLocalFields=void 0),window.__g7PendingLocalState=null)});const B=N.useRef(null);N.useLayoutEffect(()=>{if(!d&&e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:V,_merge:se,...ue}=e._localInit,ee=`${JSON.stringify(ue)}:${V||"no-force"}`;if(B.current!==ee){B.current=ee;const ve=se||"shallow",Ce=window.G7Core?.state?.get?.()?._local||{},Ae=window.__g7PendingLocalState||{},Fe={...Ce,...Ae};ve==="replace"?window.__g7PendingLocalState={loadingActions:Fe.loadingActions||{},...ue,hasChanges:!1}:ve==="deep"?window.__g7PendingLocalState=wr(Fe,{...ue,hasChanges:!1}):window.__g7PendingLocalState={...Fe,...ue,hasChanges:!1};const Re=window.__g7SetLocalOverrideKeys;Re&&typeof Re=="object"&&(ve==="replace"?window.__g7SetLocalOverrideKeys={...ue,hasChanges:!1}:window.__g7SetLocalOverrideKeys=wr(Re,{...ue,hasChanges:!1}))}}}),N.useLayoutEffect(()=>{if(!d){const V=window.__g7SetLocalOverrideKeys;if(V){D(ve=>pc(ve,V));const se=V,ue=window.__g7ForcedLocalFields,ee=window.__g7LastSetLocalSnapshot;queueMicrotask(()=>{window.__g7SetLocalOverrideKeys===se&&(window.__g7SetLocalOverrideKeys=void 0),window.__g7ForcedLocalFields===ue&&(window.__g7ForcedLocalFields=void 0),window.__g7LastSetLocalSnapshot===ee&&(window.__g7LastSetLocalSnapshot=void 0)})}}},[e._local]);const q=N.useRef(M);N.useEffect(()=>{o._fromBase&&M&&q.current!==M&&(q.current=M,D({loadingActions:{}}))},[M,o._fromBase]);const P=N.useRef(""),K=N.useRef(!1),ge=N.useRef(null),Ee=N.useRef(null),Se=N.useRef({}),Ue=N.useRef({}),Ve=N.useRef(g),qe=OC(),St=oC(),J=St?.getParentDataContext()??g;N.useEffect(()=>{if(e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:V,...se}=e._localInit,ue=JSON.stringify(se),ee=V!==void 0,ve=Pd(),he=`${ue}:${V||"no-force"}`,Ce=pC({globalTrackedKey:ve.hash,instanceHandledKey:Ee.current,trackingKey:he});if(Ce==="apply"){Ee.current=he,ve.hash=he,ve.timestamp=V,P.current=ue,ee&&(K.current=!0);const{_merge:Fe,...Re}=se,Ne=Fe||"shallow";D(ke=>Ne==="replace"?{loadingActions:ke.loadingActions||{},...Re,hasChanges:!1}:Ne==="deep"?wr(ke,{...Re,hasChanges:!1}):{...ke,...Re,hasChanges:!1}),e._globalSetState&&e._globalSetState(ke=>{const Ze=ke?._local||{};let ze;return Ne==="replace"?ze={...Re,hasChanges:!1}:Ne==="deep"?ze=wr(Ze,{...Re,hasChanges:!1}):ze={...Ze,...Re,hasChanges:!1},{...ke,_local:ze}}),i.invalidateCacheByKeys(["_local"]),at.log("_localInit applied (data changed):",Object.keys(se))}else if(Ce==="prune"){Ee.current=he;const{_merge:Fe,...Re}=se;D(ke=>pc(ke,Re)),pc(R,Re)!==R&&(i.invalidateCacheByKeys(["_local"]),at.log("_localInit pruned (applied by another renderer):",Object.keys(Re)))}ge.current=e._localInit,hC(e._localInit)}},[e._localInit,g,i]);const{isTransitioning:fe}=hm(),Le=CC(),Z=f??Le,{width:pe}=Gd(),H=__(),T=N.useMemo(()=>{let V=o;if(o.type==="iterator"&&o.data){const{data:ee,itemName:ve,indexName:he,...Ce}=o;V={...Ce,iteration:{source:ee,item_var:ve||"item",index_var:he}}}if(!V.responsive)return V;const se=hi.getMatchingKey(V.responsive,pe);if(!se)return V;const ue=V.responsive[se];return{...V,props:{...V.props,...ue.props},children:ue.children??V.children,text:ue.text??V.text,if:ue.if??V.if,iteration:ue.iteration??V.iteration,__responsiveChildrenKey:ue.children!==void 0?se:void 0}},[o,pe]),ce=N.useCallback(V=>{const se=V?.__setStateId;if(D(ue=>{const ee=window.__g7PendingLocalState,he=window.__g7SetLocalOverrideKeys||ee,Ce=he?wr(ue,he):ue;if(typeof V=="function"){const ke=V(Ce);return wr(Ce,ke)}const{__mergeMode:Ae,__setStateId:Fe,...Re}=V;let Ne;if(Ae==="replace"?Ne=Re:Ae==="shallow"?Ne={...Ce,...Re}:Ne=wr(Ce,Re),Ae!==void 0){const ke=window.__g7ForcedLocalFields;ke&&(window.__g7ForcedLocalFields={...ke,...Re})}return Ne}),se){const ue=Zr();if(ue?.isEnabled()){const ee=T.id||"unknown",ve=T.name||"Unknown";setTimeout(()=>{ue.trackComponentRender?.(ee,ve,0,["_local"],[]),ue.completeStateChange?.(se)},0)}}},[T.id,T.name]),de=d?.state??R,ye=d?.setState??ce,ie=N.useMemo(()=>{const V=e._localInit&&e._localInit!==ge.current;let se;V&&e._local?se=e._local:se=e._local?wr(e._local,de):de;const ue=window.__g7ForcedLocalFields;ue&&(se=wr(se,ue));const ee={...e,_local:se},ve=e._computedDefinitions;if(ve&&Object.keys(ve).length>0){const he=new xn,Ce={...ee,...qe?{_isolated:qe.state}:{}},Ae={},Fe=Zr(),Re=Fe?.isEnabled()??!1;for(const[Ne,ke]of Object.entries(ve)){const Ze=Re?Date.now():0,ze=Re?e._computed?.[Ne]:void 0;let Ge;try{if(typeof ke=="string")if(ke.startsWith("{{")&&ke.endsWith("}}")){const we=ke.slice(2,-2).trim(),He=Pn(we)?he.evaluatePipeExpression(we,Ce,{skipCache:!0}):he.evaluateExpression(we,Ce,{skipCache:!0});Ae[Ne]=He}else Ae[Ne]=ke;else if(ke&&typeof ke=="object"&&"$switch"in ke){const we=he.resolveSwitch(ke,Ce,{skipCache:!0});Ae[Ne]=we}}catch(we){at.warn(`Failed to recalculate computed value: ${Ne}`,we),Ae[Ne]=e._computed?.[Ne],Ge=we instanceof Error?we.message:String(we)}if(Re&&(Ge||ze!==Ae[Ne])){const He=Date.now()-Ze;Fe.trackComputedProperty?.(Ne,typeof ke=="string"?ke:JSON.stringify(ke),[{type:"_local",path:"_local",value:ee._local}],Ae[Ne],He,T.id,Ge),ze!==Ae[Ne]&&Fe.trackComputedRecalc?.(Ne,"dependency-change",ze,Ae[Ne],He,{type:"_local",path:"_local"},T.id)}}ee._computed=Ae}if(qe&&(ee._isolated=qe.state),J&&(ee.$parent=J),o.extensionPointProps){const he=i.resolveObject(o.extensionPointProps,ee,b?{skipCache:!0}:void 0);ee.extensionPointProps=S&&l?df(he,l,n,ee):he}return o.extensionPointCallbacks&&(ee.extensionPointCallbacks=o.extensionPointCallbacks),S&&(ee.$templateId===void 0&&n?.templateId&&(ee.$templateId=n.templateId),ee.$locale===void 0&&n?.locale&&(ee.$locale=n.locale)),ee},[e,de,qe?.state,J,St?.version,o.extensionPointProps,o.extensionPointCallbacks]);Se.current=ie._local,Ue.current=ie._computed||{},Ve.current=J,N.useEffect(()=>{const V=Zr();if(!V?.isEnabled())return;const se=ie._local;se&&V.updateLocalState(se);const ue=ie._computed;ue&&V.updateComputedState(ue),J&&V.updateParentContext?.(J);const ee=T.id||`comp-${Date.now()}`,ve=T.name||"Unknown",he={global:Object.keys(e._global||{}),local:Object.keys(se||{}),context:d?Object.keys(d.state||{}):[]},Ce={type:d?"componentContext":"dynamicState",hasComponentContext:!!d,parentId:d?"parent":void 0};V.trackComponentStateSource?.(ee,ve,he,Ce),de&&Object.keys(de).length>0&&V.trackDynamicState?.(ee,de);const Ae=!!(T.expandChildren||T.props?.expandChildren);V.trackContextFlow?.(ee,ve,!!d,Ae,!0)},[ie._local,e,T.id,T.name,d,de,T.expandChildren,T.props?.expandChildren,J]);const xe=N.useMemo(()=>({state:{...ie._local},setState:ye,stateRef:Se,computedRef:Ue,isolatedContext:qe,parentDataContext:ie}),[ie._local,ye,R,qe,ie]),_e=N.useMemo(()=>{const V=ts({if:T.if,condition:T.condition,conditions:T.conditions},ie,i,T.id);if(T.if||T.condition!==void 0||T.conditions){const ue=Zr();ue?.isEnabled()&&T.if&&ue.trackIfCondition(T.id||`if-${Date.now()}`,T.if,V)}return V},[T.if,T.conditions,ie,i,T.id]),Te=N.useMemo(()=>{if(!T.slot)return null;const V=T.slot;if(V.startsWith("{{")&&V.endsWith("}}")){const se=V.slice(2,-2).trim();try{const ue={componentId:T.id,componentName:T.name,propName:"slot"},ee=Pn(se)?i.evaluatePipeExpression(se,ie,void 0,ue):i.evaluateExpression(se,ie,ue);return at.log(`[Slot] 표현식 평가: "${se}" => "${ee}" (컴포넌트: ${T.id})`),typeof ee=="string"?ee:null}catch(ue){return at.warn(`slot 표현식 평가 실패 (컴포넌트: ${T.id}):`,ue),null}}return at.log(`[Slot] 정적 슬롯 ID: "${V}" (컴포넌트: ${T.id})`),V},[T.slot,T.id,ie,i]),$e=N.useMemo(()=>!Te||!T.id?"":`${T.id}-${Te}-${JSON.stringify(T.slotOrder??0)}`,[Te,T.id,T.slotOrder]),ht=N.useRef(null);N.useEffect(()=>{const V=window.__slotContextValue,se=V?.isEnabled??!1;if(T.slot&&at.log(`[Slot Registration] 컴포넌트: ${T.id}, isSlotEnabled: ${se}, shouldRender: ${_e}, resolvedSlotId: ${Te}`),!se||!_e){T.slot&&at.log(`[Slot Registration] 등록 스킵 - isSlotEnabled: ${se}, shouldRender: ${_e}`),ht.current&&T.id&&V&&(V.unregisterFromSlot(ht.current,T.id),ht.current=null);return}if(!Te||!T.id){T.slot&&at.log(`[Slot Registration] 등록 스킵 - resolvedSlotId: ${Te}, id: ${T.id}`),ht.current&&T.id&&V&&(V.unregisterFromSlot(ht.current,T.id),ht.current=null);return}ht.current&&ht.current!==Te&&V.unregisterFromSlot(ht.current,T.id);const ue={...T,slot:void 0,slotOrder:void 0};return V.registerToSlot(Te,T.id,{componentDef:ue,dataContext:e,order:T.slotOrder??0,parentFormContext:f??null,getParentComponentContext:()=>xe,translationContext:n,registrationKey:$e}),ht.current=Te,()=>{const ee=window.__slotContextValue;Te&&T.id&&ee&&ee.unregisterFromSlot(Te,T.id)}},[_e,Te,T,e,f,xe,n,$e]);const wt=N.useCallback(V=>{if(typeof V=="string"){if($l(V))return gd(V);if(Nl(V)){const se=[],ue=V.replace(new RegExp(`${to}([^${fi}]*)${fi}`,"g"),(ve,he)=>(se.push(he),`${xa}${se.length-1}${xa}`));let ee=ue;return/\$t:[a-zA-Z0-9._-]+/.test(ue)&&(ee=l.resolveTranslations(ue,n,ie)),ee.replace(new RegExp(`${xa}(\\d+)${xa}`,"g"),(ve,he)=>se[parseInt(he)])}if(V.startsWith("$t:defer:"))return V;if(/\$t:[a-zA-Z0-9._-]+/.test(V)){const se=V.trim();return se.startsWith("{")&&se.endsWith("}")||se.startsWith("[")&&se.endsWith("]")?V:l.resolveTranslations(V,n,ie)}return V}if(Array.isArray(V))return V.map(se=>wt(se));if(V&&typeof V=="object"){const se={};for(const[ue,ee]of Object.entries(V))se[ue]=wt(ee);return se}return V},[l,n,ie]),kt=N.useCallback(V=>eo(V),[]),ft=N.useCallback(V=>Aa(V),[]),nn=N.useMemo(()=>{let V={...T.props||{}};const se=["cellChildren","expandChildren","expandContext","render"],ee=a.getMetadata(T.name)?.skipBindingKeys||[],ve=[...new Set([...se,...ee])],he=b?{skipCache:!0}:void 0,Ce={...he??{},skipBindingKeys:ve},Ae=we=>{if(he)return he;if(we.startsWith("_computed")||we.startsWith("$computed"))return{skipCache:!0}};for(const[we,He]of Object.entries(V))if(!ve.includes(we))if(typeof He=="string"){const et=ft(He);if(et!==null){let _t=!1,Lt=et;et.startsWith(er)&&(_t=!0,Lt=et.slice(er.length));const kn={componentId:T.id,componentName:T.name,propName:we};let It;if(Pn(Lt))try{It=i.evaluatePipeExpression(Lt,ie,Ae(Lt),kn)}catch(Ht){at.warn(`파이프 표현식 평가 실패 (컴포넌트: ${T.id}, prop: ${we}):`,Ht),It=void 0}else if(kt(Lt))try{It=i.evaluateExpression(Lt,ie,kn)}catch(Ht){at.warn(`표현식 평가 실패 (컴포넌트: ${T.id}, prop: ${we}):`,Ht),It=void 0}else It=i.resolve(Lt,ie,Ae(Lt),kn);V[we]=_t&&It!=null?es(It):It}else{const _t={componentId:T.id,componentName:T.name,propName:we};V[we]=i.resolveBindings(He,ie,he,_t)}}else Array.isArray(He)?V[we]=He.map(et=>typeof et=="string"?i.resolveBindings(et,ie,he):typeof et=="object"&&et!==null?i.resolveObject(et,ie,Ce):et):He&&typeof He=="object"&&(V[we]=i.resolveObject(He,ie,Ce));for(const[we,He]of Object.entries(V))V[we]=wt(He);if(typeof V.style=="string"&&(V.style=T_(V.style)),V=bd(V,S?void 0:T.actions,ie,{componentContext:xe,actionDispatcher:c}),T.classMap){const we=mw(T.classMap,ie,i,{skipCache:!0});if(we){const He=V.className||"";V.className=He?`${He} ${we}`:we}}T.style&&(V.style=T.style),T.actions&&T.actions.length>0&&T.type==="composite"&&Object.assign(V,de),T.component_layout&&(V.__componentLayoutDefs=T.component_layout);const Fe=T.expandChildren||T.props?.expandChildren,Re=T.props?.cellChildren,Ne=T.children&&T.children.length>0,ke=T.component_layout,Ze=T.slot,ze=T.props?.modalId,Ge=T.type==="composite";return(Fe||Re||Ne||ke||Ze||ze||Ge)&&(V.__componentContext=xe),V},[T.props,T.actions,T.style,T.classMap,T.id,ie,n,i,l,xe,de,wt,kt,ft,b]),Ft=N.useRef(null),Nt=N.useMemo(()=>Ft.current&&pm(Ft.current,nn)?Ft.current:(Ft.current=nn,nn),[nn]),Br=N.useMemo(()=>{const V=T.id;if(typeof V!="string"||!V.includes("{{"))return V;const se=i.resolveBindings(V,ie,{skipCache:!0});return typeof se=="string"?se:V},[T.id,ie,i]),fn=N.useMemo(()=>{const V=T.dataKey,se=T.trackChanges,ue=T.debounce;if(V){const ee=V.startsWith("_global."),ve=ee?V.slice(8):V,he=ee?e._global:ie._local;return{dataKey:ve,trackChanges:se??!1,debounce:ue,setState:ee?Ae=>{e._globalSetState?e._globalSetState(Ae):at.warn("_global.formData 사용 시 _globalSetState가 필요합니다.")}:ye,state:he??{},_isGlobal:ee}}if(Z.dataKey)return Z},[T.dataKey,T.trackChanges,T.debounce,T.id,ye,ie._local,e._global,e._globalSetState,Z]),rn=N.useRef(new Set);N.useEffect(()=>{rn.current.clear()},[e._global?._remountKeys]);const hn=N.useCallback((V,se)=>{const ue=e._global?._remountKeys;return V&&ue?.[V]&&!rn.current.has(V)?(rn.current.add(V),`${V}-remount-${ue[V]}`):V||se},[e._global?._remountKeys]),Fn=N.useMemo(()=>{if(T.text!==void 0){if(typeof T.text=="string"){const V=T.text;let se=V;const ue={componentId:T.id,componentName:T.name,propName:"text",skipCache:!0},ee=ft(V);if(ee!==null){let ve=!1,he=ee;if(ee.startsWith(er)&&(ve=!0,he=ee.slice(er.length)),Pn(he))try{se=i.evaluatePipeExpression(he,ie,{skipCache:!0},ue)}catch(Ce){at.warn(`text 파이프 표현식 평가 실패 (컴포넌트: ${T.id}):`,Ce),se=""}else if(kt(he))try{se=i.evaluateExpression(he,ie,ue)}catch(Ce){at.warn(`text 표현식 평가 실패 (컴포넌트: ${T.id}):`,Ce),se=""}else se=i.resolve(he,ie,{skipCache:!0},ue);ve&&se!=null&&(se=es(se))}else V.includes("{{")&&(se=i.resolveBindings(V,ie,{skipCache:!0},ue));return se=wt(se),se??""}return T.text}return!T.children||T.children.length===0?null:T.children.map((V,se)=>{if(typeof V=="string")return V;const ue=T.__responsiveChildrenKey,ee=ue?`responsive.${ue}.children`:"children",ve=L?`${L}.${ee}.${se}`:`${se}`,he=V._fromBase?V.id||`child-${se}`:hn(V.id,`child-${se}`),Ce=!V._fromBase&&M?`${he}_${M}`:he;return dt.jsx(jr,{componentDef:V,dataContext:ie,translationContext:n,registry:a,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:xe,parentFormContextProp:fn,isInsideIteration:b,isEditMode:S,onComponentSelect:v,onComponentHover:_,componentPath:ve,onDragStart:A,onDragEnd:x,layoutKey:M},Ce)})},[T.text,T.children,T.id,e,ie,n,a,i,l,c,xe,fn,ft,kt,wt,hn,b,S,v,_,L,A,x,M]),Pr=N.useMemo(()=>{if(!T.iteration)return null;try{const V=yd(T.iteration.source,ie,i);if(!Array.isArray(V))return at.warn(`iteration source가 배열이 아닙니다 (컴포넌트: ${T.id}):`,V),null;const se=Zr();return se?.isEnabled()&&se.trackIteration(T.id||`iteration-${Date.now()}`,T.iteration.source,T.iteration.item_var,T.iteration.index_var,V.length),V.map((ue,ee)=>{const ve={...ie,[T.iteration.item_var]:ue,[`${T.iteration.item_var}_index`]:ee};T.iteration.index_var&&(ve[T.iteration.index_var]=ee);const he=ee===0||ee===V.length-1;se?.isEnabled()&&he&&se.trackNestedContext?.({componentId:`${T.id||"unknown"}-iter-${ee}`,componentType:"iteration",parentContext:{available:Object.keys(ie),values:{}},ownContext:{added:[T.iteration.item_var,...T.iteration.index_var?[T.iteration.index_var]:[]],values:{[T.iteration.item_var]:ue,...T.iteration.index_var?{[T.iteration.index_var]:ee}:{}}},depth:1});const Ce={...T,iteration:void 0,responsive:void 0},Ae=L?`${L}.iteration.${ee}`:`iteration.${ee}`,Fe=`${hn(T.id,"item")}-${ee}`;return dt.jsx(jr,{componentDef:Ce,dataContext:ve,translationContext:n,registry:a,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:xe,parentFormContextProp:fn,isInsideIteration:!0,isEditMode:S,onComponentSelect:v,onComponentHover:_,componentPath:Ae,onDragStart:A,onDragEnd:x,layoutKey:M},Fe)})}catch(V){return at.error(`iteration 렌더링 실패 (컴포넌트: ${T.id}):`,V),null}},[T.iteration,T.children,T.id,e,ie,n,a,i,l,c,xe,fn,hn,S,v,_,L,A,x,M]),[Pt,wi]=N.useState(0),na=N.useMemo(()=>{if(!T.sortable||!T.itemTemplate)return null;const{sortable:V,itemTemplate:se}=T;try{const ue=yd(V.source,ie,i);if(!Array.isArray(ue))return at.warn(`sortable source가 배열이 아닙니다 (컴포넌트: ${T.id}):`,ue),null;if(ue.length===0)return null;const ee=V.itemKey||"id",ve=V.strategy||"verticalList",he=V.itemVar||"$item",Ce=V.indexVar||"$index",Ae=V.handle,Fe=V.wrapperElement,Re=(Ze,ze)=>{const Ge=T.actions?.filter(we=>we.event==="onSortEnd"||we.type==="onSortEnd");if(wi(we=>we+1),Ge&&Ge.length>0&&c){const we={...ie,$sortedItems:Ze,$sortEvent:ze};Ge.forEach(He=>{try{const et=c.createHandler(He,we,xe),_t=new Event("sortend");et(_t)}catch(et){at.error(`onSortEnd action failed: ${He.handler}`,et)}})}},Ne=Ze=>{const ze=T.actions?.filter(Ge=>Ge.event==="onSortStart"||Ge.type==="onSortStart");if(ze&&ze.length>0&&c){const Ge={...ie,$activeId:Ze.activeId};ze.forEach(we=>{try{const He=c.createHandler(we,Ge,xe),et=new Event("sortstart");He(et)}catch(He){at.error(`onSortStart action failed: ${we.handler}`,He)}})}},ke=ue.map((Ze,ze)=>{const Ge=String(Ze[ee]),we={...ie,[he]:Ze,[Ce]:ze},He=L?`${L}.sortable.${ze}`:`sortable.${ze}`,et=`${hn(T.id,"sortable-item")}-v${Pt}-${Ge}`;return dt.jsx(A_,{id:Ge,handle:Ae,...Fe?{as:Fe}:{},children:(Fe&&se.children?se.children:[se]).map((_t,Lt)=>dt.jsx(jr,{componentDef:_t,dataContext:we,translationContext:n,registry:a,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:xe,parentFormContextProp:void 0,isInsideIteration:!0,isEditMode:S,onComponentSelect:v,onComponentHover:_,componentPath:He,onDragStart:A,onDragEnd:x,layoutKey:M},`${et}-child-${Lt}`))},et)});return dt.jsx(C_,{items:ue,itemKey:ee,strategy:ve,onSortEnd:Re,onSortStart:Ne,sortVersion:Pt,children:ke})}catch(ue){return at.error(`sortable 렌더링 실패 (컴포넌트: ${T.id}):`,ue),null}},[T.sortable,T.itemTemplate,T.actions,T.id,e,ie,n,a,i,l,c,xe,hn,S,v,_,L,A,x,Pt,M]),gn=N.useRef(!1);N.useEffect(()=>{if(gn.current)return;gn.current=!0;const V=Zr();if(V?.isEnabled()&&V.trackMount(o.id,{name:o.name,type:o.type||"component",props:Nt}),o.lifecycle?.onMount&&o.lifecycle.onMount.length>0)for(const ue of o.lifecycle.onMount)try{const ee=c.createHandler(ue,ie,xe),ve=new Event("mount");ee(ve),at.log(`Lifecycle onMount executed: ${ue.handler} (Component: ${o.id})`)}catch(ee){at.error(`Lifecycle onMount failed: ${ue.handler} (Component: ${o.id})`,ee)}const se=[];if(o.onComponentEvent&&o.onComponentEvent.length>0){const ue=window.G7Core;if(ue?.componentEvent?.on)for(const ee of o.onComponentEvent){if(!ee.event){at.warn(`onComponentEvent: event name is required (Component: ${o.id})`);continue}const ve=async Ce=>{try{const Ae={...ie,_eventData:Ce},Re=await c.createHandler({handler:ee.handler,params:ee.params,onSuccess:ee.onSuccess,onError:ee.onError},Ae,xe)(new CustomEvent(ee.event,{detail:Ce}));return at.log(`onComponentEvent "${ee.event}" handled: ${ee.handler} (Component: ${o.id})`,{eventData:Ce,result:Re}),Re}catch(Ae){throw at.error(`onComponentEvent "${ee.event}" failed: ${ee.handler} (Component: ${o.id})`,Ae),Ae}},he=ue.componentEvent.on(ee.event,ve);se.push(he),at.log(`onComponentEvent: Subscribed to "${ee.event}" (Component: ${o.id})`)}else at.warn(`onComponentEvent: G7Core.componentEvent is not available (Component: ${o.id})`)}return()=>{const ue=Zr();ue?.isEnabled()&&ue.trackUnmount(o.id);for(const ee of se)try{ee()}catch(ve){at.error(`onComponentEvent: Failed to unsubscribe (Component: ${o.id})`,ve)}if(se.length>0&&at.log(`onComponentEvent: Unsubscribed ${se.length} event(s) (Component: ${o.id})`),o.lifecycle?.onUnmount&&o.lifecycle.onUnmount.length>0)for(const ee of o.lifecycle.onUnmount)try{const ve=c.createHandler(ee,ie,xe),he=new Event("unmount");ve(he),at.log(`Lifecycle onUnmount executed: ${ee.handler} (Component: ${o.id})`)}catch(ve){at.error(`Lifecycle onUnmount failed: ${ee.handler} (Component: ${o.id})`,ve)}}},[]);const Rn=N.useMemo(()=>{const V=Nt.dataKey,se=Nt.trackChanges,ue=Nt.debounce;return V?{dataKey:V,trackChanges:se??!1,debounce:ue,setState:ye,state:de}:null},[Nt.dataKey,Nt.trackChanges,Nt.debounce,ye,de]);N.useEffect(()=>{const V=T.dataKey||Nt.dataKey;if(!V)return;const se=Zr();if(!se?.isEnabled())return;const ue=[],ee=he=>{if(he)for(const Ce of he){const Ae=Ce?.props?.name;if(Ae&&ue.push({name:Ae,type:Ce.name||Ce.type||"unknown"}),Ce?.children&&ee(Ce.children),Ce?.slots)for(const Fe of Object.values(Ce.slots))Array.isArray(Fe)&&ee(Fe)}};if(o.children&&ee(o.children),o.slots)for(const he of Object.values(o.slots))Array.isArray(he)&&ee(he);const ve=o.id||`form-${V}`;return se.trackForm(ve,V,ue),()=>{se.untrackForm(ve)}},[T,Nt.dataKey,o.id,o.children]);const tt=N.useRef(null),$n=N.useRef(void 0);N.useEffect(()=>{const V=Nt?.name;if(!V||!Z.dataKey||!Z.setState||Nt?.autoBinding===!1)return;const se=`${Z.dataKey}.${V}`,ue=window.__g7AutoBindingPaths??new Map;return window.__g7AutoBindingPaths=ue,ue.set(se,(ue.get(se)??0)+1),()=>{const ee=ue.get(se)??0;ee<=1?ue.delete(se):ue.set(se,ee-1)}},[Nt?.name,Nt?.autoBinding,Z.dataKey,Z.setState]);const pn=N.useMemo(()=>{const{dataKey:V,trackChanges:se,debounce:ue,...ee}=Nt,ve=ee.name;if(!ve||!Z.dataKey||!Z.setState)return ee;if(ee.autoBinding===!1){const{autoBinding:Ge,...we}=ee;return we}const he=`${Z.dataKey}.${ve}`,Ce=EC(Z.state,he),Ae=Ce!==void 0?Ce:ee.value,Re=a.getMetadata(o.name)?.bindingType,Ne=typeof Ae=="boolean"&&(Re==="checked"||Re==="checkable"&&["checkbox","radio"].includes(ee?.type)),ke=Z.debounce,Ze=Ge=>{const we=Z.state||{},He=_C(we,he,Ge);if(Z.trackChanges&&(He.hasChanges=!0),window.__g7PendingLocalState=He,Z.setState(He),Z._isGlobal)return;const et=window.G7Core,_t={[he]:Ge};Z.trackChanges&&(_t.hasChanges=!0),et?.state?.setLocal?.(_t,{render:!1})},ze=(Ge,we)=>{ke&&ke>0?(tt.current&&clearTimeout(tt.current),tt.current=setTimeout(()=>{Ze(Ge),tt.current=null,we&&(we(),window.__g7PendingLocalState=null)},ke)):(Ze(Ge),we&&(we(),window.__g7PendingLocalState=null))};if(Ne)return{...ee,checked:Ae,onChange:we=>{const He=we.target.checked;Ze(He),ee.onChange&&ee.onChange(we)}};{const Ge=He=>{const et=He?.target?.value!==void 0?He.target.value:He;ke&&ke>0&&($n.current=et);const _t=He?.target?{target:{value:et,name:He.target.name,type:He.target.type,checked:He.target.checked},currentTarget:He.currentTarget?{value:et,name:He.currentTarget.name}:void 0}:He;ze(et,()=>{ee.onChange&&ee.onChange(_t)})};let we;return $n.current!==void 0?tt.current!==null?we=$n.current:String(Ae??"")===String($n.current)?($n.current=void 0,we=Ae??""):we=$n.current:we=Ae??"",{...ee,value:we,onChange:Ge}}},[Nt,Z,Z.state,Z.debounce]),ra=N.useMemo(()=>{const V=Zr();if(V?.isEnabled()&&V.trackRender(o.name),!_e)return T.iteration?Pr:null;if(T.sortable&&T.itemTemplate)return na;if(T.iteration)return Pr;if(T.type==="extension_point"){const{layout:Re,columns:Ne,gap:ke,className:Ze,...ze}=T.props||{};let Ge=Ze||"";return Re==="grid"&&Ne?Ge=`${Ge} grid grid-cols-${Ne} gap-${ke||4}`.trim():Re==="flex"&&(Ge=`${Ge} flex flex-col gap-${ke||4}`.trim()),dt.jsx("div",{id:Br,className:Ge||void 0,...ze,children:Fn})}const se=a.getComponent(T.name);if(!se)return at.error(`컴포넌트를 찾을 수 없습니다: ${T.name} (ID: ${T.id})`,"componentDef:",JSON.stringify(T,null,2)),null;const ue=e._global?._remountKeys,ee={...pn,id:pn.id??Br,...ue&&Object.keys(ue).length>0&&{__remountTrigger:JSON.stringify(ue)}};if(H?.listeners&&H.handle&&pn["data-drag-handle"]!==void 0&&(Object.assign(ee,H.listeners),ee.style={...ee.style,cursor:H.isDragging?"grabbing":"grab"}),S){const Re=T.id||`auto_${T.name||T.type||"unknown"}_${Math.random().toString(36).substring(2,8)}`,Ne=ze=>{typeof ze.preventDefault=="function"&&ze.preventDefault(),v&&(ze.stopPropagation(),v(Re,ze))},ke={"data-editor-id":Re,"data-editor-name":T.name,"data-editor-type":T.type,onClick:Ne};L&&(ke["data-editor-path"]=L);const Ze=T.__editorSlotName??T.slot;typeof Ze=="string"&&(ke["data-editor-slot"]=Ze),_&&(ke.onMouseMove=ze=>{ze.stopPropagation(),_(Re,ze)},ke.onMouseLeave=ze=>{_(null,ze)}),Object.assign(ee,ke),ee.editorAttrs=ke}const ve=T.type==="basic",he=T.type==="layout",Ae=ve||he?(()=>{const Re={};for(const[Ne,ke]of Object.entries(ee))Ne.startsWith("__")||Ne==="editorAttrs"&&ve||(Re[Ne]=ke);return Re})():ee;let Fe=dt.jsx(se,{...Ae,children:Fn});if(fn&&(Fe=dt.jsx(wC,{value:fn,children:Fe})),T.isolatedState){const Re=typeof T.isolatedState=="object"?T.isolatedState:{},Ne=e?._isolatedInit,ke=Ne?{...Re,...Ne}:Re;Fe=dt.jsx(DC,{initialState:ke,scopeId:T.isolatedScopeId,children:Fe})}return Fe},[_e,T.iteration,T.sortable,T.itemTemplate,T.type,T.name,T.id,T.props,T.isolatedState,T.isolatedScopeId,a,pn,Fn,Pr,na,H,Rn,S,v,_,A,x,L,e._global?._remountKeys]),ir=N.useMemo(()=>{const V=T.blur_until_loaded;if(!V||e?._global?.__isPreview)return!1;if(typeof V=="string"){const ee=ft(V);if(ee!==null)try{const ve={componentId:T.id,componentName:T.name,propName:"blur_until_loaded"};return!!i.evaluateExpression(ee,ie,ve)}catch(ve){return at.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(Ce=>e[Ce]===void 0);if(fe)return!0;const ee=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(he=>!ee.includes(he)&&!he.startsWith("_")).some(he=>e[he]===void 0)}if(fe)return!0;const se=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(ee=>!se.includes(ee)&&!ee.startsWith("_")).some(ee=>e[ee]===void 0)},[T.blur_until_loaded,T.id,fe,e,ie,i,ft]);if(ir){const V=T.blur_until_loaded;if(typeof V=="object"&&V?.data_sources){const ue=(Array.isArray(V.data_sources)?V.data_sources:[V.data_sources]).reduce((ve,he)=>(ve[he]=e[he]===void 0?"UNDEFINED":"LOADED",ve),{}),ee=Object.keys(e).filter(ve=>!ve.startsWith("_"));at.log(`[BLUR APPLIED] Component: ${T.id}, data_sources status:`,ue,"Available keys:",ee)}else at.log(`[BLUR APPLIED] Component: ${T.id}, blur_until_loaded:`,V)}const an=N.useMemo(()=>{if(!T.blur_until_loaded)return{wrapperClasses:"",innerClasses:""};const V=nn?.className||"";if(!V)return{wrapperClasses:"",innerClasses:""};const se=[/^(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-)/],ue=V.split(/\s+/).filter(Boolean),ee=[],ve=[];for(const he of ue)se.some(Ae=>Ae.test(he))?ee.push(he):ve.push(he);return{wrapperClasses:ee.join(" "),innerClasses:ve.join(" ")}},[T.blur_until_loaded,nn?.className]),En=window.__slotContextValue;return Te&&En?.isEnabled?null:dt.jsx(R_,{componentId:o.id,componentName:o.name,children:T.blur_until_loaded?dt.jsx("div",{className:[an.wrapperClasses,ir?"opacity-50 blur-sm transition-all duration-300 pointer-events-none":void 0].filter(Boolean).join(" ")||void 0,children:ra}):ra})});jr.displayName="DynamicRenderer",typeof window<"u"&&(window.__DynamicRenderer=jr);function k_(o){const e={};try{const a=new URL(o,typeof window<"u"?window.location.origin:"http://localhost").searchParams,i=new Set;for(const l of a.keys()){if(i.has(l))continue;i.add(l);const c=a.getAll(l);c.length>1||l.endsWith("[]")?e[l]=c:e[l]=c[0]}}catch{}return e}function D_(o){try{return new URL(o,typeof window<"u"?window.location.origin:"http://localhost").pathname}catch{return o.split("?")[0]}}const Si=class Si{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 Si.instance||(Si.instance=new Si),Si.instance}initialize(){if(this.config.enabled=this.checkDebugMode(),!this.config.enabled){console.log("[G7DevTools] 비활성화됨 (환경설정 > 고급 설정 > 디버그 모드를 켜세요)");return}console.log("[G7DevTools] 활성화됨"),this.setupGlobalErrorHandler()}checkDebugMode(){try{if(window.G7Config?.debug===!0)return!0;const a=window.G7Core?.state?.get?.();return a?.settings?.advanced?.debug_mode===!0||a?._global?.settings?.advanced?.debug_mode===!0}catch{return!1}}isEnabled(){return this.config.enabled}setupGlobalErrorHandler(){window.addEventListener("error",e=>{this.config.enabled&&this.logAction({id:this.generateId(),type:"globalError",startTime:Date.now(),status:"error",error:{name:"Error",message:e.message,stack:e.error?.stack}})}),window.addEventListener("unhandledrejection",e=>{this.config.enabled&&this.logAction({id:this.generateId(),type:"unhandledRejection",startTime:Date.now(),status:"error",error:{name:"UnhandledRejection",message:String(e.reason)}})})}captureStateSnapshot(e){if(!this.config.enabled)return;const 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?.()||{},a={};if(e?._isolatedStates&&typeof e._isolatedStates=="object")for(const[i,l]of Object.entries(e._isolatedStates))a[i]=this.sanitizeObject(l);return{_global:n._global||n,_local:this.currentLocalState,_computed:this.currentComputedState,_isolated:Object.keys(a).length>0?a:void 0,$parent:this.currentParentContext}}catch{return{_global:{},_local:this.currentLocalState,_computed:this.currentComputedState}}}updateLocalState(e){this.config.enabled&&(this.currentLocalState=this.sanitizeObject(e))}updateComputedState(e){this.config.enabled&&(this.currentComputedState=this.sanitizeObject(e))}updateParentContext(e){this.config.enabled&&(this.currentParentContext=e?this.sanitizeObject(e):void 0)}getStateHistory(){return[...this.stateHistory]}getDualStorageMismatch(){const e=this.currentLocalState||{};let n={};try{n=(window.G7Core?.state?.get?.()||{})._local||{}}catch{n={}}const a=this.findMismatchedLeafPaths(e,n);return{hasMismatch:a.length>0,mismatchedPaths:a,storageA:e,storageB:n}}findMismatchedLeafPaths(e,n,a=""){const i=[],l=new Set([...Object.keys(e||{}),...Object.keys(n||{})]);for(const c of l){const d=a?`${a}.${c}`:c,f=e?.[c],g=n?.[c],m=f&&typeof f=="object"&&!Array.isArray(f),b=g&&typeof g=="object"&&!Array.isArray(g);if(m&&b)i.push(...this.findMismatchedLeafPaths(f,g,d));else{const S=f===void 0?"__undefined__":JSON.stringify(f),v=g===void 0?"__undefined__":JSON.stringify(g);S!==v&&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(a){console.error("[G7DevTools] State watcher error:",a)}}),e.diff)for(const n of e.diff.changed)this.stateWatchers.get(n.path)?.forEach(a=>{try{a(n.newValue,n.oldValue,n.path)}catch(i){console.error("[G7DevTools] State watcher error:",i)}})}diffSnapshots(e,n){const a=this.stateHistory.find(l=>l.id===e),i=this.stateHistory.find(l=>l.id===n);return!a||!i?null:this.calculateDiff(a.next,i.next)}calculateDiff(e,n,a=""){const i={added:[],removed:[],changed:[]},l=new Set(Object.keys(e)),c=new Set(Object.keys(n));for(const d of c){const f=a?`${a}.${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=a?`${a}.${d}`:d;c.has(d)||i.removed.push(f)}return i}logAction(e){if(!this.config.enabled)return;const n=this.actionHistory.findIndex(a=>a.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(a){console.error("[G7DevTools] Action watcher error:",a)}})}getActionMetrics(){const e=this.actionHistory.filter(l=>l.status==="success"),n=this.actionHistory.filter(l=>l.status==="error"),a={};for(const l of this.actionHistory)a[l.type]=(a[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:a}}recordCacheHit(){this.config.enabled&&this.cacheStats.hits++}recordCacheMiss(){this.config.enabled&&this.cacheStats.misses++}updateCacheEntries(e){this.config.enabled&&(this.cacheStats.entries=e)}getCacheStats(){const e=this.cacheStats.hits+this.cacheStats.misses;return{...this.cacheStats,hitRate:e>0?this.cacheStats.hits/e:0}}resetCacheStats(){this.cacheStats={hits:0,misses:0,entries:0}}trackCacheDecision(e){if(!this.config.enabled)return;const 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,a=0,i=0,l=0;const c={},d={};for(const g of e)g.decision==="cache_hit"?n++:g.decision==="cache_miss"?a++:g.decision==="skip_cache"?i++:g.decision==="invalidate"&&l++,c[g.reason]=(c[g.reason]||0)+1,g.context.componentId&&(d[g.context.componentId]=(d[g.context.componentId]||0)+1);const f=n+a+i;return{totalDecisions:e.length,cacheHits:n,cacheMisses:a,skipCacheCount:i,invalidateCount:l,byReason:c,byComponent:d,avgHitRate:f>0?n/f:0}}getRecentCacheDecisions(e=20,n){let a=[...this.cacheDecisions];return n&&(a=a.filter(i=>i.decision===n)),a.slice(-e)}clearCacheDecisionData(){this.cacheDecisions=[],this.cacheDecisionIdCounter=0}summarizePropsForLifecycle(e){if(!e||typeof e!="object")return e;const n={},a=["children","ref","key"];for(const[i,l]of Object.entries(e))if(!a.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 a=this.summarizePropsForLifecycle(n.props),i={...n,props:a,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),a=this.eventListeners.get(e)||[];a.length>0&&console.warn(`[G7DevTools] 컴포넌트 ${e} 언마운트 시 ${a.length}개 리스너 미정리`),n&&this.unmountWatchers.forEach(i=>{try{i({componentId:e,componentName:n.name,timestamp:Date.now(),orphanedListeners:a.length})}catch(l){console.error("[G7DevTools] Unmount watcher error:",l)}}),this.mountedComponents.delete(e)}trackListener(e,n,a){if(!this.config.enabled)return;const i=this.eventListeners.get(e)||[];i.push({type:n,target:a,addedAt:Date.now()}),this.eventListeners.set(e,i)}removeListener(e,n){if(!this.config.enabled)return;const a=this.eventListeners.get(e)||[],i=a.findIndex(l=>l.type===n);i>=0&&a.splice(i,1)}getMountedComponents(){return Array.from(this.mountedComponents.values())}getOrphanedListeners(){const e=[];for(const[n,a]of this.eventListeners)this.mountedComponents.has(n)||e.push(...a.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 a=Array.from(this.renderCounts.entries()).filter(([,i])=>i>50);return a.length>0&&e.push({type:"excessive-renders",message:`${a.length}개 컴포넌트가 50회 이상 렌더링`,suggestion:"React.memo, useMemo, useCallback 사용 고려",severity:"warning"}),e}startProfiling(){this.config.enabled&&(this.isProfiling=!0,this.profilingData=[],this.profilingStartTime=performance.now(),console.log("[G7DevTools] 프로파일링 시작"))}stopProfiling(){this.isProfiling=!1;const e=performance.now()-this.profilingStartTime,n=this.analyzeProfile(e);return console.log("[G7DevTools] 프로파일링 완료",n),n}analyzeProfile(e){const n=this.profilingData.filter(g=>g.type==="render"),a=this.profilingData.filter(g=>g.type==="binding"),i=this.profilingData.filter(g=>g.type==="action"),l={};for(const g of n)g.component&&(l[g.component]||(l[g.component]={count:0,durations:[]}),l[g.component].count++,g.duration&&l[g.component].durations.push(g.duration));const c=Object.entries(l).map(([g,m])=>({name:g,renderCount:m.count,avgDuration:m.durations.length>0?m.durations.reduce((b,S)=>b+S,0)/m.durations.length:0})).sort((g,m)=>m.renderCount-g.renderCount).slice(0,10),d={};for(const g of a)g.expression&&(d[g.expression]=(d[g.expression]||0)+1);const f=Object.entries(d).sort(([,g],[,m])=>m-g).slice(0,10).map(([g])=>g);return{duration:e,entries:this.profilingData,summary:{totalRenders:n.length,totalBindings:a.length,totalActions:i.length,slowestComponents:c,hotPaths:f}}}resetPerformanceStats(){this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[]}trackRequest(e,n,a){if(!this.config.enabled)return"";const i=this.generateId(),l=D_(e),c=k_(e);return this.activeRequests.set(i,{id:i,url:l,fullUrl:e,queryParams:c,method:n,startTime:Date.now(),status:"pending",requestBody:a?.requestBody?this.sanitizeObject(a.requestBody):void 0,dataSourceId:a?.dataSourceId}),this.isProfiling&&this.profilingData.push({type:"network",timestamp:performance.now()}),i}completeRequest(e,n,a){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(a)};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 a=this.activeRequests.get(e);if(!a)return;const i={...a,status:"error",error:n,duration:Date.now()-a.startTime,endTime:Date.now()};this.requestHistory.push(i),this.activeRequests.delete(e),this.notifyRequestWatchers(i)}trackDataSource(e){this.config.enabled&&this.pendingDataSources.add(e)}completeDataSource(e){this.config.enabled&&this.pendingDataSources.delete(e)}getActiveRequests(){return Array.from(this.activeRequests.values())}getRequestHistory(){return[...this.requestHistory]}getPendingDataSources(){return Array.from(this.pendingDataSources)}watchRequest(e){return this.requestWatchers.add(e),()=>{this.requestWatchers.delete(e)}}notifyRequestWatchers(e){this.requestWatchers.forEach(n=>{try{n(e)}catch(a){console.error("[G7DevTools] Request watcher error:",a)}})}trackWebSocketConnection(e,n,a){this.config.enabled&&this.wsConnections.set(e,{id:e,url:n,state:a,connectedAt:a==="open"?Date.now():void 0})}trackWebSocketMessage(e,n,a,i){if(!this.config.enabled)return;const l={id:this.generateId(),connectionId:e,direction:n,type:a,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(a){console.error("[G7DevTools] WebSocket watcher error:",a)}})}trackIfCondition(e,n,a){if(!this.config.enabled)return;const i=this.ifConditions.get(e),l=i?.evaluatedValue;this.ifConditions.set(e,{id:e,expression:n,evaluatedValue:a,evaluationCount:(i?.evaluationCount||0)+1,lastEvaluated:Date.now()}),i&&l!==a&&this.notifyConditionWatchers({id:e,expression:n,oldValue:l,newValue:a,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=[],a=this.getState();return n.push({name:"_global",value:a._global,source:"global"}),n.push({name:"_local",value:a._local,source:"local"}),n.push({name:"_computed",value:a._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(a){console.error("[G7DevTools] Condition watcher error:",a)}})}trackForm(e,n,a){this.config.enabled&&this.forms.set(e,{id:e,dataKey:n,inputs:a,trackedAt:Date.now()})}trackFormChange(e,n,a){if(!this.config.enabled)return;const i={formId:e,inputName:n,value:a,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(a){console.error("[G7DevTools] Form watcher error:",a)}})}trackFormBindingIssue(e,n,a){if(!this.config.enabled)return;const i={id:`form-issue-${++this.formBindingIssueIdCounter}`,timestamp:Date.now(),type:e,severity:n,formId:a.formId,formDataKey:a.formDataKey,inputInfo:a.inputInfo,contextInfo:a.contextInfo,description:a.description,suggestion:a.suggestion,docLink:a.docLink};this.formBindingIssues.push(i),this.formBindingIssues.length>this.maxFormBindingIssues&&this.formBindingIssues.shift()}validateFormBinding(e,n,a,i){const l=a.map(f=>{const g=[];let m=!0;return f.name||(g.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||(g.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:g}});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 a=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:a}}getIssueTypeDescription(e){return{"missing-datakey":"Form에 dataKey 누락","missing-input-name":"Input에 name 속성 누락","context-not-propagated":"Form 컨텍스트 전파 실패","sortable-context-break":"Sortable 컨테이너에서 컨텍스트 단절","modal-context-isolation":"모달에서 부모 Form 컨텍스트 격리","duplicate-input-name":"동일 Form 내 중복 Input name","value-type-mismatch":"값 타입과 Input 타입 불일치","binding-path-invalid":"바인딩 경로 유효하지 않음"}[e]||e}clearFormBindingIssues(){this.formBindingIssues=[],this.formBindingValidations=[],this.formBindingIssueIdCounter=0}trackComputedProperty(e,n,a,i,l,c,d){if(!this.config.enabled)return;const f=`computed-${e}-${c||"global"}`,g={id:f,name:e,expression:n,componentId:c,dependencies:a,currentValue:this.safeClone(i),lastComputedAt:Date.now(),computationTime:l,error:d};this.computedProperties.set(f,g)}trackComputedRecalc(e,n,a,i,l,c,d){if(!this.config.enabled)return;const f=`computed-${e}-${d||"global"}`,g=JSON.stringify(a)!==JSON.stringify(i),m={id:`recalc-${++this.computedRecalcIdCounter}`,computedId:f,computedName:e,timestamp:Date.now(),trigger:n,triggeredBy:c,previousValue:this.safeClone(a),newValue:this.safeClone(i),valueChanged:g,computationTime:l,cascadeCount:0};this.computedRecalcLogs.push(m),this.computedRecalcLogs.length>this.maxComputedRecalcLogs&&this.computedRecalcLogs.shift();const b=this.computedProperties.get(f);b&&(b.currentValue=this.safeClone(i),b.lastComputedAt=Date.now(),b.computationTime=l)}analyzeComputedDependencyChain(e,n){const a=new Set,i=[];let l=!1,c,d=0;const f=(m,b)=>{if(d=Math.max(d,b),a.has(m))return l=!0,c=[...i,m],{name:m,type:"computed",children:[],depth:b};a.add(m),i.push(m);const S=this.computedProperties.get(`computed-${m}-${n||"global"}`),v=[];if(S)for(const _ of S.dependencies)_.type==="computed"?v.push(f(_.path,b+1)):v.push({name:_.path,type:_.type,children:[],depth:b+1});return i.pop(),a.delete(m),{name:m,type:"computed",children:v,depth:b}},g=f(e,0);return{root:e,tree:g,hasCycle:l,cyclePath:c,maxDepth:d}}getComputedDependencyTrackingInfo(){const e=Array.from(this.computedProperties.values()),n=this.getComputedDependencyStats(),a=[];for(const i of e){const l=this.analyzeComputedDependencyChain(i.name,i.componentId);a.push(l)}return{properties:e,recalcLogs:[...this.computedRecalcLogs],dependencyChains:a,stats:n,timestamp:Date.now()}}getComputedDependencyStats(){const e={"state-change":0,"datasource-update":0,"dependency-change":0,manual:0,initial:0},n={},a={};let i=0,l=0;for(const g of this.computedRecalcLogs)e[g.trigger]++,g.valueChanged||l++,n[g.computedName]=(n[g.computedName]||0)+1,a[g.computedName]||(a[g.computedName]=[]),a[g.computedName].push(g.computationTime),i+=g.computationTime;const c=Object.entries(n).sort((g,m)=>m[1]-g[1]).slice(0,5).map(([g,m])=>({name:g,count:m})),d=Object.entries(a).map(([g,m])=>({name:g,avgTime:m.reduce((b,S)=>b+S,0)/m.length})).sort((g,m)=>m.avgTime-g.avgTime).slice(0,5);let f=0;for(const g of this.computedProperties.values())this.analyzeComputedDependencyChain(g.name,g.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 a=this.modalStates.get(e);a&&(a.closedAt=Date.now(),n&&(a.currentState={...n}),this.detectStateLeakage(a))}validateModalDefinitionExists(e,n){const a=this.currentLayout;if(!a?.layoutJson)return;const i=a.layoutJson.modals;if(!i){this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:n,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 현재 레이아웃에 modals 섹션이 없습니다. 레이아웃 경로: ${a.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 상속 누락 등을 확인하세요. 레이아웃 경로: ${a.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 a=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:a};this.modalStateChangeLogs.push(i),this.modalStateChangeLogs.length>this.maxModalStateChangeLogs&&this.modalStateChangeLogs.shift(),a&&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 a=e.initialState[n],i=e.currentState[n];if(a!==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:a})}}}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},a={"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]++,a[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:a,byScope:i,leakageDetectionCount:a["state-leakage"],cleanupFailureCount:a["cleanup-failure"]}}clearModalStateScopeTracking(){this.modalStates.clear(),this.modalStateIssues=[],this.modalStateRelations=[],this.modalStateChangeLogs=[],this.modalStateIssueIdCounter=0,this.modalStateChangeLogIdCounter=0}setNamedActionDefinitions(e){this.config.enabled&&(this.namedActionDefinitions=e||{})}trackNamedActionRef(e){if(!this.config.enabled)return;const 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 a of this.namedActionRefLogs)e[a.actionRefName]=(e[a.actionRefName]||0)+1;const n=Object.keys(this.namedActionDefinitions).filter(a=>!e[a]);return{definitions:this.namedActionDefinitions,refLogs:[...this.namedActionRefLogs],stats:{totalDefinitions:Object.keys(this.namedActionDefinitions).length,totalRefs:this.namedActionRefLogs.length,refCountByName:e,unusedDefinitions: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:a,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(a);if(d.includes("[object Object]")||/^\[.*\]$/.test(d))return{type:"array-to-string",message:"배열/객체가 문자열로 변환되었습니다",suggestion:"evaluateExpression()을 사용하여 원본 타입을 유지하세요"}}if(l==="resolveBindings"&&i==="string"&&String(a).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(g=>g.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(a=>a.expression.toLowerCase().includes(n)||a.componentName?.toLowerCase().includes(n)||a.propName?.toLowerCase().includes(n))}getExpressionStats(){const e=this.expressionHistory,n=new Set(e.map(f=>f.expression)),a=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 a)f.warning&&(d[f.warning.type]=(d[f.warning.type]||0)+1);return{totalEvaluations:e.length,uniqueExpressions:n.size,warningCount:a.length,cacheHitRate:e.length>0?i.length/e.length:0,averageDuration:l.length>0?l.reduce((f,g)=>f+g,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(a){console.error("[G7DevTools] Expression watcher error:",a)}})}setLogLevel(e){this.config.logLevel=e}setMaxHistory(e){this.config.maxHistorySize=Math.max(10,Math.min(1e3,e))}setServerEndpoint(e){this.config.serverEndpoint=e}getConfig(){return{...this.config}}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}sanitizeObject(e,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 a={};for(const i of Object.keys(e))try{a[i]=this.sanitizeObject(e[i],n)}catch{a[i]="[Unable to serialize]"}return a}getNestedValue(e,n){if(!n)return e;const a=n.split(".");let i=e;for(const l of a){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(a=>a.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,a){if(!this.config.enabled)return;const i=a.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(a),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(a=>a.handler.includes(e.handler))),e?.status&&(n=n.filter(a=>a.status===e.status)),e?.limit&&(n=n.slice(-e.limit)),n}getDataSourceUpdateHistory(e){let n=[...this.dataSourceUpdateHistory];return e?.dataSourceId&&(n=n.filter(a=>a.dataSourceId===e.dataSourceId)),e?.updateType&&(n=n.filter(a=>a.updateType===e.updateType)),e?.limit&&(n=n.slice(-e.limit)),n}getLogs(e){let n=[...this.logHistory];if(e?.level){const a=Array.isArray(e.level)?e.level:[e.level];n=n.filter(i=>a.includes(i.level))}if(e?.prefix){const a=e.prefix.toLowerCase();n=n.filter(i=>i.prefix.toLowerCase().includes(a))}if(e?.search){const a=e.search.toLowerCase();n=n.filter(i=>i.message.toLowerCase().includes(a))}return e?.since&&(n=n.filter(a=>a.timestamp>=e.since)),e?.limit&&(n=n.slice(-e.limit)),n}getLogStats(){const n=Date.now()-6e4,a={log:0,warn:0,error:0,debug:0,info:0},i={};let l=0,c=0;for(const d of this.logHistory)a[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:a,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,a){if(!this.config.enabled)return;const i=this.dataSources.get(e);if(!i)return;let l,c,d=a;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 a=this.dataSources.get(e);a&&this.dataSources.set(e,{...a,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(a=>a.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 a=this.dataPathTransforms.find(i=>i.dataSourceId===e);a&&(a.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 a=0;const i={};for(const c of e){n[c.dataSourceId]=(n[c.dataSourceId]||0)+1,a+=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:a,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}`,a=[...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:a,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 a=this.nestedContexts.find(i=>i.id===e);a&&a.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 a=0,i=0;const l={};for(const d of e){n[d.componentType]++,d.depth>a&&(a=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:a,failedAccessCount:i,commonFailedPaths:c}}getNestedContextForComponent(e){return this.nestedContexts.find(n=>n.componentId===e)}clearNestedContexts(){this.nestedContexts=[],this.nestedContextIdCounter=0}trackHandlerRegistration(e,n="custom",a,i){this.isEnabled&&this.handlers.set(e,{name:e,category:n,description:a,registeredAt:Date.now(),source:i})}trackHandlerUnregistration(e){this.isEnabled&&this.handlers.delete(e)}getHandlers(){return Array.from(this.handlers.values())}getHandler(e){return this.handlers.get(e)}getHandlersByCategory(e){return Array.from(this.handlers.values()).filter(n=>n.category===e)}clearHandlers(){this.handlers.clear()}trackEventSubscribe(e){if(!this.isEnabled)return;const n=this.componentEventSubscriptions.get(e),a=Date.now();n?(n.subscriberCount++,n.lastSubscribedAt=a):this.componentEventSubscriptions.set(e,{eventName:e,subscriberCount:1,firstSubscribedAt:a,lastSubscribedAt:a})}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,a,i,l){if(!this.isEnabled)return;const c={id:`evt_${++this.componentEventIdCounter}`,eventName:e,data:this.sanitizeForLogging(n),timestamp:Date.now(),listenerCount:a,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,a)=>n+a.subscriberCount,0),totalEmits:this.componentEventEmitHistory.length}}getEventEmitHistory(){return[...this.componentEventEmitHistory]}getEventSubscriptions(){return Array.from(this.componentEventSubscriptions.values())}clearComponentEvents(){this.componentEventSubscriptions.clear(),this.componentEventEmitHistory=[],this.componentEventIdCounter=0}sanitizeForLogging(e){if(e==null||typeof e!="object")return e;try{return JSON.parse(JSON.stringify(e))}catch{return"[Circular or Non-serializable]"}}startStateChange(e,n,a,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(a),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,a,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:a,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),a={};for(const[i,l]of this.stateToComponentMap)a[i]=Array.from(l);return{logs:e,componentRenderCounts:n,stateToComponentMap:a,stats:this.calculateStateRenderingStats()}}calculateStateRenderingStats(){const e=this.stateRenderingLogs;if(e.length===0)return{totalStateChanges:0,totalRenders:0,avgRenderDuration:0,avgComponentsPerChange:0,topRenderedComponents:[],topInfluentialPaths:[]};const n=e.reduce((d,f)=>d+f.renderedComponents.length,0),a=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:a,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(a=>a.componentName===e))}clearStateRenderingLogs(){this.stateRenderingLogs=[],this.componentRenderCounts.clear(),this.stateToComponentMap.clear(),this.currentStateChangeContext=null,this.stateRenderingIdCounter=0}trackComponentStateSource(e,n,a,i){this.config.enabled&&this.componentStateSources.set(e,{componentId:e,componentName:n,stateSource:a,stateProvider:i})}trackDynamicState(e,n){this.config.enabled&&this.dynamicStates.set(e,n)}trackContextFlow(e,n,a,i,l,c){if(!this.config.enabled)return;const d={component:n,componentId:e,contextReceived:a,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(),a=this.detectStateConflicts(n),i=Array.from(this.componentStateSources.values());return{layers:e?n.map(c=>({...c,values:this.summarizeValues(c.values,2)})):n,conflicts:a,componentStateSources:i,timestamp:Date.now()}}summarizeValues(e,n,a=0){if(e==null)return e;if(typeof e!="object")return typeof e=="string"&&e.length>100?e.substring(0,100)+`... (${e.length}자)`:e;if(a>=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,a+1)):{__type:"array",__length:e.length,__preview:e.slice(0,3).map(c=>this.summarizeValues(c,n,a+1))};const i={},l=Object.keys(e);for(const c of l)i[c]=this.summarizeValues(e[c],n,a+1);return i}buildStateHierarchyLayers(){const e=[];try{const a=window.G7Core?.state?.get?.();if(!a)return e;a._local&&e.push({name:"Global _local",type:"global",path:"_local",values:a._local,priority:1}),a._global&&e.push({name:"Global _global",type:"global",path:"_global",values:a._global,priority:1});for(const[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(a._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[,a]of this.dynamicStates)a._local&&Object.assign(n,a._local);return n}detectStateConflicts(e){const n=[],a=e.find(l=>l.type==="global"&&l.path==="_local");if(!a)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 g=a.values[d];if(JSON.stringify(g)!==JSON.stringify(f)){const m=[],b=[];for(const S of this.componentStateSources.values())S.stateSource.local.some(_=>_===`_local.${d}`||_===d)&&(S.stateProvider.type==="dynamicState"?m.push(S.componentName):S.stateProvider.type==="globalState"&&b.push(S.componentName));n.push({path:`_local.${d}`,globalValue:g,dynamicStateValue:f,effectiveValue:f,usedBy:m,notUsedBy:b,severity:b.length>0?"warning":"info",description:b.length>0?`${b.join(", ")}은(는) globalState._local을 읽어 dynamicState 값을 사용하지 못함`:"dynamicState 값이 globalState와 다르지만 모든 컴포넌트가 dynamicState를 사용"})}}}return n}getContextFlowInfo(){const e=[],n=new Set(this.contextFlowNodes.keys());for(const a of this.contextFlowNodes.values())if(a.children)for(const i of a.children)n.delete(i.componentId);for(const a of n){const i=this.contextFlowNodes.get(a);i&&e.push(i)}return{rootComponent:e.length>0?e[0].component:"Unknown",contextFlow:e,timestamp:Date.now()}}clearStateHierarchyData(){this.componentStateSources.clear(),this.contextFlowNodes.clear(),this.dynamicStates.clear()}trackComponentStyle(e,n,a,i){if(!this.config.enabled)return;const l=this.analyzeTailwindClasses(a),c={componentId:e,componentName:n,classes:a,computedStyles:i,tailwindAnalysis:l};this.componentStyles.set(e,c),this.detectStyleIssues(c)}analyzeTailwindClasses(e){const n=[],a=[],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 g of c)if(f.startsWith(g)){a.push(f);break}for(const g of d)if(g.test(f)){i.push(f);break}}return{usedClasses:l,darkClasses:n,responsiveClasses:a,dynamicClasses:i}}detectStyleIssues(e){const{componentId:n,componentName:a,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:a,property:i.opacity==="0"?"opacity":i.visibility==="hidden"?"visibility":i.display==="none"?"display":"width/height",currentValue:i.opacity==="0"?"0":i.visibility==="hidden"?"hidden":i.display==="none"?"none":"0px",severity:"warning",description:"요소가 화면에 보이지 않습니다.",suggestion:"opacity, visibility, display, width/height 값을 확인하세요."});const 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:a,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:a,property:"class",currentValue:l.dynamicClasses.join(", "),severity:"info",description:"동적으로 생성된 Tailwind 클래스가 있습니다.",suggestion:"tailwind.config.js의 safelist에 추가하거나 전체 클래스명을 상수로 정의하세요."})}addStyleIssue(e){this.styleIssues.some(a=>a.componentId===e.componentId&&a.type===e.type&&a.property===e.property)||this.styleIssues.push(e)}getStyleValidationInfo(){const e=Array.from(this.componentStyles.values());return{issues:[...this.styleIssues],componentStyles:e,stats:{totalComponents:e.length,invisibleCount:this.styleIssues.filter(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,a,i){if(!this.config.enabled)return;const l={id:`auth_${++this.authEventIdCounter}`,type:e,timestamp:Date.now(),success:n,error:a,details:i};this.authEvents.push(l),this.authEvents.length>this.maxAuthEventHistory&&(this.authEvents=this.authEvents.slice(-this.maxAuthEventHistory))}trackAuthHeader(e,n,a,i,l){if(!this.config.enabled)return;const c={url:e,hasAuthHeader:n,headerType:a,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 a=e?.auth;!a&&e?.AuthManager?.getInstance&&(a=e.AuthManager.getInstance());const i=n?.getToken?.()||a?.getAccessToken?.()||localStorage.getItem("auth_token")||localStorage.getItem("access_token"),l=a?.getRefreshToken?.()||localStorage.getItem("refresh_token");let c="unknown",d=a?.getUser?.();if(d&&(c="AuthManager"),!d){const v=e?.state?.get?.();d=v?._global?.user||v?._global?.currentUser||v?.user||v?.currentUser,d&&(c="G7Core.state")}const f=a?.isAuthenticated?.()??!1;let g="memory";localStorage.getItem("auth_token")||localStorage.getItem("access_token")?g="localStorage":(sessionStorage.getItem("auth_token")||sessionStorage.getItem("access_token"))&&(g="sessionStorage");const m=!!i&&(!!d||f);let b;i&&typeof i=="string"&&i.length>20?b=`${i.substring(0,10)}...${i.substring(i.length-6)}`:i&&(b="***");const S=d?{id:d.id,email:d.email,name:d.name,roles:d.roles?.map(v=>typeof v=="string"?{name:v}:{id:v.id,name:v.name,guard_name:v.guard_name}),permissions:d.permissions?.map(v=>typeof v=="string"?{name:v}:{id:v.id,name:v.name,guard_name:v.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:S,tokens:{hasAccessToken:!!i,hasRefreshToken:!!l,storage:g,accessTokenPreview:b},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,a,i="api"){if(!this.config.enabled)return;const l=Date.now();this.currentLayout={layoutPath:e,templateId:n,layoutJson:this.sanitizeObject(a),loadedAt:l,version:a.version,layoutName:a.layout_name,source:i};const c={id:`layout-${++this.layoutIdCounter}`,layoutPath:e,templateId:n,loadedAt:l,source:i,version:a.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()}`,a={handlerName:e,executionId:n,startTime:Date.now(),stateChanges:[],dataSourceChanges:[],alerts:[]};if(this.executionDetails.set(n,a),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,a,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=a,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||`종료 위치: ${a||"알 수 없음"}`,handlerName:l.handlerName,suggestion:n==="early-return-validation"?"검증 실패로 인한 early return입니다. 입력 데이터를 확인하세요.":"조건부 early return입니다. 조건문의 평가 결과를 확인하세요."})}recordExitReason(e,n,a,i){if(!this.config.enabled||!e)return;const l=this.executionDetails.get(e);l&&(l.exitReason=n,l.exitLocation=a,l.exitDescription=i)}recordStateChange(e,n,a,i,l){if(!this.config.enabled)return;const c={id:`sc_${++this.stateChangeIdCounter}`,path:n,changeType:a,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,a,i,l){if(!this.config.enabled)return;const c={dataSourceId:n,changeType:a,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,a){if(!this.config.enabled||!e)return;const i=this.executionDetails.get(e);if(!i)return;const l={expectedStatePaths:n,expectedDataSources:a,setAt:Date.now(),source:i.handlerName};this.changeExpectations.set(e,l)}checkExpectations(e,n,a){const i=new Set(n.stateChanges.map(c=>c.path)),l=new Set(n.dataSourceChanges.map(c=>c.dataSourceId));for(const c of a.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 a.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 a={...n,id:`alert_${++this.alertIdCounter}`,timestamp:Date.now()};if(this.changeAlerts.push(a),e){const i=this.executionDetails.get(e);i&&i.alerts.push(a)}this.changeAlerts.length>this.maxChangeAlerts&&this.changeAlerts.splice(0,this.changeAlerts.length-this.maxChangeAlerts)}compareValues(e,n){const a=this.getValueType(e),i=this.getValueType(n),l=a!==i;let c=!1,d;return!l&&(a==="object"||a==="array")?(c=this.deepEqual(e,n),!c&&a==="object"&&(d=this.getChangedKeys(e,n))):c=e===n,{typeChanged:l,oldType:a,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 a=Object.keys(e),i=Object.keys(n);if(a.length!==i.length)return!1;for(const l of a)if(!i.includes(l)||!this.deepEqual(e[l],n[l]))return!1;return!0}getChangedKeys(e,n){const a=[],i=new Set([...Object.keys(e),...Object.keys(n)]);for(const l of i)this.deepEqual(e[l],n[l])||a.push(l);return a}getChangeDetectionInfo(){const e=Array.from(this.executionDetails.values()),n={totalExecutions:e.length,executionsWithStateChange:e.filter(a=>a.stateChanges.length>0).length,executionsWithoutStateChange:e.filter(a=>a.stateChanges.length===0&&a.exitReason==="normal").length,earlyReturnCount:e.filter(a=>a.exitReason==="early-return-condition"||a.exitReason==="early-return-validation").length,alertCount:this.changeAlerts.length,alertsByType:this.getAlertsByType()};return{executionDetails:e,stateChangeHistory:[...this.stateChangeHistory],dataSourceChangeHistory:[...this.dataSourceChangeHistory],alerts:[...this.changeAlerts],stats: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 a=[...this.changeAlerts];return n&&(a=a.filter(i=>i.severity===n)),a.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()}`,a={sequenceId:n,startTime:Date.now(),totalDuration:0,trigger:e,actions:[],status:"running"};return this.sequenceExecutionStack.push(a),n}captureSequenceActionBefore(e,n,a,i,l){if(!this.config.enabled)return;const c=this.findExecutionInStack(e);if(!c)return;const d={index:n,handler:a,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,a,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(a._global),_local:this.safeClone(a._local),_isolated:a._isolated?this.safeClone(a._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 g=window.__g7PendingLocalState;g&&(f.pendingState=this.safeClone(g)),c&&(f.status="error",f.error={name:c.name,message:c.message,stack:c.stack})}endSequenceExecution(e,n){if(!this.config.enabled)return;const a=this.sequenceExecutionStack.findIndex(l=>l.sequenceId===e);if(a===-1)return;const i=this.sequenceExecutionStack[a];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(a,1)}computeStateDiff(e,n){const a=[],i=[],l=[],c=new Set(Object.keys(e)),d=new Set(Object.keys(n));for(const f of d)c.has(f)||a.push(f);for(const f of c)d.has(f)||i.push(f);for(const f of c)if(d.has(f)){const g=e[f],m=n[f];JSON.stringify(g)!==JSON.stringify(m)&&l.push({path:f,oldValue:g,newValue:m})}return{added:a,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,a=e.filter(g=>g.status==="success").length,i=e.filter(g=>g.status==="error").length,l=e.reduce((g,m)=>g+m.actions.length,0),c=n>0?e.reduce((g,m)=>g+m.totalDuration,0)/n:0,d={};for(const g of e)for(const m of g.actions)d[m.handler]=(d[m.handler]||0)+1;const f=Object.entries(d).sort(([,g],[,m])=>m-g).slice(0,5).map(([g,m])=>({handler:g,count:m}));return{totalExecutions:n,successCount:a,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(a=>a.sequenceId===e)}getRecentSequences(e=10){return this.sequenceExecutions.slice(-e)}registerStateCaptureForHandler(e,n,a){if(!this.config.enabled)return;const i=new Map,l=Date.now();for(const c of n)i.set(c,{value:this.safeClone(a[c]),capturedAt:l});this.stateCaptureRegistry.set(e,i)}detectStaleClosure(e,n,a,i,l){if(!this.config.enabled)return[];const c=this.stateCaptureRegistry.get(e);if(!c)return[];const d=Date.now(),f=[];for(const[g,m]of c){const b=this.getValueByPath(a,g),S=d-m.capturedAt;if(!this.isDeepEqual(m.value,b)&&S>0){const v=this.createStaleClosureWarning(i,n,g,m.value,m.capturedAt,b,d,S,l);f.push(v),this.addStaleClosureWarning(v)}}return this.stateCaptureRegistry.delete(e),f}trackStaleClosureWarning(e){if(!this.config.enabled)return;const n=Date.now(),a=this.createStaleClosureWarning(e.type,e.location,e.capturedPath,e.capturedValue,e.capturedAt,e.currentValue,n,n-e.capturedAt,e.actionId,e.stackTrace);this.addStaleClosureWarning(a)}createStaleClosureWarning(e,n,a,i,l,c,d,f,g,m){const b=this.getStaleClosureSeverity(e,f),{description:S,suggestion:v,docLink:_}=this.getStaleClosureMessages(e,a,f);return{id:`stale_${++this.staleClosureIdCounter}_${Date.now()}`,timestamp:Date.now(),type:e,location:n,capturedState:{path:a,capturedValue:this.safeClone(i),capturedAt:l},currentState:{path:a,currentValue:this.safeClone(c),retrievedAt:d},timeDiff:f,severity:b,description:S,suggestion:v,docLink:_,actionId:g,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,a){const i=a<1e3?`${a}ms`:`${(a/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 a=n.split(".");let i=e;for(const l of a){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 a={info:0,warning:0,error:0};for(const f of e)a[f.severity]++;const i={};for(const f of e)i[f.location]=(i[f.location]||0)+1;const l=Object.entries(i).sort(([,f],[,g])=>g-f).slice(0,5).map(([f,g])=>({location:f,count:g})),c={};for(const f of e)c[f.capturedState.path]=(c[f.capturedState.path]||0)+1;const d=Object.entries(c).sort(([,f],[,g])=>g-f).slice(0,5).map(([f,g])=>({path:f,count:g}));return{totalWarnings:e.length,warningsByType:n,warningsBySeverity:a,topLocations:l,topAffectedPaths:d}}clearStaleClosureData(){this.staleClosureWarnings=[],this.staleClosureIdCounter=0,this.stateCaptureRegistry.clear()}getRecentStaleClosureWarnings(e=10,n){let a=[...this.staleClosureWarnings];return n&&(a=a.filter(i=>i.severity===n)),a.slice(-e)}safeClone(e){if(e==null||typeof e!="object")return e;try{return JSON.parse(JSON.stringify(e))}catch{if(Array.isArray(e))return e.map(a=>{try{return JSON.parse(JSON.stringify(a))}catch{return"[Unserializable]"}});const n={};for(const a of Object.keys(e))try{n[a]=JSON.parse(JSON.stringify(e[a]))}catch{n[a]="[Unserializable]"}return n}}};$(Si,"instance");let Oa=Si;const Gn=ut("LayoutLoader");class Cr extends Error{constructor(n,a,i){super(n);$(this,"code");$(this,"details");this.code=a,this.details=i,this.name="LayoutLoaderError"}}class ff{constructor(e){$(this,"componentRegistry");$(this,"currentLayout",null);$(this,"layoutCache",new Map);$(this,"cacheVersion",0);this.componentRegistry=e}setCacheVersion(e){this.cacheVersion!==e&&(Gn.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.layoutCache.clear())}getCacheVersion(){return this.cacheVersion}async loadLayout(e,n){const a=`${e}:${n}`;if(this.layoutCache.has(a)){Gn.log("Loading layout from cache:",n);const l=await this.layoutCache.get(a),c=JSON.parse(JSON.stringify(l));return this.currentLayout=c,Oa.getInstance().trackLayoutLoad(n,e,c,"cache"),c}const i=this.fetchLayout(e,n);return this.layoutCache.set(a,i),i.catch(()=>{this.layoutCache.get(a)===i&&this.layoutCache.delete(a)}),i}async fetchLayout(e,n,a=!1){try{const i=this.cacheVersion>0?this.cacheVersion:null;let l;if(n.startsWith("__preview__/")){const S=n.replace("__preview__/","");l=$r(`/api/layouts/preview/${S}`,"json",i)}else l=$r(`/api/layouts/${e}/${n}`,"json",i);Gn.log("Fetching layout from API:",l);const c=Ir(),d=a?null:c.getToken(),f={Accept:"application/json"};d&&(f.Authorization=`Bearer ${d}`);const g=await Ll(l,{init:{headers:f},label:`layout: ${n}`});let m;try{m=await g.json()}catch{m=null}if(!g.ok){if(g.status===401&&!a&&d){Gn.log("Token invalid, removing and retrying without token"),c.removeToken();try{return await this.fetchLayout(e,n,!0)}catch(v){throw v instanceof Cr&&v.details?.status===401?new Cr(v.message,v.code,{...v.details,hadToken:!0}):v}}const S=m?.message||m?.error;throw new Cr(`Failed to fetch layout: ${g.status} ${g.statusText}`,"FETCH_FAILED",{status:g.status,statusText:g.statusText,url:l,apiMessage:S})}const b=m.data||m;return this.validateLayoutData(b),this.currentLayout=b,Oa.getInstance().trackLayoutLoad(n,e,b,"api"),Gn.log("Layout fetched and cached successfully:",b.layout_name),b}catch(i){const l=`${e}:${n}`;throw this.layoutCache.delete(l),i instanceof Cr?i:new Cr("Failed to load layout","LOAD_FAILED",{originalError:i})}}prefetchLayout(e,n){return this.loadLayout(e,n)}validateLayoutData(e){if(!e.version)throw new Cr("Layout data missing required field: version","VALIDATION_FAILED",{field:"version"});if(!e.layout_name)throw new Cr("Layout data missing required field: layout_name","VALIDATION_FAILED",{field:"layout_name"});if(!Array.isArray(e.components))throw new Cr('Layout data field "components" must be an array',"VALIDATION_FAILED",{field:"components",value:e.components});Gn.log("Layout data validation passed")}renderLayout(e,n){try{const a=n||this.currentLayout;if(!a)throw new Cr("No layout data to render","NO_LAYOUT_DATA");Gn.log("Rendering layout:",a.layout_name),e.innerHTML="",this.renderComponents(e,a.components),Gn.log("Layout rendered successfully")}catch(a){Gn.error("Render error:",a),this.renderErrorState(e,a)}}renderComponents(e,n){for(const a of n){const i=this.renderComponent(a);i&&e.appendChild(i)}}renderComponent(e){try{if(!this.componentRegistry.getComponent(e.type))return Gn.warn(`Component not found: ${e.type}`),this.createPlaceholderElement(e.type);const a=document.createElement("div");return a.setAttribute("data-component",e.type),e.props&&Object.entries(e.props).forEach(([i,l])=>{a.setAttribute(`data-prop-${i}`,JSON.stringify(l))}),e.children&&e.children.length>0?this.renderComponents(a,e.children):e.text&&(a.textContent=e.text),a}catch(n){return Gn.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=` + `},CC={onDragStart(o){let{active:e}=o;return"Picked up draggable item "+e.id+"."},onDragOver(o){let{active:e,over:r}=o;return r?"Draggable item "+e.id+" was moved over droppable area "+r.id+".":"Draggable item "+e.id+" is no longer over a droppable area."},onDragEnd(o){let{active:e,over:r}=o;return r?"Draggable item "+e.id+" was dropped over droppable area "+r.id:"Draggable item "+e.id+" was dropped."},onDragCancel(o){let{active:e}=o;return"Dragging was cancelled. Draggable item "+e.id+" was dropped."}};function EC(o){let{announcements:e=CC,container:r,hiddenTextDescribedById:a,screenReaderInstructions:i=wC}=o;const{announce:l,announcement:c}=bC(),d=So("DndLiveRegion"),[f,g]=N.useState(!1);if(N.useEffect(()=>{g(!0)},[]),vC(N.useMemo(()=>({onDragStart(y){let{active:w}=y;l(e.onDragStart({active:w}))},onDragMove(y){let{active:w,over:S}=y;e.onDragMove&&l(e.onDragMove({active:w,over:S}))},onDragOver(y){let{active:w,over:S}=y;l(e.onDragOver({active:w,over:S}))},onDragEnd(y){let{active:w,over:S}=y;l(e.onDragEnd({active:w,over:S}))},onDragCancel(y){let{active:w,over:S}=y;l(e.onDragCancel({active:w,over:S}))}}),[l,e])),!f)return null;const m=We.createElement(We.Fragment,null,We.createElement(mC,{id:a,value:i.draggable}),We.createElement(yC,{id:d,announcement:c}));return r?Oa.createPortal(m,r):m}var tn;(function(o){o.DragStart="dragStart",o.DragMove="dragMove",o.DragEnd="dragEnd",o.DragCancel="dragCancel",o.DragOver="dragOver",o.RegisterDroppable="registerDroppable",o.SetDroppableDisabled="setDroppableDisabled",o.UnregisterDroppable="unregisterDroppable"})(tn||(tn={}));function hc(){}function ym(o,e){return N.useMemo(()=>({sensor:o,options:e??{}}),[o,e])}function _C(){for(var o=arguments.length,e=new Array(o),r=0;r[...e].filter(a=>a!=null),[...e])}const wr=Object.freeze({x:0,y:0});function bm(o,e){return Math.sqrt(Math.pow(o.x-e.x,2)+Math.pow(o.y-e.y,2))}function vm(o,e){let{data:{value:r}}=o,{data:{value:a}}=e;return r-a}function AC(o,e){let{data:{value:r}}=o,{data:{value:a}}=e;return a-r}function Sm(o){let{left:e,top:r,height:a,width:i}=o;return[{x:e,y:r},{x:e+i,y:r},{x:e,y:r+a},{x:e+i,y:r+a}]}function wm(o,e){if(!o||o.length===0)return null;const[r]=o;return r[e]}function Cm(o,e,r){return e===void 0&&(e=o.left),r===void 0&&(r=o.top),{x:e+o.width*.5,y:r+o.height*.5}}const xC=o=>{let{collisionRect:e,droppableRects:r,droppableContainers:a}=o;const i=Cm(e,e.left,e.top),l=[];for(const c of a){const{id:d}=c,f=r.get(d);if(f){const g=bm(Cm(f),i);l.push({id:d,data:{droppableContainer:c,value:g}})}}return l.sort(vm)},TC=o=>{let{collisionRect:e,droppableRects:r,droppableContainers:a}=o;const i=Sm(e),l=[];for(const c of a){const{id:d}=c,f=r.get(d);if(f){const g=Sm(f),m=i.reduce((w,S,v)=>w+bm(g[v],S),0),y=Number((m/4).toFixed(4));l.push({id:d,data:{droppableContainer:c,value:y}})}}return l.sort(vm)};function kC(o,e){const r=Math.max(e.top,o.top),a=Math.max(e.left,o.left),i=Math.min(e.left+e.width,o.left+o.width),l=Math.min(e.top+e.height,o.top+o.height),c=i-a,d=l-r;if(a{let{collisionRect:e,droppableRects:r,droppableContainers:a}=o;const i=[];for(const l of a){const{id:c}=l,d=r.get(c);if(d){const f=kC(d,e);f>0&&i.push({id:c,data:{droppableContainer:l,value:f}})}}return i.sort(AC)};function DC(o,e,r){return{...o,scaleX:e&&r?e.width/r.width:1,scaleY:e&&r?e.height/r.height:1}}function Em(o,e){return o&&e?{x:o.left-e.left,y:o.top-e.top}:wr}function OC(o){return function(r){for(var a=arguments.length,i=new Array(a>1?a-1:0),l=1;l({...c,top:c.top+o*d.y,bottom:c.bottom+o*d.y,left:c.left+o*d.x,right:c.right+o*d.x}),{...r})}}const LC=OC(1);function MC(o){if(o.startsWith("matrix3d(")){const e=o.slice(9,-1).split(/, /);return{x:+e[12],y:+e[13],scaleX:+e[0],scaleY:+e[5]}}else if(o.startsWith("matrix(")){const e=o.slice(7,-1).split(/, /);return{x:+e[4],y:+e[5],scaleX:+e[0],scaleY:+e[3]}}return null}function $C(o,e,r){const a=MC(e);if(!a)return o;const{scaleX:i,scaleY:l,x:c,y:d}=a,f=o.left-c-(1-i)*parseFloat(r),g=o.top-d-(1-l)*parseFloat(r.slice(r.indexOf(" ")+1)),m=i?o.width/i:o.width,y=l?o.height/l:o.height;return{width:m,height:y,top:g,right:f+m,bottom:g+y,left:f}}const NC={ignoreTransform:!1};function ls(o,e){e===void 0&&(e=NC);let r=o.getBoundingClientRect();if(e.ignoreTransform){const{transform:g,transformOrigin:m}=Dn(o).getComputedStyle(o);g&&(r=$C(r,g,m))}const{top:a,left:i,width:l,height:c,bottom:d,right:f}=r;return{top:a,left:i,width:l,height:c,bottom:d,right:f}}function _m(o){return ls(o,{ignoreTransform:!0})}function IC(o){const e=o.innerWidth,r=o.innerHeight;return{top:0,left:0,right:e,bottom:r,width:e,height:r}}function HC(o,e){return e===void 0&&(e=Dn(o).getComputedStyle(o)),e.position==="fixed"}function jC(o,e){e===void 0&&(e=Dn(o).getComputedStyle(o));const r=/(auto|scroll|overlay)/;return["overflow","overflowX","overflowY"].some(i=>{const l=e[i];return typeof l=="string"?r.test(l):!1})}function gc(o,e){const r=[];function a(i){if(e!=null&&r.length>=e||!i)return r;if(Bd(i)&&i.scrollingElement!=null&&!r.includes(i.scrollingElement))return r.push(i.scrollingElement),r;if(!yo(i)||hm(i)||r.includes(i))return r;const l=Dn(o).getComputedStyle(i);return i!==o&&jC(i,l)&&r.push(i),HC(i,l)?r:a(i.parentNode)}return o?a(o):r}function Am(o){const[e]=gc(o,1);return e??null}function Kd(o){return!dc||!o?null:is(o)?o:Ud(o)?Bd(o)||o===ss(o).scrollingElement?window:yo(o)?o:null:null}function xm(o){return is(o)?o.scrollX:o.scrollLeft}function Tm(o){return is(o)?o.scrollY:o.scrollTop}function Wd(o){return{x:xm(o),y:Tm(o)}}var on;(function(o){o[o.Forward=1]="Forward",o[o.Backward=-1]="Backward"})(on||(on={}));function km(o){return!dc||!o?!1:o===document.scrollingElement}function Rm(o){const e={x:0,y:0},r=km(o)?{height:window.innerHeight,width:window.innerWidth}:{height:o.clientHeight,width:o.clientWidth},a={x:o.scrollWidth-r.width,y:o.scrollHeight-r.height},i=o.scrollTop<=e.y,l=o.scrollLeft<=e.x,c=o.scrollTop>=a.y,d=o.scrollLeft>=a.x;return{isTop:i,isLeft:l,isBottom:c,isRight:d,maxScroll:a,minScroll:e}}const zC={x:.2,y:.2};function UC(o,e,r,a,i){let{top:l,left:c,right:d,bottom:f}=r;a===void 0&&(a=10),i===void 0&&(i=zC);const{isTop:g,isBottom:m,isLeft:y,isRight:w}=Rm(o),S={x:0,y:0},v={x:0,y:0},A={height:e.height*i.y,width:e.width*i.x};return!g&&l<=e.top+A.height?(S.y=on.Backward,v.y=a*Math.abs((e.top+A.height-l)/A.height)):!m&&f>=e.bottom-A.height&&(S.y=on.Forward,v.y=a*Math.abs((e.bottom-A.height-f)/A.height)),!w&&d>=e.right-A.width?(S.x=on.Forward,v.x=a*Math.abs((e.right-A.width-d)/A.width)):!y&&c<=e.left+A.width&&(S.x=on.Backward,v.x=a*Math.abs((e.left+A.width-c)/A.width)),{direction:S,speed:v}}function BC(o){if(o===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:r,right:a,bottom:i}=o.getBoundingClientRect();return{top:e,left:r,right:a,bottom:i,width:o.clientWidth,height:o.clientHeight}}function Dm(o){return o.reduce((e,r)=>os(e,Wd(r)),wr)}function PC(o){return o.reduce((e,r)=>e+xm(r),0)}function qC(o){return o.reduce((e,r)=>e+Tm(r),0)}function GC(o,e){if(e===void 0&&(e=ls),!o)return;const{top:r,left:a,bottom:i,right:l}=e(o);Am(o)&&(i<=0||l<=0||r>=window.innerHeight||a>=window.innerWidth)&&o.scrollIntoView({block:"center",inline:"center"})}const VC=[["x",["left","right"],PC],["y",["top","bottom"],qC]];class Yd{constructor(e,r){this.rect=void 0,this.width=void 0,this.height=void 0,this.top=void 0,this.bottom=void 0,this.right=void 0,this.left=void 0;const a=gc(r),i=Dm(a);this.rect={...e},this.width=e.width,this.height=e.height;for(const[l,c,d]of VC)for(const f of c)Object.defineProperty(this,f,{get:()=>{const g=d(a),m=i[l]-g;return this.rect[f]+m},enumerable:!0});Object.defineProperty(this,"rect",{enumerable:!1})}}class Eo{constructor(e){this.target=void 0,this.listeners=[],this.removeAll=()=>{this.listeners.forEach(r=>{var a;return(a=this.target)==null?void 0:a.removeEventListener(...r)})},this.target=e}add(e,r,a){var i;(i=this.target)==null||i.addEventListener(e,r,a),this.listeners.push([e,r,a])}}function FC(o){const{EventTarget:e}=Dn(o);return o instanceof e?o:ss(o)}function Xd(o,e){const r=Math.abs(o.x),a=Math.abs(o.y);return typeof e=="number"?Math.sqrt(r**2+a**2)>e:"x"in e&&"y"in e?r>e.x&&a>e.y:"x"in e?r>e.x:"y"in e?a>e.y:!1}var ar;(function(o){o.Click="click",o.DragStart="dragstart",o.Keydown="keydown",o.ContextMenu="contextmenu",o.Resize="resize",o.SelectionChange="selectionchange",o.VisibilityChange="visibilitychange"})(ar||(ar={}));function Om(o){o.preventDefault()}function KC(o){o.stopPropagation()}var ot;(function(o){o.Space="Space",o.Down="ArrowDown",o.Right="ArrowRight",o.Left="ArrowLeft",o.Up="ArrowUp",o.Esc="Escape",o.Enter="Enter",o.Tab="Tab"})(ot||(ot={}));const Lm={start:[ot.Space,ot.Enter],cancel:[ot.Esc],end:[ot.Space,ot.Enter,ot.Tab]},WC=(o,e)=>{let{currentCoordinates:r}=e;switch(o.code){case ot.Right:return{...r,x:r.x+25};case ot.Left:return{...r,x:r.x-25};case ot.Down:return{...r,y:r.y+25};case ot.Up:return{...r,y:r.y-25}}};class Jd{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:r}}=e;this.props=e,this.listeners=new Eo(ss(r)),this.windowListeners=new Eo(Dn(r)),this.handleKeyDown=this.handleKeyDown.bind(this),this.handleCancel=this.handleCancel.bind(this),this.attach()}attach(){this.handleStart(),this.windowListeners.add(ar.Resize,this.handleCancel),this.windowListeners.add(ar.VisibilityChange,this.handleCancel),setTimeout(()=>this.listeners.add(ar.Keydown,this.handleKeyDown))}handleStart(){const{activeNode:e,onStart:r}=this.props,a=e.node.current;a&&GC(a),r(wr)}handleKeyDown(e){if(Vd(e)){const{active:r,context:a,options:i}=this.props,{keyboardCodes:l=Lm,coordinateGetter:c=WC,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:g}=a.current,m=g?{x:g.left,y:g.top}:wr;this.referenceCoordinates||(this.referenceCoordinates=m);const y=c(e,{active:r,context:a.current,currentCoordinates:m});if(y){const w=wo(y,m),S={x:0,y:0},{scrollableAncestors:v}=a.current;for(const A of v){const x=e.code,{isTop:R,isRight:M,isLeft:O,isBottom:L,maxScroll:q,minScroll:G}=Rm(A),B=BC(A),K={x:Math.min(x===ot.Right?B.right-B.width/2:B.right,Math.max(x===ot.Right?B.left:B.left+B.width/2,y.x)),y:Math.min(x===ot.Down?B.bottom-B.height/2:B.bottom,Math.max(x===ot.Down?B.top:B.top+B.height/2,y.y))},fe=x===ot.Right&&!M||x===ot.Left&&!O,Ce=x===ot.Down&&!L||x===ot.Up&&!R;if(fe&&K.x!==y.x){const ke=A.scrollLeft+w.x,Ue=x===ot.Right&&ke<=q.x||x===ot.Left&&ke>=G.x;if(Ue&&!w.y){A.scrollTo({left:ke,behavior:d});return}Ue?S.x=A.scrollLeft-ke:S.x=x===ot.Right?A.scrollLeft-q.x:A.scrollLeft-G.x,S.x&&A.scrollBy({left:-S.x,behavior:d});break}else if(Ce&&K.y!==y.y){const ke=A.scrollTop+w.y,Ue=x===ot.Down&&ke<=q.y||x===ot.Up&&ke>=G.y;if(Ue&&!w.x){A.scrollTo({top:ke,behavior:d});return}Ue?S.y=A.scrollTop-ke:S.y=x===ot.Down?A.scrollTop-q.y:A.scrollTop-G.y,S.y&&A.scrollBy({top:-S.y,behavior:d});break}}this.handleMove(e,os(wo(y,this.referenceCoordinates),S))}}}handleMove(e,r){const{onMove:a}=this.props;e.preventDefault(),a(r)}handleEnd(e){const{onEnd:r}=this.props;e.preventDefault(),this.detach(),r()}handleCancel(e){const{onCancel:r}=this.props;e.preventDefault(),this.detach(),r()}detach(){this.listeners.removeAll(),this.windowListeners.removeAll()}}Jd.activators=[{eventName:"onKeyDown",handler:(o,e,r)=>{let{keyboardCodes:a=Lm,onActivation:i}=e,{active:l}=r;const{code:c}=o.nativeEvent;if(a.start.includes(c)){const d=l.activatorNode.current;return d&&o.target!==d?!1:(o.preventDefault(),i?.({event:o.nativeEvent}),!0)}return!1}}];function Mm(o){return!!(o&&"distance"in o)}function $m(o){return!!(o&&"delay"in o)}class Qd{constructor(e,r,a){var i;a===void 0&&(a=FC(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=r;const{event:l}=e,{target:c}=l;this.props=e,this.events=r,this.document=ss(c),this.documentListeners=new Eo(this.document),this.listeners=new Eo(a),this.windowListeners=new Eo(Dn(c)),this.initialCoordinates=(i=Fd(l))!=null?i:wr,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:r,bypassActivationConstraint:a}}}=this;if(this.listeners.add(e.move.name,this.handleMove,{passive:!1}),this.listeners.add(e.end.name,this.handleEnd),e.cancel&&this.listeners.add(e.cancel.name,this.handleCancel),this.windowListeners.add(ar.Resize,this.handleCancel),this.windowListeners.add(ar.DragStart,Om),this.windowListeners.add(ar.VisibilityChange,this.handleCancel),this.windowListeners.add(ar.ContextMenu,Om),this.documentListeners.add(ar.Keydown,this.handleKeydown),r){if(a!=null&&a({event:this.props.event,activeNode:this.props.activeNode,options:this.props.options}))return this.handleStart();if($m(r)){this.timeoutId=setTimeout(this.handleStart,r.delay),this.handlePending(r);return}if(Mm(r)){this.handlePending(r);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,r){const{active:a,onPending:i}=this.props;i(a,e,this.initialCoordinates,r)}handleStart(){const{initialCoordinates:e}=this,{onStart:r}=this.props;e&&(this.activated=!0,this.documentListeners.add(ar.Click,KC,{capture:!0}),this.removeTextSelection(),this.documentListeners.add(ar.SelectionChange,this.removeTextSelection),r(e))}handleMove(e){var r;const{activated:a,initialCoordinates:i,props:l}=this,{onMove:c,options:{activationConstraint:d}}=l;if(!i)return;const f=(r=Fd(e))!=null?r:wr,g=wo(i,f);if(!a&&d){if(Mm(d)){if(d.tolerance!=null&&Xd(g,d.tolerance))return this.handleCancel();if(Xd(g,d.distance))return this.handleStart()}if($m(d)&&Xd(g,d.tolerance))return this.handleCancel();this.handlePending(d,g);return}e.cancelable&&e.preventDefault(),c(f)}handleEnd(){const{onAbort:e,onEnd:r}=this.props;this.detach(),this.activated||e(this.props.active),r()}handleCancel(){const{onAbort:e,onCancel:r}=this.props;this.detach(),this.activated||e(this.props.active),r()}handleKeydown(e){e.code===ot.Esc&&this.handleCancel()}removeTextSelection(){var e;(e=this.document.getSelection())==null||e.removeAllRanges()}}const YC={cancel:{name:"pointercancel"},move:{name:"pointermove"},end:{name:"pointerup"}};class Zd extends Qd{constructor(e){const{event:r}=e,a=ss(r.target);super(e,YC,a)}}Zd.activators=[{eventName:"onPointerDown",handler:(o,e)=>{let{nativeEvent:r}=o,{onActivation:a}=e;return!r.isPrimary||r.button!==0?!1:(a?.({event:r}),!0)}}];const XC={move:{name:"mousemove"},end:{name:"mouseup"}};var ef;(function(o){o[o.RightClick=2]="RightClick"})(ef||(ef={}));class JC extends Qd{constructor(e){super(e,XC,ss(e.event.target))}}JC.activators=[{eventName:"onMouseDown",handler:(o,e)=>{let{nativeEvent:r}=o,{onActivation:a}=e;return r.button===ef.RightClick?!1:(a?.({event:r}),!0)}}];const tf={cancel:{name:"touchcancel"},move:{name:"touchmove"},end:{name:"touchend"}};class QC extends Qd{constructor(e){super(e,tf)}static setup(){return window.addEventListener(tf.move.name,e,{capture:!1,passive:!1}),function(){window.removeEventListener(tf.move.name,e)};function e(){}}}QC.activators=[{eventName:"onTouchStart",handler:(o,e)=>{let{nativeEvent:r}=o,{onActivation:a}=e;const{touches:i}=r;return i.length>1?!1:(a?.({event:r}),!0)}}];var _o;(function(o){o[o.Pointer=0]="Pointer",o[o.DraggableRect=1]="DraggableRect"})(_o||(_o={}));var pc;(function(o){o[o.TreeOrder=0]="TreeOrder",o[o.ReversedTreeOrder=1]="ReversedTreeOrder"})(pc||(pc={}));function ZC(o){let{acceleration:e,activator:r=_o.Pointer,canScroll:a,draggingRect:i,enabled:l,interval:c=5,order:d=pc.TreeOrder,pointerCoordinates:f,scrollableAncestors:g,scrollableAncestorRects:m,delta:y,threshold:w}=o;const S=tE({delta:y,disabled:!l}),[v,A]=dC(),x=N.useRef({x:0,y:0}),R=N.useRef({x:0,y:0}),M=N.useMemo(()=>{switch(r){case _o.Pointer:return f?{top:f.y,bottom:f.y,left:f.x,right:f.x}:null;case _o.DraggableRect:return i}},[r,i,f]),O=N.useRef(null),L=N.useCallback(()=>{const G=O.current;if(!G)return;const B=x.current.x*R.current.x,K=x.current.y*R.current.y;G.scrollBy(B,K)},[]),q=N.useMemo(()=>d===pc.TreeOrder?[...g].reverse():g,[d,g]);N.useEffect(()=>{if(!l||!g.length||!M){A();return}for(const G of q){if(a?.(G)===!1)continue;const B=g.indexOf(G),K=m[B];if(!K)continue;const{direction:fe,speed:Ce}=UC(G,K,M,e,w);for(const ke of["x","y"])S[ke][fe[ke]]||(Ce[ke]=0,fe[ke]=0);if(Ce.x>0||Ce.y>0){A(),O.current=G,v(L,c),x.current=Ce,R.current=fe;return}}x.current={x:0,y:0},R.current={x:0,y:0},A()},[e,L,a,A,l,c,JSON.stringify(M),JSON.stringify(S),v,g,q,m,JSON.stringify(w)])}const eE={x:{[on.Backward]:!1,[on.Forward]:!1},y:{[on.Backward]:!1,[on.Forward]:!1}};function tE(o){let{delta:e,disabled:r}=o;const a=qd(e);return vo(i=>{if(r||!a||!i)return eE;const l={x:Math.sign(e.x-a.x),y:Math.sign(e.y-a.y)};return{x:{[on.Backward]:i.x[on.Backward]||l.x===-1,[on.Forward]:i.x[on.Forward]||l.x===1},y:{[on.Backward]:i.y[on.Backward]||l.y===-1,[on.Forward]:i.y[on.Forward]||l.y===1}}},[r,e,a])}function nE(o,e){const r=e!=null?o.get(e):void 0,a=r?r.node.current:null;return vo(i=>{var l;return e==null?null:(l=a??i)!=null?l:null},[a,e])}function rE(o,e){return N.useMemo(()=>o.reduce((r,a)=>{const{sensor:i}=a,l=i.activators.map(c=>({eventName:c.eventName,handler:e(c.handler,a)}));return[...r,...l]},[]),[o,e])}var Ao;(function(o){o[o.Always=0]="Always",o[o.BeforeDragging=1]="BeforeDragging",o[o.WhileDragging=2]="WhileDragging"})(Ao||(Ao={}));var nf;(function(o){o.Optimized="optimized"})(nf||(nf={}));const Nm=new Map;function aE(o,e){let{dragging:r,dependencies:a,config:i}=e;const[l,c]=N.useState(null),{frequency:d,measure:f,strategy:g}=i,m=N.useRef(o),y=x(),w=bo(y),S=N.useCallback(function(R){R===void 0&&(R=[]),!w.current&&c(M=>M===null?R:M.concat(R.filter(O=>!M.includes(O))))},[w]),v=N.useRef(null),A=vo(R=>{if(y&&!r)return Nm;if(!R||R===Nm||m.current!==o||l!=null){const M=new Map;for(let O of o){if(!O)continue;if(l&&l.length>0&&!l.includes(O.id)&&O.rect.current){M.set(O.id,O.rect.current);continue}const L=O.node.current,q=L?new Yd(f(L),L):null;O.rect.current=q,q&&M.set(O.id,q)}return M}return R},[o,l,r,y,f]);return N.useEffect(()=>{m.current=o},[o]),N.useEffect(()=>{y||S()},[r,y]),N.useEffect(()=>{l&&l.length>0&&c(null)},[JSON.stringify(l)]),N.useEffect(()=>{y||typeof d!="number"||v.current!==null||(v.current=setTimeout(()=>{S(),v.current=null},d))},[d,y,S,...a]),{droppableRects:A,measureDroppableContainers:S,measuringScheduled:l!=null};function x(){switch(g){case Ao.Always:return!1;case Ao.BeforeDragging:return r;default:return!r}}}function Im(o,e){return vo(r=>o?r||(typeof e=="function"?e(o):o):null,[e,o])}function iE(o,e){return Im(o,e)}function sE(o){let{callback:e,disabled:r}=o;const a=Pd(e),i=N.useMemo(()=>{if(r||typeof window>"u"||typeof window.MutationObserver>"u")return;const{MutationObserver:l}=window;return new l(a)},[a,r]);return N.useEffect(()=>()=>i?.disconnect(),[i]),i}function mc(o){let{callback:e,disabled:r}=o;const a=Pd(e),i=N.useMemo(()=>{if(r||typeof window>"u"||typeof window.ResizeObserver>"u")return;const{ResizeObserver:l}=window;return new l(a)},[r]);return N.useEffect(()=>()=>i?.disconnect(),[i]),i}function oE(o){return new Yd(ls(o),o)}function Hm(o,e,r){e===void 0&&(e=oE);const[a,i]=N.useState(null);function l(){i(f=>{if(!o)return null;if(o.isConnected===!1){var g;return(g=f??r)!=null?g:null}const m=e(o);return JSON.stringify(f)===JSON.stringify(m)?f:m})}const c=sE({callback(f){if(o)for(const g of f){const{type:m,target:y}=g;if(m==="childList"&&y instanceof HTMLElement&&y.contains(o)){l();break}}}}),d=mc({callback:l});return Ur(()=>{l(),o?(d?.observe(o),c?.observe(document.body,{childList:!0,subtree:!0})):(d?.disconnect(),c?.disconnect())},[o]),a}function lE(o){const e=Im(o);return Em(o,e)}const jm=[];function cE(o){const e=N.useRef(o),r=vo(a=>o?a&&a!==jm&&o&&e.current&&o.parentNode===e.current.parentNode?a:gc(o):jm,[o]);return N.useEffect(()=>{e.current=o},[o]),r}function uE(o){const[e,r]=N.useState(null),a=N.useRef(o),i=N.useCallback(l=>{const c=Kd(l.target);c&&r(d=>d?(d.set(c,Wd(c)),new Map(d)):null)},[]);return N.useEffect(()=>{const l=a.current;if(o!==l){c(l);const d=o.map(f=>{const g=Kd(f);return g?(g.addEventListener("scroll",i,{passive:!0}),[g,Wd(g)]):null}).filter(f=>f!=null);r(d.length?new Map(d):null),a.current=o}return()=>{c(o),c(l)};function c(d){d.forEach(f=>{const g=Kd(f);g?.removeEventListener("scroll",i)})}},[i,o]),N.useMemo(()=>o.length?e?Array.from(e.values()).reduce((l,c)=>os(l,c),wr):Dm(o):wr,[o,e])}function zm(o,e){e===void 0&&(e=[]);const r=N.useRef(null);return N.useEffect(()=>{r.current=null},e),N.useEffect(()=>{const a=o!==wr;a&&!r.current&&(r.current=o),!a&&r.current&&(r.current=null)},[o]),r.current?wo(o,r.current):wr}function dE(o){N.useEffect(()=>{if(!dc)return;const e=o.map(r=>{let{sensor:a}=r;return a.setup==null?void 0:a.setup()});return()=>{for(const r of e)r?.()}},o.map(e=>{let{sensor:r}=e;return r}))}function fE(o,e){return N.useMemo(()=>o.reduce((r,a)=>{let{eventName:i,handler:l}=a;return r[i]=c=>{l(c,e)},r},{}),[o,e])}function Um(o){return N.useMemo(()=>o?IC(o):null,[o])}const Bm=[];function hE(o,e){e===void 0&&(e=ls);const[r]=o,a=Um(r?Dn(r):null),[i,l]=N.useState(Bm);function c(){l(()=>o.length?o.map(f=>km(f)?a:new Yd(e(f),f)):Bm)}const d=mc({callback:c});return Ur(()=>{d?.disconnect(),c(),o.forEach(f=>d?.observe(f))},[o]),i}function gE(o){if(!o)return null;if(o.children.length>1)return o;const e=o.children[0];return yo(e)?e:o}function pE(o){let{measure:e}=o;const[r,a]=N.useState(null),i=N.useCallback(g=>{for(const{target:m}of g)if(yo(m)){a(y=>{const w=e(m);return y?{...y,width:w.width,height:w.height}:w});break}},[e]),l=mc({callback:i}),c=N.useCallback(g=>{const m=gE(g);l?.disconnect(),m&&l?.observe(m),a(m?e(m):null)},[e,l]),[d,f]=fc(c);return N.useMemo(()=>({nodeRef:d,rect:r,setRef:f}),[r,d,f])}const mE=[{sensor:Zd,options:{}},{sensor:Jd,options:{}}],yE={current:{}},yc={draggable:{measure:_m},droppable:{measure:_m,strategy:Ao.WhileDragging,frequency:nf.Optimized},dragOverlay:{measure:ls}};class xo extends Map{get(e){var r;return e!=null&&(r=super.get(e))!=null?r:void 0}toArray(){return Array.from(this.values())}getEnabled(){return this.toArray().filter(e=>{let{disabled:r}=e;return!r})}getNodeFor(e){var r,a;return(r=(a=this.get(e))==null?void 0:a.node.current)!=null?r:void 0}}const bE={activatorEvent:null,active:null,activeNode:null,activeNodeRect:null,collisions:null,containerNodeRect:null,draggableNodes:new Map,droppableRects:new Map,droppableContainers:new xo,over:null,dragOverlay:{nodeRef:{current:null},rect:null,setRef:hc},scrollableAncestors:[],scrollableAncestorRects:[],measuringConfiguration:yc,measureDroppableContainers:hc,windowRect:null,measuringScheduled:!1},vE={activatorEvent:null,activators:[],active:null,activeNodeRect:null,ariaDescribedById:{draggable:""},dispatch:hc,draggableNodes:new Map,over:null,measureDroppableContainers:hc},bc=N.createContext(vE),Pm=N.createContext(bE);function SE(){return{draggable:{active:null,initialCoordinates:{x:0,y:0},nodes:new Map,translate:{x:0,y:0}},droppable:{containers:new xo}}}function wE(o,e){switch(e.type){case tn.DragStart:return{...o,draggable:{...o.draggable,initialCoordinates:e.initialCoordinates,active:e.active}};case tn.DragMove:return o.draggable.active==null?o:{...o,draggable:{...o.draggable,translate:{x:e.coordinates.x-o.draggable.initialCoordinates.x,y:e.coordinates.y-o.draggable.initialCoordinates.y}}};case tn.DragEnd:case tn.DragCancel:return{...o,draggable:{...o.draggable,active:null,initialCoordinates:{x:0,y:0},translate:{x:0,y:0}}};case tn.RegisterDroppable:{const{element:r}=e,{id:a}=r,i=new xo(o.droppable.containers);return i.set(a,r),{...o,droppable:{...o.droppable,containers:i}}}case tn.SetDroppableDisabled:{const{id:r,key:a,disabled:i}=e,l=o.droppable.containers.get(r);if(!l||a!==l.key)return o;const c=new xo(o.droppable.containers);return c.set(r,{...l,disabled:i}),{...o,droppable:{...o.droppable,containers:c}}}case tn.UnregisterDroppable:{const{id:r,key:a}=e,i=o.droppable.containers.get(r);if(!i||a!==i.key)return o;const l=new xo(o.droppable.containers);return l.delete(r),{...o,droppable:{...o.droppable,containers:l}}}default:return o}}function CE(o){let{disabled:e}=o;const{active:r,activatorEvent:a,draggableNodes:i}=N.useContext(bc),l=qd(a),c=qd(r?.id);return N.useEffect(()=>{if(!e&&!a&&l&&c!=null){if(!Vd(l)||document.activeElement===l.target)return;const d=i.get(c);if(!d)return;const{activatorNode:f,node:g}=d;if(!f.current&&!g.current)return;requestAnimationFrame(()=>{for(const m of[f.current,g.current]){if(!m)continue;const y=gC(m);if(y){y.focus();break}}})}},[a,e,i,c,l]),null}function EE(o,e){let{transform:r,...a}=e;return o!=null&&o.length?o.reduce((i,l)=>l({transform:i,...a}),r):r}function _E(o){return N.useMemo(()=>({draggable:{...yc.draggable,...o?.draggable},droppable:{...yc.droppable,...o?.droppable},dragOverlay:{...yc.dragOverlay,...o?.dragOverlay}}),[o?.draggable,o?.droppable,o?.dragOverlay])}function AE(o){let{activeNode:e,measure:r,initialRect:a,config:i=!0}=o;const l=N.useRef(!1),{x:c,y:d}=typeof i=="boolean"?{x:i,y:i}:i;Ur(()=>{if(!c&&!d||!e){l.current=!1;return}if(l.current||!a)return;const g=e?.node.current;if(!g||g.isConnected===!1)return;const m=r(g),y=Em(m,a);if(c||(y.x=0),d||(y.y=0),l.current=!0,Math.abs(y.x)>0||Math.abs(y.y)>0){const w=Am(g);w&&w.scrollBy({top:y.y,left:y.x})}},[e,c,d,a,r])}const qm=N.createContext({...wr,scaleX:1,scaleY:1});var La;(function(o){o[o.Uninitialized=0]="Uninitialized",o[o.Initializing=1]="Initializing",o[o.Initialized=2]="Initialized"})(La||(La={}));const xE=N.memo(function(e){var r,a,i,l;let{id:c,accessibility:d,autoScroll:f=!0,children:g,sensors:m=mE,collisionDetection:y=RC,measuring:w,modifiers:S,...v}=e;const A=N.useReducer(wE,void 0,SE),[x,R]=A,[M,O]=SC(),[L,q]=N.useState(La.Uninitialized),G=L===La.Initialized,{draggable:{active:B,nodes:K,translate:fe},droppable:{containers:Ce}}=x,ke=B!=null?K.get(B):null,Ue=N.useRef({initial:null,translated:null}),Pe=N.useMemo(()=>{var ue;return B!=null?{id:B,data:(ue=ke?.data)!=null?ue:yE,rect:Ue}:null},[B,ke]),qe=N.useRef(null),[wt,J]=N.useState(null),[he,Ee]=N.useState(null),Z=bo(v,Object.values(v)),pe=So("DndDescribedBy",c),H=N.useMemo(()=>Ce.getEnabled(),[Ce]),T=_E(w),{droppableRects:ge,measureDroppableContainers:de,measuringScheduled:me}=aE(H,{dragging:G,dependencies:[fe.x,fe.y],config:T.droppable}),ae=nE(K,B),Re=N.useMemo(()=>he?Fd(he):null,[he]),ze=ve(),$e=iE(ae,T.draggable.measure);AE({activeNode:B!=null?K.get(B):null,config:ze.layoutShiftCompensation,initialRect:$e,measure:T.draggable.measure});const Ge=Hm(ae,T.draggable.measure,$e),At=Hm(ae?ae.parentElement:null),yt=N.useRef({activatorEvent:null,active:null,activeNode:ae,collisionRect:null,collisions:null,droppableRects:ge,draggableNodes:K,draggingNode:null,draggingNodeRect:null,droppableContainers:Ce,over:null,scrollableAncestors:[],scrollAdjustedTranslate:null}),dn=Ce.getNodeFor((r=yt.current.over)==null?void 0:r.id),Tt=pE({measure:T.dragOverlay.measure}),Yt=(a=Tt.nodeRef.current)!=null?a:ae,ln=G?(i=Tt.rect)!=null?i:Ge:null,zt=!!(Tt.nodeRef.current&&Tt.rect),Tr=lE(zt?null:Ge),wn=Um(Yt?Dn(Yt):null),cn=cE(G?dn??ae:null),fn=hE(cn),sr=EE(S,{transform:{x:fe.x-Tr.x,y:fe.y-Tr.y,scaleX:1,scaleY:1},activatorEvent:he,active:Pe,activeNodeRect:Ge,containerNodeRect:At,draggingNodeRect:ln,over:yt.current.over,overlayNodeRect:Tt.rect,scrollableAncestors:cn,scrollableAncestorRects:fn,windowRect:wn}),Wn=Re?os(Re,fe):null,Ut=uE(cn),bt=zm(Ut),ra=zm(Ut,[Ge]),Ln=os(sr,bt),An=ln?LC(ln,sr):null,xn=Pe&&An?y({active:Pe,collisionRect:An,droppableRects:ge,droppableContainers:H,pointerCoordinates:Wn}):null,Mn=wm(xn,"id"),[hn,aa]=N.useState(null),$n=zt?sr:os(sr,ra),Vt=DC($n,(l=hn?.rect)!=null?l:null,Ge),Cn=N.useRef(null),nn=N.useCallback((ue,we)=>{let{sensor:_e,options:Be}=we;if(qe.current==null)return;const xe=K.get(qe.current);if(!xe)return;const De=ue.nativeEvent,Ae=new _e({active:qe.current,activeNode:xe,event:De,options:Be,context:yt,onAbort(Ne){if(!K.get(Ne))return;const{onDragAbort:Se}=Z.current,Me={id:Ne};Se?.(Me),M({type:"onDragAbort",event:Me})},onPending(Ne,je,Se,Me){if(!K.get(Ne))return;const{onDragPending:kt}=Z.current,Ot={id:Ne,constraint:je,initialCoordinates:Se,offset:Me};kt?.(Ot),M({type:"onDragPending",event:Ot})},onStart(Ne){const je=qe.current;if(je==null)return;const Se=K.get(je);if(!Se)return;const{onDragStart:Me}=Z.current,Ze={activatorEvent:De,active:{id:je,data:Se.data,rect:Ue}};Oa.unstable_batchedUpdates(()=>{Me?.(Ze),q(La.Initializing),R({type:tn.DragStart,initialCoordinates:Ne,active:je}),M({type:"onDragStart",event:Ze}),J(Cn.current),Ee(De)})},onMove(Ne){R({type:tn.DragMove,coordinates:Ne})},onEnd:et(tn.DragEnd),onCancel:et(tn.DragCancel)});Cn.current=Ae;function et(Ne){return async function(){const{active:Se,collisions:Me,over:Ze,scrollAdjustedTranslate:kt}=yt.current;let Ot=null;if(Se&&kt){const{cancelDrop:Nn}=Z.current;Ot={activatorEvent:De,active:Se,collisions:Me,delta:kt,over:Ze},Ne===tn.DragEnd&&typeof Nn=="function"&&await Promise.resolve(Nn(Ot))&&(Ne=tn.DragCancel)}qe.current=null,Oa.unstable_batchedUpdates(()=>{R({type:Ne}),q(La.Uninitialized),aa(null),J(null),Ee(null),Cn.current=null;const Nn=Ne===tn.DragEnd?"onDragEnd":"onDragCancel";if(Ot){const $t=Z.current[Nn];$t?.(Ot),M({type:Nn,event:Ot})}})}}},[K]),V=N.useCallback((ue,we)=>(_e,Be)=>{const xe=_e.nativeEvent,De=K.get(Be);if(qe.current!==null||!De||xe.dndKit||xe.defaultPrevented)return;const Ae={active:De};ue(_e,we.options,Ae)===!0&&(xe.dndKit={capturedBy:we.sensor},qe.current=Be,nn(_e,we))},[K,nn]),oe=rE(m,V);dE(m),Ur(()=>{Ge&&L===La.Initializing&&q(La.Initialized)},[Ge,L]),N.useEffect(()=>{const{onDragMove:ue}=Z.current,{active:we,activatorEvent:_e,collisions:Be,over:xe}=yt.current;if(!we||!_e)return;const De={active:we,activatorEvent:_e,collisions:Be,delta:{x:Ln.x,y:Ln.y},over:xe};Oa.unstable_batchedUpdates(()=>{ue?.(De),M({type:"onDragMove",event:De})})},[Ln.x,Ln.y]),N.useEffect(()=>{const{active:ue,activatorEvent:we,collisions:_e,droppableContainers:Be,scrollAdjustedTranslate:xe}=yt.current;if(!ue||qe.current==null||!we||!xe)return;const{onDragOver:De}=Z.current,Ae=Be.get(Mn),et=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:et};Oa.unstable_batchedUpdates(()=>{aa(et),De?.(Ne),M({type:"onDragOver",event:Ne})})},[Mn]),Ur(()=>{yt.current={activatorEvent:he,active:Pe,activeNode:ae,collisionRect:An,collisions:xn,droppableRects:ge,draggableNodes:K,draggingNode:Yt,draggingNodeRect:ln,droppableContainers:Ce,over:hn,scrollableAncestors:cn,scrollAdjustedTranslate:Ln},Ue.current={initial:ln,translated:An}},[Pe,ae,xn,An,K,Yt,ln,ge,Ce,hn,cn,Ln]),ZC({...ze,delta:fe,draggingRect:An,pointerCoordinates:Wn,scrollableAncestors:cn,scrollableAncestorRects:fn});const ce=N.useMemo(()=>({active:Pe,activeNode:ae,activeNodeRect:Ge,activatorEvent:he,collisions:xn,containerNodeRect:At,dragOverlay:Tt,draggableNodes:K,droppableContainers:Ce,droppableRects:ge,over:hn,measureDroppableContainers:de,scrollableAncestors:cn,scrollableAncestorRects:fn,measuringConfiguration:T,measuringScheduled:me,windowRect:wn}),[Pe,ae,Ge,he,xn,At,Tt,K,Ce,ge,hn,de,cn,fn,T,me,wn]),X=N.useMemo(()=>({activatorEvent:he,activators:oe,active:Pe,activeNodeRect:Ge,ariaDescribedById:{draggable:pe},dispatch:R,draggableNodes:K,over:hn,measureDroppableContainers:de}),[he,oe,Pe,Ge,R,pe,K,hn,de]);return We.createElement(mm.Provider,{value:O},We.createElement(bc.Provider,{value:X},We.createElement(Pm.Provider,{value:ce},We.createElement(qm.Provider,{value:Vt},g)),We.createElement(CE,{disabled:d?.restoreFocus===!1})),We.createElement(EC,{...d,hiddenTextDescribedById:pe}));function ve(){const ue=wt?.autoScrollEnabled===!1,we=typeof f=="object"?f.enabled===!1:f===!1,_e=G&&!ue&&!we;return typeof f=="object"?{...f,enabled:_e}:{enabled:_e}}}),TE=N.createContext(null),Gm="button",kE="Draggable";function RE(o){let{id:e,data:r,disabled:a=!1,attributes:i}=o;const l=So(kE),{activators:c,activatorEvent:d,active:f,activeNodeRect:g,ariaDescribedById:m,draggableNodes:y,over:w}=N.useContext(bc),{role:S=Gm,roleDescription:v="draggable",tabIndex:A=0}=i??{},x=f?.id===e,R=N.useContext(x?qm:TE),[M,O]=fc(),[L,q]=fc(),G=fE(c,e),B=bo(r);Ur(()=>(y.set(e,{id:e,key:l,node:M,activatorNode:L,data:B}),()=>{const fe=y.get(e);fe&&fe.key===l&&y.delete(e)}),[y,e]);const K=N.useMemo(()=>({role:S,tabIndex:A,"aria-disabled":a,"aria-pressed":x&&S===Gm?!0:void 0,"aria-roledescription":v,"aria-describedby":m.draggable}),[a,S,A,x,v,m.draggable]);return{active:f,activatorEvent:d,activeNodeRect:g,attributes:K,isDragging:x,listeners:a?void 0:G,node:M,over:w,setNodeRef:O,setActivatorNodeRef:q,transform:R}}function DE(){return N.useContext(Pm)}const OE="Droppable",LE={timeout:25};function ME(o){let{data:e,disabled:r=!1,id:a,resizeObserverConfig:i}=o;const l=So(OE),{active:c,dispatch:d,over:f,measureDroppableContainers:g}=N.useContext(bc),m=N.useRef({disabled:r}),y=N.useRef(!1),w=N.useRef(null),S=N.useRef(null),{disabled:v,updateMeasurementsFor:A,timeout:x}={...LE,...i},R=bo(A??a),M=N.useCallback(()=>{if(!y.current){y.current=!0;return}S.current!=null&&clearTimeout(S.current),S.current=setTimeout(()=>{g(Array.isArray(R.current)?R.current:[R.current]),S.current=null},x)},[x]),O=mc({callback:M,disabled:v||!c}),L=N.useCallback((K,fe)=>{O&&(fe&&(O.unobserve(fe),y.current=!1),K&&O.observe(K))},[O]),[q,G]=fc(L),B=bo(e);return N.useEffect(()=>{!O||!q.current||(O.disconnect(),y.current=!1,O.observe(q.current))},[q,O]),N.useEffect(()=>(d({type:tn.RegisterDroppable,element:{id:a,key:l,disabled:r,node:q,rect:w,data:B}}),()=>d({type:tn.UnregisterDroppable,key:l,id:a})),[a]),N.useEffect(()=>{r!==m.current.disabled&&(d({type:tn.SetDroppableDisabled,id:a,key:l,disabled:r}),m.current.disabled=r)},[a,l,r,d]),{active:c,rect:w,isOver:f?.id===a,node:q,over:f,setNodeRef:G}}function rf(o,e,r){const a=o.slice();return a.splice(r<0?a.length+r:r,0,a.splice(e,1)[0]),a}function $E(o,e){return o.reduce((r,a,i)=>{const l=e.get(a);return l&&(r[i]=l),r},Array(o.length))}function vc(o){return o!==null&&o>=0}function NE(o,e){if(o===e)return!0;if(o.length!==e.length)return!1;for(let r=0;r{var e;let{rects:r,activeNodeRect:a,activeIndex:i,overIndex:l,index:c}=o;const d=(e=r[i])!=null?e:a;if(!d)return null;const f=jE(r,c,i);if(c===i){const g=r[l];return g?{x:ii&&c<=l?{x:-d.width-f,y:0,...Sc}:c=l?{x:d.width+f,y:0,...Sc}:{x:0,y:0,...Sc}};function jE(o,e,r){const a=o[e],i=o[e-1],l=o[e+1];return!a||!i&&!l?0:r{let{rects:e,activeIndex:r,overIndex:a,index:i}=o;const l=rf(e,a,r),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}},wc={scaleX:1,scaleY:1},zE=o=>{var e;let{activeIndex:r,activeNodeRect:a,index:i,rects:l,overIndex:c}=o;const d=(e=l[r])!=null?e:a;if(!d)return null;if(i===r){const g=l[c];return g?{x:0,y:rr&&i<=c?{x:0,y:-d.height-f,...wc}:i=c?{x:0,y:d.height+f,...wc}:{x:0,y:0,...wc}};function UE(o,e,r){const a=o[e],i=o[e-1],l=o[e+1];return a?ra.map(G=>typeof G=="object"&&"id"in G?G.id:G),[a]),v=c!=null,A=c?S.indexOf(c.id):-1,x=g?S.indexOf(g.id):-1,R=N.useRef(S),M=!NE(S,R.current),O=x!==-1&&A===-1||M,L=IE(l);Ur(()=>{M&&v&&m(S)},[M,S,v,m]),N.useEffect(()=>{R.current=S},[S]);const q=N.useMemo(()=>({activeIndex:A,containerId:y,disabled:L,disableTransforms:O,items:S,overIndex:x,useDragOverlay:w,sortedRects:$E(S,f),strategy:i}),[A,y,L.draggable,L.droppable,O,S,x,f,w,i]);return We.createElement(Fm.Provider,{value:q},e)}const PE=o=>{let{id:e,items:r,activeIndex:a,overIndex:i}=o;return rf(r,a,i).indexOf(e)},qE=o=>{let{containerId:e,isSorting:r,wasDragging:a,index:i,items:l,newIndex:c,previousItems:d,previousContainerId:f,transition:g}=o;return!g||!a||d!==l&&i===c?!1:r?!0:c!==i&&e===f},GE={duration:200,easing:"ease"},Km="transform",VE=Co.Transition.toString({property:Km,duration:0,easing:"linear"}),FE={roleDescription:"sortable"};function KE(o){let{disabled:e,index:r,node:a,rect:i}=o;const[l,c]=N.useState(null),d=N.useRef(r);return Ur(()=>{if(!e&&r!==d.current&&a.current){const f=i.current;if(f){const g=ls(a.current,{ignoreTransform:!0}),m={x:f.left-g.left,y:f.top-g.top,scaleX:f.width/g.width,scaleY:f.height/g.height};(m.x||m.y)&&c(m)}}r!==d.current&&(d.current=r)},[e,r,a,i]),N.useEffect(()=>{l&&c(null)},[l]),l}function WE(o){let{animateLayoutChanges:e=qE,attributes:r,disabled:a,data:i,getNewIndex:l=PE,id:c,strategy:d,resizeObserverConfig:f,transition:g=GE}=o;const{items:m,containerId:y,activeIndex:w,disabled:S,disableTransforms:v,sortedRects:A,overIndex:x,useDragOverlay:R,strategy:M}=N.useContext(Fm),O=YE(a,S),L=m.indexOf(c),q=N.useMemo(()=>({sortable:{containerId:y,index:L,items:m},...i}),[y,i,L,m]),G=N.useMemo(()=>m.slice(m.indexOf(c)),[m,c]),{rect:B,node:K,isOver:fe,setNodeRef:Ce}=ME({id:c,data:q,disabled:O.droppable,resizeObserverConfig:{updateMeasurementsFor:G,...f}}),{active:ke,activatorEvent:Ue,activeNodeRect:Pe,attributes:qe,setNodeRef:wt,listeners:J,isDragging:he,over:Ee,setActivatorNodeRef:Z,transform:pe}=RE({id:c,data:q,attributes:{...FE,...r},disabled:O.draggable}),H=uC(Ce,wt),T=!!ke,ge=T&&!v&&vc(w)&&vc(x),de=!R&&he,me=de&&ge?pe:null,Re=ge?me??(d??M)({rects:A,activeNodeRect:Pe,activeIndex:w,overIndex:x,index:L}):null,ze=vc(w)&&vc(x)?l({id:c,items:m,activeIndex:w,overIndex:x}):L,$e=ke?.id,Ge=N.useRef({activeId:$e,items:m,newIndex:ze,containerId:y}),At=m!==Ge.current.items,yt=e({active:ke,containerId:y,isDragging:he,isSorting:T,id:c,index:L,items:m,newIndex:Ge.current.newIndex,previousItems:Ge.current.items,previousContainerId:Ge.current.containerId,transition:g,wasDragging:Ge.current.activeId!=null}),dn=KE({disabled:!yt,index:L,node:K,rect:B});return N.useEffect(()=>{T&&Ge.current.newIndex!==ze&&(Ge.current.newIndex=ze),y!==Ge.current.containerId&&(Ge.current.containerId=y),m!==Ge.current.items&&(Ge.current.items=m)},[T,ze,y,m]),N.useEffect(()=>{if($e===Ge.current.activeId)return;if($e!=null&&Ge.current.activeId==null){Ge.current.activeId=$e;return}const Yt=setTimeout(()=>{Ge.current.activeId=$e},50);return()=>clearTimeout(Yt)},[$e]),{active:ke,activeIndex:w,attributes:qe,data:q,rect:B,index:L,newIndex:ze,items:m,isOver:fe,isSorting:T,isDragging:he,listeners:J,node:K,overIndex:x,over:Ee,setNodeRef:H,setActivatorNodeRef:Z,setDroppableNodeRef:Ce,setDraggableNodeRef:wt,transform:dn??Re,transition:Tt()};function Tt(){if(dn||At&&Ge.current.newIndex===L)return VE;if(!(de&&!Vd(Ue)||!g)&&(T||yt))return Co.Transition.toString({...g,property:Km})}}function YE(o,e){var r,a;return typeof o=="boolean"?{draggable:o,droppable:!1}:{draggable:(r=o?.draggable)!=null?r:e.draggable,droppable:(a=o?.droppable)!=null?a:e.droppable}}function Cc(o){if(!o)return!1;const e=o.data.current;return!!(e&&"sortable"in e&&typeof e.sortable=="object"&&"containerId"in e.sortable&&"items"in e.sortable&&"index"in e.sortable)}const XE=[ot.Down,ot.Right,ot.Up,ot.Left],JE=(o,e)=>{let{context:{active:r,collisionRect:a,droppableRects:i,droppableContainers:l,over:c,scrollableAncestors:d}}=e;if(XE.includes(o.code)){if(o.preventDefault(),!r||!a)return;const f=[];l.getEnabled().forEach(y=>{if(!y||y!=null&&y.disabled)return;const w=i.get(y.id);if(w)switch(o.code){case ot.Down:a.topw.top&&f.push(y);break;case ot.Left:a.left>w.left&&f.push(y);break;case ot.Right:a.left1&&(m=g[1].id),m!=null){const y=l.get(r.id),w=l.get(m),S=w?i.get(w.id):null,v=w?.node.current;if(v&&S&&y&&w){const x=gc(v).some((G,B)=>d[B]!==G),R=Wm(y,w),M=QE(y,w),O=x||!R?{x:0,y:0}:{x:M?a.width-S.width:0,y:M?a.height-S.height:0},L={x:S.left,y:S.top};return O.x&&O.y?L:wo(L,O)}}}};function Wm(o,e){return!Cc(o)||!Cc(e)?!1:o.data.current.sortable.containerId===e.data.current.sortable.containerId}function QE(o,e){return!Cc(o)||!Cc(e)||!Wm(o,e)?!1:o.data.current.sortable.index{const d=N.useId(),f=N.useRef({inProgress:!1,lastSortTime:0,lastActiveId:null}),g=_C(ym(Zd,{activationConstraint:{distance:5}}),ym(Jd,{coordinateGetter:JE})),m=N.useCallback(S=>{f.current={inProgress:!0,lastSortTime:Date.now(),lastActiveId:S.active.id},l?.({activeId:S.active.id})},[l]),y=N.useCallback(S=>{const{active:v,over:A}=S,x=Date.now();if(!A||v.id===A.id){f.current.inProgress=!1;return}const{lastSortTime:R,lastActiveId:M,inProgress:O}=f.current;if(M===v.id&&x-R<500&&!O)return;f.current={inProgress:!1,lastSortTime:x,lastActiveId:v.id};const L=o.findIndex(G=>String(G[e])===String(v.id)),q=o.findIndex(G=>String(G[e])===String(A.id));if(L!==-1&&q!==-1&&L!==q){const G=rf(o,L,q);i?.(G,{oldIndex:L,newIndex:q})}},[o,e,i]),w=o.map(S=>String(S[e]));return dt.jsx(xE,{id:d,sensors:g,collisionDetection:xC,onDragStart:m,onDragEnd:y,children:dt.jsx(BE,{items:w,strategy:ZE[r],children:a})},c!==void 0?`${d}-v${c}`:d)},Ym=N.createContext(null),t_=({value:o,children:e})=>dt.jsx(Ym.Provider,{value:o,children:e}),n_=()=>N.useContext(Ym),r_=({id:o,handle:e,as:r="div",children:a})=>{const{attributes:i,listeners:l,setNodeRef:c,transform:d,transition:f,isDragging:g}=WE({id:o}),m={transform:Co.Transform.toString(d),transition:f,opacity:g?.5:1,position:"relative"};return dt.jsx(r,{ref:c,style:m,...i,...e?{}:l,"data-sortable-item":!0,"data-sortable-id":String(o),"data-dragging":g,children:dt.jsx(t_,{value:{listeners:l,handle:e,isDragging:g},children:a})})},rt=ut("DynamicRenderer");function ea(){try{return window.G7Core?.devTools}catch{return}}function sf(o,e,r,a){if(typeof o=="string"){if(/\$t:[a-zA-Z_][a-zA-Z0-9_.\-]*/.test(o))try{return e.resolveTranslations(o,r,a)}catch{return o}return o}if(Array.isArray(o))return o.map(i=>sf(i,e,r,a));if(o&&typeof o=="object"){const i={};for(const[l,c]of Object.entries(o))i[l]=sf(c,e,r,a);return i}return o}function a_(o){const e=Object.keys(o);return e.length>0&&e.every(r=>/^\d+$/.test(r))}const Cr=(o,e)=>{const r=["errors"],a={...o};for(const i of Object.keys(e)){const l=e[i],c=o[i];if(l===null){a[i]=null;continue}if(r.includes(i)){a[i]=l;continue}if(Array.isArray(l)){a[i]=l;continue}if(Array.isArray(c)&&l!==null&&typeof l=="object"&&!Array.isArray(l)&&a_(l)){const d=Object.keys(l).map(g=>parseInt(g,10));if((d.length>0?Math.max(...d):0)>=c.length+d.length+10)a[i]={...l};else{const g=[...c];for(const[m,y]of Object.entries(l)){const w=parseInt(m,10);w>=0&&w=g.length&&(g[w]=y)}a[i]=g}}else l!==null&&typeof l=="object"&&c!==null&&typeof c=="object"&&!Array.isArray(c)?a[i]=Cr(c,l):a[i]=l}return a},Ec=(o,e)=>{let r=null;const a=()=>(r===null&&(r={...o}),r);for(const i of Object.keys(e)){if(!(i in o))continue;const l=e[i],c=o[i];if(l!==null&&typeof l=="object"&&!Array.isArray(l)&&c!==null&&typeof c=="object"&&!Array.isArray(c)){const d=Ec(c,l);if(d===c)continue;Object.keys(d).length===0?delete a()[i]:a()[i]=d}else delete a()[i]}return r??o},i_=o=>{const e={},r=o.split(";").filter(a=>a.trim());for(const a of r){const i=a.indexOf(":");if(i===-1)continue;const l=a.substring(0,i).trim(),c=a.substring(i+1).trim();if(l&&c){const d=l.replace(/-([a-z])/g,(f,g)=>g.toUpperCase());e[d]=c}}return e};class s_ extends N.Component{constructor(e){super(e),this.state={hasError:!1,error:null}}static getDerivedStateFromError(e){return{hasError:!0,error:e}}componentDidCatch(e,r){rt.error(`컴포넌트 렌더링 에러 (ID: ${this.props.componentId}, Name: ${this.props.componentName}):`,e,r)}render(){return this.state.hasError?this.props.fallback?this.props.fallback:dt.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:[dt.jsx("div",{className:"font-semibold mb-1",children:"컴포넌트 로드 실패"}),dt.jsxs("div",{className:"text-xs opacity-80",children:[this.props.componentName&&`[${this.props.componentName}] `,"데이터를 표시할 수 없습니다."]}),this.state.error&&dt.jsxs("details",{className:"mt-2",children:[dt.jsx("summary",{className:"cursor-pointer text-xs opacity-70 hover:opacity-100",children:"상세 정보"}),dt.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 Br=N.memo(({componentDef:o,dataContext:e,translationContext:r,registry:a,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:d,parentFormContextProp:f,parentDataContext:g,isRootRenderer:m=!1,isInsideIteration:y=!1,isEditMode:w=!1,onComponentSelect:S,onComponentHover:v,onDragStart:A,onDragEnd:x,componentPath:R,layoutKey:M})=>{const[O,L]=N.useState({loadingActions:{}});N.useLayoutEffect(()=>{d||(i.startRenderCycle(),window.__g7SetLocalOverrideKeys||(window.__g7ForcedLocalFields=void 0),window.__g7PendingLocalState=null)});const q=N.useRef(null);N.useLayoutEffect(()=>{if(!d&&e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:V,_merge:oe,...ce}=e._localInit,X=`${JSON.stringify(ce)}:${V||"no-force"}`;if(q.current!==X){q.current=X;const ve=oe||"shallow",we=window.G7Core?.state?.get?.()?._local||{},_e=window.__g7PendingLocalState||{},Be={...we,..._e};ve==="replace"?window.__g7PendingLocalState={loadingActions:Be.loadingActions||{},...ce,hasChanges:!1}:ve==="deep"?window.__g7PendingLocalState=Cr(Be,{...ce,hasChanges:!1}):window.__g7PendingLocalState={...Be,...ce,hasChanges:!1};const xe=window.__g7SetLocalOverrideKeys;xe&&typeof xe=="object"&&(ve==="replace"?window.__g7SetLocalOverrideKeys={...ce,hasChanges:!1}:window.__g7SetLocalOverrideKeys=Cr(xe,{...ce,hasChanges:!1}))}}}),N.useLayoutEffect(()=>{if(!d){const V=window.__g7SetLocalOverrideKeys;if(V){L(ve=>Ec(ve,V));const oe=V,ce=window.__g7ForcedLocalFields,X=window.__g7LastSetLocalSnapshot;queueMicrotask(()=>{window.__g7SetLocalOverrideKeys===oe&&(window.__g7SetLocalOverrideKeys=void 0),window.__g7ForcedLocalFields===ce&&(window.__g7ForcedLocalFields=void 0),window.__g7LastSetLocalSnapshot===X&&(window.__g7LastSetLocalSnapshot=void 0)})}}},[e._local]);const G=N.useRef(M);N.useEffect(()=>{o._fromBase&&M&&G.current!==M&&(G.current=M,L({loadingActions:{}}))},[M,o._fromBase]);const B=N.useRef(""),K=N.useRef(!1),fe=N.useRef(null),Ce=N.useRef(null),ke=N.useRef({}),Ue=N.useRef({}),Pe=N.useRef(g),qe=cC(),wt=z0(),J=wt?.getParentDataContext()??g;N.useEffect(()=>{if(e._localInit&&typeof e._localInit=="object"){const{_forceLocalInit:V,...oe}=e._localInit,ce=JSON.stringify(oe),X=V!==void 0,ve=Hd(),ue=`${ce}:${V||"no-force"}`,we=K0({globalTrackedKey:ve.hash,instanceHandledKey:Ce.current,trackingKey:ue});if(we==="apply"){Ce.current=ue,ve.hash=ue,ve.timestamp=V,B.current=ce,X&&(K.current=!0);const{_merge:Be,...xe}=oe,De=Be||"shallow";L(Ae=>De==="replace"?{loadingActions:Ae.loadingActions||{},...xe,hasChanges:!1}:De==="deep"?Cr(Ae,{...xe,hasChanges:!1}):{...Ae,...xe,hasChanges:!1}),e._globalSetState&&e._globalSetState(Ae=>{const et=Ae?._local||{};let Ne;return De==="replace"?Ne={...xe,hasChanges:!1}:De==="deep"?Ne=Cr(et,{...xe,hasChanges:!1}):Ne={...et,...xe,hasChanges:!1},{...Ae,_local:Ne}}),i.invalidateCacheByKeys(["_local"]),rt.log("_localInit applied (data changed):",Object.keys(oe))}else if(we==="prune"){Ce.current=ue;const{_merge:Be,...xe}=oe;L(Ae=>Ec(Ae,xe)),Ec(O,xe)!==O&&(i.invalidateCacheByKeys(["_local"]),rt.log("_localInit pruned (applied by another renderer):",Object.keys(xe)))}fe.current=e._localInit,V0(e._localInit)}},[e._localInit,g,i]);const{isTransitioning:he}=om(),Ee=eC(),Z=f??Ee,{width:pe}=zd(),H=n_(),T=N.useMemo(()=>{let V=o;if(o.type==="iterator"&&o.data){const{data:X,itemName:ve,indexName:ue,...we}=o;V={...we,iteration:{source:X,item_var:ve||"item",index_var:ue}}}if(!V.responsive)return V;const oe=mi.getMatchingKey(V.responsive,pe);if(!oe)return V;const ce=V.responsive[oe];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?oe:void 0}},[o,pe]),ge=N.useCallback(V=>{const oe=V?.__setStateId;if(L(ce=>{const X=window.__g7PendingLocalState,ue=window.__g7SetLocalOverrideKeys||X,we=ue?Cr(ce,ue):ce;if(typeof V=="function"){const Ae=V(we);return Cr(we,Ae)}const{__mergeMode:_e,__setStateId:Be,...xe}=V;let De;if(_e==="replace"?De=xe:_e==="shallow"?De={...we,...xe}:De=Cr(we,xe),_e!==void 0){const Ae=window.__g7ForcedLocalFields;Ae&&(window.__g7ForcedLocalFields={...Ae,...xe})}return De}),oe){const ce=ea();if(ce?.isEnabled()){const X=T.id||"unknown",ve=T.name||"Unknown";setTimeout(()=>{ce.trackComponentRender?.(X,ve,0,["_local"],[]),ce.completeStateChange?.(oe)},0)}}},[T.id,T.name]),de=d?.state??O,me=d?.setState??ge,ae=N.useMemo(()=>{const V=e._localInit&&e._localInit!==fe.current;let oe;V&&e._local?oe=e._local:oe=e._local?Cr(e._local,de):de;const ce=window.__g7ForcedLocalFields;ce&&(oe=Cr(oe,ce));const X={...e,_local:oe},ve=e._computedDefinitions;if(ve&&Object.keys(ve).length>0){const ue=new _n,we={...X,...qe?{_isolated:qe.state}:{}},_e={},Be=ea(),xe=Be?.isEnabled()??!1;for(const[De,Ae]of Object.entries(ve)){const et=xe?Date.now():0,Ne=xe?e._computed?.[De]:void 0;let je;try{if(typeof Ae=="string")if(Ae.startsWith("{{")&&Ae.endsWith("}}")){const Se=Ae.slice(2,-2).trim(),Me=Gn(Se)?ue.evaluatePipeExpression(Se,we,{skipCache:!0}):ue.evaluateExpression(Se,we,{skipCache:!0});_e[De]=Me}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){rt.warn(`Failed to recalculate computed value: ${De}`,Se),_e[De]=e._computed?.[De],je=Se instanceof Error?Se.message:String(Se)}if(xe&&(je||Ne!==_e[De])){const Me=Date.now()-et;Be.trackComputedProperty?.(De,typeof Ae=="string"?Ae:JSON.stringify(Ae),[{type:"_local",path:"_local",value:X._local}],_e[De],Me,T.id,je),Ne!==_e[De]&&Be.trackComputedRecalc?.(De,"dependency-change",Ne,_e[De],Me,{type:"_local",path:"_local"},T.id)}}X._computed=_e}if(qe&&(X._isolated=qe.state),J&&(X.$parent=J),o.extensionPointProps){const ue=i.resolveObject(o.extensionPointProps,X,y?{skipCache:!0}:void 0);X.extensionPointProps=w&&l?sf(ue,l,r,X):ue}return o.extensionPointCallbacks&&(X.extensionPointCallbacks=o.extensionPointCallbacks),w&&(X.$templateId===void 0&&r?.templateId&&(X.$templateId=r.templateId),X.$locale===void 0&&r?.locale&&(X.$locale=r.locale)),X},[e,de,qe?.state,J,wt?.version,o.extensionPointProps,o.extensionPointCallbacks]);ke.current=ae._local,Ue.current=ae._computed||{},Pe.current=J,N.useEffect(()=>{const V=ea();if(!V?.isEnabled())return;const oe=ae._local;oe&&V.updateLocalState(oe);const ce=ae._computed;ce&&V.updateComputedState(ce),J&&V.updateParentContext?.(J);const X=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};V.trackComponentStateSource?.(X,ve,ue,we),de&&Object.keys(de).length>0&&V.trackDynamicState?.(X,de);const _e=!!(T.expandChildren||T.props?.expandChildren);V.trackContextFlow?.(X,ve,!!d,_e,!0)},[ae._local,e,T.id,T.name,d,de,T.expandChildren,T.props?.expandChildren,J]);const Re=N.useMemo(()=>({state:{...ae._local},setState:me,stateRef:ke,computedRef:Ue,isolatedContext:qe,parentDataContext:ae}),[ae._local,me,O,qe,ae]),ze=N.useMemo(()=>{const V=Qi({if:T.if,condition:T.condition,conditions:T.conditions},ae,i,T.id);if(T.if||T.condition!==void 0||T.conditions){const ce=ea();ce?.isEnabled()&&T.if&&ce.trackIfCondition(T.id||`if-${Date.now()}`,T.if,V)}return V},[T.if,T.conditions,ae,i,T.id]),$e=N.useMemo(()=>{if(!T.slot)return null;const V=T.slot;if(V.startsWith("{{")&&V.endsWith("}}")){const oe=V.slice(2,-2).trim();try{const ce={componentId:T.id,componentName:T.name,propName:"slot"},X=Gn(oe)?i.evaluatePipeExpression(oe,ae,void 0,ce):i.evaluateExpression(oe,ae,ce);return rt.log(`[Slot] 표현식 평가: "${oe}" => "${X}" (컴포넌트: ${T.id})`),typeof X=="string"?X:null}catch(ce){return rt.warn(`slot 표현식 평가 실패 (컴포넌트: ${T.id}):`,ce),null}}return rt.log(`[Slot] 정적 슬롯 ID: "${V}" (컴포넌트: ${T.id})`),V},[T.slot,T.id,ae,i]),Ge=N.useMemo(()=>!$e||!T.id?"":`${T.id}-${$e}-${JSON.stringify(T.slotOrder??0)}`,[$e,T.id,T.slotOrder]),At=N.useRef(null);N.useEffect(()=>{const V=window.__slotContextValue,oe=V?.isEnabled??!1;if(T.slot&&rt.log(`[Slot Registration] 컴포넌트: ${T.id}, isSlotEnabled: ${oe}, shouldRender: ${ze}, resolvedSlotId: ${$e}`),!oe||!ze){T.slot&&rt.log(`[Slot Registration] 등록 스킵 - isSlotEnabled: ${oe}, shouldRender: ${ze}`),At.current&&T.id&&V&&(V.unregisterFromSlot(At.current,T.id),At.current=null);return}if(!$e||!T.id){T.slot&&rt.log(`[Slot Registration] 등록 스킵 - resolvedSlotId: ${$e}, id: ${T.id}`),At.current&&T.id&&V&&(V.unregisterFromSlot(At.current,T.id),At.current=null);return}At.current&&At.current!==$e&&V.unregisterFromSlot(At.current,T.id);const ce={...T,slot:void 0,slotOrder:void 0};return V.registerToSlot($e,T.id,{componentDef:ce,dataContext:e,order:T.slotOrder??0,parentFormContext:f??null,getParentComponentContext:()=>Re,translationContext:r,registrationKey:Ge}),At.current=$e,()=>{const X=window.__slotContextValue;$e&&T.id&&X&&X.unregisterFromSlot($e,T.id)}},[ze,$e,T,e,f,Re,r,Ge]);const yt=N.useCallback(V=>{if(typeof V=="string"){if(ql(V))return hd(V);if(Gl(V)){const oe=[],ce=V.replace(new RegExp(`${ro}([^${pi}]*)${pi}`,"g"),(ve,ue)=>(oe.push(ue),`${ka}${oe.length-1}${ka}`));let X=ce;return/\$t:[a-zA-Z0-9._-]+/.test(ce)&&(X=l.resolveTranslations(ce,r,ae)),X.replace(new RegExp(`${ka}(\\d+)${ka}`,"g"),(ve,ue)=>oe[parseInt(ue)])}if(V.startsWith("$t:defer:"))return V;if(/\$t:[a-zA-Z0-9._-]+/.test(V)){const oe=V.trim();return oe.startsWith("{")&&oe.endsWith("}")||oe.startsWith("[")&&oe.endsWith("]")?V:l.resolveTranslations(V,r,ae)}return V}if(Array.isArray(V))return V.map(oe=>yt(oe));if(V&&typeof V=="object"){const oe={};for(const[ce,X]of Object.entries(V))oe[ce]=yt(X);return oe}return V},[l,r,ae]),dn=N.useCallback(V=>no(V),[]),Tt=N.useCallback(V=>Ta(V),[]),Yt=N.useMemo(()=>{let V={...T.props||{}};const oe=["cellChildren","expandChildren","expandContext","render"],X=a.getMetadata(T.name)?.skipBindingKeys||[],ve=[...new Set([...oe,...X])],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,Me]of Object.entries(V))if(!ve.includes(Se))if(typeof Me=="string"){const Ze=Tt(Me);if(Ze!==null){let kt=!1,Ot=Ze;Ze.startsWith(nr)&&(kt=!0,Ot=Ze.slice(nr.length));const Nn={componentId:T.id,componentName:T.name,propName:Se};let $t;if(Gn(Ot))try{$t=i.evaluatePipeExpression(Ot,ae,_e(Ot),Nn)}catch(Nt){rt.warn(`파이프 표현식 평가 실패 (컴포넌트: ${T.id}, prop: ${Se}):`,Nt),$t=void 0}else if(dn(Ot))try{$t=i.evaluateExpression(Ot,ae,Nn)}catch(Nt){rt.warn(`표현식 평가 실패 (컴포넌트: ${T.id}, prop: ${Se}):`,Nt),$t=void 0}else $t=i.resolve(Ot,ae,_e(Ot),Nn);V[Se]=kt&&$t!=null?Ji($t):$t}else{const kt={componentId:T.id,componentName:T.name,propName:Se};V[Se]=i.resolveBindings(Me,ae,ue,kt)}}else Array.isArray(Me)?V[Se]=Me.map(Ze=>typeof Ze=="string"?i.resolveBindings(Ze,ae,ue):typeof Ze=="object"&&Ze!==null?i.resolveObject(Ze,ae,we):Ze):Me&&typeof Me=="object"&&(V[Se]=i.resolveObject(Me,ae,we));for(const[Se,Me]of Object.entries(V))V[Se]=yt(Me);if(typeof V.style=="string"&&(V.style=i_(V.style)),V=yd(V,w?void 0:T.actions,ae,{componentContext:Re,actionDispatcher:c}),T.classMap){const Se=cw(T.classMap,ae,i,{skipCache:!0});if(Se){const Me=V.className||"";V.className=Me?`${Me} ${Se}`:Se}}T.style&&(V.style=T.style),T.actions&&T.actions.length>0&&T.type==="composite"&&Object.assign(V,de),T.component_layout&&(V.__componentLayoutDefs=T.component_layout);const Be=T.expandChildren||T.props?.expandChildren,xe=T.props?.cellChildren,De=T.children&&T.children.length>0,Ae=T.component_layout,et=T.slot,Ne=T.props?.modalId,je=T.type==="composite";return(Be||xe||De||Ae||et||Ne||je)&&(V.__componentContext=Re),V},[T.props,T.actions,T.style,T.classMap,T.id,ae,r,i,l,Re,de,yt,dn,Tt,y]),ln=N.useRef(null),zt=N.useMemo(()=>ln.current&&cm(ln.current,Yt)?ln.current:(ln.current=Yt,Yt),[Yt]),Tr=N.useMemo(()=>{const V=T.id;if(typeof V!="string"||!V.includes("{{"))return V;const oe=i.resolveBindings(V,ae,{skipCache:!0});return typeof oe=="string"?oe:V},[T.id,ae,i]),wn=N.useMemo(()=>{const V=T.dataKey,oe=T.trackChanges,ce=T.debounce;if(V){const X=V.startsWith("_global."),ve=X?V.slice(8):V,ue=X?e._global:ae._local;return{dataKey:ve,trackChanges:oe??!1,debounce:ce,setState:X?_e=>{e._globalSetState?e._globalSetState(_e):rt.warn("_global.formData 사용 시 _globalSetState가 필요합니다.")}:me,state:ue??{},_isGlobal:X}}if(Z.dataKey)return Z},[T.dataKey,T.trackChanges,T.debounce,T.id,me,ae._local,e._global,e._globalSetState,Z]),cn=N.useRef(new Set);N.useEffect(()=>{cn.current.clear()},[e._global?._remountKeys]);const fn=N.useCallback((V,oe)=>{const ce=e._global?._remountKeys;return V&&ce?.[V]&&!cn.current.has(V)?(cn.current.add(V),`${V}-remount-${ce[V]}`):V||oe},[e._global?._remountKeys]),sr=N.useMemo(()=>{if(T.text!==void 0){if(typeof T.text=="string"){const V=T.text;let oe=V;const ce={componentId:T.id,componentName:T.name,propName:"text",skipCache:!0},X=Tt(V);if(X!==null){let ve=!1,ue=X;if(X.startsWith(nr)&&(ve=!0,ue=X.slice(nr.length)),Gn(ue))try{oe=i.evaluatePipeExpression(ue,ae,{skipCache:!0},ce)}catch(we){rt.warn(`text 파이프 표현식 평가 실패 (컴포넌트: ${T.id}):`,we),oe=""}else if(dn(ue))try{oe=i.evaluateExpression(ue,ae,ce)}catch(we){rt.warn(`text 표현식 평가 실패 (컴포넌트: ${T.id}):`,we),oe=""}else oe=i.resolve(ue,ae,{skipCache:!0},ce);ve&&oe!=null&&(oe=Ji(oe))}else V.includes("{{")&&(oe=i.resolveBindings(V,ae,{skipCache:!0},ce));return oe=yt(oe),oe??""}return T.text}return!T.children||T.children.length===0?null:T.children.map((V,oe)=>{if(typeof V=="string")return V;const ce=T.__responsiveChildrenKey,X=ce?`responsive.${ce}.children`:"children",ve=R?`${R}.${X}.${oe}`:`${oe}`,ue=V._fromBase?V.id||`child-${oe}`:fn(V.id,`child-${oe}`),we=!V._fromBase&&M?`${ue}_${M}`:ue;return dt.jsx(Br,{componentDef:V,dataContext:ae,translationContext:r,registry:a,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:Re,parentFormContextProp:wn,isInsideIteration:y,isEditMode:w,onComponentSelect:S,onComponentHover:v,componentPath:ve,onDragStart:A,onDragEnd:x,layoutKey:M},we)})},[T.text,T.children,T.id,e,ae,r,a,i,l,c,Re,wn,Tt,dn,yt,fn,y,w,S,v,R,A,x,M]),Wn=N.useMemo(()=>{if(!T.iteration)return null;try{const V=md(T.iteration.source,ae,i);if(!Array.isArray(V))return rt.warn(`iteration source가 배열이 아닙니다 (컴포넌트: ${T.id}):`,V),null;const oe=ea();return oe?.isEnabled()&&oe.trackIteration(T.id||`iteration-${Date.now()}`,T.iteration.source,T.iteration.item_var,T.iteration.index_var,V.length),V.map((ce,X)=>{const ve={...ae,[T.iteration.item_var]:ce,[`${T.iteration.item_var}_index`]:X};T.iteration.index_var&&(ve[T.iteration.index_var]=X);const ue=X===0||X===V.length-1;oe?.isEnabled()&&ue&&oe.trackNestedContext?.({componentId:`${T.id||"unknown"}-iter-${X}`,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]:X}:{}}},depth:1});const we={...T,iteration:void 0,responsive:void 0},_e=R?`${R}.iteration.${X}`:`iteration.${X}`,Be=`${fn(T.id,"item")}-${X}`;return dt.jsx(Br,{componentDef:we,dataContext:ve,translationContext:r,registry:a,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:Re,parentFormContextProp:wn,isInsideIteration:!0,isEditMode:w,onComponentSelect:S,onComponentHover:v,componentPath:_e,onDragStart:A,onDragEnd:x,layoutKey:M},Be)})}catch(V){return rt.error(`iteration 렌더링 실패 (컴포넌트: ${T.id}):`,V),null}},[T.iteration,T.children,T.id,e,ae,r,a,i,l,c,Re,wn,fn,w,S,v,R,A,x,M]),[Ut,bt]=N.useState(0),ra=N.useMemo(()=>{if(!T.sortable||!T.itemTemplate)return null;const{sortable:V,itemTemplate:oe}=T;try{const ce=md(V.source,ae,i);if(!Array.isArray(ce))return rt.warn(`sortable source가 배열이 아닙니다 (컴포넌트: ${T.id}):`,ce),null;if(ce.length===0)return null;const X=V.itemKey||"id",ve=V.strategy||"verticalList",ue=V.itemVar||"$item",we=V.indexVar||"$index",_e=V.handle,Be=V.wrapperElement,xe=(et,Ne)=>{const je=T.actions?.filter(Se=>Se.event==="onSortEnd"||Se.type==="onSortEnd");if(bt(Se=>Se+1),je&&je.length>0&&c){const Se={...ae,$sortedItems:et,$sortEvent:Ne};je.forEach(Me=>{try{const Ze=c.createHandler(Me,Se,Re),kt=new Event("sortend");Ze(kt)}catch(Ze){rt.error(`onSortEnd action failed: ${Me.handler}`,Ze)}})}},De=et=>{const Ne=T.actions?.filter(je=>je.event==="onSortStart"||je.type==="onSortStart");if(Ne&&Ne.length>0&&c){const je={...ae,$activeId:et.activeId};Ne.forEach(Se=>{try{const Me=c.createHandler(Se,je,Re),Ze=new Event("sortstart");Me(Ze)}catch(Me){rt.error(`onSortStart action failed: ${Se.handler}`,Me)}})}},Ae=ce.map((et,Ne)=>{const je=String(et[X]),Se={...ae,[ue]:et,[we]:Ne},Me=R?`${R}.sortable.${Ne}`:`sortable.${Ne}`,Ze=`${fn(T.id,"sortable-item")}-v${Ut}-${je}`;return dt.jsx(r_,{id:je,handle:_e,...Be?{as:Be}:{},children:(Be&&oe.children?oe.children:[oe]).map((kt,Ot)=>dt.jsx(Br,{componentDef:kt,dataContext:Se,translationContext:r,registry:a,bindingEngine:i,translationEngine:l,actionDispatcher:c,parentComponentContext:Re,parentFormContextProp:void 0,isInsideIteration:!0,isEditMode:w,onComponentSelect:S,onComponentHover:v,componentPath:Me,onDragStart:A,onDragEnd:x,layoutKey:M},`${Ze}-child-${Ot}`))},Ze)});return dt.jsx(e_,{items:ce,itemKey:X,strategy:ve,onSortEnd:xe,onSortStart:De,sortVersion:Ut,children:Ae})}catch(ce){return rt.error(`sortable 렌더링 실패 (컴포넌트: ${T.id}):`,ce),null}},[T.sortable,T.itemTemplate,T.actions,T.id,e,ae,r,a,i,l,c,Re,fn,w,S,v,R,A,x,Ut,M]),Ln=N.useRef(!1);N.useEffect(()=>{if(Ln.current)return;Ln.current=!0;const V=ea();if(V?.isEnabled()&&V.trackMount(o.id,{name:o.name,type:o.type||"component",props:zt}),o.lifecycle?.onMount&&o.lifecycle.onMount.length>0)for(const ce of o.lifecycle.onMount)try{const X=c.createHandler(ce,ae,Re),ve=new Event("mount");X(ve),rt.log(`Lifecycle onMount executed: ${ce.handler} (Component: ${o.id})`)}catch(X){rt.error(`Lifecycle onMount failed: ${ce.handler} (Component: ${o.id})`,X)}const oe=[];if(o.onComponentEvent&&o.onComponentEvent.length>0){const ce=window.G7Core;if(ce?.componentEvent?.on)for(const X of o.onComponentEvent){if(!X.event){rt.warn(`onComponentEvent: event name is required (Component: ${o.id})`);continue}const ve=async we=>{try{const _e={...ae,_eventData:we},xe=await c.createHandler({handler:X.handler,params:X.params,onSuccess:X.onSuccess,onError:X.onError},_e,Re)(new CustomEvent(X.event,{detail:we}));return rt.log(`onComponentEvent "${X.event}" handled: ${X.handler} (Component: ${o.id})`,{eventData:we,result:xe}),xe}catch(_e){throw rt.error(`onComponentEvent "${X.event}" failed: ${X.handler} (Component: ${o.id})`,_e),_e}},ue=ce.componentEvent.on(X.event,ve);oe.push(ue),rt.log(`onComponentEvent: Subscribed to "${X.event}" (Component: ${o.id})`)}else rt.warn(`onComponentEvent: G7Core.componentEvent is not available (Component: ${o.id})`)}return()=>{const ce=ea();ce?.isEnabled()&&ce.trackUnmount(o.id);for(const X of oe)try{X()}catch(ve){rt.error(`onComponentEvent: Failed to unsubscribe (Component: ${o.id})`,ve)}if(oe.length>0&&rt.log(`onComponentEvent: Unsubscribed ${oe.length} event(s) (Component: ${o.id})`),o.lifecycle?.onUnmount&&o.lifecycle.onUnmount.length>0)for(const X of o.lifecycle.onUnmount)try{const ve=c.createHandler(X,ae,Re),ue=new Event("unmount");ve(ue),rt.log(`Lifecycle onUnmount executed: ${X.handler} (Component: ${o.id})`)}catch(ve){rt.error(`Lifecycle onUnmount failed: ${X.handler} (Component: ${o.id})`,ve)}}},[]);const An=N.useMemo(()=>{const V=zt.dataKey,oe=zt.trackChanges,ce=zt.debounce;return V?{dataKey:V,trackChanges:oe??!1,debounce:ce,setState:me,state:de}:null},[zt.dataKey,zt.trackChanges,zt.debounce,me,de]);N.useEffect(()=>{const V=T.dataKey||zt.dataKey;if(!V)return;const oe=ea();if(!oe?.isEnabled())return;const ce=[],X=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&&X(we.children),we?.slots)for(const Be of Object.values(we.slots))Array.isArray(Be)&&X(Be)}};if(o.children&&X(o.children),o.slots)for(const ue of Object.values(o.slots))Array.isArray(ue)&&X(ue);const ve=o.id||`form-${V}`;return oe.trackForm(ve,V,ce),()=>{oe.untrackForm(ve)}},[T,zt.dataKey,o.id,o.children]);const xn=N.useRef(null),Mn=N.useRef(void 0);N.useEffect(()=>{const V=zt?.name;if(!V||!Z.dataKey||!Z.setState||zt?.autoBinding===!1)return;const oe=`${Z.dataKey}.${V}`,ce=window.__g7AutoBindingPaths??new Map;return window.__g7AutoBindingPaths=ce,ce.set(oe,(ce.get(oe)??0)+1),()=>{const X=ce.get(oe)??0;X<=1?ce.delete(oe):ce.set(oe,X-1)}},[zt?.name,zt?.autoBinding,Z.dataKey,Z.setState]);const hn=N.useMemo(()=>{const{dataKey:V,trackChanges:oe,debounce:ce,...X}=zt,ve=X.name;if(!ve||!Z.dataKey||!Z.setState)return X;if(X.autoBinding===!1){const{autoBinding:je,...Se}=X;return Se}const ue=`${Z.dataKey}.${ve}`,we=tC(Z.state,ue),_e=we!==void 0?we:X.value,xe=a.getMetadata(o.name)?.bindingType,De=typeof _e=="boolean"&&(xe==="checked"||xe==="checkable"&&["checkbox","radio"].includes(X?.type)),Ae=Z.debounce,et=je=>{const Se=Z.state||{},Me=nC(Se,ue,je);if(Z.trackChanges&&(Me.hasChanges=!0),window.__g7PendingLocalState=Me,Z.setState(Me),Z._isGlobal)return;const Ze=window.G7Core,kt={[ue]:je};Z.trackChanges&&(kt.hasChanges=!0),Ze?.state?.setLocal?.(kt,{render:!1})},Ne=(je,Se)=>{Ae&&Ae>0?(xn.current&&clearTimeout(xn.current),xn.current=setTimeout(()=>{et(je),xn.current=null,Se&&(Se(),window.__g7PendingLocalState=null)},Ae)):(et(je),Se&&(Se(),window.__g7PendingLocalState=null))};if(De)return{...X,checked:_e,onChange:Se=>{const Me=Se.target.checked;et(Me),X.onChange&&X.onChange(Se)}};{const je=Me=>{const Ze=Me?.target?.value!==void 0?Me.target.value:Me;Ae&&Ae>0&&(Mn.current=Ze);const kt=Me?.target?{target:{value:Ze,name:Me.target.name,type:Me.target.type,checked:Me.target.checked},currentTarget:Me.currentTarget?{value:Ze,name:Me.currentTarget.name}:void 0}:Me;Ne(Ze,()=>{X.onChange&&X.onChange(kt)})};let Se;return Mn.current!==void 0?xn.current!==null?Se=Mn.current:String(_e??"")===String(Mn.current)?(Mn.current=void 0,Se=_e??""):Se=Mn.current:Se=_e??"",{...X,value:Se,onChange:je}}},[zt,Z,Z.state,Z.debounce]),aa=N.useMemo(()=>{const V=ea();if(V?.isEnabled()&&V.trackRender(o.name),!ze)return T.iteration?Wn:null;if(T.sortable&&T.itemTemplate)return ra;if(T.iteration)return Wn;if(T.type==="extension_point"){const{layout:xe,columns:De,gap:Ae,className:et,...Ne}=T.props||{};let je=et||"";return xe==="grid"&&De?je=`${je} grid grid-cols-${De} gap-${Ae||4}`.trim():xe==="flex"&&(je=`${je} flex flex-col gap-${Ae||4}`.trim()),dt.jsx("div",{id:Tr,className:je||void 0,...Ne,children:sr})}const oe=a.getComponent(T.name);if(!oe)return rt.error(`컴포넌트를 찾을 수 없습니다: ${T.name} (ID: ${T.id})`,"componentDef:",JSON.stringify(T,null,2)),null;const ce=e._global?._remountKeys,X={...hn,id:hn.id??Tr,...ce&&Object.keys(ce).length>0&&{__remountTrigger:JSON.stringify(ce)}};if(H?.listeners&&H.handle&&hn["data-drag-handle"]!==void 0&&(Object.assign(X,H.listeners),X.style={...X.style,cursor:H.isDragging?"grabbing":"grab"}),w){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 et=T.__editorSlotName??T.slot;typeof et=="string"&&(Ae["data-editor-slot"]=et),v&&(Ae.onMouseMove=Ne=>{Ne.stopPropagation(),v(xe,Ne)},Ae.onMouseLeave=Ne=>{v(null,Ne)}),Object.assign(X,Ae),X.editorAttrs=Ae}const ve=T.type==="basic",ue=T.type==="layout",_e=ve||ue?(()=>{const xe={};for(const[De,Ae]of Object.entries(X))De.startsWith("__")||De==="editorAttrs"&&ve||(xe[De]=Ae);return xe})():X;let Be=dt.jsx(oe,{..._e,children:sr});if(wn&&(Be=dt.jsx(Z0,{value:wn,children:Be})),T.isolatedState){const xe=typeof T.isolatedState=="object"?T.isolatedState:{},De=e?._isolatedInit,Ae=De?{...xe,...De}:xe;Be=dt.jsx(lC,{initialState:Ae,scopeId:T.isolatedScopeId,children:Be})}return Be},[ze,T.iteration,T.sortable,T.itemTemplate,T.type,T.name,T.id,T.props,T.isolatedState,T.isolatedScopeId,a,hn,sr,Wn,ra,H,An,w,S,v,A,x,R,e._global?._remountKeys]),$n=N.useMemo(()=>{const V=T.blur_until_loaded;if(!V||e?._global?.__isPreview)return!1;if(typeof V=="string"){const X=Tt(V);if(X!==null)try{const ve={componentId:T.id,componentName:T.name,propName:"blur_until_loaded"};return!!i.evaluateExpression(X,ae,ve)}catch(ve){return rt.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(we=>e[we]===void 0);if(he)return!0;const X=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(ue=>!X.includes(ue)&&!ue.startsWith("_")).some(ue=>e[ue]===void 0)}if(he)return!0;const oe=["route","query","_global","_local","_dataSourceErrors"];return Object.keys(e).filter(X=>!oe.includes(X)&&!X.startsWith("_")).some(X=>e[X]===void 0)},[T.blur_until_loaded,T.id,he,e,ae,i,Tt]);if($n){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,ue)=>(ve[ue]=e[ue]===void 0?"UNDEFINED":"LOADED",ve),{}),X=Object.keys(e).filter(ve=>!ve.startsWith("_"));rt.log(`[BLUR APPLIED] Component: ${T.id}, data_sources status:`,ce,"Available keys:",X)}else rt.log(`[BLUR APPLIED] Component: ${T.id}, blur_until_loaded:`,V)}const Vt=N.useMemo(()=>{if(!T.blur_until_loaded)return{wrapperClasses:"",innerClasses:""};const V=Yt?.className||"";if(!V)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=V.split(/\s+/).filter(Boolean),X=[],ve=[];for(const ue of ce)oe.some(_e=>_e.test(ue))?X.push(ue):ve.push(ue);return{wrapperClasses:X.join(" "),innerClasses:ve.join(" ")}},[T.blur_until_loaded,Yt?.className]),Cn=window.__slotContextValue;return $e&&Cn?.isEnabled?null:dt.jsx(s_,{componentId:o.id,componentName:o.name,children:T.blur_until_loaded?dt.jsx("div",{className:[Vt.wrapperClasses,$n?"opacity-50 blur-sm transition-all duration-300 pointer-events-none":void 0].filter(Boolean).join(" ")||void 0,children:aa}):aa})});Br.displayName="DynamicRenderer",typeof window<"u"&&(window.__DynamicRenderer=Br);function o_(o){const e={};try{const a=new URL(o,typeof window<"u"?window.location.origin:"http://localhost").searchParams,i=new Set;for(const l of a.keys()){if(i.has(l))continue;i.add(l);const c=a.getAll(l);c.length>1||l.endsWith("[]")?e[l]=c:e[l]=c[0]}}catch{}return e}function l_(o){try{return new URL(o,typeof window<"u"?window.location.origin:"http://localhost").pathname}catch{return o.split("?")[0]}}const Ei=class Ei{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 Ei.instance||(Ei.instance=new Ei),Ei.instance}initialize(){if(this.config.enabled=this.checkDebugMode(),!this.config.enabled){console.log("[G7DevTools] 비활성화됨 (환경설정 > 고급 설정 > 디버그 모드를 켜세요)");return}console.log("[G7DevTools] 활성화됨"),this.setupGlobalErrorHandler()}checkDebugMode(){try{if(window.G7Config?.debug===!0)return!0;const a=window.G7Core?.state?.get?.();return a?.settings?.advanced?.debug_mode===!0||a?._global?.settings?.advanced?.debug_mode===!0}catch{return!1}}isEnabled(){return this.config.enabled}setupGlobalErrorHandler(){window.addEventListener("error",e=>{this.config.enabled&&this.logAction({id:this.generateId(),type:"globalError",startTime:Date.now(),status:"error",error:{name:"Error",message:e.message,stack:e.error?.stack}})}),window.addEventListener("unhandledrejection",e=>{this.config.enabled&&this.logAction({id:this.generateId(),type:"unhandledRejection",startTime:Date.now(),status:"error",error:{name:"UnhandledRejection",message:String(e.reason)}})})}captureStateSnapshot(e){if(!this.config.enabled)return;const r={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(r),this.stateHistory.length>this.config.maxHistorySize&&this.stateHistory.shift(),this.notifyStateWatchers(r)}getState(){try{const e=window.G7Core,r=e?.state?.get?.()||{},a={};if(e?._isolatedStates&&typeof e._isolatedStates=="object")for(const[i,l]of Object.entries(e._isolatedStates))a[i]=this.sanitizeObject(l);return{_global:r._global||r,_local:this.currentLocalState,_computed:this.currentComputedState,_isolated:Object.keys(a).length>0?a:void 0,$parent:this.currentParentContext}}catch{return{_global:{},_local:this.currentLocalState,_computed:this.currentComputedState}}}updateLocalState(e){this.config.enabled&&(this.currentLocalState=this.sanitizeObject(e))}updateComputedState(e){this.config.enabled&&(this.currentComputedState=this.sanitizeObject(e))}updateParentContext(e){this.config.enabled&&(this.currentParentContext=e?this.sanitizeObject(e):void 0)}getStateHistory(){return[...this.stateHistory]}getDualStorageMismatch(){const e=this.currentLocalState||{};let r={};try{r=(window.G7Core?.state?.get?.()||{})._local||{}}catch{r={}}const a=this.findMismatchedLeafPaths(e,r);return{hasMismatch:a.length>0,mismatchedPaths:a,storageA:e,storageB:r}}findMismatchedLeafPaths(e,r,a=""){const i=[],l=new Set([...Object.keys(e||{}),...Object.keys(r||{})]);for(const c of l){const d=a?`${a}.${c}`:c,f=e?.[c],g=r?.[c],m=f&&typeof f=="object"&&!Array.isArray(f),y=g&&typeof g=="object"&&!Array.isArray(g);if(m&&y)i.push(...this.findMismatchedLeafPaths(f,g,d));else{const w=f===void 0?"__undefined__":JSON.stringify(f),S=g===void 0?"__undefined__":JSON.stringify(g);w!==S&&i.push(d)}}return i}watchState(e,r){return this.stateWatchers.has(e)||this.stateWatchers.set(e,new Set),this.stateWatchers.get(e).add(r),()=>{this.stateWatchers.get(e)?.delete(r)}}notifyStateWatchers(e){if(this.stateWatchers.get("*")?.forEach(r=>{try{r(e.next,e.prev,"*")}catch(a){console.error("[G7DevTools] State watcher error:",a)}}),e.diff)for(const r of e.diff.changed)this.stateWatchers.get(r.path)?.forEach(a=>{try{a(r.newValue,r.oldValue,r.path)}catch(i){console.error("[G7DevTools] State watcher error:",i)}})}diffSnapshots(e,r){const a=this.stateHistory.find(l=>l.id===e),i=this.stateHistory.find(l=>l.id===r);return!a||!i?null:this.calculateDiff(a.next,i.next)}calculateDiff(e,r,a=""){const i={added:[],removed:[],changed:[]},l=new Set(Object.keys(e)),c=new Set(Object.keys(r));for(const d of c){const f=a?`${a}.${d}`:d;l.has(d)?JSON.stringify(e[d])!==JSON.stringify(r[d])&&i.changed.push({path:f,oldValue:e[d],newValue:r[d]}):i.added.push(f)}for(const d of l){const f=a?`${a}.${d}`:d;c.has(d)||i.removed.push(f)}return i}logAction(e){if(!this.config.enabled)return;const r=this.actionHistory.findIndex(a=>a.id===e.id);r>=0?this.actionHistory[r]={...this.actionHistory[r],...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(r=>{try{r(e)}catch(a){console.error("[G7DevTools] Action watcher error:",a)}})}getActionMetrics(){const e=this.actionHistory.filter(l=>l.status==="success"),r=this.actionHistory.filter(l=>l.status==="error"),a={};for(const l of this.actionHistory)a[l.type]=(a[l.type]||0)+1;const i=e.reduce((l,c)=>l+(c.duration||0),0);return{totalActions:this.actionHistory.length,successCount:e.length,errorCount:r.length,averageDuration:e.length>0?i/e.length:0,actionsByType:a}}recordCacheHit(){this.config.enabled&&this.cacheStats.hits++}recordCacheMiss(){this.config.enabled&&this.cacheStats.misses++}updateCacheEntries(e){this.config.enabled&&(this.cacheStats.entries=e)}getCacheStats(){const e=this.cacheStats.hits+this.cacheStats.misses;return{...this.cacheStats,hitRate:e>0?this.cacheStats.hits/e:0}}resetCacheStats(){this.cacheStats={hits:0,misses:0,entries:0}}trackCacheDecision(e){if(!this.config.enabled)return;const r={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(r),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 r=0,a=0,i=0,l=0;const c={},d={};for(const g of e)g.decision==="cache_hit"?r++:g.decision==="cache_miss"?a++:g.decision==="skip_cache"?i++:g.decision==="invalidate"&&l++,c[g.reason]=(c[g.reason]||0)+1,g.context.componentId&&(d[g.context.componentId]=(d[g.context.componentId]||0)+1);const f=r+a+i;return{totalDecisions:e.length,cacheHits:r,cacheMisses:a,skipCacheCount:i,invalidateCount:l,byReason:c,byComponent:d,avgHitRate:f>0?r/f:0}}getRecentCacheDecisions(e=20,r){let a=[...this.cacheDecisions];return r&&(a=a.filter(i=>i.decision===r)),a.slice(-e)}clearCacheDecisionData(){this.cacheDecisions=[],this.cacheDecisionIdCounter=0}summarizePropsForLifecycle(e){if(!e||typeof e!="object")return e;const r={},a=["children","ref","key"];for(const[i,l]of Object.entries(e))if(!a.includes(i))if(l==null)r[i]=l;else if(Array.isArray(l))r[i]=`[Array(${l.length})]`;else if(typeof l=="object"){const c=Object.keys(l);c.length<=3?r[i]=`{${c.join(", ")}}`:r[i]=`{${c.slice(0,3).join(", ")}, ... +${c.length-3}}`}else typeof l=="string"&&l.length>50?r[i]=l.substring(0,50)+"...":typeof l=="function"?r[i]="[Function]":r[i]=l;return r}trackMount(e,r){if(!this.config.enabled)return;const a=this.summarizePropsForLifecycle(r.props),i={...r,props:a,id:e,mountTime:Date.now()};this.mountedComponents.set(e,i),this.mountWatchers.forEach(l=>{try{l({componentId:e,componentName:r.name,timestamp:i.mountTime})}catch(c){console.error("[G7DevTools] Mount watcher error:",c)}})}trackUnmount(e){if(!this.config.enabled)return;const r=this.mountedComponents.get(e),a=this.eventListeners.get(e)||[];a.length>0&&console.warn(`[G7DevTools] 컴포넌트 ${e} 언마운트 시 ${a.length}개 리스너 미정리`),r&&this.unmountWatchers.forEach(i=>{try{i({componentId:e,componentName:r.name,timestamp:Date.now(),orphanedListeners:a.length})}catch(l){console.error("[G7DevTools] Unmount watcher error:",l)}}),this.mountedComponents.delete(e)}trackListener(e,r,a){if(!this.config.enabled)return;const i=this.eventListeners.get(e)||[];i.push({type:r,target:a,addedAt:Date.now()}),this.eventListeners.set(e,i)}removeListener(e,r){if(!this.config.enabled)return;const a=this.eventListeners.get(e)||[],i=a.findIndex(l=>l.type===r);i>=0&&a.splice(i,1)}getMountedComponents(){return Array.from(this.mountedComponents.values())}getOrphanedListeners(){const e=[];for(const[r,a]of this.eventListeners)this.mountedComponents.has(r)||e.push(...a.map(i=>({...i,componentId:r})));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 r=this.renderCounts.get(e)||0;this.renderCounts.set(e,r+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 r=this.getOrphanedListeners().length;r>0&&e.push({type:"orphaned-listeners",message:`${r}개의 정리되지 않은 이벤트 리스너`,suggestion:"useEffect cleanup 또는 removeEventListener 확인",severity:r>10?"error":"warning"});const a=Array.from(this.renderCounts.entries()).filter(([,i])=>i>50);return a.length>0&&e.push({type:"excessive-renders",message:`${a.length}개 컴포넌트가 50회 이상 렌더링`,suggestion:"React.memo, useMemo, useCallback 사용 고려",severity:"warning"}),e}startProfiling(){this.config.enabled&&(this.isProfiling=!0,this.profilingData=[],this.profilingStartTime=performance.now(),console.log("[G7DevTools] 프로파일링 시작"))}stopProfiling(){this.isProfiling=!1;const e=performance.now()-this.profilingStartTime,r=this.analyzeProfile(e);return console.log("[G7DevTools] 프로파일링 완료",r),r}analyzeProfile(e){const r=this.profilingData.filter(g=>g.type==="render"),a=this.profilingData.filter(g=>g.type==="binding"),i=this.profilingData.filter(g=>g.type==="action"),l={};for(const g of r)g.component&&(l[g.component]||(l[g.component]={count:0,durations:[]}),l[g.component].count++,g.duration&&l[g.component].durations.push(g.duration));const c=Object.entries(l).map(([g,m])=>({name:g,renderCount:m.count,avgDuration:m.durations.length>0?m.durations.reduce((y,w)=>y+w,0)/m.durations.length:0})).sort((g,m)=>m.renderCount-g.renderCount).slice(0,10),d={};for(const g of a)g.expression&&(d[g.expression]=(d[g.expression]||0)+1);const f=Object.entries(d).sort(([,g],[,m])=>m-g).slice(0,10).map(([g])=>g);return{duration:e,entries:this.profilingData,summary:{totalRenders:r.length,totalBindings:a.length,totalActions:i.length,slowestComponents:c,hotPaths:f}}}resetPerformanceStats(){this.renderCounts.clear(),this.bindingEvalCount=0,this.profilingData=[]}trackRequest(e,r,a){if(!this.config.enabled)return"";const i=this.generateId(),l=l_(e),c=o_(e);return this.activeRequests.set(i,{id:i,url:l,fullUrl:e,queryParams:c,method:r,startTime:Date.now(),status:"pending",requestBody:a?.requestBody?this.sanitizeObject(a.requestBody):void 0,dataSourceId:a?.dataSourceId}),this.isProfiling&&this.profilingData.push({type:"network",timestamp:performance.now()}),i}completeRequest(e,r,a){if(!this.config.enabled)return;const i=this.activeRequests.get(e);if(!i)return;const l={...i,status:r>=200&&r<300?"success":"error",statusCode:r,duration:Date.now()-i.startTime,endTime:Date.now(),response:this.sanitizeObject(a)};this.requestHistory.push(l),this.activeRequests.delete(e),this.requestHistory.length>this.config.maxHistorySize&&this.requestHistory.shift(),this.notifyRequestWatchers(l)}failRequest(e,r){if(!this.config.enabled)return;const a=this.activeRequests.get(e);if(!a)return;const i={...a,status:"error",error:r,duration:Date.now()-a.startTime,endTime:Date.now()};this.requestHistory.push(i),this.activeRequests.delete(e),this.notifyRequestWatchers(i)}trackDataSource(e){this.config.enabled&&this.pendingDataSources.add(e)}completeDataSource(e){this.config.enabled&&this.pendingDataSources.delete(e)}getActiveRequests(){return Array.from(this.activeRequests.values())}getRequestHistory(){return[...this.requestHistory]}getPendingDataSources(){return Array.from(this.pendingDataSources)}watchRequest(e){return this.requestWatchers.add(e),()=>{this.requestWatchers.delete(e)}}notifyRequestWatchers(e){this.requestWatchers.forEach(r=>{try{r(e)}catch(a){console.error("[G7DevTools] Request watcher error:",a)}})}trackWebSocketConnection(e,r,a){this.config.enabled&&this.wsConnections.set(e,{id:e,url:r,state:a,connectedAt:a==="open"?Date.now():void 0})}trackWebSocketMessage(e,r,a,i){if(!this.config.enabled)return;const l={id:this.generateId(),connectionId:e,direction:r,type:a,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(r=>r.state==="open")?"connected":e.some(r=>r.state==="connecting")?"reconnecting":"disconnected"}watchWebSocketMessage(e){return this.wsMessageWatchers.add(e),()=>{this.wsMessageWatchers.delete(e)}}notifyWebSocketWatchers(e){this.wsMessageWatchers.forEach(r=>{try{r(e)}catch(a){console.error("[G7DevTools] WebSocket watcher error:",a)}})}trackIfCondition(e,r,a){if(!this.config.enabled)return;const i=this.ifConditions.get(e),l=i?.evaluatedValue;this.ifConditions.set(e,{id:e,expression:r,evaluatedValue:a,evaluationCount:(i?.evaluationCount||0)+1,lastEvaluated:Date.now()}),i&&l!==a&&this.notifyConditionWatchers({id:e,expression:r,oldValue:l,newValue:a,timestamp:Date.now()})}trackIteration(e,r){this.config.enabled&&this.iterations.set(e,{id:e,...r,lastRendered:Date.now()})}getIfConditions(){return Array.from(this.ifConditions.values())}getIterations(){return Array.from(this.iterations.values())}getScopeChain(e){const r=[],a=this.getState();return r.push({name:"_global",value:a._global,source:"global"}),r.push({name:"_local",value:a._local,source:"local"}),r.push({name:"_computed",value:a._computed,source:"computed"}),r}watchConditionChange(e){return this.conditionWatchers.add(e),()=>{this.conditionWatchers.delete(e)}}notifyConditionWatchers(e){this.conditionWatchers.forEach(r=>{try{r(e)}catch(a){console.error("[G7DevTools] Condition watcher error:",a)}})}trackForm(e,r,a){this.config.enabled&&this.forms.set(e,{id:e,dataKey:r,inputs:a,trackedAt:Date.now()})}trackFormChange(e,r,a){if(!this.config.enabled)return;const i={formId:e,inputName:r,value:a,timestamp:Date.now()};this.notifyFormWatchers(i)}untrackForm(e){this.forms.delete(e)}getForms(){return Array.from(this.forms.values())}getFormState(e){const r=this.getState();return this.getNestedValue(r,e)||{}}getBindingPath(e,r){return`${e}.${r}`}watchFormChange(e){return this.formWatchers.add(e),()=>{this.formWatchers.delete(e)}}notifyFormWatchers(e){this.formWatchers.forEach(r=>{try{r(e)}catch(a){console.error("[G7DevTools] Form watcher error:",a)}})}trackFormBindingIssue(e,r,a){if(!this.config.enabled)return;const i={id:`form-issue-${++this.formBindingIssueIdCounter}`,timestamp:Date.now(),type:e,severity:r,formId:a.formId,formDataKey:a.formDataKey,inputInfo:a.inputInfo,contextInfo:a.contextInfo,description:a.description,suggestion:a.suggestion,docLink:a.docLink};this.formBindingIssues.push(i),this.formBindingIssues.length>this.maxFormBindingIssues&&this.formBindingIssues.shift()}validateFormBinding(e,r,a,i){const l=a.map(f=>{const g=[];let m=!0;return f.name||(g.push("Input에 name 속성이 없습니다"),m=!1,this.trackFormBindingIssue("missing-input-name","error",{formId:e,formDataKey:r,inputInfo:{name:f.name,type:f.type},description:"Input에 name 속성이 없어 자동 바인딩이 동작하지 않습니다",suggestion:"Input에 name 속성을 추가하세요",docLink:"troubleshooting-components-form.md"})),r||(g.push("Form에 dataKey가 없습니다"),m=!1),{inputName:f.name||"(unnamed)",inputType:f.type,bindingPath:r&&f.name?`${r}.${f.name}`:"-",isValid:m,currentValue:f.value,issues:g}});if(r||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:r,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:r,timestamp:Date.now(),contextPropagation:i,inputBindings:l,isValid:l.every(f=>f.isValid)&&!!r&&!i.isContextBroken,issueCount:l.filter(f=>!f.isValid).length+(r?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},r={info:0,warning:0,error:0};for(const i of this.formBindingIssues)e[i.type]++,r[i.severity]++;const a=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:r,topIssues:a}}getIssueTypeDescription(e){return{"missing-datakey":"Form에 dataKey 누락","missing-input-name":"Input에 name 속성 누락","context-not-propagated":"Form 컨텍스트 전파 실패","sortable-context-break":"Sortable 컨테이너에서 컨텍스트 단절","modal-context-isolation":"모달에서 부모 Form 컨텍스트 격리","duplicate-input-name":"동일 Form 내 중복 Input name","value-type-mismatch":"값 타입과 Input 타입 불일치","binding-path-invalid":"바인딩 경로 유효하지 않음"}[e]||e}clearFormBindingIssues(){this.formBindingIssues=[],this.formBindingValidations=[],this.formBindingIssueIdCounter=0}trackComputedProperty(e,r,a,i,l,c,d){if(!this.config.enabled)return;const f=`computed-${e}-${c||"global"}`,g={id:f,name:e,expression:r,componentId:c,dependencies:a,currentValue:this.safeClone(i),lastComputedAt:Date.now(),computationTime:l,error:d};this.computedProperties.set(f,g)}trackComputedRecalc(e,r,a,i,l,c,d){if(!this.config.enabled)return;const f=`computed-${e}-${d||"global"}`,g=JSON.stringify(a)!==JSON.stringify(i),m={id:`recalc-${++this.computedRecalcIdCounter}`,computedId:f,computedName:e,timestamp:Date.now(),trigger:r,triggeredBy:c,previousValue:this.safeClone(a),newValue:this.safeClone(i),valueChanged:g,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,r){const a=new Set,i=[];let l=!1,c,d=0;const f=(m,y)=>{if(d=Math.max(d,y),a.has(m))return l=!0,c=[...i,m],{name:m,type:"computed",children:[],depth:y};a.add(m),i.push(m);const w=this.computedProperties.get(`computed-${m}-${r||"global"}`),S=[];if(w)for(const v of w.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(),a.delete(m),{name:m,type:"computed",children:S,depth:y}},g=f(e,0);return{root:e,tree:g,hasCycle:l,cyclePath:c,maxDepth:d}}getComputedDependencyTrackingInfo(){const e=Array.from(this.computedProperties.values()),r=this.getComputedDependencyStats(),a=[];for(const i of e){const l=this.analyzeComputedDependencyChain(i.name,i.componentId);a.push(l)}return{properties:e,recalcLogs:[...this.computedRecalcLogs],dependencyChains:a,stats:r,timestamp:Date.now()}}getComputedDependencyStats(){const e={"state-change":0,"datasource-update":0,"dependency-change":0,manual:0,initial:0},r={},a={};let i=0,l=0;for(const g of this.computedRecalcLogs)e[g.trigger]++,g.valueChanged||l++,r[g.computedName]=(r[g.computedName]||0)+1,a[g.computedName]||(a[g.computedName]=[]),a[g.computedName].push(g.computationTime),i+=g.computationTime;const c=Object.entries(r).sort((g,m)=>m[1]-g[1]).slice(0,5).map(([g,m])=>({name:g,count:m})),d=Object.entries(a).map(([g,m])=>({name:g,avgTime:m.reduce((y,w)=>y+w,0)/m.length})).sort((g,m)=>m.avgTime-g.avgTime).slice(0,5);let f=0;for(const g of this.computedProperties.values())this.analyzeComputedDependencyChain(g.name,g.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 r={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,r),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,r){if(!this.config.enabled)return;const a=this.modalStates.get(e);a&&(a.closedAt=Date.now(),r&&(a.currentState={...r}),this.detectStateLeakage(a))}validateModalDefinitionExists(e,r){const a=this.currentLayout;if(!a?.layoutJson)return;const i=a.layoutJson.modals;if(!i){this.recordModalStateIssue({type:"missing-definition",modalId:e,modalName:r,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 현재 레이아웃에 modals 섹션이 없습니다. 레이아웃 경로: ${a.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:r,severity:"error",description:`모달 "${e}"이(가) modalStack에 추가되었으나, 렌더링된 레이아웃의 modals 섹션에 해당 ID의 정의가 없습니다. partial 로딩 실패, 레이아웃 병합 문제, extends 상속 누락 등을 확인하세요. 레이아웃 경로: ${a.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 r=this.modalStates.get(e.modalId);if(!r)return;r.stateChangeCount++,r.currentState[e.stateKey]=e.newValue;const a=this.checkIsolationViolation(r,e.stateKey),i={id:`modal-change-${++this.modalStateChangeLogIdCounter}`,modalId:e.modalId,modalName:r.modalName,timestamp:Date.now(),stateKey:e.stateKey,previousValue:e.previousValue,newValue:e.newValue,changeSource:e.changeSource||"user-action",violatesIsolation:a};this.modalStateChangeLogs.push(i),this.modalStateChangeLogs.length>this.maxModalStateChangeLogs&&this.modalStateChangeLogs.shift(),a&&this.recordModalStateIssue({type:"isolation-violation",modalId:e.modalId,modalName:r.modalName,severity:"warning",description:`모달 '${r.modalName}'에서 격리된 상태 키 '${e.stateKey}'가 변경됨`,affectedStateKeys:[e.stateKey]})}detectStateLeakage(e){if(e.scopeType==="isolated")for(const r of e.isolatedStateKeys){const a=e.initialState[r],i=e.currentState[r];if(a!==i&&e.parentModalId){const l=this.modalStates.get(e.parentModalId);l&&l.currentState.hasOwnProperty(r)&&this.recordModalStateIssue({type:"state-leakage",modalId:e.modalId,modalName:e.modalName,severity:"error",description:`모달 닫힘 후 상태 '${r}'가 부모 모달로 유출될 수 있음`,affectedStateKeys:[r],leakedValue:i,expectedValue:a})}}}checkIsolationViolation(e,r){return e.scopeType==="isolated",!1}recordModalStateIssue(e){const r={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(r),this.modalStateIssues.length>this.maxModalStateIssues&&this.modalStateIssues.shift()}getModalStateScopeTrackingInfo(){const e=Array.from(this.modalStates.values()),r=this.getModalStateScopeStats();return{modals:e,issues:[...this.modalStateIssues],relations:[...this.modalStateRelations],changeLogs:[...this.modalStateChangeLogs],stats:r,timestamp:Date.now()}}getModalStateScopeStats(){const e=Array.from(this.modalStates.values()),r={warning:0,error:0},a={"state-leakage":0,"isolation-violation":0,"parent-mutation":0,"orphaned-state":0,"scope-mismatch":0,"cleanup-failure":0,"missing-definition":0};for(const l of this.modalStateIssues)r[l.severity]++,a[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:r,issuesByType:a,byScope:i,leakageDetectionCount:a["state-leakage"],cleanupFailureCount:a["cleanup-failure"]}}clearModalStateScopeTracking(){this.modalStates.clear(),this.modalStateIssues=[],this.modalStateRelations=[],this.modalStateChangeLogs=[],this.modalStateIssueIdCounter=0,this.modalStateChangeLogIdCounter=0}setNamedActionDefinitions(e){this.config.enabled&&(this.namedActionDefinitions=e||{})}trackNamedActionRef(e){if(!this.config.enabled)return;const r={...e,id:`named_action_ref_${++this.namedActionRefIdCounter}`};this.namedActionRefLogs.push(r),this.namedActionRefLogs.length>this.maxNamedActionRefLogs&&(this.namedActionRefLogs=this.namedActionRefLogs.slice(-this.maxNamedActionRefLogs))}getNamedActionTrackingInfo(){const e={};for(const a of this.namedActionRefLogs)e[a.actionRefName]=(e[a.actionRefName]||0)+1;const r=Object.keys(this.namedActionDefinitions).filter(a=>!e[a]);return{definitions:this.namedActionDefinitions,refLogs:[...this.namedActionRefLogs],stats:{totalDefinitions:Object.keys(this.namedActionDefinitions).length,totalRefs:this.namedActionRefLogs.length,refCountByName:e,unusedDefinitions:r},timestamp:Date.now()}}clearNamedActionTracking(){this.namedActionDefinitions={},this.namedActionRefLogs=[],this.namedActionRefIdCounter=0}trackExpressionEval(e){if(!this.config.enabled)return;const r={...e,id:`expr-${++this.expressionIdCounter}`,timestamp:Date.now(),warning:this.detectExpressionWarning(e)};this.expressionHistory.push(r),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(r)}detectExpressionWarning(e){const{expression:r,result:a,resultType:i,method:l,duration:c}=e;if(i==="undefined"&&!r.includes("??")&&!r.includes("||")&&/^[a-zA-Z_$][a-zA-Z0-9_$.]*$/.test(r.replace(/{{|}}/g,"").trim()))return{type:"undefined-result",message:"표현식 결과가 undefined입니다",suggestion:`데이터가 로드되었는지 확인하거나 fallback 값을 추가하세요: ${r} ?? ''`};if(i==="null")return{type:"null-result",message:"표현식 결과가 null입니다",suggestion:`nullish coalescing 연산자를 사용하세요: ${r} ?? ''`};if(l==="resolveBindings"&&i==="string"){const d=String(a);if(d.includes("[object Object]")||/^\[.*\]$/.test(d))return{type:"array-to-string",message:"배열/객체가 문자열로 변환되었습니다",suggestion:"evaluateExpression()을 사용하여 원본 타입을 유지하세요"}}if(l==="resolveBindings"&&i==="string"&&String(a).includes("[object Object]"))return{type:"object-to-string",message:"객체가 [object Object]로 변환되었습니다",suggestion:"evaluateExpression()을 사용하거나 특정 속성에 접근하세요"};if(i==="undefined"&&r.includes(".")&&!r.includes("?.")){const d=r.replace(/{{|}}/g,"").trim().split(".");if(d.length>=2)return{type:"missing-optional-chain",message:"Optional chaining(?.) 누락 가능성",suggestion:`안전한 접근을 위해 ?. 사용을 고려하세요: ${d.join("?.")}`}}if((r.includes("{{item.")||r.includes("{{index}}"))&&Array.from(this.iterations.values()).some(g=>g.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 r=e.toLowerCase();return this.expressionHistory.filter(a=>a.expression.toLowerCase().includes(r)||a.componentName?.toLowerCase().includes(r)||a.propName?.toLowerCase().includes(r))}getExpressionStats(){const e=this.expressionHistory,r=new Set(e.map(f=>f.expression)),a=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 a)f.warning&&(d[f.warning.type]=(d[f.warning.type]||0)+1);return{totalEvaluations:e.length,uniqueExpressions:r.size,warningCount:a.length,cacheHitRate:e.length>0?i.length/e.length:0,averageDuration:l.length>0?l.reduce((f,g)=>f+g,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(r=>{try{r(e)}catch(a){console.error("[G7DevTools] Expression watcher error:",a)}})}setLogLevel(e){this.config.logLevel=e}setMaxHistory(e){this.config.maxHistorySize=Math.max(10,Math.min(1e3,e))}setServerEndpoint(e){this.config.serverEndpoint=e}getConfig(){return{...this.config}}generateId(){return`${Date.now()}-${Math.random().toString(36).substr(2,9)}`}sanitizeObject(e,r=new WeakSet){if(e===null||typeof e!="object")return e;if(r.has(e))return"[Circular]";if(r.add(e),Array.isArray(e))return e.map(i=>this.sanitizeObject(i,r));const a={};for(const i of Object.keys(e))try{a[i]=this.sanitizeObject(e[i],r)}catch{a[i]="[Unable to serialize]"}return a}getNestedValue(e,r){if(!r)return e;const a=r.split(".");let i=e;for(const l of a){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 r=[...this.stateHistory].reverse().find(a=>a.timestamp<=e);if(r)return{_global:r.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,r,a){if(!this.config.enabled)return;const i=a.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:r,message:i,args:this.sanitizeObject(a),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 r={id:`debounce-action-${++this.debounceActionIdCounter}`,...e,timestamp:Date.now()};this.debounceActionHistory.push(r),this.debounceActionHistory.length>100&&this.debounceActionHistory.shift()}trackDataSourceUpdate(e){if(!this.config.enabled)return;const r={id:`ds-update-${++this.dataSourceUpdateIdCounter}`,...e};this.dataSourceUpdateHistory.push(r),this.dataSourceUpdateHistory.length>100&&this.dataSourceUpdateHistory.shift()}getDebounceActionHistory(e){let r=[...this.debounceActionHistory];return e?.handler&&(r=r.filter(a=>a.handler.includes(e.handler))),e?.status&&(r=r.filter(a=>a.status===e.status)),e?.limit&&(r=r.slice(-e.limit)),r}getDataSourceUpdateHistory(e){let r=[...this.dataSourceUpdateHistory];return e?.dataSourceId&&(r=r.filter(a=>a.dataSourceId===e.dataSourceId)),e?.updateType&&(r=r.filter(a=>a.updateType===e.updateType)),e?.limit&&(r=r.slice(-e.limit)),r}getLogs(e){let r=[...this.logHistory];if(e?.level){const a=Array.isArray(e.level)?e.level:[e.level];r=r.filter(i=>a.includes(i.level))}if(e?.prefix){const a=e.prefix.toLowerCase();r=r.filter(i=>i.prefix.toLowerCase().includes(a))}if(e?.search){const a=e.search.toLowerCase();r=r.filter(i=>i.message.toLowerCase().includes(a))}return e?.since&&(r=r.filter(a=>a.timestamp>=e.since)),e?.limit&&(r=r.slice(-e.limit)),r}getLogStats(){const r=Date.now()-6e4,a={log:0,warn:0,error:0,debug:0,info:0},i={};let l=0,c=0;for(const d of this.logHistory)a[d.level]++,i[d.prefix]=(i[d.prefix]||0)+1,d.timestamp>=r&&(d.level==="error"&&l++,d.level==="warn"&&c++);return{totalLogs:this.logHistory.length,byLevel:a,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 r=this.dataSources.get(e);r&&this.dataSources.set(e,{...r,status:"loading"})}trackDataSourceLoaded(e,r,a){if(!this.config.enabled)return;const i=this.dataSources.get(e);if(!i)return;let l,c,d=a;r&&(Array.isArray(r)?(l=r.length,c=r.length>0&&typeof r[0]=="object"?Object.keys(r[0]):void 0):typeof r=="object"&&(Array.isArray(r.data)?(d=d||"data",l=r.data.length,c=r.data.length>0&&typeof r.data[0]=="object"?Object.keys(r.data[0]):void 0):Array.isArray(r.items)?(d=d||"items",l=r.items.length,c=r.items.length>0&&typeof r.items[0]=="object"?Object.keys(r.items[0]):void 0):c=Object.keys(r))),this.dataSources.set(e,{...i,status:"loaded",dataPath:d,itemCount:l,keys:c,lastLoadedAt:Date.now(),error:void 0})}trackDataSourceError(e,r){if(!this.config.enabled)return;const a=this.dataSources.get(e);a&&this.dataSources.set(e,{...a,status:"error",error:r,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 r=this.dataPathTransforms.find(a=>a.dataSourceId===e.dataSourceId);r||(r={dataSourceId:e.dataSourceId,timestamp:Date.now(),transformSteps:[],warnings:[]},this.dataPathTransforms.push(r),this.dataPathTransforms.length>this.maxDataPathTransforms&&this.dataPathTransforms.shift()),r.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&&r.warnings.push(e.warning)}setDataPathFinalBinding(e,r){if(!this.config.enabled)return;const a=this.dataPathTransforms.find(i=>i.dataSourceId===e);a&&(a.finalBinding={expression:r.expression,resolvedPath:r.resolvedPath,value:this.safeClone(r.value)})}getDataPathTransformTrackingInfo(){const e=this.getDataPathTransformStats();return{transforms:[...this.dataPathTransforms],stats:e,timestamp:Date.now()}}getDataPathTransformStats(){const e=this.dataPathTransforms,r={};let a=0;const i={};for(const c of e){r[c.dataSourceId]=(r[c.dataSourceId]||0)+1,a+=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:r,warningsCount:a,commonWarnings:l}}getDataPathTransformForDataSource(e){return this.dataPathTransforms.find(r=>r.dataSourceId===e)}clearDataPathTransforms(){this.dataPathTransforms=[]}trackNestedContext(e){if(!this.config.enabled)return"";const r=`nested-${++this.nestedContextIdCounter}`,a=[...new Set([...e.parentContext.available,...e.ownContext.added])],i={...e.parentContext.values,...e.ownContext.values},l={id:r,timestamp:Date.now(),componentId:e.componentId,componentType:e.componentType,parentContext:{available:e.parentContext.available,values:this.safeClone(e.parentContext.values)},ownContext:{added:e.ownContext.added,values:this.safeClone(e.ownContext.values)},mergedContext:{all:a,values:this.safeClone(i)},accessAttempts:[],depth:e.depth,parentId:e.parentId};return this.nestedContexts.push(l),this.nestedContexts.length>this.maxNestedContexts&&this.nestedContexts.shift(),r}trackNestedContextAccess(e,r){if(!this.config.enabled)return;const a=this.nestedContexts.find(i=>i.id===e);a&&a.accessAttempts.push({path:r.path,found:r.found,value:r.found?this.safeClone(r.value):void 0,error:r.error})}getNestedContextTrackingInfo(){const e=this.getNestedContextStats();return{contexts:[...this.nestedContexts],stats:e,timestamp:Date.now()}}getNestedContextStats(){const e=this.nestedContexts,r={expandChildren:0,cellChildren:0,iteration:0,modal:0,slot:0};let a=0,i=0;const l={};for(const d of e){r[d.componentType]++,d.depth>a&&(a=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:r,maxDepth:a,failedAccessCount:i,commonFailedPaths:c}}getNestedContextForComponent(e){return this.nestedContexts.find(r=>r.componentId===e)}clearNestedContexts(){this.nestedContexts=[],this.nestedContextIdCounter=0}trackHandlerRegistration(e,r="custom",a,i){this.isEnabled&&this.handlers.set(e,{name:e,category:r,description:a,registeredAt:Date.now(),source:i})}trackHandlerUnregistration(e){this.isEnabled&&this.handlers.delete(e)}getHandlers(){return Array.from(this.handlers.values())}getHandler(e){return this.handlers.get(e)}getHandlersByCategory(e){return Array.from(this.handlers.values()).filter(r=>r.category===e)}clearHandlers(){this.handlers.clear()}trackEventSubscribe(e){if(!this.isEnabled)return;const r=this.componentEventSubscriptions.get(e),a=Date.now();r?(r.subscriberCount++,r.lastSubscribedAt=a):this.componentEventSubscriptions.set(e,{eventName:e,subscriberCount:1,firstSubscribedAt:a,lastSubscribedAt:a})}trackEventUnsubscribe(e){if(!this.isEnabled)return;const r=this.componentEventSubscriptions.get(e);r&&(r.subscriberCount--,r.subscriberCount<=0&&this.componentEventSubscriptions.delete(e))}trackEventEmit(e,r,a,i,l){if(!this.isEnabled)return;const c={id:`evt_${++this.componentEventIdCounter}`,eventName:e,data:this.sanitizeForLogging(r),timestamp:Date.now(),listenerCount:a,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((r,a)=>r+a.subscriberCount,0),totalEmits:this.componentEventEmitHistory.length}}getEventEmitHistory(){return[...this.componentEventEmitHistory]}getEventSubscriptions(){return Array.from(this.componentEventSubscriptions.values())}clearComponentEvents(){this.componentEventSubscriptions.clear(),this.componentEventEmitHistory=[],this.componentEventIdCounter=0}sanitizeForLogging(e){if(e==null||typeof e!="object")return e;try{return JSON.parse(JSON.stringify(e))}catch{return"[Circular or Non-serializable]"}}startStateChange(e,r,a,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(r),newValue:this.sanitizeForLogging(a),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,r,a,i=[],l=[],c){if(!this.config.enabled)return;const d=this.componentRenderCounts.get(r)||0;this.componentRenderCounts.set(r,d+1);for(const f of i)this.stateToComponentMap.has(f)||this.stateToComponentMap.set(f,new Set),this.stateToComponentMap.get(f).add(r);if(this.currentStateChangeContext){const f={componentId:e,componentName:r,renderDuration:a,accessedStatePaths:i,evaluatedBindings:l,renderOrder:this.currentStateChangeContext.renderedComponents.length,parentId:c};this.currentStateChangeContext.renderedComponents.push(f)}this.trackRender(r)}completeStateChange(e){if(!this.config.enabled||!this.currentStateChangeContext||this.currentStateChangeContext.setStateId!==e)return;const r=this.currentStateChangeContext,i=performance.now()-r.startTime,l=this.stateRenderingLogs.findIndex(c=>c.setStateId===e);if(l>=0){const c=this.stateRenderingLogs[l];c.renderedComponents=r.renderedComponents,c.totalRenderDuration=i,c.affectedBindingsCount=r.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,r=Object.fromEntries(this.componentRenderCounts),a={};for(const[i,l]of this.stateToComponentMap)a[i]=Array.from(l);return{logs:e,componentRenderCounts:r,stateToComponentMap:a,stats:this.calculateStateRenderingStats()}}calculateStateRenderingStats(){const e=this.stateRenderingLogs;if(e.length===0)return{totalStateChanges:0,totalRenders:0,avgRenderDuration:0,avgComponentsPerChange:0,topRenderedComponents:[],topInfluentialPaths:[]};const r=e.reduce((d,f)=>d+f.renderedComponents.length,0),a=e.reduce((d,f)=>d+f.totalRenderDuration,0)/e.length,i=r/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:r,avgRenderDuration:a,avgComponentsPerChange:i,topRenderedComponents:l,topInfluentialPaths:c}}getComponentsAffectedByState(e){const r=this.stateToComponentMap.get(e);return r?Array.from(r):[]}getComponentRenderHistory(e){return this.stateRenderingLogs.filter(r=>r.renderedComponents.some(a=>a.componentName===e))}clearStateRenderingLogs(){this.stateRenderingLogs=[],this.componentRenderCounts.clear(),this.stateToComponentMap.clear(),this.currentStateChangeContext=null,this.stateRenderingIdCounter=0}trackComponentStateSource(e,r,a,i){this.config.enabled&&this.componentStateSources.set(e,{componentId:e,componentName:r,stateSource:a,stateProvider:i})}trackDynamicState(e,r){this.config.enabled&&this.dynamicStates.set(e,r)}trackContextFlow(e,r,a,i,l,c){if(!this.config.enabled)return;const d={component:r,componentId:e,contextReceived:a,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 r=this.buildStateHierarchyLayers(),a=this.detectStateConflicts(r),i=Array.from(this.componentStateSources.values());return{layers:e?r.map(c=>({...c,values:this.summarizeValues(c.values,2)})):r,conflicts:a,componentStateSources:i,timestamp:Date.now()}}summarizeValues(e,r,a=0){if(e==null)return e;if(typeof e!="object")return typeof e=="string"&&e.length>100?e.substring(0,100)+`... (${e.length}자)`:e;if(a>=r){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,r,a+1)):{__type:"array",__length:e.length,__preview:e.slice(0,3).map(c=>this.summarizeValues(c,r,a+1))};const i={},l=Object.keys(e);for(const c of l)i[c]=this.summarizeValues(e[c],r,a+1);return i}buildStateHierarchyLayers(){const e=[];try{const a=window.G7Core?.state?.get?.();if(!a)return e;a._local&&e.push({name:"Global _local",type:"global",path:"_local",values:a._local,priority:1}),a._global&&e.push({name:"Global _global",type:"global",path:"_global",values:a._global,priority:1});for(const[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(a._local||{});e.push({name:"Effective _local (merged)",type:"effective",values:i,priority:3})}catch(r){console.warn("[G7DevTools] 상태 계층 빌드 실패:",r)}return e}computeEffectiveState(e){const r={...e};for(const[,a]of this.dynamicStates)a._local&&Object.assign(r,a._local);return r}detectStateConflicts(e){const r=[],a=e.find(l=>l.type==="global"&&l.path==="_local");if(!a)return r;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 g=a.values[d];if(JSON.stringify(g)!==JSON.stringify(f)){const m=[],y=[];for(const w of this.componentStateSources.values())w.stateSource.local.some(v=>v===`_local.${d}`||v===d)&&(w.stateProvider.type==="dynamicState"?m.push(w.componentName):w.stateProvider.type==="globalState"&&y.push(w.componentName));r.push({path:`_local.${d}`,globalValue:g,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 r}getContextFlowInfo(){const e=[],r=new Set(this.contextFlowNodes.keys());for(const a of this.contextFlowNodes.values())if(a.children)for(const i of a.children)r.delete(i.componentId);for(const a of r){const i=this.contextFlowNodes.get(a);i&&e.push(i)}return{rootComponent:e.length>0?e[0].component:"Unknown",contextFlow:e,timestamp:Date.now()}}clearStateHierarchyData(){this.componentStateSources.clear(),this.contextFlowNodes.clear(),this.dynamicStates.clear()}trackComponentStyle(e,r,a,i){if(!this.config.enabled)return;const l=this.analyzeTailwindClasses(a),c={componentId:e,componentName:r,classes:a,computedStyles:i,tailwindAnalysis:l};this.componentStyles.set(e,c),this.detectStyleIssues(c)}analyzeTailwindClasses(e){const r=[],a=[],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:")&&r.push(f);for(const g of c)if(f.startsWith(g)){a.push(f);break}for(const g of d)if(g.test(f)){i.push(f);break}}return{usedClasses:l,darkClasses:r,responsiveClasses:a,dynamicClasses:i}}detectStyleIssues(e){const{componentId:r,componentName:a,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:r,componentName:a,property:i.opacity==="0"?"opacity":i.visibility==="hidden"?"visibility":i.display==="none"?"display":"width/height",currentValue:i.opacity==="0"?"0":i.visibility==="hidden"?"hidden":i.display==="none"?"none":"0px",severity:"warning",description:"요소가 화면에 보이지 않습니다.",suggestion:"opacity, visibility, display, width/height 값을 확인하세요."});const 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:r,componentName:a,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:r,componentName:a,property:"class",currentValue:l.dynamicClasses.join(", "),severity:"info",description:"동적으로 생성된 Tailwind 클래스가 있습니다.",suggestion:"tailwind.config.js의 safelist에 추가하거나 전체 클래스명을 상수로 정의하세요."})}addStyleIssue(e){this.styleIssues.some(a=>a.componentId===e.componentId&&a.type===e.type&&a.property===e.property)||this.styleIssues.push(e)}getStyleValidationInfo(){const e=Array.from(this.componentStyles.values());return{issues:[...this.styleIssues],componentStyles:e,stats:{totalComponents:e.length,invisibleCount:this.styleIssues.filter(r=>r.type==="invisible-element").length,tailwindIssueCount:this.styleIssues.filter(r=>r.type==="tailwind-purging").length,darkModeIssueCount:this.styleIssues.filter(r=>r.type==="dark-mode-missing").length},timestamp:Date.now()}}clearStyleValidationData(){this.styleIssues=[],this.componentStyles.clear()}trackAuthEvent(e,r,a,i){if(!this.config.enabled)return;const l={id:`auth_${++this.authEventIdCounter}`,type:e,timestamp:Date.now(),success:r,error:a,details:i};this.authEvents.push(l),this.authEvents.length>this.maxAuthEventHistory&&(this.authEvents=this.authEvents.slice(-this.maxAuthEventHistory))}trackAuthHeader(e,r,a,i,l){if(!this.config.enabled)return;const c={url:e,hasAuthHeader:r,headerType:a,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,r=e?.api;let a=e?.auth;!a&&e?.AuthManager?.getInstance&&(a=e.AuthManager.getInstance());const i=r?.getToken?.()||a?.getAccessToken?.()||localStorage.getItem("auth_token")||localStorage.getItem("access_token"),l=a?.getRefreshToken?.()||localStorage.getItem("refresh_token");let c="unknown",d=a?.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=a?.isAuthenticated?.()??!1;let g="memory";localStorage.getItem("auth_token")||localStorage.getItem("access_token")?g="localStorage":(sessionStorage.getItem("auth_token")||sessionStorage.getItem("access_token"))&&(g="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 w=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:w,tokens:{hasAccessToken:!!i,hasRefreshToken:!!l,storage:g,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(r=>r.type==="login").length,successfulLogins:e.filter(r=>r.type==="login"&&r.success).length,failedLogins:e.filter(r=>r.type==="login"&&!r.success).length,tokenRefreshes:e.filter(r=>r.type==="token-refresh").length,unauthorizedResponses:e.filter(r=>r.type==="api-unauthorized").length},timestamp:Date.now()}}clearAuthData(){this.authEvents=[],this.authHeaderHistory=[],this.authEventIdCounter=0}trackLayoutLoad(e,r,a,i="api"){if(!this.config.enabled)return;const l=Date.now();this.currentLayout={layoutPath:e,templateId:r,layoutJson:this.sanitizeObject(a),loadedAt:l,version:a.version,layoutName:a.layout_name,source:i};const c={id:`layout-${++this.layoutIdCounter}`,layoutPath:e,templateId:r,loadedAt:l,source:i,version:a.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 r=`exec_${++this.executionIdCounter}_${Date.now()}`,a={handlerName:e,executionId:r,startTime:Date.now(),stateChanges:[],dataSourceChanges:[],alerts:[]};if(this.executionDetails.set(r,a),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 r}endHandlerExecution(e,r,a,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=r,l.exitLocation=a,l.exitDescription=i;const c=this.changeExpectations.get(e);c&&(l.expectedChanges=c,this.checkExpectations(e,l,c),this.changeExpectations.delete(e)),r==="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"}),(r==="early-return-condition"||r==="early-return-validation")&&this.addChangeAlert(e,{type:"early-return-detected",severity:"info",message:`핸들러 "${l.handlerName}"이(가) early return으로 종료됨`,description:i||`종료 위치: ${a||"알 수 없음"}`,handlerName:l.handlerName,suggestion:r==="early-return-validation"?"검증 실패로 인한 early return입니다. 입력 데이터를 확인하세요.":"조건부 early return입니다. 조건문의 평가 결과를 확인하세요."})}recordExitReason(e,r,a,i){if(!this.config.enabled||!e)return;const l=this.executionDetails.get(e);l&&(l.exitReason=r,l.exitLocation=a,l.exitDescription=i)}recordStateChange(e,r,a,i,l){if(!this.config.enabled)return;const c={id:`sc_${++this.stateChangeIdCounter}`,path:r,changeType:a,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:`상태 "${r}"가 변경되었으나 값이 동일함`,description:"객체 참조가 동일하거나 깊은 비교 결과 변경이 없습니다. 변경 감지가 실패할 수 있습니다.",handlerName:e&&this.executionDetails.get(e)?.handlerName||"unknown",statePath:r,suggestion:"불변성을 유지하여 새 객체를 생성하세요. 예: { ...oldObject, newField: value }",docLink:"troubleshooting-state.md#object-mutation"})}recordDataSourceChange(e,r,a,i,l){if(!this.config.enabled)return;const c={dataSourceId:r,changeType:a,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,r,a){if(!this.config.enabled||!e)return;const i=this.executionDetails.get(e);if(!i)return;const l={expectedStatePaths:r,expectedDataSources:a,setAt:Date.now(),source:i.handlerName};this.changeExpectations.set(e,l)}checkExpectations(e,r,a){const i=new Set(r.stateChanges.map(c=>c.path)),l=new Set(r.dataSourceChanges.map(c=>c.dataSourceId));for(const c of a.expectedStatePaths)i.has(c)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 상태 변경 "${c}"가 발생하지 않음`,description:`핸들러 "${r.handlerName}"이(가) "${c}" 변경을 예고했지만 실제로 변경되지 않았습니다.`,handlerName:r.handlerName,statePath:c,suggestion:"핸들러 내부 로직을 확인하세요. early return이나 조건부 분기로 인해 변경이 생략되었을 수 있습니다.",docLink:"troubleshooting-state.md"});for(const c of a.expectedDataSources)l.has(c)||this.addChangeAlert(e,{type:"expected-not-fulfilled",severity:"error",message:`기대한 데이터소스 갱신 "${c}"가 발생하지 않음`,description:`핸들러 "${r.handlerName}"이(가) "${c}" 갱신을 예고했지만 실제로 갱신되지 않았습니다.`,handlerName:r.handlerName,dataSourceId:c,suggestion:"refetchDataSource 호출이 실행되었는지 확인하세요.",docLink:"data-sources.md"})}addChangeAlert(e,r){const a={...r,id:`alert_${++this.alertIdCounter}`,timestamp:Date.now()};if(this.changeAlerts.push(a),e){const i=this.executionDetails.get(e);i&&i.alerts.push(a)}this.changeAlerts.length>this.maxChangeAlerts&&this.changeAlerts.splice(0,this.changeAlerts.length-this.maxChangeAlerts)}compareValues(e,r){const a=this.getValueType(e),i=this.getValueType(r),l=a!==i;let c=!1,d;return!l&&(a==="object"||a==="array")?(c=this.deepEqual(e,r),!c&&a==="object"&&(d=this.getChangedKeys(e,r))):c=e===r,{typeChanged:l,oldType:a,newType:i,isDeepEqual:c,changedKeys:d}}getValueType(e){return e===null?"null":e===void 0?"undefined":Array.isArray(e)?"array":typeof e}deepEqual(e,r){if(e===r)return!0;if(typeof e!=typeof r)return!1;if(e===null||r===null||typeof e!="object")return e===r;if(Array.isArray(e)!==Array.isArray(r))return!1;const a=Object.keys(e),i=Object.keys(r);if(a.length!==i.length)return!1;for(const l of a)if(!i.includes(l)||!this.deepEqual(e[l],r[l]))return!1;return!0}getChangedKeys(e,r){const a=[],i=new Set([...Object.keys(e),...Object.keys(r)]);for(const l of i)this.deepEqual(e[l],r[l])||a.push(l);return a}getChangeDetectionInfo(){const e=Array.from(this.executionDetails.values()),r={totalExecutions:e.length,executionsWithStateChange:e.filter(a=>a.stateChanges.length>0).length,executionsWithoutStateChange:e.filter(a=>a.stateChanges.length===0&&a.exitReason==="normal").length,earlyReturnCount:e.filter(a=>a.exitReason==="early-return-condition"||a.exitReason==="early-return-validation").length,alertCount:this.changeAlerts.length,alertsByType:this.getAlertsByType()};return{executionDetails:e,stateChangeHistory:[...this.stateChangeHistory],dataSourceChangeHistory:[...this.dataSourceChangeHistory],alerts:[...this.changeAlerts],stats:r,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 r of this.changeAlerts)e[r.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,r){let a=[...this.changeAlerts];return r&&(a=a.filter(i=>i.severity===r)),a.slice(-e)}getHandlerExecutions(e,r=10){return Array.from(this.executionDetails.values()).filter(i=>i.handlerName===e).slice(-r)}findExecutionInStack(e){return this.sequenceExecutionStack.find(r=>r.sequenceId===e)}startSequenceExecution(e){if(!this.config.enabled)return"";const r=`seq_${++this.sequenceIdCounter}_${Date.now()}`,a={sequenceId:r,startTime:Date.now(),totalDuration:0,trigger:e,actions:[],status:"running"};return this.sequenceExecutionStack.push(a),r}captureSequenceActionBefore(e,r,a,i,l){if(!this.config.enabled)return;const c=this.findExecutionInStack(e);if(!c)return;const d={index:r,handler:a,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,r,a,i,l,c){if(!this.config.enabled)return;const d=this.findExecutionInStack(e);if(!d)return;const f=d.actions.find(m=>m.index===r);if(!f)return;f.stateAfterAction={_global:this.safeClone(a._global),_local:this.safeClone(a._local),_isolated:a._isolated?this.safeClone(a._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 g=window.__g7PendingLocalState;g&&(f.pendingState=this.safeClone(g)),c&&(f.status="error",f.error={name:c.name,message:c.message,stack:c.stack})}endSequenceExecution(e,r){if(!this.config.enabled)return;const a=this.sequenceExecutionStack.findIndex(l=>l.sequenceId===e);if(a===-1)return;const i=this.sequenceExecutionStack[a];if(i.endTime=Date.now(),i.totalDuration=i.endTime-i.startTime,r){i.status="error",i.error={name:r.name,message:r.message,stack:r.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(a,1)}computeStateDiff(e,r){const a=[],i=[],l=[],c=new Set(Object.keys(e)),d=new Set(Object.keys(r));for(const f of d)c.has(f)||a.push(f);for(const f of c)d.has(f)||i.push(f);for(const f of c)if(d.has(f)){const g=e[f],m=r[f];JSON.stringify(g)!==JSON.stringify(m)&&l.push({path:f,oldValue:g,newValue:m})}return{added:a,removed:i,changed:l}}getSequenceTrackingInfo(){const e=this.getSequenceStats(),r=this.sequenceExecutionStack.length>0?this.sequenceExecutionStack[this.sequenceExecutionStack.length-1]:void 0;return{executions:[...this.sequenceExecutions],currentExecution:r,stats:e}}getSequenceStats(){const e=this.sequenceExecutions,r=e.length,a=e.filter(g=>g.status==="success").length,i=e.filter(g=>g.status==="error").length,l=e.reduce((g,m)=>g+m.actions.length,0),c=r>0?e.reduce((g,m)=>g+m.totalDuration,0)/r:0,d={};for(const g of e)for(const m of g.actions)d[m.handler]=(d[m.handler]||0)+1;const f=Object.entries(d).sort(([,g],[,m])=>m-g).slice(0,5).map(([g,m])=>({handler:g,count:m}));return{totalExecutions:r,successCount:a,errorCount:i,totalActions:l,avgDuration:c,topHandlers:f}}clearSequenceData(){this.sequenceExecutions=[],this.sequenceExecutionStack=[],this.sequenceIdCounter=0}getSequenceExecution(e){const r=this.findExecutionInStack(e);return r||this.sequenceExecutions.find(a=>a.sequenceId===e)}getRecentSequences(e=10){return this.sequenceExecutions.slice(-e)}registerStateCaptureForHandler(e,r,a){if(!this.config.enabled)return;const i=new Map,l=Date.now();for(const c of r)i.set(c,{value:this.safeClone(a[c]),capturedAt:l});this.stateCaptureRegistry.set(e,i)}detectStaleClosure(e,r,a,i,l){if(!this.config.enabled)return[];const c=this.stateCaptureRegistry.get(e);if(!c)return[];const d=Date.now(),f=[];for(const[g,m]of c){const y=this.getValueByPath(a,g),w=d-m.capturedAt;if(!this.isDeepEqual(m.value,y)&&w>0){const S=this.createStaleClosureWarning(i,r,g,m.value,m.capturedAt,y,d,w,l);f.push(S),this.addStaleClosureWarning(S)}}return this.stateCaptureRegistry.delete(e),f}trackStaleClosureWarning(e){if(!this.config.enabled)return;const r=Date.now(),a=this.createStaleClosureWarning(e.type,e.location,e.capturedPath,e.capturedValue,e.capturedAt,e.currentValue,r,r-e.capturedAt,e.actionId,e.stackTrace);this.addStaleClosureWarning(a)}createStaleClosureWarning(e,r,a,i,l,c,d,f,g,m){const y=this.getStaleClosureSeverity(e,f),{description:w,suggestion:S,docLink:v}=this.getStaleClosureMessages(e,a,f);return{id:`stale_${++this.staleClosureIdCounter}_${Date.now()}`,timestamp:Date.now(),type:e,location:r,capturedState:{path:a,capturedValue:this.safeClone(i),capturedAt:l},currentState:{path:a,currentValue:this.safeClone(c),retrievedAt:d},timeDiff:f,severity:y,description:w,suggestion:S,docLink:v,actionId:g,stackTrace:m}}getStaleClosureSeverity(e,r){if(r>5e3)return"error";if(r>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,r,a){const i=a<1e3?`${a}ms`:`${(a/1e3).toFixed(1)}s`;switch(e){case"async-state-capture":return{description:`await 후 ${i} 경과 시점에 '${r}' 상태가 변경됨. 캡처된 상태 대신 최신 상태를 사용해야 함`,suggestion:"await 이후에는 G7Core.state.get()으로 최신 상태를 다시 조회하거나, useRef + getter 패턴을 사용하세요",docLink:"troubleshooting-state-closure.md"};case"callback-state-capture":return{description:`콜백에서 ${i} 전에 캡처된 '${r}' 상태를 사용 중. 최신 상태와 다름`,suggestion:"콜백에서 상태를 참조할 때는 stateRef.current 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};case"timeout-state-capture":return{description:`setTimeout/setInterval 콜백에서 '${r}' 상태가 ${i} 전 값 사용 중`,suggestion:"타이머 콜백 내에서는 G7Core.state.get()으로 최신 상태를 조회하세요",docLink:"troubleshooting-state-closure.md"};case"sequence-state-mismatch":return{description:`sequence 내 '${r}' 상태가 이전 액션 결과와 불일치. context.state 대신 캡처된 값 사용 의심`,suggestion:"sequence 내에서는 context.state 또는 $prev를 사용하여 최신 상태를 참조하세요",docLink:"troubleshooting-state-setstate.md"};case"event-handler-stale":return{description:`이벤트 핸들러에서 ${i} 전에 바인딩된 '${r}' 상태 사용 중`,suggestion:"이벤트 핸들러에서 상태를 참조할 때는 useRef 패턴 또는 G7Core.state.get()를 사용하세요",docLink:"troubleshooting-state-closure.md"};default:return{description:`'${r}' 상태에서 stale closure 감지됨 (${i} 경과)`,suggestion:"상태 참조 시 최신 값을 사용하는지 확인하세요"}}}addStaleClosureWarning(e){this.staleClosureWarnings.push(e),this.staleClosureWarnings.length>this.maxStaleClosureWarnings&&this.staleClosureWarnings.shift()}getValueByPath(e,r){const a=r.split(".");let i=e;for(const l of a){if(i==null)return;i=i[l]}return i}isDeepEqual(e,r){if(e===r)return!0;if(e===null||r===null)return e===r;if(typeof e!=typeof r)return!1;if(typeof e!="object")return e===r;try{return JSON.stringify(e)===JSON.stringify(r)}catch{return!1}}getStaleClosureTrackingInfo(){const e=this.getStaleClosureStats();return{warnings:[...this.staleClosureWarnings],stats:e,timestamp:Date.now()}}getStaleClosureStats(){const e=this.staleClosureWarnings,r={"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)r[f.type]++;const a={info:0,warning:0,error:0};for(const f of e)a[f.severity]++;const i={};for(const f of e)i[f.location]=(i[f.location]||0)+1;const l=Object.entries(i).sort(([,f],[,g])=>g-f).slice(0,5).map(([f,g])=>({location:f,count:g})),c={};for(const f of e)c[f.capturedState.path]=(c[f.capturedState.path]||0)+1;const d=Object.entries(c).sort(([,f],[,g])=>g-f).slice(0,5).map(([f,g])=>({path:f,count:g}));return{totalWarnings:e.length,warningsByType:r,warningsBySeverity:a,topLocations:l,topAffectedPaths:d}}clearStaleClosureData(){this.staleClosureWarnings=[],this.staleClosureIdCounter=0,this.stateCaptureRegistry.clear()}getRecentStaleClosureWarnings(e=10,r){let a=[...this.staleClosureWarnings];return r&&(a=a.filter(i=>i.severity===r)),a.slice(-e)}safeClone(e){if(e==null||typeof e!="object")return e;try{return JSON.parse(JSON.stringify(e))}catch{if(Array.isArray(e))return e.map(a=>{try{return JSON.parse(JSON.stringify(a))}catch{return"[Unserializable]"}});const r={};for(const a of Object.keys(e))try{r[a]=JSON.parse(JSON.stringify(e[a]))}catch{r[a]="[Unserializable]"}return r}}};$(Ei,"instance");let Ma=Ei;const Fn=ut("LayoutLoader");class Er extends Error{constructor(e,r,a){super(e),this.code=r,this.details=a,this.name="LayoutLoaderError"}}class of{constructor(e){$(this,"componentRegistry");$(this,"currentLayout",null);$(this,"layoutCache",new Map);$(this,"cacheVersion",0);this.componentRegistry=e}setCacheVersion(e){this.cacheVersion!==e&&(Fn.log("Cache version updated:",this.cacheVersion,"->",e),this.cacheVersion=e,this.layoutCache.clear())}getCacheVersion(){return this.cacheVersion}async loadLayout(e,r){const a=`${e}:${r}`;if(this.layoutCache.has(a)){Fn.log("Loading layout from cache:",r);const l=await this.layoutCache.get(a),c=JSON.parse(JSON.stringify(l));return this.currentLayout=c,Ma.getInstance().trackLayoutLoad(r,e,c,"cache"),c}const i=this.fetchLayout(e,r);return this.layoutCache.set(a,i),i.catch(()=>{this.layoutCache.get(a)===i&&this.layoutCache.delete(a)}),i}async fetchLayout(e,r,a=!1){try{const i=this.cacheVersion>0?this.cacheVersion:null;let l;if(r.startsWith("__preview__/")){const w=r.replace("__preview__/","");l=Nr(`/api/layouts/preview/${w}`,"json",i)}else l=Nr(`/api/layouts/${e}/${r}`,"json",i);Fn.log("Fetching layout from API:",l);const c=jr(),d=a?null:c.getToken(),f={Accept:"application/json"};d&&(f.Authorization=`Bearer ${d}`);const g=await Bl(l,{init:{headers:f},label:`layout: ${r}`});let m;try{m=await g.json()}catch{m=null}if(!g.ok){if(g.status===401&&!a&&d){Fn.log("Token invalid, removing and retrying without token"),c.removeToken();try{return await this.fetchLayout(e,r,!0)}catch(S){throw S instanceof Er&&S.details?.status===401?new Er(S.message,S.code,{...S.details,hadToken:!0}):S}}const w=m?.message||m?.error;throw new Er(`Failed to fetch layout: ${g.status} ${g.statusText}`,"FETCH_FAILED",{status:g.status,statusText:g.statusText,url:l,apiMessage:w})}const y=m.data||m;return this.validateLayoutData(y),this.currentLayout=y,Ma.getInstance().trackLayoutLoad(r,e,y,"api"),Fn.log("Layout fetched and cached successfully:",y.layout_name),y}catch(i){const l=`${e}:${r}`;throw this.layoutCache.delete(l),i instanceof Er?i:new Er("Failed to load layout","LOAD_FAILED",{originalError:i})}}prefetchLayout(e,r){return this.loadLayout(e,r)}validateLayoutData(e){if(!e.version)throw new Er("Layout data missing required field: version","VALIDATION_FAILED",{field:"version"});if(!e.layout_name)throw new Er("Layout data missing required field: layout_name","VALIDATION_FAILED",{field:"layout_name"});if(!Array.isArray(e.components))throw new Er('Layout data field "components" must be an array',"VALIDATION_FAILED",{field:"components",value:e.components});Fn.log("Layout data validation passed")}renderLayout(e,r){try{const a=r||this.currentLayout;if(!a)throw new Er("No layout data to render","NO_LAYOUT_DATA");Fn.log("Rendering layout:",a.layout_name),e.innerHTML="",this.renderComponents(e,a.components),Fn.log("Layout rendered successfully")}catch(a){Fn.error("Render error:",a),this.renderErrorState(e,a)}}renderComponents(e,r){for(const a of r){const i=this.renderComponent(a);i&&e.appendChild(i)}}renderComponent(e){try{if(!this.componentRegistry.getComponent(e.type))return Fn.warn(`Component not found: ${e.type}`),this.createPlaceholderElement(e.type);const a=document.createElement("div");return a.setAttribute("data-component",e.type),e.props&&Object.entries(e.props).forEach(([i,l])=>{a.setAttribute(`data-prop-${i}`,JSON.stringify(l))}),e.children&&e.children.length>0?this.renderComponents(a,e.children):e.text&&(a.textContent=e.text),a}catch(r){return Fn.error(`Error rendering component ${e.type}:`,r),this.createErrorElement(e.type,r)}}createPlaceholderElement(e){const r=document.createElement("div");return r.className="component-placeholder",r.setAttribute("data-component-type",e),r.innerHTML=`

Component not found: ${e}

- `,n}createErrorElement(e,n){const a=document.createElement("div");return a.className="component-error",a.setAttribute("data-component-type",e),a.innerHTML=` + `,r}createErrorElement(e,r){const a=document.createElement("div");return a.className="component-error",a.setAttribute("data-component-type",e),a.innerHTML=`

Component Error: ${e}

-

${n?.message||"Unknown error"}

+

${r?.message||"Unknown error"}

- `,a}renderErrorState(e,n){const a=n instanceof Error?n.message:String(n),i=n instanceof Cr?n.code:"UNKNOWN_ERROR";e.innerHTML=` + `,a}renderErrorState(e,r){const a=r instanceof Error?r.message:String(r),i=r instanceof Er?r.code:"UNKNOWN_ERROR";e.innerHTML=`
페이지 새로고침
- `,Gn.error("Error state rendered:",i,a)}getCurrentLayout(){return this.currentLayout}clear(){this.currentLayout=null,this.layoutCache.clear(),Gn.log("Layout data and cache cleared")}}const O_=ut("TranslationContext"),hf=N.createContext(null),mc=({children:o,translationEngine:e,translationContext:n})=>{const a=N.useMemo(()=>(l,c)=>{if(c){const d="|"+Object.entries(c).map(([f,g])=>`${f}=${g}`).join("|");return e.translate(l,n,d)}return e.translate(l,n)},[e,n]),i=N.useMemo(()=>({translationEngine:e,translationContext:n,t:a}),[e,n,a]);return dt.jsx(hf.Provider,{value:i,children:o})},ny=()=>{const o=N.useContext(hf);return o||(O_.warn("TranslationProvider 외부에서 호출되었습니다. 키를 그대로 반환합니다."),{t:e=>e,translationEngine:null,translationContext:null})},La=ut("SlotContext"),L_={registerToSlot:()=>{La.warn("SlotContext not available: registerToSlot called outside SlotProvider")},unregisterFromSlot:()=>{La.warn("SlotContext not available: unregisterFromSlot called outside SlotProvider")},getSlotComponents:()=>[],subscribeToSlot:()=>()=>{},clearAllSlots:()=>{},isEnabled:!1},M_=N.createContext(L_),gf=({children:o})=>{const e=N.useRef(new Map),n=N.useRef(new Map),a=N.useCallback(m=>{const b=n.current.get(m);b&&b.forEach(S=>{try{S()}catch(v){La.error(`Slot subscriber error (slotId: ${m}):`,v)}})},[]),i=N.useCallback((m,b,S)=>{if(!m||!b){La.warn("registerToSlot: slotId and componentId are required");return}e.current.has(m)||e.current.set(m,new Map);const v=e.current.get(m),_=v.get(b);_&&_.registrationKey===S.registrationKey||(v.set(b,S),La.log(`Component registered to slot: ${b} -> ${m} (order: ${S.order})`),a(m))},[a]),l=N.useCallback((m,b)=>{const S=e.current.get(m);S&&S.has(b)&&(S.delete(b),La.log(`Component unregistered from slot: ${b} <- ${m}`),S.size===0&&e.current.delete(m),a(m))},[a]),c=N.useCallback(m=>{const b=e.current.get(m);return b?Array.from(b.values()).sort((S,v)=>S.order-v.order):[]},[]),d=N.useCallback((m,b)=>{n.current.has(m)||n.current.set(m,new Set);const S=n.current.get(m);return S.add(b),()=>{S.delete(b),S.size===0&&n.current.delete(m)}},[]),f=N.useCallback(()=>{e.current.forEach((m,b)=>{a(b)}),e.current.clear(),n.current.clear(),La.log("All slots cleared")},[a]),g=N.useMemo(()=>({registerToSlot:i,unregisterFromSlot:l,getSlotComponents:c,subscribeToSlot:d,clearAllSlots:f,isEnabled:!0}),[i,l,c,d,f]);return N.useLayoutEffect(()=>{typeof window<"u"&&(window.__slotContextValue=g,La.log("SlotContext exposed to window.__slotContextValue"))},[g]),dt.jsx(M_.Provider,{value:g,children:o})};class pf{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 ry{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 $_(o){try{return Reflect.construct(String,[],o),!0}catch{return!1}}class mf extends pf{constructor(e,n,a){super(),this.name=n,this.pusher=e,this.options=a,this.eventFormatter=new ry(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,a)=>{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,a)}),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 ay extends mf{whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}}class N_ extends mf{whisper(e,n){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,n),this}}class I_ extends ay{here(e){return this.on("pusher:subscription_succeeded",n=>{e(Object.keys(n.members).map(a=>n.members[a]))}),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 iy extends pf{constructor(e,n,a){super(),this.events={},this.listeners={},this.name=n,this.socket=e,this.options=a,this.eventFormatter=new ry(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]=(a,i)=>{this.name===a&&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(a=>a!==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 sy extends iy{whisper(e,n){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:n}),this}}class H_ extends sy{here(e){return this.on("presence:subscribed",n=>{e(n.map(a=>a.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 yc extends pf{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 oy extends yc{whisper(e,n){return this}}class z_ extends yc{whisper(e,n){return this}}class j_ extends oy{here(e){return this}joining(e){return this}whisper(e,n){return this}leaving(e){return this}}const ly=class BS{constructor(e){this.setOptions(e),this.connect()}setOptions(e){this.options={...BS._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}};ly._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=ly;class bc 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,a){return this.channel(e).listen(n,a)}channel(e){return this.channels[e]||(this.channels[e]=new mf(this.pusher,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new ay(this.pusher,"private-"+e,this.options)),this.channels["private-"+e]}encryptedPrivateChannel(e){return this.channels["private-encrypted-"+e]||(this.channels["private-encrypted-"+e]=new N_(this.pusher,"private-encrypted-"+e,this.options)),this.channels["private-encrypted-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new I_(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())},a=["state_change","connected","disconnected"];return a.forEach(i=>{this.pusher.connection.bind(i,n)}),()=>{a.forEach(i=>{this.pusher.connection.unbind(i,n)})}}disconnect(){this.pusher.disconnect()}}class U_ 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,a){return this.channel(e).listen(n,a)}channel(e){return this.channels[e]||(this.channels[e]=new iy(this.socket,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new sy(this.socket,"private-"+e,this.options)),this.channels["private-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new H_(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())},a=["connect","disconnect","connect_error","reconnect_attempt","reconnect","reconnect_error","reconnect_failed"];return a.forEach(i=>{this.socket.on(i,n)}),()=>{a.forEach(i=>{this.socket.off(i,n)})}}disconnect(){this.socket.disconnect()}}class cy extends yf{constructor(){super(...arguments),this.channels={}}connect(){}listen(e,n,a){return new yc}channel(e){return new yc}privateChannel(e){return new oy}encryptedPrivateChannel(e){return new z_}presenceChannel(e){return new j_}leave(e){}leaveChannel(e){}socketId(){return"fake-socket-id"}connectionStatus(){return"connected"}onConnectionChange(e){return()=>{}}disconnect(){}}class B_{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 bc({...this.options,cluster:""});else if(this.options.broadcaster==="pusher")this.connector=new bc(this.options);else if(this.options.broadcaster==="ably")this.connector=new bc({...this.options,cluster:"",broadcaster:"pusher"});else if(this.options.broadcaster==="socket.io")this.connector=new U_(this.options);else if(this.options.broadcaster==="null")this.connector=new cy(this.options);else if(typeof this.options.broadcaster=="function"&&$_(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,a){return this.connector.listen(e,n,a)}private(e){return this.connector.privateChannel(e)}encryptedPrivate(e){if(this.connectorSupportsEncryptedPrivateChannels(this.connector))return this.connector.encryptedPrivateChannel(e);throw new Error(`Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} does not support encrypted private channels.`)}connectorSupportsEncryptedPrivateChannels(e){return e instanceof bc||e instanceof cy}socketId(){return this.connector.socketId()}connectionStatus(){return this.connector.connectionStatus()}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,a)=>{this.socketId()&&a.setRequestHeader("X-Socket-Id",this.socketId())})}registerTurboRequestInterceptor(){document.addEventListener("turbo:before-fetch-request",e=>{e.detail.fetchOptions.headers["X-Socket-Id"]=this.socketId()})}}var bf={exports:{}};var uy;function P_(){return uy||(uy=1,(function(o,e){(function(a,i){o.exports=i()})(self,()=>(()=>{var n={594(c,d){var f=this&&this.__extends||(function(){var M=function(R,D){return M=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(B,q){B.__proto__=q}||function(B,q){for(var P in q)q.hasOwnProperty(P)&&(B[P]=q[P])},M(R,D)};return function(R,D){M(R,D);function B(){this.constructor=R}R.prototype=D===null?Object.create(D):(B.prototype=D.prototype,new B)}})();Object.defineProperty(d,"__esModule",{value:!0});var g=256,m=(function(){function M(R){R===void 0&&(R="="),this._paddingCharacter=R}return M.prototype.encodedLength=function(R){return this._paddingCharacter?(R+2)/3*4|0:(R*8+5)/6|0},M.prototype.encode=function(R){for(var D="",B=0;B>>18&63),D+=this._encodeByte(q>>>12&63),D+=this._encodeByte(q>>>6&63),D+=this._encodeByte(q>>>0&63)}var P=R.length-B;if(P>0){var q=R[B]<<16|(P===2?R[B+1]<<8:0);D+=this._encodeByte(q>>>18&63),D+=this._encodeByte(q>>>12&63),P===2?D+=this._encodeByte(q>>>6&63):D+=this._paddingCharacter||"",D+=this._paddingCharacter||""}return D},M.prototype.maxDecodedLength=function(R){return this._paddingCharacter?R/4*3|0:(R*6+7)/8|0},M.prototype.decodedLength=function(R){return this.maxDecodedLength(R.length-this._getPaddingLength(R))},M.prototype.decode=function(R){if(R.length===0)return new Uint8Array(0);for(var D=this._getPaddingLength(R),B=R.length-D,q=new Uint8Array(this.maxDecodedLength(B)),P=0,K=0,ge=0,Ee=0,Se=0,Ue=0,Ve=0;K>>4,q[P++]=Se<<4|Ue>>>2,q[P++]=Ue<<6|Ve,ge|=Ee&g,ge|=Se&g,ge|=Ue&g,ge|=Ve&g;if(K>>4,ge|=Ee&g,ge|=Se&g),K>>2,ge|=Ue&g),K>>8&6,D+=51-R>>>8&-75,D+=61-R>>>8&-15,D+=62-R>>>8&3,String.fromCharCode(D)},M.prototype._decodeChar=function(R){var D=g;return D+=(42-R&R-44)>>>8&-g+R-43+62,D+=(46-R&R-48)>>>8&-g+R-47+63,D+=(47-R&R-58)>>>8&-g+R-48+52,D+=(64-R&R-91)>>>8&-g+R-65+0,D+=(96-R&R-123)>>>8&-g+R-97+26,D},M.prototype._getPaddingLength=function(R){var D=0;if(this._paddingCharacter){for(var B=R.length-1;B>=0&&R[B]===this._paddingCharacter;B--)D++;if(R.length<4||D>2)throw new Error("Base64Coder: incorrect padding")}return D},M})();d.Coder=m;var b=new m;function S(M){return b.encode(M)}d.encode=S;function v(M){return b.decode(M)}d.decode=v;var _=(function(M){f(R,M);function R(){return M!==null&&M.apply(this,arguments)||this}return R.prototype._encodeByte=function(D){var B=D;return B+=65,B+=25-D>>>8&6,B+=51-D>>>8&-75,B+=61-D>>>8&-13,B+=62-D>>>8&49,String.fromCharCode(B)},R.prototype._decodeChar=function(D){var B=g;return B+=(44-D&D-46)>>>8&-g+D-45+62,B+=(94-D&D-96)>>>8&-g+D-95+63,B+=(47-D&D-58)>>>8&-g+D-48+52,B+=(64-D&D-91)>>>8&-g+D-65+0,B+=(96-D&D-123)>>>8&-g+D-97+26,B},R})(m);d.URLSafeCoder=_;var A=new _;function x(M){return A.encode(M)}d.encodeURLSafe=x;function L(M){return A.decode(M)}d.decodeURLSafe=L,d.encodedLength=function(M){return b.encodedLength(M)},d.maxDecodedLength=function(M){return b.maxDecodedLength(M)},d.decodedLength=function(M){return b.decodedLength(M)}},978(c,d){var f="utf8: invalid source encoding";function g(m){for(var b=[],S=0;S=m.length)throw new Error(f);var A=m[++S];if((A&192)!==128)throw new Error(f);v=(v&31)<<6|A&63,_=128}else if(v<240){if(S>=m.length-1)throw new Error(f);var A=m[++S],x=m[++S];if((A&192)!==128||(x&192)!==128)throw new Error(f);v=(v&15)<<12|(A&63)<<6|x&63,_=2048}else if(v<248){if(S>=m.length-2)throw new Error(f);var A=m[++S],x=m[++S],L=m[++S];if((A&192)!==128||(x&192)!==128||(L&192)!==128)throw new Error(f);v=(v&15)<<18|(A&63)<<12|(x&63)<<6|L&63,_=65536}else throw new Error(f);if(v<_||v>=55296&&v<=57343)throw new Error(f);if(v>=65536){if(v>1114111)throw new Error(f);v-=65536,b.push(String.fromCharCode(55296|v>>10)),v=56320|v&1023}}b.push(String.fromCharCode(v))}return b.join("")}d.D4=g},721(c,d,f){c.exports=f(207).default},207(c,d,f){f.d(d,{default:()=>ws});class g{constructor(y,C){this.lastId=0,this.prefix=y,this.name=C}create(y){this.lastId++;var C=this.lastId,O=this.prefix+C,I=this.name+"["+C+"]",ne=!1,me=function(){ne||(y.apply(null,arguments),ne=!0)};return this[C]=me,{number:C,id:O,name:I,callback:me}}remove(y){delete this[y.number]}}var m=new g("_pusher_script_","Pusher.ScriptReceivers"),b={VERSION:"8.5.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 S=b;class v{constructor(y){this.options=y,this.receivers=y.receivers||m,this.loading={}}load(y,C,O){var I=this;if(I.loading[y]&&I.loading[y].length>0)I.loading[y].push(O);else{I.loading[y]=[O];var ne=je.createScriptRequest(I.getPath(y,C)),me=I.receivers.create(function(Me){if(I.receivers.remove(me),I.loading[y]){var Ke=I.loading[y];delete I.loading[y];for(var lt=function(zt){zt||ne.cleanup()},gt=0;gt>>6)+J(128|y&63):J(224|y>>>12&15)+J(128|y>>>6&63)+J(128|y&63)},Z=function(E){return E.replace(/[^\x00-\x7F]/g,Le)},pe=function(E){var y=[0,2,1][E.length%3],C=E.charCodeAt(0)<<16|(E.length>1?E.charCodeAt(1):0)<<8|(E.length>2?E.charCodeAt(2):0),O=[fe.charAt(C>>>18),fe.charAt(C>>>12&63),y>=2?"=":fe.charAt(C>>>6&63),y>=1?"=":fe.charAt(C&63)];return O.join("")},H=window.btoa||function(E){return E.replace(/[\s\S]{1,3}/g,pe)};class T{constructor(y,C,O,I){this.clear=C,this.timer=y(()=>{this.timer&&(this.timer=I(this.timer))},O)}isRunning(){return this.timer!==null}ensureAborted(){this.timer&&(this.clear(this.timer),this.timer=null)}}const ce=T;function de(E){window.clearTimeout(E)}function ye(E){window.clearInterval(E)}class ie extends ce{constructor(y,C){super(setTimeout,de,y,function(O){return C(),null})}}class xe extends ce{constructor(y,C){super(setInterval,ye,y,function(O){return C(),O})}}var _e={now(){return Date.now?Date.now():new Date().valueOf()},defer(E){return new ie(0,E)},method(E,...y){var C=Array.prototype.slice.call(arguments,1);return function(O){return O[E].apply(O,C.concat(arguments))}}};const Te=_e;function $e(E,...y){for(var C=0;C{window.console&&window.console.log&&window.console.log(y)}}debug(...y){this.log(this.globalLog,y)}warn(...y){this.log(this.globalLogWarn,y)}error(...y){this.log(this.globalLogError,y)}globalLogWarn(y){window.console&&window.console.warn?window.console.warn(y):this.globalLog(y)}globalLogError(y){window.console&&window.console.error?window.console.error(y):this.globalLogWarn(y)}log(y,...C){var O=ht.apply(this,arguments);ws.log?ws.log(O):ws.logToConsole&&y.bind(this)(O)}}const tt=new Rn;var $n=function(E,y,C,O,I){(C.headers!==void 0||C.headersProvider!=null)&&tt.warn(`To send headers with the ${O.toString()} request, you must use AJAX, rather than JSONP.`);var ne=E.nextAuthCallbackID.toString();E.nextAuthCallbackID++;var me=E.getDocument(),Me=me.createElement("script");E.auth_callbacks[ne]=function(gt){I(null,gt)};var Ke="Pusher.auth_callbacks['"+ne+"']";Me.src=C.endpoint+"?callback="+encodeURIComponent(Ke)+"&"+y;var lt=me.getElementsByTagName("head")[0]||me.documentElement;lt.insertBefore(Me,lt.firstChild)};const pn=$n;class ra{constructor(y){this.src=y}send(y){var C=this,O="Error loading "+C.src;C.script=document.createElement("script"),C.script.id=y.id,C.script.src=C.src,C.script.type="text/javascript",C.script.charset="UTF-8",C.script.addEventListener?(C.script.onerror=function(){y.callback(O)},C.script.onload=function(){y.callback(null)}):C.script.onreadystatechange=function(){(C.script.readyState==="loaded"||C.script.readyState==="complete")&&y.callback(null)},C.script.async===void 0&&document.attachEvent&&/opera/i.test(navigator.userAgent)?(C.errorScript=document.createElement("script"),C.errorScript.id=y.id+"_error",C.errorScript.text=y.name+"('"+O+"');",C.script.async=C.errorScript.async=!1):C.script.async=!0;var I=document.getElementsByTagName("head")[0];I.insertBefore(C.script,I.firstChild),C.errorScript&&I.insertBefore(C.errorScript,C.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 ir{constructor(y,C){this.url=y,this.data=C}send(y){if(!this.request){var C=wi(this.data),O=this.url+"/"+y.number+"?"+C;this.request=je.createScriptRequest(O),this.request.send(y)}}cleanup(){this.request&&this.request.cleanup()}}var an=function(E,y){return function(C,O){var I="http"+(y?"s":"")+"://",ne=I+(E.host||E.options.host)+E.options.path,me=je.createJSONPRequest(ne,C),Me=je.ScriptReceivers.create(function(Ke,lt){m.remove(Me),me.cleanup(),lt&<.host&&(E.host=lt.host),O&&O(Ke,lt)});me.send(Me)}},En={name:"jsonp",getAgent:an};const sn=En;function V(E,y,C){var O=E+(y.useTLS?"s":""),I=y.useTLS?y.hostTLS:y.hostNonTLS;return O+"://"+I+C}function se(E,y){var C="/app/"+E,O="?protocol="+S.PROTOCOL+"&client=js&version="+S.VERSION+(y?"&"+y:"");return C+O}var ue={getInitial:function(E,y){var C=(y.httpPath||"")+se(E,"flash=false");return V("ws",y,C)}},ee={getInitial:function(E,y){var C=(y.httpPath||"/pusher")+se(E);return V("http",y,C)}},ve={getInitial:function(E,y){return V("http",y,y.httpPath||"/pusher")},getPath:function(E,y){return se(E)}};class he{constructor(){this._callbacks={}}get(y){return this._callbacks[Ce(y)]}add(y,C,O){var I=Ce(y);this._callbacks[I]=this._callbacks[I]||[],this._callbacks[I].push({fn:C,context:O})}remove(y,C,O){if(!y&&!C&&!O){this._callbacks={};return}var I=y?[Ce(y)]:ft(this._callbacks);C||O?this.removeCallback(I,C,O):this.removeAllCallbacks(I)}removeCallback(y,C,O){Ft(y,function(I){this._callbacks[I]=fn(this._callbacks[I]||[],function(ne){return C&&C!==ne.fn||O&&O!==ne.context}),this._callbacks[I].length===0&&delete this._callbacks[I]},this)}removeAllCallbacks(y){Ft(y,function(C){delete this._callbacks[C]},this)}}function Ce(E){return"_"+E}class Ae{constructor(y){this.callbacks=new he,this.global_callbacks=[],this.failThrough=y}bind(y,C,O){return this.callbacks.add(y,C,O),this}bind_global(y){return this.global_callbacks.push(y),this}unbind(y,C,O){return this.callbacks.remove(y,C,O),this}unbind_global(y){return y?(this.global_callbacks=fn(this.global_callbacks||[],C=>C!==y),this):(this.global_callbacks=[],this)}unbind_all(){return this.unbind(),this.unbind_global(),this}emit(y,C,O){for(var I=0;I0)for(var I=0;I{this.onError(C),this.changeState("closed")}),!1}return this.bindListeners(),tt.debug("Connecting",{transport:this.name,url:y}),this.changeState("connecting"),!0}close(){return this.socket?(this.socket.close(),!0):!1}send(y){return this.state==="open"?(Te.defer(()=>{this.socket&&this.socket.send(y)}),!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(y){this.emit("error",{type:"WebSocketError",error:y}),this.timeline.error(this.buildTimelineMessage({error:y.toString()}))}onClose(y){y?this.changeState("closed",{code:y.code,reason:y.reason,wasClean:y.wasClean}):this.changeState("closed"),this.unbindListeners(),this.socket=void 0}onMessage(y){this.emit("message",y)}onActivity(){this.emit("activity")}bindListeners(){this.socket.onopen=()=>{this.onOpen()},this.socket.onerror=y=>{this.onError(y)},this.socket.onclose=y=>{this.onClose(y)},this.socket.onmessage=y=>{this.onMessage(y)},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(y,C){this.state=y,this.timeline.info(this.buildTimelineMessage({state:y,params:C})),this.emit(y,C)}buildTimelineMessage(y){return $e({cid:this.id},y)}}class Re{constructor(y){this.hooks=y}isSupported(y){return this.hooks.isSupported(y)}createConnection(y,C,O,I){return new Fe(this.hooks,y,C,O,I)}}var Ne=new Re({urls:ue,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return!!je.getWebSocketAPI()},isSupported:function(){return!!je.getWebSocketAPI()},getSocket:function(E){return je.createWebSocket(E)}}),ke={urls:ee,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},Ze=$e({getSocket:function(E){return je.HTTPFactory.createStreamingSocket(E)}},ke),ze=$e({getSocket:function(E){return je.HTTPFactory.createPollingSocket(E)}},ke),Ge={isSupported:function(){return je.isXHRSupported()}},we=new Re($e({},Ze,Ge)),He=new Re($e({},ze,Ge)),et={ws:Ne,xhr_streaming:we,xhr_polling:He};const _t=et;var Lt=new Re({file:"sockjs",urls:ve,handlesActivityChecks:!0,supportsPing:!1,isSupported:function(){return!0},isInitialized:function(){return window.SockJS!==void 0},getSocket:function(E,y){return new window.SockJS(E,null,{js_path:A.getPath("sockjs",{useTLS:y.useTLS}),ignore_null_origin:y.ignoreNullOrigin})},beforeOpen:function(E,y){E.send(JSON.stringify({path:y}))}}),kn={isSupported:function(E){var y=je.isXDRSupported(E.useTLS);return y}},It=new Re($e({},Ze,kn)),Ht=new Re($e({},ze,kn));_t.xdr_streaming=It,_t.xdr_polling=Ht,_t.sockjs=Lt;const _n=_t;class $a extends Ae{constructor(){super();var y=this;window.addEventListener!==void 0&&(window.addEventListener("online",function(){y.emit("online")},!1),window.addEventListener("offline",function(){y.emit("offline")},!1))}isOnline(){return window.navigator.onLine===void 0?!0:window.navigator.onLine}}var $o=new $a;class Af{constructor(y,C,O){this.manager=y,this.transport=C,this.minPingDelay=O.minPingDelay,this.maxPingDelay=O.maxPingDelay,this.pingDelay=void 0}createConnection(y,C,O,I){I=$e({},I,{activityTimeout:this.pingDelay});var ne=this.transport.createConnection(y,C,O,I),me=null,Me=function(){ne.unbind("open",Me),ne.bind("closed",Ke),me=Te.now()},Ke=lt=>{if(ne.unbind("closed",Ke),lt.code===1002||lt.code===1003)this.manager.reportDeath();else if(!lt.wasClean&&me){var gt=Te.now()-me;gt<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(gt/2,this.minPingDelay))}};return ne.bind("open",Me),ne}isSupported(y){return this.manager.isAlive()&&this.transport.isSupported(y)}}const Ac={decodeMessage:function(E){try{var y=JSON.parse(E.data),C=y.data;if(typeof C=="string")try{C=JSON.parse(y.data)}catch{}var O={event:y.event,channel:y.channel,data:C};return y.user_id&&(O.user_id=y.user_id),O}catch(I){throw{type:"MessageParseError",error:I,data:E.data}}},encodeMessage:function(E){return JSON.stringify(E)},processHandshake:function(E){var y=Ac.decodeMessage(E);if(y.event==="pusher:connection_established"){if(!y.data.activity_timeout)throw"No activity timeout specified in handshake";return{action:"connected",id:y.data.socket_id,activityTimeout:y.data.activity_timeout*1e3}}else{if(y.event==="pusher:error")return{action:this.getCloseAction(y.data),error:this.getCloseError(y.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}},qr=Ac;class Ci extends Ae{constructor(y,C){super(),this.id=y,this.transport=C,this.activityTimeout=C.activityTimeout,this.bindListeners()}handlesActivityChecks(){return this.transport.handlesActivityChecks()}send(y){return this.transport.send(y)}send_event(y,C,O){var I={event:y,data:C};return O&&(I.channel=O),tt.debug("Event sent",I),this.send(qr.encodeMessage(I))}ping(){this.transport.supportsPing()?this.transport.ping():this.send_event("pusher:ping",{})}close(){this.transport.close()}bindListeners(){var y={message:O=>{var I;try{I=qr.decodeMessage(O)}catch(ne){this.emit("error",{type:"MessageParseError",error:ne,data:O.data})}if(I!==void 0){switch(tt.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:O=>{this.emit("error",O)},closed:O=>{C(),O&&O.code&&this.handleCloseEvent(O),this.transport=null,this.emit("closed")}},C=()=>{kt(y,(O,I)=>{this.transport.unbind(I,O)})};kt(y,(O,I)=>{this.transport.bind(I,O)})}handleCloseEvent(y){var C=qr.getCloseAction(y),O=qr.getCloseError(y);O&&this.emit("error",O),C&&this.emit(C,{action:C,error:O})}}class No{constructor(y,C){this.transport=y,this.callback=C,this.bindListeners()}close(){this.unbindListeners(),this.transport.close()}bindListeners(){this.onMessage=y=>{this.unbindListeners();var C;try{C=qr.processHandshake(y)}catch(O){this.finish("error",{error:O}),this.transport.close();return}C.action==="connected"?this.finish("connected",{connection:new Ci(C.id,this.transport),activityTimeout:C.activityTimeout}):(this.finish(C.action,{error:C.error}),this.transport.close())},this.onClosed=y=>{this.unbindListeners();var C=qr.getCloseAction(y)||"backoff",O=qr.getCloseError(y);this.finish(C,{error:O})},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(y,C){this.callback($e({transport:this.transport,action:y},C))}}class Na{constructor(y,C){this.timeline=y,this.options=C||{}}send(y,C){this.timeline.isEmpty()||this.timeline.send(je.TimelineTransport.getAgent(this,y),C)}}class Gr extends Ae{constructor(y,C){super(function(O,I){tt.debug("No callbacks on "+y+" for "+O)}),this.name=y,this.pusher=C,this.subscribed=!1,this.subscriptionPending=!1,this.subscriptionCancelled=!1}authorize(y,C){return C(null,{auth:""})}trigger(y,C){if(y.indexOf("client-")!==0)throw new D("Event '"+y+"' does not start with 'client-'");if(!this.subscribed){var O=M.buildLogSuffix("triggeringClientEvents");tt.warn(`Client event triggered before channel 'subscription_succeeded' event . ${O}`)}return this.pusher.send_event(y,C,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(y){var C=y.event,O=y.data;if(C==="pusher_internal:subscription_succeeded")this.handleSubscriptionSucceededEvent(y);else if(C==="pusher_internal:subscription_count")this.handleSubscriptionCountEvent(y);else if(C.indexOf("pusher_internal:")!==0){var I={};this.emit(C,O,I)}}handleSubscriptionSucceededEvent(y){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):this.emit("pusher:subscription_succeeded",y.data)}handleSubscriptionCountEvent(y){y.data.subscription_count&&(this.subscriptionCount=y.data.subscription_count),this.emit("pusher:subscription_count",y.data)}subscribe(){this.subscribed||(this.subscriptionPending=!0,this.subscriptionCancelled=!1,this.authorize(this.pusher.connection.socket_id,(y,C)=>{y?(this.subscriptionPending=!1,tt.error(y.toString()),this.emit("pusher:subscription_error",Object.assign({},{type:"AuthError",error:y.message},y instanceof Ue?{status:y.status}:{}))):this.pusher.send_event("pusher:subscribe",{auth:C.auth,channel_data:C.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 aa extends Gr{authorize(y,C){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:y},C)}}class Ia{constructor(){this.reset()}get(y){return Object.prototype.hasOwnProperty.call(this.members,y)?{id:y,info:this.members[y]}:null}each(y){kt(this.members,(C,O)=>{y(this.get(O))})}setMyID(y){this.myID=y}onSubscription(y){this.members=y.presence.hash,this.count=y.presence.count,this.me=this.get(this.myID)}addMember(y){return this.get(y.user_id)===null&&this.count++,this.members[y.user_id]=y.user_info,this.get(y.user_id)}removeMember(y){var C=this.get(y.user_id);return C&&(delete this.members[y.user_id],this.count--),C}reset(){this.members={},this.count=0,this.myID=null,this.me=null}}var Xt=function(E,y,C,O){function I(ne){return ne instanceof C?ne:new C(function(me){me(ne)})}return new(C||(C=Promise))(function(ne,me){function Me(gt){try{lt(O.next(gt))}catch(zt){me(zt)}}function Ke(gt){try{lt(O.throw(gt))}catch(zt){me(zt)}}function lt(gt){gt.done?ne(gt.value):I(gt.value).then(Me,Ke)}lt((O=O.apply(E,y||[])).next())})};class xc extends aa{constructor(y,C){super(y,C),this.members=new Ia}authorize(y,C){super.authorize(y,(O,I)=>Xt(this,void 0,void 0,function*(){if(!O)if(I=I,I.channel_data!=null){var ne=JSON.parse(I.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 me=M.buildLogSuffix("authorizationEndpoint");tt.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${me}, or the user should be signed in.`),C("Invalid auth response");return}C(O,I)}))}handleEvent(y){var C=y.event;if(C.indexOf("pusher_internal:")===0)this.handleInternalEvent(y);else{var O=y.data,I={};y.user_id&&(I.user_id=y.user_id),this.emit(C,O,I)}}handleInternalEvent(y){var C=y.event,O=y.data;switch(C){case"pusher_internal:subscription_succeeded":this.handleSubscriptionSucceededEvent(y);break;case"pusher_internal:subscription_count":this.handleSubscriptionCountEvent(y);break;case"pusher_internal:member_added":var I=this.members.addMember(O);this.emit("pusher:member_added",I);break;case"pusher_internal:member_removed":var ne=this.members.removeMember(O);ne&&this.emit("pusher:member_removed",ne);break}}handleSubscriptionSucceededEvent(y){this.subscriptionPending=!1,this.subscribed=!0,this.subscriptionCancelled?this.pusher.unsubscribe(this.name):(this.members.onSubscription(y.data),this.emit("pusher:subscription_succeeded",this.members))}disconnect(){this.members.reset(),super.disconnect()}}var Tc=f(978),xr=f(594);class Ha extends aa{constructor(y,C,O){super(y,C),this.key=null,this.nacl=O}authorize(y,C){super.authorize(y,(O,I)=>{if(O){C(O,I);return}let ne=I.shared_secret;if(!ne){C(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null);return}this.key=(0,xr.decode)(ne),delete I.shared_secret,C(null,I)})}trigger(y,C){throw new ge("Client events are not currently supported for encrypted channels")}handleEvent(y){var C=y.event,O=y.data;if(C.indexOf("pusher_internal:")===0||C.indexOf("pusher:")===0){super.handleEvent(y);return}this.handleEncryptedEvent(C,O)}handleEncryptedEvent(y,C){if(!this.key){tt.debug("Received encrypted event before key has been retrieved from the authEndpoint");return}if(!C.ciphertext||!C.nonce){tt.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+C);return}let O=(0,xr.decode)(C.ciphertext);if(O.length{if(me){tt.error(`Failed to make a request to the authEndpoint: ${Me}. Unable to fetch new key, so dropping encrypted event`);return}if(ne=this.nacl.secretbox.open(O,I,this.key),ne===null){tt.error("Failed to decrypt event with new key. Dropping encrypted event");return}this.emit(y,this.getDataToEmit(ne))});return}this.emit(y,this.getDataToEmit(ne))}getDataToEmit(y){let C=(0,Tc.D4)(y);try{return JSON.parse(C)}catch{return C}}}class xf extends Ae{constructor(y,C){super(),this.state="initialized",this.connection=null,this.key=y,this.options=C,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 O=je.getNetwork();O.bind("online",()=>{this.timeline.info({netinfo:"online"}),(this.state==="connecting"||this.state==="unavailable")&&this.retryIn(0)}),O.bind("offline",()=>{this.timeline.info({netinfo:"offline"}),this.connection&&this.sendActivityCheck()}),this.updateStrategy()}switchCluster(y){this.key=y,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(y){return this.connection?this.connection.send(y):!1}send_event(y,C,O){return this.connection?this.connection.send_event(y,C,O):!1}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var y=(C,O)=>{C?this.runner=this.strategy.connect(0,y):O.action==="error"?(this.emit("error",{type:"HandshakeError",error:O.error}),this.timeline.error({handshakeError:O.error})):(this.abortConnecting(),this.handshakeCallbacks[O.action](O))};this.runner=this.strategy.connect(0,y)}abortConnecting(){this.runner&&(this.runner.abort(),this.runner=null)}disconnectInternally(){if(this.abortConnecting(),this.clearRetryTimer(),this.clearUnavailableTimer(),this.connection){var y=this.abandonConnection();y.close()}}updateStrategy(){this.strategy=this.options.getStrategy({key:this.key,timeline:this.timeline,useTLS:this.usingTLS})}retryIn(y){this.timeline.info({action:"retry",delay:y}),y>0&&this.emit("connecting_in",Math.round(y/1e3)),this.retryTimer=new ie(y||0,()=>{this.disconnectInternally(),this.connect()})}clearRetryTimer(){this.retryTimer&&(this.retryTimer.ensureAborted(),this.retryTimer=null)}setUnavailableTimer(){this.unavailableTimer=new ie(this.options.unavailableTimeout,()=>{this.updateState("unavailable")})}clearUnavailableTimer(){this.unavailableTimer&&this.unavailableTimer.ensureAborted()}sendActivityCheck(){this.stopActivityCheck(),this.connection.ping(),this.activityTimer=new ie(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 ie(this.activityTimeout,()=>{this.sendActivityCheck()}))}stopActivityCheck(){this.activityTimer&&this.activityTimer.ensureAborted()}buildConnectionCallbacks(y){return $e({},y,{message:C=>{this.resetActivityCheck(),this.emit("message",C)},ping:()=>{this.send_event("pusher:pong",{})},activity:()=>{this.resetActivityCheck()},error:C=>{this.emit("error",C)},closed:()=>{this.abandonConnection(),this.shouldRetry()&&this.retryIn(1e3)}})}buildHandshakeCallbacks(y){return $e({},y,{connected:C=>{this.activityTimeout=Math.min(this.options.activityTimeout,C.activityTimeout,C.connection.activityTimeout||1/0),this.clearUnavailableTimer(),this.setConnection(C.connection),this.socket_id=this.connection.id,this.updateState("connected",{socket_id:this.socket_id})}})}buildErrorCallbacks(){let y=C=>O=>{O.error&&this.emit("error",{type:"WebSocketError",error:O.error}),C(O)};return{tls_only:y(()=>{this.usingTLS=!0,this.updateStrategy(),this.retryIn(0)}),refused:y(()=>{this.disconnect()}),backoff:y(()=>{this.retryIn(1e3)}),retry:y(()=>{this.retryIn(0)})}}setConnection(y){this.connection=y;for(var C in this.connectionCallbacks)this.connection.bind(C,this.connectionCallbacks[C]);this.resetActivityCheck()}abandonConnection(){if(this.connection){this.stopActivityCheck();for(var y in this.connectionCallbacks)this.connection.unbind(y,this.connectionCallbacks[y]);var C=this.connection;return this.connection=null,C}}updateState(y,C){var O=this.state;if(this.state=y,O!==y){var I=y;I==="connected"&&(I+=" with new socket ID "+C.socket_id),tt.debug("State changed",O+" -> "+I),this.timeline.info({state:y,params:C}),this.emit("state_change",{previous:O,current:y}),this.emit(y,C)}}shouldRetry(){return this.state==="connecting"||this.state==="connected"}}class Rc{constructor(){this.channels={}}add(y,C){return this.channels[y]||(this.channels[y]=kc(y,C)),this.channels[y]}all(){return nn(this.channels)}find(y){return this.channels[y]}remove(y){var C=this.channels[y];return delete this.channels[y],C}disconnect(){kt(this.channels,function(y){y.disconnect()})}}function kc(E,y){if(E.indexOf("private-encrypted-")===0){if(y.config.nacl)return Nn.createEncryptedChannel(E,y,y.config.nacl);let C="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",O=M.buildLogSuffix("encryptedChannelSupport");throw new ge(`${C}. ${O}`)}else{if(E.indexOf("private-")===0)return Nn.createPrivateChannel(E,y);if(E.indexOf("presence-")===0)return Nn.createPresenceChannel(E,y);if(E.indexOf("#")===0)throw new B('Cannot create a channel with name "'+E+'".');return Nn.createChannel(E,y)}}var Tf={createChannels(){return new Rc},createConnectionManager(E,y){return new xf(E,y)},createChannel(E,y){return new Gr(E,y)},createPrivateChannel(E,y){return new aa(E,y)},createPresenceChannel(E,y){return new xc(E,y)},createEncryptedChannel(E,y,C){return new Ha(E,y,C)},createTimelineSender(E,y){return new Na(E,y)},createHandshake(E,y){return new No(E,y)},createAssistantToTheTransportManager(E,y,C){return new Af(E,y,C)}};const Nn=Tf;class Ei{constructor(y){this.options=y||{},this.livesLeft=this.options.lives||1/0}getAssistant(y){return Nn.createAssistantToTheTransportManager(this,y,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class mn{constructor(y,C){this.strategies=y,this.loop=!!C.loop,this.failFast=!!C.failFast,this.timeout=C.timeout,this.timeoutLimit=C.timeoutLimit}isSupported(){return Fn(this.strategies,Te.method("isSupported"))}connect(y,C){var O=this.strategies,I=0,ne=this.timeout,me=null,Me=(Ke,lt)=>{lt?C(null,lt):(I=I+1,this.loop&&(I=I%O.length),I0&&(ne=new ie(O.timeout,function(){me.abort(),I(!0)})),me=y.connect(C,function(Me,Ke){Me&&ne&&ne.isRunning()&&!O.failFast||(ne&&ne.ensureAborted(),I(Me,Ke))}),{abort:function(){ne&&ne.ensureAborted(),me.abort()},forceMinPriority:function(Me){me.forceMinPriority(Me)}}}}class An{constructor(y){this.strategies=y}isSupported(){return Fn(this.strategies,Te.method("isSupported"))}connect(y,C){return Dc(this.strategies,y,function(O,I){return function(ne,me){if(I[O].error=ne,ne){Rf(I)&&C(!0);return}Ft(I,function(Me){Me.forceMinPriority(me.transport.priority)}),C(null,me)}})}}function Dc(E,y,C){var O=Nt(E,function(I,ne,me,Me){return I.connect(y,C(ne,Me))});return{abort:function(){Ft(O,Io)},forceMinPriority:function(I){Ft(O,function(ne){ne.forceMinPriority(I)})}}}function Rf(E){return Pr(E,function(y){return!!y.error})}function Io(E){!E.error&&!E.aborted&&(E.abort(),E.aborted=!0)}class Oc{constructor(y,C,O){this.strategy=y,this.transports=C,this.ttl=O.ttl||18e5,this.usingTLS=O.useTLS,this.timeline=O.timeline}isSupported(){return this.strategy.isSupported()}connect(y,C){var O=this.usingTLS,I=kf(O),ne=I&&I.cacheSkipCount?I.cacheSkipCount:0,me=[this.strategy];if(I&&I.timestamp+this.ttl>=Te.now()){var Me=this.transports[I.transport];Me&&(["ws","wss"].includes(I.transport)||ne>3?(this.timeline.info({cached:!0,transport:I.transport,latency:I.latency}),me.push(new mn([Me],{timeout:I.latency*2+1e3,failFast:!0}))):ne++)}var Ke=Te.now(),lt=me.pop().connect(y,function gt(zt,Dr){zt?(ms(O),me.length>0?(Ke=Te.now(),lt=me.pop().connect(y,gt)):C(zt)):(In(O,Dr.transport.name,Te.now()-Ke,ne),C(null,Dr))});return{abort:function(){lt.abort()},forceMinPriority:function(gt){y=gt,lt&<.forceMinPriority(gt)}}}}function za(E){return"pusherTransport"+(E?"TLS":"NonTLS")}function kf(E){var y=je.getLocalStorage();if(y)try{var C=y[za(E)];if(C)return JSON.parse(C)}catch{ms(E)}return null}function In(E,y,C,O){var I=je.getLocalStorage();if(I)try{I[za(E)]=gn({timestamp:Te.now(),transport:y,latency:C,cacheSkipCount:O})}catch{}}function ms(E){var y=je.getLocalStorage();if(y)try{delete y[za(E)]}catch{}}class _i{constructor(y,{delay:C}){this.strategy=y,this.options={delay:C}}isSupported(){return this.strategy.isSupported()}connect(y,C){var O=this.strategy,I,ne=new ie(this.options.delay,function(){I=O.connect(y,C)});return{abort:function(){ne.ensureAborted(),I&&I.abort()},forceMinPriority:function(me){y=me,I&&I.forceMinPriority(me)}}}}class ia{constructor(y,C,O){this.test=y,this.trueBranch=C,this.falseBranch=O}isSupported(){var y=this.test()?this.trueBranch:this.falseBranch;return y.isSupported()}connect(y,C){var O=this.test()?this.trueBranch:this.falseBranch;return O.connect(y,C)}}class ja{constructor(y){this.strategy=y}isSupported(){return this.strategy.isSupported()}connect(y,C){var O=this.strategy.connect(y,function(I,ne){ne&&O.abort(),C(I,ne)});return O}}function Ua(E){return function(){return E.isSupported()}}var Lc=function(E,y,C){var O={};function I(Xo,Fc,Kc,Xf,Jf){var Wc=C(E,Xo,Fc,Kc,Xf,Jf);return O[Xo]=Wc,Wc}var ne=Object.assign({},y,{hostNonTLS:E.wsHost+":"+E.wsPort,hostTLS:E.wsHost+":"+E.wssPort,httpPath:E.wsPath}),me=Object.assign({},ne,{useTLS:!0}),Me=Object.assign({},y,{hostNonTLS:E.httpHost+":"+E.httpPort,hostTLS:E.httpHost+":"+E.httpsPort,httpPath:E.httpPath}),Ke={loop:!0,timeout:15e3,timeoutLimit:6e4},lt=new Ei({minPingDelay:1e4,maxPingDelay:E.activityTimeout}),gt=new Ei({lives:2,minPingDelay:1e4,maxPingDelay:E.activityTimeout}),zt=I("ws","ws",3,ne,lt),Dr=I("wss","ws",3,me,lt),Kf=I("sockjs","sockjs",1,Me),Gc=I("xhr_streaming","xhr_streaming",1,Me,gt),Wf=I("xdr_streaming","xdr_streaming",1,Me,gt),Ko=I("xhr_polling","xhr_polling",1,Me),Vc=I("xdr_polling","xdr_polling",1,Me),qa=new mn([zt],Ke),Di=new mn([Dr],Ke),Yf=new mn([Kf],Ke),Oi=new mn([new ia(Ua(Gc),Gc,Wf)],Ke),Wo=new mn([new ia(Ua(Ko),Ko,Vc)],Ke),Yo=new mn([new ia(Ua(Oi),new An([Oi,new _i(Wo,{delay:4e3})]),Wo)],Ke),Li=new ia(Ua(Yo),Yo,Yf),Mi;return y.useTLS?Mi=new An([qa,new _i(Li,{delay:2e3})]):Mi=new An([qa,new _i(Di,{delay:2e3}),new _i(Li,{delay:5e3})]),new Oc(new ja(new ia(Ua(zt),Mi,Li)),O,{ttl:18e5,timeline:y.timeline,useTLS:y.useTLS})};const Ba=Lc;function Df(){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"),A.load(E.hooks.file,{useTLS:E.options.useTLS},function(y,C){E.hooks.isInitialized()?(E.changeState("initialized"),C(!0)):(y&&E.onError(y),E.onClose(),C(!1))})):E.onClose()}var Mc={getRequest:function(E){var y=new window.XDomainRequest;return y.ontimeout=function(){E.emit("error",new q),E.close()},y.onerror=function(C){E.emit("error",C),E.close()},y.onprogress=function(){y.responseText&&y.responseText.length>0&&E.onChunk(200,y.responseText)},y.onload=function(){y.responseText&&y.responseText.length>0&&E.onChunk(200,y.responseText),E.emit("finished",200),E.close()},y},abortRequest:function(E){E.ontimeout=E.onerror=E.onprogress=E.onload=null,E.abort()}};const $c=Mc,Ho=256*1024;class Of extends Ae{constructor(y,C,O){super(),this.hooks=y,this.method=C,this.url=O}start(y){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},je.addUnloadListener(this.unloader),this.xhr.open(this.method,this.url,!0),this.xhr.setRequestHeader&&this.xhr.setRequestHeader("Content-Type","application/json"),this.xhr.send(y)}close(){this.unloader&&(je.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(y,C){for(;;){var O=this.advanceBuffer(C);if(O)this.emit("chunk",{status:y,data:O});else break}this.isBufferTooLong(C)&&this.emit("buffer_too_long")}advanceBuffer(y){var C=y.slice(this.position),O=C.indexOf(` -`);return O!==-1?(this.position+=O+1,C.slice(0,O)):null}isBufferTooLong(y){return this.position===y.length&&y.length>Ho}}var zo;(function(E){E[E.CONNECTING=0]="CONNECTING",E[E.OPEN=1]="OPEN",E[E.CLOSED=3]="CLOSED"})(zo||(zo={}));const sr=zo;var Tr=1;class jo{constructor(y,C){this.hooks=y,this.session=ys(1e3)+"/"+Ic(8),this.location=Uo(C),this.readyState=sr.CONNECTING,this.openStream()}send(y){return this.sendRaw(JSON.stringify([y]))}ping(){this.hooks.sendHeartbeat(this)}close(y,C){this.onClose(y,C,!0)}sendRaw(y){if(this.readyState===sr.OPEN)try{return je.createSocketRequest("POST",sa(Pa(this.location,this.session))).start(y),!0}catch{return!1}else return!1}reconnect(){this.closeStream(),this.openStream()}onClose(y,C,O){this.closeStream(),this.readyState=sr.CLOSED,this.onclose&&this.onclose({code:y,reason:C,wasClean:O})}onChunk(y){if(y.status===200){this.readyState===sr.OPEN&&this.onActivity();var C,O=y.data.slice(0,1);switch(O){case"o":C=JSON.parse(y.data.slice(1)||"{}"),this.onOpen(C);break;case"a":C=JSON.parse(y.data.slice(1)||"[]");for(var I=0;I{this.onChunk(y)}),this.stream.bind("finished",y=>{this.hooks.onFinished(this,y)}),this.stream.bind("buffer_too_long",()=>{this.reconnect()});try{this.stream.start()}catch(y){Te.defer(()=>{this.onError(y),this.onClose(1006,"Could not start streaming",!1)})}}closeStream(){this.stream&&(this.stream.unbind_all(),this.stream.close(),this.stream=null)}}function Uo(E){var y=/([^\?]*)\/*(\??.*)/.exec(E);return{base:y[1],queryString:y[2]}}function Pa(E,y){return E.base+"/"+y+"/xhr_send"}function sa(E){var y=E.indexOf("?")===-1?"?":"&";return E+y+"t="+ +new Date+"&n="+Tr++}function Nc(E,y){var C=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(E);return C[1]+y+C[3]}function ys(E){return je.randomInt(E)}function Ic(E){for(var y=[],C=0;C0&&E.onChunk(C.status,C.responseText);break;case 4:C.responseText&&C.responseText.length>0&&E.onChunk(C.status,C.responseText),E.emit("finished",C.status),E.close();break}},C},abortRequest:function(E){E.onreadystatechange=null,E.abort()}};const bs=Po;var Hc={createStreamingSocket(E){return this.createSocket(Bo,E)},createPollingSocket(E){return this.createSocket(Vr,E)},createSocket(E,y){return new Ai(E,y)},createXHR(E,y){return this.createRequest(bs,E,y)},createRequest(E,y,C){return new Of(E,y,C)}};const Ti=Hc;Ti.createXDR=function(E,y){return this.createRequest($c,E,y)};var zc={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:m,DependenciesReceivers:_,getDefaultStrategy:Ba,Transports:_n,transportConnectionInitializer:Df,HTTPFactory:Ti,TimelineTransport:sn,getXHRAPI(){return window.XMLHttpRequest},getWebSocketAPI(){return window.WebSocket||window.MozWebSocket},setup(E){window.Pusher=E;var y=()=>{this.onDocumentBody(E.ready)};window.JSON?y():A.load("json2",{},y)},getDocument(){return document},getProtocol(){return this.getDocument().location.protocol},getAuthorizers(){return{ajax:qe,jsonp:pn}},onDocumentBody(E){document.body?E():setTimeout(()=>{this.onDocumentBody(E)},0)},createJSONPRequest(E,y){return new ir(E,y)},createScriptRequest(E){return new ra(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 $o},createWebSocket(E){var y=this.getWebSocketAPI();return new y(E)},createSocketRequest(E,y){if(this.isXHRSupported())return this.HTTPFactory.createXHR(E,y);if(this.isXDRSupported(y.indexOf("https:")===0))return this.HTTPFactory.createXDR(E,y);throw"Cross-origin HTTP requests are not supported"},isXHRSupported(){var E=this.getXHRAPI();return!!E&&new E().withCredentials!==void 0},isXDRSupported(E){var y=E?"https:":"http:",C=this.getProtocol();return!!window.XDomainRequest&&C===y},addUnloadListener(E){window.addEventListener!==void 0?window.addEventListener("unload",E,!1):window.attachEvent!==void 0&&window.attachEvent("onunload",E)},removeUnloadListener(E){window.addEventListener!==void 0?window.removeEventListener("unload",E,!1):window.detachEvent!==void 0&&window.detachEvent("onunload",E)},randomInt(E){return Math.floor(function(){return(window.crypto||window.msCrypto).getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}()*E)}};const je=zc;var kr;(function(E){E[E.ERROR=3]="ERROR",E[E.INFO=6]="INFO",E[E.DEBUG=7]="DEBUG"})(kr||(kr={}));const oa=kr;class Ri{constructor(y,C,O){this.key=y,this.session=C,this.events=[],this.options=O||{},this.sent=0,this.uniqueID=0}log(y,C){y<=this.options.level&&(this.events.push($e({},C,{timestamp:Te.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(y){this.log(oa.ERROR,y)}info(y){this.log(oa.INFO,y)}debug(y){this.log(oa.DEBUG,y)}isEmpty(){return this.events.length===0}send(y,C){var O=$e({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=[],y(O,(I,ne)=>{I||this.sent++,C&&C(I,ne)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class Lf{constructor(y,C,O,I){this.name=y,this.priority=C,this.transport=O,this.options=I||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(y,C){if(this.isSupported()){if(this.priority{O||(gt(),ne?ne.close():I.close())},forceMinPriority:zt=>{O||this.priority{var C="socket_id="+encodeURIComponent(E.socketId);for(var O in y.params)C+="&"+encodeURIComponent(O)+"="+encodeURIComponent(y.params[O]);if(y.paramsProvider!=null){let I=y.paramsProvider();for(var O in I)C+="&"+encodeURIComponent(O)+"="+encodeURIComponent(I[O])}return C},$f=E=>{if(typeof je.getAuthorizers()[E.transport]>"u")throw`'${E.transport}' is not a recognized auth transport`;return(y,C)=>{const O=Mf(y,E);je.getAuthorizers()[E.transport](je,O,E,R.UserAuthentication,C)}},Vo=(E,y)=>{var C="socket_id="+encodeURIComponent(E.socketId);C+="&channel_name="+encodeURIComponent(E.channelName);for(var O in y.params)C+="&"+encodeURIComponent(O)+"="+encodeURIComponent(y.params[O]);if(y.paramsProvider!=null){let I=y.paramsProvider();for(var O in I)C+="&"+encodeURIComponent(O)+"="+encodeURIComponent(I[O])}return C},Nf=E=>{if(typeof je.getAuthorizers()[E.transport]>"u")throw`'${E.transport}' is not a recognized auth transport`;return(y,C)=>{const O=Vo(y,E);je.getAuthorizers()[E.transport](je,O,E,R.ChannelAuthorization,C)}},If=(E,y,C)=>{const O={authTransport:y.transport,authEndpoint:y.endpoint,auth:{params:y.params,headers:y.headers}};return(I,ne)=>{const me=E.channel(I.channelName);C(me,O).authorize(I.socketId,ne)}};function Uc(E,y){let C={activityTimeout:E.activityTimeout||S.activityTimeout,cluster:E.cluster,httpPath:E.httpPath||S.httpPath,httpPort:E.httpPort||S.httpPort,httpsPort:E.httpsPort||S.httpsPort,pongTimeout:E.pongTimeout||S.pongTimeout,statsHost:E.statsHost||S.stats_host,unavailableTimeout:E.unavailableTimeout||S.unavailableTimeout,wsPath:E.wsPath||S.wsPath,wsPort:E.wsPort||S.wsPort,wssPort:E.wssPort||S.wssPort,enableStats:Uf(E),httpHost:Hf(E),useTLS:jf(E),wsHost:Bc(E),userAuthenticator:Fo(E),channelAuthorizer:Pf(E,y)};return"disabledTransports"in E&&(C.disabledTransports=E.disabledTransports),"enabledTransports"in E&&(C.enabledTransports=E.enabledTransports),"ignoreNullOrigin"in E&&(C.ignoreNullOrigin=E.ignoreNullOrigin),"timelineParams"in E&&(C.timelineParams=E.timelineParams),"nacl"in E&&(C.nacl=E.nacl),C}function Hf(E){return E.httpHost?E.httpHost:E.cluster?`sockjs-${E.cluster}.pusher.com`:S.httpHost}function Bc(E){return E.wsHost?E.wsHost:zf(E.cluster)}function zf(E){return`ws-${E}.pusher.com`}function jf(E){return je.getProtocol()==="https:"?!0:E.forceTLS!==!1}function Uf(E){return"enableStats"in E?E.enableStats:"disableStats"in E?!E.disableStats:!1}const Pc=E=>"customHandler"in E&&E.customHandler!=null;function Fo(E){const y=Object.assign(Object.assign({},S.userAuthentication),E.userAuthentication);return Pc(y)?y.customHandler:$f(y)}function Bf(E,y){let C;if("channelAuthorization"in E)C=Object.assign(Object.assign({},S.channelAuthorization),E.channelAuthorization);else if(C={transport:E.authTransport||S.authTransport,endpoint:E.authEndpoint||S.authEndpoint},"auth"in E&&("params"in E.auth&&(C.params=E.auth.params),"headers"in E.auth&&(C.headers=E.auth.headers)),"authorizer"in E)return{customHandler:If(y,C,E.authorizer)};return C}function Pf(E,y){const C=Bf(E,y);return Pc(C)?C.customHandler:Nf(C)}class qf extends Ae{constructor(y){super(function(C,O){tt.debug(`No callbacks on watchlist events for ${C}`)}),this.pusher=y,this.bindWatchlistInternalEvent()}handleEvent(y){y.data.events.forEach(C=>{this.emit(C.name,C)})}bindWatchlistInternalEvent(){this.pusher.connection.bind("message",y=>{var C=y.event;C==="pusher_internal:watchlist_events"&&this.handleEvent(y)})}}function qc(){let E,y;return{promise:new Promise((O,I)=>{E=O,y=I}),resolve:E,reject:y}}const Gf=qc;class Vf extends Ae{constructor(y){super(function(C,O){tt.debug("No callbacks on user for "+C)}),this.signin_requested=!1,this.user_data=null,this.serverToUserChannel=null,this.signinDonePromise=null,this._signinDoneResolve=null,this._onAuthorize=(C,O)=>{if(C){tt.warn(`Error during signin: ${C}`),this._cleanup();return}this.pusher.send_event("pusher:signin",{auth:O.auth,user_data:O.user_data})},this.pusher=y,this.pusher.connection.bind("state_change",({previous:C,current:O})=>{C!=="connected"&&O==="connected"&&this._signin(),C==="connected"&&O!=="connected"&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new qf(y),this.pusher.connection.bind("message",C=>{var O=C.event;O==="pusher:signin_success"&&this._onSigninSuccess(C.data),this.serverToUserChannel&&this.serverToUserChannel.name===C.channel&&this.serverToUserChannel.handleEvent(C)})}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(y){try{this.user_data=JSON.parse(y.user_data)}catch{tt.error(`Failed parsing user data after signin: ${y.user_data}`),this._cleanup();return}if(typeof this.user_data.id!="string"||this.user_data.id===""){tt.error(`user_data doesn't contain an id. user_data: ${this.user_data}`),this._cleanup();return}this._signinDoneResolve(),this._subscribeChannels()}_subscribeChannels(){const y=C=>{C.subscriptionPending&&C.subscriptionCancelled?C.reinstateSubscription():!C.subscriptionPending&&this.pusher.connection.state==="connected"&&C.subscribe()};this.serverToUserChannel=new Gr(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((C,O)=>{C.indexOf("pusher_internal:")===0||C.indexOf("pusher:")===0||this.emit(C,O)}),y(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:y,resolve:C}=Gf();y.done=!1;const O=()=>{y.done=!0};y.then(O).catch(O),this.signinDonePromise=y,this._signinDoneResolve=C}}class on{static ready(){on.isReady=!0;for(var y=0,C=on.instances.length;yje.getDefaultStrategy(this.config,I,ki);this.connection=Nn.createConnectionManager(this.key,{getStrategy:O,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 ne=I.event,me=ne.indexOf("pusher_internal:")===0;if(I.channel){var Me=this.channel(I.channel);Me&&Me.handleEvent(I)}me||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=>{tt.warn(I)}),on.instances.push(this),this.timeline.info({instances:on.instances.length}),this.user=new Vf(this),on.isReady&&this.connect()}switchCluster(y){const{appKey:C,cluster:O}=y;this.key=C,this.options=Object.assign(Object.assign({},this.options),{cluster:O}),this.config=Uc(this.options,this),this.connection.switchCluster(this.key)}channel(y){return this.channels.find(y)}allChannels(){return this.channels.all()}connect(){if(this.connection.connect(),this.timelineSender&&!this.timelineSenderTimer){var y=this.connection.isUsingTLS(),C=this.timelineSender;this.timelineSenderTimer=new xe(6e4,function(){C.send(y)})}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(y,C,O){return this.global_emitter.bind(y,C,O),this}unbind(y,C,O){return this.global_emitter.unbind(y,C,O),this}bind_global(y){return this.global_emitter.bind_global(y),this}unbind_global(y){return this.global_emitter.unbind_global(y),this}unbind_all(y){return this.global_emitter.unbind_all(),this}subscribeAll(){var y;for(y in this.channels.channels)this.channels.channels.hasOwnProperty(y)&&this.subscribe(y)}subscribe(y){var C=this.channels.add(y,this);return C.subscriptionPending&&C.subscriptionCancelled?C.reinstateSubscription():!C.subscriptionPending&&this.connection.state==="connected"&&C.subscribe(),C}unsubscribe(y){var C=this.channels.find(y);C&&C.subscriptionPending?C.cancelSubscription():(C=this.channels.remove(y),C&&C.subscribed&&C.unsubscribe())}send_event(y,C,O){return this.connection.send_event(y,C,O)}shouldUseTLS(){return this.config.useTLS}signin(){this.user.signin()}}on.instances=[],on.isReady=!1,on.logToConsole=!1,on.Runtime=je,on.ScriptReceivers=je.ScriptReceivers,on.DependenciesReceivers=je.DependenciesReceivers,on.auth_callbacks=je.auth_callbacks;const ws=on;function Ff(E){if(E==null)throw"You must pass your app key when you instantiate Pusher."}je.setup(on)}},a={};function i(c){var d=a[c];if(d!==void 0)return d.exports;var f=a[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})())})(bf)),bf.exports}var q_=P_();const dy=Jr(q_),Ut=ut("WebSocketManager");class G_{constructor(){$(this,"echo",null);$(this,"subscriptions",new Map);$(this,"initialized",!1);$(this,"config",null)}configure(e){if(this.initialized){Ut.warn("[WebSocketManager] 이미 초기화되어 설정을 변경할 수 없습니다.");return}this.config=e,Ut.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){Ut.warn("[WebSocketManager] WebSocket 설정이 없습니다. initTemplateApp에서 websocket 옵션을 전달해주세요.");return}const{appKey:e,host:n="localhost",port:a=80,scheme:i="https",authEndpoint:l="/api/broadcasting/auth"}=this.config,c=Number(a)||80,d=i==="https";Ut.log("[WebSocketManager] 연결 설정:",{host:n,port:c,scheme:i,useTLS:d,authEndpoint:l}),window.Pusher=dy;const f=localStorage.getItem("auth_token"),g={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"}}};Ut.log("[WebSocketManager] Pusher 옵션:",g);const m=new dy(e,g);m.connection.bind("connecting",()=>{Ut.log("[WebSocketManager] 연결 시도 중...")}),m.connection.bind("connected",()=>{Ut.log("[WebSocketManager] 연결 성공! Socket ID:",m.connection.socket_id)}),m.connection.bind("failed",()=>{Ut.error("[WebSocketManager] 연결 실패 - WebSocket을 사용할 수 없습니다.")}),m.connection.bind("error",b=>{Ut.error("[WebSocketManager] 연결 오류:",b)}),m.connection.bind("state_change",b=>{Ut.log(`[WebSocketManager] 상태 변경: ${b.previous} → ${b.current}`)}),m.connection.bind("unavailable",()=>{Ut.error("[WebSocketManager] WebSocket 사용 불가 - 연결할 수 없습니다.")}),m.connection.bind("disconnected",()=>{Ut.warn("[WebSocketManager] 연결이 끊어졌습니다.")}),Ut.log("[WebSocketManager] 초기 연결 상태:",m.connection.state),this.echo=new B_({broadcaster:"reverb",client:m}),Ut.log("[WebSocketManager] 연결 시작 시도..."),m.connect(),window.Echo=this.echo,this.initialized=!0,Ut.log("[WebSocketManager] Echo 초기화 완료")}subscribe(e,n,a,i={}){if(this.initialize(),!this.echo)return Ut.warn("[WebSocketManager] Echo가 초기화되지 않았습니다."),"";const{channelType:l="private"}=i,c=`${e}:${n}`;if(this.subscriptions.has(c))return Ut.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}`,a),this.subscriptions.set(c,d),Ut.log(`[WebSocketManager] 구독 완료: ${c} (${l})`),c}unsubscribe(e){const n=this.subscriptions.get(e);if(!n)return;const a=e.lastIndexOf(":"),i=a>=0?e.substring(a+1):"";if(i)try{n.stopListening(`.${i}`)}catch(l){Ut.warn(`[WebSocketManager] stopListening 실패: ${e}`,l)}this.subscriptions.delete(e),Ut.log(`[WebSocketManager] 구독 해제: ${e}`)}leaveChannel(e){if(!this.echo)return;this.echo.leave(e);const n=[];this.subscriptions.forEach((a,i)=>{i.startsWith(`${e}:`)&&n.push(i)}),n.forEach(a=>this.subscriptions.delete(a)),Ut.log(`[WebSocketManager] 채널 구독 해제: ${e}`)}disconnect(){this.echo&&(this.echo.disconnect(),this.subscriptions.clear(),this.initialized=!1,Ut.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 G_,yt=ut("DataSourceManager"),fy=new xn;function Sc(o,e){const n=Aa(o);if(n!==null)try{return Pn(n)?fy.evaluatePipeExpression(n,e,{skipCache:!0}):fy.evaluateExpression(n,e)}catch(a){return yt.error("Failed to evaluate param expression:",n,a),o}return ns(o,e,{skipCache:!0})}function hy(o){const e={};for(const n of o.keys()){if(n in e)continue;const a=o.getAll(n);a.length>1?e[n]=a:a.length===1&&(n.endsWith("[]")?e[n]=a:e[n]=a[0])}return e}function V_(){try{return window.G7Core?.devTools}catch{return}}const _c=class _c{constructor(e={}){$(this,"options");$(this,"dataCache",new Map);$(this,"bindingEngine");$(this,"globalHeaders",[]);this.options=e,this.bindingEngine=new xn}setGlobalHeaders(e){this.globalHeaders=e||[]}matchesPattern(e,n){if(n==="*")return!0;const a=n.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${a}$`).test(e)}toFormData(e){const n=new FormData;for(const[a,i]of Object.entries(e))i instanceof File||i instanceof Blob?n.append(a,i):i!=null&&n.append(a,typeof i=="object"?JSON.stringify(i):String(i));return n}getMatchingGlobalHeaders(e,n){const a={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,c])=>{const d=Sc(c,n);d!=null&&d!==""&&(a[l]=String(d))});return a}filterByCondition(e,n={}){const a=new Set,i=[];for(const l of e){if(a.has(l.id))continue;if(!l.if&&!l.conditions){a.add(l.id),i.push(l);continue}ts({if:l.if,conditions:l.conditions},n,this.bindingEngine,`data_source:${l.id}`)&&(a.add(l.id),i.push(l))}return i}checkErrorCondition(e,n){if(!e.errorCondition?.if||e.errorCondition?.errorCode===void 0)return null;try{const a={response:n};if(ts({if:e.errorCondition.if},a,this.bindingEngine,`errorCondition:${e.id}`))return yt.log(`errorCondition matched for ${e.id}, triggering error ${e.errorCondition.errorCode}`),e.errorCondition.errorCode}catch(a){yt.error(`Failed to evaluate errorCondition for ${e.id}:`,a)}return null}async fetchDataSources(e,n={},a=new URLSearchParams,i,l){const c={},d=!!this.options.sampleProvider,f=e.filter(g=>(d||g.auto_fetch!==!1)&&g.type!=="websocket");return await Promise.all(f.map(async g=>{try{const m=await this.fetchDataSource(g,n,a,i,l);c[g.id]=m,this.dataCache.set(g.id,{data:m,timestamp:Date.now()});const b=this.checkErrorCondition(g,m);if(b!==null){const S={status:b,message:`Error condition matched for ${g.id}`,data:m},v=vr(),_=v.resolve(b,{errorHandling:g.errorHandling,onError:g.onError});if(_.handler)try{await v.execute(_.handler,S)}catch(A){yt.error(`Error executing errorCondition handler for ${g.id}:`,A)}g.fallback!==void 0&&(c[g.id]=g.fallback,this.dataCache.set(g.id,{data:g.fallback,timestamp:Date.now()}),yt.log(`Using fallback data for ${g.id} (errorCondition)`));return}if(g.onSuccess)try{const S={data:m,sourceId:g.id};await this.executeOnSuccessHandler(g.onSuccess,S)}catch(S){yt.error(`Error executing onSuccess handler for ${g.id}:`,S)}}catch(m){yt.error(`Failed to fetch data source: ${g.id}`,m);const b=m?.response?.status||m?.status||500,S=m?.response?.data,v=S?.message||m.message||"Unknown error",_={status:b,message:v,errors:S?.errors,data:S,statusText:m?.response?.statusText},A=vr(),x=A.resolve(b,{errorHandling:g.errorHandling,onError:g.onError});if(x.handler)try{await A.execute(x.handler,_)}catch(L){yt.error(`Error executing error handler for ${g.id}:`,L)}g.fallback!==void 0&&(c[g.id]=g.fallback,this.dataCache.set(g.id,{data:g.fallback,timestamp:Date.now()}),yt.log(`Using fallback data for ${g.id}`)),this.options.onError&&this.options.onError(m,g)}})),c}async fetchDataSourcesWithResults(e,n={},a=new URLSearchParams,i,l,c){if(e.some(m=>m.type==="websocket")){const m=e.filter(b=>b.type==="websocket").map(b=>b.id).join(", ");yt.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 b=await this.fetchDataSource(m,n,a,i,l);this.dataCache.set(m.id,{data:b,timestamp:Date.now()});const S=this.checkErrorCondition(m,b);if(S!==null){const v={status:S,message:`Error condition matched for ${m.id}`,data:b},_=vr(),A=_.resolve(S,{errorHandling:m.errorHandling,onError:m.onError});let x=!1;if(A.handler)if(m.loading_strategy==="blocking")_.execute(A.handler,v).catch(L=>{yt.error(`Error executing errorCondition handler for ${m.id}:`,L)}),x=!0;else try{await _.execute(A.handler,v),x=!0}catch(L){yt.error(`Error executing errorCondition handler for ${m.id}:`,L)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),yt.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: ${S}`),errorCode:S,errorHandled:x}}if(m.onSuccess)try{const v={data:b,sourceId:m.id};await this.executeOnSuccessHandler(m.onSuccess,v)}catch(v){yt.error(`Error executing onSuccess handler for ${m.id}:`,v)}return{id:m.id,state:"success",data:b}}catch(b){yt.error(`Failed to fetch data source: ${m.id}`,b);const S=b?.response?.status||b?.status||500,v=b?.response?.data,_=v?.message||b.message||"Unknown error",A={status:S,message:_,errors:v?.errors,data:v,statusText:b?.response?.statusText},x=vr(),L=x.resolve(S,{errorHandling:m.errorHandling,onError:m.onError});let M=!1;if(L.handler)if(m.loading_strategy==="blocking")x.execute(L.handler,A).catch(R=>{yt.error(`Error executing error handler for ${m.id}:`,R)}),M=!0;else try{await x.execute(L.handler,A),M=!0}catch(R){yt.error(`Error executing error handler for ${m.id}:`,R)}return m.fallback!==void 0?(this.dataCache.set(m.id,{data:m.fallback,timestamp:Date.now()}),yt.log(`Using fallback data for ${m.id}`),{id:m.id,state:"success",data:m.fallback}):(this.options.onError&&this.options.onError(b,m),{id:m.id,state:"error",error:b,errorCode:S,errorHandled:M})}}))}fetchDataSourcesInBackground(e,n={},a=new URLSearchParams,i){e.filter(c=>c.auto_fetch!==!1&&c.loading_strategy==="background"&&c.type!=="websocket").forEach(c=>{this.fetchDataSource(c,n,a).then(async d=>{this.dataCache.set(c.id,{data:d,timestamp:Date.now()});const f=this.checkErrorCondition(c,d);if(f!==null){const g={status:f,message:`Error condition matched for ${c.id}`,data:d},m=vr(),b=m.resolve(f,{errorHandling:c.errorHandling,onError:c.onError});if(b.handler)try{await m.execute(b.handler,g)}catch(S){yt.error(`Error executing errorCondition handler for ${c.id}:`,S)}c.fallback!==void 0&&(this.dataCache.set(c.id,{data:c.fallback,timestamp:Date.now()}),yt.log(`Using fallback data for ${c.id} (errorCondition)`),i&&i(c.id,c.fallback));return}if(c.onSuccess)try{const g={data:d,sourceId:c.id};await this.executeOnSuccessHandler(c.onSuccess,g)}catch(g){yt.error(`Error executing onSuccess handler for ${c.id}:`,g)}i&&i(c.id,d)}).catch(async d=>{yt.error(`Background fetch failed: ${c.id}`,d);const f=d?.response?.status||d?.status||500,g=d?.response?.data,m=g?.message||d.message||"Unknown error",b={status:f,message:m,errors:g?.errors,data:g,statusText:d?.response?.statusText},S=vr(),v=S.resolve(f,{errorHandling:c.errorHandling,onError:c.onError});if(v.handler)try{await S.execute(v.handler,b)}catch(_){yt.error(`Error executing error handler for ${c.id}:`,_)}if(c.fallback!==void 0){this.dataCache.set(c.id,{data:c.fallback,timestamp:Date.now()}),yt.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,a,i,l){switch(e.type){case"api":return this.fetchApiDataSource(e,n,a,i,l);case"static":return e.data;case"route_params":return n;case"query_params":return hy(a);default:throw new Error(`Unknown data source type: ${e.type}`)}}async fetchApiDataSource(e,n,a,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:hy(a)};i&&(c._global=i),l&&(c._local=l);let d=ns(e.endpoint,c,{skipCache:!0});const f=e.method||"GET",m=(e.contentType?typeof e.contentType=="string"&&e.contentType.includes("{{")?ns(e.contentType,c,{skipCache:!0}):e.contentType:"application/json")==="multipart/form-data";let b=m?{...e.params||{}}:JSON.parse(JSON.stringify(e.params||{}));Object.entries(b).forEach(([_,A])=>{typeof A=="string"&&(b[_]=Sc(A,c))}),Object.keys(b).forEach(_=>{b[_]===""&&delete b[_]});const S=V_();let v=null;if(S?.isEnabled()){S.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(b).length>0){const A=new URLSearchParams;Object.entries(b).forEach(([L,M])=>{Array.isArray(M)?M.forEach(R=>A.append(L,String(R))):M!=null&&A.append(L,String(M))});const x=A.toString();_=x?`${d}?${x}`:d}v=S.trackRequest(_,f,{requestBody:f!=="GET"?b:void 0,dataSourceId:e.id}),S.trackDataSourceLoading(e.id)}try{let _;const A=e.auth_mode??(e.auth_required===!0?"required":"none"),x=yr.getInstance().isAuthenticated();if(A==="required"&&!x){yt.log(`[DataSourceManager] Skipping ${e.id}: auth_mode is 'required' but no token available`),S?.isEnabled()&&(S.trackDataSourceError(e.id,"Skipped: auth_mode required but not authenticated"),v&&S.failRequest(v,"Skipped: not authenticated"));const M=new Error("Auth required but not authenticated");throw M.response={status:401,statusText:"Unauthorized",data:null},M.status=401,M._authSkipped=!0,M}const L=A==="required"||A==="optional"&&x;if(L){const M=Ir(),R=d.startsWith("/api/")?d.substring(4):d.startsWith("/api")?d.substring(4)||"/":d;this.options.onError&&yt.log(`[DataSourceManager] Normalized endpoint: ${d} -> ${R}`);const D=this.getMatchingGlobalHeaders(d,c),B={};e.headers&&Object.entries(e.headers).forEach(([ge,Ee])=>{const Se=Sc(Ee,c);Se!=null&&Se!==""&&(B[ge]=String(Se))});const q={...D,...B},P=Object.keys(q).length>0,K=m?this.toFormData(b):b;switch(f){case"GET":_=await M.get(R,{params:b,...P&&{headers:q}});break;case"POST":P?_=await M.post(R,K,{headers:q}):_=await M.post(R,K);break;case"PUT":P?_=await M.put(R,K,{headers:q}):_=await M.put(R,K);break;case"PATCH":P?_=await M.patch(R,K,{headers:q}):_=await M.patch(R,K);break;case"DELETE":_=await M.delete(R,{params:b,...P&&{headers:q}});break;default:throw new Error(`Unsupported HTTP method: ${f}`)}}else{let M=d;if(f==="GET"){const K=new URLSearchParams(b).toString();M=K?`${d}?${K}`:d}const R={...m?{}:{"Content-Type":"application/json"},Accept:"application/json"};if(typeof window<"u"){const K=localStorage.getItem("g7_locale");K&&(R["Accept-Language"]=K)}const D=this.getMatchingGlobalHeaders(d,c);Object.assign(R,D),e.headers&&Object.entries(e.headers).forEach(([K,ge])=>{const Ee=Sc(ge,c);Ee!=null&&Ee!==""&&(R[K]=String(Ee))});let B;f!=="GET"&&(m?(B=this.toFormData(b),delete R["Content-Type"]):B=JSON.stringify(b));const q=await fetch(M,{method:f,headers:R,body:B});let P;try{P=await q.json()}catch{P=null}if(v&&S?.isEnabled()&&(S.completeRequest(v,q.status,P),v=null),!q.ok){S?.isEnabled()&&S.trackDataSourceError(e.id,`HTTP ${q.status}: ${q.statusText}`);const K=new Error(`HTTP error! status: ${q.status}`);throw K.response={status:q.status,statusText:q.statusText,data:P},K.status=q.status,K}_=P,S?.isEnabled()&&S.trackDataSourceLoaded(e.id,_)}return L&&v&&S?.isEnabled()&&(S.completeRequest(v,200,_),S.trackDataSourceLoaded(e.id,_)),_}catch(_){if(v&&S?.isEnabled()){const A=_;A?.response?S.completeRequest(v,A.response.status,A.response.data):S.failRequest(v,_ instanceof Error?_.message:String(_)),S.trackDataSourceError(e.id,_ instanceof Error?_.message:String(_))}throw _}}getCachedData(e){const n=this.dataCache.get(e);if(!n)return;if(Date.now()-n.timestamp>_c.DATA_CACHE_TTL){this.dataCache.delete(e);return}return n.data}clearCache(){this.dataCache.clear()}subscribeWebSockets(e,n,a={}){const i=[],l=e.filter(c=>c.type==="websocket");return l.length===0||l.forEach(c=>{if(!c.channel||!c.event){yt.warn(`WebSocket source ${c.id} missing channel or event`);return}let d,f;try{d=ns(c.channel,a,{skipCache:!0}),f=ns(c.event,a,{skipCache:!0})}catch(b){yt.error(`Failed to resolve WebSocket channel/event for source ${c.id}:`,b);return}const g=b=>!!(!b||b.trim()===""||b.includes("{{")||b.endsWith(".")||b.endsWith(":")||b.startsWith(".")||b.startsWith(":")||b.includes("..")||b.includes("::"));if(g(d)||g(f)){yt.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(a).join(", ")}]`);return}const m=vc.subscribe(d,f,b=>{const S=c.target_source||c.id;this.dataCache.set(S,{data:b,timestamp:Date.now()}),n(S,b)},{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 a=this.options.actionDispatcher??um();if(!a){yt.warn("ActionDispatcher not available, skipping onSuccess handler");return}const i=Array.isArray(e)?e:[e];for(const l of i)try{await a.dispatchAction({type:"click",...l},{data:{response:n}})}catch(c){throw yt.error("Failed to execute onSuccess handler:",c),c}}};$(_c,"DATA_CACHE_TTL",3e5);let Er=_c;const F_=new Er,yi=ut("ModalDataSourceWrapper");function K_(o,e){if(!o||!e)return o;const a=e.replace(/\?\./g,".").split(/\.(?![^\[]*\])/).flatMap(l=>{const c=l.match(/^([^\[]*)((?:\[\d+\])*)$/);if(c){const[,d,f]=c,g=[];d&&g.push(d);const m=f.match(/\[\d+\]/g);return m&&g.push(...m),g}return[l]}).filter(l=>l!=="");let i=o;for(const l of a){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 gy=({isOpen:o,modalId:e,dataSources:n,dataContext:a,globalStateUpdater:i,bindingEngine:l,debug:c=!1,children:d})=>{const[f,g]=N.useState(!1),[m,b]=N.useState(!1),S=N.useRef(!1),v=N.useRef(null);v.current||(v.current=new Er);const _=N.useCallback(async()=>{if(!(!n||n.length===0)&&v.current){g(!0);try{const A=a.route||{},x=new URLSearchParams(window.location.search),L=n.map(R=>{let D={...R};if(R.endpoint&&l){const B=l.resolveBindings(R.endpoint,a,{skipCache:!0});D.endpoint=B}if(R.params&&l){const B={};Object.entries(R.params).forEach(([q,P])=>{typeof P=="string"?B[q]=l.resolveBindings(P,a,{skipCache:!0}):B[q]=P}),D.params=B}return D});c&&yi.log(`[ModalDataSourceWrapper] Modal "${e}" fetching data sources:`,L.map(R=>({id:R.id,endpoint:R.endpoint})));const M=await v.current.fetchDataSourcesWithResults(L,A,x);i&&M.forEach(R=>{if(R.state==="success"&&R.data!==void 0){const D=L.find(B=>B.id===R.id);if(D?.initGlobal){const B=R.data?.data??R.data,q=Array.isArray(D.initGlobal)?D.initGlobal:[D.initGlobal];for(const P of q)if(typeof P=="string")i({[P]:B}),c&&yi.log(`[ModalDataSourceWrapper] Modal "${e}" initGlobal: ${R.id}.data -> _global.${P}`);else if(typeof P=="object"&&P.key){const{key:K,path:ge}=P,Ee=ge?K_(B,ge):B;i({[K]:Ee}),c&&yi.log(`Modal "${e}" initGlobal: ${R.id}.data${ge?"."+ge:""} -> _global.${K}`)}}}else R.state==="error"&&yi.error(`Modal "${e}" data source error:`,R.id,R.error)}),c&&yi.log(`Modal "${e}" data sources fetched successfully`)}catch(A){yi.error(`Modal "${e}" data source fetch error:`,A)}finally{g(!1),b(!0)}}},[n,a,i,l,e,c]);return N.useEffect(()=>{if(!n||n.length===0)return;const A=window.__templateApp;return A?.registerModalDataSources&&A.registerModalDataSources(e,n),()=>{A?.unregisterModalDataSources&&A.unregisterModalDataSources(e)}},[e,n]),N.useEffect(()=>{!o&&S.current&&(b(!1),c&&yi.log(`[ModalDataSourceWrapper] Modal "${e}" closed, reset fetch state`)),o&&!S.current&&n&&n.length>0&&!m&&_(),S.current=o},[o,n,m,_,e,c]),dt.jsx(dt.Fragment,{children:d})};class wc extends Error{constructor(n,a,i={}){super(a);$(this,"code");$(this,"userMessageKey");$(this,"showStack");$(this,"icon");$(this,"recoverable");this.name="TemplateEngineError",this.code=n,this.userMessageKey=a,this.showStack=i.showStack??!0,this.icon=i.icon??"fa-circle-exclamation",this.recoverable=i.recoverable??!0,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}getUserMessage(n,a){if(!a||!n)return this.userMessageKey;try{return a.translate(this.userMessageKey,n)}catch{return this.userMessageKey}}}class W_ 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 py(o){if(o instanceof wc)return o;if(o instanceof Error){const e=new wc("TEMPLATE_INIT_ERROR",o.message||"$t:core.errors.template_init_error",{showStack:!0,icon:"fa-circle-exclamation",recoverable:!0});return e.stack=o.stack,e}return new wc("TEMPLATE_INIT_ERROR","$t:core.errors.template_init_error",{showStack:!1,icon:"fa-circle-exclamation",recoverable:!0})}const Y_=ut("ErrorDisplay");class vf{static render(e,n){const a=document.getElementById(e);if(!a){Y_.error(`Container #${e} not found`);return}const i=n.debug&&n.showStack&&n.stackTrace,l=window.matchMedia("(prefers-color-scheme: dark)").matches,c={container:` + `,Fn.error("Error state rendered:",i,a)}getCurrentLayout(){return this.currentLayout}clear(){this.currentLayout=null,this.layoutCache.clear(),Fn.log("Layout data and cache cleared")}}const c_=ut("TranslationContext"),lf=N.createContext(null),_c=({children:o,translationEngine:e,translationContext:r})=>{const a=N.useMemo(()=>(l,c)=>{if(c){const d="|"+Object.entries(c).map(([f,g])=>`${f}=${g}`).join("|");return e.translate(l,r,d)}return e.translate(l,r)},[e,r]),i=N.useMemo(()=>({translationEngine:e,translationContext:r,t:a}),[e,r,a]);return dt.jsx(lf.Provider,{value:i,children:o})},Xm=()=>{const o=N.useContext(lf);return o||(c_.warn("TranslationProvider 외부에서 호출되었습니다. 키를 그대로 반환합니다."),{t:e=>e,translationEngine:null,translationContext:null})},$a=ut("SlotContext"),u_={registerToSlot:()=>{$a.warn("SlotContext not available: registerToSlot called outside SlotProvider")},unregisterFromSlot:()=>{$a.warn("SlotContext not available: unregisterFromSlot called outside SlotProvider")},getSlotComponents:()=>[],subscribeToSlot:()=>()=>{},clearAllSlots:()=>{},isEnabled:!1},d_=N.createContext(u_),cf=({children:o})=>{const e=N.useRef(new Map),r=N.useRef(new Map),a=N.useCallback(m=>{const y=r.current.get(m);y&&y.forEach(w=>{try{w()}catch(S){$a.error(`Slot subscriber error (slotId: ${m}):`,S)}})},[]),i=N.useCallback((m,y,w)=>{if(!m||!y){$a.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===w.registrationKey||(S.set(y,w),$a.log(`Component registered to slot: ${y} -> ${m} (order: ${w.order})`),a(m))},[a]),l=N.useCallback((m,y)=>{const w=e.current.get(m);w&&w.has(y)&&(w.delete(y),$a.log(`Component unregistered from slot: ${y} <- ${m}`),w.size===0&&e.current.delete(m),a(m))},[a]),c=N.useCallback(m=>{const y=e.current.get(m);return y?Array.from(y.values()).sort((w,S)=>w.order-S.order):[]},[]),d=N.useCallback((m,y)=>{r.current.has(m)||r.current.set(m,new Set);const w=r.current.get(m);return w.add(y),()=>{w.delete(y),w.size===0&&r.current.delete(m)}},[]),f=N.useCallback(()=>{e.current.forEach((m,y)=>{a(y)}),e.current.clear(),r.current.clear(),$a.log("All slots cleared")},[a]),g=N.useMemo(()=>({registerToSlot:i,unregisterFromSlot:l,getSlotComponents:c,subscribeToSlot:d,clearAllSlots:f,isEnabled:!0}),[i,l,c,d,f]);return N.useLayoutEffect(()=>{typeof window<"u"&&(window.__slotContextValue=g,$a.log("SlotContext exposed to window.__slotContextValue"))},[g]),dt.jsx(d_.Provider,{value:g,children:o})};class uf{constructor(){this.notificationCreatedEvent=".Illuminate\\Notifications\\Events\\BroadcastNotificationCreated"}listenForWhisper(e,r){return this.listen(".client-"+e,r)}notification(e){return this.listen(this.notificationCreatedEvent,e)}stopListeningForNotification(e){return this.stopListening(this.notificationCreatedEvent,e)}stopListeningForWhisper(e,r){return this.stopListening(".client-"+e,r)}}class Jm{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 f_(o){try{new o}catch(e){if(e instanceof Error&&e.message.includes("is not a constructor"))return!1}return!0}class df extends uf{constructor(e,r,a){super(),this.name=r,this.pusher=e,this.options=a,this.eventFormatter=new Jm(this.options.namespace),this.subscribe()}subscribe(){this.subscription=this.pusher.subscribe(this.name)}unsubscribe(){this.pusher.unsubscribe(this.name)}listen(e,r){return this.on(this.eventFormatter.format(e),r),this}listenToAll(e){return this.subscription.bind_global((r,a)=>{if(r.startsWith("pusher:"))return;let i=String(this.options.namespace??"").replace(/\./g,"\\"),l=r.startsWith(i)?r.substring(i.length+1):"."+r;e(l,a)}),this}stopListening(e,r){return r?this.subscription.unbind(this.eventFormatter.format(e),r):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",r=>{e(r)}),this}on(e,r){return this.subscription.bind(e,r),this}}class Qm extends df{whisper(e,r){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,r),this}}class h_ extends df{whisper(e,r){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,r),this}}class g_ extends Qm{here(e){return this.on("pusher:subscription_succeeded",r=>{e(Object.keys(r.members).map(a=>r.members[a]))}),this}joining(e){return this.on("pusher:member_added",r=>{e(r.info)}),this}whisper(e,r){return this.pusher.channels.channels[this.name].trigger(`client-${e}`,r),this}leaving(e){return this.on("pusher:member_removed",r=>{e(r.info)}),this}}class Zm extends uf{constructor(e,r,a){super(),this.events={},this.listeners={},this.name=r,this.socket=e,this.options=a,this.eventFormatter=new Jm(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,r){return this.on(this.eventFormatter.format(e),r),this}stopListening(e,r){return this.unbindEvent(this.eventFormatter.format(e),r),this}subscribed(e){return this.on("connect",r=>{e(r)}),this}error(e){return this}on(e,r){return this.listeners[e]=this.listeners[e]||[],this.events[e]||(this.events[e]=(a,i)=>{this.name===a&&this.listeners[e]&&this.listeners[e].forEach(l=>l(i))},this.socket.on(e,this.events[e])),this.listeners[e].push(r),this}unbind(){Object.keys(this.events).forEach(e=>{this.unbindEvent(e)})}unbindEvent(e,r){this.listeners[e]=this.listeners[e]||[],r&&(this.listeners[e]=this.listeners[e].filter(a=>a!==r)),(!r||this.listeners[e].length===0)&&(this.events[e]&&(this.socket.removeListener(e,this.events[e]),delete this.events[e]),delete this.listeners[e])}}class ey extends Zm{whisper(e,r){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:r}),this}}class p_ extends ey{here(e){return this.on("presence:subscribed",r=>{e(r.map(a=>a.user_info))}),this}joining(e){return this.on("presence:joining",r=>e(r.user_info)),this}whisper(e,r){return this.socket.emit("client event",{channel:this.name,event:`client-${e}`,data:r}),this}leaving(e){return this.on("presence:leaving",r=>e(r.user_info)),this}}class Ac extends uf{subscribe(){}unsubscribe(){}listen(e,r){return this}listenToAll(e){return this}stopListening(e,r){return this}subscribed(e){return this}error(e){return this}on(e,r){return this}}class ty extends Ac{whisper(e,r){return this}}class m_ extends Ac{whisper(e,r){return this}}class y_ extends ty{here(e){return this}joining(e){return this}whisper(e,r){return this}leaving(e){return this}}const ny=class NS{constructor(e){this.setOptions(e),this.connect()}setOptions(e){this.options={...NS._defaultOptions,...e,broadcaster:e.broadcaster};let r=this.csrfToken();r&&(this.options.auth.headers["X-CSRF-TOKEN"]=r,this.options.userAuthentication.headers["X-CSRF-TOKEN"]=r),r=this.options.bearerToken,r&&(this.options.auth.headers.Authorization="Bearer "+r,this.options.userAuthentication.headers.Authorization="Bearer "+r)}csrfToken(){var e,r;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"?((r=document.querySelector('meta[name="csrf-token"]'))==null?void 0:r.getAttribute("content"))??null:null}};ny._defaultOptions={auth:{headers:{}},authEndpoint:"/broadcasting/auth",userAuthentication:{endpoint:"/broadcasting/user-auth",headers:{}},csrfToken:null,bearerToken:null,host:null,key:null,namespace:"App.Events"};let ff=ny;class xc extends ff{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,r,a){return this.channel(e).listen(r,a)}channel(e){return this.channels[e]||(this.channels[e]=new df(this.pusher,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new Qm(this.pusher,"private-"+e,this.options)),this.channels["private-"+e]}encryptedPrivateChannel(e){return this.channels["private-encrypted-"+e]||(this.channels["private-encrypted-"+e]=new h_(this.pusher,"private-encrypted-"+e,this.options)),this.channels["private-encrypted-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new g_(this.pusher,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"private-encrypted-"+e,"presence-"+e].forEach(r=>{this.leaveChannel(r)})}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 b_ extends ff{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(r=>{r.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,r,a){return this.channel(e).listen(r,a)}channel(e){return this.channels[e]||(this.channels[e]=new Zm(this.socket,e,this.options)),this.channels[e]}privateChannel(e){return this.channels["private-"+e]||(this.channels["private-"+e]=new ey(this.socket,"private-"+e,this.options)),this.channels["private-"+e]}presenceChannel(e){return this.channels["presence-"+e]||(this.channels["presence-"+e]=new p_(this.socket,"presence-"+e,this.options)),this.channels["presence-"+e]}leave(e){[e,"private-"+e,"presence-"+e].forEach(r=>{this.leaveChannel(r)})}leaveChannel(e){this.channels[e]&&(this.channels[e].unsubscribe(),delete this.channels[e])}socketId(){return this.socket.id}disconnect(){this.socket.disconnect()}}class ry extends ff{constructor(){super(...arguments),this.channels={}}connect(){}listen(e,r,a){return new Ac}channel(e){return new Ac}privateChannel(e){return new ty}encryptedPrivateChannel(e){return new m_}presenceChannel(e){return new y_}leave(e){}leaveChannel(e){}socketId(){return"fake-socket-id"}disconnect(){}}class v_{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 xc({...this.options,cluster:""});else if(this.options.broadcaster==="pusher")this.connector=new xc(this.options);else if(this.options.broadcaster==="ably")this.connector=new xc({...this.options,cluster:"",broadcaster:"pusher"});else if(this.options.broadcaster==="socket.io")this.connector=new b_(this.options);else if(this.options.broadcaster==="null")this.connector=new ry(this.options);else if(typeof this.options.broadcaster=="function"&&f_(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,r,a){return this.connector.listen(e,r,a)}private(e){return this.connector.privateChannel(e)}encryptedPrivate(e){if(this.connectorSupportsEncryptedPrivateChannels(this.connector))return this.connector.encryptedPrivateChannel(e);throw new Error(`Broadcaster ${typeof this.options.broadcaster} ${String(this.options.broadcaster)} does not support encrypted private channels.`)}connectorSupportsEncryptedPrivateChannels(e){return e instanceof xc||e instanceof ry}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,r)=>{this.socketId()&&e.headers.set("X-Socket-ID",this.socketId()),r()})}registerAxiosRequestInterceptor(){axios.interceptors.request.use(e=>(this.socketId()&&(e.headers["X-Socket-Id"]=this.socketId()),e))}registerjQueryAjaxSetup(){typeof jQuery.ajax<"u"&&jQuery.ajaxPrefilter((e,r,a)=>{this.socketId()&&a.setRequestHeader("X-Socket-Id",this.socketId())})}registerTurboRequestInterceptor(){document.addEventListener("turbo:before-fetch-request",e=>{e.detail.fetchOptions.headers["X-Socket-Id"]=this.socketId()})}}var hf={exports:{}};/*! + * Pusher JavaScript Library v8.4.0 + * https://pusher.com/ + * + * Copyright 2020, Pusher + * Released under the MIT licence. + */var ay;function S_(){return ay||(ay=1,(function(o,e){(function(a,i){o.exports=i()})(window,function(){return(function(r){var a={};function i(l){if(a[l])return a[l].exports;var c=a[l]={i:l,l:!1,exports:{}};return r[l].call(c.exports,c,c.exports,i),c.l=!0,c.exports}return i.m=r,i.c=a,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(g){return l[g]}.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(r,a,i){var l=this&&this.__extends||(function(){var A=function(x,R){return A=Object.setPrototypeOf||{__proto__:[]}instanceof Array&&function(M,O){M.__proto__=O}||function(M,O){for(var L in O)O.hasOwnProperty(L)&&(M[L]=O[L])},A(x,R)};return function(x,R){A(x,R);function M(){this.constructor=x}x.prototype=R===null?Object.create(R):(M.prototype=R.prototype,new M)}})();Object.defineProperty(a,"__esModule",{value:!0});var c=256,d=(function(){function A(x){x===void 0&&(x="="),this._paddingCharacter=x}return A.prototype.encodedLength=function(x){return this._paddingCharacter?(x+2)/3*4|0:(x*8+5)/6|0},A.prototype.encode=function(x){for(var R="",M=0;M>>18&63),R+=this._encodeByte(O>>>12&63),R+=this._encodeByte(O>>>6&63),R+=this._encodeByte(O>>>0&63)}var L=x.length-M;if(L>0){var O=x[M]<<16|(L===2?x[M+1]<<8:0);R+=this._encodeByte(O>>>18&63),R+=this._encodeByte(O>>>12&63),L===2?R+=this._encodeByte(O>>>6&63):R+=this._paddingCharacter||"",R+=this._paddingCharacter||""}return R},A.prototype.maxDecodedLength=function(x){return this._paddingCharacter?x/4*3|0:(x*6+7)/8|0},A.prototype.decodedLength=function(x){return this.maxDecodedLength(x.length-this._getPaddingLength(x))},A.prototype.decode=function(x){if(x.length===0)return new Uint8Array(0);for(var R=this._getPaddingLength(x),M=x.length-R,O=new Uint8Array(this.maxDecodedLength(M)),L=0,q=0,G=0,B=0,K=0,fe=0,Ce=0;q>>4,O[L++]=K<<4|fe>>>2,O[L++]=fe<<6|Ce,G|=B&c,G|=K&c,G|=fe&c,G|=Ce&c;if(q>>4,G|=B&c,G|=K&c),q>>2,G|=fe&c),q>>8&6,R+=51-x>>>8&-75,R+=61-x>>>8&-15,R+=62-x>>>8&3,String.fromCharCode(R)},A.prototype._decodeChar=function(x){var R=c;return R+=(42-x&x-44)>>>8&-c+x-43+62,R+=(46-x&x-48)>>>8&-c+x-47+63,R+=(47-x&x-58)>>>8&-c+x-48+52,R+=(64-x&x-91)>>>8&-c+x-65+0,R+=(96-x&x-123)>>>8&-c+x-97+26,R},A.prototype._getPaddingLength=function(x){var R=0;if(this._paddingCharacter){for(var M=x.length-1;M>=0&&x[M]===this._paddingCharacter;M--)R++;if(x.length<4||R>2)throw new Error("Base64Coder: incorrect padding")}return R},A})();a.Coder=d;var f=new d;function g(A){return f.encode(A)}a.encode=g;function m(A){return f.decode(A)}a.decode=m;var y=(function(A){l(x,A);function x(){return A!==null&&A.apply(this,arguments)||this}return x.prototype._encodeByte=function(R){var M=R;return M+=65,M+=25-R>>>8&6,M+=51-R>>>8&-75,M+=61-R>>>8&-13,M+=62-R>>>8&49,String.fromCharCode(M)},x.prototype._decodeChar=function(R){var M=c;return M+=(44-R&R-46)>>>8&-c+R-45+62,M+=(94-R&R-96)>>>8&-c+R-95+63,M+=(47-R&R-58)>>>8&-c+R-48+52,M+=(64-R&R-91)>>>8&-c+R-65+0,M+=(96-R&R-123)>>>8&-c+R-97+26,M},x})(d);a.URLSafeCoder=y;var w=new y;function S(A){return w.encode(A)}a.encodeURLSafe=S;function v(A){return w.decode(A)}a.decodeURLSafe=v,a.encodedLength=function(A){return f.encodedLength(A)},a.maxDecodedLength=function(A){return f.maxDecodedLength(A)},a.decodedLength=function(A){return f.decodedLength(A)}}),(function(r,a,i){Object.defineProperty(a,"__esModule",{value:!0});var l="utf8: invalid string",c="utf8: invalid source encoding";function d(m){for(var y=new Uint8Array(f(m)),w=0,S=0;S>6,y[w++]=128|v&63):v<55296?(y[w++]=224|v>>12,y[w++]=128|v>>6&63,y[w++]=128|v&63):(S++,v=(v&1023)<<10,v|=m.charCodeAt(S)&1023,v+=65536,y[w++]=240|v>>18,y[w++]=128|v>>12&63,y[w++]=128|v>>6&63,y[w++]=128|v&63)}return y}a.encode=d;function f(m){for(var y=0,w=0;w=m.length-1)throw new Error(l);w++,y+=4}else throw new Error(l)}return y}a.encodedLength=f;function g(m){for(var y=[],w=0;w=m.length)throw new Error(c);var A=m[++w];if((A&192)!==128)throw new Error(c);S=(S&31)<<6|A&63,v=128}else if(S<240){if(w>=m.length-1)throw new Error(c);var A=m[++w],x=m[++w];if((A&192)!==128||(x&192)!==128)throw new Error(c);S=(S&15)<<12|(A&63)<<6|x&63,v=2048}else if(S<248){if(w>=m.length-2)throw new Error(c);var A=m[++w],x=m[++w],R=m[++w];if((A&192)!==128||(x&192)!==128||(R&192)!==128)throw new Error(c);S=(S&15)<<18|(A&63)<<12|(x&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("")}a.decode=g}),(function(r,a,i){r.exports=i(3).default}),(function(r,a,i){i.r(a);class l{constructor(b,E){this.lastId=0,this.prefix=b,this.name=E}create(b){this.lastId++;var E=this.lastId,D=this.prefix+E,I=this.name+"["+E+"]",ie=!1,ye=function(){ie||(b.apply(null,arguments),ie=!0)};return this[E]=ye,{number:E,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 g{constructor(b){this.options=b,this.receivers=b.receivers||c,this.loading={}}load(b,E,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=Ve.createScriptRequest(I.getPath(b,E)),ye=I.receivers.create(function(Oe){if(I.receivers.remove(ye),I.loading[b]){var Fe=I.loading[b];delete I.loading[b];for(var at=function(Bt){Bt||ie.cleanup()},lt=0;lt>>6)+Ue(128|b&63):Ue(224|b>>>12&15)+Ue(128|b>>>6&63)+Ue(128|b&63)},wt=function(_){return _.replace(/[^\x00-\x7F]/g,qe)},J=function(_){var b=[0,2,1][_.length%3],E=_.charCodeAt(0)<<16|(_.length>1?_.charCodeAt(1):0)<<8|(_.length>2?_.charCodeAt(2):0),D=[Pe.charAt(E>>>18),Pe.charAt(E>>>12&63),b>=2?"=":Pe.charAt(E>>>6&63),b>=1?"=":Pe.charAt(E&63)];return D.join("")},he=window.btoa||function(_){return _.replace(/[\s\S]{1,3}/g,J)};class Ee{constructor(b,E,D,I){this.clear=E,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=Ee;function pe(_){window.clearTimeout(_)}function H(_){window.clearInterval(_)}class T extends Z{constructor(b,E){super(setTimeout,pe,b,function(D){return E(),null})}}class ge extends Z{constructor(b,E){super(setInterval,H,b,function(D){return E(),D})}}var de={now(){return Date.now?Date.now():new Date().valueOf()},defer(_){return new T(0,_)},method(_,...b){var E=Array.prototype.slice.call(arguments,1);return function(D){return D[_].apply(D,E.concat(arguments))}}},me=de;function ae(_,...b){for(var E=0;E{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,...E){var D=Re.apply(this,arguments);Jo.log?Jo.log(D):Jo.logToConsole&&b.bind(this)(D)}}var bt=new Ut,ra=function(_,b,E,D,I){(E.headers!==void 0||E.headersProvider!=null)&&bt.warn(`To send headers with the ${D.toString()} request, you must use AJAX, rather than JSONP.`);var ie=_.nextAuthCallbackID.toString();_.nextAuthCallbackID++;var ye=_.getDocument(),Oe=ye.createElement("script");_.auth_callbacks[ie]=function(lt){I(null,lt)};var Fe="Pusher.auth_callbacks['"+ie+"']";Oe.src=E.endpoint+"?callback="+encodeURIComponent(Fe)+"&"+b;var at=ye.getElementsByTagName("head")[0]||ye.documentElement;at.insertBefore(Oe,at.firstChild)},Ln=ra;class An{constructor(b){this.src=b}send(b){var E=this,D="Error loading "+E.src;E.script=document.createElement("script"),E.script.id=b.id,E.script.src=E.src,E.script.type="text/javascript",E.script.charset="UTF-8",E.script.addEventListener?(E.script.onerror=function(){b.callback(D)},E.script.onload=function(){b.callback(null)}):E.script.onreadystatechange=function(){(E.script.readyState==="loaded"||E.script.readyState==="complete")&&b.callback(null)},E.script.async===void 0&&document.attachEvent&&/opera/i.test(navigator.userAgent)?(E.errorScript=document.createElement("script"),E.errorScript.id=b.id+"_error",E.errorScript.text=b.name+"('"+D+"');",E.script.async=E.errorScript.async=!1):E.script.async=!0;var I=document.getElementsByTagName("head")[0];I.insertBefore(E.script,I.firstChild),E.errorScript&&I.insertBefore(E.errorScript,E.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 xn{constructor(b,E){this.url=b,this.data=E}send(b){if(!this.request){var E=fn(this.data),D=this.url+"/"+b.number+"?"+E;this.request=Ve.createScriptRequest(D),this.request.send(b)}}cleanup(){this.request&&this.request.cleanup()}}var Mn=function(_,b){return function(E,D){var I="http"+(b?"s":"")+"://",ie=I+(_.host||_.options.host)+_.options.path,ye=Ve.createJSONPRequest(ie,E),Oe=Ve.ScriptReceivers.create(function(Fe,at){c.remove(Oe),ye.cleanup(),at&&at.host&&(_.host=at.host),D&&D(Fe,at)});ye.send(Oe)}},hn={name:"jsonp",getAgent:Mn},aa=hn;function $n(_,b,E){var D=_+(b.useTLS?"s":""),I=b.useTLS?b.hostTLS:b.hostNonTLS;return D+"://"+I+E}function Vt(_,b){var E="/app/"+_,D="?protocol="+f.PROTOCOL+"&client=js&version="+f.VERSION+(b?"&"+b:"");return E+D}var Cn={getInitial:function(_,b){var E=(b.httpPath||"")+Vt(_,"flash=false");return $n("ws",b,E)}},nn={getInitial:function(_,b){var E=(b.httpPath||"/pusher")+Vt(_);return $n("http",b,E)}},V={getInitial:function(_,b){return $n("http",b,b.httpPath||"/pusher")},getPath:function(_,b){return Vt(_)}};class oe{constructor(){this._callbacks={}}get(b){return this._callbacks[ce(b)]}add(b,E,D){var I=ce(b);this._callbacks[I]=this._callbacks[I]||[],this._callbacks[I].push({fn:E,context:D})}remove(b,E,D){if(!b&&!E&&!D){this._callbacks={};return}var I=b?[ce(b)]:Ge(this._callbacks);E||D?this.removeCallback(I,E,D):this.removeAllCallbacks(I)}removeCallback(b,E,D){yt(b,function(I){this._callbacks[I]=Yt(this._callbacks[I]||[],function(ie){return E&&E!==ie.fn||D&&D!==ie.context}),this._callbacks[I].length===0&&delete this._callbacks[I]},this)}removeAllCallbacks(b){yt(b,function(E){delete this._callbacks[E]},this)}}function ce(_){return"_"+_}class X{constructor(b){this.callbacks=new oe,this.global_callbacks=[],this.failThrough=b}bind(b,E,D){return this.callbacks.add(b,E,D),this}bind_global(b){return this.global_callbacks.push(b),this}unbind(b,E,D){return this.callbacks.remove(b,E,D),this}unbind_global(b){return b?(this.global_callbacks=Yt(this.global_callbacks||[],E=>E!==b),this):(this.global_callbacks=[],this)}unbind_all(){return this.unbind(),this.unbind_global(),this}emit(b,E,D){for(var I=0;I0)for(var I=0;I{this.onError(E),this.changeState("closed")}),!1}return this.bindListeners(),bt.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,E){this.state=b,this.timeline.info(this.buildTimelineMessage({state:b,params:E})),this.emit(b,E)}buildTimelineMessage(b){return ae({cid:this.id},b)}}class ue{constructor(b){this.hooks=b}isSupported(b){return this.hooks.isSupported(b)}createConnection(b,E,D,I){return new ve(this.hooks,b,E,D,I)}}var we=new ue({urls:Cn,handlesActivityChecks:!1,supportsPing:!1,isInitialized:function(){return!!Ve.getWebSocketAPI()},isSupported:function(){return!!Ve.getWebSocketAPI()},getSocket:function(_){return Ve.createWebSocket(_)}}),_e={urls:nn,handlesActivityChecks:!1,supportsPing:!0,isInitialized:function(){return!0}},Be=ae({getSocket:function(_){return Ve.HTTPFactory.createStreamingSocket(_)}},_e),xe=ae({getSocket:function(_){return Ve.HTTPFactory.createPollingSocket(_)}},_e),De={isSupported:function(){return Ve.isXHRSupported()}},Ae=new ue(ae({},Be,De)),et=new ue(ae({},xe,De)),Ne={ws:we,xhr_streaming:Ae,xhr_polling:et},je=Ne,Se=new ue({file:"sockjs",urls:V,handlesActivityChecks:!0,supportsPing:!1,isSupported:function(){return!0},isInitialized:function(){return window.SockJS!==void 0},getSocket:function(_,b){return new window.SockJS(_,null,{js_path:y.getPath("sockjs",{useTLS:b.useTLS}),ignore_null_origin:b.ignoreNullOrigin})},beforeOpen:function(_,b){_.send(JSON.stringify({path:b}))}}),Me={isSupported:function(_){var b=Ve.isXDRSupported(_.useTLS);return b}},Ze=new ue(ae({},Be,Me)),kt=new ue(ae({},xe,Me));je.xdr_streaming=Ze,je.xdr_polling=kt,je.sockjs=Se;var Ot=je;class Nn extends X{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 $t=new Nn;class Nt{constructor(b,E,D){this.manager=b,this.transport=E,this.minPingDelay=D.minPingDelay,this.maxPingDelay=D.maxPingDelay,this.pingDelay=void 0}createConnection(b,E,D,I){I=ae({},I,{activityTimeout:this.pingDelay});var ie=this.transport.createConnection(b,E,D,I),ye=null,Oe=function(){ie.unbind("open",Oe),ie.bind("closed",Fe),ye=me.now()},Fe=at=>{if(ie.unbind("closed",Fe),at.code===1002||at.code===1003)this.manager.reportDeath();else if(!at.wasClean&&ye){var lt=me.now()-ye;lt<2*this.maxPingDelay&&(this.manager.reportDeath(),this.pingDelay=Math.max(lt/2,this.minPingDelay))}};return ie.bind("open",Oe),ie}isSupported(b){return this.manager.isAlive()&&this.transport.isSupported(b)}}const gn={decodeMessage:function(_){try{var b=JSON.parse(_.data),E=b.data;if(typeof E=="string")try{E=JSON.parse(b.data)}catch{}var D={event:b.event,channel:b.channel,data:E};return b.user_id&&(D.user_id=b.user_id),D}catch(I){throw{type:"MessageParseError",error:I,data:_.data}}},encodeMessage:function(_){return JSON.stringify(_)},processHandshake:function(_){var b=gn.decodeMessage(_);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(_){return _.code<4e3?_.code>=1002&&_.code<=1004?"backoff":null:_.code===4e3?"tls_only":_.code<4100?"refused":_.code<4200?"backoff":_.code<4300?"retry":"refused"},getCloseError:function(_){return _.code!==1e3&&_.code!==1001?{type:"PusherError",data:{code:_.code,message:_.reason||_.message}}:null}};var In=gn;class No extends X{constructor(b,E){super(),this.id=b,this.transport=E,this.activityTimeout=E.activityTimeout,this.bindListeners()}handlesActivityChecks(){return this.transport.handlesActivityChecks()}send(b){return this.transport.send(b)}send_event(b,E,D){var I={event:b,data:E};return D&&(I.channel=D),bt.debug("Event sent",I),this.send(In.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=In.decodeMessage(D)}catch(ie){this.emit("error",{type:"MessageParseError",error:ie,data:D.data})}if(I!==void 0){switch(bt.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=>{E(),D&&D.code&&this.handleCloseEvent(D),this.transport=null,this.emit("closed")}},E=()=>{$e(b,(D,I)=>{this.transport.unbind(I,D)})};$e(b,(D,I)=>{this.transport.bind(I,D)})}handleCloseEvent(b){var E=In.getCloseAction(b),D=In.getCloseError(b);D&&this.emit("error",D),E&&this.emit(E,{action:E,error:D})}}class Sf{constructor(b,E){this.transport=b,this.callback=E,this.bindListeners()}close(){this.unbindListeners(),this.transport.close()}bindListeners(){this.onMessage=b=>{this.unbindListeners();var E;try{E=In.processHandshake(b)}catch(D){this.finish("error",{error:D}),this.transport.close();return}E.action==="connected"?this.finish("connected",{connection:new No(E.id,this.transport),activityTimeout:E.activityTimeout}):(this.finish(E.action,{error:E.error}),this.transport.close())},this.onClosed=b=>{this.unbindListeners();var E=In.getCloseAction(b)||"backoff",D=In.getCloseError(b);this.finish(E,{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,E){this.callback(ae({transport:this.transport,action:b},E))}}class wf{constructor(b,E){this.timeline=b,this.options=E||{}}send(b,E){this.timeline.isEmpty()||this.timeline.send(Ve.TimelineTransport.getAgent(this,b),E)}}class hs extends X{constructor(b,E){super(function(D,I){bt.debug("No callbacks on "+b+" for "+D)}),this.name=b,this.pusher=E,this.subscribed=!1,this.subscriptionPending=!1,this.subscriptionCancelled=!1}authorize(b,E){return E(null,{auth:""})}trigger(b,E){if(b.indexOf("client-")!==0)throw new x("Event '"+b+"' does not start with 'client-'");if(!this.subscribed){var D=v.buildLogSuffix("triggeringClientEvents");bt.warn(`Client event triggered before channel 'subscription_succeeded' event . ${D}`)}return this.pusher.send_event(b,E,this.name)}disconnect(){this.subscribed=!1,this.subscriptionPending=!1}handleEvent(b){var E=b.event,D=b.data;if(E==="pusher_internal:subscription_succeeded")this.handleSubscriptionSucceededEvent(b);else if(E==="pusher_internal:subscription_count")this.handleSubscriptionCountEvent(b);else if(E.indexOf("pusher_internal:")!==0){var I={};this.emit(E,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,E)=>{b?(this.subscriptionPending=!1,bt.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:E.auth,channel_data:E.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 ia extends hs{authorize(b,E){return this.pusher.config.channelAuthorizer({channelName:this.name,socketId:b},E)}}class Io{constructor(){this.reset()}get(b){return Object.prototype.hasOwnProperty.call(this.members,b)?{id:b,info:this.members[b]}:null}each(b){$e(this.members,(E,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 E=this.get(b.user_id);return E&&(delete this.members[b.user_id],this.count--),E}reset(){this.members={},this.count=0,this.myID=null,this.me=null}}var Ia=function(_,b,E,D){function I(ie){return ie instanceof E?ie:new E(function(ye){ye(ie)})}return new(E||(E=Promise))(function(ie,ye){function Oe(lt){try{at(D.next(lt))}catch(Bt){ye(Bt)}}function Fe(lt){try{at(D.throw(lt))}catch(Bt){ye(Bt)}}function at(lt){lt.done?ie(lt.value):I(lt.value).then(Oe,Fe)}at((D=D.apply(_,b||[])).next())})};class Ha extends ia{constructor(b,E){super(b,E),this.members=new Io}authorize(b,E){super.authorize(b,(D,I)=>Ia(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");bt.error(`Invalid auth response for channel '${this.name}', expected 'channel_data' field. ${ye}, or the user should be signed in.`),E("Invalid auth response");return}E(D,I)}))}handleEvent(b){var E=b.event;if(E.indexOf("pusher_internal:")===0)this.handleInternalEvent(b);else{var D=b.data,I={};b.user_id&&(I.user_id=b.user_id),this.emit(E,D,I)}}handleInternalEvent(b){var E=b.event,D=b.data;switch(E){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 _i=i(1),qr=i(0);class Xt extends ia{constructor(b,E,D){super(b,E),this.key=null,this.nacl=D}authorize(b,E){super.authorize(b,(D,I)=>{if(D){E(D,I);return}let ie=I.shared_secret;if(!ie){E(new Error(`No shared_secret key in auth payload for encrypted channel: ${this.name}`),null);return}this.key=Object(qr.decode)(ie),delete I.shared_secret,E(null,I)})}trigger(b,E){throw new q("Client events are not currently supported for encrypted channels")}handleEvent(b){var E=b.event,D=b.data;if(E.indexOf("pusher_internal:")===0||E.indexOf("pusher:")===0){super.handleEvent(b);return}this.handleEncryptedEvent(E,D)}handleEncryptedEvent(b,E){if(!this.key){bt.debug("Received encrypted event before key has been retrieved from the authEndpoint");return}if(!E.ciphertext||!E.nonce){bt.error("Unexpected format for encrypted event, expected object with `ciphertext` and `nonce` fields, got: "+E);return}let D=Object(qr.decode)(E.ciphertext);if(D.length{if(ye){bt.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){bt.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 E=Object(_i.decode)(b);try{return JSON.parse(E)}catch{return E}}}class Mc extends X{constructor(b,E){super(),this.state="initialized",this.connection=null,this.key=b,this.options=E,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=Ve.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,E,D){return this.connection?this.connection.send_event(b,E,D):!1}disconnect(){this.disconnectInternally(),this.updateState("disconnected")}isUsingTLS(){return this.usingTLS}startConnecting(){var b=(E,D)=>{E?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:E=>{this.resetActivityCheck(),this.emit("message",E)},ping:()=>{this.send_event("pusher:pong",{})},activity:()=>{this.resetActivityCheck()},error:E=>{this.emit("error",E)},closed:()=>{this.abandonConnection(),this.shouldRetry()&&this.retryIn(1e3)}})}buildHandshakeCallbacks(b){return ae({},b,{connected:E=>{this.activityTimeout=Math.min(this.options.activityTimeout,E.activityTimeout,E.connection.activityTimeout||1/0),this.clearUnavailableTimer(),this.setConnection(E.connection),this.socket_id=this.connection.id,this.updateState("connected",{socket_id:this.socket_id})}})}buildErrorCallbacks(){let b=E=>D=>{D.error&&this.emit("error",{type:"WebSocketError",error:D.error}),E(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 E in this.connectionCallbacks)this.connection.bind(E,this.connectionCallbacks[E]);this.resetActivityCheck()}abandonConnection(){if(this.connection){this.stopActivityCheck();for(var b in this.connectionCallbacks)this.connection.unbind(b,this.connectionCallbacks[b]);var E=this.connection;return this.connection=null,E}}updateState(b,E){var D=this.state;if(this.state=b,D!==b){var I=b;I==="connected"&&(I+=" with new socket ID "+E.socket_id),bt.debug("State changed",D+" -> "+I),this.timeline.info({state:b,params:E}),this.emit("state_change",{previous:D,current:b}),this.emit(b,E)}}shouldRetry(){return this.state==="connecting"||this.state==="connected"}}class $c{constructor(){this.channels={}}add(b,E){return this.channels[b]||(this.channels[b]=sa(b,E)),this.channels[b]}all(){return At(this.channels)}find(b){return this.channels[b]}remove(b){var E=this.channels[b];return delete this.channels[b],E}disconnect(){$e(this.channels,function(b){b.disconnect()})}}function sa(_,b){if(_.indexOf("private-encrypted-")===0){if(b.config.nacl)return kr.createEncryptedChannel(_,b,b.config.nacl);let E="Tried to subscribe to a private-encrypted- channel but no nacl implementation available",D=v.buildLogSuffix("encryptedChannelSupport");throw new q(`${E}. ${D}`)}else{if(_.indexOf("private-")===0)return kr.createPrivateChannel(_,b);if(_.indexOf("presence-")===0)return kr.createPresenceChannel(_,b);if(_.indexOf("#")===0)throw new R('Cannot create a channel with name "'+_+'".');return kr.createChannel(_,b)}}var ja={createChannels(){return new $c},createConnectionManager(_,b){return new Mc(_,b)},createChannel(_,b){return new hs(_,b)},createPrivateChannel(_,b){return new ia(_,b)},createPresenceChannel(_,b){return new Ha(_,b)},createEncryptedChannel(_,b,E){return new Xt(_,b,E)},createTimelineSender(_,b){return new wf(_,b)},createHandshake(_,b){return new Sf(_,b)},createAssistantToTheTransportManager(_,b,E){return new Nt(_,b,E)}},kr=ja;class Ho{constructor(b){this.options=b||{},this.livesLeft=this.options.lives||1/0}getAssistant(b){return kr.createAssistantToTheTransportManager(this,b,{minPingDelay:this.options.minPingDelay,maxPingDelay:this.options.maxPingDelay})}isAlive(){return this.livesLeft>0}reportDeath(){this.livesLeft-=1}}class Gr{constructor(b,E){this.strategies=b,this.loop=!!E.loop,this.failFast=!!E.failFast,this.timeout=E.timeout,this.timeoutLimit=E.timeoutLimit}isSupported(){return Tr(this.strategies,me.method("isSupported"))}connect(b,E){var D=this.strategies,I=0,ie=this.timeout,ye=null,Oe=(Fe,at)=>{at?E(null,at):(I=I+1,this.loop&&(I=I%D.length),I0&&(ie=new T(D.timeout,function(){ye.abort(),I(!0)})),ye=b.connect(E,function(Oe,Fe){Oe&&ie&&ie.isRunning()&&!D.failFast||(ie&&ie.ensureAborted(),I(Oe,Fe))}),{abort:function(){ie&&ie.ensureAborted(),ye.abort()},forceMinPriority:function(Oe){ye.forceMinPriority(Oe)}}}}class jo{constructor(b){this.strategies=b}isSupported(){return Tr(this.strategies,me.method("isSupported"))}connect(b,E){return gs(this.strategies,b,function(D,I){return function(ie,ye){if(I[D].error=ie,ie){ps(I)&&E(!0);return}yt(I,function(Oe){Oe.forceMinPriority(ye.transport.priority)}),E(null,ye)}})}}function gs(_,b,E){var D=dn(_,function(I,ie,ye,Oe){return I.connect(b,E(ie,Oe))});return{abort:function(){yt(D,Rr)},forceMinPriority:function(I){yt(D,function(ie){ie.forceMinPriority(I)})}}}function ps(_){return wn(_,function(b){return!!b.error})}function Rr(_){!_.error&&!_.aborted&&(_.abort(),_.aborted=!0)}class Hn{constructor(b,E,D){this.strategy=b,this.transports=E,this.ttl=D.ttl||1800*1e3,this.usingTLS=D.useTLS,this.timeline=D.timeline}isSupported(){return this.strategy.isSupported()}connect(b,E){var D=this.usingTLS,I=Cf(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 Gr([Oe],{timeout:I.latency*2+1e3,failFast:!0}))):ie++)}var Fe=me.now(),at=ye.pop().connect(b,function lt(Bt,Ri){Bt?(Uo(D),ye.length>0?(Fe=me.now(),at=ye.pop().connect(b,lt)):E(Bt)):(zo(D,Ri.transport.name,me.now()-Fe,ie),E(null,Ri))});return{abort:function(){at.abort()},forceMinPriority:function(lt){b=lt,at&&at.forceMinPriority(lt)}}}}function ms(_){return"pusherTransport"+(_?"TLS":"NonTLS")}function Cf(_){var b=Ve.getLocalStorage();if(b)try{var E=b[ms(_)];if(E)return JSON.parse(E)}catch{Uo(_)}return null}function zo(_,b,E,D){var I=Ve.getLocalStorage();if(I)try{I[ms(_)]=Wn({timestamp:me.now(),transport:b,latency:E,cacheSkipCount:D})}catch{}}function Uo(_){var b=Ve.getLocalStorage();if(b)try{delete b[ms(_)]}catch{}}class oa{constructor(b,{delay:E}){this.strategy=b,this.options={delay:E}}isSupported(){return this.strategy.isSupported()}connect(b,E){var D=this.strategy,I,ie=new T(this.options.delay,function(){I=D.connect(b,E)});return{abort:function(){ie.ensureAborted(),I&&I.abort()},forceMinPriority:function(ye){b=ye,I&&I.forceMinPriority(ye)}}}}class Ai{constructor(b,E,D){this.test=b,this.trueBranch=E,this.falseBranch=D}isSupported(){var b=this.test()?this.trueBranch:this.falseBranch;return b.isSupported()}connect(b,E){var D=this.test()?this.trueBranch:this.falseBranch;return D.connect(b,E)}}class jn{constructor(b){this.strategy=b}isSupported(){return this.strategy.isSupported()}connect(b,E){var D=this.strategy.connect(b,function(I,ie){ie&&D.abort(),E(I,ie)});return D}}function la(_){return function(){return _.isSupported()}}var Nc=function(_,b,E){var D={};function I(Di,Kc,Wc,rl,al){var il=E(_,Di,Kc,Wc,rl,al);return D[Di]=il,il}var ie=Object.assign({},b,{hostNonTLS:_.wsHost+":"+_.wsPort,hostTLS:_.wsHost+":"+_.wssPort,httpPath:_.wsPath}),ye=Object.assign({},ie,{useTLS:!0}),Oe=Object.assign({},b,{hostNonTLS:_.httpHost+":"+_.httpPort,hostTLS:_.httpHost+":"+_.httpsPort,httpPath:_.httpPath}),Fe={loop:!0,timeout:15e3,timeoutLimit:6e4},at=new Ho({minPingDelay:1e4,maxPingDelay:_.activityTimeout}),lt=new Ho({lives:2,minPingDelay:1e4,maxPingDelay:_.activityTimeout}),Bt=I("ws","ws",3,ie,at),Ri=I("wss","ws",3,ye,at),Gc=I("sockjs","sockjs",1,Oe),Qo=I("xhr_streaming","xhr_streaming",1,Oe,lt),Vc=I("xdr_streaming","xdr_streaming",1,Oe,lt),Zo=I("xhr_polling","xhr_polling",1,Oe),Ga=I("xdr_polling","xdr_polling",1,Oe),Fc=new Gr([Bt],Fe),zf=new Gr([Ri],Fe),Uf=new Gr([Gc],Fe),el=new Gr([new Ai(la(Qo),Qo,Vc)],Fe),tl=new Gr([new Ai(la(Zo),Zo,Ga)],Fe),Va=new Gr([new Ai(la(el),new jo([el,new oa(tl,{delay:4e3})]),tl)],Fe),ua=new Ai(la(Va),Va,Uf),nl;return b.useTLS?nl=new jo([Fc,new oa(ua,{delay:2e3})]):nl=new jo([Fc,new oa(zf,{delay:2e3}),new oa(ua,{delay:5e3})]),new Hn(new jn(new Ai(la(Bt),nl,ua)),D,{ttl:18e5,timeline:b.timeline,useTLS:b.useTLS})},Bo=Nc,za=(function(){var _=this;_.timeline.info(_.buildTimelineMessage({transport:_.name+(_.options.useTLS?"s":"")})),_.hooks.isInitialized()?_.changeState("initialized"):_.hooks.file?(_.changeState("initializing"),y.load(_.hooks.file,{useTLS:_.options.useTLS},function(b,E){_.hooks.isInitialized()?(_.changeState("initialized"),E(!0)):(b&&_.onError(b),_.onClose(),E(!1))})):_.onClose()}),Ic={getRequest:function(_){var b=new window.XDomainRequest;return b.ontimeout=function(){_.emit("error",new M),_.close()},b.onerror=function(E){_.emit("error",E),_.close()},b.onprogress=function(){b.responseText&&b.responseText.length>0&&_.onChunk(200,b.responseText)},b.onload=function(){b.responseText&&b.responseText.length>0&&_.onChunk(200,b.responseText),_.emit("finished",200),_.close()},b},abortRequest:function(_){_.ontimeout=_.onerror=_.onprogress=_.onload=null,_.abort()}},Hc=Ic;const Ua=256*1024;class Ef extends X{constructor(b,E,D){super(),this.hooks=b,this.method=E,this.url=D}start(b){this.position=0,this.xhr=this.hooks.getRequest(this),this.unloader=()=>{this.close()},Ve.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&&(Ve.removeUnloadListener(this.unloader),this.unloader=null),this.xhr&&(this.hooks.abortRequest(this.xhr),this.xhr=null)}onChunk(b,E){for(;;){var D=this.advanceBuffer(E);if(D)this.emit("chunk",{status:b,data:D});else break}this.isBufferTooLong(E)&&this.emit("buffer_too_long")}advanceBuffer(b){var E=b.slice(this.position),D=E.indexOf(` +`);return D!==-1?(this.position+=D+1,E.slice(0,D)):null}isBufferTooLong(b){return this.position===b.length&&b.length>Ua}}var ys;(function(_){_[_.CONNECTING=0]="CONNECTING",_[_.OPEN=1]="OPEN",_[_.CLOSED=3]="CLOSED"})(ys||(ys={}));var Vr=ys,Po=1;class _f{constructor(b,E){this.hooks=b,this.session=vs(1e3)+"/"+Ba(8),this.location=Af(E),this.readyState=Vr.CONNECTING,this.openStream()}send(b){return this.sendRaw(JSON.stringify([b]))}ping(){this.hooks.sendHeartbeat(this)}close(b,E){this.onClose(b,E,!0)}sendRaw(b){if(this.readyState===Vr.OPEN)try{return Ve.createSocketRequest("POST",or(bs(this.location,this.session))).start(b),!0}catch{return!1}else return!1}reconnect(){this.closeStream(),this.openStream()}onClose(b,E,D){this.closeStream(),this.readyState=Vr.CLOSED,this.onclose&&this.onclose({code:b,reason:E,wasClean:D})}onChunk(b){if(b.status===200){this.readyState===Vr.OPEN&&this.onActivity();var E,D=b.data.slice(0,1);switch(D){case"o":E=JSON.parse(b.data.slice(1)||"{}"),this.onOpen(E);break;case"a":E=JSON.parse(b.data.slice(1)||"[]");for(var I=0;I{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 Af(_){var b=/([^\?]*)\/*(\??.*)/.exec(_);return{base:b[1],queryString:b[2]}}function bs(_,b){return _.base+"/"+b+"/xhr_send"}function or(_){var b=_.indexOf("?")===-1?"?":"&";return _+b+"t="+ +new Date+"&n="+Po++}function qo(_,b){var E=/(https?:\/\/)([^\/:]+)((\/|:)?.*)/.exec(_);return E[1]+b+E[3]}function vs(_){return Ve.randomInt(_)}function Ba(_){for(var b=[],E=0;E<_;E++)b.push(vs(32).toString(32));return b.join("")}var Pa=_f,jc={getReceiveURL:function(_,b){return _.base+"/"+b+"/xhr_streaming"+_.queryString},onHeartbeat:function(_){_.sendRaw("[]")},sendHeartbeat:function(_){_.sendRaw("[]")},onFinished:function(_,b){_.onClose(1006,"Connection interrupted ("+b+")",!1)}},Go=jc,zc={getReceiveURL:function(_,b){return _.base+"/"+b+"/xhr"+_.queryString},onHeartbeat:function(){},sendHeartbeat:function(_){_.sendRaw("[]")},onFinished:function(_,b){b===200?_.reconnect():_.onClose(1006,"Connection interrupted ("+b+")",!1)}},xi=zc,Dr={getRequest:function(_){var b=Ve.getXHRAPI(),E=new b;return E.onreadystatechange=E.onprogress=function(){switch(E.readyState){case 3:E.responseText&&E.responseText.length>0&&_.onChunk(E.status,E.responseText);break;case 4:E.responseText&&E.responseText.length>0&&_.onChunk(E.status,E.responseText),_.emit("finished",E.status),_.close();break}},E},abortRequest:function(_){_.onreadystatechange=null,_.abort()}},Vo=Dr,Ti={createStreamingSocket(_){return this.createSocket(Go,_)},createPollingSocket(_){return this.createSocket(xi,_)},createSocket(_,b){return new Pa(_,b)},createXHR(_,b){return this.createRequest(Vo,_,b)},createRequest(_,b,E){return new Ef(_,b,E)}},Or=Ti;Or.createXDR=function(_,b){return this.createRequest(Hc,_,b)};var Fo=Or,Ss={nextAuthCallbackID:1,auth_callbacks:{},ScriptReceivers:c,DependenciesReceivers:m,getDefaultStrategy:Bo,Transports:Ot,transportConnectionInitializer:za,HTTPFactory:Fo,TimelineTransport:aa,getXHRAPI(){return window.XMLHttpRequest},getWebSocketAPI(){return window.WebSocket||window.MozWebSocket},setup(_){window.Pusher=_;var b=()=>{this.onDocumentBody(_.ready)};window.JSON?b():y.load("json2",{},b)},getDocument(){return document},getProtocol(){return this.getDocument().location.protocol},getAuthorizers(){return{ajax:Ce,jsonp:Ln}},onDocumentBody(_){document.body?_():setTimeout(()=>{this.onDocumentBody(_)},0)},createJSONPRequest(_,b){return new xn(_,b)},createScriptRequest(_){return new An(_)},getLocalStorage(){try{return window.localStorage}catch{return}},createXHR(){return this.getXHRAPI()?this.createXMLHttpRequest():this.createMicrosoftXHR()},createXMLHttpRequest(){var _=this.getXHRAPI();return new _},createMicrosoftXHR(){return new ActiveXObject("Microsoft.XMLHTTP")},getNetwork(){return $t},createWebSocket(_){var b=this.getWebSocketAPI();return new b(_)},createSocketRequest(_,b){if(this.isXHRSupported())return this.HTTPFactory.createXHR(_,b);if(this.isXDRSupported(b.indexOf("https:")===0))return this.HTTPFactory.createXDR(_,b);throw"Cross-origin HTTP requests are not supported"},isXHRSupported(){var _=this.getXHRAPI();return!!_&&new _().withCredentials!==void 0},isXDRSupported(_){var b=_?"https:":"http:",E=this.getProtocol();return!!window.XDomainRequest&&E===b},addUnloadListener(_){window.addEventListener!==void 0?window.addEventListener("unload",_,!1):window.attachEvent!==void 0&&window.attachEvent("onunload",_)},removeUnloadListener(_){window.addEventListener!==void 0?window.removeEventListener("unload",_,!1):window.detachEvent!==void 0&&window.detachEvent("onunload",_)},randomInt(_){return Math.floor(function(){return(window.crypto||window.msCrypto).getRandomValues(new Uint32Array(1))[0]/Math.pow(2,32)}()*_)}},Ve=Ss,qa;(function(_){_[_.ERROR=3]="ERROR",_[_.INFO=6]="INFO",_[_.DEBUG=7]="DEBUG"})(qa||(qa={}));var ca=qa;class Uc{constructor(b,E,D){this.key=b,this.session=E,this.events=[],this.options=D||{},this.sent=0,this.uniqueID=0}log(b,E){b<=this.options.level&&(this.events.push(ae({},E,{timestamp:me.now()})),this.options.limit&&this.events.length>this.options.limit&&this.events.shift())}error(b){this.log(ca.ERROR,b)}info(b){this.log(ca.INFO,b)}debug(b){this.log(ca.DEBUG,b)}isEmpty(){return this.events.length===0}send(b,E){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++,E&&E(I,ie)}),!0}generateUniqueID(){return this.uniqueID++,this.uniqueID}}class En{constructor(b,E,D,I){this.name=b,this.priority=E,this.transport=D,this.options=I||{}}isSupported(){return this.transport.isSupported({useTLS:this.options.useTLS})}connect(b,E){if(this.isSupported()){if(this.priority{D||(lt(),ie?ie.close():I.close())},forceMinPriority:Bt=>{D||this.priority{var E="socket_id="+encodeURIComponent(_.socketId);for(var D in b.params)E+="&"+encodeURIComponent(D)+"="+encodeURIComponent(b.params[D]);if(b.paramsProvider!=null){let I=b.paramsProvider();for(var D in I)E+="&"+encodeURIComponent(D)+"="+encodeURIComponent(I[D])}return E};var Es=_=>{if(typeof Ve.getAuthorizers()[_.transport]>"u")throw`'${_.transport}' is not a recognized auth transport`;return(b,E)=>{const D=Wo(b,_);Ve.getAuthorizers()[_.transport](Ve,D,_,A.UserAuthentication,E)}};const Bc=(_,b)=>{var E="socket_id="+encodeURIComponent(_.socketId);E+="&channel_name="+encodeURIComponent(_.channelName);for(var D in b.params)E+="&"+encodeURIComponent(D)+"="+encodeURIComponent(b.params[D]);if(b.paramsProvider!=null){let I=b.paramsProvider();for(var D in I)E+="&"+encodeURIComponent(D)+"="+encodeURIComponent(I[D])}return E};var Tf=_=>{if(typeof Ve.getAuthorizers()[_.transport]>"u")throw`'${_.transport}' is not a recognized auth transport`;return(b,E)=>{const D=Bc(b,_);Ve.getAuthorizers()[_.transport](Ve,D,_,A.ChannelAuthorization,E)}};const kf=(_,b,E)=>{const D={authTransport:b.transport,authEndpoint:b.endpoint,auth:{params:b.params,headers:b.headers}};return(I,ie)=>{const ye=_.channel(I.channelName);E(ye,D).authorize(I.socketId,ie)}};function Yo(_,b){let E={activityTimeout:_.activityTimeout||f.activityTimeout,cluster:_.cluster,httpPath:_.httpPath||f.httpPath,httpPort:_.httpPort||f.httpPort,httpsPort:_.httpsPort||f.httpsPort,pongTimeout:_.pongTimeout||f.pongTimeout,statsHost:_.statsHost||f.stats_host,unavailableTimeout:_.unavailableTimeout||f.unavailableTimeout,wsPath:_.wsPath||f.wsPath,wsPort:_.wsPort||f.wsPort,wssPort:_.wssPort||f.wssPort,enableStats:Mf(_),httpHost:Rf(_),useTLS:Lf(_),wsHost:Df(_),userAuthenticator:Pc(_),channelAuthorizer:Nf(_,b)};return"disabledTransports"in _&&(E.disabledTransports=_.disabledTransports),"enabledTransports"in _&&(E.enabledTransports=_.enabledTransports),"ignoreNullOrigin"in _&&(E.ignoreNullOrigin=_.ignoreNullOrigin),"timelineParams"in _&&(E.timelineParams=_.timelineParams),"nacl"in _&&(E.nacl=_.nacl),E}function Rf(_){return _.httpHost?_.httpHost:_.cluster?`sockjs-${_.cluster}.pusher.com`:f.httpHost}function Df(_){return _.wsHost?_.wsHost:Of(_.cluster)}function Of(_){return`ws-${_}.pusher.com`}function Lf(_){return Ve.getProtocol()==="https:"?!0:_.forceTLS!==!1}function Mf(_){return"enableStats"in _?_.enableStats:"disableStats"in _?!_.disableStats:!1}function Pc(_){const b=Object.assign(Object.assign({},f.userAuthentication),_.userAuthentication);return"customHandler"in b&&b.customHandler!=null?b.customHandler:Es(b)}function $f(_,b){let E;return"channelAuthorization"in _?E=Object.assign(Object.assign({},f.channelAuthorization),_.channelAuthorization):(E={transport:_.authTransport||f.authTransport,endpoint:_.authEndpoint||f.authEndpoint},"auth"in _&&("params"in _.auth&&(E.params=_.auth.params),"headers"in _.auth&&(E.headers=_.auth.headers)),"authorizer"in _&&(E.customHandler=kf(b,E,_.authorizer))),E}function Nf(_,b){const E=$f(_,b);return"customHandler"in E&&E.customHandler!=null?E.customHandler:Tf(E)}class If extends X{constructor(b){super(function(E,D){bt.debug(`No callbacks on watchlist events for ${E}`)}),this.pusher=b,this.bindWatchlistInternalEvent()}handleEvent(b){b.data.events.forEach(E=>{this.emit(E.name,E)})}bindWatchlistInternalEvent(){this.pusher.connection.bind("message",b=>{var E=b.event;E==="pusher_internal:watchlist_events"&&this.handleEvent(b)})}}function Hf(){let _,b;return{promise:new Promise((D,I)=>{_=D,b=I}),resolve:_,reject:b}}var Xo=Hf;class jf extends X{constructor(b){super(function(E,D){bt.debug("No callbacks on user for "+E)}),this.signin_requested=!1,this.user_data=null,this.serverToUserChannel=null,this.signinDonePromise=null,this._signinDoneResolve=null,this._onAuthorize=(E,D)=>{if(E){bt.warn(`Error during signin: ${E}`),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:E,current:D})=>{E!=="connected"&&D==="connected"&&this._signin(),E==="connected"&&D!=="connected"&&(this._cleanup(),this._newSigninPromiseIfNeeded())}),this.watchlist=new If(b),this.pusher.connection.bind("message",E=>{var D=E.event;D==="pusher:signin_success"&&this._onSigninSuccess(E.data),this.serverToUserChannel&&this.serverToUserChannel.name===E.channel&&this.serverToUserChannel.handleEvent(E)})}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{bt.error(`Failed parsing user data after signin: ${b.user_data}`),this._cleanup();return}if(typeof this.user_data.id!="string"||this.user_data.id===""){bt.error(`user_data doesn't contain an id. user_data: ${this.user_data}`),this._cleanup();return}this._signinDoneResolve(),this._subscribeChannels()}_subscribeChannels(){const b=E=>{E.subscriptionPending&&E.subscriptionCancelled?E.reinstateSubscription():!E.subscriptionPending&&this.pusher.connection.state==="connected"&&E.subscribe()};this.serverToUserChannel=new hs(`#server-to-user-${this.user_data.id}`,this.pusher),this.serverToUserChannel.bind_global((E,D)=>{E.indexOf("pusher_internal:")===0||E.indexOf("pusher:")===0||this.emit(E,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:E}=Xo();b.done=!1;const D=()=>{b.done=!0};b.then(D).catch(D),this.signinDonePromise=b,this._signinDoneResolve=E}}class rn{static ready(){rn.isReady=!0;for(var b=0,E=rn.instances.length;bVe.getDefaultStrategy(this.config,I,ki);this.connection=kr.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=>{bt.warn(I)}),rn.instances.push(this),this.timeline.info({instances:rn.instances.length}),this.user=new jf(this),rn.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(),E=this.timelineSender;this.timelineSenderTimer=new ge(6e4,function(){E.send(b)})}}disconnect(){this.connection.disconnect(),this.timelineSenderTimer&&(this.timelineSenderTimer.ensureAborted(),this.timelineSenderTimer=null)}bind(b,E,D){return this.global_emitter.bind(b,E,D),this}unbind(b,E,D){return this.global_emitter.unbind(b,E,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 E=this.channels.add(b,this);return E.subscriptionPending&&E.subscriptionCancelled?E.reinstateSubscription():!E.subscriptionPending&&this.connection.state==="connected"&&E.subscribe(),E}unsubscribe(b){var E=this.channels.find(b);E&&E.subscriptionPending?E.cancelSubscription():(E=this.channels.remove(b),E&&E.subscribed&&E.unsubscribe())}send_event(b,E,D){return this.connection.send_event(b,E,D)}shouldUseTLS(){return this.config.useTLS}signin(){this.user.signin()}}rn.instances=[],rn.isReady=!1,rn.logToConsole=!1,rn.Runtime=Ve,rn.ScriptReceivers=Ve.ScriptReceivers,rn.DependenciesReceivers=Ve.DependenciesReceivers,rn.auth_callbacks=Ve.auth_callbacks;var Jo=a.default=rn;function qc(_){if(_==null)throw"You must pass your app key when you instantiate Pusher."}Ve.setup(rn)})])})})(hf)),hf.exports}var w_=S_();const iy=Qr(w_),Ht=ut("WebSocketManager");class C_{constructor(){$(this,"echo",null);$(this,"subscriptions",new Map);$(this,"initialized",!1);$(this,"config",null)}configure(e){if(this.initialized){Ht.warn("[WebSocketManager] 이미 초기화되어 설정을 변경할 수 없습니다.");return}this.config=e,Ht.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){Ht.warn("[WebSocketManager] WebSocket 설정이 없습니다. initTemplateApp에서 websocket 옵션을 전달해주세요.");return}const{appKey:e,host:r="localhost",port:a=80,scheme:i="https",authEndpoint:l="/api/broadcasting/auth"}=this.config,c=Number(a)||80,d=i==="https";Ht.log("[WebSocketManager] 연결 설정:",{host:r,port:c,scheme:i,useTLS:d,authEndpoint:l}),window.Pusher=iy;const f=localStorage.getItem("auth_token"),g={wsHost:r,wsPort:c,wssPort:c,forceTLS:d,disableStats:!0,enabledTransports:["ws","wss"],cluster:"mt1",authEndpoint:l,auth:{headers:{Authorization:f?`Bearer ${f}`:"",Accept:"application/json"}}};Ht.log("[WebSocketManager] Pusher 옵션:",g);const m=new iy(e,g);m.connection.bind("connecting",()=>{Ht.log("[WebSocketManager] 연결 시도 중...")}),m.connection.bind("connected",()=>{Ht.log("[WebSocketManager] 연결 성공! Socket ID:",m.connection.socket_id)}),m.connection.bind("failed",()=>{Ht.error("[WebSocketManager] 연결 실패 - WebSocket을 사용할 수 없습니다.")}),m.connection.bind("error",y=>{Ht.error("[WebSocketManager] 연결 오류:",y)}),m.connection.bind("state_change",y=>{Ht.log(`[WebSocketManager] 상태 변경: ${y.previous} → ${y.current}`)}),m.connection.bind("unavailable",()=>{Ht.error("[WebSocketManager] WebSocket 사용 불가 - 연결할 수 없습니다.")}),m.connection.bind("disconnected",()=>{Ht.warn("[WebSocketManager] 연결이 끊어졌습니다.")}),Ht.log("[WebSocketManager] 초기 연결 상태:",m.connection.state),this.echo=new v_({broadcaster:"reverb",client:m}),Ht.log("[WebSocketManager] 연결 시작 시도..."),m.connect(),window.Echo=this.echo,this.initialized=!0,Ht.log("[WebSocketManager] Echo 초기화 완료")}subscribe(e,r,a,i={}){if(this.initialize(),!this.echo)return Ht.warn("[WebSocketManager] Echo가 초기화되지 않았습니다."),"";const{channelType:l="private"}=i,c=`${e}:${r}`;if(this.subscriptions.has(c))return Ht.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(`.${r}`,a),this.subscriptions.set(c,d),Ht.log(`[WebSocketManager] 구독 완료: ${c} (${l})`),c}unsubscribe(e){const r=this.subscriptions.get(e);if(!r)return;const a=e.lastIndexOf(":"),i=a>=0?e.substring(a+1):"";if(i)try{r.stopListening(`.${i}`)}catch(l){Ht.warn(`[WebSocketManager] stopListening 실패: ${e}`,l)}this.subscriptions.delete(e),Ht.log(`[WebSocketManager] 구독 해제: ${e}`)}leaveChannel(e){if(!this.echo)return;this.echo.leave(e);const r=[];this.subscriptions.forEach((a,i)=>{i.startsWith(`${e}:`)&&r.push(i)}),r.forEach(a=>this.subscriptions.delete(a)),Ht.log(`[WebSocketManager] 채널 구독 해제: ${e}`)}disconnect(){this.echo&&(this.echo.disconnect(),this.subscriptions.clear(),this.initialized=!1,Ht.log("[WebSocketManager] 연결 종료"))}getEcho(){return this.echo}isInitialized(){return this.initialized}isConfigured(){return this.config!==null&&!!this.config.appKey}getSubscriptionCount(){return this.subscriptions.size}}const Tc=new C_,gt=ut("DataSourceManager"),sy=new _n;function kc(o,e){const r=Ta(o);if(r!==null)try{return Gn(r)?sy.evaluatePipeExpression(r,e,{skipCache:!0}):sy.evaluateExpression(r,e)}catch(a){return gt.error("Failed to evaluate param expression:",r,a),o}return Zi(o,e,{skipCache:!0})}function oy(o){const e={};for(const r of o.keys()){if(r in e)continue;const a=o.getAll(r);a.length>1?e[r]=a:a.length===1&&(r.endsWith("[]")?e[r]=a:e[r]=a[0])}return e}function E_(){try{return window.G7Core?.devTools}catch{return}}const Lc=class Lc{constructor(e={}){$(this,"options");$(this,"dataCache",new Map);$(this,"bindingEngine");$(this,"globalHeaders",[]);this.options=e,this.bindingEngine=new _n}setGlobalHeaders(e){this.globalHeaders=e||[]}matchesPattern(e,r){if(r==="*")return!0;const a=r.replace(/[.+?^${}()|[\]\\]/g,"\\$&").replace(/\*/g,".*");return new RegExp(`^${a}$`).test(e)}toFormData(e){const r=new FormData;for(const[a,i]of Object.entries(e))i instanceof File||i instanceof Blob?r.append(a,i):i!=null&&r.append(a,typeof i=="object"?JSON.stringify(i):String(i));return r}getMatchingGlobalHeaders(e,r){const a={};for(const i of this.globalHeaders)this.matchesPattern(e,i.pattern)&&Object.entries(i.headers).forEach(([l,c])=>{const d=kc(c,r);d!=null&&d!==""&&(a[l]=String(d))});return a}filterByCondition(e,r={}){const a=new Set,i=[];for(const l of e){if(a.has(l.id))continue;if(!l.if&&!l.conditions){a.add(l.id),i.push(l);continue}Qi({if:l.if,conditions:l.conditions},r,this.bindingEngine,`data_source:${l.id}`)&&(a.add(l.id),i.push(l))}return i}checkErrorCondition(e,r){if(!e.errorCondition?.if||e.errorCondition?.errorCode===void 0)return null;try{const a={response:r};if(Qi({if:e.errorCondition.if},a,this.bindingEngine,`errorCondition:${e.id}`))return gt.log(`errorCondition matched for ${e.id}, triggering error ${e.errorCondition.errorCode}`),e.errorCondition.errorCode}catch(a){gt.error(`Failed to evaluate errorCondition for ${e.id}:`,a)}return null}async fetchDataSources(e,r={},a=new URLSearchParams,i,l){const c={},d=!!this.options.sampleProvider,f=e.filter(g=>(d||g.auto_fetch!==!1)&&g.type!=="websocket");return await Promise.all(f.map(async g=>{try{const m=await this.fetchDataSource(g,r,a,i,l);c[g.id]=m,this.dataCache.set(g.id,{data:m,timestamp:Date.now()});const y=this.checkErrorCondition(g,m);if(y!==null){const w={status:y,message:`Error condition matched for ${g.id}`,data:m},S=Sr(),v=S.resolve(y,{errorHandling:g.errorHandling,onError:g.onError});if(v.handler)try{await S.execute(v.handler,w)}catch(A){gt.error(`Error executing errorCondition handler for ${g.id}:`,A)}g.fallback!==void 0&&(c[g.id]=g.fallback,this.dataCache.set(g.id,{data:g.fallback,timestamp:Date.now()}),gt.log(`Using fallback data for ${g.id} (errorCondition)`));return}if(g.onSuccess)try{const w={data:m,sourceId:g.id};await this.executeOnSuccessHandler(g.onSuccess,w)}catch(w){gt.error(`Error executing onSuccess handler for ${g.id}:`,w)}}catch(m){gt.error(`Failed to fetch data source: ${g.id}`,m);const y=m?.response?.status||m?.status||500,w=m?.response?.data,S=w?.message||m.message||"Unknown error",v={status:y,message:S,errors:w?.errors,data:w,statusText:m?.response?.statusText},A=Sr(),x=A.resolve(y,{errorHandling:g.errorHandling,onError:g.onError});if(x.handler)try{await A.execute(x.handler,v)}catch(R){gt.error(`Error executing error handler for ${g.id}:`,R)}g.fallback!==void 0&&(c[g.id]=g.fallback,this.dataCache.set(g.id,{data:g.fallback,timestamp:Date.now()}),gt.log(`Using fallback data for ${g.id}`)),this.options.onError&&this.options.onError(m,g)}})),c}async fetchDataSourcesWithResults(e,r={},a=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,r,a,i,l);this.dataCache.set(m.id,{data:y,timestamp:Date.now()});const w=this.checkErrorCondition(m,y);if(w!==null){const S={status:w,message:`Error condition matched for ${m.id}`,data:y},v=Sr(),A=v.resolve(w,{errorHandling:m.errorHandling,onError:m.onError});let x=!1;if(A.handler)if(m.loading_strategy==="blocking")v.execute(A.handler,S).catch(R=>{gt.error(`Error executing errorCondition handler for ${m.id}:`,R)}),x=!0;else try{await v.execute(A.handler,S),x=!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: ${w}`),errorCode:w,errorHandled:x}}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 w=y?.response?.status||y?.status||500,S=y?.response?.data,v=S?.message||y.message||"Unknown error",A={status:w,message:v,errors:S?.errors,data:S,statusText:y?.response?.statusText},x=Sr(),R=x.resolve(w,{errorHandling:m.errorHandling,onError:m.onError});let M=!1;if(R.handler)if(m.loading_strategy==="blocking")x.execute(R.handler,A).catch(O=>{gt.error(`Error executing error handler for ${m.id}:`,O)}),M=!0;else try{await x.execute(R.handler,A),M=!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:w,errorHandled:M})}}))}fetchDataSourcesInBackground(e,r={},a=new URLSearchParams,i){e.filter(c=>c.auto_fetch!==!1&&c.loading_strategy==="background"&&c.type!=="websocket").forEach(c=>{this.fetchDataSource(c,r,a).then(async d=>{this.dataCache.set(c.id,{data:d,timestamp:Date.now()});const f=this.checkErrorCondition(c,d);if(f!==null){const g={status:f,message:`Error condition matched for ${c.id}`,data:d},m=Sr(),y=m.resolve(f,{errorHandling:c.errorHandling,onError:c.onError});if(y.handler)try{await m.execute(y.handler,g)}catch(w){gt.error(`Error executing errorCondition handler for ${c.id}:`,w)}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 g={data:d,sourceId:c.id};await this.executeOnSuccessHandler(c.onSuccess,g)}catch(g){gt.error(`Error executing onSuccess handler for ${c.id}:`,g)}i&&i(c.id,d)}).catch(async d=>{gt.error(`Background fetch failed: ${c.id}`,d);const f=d?.response?.status||d?.status||500,g=d?.response?.data,m=g?.message||d.message||"Unknown error",y={status:f,message:m,errors:g?.errors,data:g,statusText:d?.response?.statusText},w=Sr(),S=w.resolve(f,{errorHandling:c.errorHandling,onError:c.onError});if(S.handler)try{await w.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,r,a,i,l){switch(e.type){case"api":return this.fetchApiDataSource(e,r,a,i,l);case"static":return e.data;case"route_params":return r;case"query_params":return oy(a);default:throw new Error(`Unknown data source type: ${e.type}`)}}async fetchApiDataSource(e,r,a,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:r,query:oy(a)};i&&(c._global=i),l&&(c._local=l);let d=Zi(e.endpoint,c,{skipCache:!0});const f=e.method||"GET",m=(e.contentType?typeof e.contentType=="string"&&e.contentType.includes("{{")?Zi(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,A])=>{typeof A=="string"&&(y[v]=kc(A,c))}),Object.keys(y).forEach(v=>{y[v]===""&&delete y[v]});const w=E_();let S=null;if(w?.isEnabled()){w.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 A=new URLSearchParams;Object.entries(y).forEach(([R,M])=>{Array.isArray(M)?M.forEach(O=>A.append(R,String(O))):M!=null&&A.append(R,String(M))});const x=A.toString();v=x?`${d}?${x}`:d}S=w.trackRequest(v,f,{requestBody:f!=="GET"?y:void 0,dataSourceId:e.id}),w.trackDataSourceLoading(e.id)}try{let v;const A=e.auth_mode??(e.auth_required===!0?"required":"none"),x=br.getInstance().isAuthenticated();if(A==="required"&&!x){gt.log(`[DataSourceManager] Skipping ${e.id}: auth_mode is 'required' but no token available`),w?.isEnabled()&&(w.trackDataSourceError(e.id,"Skipped: auth_mode required but not authenticated"),S&&w.failRequest(S,"Skipped: not authenticated"));const M=new Error("Auth required but not authenticated");throw M.response={status:401,statusText:"Unauthorized",data:null},M.status=401,M._authSkipped=!0,M}const R=A==="required"||A==="optional"&&x;if(R){const M=jr(),O=d.startsWith("/api/")?d.substring(4):d.startsWith("/api")?d.substring(4)||"/":d;this.options.onError&>.log(`[DataSourceManager] Normalized endpoint: ${d} -> ${O}`);const L=this.getMatchingGlobalHeaders(d,c),q={};e.headers&&Object.entries(e.headers).forEach(([fe,Ce])=>{const ke=kc(Ce,c);ke!=null&&ke!==""&&(q[fe]=String(ke))});const G={...L,...q},B=Object.keys(G).length>0,K=m?this.toFormData(y):y;switch(f){case"GET":v=await M.get(O,{params:y,...B&&{headers:G}});break;case"POST":B?v=await M.post(O,K,{headers:G}):v=await M.post(O,K);break;case"PUT":B?v=await M.put(O,K,{headers:G}):v=await M.put(O,K);break;case"PATCH":B?v=await M.patch(O,K,{headers:G}):v=await M.patch(O,K);break;case"DELETE":v=await M.delete(O,{params:y,...B&&{headers:G}});break;default:throw new Error(`Unsupported HTTP method: ${f}`)}}else{let M=d;if(f==="GET"){const K=new URLSearchParams(y).toString();M=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 L=this.getMatchingGlobalHeaders(d,c);Object.assign(O,L),e.headers&&Object.entries(e.headers).forEach(([K,fe])=>{const Ce=kc(fe,c);Ce!=null&&Ce!==""&&(O[K]=String(Ce))});let q;f!=="GET"&&(m?(q=this.toFormData(y),delete O["Content-Type"]):q=JSON.stringify(y));const G=await fetch(M,{method:f,headers:O,body:q});let B;try{B=await G.json()}catch{B=null}if(S&&w?.isEnabled()&&(w.completeRequest(S,G.status,B),S=null),!G.ok){w?.isEnabled()&&w.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:B},K.status=G.status,K}v=B,w?.isEnabled()&&w.trackDataSourceLoaded(e.id,v)}return R&&S&&w?.isEnabled()&&(w.completeRequest(S,200,v),w.trackDataSourceLoaded(e.id,v)),v}catch(v){if(S&&w?.isEnabled()){const A=v;A?.response?w.completeRequest(S,A.response.status,A.response.data):w.failRequest(S,v instanceof Error?v.message:String(v)),w.trackDataSourceError(e.id,v instanceof Error?v.message:String(v))}throw v}}getCachedData(e){const r=this.dataCache.get(e);if(!r)return;if(Date.now()-r.timestamp>Lc.DATA_CACHE_TTL){this.dataCache.delete(e);return}return r.data}clearCache(){this.dataCache.clear()}subscribeWebSockets(e,r,a={}){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=Zi(c.channel,a,{skipCache:!0}),f=Zi(c.event,a,{skipCache:!0})}catch(y){gt.error(`Failed to resolve WebSocket channel/event for source ${c.id}:`,y);return}const g=y=>!!(!y||y.trim()===""||y.includes("{{")||y.endsWith(".")||y.endsWith(":")||y.startsWith(".")||y.startsWith(":")||y.includes("..")||y.includes("::"));if(g(d)||g(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(a).join(", ")}]`);return}const m=Tc.subscribe(d,f,y=>{const w=c.target_source||c.id;this.dataCache.set(w,{data:y,timestamp:Date.now()}),r(w,y)},{channelType:c.channel_type||"private"});m&&i.push(m)}),i}unsubscribeWebSockets(e){e.length!==0&&e.forEach(r=>{Tc.unsubscribe(r)})}async executeOnSuccessHandler(e,r){const a=this.options.actionDispatcher??am();if(!a){gt.warn("ActionDispatcher not available, skipping onSuccess handler");return}const i=Array.isArray(e)?e:[e];for(const l of i)try{await a.dispatchAction({type:"click",...l},{data:{response:r}})}catch(c){throw gt.error("Failed to execute onSuccess handler:",c),c}}};$(Lc,"DATA_CACHE_TTL",3e5);let _r=Lc;const __=new _r,Si=ut("ModalDataSourceWrapper");function A_(o,e){if(!o||!e)return o;const a=e.replace(/\?\./g,".").split(/\.(?![^\[]*\])/).flatMap(l=>{const c=l.match(/^([^\[]*)((?:\[\d+\])*)$/);if(c){const[,d,f]=c,g=[];d&&g.push(d);const m=f.match(/\[\d+\]/g);return m&&g.push(...m),g}return[l]}).filter(l=>l!=="");let i=o;for(const l of a){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 ly=({isOpen:o,modalId:e,dataSources:r,dataContext:a,globalStateUpdater:i,bindingEngine:l,debug:c=!1,children:d})=>{const[f,g]=N.useState(!1),[m,y]=N.useState(!1),w=N.useRef(!1),S=N.useRef(null);S.current||(S.current=new _r);const v=N.useCallback(async()=>{if(!(!r||r.length===0)&&S.current){g(!0);try{const A=a.route||{},x=new URLSearchParams(window.location.search),R=r.map(O=>{let L={...O};if(O.endpoint&&l){const q=l.resolveBindings(O.endpoint,a,{skipCache:!0});L.endpoint=q}if(O.params&&l){const q={};Object.entries(O.params).forEach(([G,B])=>{typeof B=="string"?q[G]=l.resolveBindings(B,a,{skipCache:!0}):q[G]=B}),L.params=q}return L});c&&Si.log(`[ModalDataSourceWrapper] Modal "${e}" fetching data sources:`,R.map(O=>({id:O.id,endpoint:O.endpoint})));const M=await S.current.fetchDataSourcesWithResults(R,A,x);i&&M.forEach(O=>{if(O.state==="success"&&O.data!==void 0){const L=R.find(q=>q.id===O.id);if(L?.initGlobal){const q=O.data?.data??O.data,G=Array.isArray(L.initGlobal)?L.initGlobal:[L.initGlobal];for(const B of G)if(typeof B=="string")i({[B]:q}),c&&Si.log(`[ModalDataSourceWrapper] Modal "${e}" initGlobal: ${O.id}.data -> _global.${B}`);else if(typeof B=="object"&&B.key){const{key:K,path:fe}=B,Ce=fe?A_(q,fe):q;i({[K]:Ce}),c&&Si.log(`Modal "${e}" initGlobal: ${O.id}.data${fe?"."+fe:""} -> _global.${K}`)}}}else O.state==="error"&&Si.error(`Modal "${e}" data source error:`,O.id,O.error)}),c&&Si.log(`Modal "${e}" data sources fetched successfully`)}catch(A){Si.error(`Modal "${e}" data source fetch error:`,A)}finally{g(!1),y(!0)}}},[r,a,i,l,e,c]);return N.useEffect(()=>{if(!r||r.length===0)return;const A=window.__templateApp;return A?.registerModalDataSources&&A.registerModalDataSources(e,r),()=>{A?.unregisterModalDataSources&&A.unregisterModalDataSources(e)}},[e,r]),N.useEffect(()=>{!o&&w.current&&(y(!1),c&&Si.log(`[ModalDataSourceWrapper] Modal "${e}" closed, reset fetch state`)),o&&!w.current&&r&&r.length>0&&!m&&v(),w.current=o},[o,r,m,v,e,c]),dt.jsx(dt.Fragment,{children:d})};class Rc extends Error{constructor(r,a,i={}){super(a);$(this,"code");$(this,"userMessageKey");$(this,"showStack");$(this,"icon");$(this,"recoverable");this.name="TemplateEngineError",this.code=r,this.userMessageKey=a,this.showStack=i.showStack??!0,this.icon=i.icon??"fa-circle-exclamation",this.recoverable=i.recoverable??!0,Error.captureStackTrace&&Error.captureStackTrace(this,this.constructor)}getUserMessage(r,a){if(!a||!r)return this.userMessageKey;try{return a.translate(this.userMessageKey,r)}catch{return this.userMessageKey}}}class x_ extends Rc{constructor(){super("TEMPLATE_NOT_FOUND","$t:core.errors.template_not_found",{showStack:!1,icon:"fa-paint-brush",recoverable:!1}),this.name="TemplateNotFoundError"}}function cy(o){if(o instanceof Rc)return o;if(o instanceof Error){const e=new Rc("TEMPLATE_INIT_ERROR",o.message||"$t:core.errors.template_init_error",{showStack:!0,icon:"fa-circle-exclamation",recoverable:!0});return e.stack=o.stack,e}return new Rc("TEMPLATE_INIT_ERROR","$t:core.errors.template_init_error",{showStack:!1,icon:"fa-circle-exclamation",recoverable:!0})}const T_=ut("ErrorDisplay");class gf{static render(e,r){const a=document.getElementById(e);if(!a){T_.error(`Container #${e} not found`);return}const i=r.debug&&r.showStack&&r.stackTrace,l=window.matchMedia("(prefers-color-scheme: dark)").matches,c={container:` display: flex; align-items: center; justify-content: center; @@ -178,23 +221,23 @@ Error generating stack: `+u.message+`
- +

- ${this.escapeHtml(n.title)} + ${this.escapeHtml(r.title)}

- ${this.escapeHtml(n.message)} + ${this.escapeHtml(r.message)}

- ${n.detailMessage?` + ${r.detailMessage?`

- ${this.escapeHtml(n.detailMessage)} + ${this.escapeHtml(r.detailMessage)}

`:`
`} @@ -204,12 +247,12 @@ Error generating stack: `+u.message+`

Stack Trace:

-
${this.escapeHtml(n.stackTrace)}
+
${this.escapeHtml(r.stackTrace)}
`:""} - ${n.showReloadButton?` + ${r.showReloadButton?`
- `}static renderFromError(e,n,a,i=!1,l,c,d){let f,g;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?g=m.details.apiMessage:m.response?.data?.message&&(g=m.response.data.message)}this.render(e,{title:a,message:f,detailMessage:g,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 fs=ut("Router");class X_{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 a=this.eventHandlers.get(e);a&&await Promise.all(a.map(i=>i(...n)))}async loadRoutes(e){try{const n=e!==void 0&&e>0?e:null,a=await fetch($r(`/api/templates/${this.templateIdentifier}/routes`,"json",n));if(!a.ok)throw new Error(`Failed to load routes: ${a.statusText}`);const i=await a.json();if(!i.success)throw new Error("Failed to load routes from API");if(i.data&&Array.isArray(i.data.routes))this.routes=i.data.routes,fs.log(`Loaded ${this.routes.length} routes${e?` (v=${e})`:""}`);else throw new Error("Invalid routes data format")}catch(n){throw fs.error("Error loading routes:",n),n}}setRoutes(e){this.routes=e,fs.log(`Set ${this.routes.length} routes`)}match(e){const n=this.normalizePathname(e);for(const a of this.routes){const i=this.matchPattern(a.path,n);if(i!==null)return{route:a,params:i}}return null}normalizePathname(e){return e.length>1&&e.endsWith("/")?e.replace(/\/+$/,"")||"/":e}matchPattern(e,n){const a=[];let i=e.replace(/:([^/]+)/g,(f,g)=>(a.push(g),"([^/]+)"));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 a.forEach((f,g)=>{d[f]=c[g+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,a=this.match(e);if(!a){fs.warn(`No route matched for path: ${e}`),this.emit("routeNotFound",e);return}if(a.route.redirect){fs.log(`Redirecting from ${e} to ${a.route.redirect}`),this.navigate(a.route.redirect);return}if(a.route.auth_required){const c=this.getAuthType(a.route,e),d=yr.getInstance();let f=d.isAuthenticated()&&d.getAuthType()===c;if(f||(f=await d.checkAuth(c)),!f){const g=d.getLoginRedirectUrl(c,e+n);fs.log(`Not authenticated, redirecting to: ${g}`),window.location.href=g;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:a.route.layout,endpoint:a.route.endpoint,params:{...a.route.params||{},...a.params},query:l,auth_required:a.route.auth_required,auth_type:a.route.auth_type,meta:a.route.meta})}navigate(e){if(this.isNavigating){this.pendingNavigation=e;return}this.executeNavigation(e)}async executeNavigation(e){this.isNavigating=!0,this.pendingNavigation=null;try{window.history.pushState({},"",e),await this.navigateToCurrentPath()}finally{if(this.isNavigating=!1,this.pendingNavigation){const n=this.pendingNavigation;this.executeNavigation(n)}}}}const J_=/^\/admin\/layout-editor\/([^/?#]+)\/?$/;function my(o){const e=J_.exec(o);return e?{templateIdentifier:e[1]}:null}const Bt=ut("ErrorPageHandler");class Q_{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($r(`/api/templates/${this.templateId}/config`,"json"));if(!e.ok)return this.debug&&Bt.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&&Bt.warn("Invalid template config response"),this.configLoaded=!0,null;const a=n.data;return!a.error_config||!a.error_config.layouts?(this.debug&&Bt.warn("No error_config found in template.json"),this.configLoaded=!0,null):(this.errorConfig=a.error_config,this.configLoaded=!0,this.debug&&Bt.log("Error config loaded:",this.errorConfig),this.errorConfig)}catch(e){return Bt.error("Failed to load error config:",e),this.configLoaded=!0,null}}async renderError(e,n="app"){try{const a=await this.loadConfig();if(!a)return this.debug&&Bt.warn("No error config available, cannot render error page"),!1;const i=a.layouts[e]||a.layouts[String(e)];if(!i)return this.debug&&Bt.warn(`No layout defined for error code: ${e}`),!1;this.debug&&Bt.log(`Loading error layout: ${i} for code: ${e}`);const l=await this.layoutLoader.loadLayout(this.templateId,i);if(!l)return this.debug&&Bt.error(`Failed to load error layout: ${i}`),!1;this.debug&&Bt.log("Error layout loaded:",l);let c={};const d=l.data_sources||[];if(d.length>0){this.debug&&Bt.log("Fetching data sources:",d.map(v=>v.id));const m=d.filter(v=>v.loading_strategy==="blocking"),b=d.filter(v=>!v.loading_strategy||v.loading_strategy==="progressive"),S=[...m,...b];if(S.length>0)try{c=await this.dataSourceManager.fetchDataSources(S,{},new URLSearchParams),this.debug&&Bt.log("Data sources fetched:",Object.keys(c))}catch(v){Bt.error("Failed to fetch data sources:",v)}}const f={};d.length>0&&(this.processInitOptions(d,c,f),this.debug&&Bt.log("initOptions processed:",{globalKeys:Object.keys(this.globalState),localKeys:Object.keys(f)}));const g={...c,errorCode:e,_global:{...this.globalState},_local:{...f}};return await this.renderFunction({containerId:n,layoutJson:l,dataContext:g,translationContext:{templateId:this.templateId,locale:this.locale}}),this.debug&&Bt.log(`Error page ${e} rendered successfully`),!0}catch(a){return Bt.error(`Failed to render error page ${e}:`,a),!1}}processInitOptions(e,n,a){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")a[i.initLocal]=c,Bt.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;a[d]=f?this.getValueByPath(c,f):c,Bt.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,Bt.log(`initGlobal: ${i.id}.data -> _global.${f}`);else if(typeof f=="object"&&f!==null&&"key"in f){const{key:g,path:m}=f;this.globalState[g]=m?this.getValueByPath(c,m):c,Bt.log(`initGlobal: ${i.id}.data${m?"."+m:""} -> _global.${g}`)}}}}getValueByPath(e,n){return n.split(".").reduce((a,i)=>a?.[i],e)}updateGlobalState(e){this.globalState={...this.globalState,...e}}updateLocale(e){this.locale=e,this.debug&&Bt.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&&Bt.log("Config cache cleared")}}const $t=ut("ModuleAssetLoader");class Z_{constructor(){$(this,"loadedAssets",new Map);$(this,"loadingPromises",new Map);$(this,"failedJsAssets",new Set)}hasFailedJsAssets(){return this.failedJsAssets.size>0}getFailedJsAssets(){return[...this.failedJsAssets]}async loadActiveExtensionAssets(e){if(!e||e.length===0){$t.log("No module assets to load");return}const n=[...e].sort((d,f)=>d.priority-f.priority);$t.log("Loading module assets:",n.map(d=>d.identifier));const a=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([...a,...i]),c=l.filter(d=>d.status==="rejected");if(c.length>0){$t.warn(`Some module assets failed to load (${c.length}/${l.length}); continuing with the rest`,this.getFailedJsAssets());return}$t.log("All module assets loaded successfully")}async loadBundle(e,n,a){const i=[];if(a&&i.push(this.loadBundleCss(e,a)),n&&i.push(this.loadBundleJs(e,n)),i.length===0){$t.log(`No bundle assets to load for: ${e}`);return}await Promise.all(i)}async loadBundleCss(e,n){const a=`ext-bundle-css-${e}`;if(document.getElementById(a)){$t.log(`Bundle CSS already loaded: ${e}`);return}return new Promise(i=>{const l=document.createElement("link");l.rel="stylesheet",l.href=n,l.id=a,l.onload=()=>{$t.log(`Bundle CSS loaded: ${e}`),this.registerLoadedAsset(`bundle-${e}`,{type:"css",element:l}),i()},l.onerror=()=>{$t.warn(`Failed to load bundle CSS: ${e} (${n})`),i()},document.head.appendChild(l)})}async loadBundleJs(e,n){const a=`ext-bundle-js-${e}`;if(document.getElementById(a)){$t.log(`Bundle JS already loaded: ${e}`);return}const i=this.loadingPromises.get(a);if(i)return $t.log(`Bundle JS already loading: ${e}`),i;const l=sp(n,{id:a},{label:`bundle JS: ${e}`}).then(()=>{$t.log(`Bundle JS loaded: ${e}`);const c=document.getElementById(a);c&&this.registerLoadedAsset(`bundle-${e}`,{type:"js",element:c}),this.loadingPromises.delete(a)}).catch(c=>{throw $t.warn(`Failed to load bundle JS: ${e} (${n})`,c),this.failedJsAssets.add(e),this.loadingPromises.delete(a),c});return this.loadingPromises.set(a,l),l}async loadCSS(e,n){const a=`module-css-${e}`;if(document.getElementById(a)){$t.log(`CSS already loaded: ${e}`);return}return new Promise((i,l)=>{const c=document.createElement("link");c.rel="stylesheet",c.href=n,c.id=a,c.onload=()=>{$t.log(`CSS loaded: ${e}`),this.registerLoadedAsset(e,{type:"css",element:c}),i()},c.onerror=()=>{$t.warn(`Failed to load CSS: ${e} (${n})`),i()},document.head.appendChild(c)})}async loadJS(e,n){const a=`module-js-${e}`;if(document.getElementById(a)){$t.log(`JS already loaded: ${e}`);return}const i=this.loadingPromises.get(e);if(i)return $t.log(`JS already loading: ${e}`),i;const l=sp(n,{id:a},{label:`JS: ${e}`}).then(()=>{$t.log(`JS loaded: ${e}`);const c=document.getElementById(a);c&&this.registerLoadedAsset(e,{type:"js",element:c}),this.loadingPromises.delete(e)}).catch(c=>{throw $t.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 a=this.loadedAssets.get(e)||[];a.push(n),this.loadedAssets.set(e,a)}unloadExtensionAsset(e){const n=this.loadedAssets.get(e);if(!n||n.length===0){$t.log(`No assets to unload for: ${e}`);return}n.forEach(a=>{a.element.parentNode&&(a.element.parentNode.removeChild(a.element),$t.log(`${a.type.toUpperCase()} unloaded: ${e}`))}),this.loadedAssets.delete(e),$t.log(`All assets unloaded for: ${e}`)}unloadAllAssets(){Array.from(this.loadedAssets.keys()).forEach(n=>{this.unloadExtensionAsset(n)}),$t.log("All module assets unloaded")}isLoaded(e){return this.loadedAssets.has(e)}getLoadedModules(){return Array.from(this.loadedAssets.keys())}}let Sf=null;function wf(){return Sf||(Sf=new Z_),Sf}function eA(){if(typeof window>"u")return[];const o=window.G7Config;if(!o?.moduleAssets)return[];const e=[];for(const[n,a]of Object.entries(o.moduleAssets)){const i=a;e.push({identifier:n,js:i.js?Ea(i.js):i.js,css:i.css?Ea(i.css):i.css,priority:i.priority,external:i.external})}return e}function tA(){if(typeof window>"u")return null;const o=window.G7Config;if(!o?.bundleUrls)return null;const e=o.bundleUrls;return{moduleJs:e.moduleJs?Ea(e.moduleJs):e.moduleJs,moduleCss:e.moduleCss?Ea(e.moduleCss):e.moduleCss,pluginJs:e.pluginJs?Ea(e.pluginJs):e.pluginJs,pluginCss:e.pluginCss?Ea(e.pluginCss):e.pluginCss}}function nA(){if(typeof window>"u")return[];const o=window.G7Config;if(!o?.pluginAssets)return[];const e=[];for(const[n,a]of Object.entries(o.pluginAssets)){const i=a;e.push({identifier:n,js:i.js?Ea(i.js):i.js,css:i.css?Ea(i.css):i.css,priority:i.priority,external:i.external})}return e}const Cf=ut("SystemBannerManager");class Cc{static show(e){this.banners.set(e.id,e),this.render(),Cf.log(`Banner shown: ${e.id}`)}static hide(e){this.banners.delete(e)&&(this.render(),Cf.log(`Banner hidden: ${e}`))}static hideAll(){this.banners.clear(),this.render(),Cf.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)),a=this.detectLocale();e.innerHTML=n.map(i=>{const l=this.resolveMessage(i.message,a),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`:"")}}$(Cc,"banners",new Map),$(Cc,"containerId","g7-system-banners");const U=ut("TemplateApp");function yy(o){const e={};for(const n of o.keys()){if(n in e)continue;const a=o.getAll(n);a.length>1?e[n]=a:a.length===1&&(n.endsWith("[]")?e[n]=a:e[n]=a[0])}return e}const Ar=class Ar{constructor(e){$(this,"router",null);$(this,"layoutLoader",null);$(this,"errorPageHandler",null);$(this,"config");$(this,"globalState");$(this,"globalStateListeners",new Set);$(this,"currentRouteChangeId",0);$(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(),a=n||e.locale||"ko";this.config={...e,locale:a},!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 xn,a={_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,a),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,a),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 a=localStorage.getItem(n);a&&a!==localStorage.getItem(Ar.LOCALE_STORAGE_KEY)&&(localStorage.setItem(Ar.LOCALE_STORAGE_KEY,a),U.log(`Migrated locale from '${n}' to '${Ar.LOCALE_STORAGE_KEY}'`)),localStorage.removeItem(n)}catch(a){U.warn(`Failed to migrate locale key '${n}':`,a)}}async init(){try{Qs.getInstance().setDebug(this.config.debug),U.log("Initializing with config:",this.config),XS();const e=pr.getInstance(),n=yr.getInstance(),a=this.loadCacheVersionFromStorage()||0,[i,l,c,d,f]=await Promise.all([Oo({templateId:this.config.templateId,templateType:this.config.templateType,locale:this.config.locale,debug:this.config.debug,cacheVersion:a}),e.loadComponents(this.config.templateId,this.config.templateType),Ll($r(`/api/templates/${this.config.templateId}/routes`,"json",a>0?a: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($r(`/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:",f),f?.cache_version!==void 0){const A=this.loadCacheVersionFromStorage();if(this.extensionCacheVersion=f.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 x=await Ll($r(`/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(x.routes)&&(x.routes=this.resolveRouteExpressions(x.routes),Object.assign(c,x),U.log("Routes reloaded with new cache version"));try{const{TranslationEngine:L}=await Promise.resolve().then(()=>dp),M=L.getInstance();M.setCacheVersion(this.extensionCacheVersion);const R=this.config.locale||"ko",D="en";await M.loadTranslations(this.config.templateId,R,"/api",!0),R!==D&&await M.loadTranslations(this.config.templateId,D,"/api",!0),U.log("Translations reloaded with new cache version")}catch(L){U.error("Failed to reload translations:",L)}}}f?.errorHandling&&(this.templateErrorHandling=f.errorHandling,vr().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 g=Ir(),m=this.config.templateType==="admin"?"admin":"user",b=n.getConfig(m);g.setOnUnauthorized(()=>{U.log("Unauthorized - redirecting to login page"),g.removeToken();const A=window.location.pathname+window.location.search,x=n.getLoginRedirectUrl(m,A,"session_expired");window.location.href=x}),U.log("ApiClient onUnauthorized callback registered"),this.layoutLoader=new ff(e),this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),U.log("LayoutLoader initialized:",this.layoutLoader);const S=new Er({onUnauthorized:()=>{U.warn("Unauthorized request in error page")}});if(this.errorPageHandler=new Q_({templateId:this.config.templateId,layoutLoader:this.layoutLoader,locale:this.config.locale,debug:this.config.debug,renderFunction:hs,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 X_(this.config.templateId),Array.isArray(c.routes)){const A=this.resolveRouteExpressions(c.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:v}=await Promise.resolve().then(()=>Ur),_=v();if(_&&(_.setDefaultContext({navigate:A=>this.router?.navigate(A)}),_.setGlobalStateUpdater((A,x)=>this.setGlobalState(A,x)),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"&&my(window.location.pathname)){U.log("Layout editor mode detected — skipping router match"),await hs({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=wf(),n=tA();if(!n){await this.loadExtensionAssetsIndividually();return}await e.loadBundle("module",n.moduleJs,n.moduleCss),await e.loadBundle("plugin",n.pluginJs,n.pluginCss),U.log("Extension bundle assets loaded successfully")}catch(e){U.warn("Failed to load extension assets:",e)}}async loadExtensionAssetsIndividually(){const e=wf(),n=eA();n.length>0&&(U.log("Loading module assets (individual fallback):",n.map(i=>i.identifier)),await e.loadActiveExtensionAssets(n));const a=nA();a.length>0&&(U.log("Loading plugin assets (individual fallback):",a.map(i=>i.identifier)),await e.loadActiveExtensionAssets(a))}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 a=e.layout;const i=a==="__preview__";i&&e.params?.token&&(a=`__preview__/${e.params.token}`);const l=await this.layoutLoader.loadLayout(this.config.templateId,a);if(n!==this.currentRouteChangeId){U.log("Route change cancelled (newer request exists):",n);return}U.log("Layout loaded:",l);const c=vr();l.errorHandling?(c.setLayoutConfig(l.errorHandling),U.log("Layout errorHandling registered:",l.errorHandling)):c.clearLayoutConfig();const d=l.data_sources||[],f=e.query||{},g=new URLSearchParams;for(const[Z,pe]of Object.entries(f))if(Array.isArray(pe))for(const H of pe)g.append(Z,H);else g.set(Z,pe);const m={route:e.params||{},query:f,_global:this.globalState};l.scripts&&Array.isArray(l.scripts)&&await this.loadLayoutScripts(l.scripts,m);const{DataSourceManager:b,getActionDispatcher:S}=await Promise.resolve().then(()=>Ur),v=new b;if(i){const Z=S();Z&&Z.setPreviewMode(!0),this.setGlobalState({__isPreview:!0}),Cc.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=S();Z?.isPreviewMode()&&(Z.setPreviewMode(!1),Cc.hide("preview-mode"))}if(this.currentGlobalHeaders=l.globalHeaders||[],this.currentGlobalHeaders.length>0){v.setGlobalHeaders(this.currentGlobalHeaders);const Z=S();Z&&Z.setGlobalHeaders(this.currentGlobalHeaders),U.log("globalHeaders set:",this.currentGlobalHeaders.map(pe=>pe.pattern))}if(l.named_actions&&Object.keys(l.named_actions).length>0){const Z=S();Z&&Z.setNamedActions(l.named_actions)}const _=v.filterByCondition(d,m);d.length!==_.length&&U.log("Data sources filtered by condition:",{before:d.map(Z=>Z.id),after:_.map(Z=>Z.id)});const A=_.filter(Z=>Z.loading_strategy==="blocking"),x=_.filter(Z=>(Z.loading_strategy||"progressive")!=="blocking"&&Z.type!=="websocket"),L=Array.isArray(l.transition_overlay?.wait_for)?l.transition_overlay.wait_for:[],M=L.length>0&&_.some(Z=>L.includes(Z.id)&&Z.type!=="websocket"&&(Z.loading_strategy||"progressive")!=="background");if((A.length>0||M)&&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 R={},D={},B={},q={};this.currentWebSocketSubscriptions.length>0&&(U.log("Unsubscribing previous WebSocket subscriptions:",this.currentWebSocketSubscriptions),v.unsubscribeWebSockets(this.currentWebSocketSubscriptions),this.currentWebSocketSubscriptions=[]),this.currentDataSources=_,this.currentRawDataSources=d,this.currentRouteParams=e.params||{},this.currentQueryParams=g,U.log(`handleRouteChange #${n} - queryObject:`,f),U.log(`handleRouteChange #${n} - queryParams:`,g.toString()),A.length>0&&(U.log("Fetching blocking data sources:",A.map(pe=>pe.id)),(await v.fetchDataSourcesWithResults(A,e.params||{},g)).forEach(pe=>{if(pe.state==="success"&&pe.data!==void 0)R[pe.id]=pe.data;else if(pe.state==="error"&&pe.error){const H=pe.error,T=H.response?.data?.message;D[pe.id]={message:T||pe.error.message,status:H.response?.status||H.status}}}),this.processInitOptions(A,R,B,q),this.currentFetchedData={...R},U.log("Blocking data loaded:",Object.keys(R)),Object.keys(D).length>0&&U.log("Data source errors:",D),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 P=x.length>0;if(P&&(Hr.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(()=>Ur),ge=K().currentDataContext||{},Ee=x.map(Z=>Z.id),Se={};if(P){Ee.forEach(pe=>{ge[pe]!==void 0?Se[pe]=ge[pe]:Se[pe]=void 0});const Z=Object.keys(Se).filter(pe=>Se[pe]!==void 0);Z.length>0&&U.log("Preserving previous progressive data:",Z),U.log("Progressive data sources initialized:",Ee)}const Ue=l.defines||{},Ve={...Se,...e.params,...R,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState},_globalSetState:Z=>this.setGlobalState(Z),_dataSourceErrors:Object.keys(D).length>0?D:void 0,_localInit:Object.keys(B).length>0?B:void 0,_isolatedInit:Object.keys(q).length>0?q:void 0,_defines:Object.keys(Ue).length>0?Ue:void 0};if(l.computed&&Object.keys(l.computed).length>0){const Z=this.calculateComputed(l.computed,Ve);Object.keys(Z).length>0&&(Ve._computed=Z,this.globalState._computed=Z,U.log("Computed values calculated:",Object.keys(Z))),Ve._computedDefinitions=l.computed}const qe=l.layout_name||e.layout;this.currentLayoutName!==""&&this.currentLayoutName!==qe&&(U.log("_local reset due to layout change:",{from:this.currentLayoutName,to:qe}),this.globalState._local={},fC()),this.currentLayoutName=qe;const J=l.initLocal||l.state;if(J&&Object.keys(J).length>0){this.globalState._local||(this.globalState._local={});for(const[Z,pe]of Object.entries(J))this.globalState._local[Z]===void 0&&(this.globalState._local[Z]=JSON.parse(JSON.stringify(pe)));Ve._local={...this.globalState._local},U.log("initLocal applied to _local:",Object.keys(J))}if(l.initGlobal&&Object.keys(l.initGlobal).length>0){for(const[Z,pe]of Object.entries(l.initGlobal))this.globalState[Z]===void 0&&(this.globalState[Z]=JSON.parse(JSON.stringify(pe)));U.log("initGlobal applied to _global:",Object.keys(l.initGlobal))}if(l.initIsolated&&Object.keys(l.initIsolated).length>0){for(const[Z,pe]of Object.entries(l.initIsolated))q[Z]===void 0&&(q[Z]=JSON.parse(JSON.stringify(pe)));U.log("initIsolated applied:",Object.keys(l.initIsolated))}Ve._global={...this.globalState,layoutWarnings:l.warnings||[]};const fe=l.initActions||l.init_actions;if(fe&&fe.length>0){await this.executeInitActions(fe,Ve),U.log("initActions executed before render");const Z=this.globalState;if(Z._local){if(Object.keys(B).length>0){for(const[pe,H]of Object.entries(B))Z._local[pe]!==void 0?Z._local[pe]=this.deepMerge(Z._local[pe],H):Z._local[pe]=H;U.log("localInit merged into _local after initActions:",Object.keys(B))}Ve._local=Z._local,U.log("_local merged into dataContext:",Z._local)}if(Ve._global={...this.globalState,layoutWarnings:l.warnings||[]},U.log("_global merged into dataContext after initActions"),l.computed&&Object.keys(l.computed).length>0){const pe=this.calculateComputed(l.computed,Ve);Object.keys(pe).length>0&&(Ve._computed=pe,this.globalState._computed=pe,U.log("Computed values recalculated after init_actions:",Object.keys(pe)))}if(Object.keys(this.currentFetchedData).length>0){for(const[pe,H]of Object.entries(this.currentFetchedData))Ve[pe]=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 hs({containerId:"app",layoutJson:l,dataContext:Ve,translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),U.log("Initial render complete with blocking data"),this.reattachSpinnerOverlay(),x.length>0){if(n!==this.currentRouteChangeId){U.log("Route change cancelled before progressive fetch (newer request exists):",n),Hr.setPending(!1),this.hideTransitionOverlay();return}U.log("Fetching progressive/background data sources:",x.map(H=>H.id));const{updateTemplateData:Z,getState:pe}=await Promise.resolve().then(()=>Ur);try{const H=x.map(async T=>{try{const de=(await v.fetchDataSourcesWithResults([T],e.params||{},g,this.globalState))[0];if(!de){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(de.state==="success"&&de.data!==void 0){U.log(`Progressive data source loaded: ${T.id}`),this.currentFetchedData[T.id]=de.data;const ye={};this.processInitOptions([T],{[T.id]:de.data},ye);const ie=pe();if(ie.bindingEngine){const _e=[T.id];T.initGlobal&&_e.push("_global"),T.initLocal&&_e.push("_local"),ie.bindingEngine.invalidateCacheByKeys(_e)}const xe={[T.id]:de.data};Object.keys(ye).length>0&&(xe._localInit=ye,Object.assign(B,ye)),T.initGlobal&&(xe._global={...this.globalState}),Z(xe)}else if(de.state==="error"&&de.error){const ye=de.error,ie=ye.response?.data?.message;D[T.id]={message:ie||de.error.message,status:ye.response?.status||ye.status},U.log(`Progressive data source error: ${T.id}`,D[T.id]),Z({[T.id]:null,_dataSourceErrors:{...D}})}}catch(ce){U.error(`Failed to fetch data source: ${T.id}`,ce)}});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{Hr.setPending(!1),this.hideTransitionOverlay()}}else this.hideTransitionOverlay();const Le=_.filter(Z=>Z.type==="websocket");if(Le.length>0){U.log("Subscribing WebSocket data sources:",Le.map(T=>T.id));const{updateTemplateData:Z,getState:pe}=await Promise.resolve().then(()=>Ur),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=v.subscribeWebSockets(_,(T,ce)=>{U.log(`WebSocket data received for: ${T}`,ce),this.currentFetchedData[T]=ce;const de=_.find(_e=>_e.id===T),ye=pe();if(ye.bindingEngine){const _e=[T];de?.initGlobal&&_e.push("_global"),de?.initLocal&&_e.push("_local"),ye.bindingEngine.invalidateCacheByKeys(_e)}Z({[T]:ce});const xe=_.find(_e=>_e.type==="websocket"&&(_e.target_source||_e.id)===T)?.onReceive;Array.isArray(xe)&&xe.length>0&&window.G7Core?.dispatch&&(async()=>{for(const Te of xe)try{const $e=this.getActionDispatcher?.();$e&&await $e.dispatchAction(Te,{navigate:this.getRouter?.()?(ht,wt)=>this.getRouter().navigate(ht,wt):void 0,setState:ht=>this.setGlobalState(ht),state:this.globalState,data:{...this.globalState,$args:[ce],$event:ce},_isDispatchFallbackContext:!0})}catch($e){U.error(`WebSocket onReceive action failed for ${T}:`,$e)}})()},H),U.log("WebSocket subscriptions established:",this.currentWebSocketSubscriptions)}U.log("Layout rendered successfully")}catch(a){U.error("Route change handling failed:",a),this.hideTransitionOverlay(),this.showRouteError(a)}}processInitOptions(e,n,a,i){e.some(c=>c.refetchOnMount===!0&&c.initLocal)&&(a._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 g=f;if(c.initLocalDefaults&&typeof c.initLocalDefaults=="object"){const b=this.evaluateDefaults(c.initLocalDefaults,n);g={...b,...f},U.log(`initLocalDefaults applied for ${c.initLocal}:`,Object.keys(b))}const m=this.globalState._local?.[c.initLocal];m!==void 0&&typeof m=="object"&&typeof g=="object"?(a[c.initLocal]=this.deepMerge(m,g),U.log(`initLocal (merged): ${c.id}.data -> _local.${c.initLocal}`)):(a[c.initLocal]=g,U.log(`initLocal: ${c.id}.data -> _local.${c.initLocal}`))}else if(typeof c.initLocal=="object"&&c.initLocal.key){const{key:g,path:m}=c.initLocal;let b=m?this.extractValueByPathOrExpression(f,m,c.id):f;if(c.initLocalDefaults&&typeof c.initLocalDefaults=="object"){const v=this.evaluateDefaults(c.initLocalDefaults,n);b={...v,...b},U.log(`initLocalDefaults applied for ${g}:`,Object.keys(v))}const S=this.globalState._local?.[g];S!==void 0&&typeof S=="object"&&typeof b=="object"?(a[g]=this.deepMerge(S,b),U.log(`initLocal (merged): ${c.id}.data${m?"."+m:""} -> _local.${g}`)):(a[g]=b,U.log(`initLocal: ${c.id}.data${m?"."+m:""} -> _local.${g}`))}else if(typeof c.initLocal=="object"){const g=c.initLocal._merge||"deep",m=this.flattenNestedObjectToMappings(c.initLocal);for(const{targetPath:b,sourcePath:S}of m){const v=this.extractValueByPathOrExpression(f,S,c.id);if(b.includes(".")){const _=b.split(".")[0];a[_]===void 0&&this.globalState._local?.[_]!==void 0&&(a[_]=JSON.parse(JSON.stringify(this.globalState._local[_]))),this.setValueAtPath(a,b,v,g),U.log(`initLocal map (${g}): ${c.id} ${S} -> _local.${b}`)}else{const _=this.globalState._local?.[b];g==="replace"?(a[b]=v,U.log(`initLocal map (replace): ${c.id} ${S} -> _local.${b}`)):g==="shallow"?_!==void 0&&typeof _=="object"&&typeof v=="object"?(a[b]={..._,...v},U.log(`initLocal map (shallow): ${c.id} ${S} -> _local.${b}`)):(a[b]=v,U.log(`initLocal map: ${c.id} ${S} -> _local.${b}`)):_!==void 0&&typeof _=="object"&&typeof v=="object"?(a[b]=this.deepMerge(_,v),U.log(`initLocal map (deep): ${c.id} ${S} -> _local.${b}`)):(a[b]=v,U.log(`initLocal map: ${c.id} ${S} -> _local.${b}`))}}}}if(c.initGlobal)if(typeof c.initGlobal=="object"&&!Array.isArray(c.initGlobal)&&!("key"in c.initGlobal))for(const[m,b]of Object.entries(c.initGlobal)){if(typeof b!="string"){U.warn(`initGlobal map value must be string, got ${typeof b} for key ${m}`);continue}const S=this.extractValueByPathOrExpression(f,b,c.id),v=this.globalState[m];v!==void 0&&typeof v=="object"&&typeof S=="object"?(this.globalState[m]=this.deepMerge(v,S),U.log(`initGlobal map (merged): ${c.id} ${b} -> _global.${m}`)):(this.globalState[m]=S,U.log(`initGlobal map: ${c.id} ${b} -> _global.${m}`))}else{const m=Array.isArray(c.initGlobal)?c.initGlobal:[c.initGlobal];for(const b of m)if(typeof b=="string"){const S=this.globalState[b];S!==void 0&&typeof S=="object"&&typeof f=="object"?(this.globalState[b]=this.deepMerge(S,f),U.log(`initGlobal (merged): ${c.id}.data -> _global.${b}`)):(this.globalState[b]=f,U.log(`initGlobal: ${c.id}.data -> _global.${b}`))}else if(typeof b=="object"&&b.key){const{key:S,path:v}=b,_=v?this.extractValueByPathOrExpression(f,v,c.id):f,A=this.globalState[S];A!==void 0&&typeof A=="object"&&typeof _=="object"?(this.globalState[S]=this.deepMerge(A,_),U.log(`initGlobal (merged): ${c.id}.data${v?"."+v:""} -> _global.${S}`)):(this.globalState[S]=_,U.log(`initGlobal: ${c.id}.data${v?"."+v:""} -> _global.${S}`))}}if(i&&c.initIsolated){if(typeof c.initIsolated=="string"){const g=i[c.initIsolated];g!==void 0&&typeof g=="object"&&typeof f=="object"?(i[c.initIsolated]=this.deepMerge(g,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:g,path:m}=c.initIsolated,b=m?this.extractValueByPathOrExpression(f,m,c.id):f,S=i[g];S!==void 0&&typeof S=="object"&&typeof b=="object"?(i[g]=this.deepMerge(S,b),U.log(`initIsolated (merged): ${c.id}.data${m?"."+m:""} -> _isolated.${g}`)):(i[g]=b,U.log(`initIsolated: ${c.id}.data${m?"."+m:""} -> _isolated.${g}`))}else if(typeof c.initIsolated=="object")for(const[g,m]of Object.entries(c.initIsolated)){if(typeof m!="string"){U.warn(`initIsolated map value must be string, got ${typeof m} for key ${g}`);continue}const b=this.extractValueByPathOrExpression(f,m,c.id),S=i[g];S!==void 0&&typeof S=="object"&&typeof b=="object"?(i[g]=this.deepMerge(S,b),U.log(`initIsolated map (merged): ${c.id} ${m} -> _isolated.${g}`)):(i[g]=b,U.log(`initIsolated map: ${c.id} ${m} -> _isolated.${g}`))}}})}evaluateDefaults(e,n){const a={};for(const[i,l]of Object.entries(e))if(typeof l=="string"&&l.startsWith("{{")&&l.endsWith("}}")){const c=l.slice(2,-2).trim();a[i]=this.evaluateExpression(c,n)}else a[i]=l;return a}evaluateExpression(e,n){try{const a=e.split("??").map(i=>i.trim());for(const i of a){if(/^['"].*['"]$/.test(i))return i.slice(1,-1);if(i==="true")return!0;if(i==="false")return!1;if(/^-?\d+(\.\d+)?$/.test(i))return Number(i);const l=this.getNestedValue(n,i);if(l!=null)return l}return}catch(a){U.warn(`Expression evaluation failed: ${e}`,a);return}}getNestedValue(e,n){const a=n.replace(/\?\./g,".");let i=e;const l=a.split(/\.(?![^\[]*\])/).flatMap(c=>{const d=c.match(/^([^\[]*)((?:\[\d+\])*)$/);if(d){const[,f,g]=d,m=[];f&&m.push(f);const b=g.match(/\[\d+\]/g);return b&&m.push(...b),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,a){const i=Aa(n);if(i!==null){const l=new xn,c={data:e,_global:this.globalState,_local:this.globalState._local||{}};try{const d=Pn(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 ${a}:`,n,d);return}}return this.getNestedValue(e,n)}async loadLayoutScripts(e,n){const a=[];for(const i of e){if((i.if!==void 0||i.conditions!==void 0)&&!ts({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}const c=new Promise((d,f)=>{const g=document.createElement("script");g.src=i.src,g.id=i.id,g.async=i.async??!0,g.onload=()=>{U.log(`Script loaded successfully: ${i.id}`),d()},g.onerror=()=>{U.warn(`Failed to load script: ${i.id} (${i.src})`),d()},document.head.appendChild(g)});a.push(c)}a.length>0&&(await Promise.all(a),U.log(`All scripts loaded: ${e.filter(i=>!document.getElementById(i.id)||a.length>0).map(i=>i.id).join(", ")}`))}evaluateScriptCondition(e,n){try{if(e.startsWith("{{")&&e.endsWith("}}")){const a=e.slice(2,-2).trim();return new Function("ctx",` + `}static renderFromError(e,r,a,i=!1,l,c,d){let f,g;if(r.userMessageKey.startsWith("$t:"))if(c&&l)try{f=c.translate(r.userMessageKey,l)}catch{f=r.userMessageKey.replace("$t:","")}else f=r.userMessageKey.replace("$t:","");else f=r.userMessageKey;if(d){const m=d;m.details?.apiMessage?g=m.details.apiMessage:m.response?.data?.message&&(g=m.response.data.message)}this.render(e,{title:a,message:f,detailMessage:g,icon:r.icon,showStack:r.showStack,stackTrace:r.stack,showReloadButton:r.recoverable,debug:i})}static escapeHtml(e){if(!e)return"";const r=document.createElement("div");return r.textContent=e,r.innerHTML}}const cs=ut("Router");class k_{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,r){this.eventHandlers.has(e)||this.eventHandlers.set(e,[]),this.eventHandlers.get(e).push(r)}async emit(e,...r){const a=this.eventHandlers.get(e);a&&await Promise.all(a.map(i=>i(...r)))}async loadRoutes(e){try{const r=e!==void 0&&e>0?e:null,a=await fetch(Nr(`/api/templates/${this.templateIdentifier}/routes`,"json",r));if(!a.ok)throw new Error(`Failed to load routes: ${a.statusText}`);const i=await a.json();if(!i.success)throw new Error("Failed to load routes from API");if(i.data&&Array.isArray(i.data.routes))this.routes=i.data.routes,cs.log(`Loaded ${this.routes.length} routes${e?` (v=${e})`:""}`);else throw new Error("Invalid routes data format")}catch(r){throw cs.error("Error loading routes:",r),r}}setRoutes(e){this.routes=e,cs.log(`Set ${this.routes.length} routes`)}match(e){const r=this.normalizePathname(e);for(const a of this.routes){const i=this.matchPattern(a.path,r);if(i!==null)return{route:a,params:i}}return null}normalizePathname(e){return e.length>1&&e.endsWith("/")?e.replace(/\/+$/,"")||"/":e}matchPattern(e,r){const a=[];let i=e.replace(/:([^/]+)/g,(f,g)=>(a.push(g),"([^/]+)"));i.startsWith("*/")&&(i="(?:/[^/]+)?"+i.slice(1)),i=i.replace(/\//g,"\\/");const l=new RegExp(`^${i}$`),c=r.match(l);if(!c)return null;const d={};return a.forEach((f,g)=>{d[f]=c[g+1]}),d}getRoutes(){return[...this.routes]}getAuthType(e,r){return e.auth_type?e.auth_type:r.startsWith("/admin")?"admin":"user"}async navigateToCurrentPath(){const e=window.location.pathname,r=window.location.search,a=this.match(e);if(!a){cs.warn(`No route matched for path: ${e}`),this.emit("routeNotFound",e);return}if(a.route.redirect){cs.log(`Redirecting from ${e} to ${a.route.redirect}`),this.navigate(a.route.redirect);return}if(a.route.auth_required){const c=this.getAuthType(a.route,e),d=br.getInstance();let f=d.isAuthenticated()&&d.getAuthType()===c;if(f||(f=await d.checkAuth(c)),!f){const g=d.getLoginRedirectUrl(c,e+r);cs.log(`Not authenticated, redirecting to: ${g}`),window.location.href=g;return}}const i=new URLSearchParams(r),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:a.route.layout,endpoint:a.route.endpoint,params:{...a.route.params||{},...a.params},query:l,auth_required:a.route.auth_required,auth_type:a.route.auth_type,meta:a.route.meta})}navigate(e){if(this.isNavigating){this.pendingNavigation=e;return}this.executeNavigation(e)}async executeNavigation(e){this.isNavigating=!0,this.pendingNavigation=null;try{window.history.pushState({},"",e),await this.navigateToCurrentPath()}finally{if(this.isNavigating=!1,this.pendingNavigation){const r=this.pendingNavigation;this.executeNavigation(r)}}}}const R_=/^\/admin\/layout-editor\/([^/?#]+)\/?$/;function uy(o){const e=R_.exec(o);return e?{templateIdentifier:e[1]}:null}const jt=ut("ErrorPageHandler");class D_{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(Nr(`/api/templates/${this.templateId}/config`,"json"));if(!e.ok)return this.debug&&jt.warn("Failed to load template config:",e.statusText),this.configLoaded=!0,null;const r=await e.json();if(!r.success||!r.data)return this.debug&&jt.warn("Invalid template config response"),this.configLoaded=!0,null;const a=r.data;return!a.error_config||!a.error_config.layouts?(this.debug&&jt.warn("No error_config found in template.json"),this.configLoaded=!0,null):(this.errorConfig=a.error_config,this.configLoaded=!0,this.debug&&jt.log("Error config loaded:",this.errorConfig),this.errorConfig)}catch(e){return jt.error("Failed to load error config:",e),this.configLoaded=!0,null}}async renderError(e,r="app"){try{const a=await this.loadConfig();if(!a)return this.debug&&jt.warn("No error config available, cannot render error page"),!1;const i=a.layouts[e]||a.layouts[String(e)];if(!i)return this.debug&&jt.warn(`No layout defined for error code: ${e}`),!1;this.debug&&jt.log(`Loading error layout: ${i} for code: ${e}`);const l=await this.layoutLoader.loadLayout(this.templateId,i);if(!l)return this.debug&&jt.error(`Failed to load error layout: ${i}`),!1;this.debug&&jt.log("Error layout loaded:",l);let c={};const d=l.data_sources||[];if(d.length>0){this.debug&&jt.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"),w=[...m,...y];if(w.length>0)try{c=await this.dataSourceManager.fetchDataSources(w,{},new URLSearchParams),this.debug&&jt.log("Data sources fetched:",Object.keys(c))}catch(S){jt.error("Failed to fetch data sources:",S)}}const f={};d.length>0&&(this.processInitOptions(d,c,f),this.debug&&jt.log("initOptions processed:",{globalKeys:Object.keys(this.globalState),localKeys:Object.keys(f)}));const g={...c,errorCode:e,_global:{...this.globalState},_local:{...f}};return await this.renderFunction({containerId:r,layoutJson:l,dataContext:g,translationContext:{templateId:this.templateId,locale:this.locale}}),this.debug&&jt.log(`Error page ${e} rendered successfully`),!0}catch(a){return jt.error(`Failed to render error page ${e}:`,a),!1}}processInitOptions(e,r,a){for(const i of e){const l=r[i.id];if(!l)continue;const c=l?.data??l;if(i.initLocal){if(typeof i.initLocal=="string")a[i.initLocal]=c,jt.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;a[d]=f?this.getValueByPath(c,f):c,jt.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,jt.log(`initGlobal: ${i.id}.data -> _global.${f}`);else if(typeof f=="object"&&f!==null&&"key"in f){const{key:g,path:m}=f;this.globalState[g]=m?this.getValueByPath(c,m):c,jt.log(`initGlobal: ${i.id}.data${m?"."+m:""} -> _global.${g}`)}}}}getValueByPath(e,r){return r.split(".").reduce((a,i)=>a?.[i],e)}updateGlobalState(e){this.globalState={...this.globalState,...e}}updateLocale(e){this.locale=e,this.debug&&jt.log("Locale updated:",e)}isConfigLoaded(){return this.configLoaded}async hasErrorLayout(e){const r=await this.loadConfig();return r?!!(r.layouts[e]||r.layouts[String(e)]):!1}clearConfigCache(){this.errorConfig=null,this.configLoaded=!1,this.debug&&jt.log("Config cache cleared")}}const Mt=ut("ModuleAssetLoader");class O_{constructor(){$(this,"loadedAssets",new Map);$(this,"loadingPromises",new Map);$(this,"failedJsAssets",new Set)}hasFailedJsAssets(){return this.failedJsAssets.size>0}getFailedJsAssets(){return[...this.failedJsAssets]}async loadActiveExtensionAssets(e){if(!e||e.length===0){Mt.log("No module assets to load");return}const r=[...e].sort((d,f)=>d.priority-f.priority);Mt.log("Loading module assets:",r.map(d=>d.identifier));const a=r.filter(d=>d.css).map(d=>this.loadCSS(d.identifier,d.css)),i=r.filter(d=>d.js).map(d=>this.loadJS(d.identifier,d.js)),l=await Promise.allSettled([...a,...i]),c=l.filter(d=>d.status==="rejected");if(c.length>0){Mt.warn(`Some module assets failed to load (${c.length}/${l.length}); continuing with the rest`,this.getFailedJsAssets());return}Mt.log("All module assets loaded successfully")}async loadBundle(e,r,a){const i=[];if(a&&i.push(this.loadBundleCss(e,a)),r&&i.push(this.loadBundleJs(e,r)),i.length===0){Mt.log(`No bundle assets to load for: ${e}`);return}await Promise.all(i)}async loadBundleCss(e,r){const a=`ext-bundle-css-${e}`;if(document.getElementById(a)){Mt.log(`Bundle CSS already loaded: ${e}`);return}return new Promise(i=>{const l=document.createElement("link");l.rel="stylesheet",l.href=r,l.id=a,l.onload=()=>{Mt.log(`Bundle CSS loaded: ${e}`),this.registerLoadedAsset(`bundle-${e}`,{type:"css",element:l}),i()},l.onerror=()=>{Mt.warn(`Failed to load bundle CSS: ${e} (${r})`),i()},document.head.appendChild(l)})}async loadBundleJs(e,r){const a=`ext-bundle-js-${e}`;if(document.getElementById(a)){Mt.log(`Bundle JS already loaded: ${e}`);return}const i=this.loadingPromises.get(a);if(i)return Mt.log(`Bundle JS already loading: ${e}`),i;const l=Yg(r,{id:a},{label:`bundle JS: ${e}`}).then(()=>{Mt.log(`Bundle JS loaded: ${e}`);const c=document.getElementById(a);c&&this.registerLoadedAsset(`bundle-${e}`,{type:"js",element:c}),this.loadingPromises.delete(a)}).catch(c=>{throw Mt.warn(`Failed to load bundle JS: ${e} (${r})`,c),this.failedJsAssets.add(e),this.loadingPromises.delete(a),c});return this.loadingPromises.set(a,l),l}async loadCSS(e,r){const a=`module-css-${e}`;if(document.getElementById(a)){Mt.log(`CSS already loaded: ${e}`);return}return new Promise((i,l)=>{const c=document.createElement("link");c.rel="stylesheet",c.href=r,c.id=a,c.onload=()=>{Mt.log(`CSS loaded: ${e}`),this.registerLoadedAsset(e,{type:"css",element:c}),i()},c.onerror=()=>{Mt.warn(`Failed to load CSS: ${e} (${r})`),i()},document.head.appendChild(c)})}async loadJS(e,r){const a=`module-js-${e}`;if(document.getElementById(a)){Mt.log(`JS already loaded: ${e}`);return}const i=this.loadingPromises.get(e);if(i)return Mt.log(`JS already loading: ${e}`),i;const l=Yg(r,{id:a},{label:`JS: ${e}`}).then(()=>{Mt.log(`JS loaded: ${e}`);const c=document.getElementById(a);c&&this.registerLoadedAsset(e,{type:"js",element:c}),this.loadingPromises.delete(e)}).catch(c=>{throw Mt.warn(`Failed to load JS: ${e} (${r})`,c),this.failedJsAssets.add(e),this.loadingPromises.delete(e),c});return this.loadingPromises.set(e,l),l}registerLoadedAsset(e,r){const a=this.loadedAssets.get(e)||[];a.push(r),this.loadedAssets.set(e,a)}unloadExtensionAsset(e){const r=this.loadedAssets.get(e);if(!r||r.length===0){Mt.log(`No assets to unload for: ${e}`);return}r.forEach(a=>{a.element.parentNode&&(a.element.parentNode.removeChild(a.element),Mt.log(`${a.type.toUpperCase()} unloaded: ${e}`))}),this.loadedAssets.delete(e),Mt.log(`All assets unloaded for: ${e}`)}unloadAllAssets(){Array.from(this.loadedAssets.keys()).forEach(r=>{this.unloadExtensionAsset(r)}),Mt.log("All module assets unloaded")}isLoaded(e){return this.loadedAssets.has(e)}getLoadedModules(){return Array.from(this.loadedAssets.keys())}}let pf=null;function mf(){return pf||(pf=new O_),pf}function L_(){if(typeof window>"u")return[];const o=window.G7Config;if(!o?.moduleAssets)return[];const e=[];for(const[r,a]of Object.entries(o.moduleAssets)){const i=a;e.push({identifier:r,js:i.js?xa(i.js):i.js,css:i.css?xa(i.css):i.css,priority:i.priority,external:i.external})}return e}function M_(){if(typeof window>"u")return null;const o=window.G7Config;if(!o?.bundleUrls)return null;const e=o.bundleUrls;return{moduleJs:e.moduleJs?xa(e.moduleJs):e.moduleJs,moduleCss:e.moduleCss?xa(e.moduleCss):e.moduleCss,pluginJs:e.pluginJs?xa(e.pluginJs):e.pluginJs,pluginCss:e.pluginCss?xa(e.pluginCss):e.pluginCss}}function $_(){if(typeof window>"u")return[];const o=window.G7Config;if(!o?.pluginAssets)return[];const e=[];for(const[r,a]of Object.entries(o.pluginAssets)){const i=a;e.push({identifier:r,js:i.js?xa(i.js):i.js,css:i.css?xa(i.css):i.css,priority:i.priority,external:i.external})}return e}const yf=ut("SystemBannerManager");class Dc{static show(e){this.banners.set(e.id,e),this.render(),yf.log(`Banner shown: ${e.id}`)}static hide(e){this.banners.delete(e)&&(this.render(),yf.log(`Banner hidden: ${e}`))}static hideAll(){this.banners.clear(),this.render(),yf.log("All banners hidden")}static detectLocale(){try{const r=window.G7Core;if(r?.locale?.current)return r.locale.current()}catch{}return(navigator.language||"ko").split("-")[0]}static resolveMessage(e,r){return typeof e=="string"?e:e[r]||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 r=Array.from(this.banners.values()).sort((i,l)=>(i.order??0)-(l.order??0)),a=this.detectLocale();e.innerHTML=r.map(i=>{const l=this.resolveMessage(i.message,a),c=i.background||"#f59e0b",d=i.color||"white";return`
${l}
`}).join(""),requestAnimationFrame(()=>{e&&this.adjustAppPadding(e.offsetHeight)})}static adjustAppPadding(e){const r=document.getElementById("app");r&&(r.style.paddingTop=e>0?`${e}px`:"")}}$(Dc,"banners",new Map),$(Dc,"containerId","g7-system-banners");const U=ut("TemplateApp");function dy(o){const e={};for(const r of o.keys()){if(r in e)continue;const a=o.getAll(r);a.length>1?e[r]=a:a.length===1&&(r.endsWith("[]")?e[r]=a:e[r]=a[0])}return e}const xr=class xr{constructor(e){$(this,"router",null);$(this,"layoutLoader",null);$(this,"errorPageHandler",null);$(this,"config");$(this,"globalState");$(this,"globalStateListeners",new Set);$(this,"currentRouteChangeId",0);$(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 r=this.loadLocaleFromStorage(),a=r||e.locale||"ko";this.config={...e,locale:a},!r&&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 r=new _n,a={_global:this.globalState};return e.map(i=>{const l={...i};if(l.path&&l.path.includes("{{")){const c=l.path;l.path=r.resolveBindings(l.path,a),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=r.resolveBindings(l.redirect,a),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 r of e)try{const a=localStorage.getItem(r);a&&a!==localStorage.getItem(xr.LOCALE_STORAGE_KEY)&&(localStorage.setItem(xr.LOCALE_STORAGE_KEY,a),U.log(`Migrated locale from '${r}' to '${xr.LOCALE_STORAGE_KEY}'`)),localStorage.removeItem(r)}catch(a){U.warn(`Failed to migrate locale key '${r}':`,a)}}async init(){try{eo.getInstance().setDebug(this.config.debug),U.log("Initializing with config:",this.config),GS();const e=mr.getInstance(),r=br.getInstance(),a=this.loadCacheVersionFromStorage()||0,[i,l,c,d,f]=await Promise.all([Lo({templateId:this.config.templateId,templateType:this.config.templateType,locale:this.config.locale,debug:this.config.debug,cacheVersion:a}),e.loadComponents(this.config.templateId,this.config.templateType),Bl(Nr(`/api/templates/${this.config.templateId}/routes`,"json",a>0?a: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}),r.preloadAuth(this.config.templateType==="admin"?"admin":"user"),fetch(Nr(`/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:",f),f?.cache_version!==void 0){const A=this.loadCacheVersionFromStorage();if(this.extensionCacheVersion=f.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 x=await Bl(Nr(`/api/templates/${this.config.templateId}/routes`,"json",this.extensionCacheVersion),{label:"routes.json (reload)"}).then(R=>{if(!R.ok)throw new Error(`Failed to reload routes: ${R.statusText}`);return R.json()}).then(R=>{if(!R.success)throw new Error("Failed to reload routes from API");return R.data});Array.isArray(x.routes)&&(x.routes=this.resolveRouteExpressions(x.routes),Object.assign(c,x),U.log("Routes reloaded with new cache version"));try{const{TranslationEngine:R}=await Promise.resolve().then(()=>ep),M=R.getInstance();M.setCacheVersion(this.extensionCacheVersion);const O=this.config.locale||"ko",L="en";await M.loadTranslations(this.config.templateId,O,"/api",!0),O!==L&&await M.loadTranslations(this.config.templateId,L,"/api",!0),U.log("Translations reloaded with new cache version")}catch(R){U.error("Failed to reload translations:",R)}}}f?.errorHandling&&(this.templateErrorHandling=f.errorHandling,Sr().setTemplateConfig(this.templateErrorHandling),U.log("Template errorHandling registered:",this.templateErrorHandling)),r.on("logout",()=>{U.log("User logged out")}),r.on("authStateChange",A=>{U.log("Auth state changed:",A)}),U.log("AuthManager event handlers registered");const g=jr(),m=this.config.templateType==="admin"?"admin":"user",y=r.getConfig(m);g.setOnUnauthorized(()=>{U.log("Unauthorized - redirecting to login page"),g.removeToken();const A=window.location.pathname+window.location.search,x=r.getLoginRedirectUrl(m,A,"session_expired");window.location.href=x}),U.log("ApiClient onUnauthorized callback registered"),this.layoutLoader=new of(e),this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),U.log("LayoutLoader initialized:",this.layoutLoader);const w=new _r({onUnauthorized:()=>{U.warn("Unauthorized request in error page")}});if(this.errorPageHandler=new D_({templateId:this.config.templateId,layoutLoader:this.layoutLoader,locale:this.config.locale,debug:this.config.debug,renderFunction:us,dataSourceManager:w,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 k_(this.config.templateId),Array.isArray(c.routes)){const A=this.resolveRouteExpressions(c.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:S}=await Promise.resolve().then(()=>Pr),v=S();if(v&&(v.setDefaultContext({navigate:A=>this.router?.navigate(A)}),v.setGlobalStateUpdater((A,x)=>this.setGlobalState(A,x)),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"&&uy(window.location.pathname)){U.log("Layout editor mode detected — skipping router match"),await us({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=mf(),r=M_();if(!r){await this.loadExtensionAssetsIndividually();return}await e.loadBundle("module",r.moduleJs,r.moduleCss),await e.loadBundle("plugin",r.pluginJs,r.pluginCss),U.log("Extension bundle assets loaded successfully")}catch(e){U.warn("Failed to load extension assets:",e)}}async loadExtensionAssetsIndividually(){const e=mf(),r=L_();r.length>0&&(U.log("Loading module assets (individual fallback):",r.map(i=>i.identifier)),await e.loadActiveExtensionAssets(r));const a=$_();a.length>0&&(U.log("Loading plugin assets (individual fallback):",a.map(i=>i.identifier)),await e.loadActiveExtensionAssets(a))}async handleRouteChange(e){const r=++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:",r),!this.layoutLoader)throw new Error("LayoutLoader is not initialized");if(!e.layout)throw new Error("Route layout is not defined");let a=e.layout;const i=a==="__preview__";i&&e.params?.token&&(a=`__preview__/${e.params.token}`);const l=await this.layoutLoader.loadLayout(this.config.templateId,a);if(r!==this.currentRouteChangeId){U.log("Route change cancelled (newer request exists):",r);return}U.log("Layout loaded:",l);const c=Sr();l.errorHandling?(c.setLayoutConfig(l.errorHandling),U.log("Layout errorHandling registered:",l.errorHandling)):c.clearLayoutConfig();const d=l.data_sources||[],f=e.query||{},g=new URLSearchParams;for(const[Z,pe]of Object.entries(f))if(Array.isArray(pe))for(const H of pe)g.append(Z,H);else g.set(Z,pe);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:w}=await Promise.resolve().then(()=>Pr),S=new y;if(i){const Z=w();Z&&Z.setPreviewMode(!0),this.setGlobalState({__isPreview:!0}),Dc.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=w();Z?.isPreviewMode()&&(Z.setPreviewMode(!1),Dc.hide("preview-mode"))}if(this.currentGlobalHeaders=l.globalHeaders||[],this.currentGlobalHeaders.length>0){S.setGlobalHeaders(this.currentGlobalHeaders);const Z=w();Z&&Z.setGlobalHeaders(this.currentGlobalHeaders),U.log("globalHeaders set:",this.currentGlobalHeaders.map(pe=>pe.pattern))}if(l.named_actions&&Object.keys(l.named_actions).length>0){const Z=w();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 A=v.filter(Z=>Z.loading_strategy==="blocking"),x=v.filter(Z=>(Z.loading_strategy||"progressive")!=="blocking"&&Z.type!=="websocket"),R=Array.isArray(l.transition_overlay?.wait_for)?l.transition_overlay.wait_for:[],M=R.length>0&&v.some(Z=>R.includes(Z.id)&&Z.type!=="websocket"&&(Z.loading_strategy||"progressive")!=="background");if((A.length>0||M)&&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={},L={},q={},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=g,U.log(`handleRouteChange #${r} - queryObject:`,f),U.log(`handleRouteChange #${r} - queryParams:`,g.toString()),A.length>0&&(U.log("Fetching blocking data sources:",A.map(pe=>pe.id)),(await S.fetchDataSourcesWithResults(A,e.params||{},g)).forEach(pe=>{if(pe.state==="success"&&pe.data!==void 0)O[pe.id]=pe.data;else if(pe.state==="error"&&pe.error){const H=pe.error,T=H.response?.data?.message;L[pe.id]={message:T||pe.error.message,status:H.response?.status||H.status}}}),this.processInitOptions(A,O,q,G),this.currentFetchedData={...O},U.log("Blocking data loaded:",Object.keys(O)),Object.keys(L).length>0&&U.log("Data source errors:",L),Object.keys(q).length>0&&U.log("Local state init (blocking):",Object.keys(q)),Object.keys(G).length>0&&U.log("Isolated state init (blocking):",Object.keys(G)));const B=x.length>0;if(B&&(zr.setPending(!0),U.log("Transition started before rendering")),r!==this.currentRouteChangeId){U.log("Route change cancelled after blocking data (newer request exists):",r);return}const{getState:K}=await Promise.resolve().then(()=>Pr),fe=K().currentDataContext||{},Ce=x.map(Z=>Z.id),ke={};if(B){Ce.forEach(pe=>{fe[pe]!==void 0?ke[pe]=fe[pe]:ke[pe]=void 0});const Z=Object.keys(ke).filter(pe=>ke[pe]!==void 0);Z.length>0&&U.log("Preserving previous progressive data:",Z),U.log("Progressive data sources initialized:",Ce)}const Ue=l.defines||{},Pe={...ke,...e.params,...O,route:{...e.params||{},path:e.path},query:f,_global:{...this.globalState},_globalSetState:Z=>this.setGlobalState(Z),_dataSourceErrors:Object.keys(L).length>0?L:void 0,_localInit:Object.keys(q).length>0?q:void 0,_isolatedInit:Object.keys(G).length>0?G:void 0,_defines:Object.keys(Ue).length>0?Ue:void 0};if(l.computed&&Object.keys(l.computed).length>0){const Z=this.calculateComputed(l.computed,Pe);Object.keys(Z).length>0&&(Pe._computed=Z,this.globalState._computed=Z,U.log("Computed values calculated:",Object.keys(Z))),Pe._computedDefinitions=l.computed}const qe=l.layout_name||e.layout;this.currentLayoutName!==""&&this.currentLayoutName!==qe&&(U.log("_local reset due to layout change:",{from:this.currentLayoutName,to:qe}),this.globalState._local={},G0()),this.currentLayoutName=qe;const J=l.initLocal||l.state;if(J&&Object.keys(J).length>0){this.globalState._local||(this.globalState._local={});for(const[Z,pe]of Object.entries(J))this.globalState._local[Z]===void 0&&(this.globalState._local[Z]=JSON.parse(JSON.stringify(pe)));Pe._local={...this.globalState._local},U.log("initLocal applied to _local:",Object.keys(J))}if(l.initGlobal&&Object.keys(l.initGlobal).length>0){for(const[Z,pe]of Object.entries(l.initGlobal))this.globalState[Z]===void 0&&(this.globalState[Z]=JSON.parse(JSON.stringify(pe)));U.log("initGlobal applied to _global:",Object.keys(l.initGlobal))}if(l.initIsolated&&Object.keys(l.initIsolated).length>0){for(const[Z,pe]of Object.entries(l.initIsolated))G[Z]===void 0&&(G[Z]=JSON.parse(JSON.stringify(pe)));U.log("initIsolated applied:",Object.keys(l.initIsolated))}Pe._global={...this.globalState,layoutWarnings:l.warnings||[]};const he=l.initActions||l.init_actions;if(he&&he.length>0){await this.executeInitActions(he,Pe),U.log("initActions executed before render");const Z=this.globalState;if(Z._local){if(Object.keys(q).length>0){for(const[pe,H]of Object.entries(q))Z._local[pe]!==void 0?Z._local[pe]=this.deepMerge(Z._local[pe],H):Z._local[pe]=H;U.log("localInit merged into _local after initActions:",Object.keys(q))}Pe._local=Z._local,U.log("_local merged into dataContext:",Z._local)}if(Pe._global={...this.globalState,layoutWarnings:l.warnings||[]},U.log("_global merged into dataContext after initActions"),l.computed&&Object.keys(l.computed).length>0){const pe=this.calculateComputed(l.computed,Pe);Object.keys(pe).length>0&&(Pe._computed=pe,this.globalState._computed=pe,U.log("Computed values recalculated after init_actions:",Object.keys(pe)))}if(Object.keys(this.currentFetchedData).length>0){for(const[pe,H]of Object.entries(this.currentFetchedData))Pe[pe]=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 us({containerId:"app",layoutJson:l,dataContext:Pe,translationContext:{templateId:this.config.templateId,locale:this.config.locale}}),U.log("Initial render complete with blocking data"),this.reattachSpinnerOverlay(),x.length>0){if(r!==this.currentRouteChangeId){U.log("Route change cancelled before progressive fetch (newer request exists):",r),zr.setPending(!1),this.hideTransitionOverlay();return}U.log("Fetching progressive/background data sources:",x.map(H=>H.id));const{updateTemplateData:Z,getState:pe}=await Promise.resolve().then(()=>Pr);try{const H=x.map(async T=>{try{const de=(await S.fetchDataSourcesWithResults([T],e.params||{},g,this.globalState))[0];if(!de){U.log(`Data source ${T.id} skipped (no fetch result)`);return}if(r!==this.currentRouteChangeId){U.log(`Data source ${T.id} fetch cancelled (newer request exists)`);return}if(de.state==="success"&&de.data!==void 0){U.log(`Progressive data source loaded: ${T.id}`),this.currentFetchedData[T.id]=de.data;const me={};this.processInitOptions([T],{[T.id]:de.data},me);const ae=pe();if(ae.bindingEngine){const ze=[T.id];T.initGlobal&&ze.push("_global"),T.initLocal&&ze.push("_local"),ae.bindingEngine.invalidateCacheByKeys(ze)}const Re={[T.id]:de.data};Object.keys(me).length>0&&(Re._localInit=me,Object.assign(q,me)),T.initGlobal&&(Re._global={...this.globalState}),Z(Re)}else if(de.state==="error"&&de.error){const me=de.error,ae=me.response?.data?.message;L[T.id]={message:ae||de.error.message,status:me.response?.status||me.status},U.log(`Progressive data source error: ${T.id}`,L[T.id]),Z({[T.id]:null,_dataSourceErrors:{...L}})}}catch(ge){U.error(`Failed to fetch data source: ${T.id}`,ge)}});if(await Promise.all(H),r!==this.currentRouteChangeId){U.log("Route change cancelled after progressive fetch (newer request exists):",r);return}U.log("All progressive data sources loaded")}finally{zr.setPending(!1),this.hideTransitionOverlay()}}else this.hideTransitionOverlay();const Ee=v.filter(Z=>Z.type==="websocket");if(Ee.length>0){U.log("Subscribing WebSocket data sources:",Ee.map(T=>T.id));const{updateTemplateData:Z,getState:pe}=await Promise.resolve().then(()=>Pr),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(v,(T,ge)=>{U.log(`WebSocket data received for: ${T}`,ge),this.currentFetchedData[T]=ge;const de=v.find(ze=>ze.id===T),me=pe();if(me.bindingEngine){const ze=[T];de?.initGlobal&&ze.push("_global"),de?.initLocal&&ze.push("_local"),me.bindingEngine.invalidateCacheByKeys(ze)}Z({[T]:ge});const Re=v.find(ze=>ze.type==="websocket"&&(ze.target_source||ze.id)===T)?.onReceive;Array.isArray(Re)&&Re.length>0&&window.G7Core?.dispatch&&(async()=>{for(const $e of Re)try{const Ge=this.getActionDispatcher?.();Ge&&await Ge.dispatchAction($e,{navigate:this.getRouter?.()?(At,yt)=>this.getRouter().navigate(At,yt):void 0,setState:At=>this.setGlobalState(At),state:this.globalState,data:{...this.globalState,$args:[ge],$event:ge},_isDispatchFallbackContext:!0})}catch(Ge){U.error(`WebSocket onReceive action failed for ${T}:`,Ge)}})()},H),U.log("WebSocket subscriptions established:",this.currentWebSocketSubscriptions)}U.log("Layout rendered successfully")}catch(a){U.error("Route change handling failed:",a),this.hideTransitionOverlay(),this.showRouteError(a)}}processInitOptions(e,r,a,i){e.some(c=>c.refetchOnMount===!0&&c.initLocal)&&(a._forceLocalInit=Date.now(),U.log("refetchOnMount detected, forcing local state init")),e.forEach(c=>{const d=r[c.id];if(!d)return;const f=d.data??d;if(c.initLocal){if(typeof c.initLocal=="string"){let g=f;if(c.initLocalDefaults&&typeof c.initLocalDefaults=="object"){const y=this.evaluateDefaults(c.initLocalDefaults,r);g={...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 g=="object"?(a[c.initLocal]=this.deepMerge(m,g),U.log(`initLocal (merged): ${c.id}.data -> _local.${c.initLocal}`)):(a[c.initLocal]=g,U.log(`initLocal: ${c.id}.data -> _local.${c.initLocal}`))}else if(typeof c.initLocal=="object"&&c.initLocal.key){const{key:g,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,r);y={...S,...y},U.log(`initLocalDefaults applied for ${g}:`,Object.keys(S))}const w=this.globalState._local?.[g];w!==void 0&&typeof w=="object"&&typeof y=="object"?(a[g]=this.deepMerge(w,y),U.log(`initLocal (merged): ${c.id}.data${m?"."+m:""} -> _local.${g}`)):(a[g]=y,U.log(`initLocal: ${c.id}.data${m?"."+m:""} -> _local.${g}`))}else if(typeof c.initLocal=="object"){const g=c.initLocal._merge||"deep",m=this.flattenNestedObjectToMappings(c.initLocal);for(const{targetPath:y,sourcePath:w}of m){const S=this.extractValueByPathOrExpression(f,w,c.id);if(y.includes(".")){const v=y.split(".")[0];a[v]===void 0&&this.globalState._local?.[v]!==void 0&&(a[v]=JSON.parse(JSON.stringify(this.globalState._local[v]))),this.setValueAtPath(a,y,S,g),U.log(`initLocal map (${g}): ${c.id} ${w} -> _local.${y}`)}else{const v=this.globalState._local?.[y];g==="replace"?(a[y]=S,U.log(`initLocal map (replace): ${c.id} ${w} -> _local.${y}`)):g==="shallow"?v!==void 0&&typeof v=="object"&&typeof S=="object"?(a[y]={...v,...S},U.log(`initLocal map (shallow): ${c.id} ${w} -> _local.${y}`)):(a[y]=S,U.log(`initLocal map: ${c.id} ${w} -> _local.${y}`)):v!==void 0&&typeof v=="object"&&typeof S=="object"?(a[y]=this.deepMerge(v,S),U.log(`initLocal map (deep): ${c.id} ${w} -> _local.${y}`)):(a[y]=S,U.log(`initLocal map: ${c.id} ${w} -> _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 w=this.extractValueByPathOrExpression(f,y,c.id),S=this.globalState[m];S!==void 0&&typeof S=="object"&&typeof w=="object"?(this.globalState[m]=this.deepMerge(S,w),U.log(`initGlobal map (merged): ${c.id} ${y} -> _global.${m}`)):(this.globalState[m]=w,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 w=this.globalState[y];w!==void 0&&typeof w=="object"&&typeof f=="object"?(this.globalState[y]=this.deepMerge(w,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:w,path:S}=y,v=S?this.extractValueByPathOrExpression(f,S,c.id):f,A=this.globalState[w];A!==void 0&&typeof A=="object"&&typeof v=="object"?(this.globalState[w]=this.deepMerge(A,v),U.log(`initGlobal (merged): ${c.id}.data${S?"."+S:""} -> _global.${w}`)):(this.globalState[w]=v,U.log(`initGlobal: ${c.id}.data${S?"."+S:""} -> _global.${w}`))}}if(i&&c.initIsolated){if(typeof c.initIsolated=="string"){const g=i[c.initIsolated];g!==void 0&&typeof g=="object"&&typeof f=="object"?(i[c.initIsolated]=this.deepMerge(g,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:g,path:m}=c.initIsolated,y=m?this.extractValueByPathOrExpression(f,m,c.id):f,w=i[g];w!==void 0&&typeof w=="object"&&typeof y=="object"?(i[g]=this.deepMerge(w,y),U.log(`initIsolated (merged): ${c.id}.data${m?"."+m:""} -> _isolated.${g}`)):(i[g]=y,U.log(`initIsolated: ${c.id}.data${m?"."+m:""} -> _isolated.${g}`))}else if(typeof c.initIsolated=="object")for(const[g,m]of Object.entries(c.initIsolated)){if(typeof m!="string"){U.warn(`initIsolated map value must be string, got ${typeof m} for key ${g}`);continue}const y=this.extractValueByPathOrExpression(f,m,c.id),w=i[g];w!==void 0&&typeof w=="object"&&typeof y=="object"?(i[g]=this.deepMerge(w,y),U.log(`initIsolated map (merged): ${c.id} ${m} -> _isolated.${g}`)):(i[g]=y,U.log(`initIsolated map: ${c.id} ${m} -> _isolated.${g}`))}}})}evaluateDefaults(e,r){const a={};for(const[i,l]of Object.entries(e))if(typeof l=="string"&&l.startsWith("{{")&&l.endsWith("}}")){const c=l.slice(2,-2).trim();a[i]=this.evaluateExpression(c,r)}else a[i]=l;return a}evaluateExpression(e,r){try{const a=e.split("??").map(i=>i.trim());for(const i of a){if(/^['"].*['"]$/.test(i))return i.slice(1,-1);if(i==="true")return!0;if(i==="false")return!1;if(/^-?\d+(\.\d+)?$/.test(i))return Number(i);const l=this.getNestedValue(r,i);if(l!=null)return l}return}catch(a){U.warn(`Expression evaluation failed: ${e}`,a);return}}getNestedValue(e,r){const a=r.replace(/\?\./g,".");let i=e;const l=a.split(/\.(?![^\[]*\])/).flatMap(c=>{const d=c.match(/^([^\[]*)((?:\[\d+\])*)$/);if(d){const[,f,g]=d,m=[];f&&m.push(f);const y=g.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,r,a){const i=Ta(r);if(i!==null){const l=new _n,c={data:e,_global:this.globalState,_local:this.globalState._local||{}};try{const d=Gn(i)?l.evaluatePipeExpression(i,c,{skipCache:!0}):l.evaluateExpression(i,c);return U.log(`initLocal/initGlobal expression evaluated: ${r} -> `,d),d}catch(d){U.warn(`initLocal/initGlobal expression evaluation failed for ${a}:`,r,d);return}}return this.getNestedValue(e,r)}async loadLayoutScripts(e,r){const a=[];for(const i of e){if((i.if!==void 0||i.conditions!==void 0)&&!Qi({if:i.if,conditions:i.conditions},r,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}const c=new Promise((d,f)=>{const g=document.createElement("script");g.src=i.src,g.id=i.id,g.async=i.async??!0,g.onload=()=>{U.log(`Script loaded successfully: ${i.id}`),d()},g.onerror=()=>{U.warn(`Failed to load script: ${i.id} (${i.src})`),d()},document.head.appendChild(g)});a.push(c)}a.length>0&&(await Promise.all(a),U.log(`All scripts loaded: ${e.filter(i=>!document.getElementById(i.id)||a.length>0).map(i=>i.id).join(", ")}`))}evaluateScriptCondition(e,r){try{if(e.startsWith("{{")&&e.endsWith("}}")){const a=e.slice(2,-2).trim();return new Function("ctx",` with(ctx) { try { return Boolean(${a}); @@ -232,7 +275,7 @@ Error generating stack: `+u.message+` return false; } } - `)(n)}return!!e}catch(a){return U.warn(`Failed to evaluate script condition: ${e}`,a),!1}}showInitError(e){if(ld()){U.warn("Init failed while document is unloading — skipping error screen",e);return}const n=py(e);vf.renderFromError("app",n,"초기화 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}showTransitionOverlay(e,n){const a=typeof e=="boolean"?{enabled:e,style:"opaque",target:void 0,skeleton:void 0,spinner:void 0}:{enabled:e.enabled,style:e.style||"opaque",target:e.target,skeleton:e.skeleton,spinner:e.spinner,fallback_target:e.fallback_target};if(!a.enabled)return;if(this.hideTransitionOverlay(),a.style==="skeleton"&&a.skeleton?.component&&a.target&&n){this.renderSkeletonOverlay(a.target,a.skeleton,n,a.fallback_target);return}if(a.style==="spinner"&&a.target){this.renderSpinnerOverlay(a.target,a.spinner,a.fallback_target);return}const i=document.documentElement.classList.contains("dark");let l,c="";switch(a.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(a.target){const d=`#${CSS.escape(a.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 g=f.indexOf(":");g!==-1&&d.style.setProperty(f.slice(0,g).trim(),f.slice(g+1).trim())}document.body.appendChild(d),this.transitionOverlayEl=d}}hideTransitionOverlay(){this.transitionOverlayEl&&(this.transitionOverlayEl.remove(),this.transitionOverlayEl=null),this.hideSkeletonOverlay()}renderSkeletonOverlay(e,n,a,i){const c=pr.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)",b=f==="fullpage"?"app":f==="fallback"?i:e,S=`#${CSS.escape(b)}`,v=document.createElement("style");v.id="g7-skeleton-overlay-style",v.textContent=`${S}{position:relative;z-index:0;}${S}::after{content:'';position:absolute;inset:0;background:${m};z-index:2147483646;pointer-events:none;}`,document.head.appendChild(v),this.transitionOverlayEl=v;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 R=d.getBoundingClientRect(),D=window.scrollX||document.documentElement.scrollLeft,B=window.scrollY||document.documentElement.scrollTop;_.style.cssText=["position:absolute",`top:${R.top+B}px`,`left:${R.left+D}px`,`width:${R.width}px`,`height:${R.height}px`,"z-index:20","overflow:hidden","pointer-events:none",`background:${m}`].join(";")+";"}document.body.appendChild(_),this.skeletonOverlayContainer=_;const A=a.components||[];let x;if(f==="fullpage")x=A;else{const R=f==="fallback"?i:e;x=this.findComponentChildrenById(A,R)}const L=rd.createRoot(_);this.skeletonOverlayRoot=L,ka.flushSync(()=>{L.render(Ye.createElement(c,{components:x,options:{animation:n.animation||"pulse",iteration_count:n.iteration_count||5}}))});const M=f==="fullpage"?"fullpage (#app)":f==="fallback"?`fallback (#${i})`:`target (#${e})`;U.log(`Skeleton overlay rendered [${M}] with "${n.component}" (${x.length} components)`)}findComponentChildrenById(e,n){const a=i=>{for(const l of i){if(l.id===n)return l.children||[];if(l.children&&Array.isArray(l.children)){const c=a(l.children);if(c!==null)return c}}return null};return a(e)||e}renderSpinnerOverlay(e,n,a){let i=document.getElementById(e),l="target";if(!i&&a&&(i=document.getElementById(a),l="fallback"),i||(i=document.getElementById("app"),l="fullpage"),!i){U.log(`Spinner overlay: no target found (target="#${e}", fallback="${a||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const c=l==="fullpage"?"app":l==="fallback"?a: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 g=n?.text||window.G7Core?.t?.("nav.loading")||"";this._spinnerState={target:e,fallbackTarget:a,spinnerConfig:n,resolvedText:g},this._mountSpinnerInTarget(i);const m=l==="fullpage"?"fullpage (#app)":l==="fallback"?`fallback (#${a})`:`target (#${e})`,b=n?.component||"default spinner";U.log(`Spinner overlay rendered [${m}] with "${b}"`)}_mountSpinnerInTarget(e){if(!this._spinnerState)return;const{spinnerConfig:n,resolvedText:a}=this._spinnerState;if(this.skeletonOverlayRoot){try{this.skeletonOverlayRoot.unmount()}catch{}this.skeletonOverlayRoot=null}if(this.skeletonOverlayContainer){try{this.skeletonOverlayContainer.remove()}catch{}this.skeletonOverlayContainer=null}const i=document.createElement("div");if(i.id="g7-skeleton-overlay",i.setAttribute("role","status"),i.setAttribute("aria-busy","true"),e.appendChild(i),this.skeletonOverlayContainer=i,n?.component){const c=pr.getInstance().getComponent(n.component);if(c){const d=rd.createRoot(i);this.skeletonOverlayRoot=d,ka.flushSync(()=>{d.render(Ye.createElement(c,{options:{text:a}}))});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 a=document.getElementById(e);!a&&n&&(a=document.getElementById(n)),a||(a=document.getElementById("app")),a&&(this._mountSpinnerInTarget(a),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 Cr&&e.details?.status===401){const a=this.config.templateId||"",i=window.location.pathname,l=a.includes("admin")||i.startsWith("/admin")?"admin":"user",c=i+window.location.search,d=!!Ir().getToken()||e.details?.hadToken===!0,f=yr.getInstance().getLoginRedirectUrl(l,c,d?"session_expired":void 0);window.location.href=f;return}const n=py(e);vf.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($r(`/api/templates/${this.config.templateId}/config`,"json",null,`_=${Date.now()}`));if(n.ok){const a=await n.json();a?.success&&a?.data?.cache_version!==void 0&&(e=a.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(()=>dp),a=n.getInstance();this.extensionCacheVersion>0&&a.setCacheVersion(this.extensionCacheVersion);const i=this.config.locale||"ko",l="en";await a.loadTranslations(this.config.templateId,i,"/api",!0),i!==l&&await a.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 ea().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")),Ec(),await Oo({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(()=>Ur),a=n();a&&(a.setDefaultContext({navigate:i=>this.router?.navigate(i)}),a.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(Ar.LOCALE_STORAGE_KEY)}catch(e){return U.warn("Failed to load locale from storage:",e),null}}saveLocaleToStorage(e){try{localStorage.setItem(Ar.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 a,i;if(this.config.localeApi)a=this.config.localeApi.endpoint,i=this.config.localeApi.method;else{const l=this.config.templateType==="admin";a=l?"/api/admin/users/me/language":"/api/user/profile/update-language",i=l?"PATCH":"POST"}try{const l=this.getXsrfToken(),c=await fetch(a,{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(Ar.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(Ar.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(a=>{if(a.startsWith(e)&&typeof n[a]?.initModule=="function")try{n[a].initModule(),U.log(`Module handler re-initialized: ${a}`)}catch(i){U.warn(`Failed to re-initialize module handlers for ${a}:`,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(([a,i])=>{n.registerHandler(a,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(a=>{if(a.startsWith(e)&&typeof n[a]?.initPlugin=="function")try{n[a].initPlugin(),U.log(`Plugin handler re-initialized: ${a}`)}catch(i){U.warn(`Failed to re-initialize plugin handlers for ${a}:`,i)}})}getLocale(){return this.config.locale}getErrorPageHandler(){return this.errorPageHandler}getGlobalState(){return{...this.globalState}}setGlobalState(e,n){const a={...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:a,next:this.globalState}),this.globalStateListeners.forEach(l=>{l(this.globalState)}),n?.render!==!1&&Promise.resolve().then(()=>Ur).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 a=this.currentDataSources.find(i=>i.id===e);if(!a)for(const[,i]of this.modalDataSources){const l=i.find(c=>c.id===e);if(l){a=l;break}}if(!a){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)":""),Hr.setPending(!0);try{const i=new Er;this.currentGlobalHeaders.length>0&&i.setGlobalHeaders(this.currentGlobalHeaders);const l=ea(),c=l.currentDataContext?._global||{},d=n?.globalStateOverride?{...c,...n.globalStateOverride}:c,f=l.currentDataContext?._local||{},g=n?.localStateOverride?{...f,...n.localStateOverride}:f,b=(await i.fetchDataSourcesWithResults([a],this.currentRouteParams,this.currentQueryParams,d,g,{ignoreAutoFetch:!0}))[0];if(b.state==="success"&&b.data!==void 0){this.currentFetchedData[e]=b.data;const S={};this.processInitOptions([a],{[e]:b.data},S);const v=ea();if(v.bindingEngine){const A=[e];a.initGlobal&&A.push("_global"),a.initLocal&&A.push("_local"),v.bindingEngine.invalidateCacheByKeys(A)}const _={[e]:b.data};return Object.keys(S).length>0&&(_._localInit=S),a.initGlobal&&(_._global={...this.globalState}),gs(_,n?.sync?{sync:!0}:void 0),U.log(`Data source refetched successfully: ${e}`),b.data}else if(b.state==="error"){U.error(`Failed to refetch data source: ${e}`,b.error);return}}catch(i){U.error(`Error refetching data source: ${e}`,i);return}finally{Hr.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,a){if(!e){U.warn("setDataSource: dataSourceId is required");return}const{merge:i=!1,sync:l=!1}=a||{};i&&this.currentFetchedData[e]?this.currentFetchedData[e]={...this.currentFetchedData[e],...n}:this.currentFetchedData[e]=n,Promise.resolve().then(()=>Ur).then(({updateTemplateData:c})=>{c({[e]:this.currentFetchedData[e]},l?{sync:!0}:void 0)}),U.log(`setDataSource: Updated ${e}`,i?"(merged)":"(replaced)")}updateDataSourceItem(e,n,a,i,l){const{idField:c="id",merge:d=!0,skipRender:f=!1}=l||{},g=this.currentFetchedData[e];if(!g)return U.warn(`updateDataSourceItem: DataSource '${e}' not found`),!1;const m=this.parseItemPath(n);let b=g;for(const _ of m)if(b=b?.[_],b===void 0)return U.warn(`updateDataSourceItem: Path '${n}' not found in dataSource`),!1;if(!Array.isArray(b))return U.warn(`updateDataSourceItem: Target at '${n}' is not an array`),!1;const S=b.findIndex(_=>String(_[c])===String(a));if(S===-1)return U.warn(`updateDataSourceItem: Item with ${c}='${a}' not found`),!1;d?b[S]=this.deepMerge(b[S],i):b[S]={...b[S],...i};const v=window.G7Core?.devTools;return v?.isEnabled?.()&&v.trackDataSourceUpdate?.({dataSourceId:e,updateType:"partial",itemPath:n,itemId:a,updates:i,timestamp:Date.now()}),f||Promise.resolve().then(()=>Ur).then(({updateTemplateData:_})=>{_({[e]:this.currentFetchedData[e]},{sync:!1})}),U.log(`updateDataSourceItem: Updated ${e}.${n}[${c}=${a}]`),!0}parseItemPath(e){const n=[],a=/([^\.\[\]]+)|\[(\d+)\]/g;let i;for(;(i=a.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 a={...e};for(const i of Object.keys(n))typeof n[i]=="object"&&n[i]!==null&&!Array.isArray(n[i])?a[i]=this.deepMerge(a[i]||{},n[i]):a[i]=n[i];return a}setValueAtPath(e,n,a,i="deep"){const l=n.split(".");let c=e;for(let g=0;g0?l.filterByCondition(this.currentRawDataSources,d):this.currentDataSources;this.currentDataSources=f;const g=f.filter(A=>A.auto_fetch!==!1&&A.type!=="websocket");if(g.length===0){U.log("No auto_fetch data sources to refetch");return}U.log(`Refetching ${g.length} auto_fetch data sources`),Hr.setPending(!0);const m=ea().currentLayoutJson,b=m?.transition_overlay,S=Array.isArray(b?.wait_for)?b.wait_for:[],v=g.some(A=>(A.loading_strategy||"progressive")==="blocking"),_=S.length>0&&g.some(A=>S.includes(A.id)&&A.type!=="websocket"&&(A.loading_strategy||"progressive")!=="background");if((v||_)&&b&&typeof b=="object"){const A=n?.transitionOverlayTarget||b.target;b.enabled&&b.style==="skeleton"&&b.skeleton?.component&&A?this.renderSkeletonOverlay(A,b.skeleton,m,b.fallback_target):b.enabled&&b.style==="spinner"&&A&&this.renderSpinnerOverlay(A,b.spinner,b.fallback_target)}try{const A=new Er;this.currentGlobalHeaders.length>0&&A.setGlobalHeaders(this.currentGlobalHeaders);const x=ea(),L=x.currentDataContext?._global||{},M=await A.fetchDataSourcesWithResults(g,this.currentRouteParams,this.currentQueryParams,L,void 0,{ignoreAutoFetch:!1}),R={},D={},B=new Map(g.map(q=>[q.id,q]));for(const q of M){const P=B.get(q.id);if(!P){U.warn(`Refetch result id not found in autoFetchDataSources: ${q.id}`);continue}const K=q.id;q.state==="success"&&q.data!==void 0?(this.currentFetchedData[K]=q.data,R[K]=q.data,this.processInitOptions([P],{[K]:q.data},D),U.log(`Data source refetched: ${K}`)):q.state==="error"&&U.error(`Failed to refetch data source: ${K}`,q.error)}if(x.bindingEngine){const q=Object.keys(R);q.push("query"),x.bindingEngine.invalidateCacheByKeys(q)}if(Object.keys(D).length>0&&(R._localInit=D),Object.keys(R).length>0){if(R.query=yy(this.currentQueryParams),x.currentLayoutJson?.computed&&Object.keys(x.currentLayoutJson.computed).length>0){const q={...x.currentDataContext,...R,query:R.query},P=this.calculateComputed(x.currentLayoutJson.computed,q);Object.keys(P).length>0&&(R._computed=P,this.globalState._computed=P,U.log("Computed values recalculated in updateQueryParams:",Object.keys(P)))}gs(R,{sync:!0}),U.log("Template data updated with new query params")}}catch(A){U.error("Error in updateQueryParams:",A)}finally{Hr.setPending(!1),this.hideTransitionOverlay()}}calculateComputed(e,n){const a={},i=new xn;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;a[l]=d,U.log(`Computed ${l}:`,d)}catch(d){U.warn(`Failed to calculate computed value: ${l}`,d),a[l]=void 0}return a}isComputedSwitchDefinition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"$switch"in e&&"$cases"in e}evaluateComputedExpression(e,n){try{return new Function("ctx",` + `)(r)}return!!e}catch(a){return U.warn(`Failed to evaluate script condition: ${e}`,a),!1}}showInitError(e){if(ld()){U.warn("Init failed while document is unloading — skipping error screen",e);return}const r=cy(e);gf.renderFromError("app",r,"초기화 실패",this.config.debug,{templateId:this.config.templateId,locale:this.config.locale},void 0,e)}showTransitionOverlay(e,r){const a=typeof e=="boolean"?{enabled:e,style:"opaque",target:void 0,skeleton:void 0,spinner:void 0}:{enabled:e.enabled,style:e.style||"opaque",target:e.target,skeleton:e.skeleton,spinner:e.spinner,fallback_target:e.fallback_target};if(!a.enabled)return;if(this.hideTransitionOverlay(),a.style==="skeleton"&&a.skeleton?.component&&a.target&&r){this.renderSkeletonOverlay(a.target,a.skeleton,r,a.fallback_target);return}if(a.style==="spinner"&&a.target){this.renderSpinnerOverlay(a.target,a.spinner,a.fallback_target);return}const i=document.documentElement.classList.contains("dark");let l,c="";switch(a.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(a.target){const d=`#${CSS.escape(a.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 g=f.indexOf(":");g!==-1&&d.style.setProperty(f.slice(0,g).trim(),f.slice(g+1).trim())}document.body.appendChild(d),this.transitionOverlayEl=d}}hideTransitionOverlay(){this.transitionOverlayEl&&(this.transitionOverlayEl.remove(),this.transitionOverlayEl=null),this.hideSkeletonOverlay()}renderSkeletonOverlay(e,r,a,i){const c=mr.getInstance().getComponent(r.component);if(!c){U.log(`Skeleton component "${r.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,w=`#${CSS.escape(y)}`,S=document.createElement("style");S.id="g7-skeleton-overlay-style",S.textContent=`${w}{position:relative;z-index:0;}${w}::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(),L=window.scrollX||document.documentElement.scrollLeft,q=window.scrollY||document.documentElement.scrollTop;v.style.cssText=["position:absolute",`top:${O.top+q}px`,`left:${O.left+L}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 A=a.components||[];let x;if(f==="fullpage")x=A;else{const O=f==="fallback"?i:e;x=this.findComponentChildrenById(A,O)}const R=rd.createRoot(v);this.skeletonOverlayRoot=R,Oa.flushSync(()=>{R.render(We.createElement(c,{components:x,options:{animation:r.animation||"pulse",iteration_count:r.iteration_count||5}}))});const M=f==="fullpage"?"fullpage (#app)":f==="fallback"?`fallback (#${i})`:`target (#${e})`;U.log(`Skeleton overlay rendered [${M}] with "${r.component}" (${x.length} components)`)}findComponentChildrenById(e,r){const a=i=>{for(const l of i){if(l.id===r)return l.children||[];if(l.children&&Array.isArray(l.children)){const c=a(l.children);if(c!==null)return c}}return null};return a(e)||e}renderSpinnerOverlay(e,r,a){let i=document.getElementById(e),l="target";if(!i&&a&&(i=document.getElementById(a),l="fallback"),i||(i=document.getElementById("app"),l="fullpage"),!i){U.log(`Spinner overlay: no target found (target="#${e}", fallback="${a||"none"}"), falling back to opaque overlay`),this.showTransitionOverlay({enabled:!0,style:"opaque",target:e});return}this.hideSkeletonOverlay();const c=l==="fullpage"?"app":l==="fallback"?a: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 g=r?.text||window.G7Core?.t?.("nav.loading")||"";this._spinnerState={target:e,fallbackTarget:a,spinnerConfig:r,resolvedText:g},this._mountSpinnerInTarget(i);const m=l==="fullpage"?"fullpage (#app)":l==="fallback"?`fallback (#${a})`:`target (#${e})`,y=r?.component||"default spinner";U.log(`Spinner overlay rendered [${m}] with "${y}"`)}_mountSpinnerInTarget(e){if(!this._spinnerState)return;const{spinnerConfig:r,resolvedText:a}=this._spinnerState;if(this.skeletonOverlayRoot){try{this.skeletonOverlayRoot.unmount()}catch{}this.skeletonOverlayRoot=null}if(this.skeletonOverlayContainer){try{this.skeletonOverlayContainer.remove()}catch{}this.skeletonOverlayContainer=null}const i=document.createElement("div");if(i.id="g7-skeleton-overlay",i.setAttribute("role","status"),i.setAttribute("aria-busy","true"),e.appendChild(i),this.skeletonOverlayContainer=i,r?.component){const c=mr.getInstance().getComponent(r.component);if(c){const d=rd.createRoot(i);this.skeletonOverlayRoot=d,Oa.flushSync(()=>{d.render(We.createElement(c,{options:{text:a}}))});return}U.log(`Spinner component "${r.component}" not found in registry, using default spinner`)}i.innerHTML='
'}reattachSpinnerOverlay(){if(!this._spinnerState)return;const{target:e,fallbackTarget:r}=this._spinnerState;let a=document.getElementById(e);!a&&r&&(a=document.getElementById(r)),a||(a=document.getElementById("app")),a&&(this._mountSpinnerInTarget(a),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 Er&&e.details?.status===401){const a=this.config.templateId||"",i=window.location.pathname,l=a.includes("admin")||i.startsWith("/admin")?"admin":"user",c=i+window.location.search,d=!!jr().getToken()||e.details?.hadToken===!0,f=br.getInstance().getLoginRedirectUrl(l,c,d?"session_expired":void 0);window.location.href=f;return}const r=cy(e);gf.renderFromError("app",r,"페이지 로딩 실패",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(r){return U.error(`Failed to render ${e.code} page:`,r),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(r){U.error("Failed to render 404 page:",r),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 r=await fetch(Nr(`/api/templates/${this.config.templateId}/config`,"json",null,`_=${Date.now()}`));if(r.ok){const a=await r.json();a?.success&&a?.data?.cache_version!==void 0&&(e=a.data.cache_version)}}catch(r){U.warn("reloadExtensionState: failed to fetch config.json",r)}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(r){U.error("reloadExtensionState: routes reload failed",r)}try{this.layoutLoader&&(this.extensionCacheVersion>0&&this.layoutLoader.setCacheVersion(this.extensionCacheVersion),this.layoutLoader.clear(),U.log("reloadExtensionState: layout cache cleared"))}catch(r){U.error("reloadExtensionState: layout cache clear failed",r)}try{const{TranslationEngine:r}=await Promise.resolve().then(()=>ep),a=r.getInstance();this.extensionCacheVersion>0&&a.setCacheVersion(this.extensionCacheVersion);const i=this.config.locale||"ko",l="en";await a.loadTranslations(this.config.templateId,i,"/api",!0),i!==l&&await a.loadTranslations(this.config.templateId,l,"/api",!0),U.log("reloadExtensionState: translations reloaded")}catch(r){U.error("reloadExtensionState: translations reload failed",r)}try{const r=await fetch(`/api/locales/active?_=${Date.now()}`);if(r.ok){const i=(await r.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(r){U.warn("reloadExtensionState: supportedLocales refresh failed",r)}U.log("reloadExtensionState: done")}getActionDispatcher(){return ta().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")),Oc(),await Lo({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:r}=await Promise.resolve().then(()=>Pr),a=r();a&&(a.setDefaultContext({navigate:i=>this.router?.navigate(i)}),a.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(r){throw U.error("Failed to change locale:",r),r}}loadLocaleFromStorage(){try{return localStorage.getItem(xr.LOCALE_STORAGE_KEY)}catch(e){return U.warn("Failed to load locale from storage:",e),null}}saveLocaleToStorage(e){try{localStorage.setItem(xr.LOCALE_STORAGE_KEY,e)}catch(r){U.warn("Failed to save locale to storage:",r)}}async saveLocaleToDatabase(e){const r=localStorage.getItem("auth_token");if(!r){U.log("No auth token, skipping DB locale save");return}let a,i;if(this.config.localeApi)a=this.config.localeApi.endpoint,i=this.config.localeApi.method;else{const l=this.config.templateType==="admin";a=l?"/api/admin/users/me/language":"/api/user/profile/update-language",i=l?"PATCH":"POST"}try{const l=this.getXsrfToken(),c=await fetch(a,{method:i,headers:{"Content-Type":"application/json",Accept:"application/json",...l&&{"X-XSRF-TOKEN":l},Authorization:`Bearer ${r}`},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 r=`; ${document.cookie}`.split("; XSRF-TOKEN=");return r.length===2?decodeURIComponent(r.pop()?.split(";").shift()||""):null}loadCacheVersionFromStorage(){try{const e=localStorage.getItem(xr.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(xr.CACHE_VERSION_STORAGE_KEY,String(e))}catch(r){U.warn("Failed to save cache version to storage:",r)}}reinitializeModuleHandlers(){if(typeof window>"u")return;const e="__",r=window;Object.keys(r).forEach(a=>{if(a.startsWith(e)&&typeof r[a]?.initModule=="function")try{r[a].initModule(),U.log(`Module handler re-initialized: ${a}`)}catch(i){U.warn(`Failed to re-initialize module handlers for ${a}:`,i)}})}reinitializeTemplateHandlers(){if(typeof window>"u")return;const e=window.G7TemplateHandlers;if(!e){U.warn("Template handlers not found on window.G7TemplateHandlers");return}const r=this.getActionDispatcher();if(!r){U.warn("ActionDispatcher not available for template handler registration");return}Object.entries(e).forEach(([a,i])=>{r.registerHandler(a,i)}),U.log(`${Object.keys(e).length} template handler(s) re-registered:`,Object.keys(e))}reinitializePluginHandlers(){if(typeof window>"u")return;const e="__",r=window;Object.keys(r).forEach(a=>{if(a.startsWith(e)&&typeof r[a]?.initPlugin=="function")try{r[a].initPlugin(),U.log(`Plugin handler re-initialized: ${a}`)}catch(i){U.warn(`Failed to re-initialize plugin handlers for ${a}:`,i)}})}getLocale(){return this.config.locale}getErrorPageHandler(){return this.errorPageHandler}getGlobalState(){return{...this.globalState}}setGlobalState(e,r){const a={...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:a,next:this.globalState}),this.globalStateListeners.forEach(l=>{l(this.globalState)}),r?.render!==!1&&Promise.resolve().then(()=>Pr).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,r){let a=this.currentDataSources.find(i=>i.id===e);if(!a)for(const[,i]of this.modalDataSources){const l=i.find(c=>c.id===e);if(l){a=l;break}}if(!a){U.warn(`Data source not found: ${e}`);return}U.log(`Refetching data source: ${e}`,r?.sync?"(sync mode)":"",r?.globalStateOverride?"(with global override)":"",r?.localStateOverride?"(with local override)":""),zr.setPending(!0);try{const i=new _r;this.currentGlobalHeaders.length>0&&i.setGlobalHeaders(this.currentGlobalHeaders);const l=ta(),c=l.currentDataContext?._global||{},d=r?.globalStateOverride?{...c,...r.globalStateOverride}:c,f=l.currentDataContext?._local||{},g=r?.localStateOverride?{...f,...r.localStateOverride}:f,y=(await i.fetchDataSourcesWithResults([a],this.currentRouteParams,this.currentQueryParams,d,g,{ignoreAutoFetch:!0}))[0];if(y.state==="success"&&y.data!==void 0){this.currentFetchedData[e]=y.data;const w={};this.processInitOptions([a],{[e]:y.data},w);const S=ta();if(S.bindingEngine){const A=[e];a.initGlobal&&A.push("_global"),a.initLocal&&A.push("_local"),S.bindingEngine.invalidateCacheByKeys(A)}const v={[e]:y.data};return Object.keys(w).length>0&&(v._localInit=w),a.initGlobal&&(v._global={...this.globalState}),ds(v,r?.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{zr.setPending(!1)}}registerModalDataSources(e,r){this.modalDataSources.set(e,r),U.log(`Modal data sources registered: ${e} (${r.length} sources)`)}unregisterModalDataSources(e){this.modalDataSources.delete(e),U.log(`Modal data sources unregistered: ${e}`)}getDataSource(e){return this.currentFetchedData[e]}setDataSource(e,r,a){if(!e){U.warn("setDataSource: dataSourceId is required");return}const{merge:i=!1,sync:l=!1}=a||{};i&&this.currentFetchedData[e]?this.currentFetchedData[e]={...this.currentFetchedData[e],...r}:this.currentFetchedData[e]=r,Promise.resolve().then(()=>Pr).then(({updateTemplateData:c})=>{c({[e]:this.currentFetchedData[e]},l?{sync:!0}:void 0)}),U.log(`setDataSource: Updated ${e}`,i?"(merged)":"(replaced)")}updateDataSourceItem(e,r,a,i,l){const{idField:c="id",merge:d=!0,skipRender:f=!1}=l||{},g=this.currentFetchedData[e];if(!g)return U.warn(`updateDataSourceItem: DataSource '${e}' not found`),!1;const m=this.parseItemPath(r);let y=g;for(const v of m)if(y=y?.[v],y===void 0)return U.warn(`updateDataSourceItem: Path '${r}' not found in dataSource`),!1;if(!Array.isArray(y))return U.warn(`updateDataSourceItem: Target at '${r}' is not an array`),!1;const w=y.findIndex(v=>String(v[c])===String(a));if(w===-1)return U.warn(`updateDataSourceItem: Item with ${c}='${a}' not found`),!1;d?y[w]=this.deepMerge(y[w],i):y[w]={...y[w],...i};const S=window.G7Core?.devTools;return S?.isEnabled?.()&&S.trackDataSourceUpdate?.({dataSourceId:e,updateType:"partial",itemPath:r,itemId:a,updates:i,timestamp:Date.now()}),f||Promise.resolve().then(()=>Pr).then(({updateTemplateData:v})=>{v({[e]:this.currentFetchedData[e]},{sync:!1})}),U.log(`updateDataSourceItem: Updated ${e}.${r}[${c}=${a}]`),!0}parseItemPath(e){const r=[],a=/([^\.\[\]]+)|\[(\d+)\]/g;let i;for(;(i=a.exec(e))!==null;)i[1]!==void 0?r.push(i[1]):i[2]!==void 0&&r.push(parseInt(i[2],10));return r}deepMerge(e,r){if(r==null)return e;if(typeof r!="object"||Array.isArray(r))return r;const a={...e};for(const i of Object.keys(r))typeof r[i]=="object"&&r[i]!==null&&!Array.isArray(r[i])?a[i]=this.deepMerge(a[i]||{},r[i]):a[i]=r[i];return a}setValueAtPath(e,r,a,i="deep"){const l=r.split(".");let c=e;for(let g=0;g0?l.filterByCondition(this.currentRawDataSources,d):this.currentDataSources;this.currentDataSources=f;const g=f.filter(A=>A.auto_fetch!==!1&&A.type!=="websocket");if(g.length===0){U.log("No auto_fetch data sources to refetch");return}U.log(`Refetching ${g.length} auto_fetch data sources`),zr.setPending(!0);const m=ta().currentLayoutJson,y=m?.transition_overlay,w=Array.isArray(y?.wait_for)?y.wait_for:[],S=g.some(A=>(A.loading_strategy||"progressive")==="blocking"),v=w.length>0&&g.some(A=>w.includes(A.id)&&A.type!=="websocket"&&(A.loading_strategy||"progressive")!=="background");if((S||v)&&y&&typeof y=="object"){const A=r?.transitionOverlayTarget||y.target;y.enabled&&y.style==="skeleton"&&y.skeleton?.component&&A?this.renderSkeletonOverlay(A,y.skeleton,m,y.fallback_target):y.enabled&&y.style==="spinner"&&A&&this.renderSpinnerOverlay(A,y.spinner,y.fallback_target)}try{const A=new _r;this.currentGlobalHeaders.length>0&&A.setGlobalHeaders(this.currentGlobalHeaders);const x=ta(),R=x.currentDataContext?._global||{},M=await A.fetchDataSourcesWithResults(g,this.currentRouteParams,this.currentQueryParams,R,void 0,{ignoreAutoFetch:!1}),O={},L={},q=new Map(g.map(G=>[G.id,G]));for(const G of M){const B=q.get(G.id);if(!B){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([B],{[K]:G.data},L),U.log(`Data source refetched: ${K}`)):G.state==="error"&&U.error(`Failed to refetch data source: ${K}`,G.error)}if(x.bindingEngine){const G=Object.keys(O);G.push("query"),x.bindingEngine.invalidateCacheByKeys(G)}if(Object.keys(L).length>0&&(O._localInit=L),Object.keys(O).length>0){if(O.query=dy(this.currentQueryParams),x.currentLayoutJson?.computed&&Object.keys(x.currentLayoutJson.computed).length>0){const G={...x.currentDataContext,...O,query:O.query},B=this.calculateComputed(x.currentLayoutJson.computed,G);Object.keys(B).length>0&&(O._computed=B,this.globalState._computed=B,U.log("Computed values recalculated in updateQueryParams:",Object.keys(B)))}ds(O,{sync:!0}),U.log("Template data updated with new query params")}}catch(A){U.error("Error in updateQueryParams:",A)}finally{zr.setPending(!1),this.hideTransitionOverlay()}}calculateComputed(e,r){const a={},i=new _n;for(const[l,c]of Object.entries(e))try{let d;if(this.isComputedSwitchDefinition(c))d=i.resolveSwitch(c,r,{skipCache:!0});else if(typeof c=="string")if(c.startsWith("{{")&&c.endsWith("}}")){const f=c.slice(2,-2).trim();d=this.evaluateComputedExpression(f,r)}else d=c;a[l]=d,U.log(`Computed ${l}:`,d)}catch(d){U.warn(`Failed to calculate computed value: ${l}`,d),a[l]=void 0}return a}isComputedSwitchDefinition(e){return e!==null&&typeof e=="object"&&!Array.isArray(e)&&"$switch"in e&&"$cases"in e}evaluateComputedExpression(e,r){try{return new Function("ctx",` with(ctx) { try { return ${e}; @@ -240,5 +283,5 @@ Error generating stack: `+u.message+` return undefined; } } - `)(n)}catch(a){U.warn(`Expression evaluation failed: ${e}`,a);return}}async executeInitActions(e,n={}){const{getActionDispatcher:a}=await Promise.resolve().then(()=>Ur),i=a();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},g=i.createHandler(f,c),m=new Event("init");await g(m),U.log(`Init action executed: ${d.handler}`);const b=this.globalState;c={...c,_global:{...b},_local:b._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,a=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=wf().getFailedJsAssets();if(d.length>0){const f=d.some(b=>b==="module"||b==="plugin"),g=n.filter(b=>!e.customHandlers?.has(b)),m=g.length>0&&g.every(b=>d.some(S=>b.startsWith(`${S}.`)));if(f||m){U.warn("Extension asset load failed — not waiting for handlers that will never register:",{pending:g,failedAssets:d});return}}return U.log("Waiting for module handlers:",n),new Promise(f=>{const g=()=>{if(c()){U.log("All module handlers now registered"),f();return}if(Date.now()-i>=a){const m=n.filter(b=>!e.customHandlers?.has(b));U.warn("Timeout waiting for handlers:",m),f();return}setTimeout(g,l)};g()})}};$(Ar,"LOCALE_STORAGE_KEY","g7_locale"),$(Ar,"CACHE_VERSION_STORAGE_KEY","g7_cache_version");let xo=Ar;function Ef(o){const e=new xo(o);return o.websocket&&(vc.configure(o.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=Ef,window.G7Core.dataSource={refetch:async(o,e)=>{const n=window.__templateApp;if(!n){U.warn("TemplateApp not initialized (G7Core.dataSource.refetch)");return}return n.refetchDataSource(o,e)},get:o=>{const e=window.__templateApp;if(!e){U.warn("TemplateApp not initialized (G7Core.dataSource.get)");return}return e.getDataSource(o)}});function rA(o={}){const{checked:e,value:n,name:a,type:i="checkbox"}=o,c=n!==void 0?n:i==="checkbox"||i==="radio"?e??!1:String(e??""),d={checked:e??!1,value:c,name:a??"",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 aA(o={}){const{button:e=0,clientX:n=0,clientY:a=0}=o;return{button:e,clientX:n,clientY:a,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new MouseEvent("click"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"click",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("div"),currentTarget:document.createElement("div")}}function iA(){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 sA(o,e="keydown"){return{key:o,code:o.length===1?`Key${o.toUpperCase()}`:o,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new KeyboardEvent(e,{key:o}),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 oA={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 by(o){const e=o.replace(/^(dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+/,"");for(const[n,a]of Object.entries(oA))if(a.test(e))return n;return null}function vy(o){const e=o.match(/^((dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+)/);return e?e[1]:""}function lA(o,e){if(!e||e.trim()==="")return o;if(!o||o.trim()==="")return e;const n=o.split(/\s+/).filter(Boolean),a=e.split(/\s+/).filter(Boolean),i=new Map;for(const c of a){const d=by(c);if(d){const f=vy(c),g=`${d}:${f}`;i.set(g,c)}}return[...n.filter(c=>{const d=by(c);if(!d)return!0;const f=vy(c),g=`${d}:${f}`;return!i.has(g)}),...a].join(" ")}function cA(o){return Object.entries(o).filter(([,e])=>e).map(([e])=>e).join(" ")}function uA(...o){return o.filter(e=>typeof e=="string"&&e.length>0).join(" ")}const be=ut("G7CoreGlobals");function dA(){window.React=Ye,window.ReactDOM={...ad,createPortal:ka.createPortal,unstable_batchedUpdates:o=>o()},window.ReactJSXRuntime=sC,be.log("전역 객체 window.React, window.ReactDOM, window.ReactJSXRuntime에 노출됨")}function fA(o){const e=new Map,n=Oa.getInstance();o.componentEvent={on:(a,i)=>(e.has(a)||e.set(a,new Set),e.get(a).add(i),n.trackEventSubscribe(a),()=>{e.get(a)?.delete(i),n.trackEventUnsubscribe(a)}),emit:async(a,i)=>{const l=e.get(a),c=l?.size??0;if(!l||l.size===0)return n.trackEventEmit(a,i,0),[];let d,f=[];try{f=await Promise.all(Array.from(l).map(async g=>{try{return await g(i)}catch(m){throw be.error(`componentEvent: Error in listener for "${a}":`,m),m}}))}catch(g){d=g instanceof Error?g:new Error(String(g))}if(n.trackEventEmit(a,i,c,f,d),d)throw d;return f},off:a=>{e.delete(a),n.trackEventOff(a)},clear:()=>{e.clear(),n.trackEventClear()}},be.log("전역 객체 window.G7Core.componentEvent에 노출됨")}function hA(o){o.__runtime||(o.__runtime={DynamicRenderer:jr,ComponentRegistry:pr,TranslationEngine:_a,DataSourceManager:Er,dataSourceManager:F_,DataBindingEngine:xn,dataBindingEngine:md,ActionDispatcher:po,TranslationReactContext:hf,TranslationProvider:mc,useTranslation:ny,ResponsiveContext:qd,ResponsiveProvider:nc,useResponsive:Gd,responsiveManager:hi,BREAKPOINT_PRESETS:Il,AuthManager:yr,createLogger:ut,G7DevToolsCore:Oa},be.log("전역 객체 window.G7Core.__runtime(코어 런타임 표면)에 노출됨"))}function gA(o){if(o.layoutEditor&&o.layoutEditor.__isStub!==!0||o.layoutEditor&&o.layoutEditor.__isStub===!0)return;const e=[],n=[];o.layoutEditor={__isStub:!0,__queue:e,__readyCallbacks:n,registerWidget:(a,i)=>e.push(["widget",a,i]),registerNodeEditor:(a,i)=>e.push(["nodeEditor",a,i]),registerCanvasOverlay:(a,i)=>e.push(["canvasOverlay",a,i]),onReady:a=>{typeof a=="function"&&n.push(a)}},be.log("전역 객체 window.G7Core.layoutEditor 예약 접수함(stub) 노출됨")}function pA(o,e){o.useTranslation=ny,o.t=(n,a)=>{const i=e.getState();if(!i.translationEngine||!i.translationContext)return n;if(a){const l="|"+Object.entries(a).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 mA(o,e){o.createChangeEvent=rA,o.createClickEvent=aA,o.createSubmitEvent=iA,o.createKeyboardEvent=sA,o.uuid=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,n=>{const a=Math.random()*16|0;return(n==="x"?a:a&3|8).toString(16)}),o.createLogger=ut,be.log("전역 객체 window.G7Core.createLogger에 노출됨"),o.renderItemChildren=(n,a,i,l,c)=>{const d=e.getState(),m={_global:window.__templateApp?.getGlobalState?.()||{},_local:a._local||{},_computed:a._computed||{},...a},b=new Set,S=(_,A)=>{const x=m._global?._remountKeys;return _&&x?.[_]&&!b.has(_)?(b.add(_),`${_}-remount-${x[_]}`):_||A},v={translationContext:d.translationContext,translationEngine:d.translationEngine,bindingEngine:d.bindingEngine,actionDispatcher:d.actionDispatcher,getRemountKey:S,...c};return io(n,m,i,l,v)},o.evaluateCondition=(n,a)=>{if(!n)return!0;const i=e.getState(),c=window.__templateApp?.getGlobalState?.()||{},d={_global:c,_local:c._local||{},_computed:c._computed||{},...a||{}},f=i.bindingEngine??md;return mp(n,d,f)},o.getComponentMap=()=>pr.getInstance().getComponentMap(),o.renderComponentLayout=(n,a,i)=>{if(!n||!Array.isArray(n)||n.length===0)return null;const l=pr.getInstance().getComponentMap(),c=e.getState(),f=window.__templateApp?.getGlobalState?.()||{},g={_global:f._global||{},_local:f._local||{},_computed:f._computed||{},...a},m=new Set,b=(S,v)=>{const _=g._global?._remountKeys;return S&&_?.[S]&&!m.has(S)?(m.add(S),`${S}-remount-${_[S]}`):S||v};return io(n,g,l,i,{translationContext:c.translationContext,translationEngine:c.translationEngine,bindingEngine:c.bindingEngine,actionDispatcher:c.actionDispatcher,getRemountKey:b})},o.renderExpandContent=n=>{const{children:a,row:i,expandContext:l,componentContext:c,keyPrefix:d}=n;if(!a||!Array.isArray(a)||a.length===0)return null;const f=n.componentMap||pr.getInstance().getComponentMap(),g=e.getState(),m=o.state?.get?.()||{},b=c?.stateRef?.current??c?.state??{},S={...m._local||{},...b},v=c?.computedRef?.current??m._computed??{},_=g.bindingEngine??o.getDataBindingEngine?.(),A={...m,_local:S,_computed:v,row:i,item:i,$item:i};let x={};if(l&&typeof l=="object"&&_)try{for(const[D,B]of Object.entries(l))if(typeof B=="string"){const q=Aa(B);if(q!==null)try{x[D]=Pn(q)?_.evaluatePipeExpression(q,A,{skipCache:!0}):_.evaluateExpression(q,A,{skipCache:!0})}catch{x[D]=void 0}else x[D]=_.resolveBindings(B,A,{skipCache:!0})}else x[D]=B}catch(D){be.warn("renderExpandContent: expandContext 평가 오류:",D)}const L={row:i,item:i,$item:i,_local:S,_global:m._global||{},_computed:m._computed||{},...x},M=new Set,R=(D,B)=>{const q=L._global?._remountKeys;return D&&q?.[D]&&!M.has(D)?(M.add(D),`${D}-remount-${q[D]}`):D||B};return io(a,L,f,d,{translationContext:g.translationContext,translationEngine:g.translationEngine??void 0,bindingEngine:g.bindingEngine??void 0,actionDispatcher:g.actionDispatcher,componentContext:c,getRemountKey:R})},o.$get=function(a,i,l=void 0){if(a==null)return l;const c=Array.isArray(i)?i:[i];if(c.length===0)return a;let d=a;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 yA(o){o.dispatch=async(e,n)=>{const a=window.__templateApp;if(!a)return be.warn("G7Core.dispatch: TemplateApp이 초기화되지 않았습니다."),{success:!1,error:new Error("TemplateApp이 초기화되지 않았습니다.")};const i=a.getActionDispatcher?.();if(!i)return be.warn("G7Core.dispatch: ActionDispatcher를 찾을 수 없습니다."),{success:!1,error:new Error("ActionDispatcher를 찾을 수 없습니다.")};const l=a.getRouter?.(),c=a.getGlobalState?.(),d=a.setGlobalState?.bind(a),g=n?.componentContext||window.__g7ActionContext,m=window.__g7PendingLocalState;let b=g?.state??c;m&&g&&(b=m,be.log("[dispatch] Using __g7PendingLocalState for context.state:",m));let S=g?.data??c;m&&g?.data?._local&&(S={...g.data,_local:m},be.log("[dispatch] Updated context.data._local with pendingLocalState"));const v={navigate:l?(_,A)=>l.navigate(_,A):void 0,setState:g?.setState??d,state:b,data:S,_isDispatchFallbackContext:!g?.setState};if(e.debounce){const _=e.debounceKey||`dispatch-${e.handler}`,A=typeof e.debounce=="number"?e.debounce:e.debounce.delay;return i.debouncedCall(_,A,()=>{const{debounce:x,debounceKey:L,...M}=e;i.dispatchAction(M,v)}),{success:!0,debounced:!0}}try{return await i.dispatchAction(e,v)}catch(_){return be.error("G7Core.dispatch: 액션 실행 오류:",_),{success:!1,error:_ instanceof Error?_:new Error(String(_))}}},be.log("전역 객체 window.G7Core.dispatch에 노출됨")}function To(o){const e={};for(const[n,a]of Object.entries(o))if(n.includes(".")){const i=n.split(".");let l=e;for(let c=0;c0&&e.every(n=>/^\d+$/.test(n))}function wy(o,e){const n={...o};for(const a of Object.keys(e))a in n?n[a]!==null&&typeof n[a]=="object"&&!Array.isArray(n[a])&&e[a]!==null&&typeof e[a]=="object"&&!Array.isArray(e[a])&&(n[a]=wy(n[a],e[a])):n[a]=e[a];return n}function ar(o,e){if(Array.isArray(o)&&!Array.isArray(e)&&bA(e)){const a=Object.keys(e).map(l=>parseInt(l,10));if(!((a.length>0?Math.max(...a):0)>=o.length+a.length+10)){const l=[...o];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={...o};for(const[a,i]of Object.entries(e))i!==null&&typeof i=="object"&&!Array.isArray(i)?n[a]!==null&&typeof n[a]=="object"?n[a]=ar(n[a],i):n[a]={...i}:n[a]=i;return n}function vA(o){o.state={get:()=>window.__templateApp?.getGlobalState?.()||{},set:(e,n)=>{const a=window.__templateApp;if(a?.setGlobalState&&a?.getGlobalState){const i=n?.merge||"deep",l=To(e);let c;if(i==="replace")c=l;else if(i==="shallow")c={...a.getGlobalState(),...l};else{const d=a.getGlobalState();c=ar(d,l)}a.setGlobalState(c,{render:n?.render})}else be.warn("G7Core.state.set: TemplateApp이 초기화되지 않았습니다.")},setLocal:(e,n)=>{const a=window.__templateApp;if(n?.render===!1&&!n?.selfManaged){const x=window.__g7AutoBindingPaths;x&&x.size>0&&Sy(To(e)).some(M=>x.has(M))&&(be.log("[setLocal] render:false + 자동바인딩 경로 겹침 감지 → render:true 자동 승격 (engine-v1.43.0)"),n={...n,render:!0})}if(n?.debounce){const x=a?.getActionDispatcher?.();if(x){const L=n.debounceKey||`setLocal-${Object.keys(e).join(",")}`,{debounce:M,debounceKey:R,...D}=n;x.debouncedCall(L,n.debounce,()=>{o.state.setLocal(e,D)});return}}const i=n?.scope??"current",l=n?.merge||"deep",c=window.__g7ActionContext,d=To(e);if(i==="parent"||i==="root"){const x=window.__g7LayoutContextStack||[];if(x.length>0){const L=i==="parent"?x[x.length-1]:x[0];if(L?.setState){L.setState(M=>l==="replace"?d:l==="shallow"?{...M||{},...d}:ar(M||{},d)),be.log(`[setLocal] scope=${i}: 타겟 컨텍스트에 상태 업데이트 (mergeMode=${l})`,d);return}}be.warn(`[setLocal] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const f=window.__g7PendingLocalState,g=a?.getGlobalState?.()?._local||{},S=!((window.__g7LayoutContextStack||[]).length>0)&&c?.state?c.state:void 0,v=S?wy(g,S):g,_=f||v;let A;if(l==="replace"?A=d:l==="shallow"?A={..._,...d}:A=ar(_,d),a?.setGlobalState&&(a.setGlobalState({_local:A},{render:n?.render}),be.log(`[setLocal] globalLocal updated via setGlobalState (mergeMode=${l}, render=${n?.render??!0}):`,d)),window.__g7PendingLocalState=A,be.log("[setLocal] __g7PendingLocalState updated:",A),window.__g7SequenceLocalSync=A,window.__g7LastSetLocalSnapshot=A,l==="replace")window.__g7ForcedLocalFields=d;else{const x=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=ar(x,d)}if(be.log("[setLocal] __g7ForcedLocalFields updated:",d),l==="replace")window.__g7SetLocalOverrideKeys=d;else{const x=window.__g7SetLocalOverrideKeys||{};window.__g7SetLocalOverrideKeys=ar(x,d)}be.log("[setLocal] __g7SetLocalOverrideKeys updated:",d),c?.setState&&c.setState(x=>l==="replace"?d:l==="shallow"?{...x||{},...d}:ar(x||{},d)),a?.setGlobalState||be.warn("G7Core.state.setLocal: TemplateApp이 없습니다.")},getLocal:()=>{const a=(window.__templateApp?.getGlobalState?.()||{})._local||{},i=window.__g7PendingLocalState;if(i)return ar(a,i);const l=window.__g7LastSetLocalSnapshot;return l&&l!==a?ar(a,l):a},update:e=>{const n=window.__templateApp;if(n?.getGlobalState&&n?.setGlobalState){const a=n.getGlobalState(),i=e(a);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,a)=>{let i,l,c;typeof e=="string"?(i=e,l=n||{},c=a):(l=e,c=n&&typeof n=="object"&&"merge"in n?n:a);const d=c?.merge||"deep",f=To(l);if(i){const b=window.__g7IsolatedStates?.[i];b?.mergeState?b.mergeState(f,d):be.warn(`G7Core.state.setIsolated: scopeId '${i}'를 찾을 수 없습니다.`);return}const g=window.__g7ActionContext;g?.isolatedContext?.mergeState?g.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 a=n.dataContext||{};return{_local:n.state||a._local||{},_global:a._global||o.state.get()||{},setState:n.setState}},setParentLocal:(e,n,a)=>{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=a):(c=e,d=n&&typeof n=="object"&&"merge"in n?n:a);const f=d?.merge||"deep",g=To(c),m=l.state?._local!==void 0,b=m?l.state._local:l.state||{};let S;f==="replace"?S=g:f==="shallow"?S={...b,...g}:S=ar(b,g),window.__g7PendingLocalState=S;const v=window.__templateApp;if(v?.setGlobalState&&v.setGlobalState({_local:S}),l.setState(S),m?l.state._local=S:l.state=S,l.dataContext&&(l.dataContext._local=S),f==="replace")window.__g7ForcedLocalFields=g;else{const _=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=ar(_,g)}Ud()},setParentGlobal:(e,n)=>{let a;typeof e=="string"?a={[e]:n}:a=e,o.state.set(a),be.log("[setParentGlobal] 전역 상태 업데이트:",a)}},window.__g7IsolatedStates||(window.__g7IsolatedStates={}),o.state.getGlobal=o.state.get,o.state.setGlobal=o.state.set,be.log("전역 객체 window.G7Core.state에 노출됨")}function SA(o){o.dataSource={get:e=>window.__templateApp?.getDataSource?.(e),set:(e,n,a)=>{const i=window.__templateApp;i?.setDataSource?i.setDataSource(e,n,a):be.warn("G7Core.dataSource.set: TemplateApp이 초기화되지 않았습니다.")},refetch:async(e,n)=>{const a=window.__templateApp;if(a?.refetchDataSource)return a.refetchDataSource(e,n);be.warn("G7Core.dataSource.refetch: TemplateApp이 초기화되지 않았습니다.")},updateItem:(e,n,a,i,l)=>{const c=window.__templateApp;return c?.updateDataSourceItem?c.updateDataSourceItem(e,n,a,i,l):(be.warn("G7Core.dataSource.updateItem: TemplateApp이 초기화되지 않았습니다."),!1)},updateData:(e,n,a,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,g=null;if(n){const b=n.split(".");g=b.pop();for(const S of b)if(f&&typeof f=="object"&&S in f)f=f[S];else return be.warn(`G7Core.dataSource.updateData: 경로 '${n}'를 찾을 수 없습니다.`),!1;d=f[g]}else d=c;if(!Array.isArray(d))return be.warn("G7Core.dataSource.updateData: 대상 경로의 데이터가 배열이 아닙니다."),!1;if(!Array.isArray(a))return be.warn("G7Core.dataSource.updateData: newData가 배열이 아닙니다."),!1;const m=i==="prepend"?[...a,...d]:[...d,...a];return n&&g?(f[g]=m,l.setDataSource(e,c,{merge:!1})):l.setDataSource(e,m,{merge:!1}),be.log(`G7Core.dataSource.updateData: '${e}'에 ${a.length}개 항목 ${i==="prepend"?"앞에":"뒤에"} 추가됨`),!0}},be.log("전역 객체 window.G7Core.dataSource에 노출됨")}function wA(o,e){o.locale={current:()=>window.__templateApp?.getLocale?.()||"ko",supported:()=>{const a=window.__templateApp?.globalState?.appConfig?.supportedLocales;return Array.isArray(a)&&a.length>0?a:e.getState().templateMetadata?.locales||["ko","en"]},change:async n=>{const a=window.__templateApp;a?.changeLocale?await a.changeLocale(n):be.warn("G7Core.locale.change: TemplateApp이 초기화되지 않았습니다.")}},be.log("전역 객체 window.G7Core.locale에 노출됨")}function CA(o){o.toast={show:(e,n)=>{o.dispatch({handler:"toast",params:{message:e,type:n?.type||"info",...n?.duration&&{duration:n.duration}}})},success:(e,n)=>{o.toast.show(e,{type:"success",duration:n})},error:(e,n)=>{o.toast.show(e,{type:"error",duration:n})},warning:(e,n)=>{o.toast.show(e,{type:"warning",duration:n})},info:(e,n)=>{o.toast.show(e,{type:"info",duration:n})}},be.log("전역 객체 window.G7Core.toast에 노출됨")}function EA(o){o.modal={open:e=>{o.dispatch({handler:"openModal",target:e})},close:e=>{o.dispatch({handler:"closeModal",...e&&{target:e}})},closeAll:()=>{o.dispatch({handler:"closeAllModals"})},isOpen:e=>{const n=o.state.get();return n._global?.activeModal===e||n._global?.modalStack?.includes(e)||!1},getStack:()=>o.state.get()._global?.modalStack||[]},be.log("전역 객체 window.G7Core.modal에 노출됨")}function _A(o){o.style={mergeClasses:lA,conditionalClass:cA,joinClasses:uA},be.log("전역 객체 window.G7Core.style에 노출됨")}function AA(o,e){const{webSocketManager:n}=e;o.websocket={manager:n,subscribe:(a,i,l,c)=>n.subscribe(a,i,l,c),unsubscribe:a=>n.unsubscribe(a),leaveChannel:a=>n.leaveChannel(a),disconnect:()=>n.disconnect(),isInitialized:()=>n.isInitialized(),getSubscriptionCount:()=>n.getSubscriptionCount()},be.log("전역 객체 window.G7Core.websocket에 노출됨")}function xA(o,e){const{transitionManager:n}=e;o.navigation={isPending:()=>n?.getIsPending?.()||!1,onComplete:a=>{if(!n)return a(),()=>{};let i=n.getIsPending();const l=n.subscribe(c=>{c?i=!0:i&&(a(),l())});return l}},be.log("전역 객체 window.G7Core.navigation에 노출됨")}function TA(o){o.plugin={getSettings:e=>window.G7Config?.plugins?.[e],get:(e,n,a)=>window.G7Config?.plugins?.[e]?.[n]??a,getAll:()=>window.G7Config?.plugins??{}},be.log("전역 객체 window.G7Core.plugin에 노출됨")}function RA(o){o.module={getSettings:e=>window.G7Config?.modules?.[e],get:(e,n,a)=>window.G7Config?.modules?.[e]?.[n]??a,getAll:()=>window.G7Config?.modules??{}},be.log("전역 객체 window.G7Core.module에 노출됨")}function kA(o,e){const{transitionManager:n,responsiveManager:a}=e;o.AuthManager=yr,o.api=Ir(),o.TransitionManager=n,o.useTransitionState=hm,o.ResponsiveManager=a,o.useResponsive=Gd,o.useControllableState=vC,o.shallowArrayEqual=SC,o.shallowObjectEqual=pm,o.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 DA(o,e){o.getSlotContext=()=>window.__slotContextValue??null,o.getDynamicRenderer=()=>window.__DynamicRenderer??null,o.getComponentRegistry=()=>e.getComponentRegistry?.()??pr.getInstance(),o.getDataBindingEngine=()=>e.getDataBindingEngine?.()??e.getState().bindingEngine,o.getTranslationEngine=()=>e.getTranslationEngine?.()??e.getState().translationEngine,o.getActionDispatcher=()=>e.getActionDispatcher?.()??e.getState().actionDispatcher,be.log("전역 객체 window.G7Core 슬롯 API에 노출됨 (getSlotContext, getDynamicRenderer 등)")}function OA(o){o.identity={setLauncher:vt.setLauncher.bind(vt),handle:vt.handle.bind(vt),isIdentityRequired:vt.isIdentityRequired.bind(vt),hasLauncher:vt.hasLauncher.bind(vt),markDomainNoticeShown:vt.markDomainNoticeShown.bind(vt),redirectExternally:vt.redirectExternally.bind(vt),createDeferred:vt.createDeferred.bind(vt),resolveDeferred:vt.resolveDeferred.bind(vt),reset:vt.reset.bind(vt),redirectStashKey:$d},be.log("전역 객체 window.G7Core 본인인증(IDV) API에 노출됨 (identity)")}function LA(o){if(typeof window>"u")return;dA(),window.G7Core||(window.G7Core={});const e=window.G7Core;hA(e),fA(e),gA(e),kA(e,o),pA(e,o),mA(e,o),yA(e),vA(e),SA(e),wA(e,o),CA(e),EA(e),_A(e),AA(e,o),xA(e,o),TA(e),RA(e),DA(e,o),OA(e),be.log("G7Core 전역 객체 초기화 완료")}function MA(){const o=window.G7Core;if(!o){be.warn("G7Core가 초기화되지 않았습니다.");return}const e=()=>Oa.getInstance(),n={isEnabled:()=>{try{return e().isEnabled()}catch{return!1}},trackRender:a=>{try{e().isEnabled()&&e().trackRender(a)}catch{}},trackIteration:(a,i,l,c,d)=>{try{e().isEnabled()&&e().trackIteration(a,{source:i,itemVar:l,indexVar:c,sourceLength:d})}catch{}},trackIfCondition:(a,i,l,c)=>{try{e().isEnabled()&&e().trackIfCondition(a,i,l)}catch{}},trackMount:(a,i)=>{try{e().isEnabled()&&e().trackMount(a,{...i,id:a})}catch{}},trackUnmount:a=>{try{e().isEnabled()&&e().trackUnmount(a)}catch{}},trackExpressionEval:a=>{try{e().isEnabled()&&e().trackExpressionEval(a)}catch{}},trackBindingEval:a=>{try{e().isEnabled()&&e().trackBindingEval(a)}catch{}},recordCacheHit:()=>{try{e().isEnabled()&&e().recordCacheHit()}catch{}},recordCacheMiss:()=>{try{e().isEnabled()&&e().recordCacheMiss()}catch{}},trackHandlerRegistration:(a,i,l,c)=>{try{e().isEnabled()&&e().trackHandlerRegistration(a,i,l,c)}catch{}},trackHandlerUnregistration:a=>{try{e().isEnabled()&&e().trackHandlerUnregistration(a)}catch{}},logAction:a=>{try{e().isEnabled()&&e().logAction(a)}catch{}},trackRequest:(a,i)=>{try{return e().isEnabled()?e().trackRequest(a,i):""}catch{return""}},completeRequest:(a,i,l)=>{try{e().isEnabled()&&e().completeRequest(a,i,l)}catch{}},failRequest:(a,i)=>{try{e().isEnabled()&&e().failRequest(a,i)}catch{}},trackDataSourceDefinition:a=>{try{e().isEnabled()&&e().trackDataSourceDefinition(a)}catch{}},trackDataSourceLoading:a=>{try{e().isEnabled()&&e().trackDataSourceLoading(a)}catch{}},trackDataSourceLoaded:(a,i,l)=>{try{e().isEnabled()&&e().trackDataSourceLoaded(a,i,l)}catch{}},trackDataSourceError:(a,i)=>{try{e().isEnabled()&&e().trackDataSourceError(a,i)}catch{}},trackForm:(a,i,l)=>{try{e().isEnabled()&&e().trackForm(a,i,l)}catch{}},untrackForm:a=>{try{e().isEnabled()&&e().untrackForm(a)}catch{}},startStateChange:(a,i,l,c)=>{try{return e().isEnabled()?e().startStateChange(a,i,l,c):""}catch{return""}},completeStateChange:a=>{try{e().isEnabled()&&e().completeStateChange(a)}catch{}},trackComponentRender:(a,i,l,c,d,f)=>{try{e().isEnabled()&&e().trackComponentRender(a,i,l,c,d,f)}catch{}},updateLocalState:a=>{try{e().isEnabled()&&e().updateLocalState(a)}catch{}},updateComputedState:a=>{try{e().isEnabled()&&e().updateComputedState(a)}catch{}},updateParentContext:a=>{try{e().isEnabled()&&e().updateParentContext(a)}catch{}},trackComponentStateSource:(a,i,l,c)=>{try{e().isEnabled()&&e().trackComponentStateSource(a,i,l,c)}catch{}},trackDynamicState:(a,i)=>{try{e().isEnabled()&&e().trackDynamicState(a,i)}catch{}},trackContextFlow:(a,i,l,c,d,f)=>{try{e().isEnabled()&&e().trackContextFlow(a,i,l,c,d,f)}catch{}},trackComponentStyle:(a,i,l,c)=>{try{e().isEnabled()&&e().trackComponentStyle(a,i,l,c)}catch{}},trackAuthEvent:(a,i,l,c)=>{try{e().isEnabled()&&e().trackAuthEvent(a,i,l,c)}catch{}},trackAuthHeader:(a,i,l,c,d)=>{try{e().isEnabled()&&e().trackAuthHeader(a,i,l,c,d)}catch{}},trackLog:(a,i,l)=>{try{e().isEnabled()&&e().trackLog(a,i,l)}catch{}},trackAction:a=>{try{e().isEnabled()&&e().trackAction?.(a)}catch{}},trackDataSourceUpdate:a=>{try{e().isEnabled()&&e().trackDataSourceUpdate?.(a)}catch{}},startSequenceExecution:a=>{try{return e().isEnabled()?e().startSequenceExecution(a):""}catch{return""}},captureSequenceActionBefore:(a,i,l,c,d)=>{try{e().isEnabled()&&e().captureSequenceActionBefore(a,i,l,c,d)}catch{}},captureSequenceActionAfter:(a,i,l,c,d,f)=>{try{e().isEnabled()&&e().captureSequenceActionAfter(a,i,l,c,d,f)}catch{}},endSequenceExecution:(a,i)=>{try{e().isEnabled()&&e().endSequenceExecution(a,i)}catch{}},registerStateCaptureForHandler:(a,i,l)=>{try{e().isEnabled()&&e().registerStateCaptureForHandler(a,i,l)}catch{}},detectStaleClosure:(a,i,l,c,d)=>{try{return e().isEnabled()?e().detectStaleClosure(a,i,l,c,d):[]}catch{return[]}},trackStaleClosureWarning:a=>{try{e().isEnabled()&&e().trackStaleClosureWarning(a)}catch{}},trackModalOpen:a=>{try{e().isEnabled()&&e().trackModalOpen(a)}catch{}},trackModalClose:(a,i)=>{try{e().isEnabled()&&e().trackModalClose(a,i)}catch{}},trackModalStateChange:a=>{try{e().isEnabled()&&e().trackModalStateChange(a)}catch{}},trackNestedContext:a=>{try{return e().isEnabled()?e().trackNestedContext(a):""}catch{return""}},trackNestedContextAccess:(a,i)=>{try{e().isEnabled()&&e().trackNestedContextAccess(a,i)}catch{}},trackComputedProperty:(a,i,l,c,d,f,g)=>{try{e().isEnabled()&&e().trackComputedProperty(a,i,l,c,d,f,g)}catch{}},trackComputedRecalc:(a,i,l,c,d,f,g)=>{try{e().isEnabled()&&e().trackComputedRecalc(a,i,l,c,d,f,g)}catch{}},setNamedActionDefinitions:a=>{try{e().isEnabled()&&e().setNamedActionDefinitions(a)}catch{}},trackNamedActionRef:a=>{try{e().isEnabled()&&e().trackNamedActionRef(a)}catch{}}};o.devTools=n,be.log("G7Core.devTools 인터페이스 초기화 완료")}let Ro=null;function $A(){const o=window.G7Core;return o?.__devtools?Promise.resolve(o.__devtools):Ro||(Ro=new Promise((e,n)=>{const a=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 번들 로드 실패: ${a}`)),{once:!0});return}const d=document.createElement("script");d.id=i,d.src=a,d.async=!1,d.addEventListener("load",l,{once:!0}),d.addEventListener("error",()=>{Ro=null,n(new Error(`DevTools 번들 로드 실패: ${a}`))},{once:!0}),document.head.appendChild(d)}),Ro)}function NA(){const o=window.G7Core;if(!o){be.warn("G7Core가 초기화되지 않았습니다.");return}const e=Oa.getInstance();if(e.initialize(),!e.isEnabled()){window.G7DevTools={isEnabled:()=>!1,enable:()=>{be.log("환경설정 > 고급 설정 > 디버그 모드를 켜세요")}},sd(),be.log("G7DevTools 비활성화됨 (디버그 모드 꺼짐)");return}IA(o,e)}async function IA(o,e){let n;try{n=await $A()}catch(g){be.warn("DevTools 번들 로드 실패 — 최소 API 로 폴백:",g),window.G7DevTools={isEnabled:()=>!1,enable:()=>{}},sd();return}const{DiagnosticEngine:a,getServerConnector:i,getStyleTracker:l}=n;MA(),sd();try{l().enable(),be.log("StyleTracker 활성화됨")}catch(g){be.warn("StyleTracker 활성화 실패:",g)}const c=new a,d=i(),f={isEnabled:()=>e.isEnabled(),state:{get:()=>e.getState(),getHistory:()=>e.getStateHistory(),watch:(g,m)=>e.watchState(g,m)},actions:{getHistory:()=>e.getActionHistory(),watch:g=>e.watchActions(g),getMetrics:()=>e.getActionMetrics()},binding:{evaluate:g=>{const m=o.getDataBindingEngine?.();if(!m){be.warn("DataBindingEngine이 없습니다.");return}return m.evaluateExpression(g,e.getState())},getCacheStats:()=>e.getCacheStats(),clearStats:()=>{e.resetCacheStats(),be.log("캐시 통계 초기화됨")}},diagnose:{analyze:g=>c.analyze(g),suggestFix:g=>c.suggestFix(g),getCommonIssues:()=>c.getCommonIssues(),getRulesByCategory:g=>c.getRulesByCategory(g)},server:{dumpState:g=>d.dumpState(g),sendLog:g=>d.sendLog(g),sendError:(g,m)=>d.sendError(g,m),isConnected:()=>d.isConnected(),testConnection:()=>d.testConnection()},config:{isDebugMode:()=>e.isEnabled(),setLogLevel:g=>e.setLogLevel(g),setMaxHistory:g=>e.setMaxHistory(g)},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,o.devtools=f,be.log("G7DevTools 전역 객체 초기화 완료 (window.G7DevTools)"),HA(n.DevToolsPanel)}function HA(o){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(Ye.createElement(o)),be.log("DevToolsPanel UI 렌더링 완료")}catch(n){be.error("DevToolsPanel UI 렌더링 실패:",n)}}const Qe=ut("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 ko=!1;const Do=[];async function zA(o){try{Qe.log("템플릿 메타데이터 로드 중...",o);const e=o.split("-").map(a=>a.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:o,locales:["ko","en"],name:{ko:o,en:o},description:{ko:"",en:""},version:"1.0.0",type:"admin"})}catch(e){return Qe.error("템플릿 메타데이터 로드 실패",e),{identifier:o,locales:["ko","en"],name:{ko:o,en:o},description:{ko:"",en:""},version:"1.0.0",type:"admin"}}}function Cy(){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 Oo(o){try{if(Qe.log("템플릿 엔진 초기화 시작",o),ae.isInitialized)throw new Error("템플릿 엔진이 이미 초기화되었습니다. destroyTemplate()을 먼저 호출하세요.");if(!o.templateId)throw new W_;ko=o.debug??!1,typeof window<"u"&&(window.G7Config||(window.G7Config={}),window.G7Config.debug=ko),NA(),ae.templateId=o.templateId,ae.locale=o.locale||"ko",Qe.log("엔진 인스턴스 생성 중..."),ae.registry=pr.getInstance(),ae.bindingEngine=new xn,ae.translationEngine=_a.getInstance(),o.cacheVersion!==void 0&&o.cacheVersion>0&&ae.translationEngine.setCacheVersion(o.cacheVersion),ae.translationContext={templateId:o.templateId,locale:ae.locale},ae.actionDispatcher=new po({},ae.translationEngine,ae.translationContext),uC(ae.actionDispatcher),Qe.log("다국어 파일 로드 중...",o.templateId,ae.locale);const e="en",n=[ae.translationEngine.loadTranslations(o.templateId,ae.locale).then(()=>{Qe.log(`다국어 파일 로드 완료: ${ae.locale}`)}).catch(a=>{Qe.warn(`다국어 파일 로드 실패 (${ae.locale}):`,a instanceof Error?a.message:a)})];ae.locale!==e&&n.push(ae.translationEngine.loadTranslations(o.templateId,e).then(()=>{Qe.log(`폴백 다국어 파일 로드 완료: ${e}`)}).catch(a=>{Qe.warn(`폴백 다국어 파일 로드 실패 (${e}):`,a instanceof Error?a.message:a)})),await Promise.allSettled(n),Qe.log("템플릿 메타데이터 로드 중...",o.templateId),ae.templateMetadata=await zA(o.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 Lo=null;function _f(){const o=window.G7Core;return o?.__LayoutEditorChrome?Promise.resolve(o.__LayoutEditorChrome):Lo||(Lo=new Promise((e,n)=>{const a=window.G7Config?.coreEditorAsset||"/build/core/layout-editor.min.js",i="g7-layout-editor-bundle",l=document.getElementById(i),c=()=>{const f=window.G7Core?.__LayoutEditorChrome;f?e(f):n(new Error("편집기 번들 로드됨 — 그러나 __LayoutEditorChrome 미노출"))};if(window.G7Core=window.G7Core||{},window.G7Core.__onChromeReady=c,l){l.addEventListener("load",c,{once:!0}),l.addEventListener("error",()=>n(new Error(`편집기 번들 로드 실패: ${a}`)),{once:!0});return}const d=document.createElement("script");d.id=i,d.src=a,d.async=!1,d.addEventListener("load",c,{once:!0}),d.addEventListener("error",()=>{Lo=null,n(new Error(`편집기 번들 로드 실패: ${a}`))},{once:!0}),document.head.appendChild(d)}),Lo)}async function hs(o){try{if(Qe.log("템플릿 렌더링 시작",o),!ae.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다. initTemplateEngine()을 먼저 호출하세요.");if(!o.containerId)throw new Error("containerId는 필수입니다.");if(!o.layoutJson)throw new Error("layoutJson은 필수입니다.");const e=document.getElementById(o.containerId);if(!e)throw new Error(`컨테이너를 찾을 수 없습니다: #${o.containerId}`);const n=Cy();if(ae.containerId=o.containerId,ae.currentLayoutJson=o.layoutJson,ae.currentDataContext={...n,...o.dataContext||{}},ae.translationContext=o.translationContext||{templateId:ae.templateId||"",locale:ae.locale},ae.reactRoot||(Qe.log("React Root 생성"),ae.reactRoot=ad.createRoot(e)),typeof window<"u"){const l=my(window.location.pathname);if(l){Qe.log("레이아웃 편집기 모드 진입",l);let c;try{c=await _f()}catch(f){Qe.error("레이아웃 편집기 번들 로드 실패",f),vf.render(o.containerId,{title:"레이아웃 편집기 로드 실패",message:f instanceof Error?f.message:"편집기 번들을 불러오지 못했습니다.",icon:"fas fa-triangle-exclamation",showStack:!1,showReloadButton:!0,debug:ko});return}const d=Ye.createElement(c,{templateIdentifier:l.templateIdentifier,initialLocale:ae.locale});ae.reactRoot.render(Ye.createElement(mc,{translationEngine:ae.translationEngine,translationContext:ae.translationContext,children:Ye.createElement(Bd,{children:Ye.createElement(nc,{children:Ye.createElement(gf,{children:d})})})}));return}}const a=o.layoutJson.components||[];if(a.length===0){Qe.warn("렌더링할 컴포넌트가 없습니다.");return}const i=o.layoutJson.modals||[];if(Qe.log("modals 배열:",i),Qe.log("modals 개수:",i.length),Qe.log("DynamicRenderer로 렌더링 시작"),ae.reactRoot.render(Ye.createElement(mc,{translationEngine:ae.translationEngine,translationContext:ae.translationContext},Ye.createElement(Bd,null,Ye.createElement(nc,null,Ye.createElement(gf,null,[...a.map((l,c)=>{const d=ae.currentLayoutJson?.layout_name||"";return Ye.createElement(jr,{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})}),Ye.createElement(om,{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,g=c.indexOf(l.id),m=g>=0?50+g:50,b=window.__g7LayoutContextStack||[],v=b[b.length-1]?.dataContext,_=Ye.createElement(jr,{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:v});return l.data_sources&&l.data_sources.length>0?Ye.createElement(gy,{key:`modal_${l.id}`,isOpen:f,modalId:l.id,dataSources:l.data_sources,dataContext:ae.currentDataContext,globalStateUpdater:ae.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:ae.bindingEngine,debug:ko,children:_}):_}))]))))),Qe.log("템플릿 렌더링 완료"),Do.length>0){Qe.log(`대기 중인 데이터 업데이트 ${Do.length}건 적용`);const l=[...Do];Do.length=0;for(const{data:c,options:d}of l)gs(c,d)}}catch(e){throw Qe.error("템플릿 렌더링 실패",e),e}}function gs(o,e){try{if(Qe.log("템플릿 데이터 업데이트 시작",Object.keys(o)),!ae.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다.");if(!ae.reactRoot||!ae.currentLayoutJson){Qe.log("React 미준비 - 데이터 업데이트 큐잉:",Object.keys(o)),Do.push({data:o,options:e});return}const n=Cy(),a={...ae.currentDataContext._global||{},...o._global||{}},i=yC(ae.currentDataContext._localInit,o._localInit);ae.currentDataContext={...n,...ae.currentDataContext,...o,_global:a,_localInit:i},a._local!==void 0&&(ae.currentDataContext._local=a._local),a._computed!==void 0&&(ae.currentDataContext._computed=a._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(Ye.createElement(mc,{translationEngine:ae.translationEngine,translationContext:ae.translationContext},Ye.createElement(Bd,null,Ye.createElement(nc,null,Ye.createElement(gf,null,[...l.map((f,g)=>{const m=ae.currentLayoutJson?.layout_name||"";return Ye.createElement(jr,{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:g===0,layoutKey:m})}),Ye.createElement(om,{key:"__modal_parent_context_provider_update"},c.map(f=>{const g=ae.currentDataContext._global?.modalStack||[],b=g.includes(f.id)||ae.currentDataContext._global?.activeModal===f.id,S=g.indexOf(f.id),v=S>=0?50+S:50,_=window.__g7LayoutContextStack||[],x=_[_.length-1]?.dataContext,L=Ye.createElement(jr,{key:`modal_${f.id}_renderer`,componentDef:{...f,props:{...f.props,isOpen:b,style:{...f.props?.style,zIndex:v},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:x});return f.data_sources&&f.data_sources.length>0?Ye.createElement(gy,{key:`modal_${f.id}`,isOpen:b,modalId:f.id,dataSources:f.data_sources,dataContext:ae.currentDataContext,globalStateUpdater:ae.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:ae.bindingEngine,debug:ko,children:L}):L}))])))))};e?.sync?(Qe.log("재렌더링 시작 (sync mode - 즉시 렌더링)"),d()):(Qe.log("재렌더링 시작 (with startTransition)"),N.startTransition(()=>{d()})),Qe.log("템플릿 데이터 업데이트 완료")}catch(n){throw Qe.error("템플릿 데이터 업데이트 실패",n),n}}function Ec(){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(o){throw Qe.error("템플릿 정리 실패",o),o}}function ea(){return Object.freeze({...ae})}function Ey(){return ae.actionDispatcher}const Mo={initTemplateEngine:Oo,renderTemplate:hs,updateTemplateData:gs,destroyTemplate:Ec,getState:ea};typeof window<"u"&&(window.G7Core||(window.G7Core={}),window.G7Core.TemplateEngine=Mo,LA({getState:()=>({translationEngine:ae.translationEngine,translationContext:ae.translationContext,bindingEngine:ae.bindingEngine,actionDispatcher:ae.actionDispatcher,templateMetadata:ae.templateMetadata}),transitionManager:Hr,responsiveManager:hi,webSocketManager:vc}),Qe.log("전역 객체 window.G7Core.TemplateEngine에 노출됨"));const Ur=Object.freeze(Object.defineProperty({__proto__:null,DataSourceManager:Er,LayoutLoader:ff,TemplateApp:xo,TemplateEngine:Mo,default:Mo,destroyTemplate:Ec,getActionDispatcher:Ey,getState:ea,initTemplateApp:Ef,initTemplateEngine:Oo,loadLayoutEditorBundle:_f,renderTemplate:hs,updateTemplateData:gs},Symbol.toStringTag,{value:"Module"}));Yt.DataSourceManager=Er,Yt.LayoutLoader=ff,Yt.TemplateApp=xo,Yt.TemplateEngine=Mo,Yt.default=Mo,Yt.destroyTemplate=Ec,Yt.getActionDispatcher=Ey,Yt.getState=ea,Yt.initTemplateApp=Ef,Yt.initTemplateEngine=Oo,Yt.loadLayoutEditorBundle=_f,Yt.renderTemplate=hs,Yt.updateTemplateData=gs,Object.defineProperties(Yt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})(this.G7Core=this.G7Core||{}); + `)(r)}catch(a){U.warn(`Expression evaluation failed: ${e}`,a);return}}async executeInitActions(e,r={}){const{getActionDispatcher:a}=await Promise.resolve().then(()=>Pr),i=a();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:",r),U.log("Init actions dataContext._global:",r._global);const l=e.map(d=>d.handler).filter(d=>d.includes("."));l.length>0&&await this.waitForHandlers(i,l);let c={...r};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},g=i.createHandler(f,c),m=new Event("init");await g(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,r,a=5e3){const i=Date.now(),l=50,c=()=>r.every(f=>e.customHandlers?.has(f));if(c()){U.log("All module handlers already registered");return}const d=mf().getFailedJsAssets();if(d.length>0){const f=d.some(y=>y==="module"||y==="plugin"),g=r.filter(y=>!e.customHandlers?.has(y)),m=g.length>0&&g.every(y=>d.some(w=>y.startsWith(`${w}.`)));if(f||m){U.warn("Extension asset load failed — not waiting for handlers that will never register:",{pending:g,failedAssets:d});return}}return U.log("Waiting for module handlers:",r),new Promise(f=>{const g=()=>{if(c()){U.log("All module handlers now registered"),f();return}if(Date.now()-i>=a){const m=r.filter(y=>!e.customHandlers?.has(y));U.warn("Timeout waiting for handlers:",m),f();return}setTimeout(g,l)};g()})}};$(xr,"LOCALE_STORAGE_KEY","g7_locale"),$(xr,"CACHE_VERSION_STORAGE_KEY","g7_cache_version");let To=xr;function bf(o){const e=new To(o);return o.websocket&&(Tc.configure(o.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=bf,window.G7Core.dataSource={refetch:async(o,e)=>{const r=window.__templateApp;if(!r){U.warn("TemplateApp not initialized (G7Core.dataSource.refetch)");return}return r.refetchDataSource(o,e)},get:o=>{const e=window.__templateApp;if(!e){U.warn("TemplateApp not initialized (G7Core.dataSource.get)");return}return e.getDataSource(o)}});function N_(o={}){const{checked:e,value:r,name:a,type:i="checkbox"}=o,c=r!==void 0?r:i==="checkbox"||i==="radio"?e??!1:String(e??""),d={checked:e??!1,value:c,name:a??"",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 I_(o={}){const{button:e=0,clientX:r=0,clientY:a=0}=o;return{button:e,clientX:r,clientY:a,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new MouseEvent("click"),bubbles:!0,cancelable:!0,defaultPrevented:!1,eventPhase:Event.AT_TARGET,isTrusted:!1,timeStamp:Date.now(),type:"click",isDefaultPrevented:()=>!1,isPropagationStopped:()=>!1,persist:()=>{},target:document.createElement("div"),currentTarget:document.createElement("div")}}function H_(){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 j_(o,e="keydown"){return{key:o,code:o.length===1?`Key${o.toUpperCase()}`:o,preventDefault:()=>{},stopPropagation:()=>{},nativeEvent:new KeyboardEvent(e,{key:o}),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 z_={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 fy(o){const e=o.replace(/^(dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+/,"");for(const[r,a]of Object.entries(z_))if(a.test(e))return r;return null}function hy(o){const e=o.match(/^((dark:|hover:|focus:|active:|disabled:|group-hover:|sm:|md:|lg:|xl:|2xl:)+)/);return e?e[1]:""}function U_(o,e){if(!e||e.trim()==="")return o;if(!o||o.trim()==="")return e;const r=o.split(/\s+/).filter(Boolean),a=e.split(/\s+/).filter(Boolean),i=new Map;for(const c of a){const d=fy(c);if(d){const f=hy(c),g=`${d}:${f}`;i.set(g,c)}}return[...r.filter(c=>{const d=fy(c);if(!d)return!0;const f=hy(c),g=`${d}:${f}`;return!i.has(g)}),...a].join(" ")}function B_(o){return Object.entries(o).filter(([,e])=>e).map(([e])=>e).join(" ")}function P_(...o){return o.filter(e=>typeof e=="string"&&e.length>0).join(" ")}const be=ut("G7CoreGlobals");function q_(){window.React=We,window.ReactDOM={...ad,createPortal:Oa.createPortal,unstable_batchedUpdates:o=>o()},window.ReactJSXRuntime=j0,be.log("전역 객체 window.React, window.ReactDOM, window.ReactJSXRuntime에 노출됨")}function G_(o){const e=new Map,r=Ma.getInstance();o.componentEvent={on:(a,i)=>(e.has(a)||e.set(a,new Set),e.get(a).add(i),r.trackEventSubscribe(a),()=>{e.get(a)?.delete(i),r.trackEventUnsubscribe(a)}),emit:async(a,i)=>{const l=e.get(a),c=l?.size??0;if(!l||l.size===0)return r.trackEventEmit(a,i,0),[];let d,f=[];try{f=await Promise.all(Array.from(l).map(async g=>{try{return await g(i)}catch(m){throw be.error(`componentEvent: Error in listener for "${a}":`,m),m}}))}catch(g){d=g instanceof Error?g:new Error(String(g))}if(r.trackEventEmit(a,i,c,f,d),d)throw d;return f},off:a=>{e.delete(a),r.trackEventOff(a)},clear:()=>{e.clear(),r.trackEventClear()}},be.log("전역 객체 window.G7Core.componentEvent에 노출됨")}function V_(o){o.__runtime||(o.__runtime={DynamicRenderer:Br,ComponentRegistry:mr,TranslationEngine:gi,DataSourceManager:_r,dataSourceManager:__,DataBindingEngine:_n,dataBindingEngine:pd,ActionDispatcher:mo,TranslationReactContext:lf,TranslationProvider:_c,useTranslation:Xm,ResponsiveContext:jd,ResponsiveProvider:uc,useResponsive:zd,responsiveManager:mi,BREAKPOINT_PRESETS:Vl,AuthManager:br,createLogger:ut,G7DevToolsCore:Ma},be.log("전역 객체 window.G7Core.__runtime(코어 런타임 표면)에 노출됨"))}function F_(o){if(o.layoutEditor&&o.layoutEditor.__isStub!==!0||o.layoutEditor&&o.layoutEditor.__isStub===!0)return;const e=[],r=[];o.layoutEditor={__isStub:!0,__queue:e,__readyCallbacks:r,registerWidget:(a,i)=>e.push(["widget",a,i]),registerNodeEditor:(a,i)=>e.push(["nodeEditor",a,i]),registerCanvasOverlay:(a,i)=>e.push(["canvasOverlay",a,i]),onReady:a=>{typeof a=="function"&&r.push(a)}},be.log("전역 객체 window.G7Core.layoutEditor 예약 접수함(stub) 노출됨")}function K_(o,e){o.useTranslation=Xm,o.t=(r,a)=>{const i=e.getState();if(!i.translationEngine||!i.translationContext)return r;if(a){const l="|"+Object.entries(a).map(([c,d])=>`${c}=${d}`).join("|");return i.translationEngine.translate(r,i.translationContext,l)}return i.translationEngine.translate(r,i.translationContext)},be.log("전역 객체 window.G7Core.useTranslation에 노출됨")}function W_(o,e){o.createChangeEvent=N_,o.createClickEvent=I_,o.createSubmitEvent=H_,o.createKeyboardEvent=j_,o.uuid=()=>typeof crypto<"u"&&crypto.randomUUID?crypto.randomUUID():"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(/[xy]/g,r=>{const a=Math.random()*16|0;return(r==="x"?a:a&3|8).toString(16)}),o.createLogger=ut,be.log("전역 객체 window.G7Core.createLogger에 노출됨"),o.renderItemChildren=(r,a,i,l,c)=>{const d=e.getState(),m={_global:window.__templateApp?.getGlobalState?.()||{},_local:a._local||{},_computed:a._computed||{},...a},y=new Set,w=(v,A)=>{const x=m._global?._remountKeys;return v&&x?.[v]&&!y.has(v)?(y.add(v),`${v}-remount-${x[v]}`):v||A},S={translationContext:d.translationContext,translationEngine:d.translationEngine,bindingEngine:d.bindingEngine,actionDispatcher:d.actionDispatcher,getRemountKey:w,...c};return oo(r,m,i,l,S)},o.evaluateCondition=(r,a)=>{if(!r)return!0;const i=e.getState(),c=window.__templateApp?.getGlobalState?.()||{},d={_global:c,_local:c._local||{},_computed:c._computed||{},...a||{}},f=i.bindingEngine??pd;return ip(r,d,f)},o.getComponentMap=()=>mr.getInstance().getComponentMap(),o.renderComponentLayout=(r,a,i)=>{if(!r||!Array.isArray(r)||r.length===0)return null;const l=mr.getInstance().getComponentMap(),c=e.getState(),f=window.__templateApp?.getGlobalState?.()||{},g={_global:f._global||{},_local:f._local||{},_computed:f._computed||{},...a},m=new Set,y=(w,S)=>{const v=g._global?._remountKeys;return w&&v?.[w]&&!m.has(w)?(m.add(w),`${w}-remount-${v[w]}`):w||S};return oo(r,g,l,i,{translationContext:c.translationContext,translationEngine:c.translationEngine,bindingEngine:c.bindingEngine,actionDispatcher:c.actionDispatcher,getRemountKey:y})},o.renderExpandContent=r=>{const{children:a,row:i,expandContext:l,componentContext:c,keyPrefix:d}=r;if(!a||!Array.isArray(a)||a.length===0)return null;const f=r.componentMap||mr.getInstance().getComponentMap(),g=e.getState(),m=o.state?.get?.()||{},y=c?.stateRef?.current??c?.state??{},w={...m._local||{},...y},S=c?.computedRef?.current??m._computed??{},v=g.bindingEngine??o.getDataBindingEngine?.(),A={...m,_local:w,_computed:S,row:i,item:i,$item:i};let x={};if(l&&typeof l=="object"&&v)try{for(const[L,q]of Object.entries(l))if(typeof q=="string"){const G=Ta(q);if(G!==null)try{x[L]=Gn(G)?v.evaluatePipeExpression(G,A,{skipCache:!0}):v.evaluateExpression(G,A,{skipCache:!0})}catch{x[L]=void 0}else x[L]=v.resolveBindings(q,A,{skipCache:!0})}else x[L]=q}catch(L){be.warn("renderExpandContent: expandContext 평가 오류:",L)}const R={row:i,item:i,$item:i,_local:w,_global:m._global||{},_computed:m._computed||{},...x},M=new Set,O=(L,q)=>{const G=R._global?._remountKeys;return L&&G?.[L]&&!M.has(L)?(M.add(L),`${L}-remount-${G[L]}`):L||q};return oo(a,R,f,d,{translationContext:g.translationContext,translationEngine:g.translationEngine??void 0,bindingEngine:g.bindingEngine??void 0,actionDispatcher:g.actionDispatcher,componentContext:c,getRemountKey:O})},o.$get=function(a,i,l=void 0){if(a==null)return l;const c=Array.isArray(i)?i:[i];if(c.length===0)return a;let d=a;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 Y_(o){o.dispatch=async(e,r)=>{const a=window.__templateApp;if(!a)return be.warn("G7Core.dispatch: TemplateApp이 초기화되지 않았습니다."),{success:!1,error:new Error("TemplateApp이 초기화되지 않았습니다.")};const i=a.getActionDispatcher?.();if(!i)return be.warn("G7Core.dispatch: ActionDispatcher를 찾을 수 없습니다."),{success:!1,error:new Error("ActionDispatcher를 찾을 수 없습니다.")};const l=a.getRouter?.(),c=a.getGlobalState?.(),d=a.setGlobalState?.bind(a),g=r?.componentContext||window.__g7ActionContext,m=window.__g7PendingLocalState;let y=g?.state??c;m&&g&&(y=m,be.log("[dispatch] Using __g7PendingLocalState for context.state:",m));let w=g?.data??c;m&&g?.data?._local&&(w={...g.data,_local:m},be.log("[dispatch] Updated context.data._local with pendingLocalState"));const S={navigate:l?(v,A)=>l.navigate(v,A):void 0,setState:g?.setState??d,state:y,data:w,_isDispatchFallbackContext:!g?.setState};if(e.debounce){const v=e.debounceKey||`dispatch-${e.handler}`,A=typeof e.debounce=="number"?e.debounce:e.debounce.delay;return i.debouncedCall(v,A,()=>{const{debounce:x,debounceKey:R,...M}=e;i.dispatchAction(M,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 ko(o){const e={};for(const[r,a]of Object.entries(o))if(r.includes(".")){const i=r.split(".");let l=e;for(let c=0;c0&&e.every(r=>/^\d+$/.test(r))}function py(o,e){const r={...o};for(const a of Object.keys(e))a in r?r[a]!==null&&typeof r[a]=="object"&&!Array.isArray(r[a])&&e[a]!==null&&typeof e[a]=="object"&&!Array.isArray(e[a])&&(r[a]=py(r[a],e[a])):r[a]=e[a];return r}function ir(o,e){if(Array.isArray(o)&&!Array.isArray(e)&&X_(e)){const a=Object.keys(e).map(l=>parseInt(l,10));if(!((a.length>0?Math.max(...a):0)>=o.length+a.length+10)){const l=[...o];for(const[c,d]of Object.entries(e)){const f=parseInt(c,10);f>=0&&f=l.length&&(l[f]=d)}return l}}const r={...o};for(const[a,i]of Object.entries(e))i!==null&&typeof i=="object"&&!Array.isArray(i)?r[a]!==null&&typeof r[a]=="object"?r[a]=ir(r[a],i):r[a]={...i}:r[a]=i;return r}function J_(o){o.state={get:()=>window.__templateApp?.getGlobalState?.()||{},set:(e,r)=>{const a=window.__templateApp;if(a?.setGlobalState&&a?.getGlobalState){const i=r?.merge||"deep",l=ko(e);let c;if(i==="replace")c=l;else if(i==="shallow")c={...a.getGlobalState(),...l};else{const d=a.getGlobalState();c=ir(d,l)}a.setGlobalState(c,{render:r?.render})}else be.warn("G7Core.state.set: TemplateApp이 초기화되지 않았습니다.")},setLocal:(e,r)=>{const a=window.__templateApp;if(r?.render===!1&&!r?.selfManaged){const x=window.__g7AutoBindingPaths;x&&x.size>0&&gy(ko(e)).some(M=>x.has(M))&&(be.log("[setLocal] render:false + 자동바인딩 경로 겹침 감지 → render:true 자동 승격 (engine-v1.43.0)"),r={...r,render:!0})}if(r?.debounce){const x=a?.getActionDispatcher?.();if(x){const R=r.debounceKey||`setLocal-${Object.keys(e).join(",")}`,{debounce:M,debounceKey:O,...L}=r;x.debouncedCall(R,r.debounce,()=>{o.state.setLocal(e,L)});return}}const i=r?.scope??"current",l=r?.merge||"deep",c=window.__g7ActionContext,d=ko(e);if(i==="parent"||i==="root"){const x=window.__g7LayoutContextStack||[];if(x.length>0){const R=i==="parent"?x[x.length-1]:x[0];if(R?.setState){R.setState(M=>l==="replace"?d:l==="shallow"?{...M||{},...d}:ir(M||{},d)),be.log(`[setLocal] scope=${i}: 타겟 컨텍스트에 상태 업데이트 (mergeMode=${l})`,d);return}}be.warn(`[setLocal] scope=${i}: 레이아웃 컨텍스트 스택이 비어있습니다. current로 폴백합니다.`)}const f=window.__g7PendingLocalState,g=a?.getGlobalState?.()?._local||{},w=!((window.__g7LayoutContextStack||[]).length>0)&&c?.state?c.state:void 0,S=w?py(g,w):g,v=f||S;let A;if(l==="replace"?A=d:l==="shallow"?A={...v,...d}:A=ir(v,d),a?.setGlobalState&&(a.setGlobalState({_local:A},{render:r?.render}),be.log(`[setLocal] globalLocal updated via setGlobalState (mergeMode=${l}, render=${r?.render??!0}):`,d)),window.__g7PendingLocalState=A,be.log("[setLocal] __g7PendingLocalState updated:",A),window.__g7SequenceLocalSync=A,window.__g7LastSetLocalSnapshot=A,l==="replace")window.__g7ForcedLocalFields=d;else{const x=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=ir(x,d)}if(be.log("[setLocal] __g7ForcedLocalFields updated:",d),l==="replace")window.__g7SetLocalOverrideKeys=d;else{const x=window.__g7SetLocalOverrideKeys||{};window.__g7SetLocalOverrideKeys=ir(x,d)}be.log("[setLocal] __g7SetLocalOverrideKeys updated:",d),c?.setState&&c.setState(x=>l==="replace"?d:l==="shallow"?{...x||{},...d}:ir(x||{},d)),a?.setGlobalState||be.warn("G7Core.state.setLocal: TemplateApp이 없습니다.")},getLocal:()=>{const a=(window.__templateApp?.getGlobalState?.()||{})._local||{},i=window.__g7PendingLocalState;if(i)return ir(a,i);const l=window.__g7LastSetLocalSnapshot;return l&&l!==a?ir(a,l):a},update:e=>{const r=window.__templateApp;if(r?.getGlobalState&&r?.setGlobalState){const a=r.getGlobalState(),i=e(a);r.setGlobalState(i)}else be.warn("G7Core.state.update: TemplateApp이 초기화되지 않았습니다.")},subscribe:e=>{const r=window.__templateApp;return r?.onGlobalStateChange?r.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,r,a)=>{let i,l,c;typeof e=="string"?(i=e,l=r||{},c=a):(l=e,c=r&&typeof r=="object"&&"merge"in r?r:a);const d=c?.merge||"deep",f=ko(l);if(i){const y=window.__g7IsolatedStates?.[i];y?.mergeState?y.mergeState(f,d):be.warn(`G7Core.state.setIsolated: scopeId '${i}'를 찾을 수 없습니다.`);return}const g=window.__g7ActionContext;g?.isolatedContext?.mergeState?g.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 r=e[e.length-1];if(!r)return null;const a=r.dataContext||{};return{_local:r.state||a._local||{},_global:a._global||o.state.get()||{},setState:r.setState}},setParentLocal:(e,r,a)=>{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]:r},d=a):(c=e,d=r&&typeof r=="object"&&"merge"in r?r:a);const f=d?.merge||"deep",g=ko(c),m=l.state?._local!==void 0,y=m?l.state._local:l.state||{};let w;f==="replace"?w=g:f==="shallow"?w={...y,...g}:w=ir(y,g),window.__g7PendingLocalState=w;const S=window.__templateApp;if(S?.setGlobalState&&S.setGlobalState({_local:w}),l.setState(w),m?l.state._local=w:l.state=w,l.dataContext&&(l.dataContext._local=w),f==="replace")window.__g7ForcedLocalFields=g;else{const v=window.__g7ForcedLocalFields||{};window.__g7ForcedLocalFields=ir(v,g)}Nd()},setParentGlobal:(e,r)=>{let a;typeof e=="string"?a={[e]:r}:a=e,o.state.set(a),be.log("[setParentGlobal] 전역 상태 업데이트:",a)}},window.__g7IsolatedStates||(window.__g7IsolatedStates={}),o.state.getGlobal=o.state.get,o.state.setGlobal=o.state.set,be.log("전역 객체 window.G7Core.state에 노출됨")}function Q_(o){o.dataSource={get:e=>window.__templateApp?.getDataSource?.(e),set:(e,r,a)=>{const i=window.__templateApp;i?.setDataSource?i.setDataSource(e,r,a):be.warn("G7Core.dataSource.set: TemplateApp이 초기화되지 않았습니다.")},refetch:async(e,r)=>{const a=window.__templateApp;if(a?.refetchDataSource)return a.refetchDataSource(e,r);be.warn("G7Core.dataSource.refetch: TemplateApp이 초기화되지 않았습니다.")},updateItem:(e,r,a,i,l)=>{const c=window.__templateApp;return c?.updateDataSourceItem?c.updateDataSourceItem(e,r,a,i,l):(be.warn("G7Core.dataSource.updateItem: TemplateApp이 초기화되지 않았습니다."),!1)},updateData:(e,r,a,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,g=null;if(r){const y=r.split(".");g=y.pop();for(const w of y)if(f&&typeof f=="object"&&w in f)f=f[w];else return be.warn(`G7Core.dataSource.updateData: 경로 '${r}'를 찾을 수 없습니다.`),!1;d=f[g]}else d=c;if(!Array.isArray(d))return be.warn("G7Core.dataSource.updateData: 대상 경로의 데이터가 배열이 아닙니다."),!1;if(!Array.isArray(a))return be.warn("G7Core.dataSource.updateData: newData가 배열이 아닙니다."),!1;const m=i==="prepend"?[...a,...d]:[...d,...a];return r&&g?(f[g]=m,l.setDataSource(e,c,{merge:!1})):l.setDataSource(e,m,{merge:!1}),be.log(`G7Core.dataSource.updateData: '${e}'에 ${a.length}개 항목 ${i==="prepend"?"앞에":"뒤에"} 추가됨`),!0}},be.log("전역 객체 window.G7Core.dataSource에 노출됨")}function Z_(o,e){o.locale={current:()=>window.__templateApp?.getLocale?.()||"ko",supported:()=>{const a=window.__templateApp?.globalState?.appConfig?.supportedLocales;return Array.isArray(a)&&a.length>0?a:e.getState().templateMetadata?.locales||["ko","en"]},change:async r=>{const a=window.__templateApp;a?.changeLocale?await a.changeLocale(r):be.warn("G7Core.locale.change: TemplateApp이 초기화되지 않았습니다.")}},be.log("전역 객체 window.G7Core.locale에 노출됨")}function eA(o){o.toast={show:(e,r)=>{o.dispatch({handler:"toast",params:{message:e,type:r?.type||"info",...r?.duration&&{duration:r.duration}}})},success:(e,r)=>{o.toast.show(e,{type:"success",duration:r})},error:(e,r)=>{o.toast.show(e,{type:"error",duration:r})},warning:(e,r)=>{o.toast.show(e,{type:"warning",duration:r})},info:(e,r)=>{o.toast.show(e,{type:"info",duration:r})}},be.log("전역 객체 window.G7Core.toast에 노출됨")}function tA(o){o.modal={open:e=>{o.dispatch({handler:"openModal",target:e})},close:e=>{o.dispatch({handler:"closeModal",...e&&{target:e}})},closeAll:()=>{o.dispatch({handler:"closeAllModals"})},isOpen:e=>{const r=o.state.get();return r._global?.activeModal===e||r._global?.modalStack?.includes(e)||!1},getStack:()=>o.state.get()._global?.modalStack||[]},be.log("전역 객체 window.G7Core.modal에 노출됨")}function nA(o){o.style={mergeClasses:U_,conditionalClass:B_,joinClasses:P_},be.log("전역 객체 window.G7Core.style에 노출됨")}function rA(o,e){const{webSocketManager:r}=e;o.websocket={manager:r,subscribe:(a,i,l,c)=>r.subscribe(a,i,l,c),unsubscribe:a=>r.unsubscribe(a),leaveChannel:a=>r.leaveChannel(a),disconnect:()=>r.disconnect(),isInitialized:()=>r.isInitialized(),getSubscriptionCount:()=>r.getSubscriptionCount()},be.log("전역 객체 window.G7Core.websocket에 노출됨")}function aA(o,e){const{transitionManager:r}=e;o.navigation={isPending:()=>r?.getIsPending?.()||!1,onComplete:a=>{if(!r)return a(),()=>{};let i=r.getIsPending();const l=r.subscribe(c=>{c?i=!0:i&&(a(),l())});return l}},be.log("전역 객체 window.G7Core.navigation에 노출됨")}function iA(o){o.plugin={getSettings:e=>window.G7Config?.plugins?.[e],get:(e,r,a)=>window.G7Config?.plugins?.[e]?.[r]??a,getAll:()=>window.G7Config?.plugins??{}},be.log("전역 객체 window.G7Core.plugin에 노출됨")}function sA(o){o.module={getSettings:e=>window.G7Config?.modules?.[e],get:(e,r,a)=>window.G7Config?.modules?.[e]?.[r]??a,getAll:()=>window.G7Config?.modules??{}},be.log("전역 객체 window.G7Core.module에 노출됨")}function oA(o,e){const{transitionManager:r,responsiveManager:a}=e;o.AuthManager=br,o.api=jr(),o.TransitionManager=r,o.useTransitionState=om,o.ResponsiveManager=a,o.useResponsive=zd,o.useControllableState=J0,o.shallowArrayEqual=Q0,o.shallowObjectEqual=cm,o.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 lA(o,e){o.getSlotContext=()=>window.__slotContextValue??null,o.getDynamicRenderer=()=>window.__DynamicRenderer??null,o.getComponentRegistry=()=>e.getComponentRegistry?.()??mr.getInstance(),o.getDataBindingEngine=()=>e.getDataBindingEngine?.()??e.getState().bindingEngine,o.getTranslationEngine=()=>e.getTranslationEngine?.()??e.getState().translationEngine,o.getActionDispatcher=()=>e.getActionDispatcher?.()??e.getState().actionDispatcher,be.log("전역 객체 window.G7Core 슬롯 API에 노출됨 (getSlotContext, getDynamicRenderer 등)")}function cA(o){o.identity={setLauncher:mt.setLauncher.bind(mt),handle:mt.handle.bind(mt),isIdentityRequired:mt.isIdentityRequired.bind(mt),hasLauncher:mt.hasLauncher.bind(mt),markDomainNoticeShown:mt.markDomainNoticeShown.bind(mt),redirectExternally:mt.redirectExternally.bind(mt),createDeferred:mt.createDeferred.bind(mt),resolveDeferred:mt.resolveDeferred.bind(mt),reset:mt.reset.bind(mt),redirectStashKey:Rd},be.log("전역 객체 window.G7Core 본인인증(IDV) API에 노출됨 (identity)")}function uA(o){if(typeof window>"u")return;q_(),window.G7Core||(window.G7Core={});const e=window.G7Core;V_(e),G_(e),F_(e),oA(e,o),K_(e,o),W_(e,o),Y_(e),J_(e),Q_(e),Z_(e,o),eA(e),tA(e),nA(e),rA(e,o),aA(e,o),iA(e),sA(e),lA(e,o),cA(e),be.log("G7Core 전역 객체 초기화 완료")}function dA(){const o=window.G7Core;if(!o){be.warn("G7Core가 초기화되지 않았습니다.");return}const e=()=>Ma.getInstance(),r={isEnabled:()=>{try{return e().isEnabled()}catch{return!1}},trackRender:a=>{try{e().isEnabled()&&e().trackRender(a)}catch{}},trackIteration:(a,i,l,c,d)=>{try{e().isEnabled()&&e().trackIteration(a,{source:i,itemVar:l,indexVar:c,sourceLength:d})}catch{}},trackIfCondition:(a,i,l,c)=>{try{e().isEnabled()&&e().trackIfCondition(a,i,l)}catch{}},trackMount:(a,i)=>{try{e().isEnabled()&&e().trackMount(a,{...i,id:a})}catch{}},trackUnmount:a=>{try{e().isEnabled()&&e().trackUnmount(a)}catch{}},trackExpressionEval:a=>{try{e().isEnabled()&&e().trackExpressionEval(a)}catch{}},trackBindingEval:a=>{try{e().isEnabled()&&e().trackBindingEval(a)}catch{}},recordCacheHit:()=>{try{e().isEnabled()&&e().recordCacheHit()}catch{}},recordCacheMiss:()=>{try{e().isEnabled()&&e().recordCacheMiss()}catch{}},trackHandlerRegistration:(a,i,l,c)=>{try{e().isEnabled()&&e().trackHandlerRegistration(a,i,l,c)}catch{}},trackHandlerUnregistration:a=>{try{e().isEnabled()&&e().trackHandlerUnregistration(a)}catch{}},logAction:a=>{try{e().isEnabled()&&e().logAction(a)}catch{}},trackRequest:(a,i)=>{try{return e().isEnabled()?e().trackRequest(a,i):""}catch{return""}},completeRequest:(a,i,l)=>{try{e().isEnabled()&&e().completeRequest(a,i,l)}catch{}},failRequest:(a,i)=>{try{e().isEnabled()&&e().failRequest(a,i)}catch{}},trackDataSourceDefinition:a=>{try{e().isEnabled()&&e().trackDataSourceDefinition(a)}catch{}},trackDataSourceLoading:a=>{try{e().isEnabled()&&e().trackDataSourceLoading(a)}catch{}},trackDataSourceLoaded:(a,i,l)=>{try{e().isEnabled()&&e().trackDataSourceLoaded(a,i,l)}catch{}},trackDataSourceError:(a,i)=>{try{e().isEnabled()&&e().trackDataSourceError(a,i)}catch{}},trackForm:(a,i,l)=>{try{e().isEnabled()&&e().trackForm(a,i,l)}catch{}},untrackForm:a=>{try{e().isEnabled()&&e().untrackForm(a)}catch{}},startStateChange:(a,i,l,c)=>{try{return e().isEnabled()?e().startStateChange(a,i,l,c):""}catch{return""}},completeStateChange:a=>{try{e().isEnabled()&&e().completeStateChange(a)}catch{}},trackComponentRender:(a,i,l,c,d,f)=>{try{e().isEnabled()&&e().trackComponentRender(a,i,l,c,d,f)}catch{}},updateLocalState:a=>{try{e().isEnabled()&&e().updateLocalState(a)}catch{}},updateComputedState:a=>{try{e().isEnabled()&&e().updateComputedState(a)}catch{}},updateParentContext:a=>{try{e().isEnabled()&&e().updateParentContext(a)}catch{}},trackComponentStateSource:(a,i,l,c)=>{try{e().isEnabled()&&e().trackComponentStateSource(a,i,l,c)}catch{}},trackDynamicState:(a,i)=>{try{e().isEnabled()&&e().trackDynamicState(a,i)}catch{}},trackContextFlow:(a,i,l,c,d,f)=>{try{e().isEnabled()&&e().trackContextFlow(a,i,l,c,d,f)}catch{}},trackComponentStyle:(a,i,l,c)=>{try{e().isEnabled()&&e().trackComponentStyle(a,i,l,c)}catch{}},trackAuthEvent:(a,i,l,c)=>{try{e().isEnabled()&&e().trackAuthEvent(a,i,l,c)}catch{}},trackAuthHeader:(a,i,l,c,d)=>{try{e().isEnabled()&&e().trackAuthHeader(a,i,l,c,d)}catch{}},trackLog:(a,i,l)=>{try{e().isEnabled()&&e().trackLog(a,i,l)}catch{}},trackAction:a=>{try{e().isEnabled()&&e().trackAction?.(a)}catch{}},trackDataSourceUpdate:a=>{try{e().isEnabled()&&e().trackDataSourceUpdate?.(a)}catch{}},startSequenceExecution:a=>{try{return e().isEnabled()?e().startSequenceExecution(a):""}catch{return""}},captureSequenceActionBefore:(a,i,l,c,d)=>{try{e().isEnabled()&&e().captureSequenceActionBefore(a,i,l,c,d)}catch{}},captureSequenceActionAfter:(a,i,l,c,d,f)=>{try{e().isEnabled()&&e().captureSequenceActionAfter(a,i,l,c,d,f)}catch{}},endSequenceExecution:(a,i)=>{try{e().isEnabled()&&e().endSequenceExecution(a,i)}catch{}},registerStateCaptureForHandler:(a,i,l)=>{try{e().isEnabled()&&e().registerStateCaptureForHandler(a,i,l)}catch{}},detectStaleClosure:(a,i,l,c,d)=>{try{return e().isEnabled()?e().detectStaleClosure(a,i,l,c,d):[]}catch{return[]}},trackStaleClosureWarning:a=>{try{e().isEnabled()&&e().trackStaleClosureWarning(a)}catch{}},trackModalOpen:a=>{try{e().isEnabled()&&e().trackModalOpen(a)}catch{}},trackModalClose:(a,i)=>{try{e().isEnabled()&&e().trackModalClose(a,i)}catch{}},trackModalStateChange:a=>{try{e().isEnabled()&&e().trackModalStateChange(a)}catch{}},trackNestedContext:a=>{try{return e().isEnabled()?e().trackNestedContext(a):""}catch{return""}},trackNestedContextAccess:(a,i)=>{try{e().isEnabled()&&e().trackNestedContextAccess(a,i)}catch{}},trackComputedProperty:(a,i,l,c,d,f,g)=>{try{e().isEnabled()&&e().trackComputedProperty(a,i,l,c,d,f,g)}catch{}},trackComputedRecalc:(a,i,l,c,d,f,g)=>{try{e().isEnabled()&&e().trackComputedRecalc(a,i,l,c,d,f,g)}catch{}},setNamedActionDefinitions:a=>{try{e().isEnabled()&&e().setNamedActionDefinitions(a)}catch{}},trackNamedActionRef:a=>{try{e().isEnabled()&&e().trackNamedActionRef(a)}catch{}}};o.devTools=r,be.log("G7Core.devTools 인터페이스 초기화 완료")}let Ro=null;function fA(){const o=window.G7Core;return o?.__devtools?Promise.resolve(o.__devtools):Ro||(Ro=new Promise((e,r)=>{const a=window.G7Config?.coreDevToolsAsset||"/build/core/devtools.min.js",i="g7-devtools-bundle",l=()=>{const f=window.G7Core?.__devtools;f?e(f):r(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",()=>r(new Error(`DevTools 번들 로드 실패: ${a}`)),{once:!0});return}const d=document.createElement("script");d.id=i,d.src=a,d.async=!1,d.addEventListener("load",l,{once:!0}),d.addEventListener("error",()=>{Ro=null,r(new Error(`DevTools 번들 로드 실패: ${a}`))},{once:!0}),document.head.appendChild(d)}),Ro)}function hA(){const o=window.G7Core;if(!o){be.warn("G7Core가 초기화되지 않았습니다.");return}const e=Ma.getInstance();if(e.initialize(),!e.isEnabled()){window.G7DevTools={isEnabled:()=>!1,enable:()=>{be.log("환경설정 > 고급 설정 > 디버그 모드를 켜세요")}},sd(),be.log("G7DevTools 비활성화됨 (디버그 모드 꺼짐)");return}gA(o,e)}async function gA(o,e){let r;try{r=await fA()}catch(g){be.warn("DevTools 번들 로드 실패 — 최소 API 로 폴백:",g),window.G7DevTools={isEnabled:()=>!1,enable:()=>{}},sd();return}const{DiagnosticEngine:a,getServerConnector:i,getStyleTracker:l}=r;dA(),sd();try{l().enable(),be.log("StyleTracker 활성화됨")}catch(g){be.warn("StyleTracker 활성화 실패:",g)}const c=new a,d=i(),f={isEnabled:()=>e.isEnabled(),state:{get:()=>e.getState(),getHistory:()=>e.getStateHistory(),watch:(g,m)=>e.watchState(g,m)},actions:{getHistory:()=>e.getActionHistory(),watch:g=>e.watchActions(g),getMetrics:()=>e.getActionMetrics()},binding:{evaluate:g=>{const m=o.getDataBindingEngine?.();if(!m){be.warn("DataBindingEngine이 없습니다.");return}return m.evaluateExpression(g,e.getState())},getCacheStats:()=>e.getCacheStats(),clearStats:()=>{e.resetCacheStats(),be.log("캐시 통계 초기화됨")}},diagnose:{analyze:g=>c.analyze(g),suggestFix:g=>c.suggestFix(g),getCommonIssues:()=>c.getCommonIssues(),getRulesByCategory:g=>c.getRulesByCategory(g)},server:{dumpState:g=>d.dumpState(g),sendLog:g=>d.sendLog(g),sendError:(g,m)=>d.sendError(g,m),isConnected:()=>d.isConnected(),testConnection:()=>d.testConnection()},config:{isDebugMode:()=>e.isEnabled(),setLogLevel:g=>e.setLogLevel(g),setMaxHistory:g=>e.setMaxHistory(g)},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,o.devtools=f,be.log("G7DevTools 전역 객체 초기화 완료 (window.G7DevTools)"),pA(r.DevToolsPanel)}function pA(o){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(o)),be.log("DevToolsPanel UI 렌더링 완료")}catch(r){be.error("DevToolsPanel UI 렌더링 실패:",r)}}const Qe=ut("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 Do=!1;const Oo=[];async function mA(o){try{Qe.log("템플릿 메타데이터 로드 중...",o);const e=o.split("-").map(a=>a.split("_").map(i=>i.charAt(0).toUpperCase()+i.slice(1)).join("")).join(""),r=window[e];return r?.templateMetadata?(Qe.log("템플릿 메타데이터 로드 완료 (전역 변수)",r.templateMetadata),r.templateMetadata):(Qe.warn(`템플릿 번들에 메타데이터가 없습니다. 전역 변수: ${e}`),{identifier:o,locales:["ko","en"],name:{ko:o,en:o},description:{ko:"",en:""},version:"1.0.0",type:"admin"})}catch(e){return Qe.error("템플릿 메타데이터 로드 실패",e),{identifier:o,locales:["ko","en"],name:{ko:o,en:o},description:{ko:"",en:""},version:"1.0.0",type:"admin"}}}function my(){const e=(typeof window<"u"?window.__templateApp:void 0)?.globalState?.appConfig?.supportedLocales,r=re.templateMetadata?.locales;return{$locale:re.locale,$locales:Array.isArray(e)&&e.length>0?e:r||["ko","en"],$templateLocales:r||["ko","en"],$templateId:re.templateId}}async function Lo(o){try{if(Qe.log("템플릿 엔진 초기화 시작",o),re.isInitialized)throw new Error("템플릿 엔진이 이미 초기화되었습니다. destroyTemplate()을 먼저 호출하세요.");if(!o.templateId)throw new x_;Do=o.debug??!1,typeof window<"u"&&(window.G7Config||(window.G7Config={}),window.G7Config.debug=Do),hA(),re.templateId=o.templateId,re.locale=o.locale||"ko",Qe.log("엔진 인스턴스 생성 중..."),re.registry=mr.getInstance(),re.bindingEngine=new _n,re.translationEngine=gi.getInstance(),o.cacheVersion!==void 0&&o.cacheVersion>0&&re.translationEngine.setCacheVersion(o.cacheVersion),re.translationContext={templateId:o.templateId,locale:re.locale},re.actionDispatcher=new mo({},re.translationEngine,re.translationContext),P0(re.actionDispatcher),Qe.log("다국어 파일 로드 중...",o.templateId,re.locale);const e="en",r=[re.translationEngine.loadTranslations(o.templateId,re.locale).then(()=>{Qe.log(`다국어 파일 로드 완료: ${re.locale}`)}).catch(a=>{Qe.warn(`다국어 파일 로드 실패 (${re.locale}):`,a instanceof Error?a.message:a)})];re.locale!==e&&r.push(re.translationEngine.loadTranslations(o.templateId,e).then(()=>{Qe.log(`폴백 다국어 파일 로드 완료: ${e}`)}).catch(a=>{Qe.warn(`폴백 다국어 파일 로드 실패 (${e}):`,a instanceof Error?a.message:a)})),await Promise.allSettled(r),Qe.log("템플릿 메타데이터 로드 중...",o.templateId),re.templateMetadata=await mA(o.templateId),re.isInitialized=!0,Qe.log("템플릿 엔진 초기화 완료 (ComponentRegistry는 별도 로드)")}catch(e){throw Qe.error("템플릿 엔진 초기화 실패",e),re.isInitialized=!1,re.registry=null,re.bindingEngine=null,re.translationEngine=null,re.actionDispatcher=null,e}}let Mo=null;function vf(){const o=window.G7Core;return o?.__LayoutEditorChrome?Promise.resolve(o.__LayoutEditorChrome):Mo||(Mo=new Promise((e,r)=>{const a=window.G7Config?.coreEditorAsset||"/build/core/layout-editor.min.js",i="g7-layout-editor-bundle",l=document.getElementById(i),c=()=>{const f=window.G7Core?.__LayoutEditorChrome;f?e(f):r(new Error("편집기 번들 로드됨 — 그러나 __LayoutEditorChrome 미노출"))};if(window.G7Core=window.G7Core||{},window.G7Core.__onChromeReady=c,l){l.addEventListener("load",c,{once:!0}),l.addEventListener("error",()=>r(new Error(`편집기 번들 로드 실패: ${a}`)),{once:!0});return}const d=document.createElement("script");d.id=i,d.src=a,d.async=!1,d.addEventListener("load",c,{once:!0}),d.addEventListener("error",()=>{Mo=null,r(new Error(`편집기 번들 로드 실패: ${a}`))},{once:!0}),document.head.appendChild(d)}),Mo)}async function us(o){try{if(Qe.log("템플릿 렌더링 시작",o),!re.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다. initTemplateEngine()을 먼저 호출하세요.");if(!o.containerId)throw new Error("containerId는 필수입니다.");if(!o.layoutJson)throw new Error("layoutJson은 필수입니다.");const e=document.getElementById(o.containerId);if(!e)throw new Error(`컨테이너를 찾을 수 없습니다: #${o.containerId}`);const r=my();if(re.containerId=o.containerId,re.currentLayoutJson=o.layoutJson,re.currentDataContext={...r,...o.dataContext||{}},re.translationContext=o.translationContext||{templateId:re.templateId||"",locale:re.locale},re.reactRoot||(Qe.log("React Root 생성"),re.reactRoot=ad.createRoot(e)),typeof window<"u"){const l=uy(window.location.pathname);if(l){Qe.log("레이아웃 편집기 모드 진입",l);let c;try{c=await vf()}catch(f){Qe.error("레이아웃 편집기 번들 로드 실패",f),gf.render(o.containerId,{title:"레이아웃 편집기 로드 실패",message:f instanceof Error?f.message:"편집기 번들을 불러오지 못했습니다.",icon:"fas fa-triangle-exclamation",showStack:!1,showReloadButton:!0,debug:Do});return}const d=We.createElement(c,{templateIdentifier:l.templateIdentifier,initialLocale:re.locale});re.reactRoot.render(We.createElement(_c,{translationEngine:re.translationEngine,translationContext:re.translationContext,children:We.createElement(Id,{children:We.createElement(uc,{children:We.createElement(cf,{children:d})})})}));return}}const a=o.layoutJson.components||[];if(a.length===0){Qe.warn("렌더링할 컴포넌트가 없습니다.");return}const i=o.layoutJson.modals||[];if(Qe.log("modals 배열:",i),Qe.log("modals 개수:",i.length),Qe.log("DynamicRenderer로 렌더링 시작"),re.reactRoot.render(We.createElement(_c,{translationEngine:re.translationEngine,translationContext:re.translationContext},We.createElement(Id,null,We.createElement(uc,null,We.createElement(cf,null,[...a.map((l,c)=>{const d=re.currentLayoutJson?.layout_name||"";return We.createElement(Br,{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(tm,{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,g=c.indexOf(l.id),m=g>=0?50+g:50,y=window.__g7LayoutContextStack||[],S=y[y.length-1]?.dataContext,v=We.createElement(Br,{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(ly,{key:`modal_${l.id}`,isOpen:f,modalId:l.id,dataSources:l.data_sources,dataContext:re.currentDataContext,globalStateUpdater:re.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:re.bindingEngine,debug:Do,children:v}):v}))]))))),Qe.log("템플릿 렌더링 완료"),Oo.length>0){Qe.log(`대기 중인 데이터 업데이트 ${Oo.length}건 적용`);const l=[...Oo];Oo.length=0;for(const{data:c,options:d}of l)ds(c,d)}}catch(e){throw Qe.error("템플릿 렌더링 실패",e),e}}function ds(o,e){try{if(Qe.log("템플릿 데이터 업데이트 시작",Object.keys(o)),!re.isInitialized)throw new Error("템플릿 엔진이 초기화되지 않았습니다.");if(!re.reactRoot||!re.currentLayoutJson){Qe.log("React 미준비 - 데이터 업데이트 큐잉:",Object.keys(o)),Oo.push({data:o,options:e});return}const r=my(),a={...re.currentDataContext._global||{},...o._global||{}},i=Y0(re.currentDataContext._localInit,o._localInit);re.currentDataContext={...r,...re.currentDataContext,...o,_global:a,_localInit:i},a._local!==void 0&&(re.currentDataContext._local=a._local),a._computed!==void 0&&(re.currentDataContext._computed=a._computed);const l=re.currentLayoutJson.components||[],c=re.currentLayoutJson.modals||[];Qe.log("updateTemplateData - modals 배열:",c),Qe.log("updateTemplateData - modals 개수:",c.length),Qe.log("updateTemplateData - activeModal:",re.currentDataContext._global?.activeModal);const d=()=>{re.reactRoot.render(We.createElement(_c,{translationEngine:re.translationEngine,translationContext:re.translationContext},We.createElement(Id,null,We.createElement(uc,null,We.createElement(cf,null,[...l.map((f,g)=>{const m=re.currentLayoutJson?.layout_name||"";return We.createElement(Br,{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:g===0,layoutKey:m})}),We.createElement(tm,{key:"__modal_parent_context_provider_update"},c.map(f=>{const g=re.currentDataContext._global?.modalStack||[],y=g.includes(f.id)||re.currentDataContext._global?.activeModal===f.id,w=g.indexOf(f.id),S=w>=0?50+w:50,v=window.__g7LayoutContextStack||[],x=v[v.length-1]?.dataContext,R=We.createElement(Br,{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:x});return f.data_sources&&f.data_sources.length>0?We.createElement(ly,{key:`modal_${f.id}`,isOpen:y,modalId:f.id,dataSources:f.data_sources,dataContext:re.currentDataContext,globalStateUpdater:re.actionDispatcher?.getGlobalStateUpdater(),bindingEngine:re.bindingEngine,debug:Do,children:R}):R}))])))))};e?.sync?(Qe.log("재렌더링 시작 (sync mode - 즉시 렌더링)"),d()):(Qe.log("재렌더링 시작 (with startTransition)"),N.startTransition(()=>{d()})),Qe.log("템플릿 데이터 업데이트 완료")}catch(r){throw Qe.error("템플릿 데이터 업데이트 실패",r),r}}function Oc(){try{Qe.log("템플릿 정리 시작"),re.reactRoot&&(Qe.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,Qe.log("템플릿 정리 완료")}catch(o){throw Qe.error("템플릿 정리 실패",o),o}}function ta(){return Object.freeze({...re})}function yy(){return re.actionDispatcher}const $o={initTemplateEngine:Lo,renderTemplate:us,updateTemplateData:ds,destroyTemplate:Oc,getState:ta};typeof window<"u"&&(window.G7Core||(window.G7Core={}),window.G7Core.TemplateEngine=$o,uA({getState:()=>({translationEngine:re.translationEngine,translationContext:re.translationContext,bindingEngine:re.bindingEngine,actionDispatcher:re.actionDispatcher,templateMetadata:re.templateMetadata}),transitionManager:zr,responsiveManager:mi,webSocketManager:Tc}),Qe.log("전역 객체 window.G7Core.TemplateEngine에 노출됨"));const Pr=Object.freeze(Object.defineProperty({__proto__:null,DataSourceManager:_r,LayoutLoader:of,TemplateApp:To,TemplateEngine:$o,default:$o,destroyTemplate:Oc,getActionDispatcher:yy,getState:ta,initTemplateApp:bf,initTemplateEngine:Lo,loadLayoutEditorBundle:vf,renderTemplate:us,updateTemplateData:ds},Symbol.toStringTag,{value:"Module"}));Wt.DataSourceManager=_r,Wt.LayoutLoader=of,Wt.TemplateApp=To,Wt.TemplateEngine=$o,Wt.default=$o,Wt.destroyTemplate=Oc,Wt.getActionDispatcher=yy,Wt.getState=ta,Wt.initTemplateApp=bf,Wt.initTemplateEngine=Lo,Wt.loadLayoutEditorBundle=vf,Wt.renderTemplate=us,Wt.updateTemplateData=ds,Object.defineProperties(Wt,{__esModule:{value:!0},[Symbol.toStringTag]:{value:"Module"}})})(this.G7Core=this.G7Core||{}); //# sourceMappingURL=template-engine.min.js.map diff --git a/resources/js/core/template-engine/ActionDispatcher.ts b/resources/js/core/template-engine/ActionDispatcher.ts index 92fe4224..bcfa340c 100644 --- a/resources/js/core/template-engine/ActionDispatcher.ts +++ b/resources/js/core/template-engine/ActionDispatcher.ts @@ -4222,6 +4222,41 @@ export class ActionDispatcher { const update = this.createNestedUpdate(path, value, currentState); const mergedState = { ...currentState, ...update }; context.setState(update); + + // engine-v1.58.2: dot notation 경로도 canonical source(_global._local)에 동기화한다. + // + // 배경: 이 분기는 context.setState(저장소 A: React localDynamicState)만 갱신하고 + // _global._local(저장소 B)은 갱신하지 않았다. 커스텀 핸들러(모듈/플러그인)가 상태를 + // 읽는 유일한 공개 통로인 G7Core.state.getLocal() 은 B 를 읽으므로, dot notation 으로 + // 기록된 값은 핸들러에게 undefined 로 보였다 (체크아웃 간편결제 선택 → PG 플러그인이 + // 선택값을 못 읽어 통합결제창이 열린 결함). target: "local" 형태는 engine-v1.50.0 에서 + // 이미 B 를 동기화하므로, 남아 있던 비대칭을 해소한다. + // + // [동기화 기준을 전체 스냅샷이 아니라 "live B + 변경 키"로 잡은 이유] + // COMPONENT path(target:"local")는 currentState(=pending ?? context.state) 전체 스냅샷을 + // B 에 통째로 넘긴다. context.state 는 클릭된 리프 컴포넌트의 부분 상태일 수 있어 + // B 의 다른 키를 잃을 수 있고(engine-v1.50.0 주석의 안전성 의존 관계), 앞선 + // 커스텀 핸들러 setLocal 결과를 stale base 로 되돌릴 수 있다(트러블슈팅 사례 24). + // 여기서는 live B 를 base 로 삼고 변경된 최상위 키만 얹으므로 두 위험이 모두 없다. + // B 를 못 읽는 환경(테스트 등 __templateApp 부재)에서만 전체 스냅샷으로 폴백한다. + // + // [__g7PendingLocalState 를 쓰지 않는 이유] + // pending 에 B 기반 전체 스냅샷을 넣으면 handleLocalSetState 의 effectivePrev 병합에서 + // React 전용 상태(DataGrid expandedRows 등)를 초기값으로 덮어쓴다(트러블슈팅 사례 22). + // setGlobalState 는 globalState 를 동기 대입하므로 pending 없이도 같은 tick 의 + // getLocal() 이 즉시 최신값을 읽는다 — 오염 경로에 진입할 이유가 없다. + // + // scope: 'parent' | 'root' 은 이 분기가 구현하지 않는 타깃이므로 동기화 대상에서 제외한다 + // (모달에서 부모 스코프를 노린 setState 가 페이지 저장소를 오염시키는 것 방지 — 사례 29). + if (this.globalStateUpdater && scope !== 'parent' && scope !== 'root') { + const canonicalLocal = (window as any).__templateApp?.getGlobalState?.()?._local; + const syncedLocal = canonicalLocal && typeof canonicalLocal === 'object' + ? { ...canonicalLocal, ...update } + : mergedState; + this.globalStateUpdater({ _local: syncedLocal }, { render: false }); + logger.log('[handleSetState] _global._local synced for dot notation (render:false):', syncedLocal); + } + if (setStateId && devTools) setTimeout(() => devTools.completeStateChange(setStateId), 0); return mergedState; } else { diff --git a/resources/js/core/template-engine/CHANGELOG.md b/resources/js/core/template-engine/CHANGELOG.md index 6ef59f49..a2047699 100644 --- a/resources/js/core/template-engine/CHANGELOG.md +++ b/resources/js/core/template-engine/CHANGELOG.md @@ -5,6 +5,20 @@ > > 형식: [Keep a Changelog](https://keepachangelog.com/ko/1.1.0/) +## [engine-v1.58.2] - 2026-08-10 + +### Fixed + +#### `target: "_local.xxx"` 로 기록한 값을 커스텀 핸들러가 읽지 못하던 문제 + +- `ActionDispatcher.ts::handleSetState` — dot notation 경로(`target: "_local.paymentMethod"`)로 기록한 값을 canonical source 인 `_global._local` 에도 동기화한다. 기존에는 `context.setState`(React `localDynamicState`)만 갱신하고 `_global._local` 은 갱신하지 않았다. 모듈·플러그인 커스텀 핸들러가 상태를 읽는 공개 통로인 `G7Core.state.getLocal()` 은 `_global._local` 을 읽으므로, dot notation 으로 기록된 값은 핸들러에게 `undefined` 로 보였다. +- 화면은 정상으로 보인다 — 선택 표시는 React 저장소만으로 그려지기 때문이다. **예외도 경고도 콘솔 출력도 없이 핸들러가 받는 값만 비어** 발견이 늦다. 실제 발현: 주문서형 결제에서 간편결제(네이버페이 등)를 고르고 결제하면 PG 플러그인이 선택값을 못 읽어 간편결제 자체창 대신 통합결제창이 열렸다. +- `target: "local"` 형태는 engine-v1.50.0 에서 이미 `_global._local` 을 동기화하고 있었다. 같은 뜻의 두 표기가 서로 다른 저장소에 쓰이던 비대칭을 해소한 것이다. +- 동기화 기준은 **현재 `_global._local` + 변경된 최상위 키**다. `target: "local"` 경로처럼 전체 스냅샷을 넘기지 않는다 — 클릭된 리프 컴포넌트의 부분 상태가 base 가 되면 `_global._local` 의 다른 키를 잃거나, 앞서 커스텀 핸들러가 `setLocal()` 로 기록한 값을 되돌릴 수 있다. +- `__g7PendingLocalState` 는 갱신하지 않는다. `_global._local` 기반 전체 스냅샷을 pending 에 넣으면 DataGrid `expandedRows` 처럼 React 에만 존재하는 상태를 초기값으로 덮어쓴다. 전역 상태 대입은 동기적이라 pending 없이도 같은 tick 의 `getLocal()` 이 최신값을 읽는다. +- `scope: "parent" | "root"` 는 dot notation 분기가 구현하지 않는 타깃이므로 동기화 대상에서 제외한다(모달에서 부모 스코프를 노린 `setState` 가 페이지 저장소를 오염시키는 것 방지). +- 저장소 영향 범위(전수 확인): `target: "_local.xxx"` 사용은 8건이며 전부 `sirsoft-basic` 체크아웃 3개 파일이다(결제수단 선택·무통장 은행 선택·환불계좌 초기화·주문 제출 플래그). TS/TSX 코드에서 이 형태로 dispatch 하는 곳과 `$parent._local.xxx` / `$root._local.xxx` 사용은 0건이다. + ## [engine-v1.58.1] - 2026-08-07 ### Fixed diff --git a/resources/js/core/template-engine/__tests__/troubleshooting-state-setstate.test.ts b/resources/js/core/template-engine/__tests__/troubleshooting-state-setstate.test.ts index 85f24c16..d7202ad0 100644 --- a/resources/js/core/template-engine/__tests__/troubleshooting-state-setstate.test.ts +++ b/resources/js/core/template-engine/__tests__/troubleshooting-state-setstate.test.ts @@ -5151,3 +5151,121 @@ describe('[사례 38] 액션을 event 로 적은 경우의 prop 이름과 $event expect(captured?.form?.content).toBeFalsy(); }); }); + +/** + * [사례 39] setState `target: "_local.xxx"` 가 canonical source(_global._local)에 반영되지 않음 + * + * 배경: 체크아웃에서 간편결제(네이버페이)를 고르고 결제하면 자체창이 아니라 통합결제창이 열렸다. + * 결제수단 선택은 `{"target": "_local.paymentMethod"}` 로 기록되는데, dot notation 분기는 + * `context.setState`(저장소 A: React localDynamicState)만 갱신하고 `_global._local`(저장소 B)은 + * 갱신하지 않았다. PG 플러그인 핸들러는 `G7Core.state.getLocal()`(저장소 B 를 읽음)로 선택값을 + * 조회하므로 undefined 를 받았고, 간편결제 지정이 통째로 누락된 채 통합결제창이 열렸다. + * + * `target: "local"` 형태는 engine-v1.50.0 에서 이미 B 를 동기화하고 있었다 — dot notation 만 + * 남겨진 비대칭이었다. + * + * @see 트러블슈팅 가이드 "setState & init_actions & dataKey" 사례 39 + */ +describe('[사례 39] dot notation setState 의 canonical source 동기화 (engine-v1.58.2)', () => { + let dispatcher: ActionDispatcher; + let globalState: Record; + let componentState: Record; + let setStateCalls: any[]; + + /** TemplateApp.setGlobalState 와 동일한 계약: 최상위 키 얕은 병합 + 동기 대입 */ + const globalStateUpdater = vi.fn((updates: any) => { + globalState = { ...globalState, ...updates }; + }); + + beforeEach(() => { + setStateCalls = []; + componentState = {}; + globalState = { _local: {} }; + + dispatcher = new ActionDispatcher({ navigate: vi.fn() }); + dispatcher.setGlobalStateUpdater(globalStateUpdater); + Logger.getInstance().setDebug(false); + + (window as any).__templateApp = { getGlobalState: () => globalState }; + (window as any).__g7PendingLocalState = undefined; + (window as any).__g7ForcedLocalFields = undefined; + }); + + afterEach(() => { + vi.clearAllMocks(); + delete (window as any).__templateApp; + (window as any).__g7PendingLocalState = undefined; + (window as any).__g7ForcedLocalFields = undefined; + }); + + const context = () => ({ + state: componentState, + setState: vi.fn((updates: any) => { + setStateCalls.push(updates); + componentState = { ...componentState, ...updates }; + }), + actionId: 'case-39', + }); + + it('결함 재현: 선택값이 _global._local 에 반영되어 getLocal() 경로로 읽힌다', async () => { + await dispatcher.executeAction( + { handler: 'setState' as const, params: { target: '_local.paymentMethod', value: 'toss_naverpay' } }, + context() + ); + + expect(globalState._local.paymentMethod).toBe('toss_naverpay'); + }); + + it('사례 13·24 핀: canonical source 의 기존 키를 하나도 잃지 않는다 (leaf partial context 에서도)', async () => { + // 커스텀 핸들러의 setLocal 등으로 이미 canonical store 에 쌓여 있는 값 + globalState._local = { orderer: { name: '관리자' }, shipping: { zipcode: '94271' }, couponId: 7 }; + // 클릭된 리프 컴포넌트의 context.state 는 페이지 _local 전체가 아니다 + componentState = { paymentMethod: 'toss_card' }; + + await dispatcher.executeAction( + { handler: 'setState' as const, params: { target: '_local.paymentMethod', value: 'toss_naverpay' } }, + context() + ); + + expect(globalState._local.paymentMethod).toBe('toss_naverpay'); + expect(globalState._local.orderer).toEqual({ name: '관리자' }); + expect(globalState._local.shipping).toEqual({ zipcode: '94271' }); + expect(globalState._local.couponId).toBe(7); + }); + + it('사례 22 핀: __g7PendingLocalState 를 건드리지 않는다 (React 전용 배열 오염 경로 차단)', async () => { + (window as any).__g7PendingLocalState = { expandedRows: [301] }; + + await dispatcher.executeAction( + { handler: 'setState' as const, params: { target: '_local.paymentMethod', value: 'toss_naverpay' } }, + context() + ); + + expect((window as any).__g7PendingLocalState).toEqual({ expandedRows: [301] }); + }); + + it('사례 29 핀: scope parent/root 는 동기화 대상이 아니다 (모달 컨텍스트 오염 방지)', async () => { + await dispatcher.executeAction( + { + handler: 'setState' as const, + params: { target: '_local.paymentMethod', scope: 'parent', value: 'toss_naverpay' }, + }, + context() + ); + + expect(globalState._local.paymentMethod).toBeUndefined(); + }); + + it('기존 동작 유지: context.setState 에는 여전히 중첩 경로 변경분만 전달된다', async () => { + componentState = { form: { title: '기존', body: '유지' } }; + + await dispatcher.executeAction( + { handler: 'setState' as const, params: { target: '_local.form.title', value: '변경' } }, + context() + ); + + expect(setStateCalls).toHaveLength(1); + expect(setStateCalls[0]).toEqual({ form: { title: '변경', body: '유지' } }); + expect(globalState._local.form).toEqual({ title: '변경', body: '유지' }); + }); +}); diff --git a/resources/views/dev-dashboard.blade.php b/resources/views/dev-dashboard.blade.php index 8e3d56c1..db029443 100644 --- a/resources/views/dev-dashboard.blade.php +++ b/resources/views/dev-dashboard.blade.php @@ -28,6 +28,59 @@ function scanExtensions($path) { return array_values($extensions); } +/** + * 디렉토리 하위 항목을 삭제합니다 (디렉토리 자체는 보존). + * + * 인스톨러 초기화에서 "설정/업로드 내용물만 비우고 디렉토리 구조는 남긴다" 는 + * 용도로 사용합니다. 디렉토리 자체를 지우면 권한/소유권이 재생성 시점의 실행 + * 계정으로 바뀌므로 컨테이너를 보존합니다. + * + * @param string $dir 대상 디렉토리 절대경로 + * @param array $keep 보존할 항목명 목록 (basename 기준, 예: ['settings', '.preserve-ownership']) + * @return array{deleted: int, failed: int, names: array} 삭제 건수 / 실패 건수 / 삭제된 항목명 + */ +function devDashboardClearDirectory(string $dir, array $keep = []): array +{ + $result = ['deleted' => 0, 'failed' => 0, 'names' => []]; + + if (!is_dir($dir)) { + return $result; + } + + $isWindows = strtoupper(substr(PHP_OS, 0, 3)) === 'WIN'; + $keep = array_merge(['.', '..', '.gitignore', '.gitkeep'], $keep); + + foreach (scandir($dir) as $item) { + if (in_array($item, $keep, true)) { + continue; + } + + $path = $dir . DIRECTORY_SEPARATOR . $item; + + if (is_dir($path)) { + $escaped = escapeshellarg($path); + if ($isWindows) { + exec("rmdir /s /q $escaped 2>nul"); + } else { + exec("rm -rf $escaped"); + } + if (is_dir($path)) { + $result['failed']++; + } else { + $result['deleted']++; + $result['names'][] = $item; + } + } elseif (@unlink($path)) { + $result['deleted']++; + $result['names'][] = $item; + } else { + $result['failed']++; + } + } + + return $result; +} + $modules = scanExtensions(base_path('modules')); $templates = scanExtensions(base_path('templates')); $plugins = scanExtensions(base_path('plugins')); @@ -366,6 +419,110 @@ if (isset($_GET['ajax_action'])) { } } + // 환경설정 파일 삭제 (코어 + 모듈 + 플러그인 + 템플릿) + $deleteSettings = isset($_GET['delete_settings']) && $_GET['delete_settings'] === '1'; + if ($deleteSettings) { + // 코어: storage/app/settings/*.json (SettingsService 의 SSoT) + $coreSettingsPath = storage_path('app/settings'); + $cleared = devDashboardClearDirectory($coreSettingsPath); + if ($cleared['deleted'] === 0 && $cleared['failed'] === 0) { + $results[] = ['name' => '코어 환경설정 (storage/app/settings)', 'status' => 'notfound']; + } else { + $results[] = [ + 'name' => "코어 환경설정 (storage/app/settings, {$cleared['deleted']}개)", + 'status' => $cleared['failed'] === 0 ? 'deleted' : 'failed' + ]; + } + + // 모듈/플러그인: storage/app/{modules,plugins}/{identifier}/settings/ + // (ModuleSettingsService / PluginSettingsService 가 StorageInterface 로 기록하는 경로) + foreach (['modules' => '모듈', 'plugins' => '플러그인'] as $storageDir => $label) { + $basePath = storage_path('app/' . $storageDir); + $clearedIds = []; + $failedIds = []; + if (is_dir($basePath)) { + foreach (array_filter(glob($basePath . '/*'), 'is_dir') as $extDir) { + $settingsDir = $extDir . DIRECTORY_SEPARATOR . 'settings'; + if (!is_dir($settingsDir)) { + continue; + } + $cleared = devDashboardClearDirectory($settingsDir); + if ($cleared['failed'] > 0) { + $failedIds[] = basename($extDir); + } elseif ($cleared['deleted'] > 0) { + $clearedIds[] = basename($extDir); + } + } + } + if (empty($clearedIds) && empty($failedIds)) { + $results[] = ['name' => "{$label} 환경설정 (storage/app/{$storageDir})", 'status' => 'notfound']; + } else { + $detail = implode(', ', array_merge($clearedIds, $failedIds)); + $results[] = [ + 'name' => "{$label} 환경설정 ({$detail})", + 'status' => empty($failedIds) ? 'deleted' : 'failed' + ]; + } + } + + // 템플릿은 파일 기반 환경설정 저장소를 갖지 않는다. + // 활성 상태/레이아웃 편집분은 DB(templates, template_layouts), 나머지는 템플릿 패키지 파일이므로 + // 각각 "DB 테이블 전체 삭제" 와 "확장 설치 디렉토리 삭제" 가 담당한다. + // 삭제 대상이 0 건인 것과 대상 자체가 없는 것은 다르므로 그 사실을 그대로 표기한다. + $results[] = [ + 'name' => '템플릿 환경설정 (파일 저장소 없음 — DB/패키지 보관)', + 'status' => 'notfound' + ]; + } + + // 첨부파일 스토리지 삭제 + $deleteAttachments = isset($_GET['delete_attachments']) && $_GET['delete_attachments'] === '1'; + if ($deleteAttachments) { + // 코어 첨부파일 디스크(config/attachment.php) + 공개 업로드 디스크 + $attachmentPaths = [ + 'storage/app/attachments' => storage_path('app/attachments'), + 'storage/app/public' => storage_path('app/public') + ]; + foreach ($attachmentPaths as $displayName => $path) { + $cleared = devDashboardClearDirectory($path); + if ($cleared['deleted'] === 0 && $cleared['failed'] === 0) { + $results[] = ['name' => $displayName, 'status' => 'notfound']; + } else { + $results[] = [ + 'name' => "{$displayName} ({$cleared['deleted']}개)", + 'status' => $cleared['failed'] === 0 ? 'deleted' : 'failed' + ]; + } + } + + // 모듈/플러그인 업로드 파일 (예: storage/app/modules/{id}/images/products) + // settings/ 와 .preserve-ownership 마커는 보존 — 환경설정 삭제 옵션과 서로 간섭하지 않도록 분리한다. + foreach (['modules' => '모듈', 'plugins' => '플러그인'] as $storageDir => $label) { + $basePath = storage_path('app/' . $storageDir); + $clearedIds = []; + $failedIds = []; + if (is_dir($basePath)) { + foreach (array_filter(glob($basePath . '/*'), 'is_dir') as $extDir) { + $cleared = devDashboardClearDirectory($extDir, ['settings', '.preserve-ownership']); + if ($cleared['failed'] > 0) { + $failedIds[] = basename($extDir); + } elseif ($cleared['deleted'] > 0) { + $clearedIds[] = basename($extDir); + } + } + } + if (empty($clearedIds) && empty($failedIds)) { + $results[] = ['name' => "{$label} 업로드 파일 (storage/app/{$storageDir})", 'status' => 'notfound']; + } else { + $detail = implode(', ', array_merge($clearedIds, $failedIds)); + $results[] = [ + 'name' => "{$label} 업로드 파일 ({$detail})", + 'status' => empty($failedIds) ? 'deleted' : 'failed' + ]; + } + } + } + echo json_encode(['success' => true, 'results' => $results]); exit; } @@ -1002,6 +1159,24 @@ if (isset($_GET['ajax_action'])) {
+
+ 환경설정 파일 삭제 + (코어, 모듈, 플러그인) + +
+
+ 첨부파일 스토리지 삭제 + (업로드 파일 전체) + +
@@ -1239,6 +1414,8 @@ if (isset($_GET['ajax_action'])) { const deleteVendor = document.getElementById('deleteVendor').checked; const deleteExtensions = document.getElementById('deleteExtensions').checked; const dropTables = document.getElementById('dropTables').checked; + const deleteSettings = document.getElementById('deleteSettings').checked; + const deleteAttachments = document.getElementById('deleteAttachments').checked; let message = '⚠️ 인스톨러 초기화\n\n'; message += '다음 항목이 삭제됩니다:\n'; message += ' • .env\n'; @@ -1255,6 +1432,17 @@ if (isset($_GET['ajax_action'])) { if (dropTables) { message += ' • DB 테이블 전체 삭제 (migrations 포함)\n'; } + if (deleteSettings) { + message += ' • storage/app/settings/ (코어 환경설정)\n'; + message += ' • storage/app/modules/*/settings/ (모듈 환경설정)\n'; + message += ' • storage/app/plugins/*/settings/ (플러그인 환경설정)\n'; + message += ' ※ 템플릿은 파일 환경설정이 없음 (DB/패키지 보관)\n'; + } + if (deleteAttachments) { + message += ' • storage/app/attachments/ (첨부파일)\n'; + message += ' • storage/app/public/ (공개 업로드 파일)\n'; + message += ' • storage/app/modules|plugins/*/ 업로드 파일 (settings 보존)\n'; + } message += '\n계속하시겠습니까?'; if (!confirm(message)) return; @@ -1266,7 +1454,7 @@ if (isset($_GET['ajax_action'])) { panel.classList.remove('hidden'); try { - const url = `${window.location.pathname}?ajax_action=reset&delete_vendor=${deleteVendor ? '1' : '0'}&delete_extensions=${deleteExtensions ? '1' : '0'}&drop_tables=${dropTables ? '1' : '0'}`; + const url = `${window.location.pathname}?ajax_action=reset&delete_vendor=${deleteVendor ? '1' : '0'}&delete_extensions=${deleteExtensions ? '1' : '0'}&drop_tables=${dropTables ? '1' : '0'}&delete_settings=${deleteSettings ? '1' : '0'}&delete_attachments=${deleteAttachments ? '1' : '0'}`; const response = await fetch(url); const data = await response.json(); diff --git a/tests/Playwright/specs/setstate-dot-path-local-store-sync.spec.ts b/tests/Playwright/specs/setstate-dot-path-local-store-sync.spec.ts new file mode 100644 index 00000000..414825dd --- /dev/null +++ b/tests/Playwright/specs/setstate-dot-path-local-store-sync.spec.ts @@ -0,0 +1,124 @@ +/** + * E2E: `setState target: "_local.xxx"` 로 기록한 값을 커스텀 핸들러가 읽을 수 있는지 (배포 번들 기준) + * + * 배경: `_local` 은 저장소가 둘이다 — React `localDynamicState`(A)와 `_global._local`(B). + * dot notation 분기는 A 만 갱신하고 B 를 갱신하지 않았다. 모듈·플러그인 커스텀 핸들러가 상태를 + * 읽는 공개 통로인 `G7Core.state.getLocal()` 은 B 를 읽으므로, dot notation 으로 기록된 값은 + * 핸들러에게 `undefined` 로 보였다. + * + * 화면은 정상으로 보인다 — 선택 표시는 A 만으로 그려지기 때문이다. 예외도 콘솔 경고도 남지 않아 + * 화면 확인만으로는 드러나지 않는다. 실제 발현: 주문서형 결제에서 간편결제(네이버페이 등)를 + * 고르고 결제하면 PG 플러그인이 선택값을 못 읽어 간편결제 자체창 대신 통합결제창이 열렸다. + * + * 단위 테스트가 소스를 잠그지만, 실제 사용자가 실행하는 것은 빌드된 번들이므로 브라우저에서 + * 배포 번들의 액션 파이프를 직접 태워 결과를 잠근다. PG 샌드박스는 필요 없다 — 잠그는 계약은 + * "dot notation 기록이 `getLocal()` 에 도달한다" 하나이고, 화면과 무관하게 성립해야 한다. + * + * @scenario setstate_dot_path_local_store_sync + * @effects dot_path_setstate_reaches_getlocal, + * dot_path_setstate_preserves_other_local_keys, + * dot_path_setstate_accumulates_across_writes + */ +import { test, expect } from '../fixtures/auth'; +import type { Page } from '@playwright/test'; + +/** 엔진이 부팅된 아무 공개 화면. dot notation 계약은 화면과 무관하게 성립해야 한다. */ +const ANY_ENGINE_PAGE = '/'; + +/** 테스트 전용 키 — 어떤 레이아웃도 쓰지 않는 이름이라 기존 상태와 충돌하지 않는다. */ +const PROBE_KEY = '__e2eDotPathProbe'; + +/** + * 템플릿 렌더가 끝날 때까지 기다린다. + * + * `G7Core.dispatch` 는 TemplateApp 부팅 **중간**에 이미 존재하지만, 액션 디스패처에 + * `setGlobalState` 가 주입되는 것은 그보다 뒤다. dispatch 가능 시점만 보고 진행하면 + * 아직 주입 전이라 canonical 저장소 동기화가 통째로 건너뛰어진다(실측으로 이 함정에 빠졌다). + * 렌더 완료를 게이트로 삼아 부팅이 끝난 뒤에 계약을 검증한다. + */ +async function waitForEngineBoot(page: Page): Promise { + await page.waitForFunction(() => typeof (window as any).G7Core?.dispatch === 'function'); + await page.locator('footer').first().waitFor({ state: 'attached', timeout: 30_000 }); + await page.waitForLoadState('networkidle'); +} + +test.describe('setState dot notation 경로의 _local 저장소 동기화', () => { + test('dot notation 으로 기록한 값이 getLocal() 로 읽힌다', async ({ page }) => { + await page.goto(ANY_ENGINE_PAGE); + await waitForEngineBoot(page); + + const result = await page.evaluate(async (key) => { + const G7Core = (window as any).G7Core; + const before = G7Core.state.getLocal()?.[key] ?? null; + + await G7Core.dispatch({ + handler: 'setState', + params: { target: `_local.${key}`, value: 'toss_naverpay' }, + }); + + return { + before, + getLocal: G7Core.state.getLocal()?.[key] ?? null, + canonical: (window as any).__templateApp?.getGlobalState?.()?._local?.[key] ?? null, + }; + }, PROBE_KEY); + + expect(result.before, '프로브 키가 이미 오염돼 있으면 이 테스트는 의미가 없다').toBeNull(); + // 결함이 있으면 여기서 null 이 나온다 — 커스텀 핸들러가 보던 그 값이다 + expect(result.getLocal).toBe('toss_naverpay'); + expect(result.canonical).toBe('toss_naverpay'); + }); + + test('동기화가 canonical 저장소의 다른 키를 지우지 않는다', async ({ page }) => { + await page.goto(ANY_ENGINE_PAGE); + await waitForEngineBoot(page); + + const result = await page.evaluate(async (key) => { + const G7Core = (window as any).G7Core; + + // 커스텀 핸들러가 setLocal 로 canonical 저장소에 먼저 기록한 상황을 만든다 + G7Core.state.setLocal({ [`${key}Keep`]: 'must-survive' }); + + await G7Core.dispatch({ + handler: 'setState', + params: { target: `_local.${key}`, value: 'toss_naverpay' }, + }); + + const canonical = (window as any).__templateApp?.getGlobalState?.()?._local ?? {}; + return { written: canonical[key] ?? null, kept: canonical[`${key}Keep`] ?? null }; + }, PROBE_KEY); + + expect(result.written).toBe('toss_naverpay'); + // 부분 상태 스냅샷으로 canonical 을 통째 교체하면 여기서 사라진다 + expect(result.kept).toBe('must-survive'); + }); + + test('연속 기록이 서로를 지우지 않고 누적된다', async ({ page }) => { + await page.goto(ANY_ENGINE_PAGE); + await waitForEngineBoot(page); + + const canonical = await page.evaluate(async (key) => { + const G7Core = (window as any).G7Core; + + // 결제수단을 골랐다가 다른 것으로 바꾸는 흐름 — 마지막 값이 남고 동반 키는 유지돼야 한다 + await G7Core.dispatch({ + handler: 'setState', + params: { target: `_local.${key}`, value: 'toss_tosspay' }, + }); + await G7Core.dispatch({ + handler: 'setState', + params: { target: `_local.${key}Sibling`, value: 'sibling-value' }, + }); + await G7Core.dispatch({ + handler: 'setState', + params: { target: `_local.${key}`, value: 'toss_naverpay' }, + }); + + const local = (window as any).__templateApp?.getGlobalState?.()?._local ?? {}; + return { last: local[key] ?? null, sibling: local[`${key}Sibling`] ?? null }; + }, PROBE_KEY); + + expect(canonical.last).toBe('toss_naverpay'); + expect(canonical.sibling).toBe('sibling-value'); + }); +});