From a68e4c6b80a3d06e566a85da811864e3e2483021 Mon Sep 17 00:00:00 2001 From: Sergey Matyunin Date: Tue, 15 Sep 2026 10:10:51 +0300 Subject: [PATCH] =?UTF-8?q?fix:=20=D0=BE=D0=B3=D1=80=D0=B0=D0=BD=D0=B8?= =?UTF-8?q?=D1=87=D0=B8=D1=82=D1=8C=20=D0=B4=D0=BD=D0=B5=D0=B2=D0=BD=D0=BE?= =?UTF-8?q?=D0=B9=20=D0=BA=D0=BE=D0=BD=D1=82=D1=83=D1=80=20=D1=80=D0=B0?= =?UTF-8?q?=D0=B7=D0=BC=D0=B5=D1=80=D0=BE=D0=BC=20=D1=8D=D0=BA=D1=80=D0=B0?= =?UTF-8?q?=D0=BD=D0=B0=20(#582)?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Issue: #582 User-Visible: yes --- .../houseplan/frontend/houseplan-assets.json | 262 ++-- ...-ClLjW_UW.js => backdrop-pick-Bcqm2p5p.js} | 12 +- .../{de-BrzcYO-1.js => de-OKLqCJOe.js} | 2 +- .../houseplan-assets/editor-Bi3cJ768.js | 10 +- .../frontend/houseplan-assets/fr-BjvleGPe.js | 2 +- ... furniture-plan-art.generated-C_Z1hwSa.js} | 2 +- .../houseplan-card-BvxqYw8A.js | 1097 ---------------- .../houseplan-card-Cythr3Rg.js | 1112 +++++++++++++++++ ...s => houseplan-editor-runtime-CCYvnxhV.js} | 6 +- .../houseplan-onboarding-runtime-BNfzBq5J.js | 60 +- ...=> hp-zigbee-topology-overlay-Bt3_AzlX.js} | 12 +- .../iso-scene-render-RpNlnxJ0.js | 2 +- ...s => live-interaction-runtime-C8mBGPZT.js} | 2 +- ...ort-DeQrvN1z.js => pdf-export-CfU6W3j-.js} | 4 +- .../summary-panel-editor-CTfI9Enr.js | 2 +- .../summary-panel-metrics-CzgAvzH6.js | 1 - .../summary-panel-metrics-XatK0mU4.js | 1 + .../summary-panel-runtime-loaded-BbGQ8VLD.js | 4 +- .../zigbee-topology-CWUjtXoY.js | 2 +- ...js => zigbee-topology-runtime-DvLAh834.js} | 2 +- .../houseplan/frontend/houseplan-card.js | 2 +- .../houseplan/frontend/houseplan-panel.js | 2 +- demo/smoke_bg_color.mjs | 3 +- demo/smoke_daycycle_layer_budget.mjs | 236 ++++ demo/smoke_daycycle_raster.mjs | 26 +- dist/houseplan-assets.json | 262 ++-- ...-ClLjW_UW.js => backdrop-pick-Bcqm2p5p.js} | 12 +- .../{de-BrzcYO-1.js => de-OKLqCJOe.js} | 2 +- .../houseplan-assets/editor-Bi3cJ768.js | 10 +- .../houseplan-assets/fr-BjvleGPe.js | 2 +- ... furniture-plan-art.generated-C_Z1hwSa.js} | 2 +- .../houseplan-card-BvxqYw8A.js | 1097 ---------------- .../houseplan-card-Cythr3Rg.js | 1112 +++++++++++++++++ ...s => houseplan-editor-runtime-CCYvnxhV.js} | 6 +- .../houseplan-onboarding-runtime-BNfzBq5J.js | 60 +- ...=> hp-zigbee-topology-overlay-Bt3_AzlX.js} | 12 +- .../iso-scene-render-RpNlnxJ0.js | 2 +- ...s => live-interaction-runtime-C8mBGPZT.js} | 2 +- ...ort-DeQrvN1z.js => pdf-export-CfU6W3j-.js} | 4 +- .../summary-panel-editor-CTfI9Enr.js | 2 +- .../summary-panel-metrics-CzgAvzH6.js | 1 - .../summary-panel-metrics-XatK0mU4.js | 1 + .../summary-panel-runtime-loaded-BbGQ8VLD.js | 4 +- .../zigbee-topology-CWUjtXoY.js | 2 +- ...js => zigbee-topology-runtime-DvLAh834.js} | 2 +- dist/houseplan-card.js | 2 +- dist/houseplan-panel.js | 2 +- docs/ARCHITECTURE.md | 17 +- docs/CHANGELOG.md | 7 + docs/CHANGELOG.ru.md | 8 + docs/SUN.md | 17 +- docs/TESTING.md | 7 + docs/TOUCH-SUPPORT.md | 4 + scripts/mutation-registry.mjs | 14 + scripts/smoke-links.mjs | 10 + src/houseplan-card.ts | 26 +- src/render/paper-scene.ts | 22 + src/space-card.ts | 5 + src/space-render.ts | 18 +- src/styles/plan.styles.ts | 25 +- test/isometric-contract.test.mjs | 2 +- test/paper-scene-contract.test.mjs | 33 + 62 files changed, 3040 insertions(+), 2642 deletions(-) rename custom_components/houseplan/frontend/houseplan-assets/{backdrop-pick-ClLjW_UW.js => backdrop-pick-Bcqm2p5p.js} (93%) rename custom_components/houseplan/frontend/houseplan-assets/{de-BrzcYO-1.js => de-OKLqCJOe.js} (99%) rename dist/houseplan-assets/editor-Cfrg3iMq.js => custom_components/houseplan/frontend/houseplan-assets/editor-Bi3cJ768.js (86%) rename dist/houseplan-assets/fr-CLHfUBDP.js => custom_components/houseplan/frontend/houseplan-assets/fr-BjvleGPe.js (99%) rename custom_components/houseplan/frontend/houseplan-assets/{furniture-plan-art.generated-7nJsC48X.js => furniture-plan-art.generated-C_Z1hwSa.js} (99%) delete mode 100644 custom_components/houseplan/frontend/houseplan-assets/houseplan-card-BvxqYw8A.js create mode 100644 custom_components/houseplan/frontend/houseplan-assets/houseplan-card-Cythr3Rg.js rename custom_components/houseplan/frontend/houseplan-assets/{houseplan-editor-runtime-Pkk2XGqR.js => houseplan-editor-runtime-CCYvnxhV.js} (99%) rename dist/houseplan-assets/houseplan-onboarding-runtime-BhJG-ch3.js => custom_components/houseplan/frontend/houseplan-assets/houseplan-onboarding-runtime-BNfzBq5J.js (82%) rename custom_components/houseplan/frontend/houseplan-assets/{hp-zigbee-topology-overlay-jvjkBbI9.js => hp-zigbee-topology-overlay-Bt3_AzlX.js} (86%) rename dist/houseplan-assets/iso-scene-render-D2f0EUgN.js => custom_components/houseplan/frontend/houseplan-assets/iso-scene-render-RpNlnxJ0.js (99%) rename custom_components/houseplan/frontend/houseplan-assets/{live-interaction-runtime-BA69oN1Z.js => live-interaction-runtime-C8mBGPZT.js} (75%) rename custom_components/houseplan/frontend/houseplan-assets/{pdf-export-DeQrvN1z.js => pdf-export-CfU6W3j-.js} (99%) rename dist/houseplan-assets/summary-panel-editor-o2bn2wLY.js => custom_components/houseplan/frontend/houseplan-assets/summary-panel-editor-CTfI9Enr.js (97%) delete mode 100644 custom_components/houseplan/frontend/houseplan-assets/summary-panel-metrics-CzgAvzH6.js create mode 100644 custom_components/houseplan/frontend/houseplan-assets/summary-panel-metrics-XatK0mU4.js rename dist/houseplan-assets/summary-panel-runtime-loaded-B6w0YS6P.js => custom_components/houseplan/frontend/houseplan-assets/summary-panel-runtime-loaded-BbGQ8VLD.js (97%) rename dist/houseplan-assets/zigbee-topology-B8St6NV9.js => custom_components/houseplan/frontend/houseplan-assets/zigbee-topology-CWUjtXoY.js (95%) rename custom_components/houseplan/frontend/houseplan-assets/{zigbee-topology-runtime-BkrLGjiL.js => zigbee-topology-runtime-DvLAh834.js} (93%) create mode 100644 demo/smoke_daycycle_layer_budget.mjs rename dist/houseplan-assets/{backdrop-pick-ClLjW_UW.js => backdrop-pick-Bcqm2p5p.js} (93%) rename dist/houseplan-assets/{de-BrzcYO-1.js => de-OKLqCJOe.js} (99%) rename custom_components/houseplan/frontend/houseplan-assets/editor-Cfrg3iMq.js => dist/houseplan-assets/editor-Bi3cJ768.js (86%) rename custom_components/houseplan/frontend/houseplan-assets/fr-CLHfUBDP.js => dist/houseplan-assets/fr-BjvleGPe.js (99%) rename dist/houseplan-assets/{furniture-plan-art.generated-7nJsC48X.js => furniture-plan-art.generated-C_Z1hwSa.js} (99%) delete mode 100644 dist/houseplan-assets/houseplan-card-BvxqYw8A.js create mode 100644 dist/houseplan-assets/houseplan-card-Cythr3Rg.js rename dist/houseplan-assets/{houseplan-editor-runtime-Pkk2XGqR.js => houseplan-editor-runtime-CCYvnxhV.js} (99%) rename custom_components/houseplan/frontend/houseplan-assets/houseplan-onboarding-runtime-BhJG-ch3.js => dist/houseplan-assets/houseplan-onboarding-runtime-BNfzBq5J.js (82%) rename dist/houseplan-assets/{hp-zigbee-topology-overlay-jvjkBbI9.js => hp-zigbee-topology-overlay-Bt3_AzlX.js} (86%) rename custom_components/houseplan/frontend/houseplan-assets/iso-scene-render-D2f0EUgN.js => dist/houseplan-assets/iso-scene-render-RpNlnxJ0.js (99%) rename dist/houseplan-assets/{live-interaction-runtime-BA69oN1Z.js => live-interaction-runtime-C8mBGPZT.js} (75%) rename dist/houseplan-assets/{pdf-export-DeQrvN1z.js => pdf-export-CfU6W3j-.js} (99%) rename custom_components/houseplan/frontend/houseplan-assets/summary-panel-editor-o2bn2wLY.js => dist/houseplan-assets/summary-panel-editor-CTfI9Enr.js (97%) delete mode 100644 dist/houseplan-assets/summary-panel-metrics-CzgAvzH6.js create mode 100644 dist/houseplan-assets/summary-panel-metrics-XatK0mU4.js rename custom_components/houseplan/frontend/houseplan-assets/summary-panel-runtime-loaded-B6w0YS6P.js => dist/houseplan-assets/summary-panel-runtime-loaded-BbGQ8VLD.js (97%) rename custom_components/houseplan/frontend/houseplan-assets/zigbee-topology-B8St6NV9.js => dist/houseplan-assets/zigbee-topology-CWUjtXoY.js (95%) rename dist/houseplan-assets/{zigbee-topology-runtime-BkrLGjiL.js => zigbee-topology-runtime-DvLAh834.js} (93%) create mode 100644 src/render/paper-scene.ts create mode 100644 test/paper-scene-contract.test.mjs diff --git a/custom_components/houseplan/frontend/houseplan-assets.json b/custom_components/houseplan/frontend/houseplan-assets.json index 47e8ed63..3d9f0d29 100644 --- a/custom_components/houseplan/frontend/houseplan-assets.json +++ b/custom_components/houseplan/frontend/houseplan-assets.json @@ -1,295 +1,295 @@ { "schema": 1, - "fingerprint": "241ab786b7cce5c1f837e73704240f138bd3e097bfecdbb0e93046bf4a19d3ef", + "fingerprint": "3f783ed7cf5daff202a910aa89044f88f605a65af7f46794277dddf04333e502", "entry": "houseplan-card.js", "panelEntry": "houseplan-panel.js", "initialViewFiles": [ - "houseplan-assets/houseplan-card-BvxqYw8A.js", + "houseplan-assets/houseplan-card-Cythr3Rg.js", "houseplan-card.js" ], - "initialViewGzipBytes": 290805, + "initialViewGzipBytes": 290977, "initialPanelFiles": [ - "houseplan-assets/houseplan-card-BvxqYw8A.js", + "houseplan-assets/houseplan-card-Cythr3Rg.js", "houseplan-panel.js" ], - "initialPanelGzipBytes": 292327, + "initialPanelGzipBytes": 292500, "initialPanelOnlyFiles": [ "houseplan-panel.js" ], - "initialPanelOnlyGzipBytes": 2326, + "initialPanelOnlyGzipBytes": 2325, "lazyFiles": [ - "houseplan-assets/backdrop-pick-ClLjW_UW.js", - "houseplan-assets/de-BrzcYO-1.js", - "houseplan-assets/editor-Cfrg3iMq.js", - "houseplan-assets/fr-CLHfUBDP.js", - "houseplan-assets/furniture-plan-art.generated-7nJsC48X.js", - "houseplan-assets/houseplan-editor-runtime-Pkk2XGqR.js", - "houseplan-assets/houseplan-onboarding-runtime-BhJG-ch3.js", - "houseplan-assets/hp-zigbee-topology-overlay-jvjkBbI9.js", - "houseplan-assets/iso-scene-render-D2f0EUgN.js", - "houseplan-assets/live-interaction-runtime-BA69oN1Z.js", - "houseplan-assets/pdf-export-DeQrvN1z.js", - "houseplan-assets/summary-panel-runtime-loaded-B6w0YS6P.js", - "houseplan-assets/zigbee-topology-B8St6NV9.js", - "houseplan-assets/zigbee-topology-runtime-BkrLGjiL.js" + "houseplan-assets/backdrop-pick-Bcqm2p5p.js", + "houseplan-assets/de-OKLqCJOe.js", + "houseplan-assets/editor-Bi3cJ768.js", + "houseplan-assets/fr-BjvleGPe.js", + "houseplan-assets/furniture-plan-art.generated-C_Z1hwSa.js", + "houseplan-assets/houseplan-editor-runtime-CCYvnxhV.js", + "houseplan-assets/houseplan-onboarding-runtime-BNfzBq5J.js", + "houseplan-assets/hp-zigbee-topology-overlay-Bt3_AzlX.js", + "houseplan-assets/iso-scene-render-RpNlnxJ0.js", + "houseplan-assets/live-interaction-runtime-C8mBGPZT.js", + "houseplan-assets/pdf-export-CfU6W3j-.js", + "houseplan-assets/summary-panel-runtime-loaded-BbGQ8VLD.js", + "houseplan-assets/zigbee-topology-CWUjtXoY.js", + "houseplan-assets/zigbee-topology-runtime-DvLAh834.js" ], - "lazyGzipBytes": 418772, + "lazyGzipBytes": 418768, "lazyEditorFiles": [ - "houseplan-assets/backdrop-pick-ClLjW_UW.js", - "houseplan-assets/editor-Cfrg3iMq.js", - "houseplan-assets/furniture-plan-art.generated-7nJsC48X.js", - "houseplan-assets/houseplan-editor-runtime-Pkk2XGqR.js", - "houseplan-assets/zigbee-topology-B8St6NV9.js" + "houseplan-assets/backdrop-pick-Bcqm2p5p.js", + "houseplan-assets/editor-Bi3cJ768.js", + "houseplan-assets/furniture-plan-art.generated-C_Z1hwSa.js", + "houseplan-assets/houseplan-editor-runtime-CCYvnxhV.js", + "houseplan-assets/zigbee-topology-CWUjtXoY.js" ], - "lazyEditorGzipBytes": 204963, + "lazyEditorGzipBytes": 204957, "lazyOnboardingFiles": [ - "houseplan-assets/backdrop-pick-ClLjW_UW.js", - "houseplan-assets/houseplan-onboarding-runtime-BhJG-ch3.js" + "houseplan-assets/backdrop-pick-Bcqm2p5p.js", + "houseplan-assets/houseplan-onboarding-runtime-BNfzBq5J.js" ], - "lazyOnboardingGzipBytes": 13916, + "lazyOnboardingGzipBytes": 13913, "lazyLocaleFiles": [ - "houseplan-assets/de-BrzcYO-1.js", - "houseplan-assets/fr-CLHfUBDP.js" + "houseplan-assets/de-OKLqCJOe.js", + "houseplan-assets/fr-BjvleGPe.js" ], - "lazyLocaleGzipBytes": 54921, + "lazyLocaleGzipBytes": 54928, "lazyIsometricFiles": [ - "houseplan-assets/iso-scene-render-D2f0EUgN.js" + "houseplan-assets/iso-scene-render-RpNlnxJ0.js" ], - "lazyIsometricGzipBytes": 13234, + "lazyIsometricGzipBytes": 13233, "lazyFurnitureArtFiles": [ - "houseplan-assets/furniture-plan-art.generated-7nJsC48X.js" + "houseplan-assets/furniture-plan-art.generated-C_Z1hwSa.js" ], - "lazyFurnitureArtGzipBytes": 10255, + "lazyFurnitureArtGzipBytes": 10253, "lazyPdfFiles": [ - "houseplan-assets/furniture-plan-art.generated-7nJsC48X.js", - "houseplan-assets/pdf-export-DeQrvN1z.js" + "houseplan-assets/furniture-plan-art.generated-C_Z1hwSa.js", + "houseplan-assets/pdf-export-CfU6W3j-.js" ], - "lazyPdfGzipBytes": 120128, + "lazyPdfGzipBytes": 120126, "files": [ { - "path": "houseplan-assets/backdrop-pick-ClLjW_UW.js", - "sha256": "5c8e9728df6ebdaad6346a26686f058ba4cce8bebd68c01d6cf18423ac67b792", + "path": "houseplan-assets/backdrop-pick-Bcqm2p5p.js", + "sha256": "75bbf10c2e346eb00aff21123bdfc9c753efcb5a81fdb1de8735232110ad3b4b", "rawBytes": 19956, - "gzipBytes": 6880, + "gzipBytes": 6879, "isEntry": false, "imports": [ - "houseplan-assets/houseplan-card-BvxqYw8A.js" + "houseplan-assets/houseplan-card-Cythr3Rg.js" ], "dynamicImports": [] }, { - "path": "houseplan-assets/de-BrzcYO-1.js", - "sha256": "b7488c7f186f740f02cdfde3c093aed8754e91157c0903d196a36fee4fbfef60", + "path": "houseplan-assets/de-OKLqCJOe.js", + "sha256": "c2374e47db6377fdebc46f33e501bca8c75c83a34040dc32cbdfd0d77aa970f5", "rawBytes": 91590, - "gzipBytes": 27743, + "gzipBytes": 27746, "isEntry": false, "imports": [], "dynamicImports": [] }, { - "path": "houseplan-assets/editor-Cfrg3iMq.js", - "sha256": "83f9d762289e0f83a6e78730d3eb54862dbfa78408c93d410126f15988ca758c", + "path": "houseplan-assets/editor-Bi3cJ768.js", + "sha256": "856625d7c4609d8461a0a1f864c12cfe7929003add4d900affc09293d2a55ca3", "rawBytes": 3831, - "gzipBytes": 1584, + "gzipBytes": 1582, "isEntry": false, "imports": [ - "houseplan-assets/houseplan-card-BvxqYw8A.js" + "houseplan-assets/houseplan-card-Cythr3Rg.js" ], "dynamicImports": [] }, { - "path": "houseplan-assets/fr-CLHfUBDP.js", - "sha256": "3524222b350ecbe2187351bf1730cc1d6393497104b10478cc3b7b0e5f14a9ec", + "path": "houseplan-assets/fr-BjvleGPe.js", + "sha256": "ab49a526636631678544da34495d55aa2ca181a9e89e3df4933cd4100aecdf59", "rawBytes": 93884, - "gzipBytes": 27178, + "gzipBytes": 27182, "isEntry": false, "imports": [], "dynamicImports": [] }, { - "path": "houseplan-assets/furniture-plan-art.generated-7nJsC48X.js", - "sha256": "8303521f70c98617ece5cea54517760fdb808bec3fc7b68add0434ea56980dd3", + "path": "houseplan-assets/furniture-plan-art.generated-C_Z1hwSa.js", + "sha256": "c7f2275e7fe40520b80e2bf8cf1f41677382ccfdbf49c069cf8d794c866bc44a", "rawBytes": 33655, - "gzipBytes": 10255, + "gzipBytes": 10253, "isEntry": false, "imports": [], "dynamicImports": [] }, { - "path": "houseplan-assets/houseplan-card-BvxqYw8A.js", - "sha256": "da77e0c3d6445d114ff496613fc8aebfb7e7ed132bdfbc5c2bc8c5a79fd8afc2", - "rawBytes": 1032746, - "gzipBytes": 290001, + "path": "houseplan-assets/houseplan-card-Cythr3Rg.js", + "sha256": "87cc46dbb29e86af1732f00d74fecf5050295c7812b429b247ecac649abdd67a", + "rawBytes": 1033369, + "gzipBytes": 290175, "isEntry": false, "imports": [], "dynamicImports": [ - "houseplan-assets/de-BrzcYO-1.js", - "houseplan-assets/editor-Cfrg3iMq.js", - "houseplan-assets/fr-CLHfUBDP.js", - "houseplan-assets/furniture-plan-art.generated-7nJsC48X.js", - "houseplan-assets/houseplan-editor-runtime-Pkk2XGqR.js", - "houseplan-assets/houseplan-onboarding-runtime-BhJG-ch3.js", - "houseplan-assets/hp-zigbee-topology-overlay-jvjkBbI9.js", - "houseplan-assets/iso-scene-render-D2f0EUgN.js", - "houseplan-assets/live-interaction-runtime-BA69oN1Z.js", - "houseplan-assets/pdf-export-DeQrvN1z.js", - "houseplan-assets/summary-panel-runtime-loaded-B6w0YS6P.js" + "houseplan-assets/de-OKLqCJOe.js", + "houseplan-assets/editor-Bi3cJ768.js", + "houseplan-assets/fr-BjvleGPe.js", + "houseplan-assets/furniture-plan-art.generated-C_Z1hwSa.js", + "houseplan-assets/houseplan-editor-runtime-CCYvnxhV.js", + "houseplan-assets/houseplan-onboarding-runtime-BNfzBq5J.js", + "houseplan-assets/hp-zigbee-topology-overlay-Bt3_AzlX.js", + "houseplan-assets/iso-scene-render-RpNlnxJ0.js", + "houseplan-assets/live-interaction-runtime-C8mBGPZT.js", + "houseplan-assets/pdf-export-CfU6W3j-.js", + "houseplan-assets/summary-panel-runtime-loaded-BbGQ8VLD.js" ] }, { - "path": "houseplan-assets/houseplan-editor-runtime-Pkk2XGqR.js", - "sha256": "0d095de08b11966dd3cb784099bba2f92d8c294f0817a49f3e3d4813ca9baa0b", + "path": "houseplan-assets/houseplan-editor-runtime-CCYvnxhV.js", + "sha256": "440f16ed41a7b01b15fc253209be5cb6242f4c48dec1646b07bf5e7304d3f3c4", "rawBytes": 670150, - "gzipBytes": 178818, + "gzipBytes": 178815, "isEntry": false, "imports": [ - "houseplan-assets/backdrop-pick-ClLjW_UW.js", - "houseplan-assets/furniture-plan-art.generated-7nJsC48X.js", - "houseplan-assets/houseplan-card-BvxqYw8A.js", - "houseplan-assets/zigbee-topology-B8St6NV9.js" + "houseplan-assets/backdrop-pick-Bcqm2p5p.js", + "houseplan-assets/furniture-plan-art.generated-C_Z1hwSa.js", + "houseplan-assets/houseplan-card-Cythr3Rg.js", + "houseplan-assets/zigbee-topology-CWUjtXoY.js" ], "dynamicImports": [ - "houseplan-assets/zigbee-topology-runtime-BkrLGjiL.js" + "houseplan-assets/zigbee-topology-runtime-DvLAh834.js" ] }, { - "path": "houseplan-assets/houseplan-onboarding-runtime-BhJG-ch3.js", - "sha256": "66ec3c0650ce721de901ec5d8d175c3b76e4878da909dada0d92589b3c8da4b5", + "path": "houseplan-assets/houseplan-onboarding-runtime-BNfzBq5J.js", + "sha256": "ca88d8512e071d73ced67a1eccbd13a9c63ff776589d963db173d1b6ca8aded5", "rawBytes": 28287, - "gzipBytes": 7036, + "gzipBytes": 7034, "isEntry": false, "imports": [ - "houseplan-assets/backdrop-pick-ClLjW_UW.js", - "houseplan-assets/houseplan-card-BvxqYw8A.js" + "houseplan-assets/backdrop-pick-Bcqm2p5p.js", + "houseplan-assets/houseplan-card-Cythr3Rg.js" ], "dynamicImports": [] }, { - "path": "houseplan-assets/hp-zigbee-topology-overlay-jvjkBbI9.js", - "sha256": "d4b6c957d4a82b979f7a71832e583fbd93852f7f8c340ce7a32fb8f773a59bc5", + "path": "houseplan-assets/hp-zigbee-topology-overlay-Bt3_AzlX.js", + "sha256": "14a73aa0d44c2d5c0ad2198dc25a2180515d6920898f3d34643f2bafe06d8158", "rawBytes": 10756, - "gzipBytes": 3685, + "gzipBytes": 3686, "isEntry": false, "imports": [ - "houseplan-assets/houseplan-card-BvxqYw8A.js", - "houseplan-assets/zigbee-topology-B8St6NV9.js", - "houseplan-assets/zigbee-topology-runtime-BkrLGjiL.js" + "houseplan-assets/houseplan-card-Cythr3Rg.js", + "houseplan-assets/zigbee-topology-CWUjtXoY.js", + "houseplan-assets/zigbee-topology-runtime-DvLAh834.js" ], "dynamicImports": [] }, { - "path": "houseplan-assets/iso-scene-render-D2f0EUgN.js", - "sha256": "92b77a114af62667adceacab9ecb76b631afb2ac83d9e255af206678f79cac47", + "path": "houseplan-assets/iso-scene-render-RpNlnxJ0.js", + "sha256": "95c96d30a226573c9131a94334aef2ca12a5f58a8f6ce5ff258cf0ec47fbee23", "rawBytes": 39206, - "gzipBytes": 13234, + "gzipBytes": 13233, "isEntry": false, "imports": [ - "houseplan-assets/houseplan-card-BvxqYw8A.js" + "houseplan-assets/houseplan-card-Cythr3Rg.js" ], "dynamicImports": [] }, { - "path": "houseplan-assets/live-interaction-runtime-BA69oN1Z.js", - "sha256": "1e3130110cdb4af9dfe938444d9b8a88ef4f6c30502841f5785231894e1ed7a6", + "path": "houseplan-assets/live-interaction-runtime-C8mBGPZT.js", + "sha256": "6df6de94c668490716339ae897412d6e794d0f753584ae3d34f98f43349bc7d8", "rawBytes": 8216, "gzipBytes": 3207, "isEntry": false, "imports": [ - "houseplan-assets/houseplan-card-BvxqYw8A.js" + "houseplan-assets/houseplan-card-Cythr3Rg.js" ], "dynamicImports": [] }, { - "path": "houseplan-assets/pdf-export-DeQrvN1z.js", - "sha256": "11a305cbbb3772c55968cbcb502c1878e4e74522c5179e1ee281e80fb85d6f93", + "path": "houseplan-assets/pdf-export-CfU6W3j-.js", + "sha256": "28eb5327001bebfddbdf01086a7a851bbc7c04e4b7030e3b413b8dfb0a73eb3e", "rawBytes": 236244, "gzipBytes": 109873, "isEntry": false, "imports": [ - "houseplan-assets/furniture-plan-art.generated-7nJsC48X.js", - "houseplan-assets/houseplan-card-BvxqYw8A.js" + "houseplan-assets/furniture-plan-art.generated-C_Z1hwSa.js", + "houseplan-assets/houseplan-card-Cythr3Rg.js" ], "dynamicImports": [] }, { - "path": "houseplan-assets/summary-panel-editor-o2bn2wLY.js", - "sha256": "c253cfec20c5cef0a472b4dd42caca4276d147e48ea795f9d1b562c4a39da46e", + "path": "houseplan-assets/summary-panel-editor-CTfI9Enr.js", + "sha256": "559732b375119e7169332d1a93f7778382eb3f97a9bb0150eb2fe600448f1286", "rawBytes": 14824, "gzipBytes": 3401, "isEntry": false, "imports": [ - "houseplan-assets/houseplan-card-BvxqYw8A.js", - "houseplan-assets/summary-panel-runtime-loaded-B6w0YS6P.js" + "houseplan-assets/houseplan-card-Cythr3Rg.js", + "houseplan-assets/summary-panel-runtime-loaded-BbGQ8VLD.js" ], "dynamicImports": [] }, { - "path": "houseplan-assets/summary-panel-metrics-CzgAvzH6.js", - "sha256": "51530c69ada90dc42a92f5e297366734969c1a91c58ae30b9ecd528978a5441e", + "path": "houseplan-assets/summary-panel-metrics-XatK0mU4.js", + "sha256": "d627d8bb01b003f47f9fbb0594c2526a8d8676d491595612239d2c8ee0e5bffe", "rawBytes": 2610, - "gzipBytes": 1305, + "gzipBytes": 1306, "isEntry": false, "imports": [ - "houseplan-assets/houseplan-card-BvxqYw8A.js" + "houseplan-assets/houseplan-card-Cythr3Rg.js" ], "dynamicImports": [] }, { - "path": "houseplan-assets/summary-panel-runtime-loaded-B6w0YS6P.js", - "sha256": "fa463fbec81b0635b56be87906d24442eba48ed1047445e192b5eb3ec519b7c1", + "path": "houseplan-assets/summary-panel-runtime-loaded-BbGQ8VLD.js", + "sha256": "545cb01893ff659bcbe0fb14cd32c5656481f317a90053b25e1ff1cff2773096", "rawBytes": 73366, - "gzipBytes": 20089, + "gzipBytes": 20087, "isEntry": false, "imports": [ - "houseplan-assets/houseplan-card-BvxqYw8A.js" + "houseplan-assets/houseplan-card-Cythr3Rg.js" ], "dynamicImports": [ - "houseplan-assets/summary-panel-editor-o2bn2wLY.js", - "houseplan-assets/summary-panel-metrics-CzgAvzH6.js" + "houseplan-assets/summary-panel-editor-CTfI9Enr.js", + "houseplan-assets/summary-panel-metrics-XatK0mU4.js" ] }, { - "path": "houseplan-assets/zigbee-topology-B8St6NV9.js", - "sha256": "d35d5ebeedb562a4c29709da95964080f053e4e1eb0d3f2fb7eb957b71444e9c", + "path": "houseplan-assets/zigbee-topology-CWUjtXoY.js", + "sha256": "89766dbc5817dc1889e7c30a8ad36817d2c675760c9cb82f9de2adacafb9c06c", "rawBytes": 18961, - "gzipBytes": 7426, + "gzipBytes": 7428, "isEntry": false, "imports": [ - "houseplan-assets/houseplan-card-BvxqYw8A.js" + "houseplan-assets/houseplan-card-Cythr3Rg.js" ], "dynamicImports": [] }, { - "path": "houseplan-assets/zigbee-topology-runtime-BkrLGjiL.js", - "sha256": "a7774967077014e62b395dacb43dc7eb10022b03b6ac24a358ce53eee4469786", + "path": "houseplan-assets/zigbee-topology-runtime-DvLAh834.js", + "sha256": "f3a64d38e8eb5ab5983340354db8dce98db8c7b11c903699cd7cbee7a8ff3f66", "rawBytes": 3941, - "gzipBytes": 1764, + "gzipBytes": 1763, "isEntry": false, "imports": [ - "houseplan-assets/houseplan-card-BvxqYw8A.js", - "houseplan-assets/zigbee-topology-B8St6NV9.js" + "houseplan-assets/houseplan-card-Cythr3Rg.js", + "houseplan-assets/zigbee-topology-CWUjtXoY.js" ], "dynamicImports": [] }, { "path": "houseplan-card.js", - "sha256": "79b31c6683afff9ca22fb99a7a855f81957a199352f0f212807444b2998ee7d1", + "sha256": "42e5ccc368c0b72a931ec124f88711c5551e3a202dbf525cb96348f0c6aec03e", "rawBytes": 1205, - "gzipBytes": 804, + "gzipBytes": 802, "isEntry": true, "imports": [ - "houseplan-assets/houseplan-card-BvxqYw8A.js" + "houseplan-assets/houseplan-card-Cythr3Rg.js" ], "dynamicImports": [] }, { "path": "houseplan-panel.js", - "sha256": "4240e1335652c727ecf9a8868b515945f8c97b50cff332708ac302b9c0ccf6b4", + "sha256": "7e2756dab8b6fecee15843885756abc8a2bed9e49caa10fee0c393a4cd10ee1b", "rawBytes": 6165, - "gzipBytes": 2326, + "gzipBytes": 2325, "isEntry": true, "imports": [ - "houseplan-assets/houseplan-card-BvxqYw8A.js" + "houseplan-assets/houseplan-card-Cythr3Rg.js" ], "dynamicImports": [] } diff --git a/custom_components/houseplan/frontend/houseplan-assets/backdrop-pick-ClLjW_UW.js b/custom_components/houseplan/frontend/houseplan-assets/backdrop-pick-Bcqm2p5p.js similarity index 93% rename from custom_components/houseplan/frontend/houseplan-assets/backdrop-pick-ClLjW_UW.js rename to custom_components/houseplan/frontend/houseplan-assets/backdrop-pick-Bcqm2p5p.js index 30b20656..d261b601 100644 --- a/custom_components/houseplan/frontend/houseplan-assets/backdrop-pick-ClLjW_UW.js +++ b/custom_components/houseplan/frontend/houseplan-assets/backdrop-pick-Bcqm2p5p.js @@ -1,6 +1,6 @@ -globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="241ab786b7cce5c1f837e73704240f138bd3e097bfecdbb0e93046bf4a19d3ef";import{D as e,c as t,A as i,p as o,q as n,dE as r}from"./houseplan-card-BvxqYw8A.js";function s(e){const t=e.visualViewport;return t&&Number.isFinite(t.width)&&Number.isFinite(t.height)?{left:Number(t.offsetLeft)||0,top:Number(t.offsetTop)||0,width:Math.max(0,Number(t.width)||0),height:Math.max(0,Number(t.height)||0)}:{left:0,top:0,width:e.innerWidth,height:e.innerHeight}}function a(e,t,i,o=7,n=8){const r=i.left+n,s=i.top+n,a=Math.max(r,i.left+i.width-n),l=Math.max(s,i.top+i.height-n),h=Math.max(0,a-r),c=Math.max(0,l-s),d=Math.min(Math.max(0,t.width),h),u=Math.min(Math.max(0,t.height),c);let p=e.left;p+d>a&&(p=e.right-d),p=Math.min(Math.max(r,p),Math.max(r,a-d));const g=e.bottom+o,_=e.top-o-u;let m="bottom",f=g;return g+u>l&&_>=s?(m="top",f=Math.min(Math.max(s,_),Math.max(s,l-u))):f=Math.min(Math.max(s,g),Math.max(s,l-u)),{left:Math.round(p),top:Math.round(f),side:m,maxWidth:Math.round(h),maxHeight:Math.round(c)}}class l{constructor(e,t,i){this.owner=e,this.name=t,this.keydown=i,this.host=null,this.root=null}window(){return this.owner.ownerDocument.defaultView}dialog(){return this.owner.closest("hp-dialog")}usesPopover(e=!1){const t=this.window();return!e&&!!t&&function(e){const t=e.HTMLElement?.prototype;return"function"==typeof t?.showPopover&&"function"==typeof t?.hidePopover}(t)}get hasFallback(){return!!this.host}containsPath(e){return e.includes(this.owner)||!!this.host&&e.includes(this.host)}ownsActiveElement(){let e=this.owner.ownerDocument.activeElement;for(;e?.shadowRoot?.activeElement;)e=e.shadowRoot.activeElement;return!(!e||e!==this.owner&&!this.owner.shadowRoot?.contains(e)&&!this.root?.contains(e))}renderFallback(i,o){const n=this.ensureFallback();return n?(e(t`${i}`,n),n):null}surface(e,t){return t?this.owner.shadowRoot?.querySelector(e)||null:this.root?.querySelector(e)||null}destroy(){this.root&&e(i,this.root),this.host?.remove(),this.host=null,this.root=null}ensureFallback(){if(this.root?.isConnected)return this.root;const e=this.dialog()?.overlayPortal()||this.owner.ownerDocument.body;if(!e)return null;const t=this.owner.ownerDocument.createElement("div");return t.dataset.hpOverlay=this.name,t.style.display="contents",this.keydown&&t.addEventListener("keydown",this.keydown,!0),e.append(t),this.host=t,this.root=t.attachShadow({mode:"open"}),this.root}}let h=0;class c extends n{constructor(){super(...arguments),this.text="",this.ariaLabel="",this.pointerHover=!1,this._open=!1,this._openTimer=0,this._closeTimer=0,this._positionRaf=0,this._forceFallback=!1,this._hoverOwned=!1,this._overlayDispose=null,this._scrollDialog=null,this._descriptionId="hp-help-description-"+ ++h,this._surfacePointerEnter=()=>{const e=this._window();this._closeTimer&&e?.clearTimeout(this._closeTimer),this._closeTimer=0},this._surfacePointerLeave=()=>{this._scheduleClose()},this._outsidePointerDown=e=>{if(!this._open)return;const t=e.composedPath();this._floating.containsPath(t)||this._closeHelp(!1,"outside")},this._dialogScroll=e=>{const t=this._floating.containsPath(e.composedPath()),i=e.target,o=this._dialog(),n=i instanceof Node&&(i===o||i instanceof Element&&i.contains(this));var r;this._open&&(r=n,!t&&r)&&this._closeHelp(!1,"scroll")},this._keyDown=e=>{if(!this._open||e.defaultPrevented)return;if("Escape"===e.key)return e.preventDefault(),e.stopImmediatePropagation(),void this._closeHelp(this._floating.ownsActiveElement(),"escape");const t=this.renderRoot.querySelector(".trigger");if(!t||!e.composedPath().includes(t))return;const i=this._surface();if(!i||i.scrollHeight<=i.clientHeight)return;const o=Math.max(40,.8*i.clientHeight),n={ArrowDown:40,ArrowUp:-40,PageDown:o,PageUp:-o};if("Home"===e.key)i.scrollTop=0;else if("End"===e.key)i.scrollTop=i.scrollHeight;else{if(!(e.key in n))return;i.scrollBy({top:n[e.key],behavior:"auto"})}e.preventDefault(),e.stopImmediatePropagation()},this._floating=new l(this,"help",this._keyDown),this._queuePosition=()=>{if(!this._open||this._positionRaf)return;const e=this._window();e&&(this._positionRaf=e.requestAnimationFrame(()=>{this._positionRaf=0,this._position()||this._closeHelp()}))}}connectedCallback(){super.connectedCallback(),this.addEventListener("keydown",this._keyDown,!0)}willUpdate(){this.toggleAttribute("data-has-content",this._hasContent())}disconnectedCallback(){const e=this.ownerDocument.defaultView;this._unsubscribeOpenListeners(),this.removeEventListener("keydown",this._keyDown,!0),this._clearTimers(),this._positionRaf&&e?.cancelAnimationFrame(this._positionRaf),this._positionRaf=0,this._closeHelp(!1,"disconnect"),super.disconnectedCallback()}updated(e){if(e.has("pointerHover")&&!this.pointerHover){const e=this._window();this._openTimer&&e?.clearTimeout(this._openTimer),this._openTimer=0,this._hoverOwned&&this._closeHelp(!1,"outside")}this._hasContent()||!this._open?this._open&&e.has("text")&&(this._usesPopover()||this._renderFallback(),this._queuePosition()):this._closeHelp()}_window(){return this._floating.window()}_dialog(){return this._floating.dialog()}_usesPopover(){return this._floating.usesPopover(this._forceFallback)}_hasContent(){return e=this.text,t=this.ariaLabel,"string"==typeof e&&e.trim().length>0&&"string"==typeof t&&t.trim().length>0;var e,t}_clearTimers(){const e=this._window();this._openTimer&&e?.clearTimeout(this._openTimer),this._closeTimer&&e?.clearTimeout(this._closeTimer),this._openTimer=0,this._closeTimer=0}_scheduleOpen(){const e=this._window();this.pointerHover&&e&&!this._open&&!this._openTimer&&(this._closeTimer&&e.clearTimeout(this._closeTimer),this._closeTimer=0,this._openTimer=e.setTimeout(()=>{this._openTimer=0,this.isConnected&&(this._hoverOwned=!0,this._openHelp())},300))}_scheduleClose(){const e=this._window(),t=this.renderRoot.querySelector(".trigger");e&&!t?.matches(":focus-visible")&&(this._openTimer&&e.clearTimeout(this._openTimer),this._closeTimer&&e.clearTimeout(this._closeTimer),this._openTimer=0,this._closeTimer=e.setTimeout(()=>{this._closeTimer=0,this.isConnected&&this._closeHelp()},150))}_triggerPointerEnter(e){this.pointerHover&&"mouse"===e.pointerType&&this._scheduleOpen()}_triggerPointerLeave(e){"mouse"===e.pointerType&&this._scheduleClose()}_triggerFocus(){queueMicrotask(()=>{const e=this.renderRoot.querySelector(".trigger");e?.matches(":focus-visible")&&(this._hoverOwned=!1,this._openHelp())})}_triggerBlur(){this._scheduleClose()}_triggerClick(){this._open?this._closeHelp():(this._hoverOwned=!1,this._openHelp())}_subscribeOpenListeners(){this.ownerDocument.addEventListener("pointerdown",this._outsidePointerDown,!0),this.ownerDocument.addEventListener("keydown",this._keyDown,!0);const e=this._window();e?.addEventListener("resize",this._queuePosition),e?.addEventListener("orientationchange",this._queuePosition),e?.visualViewport?.addEventListener("resize",this._queuePosition),e?.visualViewport?.addEventListener("scroll",this._queuePosition),this._scrollDialog=this._dialog(),this._scrollDialog?.addEventListener("scroll",this._dialogScroll,!0)}_unsubscribeOpenListeners(){this.ownerDocument.removeEventListener("pointerdown",this._outsidePointerDown,!0),this.ownerDocument.removeEventListener("keydown",this._keyDown,!0);const e=this._window();e?.removeEventListener("resize",this._queuePosition),e?.removeEventListener("orientationchange",this._queuePosition),e?.visualViewport?.removeEventListener("resize",this._queuePosition),e?.visualViewport?.removeEventListener("scroll",this._queuePosition),this._scrollDialog?.removeEventListener("scroll",this._dialogScroll,!0),this._scrollDialog=null}async _openHelp(){!this._open&&this._hasContent()&&(this._clearTimers(),this._forceFallback=!1,this._open=!0,this._subscribeOpenListeners(),await this.updateComplete,this._open&&(this._usesPopover()||this._renderFallback(),this._position()?this._overlayDispose=this._dialog()?.registerOverlay({owner:this,group:"transient",close:e=>this._closeHelp("escape"===e&&this._floating.ownsActiveElement(),e)})||null:this._closeHelp()))}_closeHelp(e=!1,t="exclusive"){if(!this._open&&!this._floating.hasFallback)return;this._clearTimers();const i=this._overlayDispose;this._overlayDispose=null,i?.();const o=this.renderRoot.querySelector(".tooltip");if(o?.hidePopover)try{o.matches(":popover-open")&&o.hidePopover()}catch{}this._open=!1,this._hoverOwned=!1,this._unsubscribeOpenListeners(),this._floating.destroy(),e&&this.updateComplete.then(()=>this.renderRoot.querySelector(".trigger")?.focus())}_tooltipTemplate(e){return t`
a&&(p=e.right-c),p=Math.min(Math.max(r,p),Math.max(r,a-c));const g=e.bottom+o,_=e.top-o-u;let m="bottom",f=g;return g+u>l&&_>=s?(m="top",f=Math.min(Math.max(s,_),Math.max(s,l-u))):f=Math.min(Math.max(s,g),Math.max(s,l-u)),{left:Math.round(p),top:Math.round(f),side:m,maxWidth:Math.round(h),maxHeight:Math.round(d)}}class l{constructor(e,t,i){this.owner=e,this.name=t,this.keydown=i,this.host=null,this.root=null}window(){return this.owner.ownerDocument.defaultView}dialog(){return this.owner.closest("hp-dialog")}usesPopover(e=!1){const t=this.window();return!e&&!!t&&function(e){const t=e.HTMLElement?.prototype;return"function"==typeof t?.showPopover&&"function"==typeof t?.hidePopover}(t)}get hasFallback(){return!!this.host}containsPath(e){return e.includes(this.owner)||!!this.host&&e.includes(this.host)}ownsActiveElement(){let e=this.owner.ownerDocument.activeElement;for(;e?.shadowRoot?.activeElement;)e=e.shadowRoot.activeElement;return!(!e||e!==this.owner&&!this.owner.shadowRoot?.contains(e)&&!this.root?.contains(e))}renderFallback(i,o){const n=this.ensureFallback();return n?(e(t`${i}`,n),n):null}surface(e,t){return t?this.owner.shadowRoot?.querySelector(e)||null:this.root?.querySelector(e)||null}destroy(){this.root&&e(i,this.root),this.host?.remove(),this.host=null,this.root=null}ensureFallback(){if(this.root?.isConnected)return this.root;const e=this.dialog()?.overlayPortal()||this.owner.ownerDocument.body;if(!e)return null;const t=this.owner.ownerDocument.createElement("div");return t.dataset.hpOverlay=this.name,t.style.display="contents",this.keydown&&t.addEventListener("keydown",this.keydown,!0),e.append(t),this.host=t,this.root=t.attachShadow({mode:"open"}),this.root}}let h=0;class d extends n{constructor(){super(...arguments),this.text="",this.ariaLabel="",this.pointerHover=!1,this._open=!1,this._openTimer=0,this._closeTimer=0,this._positionRaf=0,this._forceFallback=!1,this._hoverOwned=!1,this._overlayDispose=null,this._scrollDialog=null,this._descriptionId="hp-help-description-"+ ++h,this._surfacePointerEnter=()=>{const e=this._window();this._closeTimer&&e?.clearTimeout(this._closeTimer),this._closeTimer=0},this._surfacePointerLeave=()=>{this._scheduleClose()},this._outsidePointerDown=e=>{if(!this._open)return;const t=e.composedPath();this._floating.containsPath(t)||this._closeHelp(!1,"outside")},this._dialogScroll=e=>{const t=this._floating.containsPath(e.composedPath()),i=e.target,o=this._dialog(),n=i instanceof Node&&(i===o||i instanceof Element&&i.contains(this));var r;this._open&&(r=n,!t&&r)&&this._closeHelp(!1,"scroll")},this._keyDown=e=>{if(!this._open||e.defaultPrevented)return;if("Escape"===e.key)return e.preventDefault(),e.stopImmediatePropagation(),void this._closeHelp(this._floating.ownsActiveElement(),"escape");const t=this.renderRoot.querySelector(".trigger");if(!t||!e.composedPath().includes(t))return;const i=this._surface();if(!i||i.scrollHeight<=i.clientHeight)return;const o=Math.max(40,.8*i.clientHeight),n={ArrowDown:40,ArrowUp:-40,PageDown:o,PageUp:-o};if("Home"===e.key)i.scrollTop=0;else if("End"===e.key)i.scrollTop=i.scrollHeight;else{if(!(e.key in n))return;i.scrollBy({top:n[e.key],behavior:"auto"})}e.preventDefault(),e.stopImmediatePropagation()},this._floating=new l(this,"help",this._keyDown),this._queuePosition=()=>{if(!this._open||this._positionRaf)return;const e=this._window();e&&(this._positionRaf=e.requestAnimationFrame(()=>{this._positionRaf=0,this._position()||this._closeHelp()}))}}connectedCallback(){super.connectedCallback(),this.addEventListener("keydown",this._keyDown,!0)}willUpdate(){this.toggleAttribute("data-has-content",this._hasContent())}disconnectedCallback(){const e=this.ownerDocument.defaultView;this._unsubscribeOpenListeners(),this.removeEventListener("keydown",this._keyDown,!0),this._clearTimers(),this._positionRaf&&e?.cancelAnimationFrame(this._positionRaf),this._positionRaf=0,this._closeHelp(!1,"disconnect"),super.disconnectedCallback()}updated(e){if(e.has("pointerHover")&&!this.pointerHover){const e=this._window();this._openTimer&&e?.clearTimeout(this._openTimer),this._openTimer=0,this._hoverOwned&&this._closeHelp(!1,"outside")}this._hasContent()||!this._open?this._open&&e.has("text")&&(this._usesPopover()||this._renderFallback(),this._queuePosition()):this._closeHelp()}_window(){return this._floating.window()}_dialog(){return this._floating.dialog()}_usesPopover(){return this._floating.usesPopover(this._forceFallback)}_hasContent(){return e=this.text,t=this.ariaLabel,"string"==typeof e&&e.trim().length>0&&"string"==typeof t&&t.trim().length>0;var e,t}_clearTimers(){const e=this._window();this._openTimer&&e?.clearTimeout(this._openTimer),this._closeTimer&&e?.clearTimeout(this._closeTimer),this._openTimer=0,this._closeTimer=0}_scheduleOpen(){const e=this._window();this.pointerHover&&e&&!this._open&&!this._openTimer&&(this._closeTimer&&e.clearTimeout(this._closeTimer),this._closeTimer=0,this._openTimer=e.setTimeout(()=>{this._openTimer=0,this.isConnected&&(this._hoverOwned=!0,this._openHelp())},300))}_scheduleClose(){const e=this._window(),t=this.renderRoot.querySelector(".trigger");e&&!t?.matches(":focus-visible")&&(this._openTimer&&e.clearTimeout(this._openTimer),this._closeTimer&&e.clearTimeout(this._closeTimer),this._openTimer=0,this._closeTimer=e.setTimeout(()=>{this._closeTimer=0,this.isConnected&&this._closeHelp()},150))}_triggerPointerEnter(e){this.pointerHover&&"mouse"===e.pointerType&&this._scheduleOpen()}_triggerPointerLeave(e){"mouse"===e.pointerType&&this._scheduleClose()}_triggerFocus(){queueMicrotask(()=>{const e=this.renderRoot.querySelector(".trigger");e?.matches(":focus-visible")&&(this._hoverOwned=!1,this._openHelp())})}_triggerBlur(){this._scheduleClose()}_triggerClick(){this._open?this._closeHelp():(this._hoverOwned=!1,this._openHelp())}_subscribeOpenListeners(){this.ownerDocument.addEventListener("pointerdown",this._outsidePointerDown,!0),this.ownerDocument.addEventListener("keydown",this._keyDown,!0);const e=this._window();e?.addEventListener("resize",this._queuePosition),e?.addEventListener("orientationchange",this._queuePosition),e?.visualViewport?.addEventListener("resize",this._queuePosition),e?.visualViewport?.addEventListener("scroll",this._queuePosition),this._scrollDialog=this._dialog(),this._scrollDialog?.addEventListener("scroll",this._dialogScroll,!0)}_unsubscribeOpenListeners(){this.ownerDocument.removeEventListener("pointerdown",this._outsidePointerDown,!0),this.ownerDocument.removeEventListener("keydown",this._keyDown,!0);const e=this._window();e?.removeEventListener("resize",this._queuePosition),e?.removeEventListener("orientationchange",this._queuePosition),e?.visualViewport?.removeEventListener("resize",this._queuePosition),e?.visualViewport?.removeEventListener("scroll",this._queuePosition),this._scrollDialog?.removeEventListener("scroll",this._dialogScroll,!0),this._scrollDialog=null}async _openHelp(){!this._open&&this._hasContent()&&(this._clearTimers(),this._forceFallback=!1,this._open=!0,this._subscribeOpenListeners(),await this.updateComplete,this._open&&(this._usesPopover()||this._renderFallback(),this._position()?this._overlayDispose=this._dialog()?.registerOverlay({owner:this,group:"transient",close:e=>this._closeHelp("escape"===e&&this._floating.ownsActiveElement(),e)})||null:this._closeHelp()))}_closeHelp(e=!1,t="exclusive"){if(!this._open&&!this._floating.hasFallback)return;this._clearTimers();const i=this._overlayDispose;this._overlayDispose=null,i?.();const o=this.renderRoot.querySelector(".tooltip");if(o?.hidePopover)try{o.matches(":popover-open")&&o.hidePopover()}catch{}this._open=!1,this._hoverOwned=!1,this._unsubscribeOpenListeners(),this._floating.destroy(),e&&this.updateComplete.then(()=>this.renderRoot.querySelector(".trigger")?.focus())}_tooltipTemplate(e){return t``}_renderFallback(){const e=c.styles.cssText;this._floating.renderFallback(this._tooltipTemplate(!1),e)}_surface(){return this._floating.surface(".tooltip",this._usesPopover())}_position(){if(!this._open)return!1;const e=this._window(),t=this.renderRoot.querySelector(".trigger");let i=this._surface();if(!e||!t?.isConnected||!i?.isConnected)return!1;const o=s(e);if(i.style.maxWidth=`${Math.max(0,Math.min(320,o.width-16))}px`,i.style.maxHeight=`${Math.max(0,o.height-16)}px`,i.style.visibility="hidden",this._usesPopover()&&i.showPopover)try{i.matches(":popover-open")||i.showPopover()}catch{if(this._forceFallback=!0,this._renderFallback(),i=this._surface(),!i?.isConnected)return!1;i.style.visibility="hidden"}const n=t.getBoundingClientRect(),r=i.getBoundingClientRect();if(!(n.width&&n.height&&r.width&&r.height))return!1;const l=a(n,r,o);return i.style.left=`${l.left}px`,i.style.top=`${l.top}px`,i.dataset.side=l.side,i.style.visibility="",!0}render(){if(!this._hasContent())return i;const e=this.ariaLabel.trim();return t` + @pointerenter=${this._surfacePointerEnter} @pointerleave=${this._surfacePointerLeave}>${this.text}
`}_renderFallback(){const e=d.styles.cssText;this._floating.renderFallback(this._tooltipTemplate(!1),e)}_surface(){return this._floating.surface(".tooltip",this._usesPopover())}_position(){if(!this._open)return!1;const e=this._window(),t=this.renderRoot.querySelector(".trigger");let i=this._surface();if(!e||!t?.isConnected||!i?.isConnected)return!1;const o=s(e);if(i.style.maxWidth=`${Math.max(0,Math.min(320,o.width-16))}px`,i.style.maxHeight=`${Math.max(0,o.height-16)}px`,i.style.visibility="hidden",this._usesPopover()&&i.showPopover)try{i.matches(":popover-open")||i.showPopover()}catch{if(this._forceFallback=!0,this._renderFallback(),i=this._surface(),!i?.isConnected)return!1;i.style.visibility="hidden"}const n=t.getBoundingClientRect(),r=i.getBoundingClientRect();if(!(n.width&&n.height&&r.width&&r.height))return!1;const l=a(n,r,o);return i.style.left=`${l.left}px`,i.style.top=`${l.top}px`,i.dataset.side=l.side,i.style.visibility="",!0}render(){if(!this._hasContent())return i;const e=this.ariaLabel.trim();return t` ${this.text} - -
- - -
- `}}Pe.properties={title:{type:String},icon:{type:String},wide:{type:Boolean,reflect:!0},alert:{type:Boolean,reflect:!0},describedBy:{type:String,attribute:"described-by"},dismissOnScrim:{type:Boolean,attribute:"dismiss-on-scrim"},flexContent:{type:Boolean,reflect:!0,attribute:"flex-content"},hass:{attribute:!1}},Pe.styles=o`:host{display:contents;color:var(--primary-text-color,#e6e7eb);font:inherit;}ha-dialog{--dialog-content-padding:0;--dialog-surface-background:var(--card-background-color,var(--hp-bg,#202126));--ha-dialog-border-radius:var(--rad-l,18px);--ha-dialog-header-title-height:auto;color:inherit;}ha-dialog::part(dialog){border:1px solid var(--hp-accent,#d89300);box-shadow:var(--shadow-3,0 18px 48px rgb(0 0 0 / 0.34));overflow:hidden;}.header-title-slot{display:block;flex:1 1 auto;width:100%;max-width:100%;min-width:0;box-sizing:border-box;white-space:normal;}.title{display:flex;flex:1 1 auto;align-items:center;gap:var(--sp-4,12px);width:100%;max-width:100%;min-width:0;font-weight:600;line-height:1.25;white-space:normal;}.title ha-icon{flex:none;color:var(--hp-accent,#d89300);}.title-text{flex:1 1 auto;min-width:0;max-width:100%;white-space:normal;overflow-wrap:anywhere;word-break:normal;}.footer{display:block;width:100%;min-width:0;box-sizing:border-box;}::slotted([slot='footer']){width:100%;box-sizing:border-box;}dialog{width:fit-content;height:fit-content;max-width:none;max-height:none;inset:0;margin:auto;padding:0;border:0;overflow:visible;color:inherit;background:transparent;}dialog::backdrop{background:rgb(0 0 0 / 0.45);}.surface{width:min(360px,92vw);max-height:92vh;display:flex;flex-direction:column;overflow:hidden;box-sizing:border-box;color:inherit;background:var(--card-background-color,var(--hp-bg,#202126));border:1px solid var(--hp-accent,#d89300);border-radius:var(--rad-l,18px);box-shadow:var(--shadow-3,0 18px 48px rgb(0 0 0 / 0.34));}:host([wide]) .surface{width:min(var(--hp-dialog-wide-width,500px),94vw);}.header{min-height:56px;display:flex;align-items:center;gap:var(--sp-4,12px);padding:var(--sp-4,12px) var(--sp-5,16px);box-sizing:border-box;border-bottom:1px solid var(--hp-line,rgb(255 255 255 / 0.12));}.header .title{flex:1;}.close{width:40px;height:40px;flex:none;display:inline-flex;align-items:center;justify-content:center;padding:0;color:inherit;background:transparent;border:0;border-radius:50%;cursor:pointer;}:host([data-pointer-hover]) .close:hover,.close:focus-visible{background:rgb(127 127 127 / 0.16);}.content{min-height:0;display:flex;flex-direction:column;}.overlay-portal{position:fixed;z-index:2147483647;inset:0;overflow:visible;pointer-events:none;}.overlay-portal:empty{display:none;}.overlay-portal>*{pointer-events:auto;}`,customElements.get("hp-dialog")||customElements.define("hp-dialog",Pe);class Fe extends he{constructor(){super(...arguments),this.hass=null,this.request=null,this.token=0}createRenderRoot(){return this}_decide(e){this.dispatchEvent(new CustomEvent("hp-confirm-decision",{detail:{token:this.token,accepted:e},bubbles:!0,composed:!0}))}render(){const e=this.request;if(!e)return null;const t="destructive"===e.kind,i=`hp-confirm-description-${this.token}`;return j`this._decide(!1)}> -
- ${e.objectName?j`${e.objectName}`:null} -

${e.message}

-
- -
`}}Fe.properties={hass:{attribute:!1},request:{attribute:!1},token:{type:Number}},customElements.get("hp-confirm")||customElements.define("hp-confirm",Fe);class ze{constructor(e){this._changed=e,this._sequence=0,this._active=null}get state(){return this._active?{token:this._active.token,request:this._active.request}:null}confirm(e){this.cancel();const t={token:++this._sequence,request:Object.freeze({...e})};return new Promise(e=>{this._active={...t,resolve:e},this._changed(t)})}resolve(e,t){const i=this._active;return!(!i||i.token!==e)&&(this._active=null,this._changed(null),i.resolve(t),!0)}cancel(){const e=this._active;return!!e&&this.resolve(e.token,!1)}}const Ie=new Set(["hacs","sun","backup","hassio","met","telegram_bot","mobile_app","systemmonitor","better_thermostat","adaptive_lighting","yandex_pogoda","upnp_serial_number"]),Oe=[{pattern:"протечк|leak|water sensor",icon:"mdi:water-alert"},{pattern:"клапан|valve",icon:"mdi:pipe-valve"},{pattern:"дым|smoke",icon:"mdi:smoke-detector"},{pattern:"термоголов|trv|radiator",icon:"mdi:radiator"},{pattern:"чайник|kettle|термопот",icon:"mdi:kettle"},{pattern:"сауна|sauna|harvia|парная|парилк",icon:"mdi:hot-tub"},{pattern:"температ|temperature|thermometer|climate sensor",icon:"mdi:thermometer"},{pattern:"qingping|air monitor|молекул|air quality",icon:"mdi:air-filter"},{pattern:"штор|curtain|blind|shade",icon:"mdi:roller-shade"},{pattern:"розетк|plug|socket|outlet",icon:"mdi:power-socket-de"},{pattern:"выключат|switch",icon:"mdi:light-switch"},{pattern:"лампа|лампочк|bulb|gx53|светильник|rgb|lamp|light strip",icon:"mdi:lightbulb"},{pattern:"камер|camera",icon:"mdi:cctv"},{pattern:"замок|ttlock|lock|sn609|sn9161",icon:"mdi:lock"},{pattern:"ворота|garage|gate",icon:"mdi:garage-variant"},{pattern:"калитк|door|открыт|contact",icon:"mdi:door"},{pattern:"счётчик|счетчик|kws|meter",icon:"mdi:meter-electric"},{pattern:"вводный автомат|breaker|wifimcbn",icon:"mdi:electric-switch"},{pattern:"myheat|котёл|котел|boiler|отоплен|heating",icon:"mdi:water-boiler"},{pattern:"холодильник|fridge",icon:"mdi:fridge"},{pattern:"стиральн|washer|washing",icon:"mdi:washing-machine"},{pattern:"сушилк|dryer",icon:"mdi:tumble-dryer"},{pattern:"пылесос|vacuum|dreame|roborock",icon:"mdi:robot-vacuum"},{pattern:"soundbar",icon:"mdi:soundbar"},{pattern:"колонк|станц|speaker|яндекс|yandex|алиса|alice",icon:"mdi:speaker"},{pattern:"tv|телевизор|hyundaitv|mitv|television",icon:"mdi:television"},{pattern:"keenetic|роутер|router|mesh|access point",icon:"mdi:router-wireless"},{pattern:"ибп|ups|kirpich",icon:"mdi:battery-charging-high"},{pattern:"slzb|координат|zigbee|coordinator",icon:"mdi:zigbee"},{pattern:"motion|движен|presence|присутств",icon:"mdi:motion-sensor"},{pattern:"humidity|влажн",icon:"mdi:water-percent"}];function Ee(e){const t=[];for(const i of e)if(i&&"string"==typeof i.pattern&&i.icon)try{t.push({re:new RegExp(i.pattern,"i"),icon:i.icon})}catch{}return t}function Ne(e){try{return new RegExp(e,"i"),!0}catch{return!1}}const He=Ee(Oe),Le={temperature:"mdi:thermometer",humidity:"mdi:water-percent",motion:"mdi:motion-sensor",occupancy:"mdi:motion-sensor",presence:"mdi:motion-sensor",door:"mdi:door",window:"mdi:window-closed",garage_door:"mdi:garage-variant",smoke:"mdi:smoke-detector",moisture:"mdi:water-alert",gas:"mdi:gas-cylinder",power:"mdi:meter-electric",energy:"mdi:meter-electric",illuminance:"mdi:brightness-5",co2:"mdi:molecule-co2",pm25:"mdi:air-filter",battery:"mdi:battery"},Be="mdi:chip";function qe(e,t,i){const n=((e||"")+" "+(t||"")).toLowerCase();for(const{re:e,icon:t}of i??He)if(e.test(n))return t;return Be}const je=["light","switch","cover","valve","lock","climate","fan","media_player","camera","vacuum","humidifier","water_heater","alarm_control_panel","sensor","binary_sensor","event","button","number","select","update"];var We=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Ue=Math.ceil,Ge=Math.floor,Ve="[BigNumber Error] ",Ke=Ve+"Number primitive has more than 15 significant digits: ",Ye=1e14,Xe=14,Ze=9007199254740991,Je=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Qe=1e7,et=1e9;function tt(e){var t=0|e;return e>0||e===t?t:t-1}function it(e){for(var t,i,n=1,r=e.length,o=e[0]+"";nc^i?1:-1;for(a=(l=r.length)<(c=o.length)?l:c,s=0;so[s]^i?1:-1;return l==c?0:l>c^i?1:-1}function rt(e,t,i,n){if(ei||e!==Ge(e))throw Error(Ve+(n||"Argument")+("number"==typeof e?ei?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function ot(e){var t=e.c.length-1;return tt(e.e/Xe)==t&&e.c[t]%2!=0}function st(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function at(e,t,i){var n,r;if(t<0){for(r=i+".";++t;r+=i);e=r+e}else if(++t>(n=e.length)){for(r=i,t-=n;--t;r+=i);e+=r}else ty?u.c=u.e=null:e.e=10;l/=10,a++);return void(a>y?u.c=u.e=null:(u.e=a,u.c=[e]))}d=String(e)}else{if(!We.test(d=String(e)))return r(u,d,c);u.s=45==d.charCodeAt(0)?(d=d.slice(1),-1):1}(a=d.indexOf("."))>-1&&(d=d.replace(".","")),(l=d.search(/e/i))>0?(a<0&&(a=l),a+=+d.slice(l+1),d=d.substring(0,l)):a<0&&(a=d.length)}else{if(rt(t,2,S.length,"Base"),10==t&&$)return D(u=new M(e),_+u.e+1,m);if(d=String(e),c="number"==typeof e){if(0*e!=0)return r(u,d,c,t);if(u.s=1/e<0?(d=d.slice(1),-1):1,M.DEBUG&&d.replace(/^0\.0*|\./,"").length>15)throw Error(Ke+e)}else u.s=45===d.charCodeAt(0)?(d=d.slice(1),-1):1;for(i=S.slice(0,t),a=l=0,h=d.length;la){a=h;continue}}else if(!s&&(d==d.toUpperCase()&&(d=d.toLowerCase())||d==d.toLowerCase()&&(d=d.toUpperCase()))){s=!0,l=-1,a=0;continue}return r(u,String(e),c,t)}c=!1,(a=(d=n(d,t,10,u.s)).indexOf("."))>-1?d=d.replace(".",""):a=d.length}for(l=0;48===d.charCodeAt(l);l++);for(h=d.length;48===d.charCodeAt(--h););if(d=d.slice(l,++h)){if(h-=l,c&&M.DEBUG&&h>15&&(e>Ze||e!==Ge(e)))throw Error(Ke+u.s*e);if((a=a-l-1)>y)u.c=u.e=null;else if(a=f)?st(l,s):at(l,s,"0");else if(o=(e=D(new M(e),t,i)).e,a=(l=it(e.c)).length,1==n||2==n&&(t<=o||o<=g)){for(;as),l=at(l,o,"0"),o+1>a){if(--t>0)for(l+=".";t--;l+="0");}else if((t+=o-a)>0)for(o+1==a&&(l+=".");t--;l+="0");return e.s<0&&r?"-"+l:l}function C(e,t){for(var i,n,r=1,o=new M(e[0]);r=10;r/=10,n++);return(i=n+i*Xe-1)>y?e.c=e.e=null:i=10;a/=10,r++);if((o=t-r)<0)o+=Xe,s=t,l=d[c=0],h=Ge(l/u[r-s-1]%10);else if((c=Ue((o+1)/Xe))>=d.length){if(!n)break e;for(;d.length<=c;d.push(0));l=h=0,r=1,s=(o%=Xe)-Xe+1}else{for(l=a=d[c],r=1;a>=10;a/=10,r++);h=(s=(o%=Xe)-Xe+r)<0?0:Ge(l/u[r-s-1]%10)}if(n=n||t<0||null!=d[c+1]||(s<0?l:l%u[r-s-1]),n=i<4?(h||n)&&(0==i||i==(e.s<0?3:2)):h>5||5==h&&(4==i||n||6==i&&(o>0?s>0?l/u[r-s]:0:d[c-1])%10&1||i==(e.s<0?8:7)),t<1||!d[0])return d.length=0,n?(t-=e.e+1,d[0]=u[(Xe-t%Xe)%Xe],e.e=-t||0):d[0]=e.e=0,e;if(0==o?(d.length=c,a=1,c--):(d.length=c+1,a=u[Xe-o],d[c]=s>0?Ge(l/u[r-s]%u[s])*a:0),n)for(;;){if(0==c){for(o=1,s=d[0];s>=10;s/=10,o++);for(s=d[0]+=a,a=1;s>=10;s/=10,a++);o!=a&&(e.e++,d[0]==Ye&&(d[0]=1));break}if(d[c]+=a,d[c]!=Ye)break;d[c--]=0,a=1}for(o=d.length;0===d[--o];d.pop());}e.e>y?e.c=e.e=null:e.e=f?st(t,i):at(t,i,"0"),e.s<0?"-"+t:t)}return M.clone=e,M.ROUND_UP=0,M.ROUND_DOWN=1,M.ROUND_CEIL=2,M.ROUND_FLOOR=3,M.ROUND_HALF_UP=4,M.ROUND_HALF_DOWN=5,M.ROUND_HALF_EVEN=6,M.ROUND_HALF_CEIL=7,M.ROUND_HALF_FLOOR=8,M.EUCLID=9,M.config=M.set=function(e){var t,i;if(null!=e){if("object"!=typeof e)throw Error(Ve+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(rt(i=e[t],0,et,t),_=i),e.hasOwnProperty(t="ROUNDING_MODE")&&(rt(i=e[t],0,8,t),m=i),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((i=e[t])&&i.pop?(rt(i[0],-et,0,t),rt(i[1],0,et,t),g=i[0],f=i[1]):(rt(i,-et,et,t),g=-(f=i<0?-i:i))),e.hasOwnProperty(t="RANGE"))if((i=e[t])&&i.pop)rt(i[0],-et,-1,t),rt(i[1],1,et,t),v=i[0],y=i[1];else{if(rt(i,-et,et,t),!i)throw Error(Ve+t+" cannot be zero: "+i);v=-(y=i<0?-i:i)}if(e.hasOwnProperty(t="CRYPTO")){if((i=e[t])!==!!i)throw Error(Ve+t+" not true or false: "+i);if(i){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw b=!i,Error(Ve+"crypto unavailable");b=i}else b=i}if(e.hasOwnProperty(t="MODULO_MODE")&&(rt(i=e[t],0,9,t),w=i),e.hasOwnProperty(t="POW_PRECISION")&&(rt(i=e[t],0,et,t),k=i),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(i=e[t]))throw Error(Ve+t+" not an object: "+i);x=i}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(i=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(i))throw Error(Ve+t+" invalid: "+i);$="0123456789"==i.slice(0,10),S=i}}return{DECIMAL_PLACES:_,ROUNDING_MODE:m,EXPONENTIAL_AT:[g,f],RANGE:[v,y],CRYPTO:b,MODULO_MODE:w,POW_PRECISION:k,FORMAT:x,ALPHABET:S}},M.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!M.DEBUG)return!0;var t,i,n=e.c,r=e.e,o=e.s;e:if("[object Array]"=={}.toString.call(n)){if((1===o||-1===o)&&r>=-et&&r<=et&&r===Ge(r)){if(0===n[0]){if(0===r&&1===n.length)return!0;break e}if((t=(r+1)%Xe)<1&&(t+=Xe),String(n[0]).length==t){for(t=0;t=Ye||i!==Ge(i))break e;if(0!==i)return!0}}}else if(null===n&&null===r&&(null===o||1===o||-1===o))return!0;throw Error(Ve+"Invalid BigNumber: "+e)},M.maximum=M.max=function(){return C(arguments,-1)},M.minimum=M.min=function(){return C(arguments,1)},M.random=(o=9007199254740992,s=Math.random()*o&2097151?function(){return Ge(Math.random()*o)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,i,n,r,o,a=0,l=[],c=new M(p);if(null==e?e=_:rt(e,0,et),r=Ue(e/Xe),b)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(r*=2));a>>11))>=9e15?(i=crypto.getRandomValues(new Uint32Array(2)),t[a]=i[0],t[a+1]=i[1]):(l.push(o%1e14),a+=2);a=r/2}else{if(!crypto.randomBytes)throw b=!1,Error(Ve+"crypto unavailable");for(t=crypto.randomBytes(r*=7);a=9e15?crypto.randomBytes(7).copy(t,a):(l.push(o%1e14),a+=7);a=r/7}if(!b)for(;a=10;o/=10,a++);ai-1&&(null==s[r+1]&&(s[r+1]=0),s[r+1]+=s[r]/i|0,s[r]%=i)}return s.reverse()}return function(n,r,o,s,a){var l,c,h,d,u,p,g,f,v=n.indexOf("."),y=_,b=m;for(v>=0&&(d=k,k=0,n=n.replace(".",""),p=(f=new M(r)).pow(n.length-v),k=d,f.c=t(at(it(p.c),p.e,"0"),10,o,e),f.e=f.c.length),h=d=(g=t(n,r,o,a?(l=S,e):(l=e,S))).length;0==g[--d];g.pop());if(!g[0])return l.charAt(0);if(v<0?--h:(p.c=g,p.e=h,p.s=s,g=(p=i(p,f,y,b,o)).c,u=p.r,h=p.e),v=g[c=h+y+1],d=o/2,u=u||c<0||null!=g[c+1],u=b<4?(null!=v||u)&&(0==b||b==(p.s<0?3:2)):v>d||v==d&&(4==b||u||6==b&&1&g[c-1]||b==(p.s<0?8:7)),c<1||!g[0])n=u?at(l.charAt(1),-y,l.charAt(0)):l.charAt(0);else{if(g.length=c,u)for(--o;++g[--c]>o;)g[c]=0,c||(++h,g=[1].concat(g));for(d=g.length;!g[--d];);for(v=0,n="";v<=d;n+=l.charAt(g[v++]));n=at(n,h,l.charAt(0))}return n}}(),i=function(){function e(e,t,i){var n,r,o,s,a=0,l=e.length,c=t%Qe,h=t/Qe|0;for(e=e.slice();l--;)a=((r=c*(o=e[l]%Qe)+(n=h*o+(s=e[l]/Qe|0)*c)%Qe*Qe+a)/i|0)+(n/Qe|0)+h*s,e[l]=r%i;return a&&(e=[a].concat(e)),e}function t(e,t,i,n){var r,o;if(i!=n)o=i>n?1:-1;else for(r=o=0;rt[r]?1:-1;break}return o}function i(e,t,i,n){for(var r=0;i--;)e[i]-=r,r=e[i]1;e.splice(0,1));}return function(n,r,o,s,a){var l,c,h,d,u,p,_,m,g,f,v,y,b,w,k,x,S,$=n.s==r.s?1:-1,R=n.c,C=r.c;if(!(R&&R[0]&&C&&C[0]))return new M(n.s&&r.s&&(R?!C||R[0]!=C[0]:C)?R&&0==R[0]||!C?0*$:$/0:NaN);for(g=(m=new M($)).c=[],$=o+(c=n.e-r.e)+1,a||(a=Ye,c=tt(n.e/Xe)-tt(r.e/Xe),$=$/Xe|0),h=0;C[h]==(R[h]||0);h++);if(C[h]>(R[h]||0)&&c--,$<0)g.push(1),d=!0;else{for(w=R.length,x=C.length,h=0,$+=2,(u=Ge(a/(C[0]+1)))>1&&(C=e(C,u,a),R=e(R,u,a),x=C.length,w=R.length),b=x,v=(f=R.slice(0,x)).length;v=a/2&&k++;do{if(u=0,(l=t(C,f,x,v))<0){if(y=f[0],x!=v&&(y=y*a+(f[1]||0)),(u=Ge(y/k))>1)for(u>=a&&(u=a-1),_=(p=e(C,u,a)).length,v=f.length;1==t(p,f,_,v);)u--,i(p,x<_?S:C,_,a),_=p.length,l=1;else 0==u&&(l=u=1),_=(p=C.slice()).length;if(_=10;$/=10,h++);D(m,o+(m.e=h+c*Xe-1)+1,s,d)}else m.e=c,m.r=+d;return m}}(),a=/^(-?)0([xbo])(?=\w[\w.]*$)/i,l=/^([^.]+)\.$/,c=/^\.([^.]+)$/,h=/^-?(Infinity|NaN)$/,d=/^\s*\+(?=[\w.])|^\s+|\s+$/g,r=function(e,t,i,n){var r,o=i?t:t.replace(d,"");if(h.test(o))e.s=isNaN(o)?null:o<0?-1:1;else{if(!i&&(o=o.replace(a,function(e,t,i){return r="x"==(i=i.toLowerCase())?16:"b"==i?2:8,n&&n!=r?e:t}),n&&(r=n,o=o.replace(l,"$1").replace(c,"0.$1")),t!=o))return new M(o,r);if(M.DEBUG)throw Error(Ve+"Not a"+(n?" base "+n:"")+" number: "+t);e.s=null}e.c=e.e=null},u.absoluteValue=u.abs=function(){var e=new M(this);return e.s<0&&(e.s=1),e},u.comparedTo=function(e,t){return nt(this,new M(e,t))},u.decimalPlaces=u.dp=function(e,t){var i,n,r,o=this;if(null!=e)return rt(e,0,et),null==t?t=m:rt(t,0,8),D(new M(o),e+o.e+1,t);if(!(i=o.c))return null;if(n=((r=i.length-1)-tt(this.e/Xe))*Xe,r=i[r])for(;r%10==0;r/=10,n--);return n<0&&(n=0),n},u.dividedBy=u.div=function(e,t){return i(this,new M(e,t),_,m)},u.dividedToIntegerBy=u.idiv=function(e,t){return i(this,new M(e,t),0,1)},u.exponentiatedBy=u.pow=function(e,t){var i,n,r,o,s,a,l,c,h=this;if((e=new M(e)).c&&!e.isInteger())throw Error(Ve+"Exponent not an integer: "+A(e));if(null!=t&&(t=new M(t)),s=e.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!e.c||!e.c[0])return c=new M(Math.pow(+A(h),s?e.s*(2-ot(e)):+A(e))),t?c.mod(t):c;if(a=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new M(NaN);(n=!a&&h.isInteger()&&t.isInteger())&&(h=h.mod(t))}else{if(e.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||s&&h.c[1]>=24e7:h.c[0]<8e13||s&&h.c[0]<=9999975e7)))return o=h.s<0&&ot(e)?-0:0,h.e>-1&&(o=1/o),new M(a?1/o:o);k&&(o=Ue(k/Xe+2))}for(s?(i=new M(.5),a&&(e.s=1),l=ot(e)):l=(r=Math.abs(+A(e)))%2,c=new M(p);;){if(l){if(!(c=c.times(h)).c)break;o?c.c.length>o&&(c.c.length=o):n&&(c=c.mod(t))}if(r){if(0===(r=Ge(r/2)))break;l=r%2}else if(D(e=e.times(i),e.e+1,1),e.e>14)l=ot(e);else{if(0===(r=+A(e)))break;l=r%2}h=h.times(h),o?h.c&&h.c.length>o&&(h.c.length=o):n&&(h=h.mod(t))}return n?c:(a&&(c=p.div(c)),t?c.mod(t):o?D(c,k,m,void 0):c)},u.integerValue=function(e){var t=new M(this);return null==e?e=m:rt(e,0,8),D(t,t.e+1,e)},u.isEqualTo=u.eq=function(e,t){return 0===nt(this,new M(e,t))},u.isFinite=function(){return!!this.c},u.isGreaterThan=u.gt=function(e,t){return nt(this,new M(e,t))>0},u.isGreaterThanOrEqualTo=u.gte=function(e,t){return 1===(t=nt(this,new M(e,t)))||0===t},u.isInteger=function(){return!!this.c&&tt(this.e/Xe)>this.c.length-2},u.isLessThan=u.lt=function(e,t){return nt(this,new M(e,t))<0},u.isLessThanOrEqualTo=u.lte=function(e,t){return-1===(t=nt(this,new M(e,t)))||0===t},u.isNaN=function(){return!this.s},u.isNegative=function(){return this.s<0},u.isPositive=function(){return this.s>0},u.isZero=function(){return!!this.c&&0==this.c[0]},u.minus=function(e,t){var i,n,r,o,s=this,a=s.s;if(t=(e=new M(e,t)).s,!a||!t)return new M(NaN);if(a!=t)return e.s=-t,s.plus(e);var l=s.e/Xe,c=e.e/Xe,h=s.c,d=e.c;if(!l||!c){if(!h||!d)return h?(e.s=-t,e):new M(d?s:NaN);if(!h[0]||!d[0])return d[0]?(e.s=-t,e):new M(h[0]?s:3==m?-0:0)}if(l=tt(l),c=tt(c),h=h.slice(),a=l-c){for((o=a<0)?(a=-a,r=h):(c=l,r=d),r.reverse(),t=a;t--;r.push(0));r.reverse()}else for(n=(o=(a=h.length)<(t=d.length))?a:t,a=t=0;t0)for(;t--;h[i++]=0);for(t=Ye-1;n>a;){if(h[--n]=0;){for(i=0,u=y[r]%g,p=y[r]/g|0,o=r+(s=l);o>r;)i=((c=u*(c=v[--s]%g)+(a=p*c+(h=v[s]/g|0)*u)%g*g+_[o]+i)/m|0)+(a/g|0)+p*h,_[o--]=c%m;_[o]=i}return i?++n:_.splice(0,1),T(e,_,n)},u.negated=function(){var e=new M(this);return e.s=-e.s||null,e},u.plus=function(e,t){var i,n=this,r=n.s;if(t=(e=new M(e,t)).s,!r||!t)return new M(NaN);if(r!=t)return e.s=-t,n.minus(e);var o=n.e/Xe,s=e.e/Xe,a=n.c,l=e.c;if(!o||!s){if(!a||!l)return new M(r/0);if(!a[0]||!l[0])return l[0]?e:new M(a[0]?n:0*r)}if(o=tt(o),s=tt(s),a=a.slice(),r=o-s){for(r>0?(s=o,i=l):(r=-r,i=a),i.reverse();r--;i.push(0));i.reverse()}for((r=a.length)-(t=l.length)<0&&(i=l,l=a,a=i,t=r),r=0;t;)r=(a[--t]=a[t]+l[t]+r)/Ye|0,a[t]=Ye===a[t]?0:a[t]%Ye;return r&&(a=[r].concat(a),++s),T(e,a,s)},u.precision=u.sd=function(e,t){var i,n,r,o=this;if(null!=e&&e!==!!e)return rt(e,1,et),null==t?t=m:rt(t,0,8),D(new M(o),e,t);if(!(i=o.c))return null;if(n=(r=i.length-1)*Xe+1,r=i[r]){for(;r%10==0;r/=10,n--);for(r=i[0];r>=10;r/=10,n++);}return e&&o.e+1>n&&(n=o.e+1),n},u.shiftedBy=function(e){return rt(e,-9007199254740991,Ze),this.times("1e"+e)},u.squareRoot=u.sqrt=function(){var e,t,n,r,o,s=this,a=s.c,l=s.s,c=s.e,h=_+4,d=new M("0.5");if(1!==l||!a||!a[0])return new M(!l||l<0&&(!a||a[0])?NaN:a?s:1/0);if(0==(l=Math.sqrt(+A(s)))||l==1/0?(((t=it(a)).length+c)%2==0&&(t+="0"),l=Math.sqrt(+t),c=tt((c+1)/2)-(c<0||c%2),n=new M(t=l==1/0?"5e"+c:(t=l.toExponential()).slice(0,t.indexOf("e")+1)+c)):n=new M(l+""),n.c[0])for((l=(c=n.e)+h)<3&&(l=0);;)if(o=n,n=d.times(o.plus(i(s,o,h,1))),it(o.c).slice(0,l)===(t=it(n.c)).slice(0,l)){if(n.e0&&_>0){for(o=_%a||a,h=p.substr(0,o);o<_;o+=a)h+=c+p.substr(o,a);l>0&&(h+=c+p.slice(o)),u&&(h="-"+h)}n=d?h+(i.decimalSeparator||"")+((l=+i.fractionGroupSize)?d.replace(new RegExp("\\d{"+l+"}\\B","g"),"$&"+(i.fractionGroupSeparator||"")):d):h}return(i.prefix||"")+n+(i.suffix||"")},u.toFraction=function(e){var t,n,r,o,s,a,l,c,h,d,u,_,g=this,f=g.c;if(null!=e&&(!(l=new M(e)).isInteger()&&(l.c||1!==l.s)||l.lt(p)))throw Error(Ve+"Argument "+(l.isInteger()?"out of range: ":"not an integer: ")+A(l));if(!f)return new M(g);for(t=new M(p),h=n=new M(p),r=c=new M(p),_=it(f),s=t.e=_.length-g.e-1,t.c[0]=Je[(a=s%Xe)<0?Xe+a:a],e=!e||l.comparedTo(t)>0?s>0?t:h:l,a=y,y=1/0,l=new M(_),c.c[0]=0;d=i(l,t,0,1),1!=(o=n.plus(d.times(r))).comparedTo(e);)n=r,r=o,h=c.plus(d.times(o=h)),c=o,t=l.minus(d.times(o=t)),l=o;return o=i(e.minus(n),r,0,1),c=c.plus(o.times(h)),n=n.plus(o.times(r)),c.s=h.s=g.s,u=i(h,r,s*=2,m).minus(g).abs().comparedTo(i(c,n,s,m).minus(g).abs())<1?[h,r]:[c,n],y=a,u},u.toNumber=function(){return+A(this)},u.toPrecision=function(e,t){return null!=e&&rt(e,1,et),R(this,e,t,2)},u.toString=function(e){var t,i=this,r=i.s,o=i.e;return null===o?r?(t="Infinity",r<0&&(t="-"+t)):t="NaN":(null==e?t=o<=g||o>=f?st(it(i.c),o):at(it(i.c),o,"0"):10===e&&$?t=at(it((i=D(new M(i),_+o+1,m)).c),i.e,"0"):(rt(e,2,S.length,"Base"),t=n(at(it(i.c),o,"0"),10,e,r,!0)),r<0&&i.c[0]&&(t="-"+t)),t},u.valueOf=u.toJSON=function(){return A(this)},u._isBigNumber=!0,u[Symbol.toStringTag]="BigNumber",u[Symbol.for("nodejs.util.inspect.custom")]=u.valueOf,null!=t&&M.set(t),M}(),ct=class{key;left=null;right=null;constructor(e){this.key=e}},ht=class extends ct{constructor(e){super(e)}},dt=class{size=0;modificationCount=0;splayCount=0;splay(e){const t=this.root;if(null==t)return this.compare(e,e),-1;let i=null,n=null,r=null,o=null,s=t;const a=this.compare;let l;for(;;)if(l=a(s.key,e),l>0){let t=s.left;if(null==t)break;if(l=a(t.key,e),l>0&&(s.left=t.right,t.right=s,s=t,t=s.left,null==t))break;null==i?n=s:i.left=s,i=s,s=t}else{if(!(l<0))break;{let t=s.right;if(null==t)break;if(l=a(t.key,e),l<0&&(s.right=t.left,t.left=s,s=t,t=s.right,null==t))break;null==r?o=s:r.right=s,r=s,s=t}}return null!=r&&(r.right=s.left,s.left=o),null!=i&&(i.left=s.right,s.right=n),this.root!==s&&(this.root=s,this.splayCount++),l}splayMin(e){let t=e,i=t.left;for(;null!=i;){const e=i;t.left=e.right,e.right=t,t=e,i=t.left}return t}splayMax(e){let t=e,i=t.right;for(;null!=i;){const e=i;t.right=e.left,e.left=t,t=e,i=t.right}return t}_delete(e){if(null==this.root)return null;if(0!=this.splay(e))return null;let t=this.root;const i=t,n=t.left;if(this.size--,null==n)this.root=t.right;else{const e=t.right;t=this.splayMax(n),t.right=e,this.root=t}return this.modificationCount++,i}addNewRoot(e,t){this.size++,this.modificationCount++;const i=this.root;null!=i?(t<0?(e.left=i,e.right=i.right,i.right=null):(e.right=i,e.left=i.left,i.left=null),this.root=e):this.root=e}_first(){const e=this.root;return null==e?null:(this.root=this.splayMin(e),this.root)}_last(){const e=this.root;return null==e?null:(this.root=this.splayMax(e),this.root)}clear(){this.root=null,this.size=0,this.modificationCount++}has(e){return this.validKey(e)&&0==this.splay(e)}defaultCompare(){return(e,t)=>et?1:0}wrap(){return{getRoot:()=>this.root,setRoot:e=>{this.root=e},getSize:()=>this.size,getModificationCount:()=>this.modificationCount,getSplayCount:()=>this.splayCount,setSplayCount:e=>{this.splayCount=e},splay:e=>this.splay(e),has:e=>this.has(e)}}},ut=class e extends dt{root=null;compare;validKey;constructor(e,t){super(),this.compare=e??this.defaultCompare(),this.validKey=t??(e=>null!=e&&null!=e)}delete(e){return!!this.validKey(e)&&null!=this._delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){const t=this[Symbol.iterator]();let i;for(;i=t.next(),!i.done;)e(i.value,i.value,this)}add(e){const t=this.splay(e);return 0!=t&&this.addNewRoot(new ht(e),t),this}addAndReturn(e){const t=this.splay(e);return 0!=t&&this.addNewRoot(new ht(e),t),this.root.key}addAll(e){for(const t of e)this.add(t)}isEmpty(){return null==this.root}isNotEmpty(){return null!=this.root}single(){if(0==this.size)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}first(){if(0==this.size)throw"Bad state: No element";return this._first().key}last(){if(0==this.size)throw"Bad state: No element";return this._last().key}lastBefore(e){if(null==e)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(e)<0)return this.root.key;let t=this.root.left;if(null==t)return null;let i=t.right;for(;null!=i;)t=i,i=t.right;return t.key}firstAfter(e){if(null==e)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(e)>0)return this.root.key;let t=this.root.right;if(null==t)return null;let i=t.left;for(;null!=i;)t=i,i=t.left;return t.key}retainAll(t){const i=new e(this.compare,this.validKey),n=this.modificationCount;for(const e of t){if(n!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(e)&&0==this.splay(e)&&i.add(this.root.key)}i.size!=this.size&&(this.root=i.root,this.size=i.size,this.modificationCount++)}lookup(e){if(!this.validKey(e))return null;return 0!=this.splay(e)?null:this.root.key}intersection(t){const i=new e(this.compare,this.validKey);for(const e of this)t.has(e)&&i.add(e);return i}difference(t){const i=new e(this.compare,this.validKey);for(const e of this)t.has(e)||i.add(e);return i}union(e){const t=this.clone();return t.addAll(e),t}clone(){const t=new e(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}copyNode(e){if(null==e)return null;const t=new ht(e.key);return function e(t,i){let n,r;do{if(n=t.left,r=t.right,null!=n){const t=new ht(n.key);i.left=t,e(n,t)}if(null!=r){const e=new ht(r.key);i.right=e,t=r,i=e}}while(null!=r)}(e,t),t}toSet(){return this.clone()}entries(){return new mt(this.wrap())}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}[Symbol.iterator](){return new _t(this.wrap())}[Symbol.toStringTag]="[object Set]"},pt=class{tree;path=new Array;modificationCount=null;splayCount;constructor(e){this.tree=e,this.splayCount=e.getSplayCount()}[Symbol.iterator](){return this}next(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}current(){if(!this.path.length)return null;const e=this.path[this.path.length-1];return this.getValue(e)}rebuildPath(e){this.path.splice(0,this.path.length),this.tree.splay(e),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}findLeftMostDescendent(e){for(;null!=e;)this.path.push(e),e=e.left}moveNext(){if(this.modificationCount!=this.tree.getModificationCount()){if(null==this.modificationCount){this.modificationCount=this.tree.getModificationCount();let e=this.tree.getRoot();for(;null!=e;)this.path.push(e),e=e.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);let e=this.path[this.path.length-1],t=e.right;if(null!=t){for(;null!=t;)this.path.push(t),t=t.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===e;)e=this.path.pop();return this.path.length>0}},_t=class extends pt{getValue(e){return e.key}},mt=class extends pt{getValue(e){return[e.key,e.key]}},gt=e=>()=>e,ft=e=>{const t=e?(t,i)=>i.minus(t).abs().isLessThanOrEqualTo(e):gt(!1);return(e,i)=>t(e,i)?0:e.comparedTo(i)};function vt(e){const t=e?(t,i,n,r,o)=>t.exponentiatedBy(2).isLessThanOrEqualTo(r.minus(i).exponentiatedBy(2).plus(o.minus(n).exponentiatedBy(2)).times(e)):gt(!1);return(e,i,n)=>{const r=e.x,o=e.y,s=n.x,a=n.y,l=o.minus(a).times(i.x.minus(s)).minus(r.minus(s).times(i.y.minus(a)));return t(l,r,o,s,a)?0:l.comparedTo(0)}}var yt=e=>e,bt=e=>{if(e){const t=new ut(ft(e)),i=new ut(ft(e)),n=(e,t)=>t.addAndReturn(e),r=e=>({x:n(e.x,t),y:n(e.y,i)});return r({x:new lt(0),y:new lt(0)}),r}return yt},wt=e=>({set:e=>{kt=wt(e)},reset:()=>wt(e),compare:ft(e),snap:bt(e),orient:vt(e)}),kt=wt(),xt=(e,t)=>e.ll.x.isLessThanOrEqualTo(t.x)&&t.x.isLessThanOrEqualTo(e.ur.x)&&e.ll.y.isLessThanOrEqualTo(t.y)&&t.y.isLessThanOrEqualTo(e.ur.y),St=(e,t)=>{if(t.ur.x.isLessThan(e.ll.x)||e.ur.x.isLessThan(t.ll.x)||t.ur.y.isLessThan(e.ll.y)||e.ur.y.isLessThan(t.ll.y))return null;const i=e.ll.x.isLessThan(t.ll.x)?t.ll.x:e.ll.x,n=e.ur.x.isLessThan(t.ur.x)?e.ur.x:t.ur.x;return{ll:{x:i,y:e.ll.y.isLessThan(t.ll.y)?t.ll.y:e.ll.y},ur:{x:n,y:e.ur.y.isLessThan(t.ur.y)?e.ur.y:t.ur.y}}},$t=(e,t)=>e.x.times(t.y).minus(e.y.times(t.x)),Mt=(e,t)=>e.x.times(t.x).plus(e.y.times(t.y)),Rt=e=>Mt(e,e).sqrt(),Ct=(e,t,i)=>{const n={x:t.x.minus(e.x),y:t.y.minus(e.y)},r={x:i.x.minus(e.x),y:i.y.minus(e.y)};return $t(r,n).div(Rt(r)).div(Rt(n))},Tt=(e,t,i)=>{const n={x:t.x.minus(e.x),y:t.y.minus(e.y)},r={x:i.x.minus(e.x),y:i.y.minus(e.y)};return Mt(r,n).div(Rt(r)).div(Rt(n))},Dt=(e,t,i)=>t.y.isZero()?null:{x:e.x.plus(t.x.div(t.y).times(i.minus(e.y))),y:i},At=(e,t,i)=>t.x.isZero()?null:{x:i,y:e.y.plus(t.y.div(t.x).times(i.minus(e.x)))},Pt=class e{point;isLeft;segment;otherSE;consumedBy;static compare(t,i){const n=e.comparePoints(t.point,i.point);return 0!==n?n:(t.point!==i.point&&t.link(i),t.isLeft!==i.isLeft?t.isLeft?1:-1:Lt.compare(t.segment,i.segment))}static comparePoints(e,t){return e.x.isLessThan(t.x)?-1:e.x.isGreaterThan(t.x)?1:e.y.isLessThan(t.y)?-1:e.y.isGreaterThan(t.y)?1:0}constructor(e,t){void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=t}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const t=e.point.events;for(let e=0,i=t.length;e{const n=i.otherSE;t.set(i,{sine:Ct(this.point,e.point,n.point),cosine:Tt(this.point,e.point,n.point)})};return(e,n)=>{t.has(e)||i(e),t.has(n)||i(n);const{sine:r,cosine:o}=t.get(e),{sine:s,cosine:a}=t.get(n);return r.isGreaterThanOrEqualTo(0)&&s.isGreaterThanOrEqualTo(0)?o.isLessThan(a)?1:o.isGreaterThan(a)?-1:0:r.isLessThan(0)&&s.isLessThan(0)?o.isLessThan(a)?-1:o.isGreaterThan(a)?1:0:s.isLessThan(r)?-1:s.isGreaterThan(r)?1:0}}},Ft=class e{events;poly;_isExteriorRing;_enclosingRing;static factory(t){const i=[];for(let n=0,r=t.length;n0&&(e=i)}let t=e.segment.prevInResult(),i=t?t.prevInResult():null;for(;;){if(!t)return null;if(!i)return t.ringOut;if(i.ringOut!==t.ringOut)return i.ringOut?.enclosingRing()!==t.ringOut?t.ringOut:t.ringOut?.enclosingRing();t=i.prevInResult(),i=t?t.prevInResult():null}}},zt=class{exteriorRing;interiorRings;constructor(e){this.exteriorRing=e,e.poly=this,this.interiorRings=[]}addInterior(e){this.interiorRings.push(e),e.poly=this}getGeom(){const e=this.exteriorRing.getGeom();if(null===e)return null;const t=[e];for(let e=0,i=this.interiorRings.length;e0?(this.tree.delete(t),i.push(e)):(this.segments.push(t),t.prev=n)}else{if(n&&r){const e=n.getIntersection(r);if(null!==e){if(!n.isAnEndpoint(e)){const t=this._splitSafely(n,e);for(let e=0,n=t.length;e0)return-1;const n=t.comparePoint(e.rightSE.point);return 0!==n?n:-1}if(i.isGreaterThan(n)){if(s.isLessThan(a)&&s.isLessThan(c))return-1;if(s.isGreaterThan(a)&&s.isGreaterThan(c))return 1;const i=t.comparePoint(e.leftSE.point);if(0!==i)return i;const n=e.comparePoint(t.rightSE.point);return n<0?1:n>0?-1:1}if(s.isLessThan(a))return-1;if(s.isGreaterThan(a))return 1;if(r.isLessThan(o)){const i=t.comparePoint(e.rightSE.point);if(0!==i)return i}if(r.isGreaterThan(o)){const i=e.comparePoint(t.rightSE.point);if(i<0)return 1;if(i>0)return-1}if(!r.eq(o)){const e=l.minus(s),t=r.minus(i),h=c.minus(a),d=o.minus(n);if(e.isGreaterThan(t)&&h.isLessThan(d))return 1;if(e.isLessThan(t)&&h.isGreaterThan(d))return-1}return r.isGreaterThan(o)?1:r.isLessThan(o)||l.isLessThan(c)?-1:l.isGreaterThan(c)?1:e.idt.id?1:0}constructor(e,t,i,n){this.id=++Ht,this.leftSE=e,e.segment=this,e.otherSE=t,this.rightSE=t,t.segment=this,t.otherSE=e,this.rings=i,this.windings=n}static fromRing(t,i,n){let r,o,s;const a=Pt.comparePoints(t,i);if(a<0)r=t,o=i,s=1;else{if(!(a>0))throw new Error(`Tried to create degenerate segment at [${t.x}, ${t.y}]`);r=i,o=t,s=-1}const l=new Pt(r,!0),c=new Pt(o,!1);return new e(l,c,[n],[s])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,t=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e.isLessThan(t)?e:t},ur:{x:this.rightSE.point.x,y:e.isGreaterThan(t)?e:t}}}vector(){return{x:this.rightSE.point.x.minus(this.leftSE.point.x),y:this.rightSE.point.y.minus(this.leftSE.point.y)}}isAnEndpoint(e){return e.x.eq(this.leftSE.point.x)&&e.y.eq(this.leftSE.point.y)||e.x.eq(this.rightSE.point.x)&&e.y.eq(this.rightSE.point.y)}comparePoint(e){return kt.orient(this.leftSE.point,e,this.rightSE.point)}getIntersection(e){const t=this.bbox(),i=e.bbox(),n=St(t,i);if(null===n)return null;const r=this.leftSE.point,o=this.rightSE.point,s=e.leftSE.point,a=e.rightSE.point,l=xt(t,s)&&0===this.comparePoint(s),c=xt(i,r)&&0===e.comparePoint(r),h=xt(t,a)&&0===this.comparePoint(a),d=xt(i,o)&&0===e.comparePoint(o);if(c&&l)return d&&!h?o:!d&&h?a:null;if(c)return h&&r.x.eq(a.x)&&r.y.eq(a.y)?null:r;if(l)return d&&o.x.eq(s.x)&&o.y.eq(s.y)?null:s;if(d&&h)return null;if(d)return o;if(h)return a;const u=((e,t,i,n)=>{if(t.x.isZero())return At(i,n,e.x);if(n.x.isZero())return At(e,t,i.x);if(t.y.isZero())return Dt(i,n,e.y);if(n.y.isZero())return Dt(e,t,i.y);const r=$t(t,n);if(r.isZero())return null;const o={x:i.x.minus(e.x),y:i.y.minus(e.y)},s=$t(o,t).div(r),a=$t(o,n).div(r),l=e.x.plus(a.times(t.x)),c=i.x.plus(s.times(n.x)),h=e.y.plus(a.times(t.y)),d=i.y.plus(s.times(n.y));return{x:l.plus(c).div(2),y:h.plus(d).div(2)}})(r,this.vector(),s,e.vector());return null===u?null:xt(n,u)?kt.snap(u):null}split(t){const i=[],n=void 0!==t.events,r=new Pt(t,!0),o=new Pt(t,!1),s=this.rightSE;this.replaceRightSE(o),i.push(o),i.push(r);const a=new e(r,s,this.rings.slice(),this.windings.slice());return Pt.comparePoints(a.leftSE.point,a.rightSE.point)>0&&a.swapEvents(),Pt.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),n&&(r.checkForConsuming(),o.checkForConsuming()),i}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let e=0,t=this.windings.length;e0){const e=i;i=n,n=e}if(i.prev===n){const e=i;i=n,n=e}for(let e=0,t=n.rings.length;e1===e.length&&e[0].isSubject;this._isInResult=i(e)!==i(t);break}}return this._isInResult}},Bt=class{poly;isExterior;segments;bbox;constructor(e,t,i){if(!Array.isArray(e)||0===e.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=t,this.isExterior=i,this.segments=[],"number"!=typeof e[0][0]||"number"!=typeof e[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const n=kt.snap({x:new lt(e[0][0]),y:new lt(e[0][1])});this.bbox={ll:{x:n.x,y:n.y},ur:{x:n.x,y:n.y}};let r=n;for(let t=1,i=e.length;tNt.run("union",e,t),Ut=(e,...t)=>Nt.run("intersection",e,t),Gt=(e,...t)=>Nt.run("difference",e,t);kt.set;const Vt=/^#[0-9a-fA-F]{6}$/;function Kt(e,t){return"string"==typeof e&&Vt.test(e)?e:t}const Yt="(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])",Xt=new RegExp(`^rgb\\(${Yt}, ${Yt}, ${Yt}\\)$`);function Zt(e){if(!Array.isArray(e)||e.length<3)return null;const t=e.slice(0,3);if(!t.every(e=>"number"==typeof e&&Number.isFinite(e)))return null;const[i,n,r]=t.map(e=>Math.round(Math.min(255,Math.max(0,e))));return`rgb(${i}, ${n}, ${r})`}function Jt(e){const t=Math.max(0,Math.min(120,(e-40)/140*120));return`hsl(${Math.round(t)}, 85%, 55%)`}function Qt(e,t){if(!(Number.isFinite(e)&&t>0))return e;const i=Math.round(e/t)*t;return Math.abs(i-e)<=1e-9*t?e:i}function ei(e,t,i,n=1/0){if(!(i>0&&e?.every(Number.isFinite)&&t?.every(Number.isFinite)))return[t[0],t[1]];const r=t[0]-e[0],o=t[1]-e[1];if(Math.abs(r)+Math.abs(o)<=1e-12)return[e[0],e[1]];const s=Math.PI/4;let a=Math.atan2(o,r);a<0&&(a+=2*Math.PI);const l=Math.floor(a/s+.5)%8,[c,h]=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]][l],d=c*c+h*h;let u=Math.max(0,Math.round((r*c+o*h)/(i*d)));if(Number.isFinite(n)&&n>=0){const t=(e,t)=>{if(!t)return 1/0;const r=t>0?n-e:e+n;return Math.max(0,Math.floor((r+1e-9*i)/i))};u=Math.min(u,t(e[0],c),t(e[1],h))}return[e[0]+c*u*i,e[1]+h*u*i]}function ti(e,t){if(t){const t=e/2.54;let i=Math.floor(t/12),n=Math.round(t-12*i);return 12===n&&(i+=1,n=0),`${i}′ ${n}″`}return`${(e/100).toFixed(2)} m`}function ii(e,t,i=1){const n=e[0].toFixed(i),r=e[1].toFixed(i),o=t[0].toFixed(i),s=t[1].toFixed(i),a=n=3?e.poly:e&&null!=e.x&&null!=e.y&&null!=e.w&&null!=e.h?[[e.x,e.y],[e.x+e.w,e.y],[e.x+e.w,e.y+e.h],[e.x,e.y+e.h]]:null}function ri(e){const t=[];for(const i of e||[])i?.poly?.length>=3?t.push({poly:i.poly.map(e=>e.join(",")).join(" ")}):i&&null!=i.x&&null!=i.y&&null!=i.w&&null!=i.h&&t.push({rect:{x:i.x,y:i.y,w:i.w,h:i.h,rx:.03*Math.min(i.w,i.h)}});return t}function oi(e){const t=[],i=new Set;for(const n of e||[]){const e=ni(n);if(e)for(let n=0;n=90?e-=180:e<-90&&(e+=180),n.step&&n.step>0){const i=Math.sqrt(d),o=Math.min(Math.max(n.length||0,0)/2,i/2);let a=Math.round(u*i/n.step)*n.step;Math.abs(u*i-i/2)<=n.step/2&&(a=i/2),a=Math.max(o,Math.min(i-o,a));const l=a/i;r={x:t+l*c,y:s+l*h,angle:e}}else r={x:p[0],y:p[1],angle:e}}}return r}function ai(e,t,i){let n=null,r=1/0;for(let o=0;o=r)continue;r=_;const m=Math.sqrt(u),g=(i>0?Math.max(0,Math.min(m,Math.round(p*m/i)*i)):p*m)/m;n=[s+g*h,a+g*d]}return n}function li(e,t,i,n,r,o=1){const s=t*Math.PI/180,a=[Math.cos(s),Math.sin(s)];let l=null,c=o;for(const t of oi(n)){const i=[[t[0],t[1]],[t[2],t[3]]],n=t=>Math.abs(a[0]*(t[1]-e[1])-a[1]*(t[0]-e[0]));if(n(i[0])>o||n(i[1])>o)continue;const r=(i[0][0]-e[0])*a[0]+(i[0][1]-e[1])*a[1],s=(i[1][0]-e[0])*a[0]+(i[1][1]-e[1])*a[1],h=Math.min(r,s),d=Math.max(r,s),u=h>0?h:d<0?-d:0;u[e[0]+a[0]*t,e[1]+a[1]*t],g=(h+d)/2;return{wallA:m(h),wallB:m(d),sideA:p,sideB:_,midA:m((h-u)/2),midB:m((u+d)/2),wallCenter:m(g),centered:Math.abs(g)<=r}}function ci(e,t,i=!1,n){if("passage"===e)return 1;if(null==t||"unavailable"===t||"unknown"===t)return"window"===e?0:1;const r="string"==typeof n?n.trim()?Number(n):NaN:Number(n),o=null!=n&&Number.isFinite(r)?Math.max(0,Math.min(1,r/100)):function(e){return["on","open","home","detected","playing","cleaning"].includes(String(e))}(t)?1:0;return i?1-o:o}function hi(e){const t=Number.isFinite(e)?Math.max(0,Math.min(1,e)):0;return Math.min(1,Math.max(0,.05*Math.round(t/.05)))}function di(e,t){return(Number.isFinite(e)&&e>0?e:0)*(Number.isFinite(t)?Math.max(0,Math.min(1,t)):0)}function ui(e){return"passage"===e.type?[]:[e.contact,e.lock].filter(e=>"string"==typeof e&&e.length>0)}function pi(e,t,i=200){const n=t.trim().toLowerCase();return(n?e.filter(e=>e.label.toLowerCase().includes(n)||e.value.toLowerCase().includes(n)):e).slice(0,Math.max(0,i))}function _i(e,t,i=.001){return Math.abs(e[0]-t[0])e[1]!=l>e[1]&&e[0]<(a-o)*(e[1]-s)/(l-s)+o&&(i=!i)}return i}function gi(e,t,i){const n=i[0]-t[0],r=i[1]-t[1],o=n*n+r*r;let s=o?((e[0]-t[0])*n+(e[1]-t[1])*r)/o:0;return s=Math.max(0,Math.min(1,s)),Math.hypot(e[0]-(t[0]+s*n),e[1]-(t[1]+s*r))}function fi(e,t){if(!t||t.length<2)return null;let i=null,n=1/0;for(let r=0;rr&&s<-r||o<-r&&s>r)&&(a>r&&l<-r||a<-r&&l>r)}function ki(e,t=24){const i=e.map(e=>e[0]),n=e.map(e=>e[1]),r=Math.min(...i),o=Math.max(...i),s=Math.min(...n),a=Math.max(...n),l=Math.max(o-r,a-s)||1;let c=0,h=0,d=0;for(let t=0;t1e-9?[h/(3*c),d/(3*c)]:[(r+o)/2,(s+a)/2],p=(t,i)=>{const n=((t,i)=>{if(!mi([t,i],e))return-1/0;let n=1/0;for(let r=0;rm&&(m=c,_=[n,l])}if(_){const[e,i]=_,n=(o-r)/t,l=(a-s)/t;for(let t=-4;t<=4;t++)for(let r=-4;r<=4;r++){const o=e+n*t/4,s=i+l*r/4,a=p(o,s);a>m&&(m=a,_=[o,s])}}return _||xi(e)||e[0]}function xi(e,t=1e-6){if(!e||e.length<3)return null;const i=e.length,n=[e.reduce((e,t)=>e+t[0],0)/i,e.reduce((e,t)=>e+t[1],0)/i];if(yi(n,e,t))return n;for(let n=0;n$i(e,t,i));return n.filter(e=>!n.some(t=>t!==e&&$i(t,e,i)))}function Ci(e){if(!e||e.length<3)return 0;let t=0;for(let i=0;i[e[0],e[1]]),[e[0][0],e[0][1]]]]}function Di(e,t){if(!e||!t||e.length<3||t.length<3)return null;const i=Wt(Ti(e),Ti(t));if(1!==i.length)return null;if(1!==i[0].length)return null;const n=i[0][0].slice(0,-1).map(e=>[e[0],e[1]]);return n.length>=3?n:null}function Ai(e,t,i){for(let n=0;n1&&_i(i[0],i[i.length-1],t)&&i.pop(),i}function Fi(e,t,i=1e-6){if(!e||e.length<3||!t||t.length<2)return null;const n=t[0],r=t[t.length-1];if(_i(n,r,i))return null;const o=Ai(e,n,i),s=Ai(e,r,i);if(o<0||s<0)return null;const a=t.slice(1,-1);for(const t of a)if(!yi(t,e,i))return null;for(let i=0;i{const s=[t];let a=(n+1)%e.length;for(let t=0;t<=e.length&&(s.push(e[a]),a!==o);t++)a=(a+1)%e.length;return s.push(r),Pi(s,i)};let c,h;if(o===s){const s=Pi([...t],i);if(s.length<3||Ci(s)<=i)return null;const a=[];for(let i=0;i=0?t:[...t].reverse();for(const e of i)a.push(e)}c=Pi(a,i),h=s}else c=Pi([...l(n,o,r,s),...[...a].reverse()],i),h=Pi([...l(r,s,n,o),...a],i);return c.length<3||h.length<3||Ci(c)<=i||Ci(h)<=i||Math.abs(Ci(c)+Ci(h)-Ci(e))>Math.max(i,1e-6*Ci(e))?null:[c,h]}function zi(e,t,i){const[n,r]=e.split(":");return"device"===n?r:"entity"===n?"lg_"+r:t&&t.startsWith("v_")?t:i()}function Ii(e){return e.length?Math.round(e.reduce((e,t)=>e+t,0)/e.length):null}function Oi(e,t){if(t>e[2]/e[3]){const i=e[3],n=e[3]*t;return{x:e[0]-(n-e[2])/2,y:e[1],w:n,h:i}}const i=e[2],n=e[2]/t;return{x:e[0],y:e[1]-(n-e[3])/2,w:i,h:n}}function Ei(e,t,i,n){if(e.length<2)return;const r=t.x+n,o=t.x+t.w-n,s=t.y+n,a=t.y+t.h-n;for(let t=0;t<60;t++){let t=!1;for(let n=0;n=0)i=t.slice(0,r).trim(),n=t.slice(r+1).trim();else{const e=t.split(".");e.length>2&&(i=e.slice(0,2).join("."),n=e.slice(2).join("."))}return/^[a-z0-9_]+\.[a-z0-9_]+$/.test(i)?r>=0&&!n||n&&!/^[a-zA-Z0-9_.-]+$/.test(n)?null:n?{entity:i,attr:n}:{entity:i}:null}function Yi(e,t){const i=String(e??"").trim(),n=String(t??"").trim(),r=Ki(n?`${i}:${n}`:i);return r?`{${r.entity}${r.attr?`:${r.attr}`:""}}`:""}function Xi(e,t,i){const n=String(t??"").trim();if(!n)return null;const r=e?.states?.[n];if(!r)return null;const o=String(i??"").trim(),s=e=>e.slice(0,60);if(o){const t=function(e){if(null==e)return null;if(Array.isArray(e)){const t=e.map(e=>null==e?"":String(e)).join(", ");return t?t.slice(0,60):null}if("object"==typeof e)return null;const t=String(e);return""===t?null:t.slice(0,60)}(r.attributes?.[o]);if(null===t)return null;const i=e?.formatEntityAttributeValue;if("function"==typeof i)try{const t=i.call(e,r,o);if("string"==typeof t&&""!==t)return{text:s(t),formatted:!0}}catch{}return{text:t,formatted:!1}}const a=r.state;if(null==a||""===a)return null;const l=e?.formatEntityState;if("function"==typeof l)try{const t=l.call(e,r);if("string"==typeof t&&""!==t)return{text:s(t),formatted:!0}}catch{}return{text:s(String(a)),formatted:!1}}function Zi(e,t,i){const n=String(t??"").trim(),r=String(i??"").trim()||n;if(!r)return e.text;const o=e.formatted&&n?function(e,t){if(!t)return e;const i=e.replace(/\s+$/,"");return i.endsWith(t)?i.slice(0,i.length-t.length).replace(/\s+$/,""):e}(e.text,n):e.text;return`${o} ${r}`}function Ji(e,t){const i=(t?.entity||"").trim();if(!i)return"";const n=e?.states?.[i],r=n?.state;if(!n||null==r||""===r||"unavailable"===r||"unknown"===r)return Gi;const o=(t?.attr||"").trim(),s=Xi(e,i,o||null);if(null===s)return Gi;return Zi(s,o?"":String(n.attributes?.unit_of_measurement??"").trim(),t?.unit)}function Qi(e,t,i,n=()=>!0){const r=e??"";let o=!1;const s=r.replace(/\{([^{}\r\n]+)\}/g,(e,t)=>{const r=Ki(t);return r?(o=!0,n(r.entity||"")?Ji(i,r):Gi):e});if(o)return s;const a=(t?.entity||"").trim();if(!a)return r;if(!n(a)){const e=r.indexOf(Vi);return e>=0?r.slice(0,e)+Gi+r.slice(e+2):r?`${r} ${Gi}`:Gi}const l=Ji(i,t),c=r.indexOf(Vi);return c>=0?r.slice(0,c)+l+r.slice(c+2):r?`${r} ${l}`:l}const en=20;function tn(e){const t=Number(e?.scale);if(Number.isFinite(t)&&t>0)return Math.min(20,Math.max(.15,t));return{s:.7,m:1,l:1.5}[String(e?.size??"")]??1}function nn(e,t){if(!t)return e;let i=e;for(const[e,n]of Object.entries(t))i=i.split("{"+e+"}").join(String(n));return i}const rn="#55606c",on=.55,sn=20,an=25,ln={c:"#607d8b",a:.18};function cn(e,t=ln){const i=e&&"object"==typeof e?e:null,n=i?.a;return{c:Kt(i?.c,t.c),a:"number"==typeof n&&Number.isFinite(n)?Math.min(1,Math.max(0,n)):t.a}}function hn(e,t){const i=cn(e),n=t?.settings;if("custom"!==n?.fill_mode)return i;const r=n?.custom_fill;return r&&"object"==typeof r?cn(r,i):i}function dn(e,t,i){const n=(e,t)=>"number"==typeof e&&Number.isFinite(e)?e:t,r=n(e,20),o=n(t,25),s=n(i?.settings?.temp_min,r),a=n(i?.settings?.temp_max,o);return{min:Math.min(s,a),max:Math.max(s,a)}}function un(e){const t=e?.settings||{},i=!e?.plan_url,n="glow"===t.fill_mode;return{showBorders:t.show_borders??i,showNames:t.show_names??i,color:Kt(t.room_color,rn),opacity:"number"==typeof t.room_opacity?Math.min(1,Math.max(0,t.room_opacity)):.55,fill:["lqi","light","temp","custom"].includes(t.fill_mode)?t.fill_mode:"none",customFill:cn(t.custom_fill),glow:"boolean"==typeof t.glow_enabled?t.glow_enabled:n,tempMin:"number"==typeof t.temp_min?t.temp_min:20,tempMax:"number"==typeof t.temp_max?t.temp_max:25,showLqi:"boolean"==typeof t.show_lqi?t.show_lqi:null,cardFontScale:"number"==typeof t.card_font_scale&&t.card_font_scale>0?Math.min(3,Math.max(.5,t.card_font_scale)):1,labelTemp:!0===t.label_temp,labelHum:!0===t.label_hum,labelLqi:!0===t.label_lqi,labelLight:!0===t.label_light,bgColor:Kt(t.bg_color,null),hideDecor:!0===t.hide_decor,hideOpenings:!0===t.hide_openings}}function pn(e,t){if(t.bgColor)return t.bgColor;const i=e?.bg_color;return Kt(i,"")}function _n(e){return!1!==e?.show_room_tooltip}const mn={light_on:{c:"#ffd45c",a:.18},light_off:{c:"#9aa0a6",a:.14},light_none:{c:"#6b7480",a:0},temp_cold:{c:"#4fc3f7",a:.18},temp_ok:{c:"#66d17a",a:.18},temp_hot:{c:"#ffd45c",a:.18},lqi_low:{c:"#f25a4a",a:.18},lqi_high:{c:"#4bd28f",a:.18},glow_base:{c:"#0d1b2a",a:.5},glow_light:{c:"#ffd9a0",a:.85},wall_fill:{c:"#ffffff",a:1}};function gn(e){const t={},i=e?.fill_colors||{};for(const e of Object.keys(mn)){const n=mn[e],r=i[e];t[e]={c:Kt(r?.c,n.c),a:r&&"number"==typeof r.a?Math.min(1,Math.max(0,r.a)):n.a}}return t}function fn(e,t,i){const n=Math.min(1,Math.max(0,i)),r=[1,3,5].map(t=>parseInt(e.slice(t,t+2),16)),o=[1,3,5].map(e=>parseInt(t.slice(e,e+2),16)),s=r.map((e,t)=>Math.round(e+(o[t]-e)*n));return"#"+s.map(e=>e.toString(16).padStart(2,"0")).join("")}function vn(e,t,i,n,r,o,s,a=ln){const l=function(e,t,i,n,r,o,s,a=ln){if("custom"===e)return cn(a);if("lqi"===e){if(null==t)return null;const e=(t-40)/140;return{c:fn(s.lqi_low.c,s.lqi_high.c,e),a:s.lqi_low.a+(s.lqi_high.a-s.lqi_low.a)*Math.min(1,Math.max(0,e))}}if("light"===e)return"none"===i?s.light_none.a>0?s.light_none:null:"on"===i?s.light_on:s.light_off;if("temp"===e){if(null==n)return null;const e=Math.min(r,o),t=Math.max(r,o);return nt?s.temp_hot:s.temp_ok}return null}(e,t,i,n,r,o,s,a);return l?{color:l.c,opacity:l.a,mode:e}:null}const yn={blind:["mdi:blinds","mdi:blinds-open"],shade:["mdi:blinds","mdi:blinds-open"],shutter:["mdi:window-shutter","mdi:window-shutter-open"],curtain:["mdi:curtains-closed","mdi:curtains"],window:["mdi:window-closed","mdi:window-open"],awning:["mdi:awning-outline","mdi:awning"],door:["mdi:door-closed","mdi:door-open"],garage:["mdi:garage","mdi:garage-open"],gate:["mdi:gate","mdi:gate-open"],damper:["mdi:circle-slice-8","mdi:circle-outline"]},bn=[["mdi:roller-shade-closed","mdi:roller-shade"],["mdi:blinds-horizontal-closed","mdi:blinds-horizontal"],["mdi:garage-variant","mdi:garage-open-variant"],["mdi:door","mdi:door-open"]];function wn(e){for(const t of[...Object.values(yn),...bn])if(e===t[0]||e===t[1])return t;return null}function kn(e,t,i,n,r){if(!n||"unavailable"===n||"unknown"===n)return e;if(r){const i="cover"===t?wn(e):null;return i?"closed"===n?i[0]:i[1]:e}if("binary_sensor"===t){if("door"===i)return"on"===n?"mdi:door-open":"mdi:door-closed";if("window"===i)return"on"===n?"mdi:window-open":"mdi:window-closed";if("garage_door"===i)return"on"===n?"mdi:garage-open-variant":"mdi:garage-variant"}if("cover"===t){const t=yn[String(i||"")];if(t)return"closed"===n?t[0]:t[1];const r=wn(e);return r?"closed"===n?r[0]:r[1]:e}return"lock"===t?"locked"===n?"mdi:lock":"mdi:lock-open-variant":"light"===t&&"mdi:lightbulb"===e&&"on"===n?"mdi:lightbulb-on":e}function xn(e){const t=Math.min(4e4,Math.max(1e3,e))/100,i=t<=66?255:329.698727446*Math.pow(t-60,-.1332047592),n=t<=66?99.4708025861*Math.log(t)-161.1195681661:288.1221695283*Math.pow(t-60,-.0755148492),r=t>=66?255:t<=19?0:138.5177312231*Math.log(t-10)-305.0447927307,o=e=>Math.round(Math.min(255,Math.max(0,e)));return[o(i),o(n),o(r)]}const Sn=1/2.2;function $n(e){const t=/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/.exec(e);return t?"#"+t.slice(1).map(e=>Math.min(255,Number(e)).toString(16).padStart(2,"0")).join(""):null}function Mn(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;const t=e;if(Object.keys(t).some(e=>"c"!==e&&"bri"!==e))return null;const i=Kt(t.c,null);return i?void 0===t.bri||null===t.bri?{c:i}:"number"!=typeof t.bri||!Number.isFinite(t.bri)||t.bri<.01||t.bri>1?null:{c:i,bri:t.bri}:null}function Rn(e,t,i){const n=Mn(t),r=e?.attributes||{},o=n?.bri??function(e){const t=e?.attributes?.brightness,i="number"==typeof t?t:"string"==typeof t&&""!==t.trim()?Number(t):Number.NaN;return Number.isFinite(i)?Math.max(0,Math.min(1,i/255)):1}(e);if(n)return{c:n.c,bri:o};const s=Zt(r.rgb_color);if(s)return{c:$n(s)||Kt(i,"#ffd9a0"),bri:o};const a=Number(r.color_temp_kelvin)||(Number(r.color_temp)>0?1e6/Number(r.color_temp):NaN);return Number.isFinite(a)&&a>0?{c:(l=xn(a),"#"+l.slice(0,3).map(e=>Math.min(255,Math.max(0,Math.round(Number(e)||0))).toString(16).padStart(2,"0")).join("")),bri:o}:{c:Kt(i,"#ffd9a0"),bri:o};var l}function Cn(e,t,i){return"on"===e?.state?Rn(e,t,i):null}function Tn(e,t=1){const i=Math.max(0,Math.min(1,Number.isFinite(e)?e:1)),n=.7*Math.max(0,Math.min(1,Number.isFinite(t)?t:1))*(.4+.6*Math.pow(i,Sn));return Math.max(0,Math.min(1,n))}function Dn(e){return e.startsWith("light.")||e.startsWith("switch.")}function An(e,t,i=1e-6){const n=[];if(!e||!t||e.length<3||t.length<3)return n;for(let r=0;ru||l>u)continue;const p=(r[0]-o[0])*h+(r[1]-o[1])*d,_=(s[0]-o[0])*h+(s[1]-o[1])*d,m=Math.max(0,Math.min(p,_)),g=Math.min(c,Math.max(p,_));g-m>i&&n.push([o[0]+h*m,o[1]+d*m,o[0]+h*g,o[1]+d*g])}}return n}function Pn(e,t,i=1e-6){const n=[];for(const r of e){const e=[r[0],r[1]],o=[r[2],r[3]],s=o[0]-e[0],a=o[1]-e[1],l=Math.hypot(s,a);if(lo||r>o)continue;const s=(n[0]-e[0])*c+(n[1]-e[1])*h,a=(n[2]-e[0])*c+(n[3]-e[1])*h,u=Math.max(0,Math.min(s,a)),p=Math.min(l,Math.max(s,a));p-u>i&&d.push([u,p])}if(!d.length){n.push([e[0],e[1],o[0],o[1]]);continue}d.sort((e,t)=>e[0]-t[0]);let u=0;for(const[t,r]of d)t-u>i&&n.push([e[0]+c*u,e[1]+h*u,e[0]+c*t,e[1]+h*t]),u=Math.max(u,r);l-u>i&&n.push([e[0]+c*u,e[1]+h*u,o[0],o[1]])}return n}function Fn(e,t,i=1e-6){const n=[];for(let t=0;t{if("string"!=typeof e||!e)return;const i=En(e);i.startsWith("/api/houseplan/content/")&&t.add(i)};for(const t of e?.spaces||[]){i(t?.plan_url);for(const e of t?.markers||[])for(const t of e?.pdfs||[])i(t?.url)}for(const t of e?.markers||[])for(const e of t?.pdfs||[])i(e?.url);return t}function En(e){return e?e.startsWith("/houseplan_files/plans/")?"/api/houseplan/content/plans/_/"+e.slice(23):e.startsWith("/houseplan_files/files/")?"/api/houseplan/content/files/"+e.slice(23):e:""}function Nn(e,t){const i=t?.settings?.fill_mode;return"none"===i||"lqi"===i||"light"===i||"temp"===i||"custom"===i?i:e}function Hn(e,t){const i=t?.settings;return"boolean"==typeof i?.glow?i.glow:"glow"===i?.fill_mode||e}function Ln(e,t,i,n){if(!t||!i||t===i)return e;const r="/files/"+t+"/",o="/files/"+i+"/";return e.map(e=>{if(!e.url.includes(r))return e;const t=e.url.split(r)[1]||"",[i,s]=[t.split("?")[0],t.includes("?")?"?"+t.split("?")[1]:""];if(n){const t=n[decodeURIComponent(i)]??n[i];return t?{...e,url:e.url.split(r+i)[0]+o+encodeURIComponent(t)+s}:e}return{...e,url:e.url.split(r).join(o)}})}function Bn(e,t=1){const i=Number(e);return Number.isFinite(i)&&i>0?Math.min(3,Math.max(.5,i)):t}function qn(e,t,i){let n=null,r=null;for(const o of t){if(!(Math.abs(o[0]-e[0])<1e-6&&Math.abs(o[1]-e[1])<1e-6)){if(Math.abs(o[0]-e[0])<=i){const t=Math.abs(o[1]-e[1]);t>1e-6&&(!n||t1e-6&&(!r||t"number"==typeof e&&Number.isFinite(e),tr=(e,t,i)=>Math.min(i,Math.max(t,e));function ir(e){return e.elevation<=-6?"night":e.elevation>=6?"day":e.rising?"dawn":"dusk"}function nr(e){const t=(Math.floor(Number(e)||0)%1440+1440)%1440;return t>=300&&t<480?"dawn":t>=480&&t<1080?"day":t>=1080&&t<1260?"dusk":"night"}function rr(e){const t=ir(e),i=e.azimuth*Math.PI/180;return{sunX:50-42*Math.sin(i),sunY:78-tr(e.elevation,0,90)/90*64,sunOpacity:"night"===t?0:tr((e.elevation+6)/12,0,1)}}function or(e){const t=(Math.floor(Number(e)||0)%1440+1440)%1440;if(t<300||t>=1260)return{sunX:50,sunY:78,sunOpacity:0};const i=(t-300)/960,n=(t-300)/120,r=(1260-t)/120;return{sunX:8+84*i,sunY:78-64*Math.sin(i*Math.PI),sunOpacity:Math.max(.18,Math.min(n,r,1))}}function sr(e,t=new Date){const i=function(e){const t=e?.states?.["sun.sun"]?.attributes;return t&&er(t.azimuth)&&er(t.elevation)&&"boolean"==typeof t.rising?{azimuth:Zn(t.azimuth),elevation:t.elevation,rising:t.rising}:null}(e);if(i)return{phase:ir(i),source:"sun",...rr(i)};const n="number"==typeof t?t:function(e=new Date){return 60*e.getHours()+e.getMinutes()}(t);return{phase:nr(n),source:"clock",...or(n)}}function ar(e){return`${e.source}|${e.phase}|${e.sunX.toFixed(2)}|${e.sunY.toFixed(2)}|`+e.sunOpacity.toFixed(3)}const lr=[[-90,"#070c14"],[-12,"#070c14"],[-4,"#131a28"],[0,"#4a3527"],[10,"#e8ddcf"],[30,"#ffffff"],[90,"#ffffff"]],cr=e=>Math.min(1,Math.max(0,e));function hr(e,t,i=6){const n=e.angle*Math.PI/180,r=[Math.sin(n),-Math.cos(n)],o=n=>{const o=[e.x+r[0]*i*n,e.y+r[1]*i*n];return t.find(e=>e.poly.length>=3&&mi(o,e.poly))||null},s=o(1),a=o(-1);return s&&a?null:s||a?s?{normal:[-r[0],-r[1]],roomId:s.id}:{normal:r,roomId:a.id}:null}function dr(e,t,i){return i>0&&e[0]*t[0]+e[1]*t[1]>.05}function ur(e,t,i,n){return[[e[0],e[1]],[t[0],t[1]],[t[0]+i[0]*n,t[1]+i[1]*n],[e[0]+i[0]*n,e[1]+i[1]*n]]}function pr(e,t){return _r(e,t)}function _r(...e){try{if(!e.length||e.some(e=>e.length<3))return[];const t=e.map(e=>[[...e.map(e=>[e[0],e[1]]),[e[0][0],e[0][1]]]]),i=Ut(t[0],...t.slice(1)),n=[];for(const e of i){const t=e[0];!Array.isArray(t)||t.length<4||n.push(t.slice(0,t.length-1).map(e=>[e[0],e[1]]))}return n}catch{return[]}}function mr(e,t,i,n,r,o,s,a="inner"){if(!(n>0))return[];const l=Jn(i,r),c=[-l[0],-l[1]],h=function(e){const t=Math.min(90,Math.max(0,e));return.7*(.8+1.7*Math.pow(1-t/90,1.6))}(n),d=[];for(const i of t){if(!(i.length>0))continue;const t=hr(i,e);if(!t||!dr(t.normal,l,n))continue;const r=e.find(e=>e.id===t.roomId);if(!r)continue;const u=o&&o[t.roomId]||r.poly,p=i.angle*Math.PI/180,_=i.length/2,m=[-t.normal[0],-t.normal[1]],g=Math.max(0,s?.[i.id]||0),f=Math.cos(p)*_,v=Math.sin(p)*_,y="outer"===a?-1:1,b=i.x+m[0]*g*y/2,w=i.y+m[1]*g*y/2,k=[b-f,w-v],x=[b+f,w+v],S=h*i.length,$=ur(k,x,c,S);let M,R=pr($,u);if("outer"===a&&g>0){const e=i.x+m[0]*g/2,t=i.y+m[1]*g/2,n=[e-f,t-v],r=[e+f,t+v],o=[[b-f,w-v],[b+f,w+v],[e+f,t+v],[e-f,t-v]];R=[..._r($,ur(n,r,c,S),u),..._r($,o)],M=[k,x,n,r]}if(!R.length)continue;const C=c[0]*m[0]+c[1]*m[1];d.push({openingId:i.id,roomId:t.roomId,polys:R,a:k,b:x,rimSources:M,dir:c,len:S,normal:m,depth:S*C})}return d}const gr=e=>"number"==typeof e&&Number.isInteger(e)&&e>=0&&e<=359?e:null;function fr(e,t){const i=gr(t?.north_deg);return null!==i?i:gr(e?.north_deg)}function vr(e){return"outer"===e?.sun_ray_origin?"outer":"inner"}function yr(e,t){const i=e=>"static"===e||"daynight"===e?e:null;return i(t?.bg_mode)??i(e?.bg_mode)??"static"}function br(e,t){const i=t?.sun_rays;return"boolean"==typeof i?i:!0===e?.sun_rays}function wr(e){const t=e?.states?.["sun.sun"]?.attributes,i=Number(t?.azimuth),n=Number(t?.elevation);return Number.isFinite(i)&&Number.isFinite(n)?{azimuth:i,elevation:n}:null}const kr=["dawn","day","dusk","night"];function xr(e){if(!e)return"";const t=Qn[e.phase];return[`--hp-day-cycle-outline-near:${t.outlineNear}`,`--hp-day-cycle-outline-mid:${t.outlineMid}`,`--hp-day-cycle-outline-far:${t.outlineFar}`].join(";")}function Sr(e,t=1){if(!e)return G;const i=[`--hp-day-cycle-sun-x:${e.sunX.toFixed(2)}%`,`--hp-day-cycle-sun-y:${e.sunY.toFixed(2)}%`,`--hp-day-cycle-sun-opacity:${e.sunOpacity.toFixed(3)}`,`opacity:${Math.min(1,Math.max(0,t)).toFixed(4)}`].join(";");return j``}const $r={color:"#607d8b",opacity:1,widthCm:3.6,fill:!1,fillColor:"#607d8b",fillOpacity:.25},Mr=(e,t=1)=>{const i=Number(e);return Number.isFinite(i)?Math.min(1,Math.max(0,i)):t},Rr=e=>{let t=Number(e);return Number.isFinite(t)?(t=(t%360+360)%360,t>180?t-360:t):0};function Cr(e,t,i){return Rr(t)?[e.x,e.y]:i([e.x,e.y])}function Tr(e,t,i,n){const r=Math.abs(i[0]-t[0]),o=Math.abs(i[1]-t[1]);return"line"===e?Math.hypot(r,o)>=n:r>=n&&o>=n}const Dr=(e,t,i)=>{const n=Number(e),r=Number.isFinite(t)&&t>0?t:5;return Number.isFinite(n)&&n>0?n/r*i:0},Ar=(e,t,i)=>{const n=Number(e),r=Number.isFinite(t)&&t>0?t:5;return Number.isFinite(n)&&i>0?n/i*r:0},Pr=(e,t,i,n=$r.widthCm)=>{const r=Number(e?.width_cm);if(Number.isFinite(r)&&r>0)return r;const o=Number(e?.width);return Number.isFinite(o)&&o>0?Ar(o,t,i):n};function Fr(e){const t=$r;return e.color===t.color&&e.opacity===t.opacity&&e.widthCm===t.widthCm&&e.fill===t.fill&&e.fillColor===t.fillColor&&e.fillOpacity===t.fillOpacity?null:{color:e.color,opacity:Mr(e.opacity),width_cm:Math.max(.1,Math.min(100,Number(e.widthCm)||.1)),fill:!!e.fill,fill_color:e.fillColor,fill_opacity:Mr(e.fillOpacity,.25)}}function zr(e,t){return{color:e.color,opacity:Mr(e.opacity),width_cm:Math.max(.1,Math.min(100,Number(e.widthCm)||.1)),...t?{fill:e.fill,fill_color:e.fillColor,fill_opacity:Mr(e.fillOpacity,.25)}:{}}}function Ir(e){const t=e.x+e.w/2,i=e.y+e.h/2,n=Rr(e.angle)*Math.PI/180,r=Math.cos(n),o=Math.sin(n),s=(e,n)=>{const s=e-t,a=n-i;return[t+s*r-a*o,i+s*o+a*r]};return[s(e.x,e.y),s(e.x+e.w,e.y),s(e.x+e.w,e.y+e.h),s(e.x,e.y+e.h)]}function Or(e){const t=Ir(e),i=(e,t)=>[(e[0]+t[0])/2,(e[1]+t[1])/2],n=[(t[0][0]+t[2][0])/2,(t[0][1]+t[2][1])/2];return{points:[...t,i(t[0],t[1]),i(t[1],t[2]),i(t[2],t[3]),i(t[3],t[0]),n],segments:t.map((e,i)=>({a:e,b:t[(i+1)%4]}))}}function Er(e,t,i,n,r,o,s,a){const l=Rr(e.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l),d=-Math.sin(l),u=Math.cos(l),p=e.x+e.w/2,_=e.y+e.h/2,m=t>0?-e.w/2:e.w/2,g=i>0?-e.h/2:e.h/2,f=p+m*c+g*d,v=_+m*h+g*u,y=n-f,b=r-v;let w=(y*c+b*h)*(t>0?1:-1),k=(y*d+b*u)*(i>0?1:-1),x=null;if(o){const t=w/Math.max(e.w,a),i=k/Math.max(e.h,a);x=Math.max(a/Math.max(e.w,a),a/Math.max(e.h,a),t,i),w=e.w*x,k=e.h*x}if(s>0)if(o){const t=Math.max(1,Math.round(e.w/s)),i=Math.max(1,Math.round(e.h/s));if(Math.abs(e.w-t*s)<1e-6&&Math.abs(e.h-i*s)<1e-6){const n=(e,t)=>{let i=Math.abs(e),n=Math.abs(t);for(;n;)[i,n]=[n,i%n];return Math.max(1,i)},r=1/n(t,i),o=Math.max(a/e.w,a/e.h),s=Math.max(o,Math.round((x??1)/r)*r);w=e.w*s,k=e.h*s}else{e.w>=e.h?(w=Math.round(w/s)*s,k=w*(e.h/Math.max(e.w,a))):(k=Math.round(k/s)*s,w=k*(e.w/Math.max(e.h,a)))}}else w=Math.round(w/s)*s,k=Math.round(k/s)*s;w=Math.max(a,w),k=Math.max(a,k);return{x:f+(t>0?w/2:-w/2)*c+(i>0?k/2:-k/2)*d-w/2,y:v+(t>0?w/2:-w/2)*h+(i>0?k/2:-k/2)*u-k/2,w:w,h:k,angle:Rr(e.angle)||void 0}}const Nr=(e,t,i)=>{const n=i[0]-t[0],r=i[1]-t[1],o=n*n+r*r;if(o<1e-12)return[...t];const s=Math.max(0,Math.min(1,((e[0]-t[0])*n+(e[1]-t[1])*r)/o));return[t[0]+n*s,t[1]+r*s]};function Hr(e,t,i,n){const r=n(e);let o=null;for(const r of t.points){const t=n(r),s=Math.hypot(t[0]-e[0],t[1]-e[1]);s<=i&&(!o||se.points),segments:e.flatMap(e=>e.segments)}}const Br=Math.tan(.25*Math.PI/180);function qr(e,t){const i=Math.abs(Number(t[0])-Number(e[0])),n=Math.abs(Number(t[1])-Number(e[1]));if(!([i,n].every(Number.isFinite)&&i>0&&n>0))return null;const r=i>=n?"horizontal":"vertical",o=Math.max(i,n),s=Math.min(i,n);return s/o>Br?null:{axis:r,major:o,minor:s,angleDegrees:180*Math.atan2(s,o)/Math.PI}}function jr(e,t){const i=qr(e,t);return i?"horizontal"===i.axis?[Number(t[0]),Number(e[1])]:[Number(e[0]),Number(t[1])]:[Number(t[0]),Number(t[1])]}const Wr=e=>`${e[0]},${e[1]}`,Ur=(e,t)=>e[0]===t[0]&&e[1]===t[1],Gr=(e,t)=>{const i=Wr(e),n=Wr(t);return i{let t=0;for(let i=0;i{if(e.length<3)return!1;for(let t=0;t1e-12},Yr=(e,t)=>Ur(e,t.from)?[...t.to]:[...e],Xr=(e,t)=>e.map(e=>Array.isArray(e?.poly)?{...e,poly:e.poly.map(e=>Yr(e,t))}:e),Zr=(e,t,i)=>{const n=e.flatMap((e,t)=>ni(e)?.some(e=>Ur(e,i.from))?[t]:[]);if(!n.length)return!1;for(const i of n){const n=ni(e[i]),r=ni(t[i]);if(!n||!r)continue;if(!Kr(r))return!1;const o=Math.sign(Vr(n)),s=Math.sign(Vr(r));if(o&&s&&o!==s)return!1}const r=new Set;for(const e of n){const i=ni(t[e]);if(i)for(let n=0;n{let i=0;for(const n of e){const e=ni(n);if(e)for(let n=0;n{const{a:i,b:n,axis:r}=e,o="horizontal"===r?{from:n,to:[n[0],i[1]]}:{from:n,to:[i[0],n[1]]},s="horizontal"===r?{from:i,to:[i[0],n[1]]}:{from:i,to:[n[0],i[1]]};return[{move:o,preservedDegree:Jr(t,i)},{move:s,preservedDegree:Jr(t,n)}].sort((e,t)=>t.preservedDegree-e.preservedDegree||Wr(e.move.to).localeCompare(Wr(t.move.to))||Wr(e.move.from).localeCompare(Wr(t.move.from))).map(e=>e.move)};function eo(e){const t=JSON.parse(JSON.stringify(e||{}));let i=Array.isArray(t.rooms)?t.rooms:[];const n=new Map;for(const e of i){const t=ni(e);if(t)for(let e=0;ee.key.localeCompare(t.key))){let t=null;for(const n of Qr(e,i)){const e=a.get(Wr(n.from));if(e&&e!==Wr(n.to))continue;const r=Xr(i,n);if(Zr(i,r,n)){t=n,i=r;break}}t?(a.set(Wr(t.from),Wr(t.to)),r++,s=Math.max(s,Math.hypot(t.to[0]-t.from[0],t.to[1]-t.from[1]))):o++}t.rooms=i;for(const e of t.partitions||[]){if(!Array.isArray(e?.a)||!Array.isArray(e?.b))continue;const i=qr(e.a,e.b);if(!i)continue;const n={key:String(e.id||Gr(e.a,e.b)),a:[...e.a],b:[...e.b],axis:i.axis};let a=null;for(const i of Qr(n,[{poly:[e.a,e.b]}])){const n=Yr(e.a,i),r=Yr(e.b,i),o=Math.hypot(r[0]-n[0],r[1]-n[1]);if(!(o>0))continue;const s=(t.openings||[]).filter(t=>"partition"===t?.host?.kind&&t.host.id===e.id).every(e=>{const t=Number(e.host.t),i=Number(e.length);return Number.isFinite(t)&&t>=0&&t<=1&&Number.isFinite(i)&&i>0&&t*o-i/2>=-1e-12&&t*o+i/2<=o+1e-12});if(s){a=i,e.a=n,e.b=r;break}}a?(r++,s=Math.max(s,Math.hypot(a.to[0]-a.from[0],a.to[1]-a.from[1]))):o++}return{space:t,report:{wallsStraightened:r,wallsStraightenSkipped:o,maxStraightenShift:s},changed:r>0}}const to=["rect","ellipse","furniture","image"],io=10**9,no=240,ro=1e-4;function oo(e){if(Array.isArray(e))return e.map(e=>oo(e));if(null!==e&&"object"==typeof e){const t={};for(const[i,n]of Object.entries(e))t[i]=oo(n);return t}return e}function so(e){if("number"!=typeof e||!Number.isFinite(e))return e;const t=(e<0||Object.is(e,-0)?-1:1)*(Math.floor(Math.abs(e)*io+.5)/io);return 0===t?0:t}function ao(e){if("number"!=typeof e||!Number.isFinite(e))return e;const t=e*no,i=Math.round(t);if(Math.abs(t-i)null!==co(e)):[]}function uo(e){return"string"==typeof e&&to.includes(e)}function po(e,t){for(const i of t)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=so(e[i]))}function _o(e,t){for(const i of t)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=ao(e[i]))}function mo(e){if(Array.isArray(e))for(let t=0;t{for(const r of n){const n=t[r];"number"==typeof n&&Number.isFinite(n)&&i(n,e)}},n=t=>{if(Array.isArray(t))for(let n=0;n{if(Array.isArray(e))for(const t of e)n(t)};for(const i of ho(e.rooms))t(i,["x","y","w","h"]),r(i.poly);for(const t of ho(e.walls))n(t.a),n(t.b);for(const t of ho(e.wall_segments))n(t.a),n(t.b);for(const i of ho(e.openings))t(i,["x","y"]);for(const i of ho(e.decor))"line"===i.kind?t(i,["x1","y1","x2","y2"]):uo(i.kind)?t(i,["x","y","w","h"]):"text"===i.kind&&t(i,["x","y"]);for(const t of ho(e.room_drafts))r(t.points);for(const t of ho(e.partitions))n(t.a),n(t.b);for(const t of ho(e.wall_columns))n(t.center);for(const t of ho(e.open_spans))n(t.a),n(t.b)}const r=co(t);if(!r)return;const o=new Map;if(n)for(const e of ho(n.spaces))null!=e.id&&o.set(String(e.id),e);for(const e of Object.values(r)){const t=co(e);if(!t)continue;const n=null!=t.s&&o.get(String(t.s))||null;for(const e of["x","y"]){const r=t[e];"number"==typeof r&&Number.isFinite(r)&&i(r,n)}}}function vo(e){const t=Number(e?.cell_cm);return t>0?t:5}function yo(e,t={}){const i={canonicalized:0,far:0,maxShift:0,maxShiftCm:0,spaces:[],bySpace:new Map},n=ho(co(e)?.spaces);let r=5;for(const e of n)r=Math.max(r,vo(e));fo(e,t,(e,t)=>{const n=e*no,o=Math.abs(n-Math.round(n)),s=ao(e),a=o>0&&o=ro))return;const l=a&&"number"==typeof s?Math.abs(s-e):0;if(a?i.canonicalized++:i.far++,i.maxShift=Math.max(i.maxShift,l),i.maxShiftCm=Math.max(i.maxShiftCm,l*no*(t?vo(t):r)),!t?.id||!a)return;const c=String(t.id);let h=i.bySpace.get(c);h||(h={spaceId:c,space:String(t.title||c),canonicalized:0,far:0,maxShift:0,maxShiftCm:0},i.bySpace.set(c,h)),h.canonicalized++,h.maxShift=Math.max(h.maxShift,l),h.maxShiftCm=Math.max(h.maxShiftCm,l*no*vo(t))}),i.bySpace.size&&fo(e,t,(e,t)=>{if(!t?.id)return;const n=i.bySpace.get(String(t.id));if(!n)return;const r=e*no;Math.abs(r-Math.round(r))>=ro&&n.far++}),i.spaces=[...i.bySpace.values()];const{bySpace:o,...s}=i;return s}function bo(e){return function(e){const t=e,i=co(t);i&&_o(i,["x","y"]);return t}(oo(e))}function wo(e){const t=e,i=co(t);if(!i)return t;for(const e of Object.values(i)){const t=co(e);t&&_o(t,["x","y"])}return t}function ko(e){return xo(oo(e))}function xo(e){const t=e,i=co(t);if(!i)return t;for(const e of ho(i.spaces)){po(e,["plan_x","plan_y","plan_scale","plan_scale_x","plan_scale_y","plan_angle"]);for(const t of ho(e.rooms))_o(t,["x","y","w","h"]),go(t.poly);for(const t of ho(e.walls))mo(t.a),mo(t.b);for(const t of ho(e.wall_segments))mo(t.a),mo(t.b);for(const t of ho(e.openings)){_o(t,["x","y"]),po(t,["angle","length"]);const e=co(t.host);e&&po(e,["t"])}for(const t of ho(e.decor))"line"===t.kind?_o(t,["x1","y1","x2","y2"]):uo(t.kind)?(_o(t,["x","y","w","h"]),po(t,["angle"])):"text"===t.kind&&(_o(t,["x","y"]),po(t,["scale","angle"]));for(const t of ho(e.room_drafts))go(t.points);for(const t of ho(e.partitions))mo(t.a),mo(t.b);for(const t of ho(e.wall_columns))mo(t.center),"square"===t.shape&&po(t,["angle"]);for(const t of ho(e.open_spans))mo(t.a),mo(t.b)}for(const e of ho(i.markers))po(e,["angle"]);return t}const So=15,$o=8;function Mo(e,t,i,n,r){const o=i[0]-e[0],s=i[1]-e[1],a=Math.hypot(o,s);if(!(a>0)||a<=r+1e-9)return null;const l=o/a,c=s/a,h=t=>{const n=(t[0]-e[0])*l+(t[1]-e[1])*c,o=(r-n)/(a-n);return!Number.isFinite(o)||o<-1e-9||o>1+1e-9?null:[t[0]+(i[0]-t[0])*o,t[1]+(i[1]-t[1])*o]},d=h(t),u=h(n);return d&&u?[[e[0],e[1]],t,d,u,n]:null}const Ro=Math.sin(.25*Math.PI/180);function Co(e,t){return Number.isFinite(e)&&e>0&&Number.isFinite(t)&&t>0&&e*t<3}function To(e){const t=Number(e)>0?Number(e):5;if(5===t)return 8;const i=5/t*8;return Math.min(80,Math.max(.5,i))}function Do(e,t){return Number.isFinite(e)&&e>0&&Number.isFinite(t)&&t>0&&e*t<2}function Ao(e){return Number.isFinite(e)?Math.max(1,Math.min(100,e)):1}function Po(e,t){return!Number.isFinite(e)||e<0?"":String(t?Math.round(e/2.54*100)/100:Math.round(100*e)/100)}function Fo(e,t,i){if(!Number.isFinite(e)||e<=0)return 0;const n=Number(t)>0?Number(t):5;return Ao(e)/n*i}function zo(e,t){return t>0&&Number.isFinite(e)?Math.round(e/t)*t:e}function Io(e){return Math.max(1e-6*Math.abs(e),1e-9)}function Oo(e,t){if(!(t>0&&Number.isFinite(e)))return e;const i=zo(e,t);return Math.abs(i-e)<=Io(t)?i:e}function Eo(e,t){let i=t[0]-e[0],n=t[1]-e[1];const r=Math.hypot(i,n);return r<1e-12?[1,0]:(i/=r,n/=r,(i<-1e-12||Math.abs(i)<=1e-12&&n<0)&&(i=-i,n=-n),[i,n])}function No(e,t,i){const n=[Oo(e[0],i),Oo(e[1],i)],r=[Oo(t[0],i),Oo(t[1],i)],o=zo((n[0]+r[0])/2,i),s=zo((n[1]+r[1])/2,i),[a,l]=Eo(n,r);let c=Math.atan2(l,a);c<0&&(c+=Math.PI);const h=Math.round(1800*c)/1800,d=i>0&&i<.01?6:i<1?4:2;return`${o.toFixed(d)},${s.toFixed(d)}@${h.toFixed(4)}`}function Ho(e,t,i,n){return 1===n?No(e,t,i):No([e[0]/n,e[1]/n],[t[0]/n,t[1]/n],i)}function Lo(e,t){if(!Array.isArray(e.a)||!Array.isArray(e.b)||e.a.length<2||e.b.length<2)return null;const i=[Number(e.a[0]),Number(e.a[1]),Number(e.b[0]),Number(e.b[1])];if(!i.every(Number.isFinite))return null;const n=t>0?t:1;return[[i[0]*n,i[1]*n],[i[2]*n,i[3]*n]]}function Bo(e,t,i,n,r){const o=r>0?r:1;return{key:Ho(e,t,n,o),cm:Ao(i),a:[e[0]/o,e[1]/o],b:[t[0]/o,t[1]/o]}}function qo(e,t){const i=t>0?t:1,n=[];for(const t of e){const e=t.key.lastIndexOf("@");if(e<0)continue;const[r,o]=t.key.slice(0,e).split(",").map(Number),s=Number(t.key.slice(e+1));[r,o,s].every(Number.isFinite)&&n.push({w:t,x:r*i,y:o*i,ang:s})}return n}function jo(e,t){const[i,n]=Eo(e,t);let r=Math.atan2(n,i);return r<0&&(r+=Math.PI),r}function Wo(e,t){let i=Math.abs(e-t);return i>Math.PI/2&&(i=Math.PI-i),i<.02}function Uo(e,t,i,n,r=1){if(!e?.length)return null;const o=Ho(t,i,n,r),s=e.find(e=>e.key===o);if(s)return s;const a=r>0?r:1,l=Io(n)*a,c=(e,t)=>Math.abs(e[0]-t[0])<=l&&Math.abs(e[1]-t[1])<=l;for(const n of e){const e=Lo(n,a);if(e&&(c(e[0],t)&&c(e[1],i)||c(e[0],i)&&c(e[1],t)))return n}const h=(t[0]+i[0])/2,d=(t[1]+i[1])/2,u=jo(t,i),p=Math.max(.5*n,1e-9)*a;for(const t of qo(e,a))if(Wo(t.ang,u)&&Math.hypot(t.x-h,t.y-d)<=p)return t.w;return null}function Go(e,t,i,n,r=1){const o=Uo(e,t,i,n,r);if(o&&o.cm>0)return Ao(o.cm);const s=function(e,t,i,n,r){if(!e?.length)return null;const o=r>0?r:1,s=Math.hypot(i[0]-t[0],i[1]-t[1]);if(s<1e-12)return null;const a=jo(t,i),l=Math.max(.5*n,1e-9)*o;let c=null;for(const n of e){if(!(n.cm>0))continue;const e=Lo(n,o);if(!e)continue;const r=Math.hypot(e[1][0]-e[0][0],e[1][1]-e[0][1]);if(r<1e-12||!Wo(jo(e[0],e[1]),a))continue;if(Is(t[0],t[1],e[0][0],e[0][1],e[1][0],e[1][1])>l||Is(i[0],i[1],e[0][0],e[0][1],e[1][0],e[1][1])>l)continue;if(r+l(o.has(e.key)||(e=>{const t=Lo(e,n);if(!t)return!1;const[i,o]=t,a=o[0]-i[0],c=o[1]-i[1],h=Math.hypot(a,c);if(h<=l)return!1;if(!s.some(e=>{const t=[e[0],e[1]],n=[e[2],e[3]];return Wo(jo(i,o),jo(t,n))&&Is(i[0],i[1],t[0],t[1],n[0],n[1])<=l&&Is(o[0],o[1],t[0],t[1],n[0],n[1])<=l}))return!1;const d=(r||[]).some(e=>{const t=[e[0],e[1]],n=[e[2],e[3]];if(!Wo(jo(i,o),jo(t,n)))return!1;const r=e=>Math.abs((e[0]-i[0])*c-(e[1]-i[1])*a)/h;if(r(t)>l||r(n)>l)return!1;const s=h*h,d=((t[0]-i[0])*a+(t[1]-i[1])*c)/s,u=((n[0]-i[0])*a+(n[1]-i[1])*c)/s;return Math.min(1,Math.max(d,u))-Math.max(0,Math.min(d,u))>l/h});return!d})(e))&&e.cm>=1&&e.cm<=100)}function Ko(e,t,i,n=8){const[r,o]=Eo(e,t);let s=Math.atan2(o,r);s<0&&(s+=Math.PI);let a=i*Math.PI/180%Math.PI;a<0&&(a+=Math.PI);let l=Math.abs(s-a);return l>Math.PI/2&&(l=Math.PI-l),l<=n*Math.PI/180}function Yo(e,t,i,n,r=1,o="affine",s){if(!e?.length)return[];if(t.length!==i.length)return"fixed-topology"===o&&s?.(),e.slice();const a=r>0?r:1,l=Math.max(.5*n,1e-9)*a,c=Math.max(n*a*1e-6,1e-9),h=[],d=new Map,u=new Map,p=(e,t,i)=>{const n=e.get(t)||new Set;n.add(i),e.set(t,n)};for(let e=0;e[e[0]+(t[0]-e[0])*i,e[1]+(t[1]-e[1])*i],m=(e,t)=>Math.hypot(e[0]-t[0],e[1]-t[1])<=c,g=(e,t)=>{if("fixed-topology"===o){const i=t.na[0]-t.oa[0],n=t.na[1]-t.oa[1],r=t.nb[0]-t.ob[0],o=t.nb[1]-t.ob[1];return Math.hypot(i-r,n-o)<=c?[e[0]+i,e[1]+n]:m(e,t.oa)?[...t.na]:m(e,t.ob)?[...t.nb]:[...e]}const i=Math.max(0,Math.min(1,((e[0]-t.oa[0])*t.dx+(e[1]-t.oa[1])*t.dy)/t.len2));return _(t.na,t.nb,i)},f=(e,t)=>{const[i,n]=Eo(e,t);return(t[0]-e[0])*i+(t[1]-e[1])*n>=0?[[...e],[...t]]:[[...t],[...e]]},v=[],y=[],b=(e,t,i)=>{if(Math.hypot(t[0]-e[0],t[1]-e[1])<=c)return;const[r,o]=f(e,t),s=Ao(i);if(y.some(e=>e.entry.cm===s&&m(e.span[0],r)&&m(e.span[1],o)))return;const l=Bo(r,o,s,n,a);v.push(l),y.push({entry:l,span:[r,o]})};for(const t of e){const e=Lo(t,a);if(e){const[i,n]=f(e[0],e[1]),r=n[0]-i[0],s=n[1]-i[1],a=r*r+s*s,d=Math.sqrt(a);if(d<=c){v.push({...t,cm:Ao(t.cm)});continue}const u=[];for(const e of h){if(!Wo(jo(i,n),jo(e.oa,e.ob)))continue;const t=e=>Math.abs((e[0]-i[0])*s-(e[1]-i[1])*r)/d;if(t(e.oa)>l||t(e.ob)>l)continue;const o=((e.oa[0]-i[0])*r+(e.oa[1]-i[1])*s)/a,h=((e.ob[0]-i[0])*r+(e.ob[1]-i[1])*s)/a,p=Math.max(0,Math.min(o,h)),_=Math.min(1,Math.max(o,h));(_-p)*d>c&&u.push({lo:p,hi:_,move:e})}if(!u.length){"fixed-topology"===o?v.push({...t}):b(i,n,t.cm);continue}const p=[0,1,...u.flatMap(({lo:e,hi:t})=>[e,t])].sort((e,t)=>e-t).filter((e,t,i)=>0===t||Math.abs(e-i[t-1])*d>c),y=[];for(let e=0;e+1a>=e.lo-1e-12&&a<=e.hi+1e-12);if(!l.length){y.push([o,s]);continue}const h=[g(o,l[0].move),g(s,l[0].move)],f=l.slice(1).some(e=>{const t=g(o,e.move),i=g(s,e.move);return!m(h[0],t)||!m(h[1],i)});y.push(f?[o,s]:h)}const w=(e,t)=>{const i=e[1][0]-e[0][0],n=e[1][1]-e[0][1],r=t[1][0]-t[0][0],o=t[1][1]-t[0][1],s=Math.hypot(i,n);return!(s<=c||i*r+n*o<=0)&&Math.abs(i*o-n*r)/s<=c},k=[];for(const e of y){const t=k[k.length-1];t&&m(t[1],e[0])&&w(t,e)?t[1]=e[1]:k.push([[...e[0]],[...e[1]]])}if("fixed-topology"===o&&1===k.length){const[i,n]=k[0];if(m(i,e[0])&&m(n,e[1])||m(i,e[1])&&m(n,e[0])){v.push({...t});continue}}for(const[e,i]of k)b(e,i,t.cm);continue}if("fixed-topology"===o){const e=u.get(t.key);if(1===e?.size){const i=[...e][0];v.push(i===t.key?{...t}:{...t,key:i});continue}const i=[qo([t],a)[0]];1!==a&&i.push(qo([t],1)[0]);const n=i.filter(Boolean).some(e=>h.some(t=>{if(!Wo(e.ang,jo(t.oa,t.ob)))return!1;const i=((e.x-t.oa[0])*t.dx+(e.y-t.oa[1])*t.dy)/t.len2;return i>=-1e-6&&i<=1.000001&&Is(e.x,e.y,t.oa[0],t.oa[1],t.ob[0],t.ob[1])<=l}));((e?.size||0)>1||n)&&s?.(),v.push({...t});continue}let i="";const r=d.get(t.key);if(1===r?.size&&(i=[...r][0]),!i){const e=qo([t],a)[0];if(e){const t=new Set;for(const i of h){if(!Wo(e.ang,jo(i.oa,i.ob)))continue;const r=((e.x-i.oa[0])*i.dx+(e.y-i.oa[1])*i.dy)/i.len2;if(r<-1e-6||r>1.000001)continue;if(Is(e.x,e.y,i.oa[0],i.oa[1],i.ob[0],i.ob[1])>l)continue;const o=g([e.x,e.y],i),[s,c]=Eo(i.na,i.nb),h=Math.max(n*a,1e-6);t.add(Ho([o[0]-s*h,o[1]-c*h],[o[0]+s*h,o[1]+c*h],n,a))}1===t.size&&(i=[...t][0])}}v.push({...t,key:i||t.key,cm:Ao(t.cm)})}return v}function Xo(e,t,i,n,r=1,o="affine"){return Yo(e,t,i,n,r,o)}function Zo(e,t,i,n,r=1,o="fixed-topology"){let s=!1;const a=Yo(e,t,i,n,r,o,()=>{s=!0});return{walls:s?(e||[]).map(e=>({...e})):a,rejected:s}}function Jo(e,t,i,n=1,r=[]){const o=n>0?n:1,s=Math.abs(i),a=Math.max(s*o*ro,1e-9),l=(r||[]).flatMap(e=>{const t=Lo(e,o);return t?t.map(e=>[...e]):[]}),c=e=>e.every((e,t)=>(e=>{if(!(s>0))return!0;const t=e/o/s;return Math.abs(t-Math.round(t))Math.abs(e-i[t])<=a)),h=[],d=e=>JSON.stringify([e.key,e.cm,e.a,e.b]);for(const i of e||[]){const e=Lo(i,o);if(!e)continue;const[n,r]=e;if(![n[0],n[1],r[0],r[1]].every(Number.isFinite)||!c(n)||!c(r)){h.push(d(i));continue}const s=r[0]-n[0],l=r[1]-n[1],u=Math.hypot(s,l);if(u<=a){h.push(d(i));continue}const p=s/u,_=l/u,m=[];for(const e of t){const[t,i]=e;if(![t?.[0],t?.[1],i?.[0],i?.[1]].every(Number.isFinite))continue;const r=e=>Math.abs((e[0]-n[0])*_-(e[1]-n[1])*p);if(r(t)>a||r(i)>a)continue;const o=(t[0]-n[0])*p+(t[1]-n[1])*_,s=(i[0]-n[0])*p+(i[1]-n[1])*_,l=Math.max(0,Math.min(o,s)),c=Math.min(u,Math.max(o,s));c-l>a&&m.push([l,c])}m.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);let g=0;for(const[e,t]of m){if(e>g+a)break;if(g=Math.max(g,t),g>=u-a)break}ge.key!==s);return null==n||n<1?a:[...a,Bo(t,i,n,r,o)]}function es(e,t,i,n,r,o=[],s=1){let a=e?e.slice():[];for(const e of function(e,t,i,n,r=1,o=[]){const s=ws(e,t,i,n,r,o);if(!s)return[];const a=[];for(let e=0;e0||(c=Qo(c,t,i,n,r,s)))}return c}function is(e){const{a:t,b:i,halfDepth:n}=e;if(!Array.isArray(t)||!Array.isArray(i)||t.length<2||i.length<2||![t[0],t[1],i[0],i[1]].every(Number.isFinite))return null;const r=i[0]-t[0],o=i[1]-t[1],s=Math.hypot(r,o);if(!(s>1e-9&&n>0&&Number.isFinite(n)))return null;const a=-o/s*n,l=r/s*n;return[[t[0]+a,t[1]+l],[i[0]+a,i[1]+l],[i[0]-a,i[1]-l],[t[0]-a,t[1]-l]]}function ns(e,t,i){return Math.hypot(e[0]-t[0],e[1]-t[1])<=i}function rs(e,t,i){const n=t.b[0]-t.a[0],r=t.b[1]-t.a[1],o=n*n+r*r;if(!(o>i*i))return!1;const s=((e[0]-t.a[0])*n+(e[1]-t.a[1])*r)/o;if(!(s>0&&s<1))return!1;const a=[t.a[0]+n*s,t.a[1]+r*s];return Math.hypot(e[0]-a[0],e[1]-a[1])<=i}function os(e,t,i,n){const r=Math.hypot(t,i);if(!(r>1e-9&&n>0))return;const o=[t/r,i/r],s=e.find(e=>Math.abs(e.u[0]*o[1]-e.u[1]*o[0])<1e-9&&e.u[0]*o[0]+e.u[1]*o[1]>1-1e-9);s?s.halfDepth=Math.max(s.halfDepth,n):e.push({u:o,halfDepth:n})}function ss(e,t){try{const i=Gt(Ns(e),Ns(t));let n=null,r=0;for(const e of i||[]){const t=e?.[0]||[],i=Math.abs(us(t));t.length>=4&&i>r&&(r=i,n=t.slice(0,-1).map(e=>[e[0],e[1]]))}return n}catch{return null}}function as(e,t=1e-6){const i=(e||[]).map((e,t)=>({segment:e,index:t})).filter(({segment:e})=>e&&Array.isArray(e.a)&&Array.isArray(e.b)&&e.a.length>=2&&e.b.length>=2&&e.a.every(Number.isFinite)&&e.b.every(Number.isFinite)&&Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])>1e-9);if(i.length<2)return[];const n=Math.max(Number.isFinite(t)?t:0,1e-9),r=i.flatMap(({segment:e})=>[e.a,e.b]).map(e=>[e[0],e[1]]).sort((e,t)=>e[0]-t[0]||e[1]-t[1]),o=[];for(const e of r)o.some(t=>ns(t,e,n))||o.push(e);const s=[];for(const e of o){const t=[];let r=!1;for(const{segment:o,index:s}of i){const i=Math.hypot(o.b[0]-o.a[0],o.b[1]-o.a[1]);ns(e,o.a,n)?t.push({u:[(o.b[0]-o.a[0])/i,(o.b[1]-o.a[1])/i],halfDepth:o.halfDepth,length:i,index:s}):ns(e,o.b,n)?t.push({u:[(o.a[0]-o.b[0])/i,(o.a[1]-o.b[1])/i],halfDepth:o.halfDepth,length:i,index:s}):rs(e,o,n)&&(r=!0)}if(r||2!==t.length)continue;const[o,a]=t,l=o.u[0]*a.u[1]-o.u[1]*a.u[0];if(Math.abs(l)<1e-9)continue;const c=l<0?1:-1,h=[-o.u[1],o.u[0]],d=[-a.u[1],a.u[0]],u=[e[0]+h[0]*o.halfDepth*c,e[1]+h[1]*o.halfDepth*c],p=[e[0]-d[0]*a.halfDepth*c,e[1]-d[1]*a.halfDepth*c];if(!ms(u,o.u,p,a.u))continue;const _=[[o,a,p,[d[0]*-c,d[1]*-c]],[a,o,u,[h[0]*c,h[1]*c]]];for(const[t,,i,r]of _){const o=Math.min(2*t.halfDepth,t.length),a=[-t.u[1]*t.halfDepth,t.u[0]*t.halfDepth],l=[[e[0]+a[0],e[1]+a[1]],[e[0]+t.u[0]*o+a[0],e[1]+t.u[1]*o+a[1]],[e[0]+t.u[0]*o-a[0],e[1]+t.u[1]*o-a[1]],[e[0]-a[0],e[1]-a[1]]],c=e=>(e[0]-i[0])*r[0]+(e[1]-i[1])*r[1],h=[];for(let e=0;e=-1e-12&&h.push(t),n>1e-12&&r<-1e-12||n<-1e-12&&r>1e-12){const e=n/(n-r);h.push([t[0]+(i[0]-t[0])*e,t[1]+(i[1]-t[1])*e])}}h.length>=3&&Math.abs(us(h))>n*n&&s.push({segmentIndex:t.index,wedge:h})}}return s}function ls(e,t=1e-6){const i=(e||[]).filter(e=>e&&Array.isArray(e.a)&&Array.isArray(e.b)&&e.a.length>=2&&e.b.length>=2&&e.a.every(Number.isFinite)&&e.b.every(Number.isFinite)&&Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])>1e-9);if(i.length<2)return[];const n=Math.max(Number.isFinite(t)?t:0,1e-9),r=i.flatMap(e=>[e.a,e.b]).map(e=>[e[0],e[1]]).sort((e,t)=>e[0]-t[0]||e[1]-t[1]),o=[];for(const e of r)o.some(t=>ns(t,e,n))||o.push(e);const s=[],a=i.map((e,t)=>({roomId:"",a:[e.a[0],e.a[1]],b:[e.b[0],e.b[1]],key:`join-${t}`,kind:"outer",cm:0,open:!1,half:e.halfDepth})),l=Ms(a,n);for(const e of Rs(l).fans)s.push(e);const c=e=>!!Cs(l,e);for(const e of o){if(c(e))continue;const t=[];for(const r of i)ns(e,r.a,n)?os(t,r.b[0]-r.a[0],r.b[1]-r.a[1],r.halfDepth):ns(e,r.b,n)?os(t,r.a[0]-r.b[0],r.a[1]-r.b[1],r.halfDepth):rs(e,r,n)&&(os(t,r.a[0]-e[0],r.a[1]-e[1],r.halfDepth),os(t,r.b[0]-e[0],r.b[1]-e[1],r.halfDepth));if(!(t.length<2)){t.sort((e,t)=>Math.atan2(e.u[1],e.u[0])-Math.atan2(t.u[1],t.u[0])||e.halfDepth-t.halfDepth);for(let i=0;in*n&&s.push(m)}}}return s}function cs(e,t,i,n){if(!(t>0)||!e||e.length<2)return"";if(i&&e.length>=3){let i=e;const r=e[e.length-1];if(e.length>=4&&Math.hypot(e[0][0]-r[0],e[0][1]-r[1])<1e-9&&(i=e.slice(0,-1)),i.length>=3){const e=i.map((e,i)=>n?.[i]||t),r=ra(i,e),o=vs(i,e);if(r&&o)return`${ys(r)} ${ys(bs(o))}`}}const r=[];for(let i=0;i=1e-9&&a>0&&r.push({a:o,b:s,halfDepth:a})}const o=r.map(is);for(const{segmentIndex:e,wedge:t}of as(r)){const i=o[e];if(!i)continue;const n=ss(i,t);n&&(o[e]=n)}const s=[...o.filter(e=>!!e),...ls(r)],a=function(e){let t=null;try{for(const i of e){if(i.length<3)continue;const e=Ns(i);t=t?Wt(t,e):[e]}return t}catch{return null}}(s);return a?Xs(a):s.map(e=>ys(e)).join(" ")}function hs(e,t,i,n,r=1){if(!i.length)return!1;const o=ds(n,r),s=(e[0]+t[0])/2,a=(e[1]+t[1])/2,[l,c]=Eo(e,t);for(const e of i){const[t,i]=Eo([e[0],e[1]],[e[2],e[3]]);if(!(Math.abs(l*i-c*t)>.05)&&Is(s,a,e[0],e[1],e[2],e[3])<=o)return!0}return!1}function ds(e,t){return Math.max(e*(t>0?t:1)*.04,1e-9)}function us(e){let t=0;for(let i=0;ie[1]!=l>e[1]&&e[0]<(a-o)*(e[1]-s)/(l-s+0)+o&&(i=!i)}return i}([c[0]+.001*a,c[1]+.001*l],e)||(a=-a,l=-l),[a,l]}function _s(e,t){const i=e[0]*t[1]-e[1]*t[0],n=e[0]*t[0]+e[1]*t[1];return Math.abs(i)<1e-9&&n>0}function ms(e,t,i,n){const r=t[0]*n[1]-t[1]*n[0];if(Math.abs(r)<1e-12)return null;const o=[i[0]-e[0],i[1]-e[1]],s=(o[0]*n[1]-o[1]*n[0])/r;return[e[0]+s*t[0],e[1]+s*t[1]]}function gs(e,t,i){const n=e?.length||0;if(n<3||!Array.isArray(i)||i.length!==n)return 0;const r=(Math.trunc(t)%n+n)%n,o=e[r],s=e[(r+1)%n],a=s[0]-o[0],l=s[1]-o[1],c=Math.hypot(a,l);if(!(c>0))return 0;const h=Math.max(0,Number(i[r])||0);if(!(h>0))return c;const d=[a/c,l/c],u=ps(e,r),p=[o[0]+u[0]*h,o[1]+u[1]*h],_=t=>{const r=Math.max(0,Number(i[t])||0);if(!(r>0))return null;const s=e[t],a=e[(t+1)%n],l=a[0]-s[0],c=a[1]-s[1],h=Math.hypot(l,c);if(!(h>0))return null;const u=ps(e,t),_=ms(p,d,[s[0]+u[0]*r,s[1]+u[1]*r],[l/h,c/h]);return _?(_[0]-o[0])*d[0]+(_[1]-o[1])*d[1]:null},m=_((r-1+n)%n)??0,g=(_((r+1)%n)??c)-m;return g>0?g:0}function fs(e,t,i,n,r,o,s,a=1){const l=(e||[]).find(e=>e?.id===t),c=ni(l);if(!c||c.length<3)return null;const h=Ds(e,t,i,n,r,o,s,a);if(!h)return c.map(()=>0);const d=4*ds(r,a);return c.map((e,t)=>{const i=c[(t+1)%c.length],n=[(e[0]+i[0])/2,(e[1]+i[1])/2];for(let e=0;e!(e>0)))return e.map(e=>[e[0],e[1]]);const r=[];for(let o=0;o0||u>0)){r.push([e[o][0],e[o][1]]);continue}if(d>0!=u>0){const t=e[o],i=d>0?[t[0]+p*d,t[1]+_*d]:[t[0],t[1]],n=u>0?[t[0]+m*u,t[1]+g*u]:[t[0],t[1]];r.push(i),Math.hypot(n[0]-i[0],n[1]-i[1])>1e-9&&r.push(n);continue}if(_s(w,k)){const t=e[o],i=[t[0]+p*d,t[1]+_*d],n=[t[0]+m*u,t[1]+g*u];r.push(i),Math.hypot(n[0]-i[0],n[1]-i[1])>1e-9&&r.push(n);continue}const $=ms(x,w,S,k),M=Math.max(d,u,1e-9),R=Cs(i,e[o])?.limit??4*M;if($){const i=Math.hypot($[0]-e[o][0],$[1]-e[o][1]);if(Number.isFinite(i)&&i<=R){r.push($);continue}if(Js(e,t,o)){r.push($);continue}}d>0&&r.push([e[o][0]+p*d,e[o][1]+_*d]),u>0&&r.push([e[o][0]+m*u,e[o][1]+g*u]),d>0||u>0||r.push([e[o][0],e[o][1]])}return r.length>=3?r:null}function ys(e,t=!0){if(!e.length)return"";let i=`M ${e[0][0]} ${e[0][1]}`;for(let t=1;te?.id===t),a=ni(s);if(!a||a.length<3)return null;const l=ds(n,r),c=[];for(const i of e||[]){if(!i||i.id===t)continue;const e=ni(i);if(e)for(const t of An(a,e,l))c.push([t[0],t[1]],[t[2],t[3]])}for(const e of i||[])c.push([e[0],e[1]],[e[2],e[3]]);for(const e of o||[]){const t=Lo(e,r);t&&c.push(t[0],t[1])}const h=[],d=[];for(let e=0;el)continue;const s=((e[0]-t[0])*(i[0]-t[0])+(e[1]-t[1])*(i[1]-t[1]))/(n*n);s<=r||s>=1-r||(o.some(e=>Math.abs(e-s)*n<=2*l)||o.push(s))}o.sort((e,t)=>e-t);for(const n of o)h.push([t[0]+(i[0]-t[0])*n,t[1]+(i[1]-t[1])*n]),d.push(e)}return{poly:h,parent:d,orig:a}}function ks(e,t,i,n){const r=t.poly.length,o=new Array(r).fill(0);if(!e?.length)return o;const s=new Set,a=[];for(let l=0;l0?(o[l]=Ao(c.cm),s.add(c.key)):a.push(l)}if(!a.length)return o;const l=n>0?n:1,c=Math.max(.5*i,1e-9)*l,h=qo(e,l).filter(e=>e.w.cm>0);for(let e=a.length-1;e>=0;e--){const i=a[e],n=t.poly[i],s=t.poly[(i+1)%r],d=jo(n,s);let u=null;for(const e of h){const t=Lo(e.w,l);if(!t||!Wo(jo(t[0],t[1]),d))continue;if(Is(n[0],n[1],t[0][0],t[0][1],t[1][0],t[1][1])>c||Is(s[0],s[1],t[0][0],t[0][1],t[1][0],t[1][1])>c)continue;const i=Math.hypot(s[0]-n[0],s[1]-n[1]),r=Math.hypot(t[1][0]-t[0][0],t[1][1]-t[0][1]),o=Math.max(0,r-i);(!u||oc||Is(r[0],r[1],t[0][0],t[0][1],t[1][0],t[1][1])>c)continue;i=!0,o=Math.max(0,Math.hypot(t[1][0]-t[0][0],t[1][1]-t[0][1])-_)}else{if(Is(e.x,e.y,n[0],n[1],r[0],r[1])>c)continue;o=Math.hypot(e.x-d,e.y-u)}(!p||i&&!p.exact||i===p.exact&&o0?i:1,o=(e||[]).filter(e=>e&&!e.open&&null!==e.kind&&Number.isFinite(e.half)&&e.half>0&&Array.isArray(e.a)&&Array.isArray(e.b)&&e.a.length>=2&&e.b.length>=2&&[e.a[0],e.a[1],e.b[0],e.b[1]].every(Number.isFinite)&&Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])>n).sort((e,t)=>e.key.localeCompare(t.key)||e.a[0]-t.a[0]||e.a[1]-t.a[1]||e.b[0]-t.b[0]||e.b[1]-t.b[1]||e.half-t.half),s=new Map;for(const e of o){const t=s.get(e.key);t?e.half>t.half&&s.set(e.key,{...t,half:e.half}):s.set(e.key,e)}const a=[...s.values()].flatMap(e=>[{point:[e.a[0],e.a[1]],other:e.b,halfDepth:e.half,kind:e.kind,key:e.key},{point:[e.b[0],e.b[1]],other:e.a,halfDepth:e.half,kind:e.kind,key:e.key}]).sort((e,t)=>e.point[0]-t.point[0]||e.point[1]-t.point[1]||e.other[0]-t.other[0]||e.other[1]-t.other[1]||e.halfDepth-t.halfDepth),l=new Map;for(const e of a){const[t,i]=xs(e.point,n),r=Ss(t,i),o=l.get(r)||[];o.push(e),l.set(r,o)}const c=[],h=new Map;for(const e of a){const t=$s(h,e.point,n).filter(t=>Math.hypot(t.point[0]-e.point[0],t.point[1]-e.point[1])<=n).sort((t,i)=>Math.hypot(t.point[0]-e.point[0],t.point[1]-e.point[1])-Math.hypot(i.point[0]-e.point[0],i.point[1]-e.point[1])||t.point[0]-i.point[0]||t.point[1]-i.point[1]);let i=t[0];if(!i){i={point:[...e.point],rays:[]},c.push(i);const[t,r]=xs(i.point,n),o=Ss(t,r),s=h.get(o)||[];s.push(i),h.set(o,s)}const r=e.other[0]-e.point[0],o=e.other[1]-e.point[1],s=Math.hypot(r,o);if(!(s>n))continue;const a=[r/s,o/s];let l=Math.atan2(a[1],a[0]);l<0&&(l+=2*Math.PI),i.rays.push({u:a,halfDepth:e.halfDepth,length:s,angle:l})}const d=[],u=e=>{const t=1e-9*Math.max(1,r),i=e.filter(e=>Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Number.isFinite(e.length)&&e.length>n);return i.filter((e,n)=>!i.some((i,r)=>r!==n&&i.halfDepth>=e.halfDepth-t&&i.length>=e.length-t&&(i.halfDepth>e.halfDepth+t||i.length>e.length+t||re.length-t.length||e.halfDepth-t.halfDepth).map(e=>({...e}))};for(const e of c){const t=e.rays.sort((e,t)=>e.angle-t.angle||e.length-t.length||e.halfDepth-t.halfDepth),i=[];for(const e of t){const t=i[i.length-1];t&&Math.abs(e.angle-t.angle)<=1e-9?t.supports.push({halfDepth:e.halfDepth,length:e.length}):i.push({u:[...e.u],angle:e.angle,supports:[{halfDepth:e.halfDepth,length:e.length}]})}if(i.length>1&&2*Math.PI-i[i.length-1].angle+i[0].angle<=1e-9){const e=i.pop();i[0].supports.push(...e.supports)}if(i.length<3)continue;const r=i.map(t=>{const i=u(t.supports),r=new Set,o=[];for(const s of i){const i=[e.point[0]+t.u[0]*s.length,e.point[1]+t.u[1]*s.length];for(const t of $s(l,i,n)){if("shared"!==t.kind||Math.hypot(t.point[0]-i[0],t.point[1]-i[1])>n)continue;const s=t.other[0]-t.point[0],a=t.other[1]-t.point[1],l=Math.hypot(s,a);if(!(l>n))continue;const c=s/l,h=a/l;if(Math.hypot(t.other[0]-e.point[0],t.other[1]-e.point[1])<=n)continue;const d=`${t.key}|${t.point[0]}|${t.point[1]}|${t.other[0]}|${t.other[1]}|${t.halfDepth}`;r.has(d)||(r.add(d),o.push({start:[t.point[0],t.point[1]],u:[c,h],length:l,halfDepth:t.halfDepth}))}}return o.sort((e,t)=>e.start[0]-t.start[0]||e.start[1]-t.start[1]||e.u[0]-t.u[0]||e.u[1]-t.u[1]||e.length-t.length||e.halfDepth-t.halfDepth),{u:[...t.u],halfDepth:Math.max(...i.map(e=>e.halfDepth)),length:Math.max(...i.map(e=>e.length)),supports:i,continuations:o}}).filter(e=>Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Number.isFinite(e.length)&&e.length>n);if(r.length<3)continue;const o=Math.max(...r.map(e=>e.halfDepth));o>0&&Number.isFinite(o)&&d.push({point:[...e.point],rays:r,halfDepth:o,limit:1.25*o})}d.sort((e,t)=>e.point[0]-t.point[0]||e.point[1]-t.point[1]);const p=new Map;for(const e of d){const[t,i]=xs(e.point,n),r=Ss(t,i),o=p.get(r)||[];o.push(e),p.set(r,o)}return{epsilon:n,coordinateScale:r,nodes:d,index:p}}function Rs(e){const t={fans:[],supports:[]};if(!e?.nodes?.length)return t;const i=Math.max(e.epsilon,1e-9)**2;for(const n of e.nodes){const e=n.rays.filter(e=>Number.isFinite(e.halfDepth)&&e.halfDepth>0).map(e=>({...e,thickLength:Math.max(...e.supports.filter(t=>t.halfDepth>=e.halfDepth-1e-12).map(e=>e.length),0),angle:(()=>{const t=Math.atan2(e.u[1],e.u[0]);return t<0?t+2*Math.PI:t})()})).sort((e,t)=>e.angle-t.angle);if(e.length<2)continue;const r=n.point;for(const i of e)for(const e of i.supports){if(!(e.halfDepth>0&&e.length>0))continue;const n=-i.u[1]*e.halfDepth,o=i.u[0]*e.halfDepth,s=[r[0]+i.u[0]*e.length,r[1]+i.u[1]*e.length];t.supports.push([[r[0]+n,r[1]+o],[s[0]+n,s[1]+o],[s[0]-n,s[1]-o],[r[0]-n,r[1]-o]])}for(let n=0;n{const e=s.angle-o.angle;return e>0?e:e+2*Math.PI})();if(a<1e-9)continue;const l=a>Math.PI+1e-9,c=4*Math.max(o.halfDepth,s.halfDepth),h=[r[0]-o.u[1]*o.halfDepth,r[1]+o.u[0]*o.halfDepth],d=[r[0]+s.u[1]*s.halfDepth,r[1]-s.u[0]*s.halfDepth],u=o.u[0]*s.u[1]-o.u[1]*s.u[0],p=e=>{let t=Math.atan2(e[1]-r[1],e[0]-r[0])-o.angle;for(;t<0;)t+=2*Math.PI;return t<=a+1e-9};let _=null;if(Math.abs(u)>1e-9){const e=((d[0]-h[0])*s.u[1]-(d[1]-h[1])*s.u[0])/u,t=((d[0]-h[0])*o.u[1]-(d[1]-h[1])*o.u[0])/u,i=[h[0]+o.u[0]*e,h[1]+o.u[1]*e];(l?e<=1e-9&&t<=1e-9:e>1e-9&&e<=o.thickLength&&t<=s.thickLength)&&Math.hypot(i[0]-r[0],i[1]-r[1])<=c&&p(i)&&(_=i)}const m=e=>{Math.abs(us(e))>i&&t.fans.push(e)};if(_){const e=1.5*Math.max(o.halfDepth,s.halfDepth);m(Mo([r[0],r[1]],h,_,d,e)??[[r[0],r[1]],h,_,d]);continue}if(l){m([[r[0],r[1]],h,d]);continue}const g=(e,t)=>Math.min(t,Math.sqrt(Math.max(c**2-e**2,0)),2*Math.max(o.halfDepth,s.halfDepth)),f=[h[0]+o.u[0]*g(o.halfDepth,o.thickLength),h[1]+o.u[1]*g(o.halfDepth,o.thickLength)],v=[d[0]+s.u[0]*g(s.halfDepth,s.thickLength),d[1]+s.u[1]*g(s.halfDepth,s.thickLength)];m([[r[0],r[1]],h,f,v,d])}}return t}function Cs(e,t){return!e||!Array.isArray(t)||t.length<2||!t.slice(0,2).every(Number.isFinite)?null:$s(e.index,t,e.epsilon).filter(i=>Math.hypot(i.point[0]-t[0],i.point[1]-t[1])<=e.epsilon).sort((e,i)=>Math.hypot(e.point[0]-t[0],e.point[1]-t[1])-Math.hypot(i.point[0]-t[0],i.point[1]-t[1])||e.point[0]-i.point[0]||e.point[1]-i.point[1])[0]||null}function Ts(e,t,i,n,r,o,s){return Ms(As(e,t,i,n,r,o,s),4*ds(n,s),s)}function Ds(e,t,i,n,r,o,s,a=1){const l=ws(e,t,n,r,a,i);if(!l)return null;const c=function(e,t,i){const n=(e||[]).find(e=>e?.id===t),r=ni(n);if(!r)return[];const o=[];for(const n of e||[]){if(!n||n.id===t)continue;const e=ni(n);if(e)for(const t of An(r,e,i))o.push(t)}return o}(e,t,ds(r,a)),h=function(e,t,i,n,r){const o=ds(n,r),s=[];for(let a=0;aIs(h,d,e[0],e[1],e[2],e[3])<=o);s.push(u?"shared":"outer")}return s}(l.poly,c,n,r,a),d=ks(i,l,r,a),u=d.map((e,t)=>h[t]&&e>0?Fo(e,o,s)/2:0);return{...l,kinds:h,cms:d,offsets:u}}function As(e,t,i,n,r,o,s=1){const a=[];for(const l of e||[]){if(!l?.id)continue;const c=Ds(e,l.id,t,i,n,r,o,s);if(c)for(let e=0;e0&&(a=Qo(a,e.a,e.b,e.cm,n,s));return a}function Fs(e,t,i,n,r,o,s=1){if(!t?.length)return[];const a=As(e,t,i,n,r,o,s),l=new Map;for(const e of a){if(e.open||!e.kind||!e.roomId)continue;const t=l.get(e.key)||new Set;t.add(e.roomId),l.set(e.key,t)}const c=e=>{const t=[...l.get(e)||[]].sort();return 1!==t.length&&2!==t.length?`ambiguous:${e}`:`${1===t.length?"outer":"shared"}:${t.join("|")}`},h=[],d=new Set;for(const e of a)!e.open&&e.cm>0&&!d.has(e.key)&&(d.add(e.key),h.push({...e,ownerSignature:c(e.key)}));const u=[];for(const a of e||[]){if(!a?.id)continue;const l=Ds(e,a.id,t,i,n,r,o,s);if(l)for(let e=0;e0)||null===l.kinds[i]){e++;continue}const o=c(Ho(l.poly[i],l.poly[(i+1)%l.poly.length],n,s));let a=e;for(;a+10&&u.push({a:[d[0],d[1]],b:[p[0],p[1]],key:Ho(d,p,n,s),cm:r,len:_,ownerSignature:o}),e=a+1}}}u.sort((e,t)=>t.len-e.len||e.key.localeCompare(t.key));const p=[],_=new Set,m=new Set,g=4*ds(n,s);for(const e of u){const t=h.filter(t=>!m.has(t.key)&&t.cm===e.cm&&t.ownerSignature===e.ownerSignature&&Wo(jo(t.a,t.b),jo(e.a,e.b))&&Is(t.a[0],t.a[1],e.a[0],e.a[1],e.b[0],e.b[1])<=g&&Is(t.b[0],t.b[1],e.a[0],e.a[1],e.b[0],e.b[1])<=g);if(t.length){for(const e of t)m.add(e.key);_.has(e.key)||(_.add(e.key),p.push(Bo(e.a,e.b,e.cm,n,s)))}}for(const e of h)m.has(e.key)||_.has(e.key)||(_.add(e.key),p.push(Bo(e.a,e.b,e.cm,n,s)));return p}function zs(e,t,i,n,r,o,s,a=1){const l=ds(r,a),c=(n[0]+n[2])/2,h=(n[1]+n[3])/2,d=jo([n[0],n[1]],[n[2],n[3]]);let u=null;for(const n of As(e,t,i,r,o,s,a)){if(!Wo(jo(n.a,n.b),d))continue;const e=Is(c,h,n.a[0],n.a[1],n.b[0],n.b[1]);e>4*l||(!u||e[e[0],e[1]]),o=Math.abs(us(r));r.length>=3&&o>i&&(t=r,i=o)}return t}function Es(e,t,i,n,r,o,s,a=1,l,c){const h=(e||[]).find(e=>e?.id===t),d=ni(h);if(!d||d.length<3)return null;if(!i?.length)return d.map(e=>[e[0],e[1]]);const u=Ds(e,t,i,n,r,o,s,a);if(!u||!u.offsets.some(e=>e>0))return d.map(e=>[e[0],e[1]]);const p=c||Ts(e,i,n,r,o,s,a),_=vs(u.poly,u.offsets,p);if(!_)return d.map(e=>[e[0],e[1]]);if(!p.nodes.length)return _;const m=void 0===l?Qs(e,i,n,[],r,o,s,a):null,g=l??("ok"===m?.status||"degraded-extra"===m?.status?m.roomGeom:void 0);if(g)try{const e=Os(Gt(Ns(u.poly),g));if(e)return e}catch{}return function(e,t){try{return Os(Ut(Ns(e),Ns(t)))}catch{return null}}(_,u.poly)||d.map(e=>[e[0],e[1]])}function Ns(e){const t=e.map(e=>[e[0],e[1]]);return t.push([e[0][0],e[0][1]]),[t]}function Hs(e){return!(!Array.isArray(e)||!e.length)&&e.every(e=>Array.isArray(e)&&e.length&&e.every(e=>Array.isArray(e)&&e.length>=4&&e.every(e=>Array.isArray(e)&&e.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1])))&&Math.abs(Ci(e[0]))>1e-9)}function Ls(e,t,i,n){const r=n?new Set(n):null;let o=null;for(let n=0;nt.epsilon))continue;const l=Us([[e.point[0]+a[0]*n.halfDepth,e.point[1]+a[1]*n.halfDepth],[e.point[0]+s.u[0]*r+a[0]*n.halfDepth,e.point[1]+s.u[1]*r+a[1]*n.halfDepth],[e.point[0]+s.u[0]*r-a[0]*n.halfDepth,e.point[1]+s.u[1]*r-a[1]*n.halfDepth],[e.point[0]-a[0]*n.halfDepth,e.point[1]-a[1]*n.halfDepth]],t.coordinateScale);if(!l)continue;const c=Ns(l);o=o?Wt(o,c):c}}return o}function Bs(e,t,i){let n=null;for(const r of e.rays)for(const e of r.continuations){const r=[-e.u[1],e.u[0]],o=[e.start[0]+e.u[0]*e.length,e.start[1]+e.u[1]*e.length],s=Us([[e.start[0]+r[0]*e.halfDepth,e.start[1]+r[1]*e.halfDepth],[o[0]+r[0]*e.halfDepth,o[1]+r[1]*e.halfDepth],[o[0]-r[0]*e.halfDepth,o[1]-r[1]*e.halfDepth],[e.start[0]-r[0]*e.halfDepth,e.start[1]-r[1]*e.halfDepth]],t.coordinateScale);if(!s)continue;const a=Ut(Ns(s),i);Array.isArray(a)&&0!==a.length&&(n=n?Wt(n,a):a)}return n}function qs(e,t,i=2*(4*e.halfDepth+2*t.epsilon)){const n=function(e,t=Ro){const i=new Set,n=Number.isFinite(t)&&t>=0?t:Ro;for(let t=0;te-t)}(e);return n.length?Ls(e,t,i,n):null}function js(e,t,i,n,r){const o=function(e){let t=null;for(const i of e){const e=Ns(i);try{t=t?Wt(t,e):e}catch{}}return t}(function(e,t,i=!1){if(!e)return[];const n=[];for(const r of e.nodes)for(let o=0;o1e-9)||h>=Math.PI-1e-9)continue;const d=[-s.u[1],s.u[0]],u=[-a.u[1],a.u[0]],p=[r.point[0]+d[0]*s.halfDepth,r.point[1]+d[1]*s.halfDepth],_=[r.point[0]-u[0]*a.halfDepth,r.point[1]-u[1]*a.halfDepth],m=ms(p,s.u,_,a.u);if(!m)continue;const g=Math.hypot(m[0]-r.point[0],m[1]-r.point[1]);if(!Number.isFinite(g)||g<=r.limit)continue;const f=t?Math.sqrt(Math.max(0,r.limit*r.limit-s.halfDepth*s.halfDepth)):0,v=t?Math.sqrt(Math.max(0,r.limit*r.limit-a.halfDepth*a.halfDepth)):0,y=Us([[p[0]+s.u[0]*f,p[1]+s.u[1]*f],[_[0]+a.u[0]*v,_[1]+a.u[1]*v],m],e.coordinateScale);if(y&&n.push(y),i){const t=m[0]-r.point[0],i=m[1]-r.point[1],o=Math.hypot(t,i),s=g-r.limit;if(o>e.epsilon&&s>e.epsilon){const a=Math.min(Math.max(8*e.epsilon,.05*r.halfDepth),.25*s),l=t/o,c=i/o,h=-c,d=l,u=Us([[m[0]-l*a+h*a,m[1]-c*a+d*a],[m[0]-l*a-h*a,m[1]-c*a-d*a],[m[0]+l*a,m[1]+c*a]],e.coordinateScale);u&&n.push(u)}}}return n}({...t,nodes:[e]},i,n));return o&&r?Gt(o,r):o}function Ws(e,t,i,n){if(!e||!t.nodes.length)return e;let r=null;try{r=function(e){let t=null;for(const i of e.nodes){const n=qs(i,e);n&&(t=t?Wt(t,n):n)}return t}(t)}catch{return e}let o=e;for(const e of t.nodes){const s=4*e.halfDepth+2*t.epsilon,a=2*s,l=[[e.point[0]-s,e.point[1]-s],[e.point[0]+s,e.point[1]-s],[e.point[0]+s,e.point[1]+s],[e.point[0]-s,e.point[1]+s]];try{let s=o;const c=js(e,t,!1,!0,r);c&&(s=Gt(s,c));let h=Ls(e,t,a);const d=js(e,t,!0,!0,r);d&&(h=Gt(h,d)),r&&(h=Wt(h,r));const u=.02*Math.min(...e.rays.map(e=>e.halfDepth));if(h=Wt(h,Ns([[e.point[0]-u,e.point[1]-u],[e.point[0]+u,e.point[1]-u],[e.point[0]+u,e.point[1]+u],[e.point[0]-u,e.point[1]+u]])),!h)continue;let p=Ut(h,Ns(l));n?p=Ut(p,n):i&&(p=Ut(p,i));const _=Ns(l),m=Gt(s,_),g=i?Gt(Ut(s,_),i):null,f=Bs(e,t,_);o=Wt(m,...g?[g]:[],...f?[f]:[],p)}catch{}}if(r)try{let e=r;n?e=Ut(e,n):i&&(e=Ut(e,i)),o=Wt(o,e)}catch{}return o}function Us(e,t=1){if(!Array.isArray(e)||e.length<3)return null;const i=Number.isFinite(t)&&t>0?t:1,n=1e-12*Math.max(1,i),r=[];for(const t of e){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),i=Number(t[1]);if(!Number.isFinite(e)||!Number.isFinite(i))return null;const o=Math.round(e/n)*n,s=Math.round(i/n)*n;if(!Number.isFinite(o)||!Number.isFinite(s))return null;r.push([Object.is(o,-0)?0:o,Object.is(s,-0)?0:s])}return Math.abs(us(r))>n*n?r:null}function Gs(e,t,i,n){if(Is(e[0],e[1],t[0],t[1],i[0],i[1])>n)return!1;const r=i[0]-t[0],o=i[1]-t[1],s=(e[0]-t[0])*r+(e[1]-t[1])*o,a=r*r+o*o,l=n*Math.sqrt(a);return s>=-l&&s<=a+l}function Vs(e,t,i){const n=[],r=[];for(let o=0;oi*i))continue;const d=i/Math.sqrt(h),u=[0,1];for(const e of t)for(const t of[e.a,e.b]){if(!Gs(t,s,a,i))continue;const e=((t[0]-s[0])*l+(t[1]-s[1])*c)/h;e>d&&e<1-d&&u.push(e)}u.sort((e,t)=>e-t);const p=u.filter((e,t)=>0===t||Math.abs(e-u[t-1])>d);for(let e=0;e=3&&r.length===n.length?{poly:n,offsets:r}:null}function Ks(e,t,i,n,r,o,s,a){const l=(e||[]).map(ni).filter(e=>!!e&&e.length>=3);if(!l.length)return null;let c=Wt(Ns(l[0]));for(let e=1;e"outer"===e.kind&&e.half>0),u=4*ds(n,s),p=a||Ms(h,u,s);let _=null;for(const e of function(e){const t=[];for(const i of Array.isArray(e)?e:[])if(Array.isArray(i))for(const e of i){if(!Array.isArray(e)||e.length<4)continue;const i=e.slice(0,-1).map(e=>[e[0],e[1]]);i.length>=3&&t.push(i)}return t}(c)){const t=Vs(e,d,u);if(!t||!t.offsets.some(e=>e>0))continue;const i=ra(t.poly,t.offsets,p),n=vs(t.poly,t.offsets,p);if(!i||!n)continue;const r=Gt(Ns(i),Ns(n));_=_?Wt(_,r):r}return{centre:c,shell:_||[]}}function Ys(e,t,i,n,r,o,s=1){try{const a=Ks(e,t,i,n,r,o,s,Ts(e,t,i,n,r,o,s));if(!a)return[];return a.shell?.length?Wt(a.centre,a.shell):a.centre}catch{return null}}function Xs(e){if(!e)return"";let t="";for(const i of e)if(Array.isArray(i))for(const e of i){if(!Array.isArray(e)||e.length<4)continue;const i=e.slice(0,e.length-1);i.length<3||(t+=(t?" ":"")+ys(i.map(e=>[e[0],e[1]])))}return t}const Zs=15;function Js(e,t,i){const n=e?.length||0;if(n<3||t?.length!==n)return!1;const r=e[(i-1+n)%n],o=e[i],s=e[(i+1)%n],a=[r[0]-o[0],r[1]-o[1]],l=[s[0]-o[0],s[1]-o[1]],c=Math.hypot(a[0],a[1]),h=Math.hypot(l[0],l[1]);if(!(c>1e-9&&h>1e-9))return!1;const d=Math.max(-1,Math.min(1,(a[0]*l[0]+a[1]*l[1])/(c*h))),u=Math.acos(d);if(!(u>1e-9))return!1;if(u>=Zs*Math.PI/180)return!1;const p=Math.max(0,t[(i-1+n)%n]),_=Math.max(0,t[i]);if(!(p>0||_>0))return!1;const m=Math.sin(u);if(!(m>1e-12))return!1;const g=(_+p*d)/m,f=(p+_*d)/m;return Number.isFinite(g)&&Number.isFinite(f)&&g>0&&f>0&&ge>0))continue;for(const e of l.offsets)e>0&&(u=Math.max(u,2*e));const c=ra(l.poly,l.offsets,d),p=vs(l.poly,l.offsets,d);c&&h.push({outset:c,inset:p})}for(const e of l){const t=e.map(e=>e[0]),i=e.map(e=>e[1]);if(t.length){const n=Math.min(Math.max(...t)-Math.min(...t),Math.max(...i)-Math.min(...i)),r=Math.min(...e.map((t,i)=>{const n=e[(i+1)%e.length];return Math.hypot(n[0]-t[0],n[1]-t[1])}));u=Math.max(u,e.length>16?n:r)}}const p=function(e,t,i,n,r,o,s,a){if(!t?.length||!i?.length)return[];const l=4*ds(n,s),c=new Map;for(const a of As(e,t,i,n,r,o,s))!a.open&&a.half>0&&!c.has(a.key)&&c.set(a.key,a);const h=[...c.values()];if(h.length<2)return[];const d=a||Ms(h,l),u=[];for(const e of i)for(const t of[[e[0],e[1]],[e[2],e[3]]])u.some(e=>Math.hypot(e[0]-t[0],e[1]-t[1])<=l)||u.push(t);const p=[],_=(e,t)=>{let i=0,n=0;if(Math.hypot(e.a[0]-t[0],e.a[1]-t[1])<=l)i=e.b[0]-e.a[0],n=e.b[1]-e.a[1];else{if(!(Math.hypot(e.b[0]-t[0],e.b[1]-t[1])<=l))return null;i=e.a[0]-e.b[0],n=e.a[1]-e.b[1]}const r=Math.hypot(i,n);return r>l?[i/r,n/r]:null};for(const e of u){const t=h.map(t=>({iv:t,u:_(t,e)})).filter(e=>!!e.u);for(let i=0;i0?[e.slice(),u,m,_]:[e.slice(),_,m,u];else{if(!f)continue;{const t=[-r.u[1],r.u[0]],i=[-o.u[1],o.u[0]],n=s<0?1:-1,a=[e[0]+t[0]*r.iv.half*n,e[1]+t[1]*r.iv.half*n],l=[e[0]-i[0]*o.iv.half*n,e[1]-i[1]*o.iv.half*n];y=s>0?[e.slice(),a,l]:[e.slice(),l,a]}}Math.abs(us(y))>l*l&&p.push(y)}}return p}(e,t,i,r,o,s,a,d),_=n.length?oa(e,t,i,r,o,s,a):null;let m="exterior";try{const v=Ks(e,t,i,r,o,s,a,d);m="paper";const y=v?v.shell?.length?Wt(v.centre,v.shell):v.centre:[],b=e=>{const t=Ns(e.outset);if(!e.inset)return t;const i=Ns(e.inset);return Gt(t,i)};m="room-rings";let w=null;for(const e of h)try{const t=b(e);w=w?Wt(w,t):t}catch{}if(m="edge-bodies",v)for(const n of ia(e,t,i,r,o,s,a))try{const e=Ut(Ns(n.quad),v.centre);w=w?Wt(w,e):e}catch{}m="junctions",w=function(e,t,i=1,n=Wt){let r=e;for(const e of t||[]){const t=Us(e,i);if(t)try{const e=Ns(t);r=r?n(r,e):e}catch{}}return r}(w,p,a),m="facade-clip",w&&v&&(w=Ut(w,v.centre)),m="exterior-shell";const k=[];let x=0;if(v?.shell?.length)if(w)try{const e=Wt(w,v.shell);if(!Hs(e))throw new Error("invalid shell union");w=e}catch{if(!Hs(w)||!Hs(v.shell))throw new Error("invalid shell");k.push({id:"exterior-shell",geom:v.shell}),x++}else w=v.shell;if(m="multi-wall-trim",w&&d.nodes.length){const e=e=>e.rays.some(e=>e.supports.some(e=>e.length<2*e.halfDepth)),t=d.nodes.filter(e);if(t.length){w=Ws(w,{...d,nodes:t},v?.centre,y)}}if(m="junction-corners",d.nodes.length){const n=Rs(d),l=function(e,t,i,n,r,o,s,a){try{const l=Ks(e,t,i,n,r,o,s,{epsilon:a.epsilon,coordinateScale:a.coordinateScale,nodes:[],index:new Map});return l?l.shell?.length?Wt(l.centre,l.shell):l.centre:null}catch{return null}}(e,t,i,r,o,s,a,d);for(const e of n.fans)try{let t=[Ns(e)];if(l&&(t=Ut(t,l)),!t?.length)continue;w=w?Wt(w,t):t}catch{}g=w,f=Math.max(d.epsilon,1e-9)**2,w=Array.isArray(g)?g.map(e=>{if(!Array.isArray(e)||!e.length)return e;const[t,...i]=e;return Math.abs(us(t||[]))<=f?null:[t,...i.filter(e=>Math.abs(us(e||[]))>f)]}).filter(e=>!!e):g}const S=w||[],$=[...Hs(S)?[{id:"room-primary",geom:S}]:[],...k.map((e,t)=>({id:`room-isolated-${t}`,geom:e.geom}))];m="openings";for(const e of n){if(!(e.length>0))continue;const t=la(_,e,!0);if(!t.negative&&!t.positive)continue;const i=e.angle*Math.PI/180,n=Math.cos(i),o=Math.sin(i),s=-o,l=n,c=e.length/2,h=1.25*Math.max(u,r*a),d=[[e.x-n*c-s*h,e.y-o*c-l*h],[e.x+n*c-s*h,e.y+o*c-l*h],[e.x+n*c+s*h,e.y+o*c+l*h],[e.x-n*c+s*h,e.y-o*c+l*h]];w&&(w=Gt(w,Ns(d)));for(const e of k)e.geom=Gt(e.geom,Ns(d))}m="extras";const M=[];let R=0;const C=c.mergeExtra||((e,t)=>e?Wt(e,t):t);for(let e=0;ee.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]))||Math.abs(Ci(t))<=1e-9){R++;continue}const i=[Ns(t)];try{const t=C(w,i,e);if(!Hs(t))throw new Error("invalid extra union");w=t}catch{R++,Hs(i)&&M.push({id:`extra-${e}`,geom:i})}}M.push(...k),M.sort((e,t)=>Xs(e.geom).localeCompare(Xs(t.geom)));const T=w||[];return{status:R||x?"degraded-extra":"ok",geom:T,components:[...Hs(T)?[{id:"primary",geom:T}]:[],...M.map((e,t)=>({...e,id:`isolated-${t}`}))],roomGeom:S,roomComponents:$,paperGeom:y,depthUnits:u,openingPadUnits:1.25*Math.max(u,r*a),openingIndex:_,multiWallNodes:d,degradedExtraCount:R+x}}catch{return c.onCoreFailure?.(m),{status:"failed-core",geom:[],components:[],roomGeom:[],paperGeom:[],roomComponents:[],depthUnits:u,openingIndex:null,multiWallNodes:d,degradedExtraCount:0}}var g,f}function ea(e,t,i,n=[],r,o,s,a=1,l=[],c={}){if(!t?.length&&!l.length)return null;return ta(Qs(e,t,i,n,r,o,s,a,l,c))}function ta(e){if("failed-core"===e.status||"not-applicable"===e.status)return null;const t=e.components.map(e=>({id:e.id,d:Xs(e.geom),fillRule:"evenodd"})).filter(e=>!!e.d),i=t[0]?.d||"",n=Xs(e.paperGeom);if(t.length){const r={status:e.status,d:i,paths:t,components:e.components,roomGeom:e.roomGeom,multiWallNodes:e.multiWallNodes,paperD:n,depthUnits:e.depthUnits,fillRule:"evenodd"};return Object.defineProperties(r,{roomComponents:{value:e.roomComponents||[],enumerable:!1},openingIndex:{value:e.openingIndex,enumerable:!1},openingPadUnits:{value:e.openingPadUnits,enumerable:!1}}),r}return null}function ia(e,t,i,n,r,o,s=1){if(!t?.length)return[];const a=new Set,l=[];for(const c of e||[]){if(!c?.id)continue;const h=Ds(e,c.id,t,i,n,r,o,s);if(!h)continue;const d=h.poly;for(let e=0;e0))continue;const p=Ho(t,i,n,s);if(a.has(p))continue;a.add(p);const _=Fo(u,r,o),[m,g]=ps(d,e),f=-m,v=-g,y=_/2,b=[[t[0]+f*y,t[1]+v*y],[i[0]+f*y,i[1]+v*y],[i[0]+m*y,i[1]+g*y],[t[0]+m*y,t[1]+g*y]];l.push({key:p,kind:c,cm:u,quad:b,a:[t[0],t[1]],b:[i[0],i[1]],depthUnits:_})}}return l}function na(e,t=[]){let i=ys(e.quad);const[n,r]=Eo(e.a,e.b),o=n,s=r,a=-s,l=o;for(const n of t){if(!Ko(e.a,e.b,n.angle))continue;if(Is(n.x,n.y,e.a[0],e.a[1],e.b[0],e.b[1])>Math.max(.55*e.depthUnits,.001))continue;const t=n.length/2,r=e.depthUnits,c=n.x,h=n.y;i+=` ${ys(bs([[c-o*t-a*r,h-s*t-l*r],[c+o*t-a*r,h+s*t-l*r],[c+o*t+a*r,h+s*t+l*r],[c-o*t+a*r,h-s*t+l*r]]))}`}return i}function ra(e,t,i){const n=e?.length||0;if(n<3||t.length!==n)return null;if(t.every(e=>!(e>0)))return e.map(e=>[e[0],e[1]]);bs(e),t.slice().reverse();const r=[];for(let o=0;o0||l>0)){r.push([e[o][0],e[o][1]]);continue}if(a>0!=l>0){const t=e[o],i=a>0?[t[0]-c*a,t[1]-h*a]:[t[0],t[1]],n=l>0?[t[0]-d*l,t[1]-u*l]:[t[0],t[1]];r.push(i),Math.hypot(n[0]-i[0],n[1]-i[1])>1e-9&&r.push(n);continue}if(_s(w,k)){const t=e[o],i=[t[0]-c*a,t[1]-h*a],n=[t[0]-d*l,t[1]-u*l];r.push(i),Math.hypot(n[0]-i[0],n[1]-i[1])>1e-9&&r.push(n);continue}const $=ms(x,w,S,k),M=Math.max(a,l,1e-9),R=Cs(i,e[o])?.limit??4*M;if($){const i=Math.hypot($[0]-e[o][0],$[1]-e[o][1]);if(Number.isFinite(i)&&i<=R){r.push($);continue}if(Js(e,t,o)){r.push([e[o][0],e[o][1]]);continue}}a>0&&r.push([e[o][0]-c*a,e[o][1]-h*a]),l>0&&r.push([e[o][0]-d*l,e[o][1]-u*l])}return r.length>=3?r:null}function oa(e,t,i,n,r,o,s=1){const a=[];for(const l of e||[]){if(!l?.id)continue;const c=Ds(e,l.id,t,i,n,r,o,s);if(!c)continue;const h=Math.abs(Ci(c.poly));for(let e=0;e[Math.max(t,e.x0),Math.min(i,e.x1)]).filter(e=>e[1]-e[0]>n).sort((e,t)=>e[0]-t[0]||e[1]-t[1]);if(!r.length)return{coverage:0,full:!1};let o=r[0][0],s=r[0][1],a=0,l=o<=t+n;for(let e=1;e=i-n,{coverage:a,full:l}}function aa(e,t){return Number(t.full)-Number(e.full)||e.faceDistance-t.faceDistance||e.area-t.area||e.roomId.localeCompare(t.roomId)}function la(e,t,i=!1){const n=Number(t?.x),r=Number(t?.y),o=Number(t?.angle),s=Number(t?.length);if(!([n,r,o,s].every(Number.isFinite)&&s>0))return{negative:null,positive:null};const a=o*Math.PI/180,l=Math.cos(a),c=Math.sin(a),h=-c,d=l,u=s/2,p=Math.max(1e-9,e.adjacencyEps),_=new Map;let m=0;for(const t of e.edges){if(i&&!(t.half>0))continue;if(!Ko(t.a,t.b,o))continue;const[e,s]=Eo(t.a,t.b);if(Math.abs((n-t.a[0])*s-(r-t.a[1])*e)>p)continue;const a=(t.a[0]-n)*l+(t.a[1]-r)*c,g=(t.b[0]-n)*l+(t.b[1]-r)*c,f=Math.max(-u,Math.min(a,g)),v=Math.min(u,Math.max(a,g));if(v-f<=p)continue;const y=t.inward[0]*h+t.inward[1]*d>=0?1:-1,b=((t.a[0]+t.b[0])/2-n)*h+((t.a[1]+t.b[1])/2-r)*d,w=Math.abs(b+y*t.half),k=`${y}|${t.roomId}`,x={x0:f,x1:v,half:t.half,cm:t.cm,key:t.key,axis:[e,s]},S=_.get(k);S?(S.pieces.push(x),S.faceDistance=Math.min(S.faceDistance,w)):_.set(k,{roomId:t.roomId,side:y,order:m++,pieces:[x],faceDistance:w,area:t.area,coverage:0,full:!1})}for(const e of _.values()){const t=sa(e.pieces,-u,u,p);e.coverage=t.coverage,e.full=t.full}const g=e=>{const t=[..._.values()].filter(t=>t.side===e&&t.coverage>p);return t.sort(aa),t[0]||null};return{negative:g(-1),positive:g(1)}}function ca(e,t,i,n,r,o,s=1,a=[]){return ha(oa(e,i,a,n,r,o,s),t)}function ha(e,t){const i=la(e,t),n=[i.negative,i.positive].filter(e=>!!e);if(!n.length)return{ox:0,oy:0,cm:0,side:-1};const r=i.negative&&i.positive?-1:n[0].side,o=t.flip_v?-r:r,s=(-1===o?i.negative:i.positive)||n[0],a=[...s.pieces].sort((e,t)=>(e.x0<=0&&e.x1>=0?0:Math.min(Math.abs(e.x0),Math.abs(e.x1)))-(t.x0<=0&&t.x1>=0?0:Math.min(Math.abs(t.x0),Math.abs(t.x1)))||t.x1-t.x0-(e.x1-e.x0)||e.key.localeCompare(t.key))[0];if(!(a.half>0&&a.cm>0))return{ox:0,oy:0,cm:0,side:o};const l=t.angle*Math.PI/180,c=-Math.sin(l),h=Math.cos(l);return{ox:c*o*a.half,oy:h*o*a.half,cm:a.cm,side:o}}function da(e,t){const i=1e-9,n=t.filter(e=>Number.isFinite(e.x0)&&Number.isFinite(e.x1)&&Number.isFinite(e.half)&&e.x1>e.x0&&e.half>0);if(!n.length)return"";const r=n.flatMap(e=>[e.x0,e.x1]).sort((e,t)=>e-t),o=[];for(const e of r){const t=o[o.length-1];(void 0===t||e>t+i)&&o.push(e)}const s=[];for(let e=0;e+1t+i))continue;const a=(t+r)/2,l=n.reduce((e,t)=>a>=t.x0-i&&a<=t.x1+i?Math.max(e,t.half):e,0);if(!(l>0))continue;const c=s[s.length-1];c&&t<=c.x1+i&&Math.abs(l-c.half)<=i?c.x1=r:s.push({x0:t,x1:r,half:l})}const a=[];for(const e of s){const t=a[a.length-1],n=t?.[t.length-1];n&&e.x0<=n.x1+i?(e.x0=n.x1,t.push(e)):a.push([e])}return a.map(t=>{const i=t[0],n=t[t.length-1],r=Math.min(.25*Math.min(...t.map(e=>e.half)),.75),o=-e*r,s=[];if(1===e){s.push(`M ${i.x0} ${o} L ${n.x1} ${o}`);for(let e=t.length-1;e>=0;e--){const i=t[e];s.push(`L ${i.x1} ${i.half} L ${i.x0} ${i.half}`)}}else{s.push(`M ${n.x1} ${o} L ${i.x0} ${o}`);for(const e of t)s.push(`L ${e.x0} ${-e.half} L ${e.x1} ${-e.half}`)}return s.push("Z"),s.join(" ")}).join(" ")}function ua(e,t,i,n){if(!n)return i;const r=e.angle*Math.PI/180,o=Math.cos(r),s=Math.sin(r),a=[],l=1e-9;for(const r of i){const[i,c]=r.axis,h=o*i+s*c;if(Math.abs(h)<=l)continue;const d=e.x*i+e.y*c,u=d+h*r.x0,p=d+h*r.x1,_=Math.min(u,p),m=Math.max(u,p),g=`${r.key}|${t}`,f=n.get(g)||[];let v=[[_,m]];for(const[e,t]of f){const i=[];for(const[n,r]of v)t<=n+l||e>=r-l?i.push([n,r]):(e>n+l&&i.push([n,Math.min(r,e)]),te[0]-t[0]||e[1]-t[1]),b=[];for(const e of y){const t=b[b.length-1];t&&e[0]<=t[1]+l?t[1]=Math.max(t[1],e[1]):b.push([e[0],e[1]])}n.set(g,b)}return a}function pa(e,t){const i=new Map;return t.map(t=>function(e,t,i){const n=la(e,t,!0),r=n.negative,o=n.positive;if(!r&&!o)return null;let s;if(r&&o)s=[{candidate:r,side:-1},{candidate:o,side:1}];else{const e=r||o;s=[{candidate:e,side:-1},{candidate:e,side:1}]}const a=s.map(({candidate:e,side:n})=>({candidate:e,side:n,pieces:ua(t,n,e.pieces,i)})),l=a.map(({candidate:e,side:t,pieces:i})=>({side:t,roomId:e.roomId,d:da(t,i)})),c=a.flatMap(({pieces:e})=>e);if(!c.length)return null;const h=Math.max(...c.map(e=>e.half));return{faces:l,minY:-h,maxY:h,wallKey:[...new Set(c.map(e=>e.key))].sort().join("|")}}(e,t,i))}const _a=150,ma=1e-6;function ga(e){return Number.isFinite(e)?Math.max(1,Math.min(_a,e)):1}function fa(e){return((Number.isFinite(Number(e))?Number(e):0)%90+90)%90}const va=e=>{const t=e.map(e=>[e[0],e[1]]);return!t.length||t[0][0]===t[t.length-1][0]&&t[0][1]===t[t.length-1][1]||t.push([...t[0]]),[t]},ya=(e,t)=>e[0]===t[0]&&e[1]===t[1];function ba(e,t=1e-6){const i=Number.isFinite(t)&&t>0?t:ma,n=[];for(const t of e||[]){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),r=Number(t[1]);if(!Number.isFinite(e)||!Number.isFinite(r))return null;const o=Math.round(e/i)*i,s=Math.round(r/i)*i;if(!Number.isFinite(o)||!Number.isFinite(s))return null;const a=[Object.is(o,-0)?0:o,Object.is(s,-0)?0:s];n.length&&ya(n[n.length-1],a)||n.push(a)}return n.length>1&&ya(n[0],n[n.length-1])&&n.pop(),n.length<3||new Set(n.map(e=>`${e[0]},${e[1]}`)).size<3?null:Ci(n)>i*i?n:null}function wa(e){const t=[];for(const i of e||[])for(const e of i||[]){const i=(e||[]).filter(e=>Array.isArray(e)&&e.length>=2);i.length<4||t.push(`M ${i.slice(0,-1).map(e=>`${e[0]} ${e[1]}`).join(" L ")} Z`)}return t.join(" ")}function ka(e,t,i,n,r){return is({a:e,b:t,halfDepth:Fo(i,n,r)/2})}function xa(e,t,i){const n=Number(t)>0?Number(t):5,r=ga(e.cm)/n*i,o=e.center[0],s=e.center[1];if("circle"===e.shape){const e=r/2;return Array.from({length:96},(t,i)=>{const n=i/96*Math.PI*2;return[o+Math.cos(n)*e,s+Math.sin(n)*e]})}const a=r/2,l=fa(e.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l);return[[-a,-a],[a,-a],[a,a],[-a,a]].map(([e,t])=>[o+e*c-t*h,s+e*h+t*c])}function Sa(e,t){const i=Number.isFinite(t)?Math.max(0,Math.min(1,t)):0,n=(e.a[0]+e.b[0])/2,r=(e.a[1]+e.b[1])/2,o=(e.b[0]-e.a[0])*i/2,s=(e.b[1]-e.a[1])*i/2;return{...e,a:[n-o,r-s],b:[n+o,r+s]}}function $a(e,t,i=1e-9){if(!t.length)return[e];let n=[va(e)];try{for(const e of t){const t=e.b[0]-e.a[0],r=e.b[1]-e.a[1],o=Math.hypot(t,r);if(!(o>i))continue;const s=t/o,a=r/o,l=-a,c=s,h=1.25*Math.max(Number(e.depth)||0,4*i),d=Math.max(2*i,1e-9*o),u=[[e.a[0]-s*d-l*h,e.a[1]-a*d-c*h],[e.b[0]+s*d-l*h,e.b[1]+a*d-c*h],[e.b[0]+s*d+l*h,e.b[1]+a*d+c*h],[e.a[0]-s*d+l*h,e.a[1]-a*d+c*h]];n=Gt(n,va(u))}return Ia(n)}catch{return[e]}}function Ma(e,t){try{const i=Gt([[...e.map(e=>[e[0],e[1]]),[e[0][0],e[0][1]]]],[[...t.map(e=>[e[0],e[1]]),[t[0][0],t[0][1]]]]);let n=null,r=0;for(const e of i||[]){const t=e?.[0]||[],i=Math.abs(Ci(t));t.length>=4&&i>r&&(r=i,n=t.slice(0,-1).map(e=>[e[0],e[1]]))}return n}catch{return null}}function Ra(e,t,i,n=Math.max(2e-4*i,1e-9),r=[]){const o=[],s=new Map;for(const e of r){const t=s.get(e.hostId)||[];t.push(e),s.set(e.hostId,t)}const a=[],l=[],c=[];for(const n of e.partitions||[]){const e={a:n.a,b:n.b,halfDepth:Fo(n.cm,t,i)/2};if(!(e.halfDepth>0))continue;const r=is(e);r&&(o.push(e),a.push(r),c.push({id:n.id,body:r}))}const h=o;for(const{segmentIndex:e,wedge:t}of as(h,n)){const i={list:a,at:e},n=Ma(i.list[i.at],t);n&&(i.list[i.at]=n,c[i.at].body=n)}for(const e of c)l.push(...$a(e.body,s.get(e.id)||[],n));const d=(e.wall_columns||[]).map(e=>xa(e,t,i)),u=ls(o,n).flatMap(e=>$a(e,r,n));return{partitions:a,columns:d,patches:u,all:[...l,...u,...d]}}function Ca(e){try{const t=e.map(e=>ba(e)).filter(e=>!!e).map(e=>va(e));return t.length?Wt(t[0],...t.slice(1)):null}catch{return null}}const Ta=e=>`M ${e.map(e=>`${e[0]} ${e[1]}`).join(" L ")} Z`;function Da(e){const t=[];for(const i of e||[]){if(Fa([i])<=1e-6)continue;const e=[];for(const t of i||[]){const i=(t||[]).filter(e=>Array.isArray(e)&&e.length>=2);i.length<4||e.push(Ta(i.slice(0,-1)))}e.length&&t.push(e.join(" "))}return t}function Aa(e,t,i={}){const n=Ca(e.filter(e=>e.length>=3)),r=t.some(e=>!ba(e))?null:Ca(t);if(!n)return[];if(r)try{return Da(Ut(n,r))}catch{}return function(e,t,i){let n=null;for(let r=0;r=4&&t.push(e.slice(0,-1).map(e=>[e[0],e[1]]));return t}function Ia(e){const t=[];for(const i of e||[]){const e=i?.[0];e?.length>=4&&t.push(e.slice(0,-1).map(e=>[e[0],e[1]]))}return t}function Oa(e,t){let i=!1;for(let n=0,r=t.length-1;ne[1]!=l>e[1]&&e[0]<(a-o)*(e[1]-s)/(l-s||1e-12)+o&&(i=!i)}return i}function Ea(e,t){for(const i of t||[]){const t=i?.[0];if(!t?.length||!Oa(e,t))continue;let n=!1;for(let t=1;ti)return!1;if(Math.abs(ga(e.cm)-ga(t.cm))>1e-6)return!1;if(e.shape!==t.shape)return!0;if("circle"===e.shape||"circle"===t.shape)return!0;const n=Math.abs(fa(e.angle)-fa(t.angle));return Math.min(n,90-n)<=1e-6}const Ha=2.54;function La(e){const t="number"==typeof e?e:NaN;return!Number.isFinite(t)||t<=0||5===t?1:5/t}function Ba(e,t){return e*La(t)}function qa(e){return e?Ha:1}function ja(e,t){if(!t)return String(e);const i=e/Ha;return String(Math.round(1e6*i)/1e6)}function Wa(e,t){return t?e*Ha:e}const Ua=1e3;function Ga(e,t){const i=Number(e),n=Number.isFinite(i)&&i>0?i:1,r=n>=1?t:t*n,o=n>=1?t/n:t;return{x:(t-r)/2,y:(t-o)/2,w:r,h:o}}const Va=.01,Ka=100;function Ya(e,t=1e3){const i=Ga(e?.plan_aspect,t),n=Number(e?.plan_scale),r=Number.isFinite(n)&&n>0?Math.min(Ka,Math.max(Va,n)):1,o=Number(e?.plan_scale_x),s=Number(e?.plan_scale_y),a=Number.isFinite(o)&&o>0?Math.min(Ka,Math.max(Va,o)):r,l=Number.isFinite(s)&&s>0?Math.min(Ka,Math.max(Va,s)):r,c=Number(e?.plan_x),h=Number(e?.plan_y),d=Rr(e?.plan_angle);return{x:i.x+(Number.isFinite(c)?sl(c):0)*t,y:i.y+(Number.isFinite(h)?sl(h):0)*t,w:i.w*a,h:i.h*l,...d?{angle:d}:{}}}function Xa(e){if(null==e.x||null==e.y)return{x:e.x,y:e.y,w:e.w,h:e.h};const t=Number(e.w)||0,i=Number(e.h)||0;return{x:t<0?e.x+t:e.x,y:i<0?e.y+i:e.y,w:Math.abs(t),h:Math.abs(i)}}function Za(e){return e&&Array.isArray(e.spaces)?e.spaces.map(e=>{const t=Ua,i=function(e){return Array.isArray(e)&&4===e.length&&e.every(e=>Number.isFinite(e))&&e[2]>1e-6&&e[3]>1e-6?e:[0,0,1,1]}(e.view_box);return{id:e.id,title:e.title,cellCm:Number.isFinite(Number(e.cell_cm))&&Number(e.cell_cm)>0?Number(e.cell_cm):5,vb:[i[0]*Ua,i[1]*t,i[2]*Ua,i[3]*t],bg:e.plan_url?{href:En(e.plan_url),...Ya(e,Ua)}:null,rooms:(e.rooms||[]).map(e=>{const i={...e,...Xa(e)};return{id:i.id,name:i.name,area:i.area??null,open_to:i.open_to||void 0,settings:i.settings||void 0,x:null!=i.x?i.x*Ua:void 0,y:null!=i.y?i.y*t:void 0,w:null!=i.w?i.w*Ua:void 0,h:null!=i.h?i.h*t:void 0,poly:i.poly?i.poly.map(e=>[e[0]*Ua,e[1]*t]):void 0,wall_ids:Array.isArray(i.wall_ids)?[...i.wall_ids]:void 0}}),wall_segments:(e.wall_segments||[]).map(e=>({...e,id:String(e.id),a:[Number(e.a?.[0])*Ua,Number(e.a?.[1])*t],b:[Number(e.b?.[0])*Ua,Number(e.b?.[1])*t],cm:Number(e.cm)})),partitions:(e.partitions||[]).map(e=>({id:e.id,a:[e.a[0]*Ua,e.a[1]*t],b:[e.b[0]*Ua,e.b[1]*t],cm:Number(e.cm)})),wall_columns:(e.wall_columns||[]).map(e=>({id:e.id,shape:"circle"===e.shape?"circle":"square",center:[e.center[0]*Ua,e.center[1]*t],cm:Number(e.cm),..."circle"===e.shape?{}:{angle:fa(e.angle)}}))}}):[]}const Ja=5e3,Qa=Ja*Ua,el=240,tl=Ua/el,il=1/el;function nl(e){if(!Number.isFinite(e))return e;const t=Math.round(e*el/Ua)*Ua/el;return Math.abs(t-e)<=1e-9*tl?e:t}function rl(e){return{x:nl(e.x),y:nl(e.y)}}function ol(e){return Number.isFinite(e)?Math.min(Qa,Math.max(-Qa,e)):0}function sl(e){return Number.isFinite(e)?Math.min(Ja,Math.max(-Ja,e)):0}const al=1/3,ll=200;function cl(e){return"house"===e?"house":"content"}function hl(e){let t=1/0,i=1/0,n=-1/0,r=-1/0;for(const o of e){const e=Number(o[0]),s=Number(o[1]);Number.isFinite(e)&&Number.isFinite(s)&&(en&&(n=e),s>r&&(r=s))}return t>n?null:{minX:t,minY:i,maxX:n,maxY:r}}function dl(e){const t=[],i=e=>{if(Array.isArray(e))if(e.length>=2&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1])))t.push([Number(e[0]),Number(e[1])]);else for(const t of e)i(t)};return i(e),hl(t)}function ul(e,t){const i=Number.isFinite(t)&&t>0?t:0;return{minX:e.minX-i,minY:e.minY-i,maxX:e.maxX+i,maxY:e.maxY+i}}function pl(e){return e.poly&&e.poly.length?hl(e.poly):null==e.x||null==e.y?null:hl([[e.x,e.y],[e.x+(e.w||0),e.y+(e.h||0)]])}function _l(e,t=1e3,i=1e3){const n=Number(e.x)*t,r=Number(e.y)*i,o=Number(e.w)*t,s=Number(e.h)*i;return![n,r,o,s].every(Number.isFinite)||o<=0||s<=0?null:hl(Ir({x:n,y:r,w:o,h:s,angle:Rr(e.angle)||void 0}))}function ml(e,t){const i=[];for(const t of e.rooms||[]){const e=pl(t);e&&i.push(e)}if(e.bg){const t=hl(Ir(e.bg));t&&i.push(t)}for(const e of t||[])if(Array.isArray(e)){const t=hl([e]);t&&i.push(t)}else i.push(e);return i}const gl=e=>{if(!e.length)return 0;const t=[...e].sort((e,t)=>e-t),i=t.length>>1;return t.length%2?t[i]:(t[i-1]+t[i])/2},fl=e=>{let t=1/0,i=1/0,n=-1/0,r=-1/0;for(const o of e)o.minXn&&(n=o.maxX),o.maxY>r&&(r=o.maxY);return t>n||i>r?null:{x:t,y:i,w:n-t,h:r-i}};function vl(e,t){let{x:i,y:n,w:r,h:o}=e;r<30&&(i=i+r/2-100,r=ll),o<30&&(n=n+o/2-100,o=ll);const s="number"==typeof t?{top:t,right:t,bottom:t,left:t}:t,a=Math.max(r,o),l=a*s.top,c=a*s.right,h=a*s.bottom,d=a*s.left;return{x:i-d,y:n-l,w:r+d+c,h:o+l+h}}function yl(e,t={}){const i=t.pad??.05,n=t.k??10,r=t.minSpread??50,o=e.filter(e=>Number.isFinite(e.minX)&&Number.isFinite(e.minY)&&Number.isFinite(e.maxX)&&Number.isFinite(e.maxY)&&Math.abs(e.minX)<=Qa&&Math.abs(e.maxX)<=Qa&&Math.abs(e.minY)<=Qa&&Math.abs(e.maxY)<=Qa);if(!o.length)return{core:null,all:null,outliers:0};const s=fl(o);if(o.length<4){const e=vl(s,i);return{core:e,all:e,outliers:0}}const a=o.map(e=>(e.minX+e.maxX)/2),l=o.map(e=>(e.minY+e.maxY)/2),c=gl(a),h=gl(l),d=o.map((e,t)=>Math.max(Math.abs(a[t]-c),Math.abs(l[t]-h))),u=Math.max(((e,t)=>e.length?e[Math.min(e.length-1,Math.max(0,Math.round(t*(e.length-1))))]:0)([...d].sort((e,t)=>e-t),.75),r),p=d.map(e=>e>n*u),_=p.filter(Boolean).length,m=_&&_<=o.length*al?o.filter((e,t)=>!p[t]):o;return{core:vl(fl(m)||s,i),all:vl(s,i),outliers:m===o?0:_}}function bl(e){return yl(e,{pad:0}).all}function wl(e,t,i=.05){const n=yl(ml(e,t),{pad:i});if(n.core)return n.core;const r=e.vb&&4===e.vb.length&&e.vb[2]>0&&e.vb[3]>0?e.vb:[0,0,Ua,Ua];return{x:r[0],y:r[1],w:r[2],h:r[3]}}function kl(e){const t=wl(e);return{x:t.x+t.w/2,y:t.y+t.h/2}}function xl(e){const t=[];for(const i of e.rooms||[]){const e=pl(i);e&&t.push(e)}const i=yl(t,{pad:0}).core,n=Ua*La(e.cellCm??5);return i?Math.max(n,Math.min(Qa,Math.max(i.w,i.h))):n}function Sl(e,t,i,n=1){const r=Number(i),o=Number.isFinite(n)&&n>0?n:1;return!Number.isFinite(r)||r<=0?e*o:e*xl(t)*o/r}const $l=[1,2,5,10,20,50,100,200,500,1e3];function Ml(e,t,i=7){if(!(e>0&&t>0&&Number.isFinite(t)))return null;const n=$l.find(n=>e*n*t>=i);if(void 0===n)return null;const r=$l.find(e=>e>=5*n)??5*n;return{fine:n,coarse:r}}function Rl(e){if(e.poly&&e.poly.length){const t=e.poly.map(e=>e[0]),i=e.poly.map(e=>e[1]),n=Math.min(...t),r=Math.min(...i);return{x:n,y:r,w:Math.max(...t)-n,h:Math.max(...i)-r}}return{x:e.x??0,y:e.y??0,w:e.w??0,h:e.h??0}}function Cl(e,t,i,n,r,o=new Set){const s=t[e.id];return!o.has(e.id)&&s&&s.s===e.space?{x:s.x*Ua,y:s.y*Ua}:n[e.id]?n[e.id]:rl(kl(r))}function Tl(e,t,i,n){const r=i["rl_"+(e.id||"")];if(r&&r.s===t)return{x:r.x*Ua,y:r.y*Ua};const o=function(e){if(e.poly){const t=e.poly.length;return[e.poly.reduce((e,t)=>e+t[0],0)/t,e.poly.reduce((e,t)=>e+t[1],0)/t]}return[e.x+e.w/2,e.y+.1*Math.min(e.w,e.h)]}(e);return rl({x:o[0],y:o[1]})}function Dl(e,t){for(const i of e?.spaces??[])for(const e of i?.decor??[])if("furniture"===e?.kind&&"string"==typeof e.symbol&&t(e.symbol))return!0;return!1}let Al=0;const Pl=new Set;const Fl=new class{constructor(e){this.options=e,this._art=null,this._failed=!1,this._terminal=!1,this._inFlight=null,this._hosts=new Set,this._settled=[]}state(){return this._art?"ready":this._failed?"fallback":"pending"}get terminal(){return this._terminal}art(e,t){if(this._art)return this._art[e];t&&!this._failed&&this._hosts.add(t)}adopt(e,t){return!!this._art||(t!==this.options.expectedFingerprint?((this.options.warn??console.warn)("[houseplan] furniture artwork from another build ignored",{fingerprint:t}),!1):(this._install(e),!0))}ensure(){return"pending"!==this.state()?Promise.resolve():(this._inFlight||(this._inFlight=this._loadWithRetry().finally(()=>{this._inFlight=null})),this._inFlight)}onSettled(e){"pending"===this.state()?this._settled.push(e):Promise.resolve().then(e)}async _loadWithRetry(){let e=new Error("furniture artwork did not load");for(const t of[0,1])try{const i=await this.options.load(t);if(i.FURNITURE_ART_FINGERPRINT!==this.options.expectedFingerprint){this._terminal=!0,e=new Error(`furniture artwork fingerprint mismatch: expected ${this.options.expectedFingerprint}, got ${i.FURNITURE_ART_FINGERPRINT}`);break}if(this._art)return;return void this._install(i.GENERATED_FURNITURE_ART)}catch(t){e=t}this._art||(this._failed=!0,(this.options.warn??console.warn)("[houseplan] furniture artwork unavailable",e),this.options.loadFailed?.(this._terminal),this._flush())}_install(e){this._art=e,this._failed=!1,this._flush()}_flush(){const e=[...this._hosts];this._hosts.clear();for(const t of e)t.isConnected&&t.requestUpdate();const t=this._settled.splice(0);for(const e of t)e()}}({expectedFingerprint:"241ab786b7cce5c1f837e73704240f138bd3e097bfecdbb0e93046bf4a19d3ef",load:async e=>0===e?await import("./furniture-plan-art.generated-7nJsC48X.js"):await import((()=>{const e=new URL("./furniture-plan-art.generated-7nJsC48X.js",import.meta.url);return e.searchParams.set("hp_retry","art-"+ ++Al),e.href})()),loadFailed:e=>{for(const t of Pl)t(e)}}),zl=["furniture","appliance","sanitary","other"],Il=[{id:"sofa",group:"furniture",category:"sofa",w:220,h:90,g:[["r",0,0,1,1],["l",.09,.26,.91,.26],["l",.09,.26,.09,1],["l",.91,.26,.91,1],["l",.5,.26,.5,1]]},{id:"armchair",group:"furniture",category:"armchair",w:90,h:85,g:[["r",0,0,1,1],["l",.14,.28,.86,.28],["l",.14,.28,.14,1],["l",.86,.28,.86,1]]},{id:"coffee_table",group:"furniture",category:"coffee_table",w:110,h:60,g:[["r",0,0,1,1],["r",.08,.14,.84,.72]]},{id:"table_dining",group:"furniture",category:"dining_table",w:140,h:80,g:[["r",0,0,1,1],["r",.06,.11,.88,.78]]},{id:"table_round",group:"furniture",category:"dining_table",w:120,h:120,g:[["e",.5,.5,.5,.5],["e",.5,.5,.41,.41]]},{id:"chair",group:"furniture",category:"chair",w:45,h:45,g:[["r",0,0,1,.18],["r",.06,.18,.88,.8]]},{id:"desk",group:"furniture",category:"work_table",w:120,h:60,g:[["r",0,0,1,1],["r",.63,.07,.31,.86],["l",.63,.5,.94,.5]]},{id:"bed_double",group:"furniture",category:"bed",w:160,h:200,g:[["r",0,0,1,1],["r",0,0,1,.07],["r",.06,.1,.4,.15],["r",.54,.1,.4,.15],["l",0,.33,1,.33]]},{id:"bed_single",group:"furniture",category:"bed",w:90,h:200,g:[["r",0,0,1,1],["r",0,0,1,.07],["r",.15,.1,.7,.15],["l",0,.33,1,.33]]},{id:"nightstand",group:"furniture",category:"nightstand",w:45,h:40,g:[["r",0,0,1,1],["r",.12,.14,.76,.33],["r",.12,.53,.76,.33]]},{id:"wardrobe",group:"furniture",category:"wardrobe",w:100,h:60,g:[["r",0,0,1,1],["l",0,.72,1,.72],["l",.5,.72,.5,1]]},{id:"bookshelf",group:"furniture",category:"wardrobe",w:80,h:30,g:[["r",0,0,1,1],["l",.34,0,.34,1],["l",.67,0,.67,1]]},{id:"fridge",group:"appliance",category:"fridge",w:60,h:65,g:[["r",0,0,1,1],["l",0,.36,1,.36],["l",.83,.44,.83,.64]]},{id:"stove",group:"appliance",category:"cooktop",w:60,h:60,g:[["r",0,0,1,1],["e",.29,.31,.15,.15],["e",.71,.31,.15,.15],["e",.29,.71,.15,.15],["e",.71,.71,.15,.15]]},{id:"dishwasher",group:"appliance",category:"dishwasher",w:60,h:60,g:[["r",0,0,1,1],["r",.1,.12,.8,.76],["e",.5,.5,.27,.27],["e",.5,.5,.13,.13]]},{id:"washer",group:"appliance",category:"washer",w:60,h:60,g:[["r",0,0,1,1],["l",.08,.17,.92,.17],["e",.5,.57,.3,.3],["e",.5,.57,.14,.14]]},{id:"dryer",group:"appliance",category:"dryer",w:60,h:60,g:[["r",0,0,1,1],["l",.08,.17,.92,.17],["e",.5,.57,.3,.3],["p",.36,.5,.5,.64,.64,.5]]},{id:"tv",group:"appliance",category:"tv",w:120,h:30,g:[["r",0,0,1,.42],["l",.5,.42,.5,.72],["l",.3,.72,.7,.72]]},{id:"ac",group:"appliance",category:"air_conditioner",w:90,h:25,g:[["r",0,0,1,1],["l",.05,.55,.95,.55],["l",.05,.79,.95,.79]]},{id:"water_heater",group:"appliance",category:"boiler",w:45,h:45,g:[["e",.5,.5,.5,.5],["e",.5,.5,.31,.31]]},{id:"toilet",group:"sanitary",category:"toilet",w:40,h:70,g:[["r",.06,0,.88,.2],["e",.5,.58,.37,.35],["e",.5,.58,.22,.2]]},{id:"bathtub",group:"sanitary",category:"bathtub",w:170,h:75,g:[["r",0,0,1,1],["r",.05,.11,.77,.78],["e",.89,.5,.045,.1]]},{id:"shower",group:"sanitary",category:"shower",w:90,h:90,g:[["r",0,0,1,1],["l",0,0,1,1],["l",1,0,0,1],["e",.5,.5,.08,.08]]},{id:"sink",group:"sanitary",category:"sink",w:60,h:45,g:[["r",0,0,1,1],["e",.5,.6,.34,.3],["e",.5,.15,.07,.07]]},{id:"kitchen_sink",group:"sanitary",category:"kitchen_sink",w:80,h:60,g:[["r",0,0,1,1],["r",.06,.24,.44,.64],["r",.54,.24,.4,.64],["e",.5,.12,.06,.06]]},{id:"bidet",group:"sanitary",category:"bidet",w:40,h:55,g:[["e",.5,.5,.44,.5],["e",.5,.5,.26,.3]]},{id:"stairs",group:"other",category:"stairs",w:100,h:280,g:[["r",0,0,1,1],["l",0,.111,1,.111],["l",0,.222,1,.222],["l",0,.333,1,.333],["l",0,.444,1,.444],["l",0,.556,1,.556],["l",0,.667,1,.667],["l",0,.778,1,.778],["l",0,.889,1,.889],["l",.5,.93,.5,.06],["p",.38,.16,.5,.06,.62,.16]]},{id:"fireplace",group:"other",category:"fireplace",w:120,h:40,g:[["r",0,0,1,1],["p",.22,1,.22,.42,.78,.42,.78,1]]},{id:"plant",group:"other",category:"plant",w:40,h:40,g:[["e",.5,.5,.22,.22],["l",.5,.28,.5,.02],["l",.5,.72,.5,.98],["l",.28,.5,.02,.5],["l",.72,.5,.98,.5],["l",.34,.34,.13,.13],["l",.66,.66,.87,.87],["l",.66,.34,.87,.13],["l",.34,.66,.13,.87]]},{id:"rug",group:"other",category:"rug",w:200,h:140,g:[["r",0,0,1,1],["r",.06,.09,.88,.82]]}],Ol=new Set(["fridge","dishwasher","washer","dryer","ac","water_heater","shower","sink","stairs","fireplace","plant","rug"]),El=[...[{id:"coffee_table",group:"furniture",category:"coffee_table",w:120,h:60},{id:"coffee_table_round",group:"furniture",category:"coffee_table",w:80,h:80},{id:"coffee_table_oval",group:"furniture",category:"coffee_table",w:120,h:60},{id:"coffee_table_rounded",group:"furniture",category:"coffee_table",w:120,h:60},{id:"table_dining",group:"furniture",category:"dining_table",w:160,h:90},{id:"table_round",group:"furniture",category:"dining_table",w:110,h:110},{id:"table_dining_oval",group:"furniture",category:"dining_table",w:180,h:100},{id:"table_dining_rounded",group:"furniture",category:"dining_table",w:160,h:90},{id:"desk",group:"furniture",category:"work_table",w:140,h:70},{id:"desk_corner",group:"furniture",category:"work_table",w:160,h:160},{id:"chair",group:"furniture",category:"chair",w:50,h:50},{id:"chair_bar",group:"furniture",category:"chair",w:45,h:48},{id:"armchair",group:"furniture",category:"armchair",w:90,h:90},{id:"armchair_office",group:"furniture",category:"armchair",w:65,h:65},{id:"sofa",group:"furniture",category:"sofa",w:180,h:90},{id:"sofa_three_seat",group:"furniture",category:"sofa",w:240,h:90},{id:"sofa_corner_right",group:"furniture",category:"sofa",w:260,h:170},{id:"bed_single",group:"furniture",category:"bed",w:90,h:200},{id:"bed_double",group:"furniture",category:"bed",w:160,h:200},{id:"nightstand",group:"furniture",category:"nightstand",w:50,h:40},{id:"cabinet_tv",group:"furniture",category:"nightstand",w:140,h:45},{id:"cabinet_shoe",group:"furniture",category:"nightstand",w:80,h:35},{id:"cabinet_sink",group:"furniture",category:"nightstand",w:80,h:50},{id:"bookshelf",group:"furniture",category:"wardrobe",w:100,h:35},{id:"wall_unit",group:"furniture",category:"wardrobe",w:240,h:45},{id:"wardrobe",group:"furniture",category:"wardrobe",w:180,h:60},{id:"kitchen_floor",group:"furniture",category:"kitchen_cabinet",w:60,h:60},{id:"kitchen_floor_corner",group:"furniture",category:"kitchen_cabinet",w:90,h:90},{id:"kitchen_wall",group:"furniture",category:"kitchen_cabinet",w:60,h:35},{id:"kitchen_wall_corner",group:"furniture",category:"kitchen_cabinet",w:60,h:60},{id:"shelf_floor",group:"furniture",category:"shelving",w:100,h:35},{id:"shelf_wall",group:"furniture",category:"shelving",w:100,h:25},{id:"cooktop_two",group:"appliance",category:"cooktop",w:30,h:50},{id:"stove",group:"appliance",category:"cooktop",w:60,h:60},{id:"tv",group:"appliance",category:"tv",w:120,h:28},{id:"tv_wall",group:"appliance",category:"tv",w:120,h:15},{id:"toilet",group:"sanitary",category:"toilet",w:40,h:70},{id:"toilet_built_in",group:"sanitary",category:"toilet",w:40,h:55},{id:"bathtub",group:"sanitary",category:"bathtub",w:170,h:75},{id:"bathtub_corner",group:"sanitary",category:"bathtub",w:140,h:140},{id:"bidet",group:"sanitary",category:"bidet",w:40,h:60},{id:"bidet_built_in",group:"sanitary",category:"bidet",w:40,h:50},{id:"kitchen_sink",group:"sanitary",category:"kitchen_sink",w:60,h:50},{id:"kitchen_sink_double",group:"sanitary",category:"kitchen_sink",w:90,h:50}].map(e=>({id:e.id,group:e.group,category:e.category,w:e.w,h:e.h,designer:!0})),...Il.filter(e=>Ol.has(e.id))],Nl=new Map(El.map(e=>[e.id,e]));function Hl(e){return e&&Nl.get(e)||null}function Ll(e){return!0===Nl.get(e)?.designer}function Bl(e){return El.filter(t=>t.group===e)}function ql(e){const t=Hl(e);return t?{w:t.w,h:t.h}:{w:60,h:60}}function jl(e,t,i=tl,n=1e3){const r=Number(t)>0?Number(t):5;return(Number(e)||0)/r*i/n}const Wl=5e-4,Ul=Ja;function Gl(e){return Number.isFinite(e)?Math.max(Wl,Math.min(Ul,e)):Wl}function Vl(e){return Number.isFinite(e)?Math.max(1,Math.min(1e4,e)):1}const Kl=e=>{const t=Math.round(1e3*e)/1e3;return Object.is(t,-0)?"0":String(t)};function Yl(e,t){const i=Hl(e);if(!i)return null;if(i.designer)return Fl.art(e,t)??null;const n=function(e,t,i){if(!e.g)return"";const n=e=>Kl(e*t),r=e=>Kl(e*i),o=[];for(const s of e.g)if("r"===s[0]){const[,e,t,i,a]=s;o.push(`M${n(e)} ${r(t)}H${n(e+i)}V${r(t+a)}H${n(e)}Z`)}else if("l"===s[0]){const[,e,t,i,a]=s;o.push(`M${n(e)} ${r(t)}L${n(i)} ${r(a)}`)}else if("e"===s[0]){const[,e,a,l,c]=s;o.push(`M${n(e-l)} ${r(a)}A${Kl(l*t)} ${Kl(c*i)} 0 0 1 ${n(e+l)} ${r(a)}A${Kl(l*t)} ${Kl(c*i)} 0 0 1 ${n(e-l)} ${r(a)}Z`)}else{const e=s.slice(1);if(e.length<4)continue;let t=`M${n(e[0])} ${r(e[1])}`;for(let i=2;i+10?n:Number.isFinite(r)&&r>0?r:1,s=Number(t),a=o*(Number.isFinite(s)&&s>0?s:1);return Number.isFinite(a)&&a>0?a:o}function Zl(e,t,i,n,r){const o=e+i/2,s=t+n/2,a=(Number(r)||0)*Math.PI/180,l=Math.cos(a),c=Math.sin(a),h=(e,t)=>{const i=e-o,n=t-s;return[o+i*l-n*c,s+i*c+n*l]};return[h(e,t),h(e+i,t),h(e+i,t+n),h(e,t+n)]}function Jl(e,t,i,n,r,o,s){const a=Number.isFinite(s)&&s>0?s:1e-6,l=(Number(e.angle)||0)*Math.PI/180,c=Math.cos(l),h=Math.sin(l),d=-Math.sin(l),u=Math.cos(l),p=e.x+e.w/2,_=e.y+e.h/2,m=t>0?-e.w/2:t<0?e.w/2:0,g=i>0?-e.h/2:i<0?e.h/2:0,f=p+m*c+g*d,v=_+m*h+g*u,y=n-f,b=r-v,w=t?(y*c+b*h)*(t>0?1:-1):e.w,k=i?(y*d+b*u)*(i>0?1:-1):e.h;let x=t?Math.abs(w):e.w,S=i?Math.abs(k):e.h;if(o&&t&&i){const t=x/Math.max(e.w,a),i=S/Math.max(e.h,a),n=Math.abs(t-1)>=Math.abs(i-1)?t:i,r=Math.max(a/e.w,a/e.h),o=Math.max(r,Number.isFinite(n)?n:r);x=e.w*o,S=e.h*o}x=Math.max(a,Number.isFinite(x)?x:a),S=Math.max(a,Number.isFinite(S)?S:a);const $=!!t&&w<0,M=!!i&&k<0,R=t?(t>0?1:-1)*($?-1:1):0,C=i?(i>0?1:-1)*(M?-1:1):0,T=f+R*(x/2)*c+C*(S/2)*d,D=v+R*(x/2)*h+C*(S/2)*u,A=!!e.flip_h!==$,P=!!e.flip_v!==M;return{x:T-x/2,y:D-S/2,w:x,h:S,...Number(e.angle)?{angle:Number(e.angle)}:{},...A?{flip_h:!0}:{},...P?{flip_v:!0}:{}}}function Ql(e,t,i,n){let r=Number(e)+(Number(i)-Number(t));if([r,t,i].every(Number.isFinite)||(r=0),n){const e=r/45;r=45*(e<0?-Math.round(Math.abs(e)):Math.round(e))}return r=(r%360+360)%360,r>180?r-360:r}function ec(e,t,i,n,r){const o=e.x*t,s=e.y*i,a=e.w*t,l=e.h*i,c=o+a/2,h=s+l/2,d=o+(e.flip_h?a:0),u=s+(e.flip_v?l:0),p=(e.flip_h?-1:1)*a/n,_=(e.flip_v?-1:1)*l/r,m=Number(e.angle)||0;return(m?`rotate(${m} ${c} ${h}) `:"")+`translate(${d} ${u}) scale(${p} ${_})`}function tc(e,t,i,n=.1){if("string"==typeof e&&!e.trim())return null;const r=Number(e);if(!Number.isFinite(r)||0===r)return null;const o=r*(t?30.48:100),s=Math.abs(o);return si?null:o}function ic(e,t,i){const n=Math.abs(Number(e))/(i?30.48:100),r=Number(n.toFixed(6));return String(t?-r:r)}const nc=15e3,rc=2e3,oc=new WeakMap;function sc(e,t){let i=oc.get(e);if(!i){const t=new Set;i={hiddenAt:"hidden"===e.visibilityState?Date.now():0,token:0,subscribers:t,onVisibility:()=>{const t=oc.get(e);if(!t)return;const i=Date.now();if("hidden"===e.visibilityState){t.hiddenAt||(t.hiddenAt=i);const e={kind:"hidden",token:t.token,at:i,hiddenFor:0,long:!1};for(const i of[...t.subscribers])i(e);return}const n=t.hiddenAt?Math.max(0,i-t.hiddenAt):0;t.hiddenAt=0,t.token++;const r={kind:"visible",token:t.token,at:i,hiddenFor:n,long:n>=nc};for(const e of[...t.subscribers])e(r)},onPageShow:t=>{const i=oc.get(e);if(!i)return;const n=Date.now();i.token++;const r={kind:"pageshow",token:i.token,at:n,hiddenFor:0,long:!!t.persisted,persisted:!!t.persisted};for(const e of[...i.subscribers])e(r)}},oc.set(e,i),e.addEventListener("visibilitychange",i.onVisibility),e.defaultView?.addEventListener("pageshow",i.onPageShow)}return i.subscribers.add(t),()=>{const i=oc.get(e);i&&(i.subscribers.delete(t),i.subscribers.size||(e.removeEventListener("visibilitychange",i.onVisibility),e.defaultView?.removeEventListener("pageshow",i.onPageShow),oc.delete(e)))}}const ac={now:()=>Date.now(),setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>window.clearTimeout(e),requestAnimationFrame:e=>window.requestAnimationFrame(e),cancelAnimationFrame:e=>window.cancelAnimationFrame(e)};class lc{constructor(e,t=ac){this.onChange=e,this.clock=t,this._state="steady",this._token=0,this._frameFingerprint="",this._hasCompleteFrame=!1,this._overlayPhase="none",this._recoveryReason=null,this._overlayTimer=0,this._overlayRaf=0,this._overlayOpaqueAt=0,this._barrierRafs=new Set,this._trace=[],this._disposed=!1}get state(){return this._state}get token(){return this._token}get frameFingerprint(){return this._frameFingerprint}get hasCompleteFrame(){return this._hasCompleteFrame}get overlayPhase(){return this._overlayPhase}get overlayVisible(){return"none"!==this._overlayPhase}get overlayBlocksInteraction(){return this.overlayVisible}get recoveryReason(){return this._recoveryReason}get trace(){return this._trace.map(e=>({...e,...e.stage?{stage:[...e.stage]}:{}}))}note(e,t={}){this.record(e,void 0,t)}record(e,t,i={}){this._trace.push({at:this.clock.now(),token:this._token,event:e,state:this._state,...t?{reason:t}:{},...i}),this._trace.length>80&&this._trace.splice(0,this._trace.length-80)}changed(){this._disposed||this.onChange()}adoptCompleteFrame(e){e&&(this._hasCompleteFrame=!0,this._frameFingerprint=e,this._state="steady",this._recoveryReason=null,this.clearOverlay(),this.record("frame-adopted"),this.changed())}markCompleteFrame(e){e&&(this._hasCompleteFrame=!0,this._frameFingerprint=e,this._state="steady",this._recoveryReason=null,this.clearOverlay(),this.record("frame-complete"),this.changed())}refreshCompleteFrame(e){!this._disposed&&this._hasCompleteFrame&&"steady"===this._state&&e&&e!==this._frameFingerprint&&(this._frameFingerprint=e,this.record("frame-refreshed"))}visibility(e){return"hidden"===e.kind?(this.record("visibility-hidden"),this._token):e.long||"visible"!==e.kind&&"pageshow"!==e.kind?this.beginCandidate("pageshow"===e.kind?"pageshow":"long-resume"):(this.record("pageshow"===e.kind?"pageshow-noop":"visibility-visible-quick"),this._token)}beginCandidate(e,t="plan"){return this._token++,this._recoveryReason=t,this._hasCompleteFrame?(this._state="connection"===t?"offline-stale":"holding",this.clearOverlay()):this.overlayVisible?this._state="overlay-visible":(this._state="overlay-pending",this.scheduleOverlay(t)),this.record("candidate-start",e),this.changed(),this._token}connectionLost(){return this.beginCandidate("connection-lost","connection")}candidateReady(e){return!this._disposed&&e===this._token&&(this._state="candidate-ready",this.record("candidate-ready"),this.changed(),!0)}async commitAfterPaint(e,t){if(this._disposed||e!==this._token)return!1;let i=!0;const n=(async()=>{for(await t.updateComplete();i&&!this._disposed&&e===this._token;)if(t.stageValid()&&t.assetsReady()){if(await this.nextFrame(),e!==this._token||!t.stageValid()||!t.assetsReady())continue;if(await this.nextFrame(),e===this._token&&t.stageValid()&&t.assetsReady())return!0}else await this.nextFrame();return!1})();let r=0;const o=new Promise(e=>{r=this.clock.setTimeout(()=>e({ready:!1,timedOut:!0}),rc)}),s=await Promise.race([n.then(e=>({ready:e,timedOut:!1})),o]);return i=!1,this.clock.clearTimeout(r),!this._disposed&&e===this._token&&(!(!s.ready&&!s.timedOut)&&(s.ready?(this._hasCompleteFrame=!0,this._frameFingerprint=t.frameFingerprint(),this.record("paint-barrier"),this.finishOverlayAfterCommit(),!0):(this.record("paint-barrier-timeout"),this._hasCompleteFrame?(this._state="connection"===this._recoveryReason?"offline-stale":"steady",this.clearOverlay()):(this._state="recovery-error","opaque"!==this._overlayPhase&&this.showOverlayNow()),this.changed(),!1)))}retry(e=this._recoveryReason||"plan"){return this.beginCandidate("retry",e)}nextFrame(){return new Promise(e=>{const t=this.clock.requestAnimationFrame(()=>{this._barrierRafs.delete(t),e()});this._barrierRafs.add(t)})}scheduleOverlay(e){this.clearOverlayTimer(),this._recoveryReason=e,this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._hasCompleteFrame||"overlay-pending"!==this._state&&"candidate-ready"!==this._state||(this._state="overlay-visible",this._overlayPhase="entering",this.record("overlay-enter"),this.changed(),this._overlayRaf=this.clock.requestAnimationFrame(()=>{this._overlayRaf=0,"entering"===this._overlayPhase&&(this._overlayPhase="fading-in",this.changed(),this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,"fading-in"===this._overlayPhase&&(this._overlayPhase="opaque",this._overlayOpaqueAt=this.clock.now(),this.record("overlay-opaque"),this.changed())},150))}))},150)}showOverlayNow(){this.clearOverlayTimer(),this._overlayPhase="opaque",this._overlayOpaqueAt=this.clock.now(),this.record("overlay-error")}finishOverlayAfterCommit(){if(this.clearOverlayTimer(),"none"===this._overlayPhase||"entering"===this._overlayPhase||"fading-in"===this._overlayPhase)return this.clearOverlay(),this._state="steady",this._recoveryReason=null,this.record("candidate-committed"),void this.changed();const e=Math.max(0,this._overlayOpaqueAt+250-this.clock.now());this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._overlayPhase="leaving",this.record("overlay-leave"),this.changed(),this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._overlayPhase="none",this._state="steady",this._recoveryReason=null,this.record("candidate-committed"),this.changed()},180)},e)}clearOverlayTimer(){this._overlayTimer&&this.clock.clearTimeout(this._overlayTimer),this._overlayTimer=0}clearOverlay(){this.clearOverlayTimer(),this._overlayRaf&&this.clock.cancelAnimationFrame(this._overlayRaf),this._overlayRaf=0,this._overlayPhase="none",this._overlayOpaqueAt=0}dispose(){this._disposed=!0,this._token++,this.clearOverlay();for(const e of this._barrierRafs)this.clock.cancelAnimationFrame(e);this._barrierRafs.clear()}}function cc(e){let t=2166136261,i=2654435769;const n=new WeakSet,r=e=>{for(let n=0;n>>0)+(i>>>2)}},o=e=>{if(null===e)return void r("n");const t=typeof e;if("string"===t)return void r(`s${e.length}:${e}`);if("number"===t)return void r(`d${Number.isNaN(e)?"NaN":String(e)}`);if("boolean"===t)return void r(e?"t":"f");if("undefined"===t)return void r("u");if("object"!==t)return void r(`${t}:${String(e)}`);const i=e;if(n.has(i))r("[cycle]");else{if(n.add(i),Array.isArray(e)){r("[");for(const t of e)o(t);return r("]"),void n.delete(i)}r("{");for(const t of Object.keys(e).sort())r(t),o(e[t]);r("}"),n.delete(i)}};return o(e),`${(t>>>0).toString(16).padStart(8,"0")}${(i>>>0).toString(16).padStart(8,"0")}`}function hc(e){return cc(e)}const dc=new WeakMap;class uc{constructor(e,t=()=>Date.now()){this.onUpdate=e,this.now=t,this.fallbackAuthority={},this.referenceOwner={},this.referenced=new Set,this.queued=new Set,this.disposed=!1,this.sharedUpdate=()=>{this.disposed||this.onUpdate()}}bind(e){const t=((e,t)=>{const i=e?.connection||e?.callWS||t;return!i||"object"!=typeof i&&"function"!=typeof i?t:i})(e,this.fallbackAuthority);return this.shared&&this.authority===t||(this.shared&&(this.shared.listeners.delete(this.sharedUpdate),this.shared.references.delete(this.referenceOwner)),this.authority=t,this.shared=(e=>{let t=dc.get(e);return t||(t={signed:{},queued:new Set,inFlight:new Map,retry:new Map,listeners:new Set,settlers:new Set,references:new Map},dc.set(e,t)),t})(t),this.disposed||(this.shared.listeners.add(this.sharedUpdate),this.shared.references.set(this.referenceOwner,new Set(this.referenced)))),this.shared}start(e,t){this.disposed=!1,this.referenced=new Set(t());const i=this.bind(e());i.listeners.add(this.sharedUpdate),i.references.set(this.referenceOwner,new Set(this.referenced)),this.stopTimer(),this.resignTimer=setInterval(()=>this.resign(e(),t()),288e5)}dispose(){if(this.disposed=!0,this.stopTimer(),clearTimeout(this.batchTimer),this.shared){this.shared.listeners.delete(this.sharedUpdate),this.shared.references.delete(this.referenceOwner);for(const e of this.queued)this.shared.queued.delete(e)}this.queued.clear()}invalidate(e){const t=this.bind(e);clearTimeout(this.batchTimer),this.queued.clear(),t.queued.clear(),t.inFlight.clear(),t.retry.clear(),t.signed={}}stopTimer(){void 0!==this.resignTimer&&clearInterval(this.resignTimer),this.resignTimer=void 0}display(e,t){const i=En(t);if(!i.startsWith("/api/houseplan/content/"))return i;const n=this.bind(e);this.referenced.add(i),n.references.set(this.referenceOwner,new Set(this.referenced));const r=n.signed[i],o=r?this.now()-r.at:1/0;return o{const t=[...this.queued];this.queued.clear();for(const e of t)i.queued.delete(e);this.sign(e,t)},30))}sign(e,t){if(!t.length||!e?.callWS)return;const i=this.bind(e);for(const n of function(e,t){const i=Math.max(1,Math.floor(t)),n=[];for(let t=0;t{const n=i.inFlight.get(e);return!(void 0!==n&&t-n<15e3)&&(i.inFlight.set(e,t),!0)});r.length&&e.callWS({type:"houseplan/content/sign",paths:r}).then(e=>{const t=this.now();let n=0,o=!1;for(const s of r){const r=e?.urls?.[s];if("string"==typeof r&&r){const e=i.signed[s];e?.loaded&&e.url!==r?(e.pending={url:r,at:t},this.preloadReplacement(i,s,r,t)):(i.signed[s]={url:r,at:t,loaded:e?.url===r&&!!e.loaded},o=!0),i.retry.delete(s),n++}else this.backOff(i,s)}if(n&&(this.trimShared(i),o))for(const e of[...i.listeners])e()}).catch(()=>{for(const e of r)this.backOff(i,e)}).finally(()=>{for(const e of r)i.inFlight.get(e)===t&&i.inFlight.delete(e);for(const e of[...i.settlers])e()})}}preloadReplacement(e,t,i,n){const r=()=>{const r=e.signed[t];if(r?.pending?.url===i){e.signed[t]={url:i,at:n,loaded:!0},e.retry.delete(t),this.trimShared(e);for(const t of[...e.listeners])t()}},o=()=>{const n=e.signed[t];n?.pending?.url===i&&(delete n.pending,this.backOff(e,t))};if("undefined"==typeof Image)return void r();const s=new Image;s.onload=()=>{("function"==typeof s.decode?s.decode():Promise.resolve()).then(r).catch(o)},s.onerror=o,s.src=i}preloadCurrentImage(e,t,i){if(i.loaded)return Promise.resolve(!0);if(i.preload)return i.preload;if("undefined"==typeof Image)return i.loaded=!0,Promise.resolve(!0);const n=i.url;return i.preload=new Promise(r=>{const o=new Image;let s=!1;const a=o=>{if(s)return;s=!0,clearTimeout(l);const a=e.signed[t];if(a===i&&delete a.preload,o&&a===i&&a.url===n){a.loaded=!0;for(const t of[...e.listeners])t();r(!0)}else o||a!==i||this.backOff(e,t),r(!1)};o.onload=()=>{("function"==typeof o.decode?o.decode():Promise.resolve()).then(()=>a(!0)).catch(()=>a(!1))},o.onerror=()=>a(!1);const l=setTimeout(()=>a(!1),rc);o.src=n}),i.preload}prepareImage(e,t){const i=En(t);if(!i.startsWith("/api/houseplan/content/"))return Promise.resolve(!0);const n=this.bind(e),r=()=>{const t=n.signed[i];if(t&&this.now()-t.atthis.now()&&!n.inFlight.has(i)&&!n.queued.has(i)?Promise.resolve(!1):null},o=r();return o?(s=o,new Promise(e=>{let t=!1;const i=i=>{t||(t=!0,clearTimeout(n),e(i))},n=setTimeout(()=>i(!1),rc);s.then(i).catch(()=>i(!1))})):new Promise(e=>{let t=!1,i=null;const o=i=>{t||(t=!0,clearTimeout(a),n.settlers.delete(s),e(i))},s=()=>{t||i||(i=r(),i&&i.then(o).catch(()=>o(!1)))},a=setTimeout(()=>o(!1),rc);n.settlers.add(s),s()});var s}backOff(e,t){const i=e.retry.get(t)?.delay||0,n=Math.min(6e4,i?2*i:2e3);e.retry.set(t,{notBefore:this.now()+n,delay:n})}trimShared(e){const t=Object.entries(e.signed);if(t.length<=512)return;const i=new Set(e.inFlight.keys());for(const t of e.references.values())for(const e of t)i.add(e);for(const[e,n]of t)(n.pending||n.preload)&&i.add(e);t.sort((e,t)=>t[1].at-e[1].at);const n=t.filter(([e])=>i.has(e));for(const e of t){if(n.length>=512)break;i.has(e[0])||n.push(e)}e.signed=Object.fromEntries(n)}resign(e,t){const i=this.bind(e);this.referenced=new Set(t),i.references.set(this.referenceOwner,new Set(this.referenced));const n=this.now(),r=new Set;for(const e of i.references.values())for(const t of e)r.add(t);const o={};for(const[e,t]of Object.entries(i.signed))r.has(e)&&n-t.at!!o[e]&&!o[e].pending))}markLoaded(e,t,i){const n=En(t);if(!n.startsWith("/api/houseplan/content/"))return;const r=this.bind(e).signed[n];if(r&&(!i||r.url===i)&&!r.loaded){r.loaded=!0;for(const t of[...this.bind(e).listeners])t()}}isReady(e,t){const i=En(t);if(!i.startsWith("/api/houseplan/content/"))return!0;const n=this.bind(e).signed[i];return!!n&&this.now()-n.at=2&&(this._sequenceMultitouch=!0,this._postGestureClickBlocked=!0))}pointerTerminal(e,t){if("touch"!==t)return!1;const i=this._sequenceMultitouch;return this._activeTouchPointers.delete(e),0===this._activeTouchPointers.size&&(this._sequenceMultitouch=!1),i}reset(){this._activeTouchPointers.clear(),this._sequenceMultitouch=!1,this._postGestureClickBlocked=!1}}const _c=1e-7,mc=(e,t)=>{const i=e.x-t.x,n=e.y-t.y;return i*i+n*n};function gc(e){const t=Math.max(0,e.floorRadius);return{left:Math.min(e.painted.left,e.center.x-t),top:Math.min(e.painted.top,e.center.y-t),right:Math.max(e.painted.right,e.center.x+t),bottom:Math.max(e.painted.bottom,e.center.y+t)}}function fc(e,t){let i=null,n=Number.POSITIVE_INFINITY;for(const r of e){const e=mc(t,r.center);(efunction(e,t){const i=Math.max(0,t.right-t.left),n=Math.max(0,t.bottom-t.top);if(i<=0||n<=0)return!1;const r=Math.min(i,n)/2,o=Math.max(t.left+r,Math.min(t.right-r,e.x)),s=Math.max(t.top+r,Math.min(t.bottom-r,e.y));return mc(e,{x:o,y:s})<=r*r+_c}(t,e.painted));if(i.length)return fc(i,t);return fc(e.filter(e=>{const i=Math.max(0,e.floorRadius);return mc(t,e.center)<=i*i+_c}),t)}class yc{constructor(e,t=44){this.cellSize=t,this.buckets=new Map;const i=Number.isFinite(t)&&t>0?t:44;this.cellSize=i;for(const t of e){const e=gc(t),n=Math.floor(e.left/i),r=Math.floor(e.right/i),o=Math.floor(e.top/i),s=Math.floor(e.bottom/i);for(let e=n;e<=r;e++)for(let i=o;i<=s;i++){const n=`${e}:${i}`,r=this.buckets.get(n);r?r.push(t):this.buckets.set(n,[t])}}}resolve(e){const t=`${Math.floor(e.x/this.cellSize)}:${Math.floor(e.y/this.cellSize)}`;return vc(this.buckets.get(t)||[],e)}}class bc{constructor(){this.active=new Map,this.released=new Map}begin(e,t){this.released.delete(e),this.active.set(e,t)}owner(e){return this.active.get(e)||null}release(e){const t=this.active.get(e)||null;if(!t)return this.released.get(e)||null;for(this.active.delete(e),this.released.set(e,t);this.released.size>16;){const e=this.released.keys().next().value;if(void 0===e)break;this.released.delete(e)}return t}consumeClick(e){const t=this.released.get(e)||null;return this.released.delete(e),t}cancel(e){const t=this.active.get(e)||null;return this.active.delete(e),t}clear(){this.active.clear(),this.released.clear()}}class wc{constructor(){this.index=null,this.pointers=new bc,this.hoverId=null,this.hoverElement=null}invalidate(){this.index=null}reset(e){this.invalidate(),this.pointers.clear(),this.hover(e,null)}clearPointers(){this.pointers.clear()}cancel(e){return this.pointers.cancel(e)}release(e){return this.pointers.release(e)}indexFor(e){if(this.index)return this.index;const t=[];for(const i of e.querySelectorAll('.devlayer > .dev[data-hp="device"][data-id]')){const e=i.querySelector(".device-shell-frame"),n=i.getBoundingClientRect(),r=e?.getBoundingClientRect();!i.dataset.id||!i.isConnected||!r||n.width<=0||n.height<=0||r.width<=0||r.height<=0||t.push({id:i.dataset.id,center:{x:n.left+n.width/2,y:n.top+n.height/2},painted:{left:r.left,top:r.top,right:r.right,bottom:r.bottom},floorRadius:Math.max(22,Math.min(r.width,r.height)/2)})}return this.index=new yc(t),this.index}at(e,t,i,n,r){const o=this.indexFor(e).resolve({x:n,y:r})?.id;return o&&t.find(e=>e.id===o&&e.space===i)||null}byId(e,t,i){return i&&e.find(e=>e.id===i&&e.space===t)||null}begin(e,t,i,n,r){const o=this.at(e,t,i,n.clientX,n.clientY)||r;return this.pointers.begin(n.pointerId,o.id),o}pointer(e,t,i,n,r){const o=n.pointerId;return(Number.isFinite(o)?this.byId(t,i,this.pointers.owner(o)):null)||this.at(e,t,i,n.clientX,n.clientY)||r}click(e,t,i,n,r){if(!(n instanceof PointerEvent))return r;const o=n,s=Number.isFinite(o.pointerId)?this.pointers.consumeClick(o.pointerId):null;return this.byId(t,i,s)||this.at(e,t,i,o.clientX,o.clientY)||r}hover(e,t){this.hoverId===t&&this.hoverElement?.isConnected||(this.hoverElement?.removeAttribute("data-hp-device-hover"),this.hoverId=t,this.hoverElement=t&&[...e.querySelectorAll('.devlayer > .dev[data-hp="device"][data-id]')].find(e=>e.dataset.id===t)||null,this.hoverElement?.setAttribute("data-hp-device-hover",""))}}function kc(e,t){if(t)return e.find(e=>e.id===t)}function xc(e,t){return{id:e,title:t,plan_url:null,view_box:[0,0,1,1],rooms:[],wall_segments:[]}}function Sc(e="file"){const t="draw"===e;return{source:e,showBorders:t,showNames:t,displayTouched:!1}}function $c(e,t){if(e.displayTouched)return{...e,source:t};const i="draw"===t;return{...e,source:t,showBorders:i,showNames:i}}function Mc(e,t,i){return{...e,[t]:i,displayTouched:!0}}function Rc(e){const t=String(e??"").trim().replace(",",".");if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(t))return null;const i=Number(t);return Number.isFinite(i)?i:null}function Cc(e,t){const i=e=>{if(""===String(e??"").trim())return{valid:!0,value:null};const t=Rc(e);return{valid:null!==t,value:t}},n=i(e),r=i(t);return n.valid&&r.valid?null!==n.value&&null!==r.value&&n.value>r.value?{valid:!0,min:r.value,max:n.value}:{valid:!0,min:n.value,max:r.value}:{valid:!1,min:n.value,max:r.value}}function Tc(e,t,i,n,r,o){const s=Cc(n,r);return dn(e,t,o&&s.valid?{settings:{...i.settings||{},temp_min:s.min,temp_max:s.max}}:i)}function Dc(e){const t=e=>"number"==typeof e&&Number.isFinite(e)?String(e):"";return[t(e?.temp_min),t(e?.temp_max)]}function Ac(e,t,i){const n=Cc(t,i);return!!n.valid&&(null===n.min?delete e.temp_min:e.temp_min=n.min,null===n.max?delete e.temp_max:e.temp_max=n.max,!0)}var Pc="M11,18H13V16H11V18M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,16.41 16.41,20 12,20M12,6A4,4 0 0,0 8,10H10A2,2 0 0,1 12,8A2,2 0 0,1 14,10C14,12 11,11.75 11,15H13C13,12.75 16,12.5 16,10A4,4 0 0,0 12,6Z";function Fc(e,t,i){return[e[0]*t+e[1]*i+e[2],e[3]*t+e[4]*i+e[5]]}function zc(e,t){let i=0;for(const[n,r]of t){const t=Fc(e,n[0],n[1]);i=Math.max(i,Math.hypot(t[0]-r[0],t[1]-r[1]))}return i}const Ic=e=>{if(null==e||""===e)return null;const t=Number(e);return Number.isFinite(t)?t:null},Oc=e=>{const t=e,i=Ic(Array.isArray(t)?t[0]:t?.x),n=Ic(Array.isArray(t)?t[1]:t?.y);return null==i||null==n?null:[i,n]};function Ec(e){if(!Array.isArray(e))return null;const t=[];for(const i of e){const e=Oc(i);if(!e)return null;t.push(e)}if(t.length>1){const e=t[0],i=t[t.length-1];e[0]===i[0]&&e[1]===i[1]&&t.pop()}if(t.length<3)return null;let i=0,n=0,r=0;for(let e=0;ee+t[0],0)/t.length,t.reduce((e,t)=>e+t[1],0)/t.length]:[n/(3*i),r/(3*i)]}function Nc(e){if(!Array.isArray(e))return null;const t=[];for(const i of e){const e=Oc(i);if(!e)return null;t.push(e)}if(t.length>1){const e=t[0],i=t[t.length-1];e[0]===i[0]&&e[1]===i[1]&&t.pop()}const i=Ec(t);if(!i)return null;const n=t.map(e=>e[0]),r=t.map(e=>e[1]);return{centroid:i,bbox:[Math.min(...n),Math.min(...r),Math.max(...n),Math.max(...r)]}}function Hc(e){let t=e;if(t&&"object"==typeof t&&!Array.isArray(t)){const e=t;t=e.path??e.points??t}if(!Array.isArray(t)||!t.length)return[];let i=(t.some(e=>(e=>Array.isArray(e)?e.length>=2&&!Array.isArray(e[0])&&("object"!=typeof e[0]||null==e[0]):!!e&&"object"==typeof e&&("x"in e||"y"in e))(e))?[t]:t.filter(Array.isArray)).map(e=>e.map(Oc).filter(e=>null!=e)).filter(e=>e.length>=2);i.length>64&&(i=i.slice(-64));const n=i.reduce((e,t)=>e+t.length,0);if(n<=4e3)return i.map(e=>e.slice());const r=4e3-2*i.length,o=i.map(e=>e.length-2),s=o.reduce((e,t)=>e+t,0),a=o.map(e=>r*e/s),l=a.map(Math.floor);let c=r-l.reduce((e,t)=>e+t,0);const h=a.map((e,t)=>({index:t,fraction:e-Math.floor(e)})).sort((e,t)=>t.fraction-e.fraction||e.index-t.index);for(let e=0;efunction(e,t){if(t>=e.length)return e.slice();if(t<=2)return[e[0],e[e.length-1]];const i=[];for(let n=0;ne.slice()),i=t[t.length-1];return i?(i.length>2?i.pop():t.pop(),t):[]}const qc=e=>Number.isFinite(e[0])&&Number.isFinite(e[1]),jc=(e,t)=>e[0]===t[0]&&e[1]===t[1];function Wc(e){if(!e)return null;const t=e.vacuum_position||e.robot_position||null,i=t&&null!=Ic(t.x)&&null!=Ic(t.y)?{x:Ic(t.x),y:Ic(t.y),a:Ic(t.a??t.angle??t.theta)}:null,n=Hc(e.path?.path??e.path?.points??e.path),r=[],o=e.rooms,s=Array.isArray(o)?o.map((e,t)=>[String(e?.id??t),e]):o&&"object"==typeof o?Object.entries(o):[];for(const[e,t]of s){if(!t||"object"!=typeof t)continue;const i=String(t.name??t.label??"").trim(),n=[[Ic(t.cx),Ic(t.cy)],[Ic(t.center?.x),Ic(t.center?.y)],[Ic(t.x),Ic(t.y)]].find(([e,t])=>null!=e&&null!=t);let o=n?.[0]??null,s=n?.[1]??null;const a=Nc(t.outline),l=Ic(t.x0),c=Ic(t.y0),h=Ic(t.x1),d=Ic(t.y1),u=(null!=l&&null!=c&&null!=h&&null!=d?[Math.min(l,h),Math.min(c,d),Math.max(l,h),Math.max(c,d)]:null)||a?.bbox||null;if(null!=o&&null!=s||!a||([o,s]=a.centroid),null!=o&&null!=s||!u||(o=(u[0]+u[2])/2,s=(u[1]+u[3])/2),i&&null!=o&&null!=s){const t={id:e,name:i,cx:o,cy:s};u&&([t.x0,t.y0,t.x1,t.y1]=u),r.push(t)}}const a=function(e){return String(e.map_name??e.current_map??e.map_index??e.selected_map??"default")}(e);return i||r.length||n.length?{pos:i,path:n,rooms:r,mapId:a}:null}function Uc(e,t,i){return![e,t,i].every(Number.isFinite)||e<0||t<=0||i<=0?Number.POSITIVE_INFINITY:e/t*i}const Gc=40;function Vc(e,t,i){if(!e||!t)return null;const n=t.attributes||{},r=e.split(".")[0]||"",o=null!=i?.platform?String(i.platform):null,s=!!Oc(n.vacuum_position??n.robot_position),a=!(!n.rooms||"object"!=typeof n.rooms),l=Hc(n.path?.path??n.path?.points??n.path).length>0,c=[n.map_name,n.current_map,n.map_index,n.selected_map].some(e=>null!=e),h="xiaomi_cloud_map_extractor"===o,d=a||l||c;let u=null;if(s?u="compatible":h?u="known_xcme_incomplete":d?u="partial":"camera"===r&&(u="camera"),!u)return null;const p=s?"camera"===r?300:200:h?100:d?50:0;return{entityId:e,name:String(n.friendly_name||e),platform:o,category:u,hasPosition:s,hasRooms:a,hasPath:l,hasMapId:c,score:p}}const Kc=e=>e.toLowerCase().replace(/[\s_\-.,]+/g,"");function Yc(e,t){const i=new Set(t.map(Kc).filter(Boolean)),n=new Set;for(const t of e){const e=Kc(t.name||"");e&&i.has(e)&&n.add(e)}return n.size}function Xc(e,t){const i=new Map(t.map(e=>[Kc(e.name),e])),n=[],r=[];for(const t of e){const e=i.get(Kc(t.name));e&&(n.push([[t.cx,t.cy],[e.cx,e.cy]]),r.push(t.name))}if(n.length<3)return null;const o=function(e){if(e.length<3)return null;let t=0,i=0,n=0,r=0,o=0,s=0,a=0,l=0,c=0,h=0,d=0,u=0;for(const[[p,_],[m,g]]of e){if(![p,_,m,g].every(Number.isFinite))return null;t+=p*p,i+=p*_,n+=p,r+=_*_,o+=_,s+=1,a+=p*m,l+=_*m,c+=m,h+=p*g,d+=_*g,u+=g}const p=[t,i,n,i,r,o,n,o,s],_=e=>{const[t,i,n,r,o,s,a,l,c]=p,h=t*(o*c-s*l)-i*(r*c-s*a)+n*(r*l-o*a);if(!Number.isFinite(h)||Math.abs(h)<1e-9)return null;const d=[(o*c-s*l)/h,(n*l-i*c)/h,(i*s-n*o)/h,(s*a-r*c)/h,(t*c-n*a)/h,(n*r-t*s)/h,(r*l-o*a)/h,(i*a-t*l)/h,(t*o-i*r)/h];return[d[0]*e[0]+d[1]*e[1]+d[2]*e[2],d[3]*e[0]+d[4]*e[1]+d[5]*e[2],d[6]*e[0]+d[7]*e[1]+d[8]*e[2]]},m=_([a,l,c]),g=_([h,d,u]);if(!m||!g)return null;const f=[m[0],m[1],m[2],g[0],g[1],g[2]];return f.every(Number.isFinite)?f:null}(n);return o?{matrix:o,matched:r,residual:zc(o,n)}:null}function Zc(e,t,i){const n=e[e.length-1];if(n&&n[0]===t[0]&&n[1]===t[1])return e;if(e.push(t),e.length<=600)return e;let r=function(e,t){if(e.length<3)return e.slice();const i=new Uint8Array(e.length);i[0]=i[e.length-1]=1;const n=[[0,e.length-1]];for(;n.length;){const[r,o]=n.pop(),[s,a]=e[r],[l,c]=e[o],h=l-s,d=c-a,u=Math.hypot(h,d)||1e-9;let p=0,_=-1;for(let t=r+1;tp&&(p=i,_=t)}_>0&&p>t&&(i[_]=1,n.push([r,_],[_,o]))}const r=[];for(let t=0;t600&&(r=r.filter((e,t)=>t%2==0||t===r.length-1)),r}function Jc(e){return"cleaning"===e||"returning"===e||"on"===e}const Qc={0:[1,0],90:[0,1],180:[-1,0],270:[0,-1]};function eh(e){const[t,i]=Qc[e.rot]||[1,0],n=e.mir?-1:1;return[e.s*t*n,-e.s*i,e.ox,e.s*i*n,e.s*t,e.oy]}function th(e){const t=e[0]*e[4]-e[1]*e[3];if(!Number.isFinite(t)||Math.abs(t)<1e-12)return null;const i=t<0,n=Math.sqrt(Math.abs(t));let r=180*Math.atan2(-e[1],e[4])/Math.PI;return r=(90*Math.round(r/90)%360+360)%360,{ox:e[2],oy:e[5],s:n,rot:r,mir:i}}function ih(e,t){const i=[],n=[];for(const t of e)null!=t.x0?(i.push(t.x0,t.x1),n.push(t.y0,t.y1)):(i.push(t.cx),n.push(t.cy));if(!i.length)return{ox:t[0]+t[2]/2,oy:t[1]+t[3]/2,s:t[2]/1e4,rot:0,mir:!0};const r=Math.min(...i),o=Math.max(...i),s=Math.min(...n),a=Math.max(...n),l=Math.max(o-r,a-s)||1,c={ox:0,oy:0,s:.6*Math.min(t[2],t[3])/l,rot:0,mir:!0},h=eh(c),[d,u]=Fc(h,(r+o)/2,(s+a)/2);return c.ox=t[0]+t[2]/2-d,c.oy=t[1]+t[3]/2-u,c}function nh(e,t,i,n){const[r,o]=Fc(eh(t),i,n),s=eh({...e,ox:0,oy:0}),[a,l]=Fc(s,i,n);return{...e,ox:r-a,oy:o-l}}function rh(e){const t=e?.trail_mode;return"never"===t||"cleaning"===t||"always"===t?t:!1===e?.trail?"never":"cleaning"}const oh=e=>"number"==typeof e&&Number.isFinite(e);function sh(e){return Array.isArray(e)&&6===e.length&&e.every(oh)?[e[0],e[1],e[2],e[3],e[4],e[5]]:null}function ah(e,t,i){return"legacy:"+e+" "+t+" "+i}function lh(e,t,i,n){const r=t?.map_routes;if(Array.isArray(r))return r.filter(e=>e&&"string"==typeof e.id&&e.id).map(e=>({id:e.id,source:String(e.source??""),map_id:String(e.map_id??""),space:String(e.space??""),calibration:sh(e.calibration)}));const o="string"==typeof t?.source&&t.source?t.source:n||"";if(!o)return[];const s=t?.calibration;if(!s||"object"!=typeof s)return[];const a=[];for(const t of Object.keys(s)){const n=sh(s[t]);n&&a.push({id:ah(e,o,t),source:o,map_id:t,space:i,calibration:n})}return a}const ch=(e,t)=>e instanceof Map?e.get(t):e?.[t];function hh(e){const t=[];let i=!1,n="",r="";for(const o of e.routes){const s=ch(e.observed,o.source);void 0!==s&&(i=!0,n||(n=o.source,r=s),s===o.map_id&&t.push(o))}if(t.length>1)return{kind:"ambiguous",routeIds:t.map(e=>e.id).sort()};if(1===t.length){const i=t[0];if(e.spaceIds&&!e.spaceIds.has(i.space))return{kind:"missing_space",route:i};const n=sh(i.calibration);return n?{kind:"ready",route:{...i,calibration:n}}:{kind:"needs_calibration",route:i}}if(i)return{kind:"unmapped",source:n,mapId:r};const o=e.observed instanceof Map?[...e.observed.entries()]:Object.entries(e.observed||{});if(o.length){const e=o.slice().sort((e,t)=>e[0].localeCompare(t[0]))[0];return{kind:"unmapped",source:e[0],mapId:e[1]}}return{kind:"none"}}function dh(e,t,i){const n=new Set;for(const t of e)t.source&&n.add(t.source);for(const e of t)e&&n.add(e);const r={};for(const e of[...n].sort()){const t=i(e);void 0!==t&&(r[e]=t)}return r}function uh(e,t,i){if(!e)return null;const n="string"==typeof e.route_id?e.route_id:"";if(n)return t.find(e=>e.id===n)||null;const r=function(e,t,i){if(!e||"string"!=typeof e.map_id)return{kind:"orphan_run"};const n=e.map_id,r="string"==typeof i?i:"";let o=t.filter(e=>e.map_id===n);return r&&(o=o.filter(e=>e.source===r)),1===o.length?{kind:"adopted",route:o[0]}:0===o.length?{kind:"orphan_run"}:{kind:"ambiguous_run",routeIds:o.map(e=>e.id).sort()}}(e,t,i);return"adopted"===r.kind?r.route:null}function ph(e){const t="ready"===e.resolution.kind?e.resolution.route:null,i=t&&t.space===e.renderSpace?sh(t.calibration):null,n=uh(e.serverCurrent,e.routes,e.rootSource),r=!!t&&!!n&&n.id===t.id,o=uh(e.serverPrevious,e.routes,e.rootSource);return{live:i,currentRunMatches:r,previous:!!o&&o.space===e.renderSpace&&(e.explicitRoutes||!!t&&o.id===t.id)?sh(o.calibration):null}}const _h={availability:"available",status:"alarm",activity:"none"},mh=new Set(["motion","vibration","sound"]),gh=new Set(["occupancy","presence"]),fh=new Set(["door","window","garage_door","opening"]),vh=new Set(["running","power"]),yh=new Set(["smoke","gas","carbon_monoxide","moisture","safety","tamper","problem"]);const bh=new Set(["running","working","washing","rinsing","spinning","drying","heating","cooling","cleaning","cooking","playing","recording","pumping","irrigating","humidifying","dehumidifying","fan","preheating","defrosting"]),wh=new Set([...bh,"start","started","run","active","in_progress","wash","rinse","spin","dry"]),kh=new Set(["off","idle","paused","standby","docked","finished","complete","completed","stopped","ready","sleeping","stop","end","done","inactive"]),xh=new Set(["heat","cool","heat_cool","auto","dry","fan_only"]),Sh=e=>""===e||"unknown"===e||"unavailable"===e||"__missing__"===e,$h=e=>String(e??"").trim().toLowerCase(),Mh=e=>$h(e).replace(/[\s-]+/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,""),Rh=new Map([["run_state",0],["job_state",0],["operation_state",0],["activity_state",0],["machine_state",1],["running_state",1],["status",2],["device_status",2],["machine_status",2]]),Ch=new Set(["wifi","connection","signal","battery"]);function Th(e,t){const i=e?.entities?.[t]||{};if("config"===i.entity_category)return null;const n=String(t||"").split(".").slice(1).join("."),r=[i.translation_key,i.original_name,i.name],o=[...r,n];r.some(e=>$h(e))||o.push(e?.states?.[t]?.attributes?.friendly_name);const s=o.map(Mh).filter(Boolean);if(s.some(e=>e.split("_").some(e=>Ch.has(e))))return null;let a=null;for(const e of s)for(const[t,i]of Rh)(e===t||e.endsWith(`_${t}`))&&(a=null==a?i:Math.min(a,i));return a}const Dh=(e,t)=>null!=Th(e,t);function Ah(e,t){if(!t.startsWith("switch."))return!1;const i=e?.entities?.[t]||{},n=e?.states?.[t],r=t.slice(7).toLowerCase();if(/(?:^|_)(?:main_)?power$/.test(r))return!0;if([i.translation_key,i.original_name,i.name].map($h).some(e=>["power","main power","power switch","питание"].includes(e)))return!0;const o=$h(n?.attributes?.friendly_name);return/(?:^|[\s._-])(?:main[\s._-]+)?power$/.test(o)||/(?:^|[\s._-])питание$/.test(o)}function Ph(e){for(const t of["hvac_action","action","current_operation","run_state","job_state","operation","activity"]){const i=$h(e?.[t]);if(bh.has(i)||kh.has(i))return i}return""}function Fh(e,t){const i=e?.states?.[t],n=i?$h(i.state):"__missing__",r=String(t||"").split(".")[0],o=$h(i?.attributes?.device_class),s={eid:t,state:n,availability:Sh(n)?"unavailable":"available",status:"neutral",activity:"none",edge:"none"};if("unavailable"===s.availability)return s;if(function(e,t,i){return"alarm_control_panel"===e?"triggered"===i:"on"===i&&Vn(e,t)}(r,o,n))return{...s,status:"alarm"};if("binary_sensor"===r)return mh.has(o)?{...s,edge:"rising"}:gh.has(o)?{...s,activity:"on"===n?"presence":"none"}:fh.has(o)?{...s,status:"on"===n?"open":"neutral",edge:"rising"}:"moving"===o?{...s,activity:"on"===n?"transition":"none"}:vh.has(o)&&"on"===n?{...s,status:"working",activity:"running"}:s;if("cover"===r)return{...s,activity:"opening"===n||"closing"===n?"transition":"none",edge:"terminal_transition"};if("lock"===r)return{...s,status:"unlocked"===n||"open"===n?"open":"neutral",activity:"locking"===n||"unlocking"===n?"transition":"none",edge:"terminal_transition"};if("valve"===r)return{...s,status:["open","opening","closing"].includes(n)?"open":"neutral",activity:"opening"===n||"closing"===n?"transition":"none",edge:"terminal_transition"};if("climate"===r){const e=Ph(i.attributes),t=Array.isArray(i.attributes?.hvac_modes)?i.attributes.hvac_modes.map($h):[],r=!kh.has(n)&&(xh.has(n)||bh.has(n)||t.includes(n));return(e?bh.has(e):r)?{...s,status:"working",activity:"running"}:s}if(["light","switch","fan","humidifier"].includes(r))return"on"===n?{...s,status:"working",activity:"running"}:s;if("media_player"===r)return"off"===n?{...s,availability:"unavailable"}:s;if("vacuum"===r)return"cleaning"===n?{...s,status:"working",activity:"running"}:"returning"===n?{...s,status:"working",activity:"transition"}:s;if("script"===r)return"on"===n?{...s,status:"working",activity:"running"}:s;if("automation"===r)return s;if("button"===r||"event"===r)return{...s,edge:"change"};const a=Ph(i.attributes);return bh.has(a)||bh.has(n)&&!kh.has(n)?{...s,status:"working",activity:"running"}:s}function zh(e,t,i){const n=i.filter(t=>t.startsWith("switch.")&&!e?.entities?.[t]?.entity_category),r=t.find(t=>Ah(e,t));if(!(n.length>1&&!!r))return t.map(t=>Fh(e,t));const o=t.find(t=>t!==r&&Dh(e,t)),s=Fh(e,r);return"unavailable"===s.availability||"off"===s.state?t.map(t=>({eid:t,state:e?.states?.[t]?$h(e.states[t].state):"__missing__",availability:"unavailable",status:"neutral",activity:"none",edge:"none"})):t.map(t=>{if(t===o)return function(e,t){const i=e?.states?.[t],n=i?$h(i.state):"__missing__",r={eid:t,state:n,availability:Sh(n)?"unavailable":"available",status:"neutral",activity:"none",edge:"none"};if("unavailable"===r.availability)return r;const o=Ph(i?.attributes);return bh.has(o)||wh.has(n)&&!kh.has(n)?{...r,status:"working",activity:"running"}:r}(e,t);return{...t===r?s:Fh(e,t),status:"neutral",activity:"none",edge:"none"}})}function Ih(e){if(!e.length)return{availability:"available",status:"neutral",activity:"none"};const t=e.filter(e=>"available"===e.availability);if(!t.length)return{availability:"unavailable",status:"neutral",activity:"none"};if(t.some(e=>"alarm"===e.status))return _h;const i=t.some(e=>"working"===e.status)?"working":t.some(e=>"open"===e.status)?"open":"neutral",n=t.some(e=>"transition"===e.activity)?"transition":t.some(e=>"presence"===e.activity)?"presence":t.some(e=>"running"===e.activity)?"running":"none";return{availability:"available",status:i,activity:n}}function Oh(e,t){if(!(e=>!!e&&!Sh(e))(e)||"unavailable"===t.availability||e===t.state)return null;if("rising"===t.edge)return"off"===e&&"on"===t.state?"event":null;if("change"===t.edge)return"event";if("terminal_transition"===t.edge){const i=new Set([e,t.state]);if(i.has("closed")&&i.has("open")||i.has("locked")&&i.has("unlocked"))return"transition"}return null}const Eh=(e,t=0)=>{const i=Number(e);return Number.isInteger(i)&&i>=0?i:t},Nh=(e,t)=>{const i={rev:0,configRev:Eh(t),off:new Set};if(null==e)return{snapshot:i,valid:!1};const n=e.off;return!Number.isInteger(e.rev)||Number(e.rev)<0||!Number.isInteger(e.config_rev)||Number(e.config_rev)<0||!Array.isArray(n)||n.some(e=>"string"!=typeof e||!e)?{snapshot:i,valid:!1}:{snapshot:{rev:Number(e.rev),configRev:Number(e.config_rev),off:new Set(n)},valid:!0}};function Hh(e,t=0){return Nh(e,t).snapshot}function Lh(e,t,i,n){const r=Nh(t,i);return n&&r.valid&&r.snapshot.configRev===i?e.configRev===i&&r.snapshot.rev{try{const[i,n]=await Promise.all([e.callWS({type:"config/device_registry/list"}),e.callWS({type:"config/entity_registry/list"})]),r=Zh(i,"id"),o=Zh(n,"entity_id");if(!r||!o)throw new Error("invalid_registry_response");t.devices=r,t.entities=o,t.authoritative=!0,t.access="full",t.lastSuccess=Date.now(),t.error=void 0}catch(e){t.authoritative=!1,t.access="limited",t.error=function(e){if(e&&"object"==typeof e){const t=e;return String(t.message||t.code||t.error||"registry_unavailable")}return String(e||"registry_unavailable")}(e)}finally{t.revision++,t.loading=void 0,function(e){for(const t of[...e.listeners])try{t()}catch{}}(t)}})()),t.loading}function Qh(e,t){void 0===t.reloadTimer&&(t.reloadTimer=globalThis.setTimeout(()=>{t.reloadTimer=void 0,Jh(e,t)},80))}async function ed(e,t){if(t.subscribing||t.unsubDevice&&t.unsubEntity)return t.subscribing;const i=e?.connection?.subscribeEvents;return"function"==typeof i?(t.subscribing=(async()=>{try{t.unsubDevice||(t.unsubDevice=await i.call(e.connection,()=>Qh(e,t),"device_registry_updated")),t.unsubEntity||(t.unsubEntity=await i.call(e.connection,()=>Qh(e,t),"entity_registry_updated"))}catch{}finally{0===t.refs&&(t.unsubDevice?.(),t.unsubEntity?.(),t.unsubDevice=void 0,t.unsubEntity=void 0),t.subscribing=void 0}})(),t.subscribing):void 0}function td(e,t){const i=Xh(e);if(!i)return()=>{};const n=0===i.refs;i.refs++,i.listeners.add(t),("pending"===i.access||n)&&Jh(e,i),ed(e,i);let r=!1;return()=>{r||(r=!0,i.listeners.delete(t),i.refs=Math.max(0,i.refs-1),i.refs>0||(i.unsubDevice?.(),i.unsubEntity?.(),i.unsubDevice=void 0,i.unsubEntity=void 0,void 0!==i.reloadTimer&&globalThis.clearTimeout(i.reloadTimer),i.reloadTimer=void 0))}}function id(e){const t=Xh(e);t&&(Qh(e,t),ed(e,t))}function nd(e){const t=Xh(e);if(!t)return{revision:0,authoritative:!1,access:"limited",devices:e?.devices||{},entities:e?.entities||{},lastSuccess:0,error:"registry_unavailable"};let i=e?.devices||{},n=e?.entities||{};if(t.authoritative){const r=t.liveDevices!==i||t.liveEntities!==n,o=void 0!==t.liveDevices||void 0!==t.liveEntities;if(r&&(t.liveDevices=i,t.liveEntities=n,t.projectedRevision=void 0,o&&Qh(e,t)),t.projectedRevision!==t.revision||!t.projectedDevices||!t.projectedEntities){const e={...t.devices},r={...t.entities};for(const[t,n]of Object.entries(i))Object.prototype.hasOwnProperty.call(e,t)||(e[t]=n);for(const[e,t]of Object.entries(n))Object.prototype.hasOwnProperty.call(r,e)||(r[e]=t);t.projectedDevices=e,t.projectedEntities=r,t.projectedRevision=t.revision}i=t.projectedDevices,n=t.projectedEntities}return{revision:t.revision,authoritative:t.authoritative,access:t.access,devices:i,entities:n,lastSuccess:t.lastSuccess,error:t.error}}function rd(e){if(!e||"object"!=typeof e&&"function"!=typeof e)return 0;let t=Gh.get(e);return t||(t=Vh++,Gh.set(e,t)),t}function od(e,t=nd(e)){return[t.revision,t.access,rd(t.devices),rd(t.entities)].join(":")}function sd(e){return!!e&&null==e.disabled_by}function ad(e,t=nd(e)){const i={},n={},r={};for(const[e,n]of Object.entries(t.devices||{}))sd(n)&&(i[e]=n);for(const[e,i]of Object.entries(t.entities||{})){if(!sd(i))continue;const r=i.device_id?t.devices?.[i.device_id]:null;t.authoritative&&i.device_id&&!r||(r&&!sd(r)||(n[e]=i))}for(const[i,n]of Object.entries(e?.states||{})){const e=t.entities?.[i];if(e&&!sd(e))continue;const o=e?.device_id?t.devices?.[e.device_id]:null;t.authoritative&&e?.device_id&&!o||(o&&!sd(o)||(r[i]=n))}return{...e,devices:i,entities:n,states:r}}function ld(e,t=nd(e)){return{...e,devices:t.devices||{},entities:t.entities||{}}}function cd(e,t){const i=[];for(const[n,r]of Object.entries(e||{}))r?.device_id===t&&i.push(n);return i}function hd(){if(Yh)return Yh;if("undefined"==typeof localStorage)return{};try{const e=JSON.parse(localStorage.getItem(Kh)||"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};const t=Date.now(),i={};for(const[n,r]of Object.entries(e))!r||"active"!==r.kind&&"ha_disabled"!==r.kind||!Number.isFinite(r.ts)||t-r.ts>7776e6||(i[n]=r);return Yh=i,Yh}catch{return{}}}function dd(e,t,i=nd(e)){if(!t||"virtual"===t)return{kind:"active",enabledEntityIds:[],allEntityIds:[]};const n=t.indexOf(":");if(n<1)return{kind:"unverified",reason:"registry_unavailable",enabledEntityIds:[],allEntityIds:[]};const r=t.slice(0,n),o=t.slice(n+1);if("device"!==r&&"entity"!==r||!o)return{kind:"unverified",reason:"registry_unavailable",enabledEntityIds:[],allEntityIds:[]};const s=i.devices||{},a=i.entities||{};if(i.authoritative){if("device"===r){const e=s[o];if(!e)return{kind:"orphaned",reason:"device_missing",enabledEntityIds:[],allEntityIds:[]};const t=cd(a,o);if(!sd(e))return{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:t};const i=t.filter(e=>sd(a[e]));return t.length&&!i.length?{kind:"ha_disabled",reason:"all_entities",enabledEntityIds:[],allEntityIds:t}:{kind:"active",enabledEntityIds:i,allEntityIds:t}}const t=a[o];return t&&!sd(t)?{kind:"ha_disabled",reason:"entity",enabledEntityIds:[],allEntityIds:[o]}:t?.device_id&&!s[t.device_id]?{kind:"orphaned",reason:"device_missing",enabledEntityIds:[],allEntityIds:[o]}:t?.device_id&&!sd(s[t.device_id])?{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:[o]}:t||e?.states?.[o]?{kind:"active",enabledEntityIds:[o],allEntityIds:[o]}:{kind:"orphaned",reason:"entity_missing",enabledEntityIds:[],allEntityIds:[]}}const l=function(e){return hd()[e]||null}(t);if("device"===r){const t=s[o],i=cd(a,o);if(null!=t?.disabled_by)return{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:i};const n=i.filter(e=>{const t=a[e];return null==t?.disabled_by&&(!t.device_id||null==s[t.device_id]?.disabled_by)});if(i.length&&!n.length&&i.every(e=>null!=a[e]?.disabled_by))return{kind:"ha_disabled",reason:"all_entities",enabledEntityIds:[],allEntityIds:i};if("ha_disabled"===l?.kind)return{kind:"ha_disabled",reason:l.reason||"device",enabledEntityIds:[],allEntityIds:i};if(t||n.some(t=>!!e?.states?.[t]))return{kind:"active",enabledEntityIds:n,allEntityIds:i}}else{const t=a[o];if(null!=t?.disabled_by)return{kind:"ha_disabled",reason:"entity",enabledEntityIds:[],allEntityIds:[o]};if(t?.device_id&&null!=s[t.device_id]?.disabled_by)return{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:[o]};if("ha_disabled"===l?.kind)return{kind:"ha_disabled",reason:l.reason||"entity",enabledEntityIds:[],allEntityIds:[o]};if(t||e?.states?.[o])return{kind:"active",enabledEntityIds:[o],allEntityIds:[o]}}return{kind:"unverified",reason:"registry_unavailable",enabledEntityIds:[],allEntityIds:[]}}function ud(e){const t=nd(e);return{access:t.access,authoritative:t.authoritative,revision:t.revision,lastSuccess:t.lastSuccess,error:t.error}}function pd(e){const t={};for(const[i,n]of Object.entries(e.entities)){if(!n?.device_id||!sd(n))continue;const r=e.devices?.[n.device_id];r&&!sd(r)||(t[n.device_id]=t[n.device_id]||[]).push(i)}return t}function _d(e,t){const i=new Map;for(const n of e){if(!0===n?.removed)continue;const e=n?.binding||"";if(!e.startsWith("entity:"))continue;const r=e.slice(7);if(!r)continue;const o=t?.entities?.[r]?.device_id;if(!o)continue;const s=i.get(o)||new Set;s.add(r),i.set(o,s)}return{byDevice:i}}function md(e,t,i,n){const r=n.byDevice.get(t);return r?.size?{partial:!0,entityIds:i.filter(t=>!r.has(t)&&!e?.entities?.[t]?.hidden)}:{partial:!1,entityIds:[...i]}}function gd(e,t,i){if(t.identifiers?.[0]?.[0])return t.identifiers[0][0];for(const t of i){const i=e.entities[t]?.platform;if(i)return i}return""}function fd(e,t){if(/_device_temperature$/.test(t))return!1;if(e.entities?.[t]?.entity_category)return!1;const i=e.states[t];if(!i)return/_temperature$/.test(t);const n=i.attributes||{};return"temperature"===n.device_class||/°C|°F/.test(n.unit_of_measurement||"")||/_temperature$/.test(t)}const vd=["vacuum","lawn_mower","climate","media_player","light","cover","lock","valve","alarm_control_panel","water_heater","fan","humidifier","siren","camera","remote"],yd=e=>[...e.filter(e=>!e.reg?.hidden),...e.filter(e=>!!e.reg?.hidden)];function bd(e,t){const i=t.map(t=>({eid:t,reg:e?.entities?.[t]})).filter(e=>!!e.reg);if(!i.length)return[];const n=i.filter(e=>!e.reg.entity_category),r=n.length?n:i;for(const e of vd){const t=r.filter(t=>t.eid.startsWith(e+"."));if(t.length)return yd(t).map(e=>e.eid)}const o=r.filter(t=>function(e,t){if(!t.startsWith("binary_sensor."))return!1;const i=$h(e?.states?.[t]?.attributes?.device_class||e?.entities?.[t]?.device_class||e?.entities?.[t]?.original_device_class);return mh.has(i)||gh.has(i)||fh.has(i)||vh.has(i)||"moving"===i||yh.has(i)}(e,t.eid));if(o.length)return yd(o).map(e=>e.eid);const s=r.filter(e=>e.eid.startsWith("switch."));if(s.length){const t=yd(s),n=t.find(t=>Ah(e,t.eid));if(s.length>1&&n){const t=i.filter(t=>t.eid!==n.eid&&"config"!==t.reg?.entity_category&&null!=Th(e,t.eid)),r=t.filter(e=>!e.reg?.entity_category),o=r.length?r:t;for(const t of[0,1,2]){const i=yd(o.filter(i=>Th(e,i.eid)===t));if(i.length)return[i[0].eid,n.eid]}}return[(n||t[0]).eid]}const a=[];for(const e of je)a.push(...yd(r.filter(t=>t.eid.startsWith(e+"."))));return a.push(...yd(r.filter(e=>!je.includes(e.eid.split(".")[0])))),a.map(e=>e.eid)}function wd(e,t,i){const n=t.map(t=>({eid:t,reg:e.entities[t],st:e.states[t]})).filter(e=>e.reg),r=[n.filter(e=>!e.reg.hidden&&!e.reg.entity_category),n.filter(e=>!e.reg.entity_category),n.filter(e=>!e.reg.hidden),n];if("mdi:thermometer"===i||"mdi:air-filter"===i)for(const t of r){const i=t.find(t=>fd(e,t.eid));if(i)return i.eid}const o=bd(e,t);return o.find(Dn)||o[0]}function kd(e,t,i=[]){return[...new Set(xd(e,t,i))].filter(e=>Dn(e))}function xd(e,t,i=[]){const n=e?.startsWith("entity:")?new Set([e.slice(7)]):new Set(i);return(t||[]).filter(e=>"string"==typeof e&&!n.has(e))}function Sd(e,t){if("string"==typeof t)return e.area===t;const i=e.marker?.room_id;return i?!!t.id&&i===t.id:!!t.area&&e.area===t.area}function $d(e){const t=e.marker?.binding?.startsWith("entity:")?e.marker.binding.slice(7):null,i=e.entities.filter(Dn),n=e.primary&&Dn(e.primary)?e.primary:null;return[...new Set([t,n,...i].filter(e=>!!e&&Dn(e)))]}function Md(e){const t=$d(e),i=e.marker?.light_entity;return i&&t.includes(i)?i:t[0]||null}function Rd(e,t){if(!1===t.marker?.is_light)return[];if(!0===t.marker?.is_light){return[{eid:Md(t),via:"forced"}]}const i=t.primary||bd(e,t.entities)[0];return i&&!i.startsWith("light.")?[]:t.entities.filter(t=>t.startsWith("light.")&&!!e.states?.[t]).map(e=>({eid:e,via:"light"}))}const Cd=new WeakMap,Td=new WeakMap;function Dd(e){return e.map(e=>[e.id||"",!0===e.hidden?1:0,e.primary||"",[...e.entities].join(","),void 0===e.controls?"":[...e.controls].join(","),e.marker?.id||"",e.marker?.binding||"",e.marker?.is_light,e.marker?.tap_action||"",!0===e.marker?.removed?1:0,e.marker?.light_entity||"",null==e.marker?.controls?"":[...e.marker.controls].join(",")].join("")).join("")}function Ad(e){const t=Dd(e),i=Cd.get(e);if(i?.fingerprint===t)return i;const n=e.filter(e=>!e.hidden),r=new Map,o=new Map;for(const t of e){o.set(t,xd(t.marker?.binding,t.marker?.controls??t.controls,t.entities));const e=t.hidden||!0!==t.marker?.is_light?null:t.marker?.id||t.id;e&&r.set(String(e),t)}const s=new Map;for(const t of e){const e=o.get(t)||[],i=new Set(void 0===t.controls?e.filter(Dn):t.controls.filter(Dn)),n=Md(t),a=i.size?[...i]:n?[n]:[];for(const i of e){if(!i.startsWith("marker:"))continue;const e=i.slice(7);if(!e||e===String(t.marker?.id||t.id||""))continue;if(!r.has(e))continue;const n=s.get(e)||{markerId:e,controllers:[],driverEids:[]};n.controllers.push({device:t,driverEids:[...a]}),n.driverEids=[...new Set([...n.driverEids,...a])],s.set(e,n)}}const a={fingerprint:t,visible:n,markerById:r,persistedByDevice:o,incomingByMarker:s};return Cd.set(e,a),a}function Pd(e){return Ad(e).incomingByMarker}function Fd(e,t){const i=kd(t.marker?.binding,t.controls??t.marker?.controls,t.entities),n=xd(t.marker?.binding,t.marker?.controls??t.controls,t.entities);return(null!=t.marker?.is_light||!i.length&&!n.some(e=>e.startsWith("marker:")))&&Rd(e,t).length>0}function zd(e,t){return Rd(e,t).some(e=>!!e.eid)}function Id(e,t,i,n){const r="always"===e||"auto"===e&&t,o=r&&!i;return{sourceExists:r,fromSourceEnabled:r&&i,manualEnabled:r,radiusEnabled:r,passive:o,effectiveMode:o&&"auto"===n?"fixed":n}}function Od(e,t){const i=kd(t.marker?.binding,t.controls??t.marker?.controls,t.entities).map(e=>({eid:e,via:"controls"})),n=Fd(e,t)?Rd(e,t):[];for(const e of n)e.eid&&i.some(t=>t.eid===e.eid)||i.push(e);return i}function Ed(e,t,i,n){if(null!=i)return Ed(e,t,null,n).filter(e=>Sd(e.device,i));const r=Dd(t),o=function(e,t){const i=new Set;for(const e of t){for(const t of e.entities)i.add(t);for(const t of e.controls||e.marker?.controls||[])"string"!=typeof t||t.startsWith("marker:")||i.add(t)}return[...i].sort().map(t=>`${t}:${e?.states?.[t]?.state??""}`).join("|")}(e,t),s=Bh(n),a=Td.get(t);if(a?.graphFingerprint===r&&a.stateFingerprint===o&&a.virtualLightFingerprint===s&&a.registry===e?.entities)return a.sources;const{visible:l,markerById:c,persistedByDevice:h,incomingByMarker:d}=Ad(t),u=null==i?l:l.filter(e=>Sd(e,i)),p=new Map,_=new Map;for(const t of u){const i=Od(e,t).filter(e=>"controls"!==e.via);for(const n of i){const i=!0===t.marker?.is_light?String(t.marker?.id||t.id||""):"",r=i?`marker:${i}`:`entity:${n.eid}`,o=n.eid?[n.eid]:[],s={key:r,eid:n.eid||"",stateEids:o,serviceEids:o,device:t,via:n.via,castsGlow:!0,passive:!n.eid,on:!n.eid||"on"===e.states?.[n.eid]?.state};p.set(t,[...p.get(t)||[],s]),n.eid&&_.set(n.eid,s)}}const m=new Map;for(const e of t){const t=h.get(e)||[],i=new Set(void 0===e.controls?t.filter(Dn):e.controls);m.set(e,i)}for(const t of p.values())for(const i of t){if(!i.passive)continue;const t=i.key.slice(7),r=d.get(t);i.on=!r||r.driverEids.some(t=>"on"===e.states?.[t]?.state),!r&&qh(i.device.marker)&&(i.on=jh(i.device.marker,n))}const g=new Map,f=e=>{const t=g.get(e.key);(!t||e.castsGlow&&!t.castsGlow)&&g.set(e.key,e)};for(const t of l){const n=h.get(t)||[],r=null==i||Sd(t,i);for(const i of n){if(i.startsWith("marker:")){const e=c.get(i.slice(7)),t=e?p.get(e):null;if(t)for(const e of t)f(e);continue}if(!Dn(i)||!m.get(t)?.has(i))continue;const n=_.get(i);n?f(n):r&&f({key:`entity:${i}`,eid:i,stateEids:[i],serviceEids:[i],device:t,via:"controls",castsGlow:!1,passive:!1,on:"on"===e.states?.[i]?.state})}for(const e of p.get(t)||[])f(e)}const v=[...g.values()];return Td.set(t,{graphFingerprint:r,stateFingerprint:o,virtualLightFingerprint:s,registry:e?.entities,sources:v}),v}function Nd(e){const t=e.filter(e=>e.castsGlow);return t.find(e=>e.on)||t[0]||null}function Hd(e){return e.length?e.some(e=>e.on)?"on":"off":"none"}function Ld(e,t){const i=[];for(const n of t){const t=e.states[n];if(!t)continue;const r=(t.attributes?.unit_of_measurement||"").toLowerCase();if(/_(linkquality|lqi)$/.test(n)||"lqi"===r){const e=parseFloat(t.state);isNaN(e)||i.push(e);continue}const o=t.attributes?.linkquality??t.attributes?.lqi;if(null!=o){const e=parseFloat(o);isNaN(e)||i.push(e)}}return Ii(i)}function Bd(e,t){for(const i of t){if(!fd(e,i))continue;const t=e.states[i];if(!t)continue;const n=parseFloat(t.state);if(!isNaN(n))return Math.round(10*n)/10}return null}function qd(e,t){for(const i of t){if(!i.startsWith("climate."))continue;const t=e.states[i];if(!t||"unavailable"===t.state||"unknown"===t.state)continue;const n=parseFloat(t.attributes?.current_temperature);if(Number.isFinite(n))return Math.round(10*n)/10}return null}function jd(e,t){if(e.entities?.[t]?.entity_category)return!1;const i=e.states[t];if(!i)return/_humidity$/.test(t);const n=i.attributes||{};return"humidity"===n.device_class||"%"===n.unit_of_measurement&&/_humidity$/.test(t)||/_humidity$/.test(t)}function Wd(e,t){for(const i of t){if(!jd(e,i))continue;const t=e.states[i];if(!t)continue;const n=parseFloat(t.state);if(!isNaN(n))return Math.round(n)}return null}function Ud(e,t){if(!t)return[];const i=[];for(const[t,n]of Object.entries(e.entities)){if(!t.startsWith("light.")||n.hidden||!sd(n))continue;let r=null;if("group"===n.platform)r=n.area_id||null;else{if(!n.device_id)continue;{const t=e.devices[n.device_id];if(!sd(t))continue;if("Group"!==t?.model)continue;r=t.area_id||n.area_id||null}}if(!r)continue;const o=e.states[t];i.push({eid:t,name:n.name||o?.attributes?.friendly_name||t,area:r})}return i}function Gd(e,t,i,n,r){const o=qe(t,i,r);if(o!==Be)return o;const s=[];for(const t of n){const i=e.states[t]?.attributes?.device_class;i&&s.push(i)}return function(e){for(const t of e){const e=Le[t];if(e)return e}return null}(s)??Be}function Vd(e,t){return e.map(e=>{if(!Array.isArray(e.controls))return e;const i=e.controls.filter(e=>!("string"==typeof e&&e.startsWith("marker:")&&t.has(e.slice(7))));return i.length===e.controls.length?e:{...e,controls:i.length?i:null}})}function Kd(e,t,i){if(!t||!i||t===i)return[...e];const n=`marker:${t}`,r=`marker:${i}`;return e.map(e=>{const t=Array.isArray(e.controls)?e.controls.map(e=>e===n?r:e):e.controls,i="derived_marker_state"===e.value_badge?.source?.kind&&e.value_badge.source.ref===n?{...e.value_badge,source:{...e.value_badge.source,ref:r}}:e.value_badge,o="derived_marker_state"===e.value_source?.kind&&e.value_source.ref===n?{...e.value_source,ref:r}:e.value_source;return t===e.controls&&i===e.value_badge&&o===e.value_source?e:{...e,controls:t,...void 0!==i?{value_badge:i}:{},...void 0!==o?{value_source:o}:{}}})}function Yd(e,t,i){if(!t||t===i)return!0;const n=new Map;for(const t of e)n.set(t.id,(t.controls||[]).filter(e=>"string"==typeof e&&e.startsWith("marker:")).map(e=>e.slice(7)));const r=new Set,o=[i];for(;o.length;){const e=o.pop();if(e===t)return!0;r.has(e)||(r.add(e),o.push(...n.get(e)||[]))}return!1}function Xd(e,t,i,n){const r=new Set([t]),o=e.filter(e=>{const o=e.id===t||!n&&e.binding===i;return o&&r.add(e.id),!o});return{markers:n?o:[...o,{id:t,binding:i,removed:!0,hidden:!0}],cleanupIds:r}}function Zd(e){const t=new Set,i=new Set,n=new Set;for(const r of e||[]){const e=String(r.binding||"").indexOf(":");if(e<1)continue;const o=r.binding.slice(0,e),s=r.binding.slice(e+1);s&&(!0===r?.removed?"device"===o?t.add(s):"entity"===o&&i.add(s):"entity"===o&&n.add(s))}return{devices:t,entities:i,liveEntities:n}}function Jd(e,t,i){if(i.liveEntities.has(t))return!1;if(i.entities.has(t))return!0;const n=e?.entities?.[t]?.device_id;return!!n&&i.devices.has(n)}function Qd(e,t,i,n,r){const o=kd(t.binding,t.controls,e.entities).filter(e=>!Jd(i,e,n)).filter(e=>"active"===dd(i,"entity:"+e,r).kind);e.marker=t,e.controls=o,e.userHidden=!0===t.hidden,e.hidden=e.userHidden||"ha_disabled"===e.bindingStatus?.kind,t.name&&(e.name=t.name),t.icon&&(e.icon=t.icon),null!=t.model&&(e.model=t.model),e.link=t.link??null,e.description=t.description??null,e.pdfs=t.pdfs||[],e.tapAction=t.tap_action??null}function eu(e){const t=e.hass,i=e.registry||nd(t),n=ad(t,i),r=ld(t,i),{areaToSpace:o,markers:s,settings:a,excluded:l,iconRules:c}=e,h=!1!==a.group_lights,d=Zd(s),u=Ud(n,h).filter(e=>!Jd(n,e.eid,d)),p=new Set(u.map(e=>e.area)),_=pd(n),m=_d(s,r),g=new Set(s.map(e=>e.binding)),f=[];for(const e of Object.values(n.devices)){const r=e.area_id;if(!r||!o[r])continue;if("service"===e.entry_type)continue;if(g.has("device:"+e.id))continue;if("active"!==dd(t,"device:"+e.id,i).kind)continue;const s=md(n,e.id,_[e.id]||[],m);if(s.partial&&!s.entityIds.length)continue;const a=s.entityIds,d=gd(n,e,a);let u=l.has(d)||"Group"===e.model||/scene/i.test(e.model||"")||/bridge/i.test((e.model||"")+(e.name||""))||"myheat"===d&&!!e.via_device_id;if(!u&&h&&p.has(r)){const t=(e.name_by_user||e.name||"").trim();"mdi:lightbulb"===Gd(n,t,e.model,a,c)&&(u=!0)}u&&f.push("device:"+e.id)}return f}function tu(e,t,i,n){if("string"==typeof e.room_id&&e.room_id.length>0&&null===e.area)return{area:"",space:e.space||n};const r=e.area||t||"";return{area:r,space:r&&i[r]||e.space||n}}function iu(e){const t=e.hass,i=e.registry||nd(t),n=ad(t,i),r=ld(t,i),{areaToSpace:o,markers:s,settings:a,excluded:l,showAll:c,firstSpaceId:h,loc:d,iconRules:u}=e,p=!1!==a.group_lights,_=Zd(s),m=Ud(n,p).filter(e=>!Jd(n,e.eid,_)),g=new Set(m.map(e=>e.area)),f=pd(n),v=function(e){const t={};for(const[i,n]of Object.entries(e.entities||{}))n?.device_id&&(t[n.device_id]=t[n.device_id]||[]).push(i);return t}(r),y=_d(s,r),b=new Set;for(const e of s){const[t,i]=e.binding.split(":");"device"!==t&&"entity"!==t||!i||b.add(e.binding)}const w=(e,t)=>s.find(i=>i.binding===e+":"+t),k={},x=[];for(const e of Object.values(n.devices)){const r=e.area_id;if(!r||!o[r])continue;if("service"===e.entry_type)continue;if(b.has("device:"+e.id))continue;const s=dd(t,"device:"+e.id,i);if("active"!==s.kind)continue;const h=w("device",e.id);if(h&&h.hidden&&!a.filter_seeded)continue;const _=md(n,e.id,f[e.id]||[],y);if(_.partial&&!_.entityIds.length)continue;const m=_.entityIds,v=_.partial?{kind:"active",enabledEntityIds:m,allEntityIds:m}:s,S=gd(n,e,m),$=!a.filter_seeded;if($&&!c){if(l.has(S))continue;if("Group"===e.model)continue;if(/scene/i.test(e.model||""))continue;if(/bridge/i.test((e.model||"")+(e.name||"")))continue;if("myheat"===S&&e.via_device_id)continue}const M=(e.name_by_user||e.name||d("device.unnamed")).trim(),R=M+"|"+r;let C=Gd(n,M,e.model,m,u);if(m.some(e=>e.startsWith("lock."))&&(C="mdi:lock"),$&&!c&&p&&"mdi:lightbulb"===C&&g.has(r))continue;k[R]=(k[R]||0)+1;const T=k[R]>1?M+" "+k[R]:M,D={id:e.id,name:T,model:e.model||"",area:r,space:o[r],icon:C,entities:m,allEntities:v.allEntityIds,bindingStatus:v,bindingKind:"device",bindingRef:e.id,pdfs:[]};D.primary=wd(n,m,C),"mdi:thermometer"!==C&&"mdi:air-filter"!==C||(D.temp=Bd(n,m)),D.primary&&jd(n,D.primary)&&(D.hum=Wd(n,m)),x.push(D)}for(const e of m)o[e.area]&&(b.has("entity:"+e.eid)||x.push({id:"lg_"+e.eid,name:e.name,model:d("device.light_group"),area:e.area,space:o[e.area],icon:"mdi:lightbulb-group",entities:[e.eid],allEntities:[e.eid],bindingStatus:{kind:"active",enabledEntityIds:[e.eid],allEntityIds:[e.eid]},primary:e.eid,bindingKind:"entity",bindingRef:e.eid,pdfs:[]}));for(const e of s){if(e.removed)continue;const[s,l]=e.binding.split(":"),c="device"===s||"entity"===s?dd(t,e.binding,i):null;if(!e.hidden||a.filter_seeded||"ha_disabled"===c?.kind)if("device"===s){const t=c;if("unverified"===t.kind)continue;const s=r.devices[l],{area:a,space:p}=tu(e,s?.area_id,o,h),m="active"===t.kind?t.enabledEntityIds:[];let g=s?Gd(n,s.name_by_user||s.name||"",s.model,m,u):"mdi:help-circle";m.some(e=>e.startsWith("lock."))&&(g="mdi:lock");const f={id:e.id,name:s?.name_by_user||s?.name||d("device.fallback"),model:s?.model||"",area:a,space:p,icon:g,entities:m,allEntities:t.allEntityIds.length?t.allEntityIds:s&&v[s.id]||[],bindingStatus:t,bindingKind:"device",bindingRef:l};f.primary=wd(n,m,g),"mdi:thermometer"!==g&&"mdi:air-filter"!==g||(f.temp=Bd(n,m)),f.primary&&jd(n,f.primary)&&(f.hum=Wd(n,m)),Qd(f,e,r,_,i),x.push(f)}else if("entity"===s){if(Jd(r,l,_))continue;const t=c;if("unverified"===t.kind)continue;const s=r.entities[l],a=s?.area_id||s?.device_id&&r.devices[s.device_id]?.area_id||"",{area:d,space:p}=tu(e,a,o,h),m=n.states[l],g=s?.name||m?.attributes?.friendly_name||l;let f=Gd(n,g,"",[l],u);l.startsWith("lock.")&&(f="mdi:lock");const v={id:e.id,name:g,model:"",area:d,space:p,icon:f,entities:"active"===t.kind?[l]:[],allEntities:[l],bindingStatus:t,primary:"active"===t.kind?l:void 0,bindingKind:"entity",bindingRef:l};"mdi:thermometer"!==f&&"mdi:air-filter"!==f||!v.entities.length||(v.temp=Bd(n,v.entities)),v.entities.length&&jd(n,l)&&(v.hum=Wd(n,v.entities)),Qd(v,e,r,_,i),x.push(v)}else{const t=e.area||"",n=e.space||t&&o[t]||h,s={id:e.id,name:e.name||d("device.virtual"),model:e.model||"",area:t,space:n,icon:e.icon||"mdi:map-marker",entities:[],allEntities:[],bindingStatus:{kind:"active",enabledEntityIds:[],allEntityIds:[]},bindingKind:"virtual",virtual:!0};Qd(s,e,r,_,i),x.push(s)}}return x}function nu(e){const{marker:t,siblingMarkers:i=[],...n}=e;return iu({...n,markers:[...i.filter(e=>e.id!==t.id),t]}).find(e=>e.id===t.id)||null}function ru(e,t,i,n){if(!t)return null;if(function(e,t,i){if(!t)return!1;const n=t.indexOf(":");if(n<1)return!1;const r=t.slice(0,n),o=t.slice(n+1),s=Zd(i);return"device"===r?s.devices.has(o):"entity"===r&&Jd(e,o,s)}(e,t,n))return null;const r=t.indexOf(":");if(r<0)return null;const o=t.slice(0,r),s=t.slice(r+1);if(!s)return null;if("entity"===o){const t=parseFloat(e.states[s]?.state);return Number.isFinite(t)?"temp"===i?Math.round(10*t)/10:Math.round(t):null}if("device"===o){const t=Object.entries(e.entities).filter(([,e])=>e.device_id===s).map(([e])=>e);return"temp"===i?Bd(e,t):Wd(e,t)}return null}const ou=new RegExp(["water","voda","coolant","flow_?temp","return_?temp","target","setpoint","chip","cpu","processor","board","core_temp","device_temp","batter","akkum","freezer","fridge","oven","kettle","boiler"].join("|"),"i");function su(e,t){return t.area?t.area:e&&t.id?`@room/${encodeURIComponent(e)}/${encodeURIComponent(t.id)}`:null}function au(e){return null==e.area&&e.space&&e.room_id?su(e.space,{id:e.room_id,area:null}):e.area||null}function lu(e){const t=e?.exclude_integrations;return t?new Set(t):Ie}function cu(e,t,i,n=Ie){const r=new Map;if(!e?.entities)return r;const o=Zd(i),s=new Set,a=new Map,l=new Map;for(const e of i||[]){if(e?.removed)continue;const t=(e.binding||"").indexOf(":");if(t<=0)continue;const i=e.binding.slice(0,t),n=e.binding.slice(t+1);if(!n)continue;!0===e.use_climate_temp&&s.add(n);const r=au(e);r&&("entity"!==i||a.has(n)?"device"!==i||l.has(n)||l.set(n,r):a.set(n,r))}const c=new Map;for(const[t,i]of Object.entries(e.entities)){if(i.device_id&&o.devices.has(i.device_id)&&!o.liveEntities.has(t)||!i.device_id&&o.entities.has(t)&&!o.liveEntities.has(t))continue;const r=i.device_id?e.devices?.[i.device_id]:null;if(!sd(i)||r&&!sd(r))continue;const h=a.get(t)||(i.device_id?l.get(i.device_id):null)||i.area_id||r?.area_id||null;if(!h)continue;if(i.entity_category)continue;if(!(s.size>0&&t.startsWith("climate.")&&(s.has(t)||i.device_id&&s.has(i.device_id)))){if(n.has(i.platform))continue;if(ou.test(t))continue}let d=c.get(h);d||(d=new Map,c.set(h,d));const u=i.device_id||t;let p=d.get(u);if(!p){const n=e.states?.[t];p={name:(r?r.name_by_user||r.name:i.name||n?.attributes?.friendly_name||t)||t,model:r?.model,ents:[]},d.set(u,p)}p.ents.push(t)}for(const[i,n]of c){const o=[],a=[];for(const[i,r]of n){const n=Gd(e,r.name,r.model,r.ents,t),l="mdi:thermometer"===n||"mdi:air-filter"===n;if(l){const t=Bd(e,r.ents);null!=t&&o.push(t)}if(s.size>0&&(s.has(i)||r.ents.some(e=>s.has(e)))){const t=qd(e,r.ents);null!=t&&o.push(t)}if(l||"mdi:water-percent"===n){const t=Wd(e,r.ents);null!=t&&a.push(t)}}(o.length||a.length)&&r.set(i,{temp:o.length?Math.round(o.reduce((e,t)=>e+t,0)/o.length*10)/10:null,hum:a.length?Math.round(a.reduce((e,t)=>e+t,0)/a.length):null})}return r}function hu(e,t,i){const n=[];for(const r of t){if(r.area!==i||r.virtual)continue;const t=Ld(e,r.entities);null!=t&&n.push(t)}return Ii(n)}const du={offStates:["off"],unknownUsesToggle:!0},uu={light:du,switch:du,fan:du,humidifier:du,input_boolean:du,automation:du,remote:du,group:du,climate:{...du,featureMasks:{turn_on:256,turn_off:128,toggle:384}},media_player:{...du,featureMasks:{turn_on:128,turn_off:256,toggle:384}},siren:{...du,featureMasks:{turn_on:1,turn_off:2,toggle:3}},vacuum:{...du,featureMasks:{turn_on:1,turn_off:2,toggle:3}},water_heater:{...du,featureMasks:{turn_on:8,turn_off:8,toggle:8}},camera:{...du,featureMasks:{turn_on:1,turn_off:1,toggle:1}}};function pu(e){return e.slice(0,e.indexOf("."))}function _u(e,t,i){if(!e?.services||"object"!=typeof e.services)return!1;const n=e.services?.[t];return!!n&&Object.prototype.hasOwnProperty.call(n,i)}function mu(e,t,i){return _u(e,t,i)?{domain:t,service:i}:_u(e,"homeassistant",i)?{domain:"homeassistant",service:i}:null}function gu(e,t){return e?.entities?.[t]||null}function fu(e,t,i){const n=e?.states?.[i],r=gu(t,i);return n?.attributes?.friendly_name||r?.name||r?.original_name||i}function vu(e,t){const i=gu(e,t);if(null!=i?.disabled_by)return!0;const n=i?.device_id?e?.devices?.[i.device_id]:null;return null!=n?.disabled_by}function yu(e,t){const i=e?.attributes?.supported_features;if(null==i||""===i)return!1;const n=Number(i);return Number.isFinite(n)&&(n&t)===t}function bu(e,t,i){const n=pu(i);if("lock"===n||"alarm_control_panel"===n)return!0;if("cover"!==n)return!1;const r=e?.states?.[i],o=gu(t,i),s=String(r?.attributes?.device_class||o?.device_class||o?.original_device_class||"");return Wi.has(s)}function wu(e,t,i,n,r){return{ref:i,entityId:n,name:n?fu(e,t,n):null,reason:r}}function ku(e,t,i,n,r,o=null){return{target:null,skipped:wu(e,t,i,n,r),semantics:o,nextEffect:null,command:null}}function xu(e,t,i,n,r=i){const o=pu(i);if("cover"!==o&&"valve"!==o)return function(e,t,i,n,r=i){const o=pu(i),s=e?.states?.[i];if(vu(t,i))return ku(e,t,r,i,"ha-disabled","power");if(bu(e,t,i))return ku(e,t,r,i,"secure");if(!s)return ku(e,t,r,i,"missing","power");if("unavailable"===s.state)return ku(e,t,r,i,"unavailable","power");const a=uu[o];if(!a)return ku(e,t,r,i,"unsupported");let l,c;if("unknown"===s.state||""===s.state){if(!a.unknownUsesToggle)return ku(e,t,r,i,"unsupported","power");l="toggle",c="toggle"}else a.offStates.includes(String(s.state))?(l="turn-on",c="turn_on"):(l="turn-off",c="turn_off");const h=a.featureMasks?.[c];if(h&&!yu(s,h))return ku(e,t,r,i,"unsupported","power");const d=mu(e,o,c);return d?{target:{entityId:i,name:fu(e,t,i),state:String(s.state||""),via:n},skipped:null,semantics:"power",nextEffect:l,command:{...d,data:{entity_id:i}}}:ku(e,t,r,i,"unsupported","power")}(e,t,i,n,r);if(vu(t,i))return ku(e,t,r,i,"ha-disabled",o);if(bu(e,t,i))return ku(e,t,r,i,"secure",o);const s=e?.states?.[i];if(!s)return ku(e,t,r,i,"missing",o);if("unavailable"===s.state)return ku(e,t,r,i,"unavailable",o);const a=function(e,t,i){const n=String(i?.state||""),r="closed"===n?{service:`open_${t}`,effect:"open",feature:1}:"open"===n?{service:`close_${t}`,effect:"close",feature:2}:"opening"===n||"closing"===n?{service:`stop_${t}`,effect:"stop",feature:8}:null;return r&&yu(i,r.feature)&&_u(e,t,r.service)?r:yu(i,3)&&_u(e,t,"toggle")?{service:"toggle",effect:"toggle"}:null}(e,o,s);if(!a)return ku(e,t,r,i,"unsupported",o);return{target:{entityId:i,name:fu(e,t,i),state:String(s.state||""),via:n},skipped:null,semantics:o,nextEffect:a.effect,command:{domain:o,service:a.service,data:{entity_id:i}}}}function Su(e){return"entity"===e.bindingKind?e.bindingRef&&Dn(e.bindingRef)?[e.bindingRef]:[]:"virtual"===e.bindingKind?[]:$d(e)}function $u(e){const t=e.marker?.toggle_entity;return t&&Su(e).includes(t)?t:null}function Mu(e,t,i){const n=function(e,t){if("entity"===e.bindingKind&&e.bindingRef){const t=e.marker?.light_entity?Md(e):null;return[...new Set([t,e.bindingRef].filter(e=>!!e))]}const i=e.entities.length?e.entities:e.allEntities||[],n=e.marker?.light_entity||e.primary&&Dn(e.primary)?Md(e):null;return[...new Set([n,...bd(t,i)].filter(e=>!!e))]}(i,t);if(!n.length)return null;const r="entity"===i.bindingKind?"binding":"device-role";if("binding"===r)return xu(e,t,n[0],r);let o=null,s=null;for(const i of n){const n=xu(e,t,i,r);if(n.command)return n;const a=n.skipped?.reason;if("missing"===a||"unavailable"===a||"secure"===a)return n;"ha-disabled"!==a?o||=n:s||=n}return o||s}function Ru(e){const t=e.skipped?.reason;return"missing"===t?"unavailable":t||"unsupported"}function Cu(e,t){return{origin:e,kind:"none",semantics:null,targets:[],skippedTargets:[],noneReason:t,nextEffect:null,command:null}}function Tu(e,t){return"cover"===e||"toggle"===e?"toggle":"more-info"===e||"run"===e||"info"===e||"none"===e?e:(null==e||""===e)&&"light"===t?"toggle":"info"}function Du(e,t){return{origin:e,kind:"single",semantics:t.semantics,targets:t.target?[t.target]:[],skippedTargets:t.skipped?[t.skipped]:[],noneReason:t.command?null:Ru(t),nextEffect:t.nextEffect,command:t.command}}function Au(e,t,i,n=[]){const r=new Map,o=[],s=new Set,a=e=>{const t=`${e.ref}\n${e.entityId||""}\n${e.reason}`;s.has(t)||(s.add(t),o.push(e))};for(const e of n)a(e);for(const n of i){const i=xu(e,t,n.entityId,n.via,n.ref);i.target?r.set(n.entityId,r.get(n.entityId)||i.target):i.skipped&&a(i.skipped)}const l=[...r.values()];if(!l.length)return{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:l,skippedTargets:o,noneReason:o.length&&o.every(e=>"secure"===e.reason)?"secure":"configured-targets-missing",nextEffect:null,command:null};const c=l.some(e=>"on"===e.state)?"turn_off":"turn_on",h=mu(e,"homeassistant",c);return h?{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:l,skippedTargets:o,noneReason:null,nextEffect:"turn_on"===c?"turn-on":"turn-off",command:{...h,data:{entity_id:l.map(e=>e.entityId)}}}:{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:[],skippedTargets:[...o,...l.map(i=>wu(e,t,i.entityId,i.entityId,"unsupported"))],noneReason:"unsupported",nextEffect:null,command:null}}function Pu(e){return String(e.marker?.id||e.id||"")}function Fu(e){const{hass:t,device:i}=e,n=e.registryHass||t,r=function(e){return"toggle"===e.tapAction?"explicit-toggle":"cover"===e.tapAction?"legacy-cover":!e.tapAction&&e.primary?.startsWith("light.")?"default-light":null}(i);if(!r)return null;const o=i.marker;if("explicit-toggle"===r&&qh(o)){const t=String(o?.id||i.id||""),n=Pd(e.devices).get(t);if(n)return function(e,t){const i=e.registryHass||e.hass;return Au(e.hass,i,t.driverEids.map(e=>({entityId:e,via:"control-marker-driver",ref:`marker:${t.markerId}`})))}(e,n);const s=jh(o,e.virtualLights);return{origin:r,kind:"single",semantics:"power",targets:[{entityId:"",name:i.name,state:s?"on":"off",via:"virtual-light"}],skippedTargets:[],noneReason:null,nextEffect:s?"turn-off":"turn-on",command:null,operation:{kind:"virtual-light",markerId:o.id}}}if("explicit-toggle"===r){if(xd(i.marker?.binding,i.marker?.controls??i.controls,i.entities).length)return function(e,t=null){const{hass:i,device:n,devices:r}=e,o=e.registryHass||i,s=xd(n.marker?.binding,n.marker?.controls??n.controls,n.entities),a=e.lightSources||Ed(i,r,null,e.virtualLights),l=new Map;for(const e of a){if(!e.key.startsWith("marker:"))continue;const t=l.get(e.key)||[];t.push(e),l.set(e.key,t)}const c=Pd(r),h=new Map;for(const e of r){const t=String(e.marker?.id||e.id||"");t&&h.set(t,e)}const d=[],u=[];t&&d.push({entityId:t,via:"entity"===n.bindingKind?"binding":"device-role",ref:t});for(const e of s){if(!e.startsWith("marker:")){Dn(e)?d.push({entityId:e,via:"control-entity",ref:e}):u.push(wu(i,o,e,e.includes(".")?e:null,"unsupported"));continue}const t=l.get(e)||[];if(!t.length){const t=h.get(e.slice(7));if("ha_disabled"===t?.bindingStatus?.kind){const n=t.bindingStatus.allEntityIds[0]||null;u.push({ref:e,entityId:n,name:t.name||(n?fu(i,o,n):null),reason:"ha-disabled"})}else u.push(wu(i,o,e,null,"missing"));continue}const r=[...new Set(t.flatMap(e=>e.serviceEids))];if(r.length){for(const t of r)d.push({entityId:t,via:"control-entity",ref:e});continue}const s=t.some(e=>e.passive),a=e.slice(7),p=Pu(n),_=c.get(a)?.controllers.find(e=>Pu(e.device)===p);if(s&&_?.driverEids.length)for(const t of _.driverEids)d.push({entityId:t,via:"control-marker-driver",ref:e});else u.push(wu(i,o,e,null,s?"missing":"unsupported"))}return Au(i,o,d,u)}(e,$u(i))}if("legacy-cover"===r){const e=i.entities.find(e=>e.startsWith("cover."))||i.allEntities?.find(e=>e.startsWith("cover."));return e?Du(r,xu(t,n,e,"device-role")):Cu(r,"no-actionable-entity")}const s=$u(i),a=s?xu(t,n,s,"entity"===i.bindingKind?"binding":"device-role"):Mu(t,n,i);return a?Du(r,a):Cu(r,i.virtual||"virtual"===i.bindingKind?"no-actionable-entity":"no-binding")}function zu(e){if(!e)return[];const t=Array.isArray(e.data.entity_id)?e.data.entity_id:[e.data.entity_id];return[...new Set(t)].sort()}function Iu(e){return e?e.operation?e.operation:e.command?{kind:"ha-service",command:e.command}:null:null}const Ou=new Set(["missing","ha-disabled","unavailable"]);function Eu(e,t){const i=Iu(e),n=Iu(t);return!(!i||!n||i.kind!==n.kind)&&("virtual-light"===i.kind&&"virtual-light"===n.kind?i.markerId===n.markerId:"ha-service"===i.kind&&"ha-service"===n.kind&&function(e,t){const i=zu(e),n=zu(t);return i.length===n.length&&i.every((e,t)=>e===n[t])}(i.command,n.command))}function Nu(e,t){const i=e.targets[0]||e.skippedTargets[0],n=[];return"group"===e.kind?e.targets.length&&n.push(t.group(e.targets)):i&&n.push(t.single(i)),e.nextEffect&&e.targets.length&&n.push("group"===e.kind?t.groupCurrentNext(e.targets,e.nextEffect):t.currentNext(e.targets[0],e.nextEffect)),e.skippedTargets.length&&n.push(t.skipped(e.skippedTargets)),!e.command&&e.noneReason&&n.push(t.none(e.noneReason)),n}function Hu(e,t){return e.catch(()=>{}).then(t)}const Lu=e=>{const t=e?.config;return t&&Array.isArray(t.spaces)?t:null},Bu=(e,t)=>"number"==typeof e&&Number.isFinite(e)?e:t;class qu{constructor(e){this.onBodyReplaced=e,this.config=null,this.configRev=0,this.configFingerprint="",this.layout={},this.layoutRev=0,this.layoutFingerprint=""}setConfig(e){const t=this.config;e!==t&&(this.config=e,this.onBodyReplaced?.("_serverCfg",t))}setLayout(e){const t=this.layout;e!==t&&(this.layout=e,this.onBodyReplaced?.("_layout",t))}currentConfigFingerprint(){return this.configFingerprint||cc(this.config)}currentLayoutFingerprint(){return this.layoutFingerprint||cc(this.layout)}adoptResponses(e,t,i,n){const r=Lu(e),o=cc(r),s=o!==this.currentConfigFingerprint();s&&(i(),this.setConfig(r),this.configFingerprint=o),this.configRev=e?.rev??this.configRev;let a=!1;if(void 0!==t){const e=t?.layout??{},i=cc(e);a=i!==this.currentLayoutFingerprint(),a&&(n(),this.setLayout(e),this.layoutFingerprint=i),this.layoutRev=t?.rev??this.layoutRev}return{configChanged:s,layoutChanged:a}}adoptMergedLayout(e,t,i){const n=cc(e),r=n!==cc(this.layout);return r&&(i?.(),this.setLayout(e)),this.layoutFingerprint=n,this.layoutRev=t?.rev??this.layoutRev,r}stageConfigCandidate(e){const t=cc(e);t!==cc(this.config)&&this.setConfig(e),this.configFingerprint=t}acceptConfigWrite(e,t){this.configFingerprint=cc(e),this.configRev=Bu(t?.rev,this.configRev+1)}acceptPairWrite(e,t,i){this.setConfig(e),this.configFingerprint=cc(e),this.setLayout(t),this.layoutFingerprint=cc(t),this.configRev=Bu(i?.config_rev,this.configRev+1),this.layoutRev=Bu(i?.layout_rev,this.layoutRev+1)}noteLayoutRevision(e){"number"==typeof e&&e>this.layoutRev&&(this.layoutRev=e)}stageLocalConfig(e){this.setConfig(e)}stageLocalLayout(e){this.setLayout(e)}seedIdentity(e){Object.assign(this,e)}refreshConfigFingerprint(){this.configFingerprint=cc(this.config)}refreshLayoutFingerprint(){this.layoutFingerprint=cc(this.layout)}beginOptimistic(e,t){return function(e,t,i,n,r){return{previous:JSON.parse(JSON.stringify(e)),previousFingerprint:i,revision:n,attempted:t,attemptedFingerprint:r(t)}}(e,t,this.configFingerprint,this.configRev,cc)}rollbackOptimistic(e){const t=this.config;return!(!t||this.configRev!==e.revision||cc(t)!==e.attemptedFingerprint)&&(this.setConfig(e.previous),this.configFingerprint=e.previousFingerprint,!0)}restoreCached(e){const t=e?.config;return!(!t||!Array.isArray(t.spaces))&&(this.setConfig(t),this.configRev=e?.rev||0,this.configFingerprint=e?.config_fingerprint||cc(t),this.setLayout(e?.layout||{}),this.layoutRev=e?.layout_rev||0,this.layoutFingerprint=e?.layout_fingerprint||cc(this.layout),!0)}snapshot(e){return this.config?(this.refreshConfigFingerprint(),this.refreshLayoutFingerprint(),{config:this.config,rev:this.configRev,config_fingerprint:this.configFingerprint,layout:this.layout,layout_rev:this.layoutRev,layout_fingerprint:this.layoutFingerprint,virtual_lights:e}):null}}async function ju(e,t){const i=t.isCurrent??(()=>!0);if(!i())return{status:"superseded"};const{cfgResp:n,layResp:r}=t,o=e._adoption,s=Lu(n),a=null!=n&&cc(s)!==o.currentConfigFingerprint()||null!=r&&cc(r.layout??{})!==o.currentLayoutFingerprint();if(a){const t=await e._signer.prepareImage(e.hass,e._candidateBackdrop(s));if(!i())return{status:"superseded"};if(!t)return e._continuity.note("asset-failed"),e._scheduleLoadRetry(!0),{status:"asset-wait"}}if(!i())return{status:"superseded"};a&&e._continuity.hasCompleteFrame&&"steady"===e._continuity.state&&e._beginContinuityCandidate(t.reason,!0),t.beforeAdopt?.();const l=e._space;return function(e,t,i){const n=e._adoption,r=!!n.config,{configChanged:o,layoutChanged:s}=n.adoptResponses(t??{},i,()=>{e._geometryHistory.clear(),e._devicePositionHistory.clear(),e._cancelDeviceDrag(),e._pendingPhysicalWrites.clear(),e._clearRoomFocus(!0),e._cancelCameraTransition(!1),r&&e._clearGeometryGesture()},()=>{e._cancelCameraTransition(!1),e._devicePositionHistory.clear(),e._cancelDeviceDrag()});if(o&&e._seedDecorStyle(n.config),t&&("virtual_lights"in t||"config"in t)){const i=Lh(e._virtualLights,t.virtual_lights,n.configRev,"virtual_lights"in t);Bh(i)!==Bh(e._virtualLights)&&(e._virtualLights=i,e._capturedSnapshotVirtual="")}e._canOptimizeUndo=!(!t?.can_optimize_undo&&!i?.can_optimize_undo),e._adoptConfigCapabilities(t),e._undoKind=t?.undo_kind||i?.undo_kind||null,"boolean"==typeof t?.can_write&&(e._serverCanWrite=t.can_write),o&&e._continuity.note("config-candidate",{configRev:n.configRev}),s&&e._continuity.note("layout-candidate",{layoutRev:n.layoutRev})}(e,n,r),"reload"===t.profile&&(e._syncDecorAssets(s).catch(()=>{}),e._adoptInitialSpace(e._model,!0),e._resumePendingNavMode(),e._cacheSnapshot()),t.afterAdopt?.(),{status:"adopted",spaceChanged:e._space!==l}}const Wu=(e,t)=>e.connection===t.connection&&e.userId===t.userId&&e.route===t.route,Uu=e=>"number"==typeof e&&Number.isFinite(e)?e:null;class Gu{constructor(){this.sequence=0,this.currentSequence=0,this.lifecycle=0,this.observedHighWater=null,this.context=null}observeContext(e){this.context?Wu(this.context,e)||(this.context={...e},this.invalidateLifecycle()):this.context={...e}}invalidateLifecycle(){this.lifecycle+=1,this.currentSequence=++this.sequence,this.observedHighWater=null}observeRevision(e,t,i){this.observeContext(i);const n=Uu(e);if(null===n)return null;const r=Uu(t)??Number.NEGATIVE_INFINITY;return n<=Math.max(r,this.observedHighWater??Number.NEGATIVE_INFINITY)?null:(this.observedHighWater=n,Object.freeze({sequence:this.currentSequence,lifecycle:this.lifecycle,context:{...i},observedRevision:n}))}isReservationCurrent(e,t,i){this.observeContext(t);const n=Uu(i)??Number.NEGATIVE_INFINITY;return e.sequence===this.currentSequence&&e.lifecycle===this.lifecycle&&Wu(e.context,t)&&e.observedRevision===this.observedHighWater&&e.observedRevision>n}begin(e){this.observeContext(e.context),e.force&&this.invalidateLifecycle();const t=++this.sequence;return this.currentSequence=t,Object.freeze({sequence:t,lifecycle:this.lifecycle,force:e.force,context:{...e.context},baselineRevision:e.baselineRevision,baselineFingerprint:e.baselineFingerprint})}isCurrent(e){this.observeContext(e.context);const t=e.claim;return e.connected&&(t.force||!e.writePending)&&t.sequence===this.currentSequence&&t.lifecycle===this.lifecycle&&Wu(t.context,e.context)&&t.baselineRevision===e.baselineRevision&&t.baselineFingerprint===e.baselineFingerprint}}const Vu=e=>{const t=e.hass,i=t?.user?.id;return{connection:t?.connection??null,userId:"string"==typeof i?i:null,route:location.pathname}};async function Ku(e,t=!1,i){let n=null;const r=e._configReloadAuthority;if(!t){if(void 0!==i&&(n=r.observeRevision(i,e._cfgRev,Vu(e)),!n))return;if(e._saveConfigDebounced.pending()&&e._saveConfigDebounced.flush(),e._cfgWriting)return clearTimeout(e._reloadRetry),void(e._reloadRetry=window.setTimeout(()=>{n&&!r.isReservationCurrent(n,Vu(e),e._cfgRev)||Ku(e,!1)},400))}const o=r.begin({force:t,context:Vu(e),baselineRevision:e._cfgRev,baselineFingerprint:e._adoption.currentConfigFingerprint()}),s=()=>((e,t)=>e._configReloadAuthority.isCurrent({claim:t,context:Vu(e),connected:e.isConnected,baselineRevision:e._cfgRev,baselineFingerprint:e._adoption.currentConfigFingerprint(),writePending:e._saveConfigDebounced.pending()||e._cfgWriting}))(e,o);let a=!1;try{const t=await e._getAuthoritativeConfig();if(!s())return;const i=await e._adoptAuthoritative({cfgResp:t,reason:"config-reload",profile:"reload",isCurrent:s,afterAdopt:()=>{e._regSignature="",e._maybeRebuildDevices()}});if("superseded"===i.status)return;if(a=!0,"adopted"!==i.status)return;i.spaceChanged&&e._restoreZoom(),e.requestUpdate()}catch(t){if(!s())return;a=!0,e._showToast(e._t("toast.cfg_reload_failed",{err:e._errText(t)}))}finally{(a||s())&&(e._continuityDataReady=!0,e.requestUpdate())}}const Yu=e=>!!e&&e.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]);function Xu(e,t=5,i=5){return Fo(e.cm,t,i)/2}function Zu(e,t,i=1,n=5,r=5,o=0){const s=e.host;if(!s||"partition"!==s.kind||"string"!=typeof s.id||!s.id)return{resolved:null,reason:"invalid-host"};const a=t.find(e=>e.id===s.id);if(!a)return{resolved:null,reason:"missing-partition"};if(!Yu(a.a)||!Yu(a.b)||!Number.isFinite(s.t)||s.t<0||s.t>1)return{resolved:null,reason:"invalid-position"};const l=a.b[0]-a.a[0],c=a.b[1]-a.a[1],h=Math.hypot(l,c),d=Number(e.length)*i;if(!(h>1e-9&&d>0&&Number.isFinite(d)))return{resolved:null,reason:"invalid-length"};const u=s.t*h;if(u-d/2h-o+1e-9)return{resolved:null,reason:"does-not-fit"};const p=l/h,_=c/h;let m=180*Math.atan2(c,l)/Math.PI;return m>=90?m-=180:m<-90&&(m+=180),{reason:null,resolved:{opening:e,host:s,partition:a,center:[a.a[0]+l*s.t,a.a[1]+c*s.t],angle:m,length:d,depth:Fo(a.cm,n,r),t:s.t,axis:{a:[a.a[0],a.a[1]],b:[a.b[0],a.b[1]],ux:p,uy:_,length:h}}}}function Ju(e,t,i=1,n=5,r=5){return Zu(e,t,i,n,r,0)}function Qu(e,t,i=1,n=5,r=5){const o=e.host,s="partition"===o?.kind?t.find(e=>e.id===o.id):void 0;if(!s)return Ju(e,t,i,n,r);const a=Zu(e,t,i,n,r,Xu(s,n,r));return"does-not-fit"===a.reason?{resolved:null,reason:"does-not-fit-jamb"}:a}function ep(e,t){return!e||(e.length!==t.length||e.host?.kind!==t.host?.kind||e.host?.id!==t.host?.id||e.host?.t!==t.host?.t)}function tp(e){const{center:t,length:i,axis:n,host:r}=e,o=i/2;return{hostId:r.id,a:[t[0]-n.ux*o,t[1]-n.uy*o],b:[t[0]+n.ux*o,t[1]+n.uy*o],depth:e.depth}}function ip(e,t=!1){const i=t?1:-1,n=e.depth/2;return{ox:-e.axis.uy*i*n,oy:e.axis.ux*i*n,cm:e.partition.cm,side:i}}function np(e,t,i){return e.flatMap(e=>!Yu(e.a)||!Yu(e.b)||Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])<=1e-9?[]:[{roomId:"",a:[e.a[0],e.a[1]],b:[e.b[0],e.b[1]],key:`partition:${e.id}`,kind:"outer",cm:e.cm,open:!1,half:Fo(e.cm,t,i)/2,partitionHost:{kind:"partition",id:e.id}}])}function rp(e,t,i){const{center:n,length:r,axis:o}=e,s=r/2,a=t.flatMap(e=>{if(!e.kind||e.open)return[];const t=e.b[0]-e.a[0],r=e.b[1]-e.a[1],a=Math.hypot(t,r);if(!(a>i))return[];const l=t/a,c=r/a;if(Math.abs(o.ux*c-o.uy*l)>1e-6)return[];if(Math.abs((n[0]-e.a[0])*c-(n[1]-e.a[1])*l)>i)return[];const h=e=>(e[0]-n[0])*o.ux+(e[1]-n[1])*o.uy,d=h(e.a),u=h(e.b),p=Math.max(-s,Math.min(d,u)),_=Math.min(s,Math.max(d,u));return _>=p-i?[[p,_]]:[]});if(!a.length)return!1;a.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);let l=-s;for(const[e,t]of a){if(e>l+i)return!1;if(l=Math.max(l,t),l>=s-i)return!0}return!1}function op(e,t,i=1e-9){const n=e.length/(2*e.axis.length),r=e.t-n,o=e.t+n;return t.some(t=>{if(t.host.id!==e.host.id||t.opening.id===e.opening.id)return!1;const n=t.length/(2*t.axis.length);return Math.max(r,t.t-n)ha-icon{align-self:start;color:var(--hp-accent);}.version-recovery-copy{min-width:0;display:flex;flex-direction:column;gap:var(--sp-2);font-size:var(--fs-m);line-height:1.35;}.version-recovery-copy>span{color:var(--hp-muted);}.version-recovery-versions{display:flex;flex-wrap:wrap;gap:var(--sp-2) var(--sp-5);}.version-recovery-versions span,.version-recovery-versions b{overflow-wrap:anywhere;}.version-recovery-reload{min-height:44px;white-space:normal;}@keyframes hp-version-recovery-in{from{opacity:0;}to{opacity:1;}}@keyframes hp-version-recovery-out{from{opacity:1;}to{opacity:0;}}@media (max-width:520px){.version-recovery-card{grid-template-columns:auto minmax(0,1fr);}.version-recovery-reload{grid-column:1 / -1;width:100%;}}@keyframes fixedfloor-spin{to{transform:rotate(360deg);}}.spacer{flex:1;}.bootveil{position:absolute;inset:0;z-index:40;display:flex;align-items:center;justify-content:center;background:var(--hp-bg,#16212e);opacity:1;transition:opacity 0.15s ease;pointer-events:none;}.bootveil.off{opacity:0;}.bootveil .boothouse{position:static;width:56px;height:56px;fill:var(--hp-accent);opacity:0.85;animation:hp-boot-pulse 1.3s ease-in-out infinite;}@keyframes hp-boot-pulse{0%,100%{opacity:0.3;transform:scale(0.94);}50%{opacity:0.9;transform:scale(1);}}@media (prefers-reduced-motion:reduce){.bootveil .boothouse{animation:none;opacity:0.7;}.version-recovery.phase-visible,.version-recovery.phase-leaving{animation:none;}}@keyframes hp-pulse-short{0%{transform:scale(1);opacity:0.55;}70%{opacity:0.22;}100%{transform:scale(var(--ripple-scale,1.5));opacity:0;}}@keyframes hp-pulse-short-b{0%{transform:scale(1);opacity:0.55;}70%{opacity:0.22;}100%{transform:scale(var(--ripple-scale,1.5));opacity:0;}}@keyframes hp-pulse-continuous{0%{transform:scale(1);opacity:0.55;}65%{opacity:0.18;}100%{transform:scale(var(--ripple-scale,1.5));opacity:0;}}@keyframes hp-pulse-alarm{0%{transform:scale(1);opacity:0.72;}100%{transform:scale(1.5);opacity:0;}}@keyframes hp-slide-left{0%{transform:translateX(4%);opacity:0.72;}100%{transform:translateX(0);opacity:1;}}@keyframes hp-slide-right{0%{transform:translateX(-4%);opacity:0.72;}100%{transform:translateX(0);opacity:1;}}@keyframes hp-sunfade-in{from{opacity:0;}to{opacity:1;}}@keyframes hp-sunfade-out{from{opacity:1;}to{opacity:0;}}.sr-only{position:absolute !important;width:1px !important;height:1px !important;padding:0 !important;margin:-1px !important;overflow:hidden !important;clip:rect(0,0,0,0) !important;white-space:nowrap !important;border:0 !important;}.toast{position:fixed;pointer-events:none;left:50%;bottom:22px;transform:translateX(-50%);background:var(--hp-bg);border:1px solid var(--hp-accent);color:var(--hp-txt);padding:var(--sp-4) var(--sp-6);border-radius:var(--rad-l);font-size:var(--fs-m);box-shadow:var(--shadow-2);z-index:120;max-width:90vw;}`,o`.fixedfloor-loading{animation:fixedfloor-spin 1.1s linear infinite;}.fixedfloor-error p{max-width:42rem;margin:0;overflow-wrap:anywhere;}@media (prefers-reduced-motion:reduce){.fixedfloor-loading{animation:none;}.radar-target{transition:none;}}.stage.noplan{background:#ffffff;}.stage.mode-plan,.stage.mode-devices,.stage.mode-decor{background:#ffffff;}.stage{position:relative;width:100%;container-type:inline-size;overflow:hidden;touch-action:none;background:var(--ha-card-background,var(--card-background-color,#111));}.zoomwrap{position:absolute;inset:0;z-index:1;}.stage.mode-transition,.stage.mode-transition .zoomwrap{transition:none !important;}.stage.mode-transition .hp-view-only-layer,.stage.mode-transition .hp-editor-only-layer{pointer-events:none;will-change:opacity;}.stage.mode-transition .hp-paper{fill:var(--hp-mode-paper) !important;}.hp-day-cycle-env{position:absolute;inset:0;z-index:0;overflow:hidden;pointer-events:none;isolation:isolate;}.hp-day-cycle-bg{position:absolute;inset:0;opacity:0;overflow:hidden;transition:opacity 1100ms cubic-bezier(.22,.61,.36,1);}.hp-day-cycle-bg.active{opacity:1;}.hp-day-cycle-sun{position:absolute;left:var(--hp-day-cycle-sun-x);top:var(--hp-day-cycle-sun-y);width:clamp(140px,25cqw,250px);height:clamp(140px,25cqw,250px);transform:translate(-50%,-50%);border-radius:50%;filter:blur(10px);opacity:var(--hp-day-cycle-sun-opacity);transition:left 1100ms cubic-bezier(.22,.61,.36,1),top 1100ms cubic-bezier(.22,.61,.36,1),opacity 1100ms cubic-bezier(.22,.61,.36,1);}.stage.mode-transition .hp-day-cycle-env{transition:none;}.stage.daycycle .hp-paperg,.hp-static-stage.daycycle .hp-paperg{filter:drop-shadow(0 0 1px var(--hp-day-cycle-outline-near)) drop-shadow(0 0 5px var(--hp-day-cycle-outline-mid)) drop-shadow(0 0 10px var(--hp-day-cycle-outline-far));will-change:filter;transition:filter 1100ms cubic-bezier(.22,.61,.36,1);}@media (prefers-reduced-motion:reduce){.hp-day-cycle-bg,.hp-day-cycle-sun,.stage.daycycle .hp-paperg,.hp-static-stage.daycycle .hp-paperg{transition:none;}}.sunlayer{pointer-events:none;}.compass{width:120px;height:120px;flex:none;touch-action:none;cursor:grab;user-select:none;}.compass:active{cursor:grabbing;}.compass .cring{fill:rgba(255,255,255,0.04);stroke:var(--divider-color,#444);stroke-width:2;}.compass .ctick{stroke:var(--secondary-text-color,#9aa4ad);stroke-width:2;}.compass .ctick.minor{stroke-width:1;opacity:0.6;}.compass .cneedle line{stroke:var(--primary-color,#3ea6ff);stroke-width:2.5;stroke-linecap:round;}.compass .cneedle path{fill:var(--primary-color,#3ea6ff);}.compass .cneedle text{fill:var(--text-primary-color,#fff);font-size:11px;font-weight:700;}.compass .cdeg{fill:var(--secondary-text-color,#9aa4ad);font-size:13px;}.compass.unset .cneedle{opacity:0.35;}.stage.hpboot .zoomwrap,.stage.hpboot .zoombadge{visibility:hidden;}.stage.hpsettle{transition:height 0.25s ease;}@media (prefers-reduced-motion:reduce){.stage.hpsettle{transition:none;}}.zoomctl{display:inline-flex;gap:var(--sp-1);background:rgba(127,127,127,0.12);border-radius:var(--rad-m);padding:var(--sp-1);}.zoomctl .zb{border:none;padding:var(--sp-3) var(--sp-4);}.zoomctl .zb[disabled]{opacity:0.4;pointer-events:none;}.projection-toggle{min-width:44px;min-height:44px;justify-content:center;padding:var(--sp-3);}.header-action{min-width:44px;min-height:44px;justify-content:center;padding:var(--sp-3);}.homearrow{position:absolute;z-index:12;transform:translate(-50%,-50%);width:40px;height:40px;border-radius:50%;display:flex;align-items:center;justify-content:center;cursor:pointer;background:var(--card-background-color,var(--hp-bg));color:var(--hp-accent);border:1px solid var(--hp-accent);opacity:0.9;padding:0;}.homearrow ha-icon{--mdc-icon-size:22px;line-height:1;}.zoombadge{position:absolute;z-index:12;left:var(--sp-4);bottom:var(--sp-4);background:var(--card-background-color,var(--hp-bg));opacity:0.92;color:var(--hp-txt);border:1px solid var(--hp-accent);border-radius:var(--rad-m);padding:var(--sp-1) var(--sp-4);font-size:var(--fs-s);font-weight:600;pointer-events:none;}.zoomwrap>svg{position:absolute;inset:0;width:100%;height:100%;display:block;}.plan-svg{z-index:1;}.iso-underlay-svg{z-index:0;overflow:visible;}.iso-shadows-svg{z-index:3;overflow:visible;}.iso-walls-svg{z-index:4;overflow:visible;}.iso-overlays-svg{z-index:5;overflow:visible;}.iso-underlay-svg,.iso-shadows-svg,.iso-walls-svg,.iso-overlays-svg,.iso-underlay,.iso-shadows,.iso-walls,.iso-openings{pointer-events:none;}.iso-side-hi{stop-color:#b9bdbe;}.iso-side-lo{stop-color:#969c9f;}.iso-top-hi{stop-color:#fafaf7;}.iso-top-lo{stop-color:#e2e4e2;}.iso-wall-side{fill:url(#hp-iso-wall-side) #a8acae;stroke:#92989b;stroke-width:0.7;vector-effect:non-scaling-stroke;}.iso-wall-top{fill:url(#hp-iso-wall-top) #f3f3f1;stroke:#d7d9d8;stroke-width:0.8;vector-effect:non-scaling-stroke;}.iso-material-texture{fill:url(#hp-iso-wall-texture);stroke:none;opacity:0.12;pointer-events:none;}.iso-floor-texture{fill:url(#hp-iso-floor-texture);opacity:0.1;}.iso-texture-mark{fill:rgba(36,43,47,0.34);}.iso-texture-line{fill:none;stroke:rgba(36,43,47,0.24);stroke-width:0.55;}.iso-floor-side{fill:#858b8d;stroke:#71787b;stroke-width:0.7;vector-effect:non-scaling-stroke;}.iso-opening-panel{fill:#d7d9d7;fill-opacity:0.96;stroke:#7f878b;stroke-width:0.9;vector-effect:non-scaling-stroke;}.iso-opening-panel.iso-window{fill:#dfeff4;fill-opacity:0.72;stroke:#8aa7b1;}.iso-opening-panel.iso-material-reveal{fill:#c7cbca;stroke:#8b9294;}.iso-opening-panel.iso-material-matte-leaf{fill:#a6abad;stroke:#737b7f;}.iso-opening-panel.iso-opening-leaf-edge,.iso-opening-panel.iso-opening-leaf-top{fill:#8d9497;}.iso-opening-panel.iso-material-light-frame,.iso-opening-panel.iso-material-light-sill{fill:#fffef8;fill-opacity:0.94;stroke:#b3b5ae;}.iso-opening-panel.iso-material-light-window,.iso-opening-panel.iso-material-glass-side{fill:#c9e4f3;fill-opacity:0.88;stroke:#8fb4c7;}.iso-opening-panel.iso-material-glass-top{fill:#e3f2fa;fill-opacity:0.96;stroke:#9fc4d5;}.iso-ambient-shadow{fill:rgba(15,21,25,0.22);filter:url(#hp-iso-ambient-shadow);}.iso-contact-shadow{fill:none;stroke:rgba(22,28,31,0.25);stroke-width:3;filter:url(#hp-iso-contact-shadow);vector-effect:non-scaling-stroke;}.iso-leaf-shadow{fill:none;stroke:rgba(18,23,27,0.24);stroke-width:4;filter:url(#hp-iso-leaf-shadow);vector-effect:non-scaling-stroke;}.stage.theme-dark .iso-side-hi{stop-color:#4c555a;}.stage.theme-dark .iso-side-lo{stop-color:#343c40;}.stage.theme-dark .iso-top-hi{stop-color:#687176;}.stage.theme-dark .iso-top-lo{stop-color:#50585d;}.stage.theme-dark .iso-wall-side{stroke:#30373b;}.stage.theme-dark .iso-wall-top{stroke:#7b858a;}.stage.theme-dark .iso-floor-side{fill:#2d3438;stroke:#20272a;}.stage.theme-dark .iso-opening-panel{fill:#626b70;stroke:#899399;}.stage.theme-dark .iso-opening-panel.iso-window{fill:#75919b;stroke:#abc6ce;}.stage.theme-dark .iso-opening-panel.iso-material-reveal{fill:#454e52;stroke:#727d82;}.stage.theme-dark .iso-opening-panel.iso-material-matte-leaf{fill:#626a6e;stroke:#899398;}.stage.theme-dark .iso-opening-panel.iso-opening-leaf-edge,.stage.theme-dark .iso-opening-panel.iso-opening-leaf-top{fill:#4b5458;}.stage.theme-dark .iso-opening-panel.iso-material-light-frame,.stage.theme-dark .iso-opening-panel.iso-material-light-sill{fill:#e8e7df;stroke:#a9aca7;}.stage.theme-dark .iso-opening-panel.iso-material-light-window,.stage.theme-dark .iso-opening-panel.iso-material-glass-side{fill:#8fbfd5;stroke:#bad9e6;}.stage.theme-dark .iso-opening-panel.iso-material-glass-top{fill:#c9e6f2;stroke:#d9eef6;}.stage.theme-dark .iso-ambient-shadow{fill:rgba(0,0,0,0.34);}.stage.theme-dark .iso-contact-shadow,.stage.theme-dark .iso-leaf-shadow{stroke:rgba(0,0,0,0.38);}.stage.theme-dark .iso-texture-mark{fill:rgba(255,255,255,0.24);}.stage.theme-dark .iso-texture-line{stroke:rgba(255,255,255,0.18);}@media (prefers-color-scheme:dark){.stage:not(.theme-light) .iso-side-hi{stop-color:#4c555a;}.stage:not(.theme-light) .iso-side-lo{stop-color:#343c40;}.stage:not(.theme-light) .iso-top-hi{stop-color:#687176;}.stage:not(.theme-light) .iso-top-lo{stop-color:#50585d;}.stage:not(.theme-light) .iso-wall-side{stroke:#30373b;}.stage:not(.theme-light) .iso-wall-top{stroke:#7b858a;}.stage:not(.theme-light) .iso-floor-side{fill:#2d3438;stroke:#20272a;}.stage:not(.theme-light) .iso-opening-panel{fill:#626b70;stroke:#899399;}.stage:not(.theme-light) .iso-opening-panel.iso-window{fill:#75919b;stroke:#abc6ce;}.stage:not(.theme-light) .iso-opening-panel.iso-material-reveal{fill:#454e52;stroke:#727d82;}.stage:not(.theme-light) .iso-opening-panel.iso-material-matte-leaf{fill:#626a6e;stroke:#899398;}.stage:not(.theme-light) .iso-opening-panel.iso-opening-leaf-edge,.stage:not(.theme-light) .iso-opening-panel.iso-opening-leaf-top{fill:#4b5458;}.stage:not(.theme-light) .iso-opening-panel.iso-material-light-frame,.stage:not(.theme-light) .iso-opening-panel.iso-material-light-sill{fill:#e8e7df;stroke:#a9aca7;}.stage:not(.theme-light) .iso-opening-panel.iso-material-light-window,.stage:not(.theme-light) .iso-opening-panel.iso-material-glass-side{fill:#8fbfd5;stroke:#bad9e6;}.stage:not(.theme-light) .iso-opening-panel.iso-material-glass-top{fill:#c9e6f2;stroke:#d9eef6;}.stage:not(.theme-light) .iso-ambient-shadow{fill:rgba(0,0,0,0.34);}.stage:not(.theme-light) .iso-contact-shadow,.stage:not(.theme-light) .iso-leaf-shadow{stroke:rgba(0,0,0,0.38);}.stage:not(.theme-light) .iso-texture-mark{fill:rgba(255,255,255,0.24);}.stage:not(.theme-light) .iso-texture-line{stroke:rgba(255,255,255,0.18);}}@media (forced-colors:active){.iso-wall-side,.iso-wall-top,.iso-floor-side,.iso-opening-panel{fill:Canvas;stroke:CanvasText;forced-color-adjust:auto;}.iso-ambient-shadow,.iso-contact-shadow,.iso-leaf-shadow,.iso-material-texture{display:none;}}@supports not (filter:blur(1px)){.iso-ambient-shadow,.iso-contact-shadow,.iso-leaf-shadow,.iso-material-texture{display:none;}}.hp-paper{fill:var(--ha-card-background,var(--card-background-color,#111));stroke:none;}.stage.noplan .hp-paper,.stage.mode-plan .hp-paper,.stage.mode-devices .hp-paper,.stage.mode-decor .hp-paper{fill:#ffffff;}.room{transition:0.12s;cursor:default;stroke-linejoin:round;stroke-linecap:round;}.stage.mode-view .room{cursor:pointer;}.room.overlay{fill:transparent;stroke:transparent;stroke-width:calc(2px * var(--hp-cell-visual-scale,1));}:host([data-pointer-hover]) .stage.mode-view .room.overlay:not(.styled):hover{stroke:var(--hp-accent);stroke-opacity:1;}.room.yard{fill:rgba(75,140,90,0.14);stroke:#4b8c5a;stroke-width:calc(2px * var(--hp-cell-visual-scale,1));}:host([data-pointer-hover]) .stage.mode-view .room.yard:not(.styled):hover{stroke:var(--hp-accent);stroke-opacity:1;}.room.styled{stroke:var(--room-stroke,transparent);stroke-opacity:var(--room-stroke-op,0);stroke-width:calc(2.5px * var(--hp-cell-visual-scale,1));fill:var(--room-fill,transparent);fill-opacity:var(--room-fill-op,0);}.glow-base-layer,.glow-base-tunnels,.glow-pools-frame,.glow-pools,.glow-spot{pointer-events:none;}.glow-pools-frame,.glow-pools,.glow-spot{isolation:isolate;}.glow-pools.blend-screen .glow-spot{mix-blend-mode:screen;}.glow-spot{opacity:1;transition:opacity 500ms ease;}.glow-spot.is-entering,.glow-spot.is-leaving{opacity:0;}@media (prefers-reduced-motion:reduce){.glow-spot{transition:none;}}:host([data-pointer-hover]) .stage.mode-view .room.styled:hover{stroke:var(--hp-accent);stroke-opacity:1;}.op-leaf{transition:transform 0.6s ease;}.op-arc{stroke-width:calc(1.5px * var(--hp-cell-visual-scale,1));transition:stroke-dashoffset 0.6s ease;}.op-outline{fill:none;stroke:var(--hp-accent);stroke-width:calc(1.5px * var(--hp-cell-visual-scale,1));opacity:0;transition:opacity 0.15s;pointer-events:none;}:host([data-pointer-hover]) .stage.markup g.opening:hover .op-outline{opacity:0.9;}.op-hit{fill:transparent;pointer-events:none;cursor:default;}.stage.markup .op-hit{pointer-events:auto;cursor:grab;touch-action:none;}.stage.markup .op-hit:active{cursor:grabbing;}.stage.markup .opening.orphan{pointer-events:auto;cursor:pointer;color:var(--error-color,#db4437);}.stage.markup .opening.orphan circle{fill:var(--hp-bg);stroke:currentColor;stroke-width:calc(2px * var(--hp-cell-visual-scale,1));}.stage.markup .opening.orphan text{fill:currentColor;font-weight:800;font-size:calc(12px * var(--hp-cell-visual-scale,1));pointer-events:none;}.stage.markup.tool-resize .op-hit{pointer-events:none;cursor:default;}.stage.mode-view .oplock{pointer-events:auto;cursor:pointer;}.stage.projection-iso.mode-view .oplock::before{content:'';position:absolute;left:50%;top:50%;width:max(44px,100%);height:max(44px,100%);transform:translate(-50%,-50%);border-radius:50%;pointer-events:auto;}@media (prefers-reduced-motion:reduce){.op-leaf,.op-arc{transition:none;}}.roomlabel{pointer-events:none;position:absolute;transform:translate(-50%,-50%);font-size:calc(var(--rl-icon-size,var(--icon-size,2.5cqw)) * 0.5 * var(--rl-scale,1) * var(--rl-font,1) * var(--rl-space,1));font-weight:700;letter-spacing:0.04em;white-space:nowrap;cursor:grab;user-select:none;z-index:1;display:flex;flex-direction:column;align-items:center;gap:0.15em;text-align:center;}.rlname{display:inline-flex;align-items:center;gap:0.25em;font-size:calc(1em * var(--rl-name,1));}.zoomwrap.slide-left{animation:hp-slide-left 0.18s cubic-bezier(0.2,0.7,0.2,1);}.zoomwrap.slide-right{animation:hp-slide-right 0.18s cubic-bezier(0.2,0.7,0.2,1);}@media (prefers-reduced-motion:reduce){.zoomwrap.slide-left,.zoomwrap.slide-right{animation:none;}}.rlgearbtn{--gear-h:calc(var(--icon-size,2.5cqw) * 0.77);position:absolute;transform:translate(-50%,-50%);display:inline-flex;align-items:center;gap:0.35em;height:var(--gear-h);padding:0 calc(var(--gear-h) * 0.38);border:0;border-radius:999px;background:var(--hp-accent);color:var(--text-primary-color,#fff);font:inherit;font-size:calc(var(--gear-h) * 0.42);font-weight:600;line-height:1;white-space:nowrap;cursor:pointer;pointer-events:auto;opacity:0.92;box-shadow:var(--shadow-1);z-index:2;}.rlgearbtn{transition:opacity 0.15s,filter 0.15s;}:host([data-pointer-hover]) .rlgearbtn:hover{opacity:1;filter:brightness(1.18);}.rlgearbtn ha-icon{--mdc-icon-size:calc(var(--gear-h) * 0.55);display:inline-flex;}.rlgear{--mdc-icon-size:0.9em;display:inline-flex;margin-right:0.2em;opacity:0.6;cursor:pointer;pointer-events:auto;}:host([data-pointer-hover]) .rlgear:hover{opacity:1;}.rlgo{--mdc-icon-size:0.85em;display:inline-flex;opacity:0.55;}.stage.mode-view .rlgo{pointer-events:auto;cursor:pointer;}:host([data-pointer-hover]) .stage.mode-view .rlgo:hover{opacity:1;}.roomlabel .rlmetrics{position:absolute;top:calc(100% + 0.15em);left:50%;transform:translateX(-50%);white-space:nowrap;display:flex;align-items:center;gap:0.55em;font-size:calc(0.75em * var(--rl-meta,1));font-weight:600;letter-spacing:0.02em;opacity:0.9;}.roomlabel .rlm{display:inline-flex;align-items:center;gap:0.12em;}.roomlabel .rlm ha-icon{--mdc-icon-size:1.05em;display:inline-flex;}.roomlabel .rlm.lit{opacity:1;}.rlhandle{display:none;position:absolute;width:9px;height:9px;border-radius:2px;background:var(--hp-accent);border:1px solid var(--card-background-color,#fff);z-index:2;}.rlhandle.tl{left:-6px;top:-6px;cursor:nwse-resize;}.rlhandle.br{right:-6px;bottom:-6px;cursor:nwse-resize;}.rlhandle.tr{right:-6px;top:-6px;cursor:nesw-resize;}.rlhandle.bl{left:-6px;bottom:-6px;cursor:nesw-resize;}:host([data-pointer-hover]) .stage.markup .roomlabel:hover .rlhandle{display:block;}.stage.markup .roomlabel{pointer-events:auto;}.stage.mode-view .roomlabel{pointer-events:auto;cursor:pointer;border-radius:0.2em;}.stage.projection-iso.mode-view .roomlabel{box-sizing:border-box;min-width:44px;min-height:44px;justify-content:center;text-shadow:none;filter:none;-webkit-text-stroke:0 transparent;color:#303936 !important;}.stage.projection-iso.theme-dark.mode-view .roomlabel{color:#f2f0e8 !important;}@media (prefers-color-scheme:dark){.stage.projection-iso:not(.theme-light).mode-view .roomlabel{color:#f2f0e8 !important;}}.stage.mode-view .roomlabel:focus-visible{outline:2px solid var(--hp-accent);outline-offset:4px;}.roomlabel:active{cursor:grabbing;}.measurelayer{position:absolute;inset:0;pointer-events:none;}.alignline{stroke:var(--hp-accent);stroke-width:calc(1.2px * var(--hp-cell-visual-scale,1));stroke-dasharray:calc(4px * var(--hp-cell-visual-scale,1)) calc(4px * var(--hp-cell-visual-scale,1));pointer-events:none;opacity:0.9;}.aligndot{fill:var(--hp-accent);pointer-events:none;}.measurelabel.on45{color:#4bd28f;border-color:#4bd28f;}.measurelabel{position:absolute;transform:translate(12px,-150%);font-size:var(--fs-s);font-weight:600;padding:1px var(--sp-3);border-radius:var(--rad-s);background:rgba(0,0,0,0.72);color:#fff;white-space:nowrap;pointer-events:none;user-select:none;z-index:3;}.measurelabel.opdimension{transform:translate(calc(-50% + var(--op-label-shift-x,0px)),calc(-50% + var(--op-label-shift-y,-12px)));border:1px solid var(--hp-open,#ff9800);}.decorlayer .dshape{pointer-events:none;}.stage.mode-decor .decorlayer .dshape{pointer-events:visiblePainted;cursor:pointer;}.stage.mode-decor.dtool-select .decorlayer .dshape{cursor:move;}.stage.mode-decor.dtool-line .decorlayer .dshape,.stage.mode-decor.dtool-rect .decorlayer .dshape,.stage.mode-decor.dtool-ellipse .decorlayer .dshape,.stage.mode-decor.dtool-text .decorlayer .dshape,.stage.mode-decor.dtool-furniture .decorlayer .dshape,.stage.mode-decor.dtool-image .decorlayer .dshape,.stage.mode-decor.dtool-backdrop .decorlayer .dshape{pointer-events:none;}.stage.mode-decor.dtool-furniture,.stage.mode-decor.dtool-image{cursor:copy;}.stage.mode-decor.dtool-select .decorlayer .dimage,.stage.mode-decor.dtool-erase .decorlayer .dimage,.stage.mode-decor.dtool-select .decorlayer .dimage-missing,.stage.mode-decor.dtool-erase .decorlayer .dimage-missing{pointer-events:bounding-box;}.decorlayer .dimage-missing rect{fill:rgba(127,127,127,0.12);stroke:var(--hp-accent);stroke-dasharray:8 5;vector-effect:non-scaling-stroke;}.decorlayer .dimage-missing path{fill:none;stroke:var(--hp-accent);vector-effect:non-scaling-stroke;}.decorlayer .decor-image-placement-preview{opacity:0.65;}.stage.mode-decor.dtool-text .decorlayer .dshape.dtext,.stage.mode-decor.dtool-select .decorlayer .dshape.dtext,.stage.mode-decor.dtool-erase .decorlayer .dshape.dtext{pointer-events:visiblePainted;pointer-events:bounding-box;}.stage.mode-decor.dtool-text .decorlayer .dshape.dtext{cursor:text;}.decorlayer .derasehit{fill:none;stroke:transparent;stroke-width:16px;stroke-linecap:round;stroke-linejoin:round;vector-effect:non-scaling-stroke;pointer-events:none;}.stage.mode-decor.dtool-erase .decorlayer .derasehit{pointer-events:stroke;}.decorlayer .dselecthit{fill:none;stroke:transparent;stroke-width:16px;stroke-linecap:round;vector-effect:non-scaling-stroke;pointer-events:none;}.stage.mode-decor.dtool-select .decorlayer .dselecthit{pointer-events:stroke;cursor:move;}.stage.mode-decor .decorlayer .dshape.dfurniturehit{fill:none;stroke:transparent;pointer-events:none;}.stage.mode-decor.dtool-select .decorlayer .dshape.dfurniturehit{pointer-events:stroke;cursor:move;}.decorlayer .dsel{filter:drop-shadow(0 0 3px var(--hp-accent));}.decorlayer .ddraft{stroke-dasharray:calc(6px * var(--hp-cell-visual-scale,1)) calc(5px * var(--hp-cell-visual-scale,1));pointer-events:none;}.decorlayer .furniture-placement-preview{opacity:0.55;pointer-events:none;}.decorlayer text{font-weight:600;user-select:none;dominant-baseline:middle;text-anchor:middle;}.stage.mode-decor{outline:2px solid #26a69a;outline-offset:-2px;}.bdframe .bdbox{fill:none;stroke:var(--hp-accent);stroke-width:2;stroke-dasharray:10 7;vector-effect:non-scaling-stroke;pointer-events:none;opacity:0.9;}.bdframe .bdhandle{fill:transparent;stroke:none;pointer-events:all;touch-action:none;}.bdframe .bdknob{fill:var(--hp-accent);stroke:#fff;stroke-width:1;vector-effect:non-scaling-stroke;pointer-events:none;}:host([data-pointer-hover]) .bdframe .bdhandle:hover + .bdknob{fill:#fff;stroke:var(--hp-accent);}.bdframe .bd-nwse{cursor:nwse-resize;}.bdframe .bd-nesw{cursor:nesw-resize;}.stage.mode-decor.bdgrab{cursor:grab;}.stage.mode-decor.bdgrabbing,.stage.mode-decor.bdgrabbing .bdframe .bdhandle{cursor:grabbing;}.measurelabel.bdmeasure{transform:translate(-50%,-50%);border:1px solid var(--hp-accent);}.dtframe .dtbox{fill:none;stroke:var(--hp-accent);stroke-width:1.5;stroke-dasharray:7 5;vector-effect:non-scaling-stroke;pointer-events:none;opacity:0.85;}.dtframe .dtstem,.bdframe .dtstem{stroke:var(--hp-accent);stroke-width:1.5;vector-effect:non-scaling-stroke;pointer-events:none;opacity:0.85;}.dtframe .dthandle{fill:transparent;stroke:none;pointer-events:all;touch-action:none;}.dtframe .dtknob{fill:var(--hp-accent);stroke:#fff;stroke-width:1;vector-effect:non-scaling-stroke;pointer-events:none;}:host([data-pointer-hover]) .dtframe .dthandle:hover + .dtknob{fill:#fff;stroke:var(--hp-accent);}.dtframe .dt-nwse{cursor:nwse-resize;}.dtframe .dt-nesw{cursor:nesw-resize;}.dtframe .dtrot{cursor:grab;}.dtframe .dt-ew{cursor:ew-resize;}.dtframe .dt-ns{cursor:ns-resize;}.dtfurnitureframe .dtrot{cursor:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M18.4 7.2A8 8 0 1 0 20 12' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round'/%3E%3Cpath d='m15.5 3.8 3.2 3.5-4.6.8' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") 12 12,grab;}.dtfurnitureframe .dtrot:active{cursor:grabbing;}.dtframe .dtendpoint{cursor:crosshair;}.bdframe .dtrot{cursor:grab;}.dtarea{resize:vertical;min-height:3.4em;font:inherit;line-height:1.35;}.stage.mode-decor.dtool-line,.stage.mode-decor.dtool-rect,.stage.mode-decor.dtool-ellipse,.stage.mode-decor.dtool-text{cursor:crosshair;}.stage.mode-decor.dtool-erase,.stage.mode-decor.dtool-erase .decorlayer .dshape{cursor:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cg transform='rotate(-45 12 12)'%3E%3Crect x='7' y='2' width='10' height='18' rx='2' fill='%23fff' stroke='%23111' stroke-width='1.5'/%3E%3Cpath d='M7 13h10v5a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2z' fill='%23ff9f43' stroke='%23111' stroke-width='1.5'/%3E%3C/g%3E%3C/svg%3E") 5 22,pointer;}.stage.mode-decor .room{pointer-events:none;}.stage.mode-decor .devlayer,.stage.mode-decor .devlayer *,.stage.mode-decor .dev::before{pointer-events:none;}.stage .room,.stage .devlayer,.stage .opening,.stage .room-outline,.stage .wallbodies,.stage .opening-tunnels,.stage .glow-base-layer,.stage .glow-pools-frame,.stage .zero-walls{opacity:var(--hp-mode-architecture-opacity,1);}.opening-preview{opacity:0.5;pointer-events:none;}.opening-preview[data-kind="passage"]{opacity:1;}.passage-preview-cut{fill:var(--wall-fill,#ffffff);fill-opacity:0.35;stroke:none;pointer-events:none;}.passage-preview-boundary{stroke:var(--hp-open,#ff9800);stroke-width:calc(2.5px * var(--hp-cell-visual-scale,1));pointer-events:none;}.opening-preview .op-leaf,.opening-preview .op-arc{transition:none;}.opening-preview-dot{fill:var(--hp-open,#ff9800);pointer-events:none;}.opening-dimensions,.opening-dimension{pointer-events:none;}.opening-dimension-line,.opening-dimension-tick{fill:none;stroke:var(--hp-open,#ff9800);stroke-width:1.5;vector-effect:non-scaling-stroke;pointer-events:none;}.opening-dimension-tick{stroke-width:2;}.stage.edit .room{pointer-events:none;}.stage.markup{cursor:crosshair;}.stage.markup.tool-merge,.stage.markup.tool-split.pickstage,.stage.markup.tool-delroom{cursor:pointer;}.stage.markup.tool-wallthick{cursor:default;}.stage.markup.tool-wallthick.wallhot{cursor:pointer;}.wallbody-fill{fill:var(--wall-fill,#ffffff);fill-opacity:var(--wall-fill-op,1);fill-rule:evenodd;stroke:none;pointer-events:none;}.wallbody{fill:url(#hp-wall-hatch);fill-rule:evenodd;stroke:var(--room-stroke,var(--hp-muted));stroke-width:calc(0.6px * var(--hp-cell-visual-scale,1));pointer-events:none;}.wallbody.solid{fill:none;}.wallthick-hover{fill:var(--accent-color,#03a9f4);fill-opacity:0.38;stroke:var(--accent-color,#03a9f4);stroke-width:calc(2.5px * var(--hp-cell-visual-scale,1));stroke-linejoin:round;stroke-linecap:round;pointer-events:none;}.wallthick-hover.isopen{fill:var(--error-color,#f44336);stroke:var(--error-color,#f44336);}.zero-wall{stroke:var(--zero-wall-stroke,var(--hp-muted));stroke-width:calc(2.5px * var(--hp-cell-visual-scale,1));stroke-dasharray:calc(7px * var(--hp-cell-visual-scale,1)) calc(7px * var(--hp-cell-visual-scale,1));stroke-linecap:butt;pointer-events:none;opacity:0.9;}.zero-walls.solid .zero-wall{stroke-dasharray:none;}.room.noedge{stroke-opacity:0 !important;}.room-outline{fill:none;stroke-width:calc(2.5px * var(--hp-cell-visual-scale,1));stroke-linejoin:round;stroke-linecap:round;pointer-events:none;}.room-outline.outlined{stroke:rgba(62,166,255,0.55);stroke-opacity:1;}.room-hover-fill{fill:#000;fill-opacity:0.22;pointer-events:none;}.room-hover-halo{fill:none;stroke:var(--hp-accent);stroke-opacity:0.28;stroke-width:calc(8px * var(--hp-cell-visual-scale,1));stroke-linejoin:round;stroke-linecap:round;pointer-events:none;}.room-hover-outline{fill:none;stroke:var(--hp-accent);stroke-width:calc(3px * var(--hp-cell-visual-scale,1));stroke-linejoin:round;stroke-linecap:round;pointer-events:none;}.stage.markup .room{pointer-events:none;}.stage.markup .devlayer .dev{display:none;}.stage.mode-plan{outline:2px solid #ffc14d;outline-offset:-2px;}.stage.mode-devices{outline:2px solid var(--hp-accent);outline-offset:-2px;}.room.outlined{stroke:rgba(62,166,255,0.55);fill:rgba(62,166,255,0.06);}.room.picked{stroke:#ffc14d;stroke-width:calc(3px * var(--hp-cell-visual-scale,1));fill:rgba(255,193,77,0.25);}.griddot{fill:var(--hp-accent);opacity:0.35;stroke:rgba(0,0,0,0.35);stroke-width:0.4;}.griddot.major{opacity:0.5;stroke-width:0;}.seg{stroke:var(--hp-accent);stroke-width:calc(2.5px * var(--hp-cell-visual-scale,1));stroke-linecap:round;stroke-linejoin:round;}.pathline{stroke:#ffc14d;stroke-width:calc(3px * var(--hp-cell-visual-scale,1));fill:none;stroke-linecap:round;stroke-linejoin:round;}.preview{stroke:#ffc14d;stroke-width:calc(2px * var(--hp-cell-visual-scale,1));stroke-dasharray:calc(6px * var(--hp-cell-visual-scale,1)) calc(5px * var(--hp-cell-visual-scale,1));opacity:0.7;}.active-axis{stroke:#ffc14d;stroke-width:2;stroke-linecap:round;vector-effect:non-scaling-stroke;pointer-events:none;}.active-vertex{fill:#ffc14d;stroke:#171006;stroke-width:2;vector-effect:non-scaling-stroke;pointer-events:none;}.wall-repair-preview{stroke:#d93025;stroke-width:4;stroke-linecap:round;stroke-dasharray:5 4;vector-effect:non-scaling-stroke;pointer-events:none;}.drawwall-preview-fill{fill:var(--wall-fill,#ffffff);fill-opacity:calc(var(--wall-fill-op,1) * 0.55);fill-rule:evenodd;stroke:none;pointer-events:none;}.drawwall-preview{fill:url(#hp-wall-hatch);fill-opacity:0.55;fill-rule:evenodd;stroke:var(--accent-color,#03a9f4);stroke-width:calc(0.5px * var(--hp-cell-visual-scale,1));stroke-opacity:0.7;pointer-events:none;}.drawwall-zero-preview{fill:none;stroke:var(--accent-color,#03a9f4);stroke-width:calc(3px * var(--hp-cell-visual-scale,1));stroke-linecap:butt;stroke-linejoin:round;opacity:0.72;pointer-events:none;}.drawwall-zero-preview.dashed{stroke-dasharray:calc(7px * var(--hp-cell-visual-scale,1)) calc(7px * var(--hp-cell-visual-scale,1));}.vertex{fill:#ffc14d;stroke:#4a2800;stroke-width:calc(1px * var(--hp-cell-visual-scale,1));}.vertex.first{fill:#4bd28f;stroke:#04121f;}.plan-snap-overlay,.plan-snap-overlay *,.hidden-wall-diagnostic,.hidden-wall-diagnostic *{pointer-events:none;}.plan-snap-line,.hidden-wall-line{fill:none;stroke:color-mix(in srgb,var(--hp-accent) 82%,white 18%);stroke-width:1;stroke-linecap:round;opacity:0.92;}.plan-snap-node,.hidden-wall-node{fill:var(--ha-card-background,var(--card-background-color,#fff));stroke:color-mix(in srgb,var(--hp-accent) 88%,#07131c 12%);stroke-width:1;vector-effect:non-scaling-stroke;}.plan-snap-node.active{fill:#ffc14d;stroke:#171006;stroke-width:2;}.plan-snap-node.active.dynamic{fill:#4bd28f;stroke:#04121f;}.plan-snap-node.conflict{fill:#fff;stroke:#d93025;stroke-width:3;}@media (prefers-color-scheme:dark){.plan-snap-line{stroke:color-mix(in srgb,var(--hp-accent) 72%,white 28%);}.hidden-wall-line{stroke:color-mix(in srgb,var(--hp-accent) 72%,white 28%);}.plan-snap-node,.hidden-wall-node{fill:#17242c;stroke:#9bdcf5;}.plan-snap-node.active{fill:#ffc14d;stroke:#fff4d6;}.plan-snap-node.active.dynamic{fill:#4bd28f;stroke:#eafff4;}}@media (forced-colors:active){.plan-snap-line,.hidden-wall-line{stroke:CanvasText;opacity:1;forced-color-adjust:auto;}.plan-snap-node,.hidden-wall-node{fill:Canvas;stroke:CanvasText;forced-color-adjust:auto;}.plan-snap-node.active,.plan-snap-node.active.dynamic{fill:Highlight;stroke:HighlightText;forced-color-adjust:auto;}}.sunlayer{animation:hp-sunfade-in 2s linear both;}.sunlayer.out{animation:hp-sunfade-out 2s linear both;}@media (prefers-reduced-motion:reduce){.sunlayer,.sunlayer.out{animation:none;}.sunlayer.out{opacity:0;}}.devlayer{position:absolute;inset:0;pointer-events:none;z-index:6;}.radar-target{position:absolute;width:8px;height:8px;box-sizing:border-box;transform:translate(-50%,-50%);border-radius:50%;background:var(--success-color,#43a047);border:2px solid var(--primary-text-color,#1f1f1f);box-shadow:0 0 0 1px color-mix(in srgb,var(--card-background-color,#fff) 80%,transparent);pointer-events:none;z-index:0;}.radar-target.smooth{transition:left 200ms linear,top 200ms linear;}.radar-ranges{position:absolute;inset:0;width:100%;height:100%;overflow:visible;pointer-events:none;z-index:0;}.radar-ranges path,.radar-ranges polyline{fill:none;stroke:var(--success-color,#43a047);stroke-width:2px;stroke-dasharray:5 4;vector-effect:non-scaling-stroke;opacity:0.72;}.radar-ranges .radar-zone{fill:color-mix(in srgb,var(--success-color,#43a047) 8%,transparent);stroke:var(--success-color,#43a047);stroke-width:2px;vector-effect:non-scaling-stroke;opacity:0.8;}.stage.mode-devices .dev{cursor:grab;}.stage.mode-devices .dev:active{cursor:grabbing;}.physical-hit{fill:transparent;stroke:transparent;pointer-events:none;cursor:grab;}.stage.tool-select .physical-hit{pointer-events:all;}.physical-hit:active{cursor:grabbing;}line.physical-hit{cursor:pointer;}.physical-hit.selected{fill:rgba(255,193,77,0.24);stroke:transparent;}line.physical-hit.selected{stroke:transparent;}.physical-drag{fill:rgba(255,193,77,0.38);stroke:#ffc14d;stroke-width:2.5;vector-effect:non-scaling-stroke;pointer-events:none;}.physical-chrome{pointer-events:none;}.physical-chrome .frame,.physical-chrome .stem{fill:none;stroke:#ffc14d;stroke-width:2;vector-effect:non-scaling-stroke;}.physical-chrome .frame{fill:rgba(255,193,77,0.22);}.physical-chrome polyline.frame{fill:none;}.physical-chrome .move-dot{fill:#ffc14d;stroke:#24262d;stroke-width:1.5;vector-effect:non-scaling-stroke;}.physical-chrome .rotate-handle{fill:#24262d;stroke:#ffc14d;stroke-width:2.5;vector-effect:non-scaling-stroke;pointer-events:all;cursor:crosshair;}.drawwall.invalid input{border-color:var(--error-color,#db4437);}.drawwall .rangehint{margin-inline-start:4px;font-size:0.78em;opacity:0.72;}.drawwall.invalid .rangehint{color:var(--error-color,#db4437);opacity:1;}.stage.markup.tool-partition,.stage.markup.tool-column{cursor:crosshair;}.rszhandle{fill:transparent;stroke:none;pointer-events:all;cursor:grab;touch-action:none;}.rszhandle:active{cursor:grabbing;}.rszhandle.disabled,.rszhandle.disabled:active{cursor:not-allowed;}.rszicon{pointer-events:none;}.rszicon path{fill:none;stroke-linecap:round;stroke-linejoin:round;vector-effect:non-scaling-stroke;}.rszhalo{stroke:var(--hp-bg);stroke-width:6;}.rszink{stroke:var(--hp-accent);stroke-width:2;}:host([data-pointer-hover]) .rszhandle:hover + .rszicon .rszink{stroke-width:3;}.rszicon.disabled{opacity:0.38;}:host([data-pointer-hover]) .rszhandle.disabled:hover + .rszicon .rszink{stroke-width:2;}.rszmeasurelayer,.rszmeasurelayer *{pointer-events:none;}.rszmeasurehalo,.rszmeasureink,.rszleader{fill:none;stroke-linecap:round;vector-effect:non-scaling-stroke;}.rszmeasurehalo{stroke:var(--hp-bg);stroke-width:7px;opacity:0.9;}.rszmeasureink{stroke:var(--hp-accent);stroke-width:3px;}.rszleader{stroke:var(--hp-accent);stroke-width:2px;opacity:0.95;}.measurelabel.dmeasure{transform:translate(-50%,-160%);}.measurelabel.rszarea{transform:translate(calc(-50% + var(--rsz-label-x,0px)),calc(-50% + var(--rsz-label-y,0px)));background:rgba(0,0,0,0.6);border:1px solid var(--hp-accent);}.measurelabel.furnmeasure{transform:translate(-50%,-50%);border:1px solid var(--hp-accent);}.alignmsg{margin:0 0 8px;font-size:13px;line-height:1.45;}`,o`.dev ha-icon{position:relative;z-index:1;}.device-pulse{position:absolute;left:50%;top:50%;width:var(--dev-size);height:var(--dev-size);transform:translate(-50%,-50%);pointer-events:none;z-index:0;}.device-pulse i{position:absolute;inset:0;border-radius:50%;border:2px solid var(--ripple-color,var(--hp-accent));opacity:0;}.device-pulse.short i{animation:hp-pulse-short 1.1s cubic-bezier(.22,.61,.36,1) 1 forwards;}.device-pulse.short i:nth-child(2){animation-delay:1.1s;}.device-pulse.short i:nth-child(3){animation-delay:2.2s;}.device-pulse.short.gen2 i{animation-name:hp-pulse-short-b;}.device-pulse.continuous i:nth-child(n + 2),.device-pulse.alarm i:nth-child(n + 3){display:none;}.device-pulse.continuous i:first-child{animation:hp-pulse-continuous 3.6s cubic-bezier(.45,.05,.55,.95) infinite;}.device-pulse.alarm i{border-width:3px;border-color:#F0410C;animation:hp-pulse-alarm 2.4s cubic-bezier(.22,.61,.36,1) infinite;}.device-pulse.alarm i:nth-child(2){animation-delay:1.2s;}.activity-dot{position:absolute;right:8%;bottom:8%;width:18%;height:18%;min-width:4px;min-height:4px;border-radius:50%;background:var(--ripple-color,var(--hp-accent));border:1px solid color-mix(in srgb,var(--hp-bg) 82%,transparent);pointer-events:none;z-index:3;}.kioskdots{position:absolute;left:50%;bottom:var(--sp-5);transform:translateX(-50%);display:flex;gap:var(--sp-4);z-index:5;pointer-events:none;}.kdot{width:9px;height:9px;border-radius:50%;background:var(--hp-muted);opacity:0.55;}.kdot.on{background:var(--hp-accent);opacity:1;}.dev.valonly{width:var(--dev-size,var(--icon-size,2.5cqw));}.dev.valonly .device-core{width:max-content;min-width:var(--dev-size,var(--icon-size,2.5cqw));padding-inline:calc(var(--dev-size,var(--icon-size,2.5cqw)) * 0.16);border-radius:calc(var(--dev-size,var(--icon-size,2.5cqw)) / 2);}.dev .valtext{overflow:visible;font-size:calc(var(--dev-size,var(--icon-size,2.5cqw)) * var(--value-font-scale,.45));font-weight:600;white-space:nowrap;}@media (prefers-reduced-motion:reduce){.device-pulse{display:none;}}.dev .newdot{position:absolute;top:calc(var(--dev-size,var(--icon-size,2.5cqw)) * -0.12);right:calc(var(--dev-size,var(--icon-size,2.5cqw)) * -0.12);width:calc(var(--dev-size,var(--icon-size,2.5cqw)) * 0.34);height:calc(var(--dev-size,var(--icon-size,2.5cqw)) * 0.34);border-radius:50%;background:#f0301f;border:2px solid var(--card-background-color,var(--hp-bg));pointer-events:none;z-index:2;}.dev{position:absolute;--dev-size:calc(var(--device-base-size,2.25cqw) * var(--dev-scale,1));--device-shell-size:calc(var(--dev-size) * 1.26875);--device-shell-inset:calc(var(--dev-size) * 0.134375);--device-shell-stroke-ratio:0.01875;--device-shell-border-width:max(1px,calc(var(--dev-size) * var(--device-shell-stroke-ratio)));--device-core-bg:var(--card-background-color,#fff);--device-core-fg:var(--primary-text-color,#252525);--device-core-bg:light-dark(#fff,#252525);--device-core-fg:light-dark(#252525,#fff);--device-face-bg:var(--device-core-bg);--device-face-fg:var(--device-core-fg);--device-shell-base-stroke:light-dark(#BCBCBC,rgb(37 37 37 / 75%));--device-shell-stroke:var(--device-shell-base-stroke);--device-shell-shadow:0 calc(var(--dev-size) * .025) calc(var(--dev-size) * .05) rgb(37 40 45 / 12%),0 calc(var(--dev-size) * .1) calc(var(--dev-size) * .175) calc(var(--dev-size) * -.025) rgb(37 40 45 / 18%);--device-core-inset-shadow:0 0 0 0 transparent;--device-ring-color:transparent;--device-ring-width:0px;width:var(--dev-size);height:var(--dev-size);margin:calc(var(--dev-size) / -2) 0 0 calc(var(--dev-size) / -2);border:0;background:transparent;display:block;color:var(--device-core-fg);cursor:pointer;pointer-events:none;transition:opacity 0.2s;box-shadow:none;outline:none;z-index:auto;}.dev.theme-light{--device-core-bg:#fff;--device-core-fg:#000;--device-shell-base-stroke:#BCBCBC;--device-shell-stroke:var(--device-shell-base-stroke);--device-shell-shadow:0 calc(var(--dev-size) * .025) calc(var(--dev-size) * .05) rgb(37 40 45 / 12%),0 calc(var(--dev-size) * .1) calc(var(--dev-size) * .175) calc(var(--dev-size) * -.025) rgb(37 40 45 / 18%);--device-core-inset-shadow:0 0 0 0 transparent;}.dev.theme-dark{--device-core-bg:#252525;--device-core-fg:#fff;--device-shell-base-stroke:rgb(37 37 37 / 75%);--device-shell-stroke:var(--device-shell-base-stroke);--device-shell-shadow:0 calc(var(--dev-size) * .025) calc(var(--dev-size) * .0375) rgb(37 40 45 / 12%),0 calc(var(--dev-size) * .1) calc(var(--dev-size) * .175) calc(var(--dev-size) * -.025) rgb(37 40 45 / 18%);--device-core-inset-shadow:inset 0 calc(var(--dev-size) * 0.0125) calc(var(--dev-size) * 0.0125) rgb(255 255 255 / 70%);}.dev::before{content:'';position:absolute;left:50%;top:50%;width:max(44px,var(--device-shell-size));height:max(44px,var(--device-shell-size));transform:translate(-50%,-50%);border-radius:50%;pointer-events:auto;z-index:1;}.device-shell{position:absolute;box-sizing:border-box;display:flex;align-items:center;gap:calc(var(--dev-size) * 0.1);padding:0;min-width:var(--dev-size);min-height:var(--dev-size);border:0;background:transparent;box-shadow:none;transition:opacity .2s;pointer-events:none;z-index:2;}.device-shell-frame{position:absolute;z-index:0;box-sizing:border-box;inset:calc(var(--device-shell-inset) / -1);border:var(--device-shell-border-width) solid var(--device-shell-stroke);border-radius:9999px;background:transparent;box-shadow:var(--device-shell-shadow);transition:border-color .15s,opacity .2s;pointer-events:auto;backdrop-filter:none;}.device-shell:not(.with-values){left:0;top:0;}.device-shell:not(.with-values):not(.text-shell) .device-shell-frame{border-radius:50%;}.device-shell.with-values.pos-right{left:0;top:50%;transform:translateY(-50%);}.device-shell.with-values.pos-left{right:0;top:50%;transform:translateY(-50%);flex-direction:row-reverse;}.device-shell.with-values.pos-bottom{left:50%;top:0;transform:translateX(-50%);flex-direction:column;}.device-shell.with-values.pos-top{left:50%;bottom:0;transform:translateX(-50%);flex-direction:column-reverse;}.device-core{position:relative;z-index:1;box-sizing:border-box;flex:0 0 auto;width:var(--dev-size);height:var(--dev-size);display:flex;align-items:center;justify-content:center;border-radius:50%;background:var(--device-face-bg);color:var(--device-face-fg);box-shadow:var(--device-core-inset-shadow),0 0 0 var(--device-ring-width) var(--device-ring-color);line-height:0;transition:background .15s,color .15s,opacity .2s;pointer-events:none;}.device-sections{display:flex;flex-direction:column;align-items:stretch;justify-content:center;gap:calc(var(--dev-size) * .08);min-width:0;pointer-events:none;}.device-shell.pos-top .device-sections,.device-shell.pos-bottom .device-sections{flex-direction:row;}.dev ha-icon{--mdc-icon-size:calc(var(--dev-size,var(--device-base-size,2.25cqw)) * 0.55);display:flex;align-items:center;justify-content:center;line-height:0;}.dev.on{--device-face-bg:#F0A00C;--device-face-fg:light-dark(#fff,#252525);--device-shell-stroke:#F0A00C;}.dev.theme-light.on{--device-face-fg:#fff;}.dev.theme-dark.on{--device-face-fg:#252525;--device-shell-stroke-ratio:.0375;}.dev.open{--device-face-bg:var(--hp-open);--device-face-fg:light-dark(#fff,#252525);}.dev.theme-light.open{--device-face-fg:#fff;}.dev.theme-dark.open{--device-face-fg:#252525;}.dev.lock-locked{--device-face-bg:#66D17A;--device-face-fg:light-dark(#fff,#252525);--device-shell-stroke:#66D17A;}.dev.theme-light.lock-locked{--device-face-fg:#fff;}.dev.theme-dark.lock-locked{--device-face-fg:#252525;--device-shell-stroke-ratio:.025;}.dev.lock-unlocked{--device-face-bg:#F0410C;--device-face-fg:light-dark(#fff,#252525);--device-shell-stroke:#F0410C;}.dev.theme-light.lock-unlocked{--device-face-fg:#fff;}.dev.theme-dark.lock-unlocked{--device-face-fg:#252525;--device-shell-stroke-ratio:.025;}:host([data-pointer-hover]) .dev:not(.unavail)[data-hp-device-hover]{--device-face-bg:#0C82F0;--device-face-fg:light-dark(#fff,#252525);--device-shell-stroke:var(--device-shell-base-stroke);}:host([data-pointer-hover]) .dev.theme-light:not(.unavail)[data-hp-device-hover]{--device-face-fg:#fff;}:host([data-pointer-hover]) .dev.theme-dark:not(.unavail)[data-hp-device-hover]{--device-face-fg:#252525;}:host([data-pointer-hover]) .dev[data-hp-device-hover],.dev:focus-visible{z-index:5;}.dev[data-hp-zigbee-topology-endpoint]{z-index:8;}:host([data-pointer-hover]) .dev[data-hp-zigbee-topology-endpoint][data-hp-device-hover]{z-index:8;}.dev.unavail{opacity:0.35;--device-face-bg:#B5BAC1;--device-shell-stroke:var(--device-shell-base-stroke);}.dev.virtual .device-shell-frame{border-style:dashed;}.dev.ghost{opacity:0.6;color:var(--hp-accent);}.dev.ghost .device-shell-frame{border-style:dashed;border-color:var(--hp-accent);box-shadow:none;}.dev.ghost .device-core{background:rgba(62,166,255,0.22);background:color-mix(in srgb,var(--hp-accent) 30%,var(--card-background-color,#1c2530));color:var(--hp-accent);}.dev.ghost.ha-disabled{opacity:0.62;color:var(--secondary-text-color,#9aa0aa);}.dev.ghost.ha-disabled .device-shell-frame{border-color:var(--secondary-text-color,#9aa0aa);}.dev.ghost.ha-disabled .device-core{background:rgba(120,124,134,0.2);background:color-mix(in srgb,var(--secondary-text-color,#9aa0aa) 24%,var(--card-background-color,#1c2530));color:var(--secondary-text-color,#9aa0aa);}.dev .habadge{position:absolute;right:-18%;bottom:-18%;display:grid;place-items:center;width:46%;height:46%;min-width:12px;min-height:12px;border-radius:50%;background:var(--card-background-color,#242832);border:1px solid currentColor;}.dev .habadge ha-icon{width:72%;height:72%;}.dev.sel{--device-ring-color:#F0A00C;--device-ring-width:calc(var(--dev-size) * 0.0375);}.dev:focus-visible{--device-ring-color:#0C82F0;--device-ring-width:calc(var(--dev-size) * 0.0375);}.dev:not(.on):not(.open):not(.alarm):not(.lock-locked):not(.lock-unlocked):not(.unavail):focus-visible{--device-face-fg:#0C82F0;}.dev.alarm,:host([data-pointer-hover]) .dev.alarm[data-hp-device-hover],.dev.alarm:focus-visible{--device-face-bg:#F0410C;--device-face-fg:light-dark(#fff,#252525);--device-shell-stroke:#F0410C;}.dev.theme-light.alarm{--device-face-fg:#fff;}.dev.theme-dark.alarm{--device-face-fg:#252525;--device-shell-stroke-ratio:.025;}.dev .value-badge{position:relative;z-index:2;box-sizing:border-box;width:max-content;min-width:calc(var(--dev-size,var(--icon-size,2.5cqw)) * .7875);height:calc(var(--dev-size,var(--icon-size,2.5cqw)) * .7875);display:flex;align-items:center;justify-content:center;overflow:visible;background:var(--device-core-bg);border:0;border-radius:calc(var(--dev-size,var(--icon-size,2.5cqw)) * 0.39375);padding:0 calc(var(--dev-size,var(--icon-size,2.5cqw)) * 0.14);font-size:calc(var(--dev-size,var(--icon-size,2.5cqw)) * var(--value-font-scale,.45));font-weight:600;line-height:1;color:var(--device-core-fg);white-space:nowrap;pointer-events:none;}.dev .value-badge.unavailable,.dev .value-badge.missing{opacity:0.66;}.dev .lqi{position:absolute;top:calc(50% + var(--device-shell-size) / 2 + var(--dev-size) * .05);left:50%;transform:translateX(-50%);margin-top:calc(var(--dev-size,var(--icon-size,2.5cqw)) * 0.05);font-size:calc(var(--dev-size,var(--icon-size,2.5cqw)) * 0.38);font-weight:600;line-height:1;text-shadow:0 0 3px rgba(0,0,0,0.9),0 0 2px rgba(0,0,0,0.9);white-space:nowrap;pointer-events:none;}.dev .lqi.below-value-badge{margin-top:calc(var(--dev-size,var(--icon-size,2.5cqw)) * 0.8875);}.temprange{display:inline-flex;align-items:center;gap:var(--sp-3);margin-left:auto;color:var(--hp-muted);font-size:var(--fs-s);}.vacwarn{position:absolute;top:-12%;right:-12%;width:calc(var(--device-base-size,2.25cqw) * 0.42);height:calc(var(--device-base-size,2.25cqw) * 0.42);border-radius:50%;display:flex;align-items:center;justify-content:center;background:light-dark(#fff,#252525);border:1px solid #E5A100;color:#E5A100;z-index:7;pointer-events:none;}.vacwarn ha-icon{--mdc-icon-size:calc(var(--device-base-size,2.25cqw) * 0.32);color:inherit;}.vacpuck{position:absolute;--puck-size:calc(var(--device-base-size,2.25cqw) * 0.8);width:var(--puck-size);height:var(--puck-size);border-radius:50%;transform:translate(-50%,-50%);--vac-core-bg:light-dark(#fff,#252525);--vac-core-fg:light-dark(#252525,#fff);background:var(--vac-core-bg);border:1px solid #BCBCBC;box-shadow:0 1px 2px rgb(37 40 45 / 12%),0 4px 8px -1.07px rgb(37 40 45 / 18%);color:var(--vac-core-fg);display:flex;align-items:center;justify-content:center;cursor:pointer;z-index:6;transition:left 1.2s linear,top 1.2s linear;animation:vacpulse 2.2s ease-out infinite;}.vacpuck.theme-light{--vac-core-bg:#fff;--vac-core-fg:#252525;}.vacpuck.theme-dark{--vac-core-bg:#252525;--vac-core-fg:#fff;}.vacpuck.jump{transition:none;}.vacpuck.stale{opacity:0.45;animation:none;}.vacpuck ha-icon{--mdc-icon-size:calc(var(--puck-size) * 0.68);color:var(--vac-core-fg);display:flex;align-items:center;justify-content:center;line-height:0;width:var(--mdc-icon-size);height:var(--mdc-icon-size);}@keyframes vacpulse{0%{box-shadow:0 0 0 0 color-mix(in srgb,var(--hp-accent) 45%,transparent);}70%{box-shadow:0 0 0 12px transparent;}100%{box-shadow:0 0 0 0 transparent;}}@media (prefers-reduced-motion:reduce){.vacpuck{animation:none;}}.vactrail{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:5;overflow:visible;}.vactrail polyline,.vactrail path{fill:none;stroke-linejoin:round;stroke-linecap:round;vector-effect:non-scaling-stroke;}.vactrail g.prev{opacity:0.4;}.vactrail .case{stroke:rgba(0,0,0,0.4);stroke-width:2.25;}.vactrail .core{stroke:rgba(255,255,255,0.82);stroke-width:0.9;}.devicepreview-empty{min-height:82px;margin:4px 0 14px;padding:var(--sp-4);display:flex;align-items:center;justify-content:center;gap:var(--sp-3);border:1px dashed var(--hp-line);border-radius:var(--rad-m);color:var(--hp-muted);text-align:center;}`,o`.hdr{position:sticky;top:var(--header-height,56px);z-index:20;background:var(--card-background-color,var(--hp-bg));border-radius:var(--ha-card-border-radius,12px) var(--ha-card-border-radius,12px) 0 0;}.tabs{display:flex;gap:var(--sp-2);background:rgba(127,127,127,0.12);padding:var(--sp-2);border-radius:var(--rad-l);flex-wrap:wrap;}.tab{border:0;background:transparent;color:var(--hp-muted);display:inline-flex;align-items:center;padding:var(--sp-3) var(--sp-5);border-radius:var(--rad-m);font-size:var(--fs-m);font-weight:600;cursor:pointer;transition:0.15s;font-family:inherit;}:host([data-pointer-hover]) .tab:hover{color:var(--hp-txt);}.tab.active{background:var(--hp-accent);color:var(--text-primary-color,#fff);}.farhint{position:absolute;left:50%;transform:translateX(-50%);bottom:var(--sp-4);z-index:12;display:flex;align-items:center;gap:var(--sp-2);max-width:calc(100% - var(--sp-8));background:var(--card-background-color,var(--hp-bg));opacity:0.94;color:var(--hp-txt);border:1px solid var(--divider-color,#33404d);border-radius:var(--rad-m);padding:var(--sp-1) var(--sp-3);font-size:var(--fs-s);}.farhint ha-icon{--mdc-icon-size:18px;color:var(--hp-warn,#e2a03f);flex:none;}.farhint span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}.dropbtn{display:flex;align-items:center;gap:var(--sp-4);width:100%;text-align:left;border:1px solid var(--hp-muted);border-radius:var(--rad-m);background:transparent;color:var(--hp-txt);padding:var(--sp-4) 10px;cursor:pointer;font-family:inherit;font-size:var(--fs-m);margin-top:var(--sp-3);}.dropbtn .ref{color:var(--hp-muted);font-size:var(--fs-s);margin-left:auto;}.dropbtn ha-icon{--mdc-icon-size:18px;margin-left:var(--sp-2);}.dropbtn.open{border-color:var(--hp-accent);}.droppanel{border:1px solid var(--hp-accent);border-top:none;border-radius:0 0 var(--rad-m) var(--rad-m);padding:var(--sp-3);margin-top:-4px;}.hdr.kioskhide{display:none;}.decorbar .dcolor{width:30px;height:26px;padding:0;border:none;background:none;cursor:pointer;}.decorbar .dwidth{font-family:inherit;font-size:var(--fs-s);border-radius:var(--rad-s);background:var(--hp-bg2,transparent);color:var(--hp-txt);border:1px solid var(--hp-muted);padding:var(--sp-2) var(--sp-3);}.decorbar .bdhint{font-size:var(--fs-s);color:var(--hp-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}.decorbar .dfill{display:inline-flex;align-items:center;gap:var(--sp-2);font-size:var(--fs-s);cursor:pointer;}.decorbar .dfill input[type="checkbox"]{width:16px;height:16px;flex:none;margin:0;padding:0;}.decorbar hp-color-opacity{flex:0 0 auto;}.modes{display:inline-flex;gap:var(--sp-1);background:rgba(127,127,127,0.12);border-radius:var(--rad-l);padding:var(--sp-2);}.modetab{display:inline-flex;align-items:center;gap:var(--sp-3);border:0;background:transparent;color:var(--hp-muted);padding:var(--sp-3) 10px;border-radius:var(--rad-m);font-size:var(--fs-m);font-weight:600;cursor:pointer;font-family:inherit;transition:background-color 0.14s ease,color 0.14s ease,transform 0.14s ease;}.modetab:active{transform:scale(0.97);}.modetab ha-icon{--mdc-icon-size:15px;}.tab[data-reorderable]{cursor:grab;}.tab.dragging{cursor:grabbing;opacity:0.55;}.tab.drop-before{box-shadow:inset 2px 0 0 0 var(--primary-color,#03a9f4);}.tab.drop-after{box-shadow:inset -2px 0 0 0 var(--primary-color,#03a9f4);}.modetab .closex{--mdc-icon-size:13px;box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;min-width:24px;min-height:24px;margin:-5.5px -5.5px -5.5px -3.5px;opacity:0.75;cursor:pointer;border-radius:var(--rad-s);}:host([data-pointer-hover]) .modetab .closex:hover{opacity:1;}.editbar .barclose{box-sizing:border-box;width:40px;height:40px;padding:0;margin:0;min-width:40px;min-height:40px;justify-content:center;gap:0;line-height:0;}.editbar .barclose ha-icon{flex:none;margin:0;}.modetab.active{background:var(--hp-accent);color:var(--text-primary-color,#fff);}@media (max-width:720px){.modetab .ml{display:none;}}.editbar{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:stretch;border-bottom:1px solid var(--hp-line);font-size:var(--fs-m);}.editbar-tools{display:flex;align-items:center;gap:10px;padding:var(--sp-4) var(--sp-5);flex-wrap:wrap;min-width:0;outline:none;}.editbar-end{display:flex;align-items:center;padding:var(--sp-4) var(--sp-5);border-inline-start:1px solid var(--hp-line);background:var(--card-background-color,var(--hp-bg));position:relative;z-index:2;}.tab .tabedit{--mdc-icon-size:13px;display:inline-flex;align-items:center;margin-left:var(--sp-3);opacity:0.4;}:host([data-pointer-hover]) .tab:hover .tabedit{opacity:0.9;}.tab.tabadd{padding:var(--sp-3) var(--sp-4);}.tab.tabadd ha-icon{--mdc-icon-size:15px;}.rhint{font-size:var(--fs-s);color:var(--hp-muted);margin-bottom:var(--sp-3);}.togglehint{overflow-wrap:anywhere;}.togglehint>div + div{margin-top:var(--sp-1);}.editorchrome{display:block;height:0;opacity:0;visibility:hidden;overflow:hidden;}.editorchrome:not(.open){pointer-events:none;}.editorchrome.open{height:auto;opacity:1;visibility:visible;overflow:visible;}.editorchrome.transitioning{overflow:hidden;will-change:height;pointer-events:none;}.editorchrome.transitioning .barclose{pointer-events:auto;}.editorchrome-inner{min-height:0;transform-origin:top center;}.editorchrome.transitioning .editorchrome-inner{will-change:opacity;}@media (prefers-reduced-motion:reduce){.modetab{transition:none;}}.editbar .warn{color:#ffc14d;}.editbar .sname{font-weight:600;}.editbar input{width:74px;background:transparent;border:1px solid var(--hp-line);color:var(--hp-txt);border-radius:var(--rad-s);padding:var(--sp-3) var(--sp-4);font-size:var(--fs-m);}.editbar label,.editbar .hint{color:var(--hp-muted);font-size:var(--fs-s);}.editbar .drawwall{display:inline-flex;align-items:center;gap:var(--sp-3);white-space:nowrap;}.editbar .wallsgroup{display:inline-flex;align-items:center;gap:10px;white-space:nowrap;}.editbar .drawwall input{width:4.2em;}.editbar .drawwall .opl{color:var(--hp-muted);font-size:var(--fs-s);}.menuwrap{position:fixed;inset:0;z-index:80;}.menu{position:fixed;background:var(--hp-bg);border:1px solid var(--hp-accent);border-radius:var(--rad-l);box-shadow:var(--shadow-2);min-width:210px;max-width:300px;overflow:hidden;transform:translate(0,8px);}.menu .hd{padding:var(--sp-4) var(--sp-5);font-weight:600;font-size:var(--fs-m);border-bottom:1px solid var(--hp-line);display:flex;align-items:center;gap:var(--sp-3);}.menu .hd ha-icon,.menu .it.all ha-icon{color:var(--hp-accent);--mdc-icon-size:16px;}.menu .it{padding:var(--sp-4) var(--sp-5);font-size:var(--fs-m);cursor:pointer;display:flex;align-items:center;gap:var(--sp-4);}.menu .it ha-icon{--mdc-icon-size:16px;color:var(--hp-muted);}:host([data-pointer-hover]) .menu .it:hover{background:rgba(127,127,127,0.15);}.menu .it.all{color:var(--hp-accent);font-weight:600;}.tip{position:fixed;pointer-events:none;background:var(--hp-bg);border:1px solid var(--hp-accent);color:var(--hp-txt);padding:var(--sp-3) 10px;border-radius:var(--rad-m);font-size:var(--fs-m);box-shadow:var(--shadow-2);z-index:60;max-width:260px;}.tip .m{color:var(--hp-muted);font-size:var(--fs-s);display:block;}`,o`.head{display:flex;align-items:center;gap:10px;padding:10px var(--sp-5);border-bottom:1px solid var(--hp-line);flex-wrap:wrap;}.title{font-size:var(--fs-l);font-weight:600;display:flex;align-items:center;gap:var(--sp-3);white-space:nowrap;}.title ha-icon{color:var(--hp-accent);--mdc-icon-size:18px;}@media (max-width:1100px){.head .count{display:none;}}@media (max-width:620px){.head{gap:var(--sp-3);padding:var(--sp-4) 10px;}.head .title{font-size:var(--fs-m);}}.count{font-size:var(--fs-s);color:var(--hp-muted);}.btn{display:inline-flex;align-items:center;gap:var(--sp-3);border:1px solid var(--hp-line);background:transparent;color:var(--hp-txt);padding:var(--sp-3) 10px;border-radius:var(--rad-m);cursor:pointer;transition:0.15s;font-family:inherit;font-size:var(--fs-m);}.btn ha-icon{--mdc-icon-size:17px;}:host([data-pointer-hover]) .btn:hover{border-color:var(--hp-accent);}.btn.on{background:var(--hp-accent);color:var(--text-primary-color,#fff);border-color:var(--hp-accent);}.btn.ghost{border:none;}.btn[disabled]{opacity:0.5;pointer-events:none;}.sunrow{display:flex;align-items:center;gap:var(--sp-5);margin:var(--sp-3) 0;}.suncol{flex:1;display:flex;flex-direction:column;gap:var(--sp-3);min-width:0;}.recoveryoverlay{position:absolute;inset:0;z-index:75;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:var(--sp-4);padding:var(--sp-6);box-sizing:border-box;background:linear-gradient(var(--ha-card-background,var(--card-background-color,#111)),var(--ha-card-background,var(--card-background-color,#111))),#111;color:var(--primary-text-color,#fff);text-align:center;pointer-events:auto;transition:opacity 0.15s ease;}.recoveryoverlay.phase-entering,.recoveryoverlay.phase-leaving{opacity:0;}.recoveryoverlay.phase-fading-in,.recoveryoverlay.phase-opaque{opacity:1;}.recoveryoverlay ha-icon{--mdc-icon-size:44px;color:var(--hp-accent);}.editorloading{position:absolute;z-index:74;left:50%;top:50%;display:flex;align-items:center;gap:var(--sp-3);padding:var(--sp-3) var(--sp-5);border:1px solid color-mix(in srgb,var(--hp-accent) 45%,transparent);border-radius:999px;background:color-mix(in srgb,var(--ha-card-background,var(--card-background-color,#111)) 92%,transparent);color:var(--primary-text-color);box-shadow:0 6px 22px rgb(0 0 0 / 18%);transform:translate(-50%,-50%);pointer-events:none;animation:editor-loading-in 0.15s ease both;}.editorloading ha-icon{--mdc-icon-size:22px;color:var(--hp-accent);animation:editor-loading-spin 0.9s linear infinite;}@keyframes editor-loading-in{from{opacity:0;transform:translate(-50%,calc(-50% + 4px));}to{opacity:1;transform:translate(-50%,-50%);}}@keyframes editor-loading-spin{to{transform:rotate(360deg);}}@media (prefers-reduced-motion:reduce){.recoveryoverlay,.editorloading,.editorloading ha-icon{transition:none;animation:none;}}.oplock{--oplock-size:calc(var(--icon-size,2.5cqw) * 0.62);--oplock-core-size:calc(var(--oplock-size) / 1.26875);--oplock-stroke-ratio:0.01875;--oplock-stroke-width:max(1px,calc(var(--oplock-core-size) * var(--oplock-stroke-ratio)));--oplock-core-bg:light-dark(#fff,#252525);--oplock-core-fg:light-dark(#252525,#fff);--oplock-shell-stroke:light-dark(#BCBCBC,rgb(37 37 37 / 75%));--oplock-shell-shadow:0 calc(var(--oplock-core-size) * .025) calc(var(--oplock-core-size) * .05) rgb(37 40 45 / 12%),0 calc(var(--oplock-core-size) * .1) calc(var(--oplock-core-size) * .175) calc(var(--oplock-core-size) * -.025) rgb(37 40 45 / 18%);--oplock-core-shadow:0 0 0 0 transparent;pointer-events:none;position:absolute;transform:translate(-50%,-50%);width:var(--oplock-size);height:var(--oplock-size);display:grid;place-items:center;border:0;background:transparent;z-index:1;}.oplock.theme-light{--oplock-core-bg:#fff;--oplock-core-fg:#252525;--oplock-shell-stroke:#BCBCBC;}.oplock.theme-dark{--oplock-core-bg:#252525;--oplock-core-fg:#fff;--oplock-shell-stroke:rgb(37 37 37 / 75%);--oplock-core-shadow:inset 0 calc(var(--oplock-core-size) * .0125) calc(var(--oplock-core-size) * .0125) rgb(255 255 255 / 70%);}.oplock-shell{box-sizing:border-box;width:100%;height:100%;border:var(--oplock-stroke-width) solid var(--oplock-shell-stroke);border-radius:50%;background:transparent;box-shadow:var(--oplock-shell-shadow);display:grid;place-items:center;pointer-events:none;backdrop-filter:none;}.oplock-core{width:var(--oplock-core-size);height:var(--oplock-core-size);border-radius:50%;background:var(--oplock-core-bg);color:var(--oplock-core-fg);box-shadow:var(--oplock-core-shadow);display:grid;place-items:center;pointer-events:none;}.oplock ha-icon{--mdc-icon-size:calc(var(--oplock-core-size) * 0.55);display:flex;line-height:0;}.oplock.locked{--oplock-core-bg:#66D17A;--oplock-core-fg:light-dark(#fff,#252525);--oplock-shell-stroke:#66D17A;}.oplock.theme-light.locked{--oplock-core-fg:#fff;}.oplock.theme-dark.locked{--oplock-core-fg:#252525;--oplock-stroke-ratio:.025;}.oplock.unlocked{--oplock-core-bg:#F0410C;--oplock-core-fg:light-dark(#fff,#252525);--oplock-shell-stroke:#F0410C;}.oplock.theme-light.unlocked{--oplock-core-fg:#fff;}.oplock.theme-dark.unlocked{--oplock-core-fg:#252525;--oplock-stroke-ratio:.025;}.oplock.unknown{--oplock-core-fg:var(--hp-muted);}.btn.lockact{width:100%;justify-content:center;display:flex;align-items:center;gap:var(--sp-3);margin-top:var(--sp-4);}.btn.lockact.warn{color:var(--error-color,#d33);border-color:var(--error-color,#d33);}.oprow{display:flex;align-items:center;gap:var(--sp-4);padding:var(--sp-3) 0;}.oprow b{margin-left:auto;}.oprow.ok b{color:#66d17a;}.oprow.warn b{color:var(--hp-open);}.bindharow{display:flex;align-items:center;gap:var(--sp-5);flex-wrap:wrap;}.bindharow .entcheck{opacity:0.9;}.ctrlchips{display:flex;flex-wrap:wrap;gap:var(--sp-3);margin:var(--sp-2) 0;}.ctrlchip{display:inline-flex;align-items:center;gap:var(--sp-2);background:var(--hp-accent);color:var(--text-primary-color,#fff);border-radius:var(--rad-l);padding:var(--sp-2) var(--sp-4);font-size:var(--fs-s);}.ctrlchip ha-icon{--mdc-icon-size:14px;cursor:pointer;}.ctrllist{display:flex;flex-direction:column;gap:var(--sp-1);margin-top:var(--sp-2);}.ctrlopt{display:flex;align-items:center;gap:var(--sp-4);text-align:left;border:0;background:transparent;color:var(--hp-txt);padding:var(--sp-3) var(--sp-4);border-radius:var(--rad-s);cursor:pointer;font-family:inherit;font-size:var(--fs-m);}:host([data-pointer-hover]) .ctrlopt:hover{background:var(--secondary-background-color,rgba(128,128,128,0.15));}.ctrlopt .sub{color:var(--hp-muted);font-size:var(--fs-s);margin-left:auto;}.ctrlopt ha-icon{--mdc-icon-size:16px;}.ctrlstates{display:flex;flex-direction:column;gap:var(--sp-2);}.ctrlstate{display:inline-flex;align-items:center;gap:var(--sp-3);color:var(--hp-muted);}.ctrlstate.on{color:var(--hp-txt);}.ctrlstate ha-icon{--mdc-icon-size:15px;}.cardpreview{display:flex;flex-direction:column;align-items:center;gap:var(--sp-2);margin:var(--sp-4) 0 var(--sp-1);padding:10px;border:1px dashed var(--hp-muted);border-radius:var(--rad-m);}.cardpreview .cpname{font-weight:700;letter-spacing:0.04em;}.cardpreview .cpmeta{display:inline-flex;align-items:center;gap:0.3em;font-weight:600;opacity:0.85;}.cardpreview .cpmeta ha-icon{--mdc-icon-size:1.05em;}.iconauto{display:flex;align-items:center;gap:var(--sp-3);font-size:var(--fs-s);margin:var(--sp-2) 0 0;}.iconauto ha-icon{--mdc-icon-size:18px;}.iconauto span{flex:1;}.iconauto .btn{min-height:32px;padding:0 var(--sp-3);}hp-dialog .dfill{display:inline-flex;align-items:center;gap:var(--sp-3);cursor:pointer;}.wallthick-dlg{position:absolute;z-index:40;min-width:200px;transform:translate(-50%,8px);padding:10px 12px;border-radius:10px;background:var(--card-background-color,#fff);box-shadow:0 8px 28px rgba(0,0,0,.22);display:flex;flex-direction:column;gap:8px;pointer-events:auto;}.wallthick-dlg .row{display:flex;align-items:center;gap:8px;}.wallthick-dlg input[type="number"]{width:5.5em;padding:4px 6px;border:1px solid var(--divider-color,#ccc);border-radius:6px;background:var(--input-fill,transparent);color:var(--primary-text-color);}.areasel,.namein{background:var(--hp-bg);border:1px solid var(--hp-line);color:var(--hp-txt);border-radius:var(--rad-s);padding:var(--sp-3) var(--sp-4);font-size:var(--fs-m);font-family:inherit;}.namein{width:130px;}.habindingbanner{display:flex;align-items:center;gap:var(--sp-3);padding:var(--sp-3) var(--sp-4);margin-bottom:var(--sp-4);border:1px solid var(--warning-color,#ff9800);border-radius:var(--rad-m);background:color-mix(in srgb,var(--warning-color,#ff9800) 12%,transparent);color:var(--primary-text-color,#f1f3f6);}.habindingbanner>span{flex:1;min-width:0;}.habindingbanner>ha-icon{color:var(--warning-color,#ff9800);flex:0 0 auto;}.habindingbanner.limited{border-color:var(--secondary-text-color,#9aa0aa);background:color-mix(in srgb,var(--secondary-text-color,#9aa0aa) 10%,transparent);}.habindingbanner.limited>ha-icon{color:var(--secondary-text-color,#9aa0aa);}.srcrow{display:flex;align-items:center;gap:var(--sp-4);font-size:var(--fs-m);cursor:pointer;padding:var(--sp-1) 0;}.dispsection{margin-top:var(--sp-5) !important;padding-top:var(--sp-4);border-top:1px solid var(--hp-line);font-weight:600;color:var(--hp-txt) !important;}.colorrow{display:flex;align-items:center;gap:var(--sp-4);}.roomtemprange{display:grid;gap:8px;min-width:0;}.roomtemprange-head{display:flex;flex-wrap:wrap;align-items:center;gap:6px;}.roomtemprange-fields{display:flex;flex-wrap:wrap;align-items:center;gap:8px;min-width:0;}.roomtemprange-fields input{flex:0 1 104px;min-width:72px;}.roomtemprange-fields input[aria-invalid='true']{border-color:var(--error-color,#db4437);}.gsrow>hp-color-opacity{min-width:min(100%,210px);justify-content:space-between;}.ripple-colorrow>hp-color-opacity{width:100%;justify-content:space-between;}.ripple-sizerow>.opl{min-width:0;}.colorrow input[type='range']{flex:1;}.colorrow .tempin{width:70px;flex:none;}hp-dialog .body .temprange .tempin{width:56px;flex:none;padding:var(--sp-2) var(--sp-3);}hp-dialog .body .colorrow .tempin{width:72px;flex:none;}.srcrow{flex-wrap:nowrap;}.srcrow ha-switch{flex:none;}.colorrow ha-slider{flex:1;min-width:0;}.srcrow>span:first-of-type{white-space:nowrap;}.colorrow .opl{color:var(--hp-muted);font-size:var(--fs-s);}.colorrow .opv{font-size:var(--fs-s);min-width:34px;text-align:right;}.markerlightgroup{min-width:0;margin:var(--sp-5) 0 0;padding:var(--sp-4);border:1px solid var(--hp-line);border-radius:var(--rad-m);}.markerlightgroup legend{display:flex;align-items:center;flex-wrap:wrap;gap:var(--sp-1);padding:0 var(--sp-2);color:var(--hp-txt);font-weight:600;}.markerlightgroup legend>span{min-width:0;overflow-wrap:anywhere;}.markerlightgroup[disabled]>:not(legend){opacity:.62;}.radargroup{display:grid;gap:var(--sp-2);}.radargroup>p{margin:0;}.radargroup>label:not(.srcrow){margin-top:var(--sp-2);}.radarcoordinates{align-items:flex-end;flex-wrap:wrap;}.radarcoordinates>label{display:grid;flex:1 1 92px;gap:var(--sp-1);min-width:0;margin:0;}hp-dialog .body .radarcoordinates .tempin{box-sizing:border-box;width:100%;}.radaradditional{margin-top:var(--sp-5);}.radaradditional summary{cursor:pointer;font-weight:600;}.radaradditional .btn{margin-top:var(--sp-3);}.radarinspection{display:grid;gap:6px;padding:10px 12px;border-radius:10px;background:color-mix(in srgb,var(--primary-color) 7%,transparent);}.radarinspection code{overflow-wrap:anywhere;font-size:12px;}.radarsetup{display:grid;gap:10px;margin-top:10px;padding:12px;border:1px solid var(--hp-accent);border-radius:var(--rad-m);background:color-mix(in srgb,var(--secondary-background-color) 88%,transparent);}.radarsetup-head{display:flex;align-items:center;gap:8px;}.radarsetup-head strong{flex:1;}.radarsetup>svg{width:min(100%,460px);aspect-ratio:1;justify-self:center;border-radius:var(--rad-m);background:var(--primary-background-color);touch-action:none;cursor:crosshair;}.radarsetup .room{fill:color-mix(in srgb,var(--hp-accent) 8%,transparent);stroke:var(--divider-color);stroke-width:3;vector-effect:non-scaling-stroke;}.radarsetup .heading{stroke:var(--hp-accent);stroke-width:4;vector-effect:non-scaling-stroke;}.radarsetup .trail{fill:none;stroke:var(--success-color,#43a047);stroke-width:3;stroke-linecap:round;stroke-linejoin:round;vector-effect:non-scaling-stroke;opacity:.55;}.radarsetup g circle{fill:var(--hp-bg);stroke:var(--hp-accent);stroke-width:3;vector-effect:non-scaling-stroke;}.radarsetup g.pending circle{stroke-dasharray:5 4;}.radarsetup g text{fill:var(--hp-txt);font-size:22px;font-weight:700;text-anchor:middle;dominant-baseline:middle;pointer-events:none;}.markerhelpfield{margin-top:var(--sp-4);}.markerhelplabel{display:flex;align-items:center;flex-wrap:wrap;gap:var(--sp-1);margin-bottom:var(--sp-1);}.markerhelplabel>label{min-width:0;overflow-wrap:anywhere;}.helpfieldlabel{display:flex;align-items:center;flex-wrap:wrap;gap:var(--sp-1);min-width:0;margin-top:var(--sp-3);color:var(--hp-muted);font-size:var(--fs-s);}.helpfieldlabel.compact{margin-top:0;}hp-dialog .body .helpfieldlabel>label{min-width:0;margin-top:0;overflow-wrap:anywhere;}.help-inline-label{display:inline-flex;align-items:center;flex-wrap:wrap;gap:var(--sp-1);}hp-dialog .body .help-inline-label>label{min-width:0;margin-top:0;overflow-wrap:anywhere;}.markerradios{display:grid;gap:var(--sp-1);min-width:0;}.markerlightgroup .srcrow>span:first-of-type{min-width:0;white-space:normal;overflow-wrap:anywhere;}.markerglowvalue{margin:var(--sp-3) 0;flex-wrap:wrap;}.markerglowvalue hp-color-opacity{flex:none;}.markerlightdisabled{display:flex;align-items:center;gap:var(--sp-2);margin-top:var(--sp-2) !important;}.markerlightdisabled ha-icon{--mdc-icon-size:18px;flex:none;}.markerbadgetechnical{min-width:0;margin:var(--sp-1) 0 var(--sp-2) !important;overflow-wrap:anywhere;}.markerbadgetechnical code{white-space:normal;}.planrow{display:flex;align-items:center;gap:10px;}.savedplans{display:flex;flex-direction:column;gap:var(--sp-3);max-height:240px;overflow:auto;margin:var(--sp-3) 0 var(--sp-1);padding:var(--sp-3);border:1px solid var(--hp-line);border-radius:var(--rad-m);background:var(--hp-bg2,rgba(255,255,255,0.03));flex:0 0 auto;min-height:2.6em;}.savedplan{display:flex;align-items:center;gap:10px;}.savedplan.cur{outline:1px solid var(--hp-accent);border-radius:var(--rad-s);}.savedplan img{width:56px;height:40px;object-fit:contain;border:1px solid var(--hp-line);border-radius:var(--rad-s);background:#fff;flex:none;}.savedmeta{display:flex;flex-direction:column;min-width:0;flex:1;}.savedmeta b{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.savedmeta .muted{font-size:var(--fs-s);}.savedplan .btn.danger ha-icon{color:#f25a4a;}.savedplan .btn[disabled]{opacity:0.4;pointer-events:none;}.planprev{max-width:120px;max-height:70px;border:1px solid var(--hp-line);border-radius:var(--rad-s);background:#fff;}.planname{font-size:var(--fs-m);max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.planname.muted{color:var(--hp-muted);}.filebtn{cursor:pointer;}.fileupload{display:inline-flex;min-width:0;}.fileupload>input{display:none;}.btn.danger{border-color:#b3402a;color:#ff7a5c;}hp-dialog .row .spacer{flex:1;}hp-dialog .body{max-height:66vh;overflow-y:auto;}hp-confirm{display:contents;}hp-dialog .danger-confirm-body{display:flex;flex-direction:column;gap:var(--sp-4);}hp-dialog .danger-confirm-body p{margin:0;line-height:1.45;}hp-dialog .danger-confirm-object{overflow-wrap:anywhere;font-size:var(--fs-l);line-height:1.3;}.descin{width:100%;box-sizing:border-box;background:var(--hp-bg);border:1px solid var(--hp-line);color:var(--hp-txt);border-radius:var(--rad-s);padding:var(--sp-3) var(--sp-4);font-size:var(--fs-m);font-family:inherit;resize:vertical;min-height:92px;flex-shrink:0;line-height:1.35;}.bindsel{display:flex;flex-direction:column;gap:var(--sp-3);border:1px solid var(--hp-line);border-radius:var(--rad-m);padding:var(--sp-4);}.bindsel .opt{display:flex;align-items:center;gap:var(--sp-3);border:1px solid var(--hp-line);background:transparent;color:var(--hp-txt);border-radius:var(--rad-s);padding:var(--sp-3) var(--sp-4);cursor:pointer;font-size:var(--fs-m);font-family:inherit;}.bindsel .opt.on{background:var(--hp-accent);color:var(--text-primary-color,#fff);border-color:var(--hp-accent);}.curbind{display:flex;align-items:center;gap:var(--sp-3);font-size:var(--fs-m);color:var(--hp-txt);flex-wrap:wrap;}.curbind .ref{color:var(--hp-muted);font-size:var(--fs-s);}.vacbox .vacbtns{display:flex;gap:var(--sp-4);margin:var(--sp-3) 0;flex-wrap:wrap;}.vacdiag{display:grid;gap:4px;margin-bottom:var(--sp-3);}.vacdiag>div{display:flex;justify-content:space-between;gap:var(--sp-5);}.vacdiag>div>span{color:var(--secondary-text-color);}.vacdiag>div>b{text-align:right;overflow-wrap:anywhere;}.vacroute-missing-group{margin-top:var(--sp-4);padding-top:var(--sp-4);border-top:1px solid var(--hp-line);}.vacroute-group-title{margin:0 0 var(--sp-3);color:var(--secondary-text-color);font-size:var(--fs-m);font-weight:600;}.vacroute-missing-group .vacroute-list{margin-top:0;}.vacpicker{margin:var(--sp-3) 0;}.vacsource-warning{display:grid;gap:8px;}.vacsource-warning .btn{justify-self:start;}.vacpicker>summary{display:inline-flex;width:auto;list-style:none;cursor:pointer;}.vacpicker>summary::-webkit-details-marker{display:none;}.vacsource-list{display:grid;gap:6px;margin-top:8px;}.vacsource-list details{padding:6px 0 0;}.vacsource-list details>summary{cursor:pointer;font-weight:600;}.vacsource{display:flex;align-items:center;justify-content:space-between;gap:12px;width:100%;min-width:0;padding:9px 10px;border:1px solid var(--divider-color);border-radius:10px;color:var(--primary-text-color);background:var(--secondary-background-color);text-align:left;cursor:pointer;}.vacsource.on{border-color:var(--accent-color);box-shadow:inset 3px 0 var(--accent-color);}.vacsource>span:first-child{min-width:0;display:grid;gap:2px;}.vacsource small{color:var(--secondary-text-color);overflow-wrap:anywhere;}.vacsource-meta{color:var(--secondary-text-color);text-align:right;font-size:0.82em;}.vacxcme pre{margin:8px 0 0;white-space:pre-wrap;user-select:text;}.vacfit{position:absolute;inset:0;width:100%;height:100%;z-index:12;overflow:visible;touch-action:none;cursor:grab;pointer-events:auto;}.vacfit:active{cursor:grabbing;}.vacfit polygon{fill:color-mix(in srgb,var(--hp-accent) 16%,transparent);stroke:var(--hp-accent);stroke-width:2;vector-effect:non-scaling-stroke;stroke-dasharray:6 4;}.vacfit text{fill:var(--hp-accent);font-size:26px;text-anchor:middle;dominant-baseline:middle;pointer-events:none;user-select:none;}.furnpalette{display:flex;flex-direction:column;max-height:38vh;border-top:1px solid var(--hp-border,rgba(255,255,255,0.12));background:var(--card-background-color,var(--hp-bg));font-size:0.85em;}.furnhd{display:flex;align-items:center;gap:6px;padding:4px 8px;font-weight:600;opacity:0.9;}.furnhd .spacer{flex:1;}.furnbody{overflow:auto;padding:0 8px 6px;}.furngroup{margin:6px 0 3px;font-size:0.85em;text-transform:uppercase;letter-spacing:0.04em;opacity:0.6;}.furnrow{display:flex;flex-wrap:wrap;gap:4px;}.furnback{min-height:34px;gap:5px;margin:2px 0 4px;}.furnitem{display:flex;flex-direction:column;align-items:center;gap:2px;width:74px;padding:4px 2px;border:1px solid transparent;border-radius:8px;background:rgba(127,127,127,0.08);color:inherit;font:inherit;font-size:0.8em;line-height:1.15;text-align:center;cursor:pointer;}:host([data-pointer-hover]) .furnitem:hover{background:rgba(127,127,127,0.18);}.furnitem.on{border-color:var(--hp-accent);background:rgba(38,166,154,0.18);}.furnprev{width:40px;height:40px;color:var(--primary-text-color,currentColor);}.furncategory{width:92px;min-height:76px;}.furncatprev{width:48px;height:48px;}.furnvariants .furnitem{min-height:74px;}.furnsize{display:flex;align-items:center;flex-wrap:wrap;gap:6px;padding:6px 8px;border-top:1px solid var(--hp-border,rgba(255,255,255,0.12));}.furnsize label{display:flex;align-items:baseline;gap:3px;opacity:0.8;}.furnsize .furnunit{opacity:0.6;font-size:0.85em;}.furnsize input{width:5.5em;padding:3px 5px;}.furnhint{opacity:0.6;}.imageupload{display:inline-flex;gap:6px;margin:4px 0 8px;cursor:pointer;}.imageupload.disabled{opacity:0.55;pointer-events:none;}.imageupload input{display:none;}.imageassets{align-items:stretch;}.imageempty{padding:12px 6px;}.imageasset{position:relative;}.imageasset .furnitem{width:104px;min-height:92px;}.imageasset img{width:64px;height:54px;object-fit:contain;border-radius:4px;background:repeating-conic-gradient(#ddd 0 25%,#fff 0 50%) 50% / 12px 12px;}.imageasset .furnitem span{max-width:96px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.imageasset .furnitem small{opacity:0.65;font-size:0.72em;}.imageassetdelete{position:absolute;top:0;right:0;min-width:30px;width:30px;min-height:30px;padding:3px;}.imagepropertypreview{display:flex;align-items:center;gap:10px;min-width:0;}.imagepropertypreview img{width:72px;height:54px;object-fit:contain;border-radius:4px;background:repeating-conic-gradient(#ddd 0 25%,#fff 0 50%) 50% / 12px 12px;}.imagepropertypreview span{overflow-wrap:anywhere;}.vacfitdot{fill:var(--hp-accent);pointer-events:none;}.vacfithandle{fill:transparent;stroke:none;cursor:nwse-resize;}.vacfitknob{fill:var(--hp-bg);stroke:var(--hp-accent);stroke-width:2;vector-effect:non-scaling-stroke;pointer-events:none;}.vaccalbar{position:fixed;left:50%;bottom:24px;transform:translateX(-50%);display:flex;gap:var(--sp-5);align-items:center;background:var(--hp-bg);color:var(--hp-txt);border:1px solid var(--hp-accent);border-radius:var(--rad-l);padding:10px var(--sp-5);z-index:60;box-shadow:var(--shadow-2);}.candlist{max-height:160px;overflow-y:auto;border-top:1px solid var(--hp-line);flex:0 0 auto;min-height:2.6em;}.cand{display:flex;justify-content:space-between;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);cursor:pointer;border-radius:var(--rad-s);font-size:var(--fs-m);}:host([data-pointer-hover]) .cand:hover{background:rgba(127,127,127,0.15);}.cand.sel{background:var(--hp-accent);color:var(--text-primary-color,#fff);}.cand .cs{color:var(--hp-muted);font-size:var(--fs-s);white-space:nowrap;}.opening-entity-candidate{width:100%;border:0;background:transparent;color:inherit;font:inherit;text-align:left;}.opening-entity-candidate.sel{background:var(--hp-accent);color:var(--text-primary-color,#fff);}.opening-entity-empty{cursor:default;}.cand.sel .cs{color:var(--text-primary-color,#fff);opacity:0.85;}.cand.muted{color:var(--hp-muted);cursor:default;}.pdfedit{display:flex;flex-wrap:wrap;gap:var(--sp-3);align-items:center;}.pdftag{display:inline-flex;align-items:center;gap:var(--sp-2);border:1px solid var(--hp-line);border-radius:var(--rad-s);padding:var(--sp-2) var(--sp-3);font-size:var(--fs-s);}.pdftag a{color:var(--hp-txt);text-decoration:none;max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.pdftag .x{--mdc-icon-size:15px;cursor:pointer;color:var(--hp-muted);}:host([data-pointer-hover]) .pdftag .x:hover{color:#ff7a5c;}.entlist{display:flex;flex-direction:column;gap:var(--sp-2);margin-bottom:10px;}.entrow{display:flex;align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-radius:var(--rad-m);background:var(--secondary-background-color,rgba(128,128,128,0.12));}.entrow ha-icon{--mdc-icon-size:20px;color:var(--hp-muted);}.entrow.on ha-icon{color:var(--hp-accent);}.entrow .en{flex:1;font-size:var(--fs-m);}.entrow .ev{font-size:var(--fs-m);color:var(--hp-muted);}.entbtn{min-width:74px;min-height:32px;padding:var(--sp-2) var(--sp-5);border:1px solid var(--hp-muted);border-radius:999px;background:transparent;color:var(--hp-txt);font:inherit;font-size:var(--fs-m);cursor:pointer;}.entbtn.on{background:var(--hp-accent);border-color:var(--hp-accent);color:var(--text-primary-color,#fff);font-weight:600;}.inforow{display:flex;gap:10px;font-size:var(--fs-m);margin:var(--sp-2) 0;}.inforow .k{color:var(--hp-muted);min-width:84px;}.inforow a{color:var(--hp-accent);word-break:break-all;}.infodesc{font-size:var(--fs-m);white-space:pre-wrap;margin-top:var(--sp-3);}.infodesc.muted{color:var(--hp-muted);}.pdflist{display:flex;flex-direction:column;gap:var(--sp-2);}.pdf{display:inline-flex;align-items:center;gap:var(--sp-2);color:var(--hp-accent);text-decoration:none;}ha-icon-picker{display:block;}.floorrow{display:flex;align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-2);font-size:var(--fs-m);cursor:pointer;}.floorrow .floorlvl{color:var(--hp-muted);font-size:var(--fs-s);border:1px solid var(--hp-line);border-radius:var(--rad-s);padding:0 var(--sp-3);}.rtest{display:flex;align-items:center;gap:var(--sp-4);margin-bottom:var(--sp-4);}.rtest .namein{flex:1;}.rtest ha-icon{color:var(--hp-accent);}.rtesticon{font-size:var(--fs-s);color:var(--hp-muted);}.rrow{display:flex;align-items:center;gap:var(--sp-3);margin:var(--sp-1) 0;}.rrow .rpat{flex:2;}.rrow .ricon{flex:1.4;}.rrow .rpat.bad{border-color:#ff7a5c;}.rrow .rprev{--mdc-icon-size:18px;color:var(--hp-txt);min-width:18px;}.rrow .ract{--mdc-icon-size:16px;color:var(--hp-muted);cursor:pointer;}:host([data-pointer-hover]) .rrow .ract:hover{color:var(--hp-txt);}:host([data-pointer-hover]) .rrow .ract.del:hover{color:#ff7a5c;}.gsrow .gsl{min-width:150px;font-size:var(--fs-m);color:var(--hp-muted);}.optimize-live{display:grid;justify-items:start;gap:var(--sp-2);margin-bottom:var(--sp-3);}.optimize-live .alignmsg,.optimize-live .rhint{margin-bottom:0;}.optimize-cleanup{min-height:44px;}.optimize-selected{color:var(--hp-txt);}.optimize-details{margin-top:var(--sp-3);color:var(--hp-muted);font-size:var(--fs-s);overflow-wrap:anywhere;}.optimize-details>summary{width:fit-content;color:var(--hp-txt);cursor:pointer;font-weight:600;}.optimize-details>summary:focus-visible{outline:2px solid var(--hp-accent);outline-offset:3px;border-radius:var(--rad-s);}.optimize-details ul{margin:var(--sp-3) 0;padding-inline-start:22px;}.optimize-details li + li{margin-top:var(--sp-1);}.btn.alignall{width:100%;justify-content:center;}.backupactions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--sp-3);}.backupactions .btn{justify-content:center;min-width:0;}.backupupload{display:inline-flex;min-width:0;}.backupupload>.btn{width:100%;justify-content:center;}.backupupload input{display:none;}.backupbody{min-width:0;}.backupplanonly{margin-inline-start:var(--sp-4) !important;align-items:flex-start !important;}.backupplanonly>span:first-of-type{display:grid;gap:2px;white-space:normal;}.backupplanonly small{color:var(--secondary-text-color);line-height:1.35;}.backupplanonlystatus{color:var(--hp-accent) !important;font-weight:700;}.backupfile,.backupsummary,.backupcontent{display:flex;flex-direction:column;min-width:0;gap:var(--sp-1);}.backupfile b,.backupcontent span{overflow-wrap:anywhere;}.backupfile span,.backupsummary span,.backupcontent span{color:var(--hp-muted);font-size:var(--fs-s);}.backupcounts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--sp-2) var(--sp-4);font-size:var(--fs-s);}.backupwarn,.backuperror{border-radius:var(--rad-s);padding:var(--sp-3);font-size:var(--fs-s);line-height:1.45;overflow-wrap:anywhere;}.backupwarn{background:color-mix(in srgb,var(--hp-accent) 12%,transparent);}.backuperror{background:rgba(179,64,42,.16);color:#ff7a5c;}.backupdetails{border:1px solid var(--hp-line);border-radius:var(--rad-s);padding:var(--sp-2) var(--sp-3);font-size:var(--fs-s);}.backupdetails summary{cursor:pointer;font-weight:700;}.backupdetails>div{display:grid;gap:var(--sp-1);padding-block-start:var(--sp-2);}.backupdetails code{overflow-wrap:anywhere;color:var(--hp-muted);}.backupchoices{display:flex;flex-direction:column;gap:var(--sp-2);border:1px solid var(--hp-line);border-radius:var(--rad-s);min-width:0;}.backupchoices label{margin:0 !important;display:flex;gap:var(--sp-2);}.backupconfirm{align-items:flex-start !important;}.backupconfirm>span:first-of-type{min-width:0;white-space:normal;overflow-wrap:anywhere;}@media (max-width:520px){.backupactions,.backupcounts{grid-template-columns:1fr;}}.aboutver{font-size:var(--fs-s);color:var(--hp-muted);margin:var(--sp-2) 0 var(--sp-3);}.aboutlink{display:flex;align-items:center;gap:var(--sp-3);width:fit-content;color:var(--hp-accent);text-decoration:none;font-size:var(--fs-m);padding:var(--sp-1) 0;}:host([data-pointer-hover]) .aboutlink:hover{text-decoration:underline;}.aboutlink ha-icon{--mdc-icon-size:18px;line-height:1;}hp-dialog .supportbody{min-width:0;overflow-x:hidden;gap:var(--sp-5);}.supportsection{display:grid;min-width:0;gap:var(--sp-2);}.supportsection + .supportsection{padding-top:var(--sp-4);border-top:1px solid var(--hp-line);}.supportsection h3{margin:0;color:var(--hp-txt);font-size:var(--fs-m);}.supportlinks,.supportactions{display:flex;align-items:center;flex-wrap:wrap;gap:var(--sp-2) var(--sp-4);min-width:0;}.supportform>label:not(.srcrow){margin-top:var(--sp-2);color:var(--hp-muted);font-size:var(--fs-s);}.supportmessage,.supportraw{width:100%;min-width:0;box-sizing:border-box;resize:vertical;border:1px solid var(--hp-line);border-radius:var(--rad-s);padding:var(--sp-3);color:var(--hp-txt);background:color-mix(in srgb,var(--card-background-color,var(--hp-bg)) 92%,var(--hp-txt));font:inherit;}.supportmessage{min-height:120px;background:var(--hp-bg);}.supportraw{min-height:220px;margin-top:var(--sp-2);resize:none;white-space:pre;overflow:auto;font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:12px;}.supportattach{min-width:0;align-items:flex-start;margin:var(--sp-2) 0 0 !important;}.supportattach>span:first-of-type{min-width:0;white-space:normal;overflow-wrap:anywhere;}.supportwarning,.supportstatus,.supportupdate{display:flex;align-items:flex-start;gap:var(--sp-2);min-width:0;margin:0;padding:var(--sp-3);border-radius:var(--rad-s);background:color-mix(in srgb,var(--hp-accent) 14%,transparent);overflow-wrap:anywhere;font-size:var(--fs-s);line-height:1.45;}.supportwarning ha-icon,.supportstatus ha-icon,.supportupdate ha-icon{flex:none;color:var(--hp-accent);--mdc-icon-size:20px;}.supportpreview,.supportmanual,.supporterror,.supportsuccess{display:grid;min-width:0;gap:var(--sp-2);padding:var(--sp-3);border:1px solid var(--hp-line);border-radius:var(--rad-s);}.supportsummary{font-weight:600;overflow-wrap:anywhere;}.supporthash{display:grid;min-width:0;gap:var(--sp-1);color:var(--hp-muted);font-size:var(--fs-s);}.supporthash code{overflow-wrap:anywhere;color:var(--hp-txt);}.supportpreview details{min-width:0;}.supportpreview summary{cursor:pointer;color:var(--hp-accent);}.supportprivacy{margin:0 !important;line-height:1.45;}.supporterror{background:color-mix(in srgb,var(--error-color,#db4437) 12%,transparent);border-color:color-mix(in srgb,var(--error-color,#db4437) 45%,var(--hp-line));}.supportsuccess{background:color-mix(in srgb,var(--success-color,#43a047) 12%,transparent);border-color:color-mix(in srgb,var(--success-color,#43a047) 45%,var(--hp-line));}.supportfooter{flex-wrap:wrap;}@media (max-width:520px){hp-dialog .supportbody{padding-inline:var(--sp-4);}hp-dialog .supportfooter{padding-inline:var(--sp-4);}.supportactions .btn,.supportactions .aboutlink{max-width:100%;}}hp-dialog .body{padding:var(--sp-5) var(--sp-6);display:flex;flex-direction:column;gap:var(--sp-3);}hp-dialog .tapconfirm-body{min-width:0;overflow-x:hidden;}hp-dialog .tapconfirm-body p{max-width:100%;min-width:0;margin:0;overflow-wrap:anywhere;white-space:normal;}hp-dialog .tapconfirm-line{color:var(--hp-muted);}hp-dialog .body label{font-size:var(--fs-s);color:var(--hp-muted);margin-top:var(--sp-3);}hp-dialog .body .namein,hp-dialog .body .areasel{width:100%;box-sizing:border-box;}hp-dialog.roomdialog .body{min-width:0;overflow-x:hidden;}hp-dialog.roomdialog .body>*{min-width:0;max-width:100%;box-sizing:border-box;}hp-dialog.roomdialog .srcrow{min-width:0;align-items:flex-start;}hp-dialog.roomdialog .srcrow>span:first-of-type{min-width:0;white-space:normal;overflow-wrap:anywhere;line-height:1.35;}hp-dialog.roomdialog .dropbtn>b,hp-dialog.roomdialog .dropbtn>.ref{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}hp-dialog .row{display:flex;justify-content:flex-end;gap:var(--sp-4);width:100%;min-width:0;box-sizing:border-box;padding:var(--sp-5) var(--sp-6);border-top:1px solid var(--hp-line);}hp-dialog>.row[slot='footer'] button{min-height:44px;}hp-dialog .row.dialog-action-footer{align-items:center;justify-content:flex-start;flex-wrap:wrap;row-gap:var(--sp-4);}hp-dialog .dialog-action-group{display:flex;flex:0 1 auto;flex-wrap:wrap;align-items:center;gap:var(--sp-4);max-width:100%;min-width:0;}hp-dialog .dialog-action-group .btn{flex:0 0 auto;min-height:44px;}hp-dialog .dialog-action-danger{margin-right:auto;}hp-dialog .dialog-action-commit{margin-left:auto;justify-content:flex-end;}hp-dialog .row.markerfooter{justify-content:space-between;align-items:center;flex-wrap:wrap;}hp-dialog .row.roomfooter{align-items:center;flex-wrap:wrap;}hp-dialog .row.infofooter{align-items:center;justify-content:flex-start;flex-wrap:wrap;gap:var(--sp-3);}hp-dialog .row.infofooter .btn{flex-shrink:0;}hp-dialog .row.infofooter .infofooter-close{margin-left:auto;}@media (max-width:480px){hp-dialog .row.infofooter{padding:var(--sp-4) var(--sp-5);}}.markeractions,.markersaveactions{display:flex;align-items:center;gap:var(--sp-4);}.markeractions:empty{display:none;}.markersaveactions{margin-left:auto;}.device-inbox{display:flex;flex-direction:column;gap:var(--sp-4);padding:var(--sp-5) var(--sp-6);min-width:0;}.device-inbox-dialog{--hp-dialog-wide-width:920px;}.device-inbox-head{display:grid;grid-template-columns:minmax(180px,1fr) auto;align-items:center;gap:var(--sp-4);}.device-inbox-search{width:100%;min-width:0;box-sizing:border-box;border:1px solid var(--hp-line);border-radius:var(--rad-m);background:transparent;color:var(--hp-txt);font:inherit;padding:11px 14px;}.device-inbox-tabs{display:flex;gap:var(--sp-2);overflow-x:auto;scrollbar-width:thin;padding-bottom:var(--sp-1);}.device-inbox-tabs button{flex:0 0 auto;border:1px solid var(--hp-line);border-radius:999px;background:transparent;color:var(--hp-txt);font:inherit;padding:8px 12px;cursor:pointer;}.device-inbox-tabs button.on{border-color:var(--hp-accent);background:color-mix(in srgb,var(--hp-accent) 18%,transparent);}.device-inbox-tabs button span{color:var(--hp-muted);margin-inline-start:4px;}.device-inbox-discovery{margin:8px 0;padding:8px 10px;border:1px solid var(--divider-color,#e0e0e0);border-radius:8px;}.device-inbox-discovery summary{cursor:pointer;font-weight:600;}.device-inbox-discovery .srcrow{display:flex;gap:6px;align-items:center;margin:8px 0;}.device-inbox-excluded{display:flex;flex-wrap:wrap;gap:6px;align-items:center;}.device-inbox-excluded>span{font-weight:500;}.device-inbox-chips{display:flex;flex-wrap:wrap;gap:4px;}.device-inbox-chips .chip{display:inline-flex;align-items:center;gap:2px;padding:1px 6px;border-radius:10px;background:var(--secondary-background-color,#f0f0f0);font-size:12px;}.device-inbox-chips .chip button{border:none;background:none;cursor:pointer;padding:0 2px;color:var(--secondary-text-color,#666);}.device-inbox-excluded input[type="text"]{flex:1 1 140px;min-width:120px;padding:4px 6px;border:1px solid var(--divider-color,#e0e0e0);border-radius:6px;background:var(--card-background-color,#fff);color:var(--primary-text-color,#212121);}.device-inbox-preview{margin:8px 0 4px;font-size:13px;opacity:0.85;}.device-inbox-filters{display:flex;flex-wrap:wrap;gap:var(--sp-4) var(--sp-6);color:var(--hp-muted);}.device-inbox-filters label{display:inline-flex;align-items:center;gap:var(--sp-2);cursor:pointer;}.device-inbox-filter-help{display:inline-flex;align-items:center;gap:var(--sp-1);min-width:0;}.device-inbox-results{display:grid;gap:var(--sp-3);min-width:0;}.device-inbox-row{display:grid;grid-template-columns:42px minmax(180px,1fr) minmax(180px,auto);align-items:center;gap:var(--sp-4);min-width:0;border:1px solid var(--hp-line);border-radius:var(--rad-m);padding:var(--sp-4);background:color-mix(in srgb,var(--hp-txt) 3%,transparent);}.device-inbox-icon{--mdc-icon-size:28px;color:var(--hp-txt);justify-self:center;}.device-inbox-copy{min-width:0;}.device-inbox-name{display:flex;align-items:center;flex-wrap:wrap;gap:var(--sp-2);}.device-inbox-new{border-radius:999px;background:var(--hp-accent);color:var(--text-primary-color,#fff);font-size:var(--fs-s);padding:2px 7px;}.device-inbox-meta,.device-inbox-reason,.device-inbox-copy code{display:block;color:var(--hp-muted);font-size:var(--fs-s);overflow-wrap:anywhere;white-space:normal;}.device-inbox-status{color:var(--error-color,#db4437);margin-inline-start:var(--sp-2);}.device-inbox-actions{display:flex;justify-content:flex-end;align-items:center;flex-wrap:wrap;gap:var(--sp-2);}.device-inbox-actions .btn{min-height:36px;padding:7px 10px;}.device-inbox-menu{position:relative;}.device-inbox-menu summary{list-style:none;cursor:pointer;}.device-inbox-menu summary::-webkit-details-marker{display:none;}.device-inbox-menu-items{position:absolute;z-index:2;inset-inline-end:0;top:calc(100% + var(--sp-1));display:grid;gap:var(--sp-1);min-width:180px;padding:var(--sp-2);border:1px solid var(--hp-line);border-radius:var(--rad-m);background:var(--hp-panel,var(--card-background-color,#fff));box-shadow:0 8px 24px rgba(0,0,0,.22);}.device-inbox-menu-items .btn{justify-content:flex-start;width:100%;}.device-inbox-empty{color:var(--hp-muted);text-align:center;padding:var(--sp-8);}.device-inbox-more{align-self:center;}@media (max-width:680px){.device-inbox{padding:var(--sp-4);}.device-inbox-head{grid-template-columns:minmax(0,1fr);}.device-inbox-head .btn{justify-self:stretch;}.device-inbox-tabs{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));overflow-x:visible;}.device-inbox-tabs button{min-width:0;overflow-wrap:anywhere;}.device-inbox-row{grid-template-columns:36px minmax(0,1fr);}.device-inbox-actions{grid-column:1 / -1;justify-content:flex-start;}}`];var lp={"editor.context_actions":"Actions: {object}","editor.tool_options":"Tool options: {tool}","editor.palette":"Palette: {tool}","editor.open_group":"Tool group: {group}","editor.group_active":"{group} — active: {item}","editor.disabled_action":"{action} is unavailable: {reason}","editor.loading":"Loading editor…","editor.loading_aria":"The plan editor is loading","editor.load_failed":"Could not load the editor.","editor.refresh_advice":"Refresh the page and try again.","editor.retry_advice":"Check your connection and press again.","version_mismatch.title":"House Plan versions do not match","version_mismatch.body":"If Home Assistant is still restarting, let it finish, then reload this page.","version_mismatch.frontend":"Card","version_mismatch.backend":"Integration","version_mismatch.reload":"Reload page","color_picker.title":"Color picker","color_picker.hue":"Hue","color_picker.saturation":"Saturation","color_picker.value":"Brightness","color_picker.hex":"Hex color","color_picker.invalid_hex":"Enter a 3- or 6-digit hex color","color_picker.confirm":"OK","btn.properties":"Properties","btn.keep_as_walls":"Keep as walls","btn.delete_room_keep_walls":"Delete room, keep walls","btn.delete_room_with_walls":"Delete room and walls","title.markup_select":"Select and edit walls and columns","title.markup_column":"Column: click a grid point to place a square column","markup.partition":"Partition","markup.column":"Column","markup.hint_column":"click a grid point to place a square column","history.wall_segment":"Add wall segment","history.column_add":"Add column","history.physical_edit":"Change physical object","history.physical_delete":"Delete physical object","history.physical_move":"Move physical object","history.wall_face_batch":"Create rooms from walls","toast.column_duplicate":"A column with the same centre and outer size already exists","physical.partition_properties":"Partition properties","physical.column_properties":"Column properties","physical.shape":"Shape","physical.square":"Square","physical.circle":"Circle","physical.diameter":"Diameter","physical.side":"Side","physical.rotation":"Rotation angle","physical.length":"Length","physical.allowed_range":"Allowed: {min}–{max} {unit}","physical.column_size_title":"Outer side of the square column placed by the click (1–150 cm).","card.title":"House plan","count.devices":"{n} dev.","empty.no_spaces":"No spaces yet.","nav.spaces":"House Plan spaces","empty.add_first":"Add the first space and upload a floor plan.","empty.read_only":"No spaces are configured. Ask an administrator to add one.","empty.install":'Install the House Plan integration and add it in "Devices & services".',"btn.add_space":"Add space","btn.cancel":"Cancel","btn.save":"Save","btn.close":"Close","btn.delete":"Delete","btn.copy":"Copy","btn.edit":"Edit","btn.open_in_ha":"Open in HA","btn.reset":"Reset","btn.attach":"Attach…","btn.upload":"Upload…","btn.replace":"Replace…","title.zoom_in":"Zoom in","title.zoom_out":"Zoom out","title.zoom_fit":"Fit all","title.configure_space":"Configure space","title.add_space":"Add space","title.markup_add":"Walls: draw a continuous chain; each accepted segment is saved independently. Shift locks to 45°","title.markup_merge":"Merge: click one room, then the neighbour it shares a wall with","title.markup_split":"Split a room: click the room, then two points on its walls","title.markup_delroom":"Delete room: click inside a room and confirm","title.need_plan":"Upload a floor-plan image","markup.add":"Walls","markup.merge":"Merge","markup.split":"Split","markup.resize":"Resize","title.markup_resize":"Resize rooms: drag an available horizontal or vertical wall handle","markup.hint_resize":"drag an available wall handle · the wall stops at the first unsafe position · Esc cancels · Ctrl+Z — undo","resize.disabled.diagonal":"This wall is angled; Resize supports only horizontal and vertical walls","resize.disabled.side-angle":"An adjoining wall is angled; Resize requires both adjoining walls to meet this wall at right angles","resize.disabled.duplicate-physical-wall":"A separate partition or column overlaps this wall; remove or move it before resizing","resize.disabled.partial-shared":"A neighbouring room uses only part of this wall, so it cannot be moved safely as one shared wall","resize.disabled.unequal-shared":"The neighbouring room uses different endpoints or wall length, so the walls cannot move together safely","resize.disabled.multiple-rooms":"Moving this wall would affect more than two rooms","resize.disabled.thickness-conflict":"The wall thickness cannot be preserved safely","resize.disabled.opening-conflict":"An opening on this wall cannot be moved safely","resize.disabled.invalid-geometry":"This wall cannot be resized without changing the plan structure","resize.limit_stopped":"Wall stopped: the next step would break a junction limit","resize.commit_failed":"Resize was cancelled because the final plan did not pass the geometry check","resize.preview_failed":"Resize stopped at the last safe position because the plan geometry could not be preserved","markup.opening":"Opening","markup.delete_room":"Delete room","history.undo":"Undo","history.redo":"Redo","history.undo_named":"Undo: {name} (Ctrl+Z)","history.redo_named":"Redo: {name} (Ctrl+Shift+Z / Ctrl+Y)","history.undo_empty":"Nothing to undo","history.redo_empty":"Nothing to redo","history.undone":"Undone: {name}","history.redone":"Redone: {name}","history.add_room":"Create room","history.split_room":"Split room","history.merge_rooms":"Merge rooms","history.resize_room":"Resize room","history.wall_thickness":"Change wall thickness","history.add_opening":"Add door or window opening","history.edit_opening":"Edit opening","history.move_opening":"Move opening","history.delete_opening":"Delete opening","history.delete_room_keep_walls":"Delete room, keep walls","history.delete_room_with_walls":"Delete room and walls","history.decor_add":"Add decor object","history.decor_edit":"Edit decor object","history.decor_move":"Move decor object","history.decor_transform":"Transform decor object","history.decor_delete":"Delete decor object","history.backdrop_transform":"Transform plan backdrop","history.device_move":"Move {name}","history.device_stale":"Device position history is no longer applicable and was cleared","opening.new":"New opening","opening.edit":"Opening","opening.door":"Door","opening.window":"Window","opening.gate":"Gate","opening.passage":"Open passage","opening.passage_binding_warning":"Saving will remove the open/close sensor and lock.","opening.invalid_passage_fields":"The open passage on plan “{room}” has unsupported settings: {fields}.","opening.type_label":"Type","opening.length_label":"Length, cm","opening.contact_label":"Open/close sensor","opening.lock_label":"Lock","opening.none":"— none —","opening.search_ph":"Search: name or entity id…","opening.invert":"Invert open/closed","opening.flip_h":"Hinge on the other jamb","opening.flip_v":"Opens to the other side","opening.open":"Open","opening.closed":"Closed","opening.locked":"Locked","opening.unlocked":"Unlocked","opening.state_unknown":"unavailable","opening.no_entities":"No sensors bound — a static symbol on the plan.","toast.opening_no_wall":"Click next to a room wall or independent wall","opening.host_partition":"Independent wall","opening.partition_orphan":"The independent wall for this opening no longer exists","opening.partition_jamb_margin":"Leave at least {distance} between the opening and the end of the wall","opening.rebind_partition":"Attach to another independent wall","confirm.delete_partition_openings_title":"Delete wall and openings?","confirm.delete_partition_openings_body":"This wall contains {count} opening(s). They will be deleted together.","confirm.delete_partition_openings_item":"• {type}, {length}","markup.hint_points":"points: {n} · Shift — 45° steps · Esc — finish chain · Ctrl+Z — undo a point · closing an area offers a room","markup.hint_start":"click a grid dot to start a wall chain","tip.lqi":"average zigbee signal:","tip.area":"area: {value}","info.device_header":"Device on the plan","info.model":"Model","info.state":"State","info.link":"Link","info.manuals":"Manuals","info.none":"No additional information","marker.new_device":"New device","marker.name_label":"Name (shown on the plan)","marker.name_ph":"Name","marker.binding_label":"Bind to an HA device","marker.binding_disabled":"disabled in Home Assistant","marker.virtual_option":"Virtual device (no binding)","marker.search_ph":"Search device / group…","marker.nothing_found":"nothing found","marker.room_label":"Room","marker.room_override":" (override placement)","marker.room_choose":"— select a room —","marker.room_auto":"— by device area (auto) —","marker.icon_label":"Icon","marker.icon_ph":"mdi:… (empty = auto)","marker.display_label":"Display","display.badge":"Icon + state","display.icon_ripple":"Icon + state and activity","display.static_icon":"Always static icon","marker.display_hint_badge":"The icon and dynamic plate show device state without the ordinary activity pulse. Red alarms remain visible.","marker.display_hint_icon_ripple":"The icon, dynamic plate and pulse show a short pulse for events and a continuous pulse for work, motion or presence. Red alarms have separate priority.","marker.display_hint_value":"A selected or automatically resolved Home Assistant value replaces the icon while the plate continues to show state. Red alarms remain visible.","marker.display_hint_static_icon":"The theme-aware shell and icon always stay the same. State, activity, unavailability and alarms do not change the face.","marker.static_alarm_warning":"This device can report alarms. Static display hides the marker's visual alarm indication.","marker.preview.title":"Display preview","marker.preview.actual":"Now","marker.preview.example":"Example","marker.preview.integration":"Provided by","marker.preview.source":"Display source","marker.preview.current_state":"Current state","marker.preview.result":"On the plan","marker.preview.details":"Source details","marker.preview.select_source":"Choose a Home Assistant device or entity to see its actual display.","marker.preview.unknown_provider":"Unknown integration","marker.preview.virtual_provider":"House Plan · virtual device","marker.preview.no_source":"No active source","marker.preview.no_state":"No current state","marker.preview.mixed_states":"Several different states","marker.preview.multiple_sources":"{n} sources","marker.preview.more_sources":"+{n} more","marker.preview.scaled":"The preview is scaled to {n}% to fit. The saved size is unchanged.","marker.preview.demo_short":"Show short activity","marker.preview.demo_continuous":"Show continuous activity","marker.preview.stop_continuous":"Stop continuous activity","marker.preview.demo_short_notice":"Short activity example; the actual device state is unchanged.","marker.preview.demo_continuous_notice":"Continuous activity example; the actual device state is unchanged.","marker.preview.demo_already_visible":"The current state already shows a real activity or alarm effect.","marker.preview.reduced_motion":"System reduced-motion is enabled, so ordinary activity is shown as a dot.","marker.preview.reason.neutral":"Neutral dark plate","marker.preview.reason.working":"Yellow plate: the device is working now","marker.preview.reason.working_activity":"Yellow plate and activity effect: the device is working now","marker.preview.reason.open":"Orange plate: physically open or unlocked","marker.preview.reason.cover_icon_state":"Neutral plate; the cover entity controls the displayed state and icon","marker.preview.reason.presence":"Activity effect while presence is detected","marker.preview.reason.event":"Short activity effect after a detected event","marker.preview.reason.transition":"Activity effect while the device is moving or changing state","marker.preview.reason.media_neutral":"Media devices stay on a neutral dark plate while available","marker.preview.reason.unavailable":"Subdued neutral plate: unavailable or off","marker.preview.reason.alarm":"Red alarm plate; alarm indication is always shown","marker.preview.reason.live_states_disabled":"Live-state styling is disabled for this card","marker.preview.reason.value_no_state":"No usable state value; the icon is shown instead","marker.preview.reason.value_ambiguous_sources":"Several possible value sources; the icon is shown instead","marker.preview.reason.value_non_scalar":"The source did not return a simple value; the icon is shown instead","marker.preview.reason.value_virtual":"A virtual device has no Home Assistant value; the icon is shown instead","marker.preview.reason.vacuum_live_plan_only":"Live vacuum position and trail are available only on the full plan","marker.preview.reason.hidden_design_preview":"The device is hidden on the plan; this design preview remains visible","marker.preview.reason.composite_power_source":"State comes from the device Power entity; auxiliary switches are ignored","marker.preview.reason.activity_display_disabled":"The selected display mode does not show ordinary activity effects","marker.preview.reason.ha_disabled":"The Home Assistant binding is disabled and will be hidden on the plan","marker.preview.reason.orphaned":"The saved Home Assistant binding can no longer be found","marker.preview.reason.static_icon":"Static mode: device state does not change the icon","marker.activity_color":"Activity pulse color","marker.ripple_size":"Activity pulse size","marker.activity_alarm_note":"Color and size affect ordinary activity only and do not change red alarms.","marker.pulse_a11y_alarm":"Alarm","marker.pulse_a11y_event":"Recent event","marker.pulse_a11y_presence":"Presence detected","marker.pulse_a11y_transition":"Changing state","marker.pulse_a11y_running":"Working","marker.state_a11y_neutral":"Default state","marker.state_a11y_working":"Working","marker.state_a11y_open":"Open","marker.state_a11y_locked":"Locked","marker.state_a11y_unlocked":"Unlocked","marker.state_a11y_alarm":"Alarm","marker.state_a11y_unavailable":"Unavailable","marker.lqi_a11y_low":"LQI {value}, low signal","marker.lqi_a11y_mid":"LQI {value}, medium signal","marker.lqi_a11y_high":"LQI {value}, high signal","marker.size_label":"Icon size / rotation","marker.angle_label":"Rotate","marker.model_label":"Model","marker.model_ph":"e.g. Aqara T&H","marker.link_label":"Link","marker.desc_label":"Description","marker.desc_ph":"Notes, specs…","marker.manuals_label":"Manuals (PDF etc.)","marker.sub_device":"device","marker.sub_z2m_group":" · Z2M group","marker.sub_group":"group","marker.sub_helper":"helper","space.new":"New space","space.copy_title":"Copy space","space.copy_name":"New space name","space.copy_fallback":"Space","space.copy_create":"Create copy","space.copy_optimize_title":"Optimize before copying?","space.copy_optimize_body":"Before creating “{name}”, House Plan must optimize the entire plan, including other spaces. Continue?","space.copy_optimize_confirm":"Optimize and copy","space.copy_error_changed":"The plan changed while confirmation was open. Review it and try again.","space.copy_error_source_missing":"The source space no longer exists. Reopen its settings and try again.","space.copy_error_source_invalid":"House Plan could not validate every wall in this space. Fix the source space and try again.","space.copy_error_spaces_limit":"House Plan already has the maximum number of spaces.","space.copy_error_partitions_limit":"This space has too many walls to copy.","space.copy_error_openings_limit":"This space has too many openings to copy.","space.copy_error_decor_limit":"This space has too many background objects to copy.","space.copy_error_columns_limit":"This space has too many columns to copy.","space.copy_error_opening_host":"One of the openings is no longer attached to a wall. Fix or delete it before copying.","space.copy_error_geometry":"The copy would create unsafe wall geometry. Fix the source space and try again.","space.copy_error_optimize_geometry":"Copy stopped because optimizing the entire plan is unsafe for one of the spaces.","space.header":"Space","space.title_label":"Title","space.title_ph":"e.g. Garage","space.plan_label":"Floor plan (background)","space.no_plan":"no plan image","space.plan_alt":"plan","room.new":"New room","room.name_label":"Display name","room.name_ph":"e.g. Terrace","room.area_label":"Home Assistant area (unassigned)","room.no_area_option":"— no area —","room.default_name":"Room","device.unnamed":"unnamed","device.light_group":"light group","device.fallback":"device","device.virtual":"virtual device","confirm.delete_room_title":'Delete room "{name}"?',"confirm.delete_room_body":"Choose whether the room's exclusive physical walls should remain. Walls shared with another room are always kept.","confirm.remove_marker_title":"Delete device from the plan?","confirm.remove_marker_body":"The device will disappear completely and stop contributing to plan data. You can add it again later.","confirm.erase_decor":"Erase the {kind} object? You can undo this action from the editor history.","confirm.delete_space_title":"Delete space?","confirm.delete_space_body":"The space, all its rooms and all its plan markup will be deleted.","confirm.delete_space_vac_routes":"Robot map assignments will also be removed: {count}.","space.delete_blocked":"This space is still used by {n} device(s). Move them to another space or delete them first.","toast.pos_save_failed":"Failed to save position: {err}","toast.no_entity":"The device has no suitable entity","toast.ha_disabled_action":"A Home Assistant object that is disabled cannot be used on the plan.","toast.ha_disabled_show_device":"A device disabled in Home Assistant cannot be shown on the plan. Enable it in Home Assistant first.","toast.ha_disabled_show_entity":"An entity disabled in Home Assistant cannot be shown on the plan. Enable it in Home Assistant first.","toast.ha_disabled_add":"A disabled Home Assistant object cannot be added to the plan. Enable it in Home Assistant first.","toast.ha_binding_unverified":"The object status could not be verified through the Home Assistant registry. Display and actions are temporarily unavailable.","toast.markup_needs_server":"Markup is available after the config is moved to the server","toast.space_order_changed":"Order changed. If any card pins its floor by number, check those panels.","toast.conflict":"Config was changed in another window — data refreshed, repeat your last action","toast.cfg_save_failed":"Failed to save config: {err}","toast.room_overlap":"The outline overlaps room “{name}” — rooms must not overlap","toast.contour_cannot_close":"The outline cannot close because it is degenerate or intersects itself","toast.merge_not_adjacent":"Only rooms that share a wall can be merged","toast.rooms_merged":"Rooms merged into “{name}”","toast.split_pick_wall":"Start the cut on the room’s wall","toast.split_bad_cut":"The cut must run wall to wall inside the room, without crossing walls or itself","merge.header":"Merge rooms","merge.hint":"The merged room keeps one name and one area. The other area is released — its devices leave the plan until another room claims it.","merge.keep":"Keep","merge.no_area":"no area","toast.room_saved":"Room saved ({n}). Devices added: {added}. Outline the next one or exit markup.","toast.room_saved_no_area":"Room saved ({n}, no area). Outline the next one or exit markup.","toast.marker_needs_server":"Device editing is available after the config is moved to the server","toast.virtual_name_required":"Enter a name for the virtual device","toast.marker_saved":"Device saved","toast.marker_removed":"Device deleted from the plan","toast.integration_missing":"The House Plan integration is not installed — management unavailable","toast.plan_formats":"Supported formats: SVG, PNG, JPG, WebP","toast.plan_required":"Upload a floor plan — it is required","toast.space_added_onboard":"Space added. Outline the rooms: click grid dots and close the contour.","toast.space_added":"Space added","toast.space_copied":"Space “{name}” created","toast.space_saved":"Space saved","toast.space_deleted":"Space deleted","toast.delete_failed":"Delete failed: {err}","toast.error":"Error: {err}","toast.toggle_target_unavailable":"Target “{name}” is unavailable — no action was performed","toast.toggle_targets_unavailable":"Targets are unavailable: {names}. No action was performed","toast.file_failed":'File "{name}" was not uploaded: {err}',"toast.files_attached":"Files attached: {n}","err.unknown":"unknown error","err.code":"code {code}","err.too_large":"file larger than {mb} MB","err.bad_ext":"unsupported type (PDF/image expected)","err.unauthorized":"administrator rights required","editor.title":"Title","editor.default_floor":"Initial space","editor.default_floor_missing":"Initial space “{id}” no longer exists. Choose another space.","editor.floor":"Fixed space","editor.floor_none":"— not fixed —","editor.floor_index":"YAML index {index} (preserved)","fixed_floor.loading":"Loading the fixed space…","fixed_floor.invalid_title":"The fixed space is unavailable","fixed_floor.invalid_body":"Check floor in the card configuration. The configured value is: {value}","editor.icon_size":"Icon size, % of plan width","editor.show_temperature":"Show temperature","editor.live_states":"Live states (on/off, open…)","editor.light_pools":"Light pools and wall shadows","editor.show_signal":"Show zigbee signal (LQI)","editor.language":"Interface language","editor.lang_auto":"Auto (HA profile)","title.icon_rules":"Icon rules: which MDI icon devices get by name","rules.title":"Icon rules","rules.hint":"Rules are checked top-down against “device name + model” (case-insensitive regex); the first match wins. When nothing matches, the entity device class decides, then the generic chip icon.","rules.pattern_ph":"regex, e.g. plug|socket","rules.icon_ph":"mdi:power-socket-de","rules.add":"Add rule","rules.reset":"Reset to defaults","rules.test_ph":"Try a device name…","rules.invalid":"invalid regex","rules.saved":"Icon rules saved","btn.up":"Up","btn.down":"Down","tap.info":"Device card","tap.more_info":"HA more-info dialog","tap.toggle":"Toggle state","marker.tap_label":"Tap action for this device","tap.toggle_note":"The resolved state is shown below. Secure devices are never toggled from the plan.","import.title":"Create spaces from HA floors","import.hint":"Your Home Assistant already knows these floors. Pick the ones to turn into plan spaces — you will upload a floor-plan image for each one next. Rooms are then outlined by hand on the plan.","import.start":"Create {n} space(s)","import.manual":"Start from scratch","import.progress":"Floor {i} of {n}","import.done":"Spaces created. Outline the rooms: click grid dots and close the contour.","btn.skip":"Skip","space.scale_label":"Scale (grid cell size)","space.cell_cm.help":"Links the grid to real dimensions: lengths, areas, wall thickness, opening sizes and glow radius depend on it. Changing it after drawing changes the calculated dimensions of the whole space without moving its points on the plan.","space.cell_cm.help.aria":"Help: space scale","space.scale_unit":"cm per cell","space.scale_unit_imperial":"in per cell","space.display_section":"Display","space.show_borders":"Always show room borders","space.zero_wall_style":"Zero-thickness walls","space.zero_wall_style.help":"Dashed zero-thickness walls pass Glow and sun rays, while solid ones block them as zero-area barriers. The choice affects every such wall in the space even when its line is hidden in View.","space.zero_wall_style.help.aria":"Help: zero-thickness wall style","space.zero_wall_dashed":"Dashed","space.zero_wall_solid":"Solid","space.show_names":"Show room names (drag to move)","space.room_color":"Border & name color","space.opacity":"Opacity","space.fill_label":"Room fill","space.fill_mode.help":"“Custom colour” is styling, while “Light”, “Temperature” and “LQI” use current Home Assistant data; Glow is enabled separately.","space.fill_mode.help.aria":"Help: room fill mode","fill.none":"None","fill.lqi":"Zigbee signal","fill.light":"Lights","fill.custom":"Custom color","space.custom_fill":"Fill color","space.source_file":"I have a floor-plan image","space.source_draw":"No image — I'll outline rooms by hand","fill.temp":"Temperature","tip.temp_avg":"average temperature:","tip.hum_avg":"average humidity:","space_card.button":"Open the space plan","space_card.not_found":"Space “{id}” not found","space_card.loading":"Loading…","continuity.restore_plan":"Restoring floor plan…","continuity.restore_connection":"Restoring device connection…","continuity.retry":"Try again","editor.space":"Space","editor.framing":"Framing","editor.fit_content":"All visible content","editor.fit_house":"Tight to house geometry","editor.show_button":"Show button","editor.button_label":"Button label","editor.button_target":"Target dashboard path","marker.sub_entity":"entity","title.general_settings":"General settings","title.export_pdf":"Save as PDF","pdf.title":"Save as PDF","pdf.dimensions":"Show dimensions and areas","pdf.decor":"Show furniture and other decor","pdf.room_names":"Show room names","pdf.backdrop":"Show backdrop","pdf.save":"Save","pdf.saving":"Creating…","pdf.failed":"Could not create the PDF.","pdf.too_large":"The images exceed the 25 MB PDF limit.","pdf.asset_failed":"A backdrop or decor image could not be loaded.","pdf.scale":"Scale 1:{n}","pdf.north":"North","gs.title":"General settings","gs.light_group":"Fill: lights","gs.light_on":"Lights on","gs.light_off":"All lights off","gs.temp_group":"Fill: temperature","gs.temp_cold":"Cold","gs.temp_ok":"Comfortable","gs.temp_hot":"Hot","gs.lqi_group":"Fill: zigbee signal","gs.lqi_low":"Weak signal","gs.lqi_high":"Strong signal","gs.reset":"Reset to defaults","gs.saved":"General settings saved","gs.radar_show_live":"Show live presence on the plan","gs.radar_show_live_hint":"Hides or shows all live radar targets. This does not start or stop observation recording.","radar.title":"Presence on the plan","radar.help":"Connect this marker to exact Home Assistant radar entities, place the sensor and choose its coordinate profile. Live positions are clipped to the selected room.","radar.help.aria":"Help: presence radar settings","radar.enabled":"Use this presence radar","radar.show_live":"Show live targets","radar.configure":"Configure radar","radar.configure_on_plan":"Configure on plan","radar.change_installation":"Change installation","radar.no_contour":"This room has no boundary. Radar points will not be clipped.","radar.discard_setup_title":"Discard radar setup?","radar.discard_setup":"The unsaved radar setup will be lost.","radar.step_place_mount":"Mark the physical sensor position","radar.step_place_heading":"Mark a point straight ahead of the sensor","radar.step_reference":"Mark reference position {n}, then start measurement","radar.step_check_reference":"Mark an independent check position","radar.start_measure":"Start measurement","radar.countdown":"Stand at the mark in {seconds} s","radar.capturing":"Stand still and alone while measuring…","radar.fit_ready":"Calibration is ready","radar.check_third":"Check at another position","radar.check_complete":"Independent check completed","radar.error_distance":"Position difference: {distance}","radar.ambiguous_target":"More than one target was reported. Repeat the measurement alone.","radar.insufficient_samples":"Not enough current coordinates. Retry or use manual setup.","radar.bad_references":"Choose separated references in different directions from the sensor.","radar.ambiguous_sources":"The measurements allow two equally plausible directions. Choose reference points that distinguish left from right.","radar.bad_fit":"Measurements do not match. Check units, mounting point and references.","radar.desktop_hint":"Use a computer for precise setup. Editing on touch devices is best effort.","radar.detected":"House Plan recognized radar metadata for this device. Review the exact sources before saving.","radar.detected_ld2450":"House Plan found an ESPHome LD2450 coordinate set. Review the exact X/Y sources before saving.","radar.additional_actions":"Additional actions","radar.declare":"This is a presence radar","radar.profile":"Data profile","radar.profile_esphome_ld2450_v1":"ESPHome LD2450 (X/Y targets)","radar.profile_cartesian_v1":"Cartesian targets (X/Y)","radar.profile_polar_v1":"Polar target (distance/angle)","radar.profile_range_v1":"Distance only","radar.profile_zones_v1":"Zone states","radar.profile_presence_v1":"Presence only","radar.room":"Radar room","radar.room_choose":"Choose a room","radar.target":"Target {n}","radar.axis_x":"X coordinate entity","radar.axis_y":"Y coordinate entity","radar.add_target":"Add target slot","radar.range_channel":"Range channel {n}","radar.add_range":"Add range channel","radar.presence_gate":"Presence gate entity","radar.swap_axes":"Swap X and Y axes","radar.axis_x_sign":"X direction","radar.axis_y_sign":"Y direction","radar.distance_source":"Distance entity","radar.angle_source":"Angle entity","radar.angle_unit":"Angle unit","radar.degrees":"Degrees","radar.radians":"Radians","radar.angle_zero":"Zero-angle direction","radar.angle_forward":"Forward","radar.angle_right":"Right","radar.angle_clockwise":"Angles increase clockwise","radar.zone_source":"Zone entity","radar.occupancy_source":"Presence entity","radar.count_source":"Target count entity","radar.availability_source":"Availability entity","radar.source_choose":"Choose an entity","radar.source_optional":"Optional","radar.source_missing":"currently unavailable","radar.saved_unsupported":"This saved radar setup is unsupported or incomplete. It remains inactive; remove it or update House Plan before configuring it again.","radar.occupancy":"Presence (on/off)","radar.count":"Count","radar.mount":"Position and direction","radar.mount_hint":"This is the physical sensor position. Moving its decorative marker does not change it.","radar.heading":"Direction, °","radar.range_cm":"Range, cm","radar.fov_deg":"Field of view, °","radar.unit":"Source unit","radar.mirror":"Mirror the left/right axis","radar.remove":"Remove radar settings","radar.invalid":"Complete the radar room, sources and position before saving.","radar.check_sources":"Check live data","radar.checking":"Checking…","radar.health":"Connection status","radar.live_summary":"Current targets: {targets}; range arcs: {ranges}","radar.health_ok":"Current data received","radar.health_off":"No targets detected","radar.health_stale":"Some coordinate data is out of date","radar.health_partial":"Some sources are current; others are out of date","radar.health_restricted":"Access to one or more sources is restricted","radar.health_incomplete":"The current radar report is incomplete","radar.health_position_unavailable":"Presence reported; current position unavailable","radar.health_unavailable":"Sensor data unavailable","radar.health_needs_setup":"Installation needs setup","radar.health_inconsistent":"The sources report conflicting values","radar.health_unknown":"Current state is unknown","radar.health_disabled":"Radar is disabled","radar.error_invalid_radar":"Check the radar settings.","radar.error_invalid_selection":"Select an existing room and valid sources.","radar.error_source_restricted":"You do not have access to all selected sources.","radar.error_rate_limited":"Too many requests. Try again shortly.","radar.error_not_ready":"Radar processing is not ready.","radar.error_conflict":"The plan changed. Reopen the radar setup and try again.","radar.error_source_unavailable":"One or more selected radar sources are unavailable.","radar.error_unsupported_capability":"This radar capability is not supported by the installed integration.","radar.report_age":"{seconds} s ago","space.show_lqi":"Show zigbee signal (LQI) next to devices","space.hide_decor":"Hide the decorative layer","space.hide_decor_tip":"Lines, shapes, labels and furniture stay where they are — visible in the backdrop editor, not on the plan.","space.hide_openings":"Hide openings","space.hide_openings_tip":"Door, window and gate symbols are not drawn, but the openings keep working: light passes through, the sun comes in at a window, contact sensors still open them. The plan editor always shows them.","gs.light_none":"No light sources","mode.plan":"Plan editor","mode.devices":"Device editor","display.value":"Value + state","marker.subarea":"no area, manual","device.new":"New device — open its editor to dismiss","opening.unlock_action":"Unlock","opening.lock_action":"Lock","opening.lock_pending":"Working…","title.close_editor":"Close editor (back to view)","title.add_device":"Add a device to the plan","devbar.add":"Add","devbar.rules":"Icon rules","device_inbox.button":"Devices","device_inbox.title":"Devices on the plan","device_inbox.search":"Search devices, entities and integrations…","device_inbox.add_virtual":"Add virtual device","device_inbox.tab_on_plan":"On plan","device_inbox.tab_available":"Available","device_inbox.tab_hidden":"Hidden","device_inbox.tab_readd":"Available again","device_inbox.only_new":"New only","device_inbox.show_entities":"Show entities","device_inbox.show_hidden":"Show hidden on plan","device_inbox.show_hidden.help":"Temporarily shows hidden and disabled markers as editor-only ghosts on the plan. Saved device visibility does not change.","device_inbox.show_hidden.help.aria":"Help: show hidden devices on the plan","device_inbox.new":"New","device_inbox.find":"Find on plan","device_inbox.edit":"Edit","device_inbox.hide":"Hide","device_inbox.show":"Show","device_inbox.add":"Add","device_inbox.readd":"Add again","device_inbox.hide_available":"Hide from list","device_inbox.show_more":"Show more","device_inbox.more_actions":"More actions","device_inbox.find_hidden_hint":"Enable “Show hidden on plan” first","device_inbox.show_disabled":"Activate this binding in Home Assistant before showing it","device_inbox.empty_on_plan":"No matching devices are on the plan yet.","device_inbox.empty_available":"No devices are available to add.","device_inbox.empty_hidden":"There are no hidden devices.","device_inbox.empty_readd":"No removed devices are available to add again.","device_inbox.reason_visible_auto":"Discovered automatically","device_inbox.reason_visible_explicit":"Added explicitly","device_inbox.reason_manual_hidden":"Hidden by user","device_inbox.reason_automatic_hidden":"Hidden automatically","device_inbox.reason_service_entry":"Service-only registry entry","device_inbox.reason_excluded_integration":"Integration “{integration}” excluded by discovery filters","device_inbox.reason_excluded_domain":"Non-spatial entity type","device_inbox.reason_grouped_light":"Represented by a room light group","device_inbox.reason_represented_by_parent":"Represented by its parent device","device_inbox.reason_removed":"Previously removed from the plan","device_inbox.reason_available":"Available to add to the plan","device_inbox.reason_no_bound_room":"HA area is not linked to a plan room","device_inbox.status_ha_disabled":"Disabled in Home Assistant","device_inbox.status_orphaned":"Binding is no longer present in Home Assistant","device_inbox.status_unverified":"Home Assistant registry is temporarily unavailable","device_inbox.saved":"Device list updated","device_inbox.filters_excluded":"Excluded integrations","device_inbox.filters_group_lights":"Group room lights into one marker","device_inbox.filters_preview_appear":"will appear: {count}","device_inbox.filters_preview_hide":"will disappear: {count}","device_inbox.filters_preview_lights":"lights affected: {count}","device_inbox.filters_reset":"Restore recommended","device_inbox.filters_save":"Save filters","device_inbox.filters_search_ph":"Add an integration…","device_inbox.filters_title":"Discovery filters","space.roomcard_section":"Room card shows:","space.label_temp":"Temperature","space.label_hum":"Humidity","space.label_lqi":"Average Zigbee signal","space.label_light":"Lights on/off","roomcard.light_on":"On","roomcard.light_off":"Off","roomcard.light_partial":"{on} of {total}","toast.split_pick_inside":"Intermediate cut points must be inside the room","mode.decor":"Background editor","decor.select":"Select","decor.line":"Line","decor.rect":"Rectangle","decor.ellipse":"Oval","decor.text":"Text","decor.erase":"Erase","decor.erase_confirm_title":"Erase object?","decor.color":"Color","decor.width":"Line width","decor.line_style":"Line style","decor.line_style_solid":"Solid","decor.line_style_dashed":"Dashed","decor.fill":"Fill","decor.fill_color":"Fill color","decor.length":"Length","decor.size":"Size","decor.flip_h":"Flip horizontally","decor.flip_v":"Flip vertically","decor.angle":"Rotation angle, °","decor.text_size":"Text size","decor.backdrop_properties":"Plan backdrop properties","decor.text_title":"Text label","decor.object_title":"Edit {kind}","decor.text_label":"Text","decor.live_group":"Insert HA variable","decor.live_entity":"Entity","decor.live_entity_ph":"choose an entity","decor.live_attr":"Value","decor.live_attr_ph":"choose state or attribute","decor.live_state":"State","decor.backdrop":"Backdrop image","decor.backdrop_hint":"Drag to move; pull a corner to resize; use the top handle to rotate. Shift changes proportions or frees the angle.","decor.backdrop_reset":"Reset the picture","decor.backdrop_reset_done":"The picture is back at its original place and size","marker.icon_auto":"Auto: {icon} (by icon rules; pick one to override)","marker.icon_pin_auto":"Pin","mode.plan_tip":"Plan editor — the geometry of the home: draw and split/merge rooms, bind them to HA areas, place doors, windows and gates, move room cards, set the scale","mode.devices_tip":"Device editor — everything about icons: drag to position, click to edit binding/icon/display, add virtual devices, icon rules","mode.decor_tip":"Background editor — purely visual decor under the plan: lines, rectangles, ovals and text labels that never react to clicks","space.glow_enabled":"Light-source glow","gs.glow_group":"Light-source glow","gs.glow_base":"House darkness","gs.glow_light":"Default light color / intensity","gs.wall_group":"Walls","gs.wall_fill":"Wall fill","gs.glow_radius":"Glow radius","gs.glow_radius.help":"Sets the default glow radius in metres or feet; a device-specific radius overrides it.","gs.glow_radius.help.aria":"Help: default glow radius","gs.unit_m":"m","gs.unit_ft":"ft","marker.controls_label":"Controls other light sources","marker.controls.help":"With the “Toggle state” action, the listed sources toggle together with this marker. Their glow stays at their own markers, and the link alone does not turn the controlling marker into a light source.","marker.controls.help.aria":"Help: controlling other light sources","marker.controls_filter":"Search lights and switches…","info.controls":"Controls","marker.glow_radius_label":"Glow radius","marker.glow_radius.help":"Sets the glow radius in metres or feet; an empty value uses the radius from general settings.","marker.glow_radius.help.aria":"Help: glow radius","markup.wallthick":"Thickness","markup.select":"Select","title.markup_wallthick":"Thickness — click a wall to set its thickness from 0 to 100 cm.","markup.hint_wallthick":"click a wall · Esc closes without applying","wallthick.field":"Thickness","wallthick.unit_cm":"cm","wallthick.unit_in":"in","wallthick.apply_room":"Apply to all walls of this room","markup.draw_wall_title":"Thickness of each new wall segment (0–100 cm). Shared walls keep the existing value.","room.queue_progress":"Room {current} of {total}","toast.wall_rooms_saved":"Created rooms: {n}","toast.wall_chain_saved":"Wall chain saved","toast.wallthick_pick":"Click a wall","toast.wallthick_set":"Wall thickness set","toast.wallthick_cleared":"Wall thickness removed","toast.physical_range":"Enter a value from {min} to {max} {unit}","toast.zero_wall_opening_conflict":"Remove the opening on this wall segment first.","toast.zero_wall_ambiguous":"The wall segment is ambiguous. Simplify or adjust the junction.","toast.zero_wall_migration_blocked":"The space was not converted: {reason}. No data was changed.","toast.physical_angle":"Enter a rotation angle from 0° up to, but not including, 90°","toast.physical_limit":"The space has reached the limit for this type of geometry","toast.geometry_unsafe":"Change canceled: wall geometry could not be built safely.","junction.limit_angle":"The angle between walls is too sharp: {actual}°, minimum {limit}°.","junction.limit_valence":"Too many walls meet in one node: {actual}, maximum {limit}.","junction.limit_length":"The wall segment is too short: {actual} cm, minimum {limit} cm.","junction.limit_distance":"Walls and nodes are too close: {actual} cm, minimum {limit} cm.","junction.limit_clearance":"No room interior is left: {actual} cm², minimum {limit} cm².","junction.limit_check_failed":"The junction check could not run — the change was not saved","toast.wall_model_migration_blocked":"The wall model could not be updated: {reason}. The plan was not changed. Run “Optimize plans”; if the error repeats, fix the conflicting wall geometry.","toast.wall_model_client_outdated":"Update the card and reload the page before editing the plan.","wall_model.reason.invalid-room":"invalid room contour","wall_model.reason.zero-length":"zero-length wall segment","wall_model.reason.third-owner":"wall shared by more than two rooms","wall_model.reason.duplicate-id":"conflicting wall identifiers","wall_model.reason.thickness-conflict":"conflicting wall thickness values","wall_model.reason.opening-host":"opening cannot be assigned to one wall","toast.delete_room_pick":"Click inside the room you want to delete","toast.plan_snap_ambiguous":"Zoom in to choose the wall node","toast.wall_repair_ambiguous":"The room outline has more than one possible connection. Zoom in and connect it explicitly.","toast.wall_repair_too_large":"The gap is larger than 2 cm. Connect the walls before creating the room.","toast.wall_repair_changed":"The wall geometry changed. Try creating the room again.","toast.opening_on_zero_wall":"Openings cannot sit on a zero-thickness wall","marker.from_ha_option":"Pick from the HA list","marker.show_entities":"Show entities","marker.show_entities_tip":"Adds not only devices to the list, but all their entities too","marker.pick_ph":"Choose a device…","room.open_area":"Open the HA area","room.fit_action":"Fit room {name}","view.volumetric":"Volumetric view","view.flat":"Flat view","kiosk.title":"This screen's sizes","kiosk.hint":"Stored on this device only — every wall tablet or TV can have its own comfortable sizes.","kiosk.icon_scale":"Device icon size","kiosk.font_scale":"Room card text size","editor.kiosk":"Wall device (kiosk) mode","editor.cycle":"Auto-switch spaces every N seconds (kiosk, 0 = off)","room.settings_title":"Room settings","room.settings_section":"Room settings (override the space)","room.fill_label":"Fill in THIS room","fill.inherit":"As the space","room.custom_fill_space":"Space color","room.custom_fill_own":"Room color","room.temp_range_label":"Comfort range","room.temp_range_min":"Lower comfort-temperature bound","room.temp_range_max":"Upper comfort-temperature bound","room.temp_range_reset":"As the space","room.temp_range.help":"This range applies only to this room. Empty fields inherit the corresponding space bounds; if the bounds are reversed, House Plan uses the smaller value as the lower bound and the larger value as the upper bound.","room.temp_range.help.aria":"About the room comfort range","room.temp_src_label":"Temperature source","room.hum_src_label":"Humidity source","room.src_average":"Average over the room's sensors (default)","room.src_pick":"A specific HA device or entity","room.src_ph":"Choose a source…","toast.room_updated":"Room updated","space.card_font":"Room-card font size (whole space)","room.sizes_section":"Font sizes","room.name_scale":"Room name size","room.label_scale":"Metrics size","preview.room_name":"Living room","toast.cfg_reload_failed":"Could not reload the plan from the server: {err}","toast.locale_load_failed":"Could not load the language pack. English is used until the page reloads.","toast.furniture_art_load_failed":"Could not load the furniture drawings. Reload the page to show them.","room.settings_short":"Room settings","room.unnamed":"Unnamed room","marker.use_climate_temp":"Include the device temperature in the room","marker.use_climate_temp_tip":"Adds an air conditioner or thermostat current_temperature to the room average. Configure the external value badge separately below.","marker.value_badge_title":"Value badge","marker.value_badge.help":"Shows one selected value next to the icon. It does not affect room metrics, light, Glow or the tap action.","marker.value_badge.help.aria":"Help: device value badge","marker.value_badge_enabled":"Show a value badge","marker.value_badge_source":"Value","marker.value_badge_source.help":"Choose a specific state, supported attribute, or derived value of this device.","marker.value_badge_source.help.aria":"Help: value badge source","marker.value_badge_position":"Position","marker.value_badge_position.help":"The chosen side stays fixed and does not flip automatically at a plan edge.","marker.value_badge_position.help.aria":"Help: value badge position","marker.value_badge_right":"Right","marker.value_badge_bottom":"Below","marker.value_badge_left":"Left","marker.value_badge_top":"Above","marker.value_badge_empty":"This device has no available values","marker.value_badge_static":"A static icon does not show live values. The setting is preserved.","marker.value_badge_missing":"Source unavailable","marker.value_badge_missing_hint":"The saved source is currently unavailable. Keep it, disable the badge, or choose another value.","marker.value_badge_duplicate":"The same value is already shown inside the icon.","marker.value_badge_state":"State · {name}","marker.value_badge_marker_state":"Light-source state · {name}","marker.value_badge_lqi":"Average Zigbee signal quality","marker.value_badge_attr_current_temperature":"Current temperature · {name}","marker.value_badge_attr_temperature":"Target temperature · {name}","marker.value_badge_attr_current_humidity":"Current humidity · {name}","marker.value_badge_attr_humidity":"Humidity · {name}","marker.value_badge_attr_current_position":"Position · {name}","marker.value_badge_attr_percentage":"Speed · {name}","marker.value_badge_attr_brightness":"Brightness · {name}","marker.value_badge_attr_volume_level":"Volume · {name}","marker.value_badge_attr_battery_level":"Battery · {name}","marker.value_badge_attr_fan_speed":"Fan speed · {name}","marker.value_source":"Value source","marker.value_source.help":"Choose the value that replaces the icon. The tap action does not change.","marker.value_source.help.aria":"Help: value face source","marker.value_source_auto":"Automatic (as before)","marker.value_source_missing_hint":"The saved source is currently unavailable. The face shows — until it recovers or you choose another value.","marker.light_role_label":"Is this device a light source?","marker.light_role.help":"“Auto” uses the bound device's resolved role, “Always” forces its own source and “Never” excludes it; linked lights above remain independent.","marker.light_role.help.aria":"Help: whether this device is a light source","marker.light_role_auto_yes":"Auto (light source)","marker.light_role_auto_no":"Auto (not a light source)","marker.light_role_always":"Always a light source","marker.light_role_never":"Never a light source","marker.light_entity_label":"Leading light entity","marker.light_entity.help":"For a composite device, choose the entity whose state, colour and brightness represent this plan source. The automatic fallback remains compatible with older plans.","marker.light_entity.help.aria":"Help: leading light entity","marker.light_entity_auto":"Automatic ({entity})","marker.light_entity_none":"no controllable entity","marker.light_entity_missing":"The saved entity {entity} is unavailable. House Plan temporarily uses {fallback}; the saved choice will be restored if it returns.","marker.toggle_entity_label":"Entity to toggle","marker.toggle_entity.help":"For a composite device, choose the exact own light or switch operated by a tap. Automatic keeps the previous target rules and is independent from the leading light entity.","marker.toggle_entity.help.aria":"Help: entity to toggle","marker.toggle_entity_auto":"Automatic ({entity})","marker.toggle_entity_none":"no own controllable entity","marker.toggle_entity_missing":"The saved entity {entity} is no longer among this marker’s selectable channels. House Plan temporarily uses {fallback}; the saved choice will be restored if it returns.","marker.glow_color_label":"Glow colour and brightness","marker.glow_mode.help":"Use live source values, override only its colour, or fix both colour and brightness. The minimum is 1%; to disable the source, choose “Never”.","marker.glow_mode.help.aria":"Help: glow colour and brightness","marker.glow_mode_auto":"From source","marker.glow_mode_color":"Set colour","marker.glow_mode_fixed":"Set colour and brightness","marker.glow_color":"Glow colour","marker.glow_brightness":"Brightness","marker.glow_disabled_never":"Glow settings are unavailable because this marker is explicitly not a light source.","marker.glow_disabled_auto":"Auto mode found no spatial light source for this marker.","marker.glow_disabled_no_entity":"No active controllable Home Assistant entity is available for this spatial source.","marker.glow_passive_hint":"This source has no own Home Assistant data. Set its colour and brightness manually; its radius remains available.","marker.control_broken":"Saved source is missing or no longer marked as a light","marker.control_missing_label":"Missing plan light","marker.control_passive":"passive source","toast.marker_control_cycle":"This link would create a circular chain of light controls.","toast.marker_binding_required":"Choose a Home Assistant device before linking another light source.","confirm.unlock_title":"Unlock?","confirm.unlock_body":"House Plan will send an unlock command to this lock.","toast.files_migrate_failed":"Attachments could not be moved to the new binding, links keep pointing at the old files: {err}","space.pick_saved":"Already uploaded","space.pick_saved_hint":"Plans stored on the server, including ones you detached earlier","space.no_saved":"No plans stored on the server yet.","space.loading":"Loading…","space.used_by":"in use: {list}","space.in_use":"A space still uses this plan — detach it first","btn.use":"Use","confirm.delete_plan_title":"Delete plan file?","confirm.delete_plan_body":"The file will be deleted from the server. This action cannot be undone.","toast.plans_list_failed":"Could not list the stored plans: {err}","toast.plan_delete_failed":"Could not delete the plan: {err}","marker.hide":"Hide","marker.hide_tip":'The device will disappear from the plan after saving but will still count toward the room signal. Restore it through the "Devices" catalog in the device editor.',"marker.show":"Show","marker.show_tip":"The device will appear on the plan again after saving.","marker.hidden_ghost":"Device hidden by the user","marker.ha_disabled_device":"The device is disabled in Home Assistant and hidden from the plan.","marker.ha_disabled_entity":"The entity is disabled in Home Assistant and hidden from the plan.","marker.ha_disabled_all_entities":"The device has no active Home Assistant entities, so it is hidden from the plan.","marker.ha_registry_limited":"The full Home Assistant registry is unavailable to this user. The unverified object cannot be shown or used for now.","marker.delete_tip":"Completely delete the device from the plan and every aggregate. You can add it again later.","tap.run":"Run automation/script/scene","tap.none":"Do nothing","marker.run_target_label":"What to run","marker.run_search_ph":"Search: automation, script or scene…","marker.run_target_gone":"Target {id} not found — pick again","marker.tap_confirm":"Ask for confirmation","marker.tap_confirm_tip":"Show a confirmation dialog before acting — a guard against accidental taps.","marker.toggle_hint_single":"Target: {name} ({id}).","marker.virtual_light_target":"Virtual light: {name}.","marker.virtual_light_current":"Manual state: {state} → {effect}.","marker.virtual_light_state_on":"on","marker.virtual_light_state_off":"off","marker.toggle_hint_group":"Will toggle {count} source(s): {names}.","marker.toggle_hint_current":"Now: {state} → {effect}.","marker.toggle_hint_group_current":"Currently on: {on} of {count} → {effect}.","marker.toggle_hint_skipped":"Will be skipped ({count}): {targets}.","marker.toggle_effect_turn_on":"will turn on","marker.toggle_effect_turn_off":"will turn off","marker.toggle_effect_open":"will open","marker.toggle_effect_close":"will close","marker.toggle_effect_stop":"will stop","marker.toggle_effect_toggle":"state will toggle","marker.toggle_skip_missing":"not found","marker.toggle_skip_ha_disabled":"disabled in HA","marker.toggle_skip_unavailable":"unavailable","marker.toggle_skip_unsupported":"toggle is unsupported","marker.toggle_skip_secure":"blocked for security","marker.toggle_none_no_binding":"This device has no binding, so there is no state to toggle. Tapping will do nothing.","marker.toggle_none_no_actionable_entity":"This device has no state that can be toggled. Tapping will do nothing.","marker.toggle_none_configured_targets_missing":"The configured targets are unavailable. The device's own entity will not be substituted for them.","marker.toggle_none_ha_disabled":"The target is disabled in Home Assistant and cannot be used on the plan.","marker.toggle_none_unavailable":"The target is currently unavailable. Tapping will do nothing.","marker.toggle_none_unsupported":"Home Assistant exposes no safe toggle operation for this entity. Tapping will do nothing.","marker.toggle_none_secure":"Toggling locks, alarms and secure gates from the plan is blocked for security.","run.automation":"automation","run.script":"script","run.scene":"scene","confirm.tap_run":'Run "{name}"?',"confirm.tap_toggle":'Toggle "{name}"?',"confirm.current_state":"Current state: {state}","confirm.expected_state":"After switching: {state}","confirm.group_current":"on {on} of {total}","confirm.group_all_on":"all are on","confirm.group_all_off":"all are off","confirm.unavailable_targets":"Unavailable: {count}","confirm.expected_by_ha":"Home Assistant will determine the state","confirm.state_on":"On","confirm.state_off":"Off","confirm.state_open":"Open","confirm.state_closed":"Closed","confirm.state_opening":"Opening","confirm.state_closing":"Closing","confirm.state_stopped":"Stopped","confirm.state_unknown":"Unknown","toast.run_started":"Started: {name}","toast.run_target_missing":"Run target not found — check the device settings","toast.run_target_required":"Pick an automation, script or scene","toast.tap_target_changed":"The action target changed. Try again.","toast.virtual_light_toggle_failed":"Could not toggle the virtual light: {err}","toast.value_badge_source_required":"Choose a value for the badge","btn.run":"Run","vac.section":"Robot vacuum: live position","vac.autocal":"Set up automatically","vac.live":"Live position on the plan","vac.trail":"Show the robot's path","vac.autocal_no_rooms":"The integration reports no room list — open “Fit manually”","vac.route_warn_unmapped":"The robot is cleaning a map that is not assigned to any floor","vac.route_warn_needs_calibration":"The map is assigned to a floor but not calibrated","vac.route_warn_ambiguous":"Two maps are indistinguishable — no floor was chosen","vac.route_warn_missing_space":"The space of this map was deleted","vac.autocal_no_match":"Room names did not match (need ≥3 in common) — open “Fit manually”","vac.autocal_done":"Done: bound via {rooms} rooms. Start a cleanup and check","vac.cal_need_pos":"The robot is not reporting coordinates — start a cleanup and pause it","vac.cal_done":"Calibration saved. Start a cleanup and check","vac.cal_cancelled":"Calibration cancelled","vac.fit":"Fit manually","vac.fit_hint":"Drag the robot map into place, stretch by the corners","vac.fit_rotate":"Rotate 90°","vac.fit_mirror":"Mirror","vac.trail_never":"Never","vac.trail_cleaning":"While cleaning","vac.trail_always":"Always","gs.bg_group":"Stage background","gs.bg_color":"Background around the plan","gs.bg_default":"Theme default","gs.bg_theme":"theme default","gs.bg_mode":"Plan background","gs.bg_mode.help":"“Follows the Sun” uses sun.sun, falling back to the browser's local clock; Static always shows the selected colour.","gs.bg_mode.help.aria":"Help: general plan background","gs.bg_static":"Static color","gs.bg_daynight":"Follows the Sun","gs.sun_group":"Sun","gs.sun_missing":"The sun.sun entity was not found — the background follows your local clock; window rays are unavailable.","gs.north":"North on the plan","gs.north.help":"The angle is measured clockwise from the plan's upward vertical; north is required for window rays, not for the “Follows the Sun” background.","gs.north.help.aria":"Help: general north direction","gs.north_ph":"not set","gs.north_clear":"Clear","gs.north_letter":"N","gs.sun_rays":"Sunlight through windows","gs.sun_ray_origin":"Sun rays","gs.sun_ray_origin.inner":"From the inner window corners","gs.sun_ray_origin.outer":"From the outer window corners","gs.about_version":"Houseplan Card v{v}","gs.about_github":"GitHub · docs & issues","gs.about_telegram":"Telegram chat","support.title":"Help & feedback","space.bg_color":"Background around the plan","space.bg_inherit":"Inherit general","space.bg_inherited":"inherits general settings","space.bg_mode":"Plan background","space.bg_mode.help":"Inherit the general background or override this space with a static colour or “Follows the Sun”.","space.bg_mode.help.aria":"Help: space background","space.north":"North on the plan (override)","space.north.help":"Overrides general north for this space; the angle is measured clockwise from the plan's upward vertical and is used by window rays.","space.north.help.aria":"Help: north for this space","space.north_inherited":"inherited: {v}","space.sun_rays":"Sunlight through windows","space.sun_inherit":"Inherit general","space.sun_on":"On","space.sun_off":"Off","canvas.far_objects":"{n} object(s) far from the plan","canvas.show_far":"Show","canvas.home_tip":"The plan is over there — click to fit it","gs.grid_group":"Plan maintenance","gs.grid_hint":"Updates data models, aligns plan elements to the grid and merges redundant wall fragments. An exact report is shown before anything is stored.","gs.align_all":"Optimize plans","gs.align_title":"Optimize plans","gs.align_none":"All plans already use the current optimized data model.","gs.optimize_no_automatic_changes":"There are no automatic changes to apply. Review the items below.","gs.align_count":"{n} of {total} elements will move, by at most {cm} cm.","gs.align_where":"The largest shift is in “{s}”.","gs.align_turned":"Openings whose angle is corrected: {n}.","gs.align_preflight_failed":"Could not safely verify the geometry of the following spaces: {spaces}{more}.","gs.align_preflight_hint":"Plans were not changed. Copy the diagnostics with the button below and attach them to the bug report together with a space export.","gs.preflight_reason_prepare-exception":"Could not prepare the space geometry (exception while building the model)","gs.preflight_reason_wall-null":"The wall body did not build (the union came back empty)","gs.preflight_reason_wall-degraded-extra":"The wall body degraded with extra geometry","gs.preflight_reason_wall-failed-core":"The wall body core failed to assemble","gs.preflight_reason_wall-exception":"Wall construction threw an exception","gs.preflight_reason_floor-null":"The floor outline did not build","gs.preflight_reason_floor-exception":"Floor construction threw an exception","gs.preflight_copy":"Copy diagnostics","gs.preflight_copied":"Diagnostics copied","gs.preflight_update_hint":"The card and integration versions differ — update House Plan and retry.","gs.align_preflight_space":"Space {n}","gs.align_preflight_more":", and {n} more","gs.optimize_changes":"Model migrations: {m}; spaces updated: {c}; noisy coordinate values removed: {p}; merged real-wall fragments: {w}; merged zero-thickness wall fragments: {s}; independent walls: {i}.","gs.zero_walls_migrated":"Virtual wall spans converted: {n}.","gs.wall_segments_migrated":"Wall segments stabilised: {n}.","gs.room_drafts_migrated":"Unfinished contours converted to ordinary walls: {drafts}; wall segments: {segments}.","gs.optimize_lattice_summary":"Noisy coordinate values canonicalized: {n}; maximum movement: {cm} cm.","gs.optimize_lattice_space":"{space}: coordinate values canonicalized: {n}; off-grid values left unchanged: {far}.","gs.optimize_coincident_partitions":"Hidden independent wall sections absorbed into room walls: {n}.","gs.optimize_openings_rehosted":"Openings reattached to room walls: {n}.","gs.optimize_walls_straightened":"Walls straightened: {n}; maximum movement: {cm} cm.","gs.optimize_walls_straightened_where":"Largest wall correction: {s}.","gs.optimize_walls_straighten_skipped":"Near-axis walls left unchanged because they could not be repaired safely: {n}.","gs.optimize_glow_migration":"Legacy Glow: {spaces} spaces → no data fill + independent Glow; {rooms} rooms → inherited data fill + independent Glow.","gs.optimize_references":"References repaired: spaces — {spaces}; rooms — {rooms}; positions — {positions}; devices detached from missing spaces — {detached}.","gs.optimize_reference_more":", and {n} more","gs.optimize_orphans_removed":"Forgotten records removed: {total} — room labels: {rooms}; devices: {devices}; group markers: {groups}. They belonged to spaces deleted earlier.","gs.optimize_live_positions":"Old positions in deleted spaces belong to existing objects: {n}{names}. They will be kept.","gs.optimize_live_positions_remove":"Old positions in deleted spaces belong to existing objects: {n}{names}. They are selected for removal.","gs.optimize_live_names":": {names}{more}","gs.optimize_live_remove":"Remove old positions","gs.optimize_live_keep":"Keep old positions","gs.optimize_live_selected":"Old positions will be removed after Optimize is applied.","gs.optimize_unverified":"Could not safely verify positions: {n}. They were left unchanged.","gs.optimize_registry_limited":"Full administrator access to the Home Assistant registries is required for a safe check.","gs.optimize_vacuum_warning":"Vacuum room mappings that still need review: {n}.","gs.optimize_details":"Details","gs.optimize_details_more":"And {n} more records.","gs.optimize_detail_removed":"will be removed","gs.optimize_detail_live":"will be kept","gs.optimize_detail_unverified":"not verified","gs.optimize_detail_room_label":"room label","gs.optimize_detail_device":"device","gs.optimize_detail_group":"group marker","gs.optimize_detail_unknown":"unknown owner","gs.optimize_detail_item":"{status}: {kind} {id}; old space {space}","gs.align_warn":"Elements deliberately placed between grid nodes will move. One undo is available after the operation, only until the next plan edit.","gs.align_run":"Optimize","gs.align_done":"Plans optimized: {n} elements moved, {m} records maintained, {r} references repaired","gs.optimize_undo":"Undo last optimization","gs.optimize_undone":"The last optimization was undone","decor.furniture":"Furniture","decor.image":"Image","decor.image_title":"Custom images","decor.image_upload":"Upload image","decor.image_replace":"Replace image","decor.image_uploading":"Uploading…","decor.image_asset":"Image file","decor.image_pick_hint":"Upload an image or choose one already used in House Plan.","decor.image_place_hint":"Click on the plan to place the image.","decor.image_none":"No uploaded images yet.","decor.image_unavailable":"Image unavailable","decor.image_used":"Used in {n} objects","decor.image_upload_failed":"Could not upload the image: {err}","decor.image_error_capacity":"The custom image storage limit has been reached.","decor.image_in_use":"Remove every placed copy before deleting this image.","decor.image_delete_title":"Delete image file?","decor.image_delete_message":"Delete “{name}” from House Plan? This cannot be undone.","furn.title":"Furniture library","furn.symbol":"Symbol","furn.group_furniture":"Furniture","furn.group_appliance":"Appliances","furn.group_sanitary":"Plumbing","furn.group_other":"Other","furn.width":"Width","furn.depth":"Depth","furn.back_to_categories":"All categories","furn.pick_hint":"Choose a category, then a symbol.","furn.place_hint":"Click on the plan — the piece lands against the nearest wall. Shift places it free.","furn.cat_air_conditioner":"Air conditioners","furn.cat_armchair":"Armchairs","furn.cat_bathtub":"Bathtubs","furn.cat_bed":"Beds","furn.cat_bidet":"Bidets","furn.cat_boiler":"Water heaters","furn.cat_chair":"Chairs","furn.cat_coffee_table":"Coffee tables","furn.cat_cooktop":"Cooktops","furn.cat_dining_table":"Dining tables","furn.cat_dishwasher":"Dishwashers","furn.cat_dryer":"Dryers","furn.cat_fireplace":"Fireplaces","furn.cat_fridge":"Refrigerators","furn.cat_kitchen_cabinet":"Kitchen cabinets","furn.cat_kitchen_sink":"Kitchen sinks","furn.cat_nightstand":"Cabinets","furn.cat_plant":"Plants","furn.cat_rug":"Rugs","furn.cat_shelving":"Shelving","furn.cat_shower":"Showers","furn.cat_sink":"Sinks","furn.cat_sofa":"Sofas","furn.cat_stairs":"Stairs","furn.cat_toilet":"Toilets","furn.cat_tv":"Televisions","furn.cat_wardrobe":"Wardrobes","furn.cat_washer":"Washing machines","furn.cat_work_table":"Desks","furn.sym_sofa":"Two-seat sofa","furn.sym_sofa_three_seat":"Three-seat sofa","furn.sym_sofa_corner_right":"Right sectional sofa","furn.sym_armchair":"Soft armchair","furn.sym_armchair_office":"Office chair","furn.sym_coffee_table":"Rectangular coffee table","furn.sym_coffee_table_round":"Round coffee table","furn.sym_coffee_table_oval":"Oval coffee table","furn.sym_coffee_table_rounded":"Rounded coffee table","furn.sym_table_dining":"Rectangular dining table","furn.sym_table_round":"Round table","furn.sym_table_dining_oval":"Oval dining table","furn.sym_table_dining_rounded":"Rounded dining table","furn.sym_chair":"Chair","furn.sym_chair_bar":"Bar stool","furn.sym_desk":"Rectangular desk","furn.sym_desk_corner":"Corner desk","furn.sym_bed_double":"Double bed","furn.sym_bed_single":"Single bed","furn.sym_nightstand":"Bedside table","furn.sym_cabinet_tv":"TV cabinet","furn.sym_cabinet_shoe":"Shoe cabinet","furn.sym_cabinet_sink":"Sink cabinet","furn.sym_wardrobe":"Wardrobe","furn.sym_bookshelf":"Bookcase","furn.sym_wall_unit":"Wall unit","furn.sym_kitchen_floor":"Kitchen floor module","furn.sym_kitchen_floor_corner":"Kitchen floor corner module","furn.sym_kitchen_wall":"Kitchen wall module","furn.sym_kitchen_wall_corner":"Kitchen wall corner module","furn.sym_shelf_floor":"Floor shelving unit","furn.sym_shelf_wall":"Wall shelf","furn.sym_fridge":"Fridge","furn.sym_stove":"Four-burner cooktop","furn.sym_cooktop_two":"Two-burner cooktop","furn.sym_dishwasher":"Dishwasher","furn.sym_washer":"Washing machine","furn.sym_dryer":"Tumble dryer","furn.sym_tv":"TV on stand","furn.sym_tv_wall":"Wall-mounted TV","furn.sym_ac":"Air conditioner","furn.sym_water_heater":"Water heater","furn.sym_toilet":"Floor-standing toilet","furn.sym_toilet_built_in":"Built-in toilet","furn.sym_bathtub":"Rectangular bathtub","furn.sym_bathtub_corner":"Corner bathtub","furn.sym_shower":"Shower","furn.sym_sink":"Washbasin","furn.sym_kitchen_sink":"Single kitchen sink","furn.sym_kitchen_sink_double":"Double kitchen sink","furn.sym_bidet":"Floor-standing bidet","furn.sym_bidet_built_in":"Built-in bidet","furn.sym_stairs":"Stairs","furn.sym_fireplace":"Fireplace","furn.sym_plant":"Plant","furn.sym_rug":"Rug","common.yes":"Yes","common.no":"No","vac.diag_source":"Source","vac.diag_platform":"Integration","vac.diag_status":"Status","vac.diag_position":"Position","vac.diag_rooms":"Rooms","vac.diag_rooms_value":"{total} · {matched} names match · {readiness}","vac.autocal_ready":"auto-calibration available","vac.autocal_not_ready":"need 3 matching names","vac.diag_path":"Integration path","vac.diag_map":"Map ID","vac.source_none":"not selected","vac.source_status_ok":"Ready","vac.source_status_missing":"Missing","vac.source_status_disabled":"Disabled in Home Assistant","vac.source_status_unavailable":"Unavailable","vac.source_status_unverified":"Cannot verify with current permissions","vac.source_status_unsupported":"No position data","vac.source_status_none":"No source","vac.source_banner_missing":"The saved source no longer exists. It was not replaced automatically; choose another source or restore it in Home Assistant.","vac.source_banner_disabled":"The saved source is disabled in Home Assistant. Enable it there or choose another source.","vac.source_banner_unverified":"Current Home Assistant permissions cannot verify this saved source. It remains pinned and will not be replaced automatically.","vac.choose_source":"Choose source","vac.source_auto":"Automatic","vac.source_auto_hint":"Use a compatible entity from this device","vac.all_cameras":"All cameras","vac.all_cameras_warn":"A camera may not provide robot data. Choose one only if it is your vacuum map.","vac.all_cameras_empty":"No other camera entities found.","vac.platform_unknown":"unknown integration","vac.cap_position":"position","vac.cap_rooms_short":"rooms","vac.cap_path":"path","vac.cap_map":"map ID","vac.cap_none":"no robot data detected","vac.xcme_hint":"Enable these Xiaomi Cloud Map Extractor attributes:","vac.documentation":"Documentation","vac.residual_title":"Check automatic calibration","vac.residual_message":"The matched rooms disagree by up to {error}. Apply this approximate calibration, refine it manually, or cancel without changing the saved setup.","vac.apply_proposal":"Apply","gs.backup_group":"Backup and transfer","gs.backup_hint":"Download a portable JSON backup or preview and import a backup made by House Plan.","backup.export_open":"Export","backup.import_open":"Import","backup.export_title":"Export House Plan","backup.import_title":"Import House Plan","backup.export_hint":"Choose whether the backup should contain the whole House Plan configuration or only the current space.","backup.full":"Full backup","backup.current_space":"Current space","backup.current_space_title":"Current space: {title}","backup.no_current_space":"No current space","backup.plan_only":"Plan only","backup.plan_only_hint":"Keep rooms, walls, openings, decor and room-label positions without devices or Home Assistant bindings.","backup.plan_only_preview":"This file contains the plan only","backup.privacy_warning":"The archive keeps names, Home Assistant identifiers and exact coordinates. Internal plans and attachments are referenced, not embedded; runtime states and vacuum trails are not included.","backup.download":"Download JSON","backup.export_done":"Backup downloaded","backup.reading":"Checking the backup…","backup.revalidated":"The plan changed after this preview. The summary was refreshed; review it and confirm again.","backup.error.support_invalid_message":"Check the support message and try again.","backup.error.support_package_too_large":"The anonymized support package exceeds the 8 MiB limit.","backup.error.support_preview_expired":"The support attachment preview expired or is no longer available.","backup.error.support_rate_limited":"Too many support reports or previews were requested. Try again later.","backup.error.support_rejected":"The report did not pass support service validation.","backup.error.support_unavailable":"The private support service is temporarily unavailable.","backup.error.unauthorized":"You do not have permission to export or import this plan.","backup.error.not_ready":"House Plan is not ready yet. Try again in a moment.","backup.error.too_large":"The backup exceeds the 8 MiB limit.","backup.error.invalid_json":"The selected file is not valid JSON.","backup.error.invalid_format":"The selected file is not a House Plan backup.","backup.error.invalid_image":"The image is damaged or does not match its format.","backup.error.unsupported_export_version":"This backup format is not supported by the installed version.","backup.error.unsupported_image":"Use a supported PNG, JPEG, WebP or SVG image.","backup.error.future_model":"The backup was created by a newer House Plan data model.","backup.error.invalid_config":"The backup contains an invalid House Plan configuration.","backup.error.wall_model_migration_blocked":"The backup wall model could not be upgraded safely. Optimize the source plan first, then export it again.","backup.error.invalid_layout":"The backup contains invalid object positions.","backup.error.invalid_content":"The backup contains invalid or inconsistent content references.","backup.error.space_not_found":"The selected space no longer exists.","backup.error.capacity_exceeded":"Adding this backup would exceed the plan limits.","backup.error.preview_expired":"The preview expired. Select the backup file again.","backup.error.preview_owner_mismatch":"This preview belongs to another Home Assistant user.","backup.error.conflict":"The plan changed after the preview. Review the refreshed summary.","backup.error.content_confirmation_required":"Confirm that unavailable local content may be detached.","backup.error.commit_failed":"The backup could not be applied safely. The previous plan was restored or is pending recovery.","backup.error.missing_plan":"A referenced plan file disappeared after the preview. Review the backup again.","backup.error.missing_content":"A referenced local attachment disappeared after the preview. Review the backup again.","backup.error.marker_control_missing":"A linked plan light is missing from the backup.","backup.error.marker_control_not_light":"A linked plan target is no longer marked as a light source.","backup.error.marker_control_self":"A light source cannot control itself.","backup.error.marker_control_cycle":"The backup contains a circular chain of light controls.","backup.error.duplicate_marker_control":"The backup contains a duplicate plan-light link.","backup.error.no_backup":"There is no import or optimization snapshot to restore.","backup.error.in_use":"The item is still in use","backup.error.invalid_data":"The request carries invalid data","backup.error.invalid_light_entity":"The leading light must be a light.* or switch.* entity","backup.error.invalid_marker_control":"Invalid marker control reference","backup.error.invalid_name":"The name is invalid","backup.error.invalid_partition_opening_host":"The opening must keep its partition host","backup.error.invalid_partition_opening_jamb_margin":"The opening leaves no physical jamb at the wall end","backup.error.invalid_passage_fields":"An open passage cannot carry door-only settings","backup.error.invalid_space_id":"Unknown space","backup.error.invalid_toggle_entity":"The toggle entity must be light.* or switch.*","backup.error.invalid_value_badge":"Invalid value badge settings","backup.error.invalid_value_badge_attribute":"Invalid value badge attribute","backup.error.invalid_value_badge_position":"Invalid value badge position","backup.error.invalid_value_badge_source":"Invalid value badge source","backup.error.invalid_vacuum_map_route":"Check how the robot's maps are assigned to spaces.","backup.error.invalid_value_source":"Invalid value source","backup.error.invalid_value_source_attribute":"Invalid value source attribute","backup.error.io_error":"A file operation failed on the server","backup.error.not_toggleable":"This device cannot be toggled","backup.error.nothing_to_repair":"Nothing to repair","backup.error.space_in_use":"The space is still referenced","backup.error.value_badge_source_required":"The value badge needs a source","backup.error.wall_model_client_outdated":"The plan was updated elsewhere — reload the page","backup.same_source":"Created on this Home Assistant instance","backup.foreign_source":"Created on another Home Assistant instance","backup.created":"Created: {value}","backup.versions":"Card {card}; integration {integration}; data model {model}","backup.count_spaces":"Spaces: {n}","backup.count_rooms":"Rooms: {n}","backup.count_walls":"Walls: {n}","backup.count_openings":"Openings: {n}","backup.count_decor":"Decor objects: {n}","backup.count_markers":"Devices: {n}","backup.count_layout":"Positions: {n}","backup.bindings":"Bindings — devices: {device}, entities: {entity}, virtual: {virtual}; positions without a space: {legacy}","backup.binding_status":"Target status — active: {active}, disabled: {disabled}, missing: {missing}","backup.missing_areas":"Areas missing on the target: {areas}","backup.dropped_marker_links":"Plan-light links outside this transferred space were omitted: {n}.","backup.room_drafts_migrated":"Legacy unfinished contours converted to ordinary walls: {drafts}; wall segments: {segments}.","backup.repaired_target_refs":"Existing references restored by this space import: {n}.","backup.preserved_unresolved_refs":"References that could not be restored unambiguously were preserved: {n}.","backup.preserved_unresolved_hint":"No data was guessed or deleted. After the import, run Optimize plans to inspect the remaining references.","backup.import_details":"Import reference details","backup.import_detail.incoming_remapped":"References updated inside the imported copy: {n}","backup.import_detail.target_repaired":"Existing references restored: {n}","backup.import_detail.preserved_unresolved":"Unresolved references preserved: {n}","backup.import_detail.collisions":"Destination conflicts preserved safely: {n}","backup.import_detail.dropped_links":"Incoming links omitted by transfer rules: {n}","backup.import_detail.bounded_lineages":"Overly nested identifiers left bounded: {n}","backup.replace_warning":"This replaces the current configuration and layout. Uploaded files are never deleted. One undo remains available until the next plan edit.","backup.foreign_bookkeeping":"Instance-specific known/new-device bookkeeping will not be imported.","backup.final_name":"New space name","backup.target_settings":"The target instance's global settings remain unchanged.","backup.duplicates":"Bindings already present: {n}","backup.skip":"Skip duplicate devices","backup.virtual_copy":"Add safe static virtual copies","backup.content":"Referenced content","backup.decor_images_summary":"Custom images: {objects} objects, {assets} files; missing files: {missing}.","backup.content_available":"available locally","backup.content_external":"external link","backup.content_detach_required":"will be detached","backup.confirm_detach":"I understand that unavailable internal plans and attachments will be detached from the imported configuration.","backup.confirm_missing_images":"I understand that missing custom images will remain as repair placeholders and other unavailable local files will be detached.","backup.replace":"Replace","backup.add":"Add space","backup.space_done":"Space imported: {rooms} rooms, {markers} devices, {refs} existing references restored","backup.full_done":"Backup restored: {spaces} spaces, {rooms} rooms, {markers} devices","backup.undo_import":"Undo last full import","backup.import_undone":"Full import undone","backdrop.large_title":"Large image","backdrop.large_body":"This image is {w}×{h} ({fileMb} MB file) and needs about {decodedMb} MB of memory to display. On tablets this can crash the page.","backdrop.unknown_body":"The image dimensions could not be read — the file may be damaged. Continuing may crash the page on tablets.","backdrop.reduced_dimensions":"Reduced copy: {w}×{h} px.","backdrop.use_downscaled":"Upload a reduced copy","backdrop.reducing":"Reducing…","backdrop.keep_original":"Keep the original","backdrop.too_large_title":"Image is too large","backdrop.too_large_body":"This image exceeds what browsers can display ({w}×{h}, limit {limit} px per side). Please reduce it in a desktop editor and upload again.","backdrop.downscale_failed":"Could not create the reduced copy. The original plan was not changed."};const cp=new WeakSet,hp=new WeakSet;function dp(e,t,i){const n=i?t.state(i):"ready";return i&&"pending"===n?(hp.has(e)||(e.inert=!0,e.setAttribute("aria-busy","true"),hp.add(e)),t.ensure(i).then(()=>{e.isConnected&&e.requestUpdate()}),cp.has(e)?"warm":"cold"):(hp.delete(e)&&(e.inert=!1,e.removeAttribute("aria-busy")),i&&(e.setAttribute("lang","fallback"===n?"en":i),cp.add(e)),"ready")}function up(){return j``}const pp=[{code:"en",nativeLabel:"English",dictionary:lp},{code:"ru",nativeLabel:"Русский",dictionary:{"editor.context_actions":"Действия: {object}","editor.tool_options":"Параметры инструмента: {tool}","editor.palette":"Палитра: {tool}","editor.open_group":"Группа инструментов: {group}","editor.group_active":"{group} — активно: {item}","editor.disabled_action":"{action} недоступно: {reason}","editor.loading":"Загружаем редактор…","editor.loading_aria":"Редактор плана загружается","editor.load_failed":"Не удалось загрузить редактор.","editor.refresh_advice":"Обновите страницу и повторите попытку.","editor.retry_advice":"Проверьте сеть и нажмите ещё раз.","version_mismatch.title":"Версии House Plan не совпадают","version_mismatch.body":"Если Home Assistant ещё перезапускается, дождитесь завершения, затем перезагрузите эту страницу.","version_mismatch.frontend":"Карточка","version_mismatch.backend":"Интеграция","version_mismatch.reload":"Перезагрузить страницу","color_picker.title":"Выбор цвета","color_picker.hue":"Оттенок","color_picker.saturation":"Насыщенность","color_picker.value":"Яркость","color_picker.hex":"Цвет HEX","color_picker.invalid_hex":"Введите цвет HEX из 3 или 6 цифр","color_picker.confirm":"ОК","btn.properties":"Свойства","btn.keep_as_walls":"Оставить стенами","btn.delete_room_keep_walls":"Удалить комнату, оставить стены","btn.delete_room_with_walls":"Удалить комнату и стены","title.markup_select":"Выбор и редактирование стен и колонн","title.markup_column":"Колонна: кликните точку сетки для квадратной колонны","markup.partition":"Перегородка","markup.column":"Колонна","markup.hint_column":"кликните точку сетки, чтобы поставить квадратную колонну","history.wall_segment":"Добавление отрезка стены","history.column_add":"Добавление колонны","history.physical_edit":"Изменение физического объекта","history.physical_delete":"Удаление физического объекта","history.physical_move":"Перемещение физического объекта","history.wall_face_batch":"Создание комнат из стен","toast.column_duplicate":"Колонна с тем же центром и внешним размером уже существует","physical.partition_properties":"Свойства перегородки","physical.column_properties":"Свойства колонны","physical.shape":"Форма","physical.square":"Квадрат","physical.circle":"Круг","physical.diameter":"Диаметр","physical.side":"Сторона","physical.rotation":"Угол поворота","physical.length":"Длина","physical.allowed_range":"Допустимо: {min}–{max} {unit}","physical.column_size_title":"Внешняя сторона квадратной колонны, создаваемой кликом (1–150 см).","card.title":"План дома","count.devices":"{n} устр.","empty.no_spaces":"Пространств пока нет.","nav.spaces":"Пространства House Plan","empty.add_first":"Добавьте первое пространство и загрузите план этажа.","empty.read_only":"Пространства не настроены. Попросите администратора добавить первое.","empty.install":"Установите интеграцию House Plan и добавьте запись в «Устройства и службы».","btn.add_space":"Добавить пространство","btn.cancel":"Отмена","btn.save":"Сохранить","btn.close":"Закрыть","btn.delete":"Удалить","btn.copy":"Копировать","btn.edit":"Редактировать","btn.open_in_ha":"Открыть в HA","btn.reset":"Сброс","btn.attach":"Прикрепить…","btn.upload":"Загрузить…","btn.replace":"Заменить…","title.zoom_in":"Приблизить","title.zoom_out":"Отдалить","title.zoom_fit":"Вписать всё","title.configure_space":"Настроить пространство","title.add_space":"Добавить пространство","title.markup_add":"Стены: рисуйте непрерывную цепочку; каждый принятый отрезок сохраняется отдельно. Shift фиксирует 45°","title.markup_merge":"Объединить: клик по одной комнате, затем по соседней с общей стеной","title.markup_split":"Разделить комнату: клик по комнате, затем две точки на её стенах","title.markup_delroom":"Удалить комнату: кликните внутри комнаты и подтвердите удаление","title.need_plan":"Загрузите подложку (план этажа)","markup.add":"Стены","markup.merge":"Объединить","markup.split":"Разделить","markup.resize":"Размер","title.markup_resize":"Изменение размера комнат: тяните доступную ручку горизонтальной или вертикальной стены","markup.hint_resize":"тяните доступную ручку стены · стена упирается в первую небезопасную позицию · Esc — отмена · Ctrl+Z — отмена шага","resize.disabled.diagonal":"Стена расположена под углом: Resize поддерживает только горизонтальные и вертикальные стены","resize.disabled.side-angle":"Примыкающая стена расположена под углом: для Resize обе примыкающие стены должны образовывать прямой угол","resize.disabled.duplicate-physical-wall":"Стену перекрывает отдельная перегородка или колонна; удалите или переместите её перед изменением размера","resize.disabled.partial-shared":"Соседняя комната использует только часть этой стены, поэтому её нельзя безопасно двигать как одну общую стену","resize.disabled.unequal-shared":"У соседней комнаты другие конечные точки или длина стены, поэтому стены нельзя безопасно двигать вместе","resize.disabled.multiple-rooms":"Перемещение затронуло бы больше двух комнат","resize.disabled.thickness-conflict":"Толщину стены нельзя безопасно сохранить","resize.disabled.opening-conflict":"Проём на этой стене нельзя безопасно переместить","resize.disabled.invalid-geometry":"Эту стену нельзя переместить без изменения структуры плана","resize.limit_stopped":"Стена остановлена: дальше нарушается ограничение стыков","resize.commit_failed":"Изменение размера отменено: итоговый план не прошёл проверку геометрии","resize.preview_failed":"Стена остановлена в последней безопасной позиции: геометрию плана нельзя сохранить без потерь","markup.opening":"Проём","markup.delete_room":"Удалить комнату","history.undo":"Отменить","history.redo":"Повторить","history.undo_named":"Отменить: {name} (Ctrl+Z)","history.redo_named":"Повторить: {name} (Ctrl+Shift+Z / Ctrl+Y)","history.undo_empty":"Нет операций для отмены","history.redo_empty":"Нет операций для повтора","history.undone":"Отменено: {name}","history.redone":"Повторено: {name}","history.add_room":"Создание комнаты","history.split_room":"Разделение комнаты","history.merge_rooms":"Объединение комнат","history.resize_room":"Изменение размера комнаты","history.wall_thickness":"Изменение толщины стены","history.add_opening":"Добавление дверного или оконного проёма","history.edit_opening":"Изменение проёма","history.move_opening":"Перемещение проёма","history.delete_opening":"Удаление проёма","history.delete_room_keep_walls":"Удаление комнаты с сохранением стен","history.delete_room_with_walls":"Удаление комнаты и её стен","history.decor_add":"Добавление объекта декора","history.decor_edit":"Изменение объекта декора","history.decor_move":"Перемещение объекта декора","history.decor_transform":"Трансформация объекта декора","history.decor_delete":"Удаление объекта декора","history.backdrop_transform":"Трансформация подложки плана","history.device_move":"Перемещение: {name}","history.device_stale":"История позиций больше неприменима и была очищена","opening.new":"Новый проём","opening.edit":"Проём","opening.door":"Дверь","opening.window":"Окно","opening.gate":"Ворота","opening.passage":"Открытый проём","opening.passage_binding_warning":"При сохранении датчик открытия и замок будут удалены.","opening.invalid_passage_fields":"У открытого проёма на плане «{room}» есть недопустимые параметры: {fields}.","opening.type_label":"Тип","opening.length_label":"Длина, см","opening.contact_label":"Датчик открытия","opening.lock_label":"Замок","opening.none":"— нет —","opening.search_ph":"Поиск: имя или entity_id…","opening.invert":"Инвертировать открыто/закрыто","opening.flip_h":"Петли с другой стороны","opening.flip_v":"Открывается в другую сторону","opening.open":"Открыто","opening.closed":"Закрыто","opening.locked":"Заперто","opening.unlocked":"Не заперто","opening.state_unknown":"недоступно","opening.no_entities":"Датчики не привязаны — статичный символ на плане.","toast.opening_no_wall":"Кликните рядом со стеной комнаты или независимой стеной","opening.host_partition":"Независимая стена","opening.partition_orphan":"Независимая стена этого проёма больше не существует","opening.partition_jamb_margin":"Оставьте от края проёма до торца стены минимум {distance}","opening.rebind_partition":"Привязать к другой независимой стене","confirm.delete_partition_openings_title":"Удалить стену и проёмы?","confirm.delete_partition_openings_body":"В стене есть проёмы: {count}. Они будут удалены вместе со стеной.","confirm.delete_partition_openings_item":"• {type}, {length}","markup.hint_points":"точек: {n} · Shift — шаг 45° · Esc — завершить цепочку · Ctrl+Z — убрать точку · при замыкании будет предложена комната","markup.hint_start":"кликните точку сетки, чтобы начать цепочку стен","tip.lqi":"средний сигнал zigbee:","tip.area":"площадь: {value}","info.device_header":"Устройство на плане","info.model":"Модель","info.state":"Состояние","info.link":"Ссылка","info.manuals":"Инструкции","info.none":"Нет дополнительной информации","marker.new_device":"Новое устройство","marker.name_label":"Имя (отображается на плане)","marker.name_ph":"Название","marker.binding_label":"Привязка к устройству HA","marker.binding_disabled":"деактивировано в Home Assistant","marker.virtual_option":"Виртуальное устройство (без привязки)","marker.search_ph":"Поиск устройства / группы…","marker.nothing_found":"ничего не найдено","marker.room_label":"Комната","marker.room_override":" (переопределить размещение)","marker.room_choose":"— выберите комнату —","marker.room_auto":"— по зоне устройства (авто) —","marker.icon_label":"Иконка","marker.icon_ph":"mdi:… (пусто = авто)","marker.display_label":"Отображение","display.badge":"Значок + состояние","display.icon_ripple":"Значок + состояние и активность","display.static_icon":"Всегда статичный значок","marker.display_hint_badge":"Значок и динамическая подложка показывают состояние устройства без обычной пульсации активности. Красная тревога сохраняется.","marker.display_hint_icon_ripple":"Значок, динамическая подложка и пульсация: короткая — для событий, постоянная — для работы, движения или присутствия. Красная тревога имеет отдельный приоритет.","marker.display_hint_value":"Значок заменяется выбранным или автоматически найденным значением Home Assistant; подложка продолжает показывать состояние. Красная тревога сохраняется.","marker.display_hint_static_icon":"Подложка в цветах темы и значок всегда остаются одинаковыми. Состояния, активность, недоступность и тревоги не меняют отображение.","marker.static_alarm_warning":"Это устройство может сообщать о тревогах. Статичный режим скрывает визуальную тревогу маркера.","marker.preview.title":"Предпросмотр отображения","marker.preview.actual":"Сейчас","marker.preview.example":"Пример","marker.preview.integration":"Интеграция","marker.preview.source":"Источник отображения","marker.preview.current_state":"Текущее состояние","marker.preview.result":"На плане","marker.preview.details":"Подробнее об источниках","marker.preview.select_source":"Выберите устройство или сущность Home Assistant, чтобы увидеть фактическое отображение.","marker.preview.unknown_provider":"Интеграция неизвестна","marker.preview.virtual_provider":"House Plan · виртуальное устройство","marker.preview.no_source":"Нет активного источника","marker.preview.no_state":"Нет текущего состояния","marker.preview.mixed_states":"Несколько разных состояний","marker.preview.multiple_sources":"Источников: {n}","marker.preview.more_sources":"ещё {n}","marker.preview.scaled":"Предпросмотр уменьшен до {n}%, чтобы поместиться. Сохранённый размер не изменится.","marker.preview.demo_short":"Показать краткую активность","marker.preview.demo_continuous":"Показать постоянную активность","marker.preview.stop_continuous":"Остановить постоянную активность","marker.preview.demo_short_notice":"Пример краткой активности; фактическое состояние устройства не меняется.","marker.preview.demo_continuous_notice":"Пример постоянной активности; фактическое состояние устройства не меняется.","marker.preview.demo_already_visible":"Текущее состояние уже показывает реальную активность или тревогу.","marker.preview.reduced_motion":"В системе включено уменьшение движения, поэтому обычная активность показана точкой.","marker.preview.reason.neutral":"Нейтральная тёмная подложка","marker.preview.reason.working":"Жёлтая подложка: устройство сейчас работает","marker.preview.reason.working_activity":"Жёлтая подложка и эффект активности: устройство сейчас работает","marker.preview.reason.open":"Оранжевая подложка: физически открыто или разблокировано","marker.preview.reason.cover_icon_state":"Нейтральная подложка; состояние и значок определяет сущность шторы или заслонки","marker.preview.reason.presence":"Эффект активности, пока обнаружено присутствие","marker.preview.reason.event":"Короткий эффект активности после события","marker.preview.reason.transition":"Эффект активности во время движения или смены состояния","marker.preview.reason.media_neutral":"Медиаустройство остаётся на нейтральной тёмной подложке, пока доступно","marker.preview.reason.unavailable":"Приглушённая нейтральная подложка: отключено или недоступно","marker.preview.reason.alarm":"Красная тревожная подложка; тревога отображается всегда","marker.preview.reason.live_states_disabled":"Оформление по живым состояниям отключено в настройках карточки","marker.preview.reason.value_no_state":"Нет подходящего значения состояния — вместо него показан значок","marker.preview.reason.value_ambiguous_sources":"Подходит несколько источников значения — вместо него показан значок","marker.preview.reason.value_non_scalar":"Источник вернул не простое значение — вместо него показан значок","marker.preview.reason.value_virtual":"У виртуального устройства нет значения HA — вместо него показан значок","marker.preview.reason.vacuum_live_plan_only":"Живая позиция и след пылесоса доступны только на полном плане","marker.preview.reason.hidden_design_preview":"Устройство скрыто на плане, но его оформление видно в предпросмотре","marker.preview.reason.composite_power_source":"Состояние берётся из сущности питания устройства; вспомогательные переключатели не учитываются","marker.preview.reason.activity_display_disabled":"Выбранный режим отображения не показывает обычные эффекты активности","marker.preview.reason.ha_disabled":"Привязка отключена в Home Assistant, поэтому устройство будет скрыто на плане","marker.preview.reason.orphaned":"Сохранённая привязка Home Assistant больше не найдена","marker.preview.reason.static_icon":"Статичный режим: состояние устройства не меняет значок","marker.activity_color":"Цвет пульсации активности","marker.ripple_size":"Размер пульсации активности","marker.activity_alarm_note":"Цвет и размер относятся только к обычной активности и не влияют на красную тревогу.","marker.pulse_a11y_alarm":"Тревога","marker.pulse_a11y_event":"Недавнее событие","marker.pulse_a11y_presence":"Обнаружено присутствие","marker.pulse_a11y_transition":"Изменение состояния","marker.pulse_a11y_running":"Работает","marker.state_a11y_neutral":"Обычное состояние","marker.state_a11y_working":"Работает","marker.state_a11y_open":"Открыто","marker.state_a11y_locked":"Заблокировано","marker.state_a11y_unlocked":"Разблокировано","marker.state_a11y_alarm":"Тревога","marker.state_a11y_unavailable":"Недоступно","marker.lqi_a11y_low":"LQI {value}, слабый сигнал","marker.lqi_a11y_mid":"LQI {value}, средний сигнал","marker.lqi_a11y_high":"LQI {value}, сильный сигнал","marker.size_label":"Размер / поворот значка","marker.angle_label":"Поворот","marker.model_label":"Модель","marker.model_ph":"напр. Aqara T&H","marker.link_label":"Ссылка","marker.desc_label":"Описание","marker.desc_ph":"Заметки, характеристики…","marker.manuals_label":"Инструкции (PDF и т.п.)","marker.sub_device":"устройство","marker.sub_z2m_group":" · Z2M-группа","marker.sub_group":"группа","marker.sub_helper":"хелпер","space.new":"Новое пространство","space.copy_title":"Копирование пространства","space.copy_name":"Название нового пространства","space.copy_fallback":"Пространство","space.copy_create":"Создать копию","space.copy_optimize_title":"Оптимизировать перед копированием?","space.copy_optimize_body":"Перед созданием «{name}» House Plan должен оптимизировать весь план, включая другие пространства. Продолжить?","space.copy_optimize_confirm":"Оптимизировать и скопировать","space.copy_error_changed":"План изменился, пока было открыто подтверждение. Проверьте его и повторите попытку.","space.copy_error_source_missing":"Исходного пространства больше нет. Снова откройте его настройки и повторите попытку.","space.copy_error_source_invalid":"House Plan не смог проверить все стены этого пространства. Исправьте исходное пространство и повторите попытку.","space.copy_error_spaces_limit":"В House Plan уже создано максимальное число пространств.","space.copy_error_partitions_limit":"В этом пространстве слишком много стен для копирования.","space.copy_error_openings_limit":"В этом пространстве слишком много проёмов для копирования.","space.copy_error_decor_limit":"В этом пространстве слишком много элементов подложки для копирования.","space.copy_error_columns_limit":"В этом пространстве слишком много колонн для копирования.","space.copy_error_opening_host":"Один из проёмов больше не привязан к стене. Исправьте или удалите его перед копированием.","space.copy_error_geometry":"Копия создаст небезопасную геометрию стен. Исправьте исходное пространство и повторите попытку.","space.copy_error_optimize_geometry":"Копирование остановлено: оптимизация всего плана небезопасна для одного из пространств.","space.header":"Пространство","space.title_label":"Название","space.title_ph":"Например: Гараж","space.plan_label":"Подложка (план)","space.no_plan":"нет подложки","space.plan_alt":"план","room.new":"Новая комната","room.name_label":"Отображаемое имя","room.name_ph":"Например: Терраса","room.area_label":"Зона Home Assistant (свободные)","room.no_area_option":"— без зоны —","room.default_name":"Комната","device.unnamed":"без имени","device.light_group":"группа света","device.fallback":"устройство","device.virtual":"виртуальное устройство","confirm.delete_room_title":"Удалить комнату «{name}»?","confirm.delete_room_body":"Выберите, нужно ли оставить физические стены, принадлежащие только этой комнате. Общие с другой комнатой стены сохраняются всегда.","confirm.remove_marker_title":"Удалить устройство с плана?","confirm.remove_marker_body":"Устройство исчезнет полностью и перестанет участвовать в данных плана. Позже его можно будет добавить заново.","confirm.erase_decor":"Стереть объект «{kind}»? Действие можно отменить из истории редактора.","confirm.delete_space_title":"Удалить пространство?","confirm.delete_space_body":"Пространство, все его комнаты и вся разметка плана будут удалены.","confirm.delete_space_vac_routes":"Также будет снято сопоставление карт роботов: {count}.","space.delete_blocked":"Это пространство всё ещё используется устройствами: {n}. Сначала перенесите их в другое пространство или удалите.","toast.pos_save_failed":"Не удалось сохранить позицию: {err}","toast.no_entity":"У устройства нет подходящей сущности","toast.ha_disabled_action":"Деактивированный объект Home Assistant нельзя использовать на плане.","toast.ha_disabled_show_device":"Деактивированное в Home Assistant устройство нельзя показать на плане. Сначала активируйте его в Home Assistant.","toast.ha_disabled_show_entity":"Деактивированную в Home Assistant сущность нельзя показать на плане. Сначала активируйте её в Home Assistant.","toast.ha_disabled_add":"Деактивированный объект Home Assistant нельзя добавить на план. Сначала активируйте его в Home Assistant.","toast.ha_binding_unverified":"Статус объекта не удалось подтвердить по реестру Home Assistant. Отображение и действия временно недоступны.","toast.markup_needs_server":"Разметка доступна после переноса конфига на сервер","toast.space_order_changed":"Порядок изменён. Если где-то этаж карточки задан номером, проверьте такие панели.","toast.conflict":"Конфиг изменён в другом окне — данные обновлены, повторите последнее действие","toast.cfg_save_failed":"Не удалось сохранить конфиг: {err}","toast.room_overlap":"Контур накладывается на комнату «{name}» — комнаты не должны накладываться","toast.contour_cannot_close":"Контур нельзя замкнуть: он вырожден или пересекает сам себя","toast.merge_not_adjacent":"Объединять можно только комнаты с общей стеной","toast.rooms_merged":"Комнаты объединены в «{name}»","toast.split_pick_wall":"Начните разрез на стене комнаты","toast.split_bad_cut":"Разрез — от стены до стены внутри комнаты, без пересечения стен и самого себя","merge.header":"Объединение комнат","merge.hint":"У объединённой комнаты одно имя и одна зона. Вторая зона освобождается — её устройства уйдут с плана, пока их не заберёт другая комната.","merge.keep":"Оставить","merge.no_area":"без зоны","toast.room_saved":"Комната сохранена ({n}). Устройств добавлено: {added}. Обведите следующую или выйдите из разметки.","toast.room_saved_no_area":"Комната сохранена ({n}, без зоны). Обведите следующую или выйдите из разметки.","toast.marker_needs_server":"Редактирование устройств доступно после переноса конфига на сервер","toast.virtual_name_required":"Укажите имя виртуального устройства","toast.marker_saved":"Устройство сохранено","toast.marker_removed":"Устройство удалено с плана","toast.integration_missing":"Интеграция House Plan не установлена — управление недоступно","toast.plan_formats":"Поддерживаются SVG, PNG, JPG, WebP","toast.plan_required":"Загрузите подложку — план этажа обязателен","toast.space_added_onboard":"Пространство добавлено. Обведите комнаты: кликайте по точкам сетки и замкните контур.","toast.space_added":"Пространство добавлено","toast.space_copied":"Пространство «{name}» создано","toast.space_saved":"Пространство сохранено","toast.space_deleted":"Пространство удалено","toast.delete_failed":"Ошибка удаления: {err}","toast.error":"Ошибка: {err}","toast.toggle_target_unavailable":"Цель «{name}» недоступна — действие не выполнено","toast.toggle_targets_unavailable":"Цели недоступны: {names}. Действие не выполнено","toast.file_failed":"Файл «{name}» не загружен: {err}","toast.files_attached":"Прикреплено файлов: {n}","err.unknown":"неизвестная ошибка","err.code":"код {code}","err.too_large":"файл больше {mb} МБ","err.bad_ext":"недопустимый тип (нужен PDF/изображение)","err.unauthorized":"нужны права администратора","editor.title":"Заголовок","editor.default_floor":"Стартовое пространство","editor.default_floor_missing":"Стартовое пространство «{id}» больше не существует. Выберите другое.","editor.floor":"Закреплённое пространство","editor.floor_none":"— не закреплять —","editor.floor_index":"YAML-индекс {index} (сохранён)","fixed_floor.loading":"Загружаем закреплённое пространство…","fixed_floor.invalid_title":"Закреплённое пространство недоступно","fixed_floor.invalid_body":"Проверьте floor в конфигурации карточки. Настроенное значение: {value}","editor.icon_size":"Размер иконок, % ширины плана","editor.show_temperature":"Показывать температуру","editor.live_states":"Живые состояния (вкл/выкл, открыто…)","editor.light_pools":"Световые пулы и тени от стен","editor.show_signal":"Показывать сигнал zigbee (LQI)","editor.language":"Язык интерфейса","editor.lang_auto":"Авто (профиль HA)","title.icon_rules":"Правила иконок: какая MDI-иконка достаётся устройству по имени","rules.title":"Правила иконок","rules.hint":"Правила проверяются сверху вниз по строке «имя устройства + модель» (regex без учёта регистра); срабатывает первое совпадение. Если ничего не подошло — решает device class сущности, затем — иконка-заглушка.","rules.pattern_ph":"regex, напр. розетк|plug","rules.icon_ph":"mdi:power-socket-de","rules.add":"Добавить правило","rules.reset":"Сбросить к умолчаниям","rules.test_ph":"Проверьте имя устройства…","rules.invalid":"некорректный regex","rules.saved":"Правила иконок сохранены","btn.up":"Вверх","btn.down":"Вниз","tap.info":"Карточка устройства","tap.more_info":"Диалог HA (more-info)","tap.toggle":"Переключить состояние","marker.tap_label":"Действие по нажатию для этого устройства","tap.toggle_note":"Под селектором показано, какое состояние изменится. Защищённые устройства не переключаются с плана.","import.title":"Создать пространства из этажей HA","import.hint":"Home Assistant уже знает эти этажи. Отметьте, какие превратить в пространства плана — далее для каждого попросим картинку плана. Комнаты затем обводятся вручную по плану.","import.start":"Создать: {n}","import.manual":"Начать с нуля","import.progress":"Этаж {i} из {n}","import.done":"Пространства созданы. Обведите комнаты: кликайте по точкам сетки и замкните контур.","btn.skip":"Пропустить","space.scale_label":"Масштаб (размер клетки сетки)","space.cell_cm.help":"Связывает сетку с реальными размерами: от значения зависят длины и площади, толщина стен, размеры проёмов и радиус свечения. Изменение после разметки меняет расчётные размеры всего пространства, но не двигает его точки на плане.","space.cell_cm.help.aria":"Подсказка: масштаб пространства","space.scale_unit":"см на клетку","space.scale_unit_imperial":"дюйм на клетку","space.display_section":"Отображение","space.show_borders":"Всегда отображать границы комнат","space.zero_wall_style":"Стены нулевой толщины","space.zero_wall_style.help":"Пунктирные стены нулевой толщины пропускают Glow и солнечные лучи, сплошные блокируют их как барьер нулевой площади. Выбор меняет все такие стены пространства, даже когда их линии скрыты в просмотре.","space.zero_wall_style.help.aria":"Подсказка: вид стен нулевой толщины","space.zero_wall_dashed":"Пунктирные","space.zero_wall_solid":"Сплошные","space.show_names":"Отображать названия комнат (перетаскиваются)","space.room_color":"Цвет границ и названий","space.opacity":"Прозрачность","space.fill_label":"Заливка комнат","space.fill_mode.help":"«Свой цвет» задаёт оформление, а «Свет», «Температура» и «LQI» используют текущие данные Home Assistant; Glow включается отдельно.","space.fill_mode.help.aria":"Подсказка: режим заливки комнат","fill.none":"Нет","fill.lqi":"По силе зигби-сигнала","fill.light":"По освещению","fill.custom":"Свой цвет","space.custom_fill":"Цвет заливки","space.source_file":"У меня есть картинка плана","space.source_draw":"Нет подложки — нарисую комнаты вручную","fill.temp":"По температуре","tip.temp_avg":"средняя температура:","tip.hum_avg":"средняя влажность:","space_card.button":"Перейти к пространству","space_card.not_found":"Пространство «{id}» не найдено","space_card.loading":"Загрузка…","continuity.restore_plan":"Восстанавливаем план…","continuity.restore_connection":"Восстанавливаем подключение к устройствам…","continuity.retry":"Повторить","editor.space":"Пространство","editor.framing":"Кадрирование","editor.fit_content":"Всё видимое содержимое","editor.fit_house":"Плотно по геометрии дома","editor.show_button":"Показывать кнопку","editor.button_label":"Текст кнопки","editor.button_target":"Путь дашборда (куда вести)","marker.sub_entity":"сущность","title.general_settings":"Общие настройки","title.export_pdf":"Сохранить в PDF","pdf.title":"Сохранение в PDF","pdf.dimensions":"Отображать размеры и площади","pdf.decor":"Отображать мебель и другой декор","pdf.room_names":"Отображать названия комнат","pdf.backdrop":"Отображать подложку","pdf.save":"Сохранить","pdf.saving":"Формируем…","pdf.failed":"Не удалось создать PDF.","pdf.too_large":"Размер изображений превышает лимит PDF 25 МБ.","pdf.asset_failed":"Не удалось загрузить подложку или изображение декора.","pdf.scale":"Масштаб 1:{n}","pdf.north":"Север","gs.title":"Общие настройки","gs.light_group":"Заливка: освещение","gs.light_on":"Свет включён","gs.light_off":"Весь свет выключен","gs.temp_group":"Заливка: температура","gs.temp_cold":"Холодно","gs.temp_ok":"Комфорт","gs.temp_hot":"Жарко","gs.lqi_group":"Заливка: зигби-сигнал","gs.lqi_low":"Слабый сигнал","gs.lqi_high":"Сильный сигнал","gs.reset":"Сбросить к умолчаниям","gs.saved":"Общие настройки сохранены","gs.radar_show_live":"Показывать текущее присутствие на плане","gs.radar_show_live_hint":"Скрывает или показывает все живые цели радаров. Это не запускает и не останавливает запись наблюдений.","radar.title":"Присутствие на плане","radar.help":"Свяжите маркер с точными сущностями радара Home Assistant, укажите положение датчика и профиль координат. Живые позиции обрезаются по выбранной комнате.","radar.help.aria":"Подсказка: настройки радара присутствия","radar.enabled":"Использовать этот радар присутствия","radar.show_live":"Показывать живые цели","radar.configure":"Настроить радар","radar.configure_on_plan":"Настроить на плане","radar.change_installation":"Сменить установку","radar.no_contour":"У комнаты нет контура. Точки радара не будут обрезаться по комнате.","radar.discard_setup_title":"Отменить настройку радара?","radar.discard_setup":"Несохранённая настройка радара будет потеряна.","radar.step_place_mount":"Укажите физическое положение датчика","radar.step_place_heading":"Укажите точку прямо перед датчиком","radar.step_reference":"Укажите контрольное положение {n}, затем начните измерение","radar.step_check_reference":"Укажите независимое проверочное положение","radar.start_measure":"Начать измерение","radar.countdown":"Встаньте в отмеченное место через {seconds} с","radar.capturing":"Стойте неподвижно и в одиночестве…","radar.fit_ready":"Калибровка готова","radar.check_third":"Проверить в другом положении","radar.check_complete":"Независимая проверка завершена","radar.error_distance":"Расхождение положения: {distance}","radar.ambiguous_target":"Обнаружено несколько целей. Повторите измерение в одиночестве.","radar.insufficient_samples":"Недостаточно актуальных координат. Повторите или настройте вручную.","radar.bad_references":"Выберите разнесённые положения в разных направлениях от датчика.","radar.ambiguous_sources":"Измерения допускают два одинаково вероятных направления. Выберите точки, по которым можно различить левую и правую стороны.","radar.bad_fit":"Измерения не совпадают. Проверьте единицы, положение датчика и контрольные точки.","radar.desktop_hint":"Для точной настройки используйте компьютер. Редактирование на тач-устройствах поддерживается по остаточному принципу.","radar.detected":"House Plan распознал признаки радара у этого устройства. Перед сохранением проверьте точные источники.","radar.detected_ld2450":"House Plan нашёл набор координат ESPHome LD2450. Перед сохранением проверьте точные источники X/Y.","radar.additional_actions":"Дополнительные действия","radar.declare":"Это радар присутствия","radar.profile":"Профиль данных","radar.profile_esphome_ld2450_v1":"ESPHome LD2450 (цели X/Y)","radar.profile_cartesian_v1":"Декартовы цели (X/Y)","radar.profile_polar_v1":"Полярная цель (дальность/угол)","radar.profile_range_v1":"Только дальность","radar.profile_zones_v1":"Состояния зон","radar.profile_presence_v1":"Только присутствие","radar.room":"Комната радара","radar.room_choose":"Выберите комнату","radar.target":"Цель {n}","radar.axis_x":"Сущность координаты X","radar.axis_y":"Сущность координаты Y","radar.add_target":"Добавить слот цели","radar.range_channel":"Канал дальности {n}","radar.add_range":"Добавить канал дальности","radar.presence_gate":"Сущность присутствия для слота","radar.swap_axes":"Поменять оси X и Y местами","radar.axis_x_sign":"Направление X","radar.axis_y_sign":"Направление Y","radar.distance_source":"Сущность дальности","radar.angle_source":"Сущность угла","radar.angle_unit":"Единица угла","radar.degrees":"Градусы","radar.radians":"Радианы","radar.angle_zero":"Направление нулевого угла","radar.angle_forward":"Вперёд","radar.angle_right":"Вправо","radar.angle_clockwise":"Угол растёт по часовой стрелке","radar.zone_source":"Сущность зоны","radar.occupancy_source":"Сущность присутствия","radar.count_source":"Сущность количества целей","radar.availability_source":"Сущность доступности","radar.source_choose":"Выберите сущность","radar.source_optional":"Необязательно","radar.source_missing":"сейчас недоступна","radar.saved_unsupported":"Сохранённая настройка радара не поддерживается или неполна. Она неактивна; удалите её либо обновите House Plan перед повторной настройкой.","radar.occupancy":"Присутствие (вкл/выкл)","radar.count":"Количество","radar.mount":"Положение и направление","radar.mount_hint":"Это физическое положение датчика. Перемещение его декоративного маркера не меняет установку.","radar.heading":"Направление, °","radar.range_cm":"Дальность, см","radar.fov_deg":"Угол обзора, °","radar.unit":"Единица источника","radar.mirror":"Отразить ось влево/вправо","radar.remove":"Удалить настройки радара","radar.invalid":"Перед сохранением заполните комнату, источники и положение радара.","radar.check_sources":"Проверить живые данные","radar.checking":"Проверяем…","radar.health":"Состояние подключения","radar.live_summary":"Текущих целей: {targets}; дуг дальности: {ranges}","radar.health_ok":"Актуальные данные получены","radar.health_off":"Цели не обнаружены","radar.health_stale":"Часть координат устарела","radar.health_partial":"Часть источников актуальна, часть устарела","radar.health_restricted":"Нет доступа к одному или нескольким источникам","radar.health_incomplete":"Текущий отчёт радара неполон","radar.health_position_unavailable":"Есть присутствие, но актуальное положение недоступно","radar.health_unavailable":"Данные датчика недоступны","radar.health_needs_setup":"Требуется настроить установку","radar.health_inconsistent":"Источники передают противоречивые данные","radar.health_unknown":"Текущее состояние неизвестно","radar.health_disabled":"Радар отключён","radar.error_invalid_radar":"Проверьте настройки радара.","radar.error_invalid_selection":"Выберите существующую комнату и допустимые источники.","radar.error_source_restricted":"Нет доступа ко всем выбранным источникам.","radar.error_rate_limited":"Слишком много запросов. Повторите чуть позже.","radar.error_not_ready":"Обработка данных радара ещё не готова.","radar.error_conflict":"План изменился. Откройте настройку радара заново и повторите попытку.","radar.error_source_unavailable":"Один или несколько выбранных источников радара недоступны.","radar.error_unsupported_capability":"Установленная интеграция не поддерживает эту возможность радара.","radar.report_age":"{seconds} с назад","space.show_lqi":"Показывать зигби-сигнал (LQI) у устройств","space.hide_decor":"Скрыть декоративный слой","space.hide_decor_tip":"Линии, фигуры, надписи и мебель остаются на месте — их видно в редакторе подложки, но не на плане.","space.hide_openings":"Скрыть проёмы","space.hide_openings_tip":"Двери, окна и ворота не рисуются, но продолжают работать: свет проходит, солнце светит в окна, датчики открытия срабатывают. В редакторе плана проёмы видно всегда.","gs.light_none":"Нет источников света","mode.plan":"Редактор плана","mode.devices":"Редактор устройств","display.value":"Значение + состояние","marker.subarea":"без зоны, вручную","device.new":"Новое устройство — откройте его редактор, чтобы снять отметку","opening.unlock_action":"Открыть замок","opening.lock_action":"Закрыть замок","opening.lock_pending":"Выполняется…","title.close_editor":"Закрыть редактор (вернуться к просмотру)","title.add_device":"Добавить устройство на план","devbar.add":"Добавить","devbar.rules":"Правила иконок","device_inbox.button":"Устройства","device_inbox.title":"Устройства на плане","device_inbox.search":"Поиск по устройствам, сущностям и интеграциям…","device_inbox.add_virtual":"Добавить виртуальное устройство","device_inbox.tab_on_plan":"На плане","device_inbox.tab_available":"Доступны","device_inbox.tab_hidden":"Скрытые","device_inbox.tab_readd":"Доступны снова","device_inbox.only_new":"Только новые","device_inbox.show_entities":"Показывать сущности","device_inbox.show_hidden":"Показывать скрытые на плане","device_inbox.show_hidden.help":"Временно показывает на плане скрытые и деактивированные маркеры служебными призраками только в редакторе устройств. Сохранённая видимость устройств не меняется.","device_inbox.show_hidden.help.aria":"Подсказка: показывать скрытые устройства на плане","device_inbox.new":"Новое","device_inbox.find":"Найти на плане","device_inbox.edit":"Настроить","device_inbox.hide":"Скрыть","device_inbox.show":"Показать","device_inbox.add":"Добавить","device_inbox.readd":"Добавить заново","device_inbox.hide_available":"Скрыть из списка","device_inbox.show_more":"Показать ещё","device_inbox.more_actions":"Другие действия","device_inbox.find_hidden_hint":"Сначала включите «Показывать скрытые на плане»","device_inbox.show_disabled":"Перед показом активируйте эту привязку в Home Assistant","device_inbox.empty_on_plan":"На плане пока нет подходящих устройств.","device_inbox.empty_available":"Нет доступных устройств для добавления.","device_inbox.empty_hidden":"Скрытых устройств нет.","device_inbox.empty_readd":"Нет удалённых устройств, доступных для повторного добавления.","device_inbox.reason_visible_auto":"Найдено автоматически","device_inbox.reason_visible_explicit":"Добавлено явно","device_inbox.reason_manual_hidden":"Скрыто пользователем","device_inbox.reason_automatic_hidden":"Скрыто автоматически","device_inbox.reason_service_entry":"Служебная запись реестра","device_inbox.reason_excluded_integration":"Исключена интеграция «{integration}»","device_inbox.reason_excluded_domain":"Непространственный тип сущности","device_inbox.reason_grouped_light":"Представлено группой света комнаты","device_inbox.reason_represented_by_parent":"Представлено родительским устройством","device_inbox.reason_removed":"Ранее удалено с плана","device_inbox.reason_available":"Можно добавить на план","device_inbox.reason_no_bound_room":"Зона HA не связана с комнатой плана","device_inbox.status_ha_disabled":"Отключено в Home Assistant","device_inbox.status_orphaned":"Привязка больше не найдена в Home Assistant","device_inbox.status_unverified":"Реестр Home Assistant временно недоступен","device_inbox.saved":"Список устройств обновлён","device_inbox.filters_excluded":"Исключённые интеграции","device_inbox.filters_group_lights":"Объединять светильники комнаты в один маркер","device_inbox.filters_preview_appear":"появится: {count}","device_inbox.filters_preview_hide":"скроется: {count}","device_inbox.filters_preview_lights":"затронет светильников: {count}","device_inbox.filters_reset":"Вернуть рекомендуемые","device_inbox.filters_save":"Сохранить фильтры","device_inbox.filters_search_ph":"Добавить интеграцию…","device_inbox.filters_title":"Фильтры обнаружения","space.roomcard_section":"В карточке комнаты:","space.label_temp":"Температура","space.label_hum":"Влажность","space.label_lqi":"Средний Zigbee-сигнал","space.label_light":"Свет вкл/выкл","roomcard.light_on":"Вкл","roomcard.light_off":"Выкл","roomcard.light_partial":"{on} из {total}","toast.split_pick_inside":"Промежуточные точки разреза — внутри комнаты","mode.decor":"Редактор подложки","decor.select":"Выбрать","decor.line":"Линия","decor.rect":"Прямоугольник","decor.ellipse":"Овал","decor.text":"Надпись","decor.erase":"Стереть","decor.erase_confirm_title":"Стереть объект?","decor.color":"Цвет","decor.width":"Толщина линии","decor.line_style":"Стиль линии","decor.line_style_solid":"Сплошная","decor.line_style_dashed":"Пунктирная","decor.fill":"Заливка","decor.fill_color":"Цвет заливки","decor.length":"Длина","decor.size":"Размер","decor.flip_h":"Отзеркалить по горизонтали","decor.flip_v":"Отзеркалить по вертикали","decor.angle":"Угол поворота, °","decor.text_size":"Размер текста","decor.backdrop_properties":"Свойства картинки-подложки","decor.text_title":"Надпись","decor.object_title":"Редактирование: {kind}","decor.text_label":"Текст","decor.live_group":"Вставить переменную HA","decor.live_entity":"Сущность","decor.live_entity_ph":"выберите сущность","decor.live_attr":"Значение","decor.live_attr_ph":"выберите состояние или атрибут","decor.live_state":"Состояние","decor.backdrop":"Картинка-подложка","decor.backdrop_hint":"Тяните картинку — перемещение; угол — размер; верхнюю ручку — поворот. Shift меняет пропорции или снимает шаг угла.","decor.backdrop_reset":"Вернуть картинку","decor.backdrop_reset_done":"Картинка вернулась на своё место и в свой размер","marker.icon_auto":"Авто: {icon} (по правилам иконок; выберите свою, чтобы заменить)","marker.icon_pin_auto":"Закрепить","mode.plan_tip":"Редактор плана — геометрия дома: рисование и объединение/разделение комнат, привязка к зонам HA, двери, окна и ворота, карточки комнат, масштаб","mode.devices_tip":"Редактор устройств — всё про значки: перетаскивание, клик — настройка привязки/иконки/отображения, виртуальные устройства, правила иконок","mode.decor_tip":"Редактор подложки — чисто визуальный декор под планом: линии, прямоугольники, овалы и надписи, не реагирующие на клики","space.glow_enabled":"Свечение источников света","gs.glow_group":"Свечение источников света","gs.glow_base":"Темнота дома","gs.glow_light":"Цвет света по умолчанию / интенсивность","gs.wall_group":"Стены","gs.wall_fill":"Цвет заливки стен","gs.glow_radius":"Радиус свечения","gs.glow_radius.help":"Задаёт общий радиус светового пятна в метрах или футах; персональный радиус устройства заменяет это значение.","gs.glow_radius.help.aria":"Подсказка: общий радиус свечения","gs.unit_m":"м","gs.unit_ft":"фут","marker.controls_label":"Управляет другими источниками света","marker.controls.help":"При действии «Переключить состояние» перечисленные источники переключаются вместе с этим маркером. Их световые пятна остаются у собственных маркеров, а эта связь сама по себе не делает управляющий маркер источником света.","marker.controls.help.aria":"Подсказка: управление другими источниками света","marker.controls_filter":"Поиск ламп и выключателей…","info.controls":"Управляет","marker.glow_radius_label":"Радиус свечения","marker.glow_radius.help":"Задаёт радиус свечения в метрах или футах; пустое значение использует радиус из общих настроек.","marker.glow_radius.help.aria":"Подсказка: радиус свечения","markup.wallthick":"Толщина","markup.select":"Выбрать","title.markup_wallthick":"Толщина — клик по стене задаёт толщину от 0 до 100 см.","markup.hint_wallthick":"клик по стене · Esc закрывает без применения","wallthick.field":"Толщина","wallthick.unit_cm":"см","wallthick.unit_in":"дюйм","wallthick.apply_room":"Применить ко всем стенам комнаты","markup.draw_wall_title":"Толщина каждого нового сегмента стены (0–100 см). Общие стены сохраняют существующее значение.","room.queue_progress":"Комната {current} из {total}","toast.wall_rooms_saved":"Создано комнат: {n}","toast.wall_chain_saved":"Цепочка стен сохранена","toast.wallthick_pick":"Кликните по стене","toast.wallthick_set":"Толщина стены задана","toast.wallthick_cleared":"Толщина стены убрана","toast.physical_range":"Введите значение от {min} до {max} {unit}","toast.zero_wall_opening_conflict":"Сначала удалите проём на этом участке стены.","toast.zero_wall_ambiguous":"Не удалось однозначно выбрать участок стены. Уточните геометрию узла.","toast.zero_wall_migration_blocked":"Пространство не преобразовано: {reason}. Данные не изменены.","toast.physical_angle":"Введите угол поворота от 0° до 90°, не включая 90°","toast.physical_limit":"В пространстве достигнут лимит объектов этого типа","toast.geometry_unsafe":"Изменение отменено: геометрию стен нельзя безопасно построить.","junction.limit_angle":"Слишком острый угол между стенами: {actual}°, минимум {limit}°.","junction.limit_valence":"Слишком много стен в одном узле: {actual}, максимум {limit}.","junction.limit_length":"Слишком короткий участок стены: {actual} см, минимум {limit} см.","junction.limit_distance":"Стены и узлы слишком близко: {actual} см, минимум {limit} см.","junction.limit_clearance":"Внутри комнаты не остаётся места: {actual} см², минимум {limit} см².","junction.limit_check_failed":"Проверку стыков выполнить не удалось — изменение не сохранено","toast.wall_model_migration_blocked":"Не удалось обновить модель стен: {reason}. План не изменён. Запустите «Оптимизировать планы»; если ошибка повторится, исправьте конфликтующую геометрию стен.","toast.wall_model_client_outdated":"Обновите карточку и перезагрузите страницу перед редактированием плана.","wall_model.reason.invalid-room":"некорректный контур комнаты","wall_model.reason.zero-length":"отрезок стены нулевой длины","wall_model.reason.third-owner":"стена принадлежит более чем двум комнатам","wall_model.reason.duplicate-id":"конфликт идентификаторов стен","wall_model.reason.thickness-conflict":"конфликт значений толщины стены","wall_model.reason.opening-host":"проём нельзя однозначно привязать к стене","toast.delete_room_pick":"Кликните внутри комнаты, которую нужно удалить","toast.plan_snap_ambiguous":"Увеличьте масштаб, чтобы выбрать узел стены","toast.wall_repair_ambiguous":"У контура несколько возможных соединений. Увеличьте масштаб и соедините стены явно.","toast.wall_repair_too_large":"Разрыв больше 2 см. Соедините стены перед созданием комнаты.","toast.wall_repair_changed":"Геометрия стен изменилась. Попробуйте создать комнату ещё раз.","toast.opening_on_zero_wall":"Проёмы на стене нулевой толщины запрещены","marker.from_ha_option":"Выбрать из списка HA","marker.show_entities":"Показывать сущности","marker.show_entities_tip":"Добавляет в список не только устройства, но и все их сущности","marker.pick_ph":"Выберите устройство…","room.open_area":"Открыть зону в HA","room.fit_action":"Вписать комнату {name}","view.volumetric":"Объёмный вид","view.flat":"Плоский вид","kiosk.title":"Размеры на этом экране","kiosk.hint":"Хранится только на этом устройстве — у каждого настенного планшета или ТВ свои удобные размеры.","kiosk.icon_scale":"Размер значков устройств","kiosk.font_scale":"Размер текста карточек комнат","editor.kiosk":"Режим настенного устройства (киоск)","editor.cycle":"Автосмена пространств каждые N секунд (киоск, 0 = выкл)","room.settings_title":"Настройки комнаты","room.settings_section":"Настройки комнаты (переопределяют пространство)","room.fill_label":"Заливка в ЭТОЙ комнате","fill.inherit":"Как у пространства","room.custom_fill_space":"Цвет пространства","room.custom_fill_own":"Цвет комнаты","room.temp_range_label":"Диапазон комфорта","room.temp_range_min":"Нижняя граница комфортной температуры","room.temp_range_max":"Верхняя граница комфортной температуры","room.temp_range_reset":"Как у пространства","room.temp_range.help":"Диапазон применяется только к этой комнате. Пустое поле наследует соответствующую границу пространства; если границы поменялись местами, House Plan использует меньшую как нижнюю, а большую как верхнюю.","room.temp_range.help.aria":"О диапазоне комфорта комнаты","room.temp_src_label":"Источник температуры","room.hum_src_label":"Источник влажности","room.src_average":"Средняя по датчикам комнаты (по умолчанию)","room.src_pick":"Конкретное устройство или сущность HA","room.src_ph":"Выберите источник…","toast.room_updated":"Комната обновлена","space.card_font":"Размер шрифта карточек комнат (всё пространство)","room.sizes_section":"Размеры шрифтов","room.name_scale":"Размер названия","room.label_scale":"Размер подписей","preview.room_name":"Гостиная","toast.cfg_reload_failed":"Не удалось перечитать план с сервера: {err}","toast.locale_load_failed":"Не удалось загрузить языковой пакет. До перезагрузки страницы используется английский.","toast.furniture_art_load_failed":"Не удалось загрузить изображения мебели. Обновите страницу, чтобы их показать.","room.settings_short":"Настройки комнаты","room.unnamed":"Комната без имени","marker.use_climate_temp":"Учитывать температуру устройства в комнате","marker.use_climate_temp_tip":"Добавляет current_temperature кондиционера или термостата в среднюю температуру комнаты. Внешний бейдж со значением настраивается отдельно ниже.","marker.value_badge_title":"Бейдж со значением","marker.value_badge.help":"Показывает одно выбранное значение рядом со значком. Не влияет на комнатные показатели, свет, Glow и действие по нажатию.","marker.value_badge.help.aria":"Подсказка: бейдж со значением устройства","marker.value_badge_enabled":"Отображать бейдж со значением","marker.value_badge_source":"Значение","marker.value_badge_source.help":"Выберите конкретное состояние, поддерживаемый атрибут или производное значение этого устройства.","marker.value_badge_source.help.aria":"Подсказка: источник значения бейджа","marker.value_badge_position":"Расположение","marker.value_badge_position.help":"Выбранная сторона сохраняется постоянно и не переворачивается автоматически у края плана.","marker.value_badge_position.help.aria":"Подсказка: расположение бейджа","marker.value_badge_right":"Справа","marker.value_badge_bottom":"Снизу","marker.value_badge_left":"Слева","marker.value_badge_top":"Сверху","marker.value_badge_empty":"У этого устройства нет доступных значений","marker.value_badge_static":"Статичный значок не показывает живые значения. Настройка сохранится.","marker.value_badge_missing":"Источник недоступен","marker.value_badge_missing_hint":"Сохранённый источник сейчас недоступен. Можно сохранить его, отключить бейдж или выбрать другой.","marker.value_badge_duplicate":"То же значение уже показано внутри значка.","marker.value_badge_state":"Состояние · {name}","marker.value_badge_marker_state":"Состояние источника света · {name}","marker.value_badge_lqi":"Качество Zigbee-сигнала (среднее)","marker.value_badge_attr_current_temperature":"Текущая температура · {name}","marker.value_badge_attr_temperature":"Целевая температура · {name}","marker.value_badge_attr_current_humidity":"Текущая влажность · {name}","marker.value_badge_attr_humidity":"Влажность · {name}","marker.value_badge_attr_current_position":"Положение · {name}","marker.value_badge_attr_percentage":"Скорость · {name}","marker.value_badge_attr_brightness":"Яркость · {name}","marker.value_badge_attr_volume_level":"Громкость · {name}","marker.value_badge_attr_battery_level":"Заряд батареи · {name}","marker.value_badge_attr_fan_speed":"Скорость вентилятора · {name}","marker.value_source":"Источник значения","marker.value_source.help":"Выберите, что заменит значок. Действие по нажатию не изменится.","marker.value_source.help.aria":"Подсказка: источник значения внутри значка","marker.value_source_auto":"Автоматически (как раньше)","marker.value_source_missing_hint":"Сохранённый источник сейчас недоступен. До его восстановления или выбора другого значения внутри будет показано —.","marker.light_role_label":"Является источником света","marker.light_role.help":"«Авто» использует фактическую роль привязанного устройства, «Всегда» принудительно создаёт собственный источник, а «Никогда» исключает его; связанные лампы выше остаются независимыми.","marker.light_role.help.aria":"Подсказка: является ли устройство источником света","marker.light_role_auto_yes":"Автоматически (источник света)","marker.light_role_auto_no":"Автоматически (не источник света)","marker.light_role_always":"Всегда источник света","marker.light_role_never":"Никогда не источник света","marker.light_entity_label":"Ведущая сущность света","marker.light_entity.help":"Для составного устройства выберите сущность, состояние, цвет и яркость которой представляют этот источник на плане. Автоматический вариант сохраняет совместимость со старыми планами.","marker.light_entity.help.aria":"Подсказка: ведущая сущность света","marker.light_entity_auto":"Автоматически ({entity})","marker.light_entity_none":"нет управляемой сущности","marker.light_entity_missing":"Сохранённая сущность {entity} недоступна. Временно используется {fallback}; выбор восстановится, если сущность вернётся.","marker.toggle_entity_label":"Переключаемая сущность","marker.toggle_entity.help":"Для составного устройства выберите собственную лампу или переключатель, которой управляет нажатие. Автоматический вариант сохраняет прежние правила цели и не зависит от ведущей сущности света.","marker.toggle_entity.help.aria":"Подсказка: переключаемая сущность","marker.toggle_entity_auto":"Автоматически ({entity})","marker.toggle_entity_none":"нет собственной управляемой сущности","marker.toggle_entity_missing":"Сохранённой сущности {entity} больше нет среди выбираемых каналов этого маркера. Временно используется {fallback}; выбор восстановится, если сущность вернётся.","marker.glow_color_label":"Цвет и яркость свечения","marker.glow_mode.help":"Используйте данные источника, задайте только цвет или зафиксируйте цвет и яркость. Минимум — 1%; чтобы отключить источник, выберите «Никогда».","marker.glow_mode.help.aria":"Подсказка: цвет и яркость свечения","marker.glow_mode_auto":"Из источника","marker.glow_mode_color":"Задать цвет","marker.glow_mode_fixed":"Задать цвет и яркость","marker.glow_color":"Цвет свечения","marker.glow_brightness":"Яркость","marker.glow_disabled_never":"Настройки свечения недоступны: маркер явно исключён из источников света.","marker.glow_disabled_auto":"В автоматическом режиме у этого маркера не найден пространственный источник света.","marker.glow_disabled_no_entity":"Для пространственного источника нет активной управляемой сущности Home Assistant.","marker.glow_passive_hint":"У источника нет собственных данных Home Assistant. Задайте цвет и яркость вручную; радиус остаётся доступным.","marker.control_broken":"Сохранённый источник отсутствует или больше не отмечен как источник света","marker.control_missing_label":"Отсутствующий источник на плане","marker.control_passive":"пассивный источник","toast.marker_control_cycle":"Такая связь создаст циклическую цепочку управления светом.","toast.marker_binding_required":"Сначала выберите устройство Home Assistant, затем добавьте управляемый источник света.","confirm.unlock_title":"Открыть замок?","confirm.unlock_body":"House Plan отправит этому замку команду открытия.","toast.files_migrate_failed":"Не удалось перенести вложения к новой привязке, ссылки остались на старые файлы: {err}","space.pick_saved":"Уже загруженные","space.pick_saved_hint":"Планы, сохранённые на сервере, включая отцеплённые ранее","space.no_saved":"На сервере пока нет сохранённых планов.","space.loading":"Загрузка…","space.used_by":"используется: {list}","space.in_use":"План используется пространством — сначала отцепите его","btn.use":"Выбрать","confirm.delete_plan_title":"Удалить файл плана?","confirm.delete_plan_body":"Файл будет удалён с сервера. Это действие нельзя отменить.","toast.plans_list_failed":"Не удалось получить список планов: {err}","toast.plan_delete_failed":"Не удалось удалить план: {err}","marker.hide":"Скрыть","marker.hide_tip":"Устройство исчезнет с плана после сохранения, но продолжит участвовать в расчёте сигнала комнаты. Вернуть его можно через каталог «Устройства» в редакторе устройств.","marker.show":"Показать","marker.show_tip":"Устройство снова появится на плане после сохранения.","marker.hidden_ghost":"Устройство скрыто пользователем","marker.ha_disabled_device":"Устройство деактивировано в Home Assistant и скрыто с плана.","marker.ha_disabled_entity":"Сущность деактивирована в Home Assistant и скрыта с плана.","marker.ha_disabled_all_entities":"У устройства нет активных сущностей Home Assistant, поэтому оно скрыто с плана.","marker.ha_registry_limited":"Полный реестр Home Assistant недоступен этому пользователю. Неподтверждённый объект временно нельзя показывать или использовать.","marker.delete_tip":"Полностью удалить устройство с плана и из всех расчётов. Позже его можно добавить заново.","tap.run":"Запустить автоматизацию/скрипт/сцену","tap.none":"Ничего не делать","marker.run_target_label":"Что запускать","marker.run_search_ph":"Поиск: автоматизация, скрипт или сцена…","marker.run_target_gone":"Цель {id} не найдена — выберите заново","marker.tap_confirm":"Спрашивать подтверждение","marker.tap_confirm_tip":"Перед выполнением показать диалог подтверждения — защита от случайных нажатий.","marker.toggle_hint_single":"Цель: {name} ({id}).","marker.virtual_light_target":"Виртуальный свет: {name}.","marker.virtual_light_current":"Ручное состояние: {state} → {effect}.","marker.virtual_light_state_on":"включён","marker.virtual_light_state_off":"выключен","marker.toggle_hint_group":"Переключатся источники ({count}): {names}.","marker.toggle_hint_current":"Сейчас: {state} → {effect}.","marker.toggle_hint_group_current":"Сейчас включено {on} из {count} → {effect}.","marker.toggle_hint_skipped":"Не будут затронуты ({count}): {targets}.","marker.toggle_effect_turn_on":"включится","marker.toggle_effect_turn_off":"выключится","marker.toggle_effect_open":"откроется","marker.toggle_effect_close":"закроется","marker.toggle_effect_stop":"остановится","marker.toggle_effect_toggle":"состояние переключится","marker.toggle_skip_missing":"не найдено","marker.toggle_skip_ha_disabled":"деактивировано в HA","marker.toggle_skip_unavailable":"недоступно","marker.toggle_skip_unsupported":"переключение не поддерживается","marker.toggle_skip_secure":"заблокировано из соображений безопасности","marker.toggle_none_no_binding":"У устройства нет привязки, состояние переключать нечем. По нажатию ничего не произойдёт.","marker.toggle_none_no_actionable_entity":"У устройства нет состояния, которое можно переключить. По нажатию ничего не произойдёт.","marker.toggle_none_configured_targets_missing":"Настроенные цели сейчас недоступны. Собственная сущность устройства не будет подставлена вместо них.","marker.toggle_none_ha_disabled":"Цель деактивирована в Home Assistant и не может использоваться на плане.","marker.toggle_none_unavailable":"Цель сейчас недоступна. По нажатию ничего не произойдёт.","marker.toggle_none_unsupported":"Для этой сущности Home Assistant не предоставляет безопасного переключения. По нажатию ничего не произойдёт.","marker.toggle_none_secure":"Переключение замков, сигнализации и защитных ворот с плана заблокировано из соображений безопасности.","run.automation":"автоматизация","run.script":"скрипт","run.scene":"сцена","confirm.tap_run":"Запустить «{name}»?","confirm.tap_toggle":"Переключить «{name}»?","confirm.current_state":"Текущее состояние: {state}","confirm.expected_state":"После переключения: {state}","confirm.group_current":"включено {on} из {total}","confirm.group_all_on":"все включены","confirm.group_all_off":"все выключены","confirm.unavailable_targets":"Недоступно: {count}","confirm.expected_by_ha":"Состояние определит Home Assistant","confirm.state_on":"Включено","confirm.state_off":"Выключено","confirm.state_open":"Открыто","confirm.state_closed":"Закрыто","confirm.state_opening":"Открывается","confirm.state_closing":"Закрывается","confirm.state_stopped":"Остановлено","confirm.state_unknown":"Неизвестно","toast.run_started":"Запущено: {name}","toast.run_target_missing":"Цель запуска не найдена — проверьте настройки устройства","toast.run_target_required":"Выберите автоматизацию, скрипт или сцену","toast.tap_target_changed":"Цель действия изменилась. Повторите попытку.","toast.virtual_light_toggle_failed":"Не удалось переключить виртуальный свет: {err}","toast.value_badge_source_required":"Выберите значение для бейджа","btn.run":"Выполнить","vac.section":"Робот-пылесос: живая позиция","vac.autocal":"Настроить автоматически","vac.live":"Живая позиция на плане","vac.trail":"Показывать путь робота","vac.autocal_no_rooms":"Интеграция не отдаёт список комнат — откройте «Подогнать вручную»","vac.route_warn_unmapped":"Робот убирает на карте, которая не сопоставлена ни одному этажу","vac.route_warn_needs_calibration":"Карта сопоставлена этажу, но не откалибрована","vac.route_warn_ambiguous":"Две карты неразличимы — этаж не выбран","vac.route_warn_missing_space":"Пространство этой карты удалено","vac.autocal_no_match":"Не совпали имена комнат (нужно ≥3 общих) — откройте «Подогнать вручную»","vac.autocal_done":"Готово: привязка по {rooms} комнатам. Запустите уборку и проверьте","vac.cal_need_pos":"Робот сейчас не отдаёт координаты — запустите уборку и поставьте на паузу","vac.cal_done":"Калибровка сохранена. Запустите уборку и проверьте","vac.cal_cancelled":"Калибровка отменена","vac.fit":"Подогнать вручную","vac.fit_hint":"Перетащите карту робота на место, растяните за уголки","vac.fit_rotate":"Повернуть 90°","vac.fit_mirror":"Отразить","vac.trail_never":"Не показывать никогда","vac.trail_cleaning":"Во время уборки","vac.trail_always":"Показывать всегда","gs.bg_group":"Фон сцены","gs.bg_color":"Цвет фона вокруг плана","gs.bg_default":"Как в теме","gs.bg_theme":"по умолчанию — из темы","gs.bg_mode":"Фон плана","gs.bg_mode.help":"«Следует за Солнцем» использует sun.sun, а при недоступности — локальные часы браузера; статичный режим всегда показывает выбранный цвет.","gs.bg_mode.help.aria":"Подсказка: общий фон плана","gs.bg_static":"Статичный цвет","gs.bg_daynight":"Следует за Солнцем","gs.sun_group":"Солнце","gs.sun_missing":"Сущность sun.sun не найдена — фон следует локальным часам, а оконные лучи недоступны.","gs.north":"Север на плане","gs.north.help":"Угол отсчитывается по часовой стрелке от верхней вертикали плана; север нужен для оконных лучей, а не для фона «Следует за Солнцем».","gs.north.help.aria":"Подсказка: общее направление севера","gs.north_ph":"не задан","gs.north_clear":"Сбросить","gs.north_letter":"С","gs.sun_rays":"Солнце в окнах","gs.sun_ray_origin":"Лучи солнца","gs.sun_ray_origin.inner":"От внутренних углов окон","gs.sun_ray_origin.outer":"От внешних углов окон","gs.about_version":"Houseplan Card v{v}","gs.about_github":"GitHub · документация и issues","gs.about_telegram":"Чат в Telegram","support.title":"Помощь и обратная связь","space.bg_color":"Цвет фона вокруг плана","space.bg_inherit":"Наследовать общий","space.bg_inherited":"наследуется из общих настроек","space.bg_mode":"Фон плана","space.bg_mode.help":"Выберите наследование общего фона либо переопределите это пространство статичным цветом или режимом «Следует за Солнцем».","space.bg_mode.help.aria":"Подсказка: фон пространства","space.north":"Север на плане (переопределение)","space.north.help":"Переопределяет общий север для этого пространства; угол отсчитывается по часовой стрелке от верхней вертикали плана и используется оконными лучами.","space.north.help.aria":"Подсказка: север для пространства","space.north_inherited":"наследуется: {v}","space.sun_rays":"Солнце в окнах","space.sun_inherit":"Наследовать общий","space.sun_on":"Вкл","space.sun_off":"Выкл","canvas.far_objects":"Объектов далеко от плана: {n}","canvas.show_far":"Показать","canvas.home_tip":"План там — нажмите, чтобы вписать","gs.grid_group":"Обслуживание планов","gs.grid_hint":"Обновляет модели данных, выравнивает элементы по сетке и объединяет лишние фрагменты стен. Перед записью будет показан точный отчёт.","gs.align_all":"Оптимизировать планы","gs.align_title":"Оптимизировать планы","gs.align_none":"Все планы уже используют актуальную и оптимальную модель данных.","gs.optimize_no_automatic_changes":"Автоматических изменений нет. Проверьте пункты ниже.","gs.align_count":"Сдвинется элементов: {n} из {total}, максимум на {cm} см.","gs.align_where":"Наибольший сдвиг — в пространстве «{s}».","gs.align_turned":"Проёмов с исправлением угла: {n}.","gs.align_preflight_failed":"Не удалось безопасно проверить геометрию следующих пространств: {spaces}{more}.","gs.align_preflight_hint":"Планы не изменены. Скопируйте диагностику кнопкой ниже и приложите её к отчёту об ошибке вместе с экспортом пространства.","gs.preflight_reason_prepare-exception":"Не удалось подготовить геометрию пространства (исключение при сборке модели)","gs.preflight_reason_wall-null":"Тело стен не построилось (объединение вернуло пустоту)","gs.preflight_reason_wall-degraded-extra":"Тело стен деградировало с лишней геометрией","gs.preflight_reason_wall-failed-core":"Ядро тела стен не собралось","gs.preflight_reason_wall-exception":"Построение стен упало с исключением","gs.preflight_reason_floor-null":"Контур пола не построился","gs.preflight_reason_floor-exception":"Построение пола упало с исключением","gs.preflight_copy":"Скопировать диагностику","gs.preflight_copied":"Диагностика скопирована","gs.preflight_update_hint":"Версии карточки и интеграции различаются — обновите House Plan и повторите.","gs.align_preflight_space":"Пространство {n}","gs.align_preflight_more":" и ещё {n}","gs.optimize_changes":"Миграций модели: {m}; обновлено пространств: {c}; устранён шум координат: {p}; объединено отрезков реальных стен: {w}; объединено отрезков стен нулевой толщины: {s}; независимых: {i}.","gs.zero_walls_migrated":"Преобразовано виртуальных участков: {n}.","gs.wall_segments_migrated":"Стабилизировано сегментов стен: {n}.","gs.room_drafts_migrated":"Незавершённые контуры преобразованы в обычные стены: {drafts}; отрезков: {segments}.","gs.optimize_lattice_summary":"Канонизировано шумовых значений координат: {n}; максимальный сдвиг: {cm} см.","gs.optimize_lattice_space":"{space}: канонизировано значений координат: {n}; оставлено значений вне сетки: {far}.","gs.optimize_coincident_partitions":"Скрытые участки независимых стен поглощены стенами комнат: {n}.","gs.optimize_openings_rehosted":"Проёмы перепривязаны к стенам комнат: {n}.","gs.optimize_walls_straightened":"Выпрямлено стен: {n}; максимальное перемещение: {cm} см.","gs.optimize_walls_straightened_where":"Максимальная правка стены: {s}.","gs.optimize_walls_straighten_skipped":"Оставлено почти осевых стен, которые нельзя безопасно выпрямить: {n}.","gs.optimize_glow_migration":"Старый Glow: пространств — {spaces} → без заливки данных + независимый Glow; комнат — {rooms} → наследуемая заливка + независимый Glow.","gs.optimize_references":"Исправлено ссылок: пространства — {spaces}; комнаты — {rooms}; позиции — {positions}; устройств отвязано от отсутствующих пространств — {detached}.","gs.optimize_reference_more":", и ещё {n}","gs.optimize_orphans_removed":"Убрано забытых записей: {total} — подписи комнат: {rooms}; устройства: {devices}; групповые метки: {groups}. Все они принадлежали пространствам, удалённым ранее.","gs.optimize_live_positions":"Старые позиции в удалённых пространствах принадлежат существующим объектам: {n}{names}. Они будут сохранены.","gs.optimize_live_positions_remove":"Старые позиции в удалённых пространствах принадлежат существующим объектам: {n}{names}. Они выбраны для удаления.","gs.optimize_live_names":": {names}{more}","gs.optimize_live_remove":"Убрать старые позиции","gs.optimize_live_keep":"Сохранить старые позиции","gs.optimize_live_selected":"Старые позиции будут убраны после применения оптимизации.","gs.optimize_unverified":"Не удалось безопасно проверить позиций: {n}. Они оставлены без изменений.","gs.optimize_registry_limited":"Для безопасной проверки нужен полный доступ администратора к реестрам Home Assistant.","gs.optimize_vacuum_warning":"Сопоставления комнат пылесоса требуют проверки: {n}.","gs.optimize_details":"Подробности","gs.optimize_details_more":"И ещё записей: {n}.","gs.optimize_detail_removed":"будет удалено","gs.optimize_detail_live":"будет сохранено","gs.optimize_detail_unverified":"не проверено","gs.optimize_detail_room_label":"подпись комнаты","gs.optimize_detail_device":"устройство","gs.optimize_detail_group":"групповая метка","gs.optimize_detail_unknown":"неизвестный владелец","gs.optimize_detail_item":"{status}: {kind} {id}; прежнее пространство {space}","gs.align_warn":"Элементы, намеренно поставленные между узлами, будут сдвинуты. После операции доступна одна отмена — только до следующего изменения плана.","gs.align_run":"Оптимизировать","gs.align_done":"Планы оптимизированы: сдвинуто элементов — {n}, обслужено записей — {m}, исправлено ссылок — {r}","gs.optimize_undo":"Отменить последнюю оптимизацию","gs.optimize_undone":"Последняя оптимизация отменена","decor.furniture":"Мебель","decor.image":"Изображение","decor.image_title":"Свои изображения","decor.image_upload":"Загрузить изображение","decor.image_replace":"Заменить изображение","decor.image_uploading":"Загрузка…","decor.image_asset":"Файл изображения","decor.image_pick_hint":"Загрузите изображение или выберите уже используемое в House Plan.","decor.image_place_hint":"Кликните по плану, чтобы разместить изображение.","decor.image_none":"Загруженных изображений пока нет.","decor.image_unavailable":"Изображение недоступно","decor.image_used":"Используется в объектах: {n}","decor.image_upload_failed":"Не удалось загрузить изображение: {err}","decor.image_error_capacity":"Хранилище пользовательских изображений заполнено.","decor.image_in_use":"Перед удалением файла удалите все размещённые копии.","decor.image_delete_title":"Удалить файл изображения?","decor.image_delete_message":"Удалить «{name}» из House Plan? Это действие нельзя отменить.","furn.title":"Библиотека мебели","furn.symbol":"Символ","furn.group_furniture":"Мебель","furn.group_appliance":"Техника","furn.group_sanitary":"Сантехника","furn.group_other":"Прочее","furn.width":"Ширина","furn.depth":"Глубина","furn.back_to_categories":"Все категории","furn.pick_hint":"Выберите категорию, затем символ.","furn.place_hint":"Кликните по плану — предмет встанет к ближайшей стене. Shift — свободно.","furn.cat_air_conditioner":"Кондиционеры","furn.cat_armchair":"Кресла","furn.cat_bathtub":"Ванны","furn.cat_bed":"Кровати","furn.cat_bidet":"Биде","furn.cat_boiler":"Бойлеры","furn.cat_chair":"Стулья","furn.cat_coffee_table":"Журнальные столы","furn.cat_cooktop":"Варочные панели","furn.cat_dining_table":"Обеденные столы","furn.cat_dishwasher":"Посудомоечные машины","furn.cat_dryer":"Сушильные машины","furn.cat_fireplace":"Камины","furn.cat_fridge":"Холодильники","furn.cat_kitchen_cabinet":"Кухонные шкафы","furn.cat_kitchen_sink":"Кухонные мойки","furn.cat_nightstand":"Тумбы","furn.cat_plant":"Растения","furn.cat_rug":"Ковры","furn.cat_shelving":"Стеллажи","furn.cat_shower":"Душевые","furn.cat_sink":"Раковины","furn.cat_sofa":"Диваны","furn.cat_stairs":"Лестницы","furn.cat_toilet":"Унитазы","furn.cat_tv":"Телевизоры","furn.cat_wardrobe":"Шкафы","furn.cat_washer":"Стиральные машины","furn.cat_work_table":"Рабочие столы","furn.sym_sofa":"Диван двухместный","furn.sym_sofa_three_seat":"Диван трёхместный","furn.sym_sofa_corner_right":"Угловой диван, правый","furn.sym_armchair":"Кресло мягкое","furn.sym_armchair_office":"Кресло офисное","furn.sym_coffee_table":"Журнальный стол, прямоугольный","furn.sym_coffee_table_round":"Журнальный стол, круглый","furn.sym_coffee_table_oval":"Журнальный стол, овальный","furn.sym_coffee_table_rounded":"Журнальный стол, скруглённый","furn.sym_table_dining":"Обеденный стол, прямоугольный","furn.sym_table_round":"Круглый стол","furn.sym_table_dining_oval":"Обеденный стол, овальный","furn.sym_table_dining_rounded":"Обеденный стол, скруглённый","furn.sym_chair":"Стул","furn.sym_chair_bar":"Барный стул","furn.sym_desk":"Рабочий стол, прямоугольный","furn.sym_desk_corner":"Рабочий стол, угловой","furn.sym_bed_double":"Двуспальная кровать","furn.sym_bed_single":"Односпальная кровать","furn.sym_nightstand":"Тумба прикроватная","furn.sym_cabinet_tv":"Тумба под телевизор","furn.sym_cabinet_shoe":"Тумба для обуви","furn.sym_cabinet_sink":"Тумба под раковину","furn.sym_wardrobe":"Шкаф гардеробный","furn.sym_bookshelf":"Шкаф книжный","furn.sym_wall_unit":"Шкаф-стенка","furn.sym_kitchen_floor":"Кухонный напольный модуль","furn.sym_kitchen_floor_corner":"Кухонный напольный угловой модуль","furn.sym_kitchen_wall":"Кухонный навесной модуль","furn.sym_kitchen_wall_corner":"Кухонный навесной угловой модуль","furn.sym_shelf_floor":"Стеллаж напольный","furn.sym_shelf_wall":"Полка настенная","furn.sym_fridge":"Холодильник","furn.sym_stove":"Варочная панель, 4 конфорки","furn.sym_cooktop_two":"Варочная панель, 2 конфорки","furn.sym_dishwasher":"Посудомоечная машина","furn.sym_washer":"Стиральная машина","furn.sym_dryer":"Сушильная машина","furn.sym_tv":"Телевизор на подставке","furn.sym_tv_wall":"Телевизор на кронштейне","furn.sym_ac":"Кондиционер","furn.sym_water_heater":"Бойлер","furn.sym_toilet":"Унитаз напольный","furn.sym_toilet_built_in":"Унитаз встроенный","furn.sym_bathtub":"Ванна прямоугольная","furn.sym_bathtub_corner":"Ванна угловая","furn.sym_shower":"Душ","furn.sym_sink":"Раковина","furn.sym_kitchen_sink":"Кухонная мойка одинарная","furn.sym_kitchen_sink_double":"Кухонная мойка двойная","furn.sym_bidet":"Биде напольное","furn.sym_bidet_built_in":"Биде встроенное","furn.sym_stairs":"Лестница","furn.sym_fireplace":"Камин","furn.sym_plant":"Растение","furn.sym_rug":"Ковёр","common.yes":"Да","common.no":"Нет","vac.diag_source":"Источник","vac.diag_platform":"Интеграция","vac.diag_status":"Статус","vac.diag_position":"Позиция","vac.diag_rooms":"Комнаты","vac.diag_rooms_value":"{total} · совпало имён: {matched} · {readiness}","vac.autocal_ready":"автокалибровка доступна","vac.autocal_not_ready":"нужно 3 совпавших имени","vac.diag_path":"Путь интеграции","vac.diag_map":"ID карты","vac.source_none":"не выбран","vac.source_status_ok":"Готов","vac.source_status_missing":"Не найден","vac.source_status_disabled":"Деактивирован в Home Assistant","vac.source_status_unavailable":"Недоступен","vac.source_status_unverified":"Нельзя проверить с текущими правами","vac.source_status_unsupported":"Нет данных позиции","vac.source_status_none":"Нет источника","vac.source_banner_missing":"Сохранённый источник больше не существует. Он не заменён автоматически: выберите другой или восстановите его в Home Assistant.","vac.source_banner_disabled":"Сохранённый источник деактивирован в Home Assistant. Активируйте его там или выберите другой.","vac.source_banner_unverified":"Текущих прав Home Assistant недостаточно для проверки источника. Привязка сохранена и не будет заменена автоматически.","vac.choose_source":"Выбрать источник","vac.source_auto":"Автоматически","vac.source_auto_hint":"Использовать совместимую сущность этого устройства","vac.all_cameras":"Все камеры","vac.all_cameras_warn":"Камера может не отдавать данные робота. Выбирайте её только если это карта вашего пылесоса.","vac.all_cameras_empty":"Других сущностей камеры не найдено.","vac.platform_unknown":"интеграция неизвестна","vac.cap_position":"позиция","vac.cap_rooms_short":"комнаты","vac.cap_path":"путь","vac.cap_map":"ID карты","vac.cap_none":"данные робота не обнаружены","vac.xcme_hint":"Включите атрибуты Xiaomi Cloud Map Extractor:","vac.documentation":"Документация","vac.residual_title":"Проверьте автокалибровку","vac.residual_message":"Совпавшие комнаты расходятся максимум на {error}. Примените приблизительную калибровку, подгоните её вручную либо отмените без изменения сохранённых настроек.","vac.apply_proposal":"Применить","gs.backup_group":"Резервная копия и перенос","gs.backup_hint":"Скачайте переносимую JSON-копию или проверьте и импортируйте копию, созданную House Plan.","backup.export_open":"Экспорт","backup.import_open":"Импорт","backup.export_title":"Экспорт House Plan","backup.import_title":"Импорт House Plan","backup.export_hint":"Выберите, должна ли копия содержать всю конфигурацию House Plan или только текущее пространство.","backup.full":"Полная копия","backup.current_space":"Текущее пространство","backup.current_space_title":"Текущее пространство: {title}","backup.no_current_space":"Нет текущего пространства","backup.plan_only":"Только планировка","backup.plan_only_hint":"Сохранить комнаты, стены, проёмы, декор и позиции подписей комнат без устройств и привязок Home Assistant.","backup.plan_only_preview":"Файл содержит только планировку","backup.privacy_warning":"Архив сохраняет названия, идентификаторы Home Assistant и точные координаты. Внутренние планы и вложения указываются ссылками, но не вкладываются; текущие состояния и маршруты пылесосов не включаются.","backup.download":"Скачать JSON","backup.export_done":"Резервная копия скачана","backup.reading":"Проверяем резервную копию…","backup.revalidated":"После предпросмотра план изменился. Сводка обновлена — проверьте её и подтвердите ещё раз.","backup.error.support_invalid_message":"Проверьте сообщение для поддержки и повторите попытку.","backup.error.support_package_too_large":"Обезличенный пакет для поддержки превышает лимит 8 МиБ.","backup.error.support_preview_expired":"Предпросмотр вложения для поддержки истёк или больше недоступен.","backup.error.support_rate_limited":"Запрошено слишком много репортов или предпросмотров. Повторите позже.","backup.error.support_rejected":"Репорт не прошёл проверку службы поддержки.","backup.error.support_unavailable":"Закрытая служба поддержки временно недоступна.","backup.error.unauthorized":"У вас нет прав на экспорт или импорт этого плана.","backup.error.not_ready":"House Plan ещё не готов. Повторите попытку через несколько секунд.","backup.error.too_large":"Размер резервной копии превышает 8 МиБ.","backup.error.invalid_json":"Выбранный файл не является корректным JSON.","backup.error.invalid_format":"Выбранный файл не является резервной копией House Plan.","backup.error.invalid_image":"Изображение повреждено или не соответствует своему формату.","backup.error.unsupported_export_version":"Эта версия формата резервной копии не поддерживается установленной версией.","backup.error.unsupported_image":"Используйте поддерживаемое изображение PNG, JPEG, WebP или SVG.","backup.error.future_model":"Резервная копия создана в более новой версии модели данных House Plan.","backup.error.invalid_config":"Резервная копия содержит некорректную конфигурацию House Plan.","backup.error.wall_model_migration_blocked":"Не удалось безопасно обновить модель стен из резервной копии. Сначала оптимизируйте исходный план и повторите экспорт.","backup.error.invalid_layout":"Резервная копия содержит некорректные позиции объектов.","backup.error.invalid_content":"Резервная копия содержит некорректные или несогласованные ссылки на файлы.","backup.error.space_not_found":"Выбранное пространство больше не существует.","backup.error.capacity_exceeded":"Добавление этой копии превысит ограничения размера плана.","backup.error.preview_expired":"Время предпросмотра истекло. Выберите файл резервной копии заново.","backup.error.preview_owner_mismatch":"Этот предпросмотр принадлежит другому пользователю Home Assistant.","backup.error.conflict":"После предпросмотра план изменился. Проверьте обновлённую сводку.","backup.error.content_confirmation_required":"Подтвердите отсоединение недоступных локальных файлов.","backup.error.commit_failed":"Не удалось безопасно применить копию. Предыдущий план восстановлен или ожидает восстановления.","backup.error.missing_plan":"После предпросмотра исчез связанный файл плана. Проверьте копию ещё раз.","backup.error.missing_content":"После предпросмотра исчез связанный локальный файл. Проверьте копию ещё раз.","backup.error.marker_control_missing":"В резервной копии отсутствует связанный источник света на плане.","backup.error.marker_control_not_light":"Связанная цель больше не отмечена как источник света.","backup.error.marker_control_self":"Источник света не может управлять самим собой.","backup.error.marker_control_cycle":"Резервная копия содержит циклическую цепочку управления светом.","backup.error.duplicate_marker_control":"Резервная копия содержит повторяющуюся связь с источником света.","backup.error.no_backup":"Нет снимка импорта или оптимизации, который можно восстановить.","backup.error.in_use":"Элемент ещё используется","backup.error.invalid_data":"Запрос содержит некорректные данные","backup.error.invalid_light_entity":"Ведущий свет должен быть сущностью light.* или switch.*","backup.error.invalid_marker_control":"Некорректная ссылка управления маркером","backup.error.invalid_name":"Некорректное имя","backup.error.invalid_partition_opening_host":"Проём должен сохранить свою перегородку-носитель","backup.error.invalid_partition_opening_jamb_margin":"Проём не оставляет физического простенка у края стены","backup.error.invalid_passage_fields":"Открытый проход не может нести настройки двери","backup.error.invalid_space_id":"Неизвестное пространство","backup.error.invalid_toggle_entity":"Сущность переключения должна быть light.* или switch.*","backup.error.invalid_value_badge":"Некорректные настройки бейджа значения","backup.error.invalid_value_badge_attribute":"Некорректный атрибут бейджа значения","backup.error.invalid_value_badge_position":"Некорректная позиция бейджа значения","backup.error.invalid_value_badge_source":"Некорректный источник бейджа значения","backup.error.invalid_vacuum_map_route":"Проверьте сопоставление карт робота пространствам.","backup.error.invalid_value_source":"Некорректный источник значения","backup.error.invalid_value_source_attribute":"Некорректный атрибут источника значения","backup.error.io_error":"Файловая операция на сервере не удалась","backup.error.not_toggleable":"Это устройство нельзя переключить","backup.error.nothing_to_repair":"Нечего чинить","backup.error.space_in_use":"На пространство ещё есть ссылки","backup.error.value_badge_source_required":"Бейджу значения нужен источник","backup.error.wall_model_client_outdated":"План обновлён в другом месте — перезагрузите страницу","backup.same_source":"Создано на этом экземпляре Home Assistant","backup.foreign_source":"Создано на другом экземпляре Home Assistant","backup.created":"Создано: {value}","backup.versions":"Карточка {card}; интеграция {integration}; модель данных {model}","backup.count_spaces":"Пространств: {n}","backup.count_rooms":"Комнат: {n}","backup.count_walls":"Стен: {n}","backup.count_openings":"Проёмов: {n}","backup.count_decor":"Объектов декора: {n}","backup.count_markers":"Устройств: {n}","backup.count_layout":"Позиций: {n}","backup.bindings":"Привязки — устройства: {device}, сущности: {entity}, виртуальные: {virtual}; позиций без пространства: {legacy}","backup.binding_status":"Статус на целевом экземпляре — активных: {active}, деактивированных: {disabled}, отсутствующих: {missing}","backup.missing_areas":"На целевом экземпляре отсутствуют зоны: {areas}","backup.dropped_marker_links":"Связи с источниками света вне переносимого пространства пропущены: {n}.","backup.room_drafts_migrated":"Старые незавершённые контуры преобразованы в обычные стены: {drafts}; отрезков: {segments}.","backup.repaired_target_refs":"Существующих ссылок восстановлено этим импортом: {n}.","backup.preserved_unresolved_refs":"Неоднозначные ссылки сохранены без изменений: {n}.","backup.preserved_unresolved_hint":"House Plan ничего не угадывал и не удалял. После импорта запустите «Оптимизировать планы», чтобы проверить оставшиеся ссылки.","backup.import_details":"Подробности восстановления ссылок","backup.import_detail.incoming_remapped":"Ссылок обновлено внутри импортируемой копии: {n}","backup.import_detail.target_repaired":"Существующих ссылок восстановлено: {n}","backup.import_detail.preserved_unresolved":"Неразрешимых ссылок сохранено: {n}","backup.import_detail.collisions":"Конфликтов назначения безопасно сохранено: {n}","backup.import_detail.dropped_links":"Входящих связей пропущено по правилам переноса: {n}","backup.import_detail.bounded_lineages":"Чрезмерно вложенных идентификаторов ограничено: {n}","backup.replace_warning":"Текущая конфигурация и расположение будут заменены. Загруженные файлы не удаляются. Одну отмену можно выполнить до следующего изменения плана.","backup.foreign_bookkeeping":"Служебные списки известных и новых устройств другого экземпляра импортированы не будут.","backup.final_name":"Название нового пространства","backup.target_settings":"Глобальные настройки целевого экземпляра не изменятся.","backup.duplicates":"Уже существующих привязок: {n}","backup.skip":"Пропустить повторяющиеся устройства","backup.virtual_copy":"Добавить безопасные статичные виртуальные копии","backup.content":"Связанное содержимое","backup.decor_images_summary":"Свои изображения: объектов — {objects}, файлов — {assets}; отсутствует файлов — {missing}.","backup.content_available":"доступно локально","backup.content_external":"внешняя ссылка","backup.content_detach_required":"будет отвязано","backup.confirm_detach":"Я понимаю, что недоступные внутренние планы и вложения будут отвязаны от импортируемой конфигурации.","backup.confirm_missing_images":"Я понимаю, что отсутствующие свои изображения останутся восстанавливаемыми заглушками, а остальные недоступные локальные файлы будут отвязаны.","backup.replace":"Заменить","backup.add":"Добавить пространство","backup.space_done":"Пространство импортировано: комнат — {rooms}, устройств — {markers}, существующих ссылок восстановлено — {refs}","backup.full_done":"Копия восстановлена: пространств — {spaces}, комнат — {rooms}, устройств — {markers}","backup.undo_import":"Отменить последний полный импорт","backup.import_undone":"Полный импорт отменён","backdrop.large_title":"Большое изображение","backdrop.large_body":"Изображение {w}×{h} ({fileMb} МБ), для показа потребуется около {decodedMb} МБ памяти. На планшетах это может привести к падению страницы.","backdrop.unknown_body":"Не удалось прочитать размеры изображения — файл может быть повреждён. Продолжение может привести к падению страницы на планшете.","backdrop.reduced_dimensions":"Уменьшенная копия: {w}×{h} px.","backdrop.use_downscaled":"Загрузить уменьшенную копию","backdrop.reducing":"Уменьшаем…","backdrop.keep_original":"Оставить оригинал","backdrop.too_large_title":"Изображение слишком большое","backdrop.too_large_body":"Изображение превышает возможности браузера ({w}×{h}, предел {limit} px по стороне). Уменьшите его в редакторе на компьютере и загрузите снова.","backdrop.downscale_failed":"Не удалось создать уменьшенную копию. Текущий план не изменён."}},{code:"de",nativeLabel:"Deutsch",loadDictionary:async function(e){const t=0===e?await import("./de-BrzcYO-1.js"):await import(new URL("./de-BrzcYO-1.js?retry",import.meta.url).href);return{dictionary:t.dictionary,fingerprint:t.fingerprint}}},{code:"fr",nativeLabel:"Français",loadDictionary:async function(e){const t=0===e?await import("./fr-CLHfUBDP.js"):await import(new URL("./fr-CLHfUBDP.js?retry",import.meta.url).href);return{dictionary:t.dictionary,fingerprint:t.fingerprint}}}],_p=lp,mp=new Set;const gp=new class{constructor(e,t,i=console.warn,n){this.entries=e,this.expectedFingerprint=t,this.warn=i,this.loadFailed=n,this.dictionaries=new Map,this.pending=new Map,this.failed=new Set;for(const t of e)t.dictionary&&this.dictionaries.set(t.code,t.dictionary)}state(e){return this.dictionaries.has(e)?"ready":this.failed.has(e)?"fallback":"pending"}dictionary(e){return this.dictionaries.get(e)}ensure(e){if("pending"!==this.state(e))return Promise.resolve();const t=this.pending.get(e);if(t)return t;const i=this.entries.find(t=>t.code===e),n=this.load(i).finally(()=>this.pending.delete(e));return this.pending.set(e,n),n}async load(e){if(!e?.loadDictionary)return void(e&&this.failed.add(e.code));let t;for(const i of[0,1])try{const t=await e.loadDictionary(i);if(t.fingerprint!==this.expectedFingerprint)throw new Error(`locale fingerprint mismatch for ${e.code}`);return this.dictionaries.set(e.code,t.dictionary),void this.failed.delete(e.code)}catch(e){t=e}this.failed.add(e.code),this.warn(`[houseplan] unable to load ${e.code} locale; using English`,t),this.loadFailed?.(e.code)}}(pp,"241ab786b7cce5c1f837e73704240f138bd3e097bfecdbb0e93046bf4a19d3ef",console.warn,function(e){for(const t of mp)t(e)});function fp(e){const t=bp(e)?.code??"en";return gp.dictionary(t)??_p}function vp(e){return"string"==typeof e?e.trim().replaceAll("_","-").toLowerCase():""}const yp=new Map(pp.map(e=>[vp(e.code),e]));function bp(e){return yp.get(vp(e))}function wp(e,t){const i=[{value:"",label:e},...pp.map(({code:e,nativeLabel:t})=>({value:e,label:t}))],n="string"==typeof t?t:"";return n&&!i.some(e=>e.value===n)&&i.push({value:n,label:bp(n)?.nativeLabel??n}),i}function kp(e,t){return function(e,t,i,n){const r=new Map(i.map(e=>[vp(e),e])),o=r.get(vp(e));if(o)return o;const s=vp(t),a=r.get(s);return a||(r.get(s.split("-")[0]||"")??n)}(t,e?.locale?.language||e?.language,pp.map(({code:e})=>e),"en")}function xp(e,t,i){return nn(fp(e)[t]??_p[t]??t,i)}function Sp(e,t){const i=fp(e)[t]??_p[t];return"string"==typeof i&&i.trim().length>0}function $p(e,t,i,n){return{ox:0,oy:0}}function Mp(e,t){const i=(e.angle+90)*Math.PI/180,n=Ba(16,t),r=e.gateFace?-n*e.gateFace.side:n*(e.flipV?-1:1);return[[e.x+Math.cos(i)*r,e.y+Math.sin(i)*r],r<0]}function Rp(e){const t=e.length/2,i=e.face.cm>0?e.face.cm/e.cellCm*e.gridPitch/2:Ba(4,e.cellCm),n="gate"===e.type?Math.sin(10*Math.PI/180)*t:0;return{half:t,jambHalf:i,gateDepth:n,outlineHalf:Math.max(Ba(16,e.cellCm),i+Ba(8,e.cellCm),n+Ba(8,e.cellCm)),hitHalf:Math.max(Ba(20,e.cellCm),i+Ba(10,e.cellCm),n+Ba(12,e.cellCm))}}function Cp(e,t,i){e.minX=Math.min(e.minX,t),e.minY=Math.min(e.minY,i),e.maxX=Math.max(e.maxX,t),e.maxY=Math.max(e.maxY,i)}function Tp(e,t,i,n,r,o,s,a){const l=Math.min(s,a)*Math.PI/180,c=Math.max(s,a)*Math.PI/180,h=(e,t)=>{const i=Math.atan2(t,e),n=[l,c];for(let e=-3;e<=3;e++){const t=e*Math.PI-i,r=Math.PI/2+e*Math.PI-i;t>l&&tl&&r0&&[e.length,e.angle,t[0],t[1]].every(Number.isFinite)))return null;const{half:i,jambHalf:n}=Rp(e),r=La(e.cellCm),o=1.75*r,s=1.25*r,a=.75*r,l={minX:-i-s,minY:-n-s,maxX:i+s,maxY:n+s},c={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("window"===e.type)Tp(c,-i,0,i,-o,o,-90,0),Tp(c,i,-i,0,-o,o,0,90),Cp(c,-i-a,-i-a),Cp(c,i+a,a);else if("gate"===e.type){const t=10*e.face.side;Tp(c,-i,0,i,-o,o,0,t),Tp(c,i,-i,0,-o,o,-t,0)}else Tp(c,-i,0,e.length,-o,o,-90,0),Cp(c,-i-a,-e.length-a),Cp(c,i+a,a);const[h,d]=Dp(e),u={...l};Cp(u,c.minX+h,c.minY+d),Cp(u,c.maxX+h,c.maxY+d);const p=e.flipH?-1:1,_="gate"===e.type?1:e.flipV?-1:1,m=e.angle*Math.PI/180,g=Math.cos(m),f=Math.sin(m),v={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};for(const e of[u.minX,u.maxX])for(const i of[u.minY,u.maxY]){const n=e*p,r=i*_;Cp(v,t[0]+n*g-r*f,t[1]+n*f+r*g)}return v}function Pp(e){if("passage"===e.type)return W``;const t=Math.max(0,Math.min(1,e.amount)),{half:i,jambHalf:n}=Rp(e),r=La(e.cellCm),o=1.75*r,s=e.flipH?-1:1,a=e.flipV?-1:1,l="gate"===e.type?1:a,[c,h]=Dp(e);let d;if("window"===e.type){const o=Math.PI/2*i,s=e.face.cm>0?W``:W``;d=W` - - - - - - - - - - - - - - ${s} - `}else if("gate"===e.type){const n=10*e.face.side*t;d=W` - - - - - - - - - - - - `}else{const n=Math.PI/2*e.length;d=W` - - - - - - - - `}return W` - - - ${d} - `}const Fp={climate:["current_temperature","temperature","current_humidity","humidity"],water_heater:["current_temperature","temperature"],cover:["current_position"],valve:["current_position"],fan:["percentage"],humidifier:["current_humidity","humidity"],light:["brightness"],media_player:["volume_level"],vacuum:["battery_level","fan_speed"],lawn_mower:["battery_level","fan_speed"]};function zp(e){return e?e.sourceLabel?`${e.sourceLabel}: ${e.fullText}`:e.fullText:""}const Ip=new WeakMap;function Op(e){return e?"entity_state"===e.kind?`state:${e.entity_id}`:"entity_attribute"===e.kind?`attr:${e.entity_id}:${e.attribute}`:"derived_marker_state"===e.kind?`marker:${e.ref}`:"derived_lqi"===e.kind?"derived:lqi":"":""}function Ep(e){if("derived:lqi"===e)return{kind:"derived_lqi"};if(e.startsWith("state:"))return{kind:"entity_state",entity_id:e.slice(6)};if(e.startsWith("attr:")){const t=e.slice(5),i=t.lastIndexOf(":");if(i>0)return{kind:"entity_attribute",entity_id:t.slice(0,i),attribute:t.slice(i+1)}}return e.startsWith("marker:marker:")?{kind:"derived_marker_state",ref:e.slice(7)}:null}function Np(e,t){const i=e?.entities?.[t],n=e?.states?.[t];return String(i?.name||i?.original_name||n?.attributes?.friendly_name||t)}function Hp(e){return e.replaceAll("_"," ")}function Lp(e,t=1){const i=Number(e);return Number.isFinite(i)?`${Math.round(i*t)} %`:null}function Bp(e){if("derived_lqi"===e.kind)return"lqi";if("entity_attribute"===e.kind){if(e.attribute.includes("temperature"))return"temperature";if(e.attribute.includes("humidity"))return"humidity"}return"default"}function qp(e,t,i,n=[]){let r=null,o="",s="available",a=null;if("entity_state"===i.kind){o=Np(e,i.entity_id);const t=e?.states?.[i.entity_id];if(t)if(Wp(e,i.entity_id))if(["string","number","boolean"].includes(typeof t.state))if(["unknown","unavailable"].includes(String(t.state).toLowerCase()))s="unavailable",a="missing";else{const n=Xi(e,i.entity_id);r=n?Zi(n,String(t.attributes?.unit_of_measurement||"")):null,r||(s="unavailable",a="missing")}else s="unavailable",a="non_scalar";else s="unavailable",a="missing";else s="missing",a="missing"}else if("entity_attribute"===i.kind){o=`${Hp(i.attribute)} · ${Np(e,i.entity_id)}`;const t=e?.states?.[i.entity_id],n=!!t&&i.attribute in(t.attributes||{}),l=n?t.attributes?.[i.attribute]:void 0;t?Wp(e,i.entity_id)?["unknown","unavailable"].includes(String(t.state).toLowerCase())?(s="unavailable",a="missing"):n?["string","number","boolean"].includes(typeof l)?(r=function(e,t,i){const n=e?.states?.[t];if(!n||!(i in(n.attributes||{})))return null;const r=Xi(e,t,i);if(r?.formatted)return r.text;const o=n.attributes?.[i];if("brightness"===i)return Lp(o,100/255);if("volume_level"===i)return Lp(o,100);if(["current_position","percentage","current_humidity","humidity","battery_level"].includes(i))return Lp(o);if("current_temperature"===i||"temperature"===i){const t=Number(o);if(!Number.isFinite(t))return null;const i=String(e?.config?.unit_system?.temperature||"°C");return`${Math.round(10*t)/10} ${i}`}return r?.text||(["string","number","boolean"].includes(typeof o)?String(o):null)}(e,i.entity_id,i.attribute),null==r&&(s="unavailable",a="missing")):(s="unavailable",a="non_scalar"):(s="unavailable",a="missing"):(s="unavailable",a="missing"):(s="missing",a="missing")}else if("derived_lqi"===i.kind){o="LQI";const i=Ld(e,t.entities);null==i?(s="unavailable",a="missing"):r=String(i)}else{o="Light state";const t=n.find(e=>e.ref===i.ref);if(t){const i=t.on?"on":"off",n=e?.localize?.(`state.default.${i}`);r="string"==typeof n&&n?n:i,o=t.name||o}else s="missing",a="missing"}const l=e?.localize?.("state.default.unavailable")||"Unavailable";return{source:i,sourceLabel:o,text:r??"—",fullText:r??l,availability:s,isLqi:"derived_lqi"===i.kind,tone:Bp(i),failure:a}}function jp(e,t){if(!0===t.marker?.use_climate_temp){const i=t.entities.find(t=>t.startsWith("climate.")&&Number.isFinite(Number(e?.states?.[t]?.attributes?.current_temperature)));return i?{kind:"entity_attribute",entity_id:i,attribute:"current_temperature"}:null}if("mdi:thermometer"===t.icon||"mdi:air-filter"===t.icon){const i=t.entities.find(t=>fd(e,t)&&Number.isFinite(Number(e?.states?.[t]?.state)));if(i)return{kind:"entity_state",entity_id:i}}return t.primary&&jd(e,t.primary)&&Number.isFinite(Number(e?.states?.[t.primary]?.state))?{kind:"entity_state",entity_id:t.primary}:null}function Wp(e,t){const i=e?.entities?.[t];if(i&&!sd(i))return!1;const n=i?.device_id?e?.devices?.[i.device_id]:null;return!n||sd(n)}function Up(e,t){return Wp(e,t)&&!!e?.states?.[t]}function Gp(e,t,i=[t]){const n=function(e,t){const i=e=>[e.id,e.primary,e.hidden?1:0,e.userHidden?1:0,e.entities.join(","),(e.controls||[]).join(","),e.marker?.binding||"",!0===e.marker?.is_light?1:0,e.marker?.light_entity||"",(e.marker?.controls||[]).join(",")].join("|");return`${i(e)}\n${t.map(i).join("\n")}`}(t,i),r=Ip.get(t);if(r&&r.states===(e?.states||null)&&r.entities===(e?.entities||null)&&r.devices===(e?.devices||null)&&r.signature===n)return r.result;const o=new Set(t.entities);for(const e of t.controls||[])e.startsWith("marker:")||o.add(e);const s=[],a=Ed(e,i),l=a.filter(e=>e.key.startsWith("marker:")).map(e=>({ref:e.key,on:e.on,name:e.device?.name||e.key})),c=i=>{const n=Op(i);if(s.some(e=>e.key===n))return;const r=qp(e,t,i,l),o="entity_attribute"===i.kind?`${i.entity_id} · ${i.attribute}`:"entity_state"===i.kind?i.entity_id:"derived_marker_state"===i.kind?i.ref:"LQI";s.push({key:n,source:i,label:r.sourceLabel,technical:o,value:r.text,available:"available"===r.availability})};for(const t of[...o].sort()){if(!Up(e,t))continue;const i=t.split(".")[0],n=e?.entities?.[t];if("button"===i||"event"===i||"config"===n?.entity_category)continue;c({kind:"entity_state",entity_id:t});const r=e?.states?.[t];for(const e of Fp[i]||[])e in(r?.attributes||{})&&c({kind:"entity_attribute",entity_id:t,attribute:e})}const h=new Set((t.marker?.controls||t.controls||[]).filter(e=>e.startsWith("marker:")));!0===t.marker?.is_light&&t.marker.id&&h.add(`marker:${t.marker.id}`);const d=new Set(a.map(e=>e.key));for(const e of[...h].sort())d.has(e)&&c({kind:"derived_marker_state",ref:e});return t.virtual||null==Ld(e,t.entities)||c({kind:"derived_lqi"}),Ip.set(t,{states:e?.states||null,entities:e?.entities||null,devices:e?.devices||null,signature:n,result:s}),s}function Vp(e,t,i){const n=jp(e,t);if(n&&i.some(e=>e.key===Op(n)))return n;const r=t.primary&&i.find(e=>e.key===`state:${t.primary}`);if(r)return r.source;const o=[e=>e.technical.includes("temperature"),e=>e.technical.includes("humidity"),e=>e.technical.includes("battery")];for(const e of o){const t=i.find(e);if(t)return t.source}return i.find(e=>"derived_lqi"!==e.source.kind)?.source||i[0]?.source||null}function Kp(e){return e.touched?{value_badge:{enabled:e.enabled,source:e.source,position:e.position}}:e.originalHas?{value_badge:e.original}:{}}function Yp(e){return e.touched?e.source?{value_source:e.source}:{}:e.originalHas?{value_source:e.original}:{}}function Xp(e,t,i){return{kind:"none",reason:"none",generation:e,expiresAt:null,color:t,diameterScale:i,animated:!1,reducedMotionIndicator:"none"}}function Zp(e,t,i,n,r=null){return{kind:t,reason:"short"===t?"event":"running",generation:Math.max(1,Math.trunc(i)),expiresAt:"short"===t?r:null,color:e.color,diameterScale:n?1:e.diameterScale,animated:!n,reducedMotionIndicator:n?"dot":"none"}}const Jp={availability:"available",status:"neutral",activity:"none"};function Qp(e){return e<=40?"low":e<180?"mid":"high"}function e_(e){return Jt(e)}function t_(e){const t=new Set,i=[];for(const n of e){if("string"!=typeof n)continue;const e=n.trim().replace(/\s+/g," ");if(!e)continue;const r=e.toLowerCase();t.has(r)||(t.add(r),i.push(e))}return i.join(", ")}function i_(e){return"static_icon"===e.display?"neutral":"alarm"===e.visual.status?"alarm":"unavailable"===e.visual.availability?"unavailable":e.lockState?e.lockState:"working"===e.visual.status?"working":"open"===e.visual.status?"open":"neutral"}const n_={sourceKind:"none",decisionIds:["source.skipped_static_fast_path"],visualSources:[],criticalSources:[],samples:[]};function r_(e,t){const i=e?.entities?.[t],n=e?.states?.[t];return String(i?.name||i?.original_name||n?.attributes?.friendly_name||t)}function o_(e,t){const i=e?.states?.[t];if(!i)return"";if("function"==typeof e?.formatEntityState)try{const t=e.formatEntityState(i);if("string"==typeof t&&t)return t}catch{}return String(i.state??"")}function s_(e,t){if(t.virtual||"virtual"===t.bindingKind||"virtual"===t.marker?.binding)return"available";const i=t.entities||[],n="ha_disabled"===t.bindingStatus?.kind||(t.bindingStatus?.allEntityIds?.length??0)>0;if(0===i.length&&!n&&("device"===t.bindingKind||t.marker?.binding?.startsWith("device:"))&&"active"===t.bindingStatus?.kind)return"available";return i.some(t=>{const i=String(e?.states?.[t]?.state??"").trim().toLowerCase();return""!==i&&"unknown"!==i&&"unavailable"!==i})?"available":"unavailable"}function a_(e,t,i,n){return{eid:t,role:i,name:r_(e,t),state:String(e?.states?.[t]?.state??""),stateText:o_(e,t),integrationDomain:e?.entities?.[t]?.platform||null,sample:n||Fh(e,t)}}function l_(e,t,i=[t],n,r=e){const o=t.hidden&&t.userHidden?{...t,hidden:!1}:t;let s="none",a=[];const l=[],c=[...o.entities,...o.allEntities||[]].some(e=>e.startsWith("cover."))?{...o,tapAction:"cover"}:o,h=(d=Fu({hass:e,devices:i,device:c,lightSources:n,registryHass:r}),"cover"!==d?.semantics?null:d.targets[0]?.entityId||d.skippedTargets[0]?.entityId||null);var d;const u=Ed(e,[o]),p=xd(o.marker?.binding,o.marker?.controls??o.controls,o.entities),_=new Set(p.filter(e=>e.startsWith("marker:"))),m=!0===o.marker?.is_light||_.size>0?n||Ed(e,i):u,g=m.filter(e=>e.device.id===o.id&&"controls"!==e.via),f=u.filter(e=>"controls"!==e.via),v=g.length?g:f,y=qh(o.marker),b=y?[...v]:[...u.filter(e=>"controls"===e.via),...v];if(_.size)for(const e of m){if(!_.has(e.key))continue;e.stateEids.length>0&&b.some(t=>t.stateEids.some(t=>e.stateEids.includes(t)))||b.some(t=>t.key===e.key)||b.push({...e,via:"controls",castsGlow:!1})}const w=bd(r,o.entities),k=!!h&&("cover"===o.tapAction||o.primary?.startsWith("cover.")||w.some(e=>e.startsWith("cover.")));if(h&&!k&&l.push("source.cover_capability_bypassed"),k)s="cover",l.push("source.cover"),a=[a_(e,h,"cover")];else if(b.length)s=!y&&b.some(e=>"controls"===e.via)?"controls":"light",y?l.push("source.manual_virtual_light"):l.push("controls"===s?"source.controls":"source.owned_light"),"controls"!==s||!o.virtual&&"virtual"!==o.bindingKind||l.push("source.virtual_controller"),a=b.map(i=>{const n="controls"===i.via?"control":"forced"===i.via?"forced_light":"light";if(!i.passive)return a_(e,i.eid,n);const r=i.on?"on":"off";return{eid:i.key,role:n,name:t.name,state:r,stateText:r,integrationDomain:null,sample:{eid:i.key,state:r,availability:"available",status:i.on?"working":"neutral",activity:"none",edge:"none"}}});else{const t=bd(r,o.entities),i=t.length?t:o.entities.filter(t=>!!e?.states?.[t]);if(i.length){s="device_role",l.push("source.device_role");const t=zh(r===e?e:{...r,states:e?.states||{}},i,o.entities),n=i.some(e=>Dh(r,e));a=t.map(t=>{const i=n?Ah(r,t.eid)?"power_gate":Dh(r,t.eid)?"lifecycle":"device_role":"device_role";return a_(e,t.eid,i,t)})}else o.primary?(s="primary",l.push("source.primary_fallback"),a=[a_(e,o.primary,"primary")]):l.push("source.none")}p.length>0&&"controls"!==s&&"light"!==s&&"cover"!==s&&l.push("source.filtered_saved_controls");const x=[];for(const t of o.entities||[]){const i=Fh(e,t);"alarm"!==i.status||a.some(e=>e.eid===t)||x.push(a_(e,t,"critical",i))}return x.length&&l.push("source.critical_sibling"),{sourceKind:s,decisionIds:l,visualSources:a,criticalSources:x,samples:[...a,...x].map(e=>e.sample)}}function c_(e,t,i,n,r=[]){if(t.virtual)return{source:null,text:null,fullText:null,fallback:"value_virtual",explicit:!1};const o=t.marker?.value_source;if(o){const i=qp(e,t,o,r);return{source:{kind:"derived_lqi"===o.kind?"derived_lqi":"derived_marker_state"===o.kind?"derived_marker_state":"entity_attribute"===o.kind&&o.attribute.includes("temperature")?"temperature":"entity_attribute"===o.kind&&o.attribute.includes("humidity")?"humidity":"entity",eid:"entity_state"===o.kind||"entity_attribute"===o.kind?o.entity_id:"derived_marker_state"===o.kind?o.ref:"derived:lqi",attribute:"entity_attribute"===o.kind?o.attribute:void 0,text:i.text,sourceKey:Op(o)},text:i.text,fullText:i.fullText,fallback:"non_scalar"===i.failure?"value_non_scalar":"missing"===i.failure?"value_no_state":null,explicit:!0}}if(n){const i=function(e,t){if(!0!==t.marker?.use_climate_temp)return null;for(const i of t.entities){if(!i.startsWith("climate."))continue;const t=Number(e?.states?.[i]?.attributes?.current_temperature);if(Number.isFinite(t))return{eid:i,text:Math.round(10*t)/10+"°"}}return null}(e,t);if(i)return{source:{kind:"temperature",eid:i.eid,attribute:"current_temperature",text:i.text,sourceKey:`attr:${i.eid}:current_temperature`},text:i.text,fullText:i.text,fallback:null,explicit:!1};const n=function(e,t){if("mdi:thermometer"!==t.icon&&"mdi:air-filter"!==t.icon)return null;for(const i of t.entities){if(!fd(e,i))continue;const t=Number(e?.states?.[i]?.state);if(Number.isFinite(t))return{eid:i,text:Math.round(10*t)/10+"°"}}return null}(e,t);if(n)return{source:{kind:"temperature",eid:n.eid,text:n.text,sourceKey:`state:${n.eid}`},text:n.text,fullText:n.text,fallback:null,explicit:!1};const r=function(e,t){if(!t.primary||!jd(e,t.primary))return null;const i=Number(e?.states?.[t.primary]?.state);return Number.isFinite(i)?{eid:t.primary,text:`${Math.round(i)}%`}:null}(e,t);if(r)return{source:{kind:"humidity",eid:r.eid,text:r.text,sourceKey:`state:${r.eid}`},text:r.text,fullText:r.text,fallback:null,explicit:!1}}const s=i.visualSources.filter(e=>!e.eid.startsWith("marker:"));let a=s.map(e=>e.eid);const l=s.find(e=>"power_gate"===e.role);if(l&&(a=[l.eid]),!a.length&&i.visualSources.some(e=>e.eid.startsWith("marker:"))&&(a=bd(e,t.entities),!a.length&&t.primary&&e?.states?.[t.primary]&&(a=[t.primary])),a=[...new Set(a)],1!==a.length)return{source:null,text:null,fullText:null,fallback:a.length?"value_ambiguous_sources":"value_no_state",explicit:!1};const c=a[0],h=function(e,t){const i=e?.states?.[t];if(!i||null==i.state||""===String(i.state).trim())return{text:"",fallback:"value_no_state"};const n=i.state;if(!["string","number","boolean"].includes(typeof n))return{text:"",fallback:"value_non_scalar"};const r=String(n).trim().toLowerCase();if("unknown"===r||"unavailable"===r)return{text:"",fallback:"value_no_state"};const o=Xi(e,t);return o?{text:Zi(o,String(i.attributes?.unit_of_measurement||"")),fallback:null}:{text:"",fallback:"value_no_state"}}(e,c);return h.fallback?{source:null,text:null,fullText:null,fallback:h.fallback,explicit:!1}:{source:{kind:"entity",eid:c,text:h.text,sourceKey:`state:${c}`},text:h.text,fullText:h.text,fallback:null,explicit:!1}}function h_(e,t,i){const n=e.marker?.binding||(e.bindingKind&&e.bindingRef?`${e.bindingKind}:${e.bindingRef}`:e.virtual?"virtual":""),r=[...t.visualSources.map(e=>`${e.role}:${e.eid}`),...t.criticalSources.map(e=>`critical:${e.eid}`)].sort(),o=i?`${i.kind}:${i.sourceKey}:${i.eid}:${i.attribute||""}`:"none";return[n,t.sourceKind,...r,`value:${o}`].join("\n")}function d_(e,t,i){return h_(t,i||l_(e,t),null).replace(/\nvalue:none$/,"")}function u_(e){if(e.effectiveHidden)return[];if("static_icon"===e.display)return["static-icon"];const t=[],{visual:i}=e;return"alarm"===e.pulse.kind?t.push("alarm"):"unavailable"===i.availability?t.push("unavail"):"working"===i.status?t.push("on"):"open"===i.status&&t.push("open"),e.lockState&&t.push(`lock-${e.lockState}`),"none"!==e.pulse.reason&&"alarm"!==e.pulse.reason&&t.push("activity-"+e.pulse.reason),e.pulse.generation%2==0&&(t.push("pulse-gen2"),"short"===e.pulse.kind&&t.push("activity-gen2")),t}function p_(e,t,i){const n=Li(t.marker?.display),r="static_icon"===n,o=r&&!1===i.sourceDetails?n_:l_(e,t,i.lightDevices||[t],i.lightSources,i.registryHass||e),s="derived_marker_state"===t.marker?.value_source?.kind||"derived_marker_state"===t.marker?.value_badge?.source?.kind,a=(i.lightSources||(s?Ed(e,i.lightDevices||[t]):[])).filter(e=>e.key.startsWith("marker:")).map(e=>({ref:e.key,on:e.on,name:e.device.name})),l=t.bindingStatus,c="ha_disabled"===l?.kind,h="orphaned"===l?.kind,d=c?"ha_disabled":h?"orphaned":"active",u=!0===t.userHidden||!0===t.marker?.hidden,p=Ih(o.samples),_=o.visualSources.find(e=>e.eid.startsWith("lock.")),m=_?["unlocked","open"].includes(_.state.toLowerCase())?"unlocked":"locked"===_.state.toLowerCase()?"locked":null:null,g=!qh(t.marker)&&xd(t.marker?.binding,t.marker?.controls??t.controls,t.entities).length>0,f="controls"===o.sourceKind||g&&"light"!==o.sourceKind&&"cover"!==o.sourceKind,v=r&&!1===i.sourceDetails?{source:null,text:null,fullText:null,fallback:null}:c_(e,t,o,i.showTemperature,a),y=h_(t,o,v.source),b=d_(e,t,o),w=i.activityRuntime,k=i.now??Date.now(),x=w?.expiresAt||(w?.flashTs?w.flashTs+3300:0),S=w?.sources===b&&w.flashTs&&w.flashKind&&x>k?w.flashKind:null,$=function(e){const t=[],i="ha_disabled"===e.bindingLifecycle||"orphaned"===e.bindingLifecycle;let n=!1;"ha_disabled"===e.bindingLifecycle?(n=!0,t.push("lifecycle.ha_disabled_hidden")):e.userHidden&&!e.designPreview?(n=!0,t.push("lifecycle.user_hidden")):e.userHidden?t.push("lifecycle.user_hidden_preview"):"orphaned"===e.bindingLifecycle?t.push("lifecycle.orphaned_diagnostic"):t.push("lifecycle.active");const r="static_icon"===e.display;let o=e.controllerFace?{...e.sourceVisual,availability:e.controllerAvailability}:e.sourceVisual;t.push(e.controllerFace?"available"===e.controllerAvailability?"availability.controller_available":"availability.controller_unavailable":"availability.source"),n?(o=Jp,t.push("face.hidden")):r?(o=Jp,t.push("face.static")):"alarm"===e.sourceVisual.status||e.liveStates?t.push("face.dynamic"):(o=Jp,t.push("face.live_states_disabled")),!r&&!n&&e.liveStates&&"alarm"!==e.sourceVisual.status&&e.shortActivity&&(o={...o,activity:e.shortActivity},t.push(`activity.short_${e.shortActivity}`)),"alarm"===o.status?t.push("status.alarm"):"unavailable"===o.availability?t.push("status.unavailable"):"working"===o.status?t.push("status.working"):"open"===o.status?t.push("status.open"):t.push("status.neutral");const s="value"===e.display&&!n&&e.valueAvailable?"value":"icon";t.push("value"===s?"content.value":"value"===e.display?"content.value_fallback_icon":"content.icon"),"value"===e.display&&!e.valueAvailable&&e.valueFallback&&t.push(`content.${e.valueFallback}`);const a=e.liveStates&&!r&&!n,l=!r&&!n,c=!n&&!i&&!r&&"available"===o.availability&&("alarm"===o.status||e.liveStates&&"icon_ripple"===e.display),h=l&&e.vacuumLiveRequested;return t.push(a?"diagnostics.dynamic_icon":"diagnostics.base_icon"),t.push(l?"diagnostics.metrics_enabled":"diagnostics.metrics_suppressed"),t.push(c?"activity.pulse_eligible":"activity.pulse_suppressed"),t.push(h?"diagnostics.vacuum_live":"diagnostics.vacuum_static"),{effectiveHidden:n,bindingUnavailable:i,visual:o,face:s,dynamicIcon:a,metrics:l,liveColor:a,pulseEligible:c,vacuumLive:h,decisionIds:t}}({bindingLifecycle:d,userHidden:u,designPreview:!0===i.designPreview,display:n,liveStates:i.liveStates,sourceVisual:p,controllerFace:f,controllerAvailability:f?s_(e,t):"available",shortActivity:S,valueAvailable:null!=v.text,valueFallback:v.fallback,vacuumLiveRequested:!0===t.marker?.vacuum?.live}),{effectiveHidden:M,visual:R}=$,C="icon_ripple"===n&&!M&&i.liveStates&&"alarm"!==R.status?R.activity:"none",T=$.metrics&&i.showTemperature?!0===t.marker?.use_climate_temp?qd(e,t.entities):"mdi:thermometer"===t.icon||"mdi:air-filter"===t.icon?Bd(e,t.entities):null:null,D=$.metrics&&i.showTemperature&&t.primary&&jd(e,t.primary)?Wd(e,t.entities):null,A=$.metrics&&i.showSignal&&!t.virtual?Ld(e,t.entities):null,P=function(e,t,i){const n=null!=t.marker?.value_badge;if(i.effectiveHidden||"static_icon"===i.display)return null;const r=t.marker?.value_badge;if(n)return r?.enabled?r.source?{configured:!0,enabled:!0,position:r.position||"right",...qp(e,t,r.source,i.markerStates)}:{configured:!0,enabled:!0,source:null,sourceLabel:"",text:"—",fullText:e?.localize?.("state.default.unavailable")||"Unavailable",position:r.position||"right",availability:"missing",isLqi:!1,tone:"default",failure:"missing"}:null;if(!i.showTemperature||"value"===i.display)return null;const o=jp(e,t);if(!o)return null;let s=null,a="default";if("entity_attribute"===o.kind&&"current_temperature"===o.attribute){const i=qd(e,t.entities);null!=i&&(s=`${i}°`),a="temperature"}else if("mdi:thermometer"===t.icon||"mdi:air-filter"===t.icon){const i=Bd(e,t.entities);null!=i&&(s=`${i}°`),a="temperature"}else{const i=Wd(e,t.entities);null!=i&&(s=`${i}%`),a="humidity"}return null==s?null:{configured:!1,enabled:!0,source:o,position:"right",sourceLabel:"entity_attribute"===o.kind?`${Hp(o.attribute)} · ${Np(e,o.entity_id)}`:"entity_state"===o.kind?Np(e,o.entity_id):"",text:s,fullText:s,availability:"available",isLqi:!1,tone:a,failure:null}}(e,t,{showTemperature:i.showTemperature,showSignal:i.showSignal,display:n,effectiveHidden:M,markerStates:a}),F=o.visualSources.find(e=>!e.eid.startsWith("marker:")),z="cover"===o.sourceKind?F?.eid:t.primary||F?.eid,I=z?e?.states?.[z]:null,O=$.dynamicIcon?kn(t.icon,z?.split(".")[0],I?.attributes?.device_class,I?.state,!!t.marker?.icon):t.icon,E=$.liveColor&&o.visualSources.filter(e=>!e.eid.startsWith("marker:")).map(t=>function(e){return e&&"on"===e.state?Zt(e.attributes?.rgb_color):null}(e?.states?.[t.eid])).find(e=>!!e)||null,N=Number(t.marker?.size)>0?Number(t.marker.size):1,H=Number(t.marker?.angle)||0,L=Number(t.marker?.ripple_size)>0?Number(t.marker.ripple_size):1.5,B=Kt(t.marker?.ripple_color,null),q=r?null:B||E||null,j=function(e){const{display:t,visual:i,semanticActivity:n,liveStates:r,effectiveHidden:o,bindingUnavailable:s=!1,reducedMotion:a=!1}=e,l=Math.max(1,Math.trunc(e.shortGeneration||1)),c=Number.isFinite(e.diameterScale)?Math.max(1,Number(e.diameterScale)):1.5,h=e.color||function(e,t){return"presence"===t?"#1DC21D":"running"===t||"working"===e.status||"open"===e.status?"#F0A00C":"#0C82F0"}(i,n);if(o||s||"unavailable"===i.availability||"static_icon"===t)return Xp(l,h,c);if("alarm"===i.status)return{kind:"alarm",reason:"alarm",generation:l,expiresAt:null,color:"#F0410C",diameterScale:1.5,animated:!a,reducedMotionIndicator:"none"};if(!r||"icon_ripple"!==t)return Xp(l,h,c);const d=e.now??Date.now(),u=e.shortExpiresAt||null;return e.shortReason&&null!=u&&u>d?{kind:"short",reason:e.shortReason,generation:l,expiresAt:u,color:h,diameterScale:a?1:c,animated:!a,reducedMotionIndicator:a?"dot":"none"}:"presence"===n||"transition"===n||"running"===n?{kind:"continuous",reason:n,generation:l,expiresAt:null,color:h,diameterScale:a?1:c,animated:!a,reducedMotionIndicator:a?"dot":"none"}:Xp(l,h,c)}({display:n,visual:R,semanticActivity:p.activity,shortReason:w?.sources===b?w?.flashKind:null,shortGeneration:w?.gen,shortExpiresAt:w?.sources===b?x:null,now:k,liveStates:i.liveStates,effectiveHidden:M,bindingUnavailable:$.bindingUnavailable,reducedMotion:i.reducedMotion,color:q,diameterScale:L}),W="value"===$.face?v.text:null,U="ha_disabled"===l?.kind?l.reason:null,G="ha_disabled"===(V={lifecycle:d,display:n,liveStates:i.liveStates,sourceKind:o.sourceKind,primaryDomain:(t.primary||"").split(".")[0],visual:R,activity:C}).lifecycle?"ha_disabled":"orphaned"===V.lifecycle?"orphaned":"static_icon"===V.display?"static_icon":"alarm"===V.visual.status?"alarm":V.liveStates?"unavailable"===V.visual.availability?"unavailable":"cover"===V.sourceKind?"cover_icon_state":"presence"===V.activity?"presence":"event"===V.activity?"event":"transition"===V.activity?"transition":"working"===V.visual.status?"icon_ripple"===V.display&&"none"!==V.activity?"working_activity":"working":"open"===V.visual.status?"open":"media_player"===V.primaryDomain?"media_neutral":"neutral":"live_states_disabled";var V;const K=[];i.designPreview&&u&&K.push("hidden_design_preview"),r||!0!==t.marker?.vacuum?.live||K.push("vacuum_live_plan_only");const Y=o.visualSources.some(t=>"power_gate"===t.role||Ah(e,t.eid)),X=t.entities.filter(t=>t.startsWith("switch.")&&!e?.entities?.[t]?.entity_category).length;Y&&X>1&&K.push("composite_power_source"),"icon_ripple"!==n&&"static_icon"!==n&&"alarm"!==p.status&&"none"!==p.activity&&K.push("activity_display_disabled");const Z={binding:t.marker?.binding||(t.bindingKind&&t.bindingRef?`${t.bindingKind}:${t.bindingRef}`:t.virtual?"virtual":""),sourceKind:o.sourceKind,visualSources:o.visualSources,criticalSources:o.criticalSources,valueSource:v.source,sourceSignature:y,decisionIds:[...o.decisionIds,...$.decisionIds,...P?["diagnostics.value_badge"]:[],...null==A?[]:[`diagnostics.lqi_${Qp(A)}`],`pulse.${j.kind}_${j.reason}`],visual:R,lockState:m,display:n,icon:O,valueText:W,valueFullText:"value"===$.face?v.fullText:null,fallbackReason:"value"===n?v.fallback:null,activity:C,activityGeneration:w?.gen||1,pulse:j,classes:[],tempText:null==T?null:String(T),humText:null==D?null:String(D),valueBadge:P,lqiText:null==A||P?.isLqi||"derived_lqi"===v.source?.kind?null:String(A),lqiColor:null==A?null:e_(A),lqiBand:null==A?null:Qp(A),lightColor:E,scale:N,angle:H,rippleScale:L,rippleColor:q,userHidden:u,effectiveHidden:M,haDisabled:c,disabledReason:U,orphaned:h,vacuumLive:$.vacuumLive,explanation:{reason:G,notices:K}};return{...Z,classes:u_(Z)}}function __(e,t=new WeakMap){if(null===e||"object"!=typeof e)return e;const i=e,n=t.get(i);if(n)return n;if(Array.isArray(e)){const n=[];t.set(i,n);for(const i of e)n.push(__(i,t));return Object.freeze(n)}const r={};t.set(i,r);for(const[i,n]of Object.entries(e))"function"!=typeof n&&(r[i]=__(n,t));return Object.freeze(r)}function m_(e){const t=new Map(e);let i;return i=Object.freeze({get size(){return t.size},get:e=>t.get(e),has:e=>t.has(e),entries:()=>t.entries(),keys:()=>t.keys(),values:()=>t.values(),forEach:(e,n)=>t.forEach((t,r)=>e.call(n,t,r,i)),[Symbol.iterator]:()=>t[Symbol.iterator]()}),i}function g_(e){const t=new Set(e.entityIds||[]),i=new Set(e.deviceIds||[]),n=new Set(e.areaIds||[]);for(const n of e.devices){for(const e of n.entities||[])t.add(e);n.primary&&t.add(n.primary);for(const e of n.controls||[])t.add(e);n.marker?.vacuum?.source&&t.add(n.marker.vacuum.source),"device"===n.bindingKind&&n.bindingRef&&i.add(n.bindingRef),"entity"===n.bindingKind&&n.bindingRef&&t.add(n.bindingRef)}const r={},o={};for(const[o,s]of Object.entries(e.hass?.entities||{})){const a=s?.device_id?e.hass?.devices?.[s.device_id]:null;(t.has(o)||s?.device_id&&i.has(s.device_id)||n.has(s?.area_id)||n.has(a?.area_id))&&(t.add(o),r[o]=s,s?.device_id&&i.add(s.device_id))}for(const t of i){const i=e.hass?.devices?.[t];i&&(o[t]=i)}const s={};for(const i of t){const t=e.hass?.states?.[i];t&&(s[i]=t)}const a=Object.freeze({states:__(s),entities:__(r),devices:__(o),config:__(e.hass?.config),locale:__(e.hass?.locale),themes:__(e.hass?.themes)}),l=__([...e.devices]),c=Object.freeze(l.filter(t=>e.facts?.has(`vacuum:${t.id}`)));return Object.freeze({sourceSequence:e.sourceSequence,capturedAt:e.capturedAt??Date.now(),hass:a,devices:l,vacuumDevices:c,positions:m_([...e.positions||[]].map(([e,t])=>[e,Object.freeze({x:t.x,y:t.y})])),presentations:m_([...e.presentations].map(([e,t])=>[e,__(t)])),facts:m_([...e.facts||[]].map(([e,t])=>[e,__(t)])),entityIds:Object.freeze([...t])})}const f_=(e,t)=>`${e}:${t?1:0}`;function v_(e){return"boolean"==typeof e?.themes?.darkMode?e.themes.darkMode?"theme-dark":"theme-light":""}function y_(e){const t=e.valueBadge;if(!t||!1!==t.configured)return[];const i=[];return null!=e.tempText&&"temperature"!==t.tone&&i.push({kind:"temperature",text:e.tempText,suffix:"°"}),null!=e.humText&&"humidity"!==t.tone&&i.push({kind:"humidity",text:e.humText,suffix:"%"}),i}function b_(e){const t=[];if(1!==e.scale&&t.push(`--dev-scale:${e.scale}`),"none"!==e.pulse.kind){t.push(`--ripple-scale:${e.pulse.diameterScale}`);const r=(i=e.pulse.color,n=null,"string"==typeof i&&(Vt.test(i)||Xt.test(i))?i:n);r&&t.push(`--ripple-color:${r}`)}var i,n;return t}function w_(e){const t=[...String(e)].reduce((e,t)=>/\s/.test(t)?e+.35:e+(t.codePointAt(0)>255?1:.62),0);return t<=8?.45:Math.max(.25,Math.round(3.6/t*1e3)/1e3)}function k_(e,t){const i=e.pulse,n=i.generation%2==0,r=y_(e),o=e.valueBadge,s=o?.position||"right",a=!!o||r.length>0,l=["device-shell",null!=e.valueText?"text-shell":"",a?`with-values pos-${s}`:"",r.length?"with-legacy":""].filter(Boolean).join(" ");return j` - ${"none"!==i.kind&&"dot"!==i.reducedMotionIndicator?j``:G} - ${"dot"===i.reducedMotionIndicator?j``:G} - ${t.newDevice?j``:G} - ${e.haDisabled?j``:G} - - ${null!=e.lqiText?j`${e.lqiText}`:G} - `}function x_(e){return!Number.isFinite(e)||e<=0?2.25:e/2.5*2.25}function S_({openings:e,geometries:t,fillsByRoomId:i,idPrefix:n="data",groupClass:r="opening-tunnels",dataLayer:o="data"}){const s=e.map((e,r)=>{const o=t[r];if(!o)return G;const s=o.faces.find(e=>-1===e.side),a=o.faces.find(e=>1===e.side);if(!s||!a)return G;const l=i.get(s.roomId)||null,c=i.get(a.roomId)||null;if(!l&&!c)return G;const h=`${s.d} ${a.d}`,d=!!l&&!!c&&l.color===c.color&&l.opacity===c.opacity,u=`translate(${e.rx} ${e.ry}) rotate(${e.angle})`;if(d)return W``;const p=o.maxY-o.minY;if(!(p>0))return G;const _=`${(100*Math.max(0,Math.min(1,-o.minY/p))).toFixed(6)}%`,m=l||{color:"#000000",opacity:0},g=c||{color:"#000000",opacity:0},f=`hp-opening-tunnel-${n.replace(/[^a-zA-Z0-9_-]/g,"-")}-${r}`;return W``});return W``}function $_(e,t,i){const n=i>0?i:1;return{a:[e[0]/n,e[1]/n],b:[t[0]/n,t[1]/n]}}function M_(e,t){const i=t>0?t:1;return[e.a[0]*i,e.a[1]*i,e.b[0]*i,e.b[1]*i]}function R_(e){return Array.isArray(e)&&e.length>=2&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))}function C_(e){if(!Array.isArray(e))return[];const t=[];for(const i of e){if(!i||"object"!=typeof i)continue;const e=i;if(!R_(e.a)||!R_(e.b))continue;const n=[Number(e.a[0]),Number(e.a[1])],r=[Number(e.b[0]),Number(e.b[1])];Math.hypot(r[0]-n[0],r[1]-n[1])<.001||t.push({a:n,b:r})}return t}function T_(e,t,i,n,r=!0){const o=(e||[]).filter(e=>e?.id),s=C_(t);if(s.length)return function(e,t,i,n){const r=C_(e);if(!r.length)return[];const o=function(e,t){const i=[],n=(e||[]).filter(e=>e?.id);for(let e=0;e4*n||o>4*n)continue;const s=(e[0]-r)*u+(e[1]-l)*p,c=(e[2]-r)*u+(e[3]-l)*p,h=Math.max(0,Math.min(s,c)),m=Math.min(d,Math.max(s,c));if(m-he.lo-t.lo||e.hi-t.hi);const i=[];for(const e of t){const t=i[i.length-1];t&&e.lo<=t.hi+a?t.hi=Math.max(t.hi,e.hi):i.push({...e})}for(const t of i){const i=[r+u*t.lo,l+p*t.lo],n=[r+u*t.hi,l+p*t.hi];Math.hypot(n[0]-i[0],n[1]-i[1])i.pair===e&&Math.abs(i.ux*s-i.uy*o)<=1e-6&&Math.abs((t[0]-i.origin[0])*i.uy-(t[1]-i.origin[1])*i.ux)<=c&&Math.abs((t[2]-i.origin[0])*i.uy-(t[3]-i.origin[1])*i.ux)<=c);h||(h={pair:e,origin:[t[0],t[1]],ux:o,uy:s,ranges:[]},l.push(h));const d=(t[0]-h.origin[0])*h.ux+(t[1]-h.origin[1])*h.uy,u=(t[2]-h.origin[0])*h.ux+(t[3]-h.origin[1])*h.uy;h.ranges.push({lo:Math.min(d,u),hi:Math.max(d,u)})}const h=[];for(const e of l){e.ranges.sort((e,t)=>e.lo-t.lo||e.hi-t.hi);const t=[];for(const i of e.ranges){const e=t[t.length-1];e&&i.lo<=e.hi+a?e.hi=Math.max(e.hi,i.hi):t.push({...i})}for(const n of t){const t=[e.origin[0]+e.ux*n.lo,e.origin[1]+e.uy*n.lo],r=[e.origin[0]+e.ux*n.hi,e.origin[1]+e.uy*n.hi];Math.hypot(r[0]-t[0],r[1]-t[1])>=a&&h.push($_(t,r,i))}}return h}(s,e,i,n).map(e=>M_(e,i));if(!r)return[];const a=[],l=(e,t)=>(e.open_to||[]).includes(t.id)||(t.open_to||[]).includes(e.id);for(let e=0;er)&&Ko([o[0],o[1]],[o[2],o[3]],i))return!0;return!1}const A_=e=>Array.isArray(e)&&e.length>=2&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1])),P_=(e,t,i)=>[Number(e[0])*i,Number(e[1])*i,Number(t[0])*i,Number(t[1])*i],F_=e=>{const t=`${Number(e[0]).toFixed(9)},${Number(e[1]).toFixed(9)}`,i=`${Number(e[2]).toFixed(9)},${Number(e[3]).toFixed(9)}`;return t<=i?`${t}|${i}`:`${i}|${t}`},z_=e=>{const t=new Map;for(const i of e.flat())!Array.isArray(i)||i.length<4||!i.every(Number.isFinite)||Math.hypot(i[2]-i[0],i[3]-i[1])<=1e-9||t.set(F_(i),[...i]);return[...t.values()]};function I_(e){return"solid"===e?.zero_wall_style?"solid":"dashed"}function O_(e,t=1,i){const n=[];for(const r of Array.isArray(e?.wall_segments)?e.wall_segments:[])0===Number(r?.cm)&&A_(r?.a)&&A_(r?.b)&&(i&&!i.has(String(r.id||""))||n.push(P_(r.a,r.b,t)));return z_([n])}function E_(e,t=1){const i=[];for(const n of Array.isArray(e?.partitions)?e.partitions:[])0===Number(n?.cm)&&A_(n?.a)&&A_(n?.b)&&i.push(P_(n.a,n.b,t));return z_([i])}function N_(e,t,i,n){if(!e)return[];const r=C_(e.open_spans);return T_(t,r.length?r:null,i,n,!0)}function H_(e,t,i,n){const r=I_(e),o=new Set;for(const e of t.rooms||[])for(const t of Array.isArray(e.wall_ids)?e.wall_ids:[])"string"==typeof t&&t&&o.add(t);const s=z_([O_(t,1,o.size?o:void 0),N_(e,t.rooms,i,n)]),a=z_([s,E_(t,1)]);return{style:r,lines:a,contour:s,barriers:"solid"===r?a:[],transmissive:"dashed"===r?s:[]}}function L_(e,t){return(e||[]).some(e=>e?.host?.kind===t.kind&&e.host.id===t.id)}function B_(e){return e instanceof Error?e.name||"Error":typeof e}function q_(e){return cc({id:e?.id??"",cell_cm:e?.cell_cm,rooms:e?.rooms||[],walls:e?.walls||[],wall_segments:e?.wall_segments||[],open_spans:e?.open_spans||[],openings:e?.openings||[],partitions:e?.partitions||[],wall_columns:e?.wall_columns||[]})}function j_(e,t,i={}){const n=(Array.isArray(e?.spaces)?e.spaces:[]).find(e=>String(e?.id||"")===String(t||"")),r=q_(n);if(!n)return{spaceId:String(t||""),displayName:"",status:"failed",reason:"prepare-exception",fingerprint:r,ok:!1};const o=X_({...e,spaces:[n]},{...i,fingerprint:()=>r}).spaces[0]||{spaceId:String(t||""),displayName:"",status:"failed",reason:"prepare-exception"};return{...o,fingerprint:r,ok:"failed"!==o.status}}function W_(e,t,i=tl,n=1e3){return T_(t.rooms,e?.open_spans,n,.02*i)}function U_(e,t,i,n=tl,r=1e3){return(Array.isArray(e?.openings)?e.openings:[]).flatMap(e=>{const o={...e,rx:Number(e.x)*r,ry:Number(e.y)*r,rlen:Number(e.length)*r};if(!e.host||"wall"===e.host.kind)return[o];const s=Ju(e,t.partitions,r,i,n);return s.resolved?[{...e,rx:s.resolved.center[0],ry:s.resolved.center[1],rlen:s.resolved.length,angle:s.resolved.angle,partitionHost:s.resolved}]:[]})}function G_(e,t=()=>!0){return e.flatMap(e=>e.host&&e.partitionHost&&t(e)?[tp(e.partitionHost)]:[])}function V_(e,t,i,n,r,o,s=tl,a=1e3){const l=As(t.rooms,[...i],n,r,o,s,a);return e.flatMap(e=>{const t={x:e.rx,y:e.ry,angle:Number(e.angle)||0,length:e.rlen};return e.host&&"wall"!==e.host.kind?e.partitionHost&&rp(e.partitionHost,l,2e-4*s)?[t]:[]:[t]})}function K_(e,t){const i=il,n=tl,r=Ua,o=Number.isFinite(Number(t.cellCm))&&Number(t.cellCm)>0?Number(t.cellCm):5,s=Array.isArray(e?.walls)?e.walls:[],a=W_(e,t,n,r),l=function(e,t,i=tl){if(!t.length)return[];const n=e.filter(e=>e?.id),r=.02*i,o=[];for(let e=0;e{const t=[(e[0]+e[2])/2,(e[1]+e[3])/2];return h.some(e=>Un(t,e)<4*r)}).map(e=>[...e]);d.length&&o.push({a:s,b:a,segs:d})}return o}(t.rooms,a,n).flatMap(e=>e.segs),c=U_(e,t,o,n,r),h=G_(c),d=Ra(t,o,n,2e-4*n,h).all;return{space:t,walls:s,openCuts:l,openings:c,roomOpenings:V_(c,t,s,l,i,o,n,r),partitionCuts:h,physicalBodies:d,wallKeyPitch:i,cellCm:o,gridPitch:n,coordScale:r}}function Y_(e,t,i){const n="string"==typeof e?.title?e.title.trim():"",r=null==e?.id?"":String(e.id).trim();return{spaceId:r,displayName:n||r||i(t+1)}}function X_(e,t={}){const i=(t.fingerprint||cc)(e),n=Array.isArray(e?.spaces)?e.spaces:[],r=t.fallbackSpaceName||(e=>`Space ${e}`),o=t.prepareSpace||K_,s=t.wallPass||Qs,a=t.floorPass||Ys,l=[];for(let i=0;i0||d.physicalBodies.length>0;if(!d.space.rooms.length&&!u){l.push({...h,status:"not-applicable"});continue}let p=null;if(u){try{p=s(d.space.rooms,d.walls,d.openCuts,d.roomOpenings,d.wallKeyPitch,d.cellCm,d.gridPitch,d.coordScale,d.physicalBodies)}catch(e){l.push({...h,status:"failed",reason:"wall-exception",detail:B_(e)});continue}if(null==p){l.push({...h,status:"failed",reason:"wall-null"});continue}if("degraded-extra"===p.status){l.push({...h,status:"failed",reason:"wall-degraded-extra"});continue}if("failed-core"===p.status){l.push({...h,status:"failed",reason:"wall-failed-core"});continue}t.captureWallGeometry?.(d,p)}if(d.space.rooms.length&&null==p?.paperGeom){let e;try{e=a(d.space.rooms,d.walls,d.openCuts,d.wallKeyPitch,d.cellCm,d.gridPitch,d.coordScale)}catch(e){l.push({...h,status:"failed",reason:"floor-exception",detail:B_(e)});continue}if(null==e){l.push({...h,status:"failed",reason:"floor-null"});continue}}l.push({...h,status:"ok"})}const c=l.filter(e=>"failed"===e.status);return{fingerprint:i,spaces:l,failures:c,ok:0===c.length}}const Z_=e=>"string"==typeof e&&e.length>0&&e.length<=500;function J_(e){return Z_(e)&&(e.startsWith("device:")||e.startsWith("entity:"))&&e.indexOf(":")0||null===e.area&&"string"==typeof e.space&&e.space.length>0&&"string"==typeof e.room_id&&e.room_id.length>0)}(i)||i&&i.binding!==t?null:"entity"!==e.bindingKind||i?t:null}function im(e,t){return e.rooms.filter(e=>{const i=function(e){if(Array.isArray(e.poly)&&e.poly.length>=3)return e.poly;const{x:t,y:i,w:n,h:r}=e;return![t,i,n,r].every(Number.isFinite)||Number(n)<=0||Number(r)<=0?null:[[t,i],[t+n,i],[t+n,i+r],[t,i+r]]}(e);return!!i&&yi(t,i)})}function nm(e,t){return{id:e,binding:null,area:null,relocate:!1,updateSnapshot:!1,removeSnapshot:!1,reason:t}}function rm(e){const t=e.indexOf(":");return[e.slice(0,t),e.slice(t+1)]}function om(e){const t=[],i=new Set;if(!e.authoritative)return{decisions:t,relocateIds:i};const n=Q_(e.snapshot);for(const i of e.cleanupSnapshotIds||[])n[i]&&t.push({...nm(i,"registry-unverified"),removeSnapshot:!0});const r=Number.isFinite(e.coordinateScale)&&Number(e.coordinateScale)>0?Number(e.coordinateScale):1e3,o=new Map;for(const t of e.model)for(const e of t.rooms){if(!e.area)continue;const i=o.get(e.area)||[];i.push({space:t,room:e}),o.set(e.area,i)}for(const s of e.devices){const a=n[s.id],l=tm(s);if(!l){a&&t.push({...nm(s.id,"registry-unverified"),removeSnapshot:!0});continue}const c=Z_(s.area)?s.area:null;if(!c){t.push({id:s.id,binding:l,area:null,relocate:!1,updateSnapshot:!1,removeSnapshot:!1,reason:"registry-unverified"});continue}const h=o.get(c);if(!h||1!==h.length){t.push({id:s.id,binding:l,area:c,relocate:!1,updateSnapshot:!1,removeSnapshot:!1,reason:"target-unresolved"});continue}if(a?.binding===l){const e=a.area!==c;e&&i.add(s.id),t.push({id:s.id,binding:l,area:c,relocate:e,updateSnapshot:e,removeSnapshot:!1,reason:e?"area-changed":"unchanged"});continue}const d=e.layout[s.id];if(!d){t.push({id:s.id,binding:l,area:c,relocate:!1,updateSnapshot:!0,removeSnapshot:!1,reason:"new-without-layout"});continue}const[{space:u,room:p}]=h;if(d.s&&d.s!==u.id){i.add(s.id),t.push({id:s.id,binding:l,area:c,relocate:!0,updateSnapshot:!0,removeSnapshot:!1,reason:"backfill-cross-space"});continue}if(d.s!==u.id||!Number.isFinite(d.x)||!Number.isFinite(d.y)){t.push({id:s.id,binding:l,area:c,relocate:!1,updateSnapshot:!0,removeSnapshot:!1,reason:"backfill-ambiguous"});continue}const _=im(u,[d.x*r,d.y*r]),m=1===_.length?_[0]:null,g=m===p||!!m?.id&&!!p.id&&m.id===p.id,f=!!m?.area&&m.area!==c,v=!g&&f;v&&i.add(s.id),t.push({id:s.id,binding:l,area:c,relocate:v,updateSnapshot:!0,removeSnapshot:!1,reason:v?"backfill-stale-room":g?"backfill-same-room":"backfill-ambiguous"})}return{decisions:t,relocateIds:i}}const sm=1,am=/^[0-9a-f]{64}$/,lm=new WeakMap;function cm(e){const t=new Set;for(const i of e?.spaces||[])for(const e of i?.decor||[])"image"===e?.kind&&am.test(e.asset_id)&&t.add(e.asset_id);return[...t]}function hm(e,t,i){const n=Number(e.x)*t,r=Number(e.y)*i,o=Number(e.w)*t,s=Number(e.h)*i;if(![n,r,o,s].every(Number.isFinite)||o<=0||s<=0)return null;const a=n+o/2,l=r+s/2,c=Rr(e.angle);return[n,r,o,s,Mr(e.opacity,1),`translate(${a} ${l}) rotate(${c}) scale(${e.flip_h?-1:1} ${e.flip_v?-1:1}) translate(${-a} ${-l})`]}function dm(e){const t=new Map,i=e?.assets;if(!Array.isArray(i))return t;for(const e of i){const i=e,n="image/png"===i.mime?"png":"image/jpeg"===i.mime?"jpg":"image/webp"===i.mime?"webp":"image/svg+xml"===i.mime?"svg":"",r=`/api/houseplan/content/assets/_/${i.asset_id}.${n}`;!am.test(String(i.asset_id||""))||i.url!==r||"string"!=typeof i.name||!Number.isFinite(i.bytes)||Number(i.bytes)<1||!Number.isFinite(i.width)||!Number.isFinite(i.height)||Number(i.width)<=0||Number(i.height)<=0||t.set(i.asset_id,i)}return t}async function um(e,t,i){const n=[...new Set(t.filter(e=>am.test(e)))].sort(),r=e.connection||e,o=JSON.stringify([i,n]),s=lm.get(r);if(s?.[0]===o)return s[1];const a=new Map;for(let t=0;t0&&t>0?e/t:1;let n=100,r=n/i;return r>200&&(r=200,n=r*i),{w:n,h:r}}const _m=1e-5;function mm(e){const t=e.map(()=>[]);for(let i=0;i=1-1e-9||u<=1e-9||u>=1-1e-9||(t[i].push(d),t[s].push(u))}}const i=[];for(let n=0;ne-t),1];for(let e=1;e{const i=t[2]-t[0],n=t[3]-t[1],r=i*i+n*n;if(!(r>0))return Math.hypot(e[0]-t[0],e[1]-t[1]);const o=Math.max(0,Math.min(1,((e[0]-t[0])*i+(e[1]-t[1])*n)/r));return Math.hypot(e[0]-(t[0]+o*i),e[1]-(t[1]+o*n))},vm=(e,t,i,n)=>{const r=n[2]-n[0],o=n[3]-n[1],s=t*o-i*r;if(Math.abs(s)<1e-12)return 1/0;const a=n[0]-e[0],l=n[1]-e[1],c=(a*o-l*r)/s;if(!(c>1e-9))return 1/0;const h=(a*i-l*t)/s;return h<-1e-9||h>1+1e-9?1/0:c};const ym=[[0,1],[45,.88],[70,.62],[86,.32],[100,0]];function bm(){return{clipCache:new Map,geometryWarnings:new Set,featherUnits:null,renderedSources:new Map,lastAppearance:new Map,enteringSources:new Set,enterRafs:new Map,fadeTimers:new Map,featherSuspendUntil:0,featherResumeTimer:0,sourceSeq:0}}function wm(e,t){if(!e.clipCache.has(t))return{hit:!1,value:null};const i=e.clipCache.get(t)??null;return e.clipCache.delete(t),e.clipCache.set(t,i),{hit:!0,value:i}}function km(e,t,i,n=256){for(e.clipCache.delete(t),e.clipCache.set(t,i);e.clipCache.size>n;){const t=e.clipCache.keys().next().value;if(void 0===t)break;e.clipCache.delete(t)}}function xm(e){const t=Ed(e.hass,e.devices,null,e.virtualLights).filter(t=>t.device.space===e.spaceId),i=new Map;for(const e of t){if(!e.device.id)continue;const t=i.get(e.device.id)||[];t.push(e),i.set(e.device.id,t)}const n=[];for(const t of e.devices){if(!t.id||t.space!==e.spaceId)continue;const r=Nd(i.get(t.id)||[]);if(!r)continue;const o=Cn(r.passive?{state:r.on?"on":"off",attributes:{}}:e.hass.states[r.eid],t.marker?.glow_color,e.defaultColor),s=Number(t.marker?.glow_radius_cm),a=Number.isFinite(s)&&s>0?s/e.cellCm*e.gridPitch:e.defaultRadiusUnits;n.push({key:`${e.spaceId}|${t.id}`,sourceEid:r.eid,pos:e.position(t),radius:a,appearance:o?{c:o.c,alpha:Tn(o.bri,e.paletteAlpha)}:null})}return n}function Sm(e){const t=cc([e.rawSpaceConfig,e.cellCm,e.gridPitch]),i=e.space.rooms.flatMap(e=>{const t=ni(e);return t?[{room:e,poly:t}]:[]}),n=Math.max(10/e.cellCm*e.gridPitch,.5*e.gridPitch),r=e=>i.some(({poly:t})=>mi(e,t)),o=e.openings.flatMap(t=>{if("door"!==(i=String(t.type))&&"gate"!==i&&"passage"!==i)return[];var i;const o=t.angle*Math.PI/180,s=-Math.sin(o),a=Math.cos(o);return r([t.rx+s*n,t.ry+a*n])&&r([t.rx-s*n,t.ry-a*n])?[{opening:t,amount:hi(e.openingAmount(t))}]:[]});return{geometryFingerprint:t,fingerprint:cc([t,o.map(({opening:e,amount:t})=>({id:e.id,type:e.type,contact:e.contact,amount:t})).filter(e=>!!e.contact&&("door"===e.type||"gate"===e.type)).map(e=>{const t=Math.max(0,Math.min(1,Number(e.amount)||0));return`${e.id}:${t.toFixed(3)}`}).sort().join("|")]),polygons:i,passageStates:o}}function $m(e){const{revision:t}=e,i=`${e.space.id}|${t.fingerprint}`,n=[...e.zeroWalls.transmissive],r=V_(t.passageStates.filter(({amount:e})=>e>0).map(({opening:e,amount:t})=>({...e,rlen:di(e.rlen,t)})),e.space,[...e.walls],e.zeroWalls.contour,e.wallKeyPitch,e.cellCm,e.gridPitch,e.coordScale);for(const e of r){const t=e.angle*Math.PI/180,i=Math.cos(t)*e.length/2,r=Math.sin(t)*e.length/2;n.push([e.x-i,e.y-r,e.x+i,e.y+r])}const o=t.passageStates.flatMap(({opening:e,amount:t})=>t>0&&e.partitionHost?[Sa(tp(e.partitionHost),t)]:[]),s=e.physicalBodies(o,i),a=[],l=e.sharedWallGeometry?.sourceFingerprint,c=(e.sharedWallGeometry&&l===t.geometryFingerprint?function(e,t=[],i=[],n={}){if("failed-core"===e.status||"not-applicable"===e.status)return null;const r=e.roomComponents?.length?e.roomComponents:Hs(e.roomGeom)?[{id:"room-primary",geom:e.roomGeom}]:[];let o=r[0]?.geom||null;const s=r.slice(1).map(e=>({...e}));try{for(const i of t){if(!(i.length>0&&e.openingIndex))continue;const t=la(e.openingIndex,i,!0);if(!t.negative&&!t.positive)continue;const n=i.angle*Math.PI/180,r=Math.cos(n),a=Math.sin(n),l=-a,c=r,h=i.length/2,d=e.openingPadUnits??1.25*Math.max(e.depthUnits,1),u=Ns([[i.x-r*h-l*d,i.y-a*h-c*d],[i.x+r*h-l*d,i.y+a*h-c*d],[i.x+r*h+l*d,i.y+a*h+c*d],[i.x-r*h+l*d,i.y-a*h+c*d]]);o&&(o=Gt(o,u));for(const e of s)e.geom=Gt(e.geom,u)}const r=[...s];let a=s.length;const l=n.mergeExtra||((e,t)=>e?Wt(e,t):t);for(let e=0;ee.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]))||Math.abs(Ci(t))<=1e-9){a++;continue}const n=[Ns(t)];try{const t=l(o,n,e);if(!Hs(t))throw new Error("invalid extra union");o=t}catch{a++,Hs(n)&&r.push({id:`policy-extra-${e}`,geom:n})}}r.sort((e,t)=>Xs(e.geom).localeCompare(Xs(t.geom)));const c=o||[];return{status:a?"degraded-extra":"ok",geom:c,components:[...Hs(c)?[{id:"primary",geom:c}]:[],...r.map((e,t)=>({...e,id:`isolated-${t}`}))]}}catch{return null}}(e.sharedWallGeometry,r,s):null)||(e.walls.length||s.length?Qs(e.space.rooms,[...e.walls],e.zeroWalls.contour,r,e.wallKeyPitch,e.cellCm,e.gridPitch,e.coordScale,s):null);if(!c||"ok"!==c.status&&"degraded-extra"!==c.status)for(const e of s)a.push(...gm(e));else for(const e of c.components)for(const t of za(e.geom))a.push(...gm(t));const h=.02*e.gridPitch;for(const{poly:e}of t.polygons){const t=n.length?Fn(e,n,h):gm(e);for(const e of t)a.push(e)}for(const t of e.zeroWalls.barriers)a.push(t);return{occluders:mm(a),floor:t.polygons.map(({poly:e})=>e),fingerprint:t.fingerprint,masonryGeometry:!c||"ok"!==c.status&&"degraded-extra"!==c.status?[]:c.components.flatMap(e=>e.geom),opaqueBodies:s}}function Mm(e){const t=function(e,t,i,n=96){if(!(t>0&&Number.isFinite(e[0])&&Number.isFinite(e[1])))return[];const r=[];for(const n of i){if(!n||n.length<4)continue;if(![n[0],n[1],n[2],n[3]].every(Number.isFinite))continue;const i=fm(e,n);if(i<1e-7)return[];i>t||r.push(n)}const o=[],s=Math.max(12,Math.round(n));for(let e=0;ee-t);const l=[];let c=Number.NEGATIVE_INFINITY;for(const i of o){if(i-c<1e-9)continue;c=i;const n=Math.cos(i),o=Math.sin(i);let s=t;for(const t of r){const i=vm(e,n,o,t);i=3?l:[]}([e.source.x,e.source.y],e.radius,e.scene.occluders,96);return{lit:t.length>=3?Aa([t],e.scene.floor,{onBoundsFailure:({boundIndex:t,phase:i})=>{const n=e.polygons[t]?.room;e.onBoundsFailure?.(n?.id||`#${t}`,i)}}):[]}}function Rm(e,t){return i=[e.x,e.y],n=t.masonryGeometry,r=t.opaqueBodies,Ea(i,n)||r.some(e=>Oa(i,e));var i,n,r}function Cm(e,t){if(t.reducedMotion())return;const i=t.window();e.featherSuspendUntil=Math.max(e.featherSuspendUntil,Date.now()+500),i.clearTimeout(e.featherResumeTimer);const n=()=>{e.featherResumeTimer=0,Date.now(){e.enterRafs.get(i)===n&&(e.enterRafs.delete(i),e.enteringSources.delete(i),t.isConnected()&&t.requestUpdate())});e.enterRafs.set(i,n)}return{domId:o,entering:e.enteringSources.has(i),leaving:!1}}if(null==o)return null;const s=e.enterRafs.get(i);if(null!=s&&r.cancelAnimationFrame(s),e.enterRafs.delete(i),e.enteringSources.delete(i),!e.fadeTimers.has(i)){Cm(e,t);const n=r.setTimeout(()=>{e.fadeTimers.get(i)===n&&(e.fadeTimers.delete(i),e.renderedSources.delete(i),e.lastAppearance.delete(i),t.isConnected()&&t.requestUpdate())},534);e.fadeTimers.set(i,n)}return{domId:o,entering:!1,leaving:!0}}function Dm(e,t,i){const n=t.window(),r=e.fadeTimers.get(i),o=e.enterRafs.get(i);null!=r&&n.clearTimeout(r),null!=o&&n.cancelAnimationFrame(o),e.fadeTimers.delete(i),e.enterRafs.delete(i),e.enteringSources.delete(i),e.renderedSources.delete(i),e.lastAppearance.delete(i)}function Am(e,t,i){const n=`${i}|`;for(const i of[...e.renderedSources.keys()])i.startsWith(n)&&Dm(e,t,i)}function Pm(e,t,i,n){const r=`${i}|`;for(const i of[...e.renderedSources.keys()])i.startsWith(r)&&!n.has(i)&&Dm(e,t,i)}function Fm(e,t){const i=t.window();for(const t of e.fadeTimers.values())i.clearTimeout(t);for(const t of e.enterRafs.values())i.cancelAnimationFrame(t);i.clearTimeout(e.featherResumeTimer),e.clipCache.clear(),e.geometryWarnings.clear(),e.fadeTimers.clear(),e.enterRafs.clear(),e.enteringSources.clear(),e.renderedSources.clear(),e.lastAppearance.clear(),e.featherUnits=null,e.featherSuspendUntil=0,e.featherResumeTimer=0,e.sourceSeq=0}function zm(e,t,i,n,r){const o=`${t}|${i}|${n}`;if(!e.geometryWarnings.has(o)){if(e.geometryWarnings.size>=128){const t=e.geometryWarnings.values().next().value;t&&e.geometryWarnings.delete(t)}e.geometryWarnings.add(o),console.warn(`HOUSEPLAN GLOW GEOMETRY FALLBACK: #218, space ${t}, room ${n}, phase ${r}`)}}function Im(e,t,i){const n=1/(t>0?t:1),r=i&&Date.now()>=e.featherSuspendUntil;return(null==e.featherUnits||r)&&(e.featherUnits=n),{feather:e.featherUnits??n,enabled:r}}function Om(e){if(!e.spots.length)return W``;const t=4*e.feather,i=e.spots.reduce((e,i)=>({x:Math.min(e.x,i.pos.x-i.r-t),y:Math.min(e.y,i.pos.y-i.r-t),maxX:Math.max(e.maxX,i.pos.x+i.r+t),maxY:Math.max(e.maxY,i.pos.y+i.r+t),w:0,h:0}),{x:1/0,y:1/0,maxX:-1/0,maxY:-1/0,w:0,h:0});i.w=i.maxX-i.x,i.h=i.maxY-i.y;const n=e.enabledClip?.length?e.enabledClip:null;return W` - ${Te(e.spots,e=>e.key,e=>{const t=e.domId;return W` - - ${ym.map(([t,i])=>W` - `)} - - ${e.geometry?W` - - - `:G}`})} - ${n?W`${n.map(e=>W` - `)} - `:G} - - - - - `}const Em=new WeakMap,Nm=new WeakMap,Hm=new WeakMap,Lm=new WeakMap;function Bm(e,t){const i=e.get(t);return void 0!==i&&(e.delete(t),e.set(t,i)),i}function qm(e,t,i,n){for(e.delete(t),e.set(t,i);e.size>n;)e.delete(e.keys().next().value)}function jm(e){const t=Za(e.cfg),i={};for(const t of e.cfg.spaces||[])for(const e of t.rooms||[])e.area&&(i[e.area]=t.id);const n=lu(e.cfg.settings),r=Ee(e.cfg.settings?.icon_rules?.length?e.cfg.settings.icon_rules:Oe);return iu({hass:e.hass,registry:e.registry,areaToSpace:i,markers:e.cfg.markers||[],settings:e.cfg.settings||{},excluded:n,showAll:!!e.cfg.settings?.show_all,firstSpaceId:t[0]?.id||"",loc:t=>xp(e.lang,t),iconRules:r})}function Wm(e){const t=Za(e.cfg),i=t.find(t=>t.id===e.spaceId);if(!i)return null;const n=un(e.cfg.spaces.find(t=>t.id===e.spaceId)),r=gn(e.cfg.settings),o=e.iconSize??2.5,s=o>8?2.5:o,a=x_(s),l=e.registry?ad(e.hass,e.registry):e.hass,c=e.registry?ld(e.hass,e.registry):e.hass,h=e.devices||jm(e),d=e.areaRelocationIds||om({devices:h,model:t,layout:e.layout,snapshot:e.cfg.settings?.marker_area_snapshot,authoritative:!0===e.registry?.authoritative,coordinateScale:Ua}).relocateIds,u=h.filter(t=>t.space===e.spaceId),p=u.filter(e=>!e.hidden),_=function(e,t,i){const n={},r=i/100*xl(t)*1.3;for(const i of t.rooms){if(!i.area)continue;const t=e.filter(e=>e.area===i.area);if(!t.length)continue;const o=Rl(i),s=.1*Math.min(o.w,o.h),a=o.w-2*s,l=o.h-2*s,c=Math.max(1,Math.round(Math.sqrt(t.length*a/Math.max(l,1)))),h=a/c,d=l/Math.max(Math.ceil(t.length/c),1),u=t.map((e,t)=>({x:o.x+s+h*(t%c+.5),y:o.y+s+d*(Math.floor(t/c)+.5)}));Ei(u,o,r,.5*s),t.forEach((e,t)=>n[e.id]=rl(u[t]))}return n}(u,i,s),m=Ee(e.cfg.settings?.icon_rules?.length?e.cfg.settings.icon_rules:Oe),g=cu(l,m,e.cfg.markers||[],lu(e.cfg.settings)),f=t=>{const n=t.settings?.temp_source;if(n)return ru(l,n,"temp",e.cfg.markers||[]);const r=su(i.id,t);return r?g.get(r)?.temp??null:null},v=[];for(const t of p){const i=e.layout[t.id];if(i&&i.s===e.spaceId){const e=i.x*Ua,t=i.y*Ua;v.push({minX:e,minY:t,maxX:e,maxY:t})}}const y=e.cfg.spaces.find(t=>t.id===e.spaceId)||{};if(!n.hideDecor)for(const t of y.decor||[]){if("image"!==t?.kind||!e.decorAssetUrl?.(String(t.asset_id||"")))continue;const i=_l(t);i&&v.push(i)}const b=Array.isArray(y.walls)?y.walls:[],w=Number(y.cell_cm)>0?Number(y.cell_cm):5,k=H_(y,i,Ua,.02*tl),x=(y.openings||[]).flatMap(e=>{if("partition"!==e.host?.kind)return[];const t=Ju(e,i.partitions,Ua,w,tl).resolved;return t?[t]:[]}),S=cc({partitions:i.partitions,columns:i.wall_columns,cellCm:w,hostedOpenings:x.map(e=>({id:e.opening.id,host:e.host,length:e.length,type:e.opening.type}))}),$=function(e,t,i,n){let r=Nm.get(e);r||(r=new Map,Nm.set(e,r));const o=r.get(t);if(o?.fingerprint===i)return o.value;const s=n();return r.set(t,{fingerprint:i,value:s}),s}(e.cfg,i.id,S,()=>Ra(i,w,tl,2e-4*tl,x.map(tp)).all);for(const e of $){const t=e.map(e=>e[0]),i=e.map(e=>e[1]);t.length&&v.push({minX:Math.min(...t),minY:Math.min(...i),maxX:Math.max(...t),maxY:Math.max(...i)})}for(const e of k.lines)v.push({minX:Math.min(e[0],e[2]),minY:Math.min(e[1],e[3]),maxX:Math.max(e[0],e[2]),maxY:Math.max(e[1],e[3])});const M=function(e,t=1e3){const i=[];for(const[n,r]of(e||[]).entries()){if("passage"!==r?.type)continue;const e={...r,id:String(r.id||`passage-${n}`),type:"passage",rx:Number(r.x)*t,ry:Number(r.y)*t,rlen:Number(r.length)*t};[e.rx,e.ry,e.rlen,e.angle].every(Number.isFinite)&&e.rlen>0&&i.push(e)}return i}((y.openings||[]).flatMap(e=>{if(!e.host||"wall"===e.host.kind)return[e];const t=x.find(t=>t.opening.id===e.id);return t?[sp(e,t,Ua)]:[]}),Ua),R=As(i.rooms,b,k.contour,il,w,tl,Ua),C=x.filter(e=>rp(e,R,2e-4*tl)).map(e=>({x:e.center[0],y:e.center[1],angle:e.angle,length:e.length})),T=cl(e.fit),D=!!(b.length||$.length&&n.showBorders),A=D?cc(M.length?{rooms:i.rooms,walls:b,extras:$,cellCm:w,zero:k.contour,passages:M.map(e=>({x:e.rx,y:e.ry,angle:e.angle,length:e.rlen})),hostedCompositeOpenings:C}:{rooms:i.rooms,walls:b,extras:$,cellCm:w,zero:k.contour}):"",P=D?function(e,t,i,n){let r=Em.get(e);r||(r=new Map,Em.set(e,r));const o=r.get(t);if(o?.fingerprint===i)return o.value;const s=n();return r.set(t,{fingerprint:i,value:s}),s}(e.cfg,i.id,A,()=>{const e=ea(i.rooms,b,k.contour,[...M.filter(e=>"partition"!==e.host?.kind).map(e=>({x:e.rx,y:e.ry,angle:e.angle,length:e.rlen})),...C],il,w,tl,Ua,$);return e&&Object.defineProperty(e,"sourceFingerprint",{value:cc([y,w,tl]),enumerable:!1}),e}):null;let F=wl(i,v,e.compactTopFrame?{top:0,right:.05,bottom:.05,left:.05}:.05);if("house"===T){const e=[],t=Ba(2.5,w)/2,r=Ba(.6,w)/2;for(const n of i.rooms){const i=pl(n);i&&e.push(ul(i,t))}if(n.showBorders)for(const t of P?.components||[]){const i=dl(t.geom);i&&e.push(ul(i,r))}if(n.showBorders)for(const t of $){const i=dl(t);i&&e.push(ul(i,r))}if(n.showBorders)for(const i of k.lines){const n={minX:Math.min(i[0],i[2]),minY:Math.min(i[1],i[3]),maxX:Math.max(i[0],i[2]),maxY:Math.max(i[1],i[3])};e.push(ul(n,t))}if(!n.hideOpenings)for(const t of x){const i=t.opening,n="gate"===i.type?!i.flip_v:!!i.flip_v,r=Ap({type:i.type,length:t.length,angle:t.angle,flipH:!!i.flip_h,flipV:!!i.flip_v,cellCm:w,gridPitch:tl,face:ip(t,n)},t.center);r&&e.push(r)}F=bl(e)||F}const z=[F.x,F.y,F.w,F.h],I=new Map(i.rooms.map(t=>{const i=Nn(n.fill,t),o=dn(n.tempMin,n.tempMax,t);return[t,vn(i,"lqi"===i&&t.area?hu(l,u,t.area):null,"light"===i?Hd(Ed(l,u,t,e.virtualLights)):"none","temp"===i?f(t):null,o.min,o.max,r,hn(n.customFill,t))]})),O=new Map;for(const e of i.rooms)e.id&&O.set(e.id,I.get(e)||null);const E=i.rooms.filter(e=>e.area||n.showBorders||"none"!==Nn(n.fill,e)).map(e=>{let t="room "+(i.bg?"overlay":"yard"),r="";const o=Nn(n.fill,e);if(n.showBorders||"none"!==o){t+=" styled";const i=[`--room-stroke:${n.color}`,`--room-stroke-op:${n.showBorders&&!k.contour.length?n.opacity:0}`],o=I.get(e)||null;o?(t+=" filled",i.push(`--room-fill:${o.color}`,`--room-fill-op:${o.opacity.toFixed(3)}`)):i.push("--room-fill:transparent","--room-fill-op:0"),r=i.join(";")}const s=e.id||G,a=e.area||G,l=e.poly?W``:W``;return l}),N=i.rooms.filter(e=>Hn(n.glow,e)),H=N.filter(e=>{const t=I.get(e);return!t||t.opacity<=0}).map(e=>e.poly?W``:W``),L=new Map;for(const e of i.rooms)if(e.id){const t=I.get(e)||null;L.set(e.id,Hn(n.glow,e)&&(!t||t.opacity<=0)?{color:r.glow_base.c,opacity:r.glow_base.a,mode:"glow"}:null)}const B=Ed(l,p,null,e.virtualLights),q=p.map(t=>{const r=Cl(t,e.layout,e.cfg,_,i,d),o=(r.x-z[0])/z[2]*100,s=(r.y-z[1])/z[3]*100,a=n.showLqi??!1!==e.showSignal,h=e.presentations?.get(f_(t.id,a))||p_(l,t,{liveStates:!1!==e.liveStates,showTemperature:!1!==e.showTemperature,showSignal:a,activityRuntime:e.activityRuntime?.get(t.id),sourceDetails:!1,lightDevices:p,lightSources:B,registryHass:c,reducedMotion:e.reducedMotion}),u=[`left:${o}%`,`top:${s}%`,...b_(h)],m=i_(h),g=t_([t.name,xp(e.lang,`marker.state_a11y_${m}`),"none"!==h.pulse.kind?xp(e.lang,`marker.pulse_a11y_${h.pulse.reason}`):"",h.valueFullText||h.valueText||"",zp(h.valueBadge),null!=h.lqiText&&h.lqiBand?xp(e.lang,`marker.lqi_a11y_${h.lqiBand}`,{value:h.lqiText}):""]);return j``}),U=n.showNames?i.rooms.filter(e=>e.name).map(t=>{const r=Tl(t,i.id,e.layout,e.cfg),o=(r.x-z[0])/z[2]*100,s=(r.y-z[1])/z[3]*100,a=Math.min(1,n.opacity+.25);return j`
${t.name}
`}):[],V=i.bg?e.displayUrl?e.displayUrl(i.bg.href):i.bg.href:"",K=(y.decor||[]).flatMap(t=>{if("image"!==t?.kind||n.hideDecor)return[];const i=e.decorAssetUrl?.(String(t.asset_id||""))||"",r=i&&e.displayUrl?e.displayUrl(i):i;if(!r)return[];const o=hm(t,Ua,Ua);if(!o)return[];const[s,a,l,c,h,d]=o;return[W`e.assetLoaded?.(i,r)} - preserveAspectRatio="none" transform=${d} pointer-events="none">`]}),Y=e.cfg.spaces.find(t=>t.id===e.spaceId)?.settings||{},X="daynight"===yr(e.cfg?.settings,Y)?sr(l,e.dayCycleNow??new Date):null,Z=pn(e.cfg?.settings,n),J=M.length&&b.length?function(e,t,i,n,r,o,s,a=1){return[r,o,s,a].every(Number.isFinite)&&o>0&&a>0&&i?.length?pa(oa(e,i,n,r,o,s,a),t):t.map(()=>null)}(i.rooms,M.map(e=>({x:e.rx,y:e.ry,angle:e.angle,length:e.rlen})),b,k.contour,il,w,tl,Ua):M.map(()=>null),Q=M.length?S_({openings:M,geometries:J,fillsByRoomId:O,idPrefix:`${i.id}-static-data`,groupClass:"opening-tunnels static-opening-tunnels",dataLayer:"data"}):G,ee=M.length?S_({openings:M,geometries:J,fillsByRoomId:L,idPrefix:`${i.id}-static-glow`,groupClass:"opening-tunnels glow-base-tunnels static-opening-tunnels",dataLayer:"glow-base"}):G,te=b.length&&P?.paperD?[{path:P.paperD}]:ri(i.rooms),ie=n.showBorders?P:null,ne=e.stageWidth&&z[2]?e.stageWidth/z[2]:1,re=To(w),oe=!!ie&&(Co(ie.depthUnits,ne)||Do(re,ne)),se=n.color||"#607d8b";let ae=G;const le=e.glowRuntime;if(e.lightPools&&le&&N.length){const t=U_(y,i,w,tl,Ua),n=Sm({rawSpaceConfig:y,space:i,openings:t,cellCm:w,gridPitch:tl,openingAmount:e=>{const t=e.contact?l.states?.[e.contact]:null;return ci(e.type,t?.state,!!e.invert,t?.attributes?.current_position)}}),o=function(e,t,i,n){let r=Hm.get(e);r||(r=new Map,Hm.set(e,r));let o=r.get(t);o||(o=new Map,r.set(t,o));const s=Bm(o,i);if(s)return s;const a=n();return qm(o,i,a,8),a}(e.cfg,i.id,n.fingerprint,()=>$m({space:i,revision:n,walls:b,zeroWalls:k,wallKeyPitch:il,cellCm:w,gridPitch:tl,coordScale:Ua,sharedWallGeometry:P,physicalBodies:e=>Ra(i,w,tl,2e-4*tl,e).all})),s=Number(e.cfg.settings.glow_radius_cm),a=Number.isFinite(s)&&s>0?s:300,c=xm({hass:l,devices:p,virtualLights:e.virtualLights,spaceId:i.id,defaultColor:r.glow_light.c,paletteAlpha:r.glow_light.a,defaultRadiusUnits:a/w*tl,cellCm:w,gridPitch:tl,position:t=>Cl(t,e.layout,e.cfg,_,i,d)}),h=new Set,u=[];for(const e of c){if(h.add(e.key),Rm(e.pos,o)){Dm(le.state,le.host,e.key);continue}const t=Tm(le.state,le.host,e.key,!!e.appearance);if(!t)continue;e.appearance&&le.state.lastAppearance.set(e.key,e.appearance);const r=le.state.lastAppearance.get(e.key);if(!r)continue;const s=`${i.id}|${o.fingerprint}|${e.pos.x.toFixed(4)},${e.pos.y.toFixed(4)}|${e.radius.toFixed(4)}`,a=wm(le.state,s),l=a.hit?a.value:Mm({spaceId:i.id,source:e.pos,radius:e.radius,scene:o,polygons:n.polygons,onBoundsFailure:(e,t)=>zm(le.state,i.id,o.fingerprint,e,t)});a.hit||km(le.state,s,l),u.push({key:e.key,sourceEid:e.sourceEid,domId:t.domId,entering:t.entering,leaving:t.leaving,pos:e.pos,c:r.c,alpha:r.alpha,geometry:l,r:e.radius})}if(Pm(le.state,le.host,i.id,h),u.length){const t=N.length===n.polygons.length,r=`${n.geometryFingerprint}|${i.rooms.filter(e=>!N.includes(e)).map(e=>e.id||`#${i.rooms.indexOf(e)}`).sort().join(",")}`,o=t?null:function(e,t,i,n){let r=Lm.get(e);r||(r=new Map,Lm.set(e,r));let o=r.get(t);o||(o=new Map,r.set(t,o));const s=Bm(o,i);if(s)return s;const a=n();return qm(o,i,a,8),a}(e.cfg,i.id,r,()=>N.flatMap(e=>{const t=ni(e);if(!t)return[];const r=b.length&&e.id&&Es(i.rooms,e.id,b,k.contour,il,w,tl,Ua,P?.roomGeom,P?.multiWallNodes)||t,o=r.map(e=>e[0]),s=r.map(e=>e[1]),a=[Math.min(...o),Math.min(...s),Math.max(...o),Math.max(...s)],l=$.filter(e=>{const t=e.map(e=>e[0]),i=e.map(e=>e[1]);return Math.max(...t)>=a[0]&&Math.min(...t)<=a[2]&&Math.max(...i)>=a[1]&&Math.min(...i)<=a[3]}),c=l.length?Pa(r,l):null,h=c?wa(c):"",d=Ri(r,n.polygons.filter(({room:t})=>t!==e).map(({poly:e})=>e)),u=e=>`M ${e.map(e=>`${e[0]} ${e[1]}`).join(" L ")} Z`;return[[h||u(r),...d.map(u)].join(" ")]})),s=Im(le.state,e.stageWidth&&z[2]?e.stageWidth/z[2]:1,!0);ae=Om({spots:u,enabledClip:o,feather:s.feather,featherEnabled:s.enabled,screenBlend:le.screenBlend})}}else le&&Am(le.state,le.host,i.id);const ce=n.hideOpenings?[]:x.map(e=>{const t=e.opening,i="passage"!==t.type&&t.contact?l.states?.[t.contact]:null,n=ci(t.type,i?.state,!!t.invert,i?.attributes?.current_position),r=n>0&&!!t.contact,o="gate"===t.type?!t.flip_v:!!t.flip_v,s={type:t.type,length:e.length,angle:e.angle,amount:n,flipH:!!t.flip_h,flipV:!!t.flip_v,base:se,tone:r?"var(--hp-open)":se,cellCm:w,gridPitch:tl,face:ip(e,o)};return W` - ${Pp(s)} - `});return j` -
- ${Sr(X)} - - ${ie?W` - - - - `:G} - ${te.map(e=>"path"in e?W``:"poly"in e?W``:W``)} - ${V?W`e.assetLoaded?.(i.bg.href,V)} - transform=${i.bg.angle?`rotate(${i.bg.angle} ${i.bg.x+i.bg.w/2} ${i.bg.y+i.bg.h/2})`:G} - preserveAspectRatio="none" />`:G} - ${E} - ${n.showBorders&&k.contour.length?W``:G} - ${Q} - ${H.length?W``:G} - ${ee} - ${K} - ${ae} - ${ie?W` - ${ie.paths.map(e=>W` - - `)} - `:G} - ${n.showBorders&&k.lines.length?W``:G} - ${ce} - - ${""} -
${q}${U}
-
- `}let Um=null,Gm=null,Vm=0,Km=-1,Ym=null,Xm=[];const Zm=new Set,Jm=(e,t)=>{"function"==typeof e&&t.push(e)};function Qm(){if(Um)return Um;try{const e=JSON.parse(localStorage.getItem("houseplan_card_cfg_v1")||"null");if(e&&e.config&&Array.isArray(e.config.spaces)){const t=e.layout||{};return{config:e.config,rev:e.rev||0,decorAssetsApi:null,summaryPanelApi:null,configFingerprint:e.config_fingerprint||cc(e.config),layout:t,layoutRev:e.layout_rev||0,layoutFingerprint:e.layout_fingerprint||cc(t),virtualLights:Hh(e.virtual_lights,e.rev||0)}}}catch{}return null}function eg(e,t=!1){if(t&&(Um=null,Vm++,Gm))return Gm.catch(()=>null).then(()=>eg(e,!1));if(Um)return Promise.resolve(Um);if(Gm)return Km!==Vm?Gm.catch(()=>null).then(()=>eg(e,!1)):Gm;return Km=Vm,Gm=async function(e,t){const[i,n]=await Promise.all([e.callWS({type:"houseplan/config/get"}),e.callWS({type:"houseplan/layout/get"})]),r=i?.rev??0,o=Um?Lh(Um.virtualLights,i?.virtual_lights,r,!!i&&"virtual_lights"in i):Hh(i?.virtual_lights,r),s={config:i?.config??null,rev:r,decorAssetsApi:1===i?.decor_assets_api?1:null,summaryPanelApi:1===i?.summary_panel_api?1:null,configFingerprint:cc(i?.config??null),layout:n?.layout??{},layoutRev:n?.rev??0,layoutFingerprint:cc(n?.layout??{}),virtualLights:o};t===Vm&&(Um=s);const a=e.connection;if(a?.subscribeEvents&&Ym!==a){for(const e of Xm)e();Xm=[],Ym=a;const e=()=>{Um=null,Vm++,Zm.forEach(e=>e())},t=[];try{if(Jm(await a.subscribeEvents(e,"houseplan_config_updated"),t),Jm(await a.subscribeEvents(e,"houseplan_layout_updated"),t),Jm(await a.subscribeEvents(e=>{if(Um){const t=Wh(Um.virtualLights,e?.data);if(t===Um.virtualLights)return;Um={...Um,virtualLights:t}}else Vm++;Zm.forEach(e=>e())},"houseplan_virtual_light_updated"),t),Ym===a)Xm=t;else for(const e of t)e()}catch{for(const e of t)e();Ym===a&&(Ym=null)}}return s}(e,Vm).finally(()=>{Gm=null,Km=-1}),Gm}const tg=3300;function ig(e,t){return{sources:e,last:Object.fromEntries(t.map(e=>[e.eid,e.state])),flashTs:0,flashKind:null,timer:0,gen:0,expiresAt:0,alarmActive:"alarm"===Ih(t).status}}function ng(e,t,i,n){n(e.timer);const r=ig(t,i);Object.assign(e,r)}function rg(e,t,i,n,r){e.flashTs&&i-e.flashTs"transition"===e.activity)&&(i(e.timer),e.flashTs=0,e.flashKind=null,e.expiresAt=0);if("alarm"===Ih(t).status){e.alarmActive||(i(e.timer),e.flashTs=0,e.flashKind=null,e.expiresAt=0);for(const i of t)e.last[i.eid]=i.state;return e.alarmActive=!0,null}if(e.alarmActive){for(const i of t)e.last[i.eid]=i.state;return e.alarmActive=!1,null}let n=null;for(const i of t){const t=Oh(e.last[i.eid],i);("event"===t||!n&&t)&&(n=t),e.last[i.eid]=i.state}return n}class sg{constructor(e,t=()=>{}){this._host=e,this._onGateChange=t,this._modality="unknown",this._gate=!1,this._media=null,this._connected=!1,this._onMediaChange=()=>this._syncGate()}get modality(){return this._modality}get hoverEnabled(){return this._gate}connect(e=globalThis.window){this._connected||(this._connected=!0,this._modality="unknown",this._media="function"==typeof e?.matchMedia?e.matchMedia("(any-hover: hover) and (any-pointer: fine)"):null,this._media?.addEventListener?.("change",this._onMediaChange),this._setGate(!1))}disconnect(){this._media?.removeEventListener?.("change",this._onMediaChange),this._media=null,this._connected=!1,this._modality="unknown",this._setGate(!1)}note(e){return this._modality=function(e,t){const i="mouse"===(n=t.pointerType)||"touch"===n||"pen"===n?n:null;var n;return i?"mouse"===i&&t.sourceCapabilities?.firesTouchEvents?e:i:e}(this._modality,e),this._syncGate(),this._modality}suspend(){this._setGate(!1)}_syncGate(){var e,t;this._setGate((e=this._modality,t=!!this._media?.matches,"mouse"===e&&t))}_setGate(e){this._gate!==e&&(this._gate=e,this._host.toggleAttribute("data-pointer-hover",e),this._onGateChange(e))}}const ag=new WeakMap;const lg=(e,t,i)=>255===e[i+3]&&t.every((t,n)=>Math.abs(e[i+n]-t)<=2);async function cg(e){const t=e.defaultView;if(!t||!t.CSS?.supports?.("mix-blend-mode","screen"))return!1;const i=[128,32,16],n=[16,64,128],r=[9,19,29],o=`\n \n \n \n \n \n `,s=t.URL.createObjectURL(new Blob([o],{type:"image/svg+xml"}));try{const o=await new Promise((e,i)=>{const n=new t.Image,r=t.setTimeout(()=>i(new Error("SVG blend probe timeout")),1e3);n.onload=()=>{t.clearTimeout(r),e(n)},n.onerror=()=>{t.clearTimeout(r),i(new Error("SVG blend probe failed"))},n.src=s}),a=e.createElement("canvas");a.width=4,a.height=1;const l=a.getContext("2d",{willReadFrequently:!0});if(!l)return!1;l.drawImage(o,0,0,4,1);const c=l.getImageData(0,0,4,1).data;return lg(c,i,0)&&lg(c,function(e,t){return[0,1,2].map(i=>Math.round(255-(255-e[i])*(255-t[i])/255))}(i,n),4)&&lg(c,n,8)&&lg(c,r,12)}catch{return!1}finally{t.URL.revokeObjectURL(s)}}function hg(e){const t=ag.get(e);if(t)return t.promise;const i={promise:Promise.resolve(!1)};return i.promise=cg(e).catch(()=>!1).then(e=>(i.resolved=e,e)),ag.set(e,i),i.promise}function dg(e){return ag.get(e)?.resolved}class ug extends he{constructor(){super(...arguments),this._spaces=null,this._spacesLoading=!1}setConfig(e){this._config=e}async _loadSpaces(){if(!this._spaces&&!this._spacesLoading&&this.hass){this._spacesLoading=!0;try{const e=await this.hass.callWS({type:"houseplan/config/get"});this._spaces=(e?.config?.spaces||[]).map(e=>({value:e.id,label:e.title||e.id}))}catch{this._spaces=[]}finally{this._spacesLoading=!1}}}get _lang(){return kp(this.hass,this._config?.language)}get _schema(){const e=this._spaces||[];return[e.length?{name:"space",selector:{select:{mode:"dropdown",options:e}}}:{name:"space",selector:{text:{}}},{name:"title",selector:{text:{}}},{name:"fit",selector:{select:{mode:"dropdown",options:[{value:"content",label:xp(this._lang,"editor.fit_content")},{value:"house",label:xp(this._lang,"editor.fit_house")}]}}},{name:"show_button",selector:{boolean:{}}},{name:"button_label",selector:{text:{}}},{name:"button_target",selector:{text:{}}},{name:"icon_size",selector:{number:{min:1,max:6,step:.1,mode:"box"}}},{name:"show_temperature",selector:{boolean:{}}},{name:"live_states",selector:{boolean:{}}},{name:"light_pools",selector:{boolean:{}}},{name:"show_signal",selector:{boolean:{}}}]}render(){if(!this.hass||!this._config)return G;const e=dp(this,gp,kp(this.hass,this._config.language));if("cold"===e)return up();if("warm"===e)return U;this._loadSpaces();const t=this._lang,i={space:xp(t,"editor.space"),title:xp(t,"editor.title"),fit:xp(t,"editor.framing"),show_button:xp(t,"editor.show_button"),button_label:xp(t,"editor.button_label"),button_target:xp(t,"editor.button_target"),icon_size:xp(t,"editor.icon_size"),show_temperature:xp(t,"editor.show_temperature"),live_states:xp(t,"editor.live_states"),light_pools:xp(t,"editor.light_pools"),show_signal:xp(t,"editor.show_signal")};return j`i[e.name]||e.name} - @value-changed=${this._valueChanged} - >`}_valueChanged(e){const t={...this._config||{},...e.detail.value};delete t.aspect_ratio;const i=new Event("config-changed",{bubbles:!0,composed:!0});i.detail={config:t},this.dispatchEvent(i)}}ug.properties={hass:{attribute:!1},_config:{state:!0},_spaces:{state:!0}},customElements.get("houseplan-space-card-editor")||customElements.define("houseplan-space-card-editor",ug);const pg=e=>{history.pushState(null,"",e),((e,t,i)=>{const n=new Event(t,{bubbles:!0,composed:!0});n.detail=i??{},e.dispatchEvent(n)})(window,"location-changed",{replace:!1})};class _g extends he{constructor(){super(...arguments),this._snap=null,this._loading=!1,this._reloadQueued=!1,this._forceReloadQueued=!1,this._reloadRetryTimer=0,this._dayCycleTimer=0,this._dayCycleClockKey="",this._stageWidth=0,this._pendingStageWidth=0,this._stageWidthRaf=0,this._haRegistryConnection=null,this._haRegistryRevision=-1,this._devices=[],this._areaRelocationIds=new Set,this._decorAssets=new Map,this._continuity=this._newContinuityController(),this._continuityHistory=[],this._continuityEpoch=0,this._continuityDataReady=!0,this._continuityPaintToken=-1,this._continuityDisposed=!1,this._renderSnapshotAt=Date.now(),this._hassSequence=0,this._connHooked=null,this._connectionWasLost=!1,this._visibleDeviceSnapshot=null,this._candidateDeviceSnapshot=null,this._stagedDeviceSnapshotToken=-1,this._capturedSnapshotSequence=-1,this._capturedSnapshotDevices=null,this._capturedSnapshotActivity="",this._capturedSnapshotVirtual="",this._activityRuntime=new Map,this._glowRuntimeState=bm(),this._glowRuntimeHost={window:()=>this.ownerDocument.defaultView||window,isConnected:()=>this.isConnected,requestUpdate:()=>this.requestUpdate(),reducedMotion:()=>this._reducedMotion},this._glowScreenBlend=!1,this._reducedMotion=!1,this._pointerModality=new sg(this),this._onMotionChange=e=>{this._reducedMotion=e.matches,this._capturedSnapshotSequence=-1,this.requestUpdate()},this._onHaRegistryUpdate=()=>{const e=nd(this.hass).revision;e!==this._haRegistryRevision&&(this._haRegistryRevision=e,this._refreshDevices(),this._capturedSnapshotSequence=-1,this.requestUpdate())},this._dayCycleTick=()=>{if(!this.isConnected||"hidden"===this.ownerDocument.visibilityState)return;const e=this._dayCycleState();if(!e)return this._dayCycleTimer&&(window.clearInterval(this._dayCycleTimer),this._dayCycleTimer=0),void(this._dayCycleClockKey="");const t=ar(e);t!==this._dayCycleClockKey&&(this._dayCycleClockKey=t,this.requestUpdate())},this._pageVisibility=e=>{if(this._continuity.visibility(e),this._dayCycleVisibility(e),"hidden"!==e.kind){if(!e.long){const e=Date.now();let t=!1;for(const i of this._activityRuntime.values())!i.flashKind||(i.expiresAt||i.flashTs+3300)>e||(i.flashTs=0,i.flashKind=null,i.expiresAt=0,t=!0);return void(t&&(this._capturedSnapshotSequence=-1,this.requestUpdate()))}Date.now()-this._renderSnapshotAt>1e3&&this._continuity.note("device-snapshot-stale"),this._continuityDataReady=!1,this._continuityPaintToken=-1,this._load(!0)}else this._pointerModality.suspend()},this._onConnLost=()=>{this._connectionWasLost=!0,this._continuityDataReady=!1,this._continuityPaintToken=-1,this._continuity.connectionLost()},this._onConnReady=()=>{!this._connectionWasLost&&this._continuity.hasCompleteFrame?this._beginContinuityCandidate("connection-ready",!1,"plan"):(this._continuityDataReady=!1,this._continuityPaintToken=-1),this._load(!0)},this._onAssetLoaded=(e,t)=>{this._signer.markLoaded(this.hass,e,t),this._continuity.note("asset-ready"),this._continuityPaintToken=-1,"steady"!==this._continuity.state&&this.requestUpdate()},this._loadedOnce=!1,this._signer=new uc(()=>this.requestUpdate()),this._retryContinuity=()=>{this._continuityDataReady=!1,this._continuityPaintToken=-1,this._continuity.retry(this._continuity.recoveryReason||"plan"),this._load(!0)},this._goToSpace=()=>{const e=(this._config?.button_target||"/plan-doma").replace(/#.*$/,"");pg(`${e}#space=${encodeURIComponent(this._config.space)}`)}}_ensureHaRegistryAuthority(){const e=this.hass?.connection||null;e&&e!==this._haRegistryConnection&&(this._haRegistryRelease?.(),this._haRegistryConnection=e,this._haRegistryRevision=-1,this._haRegistryRelease=td(this.hass,this._onHaRegistryUpdate),this._onHaRegistryUpdate())}_newContinuityController(){return new lc(()=>{this._continuityEpoch++,this.isConnected&&this.requestUpdate()})}_dayCycleState(e=new Date){const t=this._snap?.config;if(!t||!this._config)return null;const i=t.spaces?.find(e=>e.id===this._config?.space)?.settings||{};return"daynight"!==yr(t.settings,i)?null:sr(this._renderDeviceSnapshot?.hass||this.hass,e)}_syncDayCycleClock(){const e=this._dayCycleState();this._dayCycleClockKey=e?ar(e):"";const t="clock"===e?.source&&"hidden"!==this.ownerDocument.visibilityState&&this.isConnected;t&&!this._dayCycleTimer?this._dayCycleTimer=window.setInterval(this._dayCycleTick,3e4):!t&&this._dayCycleTimer&&(window.clearInterval(this._dayCycleTimer),this._dayCycleTimer=0)}_dayCycleVisibility(e){"hidden"!==e.kind?(this._dayCycleTick(),this._syncDayCycleClock()):this._dayCycleTimer&&(window.clearInterval(this._dayCycleTimer),this._dayCycleTimer=0)}_hookConnection(){const e=this.hass?.connection;e&&e!==this._connHooked&&(this._connHooked?.removeEventListener?.("ready",this._onConnReady),this._connHooked?.removeEventListener?.("disconnected",this._onConnLost),this._connHooked?.removeEventListener?.("reconnect-error",this._onConnLost),e.addEventListener?.("ready",this._onConnReady),e.addEventListener?.("disconnected",this._onConnLost),e.addEventListener?.("reconnect-error",this._onConnLost),this._connHooked=e)}static getConfigElement(){return document.createElement("houseplan-space-card-editor")}static getStubConfig(e){const t=Qm();return{type:"custom:houseplan-space-card",space:Za(t?.config||null)[0]?.id||"",show_button:!0,fit:"content",live_states:!0,show_temperature:!0,show_signal:!0,light_pools:!1}}setConfig(e){if(!e||!e.space)throw new Error('houseplan-space-card: "space" is required');this._config={show_button:!0,button_target:"/plan-doma",live_states:!0,show_temperature:!0,show_signal:!0,light_pools:!1,...e,fit:cl(e.fit)},!0!==this._config.light_pools?Fm(this._glowRuntimeState,this._glowRuntimeHost):this.isConnected&&this._resolveGlowBlend(),this._snap=this._snap||Qm()}connectedCallback(){var e;this._continuityDisposed&&(this._continuity=this._newContinuityController(),this._continuityDisposed=!1,this._continuityPaintToken=-1),super.connectedCallback(),this._pointerModality.connect(this.ownerDocument.defaultView),this._motionMedia=window.matchMedia?.("(prefers-reduced-motion: reduce)"),this._reducedMotion=!!this._motionMedia?.matches,this._motionMedia?.addEventListener?.("change",this._onMotionChange),this._resolveGlowBlend(),this.hass&&this._ensureHaRegistryAuthority(),this._continuityUnsub?.(),this._continuityUnsub=sc(this.ownerDocument,this._pageVisibility),this._unsub=(e=()=>{this._beginContinuityCandidate("config-event",!1),this._reloadQueued=!0,this._load()},Zm.add(e),()=>Zm.delete(e)),this._signer.start(()=>this.hass,()=>this._referenced())}disconnectedCallback(){this._pointerModality.disconnect(),this._continuityUnsub?.(),this._continuityUnsub=void 0,this._motionMedia?.removeEventListener?.("change",this._onMotionChange),this._motionMedia=void 0,this._unsub?.(),this._unsub=void 0,window.clearTimeout(this._reloadRetryTimer),this._reloadRetryTimer=0,this._dayCycleTimer&&(window.clearInterval(this._dayCycleTimer),this._dayCycleTimer=0),this._dayCycleClockKey="",this._stageObserver?.disconnect(),this._stageObserver=void 0,this._observedStage=void 0,this._stageWidthRaf&&cancelAnimationFrame(this._stageWidthRaf),this._stageWidthRaf=0,this._pendingStageWidth=0,this._signer.dispose(),this._haRegistryRelease?.(),this._haRegistryRelease=void 0,this._haRegistryConnection=null,this._connHooked?.removeEventListener?.("ready",this._onConnReady),this._connHooked?.removeEventListener?.("disconnected",this._onConnLost),this._connHooked?.removeEventListener?.("reconnect-error",this._onConnLost),this._connHooked=null;for(const e of this._activityRuntime.values())window.clearTimeout(e.timer);this._activityRuntime.clear(),Fm(this._glowRuntimeState,this._glowRuntimeHost),this._continuityHistory=[...this._continuityHistory,...this._continuity.trace].slice(-80),this._continuity.dispose(),this._continuityDisposed=!0,super.disconnectedCallback()}_resolveGlowBlend(){if(!this._config?.light_pools)return;const e=dg(this.ownerDocument);void 0!==e&&(this._glowScreenBlend=e),hg(this.ownerDocument).then(e=>{e!==this._glowScreenBlend&&(this._glowScreenBlend=e,this.isConnected&&this.requestUpdate())})}willUpdate(e){e.has("hass")&&this.hass&&(this._hassSequence++,this._renderSnapshotAt=Date.now(),this._continuity.note("hass-snapshot"),this._ensureHaRegistryAuthority(),this._hookConnection()),!this.hass||this._loading||this._snap&&!e.has("hass")||this._snap&&this._loadedOnce||this._load(),(e.has("hass")||e.has("_snap")||e.has("_config")||!this._devices.length)&&this._refreshDevices(),this._captureRenderDeviceSnapshot(),this._continuity.hasCompleteFrame&&"steady"===this._continuity.state&&this._continuity.refreshCompleteFrame(this._frameFingerprint())}_stampActivity(e,t){rg(e,t,Date.now(),window.clearTimeout.bind(window),e=>window.setTimeout(()=>this.requestUpdate(),e))}_syncActivity(e,t,i=this.hass){if(!1===this._config?.live_states){for(const e of this._activityRuntime.values())window.clearTimeout(e.timer);return void this._activityRuntime.clear()}const n=new Set,r=Ed(t,e,null,this._snap?.virtualLights);for(const o of e){if(o.hidden)continue;if("icon_ripple"!==Li(o.marker?.display))continue;n.add(o.id);const s=l_(t,o,e,r,i),a=s.samples,l=d_(t,o,s);let c=this._activityRuntime.get(o.id);if(!c||c.sources!==l){c&&window.clearTimeout(c.timer),c=ig(l,a),this._activityRuntime.set(o.id,c);continue}const h=og(c,a,window.clearTimeout.bind(window));h&&this._stampActivity(c,h)}for(const[e,t]of this._activityRuntime)n.has(e)||(window.clearTimeout(t.timer),this._activityRuntime.delete(e))}_refreshDevices(){if(!this.hass||!this._snap?.config||!this._config)return;const e=nd(this.hass),t=jm({hass:this.hass,registry:e,cfg:this._snap.config,lang:this._lang});e.authoritative&&(this._areaRelocationIds=om({devices:t,model:Za(this._snap.config),layout:this._snap.layout||{},snapshot:this._snap.config.settings?.marker_area_snapshot,authoritative:!0}).relocateIds),this._syncActivity(t,ad(this.hass,e),this.hass),this._devices=t}_captureRenderDeviceSnapshot(){if(!this.hass)return;const e=Date.now(),t=[...this._activityRuntime.entries()].map(([t,i])=>`${t}:${i.gen}:${i.flashTs}:`+(i.flashKind&&(i.expiresAt||i.flashTs+3300)>e?1:0)).join("|"),i=this._snap?.virtualLights?`${this._snap.virtualLights.configRev}:${this._snap.virtualLights.rev}`:"";if(this._capturedSnapshotSequence===this._hassSequence&&this._capturedSnapshotDevices===this._devices&&this._capturedSnapshotActivity===t&&this._capturedSnapshotVirtual===i)return;const n=ad(this.hass,nd(this.hass)),r=new Map,o=new Set(["sun.sun"]),s=new Set,a=new Set,l=e=>{if(!e)return;const t=e.indexOf(":");if(t<0)return void o.add(e);const i=e.slice(0,t),n=e.slice(t+1);"device"===i?s.add(n):"entity"===i&&o.add(n)},c=Za(this._snap?.config||null).find(e=>e.id===this._config?.space);for(const e of c?.rooms||[])e.area&&a.add(e.area),l(e.settings?.temp_source),l(e.settings?.hum_source);const h=this._snap?.config?.spaces?.find(e=>e.id===this._config?.space);for(const e of h?.openings||[])for(const t of ui(e))o.add(t);const d=Ed(n,this._devices,null,this._snap?.virtualLights);for(const e of this._devices)for(const t of[!1,!0])r.set(f_(e.id,t),p_(n,e,{liveStates:!1!==this._config?.live_states,showTemperature:!1!==this._config?.show_temperature,showSignal:t,activityRuntime:this._activityRuntime.get(e.id),sourceDetails:!1,lightDevices:this._devices,lightSources:d,registryHass:this.hass,reducedMotion:this._reducedMotion}));const u=g_({sourceSequence:this._hassSequence,hass:n,devices:this._devices,presentations:r,entityIds:o,deviceIds:s,areaIds:a});this._capturedSnapshotSequence=this._hassSequence,this._capturedSnapshotDevices=this._devices,this._capturedSnapshotActivity=t,this._capturedSnapshotVirtual=i,this._visibleDeviceSnapshot&&"steady"!==this._continuity.state?this._candidateDeviceSnapshot=u:(this._visibleDeviceSnapshot=u,this._candidateDeviceSnapshot=null)}get _renderDeviceSnapshot(){return this._stagedDeviceSnapshotToken===this._continuity.token?this._candidateDeviceSnapshot||this._visibleDeviceSnapshot:this._visibleDeviceSnapshot||this._candidateDeviceSnapshot}_beginContinuityCandidate(e,t,i="plan"){return this._continuityDataReady=t,this._continuityPaintToken=-1,this._stagedDeviceSnapshotToken=-1,this._continuity.beginCandidate(e,i)}_backdropRaw(){return this._snap?.config&&this._config&&Za(this._snap.config).find(e=>e.id===this._config.space)?.bg?.href||""}_candidateBackdrop(e){return e&&this._config&&Za(e).find(e=>e.id===this._config.space)?.bg?.href||""}_assetsReady(){const e=this._backdropRaw();return!e||this._signer.isReady(this.hass,e)}_frameFingerprint(){const e=this._snap;return hc([e?.rev||0,e?.configFingerprint||cc(e?.config),e?.layoutRev||0,e?.layoutFingerprint||cc(e?.layout),e?.virtualLights?`${e.virtualLights.configRev}:${e.virtualLights.rev}`:"",this._config?.space||"",!0===this._config?.light_pools,this._stageWidth,this.hass?.themes?.darkMode??this.hass?.themes?.default_theme??""])}_stageValid(){const e=this._observedStage;return!!e&&e.clientWidth>0&&e.clientHeight>0}_settleContinuityFrame(){if(!this._stageValid())return;if(!this._continuity.hasCompleteFrame&&"steady"===this._continuity.state){if(this._assetsReady())return this._renderSnapshotAt=Date.now(),void this._continuity.markCompleteFrame(this._frameFingerprint());this._beginContinuityCandidate("asset-wait",!0,"asset")}if(!this._continuityDataReady)return;if(!["holding","offline-stale","overlay-pending","overlay-visible","candidate-ready"].includes(this._continuity.state))return;const e=this._continuity.token;if(this._candidateDeviceSnapshot&&this._candidateDeviceSnapshot!==this._visibleDeviceSnapshot&&this._stagedDeviceSnapshotToken!==e)return this._stagedDeviceSnapshotToken=e,void this.requestUpdate();this._continuityPaintToken!==e&&(this._continuityPaintToken=e,this._continuity.candidateReady(e)&&this._continuity.commitAfterPaint(e,{updateComplete:()=>this.updateComplete,stageValid:()=>this.isConnected&&this._stageValid(),assetsReady:()=>this._assetsReady(),frameFingerprint:()=>this._frameFingerprint()}).then(t=>{t&&e===this._continuity.token?(this._renderSnapshotAt=Date.now(),this._candidateDeviceSnapshot&&(this._visibleDeviceSnapshot=this._candidateDeviceSnapshot),this._candidateDeviceSnapshot=null,this._stagedDeviceSnapshotToken=-1):e===this._continuity.token&&(this._continuityPaintToken=-1,this._stagedDeviceSnapshotToken=-1,this._candidateDeviceSnapshot=null,this.requestUpdate())}))}updated(){const e=this.renderRoot.querySelector(".hp-static-stage")||void 0;if(e!==this._observedStage)if(this._stageObserver?.disconnect(),this._observedStage=e,e){const t=()=>{const i=e.clientWidth;if(!(i<=0||Math.abs(i-this._stageWidth)<=.5)){if(this._stageWidth<=0)return this._stageWidth=i,void this.requestUpdate();this._pendingStageWidth=i,this._stageWidthRaf||(this._stageWidthRaf=requestAnimationFrame(()=>{this._stageWidthRaf=0;const e=this._pendingStageWidth;this._pendingStageWidth=0,!e||!this._observedStage||this._observedStage.clientWidth<=0||(Math.abs(this._observedStage.clientWidth-e)>.5?t():Math.abs(e-this._stageWidth)<=.5||(this._continuity.hasCompleteFrame&&this._beginContinuityCandidate("stage-resize",!0,"stage-size"),this._stageWidth=e,this.requestUpdate()))}))}};this._stageObserver=new ResizeObserver(t),this._stageObserver.observe(e),t()}else this._stageObserver=void 0;this._syncDayCycleClock(),this._settleContinuityFrame()}async _load(e=!1){if(this.hass){if(this._loading)return this._reloadQueued=!0,void(this._forceReloadQueued||=e);this._loading=!0,this._reloadQueued=!1;try{const t=await eg(this.hass,e),i=!this._snap||this._snap.configFingerprint!==t.configFingerprint,n=!this._snap||this._snap.layoutFingerprint!==t.layoutFingerprint,r=!this._snap||this._snap.virtualLights!==t.virtualLights,o=!this._snap||this._snap.decorAssetsApi!==t.decorAssetsApi;if(1!==t.decorAssetsApi&&(this._decorAssets=new Map),i&&!await this._signer.prepareImage(this.hass,this._candidateBackdrop(t.config)))return this._continuity.note("asset-failed"),window.clearTimeout(this._reloadRetryTimer),void(this._reloadRetryTimer=window.setTimeout(()=>{this._load(!0)},1e3));if(window.clearTimeout(this._reloadRetryTimer),this._reloadRetryTimer=0,(i||n)&&this._continuity.hasCompleteFrame&&"steady"===this._continuity.state&&this._beginContinuityCandidate("structural-response",!0),i||n||r||o?this._snap=t:this._snap&&(this._snap.rev=t.rev,this._snap.layoutRev=t.layoutRev),i&&this._continuity.note("config-candidate",{configRev:t.rev}),1===t.decorAssetsApi)try{this._decorAssets=await um(this.hass,cm(t.config),t.rev)}catch{}n&&this._continuity.note("layout-candidate",{layoutRev:t.layoutRev}),r&&(this._capturedSnapshotSequence=-1),this._loadedOnce=!0,this._connectionWasLost=!1,this._continuityDataReady=!0,this._refreshDevices()}catch{}finally{if(this._loading=!1,this._continuityDataReady=!0,this.requestUpdate(),this._reloadQueued){const e=this._forceReloadQueued;this._reloadQueued=!1,this._forceReloadQueued=!1,this._load(e)}}}}get _lang(){return kp(this.hass,this._config?.language)}getCardSize(){const e=Za(this._snap?.config||null).find(e=>e.id===this._config?.space);if(e){const t=e.vb[3]/e.vb[2];return Math.max(3,Math.round(8*t))+(!1===this._config?.show_button?0:1)}return 6}_errorCard(e){return j` -
${e}
-
`}_referenced(){const e=On(this._snap?.config);for(const t of this._decorAssets.values())e.add(t.url);return e}_renderRecoveryOverlay(){if(!this._continuity.overlayVisible&&"recovery-error"!==this._continuity.state)return G;const e="connection"===this._continuity.recoveryReason;return j`
- - ${xp(this._lang,e?"continuity.restore_connection":"continuity.restore_plan")} - ${"recovery-error"===this._continuity.state?j``:G} -
`}houseplanContinuityTrace(){return[...this._continuityHistory,...this._continuity.trace].slice(-80).map(e=>({...e,...e.stage?{stage:[...e.stage]}:{}}))}render(){if(!this._config||!this.hass)return G;const e=dp(this,gp,kp(this.hass,this._config.language));if("cold"===e)return up();if("warm"===e)return U;const t=this._snap?.config;if(!t)return this._errorCard(xp(this._lang,"space_card.loading"));const i=this._config.space,n=Za(t).find(e=>e.id===i),r=void 0!==this._config.title?this._config.title:n?.title||"",o=this._renderDeviceSnapshot,s=Wm({hass:o?.hass||this.hass,cfg:t,layout:this._snap?.layout||{},spaceId:i,iconSize:this._config.icon_size,fit:this._config.fit,compactTopFrame:""===this._config.title||null===this._config.title,stageWidth:this._stageWidth,lang:this._lang,displayUrl:e=>this._signer.display(this.hass,e),decorAssetUrl:e=>this._decorAssets.get(e)?.url||"",assetLoaded:this._onAssetLoaded,registry:o?{revision:o.sourceSequence,authoritative:!1,access:"limited",entities:{...o.hass.entities},devices:{...o.hass.devices},lastSuccess:o.capturedAt}:nd(this.hass),devices:[...o?.devices||this._devices],areaRelocationIds:this._areaRelocationIds,presentations:o?.presentations,activityRuntime:this._activityRuntime,reducedMotion:this._reducedMotion,virtualLights:this._snap?.virtualLights,lightPools:!0===this._config.light_pools,glowRuntime:{state:this._glowRuntimeState,host:this._glowRuntimeHost,screenBlend:this._glowScreenBlend},liveStates:!1!==this._config.live_states,showTemperature:!1!==this._config.show_temperature,showSignal:!1!==this._config.show_signal,inert:this._continuity.overlayBlocksInteraction});if(!s)return this._errorCard(xp(this._lang,"space_card.not_found",{id:i}));const a=!1!==this._config.show_button,l=this._config.button_label||xp(this._lang,"space_card.button"),c=this._continuity.overlayVisible||"recovery-error"===this._continuity.state?this._continuity.recoveryReason:null;return j` - this._pointerModality.note(e)} - @pointerdown=${e=>this._pointerModality.note(e)} - @pointermove=${e=>this._pointerModality.note(e)}> - ${r?j`
${r}
`:G} -
- ${s} - ${this._renderRecoveryOverlay()} -
- ${a?j`
- -
`:G} -
- `}}_g.properties={hass:{attribute:!1},_config:{state:!0},_snap:{state:!0},_continuityEpoch:{state:!0}},_g.styles=[ap,o`.hp-static-title{font-weight:700;padding:10px 14px 6px;font-size:16px;color:var(--primary-text-color);}.hp-static-body{position:relative;}.hp-static-stage{position:relative;width:100%;container-type:inline-size;overflow:hidden;pointer-events:none;background:var(--ha-card-background,var(--card-background-color,#111));}.hp-static-stage svg{position:absolute;inset:0;width:100%;height:100%;display:block;z-index:1;}.hp-paper{fill:var(--ha-card-background,var(--card-background-color,#111));stroke:none;}.wallbody-fill{fill:var(--wall-fill,#ffffff);fill-opacity:var(--wall-fill-op,1);fill-rule:evenodd;stroke:none;pointer-events:none;}.wallbody{fill:url(#hp-wall-hatch);fill-rule:evenodd;stroke:var(--room-stroke,var(--hp-muted,#607d8b));stroke-width:calc(0.6px * var(--hp-cell-visual-scale,1));pointer-events:none;}.wallbody.solid{fill:none;}.hp-static-stage .devlayer{position:absolute;inset:0;z-index:2;}.hp-static-foot{padding:8px 12px 12px;pointer-events:auto;}.hp-static-btn{width:100%;padding:9px 14px;border:none;border-radius:10px;background:var(--primary-color,#3ea6ff);color:var(--text-primary-color,#fff);font-size:14px;font-weight:600;cursor:pointer;}:host([data-pointer-hover]) .hp-static-btn:hover{filter:brightness(1.08);}.hp-static-error{padding:24px;text-align:center;color:var(--secondary-text-color,#9aa4ad);}`],customElements.get("houseplan-space-card")||customElements.define("houseplan-space-card",_g),window.customCards=window.customCards||[],window.customCards.find(e=>"houseplan-space-card"===e.type)||window.customCards.push({type:"houseplan-space-card",name:"House Plan — Space (static)",description:"Read-only live schematic of a single houseplan space, with a deep-link button.",preview:!1,documentation:"https://github.com/Matysh/houseplan-card"});const mg=o`:host{--hp-editor-tray-bg-fallback:color-mix(in srgb,var(--card-background-color,var(--hp-bg)) 94%,var(--hp-line));--hp-editor-tray-bg:color-mix(in srgb,var(--card-background-color,var(--hp-bg)) 86%,transparent);--hp-editor-tray-border:color-mix(in srgb,var(--hp-line) 82%,var(--hp-accent));--hp-editor-tray-blur:8px;--hp-editor-tray-shadow:var(--shadow-2);}.editor-secondary-host{position:absolute;inset:var(--sp-2) var(--sp-4) auto;z-index:70;display:flex;justify-content:flex-end;pointer-events:none;}.editor-secondary-host.kind-palette,.editor-secondary-host.kind-group{justify-content:flex-start;}.editor-secondary{pointer-events:none;max-width:100%;display:flex;align-items:center;gap:var(--sp-3);padding:var(--sp-3) var(--sp-4);color:var(--hp-txt);background:var(--card-background-color,var(--hp-bg));background:var(--hp-editor-tray-bg-fallback);border:1px solid var(--hp-line);border-color:var(--hp-editor-tray-border);border-radius:var(--rad-l);box-shadow:var(--hp-editor-tray-shadow);opacity:0;visibility:hidden;transform:translateY(-4px);transition:opacity 0.1s ease,transform 0.1s cubic-bezier(0.2,0.7,0.2,1),visibility 0s linear 0.1s;touch-action:auto;}.editor-secondary-host.open .editor-secondary{pointer-events:auto;opacity:1;visibility:visible;transform:translateY(0);transition-duration:0.14s,0.14s,0s;transition-delay:0s;}.editor-secondary-host.blocked .editor-secondary{pointer-events:none;}@supports ((backdrop-filter:blur(1px)) or (-webkit-backdrop-filter:blur(1px))){.editor-secondary{background:var(--hp-editor-tray-bg);-webkit-backdrop-filter:blur(var(--hp-editor-tray-blur));backdrop-filter:blur(var(--hp-editor-tray-blur));}}.editor-secondary-content,.editor-group-items{display:flex;align-items:center;gap:var(--sp-3);min-width:0;}.editor-context-label{max-width:14rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-inline-end:var(--sp-4);border-inline-end:1px solid var(--hp-line);color:var(--hp-muted);font-size:var(--fs-s);}.editor-secondary.kind-palette{width:min(760px,100%);align-items:stretch;padding:0;overflow:hidden;}.editor-secondary.kind-palette .editor-secondary-content,.editor-secondary.kind-palette .furnpalette{width:100%;}.editor-secondary.kind-palette .furnpalette{max-height:38vh;border:0;background:transparent;}.editor-group-launcher .group-chevron{--mdc-icon-size:16px;transition:transform 0.14s ease;}.editor-group-launcher[aria-expanded="true"] .group-chevron{transform:rotate(180deg);}.editor-secondary .bdhint{font-size:var(--fs-s);color:var(--hp-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}.editor-secondary .dfill{display:inline-flex;align-items:center;gap:var(--sp-2);font-size:var(--fs-s);cursor:pointer;}.editor-secondary .dfill input[type="checkbox"]{width:16px;height:16px;flex:none;margin:0;padding:0;}.editor-secondary hp-color-opacity{flex:0 0 auto;}.editor-secondary input{width:74px;background:transparent;border:1px solid var(--hp-line);color:var(--hp-txt);border-radius:var(--rad-s);padding:var(--sp-3) var(--sp-4);font-size:var(--fs-m);}.editor-secondary label,.editor-secondary .hint{color:var(--hp-muted);font-size:var(--fs-s);}.editor-secondary .drawwall{display:inline-flex;align-items:center;gap:var(--sp-3);white-space:nowrap;}.editor-secondary .drawwall input{width:4.2em;}.editor-secondary .drawwall .opl{color:var(--hp-muted);font-size:var(--fs-s);}@container (min-width:560px) and (max-width:899px){.editor-secondary-content,.editor-group-items{flex-wrap:wrap;justify-content:flex-end;}}@container (max-width:559px){.editor-secondary-host{inset-inline:var(--sp-4);}.editor-secondary{max-width:100%;}.editor-secondary-content,.editor-group-items{overflow-x:auto;scrollbar-width:thin;}.editor-secondary-content>*,.editor-group-items>*{flex:none;}.editor-context-label{display:none;}}@media (prefers-reduced-motion:reduce){.editor-secondary{transition:none;}.editor-group-launcher .group-chevron{transition:none;}}`;class gg{constructor(e=50){this._undo=[],this._redo=[],this._limit=Math.max(30,Math.floor(e))}get canUndo(){return this._undo.length>0}get canRedo(){return this._redo.length>0}get undoName(){return this._undo[this._undo.length-1]?.name??null}get redoName(){return this._redo[this._redo.length-1]?.name??null}get size(){return this._undo.length}push(e){this._undo.push(e),this._undo.length>this._limit&&this._undo.splice(0,this._undo.length-this._limit),this._redo=[]}undo(){const e=this._undo.pop()??null;return e&&this._redo.push(e),e}redo(){const e=this._redo.pop()??null;return e&&this._undo.push(e),e}removeWhere(e){const t=this._undo.length,i=this._redo.length;return this._undo=this._undo.filter(t=>!e(t)),this._redo=this._redo.filter(t=>!e(t)),t+i-this._undo.length-this._redo.length}clear(){this._undo=[],this._redo=[]}}function fg(e,t){const i=e[t];return i&&Number.isFinite(i.x)&&Number.isFinite(i.y)?{x:i.x,y:i.y,..."string"==typeof i.s?{s:i.s}:{}}:null}function vg(e,t,i){if(null===i){if(!(t in e))return e;const i={...e};return delete i[t],i}const n={...e[t]||{}};delete n.x,delete n.y,delete n.s;const r={...n,x:i.x,y:i.y,...void 0!==i.s?{s:i.s}:{}};return{...e,[t]:r}}const yg="houseplan-card:version-reload-target:v1";function bg(e){if("string"!=typeof e)return null;return e.trim()||null}class wg{constructor(e){this.hooks=e,this._input={frontendVersion:null,backendVersion:null,kiosk:!1,reducedMotion:!1},this._relation={kind:"unknown"},this._banner=null,this._connected=!1,this._attemptTarget=null,this._attemptState=null,this._noticeToken=0}get relation(){return this._relation}get banner(){return this._banner}get hasCurrentMismatchNotice(){return"mismatch"===this._relation.kind&&"visible"===this._banner?.phase}connect(){this._connected||(this._connected=!0,this._attemptTarget=null,this._attemptState=null,this._reconcile())}disconnect(){(this._connected||this._banner)&&(this._connected=!1,this._cancelTimer(),this._banner&&(this._banner=null,this.hooks.changed()))}update(e){const t={frontendVersion:bg(e.frontendVersion),backendVersion:bg(e.backendVersion),kiosk:!0===e.kiosk,reducedMotion:!0===e.reducedMotion},i=function(e,t){const i=bg(e),n=bg(t);return i&&n?i===n?{kind:"equal",frontend:i,backend:n}:{kind:"mismatch",frontend:i,backend:n}:{kind:"unknown"}}(t.frontendVersion,t.backendVersion),n=!((e,t)=>e.frontendVersion===t.frontendVersion&&e.backendVersion===t.backendVersion&&e.kiosk===t.kiosk&&e.reducedMotion===t.reducedMotion)(this._input,t)||!((e,t)=>e.kind===t.kind&&("unknown"===e.kind||"unknown"!==t.kind&&e.frontend===t.frontend&&e.backend===t.backend))(this._relation,i);this._input=t,this._relation=i,n&&this._reconcile()}finishBannerExit(e){this._banner&&"leaving"===this._banner.phase&&this._banner.token===e&&(this._banner=null,this.hooks.changed())}_reconcile(){if(this._cancelTimer(),!this._connected||"mismatch"!==this._relation.kind)return this._attemptTarget=null,this._attemptState=null,void this._hideBanner();if(!this._input.kiosk)return this._attemptTarget=null,this._attemptState=null,void this._showBanner(this._relation.frontend,this._relation.backend);const e=this._relation.backend;if(this._attemptTarget===e&&null!==this._attemptState||(this._attemptTarget=e,this._attemptState=function(e,t){try{const i=e();return i?i.getItem(yg)===t?"attempted":"fresh":"unavailable"}catch{return"unavailable"}}(this.hooks.storage,e)),"fresh"===this._attemptState)return this._hideBanner(),void this._armTimer();this._showBanner(this._relation.frontend,e)}_armTimer(){this._connected&&void 0===this._timer&&"mismatch"===this._relation.kind&&this._input.kiosk&&"fresh"===this._attemptState&&(this._timer=this.hooks.clock.setTimeout(()=>{this._timer=void 0,this._tick()},250))}_cancelTimer(){void 0!==this._timer&&(this.hooks.clock.clearTimeout(this._timer),this._timer=void 0)}_tick(){if(!this._connected||"mismatch"!==this._relation.kind||!this._input.kiosk||"fresh"!==this._attemptState)return;if(!function(e){return e.connected&&e.initialFrameSettled&&e.viewOnly&&e.surfacesIdle&&e.configWritesIdle&&e.physicalWritesIdle&&e.layoutWritesIdle&&e.gesturesIdle&&e.interactionPauseElapsed&&e.baseZoom}(this.hooks.safety()))return void this._armTimer();const e=this._relation.backend,t=function(e,t){try{const i=e();return i?i.getItem(yg)===t?"attempted":(i.setItem(yg,t),"claimed"):"unavailable"}catch{return"unavailable"}}(this.hooks.storage,e);if(this._attemptTarget=e,this._attemptState="claimed"===t?"attempted":t,"claimed"===t){this._showBanner(this._relation.frontend,e);try{this.hooks.reload()}catch{}}else this._showBanner(this._relation.frontend,e)}_showBanner(e,t){"visible"===this._banner?.phase&&this._banner.frontend===e&&this._banner.backend===t||(this._banner={frontend:e,backend:t,phase:"visible",token:++this._noticeToken},this.hooks.changed())}_hideBanner(){if(this._banner)return this._input.reducedMotion?(this._banner=null,void this.hooks.changed()):void("leaving"!==this._banner.phase&&(this._banner={...this._banner,phase:"leaving",token:++this._noticeToken},this.hooks.changed()))}}const kg=1;function xg(e,t){const i=t&&"object"==typeof t?t:{};e._haIntegrationVersion=bg(i.integration_version);const n=i.support_api;e._haSupportApi="number"==typeof n&&Number.isSafeInteger(n)?n:null,e._haDecorAssetsApi=1===i.decor_assets_api?1:null,e._haSummaryPanelApi=1===i.summary_panel_api?1:null,e._haRadarStage1Api=1===i.radar_stage1_api?1:null,e._syncVersionRecovery()}function Sg(e){const t=e._stageEl,i=e._loadOk&&!e._loading&&e._continuityDataReady&&!e._resumeSettling&&!e._connectionWasLost&&!e._booting&&!e._bootFading&&!e._bootSettling&&!e._bootSoft&&e._continuity.hasCompleteFrame&&"steady"===e._continuity.state&&!e._continuity.overlayBlocksInteraction&&!!t&&t.clientWidth>0&&t.clientHeight>0,n=!(0!==e._pointers.size||0!==e._touchContacts.size||e._touchSequenceMultitouch||e._roomPointer||e._panStart||e._panLock||e._pinchStart||e._swipeStart||e._tabDrag||e._tabDragRelease||e._drag||e._deviceDrag||e._rlResize||e._resize?.dragging||e._physicalDrag||e._physicalRotate||e._opDrag||e._decorDraft||e._decorMove||e._dtDrag||e._bdDrag||e._furnTouchPending||e._compassDrag||e._viewportGestureDirty||e._devicePositionBusy||e._modeTransitionBusy||e._cameraTransition.active||e._slide||0!==e._warmModeRequest),r=!(e._editorSecondaryDialogBlocked||e._partitionDeleteDialog||e._roomDeleteDialog||e._backdropGuard||e._vacFit||e._editorSecondary?.hasOpenGroup||e._furnPalette||e._decorImagePalette);return{connected:e.isConnected,initialFrameSettled:i,viewOnly:!0===e._config?.kiosk&&"view"===e._mode&&!e._editing,surfacesIdle:r,configWritesIdle:0===e._writesPending&&!e._saveConfigDebounced.pending(),physicalWritesIdle:0===e._pendingPhysicalWrites.size,layoutWritesIdle:!e._persistLayout.pending()&&0===e._dirtyPos.size&&0===e._sentPos.size&&!e._devicePositionBusy,gesturesIdle:n,interactionPauseElapsed:Date.now()>=e._cyclePausedUntil,baseZoom:e._zoom<=1.001}}class $g{constructor(){this.seen=null,this.diagnosticsCache=null}observe(e,t,i,n){this.invalidateDiagnosticsForHass(e,t,i),this.intake(t,n)}intake(e,t){e&&this.seen!==e&&(this.seen=e,t())}invalidate(){this.diagnosticsCache=null}invalidateDiagnosticsForHass(e,t,i){this.diagnosticsCache&&(e?.entities!==t?.entities||e?.devices!==t?.devices||[...i?.entityIds||[]].some(i=>!!e?.states?.[i]!=!!t?.states?.[i]))&&this.invalidate()}diagnostics(e,t,i){if(this.diagnosticsCache)return this.diagnosticsCache;const n={active:0,ha_disabled:0,orphaned:0,unverified:0};for(const e of t)e.removed||"virtual"===e.binding||n[i(e.binding).kind]++;return this.diagnosticsCache={registry:ud(e),bindings:n},this.diagnosticsCache}}function Mg(e){const t=e;t._hassSequence++,t._renderSnapshotAt=Date.now(),t._continuity.note("hass-snapshot"),t._ensureHaRegistryAuthority(),t._planHassMemo=null,t._hookConnection(),!t._loadOk&&!t._loading&&t._loadTries<8&&t._loadFromServer(),t._maybeRebuildDevices(),t._vacTick(),t._activityTick()}function Rg(e){return!!e&&"object"==typeof e&&1===e.version}function Cg(e,t){const i=e.radar;return e.space===t&&!0!==e.hidden&&!0!==e.removed&&Rg(i)&&!0===i.enabled&&!1!==i.show_live}const Tg={ok:"radar.health_ok",off:"radar.health_off",stale:"radar.health_stale",partial:"radar.health_partial",restricted:"radar.health_restricted",incomplete:"radar.health_incomplete",position_unavailable:"radar.health_position_unavailable",unavailable:"radar.health_unavailable",needs_setup:"radar.health_needs_setup",inconsistent:"radar.health_inconsistent",unknown:"radar.health_unknown"};const Dg=e=>"number"==typeof e&&Number.isFinite(e);class Ag{constructor(e){this.host=e,this.frames=new Map,this.connection=null,this.space="",this.generation=0,this.expiryTimer=0,this.deadlines=new Map}sync(e,t){const i=this.host.hass?.connection;if(!t||!i||!this.host.isConnected)return void this.stop();if(this.unsubscribe&&this.connection===i&&this.space===e)return;this.stop(),this.connection=i,this.space=e;const n=++this.generation,r=i.subscribeMessage?.bind(i);"function"==typeof r&&Promise.resolve(r(e=>{if(n!==this.generation||!this.host.isConnected)return;const t=function(e){if(!e||"object"!=typeof e)return null;const t=e;if("string"!=typeof t.marker_id||"string"!=typeof t.server_session_id||!Number.isSafeInteger(t.seq)||"string"!=typeof t.health)return null;const i=Array.isArray(t.targets)?t.targets.slice(0,256).flatMap(e=>{if(!e||"object"!=typeof e)return[];const t=e;return"string"==typeof t.slot&&Dg(t.x)&&Dg(t.y)&&Dg(t.expires_at)&&Dg(t.reported_at)&&("bounded_latest"===t.pair_quality||"coherent"===t.pair_quality)?[{...t,included:!0===t.included,smooth:!0===t.smooth}]:[]}):[],n=Array.isArray(t.ranges)?t.ranges.slice(0,64).flatMap(e=>{if(!e||"object"!=typeof e)return[];const t=e;if(!("string"==typeof t.id&&Dg(t.x)&&Dg(t.y)&&Dg(t.radius)&&Dg(t.expires_at)&&Dg(t.reported_at)))return[];const i=Array.isArray(t.segments)?t.segments.slice(0,64).flatMap(e=>{if(!Array.isArray(e))return[];const t=e.slice(0,181).flatMap(e=>Array.isArray(e)&&2===e.length&&Dg(e[0])&&Dg(e[1])?[[e[0],e[1]]]:[]);return t.length>=2?[t]:[]}):void 0;return[{...t,...i?{segments:i}:{}}]}):[],r=Array.isArray(t.zones)?t.zones.slice(0,64).flatMap(e=>{if(!e||"object"!=typeof e)return[];const t=e;if("string"!=typeof t.id)return[];const i=t.state;if(null!==i&&"boolean"!=typeof i&&!Dg(i))return[];const n=Array.isArray(t.polygon)?t.polygon.slice(0,64).flatMap(e=>Array.isArray(e)&&2===e.length&&Dg(e[0])&&Dg(e[1])?[[e[0],e[1]]]:[]):[];return[{id:t.id,state:i,...n.length>=3?{polygon:n}:{}}]}):[];return{server_session_id:t.server_session_id,marker_id:t.marker_id,source_generation:"string"==typeof t.source_generation?t.source_generation:void 0,calibration_revision:"string"==typeof t.calibration_revision?t.calibration_revision:void 0,seq:t.seq,reported_at:Dg(t.reported_at)?t.reported_at:void 0,expires_at:Dg(t.expires_at)?t.expires_at:void 0,health:t.health,reported_presence:"boolean"==typeof t.reported_presence?t.reported_presence:null,complete:!0===t.complete,targets:i,ranges:n,zones:r}}(e);if(!t)return;if(!function(e,t){return!e||t.server_session_id!==e.server_session_id||t.source_generation!==e.source_generation||t.calibration_revision!==e.calibration_revision||t.seq>e.seq}(this.frames.get(t.marker_id),t))return;const i=function(e,t=Date.now()){if(!Dg(e.expires_at))return null;if(!Dg(e.reported_at))return Math.max(0,1e3*e.expires_at-t);const i=Math.max(0,1e3*(e.expires_at-e.reported_at)),n=Math.max(0,t-1e3*e.reported_at);return Math.max(0,i-n)}(t);"restricted"===t.health||"disabled"===t.health||0===i?(this.frames.delete(t.marker_id),this.deadlines.delete(t.marker_id)):(this.frames.set(t.marker_id,t),null==i?this.deadlines.delete(t.marker_id):this.deadlines.set(t.marker_id,this.monotonicNow()+i)),this.armExpiry(),this.host.requestUpdate()},{type:"houseplan/radar/subscribe",space_id:e})).then(e=>{n===this.generation&&this.host.isConnected?"function"==typeof e&&(this.unsubscribe=e):"function"==typeof e&&e()}).catch(()=>{n===this.generation&&this.stop()})}stop(){this.generation++,this.unsubscribe?.(),this.unsubscribe=void 0,this.connection=null,this.space="",clearTimeout(this.expiryTimer),this.expiryTimer=0,this.frames.size&&(this.frames.clear(),this.host.isConnected&&this.host.requestUpdate()),this.deadlines.clear()}armExpiry(){clearTimeout(this.expiryTimer);const e=this.monotonicNow(),t=[...this.deadlines.values()].filter(t=>t>e);if(!t.length)return;const i=Math.max(20,Math.min(...t)-e+10);this.expiryTimer=window.setTimeout(()=>{this.expiryTimer=0;let e=!1;const t=this.monotonicNow();for(const[i,n]of this.deadlines)n>t||(this.deadlines.delete(i),this.frames.delete(i),e=!0);this.armExpiry(),e&&this.host.isConnected&&this.host.requestUpdate()},i)}monotonicNow(){return globalThis.performance?.now?.()??Date.now()}}const Pg=Object.freeze({enabled:!1,z2mBaseTopics:Object.freeze([])});function Fg(e){if("string"!=typeof e)return null;const t=e.trim().replace(/^\/+|\/+$/g,"").replace(/\/{2,}/g,"/");return!t||t.length>180||/[#+\u0000-\u001f\u007f]/.test(t)?null:t}function zg(e){const t=e?.zigbee_topology;if(!t||"object"!=typeof t)return Pg;const i=t,n=Array.isArray(i.z2m_base_topics)?i.z2m_base_topics:Array.isArray(i.z2mBaseTopics)?i.z2mBaseTopics:[],r=new Set,o=[];for(const e of n){const t=Fg(e);if(t&&!r.has(t)&&(r.add(t),o.push(t),8===o.length))break}return{enabled:!0===i.enabled,z2mBaseTopics:o}}function Ig(e,t){const i={...e},n=t.z2mBaseTopics.map(Fg).filter(Boolean);return t.enabled||n.length?i.zigbee_topology={enabled:!0===t.enabled,z2m_base_topics:[...new Set(n)].slice(0,8)}:delete i.zigbee_topology,i}const Og={now:()=>performance.now(),requestFrame:e=>requestAnimationFrame(e),cancelFrame:e=>cancelAnimationFrame(e)},Eg=e=>Math.max(0,Math.min(1,e)),Ng=(e,t,i)=>e+(t-e)*i,Hg=(e,t,i)=>{const n=1-e;return 3*n*n*e*t+3*n*e*e*i+e*e*e},Lg=e=>{const t=Eg(e);if(0===t||1===t)return t;let i=0,n=1,r=t;for(let e=0;e<12;e++)r=(i+n)/2,Hg(r,.2,.2)0&&e.w>0?t/e.w:1,viewBox:{...e}}}function qg(e,t,i){const n=Math.max(1e-9,e.pixelsPerUnit),r=Math.max(1e-9,t/n),o=Math.max(1e-9,i/n);return{x:e.centerX-r/2,y:e.centerY-o/2,w:r,h:o}}function jg(e){const t=e.trim(),i=/^rgba?\(\s*([\d.]+)[, ]+([\d.]+)[, ]+([\d.]+)(?:\s*[,/]\s*([\d.]+))?\s*\)$/i.exec(t);if(i)return[Number(i[1]),Number(i[2]),Number(i[3]),null==i[4]?1:Number(i[4])];const n=/^#([0-9a-f]{6}|[0-9a-f]{8})$/i.exec(t)?.[1];return n?[parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16),8===n.length?parseInt(n.slice(6,8),16)/255:1]:null}function Wg(e,t,i){const n=jg(e),r=jg(t);if(!n||!r)return i<.5?e:t;const o=Eg(i);return`rgba(${Math.round(Ng(n[0],r[0],o))}, ${Math.round(Ng(n[1],r[1],o))}, ${Math.round(Ng(n[2],r[2],o))}, ${Ng(n[3],r[3],o).toFixed(3)})`}class Ug{constructor(e,t=Og){this._hooks=e,this._clock=t,this._token=0,this._raf=0,this._state=null}get state(){return this._state}get active(){return"running"===this._state?.phase||"preparing"===this._state?.phase}get presented(){return this._state?.presented||null}start(e,t,i,n=220){this.cancel(!1);const r=++this._token,o=this._clock.now();if(this._state={token:r,phase:n<=0?"settling":"running",from:e,to:t,presented:n<=0?t:e,startedAt:o,duration:Math.max(0,n),targetMode:i},n<=0)return this._hooks.frame(this._state),this._hooks.settled(this._state),this._state=null,r;this._hooks.frame(this._state);const s=e=>{const t=this._state;if(!t||t.token!==r)return;const i=Eg((e-t.startedAt)/t.duration);t.presented=i>=1?t.to:function(e,t,i){const n=Lg(i),r=Ng(e.stageWidth,t.stageWidth,n),o=Ng(e.stageHeight,t.stageHeight,n),s=Math.max(1e-9,e.viewport.pixelsPerUnit),a=Math.max(1e-9,t.viewport.pixelsPerUnit),l={centerX:Ng(e.viewport.centerX,t.viewport.centerX,n),centerY:Ng(e.viewport.centerY,t.viewport.centerY,n),pixelsPerUnit:Math.exp(Ng(Math.log(s),Math.log(a),n))};return{presentedMode:n<.5?e.presentedMode:t.presentedMode,editorChromeHeight:Ng(e.editorChromeHeight,t.editorChromeHeight,n),stageWidth:r,stageHeight:o,viewport:{...l,viewBox:qg(l,r,o)},stageColor:Wg(e.stageColor,t.stageColor,n),paperColor:Wg(e.paperColor,t.paperColor,n),sceneBrightness:Ng(e.sceneBrightness,t.sceneBrightness,n),architectureOpacity:Ng(e.architectureOpacity,t.architectureOpacity,n),backdropOpacity:Ng(e.backdropOpacity,t.backdropOpacity,n),viewWeight:Ng(e.viewWeight,t.viewWeight,n),editorWeight:Ng(e.editorWeight,t.editorWeight,n),toolbarContentOpacity:Ng(e.toolbarContentOpacity,t.toolbarContentOpacity,n)}}(t.from,t.to,i),t.phase=i>=1?"settling":"running",this._hooks.frame(t),i<1?this._raf=this._clock.requestFrame(s):(this._raf=0,this._hooks.settled(t),this._state?.token===r&&(this._state=null))};return this._raf=this._clock.requestFrame(s),r}cancel(e=!0){this._raf&&this._clock.cancelFrame(this._raf),this._raf=0;const t=this._state;this._state=null,this._token++,t&&e&&(t.phase="settling",t.presented=t.to,this._hooks.frame(t),this._hooks.settled(t))}dispose(){this.cancel(!1)}}const Gg={now:()=>"undefined"!=typeof performance?performance.now():Date.now(),requestFrame:e=>"function"==typeof requestAnimationFrame?requestAnimationFrame(e):null,cancelFrame:e=>{"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(e)}},Vg=e=>Number.isFinite(e);function Kg(e){return!!e&&Vg(e.zoom)&&e.zoom>0&&Vg(e.viewBox.x)&&Vg(e.viewBox.y)&&Vg(e.viewBox.w)&&e.viewBox.w>0&&Vg(e.viewBox.h)&&e.viewBox.h>0}function Yg(e){return{zoom:e.zoom,viewBox:{...e.viewBox}}}function Xg(e,t){return Math.abs(e.zoom-t.zoom)<1e-9&&Math.abs(e.viewBox.x-t.viewBox.x)<1e-6&&Math.abs(e.viewBox.y-t.viewBox.y)<1e-6&&Math.abs(e.viewBox.w-t.viewBox.w)<1e-6&&Math.abs(e.viewBox.h-t.viewBox.h)<1e-6}const Zg=(e,t,i)=>e+(t-e)*i,Jg=(e,t,i)=>Math.exp(Zg(Math.log(e),Math.log(t),i));class Qg{constructor(e,t=Gg){this._hooks=e,this._clock=t,this._token=0,this._raf=null,this._state=null}get state(){return this._state}get active(){return"running"===this._state?.phase}get presented(){return this._state?.presented||null}get target(){return this._state?.to||null}start(e,t,i,n){this.cancel(!1);const r=++this._token,o=Yg(e),s=Yg(t),a=n>0&&Kg(o)&&Kg(s),l=this._clock.now(),c={token:r,phase:a?"running":"settling",from:o,to:s,presented:Yg(a?o:s),startedAt:l,duration:a?n:0,reason:i};if(this._state=c,this._hooks.frame(c),!a)return this._settle(r),r;const h=e=>{const t=this._state;if(!t||t.token!==r)return;const i=Math.max(0,Math.min(1,(e-t.startedAt)/t.duration));if(t.presented=i>=1?Yg(t.to):function(e,t,i){if(!Kg(e))return Yg(t);if(!Kg(t))return Yg(e);const n=Lg(i);if(n<=0)return Yg(e);if(n>=1)return Yg(t);const r=e.viewBox.x+e.viewBox.w/2,o=e.viewBox.y+e.viewBox.h/2,s=t.viewBox.x+t.viewBox.w/2,a=t.viewBox.y+t.viewBox.h/2,l=Jg(e.viewBox.w,t.viewBox.w,n),c=Jg(e.viewBox.h,t.viewBox.h,n),h=Zg(r,s,n),d=Zg(o,a,n);return{zoom:Jg(e.zoom,t.zoom,n),viewBox:{x:h-l/2,y:d-c/2,w:l,h:c}}}(t.from,t.to,i),t.phase=i>=1?"settling":"running",this._hooks.frame(t),i>=1)return this._raf=null,void this._settle(r);this._raf=this._clock.requestFrame(h),null===this._raf&&this._settle(r)};return this._raf=this._clock.requestFrame(h),null===this._raf&&(c.phase="settling",c.presented=Yg(s),this._hooks.frame(c),this._settle(r)),r}cancel(e=!0){null!==this._raf&&this._clock.cancelFrame(this._raf),this._raf=null;const t=this._state;this._state=null,this._token++,t&&e&&(t.phase="settling",t.presented=Yg(t.to),this._hooks.frame(t),this._hooks.settled(t))}dispose(){this.cancel(!1)}_settle(e){const t=this._state;t&&t.token===e&&(t.phase="settling",t.presented=Yg(t.to),this._hooks.settled(t),this._state?.token===e&&(this._state=null))}}function ef(e,t,i){const n=e.querySelector("ha-card");if(!n)return null;const r=n.getBoundingClientRect(),o=t.getBoundingClientRect().top-r.top,s=i?0:Math.min(Math.max(r.top,0),120),a=Math.round(o+s);return a>=0?a:null}const tf=Object.freeze({rotDeg:0,tiltDeg:20,xyScale:1,zScale:1,origin:Object.freeze([500,500])}),nf=84,rf=10,of=4,sf=4;function af(e){return[e.rotDeg,e.tiltDeg,e.xyScale,e.zScale,e.origin[0],e.origin[1]].every(Number.isFinite)&&Math.abs(e.xyScale)>1e-12&&Math.abs(Math.cos(e.tiltDeg*Math.PI/180))>1e-12}function lf(e,t,i=tf){if(!Number.isFinite(e[0])||!Number.isFinite(e[1]))throw new Error("invalid isometric projection input");return function(e,t){if(!Number.isFinite(e[0])||!Number.isFinite(e[1])||!t.every(Number.isFinite))throw new Error("invalid isometric affine input");const[i,n,r,o,s,a]=t;return[i*e[0]+r*e[1]+s,n*e[0]+o*e[1]+a]}(e,hf(t,i))}function cf(e,t=tf){if(!af(t)||!Number.isFinite(e[0])||!Number.isFinite(e[1]))throw new Error("invalid isometric projection input");const i=t.rotDeg*Math.PI/180,n=t.tiltDeg*Math.PI/180,r=(e[0]-t.origin[0])/t.xyScale,o=(e[1]-t.origin[1])/(t.xyScale*Math.cos(n));return[t.origin[0]+r*Math.cos(i)+o*Math.sin(i),t.origin[1]-r*Math.sin(i)+o*Math.cos(i)]}function hf(e=0,t=tf){if(!af(t)||!Number.isFinite(e))throw new Error("invalid isometric camera");const i=t.rotDeg*Math.PI/180,n=t.tiltDeg*Math.PI/180,r=t.xyScale*Math.cos(i),o=-t.xyScale*Math.sin(i),s=t.xyScale*Math.sin(i)*Math.cos(n),a=t.xyScale*Math.cos(i)*Math.cos(n);return[r,s,o,a,t.origin[0]-r*t.origin[0]-o*t.origin[1],t.origin[1]-s*t.origin[0]-a*t.origin[1]-e*t.zScale*Math.sin(n)]}function df(e=tf){return function(e=0,t=tf){return`matrix(${hf(e,t).map(e=>Number(e.toFixed(12))).join(" ")})`}(0,e)}function uf(e,t=tf){const{rect:i,wallHeight:n}=e,r=e.openingHeight??n,o=e.floorDepth??0,s=e.raisedHeight??n;if(!(i.w>=0)||!(i.h>=0)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(o)||!Number.isFinite(s)||n<0||r<0||o<0||s<0)throw new Error("invalid isometric frame");const a=[[i.x,i.y],[i.x+i.w,i.y],[i.x+i.w,i.y+i.h],[i.x,i.y+i.h]],l=Math.max(n,r,s),c=a.flatMap(e=>[lf(e,-o,t),lf(e,l,t)]),h=c.map(e=>e[0]),d=c.map(e=>e[1]),u=Math.min(...h),p=Math.min(...d);return{x:u,y:p,w:Math.max(...h)-u,h:Math.max(...d)-p}}const pf=[".dev",".vacpuck",".oplock",".op-hit",".opening",".rlgo","a","button","input","select","textarea",'[contenteditable]:not([contenteditable="false"])',"[data-room-fit-block]",'[role="link"]','[role="button"]'].join(","),_f=(e,t)=>{try{return"function"==typeof e?.matches&&e.matches(t)}catch{return!1}};function mf(e){for(const t of e){const e=t;if(_f(e,".roomlabel[data-id]")){const t=e.getAttribute?.("data-id");return t?{kind:"room",roomId:t}:{kind:"interactive"}}if(_f(e,pf))return{kind:"interactive"};if(_f(e,'[data-hp="room"][data-id]')){const t=e.getAttribute?.("data-id");return t?{kind:"room",roomId:t}:{kind:"interactive"}}if(_f(e,".stage"))return{kind:"background"}}return{kind:"outside"}}function gf(e){const t=mf(e);return"room"===t.kind?t.roomId:null}class ff{constructor(){this.pointer=null,this.sequence=null}clear(){this.pointer=null,this.sequence=null}clearOutside(e){let t={kind:"outside"};try{t=mf(e.composedPath())}catch{}"outside"===t.kind&&this.clear()}pointerDown(e,t,i){let n={kind:"outside"};try{n=mf(e.composedPath())}catch{}this.pointer=function(e){const t="mouse"===(i=e.pointerType)||"touch"===i||"pen"===i?i:null;var i;return t&&"view"===e.mode&&"background"===e.owner.kind&&!e.blocked&&e.isPrimary&&0===e.button&&Number.isFinite(e.x)&&Number.isFinite(e.y)?{pointerId:e.pointerId,spaceId:e.spaceId,modality:t,x:e.x,y:e.y}:null}({pointerId:e.pointerId,pointerType:e.pointerType,isPrimary:e.isPrimary,button:e.button,spaceId:t,mode:i?"view":"blocked",owner:n,blocked:!i,x:e.clientX,y:e.clientY}),this.pointer||(this.sequence=null)}pointerUp(e,t,i,n,r=Date.now()){let o={kind:"outside"};try{o=mf(e.composedPath())}catch{}const s=function(e,t,i){if(!t||"view"!==i.mode||"background"!==i.owner.kind||i.blocked||t.pointerId!==i.pointerId||t.spaceId!==i.spaceId||!Number.isFinite(i.x)||!Number.isFinite(i.y)||!Number.isFinite(i.now)||Math.abs(i.x-t.x)+Math.abs(i.y-t.y)>=8)return{sequence:null,trigger:!1};const n=e?i.now-e.at:Number.POSITIVE_INFINITY;return e&&e.spaceId===i.spaceId&&e.modality===t.modality&&n>=0&&n<=350?{sequence:null,trigger:!0}:{sequence:{at:i.now,spaceId:i.spaceId,modality:t.modality},trigger:!1}}(this.sequence,this.pointer,{pointerId:e.pointerId,spaceId:t,mode:i?"view":"blocked",owner:o,blocked:n||!i,x:e.clientX,y:e.clientY,now:r});return this.pointer=null,this.sequence=s.sequence,s.trigger}}const vf=e=>e.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]);function yf(e){return!!e&&Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.w)&&e.w>0&&Number.isFinite(e.h)&&e.h>0}function bf(e,t=0){if(!e.length||!Number.isFinite(t)||t<0||!e.every(vf))return null;let i=1/0,n=1/0,r=-1/0,o=-1/0;for(const t of e)i=Math.min(i,t[0]),n=Math.min(n,t[1]),r=Math.max(r,t[0]),o=Math.max(o,t[1]);const s=r-i,a=o-n;return s>0&&a>0?{x:i-t,y:n-t,w:s+2*t,h:a+2*t}:null}function wf(e,t,i){const n="string"!=typeof t||"invalid"!==t&&"no-borders"!==t&&"unverified"!==t&&!/^[a-z0-9]{1,8}$/i.test(t)?"redacted":t;return Object.freeze({kind:e,fingerprint:n,terminal:!!i})}function kf(e,t){return`${e("editor.load_failed")} ${e(t.terminal?"editor.refresh_advice":"editor.retry_advice")}`}class xf extends Error{}class Sf{constructor(e){this.options=e,this._state="idle",this._inFlight=null}get state(){return this._state}ensure(){return"ready"===this._state?Promise.resolve(!0):"failed"===this._state?Promise.resolve(!1):(this._inFlight||(this._setState("loading"),this._inFlight=this._loadWithRetry().finally(()=>{this._inFlight=null})),this._inFlight)}async _loadWithRetry(){let e=new Error("Editor runtime did not load"),t=!1;for(const i of[0,1])try{const e=await this.options.load(i);if(e.fingerprint!==this.options.expectedFingerprint)throw new xf(`Editor runtime fingerprint mismatch: expected ${this.options.expectedFingerprint}, got ${e.fingerprint}`);const t=e.create();return this.options.install(t),this._setState("ready"),!0}catch(i){e=i,i instanceof xf&&(t=!0)}return this._setState(t?"failed":"idle"),this.options.failed?.(e,{terminal:t}),!1}_setState(e){e!==this._state&&(this._state=e,this.options.stateChanged?.(e))}}const $f=(e,t)=>{if(!e.has(t))return{hit:!1};const i=e.get(t);return e.delete(t),e.set(t,i),{hit:!0,value:i}},Mf=(e,t,i,n)=>{for(e.delete(t),e.set(t,i);e.size>n;){const t=e.keys().next().value;if(void 0===t)break;e.delete(t)}},Rf=new Set(["select","draw","column","merge","split","resize","opening","wallthick","delroom"]),Cf=e=>`${window.innerWidth}x${window.innerHeight}|${location.pathname}|${JSON.stringify(e??{})}`,Tf="houseplan_card_alpha_v1",Df=Object.freeze([Object.freeze({id:"iso",issue:89,summary:"Volumetric plan renderer"})]);function Af(e){return/^[a-z][a-z0-9-]*$/.test(e.id)&&Number.isInteger(e.issue)&&e.issue>0&&!!e.summary.trim()}function Pf(e){const t=String(e||"").replace(/^#/,"");return new URLSearchParams(t)}function Ff(e){return Pf(e).get("space")||""}function zf(e,t,i=Df){const n=function(e){const t=new Set;for(const i of e){if(!Af(i)||t.has(i.id))return!1;t.add(i.id)}return!0}(i),r=function(e){let t,i=!1;const n=e=>{for(const n of e.getAll("hp_alpha"))i=!0,"1"===n?t=!0:"0"===n&&(t=!1)};return n(new URLSearchParams(String(e.search||"").replace(/^\?/,""))),n(Pf(e.hash)),{present:i,value:t}}(e),o=void 0!==r.value,s="1"===t,a=o?!0===r.value:!r.present&&s,l=n&&a;return{alpha:l,active:Object.freeze(l?i.map(e=>e.id).sort():[]),space:Ff(e.hash),persist:n&&o?l?"1":"0":void 0,knownUrlOperation:o}}let If={alpha:!1,active:Object.freeze([]),space:""},Of=!1,Ef="";const Nf=new Set;function Hf(){if("undefined"==typeof window)return If;const e=zf(window.location,function(){try{return window.localStorage.getItem(Tf)}catch{return null}}());void 0!==e.persist&&function(e){try{window.localStorage.setItem(Tf,e)}catch{}}(e.persist),If={alpha:e.alpha,active:e.active,space:e.space},window.__hpAlpha=e.alpha,window.__hpLabs=e.active;for(const e of Nf)e(If);return If}function Lf(){Hf()}function Bf(){if("undefined"==typeof window)return If;if(!Of){Of=!0,window.__hpLabsListenerCleanup?.(),window.addEventListener("hashchange",Lf),window.addEventListener("popstate",Lf);const e=()=>{window.removeEventListener("hashchange",Lf),window.removeEventListener("popstate",Lf),window.__hpLabsListenerCleanup===e&&delete window.__hpLabsListenerCleanup};window.__hpLabsListenerCleanup=e}return Hf()}const qf={window:120,door:90,passage:90,gate:300};function jf(e){return qf[e]}function Wf(e,t){return{type:e,lengthCm:jf(e),flipH:!1,flipV:!1,revision:t}}function Uf(e,t){const i=Math.max(0,e.renderedLength)/2,n=Math.max(0,e.target.physicalHalfWidth),r=n+.18*Math.max(0,t),o=e=>({x1:e,y1:-r,x2:e,y2:r});return{rect:{x:-i,y:n?-n:0,width:2*i,height:2*n},boundaries:[o(-i),o(i)]}}function Gf(e,t){const i=[e[0],e[1]],n=[t[0],t[1]];return function(e,t){return e[0]-t[0]||e[1]-t[1]}(i,n)<=0?{a:i,b:n}:{a:n,b:i}}function Vf(e){const t=new Map;return e.forEach((e,i)=>{if(!e.kind||e.open)return;const n=Gf(e.a,e.b);if(Math.hypot(n.b[0]-n.a[0],n.b[1]-n.a[1])<=1e-9)return;const r=function(e,t){const i=e=>(Math.abs(e)<=5e-10?0:Math.round(1e6*e)/1e6).toFixed(6);return`${i(e[0])},${i(e[1])}>${i(t[0])},${i(t[1])}`}(n.a,n.b),o=t.get(r);if(o)return o.physicalHalfWidth=Math.max(o.physicalHalfWidth,e.half||0),o.sourceOrder=Math.min(o.sourceOrder,i),void(e.partitionHost&&(o.partitionHost&&o.partitionHost.id!==e.partitionHost.id?o.ambiguousPartitionHost=!0:o.partitionHost=e.partitionHost));t.set(r,{segmentKey:r,a:n.a,b:n.b,physicalHalfWidth:Math.max(0,e.half||0),sourceOrder:i,...e.partitionHost?{partitionHost:e.partitionHost}:{}})}),[...t.values()]}function Kf(e,t){if(Math.abs(e.distance-t.distance)>1e-9)return e.distance-t.distance;if(Math.abs(e.perpendicular-t.perpendicular)>1e-9)return e.perpendicular-t.perpendicular;return(e.target.segmentKeyt.target.segmentKey?1:0)||e.target.sourceOrder-t.target.sourceOrder}function Yf(e){const t=Vf(e.intervals).map(t=>{const i=function(e,t){const i=t.b[0]-t.a[0],n=t.b[1]-t.a[1],r=Math.hypot(i,n),o=i/r,s=n/r,a=(e[0]-t.a[0])*o+(e[1]-t.a[1])*s,l=Math.max(0,Math.min(r,a)),c=t.a[0]+l*o,h=t.a[1]+l*s;return{along:l,length:r,x:c,y:h,distance:Math.hypot(e[0]-c,e[1]-h),perpendicular:Math.abs((e[0]-t.a[0])*s-(e[1]-t.a[1])*o)}}(e.pointer,t);return{target:t,...i,envelope:Math.max(e.baseTolerance,t.physicalHalfWidth+e.bodyPointerPadding)}}).filter(e=>e.distance<=e.envelope+1e-9).filter(t=>!function(e,t,i,n,r){const o=t.b[0]-t.a[0],s=t.b[1]-t.a[1],a=Math.hypot(o,s);if(!(a>1e-9))return!1;const l=o/a,c=s/a;for(const o of i){if(!o.open&&o.kind)continue;const i=Gf(o.a,o.b),s=i.b[0]-i.a[0],a=i.b[1]-i.a[1],h=Math.hypot(s,a);if(!(h>1e-9))continue;const d=s/h,u=a/h;if(Math.abs(l*u-c*d)>1e-6)continue;if(Math.abs((i.a[0]-t.a[0])*c-(i.a[1]-t.a[1])*l)>r)continue;const p=(e[0]-i.a[0])*d+(e[1]-i.a[1])*u,_=1e-9;if(!(p<=_||p>=h-_)&&Math.abs((e[0]-i.a[0])*u-(e[1]-i.a[1])*d)<=n+1e-9)return!0}return!1}(e.pointer,t.target,e.intervals,t.envelope,Math.max(1e-9,Math.min(e.baseTolerance,.04*e.gridStep)))),i=t.filter(t=>!!t.target.partitionHost&&e.renderedLength+2*t.target.physicalHalfWidth>t.length+1e-9).sort(Kf),n=t.filter(t=>!t.target.partitionHost||e.renderedLength+2*t.target.physicalHalfWidth<=t.length+1e-9).sort(Kf);let r=n[0];if(!r)return{candidate:null,jambBlockedTarget:i[0]?.target||null};const o=n.filter(e=>Math.abs(e.distance-r.distance)<=1e-9&&Math.abs(e.perpendicular-r.perpendicular)<=1e-9),s=o.filter(e=>e.target.partitionHost);if(s.length){if(1!==new Set(s.map(e=>e.target.partitionHost.id)).size||s.some(e=>e.target.ambiguousPartitionHost))return{candidate:null,jambBlockedTarget:null};const e=s[0],t=e.target.b[0]-e.target.a[0],i=e.target.b[1]-e.target.a[1],n=Math.hypot(t,i),a=t/n,l=i/n;if(!o.every(t=>{const i=t.target.b[0]-t.target.a[0],n=t.target.b[1]-t.target.a[1],r=Math.hypot(i,n),o=i/r,s=n/r,c=Math.abs(a*s-l*o)<=1e-6,h=Math.abs((t.target.a[0]-e.target.a[0])*l-(t.target.a[1]-e.target.a[1])*a);return c&&h<=1e-9}))return{candidate:null,jambBlockedTarget:null};r=e}if(r.target.ambiguousPartitionHost)return{candidate:null,jambBlockedTarget:null};const{target:a,length:l}=r,c=a.b[0]-a.a[0],h=a.b[1]-a.a[1],d=c/l,u=h/l,p=a.partitionHost?a.physicalHalfWidth:0,_=Math.min(Math.max(0,e.renderedLength)/2+p,l/2);let m=r.along;const g=Math.max(e.gridStep,1e-9),f=l/2;m=Math.abs(m-f)<=g/2?f:Math.round(m/g)*g,m=Math.max(_,Math.min(l-_,m));const v=a.a[0]+d*m,y=a.a[1]+u*m,b=Math.max(0,e.renderedLength)/2,w=m-b,k=m+b,x=Math.max(0,w),S=Math.max(0,l-k),$=[a.a[0]+d*(w-x/2),a.a[1]+u*(w-x/2)],M=[a.a[0]+d*(k+S/2),a.a[1]+u*(k+S/2)];let R=180*Math.atan2(h,c)/Math.PI;R>=90?R-=180:R<-90&&(R+=180);const C=Math.abs(m-f)<=1e-9;return{candidate:{presetRevision:e.preset.revision,geometryRevision:e.geometryRevision,pointer:[e.pointer[0],e.pointer[1]],type:e.preset.type,lengthCm:e.preset.lengthCm,flipH:e.preset.flipH,flipV:e.preset.flipV,x:v,y:y,angle:R,renderedLength:e.renderedLength,target:a,...a.partitionHost?{host:{...a.partitionHost,t:l>0?m/l:0}}:{},measure:{labels:[{distance:x,midpoint:$},{distance:S,midpoint:M}],guide:C?{x:v,y:y,angle:R}:null}},jambBlockedTarget:null}}function Xf(e,t,i,n,r=1e-6){return e.presetRevision===i&&e.geometryRevision===n&&Math.hypot(e.pointer[0]-t[0],e.pointer[1]-t[1])<=r}function Zf(e){return!(!e.canEdit||e.kiosk||e.fixedFloor)&&("view"!==e.mode&&("mouse"===e.pointerType&&e.spaceCount>1))}class Jf{constructor(e,t,i){this.loader=e,this.host=t,this.adopted=i,this.attachment=null}connect(){if(this.runtime)return void this.runtime.connect();this.attachment?.cancel();const e=this.loader.attach(this.host,e=>this.adopt(e));this.runtime||(this.attachment=e)}disconnect(){this.attachment?.cancel(),this.attachment=null,this.runtime?.disconnect()}adopt(e){this.attachment=null,this.runtime||(this.runtime=e,this.adopted(e))}}const Qf=new class{constructor(e){this.load=e,this.factory=null,this.pending=null}get warm(){return null!==this.factory}create(e){return this.factory?this.factory(e):null}attach(e,t){let i=!0;const n={cancel:()=>{i=!1}},r=this.create(e);return r?(t(r),n):(this.ensure().then(n=>{i&&t(n(e))},()=>{}),n)}ensure(){return this.factory?Promise.resolve(this.factory):(this.pending||(this.pending=this.load().then(e=>(this.factory=e,this.pending=null,e),e=>{throw this.pending=null,e})),this.pending)}reset(){this.factory=null,this.pending=null}}(()=>import("./summary-panel-runtime-loaded-B6w0YS6P.js").then(function(e){return e.e}).then(({LoadedSummaryPanelRuntime:e})=>t=>new e(t)));function ev(e){const t=globalThis.__HP_VERSION_OVERRIDE__;return"string"==typeof t&&t.length>0?t:e}let tv=0;const iv="1.76.0-beta.4",nv="241ab786b7cce5c1f837e73704240f138bd3e097bfecdbb0e93046bf4a19d3ef",rv=1500,ov=new Map;let sv=0,av=1e4;const lv="houseplan_card_layout_v1",cv="houseplan_card_cfg_v1",hv="houseplan_card_zoom_v1",dv="houseplan_card_nav_v1",uv="houseplan_card_view_v1",pv="hp-dialog, hp-help, hp-color-opacity, hp-device-preview",_v=1e3,mv=(e,t)=>{const i=Math.min(e.x,t.x),n=Math.min(e.y,t.y);return{x:i,y:n,w:Math.max(e.x+e.w,t.x+t.w)-i,h:Math.max(e.y+e.h,t.y+t.h)-n}},gv=(e,t,i)=>{const n=new Event(t,{bubbles:!0,composed:!0});n.detail=i??{},e.dispatchEvent(n)},fv=e=>{history.pushState(null,"",e),gv(window,"location-changed",{replace:!1})},vv=(e,t)=>{let i,n=null;const r=(...r)=>{clearTimeout(i),n=r,i=window.setTimeout(()=>{i=void 0;const t=n;n=null,t&&e(...t)},t)};return r.flush=()=>{if(void 0===i)return;clearTimeout(i),i=void 0;const t=n;n=null,t&&e(...t)},r.cancel=()=>{clearTimeout(i),i=void 0,n=null},r.pending=()=>void 0!==i,r},yv=e=>{try{e.target?.setPointerCapture?.(e.pointerId)}catch{}},bv=["edges","corners"];class wv extends he{constructor(){var e;super(...arguments),this._editorRuntime=null,this._liveRt=null,this._onboardingRuntime=null,this._editorRuntimeLoadingVisible=!1,this._backdropGuard=null,this._editorModeRequest=0,this._warmModeRequest=0,this._editorRuntimeLoader=new Sf({expectedFingerprint:nv,load:async e=>{const t=0===e?await import("./houseplan-editor-runtime-Pkk2XGqR.js"):await import((()=>{const e=new URL("./houseplan-editor-runtime-Pkk2XGqR.js",import.meta.url);return e.searchParams.set("hp_retry",`${iv}-${++tv}`),e.href})());return{fingerprint:t.EDITOR_RUNTIME_FINGERPRINT,create:()=>new t.HouseplanEditorRuntime(this)}},install:e=>{this._editorRuntime=e},stateChanged:e=>this._editorRuntimeStateChanged(e),failed:(e,t)=>{console.error("[houseplan] unable to load editor runtime",e),t.terminal&&this._versionRecovery.hasCurrentMismatchNotice||this._showToast(kf(e=>this._t(e),t))}}),this._onboardingRuntimeLoader=new Sf({expectedFingerprint:nv,load:async e=>{const t=0===e?await import("./houseplan-onboarding-runtime-BhJG-ch3.js"):await import((()=>{const e=new URL("./houseplan-onboarding-runtime-BhJG-ch3.js",import.meta.url);return e.searchParams.set("hp_retry",`${iv}-${++tv}`),e.href})());return{fingerprint:t.ONBOARDING_RUNTIME_FINGERPRINT,create:()=>new t.HouseplanOnboardingRuntime(this)}},install:e=>{this._onboardingRuntime=e},failed:(e,t)=>{console.error("[houseplan] unable to load onboarding runtime",e),t.terminal&&this._versionRecovery.hasCurrentMismatchNotice||this._showToast(kf(e=>this._t(e),t))}}),this._isoSceneRuntime=null,this._isoSceneRuntimeLoader=new Sf({expectedFingerprint:nv,load:async e=>{const t=0===e?await import("./iso-scene-render-D2f0EUgN.js"):await import((()=>{const e=new URL("./iso-scene-render-D2f0EUgN.js",import.meta.url);return e.searchParams.set("hp_retry",`${iv}-${++tv}`),e.href})());return{fingerprint:t.ISO_SCENE_RUNTIME_FINGERPRINT,create:()=>t}},install:e=>{const t=this._effectiveProjection();this._isoSceneRuntime=e,this._isoProjectionSnapshot=null;const i=this._effectiveProjection();this._convertProjectionView(t,i),this.isConnected&&this.requestUpdate()},failed:(e,t)=>{console.warn("[houseplan] hidden isometric runtime diagnostic",wf("runtime-load","unverified",t.terminal)),this.isConnected&&this.requestUpdate()}}),this._pdfRuntime=null,this._pdfRuntimeLoader=new Sf({expectedFingerprint:nv,load:async e=>{const t=0===e?await import("./pdf-export-DeQrvN1z.js"):await import((()=>{const e=new URL("./pdf-export-DeQrvN1z.js",import.meta.url);return e.searchParams.set("hp_retry",`${iv}-${++tv}`),e.href})());return{fingerprint:t.PDF_EXPORT_FINGERPRINT,create:()=>new t.PdfExportRuntime}},install:e=>{this._pdfRuntime=e,this.isConnected&&this.requestUpdate()},failed:(e,t)=>{if(console.error("[houseplan] unable to load PDF export runtime",e),!t.terminal||!this._versionRecovery.hasCurrentMismatchNotice){const e=kf(e=>this._t(e),t),i=this._t("editor.load_failed"),n=e.startsWith(i)?e.slice(i.length).trim():e;this._showToast(`${this._t("pdf.failed")} ${n}`.trim())}}}),this.panelHost=!1,this.narrow=null,this._space="f1",this._adoption=new qu((e,t)=>this.requestUpdate(e,t)),this._serverStorage=!1,this._loadOk=!1,this._serverCanWrite=null,this._loading=!1,this._loadTries=0,this._unsubCfg=null,this._unsubLayout=null,this._unsubVirtual=null,this._liveSyncAttempt=null,this._liveSyncGeneration=0,this._liveSyncConnection=null,this._configReloadAuthority=new Gu,this._virtualLights=Hh(null),this._canOptimizeUndo=!1,this._undoKind=null,this._devices=[],this._regSignature="",this._defPos={},this._newSyncKey="",this._areaRelocationIds=new Set,this._areaSnapshotCleanupCandidates=new Map,this._areaRelocationSyncKey="",this._areaRelocationWrite=Promise.resolve(),this._tip=null,this._hoverRoom=null,this._pointerModality=new sg(this,()=>this._syncPointerHoverTargets()),this._devicePressAnimations=new Map,this._selId=null,this._toast="",this._mode="view",this._pendingNavMode=null,this._decorTool="select",this._decorStyle={...$r},this._decorStyleSeeded=!1,this._decorDraft=null,this._decorMove=null,this._decorSel=null,this._decorEraseConfirm=null,this._decorTextDialog=null,this._decorShapeDialog=null,this._backdropDialog=null,this._decorTextSelection={start:0,end:0},this._furnPalette=null,this._decorImagePalette=null,this._decorAssetCatalog=[],this._decorAssets=new Map,this._decorAssetBusy=!1,this._furnCategory=null,this._furnPreviewInput=null,this._furnTouchPending=null,this._dtBox=null,this._dtDrag=null,this._bdDrag=null,this._slide="",this._reducedMotion=!1,this._onMotionChange=e=>{this._reducedMotion=e.matches,this._cancelDevicePressFeedback(),e.matches&&this._cancelCameraTransition(!0),e.matches&&this._modeTransitionPreparing?this._modeTransitionForceAtomic=!0:e.matches&&this._modeTransition.active&&this._cancelModeTransition(!0),this._syncVersionRecovery(),this.requestUpdate()},this._editorChromeMode="plan",this._modeTransitionVisual=null,this._modeTransitionPreparing=!1,this._modeTransitionForceAtomic=!1,this._modeTransitionRequest=0,this._modeTransitionTargetZoom=1,this._modeTransitionEditorCamera=null,this._modeTransition=new Ug({frame:e=>this._applyModeTransitionFrame(e),settled:e=>this._settleModeTransition(e)}),this._cameraTransitionFit=null,this._cameraTransition=new Qg({frame:e=>this._applyCameraTransitionFrame(e),settled:e=>this._settleCameraTransition(e)}),this._editorSecondaryCopy={groupActive:(e,t)=>this._t("editor.group_active",{group:e,item:t}),openGroup:e=>this._t("editor.open_group",{group:e}),disabledAction:(e,t)=>this._t("editor.disabled_action",{action:e,reason:t})},this._tool="draw",this._geometryHistory=new gg(50),this._devicePositionHistory=new gg(50),this._devicePositionBusy=!1,this._wallDialog=null,this._drawWallField=null,this._activeWallChainId=null,this._activeWallChainPartitionIds=[],this._wallChainRedo=[],this._physicalSel=null,this._physicalDialog=null,this._partitionDeleteDialog=null,this._roomDeleteDialog=null,this._physicalDrag=null,this._physicalRotate=null,this._physicalLastTap=null,this._physicalPickCycle=null,this._wallUnionCacheValue=null,this._wallUnionPool=new Map,this._isoGeometryCache=new Map,this._renderIsoScene=null,this._isoProjectionSnapshot=null,this._isoStructuralBuildCount=0,this._isoFallback=new Set,this._openingTunnelCache=null,this._openingWallIndexCache=new Map,this._openingPlacementIntervalsCache=null,this._openingDimensionContextCache=null,this._planSnapGeometryCache=null,this._planStructuralGeometryCache=null,this._hiddenWallDiagnosticCache=null,this._physicalBodiesCache=null,this._lightPhysicalBodiesCache=null,this._cleanFloorCache=new Map,this._innerContourCache=new Map,this._glowRuntimeState=bm(),this._glowRuntimeHost={window:()=>this.ownerDocument.defaultView||window,isConnected:()=>this.isConnected,requestUpdate:()=>this.requestUpdate(),reducedMotion:()=>this._reducedMotion},this._lightBarrierCache=null,this._lightBarrierPool=new Map,this._glowScreenBlend=!1,this._duplicateColumnId=null,this._duplicateColumnTimer=0,this._rszLimitViolation=null,this._path=[],this._cursorPt=null,this._planSnapHover=null,this._mergeSel=null,this._openingPreset=null,this._openingRebindId=null,this._openingPresetRevision=0,this._openingHoverCandidate=null,this._openingJambBlockCm=null,this._openingDialog=null,this._openingInfo=null,this._opDrag=null,this._opMeasure=null,this._mergeDialog=null,this._splitSel=null,this._pendingSplit=null,this._wallFaceBatch=null,this._wallRepairDiagnostic=null,this._wallFaceGraphCache=[],this._areaSel="",this._nameSel="",this._roomDialog=!1,this._roomEditId=null,this._roomFill="",this._roomCustomFill=null,this._roomTempMin="",this._roomTempMax="",this._roomTempSrc="",this._roomHumSrc="",this._roomSrcOpen=null,this._roomSrcFilter="",this._roomNameScale=1,this._roomLabelScale=1,this._zoom=1,this._view=null,this._zoomBySpace={},this._viewModeSnap=null,this._roomFocus=null,this._roomPointer=null,this._doubleFit=new ff,this._deviceHits=new wc,this._pointers=new Map,this._panStart=null,this._panLock=null,this._pinchStart=null,this._suppressClick=!1,this._viewportGestureDirty=!1,this._touchContacts=new Map,this._touchClickGuard=new pc,this._connectedPath="",this._routeDepartureHandled=!1,this._onLocationChanged=()=>{this._connectedPath&&location.pathname!==this._connectedPath?this._leaveCardRoute():location.pathname===this._connectedPath&&(this._routeDepartureHandled=!1)},this._touchGestureGuard={capture:!0,handleEvent:e=>this._guardTouchGesture(e)},this._hdrH=118,this._booting=!0,this._bootFading=!1,this._bootSettling=!1,this._bootSettleRaf=0,this._bootLastH=-1,this._bootStart=0,this._bootLastChange=0,this._bootSoft=!1,this._tapConfirm=null,this._dangerConfirm=null,this._dangerConfirmController=new ze(e=>{this._dangerConfirm=e}),this._confirmDanger=e=>this._config&&this.hass?"warm"===this._syncDangerConfirmLocaleGate()||this._dangerConfirmMissingSpace()?Promise.resolve(!1):this._dangerConfirmController.confirm(e):Promise.resolve(!1),this._cancelDangerConfirm=()=>{this._dangerConfirmController.cancel()},this._onDangerConfirmDecision=e=>{this._dangerConfirmController.resolve(e.detail.token,e.detail.accepted)},this._onboardingShown=!1,this._rulesDialog=null,this._preflightClipboardFallback=null,this._haIntegrationVersion=null,this._versionRecovery=(e=this,new wg({clock:{setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>window.clearTimeout(e)},storage:()=>e.ownerDocument.defaultView?.sessionStorage??null,safety:()=>Sg(e),reload:()=>e._reloadDocument(),changed:()=>{e.requestUpdate()}})),this._haSupportApi=null,this._haDecorAssetsApi=null,this._haSummaryPanelApi=null,this._haRadarStage1Api=null,this._radarLive=new Ag(this),this._decorAssetSyncToken=0,this._alignDialog=null,this._settingsDialog=null,this._pdfDialog=!1,this._supportDialog=null,this._backupExportDialog=null,this._backupImportDialog=null,this._sunRaysCache=null,this._dayCycleTimer=0,this._dayCycleClockKey="",this._compassDrag=!1,this._importDialog=null,this._importQueue=[],this._importTotal=0,this._rulesCompiledSrc="",this._infoCard=null,this._nativeMoreInfoEntity=null,this._deviceInbox=null,this._deviceInboxReturn=null,this._deviceInboxMemo=null,this._markerDialog=null,this._spaceDialog=null,this._keyHandler=e=>this._onKey(e),this._warmVp=null,this._warmVpArmed=!1,this._warmLongReturn=!1,this._warmRevivePending=!1,this._warmGen=++sv,this._warmKey=null,this._warmSlot=null,this._hashApplied=!1,this._navApplied=!1,this._labs={alpha:!1,active:Object.freeze([]),space:""},this._viewPreference={},this._renderProjection="flat",this._kioskScale={icon:1,font:1},this._kioskDialog=!1,this._summarySlot=new Jf(Qf,this,e=>{this._summary=e,this._capturedSnapshotSequence=-1,this.isConnected&&(e.connect(),this.hasUpdated&&this.requestUpdate())}),this._activityRt=new Map,this._vacRt=new Map,this._vacViewKey="",this._vacLastView=null,this._vacRaf=0,this._vacSrvTrails={},this._vacJumpOnce=!1,this._continuity=this._newContinuityController(),this._continuityHistory=[],this._continuityEpoch=0,this._continuityDataReady=!0,this._continuityPaintToken=-1,this._continuityDisposed=!1,this._renderSnapshotAt=Date.now(),this._hassSequence=0,this._visibleDeviceSnapshot=null,this._candidateDeviceSnapshot=null,this._stagedDeviceSnapshotToken=-1,this._capturedSnapshotSequence=-1,this._capturedSnapshotDevices=null,this._capturedSnapshotLayout=null,this._capturedSnapshotActivity="",this._capturedSnapshotConfigEpoch=-1,this._capturedSnapshotVirtual="",this._lastValidStageSize=null,this._pendingRefitSize=null,this._refitRaf=0,this._pageVisibility=e=>{if(this._continuity.visibility(e),this._dayCycleVisibility(e),this._summary?.visibility(e.kind),"hidden"===e.kind)return this._radarLive.stop(),this._editorRuntime?._cancelRadarSetup(),this._clearRoomFocus(!0),this._clearTransientHover(!0),this._cancelDevicePressFeedback(),this._cancelCameraTransition(!0),void(this._modeTransitionPreparing?this._modeTransitionForceAtomic=!0:this._cancelModeTransition(!0));if(this._vacJumpOnce=!0,this._syncRadarLive(),!e.long){const e=Date.now();let t=!1;for(const i of this._activityRt.values())!i.flashKind||(i.expiresAt||i.flashTs+tg)>e||(i.flashTs=0,i.flashKind=null,i.expiresAt=0,t=!0);return void(t&&this.requestUpdate())}Date.now()-this._renderSnapshotAt>1e3&&this._continuity.note("device-snapshot-stale"),this._continuityDataReady=!1,this._continuityPaintToken=-1,this._resumeSettling=!0,this._loading?this.requestUpdate():this._loadFromServer()},this._resumeSettling=!1,this._viewportInvalidAt=0,this._vacFit=null,this._vacAllCamerasFor=null,this._vacAllCameraCache=null,this._vacCalConfirm=null,this._kioskDots=!1,this._cyclePausedUntil=0,this._swipeStart=null,this._tabDrag=null,this._tabDragRelease=null,this._tabSuppressClick=!1,this._tabOrderWarned=!1,this._onLabsSnapshot=e=>{const t=this._effectiveProjection();this._labs=e,this._isoProjectionSnapshot=null,this._labsIso&&this._ensureIsoSceneRuntime();const i=this._effectiveProjection();this._convertProjectionView(t,i),this.requestUpdate()},this._onHashChange=()=>{if(this._hasFixedFloor)return;const e=this._hashSpace();if(e&&this._model.find(t=>t.id===e)&&e!==this._space){if(this._wallFaceBatch&&this._roomDialogCancel(),"plan"===this._mode&&"draw"===this._tool&&!this._finishWallChain())return;this._commitSpace(e),this._selId=null,this._path=[],this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._tool="draw",this._activeWallChainId=null,this._activeWallChainPartitionIds=[],this._wallChainSegmentCms=[],this._closingWallCm=null,this._restoreZoom(),this.requestUpdate()}},this._drag=null,this._deviceDrag=null,this._rlResize=null,this._holdFired=!1,this._retryContinuity=()=>{this._continuityDataReady=!1,this._continuityPaintToken=-1,this._continuity.retry(this._continuity.recoveryReason||"plan"),this._loading||this._loadFromServer()},this._cfgEpoch=0,this._cfgEpochPreservedConfig=null,this._terminalFrame=0,this._modelCache=null,this._emptySpaceStateActive=!1,this._decorSnapCache=null,this._markerPreviewMemo=null,this._markerPreviewDevicesMemo=null,this._showHidden=!1,this._connHooked=null,this._connectionWasLost=!1,this._haRegistryConnection=null,this._haRegistryRev=-1,this._haBindingCacheKey="",this._planHassMemo=null,this._renderLife=new $g,this._liveEditorPaintCount=0,this._onHaRegistryUpdate=()=>{const e=nd(this.hass);e.revision===this._haRegistryRev&&this._devices.length||(this._haRegistryRev=e.revision,this._renderLife.invalidate(),this._planHassMemo=null,this._regSignature="",this._maybeRebuildDevices(),this.requestUpdate())},this._onConnReady=()=>{if(this._loadTries=0,clearTimeout(this._loadRetryTimer),this._loadRetryTimer=void 0,id(this.hass),this._saveConfigDebounced.pending()&&this._saveConfigDebounced.flush(),this._cfgWriting)return clearTimeout(this._reloadRetry),void(this._reloadRetry=window.setTimeout(this._onConnReady,400));!this._connectionWasLost&&this._continuity.hasCompleteFrame?this._beginContinuityCandidate("connection-ready",!1,"plan"):(this._continuityDataReady=!1,this._continuityPaintToken=-1),this._loading||this._loadFromServer()},this._onConnLost=()=>{this._booting&&!this._continuity.hasCompleteFrame||(this._connectionWasLost=!0,this._continuityDataReady=!1,this._continuityPaintToken=-1,this._continuity.connectionLost())},this._signer=new uc(()=>this.requestUpdate()),this._dirtyPos=new Set,this._sentPos=new Map,this._persistLayout=vv(()=>{if(this._serverStorage){const e=[...this._dirtyPos];this._dirtyPos.clear();for(const t of e){const e=bo(this._layout[t]);e&&(this._layout={...this._layout,[t]:e},this._sentPos.set(t,e),this.hass.callWS({type:"houseplan/layout/update",device_id:t,pos:e}).then(e=>this._noteLayoutRev(e)).catch(e=>this._showToast(this._t("toast.pos_save_failed",{err:this._errText(e)}))).finally(()=>{this._sentPos.get(t)===e&&this._sentPos.delete(t)}))}this._cacheSnapshot()}else this._persistLocalLayout()},600),this._frame=null,this._showFar=!1,this._writesPending=0,this._writeChain=Promise.resolve(),this._pendingPhysicalWrites=new Map,this._undoGeometry=()=>this._editorRuntimeOrThrow()._undoGeometry(),this._redoGeometry=()=>this._editorRuntimeOrThrow()._redoGeometry(),this._saveConfigDebounced=vv(()=>{this._serverCfg&&this._writeConfig().catch(e=>{const t=!0===e?.physicalGeometryRolledBack;"geometry-unsafe"!==e?.code&&("wall_model_client_outdated"===e?.code?this._showToast(this._t("toast.wall_model_client_outdated")):"conflict"===e?.code?(this._showToast(this._t("toast.conflict")),t||(this._cancelPath(),this._reloadConfigOnly(!0))):this._showToast(this._t("toast.cfg_save_failed",{err:this._errText(e)})),t&&this._reloadRejectedPhysicalWrite())})},500),this._wallChainSegmentCms=[],this._closingWallCm=null,this._savePhysicalDialog=()=>this._editorRuntimeOrThrow()._savePhysicalDialog(),this._deletePhysicalSelection=()=>this._editorRuntimeOrThrow()._deletePhysicalSelection(),this._confirmPartitionDelete=()=>this._editorRuntimeOrThrow()._confirmPartitionDelete(),this._confirmRoomDelete=e=>this._editorRuntimeOrThrow()._confirmRoomDelete(e),this._rebindPartitionOpening=()=>this._editorRuntimeOrThrow()._rebindPartitionOpening(),this._keepClosedAsPartitions=()=>this._editorRuntimeOrThrow()._keepClosedAsPartitions(),this._toggleServerPlans=async()=>this._onboardingRuntime&&this._spaceDialogUsesOnboardingRuntime("create")?this._onboardingRuntime._toggleServerPlans():this._editorRuntimeOrThrow()._toggleServerPlans(),this._aspectJob=null,this._dayCycleTick=()=>{if(!this.isConnected||"hidden"===this.ownerDocument.visibilityState)return;const e=this._dayCycleState();if(!e)return this._dayCycleTimer&&(clearInterval(this._dayCycleTimer),this._dayCycleTimer=0),void(this._dayCycleClockKey="");const t=ar(e);t!==this._dayCycleClockKey&&(this._dayCycleClockKey=t,this.requestUpdate())},this._sunShown=!1,this._sunOut=!1,this._sunOutTimer=0,this._openSettingsDialog=()=>{if(this._editorRuntime)return this._editorRuntime._openSettingsDialog();this._ensureEditorRuntime().then(e=>{e&&this._openSettingsDialog()})},this._openSupportDialog=()=>{this._editorRuntime?this._editorRuntime._openSupportDialog():this._ensureEditorRuntime().then(e=>{e&&this._openSupportDialog()})},this._openPdfDialog=()=>{this._pdfRuntimeLoader.ensure().then(e=>{e&&(this._pdfDialog=!0,this.requestUpdate())})},this._reportedPreflightFingerprint=null,this._openAlignDialog=()=>this._editorRuntimeOrThrow()._openAlignDialog(),this._toggleOptimizeLivePositions=()=>this._editorRuntimeOrThrow()._toggleOptimizeLivePositions(),this._optimizeUndoBusy=!1,this._openBackupExport=()=>this._editorRuntimeOrThrow()._openBackupExport(),this._openRulesDialog=()=>this._editorRuntimeOrThrow()._openRulesDialog(),this._climateCache=null,this._gearPtCache=new WeakMap}requestUpdate(e,t,i){if("hass"===e&&this.hass&&this._liveRt){const e=this._visibleDeviceSnapshot||this._candidateDeviceSnapshot;if(!this._liveRt.hass(t,this.hass,e?{entityIds:e.entityIds}:null,()=>Mg(this))&&!this._summary?.observeHassComposition())return}void 0!==e&&(this._terminalFrame=0),this._editorRuntime?._routeLiveEditorUpdate(e,t)||(this._liveRt?.clear(),super.requestUpdate(e,t,i))}_editorRuntimeOrThrow(){if(!this._editorRuntime)throw new Error("Houseplan editor runtime is not loaded");return this._editorRuntime}async _ensureEditorRuntime(){return this._editorRuntimeLoader.ensure()}async _ensureOnboardingRuntime(){return this._onboardingRuntimeLoader.ensure()}async _ensureIsoSceneRuntime(){return this._isoSceneRuntimeLoader.ensure()}_editorRuntimeStateChanged(e){clearTimeout(this._editorRuntimeLoadingTimer),this._editorRuntimeLoadingTimer=void 0,"loading"!==e?(this._editorRuntimeLoadingVisible=!1,this.requestUpdate()):this._editorRuntimeLoadingTimer=window.setTimeout(()=>{this._editorRuntimeLoadingVisible=!0,this.requestUpdate()},150)}async _requestMode(e,t=!0,i=!1){const n=++this._editorModeRequest;if(i&&(this._warmModeRequest=n,this._refitRaf&&(cancelAnimationFrame(this._refitRaf),this._refitRaf=0),this._pendingRefitSize=null),"view"===e||await this._ensureEditorRuntime()){if(n===this._editorModeRequest&&this.isConnected)return i?(this._adoptMode(e),this._warmRevivePending&&(clearTimeout(this._warmReviveTimer),this._warmReviveTimer=void 0,this._warmReviveDialog()),this.requestUpdate(),void this.updateComplete.then(()=>requestAnimationFrame(()=>requestAnimationFrame(()=>{if(this._warmModeRequest!==n||n!==this._editorModeRequest)return;const e=this._stageEl;this._lastValidStageSize=e&&e.clientWidth>0&&e.clientHeight>0?[e.clientWidth,e.clientHeight]:null,this._pendingRefitSize=null,this._warmModeRequest=0})))):void this._setMode(e,t);this._warmModeRequest===n&&(this._warmModeRequest=0)}else this._warmModeRequest===n&&(this._warmModeRequest=0)}get _layout(){return this._adoption.layout}set _layout(e){this._adoption.stageLocalLayout(e)}get _layoutRev(){return this._adoption.layoutRev}set _layoutRev(e){this._adoption.seedIdentity({layoutRev:e})}get _layoutContentFingerprint(){return this._adoption.layoutFingerprint}set _layoutContentFingerprint(e){this._adoption.seedIdentity({layoutFingerprint:e})}get _serverCfg(){return this._adoption.config}set _serverCfg(e){this._adoption.stageLocalConfig(e)}get _cfgRev(){return this._adoption.configRev}set _cfgRev(e){this._adoption.seedIdentity({configRev:e})}get _cfgContentFingerprint(){return this._adoption.configFingerprint}set _cfgContentFingerprint(e){this._adoption.seedIdentity({configFingerprint:e})}_seedDecorStyle(e){var t,i;if(t=Fl,i=this,Dl(e,Ll)&&"pending"===t.state()&&(t.art("",i),t.ensure()),this._decorStyleSeeded||!e)return;this._decorStyleSeeded=!0;const n=e.settings?.decor_default_style;n&&(this._decorStyle=function(e,t){if(!e||"object"!=typeof e)return{...t};const i=e,n="string"==typeof i.color&&i.color?i.color:t.color,r="string"==typeof i.fill_color&&i.fill_color?i.fill_color:t.fillColor,o=Number(i.width_cm);return{color:n,opacity:Mr(i.opacity,t.opacity),widthCm:Number.isFinite(o)&&o>0?Math.max(.1,Math.min(100,o)):t.widthCm,fill:"boolean"==typeof i.fill?i.fill:t.fill,fillColor:r,fillOpacity:Mr(i.fill_opacity,t.fillOpacity)}}(n,$r))}get _canManageConfiguration(){return null!==this._serverCanWrite?this._serverCanWrite:!0===this.hass?.user?.is_admin}get _canEdit(){return this._norm&&this._canManageConfiguration}get _kiosk(){return!!this._config?.kiosk}_showKioskDots(){this._kioskDots=!0,clearTimeout(this._kioskDotsTimer),this._kioskDotsTimer=window.setTimeout(()=>this._kioskDots=!1,2500)}get _modeTransitionBusy(){return this._modeTransitionPreparing||this._modeTransition.active}get _doubleFitEnabled(){return!("view"!==this._mode||this._vacFit||this._modeTransitionBusy||this._touchSequenceMultitouch||"steady"!==this._continuity.state||this._continuity.overlayBlocksInteraction)}_cameraState(){const e=this._viewOr(this._baseVb());return{zoom:this._zoom,viewBox:{...e}}}_normalizeCameraState(e){const t=this._cameraTransitionFit||Oi(this._baseVb(),this._stageAspect());return{zoom:Math.min(wv.ZOOM_MAX,Math.max(wv.ZOOM_MIN,e.zoom)),viewBox:this._clampView({...e.viewBox},t)}}_applyCameraTransitionFrame(e){const t=this._normalizeCameraState(e.presented);e.presented=t,this._zoom=t.zoom,this._view={...t.viewBox},this._liveVp(!0)}_settleCameraTransition(e){const t=this._normalizeCameraState(e.to);this._zoom=t.zoom,this._view={...t.viewBox},this._cameraTransitionFit=null,"room"!==e.reason&&this._saveZoom(),this.requestUpdate()}_cancelCameraTransition(e=!1,t=!1){const i=this._cameraTransition.state?.reason,n=t&&this._cameraTransition.active?this._cameraTransition.presented?.zoom:void 0;this._cameraTransition.cancel(e),this._cameraTransitionFit=null,void 0!==n&&"room"!==i&&this._saveZoom()}_prepareCameraCommand(){this._bootSoftCancel(),this._modeTransitionBusy&&this._cancelModeTransition(!0),"opening"===this._tool&&(this._cursorPt=null,this._clearOpeningPlacement(!1))}_startCameraTransition(e,t,i,n){const r=this._cameraState(),o=this._cameraTransition.target;return(!o||!Xg(o,e))&&(Xg(r,e)?(this._cancelCameraTransition(!1),!1):(this._cameraTransitionFit={...t},this._cameraTransition.start(r,e,i,this._reducedMotion?0:n),!0))}_cssColor(e,t){const i=String(e||"").trim();if(!i)return t;const n=document.createElement("span");n.style.cssText=`position:absolute;visibility:hidden;color:${i}`,this.renderRoot.append(n);const r=getComputedStyle(n).color||t;return n.remove(),r}_currentModeVisual(e=this._mode){const t=this._modeTransition.presented||this._modeTransitionVisual;if(t)return{...t,viewport:{...t.viewport,viewBox:{...t.viewport.viewBox}}};const i=this._stageEl;if(!i||i.clientWidth<=0||i.clientHeight<=0)return null;const n=this.renderRoot.querySelector(".editorchrome"),r=this._viewOr(this._baseVb()),o=this.renderRoot.querySelector(".hp-paper"),s=this.renderRoot.querySelector(".hp-backdrop"),a=this.renderRoot.querySelector(".zoomwrap"),l=a?getComputedStyle(a).filter:"",c=Number(/brightness\(([^)]+)\)/.exec(l)?.[1]);return{presentedMode:e,editorChromeHeight:"view"===e?0:n?.getBoundingClientRect().height||0,stageWidth:i.clientWidth,stageHeight:i.clientHeight,viewport:Bg(r,i.clientWidth),stageColor:getComputedStyle(i).backgroundColor||"rgb(255, 255, 255)",paperColor:o?getComputedStyle(o).fill:"rgb(255, 255, 255)",sceneBrightness:Number.isFinite(c)?c:1,architectureOpacity:"decor"===e?.35:1,backdropOpacity:s&&Number(getComputedStyle(s).opacity)||1,viewWeight:"view"===e?1:0,editorWeight:"view"===e?0:1,toolbarContentOpacity:"view"===e?0:1}}_viewForModeTarget(e,t,i,n,r){const o=Oi(this._baseVb(),n/r),s=Math.min(wv.ZOOM_MAX,Math.max(wv.ZOOM_MIN,e)),a=o.w/s,l=o.h/s,c=t??o.x+o.w/2,h=i??o.y+o.h/2;return this._clampView({x:c-a/2,y:h-l/2,w:a,h:l},o)}_targetStageColor(e){return"view"!==e?"rgb(255, 255, 255)":this._cssColor(this._stageBg(this._spaceDisplayForRender()),this._cssColor("var(--ha-card-background, var(--card-background-color, #111))","rgb(17, 17, 17)"))}_targetPaperColor(e){return"view"===e&&this._spaceModel()?.bg?this._cssColor("var(--ha-card-background, var(--card-background-color, #111))","rgb(17, 17, 17)"):"rgb(255, 255, 255)"}_targetBrightness(e){return 1}_applyModeTransitionFrame(e){e.targetMode===this._mode&&(this._modeTransitionVisual=e.presented,this._view={...e.presented.viewport.viewBox},this.requestUpdate())}_settleModeTransition(e){if(e.targetMode!==this._mode)return;const t=this._modeTransitionRequest;this._view={...e.to.viewport.viewBox},this._zoom=this._modeTransitionTargetZoom,this._modeTransitionVisual=null,this._modeTransitionPreparing=!1,this._lastValidStageSize=[e.to.stageWidth,e.to.stageHeight],"view"===this._mode&&(this._saveZoom(),this._viewModeSnap=null,this._modeTransitionEditorCamera=null),this.requestUpdate(),this.updateComplete.then(()=>{if(!this.isConnected||t!==this._modeTransitionRequest||this._modeTransitionBusy||e.targetMode!==this._mode)return;const i=this._stageEl;if(i&&i.clientWidth>0&&i.clientHeight>0&&(Math.abs(i.clientWidth-e.to.stageWidth)>.5||Math.abs(i.clientHeight-e.to.stageHeight)>.5)){const e=this._view;this._lastValidStageSize=[i.clientWidth,i.clientHeight],this._applyView(this._zoom,e?e.x+e.w/2:void 0,e?e.y+e.h/2:void 0),this.requestUpdate()}const n=this.renderRoot.activeElement;(!n||!n.isConnected||!!n.closest?.(".editorchrome, .stage"))&&this.renderRoot.querySelector(".modetab.active")?.focus?.({preventScroll:!0})})}_cancelModeTransition(e=!0){this._cancelCameraTransition(!1);const t=!!this._modeTransition.state;this._modeTransitionRequest++,this._modeTransitionPreparing=!1,this._modeTransitionForceAtomic=!1,this._modeTransition.cancel(e),e&&t||(this._modeTransitionVisual=null)}_adoptMode(e){e!==this._mode&&(this._clearRoomFocus(!0),this._resetDeviceHitState()),this._cancelModeTransition(!1),this._mode=e,this._isoProjectionSnapshot=null,"view"!==e&&(this._editorChromeMode=e)}_commitViewModeAtomic(e,t,i,n){if(this._modeTransitionPreparing=!1,this._modeTransitionVisual=null,this._modeTransitionForceAtomic=!1,this._zoom=t,e){const r=this._stageEl?.clientWidth||e.stageWidth,o=Math.max(1,e.stageHeight+e.editorChromeHeight);this._view=this._viewForModeTarget(t,i,n,r,o),this._lastValidStageSize=[r,o]}else this._view=null;this._viewModeSnap=null,this._modeTransitionEditorCamera=null,this._saveZoom(),this.requestUpdate()}_prepareModeTransition(e,t,i,n,r,o){this.updateComplete.then(()=>{if(!this.isConnected||e!==this._modeTransitionRequest||this._mode!==i)return void(e===this._modeTransitionRequest&&(this._modeTransitionPreparing=!1,this._modeTransitionVisual=null,this._modeTransitionForceAtomic=!1,this.requestUpdate()));const s=this.renderRoot.querySelector(".editorchrome-inner"),a="view"===i?0:s?.scrollHeight||0,l=Math.max(1,(this.panelHost?this.clientHeight:innerHeight)-ef(this.renderRoot,this._stageEl,this.panelHost)),c=this._stageEl?.clientWidth||t.stageWidth,h=this._viewForModeTarget(n,r,o,c,l),d={presentedMode:i,editorChromeHeight:a,stageWidth:c,stageHeight:l,viewport:Bg(h,c),stageColor:this._targetStageColor(i),paperColor:this._targetPaperColor(i),sceneBrightness:this._targetBrightness(i),architectureOpacity:"decor"===i?.35:1,backdropOpacity:"decor"===i&&"backdrop"!==this._decorTool?.5:1,viewWeight:"view"===i?1:0,editorWeight:"view"===i?0:1,toolbarContentOpacity:"view"===i?0:1};this._modeTransitionPreparing=!1;const u=this._modeTransitionForceAtomic;this._modeTransitionForceAtomic=!1,this._modeTransition.start(t,d,i,this._reducedMotion||u?0:220)})}get _hasFixedFloor(){return!!this._config&&Object.prototype.hasOwnProperty.call(this._config,"floor")}_fixedFloorState(e=this._model,t=this._loadOk){const i=this._config?.floor,n=function(e){if(!e.hasFloor)return{kind:"absent"};const t=e.floor;if("string"==typeof t)return t.length?e.spaceIds.includes(t)?{kind:"valid",id:t,source:"id"}:{kind:"invalid",reason:"unknown-id",value:t}:{kind:"invalid",reason:"empty-id",value:t};if("number"==typeof t){if(!Number.isFinite(t))return{kind:"invalid",reason:"non-finite-index",value:t};if(!Number.isInteger(t))return{kind:"invalid",reason:"fractional-index",value:t};if(t<0)return{kind:"invalid",reason:"negative-index",value:t};const i=e.spaceIds[t];return void 0===i?{kind:"invalid",reason:"out-of-range-index",value:t}:{kind:"valid",id:i,source:"index"}}return{kind:"invalid",reason:"invalid-type",value:t}}({spaceIds:e.map(e=>e.id),hasFloor:this._hasFixedFloor,floor:i});return!this._hasFixedFloor||t?n:"number"==typeof i?"valid"===n.kind||"invalid"===n.kind&&"out-of-range-index"===n.reason?{kind:"pending",value:i}:n:"valid"===n.kind||"invalid"===n.kind&&"unknown-id"!==n.reason?n:{kind:"pending",value:i}}_canCommitSpace(e,t=!1){if(t||!this._hasFixedFloor)return!0;const i=this._fixedFloorState();return"valid"===i.kind&&i.id===e}_commitSpace(e,t=!1){return!!this._canCommitSpace(e,t)&&(e!==this._space&&(this._clearRoomFocus(!0),this._resetDeviceHitState(),this._cancelDangerConfirm(),this._cancelCameraTransition(!1),this._clearTransientHover(!0),this._cancelDevicePressFeedback(),this._editorRuntime?._clearFurniturePreview()),this._space=e,this._isoProjectionSnapshot=null,!0)}_slideTo(e,t){if(e===this._space)return!0;if(!this._canCommitSpace(e))return!1;if(this._wallFaceBatch&&this._roomDialogCancel(),"plan"===this._mode&&"draw"===this._tool&&!this._finishWallChain())return!1;this._cancelModeTransition(!0);const i=window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches;return this._commitSpace(e),this._path=[],this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._tool="draw",this._activeWallChainId=null,this._activeWallChainPartitionIds=[],this._wallChainSegmentCms=[],this._closingWallCm=null,this._selId=null,this._physicalSel=null,this._editorSecondary?.closeForNavigation(),this._physicalDialog=null,this._physicalDrag=null,this._restoreZoom(),i||(this._slide=t,clearTimeout(this._slideTimer),this._slideTimer=window.setTimeout(()=>{this._slideTimer=void 0,this._slide="",this.requestUpdate()},190),this.requestUpdate()),!0}get _canReorderTabs(){return Zf({canEdit:this._canEdit,kiosk:this._kiosk,mode:this._mode,pointerType:"mouse",spaceCount:this._model.length,fixedFloor:this._hasFixedFloor})}_tabPointerDown(e,t){Zf({canEdit:this._canEdit,kiosk:this._kiosk,mode:this._mode,pointerType:e.pointerType,spaceCount:this._model.length,fixedFloor:this._hasFixedFloor})&&(yv(e),this._tabDragRelease=e=>this._tabPointerUp(e),window.addEventListener("pointerup",this._tabDragRelease),window.addEventListener("pointercancel",this._tabDragRelease),this._tabDrag={id:t,pointerId:e.pointerId,x:e.clientX,y:e.clientY,moved:!1,targetId:null,placement:null})}_tabDropTargetAt(e,t,i){const n=this._model.map(e=>e.id),r=n.indexOf(i);if(r<0)return null;const o=this.renderRoot.querySelectorAll('[data-hp="space-tab"]');for(const s of o){const o=s.dataset.id||"";if(!o||o===i)continue;const a=s.getBoundingClientRect();if(ea.right||ta.bottom)continue;const l=n.indexOf(o);return l<0?null:{targetId:o,placement:l=4)))return;var i,n;const r=this._tabDropTargetAt(e.clientX,e.clientY,t.id);t.moved&&t.targetId===r?.targetId&&t.placement===r?.placement||(this._tabDrag={...t,moved:!0,targetId:r?.targetId||null,placement:r?.placement||null})}_tabPointerUp(e){const t=this._tabDrag;if(t&&t.pointerId!==e.pointerId)return;const i="pointerup"===e.type&&t?.moved?this._tabDropTargetAt(e.clientX,e.clientY,t.id):null;"pointerup"===e.type&&t?.moved&&this._suppressNextTabClick(),this._endTabDrag(),t?.moved&&i&&this._commitTabOrder(t.id,i.targetId)}_endTabDrag(){this._tabDrag=null,this._tabDragRelease&&(window.removeEventListener("pointerup",this._tabDragRelease),window.removeEventListener("pointercancel",this._tabDragRelease),this._tabDragRelease=null)}_tabClick(e){if(this._tabSuppressClick)return this._tabSuppressClick=!1,clearTimeout(this._tabSuppressClickTimer),void(this._tabSuppressClickTimer=void 0);this._pickSpace(e)}_suppressNextTabClick(){this._tabSuppressClick=!0,clearTimeout(this._tabSuppressClickTimer),this._tabSuppressClickTimer=window.setTimeout(()=>{this._tabSuppressClick=!1,this._tabSuppressClickTimer=void 0},0)}_commitTabOrder(e,t){const i=this._serverCfg;if(!i||!this._canReorderTabs)return;const n=this._model.map(e=>e.id),r=function(e,t,i){const n=e.indexOf(t),r=e.indexOf(i);if(n<0||r<0||n===r)return e;const o=e.slice();return o.splice(n,1),o.splice(r,0,t),o}(n,e,t);if(r===n)return;const o=new Map(this._devices.map(e=>[String(e.id),String(e.area||"")])),s=function(e,t,i,n=()=>""){if(!i)return[];const r=[];for(const o of e){if(!o||!0===o.removed)continue;const e="string"==typeof o.id?o.id:"";if(!e)continue;if("string"==typeof o.space&&o.space)continue;const s=("string"==typeof o.area?o.area:"")||n(e)||"";s&&t[s]||r.push({id:e,space:i})}return r}(i.markers||[],Object.fromEntries(Object.entries(this._areaToSpace).map(([e,t])=>[e,t.space])),n[0]||"",e=>o.get(e)||"");if(s.length){const e=new Map(s.map(e=>[e.id,e.space]));for(const t of i.markers||[]){const i=e.get(String(t.id));i&&(t.space=i)}}i.spaces=function(e,t){const i=new Map(t.map((e,t)=>[e,t]));return e.map((e,t)=>({space:e,index:t})).sort((e,t)=>(i.get(String(e.space?.id))??Number.MAX_SAFE_INTEGER)-(i.get(String(t.space?.id))??Number.MAX_SAFE_INTEGER)||e.index-t.index).map(e=>e.space)}(i.spaces||[],r),this._saveConfig(),this._tabOrderWarned||(this._tabOrderWarned=!0,this._showToast(this._t("toast.space_order_changed")))}_pickSpace(e){if(this._endTabDrag(),e===this._space)return;const t=this._model.map(e=>e.id),i=t.indexOf(this._space),n=t.indexOf(e);this._navApplied=!0,this._showFar=!1,this._frame=null,this._slideTo(e,i>=0&&n0&&Date.now()>=this._cyclePausedUntil&&this._model.length>1&&this._zoom<=1.001){const e=this._model.map(e=>e.id),t=e.indexOf(this._space);this._slideTo(e[(t+1)%e.length],"left"),this._showKioskDots()}}_syncCycleTimer(){clearInterval(this._cycleTimer),this._cycleTimer=void 0,this.isConnected&&!this._hasFixedFloor&&this._config?.kiosk&&Number(this._config.cycle)>0&&(this._cycleTimer=window.setInterval(()=>this._cycleTick(),1e3*Number(this._config.cycle)))}get _editing(){return"plan"===this._mode||"devices"===this._mode||"decor"===this._mode}get _markup(){return"plan"===this._mode}get _wallUnionCache(){return this._wallUnionCacheValue}set _wallUnionCache(e){this._wallUnionCacheValue=e,null===e&&this._wallUnionPool.clear()}get _glowClipCache(){return this._glowRuntimeState.clipCache}get _glowGeometryWarnings(){return this._glowRuntimeState.geometryWarnings}get _glowFeatherUnits(){return this._glowRuntimeState.featherUnits}set _glowFeatherUnits(e){this._glowRuntimeState.featherUnits=e}get _glowRenderedSources(){return this._glowRuntimeState.renderedSources}get _glowLastAppearance(){return this._glowRuntimeState.lastAppearance}get _glowFeatherSuspendUntil(){return this._glowRuntimeState.featherSuspendUntil}set _glowFeatherSuspendUntil(e){this._glowRuntimeState.featherSuspendUntil=e}get _glowFeatherResumeTimer(){return this._glowRuntimeState.featherResumeTimer}set _glowFeatherResumeTimer(e){this._glowRuntimeState.featherResumeTimer=e}get _glowSourceSeq(){return this._glowRuntimeState.sourceSeq}set _glowSourceSeq(e){this._glowRuntimeState.sourceSeq=e}get _touchSequenceMultitouch(){return this._touchClickGuard.sequenceMultitouch}_syncDangerConfirmLocaleGate(){return this._config&&this.hass?dp(this,gp,kp(this.hass,this._config.language)):"ready"}_dangerConfirmMissingSpace(){const e=this._model;if(!e.length)return!1;const t=this._fixedFloorState(e);return"pending"!==t.kind&&"invalid"!==t.kind&&!this._spaceModel()}_syncVersionRecovery(){this._versionRecovery.update({frontendVersion:ev(iv),backendVersion:this._haIntegrationVersion,kiosk:!0===this._config?.kiosk,reducedMotion:this._reducedMotion})}_newContinuityController(){return new lc(()=>{this._resumeSettling="steady"!==this._continuity.state,this._continuityEpoch++,this.isConnected&&this.requestUpdate()})}get _labsIso(){return this._labs.active.includes("iso")}get _desiredProjection(){return"view"===this._mode&&this._labsIso&&"iso"===this._viewPreference[this._space]?"iso":"flat"}_saveViewPreference(){try{localStorage.setItem(uv,JSON.stringify(this._viewPreference))}catch{}}_logicalViewCenter(e){const t=this._view;if(!t)return null;const i=[t.x+t.w/2,t.y+t.h/2],n="iso"===e?cf(i):i;return{x:n[0],y:n[1]}}_convertProjectionView(e,t){if(e===t)return;this._clearRoomFocus(!0);const i=this._logicalViewCenter(e);this._view=null;const n=i?"iso"===t?lf([i.x,i.y],0):[i.x,i.y]:null;this._applyView(this._zoom,n?.[0],n?.[1]),this._warmPatch({vp:this._warmViewportState()}),this.requestUpdate()}_setProjection(e){if(!this._labsIso||"view"!==this._mode)return;const t=this._effectiveProjection();if(this._viewPreference={...this._viewPreference,[this._space]:e},"iso"===e){this._ensureIsoSceneRuntime();const e=this._isoSceneKey();e&&this._isoFallback.delete(e),this._isoFallback.delete(`${this._space}|no-borders`),this._clearIsoInvalidFallback()}this._saveViewPreference(),this._isoProjectionSnapshot=null;const i=this._effectiveProjection();this._convertProjectionView(t,i)}_hashSpace(){return Ff(window.location.hash||"")}connectedCallback(){this._connectedPath=location.pathname,this._routeDepartureHandled=!1,this._configReloadAuthority.observeContext(Vu(this)),window.addEventListener("location-changed",this._onLocationChanged),window.addEventListener("popstate",this._onLocationChanged),this._continuityDisposed&&(this._continuity=this._newContinuityController(),this._continuityDisposed=!1,this._continuityPaintToken=-1);const e=dg(this.ownerDocument);var t;void 0!==e&&(this._glowScreenBlend=e),this._continuityUnsub?.(),this._continuityUnsub=sc(this.ownerDocument,this._pageVisibility),this._languageFailureUnsub?.(),this._languageFailureUnsub=function(...e){return()=>{for(const t of e)t()}}((t=()=>{this._showToast(this._t("toast.locale_load_failed"))},mp.add(t),()=>mp.delete(t)),function(e){return Pl.add(e),()=>{Pl.delete(e)}}(()=>this._showToast(this._t("toast.furniture_art_load_failed")))),super.connectedCallback(),this._summarySlot.connect(),this._ensureLiveRuntime().catch(()=>this.requestUpdate()),this._pointerModality.connect(this.ownerDocument.defaultView);const i=this.ownerDocument.defaultView?.MutationObserver;i&&(this._pointerHoverObserver=new i(e=>{let t=!1;for(const i of e){for(const e of i.addedNodes)this._syncPointerHoverSubtree(e);const e=e=>{if(e.nodeType!==Node.ELEMENT_NODE)return!1;const t=e;return t.matches(".devlayer, .devlayer *")||!!t.querySelector?.(".devlayer")};(e(i.target)||[...i.addedNodes,...i.removedNodes].some(e))&&(t=!0)}t&&this._invalidateDeviceHitGeometry()}),this._pointerHoverObserver.observe(this.renderRoot,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","style","data-id"]})),this._motionMedia=window.matchMedia?.("(prefers-reduced-motion: reduce)"),this._reducedMotion=!!this._motionMedia?.matches,this._motionMedia?.addEventListener?.("change",this._onMotionChange),this._syncVersionRecovery(),this._versionRecovery.connect(),hg(this.ownerDocument).then(e=>{e!==this._glowScreenBlend&&(this._glowScreenBlend=e,this.isConnected&&this.requestUpdate())}),this.hass&&this._ensureHaRegistryAuthority(),window.addEventListener("keydown",this._keyHandler),this._signer.start(()=>this.hass,()=>this._referencedContentUrls()),this._syncCycleTimer(),window.addEventListener("hashchange",this._onHashChange),this._labsUnsub?.(),this._labsUnsub=function(e){Nf.add(e);const t=Bf();return"undefined"==typeof window&&e(t),()=>{Nf.delete(e)}}(this._onLabsSnapshot),this._labsIso&&this._ensureIsoSceneRuntime(),this._booting?this._bootWatch():this._bootFading&&(clearTimeout(this._bootTimer),this._bootTimer=window.setTimeout(()=>{this._bootFading=!1},220)),this._bootSoft&&(clearTimeout(this._bootSoftTimer),this._bootSoftTimer=window.setTimeout(()=>{this._bootSoft=!1},rv)),!this._loadOk&&this._serverCfg&&this.hass&&this._scheduleLoadRetry(),!this._warmSlot&&this._config&&this._warmAdopt(),this._loadOk&&this._ensureLiveSyncSubscriptions(),this._warmVp&&!this._warmRevivePending&&void 0===this._warmReviveTimer&&(this._warmRevivePending=!0,this._warmReviveTimer=window.setTimeout(()=>this._warmReviveDialog(),0)),this._warmLongReturn&&this._beginResumeSettle(),this._warmLongReturn=!1,this.requestUpdate()}disconnectedCallback(){this._versionRecovery.disconnect(),this._configReloadAuthority.invalidateLifecycle(),this._liveRt?.dispose(),this._radarLive.stop(),this._editorRuntime?._disposeLiveEditor(),this._clearRoomFocus(!0),this._cancelDangerConfirm(),this._connectedPath&&location.pathname!==this._connectedPath&&this._leaveCardRoute(),window.removeEventListener("location-changed",this._onLocationChanged),window.removeEventListener("popstate",this._onLocationChanged),this._continuityUnsub?.(),this._continuityUnsub=void 0,this._languageFailureUnsub?.(),this._languageFailureUnsub=void 0,this._motionMedia?.removeEventListener?.("change",this._onMotionChange),this._motionMedia=void 0,this._vacRaf&&(cancelAnimationFrame(this._vacRaf),this._vacRaf=0),this._refitRaf&&(cancelAnimationFrame(this._refitRaf),this._refitRaf=0),this._warmModeRequest=0,this._dayCycleTimer&&(clearInterval(this._dayCycleTimer),this._dayCycleTimer=0),this._summarySlot.disconnect(),this._dayCycleClockKey="",this._bootSettleRaf&&(cancelAnimationFrame(this._bootSettleRaf),this._bootSettleRaf=0),this._bootSettling=!1;for(const e of this._activityRt.values())clearTimeout(e.timer);window.removeEventListener("keydown",this._keyHandler),this._endTabDrag(),clearTimeout(this._tabSuppressClickTimer),this._tabSuppressClickTimer=void 0,this._tabSuppressClick=!1,clearInterval(this._cycleTimer),clearTimeout(this._kioskDotsTimer),clearTimeout(this._kioskHoldTimer),clearTimeout(this._reloadRetry),clearTimeout(this._loadRetryTimer),this._loadRetryTimer=void 0,this._connHooked?.removeEventListener?.("ready",this._onConnReady),this._connHooked?.removeEventListener?.("disconnected",this._onConnLost),this._connHooked?.removeEventListener?.("reconnect-error",this._onConnLost),this._connHooked=null,this._haRegistryRelease?.(),this._haRegistryRelease=void 0,this._haRegistryConnection=null,this._signer.dispose(),clearTimeout(this._toastTimer),clearTimeout(this._slideTimer),clearTimeout(this._editorRuntimeLoadingTimer),this._editorRuntimeLoadingTimer=void 0,this._editorRuntimeLoadingVisible=!1,this._modeTransition.dispose(),this._cameraTransition.dispose(),this._cameraTransitionFit=null,this._modeTransitionVisual=null,this._modeTransitionPreparing=!1,this._modeTransitionForceAtomic=!1,this._modeTransitionRequest++,this._slideTimer=void 0,this._slide="",clearTimeout(this._bootTimer),this._bootTimer=void 0,clearTimeout(this._bootSoftTimer),this._saveConfigDebounced.flush(),this._cancelDeviceDrag(),window.removeEventListener("hashchange",this._onHashChange),this._labsUnsub?.(),this._labsUnsub=void 0,clearTimeout(this._holdTimer),this._roViewport?.disconnect(),this._roViewport=void 0,this._roHdr?.disconnect(),this._roHdr=void 0,this._onWinResize&&(window.removeEventListener("resize",this._onWinResize),this._onWinResize=void 0),this._unsubCfg&&(this._unsubCfg(),this._unsubCfg=null),this._unsubLayout&&(this._unsubLayout(),this._unsubLayout=null),this._unsubVirtual&&(this._unsubVirtual(),this._unsubVirtual=null),this._unsubTrail&&(this._unsubTrail(),this._unsubTrail=void 0),this._liveSyncGeneration++,this._liveSyncAttempt=null,this._liveSyncConnection=null,clearTimeout(this._layoutSyncTimer),clearTimeout(this._duplicateColumnTimer),Fm(this._glowRuntimeState,this._glowRuntimeHost),this._warmSnapshot(),this._warmRevivePending=!1,clearTimeout(this._warmReviveTimer),this._warmReviveTimer=void 0,this._warmRelease(),this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._editorRuntime?._clearFurniturePreview(),this._editorRuntime?._furnShiftDetach(),this._touchContacts.clear(),this._touchClickGuard.reset(),this._resetDeviceHitState(),this._clearTransientHover(!0),this._cancelDevicePressFeedback(),this._pointerHoverObserver?.disconnect(),this._pointerHoverObserver=void 0,this._pointerModality.disconnect(),this._editorSecondary?.reset(),this._resumeSettling=!1,this._continuityHistory=[...this._continuityHistory,...this._continuity.trace].slice(-80),this._continuity.dispose(),this._continuityDisposed=!0,super.disconnectedCallback()}_onKey(e){if("Escape"===e.key&&this._vacFit){if(this._vacFit.busy)return;return this._vacFit=null,this._showToast(this._t("vac.cal_cancelled")),void e.stopPropagation()}if("Escape"===e.key){if(this._tapConfirm)return void(this._tapConfirm=null);if(this._vacCalConfirm)return void(this._vacCalConfirm.busy||(this._vacCalConfirm=null));if(this._decorEraseConfirm)return void(this._decorEraseConfirm=null);if(this._openingInfo)return void(this._openingInfo=null);if(this._infoCard)return void this._closeInfoCard();if(this._rulesDialog)return void(this._rulesDialog=null);if(this._alignDialog)return this._alignDialog=null,void(this._preflightClipboardFallback=null);if(this._backupImportDialog)return void(this._backupImportDialog=null);if(this._backupExportDialog)return void(this._backupExportDialog=null);if(this._pdfDialog)return void(this._pdfDialog=!1);if(this._supportDialog)return void this._editorRuntime?._closeSupportDialog();if(this._settingsDialog)return void(this._settingsDialog=null);if(this._summary?.closeDialogIfIdle())return;if(this._markerDialog)return void this._closeMarkerDialog();if(this._deviceInbox)return void(this._deviceInbox=null);if(this._openingDialog)return void(this._openingDialog=null);if(this._physicalDialog)return void(this._physicalDialog=null);if(this._backdropDialog)return void(this._backdropDialog=null);if(this._decorShapeDialog)return void(this._decorShapeDialog=null);if(this._decorTextDialog)return void(this._decorTextDialog=null);if(this._spaceDialog&&!this._roomDialog)return this._spaceDialog=null,this._importQueue=[],void(this._importTotal=0);if(this._editorSecondary?.hasOpenGroup)return e.preventDefault(),void this._editorSecondary?.closeGroup(!0)}const t=e.composedPath?.()||[e.target],i=t.some(e=>e?.matches?.('input, textarea, select, [contenteditable="true"]')),n=t.some(e=>e?.classList?.contains?.("editor-secondary")),r=e.ctrlKey||e.metaKey,o=e.key.toLowerCase(),s=/^[a-z]$/.test(o),a="z"===o||!s&&"KeyZ"===e.code,l="y"===o||!s&&"KeyY"===e.code,c=r&&(a&&e.shiftKey||l),h=r&&a&&!e.shiftKey;if("decor"===this._mode){if((h||c)&&i)return;if(c)return e.preventDefault(),void this._redoGeometry();if(h)return e.preventDefault(),this._decorDraft?void(this._decorDraft=null):this._decorMove||this._dtDrag||this._bdDrag?void this._cancelDecorGesture():void this._undoGeometry();if(("Delete"===e.key||"Backspace"===e.key)&&this._decorSel&&!i&&!n)return e.preventDefault(),void this._decorDeleteSel();const t="ArrowLeft"===e.key?[-this._gridPitch,0]:"ArrowRight"===e.key?[this._gridPitch,0]:"ArrowUp"===e.key?[0,-this._gridPitch]:"ArrowDown"===e.key?[0,this._gridPitch]:null;return!t||r||e.altKey||"select"!==this._decorTool||!this._decorSel||!this._decorList.some(e=>e.id===this._decorSel)||this._decorDraft||this._decorMove||this._dtDrag||this._bdDrag||i||n||this._editorSecondaryDialogBlocked?void("Escape"===e.key&&(e.preventDefault(),this._decorDraft?this._decorDraft=null:this._decorMove||this._dtDrag||this._bdDrag?this._cancelDecorGesture():"furniture"===this._decorTool?(this._editorRuntime?._clearFurniturePreview(),this._editorRuntime?._furnShiftDetach(),this._furnPalette=null,this._furnCategory=null,this._decorTool="select"):this._decorSel?this._decorSel=null:"select"!==this._decorTool?this._decorTool="select":this._setMode("view"))):(e.preventDefault(),void this._decorNudge(t[0],t[1]))}if("devices"===this._mode){if((h||c)&&i)return;return c?(e.preventDefault(),void this._redoDevicePosition()):h?(e.preventDefault(),void this._undoDevicePosition()):void("Escape"===e.key&&this._deviceDrag&&(e.preventDefault(),this._cancelDeviceDrag()))}if(this._markup&&(!h&&!c||!i)){if(("Delete"===e.key||"Backspace"===e.key)&&this._physicalSel&&!i&&!n)return e.preventDefault(),void this._deletePhysicalSelection();if(c)return e.preventDefault(),void this._redoGeometry();if(h)return e.preventDefault(),this._resize?.dragging?void this._rszCancelDrag():this._wallFaceBatch?(this._roomDialogCancel(),void(this._activeWallChainId&&this._path.length>1?this._undoActiveWallPoint():this._undoPoint())):"draw"===this._tool&&this._path.length?void(this._activeWallChainId&&this._path.length>1?this._undoActiveWallPoint():this._undoPoint()):"split"===this._tool&&this._splitSel?.pts?.length?(this._splitSel={...this._splitSel,pts:this._splitSel.pts.slice(0,-1)},void(this._splitSel.pts.length||(this._cursorPt=null))):void this._undoGeometry();if("Escape"===e.key)return this._physicalDrag||this._physicalRotate?(e.preventDefault(),void this._cancelPhysicalGesture()):this._roomDialog?(e.preventDefault(),void this._roomDialogCancel()):"draw"===this._tool&&this._path.length?(e.preventDefault(),void this._finishWallChain()):this._physicalSel?(e.preventDefault(),void(this._physicalSel=null)):"resize"===this._tool?(e.preventDefault(),this._resize?.dragging?void this._rszCancelDrag():("exit-tool"===this._resize?.escapeIdle()&&(this._tool="draw"),void this.requestUpdate())):"split"===this._tool?(e.preventDefault(),void(this._splitSel?.pts?.length?(this._splitSel={...this._splitSel,pts:this._splitSel.pts.slice(0,-1)},this._splitSel.pts.length||(this._cursorPt=null)):this._splitSel?this._splitSel=null:this._tool="draw")):"merge"===this._tool?(e.preventDefault(),void(this._mergeSel?this._mergeSel=null:this._tool="draw")):this._wallDialog?(e.preventDefault(),void(this._wallDialog=null)):void("opening"!==this._tool&&"wallthick"!==this._tool&&"delroom"!==this._tool&&"column"!==this._tool||(e.preventDefault(),"opening"===this._tool&&this._clearOpeningPlacement(!0),this._tool="draw"))}}_undoPoint(){if(this._path.length)return this._contourClosed?(this._path=this._path.slice(0,-1),void(this._closingWallCm=null)):void(this._activeWallChainPartitionIds.length&&this._path.length>1?this._undoActiveWallPoint():this._path=this._path.slice(0,-1))}_undoActiveWallPoint(){const e=[...this._activeWallChainPartitionIds],t=e[e.length-1],i=this._spaceModel()?.partitions.find(e=>e.id===t),n=this._path[0]?[...this._path[0]]:null,r=this._path.slice(0,-1).map(e=>[...e]),o=this._wallChainSegmentCms.slice(0,-1),s=this._geometryHistory.undo();if(!s)return this._activeWallChainPartitionIds=[],this._wallChainSegmentCms=[],this._wallChainRedo=[],void(this._path=n?[n]:[]);this._applyGeometryState(s.before,!0)?(this._activeWallChainId||=`chain-${Date.now().toString(36)}`,this._activeWallChainPartitionIds=e.slice(0,-1),this._path=r.length?r:n?[n]:[],this._wallChainSegmentCms=o,i&&this._wallChainRedo.push({id:i.id,point:[...i.b],cm:i.cm}),this._clearPlanSnapHover(),this._showToast(this._t("history.undone",{name:s.name}))):this._geometryHistory.clear()}static async getConfigElement(){return await import("./editor-Cfrg3iMq.js"),document.createElement("houseplan-card-editor")}static getStubConfig(){return{type:"custom:houseplan-card"}}static _warmBootReset(e){for(const e of ov.values())for(const t of e)clearTimeout(t.evict);ov.clear(),av=e&&e>0?e:1e4}static _warmBootStats(){let e=0,t=0;const i=[];for(const n of ov.values())for(const r of n)e++,r.dlg&&(t++,i.push(r.dlg.kind));return{keys:ov.size,slots:e,dlgs:t,drafts:i}}setConfig(e){const t=this._config,i=!!t&&Object.prototype.hasOwnProperty.call(t,"floor");this._config={icon_size:2.5,show_temperature:!0,live_states:!0,show_signal:!0,...e};(i!==this._hasFixedFloor||t?.floor!==this._config.floor)&&(this._hashApplied=!1,this._navApplied=!1,this._warmVpArmed=!1),this._config.kiosk&&(this._booting=!1,this._bootFading=!1),!this._hasFixedFloor&&e.default_floor&&this._commitSpace(e.default_floor,!0);try{this._zoomBySpace=JSON.parse(localStorage.getItem(hv)||"{}")||{}}catch{this._zoomBySpace={}}try{const e=JSON.parse(localStorage.getItem(uv)||"{}")||{};this._viewPreference=Object.fromEntries(Object.entries(e).filter(e=>"flat"===e[1]||"iso"===e[1]))}catch{this._viewPreference={}}if(this._labs=Bf(),this.isConnected&&this._labsIso&&this._ensureIsoSceneRuntime(),!this._summary?.applyLocalScaleForCurrentIdentity())try{const e=JSON.parse(localStorage.getItem("houseplan_card_kiosk_v1")||"null");this._kioskScale={icon:Bn(e?.icon),font:Bn(e?.font)}}catch{}try{const e=JSON.parse(localStorage.getItem(cv)||"null");this._adoption.restoreCached(e)&&(this._seedDecorStyle(this._serverCfg),this._cfgEpoch++,this._virtualLights=Hh(e.virtual_lights,this._cfgRev),this._serverStorage=!0)}catch{}this._adoptInitialSpace(this._model,this._loadOk),"view"!==this._mode||this._view||(this._zoom=this._zoomBySpace[this._space]||1),this.isConnected&&(this._syncCycleTimer(),this._warmAdopt(),this._warmLongReturn&&this._beginResumeSettle(),this._warmLongReturn=!1),this._syncVersionRecovery()}_warmAdopt(){if(this._config?.kiosk)return;const e=Cf(this._config);if(this._warmKey===e&&this._warmSlot)return;this._warmSlot&&this._warmRelease();const t=this.parentNode,i=this._warmIdx(t),n=ov.get(e);if(!n||!n.length)return;const r=n.find(e=>e.owner===this._warmGen);if(r)return this._warmLongReturn=!!r.freed&&Date.now()-r.freed>=nc,clearTimeout(r.evict),r.evict=0,r.freed=0,r.live=!0,this._warmSlot=r,this._warmKey=e,r.frameFingerprint&&this._continuity.adoptCompleteFrame(r.frameFingerprint),void(!this._devices.length&&r.devices?.length&&(this._devices=[...r.devices]));const{slot:o,sure:s}=((e,t,i,n)=>{const r=e=>{const t=!!i&&e.place?.deref()===i;return t&&e.idx===n?4:e.live?0:t?3:2};let o=null,s=0,a=0,l=null;for(const i of e){if(i.owner===t)continue;l=i;const e=r(i);e<=0||(e>s?(o=i,s=e,a=1):e===s&&a++)}return!o||a>1?{slot:o||l,sure:!1}:{slot:o,sure:!0}})(n,this._warmGen,t,i);o&&(this._warmLongReturn=!!o.freed&&Date.now()-o.freed>=nc,this._booting=!1,this._bootFading=!1,this._hdrH=o.hdrH,this._bootSoft=!0,this.isConnected&&(clearTimeout(this._bootSoftTimer),this._bootSoftTimer=window.setTimeout(()=>{this._bootSoft=!1},rv)),this._warmKey=e,s?(clearTimeout(o.evict),o.evict=0,o.owner=this._warmGen,o.place=t?new WeakRef(t):null,o.idx=i,o.live=!0,this._warmSlot=o,this._warmVp=o.vp,o.frameFingerprint&&this._continuity.adoptCompleteFrame(o.frameFingerprint),!this._devices.length&&o.devices?.length&&(this._devices=[...o.devices]),this._warmAdoptViewport(this._config)):(this._warmSlot={owner:this._warmGen,path:location.pathname,place:t?new WeakRef(t):null,idx:i,live:!0,hdrH:o.hdrH,stageH:o.stageH,vp:null,frameFingerprint:"",devices:null,dlg:null,freed:0,evict:0},n.push(this._warmSlot),this._warmTrim(n)))}_warmIdx(e){const t=e?.children;if(!t)return-1;for(let e=0;e4;){const t=e.findIndex(e=>!e.live);if(t<0)break;clearTimeout(e[t].evict),e.splice(t,1)}}_warmScheduleEvict(e,t){if(clearTimeout(e.evict),!(e.dlg||e.vp&&"view"!==e.vp.mode))return;const i=e.freed,n=e.owner;e.evict=window.setTimeout(()=>{if(e.evict=0,e.freed!==i||e.owner!==n)return;var r;e.dlg=null,e.vp=(r=e.vp)&&"view"!==r.mode?{...r,mode:"view",zoom:r.snap?.space===r.space?r.snap.zoom:r.zoom,view:null,snap:null,tool:"draw",decorTool:"select",showHidden:!1,selId:null,rszSel:null,decorSel:null}:r,e.frameFingerprint="";const o=ov.get(t);if(!e.live&&o&&o.length>1){const t=o.indexOf(e);t>=0&&o.splice(t,1)}},av+250)}_warmAdoptViewport(e){const t=this._warmVp;if(!t||this._warmSlot?.path!==location.pathname)return void(this._warmVp=null);const i=this._fixedFloorState();if(this._hashApplied||!this._model.find(e=>e.id===t.space)||"valid"===i.kind&&i.id!==t.space||this._hasFixedFloor&&"valid"!==i.kind)return void(this._warmVp=null);this._commitSpace(t.space,!0),this._navApplied=!0;const n="view"!==t.mode&&this._canEdit&&!e.kiosk?t.mode:"view";this._adoptMode("view"),this._pendingNavMode="view"===t.mode||this._canEdit||e.kiosk?null:t.mode,this._zoom=t.zoom;const r=this._effectiveProjection(),o=r===t.projection&&this._labsIso===t.activeLabsIso;if(this._view=o&&t.view?{...t.view}:null,this._viewModeSnap=o&&t.snap?{...t.snap}:null,!o&&t.logicalCenter){const e="iso"===r?lf([t.logicalCenter.x,t.logicalCenter.y],0):[t.logicalCenter.x,t.logicalCenter.y];this._applyView(t.zoom,e[0],e[1])}var s;this._tool="opening"===(s=function(e){return"partition"===e?"draw":e}(s=t.tool))?"draw":"string"==typeof s&&Rf.has(s)?s:"draw",this._decorTool=t.decorTool,this._showHidden=t.showHidden,this._showFar!==t.showFar&&(this._showFar=t.showFar,this._frame=null),this._selId=t.selId,this._resize?.restoreSelection(t.rszSel),this._decorSel=t.decorSel,this._warmVpArmed=!0,"view"!==n&&this._requestMode(n,!1,!0)}_warmPatch(e,t=!1){if(this._config?.kiosk)return;const i=Cf(this._config);if(!this._warmSlot||this._warmKey===i){if(!this._warmSlot){if(!t)return;const e=this.parentNode;this._warmKey=i,this._warmSlot={owner:this._warmGen,path:location.pathname,place:e?new WeakRef(e):null,idx:this._warmIdx(e),live:!0,hdrH:this._hdrH,stageH:0,vp:null,frameFingerprint:"",devices:null,dlg:null,freed:0,evict:0};const n=ov.get(i)||[];for(n.push(this._warmSlot),ov.set(i,n),this._warmTrim(n);ov.size>8;){const e=ov.keys().next().value;if(void 0===e||e===i)break;for(const t of ov.get(e)||[])clearTimeout(t.evict);ov.delete(e)}}Object.assign(this._warmSlot,e)}}_warmViewportState(){const e=this._effectiveProjection();return{space:this._space,mode:this._mode,projection:e,activeLabsIso:this._labsIso,logicalCenter:this._logicalViewCenter(e),zoom:this._zoom,view:this._view?{...this._view}:null,snap:this._viewModeSnap?{...this._viewModeSnap}:null,tool:this._tool,decorTool:this._decorTool,showHidden:this._showHidden,showFar:this._showFar,selId:this._selId,rszSel:this._resize?.selectedRoomId,decorSel:this._decorSel}}_warmDialogState(){const e=(e,t)=>({kind:e,space:this._space,mode:this._mode,data:t});return this._tapConfirm||this._alignDialog||this._mergeDialog||this._importDialog||this._backupExportDialog||this._backupImportDialog?null:this._openingInfo?e("openingInfo",this._openingInfo.id):this._infoCard?e("info",this._infoCard.id):this._rulesDialog?this._rulesDialog.busy?null:e("rules",this._rulesDialog):this._settingsDialog?this._settingsDialog.busy?null:e("settings",this._settingsDialog):this._markerDialog?this._markerDialog.busy?null:e("marker",this._markerDialog):this._openingDialog?e("opening",this._openingDialog):this._backdropDialog?e("backdrop",this._backdropDialog):this._decorShapeDialog?e("decorShape",this._decorShapeDialog):this._decorTextDialog?e("decorText",this._decorTextDialog):this._roomDialog?e("room",{editId:this._roomEditId,fill:this._roomFill,customFill:this._roomCustomFill,tempMin:this._roomTempMin,tempMax:this._roomTempMax,tempSrc:this._roomTempSrc,humSrc:this._roomHumSrc,srcOpen:this._roomSrcOpen,srcFilter:this._roomSrcFilter,nameScale:this._roomNameScale,labelScale:this._roomLabelScale,areaSel:this._areaSel,nameSel:this._nameSel,pendingSplit:this._pendingSplit,wallFaceBatch:this._wallFaceBatch,path:this._path}):this._spaceDialog?this._spaceDialog.busy?null:e("space",this._spaceDialog):null}_warmSnapshot(){if(this._booting||this._config?.kiosk||"steady"!==this._continuity.state)return;const e={vp:this._warmViewportState(),frameFingerprint:this._continuity.frameFingerprint,devices:this._devices,hdrH:this._hdrH};if(this._warmRevivePending||(e.dlg=this._warmDialogState()),this.isConnected&&this._warmSlot?.owner===this._warmGen){const t=this.parentNode;e.place=t?new WeakRef(t):null,e.idx=this._warmIdx(t)}this._warmPatch(e)}_warmReviveDialog(){const e=this._warmSlot;if(this._warmReviveTimer=void 0,!e||!e.dlg)return void(this._warmRevivePending=!1);const t=e.dlg,i=e.freed;if(t.mode===this._mode||"view"===t.mode||this._warmVp?.mode!==t.mode||this._editorRuntime){if(this._warmRevivePending=!1,e.dlg=null,e.freed=0,clearTimeout(e.evict),e.evict=0,i&&!(Date.now()-i>av)&&t.space===this._space&&t.mode===this._mode){switch(t.kind){case"space":this._spaceDialog={...t.data,busy:!1,savedBusy:!1};break;case"marker":this._markerDialog={...t.data,busy:!1};break;case"settings":this._settingsDialog={...t.data,busy:!1};break;case"rules":this._rulesDialog={...t.data,busy:!1};break;case"opening":this._openingDialog={...t.data};break;case"backdrop":this._backdropDialog={...t.data};break;case"decorShape":this._decorShapeDialog={...t.data};break;case"decorText":{this._decorTextDialog={...t.data};const e=String(this._decorTextDialog?.text??"").length;this._decorTextSelection={start:e,end:e};break}case"room":{const e=t.data;this._roomEditId=e.editId,this._roomFill=e.fill,this._roomCustomFill=e.customFill||null,this._roomTempMin=e.tempMin||"",this._roomTempMax=e.tempMax||"",this._roomTempSrc=e.tempSrc,this._roomHumSrc=e.humSrc,this._roomSrcOpen=e.srcOpen,this._roomSrcFilter=e.srcFilter,this._roomNameScale=e.nameScale,this._roomLabelScale=e.labelScale,this._areaSel=e.areaSel,this._nameSel=e.nameSel,this._pendingSplit=e.pendingSplit,this._wallFaceBatch=e.wallFaceBatch||null,this._path=e.path,this._wallFaceBatch&&(this._activeWallChainId=`chain-${Date.now().toString(36)}`,this._activeWallChainPartitionIds=[...this._wallFaceBatch.activePartitionIds],this._wallChainSegmentCms=[...this._wallFaceBatch.activeCms]),this._roomDialog=!0;break}case"info":{const e=this._devices.find(e=>e.id===t.data);e&&(this._infoCard=e);break}case"openingInfo":{const e=(this._curSpaceCfg?.openings||[]).find(e=>e.id===t.data);e&&(this._openingInfo=e);break}}this.requestUpdate()}}else this._warmRevivePending=!0}_cacheSnapshot(){if(this._serverCfg)try{this._virtualLights=function(e,t,i){if(e.configRev===i)return e;const n=new Set((Array.isArray(t?.markers)?t.markers:[]).filter(qh).map(e=>e.id));return{...e,configRev:i,off:new Set([...e.off].filter(e=>n.has(e)))}}(this._virtualLights,this._serverCfg,this._cfgRev);const e=this._adoption.snapshot(function(e){return{rev:e.rev,config_rev:e.configRev,off:[...e.off].sort()}}(this._virtualLights));e&&localStorage.setItem(cv,JSON.stringify(e))}catch{}}_beginContinuityCandidate(e,t,i="plan"){return this._booting&&!this._continuity.hasCompleteFrame?this._continuity.token:(this._continuityDataReady=t,this._continuityPaintToken=-1,this._stagedDeviceSnapshotToken=-1,this._resumeSettling=!0,this._continuity.beginCandidate(e,i))}_continuityStageValid(){const e=this._stageEl;return!!e&&e.clientWidth>0&&e.clientHeight>0}_versionReloadSafetySnapshot(){return Sg(this)}_continuityAssetsReady(){if(!this._model.length)return!1;const e=this._model.length?this._spaceModel():null;return!e?.bg?.href||this._signer.isReady(this.hass,e.bg.href)}_initialSpaceSelection(e,t=this._loadOk){const i=this._fixedFloorState(e,t);return"valid"===i.kind?{id:i.id,source:"fixed"}:this._hasFixedFloor?{id:null,source:"none"}:function(e){const t=new Set(e.spaceIds.filter(e=>!!e));if(!t.size)return{id:null,source:"none"};const i=[["hash",!1===e.acceptHash?null:e.hashSpace],["current",e.preserveCurrent?e.currentSpace:null],["saved",e.savedSpace],["default",e.defaultSpace],["first",e.spaceIds[0]]];for(const[e,n]of i)if(n&&t.has(n))return{id:n,source:e};return{id:null,source:"none"}}({spaceIds:e.map(e=>e.id),hashSpace:this._hashSpace(),acceptHash:!this._hashApplied,currentSpace:this._space,preserveCurrent:this._hashApplied||this._navApplied||this._warmVpArmed,savedSpace:this._savedNav()?.space,defaultSpace:this._config?.default_floor})}_adoptInitialSpace(e,t=this._loadOk){const i=this._initialSpaceSelection(e,t);return i.id?(this._commitSpace(i.id,!0),"hash"===i.source&&(this._hashApplied=!0),"saved"===i.source&&(this._navApplied=!0),i):i}_candidateBackdrop(e,t=this._space){const i=Za(e),n=this._fixedFloorState(i,!0);if(this._hasFixedFloor&&"valid"!==n.kind)return"";const r=this._initialSpaceSelection(i,!0).id||(i.some(e=>e.id===t)?t:i[0]?.id);return i.find(e=>e.id===r)?.bg?.href||""}_visualFrameFingerprint(){const e=this._stageEl,t=e?[e.clientWidth,e.clientHeight]:[0,0];return hc([this._cfgRev,this._adoption.currentConfigFingerprint(),this._layoutRev,this._adoption.currentLayoutFingerprint(),this._space,this._mode,this._view,t,this._glowScreenBlend?"screen":"normal",this.hass?.themes?.darkMode??this.hass?.themes?.default_theme??""])}_settleContinuityFrame(){if(this._booting||!this._continuityStageValid())return;if(!this._continuity.hasCompleteFrame&&"steady"===this._continuity.state)return void(this._continuityAssetsReady()&&(this._renderSnapshotAt=Date.now(),this._continuity.markCompleteFrame(this._visualFrameFingerprint())));if(!this._continuityDataReady)return;if(!["holding","offline-stale","overlay-pending","overlay-visible","candidate-ready"].includes(this._continuity.state))return;const e=this._continuity.token;if(this._candidateDeviceSnapshot&&this._candidateDeviceSnapshot!==this._visibleDeviceSnapshot&&this._stagedDeviceSnapshotToken!==e)return this._stagedDeviceSnapshotToken=e,void this.requestUpdate();this._continuityPaintToken!==e&&(this._continuityPaintToken=e,this._continuity.candidateReady(e)&&this._continuity.commitAfterPaint(e,{updateComplete:()=>this.updateComplete,stageValid:()=>this.isConnected&&this._continuityStageValid(),assetsReady:()=>this._continuityAssetsReady(),frameFingerprint:()=>this._visualFrameFingerprint()}).then(t=>{t&&e===this._continuity.token?(this._resumeSettling=!1,this._renderSnapshotAt=Date.now(),this._candidateDeviceSnapshot&&(this._visibleDeviceSnapshot=this._candidateDeviceSnapshot),this._candidateDeviceSnapshot=null,this._stagedDeviceSnapshotToken=-1,this._warmSnapshot()):e===this._continuity.token&&(this._continuityPaintToken=-1,this._stagedDeviceSnapshotToken=-1,this._candidateDeviceSnapshot=null,this.requestUpdate())}))}_onBackdropLoaded(e,t){this._signer.markLoaded(this.hass,e,t),this._continuity.note("asset-ready"),this._continuityPaintToken=-1,"steady"!==this._continuity.state&&this.requestUpdate()}_renderRecoveryOverlay(){if(!this._continuity.overlayVisible&&"recovery-error"!==this._continuity.state)return G;const e="connection"===this._continuity.recoveryReason;return j`
e.stopPropagation()} - @click=${e=>e.stopPropagation()} - @wheel=${e=>e.stopPropagation()}> - - ${this._t(e?"continuity.restore_connection":"continuity.restore_plan")} - ${"recovery-error"===this._continuity.state?j``:G} -
`}_reloadDocument(){this.ownerDocument.defaultView?.location.reload()}_renderVersionBanner(){return function(e,t,i=t.banner){if(!i)return G;const n="leaving"===i.phase;return j`
{e.target===e.currentTarget&&"hp-version-recovery-out"===e.animationName&&t.finishBannerExit(i.token)}}> -
- -
- ${e._t("version_mismatch.title")} - ${e._t("version_mismatch.body")} - - ${e._t("version_mismatch.frontend")}: ${i.frontend} - ${e._t("version_mismatch.backend")}: ${i.backend} - -
- -
-
`}(this,this._versionRecovery)}_renderEditorRuntimeLoading(){return this._editorRuntimeLoadingVisible?j`
- - ${this._t("editor.loading")} -
`:G}houseplanContinuityTrace(){return[...this._continuityHistory,...this._continuity.trace].slice(-80).map(e=>({...e,...e.stage?{stage:[...e.stage]}:{}}))}getCardSize(){return 12}getGridOptions(){return{columns:"full"}}get _norm(){return!(!this._serverCfg||!this._serverCfg.spaces.length)}_cfgFingerprint(){const e=this._serverCfg?.spaces||[];let t=e.length+":";for(const i of e){t+=(i.id||"")+","+(i.plan_aspect||"")+","+(i.plan_url||"").length+","+(i.plan_x??"")+","+(i.plan_y??"")+","+(i.plan_scale??"")+","+(i.plan_scale_x??"")+","+(i.plan_scale_y??"")+","+(i.plan_angle??"")+","+(i.rooms?.length||0)+","+(i.openings?.length||0)+","+(i.decor?.length||0)+";";for(const e of i.rooms||[]){const i=e.poly?.[0],n=e.poly?.[e.poly.length-1];t+=(e.poly?.length||0)+"."+(e.id||"")+"."+(e.open_to||[]).join("+")+"."+(e.area||"")+"."+JSON.stringify(e.settings||0)+"."+(e.x??"")+","+(e.y??"")+","+(e.w??"")+","+(e.h??"")+","+(i?i[0]+"/"+i[1]:"")+","+(n?n[0]+"/"+n[1]:"")+";"}}return t}get _model(){if(!this._serverCfg)return[];const e=this._cfgEpoch+"|"+this._cfgFingerprint();if(this._modelCache&&this._modelCache.key===e)return this._modelCache.model;const t=this._buildModel();return this._modelCache={key:e,model:t},t}_buildModel(){if(!this._serverCfg)return[];const e=this._renderCfg;return Za(e).map((t,i)=>{const n=e.spaces[i]?.plan_url;return t.bg&&n?{...t,bg:{...t.bg,href:n}}:t})}_spaceModel(){return this._hasFixedFloor?kc(this._model,this._space):(e=this._model,t=this._space,e.find(e=>e.id===t)??e[0]);var e,t}_spaceModelById(e){return kc(this._model,e)}_syncEmptySpaceState(){if(!!this._serverCfg&&0===this._serverCfg.spaces.length){if(!this._emptySpaceStateActive){this._emptySpaceStateActive=!0,this._clearRoomFocus(!0);for(const e of this._pointers.keys())for(const t of this.renderRoot.querySelectorAll("*"))try{t.hasPointerCapture?.(e)&&t.releasePointerCapture(e)}catch{}this._pointers.clear(),this._panStart=null,this._panLock=null,this._pinchStart=null,this._swipeStart=null,this._drag=null,this._deviceDrag=null,this._resetDeviceHitState(),this._rlResize=null,this._vacFit=null,this._compassDrag=!1,this._cancelModeTransition(!1),this._mode="view",this._clearGeometryGesture(),this._geometryHistory.clear(),this._devicePositionHistory.clear(),this._tip=null,this._hoverRoom=null,this._openingInfo=null,this._closeInfoCard(),this._deviceInbox=null,this._deviceInboxReturn=null,this._markerDialog=null,this._physicalDialog=null,this._backdropDialog=null,this._decorShapeDialog=null,this._decorTextDialog=null,this._roomDialog=!1,"edit"===this._spaceDialog?.mode&&(this._spaceDialog=null),this._editorSecondary?.closeForNavigation(),this._saveConfigDebounced.cancel(),this._frame=null,this._planSnapGeometryCache=null,this._hiddenWallDiagnosticCache=null,this._decorSnapCache=null,this._commitSpace("",!0)}}else this._emptySpaceStateActive=!1}get _areaToSpace(){const e={};for(const t of this._model)for(const i of t.rooms)i.area&&(e[i.area]={space:t.id,room:i});return e}get _settings(){return this._serverCfg?.settings||{}}get _showAll(){return this._showHidden||!this._settings.filter_seeded&&!!this._settings.show_all}_seedHiddenDevices(){if(!(this._loadOk&&this._serverCfg&&this._norm&&this._canEdit))return;const e=this._serverCfg,t=eu({hass:this.hass,registry:this._haRegistry,areaToSpace:Object.fromEntries(Object.entries(this._areaToSpace).map(([e,t])=>[e,t.space])),markers:this._markers,settings:this._settings,excluded:this._excluded,firstSpaceId:this._model[0]?.id||"",iconRules:this._iconRules});if(!t.length&&e.settings?.filter_seeded)return;e.markers=e.markers||[];const i=[];for(const n of t){const t="h"+n.slice(n.indexOf(":")+1);e.markers.push({id:t,binding:n,hidden:!0}),i.push(n.slice(n.indexOf(":")+1))}const n={...e.settings||{},filter_seeded:!0};delete n.show_all,i.length&&Array.isArray(n.new_device_ids)&&(n.new_device_ids=n.new_device_ids.filter(e=>!i.includes(e))),e.settings=n,this._regSignature="",this._maybeRebuildDevices(),this._saveConfig(),this.requestUpdate()}get _iconRules(){const e=this._settings.icon_rules;if(!e||!Array.isArray(e)||!e.length)return;const t=JSON.stringify(e);return t!==this._rulesCompiledSrc&&(this._rulesCompiledSrc=t,this._rulesCompiled=Ee(e)),this._rulesCompiled}get _fillColors(){return gn(this._settings)}get _excluded(){return lu(this._settings)}_setAreaLifecycleConfig(e){this._cfgEpochPreservedConfig=e,this._serverCfg=e}willUpdate(e){if(this._isoProjectionSnapshot=null,this._summary?.willUpdate(),e.has("hass")&&this._configReloadAuthority.observeContext(Vu(this)),e.has("_serverCfg")){const e=this._cfgEpochPreservedConfig===this._serverCfg;this._cfgEpochPreservedConfig=null,e||this._cfgEpoch++,this._renderLife.invalidate()}if(this._syncEmptySpaceState(),this._dangerConfirm&&(this._dangerConfirmMissingSpace()||"warm"===this._syncDangerConfirmLocaleGate())&&this._cancelDangerConfirm(),e.has("hass")&&this.hass){const t=this._visibleDeviceSnapshot||this._candidateDeviceSnapshot;this._renderLife.observe(e.get("hass"),this.hass,t?{entityIds:t.entityIds}:null,()=>Mg(this))}this._continuity.hasCompleteFrame&&"steady"===this._continuity.state&&this._continuity.refreshCompleteFrame(this._visualFrameFingerprint()),this._captureRenderDeviceSnapshot()}updated(){this._summary?.updated(),this._liveRt?.commit(),this._editorRuntime?._commitLiveEditor(),this._pruneDevicePressFeedback(),this._syncDayCycleClock(),this._syncRadarLive(),this._warmSnapshot(),this._editorRuntime&&this._dtMeasure();const e=this._stageEl;e&&!this._roViewport&&(this._roViewport=new ResizeObserver(()=>{this._invalidateDeviceHitGeometry(),this._refitView(),requestAnimationFrame(()=>this._summary?.resized())}),this._roViewport.observe(e)),e&&this._booting&&!this._bootTimer&&this._bootWatch();const t=this.renderRoot.querySelector(".hdr");if(t&&e&&!this._roHdr){const i=()=>{const t=ef(this.renderRoot,e,this.panelHost);null!==t&&(t>=0&&t!==this._hdrH&&(this._hdrH=t),t>=0&&!this._booting&&!this._config?.kiosk&&e.clientHeight>0&&this._warmPatch({hdrH:t,stageH:e.clientHeight}))};this._roHdr=new ResizeObserver(()=>requestAnimationFrame(i)),this._roHdr.observe(t),this._onWinResize=()=>requestAnimationFrame(i),window.addEventListener("resize",this._onWinResize),i()}if(e&&!this._view&&this._refitView(),this._editorSecondary?.afterRender(),this._settleContinuityFrame(),this._serverStorage&&this._loadOk&&this._canManageConfiguration&&0===this._model.length&&!this._spaceDialog&&!this._importDialog&&!this._onboardingShown){this._onboardingShown=!0;const e=function(e){const t=e?.floors;if(!t||"object"!=typeof t)return[];const i=[];for(const e of Object.values(t))e&&e.floor_id&&i.push({id:e.floor_id,name:e.name||e.floor_id,level:e.level??null});return i.sort((e,t)=>{const i=e.level??1e9,n=t.level??1e9;return i!==n?i-n:e.name.localeCompare(t.name)}),i}(this.hass);e.length?this._importDialog={floors:e.map(e=>({...e,checked:!0}))}:this._openSpaceDialog("create")}}_adoptConfigCapabilities(e){xg(this,e)}_syncRadarLive(){const e=this._serverCfg?.settings?.radar,t=(this._serverCfg?.markers||[]).some(e=>Cg(e,this._space));this._radarLive.sync(this._space,1===this._haRadarStage1Api&&"view"===this._mode&&!1!==e?.show_live&&t&&"hidden"!==this.ownerDocument.visibilityState)}async _syncDecorAssets(e){const t=++this._decorAssetSyncToken;if(1!==this._haDecorAssetsApi||!this.hass)return void(this._decorAssets=new Map);const i=await um(this.hass,cm(e),this._cfgRev);t===this._decorAssetSyncToken&&(this._decorAssets=i,this._resign(),this.requestUpdate())}_adoptAuthoritative(e){return ju(this,e)}_rollbackOptimistic(e){const t=this._adoption.rollbackOptimistic(e);return t&&this.requestUpdate(),t}_resumePendingNavMode(){if(!this._pendingNavMode||!this._canEdit||this._config?.kiosk)return!1;const e=this._pendingNavMode;return this._pendingNavMode=null,this._setMode(e,!1),!0}_getAuthoritativeConfig(){return e=this,async function(e,t){const i=await e();return t(i),i}(()=>e.hass.callWS({type:"houseplan/config/get"}),t=>xg(e,t));var e}async _loadFromServer(){this._loading=!0,this._loadTries++;const e=this._space,t=!!this._view;let i=!1;const n=()=>{i=!0,this._regSignature="",this._maybeRebuildDevices()};try{const[i,r]=await Promise.all([this._getAuthoritativeConfig(),this.hass.callWS({type:"houseplan/layout/get"})]);if("adopted"!==(await this._adoptAuthoritative({cfgResp:i,layResp:r,reason:"structural-response",profile:"reload",beforeAdopt:()=>{this._connectionWasLost=!1,this._serverStorage=!0},afterAdopt:()=>{this._warmVpArmed&&this._space===this._warmVp?.space?this._warmVpArmed=!1:t&&this._space===e||this._restoreZoom(),this._loadOk=!0,n()}})).status)return;this.hass.callWS({type:"houseplan/trail/get"}).then(e=>{this._vacSrvTrails=e?.trails||{},this.requestUpdate()}).catch(()=>{}),this._ensureLiveSyncSubscriptions()}catch(e){if(this._serverCfg)this._scheduleLoadRetry(!0);else if(this._loadTries>=8){this._serverStorage=!1;try{this._layout=JSON.parse(localStorage.getItem(lv)||"{}")||{}}catch{this._layout={}}}}finally{this._loading=!1,this._continuityDataReady=!0,i||n(),this.requestUpdate()}}_ensureLiveSyncSubscriptions(){const e=this.hass?.connection;if(!e)return;if(e!==this._liveSyncConnection&&(this._unsubCfg?.(),this._unsubCfg=null,this._unsubLayout?.(),this._unsubLayout=null,this._unsubTrail?.(),this._unsubTrail=void 0,this._unsubVirtual?.(),this._unsubVirtual=null,this._liveSyncGeneration++,this._liveSyncAttempt=null,this._liveSyncConnection=e),this._liveSyncAttempt)return;const t=this._liveSyncGeneration,i=[],n=(n,r,o,s)=>{n()||i.push(async()=>{const i=await e.subscribeEvents(s,o);t===this._liveSyncGeneration&&this.isConnected&&this.hass?.connection===e&&!n()?r(i):i?.()})};if(n(()=>this._unsubCfg,e=>{this._unsubCfg=e},"houseplan_config_updated",e=>{const t=Number(e?.data?.rev??-1);t!==this._cfgRev&&this._reloadConfigOnly(!1,t)}),n(()=>this._unsubTrail,e=>{this._unsubTrail=e},"houseplan_trail_updated",async()=>{try{const e=await this.hass.callWS({type:"houseplan/trail/get"});this._vacSrvTrails=e?.trails||{},this.requestUpdate()}catch{}}),n(()=>this._unsubLayout,e=>{this._unsubLayout=e},"houseplan_layout_updated",e=>this._onLayoutEvent(Number(e?.data?.rev??-1))),n(()=>this._unsubVirtual,e=>{this._unsubVirtual=e},"houseplan_virtual_light_updated",e=>{const t=Wh(this._virtualLights,e?.data);t!==this._virtualLights&&(this._virtualLights=t,this._capturedSnapshotVirtual="",this._cacheSnapshot(),this.requestUpdate())}),!i.length)return;const r=function(e){return Promise.allSettled(e.map(e=>Promise.resolve().then(e)))}(i).then(()=>{});this._liveSyncAttempt=r,r.finally(()=>{this._liveSyncAttempt===r&&(this._liveSyncAttempt=null)})}async _reloadConfigOnly(e=!1,t){return Ku(this,e,t)}_scheduleLoadRetry(e=!1){if(void 0!==this._loadRetryTimer)return;const t=Math.min(8e3,500*2**Math.min(4,Math.max(1,this._loadTries-7)));this._loadRetryTimer=window.setTimeout(()=>{this._loadRetryTimer=void 0,!e&&this._loadOk||this._loading||!this.hass||this._loadFromServer()},t)}async _ensureLiveRuntime(){if(this._liveRt)return;const e=await import("./live-interaction-runtime-BA69oN1Z.js");this._liveRt=new e.LiveRuntime(this),this.isConnected&&this.requestUpdate()}_liveVp(e=!1){this._liveRt?this._liveRt.viewport(e):this.requestUpdate()}_syncLiveHover(){this._liveRt?this._liveRt.hover():this.requestUpdate()}_flushHa(){this._liveRt?.take()&&(this._terminalFrame=2,super.requestUpdate())}_ensureHaRegistryAuthority(){const e=this.hass?.connection||null;e&&e!==this._haRegistryConnection&&(this._haRegistryRelease?.(),this._haRegistryConnection=e,this._haRegistryRev=-1,this._haBindingCacheKey="",this._renderLife.invalidate(),this._areaSnapshotCleanupCandidates.clear(),this._planHassMemo=null,this._haRegistryRelease=td(this.hass,this._onHaRegistryUpdate),this._onHaRegistryUpdate())}get _haRegistry(){return nd(this.hass)}get _planHass(){const e=this._haRegistry,t=od(this.hass,e),i=this._planHassMemo;if(i&&i.hass===this.hass&&i.sig===t)return i.active;const n=ad(this.hass,e),r=ld(this.hass,e);return this._planHassMemo={hass:this.hass,sig:t,active:n,full:r},n}_captureRenderDeviceSnapshot(){if(!this.hass)return;const e=Date.now(),t=[...this._activityRt.entries()].map(([t,i])=>`${t}:${i.gen}:${i.flashTs}:`+(i.flashKind&&(i.expiresAt||i.flashTs+tg)>e?1:0)).join("|"),i=Bh(this._virtualLights);if(this._capturedSnapshotSequence===this._hassSequence&&this._capturedSnapshotDevices===this._devices&&this._capturedSnapshotLayout===this._layout&&this._capturedSnapshotConfigEpoch===this._cfgEpoch&&this._capturedSnapshotVirtual===i&&this._capturedSnapshotActivity===t)return;const n=this._planHass,r=new Map,o=new Map,s=new Set(["sun.sun"]);for(const e of this._summary?.entityIds()||[])s.add(e);this._vacFit?.source&&s.add(this._vacFit.source);const a=new Set,l=new Set,c=e=>{if(!e)return;const t=e.indexOf(":");if(t<0)return void s.add(e);const i=e.slice(0,t),n=e.slice(t+1);"device"===i?a.add(n):"entity"===i&&s.add(n)};for(const e of this._model)for(const t of e.rooms)t.area&&l.add(t.area),c(t.settings?.temp_source),c(t.settings?.hum_source);for(const e of this._serverCfg?.spaces||[])for(const t of e.openings||[])for(const e of ui(t))s.add(e);for(const e of this._serverCfg?.spaces||[])for(const t of e.decor||[])if("text"===t.kind){for(const e of String(t.text||"").matchAll(/\{([^{}\r\n]+)\}/g)){const t=Ki(e[1]);t?.entity&&s.add(t.entity)}t.entity&&s.add(t.entity),o.set(`decor:${e.id}:${t.id}`,Qi(t.text,t,n,e=>!!n.entities?.[e]&&!!n.states?.[e]&&!Jd(n,e,Zd(this._markers))))}const h=Ed(n,this._devices,null,this._virtualLights);for(const e of this._devices){for(const t of[!1,!0])r.set(f_(e.id,t),p_(n,e,{liveStates:!1!==this._config?.live_states,showTemperature:!1!==this._config?.show_temperature,showSignal:t,activityRuntime:this._activityRt.get(e.id),sourceDetails:!1,lightDevices:this._devices,lightSources:h,registryHass:this._fullRegistryHass,reducedMotion:this._reducedMotion}));if(this._isVacDev(e)){const t=this._vacSource(e,n),i=t?Wc(n?.states?.[t]?.attributes):null,r=this._vacRt.get(e.id),s=lh(e.id,e.marker?.vacuum??null,e.space,t),a=hh({routes:s,observed:dh(s,[t],t=>this._vacObservedMapId(e,t,n)),spaceIds:new Set(this._model.map(e=>e.id))});o.set(`vacuum:${e.id}`,{source:t,telemetry:i,routes:s,resolution:a,mapId:i?this._vacMapId(e,i,n):null,runtime:r?{trail:r.trail,lastTs:r.lastTs,moving:r.moving,jump:r.jump}:null,server:this._vacSrvTrails[e.id]||null})}}const d=g_({sourceSequence:this._hassSequence,hass:n,devices:this._devices,presentations:r,positions:(u=this._model.length>0,p=this._devices,_=e=>this._livePos(e),u?new Map(p.map(e=>[e.id,_(e)])):new Map),facts:o,entityIds:s,deviceIds:a,areaIds:l});var u,p,_;this._capturedSnapshotSequence=this._hassSequence,this._capturedSnapshotDevices=this._devices,this._capturedSnapshotLayout=this._layout,this._capturedSnapshotActivity=t,this._capturedSnapshotConfigEpoch=this._cfgEpoch,this._capturedSnapshotVirtual=i,this._visibleDeviceSnapshot&&"steady"!==this._continuity.state?this._candidateDeviceSnapshot=d:(this._visibleDeviceSnapshot=d,this._candidateDeviceSnapshot=null)}get _renderDeviceSnapshot(){return this._stagedDeviceSnapshotToken===this._continuity.token?this._candidateDeviceSnapshot||this._visibleDeviceSnapshot:this._visibleDeviceSnapshot||this._candidateDeviceSnapshot}get _renderPlanHass(){return this._renderDeviceSnapshot?.hass||this._planHass}get _renderDevices(){return this._renderDeviceSnapshot?.devices||this._devices}get _renderVacuumDevices(){return this._renderDeviceSnapshot?.vacuumDevices||this._devices}get _fullRegistryHass(){return this._planHass,this._planHassMemo?.full||this.hass}_bindingStatus(e){return dd(this.hass,e,this._haRegistry)}houseplanDiagnostics(){const{registry:e,bindings:t}=this._renderLife.diagnostics(this.hass,this._markers,e=>this._bindingStatus(e));return{registry:{...e,lastSuccessAgeMs:e.lastSuccess?Math.max(0,Date.now()-e.lastSuccess):null},bindings:t}}_openBindingInHa(e){const[t,i]=e.split(":");if(i)if("device"!==t){if("entity"===t){const e=this._fullRegistryHass.entities?.[i];e?.device_id&&fv("/config/devices/device/"+encodeURIComponent(e.device_id))}}else fv("/config/devices/device/"+encodeURIComponent(i))}_bindingHasHaPage(e){const[t,i]=e.split(":");return!!i&&("device"===t||"entity"===t&&!!this._fullRegistryHass.entities?.[i]?.device_id)}_toggleMarkerDialogVisibility(){const e=this._markerDialog;if(!e)return;const t="ha"===e.bindingMode?this._bindingStatus(e.binding):null,i=e.hideFromPlan||"ha_disabled"===t?.kind;i&&"ha_disabled"===t?.kind?this._showToast(this._t("entity"===t.reason?"toast.ha_disabled_show_entity":"toast.ha_disabled_show_device")):i&&"unverified"===t?.kind?this._showToast(this._t("toast.ha_binding_unverified")):this._markerDialog={...e,hideFromPlan:!i}}_hookConnection(){const e=this.hass?.connection;e&&e!==this._connHooked&&(this._connHooked?.removeEventListener?.("ready",this._onConnReady),this._connHooked?.removeEventListener?.("disconnected",this._onConnLost),this._connHooked?.removeEventListener?.("reconnect-error",this._onConnLost),e.addEventListener?.("ready",this._onConnReady),e.addEventListener?.("disconnected",this._onConnLost),e.addEventListener?.("reconnect-error",this._onConnLost),this._connHooked=e)}_display(e){return this._signer.display(this.hass,e)}_referencedContentUrls(){const e=On(this._serverCfg);for(const t of this._decorAssets.values())e.add(t.url);return e}_resign(){this._signer.resign(this.hass,this._referencedContentUrls())}_onLayoutEvent(e){e<=this._layoutRev||(clearTimeout(this._layoutSyncTimer),this._layoutSyncTimer=window.setTimeout(()=>{e<=this._layoutRev||this._reloadLayoutOnly()},200))}_noteLayoutRev(e){this._adoption.noteLayoutRevision(e?.rev)}async _reloadLayoutOnly(){if(!this._serverStorage||!this.hass?.callWS)return;this._beginContinuityCandidate("layout-reload",!1);const e=new Map;for(const t of this._dirtyPos)this._layout[t]&&e.set(t,this._layout[t]);this._persistLayout.pending()&&this._persistLayout.flush();for(const[t,i]of this._sentPos)e.set(t,i);try{const t=await this.hass.callWS({type:"houseplan/layout/get"}),i={...t?.layout||{}};for(const[t,n]of e)null===n?delete i[t]:i[t]=n;this._adoption.adoptMergedLayout(i,t,()=>{this._cancelDeviceDrag(),this._devicePositionHistory.clear()}),this._canOptimizeUndo=!!t?.can_optimize_undo,this._undoKind=t?.undo_kind||null,this._cacheSnapshot(),this.requestUpdate()}catch{}finally{this._continuityDataReady=!0,this.requestUpdate()}}_persistLocalLayout(){this._layout=wo(oo(this._layout)),localStorage.setItem(lv,JSON.stringify(this._layout))}_maybeRebuildDevices(){const e=this.hass;if(!e?.devices||!e?.entities||!e?.areas)return;const t=this._haRegistry,i=od(e,t)+":"+Object.keys(e.areas).length+":"+(this._norm?"n":"l")+":"+kp(e,this._config?.language);if(i===this._regSignature&&this._devices.length)return;this._regSignature=i;const n=new Map(this._devices.map(e=>[e.id,e.bindingStatus?.kind||"active"]));this._devices=iu({hass:e,registry:t,areaToSpace:Object.fromEntries(Object.entries(this._areaToSpace).map(([e,t])=>[e,t.space])),markers:this._markers,settings:this._settings,excluded:this._excluded,showAll:this._showAll,firstSpaceId:this._model[0]?.id||"",loc:e=>this._t(e),iconRules:this._iconRules});const r=this._markers.filter(e=>!e.removed&&"virtual"!==e.binding).map(e=>e.binding).sort(),o=t.revision+":"+r.join("|");if(t.authoritative&&o!==this._haBindingCacheKey){const i=new Map;for(const n of r)i.set(n,dd(e,n,t));!function(e){if("undefined"==typeof localStorage||!e.size)return;const t=hd(),i=Date.now();for(const[n,r]of e)"active"===r.kind?t[n]={kind:"active",ts:i}:"ha_disabled"===r.kind&&(t[n]={kind:"ha_disabled",reason:r.reason,ts:i});const n=Object.fromEntries(Object.entries(t).sort((e,t)=>t[1].ts-e[1].ts).slice(0,1500));Yh=n;try{localStorage.setItem(Kh,JSON.stringify(n))}catch{}}(i),this._haBindingCacheKey=o}let s=null;if(t.authoritative&&(s=this._resolveAreaRelocations(t),this._areaRelocationIds=new Set(s.relocateIds),this._areaRelocationIds.size)){this._cancelDeviceDrag();const e=this._areaRelocationIds;this._devicePositionHistory.removeWhere(({before:t,after:i})=>e.has(t.deviceId)||e.has(i.deviceId));const t=this._markerDialog;if(t?.devId&&!t.roomTouched&&this._areaRelocationIds.has(t.devId)){const e=this._devices.find(e=>e.id===t.devId);e&&(this._markerDialog={...t,room:e.marker?.room_id?`${e.space}#@${e.marker.room_id}`:e.space&&e.area?`${e.space}#${e.area}`:""})}}this._defPos=this._defaultPositions(),this._syncNewDevices(),this._seedHiddenDevices(),s&&this._syncAreaRelocations(s),this._syncActivityRuntime();const a=new Set(this._devices.filter(e=>!e.hidden).map(e=>e.id));for(const e of this._vacRt.keys())a.has(e)||this._vacRt.delete(e);if(this._infoCard){const e=this._devices.find(e=>e.id===this._infoCard.id);this._infoCard=e&&"ha_disabled"!==e.bindingStatus?.kind?e:null}const l=this._devices.some(e=>"ha_disabled"===e.bindingStatus?.kind&&"ha_disabled"!==n.get(e.id));l&&("ha_disabled"!==this._infoCard?.bindingStatus?.kind&&"ha_disabled"!==this._devices.find(e=>e.id===this._infoCard?.id)?.bindingStatus?.kind||this._closeInfoCard(),this._deviceDrag&&"ha_disabled"===this._devices.find(e=>e.id===this._deviceDrag.id)?.bindingStatus?.kind&&(this._cancelDeviceDrag(),this._devicePositionHistory.clear()),clearTimeout(this._holdTimer),this._holdFired=!1,this._tip=null,this._tapConfirm=null),this._nativeMoreInfoEntity&&!this._planEntityAvailable(this._nativeMoreInfoEntity)&&(gv(this,"hass-more-info",{entityId:null}),this._nativeMoreInfoEntity=null)}_resolveAreaRelocations(e=this._haRegistry){const t=function(e){const t=Q_(e.snapshot),i=new Set(Object.values(t).map(e=>e.binding)),n=new Map;for(const[t,r]of e.previousCandidates||[])J_(t)&&Number.isFinite(r)&&i.has(t)&&n.set(t,r);const r=new Set,o=new Set;for(const t of e.markers||[])t.removed||(Z_(t.id)&&r.add(t.id),J_(t.binding)&&o.add(t.binding));const s=new Set(Object.keys(e.registryDevices||{})),a=new Set(Object.keys(e.registryEntities||{})),l=new Set(Object.keys(e.liveStates||{})),c=new Map;for(const[e,i]of Object.entries(t)){const t=c.get(i.binding)||[];t.push(e),c.set(i.binding,t)}const h=new Set;let d=!1;for(const[t,i]of c){const[c,u]=rm(t);if(o.has(t)||i.some(e=>r.has(e))||("device"===c?s.has(u):a.has(u)||l.has(u))){n.delete(t);continue}const p="device"===c?s.size>0:a.size>0;if(!e.authoritative||!p)continue;const _=n.get(t);if(void 0!==_){if(_!==e.revision)for(const e of i)h.add(e)}else n.set(t,e.revision),d=!0}return{removeIds:h,candidates:n,needsConfirmationRefresh:d}}({snapshot:this._settings.marker_area_snapshot,authoritative:e.authoritative,revision:e.revision,registryDevices:e.devices,registryEntities:e.entities,liveStates:this.hass?.states,markers:this._markers,previousCandidates:this._areaSnapshotCleanupCandidates});return this._areaSnapshotCleanupCandidates=t.candidates,t.needsConfirmationRefresh&&this._canEdit&&id(this.hass),om({devices:this._devices,model:this._model,layout:this._layout,snapshot:this._settings.marker_area_snapshot,authoritative:e.authoritative,cleanupSnapshotIds:t.removeIds,coordinateScale:_v})}_syncNewDevices(){if(!this._norm||!this._loadOk||!this._serverCfg)return;const e=this._devices.filter(e=>!e.marker&&!e.virtual).map(e=>e.id).sort(),t=e.join(",");if(t===this._newSyncKey)return;this._newSyncKey=t;const i=this._settings,{fresh:n,known:r}=function(e,t){if(!Array.isArray(t))return{fresh:[],known:[...e]};const i=new Set(t),n=e.filter(e=>!i.has(e));return{fresh:n,known:n.length?[...t,...n]:t}}(e,i.known_devices);if(!Array.isArray(i.known_devices)||n.length){const e=[...new Set([...i.new_device_ids||[],...n])];this._serverCfg={...this._serverCfg,settings:{...i,known_devices:r,new_device_ids:e}},this._saveConfig()}}_syncAreaRelocations(e){if(!(this._loadOk&&this._serverCfg&&this._norm&&this._canEdit&&this._haRegistry.authoritative))return;const t=e.decisions.filter(e=>e.updateSnapshot||e.removeSnapshot);if(!t.length)return;const i=cc({snapshot:Q_(this._settings.marker_area_snapshot),decisions:t});i!==this._areaRelocationSyncKey&&(this._areaRelocationSyncKey=i,this._areaRelocationWrite=this._areaRelocationWrite.catch(()=>{}).then(async()=>{if(!this._serverCfg||!this._haRegistry.authoritative)return;const e=this._resolveAreaRelocations();this._areaRelocationIds=new Set(e.relocateIds);const t=new Set,i=new Map;let n=!1;for(const r of e.decisions){if(!r.relocate)continue;const e=fg(this._layout,r.id);try{await this._persistDevicePlacement(r.id,null),t.add(r.id),e&&i.set(r.id,e),this._areaRelocationIds.delete(r.id)}catch(t){n=!0,this._layout=vg(this._layout,r.id,e),this._showToast(this._t("toast.pos_save_failed",{err:this._errText(t)}))}}const r=this._settings,o=function(e,t,i=new Set){const n=Q_(e);for(const e of t.decisions)e.removeSnapshot?delete n[e.id]:e.updateSnapshot&&e.binding&&e.area&&(e.relocate&&!i.has(e.id)||(n[e.id]={binding:e.binding,area:e.area}));return n}(r.marker_area_snapshot,e,t),s=[...new Set([...Array.isArray(r.new_device_ids)?r.new_device_ids:[],...t])],a=cc(o)!==cc(Q_(r.marker_area_snapshot)),l=cc(s)!==cc(Array.isArray(r.new_device_ids)?r.new_device_ids:[]);if(a||l){const e=r.marker_area_snapshot,n=r.new_device_ids,a={...this._serverCfg,settings:{...r,marker_area_snapshot:o,...l?{new_device_ids:s}:{}}};this._setAreaLifecycleConfig(a);try{this._saveConfigDebounced.pending()&&this._saveConfigDebounced.cancel(),await this._writeConfig()}catch(r){const a=this._settings;if(cc(a.marker_area_snapshot)===cc(o)&&cc(a.new_device_ids)===cc(l?s:n)){const t={...a};void 0===e?delete t.marker_area_snapshot:t.marker_area_snapshot=e,void 0===n?delete t.new_device_ids:t.new_device_ids=n;const i={...this._serverCfg,settings:t};this._setAreaLifecycleConfig(i),this._adoption.refreshConfigFingerprint()}for(const e of t)this._areaRelocationIds.add(e);const c=new Set;for(const[e,t]of i)try{await this._persistDevicePlacement(e,t)}catch(t){c.add(e),this._showToast(this._t("toast.pos_save_failed",{err:this._errText(t)}))}this._areaRelocationSyncKey="",this._regSignature="";if("conflict"===(r&&"object"==typeof r&&"code"in r?r.code:void 0)?(this._showToast(this._t("toast.conflict")),await this._reloadConfigOnly(!0)):this._showToast(this._t("toast.cfg_save_failed",{err:this._errText(r)})),c.size&&this._serverCfg){const e=this._settings,t=[...new Set([...Array.isArray(e.new_device_ids)?e.new_device_ids:[],...c])],i={...this._serverCfg,settings:{...e,new_device_ids:t}};this._setAreaLifecycleConfig(i);try{await this._writeConfig()}catch(e){this._showToast(this._t("toast.cfg_save_failed",{err:this._errText(e)}))}}}}n&&(this._areaRelocationSyncKey=""),this.requestUpdate()}))}get _newIds(){const e=this._settings.new_device_ids;return new Set([...Array.isArray(e)?e:[],...this._areaRelocationIds])}_ackNewDevice(e){if(!this._newIds.has(e)||!this._serverCfg)return;const t=this._settings;this._serverCfg={...this._serverCfg,settings:{...t,new_device_ids:(t.new_device_ids||[]).filter(t=>t!==e)}},this._saveConfig(),this.requestUpdate()}get _markers(){return this._serverCfg?.markers||[]}_roomLqi(e){if(!e)return null;const t=[];for(const i of this._renderDevices){if(i.area!==e||i.virtual)continue;const n=Ld(this._renderPlanHass,i.entities);null!=n&&t.push(n)}return Ii(t)}_roomBounds(e){if(e.poly&&e.poly.length){const t=e.poly.map(e=>e[0]),i=e.poly.map(e=>e[1]),n=Math.min(...t),r=Math.min(...i);return{x:n,y:r,w:Math.max(...t)-n,h:Math.max(...i)-r}}return{x:e.x??0,y:e.y??0,w:e.w??0,h:e.h??0}}_defaultPositions(){const e={},t=this._config?.icon_size??2.5;for(const i of this._model){const n=t/100*xl(i)*1.3;for(const t of i.rooms){if(!t.area)continue;const r=this._devices.filter(e=>e.area===t.area&&e.space===i.id);if(!r.length)continue;const o=this._roomBounds(t),s=.1*Math.min(o.w,o.h),a=o.w-2*s,l=o.h-2*s,c=Math.max(1,Math.round(Math.sqrt(r.length*a/Math.max(l,1)))),h=Math.ceil(r.length/c),d=a/c,u=l/Math.max(h,1),p=r.map((e,t)=>({x:o.x+s+d*(t%c+.5),y:o.y+s+u*(Math.floor(t/c)+.5)}));Ei(p,o,n,.5*s),r.forEach((t,i)=>e[t.id]=rl(p[i]))}}return e}_pos(e){const t=this._renderDeviceSnapshot?.positions.get(e.id);return t?{x:t.x,y:t.y}:this._livePos(e)}_livePos(e){const t=this._spaceModelById(e.space),i=this._areaRelocationIds.has(e.id)?void 0:this._layout[e.id];if(i)if(this._norm){if(i.s===e.space)return{x:i.x*_v,y:i.y*_v}}else if(void 0===i.s)return{x:i.x,y:i.y};return this._defPos[e.id]?this._defPos[e.id]:t?rl(kl(t)):{x:500,y:500}}_devicePlacementForCanvas(e,t,i){if(!this._norm)return{x:Math.round(t),y:Math.round(i)};const n=this._gridPitch,r=Math.round(t/n)*n,o=Math.round(i/n)*n;return{s:e.space,x:sl(r/_v),y:sl(o/_v)}}_previewDevicePlacement(e,t){this._layout=vg(this._layout,e,t),this.requestUpdate()}_cancelDeviceDrag(){const e=this._deviceDrag;if(!e)return!1;this._editorRuntime?._cancelPointerMove("device"),this._deviceDrag=null,this._deviceHits.cancel(e.pointerId);try{e.source?.hasPointerCapture?.(e.pointerId)&&e.source.releasePointerCapture(e.pointerId)}catch{}return this._previewDevicePlacement(e.id,e.before),!0}async _persistDevicePlacement(e,t){if(this._layout=vg(this._layout,e,t),this._serverStorage){let i=null,n=!1;try{let r;if(null===t)i=null,this._sentPos.set(e,i),n=!0,r=await this.hass.callWS({type:"houseplan/layout/delete",device_id:e});else{const t=bo(this._layout[e]);cc(t)!==cc(this._layout[e])&&(this._layout={...this._layout,[e]:t}),i=t,this._sentPos.set(e,i),n=!0,r=await this.hass.callWS({type:"houseplan/layout/update",device_id:e,pos:t})}this._noteLayoutRev(r),this._adoption.refreshLayoutFingerprint(),this._cacheSnapshot()}finally{n&&this._sentPos.get(e)===i&&this._sentPos.delete(e)}return}this._persistLocalLayout()}_devicePositionStateValid(e){const t=this._devices.find(t=>t.id===e.deviceId);return!!t&&t.space===e.spaceId&&"ha_disabled"!==t.bindingStatus?.kind&&!!this._spaceModelById(e.spaceId)}async _runDevicePositionHistory(e){if(this._cancelDeviceDrag()||this._devicePositionBusy)return;const t="undo"===e?this._devicePositionHistory.undo():this._devicePositionHistory.redo();if(!t)return;const i="undo"===e?t.before:t.after;if(!this._devicePositionStateValid(i))return this._devicePositionHistory.clear(),this._showToast(this._t("history.device_stale")),void this.requestUpdate();const n=fg(this._layout,i.deviceId);i.spaceId!==this._space&&(this._commitSpace(i.spaceId),this._restoreZoom()),this._devicePositionBusy=!0,this._previewDevicePlacement(i.deviceId,i.placement);try{await this._persistDevicePlacement(i.deviceId,i.placement),this._showToast(this._t("undo"===e?"history.undone":"history.redone",{name:t.name}))}catch(t){this._previewDevicePlacement(i.deviceId,n),"undo"===e?this._devicePositionHistory.redo():this._devicePositionHistory.undo(),this._showToast(this._t("toast.pos_save_failed",{err:this._errText(t)}))}finally{this._devicePositionBusy=!1,this.requestUpdate()}}_undoDevicePosition(){this._runDevicePositionHistory("undo")}_redoDevicePosition(){this._runDevicePositionHistory("redo")}_savePos(e,t,i){this._spaceModelById(e.space)&&(this._layout=vg(this._layout,e.id,this._devicePlacementForCanvas(e,t,i)),this._dirtyPos.add(e.id),this._persistLayout())}_devicePresentation(e,t=!1!==this._config?.show_signal,i=!1){const n=i?null:this._renderDeviceSnapshot?.presentations.get(f_(e.id,t));return n||p_(this._renderPlanHass,e,{liveStates:!1!==this._config?.live_states,showTemperature:!1!==this._config?.show_temperature,showSignal:t,designPreview:i,activityRuntime:this._activityRt.get(e.id),sourceDetails:!1,lightDevices:this._renderDevices,registryHass:this._fullRegistryHass,reducedMotion:this._reducedMotion})}_deviceVisual(e){return this._devicePresentation(e).visual}_stateClass(e,t=this._deviceVisual(e)){const i=this._devicePresentation(e);return i.effectiveHidden?"":("icon_ripple"!==i.display||!1===this._config?.live_states||"alarm"===t.status||t.activity,u_({...i,visual:t}).join(" "))}_liveTemp(e){if(!this._config?.show_temperature)return null;if(!0===e.marker?.use_climate_temp){const t=qd(this._renderPlanHass,e.entities);if(null!=t)return t}return"mdi:thermometer"!==e.icon&&"mdi:air-filter"!==e.icon?null:Bd(this._renderPlanHass,e.entities)}_bindingEntities(e){if("virtual"===e||!e)return[];const t=this._bindingStatus(e);return"active"===t.kind?t.enabledEntityIds:t.allEntityIds}_bindingHasClimate(e){return this._bindingEntities(e).some(e=>e.startsWith("climate."))}_bindingHasAlarm(e){return this._bindingEntities(e).some(e=>{const t=this._planHass?.states?.[e]||this.hass?.states?.[e],i=this._fullRegistryHass.entities[e]||this.hass?.entities?.[e];return Vn(e.split(".")[0],t?.attributes?.device_class||i?.device_class||i?.original_device_class)})}_deviceBindingActive(e,t=!0){if(e.virtual||"virtual"===e.bindingKind)return!0;if(!e.bindingKind||!e.bindingRef)return!1;const i=this._bindingStatus(`${e.bindingKind}:${e.bindingRef}`);return"active"===i.kind||(t&&this._showToast(this._t("ha_disabled"===i.kind?"toast.ha_disabled_action":"toast.ha_binding_unverified")),!1)}_openMoreInfo(e){e?this._planEntityAvailable(e)?(this._kiosk&&(this._cyclePausedUntil=Math.max(this._cyclePausedUntil,Date.now()+6e4)),this._nativeMoreInfoEntity=e,gv(this,"hass-more-info",{entityId:e})):this._showToast(this._t("toast.ha_disabled_action")):this._showToast(this._t("toast.no_entity"))}_interruptViewGesture(e,t){if(clearTimeout(this._holdTimer),clearTimeout(this._kioskHoldTimer),void 0!==e)for(const i of[t,this._stageEl])try{i?.hasPointerCapture?.(e)&&i.releasePointerCapture(e)}catch{}this._pointers.clear(),this._panStart=null,this._panLock=null,this._pinchStart=null,this._swipeStart=null,this._roomPointer=null,this._doubleFit.clear(),this._deviceHits.clearPointers()}_closeInfoCard(){this._interruptViewGesture(),this._holdFired=!1,this._infoCard=null}_invalidateDeviceHitGeometry(){this._deviceHits.invalidate()}_resetDeviceHitState(){this._deviceHits.reset(this.renderRoot)}_deviceHitOwnerAt(e,t){return"view"!==this._mode&&"devices"!==this._mode?null:this._deviceHits.at(this.renderRoot,this._renderDevices,this._space,e,t)}_deviceForPointerEvent(e,t){return this._deviceHits.pointer(this.renderRoot,this._renderDevices,this._space,e,t)}_deviceForClickEvent(e,t){return this._deviceHits.click(this.renderRoot,this._renderDevices,this._space,e,t)}_showDeviceTip(e,t){this._liveRt?this._liveRt.devicePointerTip(e,t):this._ensureLiveRuntime().then(()=>this._liveRt?.devicePointerTip(e,t))}_showDeviceFocusTip(e,t){const i=e.currentTarget;this._liveRt?this._liveRt.deviceFocusTip(i,t):this._ensureLiveRuntime().then(()=>this._liveRt?.deviceFocusTip(i,t))}_hideDeviceFocusTip(e){this._liveRt?.deviceBlur(e)}_clearPointerHover(){this._liveRt?this._liveRt.pointerLeave():this._clearTransientHover()}_ctxDevice(e,t){"view"===this._mode&&(t=this._deviceForPointerEvent(e,t),e.preventDefault(),e.stopPropagation(),this._deviceBindingActive(t)&&(t.primary?this._openMoreInfo(t.primary):this._infoCard=t))}_clickDevice(e,t){if("view"!==this._mode&&"devices"!==this._mode)return;if(e.stopPropagation(),t=this._deviceForClickEvent(e,t),this._deviceDrag?.moved||this._suppressClick||this._holdFired)return;if("devices"===this._mode)return void this._openMarkerDialog(t);const i=this._devices.find(e=>e.id===t.id);if(!i)return;const n=Tu(i.tapAction,i.primary?.split(".")[0]);if("none"===n)return;const r=(e,t)=>{i.marker?.tap_confirm?this._tapConfirm={kind:"run",text:e,exec:t}:t()};if("toggle"===n){const e=this._toggleIntent(i);if(!e)return;if(!Iu(e))return void this._showUnavailableToggleTargets(e);const t=e=>{const t=Iu(e);if(!t)return;if("virtual-light"===t.kind)return this._startDevicePressFeedback(i.id),void this.hass.callWS({type:"houseplan/virtual_light/toggle",marker_id:t.markerId}).then(e=>{const t=Wh(this._virtualLights,e);t!==this._virtualLights&&(this._virtualLights=t,this._capturedSnapshotVirtual="",this._cacheSnapshot(),this.requestUpdate())}).catch(e=>this._showToast(this._t("toast.virtual_light_toggle_failed",{err:this._errText(e)})));const{command:n}=t;this._startDevicePressFeedback(i.id),this.hass.callService(n.domain,n.service,n.data).catch(e=>this._showToast(this._t("toast.error",{err:this._errText(e)})))},n=((o=e).targets.length?o.targets:o.skippedTargets).map(e=>e.name||e.entityId||e.ref).join(", ")||i.name;if(i.marker?.tap_confirm){const r=this._toggleConfirmationLines(e);if(!r.length)return;this._tapConfirm={kind:"toggle",text:this._t("confirm.tap_toggle",{name:n}),lines:r,initialIntent:e,deviceId:i.id,exec:()=>{const n=this._devices.find(e=>e.id===i.id),r=n?this._toggleIntent(n):null;r&&!Iu(r)&&this._showUnavailableToggleTargets(r)||(r&&Eu(e,r)?t(r):this._showToast(this._t("toast.tap_target_changed")))}}}else t(e);return}var o;if("info"===n)return this._interruptViewGesture(),void(this._infoCard=i);if(this._deviceBindingActive(i)){if("run"===n){const e=i.marker?.tap_target||"",t=function(e){const t=String(e||"").split(".")[0];return"automation"===t?{domain:"automation",service:"trigger"}:"script"===t?{domain:"script",service:"turn_on"}:"scene"===t?{domain:"scene",service:"turn_on"}:null}(e),n=this.hass.states[e];if(!t||!n)return void this._showToast(this._t("toast.run_target_missing"));const o=n.attributes?.friendly_name||e;return void r(this._t("confirm.tap_run",{name:o}),()=>{this._deviceBindingActive(i)&&this._planEntityAvailable(e)&&(this._startDevicePressFeedback(i.id),this.hass.callService(t.domain,t.service,{entity_id:e}).then(()=>{this._stampActivity(i.id,"event",this._activitySourceKey(i)),this.requestUpdate(),this._showToast(this._t("toast.run_started",{name:o}))}).catch(e=>this._showToast(this._t("toast.error",{err:this._errText(e)}))))})}"more-info"===n&&i.primary?this._openMoreInfo(i.primary):this._infoCard=i}}_showUnavailableToggleTargets(e){const t=function(e){if(!e||"group"!==e.kind||Iu(e)||"configured-targets-missing"!==e.noneReason)return[];if(!e.skippedTargets.length||e.skippedTargets.some(e=>!Ou.has(e.reason)&&"secure"!==e.reason))return[];const t=[],i=new Set;for(const n of e.skippedTargets){if(!Ou.has(n.reason))continue;const e=String(n.name||n.entityId||n.ref||"").trim();e&&!i.has(e)&&(i.add(e),t.push(e))}return t}(e);return!!t.length&&(this._showToast(1===t.length?this._t("toast.toggle_target_unavailable",{name:t[0]}):this._t("toast.toggle_targets_unavailable",{names:t.join(", ")})),!0)}_keyDevice(e,t){"Enter"!==e.key&&" "!==e.key||"view"!==this._mode&&"devices"!==this._mode||(e.preventDefault(),this._clickDevice(e,t))}_startDevicePressFeedback(e){const t=[...this.renderRoot.querySelectorAll(".dev[data-id]")].find(t=>t.dataset.id===e),i=t?.querySelector(".device-shell");if(!i||"function"!=typeof i.animate)return;const n=Number.parseFloat(this.ownerDocument.defaultView?.getComputedStyle(i).scale||""),r=Number.isFinite(n)?Math.max(.95,Math.min(1,n)):1;this._devicePressAnimations.get(e)?.cancel();const o=this._reducedMotion?[{outlineColor:"transparent",outlineStyle:"solid",outlineWidth:"0px"},{outlineColor:"var(--hp-accent, #3ea6ff)",outlineStyle:"solid",outlineWidth:"2px",outlineOffset:"2px",offset:.5},{outlineColor:"transparent",outlineStyle:"solid",outlineWidth:"0px"}]:[{scale:String(r)},{scale:"0.95",offset:.5},{scale:"1"}],s=i.animate(o,{duration:200,easing:"cubic-bezier(.22,.61,.36,1)"});this._devicePressAnimations.set(e,s);const a=()=>{this._devicePressAnimations.get(e)===s&&this._devicePressAnimations.delete(e)};s.addEventListener("finish",a,{once:!0}),s.addEventListener("cancel",a,{once:!0})}_cancelDevicePressFeedback(){for(const e of this._devicePressAnimations.values())e.cancel();this._devicePressAnimations.clear()}_pruneDevicePressFeedback(){if(!this._devicePressAnimations.size)return;const e=new Set([...this.renderRoot.querySelectorAll(".dev[data-id]")].map(e=>e.dataset.id||""));for(const[t,i]of this._devicePressAnimations)e.has(t)||(i.cancel(),this._devicePressAnimations.delete(t))}_t(e,t){return xp(kp(this.hass,this._config?.language),e,t)}get _colorPickerLabels(){return{title:this._t("color_picker.title"),hue:this._t("color_picker.hue"),saturation:this._t("color_picker.saturation"),value:this._t("color_picker.value"),hex:this._t("color_picker.hex"),invalidHex:this._t("color_picker.invalid_hex"),confirm:this._t("color_picker.confirm")}}_help(e){return this._editorRuntimeOrThrow()._help(e)}get _stageEl(){return this.renderRoot.querySelector(".stage")}_contentItems(e){const t=[];for(const i of this._devices){if(i.space!==e.id||i.hidden)continue;const n=this._pos(i);t.push({minX:n.x,minY:n.y,maxX:n.x,maxY:n.y})}if(e.id===this._space){for(const e of this._openingsR){const i=Number(e.angle)*Math.PI/180,n=Math.cos(i)*e.rlen/2,r=Math.sin(i)*e.rlen/2,o=hl([[e.rx-n,e.ry-r],[e.rx+n,e.ry+r]]);o&&t.push(o)}const i=this._decorH;for(const e of this._decorList){if("image"===e.kind&&!this._decorAssets.has(e.asset_id)&&"decor"!==this._mode)continue;const n=hl("line"===e.kind?[[e.x1*_v,e.y1*i],[e.x2*_v,e.y2*i]]:"text"===e.kind?[[e.x*_v,e.y*i]]:Ir({x:e.x*_v,y:e.y*i,w:e.w*_v,h:e.h*i,angle:e.angle}));n&&t.push(n)}for(const i of this._physicalBodiesR(e)){const e=hl(i);e&&t.push(e)}}return ml(e,t)}_frameOf(){const e=this._spaceModel();if(!e){this._frame=null;const e={x:0,y:0,w:_v,h:_v};return{rect:e,all:e,outliers:0}}const t=this._frame,i="view"!==this._mode;if(t&&t.id===e.id&&this._bdDrag)return t;if(t&&t.id===e.id&&t.model===e&&t.layout===this._layout&&t.devs===this._devices&&t.far===this._showFar&&t.grow===i)return t;const n=yl(this._contentItems(e));let r=n.all||wl(e),o=this._showFar?r:n.core||wl(e);return t&&t.id===e.id&&i&&t.grow&&(o=mv(t.rect,o),r=mv(t.all,r)),this._frame={id:e.id,model:e,layout:this._layout,devs:this._devices,far:this._showFar,grow:i,rect:o,all:r,outliers:n.outliers},this._frame}_isoSource(){const e=this._isoSceneRuntime;if(!e)return null;const t=this._spaceModel();if(!t)return null;const i=this._spaceWalls,n=this._openCuts(),r=this._openingsR;return e.createIsoStructuralSource({space:t,walls:i,openCuts:n,openings:r,partitionCuts:()=>this._partitionOpeningCuts(t),roomOpenings:()=>this._roomWallOpeningInputs(r,t),cellCm:this._cellCm,gridPitch:this._gridPitch,wallKeyPitch:this._wallKeyPitch,coordinateScale:_v,onBuild:()=>{this._isoStructuralBuildCount+=1}})}_isoSceneKey(){if(!this._labsIso||"view"!==this._mode)return null;try{return this._isoSource()?.key??null}catch{return this._isoInvalidKey()}}_isoInvalidKey(){return`${this._space}|invalid|${this._cfgEpoch}`}_clearIsoInvalidFallback(e){const t=`${this._space}|invalid|`;for(const i of this._isoFallback)i.startsWith(t)&&i!==e&&this._isoFallback.delete(i)}_isoScene(e=this._isoSource()){const t=this._isoSceneRuntime;if(!t||!e)return null;let i=this._frameOf().rect;const n=this._spaceDisplayForRender(),r=this._spaceModel();if(r&&n.showNames)for(const e of r.rooms)if(e.name){const t=this._labelPos(e,r.id);i=mv(i,{x:t.x,y:t.y,w:0,h:0})}const o=t.resolveIsoScene({source:e,cache:this._isoGeometryCache,cellCm:this._cellCm,liveFrame:i});if(!r||!n.showBorders)return o;const s=this._config?.icon_size??2.5,a=s>8?2.5:s,l=this._stageEl?.getBoundingClientRect?.()??null,c=l?.height?l.width/l.height:o.frame.w/o.frame.h,h=Oi([o.frame.x,o.frame.y,o.frame.w,o.frame.h],c),d=this._isoOverlayScene(r,this._renderDevices.filter(e=>e.space===r.id&&!e.hidden),h,n,t.resolveIsoDecorationLayers(n),o,a,x_(a),n.showLqi??this._config?.show_signal??!0,!1),u=d&&t.resolveIsoOverlayFitEnvelope({baseBounds:o.frame,entries:d.entries,stageSize:l,targetView:e=>Oi([e.x,e.y,e.w,e.h],c)});return u?{...o,frame:u.bounds,overlayFitEntries:d.entries}:o}_latchIsoFallback(e,t){if(this._isoFallback.has(e))return;this._isoFallback.add(e);const i=e.includes("|invalid|")?"invalid":e.split("|").pop()||"invalid";console.warn("HOUSEPLAN ISO FALLBACK: #89/#160",wf("structural",i,!0))}_effectiveProjection(){if(this._isoProjectionSnapshot)return this._isoProjectionSnapshot;const e=e=>this._isoProjectionSnapshot=e,t=()=>("iso"===this._renderProjection&&(this._cancelCameraTransition(!1),this._view=null,this._viewModeSnap=null),e("flat"));if(this._renderIsoScene=null,"iso"!==this._desiredProjection||!this._model.length||!this._isoSceneRuntime)return e("flat");if(!this._spaceDisplayForRender().showBorders)return this._isoFallback.has(`${this._space}|no-borders`)?t():e("iso");let i=this._isoInvalidKey();if(this._clearIsoInvalidFallback(i),this._isoFallback.has(i))return t();try{const n=this._isoSource();if(!n)return e("flat");if(i=n.key,this._isoFallback.has(i))return t();const r=this._isoScene(n);return r?this._isoFallback.has(r.key)?t():(this._renderIsoScene=r,e("iso")):e("flat")}catch(e){return this._latchIsoFallback(i,e),t()}}_scenePoint(e){return"iso"===this._renderProjection?lf(e,0):e}_floorView(e){if("iso"!==this._renderProjection)return e;const t=cf([e.x,e.y]),i=cf([e.x+e.w,e.y+e.h]);return{x:t[0],y:t[1],w:i[0]-t[0],h:i[1]-t[1]}}_isoOverlayScene(e,t,i,n,r,o,s,a,l,c=!0){const h=this._isoSceneRuntime;return h&&r?.structural&&o?h.buildIsoOverlayRenderScene({space:e,devices:t,openings:this._openingsR,view:i,display:n,wallSilhouettes:o.wallSilhouettes,resolveCollisions:c,iconPct:s,deviceBasePct:a,showLqi:l,cellCm:this._cellCm,kioskIconScale:"view"===this._mode?this._kioskScale.icon:1,kioskFontScale:"view"===this._mode?this._kioskScale.font:1,stageSize:this._stageEl?.getBoundingClientRect?.(),positionOf:e=>this._pos(e),presentationOf:(e,t)=>this._devicePresentation(e,t),labelPositionOf:(e,t)=>this._labelPos(e,t),labelScaleOf:e=>this._labelScale(e),openingEntityAvailable:e=>this._renderOpeningEntityAvailable(e),openingWallIndex:()=>this._openingWallIndexFor(e,this._openCuts()).value}):null}_baseVb(e=this._effectiveProjection(),t=this._renderIsoScene){if("iso"===e){if(!this._spaceDisplayForRender().showBorders){const e=uf({rect:this._frameOf().rect,wallHeight:0});return[e.x,e.y,e.w,e.h]}const e=t?.frame??this._frameOf().rect;return[e.x,e.y,e.w,e.h]}const i=this._frameOf().rect;return[i.x,i.y,i.w,i.h]}get _outliers(){return this._showFar?0:this._frameOf().outliers}_fitFar(){this._clearRoomFocus(),this._showFar=!0,this._frame=null,this.requestUpdate(),this._resetZoom()}_clearRoomFocus(e=!1){this._doubleFit.clear(),this._roomFocus=null,e&&(this._roomPointer=null)}_roomFitBounds(e,t){const i=ni(e);if(!i||!e.id)return null;const n=this._spaceWalls,r=this._openCuts(),o=this._wallUnionGeometry(),s=n.length&&this._innerRoomContour(t,e.id,r,o?.roomGeom,o?.multiWallNodes)||i,a=this._spaceDisplayForRender();let l=[];if(a.showBorders&&n.length){const i=Ds(t.rooms,e.id,n,r,this._wallKeyPitch,this._cellCm,this._gridPitch,_v);i&&(l=ra(i.poly,i.offsets,o?.multiWallNodes)||i.poly)}const c=this._effectiveProjection();return function(e){const t=e.floor,i=e.wall||[],n=e.padding??0;if(!t.length||!t.every(vf)||!i.every(vf)||!Number.isFinite(n)||n<0)return null;if("flat"===e.projection)return bf([...t,...i],n);const r=e.wallHeight??0,o=e.floorDepth??0;if(!Number.isFinite(r)||r<0||!Number.isFinite(o)||o<0)return null;try{const e=[];for(const i of t){const t=[i[0],i[1]];e.push(lf(t,0)),o>0&&e.push(lf(t,-o))}for(const t of i){const i=[t[0],t[1]];e.push(lf(i,0)),r>0&&e.push(lf(i,r))}return bf(e,n)}catch{return null}}({floor:s,wall:l,projection:c,wallHeight:"iso"===c&&a.showBorders?Ba(84,this._cellCm):0,floorDepth:"iso"===c&&a.showBorders?Ba(10,this._cellCm):0,padding:a.showBorders?Ba(1.25,this._cellCm):0})}_fitRoom(e,t=!0){if("view"!==this._mode)return!1;this._doubleFit.clear();const i=this._spaceModel(),n=i?.rooms.find(t=>t.id===e);if(!i||!n)return this._clearRoomFocus(),!1;let r=this._roomFitBounds(n,i);if(!r)return this._clearRoomFocus(),!1;this._roomFocus={spaceId:i.id,roomId:e};const o=this._stageEl;if(!o||o.clientWidth<=0||o.clientHeight<=0)return!0;const s=Oi(this._baseVb(),o.clientWidth/o.clientHeight),a=e=>function(e){const t=e.safeFraction??.8,{bounds:i,baseFit:n,stageWidth:r,stageHeight:o,minZoom:s,maxZoom:a}=e;if(!yf(i)||!yf(n)||!Number.isFinite(r)||r<=0||!Number.isFinite(o)||o<=0||!Number.isFinite(s)||s<=0||!Number.isFinite(a)||a1)return null;const l=r/o,c=Math.max(i.w/t,i.h/t*l);if(!Number.isFinite(c)||c<=0)return null;const h=Math.min(a,Math.max(s,n.w/c)),d=n.w/h,u=d/l;return{zoom:h,viewBox:{x:i.x+i.w/2-d/2,y:i.y+i.h/2-u/2,w:d,h:u}}}({bounds:e,baseFit:s,stageWidth:o.clientWidth,stageHeight:o.clientHeight,minZoom:wv.ZOOM_MIN,maxZoom:wv.ZOOM_MAX});let l=a(r);const c=this._isoSceneRuntime,h=this._renderIsoScene?.overlayFitEntries;if(l&&"iso"===this._effectiveProjection()&&c&&h?.length){const e=c.resolveIsoOverlayFitEnvelope({baseBounds:r,entries:h,ownerId:n.id,stageSize:{width:o.clientWidth,height:o.clientHeight},targetView:e=>a(e)?.viewBox??null});e&&(r=e.bounds,l=a(r))}if(!l)return this._clearRoomFocus(),!1;const d=this._cameraState(),u=function(e,t,i,n){const r=[e,t,i,n],o=Math.min(...r.map(e=>e.x)),s=Math.min(...r.map(e=>e.y));return{x:o,y:s,w:Math.max(...r.map(e=>e.x+e.w))-o,h:Math.max(...r.map(e=>e.y+e.h))-s}}(s,d.viewBox,l.viewBox,r);return l.viewBox=this._clampView(l.viewBox,u),t?(this._prepareCameraCommand(),this._startCameraTransition(l,u,"room",220),!0):(this._cancelCameraTransition(!1),Xg(d,l)||(this._zoom=l.zoom,this._view={...l.viewBox},this.requestUpdate()),!0)}_fitAll(e="fit"){this._clearRoomFocus(),this._showFar=!0,this._frame=null,this.requestUpdate(),this._resetZoom(e)}_renderFarHint(){return this._kiosk||"view"!==this._mode||this._booting||!this._outliers?G:j`
- - ${this._t("canvas.far_objects",{n:this._outliers})} - -
`}_renderHomeArrow(e=this._baseVb()){if(this._booting)return G;const t=this._view;if(!t||!t.w||!t.h)return G;const i=e[0],n=e[1],r=e[2],o=e[3];if(!(i+r<=t.x||i>=t.x+t.w||n+o<=t.y||n>=t.y+t.h))return G;const s=Math.atan2(n+o/2-(t.y+t.h/2),i+r/2-(t.x+t.w/2)),a=50+38*Math.cos(s),l=50+38*Math.sin(s);return j``}_stageAspect(e=this._baseVb()){const t=this._stageEl;return t&&t.clientHeight?t.clientWidth/t.clientHeight:e[2]/e[3]}_viewOr(e){return this._view&&this._view.w?this._view:Oi(e,this._stageAspect(e))}_roomLabelReferenceViewWidth(e){if(!this._markup)return e.w;const t=this._viewModeSnap;if(t?.space===this._space&&t.w)return t.w*t.zoom/this._zoom;const i=this._stageEl,n=this.renderRoot.querySelector(".editorchrome");if(!i?.clientWidth||!i.clientHeight)return e.w;const r=i.clientHeight+(n?.offsetHeight||0);return this._viewForModeTarget(this._zoom,void 0,void 0,i.clientWidth,r).w}_screenToVb(e,t){const i=this._stageEl,n=this._viewOr(this._baseVb()),r=i?.clientWidth||1,o=i?.clientHeight||1;return[n.x+e/r*n.w,n.y+t/o*n.h]}_clampView(e,t){const i=(e,t,i,n)=>{const r=1*Math.max(t,n),o=i-r,s=i+n-t+r;return Math.max(Math.min(o,s),Math.min(Math.max(o,s),e))};return{w:e.w,h:e.h,x:i(e.x,e.w,t.x,t.w),y:i(e.y,e.h,t.y,t.h)}}_applyView(e,t,i){this._cancelCameraTransition(!1);const n=this._baseVb(),r=Oi(n,this._stageAspect()),o=Math.min(wv.ZOOM_MAX,Math.max(wv.ZOOM_MIN,e)),s=r.w/o,a=r.h/o,l=this._viewOr(n),c=t??l.x+l.w/2,h=i??l.y+l.h/2,d=this._clampView({x:c-s/2,y:h-a/2,w:s,h:a},r);return!(this._view&&Math.abs(this._zoom-o)<1e-9&&Math.abs(this._view.x-d.x)<1e-6&&Math.abs(this._view.y-d.y)<1e-6&&Math.abs(this._view.w-d.w)<1e-6&&Math.abs(this._view.h-d.h)<1e-6)&&("opening"===this._tool&&(this._cursorPt=null,this._clearOpeningPlacement(!1)),this._zoom=o,this._view=d,this._liveVp(),!0)}_bootWatch(){clearTimeout(this._bootTimer),this._bootStart=Date.now(),this._bootLastH=-1,this._bootLastChange=this._bootStart;const e=()=>{if(!this._booting)return;const t=Date.now(),i=this._stageEl?this._stageEl.clientHeight:0;i!==this._bootLastH&&(this._bootLastH=i,this._bootLastChange=t);const n=t-this._bootStart;var r,o,s;n>=1200||n>=700&&i>0&&t-this._bootLastChange>=250&&(r=Fl,o=this._serverCfg,s=Ll,"pending"!==r.state()||!Dl(o,s))?this._bootSettled():this._bootTimer=window.setTimeout(e,100)};this._bootTimer=window.setTimeout(e,100)}_bootSettled(){this._booting&&!this._bootSettling&&(this._bootSettling=!0,this._refitView(),this._bootSettleRaf=requestAnimationFrame(()=>{this._bootSettleRaf=0,this._finishBootSettled()}))}_finishBootSettled(){if(!this._booting)return;this._refitView(),this._booting=!1,this._bootSettling=!1;const e=this._stageEl?.clientHeight??0;!this._config?.kiosk&&e>0&&this._warmPatch({hdrH:this._hdrH,stageH:e,vp:this._warmViewportState()},!0),this._bootFading=!0,this._bootTimer=window.setTimeout(()=>{this._bootFading=!1},220),this._bootSoft=!0,clearTimeout(this._bootSoftTimer),this._bootSoftTimer=window.setTimeout(()=>{this._bootSoft=!1},rv)}_bootSoftCancel(){if(!this._bootSoft)return;clearTimeout(this._bootSoftTimer),this._bootSoft=!1;const e=function(e,t,i,n){if(!t)return null;const r=ef(e,t,i);return i||n||null===r||(t.style.height=`calc(100dvh - ${r}px)`),t.classList.remove("hpsettle"),t.getBoundingClientRect(),t.clientWidth<=0||t.clientHeight<=0?null:{headerHeight:r,size:[t.clientWidth,t.clientHeight]}}(this.renderRoot,this._stageEl,this.panelHost,this._kiosk);if(!e)return;null!==e.headerHeight&&(this._hdrH=e.headerHeight),this._refitRaf&&(cancelAnimationFrame(this._refitRaf),this._refitRaf=0),this._pendingRefitSize=null,this._lastValidStageSize=e.size;const t=this._view;t&&this._applyView(this._zoom,t.x+t.w/2,t.y+t.h/2)}_beginResumeSettle(){this._booting||this._resumeSettling||(this._modeTransitionPreparing?this._modeTransitionForceAtomic=!0:this._cancelModeTransition(!0),this._viewportInvalidAt=0,this._beginContinuityCandidate("warm-resume",!1),this._loading?this.requestUpdate():this._loadFromServer())}_refitView(){if(this._modeTransitionBusy||this._warmModeRequest)return;const e=this._stageEl;if(!e||"visible"!==document.visibilityState||e.clientWidth<=0||e.clientHeight<=0)return this._cancelCameraTransition(!1),void(this._viewportInvalidAt||(this._viewportInvalidAt=Date.now()));const t=[e.clientWidth,e.clientHeight];if(this._bootSoft&&this._warmVp)return this._lastValidStageSize=t,void(this._pendingRefitSize=null);const i=this._lastValidStageSize,n=!!i&&Math.abs(i[0]-t[0])<=.5&&Math.abs(i[1]-t[1])<=.5,r=this._viewportInvalidAt?Date.now()-this._viewportInvalidAt:0;if(this._viewportInvalidAt=0,n)this._pendingRefitSize=null;else{if(this._cancelCameraTransition(!1),!i)return this._lastValidStageSize=t,void(this._roomFocus?.spaceId===this._space?this._fitRoom(this._roomFocus.roomId,!1):this._view||this._applyView(this._zoom));this._pendingRefitSize=t,this._refitRaf||(this._refitRaf=requestAnimationFrame(()=>{this._refitRaf=0;const e=this._pendingRefitSize;this._pendingRefitSize=null;const t=this._stageEl;if(!e||!t||t.clientWidth<=0||t.clientHeight<=0)return;if(Math.abs(t.clientWidth-e[0])>.5||Math.abs(t.clientHeight-e[1])>.5)return void this._refitView();const i=this._lastValidStageSize;if(i&&Math.abs(i[0]-e[0])<=.5&&Math.abs(i[1]-e[1])<=.5)return;this._lastValidStageSize=e;const n=this._view;r>=nc?this._beginContinuityCandidate("stage-size-restored",!0,"stage-size"):this._continuity.hasCompleteFrame&&this._beginContinuityCandidate("stage-resize",!0,"stage-size"),this._roomFocus?.spaceId!==this._space?this._applyView(this._zoom,n?n.x+n.w/2:void 0,n?n.y+n.h/2:void 0):this._fitRoom(this._roomFocus.roomId,!1)}))}}_cameraTargetAt(e,t,i,n=!1){const r=this._stageEl;if(!r||r.clientWidth<=0||r.clientHeight<=0)return null;const o=Oi(this._baseVb(),this._stageAspect()),s=Math.min(wv.ZOOM_MAX,Math.max(wv.ZOOM_MIN,i)),a=function(e,t,i,n,r,o,s){if(!Kg(e)||!Kg({zoom:t,viewBox:i})||!Vg(n)||n<=0||!Vg(r)||r<=0||!Vg(o)||!Vg(s))return null;const a=o/n,l=s/r,c=e.viewBox.x+a*e.viewBox.w,h=e.viewBox.y+l*e.viewBox.h,d=i.w/t,u=i.h/t;return{zoom:t,viewBox:{x:c-a*d,y:h-l*u,w:d,h:u}}}(n&&this._cameraTransition.target||this._cameraState(),s,o,r.clientWidth,r.clientHeight,e,t);return a?(a.viewBox=this._clampView(a.viewBox,o),{target:a,fit:o}):null}_zoomAt(e,t,i){this._clearRoomFocus(),this._cancelCameraTransition(!1);const n=this._cameraTargetAt(e,t,i);n&&("opening"===this._tool&&(this._cursorPt=null,this._clearOpeningPlacement(!1)),this._zoom=n.target.zoom,this._view={...n.target.viewBox},this._liveVp())}_onWheel(e){this._clearRoomFocus(),this._prepareCameraCommand();const t=this._stageEl;if(!t)return;e.preventDefault();const i=t.getBoundingClientRect(),n=e.deltaY<0?1.15:1/1.15,r=this._cameraTransition.target?.zoom??this._zoom,o=this._cameraTargetAt(e.clientX-i.left,e.clientY-i.top,r*n,!0);o&&this._startCameraTransition(o.target,o.fit,"wheel",160)}_stepZoom(e){this._clearRoomFocus(),this._prepareCameraCommand();const t=this._stageEl;if(!t)return;const i=this._cameraTransition.target?.zoom??this._zoom,n=this._cameraTargetAt(t.clientWidth/2,t.clientHeight/2,i*(e>0?1.4:1/1.4),!0);n&&this._startCameraTransition(n.target,n.fit,"button",180)}_resetZoom(e="fit"){this._clearRoomFocus(),this._prepareCameraCommand();const t=Oi(this._baseVb(),this._stageAspect());this._startCameraTransition({zoom:1,viewBox:{...t}},t,e,220)}_saveZoom(){if("view"===this._mode){this._zoomBySpace={...this._zoomBySpace,[this._space]:this._zoom};try{localStorage.setItem(hv,JSON.stringify(this._zoomBySpace))}catch{}}}_restoreZoom(){this._clearRoomFocus(!0),this._cancelCameraTransition(!1);const e=this._zoomBySpace[this._space]||1;this._zoom=e;const t=this._stageEl;if(t&&t.clientHeight){const t=this._baseVb();return this._applyView(e,t[0]+t[2]/2,t[1]+t[3]/2),void this.requestUpdate()}this._view=null,requestAnimationFrame(()=>{if(!this._stageEl)return;const t=this._baseVb();this._applyView(e,t[0]+t[2]/2,t[1]+t[3]/2),this.requestUpdate()})}_stagePointerDown(e){this._bootSoftCancel();const t=e.isPrimary&&0===e.button&&"view"===this._mode?gf(e.composedPath()):null;if(this._roomPointer=t?{pointerId:e.pointerId,spaceId:this._space,roomId:t}:null,this._doubleFit.pointerDown(e,this._space,this._doubleFitEnabled),this._cancelCameraTransition(!1,!0),this._vacFit)return;if(this._kiosk&&(this._cyclePausedUntil=Date.now()+6e4,0===this._pointers.size?(this._swipeStart={x:e.clientX,y:e.clientY,id:e.pointerId},e.target.closest?.(".dev, .roomlabel, .oplock")||(clearTimeout(this._kioskHoldTimer),this._kioskHoldTimer=window.setTimeout(()=>{this._roomPointer=null,this._doubleFit.clear(),this._kioskDialog=!0,this._swipeStart=null},3e3))):(this._swipeStart=null,clearTimeout(this._kioskHoldTimer))),this._drag||this._deviceDrag)return;if(this._markup&&e.target.closest?.(".roomlabel, .rlhandle, .rszhandle, .dev, .oplock, .op-hit, button"))return;if("devices"===this._mode&&e.target.closest(".dev"))return;if("decor"===this._mode&&this._decorPointerDown(e))return;this._pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});const i=this._viewOr(this._baseVb());if(1===this._pointers.size)this._panStart={sx:e.clientX,sy:e.clientY,vx:i.x,vy:i.y},this._panLock=null,this._suppressClick=!1;else if(2===this._pointers.size){this._clearRoomFocus(!0),"opening"===this._tool?(this._cursorPt=null,this._clearOpeningPlacement(!1)):"draw"===this._tool&&this._clearPlanSnapHover();const e=[...this._pointers.values()],t=Math.hypot(e[0].x-e[1].x,e[0].y-e[1].y);this._pinchStart={dist:t,zoom:this._zoom},this._panStart=null,this._panLock=null}}get _swipeZone(){return!this._hasFixedFloor&&this._kiosk&&this._zoom<=1.001&&this._model.length>1}_stagePointerMove(e){if(this._physicalRotate?.pid!==e.pointerId)if(this._physicalDrag?.pid!==e.pointerId)if(this._dtDrag?.pid!==e.pointerId)if(this._bdDrag?.pid!==e.pointerId){if(this._decorDraft?.pid===e.pointerId){const t=this._decorDraft;let i=this._decorSnap(this._svgPoint(e),e.pointerType);if(e.shiftKey&&("rect"===t.kind||"ellipse"===t.kind)){const e=i[0]-t.a[0],n=i[1]-t.a[1],r=Math.max(Math.abs(e),Math.abs(n));i=this._snap([t.a[0]+(e<0?-r:r),t.a[1]+(n<0?-r:r)])}return void(this._decorDraft={...t,b:i})}if(this._decorMove?.pid!==e.pointerId){if("decor"!==this._mode||"furniture"!==this._decorTool&&"image"!==this._decorTool||!this._editorRuntime||(this._notePointer(e),!this._editorRuntime._furnPointerMove(e,this._pointerModality.hoverEnabled)))if(this._pointers.has(e.pointerId)){if(this._pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this._markup&&1===this._pointers.size&&this._markupMove(e),this._pinchStart&&this._pointers.size>=2){this._clearRoomFocus(!0),"opening"===this._tool?(this._cursorPt=null,this._clearOpeningPlacement(!1)):"draw"===this._tool&&this._clearPlanSnapHover();const e=[...this._pointers.values()],t=Math.hypot(e[0].x-e[1].x,e[0].y-e[1].y)/(this._pinchStart.dist||1),i=this._stageEl.getBoundingClientRect(),n=(e[0].x+e[1].x)/2-i.left,r=(e[0].y+e[1].y)/2-i.top;this._zoomAt(n,r,this._pinchStart.zoom*t),this._viewportGestureDirty=!0,this._suppressClick=!0,this._saveZoom()}else if(this._panStart){const t=e.clientX-this._panStart.sx,i=e.clientY-this._panStart.sy;Math.abs(t)+Math.abs(i)>4&&(this._roomPointer=null,this._doubleFit.clear(),this._suppressClick=!0,clearTimeout(this._holdTimer),"opening"===this._tool?(this._cursorPt=null,this._clearOpeningPlacement(!1)):"draw"===this._tool&&this._clearPlanSnapHover()),null===this._panLock&&Math.abs(t)+Math.abs(i)>8&&(this._panLock=this._swipeZone&&Math.abs(t)>1.5*Math.abs(i)?"swipe":"pan","pan"===this._panLock&&this._clearRoomFocus());const n=this._stageEl;if("pan"===this._panLock&&n){const e=this._baseVb(),r=this._viewOr(e),o=Oi(e,this._stageAspect());this._view=this._clampView({x:this._panStart.vx-t/(n.clientWidth||1)*r.w,y:this._panStart.vy-i/(n.clientHeight||1)*r.h,w:r.w,h:r.h},o),this._viewportGestureDirty=!0,this._liveVp()}}}else this._markupMove(e)}else this._decorMoveUpdate(e)}else this._bdMove(e);else this._dtMove(e);else this._physicalMove(e);else this._physicalRotateMove(e)}_stagePointerLeave(e){this._editorRuntime?._cancelPointerMove("markup-hover"),"decor"===this._mode&&this._editorRuntime?._furnPointerLeave(e),this._markup&&("opening"===this._tool?(this._cursorPt=null,this._clearOpeningPlacement(!1)):"draw"===this._tool&&this._clearPlanSnapHover())}_stagePointerUp(e){this._deviceHits.release(e.pointerId),this._flushHa(),this._editorRuntime?._cancelPointerMove("markup-hover");const t=(i=this._roomPointer,n=e.pointerId,r=this._space,o=this._roomPointer&&"view"===this._mode?gf(e.composedPath()):null,s=this._suppressClick||!!this._pinchStart||null!==this._panLock||this._holdFired||this._touchSequenceMultitouch,!i||s||i.pointerId!==n||i.spaceId!==r||i.roomId!==o?null:i.roomId);var i,n,r,o,s;this._roomPointer?.pointerId===e.pointerId&&(this._roomPointer=null);if(this._doubleFit.pointerUp(e,this._space,this._doubleFitEnabled,this._suppressClick||!!this._pinchStart||null!==this._panLock||this._holdFired)&&this._fitAll("double-tap"),this._kiosk){clearTimeout(this._kioskHoldTimer);const i=this._swipeStart;if(this._swipeStart=null,!t&&i&&i.id===e.pointerId){const t=e.clientX-i.x,n=e.clientY-i.y,r="pan"===this._panLock?null:function(e,t,i,n,r,o=60){if(i>1.001||n.length<2)return null;if(Math.abs(e)e.id),this._space);r&&this._slideTo(r,t<0?"left":"right")&&(this._saveNav(),this._suppressClick=!0,setTimeout(()=>this._suppressClick=!1,0),this._showKioskDots())}}this._physicalDrag?.pid!==e.pointerId?this._physicalRotate?.pid!==e.pointerId?this._dtDrag?.pid!==e.pointerId?this._bdDrag?.pid!==e.pointerId?this._decorDraft?.pid!==e.pointerId?this._decorMove?.pid!==e.pointerId?this._editorRuntime?._furnPointerUp(e)||(this._pointers.delete(e.pointerId),this._pointers.size<2&&(this._pinchStart=null),0===this._pointers.size&&(this._panStart=null,this._panLock=null,this._suppressClick&&setTimeout(()=>this._suppressClick=!1,0)),this._viewportGestureDirty&&0===this._pointers.size&&!t&&(this._viewportGestureDirty=!1,this.requestUpdate()),t&&this._fitRoom(t)):this._editorRuntimeOrThrow()._dmUp():this._decorCommitDraft():this._bdUp():this._dtUp():this._physicalRotateUp(e):this._physicalUp(e)}_clickRoom(e){!this._suppressClick&&e.area&&fv("/config/areas/area/"+e.area)}_roomLabelKey(e,t){"view"!==this._mode||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),e.stopPropagation(),this._fitRoom(t))}_pointerDown(e,t){if("view"!==this._mode&&"devices"!==this._mode)return;if("view"===this._mode&&"touch"===e.pointerType&&this._touchSequenceMultitouch)return;if(t=this._deviceHits.begin(this.renderRoot,this._renderDevices,this._space,e,t),"view"===this._mode){this._holdFired=!1,clearTimeout(this._holdTimer);const i=e.pointerId,n=e.currentTarget;return void(this._holdTimer=window.setTimeout(()=>{this._holdFired=!0,this._interruptViewGesture(i,n),this._infoCard=t},600))}if("ha_disabled"===t.bindingStatus?.kind||this._devicePositionBusy)return;if(this._deviceDrag)return void(this._deviceDrag.pointerId!==e.pointerId&&this._cancelDeviceDrag());e.preventDefault();const i=this._pos(t);this._deviceDrag={id:t.id,spaceId:t.space,displayName:t.name,pointerId:e.pointerId,source:e.currentTarget,sx:e.clientX,sy:e.clientY,ox:i.x,oy:i.y,moved:!1,before:fg(this._layout,t.id),start:this._devicePlacementForCanvas(t,i.x,i.y)},yv(e),this._tip=null,this._syncLiveHover()}_pointerMove(e,t){if("view"!==this._mode&&"devices"!==this._mode)return null;if(t=this._deviceForPointerEvent(e,t),"devices"!==this._mode)return t;const i=this._deviceDrag;return i&&i.id===t.id&&i.pointerId===e.pointerId?(this._editorRuntimeOrThrow()._queuePointerMove("device",()=>this._pointerMoveNow(e,t)),t):t}_pointerMoveNow(e,t){if("devices"!==this._mode)return;const i=this._deviceDrag;if(!i||i.id!==t.id||i.pointerId!==e.pointerId)return;const n=this.renderRoot.querySelector(".stage");if(!n)return;const r=this._baseVb(),o=n.getBoundingClientRect(),s=this._viewOr(r),a=(e.clientX-i.sx)/o.width*s.w,l=(e.clientY-i.sy)/o.height*s.h;Math.abs(e.clientX-i.sx)+Math.abs(e.clientY-i.sy)>3&&(i.moved=!0,clearTimeout(this._holdTimer));const c=ol(i.ox+a),h=ol(i.oy+l);this._previewDevicePlacement(t.id,this._devicePlacementForCanvas(t,c,h))}_pointerUp(e,t){if(t=this._deviceForPointerEvent(e,t),this._deviceHits.release(e.pointerId),clearTimeout(this._holdTimer),"devices"!==this._mode)return;const i=this._deviceDrag;if(!i||i.id!==t.id||i.pointerId!==e.pointerId)return;this._editorRuntimeOrThrow()._flushPointerMove("device"),this._deviceDrag=null;const n=fg(this._layout,t.id);var r,o;i.moved&&null!==n&&(r=n,o=i.start,null===r||null===o?r!==o:r.x!==o.x||r.y!==o.y||r.s!==o.s)?(this._selId=t.id,this._suppressClick=!0,window.setTimeout(()=>{this._suppressClick=!1},0),this._devicePositionBusy=!0,this.requestUpdate(),this._persistDevicePlacement(t.id,n).then(()=>{const e=this._t("history.device_move",{name:i.displayName});this._devicePositionHistory.push({name:e,before:{deviceId:i.id,spaceId:i.spaceId,placement:i.before},after:{deviceId:i.id,spaceId:i.spaceId,placement:n}})}).catch(e=>{this._previewDevicePlacement(t.id,i.before),this._showToast(this._t("toast.pos_save_failed",{err:this._errText(e)}))}).finally(()=>{this._devicePositionBusy=!1,this.requestUpdate()})):this._previewDevicePlacement(t.id,i.before)}_pointerCancel(e,t){t=this._deviceForPointerEvent(e,t),this._deviceHits.cancel(e.pointerId),this._deviceDrag?.id===t.id&&this._deviceDrag.pointerId===e.pointerId&&this._cancelDeviceDrag()}_showToast(e){for(const e of this.renderRoot.querySelectorAll("hp-dialog"))e.closeTransientOverlays("toast");this._toast=e,clearTimeout(this._toastTimer),this._toastTimer=window.setTimeout(()=>{this._toast=""},3500)}_syncPointerHoverTargets(){const e=this._pointerModality.hoverEnabled;for(const t of this.renderRoot.querySelectorAll(pv))t.toggleAttribute("data-pointer-hover",e)}_syncPointerHoverSubtree(e){if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e,i=this._pointerModality.hoverEnabled;t.matches(pv)&&t.toggleAttribute("data-pointer-hover",i);for(const e of t.querySelectorAll(pv))e.toggleAttribute("data-pointer-hover",i)}_clearTransientHover(e=!1){e&&this._pointerModality.suspend(),this._liveRt?.clearDeviceFocus(),this._deviceHits.hover(this.renderRoot,null),this._tip&&(this._tip=null),this._hoverRoom&&(this._hoverRoom=null),this._syncLiveHover()}_notePointer(e){const t=this._pointerModality.modality,i=this._pointerModality.note(e);"touch"!==i&&"pen"!==i||t===i&&!this._tip&&!this._hoverRoom||this._clearTransientHover()}_guardTouchGesture(e){if(this._editorSecondary?.handleOutsideDismiss(e))return;if(this._touchClickGuard.handleActivation(e,this._suppressClick))return;const t=e;if(this._notePointer(t),"pointercancel"===e.type||"lostpointercapture"===e.type?this._doubleFit.clear():"pointerdown"===e.type&&this._doubleFit.clearOutside(t),"pointerdown"===e.type&&this._touchClickGuard.pointerDown(t.pointerId,t.pointerType),"touch"!==t.pointerType)return;if("pointerdown"===e.type){if(this._touchContacts.set(t.pointerId,{x:t.clientX,y:t.clientY,inStage:!!t.target?.closest?.(".stage")}),this._touchContacts.size>=2){this._deviceHits.clearPointers(),this._clearRoomFocus(!0),this._clearTransientHover(),clearTimeout(this._holdTimer),clearTimeout(this._kioskHoldTimer),this._swipeStart=null;const e=[...this._touchContacts.values()];if("view"===this._mode&&!this._vacFit&&e.every(e=>e.inStage)){this._pointers=new Map([...this._touchContacts].map(([e,t])=>[e,{x:t.x,y:t.y}]));const[t,i]=e;this._pinchStart={dist:Math.hypot(t.x-i.x,t.y-i.y),zoom:this._zoom},this._panStart=null,this._panLock=null}else this._vacFit&&(this._pointers.clear(),this._pinchStart=null,this._panStart=null,this._panLock=null)}return}if("pointermove"===e.type){const e=this._touchContacts.get(t.pointerId);if(!e)return;const i={...e,x:t.clientX,y:t.clientY};if(this._touchContacts.set(t.pointerId,i),this._touchSequenceMultitouch&&"view"===this._mode&&!this._vacFit&&this._pinchStart&&[...this._touchContacts.values()].every(e=>e.inStage)){this._pointers.set(t.pointerId,{x:t.clientX,y:t.clientY});const e=[...this._touchContacts.values()];if(e.length>=2&&this._stageEl){const[t,i]=e,n=Math.hypot(t.x-i.x,t.y-i.y)/(this._pinchStart.dist||1),r=this._stageEl.getBoundingClientRect();this._zoomAt((t.x+i.x)/2-r.left,(t.y+i.y)/2-r.top,this._pinchStart.zoom*n),this._saveZoom()}}return}if("pointerup"!==e.type&&"pointercancel"!==e.type&&"lostpointercapture"!==e.type)return;const i=this._touchClickGuard.pointerTerminal(t.pointerId,t.pointerType);if(this._clearTransientHover(),this._touchContacts.delete(t.pointerId),i){if(this._pointers.delete(t.pointerId),!this._vacFit&&this._pointers.size>=2){const[e,t]=[...this._pointers.values()];this._pinchStart={dist:Math.hypot(e.x-t.x,e.y-t.y),zoom:this._zoom}}else this._pinchStart=null;0===this._pointers.size&&(this._panStart=null,this._panLock=null)}}_showTip(e,t,i,n,r,o,s=!1){this._notePointer(e),this._pointerModality.hoverEnabled&&(this._drag||this._deviceDrag||s&&this._liveRt?.deviceFocusActive()||(this._tip={x:e.clientX,y:e.clientY,title:t,meta:i,lqi:n,temp:r,hum:o,room:s,source:"pointer"},this._syncLiveHover()))}_roomTipEnabledForPointer(e){return"view"===this._mode&&(this._notePointer(e),!!_n(this._settings)||(this._tip?.room&&(this._tip=null,this._syncLiveHover()),!1))}get _gridPitch(){return tl}get _cellCm(){const e=Number(this._curSpaceCfg?.cell_cm);return Number.isFinite(e)&&e>0?e:5}_fmtLen(e,t){const i=function(e,t,i,n){return Math.hypot(t[0]-e[0],t[1]-e[1])/i*n}(e,t,this._gridPitch,this._cellCm);return ti(i,"mi"===this.hass?.config?.unit_system?.length)}get _curSpaceCfg(){const e=this._resize?.preview;return e&&e.space===this._space?e.sp:this._serverCfg?.spaces.find(e=>e.id===this._space)}get _renderCfg(){const e=this._resize?.preview;return e&&this._serverCfg?{...this._serverCfg,spaces:this._serverCfg.spaces.map(t=>t.id===e.space?e.sp:t)}:this._serverCfg}get _spaceH(){return this._curSpaceCfg,_v}get _segments(){const e=this._curSpaceCfg,t=this._spaceH;return oi(e?.rooms||[]).map(e=>[e[0]*_v,e[1]*t,e[2]*_v,e[3]*t])}_savedNav(){if(this._hasFixedFloor)return null;try{return JSON.parse(localStorage.getItem(dv)||"null")}catch{return null}}_saveNav(){if(!this._hasFixedFloor)try{localStorage.setItem(dv,JSON.stringify({space:this._space}))}catch{}}_leaveCardRoute(){if(this._routeDepartureHandled)return;this._routeDepartureHandled=!0,this._configReloadAuthority.invalidateLifecycle(),this._summary?.leaveRoute(),this._clearRoomFocus(!0),this._cancelDangerConfirm(),"view"!==this._mode&&this._setMode("view",!1),this._pendingNavMode=null,this._geometryHistory.clear(),this._activeWallChainId=null,this._wallChainSegmentCms=[],this._closingWallCm=null,this._drawWallField=null,this._showHidden=!1,this._tapConfirm=null,this._vacCalConfirm=null,this._decorEraseConfirm=null,this._openingInfo=null,this._closeInfoCard(),this._rulesDialog=null,this._alignDialog=null,this._preflightClipboardFallback=null,this._backupImportDialog=null,this._backupExportDialog=null,this._pdfDialog=!1,this._supportDialog?.preview?.token&&this._editorRuntime?._discardSupportPreview(this._supportDialog.preview.token),this._supportDialog=null,this._settingsDialog=null,this._deviceInbox=null,this._deviceInboxReturn=null,this._markerDialog=null,this._openingDialog=null,this._physicalDialog=null,this._wallDialog=null,this._backdropDialog=null,this._decorShapeDialog=null,this._decorTextDialog=null,this._mergeDialog=null,this._roomDialog=!1,this._spaceDialog=null,this._importDialog=null;const e=this._warmSlot;e?.owner===this._warmGen&&(e.vp=this._warmViewportState(),e.dlg=null,e.frameFingerprint="",clearTimeout(e.evict),e.evict=0),this._saveNav()}_setMode(e,t=!0){return e!==this._mode&&(this._clearRoomFocus(!0),this._cancelDangerConfirm(),this._resetDeviceHitState(),this._clearTransientHover(!0)),this._warmModeRequest=0,this._editorRuntime?this._editorRuntime._setMode(e,t):"view"===e?void this._editorModeRequest++:void this._requestMode(e,t)}_primeDrawWallField(){return this._editorRuntimeOrThrow()._primeDrawWallField()}get _drawWallFieldValue(){return null===this._drawWallField?Po(15,this._imperial):this._drawWallField}get _drawWallCm(){const e=(e=>{const t=String(e??"").trim().replace(",",".");if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(t))return null;const i=Number(t);return Number.isFinite(i)?i:null})(this._drawWallFieldValue);if(null==e||e<0)return null;const t=this._imperial?2.54*e:e,i="column"===this._tool?_a:100;return t>=("column"===this._tool?1:0)&&t<=i?t:null}get _drawWallMaxCm(){return"column"===this._tool?_a:100}_showPhysicalRange(e=this._drawWallMaxCm,t=0){return this._editorRuntimeOrThrow()._showPhysicalRange(e,t)}_mergeSpacePartitions(e,t){return this._editorRuntimeOrThrow()._mergeSpacePartitions(e,t)}_finishWallChain(){return this._editorRuntimeOrThrow()._finishWallChain()}_activateMarkupTool(e){return this._editorRuntimeOrThrow()._activateMarkupTool(e)}_limitReached(e){return this._editorRuntimeOrThrow()._limitReached(e)}_svgPoint(e){return this._editorRuntimeOrThrow()._svgPoint(e)}_snap(e){return this._editorRuntimeOrThrow()._snap(e)}_snapDrawPoint(e,t=!1){return this._editorRuntimeOrThrow()._snapDrawPoint(e,t)}_planSnapOpeningCuts(e,t){return this._editorRuntimeOrThrow()._planSnapOpeningCuts(e,t)}_planSnapGeometrySnapshot(){return this._editorRuntimeOrThrow()._planSnapGeometrySnapshot()}_hiddenWallDiagnosticSnapshot(){return this._editorRuntimeOrThrow()._hiddenWallDiagnosticSnapshot()}_planStructuralGeometrySnapshot(){return this._editorRuntimeOrThrow()._planStructuralGeometrySnapshot()}_planSnapContextKey(e){return this._editorRuntimeOrThrow()._planSnapContextKey(e)}_resolvePlanDrawPoint(e,t){return this._editorRuntimeOrThrow()._resolvePlanDrawPoint(e,t)}get _activePlanSnapCandidate(){if(!this._markup||"draw"!==this._tool)return null;const e=this._planSnapHover;if(!e)return null;const t=this._planSnapGeometrySnapshot();return e.contextKey===this._planSnapContextKey(t.key)?e.candidate:null}get _activePlanSnapConflicts(){if(!this._markup||"draw"!==this._tool)return[];const e=this._planSnapHover;if(!e)return[];const t=this._planSnapGeometrySnapshot();return e.contextKey===this._planSnapContextKey(t.key)?e.conflicts:[]}_clearPlanSnapHover(e=!0){return this._editorRuntime?this._editorRuntimeOrThrow()._clearPlanSnapHover(e):(this._planSnapHover=null,void(e&&(this._cursorPt=null)))}_samePt(e,t){return _i(e,t)}_dropLegacySegments(){return this._editorRuntimeOrThrow()._dropLegacySegments()}_rollbackRejectedPhysicalWrites(e){return this._editorRuntimeOrThrow()._rollbackRejectedPhysicalWrites(e)}async _reloadRejectedPhysicalWrite(){return this._editorRuntimeOrThrow()._reloadRejectedPhysicalWrite()}get _cfgWriting(){return this._writesPending>0}async _sendConfigCandidate(e){const t=ko(e),i=await this.hass.callWS({type:"houseplan/config/set",config:t,expected_rev:this._cfgRev});this._adoption.acceptConfigWrite(t,i)}_writeConfig(){if(this._editorRuntime)return this._editorRuntime._writeConfig();this._writesPending++,this._writeChain=Hu(this._writeChain,async()=>{if(!this._serverCfg)return;const e=ko(this._serverCfg);this._adoption.stageConfigCandidate(e),await this._sendConfigCandidate(e)});return this._writeChain.finally(()=>{this._writesPending--})}_saveConfig(){this._cfgEpoch++,this._saveConfigDebounced()}_geometrySnapshotFromConfig(e,t){return this._editorRuntimeOrThrow()._geometrySnapshotFromConfig(e,t)}_geometrySnapshot(e=this._space){return this._editorRuntimeOrThrow()._geometrySnapshot(e)}_recordGeometry(e,t){return this._editorRuntimeOrThrow()._recordGeometry(e,t)}_restoreGeometryStateInConfig(e,t,i=!1){return this._editorRuntimeOrThrow()._restoreGeometryStateInConfig(e,t,i)}_restoreGeometryStateLocal(e){return this._editorRuntimeOrThrow()._restoreGeometryStateLocal(e)}_wallModelBlockerLabel(e){return this._editorRuntimeOrThrow()._wallModelBlockerLabel(e)}_hasLegacyZeroWallFields(e=this._serverCfg){return this._editorRuntimeOrThrow()._hasLegacyZeroWallFields(e)}_showWallModelMigrationBlocked(e){return this._editorRuntimeOrThrow()._showWallModelMigrationBlocked(e)}_limitSegmentsOf(e){return this._editorRuntimeOrThrow()._limitSegmentsOf(e)}_junctionLimitViolations(e,t,i,n){return this._editorRuntimeOrThrow()._junctionLimitViolations(e,t,i,n)}_junctionLimitLabel(e){return this._editorRuntimeOrThrow()._junctionLimitLabel(e)}_junctionLimitsIntroduced(e,t,i){return this._editorRuntimeOrThrow()._junctionLimitsIntroduced(e,t,i)}_commitPhysicalGeometry(e,t,i=[]){return this._editorRuntimeOrThrow()._commitPhysicalGeometry(e,t,i)}_clearGeometryGesture(){return this._editorRuntime?this._editorRuntimeOrThrow()._clearGeometryGesture():(this._path=[],this._planSnapHover=null,this._cursorPt=null,this._openingHoverCandidate=null,this._openingJambBlockCm=null,this._openingPreset=null,this._openingRebindId=null,this._mergeSel=null,this._mergeDialog=null,this._splitSel=null,this._pendingSplit=null,this._wallFaceBatch=null,this._wallRepairDiagnostic=null,this._roomDeleteDialog=null,this._wallDialog=null,this._physicalDialog=null,this._physicalSel=null,this._physicalDrag=null,this._physicalRotate=null,this._activeWallChainId=null,this._wallChainSegmentCms=[],this._closingWallCm=null,this._openingDialog=null,this._resize?.reset(),this._decorDraft=null,this._decorMove=null,this._dtDrag=null,void(this._bdDrag=null))}_stagePointerCancel(e){if(this._deviceHits.cancel(e.pointerId),this._flushHa(),this._editorRuntime?._cancelPointerMove("markup-hover"),this._roomPointer?.pointerId===e.pointerId&&(this._roomPointer=null),this._doubleFit.clear(),this._editorRuntime)return this._editorRuntime._stagePointerCancel(e);this._pointers.delete(e.pointerId),this._pointers.size<2&&(this._pinchStart=null),0===this._pointers.size&&(this._panStart=null,this._panLock=null,this._swipeStart=null),this._viewportGestureDirty&&0===this._pointers.size&&(this._viewportGestureDirty=!1,this.requestUpdate())}_applyGeometryState(e,t=!1){return this._editorRuntimeOrThrow()._applyGeometryState(e,t)}_roomAt(e){return this._editorRuntimeOrThrow()._roomAt(e)}_overlapRoom(e){return this._editorRuntimeOrThrow()._overlapRoom(e)}_pointInRoom(e,t){return t.poly?mi(e,t.poly):null!=t.x&&e[0]>=t.x&&e[0]<=t.x+t.w&&e[1]>=t.y&&e[1]<=t.y+t.h}_contourSelfIntersects(e){return this._editorRuntimeOrThrow()._contourSelfIntersects(e)}_canAppendWallPoint(){return this._editorRuntimeOrThrow()._canAppendWallPoint()}_markupClick(e){if(this._editorRuntime)return this._editorRuntime._markupClick(e)}_activeWallSourceKey(e){return this._editorRuntimeOrThrow()._activeWallSourceKey(e)}_wallGraphSources(e){return this._editorRuntimeOrThrow()._wallGraphSources(e)}_wallFaceGraph(e,t){return this._editorRuntimeOrThrow()._wallFaceGraph(e,t)}_offerWallFaces(e,t=this._path.length-2,i){return this._editorRuntimeOrThrow()._offerWallFaces(e,t,i)}_beginWallFaceBatch(e){return this._editorRuntimeOrThrow()._beginWallFaceBatch(e)}_offerExistingWallFace(e){return this._editorRuntimeOrThrow()._offerExistingWallFace(e)}_columnClick(e){return this._editorRuntimeOrThrow()._columnClick(e)}_openPhysicalDialog(e,t){return this._editorRuntimeOrThrow()._openPhysicalDialog(e,t)}_physicalDown(e,t,i){return this._editorRuntimeOrThrow()._physicalDown(e,t,i)}_clampPhysicalDelta(e,t,i){return this._editorRuntimeOrThrow()._clampPhysicalDelta(e,t,i)}_physicalMove(e){return this._editorRuntimeOrThrow()._physicalMove(e)}_physicalUp(e){return this._editorRuntimeOrThrow()._physicalUp(e)}_registerPhysicalTap(e,t){return this._editorRuntimeOrThrow()._registerPhysicalTap(e,t)}_cancelPhysicalGesture(){return this._editorRuntimeOrThrow()._cancelPhysicalGesture()}_physicalRotateDown(e,t){return this._editorRuntimeOrThrow()._physicalRotateDown(e,t)}_physicalRotateMove(e){return this._editorRuntimeOrThrow()._physicalRotateMove(e)}_physicalRotateUp(e){return this._editorRuntimeOrThrow()._physicalRotateUp(e)}_rszRooms(){return this._editorRuntimeOrThrow()._rszRooms()}_rszOpenings(){return this._editorRuntimeOrThrow()._rszOpenings()}_rszObstacles(){return this._editorRuntimeOrThrow()._rszObstacles()}_rszOptsFor(e,t){return this._editorRuntimeOrThrow()._rszOptsFor(e,t)}_rszResolution(e,t,i){return this._editorRuntimeOrThrow()._rszResolution(e,t,i)}_rszSnapshot(){return this._editorRuntimeOrThrow()._rszSnapshot()}_rszResetController(){return this._editorRuntimeOrThrow()._rszResetController()}_rszProjectPreview(e,t,i,n,r){return this._editorRuntimeOrThrow()._rszProjectPreview(e,t,i,n,r)}_rszAcceptPreview(e,t){return this._editorRuntimeOrThrow()._rszAcceptPreview(e,t)}_rszSpaceCandidateGeometry(e,t){return this._editorRuntimeOrThrow()._rszSpaceCandidateGeometry(e,t)}_rszSpaceCandidateRenderable(e,t){return this._editorRuntimeOrThrow()._rszSpaceCandidateRenderable(e,t)}_rszCandidateRenderable(e){return this._editorRuntimeOrThrow()._rszCandidateRenderable(e)}_rszEdgeDown(e,t,i){return this._editorRuntimeOrThrow()._rszEdgeDown(e,t,i)}_rszReasonText(e){return this._editorRuntimeOrThrow()._rszReasonText(e)}_rszDisabledActivate(e,t){return this._editorRuntimeOrThrow()._rszDisabledActivate(e,t)}_rszDisabledKey(e,t){return this._editorRuntimeOrThrow()._rszDisabledKey(e,t)}_rszMove(e){return this._editorRuntimeOrThrow()._rszMove(e)}_rszUp(e){return this._editorRuntimeOrThrow()._rszUp(e)}_rszCancelDrag(e){return this._editorRuntimeOrThrow()._rszCancelDrag(e)}_rszPointerCancel(e){return this._editorRuntimeOrThrow()._rszPointerCancel(e)}_rszEdgeLabels(e,t,i=this._resize?.rooms){return this._editorRuntimeOrThrow()._rszEdgeLabels(e,t,i)}_rszInnerSpanCms(e,t,i){return this._editorRuntimeOrThrow()._rszInnerSpanCms(e,t,i)}_renderResizeMeasurements(){return this._editorRuntimeOrThrow()._renderResizeMeasurements()}_renderResizeLayer(e,t){return this._editorRuntimeOrThrow()._renderResizeLayer(e,t)}get _openingsR(){const e=this._curSpaceCfg,t=this._spaceH,i=this._spaceModel();return i?(e?.openings||[]).flatMap(e=>{const n={...e,rx:e.x*_v,ry:e.y*t,rlen:e.length*_v};if(!e.host||"wall"===e.host.kind)return[n];const r=Ju(e,i.partitions,_v,this._cellCm,this._gridPitch);if(!r.resolved)return"plan"===this._mode?[{...n,orphanReason:r.reason||"invalid-host"}]:[];let[o,s]=r.resolved.center;const a=this._physicalDrag;return a?.moved&&"partition"===a.kind&&a.id===e.host.id&&(o+=a.delta[0],s+=a.delta[1]),[{...e,rx:o,ry:s,rlen:r.resolved.length,angle:r.resolved.angle,partitionHost:r.resolved}]}):[]}_partitionOpeningCuts(e=this._spaceModel(),t=()=>!0){if(!e)return[];return G_(U_(this._curSpaceCfg?.id===e.id?this._curSpaceCfg:null,e,this._cellCm,this._gridPitch,_v),t)}_roomWallOpeningInputs(e=this._openingsR,t=this._spaceModel()){if(!t)return[];const i=this._openCuts();return V_(e,t,this._spaceWalls,i,this._wallKeyPitch,this._cellCm,this._gridPitch,_v)}_openingFace(e,t,i){return e.partitionHost?ip(e.partitionHost,i):ha(t,{x:e.rx,y:e.ry,angle:e.angle,length:e.rlen,flip_v:i})}_cmToUnits(e){return e/this._cellCm*this._gridPitch}get _decorList(){const e=this._curSpaceCfg;return Array.isArray(e?.decor)?e.decor:[]}get _decorH(){return _v}_decorResolvedStyle(e){return function(e,t,i,n=$r){const r="rect"===e?.kind||"ellipse"===e?.kind,o=e,s=Kt(o?.color,n.color);return{color:s,opacity:Mr(o?.opacity,n.opacity),widthCm:Pr(e,t,i,n.widthCm),fill:!!r&&!0===o?.fill,fillColor:Kt(o?.fill_color,o?.fill?s:n.fillColor),fillOpacity:r&&o?.fill?Mr(o?.fill_opacity,.25):n.fillOpacity}}(e,this._cellCm,this._gridPitch,$r)}_decorWidthUnits(e){return((e,t,i,n=$r.widthCm)=>{const r=Number(e?.width_cm);if(Number.isFinite(r)&&r>0)return Dr(r,t,i);const o=Number(e?.width);return Number.isFinite(o)&&o>0?o:Dr(n,t,i)})(e,this._cellCm,this._gridPitch,$r.widthCm)}_decorTextSizeCm(e){if("text"===e?.kind){const t=Number(e.size_cm);return Number.isFinite(t)&&t>0?t:Ar(20*tn(e),this._cellCm,this._gridPitch)}return Ar(20,this._cellCm,this._gridPitch)}_decorTextUnits(e){if("text"!==e.kind)return 20;const t=Number(e.size_cm);return Number.isFinite(t)&&t>0?Dr(t,this._cellCm,this._gridPitch):20*tn(e)}_decorSmallField(e){return Math.round(100*(this._imperial?e/2.54:e))/100}_decorSmallCm(e){const t=this._imperial?2.54*e:e;return Number.isFinite(t)?Math.max(.1,Math.min(100,t)):.1}_decorTextCm(e){const t=this._imperial?2.54*e:e;return Number.isFinite(t)?Math.max(.1,Math.min(2e3,t)):.1}_decorLargeField(e){return Math.round(100*(this._imperial?e/30.48:e/100))/100}_decorLargeCm(e){const t=this._imperial?30.48*e:100*e;return Number.isFinite(t)?Math.max(.1,Math.min(Ja*this._cellCm,t)):.1}_angleField(e){const t=Number(e);return Number.isFinite(t)?String(Number(t.toFixed(3))):"0"}_decorBoxOf(e){return"rect"!==e.kind&&"ellipse"!==e.kind&&"furniture"!==e.kind&&"image"!==e.kind?null:{x:e.x*_v,y:e.y*this._decorH,w:e.w*_v,h:e.h*this._decorH,angle:Rr(e.angle)||void 0}}_decorSnapGeometry(e){return this._editorRuntimeOrThrow()._decorSnapGeometry(e)}_decorSnap(e,t="mouse",i){return this._editorRuntimeOrThrow()._decorSnap(e,t,i)}_replaceDecor(e,t){return this._editorRuntimeOrThrow()._replaceDecor(e,t)}_cancelDecorGesture(){return this._editorRuntimeOrThrow()._cancelDecorGesture()}_decorPointerDown(e){return this._editorRuntimeOrThrow()._decorPointerDown(e)}_decorCommitDraft(){return this._editorRuntimeOrThrow()._decorCommitDraft()}_decorShapeDown(e,t){if(this._editorRuntime)return this._editorRuntime._decorShapeDown(e,t)}_decorMoveUpdate(e){this._editorRuntimeOrThrow()._queuePointerMove("decor-move",()=>this._editorRuntimeOrThrow()._decorMoveUpdate(e))}_decorNudge(e,t){if("decor"!==this._mode||"select"!==this._decorTool||!this._decorSel||this._decorDraft||this._decorMove||this._dtDrag||this._bdDrag)return!1;const i=this._decorList.find(e=>e.id===this._decorSel),n=this._curSpaceCfg;if(!i||!n)return!1;const r=function(e,t,i,n,r,o){if(!([t,i,n,r,o].every(Number.isFinite)&&r>0))return null;let s;if(s="line"===e.kind?[[e.x1,e.y1],[e.x2,e.y2]]:"text"===e.kind?[[e.x,e.y]]:Ir(e),!s.length||s.some(e=>!e.slice(0,2).every(Number.isFinite)))return null;const a=s.map(e=>e[0]),l=s.map(e=>e[1]),c=Math.min(...a),h=Math.max(...a),d=Math.min(...l),u=Math.max(...l),p=t/n,_=i/r,m=p>0?Math.min(p,Math.max(0,o-h)):Math.max(p,Math.min(0,-o-c)),g=_>0?Math.min(_,Math.max(0,o-u)):Math.max(_,Math.min(0,-o-d));return m||g?"line"===e.kind?{...e,x1:e.x1+m,y1:e.y1+g,x2:e.x2+m,y2:e.y2+g}:{...e,x:e.x+m,y:e.y+g}:null}(i,e,t,_v,this._decorH,Ja);if(!r)return!1;const o=this._geometrySnapshot();return n.decor=this._decorList.map(e=>e.id===i.id?r:e),this._recordGeometry(this._t("history.decor_move"),o),this._saveConfig(),this.requestUpdate(),!0}_decorShapeDbl(e,t){if(this._editorRuntime)return this._editorRuntime._decorShapeDbl(e,t)}_openDecorProperties(e){return this._editorRuntimeOrThrow()._openDecorProperties(e)}_decorOpenText(e){return this._editorRuntimeOrThrow()._decorOpenText(e)}_decorRememberTextSelection(e){return this._editorRuntimeOrThrow()._decorRememberTextSelection(e)}_decorInsertLiveVariable(e){return this._editorRuntimeOrThrow()._decorInsertLiveVariable(e)}_decorSaveText(){return this._editorRuntimeOrThrow()._decorSaveText()}_decorSaveShape(){return this._editorRuntimeOrThrow()._decorSaveShape()}get _dtSel(){return"decor"===this._mode&&"select"===this._decorTool&&this._decorSel&&this._decorList.find(e=>e.id===this._decorSel)||null}_dtPivot(e){return this._editorRuntimeOrThrow()._dtPivot(e)}_dtApply(e,t){return this._editorRuntimeOrThrow()._dtApply(e,t)}_dtStart(e,t,i,n){return this._editorRuntimeOrThrow()._dtStart(e,t,i,n)}_dtMove(e){this._editorRuntimeOrThrow()._queuePointerMove("decor-transform",()=>this._editorRuntimeOrThrow()._dtMove(e))}_dtUp(){return this._editorRuntimeOrThrow()._flushPointerMove("decor-transform"),this._editorRuntimeOrThrow()._dtUp()}_dtMeasure(){return this._editorRuntimeOrThrow()._dtMeasure()}_deleteDecor(e){return this._editorRuntimeOrThrow()._deleteDecor(e)}_decorDeleteSel(){return this._editorRuntimeOrThrow()._decorDeleteSel()}_confirmDecorErase(){return this._editorRuntimeOrThrow()._confirmDecorErase()}get _bdBase(){const e=this._curSpaceCfg;return e?.plan_url?{...Ga(e.plan_aspect,_v)}:null}get _bdRect(){const e=this._curSpaceCfg;return e?.plan_url?Ya(e,_v):null}get _bdParams(){const e=this._curSpaceCfg,t=Number(e?.plan_x),i=Number(e?.plan_y),n=Number(e?.plan_scale),r=Number(e?.plan_scale_x),o=Number(e?.plan_scale_y),s=Number.isFinite(n)&&n>0?n:1;return{dx:Number.isFinite(t)?t:0,dy:Number.isFinite(i)?i:0,sx:Number.isFinite(r)&&r>0?r:s,sy:Number.isFinite(o)&&o>0?o:s,angle:Rr(e?.plan_angle)}}_openBackdropDialog(e){if(this._editorRuntime)return this._editorRuntime._openBackdropDialog(e)}_saveBackdropDialog(){return this._editorRuntimeOrThrow()._saveBackdropDialog()}get _bdActive(){return"decor"===this._mode&&!!this._bdRect&&"backdrop"===this._decorTool}get _bdMovable(){return"decor"===this._mode&&"backdrop"===this._decorTool&&!!this._bdRect}_bdApply(e,t,i,n,r){return this._editorRuntimeOrThrow()._bdApply(e,t,i,n,r)}_bdStart(e,t,i=!1){return this._editorRuntimeOrThrow()._bdStart(e,t,i)}_bdMove(e){return this._editorRuntimeOrThrow()._bdMove(e)}get _bdMoved(){if("decor"!==this._mode||!this._bdRect)return!1;const e=this._bdParams;return 0!==e.dx||0!==e.dy||1!==e.sx||1!==e.sy||0!==e.angle}_bdReset(){return this._editorRuntimeOrThrow()._bdReset()}_bdUp(){return this._editorRuntimeOrThrow()._bdUp()}get _bdLive(){if(!this._bdDrag)return null;const e=this._bdRect;return e?{x:e.x+e.w/2,y:e.y+e.h/2,text:`${this._fmtLen([0,0],[e.w,0])} × ${this._fmtLen([0,0],[0,e.h])}`}:null}_renderBackdropFrame(e){return this._editorRuntime?this._editorRuntimeOrThrow()._renderBackdropFrame(e):G}_renderTextFrame(e){const t=this._dtSel;if(!t)return G;if("text"===t.kind&&this._dtBox?.id!==t.id)return G;const i="text"===t.kind?this._dtBox:this._decorBoxOf(t);if("line"!==t.kind&&!i)return G;const n=.018*Math.max(e.w,e.h),r=n/4;if("line"===t.kind){const e=[t.x1*_v,t.y1*this._decorH],i=[t.x2*_v,t.y2*this._decorH];return W` - - ${[e,i].map((e,t)=>W`this._dtStart(e,"scale",void 0,t)}> - `)} - `}if(!i)return G;const[o,s]=this._dtPivot(t),a=Number(t.angle)||0,l=[[-1,-1,"nwse"],[1,-1,"nesw"],[1,1,"nwse"],[-1,1,"nesw"]],c=2.2*n,h="furniture"===t.kind||"image"===t.kind,d=h?[[0,-1,"ns"],[1,0,"ew"],[0,1,"ns"],[-1,0,"ew"]]:[];return W` - - - this._dtStart(e,"rotate")}> - - ${bv.map(e=>"edges"===e?d.map(([e,t,o])=>{const s=e<0?i.x:e>0?i.x+i.w:i.x+i.w/2,a=t<0?i.y:t>0?i.y+i.h:i.y+i.h/2;return W`this._dtStart(i,"scale",[e,t])}> - `}):l.map(([e,t,o])=>W`this._dtStart(i,"scale",[e,t])}>`))} - `}_renderDecorLayer(e,t=this._viewOr(this._baseVb())){const i=_v,n=this._decorH,r="decor"===this._mode,o=r&&"erase"===this._decorTool,s=this._stageEl,a="iso"===this._renderProjection?1:function(e,t,i,n){const r=Number(e),o=Number(t),s=Number(i),a=Number(n);if(![r,o,s,a].every(e=>Number.isFinite(e)&&e>0))return 1;const l=Math.min(r/s,o/a);return Number.isFinite(l)&&l>0?l:1}(s?.clientWidth,s?.clientHeight,t.w,t.h),l=this._decorList.filter(t=>void 0===e||t.id===e).map(e=>{const t="dshape"+(r&&this._decorSel===e.id?" dsel":""),s=this._decorResolvedStyle(e),l=this._decorWidthUnits(e),c=t=>this._decorShapeDown(t,e),h=t=>this._decorShapeDbl(t,e);if("line"===e.kind)return W` - ${r&&"select"===this._decorTool?W``:G} - ${o?W``:G}`;if("rect"===e.kind){const r=(e.x+e.w/2)*i,a=(e.y+e.h/2)*n,d=Rr(e.angle);return W` - ${o?W``:G}`}if("ellipse"===e.kind){const r=(e.x+e.w/2)*i,a=(e.y+e.h/2)*n,d=Rr(e.angle);return W` - ${o?W``:G}`}if("image"===e.kind){const s=hm(e,i,n);if(!s)return G;const[a,l,d,u,p,_]=s,m=this._decorAssets.get(e.asset_id);if(!m)return r&&this._editorRuntime?this._editorRuntime._renderMissingDecorImage(e,t,_,a,l,d,u,c,h):G;const g=this._display(m.url);return g?W`this._signer.markLoaded(this._renderPlanHass,m.url,g)} - @pointerdown=${c} @dblclick=${h}> - ${o?W``:G}`:G}if("furniture"===e.kind){const d=Yl(e.symbol,this);if(!d)return G;const u=ec(e,i,n,d.viewW,d.viewH),p=Xl(l,a),_=Xl(l+Dr(20,this._cellCm,this._gridPitch),a);return W` - ${r&&"select"===this._decorTool?W``:G} - ${o?W``:G}`}if("text"===e.kind){const r=this._decorTextUnits(e),o=this._renderDeviceSnapshot?.facts.get(`decor:${this._space}:${e.id}`),a=function(e){return String(e??"").replace(/\r\n?/g,"\n").split("\n")}("string"==typeof o?o:Qi(e.text,e,this._renderPlanHass,e=>this._renderEntityAvailable(e))),l=e.x*i,d=e.y*n,u=Number(e.angle)||0,p=d-(a.length-1)*r*1.2/2;return W`${a.map((e,t)=>W`${e}`)}`}return G});let c=G;const h=this._decorDraft;if(h){const e=this._decorStyle,t=Dr(e.widthCm,this._cellCm,this._gridPitch);if("line"===h.kind)c=W``;else{const i=Math.min(h.a[0],h.b[0]),n=Math.min(h.a[1],h.b[1]),r=Math.abs(h.b[0]-h.a[0]),o=Math.abs(h.b[1]-h.a[1]);c="rect"===h.kind?W``:W``}}return W`${l}${c}${this._editorRuntime?._renderFurniturePlacementPreview(a)??G}${this._editorRuntime?._renderDecorImagePlacementPreview()??G}`}get _editorToolbarGroups(){return"plan"!==this._mode?[]:[{id:"opening",label:this._t("markup.opening"),icon:"mdi:door",activeItemId:"opening"===this._tool?this._openingPreset?.type:void 0,items:[{id:"window",label:this._t("opening.window"),icon:"mdi:window-closed-variant",role:"tool",invoke:()=>this._activateOpeningPlacement("window")},{id:"door",label:this._t("opening.door"),icon:"mdi:door-open",role:"tool",invoke:()=>this._activateOpeningPlacement("door")},{id:"passage",label:this._t("opening.passage"),icon:"mdi:arch",role:"tool",invoke:()=>this._activateOpeningPlacement("passage")},{id:"gate",label:this._t("opening.gate"),icon:"mdi:gate",role:"tool",invoke:()=>this._activateOpeningPlacement("gate")}]}]}_renderEditorGroupLauncher(e){return this._editorRuntimeOrThrow()._renderEditorGroupLauncher(e)}get _editorSecondaryContextId(){const e=`editor:${this._mode}:${this._space}:${this._cfgEpoch}`,t=this._editorSecondary?.activeGroup(this._editorToolbarGroups);if(t)return`${e}:group:${t.id}:${this._editorSecondary?.groupGeneration}`;if("plan"===this._mode){const t=this._physicalSel;return t?`${e}:selection:${t.kind}:${t.id}`:`${e}:tool:${this._tool}:${this._path.length}`}return"decor"===this._mode?"furniture"===this._decorTool?`${e}:palette:furniture:${this._furnPalette?.symbol||"none"}`:"image"===this._decorTool?`${e}:palette:image:${this._decorImagePalette?.asset_id||"none"}`:"select"===this._decorTool&&this._decorSel?`${e}:selection:decor:${this._decorSel}`:`${e}:tool:${this._decorTool}:${this._bdMoved?1:0}:${this._bdDrag?1:0}`:`${e}:none`}_runEditorContext(e,t){return this._editorRuntimeOrThrow()._runEditorContext(e,t)}_renderEditorGroupModel(e){return this._editorRuntimeOrThrow()._renderEditorGroupModel(e)}_renderDrawWallControl(){return this._editorRuntimeOrThrow()._renderDrawWallControl()}_renderPlanSecondary(){return this._editorRuntimeOrThrow()._renderPlanSecondary()}_renderDecorSecondary(){return this._editorRuntimeOrThrow()._renderDecorSecondary()}_withBackdropReset(e){return this._editorRuntimeOrThrow()._withBackdropReset(e)}get _editorSecondaryDialogBlocked(){return!!(this._dangerConfirm||this._tapConfirm||this._vacCalConfirm||this._roomDialog||this._mergeDialog||this._openingDialog||this._physicalDialog||this._openingInfo||this._decorTextDialog||this._decorShapeDialog||this._backdropDialog||this._decorEraseConfirm||this._spaceDialog||this._markerDialog||this._deviceInbox||this._infoCard||this._rulesDialog||this._settingsDialog||this._supportDialog||this._alignDialog||this._importDialog||this._kioskDialog||this._summary?.blocksOtherDialogs()||this._backupExportDialog||this._backupImportDialog||this._wallDialog)}_renderEditorSecondary(){return this._editorRuntimeOrThrow()._renderEditorSecondary()}_renderDecorBar(){return this._editorRuntimeOrThrow()._renderDecorBar()}_renderDecorEraseConfirm(){return this._editorRuntimeOrThrow()._renderDecorEraseConfirm()}_renderDecorTextDialog(){return this._editorRuntimeOrThrow()._renderDecorTextDialog()}_renderDecorShapeDialog(){return this._editorRuntimeOrThrow()._renderDecorShapeDialog()}_renderBackdropDialog(){return this._editorRuntimeOrThrow()._renderBackdropDialog()}_cssPxToRender(e){return this._editorRuntimeOrThrow()._cssPxToRender(e)}_renderZeroWalls(e){if(e&&!e.showBorders&&!this._editing)return W``;const t=this._zeroWalls();if(!t.lines.length)return W``;const i=e?.color||"var(--hp-muted)";return W` - ${t.lines.map(e=>W``)} - `}_zeroWalls(){const e=this._spaceModel();return e?H_(this._curSpaceCfg,e,_v,.02*this._gridPitch):{style:I_(this._curSpaceCfg),lines:[],contour:[],barriers:[],transmissive:[]}}_openCuts(){return this._zeroWalls().contour}_deleteRoomClick(e){return this._editorRuntimeOrThrow()._deleteRoomClick(e)}get _wallKeyPitch(){return il}get _spaceWalls(){const e=this._curSpaceCfg?.walls;return Array.isArray(e)?e:[]}_intervalCm(e){const t=this._spaceModel();return t?zs(t.rooms,this._spaceWalls,this._openCuts(),e,this._wallKeyPitch,this._cellCm,this._gridPitch,_v):0}_normalizeWalls(e,t){const i=this._spaceModel();if(!i)return[];return Vo(Fs(i.rooms,e,t,this._wallKeyPitch,this._cellCm,this._gridPitch,_v),this._curSpaceCfg?.rooms||[],il,1,t.map(e=>[e[0]/_v,e[1]/_v,e[2]/_v,e[3]/_v]))}_paperShapes(e){if(!this._spaceWalls.length)return ri(e);const t=this._wallUnionGeometry();return t?.paperD?[{path:t.paperD}]:ri(e)}_wallUnionGeometry(){const e=this._spaceModel();if(!e)return null;const t=this._spaceWalls,i=this._physicalBodiesR();if(!t.length&&!i.length)return null;const n=`${this._space}|${this._cfgEpoch}|${e.rooms.length}`;if(!this._wallUnionCache||this._wallUnionCache.key!==n){const r=$f(this._wallUnionPool,n);if(r.hit)this._wallUnionCache=r.value;else{const r=this._openCuts(),o=this._roomWallOpeningInputs(),s=ea(e.rooms,t,r,o,this._wallKeyPitch,this._cellCm,this._gridPitch,_v,i);s&&Object.defineProperty(s,"sourceFingerprint",{value:cc([this._curSpaceCfg,this._cellCm,this._gridPitch]),enumerable:!1});const a={key:n,value:s};Mf(this._wallUnionPool,n,a,8),this._wallUnionCache=a}}return this._wallUnionCache.value}_thickWallCuts(){const e=this._spaceModel();if(!e)return[];const t=this._spaceWalls;if(!t.length)return[];const i=this._openCuts();return ia(e.rooms,t,i,this._wallKeyPitch,this._cellCm,this._gridPitch,_v).map(e=>[e.a[0],e.a[1],e.b[0],e.b[1]])}_innerRoomContour(e,t,i=this._openCuts(),n=this._wallUnionGeometry()?.roomGeom,r=this._wallUnionGeometry()?.multiWallNodes){const o=i.map(e=>e.join(",")).join(";"),s=`${e.id}|${this._cfgEpoch}|${t}|${o}`,a=$f(this._innerContourCache,s);if(a.hit)return a.value;const l=Es(e.rooms,t,this._spaceWalls,i,this._wallKeyPitch,this._cellCm,this._gridPitch,_v,n,r);return Mf(this._innerContourCache,s,l,600),l}_wallThickHit(e){return this._editorRuntimeOrThrow()._wallThickHit(e)}get _wallThickHover(){if(!this._markup||"wallthick"!==this._tool||!this._cursorPt||this._wallDialog)return null;const e=this._wallThickHit(this._cursorPt);if(!e)return null;const t=function(e,t,i){const n=Number.isFinite(e)&&e>0?e:0,r=Number.isFinite(t)&&t>0?t:5,o=Number.isFinite(i)&&i>0?i:0;return n>0?Fo(n,r,o)/2:Ba(1.5*o,r)}(e.cm,this._cellCm,this._gridPitch);let i="";for(const n of e.segs)i+=(i?" ":"")+cs([[n[0],n[1]],[n[2],n[3]]],t,!1);return{segs:e.segs,open:e.open,d:i}}_wallThickClick(e){return this._editorRuntimeOrThrow()._wallThickClick(e)}_wallThickApply(e){return this._editorRuntimeOrThrow()._wallThickApply(e)}_wallHatchDefs(e){const t=To(this._cellCm);return W` - - - - `}_resolvedRoomFills(e,t){const i=new Map,n=new Map;for(const r of e.rooms){const e=this._roomDialog&&r.id===this._roomEditId?this._roomFill||t.fill:Nn(t.fill,r),o=hn(t.customFill,this._roomDialog&&r.id===this._roomEditId?{settings:{fill_mode:this._roomFill,custom_fill:this._roomCustomFill}}:r),s=Tc(t.tempMin,t.tempMax,r,this._roomTempMin,this._roomTempMax,this._roomDialog&&r.id===this._roomEditId),a=vn(e,"lqi"===e&&r.area?this._roomLqi(r.area):null,"light"===e?Hd(Ed(this._renderPlanHass,this._renderDevices,r,this._virtualLights)):"none","temp"===e?this._roomTemp(r):null,s.min,s.max,this._fillColors,o);i.set(r,a),r.id&&n.set(r.id,a)}return{byRoom:i,byId:n}}_spaceDisplayForRender(){const e=un(this._curSpaceCfg),t=this._spaceDialog;return t&&"edit"===t.mode&&t.spaceId===this._space?{...e,showBorders:t.showBorders,showNames:t.showNames,hideDecor:t.hideDecor,hideOpenings:t.hideOpenings,color:t.roomColor,opacity:t.roomOpacity,fill:t.fillMode,customFill:t.customFill?cn(t.customFill):ln,glow:t.glowEnabled,tempMin:t.tempMin,tempMax:t.tempMax,showLqi:t.showLqi,cardFontScale:t.cardFontScale,labelTemp:t.labelTemp,labelHum:t.labelHum,labelLqi:t.labelLqi,labelLight:t.labelLight}:e}_openingWallIndexFor(e,t){const i=e.rooms.map(e=>`${e.id}:${e.poly?.map(e=>e.join(",")).join("/")||`${e.x},${e.y},${e.w},${e.h}`}`).join(";"),n=this._spaceWalls.map(e=>`${e.key}:${e.a?.join(",")||""}:${e.b?.join(",")||""}:${e.cm}`).join(";"),r=t.map(e=>e.join(",")).join(";"),o=[e.id,this._cfgEpoch,this._wallKeyPitch,this._cellCm,this._gridPitch,i,n,r].join("|");let s=this._openingWallIndexCache.get(o);return s||(s=oa(e.rooms,this._spaceWalls,t,this._wallKeyPitch,this._cellCm,this._gridPitch,_v)),Mf(this._openingWallIndexCache,o,s,4),{key:o,value:s}}_renderOpeningTunnelFills(e,t,i="data"){if(this._markup||!this._spaceWalls.length||!this._openingsR.length)return W``;if("glow-base"===i&&![...t.byRoom.values()].some(Boolean))return W``;const n=this._openCuts(),r=this._openingsR.map(e=>({x:e.rx,y:e.ry,angle:e.angle,length:e.rlen})),o=r.map(e=>`${e.x},${e.y},${e.angle},${e.length}`).join(";"),s=this._openingWallIndexFor(e,n),a=`${s.key}|${o}`;return this._openingTunnelCache&&this._openingTunnelCache.key===a||(this._openingTunnelCache={key:a,value:pa(s.value,r)}),S_({openings:this._openingsR,geometries:this._openingTunnelCache.value,fillsByRoomId:t.byId,idPrefix:`${e.id}-${i}`,groupClass:"data"===i?"opening-tunnels":"opening-tunnels glow-base-tunnels",dataLayer:i})}_resolvedGlowBase(e,t,i){const n=new Map,r=new Map,o=this._fillColors.glow_base;for(const s of e.rooms){const e=i.byRoom.get(s),a=Hn(t.glow,s)&&(!e||e.opacity<=0)?{color:o.c,opacity:o.a,mode:"glow"}:null;n.set(s,a),s.id&&r.set(s.id,a)}return{byRoom:n,byId:r}}_renderGlowBaseRooms(e,t){if(this._markup||![...t.byRoom.values()].some(Boolean))return W``;const i=new Map(e.rooms.map(e=>[e,ni(e)])),n=this._openCuts(),r=this._wallUnionGeometry()?.roomGeom,o=e=>"M "+e.map(e=>e[0]+" "+e[1]).join(" L ")+" Z",s=e.rooms.map(s=>{const a=t.byRoom.get(s)||null,l=i.get(s)||null;if(!a||!l)return G;const c=this._spaceWalls.length&&s.id&&this._innerRoomContour(e,s.id,n,r)||l,h=Ri(c,e.rooms.filter(e=>e!==s).map(e=>i.get(e)).filter(e=>!!e)),d=this._cleanFloor(s,c,e).path;return d||h.length?W``:s.poly||c!==l?W``:W``});return W``}_renderWallBodies(e){if("iso"===this._renderProjection)return W``;if(e&&!e.showBorders&&("view"===this._mode||"devices"===this._mode))return W``;const t=this._wallUnionGeometry();if(!t)return W``;const i=this._stageEl,n=this._viewOr(this._baseVb()),r=i&&i.clientWidth&&n.w?i.clientWidth/n.w:1,o=e?.color||"#607d8b",s=Co(t.depthUnits,r)||Do(To(this._cellCm),r),a=this._fillColors.wall_fill;return W` - ${t.paths.map(e=>W` - - `)} - `}_roomHoverPaths(e){const t=this._hoverRoom;if("view"!==this._mode||!t||t.space!==e.id)return null;const i=e.rooms.find(e=>e===t.room||!!e.id&&e.id===t.room.id);if(!i)return null;const n=ni(i);if(!n)return null;const r=e.rooms.filter(e=>e!==i).map(e=>({room:e,poly:ni(e)})).filter(e=>!!e.poly),o=Ri(n,r.map(e=>e.poly)),s=this._openCuts(),a=.02*this._gridPitch,l=s.filter(e=>{const t=[(e[0]+e[2])/2,(e[1]+e[3])/2];return n.some((e,i)=>Un(t,[e[0],e[1],...n[(i+1)%n.length]])<=4*a)}),c=this._spaceWalls,h=this._wallUnionGeometry()?.roomGeom,d=c.length&&i.id&&this._innerRoomContour(e,i.id,s,h)||n,u=[{axis:n,face:d}];for(const t of o){const i=r.find(e=>e.poly===t)?.room;let n=t;if(c.length&&i?.id){const r=Ds(e.rooms,i.id,c,s,this._wallKeyPitch,this._cellCm,this._gridPitch,_v);r&&(n=ra(r.poly,r.offsets)||t)}u.push({axis:t,face:n})}const p=this._roomWallOpeningInputs(this._openingsR,e).map(e=>{const t=e.angle*Math.PI/180,i=Math.cos(t)*e.length/2,n=Math.sin(t)*e.length/2;return[e.x-i,e.y-n,e.x+i,e.y+n]}),_=l.concat(p),m=u.map(({axis:e,face:t})=>{const i=_.map(i=>((e,t,i)=>{const n=e[2]-e[0],r=e[3]-e[1],o=Math.hypot(n,r);if(o.05)&&Un([c,h],[i[0],i[1],n[0],n[1]])<=4*a){d=!0;break}}if(!d)return null;let u=null;for(let e=0;e.05)continue;const p=Un([c,h],[t[0],t[1],n[0],n[1]]);(!u||p!!e);return i.length?Fn(t,i,a).map(e=>`M ${e[0]} ${e[1]} L ${e[2]} ${e[3]}`).join(" "):`M ${t.map(e=>`${e[0]} ${e[1]}`).join(" L ")} Z`}).filter(Boolean).join(" ");if(!m)return null;const g=e=>`M ${e.map(e=>`${e[0]} ${e[1]}`).join(" L ")} Z`;return{fillD:[this._cleanFloor(i,d,e).path||g(d),...o.map(g)].join(" "),outlineD:m}}_renderRoomHoverFill(e){return W` - - `}_renderRoomHoverOutline(e){return W` - - - `}_renderWallThickUi(){return this._editorRuntime?this._editorRuntimeOrThrow()._renderWallThickUi():W``}_renderWallThickDialog(){return this._editorRuntimeOrThrow()._renderWallThickDialog()}_openingAt(e){return this._editorRuntimeOrThrow()._openingAt(e)}_resolveOpeningPlacement(e){return this._editorRuntimeOrThrow()._resolveOpeningPlacement(e)}_activateOpeningPlacement(e){return this._editorRuntimeOrThrow()._activateOpeningPlacement(e)}_clearOpeningPlacement(e){return this._editorRuntime?this._editorRuntimeOrThrow()._clearOpeningPlacement(e):(this._openingHoverCandidate=null,this._openingJambBlockCm=null,void(e&&(this._openingPreset=null,this._openingRebindId=null)))}_openingClick(e){return this._editorRuntimeOrThrow()._openingClick(e)}_editOpening(e){if(this._editorRuntime)return this._editorRuntimeOrThrow()._editOpening(e)}_opPointerDown(e,t){if(this._editorRuntime)return this._editorRuntimeOrThrow()._opPointerDown(e,t)}_opPointerMove(e,t){if(this._editorRuntime)return this._editorRuntimeOrThrow()._opPointerMove(e,t)}_opRuler(e,t){return this._editorRuntimeOrThrow()._opRuler(e,t)}_opPointerUp(e,t){if(this._editorRuntime)return this._editorRuntimeOrThrow()._opPointerUp(e,t)}_opClick(e,t){if(this._editorRuntime)return this._editorRuntimeOrThrow()._opClick(e,t)}_saveOpening(){return this._editorRuntimeOrThrow()._saveOpening()}_deleteOpening(){return this._editorRuntimeOrThrow()._deleteOpening()}_contactCandidates(){return this._editorRuntimeOrThrow()._contactCandidates()}_lockCandidates(){return this._editorRuntimeOrThrow()._lockCandidates()}_toggleOpeningEntityPicker(e){return this._editorRuntimeOrThrow()._toggleOpeningEntityPicker(e)}_filterOpeningEntities(e,t){return this._editorRuntimeOrThrow()._filterOpeningEntities(e,t)}_selectOpeningEntity(e,t){return this._editorRuntimeOrThrow()._selectOpeningEntity(e,t)}_mergeClick(e){return this._editorRuntimeOrThrow()._mergeClick(e)}_commitMerge(){return this._editorRuntimeOrThrow()._commitMerge()}_splitClick(e){return this._editorRuntimeOrThrow()._splitClick(e)}get _contourClosed(){return this._path.length>=4&&this._samePt(this._path[0],this._path[this._path.length-1])&&(null!=this._closingWallCm||!this._activeWallChainId)}_markupMove(e){this._markup&&this._editorRuntime&&this._editorRuntimeOrThrow()._queuePointerMove("markup-hover",()=>this._editorRuntime._markupMove(e))}get _openingPreview(){const e=this._openingPreset;if("opening"!==this._tool||!e||!this._cursorPt)return null;const t=this._cursorPt,i=this._openingHoverCandidate;if(i&&Xf(i,[t[0],t[1]],e.revision,this._cfgEpoch))return i;if(this._openingAt(t))return this._openingHoverCandidate=null,null;const n=this._resolveOpeningPlacement(t);return this._openingHoverCandidate=n,n}get _opMeasureView(){return this._opMeasure||this._openingPreview?.measure||null}_saveRoom(){return this._editorRuntimeOrThrow()._saveRoom()}_decideWallFace(e){return this._editorRuntimeOrThrow()._decideWallFace(e)}_wallSourceCmAt(e,t,i){return this._editorRuntimeOrThrow()._wallSourceCmAt(e,t,i)}_activePathWithRepair(e,t){return this._editorRuntimeOrThrow()._activePathWithRepair(e,t)}_validateWallRepair(e,t){return this._editorRuntimeOrThrow()._validateWallRepair(e,t)}_applyWallRepair(e,t){return this._editorRuntimeOrThrow()._applyWallRepair(e,t)}_applyWallFaceBatch(){return this._editorRuntimeOrThrow()._applyWallFaceBatch()}_commitRoom(){return this._editorRuntimeOrThrow()._commitRoom()}_cancelPath(){return this._editorRuntimeOrThrow()._cancelPath()}_roomDialogCancel(){return this._editorRuntimeOrThrow()._roomDialogCancel()}get _freeAreas(){const e=new Set;for(const t of this._serverCfg?.spaces||[])for(const i of t.rooms||[])i.area&&e.add(i.area);for(const t of this._wallFaceBatch?.decisions||[])t.create&&t.area&&e.add(t.area);return Object.values(this.hass?.areas||{}).filter(t=>!e.has(t.area_id)).sort((e,t)=>(e.name||"").localeCompare(t.name||""))}_openDeviceInbox(){return this._editorRuntimeOrThrow()._openDeviceInbox()}_closeMarkerDialog(){return this._editorRuntimeOrThrow()._closeMarkerDialog()}_deviceInboxCandidates(e){return this._editorRuntimeOrThrow()._deviceInboxCandidates(e)}_deviceInboxRows(){return this._editorRuntimeOrThrow()._deviceInboxRows()}_deviceForInboxRow(e){return this._editorRuntimeOrThrow()._deviceForInboxRow(e)}_openInboxMarker(e,t=!1){return this._editorRuntimeOrThrow()._openInboxMarker(e,t)}async _setInboxHidden(e,t){return this._editorRuntimeOrThrow()._setInboxHidden(e,t)}_findInboxDevice(e){return this._editorRuntimeOrThrow()._findInboxDevice(e)}_deviceInboxTabKey(e){return this._editorRuntimeOrThrow()._deviceInboxTabKey(e)}_openMarkerDialog(e){if(this._editorRuntime)return this._editorRuntime._openMarkerDialog(e);this._ensureEditorRuntime().then(t=>{t&&this._openMarkerDialog(e)})}_runCandidates(){return this._editorRuntimeOrThrow()._runCandidates()}_bindingCandidates(){return this._editorRuntimeOrThrow()._bindingCandidates()}_physicalBodiesR(e=this._spaceModel()){if(!e)return[];const t=`${e.id}|${this._cfgEpoch}|${this._cellCm}|${this._gridPitch}`;if(this._physicalBodiesCache?.key===t)return this._physicalBodiesCache.all;const i=Ra(e,this._cellCm,this._gridPitch,2e-4*this._gridPitch,this._partitionOpeningCuts(e));return this._physicalBodiesCache={key:t,...i},i.all}_rawPhysicalBodiesR(e=this._spaceModel()){if(!e)return[];this._physicalBodiesR(e);const t=this._physicalBodiesCache;return t?[...t.partitions,...t.columns]:[]}_cleanFloor(e,t,i=this._spaceModel()){if(!i)return{floor:t,geom:null,path:"",area:Fa([[[...t,t[0]]]])};const n=e.id||`#${i.rooms.indexOf(e)}`,r=`${i.id}|${this._cfgEpoch}|${n}`;if(!this._resize?.preview){const e=$f(this._cleanFloorCache,r);if(e.hit)return e.value}const o=t.map(e=>e[0]),s=t.map(e=>e[1]),a=[Math.min(...o),Math.min(...s),Math.max(...o),Math.max(...s)],l=this._physicalBodiesR(i).filter(e=>{const t=e.map(e=>e[0]),i=e.map(e=>e[1]);return Math.max(...t)>=a[0]&&Math.min(...t)<=a[2]&&Math.max(...i)>=a[1]&&Math.min(...i)<=a[3]}),c=l.length?Pa(t,l):null,h={floor:t,geom:c,path:c?wa(c):"",area:Fa(c||[[[...t,t[0]]]])};return this._resize?.preview||Mf(this._cleanFloorCache,r,h,600),h}_autoIconForBinding(e){if("virtual"===e)return"mdi:map-marker";const[t,i]=e.split(":");if(!i)return"";const n=this._fullRegistryHass,r=this._bindingStatus(e),o="active"===r.kind?r.enabledEntityIds:r.allEntityIds;if("device"===t){const e=n.devices?.[i];if(!e)return"mdi:help-circle";const t=o;return t.some(e=>e.startsWith("lock."))?"mdi:lock":Gd(n,e.name_by_user||e.name||"",e.model,t,this._iconRules)}if("entity"===t){const e=n.entities?.[i],t=this.hass.states?.[i],r=e?.name||t?.attributes?.friendly_name||i;return i.startsWith("lock.")?"mdi:lock":Gd(n,r,"",[i],this._iconRules)}return""}_allRoomsFlat(){const e=[];for(const t of this._serverCfg?.spaces||[])for(const i of t.rooms||[])i.area?e.push({value:t.id+"#"+i.area,label:(t.title||t.id)+" · "+i.name}):i.id&&e.push({value:t.id+"#@"+i.id,label:(t.title||t.id)+" · "+i.name+" · "+this._t("marker.subarea")});return e}_errText(e){if(!e)return this._t("err.unknown");if("string"==typeof e)return e;if("invalid_passage_fields"===e.code){const t=String(e.message||e.error||"");let i="",n=[];try{const e=JSON.parse(t);i=String(e.space??""),n=Array.isArray(e.fields)?e.fields.map(String):[]}catch{const e=t.match(/space=([^;]*);\s*opening=([^;]*);\s*fields=([^;]*)/);e&&(i=e[1],n=e[3].split(",").filter(Boolean))}if(i||n.length){const e=this._serverCfg?.spaces?.find(e=>String(e.id)===i),t={contact:"opening.contact_label",lock:"opening.lock_label",invert:"opening.invert",flip_h:"opening.flip_h",flip_v:"opening.flip_v"},r=n.map(e=>t[e]?this._t(t[e]):e).join(", ");return this._t("opening.invalid_passage_fields",{room:e?.title||i,fields:r})}}if("invalid_partition_opening_jamb_margin"===e.code){const t=String(e.message||e.error||"");let i=NaN;try{i=Number(JSON.parse(t).margin_cm)}catch{const e=t.match(/margin_cm=([^;}"]*)/);i=e?Number(e[1]):NaN}if(Number.isFinite(i))return this._t("opening.partition_jamb_margin",{distance:ti(i,this._imperial)})}if(null!=e.code){const t=`backup.error.${e.code}`,i=this._t(t);return e.message&&console.warn("[houseplan] backend error",e.code,e.message),i!==t?i:this._t("err.code",{code:e.code})}if(e.message)return e.message;if(e.error)return e.error;try{return JSON.stringify(e)}catch{return String(e)}}_backupErrorText(e){return this._editorRuntimeOrThrow()._backupErrorText(e)}async _pickMarkerFiles(e){return this._editorRuntimeOrThrow()._pickMarkerFiles(e)}_removeMarkerPdf(e){return this._editorRuntimeOrThrow()._removeMarkerPdf(e)}_markerLightFields(e){return this._editorRuntimeOrThrow()._markerLightFields(e)}_markerTapActionFields(e){return this._editorRuntimeOrThrow()._markerTapActionFields(e)}_markerToggleEntityFields(e){return this._editorRuntimeOrThrow()._markerToggleEntityFields(e)}async _saveMarker(){return this._editorRuntimeOrThrow()._saveMarker()}async _deleteMarker(){return this._editorRuntimeOrThrow()._deleteMarker()}_normPos(e,t,i){return{s:e,x:t/_v,y:i/_v}}_spaceDialogUsesOnboardingRuntime(e){return"create"===e&&!this._editorRuntime&&(!!this._onboardingRuntime||0===(this._serverCfg?.spaces.length||0)||this._importTotal>0||this._importQueue.length>0)}_spaceRuntimeOrThrow(){if(!this._onboardingRuntime)throw new Error("Houseplan onboarding runtime is not loaded");return this._onboardingRuntime}_openSpaceDialog(e,t){return this._spaceDialogUsesOnboardingRuntime(e)?this._onboardingRuntime?void this._onboardingRuntime._openSpaceDialog(e,t):void this._ensureOnboardingRuntime().then(i=>{i&&this._spaceRuntimeOrThrow()._openSpaceDialog(e,t)}):this._editorRuntime?this._editorRuntime._openSpaceDialog(e,t):void this._ensureEditorRuntime().then(i=>{i&&this._openSpaceDialog(e,t)})}async _pickPlanFile(e){return this._onboardingRuntime&&this._spaceDialogUsesOnboardingRuntime("create")?this._onboardingRuntime._pickPlanFile(e):this._editorRuntimeOrThrow()._pickPlanFile(e)}_useServerPlan(e){return this._onboardingRuntime&&this._spaceDialogUsesOnboardingRuntime("create")?this._onboardingRuntime._useServerPlan(e):this._editorRuntimeOrThrow()._useServerPlan(e)}async _readPlanAspect(e){return this._onboardingRuntime&&this._spaceDialogUsesOnboardingRuntime("create")?this._onboardingRuntime._readPlanAspect(e):this._editorRuntimeOrThrow()._readPlanAspect(e)}async _deleteServerPlan(e){return this._onboardingRuntime&&this._spaceDialogUsesOnboardingRuntime("create")?this._onboardingRuntime._deleteServerPlan(e):this._editorRuntimeOrThrow()._deleteServerPlan(e)}_renderServerPlans(e){return this._onboardingRuntime&&this._spaceDialogUsesOnboardingRuntime(e.mode)?this._onboardingRuntime._renderServerPlans(e):this._editorRuntimeOrThrow()._renderServerPlans(e)}async _saveSpaceDialog(){return this._onboardingRuntime&&this._spaceDialogUsesOnboardingRuntime("create")?this._onboardingRuntime._saveSpaceDialog():this._editorRuntimeOrThrow()._saveSpaceDialog()}async _deleteSpace(){return this._editorRuntimeOrThrow()._deleteSpace()}async _saveConfigNow(){return this._editorRuntimeOrThrow()._saveConfigNow()}_startImport(){return this._onboardingRuntime?this._onboardingRuntime._startImport():this._editorRuntimeOrThrow()._startImport()}_openNextImport(){return this._onboardingRuntime?this._onboardingRuntime._openNextImport():this._editorRuntimeOrThrow()._openNextImport()}_skipImport(){return this._onboardingRuntime?this._onboardingRuntime._skipImport():this._editorRuntimeOrThrow()._skipImport()}_renderImportDialog(){return this._onboardingRuntime?this._onboardingRuntime._renderImportDialog():this._editorRuntimeOrThrow()._renderImportDialog()}_sunGlobal(){const e=this._settingsDialog;return e?{...this._settings,north_deg:e.northDeg??void 0,bg_mode:e.bgMode,sun_rays:e.sunRays,sun_ray_origin:e.sunRayOrigin}:this._settings}_sunSpace(){const e=this._spaceDialog,t=this._curSpaceCfg?.settings||{};return e&&"edit"===e.mode&&e.spaceId===this._space?{...t,north_deg:e.northDeg??void 0,bg_mode:e.bgMode??void 0,sun_rays:e.sunRays??void 0}:t}_effNorth(){return fr(this._sunGlobal(),this._sunSpace())}_effBgMode(){return yr(this._sunGlobal(),this._sunSpace())}_dayCycleState(e=new Date){return(this._modeTransitionVisual?.viewWeight??("view"===this._mode?1:0))<=0||"daynight"!==this._effBgMode()?null:sr(this._renderPlanHass,e)}_syncDayCycleClock(){const e=this._dayCycleState();this._dayCycleClockKey=e?ar(e):"";const t="clock"===e?.source&&"hidden"!==this.ownerDocument.visibilityState&&this.isConnected;t&&!this._dayCycleTimer?this._dayCycleTimer=window.setInterval(this._dayCycleTick,3e4):!t&&this._dayCycleTimer&&(clearInterval(this._dayCycleTimer),this._dayCycleTimer=0)}_dayCycleVisibility(e){"hidden"!==e.kind?(this._dayCycleTick(),this._syncDayCycleClock()):this._dayCycleTimer&&(clearInterval(this._dayCycleTimer),this._dayCycleTimer=0)}_effSunRays(){return br(this._sunGlobal(),this._sunSpace())}_effSunRayOrigin(){return vr(this._sunGlobal())}_sunNow(){return null!==this._effNorth()?wr(this._renderPlanHass):null}_renderSunRays(e){const t=W``,i=this._modeTransitionVisual?.viewWeight??0;if(this._editing&&i<=0||!this._effSunRays())return this._sunFadeReset(),t;const n=this._effNorth(),r=null!==n?wr(this._renderPlanHass):null;if(!r||r.elevation<=0)return this._sunFadeReset(),t;if(o=r.elevation,Number(o)>=3)this._sunOutTimer&&(clearTimeout(this._sunOutTimer),this._sunOutTimer=0),this._sunOut=!1,this._sunShown=!0;else{if(!this._sunShown)return t;this._sunOut||(this._sunOut=!0,this._sunOutTimer=window.setTimeout(()=>{this._sunOutTimer=0,this._sunShown=!1,this._sunOut=!1,this.requestUpdate()},2e3))}var o;const s=this._zeroWalls(),a=s.barriers.map(e=>e.join(",")).join(";"),l=this._effSunRayOrigin(),c=`${e.id}|${r.azimuth}|${r.elevation}|${n}|${l}|${this._cfgEpoch}|${s.style}|${a}`;if(!this._sunRaysCache||this._sunRaysCache.key!==c){const t=e.rooms.map(e=>({id:e.id||"",poly:ni(e)})).filter(e=>!!e.id&&!!e.poly),i=this._openingsR.filter(e=>"window"===e.type&&"partition"!==e.host?.kind).map(e=>({id:e.id,x:e.rx,y:e.ry,angle:e.angle,length:e.rlen})),o=this._spaceWalls,a=this._openCuts(),h=this._openingWallIndexFor(e,a).value,d={},u={},p=this._wallUnionGeometry()?.roomGeom;if(o.length){for(const i of t){const t=this._innerRoomContour(e,i.id,a,p);t&&(d[i.id]=t)}for(const e of i){const t=ha(h,{x:e.x,y:e.y,angle:e.angle,length:e.length});t.cm>0&&(u[e.id]=Fo(t.cm,this._cellCm,this._gridPitch))}}let _=mr(t,i,r.azimuth,r.elevation,n,o.length?d:void 0,o.length?u:void 0,l);const m=[...this._physicalBodiesR(e),...s.barriers.map(e=>[[e[0],e[1]],[e[2],e[3]]])];m.length&&(_=_.map(e=>{const t=function(e,t,i){return i>0?e.map(e=>function(e){const t=[...e].sort((e,t)=>e[0]-t[0]||e[1]-t[1]);if(t.length<=2)return t;const i=(e,t,i)=>(t[0]-e[0])*(i[1]-e[1])-(t[1]-e[1])*(i[0]-e[0]),n=[];for(const e of t){for(;n.length>=2&&i(n[n.length-2],n[n.length-1],e)<=0;)n.pop();n.push(e)}const r=[];for(let e=t.length-1;e>=0;e--){const n=t[e];for(;r.length>=2&&i(r[r.length-2],r[r.length-1],n)<=0;)r.pop();r.push(n)}return n.slice(0,-1).concat(r.slice(0,-1))}([...e,...e.map(e=>[e[0]+t[0]*i,e[1]+t[1]*i])])).filter(e=>e.length>=3):e}(m,e.dir,e.len),i=e.polys.map(e=>Pa(e,t));return{...e,paths:i.map(wa).filter(Boolean),polys:i.flatMap(Ia)}}).filter(e=>e.paths?.length||e.polys.length)),this._sunRaysCache={key:c,rays:_,rims:_.map(e=>function(e,t=1e-4){const[i,n]=e.dir,r=-n,o=i,s=[],a=e.rimSources||[e.a,e.b],l=a.filter((e,i)=>{const n=e[0]*r+e[1]*o;return a.findIndex(e=>Math.abs(e[0]*r+e[1]*o-n)<=t)===i});for(const a of l){const l=[];for(const s of e.polys)for(let e=0;et)continue;if(Math.abs((h[0]-a[0])*r+(h[1]-a[1])*o)>t)continue;const d=(c[0]-a[0])*i+(c[1]-a[1])*n,u=(h[0]-a[0])*i+(h[1]-a[1])*n;Math.abs(u-d)<=t||l.push(de[0]-t[0]);const c=[];for(const e of l){const i=c[c.length-1];i&&e[0]<=i[1]+t?i[1]=Math.max(i[1],e[1]):c.push([e[0],e[1]])}for(const[e,t]of c)s.push([[a[0]+i*e,a[1]+n*e],[a[0]+i*t,a[1]+n*t]])}return s}(e))}}const h=this._sunRaysCache.rays,d=this._sunRaysCache.rims;if(!h.length)return t;const u=(p=function(e){const t=Math.min(90,Math.max(-90,Number(e)||0));let i=lr[lr.length-1][1];for(let e=1;e - ${h.map((e,t)=>{const i=(e.a[0]+e.b[0])/2,n=(e.a[1]+e.b[1])/2,r=i+e.normal[0]*e.depth,o=n+e.normal[1]*e.depth;return W` - ${_.map(([e,t])=>W``)} - - - ${m.map(([e,t])=>W``)} - `})} - - - ${h.map((e,t)=>e.paths?.length?e.paths.map(e=>W``):e.polys.map(e=>W``))} - ${h.map((e,t)=>(d[t]||[]).map(e=>W``))} - `}_sunFadeReset(){this._sunOutTimer&&(clearTimeout(this._sunOutTimer),this._sunOutTimer=0),this._sunShown=!1,this._sunOut=!1}_compassPoint(e){const t=e.currentTarget.getBoundingClientRect(),i=e.clientX-(t.left+t.width/2),n=e.clientY-(t.top+t.height/2);if(Math.hypot(i,n)<5)return;let r=Math.round(180*Math.atan2(i,-n)/Math.PI);e.shiftKey&&(r=15*Math.round(r/15)),r=(r%360+360)%360,this._settingsDialog={...this._settingsDialog,northDeg:r}}_renderCompass(){const e=this._settingsDialog.northDeg;return j`{e.currentTarget.setPointerCapture(e.pointerId),this._compassDrag=!0,this._compassPoint(e)}} - @pointermove=${e=>{this._compassDrag&&this._compassPoint(e)}} - @pointerup=${()=>this._compassDrag=!1} - @pointercancel=${()=>this._compassDrag=!1}> - - ${[0,45,90,135,180,225,270,315].map(e=>W``)} - - - - ${this._t("gs.north_letter")} - - ${null===e?"—":e+"°"} - `}_stageBg(e){const t=this._settingsDialog,i=this._spaceDialog,n=t?t.bgColor||"":pn(this._settings,{bgColor:null});return(i&&"edit"===i.mode&&i.spaceId===this._space?i.bgColor||"":e.bgColor||"")||n}_stageBgHex(){const e=this._stageEl;if(e){const t=getComputedStyle(e).backgroundColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(t)return"#"+t.slice(1,4).map(e=>(+e).toString(16).padStart(2,"0")).join("")}return"#111111"}_renderPdfDialog(){const e=this._pdfRuntime,t=this._spaceModel(),i=this._curSpaceCfg;if(!(e&&t&&i&&this._serverCfg))return G;const n=new Map;for(const[e,t]of this._decorAssets)n.set(e,{url:this._display(t.url),mime:t.mime});const r=this._wallUnionGeometry(),o=this._openCuts(),s=new Map(t.rooms.flatMap(e=>e.id?[[e.id,e]]:[]));return e.render({config:this._serverCfg,rawSpace:i,space:t,layout:this._layout,imperial:this._imperial,cardTitle:this._config?.title||this._t("card.title"),version:ev(iv),hass:this.hass,backdropUrl:t.bg?this._display(t.bg.href):"",decorAssets:n,sharedWallGeometry:r,resolveInnerContour:e=>this._innerRoomContour(t,e,o,r?.roomGeom,r?.multiWallNodes),resolveRoomArea:(e,i)=>{const n=s.get(e);return n?this._cleanFloor(n,i,t).area:void 0},t:(e,t)=>this._t(e,t),toast:e=>this._showToast(e),close:()=>{this._pdfDialog=!1,this.requestUpdate()}})}_preflightDiagnostics(e,t){return this._editorRuntimeOrThrow()._preflightDiagnostics(e,t)}_reportPreflightFailure(e,t){return this._editorRuntimeOrThrow()._reportPreflightFailure(e,t)}_preflightVersionsDiffer(){return this._editorRuntimeOrThrow()._preflightVersionsDiffer()}async _copyPreflightDiagnostics(){return this._editorRuntimeOrThrow()._copyPreflightDiagnostics()}_checkOptimizeGeometry(e){return this._editorRuntimeOrThrow()._checkOptimizeGeometryImpl(e)}_checkSpacePhysicalGeometry(e,t,i){return this._editorRuntimeOrThrow()._checkSpacePhysicalGeometryImpl(e,t,i)}_optimizeReferenceContext(e){return this._editorRuntimeOrThrow()._optimizeReferenceContext(e)}_previewAlignDialog(e){return this._editorRuntimeOrThrow()._previewAlignDialog(e)}async _runAlignToGrid(){return this._editorRuntimeOrThrow()._runAlignToGrid()}async _undoPlanOptimization(){return this._editorRuntimeOrThrow()._undoPlanOptimization()}async _runBackupExport(){return this._editorRuntimeOrThrow()._runBackupExport()}async _pickBackupImport(e){return this._editorRuntimeOrThrow()._pickBackupImport(e)}async _setBackupDuplicatePolicy(e){return this._editorRuntimeOrThrow()._setBackupDuplicatePolicy(e)}async _applyBackupImport(){return this._editorRuntimeOrThrow()._applyBackupImport()}_renderBackupExportDialog(){return this._editorRuntimeOrThrow()._renderBackupExportDialog()}_renderBackupImportDialog(){return this._editorRuntimeOrThrow()._renderBackupImportDialog()}_setFillColor(e,t){return this._editorRuntimeOrThrow()._setFillColor(e,t)}async _saveSettingsDialog(){return this._editorRuntimeOrThrow()._saveSettingsDialog()}_boolInput(e,t,i=!1){return this._editorRuntimeOrThrow()._boolInput(e,t,i)}_rangeInput(e,t,i,n,r,o=!1,s){return this._editorRuntimeOrThrow()._rangeInput(e,t,i,n,r,o,s)}_renderColorRow(e,t){return this._editorRuntimeOrThrow()._renderColorRow(e,t)}get _glowRadiusCm(){const e=Number(this._settings.glow_radius_cm);return Number.isFinite(e)&&e>0?e:300}get _imperial(){return"mi"===this.hass?.config?.unit_system?.length}get _glowRadiusPlaceholder(){const e=this._glowRadiusCm;return this._imperial?String(Math.round(e/30.48*10)/10):String(e/100)}_glowTransition(e,t){return Tm(this._glowRuntimeState,this._glowRuntimeHost,e,t)}_forgetGlowSource(e){Dm(this._glowRuntimeState,this._glowRuntimeHost,e)}_forgetGlowSpace(e){Am(this._glowRuntimeState,this._glowRuntimeHost,e)}_warnGlowGeometryFallback(e,t,i,n){zm(this._glowRuntimeState,e,t,i,n)}_lightBarriers(e,t){const i=Sm({rawSpaceConfig:this._curSpaceCfg,space:e,openings:this._openingsR,cellCm:this._cellCm,gridPitch:this._gridPitch,openingAmount:e=>this._openingAmt(e)}),n=`${e.id}|${i.fingerprint}`,r=$f(this._lightBarrierPool,n);if(r.hit)return this._lightBarrierCache=r.value,r.value.value;const o=$m({space:e,revision:i,walls:this._spaceWalls,zeroWalls:this._zeroWalls(),wallKeyPitch:this._wallKeyPitch,cellCm:this._cellCm,gridPitch:this._gridPitch,coordScale:_v,sharedWallGeometry:this._wallUnionGeometry(),physicalBodies:(t,i)=>(this._lightPhysicalBodiesCache?.key!==i&&(this._lightPhysicalBodiesCache={key:i,all:Ra(e,this._cellCm,this._gridPitch,2e-4*this._gridPitch,t).all}),this._lightPhysicalBodiesCache.all)}),s={key:n,value:o};return Mf(this._lightBarrierPool,n,s,8),this._lightBarrierCache=s,o}_renderGlowLayer(e,t,i=this._viewOr(this._baseVb())){const n=this._fillColors,r=this._glowRadiusCm/this._cellCm*this._gridPitch,o=e.rooms.map(e=>({r:e,poly:ni(e)})).filter(e=>!!e.poly),s=o.filter(({r:e})=>Hn(t.glow,e));if(!s.length)return this._forgetGlowSpace(e.id),W``;const a=this._lightBarriers(e,o),l=xm({hass:this._renderPlanHass,devices:this._renderDevices,virtualLights:this._virtualLights,spaceId:e.id,defaultColor:n.glow_light.c,paletteAlpha:n.glow_light.a,defaultRadiusUnits:r,cellCm:this._cellCm,gridPitch:this._gridPitch,position:e=>this._pos(e)}),c=[],h=new Set;for(const t of l){const{key:i,pos:n}=t;if(h.add(i),Rm(n,a)){this._forgetGlowSource(i);continue}const r=this._glowTransition(i,!!t.appearance);if(!r)continue;t.appearance&&this._glowLastAppearance.set(i,t.appearance);const s=this._glowLastAppearance.get(i);if(!s)continue;let l=null;const d=`${e.id}|${a.fingerprint}|${n.x.toFixed(4)},${n.y.toFixed(4)}|${t.radius.toFixed(4)}`,u=wm(this._glowRuntimeState,d);u.hit?l=u.value:(l=Mm({spaceId:e.id,source:n,radius:t.radius,scene:a,polygons:o.map(({r:e,poly:t})=>({room:e,poly:t})),onBoundsFailure:(t,i)=>this._warnGlowGeometryFallback(e.id,a.fingerprint,t,i)}),km(this._glowRuntimeState,d,l)),c.push({key:i,sourceEid:t.sourceEid,domId:r.domId,entering:r.entering,leaving:r.leaving,pos:n,c:s.c,alpha:s.alpha,geometry:l,r:t.radius})}if(Pm(this._glowRuntimeState,this._glowRuntimeHost,e.id,h),!c.length)return W``;const d=this._spaceWalls,u=s.length===o.length?[]:this._openCuts(),p=this._wallUnionGeometry()?.roomGeom,_=s.length===o.length?null:s.map(({r:t,poly:i})=>{const n=d.length&&t.id&&this._innerRoomContour(e,t.id,u,p)||i,r=this._cleanFloor(t,n,e).path,s=Ri(n,o.filter(e=>e.r!==t).map(e=>e.poly)),a=e=>"M "+e.map(e=>e[0]+" "+e[1]).join(" L ")+" Z";return[r||a(n),...s.map(a)].join(" ")}),m=this._stageEl?.clientWidth&&i.w?this._stageEl.clientWidth/i.w:1,g=!this._pinchStart&&!this._panStart&&!this._cameraTransition.active,f=Im(this._glowRuntimeState,m,g);return Om({spots:c,enabledClip:_,feather:f.feather,featherEnabled:f.enabled,screenBlend:this._glowScreenBlend})}_renderAlignDialog(){return this._editorRuntimeOrThrow()._renderAlignDialog()}_renderSettingsDialog(){return this._editorRuntimeOrThrow()._renderSettingsDialog()}_renderSupportDialog(){return this._editorRuntimeOrThrow()._renderSupportDialog()}_rulesSet(e){return this._editorRuntimeOrThrow()._rulesSet(e)}async _saveRules(){return this._editorRuntimeOrThrow()._saveRules()}_renderRulesDialog(){return this._editorRuntimeOrThrow()._renderRulesDialog()}_saveKioskScale(e){this._summary?.saveScale(e)}_renderKioskDialog(){const e=this._kioskScale,t=(t,i)=>{const n=Math.round(100*e[t]);return j` -
- {const i=Number(e.target.value);Number.isFinite(i)&&this._saveKioskScale({[t]:i/100})}} aria-label=${i} /> - ${n}% -
`};return j`this._kioskDialog=!1}> -
-
${this._t("kiosk.hint")}
- ${t("icon",this._t("kiosk.icon_scale"))} - ${t("font",this._t("kiosk.font_scale"))} -
-
- - - -
-
`}_fixedFloorValue(e){if("string"==typeof e)return e||"''";try{const t=JSON.stringify(e);return(void 0===t?String(e):t).slice(0,160)}catch{return String(e).slice(0,160)}}_renderDangerConfirm(){return this._dangerConfirm?j` - `:G}_renderRoot(e){return j`${e}${this._renderVersionBanner()}${this._renderDangerConfirm()}`}render(){const e=this._renderBody();return e===G?e:this._renderRoot(e)}_renderBody(){if(!this._config||!this.hass)return G;const e=this._terminalFrame;if(this._terminalFrame=0,1===e)return U;const t=this._syncDangerConfirmLocaleGate();if("cold"===t)return up();if("warm"===t)return U;const i=!!this._importDialog||!(!this._spaceDialog||!this._spaceDialogUsesOnboardingRuntime(this._spaceDialog.mode)),n="view"!==this._mode||!!(this._roomDialog||this._mergeDialog||this._openingDialog||this._physicalDialog||this._partitionDeleteDialog||this._roomDeleteDialog||this._decorTextDialog||this._decorShapeDialog||this._backdropDialog||this._decorEraseConfirm||this._spaceDialog&&!this._spaceDialogUsesOnboardingRuntime(this._spaceDialog.mode)||this._deviceInbox||this._markerDialog||this._rulesDialog||this._settingsDialog||this._supportDialog||this._alignDialog||this._backupExportDialog||this._backupImportDialog||this._kioskDialog||this._vacFit||this._vacCalConfirm);i&&!this._onboardingRuntime&&this._ensureOnboardingRuntime(),n&&!this._editorRuntime&&this._ensureEditorRuntime();const r=this._model,o=this._renderLife.diagnostics(this.hass,this._markers,e=>this._bindingStatus(e)),s=this._fixedFloorState(r);if("pending"===s.kind)return j` - ${this.panelHost?G:j`
-
${this._config.title||this._t("card.title")}
-
`} -
- -

${this._t("fixed_floor.loading")}

-
-
`;if("invalid"===s.kind)return j` - ${this.panelHost?G:j`
-
${this._config.title||this._t("card.title")}
-
`} - -
`;if(!r.length)return j` - ${this.panelHost?G:j`
-
${this._config.title||this._t("card.title")}
-
`} -
- -

${this._t("empty.no_spaces")}

- ${this._serverStorage&&this._canManageConfiguration?j`

${this._t("empty.add_first")}

- `:j`

${this._t(this._serverStorage?"empty.read_only":"empty.install")}

`} -
- ${this._spaceDialog&&(this._onboardingRuntime||this._editorRuntime)?this._renderSpaceDialog():G} - ${this._importDialog&&this._onboardingRuntime?this._renderImportDialog():G} - ${this._toast?j``:G} -
`;const a=this._spaceModel();if(!a)return G;const l="valid"===s.kind?[a]:r,c=a.vb;let h=this._effectiveProjection();this._renderProjection=h,this._labs.active.length&&function(){const e=If,t=e.alpha?e.active.join(","):"";if(!t||t===Ef)return;Ef=t;const i=new Map(Df.map(e=>[e.id,e])),n=e.active.map(e=>`${e} (#${i.get(e).issue})`).join(", ");console.info(`HOUSEPLAN ALPHA: hp_alpha=1; ${n}`)}();let d="iso"===h;const u=d?this._isoSceneRuntime:null,p="devices"===this._mode&&this._showAll,_=this._renderDevices.filter(e=>e.space===a.id&&(!e.hidden||p)),m=this._renderDeviceSnapshot,g=this._spaceDisplayForRender(),f=this._resolvedRoomFills(a,g),v=this._resolvedGlowBase(a,g,f),y=g.showLqi??this._config.show_signal??!0,b=this._config.icon_size??2.5,w=b>8?2.5:b,k=x_(w);let x=d?this._renderIsoScene:null,S=this._viewOr(this._baseVb(h,x)),$=null;try{$=u?.resolveIsoFramePresentation({projection:h,display:g,scene:x,openings:this._openingsR,amountOf:e=>this._openingAmt(e),cellCm:this._cellCm,overlays:e=>this._isoOverlayScene(a,_,S,g,e,x,w,k,y)})??null}catch(e){this._latchIsoFallback(g.showBorders?x?.key||this._isoInvalidKey():`${a.id}|no-borders`,e),this._cancelCameraTransition(!1),h="flat",d=!1,x=null,$=null,this._renderProjection="flat",this._renderIsoScene=null,this._isoProjectionSnapshot="flat",this._view=null,this._viewModeSnap=null,S=this._viewOr(this._baseVb("flat",null))}const M=$?.layers??null,R=$?.overlays??null,C=this._editing?"":this._stageBg(g),T=this._opMeasureView,D="view"===this._mode?this._editorChromeMode:this._mode,A=this._roomHoverPaths(a),P=a.bg?this._display(a.bg.href):"",F=this._continuity.overlayVisible||"recovery-error"===this._continuity.state?this._continuity.recoveryReason:null,z=this._modeTransitionVisual,I=this._dayCycleState(),O=z?.viewWeight??("view"===this._mode?1:0),E=this._modeTransition.state?.from.presentedMode,N=!this._markup||!!z&&("view"===z.presentedMode||"devices"===z.presentedMode||"view"===E||"devices"===E),H=z?.stageColor||C,L=z?.sceneBrightness??1;return j` - this._notePointer(e)} - @pointerdown=${this._touchGestureGuard} - @pointermove=${this._touchGestureGuard} - @pointerup=${this._touchGestureGuard} - @pointercancel=${this._touchGestureGuard} - @lostpointercapture=${this._touchGestureGuard} - @keydown=${this._touchGestureGuard} - @contextmenu=${this._touchGestureGuard} - @click=${this._touchGestureGuard}> -
-
- ${this.panelHost?G:j`
- - ${this._config.title||this._t("card.title")} -
`} - - ${this._canEdit?j`
- ${[["plan","mdi:floor-plan"],["devices","mdi:tune-variant"],["decor","mdi:draw"]].map(([e,t])=>j``)} -
`:G} - ${this._t("count.devices",{n:_.filter(e=>!e.hidden).length})} - - ${this._labsIso&&"view"===this._mode&&!this._kiosk?j``:G} -
- - ${""} - - -
- ${this._norm&&this._canEdit?j` - - `:G} - ${this._kiosk?G:this._summary?.renderControls(!1)} -
- ${this._canEdit&&!this._kiosk?j`
-
- ${this._editorRuntime?"plan"===D?this._renderMarkupBar():"devices"===D?this._renderDevicesBar():this._renderDecorBar():G} -
-
`:G} -
- -
this._markupClick(e)} - @wheel=${e=>this._onWheel(e)} - @pointerdown=${e=>{this._notePointer(e),this._stagePointerDown(e)}} - @pointermove=${e=>this._stagePointerMove(e)} - @pointerleave=${e=>this._stagePointerLeave(e)} - @pointerup=${e=>this._stagePointerUp(e)} - @pointercancel=${e=>this._stagePointerCancel(e)}> - ${Sr(I,O)} - ${this._editorRuntime?this._renderEditorSecondary():G} -
- ${d&&M?.structural?W``:G} - - - ${""} - ${this._wallHatchDefs(g.color)}${W`${this._paperShapes(a.rooms).map(e=>"path"in e?W``:"poly"in e?W``:W``)}`} - ${this._editing?this._renderMarkupDefs(c):G} - ${""} - ${this._editing&&!this._markup&&this._gridLevels()?W``:G} - ${a.bg&&P?W`this._onBackdropLoaded(a.bg.href,P)} - transform=${a.bg.angle?`rotate(${a.bg.angle} ${a.bg.x+a.bg.w/2} ${a.bg.y+a.bg.h/2})`:G} - @dblclick=${e=>this._openBackdropDialog(e)} - preserveAspectRatio="none" />`:G} - ${(()=>{const e=this._openCuts(),t=this._thickWallCuts(),i=this._wallUnionGeometry()?.roomGeom,n=new Map,r=e=>(n.has(e)||n.set(e,ni(e)),n.get(e));return a.rooms.filter(e=>e.area||"view"===this._mode||this._markup||g.showBorders).map(n=>{let o="room "+(a.bg?"overlay":"yard")+(this._markup?" outlined":"");!this._markup||n.id!==this._mergeSel&&n.id!==this._splitSel?.roomId||(o+=" picked");let s="";const l=Nn(g.fill,n);if(!this._markup&&(g.showBorders||"none"!==l)){o+=" styled";const e=[];e.push(`--room-stroke:${g.color}`,`--room-stroke-op:${g.showBorders?g.opacity:0}`);const t=f.byRoom.get(n)||null;t?(o+=" filled",e.push(`--room-fill:${t.color}`,`--room-fill-op:${t.opacity}`)):e.push("--room-fill:transparent","--room-fill-op:0"),s=e.join(";")}let c;const h=e=>{this._roomTipEnabledForPointer(e)&&(void 0===c&&(c=this._roomArea(n)),this._showTip(e,n.name||this._t("room.unnamed"),c?this._t("tip.area",{value:c}):"",y?this._roomLqi(n.area):null,this._roomTemp(n),this._roomHum(n),!0))},d=e=>{this._notePointer(e),this._pointerModality.hoverEnabled&&(this._hoverRoom={space:a.id,room:n},this._syncLiveHover())},u=r(n),p=this._markup&&(n.id===this._mergeSel||n.id===this._splitSel?.roomId),_=u&&!p?e.filter(e=>{const t=[(e[0]+e[2])/2,(e[1]+e[3])/2];return u.some((e,i)=>Un(t,[e[0],e[1],...u[(i+1)%u.length]])<=.08*this._gridPitch)}):[],m=p?[]:t,v=_.concat(m);v.length&&(o+=" noedge");const b=this._spaceWalls.length&&n.id&&u&&this._innerRoomContour(a,n.id,e,i)||u,w=b?Ri(b,(k=n,a.rooms.filter(e=>e!==k).map(r).filter(Boolean))):[];var k;const x=e=>"M "+e.map(e=>e[0]+" "+e[1]).join(" L ")+" Z",S=b?this._cleanFloor(n,b,a).path:"",$=n.id||G,M=n.area||G,R=S&&b?W`this._clearPointerHover()}>`:w.length&&b?W`this._clearPointerHover()}>`:b&&b!==u?W`this._clearPointerHover()}>`:n.poly?W`this._clearPointerHover()}>`:W`this._clearPointerHover()}>`,C=v.length&&u?Fn(u,v,.02*this._gridPitch):null,T=C?W``:G;return W`${R}${T}`})})()} - ${this._renderRoomHoverFill(A)} - ${this._renderOpeningTunnelFills(a,f)} - ${this._renderGlowBaseRooms(a,v)} - ${this._renderOpeningTunnelFills(a,v,"glow-base")} - ${""} - ${g.hideDecor&&"decor"!==this._mode?G:this._renderDecorLayer(void 0,S)} - ${N?this._renderGlowLayer(a,g,S):G} - ${this._renderSunRays(a)} - ${this._editing?W`${this._renderAlignGuides()}`:G} - ${this._markup?W`${this._renderMarkupLayer(c)}`:G} - ${""} - ${""} - ${this._editing?G:this._renderZeroWalls(g)} - ${this._renderWallBodies(g)} - ${this._markup&&"resize"===this._tool?this._renderResizeMeasurements():G} - ${this._renderRoomHoverOutline(A)} - ${""} - ${this._editing?this._renderZeroWalls(g):G} - ${this._markup?W`${this._renderHiddenWallDiagnosticOverlay()}`:G} - ${this._markup?W`${this._renderOpeningPlacementPreview()}`:G} - ${T?this._renderOpeningDimensionGuides(T):G} - ${T?.guide?this._renderOpeningCenterTick(T.guide):G} - ${""} - ${""} - ${this._markup?W`${this._renderActiveChainInk()}`:G} - ${this._markup?W`${this._renderPlanSnapOverlay()}`:G} - ${g.hideOpenings&&!this._markup||M&&!M.floorSymbols?G:this._renderOpenings(g)} - ${this._renderWallThickUi()} - ${this._markup&&"resize"===this._tool?this._renderResizeLayer(S):G} - ${""} - ${this._renderBackdropFrame(S)} - ${this._renderTextFrame(S)} - - - - ${Me(d&&M?.structural?W` - - `:G)} - ${""} -
- ${function(e,t,i){const n=[...e];if(!n.length)return G;const r=[],o=[],s=[];for(const e of n){for(const t of e.zones){if(!(!0===t.state||"number"==typeof t.state&&t.state>0)||!t.polygon)continue;const e=t.polygon.map(e=>i([1e3*e[0],1e3*e[1]]));s.push(W``${e[0]},${e[1]}`).join(" ")}>`)}for(const t of e.ranges)if(t.segments)for(const e of t.segments){const t=e.map(e=>i([1e3*e[0],1e3*e[1]]));o.push(W``${e[0]},${e[1]}`).join(" ")}>`)}for(const n of e.targets){if(!n.included)continue;const o=i([1e3*n.x,1e3*n.y]),s=(o[0]-t.x)/t.w*100,a=(o[1]-t.y)/t.h*100;r.push(j``)}}return o.length||s.length||r.length?j`${o.length||s.length?W``:G}${r}`:G}([...this._radarLive.frames.values()].filter(e=>{const t=this._serverCfg?.markers.find(t=>t.id===e.marker_id);return!!t&&Cg(t,this._space)}),S,e=>this._scenePoint(e))} - ${Re(a.id,Te(_,e=>e.id,e=>this._renderDevice(e,S,y,R?.devices.get(e.id))))} - ${this._renderVacuums(this._renderVacuumDevices,S,a.id)} - ${this._renderVacFit(S)} - ${this._renderOpeningLocks(S,R?.locks)} - ${g.showNames||this._markup?a.rooms.map(e=>this._renderRoomLabel(e,a,S,g,R?.rooms.get(e))):G} - ${this._markup?a.rooms.map(e=>this._renderRoomGear(e,a,S)):G} - ${B={hass:this.hass,settings:this._settings,devices:this._renderDevices,registry:this._haRegistry,currentSpace:a.id,spaces:this._serverCfg?.spaces,viewKey:S,view:"view"===this._mode,kiosk:this._kiosk},B.view&&!B.kiosk&&!0===B.hass?.user?.is_admin&&zg(B.settings).enabled?(import("./hp-zigbee-topology-overlay-jvjkBbI9.js"),j``):G} -
-
- ${this._wallDialog?j`
${this._renderWallThickDialog()}
`:G} -
- - ${this._renderFarHint()} - ${this._renderHomeArrow(this._baseVb(h,x))} - ${this._renderEditorRuntimeLoading()} - ${this._renderRecoveryOverlay()} - ${this._summary?.renderMeasure()} - ${this._kiosk?this._summary?.renderControls(!0):G} - ${this._summary?.renderPanel()} - ${this._booting||this._bootFading?j``:G} -
- - ${this._roomDialog&&this._editorRuntime?this._renderRoomDialog():G} - ${this._mergeDialog&&this._editorRuntime?this._renderMergeDialog():G} - ${this._openingDialog&&this._editorRuntime?this._renderOpeningDialog():G} - ${this._physicalDialog&&this._editorRuntime?this._renderPhysicalDialog():G} - ${this._partitionDeleteDialog&&this._editorRuntime?this._renderPartitionDeleteDialog():G} - ${this._roomDeleteDialog&&this._editorRuntime?this._renderRoomDeleteDialog():G} - ${this._openingInfo?this._renderOpeningInfoCard():G} - ${this._decorTextDialog&&this._editorRuntime?this._renderDecorTextDialog():G} - ${this._decorShapeDialog&&this._editorRuntime?this._renderDecorShapeDialog():G} - ${this._backdropDialog&&this._editorRuntime?this._renderBackdropDialog():G} - ${this._decorEraseConfirm&&this._editorRuntime?this._renderDecorEraseConfirm():G} - ${this._spaceDialog&&(this._onboardingRuntime||this._editorRuntime)?this._renderSpaceDialog():G} - ${this._deviceInbox&&this._editorRuntime?this._renderDeviceInbox():G} - ${this._markerDialog&&this._editorRuntime?this._renderMarkerDialog():G} - ${this._backdropGuard?this._editorRuntime?this._editorRuntime._renderBackdropGuard():this._onboardingRuntime?._renderBackdropGuard()??G:G} - ${this._vacCalConfirm&&this._editorRuntime?j`{this._vacCalConfirm?.busy||(this._vacCalConfirm=null)}}> -
-

${this._t("vac.residual_message",{error:this._vacCalConfirm.error})}

-
-
- - - - -
-
`:G} - ${this._infoCard?this._renderInfoCard():G} - ${this._rulesDialog&&this._editorRuntime?this._renderRulesDialog():G} - ${this._settingsDialog&&this._editorRuntime?this._renderSettingsDialog():G} - ${this._supportDialog&&this._editorRuntime?this._renderSupportDialog():G} - ${this._pdfDialog?this._renderPdfDialog():G} - ${this._alignDialog&&this._editorRuntime?this._renderAlignDialog():G} - ${this._backupExportDialog&&this._editorRuntime?this._renderBackupExportDialog():G} - ${this._backupImportDialog&&this._editorRuntime?this._renderBackupImportDialog():G} - ${this._importDialog&&this._onboardingRuntime?this._renderImportDialog():G} - - ${this._kiosk&&!this._hasFixedFloor&&this._kioskDots&&this._model.length>1?j`
- ${this._model.map(e=>j``)} -
`:G} - ${this._kioskDialog?this._renderKioskDialog():G} - ${this._summary?.dialogOpen?this._summary.renderDialog():G} - ${this._vacFit?j`
- ${this._t("vac.fit_hint")} - - - - -
`:G} - ${this._tapConfirm?j`this._tapConfirm=null}> -
- ${"run"===this._tapConfirm.kind?j`

${this._tapConfirm.text}

`:this._tapConfirm.lines.map((e,t)=>j` -

${e}

`)} -
-
- - - -
-
`:G} - ${this._toast?j``:G} -
- `;var B}_vacCandidateStatus(e,t,i=this._planHass){const n=this._bindingStatus("entity:"+e);if("ha_disabled"===n.kind)return"disabled";if("orphaned"===n.kind)return"missing";if("unverified"===n.kind)return"unverified";const r=i?.states?.[e];return"unavailable"===r?.state?"unavailable":t?.hasPosition?"ok":"unsupported"}_vacOpenAllCameras(e){const t=this._haRegistry.entities||{},i=[];for(const[e,n]of Object.entries(this.hass?.states||{})){if(!e.startsWith("camera."))continue;const r=Vc(e,n,t[e]);r&&i.push(r)}this._vacAllCameraCache={devId:e.id,candidates:i},this._vacAllCamerasFor=e.id}_vacSourceResolution(e,t=!1,i=this._planHass){const n=e.marker?.vacuum,r="string"==typeof n?.source&&!!n.source,o=new Set(e.entities||[]),s=new Set(o);r&&s.add(n.source);const a=i?.entities||{},l=[];for(const e of s){const t=i?.states?.[e],o=Vc(e,t,a[e]);o?l.push(o):r&&e===n.source&&l.push({entityId:e,name:String(t?.attributes?.friendly_name||e),platform:a[e]?.platform?String(a[e].platform):null,category:e.startsWith("camera.")?"camera":"partial",hasPosition:!1,hasRooms:!1,hasPath:!1,hasMapId:!1,score:0})}if(t&&this._vacAllCameraCache?.devId===e.id){const e=new Set(l.map(e=>e.entityId));for(const t of this._vacAllCameraCache.candidates)e.has(t.entityId)||l.push(t)}const c={};for(const e of l)c[e.entityId]=this._vacCandidateStatus(e.entityId,e,i);return function(e,t,i,n){const r="string"==typeof e&&e.length>0,o=new Set(t),s=Array.from(i).sort((t,i)=>r&&t.entityId===e?-1:r&&i.entityId===e?1:i.score-t.score||t.entityId.localeCompare(i.entityId));if(r){const t=s.find(t=>t.entityId===e);return{entityId:e,status:n[e]||(t?.hasPosition?"ok":"unverified"),pinned:!0,candidates:s}}const a=s.find(e=>o.has(e.entityId)&&e.hasPosition&&"ok"===n[e.entityId]);return a?{entityId:a.entityId,status:"ok",pinned:!1,candidates:s}:{entityId:null,status:"none",pinned:!1,candidates:s}}(n?.source,o,l,c)}_vacSource(e,t=this._planHass){if(!1===e.marker?.vacuum?.live)return null;const i=this._vacSourceResolution(e,!1,t);return"ok"===i.status||"unsupported"===i.status?i.entityId:null}_vacEntity(e){return e.primary?.startsWith("vacuum.")?e.primary:(e.entities||[]).find(e=>e.startsWith("vacuum."))||null}_isVacDev(e){return!!this._vacEntity(e)}_activitySourceKey(e){return this._activitySnapshot(e).sourceKey}_activitySnapshot(e,t=Ed(this._planHass,this._devices,null,this._virtualLights)){const i=l_(this._planHass,e,this._devices,t,this._fullRegistryHass);return{samples:i.samples,sourceKey:d_(this._planHass,e,i)}}_stampActivity(e,t,i){let n=this._activityRt.get(e);n||(n=ig(i||"",[]),this._activityRt.set(e,n)),null!=i&&(n.sources=i),rg(n,t,Date.now(),window.clearTimeout.bind(window),e=>window.setTimeout(()=>this.requestUpdate(),e))}_syncActivityRuntime(){const e=new Map;if(!this.hass)return e;if(!1===this._config?.live_states){for(const e of this._activityRt.values())clearTimeout(e.timer);return this._activityRt.clear(),e}const t=new Set,i=Ed(this._planHass,this._devices,null,this._virtualLights);for(const n of this._devices){if(n.hidden)continue;if("icon_ripple"!==Li(n.marker?.display))continue;t.add(n.id);const r=this._activitySnapshot(n,i);e.set(n.id,r);const{samples:o,sourceKey:s}=r;let a=this._activityRt.get(n.id);a?a.sources!==s&&ng(a,s,o,window.clearTimeout.bind(window)):(a=ig(s,o),this._activityRt.set(n.id,a))}for(const[e,i]of this._activityRt)t.has(e)||(clearTimeout(i.timer),this._activityRt.delete(e));return e}_activityTick(){if(!this.hass)return;const e=this._syncActivityRuntime();for(const t of this._devices){if(t.hidden)continue;if("icon_ripple"!==Li(t.marker?.display))continue;const i=e.get(t.id)||this._activitySnapshot(t),{samples:n,sourceKey:r}=i,o=this._activityRt.get(t.id);if(!o||o.sources!==r)continue;const s=og(o,n,window.clearTimeout.bind(window));s&&this._stampActivity(t.id,s,r)}}_vacTick(){if(this.hass)for(const e of this._devices){if(e.hidden||!this._isVacDev(e))continue;if("static_icon"===Li(e.marker?.display)){this._vacRt.delete(e.id);continue}const t=this._vacSource(e);if(!t)continue;const i=this._vacEntity(e),n=Jc(this.hass.states[i||""]?.state),r=Wc(this.hass.states[t]?.attributes);let o=this._vacRt.get(e.id);o||(o={trail:[],lastKey:"",lastTs:0,moving:!1,jump:!1,endedTs:0,lastPos:null},this._vacRt.set(e.id,o)),n&&!o.moving&&(o.trail=[],o.lastPos=null);const s="never"!==rh(e.marker?.vacuum)&&!r?.path.length;!n&&o.moving&&(o.endedTs=Date.now(),s&&o.lastPos&&(o.trail=Zc(o.trail,o.lastPos,40)),o.lastPos=null),o.moving=n;const a=r?.pos;if(n&&a){const e=a.x+":"+a.y;if(e!==o.lastKey){const t=Date.now();o.jump=o.lastTs>0&&t-o.lastTs>1e4,o.lastKey=e,o.lastTs=t,s&&o.lastPos&&(o.trail=Zc(o.trail,o.lastPos,40)),o.lastPos=[a.x,a.y]}}}}_vacEnsureMarker(e){const t=this._serverCfg;if(!t)return null;t.markers=t.markers||[];const i=t.markers.find(t=>t.id===e.id);if(i)return i;if("device"!==e.bindingKind&&"entity"!==e.bindingKind||!e.bindingRef)return null;const n={id:e.id,binding:e.bindingKind+":"+e.bindingRef,space:e.space||null,area:e.area||null,hidden:!!e.hidden};return t.markers.push(n),n}_renderVacSection(e){return this._editorRuntimeOrThrow()._renderVacSection(e)}_vacMapId(e,t,i=this._planHass){const n=this._vacEntity(e),r=n?i?.states?.[n]?.attributes?.selected_map:null;return o=t.mapId,s=r,"default"!==o?o:null!=s?String(s):"default";var o,s}_vacObservedMapId(e,t,i=this._planHass){const n=Wc(i?.states?.[t]?.attributes);return n?this._vacMapId(e,n,i):void 0}_vacSaveMatrix(e,t,i,n,r=""){return this._editorRuntimeOrThrow()._vacSaveMatrix(e,t,i,n,r)}_vacPlanRoomAnchors(e){return this._editorRuntimeOrThrow()._vacPlanRoomAnchors(e)}_vacAutoCalibrate(e){return this._editorRuntimeOrThrow()._vacAutoCalibrate(e)}_vacApplyCalibrationProposal(e){return this._editorRuntimeOrThrow()._vacApplyCalibrationProposal(e)}_vacStartFit(e){return this._editorRuntimeOrThrow()._vacStartFit(e)}_vacFitSave(){return this._editorRuntimeOrThrow()._vacFitSave()}_vacFitTurn(e){return this._editorRuntimeOrThrow()._vacFitTurn(e)}_vacGhostCentre(e){return this._editorRuntimeOrThrow()._vacGhostCentre(e)}_vacDelta(e,t,i){return this._editorRuntimeOrThrow()._vacDelta(e,t,i)}_vacFitPointer(e,t){return this._editorRuntimeOrThrow()._vacFitPointer(e,t)}_renderVacFit(e){return this._editorRuntime?this._editorRuntimeOrThrow()._renderVacFit(e):G}_vacRafLoop(){this._vacRaf=requestAnimationFrame(()=>{const e=this.renderRoot,t=this._stageEl,i=this._vacLastView,n=e?.querySelectorAll?.(".vacpuck")||[];if(!t||!i||!n.length)return void(this._vacRaf=0);const r=t.getBoundingClientRect();for(const t of n){const n=t.getAttribute("data-mid"),o=t.getBoundingClientRect(),s=i.x+(o.left+o.width/2-r.left)/r.width*i.w,a=i.y+(o.top+o.height/2-r.top)/r.height*i.h;for(const t of e.querySelectorAll(`line.tip[data-mid="${n}"]`))t.setAttribute("x2",s.toFixed(1)),t.setAttribute("y2",a.toFixed(1))}this._vacRafLoop()})}_vacTrailPathD(e,t){const i=e.map(e=>e.map(([e,i])=>Fc(t,e,i))),n=function(e,t,i=console.warn){if(!Number.isFinite(t)||t<=0)return[];const n=[];let r=0;for(const i of e){if(!i.every(qc)){r++;continue}const e=i.filter((e,t)=>0===t||!jc(e,i[t-1]));if(e.length<2)continue;const o=[{kind:"move",point:e[0]}];if(2!==e.length){for(let i=1;i0&&i(`[houseplan] vacuum trail: ${r} segment(s) dropped — non-finite point (check map calibration)`),n}(i,this._cmToUnits(17.5)),r=e=>{const t=this._scenePoint(e);return`${t[0].toFixed(1)} ${t[1].toFixed(1)}`};return n.map(e=>e.map(e=>"move"===e.kind?`M ${r(e.point)}`:"line"===e.kind?`L ${r(e.point)}`:`Q ${r(e.control)} ${r(e.point)}`).join(" ")).join(" ")}_renderVacuums(e,t,i){if(this._markup||"decor"===this._mode)return G;const n=this._space+"|"+t.x+"|"+t.y+"|"+t.w+"|"+t.h,r=this._vacJumpOnce||n!==this._vacViewKey;this._vacViewKey=n,this._vacJumpOnce=!1;const o=[],s=[];for(const n of e){if(n.hidden||!this._isVacDev(n))continue;if("static_icon"===Li(n.marker?.display))continue;const e=this._renderDeviceSnapshot?.facts.get(`vacuum:${n.id}`),a=e?.source??this._vacSource(n,this._renderPlanHass);if(!a)continue;const l=e?.telemetry??Wc(this._renderPlanHass?.states[a]?.attributes);if(!l)continue;const c=e?.routes??lh(n.id,n.marker?.vacuum??null,n.space,a),h=e?.resolution??hh({routes:c,observed:dh(c,[a],e=>this._vacObservedMapId(n,e)),spaceIds:new Set(this._model.map(e=>e.id))}),d=e?.server??this._vacSrvTrails[n.id],u=ph({resolution:h,routes:c,renderSpace:i,rootSource:n.marker?.vacuum?.source??null,serverCurrent:d?.current??null,serverPrevious:d?.previous??null,explicitRoutes:Array.isArray(n.marker?.vacuum?.map_routes)});if(!u.live&&!u.previous)continue;const p=u.live,_=e?.runtime??this._vacRt.get(n.id),m=_?.moving??!1,g=rh(n.marker?.vacuum),f="always"===g||"cleaning"===g&&m,v=d,y=u.currentRunMatches&&Array.isArray(v?.current?.points)?v.current:null,b=u.previous&&Array.isArray(v?.previous?.points)?v.previous:null;if("always"===g&&b&&u.previous){const e=Hc(b.points),t=this._vacTrailPathD(e,u.previous);t&&s.push(W``)}if(f&&p){const e=Lc(l,y,_?.trail||[]),t=!m||"integration"!==e.source&&"server"!==e.source?e.path:Bc(e.path);if(t.length){const e=this._vacTrailPathD(t,p);e&&s.push(W``);const i=t[t.length-1];if(m&&i?.length>=2){const e=i[i.length-1],[t,r]=Fc(p,e[0],e[1]),o=this._scenePoint([t,r]),a=o[0].toFixed(1),l=o[1].toFixed(1);s.push(W``)}}}if(!m||!l.pos||!p)continue;const[w,k]=Fc(p,l.pos.x,l.pos.y),x=this._scenePoint([w,k]),S=(x[0]-t.x)/t.w*100,$=(x[1]-t.y)/t.h*100,M=_&&_.lastTs>0&&Date.now()-_.lastTs>6e4,R=n.marker?.icon||n.icon||"mdi:robot-vacuum";o.push(j`
{e.stopPropagation();const t=this._vacEntity(n);t&&this._openMoreInfo(t)}}> - -
`)}return this._vacLastView=t,o.length&&!this._vacRaf&&this._vacRafLoop(),o.length||s.length?j` - ${s.length?W`${s}`:G} - ${o}`:G}_renderDevice(e,t,i=!0,n){const r=this._pos(e),o=n?.visualScene??this._scenePoint([r.x,r.y]),s=(o[0]-t.x)/t.w*100,a=(o[1]-t.y)/t.h*100,l=this._devicePresentation(e,i),c=[`left:${s}%`,`top:${a}%`,...b_(l)],h=l.disabledReason,d=l.haDisabled?this._t(`marker.ha_disabled_${h}`):e.userHidden?this._t("marker.hidden_ghost"):e.name,u=i_(l),p="view"===this._mode||"devices"===this._mode,_=t_([d,l.haDisabled?"":this._t(`marker.state_a11y_${u}`),"none"!==l.pulse.kind?this._t(`marker.pulse_a11y_${l.pulse.reason}`):"",l.valueFullText||l.valueText||"",zp(l.valueBadge),null!=l.lqiText&&l.lqiBand?this._t(`marker.lqi_a11y_${l.lqiBand}`,{value:l.lqiText}):""]);return j`
this._clickDevice(t,e)} - @keydown=${t=>this._keyDevice(t,e)} - @focus=${t=>this._showDeviceFocusTip(t,e)} - @focusout=${()=>this._hideDeviceFocusTip(e.id)} - @contextmenu=${t=>this._ctxDevice(t,e)} - @pointerover=${t=>{"view"!==this._mode&&"devices"!==this._mode||this._showDeviceTip(t,this._deviceForPointerEvent(t,e))}} - @pointerleave=${()=>this._clearPointerHover()} - @pointerdown=${t=>this._pointerDown(t,e)} - @pointermove=${t=>{if("view"!==this._mode&&"devices"!==this._mode)return;const i=this._pointerMove(t,e);i&&this._showDeviceTip(t,i)}} - @pointerup=${t=>this._pointerUp(t,e)} - @pointercancel=${t=>this._pointerCancel(t,e)} - @lostpointercapture=${t=>this._pointerCancel(t,e)} - > - ${k_(l,{newDevice:this._newIds.has(e.id),newDeviceTitle:this._t("device.new"),disabledTitle:l.haDisabled?d:""})} - ${this._vacRouteBadge(e)} -
`}_vacRouteBadge(e){if(!this._isVacDev(e)||e.hidden)return G;if("static_icon"===Li(e.marker?.display))return G;const t=this._renderDeviceSnapshot?.facts.get(`vacuum:${e.id}`),i=function(e,t){if(!t||!e)return null;switch(e.kind){case"unmapped":case"needs_calibration":case"ambiguous":case"missing_space":return e.kind;default:return null}}(t?.resolution,this._vacRt.get(e.id)?.moving??!1);if(!i)return G;const n=this._t(`vac.route_warn_${i}`);return j` - `}_roomArea(e){const t=ni(e);if(!t)return null;const i=this._spaceModel();if(!i)return null;const n=this._spaceWalls.length&&e.id&&this._innerRoomContour(i,e.id)||t,r=this._cleanFloor(e,n),o=this._cellCm/this._gridPitch;return Xn(r.area*o*o/1e4,"mi"===this._renderPlanHass?.config?.unit_system?.length)}_roomTemp(e){const t=e.settings?.temp_source,i=su(this._spaceModel()?.id,e);return t?ru(this._renderPlanHass,t,"temp",this._markers):i?this._climate().get(i)?.temp??null:null}_roomHum(e){const t=e.settings?.hum_source,i=su(this._spaceModel()?.id,e);return t?ru(this._renderPlanHass,t,"hum",this._markers):i?this._climate().get(i)?.hum??null:null}_climate(){const e=this._serverCfg?.markers,t=this._renderPlanHass,i=this._climateCache,n=this._settings.exclude_integrations;if(i&&i.h===t&&i.r===this._iconRules&&i.mk===e&&i.ex===n)return i.m;const r=cu(t,this._iconRules,e,this._excluded);return this._climateCache={h:t,r:this._iconRules,mk:e,ex:n,m:r},r}_resetRoomDialogFields(){return this._editorRuntimeOrThrow()._resetRoomDialogFields()}_openRoomEdit(e){return this._editorRuntimeOrThrow()._openRoomEdit(e)}_roomSettingsFromDialog(){return this._editorRuntimeOrThrow()._roomSettingsFromDialog()}_saveRoomEdit(){return this._editorRuntimeOrThrow()._saveRoomEdit()}_roomSrcCandidates(){return this._editorRuntimeOrThrow()._roomSrcCandidates()}_roomSrcLabel(e){return this._editorRuntimeOrThrow()._roomSrcLabel(e)}_labelPos(e,t){const i=this._layout["rl_"+(e.id||"")];if(i&&i.s===t)return{x:i.x*_v,y:i.y*_v};const n=this._roomCenter(e),r=this._gridPitch;return{x:ol(Qt(n[0],r)),y:ol(Qt(n[1],r))}}_labelDown(e,t,i){if(this._editorRuntime)return this._editorRuntimeOrThrow()._labelDown(e,t,i)}_labelMove(e,t,i){if(this._editorRuntime)return this._editorRuntimeOrThrow()._labelMove(e,t,i)}_labelUp(e){if(this._editorRuntime)return this._editorRuntimeOrThrow()._labelUp(e)}_labelScale(e){const t=this._layout["rl_"+(e.id||"")]?.k;return"number"==typeof t&&Number.isFinite(t)?Math.min(3,Math.max(.5,t)):1}_rlResizeDown(e,t,i){return this._editorRuntimeOrThrow()._rlResizeDown(e,t,i)}_rlResizeMove(e){return this._editorRuntimeOrThrow()._rlResizeMove(e)}_rlResizeUp(){return this._editorRuntimeOrThrow()._rlResizeUp()}_renderRoomGear(e,t,i){return this._editorRuntimeOrThrow()._renderRoomGear(e,t,i)}_renderRoomLabel(e,t,i,n,r){if(!e.name&&!this._markup)return G;const o=this._labelPos(e,t.id),s=r?.visualScene??this._scenePoint([o.x,o.y]),a=(s[0]-i.x)/i.w*100,l=(s[1]-i.y)/i.h*100,c=Math.min(1,n.opacity+.25),h=this._labelScale(e),d=[];if(n.labelTemp||n.labelHum||n.labelLqi&&e.area||n.labelLight){if(n.labelTemp){const t=this._roomTemp(e);null!=t&&d.push(j`${t}°`)}if(n.labelHum){const t=this._roomHum(e);null!=t&&d.push(j`${t}%`)}if(n.labelLqi&&e.area){const t=this._roomLqi(e.area);null!=t&&d.push(j`${t}`)}if(n.labelLight){const t=(u=Ed(this._renderPlanHass,this._renderDevices,e,this._virtualLights)).length?{on:u.filter(e=>e.on).length,total:u.length}:null;if(t){const e=0===t.on?this._t("roomcard.light_off"):t.on===t.total?this._t("roomcard.light_on"):this._t("roomcard.light_partial",{on:t.on,total:t.total});d.push(j`${e}`)}}}var u;const p=!!e.area,_=!this._markup;return j`
this._roomLabelKey(t,e.id):G} - @pointerdown=${this._markup?i=>this._labelDown(i,e,t.id):G} - @pointermove=${this._markup?i=>this._labelMove(i,e,t.id):G} - @pointerup=${this._markup?()=>this._labelUp(e):G} - @pointercancel=${this._markup?()=>this._labelUp(e):G} - >${e.name||(this._markup?this._t("room.unnamed"):"")}${p?j`{t.stopPropagation(),this._clickRoom(e)}:G} - @pointerdown=${_?e=>e.stopPropagation():G}>`:G} - ${d.length?j`${d}`:G} - ${"plan"===this._mode?["tl","tr","bl","br"].map(i=>j`this._rlResizeDown(i,e,t.id)} - @pointermove=${e=>this._rlResizeMove(e)} - @pointerup=${()=>this._rlResizeUp()} - @pointercancel=${()=>this._rlResizeUp()}>`):G} -
`}_renderLiveEditorMeasurements(e){const t=e,i=this._opMeasureView,n=this._decorMeasure,r=this._bdLive,o=this._editorRuntime?._furnLive()??null;return j` - ${this._measureAnchor?j`
${this._renderMeasureLabel(t)}
`:G} - ${this._resize?.liveLabels?j`
${this._resize.liveLabels.map(e=>j`
${e.text}
`)}
`:G} - ${i?j`
${i.labels.map(e=>j`
${e.text}
`)}
`:G} - ${n?j`
${n.text}
`:G} - ${o?j`
${o.map(e=>j`
${e.text}
`)}
`:G} - ${r?j`
${r.text}
`:G} - `}get _measureAnchor(){return this._markup&&this._cursorPt?"draw"===this._tool&&this._path.length&&!this._contourClosed?this._path[this._path.length-1]:"split"===this._tool&&this._splitSel?.pts?.length?this._splitSel.pts[this._splitSel.pts.length-1]:null:null}_renderMeasureLabel(e){const t=this._measureAnchor,i=this._cursorPt,n=(i[0]-e.x)/e.w*100,r=(i[1]-e.y)/e.h*100,o=jn(t,i),s=Math.round(10*o)/10,a=function(e,t,i=.001){if(e.length<2||t.length<2)return!1;const n=Math.abs(t[0]-e[0]),r=Math.abs(t[1]-e[1]);if(!Number.isFinite(n)||!Number.isFinite(r)||Math.hypot(n,r)<=i)return!1;const o=Math.max(n,r,1);return n<=i*o||r<=i*o||Math.abs(n-r)<=i*o}(t,i,2e-4*this._gridPitch);return j`
- ${this._fmtLen(t,i)} · ${s}°
`}get _decorMeasure(){const e=this._decorDraft;if(!e||"decor"!==this._mode)return null;const[t,i]=e.a,[n,r]=e.b;if(Math.abs(t-n)<1e-6&&Math.abs(i-r)<1e-6)return null;const o=(t+n)/2,s=(i+r)/2;if("line"===e.kind){const t=jn(e.a,e.b);return{x:o,y:s,on45:Wn(t),text:`${this._fmtLen(e.a,e.b)} · ${Math.round(10*t)/10}°`}}const a=this._fmtLen([t,i],[n,i]),l=this._fmtLen([n,i],[n,r]);if("ellipse"===e.kind){const e=this._fmtLen([0,0],[Math.abs(n-t)/2,0]),a=this._fmtLen([0,0],[0,Math.abs(r-i)/2]);return{x:o,y:s,on45:!1,text:Math.abs(Math.abs(n-t)-Math.abs(r-i))<1e-6?`R ${e}`:`Rx ${e} × Ry ${a}`}}return{x:o,y:s,on45:!1,text:`${a} × ${l} · ${Xn(Ar(Math.abs(n-t),this._cellCm,this._gridPitch)*Ar(Math.abs(r-i),this._cellCm,this._gridPitch)/1e4,this._imperial)}`}}get _alignPoint(){if(this._markup){if("draw"===this._tool&&this._path.length&&!this._contourClosed&&this._cursorPt)return this._cursorPt;if("split"===this._tool&&this._splitSel?.pts?.length&&this._cursorPt)return this._cursorPt;if(this._drag?.id.startsWith("rl_")&&this._drag.moved){const e=this._drag.id.slice(3),t=this._spaceModel()?.rooms.find(t=>t.id===e);return t?(()=>{const e=this._labelPos(t,this._space);return[e.x,e.y]})():null}return null}if("devices"===this._mode&&this._deviceDrag?.moved){const e=this._devices.find(e=>e.id===this._deviceDrag.id);return e?(()=>{const t=this._livePos(e);return[t.x,t.y]})():null}if("decor"===this._mode){if(this._decorDraft)return this._decorDraft.b;if(this._decorMove){const e=this._decorList.find(e=>e.id===this._decorMove.id);if(!e)return null;const t=_v,i=this._decorH;return"line"===e.kind?[e.x1*t,e.y1*i]:[e.x*t,e.y*i]}return null}return null}_alignCandidates(){return this._editorRuntimeOrThrow()._alignCandidates()}_renderAlignGuides(){return this._editorRuntime?._renderAlignGuides()??G}_renderOpeningCenterTick(e){return this._editorRuntimeOrThrow()._renderOpeningCenterTick(e)}_renderOpeningDimensionGuides(e){return this._editorRuntimeOrThrow()._renderOpeningDimensionGuides(e)}_roomCenter(e){if(e.poly){const t=e.poly.length;return[e.poly.reduce((e,t)=>e+t[0],0)/t,e.poly.reduce((e,t)=>e+t[1],0)/t]}return[e.x+e.w/2,e.y+.1*Math.min(e.w,e.h)]}_openingAmt(e){const t=e.contact&&this._renderOpeningEntityAvailable(e.contact)?this._renderPlanHass.states[e.contact]:null;return ci(e.type,t?.state,!!e.invert,t?.attributes?.current_position)}_planEntityAvailable(e){return!!e&&(!Jd(this._fullRegistryHass,e,Zd(this._markers))&&"active"===this._bindingStatus("entity:"+e).kind)}_renderEntityAvailable(e){return!!e&&(!Jd(this._renderPlanHass,e,Zd(this._markers))&&(!!this._renderPlanHass.entities?.[e]&&!!this._renderPlanHass.states?.[e]))}_openingEntityAvailable(e){return function(e,t,i=nd(e)){return!!t&&"active"===dd(e,`entity:${t}`,i).kind}(this.hass,e,this._haRegistry)}_renderOpeningEntityAvailable(e){return t=this._renderPlanHass,!!(i=e)&&!!t?.states?.[i];var t,i}_renderOpeningPlacementPreview(){return this._editorRuntimeOrThrow()._renderOpeningPlacementPreview()}_renderOpenings(e,t){const i=t?this._openingsR.filter(e=>t.includes(e.id)):this._openingsR;if(!i.length)return W``;const n=this._spaceModel();if(!n)return W``;const r=e.color,o=this._spaceWalls,s=this._openCuts(),a=this._openingWallIndexFor(n,s).value;return W`${Re(n.id,Te(i,e=>e.id,e=>{if(e.orphanReason)return W`{t.stopPropagation(),this._editOpening(e)}}> - - ! - `;const t=this._openingAmt(e),i=t>0&&!!e.contact&&this._renderOpeningEntityAvailable(e.contact)?"var(--hp-open)":r,n="gate"===e.type?!e.flip_v:e.flip_v,s=e.partitionHost||o.length||"gate"===e.type?this._openingFace(e,a,!!n):{ox:0,oy:0,cm:0,side:-1},l={type:e.type,length:e.rlen,angle:e.angle,amount:t,flipH:!!e.flip_h,flipV:!!e.flip_v,base:r,tone:i,cellCm:this._cellCm,gridPitch:this._gridPitch,face:s},{half:c,outlineHalf:h,hitHalf:d}=Rp(l),u=Ba(10,this._cellCm),p=Ba(12,this._cellCm);return W` - ${Pp(l)} - - this._opClick(t,e)} - @pointerdown=${t=>this._opPointerDown(t,e)} - @pointermove=${t=>this._opPointerMove(t,e)} - @pointerup=${t=>this._opPointerUp(t,e)} - @pointercancel=${t=>this._opPointerUp(t,e)}> - `}))}`}_renderOpeningLocks(e,t){const i=this._openingsR.filter(e=>!e.orphanReason&&("door"===e.type||"gate"===e.type)&&e.lock&&this._renderOpeningEntityAvailable(e.lock));if(!i.length)return j``;const n=this._spaceModel();if(!n)return j``;const r=this._openCuts(),o=this._openingWallIndexFor(n,r).value;return j`${i.map(i=>{const n=this._renderPlanHass.states[i.lock]?.state,r="locked"===n,s=r||["unlocked","open","opening","unlocking","locking"].includes(String(n)),a="gate"===i.type?this._openingFace(i,o,!i.flip_v):null,l=Mp({x:i.rx,y:i.ry,angle:i.angle,flipV:!!i.flip_v,gateFace:a},this._cellCm)[0],c=t?.get(String(i.id)),h=c?.visualScene??this._scenePoint(l),d=(h[0]-e.x)/e.w*100,u=(h[1]-e.y)/e.h*100;return j`
{"view"===this._mode&&(e.stopPropagation(),this._openingInfo=i)}}> - -
`})}`}async _lockAction(e,t){if(this._openingEntityAvailable(e)){if("unlock"===t){const t=this.hass?.states?.[e]?.attributes?.friendly_name||e,i=await this._confirmDanger({key:"unlock",kind:"warning",title:this._t("confirm.unlock_title"),message:this._t("confirm.unlock_body"),objectName:t,confirmLabel:this._t("opening.unlock_action"),cancelLabel:this._t("btn.cancel")}),n=this._openingInfo;if(!i||!this._openingEntityAvailable(e)||!n||"door"!==n.type&&"gate"!==n.type||n.lock!==e||"locked"!==this.hass?.states?.[e]?.state)return}this.hass?.callService?.("lock",t,{entity_id:e})}}_renderOpeningInfoCard(){const e=this._openingInfo,t="passage"!==e.type&&e.contact&&this._openingEntityAvailable(e.contact)?e.contact:null,i=("door"===e.type||"gate"===e.type)&&e.lock&&this._openingEntityAvailable(e.lock)?e.lock:null,n=t?this.hass.states[t]?.state:null,r=this._openingAmt(e),o=i?this.hass.states[i]?.state:null,s="door"===e.type?"opening.door":"gate"===e.type?"opening.gate":"passage"===e.type?"opening.passage":"opening.window",a="door"===e.type?"mdi:door":"gate"===e.type?"mdi:gate":"passage"===e.type?"mdi:arch":"mdi:window-closed-variant",l="gate"===e.type?r>0?"mdi:gate-open":"mdi:gate":r>0?"mdi:door-open":"mdi:door-closed",c=(e,t,i,n="")=>j`
${t}${i}
`;return j`this._openingInfo=null}> -
- ${t?c(l,this._t("opening.contact_label"),"unavailable"===n||null==n?this._t("opening.state_unknown"):this._t(r>0?"opening.open":"opening.closed"),r>0?"warn":"ok"):G} - ${i?c("locked"===o?"mdi:lock":"mdi:lock-open-variant",this._t("opening.lock_label"),"locked"===o?this._t("opening.locked"):["unlocked","open"].includes(String(o))?this._t("opening.unlocked"):this._t("opening.state_unknown"),"locked"===o?"ok":"warn"):G} - ${i&&("locked"===o||["unlocked","open"].includes(String(o)))?j``:i&&["locking","unlocking"].includes(String(o))?j``:G} - ${t||i?G:j`

${this._t("opening.no_entities")}

`} -
-
- - -
-
`}_renderOpeningDialog(){return this._editorRuntimeOrThrow()._renderOpeningDialog()}_gridLevels(){return this._editorRuntimeOrThrow()._gridLevels()}_renderMarkupDefs(e){return this._editorRuntimeOrThrow()._renderMarkupDefs(e)}_renderPhysicalEditorLayer(){return this._editorRuntimeOrThrow()._renderPhysicalEditorLayer()}_renderHiddenWallDiagnosticOverlay(){return this._editorRuntimeOrThrow()._renderHiddenWallDiagnosticOverlay()}_renderPlanSnapOverlay(){return this._editorRuntimeOrThrow()._renderPlanSnapOverlay()}_syncPlanSnapActiveMarker(e){return this._editorRuntimeOrThrow()._syncPlanSnapActiveMarker(e)}_syncPlanSnapConflictMarkers(e){return this._editorRuntimeOrThrow()._syncPlanSnapConflictMarkers(e)}_planSnapPhysicalSegment(e){return this._editorRuntimeOrThrow()._planSnapPhysicalSegment(e)}_drawPreviewJoinPatchD(e,t){return this._editorRuntimeOrThrow()._drawPreviewJoinPatchD(e,t)}_renderMarkupLayer(e){return this._editorRuntimeOrThrow()._renderMarkupLayer(e)}_renderActiveChainInk(){return this._editorRuntimeOrThrow()._renderActiveChainInk()}_renderPartitionDeleteDialog(){return this._editorRuntimeOrThrow()._renderPartitionDeleteDialog()}_renderRoomDeleteDialog(){return this._editorRuntimeOrThrow()._renderRoomDeleteDialog()}_renderPhysicalDialog(){return this._editorRuntimeOrThrow()._renderPhysicalDialog()}_renderMarkupBar(){return this._editorRuntimeOrThrow()._renderMarkupBar()}_renderDevicesBar(){return this._editorRuntimeOrThrow()._renderDevicesBar()}_renderDeviceInbox(){return this._editorRuntimeOrThrow()._renderDeviceInbox()}_cardEntities(e){const t=this._planHass,i=[],n=new Set,r=e=>{if(!e||n.has(e)||!t.states[e])return;const r=t.entities[e];if("config"===r?.entity_category||"diagnostic"===r?.entity_category)return;n.add(e);const o=e.split(".")[0];["light","switch","fan","humidifier","siren","input_boolean"].includes(o)?i.push({eid:e,kind:"toggle"}):["cover","valve","lock","climate","media_player","vacuum","water_heater"].includes(o)?i.push({eid:e,kind:"open"}):["sensor","binary_sensor","number","select"].includes(o)&&i.push({eid:e,kind:"value"})};for(const i of Ed(t,this._devices,null,this._virtualLights))if(i.device.id===e.id)for(const e of[...i.serviceEids,...i.stateEids])r(e);e.primary&&r(e.primary);for(const t of e.entities)r(t);return i.slice(0,12)}_cardToggle(e){const t=e.split(".")[0];"lock"!==t&&"alarm_control_panel"!==t&&this._planEntityAvailable(e)&&this.hass.callService("homeassistant","toggle",{entity_id:e}).catch(e=>this._showToast(this._t("toast.error",{err:this._errText(e)})))}_renderInfoCard(){const e=this._infoCard,t=e.primary?this.hass.states[e.primary]:void 0,i=t?Xi(this.hass,e.primary)?.text??t.state:null,n=Rg(e.marker?.radar)?e.marker.radar:null,r=n?this._radarLive.frames.get(e.marker?.id||e.id):null,o=n?function(e,t){return!0!==e.enabled?"radar.health_disabled":Tg[t||""]||"radar.health_unknown"}(n,r?.health):null,s=(e.controls??e.marker?.controls??[]).filter(Dn).filter(e=>this._planEntityAvailable(e));return j` -
- ${(()=>{const t=this._cardEntities(e);return t.length?j`
- ${t.map(({eid:e,kind:t})=>{const i=this.hass.states[e],n=this.hass.entities[e]?.name||i?.attributes?.friendly_name||e,r=i?Xi(this.hass,e)?.text??i.state:"",o="on"===i?.state||["open","unlocked","playing","cleaning"].includes(i?.state);return j`
- - ${n} - ${"toggle"===t?j``:"open"===t?j``:j`${r}`} -
`})} -
`:G})()} - ${e.model?j`
${this._t("info.model")}${e.model}
`:G} - ${i&&!this._cardEntities(e).length?j`
${this._t("info.state")}${i}
`:G} - ${o?j`
${this._t("radar.health")} - ${this._t(o)}
`:G} - ${Ni(e.link)?j`
${this._t("info.link")} - ${e.link}
`:G} - ${e.description?j`
${e.description}
`:G} - ${e.pdfs&&e.pdfs.length?j`
${this._t("info.manuals")} - ${e.pdfs.map(e=>j` - ${e.name}`)}
`:G} - ${s.length?j`
${this._t("info.controls")} - - ${s.map(e=>{const t=this.hass.states[e],i="on"===t?.state;return j` - - ${t?.attributes?.friendly_name||e}`})} -
`:G} - ${e.model||i||o||e.link||e.description||e.pdfs&&e.pdfs.length||s.length?G:j`
${this._t("info.none")}
`} -
-
- - ${e.primary?j``:G} - -
-
`}_markerValueBadgeFields(e){return this._editorRuntimeOrThrow()._markerValueBadgeFields(e)}_markerDraft(e){return this._editorRuntimeOrThrow()._markerDraft(e)}_markerPreviewDevice(e){return this._editorRuntimeOrThrow()._markerPreviewDevice(e)}_markerPreviewDevices(e){return this._editorRuntimeOrThrow()._markerPreviewDevices(e)}_toggleIntent(e,t=this._devices){return Fu({hass:this._planHass,registryHass:this._fullRegistryHass,devices:t,device:e,virtualLights:this._virtualLights})}_toggleIntentForDialog(e){return this._editorRuntimeOrThrow()._toggleIntentForDialog(e)}_toggleStateText(e,t){const i=this._planHass?.states?.[e]||this.hass?.states?.[e];try{return i&&"function"==typeof this.hass?.formatEntityState?this.hass.formatEntityState(i):t}catch{return t}}_toggleConfirmationStateText(e){const t=String(e.state||"unknown"),i=e.entityId?this._toggleStateText(e.entityId,t):t;if(i.trim().toLocaleLowerCase()!==t.trim().toLocaleLowerCase())return i;const n={on:"confirm.state_on",off:"confirm.state_off",open:"confirm.state_open",closed:"confirm.state_closed",opening:"confirm.state_opening",closing:"confirm.state_closing",unknown:"confirm.state_unknown"}[t];return n?this._t(n):t.replaceAll("_"," ").replaceAll("-"," ")}_toggleConfirmationLines(e){const t={"turn-on":"confirm.state_on","turn-off":"confirm.state_off",open:"confirm.state_open",close:"confirm.state_closed",stop:"confirm.state_stopped"};return function(e,t){if(!Iu(e)||!e.nextEffect||!e.targets.length)return[];const i="group"===e.kind,n=i?e.targets.filter(e=>"on"===e.state).length:0,r=i?0===n?t.groupAllOff():t.groupCurrent(n,e.targets.length):t.state(e.targets[0]);let o;return o="toggle"===e.nextEffect?t.expectedByHa():i&&"turn-on"===e.nextEffect?t.groupAllOn():i&&"turn-off"===e.nextEffect?t.groupAllOff():t.effect(e.nextEffect),[t.current(r),t.expected(o),...e.skippedTargets.length?[t.unavailable(e.skippedTargets.length)]:[]]}(e,{state:e=>this._toggleConfirmationStateText(e),current:e=>this._t("confirm.current_state",{state:e}),expected:e=>this._t("confirm.expected_state",{state:e}),groupCurrent:(e,t)=>this._t("confirm.group_current",{on:e,total:t}),groupAllOn:()=>this._t("confirm.group_all_on"),groupAllOff:()=>this._t("confirm.group_all_off"),unavailable:e=>this._t("confirm.unavailable_targets",{count:e}),effect:e=>this._t(t[e]),expectedByHa:()=>this._t("confirm.expected_by_ha")})}_toggleHintLines(e){return this._editorRuntimeOrThrow()._toggleHintLines(e)}_effectiveStoredTapAction(e,t){return this._editorRuntimeOrThrow()._effectiveStoredTapAction(e,t)}_effectiveMarkerTapAction(e,t=this._markerPreviewDevice(e)){return this._editorRuntimeOrThrow()._effectiveMarkerTapAction(e,t)}_announceToggleDraft(e){return this._editorRuntimeOrThrow()._announceToggleDraft(e)}_valueBadgeForBinding(e,t){return this._editorRuntimeOrThrow()._valueBadgeForBinding(e,t)}_markerSpatialSource(e){return this._editorRuntimeOrThrow()._markerSpatialSource(e)}_markerAutoHasSpatialSource(e){return this._editorRuntimeOrThrow()._markerAutoHasSpatialSource(e)}_setMarkerLightRole(e){return this._editorRuntimeOrThrow()._setMarkerLightRole(e)}_controlRefInfo(e){return this._editorRuntimeOrThrow()._controlRefInfo(e)}_valueBadgeCandidateLabel(e){return this._editorRuntimeOrThrow()._valueBadgeCandidateLabel(e)}_controlCandidates(e){return this._editorRuntimeOrThrow()._controlCandidates(e)}_addControlRef(e,t){return this._editorRuntimeOrThrow()._addControlRef(e,t)}_setMarkerGlowMode(e){return this._editorRuntimeOrThrow()._setMarkerGlowMode(e)}_renderMarkerDialog(){return this._editorRuntimeOrThrow()._renderMarkerDialog()}_renderSpaceDialog(){return this._onboardingRuntime&&this._spaceDialog&&this._spaceDialogUsesOnboardingRuntime(this._spaceDialog.mode)?this._onboardingRuntime._renderSpaceDialog():this._editorRuntimeOrThrow()._renderSpaceDialog()}_renderMergeDialog(){return this._editorRuntimeOrThrow()._renderMergeDialog()}_renderCardPreview(e,t,i){const n=18*e;return j`
- - ${this._t("preview.room_name")} - - 22.4° · - 45% · - ${this._t("roomcard.light_partial",{on:1,total:3})} - -
`}_renderRoomSource(e){return this._editorRuntimeOrThrow()._renderRoomSource(e)}_renderRoomDialog(){return this._editorRuntimeOrThrow()._renderRoomDialog()}}wv.properties={_tabDrag:{state:!0},_hdrH:{state:!0},_booting:{state:!0},_bootFading:{state:!0},_bootSoft:{state:!0},_continuityEpoch:{state:!0},_editorRuntimeLoadingVisible:{state:!0},_backdropGuard:{state:!0},_tapConfirm:{state:!0},_dangerConfirm:{state:!0},hass:{attribute:!1},panelHost:{type:Boolean,attribute:"panel-host",reflect:!0},narrow:{attribute:!1},_config:{state:!0},_space:{state:!0},_devices:{state:!0},_selId:{state:!0},_toast:{state:!0},_mode:{state:!0},_tool:{state:!0},_wallDialog:{state:!0},_drawWallField:{state:!0},_activeWallChainId:{state:!0},_physicalSel:{state:!0},_physicalDialog:{state:!0},_partitionDeleteDialog:{state:!0},_roomDeleteDialog:{state:!0},_physicalDrag:{state:!0},_physicalRotate:{state:!0},_duplicateColumnId:{state:!0},_opMeasure:{state:!0},_path:{state:!0},_cursorPt:{state:!0},_mergeSel:{state:!0},_openingPreset:{state:!0},_openingDialog:{state:!0},_openingInfo:{state:!0},_mergeDialog:{state:!0},_splitSel:{state:!0},_decorTool:{state:!0},_decorStyle:{state:!0},_decorDraft:{state:!0},_decorSel:{state:!0},_decorEraseConfirm:{state:!0},_decorTextDialog:{state:!0},_decorShapeDialog:{state:!0},_backdropDialog:{state:!0},_furnPalette:{state:!0},_decorImagePalette:{state:!0},_decorAssetCatalog:{state:!0},_decorAssetBusy:{state:!0},_furnCategory:{state:!0},_furnPreviewInput:{state:!0},_bdDrag:{state:!0},_dtBox:{state:!0},_dtDrag:{state:!0},_kioskDialog:{state:!0},_vacFit:{state:!0},_vacAllCamerasFor:{state:!0},_vacCalConfirm:{state:!0},_kioskDots:{state:!0},_areaSel:{state:!0},_nameSel:{state:!0},_roomDialog:{state:!0},_roomEditId:{state:!0},_roomFill:{state:!0},_roomCustomFill:{state:!0},_roomTempMin:{state:!0},_roomTempMax:{state:!0},_roomTempSrc:{state:!0},_roomHumSrc:{state:!0},_roomSrcOpen:{state:!0},_roomSrcFilter:{state:!0},_roomNameScale:{state:!0},_roomLabelScale:{state:!0},_spaceDialog:{state:!0},_infoCard:{state:!0},_deviceInbox:{state:!0},_rulesDialog:{state:!0},_settingsDialog:{state:!0},_pdfDialog:{state:!0},_supportDialog:{state:!0},_alignDialog:{state:!0},_preflightClipboardFallback:{state:!0},_backupExportDialog:{state:!0},_backupImportDialog:{state:!0},_importDialog:{state:!0},_markerDialog:{state:!0}},wv.ZOOM_MAX=8,wv.ZOOM_MIN=1/3,wv.styles=[ap,mg],customElements.get("houseplan-card")||customElements.define("houseplan-card",wv),window.customCards=window.customCards||[],window.customCards.find(e=>"houseplan-card"===e.type)||window.customCards.push({type:"houseplan-card",name:"House Plan Card",description:"Interactive house plan: spaces, rooms and devices with live states and drag layout."}),console.info(`%c HOUSEPLAN-CARD %c v${iv} `,"background:#3ea6ff;color:#04121f;font-weight:700","");export{Gl as $,G as A,zp as B,k_ as C,le as D,U as E,Fg as F,wi as G,qr as H,$i as I,Mi as J,Ut as K,Ci as L,il as M,Ua as N,xo as O,ni as P,No as Q,C_ as R,T_ as S,ws as T,ro as U,Ko as V,_i as W,Go as X,q_ as Y,Hl as Z,sl as _,lh as a,br as a$,jl as a0,Ds as a1,ps as a2,Ts as a3,Qs as a4,Es as a5,Cc as a6,Rc as a7,si as a8,el as a9,Zd as aA,Jd as aB,Rg as aC,ti as aD,oi as aE,Pn as aF,Un as aG,pm as aH,Dr as aI,dm as aJ,zl as aK,Bl as aL,tc as aM,Ja as aN,ic as aO,Yl as aP,vs as aQ,ia as aR,is as aS,_a as aT,Na as aU,L_ as aV,ga as aW,Ps as aX,zg as aY,_n as aZ,vr as a_,Ju as aa,sp as ab,As as ac,So as ad,rp as ae,Xu as af,Qo as ag,Fs as ah,Qu as ai,oa as aj,la as ak,yo as al,wo as am,eo as an,N_ as ao,Xo as ap,tl as aq,Vo as ar,Va as as,Ka as at,en as au,tn as av,Ki as aw,Yi as ax,Za as ay,cc as az,ih as b,D_ as b$,yr as b0,fr as b1,pn as b2,Oe as b3,Sp as b4,lf as b5,Po as b6,ol as b7,Qt as b8,ei as b9,Or as bA,Lr as bB,Hr as bC,Ar as bD,Rr as bE,Tr as bF,zr as bG,jn as bH,Mr as bI,Cr as bJ,Jl as bK,Er as bL,Ql as bM,Vl as bN,ql as bO,ec as bP,Xl as bQ,Zl as bR,sm as bS,es as bT,Rp as bU,np as bV,Yf as bW,ip as bX,ha as bY,Wf as bZ,Xf as b_,jr as ba,fa as bb,kc as bc,H_ as bd,ko as be,Hu as bf,W_ as bg,yi as bh,mi as bi,Fi as bj,Oa as bk,xa as bl,ka as bm,Zo as bn,Jo as bo,ta as bp,Sl as bq,Fa as br,Pa as bs,Yn as bt,Xn as bu,ki as bv,fs as bw,gs as bx,U_ as by,G_ as bz,j as c,jf as c$,li as c0,ep as c1,op as c2,Di as c3,fi as c4,ai as c5,vi as c6,ts as c7,zi as c8,Mn as c9,X_ as cA,j_ as cB,Fr as cC,mn as cD,Ig as cE,lo as cF,wr as cG,Ee as cH,qe as cI,Ne as cJ,Wc as cK,Yc as cL,rh as cM,Ec as cN,Xc as cO,Uc as cP,Gc as cQ,nh as cR,eh as cS,Fc as cT,Dc as cU,Bn as cV,Ac as cW,qn as cX,ci as cY,Uf as cZ,Pp as c_,Gp as ca,Vp as cb,xd as cc,Tu as cd,Li as ce,Ui as cf,Kn as cg,Ln as ch,Kd as ci,em as cj,bo as ck,Xd as cl,Vd as cm,un as cn,cn as co,ln as cp,ja as cq,I_ as cr,an as cs,sn as ct,on as cu,rn as cv,qa as cw,Sc as cx,xc as cy,ev as cz,na as d,Ia as d$,Ml as d0,zs as d1,ls as d2,cs as d3,Ie as d4,lu as d5,Kp as d6,Yp as d7,nu as d8,Nu as d9,eu as dA,iu as dB,Qa as dC,Fl as dD,Pc as dE,tf as dF,nf as dG,$p as dH,of as dI,xl as dJ,rf as dK,sf as dL,Ra as dM,Ys as dN,Mp as dO,Ri as dP,y_ as dQ,$f as dR,Mf as dS,uf as dT,w_ as dU,La as dV,Br as dW,za as dX,ca as dY,Pr as dZ,Ir as d_,Nd as da,Ed as db,Fd as dc,$d as dd,Dn as de,kd as df,Yd as dg,Rn as dh,p_ as di,Op as dj,zd as dk,Id as dl,Md as dm,Su as dn,Bi as dp,Hi as dq,Ep as dr,Ni as ds,$c as dt,Wa as du,Mc as dv,qi as dw,ji as dx,$o as dy,pi as dz,pe as e,Tl as e0,V_ as e1,Ea as e2,hm as e3,wp as e4,dp as e5,gp as e6,up as e7,Jt as e8,kg as e9,K_ as ea,Xi as eb,Zi as ec,Wt as ed,wv as ee,th as f,Co as g,Do as h,_e as i,To as j,Ba as k,kp as l,Fo as m,sh as n,dh as o,o as p,he as q,hh as r,nn as s,Kt as t,ap as u,xp as v,W as w,Zp as x,v_ as y,b_ as z}; diff --git a/custom_components/houseplan/frontend/houseplan-assets/houseplan-card-Cythr3Rg.js b/custom_components/houseplan/frontend/houseplan-assets/houseplan-card-Cythr3Rg.js new file mode 100644 index 00000000..dd740d16 --- /dev/null +++ b/custom_components/houseplan/frontend/houseplan-assets/houseplan-card-Cythr3Rg.js @@ -0,0 +1,1112 @@ +globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="3f783ed7cf5daff202a910aa89044f88f605a65af7f46794277dddf04333e502";const e=globalThis,t=e.ShadowRoot&&(void 0===e.ShadyCSS||e.ShadyCSS.nativeShadow)&&"adoptedStyleSheets"in Document.prototype&&"replace"in CSSStyleSheet.prototype,i=Symbol(),n=new WeakMap;let r=class{constructor(e,t,n){if(this._$cssResult$=!0,n!==i)throw Error("CSSResult is not constructable. Use `unsafeCSS` or `css` instead.");this.cssText=e,this.t=t}get styleSheet(){let e=this.o;const i=this.t;if(t&&void 0===e){const t=void 0!==i&&1===i.length;t&&(e=n.get(i)),void 0===e&&((this.o=e=new CSSStyleSheet).replaceSync(this.cssText),t&&n.set(i,e))}return e}toString(){return this.cssText}};const o=(e,...t)=>{const n=1===e.length?e[0]:t.reduce((t,i,n)=>t+(e=>{if(!0===e._$cssResult$)return e.cssText;if("number"==typeof e)return e;throw Error("Value passed to 'css' function must be a 'css' function result: "+e+". Use 'unsafeCSS' to pass non-literal values, but take care to ensure page security.")})(i)+e[n+1],e[0]);return new r(n,e,i)},s=t?e=>e:e=>e instanceof CSSStyleSheet?(e=>{let t="";for(const i of e.cssRules)t+=i.cssText;return(e=>new r("string"==typeof e?e:e+"",void 0,i))(t)})(e):e,{is:a,defineProperty:l,getOwnPropertyDescriptor:c,getOwnPropertyNames:h,getOwnPropertySymbols:d,getPrototypeOf:u}=Object,p=globalThis,_=p.trustedTypes,m=_?_.emptyScript:"",g=p.reactiveElementPolyfillSupport,f=(e,t)=>e,v={toAttribute(e,t){switch(t){case Boolean:e=e?m:null;break;case Object:case Array:e=null==e?e:JSON.stringify(e)}return e},fromAttribute(e,t){let i=e;switch(t){case Boolean:i=null!==e;break;case Number:i=null===e?null:Number(e);break;case Object:case Array:try{i=JSON.parse(e)}catch(e){i=null}}return i}},y=(e,t)=>!a(e,t),b={attribute:!0,type:String,converter:v,reflect:!1,useDefault:!1,hasChanged:y};Symbol.metadata??=Symbol("metadata"),p.litPropertyMetadata??=new WeakMap;let w=class extends HTMLElement{static addInitializer(e){this._$Ei(),(this.l??=[]).push(e)}static get observedAttributes(){return this.finalize(),this._$Eh&&[...this._$Eh.keys()]}static createProperty(e,t=b){if(t.state&&(t.attribute=!1),this._$Ei(),this.prototype.hasOwnProperty(e)&&((t=Object.create(t)).wrapped=!0),this.elementProperties.set(e,t),!t.noAccessor){const i=Symbol(),n=this.getPropertyDescriptor(e,i,t);void 0!==n&&l(this.prototype,e,n)}}static getPropertyDescriptor(e,t,i){const{get:n,set:r}=c(this.prototype,e)??{get(){return this[t]},set(e){this[t]=e}};return{get:n,set(t){const o=n?.call(this);r?.call(this,t),this.requestUpdate(e,o,i)},configurable:!0,enumerable:!0}}static getPropertyOptions(e){return this.elementProperties.get(e)??b}static _$Ei(){if(this.hasOwnProperty(f("elementProperties")))return;const e=u(this);e.finalize(),void 0!==e.l&&(this.l=[...e.l]),this.elementProperties=new Map(e.elementProperties)}static finalize(){if(this.hasOwnProperty(f("finalized")))return;if(this.finalized=!0,this._$Ei(),this.hasOwnProperty(f("properties"))){const e=this.properties,t=[...h(e),...d(e)];for(const i of t)this.createProperty(i,e[i])}const e=this[Symbol.metadata];if(null!==e){const t=litPropertyMetadata.get(e);if(void 0!==t)for(const[e,i]of t)this.elementProperties.set(e,i)}this._$Eh=new Map;for(const[e,t]of this.elementProperties){const i=this._$Eu(e,t);void 0!==i&&this._$Eh.set(i,e)}this.elementStyles=this.finalizeStyles(this.styles)}static finalizeStyles(e){const t=[];if(Array.isArray(e)){const i=new Set(e.flat(1/0).reverse());for(const e of i)t.unshift(s(e))}else void 0!==e&&t.push(s(e));return t}static _$Eu(e,t){const i=t.attribute;return!1===i?void 0:"string"==typeof i?i:"string"==typeof e?e.toLowerCase():void 0}constructor(){super(),this._$Ep=void 0,this.isUpdatePending=!1,this.hasUpdated=!1,this._$Em=null,this._$Ev()}_$Ev(){this._$ES=new Promise(e=>this.enableUpdating=e),this._$AL=new Map,this._$E_(),this.requestUpdate(),this.constructor.l?.forEach(e=>e(this))}addController(e){(this._$EO??=new Set).add(e),void 0!==this.renderRoot&&this.isConnected&&e.hostConnected?.()}removeController(e){this._$EO?.delete(e)}_$E_(){const e=new Map,t=this.constructor.elementProperties;for(const i of t.keys())this.hasOwnProperty(i)&&(e.set(i,this[i]),delete this[i]);e.size>0&&(this._$Ep=e)}createRenderRoot(){const i=this.shadowRoot??this.attachShadow(this.constructor.shadowRootOptions);return((i,n)=>{if(t)i.adoptedStyleSheets=n.map(e=>e instanceof CSSStyleSheet?e:e.styleSheet);else for(const t of n){const n=document.createElement("style"),r=e.litNonce;void 0!==r&&n.setAttribute("nonce",r),n.textContent=t.cssText,i.appendChild(n)}})(i,this.constructor.elementStyles),i}connectedCallback(){this.renderRoot??=this.createRenderRoot(),this.enableUpdating(!0),this._$EO?.forEach(e=>e.hostConnected?.())}enableUpdating(e){}disconnectedCallback(){this._$EO?.forEach(e=>e.hostDisconnected?.())}attributeChangedCallback(e,t,i){this._$AK(e,i)}_$ET(e,t){const i=this.constructor.elementProperties.get(e),n=this.constructor._$Eu(e,i);if(void 0!==n&&!0===i.reflect){const r=(void 0!==i.converter?.toAttribute?i.converter:v).toAttribute(t,i.type);this._$Em=e,null==r?this.removeAttribute(n):this.setAttribute(n,r),this._$Em=null}}_$AK(e,t){const i=this.constructor,n=i._$Eh.get(e);if(void 0!==n&&this._$Em!==n){const e=i.getPropertyOptions(n),r="function"==typeof e.converter?{fromAttribute:e.converter}:void 0!==e.converter?.fromAttribute?e.converter:v;this._$Em=n;const o=r.fromAttribute(t,e.type);this[n]=o??this._$Ej?.get(n)??o,this._$Em=null}}requestUpdate(e,t,i,n=!1,r){if(void 0!==e){const o=this.constructor;if(!1===n&&(r=this[e]),i??=o.getPropertyOptions(e),!((i.hasChanged??y)(r,t)||i.useDefault&&i.reflect&&r===this._$Ej?.get(e)&&!this.hasAttribute(o._$Eu(e,i))))return;this.C(e,t,i)}!1===this.isUpdatePending&&(this._$ES=this._$EP())}C(e,t,{useDefault:i,reflect:n,wrapped:r},o){i&&!(this._$Ej??=new Map).has(e)&&(this._$Ej.set(e,o??t??this[e]),!0!==r||void 0!==o)||(this._$AL.has(e)||(this.hasUpdated||i||(t=void 0),this._$AL.set(e,t)),!0===n&&this._$Em!==e&&(this._$Eq??=new Set).add(e))}async _$EP(){this.isUpdatePending=!0;try{await this._$ES}catch(e){Promise.reject(e)}const e=this.scheduleUpdate();return null!=e&&await e,!this.isUpdatePending}scheduleUpdate(){return this.performUpdate()}performUpdate(){if(!this.isUpdatePending)return;if(!this.hasUpdated){if(this.renderRoot??=this.createRenderRoot(),this._$Ep){for(const[e,t]of this._$Ep)this[e]=t;this._$Ep=void 0}const e=this.constructor.elementProperties;if(e.size>0)for(const[t,i]of e){const{wrapped:e}=i,n=this[t];!0!==e||this._$AL.has(t)||void 0===n||this.C(t,void 0,i,n)}}let e=!1;const t=this._$AL;try{e=this.shouldUpdate(t),e?(this.willUpdate(t),this._$EO?.forEach(e=>e.hostUpdate?.()),this.update(t)):this._$EM()}catch(t){throw e=!1,this._$EM(),t}e&&this._$AE(t)}willUpdate(e){}_$AE(e){this._$EO?.forEach(e=>e.hostUpdated?.()),this.hasUpdated||(this.hasUpdated=!0,this.firstUpdated(e)),this.updated(e)}_$EM(){this._$AL=new Map,this.isUpdatePending=!1}get updateComplete(){return this.getUpdateComplete()}getUpdateComplete(){return this._$ES}shouldUpdate(e){return!0}update(e){this._$Eq&&=this._$Eq.forEach(e=>this._$ET(e,this[e])),this._$EM()}updated(e){}firstUpdated(e){}};w.elementStyles=[],w.shadowRootOptions={mode:"open"},w[f("elementProperties")]=new Map,w[f("finalized")]=new Map,g?.({ReactiveElement:w}),(p.reactiveElementVersions??=[]).push("2.1.2");const k=globalThis,x=e=>e,S=k.trustedTypes,$=S?S.createPolicy("lit-html",{createHTML:e=>e}):void 0,M="$lit$",R=`lit$${Math.random().toFixed(9).slice(2)}$`,C="?"+R,T=`<${C}>`,D=document,A=()=>D.createComment(""),P=e=>null===e||"object"!=typeof e&&"function"!=typeof e,F=Array.isArray,z="[ \t\n\f\r]",I=/<(?:(!--|\/[^a-zA-Z])|(\/?[a-zA-Z][^>\s]*)|(\/?$))/g,O=/-->/g,E=/>/g,N=RegExp(`>|${z}(?:([^\\s"'>=/]+)(${z}*=${z}*(?:[^ \t\n\f\r"'\`<>=]|("|')|))|$)`,"g"),H=/'/g,L=/"/g,B=/^(?:script|style|textarea|title)$/i,q=e=>(t,...i)=>({_$litType$:e,strings:t,values:i}),j=q(1),W=q(2),U=Symbol.for("lit-noChange"),G=Symbol.for("lit-nothing"),V=new WeakMap,K=D.createTreeWalker(D,129);function Y(e,t){if(!F(e)||!e.hasOwnProperty("raw"))throw Error("invalid template strings array");return void 0!==$?$.createHTML(t):t}const X=(e,t)=>{const i=e.length-1,n=[];let r,o=2===t?"":3===t?"":"",s=I;for(let t=0;t"===l[0]?(s=r??I,c=-1):void 0===l[1]?c=-2:(c=s.lastIndex-l[2].length,a=l[1],s=void 0===l[3]?N:'"'===l[3]?L:H):s===L||s===H?s=N:s===O||s===E?s=I:(s=N,r=void 0);const d=s===N&&e[t+1].startsWith("/>")?" ":"";o+=s===I?i+T:c>=0?(n.push(a),i.slice(0,c)+M+i.slice(c)+R+d):i+R+(-2===c?t:d)}return[Y(e,o+(e[i]||"")+(2===t?"":3===t?"":"")),n]};class Z{constructor({strings:e,_$litType$:t},i){let n;this.parts=[];let r=0,o=0;const s=e.length-1,a=this.parts,[l,c]=X(e,t);if(this.el=Z.createElement(l,i),K.currentNode=this.el.content,2===t||3===t){const e=this.el.content.firstChild;e.replaceWith(...e.childNodes)}for(;null!==(n=K.nextNode())&&a.length0){n.textContent=S?S.emptyScript:"";for(let i=0;iF(e)||"function"==typeof e?.[Symbol.iterator])(e)?this.k(e):this._(e)}O(e){return this._$AA.parentNode.insertBefore(e,this._$AB)}T(e){this._$AH!==e&&(this._$AR(),this._$AH=this.O(e))}_(e){this._$AH!==G&&P(this._$AH)?this._$AA.nextSibling.data=e:this.T(D.createTextNode(e)),this._$AH=e}$(e){const{values:t,_$litType$:i}=e,n="number"==typeof i?this._$AC(e):(void 0===i.el&&(i.el=Z.createElement(Y(i.h,i.h[0]),this.options)),i);if(this._$AH?._$AD===n)this._$AH.p(t);else{const e=new Q(n,this),i=e.u(this.options);e.p(t),this.T(i),this._$AH=e}}_$AC(e){let t=V.get(e.strings);return void 0===t&&V.set(e.strings,t=new Z(e)),t}k(e){F(this._$AH)||(this._$AH=[],this._$AR());const t=this._$AH;let i,n=0;for(const r of e)n===t.length?t.push(i=new ee(this.O(A()),this.O(A()),this,this.options)):i=t[n],i._$AI(r),n++;n2||""!==i[0]||""!==i[1]?(this._$AH=Array(i.length-1).fill(new String),this.strings=i):this._$AH=G}_$AI(e,t=this,i,n){const r=this.strings;let o=!1;if(void 0===r)e=J(this,e,t,0),o=!P(e)||e!==this._$AH&&e!==U,o&&(this._$AH=e);else{const n=e;let s,a;for(e=r[0],s=0;s{const n=i?.renderBefore??t;let r=n._$litPart$;if(void 0===r){const e=i?.renderBefore??null;n._$litPart$=r=new ee(t.insertBefore(A(),e),e,void 0,i??{})}return r._$AI(e),r},ce=globalThis;let he=class extends w{constructor(){super(...arguments),this.renderOptions={host:this},this._$Do=void 0}createRenderRoot(){const e=super.createRenderRoot();return this.renderOptions.renderBefore??=e.firstChild,e}update(e){const t=this.render();this.hasUpdated||(this.renderOptions.isConnected=this.isConnected),super.update(e),this._$Do=le(t,this.renderRoot,this.renderOptions)}connectedCallback(){super.connectedCallback(),this._$Do?.setConnected(!0)}disconnectedCallback(){super.disconnectedCallback(),this._$Do?.setConnected(!1)}render(){return U}};he._$litElement$=!0,he.finalized=!0,ce.litElementHydrateSupport?.({LitElement:he});const de=ce.litElementPolyfillSupport;de?.({LitElement:he}),(ce.litElementVersions??=[]).push("4.2.2");const ue=2,pe=e=>(...t)=>({_$litDirective$:e,values:t});let _e=class{constructor(e){}get _$AU(){return this._$AM._$AU}_$AT(e,t,i){this._$Ct=e,this._$AM=t,this._$Ci=i}_$AS(e,t){return this.update(e,t)}update(e,t){return this.render(...t)}};const{I:me}=se,ge=e=>e,fe=(e,t)=>void 0!==e?._$litType$,ve=()=>document.createComment(""),ye=(e,t,i)=>{const n=e._$AA.parentNode,r=void 0===t?e._$AB:t._$AA;if(void 0===i){const t=n.insertBefore(ve(),r),o=n.insertBefore(ve(),r);i=new me(t,o,e,e.options)}else{const t=i._$AB.nextSibling,o=i._$AM,s=o!==e;if(s){let t;i._$AQ?.(e),i._$AM=e,void 0!==i._$AP&&(t=e._$AU)!==o._$AU&&i._$AP(t)}if(t!==r||s){let e=i._$AA;for(;e!==t;){const t=ge(e).nextSibling;ge(n).insertBefore(e,r),e=t}}}return i},be=(e,t,i=e)=>(e._$AI(t,i),e),we={},ke=(e,t=we)=>e._$AH=t,xe=e=>e._$AH,Se=e=>{e._$AR(),e._$AA.remove()},$e=e=>(e=>null!=e?._$litType$?.h)(e)?e._$litType$.h:e.strings,Me=pe(class extends _e{constructor(e){super(e),this.et=new WeakMap}render(e){return[e]}update(e,[t]){const i=fe(this.it)?$e(this.it):null,n=fe(t)?$e(t):null;if(null!==i&&(null===n||i!==n)){const t=xe(e).pop();let n=this.et.get(i);if(void 0===n){const e=document.createDocumentFragment();n=le(G,e),n.setConnected(!1),this.et.set(i,n)}ke(n,[t]),ye(n,void 0,t)}if(null!==n){if(null===i||i!==n){const t=this.et.get(n);if(void 0!==t){const i=xe(t).pop();(e=>{e._$AR()})(e),ye(e,void 0,i),ke(e,[i])}}this.it=t}else this.it=void 0;return this.render(t)}}),Re=pe(class extends _e{constructor(){super(...arguments),this.key=G}render(e,t){return this.key=e,t}update(e,[t,i]){return t!==this.key&&(ke(e),this.key=t),i}}),Ce=(e,t,i)=>{const n=new Map;for(let r=t;r<=i;r++)n.set(e[r],r);return n},Te=pe(class extends _e{constructor(e){if(super(e),e.type!==ue)throw Error("repeat() can only be used in text expressions")}dt(e,t,i){let n;void 0===i?i=t:void 0!==t&&(n=t);const r=[],o=[];let s=0;for(const t of e)r[s]=n?n(t,s):s,o[s]=i(t,s),s++;return{values:o,keys:r}}render(e,t,i){return this.dt(e,t,i).values}update(e,[t,i,n]){const r=xe(e),{values:o,keys:s}=this.dt(t,i,n);if(!Array.isArray(r))return this.ut=s,o;const a=this.ut??=[],l=[];let c,h,d=0,u=r.length-1,p=0,_=o.length-1;for(;d<=u&&p<=_;)if(null===r[d])d++;else if(null===r[u])u--;else if(a[d]===s[p])l[p]=be(r[d],o[p]),d++,p++;else if(a[u]===s[_])l[_]=be(r[u],o[_]),u--,_--;else if(a[d]===s[_])l[_]=be(r[d],o[_]),ye(e,l[_+1],r[d]),d++,_--;else if(a[u]===s[p])l[p]=be(r[u],o[p]),ye(e,r[d],r[u]),u--,p++;else if(void 0===c&&(c=Ce(s,p,_),h=Ce(a,d,u)),c.has(a[d]))if(c.has(a[u])){const t=h.get(s[p]),i=void 0!==t?r[t]:null;if(null===i){const t=ye(e,r[d]);be(t,o[p]),l[p]=t}else l[p]=be(i,o[p]),ye(e,r[d],i),r[t]=null;p++}else Se(r[u]),u--;else Se(r[d]),d++;for(;p<=_;){const t=ye(e,l[_+1]);be(t,o[p]),l[p++]=t}for(;d<=u;){const e=r[d++];null!==e&&Se(e)}return this.ut=s,ke(e,l),U}}),De=new WeakMap;let Ae=0;class Pe extends he{constructor(){super(...arguments),this.title="",this.icon="",this.wide=!1,this.alert=!1,this.describedBy="",this.dismissOnScrim=!1,this.flexContent=!1,this.hass=null,this._opener=null,this._focusRoot=null,this._useHaDialog=null,this._closing=!1,this._overlays=[],this._titleId="hp-dialog-title-"+ ++Ae,this._focusInitial=()=>{const e=this._focusableElements(),t=e.find(e=>e.hasAttribute("autofocus"))||e[0]||(this._usesHaDialog()?null:this.renderRoot.querySelector(".close"))||this.renderRoot.querySelector(".surface")||this.renderRoot.querySelector("ha-dialog");t?.focus({preventScroll:!0})},this._requestClose=()=>{this._closing||(this._closing=!0,this.dispatchEvent(new CustomEvent("hp-close",{bubbles:!0,composed:!0})))},this._onKeyDown=e=>{if("Escape"===e.key){e.preventDefault(),e.stopImmediatePropagation(),this._pruneOverlays();const t=this._overlays[this._overlays.length-1];return t?void this._closeOverlay(t,"escape"):void this._requestClose()}if("Tab"!==e.key||this._usesHaDialog())return;const t=this.renderRoot.querySelector(".close"),i=t?[t,...this._focusableElements()]:this._focusableElements();if(!i.length)return e.preventDefault(),void this.renderRoot.querySelector(".surface")?.focus({preventScroll:!0});const n=this._deepActiveElement(),r=i[0],o=i[i.length-1];!e.shiftKey||n!==r&&i.includes(n)?e.shiftKey||n!==o||(e.preventDefault(),r.focus()):(e.preventDefault(),o.focus())},this._onFallbackCancel=e=>{e.preventDefault(),this._requestClose()},this._onFallbackClick=e=>{this.dismissOnScrim&&e.target===e.currentTarget&&this._requestClose()}}_usesHaDialog(){return!0===this._useHaDialog&&!this.alert}connectedCallback(){this.setAttribute("data-hp","dialog"),super.connectedCallback(),this._opener=this._deepActiveElement();const e=this.getRootNode();this._focusRoot=e;const t=De.get(e)||{dialogs:new Set,opener:this._opener};t.dialogs.add(this),De.set(e,t),null===this._useHaDialog&&(this._useHaDialog=!!customElements.get("ha-dialog")),this.addEventListener("keydown",this._onKeyDown,!0),queueMicrotask(()=>{this._ensureNativeModal()&&this._focusInitial()})}disconnectedCallback(){this.removeEventListener("keydown",this._onKeyDown,!0);const e=[...this._overlays];this._overlays=[];for(const t of e.reverse())t.close("disconnect");const t=this._focusRoot,i=this._opener;this._opener=null,this._focusRoot=null;const n=t?De.get(t):void 0;n?.dialogs.delete(this),super.disconnectedCallback(),t&&n&&requestAnimationFrame(()=>{const e=De.get(t);if(!e)return;if(!e.dialogs.size)return e.opener?.isConnected&&e.opener.focus({preventScroll:!0}),void De.delete(t);const n=i?.closest("hp-dialog");i?.isConnected&&n&&e.dialogs.has(n)&&i.focus({preventScroll:!0})})}firstUpdated(e){super.firstUpdated(e),this._ensureNativeModal(),queueMicrotask(()=>this._focusInitial())}updated(e){super.updated(e),this._ensureNativeModal()}_ensureNativeModal(){if(this._usesHaDialog()||!this.isConnected)return!1;const e=this.renderRoot.querySelector("dialog");if(!e?.isConnected)return!1;try{return!e.matches(":modal")&&(e.open&&e.close(),e.showModal(),!0)}catch{return!1}}_deepActiveElement(){let e=document.activeElement;for(;e?.shadowRoot?.activeElement;)e=e.shadowRoot.activeElement;return e&&e!==document.body?e:null}_focusableElements(){const e=["[autofocus]","a[href]","button:not([disabled])",'input:not([disabled]):not([type="hidden"])',"select:not([disabled])","textarea:not([disabled])",'[contenteditable="true"]','[tabindex]:not([tabindex="-1"])'].join(","),t=[],i=new Set,n=r=>{if(!i.has(r)){if(i.add(r),r instanceof HTMLElement){if(r.matches(e)&&t.push(r),r instanceof HTMLSlotElement){for(const e of r.assignedNodes({flatten:!0}))n(e);return}if(r.shadowRoot){for(const e of r.shadowRoot.childNodes)n(e);return}}for(const e of r.childNodes)n(e)}};for(const e of this.childNodes)n(e);const r=this.overlayPortal();return r&&n(r),t.filter(e=>{let t=e;for(;t;){const e=getComputedStyle(t);if(t.hidden||t.inert||"true"===t.getAttribute("aria-hidden")||"none"===e.display||"hidden"===e.visibility)return!1;if(t=t.assignedSlot||t.parentElement||(t.getRootNode()instanceof ShadowRoot?t.getRootNode().host:null),t===this)break}return!0})}rejectClose(){this._closing=!1,this.requestUpdate()}_pruneOverlays(){this._overlays=this._overlays.filter(e=>e.owner.isConnected)}_closeOverlay(e,t){const i=this._overlays.findIndex(t=>t.token===e.token);i>=0&&this._overlays.splice(i,1),e.close(t)}registerOverlay(e){this._pruneOverlays();const t=this._overlays.find(t=>t.owner===e.owner);t&&this._overlays.splice(this._overlays.indexOf(t),1);const i=e.group||"transient";for(const e of[...this._overlays].reverse())e.group===i&&this._closeOverlay(e,"exclusive");const n={...e,group:i,token:Symbol("hp-overlay")};this._overlays.push(n);let r=!1;return()=>{if(r)return;r=!0;const e=this._overlays.findIndex(e=>e.token===n.token);e>=0&&this._overlays.splice(e,1)}}closeTransientOverlays(e="outside"){this._pruneOverlays();const t=[...this._overlays].filter(e=>"transient"===(e.group||"transient"));for(const i of t.reverse())this._closeOverlay(i,e);return t.length>0}overlayPortal(){return this.renderRoot.querySelector(".overlay-portal")}render(){const e=j` + ${this.icon?j``:G} + ${this.title} + `;return this._usesHaDialog()?this.describedBy?j` + ${e} + + +
`:j` + ${e} + + +
`:j` +
+
+ ${e} + +
+
+ +
+
+
`}}Pe.properties={title:{type:String},icon:{type:String},wide:{type:Boolean,reflect:!0},alert:{type:Boolean,reflect:!0},describedBy:{type:String,attribute:"described-by"},dismissOnScrim:{type:Boolean,attribute:"dismiss-on-scrim"},flexContent:{type:Boolean,reflect:!0,attribute:"flex-content"},hass:{attribute:!1}},Pe.styles=o`:host{display:contents;color:var(--primary-text-color,#e6e7eb);font:inherit;}ha-dialog{--dialog-content-padding:0;--dialog-surface-background:var(--card-background-color,var(--hp-bg,#202126));--ha-dialog-border-radius:var(--rad-l,18px);--ha-dialog-header-title-height:auto;color:inherit;}ha-dialog::part(dialog){border:1px solid var(--hp-accent,#d89300);box-shadow:var(--shadow-3,0 18px 48px rgb(0 0 0 / 0.34));overflow:hidden;}.header-title-slot{display:block;flex:1 1 auto;width:100%;max-width:100%;min-width:0;box-sizing:border-box;white-space:normal;}.title{display:flex;flex:1 1 auto;align-items:center;gap:var(--sp-4,12px);width:100%;max-width:100%;min-width:0;font-weight:600;line-height:1.25;white-space:normal;}.title ha-icon{flex:none;color:var(--hp-accent,#d89300);}.title-text{flex:1 1 auto;min-width:0;max-width:100%;white-space:normal;overflow-wrap:anywhere;word-break:normal;}.footer{display:block;width:100%;min-width:0;box-sizing:border-box;}::slotted([slot='footer']){width:100%;box-sizing:border-box;}dialog{width:fit-content;height:fit-content;max-width:none;max-height:none;inset:0;margin:auto;padding:0;border:0;overflow:visible;color:inherit;background:transparent;}dialog::backdrop{background:rgb(0 0 0 / 0.45);}.surface{width:min(360px,92vw);max-height:92vh;display:flex;flex-direction:column;overflow:hidden;box-sizing:border-box;color:inherit;background:var(--card-background-color,var(--hp-bg,#202126));border:1px solid var(--hp-accent,#d89300);border-radius:var(--rad-l,18px);box-shadow:var(--shadow-3,0 18px 48px rgb(0 0 0 / 0.34));}:host([wide]) .surface{width:min(var(--hp-dialog-wide-width,500px),94vw);}.header{min-height:56px;display:flex;align-items:center;gap:var(--sp-4,12px);padding:var(--sp-4,12px) var(--sp-5,16px);box-sizing:border-box;border-bottom:1px solid var(--hp-line,rgb(255 255 255 / 0.12));}.header .title{flex:1;}.close{width:40px;height:40px;flex:none;display:inline-flex;align-items:center;justify-content:center;padding:0;color:inherit;background:transparent;border:0;border-radius:50%;cursor:pointer;}:host([data-pointer-hover]) .close:hover,.close:focus-visible{background:rgb(127 127 127 / 0.16);}.content{min-height:0;display:flex;flex-direction:column;}.overlay-portal{position:fixed;z-index:2147483647;inset:0;overflow:visible;pointer-events:none;}.overlay-portal:empty{display:none;}.overlay-portal>*{pointer-events:auto;}`,customElements.get("hp-dialog")||customElements.define("hp-dialog",Pe);class Fe extends he{constructor(){super(...arguments),this.hass=null,this.request=null,this.token=0}createRenderRoot(){return this}_decide(e){this.dispatchEvent(new CustomEvent("hp-confirm-decision",{detail:{token:this.token,accepted:e},bubbles:!0,composed:!0}))}render(){const e=this.request;if(!e)return null;const t="destructive"===e.kind,i=`hp-confirm-description-${this.token}`;return j`this._decide(!1)}> +
+ ${e.objectName?j`${e.objectName}`:null} +

${e.message}

+
+ +
`}}Fe.properties={hass:{attribute:!1},request:{attribute:!1},token:{type:Number}},customElements.get("hp-confirm")||customElements.define("hp-confirm",Fe);class ze{constructor(e){this._changed=e,this._sequence=0,this._active=null}get state(){return this._active?{token:this._active.token,request:this._active.request}:null}confirm(e){this.cancel();const t={token:++this._sequence,request:Object.freeze({...e})};return new Promise(e=>{this._active={...t,resolve:e},this._changed(t)})}resolve(e,t){const i=this._active;return!(!i||i.token!==e)&&(this._active=null,this._changed(null),i.resolve(t),!0)}cancel(){const e=this._active;return!!e&&this.resolve(e.token,!1)}}const Ie=new Set(["hacs","sun","backup","hassio","met","telegram_bot","mobile_app","systemmonitor","better_thermostat","adaptive_lighting","yandex_pogoda","upnp_serial_number"]),Oe=[{pattern:"протечк|leak|water sensor",icon:"mdi:water-alert"},{pattern:"клапан|valve",icon:"mdi:pipe-valve"},{pattern:"дым|smoke",icon:"mdi:smoke-detector"},{pattern:"термоголов|trv|radiator",icon:"mdi:radiator"},{pattern:"чайник|kettle|термопот",icon:"mdi:kettle"},{pattern:"сауна|sauna|harvia|парная|парилк",icon:"mdi:hot-tub"},{pattern:"температ|temperature|thermometer|climate sensor",icon:"mdi:thermometer"},{pattern:"qingping|air monitor|молекул|air quality",icon:"mdi:air-filter"},{pattern:"штор|curtain|blind|shade",icon:"mdi:roller-shade"},{pattern:"розетк|plug|socket|outlet",icon:"mdi:power-socket-de"},{pattern:"выключат|switch",icon:"mdi:light-switch"},{pattern:"лампа|лампочк|bulb|gx53|светильник|rgb|lamp|light strip",icon:"mdi:lightbulb"},{pattern:"камер|camera",icon:"mdi:cctv"},{pattern:"замок|ttlock|lock|sn609|sn9161",icon:"mdi:lock"},{pattern:"ворота|garage|gate",icon:"mdi:garage-variant"},{pattern:"калитк|door|открыт|contact",icon:"mdi:door"},{pattern:"счётчик|счетчик|kws|meter",icon:"mdi:meter-electric"},{pattern:"вводный автомат|breaker|wifimcbn",icon:"mdi:electric-switch"},{pattern:"myheat|котёл|котел|boiler|отоплен|heating",icon:"mdi:water-boiler"},{pattern:"холодильник|fridge",icon:"mdi:fridge"},{pattern:"стиральн|washer|washing",icon:"mdi:washing-machine"},{pattern:"сушилк|dryer",icon:"mdi:tumble-dryer"},{pattern:"пылесос|vacuum|dreame|roborock",icon:"mdi:robot-vacuum"},{pattern:"soundbar",icon:"mdi:soundbar"},{pattern:"колонк|станц|speaker|яндекс|yandex|алиса|alice",icon:"mdi:speaker"},{pattern:"tv|телевизор|hyundaitv|mitv|television",icon:"mdi:television"},{pattern:"keenetic|роутер|router|mesh|access point",icon:"mdi:router-wireless"},{pattern:"ибп|ups|kirpich",icon:"mdi:battery-charging-high"},{pattern:"slzb|координат|zigbee|coordinator",icon:"mdi:zigbee"},{pattern:"motion|движен|presence|присутств",icon:"mdi:motion-sensor"},{pattern:"humidity|влажн",icon:"mdi:water-percent"}];function Ee(e){const t=[];for(const i of e)if(i&&"string"==typeof i.pattern&&i.icon)try{t.push({re:new RegExp(i.pattern,"i"),icon:i.icon})}catch{}return t}function Ne(e){try{return new RegExp(e,"i"),!0}catch{return!1}}const He=Ee(Oe),Le={temperature:"mdi:thermometer",humidity:"mdi:water-percent",motion:"mdi:motion-sensor",occupancy:"mdi:motion-sensor",presence:"mdi:motion-sensor",door:"mdi:door",window:"mdi:window-closed",garage_door:"mdi:garage-variant",smoke:"mdi:smoke-detector",moisture:"mdi:water-alert",gas:"mdi:gas-cylinder",power:"mdi:meter-electric",energy:"mdi:meter-electric",illuminance:"mdi:brightness-5",co2:"mdi:molecule-co2",pm25:"mdi:air-filter",battery:"mdi:battery"},Be="mdi:chip";function qe(e,t,i){const n=((e||"")+" "+(t||"")).toLowerCase();for(const{re:e,icon:t}of i??He)if(e.test(n))return t;return Be}const je=["light","switch","cover","valve","lock","climate","fan","media_player","camera","vacuum","humidifier","water_heater","alarm_control_panel","sensor","binary_sensor","event","button","number","select","update"];var We=/^-?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d+)?$/i,Ue=Math.ceil,Ge=Math.floor,Ve="[BigNumber Error] ",Ke=Ve+"Number primitive has more than 15 significant digits: ",Ye=1e14,Xe=14,Ze=9007199254740991,Je=[1,10,100,1e3,1e4,1e5,1e6,1e7,1e8,1e9,1e10,1e11,1e12,1e13],Qe=1e7,et=1e9;function tt(e){var t=0|e;return e>0||e===t?t:t-1}function it(e){for(var t,i,n=1,r=e.length,o=e[0]+"";nc^i?1:-1;for(a=(l=r.length)<(c=o.length)?l:c,s=0;so[s]^i?1:-1;return l==c?0:l>c^i?1:-1}function rt(e,t,i,n){if(ei||e!==Ge(e))throw Error(Ve+(n||"Argument")+("number"==typeof e?ei?" out of range: ":" not an integer: ":" not a primitive number: ")+String(e))}function ot(e){var t=e.c.length-1;return tt(e.e/Xe)==t&&e.c[t]%2!=0}function st(e,t){return(e.length>1?e.charAt(0)+"."+e.slice(1):e)+(t<0?"e":"e+")+t}function at(e,t,i){var n,r;if(t<0){for(r=i+".";++t;r+=i);e=r+e}else if(++t>(n=e.length)){for(r=i,t-=n;--t;r+=i);e+=r}else ty?u.c=u.e=null:e.e=10;l/=10,a++);return void(a>y?u.c=u.e=null:(u.e=a,u.c=[e]))}d=String(e)}else{if(!We.test(d=String(e)))return r(u,d,c);u.s=45==d.charCodeAt(0)?(d=d.slice(1),-1):1}(a=d.indexOf("."))>-1&&(d=d.replace(".","")),(l=d.search(/e/i))>0?(a<0&&(a=l),a+=+d.slice(l+1),d=d.substring(0,l)):a<0&&(a=d.length)}else{if(rt(t,2,S.length,"Base"),10==t&&$)return D(u=new M(e),_+u.e+1,m);if(d=String(e),c="number"==typeof e){if(0*e!=0)return r(u,d,c,t);if(u.s=1/e<0?(d=d.slice(1),-1):1,M.DEBUG&&d.replace(/^0\.0*|\./,"").length>15)throw Error(Ke+e)}else u.s=45===d.charCodeAt(0)?(d=d.slice(1),-1):1;for(i=S.slice(0,t),a=l=0,h=d.length;la){a=h;continue}}else if(!s&&(d==d.toUpperCase()&&(d=d.toLowerCase())||d==d.toLowerCase()&&(d=d.toUpperCase()))){s=!0,l=-1,a=0;continue}return r(u,String(e),c,t)}c=!1,(a=(d=n(d,t,10,u.s)).indexOf("."))>-1?d=d.replace(".",""):a=d.length}for(l=0;48===d.charCodeAt(l);l++);for(h=d.length;48===d.charCodeAt(--h););if(d=d.slice(l,++h)){if(h-=l,c&&M.DEBUG&&h>15&&(e>Ze||e!==Ge(e)))throw Error(Ke+u.s*e);if((a=a-l-1)>y)u.c=u.e=null;else if(a=f)?st(l,s):at(l,s,"0");else if(o=(e=D(new M(e),t,i)).e,a=(l=it(e.c)).length,1==n||2==n&&(t<=o||o<=g)){for(;as),l=at(l,o,"0"),o+1>a){if(--t>0)for(l+=".";t--;l+="0");}else if((t+=o-a)>0)for(o+1==a&&(l+=".");t--;l+="0");return e.s<0&&r?"-"+l:l}function C(e,t){for(var i,n,r=1,o=new M(e[0]);r=10;r/=10,n++);return(i=n+i*Xe-1)>y?e.c=e.e=null:i=10;a/=10,r++);if((o=t-r)<0)o+=Xe,s=t,l=d[c=0],h=Ge(l/u[r-s-1]%10);else if((c=Ue((o+1)/Xe))>=d.length){if(!n)break e;for(;d.length<=c;d.push(0));l=h=0,r=1,s=(o%=Xe)-Xe+1}else{for(l=a=d[c],r=1;a>=10;a/=10,r++);h=(s=(o%=Xe)-Xe+r)<0?0:Ge(l/u[r-s-1]%10)}if(n=n||t<0||null!=d[c+1]||(s<0?l:l%u[r-s-1]),n=i<4?(h||n)&&(0==i||i==(e.s<0?3:2)):h>5||5==h&&(4==i||n||6==i&&(o>0?s>0?l/u[r-s]:0:d[c-1])%10&1||i==(e.s<0?8:7)),t<1||!d[0])return d.length=0,n?(t-=e.e+1,d[0]=u[(Xe-t%Xe)%Xe],e.e=-t||0):d[0]=e.e=0,e;if(0==o?(d.length=c,a=1,c--):(d.length=c+1,a=u[Xe-o],d[c]=s>0?Ge(l/u[r-s]%u[s])*a:0),n)for(;;){if(0==c){for(o=1,s=d[0];s>=10;s/=10,o++);for(s=d[0]+=a,a=1;s>=10;s/=10,a++);o!=a&&(e.e++,d[0]==Ye&&(d[0]=1));break}if(d[c]+=a,d[c]!=Ye)break;d[c--]=0,a=1}for(o=d.length;0===d[--o];d.pop());}e.e>y?e.c=e.e=null:e.e=f?st(t,i):at(t,i,"0"),e.s<0?"-"+t:t)}return M.clone=e,M.ROUND_UP=0,M.ROUND_DOWN=1,M.ROUND_CEIL=2,M.ROUND_FLOOR=3,M.ROUND_HALF_UP=4,M.ROUND_HALF_DOWN=5,M.ROUND_HALF_EVEN=6,M.ROUND_HALF_CEIL=7,M.ROUND_HALF_FLOOR=8,M.EUCLID=9,M.config=M.set=function(e){var t,i;if(null!=e){if("object"!=typeof e)throw Error(Ve+"Object expected: "+e);if(e.hasOwnProperty(t="DECIMAL_PLACES")&&(rt(i=e[t],0,et,t),_=i),e.hasOwnProperty(t="ROUNDING_MODE")&&(rt(i=e[t],0,8,t),m=i),e.hasOwnProperty(t="EXPONENTIAL_AT")&&((i=e[t])&&i.pop?(rt(i[0],-et,0,t),rt(i[1],0,et,t),g=i[0],f=i[1]):(rt(i,-et,et,t),g=-(f=i<0?-i:i))),e.hasOwnProperty(t="RANGE"))if((i=e[t])&&i.pop)rt(i[0],-et,-1,t),rt(i[1],1,et,t),v=i[0],y=i[1];else{if(rt(i,-et,et,t),!i)throw Error(Ve+t+" cannot be zero: "+i);v=-(y=i<0?-i:i)}if(e.hasOwnProperty(t="CRYPTO")){if((i=e[t])!==!!i)throw Error(Ve+t+" not true or false: "+i);if(i){if("undefined"==typeof crypto||!crypto||!crypto.getRandomValues&&!crypto.randomBytes)throw b=!i,Error(Ve+"crypto unavailable");b=i}else b=i}if(e.hasOwnProperty(t="MODULO_MODE")&&(rt(i=e[t],0,9,t),w=i),e.hasOwnProperty(t="POW_PRECISION")&&(rt(i=e[t],0,et,t),k=i),e.hasOwnProperty(t="FORMAT")){if("object"!=typeof(i=e[t]))throw Error(Ve+t+" not an object: "+i);x=i}if(e.hasOwnProperty(t="ALPHABET")){if("string"!=typeof(i=e[t])||/^.?$|[+\-.\s]|(.).*\1/.test(i))throw Error(Ve+t+" invalid: "+i);$="0123456789"==i.slice(0,10),S=i}}return{DECIMAL_PLACES:_,ROUNDING_MODE:m,EXPONENTIAL_AT:[g,f],RANGE:[v,y],CRYPTO:b,MODULO_MODE:w,POW_PRECISION:k,FORMAT:x,ALPHABET:S}},M.isBigNumber=function(e){if(!e||!0!==e._isBigNumber)return!1;if(!M.DEBUG)return!0;var t,i,n=e.c,r=e.e,o=e.s;e:if("[object Array]"=={}.toString.call(n)){if((1===o||-1===o)&&r>=-et&&r<=et&&r===Ge(r)){if(0===n[0]){if(0===r&&1===n.length)return!0;break e}if((t=(r+1)%Xe)<1&&(t+=Xe),String(n[0]).length==t){for(t=0;t=Ye||i!==Ge(i))break e;if(0!==i)return!0}}}else if(null===n&&null===r&&(null===o||1===o||-1===o))return!0;throw Error(Ve+"Invalid BigNumber: "+e)},M.maximum=M.max=function(){return C(arguments,-1)},M.minimum=M.min=function(){return C(arguments,1)},M.random=(o=9007199254740992,s=Math.random()*o&2097151?function(){return Ge(Math.random()*o)}:function(){return 8388608*(1073741824*Math.random()|0)+(8388608*Math.random()|0)},function(e){var t,i,n,r,o,a=0,l=[],c=new M(p);if(null==e?e=_:rt(e,0,et),r=Ue(e/Xe),b)if(crypto.getRandomValues){for(t=crypto.getRandomValues(new Uint32Array(r*=2));a>>11))>=9e15?(i=crypto.getRandomValues(new Uint32Array(2)),t[a]=i[0],t[a+1]=i[1]):(l.push(o%1e14),a+=2);a=r/2}else{if(!crypto.randomBytes)throw b=!1,Error(Ve+"crypto unavailable");for(t=crypto.randomBytes(r*=7);a=9e15?crypto.randomBytes(7).copy(t,a):(l.push(o%1e14),a+=7);a=r/7}if(!b)for(;a=10;o/=10,a++);ai-1&&(null==s[r+1]&&(s[r+1]=0),s[r+1]+=s[r]/i|0,s[r]%=i)}return s.reverse()}return function(n,r,o,s,a){var l,c,h,d,u,p,g,f,v=n.indexOf("."),y=_,b=m;for(v>=0&&(d=k,k=0,n=n.replace(".",""),p=(f=new M(r)).pow(n.length-v),k=d,f.c=t(at(it(p.c),p.e,"0"),10,o,e),f.e=f.c.length),h=d=(g=t(n,r,o,a?(l=S,e):(l=e,S))).length;0==g[--d];g.pop());if(!g[0])return l.charAt(0);if(v<0?--h:(p.c=g,p.e=h,p.s=s,g=(p=i(p,f,y,b,o)).c,u=p.r,h=p.e),v=g[c=h+y+1],d=o/2,u=u||c<0||null!=g[c+1],u=b<4?(null!=v||u)&&(0==b||b==(p.s<0?3:2)):v>d||v==d&&(4==b||u||6==b&&1&g[c-1]||b==(p.s<0?8:7)),c<1||!g[0])n=u?at(l.charAt(1),-y,l.charAt(0)):l.charAt(0);else{if(g.length=c,u)for(--o;++g[--c]>o;)g[c]=0,c||(++h,g=[1].concat(g));for(d=g.length;!g[--d];);for(v=0,n="";v<=d;n+=l.charAt(g[v++]));n=at(n,h,l.charAt(0))}return n}}(),i=function(){function e(e,t,i){var n,r,o,s,a=0,l=e.length,c=t%Qe,h=t/Qe|0;for(e=e.slice();l--;)a=((r=c*(o=e[l]%Qe)+(n=h*o+(s=e[l]/Qe|0)*c)%Qe*Qe+a)/i|0)+(n/Qe|0)+h*s,e[l]=r%i;return a&&(e=[a].concat(e)),e}function t(e,t,i,n){var r,o;if(i!=n)o=i>n?1:-1;else for(r=o=0;rt[r]?1:-1;break}return o}function i(e,t,i,n){for(var r=0;i--;)e[i]-=r,r=e[i]1;e.splice(0,1));}return function(n,r,o,s,a){var l,c,h,d,u,p,_,m,g,f,v,y,b,w,k,x,S,$=n.s==r.s?1:-1,R=n.c,C=r.c;if(!(R&&R[0]&&C&&C[0]))return new M(n.s&&r.s&&(R?!C||R[0]!=C[0]:C)?R&&0==R[0]||!C?0*$:$/0:NaN);for(g=(m=new M($)).c=[],$=o+(c=n.e-r.e)+1,a||(a=Ye,c=tt(n.e/Xe)-tt(r.e/Xe),$=$/Xe|0),h=0;C[h]==(R[h]||0);h++);if(C[h]>(R[h]||0)&&c--,$<0)g.push(1),d=!0;else{for(w=R.length,x=C.length,h=0,$+=2,(u=Ge(a/(C[0]+1)))>1&&(C=e(C,u,a),R=e(R,u,a),x=C.length,w=R.length),b=x,v=(f=R.slice(0,x)).length;v=a/2&&k++;do{if(u=0,(l=t(C,f,x,v))<0){if(y=f[0],x!=v&&(y=y*a+(f[1]||0)),(u=Ge(y/k))>1)for(u>=a&&(u=a-1),_=(p=e(C,u,a)).length,v=f.length;1==t(p,f,_,v);)u--,i(p,x<_?S:C,_,a),_=p.length,l=1;else 0==u&&(l=u=1),_=(p=C.slice()).length;if(_=10;$/=10,h++);D(m,o+(m.e=h+c*Xe-1)+1,s,d)}else m.e=c,m.r=+d;return m}}(),a=/^(-?)0([xbo])(?=\w[\w.]*$)/i,l=/^([^.]+)\.$/,c=/^\.([^.]+)$/,h=/^-?(Infinity|NaN)$/,d=/^\s*\+(?=[\w.])|^\s+|\s+$/g,r=function(e,t,i,n){var r,o=i?t:t.replace(d,"");if(h.test(o))e.s=isNaN(o)?null:o<0?-1:1;else{if(!i&&(o=o.replace(a,function(e,t,i){return r="x"==(i=i.toLowerCase())?16:"b"==i?2:8,n&&n!=r?e:t}),n&&(r=n,o=o.replace(l,"$1").replace(c,"0.$1")),t!=o))return new M(o,r);if(M.DEBUG)throw Error(Ve+"Not a"+(n?" base "+n:"")+" number: "+t);e.s=null}e.c=e.e=null},u.absoluteValue=u.abs=function(){var e=new M(this);return e.s<0&&(e.s=1),e},u.comparedTo=function(e,t){return nt(this,new M(e,t))},u.decimalPlaces=u.dp=function(e,t){var i,n,r,o=this;if(null!=e)return rt(e,0,et),null==t?t=m:rt(t,0,8),D(new M(o),e+o.e+1,t);if(!(i=o.c))return null;if(n=((r=i.length-1)-tt(this.e/Xe))*Xe,r=i[r])for(;r%10==0;r/=10,n--);return n<0&&(n=0),n},u.dividedBy=u.div=function(e,t){return i(this,new M(e,t),_,m)},u.dividedToIntegerBy=u.idiv=function(e,t){return i(this,new M(e,t),0,1)},u.exponentiatedBy=u.pow=function(e,t){var i,n,r,o,s,a,l,c,h=this;if((e=new M(e)).c&&!e.isInteger())throw Error(Ve+"Exponent not an integer: "+A(e));if(null!=t&&(t=new M(t)),s=e.e>14,!h.c||!h.c[0]||1==h.c[0]&&!h.e&&1==h.c.length||!e.c||!e.c[0])return c=new M(Math.pow(+A(h),s?e.s*(2-ot(e)):+A(e))),t?c.mod(t):c;if(a=e.s<0,t){if(t.c?!t.c[0]:!t.s)return new M(NaN);(n=!a&&h.isInteger()&&t.isInteger())&&(h=h.mod(t))}else{if(e.e>9&&(h.e>0||h.e<-1||(0==h.e?h.c[0]>1||s&&h.c[1]>=24e7:h.c[0]<8e13||s&&h.c[0]<=9999975e7)))return o=h.s<0&&ot(e)?-0:0,h.e>-1&&(o=1/o),new M(a?1/o:o);k&&(o=Ue(k/Xe+2))}for(s?(i=new M(.5),a&&(e.s=1),l=ot(e)):l=(r=Math.abs(+A(e)))%2,c=new M(p);;){if(l){if(!(c=c.times(h)).c)break;o?c.c.length>o&&(c.c.length=o):n&&(c=c.mod(t))}if(r){if(0===(r=Ge(r/2)))break;l=r%2}else if(D(e=e.times(i),e.e+1,1),e.e>14)l=ot(e);else{if(0===(r=+A(e)))break;l=r%2}h=h.times(h),o?h.c&&h.c.length>o&&(h.c.length=o):n&&(h=h.mod(t))}return n?c:(a&&(c=p.div(c)),t?c.mod(t):o?D(c,k,m,void 0):c)},u.integerValue=function(e){var t=new M(this);return null==e?e=m:rt(e,0,8),D(t,t.e+1,e)},u.isEqualTo=u.eq=function(e,t){return 0===nt(this,new M(e,t))},u.isFinite=function(){return!!this.c},u.isGreaterThan=u.gt=function(e,t){return nt(this,new M(e,t))>0},u.isGreaterThanOrEqualTo=u.gte=function(e,t){return 1===(t=nt(this,new M(e,t)))||0===t},u.isInteger=function(){return!!this.c&&tt(this.e/Xe)>this.c.length-2},u.isLessThan=u.lt=function(e,t){return nt(this,new M(e,t))<0},u.isLessThanOrEqualTo=u.lte=function(e,t){return-1===(t=nt(this,new M(e,t)))||0===t},u.isNaN=function(){return!this.s},u.isNegative=function(){return this.s<0},u.isPositive=function(){return this.s>0},u.isZero=function(){return!!this.c&&0==this.c[0]},u.minus=function(e,t){var i,n,r,o,s=this,a=s.s;if(t=(e=new M(e,t)).s,!a||!t)return new M(NaN);if(a!=t)return e.s=-t,s.plus(e);var l=s.e/Xe,c=e.e/Xe,h=s.c,d=e.c;if(!l||!c){if(!h||!d)return h?(e.s=-t,e):new M(d?s:NaN);if(!h[0]||!d[0])return d[0]?(e.s=-t,e):new M(h[0]?s:3==m?-0:0)}if(l=tt(l),c=tt(c),h=h.slice(),a=l-c){for((o=a<0)?(a=-a,r=h):(c=l,r=d),r.reverse(),t=a;t--;r.push(0));r.reverse()}else for(n=(o=(a=h.length)<(t=d.length))?a:t,a=t=0;t0)for(;t--;h[i++]=0);for(t=Ye-1;n>a;){if(h[--n]=0;){for(i=0,u=y[r]%g,p=y[r]/g|0,o=r+(s=l);o>r;)i=((c=u*(c=v[--s]%g)+(a=p*c+(h=v[s]/g|0)*u)%g*g+_[o]+i)/m|0)+(a/g|0)+p*h,_[o--]=c%m;_[o]=i}return i?++n:_.splice(0,1),T(e,_,n)},u.negated=function(){var e=new M(this);return e.s=-e.s||null,e},u.plus=function(e,t){var i,n=this,r=n.s;if(t=(e=new M(e,t)).s,!r||!t)return new M(NaN);if(r!=t)return e.s=-t,n.minus(e);var o=n.e/Xe,s=e.e/Xe,a=n.c,l=e.c;if(!o||!s){if(!a||!l)return new M(r/0);if(!a[0]||!l[0])return l[0]?e:new M(a[0]?n:0*r)}if(o=tt(o),s=tt(s),a=a.slice(),r=o-s){for(r>0?(s=o,i=l):(r=-r,i=a),i.reverse();r--;i.push(0));i.reverse()}for((r=a.length)-(t=l.length)<0&&(i=l,l=a,a=i,t=r),r=0;t;)r=(a[--t]=a[t]+l[t]+r)/Ye|0,a[t]=Ye===a[t]?0:a[t]%Ye;return r&&(a=[r].concat(a),++s),T(e,a,s)},u.precision=u.sd=function(e,t){var i,n,r,o=this;if(null!=e&&e!==!!e)return rt(e,1,et),null==t?t=m:rt(t,0,8),D(new M(o),e,t);if(!(i=o.c))return null;if(n=(r=i.length-1)*Xe+1,r=i[r]){for(;r%10==0;r/=10,n--);for(r=i[0];r>=10;r/=10,n++);}return e&&o.e+1>n&&(n=o.e+1),n},u.shiftedBy=function(e){return rt(e,-9007199254740991,Ze),this.times("1e"+e)},u.squareRoot=u.sqrt=function(){var e,t,n,r,o,s=this,a=s.c,l=s.s,c=s.e,h=_+4,d=new M("0.5");if(1!==l||!a||!a[0])return new M(!l||l<0&&(!a||a[0])?NaN:a?s:1/0);if(0==(l=Math.sqrt(+A(s)))||l==1/0?(((t=it(a)).length+c)%2==0&&(t+="0"),l=Math.sqrt(+t),c=tt((c+1)/2)-(c<0||c%2),n=new M(t=l==1/0?"5e"+c:(t=l.toExponential()).slice(0,t.indexOf("e")+1)+c)):n=new M(l+""),n.c[0])for((l=(c=n.e)+h)<3&&(l=0);;)if(o=n,n=d.times(o.plus(i(s,o,h,1))),it(o.c).slice(0,l)===(t=it(n.c)).slice(0,l)){if(n.e0&&_>0){for(o=_%a||a,h=p.substr(0,o);o<_;o+=a)h+=c+p.substr(o,a);l>0&&(h+=c+p.slice(o)),u&&(h="-"+h)}n=d?h+(i.decimalSeparator||"")+((l=+i.fractionGroupSize)?d.replace(new RegExp("\\d{"+l+"}\\B","g"),"$&"+(i.fractionGroupSeparator||"")):d):h}return(i.prefix||"")+n+(i.suffix||"")},u.toFraction=function(e){var t,n,r,o,s,a,l,c,h,d,u,_,g=this,f=g.c;if(null!=e&&(!(l=new M(e)).isInteger()&&(l.c||1!==l.s)||l.lt(p)))throw Error(Ve+"Argument "+(l.isInteger()?"out of range: ":"not an integer: ")+A(l));if(!f)return new M(g);for(t=new M(p),h=n=new M(p),r=c=new M(p),_=it(f),s=t.e=_.length-g.e-1,t.c[0]=Je[(a=s%Xe)<0?Xe+a:a],e=!e||l.comparedTo(t)>0?s>0?t:h:l,a=y,y=1/0,l=new M(_),c.c[0]=0;d=i(l,t,0,1),1!=(o=n.plus(d.times(r))).comparedTo(e);)n=r,r=o,h=c.plus(d.times(o=h)),c=o,t=l.minus(d.times(o=t)),l=o;return o=i(e.minus(n),r,0,1),c=c.plus(o.times(h)),n=n.plus(o.times(r)),c.s=h.s=g.s,u=i(h,r,s*=2,m).minus(g).abs().comparedTo(i(c,n,s,m).minus(g).abs())<1?[h,r]:[c,n],y=a,u},u.toNumber=function(){return+A(this)},u.toPrecision=function(e,t){return null!=e&&rt(e,1,et),R(this,e,t,2)},u.toString=function(e){var t,i=this,r=i.s,o=i.e;return null===o?r?(t="Infinity",r<0&&(t="-"+t)):t="NaN":(null==e?t=o<=g||o>=f?st(it(i.c),o):at(it(i.c),o,"0"):10===e&&$?t=at(it((i=D(new M(i),_+o+1,m)).c),i.e,"0"):(rt(e,2,S.length,"Base"),t=n(at(it(i.c),o,"0"),10,e,r,!0)),r<0&&i.c[0]&&(t="-"+t)),t},u.valueOf=u.toJSON=function(){return A(this)},u._isBigNumber=!0,u[Symbol.toStringTag]="BigNumber",u[Symbol.for("nodejs.util.inspect.custom")]=u.valueOf,null!=t&&M.set(t),M}(),ct=class{key;left=null;right=null;constructor(e){this.key=e}},ht=class extends ct{constructor(e){super(e)}},dt=class{size=0;modificationCount=0;splayCount=0;splay(e){const t=this.root;if(null==t)return this.compare(e,e),-1;let i=null,n=null,r=null,o=null,s=t;const a=this.compare;let l;for(;;)if(l=a(s.key,e),l>0){let t=s.left;if(null==t)break;if(l=a(t.key,e),l>0&&(s.left=t.right,t.right=s,s=t,t=s.left,null==t))break;null==i?n=s:i.left=s,i=s,s=t}else{if(!(l<0))break;{let t=s.right;if(null==t)break;if(l=a(t.key,e),l<0&&(s.right=t.left,t.left=s,s=t,t=s.right,null==t))break;null==r?o=s:r.right=s,r=s,s=t}}return null!=r&&(r.right=s.left,s.left=o),null!=i&&(i.left=s.right,s.right=n),this.root!==s&&(this.root=s,this.splayCount++),l}splayMin(e){let t=e,i=t.left;for(;null!=i;){const e=i;t.left=e.right,e.right=t,t=e,i=t.left}return t}splayMax(e){let t=e,i=t.right;for(;null!=i;){const e=i;t.right=e.left,e.left=t,t=e,i=t.right}return t}_delete(e){if(null==this.root)return null;if(0!=this.splay(e))return null;let t=this.root;const i=t,n=t.left;if(this.size--,null==n)this.root=t.right;else{const e=t.right;t=this.splayMax(n),t.right=e,this.root=t}return this.modificationCount++,i}addNewRoot(e,t){this.size++,this.modificationCount++;const i=this.root;null!=i?(t<0?(e.left=i,e.right=i.right,i.right=null):(e.right=i,e.left=i.left,i.left=null),this.root=e):this.root=e}_first(){const e=this.root;return null==e?null:(this.root=this.splayMin(e),this.root)}_last(){const e=this.root;return null==e?null:(this.root=this.splayMax(e),this.root)}clear(){this.root=null,this.size=0,this.modificationCount++}has(e){return this.validKey(e)&&0==this.splay(e)}defaultCompare(){return(e,t)=>et?1:0}wrap(){return{getRoot:()=>this.root,setRoot:e=>{this.root=e},getSize:()=>this.size,getModificationCount:()=>this.modificationCount,getSplayCount:()=>this.splayCount,setSplayCount:e=>{this.splayCount=e},splay:e=>this.splay(e),has:e=>this.has(e)}}},ut=class e extends dt{root=null;compare;validKey;constructor(e,t){super(),this.compare=e??this.defaultCompare(),this.validKey=t??(e=>null!=e&&null!=e)}delete(e){return!!this.validKey(e)&&null!=this._delete(e)}deleteAll(e){for(const t of e)this.delete(t)}forEach(e){const t=this[Symbol.iterator]();let i;for(;i=t.next(),!i.done;)e(i.value,i.value,this)}add(e){const t=this.splay(e);return 0!=t&&this.addNewRoot(new ht(e),t),this}addAndReturn(e){const t=this.splay(e);return 0!=t&&this.addNewRoot(new ht(e),t),this.root.key}addAll(e){for(const t of e)this.add(t)}isEmpty(){return null==this.root}isNotEmpty(){return null!=this.root}single(){if(0==this.size)throw"Bad state: No element";if(this.size>1)throw"Bad state: Too many element";return this.root.key}first(){if(0==this.size)throw"Bad state: No element";return this._first().key}last(){if(0==this.size)throw"Bad state: No element";return this._last().key}lastBefore(e){if(null==e)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(e)<0)return this.root.key;let t=this.root.left;if(null==t)return null;let i=t.right;for(;null!=i;)t=i,i=t.right;return t.key}firstAfter(e){if(null==e)throw"Invalid arguments(s)";if(null==this.root)return null;if(this.splay(e)>0)return this.root.key;let t=this.root.right;if(null==t)return null;let i=t.left;for(;null!=i;)t=i,i=t.left;return t.key}retainAll(t){const i=new e(this.compare,this.validKey),n=this.modificationCount;for(const e of t){if(n!=this.modificationCount)throw"Concurrent modification during iteration.";this.validKey(e)&&0==this.splay(e)&&i.add(this.root.key)}i.size!=this.size&&(this.root=i.root,this.size=i.size,this.modificationCount++)}lookup(e){if(!this.validKey(e))return null;return 0!=this.splay(e)?null:this.root.key}intersection(t){const i=new e(this.compare,this.validKey);for(const e of this)t.has(e)&&i.add(e);return i}difference(t){const i=new e(this.compare,this.validKey);for(const e of this)t.has(e)||i.add(e);return i}union(e){const t=this.clone();return t.addAll(e),t}clone(){const t=new e(this.compare,this.validKey);return t.size=this.size,t.root=this.copyNode(this.root),t}copyNode(e){if(null==e)return null;const t=new ht(e.key);return function e(t,i){let n,r;do{if(n=t.left,r=t.right,null!=n){const t=new ht(n.key);i.left=t,e(n,t)}if(null!=r){const e=new ht(r.key);i.right=e,t=r,i=e}}while(null!=r)}(e,t),t}toSet(){return this.clone()}entries(){return new mt(this.wrap())}keys(){return this[Symbol.iterator]()}values(){return this[Symbol.iterator]()}[Symbol.iterator](){return new _t(this.wrap())}[Symbol.toStringTag]="[object Set]"},pt=class{tree;path=new Array;modificationCount=null;splayCount;constructor(e){this.tree=e,this.splayCount=e.getSplayCount()}[Symbol.iterator](){return this}next(){return this.moveNext()?{done:!1,value:this.current()}:{done:!0,value:null}}current(){if(!this.path.length)return null;const e=this.path[this.path.length-1];return this.getValue(e)}rebuildPath(e){this.path.splice(0,this.path.length),this.tree.splay(e),this.path.push(this.tree.getRoot()),this.splayCount=this.tree.getSplayCount()}findLeftMostDescendent(e){for(;null!=e;)this.path.push(e),e=e.left}moveNext(){if(this.modificationCount!=this.tree.getModificationCount()){if(null==this.modificationCount){this.modificationCount=this.tree.getModificationCount();let e=this.tree.getRoot();for(;null!=e;)this.path.push(e),e=e.left;return this.path.length>0}throw"Concurrent modification during iteration."}if(!this.path.length)return!1;this.splayCount!=this.tree.getSplayCount()&&this.rebuildPath(this.path[this.path.length-1].key);let e=this.path[this.path.length-1],t=e.right;if(null!=t){for(;null!=t;)this.path.push(t),t=t.left;return!0}for(this.path.pop();this.path.length&&this.path[this.path.length-1].right===e;)e=this.path.pop();return this.path.length>0}},_t=class extends pt{getValue(e){return e.key}},mt=class extends pt{getValue(e){return[e.key,e.key]}},gt=e=>()=>e,ft=e=>{const t=e?(t,i)=>i.minus(t).abs().isLessThanOrEqualTo(e):gt(!1);return(e,i)=>t(e,i)?0:e.comparedTo(i)};function vt(e){const t=e?(t,i,n,r,o)=>t.exponentiatedBy(2).isLessThanOrEqualTo(r.minus(i).exponentiatedBy(2).plus(o.minus(n).exponentiatedBy(2)).times(e)):gt(!1);return(e,i,n)=>{const r=e.x,o=e.y,s=n.x,a=n.y,l=o.minus(a).times(i.x.minus(s)).minus(r.minus(s).times(i.y.minus(a)));return t(l,r,o,s,a)?0:l.comparedTo(0)}}var yt=e=>e,bt=e=>{if(e){const t=new ut(ft(e)),i=new ut(ft(e)),n=(e,t)=>t.addAndReturn(e),r=e=>({x:n(e.x,t),y:n(e.y,i)});return r({x:new lt(0),y:new lt(0)}),r}return yt},wt=e=>({set:e=>{kt=wt(e)},reset:()=>wt(e),compare:ft(e),snap:bt(e),orient:vt(e)}),kt=wt(),xt=(e,t)=>e.ll.x.isLessThanOrEqualTo(t.x)&&t.x.isLessThanOrEqualTo(e.ur.x)&&e.ll.y.isLessThanOrEqualTo(t.y)&&t.y.isLessThanOrEqualTo(e.ur.y),St=(e,t)=>{if(t.ur.x.isLessThan(e.ll.x)||e.ur.x.isLessThan(t.ll.x)||t.ur.y.isLessThan(e.ll.y)||e.ur.y.isLessThan(t.ll.y))return null;const i=e.ll.x.isLessThan(t.ll.x)?t.ll.x:e.ll.x,n=e.ur.x.isLessThan(t.ur.x)?e.ur.x:t.ur.x;return{ll:{x:i,y:e.ll.y.isLessThan(t.ll.y)?t.ll.y:e.ll.y},ur:{x:n,y:e.ur.y.isLessThan(t.ur.y)?e.ur.y:t.ur.y}}},$t=(e,t)=>e.x.times(t.y).minus(e.y.times(t.x)),Mt=(e,t)=>e.x.times(t.x).plus(e.y.times(t.y)),Rt=e=>Mt(e,e).sqrt(),Ct=(e,t,i)=>{const n={x:t.x.minus(e.x),y:t.y.minus(e.y)},r={x:i.x.minus(e.x),y:i.y.minus(e.y)};return $t(r,n).div(Rt(r)).div(Rt(n))},Tt=(e,t,i)=>{const n={x:t.x.minus(e.x),y:t.y.minus(e.y)},r={x:i.x.minus(e.x),y:i.y.minus(e.y)};return Mt(r,n).div(Rt(r)).div(Rt(n))},Dt=(e,t,i)=>t.y.isZero()?null:{x:e.x.plus(t.x.div(t.y).times(i.minus(e.y))),y:i},At=(e,t,i)=>t.x.isZero()?null:{x:i,y:e.y.plus(t.y.div(t.x).times(i.minus(e.x)))},Pt=class e{point;isLeft;segment;otherSE;consumedBy;static compare(t,i){const n=e.comparePoints(t.point,i.point);return 0!==n?n:(t.point!==i.point&&t.link(i),t.isLeft!==i.isLeft?t.isLeft?1:-1:Lt.compare(t.segment,i.segment))}static comparePoints(e,t){return e.x.isLessThan(t.x)?-1:e.x.isGreaterThan(t.x)?1:e.y.isLessThan(t.y)?-1:e.y.isGreaterThan(t.y)?1:0}constructor(e,t){void 0===e.events?e.events=[this]:e.events.push(this),this.point=e,this.isLeft=t}link(e){if(e.point===this.point)throw new Error("Tried to link already linked events");const t=e.point.events;for(let e=0,i=t.length;e{const n=i.otherSE;t.set(i,{sine:Ct(this.point,e.point,n.point),cosine:Tt(this.point,e.point,n.point)})};return(e,n)=>{t.has(e)||i(e),t.has(n)||i(n);const{sine:r,cosine:o}=t.get(e),{sine:s,cosine:a}=t.get(n);return r.isGreaterThanOrEqualTo(0)&&s.isGreaterThanOrEqualTo(0)?o.isLessThan(a)?1:o.isGreaterThan(a)?-1:0:r.isLessThan(0)&&s.isLessThan(0)?o.isLessThan(a)?-1:o.isGreaterThan(a)?1:0:s.isLessThan(r)?-1:s.isGreaterThan(r)?1:0}}},Ft=class e{events;poly;_isExteriorRing;_enclosingRing;static factory(t){const i=[];for(let n=0,r=t.length;n0&&(e=i)}let t=e.segment.prevInResult(),i=t?t.prevInResult():null;for(;;){if(!t)return null;if(!i)return t.ringOut;if(i.ringOut!==t.ringOut)return i.ringOut?.enclosingRing()!==t.ringOut?t.ringOut:t.ringOut?.enclosingRing();t=i.prevInResult(),i=t?t.prevInResult():null}}},zt=class{exteriorRing;interiorRings;constructor(e){this.exteriorRing=e,e.poly=this,this.interiorRings=[]}addInterior(e){this.interiorRings.push(e),e.poly=this}getGeom(){const e=this.exteriorRing.getGeom();if(null===e)return null;const t=[e];for(let e=0,i=this.interiorRings.length;e0?(this.tree.delete(t),i.push(e)):(this.segments.push(t),t.prev=n)}else{if(n&&r){const e=n.getIntersection(r);if(null!==e){if(!n.isAnEndpoint(e)){const t=this._splitSafely(n,e);for(let e=0,n=t.length;e0)return-1;const n=t.comparePoint(e.rightSE.point);return 0!==n?n:-1}if(i.isGreaterThan(n)){if(s.isLessThan(a)&&s.isLessThan(c))return-1;if(s.isGreaterThan(a)&&s.isGreaterThan(c))return 1;const i=t.comparePoint(e.leftSE.point);if(0!==i)return i;const n=e.comparePoint(t.rightSE.point);return n<0?1:n>0?-1:1}if(s.isLessThan(a))return-1;if(s.isGreaterThan(a))return 1;if(r.isLessThan(o)){const i=t.comparePoint(e.rightSE.point);if(0!==i)return i}if(r.isGreaterThan(o)){const i=e.comparePoint(t.rightSE.point);if(i<0)return 1;if(i>0)return-1}if(!r.eq(o)){const e=l.minus(s),t=r.minus(i),h=c.minus(a),d=o.minus(n);if(e.isGreaterThan(t)&&h.isLessThan(d))return 1;if(e.isLessThan(t)&&h.isGreaterThan(d))return-1}return r.isGreaterThan(o)?1:r.isLessThan(o)||l.isLessThan(c)?-1:l.isGreaterThan(c)?1:e.idt.id?1:0}constructor(e,t,i,n){this.id=++Ht,this.leftSE=e,e.segment=this,e.otherSE=t,this.rightSE=t,t.segment=this,t.otherSE=e,this.rings=i,this.windings=n}static fromRing(t,i,n){let r,o,s;const a=Pt.comparePoints(t,i);if(a<0)r=t,o=i,s=1;else{if(!(a>0))throw new Error(`Tried to create degenerate segment at [${t.x}, ${t.y}]`);r=i,o=t,s=-1}const l=new Pt(r,!0),c=new Pt(o,!1);return new e(l,c,[n],[s])}replaceRightSE(e){this.rightSE=e,this.rightSE.segment=this,this.rightSE.otherSE=this.leftSE,this.leftSE.otherSE=this.rightSE}bbox(){const e=this.leftSE.point.y,t=this.rightSE.point.y;return{ll:{x:this.leftSE.point.x,y:e.isLessThan(t)?e:t},ur:{x:this.rightSE.point.x,y:e.isGreaterThan(t)?e:t}}}vector(){return{x:this.rightSE.point.x.minus(this.leftSE.point.x),y:this.rightSE.point.y.minus(this.leftSE.point.y)}}isAnEndpoint(e){return e.x.eq(this.leftSE.point.x)&&e.y.eq(this.leftSE.point.y)||e.x.eq(this.rightSE.point.x)&&e.y.eq(this.rightSE.point.y)}comparePoint(e){return kt.orient(this.leftSE.point,e,this.rightSE.point)}getIntersection(e){const t=this.bbox(),i=e.bbox(),n=St(t,i);if(null===n)return null;const r=this.leftSE.point,o=this.rightSE.point,s=e.leftSE.point,a=e.rightSE.point,l=xt(t,s)&&0===this.comparePoint(s),c=xt(i,r)&&0===e.comparePoint(r),h=xt(t,a)&&0===this.comparePoint(a),d=xt(i,o)&&0===e.comparePoint(o);if(c&&l)return d&&!h?o:!d&&h?a:null;if(c)return h&&r.x.eq(a.x)&&r.y.eq(a.y)?null:r;if(l)return d&&o.x.eq(s.x)&&o.y.eq(s.y)?null:s;if(d&&h)return null;if(d)return o;if(h)return a;const u=((e,t,i,n)=>{if(t.x.isZero())return At(i,n,e.x);if(n.x.isZero())return At(e,t,i.x);if(t.y.isZero())return Dt(i,n,e.y);if(n.y.isZero())return Dt(e,t,i.y);const r=$t(t,n);if(r.isZero())return null;const o={x:i.x.minus(e.x),y:i.y.minus(e.y)},s=$t(o,t).div(r),a=$t(o,n).div(r),l=e.x.plus(a.times(t.x)),c=i.x.plus(s.times(n.x)),h=e.y.plus(a.times(t.y)),d=i.y.plus(s.times(n.y));return{x:l.plus(c).div(2),y:h.plus(d).div(2)}})(r,this.vector(),s,e.vector());return null===u?null:xt(n,u)?kt.snap(u):null}split(t){const i=[],n=void 0!==t.events,r=new Pt(t,!0),o=new Pt(t,!1),s=this.rightSE;this.replaceRightSE(o),i.push(o),i.push(r);const a=new e(r,s,this.rings.slice(),this.windings.slice());return Pt.comparePoints(a.leftSE.point,a.rightSE.point)>0&&a.swapEvents(),Pt.comparePoints(this.leftSE.point,this.rightSE.point)>0&&this.swapEvents(),n&&(r.checkForConsuming(),o.checkForConsuming()),i}swapEvents(){const e=this.rightSE;this.rightSE=this.leftSE,this.leftSE=e,this.leftSE.isLeft=!0,this.rightSE.isLeft=!1;for(let e=0,t=this.windings.length;e0){const e=i;i=n,n=e}if(i.prev===n){const e=i;i=n,n=e}for(let e=0,t=n.rings.length;e1===e.length&&e[0].isSubject;this._isInResult=i(e)!==i(t);break}}return this._isInResult}},Bt=class{poly;isExterior;segments;bbox;constructor(e,t,i){if(!Array.isArray(e)||0===e.length)throw new Error("Input geometry is not a valid Polygon or MultiPolygon");if(this.poly=t,this.isExterior=i,this.segments=[],"number"!=typeof e[0][0]||"number"!=typeof e[0][1])throw new Error("Input geometry is not a valid Polygon or MultiPolygon");const n=kt.snap({x:new lt(e[0][0]),y:new lt(e[0][1])});this.bbox={ll:{x:n.x,y:n.y},ur:{x:n.x,y:n.y}};let r=n;for(let t=1,i=e.length;tNt.run("union",e,t),Ut=(e,...t)=>Nt.run("intersection",e,t),Gt=(e,...t)=>Nt.run("difference",e,t);kt.set;const Vt=/^#[0-9a-fA-F]{6}$/;function Kt(e,t){return"string"==typeof e&&Vt.test(e)?e:t}const Yt="(?:25[0-5]|2[0-4][0-9]|1[0-9]{2}|[1-9]?[0-9])",Xt=new RegExp(`^rgb\\(${Yt}, ${Yt}, ${Yt}\\)$`);function Zt(e){if(!Array.isArray(e)||e.length<3)return null;const t=e.slice(0,3);if(!t.every(e=>"number"==typeof e&&Number.isFinite(e)))return null;const[i,n,r]=t.map(e=>Math.round(Math.min(255,Math.max(0,e))));return`rgb(${i}, ${n}, ${r})`}function Jt(e){const t=Math.max(0,Math.min(120,(e-40)/140*120));return`hsl(${Math.round(t)}, 85%, 55%)`}function Qt(e,t){if(!(Number.isFinite(e)&&t>0))return e;const i=Math.round(e/t)*t;return Math.abs(i-e)<=1e-9*t?e:i}function ei(e,t,i,n=1/0){if(!(i>0&&e?.every(Number.isFinite)&&t?.every(Number.isFinite)))return[t[0],t[1]];const r=t[0]-e[0],o=t[1]-e[1];if(Math.abs(r)+Math.abs(o)<=1e-12)return[e[0],e[1]];const s=Math.PI/4;let a=Math.atan2(o,r);a<0&&(a+=2*Math.PI);const l=Math.floor(a/s+.5)%8,[c,h]=[[1,0],[1,1],[0,1],[-1,1],[-1,0],[-1,-1],[0,-1],[1,-1]][l],d=c*c+h*h;let u=Math.max(0,Math.round((r*c+o*h)/(i*d)));if(Number.isFinite(n)&&n>=0){const t=(e,t)=>{if(!t)return 1/0;const r=t>0?n-e:e+n;return Math.max(0,Math.floor((r+1e-9*i)/i))};u=Math.min(u,t(e[0],c),t(e[1],h))}return[e[0]+c*u*i,e[1]+h*u*i]}function ti(e,t){if(t){const t=e/2.54;let i=Math.floor(t/12),n=Math.round(t-12*i);return 12===n&&(i+=1,n=0),`${i}′ ${n}″`}return`${(e/100).toFixed(2)} m`}function ii(e,t,i=1){const n=e[0].toFixed(i),r=e[1].toFixed(i),o=t[0].toFixed(i),s=t[1].toFixed(i),a=n=3?e.poly:e&&null!=e.x&&null!=e.y&&null!=e.w&&null!=e.h?[[e.x,e.y],[e.x+e.w,e.y],[e.x+e.w,e.y+e.h],[e.x,e.y+e.h]]:null}function ri(e){const t=[];for(const i of e||[])i?.poly?.length>=3?t.push({poly:i.poly.map(e=>e.join(",")).join(" ")}):i&&null!=i.x&&null!=i.y&&null!=i.w&&null!=i.h&&t.push({rect:{x:i.x,y:i.y,w:i.w,h:i.h,rx:.03*Math.min(i.w,i.h)}});return t}function oi(e){const t=[],i=new Set;for(const n of e||[]){const e=ni(n);if(e)for(let n=0;n=90?e-=180:e<-90&&(e+=180),n.step&&n.step>0){const i=Math.sqrt(d),o=Math.min(Math.max(n.length||0,0)/2,i/2);let a=Math.round(u*i/n.step)*n.step;Math.abs(u*i-i/2)<=n.step/2&&(a=i/2),a=Math.max(o,Math.min(i-o,a));const l=a/i;r={x:t+l*c,y:s+l*h,angle:e}}else r={x:p[0],y:p[1],angle:e}}}return r}function ai(e,t,i){let n=null,r=1/0;for(let o=0;o=r)continue;r=_;const m=Math.sqrt(u),g=(i>0?Math.max(0,Math.min(m,Math.round(p*m/i)*i)):p*m)/m;n=[s+g*h,a+g*d]}return n}function li(e,t,i,n,r,o=1){const s=t*Math.PI/180,a=[Math.cos(s),Math.sin(s)];let l=null,c=o;for(const t of oi(n)){const i=[[t[0],t[1]],[t[2],t[3]]],n=t=>Math.abs(a[0]*(t[1]-e[1])-a[1]*(t[0]-e[0]));if(n(i[0])>o||n(i[1])>o)continue;const r=(i[0][0]-e[0])*a[0]+(i[0][1]-e[1])*a[1],s=(i[1][0]-e[0])*a[0]+(i[1][1]-e[1])*a[1],h=Math.min(r,s),d=Math.max(r,s),u=h>0?h:d<0?-d:0;u[e[0]+a[0]*t,e[1]+a[1]*t],g=(h+d)/2;return{wallA:m(h),wallB:m(d),sideA:p,sideB:_,midA:m((h-u)/2),midB:m((u+d)/2),wallCenter:m(g),centered:Math.abs(g)<=r}}function ci(e,t,i=!1,n){if("passage"===e)return 1;if(null==t||"unavailable"===t||"unknown"===t)return"window"===e?0:1;const r="string"==typeof n?n.trim()?Number(n):NaN:Number(n),o=null!=n&&Number.isFinite(r)?Math.max(0,Math.min(1,r/100)):function(e){return["on","open","home","detected","playing","cleaning"].includes(String(e))}(t)?1:0;return i?1-o:o}function hi(e){const t=Number.isFinite(e)?Math.max(0,Math.min(1,e)):0;return Math.min(1,Math.max(0,.05*Math.round(t/.05)))}function di(e,t){return(Number.isFinite(e)&&e>0?e:0)*(Number.isFinite(t)?Math.max(0,Math.min(1,t)):0)}function ui(e){return"passage"===e.type?[]:[e.contact,e.lock].filter(e=>"string"==typeof e&&e.length>0)}function pi(e,t,i=200){const n=t.trim().toLowerCase();return(n?e.filter(e=>e.label.toLowerCase().includes(n)||e.value.toLowerCase().includes(n)):e).slice(0,Math.max(0,i))}function _i(e,t,i=.001){return Math.abs(e[0]-t[0])e[1]!=l>e[1]&&e[0]<(a-o)*(e[1]-s)/(l-s)+o&&(i=!i)}return i}function gi(e,t,i){const n=i[0]-t[0],r=i[1]-t[1],o=n*n+r*r;let s=o?((e[0]-t[0])*n+(e[1]-t[1])*r)/o:0;return s=Math.max(0,Math.min(1,s)),Math.hypot(e[0]-(t[0]+s*n),e[1]-(t[1]+s*r))}function fi(e,t){if(!t||t.length<2)return null;let i=null,n=1/0;for(let r=0;rr&&s<-r||o<-r&&s>r)&&(a>r&&l<-r||a<-r&&l>r)}function ki(e,t=24){const i=e.map(e=>e[0]),n=e.map(e=>e[1]),r=Math.min(...i),o=Math.max(...i),s=Math.min(...n),a=Math.max(...n),l=Math.max(o-r,a-s)||1;let c=0,h=0,d=0;for(let t=0;t1e-9?[h/(3*c),d/(3*c)]:[(r+o)/2,(s+a)/2],p=(t,i)=>{const n=((t,i)=>{if(!mi([t,i],e))return-1/0;let n=1/0;for(let r=0;rm&&(m=c,_=[n,l])}if(_){const[e,i]=_,n=(o-r)/t,l=(a-s)/t;for(let t=-4;t<=4;t++)for(let r=-4;r<=4;r++){const o=e+n*t/4,s=i+l*r/4,a=p(o,s);a>m&&(m=a,_=[o,s])}}return _||xi(e)||e[0]}function xi(e,t=1e-6){if(!e||e.length<3)return null;const i=e.length,n=[e.reduce((e,t)=>e+t[0],0)/i,e.reduce((e,t)=>e+t[1],0)/i];if(yi(n,e,t))return n;for(let n=0;n$i(e,t,i));return n.filter(e=>!n.some(t=>t!==e&&$i(t,e,i)))}function Ci(e){if(!e||e.length<3)return 0;let t=0;for(let i=0;i[e[0],e[1]]),[e[0][0],e[0][1]]]]}function Di(e,t){if(!e||!t||e.length<3||t.length<3)return null;const i=Wt(Ti(e),Ti(t));if(1!==i.length)return null;if(1!==i[0].length)return null;const n=i[0][0].slice(0,-1).map(e=>[e[0],e[1]]);return n.length>=3?n:null}function Ai(e,t,i){for(let n=0;n1&&_i(i[0],i[i.length-1],t)&&i.pop(),i}function Fi(e,t,i=1e-6){if(!e||e.length<3||!t||t.length<2)return null;const n=t[0],r=t[t.length-1];if(_i(n,r,i))return null;const o=Ai(e,n,i),s=Ai(e,r,i);if(o<0||s<0)return null;const a=t.slice(1,-1);for(const t of a)if(!yi(t,e,i))return null;for(let i=0;i{const s=[t];let a=(n+1)%e.length;for(let t=0;t<=e.length&&(s.push(e[a]),a!==o);t++)a=(a+1)%e.length;return s.push(r),Pi(s,i)};let c,h;if(o===s){const s=Pi([...t],i);if(s.length<3||Ci(s)<=i)return null;const a=[];for(let i=0;i=0?t:[...t].reverse();for(const e of i)a.push(e)}c=Pi(a,i),h=s}else c=Pi([...l(n,o,r,s),...[...a].reverse()],i),h=Pi([...l(r,s,n,o),...a],i);return c.length<3||h.length<3||Ci(c)<=i||Ci(h)<=i||Math.abs(Ci(c)+Ci(h)-Ci(e))>Math.max(i,1e-6*Ci(e))?null:[c,h]}function zi(e,t,i){const[n,r]=e.split(":");return"device"===n?r:"entity"===n?"lg_"+r:t&&t.startsWith("v_")?t:i()}function Ii(e){return e.length?Math.round(e.reduce((e,t)=>e+t,0)/e.length):null}function Oi(e,t){if(t>e[2]/e[3]){const i=e[3],n=e[3]*t;return{x:e[0]-(n-e[2])/2,y:e[1],w:n,h:i}}const i=e[2],n=e[2]/t;return{x:e[0],y:e[1]-(n-e[3])/2,w:i,h:n}}function Ei(e,t,i,n){if(e.length<2)return;const r=t.x+n,o=t.x+t.w-n,s=t.y+n,a=t.y+t.h-n;for(let t=0;t<60;t++){let t=!1;for(let n=0;n=0)i=t.slice(0,r).trim(),n=t.slice(r+1).trim();else{const e=t.split(".");e.length>2&&(i=e.slice(0,2).join("."),n=e.slice(2).join("."))}return/^[a-z0-9_]+\.[a-z0-9_]+$/.test(i)?r>=0&&!n||n&&!/^[a-zA-Z0-9_.-]+$/.test(n)?null:n?{entity:i,attr:n}:{entity:i}:null}function Yi(e,t){const i=String(e??"").trim(),n=String(t??"").trim(),r=Ki(n?`${i}:${n}`:i);return r?`{${r.entity}${r.attr?`:${r.attr}`:""}}`:""}function Xi(e,t,i){const n=String(t??"").trim();if(!n)return null;const r=e?.states?.[n];if(!r)return null;const o=String(i??"").trim(),s=e=>e.slice(0,60);if(o){const t=function(e){if(null==e)return null;if(Array.isArray(e)){const t=e.map(e=>null==e?"":String(e)).join(", ");return t?t.slice(0,60):null}if("object"==typeof e)return null;const t=String(e);return""===t?null:t.slice(0,60)}(r.attributes?.[o]);if(null===t)return null;const i=e?.formatEntityAttributeValue;if("function"==typeof i)try{const t=i.call(e,r,o);if("string"==typeof t&&""!==t)return{text:s(t),formatted:!0}}catch{}return{text:t,formatted:!1}}const a=r.state;if(null==a||""===a)return null;const l=e?.formatEntityState;if("function"==typeof l)try{const t=l.call(e,r);if("string"==typeof t&&""!==t)return{text:s(t),formatted:!0}}catch{}return{text:s(String(a)),formatted:!1}}function Zi(e,t,i){const n=String(t??"").trim(),r=String(i??"").trim()||n;if(!r)return e.text;const o=e.formatted&&n?function(e,t){if(!t)return e;const i=e.replace(/\s+$/,"");return i.endsWith(t)?i.slice(0,i.length-t.length).replace(/\s+$/,""):e}(e.text,n):e.text;return`${o} ${r}`}function Ji(e,t){const i=(t?.entity||"").trim();if(!i)return"";const n=e?.states?.[i],r=n?.state;if(!n||null==r||""===r||"unavailable"===r||"unknown"===r)return Gi;const o=(t?.attr||"").trim(),s=Xi(e,i,o||null);if(null===s)return Gi;return Zi(s,o?"":String(n.attributes?.unit_of_measurement??"").trim(),t?.unit)}function Qi(e,t,i,n=()=>!0){const r=e??"";let o=!1;const s=r.replace(/\{([^{}\r\n]+)\}/g,(e,t)=>{const r=Ki(t);return r?(o=!0,n(r.entity||"")?Ji(i,r):Gi):e});if(o)return s;const a=(t?.entity||"").trim();if(!a)return r;if(!n(a)){const e=r.indexOf(Vi);return e>=0?r.slice(0,e)+Gi+r.slice(e+2):r?`${r} ${Gi}`:Gi}const l=Ji(i,t),c=r.indexOf(Vi);return c>=0?r.slice(0,c)+l+r.slice(c+2):r?`${r} ${l}`:l}const en=20;function tn(e){const t=Number(e?.scale);if(Number.isFinite(t)&&t>0)return Math.min(20,Math.max(.15,t));return{s:.7,m:1,l:1.5}[String(e?.size??"")]??1}function nn(e,t){if(!t)return e;let i=e;for(const[e,n]of Object.entries(t))i=i.split("{"+e+"}").join(String(n));return i}const rn="#55606c",on=.55,sn=20,an=25,ln={c:"#607d8b",a:.18};function cn(e,t=ln){const i=e&&"object"==typeof e?e:null,n=i?.a;return{c:Kt(i?.c,t.c),a:"number"==typeof n&&Number.isFinite(n)?Math.min(1,Math.max(0,n)):t.a}}function hn(e,t){const i=cn(e),n=t?.settings;if("custom"!==n?.fill_mode)return i;const r=n?.custom_fill;return r&&"object"==typeof r?cn(r,i):i}function dn(e,t,i){const n=(e,t)=>"number"==typeof e&&Number.isFinite(e)?e:t,r=n(e,20),o=n(t,25),s=n(i?.settings?.temp_min,r),a=n(i?.settings?.temp_max,o);return{min:Math.min(s,a),max:Math.max(s,a)}}function un(e){const t=e?.settings||{},i=!e?.plan_url,n="glow"===t.fill_mode;return{showBorders:t.show_borders??i,showNames:t.show_names??i,color:Kt(t.room_color,rn),opacity:"number"==typeof t.room_opacity?Math.min(1,Math.max(0,t.room_opacity)):.55,fill:["lqi","light","temp","custom"].includes(t.fill_mode)?t.fill_mode:"none",customFill:cn(t.custom_fill),glow:"boolean"==typeof t.glow_enabled?t.glow_enabled:n,tempMin:"number"==typeof t.temp_min?t.temp_min:20,tempMax:"number"==typeof t.temp_max?t.temp_max:25,showLqi:"boolean"==typeof t.show_lqi?t.show_lqi:null,cardFontScale:"number"==typeof t.card_font_scale&&t.card_font_scale>0?Math.min(3,Math.max(.5,t.card_font_scale)):1,labelTemp:!0===t.label_temp,labelHum:!0===t.label_hum,labelLqi:!0===t.label_lqi,labelLight:!0===t.label_light,bgColor:Kt(t.bg_color,null),hideDecor:!0===t.hide_decor,hideOpenings:!0===t.hide_openings}}function pn(e,t){if(t.bgColor)return t.bgColor;const i=e?.bg_color;return Kt(i,"")}function _n(e){return!1!==e?.show_room_tooltip}const mn={light_on:{c:"#ffd45c",a:.18},light_off:{c:"#9aa0a6",a:.14},light_none:{c:"#6b7480",a:0},temp_cold:{c:"#4fc3f7",a:.18},temp_ok:{c:"#66d17a",a:.18},temp_hot:{c:"#ffd45c",a:.18},lqi_low:{c:"#f25a4a",a:.18},lqi_high:{c:"#4bd28f",a:.18},glow_base:{c:"#0d1b2a",a:.5},glow_light:{c:"#ffd9a0",a:.85},wall_fill:{c:"#ffffff",a:1}};function gn(e){const t={},i=e?.fill_colors||{};for(const e of Object.keys(mn)){const n=mn[e],r=i[e];t[e]={c:Kt(r?.c,n.c),a:r&&"number"==typeof r.a?Math.min(1,Math.max(0,r.a)):n.a}}return t}function fn(e,t,i){const n=Math.min(1,Math.max(0,i)),r=[1,3,5].map(t=>parseInt(e.slice(t,t+2),16)),o=[1,3,5].map(e=>parseInt(t.slice(e,e+2),16)),s=r.map((e,t)=>Math.round(e+(o[t]-e)*n));return"#"+s.map(e=>e.toString(16).padStart(2,"0")).join("")}function vn(e,t,i,n,r,o,s,a=ln){const l=function(e,t,i,n,r,o,s,a=ln){if("custom"===e)return cn(a);if("lqi"===e){if(null==t)return null;const e=(t-40)/140;return{c:fn(s.lqi_low.c,s.lqi_high.c,e),a:s.lqi_low.a+(s.lqi_high.a-s.lqi_low.a)*Math.min(1,Math.max(0,e))}}if("light"===e)return"none"===i?s.light_none.a>0?s.light_none:null:"on"===i?s.light_on:s.light_off;if("temp"===e){if(null==n)return null;const e=Math.min(r,o),t=Math.max(r,o);return nt?s.temp_hot:s.temp_ok}return null}(e,t,i,n,r,o,s,a);return l?{color:l.c,opacity:l.a,mode:e}:null}const yn={blind:["mdi:blinds","mdi:blinds-open"],shade:["mdi:blinds","mdi:blinds-open"],shutter:["mdi:window-shutter","mdi:window-shutter-open"],curtain:["mdi:curtains-closed","mdi:curtains"],window:["mdi:window-closed","mdi:window-open"],awning:["mdi:awning-outline","mdi:awning"],door:["mdi:door-closed","mdi:door-open"],garage:["mdi:garage","mdi:garage-open"],gate:["mdi:gate","mdi:gate-open"],damper:["mdi:circle-slice-8","mdi:circle-outline"]},bn=[["mdi:roller-shade-closed","mdi:roller-shade"],["mdi:blinds-horizontal-closed","mdi:blinds-horizontal"],["mdi:garage-variant","mdi:garage-open-variant"],["mdi:door","mdi:door-open"]];function wn(e){for(const t of[...Object.values(yn),...bn])if(e===t[0]||e===t[1])return t;return null}function kn(e,t,i,n,r){if(!n||"unavailable"===n||"unknown"===n)return e;if(r){const i="cover"===t?wn(e):null;return i?"closed"===n?i[0]:i[1]:e}if("binary_sensor"===t){if("door"===i)return"on"===n?"mdi:door-open":"mdi:door-closed";if("window"===i)return"on"===n?"mdi:window-open":"mdi:window-closed";if("garage_door"===i)return"on"===n?"mdi:garage-open-variant":"mdi:garage-variant"}if("cover"===t){const t=yn[String(i||"")];if(t)return"closed"===n?t[0]:t[1];const r=wn(e);return r?"closed"===n?r[0]:r[1]:e}return"lock"===t?"locked"===n?"mdi:lock":"mdi:lock-open-variant":"light"===t&&"mdi:lightbulb"===e&&"on"===n?"mdi:lightbulb-on":e}function xn(e){const t=Math.min(4e4,Math.max(1e3,e))/100,i=t<=66?255:329.698727446*Math.pow(t-60,-.1332047592),n=t<=66?99.4708025861*Math.log(t)-161.1195681661:288.1221695283*Math.pow(t-60,-.0755148492),r=t>=66?255:t<=19?0:138.5177312231*Math.log(t-10)-305.0447927307,o=e=>Math.round(Math.min(255,Math.max(0,e)));return[o(i),o(n),o(r)]}const Sn=1/2.2;function $n(e){const t=/^rgb\(\s*(\d+)\s*,\s*(\d+)\s*,\s*(\d+)\s*\)$/.exec(e);return t?"#"+t.slice(1).map(e=>Math.min(255,Number(e)).toString(16).padStart(2,"0")).join(""):null}function Mn(e){if(!e||"object"!=typeof e||Array.isArray(e))return null;const t=e;if(Object.keys(t).some(e=>"c"!==e&&"bri"!==e))return null;const i=Kt(t.c,null);return i?void 0===t.bri||null===t.bri?{c:i}:"number"!=typeof t.bri||!Number.isFinite(t.bri)||t.bri<.01||t.bri>1?null:{c:i,bri:t.bri}:null}function Rn(e,t,i){const n=Mn(t),r=e?.attributes||{},o=n?.bri??function(e){const t=e?.attributes?.brightness,i="number"==typeof t?t:"string"==typeof t&&""!==t.trim()?Number(t):Number.NaN;return Number.isFinite(i)?Math.max(0,Math.min(1,i/255)):1}(e);if(n)return{c:n.c,bri:o};const s=Zt(r.rgb_color);if(s)return{c:$n(s)||Kt(i,"#ffd9a0"),bri:o};const a=Number(r.color_temp_kelvin)||(Number(r.color_temp)>0?1e6/Number(r.color_temp):NaN);return Number.isFinite(a)&&a>0?{c:(l=xn(a),"#"+l.slice(0,3).map(e=>Math.min(255,Math.max(0,Math.round(Number(e)||0))).toString(16).padStart(2,"0")).join("")),bri:o}:{c:Kt(i,"#ffd9a0"),bri:o};var l}function Cn(e,t,i){return"on"===e?.state?Rn(e,t,i):null}function Tn(e,t=1){const i=Math.max(0,Math.min(1,Number.isFinite(e)?e:1)),n=.7*Math.max(0,Math.min(1,Number.isFinite(t)?t:1))*(.4+.6*Math.pow(i,Sn));return Math.max(0,Math.min(1,n))}function Dn(e){return e.startsWith("light.")||e.startsWith("switch.")}function An(e,t,i=1e-6){const n=[];if(!e||!t||e.length<3||t.length<3)return n;for(let r=0;ru||l>u)continue;const p=(r[0]-o[0])*h+(r[1]-o[1])*d,_=(s[0]-o[0])*h+(s[1]-o[1])*d,m=Math.max(0,Math.min(p,_)),g=Math.min(c,Math.max(p,_));g-m>i&&n.push([o[0]+h*m,o[1]+d*m,o[0]+h*g,o[1]+d*g])}}return n}function Pn(e,t,i=1e-6){const n=[];for(const r of e){const e=[r[0],r[1]],o=[r[2],r[3]],s=o[0]-e[0],a=o[1]-e[1],l=Math.hypot(s,a);if(lo||r>o)continue;const s=(n[0]-e[0])*c+(n[1]-e[1])*h,a=(n[2]-e[0])*c+(n[3]-e[1])*h,u=Math.max(0,Math.min(s,a)),p=Math.min(l,Math.max(s,a));p-u>i&&d.push([u,p])}if(!d.length){n.push([e[0],e[1],o[0],o[1]]);continue}d.sort((e,t)=>e[0]-t[0]);let u=0;for(const[t,r]of d)t-u>i&&n.push([e[0]+c*u,e[1]+h*u,e[0]+c*t,e[1]+h*t]),u=Math.max(u,r);l-u>i&&n.push([e[0]+c*u,e[1]+h*u,o[0],o[1]])}return n}function Fn(e,t,i=1e-6){const n=[];for(let t=0;t{if("string"!=typeof e||!e)return;const i=En(e);i.startsWith("/api/houseplan/content/")&&t.add(i)};for(const t of e?.spaces||[]){i(t?.plan_url);for(const e of t?.markers||[])for(const t of e?.pdfs||[])i(t?.url)}for(const t of e?.markers||[])for(const e of t?.pdfs||[])i(e?.url);return t}function En(e){return e?e.startsWith("/houseplan_files/plans/")?"/api/houseplan/content/plans/_/"+e.slice(23):e.startsWith("/houseplan_files/files/")?"/api/houseplan/content/files/"+e.slice(23):e:""}function Nn(e,t){const i=t?.settings?.fill_mode;return"none"===i||"lqi"===i||"light"===i||"temp"===i||"custom"===i?i:e}function Hn(e,t){const i=t?.settings;return"boolean"==typeof i?.glow?i.glow:"glow"===i?.fill_mode||e}function Ln(e,t,i,n){if(!t||!i||t===i)return e;const r="/files/"+t+"/",o="/files/"+i+"/";return e.map(e=>{if(!e.url.includes(r))return e;const t=e.url.split(r)[1]||"",[i,s]=[t.split("?")[0],t.includes("?")?"?"+t.split("?")[1]:""];if(n){const t=n[decodeURIComponent(i)]??n[i];return t?{...e,url:e.url.split(r+i)[0]+o+encodeURIComponent(t)+s}:e}return{...e,url:e.url.split(r).join(o)}})}function Bn(e,t=1){const i=Number(e);return Number.isFinite(i)&&i>0?Math.min(3,Math.max(.5,i)):t}function qn(e,t,i){let n=null,r=null;for(const o of t){if(!(Math.abs(o[0]-e[0])<1e-6&&Math.abs(o[1]-e[1])<1e-6)){if(Math.abs(o[0]-e[0])<=i){const t=Math.abs(o[1]-e[1]);t>1e-6&&(!n||t1e-6&&(!r||t"number"==typeof e&&Number.isFinite(e),tr=(e,t,i)=>Math.min(i,Math.max(t,e));function ir(e){return e.elevation<=-6?"night":e.elevation>=6?"day":e.rising?"dawn":"dusk"}function nr(e){const t=(Math.floor(Number(e)||0)%1440+1440)%1440;return t>=300&&t<480?"dawn":t>=480&&t<1080?"day":t>=1080&&t<1260?"dusk":"night"}function rr(e){const t=ir(e),i=e.azimuth*Math.PI/180;return{sunX:50-42*Math.sin(i),sunY:78-tr(e.elevation,0,90)/90*64,sunOpacity:"night"===t?0:tr((e.elevation+6)/12,0,1)}}function or(e){const t=(Math.floor(Number(e)||0)%1440+1440)%1440;if(t<300||t>=1260)return{sunX:50,sunY:78,sunOpacity:0};const i=(t-300)/960,n=(t-300)/120,r=(1260-t)/120;return{sunX:8+84*i,sunY:78-64*Math.sin(i*Math.PI),sunOpacity:Math.max(.18,Math.min(n,r,1))}}function sr(e,t=new Date){const i=function(e){const t=e?.states?.["sun.sun"]?.attributes;return t&&er(t.azimuth)&&er(t.elevation)&&"boolean"==typeof t.rising?{azimuth:Zn(t.azimuth),elevation:t.elevation,rising:t.rising}:null}(e);if(i)return{phase:ir(i),source:"sun",...rr(i)};const n="number"==typeof t?t:function(e=new Date){return 60*e.getHours()+e.getMinutes()}(t);return{phase:nr(n),source:"clock",...or(n)}}function ar(e){return`${e.source}|${e.phase}|${e.sunX.toFixed(2)}|${e.sunY.toFixed(2)}|`+e.sunOpacity.toFixed(3)}const lr=[[-90,"#070c14"],[-12,"#070c14"],[-4,"#131a28"],[0,"#4a3527"],[10,"#e8ddcf"],[30,"#ffffff"],[90,"#ffffff"]],cr=e=>Math.min(1,Math.max(0,e));function hr(e,t,i=6){const n=e.angle*Math.PI/180,r=[Math.sin(n),-Math.cos(n)],o=n=>{const o=[e.x+r[0]*i*n,e.y+r[1]*i*n];return t.find(e=>e.poly.length>=3&&mi(o,e.poly))||null},s=o(1),a=o(-1);return s&&a?null:s||a?s?{normal:[-r[0],-r[1]],roomId:s.id}:{normal:r,roomId:a.id}:null}function dr(e,t,i){return i>0&&e[0]*t[0]+e[1]*t[1]>.05}function ur(e,t,i,n){return[[e[0],e[1]],[t[0],t[1]],[t[0]+i[0]*n,t[1]+i[1]*n],[e[0]+i[0]*n,e[1]+i[1]*n]]}function pr(e,t){return _r(e,t)}function _r(...e){try{if(!e.length||e.some(e=>e.length<3))return[];const t=e.map(e=>[[...e.map(e=>[e[0],e[1]]),[e[0][0],e[0][1]]]]),i=Ut(t[0],...t.slice(1)),n=[];for(const e of i){const t=e[0];!Array.isArray(t)||t.length<4||n.push(t.slice(0,t.length-1).map(e=>[e[0],e[1]]))}return n}catch{return[]}}function mr(e,t,i,n,r,o,s,a="inner"){if(!(n>0))return[];const l=Jn(i,r),c=[-l[0],-l[1]],h=function(e){const t=Math.min(90,Math.max(0,e));return.7*(.8+1.7*Math.pow(1-t/90,1.6))}(n),d=[];for(const i of t){if(!(i.length>0))continue;const t=hr(i,e);if(!t||!dr(t.normal,l,n))continue;const r=e.find(e=>e.id===t.roomId);if(!r)continue;const u=o&&o[t.roomId]||r.poly,p=i.angle*Math.PI/180,_=i.length/2,m=[-t.normal[0],-t.normal[1]],g=Math.max(0,s?.[i.id]||0),f=Math.cos(p)*_,v=Math.sin(p)*_,y="outer"===a?-1:1,b=i.x+m[0]*g*y/2,w=i.y+m[1]*g*y/2,k=[b-f,w-v],x=[b+f,w+v],S=h*i.length,$=ur(k,x,c,S);let M,R=pr($,u);if("outer"===a&&g>0){const e=i.x+m[0]*g/2,t=i.y+m[1]*g/2,n=[e-f,t-v],r=[e+f,t+v],o=[[b-f,w-v],[b+f,w+v],[e+f,t+v],[e-f,t-v]];R=[..._r($,ur(n,r,c,S),u),..._r($,o)],M=[k,x,n,r]}if(!R.length)continue;const C=c[0]*m[0]+c[1]*m[1];d.push({openingId:i.id,roomId:t.roomId,polys:R,a:k,b:x,rimSources:M,dir:c,len:S,normal:m,depth:S*C})}return d}const gr=e=>"number"==typeof e&&Number.isInteger(e)&&e>=0&&e<=359?e:null;function fr(e,t){const i=gr(t?.north_deg);return null!==i?i:gr(e?.north_deg)}function vr(e){return"outer"===e?.sun_ray_origin?"outer":"inner"}function yr(e,t){const i=e=>"static"===e||"daynight"===e?e:null;return i(t?.bg_mode)??i(e?.bg_mode)??"static"}function br(e,t){const i=t?.sun_rays;return"boolean"==typeof i?i:!0===e?.sun_rays}function wr(e){const t=e?.states?.["sun.sun"]?.attributes,i=Number(t?.azimuth),n=Number(t?.elevation);return Number.isFinite(i)&&Number.isFinite(n)?{azimuth:i,elevation:n}:null}const kr=["dawn","day","dusk","night"];function xr(e){if(!e)return"";const t=Qn[e.phase];return[`--hp-day-cycle-outline-near:${t.outlineNear}`,`--hp-day-cycle-outline-mid:${t.outlineMid}`,`--hp-day-cycle-outline-far:${t.outlineFar}`].join(";")}function Sr(e,t=1){if(!e)return G;const i=[`--hp-day-cycle-sun-x:${e.sunX.toFixed(2)}%`,`--hp-day-cycle-sun-y:${e.sunY.toFixed(2)}%`,`--hp-day-cycle-sun-opacity:${e.sunOpacity.toFixed(3)}`,`opacity:${Math.min(1,Math.max(0,t)).toFixed(4)}`].join(";");return j``}function $r(e,t="hp-paperg"){return W`${e.map(e=>"path"in e?W``:"poly"in e?W``:W``)}`}const Mr={color:"#607d8b",opacity:1,widthCm:3.6,fill:!1,fillColor:"#607d8b",fillOpacity:.25},Rr=(e,t=1)=>{const i=Number(e);return Number.isFinite(i)?Math.min(1,Math.max(0,i)):t},Cr=e=>{let t=Number(e);return Number.isFinite(t)?(t=(t%360+360)%360,t>180?t-360:t):0};function Tr(e,t,i){return Cr(t)?[e.x,e.y]:i([e.x,e.y])}function Dr(e,t,i,n){const r=Math.abs(i[0]-t[0]),o=Math.abs(i[1]-t[1]);return"line"===e?Math.hypot(r,o)>=n:r>=n&&o>=n}const Ar=(e,t,i)=>{const n=Number(e),r=Number.isFinite(t)&&t>0?t:5;return Number.isFinite(n)&&n>0?n/r*i:0},Pr=(e,t,i)=>{const n=Number(e),r=Number.isFinite(t)&&t>0?t:5;return Number.isFinite(n)&&i>0?n/i*r:0},Fr=(e,t,i,n=Mr.widthCm)=>{const r=Number(e?.width_cm);if(Number.isFinite(r)&&r>0)return r;const o=Number(e?.width);return Number.isFinite(o)&&o>0?Pr(o,t,i):n};function zr(e){const t=Mr;return e.color===t.color&&e.opacity===t.opacity&&e.widthCm===t.widthCm&&e.fill===t.fill&&e.fillColor===t.fillColor&&e.fillOpacity===t.fillOpacity?null:{color:e.color,opacity:Rr(e.opacity),width_cm:Math.max(.1,Math.min(100,Number(e.widthCm)||.1)),fill:!!e.fill,fill_color:e.fillColor,fill_opacity:Rr(e.fillOpacity,.25)}}function Ir(e,t){return{color:e.color,opacity:Rr(e.opacity),width_cm:Math.max(.1,Math.min(100,Number(e.widthCm)||.1)),...t?{fill:e.fill,fill_color:e.fillColor,fill_opacity:Rr(e.fillOpacity,.25)}:{}}}function Or(e){const t=e.x+e.w/2,i=e.y+e.h/2,n=Cr(e.angle)*Math.PI/180,r=Math.cos(n),o=Math.sin(n),s=(e,n)=>{const s=e-t,a=n-i;return[t+s*r-a*o,i+s*o+a*r]};return[s(e.x,e.y),s(e.x+e.w,e.y),s(e.x+e.w,e.y+e.h),s(e.x,e.y+e.h)]}function Er(e){const t=Or(e),i=(e,t)=>[(e[0]+t[0])/2,(e[1]+t[1])/2],n=[(t[0][0]+t[2][0])/2,(t[0][1]+t[2][1])/2];return{points:[...t,i(t[0],t[1]),i(t[1],t[2]),i(t[2],t[3]),i(t[3],t[0]),n],segments:t.map((e,i)=>({a:e,b:t[(i+1)%4]}))}}function Nr(e,t,i,n,r,o,s,a){const l=Cr(e.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l),d=-Math.sin(l),u=Math.cos(l),p=e.x+e.w/2,_=e.y+e.h/2,m=t>0?-e.w/2:e.w/2,g=i>0?-e.h/2:e.h/2,f=p+m*c+g*d,v=_+m*h+g*u,y=n-f,b=r-v;let w=(y*c+b*h)*(t>0?1:-1),k=(y*d+b*u)*(i>0?1:-1),x=null;if(o){const t=w/Math.max(e.w,a),i=k/Math.max(e.h,a);x=Math.max(a/Math.max(e.w,a),a/Math.max(e.h,a),t,i),w=e.w*x,k=e.h*x}if(s>0)if(o){const t=Math.max(1,Math.round(e.w/s)),i=Math.max(1,Math.round(e.h/s));if(Math.abs(e.w-t*s)<1e-6&&Math.abs(e.h-i*s)<1e-6){const n=(e,t)=>{let i=Math.abs(e),n=Math.abs(t);for(;n;)[i,n]=[n,i%n];return Math.max(1,i)},r=1/n(t,i),o=Math.max(a/e.w,a/e.h),s=Math.max(o,Math.round((x??1)/r)*r);w=e.w*s,k=e.h*s}else{e.w>=e.h?(w=Math.round(w/s)*s,k=w*(e.h/Math.max(e.w,a))):(k=Math.round(k/s)*s,w=k*(e.w/Math.max(e.h,a)))}}else w=Math.round(w/s)*s,k=Math.round(k/s)*s;w=Math.max(a,w),k=Math.max(a,k);return{x:f+(t>0?w/2:-w/2)*c+(i>0?k/2:-k/2)*d-w/2,y:v+(t>0?w/2:-w/2)*h+(i>0?k/2:-k/2)*u-k/2,w:w,h:k,angle:Cr(e.angle)||void 0}}const Hr=(e,t,i)=>{const n=i[0]-t[0],r=i[1]-t[1],o=n*n+r*r;if(o<1e-12)return[...t];const s=Math.max(0,Math.min(1,((e[0]-t[0])*n+(e[1]-t[1])*r)/o));return[t[0]+n*s,t[1]+r*s]};function Lr(e,t,i,n){const r=n(e);let o=null;for(const r of t.points){const t=n(r),s=Math.hypot(t[0]-e[0],t[1]-e[1]);s<=i&&(!o||se.points),segments:e.flatMap(e=>e.segments)}}const qr=Math.tan(.25*Math.PI/180);function jr(e,t){const i=Math.abs(Number(t[0])-Number(e[0])),n=Math.abs(Number(t[1])-Number(e[1]));if(!([i,n].every(Number.isFinite)&&i>0&&n>0))return null;const r=i>=n?"horizontal":"vertical",o=Math.max(i,n),s=Math.min(i,n);return s/o>qr?null:{axis:r,major:o,minor:s,angleDegrees:180*Math.atan2(s,o)/Math.PI}}function Wr(e,t){const i=jr(e,t);return i?"horizontal"===i.axis?[Number(t[0]),Number(e[1])]:[Number(e[0]),Number(t[1])]:[Number(t[0]),Number(t[1])]}const Ur=e=>`${e[0]},${e[1]}`,Gr=(e,t)=>e[0]===t[0]&&e[1]===t[1],Vr=(e,t)=>{const i=Ur(e),n=Ur(t);return i{let t=0;for(let i=0;i{if(e.length<3)return!1;for(let t=0;t1e-12},Xr=(e,t)=>Gr(e,t.from)?[...t.to]:[...e],Zr=(e,t)=>e.map(e=>Array.isArray(e?.poly)?{...e,poly:e.poly.map(e=>Xr(e,t))}:e),Jr=(e,t,i)=>{const n=e.flatMap((e,t)=>ni(e)?.some(e=>Gr(e,i.from))?[t]:[]);if(!n.length)return!1;for(const i of n){const n=ni(e[i]),r=ni(t[i]);if(!n||!r)continue;if(!Yr(r))return!1;const o=Math.sign(Kr(n)),s=Math.sign(Kr(r));if(o&&s&&o!==s)return!1}const r=new Set;for(const e of n){const i=ni(t[e]);if(i)for(let n=0;n{let i=0;for(const n of e){const e=ni(n);if(e)for(let n=0;n{const{a:i,b:n,axis:r}=e,o="horizontal"===r?{from:n,to:[n[0],i[1]]}:{from:n,to:[i[0],n[1]]},s="horizontal"===r?{from:i,to:[i[0],n[1]]}:{from:i,to:[n[0],i[1]]};return[{move:o,preservedDegree:Qr(t,i)},{move:s,preservedDegree:Qr(t,n)}].sort((e,t)=>t.preservedDegree-e.preservedDegree||Ur(e.move.to).localeCompare(Ur(t.move.to))||Ur(e.move.from).localeCompare(Ur(t.move.from))).map(e=>e.move)};function to(e){const t=JSON.parse(JSON.stringify(e||{}));let i=Array.isArray(t.rooms)?t.rooms:[];const n=new Map;for(const e of i){const t=ni(e);if(t)for(let e=0;ee.key.localeCompare(t.key))){let t=null;for(const n of eo(e,i)){const e=a.get(Ur(n.from));if(e&&e!==Ur(n.to))continue;const r=Zr(i,n);if(Jr(i,r,n)){t=n,i=r;break}}t?(a.set(Ur(t.from),Ur(t.to)),r++,s=Math.max(s,Math.hypot(t.to[0]-t.from[0],t.to[1]-t.from[1]))):o++}t.rooms=i;for(const e of t.partitions||[]){if(!Array.isArray(e?.a)||!Array.isArray(e?.b))continue;const i=jr(e.a,e.b);if(!i)continue;const n={key:String(e.id||Vr(e.a,e.b)),a:[...e.a],b:[...e.b],axis:i.axis};let a=null;for(const i of eo(n,[{poly:[e.a,e.b]}])){const n=Xr(e.a,i),r=Xr(e.b,i),o=Math.hypot(r[0]-n[0],r[1]-n[1]);if(!(o>0))continue;const s=(t.openings||[]).filter(t=>"partition"===t?.host?.kind&&t.host.id===e.id).every(e=>{const t=Number(e.host.t),i=Number(e.length);return Number.isFinite(t)&&t>=0&&t<=1&&Number.isFinite(i)&&i>0&&t*o-i/2>=-1e-12&&t*o+i/2<=o+1e-12});if(s){a=i,e.a=n,e.b=r;break}}a?(r++,s=Math.max(s,Math.hypot(a.to[0]-a.from[0],a.to[1]-a.from[1]))):o++}return{space:t,report:{wallsStraightened:r,wallsStraightenSkipped:o,maxStraightenShift:s},changed:r>0}}const io=["rect","ellipse","furniture","image"],no=10**9,ro=240,oo=1e-4;function so(e){if(Array.isArray(e))return e.map(e=>so(e));if(null!==e&&"object"==typeof e){const t={};for(const[i,n]of Object.entries(e))t[i]=so(n);return t}return e}function ao(e){if("number"!=typeof e||!Number.isFinite(e))return e;const t=(e<0||Object.is(e,-0)?-1:1)*(Math.floor(Math.abs(e)*no+.5)/no);return 0===t?0:t}function lo(e){if("number"!=typeof e||!Number.isFinite(e))return e;const t=e*ro,i=Math.round(t);if(Math.abs(t-i)null!==ho(e)):[]}function po(e){return"string"==typeof e&&io.includes(e)}function _o(e,t){for(const i of t)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=ao(e[i]))}function mo(e,t){for(const i of t)Object.prototype.hasOwnProperty.call(e,i)&&(e[i]=lo(e[i]))}function go(e){if(Array.isArray(e))for(let t=0;t{for(const r of n){const n=t[r];"number"==typeof n&&Number.isFinite(n)&&i(n,e)}},n=t=>{if(Array.isArray(t))for(let n=0;n{if(Array.isArray(e))for(const t of e)n(t)};for(const i of uo(e.rooms))t(i,["x","y","w","h"]),r(i.poly);for(const t of uo(e.walls))n(t.a),n(t.b);for(const t of uo(e.wall_segments))n(t.a),n(t.b);for(const i of uo(e.openings))t(i,["x","y"]);for(const i of uo(e.decor))"line"===i.kind?t(i,["x1","y1","x2","y2"]):po(i.kind)?t(i,["x","y","w","h"]):"text"===i.kind&&t(i,["x","y"]);for(const t of uo(e.room_drafts))r(t.points);for(const t of uo(e.partitions))n(t.a),n(t.b);for(const t of uo(e.wall_columns))n(t.center);for(const t of uo(e.open_spans))n(t.a),n(t.b)}const r=ho(t);if(!r)return;const o=new Map;if(n)for(const e of uo(n.spaces))null!=e.id&&o.set(String(e.id),e);for(const e of Object.values(r)){const t=ho(e);if(!t)continue;const n=null!=t.s&&o.get(String(t.s))||null;for(const e of["x","y"]){const r=t[e];"number"==typeof r&&Number.isFinite(r)&&i(r,n)}}}function yo(e){const t=Number(e?.cell_cm);return t>0?t:5}function bo(e,t={}){const i={canonicalized:0,far:0,maxShift:0,maxShiftCm:0,spaces:[],bySpace:new Map},n=uo(ho(e)?.spaces);let r=5;for(const e of n)r=Math.max(r,yo(e));vo(e,t,(e,t)=>{const n=e*ro,o=Math.abs(n-Math.round(n)),s=lo(e),a=o>0&&o=oo))return;const l=a&&"number"==typeof s?Math.abs(s-e):0;if(a?i.canonicalized++:i.far++,i.maxShift=Math.max(i.maxShift,l),i.maxShiftCm=Math.max(i.maxShiftCm,l*ro*(t?yo(t):r)),!t?.id||!a)return;const c=String(t.id);let h=i.bySpace.get(c);h||(h={spaceId:c,space:String(t.title||c),canonicalized:0,far:0,maxShift:0,maxShiftCm:0},i.bySpace.set(c,h)),h.canonicalized++,h.maxShift=Math.max(h.maxShift,l),h.maxShiftCm=Math.max(h.maxShiftCm,l*ro*yo(t))}),i.bySpace.size&&vo(e,t,(e,t)=>{if(!t?.id)return;const n=i.bySpace.get(String(t.id));if(!n)return;const r=e*ro;Math.abs(r-Math.round(r))>=oo&&n.far++}),i.spaces=[...i.bySpace.values()];const{bySpace:o,...s}=i;return s}function wo(e){return function(e){const t=e,i=ho(t);i&&mo(i,["x","y"]);return t}(so(e))}function ko(e){const t=e,i=ho(t);if(!i)return t;for(const e of Object.values(i)){const t=ho(e);t&&mo(t,["x","y"])}return t}function xo(e){return So(so(e))}function So(e){const t=e,i=ho(t);if(!i)return t;for(const e of uo(i.spaces)){_o(e,["plan_x","plan_y","plan_scale","plan_scale_x","plan_scale_y","plan_angle"]);for(const t of uo(e.rooms))mo(t,["x","y","w","h"]),fo(t.poly);for(const t of uo(e.walls))go(t.a),go(t.b);for(const t of uo(e.wall_segments))go(t.a),go(t.b);for(const t of uo(e.openings)){mo(t,["x","y"]),_o(t,["angle","length"]);const e=ho(t.host);e&&_o(e,["t"])}for(const t of uo(e.decor))"line"===t.kind?mo(t,["x1","y1","x2","y2"]):po(t.kind)?(mo(t,["x","y","w","h"]),_o(t,["angle"])):"text"===t.kind&&(mo(t,["x","y"]),_o(t,["scale","angle"]));for(const t of uo(e.room_drafts))fo(t.points);for(const t of uo(e.partitions))go(t.a),go(t.b);for(const t of uo(e.wall_columns))go(t.center),"square"===t.shape&&_o(t,["angle"]);for(const t of uo(e.open_spans))go(t.a),go(t.b)}for(const e of uo(i.markers))_o(e,["angle"]);return t}const $o=15,Mo=8;function Ro(e,t,i,n,r){const o=i[0]-e[0],s=i[1]-e[1],a=Math.hypot(o,s);if(!(a>0)||a<=r+1e-9)return null;const l=o/a,c=s/a,h=t=>{const n=(t[0]-e[0])*l+(t[1]-e[1])*c,o=(r-n)/(a-n);return!Number.isFinite(o)||o<-1e-9||o>1+1e-9?null:[t[0]+(i[0]-t[0])*o,t[1]+(i[1]-t[1])*o]},d=h(t),u=h(n);return d&&u?[[e[0],e[1]],t,d,u,n]:null}const Co=Math.sin(.25*Math.PI/180);function To(e,t){return Number.isFinite(e)&&e>0&&Number.isFinite(t)&&t>0&&e*t<3}function Do(e){const t=Number(e)>0?Number(e):5;if(5===t)return 8;const i=5/t*8;return Math.min(80,Math.max(.5,i))}function Ao(e,t){return Number.isFinite(e)&&e>0&&Number.isFinite(t)&&t>0&&e*t<2}function Po(e){return Number.isFinite(e)?Math.max(1,Math.min(100,e)):1}function Fo(e,t){return!Number.isFinite(e)||e<0?"":String(t?Math.round(e/2.54*100)/100:Math.round(100*e)/100)}function zo(e,t,i){if(!Number.isFinite(e)||e<=0)return 0;const n=Number(t)>0?Number(t):5;return Po(e)/n*i}function Io(e,t){return t>0&&Number.isFinite(e)?Math.round(e/t)*t:e}function Oo(e){return Math.max(1e-6*Math.abs(e),1e-9)}function Eo(e,t){if(!(t>0&&Number.isFinite(e)))return e;const i=Io(e,t);return Math.abs(i-e)<=Oo(t)?i:e}function No(e,t){let i=t[0]-e[0],n=t[1]-e[1];const r=Math.hypot(i,n);return r<1e-12?[1,0]:(i/=r,n/=r,(i<-1e-12||Math.abs(i)<=1e-12&&n<0)&&(i=-i,n=-n),[i,n])}function Ho(e,t,i){const n=[Eo(e[0],i),Eo(e[1],i)],r=[Eo(t[0],i),Eo(t[1],i)],o=Io((n[0]+r[0])/2,i),s=Io((n[1]+r[1])/2,i),[a,l]=No(n,r);let c=Math.atan2(l,a);c<0&&(c+=Math.PI);const h=Math.round(1800*c)/1800,d=i>0&&i<.01?6:i<1?4:2;return`${o.toFixed(d)},${s.toFixed(d)}@${h.toFixed(4)}`}function Lo(e,t,i,n){return 1===n?Ho(e,t,i):Ho([e[0]/n,e[1]/n],[t[0]/n,t[1]/n],i)}function Bo(e,t){if(!Array.isArray(e.a)||!Array.isArray(e.b)||e.a.length<2||e.b.length<2)return null;const i=[Number(e.a[0]),Number(e.a[1]),Number(e.b[0]),Number(e.b[1])];if(!i.every(Number.isFinite))return null;const n=t>0?t:1;return[[i[0]*n,i[1]*n],[i[2]*n,i[3]*n]]}function qo(e,t,i,n,r){const o=r>0?r:1;return{key:Lo(e,t,n,o),cm:Po(i),a:[e[0]/o,e[1]/o],b:[t[0]/o,t[1]/o]}}function jo(e,t){const i=t>0?t:1,n=[];for(const t of e){const e=t.key.lastIndexOf("@");if(e<0)continue;const[r,o]=t.key.slice(0,e).split(",").map(Number),s=Number(t.key.slice(e+1));[r,o,s].every(Number.isFinite)&&n.push({w:t,x:r*i,y:o*i,ang:s})}return n}function Wo(e,t){const[i,n]=No(e,t);let r=Math.atan2(n,i);return r<0&&(r+=Math.PI),r}function Uo(e,t){let i=Math.abs(e-t);return i>Math.PI/2&&(i=Math.PI-i),i<.02}function Go(e,t,i,n,r=1){if(!e?.length)return null;const o=Lo(t,i,n,r),s=e.find(e=>e.key===o);if(s)return s;const a=r>0?r:1,l=Oo(n)*a,c=(e,t)=>Math.abs(e[0]-t[0])<=l&&Math.abs(e[1]-t[1])<=l;for(const n of e){const e=Bo(n,a);if(e&&(c(e[0],t)&&c(e[1],i)||c(e[0],i)&&c(e[1],t)))return n}const h=(t[0]+i[0])/2,d=(t[1]+i[1])/2,u=Wo(t,i),p=Math.max(.5*n,1e-9)*a;for(const t of jo(e,a))if(Uo(t.ang,u)&&Math.hypot(t.x-h,t.y-d)<=p)return t.w;return null}function Vo(e,t,i,n,r=1){const o=Go(e,t,i,n,r);if(o&&o.cm>0)return Po(o.cm);const s=function(e,t,i,n,r){if(!e?.length)return null;const o=r>0?r:1,s=Math.hypot(i[0]-t[0],i[1]-t[1]);if(s<1e-12)return null;const a=Wo(t,i),l=Math.max(.5*n,1e-9)*o;let c=null;for(const n of e){if(!(n.cm>0))continue;const e=Bo(n,o);if(!e)continue;const r=Math.hypot(e[1][0]-e[0][0],e[1][1]-e[0][1]);if(r<1e-12||!Uo(Wo(e[0],e[1]),a))continue;if(Os(t[0],t[1],e[0][0],e[0][1],e[1][0],e[1][1])>l||Os(i[0],i[1],e[0][0],e[0][1],e[1][0],e[1][1])>l)continue;if(r+l(o.has(e.key)||(e=>{const t=Bo(e,n);if(!t)return!1;const[i,o]=t,a=o[0]-i[0],c=o[1]-i[1],h=Math.hypot(a,c);if(h<=l)return!1;if(!s.some(e=>{const t=[e[0],e[1]],n=[e[2],e[3]];return Uo(Wo(i,o),Wo(t,n))&&Os(i[0],i[1],t[0],t[1],n[0],n[1])<=l&&Os(o[0],o[1],t[0],t[1],n[0],n[1])<=l}))return!1;const d=(r||[]).some(e=>{const t=[e[0],e[1]],n=[e[2],e[3]];if(!Uo(Wo(i,o),Wo(t,n)))return!1;const r=e=>Math.abs((e[0]-i[0])*c-(e[1]-i[1])*a)/h;if(r(t)>l||r(n)>l)return!1;const s=h*h,d=((t[0]-i[0])*a+(t[1]-i[1])*c)/s,u=((n[0]-i[0])*a+(n[1]-i[1])*c)/s;return Math.min(1,Math.max(d,u))-Math.max(0,Math.min(d,u))>l/h});return!d})(e))&&e.cm>=1&&e.cm<=100)}function Yo(e,t,i,n=8){const[r,o]=No(e,t);let s=Math.atan2(o,r);s<0&&(s+=Math.PI);let a=i*Math.PI/180%Math.PI;a<0&&(a+=Math.PI);let l=Math.abs(s-a);return l>Math.PI/2&&(l=Math.PI-l),l<=n*Math.PI/180}function Xo(e,t,i,n,r=1,o="affine",s){if(!e?.length)return[];if(t.length!==i.length)return"fixed-topology"===o&&s?.(),e.slice();const a=r>0?r:1,l=Math.max(.5*n,1e-9)*a,c=Math.max(n*a*1e-6,1e-9),h=[],d=new Map,u=new Map,p=(e,t,i)=>{const n=e.get(t)||new Set;n.add(i),e.set(t,n)};for(let e=0;e[e[0]+(t[0]-e[0])*i,e[1]+(t[1]-e[1])*i],m=(e,t)=>Math.hypot(e[0]-t[0],e[1]-t[1])<=c,g=(e,t)=>{if("fixed-topology"===o){const i=t.na[0]-t.oa[0],n=t.na[1]-t.oa[1],r=t.nb[0]-t.ob[0],o=t.nb[1]-t.ob[1];return Math.hypot(i-r,n-o)<=c?[e[0]+i,e[1]+n]:m(e,t.oa)?[...t.na]:m(e,t.ob)?[...t.nb]:[...e]}const i=Math.max(0,Math.min(1,((e[0]-t.oa[0])*t.dx+(e[1]-t.oa[1])*t.dy)/t.len2));return _(t.na,t.nb,i)},f=(e,t)=>{const[i,n]=No(e,t);return(t[0]-e[0])*i+(t[1]-e[1])*n>=0?[[...e],[...t]]:[[...t],[...e]]},v=[],y=[],b=(e,t,i)=>{if(Math.hypot(t[0]-e[0],t[1]-e[1])<=c)return;const[r,o]=f(e,t),s=Po(i);if(y.some(e=>e.entry.cm===s&&m(e.span[0],r)&&m(e.span[1],o)))return;const l=qo(r,o,s,n,a);v.push(l),y.push({entry:l,span:[r,o]})};for(const t of e){const e=Bo(t,a);if(e){const[i,n]=f(e[0],e[1]),r=n[0]-i[0],s=n[1]-i[1],a=r*r+s*s,d=Math.sqrt(a);if(d<=c){v.push({...t,cm:Po(t.cm)});continue}const u=[];for(const e of h){if(!Uo(Wo(i,n),Wo(e.oa,e.ob)))continue;const t=e=>Math.abs((e[0]-i[0])*s-(e[1]-i[1])*r)/d;if(t(e.oa)>l||t(e.ob)>l)continue;const o=((e.oa[0]-i[0])*r+(e.oa[1]-i[1])*s)/a,h=((e.ob[0]-i[0])*r+(e.ob[1]-i[1])*s)/a,p=Math.max(0,Math.min(o,h)),_=Math.min(1,Math.max(o,h));(_-p)*d>c&&u.push({lo:p,hi:_,move:e})}if(!u.length){"fixed-topology"===o?v.push({...t}):b(i,n,t.cm);continue}const p=[0,1,...u.flatMap(({lo:e,hi:t})=>[e,t])].sort((e,t)=>e-t).filter((e,t,i)=>0===t||Math.abs(e-i[t-1])*d>c),y=[];for(let e=0;e+1a>=e.lo-1e-12&&a<=e.hi+1e-12);if(!l.length){y.push([o,s]);continue}const h=[g(o,l[0].move),g(s,l[0].move)],f=l.slice(1).some(e=>{const t=g(o,e.move),i=g(s,e.move);return!m(h[0],t)||!m(h[1],i)});y.push(f?[o,s]:h)}const w=(e,t)=>{const i=e[1][0]-e[0][0],n=e[1][1]-e[0][1],r=t[1][0]-t[0][0],o=t[1][1]-t[0][1],s=Math.hypot(i,n);return!(s<=c||i*r+n*o<=0)&&Math.abs(i*o-n*r)/s<=c},k=[];for(const e of y){const t=k[k.length-1];t&&m(t[1],e[0])&&w(t,e)?t[1]=e[1]:k.push([[...e[0]],[...e[1]]])}if("fixed-topology"===o&&1===k.length){const[i,n]=k[0];if(m(i,e[0])&&m(n,e[1])||m(i,e[1])&&m(n,e[0])){v.push({...t});continue}}for(const[e,i]of k)b(e,i,t.cm);continue}if("fixed-topology"===o){const e=u.get(t.key);if(1===e?.size){const i=[...e][0];v.push(i===t.key?{...t}:{...t,key:i});continue}const i=[jo([t],a)[0]];1!==a&&i.push(jo([t],1)[0]);const n=i.filter(Boolean).some(e=>h.some(t=>{if(!Uo(e.ang,Wo(t.oa,t.ob)))return!1;const i=((e.x-t.oa[0])*t.dx+(e.y-t.oa[1])*t.dy)/t.len2;return i>=-1e-6&&i<=1.000001&&Os(e.x,e.y,t.oa[0],t.oa[1],t.ob[0],t.ob[1])<=l}));((e?.size||0)>1||n)&&s?.(),v.push({...t});continue}let i="";const r=d.get(t.key);if(1===r?.size&&(i=[...r][0]),!i){const e=jo([t],a)[0];if(e){const t=new Set;for(const i of h){if(!Uo(e.ang,Wo(i.oa,i.ob)))continue;const r=((e.x-i.oa[0])*i.dx+(e.y-i.oa[1])*i.dy)/i.len2;if(r<-1e-6||r>1.000001)continue;if(Os(e.x,e.y,i.oa[0],i.oa[1],i.ob[0],i.ob[1])>l)continue;const o=g([e.x,e.y],i),[s,c]=No(i.na,i.nb),h=Math.max(n*a,1e-6);t.add(Lo([o[0]-s*h,o[1]-c*h],[o[0]+s*h,o[1]+c*h],n,a))}1===t.size&&(i=[...t][0])}}v.push({...t,key:i||t.key,cm:Po(t.cm)})}return v}function Zo(e,t,i,n,r=1,o="affine"){return Xo(e,t,i,n,r,o)}function Jo(e,t,i,n,r=1,o="fixed-topology"){let s=!1;const a=Xo(e,t,i,n,r,o,()=>{s=!0});return{walls:s?(e||[]).map(e=>({...e})):a,rejected:s}}function Qo(e,t,i,n=1,r=[]){const o=n>0?n:1,s=Math.abs(i),a=Math.max(s*o*oo,1e-9),l=(r||[]).flatMap(e=>{const t=Bo(e,o);return t?t.map(e=>[...e]):[]}),c=e=>e.every((e,t)=>(e=>{if(!(s>0))return!0;const t=e/o/s;return Math.abs(t-Math.round(t))Math.abs(e-i[t])<=a)),h=[],d=e=>JSON.stringify([e.key,e.cm,e.a,e.b]);for(const i of e||[]){const e=Bo(i,o);if(!e)continue;const[n,r]=e;if(![n[0],n[1],r[0],r[1]].every(Number.isFinite)||!c(n)||!c(r)){h.push(d(i));continue}const s=r[0]-n[0],l=r[1]-n[1],u=Math.hypot(s,l);if(u<=a){h.push(d(i));continue}const p=s/u,_=l/u,m=[];for(const e of t){const[t,i]=e;if(![t?.[0],t?.[1],i?.[0],i?.[1]].every(Number.isFinite))continue;const r=e=>Math.abs((e[0]-n[0])*_-(e[1]-n[1])*p);if(r(t)>a||r(i)>a)continue;const o=(t[0]-n[0])*p+(t[1]-n[1])*_,s=(i[0]-n[0])*p+(i[1]-n[1])*_,l=Math.max(0,Math.min(o,s)),c=Math.min(u,Math.max(o,s));c-l>a&&m.push([l,c])}m.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);let g=0;for(const[e,t]of m){if(e>g+a)break;if(g=Math.max(g,t),g>=u-a)break}ge.key!==s);return null==n||n<1?a:[...a,qo(t,i,n,r,o)]}function ts(e,t,i,n,r,o=[],s=1){let a=e?e.slice():[];for(const e of function(e,t,i,n,r=1,o=[]){const s=ks(e,t,i,n,r,o);if(!s)return[];const a=[];for(let e=0;e0||(c=es(c,t,i,n,r,s)))}return c}function ns(e){const{a:t,b:i,halfDepth:n}=e;if(!Array.isArray(t)||!Array.isArray(i)||t.length<2||i.length<2||![t[0],t[1],i[0],i[1]].every(Number.isFinite))return null;const r=i[0]-t[0],o=i[1]-t[1],s=Math.hypot(r,o);if(!(s>1e-9&&n>0&&Number.isFinite(n)))return null;const a=-o/s*n,l=r/s*n;return[[t[0]+a,t[1]+l],[i[0]+a,i[1]+l],[i[0]-a,i[1]-l],[t[0]-a,t[1]-l]]}function rs(e,t,i){return Math.hypot(e[0]-t[0],e[1]-t[1])<=i}function os(e,t,i){const n=t.b[0]-t.a[0],r=t.b[1]-t.a[1],o=n*n+r*r;if(!(o>i*i))return!1;const s=((e[0]-t.a[0])*n+(e[1]-t.a[1])*r)/o;if(!(s>0&&s<1))return!1;const a=[t.a[0]+n*s,t.a[1]+r*s];return Math.hypot(e[0]-a[0],e[1]-a[1])<=i}function ss(e,t,i,n){const r=Math.hypot(t,i);if(!(r>1e-9&&n>0))return;const o=[t/r,i/r],s=e.find(e=>Math.abs(e.u[0]*o[1]-e.u[1]*o[0])<1e-9&&e.u[0]*o[0]+e.u[1]*o[1]>1-1e-9);s?s.halfDepth=Math.max(s.halfDepth,n):e.push({u:o,halfDepth:n})}function as(e,t){try{const i=Gt(Hs(e),Hs(t));let n=null,r=0;for(const e of i||[]){const t=e?.[0]||[],i=Math.abs(ps(t));t.length>=4&&i>r&&(r=i,n=t.slice(0,-1).map(e=>[e[0],e[1]]))}return n}catch{return null}}function ls(e,t=1e-6){const i=(e||[]).map((e,t)=>({segment:e,index:t})).filter(({segment:e})=>e&&Array.isArray(e.a)&&Array.isArray(e.b)&&e.a.length>=2&&e.b.length>=2&&e.a.every(Number.isFinite)&&e.b.every(Number.isFinite)&&Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])>1e-9);if(i.length<2)return[];const n=Math.max(Number.isFinite(t)?t:0,1e-9),r=i.flatMap(({segment:e})=>[e.a,e.b]).map(e=>[e[0],e[1]]).sort((e,t)=>e[0]-t[0]||e[1]-t[1]),o=[];for(const e of r)o.some(t=>rs(t,e,n))||o.push(e);const s=[];for(const e of o){const t=[];let r=!1;for(const{segment:o,index:s}of i){const i=Math.hypot(o.b[0]-o.a[0],o.b[1]-o.a[1]);rs(e,o.a,n)?t.push({u:[(o.b[0]-o.a[0])/i,(o.b[1]-o.a[1])/i],halfDepth:o.halfDepth,length:i,index:s}):rs(e,o.b,n)?t.push({u:[(o.a[0]-o.b[0])/i,(o.a[1]-o.b[1])/i],halfDepth:o.halfDepth,length:i,index:s}):os(e,o,n)&&(r=!0)}if(r||2!==t.length)continue;const[o,a]=t,l=o.u[0]*a.u[1]-o.u[1]*a.u[0];if(Math.abs(l)<1e-9)continue;const c=l<0?1:-1,h=[-o.u[1],o.u[0]],d=[-a.u[1],a.u[0]],u=[e[0]+h[0]*o.halfDepth*c,e[1]+h[1]*o.halfDepth*c],p=[e[0]-d[0]*a.halfDepth*c,e[1]-d[1]*a.halfDepth*c];if(!gs(u,o.u,p,a.u))continue;const _=[[o,a,p,[d[0]*-c,d[1]*-c]],[a,o,u,[h[0]*c,h[1]*c]]];for(const[t,,i,r]of _){const o=Math.min(2*t.halfDepth,t.length),a=[-t.u[1]*t.halfDepth,t.u[0]*t.halfDepth],l=[[e[0]+a[0],e[1]+a[1]],[e[0]+t.u[0]*o+a[0],e[1]+t.u[1]*o+a[1]],[e[0]+t.u[0]*o-a[0],e[1]+t.u[1]*o-a[1]],[e[0]-a[0],e[1]-a[1]]],c=e=>(e[0]-i[0])*r[0]+(e[1]-i[1])*r[1],h=[];for(let e=0;e=-1e-12&&h.push(t),n>1e-12&&r<-1e-12||n<-1e-12&&r>1e-12){const e=n/(n-r);h.push([t[0]+(i[0]-t[0])*e,t[1]+(i[1]-t[1])*e])}}h.length>=3&&Math.abs(ps(h))>n*n&&s.push({segmentIndex:t.index,wedge:h})}}return s}function cs(e,t=1e-6){const i=(e||[]).filter(e=>e&&Array.isArray(e.a)&&Array.isArray(e.b)&&e.a.length>=2&&e.b.length>=2&&e.a.every(Number.isFinite)&&e.b.every(Number.isFinite)&&Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])>1e-9);if(i.length<2)return[];const n=Math.max(Number.isFinite(t)?t:0,1e-9),r=i.flatMap(e=>[e.a,e.b]).map(e=>[e[0],e[1]]).sort((e,t)=>e[0]-t[0]||e[1]-t[1]),o=[];for(const e of r)o.some(t=>rs(t,e,n))||o.push(e);const s=[],a=i.map((e,t)=>({roomId:"",a:[e.a[0],e.a[1]],b:[e.b[0],e.b[1]],key:`join-${t}`,kind:"outer",cm:0,open:!1,half:e.halfDepth})),l=Rs(a,n);for(const e of Cs(l).fans)s.push(e);const c=e=>!!Ts(l,e);for(const e of o){if(c(e))continue;const t=[];for(const r of i)rs(e,r.a,n)?ss(t,r.b[0]-r.a[0],r.b[1]-r.a[1],r.halfDepth):rs(e,r.b,n)?ss(t,r.a[0]-r.b[0],r.a[1]-r.b[1],r.halfDepth):os(e,r,n)&&(ss(t,r.a[0]-e[0],r.a[1]-e[1],r.halfDepth),ss(t,r.b[0]-e[0],r.b[1]-e[1],r.halfDepth));if(!(t.length<2)){t.sort((e,t)=>Math.atan2(e.u[1],e.u[0])-Math.atan2(t.u[1],t.u[0])||e.halfDepth-t.halfDepth);for(let i=0;in*n&&s.push(m)}}}return s}function hs(e,t,i,n){if(!(t>0)||!e||e.length<2)return"";if(i&&e.length>=3){let i=e;const r=e[e.length-1];if(e.length>=4&&Math.hypot(e[0][0]-r[0],e[0][1]-r[1])<1e-9&&(i=e.slice(0,-1)),i.length>=3){const e=i.map((e,i)=>n?.[i]||t),r=oa(i,e),o=ys(i,e);if(r&&o)return`${bs(r)} ${bs(ws(o))}`}}const r=[];for(let i=0;i=1e-9&&a>0&&r.push({a:o,b:s,halfDepth:a})}const o=r.map(ns);for(const{segmentIndex:e,wedge:t}of ls(r)){const i=o[e];if(!i)continue;const n=as(i,t);n&&(o[e]=n)}const s=[...o.filter(e=>!!e),...cs(r)],a=function(e){let t=null;try{for(const i of e){if(i.length<3)continue;const e=Hs(i);t=t?Wt(t,e):[e]}return t}catch{return null}}(s);return a?Zs(a):s.map(e=>bs(e)).join(" ")}function ds(e,t,i,n,r=1){if(!i.length)return!1;const o=us(n,r),s=(e[0]+t[0])/2,a=(e[1]+t[1])/2,[l,c]=No(e,t);for(const e of i){const[t,i]=No([e[0],e[1]],[e[2],e[3]]);if(!(Math.abs(l*i-c*t)>.05)&&Os(s,a,e[0],e[1],e[2],e[3])<=o)return!0}return!1}function us(e,t){return Math.max(e*(t>0?t:1)*.04,1e-9)}function ps(e){let t=0;for(let i=0;ie[1]!=l>e[1]&&e[0]<(a-o)*(e[1]-s)/(l-s+0)+o&&(i=!i)}return i}([c[0]+.001*a,c[1]+.001*l],e)||(a=-a,l=-l),[a,l]}function ms(e,t){const i=e[0]*t[1]-e[1]*t[0],n=e[0]*t[0]+e[1]*t[1];return Math.abs(i)<1e-9&&n>0}function gs(e,t,i,n){const r=t[0]*n[1]-t[1]*n[0];if(Math.abs(r)<1e-12)return null;const o=[i[0]-e[0],i[1]-e[1]],s=(o[0]*n[1]-o[1]*n[0])/r;return[e[0]+s*t[0],e[1]+s*t[1]]}function fs(e,t,i){const n=e?.length||0;if(n<3||!Array.isArray(i)||i.length!==n)return 0;const r=(Math.trunc(t)%n+n)%n,o=e[r],s=e[(r+1)%n],a=s[0]-o[0],l=s[1]-o[1],c=Math.hypot(a,l);if(!(c>0))return 0;const h=Math.max(0,Number(i[r])||0);if(!(h>0))return c;const d=[a/c,l/c],u=_s(e,r),p=[o[0]+u[0]*h,o[1]+u[1]*h],_=t=>{const r=Math.max(0,Number(i[t])||0);if(!(r>0))return null;const s=e[t],a=e[(t+1)%n],l=a[0]-s[0],c=a[1]-s[1],h=Math.hypot(l,c);if(!(h>0))return null;const u=_s(e,t),_=gs(p,d,[s[0]+u[0]*r,s[1]+u[1]*r],[l/h,c/h]);return _?(_[0]-o[0])*d[0]+(_[1]-o[1])*d[1]:null},m=_((r-1+n)%n)??0,g=(_((r+1)%n)??c)-m;return g>0?g:0}function vs(e,t,i,n,r,o,s,a=1){const l=(e||[]).find(e=>e?.id===t),c=ni(l);if(!c||c.length<3)return null;const h=As(e,t,i,n,r,o,s,a);if(!h)return c.map(()=>0);const d=4*us(r,a);return c.map((e,t)=>{const i=c[(t+1)%c.length],n=[(e[0]+i[0])/2,(e[1]+i[1])/2];for(let e=0;e!(e>0)))return e.map(e=>[e[0],e[1]]);const r=[];for(let o=0;o0||u>0)){r.push([e[o][0],e[o][1]]);continue}if(d>0!=u>0){const t=e[o],i=d>0?[t[0]+p*d,t[1]+_*d]:[t[0],t[1]],n=u>0?[t[0]+m*u,t[1]+g*u]:[t[0],t[1]];r.push(i),Math.hypot(n[0]-i[0],n[1]-i[1])>1e-9&&r.push(n);continue}if(ms(w,k)){const t=e[o],i=[t[0]+p*d,t[1]+_*d],n=[t[0]+m*u,t[1]+g*u];r.push(i),Math.hypot(n[0]-i[0],n[1]-i[1])>1e-9&&r.push(n);continue}const $=gs(x,w,S,k),M=Math.max(d,u,1e-9),R=Ts(i,e[o])?.limit??4*M;if($){const i=Math.hypot($[0]-e[o][0],$[1]-e[o][1]);if(Number.isFinite(i)&&i<=R){r.push($);continue}if(Qs(e,t,o)){r.push($);continue}}d>0&&r.push([e[o][0]+p*d,e[o][1]+_*d]),u>0&&r.push([e[o][0]+m*u,e[o][1]+g*u]),d>0||u>0||r.push([e[o][0],e[o][1]])}return r.length>=3?r:null}function bs(e,t=!0){if(!e.length)return"";let i=`M ${e[0][0]} ${e[0][1]}`;for(let t=1;te?.id===t),a=ni(s);if(!a||a.length<3)return null;const l=us(n,r),c=[];for(const i of e||[]){if(!i||i.id===t)continue;const e=ni(i);if(e)for(const t of An(a,e,l))c.push([t[0],t[1]],[t[2],t[3]])}for(const e of i||[])c.push([e[0],e[1]],[e[2],e[3]]);for(const e of o||[]){const t=Bo(e,r);t&&c.push(t[0],t[1])}const h=[],d=[];for(let e=0;el)continue;const s=((e[0]-t[0])*(i[0]-t[0])+(e[1]-t[1])*(i[1]-t[1]))/(n*n);s<=r||s>=1-r||(o.some(e=>Math.abs(e-s)*n<=2*l)||o.push(s))}o.sort((e,t)=>e-t);for(const n of o)h.push([t[0]+(i[0]-t[0])*n,t[1]+(i[1]-t[1])*n]),d.push(e)}return{poly:h,parent:d,orig:a}}function xs(e,t,i,n){const r=t.poly.length,o=new Array(r).fill(0);if(!e?.length)return o;const s=new Set,a=[];for(let l=0;l0?(o[l]=Po(c.cm),s.add(c.key)):a.push(l)}if(!a.length)return o;const l=n>0?n:1,c=Math.max(.5*i,1e-9)*l,h=jo(e,l).filter(e=>e.w.cm>0);for(let e=a.length-1;e>=0;e--){const i=a[e],n=t.poly[i],s=t.poly[(i+1)%r],d=Wo(n,s);let u=null;for(const e of h){const t=Bo(e.w,l);if(!t||!Uo(Wo(t[0],t[1]),d))continue;if(Os(n[0],n[1],t[0][0],t[0][1],t[1][0],t[1][1])>c||Os(s[0],s[1],t[0][0],t[0][1],t[1][0],t[1][1])>c)continue;const i=Math.hypot(s[0]-n[0],s[1]-n[1]),r=Math.hypot(t[1][0]-t[0][0],t[1][1]-t[0][1]),o=Math.max(0,r-i);(!u||oc||Os(r[0],r[1],t[0][0],t[0][1],t[1][0],t[1][1])>c)continue;i=!0,o=Math.max(0,Math.hypot(t[1][0]-t[0][0],t[1][1]-t[0][1])-_)}else{if(Os(e.x,e.y,n[0],n[1],r[0],r[1])>c)continue;o=Math.hypot(e.x-d,e.y-u)}(!p||i&&!p.exact||i===p.exact&&o0?i:1,o=(e||[]).filter(e=>e&&!e.open&&null!==e.kind&&Number.isFinite(e.half)&&e.half>0&&Array.isArray(e.a)&&Array.isArray(e.b)&&e.a.length>=2&&e.b.length>=2&&[e.a[0],e.a[1],e.b[0],e.b[1]].every(Number.isFinite)&&Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])>n).sort((e,t)=>e.key.localeCompare(t.key)||e.a[0]-t.a[0]||e.a[1]-t.a[1]||e.b[0]-t.b[0]||e.b[1]-t.b[1]||e.half-t.half),s=new Map;for(const e of o){const t=s.get(e.key);t?e.half>t.half&&s.set(e.key,{...t,half:e.half}):s.set(e.key,e)}const a=[...s.values()].flatMap(e=>[{point:[e.a[0],e.a[1]],other:e.b,halfDepth:e.half,kind:e.kind,key:e.key},{point:[e.b[0],e.b[1]],other:e.a,halfDepth:e.half,kind:e.kind,key:e.key}]).sort((e,t)=>e.point[0]-t.point[0]||e.point[1]-t.point[1]||e.other[0]-t.other[0]||e.other[1]-t.other[1]||e.halfDepth-t.halfDepth),l=new Map;for(const e of a){const[t,i]=Ss(e.point,n),r=$s(t,i),o=l.get(r)||[];o.push(e),l.set(r,o)}const c=[],h=new Map;for(const e of a){const t=Ms(h,e.point,n).filter(t=>Math.hypot(t.point[0]-e.point[0],t.point[1]-e.point[1])<=n).sort((t,i)=>Math.hypot(t.point[0]-e.point[0],t.point[1]-e.point[1])-Math.hypot(i.point[0]-e.point[0],i.point[1]-e.point[1])||t.point[0]-i.point[0]||t.point[1]-i.point[1]);let i=t[0];if(!i){i={point:[...e.point],rays:[]},c.push(i);const[t,r]=Ss(i.point,n),o=$s(t,r),s=h.get(o)||[];s.push(i),h.set(o,s)}const r=e.other[0]-e.point[0],o=e.other[1]-e.point[1],s=Math.hypot(r,o);if(!(s>n))continue;const a=[r/s,o/s];let l=Math.atan2(a[1],a[0]);l<0&&(l+=2*Math.PI),i.rays.push({u:a,halfDepth:e.halfDepth,length:s,angle:l})}const d=[],u=e=>{const t=1e-9*Math.max(1,r),i=e.filter(e=>Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Number.isFinite(e.length)&&e.length>n);return i.filter((e,n)=>!i.some((i,r)=>r!==n&&i.halfDepth>=e.halfDepth-t&&i.length>=e.length-t&&(i.halfDepth>e.halfDepth+t||i.length>e.length+t||re.length-t.length||e.halfDepth-t.halfDepth).map(e=>({...e}))};for(const e of c){const t=e.rays.sort((e,t)=>e.angle-t.angle||e.length-t.length||e.halfDepth-t.halfDepth),i=[];for(const e of t){const t=i[i.length-1];t&&Math.abs(e.angle-t.angle)<=1e-9?t.supports.push({halfDepth:e.halfDepth,length:e.length}):i.push({u:[...e.u],angle:e.angle,supports:[{halfDepth:e.halfDepth,length:e.length}]})}if(i.length>1&&2*Math.PI-i[i.length-1].angle+i[0].angle<=1e-9){const e=i.pop();i[0].supports.push(...e.supports)}if(i.length<3)continue;const r=i.map(t=>{const i=u(t.supports),r=new Set,o=[];for(const s of i){const i=[e.point[0]+t.u[0]*s.length,e.point[1]+t.u[1]*s.length];for(const t of Ms(l,i,n)){if("shared"!==t.kind||Math.hypot(t.point[0]-i[0],t.point[1]-i[1])>n)continue;const s=t.other[0]-t.point[0],a=t.other[1]-t.point[1],l=Math.hypot(s,a);if(!(l>n))continue;const c=s/l,h=a/l;if(Math.hypot(t.other[0]-e.point[0],t.other[1]-e.point[1])<=n)continue;const d=`${t.key}|${t.point[0]}|${t.point[1]}|${t.other[0]}|${t.other[1]}|${t.halfDepth}`;r.has(d)||(r.add(d),o.push({start:[t.point[0],t.point[1]],u:[c,h],length:l,halfDepth:t.halfDepth}))}}return o.sort((e,t)=>e.start[0]-t.start[0]||e.start[1]-t.start[1]||e.u[0]-t.u[0]||e.u[1]-t.u[1]||e.length-t.length||e.halfDepth-t.halfDepth),{u:[...t.u],halfDepth:Math.max(...i.map(e=>e.halfDepth)),length:Math.max(...i.map(e=>e.length)),supports:i,continuations:o}}).filter(e=>Number.isFinite(e.halfDepth)&&e.halfDepth>0&&Number.isFinite(e.length)&&e.length>n);if(r.length<3)continue;const o=Math.max(...r.map(e=>e.halfDepth));o>0&&Number.isFinite(o)&&d.push({point:[...e.point],rays:r,halfDepth:o,limit:1.25*o})}d.sort((e,t)=>e.point[0]-t.point[0]||e.point[1]-t.point[1]);const p=new Map;for(const e of d){const[t,i]=Ss(e.point,n),r=$s(t,i),o=p.get(r)||[];o.push(e),p.set(r,o)}return{epsilon:n,coordinateScale:r,nodes:d,index:p}}function Cs(e){const t={fans:[],supports:[]};if(!e?.nodes?.length)return t;const i=Math.max(e.epsilon,1e-9)**2;for(const n of e.nodes){const e=n.rays.filter(e=>Number.isFinite(e.halfDepth)&&e.halfDepth>0).map(e=>({...e,thickLength:Math.max(...e.supports.filter(t=>t.halfDepth>=e.halfDepth-1e-12).map(e=>e.length),0),angle:(()=>{const t=Math.atan2(e.u[1],e.u[0]);return t<0?t+2*Math.PI:t})()})).sort((e,t)=>e.angle-t.angle);if(e.length<2)continue;const r=n.point;for(const i of e)for(const e of i.supports){if(!(e.halfDepth>0&&e.length>0))continue;const n=-i.u[1]*e.halfDepth,o=i.u[0]*e.halfDepth,s=[r[0]+i.u[0]*e.length,r[1]+i.u[1]*e.length];t.supports.push([[r[0]+n,r[1]+o],[s[0]+n,s[1]+o],[s[0]-n,s[1]-o],[r[0]-n,r[1]-o]])}for(let n=0;n{const e=s.angle-o.angle;return e>0?e:e+2*Math.PI})();if(a<1e-9)continue;const l=a>Math.PI+1e-9,c=4*Math.max(o.halfDepth,s.halfDepth),h=[r[0]-o.u[1]*o.halfDepth,r[1]+o.u[0]*o.halfDepth],d=[r[0]+s.u[1]*s.halfDepth,r[1]-s.u[0]*s.halfDepth],u=o.u[0]*s.u[1]-o.u[1]*s.u[0],p=e=>{let t=Math.atan2(e[1]-r[1],e[0]-r[0])-o.angle;for(;t<0;)t+=2*Math.PI;return t<=a+1e-9};let _=null;if(Math.abs(u)>1e-9){const e=((d[0]-h[0])*s.u[1]-(d[1]-h[1])*s.u[0])/u,t=((d[0]-h[0])*o.u[1]-(d[1]-h[1])*o.u[0])/u,i=[h[0]+o.u[0]*e,h[1]+o.u[1]*e];(l?e<=1e-9&&t<=1e-9:e>1e-9&&e<=o.thickLength&&t<=s.thickLength)&&Math.hypot(i[0]-r[0],i[1]-r[1])<=c&&p(i)&&(_=i)}const m=e=>{Math.abs(ps(e))>i&&t.fans.push(e)};if(_){const e=1.5*Math.max(o.halfDepth,s.halfDepth);m(Ro([r[0],r[1]],h,_,d,e)??[[r[0],r[1]],h,_,d]);continue}if(l){m([[r[0],r[1]],h,d]);continue}const g=(e,t)=>Math.min(t,Math.sqrt(Math.max(c**2-e**2,0)),2*Math.max(o.halfDepth,s.halfDepth)),f=[h[0]+o.u[0]*g(o.halfDepth,o.thickLength),h[1]+o.u[1]*g(o.halfDepth,o.thickLength)],v=[d[0]+s.u[0]*g(s.halfDepth,s.thickLength),d[1]+s.u[1]*g(s.halfDepth,s.thickLength)];m([[r[0],r[1]],h,f,v,d])}}return t}function Ts(e,t){return!e||!Array.isArray(t)||t.length<2||!t.slice(0,2).every(Number.isFinite)?null:Ms(e.index,t,e.epsilon).filter(i=>Math.hypot(i.point[0]-t[0],i.point[1]-t[1])<=e.epsilon).sort((e,i)=>Math.hypot(e.point[0]-t[0],e.point[1]-t[1])-Math.hypot(i.point[0]-t[0],i.point[1]-t[1])||e.point[0]-i.point[0]||e.point[1]-i.point[1])[0]||null}function Ds(e,t,i,n,r,o,s){return Rs(Ps(e,t,i,n,r,o,s),4*us(n,s),s)}function As(e,t,i,n,r,o,s,a=1){const l=ks(e,t,n,r,a,i);if(!l)return null;const c=function(e,t,i){const n=(e||[]).find(e=>e?.id===t),r=ni(n);if(!r)return[];const o=[];for(const n of e||[]){if(!n||n.id===t)continue;const e=ni(n);if(e)for(const t of An(r,e,i))o.push(t)}return o}(e,t,us(r,a)),h=function(e,t,i,n,r){const o=us(n,r),s=[];for(let a=0;aOs(h,d,e[0],e[1],e[2],e[3])<=o);s.push(u?"shared":"outer")}return s}(l.poly,c,n,r,a),d=xs(i,l,r,a),u=d.map((e,t)=>h[t]&&e>0?zo(e,o,s)/2:0);return{...l,kinds:h,cms:d,offsets:u}}function Ps(e,t,i,n,r,o,s=1){const a=[];for(const l of e||[]){if(!l?.id)continue;const c=As(e,l.id,t,i,n,r,o,s);if(c)for(let e=0;e0&&(a=es(a,e.a,e.b,e.cm,n,s));return a}function zs(e,t,i,n,r,o,s=1){if(!t?.length)return[];const a=Ps(e,t,i,n,r,o,s),l=new Map;for(const e of a){if(e.open||!e.kind||!e.roomId)continue;const t=l.get(e.key)||new Set;t.add(e.roomId),l.set(e.key,t)}const c=e=>{const t=[...l.get(e)||[]].sort();return 1!==t.length&&2!==t.length?`ambiguous:${e}`:`${1===t.length?"outer":"shared"}:${t.join("|")}`},h=[],d=new Set;for(const e of a)!e.open&&e.cm>0&&!d.has(e.key)&&(d.add(e.key),h.push({...e,ownerSignature:c(e.key)}));const u=[];for(const a of e||[]){if(!a?.id)continue;const l=As(e,a.id,t,i,n,r,o,s);if(l)for(let e=0;e0)||null===l.kinds[i]){e++;continue}const o=c(Lo(l.poly[i],l.poly[(i+1)%l.poly.length],n,s));let a=e;for(;a+10&&u.push({a:[d[0],d[1]],b:[p[0],p[1]],key:Lo(d,p,n,s),cm:r,len:_,ownerSignature:o}),e=a+1}}}u.sort((e,t)=>t.len-e.len||e.key.localeCompare(t.key));const p=[],_=new Set,m=new Set,g=4*us(n,s);for(const e of u){const t=h.filter(t=>!m.has(t.key)&&t.cm===e.cm&&t.ownerSignature===e.ownerSignature&&Uo(Wo(t.a,t.b),Wo(e.a,e.b))&&Os(t.a[0],t.a[1],e.a[0],e.a[1],e.b[0],e.b[1])<=g&&Os(t.b[0],t.b[1],e.a[0],e.a[1],e.b[0],e.b[1])<=g);if(t.length){for(const e of t)m.add(e.key);_.has(e.key)||(_.add(e.key),p.push(qo(e.a,e.b,e.cm,n,s)))}}for(const e of h)m.has(e.key)||_.has(e.key)||(_.add(e.key),p.push(qo(e.a,e.b,e.cm,n,s)));return p}function Is(e,t,i,n,r,o,s,a=1){const l=us(r,a),c=(n[0]+n[2])/2,h=(n[1]+n[3])/2,d=Wo([n[0],n[1]],[n[2],n[3]]);let u=null;for(const n of Ps(e,t,i,r,o,s,a)){if(!Uo(Wo(n.a,n.b),d))continue;const e=Os(c,h,n.a[0],n.a[1],n.b[0],n.b[1]);e>4*l||(!u||e[e[0],e[1]]),o=Math.abs(ps(r));r.length>=3&&o>i&&(t=r,i=o)}return t}function Ns(e,t,i,n,r,o,s,a=1,l,c){const h=(e||[]).find(e=>e?.id===t),d=ni(h);if(!d||d.length<3)return null;if(!i?.length)return d.map(e=>[e[0],e[1]]);const u=As(e,t,i,n,r,o,s,a);if(!u||!u.offsets.some(e=>e>0))return d.map(e=>[e[0],e[1]]);const p=c||Ds(e,i,n,r,o,s,a),_=ys(u.poly,u.offsets,p);if(!_)return d.map(e=>[e[0],e[1]]);if(!p.nodes.length)return _;const m=void 0===l?ea(e,i,n,[],r,o,s,a):null,g=l??("ok"===m?.status||"degraded-extra"===m?.status?m.roomGeom:void 0);if(g)try{const e=Es(Gt(Hs(u.poly),g));if(e)return e}catch{}return function(e,t){try{return Es(Ut(Hs(e),Hs(t)))}catch{return null}}(_,u.poly)||d.map(e=>[e[0],e[1]])}function Hs(e){const t=e.map(e=>[e[0],e[1]]);return t.push([e[0][0],e[0][1]]),[t]}function Ls(e){return!(!Array.isArray(e)||!e.length)&&e.every(e=>Array.isArray(e)&&e.length&&e.every(e=>Array.isArray(e)&&e.length>=4&&e.every(e=>Array.isArray(e)&&e.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1])))&&Math.abs(Ci(e[0]))>1e-9)}function Bs(e,t,i,n){const r=n?new Set(n):null;let o=null;for(let n=0;nt.epsilon))continue;const l=Gs([[e.point[0]+a[0]*n.halfDepth,e.point[1]+a[1]*n.halfDepth],[e.point[0]+s.u[0]*r+a[0]*n.halfDepth,e.point[1]+s.u[1]*r+a[1]*n.halfDepth],[e.point[0]+s.u[0]*r-a[0]*n.halfDepth,e.point[1]+s.u[1]*r-a[1]*n.halfDepth],[e.point[0]-a[0]*n.halfDepth,e.point[1]-a[1]*n.halfDepth]],t.coordinateScale);if(!l)continue;const c=Hs(l);o=o?Wt(o,c):c}}return o}function qs(e,t,i){let n=null;for(const r of e.rays)for(const e of r.continuations){const r=[-e.u[1],e.u[0]],o=[e.start[0]+e.u[0]*e.length,e.start[1]+e.u[1]*e.length],s=Gs([[e.start[0]+r[0]*e.halfDepth,e.start[1]+r[1]*e.halfDepth],[o[0]+r[0]*e.halfDepth,o[1]+r[1]*e.halfDepth],[o[0]-r[0]*e.halfDepth,o[1]-r[1]*e.halfDepth],[e.start[0]-r[0]*e.halfDepth,e.start[1]-r[1]*e.halfDepth]],t.coordinateScale);if(!s)continue;const a=Ut(Hs(s),i);Array.isArray(a)&&0!==a.length&&(n=n?Wt(n,a):a)}return n}function js(e,t,i=2*(4*e.halfDepth+2*t.epsilon)){const n=function(e,t=Co){const i=new Set,n=Number.isFinite(t)&&t>=0?t:Co;for(let t=0;te-t)}(e);return n.length?Bs(e,t,i,n):null}function Ws(e,t,i,n,r){const o=function(e){let t=null;for(const i of e){const e=Hs(i);try{t=t?Wt(t,e):e}catch{}}return t}(function(e,t,i=!1){if(!e)return[];const n=[];for(const r of e.nodes)for(let o=0;o1e-9)||h>=Math.PI-1e-9)continue;const d=[-s.u[1],s.u[0]],u=[-a.u[1],a.u[0]],p=[r.point[0]+d[0]*s.halfDepth,r.point[1]+d[1]*s.halfDepth],_=[r.point[0]-u[0]*a.halfDepth,r.point[1]-u[1]*a.halfDepth],m=gs(p,s.u,_,a.u);if(!m)continue;const g=Math.hypot(m[0]-r.point[0],m[1]-r.point[1]);if(!Number.isFinite(g)||g<=r.limit)continue;const f=t?Math.sqrt(Math.max(0,r.limit*r.limit-s.halfDepth*s.halfDepth)):0,v=t?Math.sqrt(Math.max(0,r.limit*r.limit-a.halfDepth*a.halfDepth)):0,y=Gs([[p[0]+s.u[0]*f,p[1]+s.u[1]*f],[_[0]+a.u[0]*v,_[1]+a.u[1]*v],m],e.coordinateScale);if(y&&n.push(y),i){const t=m[0]-r.point[0],i=m[1]-r.point[1],o=Math.hypot(t,i),s=g-r.limit;if(o>e.epsilon&&s>e.epsilon){const a=Math.min(Math.max(8*e.epsilon,.05*r.halfDepth),.25*s),l=t/o,c=i/o,h=-c,d=l,u=Gs([[m[0]-l*a+h*a,m[1]-c*a+d*a],[m[0]-l*a-h*a,m[1]-c*a-d*a],[m[0]+l*a,m[1]+c*a]],e.coordinateScale);u&&n.push(u)}}}return n}({...t,nodes:[e]},i,n));return o&&r?Gt(o,r):o}function Us(e,t,i,n){if(!e||!t.nodes.length)return e;let r=null;try{r=function(e){let t=null;for(const i of e.nodes){const n=js(i,e);n&&(t=t?Wt(t,n):n)}return t}(t)}catch{return e}let o=e;for(const e of t.nodes){const s=4*e.halfDepth+2*t.epsilon,a=2*s,l=[[e.point[0]-s,e.point[1]-s],[e.point[0]+s,e.point[1]-s],[e.point[0]+s,e.point[1]+s],[e.point[0]-s,e.point[1]+s]];try{let s=o;const c=Ws(e,t,!1,!0,r);c&&(s=Gt(s,c));let h=Bs(e,t,a);const d=Ws(e,t,!0,!0,r);d&&(h=Gt(h,d)),r&&(h=Wt(h,r));const u=.02*Math.min(...e.rays.map(e=>e.halfDepth));if(h=Wt(h,Hs([[e.point[0]-u,e.point[1]-u],[e.point[0]+u,e.point[1]-u],[e.point[0]+u,e.point[1]+u],[e.point[0]-u,e.point[1]+u]])),!h)continue;let p=Ut(h,Hs(l));n?p=Ut(p,n):i&&(p=Ut(p,i));const _=Hs(l),m=Gt(s,_),g=i?Gt(Ut(s,_),i):null,f=qs(e,t,_);o=Wt(m,...g?[g]:[],...f?[f]:[],p)}catch{}}if(r)try{let e=r;n?e=Ut(e,n):i&&(e=Ut(e,i)),o=Wt(o,e)}catch{}return o}function Gs(e,t=1){if(!Array.isArray(e)||e.length<3)return null;const i=Number.isFinite(t)&&t>0?t:1,n=1e-12*Math.max(1,i),r=[];for(const t of e){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),i=Number(t[1]);if(!Number.isFinite(e)||!Number.isFinite(i))return null;const o=Math.round(e/n)*n,s=Math.round(i/n)*n;if(!Number.isFinite(o)||!Number.isFinite(s))return null;r.push([Object.is(o,-0)?0:o,Object.is(s,-0)?0:s])}return Math.abs(ps(r))>n*n?r:null}function Vs(e,t,i,n){if(Os(e[0],e[1],t[0],t[1],i[0],i[1])>n)return!1;const r=i[0]-t[0],o=i[1]-t[1],s=(e[0]-t[0])*r+(e[1]-t[1])*o,a=r*r+o*o,l=n*Math.sqrt(a);return s>=-l&&s<=a+l}function Ks(e,t,i){const n=[],r=[];for(let o=0;oi*i))continue;const d=i/Math.sqrt(h),u=[0,1];for(const e of t)for(const t of[e.a,e.b]){if(!Vs(t,s,a,i))continue;const e=((t[0]-s[0])*l+(t[1]-s[1])*c)/h;e>d&&e<1-d&&u.push(e)}u.sort((e,t)=>e-t);const p=u.filter((e,t)=>0===t||Math.abs(e-u[t-1])>d);for(let e=0;e=3&&r.length===n.length?{poly:n,offsets:r}:null}function Ys(e,t,i,n,r,o,s,a){const l=(e||[]).map(ni).filter(e=>!!e&&e.length>=3);if(!l.length)return null;let c=Wt(Hs(l[0]));for(let e=1;e"outer"===e.kind&&e.half>0),u=4*us(n,s),p=a||Rs(h,u,s);let _=null;for(const e of function(e){const t=[];for(const i of Array.isArray(e)?e:[])if(Array.isArray(i))for(const e of i){if(!Array.isArray(e)||e.length<4)continue;const i=e.slice(0,-1).map(e=>[e[0],e[1]]);i.length>=3&&t.push(i)}return t}(c)){const t=Ks(e,d,u);if(!t||!t.offsets.some(e=>e>0))continue;const i=oa(t.poly,t.offsets,p),n=ys(t.poly,t.offsets,p);if(!i||!n)continue;const r=Gt(Hs(i),Hs(n));_=_?Wt(_,r):r}return{centre:c,shell:_||[]}}function Xs(e,t,i,n,r,o,s=1){try{const a=Ys(e,t,i,n,r,o,s,Ds(e,t,i,n,r,o,s));if(!a)return[];return a.shell?.length?Wt(a.centre,a.shell):a.centre}catch{return null}}function Zs(e){if(!e)return"";let t="";for(const i of e)if(Array.isArray(i))for(const e of i){if(!Array.isArray(e)||e.length<4)continue;const i=e.slice(0,e.length-1);i.length<3||(t+=(t?" ":"")+bs(i.map(e=>[e[0],e[1]])))}return t}const Js=15;function Qs(e,t,i){const n=e?.length||0;if(n<3||t?.length!==n)return!1;const r=e[(i-1+n)%n],o=e[i],s=e[(i+1)%n],a=[r[0]-o[0],r[1]-o[1]],l=[s[0]-o[0],s[1]-o[1]],c=Math.hypot(a[0],a[1]),h=Math.hypot(l[0],l[1]);if(!(c>1e-9&&h>1e-9))return!1;const d=Math.max(-1,Math.min(1,(a[0]*l[0]+a[1]*l[1])/(c*h))),u=Math.acos(d);if(!(u>1e-9))return!1;if(u>=Js*Math.PI/180)return!1;const p=Math.max(0,t[(i-1+n)%n]),_=Math.max(0,t[i]);if(!(p>0||_>0))return!1;const m=Math.sin(u);if(!(m>1e-12))return!1;const g=(_+p*d)/m,f=(p+_*d)/m;return Number.isFinite(g)&&Number.isFinite(f)&&g>0&&f>0&&ge>0))continue;for(const e of l.offsets)e>0&&(u=Math.max(u,2*e));const c=oa(l.poly,l.offsets,d),p=ys(l.poly,l.offsets,d);c&&h.push({outset:c,inset:p})}for(const e of l){const t=e.map(e=>e[0]),i=e.map(e=>e[1]);if(t.length){const n=Math.min(Math.max(...t)-Math.min(...t),Math.max(...i)-Math.min(...i)),r=Math.min(...e.map((t,i)=>{const n=e[(i+1)%e.length];return Math.hypot(n[0]-t[0],n[1]-t[1])}));u=Math.max(u,e.length>16?n:r)}}const p=function(e,t,i,n,r,o,s,a){if(!t?.length||!i?.length)return[];const l=4*us(n,s),c=new Map;for(const a of Ps(e,t,i,n,r,o,s))!a.open&&a.half>0&&!c.has(a.key)&&c.set(a.key,a);const h=[...c.values()];if(h.length<2)return[];const d=a||Rs(h,l),u=[];for(const e of i)for(const t of[[e[0],e[1]],[e[2],e[3]]])u.some(e=>Math.hypot(e[0]-t[0],e[1]-t[1])<=l)||u.push(t);const p=[],_=(e,t)=>{let i=0,n=0;if(Math.hypot(e.a[0]-t[0],e.a[1]-t[1])<=l)i=e.b[0]-e.a[0],n=e.b[1]-e.a[1];else{if(!(Math.hypot(e.b[0]-t[0],e.b[1]-t[1])<=l))return null;i=e.a[0]-e.b[0],n=e.a[1]-e.b[1]}const r=Math.hypot(i,n);return r>l?[i/r,n/r]:null};for(const e of u){const t=h.map(t=>({iv:t,u:_(t,e)})).filter(e=>!!e.u);for(let i=0;i0?[e.slice(),u,m,_]:[e.slice(),_,m,u];else{if(!f)continue;{const t=[-r.u[1],r.u[0]],i=[-o.u[1],o.u[0]],n=s<0?1:-1,a=[e[0]+t[0]*r.iv.half*n,e[1]+t[1]*r.iv.half*n],l=[e[0]-i[0]*o.iv.half*n,e[1]-i[1]*o.iv.half*n];y=s>0?[e.slice(),a,l]:[e.slice(),l,a]}}Math.abs(ps(y))>l*l&&p.push(y)}}return p}(e,t,i,r,o,s,a,d),_=n.length?sa(e,t,i,r,o,s,a):null;let m="exterior";try{const v=Ys(e,t,i,r,o,s,a,d);m="paper";const y=v?v.shell?.length?Wt(v.centre,v.shell):v.centre:[],b=e=>{const t=Hs(e.outset);if(!e.inset)return t;const i=Hs(e.inset);return Gt(t,i)};m="room-rings";let w=null;for(const e of h)try{const t=b(e);w=w?Wt(w,t):t}catch{}if(m="edge-bodies",v)for(const n of na(e,t,i,r,o,s,a))try{const e=Ut(Hs(n.quad),v.centre);w=w?Wt(w,e):e}catch{}m="junctions",w=function(e,t,i=1,n=Wt){let r=e;for(const e of t||[]){const t=Gs(e,i);if(t)try{const e=Hs(t);r=r?n(r,e):e}catch{}}return r}(w,p,a),m="facade-clip",w&&v&&(w=Ut(w,v.centre)),m="exterior-shell";const k=[];let x=0;if(v?.shell?.length)if(w)try{const e=Wt(w,v.shell);if(!Ls(e))throw new Error("invalid shell union");w=e}catch{if(!Ls(w)||!Ls(v.shell))throw new Error("invalid shell");k.push({id:"exterior-shell",geom:v.shell}),x++}else w=v.shell;if(m="multi-wall-trim",w&&d.nodes.length){const e=e=>e.rays.some(e=>e.supports.some(e=>e.length<2*e.halfDepth)),t=d.nodes.filter(e);if(t.length){w=Us(w,{...d,nodes:t},v?.centre,y)}}if(m="junction-corners",d.nodes.length){const n=Cs(d),l=function(e,t,i,n,r,o,s,a){try{const l=Ys(e,t,i,n,r,o,s,{epsilon:a.epsilon,coordinateScale:a.coordinateScale,nodes:[],index:new Map});return l?l.shell?.length?Wt(l.centre,l.shell):l.centre:null}catch{return null}}(e,t,i,r,o,s,a,d);for(const e of n.fans)try{let t=[Hs(e)];if(l&&(t=Ut(t,l)),!t?.length)continue;w=w?Wt(w,t):t}catch{}g=w,f=Math.max(d.epsilon,1e-9)**2,w=Array.isArray(g)?g.map(e=>{if(!Array.isArray(e)||!e.length)return e;const[t,...i]=e;return Math.abs(ps(t||[]))<=f?null:[t,...i.filter(e=>Math.abs(ps(e||[]))>f)]}).filter(e=>!!e):g}const S=w||[],$=[...Ls(S)?[{id:"room-primary",geom:S}]:[],...k.map((e,t)=>({id:`room-isolated-${t}`,geom:e.geom}))];m="openings";for(const e of n){if(!(e.length>0))continue;const t=ca(_,e,!0);if(!t.negative&&!t.positive)continue;const i=e.angle*Math.PI/180,n=Math.cos(i),o=Math.sin(i),s=-o,l=n,c=e.length/2,h=1.25*Math.max(u,r*a),d=[[e.x-n*c-s*h,e.y-o*c-l*h],[e.x+n*c-s*h,e.y+o*c-l*h],[e.x+n*c+s*h,e.y+o*c+l*h],[e.x-n*c+s*h,e.y-o*c+l*h]];w&&(w=Gt(w,Hs(d)));for(const e of k)e.geom=Gt(e.geom,Hs(d))}m="extras";const M=[];let R=0;const C=c.mergeExtra||((e,t)=>e?Wt(e,t):t);for(let e=0;ee.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]))||Math.abs(Ci(t))<=1e-9){R++;continue}const i=[Hs(t)];try{const t=C(w,i,e);if(!Ls(t))throw new Error("invalid extra union");w=t}catch{R++,Ls(i)&&M.push({id:`extra-${e}`,geom:i})}}M.push(...k),M.sort((e,t)=>Zs(e.geom).localeCompare(Zs(t.geom)));const T=w||[];return{status:R||x?"degraded-extra":"ok",geom:T,components:[...Ls(T)?[{id:"primary",geom:T}]:[],...M.map((e,t)=>({...e,id:`isolated-${t}`}))],roomGeom:S,roomComponents:$,paperGeom:y,depthUnits:u,openingPadUnits:1.25*Math.max(u,r*a),openingIndex:_,multiWallNodes:d,degradedExtraCount:R+x}}catch{return c.onCoreFailure?.(m),{status:"failed-core",geom:[],components:[],roomGeom:[],paperGeom:[],roomComponents:[],depthUnits:u,openingIndex:null,multiWallNodes:d,degradedExtraCount:0}}var g,f}function ta(e,t,i,n=[],r,o,s,a=1,l=[],c={}){if(!t?.length&&!l.length)return null;return ia(ea(e,t,i,n,r,o,s,a,l,c))}function ia(e){if("failed-core"===e.status||"not-applicable"===e.status)return null;const t=e.components.map(e=>({id:e.id,d:Zs(e.geom),fillRule:"evenodd"})).filter(e=>!!e.d),i=t[0]?.d||"",n=Zs(e.paperGeom);if(t.length){const r={status:e.status,d:i,paths:t,components:e.components,roomGeom:e.roomGeom,multiWallNodes:e.multiWallNodes,paperD:n,depthUnits:e.depthUnits,fillRule:"evenodd"};return Object.defineProperties(r,{roomComponents:{value:e.roomComponents||[],enumerable:!1},openingIndex:{value:e.openingIndex,enumerable:!1},openingPadUnits:{value:e.openingPadUnits,enumerable:!1}}),r}return null}function na(e,t,i,n,r,o,s=1){if(!t?.length)return[];const a=new Set,l=[];for(const c of e||[]){if(!c?.id)continue;const h=As(e,c.id,t,i,n,r,o,s);if(!h)continue;const d=h.poly;for(let e=0;e0))continue;const p=Lo(t,i,n,s);if(a.has(p))continue;a.add(p);const _=zo(u,r,o),[m,g]=_s(d,e),f=-m,v=-g,y=_/2,b=[[t[0]+f*y,t[1]+v*y],[i[0]+f*y,i[1]+v*y],[i[0]+m*y,i[1]+g*y],[t[0]+m*y,t[1]+g*y]];l.push({key:p,kind:c,cm:u,quad:b,a:[t[0],t[1]],b:[i[0],i[1]],depthUnits:_})}}return l}function ra(e,t=[]){let i=bs(e.quad);const[n,r]=No(e.a,e.b),o=n,s=r,a=-s,l=o;for(const n of t){if(!Yo(e.a,e.b,n.angle))continue;if(Os(n.x,n.y,e.a[0],e.a[1],e.b[0],e.b[1])>Math.max(.55*e.depthUnits,.001))continue;const t=n.length/2,r=e.depthUnits,c=n.x,h=n.y;i+=` ${bs(ws([[c-o*t-a*r,h-s*t-l*r],[c+o*t-a*r,h+s*t-l*r],[c+o*t+a*r,h+s*t+l*r],[c-o*t+a*r,h-s*t+l*r]]))}`}return i}function oa(e,t,i){const n=e?.length||0;if(n<3||t.length!==n)return null;if(t.every(e=>!(e>0)))return e.map(e=>[e[0],e[1]]);ws(e),t.slice().reverse();const r=[];for(let o=0;o0||l>0)){r.push([e[o][0],e[o][1]]);continue}if(a>0!=l>0){const t=e[o],i=a>0?[t[0]-c*a,t[1]-h*a]:[t[0],t[1]],n=l>0?[t[0]-d*l,t[1]-u*l]:[t[0],t[1]];r.push(i),Math.hypot(n[0]-i[0],n[1]-i[1])>1e-9&&r.push(n);continue}if(ms(w,k)){const t=e[o],i=[t[0]-c*a,t[1]-h*a],n=[t[0]-d*l,t[1]-u*l];r.push(i),Math.hypot(n[0]-i[0],n[1]-i[1])>1e-9&&r.push(n);continue}const $=gs(x,w,S,k),M=Math.max(a,l,1e-9),R=Ts(i,e[o])?.limit??4*M;if($){const i=Math.hypot($[0]-e[o][0],$[1]-e[o][1]);if(Number.isFinite(i)&&i<=R){r.push($);continue}if(Qs(e,t,o)){r.push([e[o][0],e[o][1]]);continue}}a>0&&r.push([e[o][0]-c*a,e[o][1]-h*a]),l>0&&r.push([e[o][0]-d*l,e[o][1]-u*l])}return r.length>=3?r:null}function sa(e,t,i,n,r,o,s=1){const a=[];for(const l of e||[]){if(!l?.id)continue;const c=As(e,l.id,t,i,n,r,o,s);if(!c)continue;const h=Math.abs(Ci(c.poly));for(let e=0;e[Math.max(t,e.x0),Math.min(i,e.x1)]).filter(e=>e[1]-e[0]>n).sort((e,t)=>e[0]-t[0]||e[1]-t[1]);if(!r.length)return{coverage:0,full:!1};let o=r[0][0],s=r[0][1],a=0,l=o<=t+n;for(let e=1;e=i-n,{coverage:a,full:l}}function la(e,t){return Number(t.full)-Number(e.full)||e.faceDistance-t.faceDistance||e.area-t.area||e.roomId.localeCompare(t.roomId)}function ca(e,t,i=!1){const n=Number(t?.x),r=Number(t?.y),o=Number(t?.angle),s=Number(t?.length);if(!([n,r,o,s].every(Number.isFinite)&&s>0))return{negative:null,positive:null};const a=o*Math.PI/180,l=Math.cos(a),c=Math.sin(a),h=-c,d=l,u=s/2,p=Math.max(1e-9,e.adjacencyEps),_=new Map;let m=0;for(const t of e.edges){if(i&&!(t.half>0))continue;if(!Yo(t.a,t.b,o))continue;const[e,s]=No(t.a,t.b);if(Math.abs((n-t.a[0])*s-(r-t.a[1])*e)>p)continue;const a=(t.a[0]-n)*l+(t.a[1]-r)*c,g=(t.b[0]-n)*l+(t.b[1]-r)*c,f=Math.max(-u,Math.min(a,g)),v=Math.min(u,Math.max(a,g));if(v-f<=p)continue;const y=t.inward[0]*h+t.inward[1]*d>=0?1:-1,b=((t.a[0]+t.b[0])/2-n)*h+((t.a[1]+t.b[1])/2-r)*d,w=Math.abs(b+y*t.half),k=`${y}|${t.roomId}`,x={x0:f,x1:v,half:t.half,cm:t.cm,key:t.key,axis:[e,s]},S=_.get(k);S?(S.pieces.push(x),S.faceDistance=Math.min(S.faceDistance,w)):_.set(k,{roomId:t.roomId,side:y,order:m++,pieces:[x],faceDistance:w,area:t.area,coverage:0,full:!1})}for(const e of _.values()){const t=aa(e.pieces,-u,u,p);e.coverage=t.coverage,e.full=t.full}const g=e=>{const t=[..._.values()].filter(t=>t.side===e&&t.coverage>p);return t.sort(la),t[0]||null};return{negative:g(-1),positive:g(1)}}function ha(e,t,i,n,r,o,s=1,a=[]){return da(sa(e,i,a,n,r,o,s),t)}function da(e,t){const i=ca(e,t),n=[i.negative,i.positive].filter(e=>!!e);if(!n.length)return{ox:0,oy:0,cm:0,side:-1};const r=i.negative&&i.positive?-1:n[0].side,o=t.flip_v?-r:r,s=(-1===o?i.negative:i.positive)||n[0],a=[...s.pieces].sort((e,t)=>(e.x0<=0&&e.x1>=0?0:Math.min(Math.abs(e.x0),Math.abs(e.x1)))-(t.x0<=0&&t.x1>=0?0:Math.min(Math.abs(t.x0),Math.abs(t.x1)))||t.x1-t.x0-(e.x1-e.x0)||e.key.localeCompare(t.key))[0];if(!(a.half>0&&a.cm>0))return{ox:0,oy:0,cm:0,side:o};const l=t.angle*Math.PI/180,c=-Math.sin(l),h=Math.cos(l);return{ox:c*o*a.half,oy:h*o*a.half,cm:a.cm,side:o}}function ua(e,t){const i=1e-9,n=t.filter(e=>Number.isFinite(e.x0)&&Number.isFinite(e.x1)&&Number.isFinite(e.half)&&e.x1>e.x0&&e.half>0);if(!n.length)return"";const r=n.flatMap(e=>[e.x0,e.x1]).sort((e,t)=>e-t),o=[];for(const e of r){const t=o[o.length-1];(void 0===t||e>t+i)&&o.push(e)}const s=[];for(let e=0;e+1t+i))continue;const a=(t+r)/2,l=n.reduce((e,t)=>a>=t.x0-i&&a<=t.x1+i?Math.max(e,t.half):e,0);if(!(l>0))continue;const c=s[s.length-1];c&&t<=c.x1+i&&Math.abs(l-c.half)<=i?c.x1=r:s.push({x0:t,x1:r,half:l})}const a=[];for(const e of s){const t=a[a.length-1],n=t?.[t.length-1];n&&e.x0<=n.x1+i?(e.x0=n.x1,t.push(e)):a.push([e])}return a.map(t=>{const i=t[0],n=t[t.length-1],r=Math.min(.25*Math.min(...t.map(e=>e.half)),.75),o=-e*r,s=[];if(1===e){s.push(`M ${i.x0} ${o} L ${n.x1} ${o}`);for(let e=t.length-1;e>=0;e--){const i=t[e];s.push(`L ${i.x1} ${i.half} L ${i.x0} ${i.half}`)}}else{s.push(`M ${n.x1} ${o} L ${i.x0} ${o}`);for(const e of t)s.push(`L ${e.x0} ${-e.half} L ${e.x1} ${-e.half}`)}return s.push("Z"),s.join(" ")}).join(" ")}function pa(e,t,i,n){if(!n)return i;const r=e.angle*Math.PI/180,o=Math.cos(r),s=Math.sin(r),a=[],l=1e-9;for(const r of i){const[i,c]=r.axis,h=o*i+s*c;if(Math.abs(h)<=l)continue;const d=e.x*i+e.y*c,u=d+h*r.x0,p=d+h*r.x1,_=Math.min(u,p),m=Math.max(u,p),g=`${r.key}|${t}`,f=n.get(g)||[];let v=[[_,m]];for(const[e,t]of f){const i=[];for(const[n,r]of v)t<=n+l||e>=r-l?i.push([n,r]):(e>n+l&&i.push([n,Math.min(r,e)]),te[0]-t[0]||e[1]-t[1]),b=[];for(const e of y){const t=b[b.length-1];t&&e[0]<=t[1]+l?t[1]=Math.max(t[1],e[1]):b.push([e[0],e[1]])}n.set(g,b)}return a}function _a(e,t){const i=new Map;return t.map(t=>function(e,t,i){const n=ca(e,t,!0),r=n.negative,o=n.positive;if(!r&&!o)return null;let s;if(r&&o)s=[{candidate:r,side:-1},{candidate:o,side:1}];else{const e=r||o;s=[{candidate:e,side:-1},{candidate:e,side:1}]}const a=s.map(({candidate:e,side:n})=>({candidate:e,side:n,pieces:pa(t,n,e.pieces,i)})),l=a.map(({candidate:e,side:t,pieces:i})=>({side:t,roomId:e.roomId,d:ua(t,i)})),c=a.flatMap(({pieces:e})=>e);if(!c.length)return null;const h=Math.max(...c.map(e=>e.half));return{faces:l,minY:-h,maxY:h,wallKey:[...new Set(c.map(e=>e.key))].sort().join("|")}}(e,t,i))}const ma=150,ga=1e-6;function fa(e){return Number.isFinite(e)?Math.max(1,Math.min(ma,e)):1}function va(e){return((Number.isFinite(Number(e))?Number(e):0)%90+90)%90}const ya=e=>{const t=e.map(e=>[e[0],e[1]]);return!t.length||t[0][0]===t[t.length-1][0]&&t[0][1]===t[t.length-1][1]||t.push([...t[0]]),[t]},ba=(e,t)=>e[0]===t[0]&&e[1]===t[1];function wa(e,t=1e-6){const i=Number.isFinite(t)&&t>0?t:ga,n=[];for(const t of e||[]){if(!Array.isArray(t)||t.length<2)return null;const e=Number(t[0]),r=Number(t[1]);if(!Number.isFinite(e)||!Number.isFinite(r))return null;const o=Math.round(e/i)*i,s=Math.round(r/i)*i;if(!Number.isFinite(o)||!Number.isFinite(s))return null;const a=[Object.is(o,-0)?0:o,Object.is(s,-0)?0:s];n.length&&ba(n[n.length-1],a)||n.push(a)}return n.length>1&&ba(n[0],n[n.length-1])&&n.pop(),n.length<3||new Set(n.map(e=>`${e[0]},${e[1]}`)).size<3?null:Ci(n)>i*i?n:null}function ka(e){const t=[];for(const i of e||[])for(const e of i||[]){const i=(e||[]).filter(e=>Array.isArray(e)&&e.length>=2);i.length<4||t.push(`M ${i.slice(0,-1).map(e=>`${e[0]} ${e[1]}`).join(" L ")} Z`)}return t.join(" ")}function xa(e,t,i,n,r){return ns({a:e,b:t,halfDepth:zo(i,n,r)/2})}function Sa(e,t,i){const n=Number(t)>0?Number(t):5,r=fa(e.cm)/n*i,o=e.center[0],s=e.center[1];if("circle"===e.shape){const e=r/2;return Array.from({length:96},(t,i)=>{const n=i/96*Math.PI*2;return[o+Math.cos(n)*e,s+Math.sin(n)*e]})}const a=r/2,l=va(e.angle)*Math.PI/180,c=Math.cos(l),h=Math.sin(l);return[[-a,-a],[a,-a],[a,a],[-a,a]].map(([e,t])=>[o+e*c-t*h,s+e*h+t*c])}function $a(e,t){const i=Number.isFinite(t)?Math.max(0,Math.min(1,t)):0,n=(e.a[0]+e.b[0])/2,r=(e.a[1]+e.b[1])/2,o=(e.b[0]-e.a[0])*i/2,s=(e.b[1]-e.a[1])*i/2;return{...e,a:[n-o,r-s],b:[n+o,r+s]}}function Ma(e,t,i=1e-9){if(!t.length)return[e];let n=[ya(e)];try{for(const e of t){const t=e.b[0]-e.a[0],r=e.b[1]-e.a[1],o=Math.hypot(t,r);if(!(o>i))continue;const s=t/o,a=r/o,l=-a,c=s,h=1.25*Math.max(Number(e.depth)||0,4*i),d=Math.max(2*i,1e-9*o),u=[[e.a[0]-s*d-l*h,e.a[1]-a*d-c*h],[e.b[0]+s*d-l*h,e.b[1]+a*d-c*h],[e.b[0]+s*d+l*h,e.b[1]+a*d+c*h],[e.a[0]-s*d+l*h,e.a[1]-a*d+c*h]];n=Gt(n,ya(u))}return Oa(n)}catch{return[e]}}function Ra(e,t){try{const i=Gt([[...e.map(e=>[e[0],e[1]]),[e[0][0],e[0][1]]]],[[...t.map(e=>[e[0],e[1]]),[t[0][0],t[0][1]]]]);let n=null,r=0;for(const e of i||[]){const t=e?.[0]||[],i=Math.abs(Ci(t));t.length>=4&&i>r&&(r=i,n=t.slice(0,-1).map(e=>[e[0],e[1]]))}return n}catch{return null}}function Ca(e,t,i,n=Math.max(2e-4*i,1e-9),r=[]){const o=[],s=new Map;for(const e of r){const t=s.get(e.hostId)||[];t.push(e),s.set(e.hostId,t)}const a=[],l=[],c=[];for(const n of e.partitions||[]){const e={a:n.a,b:n.b,halfDepth:zo(n.cm,t,i)/2};if(!(e.halfDepth>0))continue;const r=ns(e);r&&(o.push(e),a.push(r),c.push({id:n.id,body:r}))}const h=o;for(const{segmentIndex:e,wedge:t}of ls(h,n)){const i={list:a,at:e},n=Ra(i.list[i.at],t);n&&(i.list[i.at]=n,c[i.at].body=n)}for(const e of c)l.push(...Ma(e.body,s.get(e.id)||[],n));const d=(e.wall_columns||[]).map(e=>Sa(e,t,i)),u=cs(o,n).flatMap(e=>Ma(e,r,n));return{partitions:a,columns:d,patches:u,all:[...l,...u,...d]}}function Ta(e){try{const t=e.map(e=>wa(e)).filter(e=>!!e).map(e=>ya(e));return t.length?Wt(t[0],...t.slice(1)):null}catch{return null}}const Da=e=>`M ${e.map(e=>`${e[0]} ${e[1]}`).join(" L ")} Z`;function Aa(e){const t=[];for(const i of e||[]){if(za([i])<=1e-6)continue;const e=[];for(const t of i||[]){const i=(t||[]).filter(e=>Array.isArray(e)&&e.length>=2);i.length<4||e.push(Da(i.slice(0,-1)))}e.length&&t.push(e.join(" "))}return t}function Pa(e,t,i={}){const n=Ta(e.filter(e=>e.length>=3)),r=t.some(e=>!wa(e))?null:Ta(t);if(!n)return[];if(r)try{return Aa(Ut(n,r))}catch{}return function(e,t,i){let n=null;for(let r=0;r=4&&t.push(e.slice(0,-1).map(e=>[e[0],e[1]]));return t}function Oa(e){const t=[];for(const i of e||[]){const e=i?.[0];e?.length>=4&&t.push(e.slice(0,-1).map(e=>[e[0],e[1]]))}return t}function Ea(e,t){let i=!1;for(let n=0,r=t.length-1;ne[1]!=l>e[1]&&e[0]<(a-o)*(e[1]-s)/(l-s||1e-12)+o&&(i=!i)}return i}function Na(e,t){for(const i of t||[]){const t=i?.[0];if(!t?.length||!Ea(e,t))continue;let n=!1;for(let t=1;ti)return!1;if(Math.abs(fa(e.cm)-fa(t.cm))>1e-6)return!1;if(e.shape!==t.shape)return!0;if("circle"===e.shape||"circle"===t.shape)return!0;const n=Math.abs(va(e.angle)-va(t.angle));return Math.min(n,90-n)<=1e-6}const La=2.54;function Ba(e){const t="number"==typeof e?e:NaN;return!Number.isFinite(t)||t<=0||5===t?1:5/t}function qa(e,t){return e*Ba(t)}function ja(e){return e?La:1}function Wa(e,t){if(!t)return String(e);const i=e/La;return String(Math.round(1e6*i)/1e6)}function Ua(e,t){return t?e*La:e}const Ga=1e3;function Va(e,t){const i=Number(e),n=Number.isFinite(i)&&i>0?i:1,r=n>=1?t:t*n,o=n>=1?t/n:t;return{x:(t-r)/2,y:(t-o)/2,w:r,h:o}}const Ka=.01,Ya=100;function Xa(e,t=1e3){const i=Va(e?.plan_aspect,t),n=Number(e?.plan_scale),r=Number.isFinite(n)&&n>0?Math.min(Ya,Math.max(Ka,n)):1,o=Number(e?.plan_scale_x),s=Number(e?.plan_scale_y),a=Number.isFinite(o)&&o>0?Math.min(Ya,Math.max(Ka,o)):r,l=Number.isFinite(s)&&s>0?Math.min(Ya,Math.max(Ka,s)):r,c=Number(e?.plan_x),h=Number(e?.plan_y),d=Cr(e?.plan_angle);return{x:i.x+(Number.isFinite(c)?al(c):0)*t,y:i.y+(Number.isFinite(h)?al(h):0)*t,w:i.w*a,h:i.h*l,...d?{angle:d}:{}}}function Za(e){if(null==e.x||null==e.y)return{x:e.x,y:e.y,w:e.w,h:e.h};const t=Number(e.w)||0,i=Number(e.h)||0;return{x:t<0?e.x+t:e.x,y:i<0?e.y+i:e.y,w:Math.abs(t),h:Math.abs(i)}}function Ja(e){return e&&Array.isArray(e.spaces)?e.spaces.map(e=>{const t=Ga,i=function(e){return Array.isArray(e)&&4===e.length&&e.every(e=>Number.isFinite(e))&&e[2]>1e-6&&e[3]>1e-6?e:[0,0,1,1]}(e.view_box);return{id:e.id,title:e.title,cellCm:Number.isFinite(Number(e.cell_cm))&&Number(e.cell_cm)>0?Number(e.cell_cm):5,vb:[i[0]*Ga,i[1]*t,i[2]*Ga,i[3]*t],bg:e.plan_url?{href:En(e.plan_url),...Xa(e,Ga)}:null,rooms:(e.rooms||[]).map(e=>{const i={...e,...Za(e)};return{id:i.id,name:i.name,area:i.area??null,open_to:i.open_to||void 0,settings:i.settings||void 0,x:null!=i.x?i.x*Ga:void 0,y:null!=i.y?i.y*t:void 0,w:null!=i.w?i.w*Ga:void 0,h:null!=i.h?i.h*t:void 0,poly:i.poly?i.poly.map(e=>[e[0]*Ga,e[1]*t]):void 0,wall_ids:Array.isArray(i.wall_ids)?[...i.wall_ids]:void 0}}),wall_segments:(e.wall_segments||[]).map(e=>({...e,id:String(e.id),a:[Number(e.a?.[0])*Ga,Number(e.a?.[1])*t],b:[Number(e.b?.[0])*Ga,Number(e.b?.[1])*t],cm:Number(e.cm)})),partitions:(e.partitions||[]).map(e=>({id:e.id,a:[e.a[0]*Ga,e.a[1]*t],b:[e.b[0]*Ga,e.b[1]*t],cm:Number(e.cm)})),wall_columns:(e.wall_columns||[]).map(e=>({id:e.id,shape:"circle"===e.shape?"circle":"square",center:[e.center[0]*Ga,e.center[1]*t],cm:Number(e.cm),..."circle"===e.shape?{}:{angle:va(e.angle)}}))}}):[]}const Qa=5e3,el=Qa*Ga,tl=240,il=Ga/tl,nl=1/tl;function rl(e){if(!Number.isFinite(e))return e;const t=Math.round(e*tl/Ga)*Ga/tl;return Math.abs(t-e)<=1e-9*il?e:t}function ol(e){return{x:rl(e.x),y:rl(e.y)}}function sl(e){return Number.isFinite(e)?Math.min(el,Math.max(-el,e)):0}function al(e){return Number.isFinite(e)?Math.min(Qa,Math.max(-Qa,e)):0}const ll=1/3,cl=200;function hl(e){return"house"===e?"house":"content"}function dl(e){let t=1/0,i=1/0,n=-1/0,r=-1/0;for(const o of e){const e=Number(o[0]),s=Number(o[1]);Number.isFinite(e)&&Number.isFinite(s)&&(en&&(n=e),s>r&&(r=s))}return t>n?null:{minX:t,minY:i,maxX:n,maxY:r}}function ul(e){const t=[],i=e=>{if(Array.isArray(e))if(e.length>=2&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1])))t.push([Number(e[0]),Number(e[1])]);else for(const t of e)i(t)};return i(e),dl(t)}function pl(e,t){const i=Number.isFinite(t)&&t>0?t:0;return{minX:e.minX-i,minY:e.minY-i,maxX:e.maxX+i,maxY:e.maxY+i}}function _l(e){return e.poly&&e.poly.length?dl(e.poly):null==e.x||null==e.y?null:dl([[e.x,e.y],[e.x+(e.w||0),e.y+(e.h||0)]])}function ml(e,t=1e3,i=1e3){const n=Number(e.x)*t,r=Number(e.y)*i,o=Number(e.w)*t,s=Number(e.h)*i;return![n,r,o,s].every(Number.isFinite)||o<=0||s<=0?null:dl(Or({x:n,y:r,w:o,h:s,angle:Cr(e.angle)||void 0}))}function gl(e,t){const i=[];for(const t of e.rooms||[]){const e=_l(t);e&&i.push(e)}if(e.bg){const t=dl(Or(e.bg));t&&i.push(t)}for(const e of t||[])if(Array.isArray(e)){const t=dl([e]);t&&i.push(t)}else i.push(e);return i}const fl=e=>{if(!e.length)return 0;const t=[...e].sort((e,t)=>e-t),i=t.length>>1;return t.length%2?t[i]:(t[i-1]+t[i])/2},vl=e=>{let t=1/0,i=1/0,n=-1/0,r=-1/0;for(const o of e)o.minXn&&(n=o.maxX),o.maxY>r&&(r=o.maxY);return t>n||i>r?null:{x:t,y:i,w:n-t,h:r-i}};function yl(e,t){let{x:i,y:n,w:r,h:o}=e;r<30&&(i=i+r/2-100,r=cl),o<30&&(n=n+o/2-100,o=cl);const s="number"==typeof t?{top:t,right:t,bottom:t,left:t}:t,a=Math.max(r,o),l=a*s.top,c=a*s.right,h=a*s.bottom,d=a*s.left;return{x:i-d,y:n-l,w:r+d+c,h:o+l+h}}function bl(e,t={}){const i=t.pad??.05,n=t.k??10,r=t.minSpread??50,o=e.filter(e=>Number.isFinite(e.minX)&&Number.isFinite(e.minY)&&Number.isFinite(e.maxX)&&Number.isFinite(e.maxY)&&Math.abs(e.minX)<=el&&Math.abs(e.maxX)<=el&&Math.abs(e.minY)<=el&&Math.abs(e.maxY)<=el);if(!o.length)return{core:null,all:null,outliers:0};const s=vl(o);if(o.length<4){const e=yl(s,i);return{core:e,all:e,outliers:0}}const a=o.map(e=>(e.minX+e.maxX)/2),l=o.map(e=>(e.minY+e.maxY)/2),c=fl(a),h=fl(l),d=o.map((e,t)=>Math.max(Math.abs(a[t]-c),Math.abs(l[t]-h))),u=Math.max(((e,t)=>e.length?e[Math.min(e.length-1,Math.max(0,Math.round(t*(e.length-1))))]:0)([...d].sort((e,t)=>e-t),.75),r),p=d.map(e=>e>n*u),_=p.filter(Boolean).length,m=_&&_<=o.length*ll?o.filter((e,t)=>!p[t]):o;return{core:yl(vl(m)||s,i),all:yl(s,i),outliers:m===o?0:_}}function wl(e){return bl(e,{pad:0}).all}function kl(e,t,i=.05){const n=bl(gl(e,t),{pad:i});if(n.core)return n.core;const r=e.vb&&4===e.vb.length&&e.vb[2]>0&&e.vb[3]>0?e.vb:[0,0,Ga,Ga];return{x:r[0],y:r[1],w:r[2],h:r[3]}}function xl(e){const t=kl(e);return{x:t.x+t.w/2,y:t.y+t.h/2}}function Sl(e){const t=[];for(const i of e.rooms||[]){const e=_l(i);e&&t.push(e)}const i=bl(t,{pad:0}).core,n=Ga*Ba(e.cellCm??5);return i?Math.max(n,Math.min(el,Math.max(i.w,i.h))):n}function $l(e,t,i,n=1){const r=Number(i),o=Number.isFinite(n)&&n>0?n:1;return!Number.isFinite(r)||r<=0?e*o:e*Sl(t)*o/r}const Ml=[1,2,5,10,20,50,100,200,500,1e3];function Rl(e,t,i=7){if(!(e>0&&t>0&&Number.isFinite(t)))return null;const n=Ml.find(n=>e*n*t>=i);if(void 0===n)return null;const r=Ml.find(e=>e>=5*n)??5*n;return{fine:n,coarse:r}}function Cl(e){if(e.poly&&e.poly.length){const t=e.poly.map(e=>e[0]),i=e.poly.map(e=>e[1]),n=Math.min(...t),r=Math.min(...i);return{x:n,y:r,w:Math.max(...t)-n,h:Math.max(...i)-r}}return{x:e.x??0,y:e.y??0,w:e.w??0,h:e.h??0}}function Tl(e,t,i,n,r,o=new Set){const s=t[e.id];return!o.has(e.id)&&s&&s.s===e.space?{x:s.x*Ga,y:s.y*Ga}:n[e.id]?n[e.id]:ol(xl(r))}function Dl(e,t,i,n){const r=i["rl_"+(e.id||"")];if(r&&r.s===t)return{x:r.x*Ga,y:r.y*Ga};const o=function(e){if(e.poly){const t=e.poly.length;return[e.poly.reduce((e,t)=>e+t[0],0)/t,e.poly.reduce((e,t)=>e+t[1],0)/t]}return[e.x+e.w/2,e.y+.1*Math.min(e.w,e.h)]}(e);return ol({x:o[0],y:o[1]})}function Al(e,t){for(const i of e?.spaces??[])for(const e of i?.decor??[])if("furniture"===e?.kind&&"string"==typeof e.symbol&&t(e.symbol))return!0;return!1}let Pl=0;const Fl=new Set;const zl=new class{constructor(e){this.options=e,this._art=null,this._failed=!1,this._terminal=!1,this._inFlight=null,this._hosts=new Set,this._settled=[]}state(){return this._art?"ready":this._failed?"fallback":"pending"}get terminal(){return this._terminal}art(e,t){if(this._art)return this._art[e];t&&!this._failed&&this._hosts.add(t)}adopt(e,t){return!!this._art||(t!==this.options.expectedFingerprint?((this.options.warn??console.warn)("[houseplan] furniture artwork from another build ignored",{fingerprint:t}),!1):(this._install(e),!0))}ensure(){return"pending"!==this.state()?Promise.resolve():(this._inFlight||(this._inFlight=this._loadWithRetry().finally(()=>{this._inFlight=null})),this._inFlight)}onSettled(e){"pending"===this.state()?this._settled.push(e):Promise.resolve().then(e)}async _loadWithRetry(){let e=new Error("furniture artwork did not load");for(const t of[0,1])try{const i=await this.options.load(t);if(i.FURNITURE_ART_FINGERPRINT!==this.options.expectedFingerprint){this._terminal=!0,e=new Error(`furniture artwork fingerprint mismatch: expected ${this.options.expectedFingerprint}, got ${i.FURNITURE_ART_FINGERPRINT}`);break}if(this._art)return;return void this._install(i.GENERATED_FURNITURE_ART)}catch(t){e=t}this._art||(this._failed=!0,(this.options.warn??console.warn)("[houseplan] furniture artwork unavailable",e),this.options.loadFailed?.(this._terminal),this._flush())}_install(e){this._art=e,this._failed=!1,this._flush()}_flush(){const e=[...this._hosts];this._hosts.clear();for(const t of e)t.isConnected&&t.requestUpdate();const t=this._settled.splice(0);for(const e of t)e()}}({expectedFingerprint:"3f783ed7cf5daff202a910aa89044f88f605a65af7f46794277dddf04333e502",load:async e=>0===e?await import("./furniture-plan-art.generated-C_Z1hwSa.js"):await import((()=>{const e=new URL("./furniture-plan-art.generated-C_Z1hwSa.js",import.meta.url);return e.searchParams.set("hp_retry","art-"+ ++Pl),e.href})()),loadFailed:e=>{for(const t of Fl)t(e)}}),Il=["furniture","appliance","sanitary","other"],Ol=[{id:"sofa",group:"furniture",category:"sofa",w:220,h:90,g:[["r",0,0,1,1],["l",.09,.26,.91,.26],["l",.09,.26,.09,1],["l",.91,.26,.91,1],["l",.5,.26,.5,1]]},{id:"armchair",group:"furniture",category:"armchair",w:90,h:85,g:[["r",0,0,1,1],["l",.14,.28,.86,.28],["l",.14,.28,.14,1],["l",.86,.28,.86,1]]},{id:"coffee_table",group:"furniture",category:"coffee_table",w:110,h:60,g:[["r",0,0,1,1],["r",.08,.14,.84,.72]]},{id:"table_dining",group:"furniture",category:"dining_table",w:140,h:80,g:[["r",0,0,1,1],["r",.06,.11,.88,.78]]},{id:"table_round",group:"furniture",category:"dining_table",w:120,h:120,g:[["e",.5,.5,.5,.5],["e",.5,.5,.41,.41]]},{id:"chair",group:"furniture",category:"chair",w:45,h:45,g:[["r",0,0,1,.18],["r",.06,.18,.88,.8]]},{id:"desk",group:"furniture",category:"work_table",w:120,h:60,g:[["r",0,0,1,1],["r",.63,.07,.31,.86],["l",.63,.5,.94,.5]]},{id:"bed_double",group:"furniture",category:"bed",w:160,h:200,g:[["r",0,0,1,1],["r",0,0,1,.07],["r",.06,.1,.4,.15],["r",.54,.1,.4,.15],["l",0,.33,1,.33]]},{id:"bed_single",group:"furniture",category:"bed",w:90,h:200,g:[["r",0,0,1,1],["r",0,0,1,.07],["r",.15,.1,.7,.15],["l",0,.33,1,.33]]},{id:"nightstand",group:"furniture",category:"nightstand",w:45,h:40,g:[["r",0,0,1,1],["r",.12,.14,.76,.33],["r",.12,.53,.76,.33]]},{id:"wardrobe",group:"furniture",category:"wardrobe",w:100,h:60,g:[["r",0,0,1,1],["l",0,.72,1,.72],["l",.5,.72,.5,1]]},{id:"bookshelf",group:"furniture",category:"wardrobe",w:80,h:30,g:[["r",0,0,1,1],["l",.34,0,.34,1],["l",.67,0,.67,1]]},{id:"fridge",group:"appliance",category:"fridge",w:60,h:65,g:[["r",0,0,1,1],["l",0,.36,1,.36],["l",.83,.44,.83,.64]]},{id:"stove",group:"appliance",category:"cooktop",w:60,h:60,g:[["r",0,0,1,1],["e",.29,.31,.15,.15],["e",.71,.31,.15,.15],["e",.29,.71,.15,.15],["e",.71,.71,.15,.15]]},{id:"dishwasher",group:"appliance",category:"dishwasher",w:60,h:60,g:[["r",0,0,1,1],["r",.1,.12,.8,.76],["e",.5,.5,.27,.27],["e",.5,.5,.13,.13]]},{id:"washer",group:"appliance",category:"washer",w:60,h:60,g:[["r",0,0,1,1],["l",.08,.17,.92,.17],["e",.5,.57,.3,.3],["e",.5,.57,.14,.14]]},{id:"dryer",group:"appliance",category:"dryer",w:60,h:60,g:[["r",0,0,1,1],["l",.08,.17,.92,.17],["e",.5,.57,.3,.3],["p",.36,.5,.5,.64,.64,.5]]},{id:"tv",group:"appliance",category:"tv",w:120,h:30,g:[["r",0,0,1,.42],["l",.5,.42,.5,.72],["l",.3,.72,.7,.72]]},{id:"ac",group:"appliance",category:"air_conditioner",w:90,h:25,g:[["r",0,0,1,1],["l",.05,.55,.95,.55],["l",.05,.79,.95,.79]]},{id:"water_heater",group:"appliance",category:"boiler",w:45,h:45,g:[["e",.5,.5,.5,.5],["e",.5,.5,.31,.31]]},{id:"toilet",group:"sanitary",category:"toilet",w:40,h:70,g:[["r",.06,0,.88,.2],["e",.5,.58,.37,.35],["e",.5,.58,.22,.2]]},{id:"bathtub",group:"sanitary",category:"bathtub",w:170,h:75,g:[["r",0,0,1,1],["r",.05,.11,.77,.78],["e",.89,.5,.045,.1]]},{id:"shower",group:"sanitary",category:"shower",w:90,h:90,g:[["r",0,0,1,1],["l",0,0,1,1],["l",1,0,0,1],["e",.5,.5,.08,.08]]},{id:"sink",group:"sanitary",category:"sink",w:60,h:45,g:[["r",0,0,1,1],["e",.5,.6,.34,.3],["e",.5,.15,.07,.07]]},{id:"kitchen_sink",group:"sanitary",category:"kitchen_sink",w:80,h:60,g:[["r",0,0,1,1],["r",.06,.24,.44,.64],["r",.54,.24,.4,.64],["e",.5,.12,.06,.06]]},{id:"bidet",group:"sanitary",category:"bidet",w:40,h:55,g:[["e",.5,.5,.44,.5],["e",.5,.5,.26,.3]]},{id:"stairs",group:"other",category:"stairs",w:100,h:280,g:[["r",0,0,1,1],["l",0,.111,1,.111],["l",0,.222,1,.222],["l",0,.333,1,.333],["l",0,.444,1,.444],["l",0,.556,1,.556],["l",0,.667,1,.667],["l",0,.778,1,.778],["l",0,.889,1,.889],["l",.5,.93,.5,.06],["p",.38,.16,.5,.06,.62,.16]]},{id:"fireplace",group:"other",category:"fireplace",w:120,h:40,g:[["r",0,0,1,1],["p",.22,1,.22,.42,.78,.42,.78,1]]},{id:"plant",group:"other",category:"plant",w:40,h:40,g:[["e",.5,.5,.22,.22],["l",.5,.28,.5,.02],["l",.5,.72,.5,.98],["l",.28,.5,.02,.5],["l",.72,.5,.98,.5],["l",.34,.34,.13,.13],["l",.66,.66,.87,.87],["l",.66,.34,.87,.13],["l",.34,.66,.13,.87]]},{id:"rug",group:"other",category:"rug",w:200,h:140,g:[["r",0,0,1,1],["r",.06,.09,.88,.82]]}],El=new Set(["fridge","dishwasher","washer","dryer","ac","water_heater","shower","sink","stairs","fireplace","plant","rug"]),Nl=[...[{id:"coffee_table",group:"furniture",category:"coffee_table",w:120,h:60},{id:"coffee_table_round",group:"furniture",category:"coffee_table",w:80,h:80},{id:"coffee_table_oval",group:"furniture",category:"coffee_table",w:120,h:60},{id:"coffee_table_rounded",group:"furniture",category:"coffee_table",w:120,h:60},{id:"table_dining",group:"furniture",category:"dining_table",w:160,h:90},{id:"table_round",group:"furniture",category:"dining_table",w:110,h:110},{id:"table_dining_oval",group:"furniture",category:"dining_table",w:180,h:100},{id:"table_dining_rounded",group:"furniture",category:"dining_table",w:160,h:90},{id:"desk",group:"furniture",category:"work_table",w:140,h:70},{id:"desk_corner",group:"furniture",category:"work_table",w:160,h:160},{id:"chair",group:"furniture",category:"chair",w:50,h:50},{id:"chair_bar",group:"furniture",category:"chair",w:45,h:48},{id:"armchair",group:"furniture",category:"armchair",w:90,h:90},{id:"armchair_office",group:"furniture",category:"armchair",w:65,h:65},{id:"sofa",group:"furniture",category:"sofa",w:180,h:90},{id:"sofa_three_seat",group:"furniture",category:"sofa",w:240,h:90},{id:"sofa_corner_right",group:"furniture",category:"sofa",w:260,h:170},{id:"bed_single",group:"furniture",category:"bed",w:90,h:200},{id:"bed_double",group:"furniture",category:"bed",w:160,h:200},{id:"nightstand",group:"furniture",category:"nightstand",w:50,h:40},{id:"cabinet_tv",group:"furniture",category:"nightstand",w:140,h:45},{id:"cabinet_shoe",group:"furniture",category:"nightstand",w:80,h:35},{id:"cabinet_sink",group:"furniture",category:"nightstand",w:80,h:50},{id:"bookshelf",group:"furniture",category:"wardrobe",w:100,h:35},{id:"wall_unit",group:"furniture",category:"wardrobe",w:240,h:45},{id:"wardrobe",group:"furniture",category:"wardrobe",w:180,h:60},{id:"kitchen_floor",group:"furniture",category:"kitchen_cabinet",w:60,h:60},{id:"kitchen_floor_corner",group:"furniture",category:"kitchen_cabinet",w:90,h:90},{id:"kitchen_wall",group:"furniture",category:"kitchen_cabinet",w:60,h:35},{id:"kitchen_wall_corner",group:"furniture",category:"kitchen_cabinet",w:60,h:60},{id:"shelf_floor",group:"furniture",category:"shelving",w:100,h:35},{id:"shelf_wall",group:"furniture",category:"shelving",w:100,h:25},{id:"cooktop_two",group:"appliance",category:"cooktop",w:30,h:50},{id:"stove",group:"appliance",category:"cooktop",w:60,h:60},{id:"tv",group:"appliance",category:"tv",w:120,h:28},{id:"tv_wall",group:"appliance",category:"tv",w:120,h:15},{id:"toilet",group:"sanitary",category:"toilet",w:40,h:70},{id:"toilet_built_in",group:"sanitary",category:"toilet",w:40,h:55},{id:"bathtub",group:"sanitary",category:"bathtub",w:170,h:75},{id:"bathtub_corner",group:"sanitary",category:"bathtub",w:140,h:140},{id:"bidet",group:"sanitary",category:"bidet",w:40,h:60},{id:"bidet_built_in",group:"sanitary",category:"bidet",w:40,h:50},{id:"kitchen_sink",group:"sanitary",category:"kitchen_sink",w:60,h:50},{id:"kitchen_sink_double",group:"sanitary",category:"kitchen_sink",w:90,h:50}].map(e=>({id:e.id,group:e.group,category:e.category,w:e.w,h:e.h,designer:!0})),...Ol.filter(e=>El.has(e.id))],Hl=new Map(Nl.map(e=>[e.id,e]));function Ll(e){return e&&Hl.get(e)||null}function Bl(e){return!0===Hl.get(e)?.designer}function ql(e){return Nl.filter(t=>t.group===e)}function jl(e){const t=Ll(e);return t?{w:t.w,h:t.h}:{w:60,h:60}}function Wl(e,t,i=il,n=1e3){const r=Number(t)>0?Number(t):5;return(Number(e)||0)/r*i/n}const Ul=5e-4,Gl=Qa;function Vl(e){return Number.isFinite(e)?Math.max(Ul,Math.min(Gl,e)):Ul}function Kl(e){return Number.isFinite(e)?Math.max(1,Math.min(1e4,e)):1}const Yl=e=>{const t=Math.round(1e3*e)/1e3;return Object.is(t,-0)?"0":String(t)};function Xl(e,t){const i=Ll(e);if(!i)return null;if(i.designer)return zl.art(e,t)??null;const n=function(e,t,i){if(!e.g)return"";const n=e=>Yl(e*t),r=e=>Yl(e*i),o=[];for(const s of e.g)if("r"===s[0]){const[,e,t,i,a]=s;o.push(`M${n(e)} ${r(t)}H${n(e+i)}V${r(t+a)}H${n(e)}Z`)}else if("l"===s[0]){const[,e,t,i,a]=s;o.push(`M${n(e)} ${r(t)}L${n(i)} ${r(a)}`)}else if("e"===s[0]){const[,e,a,l,c]=s;o.push(`M${n(e-l)} ${r(a)}A${Yl(l*t)} ${Yl(c*i)} 0 0 1 ${n(e+l)} ${r(a)}A${Yl(l*t)} ${Yl(c*i)} 0 0 1 ${n(e-l)} ${r(a)}Z`)}else{const e=s.slice(1);if(e.length<4)continue;let t=`M${n(e[0])} ${r(e[1])}`;for(let i=2;i+10?n:Number.isFinite(r)&&r>0?r:1,s=Number(t),a=o*(Number.isFinite(s)&&s>0?s:1);return Number.isFinite(a)&&a>0?a:o}function Jl(e,t,i,n,r){const o=e+i/2,s=t+n/2,a=(Number(r)||0)*Math.PI/180,l=Math.cos(a),c=Math.sin(a),h=(e,t)=>{const i=e-o,n=t-s;return[o+i*l-n*c,s+i*c+n*l]};return[h(e,t),h(e+i,t),h(e+i,t+n),h(e,t+n)]}function Ql(e,t,i,n,r,o,s){const a=Number.isFinite(s)&&s>0?s:1e-6,l=(Number(e.angle)||0)*Math.PI/180,c=Math.cos(l),h=Math.sin(l),d=-Math.sin(l),u=Math.cos(l),p=e.x+e.w/2,_=e.y+e.h/2,m=t>0?-e.w/2:t<0?e.w/2:0,g=i>0?-e.h/2:i<0?e.h/2:0,f=p+m*c+g*d,v=_+m*h+g*u,y=n-f,b=r-v,w=t?(y*c+b*h)*(t>0?1:-1):e.w,k=i?(y*d+b*u)*(i>0?1:-1):e.h;let x=t?Math.abs(w):e.w,S=i?Math.abs(k):e.h;if(o&&t&&i){const t=x/Math.max(e.w,a),i=S/Math.max(e.h,a),n=Math.abs(t-1)>=Math.abs(i-1)?t:i,r=Math.max(a/e.w,a/e.h),o=Math.max(r,Number.isFinite(n)?n:r);x=e.w*o,S=e.h*o}x=Math.max(a,Number.isFinite(x)?x:a),S=Math.max(a,Number.isFinite(S)?S:a);const $=!!t&&w<0,M=!!i&&k<0,R=t?(t>0?1:-1)*($?-1:1):0,C=i?(i>0?1:-1)*(M?-1:1):0,T=f+R*(x/2)*c+C*(S/2)*d,D=v+R*(x/2)*h+C*(S/2)*u,A=!!e.flip_h!==$,P=!!e.flip_v!==M;return{x:T-x/2,y:D-S/2,w:x,h:S,...Number(e.angle)?{angle:Number(e.angle)}:{},...A?{flip_h:!0}:{},...P?{flip_v:!0}:{}}}function ec(e,t,i,n){let r=Number(e)+(Number(i)-Number(t));if([r,t,i].every(Number.isFinite)||(r=0),n){const e=r/45;r=45*(e<0?-Math.round(Math.abs(e)):Math.round(e))}return r=(r%360+360)%360,r>180?r-360:r}function tc(e,t,i,n,r){const o=e.x*t,s=e.y*i,a=e.w*t,l=e.h*i,c=o+a/2,h=s+l/2,d=o+(e.flip_h?a:0),u=s+(e.flip_v?l:0),p=(e.flip_h?-1:1)*a/n,_=(e.flip_v?-1:1)*l/r,m=Number(e.angle)||0;return(m?`rotate(${m} ${c} ${h}) `:"")+`translate(${d} ${u}) scale(${p} ${_})`}function ic(e,t,i,n=.1){if("string"==typeof e&&!e.trim())return null;const r=Number(e);if(!Number.isFinite(r)||0===r)return null;const o=r*(t?30.48:100),s=Math.abs(o);return si?null:o}function nc(e,t,i){const n=Math.abs(Number(e))/(i?30.48:100),r=Number(n.toFixed(6));return String(t?-r:r)}const rc=15e3,oc=2e3,sc=new WeakMap;function ac(e,t){let i=sc.get(e);if(!i){const t=new Set;i={hiddenAt:"hidden"===e.visibilityState?Date.now():0,token:0,subscribers:t,onVisibility:()=>{const t=sc.get(e);if(!t)return;const i=Date.now();if("hidden"===e.visibilityState){t.hiddenAt||(t.hiddenAt=i);const e={kind:"hidden",token:t.token,at:i,hiddenFor:0,long:!1};for(const i of[...t.subscribers])i(e);return}const n=t.hiddenAt?Math.max(0,i-t.hiddenAt):0;t.hiddenAt=0,t.token++;const r={kind:"visible",token:t.token,at:i,hiddenFor:n,long:n>=rc};for(const e of[...t.subscribers])e(r)},onPageShow:t=>{const i=sc.get(e);if(!i)return;const n=Date.now();i.token++;const r={kind:"pageshow",token:i.token,at:n,hiddenFor:0,long:!!t.persisted,persisted:!!t.persisted};for(const e of[...i.subscribers])e(r)}},sc.set(e,i),e.addEventListener("visibilitychange",i.onVisibility),e.defaultView?.addEventListener("pageshow",i.onPageShow)}return i.subscribers.add(t),()=>{const i=sc.get(e);i&&(i.subscribers.delete(t),i.subscribers.size||(e.removeEventListener("visibilitychange",i.onVisibility),e.defaultView?.removeEventListener("pageshow",i.onPageShow),sc.delete(e)))}}const lc={now:()=>Date.now(),setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>window.clearTimeout(e),requestAnimationFrame:e=>window.requestAnimationFrame(e),cancelAnimationFrame:e=>window.cancelAnimationFrame(e)};class cc{constructor(e,t=lc){this.onChange=e,this.clock=t,this._state="steady",this._token=0,this._frameFingerprint="",this._hasCompleteFrame=!1,this._overlayPhase="none",this._recoveryReason=null,this._overlayTimer=0,this._overlayRaf=0,this._overlayOpaqueAt=0,this._barrierRafs=new Set,this._trace=[],this._disposed=!1}get state(){return this._state}get token(){return this._token}get frameFingerprint(){return this._frameFingerprint}get hasCompleteFrame(){return this._hasCompleteFrame}get overlayPhase(){return this._overlayPhase}get overlayVisible(){return"none"!==this._overlayPhase}get overlayBlocksInteraction(){return this.overlayVisible}get recoveryReason(){return this._recoveryReason}get trace(){return this._trace.map(e=>({...e,...e.stage?{stage:[...e.stage]}:{}}))}note(e,t={}){this.record(e,void 0,t)}record(e,t,i={}){this._trace.push({at:this.clock.now(),token:this._token,event:e,state:this._state,...t?{reason:t}:{},...i}),this._trace.length>80&&this._trace.splice(0,this._trace.length-80)}changed(){this._disposed||this.onChange()}adoptCompleteFrame(e){e&&(this._hasCompleteFrame=!0,this._frameFingerprint=e,this._state="steady",this._recoveryReason=null,this.clearOverlay(),this.record("frame-adopted"),this.changed())}markCompleteFrame(e){e&&(this._hasCompleteFrame=!0,this._frameFingerprint=e,this._state="steady",this._recoveryReason=null,this.clearOverlay(),this.record("frame-complete"),this.changed())}refreshCompleteFrame(e){!this._disposed&&this._hasCompleteFrame&&"steady"===this._state&&e&&e!==this._frameFingerprint&&(this._frameFingerprint=e,this.record("frame-refreshed"))}visibility(e){return"hidden"===e.kind?(this.record("visibility-hidden"),this._token):e.long||"visible"!==e.kind&&"pageshow"!==e.kind?this.beginCandidate("pageshow"===e.kind?"pageshow":"long-resume"):(this.record("pageshow"===e.kind?"pageshow-noop":"visibility-visible-quick"),this._token)}beginCandidate(e,t="plan"){return this._token++,this._recoveryReason=t,this._hasCompleteFrame?(this._state="connection"===t?"offline-stale":"holding",this.clearOverlay()):this.overlayVisible?this._state="overlay-visible":(this._state="overlay-pending",this.scheduleOverlay(t)),this.record("candidate-start",e),this.changed(),this._token}connectionLost(){return this.beginCandidate("connection-lost","connection")}candidateReady(e){return!this._disposed&&e===this._token&&(this._state="candidate-ready",this.record("candidate-ready"),this.changed(),!0)}async commitAfterPaint(e,t){if(this._disposed||e!==this._token)return!1;let i=!0;const n=(async()=>{for(await t.updateComplete();i&&!this._disposed&&e===this._token;)if(t.stageValid()&&t.assetsReady()){if(await this.nextFrame(),e!==this._token||!t.stageValid()||!t.assetsReady())continue;if(await this.nextFrame(),e===this._token&&t.stageValid()&&t.assetsReady())return!0}else await this.nextFrame();return!1})();let r=0;const o=new Promise(e=>{r=this.clock.setTimeout(()=>e({ready:!1,timedOut:!0}),oc)}),s=await Promise.race([n.then(e=>({ready:e,timedOut:!1})),o]);return i=!1,this.clock.clearTimeout(r),!this._disposed&&e===this._token&&(!(!s.ready&&!s.timedOut)&&(s.ready?(this._hasCompleteFrame=!0,this._frameFingerprint=t.frameFingerprint(),this.record("paint-barrier"),this.finishOverlayAfterCommit(),!0):(this.record("paint-barrier-timeout"),this._hasCompleteFrame?(this._state="connection"===this._recoveryReason?"offline-stale":"steady",this.clearOverlay()):(this._state="recovery-error","opaque"!==this._overlayPhase&&this.showOverlayNow()),this.changed(),!1)))}retry(e=this._recoveryReason||"plan"){return this.beginCandidate("retry",e)}nextFrame(){return new Promise(e=>{const t=this.clock.requestAnimationFrame(()=>{this._barrierRafs.delete(t),e()});this._barrierRafs.add(t)})}scheduleOverlay(e){this.clearOverlayTimer(),this._recoveryReason=e,this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._hasCompleteFrame||"overlay-pending"!==this._state&&"candidate-ready"!==this._state||(this._state="overlay-visible",this._overlayPhase="entering",this.record("overlay-enter"),this.changed(),this._overlayRaf=this.clock.requestAnimationFrame(()=>{this._overlayRaf=0,"entering"===this._overlayPhase&&(this._overlayPhase="fading-in",this.changed(),this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,"fading-in"===this._overlayPhase&&(this._overlayPhase="opaque",this._overlayOpaqueAt=this.clock.now(),this.record("overlay-opaque"),this.changed())},150))}))},150)}showOverlayNow(){this.clearOverlayTimer(),this._overlayPhase="opaque",this._overlayOpaqueAt=this.clock.now(),this.record("overlay-error")}finishOverlayAfterCommit(){if(this.clearOverlayTimer(),"none"===this._overlayPhase||"entering"===this._overlayPhase||"fading-in"===this._overlayPhase)return this.clearOverlay(),this._state="steady",this._recoveryReason=null,this.record("candidate-committed"),void this.changed();const e=Math.max(0,this._overlayOpaqueAt+250-this.clock.now());this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._overlayPhase="leaving",this.record("overlay-leave"),this.changed(),this._overlayTimer=this.clock.setTimeout(()=>{this._overlayTimer=0,this._overlayPhase="none",this._state="steady",this._recoveryReason=null,this.record("candidate-committed"),this.changed()},180)},e)}clearOverlayTimer(){this._overlayTimer&&this.clock.clearTimeout(this._overlayTimer),this._overlayTimer=0}clearOverlay(){this.clearOverlayTimer(),this._overlayRaf&&this.clock.cancelAnimationFrame(this._overlayRaf),this._overlayRaf=0,this._overlayPhase="none",this._overlayOpaqueAt=0}dispose(){this._disposed=!0,this._token++,this.clearOverlay();for(const e of this._barrierRafs)this.clock.cancelAnimationFrame(e);this._barrierRafs.clear()}}function hc(e){let t=2166136261,i=2654435769;const n=new WeakSet,r=e=>{for(let n=0;n>>0)+(i>>>2)}},o=e=>{if(null===e)return void r("n");const t=typeof e;if("string"===t)return void r(`s${e.length}:${e}`);if("number"===t)return void r(`d${Number.isNaN(e)?"NaN":String(e)}`);if("boolean"===t)return void r(e?"t":"f");if("undefined"===t)return void r("u");if("object"!==t)return void r(`${t}:${String(e)}`);const i=e;if(n.has(i))r("[cycle]");else{if(n.add(i),Array.isArray(e)){r("[");for(const t of e)o(t);return r("]"),void n.delete(i)}r("{");for(const t of Object.keys(e).sort())r(t),o(e[t]);r("}"),n.delete(i)}};return o(e),`${(t>>>0).toString(16).padStart(8,"0")}${(i>>>0).toString(16).padStart(8,"0")}`}function dc(e){return hc(e)}const uc=new WeakMap;class pc{constructor(e,t=()=>Date.now()){this.onUpdate=e,this.now=t,this.fallbackAuthority={},this.referenceOwner={},this.referenced=new Set,this.queued=new Set,this.disposed=!1,this.sharedUpdate=()=>{this.disposed||this.onUpdate()}}bind(e){const t=((e,t)=>{const i=e?.connection||e?.callWS||t;return!i||"object"!=typeof i&&"function"!=typeof i?t:i})(e,this.fallbackAuthority);return this.shared&&this.authority===t||(this.shared&&(this.shared.listeners.delete(this.sharedUpdate),this.shared.references.delete(this.referenceOwner)),this.authority=t,this.shared=(e=>{let t=uc.get(e);return t||(t={signed:{},queued:new Set,inFlight:new Map,retry:new Map,listeners:new Set,settlers:new Set,references:new Map},uc.set(e,t)),t})(t),this.disposed||(this.shared.listeners.add(this.sharedUpdate),this.shared.references.set(this.referenceOwner,new Set(this.referenced)))),this.shared}start(e,t){this.disposed=!1,this.referenced=new Set(t());const i=this.bind(e());i.listeners.add(this.sharedUpdate),i.references.set(this.referenceOwner,new Set(this.referenced)),this.stopTimer(),this.resignTimer=setInterval(()=>this.resign(e(),t()),288e5)}dispose(){if(this.disposed=!0,this.stopTimer(),clearTimeout(this.batchTimer),this.shared){this.shared.listeners.delete(this.sharedUpdate),this.shared.references.delete(this.referenceOwner);for(const e of this.queued)this.shared.queued.delete(e)}this.queued.clear()}invalidate(e){const t=this.bind(e);clearTimeout(this.batchTimer),this.queued.clear(),t.queued.clear(),t.inFlight.clear(),t.retry.clear(),t.signed={}}stopTimer(){void 0!==this.resignTimer&&clearInterval(this.resignTimer),this.resignTimer=void 0}display(e,t){const i=En(t);if(!i.startsWith("/api/houseplan/content/"))return i;const n=this.bind(e);this.referenced.add(i),n.references.set(this.referenceOwner,new Set(this.referenced));const r=n.signed[i],o=r?this.now()-r.at:1/0;return o{const t=[...this.queued];this.queued.clear();for(const e of t)i.queued.delete(e);this.sign(e,t)},30))}sign(e,t){if(!t.length||!e?.callWS)return;const i=this.bind(e);for(const n of function(e,t){const i=Math.max(1,Math.floor(t)),n=[];for(let t=0;t{const n=i.inFlight.get(e);return!(void 0!==n&&t-n<15e3)&&(i.inFlight.set(e,t),!0)});r.length&&e.callWS({type:"houseplan/content/sign",paths:r}).then(e=>{const t=this.now();let n=0,o=!1;for(const s of r){const r=e?.urls?.[s];if("string"==typeof r&&r){const e=i.signed[s];e?.loaded&&e.url!==r?(e.pending={url:r,at:t},this.preloadReplacement(i,s,r,t)):(i.signed[s]={url:r,at:t,loaded:e?.url===r&&!!e.loaded},o=!0),i.retry.delete(s),n++}else this.backOff(i,s)}if(n&&(this.trimShared(i),o))for(const e of[...i.listeners])e()}).catch(()=>{for(const e of r)this.backOff(i,e)}).finally(()=>{for(const e of r)i.inFlight.get(e)===t&&i.inFlight.delete(e);for(const e of[...i.settlers])e()})}}preloadReplacement(e,t,i,n){const r=()=>{const r=e.signed[t];if(r?.pending?.url===i){e.signed[t]={url:i,at:n,loaded:!0},e.retry.delete(t),this.trimShared(e);for(const t of[...e.listeners])t()}},o=()=>{const n=e.signed[t];n?.pending?.url===i&&(delete n.pending,this.backOff(e,t))};if("undefined"==typeof Image)return void r();const s=new Image;s.onload=()=>{("function"==typeof s.decode?s.decode():Promise.resolve()).then(r).catch(o)},s.onerror=o,s.src=i}preloadCurrentImage(e,t,i){if(i.loaded)return Promise.resolve(!0);if(i.preload)return i.preload;if("undefined"==typeof Image)return i.loaded=!0,Promise.resolve(!0);const n=i.url;return i.preload=new Promise(r=>{const o=new Image;let s=!1;const a=o=>{if(s)return;s=!0,clearTimeout(l);const a=e.signed[t];if(a===i&&delete a.preload,o&&a===i&&a.url===n){a.loaded=!0;for(const t of[...e.listeners])t();r(!0)}else o||a!==i||this.backOff(e,t),r(!1)};o.onload=()=>{("function"==typeof o.decode?o.decode():Promise.resolve()).then(()=>a(!0)).catch(()=>a(!1))},o.onerror=()=>a(!1);const l=setTimeout(()=>a(!1),oc);o.src=n}),i.preload}prepareImage(e,t){const i=En(t);if(!i.startsWith("/api/houseplan/content/"))return Promise.resolve(!0);const n=this.bind(e),r=()=>{const t=n.signed[i];if(t&&this.now()-t.atthis.now()&&!n.inFlight.has(i)&&!n.queued.has(i)?Promise.resolve(!1):null},o=r();return o?(s=o,new Promise(e=>{let t=!1;const i=i=>{t||(t=!0,clearTimeout(n),e(i))},n=setTimeout(()=>i(!1),oc);s.then(i).catch(()=>i(!1))})):new Promise(e=>{let t=!1,i=null;const o=i=>{t||(t=!0,clearTimeout(a),n.settlers.delete(s),e(i))},s=()=>{t||i||(i=r(),i&&i.then(o).catch(()=>o(!1)))},a=setTimeout(()=>o(!1),oc);n.settlers.add(s),s()});var s}backOff(e,t){const i=e.retry.get(t)?.delay||0,n=Math.min(6e4,i?2*i:2e3);e.retry.set(t,{notBefore:this.now()+n,delay:n})}trimShared(e){const t=Object.entries(e.signed);if(t.length<=512)return;const i=new Set(e.inFlight.keys());for(const t of e.references.values())for(const e of t)i.add(e);for(const[e,n]of t)(n.pending||n.preload)&&i.add(e);t.sort((e,t)=>t[1].at-e[1].at);const n=t.filter(([e])=>i.has(e));for(const e of t){if(n.length>=512)break;i.has(e[0])||n.push(e)}e.signed=Object.fromEntries(n)}resign(e,t){const i=this.bind(e);this.referenced=new Set(t),i.references.set(this.referenceOwner,new Set(this.referenced));const n=this.now(),r=new Set;for(const e of i.references.values())for(const t of e)r.add(t);const o={};for(const[e,t]of Object.entries(i.signed))r.has(e)&&n-t.at!!o[e]&&!o[e].pending))}markLoaded(e,t,i){const n=En(t);if(!n.startsWith("/api/houseplan/content/"))return;const r=this.bind(e).signed[n];if(r&&(!i||r.url===i)&&!r.loaded){r.loaded=!0;for(const t of[...this.bind(e).listeners])t()}}isReady(e,t){const i=En(t);if(!i.startsWith("/api/houseplan/content/"))return!0;const n=this.bind(e).signed[i];return!!n&&this.now()-n.at=2&&(this._sequenceMultitouch=!0,this._postGestureClickBlocked=!0))}pointerTerminal(e,t){if("touch"!==t)return!1;const i=this._sequenceMultitouch;return this._activeTouchPointers.delete(e),0===this._activeTouchPointers.size&&(this._sequenceMultitouch=!1),i}reset(){this._activeTouchPointers.clear(),this._sequenceMultitouch=!1,this._postGestureClickBlocked=!1}}const mc=1e-7,gc=(e,t)=>{const i=e.x-t.x,n=e.y-t.y;return i*i+n*n};function fc(e){const t=Math.max(0,e.floorRadius);return{left:Math.min(e.painted.left,e.center.x-t),top:Math.min(e.painted.top,e.center.y-t),right:Math.max(e.painted.right,e.center.x+t),bottom:Math.max(e.painted.bottom,e.center.y+t)}}function vc(e,t){let i=null,n=Number.POSITIVE_INFINITY;for(const r of e){const e=gc(t,r.center);(efunction(e,t){const i=Math.max(0,t.right-t.left),n=Math.max(0,t.bottom-t.top);if(i<=0||n<=0)return!1;const r=Math.min(i,n)/2,o=Math.max(t.left+r,Math.min(t.right-r,e.x)),s=Math.max(t.top+r,Math.min(t.bottom-r,e.y));return gc(e,{x:o,y:s})<=r*r+mc}(t,e.painted));if(i.length)return vc(i,t);return vc(e.filter(e=>{const i=Math.max(0,e.floorRadius);return gc(t,e.center)<=i*i+mc}),t)}class bc{constructor(e,t=44){this.cellSize=t,this.buckets=new Map;const i=Number.isFinite(t)&&t>0?t:44;this.cellSize=i;for(const t of e){const e=fc(t),n=Math.floor(e.left/i),r=Math.floor(e.right/i),o=Math.floor(e.top/i),s=Math.floor(e.bottom/i);for(let e=n;e<=r;e++)for(let i=o;i<=s;i++){const n=`${e}:${i}`,r=this.buckets.get(n);r?r.push(t):this.buckets.set(n,[t])}}}resolve(e){const t=`${Math.floor(e.x/this.cellSize)}:${Math.floor(e.y/this.cellSize)}`;return yc(this.buckets.get(t)||[],e)}}class wc{constructor(){this.active=new Map,this.released=new Map}begin(e,t){this.released.delete(e),this.active.set(e,t)}owner(e){return this.active.get(e)||null}release(e){const t=this.active.get(e)||null;if(!t)return this.released.get(e)||null;for(this.active.delete(e),this.released.set(e,t);this.released.size>16;){const e=this.released.keys().next().value;if(void 0===e)break;this.released.delete(e)}return t}consumeClick(e){const t=this.released.get(e)||null;return this.released.delete(e),t}cancel(e){const t=this.active.get(e)||null;return this.active.delete(e),t}clear(){this.active.clear(),this.released.clear()}}class kc{constructor(){this.index=null,this.pointers=new wc,this.hoverId=null,this.hoverElement=null}invalidate(){this.index=null}reset(e){this.invalidate(),this.pointers.clear(),this.hover(e,null)}clearPointers(){this.pointers.clear()}cancel(e){return this.pointers.cancel(e)}release(e){return this.pointers.release(e)}indexFor(e){if(this.index)return this.index;const t=[];for(const i of e.querySelectorAll('.devlayer > .dev[data-hp="device"][data-id]')){const e=i.querySelector(".device-shell-frame"),n=i.getBoundingClientRect(),r=e?.getBoundingClientRect();!i.dataset.id||!i.isConnected||!r||n.width<=0||n.height<=0||r.width<=0||r.height<=0||t.push({id:i.dataset.id,center:{x:n.left+n.width/2,y:n.top+n.height/2},painted:{left:r.left,top:r.top,right:r.right,bottom:r.bottom},floorRadius:Math.max(22,Math.min(r.width,r.height)/2)})}return this.index=new bc(t),this.index}at(e,t,i,n,r){const o=this.indexFor(e).resolve({x:n,y:r})?.id;return o&&t.find(e=>e.id===o&&e.space===i)||null}byId(e,t,i){return i&&e.find(e=>e.id===i&&e.space===t)||null}begin(e,t,i,n,r){const o=this.at(e,t,i,n.clientX,n.clientY)||r;return this.pointers.begin(n.pointerId,o.id),o}pointer(e,t,i,n,r){const o=n.pointerId;return(Number.isFinite(o)?this.byId(t,i,this.pointers.owner(o)):null)||this.at(e,t,i,n.clientX,n.clientY)||r}click(e,t,i,n,r){if(!(n instanceof PointerEvent))return r;const o=n,s=Number.isFinite(o.pointerId)?this.pointers.consumeClick(o.pointerId):null;return this.byId(t,i,s)||this.at(e,t,i,o.clientX,o.clientY)||r}hover(e,t){this.hoverId===t&&this.hoverElement?.isConnected||(this.hoverElement?.removeAttribute("data-hp-device-hover"),this.hoverId=t,this.hoverElement=t&&[...e.querySelectorAll('.devlayer > .dev[data-hp="device"][data-id]')].find(e=>e.dataset.id===t)||null,this.hoverElement?.setAttribute("data-hp-device-hover",""))}}function xc(e,t){if(t)return e.find(e=>e.id===t)}function Sc(e,t){return{id:e,title:t,plan_url:null,view_box:[0,0,1,1],rooms:[],wall_segments:[]}}function $c(e="file"){const t="draw"===e;return{source:e,showBorders:t,showNames:t,displayTouched:!1}}function Mc(e,t){if(e.displayTouched)return{...e,source:t};const i="draw"===t;return{...e,source:t,showBorders:i,showNames:i}}function Rc(e,t,i){return{...e,[t]:i,displayTouched:!0}}function Cc(e){const t=String(e??"").trim().replace(",",".");if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(t))return null;const i=Number(t);return Number.isFinite(i)?i:null}function Tc(e,t){const i=e=>{if(""===String(e??"").trim())return{valid:!0,value:null};const t=Cc(e);return{valid:null!==t,value:t}},n=i(e),r=i(t);return n.valid&&r.valid?null!==n.value&&null!==r.value&&n.value>r.value?{valid:!0,min:r.value,max:n.value}:{valid:!0,min:n.value,max:r.value}:{valid:!1,min:n.value,max:r.value}}function Dc(e,t,i,n,r,o){const s=Tc(n,r);return dn(e,t,o&&s.valid?{settings:{...i.settings||{},temp_min:s.min,temp_max:s.max}}:i)}function Ac(e){const t=e=>"number"==typeof e&&Number.isFinite(e)?String(e):"";return[t(e?.temp_min),t(e?.temp_max)]}function Pc(e,t,i){const n=Tc(t,i);return!!n.valid&&(null===n.min?delete e.temp_min:e.temp_min=n.min,null===n.max?delete e.temp_max:e.temp_max=n.max,!0)}var Fc="M11,18H13V16H11V18M12,2A10,10 0 0,0 2,12A10,10 0 0,0 12,22A10,10 0 0,0 22,12A10,10 0 0,0 12,2M12,20C7.59,20 4,16.41 4,12C4,7.59 7.59,4 12,4C16.41,4 20,7.59 20,12C20,16.41 16.41,20 12,20M12,6A4,4 0 0,0 8,10H10A2,2 0 0,1 12,8A2,2 0 0,1 14,10C14,12 11,11.75 11,15H13C13,12.75 16,12.5 16,10A4,4 0 0,0 12,6Z";function zc(e,t,i){return[e[0]*t+e[1]*i+e[2],e[3]*t+e[4]*i+e[5]]}function Ic(e,t){let i=0;for(const[n,r]of t){const t=zc(e,n[0],n[1]);i=Math.max(i,Math.hypot(t[0]-r[0],t[1]-r[1]))}return i}const Oc=e=>{if(null==e||""===e)return null;const t=Number(e);return Number.isFinite(t)?t:null},Ec=e=>{const t=e,i=Oc(Array.isArray(t)?t[0]:t?.x),n=Oc(Array.isArray(t)?t[1]:t?.y);return null==i||null==n?null:[i,n]};function Nc(e){if(!Array.isArray(e))return null;const t=[];for(const i of e){const e=Ec(i);if(!e)return null;t.push(e)}if(t.length>1){const e=t[0],i=t[t.length-1];e[0]===i[0]&&e[1]===i[1]&&t.pop()}if(t.length<3)return null;let i=0,n=0,r=0;for(let e=0;ee+t[0],0)/t.length,t.reduce((e,t)=>e+t[1],0)/t.length]:[n/(3*i),r/(3*i)]}function Hc(e){if(!Array.isArray(e))return null;const t=[];for(const i of e){const e=Ec(i);if(!e)return null;t.push(e)}if(t.length>1){const e=t[0],i=t[t.length-1];e[0]===i[0]&&e[1]===i[1]&&t.pop()}const i=Nc(t);if(!i)return null;const n=t.map(e=>e[0]),r=t.map(e=>e[1]);return{centroid:i,bbox:[Math.min(...n),Math.min(...r),Math.max(...n),Math.max(...r)]}}function Lc(e){let t=e;if(t&&"object"==typeof t&&!Array.isArray(t)){const e=t;t=e.path??e.points??t}if(!Array.isArray(t)||!t.length)return[];let i=(t.some(e=>(e=>Array.isArray(e)?e.length>=2&&!Array.isArray(e[0])&&("object"!=typeof e[0]||null==e[0]):!!e&&"object"==typeof e&&("x"in e||"y"in e))(e))?[t]:t.filter(Array.isArray)).map(e=>e.map(Ec).filter(e=>null!=e)).filter(e=>e.length>=2);i.length>64&&(i=i.slice(-64));const n=i.reduce((e,t)=>e+t.length,0);if(n<=4e3)return i.map(e=>e.slice());const r=4e3-2*i.length,o=i.map(e=>e.length-2),s=o.reduce((e,t)=>e+t,0),a=o.map(e=>r*e/s),l=a.map(Math.floor);let c=r-l.reduce((e,t)=>e+t,0);const h=a.map((e,t)=>({index:t,fraction:e-Math.floor(e)})).sort((e,t)=>t.fraction-e.fraction||e.index-t.index);for(let e=0;efunction(e,t){if(t>=e.length)return e.slice();if(t<=2)return[e[0],e[e.length-1]];const i=[];for(let n=0;ne.slice()),i=t[t.length-1];return i?(i.length>2?i.pop():t.pop(),t):[]}const jc=e=>Number.isFinite(e[0])&&Number.isFinite(e[1]),Wc=(e,t)=>e[0]===t[0]&&e[1]===t[1];function Uc(e){if(!e)return null;const t=e.vacuum_position||e.robot_position||null,i=t&&null!=Oc(t.x)&&null!=Oc(t.y)?{x:Oc(t.x),y:Oc(t.y),a:Oc(t.a??t.angle??t.theta)}:null,n=Lc(e.path?.path??e.path?.points??e.path),r=[],o=e.rooms,s=Array.isArray(o)?o.map((e,t)=>[String(e?.id??t),e]):o&&"object"==typeof o?Object.entries(o):[];for(const[e,t]of s){if(!t||"object"!=typeof t)continue;const i=String(t.name??t.label??"").trim(),n=[[Oc(t.cx),Oc(t.cy)],[Oc(t.center?.x),Oc(t.center?.y)],[Oc(t.x),Oc(t.y)]].find(([e,t])=>null!=e&&null!=t);let o=n?.[0]??null,s=n?.[1]??null;const a=Hc(t.outline),l=Oc(t.x0),c=Oc(t.y0),h=Oc(t.x1),d=Oc(t.y1),u=(null!=l&&null!=c&&null!=h&&null!=d?[Math.min(l,h),Math.min(c,d),Math.max(l,h),Math.max(c,d)]:null)||a?.bbox||null;if(null!=o&&null!=s||!a||([o,s]=a.centroid),null!=o&&null!=s||!u||(o=(u[0]+u[2])/2,s=(u[1]+u[3])/2),i&&null!=o&&null!=s){const t={id:e,name:i,cx:o,cy:s};u&&([t.x0,t.y0,t.x1,t.y1]=u),r.push(t)}}const a=function(e){return String(e.map_name??e.current_map??e.map_index??e.selected_map??"default")}(e);return i||r.length||n.length?{pos:i,path:n,rooms:r,mapId:a}:null}function Gc(e,t,i){return![e,t,i].every(Number.isFinite)||e<0||t<=0||i<=0?Number.POSITIVE_INFINITY:e/t*i}const Vc=40;function Kc(e,t,i){if(!e||!t)return null;const n=t.attributes||{},r=e.split(".")[0]||"",o=null!=i?.platform?String(i.platform):null,s=!!Ec(n.vacuum_position??n.robot_position),a=!(!n.rooms||"object"!=typeof n.rooms),l=Lc(n.path?.path??n.path?.points??n.path).length>0,c=[n.map_name,n.current_map,n.map_index,n.selected_map].some(e=>null!=e),h="xiaomi_cloud_map_extractor"===o,d=a||l||c;let u=null;if(s?u="compatible":h?u="known_xcme_incomplete":d?u="partial":"camera"===r&&(u="camera"),!u)return null;const p=s?"camera"===r?300:200:h?100:d?50:0;return{entityId:e,name:String(n.friendly_name||e),platform:o,category:u,hasPosition:s,hasRooms:a,hasPath:l,hasMapId:c,score:p}}const Yc=e=>e.toLowerCase().replace(/[\s_\-.,]+/g,"");function Xc(e,t){const i=new Set(t.map(Yc).filter(Boolean)),n=new Set;for(const t of e){const e=Yc(t.name||"");e&&i.has(e)&&n.add(e)}return n.size}function Zc(e,t){const i=new Map(t.map(e=>[Yc(e.name),e])),n=[],r=[];for(const t of e){const e=i.get(Yc(t.name));e&&(n.push([[t.cx,t.cy],[e.cx,e.cy]]),r.push(t.name))}if(n.length<3)return null;const o=function(e){if(e.length<3)return null;let t=0,i=0,n=0,r=0,o=0,s=0,a=0,l=0,c=0,h=0,d=0,u=0;for(const[[p,_],[m,g]]of e){if(![p,_,m,g].every(Number.isFinite))return null;t+=p*p,i+=p*_,n+=p,r+=_*_,o+=_,s+=1,a+=p*m,l+=_*m,c+=m,h+=p*g,d+=_*g,u+=g}const p=[t,i,n,i,r,o,n,o,s],_=e=>{const[t,i,n,r,o,s,a,l,c]=p,h=t*(o*c-s*l)-i*(r*c-s*a)+n*(r*l-o*a);if(!Number.isFinite(h)||Math.abs(h)<1e-9)return null;const d=[(o*c-s*l)/h,(n*l-i*c)/h,(i*s-n*o)/h,(s*a-r*c)/h,(t*c-n*a)/h,(n*r-t*s)/h,(r*l-o*a)/h,(i*a-t*l)/h,(t*o-i*r)/h];return[d[0]*e[0]+d[1]*e[1]+d[2]*e[2],d[3]*e[0]+d[4]*e[1]+d[5]*e[2],d[6]*e[0]+d[7]*e[1]+d[8]*e[2]]},m=_([a,l,c]),g=_([h,d,u]);if(!m||!g)return null;const f=[m[0],m[1],m[2],g[0],g[1],g[2]];return f.every(Number.isFinite)?f:null}(n);return o?{matrix:o,matched:r,residual:Ic(o,n)}:null}function Jc(e,t,i){const n=e[e.length-1];if(n&&n[0]===t[0]&&n[1]===t[1])return e;if(e.push(t),e.length<=600)return e;let r=function(e,t){if(e.length<3)return e.slice();const i=new Uint8Array(e.length);i[0]=i[e.length-1]=1;const n=[[0,e.length-1]];for(;n.length;){const[r,o]=n.pop(),[s,a]=e[r],[l,c]=e[o],h=l-s,d=c-a,u=Math.hypot(h,d)||1e-9;let p=0,_=-1;for(let t=r+1;tp&&(p=i,_=t)}_>0&&p>t&&(i[_]=1,n.push([r,_],[_,o]))}const r=[];for(let t=0;t600&&(r=r.filter((e,t)=>t%2==0||t===r.length-1)),r}function Qc(e){return"cleaning"===e||"returning"===e||"on"===e}const eh={0:[1,0],90:[0,1],180:[-1,0],270:[0,-1]};function th(e){const[t,i]=eh[e.rot]||[1,0],n=e.mir?-1:1;return[e.s*t*n,-e.s*i,e.ox,e.s*i*n,e.s*t,e.oy]}function ih(e){const t=e[0]*e[4]-e[1]*e[3];if(!Number.isFinite(t)||Math.abs(t)<1e-12)return null;const i=t<0,n=Math.sqrt(Math.abs(t));let r=180*Math.atan2(-e[1],e[4])/Math.PI;return r=(90*Math.round(r/90)%360+360)%360,{ox:e[2],oy:e[5],s:n,rot:r,mir:i}}function nh(e,t){const i=[],n=[];for(const t of e)null!=t.x0?(i.push(t.x0,t.x1),n.push(t.y0,t.y1)):(i.push(t.cx),n.push(t.cy));if(!i.length)return{ox:t[0]+t[2]/2,oy:t[1]+t[3]/2,s:t[2]/1e4,rot:0,mir:!0};const r=Math.min(...i),o=Math.max(...i),s=Math.min(...n),a=Math.max(...n),l=Math.max(o-r,a-s)||1,c={ox:0,oy:0,s:.6*Math.min(t[2],t[3])/l,rot:0,mir:!0},h=th(c),[d,u]=zc(h,(r+o)/2,(s+a)/2);return c.ox=t[0]+t[2]/2-d,c.oy=t[1]+t[3]/2-u,c}function rh(e,t,i,n){const[r,o]=zc(th(t),i,n),s=th({...e,ox:0,oy:0}),[a,l]=zc(s,i,n);return{...e,ox:r-a,oy:o-l}}function oh(e){const t=e?.trail_mode;return"never"===t||"cleaning"===t||"always"===t?t:!1===e?.trail?"never":"cleaning"}const sh=e=>"number"==typeof e&&Number.isFinite(e);function ah(e){return Array.isArray(e)&&6===e.length&&e.every(sh)?[e[0],e[1],e[2],e[3],e[4],e[5]]:null}function lh(e,t,i){return"legacy:"+e+" "+t+" "+i}function ch(e,t,i,n){const r=t?.map_routes;if(Array.isArray(r))return r.filter(e=>e&&"string"==typeof e.id&&e.id).map(e=>({id:e.id,source:String(e.source??""),map_id:String(e.map_id??""),space:String(e.space??""),calibration:ah(e.calibration)}));const o="string"==typeof t?.source&&t.source?t.source:n||"";if(!o)return[];const s=t?.calibration;if(!s||"object"!=typeof s)return[];const a=[];for(const t of Object.keys(s)){const n=ah(s[t]);n&&a.push({id:lh(e,o,t),source:o,map_id:t,space:i,calibration:n})}return a}const hh=(e,t)=>e instanceof Map?e.get(t):e?.[t];function dh(e){const t=[];let i=!1,n="",r="";for(const o of e.routes){const s=hh(e.observed,o.source);void 0!==s&&(i=!0,n||(n=o.source,r=s),s===o.map_id&&t.push(o))}if(t.length>1)return{kind:"ambiguous",routeIds:t.map(e=>e.id).sort()};if(1===t.length){const i=t[0];if(e.spaceIds&&!e.spaceIds.has(i.space))return{kind:"missing_space",route:i};const n=ah(i.calibration);return n?{kind:"ready",route:{...i,calibration:n}}:{kind:"needs_calibration",route:i}}if(i)return{kind:"unmapped",source:n,mapId:r};const o=e.observed instanceof Map?[...e.observed.entries()]:Object.entries(e.observed||{});if(o.length){const e=o.slice().sort((e,t)=>e[0].localeCompare(t[0]))[0];return{kind:"unmapped",source:e[0],mapId:e[1]}}return{kind:"none"}}function uh(e,t,i){const n=new Set;for(const t of e)t.source&&n.add(t.source);for(const e of t)e&&n.add(e);const r={};for(const e of[...n].sort()){const t=i(e);void 0!==t&&(r[e]=t)}return r}function ph(e,t,i){if(!e)return null;const n="string"==typeof e.route_id?e.route_id:"";if(n)return t.find(e=>e.id===n)||null;const r=function(e,t,i){if(!e||"string"!=typeof e.map_id)return{kind:"orphan_run"};const n=e.map_id,r="string"==typeof i?i:"";let o=t.filter(e=>e.map_id===n);return r&&(o=o.filter(e=>e.source===r)),1===o.length?{kind:"adopted",route:o[0]}:0===o.length?{kind:"orphan_run"}:{kind:"ambiguous_run",routeIds:o.map(e=>e.id).sort()}}(e,t,i);return"adopted"===r.kind?r.route:null}function _h(e){const t="ready"===e.resolution.kind?e.resolution.route:null,i=t&&t.space===e.renderSpace?ah(t.calibration):null,n=ph(e.serverCurrent,e.routes,e.rootSource),r=!!t&&!!n&&n.id===t.id,o=ph(e.serverPrevious,e.routes,e.rootSource);return{live:i,currentRunMatches:r,previous:!!o&&o.space===e.renderSpace&&(e.explicitRoutes||!!t&&o.id===t.id)?ah(o.calibration):null}}const mh={availability:"available",status:"alarm",activity:"none"},gh=new Set(["motion","vibration","sound"]),fh=new Set(["occupancy","presence"]),vh=new Set(["door","window","garage_door","opening"]),yh=new Set(["running","power"]),bh=new Set(["smoke","gas","carbon_monoxide","moisture","safety","tamper","problem"]);const wh=new Set(["running","working","washing","rinsing","spinning","drying","heating","cooling","cleaning","cooking","playing","recording","pumping","irrigating","humidifying","dehumidifying","fan","preheating","defrosting"]),kh=new Set([...wh,"start","started","run","active","in_progress","wash","rinse","spin","dry"]),xh=new Set(["off","idle","paused","standby","docked","finished","complete","completed","stopped","ready","sleeping","stop","end","done","inactive"]),Sh=new Set(["heat","cool","heat_cool","auto","dry","fan_only"]),$h=e=>""===e||"unknown"===e||"unavailable"===e||"__missing__"===e,Mh=e=>String(e??"").trim().toLowerCase(),Rh=e=>Mh(e).replace(/[\s-]+/g,"_").replace(/_+/g,"_").replace(/^_|_$/g,""),Ch=new Map([["run_state",0],["job_state",0],["operation_state",0],["activity_state",0],["machine_state",1],["running_state",1],["status",2],["device_status",2],["machine_status",2]]),Th=new Set(["wifi","connection","signal","battery"]);function Dh(e,t){const i=e?.entities?.[t]||{};if("config"===i.entity_category)return null;const n=String(t||"").split(".").slice(1).join("."),r=[i.translation_key,i.original_name,i.name],o=[...r,n];r.some(e=>Mh(e))||o.push(e?.states?.[t]?.attributes?.friendly_name);const s=o.map(Rh).filter(Boolean);if(s.some(e=>e.split("_").some(e=>Th.has(e))))return null;let a=null;for(const e of s)for(const[t,i]of Ch)(e===t||e.endsWith(`_${t}`))&&(a=null==a?i:Math.min(a,i));return a}const Ah=(e,t)=>null!=Dh(e,t);function Ph(e,t){if(!t.startsWith("switch."))return!1;const i=e?.entities?.[t]||{},n=e?.states?.[t],r=t.slice(7).toLowerCase();if(/(?:^|_)(?:main_)?power$/.test(r))return!0;if([i.translation_key,i.original_name,i.name].map(Mh).some(e=>["power","main power","power switch","питание"].includes(e)))return!0;const o=Mh(n?.attributes?.friendly_name);return/(?:^|[\s._-])(?:main[\s._-]+)?power$/.test(o)||/(?:^|[\s._-])питание$/.test(o)}function Fh(e){for(const t of["hvac_action","action","current_operation","run_state","job_state","operation","activity"]){const i=Mh(e?.[t]);if(wh.has(i)||xh.has(i))return i}return""}function zh(e,t){const i=e?.states?.[t],n=i?Mh(i.state):"__missing__",r=String(t||"").split(".")[0],o=Mh(i?.attributes?.device_class),s={eid:t,state:n,availability:$h(n)?"unavailable":"available",status:"neutral",activity:"none",edge:"none"};if("unavailable"===s.availability)return s;if(function(e,t,i){return"alarm_control_panel"===e?"triggered"===i:"on"===i&&Vn(e,t)}(r,o,n))return{...s,status:"alarm"};if("binary_sensor"===r)return gh.has(o)?{...s,edge:"rising"}:fh.has(o)?{...s,activity:"on"===n?"presence":"none"}:vh.has(o)?{...s,status:"on"===n?"open":"neutral",edge:"rising"}:"moving"===o?{...s,activity:"on"===n?"transition":"none"}:yh.has(o)&&"on"===n?{...s,status:"working",activity:"running"}:s;if("cover"===r)return{...s,activity:"opening"===n||"closing"===n?"transition":"none",edge:"terminal_transition"};if("lock"===r)return{...s,status:"unlocked"===n||"open"===n?"open":"neutral",activity:"locking"===n||"unlocking"===n?"transition":"none",edge:"terminal_transition"};if("valve"===r)return{...s,status:["open","opening","closing"].includes(n)?"open":"neutral",activity:"opening"===n||"closing"===n?"transition":"none",edge:"terminal_transition"};if("climate"===r){const e=Fh(i.attributes),t=Array.isArray(i.attributes?.hvac_modes)?i.attributes.hvac_modes.map(Mh):[],r=!xh.has(n)&&(Sh.has(n)||wh.has(n)||t.includes(n));return(e?wh.has(e):r)?{...s,status:"working",activity:"running"}:s}if(["light","switch","fan","humidifier"].includes(r))return"on"===n?{...s,status:"working",activity:"running"}:s;if("media_player"===r)return"off"===n?{...s,availability:"unavailable"}:s;if("vacuum"===r)return"cleaning"===n?{...s,status:"working",activity:"running"}:"returning"===n?{...s,status:"working",activity:"transition"}:s;if("script"===r)return"on"===n?{...s,status:"working",activity:"running"}:s;if("automation"===r)return s;if("button"===r||"event"===r)return{...s,edge:"change"};const a=Fh(i.attributes);return wh.has(a)||wh.has(n)&&!xh.has(n)?{...s,status:"working",activity:"running"}:s}function Ih(e,t,i){const n=i.filter(t=>t.startsWith("switch.")&&!e?.entities?.[t]?.entity_category),r=t.find(t=>Ph(e,t));if(!(n.length>1&&!!r))return t.map(t=>zh(e,t));const o=t.find(t=>t!==r&&Ah(e,t)),s=zh(e,r);return"unavailable"===s.availability||"off"===s.state?t.map(t=>({eid:t,state:e?.states?.[t]?Mh(e.states[t].state):"__missing__",availability:"unavailable",status:"neutral",activity:"none",edge:"none"})):t.map(t=>{if(t===o)return function(e,t){const i=e?.states?.[t],n=i?Mh(i.state):"__missing__",r={eid:t,state:n,availability:$h(n)?"unavailable":"available",status:"neutral",activity:"none",edge:"none"};if("unavailable"===r.availability)return r;const o=Fh(i?.attributes);return wh.has(o)||kh.has(n)&&!xh.has(n)?{...r,status:"working",activity:"running"}:r}(e,t);return{...t===r?s:zh(e,t),status:"neutral",activity:"none",edge:"none"}})}function Oh(e){if(!e.length)return{availability:"available",status:"neutral",activity:"none"};const t=e.filter(e=>"available"===e.availability);if(!t.length)return{availability:"unavailable",status:"neutral",activity:"none"};if(t.some(e=>"alarm"===e.status))return mh;const i=t.some(e=>"working"===e.status)?"working":t.some(e=>"open"===e.status)?"open":"neutral",n=t.some(e=>"transition"===e.activity)?"transition":t.some(e=>"presence"===e.activity)?"presence":t.some(e=>"running"===e.activity)?"running":"none";return{availability:"available",status:i,activity:n}}function Eh(e,t){if(!(e=>!!e&&!$h(e))(e)||"unavailable"===t.availability||e===t.state)return null;if("rising"===t.edge)return"off"===e&&"on"===t.state?"event":null;if("change"===t.edge)return"event";if("terminal_transition"===t.edge){const i=new Set([e,t.state]);if(i.has("closed")&&i.has("open")||i.has("locked")&&i.has("unlocked"))return"transition"}return null}const Nh=(e,t=0)=>{const i=Number(e);return Number.isInteger(i)&&i>=0?i:t},Hh=(e,t)=>{const i={rev:0,configRev:Nh(t),off:new Set};if(null==e)return{snapshot:i,valid:!1};const n=e.off;return!Number.isInteger(e.rev)||Number(e.rev)<0||!Number.isInteger(e.config_rev)||Number(e.config_rev)<0||!Array.isArray(n)||n.some(e=>"string"!=typeof e||!e)?{snapshot:i,valid:!1}:{snapshot:{rev:Number(e.rev),configRev:Number(e.config_rev),off:new Set(n)},valid:!0}};function Lh(e,t=0){return Hh(e,t).snapshot}function Bh(e,t,i,n){const r=Hh(t,i);return n&&r.valid&&r.snapshot.configRev===i?e.configRev===i&&r.snapshot.rev{try{const[i,n]=await Promise.all([e.callWS({type:"config/device_registry/list"}),e.callWS({type:"config/entity_registry/list"})]),r=Jh(i,"id"),o=Jh(n,"entity_id");if(!r||!o)throw new Error("invalid_registry_response");t.devices=r,t.entities=o,t.authoritative=!0,t.access="full",t.lastSuccess=Date.now(),t.error=void 0}catch(e){t.authoritative=!1,t.access="limited",t.error=function(e){if(e&&"object"==typeof e){const t=e;return String(t.message||t.code||t.error||"registry_unavailable")}return String(e||"registry_unavailable")}(e)}finally{t.revision++,t.loading=void 0,function(e){for(const t of[...e.listeners])try{t()}catch{}}(t)}})()),t.loading}function ed(e,t){void 0===t.reloadTimer&&(t.reloadTimer=globalThis.setTimeout(()=>{t.reloadTimer=void 0,Qh(e,t)},80))}async function td(e,t){if(t.subscribing||t.unsubDevice&&t.unsubEntity)return t.subscribing;const i=e?.connection?.subscribeEvents;return"function"==typeof i?(t.subscribing=(async()=>{try{t.unsubDevice||(t.unsubDevice=await i.call(e.connection,()=>ed(e,t),"device_registry_updated")),t.unsubEntity||(t.unsubEntity=await i.call(e.connection,()=>ed(e,t),"entity_registry_updated"))}catch{}finally{0===t.refs&&(t.unsubDevice?.(),t.unsubEntity?.(),t.unsubDevice=void 0,t.unsubEntity=void 0),t.subscribing=void 0}})(),t.subscribing):void 0}function id(e,t){const i=Zh(e);if(!i)return()=>{};const n=0===i.refs;i.refs++,i.listeners.add(t),("pending"===i.access||n)&&Qh(e,i),td(e,i);let r=!1;return()=>{r||(r=!0,i.listeners.delete(t),i.refs=Math.max(0,i.refs-1),i.refs>0||(i.unsubDevice?.(),i.unsubEntity?.(),i.unsubDevice=void 0,i.unsubEntity=void 0,void 0!==i.reloadTimer&&globalThis.clearTimeout(i.reloadTimer),i.reloadTimer=void 0))}}function nd(e){const t=Zh(e);t&&(ed(e,t),td(e,t))}function rd(e){const t=Zh(e);if(!t)return{revision:0,authoritative:!1,access:"limited",devices:e?.devices||{},entities:e?.entities||{},lastSuccess:0,error:"registry_unavailable"};let i=e?.devices||{},n=e?.entities||{};if(t.authoritative){const r=t.liveDevices!==i||t.liveEntities!==n,o=void 0!==t.liveDevices||void 0!==t.liveEntities;if(r&&(t.liveDevices=i,t.liveEntities=n,t.projectedRevision=void 0,o&&ed(e,t)),t.projectedRevision!==t.revision||!t.projectedDevices||!t.projectedEntities){const e={...t.devices},r={...t.entities};for(const[t,n]of Object.entries(i))Object.prototype.hasOwnProperty.call(e,t)||(e[t]=n);for(const[e,t]of Object.entries(n))Object.prototype.hasOwnProperty.call(r,e)||(r[e]=t);t.projectedDevices=e,t.projectedEntities=r,t.projectedRevision=t.revision}i=t.projectedDevices,n=t.projectedEntities}return{revision:t.revision,authoritative:t.authoritative,access:t.access,devices:i,entities:n,lastSuccess:t.lastSuccess,error:t.error}}function od(e){if(!e||"object"!=typeof e&&"function"!=typeof e)return 0;let t=Vh.get(e);return t||(t=Kh++,Vh.set(e,t)),t}function sd(e,t=rd(e)){return[t.revision,t.access,od(t.devices),od(t.entities)].join(":")}function ad(e){return!!e&&null==e.disabled_by}function ld(e,t=rd(e)){const i={},n={},r={};for(const[e,n]of Object.entries(t.devices||{}))ad(n)&&(i[e]=n);for(const[e,i]of Object.entries(t.entities||{})){if(!ad(i))continue;const r=i.device_id?t.devices?.[i.device_id]:null;t.authoritative&&i.device_id&&!r||(r&&!ad(r)||(n[e]=i))}for(const[i,n]of Object.entries(e?.states||{})){const e=t.entities?.[i];if(e&&!ad(e))continue;const o=e?.device_id?t.devices?.[e.device_id]:null;t.authoritative&&e?.device_id&&!o||(o&&!ad(o)||(r[i]=n))}return{...e,devices:i,entities:n,states:r}}function cd(e,t=rd(e)){return{...e,devices:t.devices||{},entities:t.entities||{}}}function hd(e,t){const i=[];for(const[n,r]of Object.entries(e||{}))r?.device_id===t&&i.push(n);return i}function dd(){if(Xh)return Xh;if("undefined"==typeof localStorage)return{};try{const e=JSON.parse(localStorage.getItem(Yh)||"{}");if(!e||"object"!=typeof e||Array.isArray(e))return{};const t=Date.now(),i={};for(const[n,r]of Object.entries(e))!r||"active"!==r.kind&&"ha_disabled"!==r.kind||!Number.isFinite(r.ts)||t-r.ts>7776e6||(i[n]=r);return Xh=i,Xh}catch{return{}}}function ud(e,t,i=rd(e)){if(!t||"virtual"===t)return{kind:"active",enabledEntityIds:[],allEntityIds:[]};const n=t.indexOf(":");if(n<1)return{kind:"unverified",reason:"registry_unavailable",enabledEntityIds:[],allEntityIds:[]};const r=t.slice(0,n),o=t.slice(n+1);if("device"!==r&&"entity"!==r||!o)return{kind:"unverified",reason:"registry_unavailable",enabledEntityIds:[],allEntityIds:[]};const s=i.devices||{},a=i.entities||{};if(i.authoritative){if("device"===r){const e=s[o];if(!e)return{kind:"orphaned",reason:"device_missing",enabledEntityIds:[],allEntityIds:[]};const t=hd(a,o);if(!ad(e))return{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:t};const i=t.filter(e=>ad(a[e]));return t.length&&!i.length?{kind:"ha_disabled",reason:"all_entities",enabledEntityIds:[],allEntityIds:t}:{kind:"active",enabledEntityIds:i,allEntityIds:t}}const t=a[o];return t&&!ad(t)?{kind:"ha_disabled",reason:"entity",enabledEntityIds:[],allEntityIds:[o]}:t?.device_id&&!s[t.device_id]?{kind:"orphaned",reason:"device_missing",enabledEntityIds:[],allEntityIds:[o]}:t?.device_id&&!ad(s[t.device_id])?{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:[o]}:t||e?.states?.[o]?{kind:"active",enabledEntityIds:[o],allEntityIds:[o]}:{kind:"orphaned",reason:"entity_missing",enabledEntityIds:[],allEntityIds:[]}}const l=function(e){return dd()[e]||null}(t);if("device"===r){const t=s[o],i=hd(a,o);if(null!=t?.disabled_by)return{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:i};const n=i.filter(e=>{const t=a[e];return null==t?.disabled_by&&(!t.device_id||null==s[t.device_id]?.disabled_by)});if(i.length&&!n.length&&i.every(e=>null!=a[e]?.disabled_by))return{kind:"ha_disabled",reason:"all_entities",enabledEntityIds:[],allEntityIds:i};if("ha_disabled"===l?.kind)return{kind:"ha_disabled",reason:l.reason||"device",enabledEntityIds:[],allEntityIds:i};if(t||n.some(t=>!!e?.states?.[t]))return{kind:"active",enabledEntityIds:n,allEntityIds:i}}else{const t=a[o];if(null!=t?.disabled_by)return{kind:"ha_disabled",reason:"entity",enabledEntityIds:[],allEntityIds:[o]};if(t?.device_id&&null!=s[t.device_id]?.disabled_by)return{kind:"ha_disabled",reason:"device",enabledEntityIds:[],allEntityIds:[o]};if("ha_disabled"===l?.kind)return{kind:"ha_disabled",reason:l.reason||"entity",enabledEntityIds:[],allEntityIds:[o]};if(t||e?.states?.[o])return{kind:"active",enabledEntityIds:[o],allEntityIds:[o]}}return{kind:"unverified",reason:"registry_unavailable",enabledEntityIds:[],allEntityIds:[]}}function pd(e){const t=rd(e);return{access:t.access,authoritative:t.authoritative,revision:t.revision,lastSuccess:t.lastSuccess,error:t.error}}function _d(e){const t={};for(const[i,n]of Object.entries(e.entities)){if(!n?.device_id||!ad(n))continue;const r=e.devices?.[n.device_id];r&&!ad(r)||(t[n.device_id]=t[n.device_id]||[]).push(i)}return t}function md(e,t){const i=new Map;for(const n of e){if(!0===n?.removed)continue;const e=n?.binding||"";if(!e.startsWith("entity:"))continue;const r=e.slice(7);if(!r)continue;const o=t?.entities?.[r]?.device_id;if(!o)continue;const s=i.get(o)||new Set;s.add(r),i.set(o,s)}return{byDevice:i}}function gd(e,t,i,n){const r=n.byDevice.get(t);return r?.size?{partial:!0,entityIds:i.filter(t=>!r.has(t)&&!e?.entities?.[t]?.hidden)}:{partial:!1,entityIds:[...i]}}function fd(e,t,i){if(t.identifiers?.[0]?.[0])return t.identifiers[0][0];for(const t of i){const i=e.entities[t]?.platform;if(i)return i}return""}function vd(e,t){if(/_device_temperature$/.test(t))return!1;if(e.entities?.[t]?.entity_category)return!1;const i=e.states[t];if(!i)return/_temperature$/.test(t);const n=i.attributes||{};return"temperature"===n.device_class||/°C|°F/.test(n.unit_of_measurement||"")||/_temperature$/.test(t)}const yd=["vacuum","lawn_mower","climate","media_player","light","cover","lock","valve","alarm_control_panel","water_heater","fan","humidifier","siren","camera","remote"],bd=e=>[...e.filter(e=>!e.reg?.hidden),...e.filter(e=>!!e.reg?.hidden)];function wd(e,t){const i=t.map(t=>({eid:t,reg:e?.entities?.[t]})).filter(e=>!!e.reg);if(!i.length)return[];const n=i.filter(e=>!e.reg.entity_category),r=n.length?n:i;for(const e of yd){const t=r.filter(t=>t.eid.startsWith(e+"."));if(t.length)return bd(t).map(e=>e.eid)}const o=r.filter(t=>function(e,t){if(!t.startsWith("binary_sensor."))return!1;const i=Mh(e?.states?.[t]?.attributes?.device_class||e?.entities?.[t]?.device_class||e?.entities?.[t]?.original_device_class);return gh.has(i)||fh.has(i)||vh.has(i)||yh.has(i)||"moving"===i||bh.has(i)}(e,t.eid));if(o.length)return bd(o).map(e=>e.eid);const s=r.filter(e=>e.eid.startsWith("switch."));if(s.length){const t=bd(s),n=t.find(t=>Ph(e,t.eid));if(s.length>1&&n){const t=i.filter(t=>t.eid!==n.eid&&"config"!==t.reg?.entity_category&&null!=Dh(e,t.eid)),r=t.filter(e=>!e.reg?.entity_category),o=r.length?r:t;for(const t of[0,1,2]){const i=bd(o.filter(i=>Dh(e,i.eid)===t));if(i.length)return[i[0].eid,n.eid]}}return[(n||t[0]).eid]}const a=[];for(const e of je)a.push(...bd(r.filter(t=>t.eid.startsWith(e+"."))));return a.push(...bd(r.filter(e=>!je.includes(e.eid.split(".")[0])))),a.map(e=>e.eid)}function kd(e,t,i){const n=t.map(t=>({eid:t,reg:e.entities[t],st:e.states[t]})).filter(e=>e.reg),r=[n.filter(e=>!e.reg.hidden&&!e.reg.entity_category),n.filter(e=>!e.reg.entity_category),n.filter(e=>!e.reg.hidden),n];if("mdi:thermometer"===i||"mdi:air-filter"===i)for(const t of r){const i=t.find(t=>vd(e,t.eid));if(i)return i.eid}const o=wd(e,t);return o.find(Dn)||o[0]}function xd(e,t,i=[]){return[...new Set(Sd(e,t,i))].filter(e=>Dn(e))}function Sd(e,t,i=[]){const n=e?.startsWith("entity:")?new Set([e.slice(7)]):new Set(i);return(t||[]).filter(e=>"string"==typeof e&&!n.has(e))}function $d(e,t){if("string"==typeof t)return e.area===t;const i=e.marker?.room_id;return i?!!t.id&&i===t.id:!!t.area&&e.area===t.area}function Md(e){const t=e.marker?.binding?.startsWith("entity:")?e.marker.binding.slice(7):null,i=e.entities.filter(Dn),n=e.primary&&Dn(e.primary)?e.primary:null;return[...new Set([t,n,...i].filter(e=>!!e&&Dn(e)))]}function Rd(e){const t=Md(e),i=e.marker?.light_entity;return i&&t.includes(i)?i:t[0]||null}function Cd(e,t){if(!1===t.marker?.is_light)return[];if(!0===t.marker?.is_light){return[{eid:Rd(t),via:"forced"}]}const i=t.primary||wd(e,t.entities)[0];return i&&!i.startsWith("light.")?[]:t.entities.filter(t=>t.startsWith("light.")&&!!e.states?.[t]).map(e=>({eid:e,via:"light"}))}const Td=new WeakMap,Dd=new WeakMap;function Ad(e){return e.map(e=>[e.id||"",!0===e.hidden?1:0,e.primary||"",[...e.entities].join(","),void 0===e.controls?"":[...e.controls].join(","),e.marker?.id||"",e.marker?.binding||"",e.marker?.is_light,e.marker?.tap_action||"",!0===e.marker?.removed?1:0,e.marker?.light_entity||"",null==e.marker?.controls?"":[...e.marker.controls].join(",")].join("")).join("")}function Pd(e){const t=Ad(e),i=Td.get(e);if(i?.fingerprint===t)return i;const n=e.filter(e=>!e.hidden),r=new Map,o=new Map;for(const t of e){o.set(t,Sd(t.marker?.binding,t.marker?.controls??t.controls,t.entities));const e=t.hidden||!0!==t.marker?.is_light?null:t.marker?.id||t.id;e&&r.set(String(e),t)}const s=new Map;for(const t of e){const e=o.get(t)||[],i=new Set(void 0===t.controls?e.filter(Dn):t.controls.filter(Dn)),n=Rd(t),a=i.size?[...i]:n?[n]:[];for(const i of e){if(!i.startsWith("marker:"))continue;const e=i.slice(7);if(!e||e===String(t.marker?.id||t.id||""))continue;if(!r.has(e))continue;const n=s.get(e)||{markerId:e,controllers:[],driverEids:[]};n.controllers.push({device:t,driverEids:[...a]}),n.driverEids=[...new Set([...n.driverEids,...a])],s.set(e,n)}}const a={fingerprint:t,visible:n,markerById:r,persistedByDevice:o,incomingByMarker:s};return Td.set(e,a),a}function Fd(e){return Pd(e).incomingByMarker}function zd(e,t){const i=xd(t.marker?.binding,t.controls??t.marker?.controls,t.entities),n=Sd(t.marker?.binding,t.marker?.controls??t.controls,t.entities);return(null!=t.marker?.is_light||!i.length&&!n.some(e=>e.startsWith("marker:")))&&Cd(e,t).length>0}function Id(e,t){return Cd(e,t).some(e=>!!e.eid)}function Od(e,t,i,n){const r="always"===e||"auto"===e&&t,o=r&&!i;return{sourceExists:r,fromSourceEnabled:r&&i,manualEnabled:r,radiusEnabled:r,passive:o,effectiveMode:o&&"auto"===n?"fixed":n}}function Ed(e,t){const i=xd(t.marker?.binding,t.controls??t.marker?.controls,t.entities).map(e=>({eid:e,via:"controls"})),n=zd(e,t)?Cd(e,t):[];for(const e of n)e.eid&&i.some(t=>t.eid===e.eid)||i.push(e);return i}function Nd(e,t,i,n){if(null!=i)return Nd(e,t,null,n).filter(e=>$d(e.device,i));const r=Ad(t),o=function(e,t){const i=new Set;for(const e of t){for(const t of e.entities)i.add(t);for(const t of e.controls||e.marker?.controls||[])"string"!=typeof t||t.startsWith("marker:")||i.add(t)}return[...i].sort().map(t=>`${t}:${e?.states?.[t]?.state??""}`).join("|")}(e,t),s=qh(n),a=Dd.get(t);if(a?.graphFingerprint===r&&a.stateFingerprint===o&&a.virtualLightFingerprint===s&&a.registry===e?.entities)return a.sources;const{visible:l,markerById:c,persistedByDevice:h,incomingByMarker:d}=Pd(t),u=null==i?l:l.filter(e=>$d(e,i)),p=new Map,_=new Map;for(const t of u){const i=Ed(e,t).filter(e=>"controls"!==e.via);for(const n of i){const i=!0===t.marker?.is_light?String(t.marker?.id||t.id||""):"",r=i?`marker:${i}`:`entity:${n.eid}`,o=n.eid?[n.eid]:[],s={key:r,eid:n.eid||"",stateEids:o,serviceEids:o,device:t,via:n.via,castsGlow:!0,passive:!n.eid,on:!n.eid||"on"===e.states?.[n.eid]?.state};p.set(t,[...p.get(t)||[],s]),n.eid&&_.set(n.eid,s)}}const m=new Map;for(const e of t){const t=h.get(e)||[],i=new Set(void 0===e.controls?t.filter(Dn):e.controls);m.set(e,i)}for(const t of p.values())for(const i of t){if(!i.passive)continue;const t=i.key.slice(7),r=d.get(t);i.on=!r||r.driverEids.some(t=>"on"===e.states?.[t]?.state),!r&&jh(i.device.marker)&&(i.on=Wh(i.device.marker,n))}const g=new Map,f=e=>{const t=g.get(e.key);(!t||e.castsGlow&&!t.castsGlow)&&g.set(e.key,e)};for(const t of l){const n=h.get(t)||[],r=null==i||$d(t,i);for(const i of n){if(i.startsWith("marker:")){const e=c.get(i.slice(7)),t=e?p.get(e):null;if(t)for(const e of t)f(e);continue}if(!Dn(i)||!m.get(t)?.has(i))continue;const n=_.get(i);n?f(n):r&&f({key:`entity:${i}`,eid:i,stateEids:[i],serviceEids:[i],device:t,via:"controls",castsGlow:!1,passive:!1,on:"on"===e.states?.[i]?.state})}for(const e of p.get(t)||[])f(e)}const v=[...g.values()];return Dd.set(t,{graphFingerprint:r,stateFingerprint:o,virtualLightFingerprint:s,registry:e?.entities,sources:v}),v}function Hd(e){const t=e.filter(e=>e.castsGlow);return t.find(e=>e.on)||t[0]||null}function Ld(e){return e.length?e.some(e=>e.on)?"on":"off":"none"}function Bd(e,t){const i=[];for(const n of t){const t=e.states[n];if(!t)continue;const r=(t.attributes?.unit_of_measurement||"").toLowerCase();if(/_(linkquality|lqi)$/.test(n)||"lqi"===r){const e=parseFloat(t.state);isNaN(e)||i.push(e);continue}const o=t.attributes?.linkquality??t.attributes?.lqi;if(null!=o){const e=parseFloat(o);isNaN(e)||i.push(e)}}return Ii(i)}function qd(e,t){for(const i of t){if(!vd(e,i))continue;const t=e.states[i];if(!t)continue;const n=parseFloat(t.state);if(!isNaN(n))return Math.round(10*n)/10}return null}function jd(e,t){for(const i of t){if(!i.startsWith("climate."))continue;const t=e.states[i];if(!t||"unavailable"===t.state||"unknown"===t.state)continue;const n=parseFloat(t.attributes?.current_temperature);if(Number.isFinite(n))return Math.round(10*n)/10}return null}function Wd(e,t){if(e.entities?.[t]?.entity_category)return!1;const i=e.states[t];if(!i)return/_humidity$/.test(t);const n=i.attributes||{};return"humidity"===n.device_class||"%"===n.unit_of_measurement&&/_humidity$/.test(t)||/_humidity$/.test(t)}function Ud(e,t){for(const i of t){if(!Wd(e,i))continue;const t=e.states[i];if(!t)continue;const n=parseFloat(t.state);if(!isNaN(n))return Math.round(n)}return null}function Gd(e,t){if(!t)return[];const i=[];for(const[t,n]of Object.entries(e.entities)){if(!t.startsWith("light.")||n.hidden||!ad(n))continue;let r=null;if("group"===n.platform)r=n.area_id||null;else{if(!n.device_id)continue;{const t=e.devices[n.device_id];if(!ad(t))continue;if("Group"!==t?.model)continue;r=t.area_id||n.area_id||null}}if(!r)continue;const o=e.states[t];i.push({eid:t,name:n.name||o?.attributes?.friendly_name||t,area:r})}return i}function Vd(e,t,i,n,r){const o=qe(t,i,r);if(o!==Be)return o;const s=[];for(const t of n){const i=e.states[t]?.attributes?.device_class;i&&s.push(i)}return function(e){for(const t of e){const e=Le[t];if(e)return e}return null}(s)??Be}function Kd(e,t){return e.map(e=>{if(!Array.isArray(e.controls))return e;const i=e.controls.filter(e=>!("string"==typeof e&&e.startsWith("marker:")&&t.has(e.slice(7))));return i.length===e.controls.length?e:{...e,controls:i.length?i:null}})}function Yd(e,t,i){if(!t||!i||t===i)return[...e];const n=`marker:${t}`,r=`marker:${i}`;return e.map(e=>{const t=Array.isArray(e.controls)?e.controls.map(e=>e===n?r:e):e.controls,i="derived_marker_state"===e.value_badge?.source?.kind&&e.value_badge.source.ref===n?{...e.value_badge,source:{...e.value_badge.source,ref:r}}:e.value_badge,o="derived_marker_state"===e.value_source?.kind&&e.value_source.ref===n?{...e.value_source,ref:r}:e.value_source;return t===e.controls&&i===e.value_badge&&o===e.value_source?e:{...e,controls:t,...void 0!==i?{value_badge:i}:{},...void 0!==o?{value_source:o}:{}}})}function Xd(e,t,i){if(!t||t===i)return!0;const n=new Map;for(const t of e)n.set(t.id,(t.controls||[]).filter(e=>"string"==typeof e&&e.startsWith("marker:")).map(e=>e.slice(7)));const r=new Set,o=[i];for(;o.length;){const e=o.pop();if(e===t)return!0;r.has(e)||(r.add(e),o.push(...n.get(e)||[]))}return!1}function Zd(e,t,i,n){const r=new Set([t]),o=e.filter(e=>{const o=e.id===t||!n&&e.binding===i;return o&&r.add(e.id),!o});return{markers:n?o:[...o,{id:t,binding:i,removed:!0,hidden:!0}],cleanupIds:r}}function Jd(e){const t=new Set,i=new Set,n=new Set;for(const r of e||[]){const e=String(r.binding||"").indexOf(":");if(e<1)continue;const o=r.binding.slice(0,e),s=r.binding.slice(e+1);s&&(!0===r?.removed?"device"===o?t.add(s):"entity"===o&&i.add(s):"entity"===o&&n.add(s))}return{devices:t,entities:i,liveEntities:n}}function Qd(e,t,i){if(i.liveEntities.has(t))return!1;if(i.entities.has(t))return!0;const n=e?.entities?.[t]?.device_id;return!!n&&i.devices.has(n)}function eu(e,t,i,n,r){const o=xd(t.binding,t.controls,e.entities).filter(e=>!Qd(i,e,n)).filter(e=>"active"===ud(i,"entity:"+e,r).kind);e.marker=t,e.controls=o,e.userHidden=!0===t.hidden,e.hidden=e.userHidden||"ha_disabled"===e.bindingStatus?.kind,t.name&&(e.name=t.name),t.icon&&(e.icon=t.icon),null!=t.model&&(e.model=t.model),e.link=t.link??null,e.description=t.description??null,e.pdfs=t.pdfs||[],e.tapAction=t.tap_action??null}function tu(e){const t=e.hass,i=e.registry||rd(t),n=ld(t,i),r=cd(t,i),{areaToSpace:o,markers:s,settings:a,excluded:l,iconRules:c}=e,h=!1!==a.group_lights,d=Jd(s),u=Gd(n,h).filter(e=>!Qd(n,e.eid,d)),p=new Set(u.map(e=>e.area)),_=_d(n),m=md(s,r),g=new Set(s.map(e=>e.binding)),f=[];for(const e of Object.values(n.devices)){const r=e.area_id;if(!r||!o[r])continue;if("service"===e.entry_type)continue;if(g.has("device:"+e.id))continue;if("active"!==ud(t,"device:"+e.id,i).kind)continue;const s=gd(n,e.id,_[e.id]||[],m);if(s.partial&&!s.entityIds.length)continue;const a=s.entityIds,d=fd(n,e,a);let u=l.has(d)||"Group"===e.model||/scene/i.test(e.model||"")||/bridge/i.test((e.model||"")+(e.name||""))||"myheat"===d&&!!e.via_device_id;if(!u&&h&&p.has(r)){const t=(e.name_by_user||e.name||"").trim();"mdi:lightbulb"===Vd(n,t,e.model,a,c)&&(u=!0)}u&&f.push("device:"+e.id)}return f}function iu(e,t,i,n){if("string"==typeof e.room_id&&e.room_id.length>0&&null===e.area)return{area:"",space:e.space||n};const r=e.area||t||"";return{area:r,space:r&&i[r]||e.space||n}}function nu(e){const t=e.hass,i=e.registry||rd(t),n=ld(t,i),r=cd(t,i),{areaToSpace:o,markers:s,settings:a,excluded:l,showAll:c,firstSpaceId:h,loc:d,iconRules:u}=e,p=!1!==a.group_lights,_=Jd(s),m=Gd(n,p).filter(e=>!Qd(n,e.eid,_)),g=new Set(m.map(e=>e.area)),f=_d(n),v=function(e){const t={};for(const[i,n]of Object.entries(e.entities||{}))n?.device_id&&(t[n.device_id]=t[n.device_id]||[]).push(i);return t}(r),y=md(s,r),b=new Set;for(const e of s){const[t,i]=e.binding.split(":");"device"!==t&&"entity"!==t||!i||b.add(e.binding)}const w=(e,t)=>s.find(i=>i.binding===e+":"+t),k={},x=[];for(const e of Object.values(n.devices)){const r=e.area_id;if(!r||!o[r])continue;if("service"===e.entry_type)continue;if(b.has("device:"+e.id))continue;const s=ud(t,"device:"+e.id,i);if("active"!==s.kind)continue;const h=w("device",e.id);if(h&&h.hidden&&!a.filter_seeded)continue;const _=gd(n,e.id,f[e.id]||[],y);if(_.partial&&!_.entityIds.length)continue;const m=_.entityIds,v=_.partial?{kind:"active",enabledEntityIds:m,allEntityIds:m}:s,S=fd(n,e,m),$=!a.filter_seeded;if($&&!c){if(l.has(S))continue;if("Group"===e.model)continue;if(/scene/i.test(e.model||""))continue;if(/bridge/i.test((e.model||"")+(e.name||"")))continue;if("myheat"===S&&e.via_device_id)continue}const M=(e.name_by_user||e.name||d("device.unnamed")).trim(),R=M+"|"+r;let C=Vd(n,M,e.model,m,u);if(m.some(e=>e.startsWith("lock."))&&(C="mdi:lock"),$&&!c&&p&&"mdi:lightbulb"===C&&g.has(r))continue;k[R]=(k[R]||0)+1;const T=k[R]>1?M+" "+k[R]:M,D={id:e.id,name:T,model:e.model||"",area:r,space:o[r],icon:C,entities:m,allEntities:v.allEntityIds,bindingStatus:v,bindingKind:"device",bindingRef:e.id,pdfs:[]};D.primary=kd(n,m,C),"mdi:thermometer"!==C&&"mdi:air-filter"!==C||(D.temp=qd(n,m)),D.primary&&Wd(n,D.primary)&&(D.hum=Ud(n,m)),x.push(D)}for(const e of m)o[e.area]&&(b.has("entity:"+e.eid)||x.push({id:"lg_"+e.eid,name:e.name,model:d("device.light_group"),area:e.area,space:o[e.area],icon:"mdi:lightbulb-group",entities:[e.eid],allEntities:[e.eid],bindingStatus:{kind:"active",enabledEntityIds:[e.eid],allEntityIds:[e.eid]},primary:e.eid,bindingKind:"entity",bindingRef:e.eid,pdfs:[]}));for(const e of s){if(e.removed)continue;const[s,l]=e.binding.split(":"),c="device"===s||"entity"===s?ud(t,e.binding,i):null;if(!e.hidden||a.filter_seeded||"ha_disabled"===c?.kind)if("device"===s){const t=c;if("unverified"===t.kind)continue;const s=r.devices[l],{area:a,space:p}=iu(e,s?.area_id,o,h),m="active"===t.kind?t.enabledEntityIds:[];let g=s?Vd(n,s.name_by_user||s.name||"",s.model,m,u):"mdi:help-circle";m.some(e=>e.startsWith("lock."))&&(g="mdi:lock");const f={id:e.id,name:s?.name_by_user||s?.name||d("device.fallback"),model:s?.model||"",area:a,space:p,icon:g,entities:m,allEntities:t.allEntityIds.length?t.allEntityIds:s&&v[s.id]||[],bindingStatus:t,bindingKind:"device",bindingRef:l};f.primary=kd(n,m,g),"mdi:thermometer"!==g&&"mdi:air-filter"!==g||(f.temp=qd(n,m)),f.primary&&Wd(n,f.primary)&&(f.hum=Ud(n,m)),eu(f,e,r,_,i),x.push(f)}else if("entity"===s){if(Qd(r,l,_))continue;const t=c;if("unverified"===t.kind)continue;const s=r.entities[l],a=s?.area_id||s?.device_id&&r.devices[s.device_id]?.area_id||"",{area:d,space:p}=iu(e,a,o,h),m=n.states[l],g=s?.name||m?.attributes?.friendly_name||l;let f=Vd(n,g,"",[l],u);l.startsWith("lock.")&&(f="mdi:lock");const v={id:e.id,name:g,model:"",area:d,space:p,icon:f,entities:"active"===t.kind?[l]:[],allEntities:[l],bindingStatus:t,primary:"active"===t.kind?l:void 0,bindingKind:"entity",bindingRef:l};"mdi:thermometer"!==f&&"mdi:air-filter"!==f||!v.entities.length||(v.temp=qd(n,v.entities)),v.entities.length&&Wd(n,l)&&(v.hum=Ud(n,v.entities)),eu(v,e,r,_,i),x.push(v)}else{const t=e.area||"",n=e.space||t&&o[t]||h,s={id:e.id,name:e.name||d("device.virtual"),model:e.model||"",area:t,space:n,icon:e.icon||"mdi:map-marker",entities:[],allEntities:[],bindingStatus:{kind:"active",enabledEntityIds:[],allEntityIds:[]},bindingKind:"virtual",virtual:!0};eu(s,e,r,_,i),x.push(s)}}return x}function ru(e){const{marker:t,siblingMarkers:i=[],...n}=e;return nu({...n,markers:[...i.filter(e=>e.id!==t.id),t]}).find(e=>e.id===t.id)||null}function ou(e,t,i,n){if(!t)return null;if(function(e,t,i){if(!t)return!1;const n=t.indexOf(":");if(n<1)return!1;const r=t.slice(0,n),o=t.slice(n+1),s=Jd(i);return"device"===r?s.devices.has(o):"entity"===r&&Qd(e,o,s)}(e,t,n))return null;const r=t.indexOf(":");if(r<0)return null;const o=t.slice(0,r),s=t.slice(r+1);if(!s)return null;if("entity"===o){const t=parseFloat(e.states[s]?.state);return Number.isFinite(t)?"temp"===i?Math.round(10*t)/10:Math.round(t):null}if("device"===o){const t=Object.entries(e.entities).filter(([,e])=>e.device_id===s).map(([e])=>e);return"temp"===i?qd(e,t):Ud(e,t)}return null}const su=new RegExp(["water","voda","coolant","flow_?temp","return_?temp","target","setpoint","chip","cpu","processor","board","core_temp","device_temp","batter","akkum","freezer","fridge","oven","kettle","boiler"].join("|"),"i");function au(e,t){return t.area?t.area:e&&t.id?`@room/${encodeURIComponent(e)}/${encodeURIComponent(t.id)}`:null}function lu(e){return null==e.area&&e.space&&e.room_id?au(e.space,{id:e.room_id,area:null}):e.area||null}function cu(e){const t=e?.exclude_integrations;return t?new Set(t):Ie}function hu(e,t,i,n=Ie){const r=new Map;if(!e?.entities)return r;const o=Jd(i),s=new Set,a=new Map,l=new Map;for(const e of i||[]){if(e?.removed)continue;const t=(e.binding||"").indexOf(":");if(t<=0)continue;const i=e.binding.slice(0,t),n=e.binding.slice(t+1);if(!n)continue;!0===e.use_climate_temp&&s.add(n);const r=lu(e);r&&("entity"!==i||a.has(n)?"device"!==i||l.has(n)||l.set(n,r):a.set(n,r))}const c=new Map;for(const[t,i]of Object.entries(e.entities)){if(i.device_id&&o.devices.has(i.device_id)&&!o.liveEntities.has(t)||!i.device_id&&o.entities.has(t)&&!o.liveEntities.has(t))continue;const r=i.device_id?e.devices?.[i.device_id]:null;if(!ad(i)||r&&!ad(r))continue;const h=a.get(t)||(i.device_id?l.get(i.device_id):null)||i.area_id||r?.area_id||null;if(!h)continue;if(i.entity_category)continue;if(!(s.size>0&&t.startsWith("climate.")&&(s.has(t)||i.device_id&&s.has(i.device_id)))){if(n.has(i.platform))continue;if(su.test(t))continue}let d=c.get(h);d||(d=new Map,c.set(h,d));const u=i.device_id||t;let p=d.get(u);if(!p){const n=e.states?.[t];p={name:(r?r.name_by_user||r.name:i.name||n?.attributes?.friendly_name||t)||t,model:r?.model,ents:[]},d.set(u,p)}p.ents.push(t)}for(const[i,n]of c){const o=[],a=[];for(const[i,r]of n){const n=Vd(e,r.name,r.model,r.ents,t),l="mdi:thermometer"===n||"mdi:air-filter"===n;if(l){const t=qd(e,r.ents);null!=t&&o.push(t)}if(s.size>0&&(s.has(i)||r.ents.some(e=>s.has(e)))){const t=jd(e,r.ents);null!=t&&o.push(t)}if(l||"mdi:water-percent"===n){const t=Ud(e,r.ents);null!=t&&a.push(t)}}(o.length||a.length)&&r.set(i,{temp:o.length?Math.round(o.reduce((e,t)=>e+t,0)/o.length*10)/10:null,hum:a.length?Math.round(a.reduce((e,t)=>e+t,0)/a.length):null})}return r}function du(e,t,i){const n=[];for(const r of t){if(r.area!==i||r.virtual)continue;const t=Bd(e,r.entities);null!=t&&n.push(t)}return Ii(n)}const uu={offStates:["off"],unknownUsesToggle:!0},pu={light:uu,switch:uu,fan:uu,humidifier:uu,input_boolean:uu,automation:uu,remote:uu,group:uu,climate:{...uu,featureMasks:{turn_on:256,turn_off:128,toggle:384}},media_player:{...uu,featureMasks:{turn_on:128,turn_off:256,toggle:384}},siren:{...uu,featureMasks:{turn_on:1,turn_off:2,toggle:3}},vacuum:{...uu,featureMasks:{turn_on:1,turn_off:2,toggle:3}},water_heater:{...uu,featureMasks:{turn_on:8,turn_off:8,toggle:8}},camera:{...uu,featureMasks:{turn_on:1,turn_off:1,toggle:1}}};function _u(e){return e.slice(0,e.indexOf("."))}function mu(e,t,i){if(!e?.services||"object"!=typeof e.services)return!1;const n=e.services?.[t];return!!n&&Object.prototype.hasOwnProperty.call(n,i)}function gu(e,t,i){return mu(e,t,i)?{domain:t,service:i}:mu(e,"homeassistant",i)?{domain:"homeassistant",service:i}:null}function fu(e,t){return e?.entities?.[t]||null}function vu(e,t,i){const n=e?.states?.[i],r=fu(t,i);return n?.attributes?.friendly_name||r?.name||r?.original_name||i}function yu(e,t){const i=fu(e,t);if(null!=i?.disabled_by)return!0;const n=i?.device_id?e?.devices?.[i.device_id]:null;return null!=n?.disabled_by}function bu(e,t){const i=e?.attributes?.supported_features;if(null==i||""===i)return!1;const n=Number(i);return Number.isFinite(n)&&(n&t)===t}function wu(e,t,i){const n=_u(i);if("lock"===n||"alarm_control_panel"===n)return!0;if("cover"!==n)return!1;const r=e?.states?.[i],o=fu(t,i),s=String(r?.attributes?.device_class||o?.device_class||o?.original_device_class||"");return Wi.has(s)}function ku(e,t,i,n,r){return{ref:i,entityId:n,name:n?vu(e,t,n):null,reason:r}}function xu(e,t,i,n,r,o=null){return{target:null,skipped:ku(e,t,i,n,r),semantics:o,nextEffect:null,command:null}}function Su(e,t,i,n,r=i){const o=_u(i);if("cover"!==o&&"valve"!==o)return function(e,t,i,n,r=i){const o=_u(i),s=e?.states?.[i];if(yu(t,i))return xu(e,t,r,i,"ha-disabled","power");if(wu(e,t,i))return xu(e,t,r,i,"secure");if(!s)return xu(e,t,r,i,"missing","power");if("unavailable"===s.state)return xu(e,t,r,i,"unavailable","power");const a=pu[o];if(!a)return xu(e,t,r,i,"unsupported");let l,c;if("unknown"===s.state||""===s.state){if(!a.unknownUsesToggle)return xu(e,t,r,i,"unsupported","power");l="toggle",c="toggle"}else a.offStates.includes(String(s.state))?(l="turn-on",c="turn_on"):(l="turn-off",c="turn_off");const h=a.featureMasks?.[c];if(h&&!bu(s,h))return xu(e,t,r,i,"unsupported","power");const d=gu(e,o,c);return d?{target:{entityId:i,name:vu(e,t,i),state:String(s.state||""),via:n},skipped:null,semantics:"power",nextEffect:l,command:{...d,data:{entity_id:i}}}:xu(e,t,r,i,"unsupported","power")}(e,t,i,n,r);if(yu(t,i))return xu(e,t,r,i,"ha-disabled",o);if(wu(e,t,i))return xu(e,t,r,i,"secure",o);const s=e?.states?.[i];if(!s)return xu(e,t,r,i,"missing",o);if("unavailable"===s.state)return xu(e,t,r,i,"unavailable",o);const a=function(e,t,i){const n=String(i?.state||""),r="closed"===n?{service:`open_${t}`,effect:"open",feature:1}:"open"===n?{service:`close_${t}`,effect:"close",feature:2}:"opening"===n||"closing"===n?{service:`stop_${t}`,effect:"stop",feature:8}:null;return r&&bu(i,r.feature)&&mu(e,t,r.service)?r:bu(i,3)&&mu(e,t,"toggle")?{service:"toggle",effect:"toggle"}:null}(e,o,s);if(!a)return xu(e,t,r,i,"unsupported",o);return{target:{entityId:i,name:vu(e,t,i),state:String(s.state||""),via:n},skipped:null,semantics:o,nextEffect:a.effect,command:{domain:o,service:a.service,data:{entity_id:i}}}}function $u(e){return"entity"===e.bindingKind?e.bindingRef&&Dn(e.bindingRef)?[e.bindingRef]:[]:"virtual"===e.bindingKind?[]:Md(e)}function Mu(e){const t=e.marker?.toggle_entity;return t&&$u(e).includes(t)?t:null}function Ru(e,t,i){const n=function(e,t){if("entity"===e.bindingKind&&e.bindingRef){const t=e.marker?.light_entity?Rd(e):null;return[...new Set([t,e.bindingRef].filter(e=>!!e))]}const i=e.entities.length?e.entities:e.allEntities||[],n=e.marker?.light_entity||e.primary&&Dn(e.primary)?Rd(e):null;return[...new Set([n,...wd(t,i)].filter(e=>!!e))]}(i,t);if(!n.length)return null;const r="entity"===i.bindingKind?"binding":"device-role";if("binding"===r)return Su(e,t,n[0],r);let o=null,s=null;for(const i of n){const n=Su(e,t,i,r);if(n.command)return n;const a=n.skipped?.reason;if("missing"===a||"unavailable"===a||"secure"===a)return n;"ha-disabled"!==a?o||=n:s||=n}return o||s}function Cu(e){const t=e.skipped?.reason;return"missing"===t?"unavailable":t||"unsupported"}function Tu(e,t){return{origin:e,kind:"none",semantics:null,targets:[],skippedTargets:[],noneReason:t,nextEffect:null,command:null}}function Du(e,t){return"cover"===e||"toggle"===e?"toggle":"more-info"===e||"run"===e||"info"===e||"none"===e?e:(null==e||""===e)&&"light"===t?"toggle":"info"}function Au(e,t){return{origin:e,kind:"single",semantics:t.semantics,targets:t.target?[t.target]:[],skippedTargets:t.skipped?[t.skipped]:[],noneReason:t.command?null:Cu(t),nextEffect:t.nextEffect,command:t.command}}function Pu(e,t,i,n=[]){const r=new Map,o=[],s=new Set,a=e=>{const t=`${e.ref}\n${e.entityId||""}\n${e.reason}`;s.has(t)||(s.add(t),o.push(e))};for(const e of n)a(e);for(const n of i){const i=Su(e,t,n.entityId,n.via,n.ref);i.target?r.set(n.entityId,r.get(n.entityId)||i.target):i.skipped&&a(i.skipped)}const l=[...r.values()];if(!l.length)return{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:l,skippedTargets:o,noneReason:o.length&&o.every(e=>"secure"===e.reason)?"secure":"configured-targets-missing",nextEffect:null,command:null};const c=l.some(e=>"on"===e.state)?"turn_off":"turn_on",h=gu(e,"homeassistant",c);return h?{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:l,skippedTargets:o,noneReason:null,nextEffect:"turn_on"===c?"turn-on":"turn-off",command:{...h,data:{entity_id:l.map(e=>e.entityId)}}}:{origin:"explicit-toggle",kind:"group",semantics:"group-power",targets:[],skippedTargets:[...o,...l.map(i=>ku(e,t,i.entityId,i.entityId,"unsupported"))],noneReason:"unsupported",nextEffect:null,command:null}}function Fu(e){return String(e.marker?.id||e.id||"")}function zu(e){const{hass:t,device:i}=e,n=e.registryHass||t,r=function(e){return"toggle"===e.tapAction?"explicit-toggle":"cover"===e.tapAction?"legacy-cover":!e.tapAction&&e.primary?.startsWith("light.")?"default-light":null}(i);if(!r)return null;const o=i.marker;if("explicit-toggle"===r&&jh(o)){const t=String(o?.id||i.id||""),n=Fd(e.devices).get(t);if(n)return function(e,t){const i=e.registryHass||e.hass;return Pu(e.hass,i,t.driverEids.map(e=>({entityId:e,via:"control-marker-driver",ref:`marker:${t.markerId}`})))}(e,n);const s=Wh(o,e.virtualLights);return{origin:r,kind:"single",semantics:"power",targets:[{entityId:"",name:i.name,state:s?"on":"off",via:"virtual-light"}],skippedTargets:[],noneReason:null,nextEffect:s?"turn-off":"turn-on",command:null,operation:{kind:"virtual-light",markerId:o.id}}}if("explicit-toggle"===r){if(Sd(i.marker?.binding,i.marker?.controls??i.controls,i.entities).length)return function(e,t=null){const{hass:i,device:n,devices:r}=e,o=e.registryHass||i,s=Sd(n.marker?.binding,n.marker?.controls??n.controls,n.entities),a=e.lightSources||Nd(i,r,null,e.virtualLights),l=new Map;for(const e of a){if(!e.key.startsWith("marker:"))continue;const t=l.get(e.key)||[];t.push(e),l.set(e.key,t)}const c=Fd(r),h=new Map;for(const e of r){const t=String(e.marker?.id||e.id||"");t&&h.set(t,e)}const d=[],u=[];t&&d.push({entityId:t,via:"entity"===n.bindingKind?"binding":"device-role",ref:t});for(const e of s){if(!e.startsWith("marker:")){Dn(e)?d.push({entityId:e,via:"control-entity",ref:e}):u.push(ku(i,o,e,e.includes(".")?e:null,"unsupported"));continue}const t=l.get(e)||[];if(!t.length){const t=h.get(e.slice(7));if("ha_disabled"===t?.bindingStatus?.kind){const n=t.bindingStatus.allEntityIds[0]||null;u.push({ref:e,entityId:n,name:t.name||(n?vu(i,o,n):null),reason:"ha-disabled"})}else u.push(ku(i,o,e,null,"missing"));continue}const r=[...new Set(t.flatMap(e=>e.serviceEids))];if(r.length){for(const t of r)d.push({entityId:t,via:"control-entity",ref:e});continue}const s=t.some(e=>e.passive),a=e.slice(7),p=Fu(n),_=c.get(a)?.controllers.find(e=>Fu(e.device)===p);if(s&&_?.driverEids.length)for(const t of _.driverEids)d.push({entityId:t,via:"control-marker-driver",ref:e});else u.push(ku(i,o,e,null,s?"missing":"unsupported"))}return Pu(i,o,d,u)}(e,Mu(i))}if("legacy-cover"===r){const e=i.entities.find(e=>e.startsWith("cover."))||i.allEntities?.find(e=>e.startsWith("cover."));return e?Au(r,Su(t,n,e,"device-role")):Tu(r,"no-actionable-entity")}const s=Mu(i),a=s?Su(t,n,s,"entity"===i.bindingKind?"binding":"device-role"):Ru(t,n,i);return a?Au(r,a):Tu(r,i.virtual||"virtual"===i.bindingKind?"no-actionable-entity":"no-binding")}function Iu(e){if(!e)return[];const t=Array.isArray(e.data.entity_id)?e.data.entity_id:[e.data.entity_id];return[...new Set(t)].sort()}function Ou(e){return e?e.operation?e.operation:e.command?{kind:"ha-service",command:e.command}:null:null}const Eu=new Set(["missing","ha-disabled","unavailable"]);function Nu(e,t){const i=Ou(e),n=Ou(t);return!(!i||!n||i.kind!==n.kind)&&("virtual-light"===i.kind&&"virtual-light"===n.kind?i.markerId===n.markerId:"ha-service"===i.kind&&"ha-service"===n.kind&&function(e,t){const i=Iu(e),n=Iu(t);return i.length===n.length&&i.every((e,t)=>e===n[t])}(i.command,n.command))}function Hu(e,t){const i=e.targets[0]||e.skippedTargets[0],n=[];return"group"===e.kind?e.targets.length&&n.push(t.group(e.targets)):i&&n.push(t.single(i)),e.nextEffect&&e.targets.length&&n.push("group"===e.kind?t.groupCurrentNext(e.targets,e.nextEffect):t.currentNext(e.targets[0],e.nextEffect)),e.skippedTargets.length&&n.push(t.skipped(e.skippedTargets)),!e.command&&e.noneReason&&n.push(t.none(e.noneReason)),n}function Lu(e,t){return e.catch(()=>{}).then(t)}const Bu=e=>{const t=e?.config;return t&&Array.isArray(t.spaces)?t:null},qu=(e,t)=>"number"==typeof e&&Number.isFinite(e)?e:t;class ju{constructor(e){this.onBodyReplaced=e,this.config=null,this.configRev=0,this.configFingerprint="",this.layout={},this.layoutRev=0,this.layoutFingerprint=""}setConfig(e){const t=this.config;e!==t&&(this.config=e,this.onBodyReplaced?.("_serverCfg",t))}setLayout(e){const t=this.layout;e!==t&&(this.layout=e,this.onBodyReplaced?.("_layout",t))}currentConfigFingerprint(){return this.configFingerprint||hc(this.config)}currentLayoutFingerprint(){return this.layoutFingerprint||hc(this.layout)}adoptResponses(e,t,i,n){const r=Bu(e),o=hc(r),s=o!==this.currentConfigFingerprint();s&&(i(),this.setConfig(r),this.configFingerprint=o),this.configRev=e?.rev??this.configRev;let a=!1;if(void 0!==t){const e=t?.layout??{},i=hc(e);a=i!==this.currentLayoutFingerprint(),a&&(n(),this.setLayout(e),this.layoutFingerprint=i),this.layoutRev=t?.rev??this.layoutRev}return{configChanged:s,layoutChanged:a}}adoptMergedLayout(e,t,i){const n=hc(e),r=n!==hc(this.layout);return r&&(i?.(),this.setLayout(e)),this.layoutFingerprint=n,this.layoutRev=t?.rev??this.layoutRev,r}stageConfigCandidate(e){const t=hc(e);t!==hc(this.config)&&this.setConfig(e),this.configFingerprint=t}acceptConfigWrite(e,t){this.configFingerprint=hc(e),this.configRev=qu(t?.rev,this.configRev+1)}acceptPairWrite(e,t,i){this.setConfig(e),this.configFingerprint=hc(e),this.setLayout(t),this.layoutFingerprint=hc(t),this.configRev=qu(i?.config_rev,this.configRev+1),this.layoutRev=qu(i?.layout_rev,this.layoutRev+1)}noteLayoutRevision(e){"number"==typeof e&&e>this.layoutRev&&(this.layoutRev=e)}stageLocalConfig(e){this.setConfig(e)}stageLocalLayout(e){this.setLayout(e)}seedIdentity(e){Object.assign(this,e)}refreshConfigFingerprint(){this.configFingerprint=hc(this.config)}refreshLayoutFingerprint(){this.layoutFingerprint=hc(this.layout)}beginOptimistic(e,t){return function(e,t,i,n,r){return{previous:JSON.parse(JSON.stringify(e)),previousFingerprint:i,revision:n,attempted:t,attemptedFingerprint:r(t)}}(e,t,this.configFingerprint,this.configRev,hc)}rollbackOptimistic(e){const t=this.config;return!(!t||this.configRev!==e.revision||hc(t)!==e.attemptedFingerprint)&&(this.setConfig(e.previous),this.configFingerprint=e.previousFingerprint,!0)}restoreCached(e){const t=e?.config;return!(!t||!Array.isArray(t.spaces))&&(this.setConfig(t),this.configRev=e?.rev||0,this.configFingerprint=e?.config_fingerprint||hc(t),this.setLayout(e?.layout||{}),this.layoutRev=e?.layout_rev||0,this.layoutFingerprint=e?.layout_fingerprint||hc(this.layout),!0)}snapshot(e){return this.config?(this.refreshConfigFingerprint(),this.refreshLayoutFingerprint(),{config:this.config,rev:this.configRev,config_fingerprint:this.configFingerprint,layout:this.layout,layout_rev:this.layoutRev,layout_fingerprint:this.layoutFingerprint,virtual_lights:e}):null}}async function Wu(e,t){const i=t.isCurrent??(()=>!0);if(!i())return{status:"superseded"};const{cfgResp:n,layResp:r}=t,o=e._adoption,s=Bu(n),a=null!=n&&hc(s)!==o.currentConfigFingerprint()||null!=r&&hc(r.layout??{})!==o.currentLayoutFingerprint();if(a){const t=await e._signer.prepareImage(e.hass,e._candidateBackdrop(s));if(!i())return{status:"superseded"};if(!t)return e._continuity.note("asset-failed"),e._scheduleLoadRetry(!0),{status:"asset-wait"}}if(!i())return{status:"superseded"};a&&e._continuity.hasCompleteFrame&&"steady"===e._continuity.state&&e._beginContinuityCandidate(t.reason,!0),t.beforeAdopt?.();const l=e._space;return function(e,t,i){const n=e._adoption,r=!!n.config,{configChanged:o,layoutChanged:s}=n.adoptResponses(t??{},i,()=>{e._geometryHistory.clear(),e._devicePositionHistory.clear(),e._cancelDeviceDrag(),e._pendingPhysicalWrites.clear(),e._clearRoomFocus(!0),e._cancelCameraTransition(!1),r&&e._clearGeometryGesture()},()=>{e._cancelCameraTransition(!1),e._devicePositionHistory.clear(),e._cancelDeviceDrag()});if(o&&e._seedDecorStyle(n.config),t&&("virtual_lights"in t||"config"in t)){const i=Bh(e._virtualLights,t.virtual_lights,n.configRev,"virtual_lights"in t);qh(i)!==qh(e._virtualLights)&&(e._virtualLights=i,e._capturedSnapshotVirtual="")}e._canOptimizeUndo=!(!t?.can_optimize_undo&&!i?.can_optimize_undo),e._adoptConfigCapabilities(t),e._undoKind=t?.undo_kind||i?.undo_kind||null,"boolean"==typeof t?.can_write&&(e._serverCanWrite=t.can_write),o&&e._continuity.note("config-candidate",{configRev:n.configRev}),s&&e._continuity.note("layout-candidate",{layoutRev:n.layoutRev})}(e,n,r),"reload"===t.profile&&(e._syncDecorAssets(s).catch(()=>{}),e._adoptInitialSpace(e._model,!0),e._resumePendingNavMode(),e._cacheSnapshot()),t.afterAdopt?.(),{status:"adopted",spaceChanged:e._space!==l}}const Uu=(e,t)=>e.connection===t.connection&&e.userId===t.userId&&e.route===t.route,Gu=e=>"number"==typeof e&&Number.isFinite(e)?e:null;class Vu{constructor(){this.sequence=0,this.currentSequence=0,this.lifecycle=0,this.observedHighWater=null,this.context=null}observeContext(e){this.context?Uu(this.context,e)||(this.context={...e},this.invalidateLifecycle()):this.context={...e}}invalidateLifecycle(){this.lifecycle+=1,this.currentSequence=++this.sequence,this.observedHighWater=null}observeRevision(e,t,i){this.observeContext(i);const n=Gu(e);if(null===n)return null;const r=Gu(t)??Number.NEGATIVE_INFINITY;return n<=Math.max(r,this.observedHighWater??Number.NEGATIVE_INFINITY)?null:(this.observedHighWater=n,Object.freeze({sequence:this.currentSequence,lifecycle:this.lifecycle,context:{...i},observedRevision:n}))}isReservationCurrent(e,t,i){this.observeContext(t);const n=Gu(i)??Number.NEGATIVE_INFINITY;return e.sequence===this.currentSequence&&e.lifecycle===this.lifecycle&&Uu(e.context,t)&&e.observedRevision===this.observedHighWater&&e.observedRevision>n}begin(e){this.observeContext(e.context),e.force&&this.invalidateLifecycle();const t=++this.sequence;return this.currentSequence=t,Object.freeze({sequence:t,lifecycle:this.lifecycle,force:e.force,context:{...e.context},baselineRevision:e.baselineRevision,baselineFingerprint:e.baselineFingerprint})}isCurrent(e){this.observeContext(e.context);const t=e.claim;return e.connected&&(t.force||!e.writePending)&&t.sequence===this.currentSequence&&t.lifecycle===this.lifecycle&&Uu(t.context,e.context)&&t.baselineRevision===e.baselineRevision&&t.baselineFingerprint===e.baselineFingerprint}}const Ku=e=>{const t=e.hass,i=t?.user?.id;return{connection:t?.connection??null,userId:"string"==typeof i?i:null,route:location.pathname}};async function Yu(e,t=!1,i){let n=null;const r=e._configReloadAuthority;if(!t){if(void 0!==i&&(n=r.observeRevision(i,e._cfgRev,Ku(e)),!n))return;if(e._saveConfigDebounced.pending()&&e._saveConfigDebounced.flush(),e._cfgWriting)return clearTimeout(e._reloadRetry),void(e._reloadRetry=window.setTimeout(()=>{n&&!r.isReservationCurrent(n,Ku(e),e._cfgRev)||Yu(e,!1)},400))}const o=r.begin({force:t,context:Ku(e),baselineRevision:e._cfgRev,baselineFingerprint:e._adoption.currentConfigFingerprint()}),s=()=>((e,t)=>e._configReloadAuthority.isCurrent({claim:t,context:Ku(e),connected:e.isConnected,baselineRevision:e._cfgRev,baselineFingerprint:e._adoption.currentConfigFingerprint(),writePending:e._saveConfigDebounced.pending()||e._cfgWriting}))(e,o);let a=!1;try{const t=await e._getAuthoritativeConfig();if(!s())return;const i=await e._adoptAuthoritative({cfgResp:t,reason:"config-reload",profile:"reload",isCurrent:s,afterAdopt:()=>{e._regSignature="",e._maybeRebuildDevices()}});if("superseded"===i.status)return;if(a=!0,"adopted"!==i.status)return;i.spaceChanged&&e._restoreZoom(),e.requestUpdate()}catch(t){if(!s())return;a=!0,e._showToast(e._t("toast.cfg_reload_failed",{err:e._errText(t)}))}finally{(a||s())&&(e._continuityDataReady=!0,e.requestUpdate())}}const Xu=e=>!!e&&e.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]);function Zu(e,t=5,i=5){return zo(e.cm,t,i)/2}function Ju(e,t,i=1,n=5,r=5,o=0){const s=e.host;if(!s||"partition"!==s.kind||"string"!=typeof s.id||!s.id)return{resolved:null,reason:"invalid-host"};const a=t.find(e=>e.id===s.id);if(!a)return{resolved:null,reason:"missing-partition"};if(!Xu(a.a)||!Xu(a.b)||!Number.isFinite(s.t)||s.t<0||s.t>1)return{resolved:null,reason:"invalid-position"};const l=a.b[0]-a.a[0],c=a.b[1]-a.a[1],h=Math.hypot(l,c),d=Number(e.length)*i;if(!(h>1e-9&&d>0&&Number.isFinite(d)))return{resolved:null,reason:"invalid-length"};const u=s.t*h;if(u-d/2h-o+1e-9)return{resolved:null,reason:"does-not-fit"};const p=l/h,_=c/h;let m=180*Math.atan2(c,l)/Math.PI;return m>=90?m-=180:m<-90&&(m+=180),{reason:null,resolved:{opening:e,host:s,partition:a,center:[a.a[0]+l*s.t,a.a[1]+c*s.t],angle:m,length:d,depth:zo(a.cm,n,r),t:s.t,axis:{a:[a.a[0],a.a[1]],b:[a.b[0],a.b[1]],ux:p,uy:_,length:h}}}}function Qu(e,t,i=1,n=5,r=5){return Ju(e,t,i,n,r,0)}function ep(e,t,i=1,n=5,r=5){const o=e.host,s="partition"===o?.kind?t.find(e=>e.id===o.id):void 0;if(!s)return Qu(e,t,i,n,r);const a=Ju(e,t,i,n,r,Zu(s,n,r));return"does-not-fit"===a.reason?{resolved:null,reason:"does-not-fit-jamb"}:a}function tp(e,t){return!e||(e.length!==t.length||e.host?.kind!==t.host?.kind||e.host?.id!==t.host?.id||e.host?.t!==t.host?.t)}function ip(e){const{center:t,length:i,axis:n,host:r}=e,o=i/2;return{hostId:r.id,a:[t[0]-n.ux*o,t[1]-n.uy*o],b:[t[0]+n.ux*o,t[1]+n.uy*o],depth:e.depth}}function np(e,t=!1){const i=t?1:-1,n=e.depth/2;return{ox:-e.axis.uy*i*n,oy:e.axis.ux*i*n,cm:e.partition.cm,side:i}}function rp(e,t,i){return e.flatMap(e=>!Xu(e.a)||!Xu(e.b)||Math.hypot(e.b[0]-e.a[0],e.b[1]-e.a[1])<=1e-9?[]:[{roomId:"",a:[e.a[0],e.a[1]],b:[e.b[0],e.b[1]],key:`partition:${e.id}`,kind:"outer",cm:e.cm,open:!1,half:zo(e.cm,t,i)/2,partitionHost:{kind:"partition",id:e.id}}])}function op(e,t,i){const{center:n,length:r,axis:o}=e,s=r/2,a=t.flatMap(e=>{if(!e.kind||e.open)return[];const t=e.b[0]-e.a[0],r=e.b[1]-e.a[1],a=Math.hypot(t,r);if(!(a>i))return[];const l=t/a,c=r/a;if(Math.abs(o.ux*c-o.uy*l)>1e-6)return[];if(Math.abs((n[0]-e.a[0])*c-(n[1]-e.a[1])*l)>i)return[];const h=e=>(e[0]-n[0])*o.ux+(e[1]-n[1])*o.uy,d=h(e.a),u=h(e.b),p=Math.max(-s,Math.min(d,u)),_=Math.min(s,Math.max(d,u));return _>=p-i?[[p,_]]:[]});if(!a.length)return!1;a.sort((e,t)=>e[0]-t[0]||e[1]-t[1]);let l=-s;for(const[e,t]of a){if(e>l+i)return!1;if(l=Math.max(l,t),l>=s-i)return!0}return!1}function sp(e,t,i=1e-9){const n=e.length/(2*e.axis.length),r=e.t-n,o=e.t+n;return t.some(t=>{if(t.host.id!==e.host.id||t.opening.id===e.opening.id)return!1;const n=t.length/(2*t.axis.length);return Math.max(r,t.t-n)ha-icon{align-self:start;color:var(--hp-accent);}.version-recovery-copy{min-width:0;display:flex;flex-direction:column;gap:var(--sp-2);font-size:var(--fs-m);line-height:1.35;}.version-recovery-copy>span{color:var(--hp-muted);}.version-recovery-versions{display:flex;flex-wrap:wrap;gap:var(--sp-2) var(--sp-5);}.version-recovery-versions span,.version-recovery-versions b{overflow-wrap:anywhere;}.version-recovery-reload{min-height:44px;white-space:normal;}@keyframes hp-version-recovery-in{from{opacity:0;}to{opacity:1;}}@keyframes hp-version-recovery-out{from{opacity:1;}to{opacity:0;}}@media (max-width:520px){.version-recovery-card{grid-template-columns:auto minmax(0,1fr);}.version-recovery-reload{grid-column:1 / -1;width:100%;}}@keyframes fixedfloor-spin{to{transform:rotate(360deg);}}.spacer{flex:1;}.bootveil{position:absolute;inset:0;z-index:40;display:flex;align-items:center;justify-content:center;background:var(--hp-bg,#16212e);opacity:1;transition:opacity 0.15s ease;pointer-events:none;}.bootveil.off{opacity:0;}.bootveil .boothouse{position:static;width:56px;height:56px;fill:var(--hp-accent);opacity:0.85;animation:hp-boot-pulse 1.3s ease-in-out infinite;}@keyframes hp-boot-pulse{0%,100%{opacity:0.3;transform:scale(0.94);}50%{opacity:0.9;transform:scale(1);}}@media (prefers-reduced-motion:reduce){.bootveil .boothouse{animation:none;opacity:0.7;}.version-recovery.phase-visible,.version-recovery.phase-leaving{animation:none;}}@keyframes hp-pulse-short{0%{transform:scale(1);opacity:0.55;}70%{opacity:0.22;}100%{transform:scale(var(--ripple-scale,1.5));opacity:0;}}@keyframes hp-pulse-short-b{0%{transform:scale(1);opacity:0.55;}70%{opacity:0.22;}100%{transform:scale(var(--ripple-scale,1.5));opacity:0;}}@keyframes hp-pulse-continuous{0%{transform:scale(1);opacity:0.55;}65%{opacity:0.18;}100%{transform:scale(var(--ripple-scale,1.5));opacity:0;}}@keyframes hp-pulse-alarm{0%{transform:scale(1);opacity:0.72;}100%{transform:scale(1.5);opacity:0;}}@keyframes hp-slide-left{0%{transform:translateX(4%);opacity:0.72;}100%{transform:translateX(0);opacity:1;}}@keyframes hp-slide-right{0%{transform:translateX(-4%);opacity:0.72;}100%{transform:translateX(0);opacity:1;}}@keyframes hp-sunfade-in{from{opacity:0;}to{opacity:1;}}@keyframes hp-sunfade-out{from{opacity:1;}to{opacity:0;}}.sr-only{position:absolute !important;width:1px !important;height:1px !important;padding:0 !important;margin:-1px !important;overflow:hidden !important;clip:rect(0,0,0,0) !important;white-space:nowrap !important;border:0 !important;}.toast{position:fixed;pointer-events:none;left:50%;bottom:22px;transform:translateX(-50%);background:var(--hp-bg);border:1px solid var(--hp-accent);color:var(--hp-txt);padding:var(--sp-4) var(--sp-6);border-radius:var(--rad-l);font-size:var(--fs-m);box-shadow:var(--shadow-2);z-index:120;max-width:90vw;}`,o`.fixedfloor-loading{animation:fixedfloor-spin 1.1s linear infinite;}.fixedfloor-error p{max-width:42rem;margin:0;overflow-wrap:anywhere;}@media (prefers-reduced-motion:reduce){.fixedfloor-loading{animation:none;}.radar-target{transition:none;}}.stage.noplan{background:#ffffff;}.stage.mode-plan,.stage.mode-devices,.stage.mode-decor{background:#ffffff;}.stage{position:relative;width:100%;container-type:inline-size;overflow:hidden;touch-action:none;background:var(--ha-card-background,var(--card-background-color,#111));}.zoomwrap{position:absolute;inset:0;z-index:1;}.stage.mode-transition,.stage.mode-transition .zoomwrap{transition:none !important;}.stage.mode-transition .hp-view-only-layer,.stage.mode-transition .hp-editor-only-layer{pointer-events:none;will-change:opacity;}.stage.mode-transition .hp-paper{fill:var(--hp-mode-paper) !important;}.hp-day-cycle-env{position:absolute;inset:0;z-index:0;overflow:hidden;pointer-events:none;isolation:isolate;}.hp-day-cycle-bg{position:absolute;inset:0;opacity:0;overflow:hidden;transition:opacity 1100ms cubic-bezier(.22,.61,.36,1);}.hp-day-cycle-bg.active{opacity:1;}.hp-day-cycle-sun{position:absolute;left:var(--hp-day-cycle-sun-x);top:var(--hp-day-cycle-sun-y);width:clamp(140px,25cqw,250px);height:clamp(140px,25cqw,250px);transform:translate(-50%,-50%);border-radius:50%;filter:blur(10px);opacity:var(--hp-day-cycle-sun-opacity);transition:left 1100ms cubic-bezier(.22,.61,.36,1),top 1100ms cubic-bezier(.22,.61,.36,1),opacity 1100ms cubic-bezier(.22,.61,.36,1);}.stage.mode-transition .hp-day-cycle-env{transition:none;}.stage.daycycle .hp-paper-outline-svg,.hp-static-stage.daycycle .hp-paper-outline-svg{filter:drop-shadow(0 0 1px var(--hp-day-cycle-outline-near)) drop-shadow(0 0 5px var(--hp-day-cycle-outline-mid)) drop-shadow(0 0 10px var(--hp-day-cycle-outline-far));will-change:filter;transition:filter 1100ms cubic-bezier(.22,.61,.36,1);}@media (prefers-reduced-motion:reduce){.hp-day-cycle-bg,.hp-day-cycle-sun,.stage.daycycle .hp-paper-outline-svg,.hp-static-stage.daycycle .hp-paper-outline-svg{transition:none;}}.sunlayer{pointer-events:none;}.compass{width:120px;height:120px;flex:none;touch-action:none;cursor:grab;user-select:none;}.compass:active{cursor:grabbing;}.compass .cring{fill:rgba(255,255,255,0.04);stroke:var(--divider-color,#444);stroke-width:2;}.compass .ctick{stroke:var(--secondary-text-color,#9aa4ad);stroke-width:2;}.compass .ctick.minor{stroke-width:1;opacity:0.6;}.compass .cneedle line{stroke:var(--primary-color,#3ea6ff);stroke-width:2.5;stroke-linecap:round;}.compass .cneedle path{fill:var(--primary-color,#3ea6ff);}.compass .cneedle text{fill:var(--text-primary-color,#fff);font-size:11px;font-weight:700;}.compass .cdeg{fill:var(--secondary-text-color,#9aa4ad);font-size:13px;}.compass.unset .cneedle{opacity:0.35;}.stage.hpboot .zoomwrap,.stage.hpboot .zoombadge{visibility:hidden;}.stage.hpsettle{transition:height 0.25s ease;}@media (prefers-reduced-motion:reduce){.stage.hpsettle{transition:none;}}.zoomctl{display:inline-flex;gap:var(--sp-1);background:rgba(127,127,127,0.12);border-radius:var(--rad-m);padding:var(--sp-1);}.zoomctl .zb{border:none;padding:var(--sp-3) var(--sp-4);}.zoomctl .zb[disabled]{opacity:0.4;pointer-events:none;}.projection-toggle{min-width:44px;min-height:44px;justify-content:center;padding:var(--sp-3);}.header-action{min-width:44px;min-height:44px;justify-content:center;padding:var(--sp-3);}.homearrow{position:absolute;z-index:12;transform:translate(-50%,-50%);width:40px;height:40px;border-radius:50%;display:flex;align-items:center;justify-content:center;cursor:pointer;background:var(--card-background-color,var(--hp-bg));color:var(--hp-accent);border:1px solid var(--hp-accent);opacity:0.9;padding:0;}.homearrow ha-icon{--mdc-icon-size:22px;line-height:1;}.zoombadge{position:absolute;z-index:12;left:var(--sp-4);bottom:var(--sp-4);background:var(--card-background-color,var(--hp-bg));opacity:0.92;color:var(--hp-txt);border:1px solid var(--hp-accent);border-radius:var(--rad-m);padding:var(--sp-1) var(--sp-4);font-size:var(--fs-s);font-weight:600;pointer-events:none;}.zoomwrap>svg{position:absolute;inset:0;width:100%;height:100%;display:block;}.plan-svg{z-index:1;}.hp-paper-outline-svg{z-index:0;overflow:visible;pointer-events:none;}.iso-underlay-svg{z-index:0;overflow:visible;}.iso-shadows-svg{z-index:3;overflow:visible;}.iso-walls-svg{z-index:4;overflow:visible;}.iso-overlays-svg{z-index:5;overflow:visible;}.iso-underlay-svg,.iso-shadows-svg,.iso-walls-svg,.iso-overlays-svg,.iso-underlay,.iso-shadows,.iso-walls,.iso-openings{pointer-events:none;}.iso-side-hi{stop-color:#b9bdbe;}.iso-side-lo{stop-color:#969c9f;}.iso-top-hi{stop-color:#fafaf7;}.iso-top-lo{stop-color:#e2e4e2;}.iso-wall-side{fill:url(#hp-iso-wall-side) #a8acae;stroke:#92989b;stroke-width:0.7;vector-effect:non-scaling-stroke;}.iso-wall-top{fill:url(#hp-iso-wall-top) #f3f3f1;stroke:#d7d9d8;stroke-width:0.8;vector-effect:non-scaling-stroke;}.iso-material-texture{fill:url(#hp-iso-wall-texture);stroke:none;opacity:0.12;pointer-events:none;}.iso-floor-texture{fill:url(#hp-iso-floor-texture);opacity:0.1;}.iso-texture-mark{fill:rgba(36,43,47,0.34);}.iso-texture-line{fill:none;stroke:rgba(36,43,47,0.24);stroke-width:0.55;}.iso-floor-side{fill:#858b8d;stroke:#71787b;stroke-width:0.7;vector-effect:non-scaling-stroke;}.iso-opening-panel{fill:#d7d9d7;fill-opacity:0.96;stroke:#7f878b;stroke-width:0.9;vector-effect:non-scaling-stroke;}.iso-opening-panel.iso-window{fill:#dfeff4;fill-opacity:0.72;stroke:#8aa7b1;}.iso-opening-panel.iso-material-reveal{fill:#c7cbca;stroke:#8b9294;}.iso-opening-panel.iso-material-matte-leaf{fill:#a6abad;stroke:#737b7f;}.iso-opening-panel.iso-opening-leaf-edge,.iso-opening-panel.iso-opening-leaf-top{fill:#8d9497;}.iso-opening-panel.iso-material-light-frame,.iso-opening-panel.iso-material-light-sill{fill:#fffef8;fill-opacity:0.94;stroke:#b3b5ae;}.iso-opening-panel.iso-material-light-window,.iso-opening-panel.iso-material-glass-side{fill:#c9e4f3;fill-opacity:0.88;stroke:#8fb4c7;}.iso-opening-panel.iso-material-glass-top{fill:#e3f2fa;fill-opacity:0.96;stroke:#9fc4d5;}.iso-ambient-shadow{fill:rgba(15,21,25,0.22);filter:url(#hp-iso-ambient-shadow);}.iso-contact-shadow{fill:none;stroke:rgba(22,28,31,0.25);stroke-width:3;filter:url(#hp-iso-contact-shadow);vector-effect:non-scaling-stroke;}.iso-leaf-shadow{fill:none;stroke:rgba(18,23,27,0.24);stroke-width:4;filter:url(#hp-iso-leaf-shadow);vector-effect:non-scaling-stroke;}.stage.theme-dark .iso-side-hi{stop-color:#4c555a;}.stage.theme-dark .iso-side-lo{stop-color:#343c40;}.stage.theme-dark .iso-top-hi{stop-color:#687176;}.stage.theme-dark .iso-top-lo{stop-color:#50585d;}.stage.theme-dark .iso-wall-side{stroke:#30373b;}.stage.theme-dark .iso-wall-top{stroke:#7b858a;}.stage.theme-dark .iso-floor-side{fill:#2d3438;stroke:#20272a;}.stage.theme-dark .iso-opening-panel{fill:#626b70;stroke:#899399;}.stage.theme-dark .iso-opening-panel.iso-window{fill:#75919b;stroke:#abc6ce;}.stage.theme-dark .iso-opening-panel.iso-material-reveal{fill:#454e52;stroke:#727d82;}.stage.theme-dark .iso-opening-panel.iso-material-matte-leaf{fill:#626a6e;stroke:#899398;}.stage.theme-dark .iso-opening-panel.iso-opening-leaf-edge,.stage.theme-dark .iso-opening-panel.iso-opening-leaf-top{fill:#4b5458;}.stage.theme-dark .iso-opening-panel.iso-material-light-frame,.stage.theme-dark .iso-opening-panel.iso-material-light-sill{fill:#e8e7df;stroke:#a9aca7;}.stage.theme-dark .iso-opening-panel.iso-material-light-window,.stage.theme-dark .iso-opening-panel.iso-material-glass-side{fill:#8fbfd5;stroke:#bad9e6;}.stage.theme-dark .iso-opening-panel.iso-material-glass-top{fill:#c9e6f2;stroke:#d9eef6;}.stage.theme-dark .iso-ambient-shadow{fill:rgba(0,0,0,0.34);}.stage.theme-dark .iso-contact-shadow,.stage.theme-dark .iso-leaf-shadow{stroke:rgba(0,0,0,0.38);}.stage.theme-dark .iso-texture-mark{fill:rgba(255,255,255,0.24);}.stage.theme-dark .iso-texture-line{stroke:rgba(255,255,255,0.18);}@media (prefers-color-scheme:dark){.stage:not(.theme-light) .iso-side-hi{stop-color:#4c555a;}.stage:not(.theme-light) .iso-side-lo{stop-color:#343c40;}.stage:not(.theme-light) .iso-top-hi{stop-color:#687176;}.stage:not(.theme-light) .iso-top-lo{stop-color:#50585d;}.stage:not(.theme-light) .iso-wall-side{stroke:#30373b;}.stage:not(.theme-light) .iso-wall-top{stroke:#7b858a;}.stage:not(.theme-light) .iso-floor-side{fill:#2d3438;stroke:#20272a;}.stage:not(.theme-light) .iso-opening-panel{fill:#626b70;stroke:#899399;}.stage:not(.theme-light) .iso-opening-panel.iso-window{fill:#75919b;stroke:#abc6ce;}.stage:not(.theme-light) .iso-opening-panel.iso-material-reveal{fill:#454e52;stroke:#727d82;}.stage:not(.theme-light) .iso-opening-panel.iso-material-matte-leaf{fill:#626a6e;stroke:#899398;}.stage:not(.theme-light) .iso-opening-panel.iso-opening-leaf-edge,.stage:not(.theme-light) .iso-opening-panel.iso-opening-leaf-top{fill:#4b5458;}.stage:not(.theme-light) .iso-opening-panel.iso-material-light-frame,.stage:not(.theme-light) .iso-opening-panel.iso-material-light-sill{fill:#e8e7df;stroke:#a9aca7;}.stage:not(.theme-light) .iso-opening-panel.iso-material-light-window,.stage:not(.theme-light) .iso-opening-panel.iso-material-glass-side{fill:#8fbfd5;stroke:#bad9e6;}.stage:not(.theme-light) .iso-opening-panel.iso-material-glass-top{fill:#c9e6f2;stroke:#d9eef6;}.stage:not(.theme-light) .iso-ambient-shadow{fill:rgba(0,0,0,0.34);}.stage:not(.theme-light) .iso-contact-shadow,.stage:not(.theme-light) .iso-leaf-shadow{stroke:rgba(0,0,0,0.38);}.stage:not(.theme-light) .iso-texture-mark{fill:rgba(255,255,255,0.24);}.stage:not(.theme-light) .iso-texture-line{stroke:rgba(255,255,255,0.18);}}@media (forced-colors:active){.iso-wall-side,.iso-wall-top,.iso-floor-side,.iso-opening-panel{fill:Canvas;stroke:CanvasText;forced-color-adjust:auto;}.iso-ambient-shadow,.iso-contact-shadow,.iso-leaf-shadow,.iso-material-texture{display:none;}}@supports not (filter:blur(1px)){.iso-ambient-shadow,.iso-contact-shadow,.iso-leaf-shadow,.iso-material-texture{display:none;}}.hp-paper{fill:var(--ha-card-background,var(--card-background-color,#111));stroke:none;}.stage.noplan .hp-paper,.stage.mode-plan .hp-paper,.stage.mode-devices .hp-paper,.stage.mode-decor .hp-paper{fill:#ffffff;}.room{transition:0.12s;cursor:default;stroke-linejoin:round;stroke-linecap:round;}.stage.mode-view .room{cursor:pointer;}.room.overlay{fill:transparent;stroke:transparent;stroke-width:calc(2px * var(--hp-cell-visual-scale,1));}:host([data-pointer-hover]) .stage.mode-view .room.overlay:not(.styled):hover{stroke:var(--hp-accent);stroke-opacity:1;}.room.yard{fill:rgba(75,140,90,0.14);stroke:#4b8c5a;stroke-width:calc(2px * var(--hp-cell-visual-scale,1));}:host([data-pointer-hover]) .stage.mode-view .room.yard:not(.styled):hover{stroke:var(--hp-accent);stroke-opacity:1;}.room.styled{stroke:var(--room-stroke,transparent);stroke-opacity:var(--room-stroke-op,0);stroke-width:calc(2.5px * var(--hp-cell-visual-scale,1));fill:var(--room-fill,transparent);fill-opacity:var(--room-fill-op,0);}.glow-base-layer,.glow-base-tunnels,.glow-pools-frame,.glow-pools,.glow-spot{pointer-events:none;}.glow-pools-frame,.glow-pools,.glow-spot{isolation:isolate;}.glow-pools.blend-screen .glow-spot{mix-blend-mode:screen;}.glow-spot{opacity:1;transition:opacity 500ms ease;}.glow-spot.is-entering,.glow-spot.is-leaving{opacity:0;}@media (prefers-reduced-motion:reduce){.glow-spot{transition:none;}}:host([data-pointer-hover]) .stage.mode-view .room.styled:hover{stroke:var(--hp-accent);stroke-opacity:1;}.op-leaf{transition:transform 0.6s ease;}.op-arc{stroke-width:calc(1.5px * var(--hp-cell-visual-scale,1));transition:stroke-dashoffset 0.6s ease;}.op-outline{fill:none;stroke:var(--hp-accent);stroke-width:calc(1.5px * var(--hp-cell-visual-scale,1));opacity:0;transition:opacity 0.15s;pointer-events:none;}:host([data-pointer-hover]) .stage.markup g.opening:hover .op-outline{opacity:0.9;}.op-hit{fill:transparent;pointer-events:none;cursor:default;}.stage.markup .op-hit{pointer-events:auto;cursor:grab;touch-action:none;}.stage.markup .op-hit:active{cursor:grabbing;}.stage.markup .opening.orphan{pointer-events:auto;cursor:pointer;color:var(--error-color,#db4437);}.stage.markup .opening.orphan circle{fill:var(--hp-bg);stroke:currentColor;stroke-width:calc(2px * var(--hp-cell-visual-scale,1));}.stage.markup .opening.orphan text{fill:currentColor;font-weight:800;font-size:calc(12px * var(--hp-cell-visual-scale,1));pointer-events:none;}.stage.markup.tool-resize .op-hit{pointer-events:none;cursor:default;}.stage.mode-view .oplock{pointer-events:auto;cursor:pointer;}.stage.projection-iso.mode-view .oplock::before{content:'';position:absolute;left:50%;top:50%;width:max(44px,100%);height:max(44px,100%);transform:translate(-50%,-50%);border-radius:50%;pointer-events:auto;}@media (prefers-reduced-motion:reduce){.op-leaf,.op-arc{transition:none;}}.roomlabel{pointer-events:none;position:absolute;transform:translate(-50%,-50%);font-size:calc(var(--rl-icon-size,var(--icon-size,2.5cqw)) * 0.5 * var(--rl-scale,1) * var(--rl-font,1) * var(--rl-space,1));font-weight:700;letter-spacing:0.04em;white-space:nowrap;cursor:grab;user-select:none;z-index:1;display:flex;flex-direction:column;align-items:center;gap:0.15em;text-align:center;}.rlname{display:inline-flex;align-items:center;gap:0.25em;font-size:calc(1em * var(--rl-name,1));}.zoomwrap.slide-left{animation:hp-slide-left 0.18s cubic-bezier(0.2,0.7,0.2,1);}.zoomwrap.slide-right{animation:hp-slide-right 0.18s cubic-bezier(0.2,0.7,0.2,1);}@media (prefers-reduced-motion:reduce){.zoomwrap.slide-left,.zoomwrap.slide-right{animation:none;}}.rlgearbtn{--gear-h:calc(var(--icon-size,2.5cqw) * 0.77);position:absolute;transform:translate(-50%,-50%);display:inline-flex;align-items:center;gap:0.35em;height:var(--gear-h);padding:0 calc(var(--gear-h) * 0.38);border:0;border-radius:999px;background:var(--hp-accent);color:var(--text-primary-color,#fff);font:inherit;font-size:calc(var(--gear-h) * 0.42);font-weight:600;line-height:1;white-space:nowrap;cursor:pointer;pointer-events:auto;opacity:0.92;box-shadow:var(--shadow-1);z-index:2;}.rlgearbtn{transition:opacity 0.15s,filter 0.15s;}:host([data-pointer-hover]) .rlgearbtn:hover{opacity:1;filter:brightness(1.18);}.rlgearbtn ha-icon{--mdc-icon-size:calc(var(--gear-h) * 0.55);display:inline-flex;}.rlgear{--mdc-icon-size:0.9em;display:inline-flex;margin-right:0.2em;opacity:0.6;cursor:pointer;pointer-events:auto;}:host([data-pointer-hover]) .rlgear:hover{opacity:1;}.rlgo{--mdc-icon-size:0.85em;display:inline-flex;opacity:0.55;}.stage.mode-view .rlgo{pointer-events:auto;cursor:pointer;}:host([data-pointer-hover]) .stage.mode-view .rlgo:hover{opacity:1;}.roomlabel .rlmetrics{position:absolute;top:calc(100% + 0.15em);left:50%;transform:translateX(-50%);white-space:nowrap;display:flex;align-items:center;gap:0.55em;font-size:calc(0.75em * var(--rl-meta,1));font-weight:600;letter-spacing:0.02em;opacity:0.9;}.roomlabel .rlm{display:inline-flex;align-items:center;gap:0.12em;}.roomlabel .rlm ha-icon{--mdc-icon-size:1.05em;display:inline-flex;}.roomlabel .rlm.lit{opacity:1;}.rlhandle{display:none;position:absolute;width:9px;height:9px;border-radius:2px;background:var(--hp-accent);border:1px solid var(--card-background-color,#fff);z-index:2;}.rlhandle.tl{left:-6px;top:-6px;cursor:nwse-resize;}.rlhandle.br{right:-6px;bottom:-6px;cursor:nwse-resize;}.rlhandle.tr{right:-6px;top:-6px;cursor:nesw-resize;}.rlhandle.bl{left:-6px;bottom:-6px;cursor:nesw-resize;}:host([data-pointer-hover]) .stage.markup .roomlabel:hover .rlhandle{display:block;}.stage.markup .roomlabel{pointer-events:auto;}.stage.mode-view .roomlabel{pointer-events:auto;cursor:pointer;border-radius:0.2em;}.stage.projection-iso.mode-view .roomlabel{box-sizing:border-box;min-width:44px;min-height:44px;justify-content:center;text-shadow:none;filter:none;-webkit-text-stroke:0 transparent;color:#303936 !important;}.stage.projection-iso.theme-dark.mode-view .roomlabel{color:#f2f0e8 !important;}@media (prefers-color-scheme:dark){.stage.projection-iso:not(.theme-light).mode-view .roomlabel{color:#f2f0e8 !important;}}.stage.mode-view .roomlabel:focus-visible{outline:2px solid var(--hp-accent);outline-offset:4px;}.roomlabel:active{cursor:grabbing;}.measurelayer{position:absolute;inset:0;pointer-events:none;}.alignline{stroke:var(--hp-accent);stroke-width:calc(1.2px * var(--hp-cell-visual-scale,1));stroke-dasharray:calc(4px * var(--hp-cell-visual-scale,1)) calc(4px * var(--hp-cell-visual-scale,1));pointer-events:none;opacity:0.9;}.aligndot{fill:var(--hp-accent);pointer-events:none;}.measurelabel.on45{color:#4bd28f;border-color:#4bd28f;}.measurelabel{position:absolute;transform:translate(12px,-150%);font-size:var(--fs-s);font-weight:600;padding:1px var(--sp-3);border-radius:var(--rad-s);background:rgba(0,0,0,0.72);color:#fff;white-space:nowrap;pointer-events:none;user-select:none;z-index:3;}.measurelabel.opdimension{transform:translate(calc(-50% + var(--op-label-shift-x,0px)),calc(-50% + var(--op-label-shift-y,-12px)));border:1px solid var(--hp-open,#ff9800);}.decorlayer .dshape{pointer-events:none;}.stage.mode-decor .decorlayer .dshape{pointer-events:visiblePainted;cursor:pointer;}.stage.mode-decor.dtool-select .decorlayer .dshape{cursor:move;}.stage.mode-decor.dtool-line .decorlayer .dshape,.stage.mode-decor.dtool-rect .decorlayer .dshape,.stage.mode-decor.dtool-ellipse .decorlayer .dshape,.stage.mode-decor.dtool-text .decorlayer .dshape,.stage.mode-decor.dtool-furniture .decorlayer .dshape,.stage.mode-decor.dtool-image .decorlayer .dshape,.stage.mode-decor.dtool-backdrop .decorlayer .dshape{pointer-events:none;}.stage.mode-decor.dtool-furniture,.stage.mode-decor.dtool-image{cursor:copy;}.stage.mode-decor.dtool-select .decorlayer .dimage,.stage.mode-decor.dtool-erase .decorlayer .dimage,.stage.mode-decor.dtool-select .decorlayer .dimage-missing,.stage.mode-decor.dtool-erase .decorlayer .dimage-missing{pointer-events:bounding-box;}.decorlayer .dimage-missing rect{fill:rgba(127,127,127,0.12);stroke:var(--hp-accent);stroke-dasharray:8 5;vector-effect:non-scaling-stroke;}.decorlayer .dimage-missing path{fill:none;stroke:var(--hp-accent);vector-effect:non-scaling-stroke;}.decorlayer .decor-image-placement-preview{opacity:0.65;}.stage.mode-decor.dtool-text .decorlayer .dshape.dtext,.stage.mode-decor.dtool-select .decorlayer .dshape.dtext,.stage.mode-decor.dtool-erase .decorlayer .dshape.dtext{pointer-events:visiblePainted;pointer-events:bounding-box;}.stage.mode-decor.dtool-text .decorlayer .dshape.dtext{cursor:text;}.decorlayer .derasehit{fill:none;stroke:transparent;stroke-width:16px;stroke-linecap:round;stroke-linejoin:round;vector-effect:non-scaling-stroke;pointer-events:none;}.stage.mode-decor.dtool-erase .decorlayer .derasehit{pointer-events:stroke;}.decorlayer .dselecthit{fill:none;stroke:transparent;stroke-width:16px;stroke-linecap:round;vector-effect:non-scaling-stroke;pointer-events:none;}.stage.mode-decor.dtool-select .decorlayer .dselecthit{pointer-events:stroke;cursor:move;}.stage.mode-decor .decorlayer .dshape.dfurniturehit{fill:none;stroke:transparent;pointer-events:none;}.stage.mode-decor.dtool-select .decorlayer .dshape.dfurniturehit{pointer-events:stroke;cursor:move;}.decorlayer .dsel{filter:drop-shadow(0 0 3px var(--hp-accent));}.decorlayer .ddraft{stroke-dasharray:calc(6px * var(--hp-cell-visual-scale,1)) calc(5px * var(--hp-cell-visual-scale,1));pointer-events:none;}.decorlayer .furniture-placement-preview{opacity:0.55;pointer-events:none;}.decorlayer text{font-weight:600;user-select:none;dominant-baseline:middle;text-anchor:middle;}.stage.mode-decor{outline:2px solid #26a69a;outline-offset:-2px;}.bdframe .bdbox{fill:none;stroke:var(--hp-accent);stroke-width:2;stroke-dasharray:10 7;vector-effect:non-scaling-stroke;pointer-events:none;opacity:0.9;}.bdframe .bdhandle{fill:transparent;stroke:none;pointer-events:all;touch-action:none;}.bdframe .bdknob{fill:var(--hp-accent);stroke:#fff;stroke-width:1;vector-effect:non-scaling-stroke;pointer-events:none;}:host([data-pointer-hover]) .bdframe .bdhandle:hover + .bdknob{fill:#fff;stroke:var(--hp-accent);}.bdframe .bd-nwse{cursor:nwse-resize;}.bdframe .bd-nesw{cursor:nesw-resize;}.stage.mode-decor.bdgrab{cursor:grab;}.stage.mode-decor.bdgrabbing,.stage.mode-decor.bdgrabbing .bdframe .bdhandle{cursor:grabbing;}.measurelabel.bdmeasure{transform:translate(-50%,-50%);border:1px solid var(--hp-accent);}.dtframe .dtbox{fill:none;stroke:var(--hp-accent);stroke-width:1.5;stroke-dasharray:7 5;vector-effect:non-scaling-stroke;pointer-events:none;opacity:0.85;}.dtframe .dtstem,.bdframe .dtstem{stroke:var(--hp-accent);stroke-width:1.5;vector-effect:non-scaling-stroke;pointer-events:none;opacity:0.85;}.dtframe .dthandle{fill:transparent;stroke:none;pointer-events:all;touch-action:none;}.dtframe .dtknob{fill:var(--hp-accent);stroke:#fff;stroke-width:1;vector-effect:non-scaling-stroke;pointer-events:none;}:host([data-pointer-hover]) .dtframe .dthandle:hover + .dtknob{fill:#fff;stroke:var(--hp-accent);}.dtframe .dt-nwse{cursor:nwse-resize;}.dtframe .dt-nesw{cursor:nesw-resize;}.dtframe .dtrot{cursor:grab;}.dtframe .dt-ew{cursor:ew-resize;}.dtframe .dt-ns{cursor:ns-resize;}.dtfurnitureframe .dtrot{cursor:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cpath d='M18.4 7.2A8 8 0 1 0 20 12' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round'/%3E%3Cpath d='m15.5 3.8 3.2 3.5-4.6.8' fill='none' stroke='%23000' stroke-width='2' stroke-linecap='round' stroke-linejoin='round'/%3E%3C/svg%3E") 12 12,grab;}.dtfurnitureframe .dtrot:active{cursor:grabbing;}.dtframe .dtendpoint{cursor:crosshair;}.bdframe .dtrot{cursor:grab;}.dtarea{resize:vertical;min-height:3.4em;font:inherit;line-height:1.35;}.stage.mode-decor.dtool-line,.stage.mode-decor.dtool-rect,.stage.mode-decor.dtool-ellipse,.stage.mode-decor.dtool-text{cursor:crosshair;}.stage.mode-decor.dtool-erase,.stage.mode-decor.dtool-erase .decorlayer .dshape{cursor:url("data:image/svg+xml,%3Csvg xmlns='http://www.w3.org/2000/svg' width='24' height='24' viewBox='0 0 24 24'%3E%3Cg transform='rotate(-45 12 12)'%3E%3Crect x='7' y='2' width='10' height='18' rx='2' fill='%23fff' stroke='%23111' stroke-width='1.5'/%3E%3Cpath d='M7 13h10v5a2 2 0 0 1-2 2H9a2 2 0 0 1-2-2z' fill='%23ff9f43' stroke='%23111' stroke-width='1.5'/%3E%3C/g%3E%3C/svg%3E") 5 22,pointer;}.stage.mode-decor .room{pointer-events:none;}.stage.mode-decor .devlayer,.stage.mode-decor .devlayer *,.stage.mode-decor .dev::before{pointer-events:none;}.stage .room,.stage .devlayer,.stage .opening,.stage .room-outline,.stage .wallbodies,.stage .opening-tunnels,.stage .glow-base-layer,.stage .glow-pools-frame,.stage .zero-walls{opacity:var(--hp-mode-architecture-opacity,1);}.opening-preview{opacity:0.5;pointer-events:none;}.opening-preview[data-kind="passage"]{opacity:1;}.passage-preview-cut{fill:var(--wall-fill,#ffffff);fill-opacity:0.35;stroke:none;pointer-events:none;}.passage-preview-boundary{stroke:var(--hp-open,#ff9800);stroke-width:calc(2.5px * var(--hp-cell-visual-scale,1));pointer-events:none;}.opening-preview .op-leaf,.opening-preview .op-arc{transition:none;}.opening-preview-dot{fill:var(--hp-open,#ff9800);pointer-events:none;}.opening-dimensions,.opening-dimension{pointer-events:none;}.opening-dimension-line,.opening-dimension-tick{fill:none;stroke:var(--hp-open,#ff9800);stroke-width:1.5;vector-effect:non-scaling-stroke;pointer-events:none;}.opening-dimension-tick{stroke-width:2;}.stage.edit .room{pointer-events:none;}.stage.markup{cursor:crosshair;}.stage.markup.tool-merge,.stage.markup.tool-split.pickstage,.stage.markup.tool-delroom{cursor:pointer;}.stage.markup.tool-wallthick{cursor:default;}.stage.markup.tool-wallthick.wallhot{cursor:pointer;}.wallbody-fill{fill:var(--wall-fill,#ffffff);fill-opacity:var(--wall-fill-op,1);fill-rule:evenodd;stroke:none;pointer-events:none;}.wallbody{fill:url(#hp-wall-hatch);fill-rule:evenodd;stroke:var(--room-stroke,var(--hp-muted));stroke-width:calc(0.6px * var(--hp-cell-visual-scale,1));pointer-events:none;}.wallbody.solid{fill:none;}.wallthick-hover{fill:var(--accent-color,#03a9f4);fill-opacity:0.38;stroke:var(--accent-color,#03a9f4);stroke-width:calc(2.5px * var(--hp-cell-visual-scale,1));stroke-linejoin:round;stroke-linecap:round;pointer-events:none;}.wallthick-hover.isopen{fill:var(--error-color,#f44336);stroke:var(--error-color,#f44336);}.zero-wall{stroke:var(--zero-wall-stroke,var(--hp-muted));stroke-width:calc(2.5px * var(--hp-cell-visual-scale,1));stroke-dasharray:calc(7px * var(--hp-cell-visual-scale,1)) calc(7px * var(--hp-cell-visual-scale,1));stroke-linecap:butt;pointer-events:none;opacity:0.9;}.zero-walls.solid .zero-wall{stroke-dasharray:none;}.room.noedge{stroke-opacity:0 !important;}.room-outline{fill:none;stroke-width:calc(2.5px * var(--hp-cell-visual-scale,1));stroke-linejoin:round;stroke-linecap:round;pointer-events:none;}.room-outline.outlined{stroke:rgba(62,166,255,0.55);stroke-opacity:1;}.room-hover-fill{fill:#000;fill-opacity:0.22;pointer-events:none;}.room-hover-halo{fill:none;stroke:var(--hp-accent);stroke-opacity:0.28;stroke-width:calc(8px * var(--hp-cell-visual-scale,1));stroke-linejoin:round;stroke-linecap:round;pointer-events:none;}.room-hover-outline{fill:none;stroke:var(--hp-accent);stroke-width:calc(3px * var(--hp-cell-visual-scale,1));stroke-linejoin:round;stroke-linecap:round;pointer-events:none;}.stage.markup .room{pointer-events:none;}.stage.markup .devlayer .dev{display:none;}.stage.mode-plan{outline:2px solid #ffc14d;outline-offset:-2px;}.stage.mode-devices{outline:2px solid var(--hp-accent);outline-offset:-2px;}.room.outlined{stroke:rgba(62,166,255,0.55);fill:rgba(62,166,255,0.06);}.room.picked{stroke:#ffc14d;stroke-width:calc(3px * var(--hp-cell-visual-scale,1));fill:rgba(255,193,77,0.25);}.griddot{fill:var(--hp-accent);opacity:0.35;stroke:rgba(0,0,0,0.35);stroke-width:0.4;}.griddot.major{opacity:0.5;stroke-width:0;}.seg{stroke:var(--hp-accent);stroke-width:calc(2.5px * var(--hp-cell-visual-scale,1));stroke-linecap:round;stroke-linejoin:round;}.pathline{stroke:#ffc14d;stroke-width:calc(3px * var(--hp-cell-visual-scale,1));fill:none;stroke-linecap:round;stroke-linejoin:round;}.preview{stroke:#ffc14d;stroke-width:calc(2px * var(--hp-cell-visual-scale,1));stroke-dasharray:calc(6px * var(--hp-cell-visual-scale,1)) calc(5px * var(--hp-cell-visual-scale,1));opacity:0.7;}.active-axis{stroke:#ffc14d;stroke-width:2;stroke-linecap:round;vector-effect:non-scaling-stroke;pointer-events:none;}.active-vertex{fill:#ffc14d;stroke:#171006;stroke-width:2;vector-effect:non-scaling-stroke;pointer-events:none;}.wall-repair-preview{stroke:#d93025;stroke-width:4;stroke-linecap:round;stroke-dasharray:5 4;vector-effect:non-scaling-stroke;pointer-events:none;}.drawwall-preview-fill{fill:var(--wall-fill,#ffffff);fill-opacity:calc(var(--wall-fill-op,1) * 0.55);fill-rule:evenodd;stroke:none;pointer-events:none;}.drawwall-preview{fill:url(#hp-wall-hatch);fill-opacity:0.55;fill-rule:evenodd;stroke:var(--accent-color,#03a9f4);stroke-width:calc(0.5px * var(--hp-cell-visual-scale,1));stroke-opacity:0.7;pointer-events:none;}.drawwall-zero-preview{fill:none;stroke:var(--accent-color,#03a9f4);stroke-width:calc(3px * var(--hp-cell-visual-scale,1));stroke-linecap:butt;stroke-linejoin:round;opacity:0.72;pointer-events:none;}.drawwall-zero-preview.dashed{stroke-dasharray:calc(7px * var(--hp-cell-visual-scale,1)) calc(7px * var(--hp-cell-visual-scale,1));}.vertex{fill:#ffc14d;stroke:#4a2800;stroke-width:calc(1px * var(--hp-cell-visual-scale,1));}.vertex.first{fill:#4bd28f;stroke:#04121f;}.plan-snap-overlay,.plan-snap-overlay *,.hidden-wall-diagnostic,.hidden-wall-diagnostic *{pointer-events:none;}.plan-snap-line,.hidden-wall-line{fill:none;stroke:color-mix(in srgb,var(--hp-accent) 82%,white 18%);stroke-width:1;stroke-linecap:round;opacity:0.92;}.plan-snap-node,.hidden-wall-node{fill:var(--ha-card-background,var(--card-background-color,#fff));stroke:color-mix(in srgb,var(--hp-accent) 88%,#07131c 12%);stroke-width:1;vector-effect:non-scaling-stroke;}.plan-snap-node.active{fill:#ffc14d;stroke:#171006;stroke-width:2;}.plan-snap-node.active.dynamic{fill:#4bd28f;stroke:#04121f;}.plan-snap-node.conflict{fill:#fff;stroke:#d93025;stroke-width:3;}@media (prefers-color-scheme:dark){.plan-snap-line{stroke:color-mix(in srgb,var(--hp-accent) 72%,white 28%);}.hidden-wall-line{stroke:color-mix(in srgb,var(--hp-accent) 72%,white 28%);}.plan-snap-node,.hidden-wall-node{fill:#17242c;stroke:#9bdcf5;}.plan-snap-node.active{fill:#ffc14d;stroke:#fff4d6;}.plan-snap-node.active.dynamic{fill:#4bd28f;stroke:#eafff4;}}@media (forced-colors:active){.plan-snap-line,.hidden-wall-line{stroke:CanvasText;opacity:1;forced-color-adjust:auto;}.plan-snap-node,.hidden-wall-node{fill:Canvas;stroke:CanvasText;forced-color-adjust:auto;}.plan-snap-node.active,.plan-snap-node.active.dynamic{fill:Highlight;stroke:HighlightText;forced-color-adjust:auto;}}.sunlayer{animation:hp-sunfade-in 2s linear both;}.sunlayer.out{animation:hp-sunfade-out 2s linear both;}@media (prefers-reduced-motion:reduce){.sunlayer,.sunlayer.out{animation:none;}.sunlayer.out{opacity:0;}}.devlayer{position:absolute;inset:0;pointer-events:none;z-index:6;}.radar-target{position:absolute;width:8px;height:8px;box-sizing:border-box;transform:translate(-50%,-50%);border-radius:50%;background:var(--success-color,#43a047);border:2px solid var(--primary-text-color,#1f1f1f);box-shadow:0 0 0 1px color-mix(in srgb,var(--card-background-color,#fff) 80%,transparent);pointer-events:none;z-index:0;}.radar-target.smooth{transition:left 200ms linear,top 200ms linear;}.radar-ranges{position:absolute;inset:0;width:100%;height:100%;overflow:visible;pointer-events:none;z-index:0;}.radar-ranges path,.radar-ranges polyline{fill:none;stroke:var(--success-color,#43a047);stroke-width:2px;stroke-dasharray:5 4;vector-effect:non-scaling-stroke;opacity:0.72;}.radar-ranges .radar-zone{fill:color-mix(in srgb,var(--success-color,#43a047) 8%,transparent);stroke:var(--success-color,#43a047);stroke-width:2px;vector-effect:non-scaling-stroke;opacity:0.8;}.stage.mode-devices .dev{cursor:grab;}.stage.mode-devices .dev:active{cursor:grabbing;}.physical-hit{fill:transparent;stroke:transparent;pointer-events:none;cursor:grab;}.stage.tool-select .physical-hit{pointer-events:all;}.physical-hit:active{cursor:grabbing;}line.physical-hit{cursor:pointer;}.physical-hit.selected{fill:rgba(255,193,77,0.24);stroke:transparent;}line.physical-hit.selected{stroke:transparent;}.physical-drag{fill:rgba(255,193,77,0.38);stroke:#ffc14d;stroke-width:2.5;vector-effect:non-scaling-stroke;pointer-events:none;}.physical-chrome{pointer-events:none;}.physical-chrome .frame,.physical-chrome .stem{fill:none;stroke:#ffc14d;stroke-width:2;vector-effect:non-scaling-stroke;}.physical-chrome .frame{fill:rgba(255,193,77,0.22);}.physical-chrome polyline.frame{fill:none;}.physical-chrome .move-dot{fill:#ffc14d;stroke:#24262d;stroke-width:1.5;vector-effect:non-scaling-stroke;}.physical-chrome .rotate-handle{fill:#24262d;stroke:#ffc14d;stroke-width:2.5;vector-effect:non-scaling-stroke;pointer-events:all;cursor:crosshair;}.drawwall.invalid input{border-color:var(--error-color,#db4437);}.drawwall .rangehint{margin-inline-start:4px;font-size:0.78em;opacity:0.72;}.drawwall.invalid .rangehint{color:var(--error-color,#db4437);opacity:1;}.stage.markup.tool-partition,.stage.markup.tool-column{cursor:crosshair;}.rszhandle{fill:transparent;stroke:none;pointer-events:all;cursor:grab;touch-action:none;}.rszhandle:active{cursor:grabbing;}.rszhandle.disabled,.rszhandle.disabled:active{cursor:not-allowed;}.rszicon{pointer-events:none;}.rszicon path{fill:none;stroke-linecap:round;stroke-linejoin:round;vector-effect:non-scaling-stroke;}.rszhalo{stroke:var(--hp-bg);stroke-width:6;}.rszink{stroke:var(--hp-accent);stroke-width:2;}:host([data-pointer-hover]) .rszhandle:hover + .rszicon .rszink{stroke-width:3;}.rszicon.disabled{opacity:0.38;}:host([data-pointer-hover]) .rszhandle.disabled:hover + .rszicon .rszink{stroke-width:2;}.rszmeasurelayer,.rszmeasurelayer *{pointer-events:none;}.rszmeasurehalo,.rszmeasureink,.rszleader{fill:none;stroke-linecap:round;vector-effect:non-scaling-stroke;}.rszmeasurehalo{stroke:var(--hp-bg);stroke-width:7px;opacity:0.9;}.rszmeasureink{stroke:var(--hp-accent);stroke-width:3px;}.rszleader{stroke:var(--hp-accent);stroke-width:2px;opacity:0.95;}.measurelabel.dmeasure{transform:translate(-50%,-160%);}.measurelabel.rszarea{transform:translate(calc(-50% + var(--rsz-label-x,0px)),calc(-50% + var(--rsz-label-y,0px)));background:rgba(0,0,0,0.6);border:1px solid var(--hp-accent);}.measurelabel.furnmeasure{transform:translate(-50%,-50%);border:1px solid var(--hp-accent);}.alignmsg{margin:0 0 8px;font-size:13px;line-height:1.45;}`,o`.dev ha-icon{position:relative;z-index:1;}.device-pulse{position:absolute;left:50%;top:50%;width:var(--dev-size);height:var(--dev-size);transform:translate(-50%,-50%);pointer-events:none;z-index:0;}.device-pulse i{position:absolute;inset:0;border-radius:50%;border:2px solid var(--ripple-color,var(--hp-accent));opacity:0;}.device-pulse.short i{animation:hp-pulse-short 1.1s cubic-bezier(.22,.61,.36,1) 1 forwards;}.device-pulse.short i:nth-child(2){animation-delay:1.1s;}.device-pulse.short i:nth-child(3){animation-delay:2.2s;}.device-pulse.short.gen2 i{animation-name:hp-pulse-short-b;}.device-pulse.continuous i:nth-child(n + 2),.device-pulse.alarm i:nth-child(n + 3){display:none;}.device-pulse.continuous i:first-child{animation:hp-pulse-continuous 3.6s cubic-bezier(.45,.05,.55,.95) infinite;}.device-pulse.alarm i{border-width:3px;border-color:#F0410C;animation:hp-pulse-alarm 2.4s cubic-bezier(.22,.61,.36,1) infinite;}.device-pulse.alarm i:nth-child(2){animation-delay:1.2s;}.activity-dot{position:absolute;right:8%;bottom:8%;width:18%;height:18%;min-width:4px;min-height:4px;border-radius:50%;background:var(--ripple-color,var(--hp-accent));border:1px solid color-mix(in srgb,var(--hp-bg) 82%,transparent);pointer-events:none;z-index:3;}.kioskdots{position:absolute;left:50%;bottom:var(--sp-5);transform:translateX(-50%);display:flex;gap:var(--sp-4);z-index:5;pointer-events:none;}.kdot{width:9px;height:9px;border-radius:50%;background:var(--hp-muted);opacity:0.55;}.kdot.on{background:var(--hp-accent);opacity:1;}.dev.valonly{width:var(--dev-size,var(--icon-size,2.5cqw));}.dev.valonly .device-core{width:max-content;min-width:var(--dev-size,var(--icon-size,2.5cqw));padding-inline:calc(var(--dev-size,var(--icon-size,2.5cqw)) * 0.16);border-radius:calc(var(--dev-size,var(--icon-size,2.5cqw)) / 2);}.dev .valtext{overflow:visible;font-size:calc(var(--dev-size,var(--icon-size,2.5cqw)) * var(--value-font-scale,.45));font-weight:600;white-space:nowrap;}@media (prefers-reduced-motion:reduce){.device-pulse{display:none;}}.dev .newdot{position:absolute;top:calc(var(--dev-size,var(--icon-size,2.5cqw)) * -0.12);right:calc(var(--dev-size,var(--icon-size,2.5cqw)) * -0.12);width:calc(var(--dev-size,var(--icon-size,2.5cqw)) * 0.34);height:calc(var(--dev-size,var(--icon-size,2.5cqw)) * 0.34);border-radius:50%;background:#f0301f;border:2px solid var(--card-background-color,var(--hp-bg));pointer-events:none;z-index:2;}.dev{position:absolute;--dev-size:calc(var(--device-base-size,2.25cqw) * var(--dev-scale,1));--device-shell-size:calc(var(--dev-size) * 1.26875);--device-shell-inset:calc(var(--dev-size) * 0.134375);--device-shell-stroke-ratio:0.01875;--device-shell-border-width:max(1px,calc(var(--dev-size) * var(--device-shell-stroke-ratio)));--device-core-bg:var(--card-background-color,#fff);--device-core-fg:var(--primary-text-color,#252525);--device-core-bg:light-dark(#fff,#252525);--device-core-fg:light-dark(#252525,#fff);--device-face-bg:var(--device-core-bg);--device-face-fg:var(--device-core-fg);--device-shell-base-stroke:light-dark(#BCBCBC,rgb(37 37 37 / 75%));--device-shell-stroke:var(--device-shell-base-stroke);--device-shell-shadow:0 calc(var(--dev-size) * .025) calc(var(--dev-size) * .05) rgb(37 40 45 / 12%),0 calc(var(--dev-size) * .1) calc(var(--dev-size) * .175) calc(var(--dev-size) * -.025) rgb(37 40 45 / 18%);--device-core-inset-shadow:0 0 0 0 transparent;--device-ring-color:transparent;--device-ring-width:0px;width:var(--dev-size);height:var(--dev-size);margin:calc(var(--dev-size) / -2) 0 0 calc(var(--dev-size) / -2);border:0;background:transparent;display:block;color:var(--device-core-fg);cursor:pointer;pointer-events:none;transition:opacity 0.2s;box-shadow:none;outline:none;z-index:auto;}.dev.theme-light{--device-core-bg:#fff;--device-core-fg:#000;--device-shell-base-stroke:#BCBCBC;--device-shell-stroke:var(--device-shell-base-stroke);--device-shell-shadow:0 calc(var(--dev-size) * .025) calc(var(--dev-size) * .05) rgb(37 40 45 / 12%),0 calc(var(--dev-size) * .1) calc(var(--dev-size) * .175) calc(var(--dev-size) * -.025) rgb(37 40 45 / 18%);--device-core-inset-shadow:0 0 0 0 transparent;}.dev.theme-dark{--device-core-bg:#252525;--device-core-fg:#fff;--device-shell-base-stroke:rgb(37 37 37 / 75%);--device-shell-stroke:var(--device-shell-base-stroke);--device-shell-shadow:0 calc(var(--dev-size) * .025) calc(var(--dev-size) * .0375) rgb(37 40 45 / 12%),0 calc(var(--dev-size) * .1) calc(var(--dev-size) * .175) calc(var(--dev-size) * -.025) rgb(37 40 45 / 18%);--device-core-inset-shadow:inset 0 calc(var(--dev-size) * 0.0125) calc(var(--dev-size) * 0.0125) rgb(255 255 255 / 70%);}.dev::before{content:'';position:absolute;left:50%;top:50%;width:max(44px,var(--device-shell-size));height:max(44px,var(--device-shell-size));transform:translate(-50%,-50%);border-radius:50%;pointer-events:auto;z-index:1;}.device-shell{position:absolute;box-sizing:border-box;display:flex;align-items:center;gap:calc(var(--dev-size) * 0.1);padding:0;min-width:var(--dev-size);min-height:var(--dev-size);border:0;background:transparent;box-shadow:none;transition:opacity .2s;pointer-events:none;z-index:2;}.device-shell-frame{position:absolute;z-index:0;box-sizing:border-box;inset:calc(var(--device-shell-inset) / -1);border:var(--device-shell-border-width) solid var(--device-shell-stroke);border-radius:9999px;background:transparent;box-shadow:var(--device-shell-shadow);transition:border-color .15s,opacity .2s;pointer-events:auto;backdrop-filter:none;}.device-shell:not(.with-values){left:0;top:0;}.device-shell:not(.with-values):not(.text-shell) .device-shell-frame{border-radius:50%;}.device-shell.with-values.pos-right{left:0;top:50%;transform:translateY(-50%);}.device-shell.with-values.pos-left{right:0;top:50%;transform:translateY(-50%);flex-direction:row-reverse;}.device-shell.with-values.pos-bottom{left:50%;top:0;transform:translateX(-50%);flex-direction:column;}.device-shell.with-values.pos-top{left:50%;bottom:0;transform:translateX(-50%);flex-direction:column-reverse;}.device-core{position:relative;z-index:1;box-sizing:border-box;flex:0 0 auto;width:var(--dev-size);height:var(--dev-size);display:flex;align-items:center;justify-content:center;border-radius:50%;background:var(--device-face-bg);color:var(--device-face-fg);box-shadow:var(--device-core-inset-shadow),0 0 0 var(--device-ring-width) var(--device-ring-color);line-height:0;transition:background .15s,color .15s,opacity .2s;pointer-events:none;}.device-sections{display:flex;flex-direction:column;align-items:stretch;justify-content:center;gap:calc(var(--dev-size) * .08);min-width:0;pointer-events:none;}.device-shell.pos-top .device-sections,.device-shell.pos-bottom .device-sections{flex-direction:row;}.dev ha-icon{--mdc-icon-size:calc(var(--dev-size,var(--device-base-size,2.25cqw)) * 0.55);display:flex;align-items:center;justify-content:center;line-height:0;}.dev.on{--device-face-bg:#F0A00C;--device-face-fg:light-dark(#fff,#252525);--device-shell-stroke:#F0A00C;}.dev.theme-light.on{--device-face-fg:#fff;}.dev.theme-dark.on{--device-face-fg:#252525;--device-shell-stroke-ratio:.0375;}.dev.open{--device-face-bg:var(--hp-open);--device-face-fg:light-dark(#fff,#252525);}.dev.theme-light.open{--device-face-fg:#fff;}.dev.theme-dark.open{--device-face-fg:#252525;}.dev.lock-locked{--device-face-bg:#66D17A;--device-face-fg:light-dark(#fff,#252525);--device-shell-stroke:#66D17A;}.dev.theme-light.lock-locked{--device-face-fg:#fff;}.dev.theme-dark.lock-locked{--device-face-fg:#252525;--device-shell-stroke-ratio:.025;}.dev.lock-unlocked{--device-face-bg:#F0410C;--device-face-fg:light-dark(#fff,#252525);--device-shell-stroke:#F0410C;}.dev.theme-light.lock-unlocked{--device-face-fg:#fff;}.dev.theme-dark.lock-unlocked{--device-face-fg:#252525;--device-shell-stroke-ratio:.025;}:host([data-pointer-hover]) .dev:not(.unavail)[data-hp-device-hover]{--device-face-bg:#0C82F0;--device-face-fg:light-dark(#fff,#252525);--device-shell-stroke:var(--device-shell-base-stroke);}:host([data-pointer-hover]) .dev.theme-light:not(.unavail)[data-hp-device-hover]{--device-face-fg:#fff;}:host([data-pointer-hover]) .dev.theme-dark:not(.unavail)[data-hp-device-hover]{--device-face-fg:#252525;}:host([data-pointer-hover]) .dev[data-hp-device-hover],.dev:focus-visible{z-index:5;}.dev[data-hp-zigbee-topology-endpoint]{z-index:8;}:host([data-pointer-hover]) .dev[data-hp-zigbee-topology-endpoint][data-hp-device-hover]{z-index:8;}.dev.unavail{opacity:0.35;--device-face-bg:#B5BAC1;--device-shell-stroke:var(--device-shell-base-stroke);}.dev.virtual .device-shell-frame{border-style:dashed;}.dev.ghost{opacity:0.6;color:var(--hp-accent);}.dev.ghost .device-shell-frame{border-style:dashed;border-color:var(--hp-accent);box-shadow:none;}.dev.ghost .device-core{background:rgba(62,166,255,0.22);background:color-mix(in srgb,var(--hp-accent) 30%,var(--card-background-color,#1c2530));color:var(--hp-accent);}.dev.ghost.ha-disabled{opacity:0.62;color:var(--secondary-text-color,#9aa0aa);}.dev.ghost.ha-disabled .device-shell-frame{border-color:var(--secondary-text-color,#9aa0aa);}.dev.ghost.ha-disabled .device-core{background:rgba(120,124,134,0.2);background:color-mix(in srgb,var(--secondary-text-color,#9aa0aa) 24%,var(--card-background-color,#1c2530));color:var(--secondary-text-color,#9aa0aa);}.dev .habadge{position:absolute;right:-18%;bottom:-18%;display:grid;place-items:center;width:46%;height:46%;min-width:12px;min-height:12px;border-radius:50%;background:var(--card-background-color,#242832);border:1px solid currentColor;}.dev .habadge ha-icon{width:72%;height:72%;}.dev.sel{--device-ring-color:#F0A00C;--device-ring-width:calc(var(--dev-size) * 0.0375);}.dev:focus-visible{--device-ring-color:#0C82F0;--device-ring-width:calc(var(--dev-size) * 0.0375);}.dev:not(.on):not(.open):not(.alarm):not(.lock-locked):not(.lock-unlocked):not(.unavail):focus-visible{--device-face-fg:#0C82F0;}.dev.alarm,:host([data-pointer-hover]) .dev.alarm[data-hp-device-hover],.dev.alarm:focus-visible{--device-face-bg:#F0410C;--device-face-fg:light-dark(#fff,#252525);--device-shell-stroke:#F0410C;}.dev.theme-light.alarm{--device-face-fg:#fff;}.dev.theme-dark.alarm{--device-face-fg:#252525;--device-shell-stroke-ratio:.025;}.dev .value-badge{position:relative;z-index:2;box-sizing:border-box;width:max-content;min-width:calc(var(--dev-size,var(--icon-size,2.5cqw)) * .7875);height:calc(var(--dev-size,var(--icon-size,2.5cqw)) * .7875);display:flex;align-items:center;justify-content:center;overflow:visible;background:var(--device-core-bg);border:0;border-radius:calc(var(--dev-size,var(--icon-size,2.5cqw)) * 0.39375);padding:0 calc(var(--dev-size,var(--icon-size,2.5cqw)) * 0.14);font-size:calc(var(--dev-size,var(--icon-size,2.5cqw)) * var(--value-font-scale,.45));font-weight:600;line-height:1;color:var(--device-core-fg);white-space:nowrap;pointer-events:none;}.dev .value-badge.unavailable,.dev .value-badge.missing{opacity:0.66;}.dev .lqi{position:absolute;top:calc(50% + var(--device-shell-size) / 2 + var(--dev-size) * .05);left:50%;transform:translateX(-50%);margin-top:calc(var(--dev-size,var(--icon-size,2.5cqw)) * 0.05);font-size:calc(var(--dev-size,var(--icon-size,2.5cqw)) * 0.38);font-weight:600;line-height:1;text-shadow:0 0 3px rgba(0,0,0,0.9),0 0 2px rgba(0,0,0,0.9);white-space:nowrap;pointer-events:none;}.dev .lqi.below-value-badge{margin-top:calc(var(--dev-size,var(--icon-size,2.5cqw)) * 0.8875);}.temprange{display:inline-flex;align-items:center;gap:var(--sp-3);margin-left:auto;color:var(--hp-muted);font-size:var(--fs-s);}.vacwarn{position:absolute;top:-12%;right:-12%;width:calc(var(--device-base-size,2.25cqw) * 0.42);height:calc(var(--device-base-size,2.25cqw) * 0.42);border-radius:50%;display:flex;align-items:center;justify-content:center;background:light-dark(#fff,#252525);border:1px solid #E5A100;color:#E5A100;z-index:7;pointer-events:none;}.vacwarn ha-icon{--mdc-icon-size:calc(var(--device-base-size,2.25cqw) * 0.32);color:inherit;}.vacpuck{position:absolute;--puck-size:calc(var(--device-base-size,2.25cqw) * 0.8);width:var(--puck-size);height:var(--puck-size);border-radius:50%;transform:translate(-50%,-50%);--vac-core-bg:light-dark(#fff,#252525);--vac-core-fg:light-dark(#252525,#fff);background:var(--vac-core-bg);border:1px solid #BCBCBC;box-shadow:0 1px 2px rgb(37 40 45 / 12%),0 4px 8px -1.07px rgb(37 40 45 / 18%);color:var(--vac-core-fg);display:flex;align-items:center;justify-content:center;cursor:pointer;z-index:6;transition:left 1.2s linear,top 1.2s linear;animation:vacpulse 2.2s ease-out infinite;}.vacpuck.theme-light{--vac-core-bg:#fff;--vac-core-fg:#252525;}.vacpuck.theme-dark{--vac-core-bg:#252525;--vac-core-fg:#fff;}.vacpuck.jump{transition:none;}.vacpuck.stale{opacity:0.45;animation:none;}.vacpuck ha-icon{--mdc-icon-size:calc(var(--puck-size) * 0.68);color:var(--vac-core-fg);display:flex;align-items:center;justify-content:center;line-height:0;width:var(--mdc-icon-size);height:var(--mdc-icon-size);}@keyframes vacpulse{0%{box-shadow:0 0 0 0 color-mix(in srgb,var(--hp-accent) 45%,transparent);}70%{box-shadow:0 0 0 12px transparent;}100%{box-shadow:0 0 0 0 transparent;}}@media (prefers-reduced-motion:reduce){.vacpuck{animation:none;}}.vactrail{position:absolute;inset:0;width:100%;height:100%;pointer-events:none;z-index:5;overflow:visible;}.vactrail polyline,.vactrail path{fill:none;stroke-linejoin:round;stroke-linecap:round;vector-effect:non-scaling-stroke;}.vactrail g.prev{opacity:0.4;}.vactrail .case{stroke:rgba(0,0,0,0.4);stroke-width:2.25;}.vactrail .core{stroke:rgba(255,255,255,0.82);stroke-width:0.9;}.devicepreview-empty{min-height:82px;margin:4px 0 14px;padding:var(--sp-4);display:flex;align-items:center;justify-content:center;gap:var(--sp-3);border:1px dashed var(--hp-line);border-radius:var(--rad-m);color:var(--hp-muted);text-align:center;}`,o`.hdr{position:sticky;top:var(--header-height,56px);z-index:20;background:var(--card-background-color,var(--hp-bg));border-radius:var(--ha-card-border-radius,12px) var(--ha-card-border-radius,12px) 0 0;}.tabs{display:flex;gap:var(--sp-2);background:rgba(127,127,127,0.12);padding:var(--sp-2);border-radius:var(--rad-l);flex-wrap:wrap;}.tab{border:0;background:transparent;color:var(--hp-muted);display:inline-flex;align-items:center;padding:var(--sp-3) var(--sp-5);border-radius:var(--rad-m);font-size:var(--fs-m);font-weight:600;cursor:pointer;transition:0.15s;font-family:inherit;}:host([data-pointer-hover]) .tab:hover{color:var(--hp-txt);}.tab.active{background:var(--hp-accent);color:var(--text-primary-color,#fff);}.farhint{position:absolute;left:50%;transform:translateX(-50%);bottom:var(--sp-4);z-index:12;display:flex;align-items:center;gap:var(--sp-2);max-width:calc(100% - var(--sp-8));background:var(--card-background-color,var(--hp-bg));opacity:0.94;color:var(--hp-txt);border:1px solid var(--divider-color,#33404d);border-radius:var(--rad-m);padding:var(--sp-1) var(--sp-3);font-size:var(--fs-s);}.farhint ha-icon{--mdc-icon-size:18px;color:var(--hp-warn,#e2a03f);flex:none;}.farhint span{white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}.dropbtn{display:flex;align-items:center;gap:var(--sp-4);width:100%;text-align:left;border:1px solid var(--hp-muted);border-radius:var(--rad-m);background:transparent;color:var(--hp-txt);padding:var(--sp-4) 10px;cursor:pointer;font-family:inherit;font-size:var(--fs-m);margin-top:var(--sp-3);}.dropbtn .ref{color:var(--hp-muted);font-size:var(--fs-s);margin-left:auto;}.dropbtn ha-icon{--mdc-icon-size:18px;margin-left:var(--sp-2);}.dropbtn.open{border-color:var(--hp-accent);}.droppanel{border:1px solid var(--hp-accent);border-top:none;border-radius:0 0 var(--rad-m) var(--rad-m);padding:var(--sp-3);margin-top:-4px;}.hdr.kioskhide{display:none;}.decorbar .dcolor{width:30px;height:26px;padding:0;border:none;background:none;cursor:pointer;}.decorbar .dwidth{font-family:inherit;font-size:var(--fs-s);border-radius:var(--rad-s);background:var(--hp-bg2,transparent);color:var(--hp-txt);border:1px solid var(--hp-muted);padding:var(--sp-2) var(--sp-3);}.decorbar .bdhint{font-size:var(--fs-s);color:var(--hp-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}.decorbar .dfill{display:inline-flex;align-items:center;gap:var(--sp-2);font-size:var(--fs-s);cursor:pointer;}.decorbar .dfill input[type="checkbox"]{width:16px;height:16px;flex:none;margin:0;padding:0;}.decorbar hp-color-opacity{flex:0 0 auto;}.modes{display:inline-flex;gap:var(--sp-1);background:rgba(127,127,127,0.12);border-radius:var(--rad-l);padding:var(--sp-2);}.modetab{display:inline-flex;align-items:center;gap:var(--sp-3);border:0;background:transparent;color:var(--hp-muted);padding:var(--sp-3) 10px;border-radius:var(--rad-m);font-size:var(--fs-m);font-weight:600;cursor:pointer;font-family:inherit;transition:background-color 0.14s ease,color 0.14s ease,transform 0.14s ease;}.modetab:active{transform:scale(0.97);}.modetab ha-icon{--mdc-icon-size:15px;}.tab[data-reorderable]{cursor:grab;}.tab.dragging{cursor:grabbing;opacity:0.55;}.tab.drop-before{box-shadow:inset 2px 0 0 0 var(--primary-color,#03a9f4);}.tab.drop-after{box-shadow:inset -2px 0 0 0 var(--primary-color,#03a9f4);}.modetab .closex{--mdc-icon-size:13px;box-sizing:border-box;display:inline-flex;align-items:center;justify-content:center;width:24px;height:24px;min-width:24px;min-height:24px;margin:-5.5px -5.5px -5.5px -3.5px;opacity:0.75;cursor:pointer;border-radius:var(--rad-s);}:host([data-pointer-hover]) .modetab .closex:hover{opacity:1;}.editbar .barclose{box-sizing:border-box;width:40px;height:40px;padding:0;margin:0;min-width:40px;min-height:40px;justify-content:center;gap:0;line-height:0;}.editbar .barclose ha-icon{flex:none;margin:0;}.modetab.active{background:var(--hp-accent);color:var(--text-primary-color,#fff);}@media (max-width:720px){.modetab .ml{display:none;}}.editbar{display:grid;grid-template-columns:minmax(0,1fr) auto;align-items:stretch;border-bottom:1px solid var(--hp-line);font-size:var(--fs-m);}.editbar-tools{display:flex;align-items:center;gap:10px;padding:var(--sp-4) var(--sp-5);flex-wrap:wrap;min-width:0;outline:none;}.editbar-end{display:flex;align-items:center;padding:var(--sp-4) var(--sp-5);border-inline-start:1px solid var(--hp-line);background:var(--card-background-color,var(--hp-bg));position:relative;z-index:2;}.tab .tabedit{--mdc-icon-size:13px;display:inline-flex;align-items:center;margin-left:var(--sp-3);opacity:0.4;}:host([data-pointer-hover]) .tab:hover .tabedit{opacity:0.9;}.tab.tabadd{padding:var(--sp-3) var(--sp-4);}.tab.tabadd ha-icon{--mdc-icon-size:15px;}.rhint{font-size:var(--fs-s);color:var(--hp-muted);margin-bottom:var(--sp-3);}.togglehint{overflow-wrap:anywhere;}.togglehint>div + div{margin-top:var(--sp-1);}.editorchrome{display:block;height:0;opacity:0;visibility:hidden;overflow:hidden;}.editorchrome:not(.open){pointer-events:none;}.editorchrome.open{height:auto;opacity:1;visibility:visible;overflow:visible;}.editorchrome.transitioning{overflow:hidden;will-change:height;pointer-events:none;}.editorchrome.transitioning .barclose{pointer-events:auto;}.editorchrome-inner{min-height:0;transform-origin:top center;}.editorchrome.transitioning .editorchrome-inner{will-change:opacity;}@media (prefers-reduced-motion:reduce){.modetab{transition:none;}}.editbar .warn{color:#ffc14d;}.editbar .sname{font-weight:600;}.editbar input{width:74px;background:transparent;border:1px solid var(--hp-line);color:var(--hp-txt);border-radius:var(--rad-s);padding:var(--sp-3) var(--sp-4);font-size:var(--fs-m);}.editbar label,.editbar .hint{color:var(--hp-muted);font-size:var(--fs-s);}.editbar .drawwall{display:inline-flex;align-items:center;gap:var(--sp-3);white-space:nowrap;}.editbar .wallsgroup{display:inline-flex;align-items:center;gap:10px;white-space:nowrap;}.editbar .drawwall input{width:4.2em;}.editbar .drawwall .opl{color:var(--hp-muted);font-size:var(--fs-s);}.menuwrap{position:fixed;inset:0;z-index:80;}.menu{position:fixed;background:var(--hp-bg);border:1px solid var(--hp-accent);border-radius:var(--rad-l);box-shadow:var(--shadow-2);min-width:210px;max-width:300px;overflow:hidden;transform:translate(0,8px);}.menu .hd{padding:var(--sp-4) var(--sp-5);font-weight:600;font-size:var(--fs-m);border-bottom:1px solid var(--hp-line);display:flex;align-items:center;gap:var(--sp-3);}.menu .hd ha-icon,.menu .it.all ha-icon{color:var(--hp-accent);--mdc-icon-size:16px;}.menu .it{padding:var(--sp-4) var(--sp-5);font-size:var(--fs-m);cursor:pointer;display:flex;align-items:center;gap:var(--sp-4);}.menu .it ha-icon{--mdc-icon-size:16px;color:var(--hp-muted);}:host([data-pointer-hover]) .menu .it:hover{background:rgba(127,127,127,0.15);}.menu .it.all{color:var(--hp-accent);font-weight:600;}.tip{position:fixed;pointer-events:none;background:var(--hp-bg);border:1px solid var(--hp-accent);color:var(--hp-txt);padding:var(--sp-3) 10px;border-radius:var(--rad-m);font-size:var(--fs-m);box-shadow:var(--shadow-2);z-index:60;max-width:260px;}.tip .m{color:var(--hp-muted);font-size:var(--fs-s);display:block;}`,o`.head{display:flex;align-items:center;gap:10px;padding:10px var(--sp-5);border-bottom:1px solid var(--hp-line);flex-wrap:wrap;}.title{font-size:var(--fs-l);font-weight:600;display:flex;align-items:center;gap:var(--sp-3);white-space:nowrap;}.title ha-icon{color:var(--hp-accent);--mdc-icon-size:18px;}@media (max-width:1100px){.head .count{display:none;}}@media (max-width:620px){.head{gap:var(--sp-3);padding:var(--sp-4) 10px;}.head .title{font-size:var(--fs-m);}}.count{font-size:var(--fs-s);color:var(--hp-muted);}.btn{display:inline-flex;align-items:center;gap:var(--sp-3);border:1px solid var(--hp-line);background:transparent;color:var(--hp-txt);padding:var(--sp-3) 10px;border-radius:var(--rad-m);cursor:pointer;transition:0.15s;font-family:inherit;font-size:var(--fs-m);}.btn ha-icon{--mdc-icon-size:17px;}:host([data-pointer-hover]) .btn:hover{border-color:var(--hp-accent);}.btn.on{background:var(--hp-accent);color:var(--text-primary-color,#fff);border-color:var(--hp-accent);}.btn.ghost{border:none;}.btn[disabled]{opacity:0.5;pointer-events:none;}.sunrow{display:flex;align-items:center;gap:var(--sp-5);margin:var(--sp-3) 0;}.suncol{flex:1;display:flex;flex-direction:column;gap:var(--sp-3);min-width:0;}.recoveryoverlay{position:absolute;inset:0;z-index:75;display:flex;flex-direction:column;align-items:center;justify-content:center;gap:var(--sp-4);padding:var(--sp-6);box-sizing:border-box;background:linear-gradient(var(--ha-card-background,var(--card-background-color,#111)),var(--ha-card-background,var(--card-background-color,#111))),#111;color:var(--primary-text-color,#fff);text-align:center;pointer-events:auto;transition:opacity 0.15s ease;}.recoveryoverlay.phase-entering,.recoveryoverlay.phase-leaving{opacity:0;}.recoveryoverlay.phase-fading-in,.recoveryoverlay.phase-opaque{opacity:1;}.recoveryoverlay ha-icon{--mdc-icon-size:44px;color:var(--hp-accent);}.editorloading{position:absolute;z-index:74;left:50%;top:50%;display:flex;align-items:center;gap:var(--sp-3);padding:var(--sp-3) var(--sp-5);border:1px solid color-mix(in srgb,var(--hp-accent) 45%,transparent);border-radius:999px;background:color-mix(in srgb,var(--ha-card-background,var(--card-background-color,#111)) 92%,transparent);color:var(--primary-text-color);box-shadow:0 6px 22px rgb(0 0 0 / 18%);transform:translate(-50%,-50%);pointer-events:none;animation:editor-loading-in 0.15s ease both;}.editorloading ha-icon{--mdc-icon-size:22px;color:var(--hp-accent);animation:editor-loading-spin 0.9s linear infinite;}@keyframes editor-loading-in{from{opacity:0;transform:translate(-50%,calc(-50% + 4px));}to{opacity:1;transform:translate(-50%,-50%);}}@keyframes editor-loading-spin{to{transform:rotate(360deg);}}@media (prefers-reduced-motion:reduce){.recoveryoverlay,.editorloading,.editorloading ha-icon{transition:none;animation:none;}}.oplock{--oplock-size:calc(var(--icon-size,2.5cqw) * 0.62);--oplock-core-size:calc(var(--oplock-size) / 1.26875);--oplock-stroke-ratio:0.01875;--oplock-stroke-width:max(1px,calc(var(--oplock-core-size) * var(--oplock-stroke-ratio)));--oplock-core-bg:light-dark(#fff,#252525);--oplock-core-fg:light-dark(#252525,#fff);--oplock-shell-stroke:light-dark(#BCBCBC,rgb(37 37 37 / 75%));--oplock-shell-shadow:0 calc(var(--oplock-core-size) * .025) calc(var(--oplock-core-size) * .05) rgb(37 40 45 / 12%),0 calc(var(--oplock-core-size) * .1) calc(var(--oplock-core-size) * .175) calc(var(--oplock-core-size) * -.025) rgb(37 40 45 / 18%);--oplock-core-shadow:0 0 0 0 transparent;pointer-events:none;position:absolute;transform:translate(-50%,-50%);width:var(--oplock-size);height:var(--oplock-size);display:grid;place-items:center;border:0;background:transparent;z-index:1;}.oplock.theme-light{--oplock-core-bg:#fff;--oplock-core-fg:#252525;--oplock-shell-stroke:#BCBCBC;}.oplock.theme-dark{--oplock-core-bg:#252525;--oplock-core-fg:#fff;--oplock-shell-stroke:rgb(37 37 37 / 75%);--oplock-core-shadow:inset 0 calc(var(--oplock-core-size) * .0125) calc(var(--oplock-core-size) * .0125) rgb(255 255 255 / 70%);}.oplock-shell{box-sizing:border-box;width:100%;height:100%;border:var(--oplock-stroke-width) solid var(--oplock-shell-stroke);border-radius:50%;background:transparent;box-shadow:var(--oplock-shell-shadow);display:grid;place-items:center;pointer-events:none;backdrop-filter:none;}.oplock-core{width:var(--oplock-core-size);height:var(--oplock-core-size);border-radius:50%;background:var(--oplock-core-bg);color:var(--oplock-core-fg);box-shadow:var(--oplock-core-shadow);display:grid;place-items:center;pointer-events:none;}.oplock ha-icon{--mdc-icon-size:calc(var(--oplock-core-size) * 0.55);display:flex;line-height:0;}.oplock.locked{--oplock-core-bg:#66D17A;--oplock-core-fg:light-dark(#fff,#252525);--oplock-shell-stroke:#66D17A;}.oplock.theme-light.locked{--oplock-core-fg:#fff;}.oplock.theme-dark.locked{--oplock-core-fg:#252525;--oplock-stroke-ratio:.025;}.oplock.unlocked{--oplock-core-bg:#F0410C;--oplock-core-fg:light-dark(#fff,#252525);--oplock-shell-stroke:#F0410C;}.oplock.theme-light.unlocked{--oplock-core-fg:#fff;}.oplock.theme-dark.unlocked{--oplock-core-fg:#252525;--oplock-stroke-ratio:.025;}.oplock.unknown{--oplock-core-fg:var(--hp-muted);}.btn.lockact{width:100%;justify-content:center;display:flex;align-items:center;gap:var(--sp-3);margin-top:var(--sp-4);}.btn.lockact.warn{color:var(--error-color,#d33);border-color:var(--error-color,#d33);}.oprow{display:flex;align-items:center;gap:var(--sp-4);padding:var(--sp-3) 0;}.oprow b{margin-left:auto;}.oprow.ok b{color:#66d17a;}.oprow.warn b{color:var(--hp-open);}.bindharow{display:flex;align-items:center;gap:var(--sp-5);flex-wrap:wrap;}.bindharow .entcheck{opacity:0.9;}.ctrlchips{display:flex;flex-wrap:wrap;gap:var(--sp-3);margin:var(--sp-2) 0;}.ctrlchip{display:inline-flex;align-items:center;gap:var(--sp-2);background:var(--hp-accent);color:var(--text-primary-color,#fff);border-radius:var(--rad-l);padding:var(--sp-2) var(--sp-4);font-size:var(--fs-s);}.ctrlchip ha-icon{--mdc-icon-size:14px;cursor:pointer;}.ctrllist{display:flex;flex-direction:column;gap:var(--sp-1);margin-top:var(--sp-2);}.ctrlopt{display:flex;align-items:center;gap:var(--sp-4);text-align:left;border:0;background:transparent;color:var(--hp-txt);padding:var(--sp-3) var(--sp-4);border-radius:var(--rad-s);cursor:pointer;font-family:inherit;font-size:var(--fs-m);}:host([data-pointer-hover]) .ctrlopt:hover{background:var(--secondary-background-color,rgba(128,128,128,0.15));}.ctrlopt .sub{color:var(--hp-muted);font-size:var(--fs-s);margin-left:auto;}.ctrlopt ha-icon{--mdc-icon-size:16px;}.ctrlstates{display:flex;flex-direction:column;gap:var(--sp-2);}.ctrlstate{display:inline-flex;align-items:center;gap:var(--sp-3);color:var(--hp-muted);}.ctrlstate.on{color:var(--hp-txt);}.ctrlstate ha-icon{--mdc-icon-size:15px;}.cardpreview{display:flex;flex-direction:column;align-items:center;gap:var(--sp-2);margin:var(--sp-4) 0 var(--sp-1);padding:10px;border:1px dashed var(--hp-muted);border-radius:var(--rad-m);}.cardpreview .cpname{font-weight:700;letter-spacing:0.04em;}.cardpreview .cpmeta{display:inline-flex;align-items:center;gap:0.3em;font-weight:600;opacity:0.85;}.cardpreview .cpmeta ha-icon{--mdc-icon-size:1.05em;}.iconauto{display:flex;align-items:center;gap:var(--sp-3);font-size:var(--fs-s);margin:var(--sp-2) 0 0;}.iconauto ha-icon{--mdc-icon-size:18px;}.iconauto span{flex:1;}.iconauto .btn{min-height:32px;padding:0 var(--sp-3);}hp-dialog .dfill{display:inline-flex;align-items:center;gap:var(--sp-3);cursor:pointer;}.wallthick-dlg{position:absolute;z-index:40;min-width:200px;transform:translate(-50%,8px);padding:10px 12px;border-radius:10px;background:var(--card-background-color,#fff);box-shadow:0 8px 28px rgba(0,0,0,.22);display:flex;flex-direction:column;gap:8px;pointer-events:auto;}.wallthick-dlg .row{display:flex;align-items:center;gap:8px;}.wallthick-dlg input[type="number"]{width:5.5em;padding:4px 6px;border:1px solid var(--divider-color,#ccc);border-radius:6px;background:var(--input-fill,transparent);color:var(--primary-text-color);}.areasel,.namein{background:var(--hp-bg);border:1px solid var(--hp-line);color:var(--hp-txt);border-radius:var(--rad-s);padding:var(--sp-3) var(--sp-4);font-size:var(--fs-m);font-family:inherit;}.namein{width:130px;}.habindingbanner{display:flex;align-items:center;gap:var(--sp-3);padding:var(--sp-3) var(--sp-4);margin-bottom:var(--sp-4);border:1px solid var(--warning-color,#ff9800);border-radius:var(--rad-m);background:color-mix(in srgb,var(--warning-color,#ff9800) 12%,transparent);color:var(--primary-text-color,#f1f3f6);}.habindingbanner>span{flex:1;min-width:0;}.habindingbanner>ha-icon{color:var(--warning-color,#ff9800);flex:0 0 auto;}.habindingbanner.limited{border-color:var(--secondary-text-color,#9aa0aa);background:color-mix(in srgb,var(--secondary-text-color,#9aa0aa) 10%,transparent);}.habindingbanner.limited>ha-icon{color:var(--secondary-text-color,#9aa0aa);}.srcrow{display:flex;align-items:center;gap:var(--sp-4);font-size:var(--fs-m);cursor:pointer;padding:var(--sp-1) 0;}.dispsection{margin-top:var(--sp-5) !important;padding-top:var(--sp-4);border-top:1px solid var(--hp-line);font-weight:600;color:var(--hp-txt) !important;}.colorrow{display:flex;align-items:center;gap:var(--sp-4);}.roomtemprange{display:grid;gap:8px;min-width:0;}.roomtemprange-head{display:flex;flex-wrap:wrap;align-items:center;gap:6px;}.roomtemprange-fields{display:flex;flex-wrap:wrap;align-items:center;gap:8px;min-width:0;}.roomtemprange-fields input{flex:0 1 104px;min-width:72px;}.roomtemprange-fields input[aria-invalid='true']{border-color:var(--error-color,#db4437);}.gsrow>hp-color-opacity{min-width:min(100%,210px);justify-content:space-between;}.ripple-colorrow>hp-color-opacity{width:100%;justify-content:space-between;}.ripple-sizerow>.opl{min-width:0;}.colorrow input[type='range']{flex:1;}.colorrow .tempin{width:70px;flex:none;}hp-dialog .body .temprange .tempin{width:56px;flex:none;padding:var(--sp-2) var(--sp-3);}hp-dialog .body .colorrow .tempin{width:72px;flex:none;}.srcrow{flex-wrap:nowrap;}.srcrow ha-switch{flex:none;}.colorrow ha-slider{flex:1;min-width:0;}.srcrow>span:first-of-type{white-space:nowrap;}.colorrow .opl{color:var(--hp-muted);font-size:var(--fs-s);}.colorrow .opv{font-size:var(--fs-s);min-width:34px;text-align:right;}.markerlightgroup{min-width:0;margin:var(--sp-5) 0 0;padding:var(--sp-4);border:1px solid var(--hp-line);border-radius:var(--rad-m);}.markerlightgroup legend{display:flex;align-items:center;flex-wrap:wrap;gap:var(--sp-1);padding:0 var(--sp-2);color:var(--hp-txt);font-weight:600;}.markerlightgroup legend>span{min-width:0;overflow-wrap:anywhere;}.markerlightgroup[disabled]>:not(legend){opacity:.62;}.radargroup{display:grid;gap:var(--sp-2);}.radargroup>p{margin:0;}.radargroup>label:not(.srcrow){margin-top:var(--sp-2);}.radarcoordinates{align-items:flex-end;flex-wrap:wrap;}.radarcoordinates>label{display:grid;flex:1 1 92px;gap:var(--sp-1);min-width:0;margin:0;}hp-dialog .body .radarcoordinates .tempin{box-sizing:border-box;width:100%;}.radaradditional{margin-top:var(--sp-5);}.radaradditional summary{cursor:pointer;font-weight:600;}.radaradditional .btn{margin-top:var(--sp-3);}.radarinspection{display:grid;gap:6px;padding:10px 12px;border-radius:10px;background:color-mix(in srgb,var(--primary-color) 7%,transparent);}.radarinspection code{overflow-wrap:anywhere;font-size:12px;}.radarsetup{display:grid;gap:10px;margin-top:10px;padding:12px;border:1px solid var(--hp-accent);border-radius:var(--rad-m);background:color-mix(in srgb,var(--secondary-background-color) 88%,transparent);}.radarsetup-head{display:flex;align-items:center;gap:8px;}.radarsetup-head strong{flex:1;}.radarsetup>svg{width:min(100%,460px);aspect-ratio:1;justify-self:center;border-radius:var(--rad-m);background:var(--primary-background-color);touch-action:none;cursor:crosshair;}.radarsetup .room{fill:color-mix(in srgb,var(--hp-accent) 8%,transparent);stroke:var(--divider-color);stroke-width:3;vector-effect:non-scaling-stroke;}.radarsetup .heading{stroke:var(--hp-accent);stroke-width:4;vector-effect:non-scaling-stroke;}.radarsetup .trail{fill:none;stroke:var(--success-color,#43a047);stroke-width:3;stroke-linecap:round;stroke-linejoin:round;vector-effect:non-scaling-stroke;opacity:.55;}.radarsetup g circle{fill:var(--hp-bg);stroke:var(--hp-accent);stroke-width:3;vector-effect:non-scaling-stroke;}.radarsetup g.pending circle{stroke-dasharray:5 4;}.radarsetup g text{fill:var(--hp-txt);font-size:22px;font-weight:700;text-anchor:middle;dominant-baseline:middle;pointer-events:none;}.markerhelpfield{margin-top:var(--sp-4);}.markerhelplabel{display:flex;align-items:center;flex-wrap:wrap;gap:var(--sp-1);margin-bottom:var(--sp-1);}.markerhelplabel>label{min-width:0;overflow-wrap:anywhere;}.helpfieldlabel{display:flex;align-items:center;flex-wrap:wrap;gap:var(--sp-1);min-width:0;margin-top:var(--sp-3);color:var(--hp-muted);font-size:var(--fs-s);}.helpfieldlabel.compact{margin-top:0;}hp-dialog .body .helpfieldlabel>label{min-width:0;margin-top:0;overflow-wrap:anywhere;}.help-inline-label{display:inline-flex;align-items:center;flex-wrap:wrap;gap:var(--sp-1);}hp-dialog .body .help-inline-label>label{min-width:0;margin-top:0;overflow-wrap:anywhere;}.markerradios{display:grid;gap:var(--sp-1);min-width:0;}.markerlightgroup .srcrow>span:first-of-type{min-width:0;white-space:normal;overflow-wrap:anywhere;}.markerglowvalue{margin:var(--sp-3) 0;flex-wrap:wrap;}.markerglowvalue hp-color-opacity{flex:none;}.markerlightdisabled{display:flex;align-items:center;gap:var(--sp-2);margin-top:var(--sp-2) !important;}.markerlightdisabled ha-icon{--mdc-icon-size:18px;flex:none;}.markerbadgetechnical{min-width:0;margin:var(--sp-1) 0 var(--sp-2) !important;overflow-wrap:anywhere;}.markerbadgetechnical code{white-space:normal;}.planrow{display:flex;align-items:center;gap:10px;}.savedplans{display:flex;flex-direction:column;gap:var(--sp-3);max-height:240px;overflow:auto;margin:var(--sp-3) 0 var(--sp-1);padding:var(--sp-3);border:1px solid var(--hp-line);border-radius:var(--rad-m);background:var(--hp-bg2,rgba(255,255,255,0.03));flex:0 0 auto;min-height:2.6em;}.savedplan{display:flex;align-items:center;gap:10px;}.savedplan.cur{outline:1px solid var(--hp-accent);border-radius:var(--rad-s);}.savedplan img{width:56px;height:40px;object-fit:contain;border:1px solid var(--hp-line);border-radius:var(--rad-s);background:#fff;flex:none;}.savedmeta{display:flex;flex-direction:column;min-width:0;flex:1;}.savedmeta b{overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.savedmeta .muted{font-size:var(--fs-s);}.savedplan .btn.danger ha-icon{color:#f25a4a;}.savedplan .btn[disabled]{opacity:0.4;pointer-events:none;}.planprev{max-width:120px;max-height:70px;border:1px solid var(--hp-line);border-radius:var(--rad-s);background:#fff;}.planname{font-size:var(--fs-m);max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.planname.muted{color:var(--hp-muted);}.filebtn{cursor:pointer;}.fileupload{display:inline-flex;min-width:0;}.fileupload>input{display:none;}.btn.danger{border-color:#b3402a;color:#ff7a5c;}hp-dialog .row .spacer{flex:1;}hp-dialog .body{max-height:66vh;overflow-y:auto;}hp-confirm{display:contents;}hp-dialog .danger-confirm-body{display:flex;flex-direction:column;gap:var(--sp-4);}hp-dialog .danger-confirm-body p{margin:0;line-height:1.45;}hp-dialog .danger-confirm-object{overflow-wrap:anywhere;font-size:var(--fs-l);line-height:1.3;}.descin{width:100%;box-sizing:border-box;background:var(--hp-bg);border:1px solid var(--hp-line);color:var(--hp-txt);border-radius:var(--rad-s);padding:var(--sp-3) var(--sp-4);font-size:var(--fs-m);font-family:inherit;resize:vertical;min-height:92px;flex-shrink:0;line-height:1.35;}.bindsel{display:flex;flex-direction:column;gap:var(--sp-3);border:1px solid var(--hp-line);border-radius:var(--rad-m);padding:var(--sp-4);}.bindsel .opt{display:flex;align-items:center;gap:var(--sp-3);border:1px solid var(--hp-line);background:transparent;color:var(--hp-txt);border-radius:var(--rad-s);padding:var(--sp-3) var(--sp-4);cursor:pointer;font-size:var(--fs-m);font-family:inherit;}.bindsel .opt.on{background:var(--hp-accent);color:var(--text-primary-color,#fff);border-color:var(--hp-accent);}.curbind{display:flex;align-items:center;gap:var(--sp-3);font-size:var(--fs-m);color:var(--hp-txt);flex-wrap:wrap;}.curbind .ref{color:var(--hp-muted);font-size:var(--fs-s);}.vacbox .vacbtns{display:flex;gap:var(--sp-4);margin:var(--sp-3) 0;flex-wrap:wrap;}.vacdiag{display:grid;gap:4px;margin-bottom:var(--sp-3);}.vacdiag>div{display:flex;justify-content:space-between;gap:var(--sp-5);}.vacdiag>div>span{color:var(--secondary-text-color);}.vacdiag>div>b{text-align:right;overflow-wrap:anywhere;}.vacroute-missing-group{margin-top:var(--sp-4);padding-top:var(--sp-4);border-top:1px solid var(--hp-line);}.vacroute-group-title{margin:0 0 var(--sp-3);color:var(--secondary-text-color);font-size:var(--fs-m);font-weight:600;}.vacroute-missing-group .vacroute-list{margin-top:0;}.vacpicker{margin:var(--sp-3) 0;}.vacsource-warning{display:grid;gap:8px;}.vacsource-warning .btn{justify-self:start;}.vacpicker>summary{display:inline-flex;width:auto;list-style:none;cursor:pointer;}.vacpicker>summary::-webkit-details-marker{display:none;}.vacsource-list{display:grid;gap:6px;margin-top:8px;}.vacsource-list details{padding:6px 0 0;}.vacsource-list details>summary{cursor:pointer;font-weight:600;}.vacsource{display:flex;align-items:center;justify-content:space-between;gap:12px;width:100%;min-width:0;padding:9px 10px;border:1px solid var(--divider-color);border-radius:10px;color:var(--primary-text-color);background:var(--secondary-background-color);text-align:left;cursor:pointer;}.vacsource.on{border-color:var(--accent-color);box-shadow:inset 3px 0 var(--accent-color);}.vacsource>span:first-child{min-width:0;display:grid;gap:2px;}.vacsource small{color:var(--secondary-text-color);overflow-wrap:anywhere;}.vacsource-meta{color:var(--secondary-text-color);text-align:right;font-size:0.82em;}.vacxcme pre{margin:8px 0 0;white-space:pre-wrap;user-select:text;}.vacfit{position:absolute;inset:0;width:100%;height:100%;z-index:12;overflow:visible;touch-action:none;cursor:grab;pointer-events:auto;}.vacfit:active{cursor:grabbing;}.vacfit polygon{fill:color-mix(in srgb,var(--hp-accent) 16%,transparent);stroke:var(--hp-accent);stroke-width:2;vector-effect:non-scaling-stroke;stroke-dasharray:6 4;}.vacfit text{fill:var(--hp-accent);font-size:26px;text-anchor:middle;dominant-baseline:middle;pointer-events:none;user-select:none;}.furnpalette{display:flex;flex-direction:column;max-height:38vh;border-top:1px solid var(--hp-border,rgba(255,255,255,0.12));background:var(--card-background-color,var(--hp-bg));font-size:0.85em;}.furnhd{display:flex;align-items:center;gap:6px;padding:4px 8px;font-weight:600;opacity:0.9;}.furnhd .spacer{flex:1;}.furnbody{overflow:auto;padding:0 8px 6px;}.furngroup{margin:6px 0 3px;font-size:0.85em;text-transform:uppercase;letter-spacing:0.04em;opacity:0.6;}.furnrow{display:flex;flex-wrap:wrap;gap:4px;}.furnback{min-height:34px;gap:5px;margin:2px 0 4px;}.furnitem{display:flex;flex-direction:column;align-items:center;gap:2px;width:74px;padding:4px 2px;border:1px solid transparent;border-radius:8px;background:rgba(127,127,127,0.08);color:inherit;font:inherit;font-size:0.8em;line-height:1.15;text-align:center;cursor:pointer;}:host([data-pointer-hover]) .furnitem:hover{background:rgba(127,127,127,0.18);}.furnitem.on{border-color:var(--hp-accent);background:rgba(38,166,154,0.18);}.furnprev{width:40px;height:40px;color:var(--primary-text-color,currentColor);}.furncategory{width:92px;min-height:76px;}.furncatprev{width:48px;height:48px;}.furnvariants .furnitem{min-height:74px;}.furnsize{display:flex;align-items:center;flex-wrap:wrap;gap:6px;padding:6px 8px;border-top:1px solid var(--hp-border,rgba(255,255,255,0.12));}.furnsize label{display:flex;align-items:baseline;gap:3px;opacity:0.8;}.furnsize .furnunit{opacity:0.6;font-size:0.85em;}.furnsize input{width:5.5em;padding:3px 5px;}.furnhint{opacity:0.6;}.imageupload{display:inline-flex;gap:6px;margin:4px 0 8px;cursor:pointer;}.imageupload.disabled{opacity:0.55;pointer-events:none;}.imageupload input{display:none;}.imageassets{align-items:stretch;}.imageempty{padding:12px 6px;}.imageasset{position:relative;}.imageasset .furnitem{width:104px;min-height:92px;}.imageasset img{width:64px;height:54px;object-fit:contain;border-radius:4px;background:repeating-conic-gradient(#ddd 0 25%,#fff 0 50%) 50% / 12px 12px;}.imageasset .furnitem span{max-width:96px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.imageasset .furnitem small{opacity:0.65;font-size:0.72em;}.imageassetdelete{position:absolute;top:0;right:0;min-width:30px;width:30px;min-height:30px;padding:3px;}.imagepropertypreview{display:flex;align-items:center;gap:10px;min-width:0;}.imagepropertypreview img{width:72px;height:54px;object-fit:contain;border-radius:4px;background:repeating-conic-gradient(#ddd 0 25%,#fff 0 50%) 50% / 12px 12px;}.imagepropertypreview span{overflow-wrap:anywhere;}.vacfitdot{fill:var(--hp-accent);pointer-events:none;}.vacfithandle{fill:transparent;stroke:none;cursor:nwse-resize;}.vacfitknob{fill:var(--hp-bg);stroke:var(--hp-accent);stroke-width:2;vector-effect:non-scaling-stroke;pointer-events:none;}.vaccalbar{position:fixed;left:50%;bottom:24px;transform:translateX(-50%);display:flex;gap:var(--sp-5);align-items:center;background:var(--hp-bg);color:var(--hp-txt);border:1px solid var(--hp-accent);border-radius:var(--rad-l);padding:10px var(--sp-5);z-index:60;box-shadow:var(--shadow-2);}.candlist{max-height:160px;overflow-y:auto;border-top:1px solid var(--hp-line);flex:0 0 auto;min-height:2.6em;}.cand{display:flex;justify-content:space-between;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);cursor:pointer;border-radius:var(--rad-s);font-size:var(--fs-m);}:host([data-pointer-hover]) .cand:hover{background:rgba(127,127,127,0.15);}.cand.sel{background:var(--hp-accent);color:var(--text-primary-color,#fff);}.cand .cs{color:var(--hp-muted);font-size:var(--fs-s);white-space:nowrap;}.opening-entity-candidate{width:100%;border:0;background:transparent;color:inherit;font:inherit;text-align:left;}.opening-entity-candidate.sel{background:var(--hp-accent);color:var(--text-primary-color,#fff);}.opening-entity-empty{cursor:default;}.cand.sel .cs{color:var(--text-primary-color,#fff);opacity:0.85;}.cand.muted{color:var(--hp-muted);cursor:default;}.pdfedit{display:flex;flex-wrap:wrap;gap:var(--sp-3);align-items:center;}.pdftag{display:inline-flex;align-items:center;gap:var(--sp-2);border:1px solid var(--hp-line);border-radius:var(--rad-s);padding:var(--sp-2) var(--sp-3);font-size:var(--fs-s);}.pdftag a{color:var(--hp-txt);text-decoration:none;max-width:150px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}.pdftag .x{--mdc-icon-size:15px;cursor:pointer;color:var(--hp-muted);}:host([data-pointer-hover]) .pdftag .x:hover{color:#ff7a5c;}.entlist{display:flex;flex-direction:column;gap:var(--sp-2);margin-bottom:10px;}.entrow{display:flex;align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-4);border-radius:var(--rad-m);background:var(--secondary-background-color,rgba(128,128,128,0.12));}.entrow ha-icon{--mdc-icon-size:20px;color:var(--hp-muted);}.entrow.on ha-icon{color:var(--hp-accent);}.entrow .en{flex:1;font-size:var(--fs-m);}.entrow .ev{font-size:var(--fs-m);color:var(--hp-muted);}.entbtn{min-width:74px;min-height:32px;padding:var(--sp-2) var(--sp-5);border:1px solid var(--hp-muted);border-radius:999px;background:transparent;color:var(--hp-txt);font:inherit;font-size:var(--fs-m);cursor:pointer;}.entbtn.on{background:var(--hp-accent);border-color:var(--hp-accent);color:var(--text-primary-color,#fff);font-weight:600;}.inforow{display:flex;gap:10px;font-size:var(--fs-m);margin:var(--sp-2) 0;}.inforow .k{color:var(--hp-muted);min-width:84px;}.inforow a{color:var(--hp-accent);word-break:break-all;}.infodesc{font-size:var(--fs-m);white-space:pre-wrap;margin-top:var(--sp-3);}.infodesc.muted{color:var(--hp-muted);}.pdflist{display:flex;flex-direction:column;gap:var(--sp-2);}.pdf{display:inline-flex;align-items:center;gap:var(--sp-2);color:var(--hp-accent);text-decoration:none;}ha-icon-picker{display:block;}.floorrow{display:flex;align-items:center;gap:var(--sp-4);padding:var(--sp-3) var(--sp-2);font-size:var(--fs-m);cursor:pointer;}.floorrow .floorlvl{color:var(--hp-muted);font-size:var(--fs-s);border:1px solid var(--hp-line);border-radius:var(--rad-s);padding:0 var(--sp-3);}.rtest{display:flex;align-items:center;gap:var(--sp-4);margin-bottom:var(--sp-4);}.rtest .namein{flex:1;}.rtest ha-icon{color:var(--hp-accent);}.rtesticon{font-size:var(--fs-s);color:var(--hp-muted);}.rrow{display:flex;align-items:center;gap:var(--sp-3);margin:var(--sp-1) 0;}.rrow .rpat{flex:2;}.rrow .ricon{flex:1.4;}.rrow .rpat.bad{border-color:#ff7a5c;}.rrow .rprev{--mdc-icon-size:18px;color:var(--hp-txt);min-width:18px;}.rrow .ract{--mdc-icon-size:16px;color:var(--hp-muted);cursor:pointer;}:host([data-pointer-hover]) .rrow .ract:hover{color:var(--hp-txt);}:host([data-pointer-hover]) .rrow .ract.del:hover{color:#ff7a5c;}.gsrow .gsl{min-width:150px;font-size:var(--fs-m);color:var(--hp-muted);}.optimize-live{display:grid;justify-items:start;gap:var(--sp-2);margin-bottom:var(--sp-3);}.optimize-live .alignmsg,.optimize-live .rhint{margin-bottom:0;}.optimize-cleanup{min-height:44px;}.optimize-selected{color:var(--hp-txt);}.optimize-details{margin-top:var(--sp-3);color:var(--hp-muted);font-size:var(--fs-s);overflow-wrap:anywhere;}.optimize-details>summary{width:fit-content;color:var(--hp-txt);cursor:pointer;font-weight:600;}.optimize-details>summary:focus-visible{outline:2px solid var(--hp-accent);outline-offset:3px;border-radius:var(--rad-s);}.optimize-details ul{margin:var(--sp-3) 0;padding-inline-start:22px;}.optimize-details li + li{margin-top:var(--sp-1);}.btn.alignall{width:100%;justify-content:center;}.backupactions{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--sp-3);}.backupactions .btn{justify-content:center;min-width:0;}.backupupload{display:inline-flex;min-width:0;}.backupupload>.btn{width:100%;justify-content:center;}.backupupload input{display:none;}.backupbody{min-width:0;}.backupplanonly{margin-inline-start:var(--sp-4) !important;align-items:flex-start !important;}.backupplanonly>span:first-of-type{display:grid;gap:2px;white-space:normal;}.backupplanonly small{color:var(--secondary-text-color);line-height:1.35;}.backupplanonlystatus{color:var(--hp-accent) !important;font-weight:700;}.backupfile,.backupsummary,.backupcontent{display:flex;flex-direction:column;min-width:0;gap:var(--sp-1);}.backupfile b,.backupcontent span{overflow-wrap:anywhere;}.backupfile span,.backupsummary span,.backupcontent span{color:var(--hp-muted);font-size:var(--fs-s);}.backupcounts{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));gap:var(--sp-2) var(--sp-4);font-size:var(--fs-s);}.backupwarn,.backuperror{border-radius:var(--rad-s);padding:var(--sp-3);font-size:var(--fs-s);line-height:1.45;overflow-wrap:anywhere;}.backupwarn{background:color-mix(in srgb,var(--hp-accent) 12%,transparent);}.backuperror{background:rgba(179,64,42,.16);color:#ff7a5c;}.backupdetails{border:1px solid var(--hp-line);border-radius:var(--rad-s);padding:var(--sp-2) var(--sp-3);font-size:var(--fs-s);}.backupdetails summary{cursor:pointer;font-weight:700;}.backupdetails>div{display:grid;gap:var(--sp-1);padding-block-start:var(--sp-2);}.backupdetails code{overflow-wrap:anywhere;color:var(--hp-muted);}.backupchoices{display:flex;flex-direction:column;gap:var(--sp-2);border:1px solid var(--hp-line);border-radius:var(--rad-s);min-width:0;}.backupchoices label{margin:0 !important;display:flex;gap:var(--sp-2);}.backupconfirm{align-items:flex-start !important;}.backupconfirm>span:first-of-type{min-width:0;white-space:normal;overflow-wrap:anywhere;}@media (max-width:520px){.backupactions,.backupcounts{grid-template-columns:1fr;}}.aboutver{font-size:var(--fs-s);color:var(--hp-muted);margin:var(--sp-2) 0 var(--sp-3);}.aboutlink{display:flex;align-items:center;gap:var(--sp-3);width:fit-content;color:var(--hp-accent);text-decoration:none;font-size:var(--fs-m);padding:var(--sp-1) 0;}:host([data-pointer-hover]) .aboutlink:hover{text-decoration:underline;}.aboutlink ha-icon{--mdc-icon-size:18px;line-height:1;}hp-dialog .supportbody{min-width:0;overflow-x:hidden;gap:var(--sp-5);}.supportsection{display:grid;min-width:0;gap:var(--sp-2);}.supportsection + .supportsection{padding-top:var(--sp-4);border-top:1px solid var(--hp-line);}.supportsection h3{margin:0;color:var(--hp-txt);font-size:var(--fs-m);}.supportlinks,.supportactions{display:flex;align-items:center;flex-wrap:wrap;gap:var(--sp-2) var(--sp-4);min-width:0;}.supportform>label:not(.srcrow){margin-top:var(--sp-2);color:var(--hp-muted);font-size:var(--fs-s);}.supportmessage,.supportraw{width:100%;min-width:0;box-sizing:border-box;resize:vertical;border:1px solid var(--hp-line);border-radius:var(--rad-s);padding:var(--sp-3);color:var(--hp-txt);background:color-mix(in srgb,var(--card-background-color,var(--hp-bg)) 92%,var(--hp-txt));font:inherit;}.supportmessage{min-height:120px;background:var(--hp-bg);}.supportraw{min-height:220px;margin-top:var(--sp-2);resize:none;white-space:pre;overflow:auto;font-family:ui-monospace,SFMono-Regular,Consolas,monospace;font-size:12px;}.supportattach{min-width:0;align-items:flex-start;margin:var(--sp-2) 0 0 !important;}.supportattach>span:first-of-type{min-width:0;white-space:normal;overflow-wrap:anywhere;}.supportwarning,.supportstatus,.supportupdate{display:flex;align-items:flex-start;gap:var(--sp-2);min-width:0;margin:0;padding:var(--sp-3);border-radius:var(--rad-s);background:color-mix(in srgb,var(--hp-accent) 14%,transparent);overflow-wrap:anywhere;font-size:var(--fs-s);line-height:1.45;}.supportwarning ha-icon,.supportstatus ha-icon,.supportupdate ha-icon{flex:none;color:var(--hp-accent);--mdc-icon-size:20px;}.supportpreview,.supportmanual,.supporterror,.supportsuccess{display:grid;min-width:0;gap:var(--sp-2);padding:var(--sp-3);border:1px solid var(--hp-line);border-radius:var(--rad-s);}.supportsummary{font-weight:600;overflow-wrap:anywhere;}.supporthash{display:grid;min-width:0;gap:var(--sp-1);color:var(--hp-muted);font-size:var(--fs-s);}.supporthash code{overflow-wrap:anywhere;color:var(--hp-txt);}.supportpreview details{min-width:0;}.supportpreview summary{cursor:pointer;color:var(--hp-accent);}.supportprivacy{margin:0 !important;line-height:1.45;}.supporterror{background:color-mix(in srgb,var(--error-color,#db4437) 12%,transparent);border-color:color-mix(in srgb,var(--error-color,#db4437) 45%,var(--hp-line));}.supportsuccess{background:color-mix(in srgb,var(--success-color,#43a047) 12%,transparent);border-color:color-mix(in srgb,var(--success-color,#43a047) 45%,var(--hp-line));}.supportfooter{flex-wrap:wrap;}@media (max-width:520px){hp-dialog .supportbody{padding-inline:var(--sp-4);}hp-dialog .supportfooter{padding-inline:var(--sp-4);}.supportactions .btn,.supportactions .aboutlink{max-width:100%;}}hp-dialog .body{padding:var(--sp-5) var(--sp-6);display:flex;flex-direction:column;gap:var(--sp-3);}hp-dialog .tapconfirm-body{min-width:0;overflow-x:hidden;}hp-dialog .tapconfirm-body p{max-width:100%;min-width:0;margin:0;overflow-wrap:anywhere;white-space:normal;}hp-dialog .tapconfirm-line{color:var(--hp-muted);}hp-dialog .body label{font-size:var(--fs-s);color:var(--hp-muted);margin-top:var(--sp-3);}hp-dialog .body .namein,hp-dialog .body .areasel{width:100%;box-sizing:border-box;}hp-dialog.roomdialog .body{min-width:0;overflow-x:hidden;}hp-dialog.roomdialog .body>*{min-width:0;max-width:100%;box-sizing:border-box;}hp-dialog.roomdialog .srcrow{min-width:0;align-items:flex-start;}hp-dialog.roomdialog .srcrow>span:first-of-type{min-width:0;white-space:normal;overflow-wrap:anywhere;line-height:1.35;}hp-dialog.roomdialog .dropbtn>b,hp-dialog.roomdialog .dropbtn>.ref{min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;}hp-dialog .row{display:flex;justify-content:flex-end;gap:var(--sp-4);width:100%;min-width:0;box-sizing:border-box;padding:var(--sp-5) var(--sp-6);border-top:1px solid var(--hp-line);}hp-dialog>.row[slot='footer'] button{min-height:44px;}hp-dialog .row.dialog-action-footer{align-items:center;justify-content:flex-start;flex-wrap:wrap;row-gap:var(--sp-4);}hp-dialog .dialog-action-group{display:flex;flex:0 1 auto;flex-wrap:wrap;align-items:center;gap:var(--sp-4);max-width:100%;min-width:0;}hp-dialog .dialog-action-group .btn{flex:0 0 auto;min-height:44px;}hp-dialog .dialog-action-danger{margin-right:auto;}hp-dialog .dialog-action-commit{margin-left:auto;justify-content:flex-end;}hp-dialog .row.markerfooter{justify-content:space-between;align-items:center;flex-wrap:wrap;}hp-dialog .row.roomfooter{align-items:center;flex-wrap:wrap;}hp-dialog .row.infofooter{align-items:center;justify-content:flex-start;flex-wrap:wrap;gap:var(--sp-3);}hp-dialog .row.infofooter .btn{flex-shrink:0;}hp-dialog .row.infofooter .infofooter-close{margin-left:auto;}@media (max-width:480px){hp-dialog .row.infofooter{padding:var(--sp-4) var(--sp-5);}}.markeractions,.markersaveactions{display:flex;align-items:center;gap:var(--sp-4);}.markeractions:empty{display:none;}.markersaveactions{margin-left:auto;}.device-inbox{display:flex;flex-direction:column;gap:var(--sp-4);padding:var(--sp-5) var(--sp-6);min-width:0;}.device-inbox-dialog{--hp-dialog-wide-width:920px;}.device-inbox-head{display:grid;grid-template-columns:minmax(180px,1fr) auto;align-items:center;gap:var(--sp-4);}.device-inbox-search{width:100%;min-width:0;box-sizing:border-box;border:1px solid var(--hp-line);border-radius:var(--rad-m);background:transparent;color:var(--hp-txt);font:inherit;padding:11px 14px;}.device-inbox-tabs{display:flex;gap:var(--sp-2);overflow-x:auto;scrollbar-width:thin;padding-bottom:var(--sp-1);}.device-inbox-tabs button{flex:0 0 auto;border:1px solid var(--hp-line);border-radius:999px;background:transparent;color:var(--hp-txt);font:inherit;padding:8px 12px;cursor:pointer;}.device-inbox-tabs button.on{border-color:var(--hp-accent);background:color-mix(in srgb,var(--hp-accent) 18%,transparent);}.device-inbox-tabs button span{color:var(--hp-muted);margin-inline-start:4px;}.device-inbox-discovery{margin:8px 0;padding:8px 10px;border:1px solid var(--divider-color,#e0e0e0);border-radius:8px;}.device-inbox-discovery summary{cursor:pointer;font-weight:600;}.device-inbox-discovery .srcrow{display:flex;gap:6px;align-items:center;margin:8px 0;}.device-inbox-excluded{display:flex;flex-wrap:wrap;gap:6px;align-items:center;}.device-inbox-excluded>span{font-weight:500;}.device-inbox-chips{display:flex;flex-wrap:wrap;gap:4px;}.device-inbox-chips .chip{display:inline-flex;align-items:center;gap:2px;padding:1px 6px;border-radius:10px;background:var(--secondary-background-color,#f0f0f0);font-size:12px;}.device-inbox-chips .chip button{border:none;background:none;cursor:pointer;padding:0 2px;color:var(--secondary-text-color,#666);}.device-inbox-excluded input[type="text"]{flex:1 1 140px;min-width:120px;padding:4px 6px;border:1px solid var(--divider-color,#e0e0e0);border-radius:6px;background:var(--card-background-color,#fff);color:var(--primary-text-color,#212121);}.device-inbox-preview{margin:8px 0 4px;font-size:13px;opacity:0.85;}.device-inbox-filters{display:flex;flex-wrap:wrap;gap:var(--sp-4) var(--sp-6);color:var(--hp-muted);}.device-inbox-filters label{display:inline-flex;align-items:center;gap:var(--sp-2);cursor:pointer;}.device-inbox-filter-help{display:inline-flex;align-items:center;gap:var(--sp-1);min-width:0;}.device-inbox-results{display:grid;gap:var(--sp-3);min-width:0;}.device-inbox-row{display:grid;grid-template-columns:42px minmax(180px,1fr) minmax(180px,auto);align-items:center;gap:var(--sp-4);min-width:0;border:1px solid var(--hp-line);border-radius:var(--rad-m);padding:var(--sp-4);background:color-mix(in srgb,var(--hp-txt) 3%,transparent);}.device-inbox-icon{--mdc-icon-size:28px;color:var(--hp-txt);justify-self:center;}.device-inbox-copy{min-width:0;}.device-inbox-name{display:flex;align-items:center;flex-wrap:wrap;gap:var(--sp-2);}.device-inbox-new{border-radius:999px;background:var(--hp-accent);color:var(--text-primary-color,#fff);font-size:var(--fs-s);padding:2px 7px;}.device-inbox-meta,.device-inbox-reason,.device-inbox-copy code{display:block;color:var(--hp-muted);font-size:var(--fs-s);overflow-wrap:anywhere;white-space:normal;}.device-inbox-status{color:var(--error-color,#db4437);margin-inline-start:var(--sp-2);}.device-inbox-actions{display:flex;justify-content:flex-end;align-items:center;flex-wrap:wrap;gap:var(--sp-2);}.device-inbox-actions .btn{min-height:36px;padding:7px 10px;}.device-inbox-menu{position:relative;}.device-inbox-menu summary{list-style:none;cursor:pointer;}.device-inbox-menu summary::-webkit-details-marker{display:none;}.device-inbox-menu-items{position:absolute;z-index:2;inset-inline-end:0;top:calc(100% + var(--sp-1));display:grid;gap:var(--sp-1);min-width:180px;padding:var(--sp-2);border:1px solid var(--hp-line);border-radius:var(--rad-m);background:var(--hp-panel,var(--card-background-color,#fff));box-shadow:0 8px 24px rgba(0,0,0,.22);}.device-inbox-menu-items .btn{justify-content:flex-start;width:100%;}.device-inbox-empty{color:var(--hp-muted);text-align:center;padding:var(--sp-8);}.device-inbox-more{align-self:center;}@media (max-width:680px){.device-inbox{padding:var(--sp-4);}.device-inbox-head{grid-template-columns:minmax(0,1fr);}.device-inbox-head .btn{justify-self:stretch;}.device-inbox-tabs{display:grid;grid-template-columns:repeat(2,minmax(0,1fr));overflow-x:visible;}.device-inbox-tabs button{min-width:0;overflow-wrap:anywhere;}.device-inbox-row{grid-template-columns:36px minmax(0,1fr);}.device-inbox-actions{grid-column:1 / -1;justify-content:flex-start;}}`];var cp={"editor.context_actions":"Actions: {object}","editor.tool_options":"Tool options: {tool}","editor.palette":"Palette: {tool}","editor.open_group":"Tool group: {group}","editor.group_active":"{group} — active: {item}","editor.disabled_action":"{action} is unavailable: {reason}","editor.loading":"Loading editor…","editor.loading_aria":"The plan editor is loading","editor.load_failed":"Could not load the editor.","editor.refresh_advice":"Refresh the page and try again.","editor.retry_advice":"Check your connection and press again.","version_mismatch.title":"House Plan versions do not match","version_mismatch.body":"If Home Assistant is still restarting, let it finish, then reload this page.","version_mismatch.frontend":"Card","version_mismatch.backend":"Integration","version_mismatch.reload":"Reload page","color_picker.title":"Color picker","color_picker.hue":"Hue","color_picker.saturation":"Saturation","color_picker.value":"Brightness","color_picker.hex":"Hex color","color_picker.invalid_hex":"Enter a 3- or 6-digit hex color","color_picker.confirm":"OK","btn.properties":"Properties","btn.keep_as_walls":"Keep as walls","btn.delete_room_keep_walls":"Delete room, keep walls","btn.delete_room_with_walls":"Delete room and walls","title.markup_select":"Select and edit walls and columns","title.markup_column":"Column: click a grid point to place a square column","markup.partition":"Partition","markup.column":"Column","markup.hint_column":"click a grid point to place a square column","history.wall_segment":"Add wall segment","history.column_add":"Add column","history.physical_edit":"Change physical object","history.physical_delete":"Delete physical object","history.physical_move":"Move physical object","history.wall_face_batch":"Create rooms from walls","toast.column_duplicate":"A column with the same centre and outer size already exists","physical.partition_properties":"Partition properties","physical.column_properties":"Column properties","physical.shape":"Shape","physical.square":"Square","physical.circle":"Circle","physical.diameter":"Diameter","physical.side":"Side","physical.rotation":"Rotation angle","physical.length":"Length","physical.allowed_range":"Allowed: {min}–{max} {unit}","physical.column_size_title":"Outer side of the square column placed by the click (1–150 cm).","card.title":"House plan","count.devices":"{n} dev.","empty.no_spaces":"No spaces yet.","nav.spaces":"House Plan spaces","empty.add_first":"Add the first space and upload a floor plan.","empty.read_only":"No spaces are configured. Ask an administrator to add one.","empty.install":'Install the House Plan integration and add it in "Devices & services".',"btn.add_space":"Add space","btn.cancel":"Cancel","btn.save":"Save","btn.close":"Close","btn.delete":"Delete","btn.copy":"Copy","btn.edit":"Edit","btn.open_in_ha":"Open in HA","btn.reset":"Reset","btn.attach":"Attach…","btn.upload":"Upload…","btn.replace":"Replace…","title.zoom_in":"Zoom in","title.zoom_out":"Zoom out","title.zoom_fit":"Fit all","title.configure_space":"Configure space","title.add_space":"Add space","title.markup_add":"Walls: draw a continuous chain; each accepted segment is saved independently. Shift locks to 45°","title.markup_merge":"Merge: click one room, then the neighbour it shares a wall with","title.markup_split":"Split a room: click the room, then two points on its walls","title.markup_delroom":"Delete room: click inside a room and confirm","title.need_plan":"Upload a floor-plan image","markup.add":"Walls","markup.merge":"Merge","markup.split":"Split","markup.resize":"Resize","title.markup_resize":"Resize rooms: drag an available horizontal or vertical wall handle","markup.hint_resize":"drag an available wall handle · the wall stops at the first unsafe position · Esc cancels · Ctrl+Z — undo","resize.disabled.diagonal":"This wall is angled; Resize supports only horizontal and vertical walls","resize.disabled.side-angle":"An adjoining wall is angled; Resize requires both adjoining walls to meet this wall at right angles","resize.disabled.duplicate-physical-wall":"A separate partition or column overlaps this wall; remove or move it before resizing","resize.disabled.partial-shared":"A neighbouring room uses only part of this wall, so it cannot be moved safely as one shared wall","resize.disabled.unequal-shared":"The neighbouring room uses different endpoints or wall length, so the walls cannot move together safely","resize.disabled.multiple-rooms":"Moving this wall would affect more than two rooms","resize.disabled.thickness-conflict":"The wall thickness cannot be preserved safely","resize.disabled.opening-conflict":"An opening on this wall cannot be moved safely","resize.disabled.invalid-geometry":"This wall cannot be resized without changing the plan structure","resize.limit_stopped":"Wall stopped: the next step would break a junction limit","resize.commit_failed":"Resize was cancelled because the final plan did not pass the geometry check","resize.preview_failed":"Resize stopped at the last safe position because the plan geometry could not be preserved","markup.opening":"Opening","markup.delete_room":"Delete room","history.undo":"Undo","history.redo":"Redo","history.undo_named":"Undo: {name} (Ctrl+Z)","history.redo_named":"Redo: {name} (Ctrl+Shift+Z / Ctrl+Y)","history.undo_empty":"Nothing to undo","history.redo_empty":"Nothing to redo","history.undone":"Undone: {name}","history.redone":"Redone: {name}","history.add_room":"Create room","history.split_room":"Split room","history.merge_rooms":"Merge rooms","history.resize_room":"Resize room","history.wall_thickness":"Change wall thickness","history.add_opening":"Add door or window opening","history.edit_opening":"Edit opening","history.move_opening":"Move opening","history.delete_opening":"Delete opening","history.delete_room_keep_walls":"Delete room, keep walls","history.delete_room_with_walls":"Delete room and walls","history.decor_add":"Add decor object","history.decor_edit":"Edit decor object","history.decor_move":"Move decor object","history.decor_transform":"Transform decor object","history.decor_delete":"Delete decor object","history.backdrop_transform":"Transform plan backdrop","history.device_move":"Move {name}","history.device_stale":"Device position history is no longer applicable and was cleared","opening.new":"New opening","opening.edit":"Opening","opening.door":"Door","opening.window":"Window","opening.gate":"Gate","opening.passage":"Open passage","opening.passage_binding_warning":"Saving will remove the open/close sensor and lock.","opening.invalid_passage_fields":"The open passage on plan “{room}” has unsupported settings: {fields}.","opening.type_label":"Type","opening.length_label":"Length, cm","opening.contact_label":"Open/close sensor","opening.lock_label":"Lock","opening.none":"— none —","opening.search_ph":"Search: name or entity id…","opening.invert":"Invert open/closed","opening.flip_h":"Hinge on the other jamb","opening.flip_v":"Opens to the other side","opening.open":"Open","opening.closed":"Closed","opening.locked":"Locked","opening.unlocked":"Unlocked","opening.state_unknown":"unavailable","opening.no_entities":"No sensors bound — a static symbol on the plan.","toast.opening_no_wall":"Click next to a room wall or independent wall","opening.host_partition":"Independent wall","opening.partition_orphan":"The independent wall for this opening no longer exists","opening.partition_jamb_margin":"Leave at least {distance} between the opening and the end of the wall","opening.rebind_partition":"Attach to another independent wall","confirm.delete_partition_openings_title":"Delete wall and openings?","confirm.delete_partition_openings_body":"This wall contains {count} opening(s). They will be deleted together.","confirm.delete_partition_openings_item":"• {type}, {length}","markup.hint_points":"points: {n} · Shift — 45° steps · Esc — finish chain · Ctrl+Z — undo a point · closing an area offers a room","markup.hint_start":"click a grid dot to start a wall chain","tip.lqi":"average zigbee signal:","tip.area":"area: {value}","info.device_header":"Device on the plan","info.model":"Model","info.state":"State","info.link":"Link","info.manuals":"Manuals","info.none":"No additional information","marker.new_device":"New device","marker.name_label":"Name (shown on the plan)","marker.name_ph":"Name","marker.binding_label":"Bind to an HA device","marker.binding_disabled":"disabled in Home Assistant","marker.virtual_option":"Virtual device (no binding)","marker.search_ph":"Search device / group…","marker.nothing_found":"nothing found","marker.room_label":"Room","marker.room_override":" (override placement)","marker.room_choose":"— select a room —","marker.room_auto":"— by device area (auto) —","marker.icon_label":"Icon","marker.icon_ph":"mdi:… (empty = auto)","marker.display_label":"Display","display.badge":"Icon + state","display.icon_ripple":"Icon + state and activity","display.static_icon":"Always static icon","marker.display_hint_badge":"The icon and dynamic plate show device state without the ordinary activity pulse. Red alarms remain visible.","marker.display_hint_icon_ripple":"The icon, dynamic plate and pulse show a short pulse for events and a continuous pulse for work, motion or presence. Red alarms have separate priority.","marker.display_hint_value":"A selected or automatically resolved Home Assistant value replaces the icon while the plate continues to show state. Red alarms remain visible.","marker.display_hint_static_icon":"The theme-aware shell and icon always stay the same. State, activity, unavailability and alarms do not change the face.","marker.static_alarm_warning":"This device can report alarms. Static display hides the marker's visual alarm indication.","marker.preview.title":"Display preview","marker.preview.actual":"Now","marker.preview.example":"Example","marker.preview.integration":"Provided by","marker.preview.source":"Display source","marker.preview.current_state":"Current state","marker.preview.result":"On the plan","marker.preview.details":"Source details","marker.preview.select_source":"Choose a Home Assistant device or entity to see its actual display.","marker.preview.unknown_provider":"Unknown integration","marker.preview.virtual_provider":"House Plan · virtual device","marker.preview.no_source":"No active source","marker.preview.no_state":"No current state","marker.preview.mixed_states":"Several different states","marker.preview.multiple_sources":"{n} sources","marker.preview.more_sources":"+{n} more","marker.preview.scaled":"The preview is scaled to {n}% to fit. The saved size is unchanged.","marker.preview.demo_short":"Show short activity","marker.preview.demo_continuous":"Show continuous activity","marker.preview.stop_continuous":"Stop continuous activity","marker.preview.demo_short_notice":"Short activity example; the actual device state is unchanged.","marker.preview.demo_continuous_notice":"Continuous activity example; the actual device state is unchanged.","marker.preview.demo_already_visible":"The current state already shows a real activity or alarm effect.","marker.preview.reduced_motion":"System reduced-motion is enabled, so ordinary activity is shown as a dot.","marker.preview.reason.neutral":"Neutral dark plate","marker.preview.reason.working":"Yellow plate: the device is working now","marker.preview.reason.working_activity":"Yellow plate and activity effect: the device is working now","marker.preview.reason.open":"Orange plate: physically open or unlocked","marker.preview.reason.cover_icon_state":"Neutral plate; the cover entity controls the displayed state and icon","marker.preview.reason.presence":"Activity effect while presence is detected","marker.preview.reason.event":"Short activity effect after a detected event","marker.preview.reason.transition":"Activity effect while the device is moving or changing state","marker.preview.reason.media_neutral":"Media devices stay on a neutral dark plate while available","marker.preview.reason.unavailable":"Subdued neutral plate: unavailable or off","marker.preview.reason.alarm":"Red alarm plate; alarm indication is always shown","marker.preview.reason.live_states_disabled":"Live-state styling is disabled for this card","marker.preview.reason.value_no_state":"No usable state value; the icon is shown instead","marker.preview.reason.value_ambiguous_sources":"Several possible value sources; the icon is shown instead","marker.preview.reason.value_non_scalar":"The source did not return a simple value; the icon is shown instead","marker.preview.reason.value_virtual":"A virtual device has no Home Assistant value; the icon is shown instead","marker.preview.reason.vacuum_live_plan_only":"Live vacuum position and trail are available only on the full plan","marker.preview.reason.hidden_design_preview":"The device is hidden on the plan; this design preview remains visible","marker.preview.reason.composite_power_source":"State comes from the device Power entity; auxiliary switches are ignored","marker.preview.reason.activity_display_disabled":"The selected display mode does not show ordinary activity effects","marker.preview.reason.ha_disabled":"The Home Assistant binding is disabled and will be hidden on the plan","marker.preview.reason.orphaned":"The saved Home Assistant binding can no longer be found","marker.preview.reason.static_icon":"Static mode: device state does not change the icon","marker.activity_color":"Activity pulse color","marker.ripple_size":"Activity pulse size","marker.activity_alarm_note":"Color and size affect ordinary activity only and do not change red alarms.","marker.pulse_a11y_alarm":"Alarm","marker.pulse_a11y_event":"Recent event","marker.pulse_a11y_presence":"Presence detected","marker.pulse_a11y_transition":"Changing state","marker.pulse_a11y_running":"Working","marker.state_a11y_neutral":"Default state","marker.state_a11y_working":"Working","marker.state_a11y_open":"Open","marker.state_a11y_locked":"Locked","marker.state_a11y_unlocked":"Unlocked","marker.state_a11y_alarm":"Alarm","marker.state_a11y_unavailable":"Unavailable","marker.lqi_a11y_low":"LQI {value}, low signal","marker.lqi_a11y_mid":"LQI {value}, medium signal","marker.lqi_a11y_high":"LQI {value}, high signal","marker.size_label":"Icon size / rotation","marker.angle_label":"Rotate","marker.model_label":"Model","marker.model_ph":"e.g. Aqara T&H","marker.link_label":"Link","marker.desc_label":"Description","marker.desc_ph":"Notes, specs…","marker.manuals_label":"Manuals (PDF etc.)","marker.sub_device":"device","marker.sub_z2m_group":" · Z2M group","marker.sub_group":"group","marker.sub_helper":"helper","space.new":"New space","space.copy_title":"Copy space","space.copy_name":"New space name","space.copy_fallback":"Space","space.copy_create":"Create copy","space.copy_optimize_title":"Optimize before copying?","space.copy_optimize_body":"Before creating “{name}”, House Plan must optimize the entire plan, including other spaces. Continue?","space.copy_optimize_confirm":"Optimize and copy","space.copy_error_changed":"The plan changed while confirmation was open. Review it and try again.","space.copy_error_source_missing":"The source space no longer exists. Reopen its settings and try again.","space.copy_error_source_invalid":"House Plan could not validate every wall in this space. Fix the source space and try again.","space.copy_error_spaces_limit":"House Plan already has the maximum number of spaces.","space.copy_error_partitions_limit":"This space has too many walls to copy.","space.copy_error_openings_limit":"This space has too many openings to copy.","space.copy_error_decor_limit":"This space has too many background objects to copy.","space.copy_error_columns_limit":"This space has too many columns to copy.","space.copy_error_opening_host":"One of the openings is no longer attached to a wall. Fix or delete it before copying.","space.copy_error_geometry":"The copy would create unsafe wall geometry. Fix the source space and try again.","space.copy_error_optimize_geometry":"Copy stopped because optimizing the entire plan is unsafe for one of the spaces.","space.header":"Space","space.title_label":"Title","space.title_ph":"e.g. Garage","space.plan_label":"Floor plan (background)","space.no_plan":"no plan image","space.plan_alt":"plan","room.new":"New room","room.name_label":"Display name","room.name_ph":"e.g. Terrace","room.area_label":"Home Assistant area (unassigned)","room.no_area_option":"— no area —","room.default_name":"Room","device.unnamed":"unnamed","device.light_group":"light group","device.fallback":"device","device.virtual":"virtual device","confirm.delete_room_title":'Delete room "{name}"?',"confirm.delete_room_body":"Choose whether the room's exclusive physical walls should remain. Walls shared with another room are always kept.","confirm.remove_marker_title":"Delete device from the plan?","confirm.remove_marker_body":"The device will disappear completely and stop contributing to plan data. You can add it again later.","confirm.erase_decor":"Erase the {kind} object? You can undo this action from the editor history.","confirm.delete_space_title":"Delete space?","confirm.delete_space_body":"The space, all its rooms and all its plan markup will be deleted.","confirm.delete_space_vac_routes":"Robot map assignments will also be removed: {count}.","space.delete_blocked":"This space is still used by {n} device(s). Move them to another space or delete them first.","toast.pos_save_failed":"Failed to save position: {err}","toast.no_entity":"The device has no suitable entity","toast.ha_disabled_action":"A Home Assistant object that is disabled cannot be used on the plan.","toast.ha_disabled_show_device":"A device disabled in Home Assistant cannot be shown on the plan. Enable it in Home Assistant first.","toast.ha_disabled_show_entity":"An entity disabled in Home Assistant cannot be shown on the plan. Enable it in Home Assistant first.","toast.ha_disabled_add":"A disabled Home Assistant object cannot be added to the plan. Enable it in Home Assistant first.","toast.ha_binding_unverified":"The object status could not be verified through the Home Assistant registry. Display and actions are temporarily unavailable.","toast.markup_needs_server":"Markup is available after the config is moved to the server","toast.space_order_changed":"Order changed. If any card pins its floor by number, check those panels.","toast.conflict":"Config was changed in another window — data refreshed, repeat your last action","toast.cfg_save_failed":"Failed to save config: {err}","toast.room_overlap":"The outline overlaps room “{name}” — rooms must not overlap","toast.contour_cannot_close":"The outline cannot close because it is degenerate or intersects itself","toast.merge_not_adjacent":"Only rooms that share a wall can be merged","toast.rooms_merged":"Rooms merged into “{name}”","toast.split_pick_wall":"Start the cut on the room’s wall","toast.split_bad_cut":"The cut must run wall to wall inside the room, without crossing walls or itself","merge.header":"Merge rooms","merge.hint":"The merged room keeps one name and one area. The other area is released — its devices leave the plan until another room claims it.","merge.keep":"Keep","merge.no_area":"no area","toast.room_saved":"Room saved ({n}). Devices added: {added}. Outline the next one or exit markup.","toast.room_saved_no_area":"Room saved ({n}, no area). Outline the next one or exit markup.","toast.marker_needs_server":"Device editing is available after the config is moved to the server","toast.virtual_name_required":"Enter a name for the virtual device","toast.marker_saved":"Device saved","toast.marker_removed":"Device deleted from the plan","toast.integration_missing":"The House Plan integration is not installed — management unavailable","toast.plan_formats":"Supported formats: SVG, PNG, JPG, WebP","toast.plan_required":"Upload a floor plan — it is required","toast.space_added_onboard":"Space added. Outline the rooms: click grid dots and close the contour.","toast.space_added":"Space added","toast.space_copied":"Space “{name}” created","toast.space_saved":"Space saved","toast.space_deleted":"Space deleted","toast.delete_failed":"Delete failed: {err}","toast.error":"Error: {err}","toast.toggle_target_unavailable":"Target “{name}” is unavailable — no action was performed","toast.toggle_targets_unavailable":"Targets are unavailable: {names}. No action was performed","toast.file_failed":'File "{name}" was not uploaded: {err}',"toast.files_attached":"Files attached: {n}","err.unknown":"unknown error","err.code":"code {code}","err.too_large":"file larger than {mb} MB","err.bad_ext":"unsupported type (PDF/image expected)","err.unauthorized":"administrator rights required","editor.title":"Title","editor.default_floor":"Initial space","editor.default_floor_missing":"Initial space “{id}” no longer exists. Choose another space.","editor.floor":"Fixed space","editor.floor_none":"— not fixed —","editor.floor_index":"YAML index {index} (preserved)","fixed_floor.loading":"Loading the fixed space…","fixed_floor.invalid_title":"The fixed space is unavailable","fixed_floor.invalid_body":"Check floor in the card configuration. The configured value is: {value}","editor.icon_size":"Icon size, % of plan width","editor.show_temperature":"Show temperature","editor.live_states":"Live states (on/off, open…)","editor.light_pools":"Light pools and wall shadows","editor.show_signal":"Show zigbee signal (LQI)","editor.language":"Interface language","editor.lang_auto":"Auto (HA profile)","title.icon_rules":"Icon rules: which MDI icon devices get by name","rules.title":"Icon rules","rules.hint":"Rules are checked top-down against “device name + model” (case-insensitive regex); the first match wins. When nothing matches, the entity device class decides, then the generic chip icon.","rules.pattern_ph":"regex, e.g. plug|socket","rules.icon_ph":"mdi:power-socket-de","rules.add":"Add rule","rules.reset":"Reset to defaults","rules.test_ph":"Try a device name…","rules.invalid":"invalid regex","rules.saved":"Icon rules saved","btn.up":"Up","btn.down":"Down","tap.info":"Device card","tap.more_info":"HA more-info dialog","tap.toggle":"Toggle state","marker.tap_label":"Tap action for this device","tap.toggle_note":"The resolved state is shown below. Secure devices are never toggled from the plan.","import.title":"Create spaces from HA floors","import.hint":"Your Home Assistant already knows these floors. Pick the ones to turn into plan spaces — you will upload a floor-plan image for each one next. Rooms are then outlined by hand on the plan.","import.start":"Create {n} space(s)","import.manual":"Start from scratch","import.progress":"Floor {i} of {n}","import.done":"Spaces created. Outline the rooms: click grid dots and close the contour.","btn.skip":"Skip","space.scale_label":"Scale (grid cell size)","space.cell_cm.help":"Links the grid to real dimensions: lengths, areas, wall thickness, opening sizes and glow radius depend on it. Changing it after drawing changes the calculated dimensions of the whole space without moving its points on the plan.","space.cell_cm.help.aria":"Help: space scale","space.scale_unit":"cm per cell","space.scale_unit_imperial":"in per cell","space.display_section":"Display","space.show_borders":"Always show room borders","space.zero_wall_style":"Zero-thickness walls","space.zero_wall_style.help":"Dashed zero-thickness walls pass Glow and sun rays, while solid ones block them as zero-area barriers. The choice affects every such wall in the space even when its line is hidden in View.","space.zero_wall_style.help.aria":"Help: zero-thickness wall style","space.zero_wall_dashed":"Dashed","space.zero_wall_solid":"Solid","space.show_names":"Show room names (drag to move)","space.room_color":"Border & name color","space.opacity":"Opacity","space.fill_label":"Room fill","space.fill_mode.help":"“Custom colour” is styling, while “Light”, “Temperature” and “LQI” use current Home Assistant data; Glow is enabled separately.","space.fill_mode.help.aria":"Help: room fill mode","fill.none":"None","fill.lqi":"Zigbee signal","fill.light":"Lights","fill.custom":"Custom color","space.custom_fill":"Fill color","space.source_file":"I have a floor-plan image","space.source_draw":"No image — I'll outline rooms by hand","fill.temp":"Temperature","tip.temp_avg":"average temperature:","tip.hum_avg":"average humidity:","space_card.button":"Open the space plan","space_card.not_found":"Space “{id}” not found","space_card.loading":"Loading…","continuity.restore_plan":"Restoring floor plan…","continuity.restore_connection":"Restoring device connection…","continuity.retry":"Try again","editor.space":"Space","editor.framing":"Framing","editor.fit_content":"All visible content","editor.fit_house":"Tight to house geometry","editor.show_button":"Show button","editor.button_label":"Button label","editor.button_target":"Target dashboard path","marker.sub_entity":"entity","title.general_settings":"General settings","title.export_pdf":"Save as PDF","pdf.title":"Save as PDF","pdf.dimensions":"Show dimensions and areas","pdf.decor":"Show furniture and other decor","pdf.room_names":"Show room names","pdf.backdrop":"Show backdrop","pdf.save":"Save","pdf.saving":"Creating…","pdf.failed":"Could not create the PDF.","pdf.too_large":"The images exceed the 25 MB PDF limit.","pdf.asset_failed":"A backdrop or decor image could not be loaded.","pdf.scale":"Scale 1:{n}","pdf.north":"North","gs.title":"General settings","gs.light_group":"Fill: lights","gs.light_on":"Lights on","gs.light_off":"All lights off","gs.temp_group":"Fill: temperature","gs.temp_cold":"Cold","gs.temp_ok":"Comfortable","gs.temp_hot":"Hot","gs.lqi_group":"Fill: zigbee signal","gs.lqi_low":"Weak signal","gs.lqi_high":"Strong signal","gs.reset":"Reset to defaults","gs.saved":"General settings saved","gs.radar_show_live":"Show live presence on the plan","gs.radar_show_live_hint":"Hides or shows all live radar targets. This does not start or stop observation recording.","radar.title":"Presence on the plan","radar.help":"Connect this marker to exact Home Assistant radar entities, place the sensor and choose its coordinate profile. Live positions are clipped to the selected room.","radar.help.aria":"Help: presence radar settings","radar.enabled":"Use this presence radar","radar.show_live":"Show live targets","radar.configure":"Configure radar","radar.configure_on_plan":"Configure on plan","radar.change_installation":"Change installation","radar.no_contour":"This room has no boundary. Radar points will not be clipped.","radar.discard_setup_title":"Discard radar setup?","radar.discard_setup":"The unsaved radar setup will be lost.","radar.step_place_mount":"Mark the physical sensor position","radar.step_place_heading":"Mark a point straight ahead of the sensor","radar.step_reference":"Mark reference position {n}, then start measurement","radar.step_check_reference":"Mark an independent check position","radar.start_measure":"Start measurement","radar.countdown":"Stand at the mark in {seconds} s","radar.capturing":"Stand still and alone while measuring…","radar.fit_ready":"Calibration is ready","radar.check_third":"Check at another position","radar.check_complete":"Independent check completed","radar.error_distance":"Position difference: {distance}","radar.ambiguous_target":"More than one target was reported. Repeat the measurement alone.","radar.insufficient_samples":"Not enough current coordinates. Retry or use manual setup.","radar.bad_references":"Choose separated references in different directions from the sensor.","radar.ambiguous_sources":"The measurements allow two equally plausible directions. Choose reference points that distinguish left from right.","radar.bad_fit":"Measurements do not match. Check units, mounting point and references.","radar.desktop_hint":"Use a computer for precise setup. Editing on touch devices is best effort.","radar.detected":"House Plan recognized radar metadata for this device. Review the exact sources before saving.","radar.detected_ld2450":"House Plan found an ESPHome LD2450 coordinate set. Review the exact X/Y sources before saving.","radar.additional_actions":"Additional actions","radar.declare":"This is a presence radar","radar.profile":"Data profile","radar.profile_esphome_ld2450_v1":"ESPHome LD2450 (X/Y targets)","radar.profile_cartesian_v1":"Cartesian targets (X/Y)","radar.profile_polar_v1":"Polar target (distance/angle)","radar.profile_range_v1":"Distance only","radar.profile_zones_v1":"Zone states","radar.profile_presence_v1":"Presence only","radar.room":"Radar room","radar.room_choose":"Choose a room","radar.target":"Target {n}","radar.axis_x":"X coordinate entity","radar.axis_y":"Y coordinate entity","radar.add_target":"Add target slot","radar.range_channel":"Range channel {n}","radar.add_range":"Add range channel","radar.presence_gate":"Presence gate entity","radar.swap_axes":"Swap X and Y axes","radar.axis_x_sign":"X direction","radar.axis_y_sign":"Y direction","radar.distance_source":"Distance entity","radar.angle_source":"Angle entity","radar.angle_unit":"Angle unit","radar.degrees":"Degrees","radar.radians":"Radians","radar.angle_zero":"Zero-angle direction","radar.angle_forward":"Forward","radar.angle_right":"Right","radar.angle_clockwise":"Angles increase clockwise","radar.zone_source":"Zone entity","radar.occupancy_source":"Presence entity","radar.count_source":"Target count entity","radar.availability_source":"Availability entity","radar.source_choose":"Choose an entity","radar.source_optional":"Optional","radar.source_missing":"currently unavailable","radar.saved_unsupported":"This saved radar setup is unsupported or incomplete. It remains inactive; remove it or update House Plan before configuring it again.","radar.occupancy":"Presence (on/off)","radar.count":"Count","radar.mount":"Position and direction","radar.mount_hint":"This is the physical sensor position. Moving its decorative marker does not change it.","radar.heading":"Direction, °","radar.range_cm":"Range, cm","radar.fov_deg":"Field of view, °","radar.unit":"Source unit","radar.mirror":"Mirror the left/right axis","radar.remove":"Remove radar settings","radar.invalid":"Complete the radar room, sources and position before saving.","radar.check_sources":"Check live data","radar.checking":"Checking…","radar.health":"Connection status","radar.live_summary":"Current targets: {targets}; range arcs: {ranges}","radar.health_ok":"Current data received","radar.health_off":"No targets detected","radar.health_stale":"Some coordinate data is out of date","radar.health_partial":"Some sources are current; others are out of date","radar.health_restricted":"Access to one or more sources is restricted","radar.health_incomplete":"The current radar report is incomplete","radar.health_position_unavailable":"Presence reported; current position unavailable","radar.health_unavailable":"Sensor data unavailable","radar.health_needs_setup":"Installation needs setup","radar.health_inconsistent":"The sources report conflicting values","radar.health_unknown":"Current state is unknown","radar.health_disabled":"Radar is disabled","radar.error_invalid_radar":"Check the radar settings.","radar.error_invalid_selection":"Select an existing room and valid sources.","radar.error_source_restricted":"You do not have access to all selected sources.","radar.error_rate_limited":"Too many requests. Try again shortly.","radar.error_not_ready":"Radar processing is not ready.","radar.error_conflict":"The plan changed. Reopen the radar setup and try again.","radar.error_source_unavailable":"One or more selected radar sources are unavailable.","radar.error_unsupported_capability":"This radar capability is not supported by the installed integration.","radar.report_age":"{seconds} s ago","space.show_lqi":"Show zigbee signal (LQI) next to devices","space.hide_decor":"Hide the decorative layer","space.hide_decor_tip":"Lines, shapes, labels and furniture stay where they are — visible in the backdrop editor, not on the plan.","space.hide_openings":"Hide openings","space.hide_openings_tip":"Door, window and gate symbols are not drawn, but the openings keep working: light passes through, the sun comes in at a window, contact sensors still open them. The plan editor always shows them.","gs.light_none":"No light sources","mode.plan":"Plan editor","mode.devices":"Device editor","display.value":"Value + state","marker.subarea":"no area, manual","device.new":"New device — open its editor to dismiss","opening.unlock_action":"Unlock","opening.lock_action":"Lock","opening.lock_pending":"Working…","title.close_editor":"Close editor (back to view)","title.add_device":"Add a device to the plan","devbar.add":"Add","devbar.rules":"Icon rules","device_inbox.button":"Devices","device_inbox.title":"Devices on the plan","device_inbox.search":"Search devices, entities and integrations…","device_inbox.add_virtual":"Add virtual device","device_inbox.tab_on_plan":"On plan","device_inbox.tab_available":"Available","device_inbox.tab_hidden":"Hidden","device_inbox.tab_readd":"Available again","device_inbox.only_new":"New only","device_inbox.show_entities":"Show entities","device_inbox.show_hidden":"Show hidden on plan","device_inbox.show_hidden.help":"Temporarily shows hidden and disabled markers as editor-only ghosts on the plan. Saved device visibility does not change.","device_inbox.show_hidden.help.aria":"Help: show hidden devices on the plan","device_inbox.new":"New","device_inbox.find":"Find on plan","device_inbox.edit":"Edit","device_inbox.hide":"Hide","device_inbox.show":"Show","device_inbox.add":"Add","device_inbox.readd":"Add again","device_inbox.hide_available":"Hide from list","device_inbox.show_more":"Show more","device_inbox.more_actions":"More actions","device_inbox.find_hidden_hint":"Enable “Show hidden on plan” first","device_inbox.show_disabled":"Activate this binding in Home Assistant before showing it","device_inbox.empty_on_plan":"No matching devices are on the plan yet.","device_inbox.empty_available":"No devices are available to add.","device_inbox.empty_hidden":"There are no hidden devices.","device_inbox.empty_readd":"No removed devices are available to add again.","device_inbox.reason_visible_auto":"Discovered automatically","device_inbox.reason_visible_explicit":"Added explicitly","device_inbox.reason_manual_hidden":"Hidden by user","device_inbox.reason_automatic_hidden":"Hidden automatically","device_inbox.reason_service_entry":"Service-only registry entry","device_inbox.reason_excluded_integration":"Integration “{integration}” excluded by discovery filters","device_inbox.reason_excluded_domain":"Non-spatial entity type","device_inbox.reason_grouped_light":"Represented by a room light group","device_inbox.reason_represented_by_parent":"Represented by its parent device","device_inbox.reason_removed":"Previously removed from the plan","device_inbox.reason_available":"Available to add to the plan","device_inbox.reason_no_bound_room":"HA area is not linked to a plan room","device_inbox.status_ha_disabled":"Disabled in Home Assistant","device_inbox.status_orphaned":"Binding is no longer present in Home Assistant","device_inbox.status_unverified":"Home Assistant registry is temporarily unavailable","device_inbox.saved":"Device list updated","device_inbox.filters_excluded":"Excluded integrations","device_inbox.filters_group_lights":"Group room lights into one marker","device_inbox.filters_preview_appear":"will appear: {count}","device_inbox.filters_preview_hide":"will disappear: {count}","device_inbox.filters_preview_lights":"lights affected: {count}","device_inbox.filters_reset":"Restore recommended","device_inbox.filters_save":"Save filters","device_inbox.filters_search_ph":"Add an integration…","device_inbox.filters_title":"Discovery filters","space.roomcard_section":"Room card shows:","space.label_temp":"Temperature","space.label_hum":"Humidity","space.label_lqi":"Average Zigbee signal","space.label_light":"Lights on/off","roomcard.light_on":"On","roomcard.light_off":"Off","roomcard.light_partial":"{on} of {total}","toast.split_pick_inside":"Intermediate cut points must be inside the room","mode.decor":"Background editor","decor.select":"Select","decor.line":"Line","decor.rect":"Rectangle","decor.ellipse":"Oval","decor.text":"Text","decor.erase":"Erase","decor.erase_confirm_title":"Erase object?","decor.color":"Color","decor.width":"Line width","decor.line_style":"Line style","decor.line_style_solid":"Solid","decor.line_style_dashed":"Dashed","decor.fill":"Fill","decor.fill_color":"Fill color","decor.length":"Length","decor.size":"Size","decor.flip_h":"Flip horizontally","decor.flip_v":"Flip vertically","decor.angle":"Rotation angle, °","decor.text_size":"Text size","decor.backdrop_properties":"Plan backdrop properties","decor.text_title":"Text label","decor.object_title":"Edit {kind}","decor.text_label":"Text","decor.live_group":"Insert HA variable","decor.live_entity":"Entity","decor.live_entity_ph":"choose an entity","decor.live_attr":"Value","decor.live_attr_ph":"choose state or attribute","decor.live_state":"State","decor.backdrop":"Backdrop image","decor.backdrop_hint":"Drag to move; pull a corner to resize; use the top handle to rotate. Shift changes proportions or frees the angle.","decor.backdrop_reset":"Reset the picture","decor.backdrop_reset_done":"The picture is back at its original place and size","marker.icon_auto":"Auto: {icon} (by icon rules; pick one to override)","marker.icon_pin_auto":"Pin","mode.plan_tip":"Plan editor — the geometry of the home: draw and split/merge rooms, bind them to HA areas, place doors, windows and gates, move room cards, set the scale","mode.devices_tip":"Device editor — everything about icons: drag to position, click to edit binding/icon/display, add virtual devices, icon rules","mode.decor_tip":"Background editor — purely visual decor under the plan: lines, rectangles, ovals and text labels that never react to clicks","space.glow_enabled":"Light-source glow","gs.glow_group":"Light-source glow","gs.glow_base":"House darkness","gs.glow_light":"Default light color / intensity","gs.wall_group":"Walls","gs.wall_fill":"Wall fill","gs.glow_radius":"Glow radius","gs.glow_radius.help":"Sets the default glow radius in metres or feet; a device-specific radius overrides it.","gs.glow_radius.help.aria":"Help: default glow radius","gs.unit_m":"m","gs.unit_ft":"ft","marker.controls_label":"Controls other light sources","marker.controls.help":"With the “Toggle state” action, the listed sources toggle together with this marker. Their glow stays at their own markers, and the link alone does not turn the controlling marker into a light source.","marker.controls.help.aria":"Help: controlling other light sources","marker.controls_filter":"Search lights and switches…","info.controls":"Controls","marker.glow_radius_label":"Glow radius","marker.glow_radius.help":"Sets the glow radius in metres or feet; an empty value uses the radius from general settings.","marker.glow_radius.help.aria":"Help: glow radius","markup.wallthick":"Thickness","markup.select":"Select","title.markup_wallthick":"Thickness — click a wall to set its thickness from 0 to 100 cm.","markup.hint_wallthick":"click a wall · Esc closes without applying","wallthick.field":"Thickness","wallthick.unit_cm":"cm","wallthick.unit_in":"in","wallthick.apply_room":"Apply to all walls of this room","markup.draw_wall_title":"Thickness of each new wall segment (0–100 cm). Shared walls keep the existing value.","room.queue_progress":"Room {current} of {total}","toast.wall_rooms_saved":"Created rooms: {n}","toast.wall_chain_saved":"Wall chain saved","toast.wallthick_pick":"Click a wall","toast.wallthick_set":"Wall thickness set","toast.wallthick_cleared":"Wall thickness removed","toast.physical_range":"Enter a value from {min} to {max} {unit}","toast.zero_wall_opening_conflict":"Remove the opening on this wall segment first.","toast.zero_wall_ambiguous":"The wall segment is ambiguous. Simplify or adjust the junction.","toast.zero_wall_migration_blocked":"The space was not converted: {reason}. No data was changed.","toast.physical_angle":"Enter a rotation angle from 0° up to, but not including, 90°","toast.physical_limit":"The space has reached the limit for this type of geometry","toast.geometry_unsafe":"Change canceled: wall geometry could not be built safely.","junction.limit_angle":"The angle between walls is too sharp: {actual}°, minimum {limit}°.","junction.limit_valence":"Too many walls meet in one node: {actual}, maximum {limit}.","junction.limit_length":"The wall segment is too short: {actual} cm, minimum {limit} cm.","junction.limit_distance":"Walls and nodes are too close: {actual} cm, minimum {limit} cm.","junction.limit_clearance":"No room interior is left: {actual} cm², minimum {limit} cm².","junction.limit_check_failed":"The junction check could not run — the change was not saved","toast.wall_model_migration_blocked":"The wall model could not be updated: {reason}. The plan was not changed. Run “Optimize plans”; if the error repeats, fix the conflicting wall geometry.","toast.wall_model_client_outdated":"Update the card and reload the page before editing the plan.","wall_model.reason.invalid-room":"invalid room contour","wall_model.reason.zero-length":"zero-length wall segment","wall_model.reason.third-owner":"wall shared by more than two rooms","wall_model.reason.duplicate-id":"conflicting wall identifiers","wall_model.reason.thickness-conflict":"conflicting wall thickness values","wall_model.reason.opening-host":"opening cannot be assigned to one wall","toast.delete_room_pick":"Click inside the room you want to delete","toast.plan_snap_ambiguous":"Zoom in to choose the wall node","toast.wall_repair_ambiguous":"The room outline has more than one possible connection. Zoom in and connect it explicitly.","toast.wall_repair_too_large":"The gap is larger than 2 cm. Connect the walls before creating the room.","toast.wall_repair_changed":"The wall geometry changed. Try creating the room again.","toast.opening_on_zero_wall":"Openings cannot sit on a zero-thickness wall","marker.from_ha_option":"Pick from the HA list","marker.show_entities":"Show entities","marker.show_entities_tip":"Adds not only devices to the list, but all their entities too","marker.pick_ph":"Choose a device…","room.open_area":"Open the HA area","room.fit_action":"Fit room {name}","view.volumetric":"Volumetric view","view.flat":"Flat view","kiosk.title":"This screen's sizes","kiosk.hint":"Stored on this device only — every wall tablet or TV can have its own comfortable sizes.","kiosk.icon_scale":"Device icon size","kiosk.font_scale":"Room card text size","editor.kiosk":"Wall device (kiosk) mode","editor.cycle":"Auto-switch spaces every N seconds (kiosk, 0 = off)","room.settings_title":"Room settings","room.settings_section":"Room settings (override the space)","room.fill_label":"Fill in THIS room","fill.inherit":"As the space","room.custom_fill_space":"Space color","room.custom_fill_own":"Room color","room.temp_range_label":"Comfort range","room.temp_range_min":"Lower comfort-temperature bound","room.temp_range_max":"Upper comfort-temperature bound","room.temp_range_reset":"As the space","room.temp_range.help":"This range applies only to this room. Empty fields inherit the corresponding space bounds; if the bounds are reversed, House Plan uses the smaller value as the lower bound and the larger value as the upper bound.","room.temp_range.help.aria":"About the room comfort range","room.temp_src_label":"Temperature source","room.hum_src_label":"Humidity source","room.src_average":"Average over the room's sensors (default)","room.src_pick":"A specific HA device or entity","room.src_ph":"Choose a source…","toast.room_updated":"Room updated","space.card_font":"Room-card font size (whole space)","room.sizes_section":"Font sizes","room.name_scale":"Room name size","room.label_scale":"Metrics size","preview.room_name":"Living room","toast.cfg_reload_failed":"Could not reload the plan from the server: {err}","toast.locale_load_failed":"Could not load the language pack. English is used until the page reloads.","toast.furniture_art_load_failed":"Could not load the furniture drawings. Reload the page to show them.","room.settings_short":"Room settings","room.unnamed":"Unnamed room","marker.use_climate_temp":"Include the device temperature in the room","marker.use_climate_temp_tip":"Adds an air conditioner or thermostat current_temperature to the room average. Configure the external value badge separately below.","marker.value_badge_title":"Value badge","marker.value_badge.help":"Shows one selected value next to the icon. It does not affect room metrics, light, Glow or the tap action.","marker.value_badge.help.aria":"Help: device value badge","marker.value_badge_enabled":"Show a value badge","marker.value_badge_source":"Value","marker.value_badge_source.help":"Choose a specific state, supported attribute, or derived value of this device.","marker.value_badge_source.help.aria":"Help: value badge source","marker.value_badge_position":"Position","marker.value_badge_position.help":"The chosen side stays fixed and does not flip automatically at a plan edge.","marker.value_badge_position.help.aria":"Help: value badge position","marker.value_badge_right":"Right","marker.value_badge_bottom":"Below","marker.value_badge_left":"Left","marker.value_badge_top":"Above","marker.value_badge_empty":"This device has no available values","marker.value_badge_static":"A static icon does not show live values. The setting is preserved.","marker.value_badge_missing":"Source unavailable","marker.value_badge_missing_hint":"The saved source is currently unavailable. Keep it, disable the badge, or choose another value.","marker.value_badge_duplicate":"The same value is already shown inside the icon.","marker.value_badge_state":"State · {name}","marker.value_badge_marker_state":"Light-source state · {name}","marker.value_badge_lqi":"Average Zigbee signal quality","marker.value_badge_attr_current_temperature":"Current temperature · {name}","marker.value_badge_attr_temperature":"Target temperature · {name}","marker.value_badge_attr_current_humidity":"Current humidity · {name}","marker.value_badge_attr_humidity":"Humidity · {name}","marker.value_badge_attr_current_position":"Position · {name}","marker.value_badge_attr_percentage":"Speed · {name}","marker.value_badge_attr_brightness":"Brightness · {name}","marker.value_badge_attr_volume_level":"Volume · {name}","marker.value_badge_attr_battery_level":"Battery · {name}","marker.value_badge_attr_fan_speed":"Fan speed · {name}","marker.value_source":"Value source","marker.value_source.help":"Choose the value that replaces the icon. The tap action does not change.","marker.value_source.help.aria":"Help: value face source","marker.value_source_auto":"Automatic (as before)","marker.value_source_missing_hint":"The saved source is currently unavailable. The face shows — until it recovers or you choose another value.","marker.light_role_label":"Is this device a light source?","marker.light_role.help":"“Auto” uses the bound device's resolved role, “Always” forces its own source and “Never” excludes it; linked lights above remain independent.","marker.light_role.help.aria":"Help: whether this device is a light source","marker.light_role_auto_yes":"Auto (light source)","marker.light_role_auto_no":"Auto (not a light source)","marker.light_role_always":"Always a light source","marker.light_role_never":"Never a light source","marker.light_entity_label":"Leading light entity","marker.light_entity.help":"For a composite device, choose the entity whose state, colour and brightness represent this plan source. The automatic fallback remains compatible with older plans.","marker.light_entity.help.aria":"Help: leading light entity","marker.light_entity_auto":"Automatic ({entity})","marker.light_entity_none":"no controllable entity","marker.light_entity_missing":"The saved entity {entity} is unavailable. House Plan temporarily uses {fallback}; the saved choice will be restored if it returns.","marker.toggle_entity_label":"Entity to toggle","marker.toggle_entity.help":"For a composite device, choose the exact own light or switch operated by a tap. Automatic keeps the previous target rules and is independent from the leading light entity.","marker.toggle_entity.help.aria":"Help: entity to toggle","marker.toggle_entity_auto":"Automatic ({entity})","marker.toggle_entity_none":"no own controllable entity","marker.toggle_entity_missing":"The saved entity {entity} is no longer among this marker’s selectable channels. House Plan temporarily uses {fallback}; the saved choice will be restored if it returns.","marker.glow_color_label":"Glow colour and brightness","marker.glow_mode.help":"Use live source values, override only its colour, or fix both colour and brightness. The minimum is 1%; to disable the source, choose “Never”.","marker.glow_mode.help.aria":"Help: glow colour and brightness","marker.glow_mode_auto":"From source","marker.glow_mode_color":"Set colour","marker.glow_mode_fixed":"Set colour and brightness","marker.glow_color":"Glow colour","marker.glow_brightness":"Brightness","marker.glow_disabled_never":"Glow settings are unavailable because this marker is explicitly not a light source.","marker.glow_disabled_auto":"Auto mode found no spatial light source for this marker.","marker.glow_disabled_no_entity":"No active controllable Home Assistant entity is available for this spatial source.","marker.glow_passive_hint":"This source has no own Home Assistant data. Set its colour and brightness manually; its radius remains available.","marker.control_broken":"Saved source is missing or no longer marked as a light","marker.control_missing_label":"Missing plan light","marker.control_passive":"passive source","toast.marker_control_cycle":"This link would create a circular chain of light controls.","toast.marker_binding_required":"Choose a Home Assistant device before linking another light source.","confirm.unlock_title":"Unlock?","confirm.unlock_body":"House Plan will send an unlock command to this lock.","toast.files_migrate_failed":"Attachments could not be moved to the new binding, links keep pointing at the old files: {err}","space.pick_saved":"Already uploaded","space.pick_saved_hint":"Plans stored on the server, including ones you detached earlier","space.no_saved":"No plans stored on the server yet.","space.loading":"Loading…","space.used_by":"in use: {list}","space.in_use":"A space still uses this plan — detach it first","btn.use":"Use","confirm.delete_plan_title":"Delete plan file?","confirm.delete_plan_body":"The file will be deleted from the server. This action cannot be undone.","toast.plans_list_failed":"Could not list the stored plans: {err}","toast.plan_delete_failed":"Could not delete the plan: {err}","marker.hide":"Hide","marker.hide_tip":'The device will disappear from the plan after saving but will still count toward the room signal. Restore it through the "Devices" catalog in the device editor.',"marker.show":"Show","marker.show_tip":"The device will appear on the plan again after saving.","marker.hidden_ghost":"Device hidden by the user","marker.ha_disabled_device":"The device is disabled in Home Assistant and hidden from the plan.","marker.ha_disabled_entity":"The entity is disabled in Home Assistant and hidden from the plan.","marker.ha_disabled_all_entities":"The device has no active Home Assistant entities, so it is hidden from the plan.","marker.ha_registry_limited":"The full Home Assistant registry is unavailable to this user. The unverified object cannot be shown or used for now.","marker.delete_tip":"Completely delete the device from the plan and every aggregate. You can add it again later.","tap.run":"Run automation/script/scene","tap.none":"Do nothing","marker.run_target_label":"What to run","marker.run_search_ph":"Search: automation, script or scene…","marker.run_target_gone":"Target {id} not found — pick again","marker.tap_confirm":"Ask for confirmation","marker.tap_confirm_tip":"Show a confirmation dialog before acting — a guard against accidental taps.","marker.toggle_hint_single":"Target: {name} ({id}).","marker.virtual_light_target":"Virtual light: {name}.","marker.virtual_light_current":"Manual state: {state} → {effect}.","marker.virtual_light_state_on":"on","marker.virtual_light_state_off":"off","marker.toggle_hint_group":"Will toggle {count} source(s): {names}.","marker.toggle_hint_current":"Now: {state} → {effect}.","marker.toggle_hint_group_current":"Currently on: {on} of {count} → {effect}.","marker.toggle_hint_skipped":"Will be skipped ({count}): {targets}.","marker.toggle_effect_turn_on":"will turn on","marker.toggle_effect_turn_off":"will turn off","marker.toggle_effect_open":"will open","marker.toggle_effect_close":"will close","marker.toggle_effect_stop":"will stop","marker.toggle_effect_toggle":"state will toggle","marker.toggle_skip_missing":"not found","marker.toggle_skip_ha_disabled":"disabled in HA","marker.toggle_skip_unavailable":"unavailable","marker.toggle_skip_unsupported":"toggle is unsupported","marker.toggle_skip_secure":"blocked for security","marker.toggle_none_no_binding":"This device has no binding, so there is no state to toggle. Tapping will do nothing.","marker.toggle_none_no_actionable_entity":"This device has no state that can be toggled. Tapping will do nothing.","marker.toggle_none_configured_targets_missing":"The configured targets are unavailable. The device's own entity will not be substituted for them.","marker.toggle_none_ha_disabled":"The target is disabled in Home Assistant and cannot be used on the plan.","marker.toggle_none_unavailable":"The target is currently unavailable. Tapping will do nothing.","marker.toggle_none_unsupported":"Home Assistant exposes no safe toggle operation for this entity. Tapping will do nothing.","marker.toggle_none_secure":"Toggling locks, alarms and secure gates from the plan is blocked for security.","run.automation":"automation","run.script":"script","run.scene":"scene","confirm.tap_run":'Run "{name}"?',"confirm.tap_toggle":'Toggle "{name}"?',"confirm.current_state":"Current state: {state}","confirm.expected_state":"After switching: {state}","confirm.group_current":"on {on} of {total}","confirm.group_all_on":"all are on","confirm.group_all_off":"all are off","confirm.unavailable_targets":"Unavailable: {count}","confirm.expected_by_ha":"Home Assistant will determine the state","confirm.state_on":"On","confirm.state_off":"Off","confirm.state_open":"Open","confirm.state_closed":"Closed","confirm.state_opening":"Opening","confirm.state_closing":"Closing","confirm.state_stopped":"Stopped","confirm.state_unknown":"Unknown","toast.run_started":"Started: {name}","toast.run_target_missing":"Run target not found — check the device settings","toast.run_target_required":"Pick an automation, script or scene","toast.tap_target_changed":"The action target changed. Try again.","toast.virtual_light_toggle_failed":"Could not toggle the virtual light: {err}","toast.value_badge_source_required":"Choose a value for the badge","btn.run":"Run","vac.section":"Robot vacuum: live position","vac.autocal":"Set up automatically","vac.live":"Live position on the plan","vac.trail":"Show the robot's path","vac.autocal_no_rooms":"The integration reports no room list — open “Fit manually”","vac.route_warn_unmapped":"The robot is cleaning a map that is not assigned to any floor","vac.route_warn_needs_calibration":"The map is assigned to a floor but not calibrated","vac.route_warn_ambiguous":"Two maps are indistinguishable — no floor was chosen","vac.route_warn_missing_space":"The space of this map was deleted","vac.autocal_no_match":"Room names did not match (need ≥3 in common) — open “Fit manually”","vac.autocal_done":"Done: bound via {rooms} rooms. Start a cleanup and check","vac.cal_need_pos":"The robot is not reporting coordinates — start a cleanup and pause it","vac.cal_done":"Calibration saved. Start a cleanup and check","vac.cal_cancelled":"Calibration cancelled","vac.fit":"Fit manually","vac.fit_hint":"Drag the robot map into place, stretch by the corners","vac.fit_rotate":"Rotate 90°","vac.fit_mirror":"Mirror","vac.trail_never":"Never","vac.trail_cleaning":"While cleaning","vac.trail_always":"Always","gs.bg_group":"Stage background","gs.bg_color":"Background around the plan","gs.bg_default":"Theme default","gs.bg_theme":"theme default","gs.bg_mode":"Plan background","gs.bg_mode.help":"“Follows the Sun” uses sun.sun, falling back to the browser's local clock; Static always shows the selected colour.","gs.bg_mode.help.aria":"Help: general plan background","gs.bg_static":"Static color","gs.bg_daynight":"Follows the Sun","gs.sun_group":"Sun","gs.sun_missing":"The sun.sun entity was not found — the background follows your local clock; window rays are unavailable.","gs.north":"North on the plan","gs.north.help":"The angle is measured clockwise from the plan's upward vertical; north is required for window rays, not for the “Follows the Sun” background.","gs.north.help.aria":"Help: general north direction","gs.north_ph":"not set","gs.north_clear":"Clear","gs.north_letter":"N","gs.sun_rays":"Sunlight through windows","gs.sun_ray_origin":"Sun rays","gs.sun_ray_origin.inner":"From the inner window corners","gs.sun_ray_origin.outer":"From the outer window corners","gs.about_version":"Houseplan Card v{v}","gs.about_github":"GitHub · docs & issues","gs.about_telegram":"Telegram chat","support.title":"Help & feedback","space.bg_color":"Background around the plan","space.bg_inherit":"Inherit general","space.bg_inherited":"inherits general settings","space.bg_mode":"Plan background","space.bg_mode.help":"Inherit the general background or override this space with a static colour or “Follows the Sun”.","space.bg_mode.help.aria":"Help: space background","space.north":"North on the plan (override)","space.north.help":"Overrides general north for this space; the angle is measured clockwise from the plan's upward vertical and is used by window rays.","space.north.help.aria":"Help: north for this space","space.north_inherited":"inherited: {v}","space.sun_rays":"Sunlight through windows","space.sun_inherit":"Inherit general","space.sun_on":"On","space.sun_off":"Off","canvas.far_objects":"{n} object(s) far from the plan","canvas.show_far":"Show","canvas.home_tip":"The plan is over there — click to fit it","gs.grid_group":"Plan maintenance","gs.grid_hint":"Updates data models, aligns plan elements to the grid and merges redundant wall fragments. An exact report is shown before anything is stored.","gs.align_all":"Optimize plans","gs.align_title":"Optimize plans","gs.align_none":"All plans already use the current optimized data model.","gs.optimize_no_automatic_changes":"There are no automatic changes to apply. Review the items below.","gs.align_count":"{n} of {total} elements will move, by at most {cm} cm.","gs.align_where":"The largest shift is in “{s}”.","gs.align_turned":"Openings whose angle is corrected: {n}.","gs.align_preflight_failed":"Could not safely verify the geometry of the following spaces: {spaces}{more}.","gs.align_preflight_hint":"Plans were not changed. Copy the diagnostics with the button below and attach them to the bug report together with a space export.","gs.preflight_reason_prepare-exception":"Could not prepare the space geometry (exception while building the model)","gs.preflight_reason_wall-null":"The wall body did not build (the union came back empty)","gs.preflight_reason_wall-degraded-extra":"The wall body degraded with extra geometry","gs.preflight_reason_wall-failed-core":"The wall body core failed to assemble","gs.preflight_reason_wall-exception":"Wall construction threw an exception","gs.preflight_reason_floor-null":"The floor outline did not build","gs.preflight_reason_floor-exception":"Floor construction threw an exception","gs.preflight_copy":"Copy diagnostics","gs.preflight_copied":"Diagnostics copied","gs.preflight_update_hint":"The card and integration versions differ — update House Plan and retry.","gs.align_preflight_space":"Space {n}","gs.align_preflight_more":", and {n} more","gs.optimize_changes":"Model migrations: {m}; spaces updated: {c}; noisy coordinate values removed: {p}; merged real-wall fragments: {w}; merged zero-thickness wall fragments: {s}; independent walls: {i}.","gs.zero_walls_migrated":"Virtual wall spans converted: {n}.","gs.wall_segments_migrated":"Wall segments stabilised: {n}.","gs.room_drafts_migrated":"Unfinished contours converted to ordinary walls: {drafts}; wall segments: {segments}.","gs.optimize_lattice_summary":"Noisy coordinate values canonicalized: {n}; maximum movement: {cm} cm.","gs.optimize_lattice_space":"{space}: coordinate values canonicalized: {n}; off-grid values left unchanged: {far}.","gs.optimize_coincident_partitions":"Hidden independent wall sections absorbed into room walls: {n}.","gs.optimize_openings_rehosted":"Openings reattached to room walls: {n}.","gs.optimize_walls_straightened":"Walls straightened: {n}; maximum movement: {cm} cm.","gs.optimize_walls_straightened_where":"Largest wall correction: {s}.","gs.optimize_walls_straighten_skipped":"Near-axis walls left unchanged because they could not be repaired safely: {n}.","gs.optimize_glow_migration":"Legacy Glow: {spaces} spaces → no data fill + independent Glow; {rooms} rooms → inherited data fill + independent Glow.","gs.optimize_references":"References repaired: spaces — {spaces}; rooms — {rooms}; positions — {positions}; devices detached from missing spaces — {detached}.","gs.optimize_reference_more":", and {n} more","gs.optimize_orphans_removed":"Forgotten records removed: {total} — room labels: {rooms}; devices: {devices}; group markers: {groups}. They belonged to spaces deleted earlier.","gs.optimize_live_positions":"Old positions in deleted spaces belong to existing objects: {n}{names}. They will be kept.","gs.optimize_live_positions_remove":"Old positions in deleted spaces belong to existing objects: {n}{names}. They are selected for removal.","gs.optimize_live_names":": {names}{more}","gs.optimize_live_remove":"Remove old positions","gs.optimize_live_keep":"Keep old positions","gs.optimize_live_selected":"Old positions will be removed after Optimize is applied.","gs.optimize_unverified":"Could not safely verify positions: {n}. They were left unchanged.","gs.optimize_registry_limited":"Full administrator access to the Home Assistant registries is required for a safe check.","gs.optimize_vacuum_warning":"Vacuum room mappings that still need review: {n}.","gs.optimize_details":"Details","gs.optimize_details_more":"And {n} more records.","gs.optimize_detail_removed":"will be removed","gs.optimize_detail_live":"will be kept","gs.optimize_detail_unverified":"not verified","gs.optimize_detail_room_label":"room label","gs.optimize_detail_device":"device","gs.optimize_detail_group":"group marker","gs.optimize_detail_unknown":"unknown owner","gs.optimize_detail_item":"{status}: {kind} {id}; old space {space}","gs.align_warn":"Elements deliberately placed between grid nodes will move. One undo is available after the operation, only until the next plan edit.","gs.align_run":"Optimize","gs.align_done":"Plans optimized: {n} elements moved, {m} records maintained, {r} references repaired","gs.optimize_undo":"Undo last optimization","gs.optimize_undone":"The last optimization was undone","decor.furniture":"Furniture","decor.image":"Image","decor.image_title":"Custom images","decor.image_upload":"Upload image","decor.image_replace":"Replace image","decor.image_uploading":"Uploading…","decor.image_asset":"Image file","decor.image_pick_hint":"Upload an image or choose one already used in House Plan.","decor.image_place_hint":"Click on the plan to place the image.","decor.image_none":"No uploaded images yet.","decor.image_unavailable":"Image unavailable","decor.image_used":"Used in {n} objects","decor.image_upload_failed":"Could not upload the image: {err}","decor.image_error_capacity":"The custom image storage limit has been reached.","decor.image_in_use":"Remove every placed copy before deleting this image.","decor.image_delete_title":"Delete image file?","decor.image_delete_message":"Delete “{name}” from House Plan? This cannot be undone.","furn.title":"Furniture library","furn.symbol":"Symbol","furn.group_furniture":"Furniture","furn.group_appliance":"Appliances","furn.group_sanitary":"Plumbing","furn.group_other":"Other","furn.width":"Width","furn.depth":"Depth","furn.back_to_categories":"All categories","furn.pick_hint":"Choose a category, then a symbol.","furn.place_hint":"Click on the plan — the piece lands against the nearest wall. Shift places it free.","furn.cat_air_conditioner":"Air conditioners","furn.cat_armchair":"Armchairs","furn.cat_bathtub":"Bathtubs","furn.cat_bed":"Beds","furn.cat_bidet":"Bidets","furn.cat_boiler":"Water heaters","furn.cat_chair":"Chairs","furn.cat_coffee_table":"Coffee tables","furn.cat_cooktop":"Cooktops","furn.cat_dining_table":"Dining tables","furn.cat_dishwasher":"Dishwashers","furn.cat_dryer":"Dryers","furn.cat_fireplace":"Fireplaces","furn.cat_fridge":"Refrigerators","furn.cat_kitchen_cabinet":"Kitchen cabinets","furn.cat_kitchen_sink":"Kitchen sinks","furn.cat_nightstand":"Cabinets","furn.cat_plant":"Plants","furn.cat_rug":"Rugs","furn.cat_shelving":"Shelving","furn.cat_shower":"Showers","furn.cat_sink":"Sinks","furn.cat_sofa":"Sofas","furn.cat_stairs":"Stairs","furn.cat_toilet":"Toilets","furn.cat_tv":"Televisions","furn.cat_wardrobe":"Wardrobes","furn.cat_washer":"Washing machines","furn.cat_work_table":"Desks","furn.sym_sofa":"Two-seat sofa","furn.sym_sofa_three_seat":"Three-seat sofa","furn.sym_sofa_corner_right":"Right sectional sofa","furn.sym_armchair":"Soft armchair","furn.sym_armchair_office":"Office chair","furn.sym_coffee_table":"Rectangular coffee table","furn.sym_coffee_table_round":"Round coffee table","furn.sym_coffee_table_oval":"Oval coffee table","furn.sym_coffee_table_rounded":"Rounded coffee table","furn.sym_table_dining":"Rectangular dining table","furn.sym_table_round":"Round table","furn.sym_table_dining_oval":"Oval dining table","furn.sym_table_dining_rounded":"Rounded dining table","furn.sym_chair":"Chair","furn.sym_chair_bar":"Bar stool","furn.sym_desk":"Rectangular desk","furn.sym_desk_corner":"Corner desk","furn.sym_bed_double":"Double bed","furn.sym_bed_single":"Single bed","furn.sym_nightstand":"Bedside table","furn.sym_cabinet_tv":"TV cabinet","furn.sym_cabinet_shoe":"Shoe cabinet","furn.sym_cabinet_sink":"Sink cabinet","furn.sym_wardrobe":"Wardrobe","furn.sym_bookshelf":"Bookcase","furn.sym_wall_unit":"Wall unit","furn.sym_kitchen_floor":"Kitchen floor module","furn.sym_kitchen_floor_corner":"Kitchen floor corner module","furn.sym_kitchen_wall":"Kitchen wall module","furn.sym_kitchen_wall_corner":"Kitchen wall corner module","furn.sym_shelf_floor":"Floor shelving unit","furn.sym_shelf_wall":"Wall shelf","furn.sym_fridge":"Fridge","furn.sym_stove":"Four-burner cooktop","furn.sym_cooktop_two":"Two-burner cooktop","furn.sym_dishwasher":"Dishwasher","furn.sym_washer":"Washing machine","furn.sym_dryer":"Tumble dryer","furn.sym_tv":"TV on stand","furn.sym_tv_wall":"Wall-mounted TV","furn.sym_ac":"Air conditioner","furn.sym_water_heater":"Water heater","furn.sym_toilet":"Floor-standing toilet","furn.sym_toilet_built_in":"Built-in toilet","furn.sym_bathtub":"Rectangular bathtub","furn.sym_bathtub_corner":"Corner bathtub","furn.sym_shower":"Shower","furn.sym_sink":"Washbasin","furn.sym_kitchen_sink":"Single kitchen sink","furn.sym_kitchen_sink_double":"Double kitchen sink","furn.sym_bidet":"Floor-standing bidet","furn.sym_bidet_built_in":"Built-in bidet","furn.sym_stairs":"Stairs","furn.sym_fireplace":"Fireplace","furn.sym_plant":"Plant","furn.sym_rug":"Rug","common.yes":"Yes","common.no":"No","vac.diag_source":"Source","vac.diag_platform":"Integration","vac.diag_status":"Status","vac.diag_position":"Position","vac.diag_rooms":"Rooms","vac.diag_rooms_value":"{total} · {matched} names match · {readiness}","vac.autocal_ready":"auto-calibration available","vac.autocal_not_ready":"need 3 matching names","vac.diag_path":"Integration path","vac.diag_map":"Map ID","vac.source_none":"not selected","vac.source_status_ok":"Ready","vac.source_status_missing":"Missing","vac.source_status_disabled":"Disabled in Home Assistant","vac.source_status_unavailable":"Unavailable","vac.source_status_unverified":"Cannot verify with current permissions","vac.source_status_unsupported":"No position data","vac.source_status_none":"No source","vac.source_banner_missing":"The saved source no longer exists. It was not replaced automatically; choose another source or restore it in Home Assistant.","vac.source_banner_disabled":"The saved source is disabled in Home Assistant. Enable it there or choose another source.","vac.source_banner_unverified":"Current Home Assistant permissions cannot verify this saved source. It remains pinned and will not be replaced automatically.","vac.choose_source":"Choose source","vac.source_auto":"Automatic","vac.source_auto_hint":"Use a compatible entity from this device","vac.all_cameras":"All cameras","vac.all_cameras_warn":"A camera may not provide robot data. Choose one only if it is your vacuum map.","vac.all_cameras_empty":"No other camera entities found.","vac.platform_unknown":"unknown integration","vac.cap_position":"position","vac.cap_rooms_short":"rooms","vac.cap_path":"path","vac.cap_map":"map ID","vac.cap_none":"no robot data detected","vac.xcme_hint":"Enable these Xiaomi Cloud Map Extractor attributes:","vac.documentation":"Documentation","vac.residual_title":"Check automatic calibration","vac.residual_message":"The matched rooms disagree by up to {error}. Apply this approximate calibration, refine it manually, or cancel without changing the saved setup.","vac.apply_proposal":"Apply","gs.backup_group":"Backup and transfer","gs.backup_hint":"Download a portable JSON backup or preview and import a backup made by House Plan.","backup.export_open":"Export","backup.import_open":"Import","backup.export_title":"Export House Plan","backup.import_title":"Import House Plan","backup.export_hint":"Choose whether the backup should contain the whole House Plan configuration or only the current space.","backup.full":"Full backup","backup.current_space":"Current space","backup.current_space_title":"Current space: {title}","backup.no_current_space":"No current space","backup.plan_only":"Plan only","backup.plan_only_hint":"Keep rooms, walls, openings, decor and room-label positions without devices or Home Assistant bindings.","backup.plan_only_preview":"This file contains the plan only","backup.privacy_warning":"The archive keeps names, Home Assistant identifiers and exact coordinates. Internal plans and attachments are referenced, not embedded; runtime states and vacuum trails are not included.","backup.download":"Download JSON","backup.export_done":"Backup downloaded","backup.reading":"Checking the backup…","backup.revalidated":"The plan changed after this preview. The summary was refreshed; review it and confirm again.","backup.error.support_invalid_message":"Check the support message and try again.","backup.error.support_package_too_large":"The anonymized support package exceeds the 8 MiB limit.","backup.error.support_preview_expired":"The support attachment preview expired or is no longer available.","backup.error.support_rate_limited":"Too many support reports or previews were requested. Try again later.","backup.error.support_rejected":"The report did not pass support service validation.","backup.error.support_unavailable":"The private support service is temporarily unavailable.","backup.error.unauthorized":"You do not have permission to export or import this plan.","backup.error.not_ready":"House Plan is not ready yet. Try again in a moment.","backup.error.too_large":"The backup exceeds the 8 MiB limit.","backup.error.invalid_json":"The selected file is not valid JSON.","backup.error.invalid_format":"The selected file is not a House Plan backup.","backup.error.invalid_image":"The image is damaged or does not match its format.","backup.error.unsupported_export_version":"This backup format is not supported by the installed version.","backup.error.unsupported_image":"Use a supported PNG, JPEG, WebP or SVG image.","backup.error.future_model":"The backup was created by a newer House Plan data model.","backup.error.invalid_config":"The backup contains an invalid House Plan configuration.","backup.error.wall_model_migration_blocked":"The backup wall model could not be upgraded safely. Optimize the source plan first, then export it again.","backup.error.invalid_layout":"The backup contains invalid object positions.","backup.error.invalid_content":"The backup contains invalid or inconsistent content references.","backup.error.space_not_found":"The selected space no longer exists.","backup.error.capacity_exceeded":"Adding this backup would exceed the plan limits.","backup.error.preview_expired":"The preview expired. Select the backup file again.","backup.error.preview_owner_mismatch":"This preview belongs to another Home Assistant user.","backup.error.conflict":"The plan changed after the preview. Review the refreshed summary.","backup.error.content_confirmation_required":"Confirm that unavailable local content may be detached.","backup.error.commit_failed":"The backup could not be applied safely. The previous plan was restored or is pending recovery.","backup.error.missing_plan":"A referenced plan file disappeared after the preview. Review the backup again.","backup.error.missing_content":"A referenced local attachment disappeared after the preview. Review the backup again.","backup.error.marker_control_missing":"A linked plan light is missing from the backup.","backup.error.marker_control_not_light":"A linked plan target is no longer marked as a light source.","backup.error.marker_control_self":"A light source cannot control itself.","backup.error.marker_control_cycle":"The backup contains a circular chain of light controls.","backup.error.duplicate_marker_control":"The backup contains a duplicate plan-light link.","backup.error.no_backup":"There is no import or optimization snapshot to restore.","backup.error.in_use":"The item is still in use","backup.error.invalid_data":"The request carries invalid data","backup.error.invalid_light_entity":"The leading light must be a light.* or switch.* entity","backup.error.invalid_marker_control":"Invalid marker control reference","backup.error.invalid_name":"The name is invalid","backup.error.invalid_partition_opening_host":"The opening must keep its partition host","backup.error.invalid_partition_opening_jamb_margin":"The opening leaves no physical jamb at the wall end","backup.error.invalid_passage_fields":"An open passage cannot carry door-only settings","backup.error.invalid_space_id":"Unknown space","backup.error.invalid_toggle_entity":"The toggle entity must be light.* or switch.*","backup.error.invalid_value_badge":"Invalid value badge settings","backup.error.invalid_value_badge_attribute":"Invalid value badge attribute","backup.error.invalid_value_badge_position":"Invalid value badge position","backup.error.invalid_value_badge_source":"Invalid value badge source","backup.error.invalid_vacuum_map_route":"Check how the robot's maps are assigned to spaces.","backup.error.invalid_value_source":"Invalid value source","backup.error.invalid_value_source_attribute":"Invalid value source attribute","backup.error.io_error":"A file operation failed on the server","backup.error.not_toggleable":"This device cannot be toggled","backup.error.nothing_to_repair":"Nothing to repair","backup.error.space_in_use":"The space is still referenced","backup.error.value_badge_source_required":"The value badge needs a source","backup.error.wall_model_client_outdated":"The plan was updated elsewhere — reload the page","backup.same_source":"Created on this Home Assistant instance","backup.foreign_source":"Created on another Home Assistant instance","backup.created":"Created: {value}","backup.versions":"Card {card}; integration {integration}; data model {model}","backup.count_spaces":"Spaces: {n}","backup.count_rooms":"Rooms: {n}","backup.count_walls":"Walls: {n}","backup.count_openings":"Openings: {n}","backup.count_decor":"Decor objects: {n}","backup.count_markers":"Devices: {n}","backup.count_layout":"Positions: {n}","backup.bindings":"Bindings — devices: {device}, entities: {entity}, virtual: {virtual}; positions without a space: {legacy}","backup.binding_status":"Target status — active: {active}, disabled: {disabled}, missing: {missing}","backup.missing_areas":"Areas missing on the target: {areas}","backup.dropped_marker_links":"Plan-light links outside this transferred space were omitted: {n}.","backup.room_drafts_migrated":"Legacy unfinished contours converted to ordinary walls: {drafts}; wall segments: {segments}.","backup.repaired_target_refs":"Existing references restored by this space import: {n}.","backup.preserved_unresolved_refs":"References that could not be restored unambiguously were preserved: {n}.","backup.preserved_unresolved_hint":"No data was guessed or deleted. After the import, run Optimize plans to inspect the remaining references.","backup.import_details":"Import reference details","backup.import_detail.incoming_remapped":"References updated inside the imported copy: {n}","backup.import_detail.target_repaired":"Existing references restored: {n}","backup.import_detail.preserved_unresolved":"Unresolved references preserved: {n}","backup.import_detail.collisions":"Destination conflicts preserved safely: {n}","backup.import_detail.dropped_links":"Incoming links omitted by transfer rules: {n}","backup.import_detail.bounded_lineages":"Overly nested identifiers left bounded: {n}","backup.replace_warning":"This replaces the current configuration and layout. Uploaded files are never deleted. One undo remains available until the next plan edit.","backup.foreign_bookkeeping":"Instance-specific known/new-device bookkeeping will not be imported.","backup.final_name":"New space name","backup.target_settings":"The target instance's global settings remain unchanged.","backup.duplicates":"Bindings already present: {n}","backup.skip":"Skip duplicate devices","backup.virtual_copy":"Add safe static virtual copies","backup.content":"Referenced content","backup.decor_images_summary":"Custom images: {objects} objects, {assets} files; missing files: {missing}.","backup.content_available":"available locally","backup.content_external":"external link","backup.content_detach_required":"will be detached","backup.confirm_detach":"I understand that unavailable internal plans and attachments will be detached from the imported configuration.","backup.confirm_missing_images":"I understand that missing custom images will remain as repair placeholders and other unavailable local files will be detached.","backup.replace":"Replace","backup.add":"Add space","backup.space_done":"Space imported: {rooms} rooms, {markers} devices, {refs} existing references restored","backup.full_done":"Backup restored: {spaces} spaces, {rooms} rooms, {markers} devices","backup.undo_import":"Undo last full import","backup.import_undone":"Full import undone","backdrop.large_title":"Large image","backdrop.large_body":"This image is {w}×{h} ({fileMb} MB file) and needs about {decodedMb} MB of memory to display. On tablets this can crash the page.","backdrop.unknown_body":"The image dimensions could not be read — the file may be damaged. Continuing may crash the page on tablets.","backdrop.reduced_dimensions":"Reduced copy: {w}×{h} px.","backdrop.use_downscaled":"Upload a reduced copy","backdrop.reducing":"Reducing…","backdrop.keep_original":"Keep the original","backdrop.too_large_title":"Image is too large","backdrop.too_large_body":"This image exceeds what browsers can display ({w}×{h}, limit {limit} px per side). Please reduce it in a desktop editor and upload again.","backdrop.downscale_failed":"Could not create the reduced copy. The original plan was not changed."};const hp=new WeakSet,dp=new WeakSet;function up(e,t,i){const n=i?t.state(i):"ready";return i&&"pending"===n?(dp.has(e)||(e.inert=!0,e.setAttribute("aria-busy","true"),dp.add(e)),t.ensure(i).then(()=>{e.isConnected&&e.requestUpdate()}),hp.has(e)?"warm":"cold"):(dp.delete(e)&&(e.inert=!1,e.removeAttribute("aria-busy")),i&&(e.setAttribute("lang","fallback"===n?"en":i),hp.add(e)),"ready")}function pp(){return j``}const _p=[{code:"en",nativeLabel:"English",dictionary:cp},{code:"ru",nativeLabel:"Русский",dictionary:{"editor.context_actions":"Действия: {object}","editor.tool_options":"Параметры инструмента: {tool}","editor.palette":"Палитра: {tool}","editor.open_group":"Группа инструментов: {group}","editor.group_active":"{group} — активно: {item}","editor.disabled_action":"{action} недоступно: {reason}","editor.loading":"Загружаем редактор…","editor.loading_aria":"Редактор плана загружается","editor.load_failed":"Не удалось загрузить редактор.","editor.refresh_advice":"Обновите страницу и повторите попытку.","editor.retry_advice":"Проверьте сеть и нажмите ещё раз.","version_mismatch.title":"Версии House Plan не совпадают","version_mismatch.body":"Если Home Assistant ещё перезапускается, дождитесь завершения, затем перезагрузите эту страницу.","version_mismatch.frontend":"Карточка","version_mismatch.backend":"Интеграция","version_mismatch.reload":"Перезагрузить страницу","color_picker.title":"Выбор цвета","color_picker.hue":"Оттенок","color_picker.saturation":"Насыщенность","color_picker.value":"Яркость","color_picker.hex":"Цвет HEX","color_picker.invalid_hex":"Введите цвет HEX из 3 или 6 цифр","color_picker.confirm":"ОК","btn.properties":"Свойства","btn.keep_as_walls":"Оставить стенами","btn.delete_room_keep_walls":"Удалить комнату, оставить стены","btn.delete_room_with_walls":"Удалить комнату и стены","title.markup_select":"Выбор и редактирование стен и колонн","title.markup_column":"Колонна: кликните точку сетки для квадратной колонны","markup.partition":"Перегородка","markup.column":"Колонна","markup.hint_column":"кликните точку сетки, чтобы поставить квадратную колонну","history.wall_segment":"Добавление отрезка стены","history.column_add":"Добавление колонны","history.physical_edit":"Изменение физического объекта","history.physical_delete":"Удаление физического объекта","history.physical_move":"Перемещение физического объекта","history.wall_face_batch":"Создание комнат из стен","toast.column_duplicate":"Колонна с тем же центром и внешним размером уже существует","physical.partition_properties":"Свойства перегородки","physical.column_properties":"Свойства колонны","physical.shape":"Форма","physical.square":"Квадрат","physical.circle":"Круг","physical.diameter":"Диаметр","physical.side":"Сторона","physical.rotation":"Угол поворота","physical.length":"Длина","physical.allowed_range":"Допустимо: {min}–{max} {unit}","physical.column_size_title":"Внешняя сторона квадратной колонны, создаваемой кликом (1–150 см).","card.title":"План дома","count.devices":"{n} устр.","empty.no_spaces":"Пространств пока нет.","nav.spaces":"Пространства House Plan","empty.add_first":"Добавьте первое пространство и загрузите план этажа.","empty.read_only":"Пространства не настроены. Попросите администратора добавить первое.","empty.install":"Установите интеграцию House Plan и добавьте запись в «Устройства и службы».","btn.add_space":"Добавить пространство","btn.cancel":"Отмена","btn.save":"Сохранить","btn.close":"Закрыть","btn.delete":"Удалить","btn.copy":"Копировать","btn.edit":"Редактировать","btn.open_in_ha":"Открыть в HA","btn.reset":"Сброс","btn.attach":"Прикрепить…","btn.upload":"Загрузить…","btn.replace":"Заменить…","title.zoom_in":"Приблизить","title.zoom_out":"Отдалить","title.zoom_fit":"Вписать всё","title.configure_space":"Настроить пространство","title.add_space":"Добавить пространство","title.markup_add":"Стены: рисуйте непрерывную цепочку; каждый принятый отрезок сохраняется отдельно. Shift фиксирует 45°","title.markup_merge":"Объединить: клик по одной комнате, затем по соседней с общей стеной","title.markup_split":"Разделить комнату: клик по комнате, затем две точки на её стенах","title.markup_delroom":"Удалить комнату: кликните внутри комнаты и подтвердите удаление","title.need_plan":"Загрузите подложку (план этажа)","markup.add":"Стены","markup.merge":"Объединить","markup.split":"Разделить","markup.resize":"Размер","title.markup_resize":"Изменение размера комнат: тяните доступную ручку горизонтальной или вертикальной стены","markup.hint_resize":"тяните доступную ручку стены · стена упирается в первую небезопасную позицию · Esc — отмена · Ctrl+Z — отмена шага","resize.disabled.diagonal":"Стена расположена под углом: Resize поддерживает только горизонтальные и вертикальные стены","resize.disabled.side-angle":"Примыкающая стена расположена под углом: для Resize обе примыкающие стены должны образовывать прямой угол","resize.disabled.duplicate-physical-wall":"Стену перекрывает отдельная перегородка или колонна; удалите или переместите её перед изменением размера","resize.disabled.partial-shared":"Соседняя комната использует только часть этой стены, поэтому её нельзя безопасно двигать как одну общую стену","resize.disabled.unequal-shared":"У соседней комнаты другие конечные точки или длина стены, поэтому стены нельзя безопасно двигать вместе","resize.disabled.multiple-rooms":"Перемещение затронуло бы больше двух комнат","resize.disabled.thickness-conflict":"Толщину стены нельзя безопасно сохранить","resize.disabled.opening-conflict":"Проём на этой стене нельзя безопасно переместить","resize.disabled.invalid-geometry":"Эту стену нельзя переместить без изменения структуры плана","resize.limit_stopped":"Стена остановлена: дальше нарушается ограничение стыков","resize.commit_failed":"Изменение размера отменено: итоговый план не прошёл проверку геометрии","resize.preview_failed":"Стена остановлена в последней безопасной позиции: геометрию плана нельзя сохранить без потерь","markup.opening":"Проём","markup.delete_room":"Удалить комнату","history.undo":"Отменить","history.redo":"Повторить","history.undo_named":"Отменить: {name} (Ctrl+Z)","history.redo_named":"Повторить: {name} (Ctrl+Shift+Z / Ctrl+Y)","history.undo_empty":"Нет операций для отмены","history.redo_empty":"Нет операций для повтора","history.undone":"Отменено: {name}","history.redone":"Повторено: {name}","history.add_room":"Создание комнаты","history.split_room":"Разделение комнаты","history.merge_rooms":"Объединение комнат","history.resize_room":"Изменение размера комнаты","history.wall_thickness":"Изменение толщины стены","history.add_opening":"Добавление дверного или оконного проёма","history.edit_opening":"Изменение проёма","history.move_opening":"Перемещение проёма","history.delete_opening":"Удаление проёма","history.delete_room_keep_walls":"Удаление комнаты с сохранением стен","history.delete_room_with_walls":"Удаление комнаты и её стен","history.decor_add":"Добавление объекта декора","history.decor_edit":"Изменение объекта декора","history.decor_move":"Перемещение объекта декора","history.decor_transform":"Трансформация объекта декора","history.decor_delete":"Удаление объекта декора","history.backdrop_transform":"Трансформация подложки плана","history.device_move":"Перемещение: {name}","history.device_stale":"История позиций больше неприменима и была очищена","opening.new":"Новый проём","opening.edit":"Проём","opening.door":"Дверь","opening.window":"Окно","opening.gate":"Ворота","opening.passage":"Открытый проём","opening.passage_binding_warning":"При сохранении датчик открытия и замок будут удалены.","opening.invalid_passage_fields":"У открытого проёма на плане «{room}» есть недопустимые параметры: {fields}.","opening.type_label":"Тип","opening.length_label":"Длина, см","opening.contact_label":"Датчик открытия","opening.lock_label":"Замок","opening.none":"— нет —","opening.search_ph":"Поиск: имя или entity_id…","opening.invert":"Инвертировать открыто/закрыто","opening.flip_h":"Петли с другой стороны","opening.flip_v":"Открывается в другую сторону","opening.open":"Открыто","opening.closed":"Закрыто","opening.locked":"Заперто","opening.unlocked":"Не заперто","opening.state_unknown":"недоступно","opening.no_entities":"Датчики не привязаны — статичный символ на плане.","toast.opening_no_wall":"Кликните рядом со стеной комнаты или независимой стеной","opening.host_partition":"Независимая стена","opening.partition_orphan":"Независимая стена этого проёма больше не существует","opening.partition_jamb_margin":"Оставьте от края проёма до торца стены минимум {distance}","opening.rebind_partition":"Привязать к другой независимой стене","confirm.delete_partition_openings_title":"Удалить стену и проёмы?","confirm.delete_partition_openings_body":"В стене есть проёмы: {count}. Они будут удалены вместе со стеной.","confirm.delete_partition_openings_item":"• {type}, {length}","markup.hint_points":"точек: {n} · Shift — шаг 45° · Esc — завершить цепочку · Ctrl+Z — убрать точку · при замыкании будет предложена комната","markup.hint_start":"кликните точку сетки, чтобы начать цепочку стен","tip.lqi":"средний сигнал zigbee:","tip.area":"площадь: {value}","info.device_header":"Устройство на плане","info.model":"Модель","info.state":"Состояние","info.link":"Ссылка","info.manuals":"Инструкции","info.none":"Нет дополнительной информации","marker.new_device":"Новое устройство","marker.name_label":"Имя (отображается на плане)","marker.name_ph":"Название","marker.binding_label":"Привязка к устройству HA","marker.binding_disabled":"деактивировано в Home Assistant","marker.virtual_option":"Виртуальное устройство (без привязки)","marker.search_ph":"Поиск устройства / группы…","marker.nothing_found":"ничего не найдено","marker.room_label":"Комната","marker.room_override":" (переопределить размещение)","marker.room_choose":"— выберите комнату —","marker.room_auto":"— по зоне устройства (авто) —","marker.icon_label":"Иконка","marker.icon_ph":"mdi:… (пусто = авто)","marker.display_label":"Отображение","display.badge":"Значок + состояние","display.icon_ripple":"Значок + состояние и активность","display.static_icon":"Всегда статичный значок","marker.display_hint_badge":"Значок и динамическая подложка показывают состояние устройства без обычной пульсации активности. Красная тревога сохраняется.","marker.display_hint_icon_ripple":"Значок, динамическая подложка и пульсация: короткая — для событий, постоянная — для работы, движения или присутствия. Красная тревога имеет отдельный приоритет.","marker.display_hint_value":"Значок заменяется выбранным или автоматически найденным значением Home Assistant; подложка продолжает показывать состояние. Красная тревога сохраняется.","marker.display_hint_static_icon":"Подложка в цветах темы и значок всегда остаются одинаковыми. Состояния, активность, недоступность и тревоги не меняют отображение.","marker.static_alarm_warning":"Это устройство может сообщать о тревогах. Статичный режим скрывает визуальную тревогу маркера.","marker.preview.title":"Предпросмотр отображения","marker.preview.actual":"Сейчас","marker.preview.example":"Пример","marker.preview.integration":"Интеграция","marker.preview.source":"Источник отображения","marker.preview.current_state":"Текущее состояние","marker.preview.result":"На плане","marker.preview.details":"Подробнее об источниках","marker.preview.select_source":"Выберите устройство или сущность Home Assistant, чтобы увидеть фактическое отображение.","marker.preview.unknown_provider":"Интеграция неизвестна","marker.preview.virtual_provider":"House Plan · виртуальное устройство","marker.preview.no_source":"Нет активного источника","marker.preview.no_state":"Нет текущего состояния","marker.preview.mixed_states":"Несколько разных состояний","marker.preview.multiple_sources":"Источников: {n}","marker.preview.more_sources":"ещё {n}","marker.preview.scaled":"Предпросмотр уменьшен до {n}%, чтобы поместиться. Сохранённый размер не изменится.","marker.preview.demo_short":"Показать краткую активность","marker.preview.demo_continuous":"Показать постоянную активность","marker.preview.stop_continuous":"Остановить постоянную активность","marker.preview.demo_short_notice":"Пример краткой активности; фактическое состояние устройства не меняется.","marker.preview.demo_continuous_notice":"Пример постоянной активности; фактическое состояние устройства не меняется.","marker.preview.demo_already_visible":"Текущее состояние уже показывает реальную активность или тревогу.","marker.preview.reduced_motion":"В системе включено уменьшение движения, поэтому обычная активность показана точкой.","marker.preview.reason.neutral":"Нейтральная тёмная подложка","marker.preview.reason.working":"Жёлтая подложка: устройство сейчас работает","marker.preview.reason.working_activity":"Жёлтая подложка и эффект активности: устройство сейчас работает","marker.preview.reason.open":"Оранжевая подложка: физически открыто или разблокировано","marker.preview.reason.cover_icon_state":"Нейтральная подложка; состояние и значок определяет сущность шторы или заслонки","marker.preview.reason.presence":"Эффект активности, пока обнаружено присутствие","marker.preview.reason.event":"Короткий эффект активности после события","marker.preview.reason.transition":"Эффект активности во время движения или смены состояния","marker.preview.reason.media_neutral":"Медиаустройство остаётся на нейтральной тёмной подложке, пока доступно","marker.preview.reason.unavailable":"Приглушённая нейтральная подложка: отключено или недоступно","marker.preview.reason.alarm":"Красная тревожная подложка; тревога отображается всегда","marker.preview.reason.live_states_disabled":"Оформление по живым состояниям отключено в настройках карточки","marker.preview.reason.value_no_state":"Нет подходящего значения состояния — вместо него показан значок","marker.preview.reason.value_ambiguous_sources":"Подходит несколько источников значения — вместо него показан значок","marker.preview.reason.value_non_scalar":"Источник вернул не простое значение — вместо него показан значок","marker.preview.reason.value_virtual":"У виртуального устройства нет значения HA — вместо него показан значок","marker.preview.reason.vacuum_live_plan_only":"Живая позиция и след пылесоса доступны только на полном плане","marker.preview.reason.hidden_design_preview":"Устройство скрыто на плане, но его оформление видно в предпросмотре","marker.preview.reason.composite_power_source":"Состояние берётся из сущности питания устройства; вспомогательные переключатели не учитываются","marker.preview.reason.activity_display_disabled":"Выбранный режим отображения не показывает обычные эффекты активности","marker.preview.reason.ha_disabled":"Привязка отключена в Home Assistant, поэтому устройство будет скрыто на плане","marker.preview.reason.orphaned":"Сохранённая привязка Home Assistant больше не найдена","marker.preview.reason.static_icon":"Статичный режим: состояние устройства не меняет значок","marker.activity_color":"Цвет пульсации активности","marker.ripple_size":"Размер пульсации активности","marker.activity_alarm_note":"Цвет и размер относятся только к обычной активности и не влияют на красную тревогу.","marker.pulse_a11y_alarm":"Тревога","marker.pulse_a11y_event":"Недавнее событие","marker.pulse_a11y_presence":"Обнаружено присутствие","marker.pulse_a11y_transition":"Изменение состояния","marker.pulse_a11y_running":"Работает","marker.state_a11y_neutral":"Обычное состояние","marker.state_a11y_working":"Работает","marker.state_a11y_open":"Открыто","marker.state_a11y_locked":"Заблокировано","marker.state_a11y_unlocked":"Разблокировано","marker.state_a11y_alarm":"Тревога","marker.state_a11y_unavailable":"Недоступно","marker.lqi_a11y_low":"LQI {value}, слабый сигнал","marker.lqi_a11y_mid":"LQI {value}, средний сигнал","marker.lqi_a11y_high":"LQI {value}, сильный сигнал","marker.size_label":"Размер / поворот значка","marker.angle_label":"Поворот","marker.model_label":"Модель","marker.model_ph":"напр. Aqara T&H","marker.link_label":"Ссылка","marker.desc_label":"Описание","marker.desc_ph":"Заметки, характеристики…","marker.manuals_label":"Инструкции (PDF и т.п.)","marker.sub_device":"устройство","marker.sub_z2m_group":" · Z2M-группа","marker.sub_group":"группа","marker.sub_helper":"хелпер","space.new":"Новое пространство","space.copy_title":"Копирование пространства","space.copy_name":"Название нового пространства","space.copy_fallback":"Пространство","space.copy_create":"Создать копию","space.copy_optimize_title":"Оптимизировать перед копированием?","space.copy_optimize_body":"Перед созданием «{name}» House Plan должен оптимизировать весь план, включая другие пространства. Продолжить?","space.copy_optimize_confirm":"Оптимизировать и скопировать","space.copy_error_changed":"План изменился, пока было открыто подтверждение. Проверьте его и повторите попытку.","space.copy_error_source_missing":"Исходного пространства больше нет. Снова откройте его настройки и повторите попытку.","space.copy_error_source_invalid":"House Plan не смог проверить все стены этого пространства. Исправьте исходное пространство и повторите попытку.","space.copy_error_spaces_limit":"В House Plan уже создано максимальное число пространств.","space.copy_error_partitions_limit":"В этом пространстве слишком много стен для копирования.","space.copy_error_openings_limit":"В этом пространстве слишком много проёмов для копирования.","space.copy_error_decor_limit":"В этом пространстве слишком много элементов подложки для копирования.","space.copy_error_columns_limit":"В этом пространстве слишком много колонн для копирования.","space.copy_error_opening_host":"Один из проёмов больше не привязан к стене. Исправьте или удалите его перед копированием.","space.copy_error_geometry":"Копия создаст небезопасную геометрию стен. Исправьте исходное пространство и повторите попытку.","space.copy_error_optimize_geometry":"Копирование остановлено: оптимизация всего плана небезопасна для одного из пространств.","space.header":"Пространство","space.title_label":"Название","space.title_ph":"Например: Гараж","space.plan_label":"Подложка (план)","space.no_plan":"нет подложки","space.plan_alt":"план","room.new":"Новая комната","room.name_label":"Отображаемое имя","room.name_ph":"Например: Терраса","room.area_label":"Зона Home Assistant (свободные)","room.no_area_option":"— без зоны —","room.default_name":"Комната","device.unnamed":"без имени","device.light_group":"группа света","device.fallback":"устройство","device.virtual":"виртуальное устройство","confirm.delete_room_title":"Удалить комнату «{name}»?","confirm.delete_room_body":"Выберите, нужно ли оставить физические стены, принадлежащие только этой комнате. Общие с другой комнатой стены сохраняются всегда.","confirm.remove_marker_title":"Удалить устройство с плана?","confirm.remove_marker_body":"Устройство исчезнет полностью и перестанет участвовать в данных плана. Позже его можно будет добавить заново.","confirm.erase_decor":"Стереть объект «{kind}»? Действие можно отменить из истории редактора.","confirm.delete_space_title":"Удалить пространство?","confirm.delete_space_body":"Пространство, все его комнаты и вся разметка плана будут удалены.","confirm.delete_space_vac_routes":"Также будет снято сопоставление карт роботов: {count}.","space.delete_blocked":"Это пространство всё ещё используется устройствами: {n}. Сначала перенесите их в другое пространство или удалите.","toast.pos_save_failed":"Не удалось сохранить позицию: {err}","toast.no_entity":"У устройства нет подходящей сущности","toast.ha_disabled_action":"Деактивированный объект Home Assistant нельзя использовать на плане.","toast.ha_disabled_show_device":"Деактивированное в Home Assistant устройство нельзя показать на плане. Сначала активируйте его в Home Assistant.","toast.ha_disabled_show_entity":"Деактивированную в Home Assistant сущность нельзя показать на плане. Сначала активируйте её в Home Assistant.","toast.ha_disabled_add":"Деактивированный объект Home Assistant нельзя добавить на план. Сначала активируйте его в Home Assistant.","toast.ha_binding_unverified":"Статус объекта не удалось подтвердить по реестру Home Assistant. Отображение и действия временно недоступны.","toast.markup_needs_server":"Разметка доступна после переноса конфига на сервер","toast.space_order_changed":"Порядок изменён. Если где-то этаж карточки задан номером, проверьте такие панели.","toast.conflict":"Конфиг изменён в другом окне — данные обновлены, повторите последнее действие","toast.cfg_save_failed":"Не удалось сохранить конфиг: {err}","toast.room_overlap":"Контур накладывается на комнату «{name}» — комнаты не должны накладываться","toast.contour_cannot_close":"Контур нельзя замкнуть: он вырожден или пересекает сам себя","toast.merge_not_adjacent":"Объединять можно только комнаты с общей стеной","toast.rooms_merged":"Комнаты объединены в «{name}»","toast.split_pick_wall":"Начните разрез на стене комнаты","toast.split_bad_cut":"Разрез — от стены до стены внутри комнаты, без пересечения стен и самого себя","merge.header":"Объединение комнат","merge.hint":"У объединённой комнаты одно имя и одна зона. Вторая зона освобождается — её устройства уйдут с плана, пока их не заберёт другая комната.","merge.keep":"Оставить","merge.no_area":"без зоны","toast.room_saved":"Комната сохранена ({n}). Устройств добавлено: {added}. Обведите следующую или выйдите из разметки.","toast.room_saved_no_area":"Комната сохранена ({n}, без зоны). Обведите следующую или выйдите из разметки.","toast.marker_needs_server":"Редактирование устройств доступно после переноса конфига на сервер","toast.virtual_name_required":"Укажите имя виртуального устройства","toast.marker_saved":"Устройство сохранено","toast.marker_removed":"Устройство удалено с плана","toast.integration_missing":"Интеграция House Plan не установлена — управление недоступно","toast.plan_formats":"Поддерживаются SVG, PNG, JPG, WebP","toast.plan_required":"Загрузите подложку — план этажа обязателен","toast.space_added_onboard":"Пространство добавлено. Обведите комнаты: кликайте по точкам сетки и замкните контур.","toast.space_added":"Пространство добавлено","toast.space_copied":"Пространство «{name}» создано","toast.space_saved":"Пространство сохранено","toast.space_deleted":"Пространство удалено","toast.delete_failed":"Ошибка удаления: {err}","toast.error":"Ошибка: {err}","toast.toggle_target_unavailable":"Цель «{name}» недоступна — действие не выполнено","toast.toggle_targets_unavailable":"Цели недоступны: {names}. Действие не выполнено","toast.file_failed":"Файл «{name}» не загружен: {err}","toast.files_attached":"Прикреплено файлов: {n}","err.unknown":"неизвестная ошибка","err.code":"код {code}","err.too_large":"файл больше {mb} МБ","err.bad_ext":"недопустимый тип (нужен PDF/изображение)","err.unauthorized":"нужны права администратора","editor.title":"Заголовок","editor.default_floor":"Стартовое пространство","editor.default_floor_missing":"Стартовое пространство «{id}» больше не существует. Выберите другое.","editor.floor":"Закреплённое пространство","editor.floor_none":"— не закреплять —","editor.floor_index":"YAML-индекс {index} (сохранён)","fixed_floor.loading":"Загружаем закреплённое пространство…","fixed_floor.invalid_title":"Закреплённое пространство недоступно","fixed_floor.invalid_body":"Проверьте floor в конфигурации карточки. Настроенное значение: {value}","editor.icon_size":"Размер иконок, % ширины плана","editor.show_temperature":"Показывать температуру","editor.live_states":"Живые состояния (вкл/выкл, открыто…)","editor.light_pools":"Световые пулы и тени от стен","editor.show_signal":"Показывать сигнал zigbee (LQI)","editor.language":"Язык интерфейса","editor.lang_auto":"Авто (профиль HA)","title.icon_rules":"Правила иконок: какая MDI-иконка достаётся устройству по имени","rules.title":"Правила иконок","rules.hint":"Правила проверяются сверху вниз по строке «имя устройства + модель» (regex без учёта регистра); срабатывает первое совпадение. Если ничего не подошло — решает device class сущности, затем — иконка-заглушка.","rules.pattern_ph":"regex, напр. розетк|plug","rules.icon_ph":"mdi:power-socket-de","rules.add":"Добавить правило","rules.reset":"Сбросить к умолчаниям","rules.test_ph":"Проверьте имя устройства…","rules.invalid":"некорректный regex","rules.saved":"Правила иконок сохранены","btn.up":"Вверх","btn.down":"Вниз","tap.info":"Карточка устройства","tap.more_info":"Диалог HA (more-info)","tap.toggle":"Переключить состояние","marker.tap_label":"Действие по нажатию для этого устройства","tap.toggle_note":"Под селектором показано, какое состояние изменится. Защищённые устройства не переключаются с плана.","import.title":"Создать пространства из этажей HA","import.hint":"Home Assistant уже знает эти этажи. Отметьте, какие превратить в пространства плана — далее для каждого попросим картинку плана. Комнаты затем обводятся вручную по плану.","import.start":"Создать: {n}","import.manual":"Начать с нуля","import.progress":"Этаж {i} из {n}","import.done":"Пространства созданы. Обведите комнаты: кликайте по точкам сетки и замкните контур.","btn.skip":"Пропустить","space.scale_label":"Масштаб (размер клетки сетки)","space.cell_cm.help":"Связывает сетку с реальными размерами: от значения зависят длины и площади, толщина стен, размеры проёмов и радиус свечения. Изменение после разметки меняет расчётные размеры всего пространства, но не двигает его точки на плане.","space.cell_cm.help.aria":"Подсказка: масштаб пространства","space.scale_unit":"см на клетку","space.scale_unit_imperial":"дюйм на клетку","space.display_section":"Отображение","space.show_borders":"Всегда отображать границы комнат","space.zero_wall_style":"Стены нулевой толщины","space.zero_wall_style.help":"Пунктирные стены нулевой толщины пропускают Glow и солнечные лучи, сплошные блокируют их как барьер нулевой площади. Выбор меняет все такие стены пространства, даже когда их линии скрыты в просмотре.","space.zero_wall_style.help.aria":"Подсказка: вид стен нулевой толщины","space.zero_wall_dashed":"Пунктирные","space.zero_wall_solid":"Сплошные","space.show_names":"Отображать названия комнат (перетаскиваются)","space.room_color":"Цвет границ и названий","space.opacity":"Прозрачность","space.fill_label":"Заливка комнат","space.fill_mode.help":"«Свой цвет» задаёт оформление, а «Свет», «Температура» и «LQI» используют текущие данные Home Assistant; Glow включается отдельно.","space.fill_mode.help.aria":"Подсказка: режим заливки комнат","fill.none":"Нет","fill.lqi":"По силе зигби-сигнала","fill.light":"По освещению","fill.custom":"Свой цвет","space.custom_fill":"Цвет заливки","space.source_file":"У меня есть картинка плана","space.source_draw":"Нет подложки — нарисую комнаты вручную","fill.temp":"По температуре","tip.temp_avg":"средняя температура:","tip.hum_avg":"средняя влажность:","space_card.button":"Перейти к пространству","space_card.not_found":"Пространство «{id}» не найдено","space_card.loading":"Загрузка…","continuity.restore_plan":"Восстанавливаем план…","continuity.restore_connection":"Восстанавливаем подключение к устройствам…","continuity.retry":"Повторить","editor.space":"Пространство","editor.framing":"Кадрирование","editor.fit_content":"Всё видимое содержимое","editor.fit_house":"Плотно по геометрии дома","editor.show_button":"Показывать кнопку","editor.button_label":"Текст кнопки","editor.button_target":"Путь дашборда (куда вести)","marker.sub_entity":"сущность","title.general_settings":"Общие настройки","title.export_pdf":"Сохранить в PDF","pdf.title":"Сохранение в PDF","pdf.dimensions":"Отображать размеры и площади","pdf.decor":"Отображать мебель и другой декор","pdf.room_names":"Отображать названия комнат","pdf.backdrop":"Отображать подложку","pdf.save":"Сохранить","pdf.saving":"Формируем…","pdf.failed":"Не удалось создать PDF.","pdf.too_large":"Размер изображений превышает лимит PDF 25 МБ.","pdf.asset_failed":"Не удалось загрузить подложку или изображение декора.","pdf.scale":"Масштаб 1:{n}","pdf.north":"Север","gs.title":"Общие настройки","gs.light_group":"Заливка: освещение","gs.light_on":"Свет включён","gs.light_off":"Весь свет выключен","gs.temp_group":"Заливка: температура","gs.temp_cold":"Холодно","gs.temp_ok":"Комфорт","gs.temp_hot":"Жарко","gs.lqi_group":"Заливка: зигби-сигнал","gs.lqi_low":"Слабый сигнал","gs.lqi_high":"Сильный сигнал","gs.reset":"Сбросить к умолчаниям","gs.saved":"Общие настройки сохранены","gs.radar_show_live":"Показывать текущее присутствие на плане","gs.radar_show_live_hint":"Скрывает или показывает все живые цели радаров. Это не запускает и не останавливает запись наблюдений.","radar.title":"Присутствие на плане","radar.help":"Свяжите маркер с точными сущностями радара Home Assistant, укажите положение датчика и профиль координат. Живые позиции обрезаются по выбранной комнате.","radar.help.aria":"Подсказка: настройки радара присутствия","radar.enabled":"Использовать этот радар присутствия","radar.show_live":"Показывать живые цели","radar.configure":"Настроить радар","radar.configure_on_plan":"Настроить на плане","radar.change_installation":"Сменить установку","radar.no_contour":"У комнаты нет контура. Точки радара не будут обрезаться по комнате.","radar.discard_setup_title":"Отменить настройку радара?","radar.discard_setup":"Несохранённая настройка радара будет потеряна.","radar.step_place_mount":"Укажите физическое положение датчика","radar.step_place_heading":"Укажите точку прямо перед датчиком","radar.step_reference":"Укажите контрольное положение {n}, затем начните измерение","radar.step_check_reference":"Укажите независимое проверочное положение","radar.start_measure":"Начать измерение","radar.countdown":"Встаньте в отмеченное место через {seconds} с","radar.capturing":"Стойте неподвижно и в одиночестве…","radar.fit_ready":"Калибровка готова","radar.check_third":"Проверить в другом положении","radar.check_complete":"Независимая проверка завершена","radar.error_distance":"Расхождение положения: {distance}","radar.ambiguous_target":"Обнаружено несколько целей. Повторите измерение в одиночестве.","radar.insufficient_samples":"Недостаточно актуальных координат. Повторите или настройте вручную.","radar.bad_references":"Выберите разнесённые положения в разных направлениях от датчика.","radar.ambiguous_sources":"Измерения допускают два одинаково вероятных направления. Выберите точки, по которым можно различить левую и правую стороны.","radar.bad_fit":"Измерения не совпадают. Проверьте единицы, положение датчика и контрольные точки.","radar.desktop_hint":"Для точной настройки используйте компьютер. Редактирование на тач-устройствах поддерживается по остаточному принципу.","radar.detected":"House Plan распознал признаки радара у этого устройства. Перед сохранением проверьте точные источники.","radar.detected_ld2450":"House Plan нашёл набор координат ESPHome LD2450. Перед сохранением проверьте точные источники X/Y.","radar.additional_actions":"Дополнительные действия","radar.declare":"Это радар присутствия","radar.profile":"Профиль данных","radar.profile_esphome_ld2450_v1":"ESPHome LD2450 (цели X/Y)","radar.profile_cartesian_v1":"Декартовы цели (X/Y)","radar.profile_polar_v1":"Полярная цель (дальность/угол)","radar.profile_range_v1":"Только дальность","radar.profile_zones_v1":"Состояния зон","radar.profile_presence_v1":"Только присутствие","radar.room":"Комната радара","radar.room_choose":"Выберите комнату","radar.target":"Цель {n}","radar.axis_x":"Сущность координаты X","radar.axis_y":"Сущность координаты Y","radar.add_target":"Добавить слот цели","radar.range_channel":"Канал дальности {n}","radar.add_range":"Добавить канал дальности","radar.presence_gate":"Сущность присутствия для слота","radar.swap_axes":"Поменять оси X и Y местами","radar.axis_x_sign":"Направление X","radar.axis_y_sign":"Направление Y","radar.distance_source":"Сущность дальности","radar.angle_source":"Сущность угла","radar.angle_unit":"Единица угла","radar.degrees":"Градусы","radar.radians":"Радианы","radar.angle_zero":"Направление нулевого угла","radar.angle_forward":"Вперёд","radar.angle_right":"Вправо","radar.angle_clockwise":"Угол растёт по часовой стрелке","radar.zone_source":"Сущность зоны","radar.occupancy_source":"Сущность присутствия","radar.count_source":"Сущность количества целей","radar.availability_source":"Сущность доступности","radar.source_choose":"Выберите сущность","radar.source_optional":"Необязательно","radar.source_missing":"сейчас недоступна","radar.saved_unsupported":"Сохранённая настройка радара не поддерживается или неполна. Она неактивна; удалите её либо обновите House Plan перед повторной настройкой.","radar.occupancy":"Присутствие (вкл/выкл)","radar.count":"Количество","radar.mount":"Положение и направление","radar.mount_hint":"Это физическое положение датчика. Перемещение его декоративного маркера не меняет установку.","radar.heading":"Направление, °","radar.range_cm":"Дальность, см","radar.fov_deg":"Угол обзора, °","radar.unit":"Единица источника","radar.mirror":"Отразить ось влево/вправо","radar.remove":"Удалить настройки радара","radar.invalid":"Перед сохранением заполните комнату, источники и положение радара.","radar.check_sources":"Проверить живые данные","radar.checking":"Проверяем…","radar.health":"Состояние подключения","radar.live_summary":"Текущих целей: {targets}; дуг дальности: {ranges}","radar.health_ok":"Актуальные данные получены","radar.health_off":"Цели не обнаружены","radar.health_stale":"Часть координат устарела","radar.health_partial":"Часть источников актуальна, часть устарела","radar.health_restricted":"Нет доступа к одному или нескольким источникам","radar.health_incomplete":"Текущий отчёт радара неполон","radar.health_position_unavailable":"Есть присутствие, но актуальное положение недоступно","radar.health_unavailable":"Данные датчика недоступны","radar.health_needs_setup":"Требуется настроить установку","radar.health_inconsistent":"Источники передают противоречивые данные","radar.health_unknown":"Текущее состояние неизвестно","radar.health_disabled":"Радар отключён","radar.error_invalid_radar":"Проверьте настройки радара.","radar.error_invalid_selection":"Выберите существующую комнату и допустимые источники.","radar.error_source_restricted":"Нет доступа ко всем выбранным источникам.","radar.error_rate_limited":"Слишком много запросов. Повторите чуть позже.","radar.error_not_ready":"Обработка данных радара ещё не готова.","radar.error_conflict":"План изменился. Откройте настройку радара заново и повторите попытку.","radar.error_source_unavailable":"Один или несколько выбранных источников радара недоступны.","radar.error_unsupported_capability":"Установленная интеграция не поддерживает эту возможность радара.","radar.report_age":"{seconds} с назад","space.show_lqi":"Показывать зигби-сигнал (LQI) у устройств","space.hide_decor":"Скрыть декоративный слой","space.hide_decor_tip":"Линии, фигуры, надписи и мебель остаются на месте — их видно в редакторе подложки, но не на плане.","space.hide_openings":"Скрыть проёмы","space.hide_openings_tip":"Двери, окна и ворота не рисуются, но продолжают работать: свет проходит, солнце светит в окна, датчики открытия срабатывают. В редакторе плана проёмы видно всегда.","gs.light_none":"Нет источников света","mode.plan":"Редактор плана","mode.devices":"Редактор устройств","display.value":"Значение + состояние","marker.subarea":"без зоны, вручную","device.new":"Новое устройство — откройте его редактор, чтобы снять отметку","opening.unlock_action":"Открыть замок","opening.lock_action":"Закрыть замок","opening.lock_pending":"Выполняется…","title.close_editor":"Закрыть редактор (вернуться к просмотру)","title.add_device":"Добавить устройство на план","devbar.add":"Добавить","devbar.rules":"Правила иконок","device_inbox.button":"Устройства","device_inbox.title":"Устройства на плане","device_inbox.search":"Поиск по устройствам, сущностям и интеграциям…","device_inbox.add_virtual":"Добавить виртуальное устройство","device_inbox.tab_on_plan":"На плане","device_inbox.tab_available":"Доступны","device_inbox.tab_hidden":"Скрытые","device_inbox.tab_readd":"Доступны снова","device_inbox.only_new":"Только новые","device_inbox.show_entities":"Показывать сущности","device_inbox.show_hidden":"Показывать скрытые на плане","device_inbox.show_hidden.help":"Временно показывает на плане скрытые и деактивированные маркеры служебными призраками только в редакторе устройств. Сохранённая видимость устройств не меняется.","device_inbox.show_hidden.help.aria":"Подсказка: показывать скрытые устройства на плане","device_inbox.new":"Новое","device_inbox.find":"Найти на плане","device_inbox.edit":"Настроить","device_inbox.hide":"Скрыть","device_inbox.show":"Показать","device_inbox.add":"Добавить","device_inbox.readd":"Добавить заново","device_inbox.hide_available":"Скрыть из списка","device_inbox.show_more":"Показать ещё","device_inbox.more_actions":"Другие действия","device_inbox.find_hidden_hint":"Сначала включите «Показывать скрытые на плане»","device_inbox.show_disabled":"Перед показом активируйте эту привязку в Home Assistant","device_inbox.empty_on_plan":"На плане пока нет подходящих устройств.","device_inbox.empty_available":"Нет доступных устройств для добавления.","device_inbox.empty_hidden":"Скрытых устройств нет.","device_inbox.empty_readd":"Нет удалённых устройств, доступных для повторного добавления.","device_inbox.reason_visible_auto":"Найдено автоматически","device_inbox.reason_visible_explicit":"Добавлено явно","device_inbox.reason_manual_hidden":"Скрыто пользователем","device_inbox.reason_automatic_hidden":"Скрыто автоматически","device_inbox.reason_service_entry":"Служебная запись реестра","device_inbox.reason_excluded_integration":"Исключена интеграция «{integration}»","device_inbox.reason_excluded_domain":"Непространственный тип сущности","device_inbox.reason_grouped_light":"Представлено группой света комнаты","device_inbox.reason_represented_by_parent":"Представлено родительским устройством","device_inbox.reason_removed":"Ранее удалено с плана","device_inbox.reason_available":"Можно добавить на план","device_inbox.reason_no_bound_room":"Зона HA не связана с комнатой плана","device_inbox.status_ha_disabled":"Отключено в Home Assistant","device_inbox.status_orphaned":"Привязка больше не найдена в Home Assistant","device_inbox.status_unverified":"Реестр Home Assistant временно недоступен","device_inbox.saved":"Список устройств обновлён","device_inbox.filters_excluded":"Исключённые интеграции","device_inbox.filters_group_lights":"Объединять светильники комнаты в один маркер","device_inbox.filters_preview_appear":"появится: {count}","device_inbox.filters_preview_hide":"скроется: {count}","device_inbox.filters_preview_lights":"затронет светильников: {count}","device_inbox.filters_reset":"Вернуть рекомендуемые","device_inbox.filters_save":"Сохранить фильтры","device_inbox.filters_search_ph":"Добавить интеграцию…","device_inbox.filters_title":"Фильтры обнаружения","space.roomcard_section":"В карточке комнаты:","space.label_temp":"Температура","space.label_hum":"Влажность","space.label_lqi":"Средний Zigbee-сигнал","space.label_light":"Свет вкл/выкл","roomcard.light_on":"Вкл","roomcard.light_off":"Выкл","roomcard.light_partial":"{on} из {total}","toast.split_pick_inside":"Промежуточные точки разреза — внутри комнаты","mode.decor":"Редактор подложки","decor.select":"Выбрать","decor.line":"Линия","decor.rect":"Прямоугольник","decor.ellipse":"Овал","decor.text":"Надпись","decor.erase":"Стереть","decor.erase_confirm_title":"Стереть объект?","decor.color":"Цвет","decor.width":"Толщина линии","decor.line_style":"Стиль линии","decor.line_style_solid":"Сплошная","decor.line_style_dashed":"Пунктирная","decor.fill":"Заливка","decor.fill_color":"Цвет заливки","decor.length":"Длина","decor.size":"Размер","decor.flip_h":"Отзеркалить по горизонтали","decor.flip_v":"Отзеркалить по вертикали","decor.angle":"Угол поворота, °","decor.text_size":"Размер текста","decor.backdrop_properties":"Свойства картинки-подложки","decor.text_title":"Надпись","decor.object_title":"Редактирование: {kind}","decor.text_label":"Текст","decor.live_group":"Вставить переменную HA","decor.live_entity":"Сущность","decor.live_entity_ph":"выберите сущность","decor.live_attr":"Значение","decor.live_attr_ph":"выберите состояние или атрибут","decor.live_state":"Состояние","decor.backdrop":"Картинка-подложка","decor.backdrop_hint":"Тяните картинку — перемещение; угол — размер; верхнюю ручку — поворот. Shift меняет пропорции или снимает шаг угла.","decor.backdrop_reset":"Вернуть картинку","decor.backdrop_reset_done":"Картинка вернулась на своё место и в свой размер","marker.icon_auto":"Авто: {icon} (по правилам иконок; выберите свою, чтобы заменить)","marker.icon_pin_auto":"Закрепить","mode.plan_tip":"Редактор плана — геометрия дома: рисование и объединение/разделение комнат, привязка к зонам HA, двери, окна и ворота, карточки комнат, масштаб","mode.devices_tip":"Редактор устройств — всё про значки: перетаскивание, клик — настройка привязки/иконки/отображения, виртуальные устройства, правила иконок","mode.decor_tip":"Редактор подложки — чисто визуальный декор под планом: линии, прямоугольники, овалы и надписи, не реагирующие на клики","space.glow_enabled":"Свечение источников света","gs.glow_group":"Свечение источников света","gs.glow_base":"Темнота дома","gs.glow_light":"Цвет света по умолчанию / интенсивность","gs.wall_group":"Стены","gs.wall_fill":"Цвет заливки стен","gs.glow_radius":"Радиус свечения","gs.glow_radius.help":"Задаёт общий радиус светового пятна в метрах или футах; персональный радиус устройства заменяет это значение.","gs.glow_radius.help.aria":"Подсказка: общий радиус свечения","gs.unit_m":"м","gs.unit_ft":"фут","marker.controls_label":"Управляет другими источниками света","marker.controls.help":"При действии «Переключить состояние» перечисленные источники переключаются вместе с этим маркером. Их световые пятна остаются у собственных маркеров, а эта связь сама по себе не делает управляющий маркер источником света.","marker.controls.help.aria":"Подсказка: управление другими источниками света","marker.controls_filter":"Поиск ламп и выключателей…","info.controls":"Управляет","marker.glow_radius_label":"Радиус свечения","marker.glow_radius.help":"Задаёт радиус свечения в метрах или футах; пустое значение использует радиус из общих настроек.","marker.glow_radius.help.aria":"Подсказка: радиус свечения","markup.wallthick":"Толщина","markup.select":"Выбрать","title.markup_wallthick":"Толщина — клик по стене задаёт толщину от 0 до 100 см.","markup.hint_wallthick":"клик по стене · Esc закрывает без применения","wallthick.field":"Толщина","wallthick.unit_cm":"см","wallthick.unit_in":"дюйм","wallthick.apply_room":"Применить ко всем стенам комнаты","markup.draw_wall_title":"Толщина каждого нового сегмента стены (0–100 см). Общие стены сохраняют существующее значение.","room.queue_progress":"Комната {current} из {total}","toast.wall_rooms_saved":"Создано комнат: {n}","toast.wall_chain_saved":"Цепочка стен сохранена","toast.wallthick_pick":"Кликните по стене","toast.wallthick_set":"Толщина стены задана","toast.wallthick_cleared":"Толщина стены убрана","toast.physical_range":"Введите значение от {min} до {max} {unit}","toast.zero_wall_opening_conflict":"Сначала удалите проём на этом участке стены.","toast.zero_wall_ambiguous":"Не удалось однозначно выбрать участок стены. Уточните геометрию узла.","toast.zero_wall_migration_blocked":"Пространство не преобразовано: {reason}. Данные не изменены.","toast.physical_angle":"Введите угол поворота от 0° до 90°, не включая 90°","toast.physical_limit":"В пространстве достигнут лимит объектов этого типа","toast.geometry_unsafe":"Изменение отменено: геометрию стен нельзя безопасно построить.","junction.limit_angle":"Слишком острый угол между стенами: {actual}°, минимум {limit}°.","junction.limit_valence":"Слишком много стен в одном узле: {actual}, максимум {limit}.","junction.limit_length":"Слишком короткий участок стены: {actual} см, минимум {limit} см.","junction.limit_distance":"Стены и узлы слишком близко: {actual} см, минимум {limit} см.","junction.limit_clearance":"Внутри комнаты не остаётся места: {actual} см², минимум {limit} см².","junction.limit_check_failed":"Проверку стыков выполнить не удалось — изменение не сохранено","toast.wall_model_migration_blocked":"Не удалось обновить модель стен: {reason}. План не изменён. Запустите «Оптимизировать планы»; если ошибка повторится, исправьте конфликтующую геометрию стен.","toast.wall_model_client_outdated":"Обновите карточку и перезагрузите страницу перед редактированием плана.","wall_model.reason.invalid-room":"некорректный контур комнаты","wall_model.reason.zero-length":"отрезок стены нулевой длины","wall_model.reason.third-owner":"стена принадлежит более чем двум комнатам","wall_model.reason.duplicate-id":"конфликт идентификаторов стен","wall_model.reason.thickness-conflict":"конфликт значений толщины стены","wall_model.reason.opening-host":"проём нельзя однозначно привязать к стене","toast.delete_room_pick":"Кликните внутри комнаты, которую нужно удалить","toast.plan_snap_ambiguous":"Увеличьте масштаб, чтобы выбрать узел стены","toast.wall_repair_ambiguous":"У контура несколько возможных соединений. Увеличьте масштаб и соедините стены явно.","toast.wall_repair_too_large":"Разрыв больше 2 см. Соедините стены перед созданием комнаты.","toast.wall_repair_changed":"Геометрия стен изменилась. Попробуйте создать комнату ещё раз.","toast.opening_on_zero_wall":"Проёмы на стене нулевой толщины запрещены","marker.from_ha_option":"Выбрать из списка HA","marker.show_entities":"Показывать сущности","marker.show_entities_tip":"Добавляет в список не только устройства, но и все их сущности","marker.pick_ph":"Выберите устройство…","room.open_area":"Открыть зону в HA","room.fit_action":"Вписать комнату {name}","view.volumetric":"Объёмный вид","view.flat":"Плоский вид","kiosk.title":"Размеры на этом экране","kiosk.hint":"Хранится только на этом устройстве — у каждого настенного планшета или ТВ свои удобные размеры.","kiosk.icon_scale":"Размер значков устройств","kiosk.font_scale":"Размер текста карточек комнат","editor.kiosk":"Режим настенного устройства (киоск)","editor.cycle":"Автосмена пространств каждые N секунд (киоск, 0 = выкл)","room.settings_title":"Настройки комнаты","room.settings_section":"Настройки комнаты (переопределяют пространство)","room.fill_label":"Заливка в ЭТОЙ комнате","fill.inherit":"Как у пространства","room.custom_fill_space":"Цвет пространства","room.custom_fill_own":"Цвет комнаты","room.temp_range_label":"Диапазон комфорта","room.temp_range_min":"Нижняя граница комфортной температуры","room.temp_range_max":"Верхняя граница комфортной температуры","room.temp_range_reset":"Как у пространства","room.temp_range.help":"Диапазон применяется только к этой комнате. Пустое поле наследует соответствующую границу пространства; если границы поменялись местами, House Plan использует меньшую как нижнюю, а большую как верхнюю.","room.temp_range.help.aria":"О диапазоне комфорта комнаты","room.temp_src_label":"Источник температуры","room.hum_src_label":"Источник влажности","room.src_average":"Средняя по датчикам комнаты (по умолчанию)","room.src_pick":"Конкретное устройство или сущность HA","room.src_ph":"Выберите источник…","toast.room_updated":"Комната обновлена","space.card_font":"Размер шрифта карточек комнат (всё пространство)","room.sizes_section":"Размеры шрифтов","room.name_scale":"Размер названия","room.label_scale":"Размер подписей","preview.room_name":"Гостиная","toast.cfg_reload_failed":"Не удалось перечитать план с сервера: {err}","toast.locale_load_failed":"Не удалось загрузить языковой пакет. До перезагрузки страницы используется английский.","toast.furniture_art_load_failed":"Не удалось загрузить изображения мебели. Обновите страницу, чтобы их показать.","room.settings_short":"Настройки комнаты","room.unnamed":"Комната без имени","marker.use_climate_temp":"Учитывать температуру устройства в комнате","marker.use_climate_temp_tip":"Добавляет current_temperature кондиционера или термостата в среднюю температуру комнаты. Внешний бейдж со значением настраивается отдельно ниже.","marker.value_badge_title":"Бейдж со значением","marker.value_badge.help":"Показывает одно выбранное значение рядом со значком. Не влияет на комнатные показатели, свет, Glow и действие по нажатию.","marker.value_badge.help.aria":"Подсказка: бейдж со значением устройства","marker.value_badge_enabled":"Отображать бейдж со значением","marker.value_badge_source":"Значение","marker.value_badge_source.help":"Выберите конкретное состояние, поддерживаемый атрибут или производное значение этого устройства.","marker.value_badge_source.help.aria":"Подсказка: источник значения бейджа","marker.value_badge_position":"Расположение","marker.value_badge_position.help":"Выбранная сторона сохраняется постоянно и не переворачивается автоматически у края плана.","marker.value_badge_position.help.aria":"Подсказка: расположение бейджа","marker.value_badge_right":"Справа","marker.value_badge_bottom":"Снизу","marker.value_badge_left":"Слева","marker.value_badge_top":"Сверху","marker.value_badge_empty":"У этого устройства нет доступных значений","marker.value_badge_static":"Статичный значок не показывает живые значения. Настройка сохранится.","marker.value_badge_missing":"Источник недоступен","marker.value_badge_missing_hint":"Сохранённый источник сейчас недоступен. Можно сохранить его, отключить бейдж или выбрать другой.","marker.value_badge_duplicate":"То же значение уже показано внутри значка.","marker.value_badge_state":"Состояние · {name}","marker.value_badge_marker_state":"Состояние источника света · {name}","marker.value_badge_lqi":"Качество Zigbee-сигнала (среднее)","marker.value_badge_attr_current_temperature":"Текущая температура · {name}","marker.value_badge_attr_temperature":"Целевая температура · {name}","marker.value_badge_attr_current_humidity":"Текущая влажность · {name}","marker.value_badge_attr_humidity":"Влажность · {name}","marker.value_badge_attr_current_position":"Положение · {name}","marker.value_badge_attr_percentage":"Скорость · {name}","marker.value_badge_attr_brightness":"Яркость · {name}","marker.value_badge_attr_volume_level":"Громкость · {name}","marker.value_badge_attr_battery_level":"Заряд батареи · {name}","marker.value_badge_attr_fan_speed":"Скорость вентилятора · {name}","marker.value_source":"Источник значения","marker.value_source.help":"Выберите, что заменит значок. Действие по нажатию не изменится.","marker.value_source.help.aria":"Подсказка: источник значения внутри значка","marker.value_source_auto":"Автоматически (как раньше)","marker.value_source_missing_hint":"Сохранённый источник сейчас недоступен. До его восстановления или выбора другого значения внутри будет показано —.","marker.light_role_label":"Является источником света","marker.light_role.help":"«Авто» использует фактическую роль привязанного устройства, «Всегда» принудительно создаёт собственный источник, а «Никогда» исключает его; связанные лампы выше остаются независимыми.","marker.light_role.help.aria":"Подсказка: является ли устройство источником света","marker.light_role_auto_yes":"Автоматически (источник света)","marker.light_role_auto_no":"Автоматически (не источник света)","marker.light_role_always":"Всегда источник света","marker.light_role_never":"Никогда не источник света","marker.light_entity_label":"Ведущая сущность света","marker.light_entity.help":"Для составного устройства выберите сущность, состояние, цвет и яркость которой представляют этот источник на плане. Автоматический вариант сохраняет совместимость со старыми планами.","marker.light_entity.help.aria":"Подсказка: ведущая сущность света","marker.light_entity_auto":"Автоматически ({entity})","marker.light_entity_none":"нет управляемой сущности","marker.light_entity_missing":"Сохранённая сущность {entity} недоступна. Временно используется {fallback}; выбор восстановится, если сущность вернётся.","marker.toggle_entity_label":"Переключаемая сущность","marker.toggle_entity.help":"Для составного устройства выберите собственную лампу или переключатель, которой управляет нажатие. Автоматический вариант сохраняет прежние правила цели и не зависит от ведущей сущности света.","marker.toggle_entity.help.aria":"Подсказка: переключаемая сущность","marker.toggle_entity_auto":"Автоматически ({entity})","marker.toggle_entity_none":"нет собственной управляемой сущности","marker.toggle_entity_missing":"Сохранённой сущности {entity} больше нет среди выбираемых каналов этого маркера. Временно используется {fallback}; выбор восстановится, если сущность вернётся.","marker.glow_color_label":"Цвет и яркость свечения","marker.glow_mode.help":"Используйте данные источника, задайте только цвет или зафиксируйте цвет и яркость. Минимум — 1%; чтобы отключить источник, выберите «Никогда».","marker.glow_mode.help.aria":"Подсказка: цвет и яркость свечения","marker.glow_mode_auto":"Из источника","marker.glow_mode_color":"Задать цвет","marker.glow_mode_fixed":"Задать цвет и яркость","marker.glow_color":"Цвет свечения","marker.glow_brightness":"Яркость","marker.glow_disabled_never":"Настройки свечения недоступны: маркер явно исключён из источников света.","marker.glow_disabled_auto":"В автоматическом режиме у этого маркера не найден пространственный источник света.","marker.glow_disabled_no_entity":"Для пространственного источника нет активной управляемой сущности Home Assistant.","marker.glow_passive_hint":"У источника нет собственных данных Home Assistant. Задайте цвет и яркость вручную; радиус остаётся доступным.","marker.control_broken":"Сохранённый источник отсутствует или больше не отмечен как источник света","marker.control_missing_label":"Отсутствующий источник на плане","marker.control_passive":"пассивный источник","toast.marker_control_cycle":"Такая связь создаст циклическую цепочку управления светом.","toast.marker_binding_required":"Сначала выберите устройство Home Assistant, затем добавьте управляемый источник света.","confirm.unlock_title":"Открыть замок?","confirm.unlock_body":"House Plan отправит этому замку команду открытия.","toast.files_migrate_failed":"Не удалось перенести вложения к новой привязке, ссылки остались на старые файлы: {err}","space.pick_saved":"Уже загруженные","space.pick_saved_hint":"Планы, сохранённые на сервере, включая отцеплённые ранее","space.no_saved":"На сервере пока нет сохранённых планов.","space.loading":"Загрузка…","space.used_by":"используется: {list}","space.in_use":"План используется пространством — сначала отцепите его","btn.use":"Выбрать","confirm.delete_plan_title":"Удалить файл плана?","confirm.delete_plan_body":"Файл будет удалён с сервера. Это действие нельзя отменить.","toast.plans_list_failed":"Не удалось получить список планов: {err}","toast.plan_delete_failed":"Не удалось удалить план: {err}","marker.hide":"Скрыть","marker.hide_tip":"Устройство исчезнет с плана после сохранения, но продолжит участвовать в расчёте сигнала комнаты. Вернуть его можно через каталог «Устройства» в редакторе устройств.","marker.show":"Показать","marker.show_tip":"Устройство снова появится на плане после сохранения.","marker.hidden_ghost":"Устройство скрыто пользователем","marker.ha_disabled_device":"Устройство деактивировано в Home Assistant и скрыто с плана.","marker.ha_disabled_entity":"Сущность деактивирована в Home Assistant и скрыта с плана.","marker.ha_disabled_all_entities":"У устройства нет активных сущностей Home Assistant, поэтому оно скрыто с плана.","marker.ha_registry_limited":"Полный реестр Home Assistant недоступен этому пользователю. Неподтверждённый объект временно нельзя показывать или использовать.","marker.delete_tip":"Полностью удалить устройство с плана и из всех расчётов. Позже его можно добавить заново.","tap.run":"Запустить автоматизацию/скрипт/сцену","tap.none":"Ничего не делать","marker.run_target_label":"Что запускать","marker.run_search_ph":"Поиск: автоматизация, скрипт или сцена…","marker.run_target_gone":"Цель {id} не найдена — выберите заново","marker.tap_confirm":"Спрашивать подтверждение","marker.tap_confirm_tip":"Перед выполнением показать диалог подтверждения — защита от случайных нажатий.","marker.toggle_hint_single":"Цель: {name} ({id}).","marker.virtual_light_target":"Виртуальный свет: {name}.","marker.virtual_light_current":"Ручное состояние: {state} → {effect}.","marker.virtual_light_state_on":"включён","marker.virtual_light_state_off":"выключен","marker.toggle_hint_group":"Переключатся источники ({count}): {names}.","marker.toggle_hint_current":"Сейчас: {state} → {effect}.","marker.toggle_hint_group_current":"Сейчас включено {on} из {count} → {effect}.","marker.toggle_hint_skipped":"Не будут затронуты ({count}): {targets}.","marker.toggle_effect_turn_on":"включится","marker.toggle_effect_turn_off":"выключится","marker.toggle_effect_open":"откроется","marker.toggle_effect_close":"закроется","marker.toggle_effect_stop":"остановится","marker.toggle_effect_toggle":"состояние переключится","marker.toggle_skip_missing":"не найдено","marker.toggle_skip_ha_disabled":"деактивировано в HA","marker.toggle_skip_unavailable":"недоступно","marker.toggle_skip_unsupported":"переключение не поддерживается","marker.toggle_skip_secure":"заблокировано из соображений безопасности","marker.toggle_none_no_binding":"У устройства нет привязки, состояние переключать нечем. По нажатию ничего не произойдёт.","marker.toggle_none_no_actionable_entity":"У устройства нет состояния, которое можно переключить. По нажатию ничего не произойдёт.","marker.toggle_none_configured_targets_missing":"Настроенные цели сейчас недоступны. Собственная сущность устройства не будет подставлена вместо них.","marker.toggle_none_ha_disabled":"Цель деактивирована в Home Assistant и не может использоваться на плане.","marker.toggle_none_unavailable":"Цель сейчас недоступна. По нажатию ничего не произойдёт.","marker.toggle_none_unsupported":"Для этой сущности Home Assistant не предоставляет безопасного переключения. По нажатию ничего не произойдёт.","marker.toggle_none_secure":"Переключение замков, сигнализации и защитных ворот с плана заблокировано из соображений безопасности.","run.automation":"автоматизация","run.script":"скрипт","run.scene":"сцена","confirm.tap_run":"Запустить «{name}»?","confirm.tap_toggle":"Переключить «{name}»?","confirm.current_state":"Текущее состояние: {state}","confirm.expected_state":"После переключения: {state}","confirm.group_current":"включено {on} из {total}","confirm.group_all_on":"все включены","confirm.group_all_off":"все выключены","confirm.unavailable_targets":"Недоступно: {count}","confirm.expected_by_ha":"Состояние определит Home Assistant","confirm.state_on":"Включено","confirm.state_off":"Выключено","confirm.state_open":"Открыто","confirm.state_closed":"Закрыто","confirm.state_opening":"Открывается","confirm.state_closing":"Закрывается","confirm.state_stopped":"Остановлено","confirm.state_unknown":"Неизвестно","toast.run_started":"Запущено: {name}","toast.run_target_missing":"Цель запуска не найдена — проверьте настройки устройства","toast.run_target_required":"Выберите автоматизацию, скрипт или сцену","toast.tap_target_changed":"Цель действия изменилась. Повторите попытку.","toast.virtual_light_toggle_failed":"Не удалось переключить виртуальный свет: {err}","toast.value_badge_source_required":"Выберите значение для бейджа","btn.run":"Выполнить","vac.section":"Робот-пылесос: живая позиция","vac.autocal":"Настроить автоматически","vac.live":"Живая позиция на плане","vac.trail":"Показывать путь робота","vac.autocal_no_rooms":"Интеграция не отдаёт список комнат — откройте «Подогнать вручную»","vac.route_warn_unmapped":"Робот убирает на карте, которая не сопоставлена ни одному этажу","vac.route_warn_needs_calibration":"Карта сопоставлена этажу, но не откалибрована","vac.route_warn_ambiguous":"Две карты неразличимы — этаж не выбран","vac.route_warn_missing_space":"Пространство этой карты удалено","vac.autocal_no_match":"Не совпали имена комнат (нужно ≥3 общих) — откройте «Подогнать вручную»","vac.autocal_done":"Готово: привязка по {rooms} комнатам. Запустите уборку и проверьте","vac.cal_need_pos":"Робот сейчас не отдаёт координаты — запустите уборку и поставьте на паузу","vac.cal_done":"Калибровка сохранена. Запустите уборку и проверьте","vac.cal_cancelled":"Калибровка отменена","vac.fit":"Подогнать вручную","vac.fit_hint":"Перетащите карту робота на место, растяните за уголки","vac.fit_rotate":"Повернуть 90°","vac.fit_mirror":"Отразить","vac.trail_never":"Не показывать никогда","vac.trail_cleaning":"Во время уборки","vac.trail_always":"Показывать всегда","gs.bg_group":"Фон сцены","gs.bg_color":"Цвет фона вокруг плана","gs.bg_default":"Как в теме","gs.bg_theme":"по умолчанию — из темы","gs.bg_mode":"Фон плана","gs.bg_mode.help":"«Следует за Солнцем» использует sun.sun, а при недоступности — локальные часы браузера; статичный режим всегда показывает выбранный цвет.","gs.bg_mode.help.aria":"Подсказка: общий фон плана","gs.bg_static":"Статичный цвет","gs.bg_daynight":"Следует за Солнцем","gs.sun_group":"Солнце","gs.sun_missing":"Сущность sun.sun не найдена — фон следует локальным часам, а оконные лучи недоступны.","gs.north":"Север на плане","gs.north.help":"Угол отсчитывается по часовой стрелке от верхней вертикали плана; север нужен для оконных лучей, а не для фона «Следует за Солнцем».","gs.north.help.aria":"Подсказка: общее направление севера","gs.north_ph":"не задан","gs.north_clear":"Сбросить","gs.north_letter":"С","gs.sun_rays":"Солнце в окнах","gs.sun_ray_origin":"Лучи солнца","gs.sun_ray_origin.inner":"От внутренних углов окон","gs.sun_ray_origin.outer":"От внешних углов окон","gs.about_version":"Houseplan Card v{v}","gs.about_github":"GitHub · документация и issues","gs.about_telegram":"Чат в Telegram","support.title":"Помощь и обратная связь","space.bg_color":"Цвет фона вокруг плана","space.bg_inherit":"Наследовать общий","space.bg_inherited":"наследуется из общих настроек","space.bg_mode":"Фон плана","space.bg_mode.help":"Выберите наследование общего фона либо переопределите это пространство статичным цветом или режимом «Следует за Солнцем».","space.bg_mode.help.aria":"Подсказка: фон пространства","space.north":"Север на плане (переопределение)","space.north.help":"Переопределяет общий север для этого пространства; угол отсчитывается по часовой стрелке от верхней вертикали плана и используется оконными лучами.","space.north.help.aria":"Подсказка: север для пространства","space.north_inherited":"наследуется: {v}","space.sun_rays":"Солнце в окнах","space.sun_inherit":"Наследовать общий","space.sun_on":"Вкл","space.sun_off":"Выкл","canvas.far_objects":"Объектов далеко от плана: {n}","canvas.show_far":"Показать","canvas.home_tip":"План там — нажмите, чтобы вписать","gs.grid_group":"Обслуживание планов","gs.grid_hint":"Обновляет модели данных, выравнивает элементы по сетке и объединяет лишние фрагменты стен. Перед записью будет показан точный отчёт.","gs.align_all":"Оптимизировать планы","gs.align_title":"Оптимизировать планы","gs.align_none":"Все планы уже используют актуальную и оптимальную модель данных.","gs.optimize_no_automatic_changes":"Автоматических изменений нет. Проверьте пункты ниже.","gs.align_count":"Сдвинется элементов: {n} из {total}, максимум на {cm} см.","gs.align_where":"Наибольший сдвиг — в пространстве «{s}».","gs.align_turned":"Проёмов с исправлением угла: {n}.","gs.align_preflight_failed":"Не удалось безопасно проверить геометрию следующих пространств: {spaces}{more}.","gs.align_preflight_hint":"Планы не изменены. Скопируйте диагностику кнопкой ниже и приложите её к отчёту об ошибке вместе с экспортом пространства.","gs.preflight_reason_prepare-exception":"Не удалось подготовить геометрию пространства (исключение при сборке модели)","gs.preflight_reason_wall-null":"Тело стен не построилось (объединение вернуло пустоту)","gs.preflight_reason_wall-degraded-extra":"Тело стен деградировало с лишней геометрией","gs.preflight_reason_wall-failed-core":"Ядро тела стен не собралось","gs.preflight_reason_wall-exception":"Построение стен упало с исключением","gs.preflight_reason_floor-null":"Контур пола не построился","gs.preflight_reason_floor-exception":"Построение пола упало с исключением","gs.preflight_copy":"Скопировать диагностику","gs.preflight_copied":"Диагностика скопирована","gs.preflight_update_hint":"Версии карточки и интеграции различаются — обновите House Plan и повторите.","gs.align_preflight_space":"Пространство {n}","gs.align_preflight_more":" и ещё {n}","gs.optimize_changes":"Миграций модели: {m}; обновлено пространств: {c}; устранён шум координат: {p}; объединено отрезков реальных стен: {w}; объединено отрезков стен нулевой толщины: {s}; независимых: {i}.","gs.zero_walls_migrated":"Преобразовано виртуальных участков: {n}.","gs.wall_segments_migrated":"Стабилизировано сегментов стен: {n}.","gs.room_drafts_migrated":"Незавершённые контуры преобразованы в обычные стены: {drafts}; отрезков: {segments}.","gs.optimize_lattice_summary":"Канонизировано шумовых значений координат: {n}; максимальный сдвиг: {cm} см.","gs.optimize_lattice_space":"{space}: канонизировано значений координат: {n}; оставлено значений вне сетки: {far}.","gs.optimize_coincident_partitions":"Скрытые участки независимых стен поглощены стенами комнат: {n}.","gs.optimize_openings_rehosted":"Проёмы перепривязаны к стенам комнат: {n}.","gs.optimize_walls_straightened":"Выпрямлено стен: {n}; максимальное перемещение: {cm} см.","gs.optimize_walls_straightened_where":"Максимальная правка стены: {s}.","gs.optimize_walls_straighten_skipped":"Оставлено почти осевых стен, которые нельзя безопасно выпрямить: {n}.","gs.optimize_glow_migration":"Старый Glow: пространств — {spaces} → без заливки данных + независимый Glow; комнат — {rooms} → наследуемая заливка + независимый Glow.","gs.optimize_references":"Исправлено ссылок: пространства — {spaces}; комнаты — {rooms}; позиции — {positions}; устройств отвязано от отсутствующих пространств — {detached}.","gs.optimize_reference_more":", и ещё {n}","gs.optimize_orphans_removed":"Убрано забытых записей: {total} — подписи комнат: {rooms}; устройства: {devices}; групповые метки: {groups}. Все они принадлежали пространствам, удалённым ранее.","gs.optimize_live_positions":"Старые позиции в удалённых пространствах принадлежат существующим объектам: {n}{names}. Они будут сохранены.","gs.optimize_live_positions_remove":"Старые позиции в удалённых пространствах принадлежат существующим объектам: {n}{names}. Они выбраны для удаления.","gs.optimize_live_names":": {names}{more}","gs.optimize_live_remove":"Убрать старые позиции","gs.optimize_live_keep":"Сохранить старые позиции","gs.optimize_live_selected":"Старые позиции будут убраны после применения оптимизации.","gs.optimize_unverified":"Не удалось безопасно проверить позиций: {n}. Они оставлены без изменений.","gs.optimize_registry_limited":"Для безопасной проверки нужен полный доступ администратора к реестрам Home Assistant.","gs.optimize_vacuum_warning":"Сопоставления комнат пылесоса требуют проверки: {n}.","gs.optimize_details":"Подробности","gs.optimize_details_more":"И ещё записей: {n}.","gs.optimize_detail_removed":"будет удалено","gs.optimize_detail_live":"будет сохранено","gs.optimize_detail_unverified":"не проверено","gs.optimize_detail_room_label":"подпись комнаты","gs.optimize_detail_device":"устройство","gs.optimize_detail_group":"групповая метка","gs.optimize_detail_unknown":"неизвестный владелец","gs.optimize_detail_item":"{status}: {kind} {id}; прежнее пространство {space}","gs.align_warn":"Элементы, намеренно поставленные между узлами, будут сдвинуты. После операции доступна одна отмена — только до следующего изменения плана.","gs.align_run":"Оптимизировать","gs.align_done":"Планы оптимизированы: сдвинуто элементов — {n}, обслужено записей — {m}, исправлено ссылок — {r}","gs.optimize_undo":"Отменить последнюю оптимизацию","gs.optimize_undone":"Последняя оптимизация отменена","decor.furniture":"Мебель","decor.image":"Изображение","decor.image_title":"Свои изображения","decor.image_upload":"Загрузить изображение","decor.image_replace":"Заменить изображение","decor.image_uploading":"Загрузка…","decor.image_asset":"Файл изображения","decor.image_pick_hint":"Загрузите изображение или выберите уже используемое в House Plan.","decor.image_place_hint":"Кликните по плану, чтобы разместить изображение.","decor.image_none":"Загруженных изображений пока нет.","decor.image_unavailable":"Изображение недоступно","decor.image_used":"Используется в объектах: {n}","decor.image_upload_failed":"Не удалось загрузить изображение: {err}","decor.image_error_capacity":"Хранилище пользовательских изображений заполнено.","decor.image_in_use":"Перед удалением файла удалите все размещённые копии.","decor.image_delete_title":"Удалить файл изображения?","decor.image_delete_message":"Удалить «{name}» из House Plan? Это действие нельзя отменить.","furn.title":"Библиотека мебели","furn.symbol":"Символ","furn.group_furniture":"Мебель","furn.group_appliance":"Техника","furn.group_sanitary":"Сантехника","furn.group_other":"Прочее","furn.width":"Ширина","furn.depth":"Глубина","furn.back_to_categories":"Все категории","furn.pick_hint":"Выберите категорию, затем символ.","furn.place_hint":"Кликните по плану — предмет встанет к ближайшей стене. Shift — свободно.","furn.cat_air_conditioner":"Кондиционеры","furn.cat_armchair":"Кресла","furn.cat_bathtub":"Ванны","furn.cat_bed":"Кровати","furn.cat_bidet":"Биде","furn.cat_boiler":"Бойлеры","furn.cat_chair":"Стулья","furn.cat_coffee_table":"Журнальные столы","furn.cat_cooktop":"Варочные панели","furn.cat_dining_table":"Обеденные столы","furn.cat_dishwasher":"Посудомоечные машины","furn.cat_dryer":"Сушильные машины","furn.cat_fireplace":"Камины","furn.cat_fridge":"Холодильники","furn.cat_kitchen_cabinet":"Кухонные шкафы","furn.cat_kitchen_sink":"Кухонные мойки","furn.cat_nightstand":"Тумбы","furn.cat_plant":"Растения","furn.cat_rug":"Ковры","furn.cat_shelving":"Стеллажи","furn.cat_shower":"Душевые","furn.cat_sink":"Раковины","furn.cat_sofa":"Диваны","furn.cat_stairs":"Лестницы","furn.cat_toilet":"Унитазы","furn.cat_tv":"Телевизоры","furn.cat_wardrobe":"Шкафы","furn.cat_washer":"Стиральные машины","furn.cat_work_table":"Рабочие столы","furn.sym_sofa":"Диван двухместный","furn.sym_sofa_three_seat":"Диван трёхместный","furn.sym_sofa_corner_right":"Угловой диван, правый","furn.sym_armchair":"Кресло мягкое","furn.sym_armchair_office":"Кресло офисное","furn.sym_coffee_table":"Журнальный стол, прямоугольный","furn.sym_coffee_table_round":"Журнальный стол, круглый","furn.sym_coffee_table_oval":"Журнальный стол, овальный","furn.sym_coffee_table_rounded":"Журнальный стол, скруглённый","furn.sym_table_dining":"Обеденный стол, прямоугольный","furn.sym_table_round":"Круглый стол","furn.sym_table_dining_oval":"Обеденный стол, овальный","furn.sym_table_dining_rounded":"Обеденный стол, скруглённый","furn.sym_chair":"Стул","furn.sym_chair_bar":"Барный стул","furn.sym_desk":"Рабочий стол, прямоугольный","furn.sym_desk_corner":"Рабочий стол, угловой","furn.sym_bed_double":"Двуспальная кровать","furn.sym_bed_single":"Односпальная кровать","furn.sym_nightstand":"Тумба прикроватная","furn.sym_cabinet_tv":"Тумба под телевизор","furn.sym_cabinet_shoe":"Тумба для обуви","furn.sym_cabinet_sink":"Тумба под раковину","furn.sym_wardrobe":"Шкаф гардеробный","furn.sym_bookshelf":"Шкаф книжный","furn.sym_wall_unit":"Шкаф-стенка","furn.sym_kitchen_floor":"Кухонный напольный модуль","furn.sym_kitchen_floor_corner":"Кухонный напольный угловой модуль","furn.sym_kitchen_wall":"Кухонный навесной модуль","furn.sym_kitchen_wall_corner":"Кухонный навесной угловой модуль","furn.sym_shelf_floor":"Стеллаж напольный","furn.sym_shelf_wall":"Полка настенная","furn.sym_fridge":"Холодильник","furn.sym_stove":"Варочная панель, 4 конфорки","furn.sym_cooktop_two":"Варочная панель, 2 конфорки","furn.sym_dishwasher":"Посудомоечная машина","furn.sym_washer":"Стиральная машина","furn.sym_dryer":"Сушильная машина","furn.sym_tv":"Телевизор на подставке","furn.sym_tv_wall":"Телевизор на кронштейне","furn.sym_ac":"Кондиционер","furn.sym_water_heater":"Бойлер","furn.sym_toilet":"Унитаз напольный","furn.sym_toilet_built_in":"Унитаз встроенный","furn.sym_bathtub":"Ванна прямоугольная","furn.sym_bathtub_corner":"Ванна угловая","furn.sym_shower":"Душ","furn.sym_sink":"Раковина","furn.sym_kitchen_sink":"Кухонная мойка одинарная","furn.sym_kitchen_sink_double":"Кухонная мойка двойная","furn.sym_bidet":"Биде напольное","furn.sym_bidet_built_in":"Биде встроенное","furn.sym_stairs":"Лестница","furn.sym_fireplace":"Камин","furn.sym_plant":"Растение","furn.sym_rug":"Ковёр","common.yes":"Да","common.no":"Нет","vac.diag_source":"Источник","vac.diag_platform":"Интеграция","vac.diag_status":"Статус","vac.diag_position":"Позиция","vac.diag_rooms":"Комнаты","vac.diag_rooms_value":"{total} · совпало имён: {matched} · {readiness}","vac.autocal_ready":"автокалибровка доступна","vac.autocal_not_ready":"нужно 3 совпавших имени","vac.diag_path":"Путь интеграции","vac.diag_map":"ID карты","vac.source_none":"не выбран","vac.source_status_ok":"Готов","vac.source_status_missing":"Не найден","vac.source_status_disabled":"Деактивирован в Home Assistant","vac.source_status_unavailable":"Недоступен","vac.source_status_unverified":"Нельзя проверить с текущими правами","vac.source_status_unsupported":"Нет данных позиции","vac.source_status_none":"Нет источника","vac.source_banner_missing":"Сохранённый источник больше не существует. Он не заменён автоматически: выберите другой или восстановите его в Home Assistant.","vac.source_banner_disabled":"Сохранённый источник деактивирован в Home Assistant. Активируйте его там или выберите другой.","vac.source_banner_unverified":"Текущих прав Home Assistant недостаточно для проверки источника. Привязка сохранена и не будет заменена автоматически.","vac.choose_source":"Выбрать источник","vac.source_auto":"Автоматически","vac.source_auto_hint":"Использовать совместимую сущность этого устройства","vac.all_cameras":"Все камеры","vac.all_cameras_warn":"Камера может не отдавать данные робота. Выбирайте её только если это карта вашего пылесоса.","vac.all_cameras_empty":"Других сущностей камеры не найдено.","vac.platform_unknown":"интеграция неизвестна","vac.cap_position":"позиция","vac.cap_rooms_short":"комнаты","vac.cap_path":"путь","vac.cap_map":"ID карты","vac.cap_none":"данные робота не обнаружены","vac.xcme_hint":"Включите атрибуты Xiaomi Cloud Map Extractor:","vac.documentation":"Документация","vac.residual_title":"Проверьте автокалибровку","vac.residual_message":"Совпавшие комнаты расходятся максимум на {error}. Примените приблизительную калибровку, подгоните её вручную либо отмените без изменения сохранённых настроек.","vac.apply_proposal":"Применить","gs.backup_group":"Резервная копия и перенос","gs.backup_hint":"Скачайте переносимую JSON-копию или проверьте и импортируйте копию, созданную House Plan.","backup.export_open":"Экспорт","backup.import_open":"Импорт","backup.export_title":"Экспорт House Plan","backup.import_title":"Импорт House Plan","backup.export_hint":"Выберите, должна ли копия содержать всю конфигурацию House Plan или только текущее пространство.","backup.full":"Полная копия","backup.current_space":"Текущее пространство","backup.current_space_title":"Текущее пространство: {title}","backup.no_current_space":"Нет текущего пространства","backup.plan_only":"Только планировка","backup.plan_only_hint":"Сохранить комнаты, стены, проёмы, декор и позиции подписей комнат без устройств и привязок Home Assistant.","backup.plan_only_preview":"Файл содержит только планировку","backup.privacy_warning":"Архив сохраняет названия, идентификаторы Home Assistant и точные координаты. Внутренние планы и вложения указываются ссылками, но не вкладываются; текущие состояния и маршруты пылесосов не включаются.","backup.download":"Скачать JSON","backup.export_done":"Резервная копия скачана","backup.reading":"Проверяем резервную копию…","backup.revalidated":"После предпросмотра план изменился. Сводка обновлена — проверьте её и подтвердите ещё раз.","backup.error.support_invalid_message":"Проверьте сообщение для поддержки и повторите попытку.","backup.error.support_package_too_large":"Обезличенный пакет для поддержки превышает лимит 8 МиБ.","backup.error.support_preview_expired":"Предпросмотр вложения для поддержки истёк или больше недоступен.","backup.error.support_rate_limited":"Запрошено слишком много репортов или предпросмотров. Повторите позже.","backup.error.support_rejected":"Репорт не прошёл проверку службы поддержки.","backup.error.support_unavailable":"Закрытая служба поддержки временно недоступна.","backup.error.unauthorized":"У вас нет прав на экспорт или импорт этого плана.","backup.error.not_ready":"House Plan ещё не готов. Повторите попытку через несколько секунд.","backup.error.too_large":"Размер резервной копии превышает 8 МиБ.","backup.error.invalid_json":"Выбранный файл не является корректным JSON.","backup.error.invalid_format":"Выбранный файл не является резервной копией House Plan.","backup.error.invalid_image":"Изображение повреждено или не соответствует своему формату.","backup.error.unsupported_export_version":"Эта версия формата резервной копии не поддерживается установленной версией.","backup.error.unsupported_image":"Используйте поддерживаемое изображение PNG, JPEG, WebP или SVG.","backup.error.future_model":"Резервная копия создана в более новой версии модели данных House Plan.","backup.error.invalid_config":"Резервная копия содержит некорректную конфигурацию House Plan.","backup.error.wall_model_migration_blocked":"Не удалось безопасно обновить модель стен из резервной копии. Сначала оптимизируйте исходный план и повторите экспорт.","backup.error.invalid_layout":"Резервная копия содержит некорректные позиции объектов.","backup.error.invalid_content":"Резервная копия содержит некорректные или несогласованные ссылки на файлы.","backup.error.space_not_found":"Выбранное пространство больше не существует.","backup.error.capacity_exceeded":"Добавление этой копии превысит ограничения размера плана.","backup.error.preview_expired":"Время предпросмотра истекло. Выберите файл резервной копии заново.","backup.error.preview_owner_mismatch":"Этот предпросмотр принадлежит другому пользователю Home Assistant.","backup.error.conflict":"После предпросмотра план изменился. Проверьте обновлённую сводку.","backup.error.content_confirmation_required":"Подтвердите отсоединение недоступных локальных файлов.","backup.error.commit_failed":"Не удалось безопасно применить копию. Предыдущий план восстановлен или ожидает восстановления.","backup.error.missing_plan":"После предпросмотра исчез связанный файл плана. Проверьте копию ещё раз.","backup.error.missing_content":"После предпросмотра исчез связанный локальный файл. Проверьте копию ещё раз.","backup.error.marker_control_missing":"В резервной копии отсутствует связанный источник света на плане.","backup.error.marker_control_not_light":"Связанная цель больше не отмечена как источник света.","backup.error.marker_control_self":"Источник света не может управлять самим собой.","backup.error.marker_control_cycle":"Резервная копия содержит циклическую цепочку управления светом.","backup.error.duplicate_marker_control":"Резервная копия содержит повторяющуюся связь с источником света.","backup.error.no_backup":"Нет снимка импорта или оптимизации, который можно восстановить.","backup.error.in_use":"Элемент ещё используется","backup.error.invalid_data":"Запрос содержит некорректные данные","backup.error.invalid_light_entity":"Ведущий свет должен быть сущностью light.* или switch.*","backup.error.invalid_marker_control":"Некорректная ссылка управления маркером","backup.error.invalid_name":"Некорректное имя","backup.error.invalid_partition_opening_host":"Проём должен сохранить свою перегородку-носитель","backup.error.invalid_partition_opening_jamb_margin":"Проём не оставляет физического простенка у края стены","backup.error.invalid_passage_fields":"Открытый проход не может нести настройки двери","backup.error.invalid_space_id":"Неизвестное пространство","backup.error.invalid_toggle_entity":"Сущность переключения должна быть light.* или switch.*","backup.error.invalid_value_badge":"Некорректные настройки бейджа значения","backup.error.invalid_value_badge_attribute":"Некорректный атрибут бейджа значения","backup.error.invalid_value_badge_position":"Некорректная позиция бейджа значения","backup.error.invalid_value_badge_source":"Некорректный источник бейджа значения","backup.error.invalid_vacuum_map_route":"Проверьте сопоставление карт робота пространствам.","backup.error.invalid_value_source":"Некорректный источник значения","backup.error.invalid_value_source_attribute":"Некорректный атрибут источника значения","backup.error.io_error":"Файловая операция на сервере не удалась","backup.error.not_toggleable":"Это устройство нельзя переключить","backup.error.nothing_to_repair":"Нечего чинить","backup.error.space_in_use":"На пространство ещё есть ссылки","backup.error.value_badge_source_required":"Бейджу значения нужен источник","backup.error.wall_model_client_outdated":"План обновлён в другом месте — перезагрузите страницу","backup.same_source":"Создано на этом экземпляре Home Assistant","backup.foreign_source":"Создано на другом экземпляре Home Assistant","backup.created":"Создано: {value}","backup.versions":"Карточка {card}; интеграция {integration}; модель данных {model}","backup.count_spaces":"Пространств: {n}","backup.count_rooms":"Комнат: {n}","backup.count_walls":"Стен: {n}","backup.count_openings":"Проёмов: {n}","backup.count_decor":"Объектов декора: {n}","backup.count_markers":"Устройств: {n}","backup.count_layout":"Позиций: {n}","backup.bindings":"Привязки — устройства: {device}, сущности: {entity}, виртуальные: {virtual}; позиций без пространства: {legacy}","backup.binding_status":"Статус на целевом экземпляре — активных: {active}, деактивированных: {disabled}, отсутствующих: {missing}","backup.missing_areas":"На целевом экземпляре отсутствуют зоны: {areas}","backup.dropped_marker_links":"Связи с источниками света вне переносимого пространства пропущены: {n}.","backup.room_drafts_migrated":"Старые незавершённые контуры преобразованы в обычные стены: {drafts}; отрезков: {segments}.","backup.repaired_target_refs":"Существующих ссылок восстановлено этим импортом: {n}.","backup.preserved_unresolved_refs":"Неоднозначные ссылки сохранены без изменений: {n}.","backup.preserved_unresolved_hint":"House Plan ничего не угадывал и не удалял. После импорта запустите «Оптимизировать планы», чтобы проверить оставшиеся ссылки.","backup.import_details":"Подробности восстановления ссылок","backup.import_detail.incoming_remapped":"Ссылок обновлено внутри импортируемой копии: {n}","backup.import_detail.target_repaired":"Существующих ссылок восстановлено: {n}","backup.import_detail.preserved_unresolved":"Неразрешимых ссылок сохранено: {n}","backup.import_detail.collisions":"Конфликтов назначения безопасно сохранено: {n}","backup.import_detail.dropped_links":"Входящих связей пропущено по правилам переноса: {n}","backup.import_detail.bounded_lineages":"Чрезмерно вложенных идентификаторов ограничено: {n}","backup.replace_warning":"Текущая конфигурация и расположение будут заменены. Загруженные файлы не удаляются. Одну отмену можно выполнить до следующего изменения плана.","backup.foreign_bookkeeping":"Служебные списки известных и новых устройств другого экземпляра импортированы не будут.","backup.final_name":"Название нового пространства","backup.target_settings":"Глобальные настройки целевого экземпляра не изменятся.","backup.duplicates":"Уже существующих привязок: {n}","backup.skip":"Пропустить повторяющиеся устройства","backup.virtual_copy":"Добавить безопасные статичные виртуальные копии","backup.content":"Связанное содержимое","backup.decor_images_summary":"Свои изображения: объектов — {objects}, файлов — {assets}; отсутствует файлов — {missing}.","backup.content_available":"доступно локально","backup.content_external":"внешняя ссылка","backup.content_detach_required":"будет отвязано","backup.confirm_detach":"Я понимаю, что недоступные внутренние планы и вложения будут отвязаны от импортируемой конфигурации.","backup.confirm_missing_images":"Я понимаю, что отсутствующие свои изображения останутся восстанавливаемыми заглушками, а остальные недоступные локальные файлы будут отвязаны.","backup.replace":"Заменить","backup.add":"Добавить пространство","backup.space_done":"Пространство импортировано: комнат — {rooms}, устройств — {markers}, существующих ссылок восстановлено — {refs}","backup.full_done":"Копия восстановлена: пространств — {spaces}, комнат — {rooms}, устройств — {markers}","backup.undo_import":"Отменить последний полный импорт","backup.import_undone":"Полный импорт отменён","backdrop.large_title":"Большое изображение","backdrop.large_body":"Изображение {w}×{h} ({fileMb} МБ), для показа потребуется около {decodedMb} МБ памяти. На планшетах это может привести к падению страницы.","backdrop.unknown_body":"Не удалось прочитать размеры изображения — файл может быть повреждён. Продолжение может привести к падению страницы на планшете.","backdrop.reduced_dimensions":"Уменьшенная копия: {w}×{h} px.","backdrop.use_downscaled":"Загрузить уменьшенную копию","backdrop.reducing":"Уменьшаем…","backdrop.keep_original":"Оставить оригинал","backdrop.too_large_title":"Изображение слишком большое","backdrop.too_large_body":"Изображение превышает возможности браузера ({w}×{h}, предел {limit} px по стороне). Уменьшите его в редакторе на компьютере и загрузите снова.","backdrop.downscale_failed":"Не удалось создать уменьшенную копию. Текущий план не изменён."}},{code:"de",nativeLabel:"Deutsch",loadDictionary:async function(e){const t=0===e?await import("./de-OKLqCJOe.js"):await import(new URL("./de-OKLqCJOe.js?retry",import.meta.url).href);return{dictionary:t.dictionary,fingerprint:t.fingerprint}}},{code:"fr",nativeLabel:"Français",loadDictionary:async function(e){const t=0===e?await import("./fr-BjvleGPe.js"):await import(new URL("./fr-BjvleGPe.js?retry",import.meta.url).href);return{dictionary:t.dictionary,fingerprint:t.fingerprint}}}],mp=cp,gp=new Set;const fp=new class{constructor(e,t,i=console.warn,n){this.entries=e,this.expectedFingerprint=t,this.warn=i,this.loadFailed=n,this.dictionaries=new Map,this.pending=new Map,this.failed=new Set;for(const t of e)t.dictionary&&this.dictionaries.set(t.code,t.dictionary)}state(e){return this.dictionaries.has(e)?"ready":this.failed.has(e)?"fallback":"pending"}dictionary(e){return this.dictionaries.get(e)}ensure(e){if("pending"!==this.state(e))return Promise.resolve();const t=this.pending.get(e);if(t)return t;const i=this.entries.find(t=>t.code===e),n=this.load(i).finally(()=>this.pending.delete(e));return this.pending.set(e,n),n}async load(e){if(!e?.loadDictionary)return void(e&&this.failed.add(e.code));let t;for(const i of[0,1])try{const t=await e.loadDictionary(i);if(t.fingerprint!==this.expectedFingerprint)throw new Error(`locale fingerprint mismatch for ${e.code}`);return this.dictionaries.set(e.code,t.dictionary),void this.failed.delete(e.code)}catch(e){t=e}this.failed.add(e.code),this.warn(`[houseplan] unable to load ${e.code} locale; using English`,t),this.loadFailed?.(e.code)}}(_p,"3f783ed7cf5daff202a910aa89044f88f605a65af7f46794277dddf04333e502",console.warn,function(e){for(const t of gp)t(e)});function vp(e){const t=wp(e)?.code??"en";return fp.dictionary(t)??mp}function yp(e){return"string"==typeof e?e.trim().replaceAll("_","-").toLowerCase():""}const bp=new Map(_p.map(e=>[yp(e.code),e]));function wp(e){return bp.get(yp(e))}function kp(e,t){const i=[{value:"",label:e},..._p.map(({code:e,nativeLabel:t})=>({value:e,label:t}))],n="string"==typeof t?t:"";return n&&!i.some(e=>e.value===n)&&i.push({value:n,label:wp(n)?.nativeLabel??n}),i}function xp(e,t){return function(e,t,i,n){const r=new Map(i.map(e=>[yp(e),e])),o=r.get(yp(e));if(o)return o;const s=yp(t),a=r.get(s);return a||(r.get(s.split("-")[0]||"")??n)}(t,e?.locale?.language||e?.language,_p.map(({code:e})=>e),"en")}function Sp(e,t,i){return nn(vp(e)[t]??mp[t]??t,i)}function $p(e,t){const i=vp(e)[t]??mp[t];return"string"==typeof i&&i.trim().length>0}function Mp(e,t,i,n){return{ox:0,oy:0}}function Rp(e,t){const i=(e.angle+90)*Math.PI/180,n=qa(16,t),r=e.gateFace?-n*e.gateFace.side:n*(e.flipV?-1:1);return[[e.x+Math.cos(i)*r,e.y+Math.sin(i)*r],r<0]}function Cp(e){const t=e.length/2,i=e.face.cm>0?e.face.cm/e.cellCm*e.gridPitch/2:qa(4,e.cellCm),n="gate"===e.type?Math.sin(10*Math.PI/180)*t:0;return{half:t,jambHalf:i,gateDepth:n,outlineHalf:Math.max(qa(16,e.cellCm),i+qa(8,e.cellCm),n+qa(8,e.cellCm)),hitHalf:Math.max(qa(20,e.cellCm),i+qa(10,e.cellCm),n+qa(12,e.cellCm))}}function Tp(e,t,i){e.minX=Math.min(e.minX,t),e.minY=Math.min(e.minY,i),e.maxX=Math.max(e.maxX,t),e.maxY=Math.max(e.maxY,i)}function Dp(e,t,i,n,r,o,s,a){const l=Math.min(s,a)*Math.PI/180,c=Math.max(s,a)*Math.PI/180,h=(e,t)=>{const i=Math.atan2(t,e),n=[l,c];for(let e=-3;e<=3;e++){const t=e*Math.PI-i,r=Math.PI/2+e*Math.PI-i;t>l&&tl&&r0&&[e.length,e.angle,t[0],t[1]].every(Number.isFinite)))return null;const{half:i,jambHalf:n}=Cp(e),r=Ba(e.cellCm),o=1.75*r,s=1.25*r,a=.75*r,l={minX:-i-s,minY:-n-s,maxX:i+s,maxY:n+s},c={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};if("window"===e.type)Dp(c,-i,0,i,-o,o,-90,0),Dp(c,i,-i,0,-o,o,0,90),Tp(c,-i-a,-i-a),Tp(c,i+a,a);else if("gate"===e.type){const t=10*e.face.side;Dp(c,-i,0,i,-o,o,0,t),Dp(c,i,-i,0,-o,o,-t,0)}else Dp(c,-i,0,e.length,-o,o,-90,0),Tp(c,-i-a,-e.length-a),Tp(c,i+a,a);const[h,d]=Ap(e),u={...l};Tp(u,c.minX+h,c.minY+d),Tp(u,c.maxX+h,c.maxY+d);const p=e.flipH?-1:1,_="gate"===e.type?1:e.flipV?-1:1,m=e.angle*Math.PI/180,g=Math.cos(m),f=Math.sin(m),v={minX:1/0,minY:1/0,maxX:-1/0,maxY:-1/0};for(const e of[u.minX,u.maxX])for(const i of[u.minY,u.maxY]){const n=e*p,r=i*_;Tp(v,t[0]+n*g-r*f,t[1]+n*f+r*g)}return v}function Fp(e){if("passage"===e.type)return W``;const t=Math.max(0,Math.min(1,e.amount)),{half:i,jambHalf:n}=Cp(e),r=Ba(e.cellCm),o=1.75*r,s=e.flipH?-1:1,a=e.flipV?-1:1,l="gate"===e.type?1:a,[c,h]=Ap(e);let d;if("window"===e.type){const o=Math.PI/2*i,s=e.face.cm>0?W``:W``;d=W` + + + + + + + + + + + + + + ${s} + `}else if("gate"===e.type){const n=10*e.face.side*t;d=W` + + + + + + + + + + + + `}else{const n=Math.PI/2*e.length;d=W` + + + + + + + + `}return W` + + + ${d} + `}const zp={climate:["current_temperature","temperature","current_humidity","humidity"],water_heater:["current_temperature","temperature"],cover:["current_position"],valve:["current_position"],fan:["percentage"],humidifier:["current_humidity","humidity"],light:["brightness"],media_player:["volume_level"],vacuum:["battery_level","fan_speed"],lawn_mower:["battery_level","fan_speed"]};function Ip(e){return e?e.sourceLabel?`${e.sourceLabel}: ${e.fullText}`:e.fullText:""}const Op=new WeakMap;function Ep(e){return e?"entity_state"===e.kind?`state:${e.entity_id}`:"entity_attribute"===e.kind?`attr:${e.entity_id}:${e.attribute}`:"derived_marker_state"===e.kind?`marker:${e.ref}`:"derived_lqi"===e.kind?"derived:lqi":"":""}function Np(e){if("derived:lqi"===e)return{kind:"derived_lqi"};if(e.startsWith("state:"))return{kind:"entity_state",entity_id:e.slice(6)};if(e.startsWith("attr:")){const t=e.slice(5),i=t.lastIndexOf(":");if(i>0)return{kind:"entity_attribute",entity_id:t.slice(0,i),attribute:t.slice(i+1)}}return e.startsWith("marker:marker:")?{kind:"derived_marker_state",ref:e.slice(7)}:null}function Hp(e,t){const i=e?.entities?.[t],n=e?.states?.[t];return String(i?.name||i?.original_name||n?.attributes?.friendly_name||t)}function Lp(e){return e.replaceAll("_"," ")}function Bp(e,t=1){const i=Number(e);return Number.isFinite(i)?`${Math.round(i*t)} %`:null}function qp(e){if("derived_lqi"===e.kind)return"lqi";if("entity_attribute"===e.kind){if(e.attribute.includes("temperature"))return"temperature";if(e.attribute.includes("humidity"))return"humidity"}return"default"}function jp(e,t,i,n=[]){let r=null,o="",s="available",a=null;if("entity_state"===i.kind){o=Hp(e,i.entity_id);const t=e?.states?.[i.entity_id];if(t)if(Up(e,i.entity_id))if(["string","number","boolean"].includes(typeof t.state))if(["unknown","unavailable"].includes(String(t.state).toLowerCase()))s="unavailable",a="missing";else{const n=Xi(e,i.entity_id);r=n?Zi(n,String(t.attributes?.unit_of_measurement||"")):null,r||(s="unavailable",a="missing")}else s="unavailable",a="non_scalar";else s="unavailable",a="missing";else s="missing",a="missing"}else if("entity_attribute"===i.kind){o=`${Lp(i.attribute)} · ${Hp(e,i.entity_id)}`;const t=e?.states?.[i.entity_id],n=!!t&&i.attribute in(t.attributes||{}),l=n?t.attributes?.[i.attribute]:void 0;t?Up(e,i.entity_id)?["unknown","unavailable"].includes(String(t.state).toLowerCase())?(s="unavailable",a="missing"):n?["string","number","boolean"].includes(typeof l)?(r=function(e,t,i){const n=e?.states?.[t];if(!n||!(i in(n.attributes||{})))return null;const r=Xi(e,t,i);if(r?.formatted)return r.text;const o=n.attributes?.[i];if("brightness"===i)return Bp(o,100/255);if("volume_level"===i)return Bp(o,100);if(["current_position","percentage","current_humidity","humidity","battery_level"].includes(i))return Bp(o);if("current_temperature"===i||"temperature"===i){const t=Number(o);if(!Number.isFinite(t))return null;const i=String(e?.config?.unit_system?.temperature||"°C");return`${Math.round(10*t)/10} ${i}`}return r?.text||(["string","number","boolean"].includes(typeof o)?String(o):null)}(e,i.entity_id,i.attribute),null==r&&(s="unavailable",a="missing")):(s="unavailable",a="non_scalar"):(s="unavailable",a="missing"):(s="unavailable",a="missing"):(s="missing",a="missing")}else if("derived_lqi"===i.kind){o="LQI";const i=Bd(e,t.entities);null==i?(s="unavailable",a="missing"):r=String(i)}else{o="Light state";const t=n.find(e=>e.ref===i.ref);if(t){const i=t.on?"on":"off",n=e?.localize?.(`state.default.${i}`);r="string"==typeof n&&n?n:i,o=t.name||o}else s="missing",a="missing"}const l=e?.localize?.("state.default.unavailable")||"Unavailable";return{source:i,sourceLabel:o,text:r??"—",fullText:r??l,availability:s,isLqi:"derived_lqi"===i.kind,tone:qp(i),failure:a}}function Wp(e,t){if(!0===t.marker?.use_climate_temp){const i=t.entities.find(t=>t.startsWith("climate.")&&Number.isFinite(Number(e?.states?.[t]?.attributes?.current_temperature)));return i?{kind:"entity_attribute",entity_id:i,attribute:"current_temperature"}:null}if("mdi:thermometer"===t.icon||"mdi:air-filter"===t.icon){const i=t.entities.find(t=>vd(e,t)&&Number.isFinite(Number(e?.states?.[t]?.state)));if(i)return{kind:"entity_state",entity_id:i}}return t.primary&&Wd(e,t.primary)&&Number.isFinite(Number(e?.states?.[t.primary]?.state))?{kind:"entity_state",entity_id:t.primary}:null}function Up(e,t){const i=e?.entities?.[t];if(i&&!ad(i))return!1;const n=i?.device_id?e?.devices?.[i.device_id]:null;return!n||ad(n)}function Gp(e,t){return Up(e,t)&&!!e?.states?.[t]}function Vp(e,t,i=[t]){const n=function(e,t){const i=e=>[e.id,e.primary,e.hidden?1:0,e.userHidden?1:0,e.entities.join(","),(e.controls||[]).join(","),e.marker?.binding||"",!0===e.marker?.is_light?1:0,e.marker?.light_entity||"",(e.marker?.controls||[]).join(",")].join("|");return`${i(e)}\n${t.map(i).join("\n")}`}(t,i),r=Op.get(t);if(r&&r.states===(e?.states||null)&&r.entities===(e?.entities||null)&&r.devices===(e?.devices||null)&&r.signature===n)return r.result;const o=new Set(t.entities);for(const e of t.controls||[])e.startsWith("marker:")||o.add(e);const s=[],a=Nd(e,i),l=a.filter(e=>e.key.startsWith("marker:")).map(e=>({ref:e.key,on:e.on,name:e.device?.name||e.key})),c=i=>{const n=Ep(i);if(s.some(e=>e.key===n))return;const r=jp(e,t,i,l),o="entity_attribute"===i.kind?`${i.entity_id} · ${i.attribute}`:"entity_state"===i.kind?i.entity_id:"derived_marker_state"===i.kind?i.ref:"LQI";s.push({key:n,source:i,label:r.sourceLabel,technical:o,value:r.text,available:"available"===r.availability})};for(const t of[...o].sort()){if(!Gp(e,t))continue;const i=t.split(".")[0],n=e?.entities?.[t];if("button"===i||"event"===i||"config"===n?.entity_category)continue;c({kind:"entity_state",entity_id:t});const r=e?.states?.[t];for(const e of zp[i]||[])e in(r?.attributes||{})&&c({kind:"entity_attribute",entity_id:t,attribute:e})}const h=new Set((t.marker?.controls||t.controls||[]).filter(e=>e.startsWith("marker:")));!0===t.marker?.is_light&&t.marker.id&&h.add(`marker:${t.marker.id}`);const d=new Set(a.map(e=>e.key));for(const e of[...h].sort())d.has(e)&&c({kind:"derived_marker_state",ref:e});return t.virtual||null==Bd(e,t.entities)||c({kind:"derived_lqi"}),Op.set(t,{states:e?.states||null,entities:e?.entities||null,devices:e?.devices||null,signature:n,result:s}),s}function Kp(e,t,i){const n=Wp(e,t);if(n&&i.some(e=>e.key===Ep(n)))return n;const r=t.primary&&i.find(e=>e.key===`state:${t.primary}`);if(r)return r.source;const o=[e=>e.technical.includes("temperature"),e=>e.technical.includes("humidity"),e=>e.technical.includes("battery")];for(const e of o){const t=i.find(e);if(t)return t.source}return i.find(e=>"derived_lqi"!==e.source.kind)?.source||i[0]?.source||null}function Yp(e){return e.touched?{value_badge:{enabled:e.enabled,source:e.source,position:e.position}}:e.originalHas?{value_badge:e.original}:{}}function Xp(e){return e.touched?e.source?{value_source:e.source}:{}:e.originalHas?{value_source:e.original}:{}}function Zp(e,t,i){return{kind:"none",reason:"none",generation:e,expiresAt:null,color:t,diameterScale:i,animated:!1,reducedMotionIndicator:"none"}}function Jp(e,t,i,n,r=null){return{kind:t,reason:"short"===t?"event":"running",generation:Math.max(1,Math.trunc(i)),expiresAt:"short"===t?r:null,color:e.color,diameterScale:n?1:e.diameterScale,animated:!n,reducedMotionIndicator:n?"dot":"none"}}const Qp={availability:"available",status:"neutral",activity:"none"};function e_(e){return e<=40?"low":e<180?"mid":"high"}function t_(e){return Jt(e)}function i_(e){const t=new Set,i=[];for(const n of e){if("string"!=typeof n)continue;const e=n.trim().replace(/\s+/g," ");if(!e)continue;const r=e.toLowerCase();t.has(r)||(t.add(r),i.push(e))}return i.join(", ")}function n_(e){return"static_icon"===e.display?"neutral":"alarm"===e.visual.status?"alarm":"unavailable"===e.visual.availability?"unavailable":e.lockState?e.lockState:"working"===e.visual.status?"working":"open"===e.visual.status?"open":"neutral"}const r_={sourceKind:"none",decisionIds:["source.skipped_static_fast_path"],visualSources:[],criticalSources:[],samples:[]};function o_(e,t){const i=e?.entities?.[t],n=e?.states?.[t];return String(i?.name||i?.original_name||n?.attributes?.friendly_name||t)}function s_(e,t){const i=e?.states?.[t];if(!i)return"";if("function"==typeof e?.formatEntityState)try{const t=e.formatEntityState(i);if("string"==typeof t&&t)return t}catch{}return String(i.state??"")}function a_(e,t){if(t.virtual||"virtual"===t.bindingKind||"virtual"===t.marker?.binding)return"available";const i=t.entities||[],n="ha_disabled"===t.bindingStatus?.kind||(t.bindingStatus?.allEntityIds?.length??0)>0;if(0===i.length&&!n&&("device"===t.bindingKind||t.marker?.binding?.startsWith("device:"))&&"active"===t.bindingStatus?.kind)return"available";return i.some(t=>{const i=String(e?.states?.[t]?.state??"").trim().toLowerCase();return""!==i&&"unknown"!==i&&"unavailable"!==i})?"available":"unavailable"}function l_(e,t,i,n){return{eid:t,role:i,name:o_(e,t),state:String(e?.states?.[t]?.state??""),stateText:s_(e,t),integrationDomain:e?.entities?.[t]?.platform||null,sample:n||zh(e,t)}}function c_(e,t,i=[t],n,r=e){const o=t.hidden&&t.userHidden?{...t,hidden:!1}:t;let s="none",a=[];const l=[],c=[...o.entities,...o.allEntities||[]].some(e=>e.startsWith("cover."))?{...o,tapAction:"cover"}:o,h=(d=zu({hass:e,devices:i,device:c,lightSources:n,registryHass:r}),"cover"!==d?.semantics?null:d.targets[0]?.entityId||d.skippedTargets[0]?.entityId||null);var d;const u=Nd(e,[o]),p=Sd(o.marker?.binding,o.marker?.controls??o.controls,o.entities),_=new Set(p.filter(e=>e.startsWith("marker:"))),m=!0===o.marker?.is_light||_.size>0?n||Nd(e,i):u,g=m.filter(e=>e.device.id===o.id&&"controls"!==e.via),f=u.filter(e=>"controls"!==e.via),v=g.length?g:f,y=jh(o.marker),b=y?[...v]:[...u.filter(e=>"controls"===e.via),...v];if(_.size)for(const e of m){if(!_.has(e.key))continue;e.stateEids.length>0&&b.some(t=>t.stateEids.some(t=>e.stateEids.includes(t)))||b.some(t=>t.key===e.key)||b.push({...e,via:"controls",castsGlow:!1})}const w=wd(r,o.entities),k=!!h&&("cover"===o.tapAction||o.primary?.startsWith("cover.")||w.some(e=>e.startsWith("cover.")));if(h&&!k&&l.push("source.cover_capability_bypassed"),k)s="cover",l.push("source.cover"),a=[l_(e,h,"cover")];else if(b.length)s=!y&&b.some(e=>"controls"===e.via)?"controls":"light",y?l.push("source.manual_virtual_light"):l.push("controls"===s?"source.controls":"source.owned_light"),"controls"!==s||!o.virtual&&"virtual"!==o.bindingKind||l.push("source.virtual_controller"),a=b.map(i=>{const n="controls"===i.via?"control":"forced"===i.via?"forced_light":"light";if(!i.passive)return l_(e,i.eid,n);const r=i.on?"on":"off";return{eid:i.key,role:n,name:t.name,state:r,stateText:r,integrationDomain:null,sample:{eid:i.key,state:r,availability:"available",status:i.on?"working":"neutral",activity:"none",edge:"none"}}});else{const t=wd(r,o.entities),i=t.length?t:o.entities.filter(t=>!!e?.states?.[t]);if(i.length){s="device_role",l.push("source.device_role");const t=Ih(r===e?e:{...r,states:e?.states||{}},i,o.entities),n=i.some(e=>Ah(r,e));a=t.map(t=>{const i=n?Ph(r,t.eid)?"power_gate":Ah(r,t.eid)?"lifecycle":"device_role":"device_role";return l_(e,t.eid,i,t)})}else o.primary?(s="primary",l.push("source.primary_fallback"),a=[l_(e,o.primary,"primary")]):l.push("source.none")}p.length>0&&"controls"!==s&&"light"!==s&&"cover"!==s&&l.push("source.filtered_saved_controls");const x=[];for(const t of o.entities||[]){const i=zh(e,t);"alarm"!==i.status||a.some(e=>e.eid===t)||x.push(l_(e,t,"critical",i))}return x.length&&l.push("source.critical_sibling"),{sourceKind:s,decisionIds:l,visualSources:a,criticalSources:x,samples:[...a,...x].map(e=>e.sample)}}function h_(e,t,i,n,r=[]){if(t.virtual)return{source:null,text:null,fullText:null,fallback:"value_virtual",explicit:!1};const o=t.marker?.value_source;if(o){const i=jp(e,t,o,r);return{source:{kind:"derived_lqi"===o.kind?"derived_lqi":"derived_marker_state"===o.kind?"derived_marker_state":"entity_attribute"===o.kind&&o.attribute.includes("temperature")?"temperature":"entity_attribute"===o.kind&&o.attribute.includes("humidity")?"humidity":"entity",eid:"entity_state"===o.kind||"entity_attribute"===o.kind?o.entity_id:"derived_marker_state"===o.kind?o.ref:"derived:lqi",attribute:"entity_attribute"===o.kind?o.attribute:void 0,text:i.text,sourceKey:Ep(o)},text:i.text,fullText:i.fullText,fallback:"non_scalar"===i.failure?"value_non_scalar":"missing"===i.failure?"value_no_state":null,explicit:!0}}if(n){const i=function(e,t){if(!0!==t.marker?.use_climate_temp)return null;for(const i of t.entities){if(!i.startsWith("climate."))continue;const t=Number(e?.states?.[i]?.attributes?.current_temperature);if(Number.isFinite(t))return{eid:i,text:Math.round(10*t)/10+"°"}}return null}(e,t);if(i)return{source:{kind:"temperature",eid:i.eid,attribute:"current_temperature",text:i.text,sourceKey:`attr:${i.eid}:current_temperature`},text:i.text,fullText:i.text,fallback:null,explicit:!1};const n=function(e,t){if("mdi:thermometer"!==t.icon&&"mdi:air-filter"!==t.icon)return null;for(const i of t.entities){if(!vd(e,i))continue;const t=Number(e?.states?.[i]?.state);if(Number.isFinite(t))return{eid:i,text:Math.round(10*t)/10+"°"}}return null}(e,t);if(n)return{source:{kind:"temperature",eid:n.eid,text:n.text,sourceKey:`state:${n.eid}`},text:n.text,fullText:n.text,fallback:null,explicit:!1};const r=function(e,t){if(!t.primary||!Wd(e,t.primary))return null;const i=Number(e?.states?.[t.primary]?.state);return Number.isFinite(i)?{eid:t.primary,text:`${Math.round(i)}%`}:null}(e,t);if(r)return{source:{kind:"humidity",eid:r.eid,text:r.text,sourceKey:`state:${r.eid}`},text:r.text,fullText:r.text,fallback:null,explicit:!1}}const s=i.visualSources.filter(e=>!e.eid.startsWith("marker:"));let a=s.map(e=>e.eid);const l=s.find(e=>"power_gate"===e.role);if(l&&(a=[l.eid]),!a.length&&i.visualSources.some(e=>e.eid.startsWith("marker:"))&&(a=wd(e,t.entities),!a.length&&t.primary&&e?.states?.[t.primary]&&(a=[t.primary])),a=[...new Set(a)],1!==a.length)return{source:null,text:null,fullText:null,fallback:a.length?"value_ambiguous_sources":"value_no_state",explicit:!1};const c=a[0],h=function(e,t){const i=e?.states?.[t];if(!i||null==i.state||""===String(i.state).trim())return{text:"",fallback:"value_no_state"};const n=i.state;if(!["string","number","boolean"].includes(typeof n))return{text:"",fallback:"value_non_scalar"};const r=String(n).trim().toLowerCase();if("unknown"===r||"unavailable"===r)return{text:"",fallback:"value_no_state"};const o=Xi(e,t);return o?{text:Zi(o,String(i.attributes?.unit_of_measurement||"")),fallback:null}:{text:"",fallback:"value_no_state"}}(e,c);return h.fallback?{source:null,text:null,fullText:null,fallback:h.fallback,explicit:!1}:{source:{kind:"entity",eid:c,text:h.text,sourceKey:`state:${c}`},text:h.text,fullText:h.text,fallback:null,explicit:!1}}function d_(e,t,i){const n=e.marker?.binding||(e.bindingKind&&e.bindingRef?`${e.bindingKind}:${e.bindingRef}`:e.virtual?"virtual":""),r=[...t.visualSources.map(e=>`${e.role}:${e.eid}`),...t.criticalSources.map(e=>`critical:${e.eid}`)].sort(),o=i?`${i.kind}:${i.sourceKey}:${i.eid}:${i.attribute||""}`:"none";return[n,t.sourceKind,...r,`value:${o}`].join("\n")}function u_(e,t,i){return d_(t,i||c_(e,t),null).replace(/\nvalue:none$/,"")}function p_(e){if(e.effectiveHidden)return[];if("static_icon"===e.display)return["static-icon"];const t=[],{visual:i}=e;return"alarm"===e.pulse.kind?t.push("alarm"):"unavailable"===i.availability?t.push("unavail"):"working"===i.status?t.push("on"):"open"===i.status&&t.push("open"),e.lockState&&t.push(`lock-${e.lockState}`),"none"!==e.pulse.reason&&"alarm"!==e.pulse.reason&&t.push("activity-"+e.pulse.reason),e.pulse.generation%2==0&&(t.push("pulse-gen2"),"short"===e.pulse.kind&&t.push("activity-gen2")),t}function __(e,t,i){const n=Li(t.marker?.display),r="static_icon"===n,o=r&&!1===i.sourceDetails?r_:c_(e,t,i.lightDevices||[t],i.lightSources,i.registryHass||e),s="derived_marker_state"===t.marker?.value_source?.kind||"derived_marker_state"===t.marker?.value_badge?.source?.kind,a=(i.lightSources||(s?Nd(e,i.lightDevices||[t]):[])).filter(e=>e.key.startsWith("marker:")).map(e=>({ref:e.key,on:e.on,name:e.device.name})),l=t.bindingStatus,c="ha_disabled"===l?.kind,h="orphaned"===l?.kind,d=c?"ha_disabled":h?"orphaned":"active",u=!0===t.userHidden||!0===t.marker?.hidden,p=Oh(o.samples),_=o.visualSources.find(e=>e.eid.startsWith("lock.")),m=_?["unlocked","open"].includes(_.state.toLowerCase())?"unlocked":"locked"===_.state.toLowerCase()?"locked":null:null,g=!jh(t.marker)&&Sd(t.marker?.binding,t.marker?.controls??t.controls,t.entities).length>0,f="controls"===o.sourceKind||g&&"light"!==o.sourceKind&&"cover"!==o.sourceKind,v=r&&!1===i.sourceDetails?{source:null,text:null,fullText:null,fallback:null}:h_(e,t,o,i.showTemperature,a),y=d_(t,o,v.source),b=u_(e,t,o),w=i.activityRuntime,k=i.now??Date.now(),x=w?.expiresAt||(w?.flashTs?w.flashTs+3300:0),S=w?.sources===b&&w.flashTs&&w.flashKind&&x>k?w.flashKind:null,$=function(e){const t=[],i="ha_disabled"===e.bindingLifecycle||"orphaned"===e.bindingLifecycle;let n=!1;"ha_disabled"===e.bindingLifecycle?(n=!0,t.push("lifecycle.ha_disabled_hidden")):e.userHidden&&!e.designPreview?(n=!0,t.push("lifecycle.user_hidden")):e.userHidden?t.push("lifecycle.user_hidden_preview"):"orphaned"===e.bindingLifecycle?t.push("lifecycle.orphaned_diagnostic"):t.push("lifecycle.active");const r="static_icon"===e.display;let o=e.controllerFace?{...e.sourceVisual,availability:e.controllerAvailability}:e.sourceVisual;t.push(e.controllerFace?"available"===e.controllerAvailability?"availability.controller_available":"availability.controller_unavailable":"availability.source"),n?(o=Qp,t.push("face.hidden")):r?(o=Qp,t.push("face.static")):"alarm"===e.sourceVisual.status||e.liveStates?t.push("face.dynamic"):(o=Qp,t.push("face.live_states_disabled")),!r&&!n&&e.liveStates&&"alarm"!==e.sourceVisual.status&&e.shortActivity&&(o={...o,activity:e.shortActivity},t.push(`activity.short_${e.shortActivity}`)),"alarm"===o.status?t.push("status.alarm"):"unavailable"===o.availability?t.push("status.unavailable"):"working"===o.status?t.push("status.working"):"open"===o.status?t.push("status.open"):t.push("status.neutral");const s="value"===e.display&&!n&&e.valueAvailable?"value":"icon";t.push("value"===s?"content.value":"value"===e.display?"content.value_fallback_icon":"content.icon"),"value"===e.display&&!e.valueAvailable&&e.valueFallback&&t.push(`content.${e.valueFallback}`);const a=e.liveStates&&!r&&!n,l=!r&&!n,c=!n&&!i&&!r&&"available"===o.availability&&("alarm"===o.status||e.liveStates&&"icon_ripple"===e.display),h=l&&e.vacuumLiveRequested;return t.push(a?"diagnostics.dynamic_icon":"diagnostics.base_icon"),t.push(l?"diagnostics.metrics_enabled":"diagnostics.metrics_suppressed"),t.push(c?"activity.pulse_eligible":"activity.pulse_suppressed"),t.push(h?"diagnostics.vacuum_live":"diagnostics.vacuum_static"),{effectiveHidden:n,bindingUnavailable:i,visual:o,face:s,dynamicIcon:a,metrics:l,liveColor:a,pulseEligible:c,vacuumLive:h,decisionIds:t}}({bindingLifecycle:d,userHidden:u,designPreview:!0===i.designPreview,display:n,liveStates:i.liveStates,sourceVisual:p,controllerFace:f,controllerAvailability:f?a_(e,t):"available",shortActivity:S,valueAvailable:null!=v.text,valueFallback:v.fallback,vacuumLiveRequested:!0===t.marker?.vacuum?.live}),{effectiveHidden:M,visual:R}=$,C="icon_ripple"===n&&!M&&i.liveStates&&"alarm"!==R.status?R.activity:"none",T=$.metrics&&i.showTemperature?!0===t.marker?.use_climate_temp?jd(e,t.entities):"mdi:thermometer"===t.icon||"mdi:air-filter"===t.icon?qd(e,t.entities):null:null,D=$.metrics&&i.showTemperature&&t.primary&&Wd(e,t.primary)?Ud(e,t.entities):null,A=$.metrics&&i.showSignal&&!t.virtual?Bd(e,t.entities):null,P=function(e,t,i){const n=null!=t.marker?.value_badge;if(i.effectiveHidden||"static_icon"===i.display)return null;const r=t.marker?.value_badge;if(n)return r?.enabled?r.source?{configured:!0,enabled:!0,position:r.position||"right",...jp(e,t,r.source,i.markerStates)}:{configured:!0,enabled:!0,source:null,sourceLabel:"",text:"—",fullText:e?.localize?.("state.default.unavailable")||"Unavailable",position:r.position||"right",availability:"missing",isLqi:!1,tone:"default",failure:"missing"}:null;if(!i.showTemperature||"value"===i.display)return null;const o=Wp(e,t);if(!o)return null;let s=null,a="default";if("entity_attribute"===o.kind&&"current_temperature"===o.attribute){const i=jd(e,t.entities);null!=i&&(s=`${i}°`),a="temperature"}else if("mdi:thermometer"===t.icon||"mdi:air-filter"===t.icon){const i=qd(e,t.entities);null!=i&&(s=`${i}°`),a="temperature"}else{const i=Ud(e,t.entities);null!=i&&(s=`${i}%`),a="humidity"}return null==s?null:{configured:!1,enabled:!0,source:o,position:"right",sourceLabel:"entity_attribute"===o.kind?`${Lp(o.attribute)} · ${Hp(e,o.entity_id)}`:"entity_state"===o.kind?Hp(e,o.entity_id):"",text:s,fullText:s,availability:"available",isLqi:!1,tone:a,failure:null}}(e,t,{showTemperature:i.showTemperature,showSignal:i.showSignal,display:n,effectiveHidden:M,markerStates:a}),F=o.visualSources.find(e=>!e.eid.startsWith("marker:")),z="cover"===o.sourceKind?F?.eid:t.primary||F?.eid,I=z?e?.states?.[z]:null,O=$.dynamicIcon?kn(t.icon,z?.split(".")[0],I?.attributes?.device_class,I?.state,!!t.marker?.icon):t.icon,E=$.liveColor&&o.visualSources.filter(e=>!e.eid.startsWith("marker:")).map(t=>function(e){return e&&"on"===e.state?Zt(e.attributes?.rgb_color):null}(e?.states?.[t.eid])).find(e=>!!e)||null,N=Number(t.marker?.size)>0?Number(t.marker.size):1,H=Number(t.marker?.angle)||0,L=Number(t.marker?.ripple_size)>0?Number(t.marker.ripple_size):1.5,B=Kt(t.marker?.ripple_color,null),q=r?null:B||E||null,j=function(e){const{display:t,visual:i,semanticActivity:n,liveStates:r,effectiveHidden:o,bindingUnavailable:s=!1,reducedMotion:a=!1}=e,l=Math.max(1,Math.trunc(e.shortGeneration||1)),c=Number.isFinite(e.diameterScale)?Math.max(1,Number(e.diameterScale)):1.5,h=e.color||function(e,t){return"presence"===t?"#1DC21D":"running"===t||"working"===e.status||"open"===e.status?"#F0A00C":"#0C82F0"}(i,n);if(o||s||"unavailable"===i.availability||"static_icon"===t)return Zp(l,h,c);if("alarm"===i.status)return{kind:"alarm",reason:"alarm",generation:l,expiresAt:null,color:"#F0410C",diameterScale:1.5,animated:!a,reducedMotionIndicator:"none"};if(!r||"icon_ripple"!==t)return Zp(l,h,c);const d=e.now??Date.now(),u=e.shortExpiresAt||null;return e.shortReason&&null!=u&&u>d?{kind:"short",reason:e.shortReason,generation:l,expiresAt:u,color:h,diameterScale:a?1:c,animated:!a,reducedMotionIndicator:a?"dot":"none"}:"presence"===n||"transition"===n||"running"===n?{kind:"continuous",reason:n,generation:l,expiresAt:null,color:h,diameterScale:a?1:c,animated:!a,reducedMotionIndicator:a?"dot":"none"}:Zp(l,h,c)}({display:n,visual:R,semanticActivity:p.activity,shortReason:w?.sources===b?w?.flashKind:null,shortGeneration:w?.gen,shortExpiresAt:w?.sources===b?x:null,now:k,liveStates:i.liveStates,effectiveHidden:M,bindingUnavailable:$.bindingUnavailable,reducedMotion:i.reducedMotion,color:q,diameterScale:L}),W="value"===$.face?v.text:null,U="ha_disabled"===l?.kind?l.reason:null,G="ha_disabled"===(V={lifecycle:d,display:n,liveStates:i.liveStates,sourceKind:o.sourceKind,primaryDomain:(t.primary||"").split(".")[0],visual:R,activity:C}).lifecycle?"ha_disabled":"orphaned"===V.lifecycle?"orphaned":"static_icon"===V.display?"static_icon":"alarm"===V.visual.status?"alarm":V.liveStates?"unavailable"===V.visual.availability?"unavailable":"cover"===V.sourceKind?"cover_icon_state":"presence"===V.activity?"presence":"event"===V.activity?"event":"transition"===V.activity?"transition":"working"===V.visual.status?"icon_ripple"===V.display&&"none"!==V.activity?"working_activity":"working":"open"===V.visual.status?"open":"media_player"===V.primaryDomain?"media_neutral":"neutral":"live_states_disabled";var V;const K=[];i.designPreview&&u&&K.push("hidden_design_preview"),r||!0!==t.marker?.vacuum?.live||K.push("vacuum_live_plan_only");const Y=o.visualSources.some(t=>"power_gate"===t.role||Ph(e,t.eid)),X=t.entities.filter(t=>t.startsWith("switch.")&&!e?.entities?.[t]?.entity_category).length;Y&&X>1&&K.push("composite_power_source"),"icon_ripple"!==n&&"static_icon"!==n&&"alarm"!==p.status&&"none"!==p.activity&&K.push("activity_display_disabled");const Z={binding:t.marker?.binding||(t.bindingKind&&t.bindingRef?`${t.bindingKind}:${t.bindingRef}`:t.virtual?"virtual":""),sourceKind:o.sourceKind,visualSources:o.visualSources,criticalSources:o.criticalSources,valueSource:v.source,sourceSignature:y,decisionIds:[...o.decisionIds,...$.decisionIds,...P?["diagnostics.value_badge"]:[],...null==A?[]:[`diagnostics.lqi_${e_(A)}`],`pulse.${j.kind}_${j.reason}`],visual:R,lockState:m,display:n,icon:O,valueText:W,valueFullText:"value"===$.face?v.fullText:null,fallbackReason:"value"===n?v.fallback:null,activity:C,activityGeneration:w?.gen||1,pulse:j,classes:[],tempText:null==T?null:String(T),humText:null==D?null:String(D),valueBadge:P,lqiText:null==A||P?.isLqi||"derived_lqi"===v.source?.kind?null:String(A),lqiColor:null==A?null:t_(A),lqiBand:null==A?null:e_(A),lightColor:E,scale:N,angle:H,rippleScale:L,rippleColor:q,userHidden:u,effectiveHidden:M,haDisabled:c,disabledReason:U,orphaned:h,vacuumLive:$.vacuumLive,explanation:{reason:G,notices:K}};return{...Z,classes:p_(Z)}}function m_(e,t=new WeakMap){if(null===e||"object"!=typeof e)return e;const i=e,n=t.get(i);if(n)return n;if(Array.isArray(e)){const n=[];t.set(i,n);for(const i of e)n.push(m_(i,t));return Object.freeze(n)}const r={};t.set(i,r);for(const[i,n]of Object.entries(e))"function"!=typeof n&&(r[i]=m_(n,t));return Object.freeze(r)}function g_(e){const t=new Map(e);let i;return i=Object.freeze({get size(){return t.size},get:e=>t.get(e),has:e=>t.has(e),entries:()=>t.entries(),keys:()=>t.keys(),values:()=>t.values(),forEach:(e,n)=>t.forEach((t,r)=>e.call(n,t,r,i)),[Symbol.iterator]:()=>t[Symbol.iterator]()}),i}function f_(e){const t=new Set(e.entityIds||[]),i=new Set(e.deviceIds||[]),n=new Set(e.areaIds||[]);for(const n of e.devices){for(const e of n.entities||[])t.add(e);n.primary&&t.add(n.primary);for(const e of n.controls||[])t.add(e);n.marker?.vacuum?.source&&t.add(n.marker.vacuum.source),"device"===n.bindingKind&&n.bindingRef&&i.add(n.bindingRef),"entity"===n.bindingKind&&n.bindingRef&&t.add(n.bindingRef)}const r={},o={};for(const[o,s]of Object.entries(e.hass?.entities||{})){const a=s?.device_id?e.hass?.devices?.[s.device_id]:null;(t.has(o)||s?.device_id&&i.has(s.device_id)||n.has(s?.area_id)||n.has(a?.area_id))&&(t.add(o),r[o]=s,s?.device_id&&i.add(s.device_id))}for(const t of i){const i=e.hass?.devices?.[t];i&&(o[t]=i)}const s={};for(const i of t){const t=e.hass?.states?.[i];t&&(s[i]=t)}const a=Object.freeze({states:m_(s),entities:m_(r),devices:m_(o),config:m_(e.hass?.config),locale:m_(e.hass?.locale),themes:m_(e.hass?.themes)}),l=m_([...e.devices]),c=Object.freeze(l.filter(t=>e.facts?.has(`vacuum:${t.id}`)));return Object.freeze({sourceSequence:e.sourceSequence,capturedAt:e.capturedAt??Date.now(),hass:a,devices:l,vacuumDevices:c,positions:g_([...e.positions||[]].map(([e,t])=>[e,Object.freeze({x:t.x,y:t.y})])),presentations:g_([...e.presentations].map(([e,t])=>[e,m_(t)])),facts:g_([...e.facts||[]].map(([e,t])=>[e,m_(t)])),entityIds:Object.freeze([...t])})}const v_=(e,t)=>`${e}:${t?1:0}`;function y_(e){return"boolean"==typeof e?.themes?.darkMode?e.themes.darkMode?"theme-dark":"theme-light":""}function b_(e){const t=e.valueBadge;if(!t||!1!==t.configured)return[];const i=[];return null!=e.tempText&&"temperature"!==t.tone&&i.push({kind:"temperature",text:e.tempText,suffix:"°"}),null!=e.humText&&"humidity"!==t.tone&&i.push({kind:"humidity",text:e.humText,suffix:"%"}),i}function w_(e){const t=[];if(1!==e.scale&&t.push(`--dev-scale:${e.scale}`),"none"!==e.pulse.kind){t.push(`--ripple-scale:${e.pulse.diameterScale}`);const r=(i=e.pulse.color,n=null,"string"==typeof i&&(Vt.test(i)||Xt.test(i))?i:n);r&&t.push(`--ripple-color:${r}`)}var i,n;return t}function k_(e){const t=[...String(e)].reduce((e,t)=>/\s/.test(t)?e+.35:e+(t.codePointAt(0)>255?1:.62),0);return t<=8?.45:Math.max(.25,Math.round(3.6/t*1e3)/1e3)}function x_(e,t){const i=e.pulse,n=i.generation%2==0,r=b_(e),o=e.valueBadge,s=o?.position||"right",a=!!o||r.length>0,l=["device-shell",null!=e.valueText?"text-shell":"",a?`with-values pos-${s}`:"",r.length?"with-legacy":""].filter(Boolean).join(" ");return j` + ${"none"!==i.kind&&"dot"!==i.reducedMotionIndicator?j``:G} + ${"dot"===i.reducedMotionIndicator?j``:G} + ${t.newDevice?j``:G} + ${e.haDisabled?j``:G} + + ${null!=e.lqiText?j`${e.lqiText}`:G} + `}function S_(e){return!Number.isFinite(e)||e<=0?2.25:e/2.5*2.25}function $_({openings:e,geometries:t,fillsByRoomId:i,idPrefix:n="data",groupClass:r="opening-tunnels",dataLayer:o="data"}){const s=e.map((e,r)=>{const o=t[r];if(!o)return G;const s=o.faces.find(e=>-1===e.side),a=o.faces.find(e=>1===e.side);if(!s||!a)return G;const l=i.get(s.roomId)||null,c=i.get(a.roomId)||null;if(!l&&!c)return G;const h=`${s.d} ${a.d}`,d=!!l&&!!c&&l.color===c.color&&l.opacity===c.opacity,u=`translate(${e.rx} ${e.ry}) rotate(${e.angle})`;if(d)return W``;const p=o.maxY-o.minY;if(!(p>0))return G;const _=`${(100*Math.max(0,Math.min(1,-o.minY/p))).toFixed(6)}%`,m=l||{color:"#000000",opacity:0},g=c||{color:"#000000",opacity:0},f=`hp-opening-tunnel-${n.replace(/[^a-zA-Z0-9_-]/g,"-")}-${r}`;return W``});return W``}function M_(e,t,i){const n=i>0?i:1;return{a:[e[0]/n,e[1]/n],b:[t[0]/n,t[1]/n]}}function R_(e,t){const i=t>0?t:1;return[e.a[0]*i,e.a[1]*i,e.b[0]*i,e.b[1]*i]}function C_(e){return Array.isArray(e)&&e.length>=2&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1]))}function T_(e){if(!Array.isArray(e))return[];const t=[];for(const i of e){if(!i||"object"!=typeof i)continue;const e=i;if(!C_(e.a)||!C_(e.b))continue;const n=[Number(e.a[0]),Number(e.a[1])],r=[Number(e.b[0]),Number(e.b[1])];Math.hypot(r[0]-n[0],r[1]-n[1])<.001||t.push({a:n,b:r})}return t}function D_(e,t,i,n,r=!0){const o=(e||[]).filter(e=>e?.id),s=T_(t);if(s.length)return function(e,t,i,n){const r=T_(e);if(!r.length)return[];const o=function(e,t){const i=[],n=(e||[]).filter(e=>e?.id);for(let e=0;e4*n||o>4*n)continue;const s=(e[0]-r)*u+(e[1]-l)*p,c=(e[2]-r)*u+(e[3]-l)*p,h=Math.max(0,Math.min(s,c)),m=Math.min(d,Math.max(s,c));if(m-he.lo-t.lo||e.hi-t.hi);const i=[];for(const e of t){const t=i[i.length-1];t&&e.lo<=t.hi+a?t.hi=Math.max(t.hi,e.hi):i.push({...e})}for(const t of i){const i=[r+u*t.lo,l+p*t.lo],n=[r+u*t.hi,l+p*t.hi];Math.hypot(n[0]-i[0],n[1]-i[1])i.pair===e&&Math.abs(i.ux*s-i.uy*o)<=1e-6&&Math.abs((t[0]-i.origin[0])*i.uy-(t[1]-i.origin[1])*i.ux)<=c&&Math.abs((t[2]-i.origin[0])*i.uy-(t[3]-i.origin[1])*i.ux)<=c);h||(h={pair:e,origin:[t[0],t[1]],ux:o,uy:s,ranges:[]},l.push(h));const d=(t[0]-h.origin[0])*h.ux+(t[1]-h.origin[1])*h.uy,u=(t[2]-h.origin[0])*h.ux+(t[3]-h.origin[1])*h.uy;h.ranges.push({lo:Math.min(d,u),hi:Math.max(d,u)})}const h=[];for(const e of l){e.ranges.sort((e,t)=>e.lo-t.lo||e.hi-t.hi);const t=[];for(const i of e.ranges){const e=t[t.length-1];e&&i.lo<=e.hi+a?e.hi=Math.max(e.hi,i.hi):t.push({...i})}for(const n of t){const t=[e.origin[0]+e.ux*n.lo,e.origin[1]+e.uy*n.lo],r=[e.origin[0]+e.ux*n.hi,e.origin[1]+e.uy*n.hi];Math.hypot(r[0]-t[0],r[1]-t[1])>=a&&h.push(M_(t,r,i))}}return h}(s,e,i,n).map(e=>R_(e,i));if(!r)return[];const a=[],l=(e,t)=>(e.open_to||[]).includes(t.id)||(t.open_to||[]).includes(e.id);for(let e=0;er)&&Yo([o[0],o[1]],[o[2],o[3]],i))return!0;return!1}const P_=e=>Array.isArray(e)&&e.length>=2&&Number.isFinite(Number(e[0]))&&Number.isFinite(Number(e[1])),F_=(e,t,i)=>[Number(e[0])*i,Number(e[1])*i,Number(t[0])*i,Number(t[1])*i],z_=e=>{const t=`${Number(e[0]).toFixed(9)},${Number(e[1]).toFixed(9)}`,i=`${Number(e[2]).toFixed(9)},${Number(e[3]).toFixed(9)}`;return t<=i?`${t}|${i}`:`${i}|${t}`},I_=e=>{const t=new Map;for(const i of e.flat())!Array.isArray(i)||i.length<4||!i.every(Number.isFinite)||Math.hypot(i[2]-i[0],i[3]-i[1])<=1e-9||t.set(z_(i),[...i]);return[...t.values()]};function O_(e){return"solid"===e?.zero_wall_style?"solid":"dashed"}function E_(e,t=1,i){const n=[];for(const r of Array.isArray(e?.wall_segments)?e.wall_segments:[])0===Number(r?.cm)&&P_(r?.a)&&P_(r?.b)&&(i&&!i.has(String(r.id||""))||n.push(F_(r.a,r.b,t)));return I_([n])}function N_(e,t=1){const i=[];for(const n of Array.isArray(e?.partitions)?e.partitions:[])0===Number(n?.cm)&&P_(n?.a)&&P_(n?.b)&&i.push(F_(n.a,n.b,t));return I_([i])}function H_(e,t,i,n){if(!e)return[];const r=T_(e.open_spans);return D_(t,r.length?r:null,i,n,!0)}function L_(e,t,i,n){const r=O_(e),o=new Set;for(const e of t.rooms||[])for(const t of Array.isArray(e.wall_ids)?e.wall_ids:[])"string"==typeof t&&t&&o.add(t);const s=I_([E_(t,1,o.size?o:void 0),H_(e,t.rooms,i,n)]),a=I_([s,N_(t,1)]);return{style:r,lines:a,contour:s,barriers:"solid"===r?a:[],transmissive:"dashed"===r?s:[]}}function B_(e,t){return(e||[]).some(e=>e?.host?.kind===t.kind&&e.host.id===t.id)}function q_(e){return e instanceof Error?e.name||"Error":typeof e}function j_(e){return hc({id:e?.id??"",cell_cm:e?.cell_cm,rooms:e?.rooms||[],walls:e?.walls||[],wall_segments:e?.wall_segments||[],open_spans:e?.open_spans||[],openings:e?.openings||[],partitions:e?.partitions||[],wall_columns:e?.wall_columns||[]})}function W_(e,t,i={}){const n=(Array.isArray(e?.spaces)?e.spaces:[]).find(e=>String(e?.id||"")===String(t||"")),r=j_(n);if(!n)return{spaceId:String(t||""),displayName:"",status:"failed",reason:"prepare-exception",fingerprint:r,ok:!1};const o=Z_({...e,spaces:[n]},{...i,fingerprint:()=>r}).spaces[0]||{spaceId:String(t||""),displayName:"",status:"failed",reason:"prepare-exception"};return{...o,fingerprint:r,ok:"failed"!==o.status}}function U_(e,t,i=il,n=1e3){return D_(t.rooms,e?.open_spans,n,.02*i)}function G_(e,t,i,n=il,r=1e3){return(Array.isArray(e?.openings)?e.openings:[]).flatMap(e=>{const o={...e,rx:Number(e.x)*r,ry:Number(e.y)*r,rlen:Number(e.length)*r};if(!e.host||"wall"===e.host.kind)return[o];const s=Qu(e,t.partitions,r,i,n);return s.resolved?[{...e,rx:s.resolved.center[0],ry:s.resolved.center[1],rlen:s.resolved.length,angle:s.resolved.angle,partitionHost:s.resolved}]:[]})}function V_(e,t=()=>!0){return e.flatMap(e=>e.host&&e.partitionHost&&t(e)?[ip(e.partitionHost)]:[])}function K_(e,t,i,n,r,o,s=il,a=1e3){const l=Ps(t.rooms,[...i],n,r,o,s,a);return e.flatMap(e=>{const t={x:e.rx,y:e.ry,angle:Number(e.angle)||0,length:e.rlen};return e.host&&"wall"!==e.host.kind?e.partitionHost&&op(e.partitionHost,l,2e-4*s)?[t]:[]:[t]})}function Y_(e,t){const i=nl,n=il,r=Ga,o=Number.isFinite(Number(t.cellCm))&&Number(t.cellCm)>0?Number(t.cellCm):5,s=Array.isArray(e?.walls)?e.walls:[],a=U_(e,t,n,r),l=function(e,t,i=il){if(!t.length)return[];const n=e.filter(e=>e?.id),r=.02*i,o=[];for(let e=0;e{const t=[(e[0]+e[2])/2,(e[1]+e[3])/2];return h.some(e=>Un(t,e)<4*r)}).map(e=>[...e]);d.length&&o.push({a:s,b:a,segs:d})}return o}(t.rooms,a,n).flatMap(e=>e.segs),c=G_(e,t,o,n,r),h=V_(c),d=Ca(t,o,n,2e-4*n,h).all;return{space:t,walls:s,openCuts:l,openings:c,roomOpenings:K_(c,t,s,l,i,o,n,r),partitionCuts:h,physicalBodies:d,wallKeyPitch:i,cellCm:o,gridPitch:n,coordScale:r}}function X_(e,t,i){const n="string"==typeof e?.title?e.title.trim():"",r=null==e?.id?"":String(e.id).trim();return{spaceId:r,displayName:n||r||i(t+1)}}function Z_(e,t={}){const i=(t.fingerprint||hc)(e),n=Array.isArray(e?.spaces)?e.spaces:[],r=t.fallbackSpaceName||(e=>`Space ${e}`),o=t.prepareSpace||Y_,s=t.wallPass||ea,a=t.floorPass||Xs,l=[];for(let i=0;i0||d.physicalBodies.length>0;if(!d.space.rooms.length&&!u){l.push({...h,status:"not-applicable"});continue}let p=null;if(u){try{p=s(d.space.rooms,d.walls,d.openCuts,d.roomOpenings,d.wallKeyPitch,d.cellCm,d.gridPitch,d.coordScale,d.physicalBodies)}catch(e){l.push({...h,status:"failed",reason:"wall-exception",detail:q_(e)});continue}if(null==p){l.push({...h,status:"failed",reason:"wall-null"});continue}if("degraded-extra"===p.status){l.push({...h,status:"failed",reason:"wall-degraded-extra"});continue}if("failed-core"===p.status){l.push({...h,status:"failed",reason:"wall-failed-core"});continue}t.captureWallGeometry?.(d,p)}if(d.space.rooms.length&&null==p?.paperGeom){let e;try{e=a(d.space.rooms,d.walls,d.openCuts,d.wallKeyPitch,d.cellCm,d.gridPitch,d.coordScale)}catch(e){l.push({...h,status:"failed",reason:"floor-exception",detail:q_(e)});continue}if(null==e){l.push({...h,status:"failed",reason:"floor-null"});continue}}l.push({...h,status:"ok"})}const c=l.filter(e=>"failed"===e.status);return{fingerprint:i,spaces:l,failures:c,ok:0===c.length}}const J_=e=>"string"==typeof e&&e.length>0&&e.length<=500;function Q_(e){return J_(e)&&(e.startsWith("device:")||e.startsWith("entity:"))&&e.indexOf(":")0||null===e.area&&"string"==typeof e.space&&e.space.length>0&&"string"==typeof e.room_id&&e.room_id.length>0)}(i)||i&&i.binding!==t?null:"entity"!==e.bindingKind||i?t:null}function nm(e,t){return e.rooms.filter(e=>{const i=function(e){if(Array.isArray(e.poly)&&e.poly.length>=3)return e.poly;const{x:t,y:i,w:n,h:r}=e;return![t,i,n,r].every(Number.isFinite)||Number(n)<=0||Number(r)<=0?null:[[t,i],[t+n,i],[t+n,i+r],[t,i+r]]}(e);return!!i&&yi(t,i)})}function rm(e,t){return{id:e,binding:null,area:null,relocate:!1,updateSnapshot:!1,removeSnapshot:!1,reason:t}}function om(e){const t=e.indexOf(":");return[e.slice(0,t),e.slice(t+1)]}function sm(e){const t=[],i=new Set;if(!e.authoritative)return{decisions:t,relocateIds:i};const n=em(e.snapshot);for(const i of e.cleanupSnapshotIds||[])n[i]&&t.push({...rm(i,"registry-unverified"),removeSnapshot:!0});const r=Number.isFinite(e.coordinateScale)&&Number(e.coordinateScale)>0?Number(e.coordinateScale):1e3,o=new Map;for(const t of e.model)for(const e of t.rooms){if(!e.area)continue;const i=o.get(e.area)||[];i.push({space:t,room:e}),o.set(e.area,i)}for(const s of e.devices){const a=n[s.id],l=im(s);if(!l){a&&t.push({...rm(s.id,"registry-unverified"),removeSnapshot:!0});continue}const c=J_(s.area)?s.area:null;if(!c){t.push({id:s.id,binding:l,area:null,relocate:!1,updateSnapshot:!1,removeSnapshot:!1,reason:"registry-unverified"});continue}const h=o.get(c);if(!h||1!==h.length){t.push({id:s.id,binding:l,area:c,relocate:!1,updateSnapshot:!1,removeSnapshot:!1,reason:"target-unresolved"});continue}if(a?.binding===l){const e=a.area!==c;e&&i.add(s.id),t.push({id:s.id,binding:l,area:c,relocate:e,updateSnapshot:e,removeSnapshot:!1,reason:e?"area-changed":"unchanged"});continue}const d=e.layout[s.id];if(!d){t.push({id:s.id,binding:l,area:c,relocate:!1,updateSnapshot:!0,removeSnapshot:!1,reason:"new-without-layout"});continue}const[{space:u,room:p}]=h;if(d.s&&d.s!==u.id){i.add(s.id),t.push({id:s.id,binding:l,area:c,relocate:!0,updateSnapshot:!0,removeSnapshot:!1,reason:"backfill-cross-space"});continue}if(d.s!==u.id||!Number.isFinite(d.x)||!Number.isFinite(d.y)){t.push({id:s.id,binding:l,area:c,relocate:!1,updateSnapshot:!0,removeSnapshot:!1,reason:"backfill-ambiguous"});continue}const _=nm(u,[d.x*r,d.y*r]),m=1===_.length?_[0]:null,g=m===p||!!m?.id&&!!p.id&&m.id===p.id,f=!!m?.area&&m.area!==c,v=!g&&f;v&&i.add(s.id),t.push({id:s.id,binding:l,area:c,relocate:v,updateSnapshot:!0,removeSnapshot:!1,reason:v?"backfill-stale-room":g?"backfill-same-room":"backfill-ambiguous"})}return{decisions:t,relocateIds:i}}const am=1,lm=/^[0-9a-f]{64}$/,cm=new WeakMap;function hm(e){const t=new Set;for(const i of e?.spaces||[])for(const e of i?.decor||[])"image"===e?.kind&&lm.test(e.asset_id)&&t.add(e.asset_id);return[...t]}function dm(e,t,i){const n=Number(e.x)*t,r=Number(e.y)*i,o=Number(e.w)*t,s=Number(e.h)*i;if(![n,r,o,s].every(Number.isFinite)||o<=0||s<=0)return null;const a=n+o/2,l=r+s/2,c=Cr(e.angle);return[n,r,o,s,Rr(e.opacity,1),`translate(${a} ${l}) rotate(${c}) scale(${e.flip_h?-1:1} ${e.flip_v?-1:1}) translate(${-a} ${-l})`]}function um(e){const t=new Map,i=e?.assets;if(!Array.isArray(i))return t;for(const e of i){const i=e,n="image/png"===i.mime?"png":"image/jpeg"===i.mime?"jpg":"image/webp"===i.mime?"webp":"image/svg+xml"===i.mime?"svg":"",r=`/api/houseplan/content/assets/_/${i.asset_id}.${n}`;!lm.test(String(i.asset_id||""))||i.url!==r||"string"!=typeof i.name||!Number.isFinite(i.bytes)||Number(i.bytes)<1||!Number.isFinite(i.width)||!Number.isFinite(i.height)||Number(i.width)<=0||Number(i.height)<=0||t.set(i.asset_id,i)}return t}async function pm(e,t,i){const n=[...new Set(t.filter(e=>lm.test(e)))].sort(),r=e.connection||e,o=JSON.stringify([i,n]),s=cm.get(r);if(s?.[0]===o)return s[1];const a=new Map;for(let t=0;t0&&t>0?e/t:1;let n=100,r=n/i;return r>200&&(r=200,n=r*i),{w:n,h:r}}const mm=1e-5;function gm(e){const t=e.map(()=>[]);for(let i=0;i=1-1e-9||u<=1e-9||u>=1-1e-9||(t[i].push(d),t[s].push(u))}}const i=[];for(let n=0;ne-t),1];for(let e=1;e{const i=t[2]-t[0],n=t[3]-t[1],r=i*i+n*n;if(!(r>0))return Math.hypot(e[0]-t[0],e[1]-t[1]);const o=Math.max(0,Math.min(1,((e[0]-t[0])*i+(e[1]-t[1])*n)/r));return Math.hypot(e[0]-(t[0]+o*i),e[1]-(t[1]+o*n))},ym=(e,t,i,n)=>{const r=n[2]-n[0],o=n[3]-n[1],s=t*o-i*r;if(Math.abs(s)<1e-12)return 1/0;const a=n[0]-e[0],l=n[1]-e[1],c=(a*o-l*r)/s;if(!(c>1e-9))return 1/0;const h=(a*i-l*t)/s;return h<-1e-9||h>1+1e-9?1/0:c};const bm=[[0,1],[45,.88],[70,.62],[86,.32],[100,0]];function wm(){return{clipCache:new Map,geometryWarnings:new Set,featherUnits:null,renderedSources:new Map,lastAppearance:new Map,enteringSources:new Set,enterRafs:new Map,fadeTimers:new Map,featherSuspendUntil:0,featherResumeTimer:0,sourceSeq:0}}function km(e,t){if(!e.clipCache.has(t))return{hit:!1,value:null};const i=e.clipCache.get(t)??null;return e.clipCache.delete(t),e.clipCache.set(t,i),{hit:!0,value:i}}function xm(e,t,i,n=256){for(e.clipCache.delete(t),e.clipCache.set(t,i);e.clipCache.size>n;){const t=e.clipCache.keys().next().value;if(void 0===t)break;e.clipCache.delete(t)}}function Sm(e){const t=Nd(e.hass,e.devices,null,e.virtualLights).filter(t=>t.device.space===e.spaceId),i=new Map;for(const e of t){if(!e.device.id)continue;const t=i.get(e.device.id)||[];t.push(e),i.set(e.device.id,t)}const n=[];for(const t of e.devices){if(!t.id||t.space!==e.spaceId)continue;const r=Hd(i.get(t.id)||[]);if(!r)continue;const o=Cn(r.passive?{state:r.on?"on":"off",attributes:{}}:e.hass.states[r.eid],t.marker?.glow_color,e.defaultColor),s=Number(t.marker?.glow_radius_cm),a=Number.isFinite(s)&&s>0?s/e.cellCm*e.gridPitch:e.defaultRadiusUnits;n.push({key:`${e.spaceId}|${t.id}`,sourceEid:r.eid,pos:e.position(t),radius:a,appearance:o?{c:o.c,alpha:Tn(o.bri,e.paletteAlpha)}:null})}return n}function $m(e){const t=hc([e.rawSpaceConfig,e.cellCm,e.gridPitch]),i=e.space.rooms.flatMap(e=>{const t=ni(e);return t?[{room:e,poly:t}]:[]}),n=Math.max(10/e.cellCm*e.gridPitch,.5*e.gridPitch),r=e=>i.some(({poly:t})=>mi(e,t)),o=e.openings.flatMap(t=>{if("door"!==(i=String(t.type))&&"gate"!==i&&"passage"!==i)return[];var i;const o=t.angle*Math.PI/180,s=-Math.sin(o),a=Math.cos(o);return r([t.rx+s*n,t.ry+a*n])&&r([t.rx-s*n,t.ry-a*n])?[{opening:t,amount:hi(e.openingAmount(t))}]:[]});return{geometryFingerprint:t,fingerprint:hc([t,o.map(({opening:e,amount:t})=>({id:e.id,type:e.type,contact:e.contact,amount:t})).filter(e=>!!e.contact&&("door"===e.type||"gate"===e.type)).map(e=>{const t=Math.max(0,Math.min(1,Number(e.amount)||0));return`${e.id}:${t.toFixed(3)}`}).sort().join("|")]),polygons:i,passageStates:o}}function Mm(e){const{revision:t}=e,i=`${e.space.id}|${t.fingerprint}`,n=[...e.zeroWalls.transmissive],r=K_(t.passageStates.filter(({amount:e})=>e>0).map(({opening:e,amount:t})=>({...e,rlen:di(e.rlen,t)})),e.space,[...e.walls],e.zeroWalls.contour,e.wallKeyPitch,e.cellCm,e.gridPitch,e.coordScale);for(const e of r){const t=e.angle*Math.PI/180,i=Math.cos(t)*e.length/2,r=Math.sin(t)*e.length/2;n.push([e.x-i,e.y-r,e.x+i,e.y+r])}const o=t.passageStates.flatMap(({opening:e,amount:t})=>t>0&&e.partitionHost?[$a(ip(e.partitionHost),t)]:[]),s=e.physicalBodies(o,i),a=[],l=e.sharedWallGeometry?.sourceFingerprint,c=(e.sharedWallGeometry&&l===t.geometryFingerprint?function(e,t=[],i=[],n={}){if("failed-core"===e.status||"not-applicable"===e.status)return null;const r=e.roomComponents?.length?e.roomComponents:Ls(e.roomGeom)?[{id:"room-primary",geom:e.roomGeom}]:[];let o=r[0]?.geom||null;const s=r.slice(1).map(e=>({...e}));try{for(const i of t){if(!(i.length>0&&e.openingIndex))continue;const t=ca(e.openingIndex,i,!0);if(!t.negative&&!t.positive)continue;const n=i.angle*Math.PI/180,r=Math.cos(n),a=Math.sin(n),l=-a,c=r,h=i.length/2,d=e.openingPadUnits??1.25*Math.max(e.depthUnits,1),u=Hs([[i.x-r*h-l*d,i.y-a*h-c*d],[i.x+r*h-l*d,i.y+a*h-c*d],[i.x+r*h+l*d,i.y+a*h+c*d],[i.x-r*h+l*d,i.y-a*h+c*d]]);o&&(o=Gt(o,u));for(const e of s)e.geom=Gt(e.geom,u)}const r=[...s];let a=s.length;const l=n.mergeExtra||((e,t)=>e?Wt(e,t):t);for(let e=0;ee.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]))||Math.abs(Ci(t))<=1e-9){a++;continue}const n=[Hs(t)];try{const t=l(o,n,e);if(!Ls(t))throw new Error("invalid extra union");o=t}catch{a++,Ls(n)&&r.push({id:`policy-extra-${e}`,geom:n})}}r.sort((e,t)=>Zs(e.geom).localeCompare(Zs(t.geom)));const c=o||[];return{status:a?"degraded-extra":"ok",geom:c,components:[...Ls(c)?[{id:"primary",geom:c}]:[],...r.map((e,t)=>({...e,id:`isolated-${t}`}))]}}catch{return null}}(e.sharedWallGeometry,r,s):null)||(e.walls.length||s.length?ea(e.space.rooms,[...e.walls],e.zeroWalls.contour,r,e.wallKeyPitch,e.cellCm,e.gridPitch,e.coordScale,s):null);if(!c||"ok"!==c.status&&"degraded-extra"!==c.status)for(const e of s)a.push(...fm(e));else for(const e of c.components)for(const t of Ia(e.geom))a.push(...fm(t));const h=.02*e.gridPitch;for(const{poly:e}of t.polygons){const t=n.length?Fn(e,n,h):fm(e);for(const e of t)a.push(e)}for(const t of e.zeroWalls.barriers)a.push(t);return{occluders:gm(a),floor:t.polygons.map(({poly:e})=>e),fingerprint:t.fingerprint,masonryGeometry:!c||"ok"!==c.status&&"degraded-extra"!==c.status?[]:c.components.flatMap(e=>e.geom),opaqueBodies:s}}function Rm(e){const t=function(e,t,i,n=96){if(!(t>0&&Number.isFinite(e[0])&&Number.isFinite(e[1])))return[];const r=[];for(const n of i){if(!n||n.length<4)continue;if(![n[0],n[1],n[2],n[3]].every(Number.isFinite))continue;const i=vm(e,n);if(i<1e-7)return[];i>t||r.push(n)}const o=[],s=Math.max(12,Math.round(n));for(let e=0;ee-t);const l=[];let c=Number.NEGATIVE_INFINITY;for(const i of o){if(i-c<1e-9)continue;c=i;const n=Math.cos(i),o=Math.sin(i);let s=t;for(const t of r){const i=ym(e,n,o,t);i=3?l:[]}([e.source.x,e.source.y],e.radius,e.scene.occluders,96);return{lit:t.length>=3?Pa([t],e.scene.floor,{onBoundsFailure:({boundIndex:t,phase:i})=>{const n=e.polygons[t]?.room;e.onBoundsFailure?.(n?.id||`#${t}`,i)}}):[]}}function Cm(e,t){return i=[e.x,e.y],n=t.masonryGeometry,r=t.opaqueBodies,Na(i,n)||r.some(e=>Ea(i,e));var i,n,r}function Tm(e,t){if(t.reducedMotion())return;const i=t.window();e.featherSuspendUntil=Math.max(e.featherSuspendUntil,Date.now()+500),i.clearTimeout(e.featherResumeTimer);const n=()=>{e.featherResumeTimer=0,Date.now(){e.enterRafs.get(i)===n&&(e.enterRafs.delete(i),e.enteringSources.delete(i),t.isConnected()&&t.requestUpdate())});e.enterRafs.set(i,n)}return{domId:o,entering:e.enteringSources.has(i),leaving:!1}}if(null==o)return null;const s=e.enterRafs.get(i);if(null!=s&&r.cancelAnimationFrame(s),e.enterRafs.delete(i),e.enteringSources.delete(i),!e.fadeTimers.has(i)){Tm(e,t);const n=r.setTimeout(()=>{e.fadeTimers.get(i)===n&&(e.fadeTimers.delete(i),e.renderedSources.delete(i),e.lastAppearance.delete(i),t.isConnected()&&t.requestUpdate())},534);e.fadeTimers.set(i,n)}return{domId:o,entering:!1,leaving:!0}}function Am(e,t,i){const n=t.window(),r=e.fadeTimers.get(i),o=e.enterRafs.get(i);null!=r&&n.clearTimeout(r),null!=o&&n.cancelAnimationFrame(o),e.fadeTimers.delete(i),e.enterRafs.delete(i),e.enteringSources.delete(i),e.renderedSources.delete(i),e.lastAppearance.delete(i)}function Pm(e,t,i){const n=`${i}|`;for(const i of[...e.renderedSources.keys()])i.startsWith(n)&&Am(e,t,i)}function Fm(e,t,i,n){const r=`${i}|`;for(const i of[...e.renderedSources.keys()])i.startsWith(r)&&!n.has(i)&&Am(e,t,i)}function zm(e,t){const i=t.window();for(const t of e.fadeTimers.values())i.clearTimeout(t);for(const t of e.enterRafs.values())i.cancelAnimationFrame(t);i.clearTimeout(e.featherResumeTimer),e.clipCache.clear(),e.geometryWarnings.clear(),e.fadeTimers.clear(),e.enterRafs.clear(),e.enteringSources.clear(),e.renderedSources.clear(),e.lastAppearance.clear(),e.featherUnits=null,e.featherSuspendUntil=0,e.featherResumeTimer=0,e.sourceSeq=0}function Im(e,t,i,n,r){const o=`${t}|${i}|${n}`;if(!e.geometryWarnings.has(o)){if(e.geometryWarnings.size>=128){const t=e.geometryWarnings.values().next().value;t&&e.geometryWarnings.delete(t)}e.geometryWarnings.add(o),console.warn(`HOUSEPLAN GLOW GEOMETRY FALLBACK: #218, space ${t}, room ${n}, phase ${r}`)}}function Om(e,t,i){const n=1/(t>0?t:1),r=i&&Date.now()>=e.featherSuspendUntil;return(null==e.featherUnits||r)&&(e.featherUnits=n),{feather:e.featherUnits??n,enabled:r}}function Em(e){if(!e.spots.length)return W``;const t=4*e.feather,i=e.spots.reduce((e,i)=>({x:Math.min(e.x,i.pos.x-i.r-t),y:Math.min(e.y,i.pos.y-i.r-t),maxX:Math.max(e.maxX,i.pos.x+i.r+t),maxY:Math.max(e.maxY,i.pos.y+i.r+t),w:0,h:0}),{x:1/0,y:1/0,maxX:-1/0,maxY:-1/0,w:0,h:0});i.w=i.maxX-i.x,i.h=i.maxY-i.y;const n=e.enabledClip?.length?e.enabledClip:null;return W` + ${Te(e.spots,e=>e.key,e=>{const t=e.domId;return W` + + ${bm.map(([t,i])=>W` + `)} + + ${e.geometry?W` + + + `:G}`})} + ${n?W`${n.map(e=>W` + `)} + `:G} + + + + + `}const Nm=new WeakMap,Hm=new WeakMap,Lm=new WeakMap,Bm=new WeakMap;function qm(e,t){const i=e.get(t);return void 0!==i&&(e.delete(t),e.set(t,i)),i}function jm(e,t,i,n){for(e.delete(t),e.set(t,i);e.size>n;)e.delete(e.keys().next().value)}function Wm(e){const t=Ja(e.cfg),i={};for(const t of e.cfg.spaces||[])for(const e of t.rooms||[])e.area&&(i[e.area]=t.id);const n=cu(e.cfg.settings),r=Ee(e.cfg.settings?.icon_rules?.length?e.cfg.settings.icon_rules:Oe);return nu({hass:e.hass,registry:e.registry,areaToSpace:i,markers:e.cfg.markers||[],settings:e.cfg.settings||{},excluded:n,showAll:!!e.cfg.settings?.show_all,firstSpaceId:t[0]?.id||"",loc:t=>Sp(e.lang,t),iconRules:r})}function Um(e){const t=Ja(e.cfg),i=t.find(t=>t.id===e.spaceId);if(!i)return null;const n=un(e.cfg.spaces.find(t=>t.id===e.spaceId)),r=gn(e.cfg.settings),o=e.iconSize??2.5,s=o>8?2.5:o,a=S_(s),l=e.registry?ld(e.hass,e.registry):e.hass,c=e.registry?cd(e.hass,e.registry):e.hass,h=e.devices||Wm(e),d=e.areaRelocationIds||sm({devices:h,model:t,layout:e.layout,snapshot:e.cfg.settings?.marker_area_snapshot,authoritative:!0===e.registry?.authoritative,coordinateScale:Ga}).relocateIds,u=h.filter(t=>t.space===e.spaceId),p=u.filter(e=>!e.hidden),_=function(e,t,i){const n={},r=i/100*Sl(t)*1.3;for(const i of t.rooms){if(!i.area)continue;const t=e.filter(e=>e.area===i.area);if(!t.length)continue;const o=Cl(i),s=.1*Math.min(o.w,o.h),a=o.w-2*s,l=o.h-2*s,c=Math.max(1,Math.round(Math.sqrt(t.length*a/Math.max(l,1)))),h=a/c,d=l/Math.max(Math.ceil(t.length/c),1),u=t.map((e,t)=>({x:o.x+s+h*(t%c+.5),y:o.y+s+d*(Math.floor(t/c)+.5)}));Ei(u,o,r,.5*s),t.forEach((e,t)=>n[e.id]=ol(u[t]))}return n}(u,i,s),m=Ee(e.cfg.settings?.icon_rules?.length?e.cfg.settings.icon_rules:Oe),g=hu(l,m,e.cfg.markers||[],cu(e.cfg.settings)),f=t=>{const n=t.settings?.temp_source;if(n)return ou(l,n,"temp",e.cfg.markers||[]);const r=au(i.id,t);return r?g.get(r)?.temp??null:null},v=[];for(const t of p){const i=e.layout[t.id];if(i&&i.s===e.spaceId){const e=i.x*Ga,t=i.y*Ga;v.push({minX:e,minY:t,maxX:e,maxY:t})}}const y=e.cfg.spaces.find(t=>t.id===e.spaceId)||{};if(!n.hideDecor)for(const t of y.decor||[]){if("image"!==t?.kind||!e.decorAssetUrl?.(String(t.asset_id||"")))continue;const i=ml(t);i&&v.push(i)}const b=Array.isArray(y.walls)?y.walls:[],w=Number(y.cell_cm)>0?Number(y.cell_cm):5,k=L_(y,i,Ga,.02*il),x=(y.openings||[]).flatMap(e=>{if("partition"!==e.host?.kind)return[];const t=Qu(e,i.partitions,Ga,w,il).resolved;return t?[t]:[]}),S=hc({partitions:i.partitions,columns:i.wall_columns,cellCm:w,hostedOpenings:x.map(e=>({id:e.opening.id,host:e.host,length:e.length,type:e.opening.type}))}),$=function(e,t,i,n){let r=Hm.get(e);r||(r=new Map,Hm.set(e,r));const o=r.get(t);if(o?.fingerprint===i)return o.value;const s=n();return r.set(t,{fingerprint:i,value:s}),s}(e.cfg,i.id,S,()=>Ca(i,w,il,2e-4*il,x.map(ip)).all);for(const e of $){const t=e.map(e=>e[0]),i=e.map(e=>e[1]);t.length&&v.push({minX:Math.min(...t),minY:Math.min(...i),maxX:Math.max(...t),maxY:Math.max(...i)})}for(const e of k.lines)v.push({minX:Math.min(e[0],e[2]),minY:Math.min(e[1],e[3]),maxX:Math.max(e[0],e[2]),maxY:Math.max(e[1],e[3])});const M=function(e,t=1e3){const i=[];for(const[n,r]of(e||[]).entries()){if("passage"!==r?.type)continue;const e={...r,id:String(r.id||`passage-${n}`),type:"passage",rx:Number(r.x)*t,ry:Number(r.y)*t,rlen:Number(r.length)*t};[e.rx,e.ry,e.rlen,e.angle].every(Number.isFinite)&&e.rlen>0&&i.push(e)}return i}((y.openings||[]).flatMap(e=>{if(!e.host||"wall"===e.host.kind)return[e];const t=x.find(t=>t.opening.id===e.id);return t?[ap(e,t,Ga)]:[]}),Ga),R=Ps(i.rooms,b,k.contour,nl,w,il,Ga),C=x.filter(e=>op(e,R,2e-4*il)).map(e=>({x:e.center[0],y:e.center[1],angle:e.angle,length:e.length})),T=hl(e.fit),D=!!(b.length||$.length&&n.showBorders),A=D?hc(M.length?{rooms:i.rooms,walls:b,extras:$,cellCm:w,zero:k.contour,passages:M.map(e=>({x:e.rx,y:e.ry,angle:e.angle,length:e.rlen})),hostedCompositeOpenings:C}:{rooms:i.rooms,walls:b,extras:$,cellCm:w,zero:k.contour}):"",P=D?function(e,t,i,n){let r=Nm.get(e);r||(r=new Map,Nm.set(e,r));const o=r.get(t);if(o?.fingerprint===i)return o.value;const s=n();return r.set(t,{fingerprint:i,value:s}),s}(e.cfg,i.id,A,()=>{const e=ta(i.rooms,b,k.contour,[...M.filter(e=>"partition"!==e.host?.kind).map(e=>({x:e.rx,y:e.ry,angle:e.angle,length:e.rlen})),...C],nl,w,il,Ga,$);return e&&Object.defineProperty(e,"sourceFingerprint",{value:hc([y,w,il]),enumerable:!1}),e}):null;let F=kl(i,v,e.compactTopFrame?{top:0,right:.05,bottom:.05,left:.05}:.05);if("house"===T){const e=[],t=qa(2.5,w)/2,r=qa(.6,w)/2;for(const n of i.rooms){const i=_l(n);i&&e.push(pl(i,t))}if(n.showBorders)for(const t of P?.components||[]){const i=ul(t.geom);i&&e.push(pl(i,r))}if(n.showBorders)for(const t of $){const i=ul(t);i&&e.push(pl(i,r))}if(n.showBorders)for(const i of k.lines){const n={minX:Math.min(i[0],i[2]),minY:Math.min(i[1],i[3]),maxX:Math.max(i[0],i[2]),maxY:Math.max(i[1],i[3])};e.push(pl(n,t))}if(!n.hideOpenings)for(const t of x){const i=t.opening,n="gate"===i.type?!i.flip_v:!!i.flip_v,r=Pp({type:i.type,length:t.length,angle:t.angle,flipH:!!i.flip_h,flipV:!!i.flip_v,cellCm:w,gridPitch:il,face:np(t,n)},t.center);r&&e.push(r)}F=wl(e)||F}const z=[F.x,F.y,F.w,F.h],I=new Map(i.rooms.map(t=>{const i=Nn(n.fill,t),o=dn(n.tempMin,n.tempMax,t);return[t,vn(i,"lqi"===i&&t.area?du(l,u,t.area):null,"light"===i?Ld(Nd(l,u,t,e.virtualLights)):"none","temp"===i?f(t):null,o.min,o.max,r,hn(n.customFill,t))]})),O=new Map;for(const e of i.rooms)e.id&&O.set(e.id,I.get(e)||null);const E=i.rooms.filter(e=>e.area||n.showBorders||"none"!==Nn(n.fill,e)).map(e=>{let t="room "+(i.bg?"overlay":"yard"),r="";const o=Nn(n.fill,e);if(n.showBorders||"none"!==o){t+=" styled";const i=[`--room-stroke:${n.color}`,`--room-stroke-op:${n.showBorders&&!k.contour.length?n.opacity:0}`],o=I.get(e)||null;o?(t+=" filled",i.push(`--room-fill:${o.color}`,`--room-fill-op:${o.opacity.toFixed(3)}`)):i.push("--room-fill:transparent","--room-fill-op:0"),r=i.join(";")}const s=e.id||G,a=e.area||G,l=e.poly?W``:W``;return l}),N=i.rooms.filter(e=>Hn(n.glow,e)),H=N.filter(e=>{const t=I.get(e);return!t||t.opacity<=0}).map(e=>e.poly?W``:W``),L=new Map;for(const e of i.rooms)if(e.id){const t=I.get(e)||null;L.set(e.id,Hn(n.glow,e)&&(!t||t.opacity<=0)?{color:r.glow_base.c,opacity:r.glow_base.a,mode:"glow"}:null)}const B=Nd(l,p,null,e.virtualLights),q=p.map(t=>{const r=Tl(t,e.layout,e.cfg,_,i,d),o=(r.x-z[0])/z[2]*100,s=(r.y-z[1])/z[3]*100,a=n.showLqi??!1!==e.showSignal,h=e.presentations?.get(v_(t.id,a))||__(l,t,{liveStates:!1!==e.liveStates,showTemperature:!1!==e.showTemperature,showSignal:a,activityRuntime:e.activityRuntime?.get(t.id),sourceDetails:!1,lightDevices:p,lightSources:B,registryHass:c,reducedMotion:e.reducedMotion}),u=[`left:${o}%`,`top:${s}%`,...w_(h)],m=n_(h),g=i_([t.name,Sp(e.lang,`marker.state_a11y_${m}`),"none"!==h.pulse.kind?Sp(e.lang,`marker.pulse_a11y_${h.pulse.reason}`):"",h.valueFullText||h.valueText||"",Ip(h.valueBadge),null!=h.lqiText&&h.lqiBand?Sp(e.lang,`marker.lqi_a11y_${h.lqiBand}`,{value:h.lqiText}):""]);return j``}),U=n.showNames?i.rooms.filter(e=>e.name).map(t=>{const r=Dl(t,i.id,e.layout,e.cfg),o=(r.x-z[0])/z[2]*100,s=(r.y-z[1])/z[3]*100,a=Math.min(1,n.opacity+.25);return j`
${t.name}
`}):[],V=i.bg?e.displayUrl?e.displayUrl(i.bg.href):i.bg.href:"",K=(y.decor||[]).flatMap(t=>{if("image"!==t?.kind||n.hideDecor)return[];const i=e.decorAssetUrl?.(String(t.asset_id||""))||"",r=i&&e.displayUrl?e.displayUrl(i):i;if(!r)return[];const o=dm(t,Ga,Ga);if(!o)return[];const[s,a,l,c,h,d]=o;return[W`e.assetLoaded?.(i,r)} + preserveAspectRatio="none" transform=${d} pointer-events="none">`]}),Y=e.cfg.spaces.find(t=>t.id===e.spaceId)?.settings||{},X="daynight"===yr(e.cfg?.settings,Y)?sr(l,e.dayCycleNow??new Date):null,Z=pn(e.cfg?.settings,n),J=M.length&&b.length?function(e,t,i,n,r,o,s,a=1){return[r,o,s,a].every(Number.isFinite)&&o>0&&a>0&&i?.length?_a(sa(e,i,n,r,o,s,a),t):t.map(()=>null)}(i.rooms,M.map(e=>({x:e.rx,y:e.ry,angle:e.angle,length:e.rlen})),b,k.contour,nl,w,il,Ga):M.map(()=>null),Q=M.length?$_({openings:M,geometries:J,fillsByRoomId:O,idPrefix:`${i.id}-static-data`,groupClass:"opening-tunnels static-opening-tunnels",dataLayer:"data"}):G,ee=M.length?$_({openings:M,geometries:J,fillsByRoomId:L,idPrefix:`${i.id}-static-glow`,groupClass:"opening-tunnels glow-base-tunnels static-opening-tunnels",dataLayer:"glow-base"}):G,te=b.length&&P?.paperD?[{path:P.paperD}]:ri(i.rooms),ie=n.showBorders?P:null,ne=e.stageWidth&&z[2]?e.stageWidth/z[2]:1,re=Do(w),oe=!!ie&&(To(ie.depthUnits,ne)||Ao(re,ne)),se=n.color||"#607d8b";let ae=G;const le=e.glowRuntime;if(e.lightPools&&le&&N.length){const t=G_(y,i,w,il,Ga),n=$m({rawSpaceConfig:y,space:i,openings:t,cellCm:w,gridPitch:il,openingAmount:e=>{const t=e.contact?l.states?.[e.contact]:null;return ci(e.type,t?.state,!!e.invert,t?.attributes?.current_position)}}),o=function(e,t,i,n){let r=Lm.get(e);r||(r=new Map,Lm.set(e,r));let o=r.get(t);o||(o=new Map,r.set(t,o));const s=qm(o,i);if(s)return s;const a=n();return jm(o,i,a,8),a}(e.cfg,i.id,n.fingerprint,()=>Mm({space:i,revision:n,walls:b,zeroWalls:k,wallKeyPitch:nl,cellCm:w,gridPitch:il,coordScale:Ga,sharedWallGeometry:P,physicalBodies:e=>Ca(i,w,il,2e-4*il,e).all})),s=Number(e.cfg.settings.glow_radius_cm),a=Number.isFinite(s)&&s>0?s:300,c=Sm({hass:l,devices:p,virtualLights:e.virtualLights,spaceId:i.id,defaultColor:r.glow_light.c,paletteAlpha:r.glow_light.a,defaultRadiusUnits:a/w*il,cellCm:w,gridPitch:il,position:t=>Tl(t,e.layout,e.cfg,_,i,d)}),h=new Set,u=[];for(const e of c){if(h.add(e.key),Cm(e.pos,o)){Am(le.state,le.host,e.key);continue}const t=Dm(le.state,le.host,e.key,!!e.appearance);if(!t)continue;e.appearance&&le.state.lastAppearance.set(e.key,e.appearance);const r=le.state.lastAppearance.get(e.key);if(!r)continue;const s=`${i.id}|${o.fingerprint}|${e.pos.x.toFixed(4)},${e.pos.y.toFixed(4)}|${e.radius.toFixed(4)}`,a=km(le.state,s),l=a.hit?a.value:Rm({spaceId:i.id,source:e.pos,radius:e.radius,scene:o,polygons:n.polygons,onBoundsFailure:(e,t)=>Im(le.state,i.id,o.fingerprint,e,t)});a.hit||xm(le.state,s,l),u.push({key:e.key,sourceEid:e.sourceEid,domId:t.domId,entering:t.entering,leaving:t.leaving,pos:e.pos,c:r.c,alpha:r.alpha,geometry:l,r:e.radius})}if(Fm(le.state,le.host,i.id,h),u.length){const t=N.length===n.polygons.length,r=`${n.geometryFingerprint}|${i.rooms.filter(e=>!N.includes(e)).map(e=>e.id||`#${i.rooms.indexOf(e)}`).sort().join(",")}`,o=t?null:function(e,t,i,n){let r=Bm.get(e);r||(r=new Map,Bm.set(e,r));let o=r.get(t);o||(o=new Map,r.set(t,o));const s=qm(o,i);if(s)return s;const a=n();return jm(o,i,a,8),a}(e.cfg,i.id,r,()=>N.flatMap(e=>{const t=ni(e);if(!t)return[];const r=b.length&&e.id&&Ns(i.rooms,e.id,b,k.contour,nl,w,il,Ga,P?.roomGeom,P?.multiWallNodes)||t,o=r.map(e=>e[0]),s=r.map(e=>e[1]),a=[Math.min(...o),Math.min(...s),Math.max(...o),Math.max(...s)],l=$.filter(e=>{const t=e.map(e=>e[0]),i=e.map(e=>e[1]);return Math.max(...t)>=a[0]&&Math.min(...t)<=a[2]&&Math.max(...i)>=a[1]&&Math.min(...i)<=a[3]}),c=l.length?Fa(r,l):null,h=c?ka(c):"",d=Ri(r,n.polygons.filter(({room:t})=>t!==e).map(({poly:e})=>e)),u=e=>`M ${e.map(e=>`${e[0]} ${e[1]}`).join(" L ")} Z`;return[[h||u(r),...d.map(u)].join(" ")]})),s=Om(le.state,e.stageWidth&&z[2]?e.stageWidth/z[2]:1,!0);ae=Em({spots:u,enabledClip:o,feather:s.feather,featherEnabled:s.enabled,screenBlend:le.screenBlend})}}else le&&Pm(le.state,le.host,i.id);const ce=n.hideOpenings?[]:x.map(e=>{const t=e.opening,i="passage"!==t.type&&t.contact?l.states?.[t.contact]:null,n=ci(t.type,i?.state,!!t.invert,i?.attributes?.current_position),r=n>0&&!!t.contact,o="gate"===t.type?!t.flip_v:!!t.flip_v,s={type:t.type,length:e.length,angle:e.angle,amount:n,flipH:!!t.flip_h,flipV:!!t.flip_v,base:se,tone:r?"var(--hp-open)":se,cellCm:w,gridPitch:il,face:np(e,o)};return W` + ${Fp(s)} + `});return j` +
+ ${Sr(X)} + ${X&&te.length?W``:G} + + ${ie?W` + + + + `:G} + ${$r(te)} + ${V?W`e.assetLoaded?.(i.bg.href,V)} + transform=${i.bg.angle?`rotate(${i.bg.angle} ${i.bg.x+i.bg.w/2} ${i.bg.y+i.bg.h/2})`:G} + preserveAspectRatio="none" />`:G} + ${E} + ${n.showBorders&&k.contour.length?W``:G} + ${Q} + ${H.length?W``:G} + ${ee} + ${K} + ${ae} + ${ie?W` + ${ie.paths.map(e=>W` + + `)} + `:G} + ${n.showBorders&&k.lines.length?W``:G} + ${ce} + + ${""} +
${q}${U}
+
+ `}let Gm=null,Vm=null,Km=0,Ym=-1,Xm=null,Zm=[];const Jm=new Set,Qm=(e,t)=>{"function"==typeof e&&t.push(e)};function eg(){if(Gm)return Gm;try{const e=JSON.parse(localStorage.getItem("houseplan_card_cfg_v1")||"null");if(e&&e.config&&Array.isArray(e.config.spaces)){const t=e.layout||{};return{config:e.config,rev:e.rev||0,decorAssetsApi:null,summaryPanelApi:null,configFingerprint:e.config_fingerprint||hc(e.config),layout:t,layoutRev:e.layout_rev||0,layoutFingerprint:e.layout_fingerprint||hc(t),virtualLights:Lh(e.virtual_lights,e.rev||0)}}}catch{}return null}function tg(e,t=!1){if(t&&(Gm=null,Km++,Vm))return Vm.catch(()=>null).then(()=>tg(e,!1));if(Gm)return Promise.resolve(Gm);if(Vm)return Ym!==Km?Vm.catch(()=>null).then(()=>tg(e,!1)):Vm;return Ym=Km,Vm=async function(e,t){const[i,n]=await Promise.all([e.callWS({type:"houseplan/config/get"}),e.callWS({type:"houseplan/layout/get"})]),r=i?.rev??0,o=Gm?Bh(Gm.virtualLights,i?.virtual_lights,r,!!i&&"virtual_lights"in i):Lh(i?.virtual_lights,r),s={config:i?.config??null,rev:r,decorAssetsApi:1===i?.decor_assets_api?1:null,summaryPanelApi:1===i?.summary_panel_api?1:null,configFingerprint:hc(i?.config??null),layout:n?.layout??{},layoutRev:n?.rev??0,layoutFingerprint:hc(n?.layout??{}),virtualLights:o};t===Km&&(Gm=s);const a=e.connection;if(a?.subscribeEvents&&Xm!==a){for(const e of Zm)e();Zm=[],Xm=a;const e=()=>{Gm=null,Km++,Jm.forEach(e=>e())},t=[];try{if(Qm(await a.subscribeEvents(e,"houseplan_config_updated"),t),Qm(await a.subscribeEvents(e,"houseplan_layout_updated"),t),Qm(await a.subscribeEvents(e=>{if(Gm){const t=Uh(Gm.virtualLights,e?.data);if(t===Gm.virtualLights)return;Gm={...Gm,virtualLights:t}}else Km++;Jm.forEach(e=>e())},"houseplan_virtual_light_updated"),t),Xm===a)Zm=t;else for(const e of t)e()}catch{for(const e of t)e();Xm===a&&(Xm=null)}}return s}(e,Km).finally(()=>{Vm=null,Ym=-1}),Vm}const ig=3300;function ng(e,t){return{sources:e,last:Object.fromEntries(t.map(e=>[e.eid,e.state])),flashTs:0,flashKind:null,timer:0,gen:0,expiresAt:0,alarmActive:"alarm"===Oh(t).status}}function rg(e,t,i,n){n(e.timer);const r=ng(t,i);Object.assign(e,r)}function og(e,t,i,n,r){e.flashTs&&i-e.flashTs"transition"===e.activity)&&(i(e.timer),e.flashTs=0,e.flashKind=null,e.expiresAt=0);if("alarm"===Oh(t).status){e.alarmActive||(i(e.timer),e.flashTs=0,e.flashKind=null,e.expiresAt=0);for(const i of t)e.last[i.eid]=i.state;return e.alarmActive=!0,null}if(e.alarmActive){for(const i of t)e.last[i.eid]=i.state;return e.alarmActive=!1,null}let n=null;for(const i of t){const t=Eh(e.last[i.eid],i);("event"===t||!n&&t)&&(n=t),e.last[i.eid]=i.state}return n}class ag{constructor(e,t=()=>{}){this._host=e,this._onGateChange=t,this._modality="unknown",this._gate=!1,this._media=null,this._connected=!1,this._onMediaChange=()=>this._syncGate()}get modality(){return this._modality}get hoverEnabled(){return this._gate}connect(e=globalThis.window){this._connected||(this._connected=!0,this._modality="unknown",this._media="function"==typeof e?.matchMedia?e.matchMedia("(any-hover: hover) and (any-pointer: fine)"):null,this._media?.addEventListener?.("change",this._onMediaChange),this._setGate(!1))}disconnect(){this._media?.removeEventListener?.("change",this._onMediaChange),this._media=null,this._connected=!1,this._modality="unknown",this._setGate(!1)}note(e){return this._modality=function(e,t){const i="mouse"===(n=t.pointerType)||"touch"===n||"pen"===n?n:null;var n;return i?"mouse"===i&&t.sourceCapabilities?.firesTouchEvents?e:i:e}(this._modality,e),this._syncGate(),this._modality}suspend(){this._setGate(!1)}_syncGate(){var e,t;this._setGate((e=this._modality,t=!!this._media?.matches,"mouse"===e&&t))}_setGate(e){this._gate!==e&&(this._gate=e,this._host.toggleAttribute("data-pointer-hover",e),this._onGateChange(e))}}const lg=new WeakMap;const cg=(e,t,i)=>255===e[i+3]&&t.every((t,n)=>Math.abs(e[i+n]-t)<=2);async function hg(e){const t=e.defaultView;if(!t||!t.CSS?.supports?.("mix-blend-mode","screen"))return!1;const i=[128,32,16],n=[16,64,128],r=[9,19,29],o=`\n \n \n \n \n \n `,s=t.URL.createObjectURL(new Blob([o],{type:"image/svg+xml"}));try{const o=await new Promise((e,i)=>{const n=new t.Image,r=t.setTimeout(()=>i(new Error("SVG blend probe timeout")),1e3);n.onload=()=>{t.clearTimeout(r),e(n)},n.onerror=()=>{t.clearTimeout(r),i(new Error("SVG blend probe failed"))},n.src=s}),a=e.createElement("canvas");a.width=4,a.height=1;const l=a.getContext("2d",{willReadFrequently:!0});if(!l)return!1;l.drawImage(o,0,0,4,1);const c=l.getImageData(0,0,4,1).data;return cg(c,i,0)&&cg(c,function(e,t){return[0,1,2].map(i=>Math.round(255-(255-e[i])*(255-t[i])/255))}(i,n),4)&&cg(c,n,8)&&cg(c,r,12)}catch{return!1}finally{t.URL.revokeObjectURL(s)}}function dg(e){const t=lg.get(e);if(t)return t.promise;const i={promise:Promise.resolve(!1)};return i.promise=hg(e).catch(()=>!1).then(e=>(i.resolved=e,e)),lg.set(e,i),i.promise}function ug(e){return lg.get(e)?.resolved}class pg extends he{constructor(){super(...arguments),this._spaces=null,this._spacesLoading=!1}setConfig(e){this._config=e}async _loadSpaces(){if(!this._spaces&&!this._spacesLoading&&this.hass){this._spacesLoading=!0;try{const e=await this.hass.callWS({type:"houseplan/config/get"});this._spaces=(e?.config?.spaces||[]).map(e=>({value:e.id,label:e.title||e.id}))}catch{this._spaces=[]}finally{this._spacesLoading=!1}}}get _lang(){return xp(this.hass,this._config?.language)}get _schema(){const e=this._spaces||[];return[e.length?{name:"space",selector:{select:{mode:"dropdown",options:e}}}:{name:"space",selector:{text:{}}},{name:"title",selector:{text:{}}},{name:"fit",selector:{select:{mode:"dropdown",options:[{value:"content",label:Sp(this._lang,"editor.fit_content")},{value:"house",label:Sp(this._lang,"editor.fit_house")}]}}},{name:"show_button",selector:{boolean:{}}},{name:"button_label",selector:{text:{}}},{name:"button_target",selector:{text:{}}},{name:"icon_size",selector:{number:{min:1,max:6,step:.1,mode:"box"}}},{name:"show_temperature",selector:{boolean:{}}},{name:"live_states",selector:{boolean:{}}},{name:"light_pools",selector:{boolean:{}}},{name:"show_signal",selector:{boolean:{}}}]}render(){if(!this.hass||!this._config)return G;const e=up(this,fp,xp(this.hass,this._config.language));if("cold"===e)return pp();if("warm"===e)return U;this._loadSpaces();const t=this._lang,i={space:Sp(t,"editor.space"),title:Sp(t,"editor.title"),fit:Sp(t,"editor.framing"),show_button:Sp(t,"editor.show_button"),button_label:Sp(t,"editor.button_label"),button_target:Sp(t,"editor.button_target"),icon_size:Sp(t,"editor.icon_size"),show_temperature:Sp(t,"editor.show_temperature"),live_states:Sp(t,"editor.live_states"),light_pools:Sp(t,"editor.light_pools"),show_signal:Sp(t,"editor.show_signal")};return j`i[e.name]||e.name} + @value-changed=${this._valueChanged} + >`}_valueChanged(e){const t={...this._config||{},...e.detail.value};delete t.aspect_ratio;const i=new Event("config-changed",{bubbles:!0,composed:!0});i.detail={config:t},this.dispatchEvent(i)}}pg.properties={hass:{attribute:!1},_config:{state:!0},_spaces:{state:!0}},customElements.get("houseplan-space-card-editor")||customElements.define("houseplan-space-card-editor",pg);const _g=e=>{history.pushState(null,"",e),((e,t,i)=>{const n=new Event(t,{bubbles:!0,composed:!0});n.detail=i??{},e.dispatchEvent(n)})(window,"location-changed",{replace:!1})};class mg extends he{constructor(){super(...arguments),this._snap=null,this._loading=!1,this._reloadQueued=!1,this._forceReloadQueued=!1,this._reloadRetryTimer=0,this._dayCycleTimer=0,this._dayCycleClockKey="",this._stageWidth=0,this._pendingStageWidth=0,this._stageWidthRaf=0,this._haRegistryConnection=null,this._haRegistryRevision=-1,this._devices=[],this._areaRelocationIds=new Set,this._decorAssets=new Map,this._continuity=this._newContinuityController(),this._continuityHistory=[],this._continuityEpoch=0,this._continuityDataReady=!0,this._continuityPaintToken=-1,this._continuityDisposed=!1,this._renderSnapshotAt=Date.now(),this._hassSequence=0,this._connHooked=null,this._connectionWasLost=!1,this._visibleDeviceSnapshot=null,this._candidateDeviceSnapshot=null,this._stagedDeviceSnapshotToken=-1,this._capturedSnapshotSequence=-1,this._capturedSnapshotDevices=null,this._capturedSnapshotActivity="",this._capturedSnapshotVirtual="",this._activityRuntime=new Map,this._glowRuntimeState=wm(),this._glowRuntimeHost={window:()=>this.ownerDocument.defaultView||window,isConnected:()=>this.isConnected,requestUpdate:()=>this.requestUpdate(),reducedMotion:()=>this._reducedMotion},this._glowScreenBlend=!1,this._reducedMotion=!1,this._pointerModality=new ag(this),this._onMotionChange=e=>{this._reducedMotion=e.matches,this._capturedSnapshotSequence=-1,this.requestUpdate()},this._onHaRegistryUpdate=()=>{const e=rd(this.hass).revision;e!==this._haRegistryRevision&&(this._haRegistryRevision=e,this._refreshDevices(),this._capturedSnapshotSequence=-1,this.requestUpdate())},this._dayCycleTick=()=>{if(!this.isConnected||"hidden"===this.ownerDocument.visibilityState)return;const e=this._dayCycleState();if(!e)return this._dayCycleTimer&&(window.clearInterval(this._dayCycleTimer),this._dayCycleTimer=0),void(this._dayCycleClockKey="");const t=ar(e);t!==this._dayCycleClockKey&&(this._dayCycleClockKey=t,this.requestUpdate())},this._pageVisibility=e=>{if(this._continuity.visibility(e),this._dayCycleVisibility(e),"hidden"!==e.kind){if(!e.long){const e=Date.now();let t=!1;for(const i of this._activityRuntime.values())!i.flashKind||(i.expiresAt||i.flashTs+3300)>e||(i.flashTs=0,i.flashKind=null,i.expiresAt=0,t=!0);return void(t&&(this._capturedSnapshotSequence=-1,this.requestUpdate()))}Date.now()-this._renderSnapshotAt>1e3&&this._continuity.note("device-snapshot-stale"),this._continuityDataReady=!1,this._continuityPaintToken=-1,this._load(!0)}else this._pointerModality.suspend()},this._onConnLost=()=>{this._connectionWasLost=!0,this._continuityDataReady=!1,this._continuityPaintToken=-1,this._continuity.connectionLost()},this._onConnReady=()=>{!this._connectionWasLost&&this._continuity.hasCompleteFrame?this._beginContinuityCandidate("connection-ready",!1,"plan"):(this._continuityDataReady=!1,this._continuityPaintToken=-1),this._load(!0)},this._onAssetLoaded=(e,t)=>{this._signer.markLoaded(this.hass,e,t),this._continuity.note("asset-ready"),this._continuityPaintToken=-1,"steady"!==this._continuity.state&&this.requestUpdate()},this._loadedOnce=!1,this._signer=new pc(()=>this.requestUpdate()),this._retryContinuity=()=>{this._continuityDataReady=!1,this._continuityPaintToken=-1,this._continuity.retry(this._continuity.recoveryReason||"plan"),this._load(!0)},this._goToSpace=()=>{const e=(this._config?.button_target||"/plan-doma").replace(/#.*$/,"");_g(`${e}#space=${encodeURIComponent(this._config.space)}`)}}_ensureHaRegistryAuthority(){const e=this.hass?.connection||null;e&&e!==this._haRegistryConnection&&(this._haRegistryRelease?.(),this._haRegistryConnection=e,this._haRegistryRevision=-1,this._haRegistryRelease=id(this.hass,this._onHaRegistryUpdate),this._onHaRegistryUpdate())}_newContinuityController(){return new cc(()=>{this._continuityEpoch++,this.isConnected&&this.requestUpdate()})}_dayCycleState(e=new Date){const t=this._snap?.config;if(!t||!this._config)return null;const i=t.spaces?.find(e=>e.id===this._config?.space)?.settings||{};return"daynight"!==yr(t.settings,i)?null:sr(this._renderDeviceSnapshot?.hass||this.hass,e)}_syncDayCycleClock(){const e=this._dayCycleState();this._dayCycleClockKey=e?ar(e):"";const t="clock"===e?.source&&"hidden"!==this.ownerDocument.visibilityState&&this.isConnected;t&&!this._dayCycleTimer?this._dayCycleTimer=window.setInterval(this._dayCycleTick,3e4):!t&&this._dayCycleTimer&&(window.clearInterval(this._dayCycleTimer),this._dayCycleTimer=0)}_dayCycleVisibility(e){"hidden"!==e.kind?(this._dayCycleTick(),this._syncDayCycleClock()):this._dayCycleTimer&&(window.clearInterval(this._dayCycleTimer),this._dayCycleTimer=0)}_hookConnection(){const e=this.hass?.connection;e&&e!==this._connHooked&&(this._connHooked?.removeEventListener?.("ready",this._onConnReady),this._connHooked?.removeEventListener?.("disconnected",this._onConnLost),this._connHooked?.removeEventListener?.("reconnect-error",this._onConnLost),e.addEventListener?.("ready",this._onConnReady),e.addEventListener?.("disconnected",this._onConnLost),e.addEventListener?.("reconnect-error",this._onConnLost),this._connHooked=e)}static getConfigElement(){return document.createElement("houseplan-space-card-editor")}static getStubConfig(e){const t=eg();return{type:"custom:houseplan-space-card",space:Ja(t?.config||null)[0]?.id||"",show_button:!0,fit:"content",live_states:!0,show_temperature:!0,show_signal:!0,light_pools:!1}}setConfig(e){if(!e||!e.space)throw new Error('houseplan-space-card: "space" is required');this._config={show_button:!0,button_target:"/plan-doma",live_states:!0,show_temperature:!0,show_signal:!0,light_pools:!1,...e,fit:hl(e.fit)},!0!==this._config.light_pools?zm(this._glowRuntimeState,this._glowRuntimeHost):this.isConnected&&this._resolveGlowBlend(),this._snap=this._snap||eg()}connectedCallback(){var e;this._continuityDisposed&&(this._continuity=this._newContinuityController(),this._continuityDisposed=!1,this._continuityPaintToken=-1),super.connectedCallback(),this._pointerModality.connect(this.ownerDocument.defaultView),this._motionMedia=window.matchMedia?.("(prefers-reduced-motion: reduce)"),this._reducedMotion=!!this._motionMedia?.matches,this._motionMedia?.addEventListener?.("change",this._onMotionChange),this._resolveGlowBlend(),this.hass&&this._ensureHaRegistryAuthority(),this._continuityUnsub?.(),this._continuityUnsub=ac(this.ownerDocument,this._pageVisibility),this._unsub=(e=()=>{this._beginContinuityCandidate("config-event",!1),this._reloadQueued=!0,this._load()},Jm.add(e),()=>Jm.delete(e)),this._signer.start(()=>this.hass,()=>this._referenced())}disconnectedCallback(){this._pointerModality.disconnect(),this._continuityUnsub?.(),this._continuityUnsub=void 0,this._motionMedia?.removeEventListener?.("change",this._onMotionChange),this._motionMedia=void 0,this._unsub?.(),this._unsub=void 0,window.clearTimeout(this._reloadRetryTimer),this._reloadRetryTimer=0,this._dayCycleTimer&&(window.clearInterval(this._dayCycleTimer),this._dayCycleTimer=0),this._dayCycleClockKey="",this._stageObserver?.disconnect(),this._stageObserver=void 0,this._observedStage=void 0,this._stageWidthRaf&&cancelAnimationFrame(this._stageWidthRaf),this._stageWidthRaf=0,this._pendingStageWidth=0,this._signer.dispose(),this._haRegistryRelease?.(),this._haRegistryRelease=void 0,this._haRegistryConnection=null,this._connHooked?.removeEventListener?.("ready",this._onConnReady),this._connHooked?.removeEventListener?.("disconnected",this._onConnLost),this._connHooked?.removeEventListener?.("reconnect-error",this._onConnLost),this._connHooked=null;for(const e of this._activityRuntime.values())window.clearTimeout(e.timer);this._activityRuntime.clear(),zm(this._glowRuntimeState,this._glowRuntimeHost),this._continuityHistory=[...this._continuityHistory,...this._continuity.trace].slice(-80),this._continuity.dispose(),this._continuityDisposed=!0,super.disconnectedCallback()}_resolveGlowBlend(){if(!this._config?.light_pools)return;const e=ug(this.ownerDocument);void 0!==e&&(this._glowScreenBlend=e),dg(this.ownerDocument).then(e=>{e!==this._glowScreenBlend&&(this._glowScreenBlend=e,this.isConnected&&this.requestUpdate())})}willUpdate(e){e.has("hass")&&this.hass&&(this._hassSequence++,this._renderSnapshotAt=Date.now(),this._continuity.note("hass-snapshot"),this._ensureHaRegistryAuthority(),this._hookConnection()),!this.hass||this._loading||this._snap&&!e.has("hass")||this._snap&&this._loadedOnce||this._load(),(e.has("hass")||e.has("_snap")||e.has("_config")||!this._devices.length)&&this._refreshDevices(),this._captureRenderDeviceSnapshot(),this._continuity.hasCompleteFrame&&"steady"===this._continuity.state&&this._continuity.refreshCompleteFrame(this._frameFingerprint())}_stampActivity(e,t){og(e,t,Date.now(),window.clearTimeout.bind(window),e=>window.setTimeout(()=>this.requestUpdate(),e))}_syncActivity(e,t,i=this.hass){if(!1===this._config?.live_states){for(const e of this._activityRuntime.values())window.clearTimeout(e.timer);return void this._activityRuntime.clear()}const n=new Set,r=Nd(t,e,null,this._snap?.virtualLights);for(const o of e){if(o.hidden)continue;if("icon_ripple"!==Li(o.marker?.display))continue;n.add(o.id);const s=c_(t,o,e,r,i),a=s.samples,l=u_(t,o,s);let c=this._activityRuntime.get(o.id);if(!c||c.sources!==l){c&&window.clearTimeout(c.timer),c=ng(l,a),this._activityRuntime.set(o.id,c);continue}const h=sg(c,a,window.clearTimeout.bind(window));h&&this._stampActivity(c,h)}for(const[e,t]of this._activityRuntime)n.has(e)||(window.clearTimeout(t.timer),this._activityRuntime.delete(e))}_refreshDevices(){if(!this.hass||!this._snap?.config||!this._config)return;const e=rd(this.hass),t=Wm({hass:this.hass,registry:e,cfg:this._snap.config,lang:this._lang});e.authoritative&&(this._areaRelocationIds=sm({devices:t,model:Ja(this._snap.config),layout:this._snap.layout||{},snapshot:this._snap.config.settings?.marker_area_snapshot,authoritative:!0}).relocateIds),this._syncActivity(t,ld(this.hass,e),this.hass),this._devices=t}_captureRenderDeviceSnapshot(){if(!this.hass)return;const e=Date.now(),t=[...this._activityRuntime.entries()].map(([t,i])=>`${t}:${i.gen}:${i.flashTs}:`+(i.flashKind&&(i.expiresAt||i.flashTs+3300)>e?1:0)).join("|"),i=this._snap?.virtualLights?`${this._snap.virtualLights.configRev}:${this._snap.virtualLights.rev}`:"";if(this._capturedSnapshotSequence===this._hassSequence&&this._capturedSnapshotDevices===this._devices&&this._capturedSnapshotActivity===t&&this._capturedSnapshotVirtual===i)return;const n=ld(this.hass,rd(this.hass)),r=new Map,o=new Set(["sun.sun"]),s=new Set,a=new Set,l=e=>{if(!e)return;const t=e.indexOf(":");if(t<0)return void o.add(e);const i=e.slice(0,t),n=e.slice(t+1);"device"===i?s.add(n):"entity"===i&&o.add(n)},c=Ja(this._snap?.config||null).find(e=>e.id===this._config?.space);for(const e of c?.rooms||[])e.area&&a.add(e.area),l(e.settings?.temp_source),l(e.settings?.hum_source);const h=this._snap?.config?.spaces?.find(e=>e.id===this._config?.space);for(const e of h?.openings||[])for(const t of ui(e))o.add(t);const d=Nd(n,this._devices,null,this._snap?.virtualLights);for(const e of this._devices)for(const t of[!1,!0])r.set(v_(e.id,t),__(n,e,{liveStates:!1!==this._config?.live_states,showTemperature:!1!==this._config?.show_temperature,showSignal:t,activityRuntime:this._activityRuntime.get(e.id),sourceDetails:!1,lightDevices:this._devices,lightSources:d,registryHass:this.hass,reducedMotion:this._reducedMotion}));const u=f_({sourceSequence:this._hassSequence,hass:n,devices:this._devices,presentations:r,entityIds:o,deviceIds:s,areaIds:a});this._capturedSnapshotSequence=this._hassSequence,this._capturedSnapshotDevices=this._devices,this._capturedSnapshotActivity=t,this._capturedSnapshotVirtual=i,this._visibleDeviceSnapshot&&"steady"!==this._continuity.state?this._candidateDeviceSnapshot=u:(this._visibleDeviceSnapshot=u,this._candidateDeviceSnapshot=null)}get _renderDeviceSnapshot(){return this._stagedDeviceSnapshotToken===this._continuity.token?this._candidateDeviceSnapshot||this._visibleDeviceSnapshot:this._visibleDeviceSnapshot||this._candidateDeviceSnapshot}_beginContinuityCandidate(e,t,i="plan"){return this._continuityDataReady=t,this._continuityPaintToken=-1,this._stagedDeviceSnapshotToken=-1,this._continuity.beginCandidate(e,i)}_backdropRaw(){return this._snap?.config&&this._config&&Ja(this._snap.config).find(e=>e.id===this._config.space)?.bg?.href||""}_candidateBackdrop(e){return e&&this._config&&Ja(e).find(e=>e.id===this._config.space)?.bg?.href||""}_assetsReady(){const e=this._backdropRaw();return!e||this._signer.isReady(this.hass,e)}_frameFingerprint(){const e=this._snap;return dc([e?.rev||0,e?.configFingerprint||hc(e?.config),e?.layoutRev||0,e?.layoutFingerprint||hc(e?.layout),e?.virtualLights?`${e.virtualLights.configRev}:${e.virtualLights.rev}`:"",this._config?.space||"",!0===this._config?.light_pools,this._stageWidth,this.hass?.themes?.darkMode??this.hass?.themes?.default_theme??""])}_stageValid(){const e=this._observedStage;return!!e&&e.clientWidth>0&&e.clientHeight>0}_settleContinuityFrame(){if(!this._stageValid())return;if(!this._continuity.hasCompleteFrame&&"steady"===this._continuity.state){if(this._assetsReady())return this._renderSnapshotAt=Date.now(),void this._continuity.markCompleteFrame(this._frameFingerprint());this._beginContinuityCandidate("asset-wait",!0,"asset")}if(!this._continuityDataReady)return;if(!["holding","offline-stale","overlay-pending","overlay-visible","candidate-ready"].includes(this._continuity.state))return;const e=this._continuity.token;if(this._candidateDeviceSnapshot&&this._candidateDeviceSnapshot!==this._visibleDeviceSnapshot&&this._stagedDeviceSnapshotToken!==e)return this._stagedDeviceSnapshotToken=e,void this.requestUpdate();this._continuityPaintToken!==e&&(this._continuityPaintToken=e,this._continuity.candidateReady(e)&&this._continuity.commitAfterPaint(e,{updateComplete:()=>this.updateComplete,stageValid:()=>this.isConnected&&this._stageValid(),assetsReady:()=>this._assetsReady(),frameFingerprint:()=>this._frameFingerprint()}).then(t=>{t&&e===this._continuity.token?(this._renderSnapshotAt=Date.now(),this._candidateDeviceSnapshot&&(this._visibleDeviceSnapshot=this._candidateDeviceSnapshot),this._candidateDeviceSnapshot=null,this._stagedDeviceSnapshotToken=-1):e===this._continuity.token&&(this._continuityPaintToken=-1,this._stagedDeviceSnapshotToken=-1,this._candidateDeviceSnapshot=null,this.requestUpdate())}))}updated(){const e=this.renderRoot.querySelector(".hp-static-stage")||void 0;if(e!==this._observedStage)if(this._stageObserver?.disconnect(),this._observedStage=e,e){const t=()=>{const i=e.clientWidth;if(!(i<=0||Math.abs(i-this._stageWidth)<=.5)){if(this._stageWidth<=0)return this._stageWidth=i,void this.requestUpdate();this._pendingStageWidth=i,this._stageWidthRaf||(this._stageWidthRaf=requestAnimationFrame(()=>{this._stageWidthRaf=0;const e=this._pendingStageWidth;this._pendingStageWidth=0,!e||!this._observedStage||this._observedStage.clientWidth<=0||(Math.abs(this._observedStage.clientWidth-e)>.5?t():Math.abs(e-this._stageWidth)<=.5||(this._continuity.hasCompleteFrame&&this._beginContinuityCandidate("stage-resize",!0,"stage-size"),this._stageWidth=e,this.requestUpdate()))}))}};this._stageObserver=new ResizeObserver(t),this._stageObserver.observe(e),t()}else this._stageObserver=void 0;this._syncDayCycleClock(),this._settleContinuityFrame()}async _load(e=!1){if(this.hass){if(this._loading)return this._reloadQueued=!0,void(this._forceReloadQueued||=e);this._loading=!0,this._reloadQueued=!1;try{const t=await tg(this.hass,e),i=!this._snap||this._snap.configFingerprint!==t.configFingerprint,n=!this._snap||this._snap.layoutFingerprint!==t.layoutFingerprint,r=!this._snap||this._snap.virtualLights!==t.virtualLights,o=!this._snap||this._snap.decorAssetsApi!==t.decorAssetsApi;if(1!==t.decorAssetsApi&&(this._decorAssets=new Map),i&&!await this._signer.prepareImage(this.hass,this._candidateBackdrop(t.config)))return this._continuity.note("asset-failed"),window.clearTimeout(this._reloadRetryTimer),void(this._reloadRetryTimer=window.setTimeout(()=>{this._load(!0)},1e3));if(window.clearTimeout(this._reloadRetryTimer),this._reloadRetryTimer=0,(i||n)&&this._continuity.hasCompleteFrame&&"steady"===this._continuity.state&&this._beginContinuityCandidate("structural-response",!0),i||n||r||o?this._snap=t:this._snap&&(this._snap.rev=t.rev,this._snap.layoutRev=t.layoutRev),i&&this._continuity.note("config-candidate",{configRev:t.rev}),1===t.decorAssetsApi)try{this._decorAssets=await pm(this.hass,hm(t.config),t.rev)}catch{}n&&this._continuity.note("layout-candidate",{layoutRev:t.layoutRev}),r&&(this._capturedSnapshotSequence=-1),this._loadedOnce=!0,this._connectionWasLost=!1,this._continuityDataReady=!0,this._refreshDevices()}catch{}finally{if(this._loading=!1,this._continuityDataReady=!0,this.requestUpdate(),this._reloadQueued){const e=this._forceReloadQueued;this._reloadQueued=!1,this._forceReloadQueued=!1,this._load(e)}}}}get _lang(){return xp(this.hass,this._config?.language)}getCardSize(){const e=Ja(this._snap?.config||null).find(e=>e.id===this._config?.space);if(e){const t=e.vb[3]/e.vb[2];return Math.max(3,Math.round(8*t))+(!1===this._config?.show_button?0:1)}return 6}_errorCard(e){return j` +
${e}
+
`}_referenced(){const e=On(this._snap?.config);for(const t of this._decorAssets.values())e.add(t.url);return e}_renderRecoveryOverlay(){if(!this._continuity.overlayVisible&&"recovery-error"!==this._continuity.state)return G;const e="connection"===this._continuity.recoveryReason;return j`
+ + ${Sp(this._lang,e?"continuity.restore_connection":"continuity.restore_plan")} + ${"recovery-error"===this._continuity.state?j``:G} +
`}houseplanContinuityTrace(){return[...this._continuityHistory,...this._continuity.trace].slice(-80).map(e=>({...e,...e.stage?{stage:[...e.stage]}:{}}))}render(){if(!this._config||!this.hass)return G;const e=up(this,fp,xp(this.hass,this._config.language));if("cold"===e)return pp();if("warm"===e)return U;const t=this._snap?.config;if(!t)return this._errorCard(Sp(this._lang,"space_card.loading"));const i=this._config.space,n=Ja(t).find(e=>e.id===i),r=void 0!==this._config.title?this._config.title:n?.title||"",o=this._renderDeviceSnapshot,s=Um({hass:o?.hass||this.hass,cfg:t,layout:this._snap?.layout||{},spaceId:i,iconSize:this._config.icon_size,fit:this._config.fit,compactTopFrame:""===this._config.title||null===this._config.title,stageWidth:this._stageWidth,lang:this._lang,displayUrl:e=>this._signer.display(this.hass,e),decorAssetUrl:e=>this._decorAssets.get(e)?.url||"",assetLoaded:this._onAssetLoaded,registry:o?{revision:o.sourceSequence,authoritative:!1,access:"limited",entities:{...o.hass.entities},devices:{...o.hass.devices},lastSuccess:o.capturedAt}:rd(this.hass),devices:[...o?.devices||this._devices],areaRelocationIds:this._areaRelocationIds,presentations:o?.presentations,activityRuntime:this._activityRuntime,reducedMotion:this._reducedMotion,virtualLights:this._snap?.virtualLights,lightPools:!0===this._config.light_pools,glowRuntime:{state:this._glowRuntimeState,host:this._glowRuntimeHost,screenBlend:this._glowScreenBlend},liveStates:!1!==this._config.live_states,showTemperature:!1!==this._config.show_temperature,showSignal:!1!==this._config.show_signal,inert:this._continuity.overlayBlocksInteraction});if(!s)return this._errorCard(Sp(this._lang,"space_card.not_found",{id:i}));const a=!1!==this._config.show_button,l=this._config.button_label||Sp(this._lang,"space_card.button"),c=this._continuity.overlayVisible||"recovery-error"===this._continuity.state?this._continuity.recoveryReason:null;return j` + this._pointerModality.note(e)} + @pointerdown=${e=>this._pointerModality.note(e)} + @pointermove=${e=>this._pointerModality.note(e)}> + ${r?j`
${r}
`:G} +
+ ${s} + ${this._renderRecoveryOverlay()} +
+ ${a?j`
+ +
`:G} +
+ `}}mg.properties={hass:{attribute:!1},_config:{state:!0},_snap:{state:!0},_continuityEpoch:{state:!0}},mg.styles=[lp,o`.hp-static-title{font-weight:700;padding:10px 14px 6px;font-size:16px;color:var(--primary-text-color);}.hp-static-body{position:relative;}.hp-static-stage{position:relative;width:100%;container-type:inline-size;overflow:hidden;pointer-events:none;background:var(--ha-card-background,var(--card-background-color,#111));}.hp-static-stage svg{position:absolute;inset:0;width:100%;height:100%;display:block;z-index:1;}.hp-static-stage .hp-paper-outline-svg{z-index:0;overflow:visible;pointer-events:none;}.hp-paper{fill:var(--ha-card-background,var(--card-background-color,#111));stroke:none;}.wallbody-fill{fill:var(--wall-fill,#ffffff);fill-opacity:var(--wall-fill-op,1);fill-rule:evenodd;stroke:none;pointer-events:none;}.wallbody{fill:url(#hp-wall-hatch);fill-rule:evenodd;stroke:var(--room-stroke,var(--hp-muted,#607d8b));stroke-width:calc(0.6px * var(--hp-cell-visual-scale,1));pointer-events:none;}.wallbody.solid{fill:none;}.hp-static-stage .devlayer{position:absolute;inset:0;z-index:2;}.hp-static-foot{padding:8px 12px 12px;pointer-events:auto;}.hp-static-btn{width:100%;padding:9px 14px;border:none;border-radius:10px;background:var(--primary-color,#3ea6ff);color:var(--text-primary-color,#fff);font-size:14px;font-weight:600;cursor:pointer;}:host([data-pointer-hover]) .hp-static-btn:hover{filter:brightness(1.08);}.hp-static-error{padding:24px;text-align:center;color:var(--secondary-text-color,#9aa4ad);}`],customElements.get("houseplan-space-card")||customElements.define("houseplan-space-card",mg),window.customCards=window.customCards||[],window.customCards.find(e=>"houseplan-space-card"===e.type)||window.customCards.push({type:"houseplan-space-card",name:"House Plan — Space (static)",description:"Read-only live schematic of a single houseplan space, with a deep-link button.",preview:!1,documentation:"https://github.com/Matysh/houseplan-card"});const gg=o`:host{--hp-editor-tray-bg-fallback:color-mix(in srgb,var(--card-background-color,var(--hp-bg)) 94%,var(--hp-line));--hp-editor-tray-bg:color-mix(in srgb,var(--card-background-color,var(--hp-bg)) 86%,transparent);--hp-editor-tray-border:color-mix(in srgb,var(--hp-line) 82%,var(--hp-accent));--hp-editor-tray-blur:8px;--hp-editor-tray-shadow:var(--shadow-2);}.editor-secondary-host{position:absolute;inset:var(--sp-2) var(--sp-4) auto;z-index:70;display:flex;justify-content:flex-end;pointer-events:none;}.editor-secondary-host.kind-palette,.editor-secondary-host.kind-group{justify-content:flex-start;}.editor-secondary{pointer-events:none;max-width:100%;display:flex;align-items:center;gap:var(--sp-3);padding:var(--sp-3) var(--sp-4);color:var(--hp-txt);background:var(--card-background-color,var(--hp-bg));background:var(--hp-editor-tray-bg-fallback);border:1px solid var(--hp-line);border-color:var(--hp-editor-tray-border);border-radius:var(--rad-l);box-shadow:var(--hp-editor-tray-shadow);opacity:0;visibility:hidden;transform:translateY(-4px);transition:opacity 0.1s ease,transform 0.1s cubic-bezier(0.2,0.7,0.2,1),visibility 0s linear 0.1s;touch-action:auto;}.editor-secondary-host.open .editor-secondary{pointer-events:auto;opacity:1;visibility:visible;transform:translateY(0);transition-duration:0.14s,0.14s,0s;transition-delay:0s;}.editor-secondary-host.blocked .editor-secondary{pointer-events:none;}@supports ((backdrop-filter:blur(1px)) or (-webkit-backdrop-filter:blur(1px))){.editor-secondary{background:var(--hp-editor-tray-bg);-webkit-backdrop-filter:blur(var(--hp-editor-tray-blur));backdrop-filter:blur(var(--hp-editor-tray-blur));}}.editor-secondary-content,.editor-group-items{display:flex;align-items:center;gap:var(--sp-3);min-width:0;}.editor-context-label{max-width:14rem;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;padding-inline-end:var(--sp-4);border-inline-end:1px solid var(--hp-line);color:var(--hp-muted);font-size:var(--fs-s);}.editor-secondary.kind-palette{width:min(760px,100%);align-items:stretch;padding:0;overflow:hidden;}.editor-secondary.kind-palette .editor-secondary-content,.editor-secondary.kind-palette .furnpalette{width:100%;}.editor-secondary.kind-palette .furnpalette{max-height:38vh;border:0;background:transparent;}.editor-group-launcher .group-chevron{--mdc-icon-size:16px;transition:transform 0.14s ease;}.editor-group-launcher[aria-expanded="true"] .group-chevron{transform:rotate(180deg);}.editor-secondary .bdhint{font-size:var(--fs-s);color:var(--hp-muted);white-space:nowrap;overflow:hidden;text-overflow:ellipsis;}.editor-secondary .dfill{display:inline-flex;align-items:center;gap:var(--sp-2);font-size:var(--fs-s);cursor:pointer;}.editor-secondary .dfill input[type="checkbox"]{width:16px;height:16px;flex:none;margin:0;padding:0;}.editor-secondary hp-color-opacity{flex:0 0 auto;}.editor-secondary input{width:74px;background:transparent;border:1px solid var(--hp-line);color:var(--hp-txt);border-radius:var(--rad-s);padding:var(--sp-3) var(--sp-4);font-size:var(--fs-m);}.editor-secondary label,.editor-secondary .hint{color:var(--hp-muted);font-size:var(--fs-s);}.editor-secondary .drawwall{display:inline-flex;align-items:center;gap:var(--sp-3);white-space:nowrap;}.editor-secondary .drawwall input{width:4.2em;}.editor-secondary .drawwall .opl{color:var(--hp-muted);font-size:var(--fs-s);}@container (min-width:560px) and (max-width:899px){.editor-secondary-content,.editor-group-items{flex-wrap:wrap;justify-content:flex-end;}}@container (max-width:559px){.editor-secondary-host{inset-inline:var(--sp-4);}.editor-secondary{max-width:100%;}.editor-secondary-content,.editor-group-items{overflow-x:auto;scrollbar-width:thin;}.editor-secondary-content>*,.editor-group-items>*{flex:none;}.editor-context-label{display:none;}}@media (prefers-reduced-motion:reduce){.editor-secondary{transition:none;}.editor-group-launcher .group-chevron{transition:none;}}`;class fg{constructor(e=50){this._undo=[],this._redo=[],this._limit=Math.max(30,Math.floor(e))}get canUndo(){return this._undo.length>0}get canRedo(){return this._redo.length>0}get undoName(){return this._undo[this._undo.length-1]?.name??null}get redoName(){return this._redo[this._redo.length-1]?.name??null}get size(){return this._undo.length}push(e){this._undo.push(e),this._undo.length>this._limit&&this._undo.splice(0,this._undo.length-this._limit),this._redo=[]}undo(){const e=this._undo.pop()??null;return e&&this._redo.push(e),e}redo(){const e=this._redo.pop()??null;return e&&this._undo.push(e),e}removeWhere(e){const t=this._undo.length,i=this._redo.length;return this._undo=this._undo.filter(t=>!e(t)),this._redo=this._redo.filter(t=>!e(t)),t+i-this._undo.length-this._redo.length}clear(){this._undo=[],this._redo=[]}}function vg(e,t){const i=e[t];return i&&Number.isFinite(i.x)&&Number.isFinite(i.y)?{x:i.x,y:i.y,..."string"==typeof i.s?{s:i.s}:{}}:null}function yg(e,t,i){if(null===i){if(!(t in e))return e;const i={...e};return delete i[t],i}const n={...e[t]||{}};delete n.x,delete n.y,delete n.s;const r={...n,x:i.x,y:i.y,...void 0!==i.s?{s:i.s}:{}};return{...e,[t]:r}}const bg="houseplan-card:version-reload-target:v1";function wg(e){if("string"!=typeof e)return null;return e.trim()||null}class kg{constructor(e){this.hooks=e,this._input={frontendVersion:null,backendVersion:null,kiosk:!1,reducedMotion:!1},this._relation={kind:"unknown"},this._banner=null,this._connected=!1,this._attemptTarget=null,this._attemptState=null,this._noticeToken=0}get relation(){return this._relation}get banner(){return this._banner}get hasCurrentMismatchNotice(){return"mismatch"===this._relation.kind&&"visible"===this._banner?.phase}connect(){this._connected||(this._connected=!0,this._attemptTarget=null,this._attemptState=null,this._reconcile())}disconnect(){(this._connected||this._banner)&&(this._connected=!1,this._cancelTimer(),this._banner&&(this._banner=null,this.hooks.changed()))}update(e){const t={frontendVersion:wg(e.frontendVersion),backendVersion:wg(e.backendVersion),kiosk:!0===e.kiosk,reducedMotion:!0===e.reducedMotion},i=function(e,t){const i=wg(e),n=wg(t);return i&&n?i===n?{kind:"equal",frontend:i,backend:n}:{kind:"mismatch",frontend:i,backend:n}:{kind:"unknown"}}(t.frontendVersion,t.backendVersion),n=!((e,t)=>e.frontendVersion===t.frontendVersion&&e.backendVersion===t.backendVersion&&e.kiosk===t.kiosk&&e.reducedMotion===t.reducedMotion)(this._input,t)||!((e,t)=>e.kind===t.kind&&("unknown"===e.kind||"unknown"!==t.kind&&e.frontend===t.frontend&&e.backend===t.backend))(this._relation,i);this._input=t,this._relation=i,n&&this._reconcile()}finishBannerExit(e){this._banner&&"leaving"===this._banner.phase&&this._banner.token===e&&(this._banner=null,this.hooks.changed())}_reconcile(){if(this._cancelTimer(),!this._connected||"mismatch"!==this._relation.kind)return this._attemptTarget=null,this._attemptState=null,void this._hideBanner();if(!this._input.kiosk)return this._attemptTarget=null,this._attemptState=null,void this._showBanner(this._relation.frontend,this._relation.backend);const e=this._relation.backend;if(this._attemptTarget===e&&null!==this._attemptState||(this._attemptTarget=e,this._attemptState=function(e,t){try{const i=e();return i?i.getItem(bg)===t?"attempted":"fresh":"unavailable"}catch{return"unavailable"}}(this.hooks.storage,e)),"fresh"===this._attemptState)return this._hideBanner(),void this._armTimer();this._showBanner(this._relation.frontend,e)}_armTimer(){this._connected&&void 0===this._timer&&"mismatch"===this._relation.kind&&this._input.kiosk&&"fresh"===this._attemptState&&(this._timer=this.hooks.clock.setTimeout(()=>{this._timer=void 0,this._tick()},250))}_cancelTimer(){void 0!==this._timer&&(this.hooks.clock.clearTimeout(this._timer),this._timer=void 0)}_tick(){if(!this._connected||"mismatch"!==this._relation.kind||!this._input.kiosk||"fresh"!==this._attemptState)return;if(!function(e){return e.connected&&e.initialFrameSettled&&e.viewOnly&&e.surfacesIdle&&e.configWritesIdle&&e.physicalWritesIdle&&e.layoutWritesIdle&&e.gesturesIdle&&e.interactionPauseElapsed&&e.baseZoom}(this.hooks.safety()))return void this._armTimer();const e=this._relation.backend,t=function(e,t){try{const i=e();return i?i.getItem(bg)===t?"attempted":(i.setItem(bg,t),"claimed"):"unavailable"}catch{return"unavailable"}}(this.hooks.storage,e);if(this._attemptTarget=e,this._attemptState="claimed"===t?"attempted":t,"claimed"===t){this._showBanner(this._relation.frontend,e);try{this.hooks.reload()}catch{}}else this._showBanner(this._relation.frontend,e)}_showBanner(e,t){"visible"===this._banner?.phase&&this._banner.frontend===e&&this._banner.backend===t||(this._banner={frontend:e,backend:t,phase:"visible",token:++this._noticeToken},this.hooks.changed())}_hideBanner(){if(this._banner)return this._input.reducedMotion?(this._banner=null,void this.hooks.changed()):void("leaving"!==this._banner.phase&&(this._banner={...this._banner,phase:"leaving",token:++this._noticeToken},this.hooks.changed()))}}const xg=1;function Sg(e,t){const i=t&&"object"==typeof t?t:{};e._haIntegrationVersion=wg(i.integration_version);const n=i.support_api;e._haSupportApi="number"==typeof n&&Number.isSafeInteger(n)?n:null,e._haDecorAssetsApi=1===i.decor_assets_api?1:null,e._haSummaryPanelApi=1===i.summary_panel_api?1:null,e._haRadarStage1Api=1===i.radar_stage1_api?1:null,e._syncVersionRecovery()}function $g(e){const t=e._stageEl,i=e._loadOk&&!e._loading&&e._continuityDataReady&&!e._resumeSettling&&!e._connectionWasLost&&!e._booting&&!e._bootFading&&!e._bootSettling&&!e._bootSoft&&e._continuity.hasCompleteFrame&&"steady"===e._continuity.state&&!e._continuity.overlayBlocksInteraction&&!!t&&t.clientWidth>0&&t.clientHeight>0,n=!(0!==e._pointers.size||0!==e._touchContacts.size||e._touchSequenceMultitouch||e._roomPointer||e._panStart||e._panLock||e._pinchStart||e._swipeStart||e._tabDrag||e._tabDragRelease||e._drag||e._deviceDrag||e._rlResize||e._resize?.dragging||e._physicalDrag||e._physicalRotate||e._opDrag||e._decorDraft||e._decorMove||e._dtDrag||e._bdDrag||e._furnTouchPending||e._compassDrag||e._viewportGestureDirty||e._devicePositionBusy||e._modeTransitionBusy||e._cameraTransition.active||e._slide||0!==e._warmModeRequest),r=!(e._editorSecondaryDialogBlocked||e._partitionDeleteDialog||e._roomDeleteDialog||e._backdropGuard||e._vacFit||e._editorSecondary?.hasOpenGroup||e._furnPalette||e._decorImagePalette);return{connected:e.isConnected,initialFrameSettled:i,viewOnly:!0===e._config?.kiosk&&"view"===e._mode&&!e._editing,surfacesIdle:r,configWritesIdle:0===e._writesPending&&!e._saveConfigDebounced.pending(),physicalWritesIdle:0===e._pendingPhysicalWrites.size,layoutWritesIdle:!e._persistLayout.pending()&&0===e._dirtyPos.size&&0===e._sentPos.size&&!e._devicePositionBusy,gesturesIdle:n,interactionPauseElapsed:Date.now()>=e._cyclePausedUntil,baseZoom:e._zoom<=1.001}}class Mg{constructor(){this.seen=null,this.diagnosticsCache=null}observe(e,t,i,n){this.invalidateDiagnosticsForHass(e,t,i),this.intake(t,n)}intake(e,t){e&&this.seen!==e&&(this.seen=e,t())}invalidate(){this.diagnosticsCache=null}invalidateDiagnosticsForHass(e,t,i){this.diagnosticsCache&&(e?.entities!==t?.entities||e?.devices!==t?.devices||[...i?.entityIds||[]].some(i=>!!e?.states?.[i]!=!!t?.states?.[i]))&&this.invalidate()}diagnostics(e,t,i){if(this.diagnosticsCache)return this.diagnosticsCache;const n={active:0,ha_disabled:0,orphaned:0,unverified:0};for(const e of t)e.removed||"virtual"===e.binding||n[i(e.binding).kind]++;return this.diagnosticsCache={registry:pd(e),bindings:n},this.diagnosticsCache}}function Rg(e){const t=e;t._hassSequence++,t._renderSnapshotAt=Date.now(),t._continuity.note("hass-snapshot"),t._ensureHaRegistryAuthority(),t._planHassMemo=null,t._hookConnection(),!t._loadOk&&!t._loading&&t._loadTries<8&&t._loadFromServer(),t._maybeRebuildDevices(),t._vacTick(),t._activityTick()}function Cg(e){return!!e&&"object"==typeof e&&1===e.version}function Tg(e,t){const i=e.radar;return e.space===t&&!0!==e.hidden&&!0!==e.removed&&Cg(i)&&!0===i.enabled&&!1!==i.show_live}const Dg={ok:"radar.health_ok",off:"radar.health_off",stale:"radar.health_stale",partial:"radar.health_partial",restricted:"radar.health_restricted",incomplete:"radar.health_incomplete",position_unavailable:"radar.health_position_unavailable",unavailable:"radar.health_unavailable",needs_setup:"radar.health_needs_setup",inconsistent:"radar.health_inconsistent",unknown:"radar.health_unknown"};const Ag=e=>"number"==typeof e&&Number.isFinite(e);class Pg{constructor(e){this.host=e,this.frames=new Map,this.connection=null,this.space="",this.generation=0,this.expiryTimer=0,this.deadlines=new Map}sync(e,t){const i=this.host.hass?.connection;if(!t||!i||!this.host.isConnected)return void this.stop();if(this.unsubscribe&&this.connection===i&&this.space===e)return;this.stop(),this.connection=i,this.space=e;const n=++this.generation,r=i.subscribeMessage?.bind(i);"function"==typeof r&&Promise.resolve(r(e=>{if(n!==this.generation||!this.host.isConnected)return;const t=function(e){if(!e||"object"!=typeof e)return null;const t=e;if("string"!=typeof t.marker_id||"string"!=typeof t.server_session_id||!Number.isSafeInteger(t.seq)||"string"!=typeof t.health)return null;const i=Array.isArray(t.targets)?t.targets.slice(0,256).flatMap(e=>{if(!e||"object"!=typeof e)return[];const t=e;return"string"==typeof t.slot&&Ag(t.x)&&Ag(t.y)&&Ag(t.expires_at)&&Ag(t.reported_at)&&("bounded_latest"===t.pair_quality||"coherent"===t.pair_quality)?[{...t,included:!0===t.included,smooth:!0===t.smooth}]:[]}):[],n=Array.isArray(t.ranges)?t.ranges.slice(0,64).flatMap(e=>{if(!e||"object"!=typeof e)return[];const t=e;if(!("string"==typeof t.id&&Ag(t.x)&&Ag(t.y)&&Ag(t.radius)&&Ag(t.expires_at)&&Ag(t.reported_at)))return[];const i=Array.isArray(t.segments)?t.segments.slice(0,64).flatMap(e=>{if(!Array.isArray(e))return[];const t=e.slice(0,181).flatMap(e=>Array.isArray(e)&&2===e.length&&Ag(e[0])&&Ag(e[1])?[[e[0],e[1]]]:[]);return t.length>=2?[t]:[]}):void 0;return[{...t,...i?{segments:i}:{}}]}):[],r=Array.isArray(t.zones)?t.zones.slice(0,64).flatMap(e=>{if(!e||"object"!=typeof e)return[];const t=e;if("string"!=typeof t.id)return[];const i=t.state;if(null!==i&&"boolean"!=typeof i&&!Ag(i))return[];const n=Array.isArray(t.polygon)?t.polygon.slice(0,64).flatMap(e=>Array.isArray(e)&&2===e.length&&Ag(e[0])&&Ag(e[1])?[[e[0],e[1]]]:[]):[];return[{id:t.id,state:i,...n.length>=3?{polygon:n}:{}}]}):[];return{server_session_id:t.server_session_id,marker_id:t.marker_id,source_generation:"string"==typeof t.source_generation?t.source_generation:void 0,calibration_revision:"string"==typeof t.calibration_revision?t.calibration_revision:void 0,seq:t.seq,reported_at:Ag(t.reported_at)?t.reported_at:void 0,expires_at:Ag(t.expires_at)?t.expires_at:void 0,health:t.health,reported_presence:"boolean"==typeof t.reported_presence?t.reported_presence:null,complete:!0===t.complete,targets:i,ranges:n,zones:r}}(e);if(!t)return;if(!function(e,t){return!e||t.server_session_id!==e.server_session_id||t.source_generation!==e.source_generation||t.calibration_revision!==e.calibration_revision||t.seq>e.seq}(this.frames.get(t.marker_id),t))return;const i=function(e,t=Date.now()){if(!Ag(e.expires_at))return null;if(!Ag(e.reported_at))return Math.max(0,1e3*e.expires_at-t);const i=Math.max(0,1e3*(e.expires_at-e.reported_at)),n=Math.max(0,t-1e3*e.reported_at);return Math.max(0,i-n)}(t);"restricted"===t.health||"disabled"===t.health||0===i?(this.frames.delete(t.marker_id),this.deadlines.delete(t.marker_id)):(this.frames.set(t.marker_id,t),null==i?this.deadlines.delete(t.marker_id):this.deadlines.set(t.marker_id,this.monotonicNow()+i)),this.armExpiry(),this.host.requestUpdate()},{type:"houseplan/radar/subscribe",space_id:e})).then(e=>{n===this.generation&&this.host.isConnected?"function"==typeof e&&(this.unsubscribe=e):"function"==typeof e&&e()}).catch(()=>{n===this.generation&&this.stop()})}stop(){this.generation++,this.unsubscribe?.(),this.unsubscribe=void 0,this.connection=null,this.space="",clearTimeout(this.expiryTimer),this.expiryTimer=0,this.frames.size&&(this.frames.clear(),this.host.isConnected&&this.host.requestUpdate()),this.deadlines.clear()}armExpiry(){clearTimeout(this.expiryTimer);const e=this.monotonicNow(),t=[...this.deadlines.values()].filter(t=>t>e);if(!t.length)return;const i=Math.max(20,Math.min(...t)-e+10);this.expiryTimer=window.setTimeout(()=>{this.expiryTimer=0;let e=!1;const t=this.monotonicNow();for(const[i,n]of this.deadlines)n>t||(this.deadlines.delete(i),this.frames.delete(i),e=!0);this.armExpiry(),e&&this.host.isConnected&&this.host.requestUpdate()},i)}monotonicNow(){return globalThis.performance?.now?.()??Date.now()}}const Fg=Object.freeze({enabled:!1,z2mBaseTopics:Object.freeze([])});function zg(e){if("string"!=typeof e)return null;const t=e.trim().replace(/^\/+|\/+$/g,"").replace(/\/{2,}/g,"/");return!t||t.length>180||/[#+\u0000-\u001f\u007f]/.test(t)?null:t}function Ig(e){const t=e?.zigbee_topology;if(!t||"object"!=typeof t)return Fg;const i=t,n=Array.isArray(i.z2m_base_topics)?i.z2m_base_topics:Array.isArray(i.z2mBaseTopics)?i.z2mBaseTopics:[],r=new Set,o=[];for(const e of n){const t=zg(e);if(t&&!r.has(t)&&(r.add(t),o.push(t),8===o.length))break}return{enabled:!0===i.enabled,z2mBaseTopics:o}}function Og(e,t){const i={...e},n=t.z2mBaseTopics.map(zg).filter(Boolean);return t.enabled||n.length?i.zigbee_topology={enabled:!0===t.enabled,z2m_base_topics:[...new Set(n)].slice(0,8)}:delete i.zigbee_topology,i}const Eg={now:()=>performance.now(),requestFrame:e=>requestAnimationFrame(e),cancelFrame:e=>cancelAnimationFrame(e)},Ng=e=>Math.max(0,Math.min(1,e)),Hg=(e,t,i)=>e+(t-e)*i,Lg=(e,t,i)=>{const n=1-e;return 3*n*n*e*t+3*n*e*e*i+e*e*e},Bg=e=>{const t=Ng(e);if(0===t||1===t)return t;let i=0,n=1,r=t;for(let e=0;e<12;e++)r=(i+n)/2,Lg(r,.2,.2)0&&e.w>0?t/e.w:1,viewBox:{...e}}}function jg(e,t,i){const n=Math.max(1e-9,e.pixelsPerUnit),r=Math.max(1e-9,t/n),o=Math.max(1e-9,i/n);return{x:e.centerX-r/2,y:e.centerY-o/2,w:r,h:o}}function Wg(e){const t=e.trim(),i=/^rgba?\(\s*([\d.]+)[, ]+([\d.]+)[, ]+([\d.]+)(?:\s*[,/]\s*([\d.]+))?\s*\)$/i.exec(t);if(i)return[Number(i[1]),Number(i[2]),Number(i[3]),null==i[4]?1:Number(i[4])];const n=/^#([0-9a-f]{6}|[0-9a-f]{8})$/i.exec(t)?.[1];return n?[parseInt(n.slice(0,2),16),parseInt(n.slice(2,4),16),parseInt(n.slice(4,6),16),8===n.length?parseInt(n.slice(6,8),16)/255:1]:null}function Ug(e,t,i){const n=Wg(e),r=Wg(t);if(!n||!r)return i<.5?e:t;const o=Ng(i);return`rgba(${Math.round(Hg(n[0],r[0],o))}, ${Math.round(Hg(n[1],r[1],o))}, ${Math.round(Hg(n[2],r[2],o))}, ${Hg(n[3],r[3],o).toFixed(3)})`}class Gg{constructor(e,t=Eg){this._hooks=e,this._clock=t,this._token=0,this._raf=0,this._state=null}get state(){return this._state}get active(){return"running"===this._state?.phase||"preparing"===this._state?.phase}get presented(){return this._state?.presented||null}start(e,t,i,n=220){this.cancel(!1);const r=++this._token,o=this._clock.now();if(this._state={token:r,phase:n<=0?"settling":"running",from:e,to:t,presented:n<=0?t:e,startedAt:o,duration:Math.max(0,n),targetMode:i},n<=0)return this._hooks.frame(this._state),this._hooks.settled(this._state),this._state=null,r;this._hooks.frame(this._state);const s=e=>{const t=this._state;if(!t||t.token!==r)return;const i=Ng((e-t.startedAt)/t.duration);t.presented=i>=1?t.to:function(e,t,i){const n=Bg(i),r=Hg(e.stageWidth,t.stageWidth,n),o=Hg(e.stageHeight,t.stageHeight,n),s=Math.max(1e-9,e.viewport.pixelsPerUnit),a=Math.max(1e-9,t.viewport.pixelsPerUnit),l={centerX:Hg(e.viewport.centerX,t.viewport.centerX,n),centerY:Hg(e.viewport.centerY,t.viewport.centerY,n),pixelsPerUnit:Math.exp(Hg(Math.log(s),Math.log(a),n))};return{presentedMode:n<.5?e.presentedMode:t.presentedMode,editorChromeHeight:Hg(e.editorChromeHeight,t.editorChromeHeight,n),stageWidth:r,stageHeight:o,viewport:{...l,viewBox:jg(l,r,o)},stageColor:Ug(e.stageColor,t.stageColor,n),paperColor:Ug(e.paperColor,t.paperColor,n),sceneBrightness:Hg(e.sceneBrightness,t.sceneBrightness,n),architectureOpacity:Hg(e.architectureOpacity,t.architectureOpacity,n),backdropOpacity:Hg(e.backdropOpacity,t.backdropOpacity,n),viewWeight:Hg(e.viewWeight,t.viewWeight,n),editorWeight:Hg(e.editorWeight,t.editorWeight,n),toolbarContentOpacity:Hg(e.toolbarContentOpacity,t.toolbarContentOpacity,n)}}(t.from,t.to,i),t.phase=i>=1?"settling":"running",this._hooks.frame(t),i<1?this._raf=this._clock.requestFrame(s):(this._raf=0,this._hooks.settled(t),this._state?.token===r&&(this._state=null))};return this._raf=this._clock.requestFrame(s),r}cancel(e=!0){this._raf&&this._clock.cancelFrame(this._raf),this._raf=0;const t=this._state;this._state=null,this._token++,t&&e&&(t.phase="settling",t.presented=t.to,this._hooks.frame(t),this._hooks.settled(t))}dispose(){this.cancel(!1)}}const Vg={now:()=>"undefined"!=typeof performance?performance.now():Date.now(),requestFrame:e=>"function"==typeof requestAnimationFrame?requestAnimationFrame(e):null,cancelFrame:e=>{"function"==typeof cancelAnimationFrame&&cancelAnimationFrame(e)}},Kg=e=>Number.isFinite(e);function Yg(e){return!!e&&Kg(e.zoom)&&e.zoom>0&&Kg(e.viewBox.x)&&Kg(e.viewBox.y)&&Kg(e.viewBox.w)&&e.viewBox.w>0&&Kg(e.viewBox.h)&&e.viewBox.h>0}function Xg(e){return{zoom:e.zoom,viewBox:{...e.viewBox}}}function Zg(e,t){return Math.abs(e.zoom-t.zoom)<1e-9&&Math.abs(e.viewBox.x-t.viewBox.x)<1e-6&&Math.abs(e.viewBox.y-t.viewBox.y)<1e-6&&Math.abs(e.viewBox.w-t.viewBox.w)<1e-6&&Math.abs(e.viewBox.h-t.viewBox.h)<1e-6}const Jg=(e,t,i)=>e+(t-e)*i,Qg=(e,t,i)=>Math.exp(Jg(Math.log(e),Math.log(t),i));class ef{constructor(e,t=Vg){this._hooks=e,this._clock=t,this._token=0,this._raf=null,this._state=null}get state(){return this._state}get active(){return"running"===this._state?.phase}get presented(){return this._state?.presented||null}get target(){return this._state?.to||null}start(e,t,i,n){this.cancel(!1);const r=++this._token,o=Xg(e),s=Xg(t),a=n>0&&Yg(o)&&Yg(s),l=this._clock.now(),c={token:r,phase:a?"running":"settling",from:o,to:s,presented:Xg(a?o:s),startedAt:l,duration:a?n:0,reason:i};if(this._state=c,this._hooks.frame(c),!a)return this._settle(r),r;const h=e=>{const t=this._state;if(!t||t.token!==r)return;const i=Math.max(0,Math.min(1,(e-t.startedAt)/t.duration));if(t.presented=i>=1?Xg(t.to):function(e,t,i){if(!Yg(e))return Xg(t);if(!Yg(t))return Xg(e);const n=Bg(i);if(n<=0)return Xg(e);if(n>=1)return Xg(t);const r=e.viewBox.x+e.viewBox.w/2,o=e.viewBox.y+e.viewBox.h/2,s=t.viewBox.x+t.viewBox.w/2,a=t.viewBox.y+t.viewBox.h/2,l=Qg(e.viewBox.w,t.viewBox.w,n),c=Qg(e.viewBox.h,t.viewBox.h,n),h=Jg(r,s,n),d=Jg(o,a,n);return{zoom:Qg(e.zoom,t.zoom,n),viewBox:{x:h-l/2,y:d-c/2,w:l,h:c}}}(t.from,t.to,i),t.phase=i>=1?"settling":"running",this._hooks.frame(t),i>=1)return this._raf=null,void this._settle(r);this._raf=this._clock.requestFrame(h),null===this._raf&&this._settle(r)};return this._raf=this._clock.requestFrame(h),null===this._raf&&(c.phase="settling",c.presented=Xg(s),this._hooks.frame(c),this._settle(r)),r}cancel(e=!0){null!==this._raf&&this._clock.cancelFrame(this._raf),this._raf=null;const t=this._state;this._state=null,this._token++,t&&e&&(t.phase="settling",t.presented=Xg(t.to),this._hooks.frame(t),this._hooks.settled(t))}dispose(){this.cancel(!1)}_settle(e){const t=this._state;t&&t.token===e&&(t.phase="settling",t.presented=Xg(t.to),this._hooks.settled(t),this._state?.token===e&&(this._state=null))}}function tf(e,t,i){const n=e.querySelector("ha-card");if(!n)return null;const r=n.getBoundingClientRect(),o=t.getBoundingClientRect().top-r.top,s=i?0:Math.min(Math.max(r.top,0),120),a=Math.round(o+s);return a>=0?a:null}const nf=Object.freeze({rotDeg:0,tiltDeg:20,xyScale:1,zScale:1,origin:Object.freeze([500,500])}),rf=84,of=10,sf=4,af=4;function lf(e){return[e.rotDeg,e.tiltDeg,e.xyScale,e.zScale,e.origin[0],e.origin[1]].every(Number.isFinite)&&Math.abs(e.xyScale)>1e-12&&Math.abs(Math.cos(e.tiltDeg*Math.PI/180))>1e-12}function cf(e,t,i=nf){if(!Number.isFinite(e[0])||!Number.isFinite(e[1]))throw new Error("invalid isometric projection input");return function(e,t){if(!Number.isFinite(e[0])||!Number.isFinite(e[1])||!t.every(Number.isFinite))throw new Error("invalid isometric affine input");const[i,n,r,o,s,a]=t;return[i*e[0]+r*e[1]+s,n*e[0]+o*e[1]+a]}(e,df(t,i))}function hf(e,t=nf){if(!lf(t)||!Number.isFinite(e[0])||!Number.isFinite(e[1]))throw new Error("invalid isometric projection input");const i=t.rotDeg*Math.PI/180,n=t.tiltDeg*Math.PI/180,r=(e[0]-t.origin[0])/t.xyScale,o=(e[1]-t.origin[1])/(t.xyScale*Math.cos(n));return[t.origin[0]+r*Math.cos(i)+o*Math.sin(i),t.origin[1]-r*Math.sin(i)+o*Math.cos(i)]}function df(e=0,t=nf){if(!lf(t)||!Number.isFinite(e))throw new Error("invalid isometric camera");const i=t.rotDeg*Math.PI/180,n=t.tiltDeg*Math.PI/180,r=t.xyScale*Math.cos(i),o=-t.xyScale*Math.sin(i),s=t.xyScale*Math.sin(i)*Math.cos(n),a=t.xyScale*Math.cos(i)*Math.cos(n);return[r,s,o,a,t.origin[0]-r*t.origin[0]-o*t.origin[1],t.origin[1]-s*t.origin[0]-a*t.origin[1]-e*t.zScale*Math.sin(n)]}function uf(e=nf){return function(e=0,t=nf){return`matrix(${df(e,t).map(e=>Number(e.toFixed(12))).join(" ")})`}(0,e)}function pf(e,t=nf){const{rect:i,wallHeight:n}=e,r=e.openingHeight??n,o=e.floorDepth??0,s=e.raisedHeight??n;if(!(i.w>=0)||!(i.h>=0)||!Number.isFinite(n)||!Number.isFinite(r)||!Number.isFinite(o)||!Number.isFinite(s)||n<0||r<0||o<0||s<0)throw new Error("invalid isometric frame");const a=[[i.x,i.y],[i.x+i.w,i.y],[i.x+i.w,i.y+i.h],[i.x,i.y+i.h]],l=Math.max(n,r,s),c=a.flatMap(e=>[cf(e,-o,t),cf(e,l,t)]),h=c.map(e=>e[0]),d=c.map(e=>e[1]),u=Math.min(...h),p=Math.min(...d);return{x:u,y:p,w:Math.max(...h)-u,h:Math.max(...d)-p}}const _f=[".dev",".vacpuck",".oplock",".op-hit",".opening",".rlgo","a","button","input","select","textarea",'[contenteditable]:not([contenteditable="false"])',"[data-room-fit-block]",'[role="link"]','[role="button"]'].join(","),mf=(e,t)=>{try{return"function"==typeof e?.matches&&e.matches(t)}catch{return!1}};function gf(e){for(const t of e){const e=t;if(mf(e,".roomlabel[data-id]")){const t=e.getAttribute?.("data-id");return t?{kind:"room",roomId:t}:{kind:"interactive"}}if(mf(e,_f))return{kind:"interactive"};if(mf(e,'[data-hp="room"][data-id]')){const t=e.getAttribute?.("data-id");return t?{kind:"room",roomId:t}:{kind:"interactive"}}if(mf(e,".stage"))return{kind:"background"}}return{kind:"outside"}}function ff(e){const t=gf(e);return"room"===t.kind?t.roomId:null}class vf{constructor(){this.pointer=null,this.sequence=null}clear(){this.pointer=null,this.sequence=null}clearOutside(e){let t={kind:"outside"};try{t=gf(e.composedPath())}catch{}"outside"===t.kind&&this.clear()}pointerDown(e,t,i){let n={kind:"outside"};try{n=gf(e.composedPath())}catch{}this.pointer=function(e){const t="mouse"===(i=e.pointerType)||"touch"===i||"pen"===i?i:null;var i;return t&&"view"===e.mode&&"background"===e.owner.kind&&!e.blocked&&e.isPrimary&&0===e.button&&Number.isFinite(e.x)&&Number.isFinite(e.y)?{pointerId:e.pointerId,spaceId:e.spaceId,modality:t,x:e.x,y:e.y}:null}({pointerId:e.pointerId,pointerType:e.pointerType,isPrimary:e.isPrimary,button:e.button,spaceId:t,mode:i?"view":"blocked",owner:n,blocked:!i,x:e.clientX,y:e.clientY}),this.pointer||(this.sequence=null)}pointerUp(e,t,i,n,r=Date.now()){let o={kind:"outside"};try{o=gf(e.composedPath())}catch{}const s=function(e,t,i){if(!t||"view"!==i.mode||"background"!==i.owner.kind||i.blocked||t.pointerId!==i.pointerId||t.spaceId!==i.spaceId||!Number.isFinite(i.x)||!Number.isFinite(i.y)||!Number.isFinite(i.now)||Math.abs(i.x-t.x)+Math.abs(i.y-t.y)>=8)return{sequence:null,trigger:!1};const n=e?i.now-e.at:Number.POSITIVE_INFINITY;return e&&e.spaceId===i.spaceId&&e.modality===t.modality&&n>=0&&n<=350?{sequence:null,trigger:!0}:{sequence:{at:i.now,spaceId:i.spaceId,modality:t.modality},trigger:!1}}(this.sequence,this.pointer,{pointerId:e.pointerId,spaceId:t,mode:i?"view":"blocked",owner:o,blocked:n||!i,x:e.clientX,y:e.clientY,now:r});return this.pointer=null,this.sequence=s.sequence,s.trigger}}const yf=e=>e.length>=2&&Number.isFinite(e[0])&&Number.isFinite(e[1]);function bf(e){return!!e&&Number.isFinite(e.x)&&Number.isFinite(e.y)&&Number.isFinite(e.w)&&e.w>0&&Number.isFinite(e.h)&&e.h>0}function wf(e,t=0){if(!e.length||!Number.isFinite(t)||t<0||!e.every(yf))return null;let i=1/0,n=1/0,r=-1/0,o=-1/0;for(const t of e)i=Math.min(i,t[0]),n=Math.min(n,t[1]),r=Math.max(r,t[0]),o=Math.max(o,t[1]);const s=r-i,a=o-n;return s>0&&a>0?{x:i-t,y:n-t,w:s+2*t,h:a+2*t}:null}function kf(e,t,i){const n="string"!=typeof t||"invalid"!==t&&"no-borders"!==t&&"unverified"!==t&&!/^[a-z0-9]{1,8}$/i.test(t)?"redacted":t;return Object.freeze({kind:e,fingerprint:n,terminal:!!i})}function xf(e,t){return`${e("editor.load_failed")} ${e(t.terminal?"editor.refresh_advice":"editor.retry_advice")}`}class Sf extends Error{}class $f{constructor(e){this.options=e,this._state="idle",this._inFlight=null}get state(){return this._state}ensure(){return"ready"===this._state?Promise.resolve(!0):"failed"===this._state?Promise.resolve(!1):(this._inFlight||(this._setState("loading"),this._inFlight=this._loadWithRetry().finally(()=>{this._inFlight=null})),this._inFlight)}async _loadWithRetry(){let e=new Error("Editor runtime did not load"),t=!1;for(const i of[0,1])try{const e=await this.options.load(i);if(e.fingerprint!==this.options.expectedFingerprint)throw new Sf(`Editor runtime fingerprint mismatch: expected ${this.options.expectedFingerprint}, got ${e.fingerprint}`);const t=e.create();return this.options.install(t),this._setState("ready"),!0}catch(i){e=i,i instanceof Sf&&(t=!0)}return this._setState(t?"failed":"idle"),this.options.failed?.(e,{terminal:t}),!1}_setState(e){e!==this._state&&(this._state=e,this.options.stateChanged?.(e))}}const Mf=(e,t)=>{if(!e.has(t))return{hit:!1};const i=e.get(t);return e.delete(t),e.set(t,i),{hit:!0,value:i}},Rf=(e,t,i,n)=>{for(e.delete(t),e.set(t,i);e.size>n;){const t=e.keys().next().value;if(void 0===t)break;e.delete(t)}},Cf=new Set(["select","draw","column","merge","split","resize","opening","wallthick","delroom"]),Tf=e=>`${window.innerWidth}x${window.innerHeight}|${location.pathname}|${JSON.stringify(e??{})}`,Df="houseplan_card_alpha_v1",Af=Object.freeze([Object.freeze({id:"iso",issue:89,summary:"Volumetric plan renderer"})]);function Pf(e){return/^[a-z][a-z0-9-]*$/.test(e.id)&&Number.isInteger(e.issue)&&e.issue>0&&!!e.summary.trim()}function Ff(e){const t=String(e||"").replace(/^#/,"");return new URLSearchParams(t)}function zf(e){return Ff(e).get("space")||""}function If(e,t,i=Af){const n=function(e){const t=new Set;for(const i of e){if(!Pf(i)||t.has(i.id))return!1;t.add(i.id)}return!0}(i),r=function(e){let t,i=!1;const n=e=>{for(const n of e.getAll("hp_alpha"))i=!0,"1"===n?t=!0:"0"===n&&(t=!1)};return n(new URLSearchParams(String(e.search||"").replace(/^\?/,""))),n(Ff(e.hash)),{present:i,value:t}}(e),o=void 0!==r.value,s="1"===t,a=o?!0===r.value:!r.present&&s,l=n&&a;return{alpha:l,active:Object.freeze(l?i.map(e=>e.id).sort():[]),space:zf(e.hash),persist:n&&o?l?"1":"0":void 0,knownUrlOperation:o}}let Of={alpha:!1,active:Object.freeze([]),space:""},Ef=!1,Nf="";const Hf=new Set;function Lf(){if("undefined"==typeof window)return Of;const e=If(window.location,function(){try{return window.localStorage.getItem(Df)}catch{return null}}());void 0!==e.persist&&function(e){try{window.localStorage.setItem(Df,e)}catch{}}(e.persist),Of={alpha:e.alpha,active:e.active,space:e.space},window.__hpAlpha=e.alpha,window.__hpLabs=e.active;for(const e of Hf)e(Of);return Of}function Bf(){Lf()}function qf(){if("undefined"==typeof window)return Of;if(!Ef){Ef=!0,window.__hpLabsListenerCleanup?.(),window.addEventListener("hashchange",Bf),window.addEventListener("popstate",Bf);const e=()=>{window.removeEventListener("hashchange",Bf),window.removeEventListener("popstate",Bf),window.__hpLabsListenerCleanup===e&&delete window.__hpLabsListenerCleanup};window.__hpLabsListenerCleanup=e}return Lf()}const jf={window:120,door:90,passage:90,gate:300};function Wf(e){return jf[e]}function Uf(e,t){return{type:e,lengthCm:Wf(e),flipH:!1,flipV:!1,revision:t}}function Gf(e,t){const i=Math.max(0,e.renderedLength)/2,n=Math.max(0,e.target.physicalHalfWidth),r=n+.18*Math.max(0,t),o=e=>({x1:e,y1:-r,x2:e,y2:r});return{rect:{x:-i,y:n?-n:0,width:2*i,height:2*n},boundaries:[o(-i),o(i)]}}function Vf(e,t){const i=[e[0],e[1]],n=[t[0],t[1]];return function(e,t){return e[0]-t[0]||e[1]-t[1]}(i,n)<=0?{a:i,b:n}:{a:n,b:i}}function Kf(e){const t=new Map;return e.forEach((e,i)=>{if(!e.kind||e.open)return;const n=Vf(e.a,e.b);if(Math.hypot(n.b[0]-n.a[0],n.b[1]-n.a[1])<=1e-9)return;const r=function(e,t){const i=e=>(Math.abs(e)<=5e-10?0:Math.round(1e6*e)/1e6).toFixed(6);return`${i(e[0])},${i(e[1])}>${i(t[0])},${i(t[1])}`}(n.a,n.b),o=t.get(r);if(o)return o.physicalHalfWidth=Math.max(o.physicalHalfWidth,e.half||0),o.sourceOrder=Math.min(o.sourceOrder,i),void(e.partitionHost&&(o.partitionHost&&o.partitionHost.id!==e.partitionHost.id?o.ambiguousPartitionHost=!0:o.partitionHost=e.partitionHost));t.set(r,{segmentKey:r,a:n.a,b:n.b,physicalHalfWidth:Math.max(0,e.half||0),sourceOrder:i,...e.partitionHost?{partitionHost:e.partitionHost}:{}})}),[...t.values()]}function Yf(e,t){if(Math.abs(e.distance-t.distance)>1e-9)return e.distance-t.distance;if(Math.abs(e.perpendicular-t.perpendicular)>1e-9)return e.perpendicular-t.perpendicular;return(e.target.segmentKeyt.target.segmentKey?1:0)||e.target.sourceOrder-t.target.sourceOrder}function Xf(e){const t=Kf(e.intervals).map(t=>{const i=function(e,t){const i=t.b[0]-t.a[0],n=t.b[1]-t.a[1],r=Math.hypot(i,n),o=i/r,s=n/r,a=(e[0]-t.a[0])*o+(e[1]-t.a[1])*s,l=Math.max(0,Math.min(r,a)),c=t.a[0]+l*o,h=t.a[1]+l*s;return{along:l,length:r,x:c,y:h,distance:Math.hypot(e[0]-c,e[1]-h),perpendicular:Math.abs((e[0]-t.a[0])*s-(e[1]-t.a[1])*o)}}(e.pointer,t);return{target:t,...i,envelope:Math.max(e.baseTolerance,t.physicalHalfWidth+e.bodyPointerPadding)}}).filter(e=>e.distance<=e.envelope+1e-9).filter(t=>!function(e,t,i,n,r){const o=t.b[0]-t.a[0],s=t.b[1]-t.a[1],a=Math.hypot(o,s);if(!(a>1e-9))return!1;const l=o/a,c=s/a;for(const o of i){if(!o.open&&o.kind)continue;const i=Vf(o.a,o.b),s=i.b[0]-i.a[0],a=i.b[1]-i.a[1],h=Math.hypot(s,a);if(!(h>1e-9))continue;const d=s/h,u=a/h;if(Math.abs(l*u-c*d)>1e-6)continue;if(Math.abs((i.a[0]-t.a[0])*c-(i.a[1]-t.a[1])*l)>r)continue;const p=(e[0]-i.a[0])*d+(e[1]-i.a[1])*u,_=1e-9;if(!(p<=_||p>=h-_)&&Math.abs((e[0]-i.a[0])*u-(e[1]-i.a[1])*d)<=n+1e-9)return!0}return!1}(e.pointer,t.target,e.intervals,t.envelope,Math.max(1e-9,Math.min(e.baseTolerance,.04*e.gridStep)))),i=t.filter(t=>!!t.target.partitionHost&&e.renderedLength+2*t.target.physicalHalfWidth>t.length+1e-9).sort(Yf),n=t.filter(t=>!t.target.partitionHost||e.renderedLength+2*t.target.physicalHalfWidth<=t.length+1e-9).sort(Yf);let r=n[0];if(!r)return{candidate:null,jambBlockedTarget:i[0]?.target||null};const o=n.filter(e=>Math.abs(e.distance-r.distance)<=1e-9&&Math.abs(e.perpendicular-r.perpendicular)<=1e-9),s=o.filter(e=>e.target.partitionHost);if(s.length){if(1!==new Set(s.map(e=>e.target.partitionHost.id)).size||s.some(e=>e.target.ambiguousPartitionHost))return{candidate:null,jambBlockedTarget:null};const e=s[0],t=e.target.b[0]-e.target.a[0],i=e.target.b[1]-e.target.a[1],n=Math.hypot(t,i),a=t/n,l=i/n;if(!o.every(t=>{const i=t.target.b[0]-t.target.a[0],n=t.target.b[1]-t.target.a[1],r=Math.hypot(i,n),o=i/r,s=n/r,c=Math.abs(a*s-l*o)<=1e-6,h=Math.abs((t.target.a[0]-e.target.a[0])*l-(t.target.a[1]-e.target.a[1])*a);return c&&h<=1e-9}))return{candidate:null,jambBlockedTarget:null};r=e}if(r.target.ambiguousPartitionHost)return{candidate:null,jambBlockedTarget:null};const{target:a,length:l}=r,c=a.b[0]-a.a[0],h=a.b[1]-a.a[1],d=c/l,u=h/l,p=a.partitionHost?a.physicalHalfWidth:0,_=Math.min(Math.max(0,e.renderedLength)/2+p,l/2);let m=r.along;const g=Math.max(e.gridStep,1e-9),f=l/2;m=Math.abs(m-f)<=g/2?f:Math.round(m/g)*g,m=Math.max(_,Math.min(l-_,m));const v=a.a[0]+d*m,y=a.a[1]+u*m,b=Math.max(0,e.renderedLength)/2,w=m-b,k=m+b,x=Math.max(0,w),S=Math.max(0,l-k),$=[a.a[0]+d*(w-x/2),a.a[1]+u*(w-x/2)],M=[a.a[0]+d*(k+S/2),a.a[1]+u*(k+S/2)];let R=180*Math.atan2(h,c)/Math.PI;R>=90?R-=180:R<-90&&(R+=180);const C=Math.abs(m-f)<=1e-9;return{candidate:{presetRevision:e.preset.revision,geometryRevision:e.geometryRevision,pointer:[e.pointer[0],e.pointer[1]],type:e.preset.type,lengthCm:e.preset.lengthCm,flipH:e.preset.flipH,flipV:e.preset.flipV,x:v,y:y,angle:R,renderedLength:e.renderedLength,target:a,...a.partitionHost?{host:{...a.partitionHost,t:l>0?m/l:0}}:{},measure:{labels:[{distance:x,midpoint:$},{distance:S,midpoint:M}],guide:C?{x:v,y:y,angle:R}:null}},jambBlockedTarget:null}}function Zf(e,t,i,n,r=1e-6){return e.presetRevision===i&&e.geometryRevision===n&&Math.hypot(e.pointer[0]-t[0],e.pointer[1]-t[1])<=r}function Jf(e){return!(!e.canEdit||e.kiosk||e.fixedFloor)&&("view"!==e.mode&&("mouse"===e.pointerType&&e.spaceCount>1))}class Qf{constructor(e,t,i){this.loader=e,this.host=t,this.adopted=i,this.attachment=null}connect(){if(this.runtime)return void this.runtime.connect();this.attachment?.cancel();const e=this.loader.attach(this.host,e=>this.adopt(e));this.runtime||(this.attachment=e)}disconnect(){this.attachment?.cancel(),this.attachment=null,this.runtime?.disconnect()}adopt(e){this.attachment=null,this.runtime||(this.runtime=e,this.adopted(e))}}const ev=new class{constructor(e){this.load=e,this.factory=null,this.pending=null}get warm(){return null!==this.factory}create(e){return this.factory?this.factory(e):null}attach(e,t){let i=!0;const n={cancel:()=>{i=!1}},r=this.create(e);return r?(t(r),n):(this.ensure().then(n=>{i&&t(n(e))},()=>{}),n)}ensure(){return this.factory?Promise.resolve(this.factory):(this.pending||(this.pending=this.load().then(e=>(this.factory=e,this.pending=null,e),e=>{throw this.pending=null,e})),this.pending)}reset(){this.factory=null,this.pending=null}}(()=>import("./summary-panel-runtime-loaded-BbGQ8VLD.js").then(function(e){return e.e}).then(({LoadedSummaryPanelRuntime:e})=>t=>new e(t)));function tv(e){const t=globalThis.__HP_VERSION_OVERRIDE__;return"string"==typeof t&&t.length>0?t:e}let iv=0;const nv="1.76.0-beta.4",rv="3f783ed7cf5daff202a910aa89044f88f605a65af7f46794277dddf04333e502",ov=1500,sv=new Map;let av=0,lv=1e4;const cv="houseplan_card_layout_v1",hv="houseplan_card_cfg_v1",dv="houseplan_card_zoom_v1",uv="houseplan_card_nav_v1",pv="houseplan_card_view_v1",_v="hp-dialog, hp-help, hp-color-opacity, hp-device-preview",mv=1e3,gv=(e,t)=>{const i=Math.min(e.x,t.x),n=Math.min(e.y,t.y);return{x:i,y:n,w:Math.max(e.x+e.w,t.x+t.w)-i,h:Math.max(e.y+e.h,t.y+t.h)-n}},fv=(e,t,i)=>{const n=new Event(t,{bubbles:!0,composed:!0});n.detail=i??{},e.dispatchEvent(n)},vv=e=>{history.pushState(null,"",e),fv(window,"location-changed",{replace:!1})},yv=(e,t)=>{let i,n=null;const r=(...r)=>{clearTimeout(i),n=r,i=window.setTimeout(()=>{i=void 0;const t=n;n=null,t&&e(...t)},t)};return r.flush=()=>{if(void 0===i)return;clearTimeout(i),i=void 0;const t=n;n=null,t&&e(...t)},r.cancel=()=>{clearTimeout(i),i=void 0,n=null},r.pending=()=>void 0!==i,r},bv=e=>{try{e.target?.setPointerCapture?.(e.pointerId)}catch{}},wv=["edges","corners"];class kv extends he{constructor(){var e;super(...arguments),this._editorRuntime=null,this._liveRt=null,this._onboardingRuntime=null,this._editorRuntimeLoadingVisible=!1,this._backdropGuard=null,this._editorModeRequest=0,this._warmModeRequest=0,this._editorRuntimeLoader=new $f({expectedFingerprint:rv,load:async e=>{const t=0===e?await import("./houseplan-editor-runtime-CCYvnxhV.js"):await import((()=>{const e=new URL("./houseplan-editor-runtime-CCYvnxhV.js",import.meta.url);return e.searchParams.set("hp_retry",`${nv}-${++iv}`),e.href})());return{fingerprint:t.EDITOR_RUNTIME_FINGERPRINT,create:()=>new t.HouseplanEditorRuntime(this)}},install:e=>{this._editorRuntime=e},stateChanged:e=>this._editorRuntimeStateChanged(e),failed:(e,t)=>{console.error("[houseplan] unable to load editor runtime",e),t.terminal&&this._versionRecovery.hasCurrentMismatchNotice||this._showToast(xf(e=>this._t(e),t))}}),this._onboardingRuntimeLoader=new $f({expectedFingerprint:rv,load:async e=>{const t=0===e?await import("./houseplan-onboarding-runtime-BNfzBq5J.js"):await import((()=>{const e=new URL("./houseplan-onboarding-runtime-BNfzBq5J.js",import.meta.url);return e.searchParams.set("hp_retry",`${nv}-${++iv}`),e.href})());return{fingerprint:t.ONBOARDING_RUNTIME_FINGERPRINT,create:()=>new t.HouseplanOnboardingRuntime(this)}},install:e=>{this._onboardingRuntime=e},failed:(e,t)=>{console.error("[houseplan] unable to load onboarding runtime",e),t.terminal&&this._versionRecovery.hasCurrentMismatchNotice||this._showToast(xf(e=>this._t(e),t))}}),this._isoSceneRuntime=null,this._isoSceneRuntimeLoader=new $f({expectedFingerprint:rv,load:async e=>{const t=0===e?await import("./iso-scene-render-RpNlnxJ0.js"):await import((()=>{const e=new URL("./iso-scene-render-RpNlnxJ0.js",import.meta.url);return e.searchParams.set("hp_retry",`${nv}-${++iv}`),e.href})());return{fingerprint:t.ISO_SCENE_RUNTIME_FINGERPRINT,create:()=>t}},install:e=>{const t=this._effectiveProjection();this._isoSceneRuntime=e,this._isoProjectionSnapshot=null;const i=this._effectiveProjection();this._convertProjectionView(t,i),this.isConnected&&this.requestUpdate()},failed:(e,t)=>{console.warn("[houseplan] hidden isometric runtime diagnostic",kf("runtime-load","unverified",t.terminal)),this.isConnected&&this.requestUpdate()}}),this._pdfRuntime=null,this._pdfRuntimeLoader=new $f({expectedFingerprint:rv,load:async e=>{const t=0===e?await import("./pdf-export-CfU6W3j-.js"):await import((()=>{const e=new URL("./pdf-export-CfU6W3j-.js",import.meta.url);return e.searchParams.set("hp_retry",`${nv}-${++iv}`),e.href})());return{fingerprint:t.PDF_EXPORT_FINGERPRINT,create:()=>new t.PdfExportRuntime}},install:e=>{this._pdfRuntime=e,this.isConnected&&this.requestUpdate()},failed:(e,t)=>{if(console.error("[houseplan] unable to load PDF export runtime",e),!t.terminal||!this._versionRecovery.hasCurrentMismatchNotice){const e=xf(e=>this._t(e),t),i=this._t("editor.load_failed"),n=e.startsWith(i)?e.slice(i.length).trim():e;this._showToast(`${this._t("pdf.failed")} ${n}`.trim())}}}),this.panelHost=!1,this.narrow=null,this._space="f1",this._adoption=new ju((e,t)=>this.requestUpdate(e,t)),this._serverStorage=!1,this._loadOk=!1,this._serverCanWrite=null,this._loading=!1,this._loadTries=0,this._unsubCfg=null,this._unsubLayout=null,this._unsubVirtual=null,this._liveSyncAttempt=null,this._liveSyncGeneration=0,this._liveSyncConnection=null,this._configReloadAuthority=new Vu,this._virtualLights=Lh(null),this._canOptimizeUndo=!1,this._undoKind=null,this._devices=[],this._regSignature="",this._defPos={},this._newSyncKey="",this._areaRelocationIds=new Set,this._areaSnapshotCleanupCandidates=new Map,this._areaRelocationSyncKey="",this._areaRelocationWrite=Promise.resolve(),this._tip=null,this._hoverRoom=null,this._pointerModality=new ag(this,()=>this._syncPointerHoverTargets()),this._devicePressAnimations=new Map,this._selId=null,this._toast="",this._mode="view",this._pendingNavMode=null,this._decorTool="select",this._decorStyle={...Mr},this._decorStyleSeeded=!1,this._decorDraft=null,this._decorMove=null,this._decorSel=null,this._decorEraseConfirm=null,this._decorTextDialog=null,this._decorShapeDialog=null,this._backdropDialog=null,this._decorTextSelection={start:0,end:0},this._furnPalette=null,this._decorImagePalette=null,this._decorAssetCatalog=[],this._decorAssets=new Map,this._decorAssetBusy=!1,this._furnCategory=null,this._furnPreviewInput=null,this._furnTouchPending=null,this._dtBox=null,this._dtDrag=null,this._bdDrag=null,this._slide="",this._reducedMotion=!1,this._onMotionChange=e=>{this._reducedMotion=e.matches,this._cancelDevicePressFeedback(),e.matches&&this._cancelCameraTransition(!0),e.matches&&this._modeTransitionPreparing?this._modeTransitionForceAtomic=!0:e.matches&&this._modeTransition.active&&this._cancelModeTransition(!0),this._syncVersionRecovery(),this.requestUpdate()},this._editorChromeMode="plan",this._modeTransitionVisual=null,this._modeTransitionPreparing=!1,this._modeTransitionForceAtomic=!1,this._modeTransitionRequest=0,this._modeTransitionTargetZoom=1,this._modeTransitionEditorCamera=null,this._modeTransition=new Gg({frame:e=>this._applyModeTransitionFrame(e),settled:e=>this._settleModeTransition(e)}),this._cameraTransitionFit=null,this._cameraTransition=new ef({frame:e=>this._applyCameraTransitionFrame(e),settled:e=>this._settleCameraTransition(e)}),this._editorSecondaryCopy={groupActive:(e,t)=>this._t("editor.group_active",{group:e,item:t}),openGroup:e=>this._t("editor.open_group",{group:e}),disabledAction:(e,t)=>this._t("editor.disabled_action",{action:e,reason:t})},this._tool="draw",this._geometryHistory=new fg(50),this._devicePositionHistory=new fg(50),this._devicePositionBusy=!1,this._wallDialog=null,this._drawWallField=null,this._activeWallChainId=null,this._activeWallChainPartitionIds=[],this._wallChainRedo=[],this._physicalSel=null,this._physicalDialog=null,this._partitionDeleteDialog=null,this._roomDeleteDialog=null,this._physicalDrag=null,this._physicalRotate=null,this._physicalLastTap=null,this._physicalPickCycle=null,this._wallUnionCacheValue=null,this._wallUnionPool=new Map,this._isoGeometryCache=new Map,this._renderIsoScene=null,this._isoProjectionSnapshot=null,this._isoStructuralBuildCount=0,this._isoFallback=new Set,this._openingTunnelCache=null,this._openingWallIndexCache=new Map,this._openingPlacementIntervalsCache=null,this._openingDimensionContextCache=null,this._planSnapGeometryCache=null,this._planStructuralGeometryCache=null,this._hiddenWallDiagnosticCache=null,this._physicalBodiesCache=null,this._lightPhysicalBodiesCache=null,this._cleanFloorCache=new Map,this._innerContourCache=new Map,this._glowRuntimeState=wm(),this._glowRuntimeHost={window:()=>this.ownerDocument.defaultView||window,isConnected:()=>this.isConnected,requestUpdate:()=>this.requestUpdate(),reducedMotion:()=>this._reducedMotion},this._lightBarrierCache=null,this._lightBarrierPool=new Map,this._glowScreenBlend=!1,this._duplicateColumnId=null,this._duplicateColumnTimer=0,this._rszLimitViolation=null,this._path=[],this._cursorPt=null,this._planSnapHover=null,this._mergeSel=null,this._openingPreset=null,this._openingRebindId=null,this._openingPresetRevision=0,this._openingHoverCandidate=null,this._openingJambBlockCm=null,this._openingDialog=null,this._openingInfo=null,this._opDrag=null,this._opMeasure=null,this._mergeDialog=null,this._splitSel=null,this._pendingSplit=null,this._wallFaceBatch=null,this._wallRepairDiagnostic=null,this._wallFaceGraphCache=[],this._areaSel="",this._nameSel="",this._roomDialog=!1,this._roomEditId=null,this._roomFill="",this._roomCustomFill=null,this._roomTempMin="",this._roomTempMax="",this._roomTempSrc="",this._roomHumSrc="",this._roomSrcOpen=null,this._roomSrcFilter="",this._roomNameScale=1,this._roomLabelScale=1,this._zoom=1,this._view=null,this._zoomBySpace={},this._viewModeSnap=null,this._roomFocus=null,this._roomPointer=null,this._doubleFit=new vf,this._deviceHits=new kc,this._pointers=new Map,this._panStart=null,this._panLock=null,this._pinchStart=null,this._suppressClick=!1,this._viewportGestureDirty=!1,this._touchContacts=new Map,this._touchClickGuard=new _c,this._connectedPath="",this._routeDepartureHandled=!1,this._onLocationChanged=()=>{this._connectedPath&&location.pathname!==this._connectedPath?this._leaveCardRoute():location.pathname===this._connectedPath&&(this._routeDepartureHandled=!1)},this._touchGestureGuard={capture:!0,handleEvent:e=>this._guardTouchGesture(e)},this._hdrH=118,this._booting=!0,this._bootFading=!1,this._bootSettling=!1,this._bootSettleRaf=0,this._bootLastH=-1,this._bootStart=0,this._bootLastChange=0,this._bootSoft=!1,this._tapConfirm=null,this._dangerConfirm=null,this._dangerConfirmController=new ze(e=>{this._dangerConfirm=e}),this._confirmDanger=e=>this._config&&this.hass?"warm"===this._syncDangerConfirmLocaleGate()||this._dangerConfirmMissingSpace()?Promise.resolve(!1):this._dangerConfirmController.confirm(e):Promise.resolve(!1),this._cancelDangerConfirm=()=>{this._dangerConfirmController.cancel()},this._onDangerConfirmDecision=e=>{this._dangerConfirmController.resolve(e.detail.token,e.detail.accepted)},this._onboardingShown=!1,this._rulesDialog=null,this._preflightClipboardFallback=null,this._haIntegrationVersion=null,this._versionRecovery=(e=this,new kg({clock:{setTimeout:(e,t)=>window.setTimeout(e,t),clearTimeout:e=>window.clearTimeout(e)},storage:()=>e.ownerDocument.defaultView?.sessionStorage??null,safety:()=>$g(e),reload:()=>e._reloadDocument(),changed:()=>{e.requestUpdate()}})),this._haSupportApi=null,this._haDecorAssetsApi=null,this._haSummaryPanelApi=null,this._haRadarStage1Api=null,this._radarLive=new Pg(this),this._decorAssetSyncToken=0,this._alignDialog=null,this._settingsDialog=null,this._pdfDialog=!1,this._supportDialog=null,this._backupExportDialog=null,this._backupImportDialog=null,this._sunRaysCache=null,this._dayCycleTimer=0,this._dayCycleClockKey="",this._compassDrag=!1,this._importDialog=null,this._importQueue=[],this._importTotal=0,this._rulesCompiledSrc="",this._infoCard=null,this._nativeMoreInfoEntity=null,this._deviceInbox=null,this._deviceInboxReturn=null,this._deviceInboxMemo=null,this._markerDialog=null,this._spaceDialog=null,this._keyHandler=e=>this._onKey(e),this._warmVp=null,this._warmVpArmed=!1,this._warmLongReturn=!1,this._warmRevivePending=!1,this._warmGen=++av,this._warmKey=null,this._warmSlot=null,this._hashApplied=!1,this._navApplied=!1,this._labs={alpha:!1,active:Object.freeze([]),space:""},this._viewPreference={},this._renderProjection="flat",this._kioskScale={icon:1,font:1},this._kioskDialog=!1,this._summarySlot=new Qf(ev,this,e=>{this._summary=e,this._capturedSnapshotSequence=-1,this.isConnected&&(e.connect(),this.hasUpdated&&this.requestUpdate())}),this._activityRt=new Map,this._vacRt=new Map,this._vacViewKey="",this._vacLastView=null,this._vacRaf=0,this._vacSrvTrails={},this._vacJumpOnce=!1,this._continuity=this._newContinuityController(),this._continuityHistory=[],this._continuityEpoch=0,this._continuityDataReady=!0,this._continuityPaintToken=-1,this._continuityDisposed=!1,this._renderSnapshotAt=Date.now(),this._hassSequence=0,this._visibleDeviceSnapshot=null,this._candidateDeviceSnapshot=null,this._stagedDeviceSnapshotToken=-1,this._capturedSnapshotSequence=-1,this._capturedSnapshotDevices=null,this._capturedSnapshotLayout=null,this._capturedSnapshotActivity="",this._capturedSnapshotConfigEpoch=-1,this._capturedSnapshotVirtual="",this._lastValidStageSize=null,this._pendingRefitSize=null,this._refitRaf=0,this._pageVisibility=e=>{if(this._continuity.visibility(e),this._dayCycleVisibility(e),this._summary?.visibility(e.kind),"hidden"===e.kind)return this._radarLive.stop(),this._editorRuntime?._cancelRadarSetup(),this._clearRoomFocus(!0),this._clearTransientHover(!0),this._cancelDevicePressFeedback(),this._cancelCameraTransition(!0),void(this._modeTransitionPreparing?this._modeTransitionForceAtomic=!0:this._cancelModeTransition(!0));if(this._vacJumpOnce=!0,this._syncRadarLive(),!e.long){const e=Date.now();let t=!1;for(const i of this._activityRt.values())!i.flashKind||(i.expiresAt||i.flashTs+ig)>e||(i.flashTs=0,i.flashKind=null,i.expiresAt=0,t=!0);return void(t&&this.requestUpdate())}Date.now()-this._renderSnapshotAt>1e3&&this._continuity.note("device-snapshot-stale"),this._continuityDataReady=!1,this._continuityPaintToken=-1,this._resumeSettling=!0,this._loading?this.requestUpdate():this._loadFromServer()},this._resumeSettling=!1,this._viewportInvalidAt=0,this._vacFit=null,this._vacAllCamerasFor=null,this._vacAllCameraCache=null,this._vacCalConfirm=null,this._kioskDots=!1,this._cyclePausedUntil=0,this._swipeStart=null,this._tabDrag=null,this._tabDragRelease=null,this._tabSuppressClick=!1,this._tabOrderWarned=!1,this._onLabsSnapshot=e=>{const t=this._effectiveProjection();this._labs=e,this._isoProjectionSnapshot=null,this._labsIso&&this._ensureIsoSceneRuntime();const i=this._effectiveProjection();this._convertProjectionView(t,i),this.requestUpdate()},this._onHashChange=()=>{if(this._hasFixedFloor)return;const e=this._hashSpace();if(e&&this._model.find(t=>t.id===e)&&e!==this._space){if(this._wallFaceBatch&&this._roomDialogCancel(),"plan"===this._mode&&"draw"===this._tool&&!this._finishWallChain())return;this._commitSpace(e),this._selId=null,this._path=[],this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._tool="draw",this._activeWallChainId=null,this._activeWallChainPartitionIds=[],this._wallChainSegmentCms=[],this._closingWallCm=null,this._restoreZoom(),this.requestUpdate()}},this._drag=null,this._deviceDrag=null,this._rlResize=null,this._holdFired=!1,this._retryContinuity=()=>{this._continuityDataReady=!1,this._continuityPaintToken=-1,this._continuity.retry(this._continuity.recoveryReason||"plan"),this._loading||this._loadFromServer()},this._cfgEpoch=0,this._cfgEpochPreservedConfig=null,this._terminalFrame=0,this._modelCache=null,this._emptySpaceStateActive=!1,this._decorSnapCache=null,this._markerPreviewMemo=null,this._markerPreviewDevicesMemo=null,this._showHidden=!1,this._connHooked=null,this._connectionWasLost=!1,this._haRegistryConnection=null,this._haRegistryRev=-1,this._haBindingCacheKey="",this._planHassMemo=null,this._renderLife=new Mg,this._liveEditorPaintCount=0,this._onHaRegistryUpdate=()=>{const e=rd(this.hass);e.revision===this._haRegistryRev&&this._devices.length||(this._haRegistryRev=e.revision,this._renderLife.invalidate(),this._planHassMemo=null,this._regSignature="",this._maybeRebuildDevices(),this.requestUpdate())},this._onConnReady=()=>{if(this._loadTries=0,clearTimeout(this._loadRetryTimer),this._loadRetryTimer=void 0,nd(this.hass),this._saveConfigDebounced.pending()&&this._saveConfigDebounced.flush(),this._cfgWriting)return clearTimeout(this._reloadRetry),void(this._reloadRetry=window.setTimeout(this._onConnReady,400));!this._connectionWasLost&&this._continuity.hasCompleteFrame?this._beginContinuityCandidate("connection-ready",!1,"plan"):(this._continuityDataReady=!1,this._continuityPaintToken=-1),this._loading||this._loadFromServer()},this._onConnLost=()=>{this._booting&&!this._continuity.hasCompleteFrame||(this._connectionWasLost=!0,this._continuityDataReady=!1,this._continuityPaintToken=-1,this._continuity.connectionLost())},this._signer=new pc(()=>this.requestUpdate()),this._dirtyPos=new Set,this._sentPos=new Map,this._persistLayout=yv(()=>{if(this._serverStorage){const e=[...this._dirtyPos];this._dirtyPos.clear();for(const t of e){const e=wo(this._layout[t]);e&&(this._layout={...this._layout,[t]:e},this._sentPos.set(t,e),this.hass.callWS({type:"houseplan/layout/update",device_id:t,pos:e}).then(e=>this._noteLayoutRev(e)).catch(e=>this._showToast(this._t("toast.pos_save_failed",{err:this._errText(e)}))).finally(()=>{this._sentPos.get(t)===e&&this._sentPos.delete(t)}))}this._cacheSnapshot()}else this._persistLocalLayout()},600),this._frame=null,this._showFar=!1,this._writesPending=0,this._writeChain=Promise.resolve(),this._pendingPhysicalWrites=new Map,this._undoGeometry=()=>this._editorRuntimeOrThrow()._undoGeometry(),this._redoGeometry=()=>this._editorRuntimeOrThrow()._redoGeometry(),this._saveConfigDebounced=yv(()=>{this._serverCfg&&this._writeConfig().catch(e=>{const t=!0===e?.physicalGeometryRolledBack;"geometry-unsafe"!==e?.code&&("wall_model_client_outdated"===e?.code?this._showToast(this._t("toast.wall_model_client_outdated")):"conflict"===e?.code?(this._showToast(this._t("toast.conflict")),t||(this._cancelPath(),this._reloadConfigOnly(!0))):this._showToast(this._t("toast.cfg_save_failed",{err:this._errText(e)})),t&&this._reloadRejectedPhysicalWrite())})},500),this._wallChainSegmentCms=[],this._closingWallCm=null,this._savePhysicalDialog=()=>this._editorRuntimeOrThrow()._savePhysicalDialog(),this._deletePhysicalSelection=()=>this._editorRuntimeOrThrow()._deletePhysicalSelection(),this._confirmPartitionDelete=()=>this._editorRuntimeOrThrow()._confirmPartitionDelete(),this._confirmRoomDelete=e=>this._editorRuntimeOrThrow()._confirmRoomDelete(e),this._rebindPartitionOpening=()=>this._editorRuntimeOrThrow()._rebindPartitionOpening(),this._keepClosedAsPartitions=()=>this._editorRuntimeOrThrow()._keepClosedAsPartitions(),this._toggleServerPlans=async()=>this._onboardingRuntime&&this._spaceDialogUsesOnboardingRuntime("create")?this._onboardingRuntime._toggleServerPlans():this._editorRuntimeOrThrow()._toggleServerPlans(),this._aspectJob=null,this._dayCycleTick=()=>{if(!this.isConnected||"hidden"===this.ownerDocument.visibilityState)return;const e=this._dayCycleState();if(!e)return this._dayCycleTimer&&(clearInterval(this._dayCycleTimer),this._dayCycleTimer=0),void(this._dayCycleClockKey="");const t=ar(e);t!==this._dayCycleClockKey&&(this._dayCycleClockKey=t,this.requestUpdate())},this._sunShown=!1,this._sunOut=!1,this._sunOutTimer=0,this._openSettingsDialog=()=>{if(this._editorRuntime)return this._editorRuntime._openSettingsDialog();this._ensureEditorRuntime().then(e=>{e&&this._openSettingsDialog()})},this._openSupportDialog=()=>{this._editorRuntime?this._editorRuntime._openSupportDialog():this._ensureEditorRuntime().then(e=>{e&&this._openSupportDialog()})},this._openPdfDialog=()=>{this._pdfRuntimeLoader.ensure().then(e=>{e&&(this._pdfDialog=!0,this.requestUpdate())})},this._reportedPreflightFingerprint=null,this._openAlignDialog=()=>this._editorRuntimeOrThrow()._openAlignDialog(),this._toggleOptimizeLivePositions=()=>this._editorRuntimeOrThrow()._toggleOptimizeLivePositions(),this._optimizeUndoBusy=!1,this._openBackupExport=()=>this._editorRuntimeOrThrow()._openBackupExport(),this._openRulesDialog=()=>this._editorRuntimeOrThrow()._openRulesDialog(),this._climateCache=null,this._gearPtCache=new WeakMap}requestUpdate(e,t,i){if("hass"===e&&this.hass&&this._liveRt){const e=this._visibleDeviceSnapshot||this._candidateDeviceSnapshot;if(!this._liveRt.hass(t,this.hass,e?{entityIds:e.entityIds}:null,()=>Rg(this))&&!this._summary?.observeHassComposition())return}void 0!==e&&(this._terminalFrame=0),this._editorRuntime?._routeLiveEditorUpdate(e,t)||(this._liveRt?.clear(),super.requestUpdate(e,t,i))}_editorRuntimeOrThrow(){if(!this._editorRuntime)throw new Error("Houseplan editor runtime is not loaded");return this._editorRuntime}async _ensureEditorRuntime(){return this._editorRuntimeLoader.ensure()}async _ensureOnboardingRuntime(){return this._onboardingRuntimeLoader.ensure()}async _ensureIsoSceneRuntime(){return this._isoSceneRuntimeLoader.ensure()}_editorRuntimeStateChanged(e){clearTimeout(this._editorRuntimeLoadingTimer),this._editorRuntimeLoadingTimer=void 0,"loading"!==e?(this._editorRuntimeLoadingVisible=!1,this.requestUpdate()):this._editorRuntimeLoadingTimer=window.setTimeout(()=>{this._editorRuntimeLoadingVisible=!0,this.requestUpdate()},150)}async _requestMode(e,t=!0,i=!1){const n=++this._editorModeRequest;if(i&&(this._warmModeRequest=n,this._refitRaf&&(cancelAnimationFrame(this._refitRaf),this._refitRaf=0),this._pendingRefitSize=null),"view"===e||await this._ensureEditorRuntime()){if(n===this._editorModeRequest&&this.isConnected)return i?(this._adoptMode(e),this._warmRevivePending&&(clearTimeout(this._warmReviveTimer),this._warmReviveTimer=void 0,this._warmReviveDialog()),this.requestUpdate(),void this.updateComplete.then(()=>requestAnimationFrame(()=>requestAnimationFrame(()=>{if(this._warmModeRequest!==n||n!==this._editorModeRequest)return;const e=this._stageEl;this._lastValidStageSize=e&&e.clientWidth>0&&e.clientHeight>0?[e.clientWidth,e.clientHeight]:null,this._pendingRefitSize=null,this._warmModeRequest=0})))):void this._setMode(e,t);this._warmModeRequest===n&&(this._warmModeRequest=0)}else this._warmModeRequest===n&&(this._warmModeRequest=0)}get _layout(){return this._adoption.layout}set _layout(e){this._adoption.stageLocalLayout(e)}get _layoutRev(){return this._adoption.layoutRev}set _layoutRev(e){this._adoption.seedIdentity({layoutRev:e})}get _layoutContentFingerprint(){return this._adoption.layoutFingerprint}set _layoutContentFingerprint(e){this._adoption.seedIdentity({layoutFingerprint:e})}get _serverCfg(){return this._adoption.config}set _serverCfg(e){this._adoption.stageLocalConfig(e)}get _cfgRev(){return this._adoption.configRev}set _cfgRev(e){this._adoption.seedIdentity({configRev:e})}get _cfgContentFingerprint(){return this._adoption.configFingerprint}set _cfgContentFingerprint(e){this._adoption.seedIdentity({configFingerprint:e})}_seedDecorStyle(e){var t,i;if(t=zl,i=this,Al(e,Bl)&&"pending"===t.state()&&(t.art("",i),t.ensure()),this._decorStyleSeeded||!e)return;this._decorStyleSeeded=!0;const n=e.settings?.decor_default_style;n&&(this._decorStyle=function(e,t){if(!e||"object"!=typeof e)return{...t};const i=e,n="string"==typeof i.color&&i.color?i.color:t.color,r="string"==typeof i.fill_color&&i.fill_color?i.fill_color:t.fillColor,o=Number(i.width_cm);return{color:n,opacity:Rr(i.opacity,t.opacity),widthCm:Number.isFinite(o)&&o>0?Math.max(.1,Math.min(100,o)):t.widthCm,fill:"boolean"==typeof i.fill?i.fill:t.fill,fillColor:r,fillOpacity:Rr(i.fill_opacity,t.fillOpacity)}}(n,Mr))}get _canManageConfiguration(){return null!==this._serverCanWrite?this._serverCanWrite:!0===this.hass?.user?.is_admin}get _canEdit(){return this._norm&&this._canManageConfiguration}get _kiosk(){return!!this._config?.kiosk}_showKioskDots(){this._kioskDots=!0,clearTimeout(this._kioskDotsTimer),this._kioskDotsTimer=window.setTimeout(()=>this._kioskDots=!1,2500)}get _modeTransitionBusy(){return this._modeTransitionPreparing||this._modeTransition.active}get _doubleFitEnabled(){return!("view"!==this._mode||this._vacFit||this._modeTransitionBusy||this._touchSequenceMultitouch||"steady"!==this._continuity.state||this._continuity.overlayBlocksInteraction)}_cameraState(){const e=this._viewOr(this._baseVb());return{zoom:this._zoom,viewBox:{...e}}}_normalizeCameraState(e){const t=this._cameraTransitionFit||Oi(this._baseVb(),this._stageAspect());return{zoom:Math.min(kv.ZOOM_MAX,Math.max(kv.ZOOM_MIN,e.zoom)),viewBox:this._clampView({...e.viewBox},t)}}_applyCameraTransitionFrame(e){const t=this._normalizeCameraState(e.presented);e.presented=t,this._zoom=t.zoom,this._view={...t.viewBox},this._liveVp(!0)}_settleCameraTransition(e){const t=this._normalizeCameraState(e.to);this._zoom=t.zoom,this._view={...t.viewBox},this._cameraTransitionFit=null,"room"!==e.reason&&this._saveZoom(),this.requestUpdate()}_cancelCameraTransition(e=!1,t=!1){const i=this._cameraTransition.state?.reason,n=t&&this._cameraTransition.active?this._cameraTransition.presented?.zoom:void 0;this._cameraTransition.cancel(e),this._cameraTransitionFit=null,void 0!==n&&"room"!==i&&this._saveZoom()}_prepareCameraCommand(){this._bootSoftCancel(),this._modeTransitionBusy&&this._cancelModeTransition(!0),"opening"===this._tool&&(this._cursorPt=null,this._clearOpeningPlacement(!1))}_startCameraTransition(e,t,i,n){const r=this._cameraState(),o=this._cameraTransition.target;return(!o||!Zg(o,e))&&(Zg(r,e)?(this._cancelCameraTransition(!1),!1):(this._cameraTransitionFit={...t},this._cameraTransition.start(r,e,i,this._reducedMotion?0:n),!0))}_cssColor(e,t){const i=String(e||"").trim();if(!i)return t;const n=document.createElement("span");n.style.cssText=`position:absolute;visibility:hidden;color:${i}`,this.renderRoot.append(n);const r=getComputedStyle(n).color||t;return n.remove(),r}_currentModeVisual(e=this._mode){const t=this._modeTransition.presented||this._modeTransitionVisual;if(t)return{...t,viewport:{...t.viewport,viewBox:{...t.viewport.viewBox}}};const i=this._stageEl;if(!i||i.clientWidth<=0||i.clientHeight<=0)return null;const n=this.renderRoot.querySelector(".editorchrome"),r=this._viewOr(this._baseVb()),o=this.renderRoot.querySelector(".hp-paper"),s=this.renderRoot.querySelector(".hp-backdrop"),a=this.renderRoot.querySelector(".zoomwrap"),l=a?getComputedStyle(a).filter:"",c=Number(/brightness\(([^)]+)\)/.exec(l)?.[1]);return{presentedMode:e,editorChromeHeight:"view"===e?0:n?.getBoundingClientRect().height||0,stageWidth:i.clientWidth,stageHeight:i.clientHeight,viewport:qg(r,i.clientWidth),stageColor:getComputedStyle(i).backgroundColor||"rgb(255, 255, 255)",paperColor:o?getComputedStyle(o).fill:"rgb(255, 255, 255)",sceneBrightness:Number.isFinite(c)?c:1,architectureOpacity:"decor"===e?.35:1,backdropOpacity:s&&Number(getComputedStyle(s).opacity)||1,viewWeight:"view"===e?1:0,editorWeight:"view"===e?0:1,toolbarContentOpacity:"view"===e?0:1}}_viewForModeTarget(e,t,i,n,r){const o=Oi(this._baseVb(),n/r),s=Math.min(kv.ZOOM_MAX,Math.max(kv.ZOOM_MIN,e)),a=o.w/s,l=o.h/s,c=t??o.x+o.w/2,h=i??o.y+o.h/2;return this._clampView({x:c-a/2,y:h-l/2,w:a,h:l},o)}_targetStageColor(e){return"view"!==e?"rgb(255, 255, 255)":this._cssColor(this._stageBg(this._spaceDisplayForRender()),this._cssColor("var(--ha-card-background, var(--card-background-color, #111))","rgb(17, 17, 17)"))}_targetPaperColor(e){return"view"===e&&this._spaceModel()?.bg?this._cssColor("var(--ha-card-background, var(--card-background-color, #111))","rgb(17, 17, 17)"):"rgb(255, 255, 255)"}_targetBrightness(e){return 1}_applyModeTransitionFrame(e){e.targetMode===this._mode&&(this._modeTransitionVisual=e.presented,this._view={...e.presented.viewport.viewBox},this.requestUpdate())}_settleModeTransition(e){if(e.targetMode!==this._mode)return;const t=this._modeTransitionRequest;this._view={...e.to.viewport.viewBox},this._zoom=this._modeTransitionTargetZoom,this._modeTransitionVisual=null,this._modeTransitionPreparing=!1,this._lastValidStageSize=[e.to.stageWidth,e.to.stageHeight],"view"===this._mode&&(this._saveZoom(),this._viewModeSnap=null,this._modeTransitionEditorCamera=null),this.requestUpdate(),this.updateComplete.then(()=>{if(!this.isConnected||t!==this._modeTransitionRequest||this._modeTransitionBusy||e.targetMode!==this._mode)return;const i=this._stageEl;if(i&&i.clientWidth>0&&i.clientHeight>0&&(Math.abs(i.clientWidth-e.to.stageWidth)>.5||Math.abs(i.clientHeight-e.to.stageHeight)>.5)){const e=this._view;this._lastValidStageSize=[i.clientWidth,i.clientHeight],this._applyView(this._zoom,e?e.x+e.w/2:void 0,e?e.y+e.h/2:void 0),this.requestUpdate()}const n=this.renderRoot.activeElement;(!n||!n.isConnected||!!n.closest?.(".editorchrome, .stage"))&&this.renderRoot.querySelector(".modetab.active")?.focus?.({preventScroll:!0})})}_cancelModeTransition(e=!0){this._cancelCameraTransition(!1);const t=!!this._modeTransition.state;this._modeTransitionRequest++,this._modeTransitionPreparing=!1,this._modeTransitionForceAtomic=!1,this._modeTransition.cancel(e),e&&t||(this._modeTransitionVisual=null)}_adoptMode(e){e!==this._mode&&(this._clearRoomFocus(!0),this._resetDeviceHitState()),this._cancelModeTransition(!1),this._mode=e,this._isoProjectionSnapshot=null,"view"!==e&&(this._editorChromeMode=e)}_commitViewModeAtomic(e,t,i,n){if(this._modeTransitionPreparing=!1,this._modeTransitionVisual=null,this._modeTransitionForceAtomic=!1,this._zoom=t,e){const r=this._stageEl?.clientWidth||e.stageWidth,o=Math.max(1,e.stageHeight+e.editorChromeHeight);this._view=this._viewForModeTarget(t,i,n,r,o),this._lastValidStageSize=[r,o]}else this._view=null;this._viewModeSnap=null,this._modeTransitionEditorCamera=null,this._saveZoom(),this.requestUpdate()}_prepareModeTransition(e,t,i,n,r,o){this.updateComplete.then(()=>{if(!this.isConnected||e!==this._modeTransitionRequest||this._mode!==i)return void(e===this._modeTransitionRequest&&(this._modeTransitionPreparing=!1,this._modeTransitionVisual=null,this._modeTransitionForceAtomic=!1,this.requestUpdate()));const s=this.renderRoot.querySelector(".editorchrome-inner"),a="view"===i?0:s?.scrollHeight||0,l=Math.max(1,(this.panelHost?this.clientHeight:innerHeight)-tf(this.renderRoot,this._stageEl,this.panelHost)),c=this._stageEl?.clientWidth||t.stageWidth,h=this._viewForModeTarget(n,r,o,c,l),d={presentedMode:i,editorChromeHeight:a,stageWidth:c,stageHeight:l,viewport:qg(h,c),stageColor:this._targetStageColor(i),paperColor:this._targetPaperColor(i),sceneBrightness:this._targetBrightness(i),architectureOpacity:"decor"===i?.35:1,backdropOpacity:"decor"===i&&"backdrop"!==this._decorTool?.5:1,viewWeight:"view"===i?1:0,editorWeight:"view"===i?0:1,toolbarContentOpacity:"view"===i?0:1};this._modeTransitionPreparing=!1;const u=this._modeTransitionForceAtomic;this._modeTransitionForceAtomic=!1,this._modeTransition.start(t,d,i,this._reducedMotion||u?0:220)})}get _hasFixedFloor(){return!!this._config&&Object.prototype.hasOwnProperty.call(this._config,"floor")}_fixedFloorState(e=this._model,t=this._loadOk){const i=this._config?.floor,n=function(e){if(!e.hasFloor)return{kind:"absent"};const t=e.floor;if("string"==typeof t)return t.length?e.spaceIds.includes(t)?{kind:"valid",id:t,source:"id"}:{kind:"invalid",reason:"unknown-id",value:t}:{kind:"invalid",reason:"empty-id",value:t};if("number"==typeof t){if(!Number.isFinite(t))return{kind:"invalid",reason:"non-finite-index",value:t};if(!Number.isInteger(t))return{kind:"invalid",reason:"fractional-index",value:t};if(t<0)return{kind:"invalid",reason:"negative-index",value:t};const i=e.spaceIds[t];return void 0===i?{kind:"invalid",reason:"out-of-range-index",value:t}:{kind:"valid",id:i,source:"index"}}return{kind:"invalid",reason:"invalid-type",value:t}}({spaceIds:e.map(e=>e.id),hasFloor:this._hasFixedFloor,floor:i});return!this._hasFixedFloor||t?n:"number"==typeof i?"valid"===n.kind||"invalid"===n.kind&&"out-of-range-index"===n.reason?{kind:"pending",value:i}:n:"valid"===n.kind||"invalid"===n.kind&&"unknown-id"!==n.reason?n:{kind:"pending",value:i}}_canCommitSpace(e,t=!1){if(t||!this._hasFixedFloor)return!0;const i=this._fixedFloorState();return"valid"===i.kind&&i.id===e}_commitSpace(e,t=!1){return!!this._canCommitSpace(e,t)&&(e!==this._space&&(this._clearRoomFocus(!0),this._resetDeviceHitState(),this._cancelDangerConfirm(),this._cancelCameraTransition(!1),this._clearTransientHover(!0),this._cancelDevicePressFeedback(),this._editorRuntime?._clearFurniturePreview()),this._space=e,this._isoProjectionSnapshot=null,!0)}_slideTo(e,t){if(e===this._space)return!0;if(!this._canCommitSpace(e))return!1;if(this._wallFaceBatch&&this._roomDialogCancel(),"plan"===this._mode&&"draw"===this._tool&&!this._finishWallChain())return!1;this._cancelModeTransition(!0);const i=window.matchMedia?.("(prefers-reduced-motion: reduce)")?.matches;return this._commitSpace(e),this._path=[],this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._tool="draw",this._activeWallChainId=null,this._activeWallChainPartitionIds=[],this._wallChainSegmentCms=[],this._closingWallCm=null,this._selId=null,this._physicalSel=null,this._editorSecondary?.closeForNavigation(),this._physicalDialog=null,this._physicalDrag=null,this._restoreZoom(),i||(this._slide=t,clearTimeout(this._slideTimer),this._slideTimer=window.setTimeout(()=>{this._slideTimer=void 0,this._slide="",this.requestUpdate()},190),this.requestUpdate()),!0}get _canReorderTabs(){return Jf({canEdit:this._canEdit,kiosk:this._kiosk,mode:this._mode,pointerType:"mouse",spaceCount:this._model.length,fixedFloor:this._hasFixedFloor})}_tabPointerDown(e,t){Jf({canEdit:this._canEdit,kiosk:this._kiosk,mode:this._mode,pointerType:e.pointerType,spaceCount:this._model.length,fixedFloor:this._hasFixedFloor})&&(bv(e),this._tabDragRelease=e=>this._tabPointerUp(e),window.addEventListener("pointerup",this._tabDragRelease),window.addEventListener("pointercancel",this._tabDragRelease),this._tabDrag={id:t,pointerId:e.pointerId,x:e.clientX,y:e.clientY,moved:!1,targetId:null,placement:null})}_tabDropTargetAt(e,t,i){const n=this._model.map(e=>e.id),r=n.indexOf(i);if(r<0)return null;const o=this.renderRoot.querySelectorAll('[data-hp="space-tab"]');for(const s of o){const o=s.dataset.id||"";if(!o||o===i)continue;const a=s.getBoundingClientRect();if(ea.right||ta.bottom)continue;const l=n.indexOf(o);return l<0?null:{targetId:o,placement:l=4)))return;var i,n;const r=this._tabDropTargetAt(e.clientX,e.clientY,t.id);t.moved&&t.targetId===r?.targetId&&t.placement===r?.placement||(this._tabDrag={...t,moved:!0,targetId:r?.targetId||null,placement:r?.placement||null})}_tabPointerUp(e){const t=this._tabDrag;if(t&&t.pointerId!==e.pointerId)return;const i="pointerup"===e.type&&t?.moved?this._tabDropTargetAt(e.clientX,e.clientY,t.id):null;"pointerup"===e.type&&t?.moved&&this._suppressNextTabClick(),this._endTabDrag(),t?.moved&&i&&this._commitTabOrder(t.id,i.targetId)}_endTabDrag(){this._tabDrag=null,this._tabDragRelease&&(window.removeEventListener("pointerup",this._tabDragRelease),window.removeEventListener("pointercancel",this._tabDragRelease),this._tabDragRelease=null)}_tabClick(e){if(this._tabSuppressClick)return this._tabSuppressClick=!1,clearTimeout(this._tabSuppressClickTimer),void(this._tabSuppressClickTimer=void 0);this._pickSpace(e)}_suppressNextTabClick(){this._tabSuppressClick=!0,clearTimeout(this._tabSuppressClickTimer),this._tabSuppressClickTimer=window.setTimeout(()=>{this._tabSuppressClick=!1,this._tabSuppressClickTimer=void 0},0)}_commitTabOrder(e,t){const i=this._serverCfg;if(!i||!this._canReorderTabs)return;const n=this._model.map(e=>e.id),r=function(e,t,i){const n=e.indexOf(t),r=e.indexOf(i);if(n<0||r<0||n===r)return e;const o=e.slice();return o.splice(n,1),o.splice(r,0,t),o}(n,e,t);if(r===n)return;const o=new Map(this._devices.map(e=>[String(e.id),String(e.area||"")])),s=function(e,t,i,n=()=>""){if(!i)return[];const r=[];for(const o of e){if(!o||!0===o.removed)continue;const e="string"==typeof o.id?o.id:"";if(!e)continue;if("string"==typeof o.space&&o.space)continue;const s=("string"==typeof o.area?o.area:"")||n(e)||"";s&&t[s]||r.push({id:e,space:i})}return r}(i.markers||[],Object.fromEntries(Object.entries(this._areaToSpace).map(([e,t])=>[e,t.space])),n[0]||"",e=>o.get(e)||"");if(s.length){const e=new Map(s.map(e=>[e.id,e.space]));for(const t of i.markers||[]){const i=e.get(String(t.id));i&&(t.space=i)}}i.spaces=function(e,t){const i=new Map(t.map((e,t)=>[e,t]));return e.map((e,t)=>({space:e,index:t})).sort((e,t)=>(i.get(String(e.space?.id))??Number.MAX_SAFE_INTEGER)-(i.get(String(t.space?.id))??Number.MAX_SAFE_INTEGER)||e.index-t.index).map(e=>e.space)}(i.spaces||[],r),this._saveConfig(),this._tabOrderWarned||(this._tabOrderWarned=!0,this._showToast(this._t("toast.space_order_changed")))}_pickSpace(e){if(this._endTabDrag(),e===this._space)return;const t=this._model.map(e=>e.id),i=t.indexOf(this._space),n=t.indexOf(e);this._navApplied=!0,this._showFar=!1,this._frame=null,this._slideTo(e,i>=0&&n0&&Date.now()>=this._cyclePausedUntil&&this._model.length>1&&this._zoom<=1.001){const e=this._model.map(e=>e.id),t=e.indexOf(this._space);this._slideTo(e[(t+1)%e.length],"left"),this._showKioskDots()}}_syncCycleTimer(){clearInterval(this._cycleTimer),this._cycleTimer=void 0,this.isConnected&&!this._hasFixedFloor&&this._config?.kiosk&&Number(this._config.cycle)>0&&(this._cycleTimer=window.setInterval(()=>this._cycleTick(),1e3*Number(this._config.cycle)))}get _editing(){return"plan"===this._mode||"devices"===this._mode||"decor"===this._mode}get _markup(){return"plan"===this._mode}get _wallUnionCache(){return this._wallUnionCacheValue}set _wallUnionCache(e){this._wallUnionCacheValue=e,null===e&&this._wallUnionPool.clear()}get _glowClipCache(){return this._glowRuntimeState.clipCache}get _glowGeometryWarnings(){return this._glowRuntimeState.geometryWarnings}get _glowFeatherUnits(){return this._glowRuntimeState.featherUnits}set _glowFeatherUnits(e){this._glowRuntimeState.featherUnits=e}get _glowRenderedSources(){return this._glowRuntimeState.renderedSources}get _glowLastAppearance(){return this._glowRuntimeState.lastAppearance}get _glowFeatherSuspendUntil(){return this._glowRuntimeState.featherSuspendUntil}set _glowFeatherSuspendUntil(e){this._glowRuntimeState.featherSuspendUntil=e}get _glowFeatherResumeTimer(){return this._glowRuntimeState.featherResumeTimer}set _glowFeatherResumeTimer(e){this._glowRuntimeState.featherResumeTimer=e}get _glowSourceSeq(){return this._glowRuntimeState.sourceSeq}set _glowSourceSeq(e){this._glowRuntimeState.sourceSeq=e}get _touchSequenceMultitouch(){return this._touchClickGuard.sequenceMultitouch}_syncDangerConfirmLocaleGate(){return this._config&&this.hass?up(this,fp,xp(this.hass,this._config.language)):"ready"}_dangerConfirmMissingSpace(){const e=this._model;if(!e.length)return!1;const t=this._fixedFloorState(e);return"pending"!==t.kind&&"invalid"!==t.kind&&!this._spaceModel()}_syncVersionRecovery(){this._versionRecovery.update({frontendVersion:tv(nv),backendVersion:this._haIntegrationVersion,kiosk:!0===this._config?.kiosk,reducedMotion:this._reducedMotion})}_newContinuityController(){return new cc(()=>{this._resumeSettling="steady"!==this._continuity.state,this._continuityEpoch++,this.isConnected&&this.requestUpdate()})}get _labsIso(){return this._labs.active.includes("iso")}get _desiredProjection(){return"view"===this._mode&&this._labsIso&&"iso"===this._viewPreference[this._space]?"iso":"flat"}_saveViewPreference(){try{localStorage.setItem(pv,JSON.stringify(this._viewPreference))}catch{}}_logicalViewCenter(e){const t=this._view;if(!t)return null;const i=[t.x+t.w/2,t.y+t.h/2],n="iso"===e?hf(i):i;return{x:n[0],y:n[1]}}_convertProjectionView(e,t){if(e===t)return;this._clearRoomFocus(!0);const i=this._logicalViewCenter(e);this._view=null;const n=i?"iso"===t?cf([i.x,i.y],0):[i.x,i.y]:null;this._applyView(this._zoom,n?.[0],n?.[1]),this._warmPatch({vp:this._warmViewportState()}),this.requestUpdate()}_setProjection(e){if(!this._labsIso||"view"!==this._mode)return;const t=this._effectiveProjection();if(this._viewPreference={...this._viewPreference,[this._space]:e},"iso"===e){this._ensureIsoSceneRuntime();const e=this._isoSceneKey();e&&this._isoFallback.delete(e),this._isoFallback.delete(`${this._space}|no-borders`),this._clearIsoInvalidFallback()}this._saveViewPreference(),this._isoProjectionSnapshot=null;const i=this._effectiveProjection();this._convertProjectionView(t,i)}_hashSpace(){return zf(window.location.hash||"")}connectedCallback(){this._connectedPath=location.pathname,this._routeDepartureHandled=!1,this._configReloadAuthority.observeContext(Ku(this)),window.addEventListener("location-changed",this._onLocationChanged),window.addEventListener("popstate",this._onLocationChanged),this._continuityDisposed&&(this._continuity=this._newContinuityController(),this._continuityDisposed=!1,this._continuityPaintToken=-1);const e=ug(this.ownerDocument);var t;void 0!==e&&(this._glowScreenBlend=e),this._continuityUnsub?.(),this._continuityUnsub=ac(this.ownerDocument,this._pageVisibility),this._languageFailureUnsub?.(),this._languageFailureUnsub=function(...e){return()=>{for(const t of e)t()}}((t=()=>{this._showToast(this._t("toast.locale_load_failed"))},gp.add(t),()=>gp.delete(t)),function(e){return Fl.add(e),()=>{Fl.delete(e)}}(()=>this._showToast(this._t("toast.furniture_art_load_failed")))),super.connectedCallback(),this._summarySlot.connect(),this._ensureLiveRuntime().catch(()=>this.requestUpdate()),this._pointerModality.connect(this.ownerDocument.defaultView);const i=this.ownerDocument.defaultView?.MutationObserver;i&&(this._pointerHoverObserver=new i(e=>{let t=!1;for(const i of e){for(const e of i.addedNodes)this._syncPointerHoverSubtree(e);const e=e=>{if(e.nodeType!==Node.ELEMENT_NODE)return!1;const t=e;return t.matches(".devlayer, .devlayer *")||!!t.querySelector?.(".devlayer")};(e(i.target)||[...i.addedNodes,...i.removedNodes].some(e))&&(t=!0)}t&&this._invalidateDeviceHitGeometry()}),this._pointerHoverObserver.observe(this.renderRoot,{childList:!0,subtree:!0,attributes:!0,attributeFilter:["class","style","data-id"]})),this._motionMedia=window.matchMedia?.("(prefers-reduced-motion: reduce)"),this._reducedMotion=!!this._motionMedia?.matches,this._motionMedia?.addEventListener?.("change",this._onMotionChange),this._syncVersionRecovery(),this._versionRecovery.connect(),dg(this.ownerDocument).then(e=>{e!==this._glowScreenBlend&&(this._glowScreenBlend=e,this.isConnected&&this.requestUpdate())}),this.hass&&this._ensureHaRegistryAuthority(),window.addEventListener("keydown",this._keyHandler),this._signer.start(()=>this.hass,()=>this._referencedContentUrls()),this._syncCycleTimer(),window.addEventListener("hashchange",this._onHashChange),this._labsUnsub?.(),this._labsUnsub=function(e){Hf.add(e);const t=qf();return"undefined"==typeof window&&e(t),()=>{Hf.delete(e)}}(this._onLabsSnapshot),this._labsIso&&this._ensureIsoSceneRuntime(),this._booting?this._bootWatch():this._bootFading&&(clearTimeout(this._bootTimer),this._bootTimer=window.setTimeout(()=>{this._bootFading=!1},220)),this._bootSoft&&(clearTimeout(this._bootSoftTimer),this._bootSoftTimer=window.setTimeout(()=>{this._bootSoft=!1},ov)),!this._loadOk&&this._serverCfg&&this.hass&&this._scheduleLoadRetry(),!this._warmSlot&&this._config&&this._warmAdopt(),this._loadOk&&this._ensureLiveSyncSubscriptions(),this._warmVp&&!this._warmRevivePending&&void 0===this._warmReviveTimer&&(this._warmRevivePending=!0,this._warmReviveTimer=window.setTimeout(()=>this._warmReviveDialog(),0)),this._warmLongReturn&&this._beginResumeSettle(),this._warmLongReturn=!1,this.requestUpdate()}disconnectedCallback(){this._versionRecovery.disconnect(),this._configReloadAuthority.invalidateLifecycle(),this._liveRt?.dispose(),this._radarLive.stop(),this._editorRuntime?._disposeLiveEditor(),this._clearRoomFocus(!0),this._cancelDangerConfirm(),this._connectedPath&&location.pathname!==this._connectedPath&&this._leaveCardRoute(),window.removeEventListener("location-changed",this._onLocationChanged),window.removeEventListener("popstate",this._onLocationChanged),this._continuityUnsub?.(),this._continuityUnsub=void 0,this._languageFailureUnsub?.(),this._languageFailureUnsub=void 0,this._motionMedia?.removeEventListener?.("change",this._onMotionChange),this._motionMedia=void 0,this._vacRaf&&(cancelAnimationFrame(this._vacRaf),this._vacRaf=0),this._refitRaf&&(cancelAnimationFrame(this._refitRaf),this._refitRaf=0),this._warmModeRequest=0,this._dayCycleTimer&&(clearInterval(this._dayCycleTimer),this._dayCycleTimer=0),this._summarySlot.disconnect(),this._dayCycleClockKey="",this._bootSettleRaf&&(cancelAnimationFrame(this._bootSettleRaf),this._bootSettleRaf=0),this._bootSettling=!1;for(const e of this._activityRt.values())clearTimeout(e.timer);window.removeEventListener("keydown",this._keyHandler),this._endTabDrag(),clearTimeout(this._tabSuppressClickTimer),this._tabSuppressClickTimer=void 0,this._tabSuppressClick=!1,clearInterval(this._cycleTimer),clearTimeout(this._kioskDotsTimer),clearTimeout(this._kioskHoldTimer),clearTimeout(this._reloadRetry),clearTimeout(this._loadRetryTimer),this._loadRetryTimer=void 0,this._connHooked?.removeEventListener?.("ready",this._onConnReady),this._connHooked?.removeEventListener?.("disconnected",this._onConnLost),this._connHooked?.removeEventListener?.("reconnect-error",this._onConnLost),this._connHooked=null,this._haRegistryRelease?.(),this._haRegistryRelease=void 0,this._haRegistryConnection=null,this._signer.dispose(),clearTimeout(this._toastTimer),clearTimeout(this._slideTimer),clearTimeout(this._editorRuntimeLoadingTimer),this._editorRuntimeLoadingTimer=void 0,this._editorRuntimeLoadingVisible=!1,this._modeTransition.dispose(),this._cameraTransition.dispose(),this._cameraTransitionFit=null,this._modeTransitionVisual=null,this._modeTransitionPreparing=!1,this._modeTransitionForceAtomic=!1,this._modeTransitionRequest++,this._slideTimer=void 0,this._slide="",clearTimeout(this._bootTimer),this._bootTimer=void 0,clearTimeout(this._bootSoftTimer),this._saveConfigDebounced.flush(),this._cancelDeviceDrag(),window.removeEventListener("hashchange",this._onHashChange),this._labsUnsub?.(),this._labsUnsub=void 0,clearTimeout(this._holdTimer),this._roViewport?.disconnect(),this._roViewport=void 0,this._roHdr?.disconnect(),this._roHdr=void 0,this._onWinResize&&(window.removeEventListener("resize",this._onWinResize),this._onWinResize=void 0),this._unsubCfg&&(this._unsubCfg(),this._unsubCfg=null),this._unsubLayout&&(this._unsubLayout(),this._unsubLayout=null),this._unsubVirtual&&(this._unsubVirtual(),this._unsubVirtual=null),this._unsubTrail&&(this._unsubTrail(),this._unsubTrail=void 0),this._liveSyncGeneration++,this._liveSyncAttempt=null,this._liveSyncConnection=null,clearTimeout(this._layoutSyncTimer),clearTimeout(this._duplicateColumnTimer),zm(this._glowRuntimeState,this._glowRuntimeHost),this._warmSnapshot(),this._warmRevivePending=!1,clearTimeout(this._warmReviveTimer),this._warmReviveTimer=void 0,this._warmRelease(),this._clearPlanSnapHover(),this._clearOpeningPlacement(!0),this._editorRuntime?._clearFurniturePreview(),this._editorRuntime?._furnShiftDetach(),this._touchContacts.clear(),this._touchClickGuard.reset(),this._resetDeviceHitState(),this._clearTransientHover(!0),this._cancelDevicePressFeedback(),this._pointerHoverObserver?.disconnect(),this._pointerHoverObserver=void 0,this._pointerModality.disconnect(),this._editorSecondary?.reset(),this._resumeSettling=!1,this._continuityHistory=[...this._continuityHistory,...this._continuity.trace].slice(-80),this._continuity.dispose(),this._continuityDisposed=!0,super.disconnectedCallback()}_onKey(e){if("Escape"===e.key&&this._vacFit){if(this._vacFit.busy)return;return this._vacFit=null,this._showToast(this._t("vac.cal_cancelled")),void e.stopPropagation()}if("Escape"===e.key){if(this._tapConfirm)return void(this._tapConfirm=null);if(this._vacCalConfirm)return void(this._vacCalConfirm.busy||(this._vacCalConfirm=null));if(this._decorEraseConfirm)return void(this._decorEraseConfirm=null);if(this._openingInfo)return void(this._openingInfo=null);if(this._infoCard)return void this._closeInfoCard();if(this._rulesDialog)return void(this._rulesDialog=null);if(this._alignDialog)return this._alignDialog=null,void(this._preflightClipboardFallback=null);if(this._backupImportDialog)return void(this._backupImportDialog=null);if(this._backupExportDialog)return void(this._backupExportDialog=null);if(this._pdfDialog)return void(this._pdfDialog=!1);if(this._supportDialog)return void this._editorRuntime?._closeSupportDialog();if(this._settingsDialog)return void(this._settingsDialog=null);if(this._summary?.closeDialogIfIdle())return;if(this._markerDialog)return void this._closeMarkerDialog();if(this._deviceInbox)return void(this._deviceInbox=null);if(this._openingDialog)return void(this._openingDialog=null);if(this._physicalDialog)return void(this._physicalDialog=null);if(this._backdropDialog)return void(this._backdropDialog=null);if(this._decorShapeDialog)return void(this._decorShapeDialog=null);if(this._decorTextDialog)return void(this._decorTextDialog=null);if(this._spaceDialog&&!this._roomDialog)return this._spaceDialog=null,this._importQueue=[],void(this._importTotal=0);if(this._editorSecondary?.hasOpenGroup)return e.preventDefault(),void this._editorSecondary?.closeGroup(!0)}const t=e.composedPath?.()||[e.target],i=t.some(e=>e?.matches?.('input, textarea, select, [contenteditable="true"]')),n=t.some(e=>e?.classList?.contains?.("editor-secondary")),r=e.ctrlKey||e.metaKey,o=e.key.toLowerCase(),s=/^[a-z]$/.test(o),a="z"===o||!s&&"KeyZ"===e.code,l="y"===o||!s&&"KeyY"===e.code,c=r&&(a&&e.shiftKey||l),h=r&&a&&!e.shiftKey;if("decor"===this._mode){if((h||c)&&i)return;if(c)return e.preventDefault(),void this._redoGeometry();if(h)return e.preventDefault(),this._decorDraft?void(this._decorDraft=null):this._decorMove||this._dtDrag||this._bdDrag?void this._cancelDecorGesture():void this._undoGeometry();if(("Delete"===e.key||"Backspace"===e.key)&&this._decorSel&&!i&&!n)return e.preventDefault(),void this._decorDeleteSel();const t="ArrowLeft"===e.key?[-this._gridPitch,0]:"ArrowRight"===e.key?[this._gridPitch,0]:"ArrowUp"===e.key?[0,-this._gridPitch]:"ArrowDown"===e.key?[0,this._gridPitch]:null;return!t||r||e.altKey||"select"!==this._decorTool||!this._decorSel||!this._decorList.some(e=>e.id===this._decorSel)||this._decorDraft||this._decorMove||this._dtDrag||this._bdDrag||i||n||this._editorSecondaryDialogBlocked?void("Escape"===e.key&&(e.preventDefault(),this._decorDraft?this._decorDraft=null:this._decorMove||this._dtDrag||this._bdDrag?this._cancelDecorGesture():"furniture"===this._decorTool?(this._editorRuntime?._clearFurniturePreview(),this._editorRuntime?._furnShiftDetach(),this._furnPalette=null,this._furnCategory=null,this._decorTool="select"):this._decorSel?this._decorSel=null:"select"!==this._decorTool?this._decorTool="select":this._setMode("view"))):(e.preventDefault(),void this._decorNudge(t[0],t[1]))}if("devices"===this._mode){if((h||c)&&i)return;return c?(e.preventDefault(),void this._redoDevicePosition()):h?(e.preventDefault(),void this._undoDevicePosition()):void("Escape"===e.key&&this._deviceDrag&&(e.preventDefault(),this._cancelDeviceDrag()))}if(this._markup&&(!h&&!c||!i)){if(("Delete"===e.key||"Backspace"===e.key)&&this._physicalSel&&!i&&!n)return e.preventDefault(),void this._deletePhysicalSelection();if(c)return e.preventDefault(),void this._redoGeometry();if(h)return e.preventDefault(),this._resize?.dragging?void this._rszCancelDrag():this._wallFaceBatch?(this._roomDialogCancel(),void(this._activeWallChainId&&this._path.length>1?this._undoActiveWallPoint():this._undoPoint())):"draw"===this._tool&&this._path.length?void(this._activeWallChainId&&this._path.length>1?this._undoActiveWallPoint():this._undoPoint()):"split"===this._tool&&this._splitSel?.pts?.length?(this._splitSel={...this._splitSel,pts:this._splitSel.pts.slice(0,-1)},void(this._splitSel.pts.length||(this._cursorPt=null))):void this._undoGeometry();if("Escape"===e.key)return this._physicalDrag||this._physicalRotate?(e.preventDefault(),void this._cancelPhysicalGesture()):this._roomDialog?(e.preventDefault(),void this._roomDialogCancel()):"draw"===this._tool&&this._path.length?(e.preventDefault(),void this._finishWallChain()):this._physicalSel?(e.preventDefault(),void(this._physicalSel=null)):"resize"===this._tool?(e.preventDefault(),this._resize?.dragging?void this._rszCancelDrag():("exit-tool"===this._resize?.escapeIdle()&&(this._tool="draw"),void this.requestUpdate())):"split"===this._tool?(e.preventDefault(),void(this._splitSel?.pts?.length?(this._splitSel={...this._splitSel,pts:this._splitSel.pts.slice(0,-1)},this._splitSel.pts.length||(this._cursorPt=null)):this._splitSel?this._splitSel=null:this._tool="draw")):"merge"===this._tool?(e.preventDefault(),void(this._mergeSel?this._mergeSel=null:this._tool="draw")):this._wallDialog?(e.preventDefault(),void(this._wallDialog=null)):void("opening"!==this._tool&&"wallthick"!==this._tool&&"delroom"!==this._tool&&"column"!==this._tool||(e.preventDefault(),"opening"===this._tool&&this._clearOpeningPlacement(!0),this._tool="draw"))}}_undoPoint(){if(this._path.length)return this._contourClosed?(this._path=this._path.slice(0,-1),void(this._closingWallCm=null)):void(this._activeWallChainPartitionIds.length&&this._path.length>1?this._undoActiveWallPoint():this._path=this._path.slice(0,-1))}_undoActiveWallPoint(){const e=[...this._activeWallChainPartitionIds],t=e[e.length-1],i=this._spaceModel()?.partitions.find(e=>e.id===t),n=this._path[0]?[...this._path[0]]:null,r=this._path.slice(0,-1).map(e=>[...e]),o=this._wallChainSegmentCms.slice(0,-1),s=this._geometryHistory.undo();if(!s)return this._activeWallChainPartitionIds=[],this._wallChainSegmentCms=[],this._wallChainRedo=[],void(this._path=n?[n]:[]);this._applyGeometryState(s.before,!0)?(this._activeWallChainId||=`chain-${Date.now().toString(36)}`,this._activeWallChainPartitionIds=e.slice(0,-1),this._path=r.length?r:n?[n]:[],this._wallChainSegmentCms=o,i&&this._wallChainRedo.push({id:i.id,point:[...i.b],cm:i.cm}),this._clearPlanSnapHover(),this._showToast(this._t("history.undone",{name:s.name}))):this._geometryHistory.clear()}static async getConfigElement(){return await import("./editor-Bi3cJ768.js"),document.createElement("houseplan-card-editor")}static getStubConfig(){return{type:"custom:houseplan-card"}}static _warmBootReset(e){for(const e of sv.values())for(const t of e)clearTimeout(t.evict);sv.clear(),lv=e&&e>0?e:1e4}static _warmBootStats(){let e=0,t=0;const i=[];for(const n of sv.values())for(const r of n)e++,r.dlg&&(t++,i.push(r.dlg.kind));return{keys:sv.size,slots:e,dlgs:t,drafts:i}}setConfig(e){const t=this._config,i=!!t&&Object.prototype.hasOwnProperty.call(t,"floor");this._config={icon_size:2.5,show_temperature:!0,live_states:!0,show_signal:!0,...e};(i!==this._hasFixedFloor||t?.floor!==this._config.floor)&&(this._hashApplied=!1,this._navApplied=!1,this._warmVpArmed=!1),this._config.kiosk&&(this._booting=!1,this._bootFading=!1),!this._hasFixedFloor&&e.default_floor&&this._commitSpace(e.default_floor,!0);try{this._zoomBySpace=JSON.parse(localStorage.getItem(dv)||"{}")||{}}catch{this._zoomBySpace={}}try{const e=JSON.parse(localStorage.getItem(pv)||"{}")||{};this._viewPreference=Object.fromEntries(Object.entries(e).filter(e=>"flat"===e[1]||"iso"===e[1]))}catch{this._viewPreference={}}if(this._labs=qf(),this.isConnected&&this._labsIso&&this._ensureIsoSceneRuntime(),!this._summary?.applyLocalScaleForCurrentIdentity())try{const e=JSON.parse(localStorage.getItem("houseplan_card_kiosk_v1")||"null");this._kioskScale={icon:Bn(e?.icon),font:Bn(e?.font)}}catch{}try{const e=JSON.parse(localStorage.getItem(hv)||"null");this._adoption.restoreCached(e)&&(this._seedDecorStyle(this._serverCfg),this._cfgEpoch++,this._virtualLights=Lh(e.virtual_lights,this._cfgRev),this._serverStorage=!0)}catch{}this._adoptInitialSpace(this._model,this._loadOk),"view"!==this._mode||this._view||(this._zoom=this._zoomBySpace[this._space]||1),this.isConnected&&(this._syncCycleTimer(),this._warmAdopt(),this._warmLongReturn&&this._beginResumeSettle(),this._warmLongReturn=!1),this._syncVersionRecovery()}_warmAdopt(){if(this._config?.kiosk)return;const e=Tf(this._config);if(this._warmKey===e&&this._warmSlot)return;this._warmSlot&&this._warmRelease();const t=this.parentNode,i=this._warmIdx(t),n=sv.get(e);if(!n||!n.length)return;const r=n.find(e=>e.owner===this._warmGen);if(r)return this._warmLongReturn=!!r.freed&&Date.now()-r.freed>=rc,clearTimeout(r.evict),r.evict=0,r.freed=0,r.live=!0,this._warmSlot=r,this._warmKey=e,r.frameFingerprint&&this._continuity.adoptCompleteFrame(r.frameFingerprint),void(!this._devices.length&&r.devices?.length&&(this._devices=[...r.devices]));const{slot:o,sure:s}=((e,t,i,n)=>{const r=e=>{const t=!!i&&e.place?.deref()===i;return t&&e.idx===n?4:e.live?0:t?3:2};let o=null,s=0,a=0,l=null;for(const i of e){if(i.owner===t)continue;l=i;const e=r(i);e<=0||(e>s?(o=i,s=e,a=1):e===s&&a++)}return!o||a>1?{slot:o||l,sure:!1}:{slot:o,sure:!0}})(n,this._warmGen,t,i);o&&(this._warmLongReturn=!!o.freed&&Date.now()-o.freed>=rc,this._booting=!1,this._bootFading=!1,this._hdrH=o.hdrH,this._bootSoft=!0,this.isConnected&&(clearTimeout(this._bootSoftTimer),this._bootSoftTimer=window.setTimeout(()=>{this._bootSoft=!1},ov)),this._warmKey=e,s?(clearTimeout(o.evict),o.evict=0,o.owner=this._warmGen,o.place=t?new WeakRef(t):null,o.idx=i,o.live=!0,this._warmSlot=o,this._warmVp=o.vp,o.frameFingerprint&&this._continuity.adoptCompleteFrame(o.frameFingerprint),!this._devices.length&&o.devices?.length&&(this._devices=[...o.devices]),this._warmAdoptViewport(this._config)):(this._warmSlot={owner:this._warmGen,path:location.pathname,place:t?new WeakRef(t):null,idx:i,live:!0,hdrH:o.hdrH,stageH:o.stageH,vp:null,frameFingerprint:"",devices:null,dlg:null,freed:0,evict:0},n.push(this._warmSlot),this._warmTrim(n)))}_warmIdx(e){const t=e?.children;if(!t)return-1;for(let e=0;e4;){const t=e.findIndex(e=>!e.live);if(t<0)break;clearTimeout(e[t].evict),e.splice(t,1)}}_warmScheduleEvict(e,t){if(clearTimeout(e.evict),!(e.dlg||e.vp&&"view"!==e.vp.mode))return;const i=e.freed,n=e.owner;e.evict=window.setTimeout(()=>{if(e.evict=0,e.freed!==i||e.owner!==n)return;var r;e.dlg=null,e.vp=(r=e.vp)&&"view"!==r.mode?{...r,mode:"view",zoom:r.snap?.space===r.space?r.snap.zoom:r.zoom,view:null,snap:null,tool:"draw",decorTool:"select",showHidden:!1,selId:null,rszSel:null,decorSel:null}:r,e.frameFingerprint="";const o=sv.get(t);if(!e.live&&o&&o.length>1){const t=o.indexOf(e);t>=0&&o.splice(t,1)}},lv+250)}_warmAdoptViewport(e){const t=this._warmVp;if(!t||this._warmSlot?.path!==location.pathname)return void(this._warmVp=null);const i=this._fixedFloorState();if(this._hashApplied||!this._model.find(e=>e.id===t.space)||"valid"===i.kind&&i.id!==t.space||this._hasFixedFloor&&"valid"!==i.kind)return void(this._warmVp=null);this._commitSpace(t.space,!0),this._navApplied=!0;const n="view"!==t.mode&&this._canEdit&&!e.kiosk?t.mode:"view";this._adoptMode("view"),this._pendingNavMode="view"===t.mode||this._canEdit||e.kiosk?null:t.mode,this._zoom=t.zoom;const r=this._effectiveProjection(),o=r===t.projection&&this._labsIso===t.activeLabsIso;if(this._view=o&&t.view?{...t.view}:null,this._viewModeSnap=o&&t.snap?{...t.snap}:null,!o&&t.logicalCenter){const e="iso"===r?cf([t.logicalCenter.x,t.logicalCenter.y],0):[t.logicalCenter.x,t.logicalCenter.y];this._applyView(t.zoom,e[0],e[1])}var s;this._tool="opening"===(s=function(e){return"partition"===e?"draw":e}(s=t.tool))?"draw":"string"==typeof s&&Cf.has(s)?s:"draw",this._decorTool=t.decorTool,this._showHidden=t.showHidden,this._showFar!==t.showFar&&(this._showFar=t.showFar,this._frame=null),this._selId=t.selId,this._resize?.restoreSelection(t.rszSel),this._decorSel=t.decorSel,this._warmVpArmed=!0,"view"!==n&&this._requestMode(n,!1,!0)}_warmPatch(e,t=!1){if(this._config?.kiosk)return;const i=Tf(this._config);if(!this._warmSlot||this._warmKey===i){if(!this._warmSlot){if(!t)return;const e=this.parentNode;this._warmKey=i,this._warmSlot={owner:this._warmGen,path:location.pathname,place:e?new WeakRef(e):null,idx:this._warmIdx(e),live:!0,hdrH:this._hdrH,stageH:0,vp:null,frameFingerprint:"",devices:null,dlg:null,freed:0,evict:0};const n=sv.get(i)||[];for(n.push(this._warmSlot),sv.set(i,n),this._warmTrim(n);sv.size>8;){const e=sv.keys().next().value;if(void 0===e||e===i)break;for(const t of sv.get(e)||[])clearTimeout(t.evict);sv.delete(e)}}Object.assign(this._warmSlot,e)}}_warmViewportState(){const e=this._effectiveProjection();return{space:this._space,mode:this._mode,projection:e,activeLabsIso:this._labsIso,logicalCenter:this._logicalViewCenter(e),zoom:this._zoom,view:this._view?{...this._view}:null,snap:this._viewModeSnap?{...this._viewModeSnap}:null,tool:this._tool,decorTool:this._decorTool,showHidden:this._showHidden,showFar:this._showFar,selId:this._selId,rszSel:this._resize?.selectedRoomId,decorSel:this._decorSel}}_warmDialogState(){const e=(e,t)=>({kind:e,space:this._space,mode:this._mode,data:t});return this._tapConfirm||this._alignDialog||this._mergeDialog||this._importDialog||this._backupExportDialog||this._backupImportDialog?null:this._openingInfo?e("openingInfo",this._openingInfo.id):this._infoCard?e("info",this._infoCard.id):this._rulesDialog?this._rulesDialog.busy?null:e("rules",this._rulesDialog):this._settingsDialog?this._settingsDialog.busy?null:e("settings",this._settingsDialog):this._markerDialog?this._markerDialog.busy?null:e("marker",this._markerDialog):this._openingDialog?e("opening",this._openingDialog):this._backdropDialog?e("backdrop",this._backdropDialog):this._decorShapeDialog?e("decorShape",this._decorShapeDialog):this._decorTextDialog?e("decorText",this._decorTextDialog):this._roomDialog?e("room",{editId:this._roomEditId,fill:this._roomFill,customFill:this._roomCustomFill,tempMin:this._roomTempMin,tempMax:this._roomTempMax,tempSrc:this._roomTempSrc,humSrc:this._roomHumSrc,srcOpen:this._roomSrcOpen,srcFilter:this._roomSrcFilter,nameScale:this._roomNameScale,labelScale:this._roomLabelScale,areaSel:this._areaSel,nameSel:this._nameSel,pendingSplit:this._pendingSplit,wallFaceBatch:this._wallFaceBatch,path:this._path}):this._spaceDialog?this._spaceDialog.busy?null:e("space",this._spaceDialog):null}_warmSnapshot(){if(this._booting||this._config?.kiosk||"steady"!==this._continuity.state)return;const e={vp:this._warmViewportState(),frameFingerprint:this._continuity.frameFingerprint,devices:this._devices,hdrH:this._hdrH};if(this._warmRevivePending||(e.dlg=this._warmDialogState()),this.isConnected&&this._warmSlot?.owner===this._warmGen){const t=this.parentNode;e.place=t?new WeakRef(t):null,e.idx=this._warmIdx(t)}this._warmPatch(e)}_warmReviveDialog(){const e=this._warmSlot;if(this._warmReviveTimer=void 0,!e||!e.dlg)return void(this._warmRevivePending=!1);const t=e.dlg,i=e.freed;if(t.mode===this._mode||"view"===t.mode||this._warmVp?.mode!==t.mode||this._editorRuntime){if(this._warmRevivePending=!1,e.dlg=null,e.freed=0,clearTimeout(e.evict),e.evict=0,i&&!(Date.now()-i>lv)&&t.space===this._space&&t.mode===this._mode){switch(t.kind){case"space":this._spaceDialog={...t.data,busy:!1,savedBusy:!1};break;case"marker":this._markerDialog={...t.data,busy:!1};break;case"settings":this._settingsDialog={...t.data,busy:!1};break;case"rules":this._rulesDialog={...t.data,busy:!1};break;case"opening":this._openingDialog={...t.data};break;case"backdrop":this._backdropDialog={...t.data};break;case"decorShape":this._decorShapeDialog={...t.data};break;case"decorText":{this._decorTextDialog={...t.data};const e=String(this._decorTextDialog?.text??"").length;this._decorTextSelection={start:e,end:e};break}case"room":{const e=t.data;this._roomEditId=e.editId,this._roomFill=e.fill,this._roomCustomFill=e.customFill||null,this._roomTempMin=e.tempMin||"",this._roomTempMax=e.tempMax||"",this._roomTempSrc=e.tempSrc,this._roomHumSrc=e.humSrc,this._roomSrcOpen=e.srcOpen,this._roomSrcFilter=e.srcFilter,this._roomNameScale=e.nameScale,this._roomLabelScale=e.labelScale,this._areaSel=e.areaSel,this._nameSel=e.nameSel,this._pendingSplit=e.pendingSplit,this._wallFaceBatch=e.wallFaceBatch||null,this._path=e.path,this._wallFaceBatch&&(this._activeWallChainId=`chain-${Date.now().toString(36)}`,this._activeWallChainPartitionIds=[...this._wallFaceBatch.activePartitionIds],this._wallChainSegmentCms=[...this._wallFaceBatch.activeCms]),this._roomDialog=!0;break}case"info":{const e=this._devices.find(e=>e.id===t.data);e&&(this._infoCard=e);break}case"openingInfo":{const e=(this._curSpaceCfg?.openings||[]).find(e=>e.id===t.data);e&&(this._openingInfo=e);break}}this.requestUpdate()}}else this._warmRevivePending=!0}_cacheSnapshot(){if(this._serverCfg)try{this._virtualLights=function(e,t,i){if(e.configRev===i)return e;const n=new Set((Array.isArray(t?.markers)?t.markers:[]).filter(jh).map(e=>e.id));return{...e,configRev:i,off:new Set([...e.off].filter(e=>n.has(e)))}}(this._virtualLights,this._serverCfg,this._cfgRev);const e=this._adoption.snapshot(function(e){return{rev:e.rev,config_rev:e.configRev,off:[...e.off].sort()}}(this._virtualLights));e&&localStorage.setItem(hv,JSON.stringify(e))}catch{}}_beginContinuityCandidate(e,t,i="plan"){return this._booting&&!this._continuity.hasCompleteFrame?this._continuity.token:(this._continuityDataReady=t,this._continuityPaintToken=-1,this._stagedDeviceSnapshotToken=-1,this._resumeSettling=!0,this._continuity.beginCandidate(e,i))}_continuityStageValid(){const e=this._stageEl;return!!e&&e.clientWidth>0&&e.clientHeight>0}_versionReloadSafetySnapshot(){return $g(this)}_continuityAssetsReady(){if(!this._model.length)return!1;const e=this._model.length?this._spaceModel():null;return!e?.bg?.href||this._signer.isReady(this.hass,e.bg.href)}_initialSpaceSelection(e,t=this._loadOk){const i=this._fixedFloorState(e,t);return"valid"===i.kind?{id:i.id,source:"fixed"}:this._hasFixedFloor?{id:null,source:"none"}:function(e){const t=new Set(e.spaceIds.filter(e=>!!e));if(!t.size)return{id:null,source:"none"};const i=[["hash",!1===e.acceptHash?null:e.hashSpace],["current",e.preserveCurrent?e.currentSpace:null],["saved",e.savedSpace],["default",e.defaultSpace],["first",e.spaceIds[0]]];for(const[e,n]of i)if(n&&t.has(n))return{id:n,source:e};return{id:null,source:"none"}}({spaceIds:e.map(e=>e.id),hashSpace:this._hashSpace(),acceptHash:!this._hashApplied,currentSpace:this._space,preserveCurrent:this._hashApplied||this._navApplied||this._warmVpArmed,savedSpace:this._savedNav()?.space,defaultSpace:this._config?.default_floor})}_adoptInitialSpace(e,t=this._loadOk){const i=this._initialSpaceSelection(e,t);return i.id?(this._commitSpace(i.id,!0),"hash"===i.source&&(this._hashApplied=!0),"saved"===i.source&&(this._navApplied=!0),i):i}_candidateBackdrop(e,t=this._space){const i=Ja(e),n=this._fixedFloorState(i,!0);if(this._hasFixedFloor&&"valid"!==n.kind)return"";const r=this._initialSpaceSelection(i,!0).id||(i.some(e=>e.id===t)?t:i[0]?.id);return i.find(e=>e.id===r)?.bg?.href||""}_visualFrameFingerprint(){const e=this._stageEl,t=e?[e.clientWidth,e.clientHeight]:[0,0];return dc([this._cfgRev,this._adoption.currentConfigFingerprint(),this._layoutRev,this._adoption.currentLayoutFingerprint(),this._space,this._mode,this._view,t,this._glowScreenBlend?"screen":"normal",this.hass?.themes?.darkMode??this.hass?.themes?.default_theme??""])}_settleContinuityFrame(){if(this._booting||!this._continuityStageValid())return;if(!this._continuity.hasCompleteFrame&&"steady"===this._continuity.state)return void(this._continuityAssetsReady()&&(this._renderSnapshotAt=Date.now(),this._continuity.markCompleteFrame(this._visualFrameFingerprint())));if(!this._continuityDataReady)return;if(!["holding","offline-stale","overlay-pending","overlay-visible","candidate-ready"].includes(this._continuity.state))return;const e=this._continuity.token;if(this._candidateDeviceSnapshot&&this._candidateDeviceSnapshot!==this._visibleDeviceSnapshot&&this._stagedDeviceSnapshotToken!==e)return this._stagedDeviceSnapshotToken=e,void this.requestUpdate();this._continuityPaintToken!==e&&(this._continuityPaintToken=e,this._continuity.candidateReady(e)&&this._continuity.commitAfterPaint(e,{updateComplete:()=>this.updateComplete,stageValid:()=>this.isConnected&&this._continuityStageValid(),assetsReady:()=>this._continuityAssetsReady(),frameFingerprint:()=>this._visualFrameFingerprint()}).then(t=>{t&&e===this._continuity.token?(this._resumeSettling=!1,this._renderSnapshotAt=Date.now(),this._candidateDeviceSnapshot&&(this._visibleDeviceSnapshot=this._candidateDeviceSnapshot),this._candidateDeviceSnapshot=null,this._stagedDeviceSnapshotToken=-1,this._warmSnapshot()):e===this._continuity.token&&(this._continuityPaintToken=-1,this._stagedDeviceSnapshotToken=-1,this._candidateDeviceSnapshot=null,this.requestUpdate())}))}_onBackdropLoaded(e,t){this._signer.markLoaded(this.hass,e,t),this._continuity.note("asset-ready"),this._continuityPaintToken=-1,"steady"!==this._continuity.state&&this.requestUpdate()}_renderRecoveryOverlay(){if(!this._continuity.overlayVisible&&"recovery-error"!==this._continuity.state)return G;const e="connection"===this._continuity.recoveryReason;return j`
e.stopPropagation()} + @click=${e=>e.stopPropagation()} + @wheel=${e=>e.stopPropagation()}> + + ${this._t(e?"continuity.restore_connection":"continuity.restore_plan")} + ${"recovery-error"===this._continuity.state?j``:G} +
`}_reloadDocument(){this.ownerDocument.defaultView?.location.reload()}_renderVersionBanner(){return function(e,t,i=t.banner){if(!i)return G;const n="leaving"===i.phase;return j`
{e.target===e.currentTarget&&"hp-version-recovery-out"===e.animationName&&t.finishBannerExit(i.token)}}> +
+ +
+ ${e._t("version_mismatch.title")} + ${e._t("version_mismatch.body")} + + ${e._t("version_mismatch.frontend")}: ${i.frontend} + ${e._t("version_mismatch.backend")}: ${i.backend} + +
+ +
+
`}(this,this._versionRecovery)}_renderEditorRuntimeLoading(){return this._editorRuntimeLoadingVisible?j`
+ + ${this._t("editor.loading")} +
`:G}houseplanContinuityTrace(){return[...this._continuityHistory,...this._continuity.trace].slice(-80).map(e=>({...e,...e.stage?{stage:[...e.stage]}:{}}))}getCardSize(){return 12}getGridOptions(){return{columns:"full"}}get _norm(){return!(!this._serverCfg||!this._serverCfg.spaces.length)}_cfgFingerprint(){const e=this._serverCfg?.spaces||[];let t=e.length+":";for(const i of e){t+=(i.id||"")+","+(i.plan_aspect||"")+","+(i.plan_url||"").length+","+(i.plan_x??"")+","+(i.plan_y??"")+","+(i.plan_scale??"")+","+(i.plan_scale_x??"")+","+(i.plan_scale_y??"")+","+(i.plan_angle??"")+","+(i.rooms?.length||0)+","+(i.openings?.length||0)+","+(i.decor?.length||0)+";";for(const e of i.rooms||[]){const i=e.poly?.[0],n=e.poly?.[e.poly.length-1];t+=(e.poly?.length||0)+"."+(e.id||"")+"."+(e.open_to||[]).join("+")+"."+(e.area||"")+"."+JSON.stringify(e.settings||0)+"."+(e.x??"")+","+(e.y??"")+","+(e.w??"")+","+(e.h??"")+","+(i?i[0]+"/"+i[1]:"")+","+(n?n[0]+"/"+n[1]:"")+";"}}return t}get _model(){if(!this._serverCfg)return[];const e=this._cfgEpoch+"|"+this._cfgFingerprint();if(this._modelCache&&this._modelCache.key===e)return this._modelCache.model;const t=this._buildModel();return this._modelCache={key:e,model:t},t}_buildModel(){if(!this._serverCfg)return[];const e=this._renderCfg;return Ja(e).map((t,i)=>{const n=e.spaces[i]?.plan_url;return t.bg&&n?{...t,bg:{...t.bg,href:n}}:t})}_spaceModel(){return this._hasFixedFloor?xc(this._model,this._space):(e=this._model,t=this._space,e.find(e=>e.id===t)??e[0]);var e,t}_spaceModelById(e){return xc(this._model,e)}_syncEmptySpaceState(){if(!!this._serverCfg&&0===this._serverCfg.spaces.length){if(!this._emptySpaceStateActive){this._emptySpaceStateActive=!0,this._clearRoomFocus(!0);for(const e of this._pointers.keys())for(const t of this.renderRoot.querySelectorAll("*"))try{t.hasPointerCapture?.(e)&&t.releasePointerCapture(e)}catch{}this._pointers.clear(),this._panStart=null,this._panLock=null,this._pinchStart=null,this._swipeStart=null,this._drag=null,this._deviceDrag=null,this._resetDeviceHitState(),this._rlResize=null,this._vacFit=null,this._compassDrag=!1,this._cancelModeTransition(!1),this._mode="view",this._clearGeometryGesture(),this._geometryHistory.clear(),this._devicePositionHistory.clear(),this._tip=null,this._hoverRoom=null,this._openingInfo=null,this._closeInfoCard(),this._deviceInbox=null,this._deviceInboxReturn=null,this._markerDialog=null,this._physicalDialog=null,this._backdropDialog=null,this._decorShapeDialog=null,this._decorTextDialog=null,this._roomDialog=!1,"edit"===this._spaceDialog?.mode&&(this._spaceDialog=null),this._editorSecondary?.closeForNavigation(),this._saveConfigDebounced.cancel(),this._frame=null,this._planSnapGeometryCache=null,this._hiddenWallDiagnosticCache=null,this._decorSnapCache=null,this._commitSpace("",!0)}}else this._emptySpaceStateActive=!1}get _areaToSpace(){const e={};for(const t of this._model)for(const i of t.rooms)i.area&&(e[i.area]={space:t.id,room:i});return e}get _settings(){return this._serverCfg?.settings||{}}get _showAll(){return this._showHidden||!this._settings.filter_seeded&&!!this._settings.show_all}_seedHiddenDevices(){if(!(this._loadOk&&this._serverCfg&&this._norm&&this._canEdit))return;const e=this._serverCfg,t=tu({hass:this.hass,registry:this._haRegistry,areaToSpace:Object.fromEntries(Object.entries(this._areaToSpace).map(([e,t])=>[e,t.space])),markers:this._markers,settings:this._settings,excluded:this._excluded,firstSpaceId:this._model[0]?.id||"",iconRules:this._iconRules});if(!t.length&&e.settings?.filter_seeded)return;e.markers=e.markers||[];const i=[];for(const n of t){const t="h"+n.slice(n.indexOf(":")+1);e.markers.push({id:t,binding:n,hidden:!0}),i.push(n.slice(n.indexOf(":")+1))}const n={...e.settings||{},filter_seeded:!0};delete n.show_all,i.length&&Array.isArray(n.new_device_ids)&&(n.new_device_ids=n.new_device_ids.filter(e=>!i.includes(e))),e.settings=n,this._regSignature="",this._maybeRebuildDevices(),this._saveConfig(),this.requestUpdate()}get _iconRules(){const e=this._settings.icon_rules;if(!e||!Array.isArray(e)||!e.length)return;const t=JSON.stringify(e);return t!==this._rulesCompiledSrc&&(this._rulesCompiledSrc=t,this._rulesCompiled=Ee(e)),this._rulesCompiled}get _fillColors(){return gn(this._settings)}get _excluded(){return cu(this._settings)}_setAreaLifecycleConfig(e){this._cfgEpochPreservedConfig=e,this._serverCfg=e}willUpdate(e){if(this._isoProjectionSnapshot=null,this._summary?.willUpdate(),e.has("hass")&&this._configReloadAuthority.observeContext(Ku(this)),e.has("_serverCfg")){const e=this._cfgEpochPreservedConfig===this._serverCfg;this._cfgEpochPreservedConfig=null,e||this._cfgEpoch++,this._renderLife.invalidate()}if(this._syncEmptySpaceState(),this._dangerConfirm&&(this._dangerConfirmMissingSpace()||"warm"===this._syncDangerConfirmLocaleGate())&&this._cancelDangerConfirm(),e.has("hass")&&this.hass){const t=this._visibleDeviceSnapshot||this._candidateDeviceSnapshot;this._renderLife.observe(e.get("hass"),this.hass,t?{entityIds:t.entityIds}:null,()=>Rg(this))}this._continuity.hasCompleteFrame&&"steady"===this._continuity.state&&this._continuity.refreshCompleteFrame(this._visualFrameFingerprint()),this._captureRenderDeviceSnapshot()}updated(){this._summary?.updated(),this._liveRt?.commit(),this._editorRuntime?._commitLiveEditor(),this._pruneDevicePressFeedback(),this._syncDayCycleClock(),this._syncRadarLive(),this._warmSnapshot(),this._editorRuntime&&this._dtMeasure();const e=this._stageEl;e&&!this._roViewport&&(this._roViewport=new ResizeObserver(()=>{this._invalidateDeviceHitGeometry(),this._refitView(),requestAnimationFrame(()=>this._summary?.resized())}),this._roViewport.observe(e)),e&&this._booting&&!this._bootTimer&&this._bootWatch();const t=this.renderRoot.querySelector(".hdr");if(t&&e&&!this._roHdr){const i=()=>{const t=tf(this.renderRoot,e,this.panelHost);null!==t&&(t>=0&&t!==this._hdrH&&(this._hdrH=t),t>=0&&!this._booting&&!this._config?.kiosk&&e.clientHeight>0&&this._warmPatch({hdrH:t,stageH:e.clientHeight}))};this._roHdr=new ResizeObserver(()=>requestAnimationFrame(i)),this._roHdr.observe(t),this._onWinResize=()=>requestAnimationFrame(i),window.addEventListener("resize",this._onWinResize),i()}if(e&&!this._view&&this._refitView(),this._editorSecondary?.afterRender(),this._settleContinuityFrame(),this._serverStorage&&this._loadOk&&this._canManageConfiguration&&0===this._model.length&&!this._spaceDialog&&!this._importDialog&&!this._onboardingShown){this._onboardingShown=!0;const e=function(e){const t=e?.floors;if(!t||"object"!=typeof t)return[];const i=[];for(const e of Object.values(t))e&&e.floor_id&&i.push({id:e.floor_id,name:e.name||e.floor_id,level:e.level??null});return i.sort((e,t)=>{const i=e.level??1e9,n=t.level??1e9;return i!==n?i-n:e.name.localeCompare(t.name)}),i}(this.hass);e.length?this._importDialog={floors:e.map(e=>({...e,checked:!0}))}:this._openSpaceDialog("create")}}_adoptConfigCapabilities(e){Sg(this,e)}_syncRadarLive(){const e=this._serverCfg?.settings?.radar,t=(this._serverCfg?.markers||[]).some(e=>Tg(e,this._space));this._radarLive.sync(this._space,1===this._haRadarStage1Api&&"view"===this._mode&&!1!==e?.show_live&&t&&"hidden"!==this.ownerDocument.visibilityState)}async _syncDecorAssets(e){const t=++this._decorAssetSyncToken;if(1!==this._haDecorAssetsApi||!this.hass)return void(this._decorAssets=new Map);const i=await pm(this.hass,hm(e),this._cfgRev);t===this._decorAssetSyncToken&&(this._decorAssets=i,this._resign(),this.requestUpdate())}_adoptAuthoritative(e){return Wu(this,e)}_rollbackOptimistic(e){const t=this._adoption.rollbackOptimistic(e);return t&&this.requestUpdate(),t}_resumePendingNavMode(){if(!this._pendingNavMode||!this._canEdit||this._config?.kiosk)return!1;const e=this._pendingNavMode;return this._pendingNavMode=null,this._setMode(e,!1),!0}_getAuthoritativeConfig(){return e=this,async function(e,t){const i=await e();return t(i),i}(()=>e.hass.callWS({type:"houseplan/config/get"}),t=>Sg(e,t));var e}async _loadFromServer(){this._loading=!0,this._loadTries++;const e=this._space,t=!!this._view;let i=!1;const n=()=>{i=!0,this._regSignature="",this._maybeRebuildDevices()};try{const[i,r]=await Promise.all([this._getAuthoritativeConfig(),this.hass.callWS({type:"houseplan/layout/get"})]);if("adopted"!==(await this._adoptAuthoritative({cfgResp:i,layResp:r,reason:"structural-response",profile:"reload",beforeAdopt:()=>{this._connectionWasLost=!1,this._serverStorage=!0},afterAdopt:()=>{this._warmVpArmed&&this._space===this._warmVp?.space?this._warmVpArmed=!1:t&&this._space===e||this._restoreZoom(),this._loadOk=!0,n()}})).status)return;this.hass.callWS({type:"houseplan/trail/get"}).then(e=>{this._vacSrvTrails=e?.trails||{},this.requestUpdate()}).catch(()=>{}),this._ensureLiveSyncSubscriptions()}catch(e){if(this._serverCfg)this._scheduleLoadRetry(!0);else if(this._loadTries>=8){this._serverStorage=!1;try{this._layout=JSON.parse(localStorage.getItem(cv)||"{}")||{}}catch{this._layout={}}}}finally{this._loading=!1,this._continuityDataReady=!0,i||n(),this.requestUpdate()}}_ensureLiveSyncSubscriptions(){const e=this.hass?.connection;if(!e)return;if(e!==this._liveSyncConnection&&(this._unsubCfg?.(),this._unsubCfg=null,this._unsubLayout?.(),this._unsubLayout=null,this._unsubTrail?.(),this._unsubTrail=void 0,this._unsubVirtual?.(),this._unsubVirtual=null,this._liveSyncGeneration++,this._liveSyncAttempt=null,this._liveSyncConnection=e),this._liveSyncAttempt)return;const t=this._liveSyncGeneration,i=[],n=(n,r,o,s)=>{n()||i.push(async()=>{const i=await e.subscribeEvents(s,o);t===this._liveSyncGeneration&&this.isConnected&&this.hass?.connection===e&&!n()?r(i):i?.()})};if(n(()=>this._unsubCfg,e=>{this._unsubCfg=e},"houseplan_config_updated",e=>{const t=Number(e?.data?.rev??-1);t!==this._cfgRev&&this._reloadConfigOnly(!1,t)}),n(()=>this._unsubTrail,e=>{this._unsubTrail=e},"houseplan_trail_updated",async()=>{try{const e=await this.hass.callWS({type:"houseplan/trail/get"});this._vacSrvTrails=e?.trails||{},this.requestUpdate()}catch{}}),n(()=>this._unsubLayout,e=>{this._unsubLayout=e},"houseplan_layout_updated",e=>this._onLayoutEvent(Number(e?.data?.rev??-1))),n(()=>this._unsubVirtual,e=>{this._unsubVirtual=e},"houseplan_virtual_light_updated",e=>{const t=Uh(this._virtualLights,e?.data);t!==this._virtualLights&&(this._virtualLights=t,this._capturedSnapshotVirtual="",this._cacheSnapshot(),this.requestUpdate())}),!i.length)return;const r=function(e){return Promise.allSettled(e.map(e=>Promise.resolve().then(e)))}(i).then(()=>{});this._liveSyncAttempt=r,r.finally(()=>{this._liveSyncAttempt===r&&(this._liveSyncAttempt=null)})}async _reloadConfigOnly(e=!1,t){return Yu(this,e,t)}_scheduleLoadRetry(e=!1){if(void 0!==this._loadRetryTimer)return;const t=Math.min(8e3,500*2**Math.min(4,Math.max(1,this._loadTries-7)));this._loadRetryTimer=window.setTimeout(()=>{this._loadRetryTimer=void 0,!e&&this._loadOk||this._loading||!this.hass||this._loadFromServer()},t)}async _ensureLiveRuntime(){if(this._liveRt)return;const e=await import("./live-interaction-runtime-C8mBGPZT.js");this._liveRt=new e.LiveRuntime(this),this.isConnected&&this.requestUpdate()}_liveVp(e=!1){this._liveRt?this._liveRt.viewport(e):this.requestUpdate()}_syncLiveHover(){this._liveRt?this._liveRt.hover():this.requestUpdate()}_flushHa(){this._liveRt?.take()&&(this._terminalFrame=2,super.requestUpdate())}_ensureHaRegistryAuthority(){const e=this.hass?.connection||null;e&&e!==this._haRegistryConnection&&(this._haRegistryRelease?.(),this._haRegistryConnection=e,this._haRegistryRev=-1,this._haBindingCacheKey="",this._renderLife.invalidate(),this._areaSnapshotCleanupCandidates.clear(),this._planHassMemo=null,this._haRegistryRelease=id(this.hass,this._onHaRegistryUpdate),this._onHaRegistryUpdate())}get _haRegistry(){return rd(this.hass)}get _planHass(){const e=this._haRegistry,t=sd(this.hass,e),i=this._planHassMemo;if(i&&i.hass===this.hass&&i.sig===t)return i.active;const n=ld(this.hass,e),r=cd(this.hass,e);return this._planHassMemo={hass:this.hass,sig:t,active:n,full:r},n}_captureRenderDeviceSnapshot(){if(!this.hass)return;const e=Date.now(),t=[...this._activityRt.entries()].map(([t,i])=>`${t}:${i.gen}:${i.flashTs}:`+(i.flashKind&&(i.expiresAt||i.flashTs+ig)>e?1:0)).join("|"),i=qh(this._virtualLights);if(this._capturedSnapshotSequence===this._hassSequence&&this._capturedSnapshotDevices===this._devices&&this._capturedSnapshotLayout===this._layout&&this._capturedSnapshotConfigEpoch===this._cfgEpoch&&this._capturedSnapshotVirtual===i&&this._capturedSnapshotActivity===t)return;const n=this._planHass,r=new Map,o=new Map,s=new Set(["sun.sun"]);for(const e of this._summary?.entityIds()||[])s.add(e);this._vacFit?.source&&s.add(this._vacFit.source);const a=new Set,l=new Set,c=e=>{if(!e)return;const t=e.indexOf(":");if(t<0)return void s.add(e);const i=e.slice(0,t),n=e.slice(t+1);"device"===i?a.add(n):"entity"===i&&s.add(n)};for(const e of this._model)for(const t of e.rooms)t.area&&l.add(t.area),c(t.settings?.temp_source),c(t.settings?.hum_source);for(const e of this._serverCfg?.spaces||[])for(const t of e.openings||[])for(const e of ui(t))s.add(e);for(const e of this._serverCfg?.spaces||[])for(const t of e.decor||[])if("text"===t.kind){for(const e of String(t.text||"").matchAll(/\{([^{}\r\n]+)\}/g)){const t=Ki(e[1]);t?.entity&&s.add(t.entity)}t.entity&&s.add(t.entity),o.set(`decor:${e.id}:${t.id}`,Qi(t.text,t,n,e=>!!n.entities?.[e]&&!!n.states?.[e]&&!Qd(n,e,Jd(this._markers))))}const h=Nd(n,this._devices,null,this._virtualLights);for(const e of this._devices){for(const t of[!1,!0])r.set(v_(e.id,t),__(n,e,{liveStates:!1!==this._config?.live_states,showTemperature:!1!==this._config?.show_temperature,showSignal:t,activityRuntime:this._activityRt.get(e.id),sourceDetails:!1,lightDevices:this._devices,lightSources:h,registryHass:this._fullRegistryHass,reducedMotion:this._reducedMotion}));if(this._isVacDev(e)){const t=this._vacSource(e,n),i=t?Uc(n?.states?.[t]?.attributes):null,r=this._vacRt.get(e.id),s=ch(e.id,e.marker?.vacuum??null,e.space,t),a=dh({routes:s,observed:uh(s,[t],t=>this._vacObservedMapId(e,t,n)),spaceIds:new Set(this._model.map(e=>e.id))});o.set(`vacuum:${e.id}`,{source:t,telemetry:i,routes:s,resolution:a,mapId:i?this._vacMapId(e,i,n):null,runtime:r?{trail:r.trail,lastTs:r.lastTs,moving:r.moving,jump:r.jump}:null,server:this._vacSrvTrails[e.id]||null})}}const d=f_({sourceSequence:this._hassSequence,hass:n,devices:this._devices,presentations:r,positions:(u=this._model.length>0,p=this._devices,_=e=>this._livePos(e),u?new Map(p.map(e=>[e.id,_(e)])):new Map),facts:o,entityIds:s,deviceIds:a,areaIds:l});var u,p,_;this._capturedSnapshotSequence=this._hassSequence,this._capturedSnapshotDevices=this._devices,this._capturedSnapshotLayout=this._layout,this._capturedSnapshotActivity=t,this._capturedSnapshotConfigEpoch=this._cfgEpoch,this._capturedSnapshotVirtual=i,this._visibleDeviceSnapshot&&"steady"!==this._continuity.state?this._candidateDeviceSnapshot=d:(this._visibleDeviceSnapshot=d,this._candidateDeviceSnapshot=null)}get _renderDeviceSnapshot(){return this._stagedDeviceSnapshotToken===this._continuity.token?this._candidateDeviceSnapshot||this._visibleDeviceSnapshot:this._visibleDeviceSnapshot||this._candidateDeviceSnapshot}get _renderPlanHass(){return this._renderDeviceSnapshot?.hass||this._planHass}get _renderDevices(){return this._renderDeviceSnapshot?.devices||this._devices}get _renderVacuumDevices(){return this._renderDeviceSnapshot?.vacuumDevices||this._devices}get _fullRegistryHass(){return this._planHass,this._planHassMemo?.full||this.hass}_bindingStatus(e){return ud(this.hass,e,this._haRegistry)}houseplanDiagnostics(){const{registry:e,bindings:t}=this._renderLife.diagnostics(this.hass,this._markers,e=>this._bindingStatus(e));return{registry:{...e,lastSuccessAgeMs:e.lastSuccess?Math.max(0,Date.now()-e.lastSuccess):null},bindings:t}}_openBindingInHa(e){const[t,i]=e.split(":");if(i)if("device"!==t){if("entity"===t){const e=this._fullRegistryHass.entities?.[i];e?.device_id&&vv("/config/devices/device/"+encodeURIComponent(e.device_id))}}else vv("/config/devices/device/"+encodeURIComponent(i))}_bindingHasHaPage(e){const[t,i]=e.split(":");return!!i&&("device"===t||"entity"===t&&!!this._fullRegistryHass.entities?.[i]?.device_id)}_toggleMarkerDialogVisibility(){const e=this._markerDialog;if(!e)return;const t="ha"===e.bindingMode?this._bindingStatus(e.binding):null,i=e.hideFromPlan||"ha_disabled"===t?.kind;i&&"ha_disabled"===t?.kind?this._showToast(this._t("entity"===t.reason?"toast.ha_disabled_show_entity":"toast.ha_disabled_show_device")):i&&"unverified"===t?.kind?this._showToast(this._t("toast.ha_binding_unverified")):this._markerDialog={...e,hideFromPlan:!i}}_hookConnection(){const e=this.hass?.connection;e&&e!==this._connHooked&&(this._connHooked?.removeEventListener?.("ready",this._onConnReady),this._connHooked?.removeEventListener?.("disconnected",this._onConnLost),this._connHooked?.removeEventListener?.("reconnect-error",this._onConnLost),e.addEventListener?.("ready",this._onConnReady),e.addEventListener?.("disconnected",this._onConnLost),e.addEventListener?.("reconnect-error",this._onConnLost),this._connHooked=e)}_display(e){return this._signer.display(this.hass,e)}_referencedContentUrls(){const e=On(this._serverCfg);for(const t of this._decorAssets.values())e.add(t.url);return e}_resign(){this._signer.resign(this.hass,this._referencedContentUrls())}_onLayoutEvent(e){e<=this._layoutRev||(clearTimeout(this._layoutSyncTimer),this._layoutSyncTimer=window.setTimeout(()=>{e<=this._layoutRev||this._reloadLayoutOnly()},200))}_noteLayoutRev(e){this._adoption.noteLayoutRevision(e?.rev)}async _reloadLayoutOnly(){if(!this._serverStorage||!this.hass?.callWS)return;this._beginContinuityCandidate("layout-reload",!1);const e=new Map;for(const t of this._dirtyPos)this._layout[t]&&e.set(t,this._layout[t]);this._persistLayout.pending()&&this._persistLayout.flush();for(const[t,i]of this._sentPos)e.set(t,i);try{const t=await this.hass.callWS({type:"houseplan/layout/get"}),i={...t?.layout||{}};for(const[t,n]of e)null===n?delete i[t]:i[t]=n;this._adoption.adoptMergedLayout(i,t,()=>{this._cancelDeviceDrag(),this._devicePositionHistory.clear()}),this._canOptimizeUndo=!!t?.can_optimize_undo,this._undoKind=t?.undo_kind||null,this._cacheSnapshot(),this.requestUpdate()}catch{}finally{this._continuityDataReady=!0,this.requestUpdate()}}_persistLocalLayout(){this._layout=ko(so(this._layout)),localStorage.setItem(cv,JSON.stringify(this._layout))}_maybeRebuildDevices(){const e=this.hass;if(!e?.devices||!e?.entities||!e?.areas)return;const t=this._haRegistry,i=sd(e,t)+":"+Object.keys(e.areas).length+":"+(this._norm?"n":"l")+":"+xp(e,this._config?.language);if(i===this._regSignature&&this._devices.length)return;this._regSignature=i;const n=new Map(this._devices.map(e=>[e.id,e.bindingStatus?.kind||"active"]));this._devices=nu({hass:e,registry:t,areaToSpace:Object.fromEntries(Object.entries(this._areaToSpace).map(([e,t])=>[e,t.space])),markers:this._markers,settings:this._settings,excluded:this._excluded,showAll:this._showAll,firstSpaceId:this._model[0]?.id||"",loc:e=>this._t(e),iconRules:this._iconRules});const r=this._markers.filter(e=>!e.removed&&"virtual"!==e.binding).map(e=>e.binding).sort(),o=t.revision+":"+r.join("|");if(t.authoritative&&o!==this._haBindingCacheKey){const i=new Map;for(const n of r)i.set(n,ud(e,n,t));!function(e){if("undefined"==typeof localStorage||!e.size)return;const t=dd(),i=Date.now();for(const[n,r]of e)"active"===r.kind?t[n]={kind:"active",ts:i}:"ha_disabled"===r.kind&&(t[n]={kind:"ha_disabled",reason:r.reason,ts:i});const n=Object.fromEntries(Object.entries(t).sort((e,t)=>t[1].ts-e[1].ts).slice(0,1500));Xh=n;try{localStorage.setItem(Yh,JSON.stringify(n))}catch{}}(i),this._haBindingCacheKey=o}let s=null;if(t.authoritative&&(s=this._resolveAreaRelocations(t),this._areaRelocationIds=new Set(s.relocateIds),this._areaRelocationIds.size)){this._cancelDeviceDrag();const e=this._areaRelocationIds;this._devicePositionHistory.removeWhere(({before:t,after:i})=>e.has(t.deviceId)||e.has(i.deviceId));const t=this._markerDialog;if(t?.devId&&!t.roomTouched&&this._areaRelocationIds.has(t.devId)){const e=this._devices.find(e=>e.id===t.devId);e&&(this._markerDialog={...t,room:e.marker?.room_id?`${e.space}#@${e.marker.room_id}`:e.space&&e.area?`${e.space}#${e.area}`:""})}}this._defPos=this._defaultPositions(),this._syncNewDevices(),this._seedHiddenDevices(),s&&this._syncAreaRelocations(s),this._syncActivityRuntime();const a=new Set(this._devices.filter(e=>!e.hidden).map(e=>e.id));for(const e of this._vacRt.keys())a.has(e)||this._vacRt.delete(e);if(this._infoCard){const e=this._devices.find(e=>e.id===this._infoCard.id);this._infoCard=e&&"ha_disabled"!==e.bindingStatus?.kind?e:null}const l=this._devices.some(e=>"ha_disabled"===e.bindingStatus?.kind&&"ha_disabled"!==n.get(e.id));l&&("ha_disabled"!==this._infoCard?.bindingStatus?.kind&&"ha_disabled"!==this._devices.find(e=>e.id===this._infoCard?.id)?.bindingStatus?.kind||this._closeInfoCard(),this._deviceDrag&&"ha_disabled"===this._devices.find(e=>e.id===this._deviceDrag.id)?.bindingStatus?.kind&&(this._cancelDeviceDrag(),this._devicePositionHistory.clear()),clearTimeout(this._holdTimer),this._holdFired=!1,this._tip=null,this._tapConfirm=null),this._nativeMoreInfoEntity&&!this._planEntityAvailable(this._nativeMoreInfoEntity)&&(fv(this,"hass-more-info",{entityId:null}),this._nativeMoreInfoEntity=null)}_resolveAreaRelocations(e=this._haRegistry){const t=function(e){const t=em(e.snapshot),i=new Set(Object.values(t).map(e=>e.binding)),n=new Map;for(const[t,r]of e.previousCandidates||[])Q_(t)&&Number.isFinite(r)&&i.has(t)&&n.set(t,r);const r=new Set,o=new Set;for(const t of e.markers||[])t.removed||(J_(t.id)&&r.add(t.id),Q_(t.binding)&&o.add(t.binding));const s=new Set(Object.keys(e.registryDevices||{})),a=new Set(Object.keys(e.registryEntities||{})),l=new Set(Object.keys(e.liveStates||{})),c=new Map;for(const[e,i]of Object.entries(t)){const t=c.get(i.binding)||[];t.push(e),c.set(i.binding,t)}const h=new Set;let d=!1;for(const[t,i]of c){const[c,u]=om(t);if(o.has(t)||i.some(e=>r.has(e))||("device"===c?s.has(u):a.has(u)||l.has(u))){n.delete(t);continue}const p="device"===c?s.size>0:a.size>0;if(!e.authoritative||!p)continue;const _=n.get(t);if(void 0!==_){if(_!==e.revision)for(const e of i)h.add(e)}else n.set(t,e.revision),d=!0}return{removeIds:h,candidates:n,needsConfirmationRefresh:d}}({snapshot:this._settings.marker_area_snapshot,authoritative:e.authoritative,revision:e.revision,registryDevices:e.devices,registryEntities:e.entities,liveStates:this.hass?.states,markers:this._markers,previousCandidates:this._areaSnapshotCleanupCandidates});return this._areaSnapshotCleanupCandidates=t.candidates,t.needsConfirmationRefresh&&this._canEdit&&nd(this.hass),sm({devices:this._devices,model:this._model,layout:this._layout,snapshot:this._settings.marker_area_snapshot,authoritative:e.authoritative,cleanupSnapshotIds:t.removeIds,coordinateScale:mv})}_syncNewDevices(){if(!this._norm||!this._loadOk||!this._serverCfg)return;const e=this._devices.filter(e=>!e.marker&&!e.virtual).map(e=>e.id).sort(),t=e.join(",");if(t===this._newSyncKey)return;this._newSyncKey=t;const i=this._settings,{fresh:n,known:r}=function(e,t){if(!Array.isArray(t))return{fresh:[],known:[...e]};const i=new Set(t),n=e.filter(e=>!i.has(e));return{fresh:n,known:n.length?[...t,...n]:t}}(e,i.known_devices);if(!Array.isArray(i.known_devices)||n.length){const e=[...new Set([...i.new_device_ids||[],...n])];this._serverCfg={...this._serverCfg,settings:{...i,known_devices:r,new_device_ids:e}},this._saveConfig()}}_syncAreaRelocations(e){if(!(this._loadOk&&this._serverCfg&&this._norm&&this._canEdit&&this._haRegistry.authoritative))return;const t=e.decisions.filter(e=>e.updateSnapshot||e.removeSnapshot);if(!t.length)return;const i=hc({snapshot:em(this._settings.marker_area_snapshot),decisions:t});i!==this._areaRelocationSyncKey&&(this._areaRelocationSyncKey=i,this._areaRelocationWrite=this._areaRelocationWrite.catch(()=>{}).then(async()=>{if(!this._serverCfg||!this._haRegistry.authoritative)return;const e=this._resolveAreaRelocations();this._areaRelocationIds=new Set(e.relocateIds);const t=new Set,i=new Map;let n=!1;for(const r of e.decisions){if(!r.relocate)continue;const e=vg(this._layout,r.id);try{await this._persistDevicePlacement(r.id,null),t.add(r.id),e&&i.set(r.id,e),this._areaRelocationIds.delete(r.id)}catch(t){n=!0,this._layout=yg(this._layout,r.id,e),this._showToast(this._t("toast.pos_save_failed",{err:this._errText(t)}))}}const r=this._settings,o=function(e,t,i=new Set){const n=em(e);for(const e of t.decisions)e.removeSnapshot?delete n[e.id]:e.updateSnapshot&&e.binding&&e.area&&(e.relocate&&!i.has(e.id)||(n[e.id]={binding:e.binding,area:e.area}));return n}(r.marker_area_snapshot,e,t),s=[...new Set([...Array.isArray(r.new_device_ids)?r.new_device_ids:[],...t])],a=hc(o)!==hc(em(r.marker_area_snapshot)),l=hc(s)!==hc(Array.isArray(r.new_device_ids)?r.new_device_ids:[]);if(a||l){const e=r.marker_area_snapshot,n=r.new_device_ids,a={...this._serverCfg,settings:{...r,marker_area_snapshot:o,...l?{new_device_ids:s}:{}}};this._setAreaLifecycleConfig(a);try{this._saveConfigDebounced.pending()&&this._saveConfigDebounced.cancel(),await this._writeConfig()}catch(r){const a=this._settings;if(hc(a.marker_area_snapshot)===hc(o)&&hc(a.new_device_ids)===hc(l?s:n)){const t={...a};void 0===e?delete t.marker_area_snapshot:t.marker_area_snapshot=e,void 0===n?delete t.new_device_ids:t.new_device_ids=n;const i={...this._serverCfg,settings:t};this._setAreaLifecycleConfig(i),this._adoption.refreshConfigFingerprint()}for(const e of t)this._areaRelocationIds.add(e);const c=new Set;for(const[e,t]of i)try{await this._persistDevicePlacement(e,t)}catch(t){c.add(e),this._showToast(this._t("toast.pos_save_failed",{err:this._errText(t)}))}this._areaRelocationSyncKey="",this._regSignature="";if("conflict"===(r&&"object"==typeof r&&"code"in r?r.code:void 0)?(this._showToast(this._t("toast.conflict")),await this._reloadConfigOnly(!0)):this._showToast(this._t("toast.cfg_save_failed",{err:this._errText(r)})),c.size&&this._serverCfg){const e=this._settings,t=[...new Set([...Array.isArray(e.new_device_ids)?e.new_device_ids:[],...c])],i={...this._serverCfg,settings:{...e,new_device_ids:t}};this._setAreaLifecycleConfig(i);try{await this._writeConfig()}catch(e){this._showToast(this._t("toast.cfg_save_failed",{err:this._errText(e)}))}}}}n&&(this._areaRelocationSyncKey=""),this.requestUpdate()}))}get _newIds(){const e=this._settings.new_device_ids;return new Set([...Array.isArray(e)?e:[],...this._areaRelocationIds])}_ackNewDevice(e){if(!this._newIds.has(e)||!this._serverCfg)return;const t=this._settings;this._serverCfg={...this._serverCfg,settings:{...t,new_device_ids:(t.new_device_ids||[]).filter(t=>t!==e)}},this._saveConfig(),this.requestUpdate()}get _markers(){return this._serverCfg?.markers||[]}_roomLqi(e){if(!e)return null;const t=[];for(const i of this._renderDevices){if(i.area!==e||i.virtual)continue;const n=Bd(this._renderPlanHass,i.entities);null!=n&&t.push(n)}return Ii(t)}_roomBounds(e){if(e.poly&&e.poly.length){const t=e.poly.map(e=>e[0]),i=e.poly.map(e=>e[1]),n=Math.min(...t),r=Math.min(...i);return{x:n,y:r,w:Math.max(...t)-n,h:Math.max(...i)-r}}return{x:e.x??0,y:e.y??0,w:e.w??0,h:e.h??0}}_defaultPositions(){const e={},t=this._config?.icon_size??2.5;for(const i of this._model){const n=t/100*Sl(i)*1.3;for(const t of i.rooms){if(!t.area)continue;const r=this._devices.filter(e=>e.area===t.area&&e.space===i.id);if(!r.length)continue;const o=this._roomBounds(t),s=.1*Math.min(o.w,o.h),a=o.w-2*s,l=o.h-2*s,c=Math.max(1,Math.round(Math.sqrt(r.length*a/Math.max(l,1)))),h=Math.ceil(r.length/c),d=a/c,u=l/Math.max(h,1),p=r.map((e,t)=>({x:o.x+s+d*(t%c+.5),y:o.y+s+u*(Math.floor(t/c)+.5)}));Ei(p,o,n,.5*s),r.forEach((t,i)=>e[t.id]=ol(p[i]))}}return e}_pos(e){const t=this._renderDeviceSnapshot?.positions.get(e.id);return t?{x:t.x,y:t.y}:this._livePos(e)}_livePos(e){const t=this._spaceModelById(e.space),i=this._areaRelocationIds.has(e.id)?void 0:this._layout[e.id];if(i)if(this._norm){if(i.s===e.space)return{x:i.x*mv,y:i.y*mv}}else if(void 0===i.s)return{x:i.x,y:i.y};return this._defPos[e.id]?this._defPos[e.id]:t?ol(xl(t)):{x:500,y:500}}_devicePlacementForCanvas(e,t,i){if(!this._norm)return{x:Math.round(t),y:Math.round(i)};const n=this._gridPitch,r=Math.round(t/n)*n,o=Math.round(i/n)*n;return{s:e.space,x:al(r/mv),y:al(o/mv)}}_previewDevicePlacement(e,t){this._layout=yg(this._layout,e,t),this.requestUpdate()}_cancelDeviceDrag(){const e=this._deviceDrag;if(!e)return!1;this._editorRuntime?._cancelPointerMove("device"),this._deviceDrag=null,this._deviceHits.cancel(e.pointerId);try{e.source?.hasPointerCapture?.(e.pointerId)&&e.source.releasePointerCapture(e.pointerId)}catch{}return this._previewDevicePlacement(e.id,e.before),!0}async _persistDevicePlacement(e,t){if(this._layout=yg(this._layout,e,t),this._serverStorage){let i=null,n=!1;try{let r;if(null===t)i=null,this._sentPos.set(e,i),n=!0,r=await this.hass.callWS({type:"houseplan/layout/delete",device_id:e});else{const t=wo(this._layout[e]);hc(t)!==hc(this._layout[e])&&(this._layout={...this._layout,[e]:t}),i=t,this._sentPos.set(e,i),n=!0,r=await this.hass.callWS({type:"houseplan/layout/update",device_id:e,pos:t})}this._noteLayoutRev(r),this._adoption.refreshLayoutFingerprint(),this._cacheSnapshot()}finally{n&&this._sentPos.get(e)===i&&this._sentPos.delete(e)}return}this._persistLocalLayout()}_devicePositionStateValid(e){const t=this._devices.find(t=>t.id===e.deviceId);return!!t&&t.space===e.spaceId&&"ha_disabled"!==t.bindingStatus?.kind&&!!this._spaceModelById(e.spaceId)}async _runDevicePositionHistory(e){if(this._cancelDeviceDrag()||this._devicePositionBusy)return;const t="undo"===e?this._devicePositionHistory.undo():this._devicePositionHistory.redo();if(!t)return;const i="undo"===e?t.before:t.after;if(!this._devicePositionStateValid(i))return this._devicePositionHistory.clear(),this._showToast(this._t("history.device_stale")),void this.requestUpdate();const n=vg(this._layout,i.deviceId);i.spaceId!==this._space&&(this._commitSpace(i.spaceId),this._restoreZoom()),this._devicePositionBusy=!0,this._previewDevicePlacement(i.deviceId,i.placement);try{await this._persistDevicePlacement(i.deviceId,i.placement),this._showToast(this._t("undo"===e?"history.undone":"history.redone",{name:t.name}))}catch(t){this._previewDevicePlacement(i.deviceId,n),"undo"===e?this._devicePositionHistory.redo():this._devicePositionHistory.undo(),this._showToast(this._t("toast.pos_save_failed",{err:this._errText(t)}))}finally{this._devicePositionBusy=!1,this.requestUpdate()}}_undoDevicePosition(){this._runDevicePositionHistory("undo")}_redoDevicePosition(){this._runDevicePositionHistory("redo")}_savePos(e,t,i){this._spaceModelById(e.space)&&(this._layout=yg(this._layout,e.id,this._devicePlacementForCanvas(e,t,i)),this._dirtyPos.add(e.id),this._persistLayout())}_devicePresentation(e,t=!1!==this._config?.show_signal,i=!1){const n=i?null:this._renderDeviceSnapshot?.presentations.get(v_(e.id,t));return n||__(this._renderPlanHass,e,{liveStates:!1!==this._config?.live_states,showTemperature:!1!==this._config?.show_temperature,showSignal:t,designPreview:i,activityRuntime:this._activityRt.get(e.id),sourceDetails:!1,lightDevices:this._renderDevices,registryHass:this._fullRegistryHass,reducedMotion:this._reducedMotion})}_deviceVisual(e){return this._devicePresentation(e).visual}_stateClass(e,t=this._deviceVisual(e)){const i=this._devicePresentation(e);return i.effectiveHidden?"":("icon_ripple"!==i.display||!1===this._config?.live_states||"alarm"===t.status||t.activity,p_({...i,visual:t}).join(" "))}_liveTemp(e){if(!this._config?.show_temperature)return null;if(!0===e.marker?.use_climate_temp){const t=jd(this._renderPlanHass,e.entities);if(null!=t)return t}return"mdi:thermometer"!==e.icon&&"mdi:air-filter"!==e.icon?null:qd(this._renderPlanHass,e.entities)}_bindingEntities(e){if("virtual"===e||!e)return[];const t=this._bindingStatus(e);return"active"===t.kind?t.enabledEntityIds:t.allEntityIds}_bindingHasClimate(e){return this._bindingEntities(e).some(e=>e.startsWith("climate."))}_bindingHasAlarm(e){return this._bindingEntities(e).some(e=>{const t=this._planHass?.states?.[e]||this.hass?.states?.[e],i=this._fullRegistryHass.entities[e]||this.hass?.entities?.[e];return Vn(e.split(".")[0],t?.attributes?.device_class||i?.device_class||i?.original_device_class)})}_deviceBindingActive(e,t=!0){if(e.virtual||"virtual"===e.bindingKind)return!0;if(!e.bindingKind||!e.bindingRef)return!1;const i=this._bindingStatus(`${e.bindingKind}:${e.bindingRef}`);return"active"===i.kind||(t&&this._showToast(this._t("ha_disabled"===i.kind?"toast.ha_disabled_action":"toast.ha_binding_unverified")),!1)}_openMoreInfo(e){e?this._planEntityAvailable(e)?(this._kiosk&&(this._cyclePausedUntil=Math.max(this._cyclePausedUntil,Date.now()+6e4)),this._nativeMoreInfoEntity=e,fv(this,"hass-more-info",{entityId:e})):this._showToast(this._t("toast.ha_disabled_action")):this._showToast(this._t("toast.no_entity"))}_interruptViewGesture(e,t){if(clearTimeout(this._holdTimer),clearTimeout(this._kioskHoldTimer),void 0!==e)for(const i of[t,this._stageEl])try{i?.hasPointerCapture?.(e)&&i.releasePointerCapture(e)}catch{}this._pointers.clear(),this._panStart=null,this._panLock=null,this._pinchStart=null,this._swipeStart=null,this._roomPointer=null,this._doubleFit.clear(),this._deviceHits.clearPointers()}_closeInfoCard(){this._interruptViewGesture(),this._holdFired=!1,this._infoCard=null}_invalidateDeviceHitGeometry(){this._deviceHits.invalidate()}_resetDeviceHitState(){this._deviceHits.reset(this.renderRoot)}_deviceHitOwnerAt(e,t){return"view"!==this._mode&&"devices"!==this._mode?null:this._deviceHits.at(this.renderRoot,this._renderDevices,this._space,e,t)}_deviceForPointerEvent(e,t){return this._deviceHits.pointer(this.renderRoot,this._renderDevices,this._space,e,t)}_deviceForClickEvent(e,t){return this._deviceHits.click(this.renderRoot,this._renderDevices,this._space,e,t)}_showDeviceTip(e,t){this._liveRt?this._liveRt.devicePointerTip(e,t):this._ensureLiveRuntime().then(()=>this._liveRt?.devicePointerTip(e,t))}_showDeviceFocusTip(e,t){const i=e.currentTarget;this._liveRt?this._liveRt.deviceFocusTip(i,t):this._ensureLiveRuntime().then(()=>this._liveRt?.deviceFocusTip(i,t))}_hideDeviceFocusTip(e){this._liveRt?.deviceBlur(e)}_clearPointerHover(){this._liveRt?this._liveRt.pointerLeave():this._clearTransientHover()}_ctxDevice(e,t){"view"===this._mode&&(t=this._deviceForPointerEvent(e,t),e.preventDefault(),e.stopPropagation(),this._deviceBindingActive(t)&&(t.primary?this._openMoreInfo(t.primary):this._infoCard=t))}_clickDevice(e,t){if("view"!==this._mode&&"devices"!==this._mode)return;if(e.stopPropagation(),t=this._deviceForClickEvent(e,t),this._deviceDrag?.moved||this._suppressClick||this._holdFired)return;if("devices"===this._mode)return void this._openMarkerDialog(t);const i=this._devices.find(e=>e.id===t.id);if(!i)return;const n=Du(i.tapAction,i.primary?.split(".")[0]);if("none"===n)return;const r=(e,t)=>{i.marker?.tap_confirm?this._tapConfirm={kind:"run",text:e,exec:t}:t()};if("toggle"===n){const e=this._toggleIntent(i);if(!e)return;if(!Ou(e))return void this._showUnavailableToggleTargets(e);const t=e=>{const t=Ou(e);if(!t)return;if("virtual-light"===t.kind)return this._startDevicePressFeedback(i.id),void this.hass.callWS({type:"houseplan/virtual_light/toggle",marker_id:t.markerId}).then(e=>{const t=Uh(this._virtualLights,e);t!==this._virtualLights&&(this._virtualLights=t,this._capturedSnapshotVirtual="",this._cacheSnapshot(),this.requestUpdate())}).catch(e=>this._showToast(this._t("toast.virtual_light_toggle_failed",{err:this._errText(e)})));const{command:n}=t;this._startDevicePressFeedback(i.id),this.hass.callService(n.domain,n.service,n.data).catch(e=>this._showToast(this._t("toast.error",{err:this._errText(e)})))},n=((o=e).targets.length?o.targets:o.skippedTargets).map(e=>e.name||e.entityId||e.ref).join(", ")||i.name;if(i.marker?.tap_confirm){const r=this._toggleConfirmationLines(e);if(!r.length)return;this._tapConfirm={kind:"toggle",text:this._t("confirm.tap_toggle",{name:n}),lines:r,initialIntent:e,deviceId:i.id,exec:()=>{const n=this._devices.find(e=>e.id===i.id),r=n?this._toggleIntent(n):null;r&&!Ou(r)&&this._showUnavailableToggleTargets(r)||(r&&Nu(e,r)?t(r):this._showToast(this._t("toast.tap_target_changed")))}}}else t(e);return}var o;if("info"===n)return this._interruptViewGesture(),void(this._infoCard=i);if(this._deviceBindingActive(i)){if("run"===n){const e=i.marker?.tap_target||"",t=function(e){const t=String(e||"").split(".")[0];return"automation"===t?{domain:"automation",service:"trigger"}:"script"===t?{domain:"script",service:"turn_on"}:"scene"===t?{domain:"scene",service:"turn_on"}:null}(e),n=this.hass.states[e];if(!t||!n)return void this._showToast(this._t("toast.run_target_missing"));const o=n.attributes?.friendly_name||e;return void r(this._t("confirm.tap_run",{name:o}),()=>{this._deviceBindingActive(i)&&this._planEntityAvailable(e)&&(this._startDevicePressFeedback(i.id),this.hass.callService(t.domain,t.service,{entity_id:e}).then(()=>{this._stampActivity(i.id,"event",this._activitySourceKey(i)),this.requestUpdate(),this._showToast(this._t("toast.run_started",{name:o}))}).catch(e=>this._showToast(this._t("toast.error",{err:this._errText(e)}))))})}"more-info"===n&&i.primary?this._openMoreInfo(i.primary):this._infoCard=i}}_showUnavailableToggleTargets(e){const t=function(e){if(!e||"group"!==e.kind||Ou(e)||"configured-targets-missing"!==e.noneReason)return[];if(!e.skippedTargets.length||e.skippedTargets.some(e=>!Eu.has(e.reason)&&"secure"!==e.reason))return[];const t=[],i=new Set;for(const n of e.skippedTargets){if(!Eu.has(n.reason))continue;const e=String(n.name||n.entityId||n.ref||"").trim();e&&!i.has(e)&&(i.add(e),t.push(e))}return t}(e);return!!t.length&&(this._showToast(1===t.length?this._t("toast.toggle_target_unavailable",{name:t[0]}):this._t("toast.toggle_targets_unavailable",{names:t.join(", ")})),!0)}_keyDevice(e,t){"Enter"!==e.key&&" "!==e.key||"view"!==this._mode&&"devices"!==this._mode||(e.preventDefault(),this._clickDevice(e,t))}_startDevicePressFeedback(e){const t=[...this.renderRoot.querySelectorAll(".dev[data-id]")].find(t=>t.dataset.id===e),i=t?.querySelector(".device-shell");if(!i||"function"!=typeof i.animate)return;const n=Number.parseFloat(this.ownerDocument.defaultView?.getComputedStyle(i).scale||""),r=Number.isFinite(n)?Math.max(.95,Math.min(1,n)):1;this._devicePressAnimations.get(e)?.cancel();const o=this._reducedMotion?[{outlineColor:"transparent",outlineStyle:"solid",outlineWidth:"0px"},{outlineColor:"var(--hp-accent, #3ea6ff)",outlineStyle:"solid",outlineWidth:"2px",outlineOffset:"2px",offset:.5},{outlineColor:"transparent",outlineStyle:"solid",outlineWidth:"0px"}]:[{scale:String(r)},{scale:"0.95",offset:.5},{scale:"1"}],s=i.animate(o,{duration:200,easing:"cubic-bezier(.22,.61,.36,1)"});this._devicePressAnimations.set(e,s);const a=()=>{this._devicePressAnimations.get(e)===s&&this._devicePressAnimations.delete(e)};s.addEventListener("finish",a,{once:!0}),s.addEventListener("cancel",a,{once:!0})}_cancelDevicePressFeedback(){for(const e of this._devicePressAnimations.values())e.cancel();this._devicePressAnimations.clear()}_pruneDevicePressFeedback(){if(!this._devicePressAnimations.size)return;const e=new Set([...this.renderRoot.querySelectorAll(".dev[data-id]")].map(e=>e.dataset.id||""));for(const[t,i]of this._devicePressAnimations)e.has(t)||(i.cancel(),this._devicePressAnimations.delete(t))}_t(e,t){return Sp(xp(this.hass,this._config?.language),e,t)}get _colorPickerLabels(){return{title:this._t("color_picker.title"),hue:this._t("color_picker.hue"),saturation:this._t("color_picker.saturation"),value:this._t("color_picker.value"),hex:this._t("color_picker.hex"),invalidHex:this._t("color_picker.invalid_hex"),confirm:this._t("color_picker.confirm")}}_help(e){return this._editorRuntimeOrThrow()._help(e)}get _stageEl(){return this.renderRoot.querySelector(".stage")}_contentItems(e){const t=[];for(const i of this._devices){if(i.space!==e.id||i.hidden)continue;const n=this._pos(i);t.push({minX:n.x,minY:n.y,maxX:n.x,maxY:n.y})}if(e.id===this._space){for(const e of this._openingsR){const i=Number(e.angle)*Math.PI/180,n=Math.cos(i)*e.rlen/2,r=Math.sin(i)*e.rlen/2,o=dl([[e.rx-n,e.ry-r],[e.rx+n,e.ry+r]]);o&&t.push(o)}const i=this._decorH;for(const e of this._decorList){if("image"===e.kind&&!this._decorAssets.has(e.asset_id)&&"decor"!==this._mode)continue;const n=dl("line"===e.kind?[[e.x1*mv,e.y1*i],[e.x2*mv,e.y2*i]]:"text"===e.kind?[[e.x*mv,e.y*i]]:Or({x:e.x*mv,y:e.y*i,w:e.w*mv,h:e.h*i,angle:e.angle}));n&&t.push(n)}for(const i of this._physicalBodiesR(e)){const e=dl(i);e&&t.push(e)}}return gl(e,t)}_frameOf(){const e=this._spaceModel();if(!e){this._frame=null;const e={x:0,y:0,w:mv,h:mv};return{rect:e,all:e,outliers:0}}const t=this._frame,i="view"!==this._mode;if(t&&t.id===e.id&&this._bdDrag)return t;if(t&&t.id===e.id&&t.model===e&&t.layout===this._layout&&t.devs===this._devices&&t.far===this._showFar&&t.grow===i)return t;const n=bl(this._contentItems(e));let r=n.all||kl(e),o=this._showFar?r:n.core||kl(e);return t&&t.id===e.id&&i&&t.grow&&(o=gv(t.rect,o),r=gv(t.all,r)),this._frame={id:e.id,model:e,layout:this._layout,devs:this._devices,far:this._showFar,grow:i,rect:o,all:r,outliers:n.outliers},this._frame}_isoSource(){const e=this._isoSceneRuntime;if(!e)return null;const t=this._spaceModel();if(!t)return null;const i=this._spaceWalls,n=this._openCuts(),r=this._openingsR;return e.createIsoStructuralSource({space:t,walls:i,openCuts:n,openings:r,partitionCuts:()=>this._partitionOpeningCuts(t),roomOpenings:()=>this._roomWallOpeningInputs(r,t),cellCm:this._cellCm,gridPitch:this._gridPitch,wallKeyPitch:this._wallKeyPitch,coordinateScale:mv,onBuild:()=>{this._isoStructuralBuildCount+=1}})}_isoSceneKey(){if(!this._labsIso||"view"!==this._mode)return null;try{return this._isoSource()?.key??null}catch{return this._isoInvalidKey()}}_isoInvalidKey(){return`${this._space}|invalid|${this._cfgEpoch}`}_clearIsoInvalidFallback(e){const t=`${this._space}|invalid|`;for(const i of this._isoFallback)i.startsWith(t)&&i!==e&&this._isoFallback.delete(i)}_isoScene(e=this._isoSource()){const t=this._isoSceneRuntime;if(!t||!e)return null;let i=this._frameOf().rect;const n=this._spaceDisplayForRender(),r=this._spaceModel();if(r&&n.showNames)for(const e of r.rooms)if(e.name){const t=this._labelPos(e,r.id);i=gv(i,{x:t.x,y:t.y,w:0,h:0})}const o=t.resolveIsoScene({source:e,cache:this._isoGeometryCache,cellCm:this._cellCm,liveFrame:i});if(!r||!n.showBorders)return o;const s=this._config?.icon_size??2.5,a=s>8?2.5:s,l=this._stageEl?.getBoundingClientRect?.()??null,c=l?.height?l.width/l.height:o.frame.w/o.frame.h,h=Oi([o.frame.x,o.frame.y,o.frame.w,o.frame.h],c),d=this._isoOverlayScene(r,this._renderDevices.filter(e=>e.space===r.id&&!e.hidden),h,n,t.resolveIsoDecorationLayers(n),o,a,S_(a),n.showLqi??this._config?.show_signal??!0,!1),u=d&&t.resolveIsoOverlayFitEnvelope({baseBounds:o.frame,entries:d.entries,stageSize:l,targetView:e=>Oi([e.x,e.y,e.w,e.h],c)});return u?{...o,frame:u.bounds,overlayFitEntries:d.entries}:o}_latchIsoFallback(e,t){if(this._isoFallback.has(e))return;this._isoFallback.add(e);const i=e.includes("|invalid|")?"invalid":e.split("|").pop()||"invalid";console.warn("HOUSEPLAN ISO FALLBACK: #89/#160",kf("structural",i,!0))}_effectiveProjection(){if(this._isoProjectionSnapshot)return this._isoProjectionSnapshot;const e=e=>this._isoProjectionSnapshot=e,t=()=>("iso"===this._renderProjection&&(this._cancelCameraTransition(!1),this._view=null,this._viewModeSnap=null),e("flat"));if(this._renderIsoScene=null,"iso"!==this._desiredProjection||!this._model.length||!this._isoSceneRuntime)return e("flat");if(!this._spaceDisplayForRender().showBorders)return this._isoFallback.has(`${this._space}|no-borders`)?t():e("iso");let i=this._isoInvalidKey();if(this._clearIsoInvalidFallback(i),this._isoFallback.has(i))return t();try{const n=this._isoSource();if(!n)return e("flat");if(i=n.key,this._isoFallback.has(i))return t();const r=this._isoScene(n);return r?this._isoFallback.has(r.key)?t():(this._renderIsoScene=r,e("iso")):e("flat")}catch(e){return this._latchIsoFallback(i,e),t()}}_scenePoint(e){return"iso"===this._renderProjection?cf(e,0):e}_floorView(e){if("iso"!==this._renderProjection)return e;const t=hf([e.x,e.y]),i=hf([e.x+e.w,e.y+e.h]);return{x:t[0],y:t[1],w:i[0]-t[0],h:i[1]-t[1]}}_isoOverlayScene(e,t,i,n,r,o,s,a,l,c=!0){const h=this._isoSceneRuntime;return h&&r?.structural&&o?h.buildIsoOverlayRenderScene({space:e,devices:t,openings:this._openingsR,view:i,display:n,wallSilhouettes:o.wallSilhouettes,resolveCollisions:c,iconPct:s,deviceBasePct:a,showLqi:l,cellCm:this._cellCm,kioskIconScale:"view"===this._mode?this._kioskScale.icon:1,kioskFontScale:"view"===this._mode?this._kioskScale.font:1,stageSize:this._stageEl?.getBoundingClientRect?.(),positionOf:e=>this._pos(e),presentationOf:(e,t)=>this._devicePresentation(e,t),labelPositionOf:(e,t)=>this._labelPos(e,t),labelScaleOf:e=>this._labelScale(e),openingEntityAvailable:e=>this._renderOpeningEntityAvailable(e),openingWallIndex:()=>this._openingWallIndexFor(e,this._openCuts()).value}):null}_baseVb(e=this._effectiveProjection(),t=this._renderIsoScene){if("iso"===e){if(!this._spaceDisplayForRender().showBorders){const e=pf({rect:this._frameOf().rect,wallHeight:0});return[e.x,e.y,e.w,e.h]}const e=t?.frame??this._frameOf().rect;return[e.x,e.y,e.w,e.h]}const i=this._frameOf().rect;return[i.x,i.y,i.w,i.h]}get _outliers(){return this._showFar?0:this._frameOf().outliers}_fitFar(){this._clearRoomFocus(),this._showFar=!0,this._frame=null,this.requestUpdate(),this._resetZoom()}_clearRoomFocus(e=!1){this._doubleFit.clear(),this._roomFocus=null,e&&(this._roomPointer=null)}_roomFitBounds(e,t){const i=ni(e);if(!i||!e.id)return null;const n=this._spaceWalls,r=this._openCuts(),o=this._wallUnionGeometry(),s=n.length&&this._innerRoomContour(t,e.id,r,o?.roomGeom,o?.multiWallNodes)||i,a=this._spaceDisplayForRender();let l=[];if(a.showBorders&&n.length){const i=As(t.rooms,e.id,n,r,this._wallKeyPitch,this._cellCm,this._gridPitch,mv);i&&(l=oa(i.poly,i.offsets,o?.multiWallNodes)||i.poly)}const c=this._effectiveProjection();return function(e){const t=e.floor,i=e.wall||[],n=e.padding??0;if(!t.length||!t.every(yf)||!i.every(yf)||!Number.isFinite(n)||n<0)return null;if("flat"===e.projection)return wf([...t,...i],n);const r=e.wallHeight??0,o=e.floorDepth??0;if(!Number.isFinite(r)||r<0||!Number.isFinite(o)||o<0)return null;try{const e=[];for(const i of t){const t=[i[0],i[1]];e.push(cf(t,0)),o>0&&e.push(cf(t,-o))}for(const t of i){const i=[t[0],t[1]];e.push(cf(i,0)),r>0&&e.push(cf(i,r))}return wf(e,n)}catch{return null}}({floor:s,wall:l,projection:c,wallHeight:"iso"===c&&a.showBorders?qa(84,this._cellCm):0,floorDepth:"iso"===c&&a.showBorders?qa(10,this._cellCm):0,padding:a.showBorders?qa(1.25,this._cellCm):0})}_fitRoom(e,t=!0){if("view"!==this._mode)return!1;this._doubleFit.clear();const i=this._spaceModel(),n=i?.rooms.find(t=>t.id===e);if(!i||!n)return this._clearRoomFocus(),!1;let r=this._roomFitBounds(n,i);if(!r)return this._clearRoomFocus(),!1;this._roomFocus={spaceId:i.id,roomId:e};const o=this._stageEl;if(!o||o.clientWidth<=0||o.clientHeight<=0)return!0;const s=Oi(this._baseVb(),o.clientWidth/o.clientHeight),a=e=>function(e){const t=e.safeFraction??.8,{bounds:i,baseFit:n,stageWidth:r,stageHeight:o,minZoom:s,maxZoom:a}=e;if(!bf(i)||!bf(n)||!Number.isFinite(r)||r<=0||!Number.isFinite(o)||o<=0||!Number.isFinite(s)||s<=0||!Number.isFinite(a)||a1)return null;const l=r/o,c=Math.max(i.w/t,i.h/t*l);if(!Number.isFinite(c)||c<=0)return null;const h=Math.min(a,Math.max(s,n.w/c)),d=n.w/h,u=d/l;return{zoom:h,viewBox:{x:i.x+i.w/2-d/2,y:i.y+i.h/2-u/2,w:d,h:u}}}({bounds:e,baseFit:s,stageWidth:o.clientWidth,stageHeight:o.clientHeight,minZoom:kv.ZOOM_MIN,maxZoom:kv.ZOOM_MAX});let l=a(r);const c=this._isoSceneRuntime,h=this._renderIsoScene?.overlayFitEntries;if(l&&"iso"===this._effectiveProjection()&&c&&h?.length){const e=c.resolveIsoOverlayFitEnvelope({baseBounds:r,entries:h,ownerId:n.id,stageSize:{width:o.clientWidth,height:o.clientHeight},targetView:e=>a(e)?.viewBox??null});e&&(r=e.bounds,l=a(r))}if(!l)return this._clearRoomFocus(),!1;const d=this._cameraState(),u=function(e,t,i,n){const r=[e,t,i,n],o=Math.min(...r.map(e=>e.x)),s=Math.min(...r.map(e=>e.y));return{x:o,y:s,w:Math.max(...r.map(e=>e.x+e.w))-o,h:Math.max(...r.map(e=>e.y+e.h))-s}}(s,d.viewBox,l.viewBox,r);return l.viewBox=this._clampView(l.viewBox,u),t?(this._prepareCameraCommand(),this._startCameraTransition(l,u,"room",220),!0):(this._cancelCameraTransition(!1),Zg(d,l)||(this._zoom=l.zoom,this._view={...l.viewBox},this.requestUpdate()),!0)}_fitAll(e="fit"){this._clearRoomFocus(),this._showFar=!0,this._frame=null,this.requestUpdate(),this._resetZoom(e)}_renderFarHint(){return this._kiosk||"view"!==this._mode||this._booting||!this._outliers?G:j`
+ + ${this._t("canvas.far_objects",{n:this._outliers})} + +
`}_renderHomeArrow(e=this._baseVb()){if(this._booting)return G;const t=this._view;if(!t||!t.w||!t.h)return G;const i=e[0],n=e[1],r=e[2],o=e[3];if(!(i+r<=t.x||i>=t.x+t.w||n+o<=t.y||n>=t.y+t.h))return G;const s=Math.atan2(n+o/2-(t.y+t.h/2),i+r/2-(t.x+t.w/2)),a=50+38*Math.cos(s),l=50+38*Math.sin(s);return j``}_stageAspect(e=this._baseVb()){const t=this._stageEl;return t&&t.clientHeight?t.clientWidth/t.clientHeight:e[2]/e[3]}_viewOr(e){return this._view&&this._view.w?this._view:Oi(e,this._stageAspect(e))}_roomLabelReferenceViewWidth(e){if(!this._markup)return e.w;const t=this._viewModeSnap;if(t?.space===this._space&&t.w)return t.w*t.zoom/this._zoom;const i=this._stageEl,n=this.renderRoot.querySelector(".editorchrome");if(!i?.clientWidth||!i.clientHeight)return e.w;const r=i.clientHeight+(n?.offsetHeight||0);return this._viewForModeTarget(this._zoom,void 0,void 0,i.clientWidth,r).w}_screenToVb(e,t){const i=this._stageEl,n=this._viewOr(this._baseVb()),r=i?.clientWidth||1,o=i?.clientHeight||1;return[n.x+e/r*n.w,n.y+t/o*n.h]}_clampView(e,t){const i=(e,t,i,n)=>{const r=1*Math.max(t,n),o=i-r,s=i+n-t+r;return Math.max(Math.min(o,s),Math.min(Math.max(o,s),e))};return{w:e.w,h:e.h,x:i(e.x,e.w,t.x,t.w),y:i(e.y,e.h,t.y,t.h)}}_applyView(e,t,i){this._cancelCameraTransition(!1);const n=this._baseVb(),r=Oi(n,this._stageAspect()),o=Math.min(kv.ZOOM_MAX,Math.max(kv.ZOOM_MIN,e)),s=r.w/o,a=r.h/o,l=this._viewOr(n),c=t??l.x+l.w/2,h=i??l.y+l.h/2,d=this._clampView({x:c-s/2,y:h-a/2,w:s,h:a},r);return!(this._view&&Math.abs(this._zoom-o)<1e-9&&Math.abs(this._view.x-d.x)<1e-6&&Math.abs(this._view.y-d.y)<1e-6&&Math.abs(this._view.w-d.w)<1e-6&&Math.abs(this._view.h-d.h)<1e-6)&&("opening"===this._tool&&(this._cursorPt=null,this._clearOpeningPlacement(!1)),this._zoom=o,this._view=d,this._liveVp(),!0)}_bootWatch(){clearTimeout(this._bootTimer),this._bootStart=Date.now(),this._bootLastH=-1,this._bootLastChange=this._bootStart;const e=()=>{if(!this._booting)return;const t=Date.now(),i=this._stageEl?this._stageEl.clientHeight:0;i!==this._bootLastH&&(this._bootLastH=i,this._bootLastChange=t);const n=t-this._bootStart;var r,o,s;n>=1200||n>=700&&i>0&&t-this._bootLastChange>=250&&(r=zl,o=this._serverCfg,s=Bl,"pending"!==r.state()||!Al(o,s))?this._bootSettled():this._bootTimer=window.setTimeout(e,100)};this._bootTimer=window.setTimeout(e,100)}_bootSettled(){this._booting&&!this._bootSettling&&(this._bootSettling=!0,this._refitView(),this._bootSettleRaf=requestAnimationFrame(()=>{this._bootSettleRaf=0,this._finishBootSettled()}))}_finishBootSettled(){if(!this._booting)return;this._refitView(),this._booting=!1,this._bootSettling=!1;const e=this._stageEl?.clientHeight??0;!this._config?.kiosk&&e>0&&this._warmPatch({hdrH:this._hdrH,stageH:e,vp:this._warmViewportState()},!0),this._bootFading=!0,this._bootTimer=window.setTimeout(()=>{this._bootFading=!1},220),this._bootSoft=!0,clearTimeout(this._bootSoftTimer),this._bootSoftTimer=window.setTimeout(()=>{this._bootSoft=!1},ov)}_bootSoftCancel(){if(!this._bootSoft)return;clearTimeout(this._bootSoftTimer),this._bootSoft=!1;const e=function(e,t,i,n){if(!t)return null;const r=tf(e,t,i);return i||n||null===r||(t.style.height=`calc(100dvh - ${r}px)`),t.classList.remove("hpsettle"),t.getBoundingClientRect(),t.clientWidth<=0||t.clientHeight<=0?null:{headerHeight:r,size:[t.clientWidth,t.clientHeight]}}(this.renderRoot,this._stageEl,this.panelHost,this._kiosk);if(!e)return;null!==e.headerHeight&&(this._hdrH=e.headerHeight),this._refitRaf&&(cancelAnimationFrame(this._refitRaf),this._refitRaf=0),this._pendingRefitSize=null,this._lastValidStageSize=e.size;const t=this._view;t&&this._applyView(this._zoom,t.x+t.w/2,t.y+t.h/2)}_beginResumeSettle(){this._booting||this._resumeSettling||(this._modeTransitionPreparing?this._modeTransitionForceAtomic=!0:this._cancelModeTransition(!0),this._viewportInvalidAt=0,this._beginContinuityCandidate("warm-resume",!1),this._loading?this.requestUpdate():this._loadFromServer())}_refitView(){if(this._modeTransitionBusy||this._warmModeRequest)return;const e=this._stageEl;if(!e||"visible"!==document.visibilityState||e.clientWidth<=0||e.clientHeight<=0)return this._cancelCameraTransition(!1),void(this._viewportInvalidAt||(this._viewportInvalidAt=Date.now()));const t=[e.clientWidth,e.clientHeight];if(this._bootSoft&&this._warmVp)return this._lastValidStageSize=t,void(this._pendingRefitSize=null);const i=this._lastValidStageSize,n=!!i&&Math.abs(i[0]-t[0])<=.5&&Math.abs(i[1]-t[1])<=.5,r=this._viewportInvalidAt?Date.now()-this._viewportInvalidAt:0;if(this._viewportInvalidAt=0,n)this._pendingRefitSize=null;else{if(this._cancelCameraTransition(!1),!i)return this._lastValidStageSize=t,void(this._roomFocus?.spaceId===this._space?this._fitRoom(this._roomFocus.roomId,!1):this._view||this._applyView(this._zoom));this._pendingRefitSize=t,this._refitRaf||(this._refitRaf=requestAnimationFrame(()=>{this._refitRaf=0;const e=this._pendingRefitSize;this._pendingRefitSize=null;const t=this._stageEl;if(!e||!t||t.clientWidth<=0||t.clientHeight<=0)return;if(Math.abs(t.clientWidth-e[0])>.5||Math.abs(t.clientHeight-e[1])>.5)return void this._refitView();const i=this._lastValidStageSize;if(i&&Math.abs(i[0]-e[0])<=.5&&Math.abs(i[1]-e[1])<=.5)return;this._lastValidStageSize=e;const n=this._view;r>=rc?this._beginContinuityCandidate("stage-size-restored",!0,"stage-size"):this._continuity.hasCompleteFrame&&this._beginContinuityCandidate("stage-resize",!0,"stage-size"),this._roomFocus?.spaceId!==this._space?this._applyView(this._zoom,n?n.x+n.w/2:void 0,n?n.y+n.h/2:void 0):this._fitRoom(this._roomFocus.roomId,!1)}))}}_cameraTargetAt(e,t,i,n=!1){const r=this._stageEl;if(!r||r.clientWidth<=0||r.clientHeight<=0)return null;const o=Oi(this._baseVb(),this._stageAspect()),s=Math.min(kv.ZOOM_MAX,Math.max(kv.ZOOM_MIN,i)),a=function(e,t,i,n,r,o,s){if(!Yg(e)||!Yg({zoom:t,viewBox:i})||!Kg(n)||n<=0||!Kg(r)||r<=0||!Kg(o)||!Kg(s))return null;const a=o/n,l=s/r,c=e.viewBox.x+a*e.viewBox.w,h=e.viewBox.y+l*e.viewBox.h,d=i.w/t,u=i.h/t;return{zoom:t,viewBox:{x:c-a*d,y:h-l*u,w:d,h:u}}}(n&&this._cameraTransition.target||this._cameraState(),s,o,r.clientWidth,r.clientHeight,e,t);return a?(a.viewBox=this._clampView(a.viewBox,o),{target:a,fit:o}):null}_zoomAt(e,t,i){this._clearRoomFocus(),this._cancelCameraTransition(!1);const n=this._cameraTargetAt(e,t,i);n&&("opening"===this._tool&&(this._cursorPt=null,this._clearOpeningPlacement(!1)),this._zoom=n.target.zoom,this._view={...n.target.viewBox},this._liveVp())}_onWheel(e){this._clearRoomFocus(),this._prepareCameraCommand();const t=this._stageEl;if(!t)return;e.preventDefault();const i=t.getBoundingClientRect(),n=e.deltaY<0?1.15:1/1.15,r=this._cameraTransition.target?.zoom??this._zoom,o=this._cameraTargetAt(e.clientX-i.left,e.clientY-i.top,r*n,!0);o&&this._startCameraTransition(o.target,o.fit,"wheel",160)}_stepZoom(e){this._clearRoomFocus(),this._prepareCameraCommand();const t=this._stageEl;if(!t)return;const i=this._cameraTransition.target?.zoom??this._zoom,n=this._cameraTargetAt(t.clientWidth/2,t.clientHeight/2,i*(e>0?1.4:1/1.4),!0);n&&this._startCameraTransition(n.target,n.fit,"button",180)}_resetZoom(e="fit"){this._clearRoomFocus(),this._prepareCameraCommand();const t=Oi(this._baseVb(),this._stageAspect());this._startCameraTransition({zoom:1,viewBox:{...t}},t,e,220)}_saveZoom(){if("view"===this._mode){this._zoomBySpace={...this._zoomBySpace,[this._space]:this._zoom};try{localStorage.setItem(dv,JSON.stringify(this._zoomBySpace))}catch{}}}_restoreZoom(){this._clearRoomFocus(!0),this._cancelCameraTransition(!1);const e=this._zoomBySpace[this._space]||1;this._zoom=e;const t=this._stageEl;if(t&&t.clientHeight){const t=this._baseVb();return this._applyView(e,t[0]+t[2]/2,t[1]+t[3]/2),void this.requestUpdate()}this._view=null,requestAnimationFrame(()=>{if(!this._stageEl)return;const t=this._baseVb();this._applyView(e,t[0]+t[2]/2,t[1]+t[3]/2),this.requestUpdate()})}_stagePointerDown(e){this._bootSoftCancel();const t=e.isPrimary&&0===e.button&&"view"===this._mode?ff(e.composedPath()):null;if(this._roomPointer=t?{pointerId:e.pointerId,spaceId:this._space,roomId:t}:null,this._doubleFit.pointerDown(e,this._space,this._doubleFitEnabled),this._cancelCameraTransition(!1,!0),this._vacFit)return;if(this._kiosk&&(this._cyclePausedUntil=Date.now()+6e4,0===this._pointers.size?(this._swipeStart={x:e.clientX,y:e.clientY,id:e.pointerId},e.target.closest?.(".dev, .roomlabel, .oplock")||(clearTimeout(this._kioskHoldTimer),this._kioskHoldTimer=window.setTimeout(()=>{this._roomPointer=null,this._doubleFit.clear(),this._kioskDialog=!0,this._swipeStart=null},3e3))):(this._swipeStart=null,clearTimeout(this._kioskHoldTimer))),this._drag||this._deviceDrag)return;if(this._markup&&e.target.closest?.(".roomlabel, .rlhandle, .rszhandle, .dev, .oplock, .op-hit, button"))return;if("devices"===this._mode&&e.target.closest(".dev"))return;if("decor"===this._mode&&this._decorPointerDown(e))return;this._pointers.set(e.pointerId,{x:e.clientX,y:e.clientY});const i=this._viewOr(this._baseVb());if(1===this._pointers.size)this._panStart={sx:e.clientX,sy:e.clientY,vx:i.x,vy:i.y},this._panLock=null,this._suppressClick=!1;else if(2===this._pointers.size){this._clearRoomFocus(!0),"opening"===this._tool?(this._cursorPt=null,this._clearOpeningPlacement(!1)):"draw"===this._tool&&this._clearPlanSnapHover();const e=[...this._pointers.values()],t=Math.hypot(e[0].x-e[1].x,e[0].y-e[1].y);this._pinchStart={dist:t,zoom:this._zoom},this._panStart=null,this._panLock=null}}get _swipeZone(){return!this._hasFixedFloor&&this._kiosk&&this._zoom<=1.001&&this._model.length>1}_stagePointerMove(e){if(this._physicalRotate?.pid!==e.pointerId)if(this._physicalDrag?.pid!==e.pointerId)if(this._dtDrag?.pid!==e.pointerId)if(this._bdDrag?.pid!==e.pointerId){if(this._decorDraft?.pid===e.pointerId){const t=this._decorDraft;let i=this._decorSnap(this._svgPoint(e),e.pointerType);if(e.shiftKey&&("rect"===t.kind||"ellipse"===t.kind)){const e=i[0]-t.a[0],n=i[1]-t.a[1],r=Math.max(Math.abs(e),Math.abs(n));i=this._snap([t.a[0]+(e<0?-r:r),t.a[1]+(n<0?-r:r)])}return void(this._decorDraft={...t,b:i})}if(this._decorMove?.pid!==e.pointerId){if("decor"!==this._mode||"furniture"!==this._decorTool&&"image"!==this._decorTool||!this._editorRuntime||(this._notePointer(e),!this._editorRuntime._furnPointerMove(e,this._pointerModality.hoverEnabled)))if(this._pointers.has(e.pointerId)){if(this._pointers.set(e.pointerId,{x:e.clientX,y:e.clientY}),this._markup&&1===this._pointers.size&&this._markupMove(e),this._pinchStart&&this._pointers.size>=2){this._clearRoomFocus(!0),"opening"===this._tool?(this._cursorPt=null,this._clearOpeningPlacement(!1)):"draw"===this._tool&&this._clearPlanSnapHover();const e=[...this._pointers.values()],t=Math.hypot(e[0].x-e[1].x,e[0].y-e[1].y)/(this._pinchStart.dist||1),i=this._stageEl.getBoundingClientRect(),n=(e[0].x+e[1].x)/2-i.left,r=(e[0].y+e[1].y)/2-i.top;this._zoomAt(n,r,this._pinchStart.zoom*t),this._viewportGestureDirty=!0,this._suppressClick=!0,this._saveZoom()}else if(this._panStart){const t=e.clientX-this._panStart.sx,i=e.clientY-this._panStart.sy;Math.abs(t)+Math.abs(i)>4&&(this._roomPointer=null,this._doubleFit.clear(),this._suppressClick=!0,clearTimeout(this._holdTimer),"opening"===this._tool?(this._cursorPt=null,this._clearOpeningPlacement(!1)):"draw"===this._tool&&this._clearPlanSnapHover()),null===this._panLock&&Math.abs(t)+Math.abs(i)>8&&(this._panLock=this._swipeZone&&Math.abs(t)>1.5*Math.abs(i)?"swipe":"pan","pan"===this._panLock&&this._clearRoomFocus());const n=this._stageEl;if("pan"===this._panLock&&n){const e=this._baseVb(),r=this._viewOr(e),o=Oi(e,this._stageAspect());this._view=this._clampView({x:this._panStart.vx-t/(n.clientWidth||1)*r.w,y:this._panStart.vy-i/(n.clientHeight||1)*r.h,w:r.w,h:r.h},o),this._viewportGestureDirty=!0,this._liveVp()}}}else this._markupMove(e)}else this._decorMoveUpdate(e)}else this._bdMove(e);else this._dtMove(e);else this._physicalMove(e);else this._physicalRotateMove(e)}_stagePointerLeave(e){this._editorRuntime?._cancelPointerMove("markup-hover"),"decor"===this._mode&&this._editorRuntime?._furnPointerLeave(e),this._markup&&("opening"===this._tool?(this._cursorPt=null,this._clearOpeningPlacement(!1)):"draw"===this._tool&&this._clearPlanSnapHover())}_stagePointerUp(e){this._deviceHits.release(e.pointerId),this._flushHa(),this._editorRuntime?._cancelPointerMove("markup-hover");const t=(i=this._roomPointer,n=e.pointerId,r=this._space,o=this._roomPointer&&"view"===this._mode?ff(e.composedPath()):null,s=this._suppressClick||!!this._pinchStart||null!==this._panLock||this._holdFired||this._touchSequenceMultitouch,!i||s||i.pointerId!==n||i.spaceId!==r||i.roomId!==o?null:i.roomId);var i,n,r,o,s;this._roomPointer?.pointerId===e.pointerId&&(this._roomPointer=null);if(this._doubleFit.pointerUp(e,this._space,this._doubleFitEnabled,this._suppressClick||!!this._pinchStart||null!==this._panLock||this._holdFired)&&this._fitAll("double-tap"),this._kiosk){clearTimeout(this._kioskHoldTimer);const i=this._swipeStart;if(this._swipeStart=null,!t&&i&&i.id===e.pointerId){const t=e.clientX-i.x,n=e.clientY-i.y,r="pan"===this._panLock?null:function(e,t,i,n,r,o=60){if(i>1.001||n.length<2)return null;if(Math.abs(e)e.id),this._space);r&&this._slideTo(r,t<0?"left":"right")&&(this._saveNav(),this._suppressClick=!0,setTimeout(()=>this._suppressClick=!1,0),this._showKioskDots())}}this._physicalDrag?.pid!==e.pointerId?this._physicalRotate?.pid!==e.pointerId?this._dtDrag?.pid!==e.pointerId?this._bdDrag?.pid!==e.pointerId?this._decorDraft?.pid!==e.pointerId?this._decorMove?.pid!==e.pointerId?this._editorRuntime?._furnPointerUp(e)||(this._pointers.delete(e.pointerId),this._pointers.size<2&&(this._pinchStart=null),0===this._pointers.size&&(this._panStart=null,this._panLock=null,this._suppressClick&&setTimeout(()=>this._suppressClick=!1,0)),this._viewportGestureDirty&&0===this._pointers.size&&!t&&(this._viewportGestureDirty=!1,this.requestUpdate()),t&&this._fitRoom(t)):this._editorRuntimeOrThrow()._dmUp():this._decorCommitDraft():this._bdUp():this._dtUp():this._physicalRotateUp(e):this._physicalUp(e)}_clickRoom(e){!this._suppressClick&&e.area&&vv("/config/areas/area/"+e.area)}_roomLabelKey(e,t){"view"!==this._mode||"Enter"!==e.key&&" "!==e.key||(e.preventDefault(),e.stopPropagation(),this._fitRoom(t))}_pointerDown(e,t){if("view"!==this._mode&&"devices"!==this._mode)return;if("view"===this._mode&&"touch"===e.pointerType&&this._touchSequenceMultitouch)return;if(t=this._deviceHits.begin(this.renderRoot,this._renderDevices,this._space,e,t),"view"===this._mode){this._holdFired=!1,clearTimeout(this._holdTimer);const i=e.pointerId,n=e.currentTarget;return void(this._holdTimer=window.setTimeout(()=>{this._holdFired=!0,this._interruptViewGesture(i,n),this._infoCard=t},600))}if("ha_disabled"===t.bindingStatus?.kind||this._devicePositionBusy)return;if(this._deviceDrag)return void(this._deviceDrag.pointerId!==e.pointerId&&this._cancelDeviceDrag());e.preventDefault();const i=this._pos(t);this._deviceDrag={id:t.id,spaceId:t.space,displayName:t.name,pointerId:e.pointerId,source:e.currentTarget,sx:e.clientX,sy:e.clientY,ox:i.x,oy:i.y,moved:!1,before:vg(this._layout,t.id),start:this._devicePlacementForCanvas(t,i.x,i.y)},bv(e),this._tip=null,this._syncLiveHover()}_pointerMove(e,t){if("view"!==this._mode&&"devices"!==this._mode)return null;if(t=this._deviceForPointerEvent(e,t),"devices"!==this._mode)return t;const i=this._deviceDrag;return i&&i.id===t.id&&i.pointerId===e.pointerId?(this._editorRuntimeOrThrow()._queuePointerMove("device",()=>this._pointerMoveNow(e,t)),t):t}_pointerMoveNow(e,t){if("devices"!==this._mode)return;const i=this._deviceDrag;if(!i||i.id!==t.id||i.pointerId!==e.pointerId)return;const n=this.renderRoot.querySelector(".stage");if(!n)return;const r=this._baseVb(),o=n.getBoundingClientRect(),s=this._viewOr(r),a=(e.clientX-i.sx)/o.width*s.w,l=(e.clientY-i.sy)/o.height*s.h;Math.abs(e.clientX-i.sx)+Math.abs(e.clientY-i.sy)>3&&(i.moved=!0,clearTimeout(this._holdTimer));const c=sl(i.ox+a),h=sl(i.oy+l);this._previewDevicePlacement(t.id,this._devicePlacementForCanvas(t,c,h))}_pointerUp(e,t){if(t=this._deviceForPointerEvent(e,t),this._deviceHits.release(e.pointerId),clearTimeout(this._holdTimer),"devices"!==this._mode)return;const i=this._deviceDrag;if(!i||i.id!==t.id||i.pointerId!==e.pointerId)return;this._editorRuntimeOrThrow()._flushPointerMove("device"),this._deviceDrag=null;const n=vg(this._layout,t.id);var r,o;i.moved&&null!==n&&(r=n,o=i.start,null===r||null===o?r!==o:r.x!==o.x||r.y!==o.y||r.s!==o.s)?(this._selId=t.id,this._suppressClick=!0,window.setTimeout(()=>{this._suppressClick=!1},0),this._devicePositionBusy=!0,this.requestUpdate(),this._persistDevicePlacement(t.id,n).then(()=>{const e=this._t("history.device_move",{name:i.displayName});this._devicePositionHistory.push({name:e,before:{deviceId:i.id,spaceId:i.spaceId,placement:i.before},after:{deviceId:i.id,spaceId:i.spaceId,placement:n}})}).catch(e=>{this._previewDevicePlacement(t.id,i.before),this._showToast(this._t("toast.pos_save_failed",{err:this._errText(e)}))}).finally(()=>{this._devicePositionBusy=!1,this.requestUpdate()})):this._previewDevicePlacement(t.id,i.before)}_pointerCancel(e,t){t=this._deviceForPointerEvent(e,t),this._deviceHits.cancel(e.pointerId),this._deviceDrag?.id===t.id&&this._deviceDrag.pointerId===e.pointerId&&this._cancelDeviceDrag()}_showToast(e){for(const e of this.renderRoot.querySelectorAll("hp-dialog"))e.closeTransientOverlays("toast");this._toast=e,clearTimeout(this._toastTimer),this._toastTimer=window.setTimeout(()=>{this._toast=""},3500)}_syncPointerHoverTargets(){const e=this._pointerModality.hoverEnabled;for(const t of this.renderRoot.querySelectorAll(_v))t.toggleAttribute("data-pointer-hover",e)}_syncPointerHoverSubtree(e){if(e.nodeType!==Node.ELEMENT_NODE)return;const t=e,i=this._pointerModality.hoverEnabled;t.matches(_v)&&t.toggleAttribute("data-pointer-hover",i);for(const e of t.querySelectorAll(_v))e.toggleAttribute("data-pointer-hover",i)}_clearTransientHover(e=!1){e&&this._pointerModality.suspend(),this._liveRt?.clearDeviceFocus(),this._deviceHits.hover(this.renderRoot,null),this._tip&&(this._tip=null),this._hoverRoom&&(this._hoverRoom=null),this._syncLiveHover()}_notePointer(e){const t=this._pointerModality.modality,i=this._pointerModality.note(e);"touch"!==i&&"pen"!==i||t===i&&!this._tip&&!this._hoverRoom||this._clearTransientHover()}_guardTouchGesture(e){if(this._editorSecondary?.handleOutsideDismiss(e))return;if(this._touchClickGuard.handleActivation(e,this._suppressClick))return;const t=e;if(this._notePointer(t),"pointercancel"===e.type||"lostpointercapture"===e.type?this._doubleFit.clear():"pointerdown"===e.type&&this._doubleFit.clearOutside(t),"pointerdown"===e.type&&this._touchClickGuard.pointerDown(t.pointerId,t.pointerType),"touch"!==t.pointerType)return;if("pointerdown"===e.type){if(this._touchContacts.set(t.pointerId,{x:t.clientX,y:t.clientY,inStage:!!t.target?.closest?.(".stage")}),this._touchContacts.size>=2){this._deviceHits.clearPointers(),this._clearRoomFocus(!0),this._clearTransientHover(),clearTimeout(this._holdTimer),clearTimeout(this._kioskHoldTimer),this._swipeStart=null;const e=[...this._touchContacts.values()];if("view"===this._mode&&!this._vacFit&&e.every(e=>e.inStage)){this._pointers=new Map([...this._touchContacts].map(([e,t])=>[e,{x:t.x,y:t.y}]));const[t,i]=e;this._pinchStart={dist:Math.hypot(t.x-i.x,t.y-i.y),zoom:this._zoom},this._panStart=null,this._panLock=null}else this._vacFit&&(this._pointers.clear(),this._pinchStart=null,this._panStart=null,this._panLock=null)}return}if("pointermove"===e.type){const e=this._touchContacts.get(t.pointerId);if(!e)return;const i={...e,x:t.clientX,y:t.clientY};if(this._touchContacts.set(t.pointerId,i),this._touchSequenceMultitouch&&"view"===this._mode&&!this._vacFit&&this._pinchStart&&[...this._touchContacts.values()].every(e=>e.inStage)){this._pointers.set(t.pointerId,{x:t.clientX,y:t.clientY});const e=[...this._touchContacts.values()];if(e.length>=2&&this._stageEl){const[t,i]=e,n=Math.hypot(t.x-i.x,t.y-i.y)/(this._pinchStart.dist||1),r=this._stageEl.getBoundingClientRect();this._zoomAt((t.x+i.x)/2-r.left,(t.y+i.y)/2-r.top,this._pinchStart.zoom*n),this._saveZoom()}}return}if("pointerup"!==e.type&&"pointercancel"!==e.type&&"lostpointercapture"!==e.type)return;const i=this._touchClickGuard.pointerTerminal(t.pointerId,t.pointerType);if(this._clearTransientHover(),this._touchContacts.delete(t.pointerId),i){if(this._pointers.delete(t.pointerId),!this._vacFit&&this._pointers.size>=2){const[e,t]=[...this._pointers.values()];this._pinchStart={dist:Math.hypot(e.x-t.x,e.y-t.y),zoom:this._zoom}}else this._pinchStart=null;0===this._pointers.size&&(this._panStart=null,this._panLock=null)}}_showTip(e,t,i,n,r,o,s=!1){this._notePointer(e),this._pointerModality.hoverEnabled&&(this._drag||this._deviceDrag||s&&this._liveRt?.deviceFocusActive()||(this._tip={x:e.clientX,y:e.clientY,title:t,meta:i,lqi:n,temp:r,hum:o,room:s,source:"pointer"},this._syncLiveHover()))}_roomTipEnabledForPointer(e){return"view"===this._mode&&(this._notePointer(e),!!_n(this._settings)||(this._tip?.room&&(this._tip=null,this._syncLiveHover()),!1))}get _gridPitch(){return il}get _cellCm(){const e=Number(this._curSpaceCfg?.cell_cm);return Number.isFinite(e)&&e>0?e:5}_fmtLen(e,t){const i=function(e,t,i,n){return Math.hypot(t[0]-e[0],t[1]-e[1])/i*n}(e,t,this._gridPitch,this._cellCm);return ti(i,"mi"===this.hass?.config?.unit_system?.length)}get _curSpaceCfg(){const e=this._resize?.preview;return e&&e.space===this._space?e.sp:this._serverCfg?.spaces.find(e=>e.id===this._space)}get _renderCfg(){const e=this._resize?.preview;return e&&this._serverCfg?{...this._serverCfg,spaces:this._serverCfg.spaces.map(t=>t.id===e.space?e.sp:t)}:this._serverCfg}get _spaceH(){return this._curSpaceCfg,mv}get _segments(){const e=this._curSpaceCfg,t=this._spaceH;return oi(e?.rooms||[]).map(e=>[e[0]*mv,e[1]*t,e[2]*mv,e[3]*t])}_savedNav(){if(this._hasFixedFloor)return null;try{return JSON.parse(localStorage.getItem(uv)||"null")}catch{return null}}_saveNav(){if(!this._hasFixedFloor)try{localStorage.setItem(uv,JSON.stringify({space:this._space}))}catch{}}_leaveCardRoute(){if(this._routeDepartureHandled)return;this._routeDepartureHandled=!0,this._configReloadAuthority.invalidateLifecycle(),this._summary?.leaveRoute(),this._clearRoomFocus(!0),this._cancelDangerConfirm(),"view"!==this._mode&&this._setMode("view",!1),this._pendingNavMode=null,this._geometryHistory.clear(),this._activeWallChainId=null,this._wallChainSegmentCms=[],this._closingWallCm=null,this._drawWallField=null,this._showHidden=!1,this._tapConfirm=null,this._vacCalConfirm=null,this._decorEraseConfirm=null,this._openingInfo=null,this._closeInfoCard(),this._rulesDialog=null,this._alignDialog=null,this._preflightClipboardFallback=null,this._backupImportDialog=null,this._backupExportDialog=null,this._pdfDialog=!1,this._supportDialog?.preview?.token&&this._editorRuntime?._discardSupportPreview(this._supportDialog.preview.token),this._supportDialog=null,this._settingsDialog=null,this._deviceInbox=null,this._deviceInboxReturn=null,this._markerDialog=null,this._openingDialog=null,this._physicalDialog=null,this._wallDialog=null,this._backdropDialog=null,this._decorShapeDialog=null,this._decorTextDialog=null,this._mergeDialog=null,this._roomDialog=!1,this._spaceDialog=null,this._importDialog=null;const e=this._warmSlot;e?.owner===this._warmGen&&(e.vp=this._warmViewportState(),e.dlg=null,e.frameFingerprint="",clearTimeout(e.evict),e.evict=0),this._saveNav()}_setMode(e,t=!0){return e!==this._mode&&(this._clearRoomFocus(!0),this._cancelDangerConfirm(),this._resetDeviceHitState(),this._clearTransientHover(!0)),this._warmModeRequest=0,this._editorRuntime?this._editorRuntime._setMode(e,t):"view"===e?void this._editorModeRequest++:void this._requestMode(e,t)}_primeDrawWallField(){return this._editorRuntimeOrThrow()._primeDrawWallField()}get _drawWallFieldValue(){return null===this._drawWallField?Fo(15,this._imperial):this._drawWallField}get _drawWallCm(){const e=(e=>{const t=String(e??"").trim().replace(",",".");if(!/^[+-]?(?:\d+(?:\.\d*)?|\.\d+)$/.test(t))return null;const i=Number(t);return Number.isFinite(i)?i:null})(this._drawWallFieldValue);if(null==e||e<0)return null;const t=this._imperial?2.54*e:e,i="column"===this._tool?ma:100;return t>=("column"===this._tool?1:0)&&t<=i?t:null}get _drawWallMaxCm(){return"column"===this._tool?ma:100}_showPhysicalRange(e=this._drawWallMaxCm,t=0){return this._editorRuntimeOrThrow()._showPhysicalRange(e,t)}_mergeSpacePartitions(e,t){return this._editorRuntimeOrThrow()._mergeSpacePartitions(e,t)}_finishWallChain(){return this._editorRuntimeOrThrow()._finishWallChain()}_activateMarkupTool(e){return this._editorRuntimeOrThrow()._activateMarkupTool(e)}_limitReached(e){return this._editorRuntimeOrThrow()._limitReached(e)}_svgPoint(e){return this._editorRuntimeOrThrow()._svgPoint(e)}_snap(e){return this._editorRuntimeOrThrow()._snap(e)}_snapDrawPoint(e,t=!1){return this._editorRuntimeOrThrow()._snapDrawPoint(e,t)}_planSnapOpeningCuts(e,t){return this._editorRuntimeOrThrow()._planSnapOpeningCuts(e,t)}_planSnapGeometrySnapshot(){return this._editorRuntimeOrThrow()._planSnapGeometrySnapshot()}_hiddenWallDiagnosticSnapshot(){return this._editorRuntimeOrThrow()._hiddenWallDiagnosticSnapshot()}_planStructuralGeometrySnapshot(){return this._editorRuntimeOrThrow()._planStructuralGeometrySnapshot()}_planSnapContextKey(e){return this._editorRuntimeOrThrow()._planSnapContextKey(e)}_resolvePlanDrawPoint(e,t){return this._editorRuntimeOrThrow()._resolvePlanDrawPoint(e,t)}get _activePlanSnapCandidate(){if(!this._markup||"draw"!==this._tool)return null;const e=this._planSnapHover;if(!e)return null;const t=this._planSnapGeometrySnapshot();return e.contextKey===this._planSnapContextKey(t.key)?e.candidate:null}get _activePlanSnapConflicts(){if(!this._markup||"draw"!==this._tool)return[];const e=this._planSnapHover;if(!e)return[];const t=this._planSnapGeometrySnapshot();return e.contextKey===this._planSnapContextKey(t.key)?e.conflicts:[]}_clearPlanSnapHover(e=!0){return this._editorRuntime?this._editorRuntimeOrThrow()._clearPlanSnapHover(e):(this._planSnapHover=null,void(e&&(this._cursorPt=null)))}_samePt(e,t){return _i(e,t)}_dropLegacySegments(){return this._editorRuntimeOrThrow()._dropLegacySegments()}_rollbackRejectedPhysicalWrites(e){return this._editorRuntimeOrThrow()._rollbackRejectedPhysicalWrites(e)}async _reloadRejectedPhysicalWrite(){return this._editorRuntimeOrThrow()._reloadRejectedPhysicalWrite()}get _cfgWriting(){return this._writesPending>0}async _sendConfigCandidate(e){const t=xo(e),i=await this.hass.callWS({type:"houseplan/config/set",config:t,expected_rev:this._cfgRev});this._adoption.acceptConfigWrite(t,i)}_writeConfig(){if(this._editorRuntime)return this._editorRuntime._writeConfig();this._writesPending++,this._writeChain=Lu(this._writeChain,async()=>{if(!this._serverCfg)return;const e=xo(this._serverCfg);this._adoption.stageConfigCandidate(e),await this._sendConfigCandidate(e)});return this._writeChain.finally(()=>{this._writesPending--})}_saveConfig(){this._cfgEpoch++,this._saveConfigDebounced()}_geometrySnapshotFromConfig(e,t){return this._editorRuntimeOrThrow()._geometrySnapshotFromConfig(e,t)}_geometrySnapshot(e=this._space){return this._editorRuntimeOrThrow()._geometrySnapshot(e)}_recordGeometry(e,t){return this._editorRuntimeOrThrow()._recordGeometry(e,t)}_restoreGeometryStateInConfig(e,t,i=!1){return this._editorRuntimeOrThrow()._restoreGeometryStateInConfig(e,t,i)}_restoreGeometryStateLocal(e){return this._editorRuntimeOrThrow()._restoreGeometryStateLocal(e)}_wallModelBlockerLabel(e){return this._editorRuntimeOrThrow()._wallModelBlockerLabel(e)}_hasLegacyZeroWallFields(e=this._serverCfg){return this._editorRuntimeOrThrow()._hasLegacyZeroWallFields(e)}_showWallModelMigrationBlocked(e){return this._editorRuntimeOrThrow()._showWallModelMigrationBlocked(e)}_limitSegmentsOf(e){return this._editorRuntimeOrThrow()._limitSegmentsOf(e)}_junctionLimitViolations(e,t,i,n){return this._editorRuntimeOrThrow()._junctionLimitViolations(e,t,i,n)}_junctionLimitLabel(e){return this._editorRuntimeOrThrow()._junctionLimitLabel(e)}_junctionLimitsIntroduced(e,t,i){return this._editorRuntimeOrThrow()._junctionLimitsIntroduced(e,t,i)}_commitPhysicalGeometry(e,t,i=[]){return this._editorRuntimeOrThrow()._commitPhysicalGeometry(e,t,i)}_clearGeometryGesture(){return this._editorRuntime?this._editorRuntimeOrThrow()._clearGeometryGesture():(this._path=[],this._planSnapHover=null,this._cursorPt=null,this._openingHoverCandidate=null,this._openingJambBlockCm=null,this._openingPreset=null,this._openingRebindId=null,this._mergeSel=null,this._mergeDialog=null,this._splitSel=null,this._pendingSplit=null,this._wallFaceBatch=null,this._wallRepairDiagnostic=null,this._roomDeleteDialog=null,this._wallDialog=null,this._physicalDialog=null,this._physicalSel=null,this._physicalDrag=null,this._physicalRotate=null,this._activeWallChainId=null,this._wallChainSegmentCms=[],this._closingWallCm=null,this._openingDialog=null,this._resize?.reset(),this._decorDraft=null,this._decorMove=null,this._dtDrag=null,void(this._bdDrag=null))}_stagePointerCancel(e){if(this._deviceHits.cancel(e.pointerId),this._flushHa(),this._editorRuntime?._cancelPointerMove("markup-hover"),this._roomPointer?.pointerId===e.pointerId&&(this._roomPointer=null),this._doubleFit.clear(),this._editorRuntime)return this._editorRuntime._stagePointerCancel(e);this._pointers.delete(e.pointerId),this._pointers.size<2&&(this._pinchStart=null),0===this._pointers.size&&(this._panStart=null,this._panLock=null,this._swipeStart=null),this._viewportGestureDirty&&0===this._pointers.size&&(this._viewportGestureDirty=!1,this.requestUpdate())}_applyGeometryState(e,t=!1){return this._editorRuntimeOrThrow()._applyGeometryState(e,t)}_roomAt(e){return this._editorRuntimeOrThrow()._roomAt(e)}_overlapRoom(e){return this._editorRuntimeOrThrow()._overlapRoom(e)}_pointInRoom(e,t){return t.poly?mi(e,t.poly):null!=t.x&&e[0]>=t.x&&e[0]<=t.x+t.w&&e[1]>=t.y&&e[1]<=t.y+t.h}_contourSelfIntersects(e){return this._editorRuntimeOrThrow()._contourSelfIntersects(e)}_canAppendWallPoint(){return this._editorRuntimeOrThrow()._canAppendWallPoint()}_markupClick(e){if(this._editorRuntime)return this._editorRuntime._markupClick(e)}_activeWallSourceKey(e){return this._editorRuntimeOrThrow()._activeWallSourceKey(e)}_wallGraphSources(e){return this._editorRuntimeOrThrow()._wallGraphSources(e)}_wallFaceGraph(e,t){return this._editorRuntimeOrThrow()._wallFaceGraph(e,t)}_offerWallFaces(e,t=this._path.length-2,i){return this._editorRuntimeOrThrow()._offerWallFaces(e,t,i)}_beginWallFaceBatch(e){return this._editorRuntimeOrThrow()._beginWallFaceBatch(e)}_offerExistingWallFace(e){return this._editorRuntimeOrThrow()._offerExistingWallFace(e)}_columnClick(e){return this._editorRuntimeOrThrow()._columnClick(e)}_openPhysicalDialog(e,t){return this._editorRuntimeOrThrow()._openPhysicalDialog(e,t)}_physicalDown(e,t,i){return this._editorRuntimeOrThrow()._physicalDown(e,t,i)}_clampPhysicalDelta(e,t,i){return this._editorRuntimeOrThrow()._clampPhysicalDelta(e,t,i)}_physicalMove(e){return this._editorRuntimeOrThrow()._physicalMove(e)}_physicalUp(e){return this._editorRuntimeOrThrow()._physicalUp(e)}_registerPhysicalTap(e,t){return this._editorRuntimeOrThrow()._registerPhysicalTap(e,t)}_cancelPhysicalGesture(){return this._editorRuntimeOrThrow()._cancelPhysicalGesture()}_physicalRotateDown(e,t){return this._editorRuntimeOrThrow()._physicalRotateDown(e,t)}_physicalRotateMove(e){return this._editorRuntimeOrThrow()._physicalRotateMove(e)}_physicalRotateUp(e){return this._editorRuntimeOrThrow()._physicalRotateUp(e)}_rszRooms(){return this._editorRuntimeOrThrow()._rszRooms()}_rszOpenings(){return this._editorRuntimeOrThrow()._rszOpenings()}_rszObstacles(){return this._editorRuntimeOrThrow()._rszObstacles()}_rszOptsFor(e,t){return this._editorRuntimeOrThrow()._rszOptsFor(e,t)}_rszResolution(e,t,i){return this._editorRuntimeOrThrow()._rszResolution(e,t,i)}_rszSnapshot(){return this._editorRuntimeOrThrow()._rszSnapshot()}_rszResetController(){return this._editorRuntimeOrThrow()._rszResetController()}_rszProjectPreview(e,t,i,n,r){return this._editorRuntimeOrThrow()._rszProjectPreview(e,t,i,n,r)}_rszAcceptPreview(e,t){return this._editorRuntimeOrThrow()._rszAcceptPreview(e,t)}_rszSpaceCandidateGeometry(e,t){return this._editorRuntimeOrThrow()._rszSpaceCandidateGeometry(e,t)}_rszSpaceCandidateRenderable(e,t){return this._editorRuntimeOrThrow()._rszSpaceCandidateRenderable(e,t)}_rszCandidateRenderable(e){return this._editorRuntimeOrThrow()._rszCandidateRenderable(e)}_rszEdgeDown(e,t,i){return this._editorRuntimeOrThrow()._rszEdgeDown(e,t,i)}_rszReasonText(e){return this._editorRuntimeOrThrow()._rszReasonText(e)}_rszDisabledActivate(e,t){return this._editorRuntimeOrThrow()._rszDisabledActivate(e,t)}_rszDisabledKey(e,t){return this._editorRuntimeOrThrow()._rszDisabledKey(e,t)}_rszMove(e){return this._editorRuntimeOrThrow()._rszMove(e)}_rszUp(e){return this._editorRuntimeOrThrow()._rszUp(e)}_rszCancelDrag(e){return this._editorRuntimeOrThrow()._rszCancelDrag(e)}_rszPointerCancel(e){return this._editorRuntimeOrThrow()._rszPointerCancel(e)}_rszEdgeLabels(e,t,i=this._resize?.rooms){return this._editorRuntimeOrThrow()._rszEdgeLabels(e,t,i)}_rszInnerSpanCms(e,t,i){return this._editorRuntimeOrThrow()._rszInnerSpanCms(e,t,i)}_renderResizeMeasurements(){return this._editorRuntimeOrThrow()._renderResizeMeasurements()}_renderResizeLayer(e,t){return this._editorRuntimeOrThrow()._renderResizeLayer(e,t)}get _openingsR(){const e=this._curSpaceCfg,t=this._spaceH,i=this._spaceModel();return i?(e?.openings||[]).flatMap(e=>{const n={...e,rx:e.x*mv,ry:e.y*t,rlen:e.length*mv};if(!e.host||"wall"===e.host.kind)return[n];const r=Qu(e,i.partitions,mv,this._cellCm,this._gridPitch);if(!r.resolved)return"plan"===this._mode?[{...n,orphanReason:r.reason||"invalid-host"}]:[];let[o,s]=r.resolved.center;const a=this._physicalDrag;return a?.moved&&"partition"===a.kind&&a.id===e.host.id&&(o+=a.delta[0],s+=a.delta[1]),[{...e,rx:o,ry:s,rlen:r.resolved.length,angle:r.resolved.angle,partitionHost:r.resolved}]}):[]}_partitionOpeningCuts(e=this._spaceModel(),t=()=>!0){if(!e)return[];return V_(G_(this._curSpaceCfg?.id===e.id?this._curSpaceCfg:null,e,this._cellCm,this._gridPitch,mv),t)}_roomWallOpeningInputs(e=this._openingsR,t=this._spaceModel()){if(!t)return[];const i=this._openCuts();return K_(e,t,this._spaceWalls,i,this._wallKeyPitch,this._cellCm,this._gridPitch,mv)}_openingFace(e,t,i){return e.partitionHost?np(e.partitionHost,i):da(t,{x:e.rx,y:e.ry,angle:e.angle,length:e.rlen,flip_v:i})}_cmToUnits(e){return e/this._cellCm*this._gridPitch}get _decorList(){const e=this._curSpaceCfg;return Array.isArray(e?.decor)?e.decor:[]}get _decorH(){return mv}_decorResolvedStyle(e){return function(e,t,i,n=Mr){const r="rect"===e?.kind||"ellipse"===e?.kind,o=e,s=Kt(o?.color,n.color);return{color:s,opacity:Rr(o?.opacity,n.opacity),widthCm:Fr(e,t,i,n.widthCm),fill:!!r&&!0===o?.fill,fillColor:Kt(o?.fill_color,o?.fill?s:n.fillColor),fillOpacity:r&&o?.fill?Rr(o?.fill_opacity,.25):n.fillOpacity}}(e,this._cellCm,this._gridPitch,Mr)}_decorWidthUnits(e){return((e,t,i,n=Mr.widthCm)=>{const r=Number(e?.width_cm);if(Number.isFinite(r)&&r>0)return Ar(r,t,i);const o=Number(e?.width);return Number.isFinite(o)&&o>0?o:Ar(n,t,i)})(e,this._cellCm,this._gridPitch,Mr.widthCm)}_decorTextSizeCm(e){if("text"===e?.kind){const t=Number(e.size_cm);return Number.isFinite(t)&&t>0?t:Pr(20*tn(e),this._cellCm,this._gridPitch)}return Pr(20,this._cellCm,this._gridPitch)}_decorTextUnits(e){if("text"!==e.kind)return 20;const t=Number(e.size_cm);return Number.isFinite(t)&&t>0?Ar(t,this._cellCm,this._gridPitch):20*tn(e)}_decorSmallField(e){return Math.round(100*(this._imperial?e/2.54:e))/100}_decorSmallCm(e){const t=this._imperial?2.54*e:e;return Number.isFinite(t)?Math.max(.1,Math.min(100,t)):.1}_decorTextCm(e){const t=this._imperial?2.54*e:e;return Number.isFinite(t)?Math.max(.1,Math.min(2e3,t)):.1}_decorLargeField(e){return Math.round(100*(this._imperial?e/30.48:e/100))/100}_decorLargeCm(e){const t=this._imperial?30.48*e:100*e;return Number.isFinite(t)?Math.max(.1,Math.min(Qa*this._cellCm,t)):.1}_angleField(e){const t=Number(e);return Number.isFinite(t)?String(Number(t.toFixed(3))):"0"}_decorBoxOf(e){return"rect"!==e.kind&&"ellipse"!==e.kind&&"furniture"!==e.kind&&"image"!==e.kind?null:{x:e.x*mv,y:e.y*this._decorH,w:e.w*mv,h:e.h*this._decorH,angle:Cr(e.angle)||void 0}}_decorSnapGeometry(e){return this._editorRuntimeOrThrow()._decorSnapGeometry(e)}_decorSnap(e,t="mouse",i){return this._editorRuntimeOrThrow()._decorSnap(e,t,i)}_replaceDecor(e,t){return this._editorRuntimeOrThrow()._replaceDecor(e,t)}_cancelDecorGesture(){return this._editorRuntimeOrThrow()._cancelDecorGesture()}_decorPointerDown(e){return this._editorRuntimeOrThrow()._decorPointerDown(e)}_decorCommitDraft(){return this._editorRuntimeOrThrow()._decorCommitDraft()}_decorShapeDown(e,t){if(this._editorRuntime)return this._editorRuntime._decorShapeDown(e,t)}_decorMoveUpdate(e){this._editorRuntimeOrThrow()._queuePointerMove("decor-move",()=>this._editorRuntimeOrThrow()._decorMoveUpdate(e))}_decorNudge(e,t){if("decor"!==this._mode||"select"!==this._decorTool||!this._decorSel||this._decorDraft||this._decorMove||this._dtDrag||this._bdDrag)return!1;const i=this._decorList.find(e=>e.id===this._decorSel),n=this._curSpaceCfg;if(!i||!n)return!1;const r=function(e,t,i,n,r,o){if(!([t,i,n,r,o].every(Number.isFinite)&&r>0))return null;let s;if(s="line"===e.kind?[[e.x1,e.y1],[e.x2,e.y2]]:"text"===e.kind?[[e.x,e.y]]:Or(e),!s.length||s.some(e=>!e.slice(0,2).every(Number.isFinite)))return null;const a=s.map(e=>e[0]),l=s.map(e=>e[1]),c=Math.min(...a),h=Math.max(...a),d=Math.min(...l),u=Math.max(...l),p=t/n,_=i/r,m=p>0?Math.min(p,Math.max(0,o-h)):Math.max(p,Math.min(0,-o-c)),g=_>0?Math.min(_,Math.max(0,o-u)):Math.max(_,Math.min(0,-o-d));return m||g?"line"===e.kind?{...e,x1:e.x1+m,y1:e.y1+g,x2:e.x2+m,y2:e.y2+g}:{...e,x:e.x+m,y:e.y+g}:null}(i,e,t,mv,this._decorH,Qa);if(!r)return!1;const o=this._geometrySnapshot();return n.decor=this._decorList.map(e=>e.id===i.id?r:e),this._recordGeometry(this._t("history.decor_move"),o),this._saveConfig(),this.requestUpdate(),!0}_decorShapeDbl(e,t){if(this._editorRuntime)return this._editorRuntime._decorShapeDbl(e,t)}_openDecorProperties(e){return this._editorRuntimeOrThrow()._openDecorProperties(e)}_decorOpenText(e){return this._editorRuntimeOrThrow()._decorOpenText(e)}_decorRememberTextSelection(e){return this._editorRuntimeOrThrow()._decorRememberTextSelection(e)}_decorInsertLiveVariable(e){return this._editorRuntimeOrThrow()._decorInsertLiveVariable(e)}_decorSaveText(){return this._editorRuntimeOrThrow()._decorSaveText()}_decorSaveShape(){return this._editorRuntimeOrThrow()._decorSaveShape()}get _dtSel(){return"decor"===this._mode&&"select"===this._decorTool&&this._decorSel&&this._decorList.find(e=>e.id===this._decorSel)||null}_dtPivot(e){return this._editorRuntimeOrThrow()._dtPivot(e)}_dtApply(e,t){return this._editorRuntimeOrThrow()._dtApply(e,t)}_dtStart(e,t,i,n){return this._editorRuntimeOrThrow()._dtStart(e,t,i,n)}_dtMove(e){this._editorRuntimeOrThrow()._queuePointerMove("decor-transform",()=>this._editorRuntimeOrThrow()._dtMove(e))}_dtUp(){return this._editorRuntimeOrThrow()._flushPointerMove("decor-transform"),this._editorRuntimeOrThrow()._dtUp()}_dtMeasure(){return this._editorRuntimeOrThrow()._dtMeasure()}_deleteDecor(e){return this._editorRuntimeOrThrow()._deleteDecor(e)}_decorDeleteSel(){return this._editorRuntimeOrThrow()._decorDeleteSel()}_confirmDecorErase(){return this._editorRuntimeOrThrow()._confirmDecorErase()}get _bdBase(){const e=this._curSpaceCfg;return e?.plan_url?{...Va(e.plan_aspect,mv)}:null}get _bdRect(){const e=this._curSpaceCfg;return e?.plan_url?Xa(e,mv):null}get _bdParams(){const e=this._curSpaceCfg,t=Number(e?.plan_x),i=Number(e?.plan_y),n=Number(e?.plan_scale),r=Number(e?.plan_scale_x),o=Number(e?.plan_scale_y),s=Number.isFinite(n)&&n>0?n:1;return{dx:Number.isFinite(t)?t:0,dy:Number.isFinite(i)?i:0,sx:Number.isFinite(r)&&r>0?r:s,sy:Number.isFinite(o)&&o>0?o:s,angle:Cr(e?.plan_angle)}}_openBackdropDialog(e){if(this._editorRuntime)return this._editorRuntime._openBackdropDialog(e)}_saveBackdropDialog(){return this._editorRuntimeOrThrow()._saveBackdropDialog()}get _bdActive(){return"decor"===this._mode&&!!this._bdRect&&"backdrop"===this._decorTool}get _bdMovable(){return"decor"===this._mode&&"backdrop"===this._decorTool&&!!this._bdRect}_bdApply(e,t,i,n,r){return this._editorRuntimeOrThrow()._bdApply(e,t,i,n,r)}_bdStart(e,t,i=!1){return this._editorRuntimeOrThrow()._bdStart(e,t,i)}_bdMove(e){return this._editorRuntimeOrThrow()._bdMove(e)}get _bdMoved(){if("decor"!==this._mode||!this._bdRect)return!1;const e=this._bdParams;return 0!==e.dx||0!==e.dy||1!==e.sx||1!==e.sy||0!==e.angle}_bdReset(){return this._editorRuntimeOrThrow()._bdReset()}_bdUp(){return this._editorRuntimeOrThrow()._bdUp()}get _bdLive(){if(!this._bdDrag)return null;const e=this._bdRect;return e?{x:e.x+e.w/2,y:e.y+e.h/2,text:`${this._fmtLen([0,0],[e.w,0])} × ${this._fmtLen([0,0],[0,e.h])}`}:null}_renderBackdropFrame(e){return this._editorRuntime?this._editorRuntimeOrThrow()._renderBackdropFrame(e):G}_renderTextFrame(e){const t=this._dtSel;if(!t)return G;if("text"===t.kind&&this._dtBox?.id!==t.id)return G;const i="text"===t.kind?this._dtBox:this._decorBoxOf(t);if("line"!==t.kind&&!i)return G;const n=.018*Math.max(e.w,e.h),r=n/4;if("line"===t.kind){const e=[t.x1*mv,t.y1*this._decorH],i=[t.x2*mv,t.y2*this._decorH];return W` + + ${[e,i].map((e,t)=>W`this._dtStart(e,"scale",void 0,t)}> + `)} + `}if(!i)return G;const[o,s]=this._dtPivot(t),a=Number(t.angle)||0,l=[[-1,-1,"nwse"],[1,-1,"nesw"],[1,1,"nwse"],[-1,1,"nesw"]],c=2.2*n,h="furniture"===t.kind||"image"===t.kind,d=h?[[0,-1,"ns"],[1,0,"ew"],[0,1,"ns"],[-1,0,"ew"]]:[];return W` + + + this._dtStart(e,"rotate")}> + + ${wv.map(e=>"edges"===e?d.map(([e,t,o])=>{const s=e<0?i.x:e>0?i.x+i.w:i.x+i.w/2,a=t<0?i.y:t>0?i.y+i.h:i.y+i.h/2;return W`this._dtStart(i,"scale",[e,t])}> + `}):l.map(([e,t,o])=>W`this._dtStart(i,"scale",[e,t])}>`))} + `}_renderDecorLayer(e,t=this._viewOr(this._baseVb())){const i=mv,n=this._decorH,r="decor"===this._mode,o=r&&"erase"===this._decorTool,s=this._stageEl,a="iso"===this._renderProjection?1:function(e,t,i,n){const r=Number(e),o=Number(t),s=Number(i),a=Number(n);if(![r,o,s,a].every(e=>Number.isFinite(e)&&e>0))return 1;const l=Math.min(r/s,o/a);return Number.isFinite(l)&&l>0?l:1}(s?.clientWidth,s?.clientHeight,t.w,t.h),l=this._decorList.filter(t=>void 0===e||t.id===e).map(e=>{const t="dshape"+(r&&this._decorSel===e.id?" dsel":""),s=this._decorResolvedStyle(e),l=this._decorWidthUnits(e),c=t=>this._decorShapeDown(t,e),h=t=>this._decorShapeDbl(t,e);if("line"===e.kind)return W` + ${r&&"select"===this._decorTool?W``:G} + ${o?W``:G}`;if("rect"===e.kind){const r=(e.x+e.w/2)*i,a=(e.y+e.h/2)*n,d=Cr(e.angle);return W` + ${o?W``:G}`}if("ellipse"===e.kind){const r=(e.x+e.w/2)*i,a=(e.y+e.h/2)*n,d=Cr(e.angle);return W` + ${o?W``:G}`}if("image"===e.kind){const s=dm(e,i,n);if(!s)return G;const[a,l,d,u,p,_]=s,m=this._decorAssets.get(e.asset_id);if(!m)return r&&this._editorRuntime?this._editorRuntime._renderMissingDecorImage(e,t,_,a,l,d,u,c,h):G;const g=this._display(m.url);return g?W`this._signer.markLoaded(this._renderPlanHass,m.url,g)} + @pointerdown=${c} @dblclick=${h}> + ${o?W``:G}`:G}if("furniture"===e.kind){const d=Xl(e.symbol,this);if(!d)return G;const u=tc(e,i,n,d.viewW,d.viewH),p=Zl(l,a),_=Zl(l+Ar(20,this._cellCm,this._gridPitch),a);return W` + ${r&&"select"===this._decorTool?W``:G} + ${o?W``:G}`}if("text"===e.kind){const r=this._decorTextUnits(e),o=this._renderDeviceSnapshot?.facts.get(`decor:${this._space}:${e.id}`),a=function(e){return String(e??"").replace(/\r\n?/g,"\n").split("\n")}("string"==typeof o?o:Qi(e.text,e,this._renderPlanHass,e=>this._renderEntityAvailable(e))),l=e.x*i,d=e.y*n,u=Number(e.angle)||0,p=d-(a.length-1)*r*1.2/2;return W`${a.map((e,t)=>W`${e}`)}`}return G});let c=G;const h=this._decorDraft;if(h){const e=this._decorStyle,t=Ar(e.widthCm,this._cellCm,this._gridPitch);if("line"===h.kind)c=W``;else{const i=Math.min(h.a[0],h.b[0]),n=Math.min(h.a[1],h.b[1]),r=Math.abs(h.b[0]-h.a[0]),o=Math.abs(h.b[1]-h.a[1]);c="rect"===h.kind?W``:W``}}return W`${l}${c}${this._editorRuntime?._renderFurniturePlacementPreview(a)??G}${this._editorRuntime?._renderDecorImagePlacementPreview()??G}`}get _editorToolbarGroups(){return"plan"!==this._mode?[]:[{id:"opening",label:this._t("markup.opening"),icon:"mdi:door",activeItemId:"opening"===this._tool?this._openingPreset?.type:void 0,items:[{id:"window",label:this._t("opening.window"),icon:"mdi:window-closed-variant",role:"tool",invoke:()=>this._activateOpeningPlacement("window")},{id:"door",label:this._t("opening.door"),icon:"mdi:door-open",role:"tool",invoke:()=>this._activateOpeningPlacement("door")},{id:"passage",label:this._t("opening.passage"),icon:"mdi:arch",role:"tool",invoke:()=>this._activateOpeningPlacement("passage")},{id:"gate",label:this._t("opening.gate"),icon:"mdi:gate",role:"tool",invoke:()=>this._activateOpeningPlacement("gate")}]}]}_renderEditorGroupLauncher(e){return this._editorRuntimeOrThrow()._renderEditorGroupLauncher(e)}get _editorSecondaryContextId(){const e=`editor:${this._mode}:${this._space}:${this._cfgEpoch}`,t=this._editorSecondary?.activeGroup(this._editorToolbarGroups);if(t)return`${e}:group:${t.id}:${this._editorSecondary?.groupGeneration}`;if("plan"===this._mode){const t=this._physicalSel;return t?`${e}:selection:${t.kind}:${t.id}`:`${e}:tool:${this._tool}:${this._path.length}`}return"decor"===this._mode?"furniture"===this._decorTool?`${e}:palette:furniture:${this._furnPalette?.symbol||"none"}`:"image"===this._decorTool?`${e}:palette:image:${this._decorImagePalette?.asset_id||"none"}`:"select"===this._decorTool&&this._decorSel?`${e}:selection:decor:${this._decorSel}`:`${e}:tool:${this._decorTool}:${this._bdMoved?1:0}:${this._bdDrag?1:0}`:`${e}:none`}_runEditorContext(e,t){return this._editorRuntimeOrThrow()._runEditorContext(e,t)}_renderEditorGroupModel(e){return this._editorRuntimeOrThrow()._renderEditorGroupModel(e)}_renderDrawWallControl(){return this._editorRuntimeOrThrow()._renderDrawWallControl()}_renderPlanSecondary(){return this._editorRuntimeOrThrow()._renderPlanSecondary()}_renderDecorSecondary(){return this._editorRuntimeOrThrow()._renderDecorSecondary()}_withBackdropReset(e){return this._editorRuntimeOrThrow()._withBackdropReset(e)}get _editorSecondaryDialogBlocked(){return!!(this._dangerConfirm||this._tapConfirm||this._vacCalConfirm||this._roomDialog||this._mergeDialog||this._openingDialog||this._physicalDialog||this._openingInfo||this._decorTextDialog||this._decorShapeDialog||this._backdropDialog||this._decorEraseConfirm||this._spaceDialog||this._markerDialog||this._deviceInbox||this._infoCard||this._rulesDialog||this._settingsDialog||this._supportDialog||this._alignDialog||this._importDialog||this._kioskDialog||this._summary?.blocksOtherDialogs()||this._backupExportDialog||this._backupImportDialog||this._wallDialog)}_renderEditorSecondary(){return this._editorRuntimeOrThrow()._renderEditorSecondary()}_renderDecorBar(){return this._editorRuntimeOrThrow()._renderDecorBar()}_renderDecorEraseConfirm(){return this._editorRuntimeOrThrow()._renderDecorEraseConfirm()}_renderDecorTextDialog(){return this._editorRuntimeOrThrow()._renderDecorTextDialog()}_renderDecorShapeDialog(){return this._editorRuntimeOrThrow()._renderDecorShapeDialog()}_renderBackdropDialog(){return this._editorRuntimeOrThrow()._renderBackdropDialog()}_cssPxToRender(e){return this._editorRuntimeOrThrow()._cssPxToRender(e)}_renderZeroWalls(e){if(e&&!e.showBorders&&!this._editing)return W``;const t=this._zeroWalls();if(!t.lines.length)return W``;const i=e?.color||"var(--hp-muted)";return W` + ${t.lines.map(e=>W``)} + `}_zeroWalls(){const e=this._spaceModel();return e?L_(this._curSpaceCfg,e,mv,.02*this._gridPitch):{style:O_(this._curSpaceCfg),lines:[],contour:[],barriers:[],transmissive:[]}}_openCuts(){return this._zeroWalls().contour}_deleteRoomClick(e){return this._editorRuntimeOrThrow()._deleteRoomClick(e)}get _wallKeyPitch(){return nl}get _spaceWalls(){const e=this._curSpaceCfg?.walls;return Array.isArray(e)?e:[]}_intervalCm(e){const t=this._spaceModel();return t?Is(t.rooms,this._spaceWalls,this._openCuts(),e,this._wallKeyPitch,this._cellCm,this._gridPitch,mv):0}_normalizeWalls(e,t){const i=this._spaceModel();if(!i)return[];return Ko(zs(i.rooms,e,t,this._wallKeyPitch,this._cellCm,this._gridPitch,mv),this._curSpaceCfg?.rooms||[],nl,1,t.map(e=>[e[0]/mv,e[1]/mv,e[2]/mv,e[3]/mv]))}_paperShapes(e){if(!this._spaceWalls.length)return ri(e);const t=this._wallUnionGeometry();return t?.paperD?[{path:t.paperD}]:ri(e)}_wallUnionGeometry(){const e=this._spaceModel();if(!e)return null;const t=this._spaceWalls,i=this._physicalBodiesR();if(!t.length&&!i.length)return null;const n=`${this._space}|${this._cfgEpoch}|${e.rooms.length}`;if(!this._wallUnionCache||this._wallUnionCache.key!==n){const r=Mf(this._wallUnionPool,n);if(r.hit)this._wallUnionCache=r.value;else{const r=this._openCuts(),o=this._roomWallOpeningInputs(),s=ta(e.rooms,t,r,o,this._wallKeyPitch,this._cellCm,this._gridPitch,mv,i);s&&Object.defineProperty(s,"sourceFingerprint",{value:hc([this._curSpaceCfg,this._cellCm,this._gridPitch]),enumerable:!1});const a={key:n,value:s};Rf(this._wallUnionPool,n,a,8),this._wallUnionCache=a}}return this._wallUnionCache.value}_thickWallCuts(){const e=this._spaceModel();if(!e)return[];const t=this._spaceWalls;if(!t.length)return[];const i=this._openCuts();return na(e.rooms,t,i,this._wallKeyPitch,this._cellCm,this._gridPitch,mv).map(e=>[e.a[0],e.a[1],e.b[0],e.b[1]])}_innerRoomContour(e,t,i=this._openCuts(),n=this._wallUnionGeometry()?.roomGeom,r=this._wallUnionGeometry()?.multiWallNodes){const o=i.map(e=>e.join(",")).join(";"),s=`${e.id}|${this._cfgEpoch}|${t}|${o}`,a=Mf(this._innerContourCache,s);if(a.hit)return a.value;const l=Ns(e.rooms,t,this._spaceWalls,i,this._wallKeyPitch,this._cellCm,this._gridPitch,mv,n,r);return Rf(this._innerContourCache,s,l,600),l}_wallThickHit(e){return this._editorRuntimeOrThrow()._wallThickHit(e)}get _wallThickHover(){if(!this._markup||"wallthick"!==this._tool||!this._cursorPt||this._wallDialog)return null;const e=this._wallThickHit(this._cursorPt);if(!e)return null;const t=function(e,t,i){const n=Number.isFinite(e)&&e>0?e:0,r=Number.isFinite(t)&&t>0?t:5,o=Number.isFinite(i)&&i>0?i:0;return n>0?zo(n,r,o)/2:qa(1.5*o,r)}(e.cm,this._cellCm,this._gridPitch);let i="";for(const n of e.segs)i+=(i?" ":"")+hs([[n[0],n[1]],[n[2],n[3]]],t,!1);return{segs:e.segs,open:e.open,d:i}}_wallThickClick(e){return this._editorRuntimeOrThrow()._wallThickClick(e)}_wallThickApply(e){return this._editorRuntimeOrThrow()._wallThickApply(e)}_wallHatchDefs(e){const t=Do(this._cellCm);return W` + + + + `}_resolvedRoomFills(e,t){const i=new Map,n=new Map;for(const r of e.rooms){const e=this._roomDialog&&r.id===this._roomEditId?this._roomFill||t.fill:Nn(t.fill,r),o=hn(t.customFill,this._roomDialog&&r.id===this._roomEditId?{settings:{fill_mode:this._roomFill,custom_fill:this._roomCustomFill}}:r),s=Dc(t.tempMin,t.tempMax,r,this._roomTempMin,this._roomTempMax,this._roomDialog&&r.id===this._roomEditId),a=vn(e,"lqi"===e&&r.area?this._roomLqi(r.area):null,"light"===e?Ld(Nd(this._renderPlanHass,this._renderDevices,r,this._virtualLights)):"none","temp"===e?this._roomTemp(r):null,s.min,s.max,this._fillColors,o);i.set(r,a),r.id&&n.set(r.id,a)}return{byRoom:i,byId:n}}_spaceDisplayForRender(){const e=un(this._curSpaceCfg),t=this._spaceDialog;return t&&"edit"===t.mode&&t.spaceId===this._space?{...e,showBorders:t.showBorders,showNames:t.showNames,hideDecor:t.hideDecor,hideOpenings:t.hideOpenings,color:t.roomColor,opacity:t.roomOpacity,fill:t.fillMode,customFill:t.customFill?cn(t.customFill):ln,glow:t.glowEnabled,tempMin:t.tempMin,tempMax:t.tempMax,showLqi:t.showLqi,cardFontScale:t.cardFontScale,labelTemp:t.labelTemp,labelHum:t.labelHum,labelLqi:t.labelLqi,labelLight:t.labelLight}:e}_openingWallIndexFor(e,t){const i=e.rooms.map(e=>`${e.id}:${e.poly?.map(e=>e.join(",")).join("/")||`${e.x},${e.y},${e.w},${e.h}`}`).join(";"),n=this._spaceWalls.map(e=>`${e.key}:${e.a?.join(",")||""}:${e.b?.join(",")||""}:${e.cm}`).join(";"),r=t.map(e=>e.join(",")).join(";"),o=[e.id,this._cfgEpoch,this._wallKeyPitch,this._cellCm,this._gridPitch,i,n,r].join("|");let s=this._openingWallIndexCache.get(o);return s||(s=sa(e.rooms,this._spaceWalls,t,this._wallKeyPitch,this._cellCm,this._gridPitch,mv)),Rf(this._openingWallIndexCache,o,s,4),{key:o,value:s}}_renderOpeningTunnelFills(e,t,i="data"){if(this._markup||!this._spaceWalls.length||!this._openingsR.length)return W``;if("glow-base"===i&&![...t.byRoom.values()].some(Boolean))return W``;const n=this._openCuts(),r=this._openingsR.map(e=>({x:e.rx,y:e.ry,angle:e.angle,length:e.rlen})),o=r.map(e=>`${e.x},${e.y},${e.angle},${e.length}`).join(";"),s=this._openingWallIndexFor(e,n),a=`${s.key}|${o}`;return this._openingTunnelCache&&this._openingTunnelCache.key===a||(this._openingTunnelCache={key:a,value:_a(s.value,r)}),$_({openings:this._openingsR,geometries:this._openingTunnelCache.value,fillsByRoomId:t.byId,idPrefix:`${e.id}-${i}`,groupClass:"data"===i?"opening-tunnels":"opening-tunnels glow-base-tunnels",dataLayer:i})}_resolvedGlowBase(e,t,i){const n=new Map,r=new Map,o=this._fillColors.glow_base;for(const s of e.rooms){const e=i.byRoom.get(s),a=Hn(t.glow,s)&&(!e||e.opacity<=0)?{color:o.c,opacity:o.a,mode:"glow"}:null;n.set(s,a),s.id&&r.set(s.id,a)}return{byRoom:n,byId:r}}_renderGlowBaseRooms(e,t){if(this._markup||![...t.byRoom.values()].some(Boolean))return W``;const i=new Map(e.rooms.map(e=>[e,ni(e)])),n=this._openCuts(),r=this._wallUnionGeometry()?.roomGeom,o=e=>"M "+e.map(e=>e[0]+" "+e[1]).join(" L ")+" Z",s=e.rooms.map(s=>{const a=t.byRoom.get(s)||null,l=i.get(s)||null;if(!a||!l)return G;const c=this._spaceWalls.length&&s.id&&this._innerRoomContour(e,s.id,n,r)||l,h=Ri(c,e.rooms.filter(e=>e!==s).map(e=>i.get(e)).filter(e=>!!e)),d=this._cleanFloor(s,c,e).path;return d||h.length?W``:s.poly||c!==l?W``:W``});return W``}_renderWallBodies(e){if("iso"===this._renderProjection)return W``;if(e&&!e.showBorders&&("view"===this._mode||"devices"===this._mode))return W``;const t=this._wallUnionGeometry();if(!t)return W``;const i=this._stageEl,n=this._viewOr(this._baseVb()),r=i&&i.clientWidth&&n.w?i.clientWidth/n.w:1,o=e?.color||"#607d8b",s=To(t.depthUnits,r)||Ao(Do(this._cellCm),r),a=this._fillColors.wall_fill;return W` + ${t.paths.map(e=>W` + + `)} + `}_roomHoverPaths(e){const t=this._hoverRoom;if("view"!==this._mode||!t||t.space!==e.id)return null;const i=e.rooms.find(e=>e===t.room||!!e.id&&e.id===t.room.id);if(!i)return null;const n=ni(i);if(!n)return null;const r=e.rooms.filter(e=>e!==i).map(e=>({room:e,poly:ni(e)})).filter(e=>!!e.poly),o=Ri(n,r.map(e=>e.poly)),s=this._openCuts(),a=.02*this._gridPitch,l=s.filter(e=>{const t=[(e[0]+e[2])/2,(e[1]+e[3])/2];return n.some((e,i)=>Un(t,[e[0],e[1],...n[(i+1)%n.length]])<=4*a)}),c=this._spaceWalls,h=this._wallUnionGeometry()?.roomGeom,d=c.length&&i.id&&this._innerRoomContour(e,i.id,s,h)||n,u=[{axis:n,face:d}];for(const t of o){const i=r.find(e=>e.poly===t)?.room;let n=t;if(c.length&&i?.id){const r=As(e.rooms,i.id,c,s,this._wallKeyPitch,this._cellCm,this._gridPitch,mv);r&&(n=oa(r.poly,r.offsets)||t)}u.push({axis:t,face:n})}const p=this._roomWallOpeningInputs(this._openingsR,e).map(e=>{const t=e.angle*Math.PI/180,i=Math.cos(t)*e.length/2,n=Math.sin(t)*e.length/2;return[e.x-i,e.y-n,e.x+i,e.y+n]}),_=l.concat(p),m=u.map(({axis:e,face:t})=>{const i=_.map(i=>((e,t,i)=>{const n=e[2]-e[0],r=e[3]-e[1],o=Math.hypot(n,r);if(o.05)&&Un([c,h],[i[0],i[1],n[0],n[1]])<=4*a){d=!0;break}}if(!d)return null;let u=null;for(let e=0;e.05)continue;const p=Un([c,h],[t[0],t[1],n[0],n[1]]);(!u||p!!e);return i.length?Fn(t,i,a).map(e=>`M ${e[0]} ${e[1]} L ${e[2]} ${e[3]}`).join(" "):`M ${t.map(e=>`${e[0]} ${e[1]}`).join(" L ")} Z`}).filter(Boolean).join(" ");if(!m)return null;const g=e=>`M ${e.map(e=>`${e[0]} ${e[1]}`).join(" L ")} Z`;return{fillD:[this._cleanFloor(i,d,e).path||g(d),...o.map(g)].join(" "),outlineD:m}}_renderRoomHoverFill(e){return W` + + `}_renderRoomHoverOutline(e){return W` + + + `}_renderWallThickUi(){return this._editorRuntime?this._editorRuntimeOrThrow()._renderWallThickUi():W``}_renderWallThickDialog(){return this._editorRuntimeOrThrow()._renderWallThickDialog()}_openingAt(e){return this._editorRuntimeOrThrow()._openingAt(e)}_resolveOpeningPlacement(e){return this._editorRuntimeOrThrow()._resolveOpeningPlacement(e)}_activateOpeningPlacement(e){return this._editorRuntimeOrThrow()._activateOpeningPlacement(e)}_clearOpeningPlacement(e){return this._editorRuntime?this._editorRuntimeOrThrow()._clearOpeningPlacement(e):(this._openingHoverCandidate=null,this._openingJambBlockCm=null,void(e&&(this._openingPreset=null,this._openingRebindId=null)))}_openingClick(e){return this._editorRuntimeOrThrow()._openingClick(e)}_editOpening(e){if(this._editorRuntime)return this._editorRuntimeOrThrow()._editOpening(e)}_opPointerDown(e,t){if(this._editorRuntime)return this._editorRuntimeOrThrow()._opPointerDown(e,t)}_opPointerMove(e,t){if(this._editorRuntime)return this._editorRuntimeOrThrow()._opPointerMove(e,t)}_opRuler(e,t){return this._editorRuntimeOrThrow()._opRuler(e,t)}_opPointerUp(e,t){if(this._editorRuntime)return this._editorRuntimeOrThrow()._opPointerUp(e,t)}_opClick(e,t){if(this._editorRuntime)return this._editorRuntimeOrThrow()._opClick(e,t)}_saveOpening(){return this._editorRuntimeOrThrow()._saveOpening()}_deleteOpening(){return this._editorRuntimeOrThrow()._deleteOpening()}_contactCandidates(){return this._editorRuntimeOrThrow()._contactCandidates()}_lockCandidates(){return this._editorRuntimeOrThrow()._lockCandidates()}_toggleOpeningEntityPicker(e){return this._editorRuntimeOrThrow()._toggleOpeningEntityPicker(e)}_filterOpeningEntities(e,t){return this._editorRuntimeOrThrow()._filterOpeningEntities(e,t)}_selectOpeningEntity(e,t){return this._editorRuntimeOrThrow()._selectOpeningEntity(e,t)}_mergeClick(e){return this._editorRuntimeOrThrow()._mergeClick(e)}_commitMerge(){return this._editorRuntimeOrThrow()._commitMerge()}_splitClick(e){return this._editorRuntimeOrThrow()._splitClick(e)}get _contourClosed(){return this._path.length>=4&&this._samePt(this._path[0],this._path[this._path.length-1])&&(null!=this._closingWallCm||!this._activeWallChainId)}_markupMove(e){this._markup&&this._editorRuntime&&this._editorRuntimeOrThrow()._queuePointerMove("markup-hover",()=>this._editorRuntime._markupMove(e))}get _openingPreview(){const e=this._openingPreset;if("opening"!==this._tool||!e||!this._cursorPt)return null;const t=this._cursorPt,i=this._openingHoverCandidate;if(i&&Zf(i,[t[0],t[1]],e.revision,this._cfgEpoch))return i;if(this._openingAt(t))return this._openingHoverCandidate=null,null;const n=this._resolveOpeningPlacement(t);return this._openingHoverCandidate=n,n}get _opMeasureView(){return this._opMeasure||this._openingPreview?.measure||null}_saveRoom(){return this._editorRuntimeOrThrow()._saveRoom()}_decideWallFace(e){return this._editorRuntimeOrThrow()._decideWallFace(e)}_wallSourceCmAt(e,t,i){return this._editorRuntimeOrThrow()._wallSourceCmAt(e,t,i)}_activePathWithRepair(e,t){return this._editorRuntimeOrThrow()._activePathWithRepair(e,t)}_validateWallRepair(e,t){return this._editorRuntimeOrThrow()._validateWallRepair(e,t)}_applyWallRepair(e,t){return this._editorRuntimeOrThrow()._applyWallRepair(e,t)}_applyWallFaceBatch(){return this._editorRuntimeOrThrow()._applyWallFaceBatch()}_commitRoom(){return this._editorRuntimeOrThrow()._commitRoom()}_cancelPath(){return this._editorRuntimeOrThrow()._cancelPath()}_roomDialogCancel(){return this._editorRuntimeOrThrow()._roomDialogCancel()}get _freeAreas(){const e=new Set;for(const t of this._serverCfg?.spaces||[])for(const i of t.rooms||[])i.area&&e.add(i.area);for(const t of this._wallFaceBatch?.decisions||[])t.create&&t.area&&e.add(t.area);return Object.values(this.hass?.areas||{}).filter(t=>!e.has(t.area_id)).sort((e,t)=>(e.name||"").localeCompare(t.name||""))}_openDeviceInbox(){return this._editorRuntimeOrThrow()._openDeviceInbox()}_closeMarkerDialog(){return this._editorRuntimeOrThrow()._closeMarkerDialog()}_deviceInboxCandidates(e){return this._editorRuntimeOrThrow()._deviceInboxCandidates(e)}_deviceInboxRows(){return this._editorRuntimeOrThrow()._deviceInboxRows()}_deviceForInboxRow(e){return this._editorRuntimeOrThrow()._deviceForInboxRow(e)}_openInboxMarker(e,t=!1){return this._editorRuntimeOrThrow()._openInboxMarker(e,t)}async _setInboxHidden(e,t){return this._editorRuntimeOrThrow()._setInboxHidden(e,t)}_findInboxDevice(e){return this._editorRuntimeOrThrow()._findInboxDevice(e)}_deviceInboxTabKey(e){return this._editorRuntimeOrThrow()._deviceInboxTabKey(e)}_openMarkerDialog(e){if(this._editorRuntime)return this._editorRuntime._openMarkerDialog(e);this._ensureEditorRuntime().then(t=>{t&&this._openMarkerDialog(e)})}_runCandidates(){return this._editorRuntimeOrThrow()._runCandidates()}_bindingCandidates(){return this._editorRuntimeOrThrow()._bindingCandidates()}_physicalBodiesR(e=this._spaceModel()){if(!e)return[];const t=`${e.id}|${this._cfgEpoch}|${this._cellCm}|${this._gridPitch}`;if(this._physicalBodiesCache?.key===t)return this._physicalBodiesCache.all;const i=Ca(e,this._cellCm,this._gridPitch,2e-4*this._gridPitch,this._partitionOpeningCuts(e));return this._physicalBodiesCache={key:t,...i},i.all}_rawPhysicalBodiesR(e=this._spaceModel()){if(!e)return[];this._physicalBodiesR(e);const t=this._physicalBodiesCache;return t?[...t.partitions,...t.columns]:[]}_cleanFloor(e,t,i=this._spaceModel()){if(!i)return{floor:t,geom:null,path:"",area:za([[[...t,t[0]]]])};const n=e.id||`#${i.rooms.indexOf(e)}`,r=`${i.id}|${this._cfgEpoch}|${n}`;if(!this._resize?.preview){const e=Mf(this._cleanFloorCache,r);if(e.hit)return e.value}const o=t.map(e=>e[0]),s=t.map(e=>e[1]),a=[Math.min(...o),Math.min(...s),Math.max(...o),Math.max(...s)],l=this._physicalBodiesR(i).filter(e=>{const t=e.map(e=>e[0]),i=e.map(e=>e[1]);return Math.max(...t)>=a[0]&&Math.min(...t)<=a[2]&&Math.max(...i)>=a[1]&&Math.min(...i)<=a[3]}),c=l.length?Fa(t,l):null,h={floor:t,geom:c,path:c?ka(c):"",area:za(c||[[[...t,t[0]]]])};return this._resize?.preview||Rf(this._cleanFloorCache,r,h,600),h}_autoIconForBinding(e){if("virtual"===e)return"mdi:map-marker";const[t,i]=e.split(":");if(!i)return"";const n=this._fullRegistryHass,r=this._bindingStatus(e),o="active"===r.kind?r.enabledEntityIds:r.allEntityIds;if("device"===t){const e=n.devices?.[i];if(!e)return"mdi:help-circle";const t=o;return t.some(e=>e.startsWith("lock."))?"mdi:lock":Vd(n,e.name_by_user||e.name||"",e.model,t,this._iconRules)}if("entity"===t){const e=n.entities?.[i],t=this.hass.states?.[i],r=e?.name||t?.attributes?.friendly_name||i;return i.startsWith("lock.")?"mdi:lock":Vd(n,r,"",[i],this._iconRules)}return""}_allRoomsFlat(){const e=[];for(const t of this._serverCfg?.spaces||[])for(const i of t.rooms||[])i.area?e.push({value:t.id+"#"+i.area,label:(t.title||t.id)+" · "+i.name}):i.id&&e.push({value:t.id+"#@"+i.id,label:(t.title||t.id)+" · "+i.name+" · "+this._t("marker.subarea")});return e}_errText(e){if(!e)return this._t("err.unknown");if("string"==typeof e)return e;if("invalid_passage_fields"===e.code){const t=String(e.message||e.error||"");let i="",n=[];try{const e=JSON.parse(t);i=String(e.space??""),n=Array.isArray(e.fields)?e.fields.map(String):[]}catch{const e=t.match(/space=([^;]*);\s*opening=([^;]*);\s*fields=([^;]*)/);e&&(i=e[1],n=e[3].split(",").filter(Boolean))}if(i||n.length){const e=this._serverCfg?.spaces?.find(e=>String(e.id)===i),t={contact:"opening.contact_label",lock:"opening.lock_label",invert:"opening.invert",flip_h:"opening.flip_h",flip_v:"opening.flip_v"},r=n.map(e=>t[e]?this._t(t[e]):e).join(", ");return this._t("opening.invalid_passage_fields",{room:e?.title||i,fields:r})}}if("invalid_partition_opening_jamb_margin"===e.code){const t=String(e.message||e.error||"");let i=NaN;try{i=Number(JSON.parse(t).margin_cm)}catch{const e=t.match(/margin_cm=([^;}"]*)/);i=e?Number(e[1]):NaN}if(Number.isFinite(i))return this._t("opening.partition_jamb_margin",{distance:ti(i,this._imperial)})}if(null!=e.code){const t=`backup.error.${e.code}`,i=this._t(t);return e.message&&console.warn("[houseplan] backend error",e.code,e.message),i!==t?i:this._t("err.code",{code:e.code})}if(e.message)return e.message;if(e.error)return e.error;try{return JSON.stringify(e)}catch{return String(e)}}_backupErrorText(e){return this._editorRuntimeOrThrow()._backupErrorText(e)}async _pickMarkerFiles(e){return this._editorRuntimeOrThrow()._pickMarkerFiles(e)}_removeMarkerPdf(e){return this._editorRuntimeOrThrow()._removeMarkerPdf(e)}_markerLightFields(e){return this._editorRuntimeOrThrow()._markerLightFields(e)}_markerTapActionFields(e){return this._editorRuntimeOrThrow()._markerTapActionFields(e)}_markerToggleEntityFields(e){return this._editorRuntimeOrThrow()._markerToggleEntityFields(e)}async _saveMarker(){return this._editorRuntimeOrThrow()._saveMarker()}async _deleteMarker(){return this._editorRuntimeOrThrow()._deleteMarker()}_normPos(e,t,i){return{s:e,x:t/mv,y:i/mv}}_spaceDialogUsesOnboardingRuntime(e){return"create"===e&&!this._editorRuntime&&(!!this._onboardingRuntime||0===(this._serverCfg?.spaces.length||0)||this._importTotal>0||this._importQueue.length>0)}_spaceRuntimeOrThrow(){if(!this._onboardingRuntime)throw new Error("Houseplan onboarding runtime is not loaded");return this._onboardingRuntime}_openSpaceDialog(e,t){return this._spaceDialogUsesOnboardingRuntime(e)?this._onboardingRuntime?void this._onboardingRuntime._openSpaceDialog(e,t):void this._ensureOnboardingRuntime().then(i=>{i&&this._spaceRuntimeOrThrow()._openSpaceDialog(e,t)}):this._editorRuntime?this._editorRuntime._openSpaceDialog(e,t):void this._ensureEditorRuntime().then(i=>{i&&this._openSpaceDialog(e,t)})}async _pickPlanFile(e){return this._onboardingRuntime&&this._spaceDialogUsesOnboardingRuntime("create")?this._onboardingRuntime._pickPlanFile(e):this._editorRuntimeOrThrow()._pickPlanFile(e)}_useServerPlan(e){return this._onboardingRuntime&&this._spaceDialogUsesOnboardingRuntime("create")?this._onboardingRuntime._useServerPlan(e):this._editorRuntimeOrThrow()._useServerPlan(e)}async _readPlanAspect(e){return this._onboardingRuntime&&this._spaceDialogUsesOnboardingRuntime("create")?this._onboardingRuntime._readPlanAspect(e):this._editorRuntimeOrThrow()._readPlanAspect(e)}async _deleteServerPlan(e){return this._onboardingRuntime&&this._spaceDialogUsesOnboardingRuntime("create")?this._onboardingRuntime._deleteServerPlan(e):this._editorRuntimeOrThrow()._deleteServerPlan(e)}_renderServerPlans(e){return this._onboardingRuntime&&this._spaceDialogUsesOnboardingRuntime(e.mode)?this._onboardingRuntime._renderServerPlans(e):this._editorRuntimeOrThrow()._renderServerPlans(e)}async _saveSpaceDialog(){return this._onboardingRuntime&&this._spaceDialogUsesOnboardingRuntime("create")?this._onboardingRuntime._saveSpaceDialog():this._editorRuntimeOrThrow()._saveSpaceDialog()}async _deleteSpace(){return this._editorRuntimeOrThrow()._deleteSpace()}async _saveConfigNow(){return this._editorRuntimeOrThrow()._saveConfigNow()}_startImport(){return this._onboardingRuntime?this._onboardingRuntime._startImport():this._editorRuntimeOrThrow()._startImport()}_openNextImport(){return this._onboardingRuntime?this._onboardingRuntime._openNextImport():this._editorRuntimeOrThrow()._openNextImport()}_skipImport(){return this._onboardingRuntime?this._onboardingRuntime._skipImport():this._editorRuntimeOrThrow()._skipImport()}_renderImportDialog(){return this._onboardingRuntime?this._onboardingRuntime._renderImportDialog():this._editorRuntimeOrThrow()._renderImportDialog()}_sunGlobal(){const e=this._settingsDialog;return e?{...this._settings,north_deg:e.northDeg??void 0,bg_mode:e.bgMode,sun_rays:e.sunRays,sun_ray_origin:e.sunRayOrigin}:this._settings}_sunSpace(){const e=this._spaceDialog,t=this._curSpaceCfg?.settings||{};return e&&"edit"===e.mode&&e.spaceId===this._space?{...t,north_deg:e.northDeg??void 0,bg_mode:e.bgMode??void 0,sun_rays:e.sunRays??void 0}:t}_effNorth(){return fr(this._sunGlobal(),this._sunSpace())}_effBgMode(){return yr(this._sunGlobal(),this._sunSpace())}_dayCycleState(e=new Date){return(this._modeTransitionVisual?.viewWeight??("view"===this._mode?1:0))<=0||"daynight"!==this._effBgMode()?null:sr(this._renderPlanHass,e)}_syncDayCycleClock(){const e=this._dayCycleState();this._dayCycleClockKey=e?ar(e):"";const t="clock"===e?.source&&"hidden"!==this.ownerDocument.visibilityState&&this.isConnected;t&&!this._dayCycleTimer?this._dayCycleTimer=window.setInterval(this._dayCycleTick,3e4):!t&&this._dayCycleTimer&&(clearInterval(this._dayCycleTimer),this._dayCycleTimer=0)}_dayCycleVisibility(e){"hidden"!==e.kind?(this._dayCycleTick(),this._syncDayCycleClock()):this._dayCycleTimer&&(clearInterval(this._dayCycleTimer),this._dayCycleTimer=0)}_effSunRays(){return br(this._sunGlobal(),this._sunSpace())}_effSunRayOrigin(){return vr(this._sunGlobal())}_sunNow(){return null!==this._effNorth()?wr(this._renderPlanHass):null}_renderSunRays(e){const t=W``,i=this._modeTransitionVisual?.viewWeight??0;if(this._editing&&i<=0||!this._effSunRays())return this._sunFadeReset(),t;const n=this._effNorth(),r=null!==n?wr(this._renderPlanHass):null;if(!r||r.elevation<=0)return this._sunFadeReset(),t;if(o=r.elevation,Number(o)>=3)this._sunOutTimer&&(clearTimeout(this._sunOutTimer),this._sunOutTimer=0),this._sunOut=!1,this._sunShown=!0;else{if(!this._sunShown)return t;this._sunOut||(this._sunOut=!0,this._sunOutTimer=window.setTimeout(()=>{this._sunOutTimer=0,this._sunShown=!1,this._sunOut=!1,this.requestUpdate()},2e3))}var o;const s=this._zeroWalls(),a=s.barriers.map(e=>e.join(",")).join(";"),l=this._effSunRayOrigin(),c=`${e.id}|${r.azimuth}|${r.elevation}|${n}|${l}|${this._cfgEpoch}|${s.style}|${a}`;if(!this._sunRaysCache||this._sunRaysCache.key!==c){const t=e.rooms.map(e=>({id:e.id||"",poly:ni(e)})).filter(e=>!!e.id&&!!e.poly),i=this._openingsR.filter(e=>"window"===e.type&&"partition"!==e.host?.kind).map(e=>({id:e.id,x:e.rx,y:e.ry,angle:e.angle,length:e.rlen})),o=this._spaceWalls,a=this._openCuts(),h=this._openingWallIndexFor(e,a).value,d={},u={},p=this._wallUnionGeometry()?.roomGeom;if(o.length){for(const i of t){const t=this._innerRoomContour(e,i.id,a,p);t&&(d[i.id]=t)}for(const e of i){const t=da(h,{x:e.x,y:e.y,angle:e.angle,length:e.length});t.cm>0&&(u[e.id]=zo(t.cm,this._cellCm,this._gridPitch))}}let _=mr(t,i,r.azimuth,r.elevation,n,o.length?d:void 0,o.length?u:void 0,l);const m=[...this._physicalBodiesR(e),...s.barriers.map(e=>[[e[0],e[1]],[e[2],e[3]]])];m.length&&(_=_.map(e=>{const t=function(e,t,i){return i>0?e.map(e=>function(e){const t=[...e].sort((e,t)=>e[0]-t[0]||e[1]-t[1]);if(t.length<=2)return t;const i=(e,t,i)=>(t[0]-e[0])*(i[1]-e[1])-(t[1]-e[1])*(i[0]-e[0]),n=[];for(const e of t){for(;n.length>=2&&i(n[n.length-2],n[n.length-1],e)<=0;)n.pop();n.push(e)}const r=[];for(let e=t.length-1;e>=0;e--){const n=t[e];for(;r.length>=2&&i(r[r.length-2],r[r.length-1],n)<=0;)r.pop();r.push(n)}return n.slice(0,-1).concat(r.slice(0,-1))}([...e,...e.map(e=>[e[0]+t[0]*i,e[1]+t[1]*i])])).filter(e=>e.length>=3):e}(m,e.dir,e.len),i=e.polys.map(e=>Fa(e,t));return{...e,paths:i.map(ka).filter(Boolean),polys:i.flatMap(Oa)}}).filter(e=>e.paths?.length||e.polys.length)),this._sunRaysCache={key:c,rays:_,rims:_.map(e=>function(e,t=1e-4){const[i,n]=e.dir,r=-n,o=i,s=[],a=e.rimSources||[e.a,e.b],l=a.filter((e,i)=>{const n=e[0]*r+e[1]*o;return a.findIndex(e=>Math.abs(e[0]*r+e[1]*o-n)<=t)===i});for(const a of l){const l=[];for(const s of e.polys)for(let e=0;et)continue;if(Math.abs((h[0]-a[0])*r+(h[1]-a[1])*o)>t)continue;const d=(c[0]-a[0])*i+(c[1]-a[1])*n,u=(h[0]-a[0])*i+(h[1]-a[1])*n;Math.abs(u-d)<=t||l.push(de[0]-t[0]);const c=[];for(const e of l){const i=c[c.length-1];i&&e[0]<=i[1]+t?i[1]=Math.max(i[1],e[1]):c.push([e[0],e[1]])}for(const[e,t]of c)s.push([[a[0]+i*e,a[1]+n*e],[a[0]+i*t,a[1]+n*t]])}return s}(e))}}const h=this._sunRaysCache.rays,d=this._sunRaysCache.rims;if(!h.length)return t;const u=(p=function(e){const t=Math.min(90,Math.max(-90,Number(e)||0));let i=lr[lr.length-1][1];for(let e=1;e + ${h.map((e,t)=>{const i=(e.a[0]+e.b[0])/2,n=(e.a[1]+e.b[1])/2,r=i+e.normal[0]*e.depth,o=n+e.normal[1]*e.depth;return W` + ${_.map(([e,t])=>W``)} + + + ${m.map(([e,t])=>W``)} + `})} + + + ${h.map((e,t)=>e.paths?.length?e.paths.map(e=>W``):e.polys.map(e=>W``))} + ${h.map((e,t)=>(d[t]||[]).map(e=>W``))} + `}_sunFadeReset(){this._sunOutTimer&&(clearTimeout(this._sunOutTimer),this._sunOutTimer=0),this._sunShown=!1,this._sunOut=!1}_compassPoint(e){const t=e.currentTarget.getBoundingClientRect(),i=e.clientX-(t.left+t.width/2),n=e.clientY-(t.top+t.height/2);if(Math.hypot(i,n)<5)return;let r=Math.round(180*Math.atan2(i,-n)/Math.PI);e.shiftKey&&(r=15*Math.round(r/15)),r=(r%360+360)%360,this._settingsDialog={...this._settingsDialog,northDeg:r}}_renderCompass(){const e=this._settingsDialog.northDeg;return j`{e.currentTarget.setPointerCapture(e.pointerId),this._compassDrag=!0,this._compassPoint(e)}} + @pointermove=${e=>{this._compassDrag&&this._compassPoint(e)}} + @pointerup=${()=>this._compassDrag=!1} + @pointercancel=${()=>this._compassDrag=!1}> + + ${[0,45,90,135,180,225,270,315].map(e=>W``)} + + + + ${this._t("gs.north_letter")} + + ${null===e?"—":e+"°"} + `}_stageBg(e){const t=this._settingsDialog,i=this._spaceDialog,n=t?t.bgColor||"":pn(this._settings,{bgColor:null});return(i&&"edit"===i.mode&&i.spaceId===this._space?i.bgColor||"":e.bgColor||"")||n}_stageBgHex(){const e=this._stageEl;if(e){const t=getComputedStyle(e).backgroundColor.match(/rgba?\((\d+),\s*(\d+),\s*(\d+)/);if(t)return"#"+t.slice(1,4).map(e=>(+e).toString(16).padStart(2,"0")).join("")}return"#111111"}_renderPdfDialog(){const e=this._pdfRuntime,t=this._spaceModel(),i=this._curSpaceCfg;if(!(e&&t&&i&&this._serverCfg))return G;const n=new Map;for(const[e,t]of this._decorAssets)n.set(e,{url:this._display(t.url),mime:t.mime});const r=this._wallUnionGeometry(),o=this._openCuts(),s=new Map(t.rooms.flatMap(e=>e.id?[[e.id,e]]:[]));return e.render({config:this._serverCfg,rawSpace:i,space:t,layout:this._layout,imperial:this._imperial,cardTitle:this._config?.title||this._t("card.title"),version:tv(nv),hass:this.hass,backdropUrl:t.bg?this._display(t.bg.href):"",decorAssets:n,sharedWallGeometry:r,resolveInnerContour:e=>this._innerRoomContour(t,e,o,r?.roomGeom,r?.multiWallNodes),resolveRoomArea:(e,i)=>{const n=s.get(e);return n?this._cleanFloor(n,i,t).area:void 0},t:(e,t)=>this._t(e,t),toast:e=>this._showToast(e),close:()=>{this._pdfDialog=!1,this.requestUpdate()}})}_preflightDiagnostics(e,t){return this._editorRuntimeOrThrow()._preflightDiagnostics(e,t)}_reportPreflightFailure(e,t){return this._editorRuntimeOrThrow()._reportPreflightFailure(e,t)}_preflightVersionsDiffer(){return this._editorRuntimeOrThrow()._preflightVersionsDiffer()}async _copyPreflightDiagnostics(){return this._editorRuntimeOrThrow()._copyPreflightDiagnostics()}_checkOptimizeGeometry(e){return this._editorRuntimeOrThrow()._checkOptimizeGeometryImpl(e)}_checkSpacePhysicalGeometry(e,t,i){return this._editorRuntimeOrThrow()._checkSpacePhysicalGeometryImpl(e,t,i)}_optimizeReferenceContext(e){return this._editorRuntimeOrThrow()._optimizeReferenceContext(e)}_previewAlignDialog(e){return this._editorRuntimeOrThrow()._previewAlignDialog(e)}async _runAlignToGrid(){return this._editorRuntimeOrThrow()._runAlignToGrid()}async _undoPlanOptimization(){return this._editorRuntimeOrThrow()._undoPlanOptimization()}async _runBackupExport(){return this._editorRuntimeOrThrow()._runBackupExport()}async _pickBackupImport(e){return this._editorRuntimeOrThrow()._pickBackupImport(e)}async _setBackupDuplicatePolicy(e){return this._editorRuntimeOrThrow()._setBackupDuplicatePolicy(e)}async _applyBackupImport(){return this._editorRuntimeOrThrow()._applyBackupImport()}_renderBackupExportDialog(){return this._editorRuntimeOrThrow()._renderBackupExportDialog()}_renderBackupImportDialog(){return this._editorRuntimeOrThrow()._renderBackupImportDialog()}_setFillColor(e,t){return this._editorRuntimeOrThrow()._setFillColor(e,t)}async _saveSettingsDialog(){return this._editorRuntimeOrThrow()._saveSettingsDialog()}_boolInput(e,t,i=!1){return this._editorRuntimeOrThrow()._boolInput(e,t,i)}_rangeInput(e,t,i,n,r,o=!1,s){return this._editorRuntimeOrThrow()._rangeInput(e,t,i,n,r,o,s)}_renderColorRow(e,t){return this._editorRuntimeOrThrow()._renderColorRow(e,t)}get _glowRadiusCm(){const e=Number(this._settings.glow_radius_cm);return Number.isFinite(e)&&e>0?e:300}get _imperial(){return"mi"===this.hass?.config?.unit_system?.length}get _glowRadiusPlaceholder(){const e=this._glowRadiusCm;return this._imperial?String(Math.round(e/30.48*10)/10):String(e/100)}_glowTransition(e,t){return Dm(this._glowRuntimeState,this._glowRuntimeHost,e,t)}_forgetGlowSource(e){Am(this._glowRuntimeState,this._glowRuntimeHost,e)}_forgetGlowSpace(e){Pm(this._glowRuntimeState,this._glowRuntimeHost,e)}_warnGlowGeometryFallback(e,t,i,n){Im(this._glowRuntimeState,e,t,i,n)}_lightBarriers(e,t){const i=$m({rawSpaceConfig:this._curSpaceCfg,space:e,openings:this._openingsR,cellCm:this._cellCm,gridPitch:this._gridPitch,openingAmount:e=>this._openingAmt(e)}),n=`${e.id}|${i.fingerprint}`,r=Mf(this._lightBarrierPool,n);if(r.hit)return this._lightBarrierCache=r.value,r.value.value;const o=Mm({space:e,revision:i,walls:this._spaceWalls,zeroWalls:this._zeroWalls(),wallKeyPitch:this._wallKeyPitch,cellCm:this._cellCm,gridPitch:this._gridPitch,coordScale:mv,sharedWallGeometry:this._wallUnionGeometry(),physicalBodies:(t,i)=>(this._lightPhysicalBodiesCache?.key!==i&&(this._lightPhysicalBodiesCache={key:i,all:Ca(e,this._cellCm,this._gridPitch,2e-4*this._gridPitch,t).all}),this._lightPhysicalBodiesCache.all)}),s={key:n,value:o};return Rf(this._lightBarrierPool,n,s,8),this._lightBarrierCache=s,o}_renderGlowLayer(e,t,i=this._viewOr(this._baseVb())){const n=this._fillColors,r=this._glowRadiusCm/this._cellCm*this._gridPitch,o=e.rooms.map(e=>({r:e,poly:ni(e)})).filter(e=>!!e.poly),s=o.filter(({r:e})=>Hn(t.glow,e));if(!s.length)return this._forgetGlowSpace(e.id),W``;const a=this._lightBarriers(e,o),l=Sm({hass:this._renderPlanHass,devices:this._renderDevices,virtualLights:this._virtualLights,spaceId:e.id,defaultColor:n.glow_light.c,paletteAlpha:n.glow_light.a,defaultRadiusUnits:r,cellCm:this._cellCm,gridPitch:this._gridPitch,position:e=>this._pos(e)}),c=[],h=new Set;for(const t of l){const{key:i,pos:n}=t;if(h.add(i),Cm(n,a)){this._forgetGlowSource(i);continue}const r=this._glowTransition(i,!!t.appearance);if(!r)continue;t.appearance&&this._glowLastAppearance.set(i,t.appearance);const s=this._glowLastAppearance.get(i);if(!s)continue;let l=null;const d=`${e.id}|${a.fingerprint}|${n.x.toFixed(4)},${n.y.toFixed(4)}|${t.radius.toFixed(4)}`,u=km(this._glowRuntimeState,d);u.hit?l=u.value:(l=Rm({spaceId:e.id,source:n,radius:t.radius,scene:a,polygons:o.map(({r:e,poly:t})=>({room:e,poly:t})),onBoundsFailure:(t,i)=>this._warnGlowGeometryFallback(e.id,a.fingerprint,t,i)}),xm(this._glowRuntimeState,d,l)),c.push({key:i,sourceEid:t.sourceEid,domId:r.domId,entering:r.entering,leaving:r.leaving,pos:n,c:s.c,alpha:s.alpha,geometry:l,r:t.radius})}if(Fm(this._glowRuntimeState,this._glowRuntimeHost,e.id,h),!c.length)return W``;const d=this._spaceWalls,u=s.length===o.length?[]:this._openCuts(),p=this._wallUnionGeometry()?.roomGeom,_=s.length===o.length?null:s.map(({r:t,poly:i})=>{const n=d.length&&t.id&&this._innerRoomContour(e,t.id,u,p)||i,r=this._cleanFloor(t,n,e).path,s=Ri(n,o.filter(e=>e.r!==t).map(e=>e.poly)),a=e=>"M "+e.map(e=>e[0]+" "+e[1]).join(" L ")+" Z";return[r||a(n),...s.map(a)].join(" ")}),m=this._stageEl?.clientWidth&&i.w?this._stageEl.clientWidth/i.w:1,g=!this._pinchStart&&!this._panStart&&!this._cameraTransition.active,f=Om(this._glowRuntimeState,m,g);return Em({spots:c,enabledClip:_,feather:f.feather,featherEnabled:f.enabled,screenBlend:this._glowScreenBlend})}_renderAlignDialog(){return this._editorRuntimeOrThrow()._renderAlignDialog()}_renderSettingsDialog(){return this._editorRuntimeOrThrow()._renderSettingsDialog()}_renderSupportDialog(){return this._editorRuntimeOrThrow()._renderSupportDialog()}_rulesSet(e){return this._editorRuntimeOrThrow()._rulesSet(e)}async _saveRules(){return this._editorRuntimeOrThrow()._saveRules()}_renderRulesDialog(){return this._editorRuntimeOrThrow()._renderRulesDialog()}_saveKioskScale(e){this._summary?.saveScale(e)}_renderKioskDialog(){const e=this._kioskScale,t=(t,i)=>{const n=Math.round(100*e[t]);return j` +
+ {const i=Number(e.target.value);Number.isFinite(i)&&this._saveKioskScale({[t]:i/100})}} aria-label=${i} /> + ${n}% +
`};return j`this._kioskDialog=!1}> +
+
${this._t("kiosk.hint")}
+ ${t("icon",this._t("kiosk.icon_scale"))} + ${t("font",this._t("kiosk.font_scale"))} +
+
+ + + +
+
`}_fixedFloorValue(e){if("string"==typeof e)return e||"''";try{const t=JSON.stringify(e);return(void 0===t?String(e):t).slice(0,160)}catch{return String(e).slice(0,160)}}_renderDangerConfirm(){return this._dangerConfirm?j` + `:G}_renderRoot(e){return j`${e}${this._renderVersionBanner()}${this._renderDangerConfirm()}`}render(){const e=this._renderBody();return e===G?e:this._renderRoot(e)}_renderBody(){if(!this._config||!this.hass)return G;const e=this._terminalFrame;if(this._terminalFrame=0,1===e)return U;const t=this._syncDangerConfirmLocaleGate();if("cold"===t)return pp();if("warm"===t)return U;const i=!!this._importDialog||!(!this._spaceDialog||!this._spaceDialogUsesOnboardingRuntime(this._spaceDialog.mode)),n="view"!==this._mode||!!(this._roomDialog||this._mergeDialog||this._openingDialog||this._physicalDialog||this._partitionDeleteDialog||this._roomDeleteDialog||this._decorTextDialog||this._decorShapeDialog||this._backdropDialog||this._decorEraseConfirm||this._spaceDialog&&!this._spaceDialogUsesOnboardingRuntime(this._spaceDialog.mode)||this._deviceInbox||this._markerDialog||this._rulesDialog||this._settingsDialog||this._supportDialog||this._alignDialog||this._backupExportDialog||this._backupImportDialog||this._kioskDialog||this._vacFit||this._vacCalConfirm);i&&!this._onboardingRuntime&&this._ensureOnboardingRuntime(),n&&!this._editorRuntime&&this._ensureEditorRuntime();const r=this._model,o=this._renderLife.diagnostics(this.hass,this._markers,e=>this._bindingStatus(e)),s=this._fixedFloorState(r);if("pending"===s.kind)return j` + ${this.panelHost?G:j`
+
${this._config.title||this._t("card.title")}
+
`} +
+ +

${this._t("fixed_floor.loading")}

+
+
`;if("invalid"===s.kind)return j` + ${this.panelHost?G:j`
+
${this._config.title||this._t("card.title")}
+
`} + +
`;if(!r.length)return j` + ${this.panelHost?G:j`
+
${this._config.title||this._t("card.title")}
+
`} +
+ +

${this._t("empty.no_spaces")}

+ ${this._serverStorage&&this._canManageConfiguration?j`

${this._t("empty.add_first")}

+ `:j`

${this._t(this._serverStorage?"empty.read_only":"empty.install")}

`} +
+ ${this._spaceDialog&&(this._onboardingRuntime||this._editorRuntime)?this._renderSpaceDialog():G} + ${this._importDialog&&this._onboardingRuntime?this._renderImportDialog():G} + ${this._toast?j``:G} +
`;const a=this._spaceModel();if(!a)return G;const l="valid"===s.kind?[a]:r,c=a.vb;let h=this._effectiveProjection();this._renderProjection=h,this._labs.active.length&&function(){const e=Of,t=e.alpha?e.active.join(","):"";if(!t||t===Nf)return;Nf=t;const i=new Map(Af.map(e=>[e.id,e])),n=e.active.map(e=>`${e} (#${i.get(e).issue})`).join(", ");console.info(`HOUSEPLAN ALPHA: hp_alpha=1; ${n}`)}();let d="iso"===h;const u=d?this._isoSceneRuntime:null,p="devices"===this._mode&&this._showAll,_=this._renderDevices.filter(e=>e.space===a.id&&(!e.hidden||p)),m=this._renderDeviceSnapshot,g=this._spaceDisplayForRender(),f=this._resolvedRoomFills(a,g),v=this._resolvedGlowBase(a,g,f),y=g.showLqi??this._config.show_signal??!0,b=this._config.icon_size??2.5,w=b>8?2.5:b,k=S_(w);let x=d?this._renderIsoScene:null,S=this._viewOr(this._baseVb(h,x)),$=null;try{$=u?.resolveIsoFramePresentation({projection:h,display:g,scene:x,openings:this._openingsR,amountOf:e=>this._openingAmt(e),cellCm:this._cellCm,overlays:e=>this._isoOverlayScene(a,_,S,g,e,x,w,k,y)})??null}catch(e){this._latchIsoFallback(g.showBorders?x?.key||this._isoInvalidKey():`${a.id}|no-borders`,e),this._cancelCameraTransition(!1),h="flat",d=!1,x=null,$=null,this._renderProjection="flat",this._renderIsoScene=null,this._isoProjectionSnapshot="flat",this._view=null,this._viewModeSnap=null,S=this._viewOr(this._baseVb("flat",null))}const M=$?.layers??null,R=$?.overlays??null,C=this._editing?"":this._stageBg(g),T=this._opMeasureView,D="view"===this._mode?this._editorChromeMode:this._mode,A=this._roomHoverPaths(a),P=a.bg?this._display(a.bg.href):"",F=this._continuity.overlayVisible||"recovery-error"===this._continuity.state?this._continuity.recoveryReason:null,z=this._modeTransitionVisual,I=this._dayCycleState(),O=z?.viewWeight??("view"===this._mode?1:0),E=this._paperShapes(a.rooms),N=this._modeTransition.state?.from.presentedMode,H=!this._markup||!!z&&("view"===z.presentedMode||"devices"===z.presentedMode||"view"===N||"devices"===N),L=z?.stageColor||C,B=z?.sceneBrightness??1;return j` + this._notePointer(e)} + @pointerdown=${this._touchGestureGuard} + @pointermove=${this._touchGestureGuard} + @pointerup=${this._touchGestureGuard} + @pointercancel=${this._touchGestureGuard} + @lostpointercapture=${this._touchGestureGuard} + @keydown=${this._touchGestureGuard} + @contextmenu=${this._touchGestureGuard} + @click=${this._touchGestureGuard}> +
+
+ ${this.panelHost?G:j`
+ + ${this._config.title||this._t("card.title")} +
`} + + ${this._canEdit?j`
+ ${[["plan","mdi:floor-plan"],["devices","mdi:tune-variant"],["decor","mdi:draw"]].map(([e,t])=>j``)} +
`:G} + ${this._t("count.devices",{n:_.filter(e=>!e.hidden).length})} + + ${this._labsIso&&"view"===this._mode&&!this._kiosk?j``:G} +
+ + ${""} + + +
+ ${this._norm&&this._canEdit?j` + + `:G} + ${this._kiosk?G:this._summary?.renderControls(!1)} +
+ ${this._canEdit&&!this._kiosk?j`
+
+ ${this._editorRuntime?"plan"===D?this._renderMarkupBar():"devices"===D?this._renderDevicesBar():this._renderDecorBar():G} +
+
`:G} +
+ +
this._markupClick(e)} + @wheel=${e=>this._onWheel(e)} + @pointerdown=${e=>{this._notePointer(e),this._stagePointerDown(e)}} + @pointermove=${e=>this._stagePointerMove(e)} + @pointerleave=${e=>this._stagePointerLeave(e)} + @pointerup=${e=>this._stagePointerUp(e)} + @pointercancel=${e=>this._stagePointerCancel(e)}> + ${Sr(I,O)} + ${this._editorRuntime?this._renderEditorSecondary():G} +
+ ${d&&M?.structural?W``:G} + ${I&&E.length?W``:G} + + + ${""} + ${this._wallHatchDefs(g.color)}${$r(E)} + ${this._editing?this._renderMarkupDefs(c):G} + ${""} + ${this._editing&&!this._markup&&this._gridLevels()?W``:G} + ${a.bg&&P?W`this._onBackdropLoaded(a.bg.href,P)} + transform=${a.bg.angle?`rotate(${a.bg.angle} ${a.bg.x+a.bg.w/2} ${a.bg.y+a.bg.h/2})`:G} + @dblclick=${e=>this._openBackdropDialog(e)} + preserveAspectRatio="none" />`:G} + ${(()=>{const e=this._openCuts(),t=this._thickWallCuts(),i=this._wallUnionGeometry()?.roomGeom,n=new Map,r=e=>(n.has(e)||n.set(e,ni(e)),n.get(e));return a.rooms.filter(e=>e.area||"view"===this._mode||this._markup||g.showBorders).map(n=>{let o="room "+(a.bg?"overlay":"yard")+(this._markup?" outlined":"");!this._markup||n.id!==this._mergeSel&&n.id!==this._splitSel?.roomId||(o+=" picked");let s="";const l=Nn(g.fill,n);if(!this._markup&&(g.showBorders||"none"!==l)){o+=" styled";const e=[];e.push(`--room-stroke:${g.color}`,`--room-stroke-op:${g.showBorders?g.opacity:0}`);const t=f.byRoom.get(n)||null;t?(o+=" filled",e.push(`--room-fill:${t.color}`,`--room-fill-op:${t.opacity}`)):e.push("--room-fill:transparent","--room-fill-op:0"),s=e.join(";")}let c;const h=e=>{this._roomTipEnabledForPointer(e)&&(void 0===c&&(c=this._roomArea(n)),this._showTip(e,n.name||this._t("room.unnamed"),c?this._t("tip.area",{value:c}):"",y?this._roomLqi(n.area):null,this._roomTemp(n),this._roomHum(n),!0))},d=e=>{this._notePointer(e),this._pointerModality.hoverEnabled&&(this._hoverRoom={space:a.id,room:n},this._syncLiveHover())},u=r(n),p=this._markup&&(n.id===this._mergeSel||n.id===this._splitSel?.roomId),_=u&&!p?e.filter(e=>{const t=[(e[0]+e[2])/2,(e[1]+e[3])/2];return u.some((e,i)=>Un(t,[e[0],e[1],...u[(i+1)%u.length]])<=.08*this._gridPitch)}):[],m=p?[]:t,v=_.concat(m);v.length&&(o+=" noedge");const b=this._spaceWalls.length&&n.id&&u&&this._innerRoomContour(a,n.id,e,i)||u,w=b?Ri(b,(k=n,a.rooms.filter(e=>e!==k).map(r).filter(Boolean))):[];var k;const x=e=>"M "+e.map(e=>e[0]+" "+e[1]).join(" L ")+" Z",S=b?this._cleanFloor(n,b,a).path:"",$=n.id||G,M=n.area||G,R=S&&b?W`this._clearPointerHover()}>`:w.length&&b?W`this._clearPointerHover()}>`:b&&b!==u?W`this._clearPointerHover()}>`:n.poly?W`this._clearPointerHover()}>`:W`this._clearPointerHover()}>`,C=v.length&&u?Fn(u,v,.02*this._gridPitch):null,T=C?W``:G;return W`${R}${T}`})})()} + ${this._renderRoomHoverFill(A)} + ${this._renderOpeningTunnelFills(a,f)} + ${this._renderGlowBaseRooms(a,v)} + ${this._renderOpeningTunnelFills(a,v,"glow-base")} + ${""} + ${g.hideDecor&&"decor"!==this._mode?G:this._renderDecorLayer(void 0,S)} + ${H?this._renderGlowLayer(a,g,S):G} + ${this._renderSunRays(a)} + ${this._editing?W`${this._renderAlignGuides()}`:G} + ${this._markup?W`${this._renderMarkupLayer(c)}`:G} + ${""} + ${""} + ${this._editing?G:this._renderZeroWalls(g)} + ${this._renderWallBodies(g)} + ${this._markup&&"resize"===this._tool?this._renderResizeMeasurements():G} + ${this._renderRoomHoverOutline(A)} + ${""} + ${this._editing?this._renderZeroWalls(g):G} + ${this._markup?W`${this._renderHiddenWallDiagnosticOverlay()}`:G} + ${this._markup?W`${this._renderOpeningPlacementPreview()}`:G} + ${T?this._renderOpeningDimensionGuides(T):G} + ${T?.guide?this._renderOpeningCenterTick(T.guide):G} + ${""} + ${""} + ${this._markup?W`${this._renderActiveChainInk()}`:G} + ${this._markup?W`${this._renderPlanSnapOverlay()}`:G} + ${g.hideOpenings&&!this._markup||M&&!M.floorSymbols?G:this._renderOpenings(g)} + ${this._renderWallThickUi()} + ${this._markup&&"resize"===this._tool?this._renderResizeLayer(S):G} + ${""} + ${this._renderBackdropFrame(S)} + ${this._renderTextFrame(S)} + + + + ${Me(d&&M?.structural?W` + + `:G)} + ${""} +
+ ${function(e,t,i){const n=[...e];if(!n.length)return G;const r=[],o=[],s=[];for(const e of n){for(const t of e.zones){if(!(!0===t.state||"number"==typeof t.state&&t.state>0)||!t.polygon)continue;const e=t.polygon.map(e=>i([1e3*e[0],1e3*e[1]]));s.push(W``${e[0]},${e[1]}`).join(" ")}>`)}for(const t of e.ranges)if(t.segments)for(const e of t.segments){const t=e.map(e=>i([1e3*e[0],1e3*e[1]]));o.push(W``${e[0]},${e[1]}`).join(" ")}>`)}for(const n of e.targets){if(!n.included)continue;const o=i([1e3*n.x,1e3*n.y]),s=(o[0]-t.x)/t.w*100,a=(o[1]-t.y)/t.h*100;r.push(j``)}}return o.length||s.length||r.length?j`${o.length||s.length?W``:G}${r}`:G}([...this._radarLive.frames.values()].filter(e=>{const t=this._serverCfg?.markers.find(t=>t.id===e.marker_id);return!!t&&Tg(t,this._space)}),S,e=>this._scenePoint(e))} + ${Re(a.id,Te(_,e=>e.id,e=>this._renderDevice(e,S,y,R?.devices.get(e.id))))} + ${this._renderVacuums(this._renderVacuumDevices,S,a.id)} + ${this._renderVacFit(S)} + ${this._renderOpeningLocks(S,R?.locks)} + ${g.showNames||this._markup?a.rooms.map(e=>this._renderRoomLabel(e,a,S,g,R?.rooms.get(e))):G} + ${this._markup?a.rooms.map(e=>this._renderRoomGear(e,a,S)):G} + ${q={hass:this.hass,settings:this._settings,devices:this._renderDevices,registry:this._haRegistry,currentSpace:a.id,spaces:this._serverCfg?.spaces,viewKey:S,view:"view"===this._mode,kiosk:this._kiosk},q.view&&!q.kiosk&&!0===q.hass?.user?.is_admin&&Ig(q.settings).enabled?(import("./hp-zigbee-topology-overlay-Bt3_AzlX.js"),j``):G} +
+
+ ${this._wallDialog?j`
${this._renderWallThickDialog()}
`:G} +
+ + ${this._renderFarHint()} + ${this._renderHomeArrow(this._baseVb(h,x))} + ${this._renderEditorRuntimeLoading()} + ${this._renderRecoveryOverlay()} + ${this._summary?.renderMeasure()} + ${this._kiosk?this._summary?.renderControls(!0):G} + ${this._summary?.renderPanel()} + ${this._booting||this._bootFading?j``:G} +
+ + ${this._roomDialog&&this._editorRuntime?this._renderRoomDialog():G} + ${this._mergeDialog&&this._editorRuntime?this._renderMergeDialog():G} + ${this._openingDialog&&this._editorRuntime?this._renderOpeningDialog():G} + ${this._physicalDialog&&this._editorRuntime?this._renderPhysicalDialog():G} + ${this._partitionDeleteDialog&&this._editorRuntime?this._renderPartitionDeleteDialog():G} + ${this._roomDeleteDialog&&this._editorRuntime?this._renderRoomDeleteDialog():G} + ${this._openingInfo?this._renderOpeningInfoCard():G} + ${this._decorTextDialog&&this._editorRuntime?this._renderDecorTextDialog():G} + ${this._decorShapeDialog&&this._editorRuntime?this._renderDecorShapeDialog():G} + ${this._backdropDialog&&this._editorRuntime?this._renderBackdropDialog():G} + ${this._decorEraseConfirm&&this._editorRuntime?this._renderDecorEraseConfirm():G} + ${this._spaceDialog&&(this._onboardingRuntime||this._editorRuntime)?this._renderSpaceDialog():G} + ${this._deviceInbox&&this._editorRuntime?this._renderDeviceInbox():G} + ${this._markerDialog&&this._editorRuntime?this._renderMarkerDialog():G} + ${this._backdropGuard?this._editorRuntime?this._editorRuntime._renderBackdropGuard():this._onboardingRuntime?._renderBackdropGuard()??G:G} + ${this._vacCalConfirm&&this._editorRuntime?j`{this._vacCalConfirm?.busy||(this._vacCalConfirm=null)}}> +
+

${this._t("vac.residual_message",{error:this._vacCalConfirm.error})}

+
+
+ + + + +
+
`:G} + ${this._infoCard?this._renderInfoCard():G} + ${this._rulesDialog&&this._editorRuntime?this._renderRulesDialog():G} + ${this._settingsDialog&&this._editorRuntime?this._renderSettingsDialog():G} + ${this._supportDialog&&this._editorRuntime?this._renderSupportDialog():G} + ${this._pdfDialog?this._renderPdfDialog():G} + ${this._alignDialog&&this._editorRuntime?this._renderAlignDialog():G} + ${this._backupExportDialog&&this._editorRuntime?this._renderBackupExportDialog():G} + ${this._backupImportDialog&&this._editorRuntime?this._renderBackupImportDialog():G} + ${this._importDialog&&this._onboardingRuntime?this._renderImportDialog():G} + + ${this._kiosk&&!this._hasFixedFloor&&this._kioskDots&&this._model.length>1?j`
+ ${this._model.map(e=>j``)} +
`:G} + ${this._kioskDialog?this._renderKioskDialog():G} + ${this._summary?.dialogOpen?this._summary.renderDialog():G} + ${this._vacFit?j`
+ ${this._t("vac.fit_hint")} + + + + +
`:G} + ${this._tapConfirm?j`this._tapConfirm=null}> +
+ ${"run"===this._tapConfirm.kind?j`

${this._tapConfirm.text}

`:this._tapConfirm.lines.map((e,t)=>j` +

${e}

`)} +
+
+ + + +
+
`:G} + ${this._toast?j``:G} +
+ `;var q}_vacCandidateStatus(e,t,i=this._planHass){const n=this._bindingStatus("entity:"+e);if("ha_disabled"===n.kind)return"disabled";if("orphaned"===n.kind)return"missing";if("unverified"===n.kind)return"unverified";const r=i?.states?.[e];return"unavailable"===r?.state?"unavailable":t?.hasPosition?"ok":"unsupported"}_vacOpenAllCameras(e){const t=this._haRegistry.entities||{},i=[];for(const[e,n]of Object.entries(this.hass?.states||{})){if(!e.startsWith("camera."))continue;const r=Kc(e,n,t[e]);r&&i.push(r)}this._vacAllCameraCache={devId:e.id,candidates:i},this._vacAllCamerasFor=e.id}_vacSourceResolution(e,t=!1,i=this._planHass){const n=e.marker?.vacuum,r="string"==typeof n?.source&&!!n.source,o=new Set(e.entities||[]),s=new Set(o);r&&s.add(n.source);const a=i?.entities||{},l=[];for(const e of s){const t=i?.states?.[e],o=Kc(e,t,a[e]);o?l.push(o):r&&e===n.source&&l.push({entityId:e,name:String(t?.attributes?.friendly_name||e),platform:a[e]?.platform?String(a[e].platform):null,category:e.startsWith("camera.")?"camera":"partial",hasPosition:!1,hasRooms:!1,hasPath:!1,hasMapId:!1,score:0})}if(t&&this._vacAllCameraCache?.devId===e.id){const e=new Set(l.map(e=>e.entityId));for(const t of this._vacAllCameraCache.candidates)e.has(t.entityId)||l.push(t)}const c={};for(const e of l)c[e.entityId]=this._vacCandidateStatus(e.entityId,e,i);return function(e,t,i,n){const r="string"==typeof e&&e.length>0,o=new Set(t),s=Array.from(i).sort((t,i)=>r&&t.entityId===e?-1:r&&i.entityId===e?1:i.score-t.score||t.entityId.localeCompare(i.entityId));if(r){const t=s.find(t=>t.entityId===e);return{entityId:e,status:n[e]||(t?.hasPosition?"ok":"unverified"),pinned:!0,candidates:s}}const a=s.find(e=>o.has(e.entityId)&&e.hasPosition&&"ok"===n[e.entityId]);return a?{entityId:a.entityId,status:"ok",pinned:!1,candidates:s}:{entityId:null,status:"none",pinned:!1,candidates:s}}(n?.source,o,l,c)}_vacSource(e,t=this._planHass){if(!1===e.marker?.vacuum?.live)return null;const i=this._vacSourceResolution(e,!1,t);return"ok"===i.status||"unsupported"===i.status?i.entityId:null}_vacEntity(e){return e.primary?.startsWith("vacuum.")?e.primary:(e.entities||[]).find(e=>e.startsWith("vacuum."))||null}_isVacDev(e){return!!this._vacEntity(e)}_activitySourceKey(e){return this._activitySnapshot(e).sourceKey}_activitySnapshot(e,t=Nd(this._planHass,this._devices,null,this._virtualLights)){const i=c_(this._planHass,e,this._devices,t,this._fullRegistryHass);return{samples:i.samples,sourceKey:u_(this._planHass,e,i)}}_stampActivity(e,t,i){let n=this._activityRt.get(e);n||(n=ng(i||"",[]),this._activityRt.set(e,n)),null!=i&&(n.sources=i),og(n,t,Date.now(),window.clearTimeout.bind(window),e=>window.setTimeout(()=>this.requestUpdate(),e))}_syncActivityRuntime(){const e=new Map;if(!this.hass)return e;if(!1===this._config?.live_states){for(const e of this._activityRt.values())clearTimeout(e.timer);return this._activityRt.clear(),e}const t=new Set,i=Nd(this._planHass,this._devices,null,this._virtualLights);for(const n of this._devices){if(n.hidden)continue;if("icon_ripple"!==Li(n.marker?.display))continue;t.add(n.id);const r=this._activitySnapshot(n,i);e.set(n.id,r);const{samples:o,sourceKey:s}=r;let a=this._activityRt.get(n.id);a?a.sources!==s&&rg(a,s,o,window.clearTimeout.bind(window)):(a=ng(s,o),this._activityRt.set(n.id,a))}for(const[e,i]of this._activityRt)t.has(e)||(clearTimeout(i.timer),this._activityRt.delete(e));return e}_activityTick(){if(!this.hass)return;const e=this._syncActivityRuntime();for(const t of this._devices){if(t.hidden)continue;if("icon_ripple"!==Li(t.marker?.display))continue;const i=e.get(t.id)||this._activitySnapshot(t),{samples:n,sourceKey:r}=i,o=this._activityRt.get(t.id);if(!o||o.sources!==r)continue;const s=sg(o,n,window.clearTimeout.bind(window));s&&this._stampActivity(t.id,s,r)}}_vacTick(){if(this.hass)for(const e of this._devices){if(e.hidden||!this._isVacDev(e))continue;if("static_icon"===Li(e.marker?.display)){this._vacRt.delete(e.id);continue}const t=this._vacSource(e);if(!t)continue;const i=this._vacEntity(e),n=Qc(this.hass.states[i||""]?.state),r=Uc(this.hass.states[t]?.attributes);let o=this._vacRt.get(e.id);o||(o={trail:[],lastKey:"",lastTs:0,moving:!1,jump:!1,endedTs:0,lastPos:null},this._vacRt.set(e.id,o)),n&&!o.moving&&(o.trail=[],o.lastPos=null);const s="never"!==oh(e.marker?.vacuum)&&!r?.path.length;!n&&o.moving&&(o.endedTs=Date.now(),s&&o.lastPos&&(o.trail=Jc(o.trail,o.lastPos,40)),o.lastPos=null),o.moving=n;const a=r?.pos;if(n&&a){const e=a.x+":"+a.y;if(e!==o.lastKey){const t=Date.now();o.jump=o.lastTs>0&&t-o.lastTs>1e4,o.lastKey=e,o.lastTs=t,s&&o.lastPos&&(o.trail=Jc(o.trail,o.lastPos,40)),o.lastPos=[a.x,a.y]}}}}_vacEnsureMarker(e){const t=this._serverCfg;if(!t)return null;t.markers=t.markers||[];const i=t.markers.find(t=>t.id===e.id);if(i)return i;if("device"!==e.bindingKind&&"entity"!==e.bindingKind||!e.bindingRef)return null;const n={id:e.id,binding:e.bindingKind+":"+e.bindingRef,space:e.space||null,area:e.area||null,hidden:!!e.hidden};return t.markers.push(n),n}_renderVacSection(e){return this._editorRuntimeOrThrow()._renderVacSection(e)}_vacMapId(e,t,i=this._planHass){const n=this._vacEntity(e),r=n?i?.states?.[n]?.attributes?.selected_map:null;return o=t.mapId,s=r,"default"!==o?o:null!=s?String(s):"default";var o,s}_vacObservedMapId(e,t,i=this._planHass){const n=Uc(i?.states?.[t]?.attributes);return n?this._vacMapId(e,n,i):void 0}_vacSaveMatrix(e,t,i,n,r=""){return this._editorRuntimeOrThrow()._vacSaveMatrix(e,t,i,n,r)}_vacPlanRoomAnchors(e){return this._editorRuntimeOrThrow()._vacPlanRoomAnchors(e)}_vacAutoCalibrate(e){return this._editorRuntimeOrThrow()._vacAutoCalibrate(e)}_vacApplyCalibrationProposal(e){return this._editorRuntimeOrThrow()._vacApplyCalibrationProposal(e)}_vacStartFit(e){return this._editorRuntimeOrThrow()._vacStartFit(e)}_vacFitSave(){return this._editorRuntimeOrThrow()._vacFitSave()}_vacFitTurn(e){return this._editorRuntimeOrThrow()._vacFitTurn(e)}_vacGhostCentre(e){return this._editorRuntimeOrThrow()._vacGhostCentre(e)}_vacDelta(e,t,i){return this._editorRuntimeOrThrow()._vacDelta(e,t,i)}_vacFitPointer(e,t){return this._editorRuntimeOrThrow()._vacFitPointer(e,t)}_renderVacFit(e){return this._editorRuntime?this._editorRuntimeOrThrow()._renderVacFit(e):G}_vacRafLoop(){this._vacRaf=requestAnimationFrame(()=>{const e=this.renderRoot,t=this._stageEl,i=this._vacLastView,n=e?.querySelectorAll?.(".vacpuck")||[];if(!t||!i||!n.length)return void(this._vacRaf=0);const r=t.getBoundingClientRect();for(const t of n){const n=t.getAttribute("data-mid"),o=t.getBoundingClientRect(),s=i.x+(o.left+o.width/2-r.left)/r.width*i.w,a=i.y+(o.top+o.height/2-r.top)/r.height*i.h;for(const t of e.querySelectorAll(`line.tip[data-mid="${n}"]`))t.setAttribute("x2",s.toFixed(1)),t.setAttribute("y2",a.toFixed(1))}this._vacRafLoop()})}_vacTrailPathD(e,t){const i=e.map(e=>e.map(([e,i])=>zc(t,e,i))),n=function(e,t,i=console.warn){if(!Number.isFinite(t)||t<=0)return[];const n=[];let r=0;for(const i of e){if(!i.every(jc)){r++;continue}const e=i.filter((e,t)=>0===t||!Wc(e,i[t-1]));if(e.length<2)continue;const o=[{kind:"move",point:e[0]}];if(2!==e.length){for(let i=1;i0&&i(`[houseplan] vacuum trail: ${r} segment(s) dropped — non-finite point (check map calibration)`),n}(i,this._cmToUnits(17.5)),r=e=>{const t=this._scenePoint(e);return`${t[0].toFixed(1)} ${t[1].toFixed(1)}`};return n.map(e=>e.map(e=>"move"===e.kind?`M ${r(e.point)}`:"line"===e.kind?`L ${r(e.point)}`:`Q ${r(e.control)} ${r(e.point)}`).join(" ")).join(" ")}_renderVacuums(e,t,i){if(this._markup||"decor"===this._mode)return G;const n=this._space+"|"+t.x+"|"+t.y+"|"+t.w+"|"+t.h,r=this._vacJumpOnce||n!==this._vacViewKey;this._vacViewKey=n,this._vacJumpOnce=!1;const o=[],s=[];for(const n of e){if(n.hidden||!this._isVacDev(n))continue;if("static_icon"===Li(n.marker?.display))continue;const e=this._renderDeviceSnapshot?.facts.get(`vacuum:${n.id}`),a=e?.source??this._vacSource(n,this._renderPlanHass);if(!a)continue;const l=e?.telemetry??Uc(this._renderPlanHass?.states[a]?.attributes);if(!l)continue;const c=e?.routes??ch(n.id,n.marker?.vacuum??null,n.space,a),h=e?.resolution??dh({routes:c,observed:uh(c,[a],e=>this._vacObservedMapId(n,e)),spaceIds:new Set(this._model.map(e=>e.id))}),d=e?.server??this._vacSrvTrails[n.id],u=_h({resolution:h,routes:c,renderSpace:i,rootSource:n.marker?.vacuum?.source??null,serverCurrent:d?.current??null,serverPrevious:d?.previous??null,explicitRoutes:Array.isArray(n.marker?.vacuum?.map_routes)});if(!u.live&&!u.previous)continue;const p=u.live,_=e?.runtime??this._vacRt.get(n.id),m=_?.moving??!1,g=oh(n.marker?.vacuum),f="always"===g||"cleaning"===g&&m,v=d,y=u.currentRunMatches&&Array.isArray(v?.current?.points)?v.current:null,b=u.previous&&Array.isArray(v?.previous?.points)?v.previous:null;if("always"===g&&b&&u.previous){const e=Lc(b.points),t=this._vacTrailPathD(e,u.previous);t&&s.push(W``)}if(f&&p){const e=Bc(l,y,_?.trail||[]),t=!m||"integration"!==e.source&&"server"!==e.source?e.path:qc(e.path);if(t.length){const e=this._vacTrailPathD(t,p);e&&s.push(W``);const i=t[t.length-1];if(m&&i?.length>=2){const e=i[i.length-1],[t,r]=zc(p,e[0],e[1]),o=this._scenePoint([t,r]),a=o[0].toFixed(1),l=o[1].toFixed(1);s.push(W``)}}}if(!m||!l.pos||!p)continue;const[w,k]=zc(p,l.pos.x,l.pos.y),x=this._scenePoint([w,k]),S=(x[0]-t.x)/t.w*100,$=(x[1]-t.y)/t.h*100,M=_&&_.lastTs>0&&Date.now()-_.lastTs>6e4,R=n.marker?.icon||n.icon||"mdi:robot-vacuum";o.push(j`
{e.stopPropagation();const t=this._vacEntity(n);t&&this._openMoreInfo(t)}}> + +
`)}return this._vacLastView=t,o.length&&!this._vacRaf&&this._vacRafLoop(),o.length||s.length?j` + ${s.length?W`${s}`:G} + ${o}`:G}_renderDevice(e,t,i=!0,n){const r=this._pos(e),o=n?.visualScene??this._scenePoint([r.x,r.y]),s=(o[0]-t.x)/t.w*100,a=(o[1]-t.y)/t.h*100,l=this._devicePresentation(e,i),c=[`left:${s}%`,`top:${a}%`,...w_(l)],h=l.disabledReason,d=l.haDisabled?this._t(`marker.ha_disabled_${h}`):e.userHidden?this._t("marker.hidden_ghost"):e.name,u=n_(l),p="view"===this._mode||"devices"===this._mode,_=i_([d,l.haDisabled?"":this._t(`marker.state_a11y_${u}`),"none"!==l.pulse.kind?this._t(`marker.pulse_a11y_${l.pulse.reason}`):"",l.valueFullText||l.valueText||"",Ip(l.valueBadge),null!=l.lqiText&&l.lqiBand?this._t(`marker.lqi_a11y_${l.lqiBand}`,{value:l.lqiText}):""]);return j`
this._clickDevice(t,e)} + @keydown=${t=>this._keyDevice(t,e)} + @focus=${t=>this._showDeviceFocusTip(t,e)} + @focusout=${()=>this._hideDeviceFocusTip(e.id)} + @contextmenu=${t=>this._ctxDevice(t,e)} + @pointerover=${t=>{"view"!==this._mode&&"devices"!==this._mode||this._showDeviceTip(t,this._deviceForPointerEvent(t,e))}} + @pointerleave=${()=>this._clearPointerHover()} + @pointerdown=${t=>this._pointerDown(t,e)} + @pointermove=${t=>{if("view"!==this._mode&&"devices"!==this._mode)return;const i=this._pointerMove(t,e);i&&this._showDeviceTip(t,i)}} + @pointerup=${t=>this._pointerUp(t,e)} + @pointercancel=${t=>this._pointerCancel(t,e)} + @lostpointercapture=${t=>this._pointerCancel(t,e)} + > + ${x_(l,{newDevice:this._newIds.has(e.id),newDeviceTitle:this._t("device.new"),disabledTitle:l.haDisabled?d:""})} + ${this._vacRouteBadge(e)} +
`}_vacRouteBadge(e){if(!this._isVacDev(e)||e.hidden)return G;if("static_icon"===Li(e.marker?.display))return G;const t=this._renderDeviceSnapshot?.facts.get(`vacuum:${e.id}`),i=function(e,t){if(!t||!e)return null;switch(e.kind){case"unmapped":case"needs_calibration":case"ambiguous":case"missing_space":return e.kind;default:return null}}(t?.resolution,this._vacRt.get(e.id)?.moving??!1);if(!i)return G;const n=this._t(`vac.route_warn_${i}`);return j` + `}_roomArea(e){const t=ni(e);if(!t)return null;const i=this._spaceModel();if(!i)return null;const n=this._spaceWalls.length&&e.id&&this._innerRoomContour(i,e.id)||t,r=this._cleanFloor(e,n),o=this._cellCm/this._gridPitch;return Xn(r.area*o*o/1e4,"mi"===this._renderPlanHass?.config?.unit_system?.length)}_roomTemp(e){const t=e.settings?.temp_source,i=au(this._spaceModel()?.id,e);return t?ou(this._renderPlanHass,t,"temp",this._markers):i?this._climate().get(i)?.temp??null:null}_roomHum(e){const t=e.settings?.hum_source,i=au(this._spaceModel()?.id,e);return t?ou(this._renderPlanHass,t,"hum",this._markers):i?this._climate().get(i)?.hum??null:null}_climate(){const e=this._serverCfg?.markers,t=this._renderPlanHass,i=this._climateCache,n=this._settings.exclude_integrations;if(i&&i.h===t&&i.r===this._iconRules&&i.mk===e&&i.ex===n)return i.m;const r=hu(t,this._iconRules,e,this._excluded);return this._climateCache={h:t,r:this._iconRules,mk:e,ex:n,m:r},r}_resetRoomDialogFields(){return this._editorRuntimeOrThrow()._resetRoomDialogFields()}_openRoomEdit(e){return this._editorRuntimeOrThrow()._openRoomEdit(e)}_roomSettingsFromDialog(){return this._editorRuntimeOrThrow()._roomSettingsFromDialog()}_saveRoomEdit(){return this._editorRuntimeOrThrow()._saveRoomEdit()}_roomSrcCandidates(){return this._editorRuntimeOrThrow()._roomSrcCandidates()}_roomSrcLabel(e){return this._editorRuntimeOrThrow()._roomSrcLabel(e)}_labelPos(e,t){const i=this._layout["rl_"+(e.id||"")];if(i&&i.s===t)return{x:i.x*mv,y:i.y*mv};const n=this._roomCenter(e),r=this._gridPitch;return{x:sl(Qt(n[0],r)),y:sl(Qt(n[1],r))}}_labelDown(e,t,i){if(this._editorRuntime)return this._editorRuntimeOrThrow()._labelDown(e,t,i)}_labelMove(e,t,i){if(this._editorRuntime)return this._editorRuntimeOrThrow()._labelMove(e,t,i)}_labelUp(e){if(this._editorRuntime)return this._editorRuntimeOrThrow()._labelUp(e)}_labelScale(e){const t=this._layout["rl_"+(e.id||"")]?.k;return"number"==typeof t&&Number.isFinite(t)?Math.min(3,Math.max(.5,t)):1}_rlResizeDown(e,t,i){return this._editorRuntimeOrThrow()._rlResizeDown(e,t,i)}_rlResizeMove(e){return this._editorRuntimeOrThrow()._rlResizeMove(e)}_rlResizeUp(){return this._editorRuntimeOrThrow()._rlResizeUp()}_renderRoomGear(e,t,i){return this._editorRuntimeOrThrow()._renderRoomGear(e,t,i)}_renderRoomLabel(e,t,i,n,r){if(!e.name&&!this._markup)return G;const o=this._labelPos(e,t.id),s=r?.visualScene??this._scenePoint([o.x,o.y]),a=(s[0]-i.x)/i.w*100,l=(s[1]-i.y)/i.h*100,c=Math.min(1,n.opacity+.25),h=this._labelScale(e),d=[];if(n.labelTemp||n.labelHum||n.labelLqi&&e.area||n.labelLight){if(n.labelTemp){const t=this._roomTemp(e);null!=t&&d.push(j`${t}°`)}if(n.labelHum){const t=this._roomHum(e);null!=t&&d.push(j`${t}%`)}if(n.labelLqi&&e.area){const t=this._roomLqi(e.area);null!=t&&d.push(j`${t}`)}if(n.labelLight){const t=(u=Nd(this._renderPlanHass,this._renderDevices,e,this._virtualLights)).length?{on:u.filter(e=>e.on).length,total:u.length}:null;if(t){const e=0===t.on?this._t("roomcard.light_off"):t.on===t.total?this._t("roomcard.light_on"):this._t("roomcard.light_partial",{on:t.on,total:t.total});d.push(j`${e}`)}}}var u;const p=!!e.area,_=!this._markup;return j`
this._roomLabelKey(t,e.id):G} + @pointerdown=${this._markup?i=>this._labelDown(i,e,t.id):G} + @pointermove=${this._markup?i=>this._labelMove(i,e,t.id):G} + @pointerup=${this._markup?()=>this._labelUp(e):G} + @pointercancel=${this._markup?()=>this._labelUp(e):G} + >${e.name||(this._markup?this._t("room.unnamed"):"")}${p?j`{t.stopPropagation(),this._clickRoom(e)}:G} + @pointerdown=${_?e=>e.stopPropagation():G}>`:G} + ${d.length?j`${d}`:G} + ${"plan"===this._mode?["tl","tr","bl","br"].map(i=>j`this._rlResizeDown(i,e,t.id)} + @pointermove=${e=>this._rlResizeMove(e)} + @pointerup=${()=>this._rlResizeUp()} + @pointercancel=${()=>this._rlResizeUp()}>`):G} +
`}_renderLiveEditorMeasurements(e){const t=e,i=this._opMeasureView,n=this._decorMeasure,r=this._bdLive,o=this._editorRuntime?._furnLive()??null;return j` + ${this._measureAnchor?j`
${this._renderMeasureLabel(t)}
`:G} + ${this._resize?.liveLabels?j`
${this._resize.liveLabels.map(e=>j`
${e.text}
`)}
`:G} + ${i?j`
${i.labels.map(e=>j`
${e.text}
`)}
`:G} + ${n?j`
${n.text}
`:G} + ${o?j`
${o.map(e=>j`
${e.text}
`)}
`:G} + ${r?j`
${r.text}
`:G} + `}get _measureAnchor(){return this._markup&&this._cursorPt?"draw"===this._tool&&this._path.length&&!this._contourClosed?this._path[this._path.length-1]:"split"===this._tool&&this._splitSel?.pts?.length?this._splitSel.pts[this._splitSel.pts.length-1]:null:null}_renderMeasureLabel(e){const t=this._measureAnchor,i=this._cursorPt,n=(i[0]-e.x)/e.w*100,r=(i[1]-e.y)/e.h*100,o=jn(t,i),s=Math.round(10*o)/10,a=function(e,t,i=.001){if(e.length<2||t.length<2)return!1;const n=Math.abs(t[0]-e[0]),r=Math.abs(t[1]-e[1]);if(!Number.isFinite(n)||!Number.isFinite(r)||Math.hypot(n,r)<=i)return!1;const o=Math.max(n,r,1);return n<=i*o||r<=i*o||Math.abs(n-r)<=i*o}(t,i,2e-4*this._gridPitch);return j`
+ ${this._fmtLen(t,i)} · ${s}°
`}get _decorMeasure(){const e=this._decorDraft;if(!e||"decor"!==this._mode)return null;const[t,i]=e.a,[n,r]=e.b;if(Math.abs(t-n)<1e-6&&Math.abs(i-r)<1e-6)return null;const o=(t+n)/2,s=(i+r)/2;if("line"===e.kind){const t=jn(e.a,e.b);return{x:o,y:s,on45:Wn(t),text:`${this._fmtLen(e.a,e.b)} · ${Math.round(10*t)/10}°`}}const a=this._fmtLen([t,i],[n,i]),l=this._fmtLen([n,i],[n,r]);if("ellipse"===e.kind){const e=this._fmtLen([0,0],[Math.abs(n-t)/2,0]),a=this._fmtLen([0,0],[0,Math.abs(r-i)/2]);return{x:o,y:s,on45:!1,text:Math.abs(Math.abs(n-t)-Math.abs(r-i))<1e-6?`R ${e}`:`Rx ${e} × Ry ${a}`}}return{x:o,y:s,on45:!1,text:`${a} × ${l} · ${Xn(Pr(Math.abs(n-t),this._cellCm,this._gridPitch)*Pr(Math.abs(r-i),this._cellCm,this._gridPitch)/1e4,this._imperial)}`}}get _alignPoint(){if(this._markup){if("draw"===this._tool&&this._path.length&&!this._contourClosed&&this._cursorPt)return this._cursorPt;if("split"===this._tool&&this._splitSel?.pts?.length&&this._cursorPt)return this._cursorPt;if(this._drag?.id.startsWith("rl_")&&this._drag.moved){const e=this._drag.id.slice(3),t=this._spaceModel()?.rooms.find(t=>t.id===e);return t?(()=>{const e=this._labelPos(t,this._space);return[e.x,e.y]})():null}return null}if("devices"===this._mode&&this._deviceDrag?.moved){const e=this._devices.find(e=>e.id===this._deviceDrag.id);return e?(()=>{const t=this._livePos(e);return[t.x,t.y]})():null}if("decor"===this._mode){if(this._decorDraft)return this._decorDraft.b;if(this._decorMove){const e=this._decorList.find(e=>e.id===this._decorMove.id);if(!e)return null;const t=mv,i=this._decorH;return"line"===e.kind?[e.x1*t,e.y1*i]:[e.x*t,e.y*i]}return null}return null}_alignCandidates(){return this._editorRuntimeOrThrow()._alignCandidates()}_renderAlignGuides(){return this._editorRuntime?._renderAlignGuides()??G}_renderOpeningCenterTick(e){return this._editorRuntimeOrThrow()._renderOpeningCenterTick(e)}_renderOpeningDimensionGuides(e){return this._editorRuntimeOrThrow()._renderOpeningDimensionGuides(e)}_roomCenter(e){if(e.poly){const t=e.poly.length;return[e.poly.reduce((e,t)=>e+t[0],0)/t,e.poly.reduce((e,t)=>e+t[1],0)/t]}return[e.x+e.w/2,e.y+.1*Math.min(e.w,e.h)]}_openingAmt(e){const t=e.contact&&this._renderOpeningEntityAvailable(e.contact)?this._renderPlanHass.states[e.contact]:null;return ci(e.type,t?.state,!!e.invert,t?.attributes?.current_position)}_planEntityAvailable(e){return!!e&&(!Qd(this._fullRegistryHass,e,Jd(this._markers))&&"active"===this._bindingStatus("entity:"+e).kind)}_renderEntityAvailable(e){return!!e&&(!Qd(this._renderPlanHass,e,Jd(this._markers))&&(!!this._renderPlanHass.entities?.[e]&&!!this._renderPlanHass.states?.[e]))}_openingEntityAvailable(e){return function(e,t,i=rd(e)){return!!t&&"active"===ud(e,`entity:${t}`,i).kind}(this.hass,e,this._haRegistry)}_renderOpeningEntityAvailable(e){return t=this._renderPlanHass,!!(i=e)&&!!t?.states?.[i];var t,i}_renderOpeningPlacementPreview(){return this._editorRuntimeOrThrow()._renderOpeningPlacementPreview()}_renderOpenings(e,t){const i=t?this._openingsR.filter(e=>t.includes(e.id)):this._openingsR;if(!i.length)return W``;const n=this._spaceModel();if(!n)return W``;const r=e.color,o=this._spaceWalls,s=this._openCuts(),a=this._openingWallIndexFor(n,s).value;return W`${Re(n.id,Te(i,e=>e.id,e=>{if(e.orphanReason)return W`{t.stopPropagation(),this._editOpening(e)}}> + + ! + `;const t=this._openingAmt(e),i=t>0&&!!e.contact&&this._renderOpeningEntityAvailable(e.contact)?"var(--hp-open)":r,n="gate"===e.type?!e.flip_v:e.flip_v,s=e.partitionHost||o.length||"gate"===e.type?this._openingFace(e,a,!!n):{ox:0,oy:0,cm:0,side:-1},l={type:e.type,length:e.rlen,angle:e.angle,amount:t,flipH:!!e.flip_h,flipV:!!e.flip_v,base:r,tone:i,cellCm:this._cellCm,gridPitch:this._gridPitch,face:s},{half:c,outlineHalf:h,hitHalf:d}=Cp(l),u=qa(10,this._cellCm),p=qa(12,this._cellCm);return W` + ${Fp(l)} + + this._opClick(t,e)} + @pointerdown=${t=>this._opPointerDown(t,e)} + @pointermove=${t=>this._opPointerMove(t,e)} + @pointerup=${t=>this._opPointerUp(t,e)} + @pointercancel=${t=>this._opPointerUp(t,e)}> + `}))}`}_renderOpeningLocks(e,t){const i=this._openingsR.filter(e=>!e.orphanReason&&("door"===e.type||"gate"===e.type)&&e.lock&&this._renderOpeningEntityAvailable(e.lock));if(!i.length)return j``;const n=this._spaceModel();if(!n)return j``;const r=this._openCuts(),o=this._openingWallIndexFor(n,r).value;return j`${i.map(i=>{const n=this._renderPlanHass.states[i.lock]?.state,r="locked"===n,s=r||["unlocked","open","opening","unlocking","locking"].includes(String(n)),a="gate"===i.type?this._openingFace(i,o,!i.flip_v):null,l=Rp({x:i.rx,y:i.ry,angle:i.angle,flipV:!!i.flip_v,gateFace:a},this._cellCm)[0],c=t?.get(String(i.id)),h=c?.visualScene??this._scenePoint(l),d=(h[0]-e.x)/e.w*100,u=(h[1]-e.y)/e.h*100;return j`
{"view"===this._mode&&(e.stopPropagation(),this._openingInfo=i)}}> + +
`})}`}async _lockAction(e,t){if(this._openingEntityAvailable(e)){if("unlock"===t){const t=this.hass?.states?.[e]?.attributes?.friendly_name||e,i=await this._confirmDanger({key:"unlock",kind:"warning",title:this._t("confirm.unlock_title"),message:this._t("confirm.unlock_body"),objectName:t,confirmLabel:this._t("opening.unlock_action"),cancelLabel:this._t("btn.cancel")}),n=this._openingInfo;if(!i||!this._openingEntityAvailable(e)||!n||"door"!==n.type&&"gate"!==n.type||n.lock!==e||"locked"!==this.hass?.states?.[e]?.state)return}this.hass?.callService?.("lock",t,{entity_id:e})}}_renderOpeningInfoCard(){const e=this._openingInfo,t="passage"!==e.type&&e.contact&&this._openingEntityAvailable(e.contact)?e.contact:null,i=("door"===e.type||"gate"===e.type)&&e.lock&&this._openingEntityAvailable(e.lock)?e.lock:null,n=t?this.hass.states[t]?.state:null,r=this._openingAmt(e),o=i?this.hass.states[i]?.state:null,s="door"===e.type?"opening.door":"gate"===e.type?"opening.gate":"passage"===e.type?"opening.passage":"opening.window",a="door"===e.type?"mdi:door":"gate"===e.type?"mdi:gate":"passage"===e.type?"mdi:arch":"mdi:window-closed-variant",l="gate"===e.type?r>0?"mdi:gate-open":"mdi:gate":r>0?"mdi:door-open":"mdi:door-closed",c=(e,t,i,n="")=>j`
${t}${i}
`;return j`this._openingInfo=null}> +
+ ${t?c(l,this._t("opening.contact_label"),"unavailable"===n||null==n?this._t("opening.state_unknown"):this._t(r>0?"opening.open":"opening.closed"),r>0?"warn":"ok"):G} + ${i?c("locked"===o?"mdi:lock":"mdi:lock-open-variant",this._t("opening.lock_label"),"locked"===o?this._t("opening.locked"):["unlocked","open"].includes(String(o))?this._t("opening.unlocked"):this._t("opening.state_unknown"),"locked"===o?"ok":"warn"):G} + ${i&&("locked"===o||["unlocked","open"].includes(String(o)))?j``:i&&["locking","unlocking"].includes(String(o))?j``:G} + ${t||i?G:j`

${this._t("opening.no_entities")}

`} +
+
+ + +
+
`}_renderOpeningDialog(){return this._editorRuntimeOrThrow()._renderOpeningDialog()}_gridLevels(){return this._editorRuntimeOrThrow()._gridLevels()}_renderMarkupDefs(e){return this._editorRuntimeOrThrow()._renderMarkupDefs(e)}_renderPhysicalEditorLayer(){return this._editorRuntimeOrThrow()._renderPhysicalEditorLayer()}_renderHiddenWallDiagnosticOverlay(){return this._editorRuntimeOrThrow()._renderHiddenWallDiagnosticOverlay()}_renderPlanSnapOverlay(){return this._editorRuntimeOrThrow()._renderPlanSnapOverlay()}_syncPlanSnapActiveMarker(e){return this._editorRuntimeOrThrow()._syncPlanSnapActiveMarker(e)}_syncPlanSnapConflictMarkers(e){return this._editorRuntimeOrThrow()._syncPlanSnapConflictMarkers(e)}_planSnapPhysicalSegment(e){return this._editorRuntimeOrThrow()._planSnapPhysicalSegment(e)}_drawPreviewJoinPatchD(e,t){return this._editorRuntimeOrThrow()._drawPreviewJoinPatchD(e,t)}_renderMarkupLayer(e){return this._editorRuntimeOrThrow()._renderMarkupLayer(e)}_renderActiveChainInk(){return this._editorRuntimeOrThrow()._renderActiveChainInk()}_renderPartitionDeleteDialog(){return this._editorRuntimeOrThrow()._renderPartitionDeleteDialog()}_renderRoomDeleteDialog(){return this._editorRuntimeOrThrow()._renderRoomDeleteDialog()}_renderPhysicalDialog(){return this._editorRuntimeOrThrow()._renderPhysicalDialog()}_renderMarkupBar(){return this._editorRuntimeOrThrow()._renderMarkupBar()}_renderDevicesBar(){return this._editorRuntimeOrThrow()._renderDevicesBar()}_renderDeviceInbox(){return this._editorRuntimeOrThrow()._renderDeviceInbox()}_cardEntities(e){const t=this._planHass,i=[],n=new Set,r=e=>{if(!e||n.has(e)||!t.states[e])return;const r=t.entities[e];if("config"===r?.entity_category||"diagnostic"===r?.entity_category)return;n.add(e);const o=e.split(".")[0];["light","switch","fan","humidifier","siren","input_boolean"].includes(o)?i.push({eid:e,kind:"toggle"}):["cover","valve","lock","climate","media_player","vacuum","water_heater"].includes(o)?i.push({eid:e,kind:"open"}):["sensor","binary_sensor","number","select"].includes(o)&&i.push({eid:e,kind:"value"})};for(const i of Nd(t,this._devices,null,this._virtualLights))if(i.device.id===e.id)for(const e of[...i.serviceEids,...i.stateEids])r(e);e.primary&&r(e.primary);for(const t of e.entities)r(t);return i.slice(0,12)}_cardToggle(e){const t=e.split(".")[0];"lock"!==t&&"alarm_control_panel"!==t&&this._planEntityAvailable(e)&&this.hass.callService("homeassistant","toggle",{entity_id:e}).catch(e=>this._showToast(this._t("toast.error",{err:this._errText(e)})))}_renderInfoCard(){const e=this._infoCard,t=e.primary?this.hass.states[e.primary]:void 0,i=t?Xi(this.hass,e.primary)?.text??t.state:null,n=Cg(e.marker?.radar)?e.marker.radar:null,r=n?this._radarLive.frames.get(e.marker?.id||e.id):null,o=n?function(e,t){return!0!==e.enabled?"radar.health_disabled":Dg[t||""]||"radar.health_unknown"}(n,r?.health):null,s=(e.controls??e.marker?.controls??[]).filter(Dn).filter(e=>this._planEntityAvailable(e));return j` +
+ ${(()=>{const t=this._cardEntities(e);return t.length?j`
+ ${t.map(({eid:e,kind:t})=>{const i=this.hass.states[e],n=this.hass.entities[e]?.name||i?.attributes?.friendly_name||e,r=i?Xi(this.hass,e)?.text??i.state:"",o="on"===i?.state||["open","unlocked","playing","cleaning"].includes(i?.state);return j`
+ + ${n} + ${"toggle"===t?j``:"open"===t?j``:j`${r}`} +
`})} +
`:G})()} + ${e.model?j`
${this._t("info.model")}${e.model}
`:G} + ${i&&!this._cardEntities(e).length?j`
${this._t("info.state")}${i}
`:G} + ${o?j`
${this._t("radar.health")} + ${this._t(o)}
`:G} + ${Ni(e.link)?j`
${this._t("info.link")} + ${e.link}
`:G} + ${e.description?j`
${e.description}
`:G} + ${e.pdfs&&e.pdfs.length?j`
${this._t("info.manuals")} + ${e.pdfs.map(e=>j` + ${e.name}`)}
`:G} + ${s.length?j`
${this._t("info.controls")} + + ${s.map(e=>{const t=this.hass.states[e],i="on"===t?.state;return j` + + ${t?.attributes?.friendly_name||e}`})} +
`:G} + ${e.model||i||o||e.link||e.description||e.pdfs&&e.pdfs.length||s.length?G:j`
${this._t("info.none")}
`} +
+
+ + ${e.primary?j``:G} + +
+
`}_markerValueBadgeFields(e){return this._editorRuntimeOrThrow()._markerValueBadgeFields(e)}_markerDraft(e){return this._editorRuntimeOrThrow()._markerDraft(e)}_markerPreviewDevice(e){return this._editorRuntimeOrThrow()._markerPreviewDevice(e)}_markerPreviewDevices(e){return this._editorRuntimeOrThrow()._markerPreviewDevices(e)}_toggleIntent(e,t=this._devices){return zu({hass:this._planHass,registryHass:this._fullRegistryHass,devices:t,device:e,virtualLights:this._virtualLights})}_toggleIntentForDialog(e){return this._editorRuntimeOrThrow()._toggleIntentForDialog(e)}_toggleStateText(e,t){const i=this._planHass?.states?.[e]||this.hass?.states?.[e];try{return i&&"function"==typeof this.hass?.formatEntityState?this.hass.formatEntityState(i):t}catch{return t}}_toggleConfirmationStateText(e){const t=String(e.state||"unknown"),i=e.entityId?this._toggleStateText(e.entityId,t):t;if(i.trim().toLocaleLowerCase()!==t.trim().toLocaleLowerCase())return i;const n={on:"confirm.state_on",off:"confirm.state_off",open:"confirm.state_open",closed:"confirm.state_closed",opening:"confirm.state_opening",closing:"confirm.state_closing",unknown:"confirm.state_unknown"}[t];return n?this._t(n):t.replaceAll("_"," ").replaceAll("-"," ")}_toggleConfirmationLines(e){const t={"turn-on":"confirm.state_on","turn-off":"confirm.state_off",open:"confirm.state_open",close:"confirm.state_closed",stop:"confirm.state_stopped"};return function(e,t){if(!Ou(e)||!e.nextEffect||!e.targets.length)return[];const i="group"===e.kind,n=i?e.targets.filter(e=>"on"===e.state).length:0,r=i?0===n?t.groupAllOff():t.groupCurrent(n,e.targets.length):t.state(e.targets[0]);let o;return o="toggle"===e.nextEffect?t.expectedByHa():i&&"turn-on"===e.nextEffect?t.groupAllOn():i&&"turn-off"===e.nextEffect?t.groupAllOff():t.effect(e.nextEffect),[t.current(r),t.expected(o),...e.skippedTargets.length?[t.unavailable(e.skippedTargets.length)]:[]]}(e,{state:e=>this._toggleConfirmationStateText(e),current:e=>this._t("confirm.current_state",{state:e}),expected:e=>this._t("confirm.expected_state",{state:e}),groupCurrent:(e,t)=>this._t("confirm.group_current",{on:e,total:t}),groupAllOn:()=>this._t("confirm.group_all_on"),groupAllOff:()=>this._t("confirm.group_all_off"),unavailable:e=>this._t("confirm.unavailable_targets",{count:e}),effect:e=>this._t(t[e]),expectedByHa:()=>this._t("confirm.expected_by_ha")})}_toggleHintLines(e){return this._editorRuntimeOrThrow()._toggleHintLines(e)}_effectiveStoredTapAction(e,t){return this._editorRuntimeOrThrow()._effectiveStoredTapAction(e,t)}_effectiveMarkerTapAction(e,t=this._markerPreviewDevice(e)){return this._editorRuntimeOrThrow()._effectiveMarkerTapAction(e,t)}_announceToggleDraft(e){return this._editorRuntimeOrThrow()._announceToggleDraft(e)}_valueBadgeForBinding(e,t){return this._editorRuntimeOrThrow()._valueBadgeForBinding(e,t)}_markerSpatialSource(e){return this._editorRuntimeOrThrow()._markerSpatialSource(e)}_markerAutoHasSpatialSource(e){return this._editorRuntimeOrThrow()._markerAutoHasSpatialSource(e)}_setMarkerLightRole(e){return this._editorRuntimeOrThrow()._setMarkerLightRole(e)}_controlRefInfo(e){return this._editorRuntimeOrThrow()._controlRefInfo(e)}_valueBadgeCandidateLabel(e){return this._editorRuntimeOrThrow()._valueBadgeCandidateLabel(e)}_controlCandidates(e){return this._editorRuntimeOrThrow()._controlCandidates(e)}_addControlRef(e,t){return this._editorRuntimeOrThrow()._addControlRef(e,t)}_setMarkerGlowMode(e){return this._editorRuntimeOrThrow()._setMarkerGlowMode(e)}_renderMarkerDialog(){return this._editorRuntimeOrThrow()._renderMarkerDialog()}_renderSpaceDialog(){return this._onboardingRuntime&&this._spaceDialog&&this._spaceDialogUsesOnboardingRuntime(this._spaceDialog.mode)?this._onboardingRuntime._renderSpaceDialog():this._editorRuntimeOrThrow()._renderSpaceDialog()}_renderMergeDialog(){return this._editorRuntimeOrThrow()._renderMergeDialog()}_renderCardPreview(e,t,i){const n=18*e;return j`
+ + ${this._t("preview.room_name")} + + 22.4° · + 45% · + ${this._t("roomcard.light_partial",{on:1,total:3})} + +
`}_renderRoomSource(e){return this._editorRuntimeOrThrow()._renderRoomSource(e)}_renderRoomDialog(){return this._editorRuntimeOrThrow()._renderRoomDialog()}}kv.properties={_tabDrag:{state:!0},_hdrH:{state:!0},_booting:{state:!0},_bootFading:{state:!0},_bootSoft:{state:!0},_continuityEpoch:{state:!0},_editorRuntimeLoadingVisible:{state:!0},_backdropGuard:{state:!0},_tapConfirm:{state:!0},_dangerConfirm:{state:!0},hass:{attribute:!1},panelHost:{type:Boolean,attribute:"panel-host",reflect:!0},narrow:{attribute:!1},_config:{state:!0},_space:{state:!0},_devices:{state:!0},_selId:{state:!0},_toast:{state:!0},_mode:{state:!0},_tool:{state:!0},_wallDialog:{state:!0},_drawWallField:{state:!0},_activeWallChainId:{state:!0},_physicalSel:{state:!0},_physicalDialog:{state:!0},_partitionDeleteDialog:{state:!0},_roomDeleteDialog:{state:!0},_physicalDrag:{state:!0},_physicalRotate:{state:!0},_duplicateColumnId:{state:!0},_opMeasure:{state:!0},_path:{state:!0},_cursorPt:{state:!0},_mergeSel:{state:!0},_openingPreset:{state:!0},_openingDialog:{state:!0},_openingInfo:{state:!0},_mergeDialog:{state:!0},_splitSel:{state:!0},_decorTool:{state:!0},_decorStyle:{state:!0},_decorDraft:{state:!0},_decorSel:{state:!0},_decorEraseConfirm:{state:!0},_decorTextDialog:{state:!0},_decorShapeDialog:{state:!0},_backdropDialog:{state:!0},_furnPalette:{state:!0},_decorImagePalette:{state:!0},_decorAssetCatalog:{state:!0},_decorAssetBusy:{state:!0},_furnCategory:{state:!0},_furnPreviewInput:{state:!0},_bdDrag:{state:!0},_dtBox:{state:!0},_dtDrag:{state:!0},_kioskDialog:{state:!0},_vacFit:{state:!0},_vacAllCamerasFor:{state:!0},_vacCalConfirm:{state:!0},_kioskDots:{state:!0},_areaSel:{state:!0},_nameSel:{state:!0},_roomDialog:{state:!0},_roomEditId:{state:!0},_roomFill:{state:!0},_roomCustomFill:{state:!0},_roomTempMin:{state:!0},_roomTempMax:{state:!0},_roomTempSrc:{state:!0},_roomHumSrc:{state:!0},_roomSrcOpen:{state:!0},_roomSrcFilter:{state:!0},_roomNameScale:{state:!0},_roomLabelScale:{state:!0},_spaceDialog:{state:!0},_infoCard:{state:!0},_deviceInbox:{state:!0},_rulesDialog:{state:!0},_settingsDialog:{state:!0},_pdfDialog:{state:!0},_supportDialog:{state:!0},_alignDialog:{state:!0},_preflightClipboardFallback:{state:!0},_backupExportDialog:{state:!0},_backupImportDialog:{state:!0},_importDialog:{state:!0},_markerDialog:{state:!0}},kv.ZOOM_MAX=8,kv.ZOOM_MIN=1/3,kv.styles=[lp,gg],customElements.get("houseplan-card")||customElements.define("houseplan-card",kv),window.customCards=window.customCards||[],window.customCards.find(e=>"houseplan-card"===e.type)||window.customCards.push({type:"houseplan-card",name:"House Plan Card",description:"Interactive house plan: spaces, rooms and devices with live states and drag layout."}),console.info(`%c HOUSEPLAN-CARD %c v${nv} `,"background:#3ea6ff;color:#04121f;font-weight:700","");export{Vl as $,G as A,Ip as B,x_ as C,le as D,U as E,zg as F,wi as G,jr as H,$i as I,Mi as J,Ut as K,Ci as L,nl as M,Ga as N,So as O,ni as P,Ho as Q,T_ as R,D_ as S,ks as T,oo as U,Yo as V,_i as W,Vo as X,j_ as Y,Ll as Z,al as _,ch as a,br as a$,Wl as a0,As as a1,_s as a2,Ds as a3,ea as a4,Ns as a5,Tc as a6,Cc as a7,si as a8,tl as a9,Jd as aA,Qd as aB,Cg as aC,ti as aD,oi as aE,Pn as aF,Un as aG,_m as aH,Ar as aI,um as aJ,Il as aK,ql as aL,ic as aM,Qa as aN,nc as aO,Xl as aP,ys as aQ,na as aR,ns as aS,ma as aT,Ha as aU,B_ as aV,fa as aW,Fs as aX,Ig as aY,_n as aZ,vr as a_,Qu as aa,ap as ab,Ps as ac,$o as ad,op as ae,Zu as af,es as ag,zs as ah,ep as ai,sa as aj,ca as ak,bo as al,ko as am,to as an,H_ as ao,Zo as ap,il as aq,Ko as ar,Ka as as,Ya as at,en as au,tn as av,Ki as aw,Yi as ax,Ja as ay,hc as az,nh as b,A_ as b$,yr as b0,fr as b1,pn as b2,Oe as b3,$p as b4,cf as b5,Fo as b6,sl as b7,Qt as b8,ei as b9,Er as bA,Br as bB,Lr as bC,Pr as bD,Cr as bE,Dr as bF,Ir as bG,jn as bH,Rr as bI,Tr as bJ,Ql as bK,Nr as bL,ec as bM,Kl as bN,jl as bO,tc as bP,Zl as bQ,Jl as bR,am as bS,ts as bT,Cp as bU,rp as bV,Xf as bW,np as bX,da as bY,Uf as bZ,Zf as b_,Wr as ba,va as bb,xc as bc,L_ as bd,xo as be,Lu as bf,U_ as bg,yi as bh,mi as bi,Fi as bj,Ea as bk,Sa as bl,xa as bm,Jo as bn,Qo as bo,ia as bp,$l as bq,za as br,Fa as bs,Yn as bt,Xn as bu,ki as bv,vs as bw,fs as bx,G_ as by,V_ as bz,j as c,Wf as c$,li as c0,tp as c1,sp as c2,Di as c3,fi as c4,ai as c5,vi as c6,is as c7,zi as c8,Mn as c9,Z_ as cA,W_ as cB,zr as cC,mn as cD,Og as cE,co as cF,wr as cG,Ee as cH,qe as cI,Ne as cJ,Uc as cK,Xc as cL,oh as cM,Nc as cN,Zc as cO,Gc as cP,Vc as cQ,rh as cR,th as cS,zc as cT,Ac as cU,Bn as cV,Pc as cW,qn as cX,ci as cY,Gf as cZ,Fp as c_,Vp as ca,Kp as cb,Sd as cc,Du as cd,Li as ce,Ui as cf,Kn as cg,Ln as ch,Yd as ci,tm as cj,wo as ck,Zd as cl,Kd as cm,un as cn,cn as co,ln as cp,Wa as cq,O_ as cr,an as cs,sn as ct,on as cu,rn as cv,ja as cw,$c as cx,Sc as cy,tv as cz,ra as d,Oa as d$,Rl as d0,Is as d1,cs as d2,hs as d3,Ie as d4,cu as d5,Yp as d6,Xp as d7,ru as d8,Hu as d9,tu as dA,nu as dB,el as dC,zl as dD,Fc as dE,nf as dF,rf as dG,Mp as dH,sf as dI,Sl as dJ,of as dK,af as dL,Ca as dM,Xs as dN,Rp as dO,Ri as dP,b_ as dQ,Mf as dR,Rf as dS,pf as dT,k_ as dU,Ba as dV,qr as dW,Ia as dX,ha as dY,Fr as dZ,Or as d_,Hd as da,Nd as db,zd as dc,Md as dd,Dn as de,xd as df,Xd as dg,Rn as dh,__ as di,Ep as dj,Id as dk,Od as dl,Rd as dm,$u as dn,Bi as dp,Hi as dq,Np as dr,Ni as ds,Mc as dt,Ua as du,Rc as dv,qi as dw,ji as dx,Mo as dy,pi as dz,pe as e,Dl as e0,K_ as e1,Na as e2,dm as e3,kp as e4,up as e5,fp as e6,pp as e7,Jt as e8,xg as e9,Y_ as ea,Xi as eb,Zi as ec,Wt as ed,kv as ee,ih as f,To as g,Ao as h,_e as i,Do as j,qa as k,xp as l,zo as m,ah as n,uh as o,o as p,he as q,dh as r,nn as s,Kt as t,lp as u,Sp as v,W as w,Jp as x,y_ as y,w_ as z}; diff --git a/custom_components/houseplan/frontend/houseplan-assets/houseplan-editor-runtime-Pkk2XGqR.js b/custom_components/houseplan/frontend/houseplan-assets/houseplan-editor-runtime-CCYvnxhV.js similarity index 99% rename from custom_components/houseplan/frontend/houseplan-assets/houseplan-editor-runtime-Pkk2XGqR.js rename to custom_components/houseplan/frontend/houseplan-assets/houseplan-editor-runtime-CCYvnxhV.js index 2e943290..ae76ab08 100644 --- a/custom_components/houseplan/frontend/houseplan-assets/houseplan-editor-runtime-Pkk2XGqR.js +++ b/custom_components/houseplan/frontend/houseplan-assets/houseplan-editor-runtime-CCYvnxhV.js @@ -1,4 +1,4 @@ -globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="241ab786b7cce5c1f837e73704240f138bd3e097bfecdbb0e93046bf4a19d3ef";import{e as t,i as e,E as s,s as i,a as o,n as a,f as n,b as r,l,o as h,r as c,A as d,c as p,D as u,w as _,N as m,d as g,g as f,h as b,j as v,k as y,m as $,p as w,q as k,t as x,u as S,v as M,x as C,y as P,z as D,B as I,C as T,F as R,G as z,H as A,I as F,J as N,K as E,L as H,M as O,O as L,P as B,Q as W,R as j,S as G,T as q,U,V as K,W as V,X as J,Y,Z as X,_ as Z,$ as Q,a0 as tt,a1 as et,a2 as st,a3 as it,a4 as ot,a5 as at,a6 as nt,a7 as rt,a8 as lt,a9 as ht,aa as ct,ab as dt,ac as pt,ad as ut,ae as _t,af as mt,ag as gt,ah as ft,ai as bt,aj as vt,ak as yt,al as $t,am as wt,an as kt,ao as xt,ap as St,aq as Mt,ar as Ct,as as Pt,at as Dt,au as It,av as Tt,aw as Rt,ax as zt,ay as At,az as Ft,aA as Nt,aB as Et,aC as Ht,aD as Ot,aE as Lt,aF as Bt,aG as Wt,aH as jt,aI as Gt,aJ as qt,aK as Ut,aL as Kt,aM as Vt,aN as Jt,aO as Yt,aP as Xt,aQ as Zt,aR as Qt,aS as te,aT as ee,aU as se,aV as ie,aW as oe,aX as ae,aY as ne,aZ as re,a_ as le,a$ as he,b0 as ce,b1 as de,b2 as pe,b3 as ue,b4 as _e,b5 as me,b6 as ge,b7 as fe,b8 as be,b9 as ve,ba as ye,bb as $e,bc as we,bd as ke,be as xe,bf as Se,bg as Me,bh as Ce,bi as Pe,bj as De,bk as Ie,bl as Te,bm as Re,bn as ze,bo as Ae,bp as Fe,bq as Ne,br as Ee,bs as He,bt as Oe,bu as Le,bv as Be,bw as We,bx as je,by as Ge,bz as qe,bA as Ue,bB as Ke,bC as Ve,bD as Je,bE as Ye,bF as Xe,bG as Ze,bH as Qe,bI as ts,bJ as es,bK as ss,bL as is,bM as os,bN as as,bO as ns,bP as rs,bQ as ls,bR as hs,bS as cs,bT as ds,bU as ps,bV as us,bW as _s,bX as ms,bY as gs,bZ as fs,b_ as bs,b$ as vs,c0 as ys,c1 as $s,c2 as ws,c3 as ks,c4 as xs,c5 as Ss,c6 as Ms,c7 as Cs,c8 as Ps,c9 as Ds,ca as Is,cb as Ts,cc as Rs,cd as zs,ce as As,cf as Fs,cg as Ns,ch as Es,ci as Hs,cj as Os,ck as Ls,cl as Bs,cm as Ws,cn as js,co as Gs,cp as qs,cq as Us,cr as Ks,cs as Vs,ct as Js,cu as Ys,cv as Xs,cw as Zs,cx as Qs,cy as ti,cz as ei,cA as si,cB as ii,cC as oi,cD as ai,cE as ni,cF as ri,cG as li,cH as hi,cI as ci,cJ as di,cK as pi,cL as ui,cM as _i,cN as mi,cO as gi,cP as fi,cQ as bi,cR as vi,cS as yi,cT as $i,cU as wi,cV as ki,cW as xi,cX as Si,cY as Mi,cZ as Ci,c_ as Pi,c$ as Di,d0 as Ii,d1 as Ti,d2 as Ri,d3 as zi,d4 as Ai,d5 as Fi,d6 as Ni,d7 as Ei,d8 as Hi,d9 as Oi,da as Li,db as Bi,dc as Wi,dd as ji,de as Gi,df as qi,dg as Ui,dh as Ki,di as Vi,dj as Ji,dk as Yi,dl as Xi,dm as Zi,dn as Qi,dp as to,dq as eo,dr as so,ds as io,dt as oo,du as ao,dv as no,dw as ro,dx as lo,dy as ho,dz as co,dA as po,dB as uo,dC as _o,dD as mo}from"./houseplan-card-BvxqYw8A.js";import{F as go,f as fo,p as bo,c as vo,e as yo,r as $o,a as wo,s as ko}from"./backdrop-pick-ClLjW_UW.js";import{t as xo,h as So,m as Mo,T as Co}from"./zigbee-topology-B8St6NV9.js";import{GENERATED_FURNITURE_ART as Po,FURNITURE_ART_FINGERPRINT as Do}from"./furniture-plan-art.generated-7nJsC48X.js";const Io={},To=t(class extends e{constructor(){super(...arguments),this.ot=Io}render(t,e){return e()}update(t,[e,i]){if(Array.isArray(e)){if(Array.isArray(this.ot)&&this.ot.length===e.length&&e.every((t,e)=>t===this.ot[e]))return s}else if(this.ot===e)return s;return this.ot=Array.isArray(e)?Array.from(e):e,this.render(e,i)}});var Ro={"gs.hint":"Fill colors apply to every space; each color has its own opacity. Which fill mode a space uses is set in that space's dialog.","gs.show_room_tooltip":"Show the room information window on hover","support.about_group":"About the card","support.guide_group":"Documentation","support.guide":"User guide","support.form_group":"Send a report or suggestion","support.contact":"Contact details (email/tg/WhatsApp), optional.","support.message":"Message","support.attach":"Attach anonymized information from your plan","support.attach_hint":"Includes only allowed plan geometry, settings and bounded runtime facts. Excludes names, Home Assistant IDs, live states, URLs, files, and your message/contact.","support.geometry_warning":"The package contains no names or Home Assistant IDs, but it does contain the exact geometry and dimensions of your home.","support.close_busy_title":"Stop the current operation?","support.close_busy_body":"House Plan is preparing or sending the report. Closing now stops waiting for the result.","support.building":"Preparing anonymized data…","support.preview_summary":"Package v{version} · {spaces} spaces · {size} KiB","support.prepared":"Snapshot prepared {n} min ago","support.show_data":"Show data","support.download":"Download JSON","support.refresh":"Refresh snapshot","support.privacy":"When you send, your message, optional contact and, if selected, exact geometry leave your Home Assistant through the House Plan project relay and are visible to maintainers. The project node keeps the report for up to 30 days. Network infrastructure sees your HA server address, but House Plan does not retain it raw; rate-limit and idempotency metadata is kept for up to 24 hours.","support.error_title":"The report was not sent","support.manual_recovery":"You can keep the message and attachment and continue manually:","support.copy_message":"Copy message","support.success":"Report sent: {id}. Save this number when contacting support.","support.copy_id":"Copy ID","support.sending":"Sending…","support.retry":"Retry","support.send":"Send","support.update_required":"Update the House Plan card and integration to compatible versions to send reports.","support.message_copied":"Message copied","support.id_copied":"Report ID copied","support.copy_failed":"Could not access the clipboard. Select and copy the text manually.","support.validation.message_required":"Enter a message.","support.validation.message_too_long":"The message must contain no more than 10,000 characters.","support.validation.contact_too_long":"Contact details must contain no more than 320 characters.","support.validation.preview_missing":"Wait for the attachment preview or turn the attachment off.","support.validation.preview_expired":"The attachment preview expired. Refresh the snapshot.","support.error.support_invalid_message":"Check the message and try again.","support.error.support_preview_expired":"The attachment preview expired or is no longer available. Refresh the snapshot.","support.error.support_package_too_large":"The anonymized package exceeds the 8 MiB limit.","support.error.support_rate_limited":"Too many reports or previews were requested. Try again later.","support.error.support_unavailable":"The private support service is temporarily unavailable. Your draft remains here.","support.error.support_rejected":"The report did not pass the support service validation.","support.error.unauthorized":"You do not have permission to send this report.","vac.routes_section":"Maps and floors","vac.routes_current_map":"Current map","vac.routes_no_map":"no telemetry","vac.routes_status":"Routing","vac.routes_state_ready":"map assigned and calibrated","vac.routes_state_needs_calibration":"map assigned, calibration needed","vac.routes_state_unmapped":"current map is not assigned to a floor","vac.routes_state_ambiguous":"two maps are indistinguishable — no floor is chosen","vac.routes_state_missing_space":"the map's space was deleted","vac.routes_state_none":"no map data","vac.routes_empty":"No map is assigned to a floor yet.","vac.route_map_default":"no map id","vac.route_active":"Active","vac.route_space":"Space","vac.route_space_none":"not selected","vac.route_status_ready":"ready","vac.route_status_needs_calibration":"needs calibration","vac.route_status_ambiguous":"ambiguous","vac.route_status_missing_space":"space deleted","vac.route_missing_space_group":"Deleted space","vac.route_add_current":"Add current map","vac.route_delete":"Remove map","vac.route_delete_title":"Remove the map from its floor?","vac.route_delete_body":"Calibration and saved paths for this map will be removed. Continue?","vac.route_delete_confirm":"Remove","vac.route_space_title":"Move the map to another space?","vac.route_space_body":"Calibration and saved paths for this map will be removed. Continue?","vac.route_space_confirm":"Move","vac.route_missing_space_hint":"One of the maps points at a deleted space: pick a new one or remove the map. Until then the robot is not drawn for that map.","vac.route_default_hint":"The source reports no stable map id. Several floors cannot be told apart without another source or the robot's own selected map.","vac.route_target_hint":"The dock stays in the “{space}” space regardless of the current map.","vac.route_add_source":"Add a map source","vac.route_add_source_hint":"For integrations that give each map its own camera. The “All cameras” section above widens this list.","vac.route_source_no_map":"no map reported"};const zo={en:Ro,ru:{"gs.hint":"Цвета заливок действуют на все пространства; у каждого цвета своя прозрачность. Какой режим заливки использует пространство — задаётся в его диалоге.","gs.show_room_tooltip":"Показывать окно с информацией при наведении на комнату","support.about_group":"О карточке","support.guide_group":"Документация","support.guide":"Руководство пользователя","support.form_group":"Отправить репорт или предложение","support.contact":"Контакт для связи (email/tg/WhatsApp), необязательно.","support.message":"Сообщение","support.attach":"Прикрепить обезличенную информацию из вашего плана","support.attach_hint":"В пакет входят только разрешённые геометрия, настройки и ограниченные сведения о среде. Не входят имена, HA id, текущие состояния, URL, файлы, сообщение и контакт.","support.geometry_warning":"Пакет не содержит имён и HA id, но содержит точную геометрию и размеры дома.","support.close_busy_title":"Прервать текущую операцию?","support.close_busy_body":"House Plan подготавливает или отправляет репорт. При закрытии ожидание результата прекратится.","support.building":"Подготавливаем обезличенные данные…","support.preview_summary":"Пакет v{version} · пространств: {spaces} · {size} КиБ","support.prepared":"Снимок подготовлен {n} мин назад","support.show_data":"Показать данные","support.download":"Скачать JSON","support.refresh":"Обновить снимок","support.privacy":"При отправке сообщение, необязательный контакт и, если выбран пакет, точная геометрия покидают ваш Home Assistant через relay проекта House Plan и доступны мейнтейнерам. Узел проекта хранит репорт до 30 дней. Сетевая инфраструктура видит адрес сервера HA, но House Plan не сохраняет его в исходном виде; метаданные лимитов и идемпотентности хранятся до 24 часов.","support.error_title":"Репорт не отправлен","support.manual_recovery":"Сообщение и вложение можно сохранить и продолжить вручную:","support.copy_message":"Копировать сообщение","support.success":"Репорт отправлен: {id}. Сохраните номер для связи с поддержкой.","support.copy_id":"Копировать ID","support.sending":"Отправляем…","support.retry":"Повторить","support.send":"Отправить","support.update_required":"Обновите карточку и интеграцию House Plan до совместимых версий, чтобы отправлять репорты.","support.message_copied":"Сообщение скопировано","support.id_copied":"ID репорта скопирован","support.copy_failed":"Не удалось получить доступ к буферу обмена. Выделите и скопируйте текст вручную.","support.validation.message_required":"Введите сообщение.","support.validation.message_too_long":"Сообщение должно содержать не более 10 000 символов.","support.validation.contact_too_long":"Контакт должен содержать не более 320 символов.","support.validation.preview_missing":"Дождитесь предпросмотра вложения или отключите его.","support.validation.preview_expired":"Предпросмотр вложения истёк. Обновите снимок.","support.error.support_invalid_message":"Проверьте сообщение и повторите попытку.","support.error.support_preview_expired":"Предпросмотр вложения истёк или больше недоступен. Обновите снимок.","support.error.support_package_too_large":"Обезличенный пакет превышает лимит 8 МиБ.","support.error.support_rate_limited":"Запрошено слишком много репортов или предпросмотров. Повторите позже.","support.error.support_unavailable":"Закрытая служба поддержки временно недоступна. Черновик сохранён в этом окне.","support.error.support_rejected":"Репорт не прошёл проверку службы поддержки.","support.error.unauthorized":"У вас нет прав на отправку этого репорта.","vac.routes_section":"Карты и этажи","vac.routes_current_map":"Текущая карта","vac.routes_no_map":"источник молчит","vac.routes_status":"Маршрутизация","vac.routes_state_ready":"карта сопоставлена и откалибрована","vac.routes_state_needs_calibration":"карта сопоставлена, нужна калибровка","vac.routes_state_unmapped":"текущая карта не сопоставлена этажу","vac.routes_state_ambiguous":"две карты неразличимы — этаж не выбирается","vac.routes_state_missing_space":"пространство карты удалено","vac.routes_state_none":"нет данных о карте","vac.routes_empty":"Ни одна карта ещё не сопоставлена этажу.","vac.route_map_default":"без идентификатора","vac.route_active":"Текущая","vac.route_space":"Пространство","vac.route_space_none":"не выбрано","vac.route_status_ready":"готова","vac.route_status_needs_calibration":"нужна калибровка","vac.route_status_ambiguous":"неоднозначна","vac.route_status_missing_space":"пространство удалено","vac.route_missing_space_group":"Пространство удалено","vac.route_add_current":"Добавить текущую карту","vac.route_delete":"Удалить карту","vac.route_delete_title":"Удалить карту с этажа?","vac.route_delete_body":"Калибровка и сохранённые пути этой карты будут удалены. Продолжить?","vac.route_delete_confirm":"Удалить","vac.route_space_title":"Перенести карту в другое пространство?","vac.route_space_body":"Калибровка и сохранённые пути этой карты будут удалены. Продолжить?","vac.route_space_confirm":"Перенести","vac.route_missing_space_hint":"Одна из карт ссылается на удалённое пространство: выберите новое или удалите карту. Пока ссылка не исправлена, робот на этой карте не рисуется.","vac.route_default_hint":"Источник не сообщает стабильный идентификатор карты. Несколько этажей нельзя различить без другого источника или собственной карты робота.","vac.route_target_hint":"Док остаётся в пространстве «{space}» независимо от текущей карты.","vac.route_add_source":"Добавить источник карты","vac.route_add_source_hint":"Для интеграций, где у каждой карты своя камера. Список расширяется разделом «Все камеры» выше.","vac.route_source_no_map":"карта не читается"},de:{"gs.hint":"Füllfarben gelten für jeden Bereich; jede Farbe hat ihre eigene Deckkraft. Der Füllmodus wird in den Einstellungen des jeweiligen Bereichs festgelegt.","gs.show_room_tooltip":"Rauminformationen beim Darüberfahren anzeigen","support.about_group":"Über die Karte","support.guide_group":"Dokumentation","support.guide":"Benutzerhandbuch","support.form_group":"Bericht oder Vorschlag senden","support.contact":"Kontakt (E-Mail/tg/WhatsApp), optional.","support.message":"Nachricht","support.attach":"Anonymisierte Informationen aus dem Plan anhängen","support.attach_hint":"Enthält nur erlaubte Plangeometrie, Einstellungen und begrenzte Laufzeitdaten. Namen, Home-Assistant-IDs, Live-Zustände, URLs, Dateien, Nachricht und Kontakt werden ausgeschlossen.","support.geometry_warning":"Das Paket enthält keine Namen oder Home-Assistant-IDs, aber die exakte Geometrie und die Maße Ihres Hauses.","support.close_busy_title":"Aktuellen Vorgang abbrechen?","support.close_busy_body":"House Plan bereitet den Bericht vor oder sendet ihn. Beim Schließen wird nicht weiter auf das Ergebnis gewartet.","support.building":"Anonymisierte Daten werden vorbereitet…","support.preview_summary":"Paket v{version} · {spaces} Bereiche · {size} KiB","support.prepared":"Schnappschuss vor {n} Min. erstellt","support.show_data":"Daten anzeigen","support.download":"JSON herunterladen","support.refresh":"Schnappschuss aktualisieren","support.privacy":"Beim Senden verlassen Ihre Nachricht, der optionale Kontakt und, falls ausgewählt, die exakte Geometrie Ihren Home Assistant über das House-Plan-Projektrelay und sind für die Maintainer sichtbar. Der Projektserver speichert den Bericht bis zu 30 Tage. Die Netzwerkinfrastruktur sieht die Adresse Ihres HA-Servers, House Plan speichert sie jedoch nicht im Rohformat; Limit- und Idempotenzdaten bleiben bis zu 24 Stunden erhalten.","support.error_title":"Der Bericht wurde nicht gesendet","support.manual_recovery":"Nachricht und Anhang können gespeichert und manuell weitergegeben werden:","support.copy_message":"Nachricht kopieren","support.success":"Bericht gesendet: {id}. Bewahren Sie diese Nummer für den Support auf.","support.copy_id":"ID kopieren","support.sending":"Wird gesendet…","support.retry":"Erneut versuchen","support.send":"Senden","support.update_required":"Aktualisieren Sie House-Plan-Karte und Integration auf kompatible Versionen, um Berichte zu senden.","support.message_copied":"Nachricht kopiert","support.id_copied":"Berichts-ID kopiert","support.copy_failed":"Kein Zugriff auf die Zwischenablage. Markieren und kopieren Sie den Text manuell.","support.validation.message_required":"Geben Sie eine Nachricht ein.","support.validation.message_too_long":"Die Nachricht darf höchstens 10.000 Zeichen enthalten.","support.validation.contact_too_long":"Der Kontakt darf höchstens 320 Zeichen enthalten.","support.validation.preview_missing":"Warten Sie auf die Vorschau oder deaktivieren Sie den Anhang.","support.validation.preview_expired":"Die Anhangsvorschau ist abgelaufen. Aktualisieren Sie den Schnappschuss.","support.error.support_invalid_message":"Prüfen Sie die Nachricht und versuchen Sie es erneut.","support.error.support_preview_expired":"Die Anhangsvorschau ist abgelaufen oder nicht mehr verfügbar. Aktualisieren Sie den Schnappschuss.","support.error.support_package_too_large":"Das anonymisierte Paket überschreitet das Limit von 8 MiB.","support.error.support_rate_limited":"Zu viele Berichte oder Vorschauen wurden angefordert. Versuchen Sie es später erneut.","support.error.support_unavailable":"Der private Supportdienst ist vorübergehend nicht verfügbar. Der Entwurf bleibt in diesem Fenster erhalten.","support.error.support_rejected":"Der Bericht hat die Prüfung des Supportdienstes nicht bestanden.","support.error.unauthorized":"Sie dürfen diesen Bericht nicht senden.","vac.routes_section":"Karten und Etagen","vac.routes_current_map":"Aktuelle Karte","vac.routes_no_map":"keine Telemetrie","vac.routes_status":"Zuordnung","vac.routes_state_ready":"Karte zugeordnet und kalibriert","vac.routes_state_needs_calibration":"Karte zugeordnet, Kalibrierung nötig","vac.routes_state_unmapped":"aktuelle Karte keiner Etage zugeordnet","vac.routes_state_ambiguous":"zwei Karten nicht unterscheidbar — keine Etage gewählt","vac.routes_state_missing_space":"der Raum der Karte wurde gelöscht","vac.routes_state_none":"keine Kartendaten","vac.routes_empty":"Noch keine Karte einer Etage zugeordnet.","vac.route_map_default":"ohne Karten-ID","vac.route_active":"Aktiv","vac.route_space":"Raum","vac.route_space_none":"nicht gewählt","vac.route_status_ready":"bereit","vac.route_status_needs_calibration":"Kalibrierung nötig","vac.route_status_ambiguous":"mehrdeutig","vac.route_status_missing_space":"Raum gelöscht","vac.route_missing_space_group":"Gelöschter Bereich","vac.route_add_current":"Aktuelle Karte hinzufügen","vac.route_delete":"Karte entfernen","vac.route_delete_title":"Karte von der Etage entfernen?","vac.route_delete_body":"Kalibrierung und gespeicherte Pfade dieser Karte werden entfernt. Fortfahren?","vac.route_delete_confirm":"Entfernen","vac.route_space_title":"Karte in einen anderen Raum verschieben?","vac.route_space_body":"Kalibrierung und gespeicherte Pfade dieser Karte werden entfernt. Fortfahren?","vac.route_space_confirm":"Verschieben","vac.route_missing_space_hint":"Eine Karte verweist auf einen gelöschten Raum: neuen wählen oder Karte entfernen. Bis dahin wird der Roboter für diese Karte nicht gezeichnet.","vac.route_default_hint":"Die Quelle meldet keine stabile Karten-ID. Mehrere Etagen lassen sich ohne andere Quelle oder die vom Roboter gewählte Karte nicht unterscheiden.","vac.route_target_hint":"Die Station bleibt unabhängig von der aktuellen Karte im Raum „{space}“.","vac.route_add_source":"Kartenquelle hinzufügen","vac.route_add_source_hint":"Für Integrationen, die jeder Karte eine eigene Kamera geben. Der Abschnitt „Alle Kameras“ oben erweitert diese Liste.","vac.route_source_no_map":"keine Karte gemeldet"},fr:{"gs.hint":"Les couleurs de remplissage s’appliquent à tous les espaces ; chaque couleur possède sa propre opacité. Le mode de remplissage utilisé par un espace se règle dans la boîte de dialogue de cet espace.","gs.show_room_tooltip":"Afficher les informations de la pièce au survol","support.about_group":"À propos de la carte","support.guide_group":"Documentation d’aide","support.guide":"Guide utilisateur","support.form_group":"Envoyer un rapport ou une suggestion","support.contact":"Contact (e-mail/tg/WhatsApp), facultatif.","support.message":"Votre message","support.attach":"Joindre des informations anonymisées de votre plan","support.attach_hint":"Inclut uniquement la géométrie, les réglages autorisés et des données d’exécution limitées. Exclut les noms, identifiants Home Assistant, états en direct, URL, fichiers, message et contact.","support.geometry_warning":"Le paquet ne contient ni noms ni identifiants Home Assistant, mais il contient la géométrie et les dimensions exactes de votre logement.","support.close_busy_title":"Interrompre l’opération en cours ?","support.close_busy_body":"House Plan prépare ou envoie le rapport. Fermer maintenant arrête l’attente du résultat.","support.building":"Préparation des données anonymisées…","support.preview_summary":"Paquet v{version} · {spaces} espaces · {size} Kio","support.prepared":"Instantané préparé il y a {n} min","support.show_data":"Afficher les données","support.download":"Télécharger le JSON","support.refresh":"Actualiser l’instantané","support.privacy":"Lors de l’envoi, votre message, le contact facultatif et, si elle est sélectionnée, la géométrie exacte quittent votre Home Assistant via le relais du projet House Plan et sont visibles par les mainteneurs. Le serveur du projet conserve le rapport jusqu’à 30 jours. L’infrastructure réseau voit l’adresse de votre serveur HA, mais House Plan ne la conserve pas en clair ; les métadonnées de limitation et d’idempotence sont gardées jusqu’à 24 heures.","support.error_title":"Le rapport n’a pas été envoyé","support.manual_recovery":"Vous pouvez conserver le message et la pièce jointe puis continuer manuellement :","support.copy_message":"Copier le message","support.success":"Rapport envoyé : {id}. Conservez ce numéro pour contacter l’assistance.","support.copy_id":"Copier l’ID","support.sending":"Envoi…","support.retry":"Réessayer","support.send":"Envoyer","support.update_required":"Mettez à jour la carte et l’intégration House Plan vers des versions compatibles pour envoyer des rapports.","support.message_copied":"Message copié","support.id_copied":"ID du rapport copié","support.copy_failed":"Impossible d’accéder au presse-papiers. Sélectionnez et copiez le texte manuellement.","support.validation.message_required":"Saisissez un message.","support.validation.message_too_long":"Le message ne doit pas dépasser 10 000 caractères.","support.validation.contact_too_long":"Le contact ne doit pas dépasser 320 caractères.","support.validation.preview_missing":"Attendez l’aperçu de la pièce jointe ou désactivez-la.","support.validation.preview_expired":"L’aperçu de la pièce jointe a expiré. Actualisez l’instantané.","support.error.support_invalid_message":"Vérifiez le message et réessayez.","support.error.support_preview_expired":"L’aperçu de la pièce jointe a expiré ou n’est plus disponible. Actualisez l’instantané.","support.error.support_package_too_large":"Le paquet anonymisé dépasse la limite de 8 Mio.","support.error.support_rate_limited":"Trop de rapports ou d’aperçus ont été demandés. Réessayez plus tard.","support.error.support_unavailable":"Le service d’assistance privé est temporairement indisponible. Le brouillon reste dans cette fenêtre.","support.error.support_rejected":"Le rapport n’a pas passé la validation du service d’assistance.","support.error.unauthorized":"Vous n’êtes pas autorisé à envoyer ce rapport.","vac.routes_section":"Cartes et étages","vac.routes_current_map":"Carte actuelle","vac.routes_no_map":"aucune télémétrie","vac.routes_status":"Routage","vac.routes_state_ready":"carte assignée et calibrée","vac.routes_state_needs_calibration":"carte assignée, calibrage requis","vac.routes_state_unmapped":"carte actuelle non assignée à un étage","vac.routes_state_ambiguous":"deux cartes indiscernables — aucun étage choisi","vac.routes_state_missing_space":"l'espace de la carte a été supprimé","vac.routes_state_none":"aucune donnée de carte","vac.routes_empty":"Aucune carte n'est encore assignée à un étage.","vac.route_map_default":"sans identifiant","vac.route_active":"Active","vac.route_space":"Espace","vac.route_space_none":"non sélectionné","vac.route_status_ready":"prête","vac.route_status_needs_calibration":"calibrage requis","vac.route_status_ambiguous":"ambiguë","vac.route_status_missing_space":"espace supprimé","vac.route_missing_space_group":"Espace supprimé","vac.route_add_current":"Ajouter la carte actuelle","vac.route_delete":"Supprimer la carte","vac.route_delete_title":"Retirer la carte de son étage ?","vac.route_delete_body":"Le calibrage et les trajets enregistrés de cette carte seront supprimés. Continuer ?","vac.route_delete_confirm":"Supprimer","vac.route_space_title":"Déplacer la carte vers un autre espace ?","vac.route_space_body":"Le calibrage et les trajets enregistrés de cette carte seront supprimés. Continuer ?","vac.route_space_confirm":"Déplacer","vac.route_missing_space_hint":"Une carte pointe vers un espace supprimé : choisissez-en un autre ou supprimez la carte. D'ici là, le robot n'est pas dessiné pour cette carte.","vac.route_default_hint":"La source ne fournit pas d'identifiant de carte stable. Plusieurs étages ne peuvent pas être distingués sans une autre source ou la carte sélectionnée du robot.","vac.route_target_hint":"La station reste dans l'espace « {space} » quelle que soit la carte actuelle.","vac.route_add_source":"Ajouter une source de carte","vac.route_add_source_hint":"Pour les intégrations qui donnent à chaque carte sa propre caméra. La section « Toutes les caméras » ci-dessus élargit cette liste.","vac.route_source_no_map":"aucune carte signalée"}};function Ao(t,e,s){return i(zo[t]?.[e]??Ro[e]??e,s)}function Fo(t,e,s,i,o){return{markerId:t,source:i,mapId:o,space:e.length?"":s}}function No(t,e,s){return{...t,space:s.has(e)?e:""}}function Eo(t,e=Math.random){const s=new Set(t);for(let t=0;t<64;t+=1){const t="vr_"+Math.floor(16777215*e()).toString(36).padStart(5,"0");if(!s.has(t))return t}return"vr_"+Date.now().toString(36)}function Ho(t,e,s){return t.map(t=>t.id===e?{...t,calibration:s}:t)}const Oo=new WeakMap,Lo=(t,e)=>{const s=(t._serverCfg?.spaces||[]).find(t=>t?.id===e);return String(s?.name||s?.id||e)};function Bo(t,e,s){const i=t.host,n=l(i.hass,i._config?.language),r=(t,e)=>Ao(n,t,e),u=e.marker?.vacuum||{},_=Array.isArray(u.map_routes),m=i._vacSource(e)||"",g=o(e.id,u,e.space,m),f=(i._serverCfg?.spaces||[]).filter(t=>"string"==typeof t?.id&&!!t.id).map(t=>({id:t.id,name:String(t.name||t.id)})),b=new Set(f.map(t=>t.id)),v=h(g,[m],t=>i._vacObservedMapId(e,t)),y=c({routes:g,observed:v,spaceIds:b}),$="ready"===y.kind||"needs_calibration"===y.kind||"missing_space"===y.kind?y.route.id:"",w=m?v[m]:void 0,k=async s=>{let o=_?u.map_routes??null:null;if(!o&&(o=function(t,e,s,i){if(!s)return null;const o=t?.calibration;if(!o||"object"!=typeof o)return null;const n=new Set,r=[];for(const t of Object.keys(o)){const l=a(o[t]);if(!l)continue;const h=i(n);n.add(h),r.push({id:h,source:s,map_id:t,space:e,calibration:l})}return r.length?r:null}(u,e.space,m,t=>Eo(t))??[],!m&&Object.keys(u.calibration||{}).length))return!1;const n=s(o);return!!n&&(async s=>{const o=i._serverCfg;if(!o)return!1;const a=JSON.parse(JSON.stringify(o));a.markers=a.markers||[];let n=a.markers.find(t=>t.id===e.id);if(!n){if("device"!==e.bindingKind&&"entity"!==e.bindingKind||!e.bindingRef)return!1;n={id:e.id,binding:`${e.bindingKind}:${e.bindingRef}`,space:e.space||null,area:e.area||null,hidden:!!e.hidden},a.markers.push(n)}n.vacuum={...n.vacuum||{},map_routes:s},delete n.vacuum.calibration;const r=i._adoption.beginOptimistic(o,a);i._adoption.stageLocalConfig(a),i._regSignature="",i._maybeRebuildDevices(),i.requestUpdate(),i._saveConfigDebounced.pending()&&i._saveConfigDebounced.cancel();try{return await t._saveConfigNow(),!0}catch(t){return i._rollbackOptimistic(r),i._regSignature="",i._maybeRebuildDevices(),i.requestUpdate(),i._showToast(i._t("toast.cfg_save_failed",{err:i._errText(t)})),!1}})(n)},x=s.candidates.filter(t=>t.entityId!==m&&!g.some(e=>e.source===t.entityId)),S=async(t,e)=>{if(!e||e===t.space)return;await i._confirmDanger({key:"vacuum_route_space",kind:"warning",title:r("vac.route_space_title"),message:r("vac.route_space_body"),objectName:t.map_id||r("vac.route_map_default"),confirmLabel:r("vac.route_space_confirm"),cancelLabel:i._t("btn.cancel")})&&await k(s=>function(t,e,s,i){return t.map(t=>t.id===e?{...t,id:i,space:s,calibration:null}:t)}(s,t.id,e,Eo(new Set(g.map(t=>t.id)))))},M=new Map(f.map((t,e)=>[t.id,e])),C=(t,e)=>t.map_id.localeCompare(e.map_id)||t.source.localeCompare(e.source)||t.id.localeCompare(e.id),P=g.filter(t=>b.has(t.space)).sort((t,e)=>(M.get(t.space)??0)-(M.get(e.space)??0)||C(t,e)),D=g.filter(t=>!b.has(t.space)).sort(C),I=[...P,...D],T=!!m&&void 0!==w&&!g.some(t=>t.source===m&&t.map_id===w);let R=Oo.get(t);const z=R?.source||"",A=R?.mapId||"",F=!!R&&g.some(t=>t.source===z&&t.map_id===A);R&&(R.markerId!==e.id||i._vacObservedMapId(e,R.source)!==R.mapId||F&&!R.saving)&&(Oo.delete(t),R=void 0),R?.space&&!b.has(R.space)&&(R=No(R,"",b),Oo.set(t,R));const N=s=>p` +globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="3f783ed7cf5daff202a910aa89044f88f605a65af7f46794277dddf04333e502";import{e as t,i as e,E as s,s as i,a as o,n as a,f as n,b as r,l,o as h,r as c,A as d,c as p,D as u,w as _,N as m,d as g,g as f,h as b,j as v,k as y,m as $,p as w,q as k,t as x,u as S,v as M,x as C,y as P,z as D,B as I,C as T,F as R,G as z,H as A,I as F,J as N,K as E,L as H,M as O,O as L,P as B,Q as W,R as j,S as G,T as q,U,V as K,W as V,X as J,Y,Z as X,_ as Z,$ as Q,a0 as tt,a1 as et,a2 as st,a3 as it,a4 as ot,a5 as at,a6 as nt,a7 as rt,a8 as lt,a9 as ht,aa as ct,ab as dt,ac as pt,ad as ut,ae as _t,af as mt,ag as gt,ah as ft,ai as bt,aj as vt,ak as yt,al as $t,am as wt,an as kt,ao as xt,ap as St,aq as Mt,ar as Ct,as as Pt,at as Dt,au as It,av as Tt,aw as Rt,ax as zt,ay as At,az as Ft,aA as Nt,aB as Et,aC as Ht,aD as Ot,aE as Lt,aF as Bt,aG as Wt,aH as jt,aI as Gt,aJ as qt,aK as Ut,aL as Kt,aM as Vt,aN as Jt,aO as Yt,aP as Xt,aQ as Zt,aR as Qt,aS as te,aT as ee,aU as se,aV as ie,aW as oe,aX as ae,aY as ne,aZ as re,a_ as le,a$ as he,b0 as ce,b1 as de,b2 as pe,b3 as ue,b4 as _e,b5 as me,b6 as ge,b7 as fe,b8 as be,b9 as ve,ba as ye,bb as $e,bc as we,bd as ke,be as xe,bf as Se,bg as Me,bh as Ce,bi as Pe,bj as De,bk as Ie,bl as Te,bm as Re,bn as ze,bo as Ae,bp as Fe,bq as Ne,br as Ee,bs as He,bt as Oe,bu as Le,bv as Be,bw as We,bx as je,by as Ge,bz as qe,bA as Ue,bB as Ke,bC as Ve,bD as Je,bE as Ye,bF as Xe,bG as Ze,bH as Qe,bI as ts,bJ as es,bK as ss,bL as is,bM as os,bN as as,bO as ns,bP as rs,bQ as ls,bR as hs,bS as cs,bT as ds,bU as ps,bV as us,bW as _s,bX as ms,bY as gs,bZ as fs,b_ as bs,b$ as vs,c0 as ys,c1 as $s,c2 as ws,c3 as ks,c4 as xs,c5 as Ss,c6 as Ms,c7 as Cs,c8 as Ps,c9 as Ds,ca as Is,cb as Ts,cc as Rs,cd as zs,ce as As,cf as Fs,cg as Ns,ch as Es,ci as Hs,cj as Os,ck as Ls,cl as Bs,cm as Ws,cn as js,co as Gs,cp as qs,cq as Us,cr as Ks,cs as Vs,ct as Js,cu as Ys,cv as Xs,cw as Zs,cx as Qs,cy as ti,cz as ei,cA as si,cB as ii,cC as oi,cD as ai,cE as ni,cF as ri,cG as li,cH as hi,cI as ci,cJ as di,cK as pi,cL as ui,cM as _i,cN as mi,cO as gi,cP as fi,cQ as bi,cR as vi,cS as yi,cT as $i,cU as wi,cV as ki,cW as xi,cX as Si,cY as Mi,cZ as Ci,c_ as Pi,c$ as Di,d0 as Ii,d1 as Ti,d2 as Ri,d3 as zi,d4 as Ai,d5 as Fi,d6 as Ni,d7 as Ei,d8 as Hi,d9 as Oi,da as Li,db as Bi,dc as Wi,dd as ji,de as Gi,df as qi,dg as Ui,dh as Ki,di as Vi,dj as Ji,dk as Yi,dl as Xi,dm as Zi,dn as Qi,dp as to,dq as eo,dr as so,ds as io,dt as oo,du as ao,dv as no,dw as ro,dx as lo,dy as ho,dz as co,dA as po,dB as uo,dC as _o,dD as mo}from"./houseplan-card-Cythr3Rg.js";import{F as go,f as fo,p as bo,c as vo,e as yo,r as $o,a as wo,s as ko}from"./backdrop-pick-Bcqm2p5p.js";import{t as xo,h as So,m as Mo,T as Co}from"./zigbee-topology-CWUjtXoY.js";import{GENERATED_FURNITURE_ART as Po,FURNITURE_ART_FINGERPRINT as Do}from"./furniture-plan-art.generated-C_Z1hwSa.js";const Io={},To=t(class extends e{constructor(){super(...arguments),this.ot=Io}render(t,e){return e()}update(t,[e,i]){if(Array.isArray(e)){if(Array.isArray(this.ot)&&this.ot.length===e.length&&e.every((t,e)=>t===this.ot[e]))return s}else if(this.ot===e)return s;return this.ot=Array.isArray(e)?Array.from(e):e,this.render(e,i)}});var Ro={"gs.hint":"Fill colors apply to every space; each color has its own opacity. Which fill mode a space uses is set in that space's dialog.","gs.show_room_tooltip":"Show the room information window on hover","support.about_group":"About the card","support.guide_group":"Documentation","support.guide":"User guide","support.form_group":"Send a report or suggestion","support.contact":"Contact details (email/tg/WhatsApp), optional.","support.message":"Message","support.attach":"Attach anonymized information from your plan","support.attach_hint":"Includes only allowed plan geometry, settings and bounded runtime facts. Excludes names, Home Assistant IDs, live states, URLs, files, and your message/contact.","support.geometry_warning":"The package contains no names or Home Assistant IDs, but it does contain the exact geometry and dimensions of your home.","support.close_busy_title":"Stop the current operation?","support.close_busy_body":"House Plan is preparing or sending the report. Closing now stops waiting for the result.","support.building":"Preparing anonymized data…","support.preview_summary":"Package v{version} · {spaces} spaces · {size} KiB","support.prepared":"Snapshot prepared {n} min ago","support.show_data":"Show data","support.download":"Download JSON","support.refresh":"Refresh snapshot","support.privacy":"When you send, your message, optional contact and, if selected, exact geometry leave your Home Assistant through the House Plan project relay and are visible to maintainers. The project node keeps the report for up to 30 days. Network infrastructure sees your HA server address, but House Plan does not retain it raw; rate-limit and idempotency metadata is kept for up to 24 hours.","support.error_title":"The report was not sent","support.manual_recovery":"You can keep the message and attachment and continue manually:","support.copy_message":"Copy message","support.success":"Report sent: {id}. Save this number when contacting support.","support.copy_id":"Copy ID","support.sending":"Sending…","support.retry":"Retry","support.send":"Send","support.update_required":"Update the House Plan card and integration to compatible versions to send reports.","support.message_copied":"Message copied","support.id_copied":"Report ID copied","support.copy_failed":"Could not access the clipboard. Select and copy the text manually.","support.validation.message_required":"Enter a message.","support.validation.message_too_long":"The message must contain no more than 10,000 characters.","support.validation.contact_too_long":"Contact details must contain no more than 320 characters.","support.validation.preview_missing":"Wait for the attachment preview or turn the attachment off.","support.validation.preview_expired":"The attachment preview expired. Refresh the snapshot.","support.error.support_invalid_message":"Check the message and try again.","support.error.support_preview_expired":"The attachment preview expired or is no longer available. Refresh the snapshot.","support.error.support_package_too_large":"The anonymized package exceeds the 8 MiB limit.","support.error.support_rate_limited":"Too many reports or previews were requested. Try again later.","support.error.support_unavailable":"The private support service is temporarily unavailable. Your draft remains here.","support.error.support_rejected":"The report did not pass the support service validation.","support.error.unauthorized":"You do not have permission to send this report.","vac.routes_section":"Maps and floors","vac.routes_current_map":"Current map","vac.routes_no_map":"no telemetry","vac.routes_status":"Routing","vac.routes_state_ready":"map assigned and calibrated","vac.routes_state_needs_calibration":"map assigned, calibration needed","vac.routes_state_unmapped":"current map is not assigned to a floor","vac.routes_state_ambiguous":"two maps are indistinguishable — no floor is chosen","vac.routes_state_missing_space":"the map's space was deleted","vac.routes_state_none":"no map data","vac.routes_empty":"No map is assigned to a floor yet.","vac.route_map_default":"no map id","vac.route_active":"Active","vac.route_space":"Space","vac.route_space_none":"not selected","vac.route_status_ready":"ready","vac.route_status_needs_calibration":"needs calibration","vac.route_status_ambiguous":"ambiguous","vac.route_status_missing_space":"space deleted","vac.route_missing_space_group":"Deleted space","vac.route_add_current":"Add current map","vac.route_delete":"Remove map","vac.route_delete_title":"Remove the map from its floor?","vac.route_delete_body":"Calibration and saved paths for this map will be removed. Continue?","vac.route_delete_confirm":"Remove","vac.route_space_title":"Move the map to another space?","vac.route_space_body":"Calibration and saved paths for this map will be removed. Continue?","vac.route_space_confirm":"Move","vac.route_missing_space_hint":"One of the maps points at a deleted space: pick a new one or remove the map. Until then the robot is not drawn for that map.","vac.route_default_hint":"The source reports no stable map id. Several floors cannot be told apart without another source or the robot's own selected map.","vac.route_target_hint":"The dock stays in the “{space}” space regardless of the current map.","vac.route_add_source":"Add a map source","vac.route_add_source_hint":"For integrations that give each map its own camera. The “All cameras” section above widens this list.","vac.route_source_no_map":"no map reported"};const zo={en:Ro,ru:{"gs.hint":"Цвета заливок действуют на все пространства; у каждого цвета своя прозрачность. Какой режим заливки использует пространство — задаётся в его диалоге.","gs.show_room_tooltip":"Показывать окно с информацией при наведении на комнату","support.about_group":"О карточке","support.guide_group":"Документация","support.guide":"Руководство пользователя","support.form_group":"Отправить репорт или предложение","support.contact":"Контакт для связи (email/tg/WhatsApp), необязательно.","support.message":"Сообщение","support.attach":"Прикрепить обезличенную информацию из вашего плана","support.attach_hint":"В пакет входят только разрешённые геометрия, настройки и ограниченные сведения о среде. Не входят имена, HA id, текущие состояния, URL, файлы, сообщение и контакт.","support.geometry_warning":"Пакет не содержит имён и HA id, но содержит точную геометрию и размеры дома.","support.close_busy_title":"Прервать текущую операцию?","support.close_busy_body":"House Plan подготавливает или отправляет репорт. При закрытии ожидание результата прекратится.","support.building":"Подготавливаем обезличенные данные…","support.preview_summary":"Пакет v{version} · пространств: {spaces} · {size} КиБ","support.prepared":"Снимок подготовлен {n} мин назад","support.show_data":"Показать данные","support.download":"Скачать JSON","support.refresh":"Обновить снимок","support.privacy":"При отправке сообщение, необязательный контакт и, если выбран пакет, точная геометрия покидают ваш Home Assistant через relay проекта House Plan и доступны мейнтейнерам. Узел проекта хранит репорт до 30 дней. Сетевая инфраструктура видит адрес сервера HA, но House Plan не сохраняет его в исходном виде; метаданные лимитов и идемпотентности хранятся до 24 часов.","support.error_title":"Репорт не отправлен","support.manual_recovery":"Сообщение и вложение можно сохранить и продолжить вручную:","support.copy_message":"Копировать сообщение","support.success":"Репорт отправлен: {id}. Сохраните номер для связи с поддержкой.","support.copy_id":"Копировать ID","support.sending":"Отправляем…","support.retry":"Повторить","support.send":"Отправить","support.update_required":"Обновите карточку и интеграцию House Plan до совместимых версий, чтобы отправлять репорты.","support.message_copied":"Сообщение скопировано","support.id_copied":"ID репорта скопирован","support.copy_failed":"Не удалось получить доступ к буферу обмена. Выделите и скопируйте текст вручную.","support.validation.message_required":"Введите сообщение.","support.validation.message_too_long":"Сообщение должно содержать не более 10 000 символов.","support.validation.contact_too_long":"Контакт должен содержать не более 320 символов.","support.validation.preview_missing":"Дождитесь предпросмотра вложения или отключите его.","support.validation.preview_expired":"Предпросмотр вложения истёк. Обновите снимок.","support.error.support_invalid_message":"Проверьте сообщение и повторите попытку.","support.error.support_preview_expired":"Предпросмотр вложения истёк или больше недоступен. Обновите снимок.","support.error.support_package_too_large":"Обезличенный пакет превышает лимит 8 МиБ.","support.error.support_rate_limited":"Запрошено слишком много репортов или предпросмотров. Повторите позже.","support.error.support_unavailable":"Закрытая служба поддержки временно недоступна. Черновик сохранён в этом окне.","support.error.support_rejected":"Репорт не прошёл проверку службы поддержки.","support.error.unauthorized":"У вас нет прав на отправку этого репорта.","vac.routes_section":"Карты и этажи","vac.routes_current_map":"Текущая карта","vac.routes_no_map":"источник молчит","vac.routes_status":"Маршрутизация","vac.routes_state_ready":"карта сопоставлена и откалибрована","vac.routes_state_needs_calibration":"карта сопоставлена, нужна калибровка","vac.routes_state_unmapped":"текущая карта не сопоставлена этажу","vac.routes_state_ambiguous":"две карты неразличимы — этаж не выбирается","vac.routes_state_missing_space":"пространство карты удалено","vac.routes_state_none":"нет данных о карте","vac.routes_empty":"Ни одна карта ещё не сопоставлена этажу.","vac.route_map_default":"без идентификатора","vac.route_active":"Текущая","vac.route_space":"Пространство","vac.route_space_none":"не выбрано","vac.route_status_ready":"готова","vac.route_status_needs_calibration":"нужна калибровка","vac.route_status_ambiguous":"неоднозначна","vac.route_status_missing_space":"пространство удалено","vac.route_missing_space_group":"Пространство удалено","vac.route_add_current":"Добавить текущую карту","vac.route_delete":"Удалить карту","vac.route_delete_title":"Удалить карту с этажа?","vac.route_delete_body":"Калибровка и сохранённые пути этой карты будут удалены. Продолжить?","vac.route_delete_confirm":"Удалить","vac.route_space_title":"Перенести карту в другое пространство?","vac.route_space_body":"Калибровка и сохранённые пути этой карты будут удалены. Продолжить?","vac.route_space_confirm":"Перенести","vac.route_missing_space_hint":"Одна из карт ссылается на удалённое пространство: выберите новое или удалите карту. Пока ссылка не исправлена, робот на этой карте не рисуется.","vac.route_default_hint":"Источник не сообщает стабильный идентификатор карты. Несколько этажей нельзя различить без другого источника или собственной карты робота.","vac.route_target_hint":"Док остаётся в пространстве «{space}» независимо от текущей карты.","vac.route_add_source":"Добавить источник карты","vac.route_add_source_hint":"Для интеграций, где у каждой карты своя камера. Список расширяется разделом «Все камеры» выше.","vac.route_source_no_map":"карта не читается"},de:{"gs.hint":"Füllfarben gelten für jeden Bereich; jede Farbe hat ihre eigene Deckkraft. Der Füllmodus wird in den Einstellungen des jeweiligen Bereichs festgelegt.","gs.show_room_tooltip":"Rauminformationen beim Darüberfahren anzeigen","support.about_group":"Über die Karte","support.guide_group":"Dokumentation","support.guide":"Benutzerhandbuch","support.form_group":"Bericht oder Vorschlag senden","support.contact":"Kontakt (E-Mail/tg/WhatsApp), optional.","support.message":"Nachricht","support.attach":"Anonymisierte Informationen aus dem Plan anhängen","support.attach_hint":"Enthält nur erlaubte Plangeometrie, Einstellungen und begrenzte Laufzeitdaten. Namen, Home-Assistant-IDs, Live-Zustände, URLs, Dateien, Nachricht und Kontakt werden ausgeschlossen.","support.geometry_warning":"Das Paket enthält keine Namen oder Home-Assistant-IDs, aber die exakte Geometrie und die Maße Ihres Hauses.","support.close_busy_title":"Aktuellen Vorgang abbrechen?","support.close_busy_body":"House Plan bereitet den Bericht vor oder sendet ihn. Beim Schließen wird nicht weiter auf das Ergebnis gewartet.","support.building":"Anonymisierte Daten werden vorbereitet…","support.preview_summary":"Paket v{version} · {spaces} Bereiche · {size} KiB","support.prepared":"Schnappschuss vor {n} Min. erstellt","support.show_data":"Daten anzeigen","support.download":"JSON herunterladen","support.refresh":"Schnappschuss aktualisieren","support.privacy":"Beim Senden verlassen Ihre Nachricht, der optionale Kontakt und, falls ausgewählt, die exakte Geometrie Ihren Home Assistant über das House-Plan-Projektrelay und sind für die Maintainer sichtbar. Der Projektserver speichert den Bericht bis zu 30 Tage. Die Netzwerkinfrastruktur sieht die Adresse Ihres HA-Servers, House Plan speichert sie jedoch nicht im Rohformat; Limit- und Idempotenzdaten bleiben bis zu 24 Stunden erhalten.","support.error_title":"Der Bericht wurde nicht gesendet","support.manual_recovery":"Nachricht und Anhang können gespeichert und manuell weitergegeben werden:","support.copy_message":"Nachricht kopieren","support.success":"Bericht gesendet: {id}. Bewahren Sie diese Nummer für den Support auf.","support.copy_id":"ID kopieren","support.sending":"Wird gesendet…","support.retry":"Erneut versuchen","support.send":"Senden","support.update_required":"Aktualisieren Sie House-Plan-Karte und Integration auf kompatible Versionen, um Berichte zu senden.","support.message_copied":"Nachricht kopiert","support.id_copied":"Berichts-ID kopiert","support.copy_failed":"Kein Zugriff auf die Zwischenablage. Markieren und kopieren Sie den Text manuell.","support.validation.message_required":"Geben Sie eine Nachricht ein.","support.validation.message_too_long":"Die Nachricht darf höchstens 10.000 Zeichen enthalten.","support.validation.contact_too_long":"Der Kontakt darf höchstens 320 Zeichen enthalten.","support.validation.preview_missing":"Warten Sie auf die Vorschau oder deaktivieren Sie den Anhang.","support.validation.preview_expired":"Die Anhangsvorschau ist abgelaufen. Aktualisieren Sie den Schnappschuss.","support.error.support_invalid_message":"Prüfen Sie die Nachricht und versuchen Sie es erneut.","support.error.support_preview_expired":"Die Anhangsvorschau ist abgelaufen oder nicht mehr verfügbar. Aktualisieren Sie den Schnappschuss.","support.error.support_package_too_large":"Das anonymisierte Paket überschreitet das Limit von 8 MiB.","support.error.support_rate_limited":"Zu viele Berichte oder Vorschauen wurden angefordert. Versuchen Sie es später erneut.","support.error.support_unavailable":"Der private Supportdienst ist vorübergehend nicht verfügbar. Der Entwurf bleibt in diesem Fenster erhalten.","support.error.support_rejected":"Der Bericht hat die Prüfung des Supportdienstes nicht bestanden.","support.error.unauthorized":"Sie dürfen diesen Bericht nicht senden.","vac.routes_section":"Karten und Etagen","vac.routes_current_map":"Aktuelle Karte","vac.routes_no_map":"keine Telemetrie","vac.routes_status":"Zuordnung","vac.routes_state_ready":"Karte zugeordnet und kalibriert","vac.routes_state_needs_calibration":"Karte zugeordnet, Kalibrierung nötig","vac.routes_state_unmapped":"aktuelle Karte keiner Etage zugeordnet","vac.routes_state_ambiguous":"zwei Karten nicht unterscheidbar — keine Etage gewählt","vac.routes_state_missing_space":"der Raum der Karte wurde gelöscht","vac.routes_state_none":"keine Kartendaten","vac.routes_empty":"Noch keine Karte einer Etage zugeordnet.","vac.route_map_default":"ohne Karten-ID","vac.route_active":"Aktiv","vac.route_space":"Raum","vac.route_space_none":"nicht gewählt","vac.route_status_ready":"bereit","vac.route_status_needs_calibration":"Kalibrierung nötig","vac.route_status_ambiguous":"mehrdeutig","vac.route_status_missing_space":"Raum gelöscht","vac.route_missing_space_group":"Gelöschter Bereich","vac.route_add_current":"Aktuelle Karte hinzufügen","vac.route_delete":"Karte entfernen","vac.route_delete_title":"Karte von der Etage entfernen?","vac.route_delete_body":"Kalibrierung und gespeicherte Pfade dieser Karte werden entfernt. Fortfahren?","vac.route_delete_confirm":"Entfernen","vac.route_space_title":"Karte in einen anderen Raum verschieben?","vac.route_space_body":"Kalibrierung und gespeicherte Pfade dieser Karte werden entfernt. Fortfahren?","vac.route_space_confirm":"Verschieben","vac.route_missing_space_hint":"Eine Karte verweist auf einen gelöschten Raum: neuen wählen oder Karte entfernen. Bis dahin wird der Roboter für diese Karte nicht gezeichnet.","vac.route_default_hint":"Die Quelle meldet keine stabile Karten-ID. Mehrere Etagen lassen sich ohne andere Quelle oder die vom Roboter gewählte Karte nicht unterscheiden.","vac.route_target_hint":"Die Station bleibt unabhängig von der aktuellen Karte im Raum „{space}“.","vac.route_add_source":"Kartenquelle hinzufügen","vac.route_add_source_hint":"Für Integrationen, die jeder Karte eine eigene Kamera geben. Der Abschnitt „Alle Kameras“ oben erweitert diese Liste.","vac.route_source_no_map":"keine Karte gemeldet"},fr:{"gs.hint":"Les couleurs de remplissage s’appliquent à tous les espaces ; chaque couleur possède sa propre opacité. Le mode de remplissage utilisé par un espace se règle dans la boîte de dialogue de cet espace.","gs.show_room_tooltip":"Afficher les informations de la pièce au survol","support.about_group":"À propos de la carte","support.guide_group":"Documentation d’aide","support.guide":"Guide utilisateur","support.form_group":"Envoyer un rapport ou une suggestion","support.contact":"Contact (e-mail/tg/WhatsApp), facultatif.","support.message":"Votre message","support.attach":"Joindre des informations anonymisées de votre plan","support.attach_hint":"Inclut uniquement la géométrie, les réglages autorisés et des données d’exécution limitées. Exclut les noms, identifiants Home Assistant, états en direct, URL, fichiers, message et contact.","support.geometry_warning":"Le paquet ne contient ni noms ni identifiants Home Assistant, mais il contient la géométrie et les dimensions exactes de votre logement.","support.close_busy_title":"Interrompre l’opération en cours ?","support.close_busy_body":"House Plan prépare ou envoie le rapport. Fermer maintenant arrête l’attente du résultat.","support.building":"Préparation des données anonymisées…","support.preview_summary":"Paquet v{version} · {spaces} espaces · {size} Kio","support.prepared":"Instantané préparé il y a {n} min","support.show_data":"Afficher les données","support.download":"Télécharger le JSON","support.refresh":"Actualiser l’instantané","support.privacy":"Lors de l’envoi, votre message, le contact facultatif et, si elle est sélectionnée, la géométrie exacte quittent votre Home Assistant via le relais du projet House Plan et sont visibles par les mainteneurs. Le serveur du projet conserve le rapport jusqu’à 30 jours. L’infrastructure réseau voit l’adresse de votre serveur HA, mais House Plan ne la conserve pas en clair ; les métadonnées de limitation et d’idempotence sont gardées jusqu’à 24 heures.","support.error_title":"Le rapport n’a pas été envoyé","support.manual_recovery":"Vous pouvez conserver le message et la pièce jointe puis continuer manuellement :","support.copy_message":"Copier le message","support.success":"Rapport envoyé : {id}. Conservez ce numéro pour contacter l’assistance.","support.copy_id":"Copier l’ID","support.sending":"Envoi…","support.retry":"Réessayer","support.send":"Envoyer","support.update_required":"Mettez à jour la carte et l’intégration House Plan vers des versions compatibles pour envoyer des rapports.","support.message_copied":"Message copié","support.id_copied":"ID du rapport copié","support.copy_failed":"Impossible d’accéder au presse-papiers. Sélectionnez et copiez le texte manuellement.","support.validation.message_required":"Saisissez un message.","support.validation.message_too_long":"Le message ne doit pas dépasser 10 000 caractères.","support.validation.contact_too_long":"Le contact ne doit pas dépasser 320 caractères.","support.validation.preview_missing":"Attendez l’aperçu de la pièce jointe ou désactivez-la.","support.validation.preview_expired":"L’aperçu de la pièce jointe a expiré. Actualisez l’instantané.","support.error.support_invalid_message":"Vérifiez le message et réessayez.","support.error.support_preview_expired":"L’aperçu de la pièce jointe a expiré ou n’est plus disponible. Actualisez l’instantané.","support.error.support_package_too_large":"Le paquet anonymisé dépasse la limite de 8 Mio.","support.error.support_rate_limited":"Trop de rapports ou d’aperçus ont été demandés. Réessayez plus tard.","support.error.support_unavailable":"Le service d’assistance privé est temporairement indisponible. Le brouillon reste dans cette fenêtre.","support.error.support_rejected":"Le rapport n’a pas passé la validation du service d’assistance.","support.error.unauthorized":"Vous n’êtes pas autorisé à envoyer ce rapport.","vac.routes_section":"Cartes et étages","vac.routes_current_map":"Carte actuelle","vac.routes_no_map":"aucune télémétrie","vac.routes_status":"Routage","vac.routes_state_ready":"carte assignée et calibrée","vac.routes_state_needs_calibration":"carte assignée, calibrage requis","vac.routes_state_unmapped":"carte actuelle non assignée à un étage","vac.routes_state_ambiguous":"deux cartes indiscernables — aucun étage choisi","vac.routes_state_missing_space":"l'espace de la carte a été supprimé","vac.routes_state_none":"aucune donnée de carte","vac.routes_empty":"Aucune carte n'est encore assignée à un étage.","vac.route_map_default":"sans identifiant","vac.route_active":"Active","vac.route_space":"Espace","vac.route_space_none":"non sélectionné","vac.route_status_ready":"prête","vac.route_status_needs_calibration":"calibrage requis","vac.route_status_ambiguous":"ambiguë","vac.route_status_missing_space":"espace supprimé","vac.route_missing_space_group":"Espace supprimé","vac.route_add_current":"Ajouter la carte actuelle","vac.route_delete":"Supprimer la carte","vac.route_delete_title":"Retirer la carte de son étage ?","vac.route_delete_body":"Le calibrage et les trajets enregistrés de cette carte seront supprimés. Continuer ?","vac.route_delete_confirm":"Supprimer","vac.route_space_title":"Déplacer la carte vers un autre espace ?","vac.route_space_body":"Le calibrage et les trajets enregistrés de cette carte seront supprimés. Continuer ?","vac.route_space_confirm":"Déplacer","vac.route_missing_space_hint":"Une carte pointe vers un espace supprimé : choisissez-en un autre ou supprimez la carte. D'ici là, le robot n'est pas dessiné pour cette carte.","vac.route_default_hint":"La source ne fournit pas d'identifiant de carte stable. Plusieurs étages ne peuvent pas être distingués sans une autre source ou la carte sélectionnée du robot.","vac.route_target_hint":"La station reste dans l'espace « {space} » quelle que soit la carte actuelle.","vac.route_add_source":"Ajouter une source de carte","vac.route_add_source_hint":"Pour les intégrations qui donnent à chaque carte sa propre caméra. La section « Toutes les caméras » ci-dessus élargit cette liste.","vac.route_source_no_map":"aucune carte signalée"}};function Ao(t,e,s){return i(zo[t]?.[e]??Ro[e]??e,s)}function Fo(t,e,s,i,o){return{markerId:t,source:i,mapId:o,space:e.length?"":s}}function No(t,e,s){return{...t,space:s.has(e)?e:""}}function Eo(t,e=Math.random){const s=new Set(t);for(let t=0;t<64;t+=1){const t="vr_"+Math.floor(16777215*e()).toString(36).padStart(5,"0");if(!s.has(t))return t}return"vr_"+Date.now().toString(36)}function Ho(t,e,s){return t.map(t=>t.id===e?{...t,calibration:s}:t)}const Oo=new WeakMap,Lo=(t,e)=>{const s=(t._serverCfg?.spaces||[]).find(t=>t?.id===e);return String(s?.name||s?.id||e)};function Bo(t,e,s){const i=t.host,n=l(i.hass,i._config?.language),r=(t,e)=>Ao(n,t,e),u=e.marker?.vacuum||{},_=Array.isArray(u.map_routes),m=i._vacSource(e)||"",g=o(e.id,u,e.space,m),f=(i._serverCfg?.spaces||[]).filter(t=>"string"==typeof t?.id&&!!t.id).map(t=>({id:t.id,name:String(t.name||t.id)})),b=new Set(f.map(t=>t.id)),v=h(g,[m],t=>i._vacObservedMapId(e,t)),y=c({routes:g,observed:v,spaceIds:b}),$="ready"===y.kind||"needs_calibration"===y.kind||"missing_space"===y.kind?y.route.id:"",w=m?v[m]:void 0,k=async s=>{let o=_?u.map_routes??null:null;if(!o&&(o=function(t,e,s,i){if(!s)return null;const o=t?.calibration;if(!o||"object"!=typeof o)return null;const n=new Set,r=[];for(const t of Object.keys(o)){const l=a(o[t]);if(!l)continue;const h=i(n);n.add(h),r.push({id:h,source:s,map_id:t,space:e,calibration:l})}return r.length?r:null}(u,e.space,m,t=>Eo(t))??[],!m&&Object.keys(u.calibration||{}).length))return!1;const n=s(o);return!!n&&(async s=>{const o=i._serverCfg;if(!o)return!1;const a=JSON.parse(JSON.stringify(o));a.markers=a.markers||[];let n=a.markers.find(t=>t.id===e.id);if(!n){if("device"!==e.bindingKind&&"entity"!==e.bindingKind||!e.bindingRef)return!1;n={id:e.id,binding:`${e.bindingKind}:${e.bindingRef}`,space:e.space||null,area:e.area||null,hidden:!!e.hidden},a.markers.push(n)}n.vacuum={...n.vacuum||{},map_routes:s},delete n.vacuum.calibration;const r=i._adoption.beginOptimistic(o,a);i._adoption.stageLocalConfig(a),i._regSignature="",i._maybeRebuildDevices(),i.requestUpdate(),i._saveConfigDebounced.pending()&&i._saveConfigDebounced.cancel();try{return await t._saveConfigNow(),!0}catch(t){return i._rollbackOptimistic(r),i._regSignature="",i._maybeRebuildDevices(),i.requestUpdate(),i._showToast(i._t("toast.cfg_save_failed",{err:i._errText(t)})),!1}})(n)},x=s.candidates.filter(t=>t.entityId!==m&&!g.some(e=>e.source===t.entityId)),S=async(t,e)=>{if(!e||e===t.space)return;await i._confirmDanger({key:"vacuum_route_space",kind:"warning",title:r("vac.route_space_title"),message:r("vac.route_space_body"),objectName:t.map_id||r("vac.route_map_default"),confirmLabel:r("vac.route_space_confirm"),cancelLabel:i._t("btn.cancel")})&&await k(s=>function(t,e,s,i){return t.map(t=>t.id===e?{...t,id:i,space:s,calibration:null}:t)}(s,t.id,e,Eo(new Set(g.map(t=>t.id)))))},M=new Map(f.map((t,e)=>[t.id,e])),C=(t,e)=>t.map_id.localeCompare(e.map_id)||t.source.localeCompare(e.source)||t.id.localeCompare(e.id),P=g.filter(t=>b.has(t.space)).sort((t,e)=>(M.get(t.space)??0)-(M.get(e.space)??0)||C(t,e)),D=g.filter(t=>!b.has(t.space)).sort(C),I=[...P,...D],T=!!m&&void 0!==w&&!g.some(t=>t.source===m&&t.map_id===w);let R=Oo.get(t);const z=R?.source||"",A=R?.mapId||"",F=!!R&&g.some(t=>t.source===z&&t.map_id===A);R&&(R.markerId!==e.id||i._vacObservedMapId(e,R.source)!==R.mapId||F&&!R.saving)&&(Oo.delete(t),R=void 0),R?.space&&!b.has(R.space)&&(R=No(R,"",b),Oo.set(t,R));const N=s=>p`
  • ${s.map_id||r("vac.route_map_default")} @@ -235,7 +235,7 @@ globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="241ab786b7cce5c1f837e73704240f138bd3
    `:d} `}}Ma.properties={hass:{attribute:!1},presentation:{attribute:!1},registry:{attribute:!1},deviceName:{attribute:!1}},Ma.styles=[S,w`:host{display:block;min-width:0;}.devicepreview{margin:4px 0 14px;padding:14px;border:1px solid var(--divider-color,rgba(127,127,127,0.28));border-radius:14px;background:color-mix(in srgb,var(--card-background-color,#20232b) 92%,var(--primary-color,#03a9f4));color:var(--primary-text-color,#fff);overflow:hidden;}.previewhead{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px;}.previewbadge{padding:3px 9px;border-radius:999px;color:var(--secondary-text-color,#9aa0aa);background:color-mix(in srgb,var(--secondary-text-color,#9aa0aa) 12%,transparent);font-size:12px;font-weight:700;}.previewbadge.example{color:var(--warning-color,#ffb300);}.previewgrid{display:grid;grid-template-columns:minmax(170px,0.8fr) minmax(240px,1.2fr);gap:16px;align-items:stretch;}.previewstage{position:relative;min-height:168px;border-radius:12px;background:var(--secondary-background-color,rgba(0,0,0,0.16));overflow:hidden;pointer-events:none;container-type:inline-size;--icon-size:54px;--device-base-size:48.6px;}.previewfit{position:absolute;left:50%;top:50%;transform-origin:center;}.previewstage .dev{left:0;top:0;cursor:default;}:host([data-pointer-hover]) .previewstage .dev:hover{z-index:2;}.previewfacts{min-width:0;display:grid;align-content:start;gap:8px;}.previewfacts>div{display:grid;grid-template-columns:minmax(115px,0.8fr) minmax(0,1.3fr);gap:8px;}.previewfacts span{color:var(--secondary-text-color,#9aa0aa);}.previewfacts b{min-width:0;overflow-wrap:anywhere;}.previewnotice{margin:2px 0 0;color:var(--secondary-text-color,#9aa0aa);font-size:13px;}.previewdetails{margin-top:12px;}.previewdetails summary{cursor:pointer;color:var(--secondary-text-color,#9aa0aa);}.previewtable{display:grid;gap:8px;margin-top:9px;}.previewsource{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:3px 10px;font-size:13px;}.previewsource>*{min-width:0;overflow-wrap:anywhere;}.previewsource code{color:var(--secondary-text-color,#9aa0aa);}.previewdemo{min-height:40px;display:inline-flex;align-items:center;gap:8px;padding:8px 12px;border:1px solid var(--divider-color,rgba(127,127,127,0.35));border-radius:10px;background:transparent;color:inherit;cursor:pointer;}.previewdemos{display:flex;flex-wrap:wrap;gap:8px;margin-top:12px;}.previewdemo:focus-visible{outline:2px solid var(--primary-color,#03a9f4);outline-offset:2px;}.previewdemo:disabled{opacity:0.5;cursor:not-allowed;}@media (max-width:640px){.previewgrid{grid-template-columns:minmax(0,1fr);}.previewstage{min-height:142px;}.previewfacts>div{grid-template-columns:minmax(0,1fr);gap:2px;}}`],customElements.get("hp-device-preview")||customElements.define("hp-device-preview",Ma);const Ca={revision:0,topologies:[],states:{}};class Pa extends k{constructor(){super(...arguments),this.value={enabled:!1,z2mBaseTopics:[]},this.savedEnabled=!1,this.devices=[],this._runtime=null,this._snapshot=Ca,this._topicText="zigbee2mqtt",this._invalidTopic=!1}disconnectedCallback(){this._release?.(),this._release=void 0,super.disconnectedCallback()}updated(t){t.has("hass")&&(this._release?.(),this._release=void 0,this._runtime=null,this._snapshot=Ca),this.savedEnabled&&this._admin&&this._ensureRuntime()}willUpdate(t){t.has("value")&&(this._topicText=(this.value.z2mBaseTopics.length?this.value.z2mBaseTopics:["zigbee2mqtt"]).join("\n"),this._invalidTopic=!1)}get _admin(){return!0===this.hass?.user?.is_admin}_t(t,e){return xo(l(this.hass),t,e)}_help(){const t=l(this.hass);return So(t,"help")&&So(t,"help_aria")?p``:d}async _ensureRuntime(){return this._runtime||(this._runtime=await import("./zigbee-topology-runtime-BkrLGjiL.js"),this._snapshot=this._runtime.zigbeeTopologyRuntimeSnapshot(this.hass),this._release=this._runtime.subscribeZigbeeTopology(this.hass,()=>{this._snapshot=this._runtime.zigbeeTopologyRuntimeSnapshot(this.hass),this.requestUpdate()}),this.requestUpdate()),this._runtime}_emit(t){this._admin&&this.dispatchEvent(new CustomEvent("hp-topology-settings-change",{detail:t,bubbles:!0,composed:!0}))}_topics(){return this.value.z2mBaseTopics.length?this.value.z2mBaseTopics:["zigbee2mqtt"]}_editTopics(t){this._topicText=t;const e=t.split(/[\r\n,]+/).map(t=>t.trim()).filter(Boolean),s=e.map(R).filter(Boolean);this._invalidTopic=s.length!==e.length,this._invalidTopic?this.requestUpdate():this._emit({...this.value,z2mBaseTopics:[...new Set(s)].slice(0,8)})}_status(t){const e=this._snapshot.states[t];if(!e)return this._t("status_idle");if("loading"===e.phase)return this._t("status_loading");if("error"===e.phase)return this._t(`error_${e.error||"provider"}`);if("ready"!==e.phase||!e.obtainedAt)return this._t("status_idle");const s=new Date(e.obtainedAt).toLocaleTimeString(l(this.hass),{hour:"2-digit",minute:"2-digit"}),i=this._snapshot.topologies.find(e=>"zha"===t?"zha"===e.provider:`z2m:${e.instanceId}`===t),o=!!i&&!!this.registry&&Mo(i,this.devices,this.registry).warnings.length>0;return e.partial||o?this._t("status_partial",{time:s}):i&&!i.links.length?this._t("status_no_links",{time:s}):this._t(Date.now()-e.obtainedAt>Co?"status_stale":"status_ready",{time:s})}_busy(t){return"loading"===this._snapshot.states[t]?.phase}async _readZha(){this.savedEnabled&&this._admin&&(await this._ensureRuntime()).readZhaTopology(this.hass)}async _refreshZ2m(t){this.savedEnabled&&this._admin&&(await this._ensureRuntime()).refreshZ2mTopology(this.hass,t)}render(){const t=this._admin,e=this.value.enabled,s=t&&this.savedEnabled,i=this._topics();return p` + .ariaLabel=${this._t("help_aria")}>`:d}async _ensureRuntime(){return this._runtime||(this._runtime=await import("./zigbee-topology-runtime-DvLAh834.js"),this._snapshot=this._runtime.zigbeeTopologyRuntimeSnapshot(this.hass),this._release=this._runtime.subscribeZigbeeTopology(this.hass,()=>{this._snapshot=this._runtime.zigbeeTopologyRuntimeSnapshot(this.hass),this.requestUpdate()}),this.requestUpdate()),this._runtime}_emit(t){this._admin&&this.dispatchEvent(new CustomEvent("hp-topology-settings-change",{detail:t,bubbles:!0,composed:!0}))}_topics(){return this.value.z2mBaseTopics.length?this.value.z2mBaseTopics:["zigbee2mqtt"]}_editTopics(t){this._topicText=t;const e=t.split(/[\r\n,]+/).map(t=>t.trim()).filter(Boolean),s=e.map(R).filter(Boolean);this._invalidTopic=s.length!==e.length,this._invalidTopic?this.requestUpdate():this._emit({...this.value,z2mBaseTopics:[...new Set(s)].slice(0,8)})}_status(t){const e=this._snapshot.states[t];if(!e)return this._t("status_idle");if("loading"===e.phase)return this._t("status_loading");if("error"===e.phase)return this._t(`error_${e.error||"provider"}`);if("ready"!==e.phase||!e.obtainedAt)return this._t("status_idle");const s=new Date(e.obtainedAt).toLocaleTimeString(l(this.hass),{hour:"2-digit",minute:"2-digit"}),i=this._snapshot.topologies.find(e=>"zha"===t?"zha"===e.provider:`z2m:${e.instanceId}`===t),o=!!i&&!!this.registry&&Mo(i,this.devices,this.registry).warnings.length>0;return e.partial||o?this._t("status_partial",{time:s}):i&&!i.links.length?this._t("status_no_links",{time:s}):this._t(Date.now()-e.obtainedAt>Co?"status_stale":"status_ready",{time:s})}_busy(t){return"loading"===this._snapshot.states[t]?.phase}async _readZha(){this.savedEnabled&&this._admin&&(await this._ensureRuntime()).readZhaTopology(this.hass)}async _refreshZ2m(t){this.savedEnabled&&this._admin&&(await this._ensureRuntime()).refreshZ2mTopology(this.hass,t)}render(){const t=this._admin,e=this.value.enabled,s=t&&this.savedEnabled,i=this._topics();return p`
    ${this._t("title")}${this._help()}
  • ${s.map_id||r("vac.route_map_default")} @@ -235,7 +235,7 @@ globalThis.__HOUSEPLAN_BUILD_FINGERPRINT__="241ab786b7cce5c1f837e73704240f138bd3
    `:d} `}}Ma.properties={hass:{attribute:!1},presentation:{attribute:!1},registry:{attribute:!1},deviceName:{attribute:!1}},Ma.styles=[S,w`:host{display:block;min-width:0;}.devicepreview{margin:4px 0 14px;padding:14px;border:1px solid var(--divider-color,rgba(127,127,127,0.28));border-radius:14px;background:color-mix(in srgb,var(--card-background-color,#20232b) 92%,var(--primary-color,#03a9f4));color:var(--primary-text-color,#fff);overflow:hidden;}.previewhead{display:flex;align-items:center;justify-content:space-between;gap:12px;margin-bottom:12px;}.previewbadge{padding:3px 9px;border-radius:999px;color:var(--secondary-text-color,#9aa0aa);background:color-mix(in srgb,var(--secondary-text-color,#9aa0aa) 12%,transparent);font-size:12px;font-weight:700;}.previewbadge.example{color:var(--warning-color,#ffb300);}.previewgrid{display:grid;grid-template-columns:minmax(170px,0.8fr) minmax(240px,1.2fr);gap:16px;align-items:stretch;}.previewstage{position:relative;min-height:168px;border-radius:12px;background:var(--secondary-background-color,rgba(0,0,0,0.16));overflow:hidden;pointer-events:none;container-type:inline-size;--icon-size:54px;--device-base-size:48.6px;}.previewfit{position:absolute;left:50%;top:50%;transform-origin:center;}.previewstage .dev{left:0;top:0;cursor:default;}:host([data-pointer-hover]) .previewstage .dev:hover{z-index:2;}.previewfacts{min-width:0;display:grid;align-content:start;gap:8px;}.previewfacts>div{display:grid;grid-template-columns:minmax(115px,0.8fr) minmax(0,1.3fr);gap:8px;}.previewfacts span{color:var(--secondary-text-color,#9aa0aa);}.previewfacts b{min-width:0;overflow-wrap:anywhere;}.previewnotice{margin:2px 0 0;color:var(--secondary-text-color,#9aa0aa);font-size:13px;}.previewdetails{margin-top:12px;}.previewdetails summary{cursor:pointer;color:var(--secondary-text-color,#9aa0aa);}.previewtable{display:grid;gap:8px;margin-top:9px;}.previewsource{display:grid;grid-template-columns:minmax(0,1fr) minmax(0,1fr);gap:3px 10px;font-size:13px;}.previewsource>*{min-width:0;overflow-wrap:anywhere;}.previewsource code{color:var(--secondary-text-color,#9aa0aa);}.previewdemo{min-height:40px;display:inline-flex;align-items:center;gap:8px;padding:8px 12px;border:1px solid var(--divider-color,rgba(127,127,127,0.35));border-radius:10px;background:transparent;color:inherit;cursor:pointer;}.previewdemos{display:flex;flex-wrap:wrap;gap:8px;margin-top:12px;}.previewdemo:focus-visible{outline:2px solid var(--primary-color,#03a9f4);outline-offset:2px;}.previewdemo:disabled{opacity:0.5;cursor:not-allowed;}@media (max-width:640px){.previewgrid{grid-template-columns:minmax(0,1fr);}.previewstage{min-height:142px;}.previewfacts>div{grid-template-columns:minmax(0,1fr);gap:2px;}}`],customElements.get("hp-device-preview")||customElements.define("hp-device-preview",Ma);const Ca={revision:0,topologies:[],states:{}};class Pa extends k{constructor(){super(...arguments),this.value={enabled:!1,z2mBaseTopics:[]},this.savedEnabled=!1,this.devices=[],this._runtime=null,this._snapshot=Ca,this._topicText="zigbee2mqtt",this._invalidTopic=!1}disconnectedCallback(){this._release?.(),this._release=void 0,super.disconnectedCallback()}updated(t){t.has("hass")&&(this._release?.(),this._release=void 0,this._runtime=null,this._snapshot=Ca),this.savedEnabled&&this._admin&&this._ensureRuntime()}willUpdate(t){t.has("value")&&(this._topicText=(this.value.z2mBaseTopics.length?this.value.z2mBaseTopics:["zigbee2mqtt"]).join("\n"),this._invalidTopic=!1)}get _admin(){return!0===this.hass?.user?.is_admin}_t(t,e){return xo(l(this.hass),t,e)}_help(){const t=l(this.hass);return So(t,"help")&&So(t,"help_aria")?p``:d}async _ensureRuntime(){return this._runtime||(this._runtime=await import("./zigbee-topology-runtime-BkrLGjiL.js"),this._snapshot=this._runtime.zigbeeTopologyRuntimeSnapshot(this.hass),this._release=this._runtime.subscribeZigbeeTopology(this.hass,()=>{this._snapshot=this._runtime.zigbeeTopologyRuntimeSnapshot(this.hass),this.requestUpdate()}),this.requestUpdate()),this._runtime}_emit(t){this._admin&&this.dispatchEvent(new CustomEvent("hp-topology-settings-change",{detail:t,bubbles:!0,composed:!0}))}_topics(){return this.value.z2mBaseTopics.length?this.value.z2mBaseTopics:["zigbee2mqtt"]}_editTopics(t){this._topicText=t;const e=t.split(/[\r\n,]+/).map(t=>t.trim()).filter(Boolean),s=e.map(R).filter(Boolean);this._invalidTopic=s.length!==e.length,this._invalidTopic?this.requestUpdate():this._emit({...this.value,z2mBaseTopics:[...new Set(s)].slice(0,8)})}_status(t){const e=this._snapshot.states[t];if(!e)return this._t("status_idle");if("loading"===e.phase)return this._t("status_loading");if("error"===e.phase)return this._t(`error_${e.error||"provider"}`);if("ready"!==e.phase||!e.obtainedAt)return this._t("status_idle");const s=new Date(e.obtainedAt).toLocaleTimeString(l(this.hass),{hour:"2-digit",minute:"2-digit"}),i=this._snapshot.topologies.find(e=>"zha"===t?"zha"===e.provider:`z2m:${e.instanceId}`===t),o=!!i&&!!this.registry&&Mo(i,this.devices,this.registry).warnings.length>0;return e.partial||o?this._t("status_partial",{time:s}):i&&!i.links.length?this._t("status_no_links",{time:s}):this._t(Date.now()-e.obtainedAt>Co?"status_stale":"status_ready",{time:s})}_busy(t){return"loading"===this._snapshot.states[t]?.phase}async _readZha(){this.savedEnabled&&this._admin&&(await this._ensureRuntime()).readZhaTopology(this.hass)}async _refreshZ2m(t){this.savedEnabled&&this._admin&&(await this._ensureRuntime()).refreshZ2mTopology(this.hass,t)}render(){const t=this._admin,e=this.value.enabled,s=t&&this.savedEnabled,i=this._topics();return p` + .ariaLabel=${this._t("help_aria")}>`:d}async _ensureRuntime(){return this._runtime||(this._runtime=await import("./zigbee-topology-runtime-DvLAh834.js"),this._snapshot=this._runtime.zigbeeTopologyRuntimeSnapshot(this.hass),this._release=this._runtime.subscribeZigbeeTopology(this.hass,()=>{this._snapshot=this._runtime.zigbeeTopologyRuntimeSnapshot(this.hass),this.requestUpdate()}),this.requestUpdate()),this._runtime}_emit(t){this._admin&&this.dispatchEvent(new CustomEvent("hp-topology-settings-change",{detail:t,bubbles:!0,composed:!0}))}_topics(){return this.value.z2mBaseTopics.length?this.value.z2mBaseTopics:["zigbee2mqtt"]}_editTopics(t){this._topicText=t;const e=t.split(/[\r\n,]+/).map(t=>t.trim()).filter(Boolean),s=e.map(R).filter(Boolean);this._invalidTopic=s.length!==e.length,this._invalidTopic?this.requestUpdate():this._emit({...this.value,z2mBaseTopics:[...new Set(s)].slice(0,8)})}_status(t){const e=this._snapshot.states[t];if(!e)return this._t("status_idle");if("loading"===e.phase)return this._t("status_loading");if("error"===e.phase)return this._t(`error_${e.error||"provider"}`);if("ready"!==e.phase||!e.obtainedAt)return this._t("status_idle");const s=new Date(e.obtainedAt).toLocaleTimeString(l(this.hass),{hour:"2-digit",minute:"2-digit"}),i=this._snapshot.topologies.find(e=>"zha"===t?"zha"===e.provider:`z2m:${e.instanceId}`===t),o=!!i&&!!this.registry&&Mo(i,this.devices,this.registry).warnings.length>0;return e.partial||o?this._t("status_partial",{time:s}):i&&!i.links.length?this._t("status_no_links",{time:s}):this._t(Date.now()-e.obtainedAt>Co?"status_stale":"status_ready",{time:s})}_busy(t){return"loading"===this._snapshot.states[t]?.phase}async _readZha(){this.savedEnabled&&this._admin&&(await this._ensureRuntime()).readZhaTopology(this.hass)}async _refreshZ2m(t){this.savedEnabled&&this._admin&&(await this._ensureRuntime()).refreshZ2mTopology(this.hass,t)}render(){const t=this._admin,e=this.value.enabled,s=t&&this.savedEnabled,i=this._topics();return p`
    ${this._t("title")}${this._help()}