@duckcodeailabs/dql-cli 1.14.1 → 1.14.3-rc.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/args.d.ts +4 -0
- package/dist/args.d.ts.map +1 -1
- package/dist/args.js +16 -0
- package/dist/args.js.map +1 -1
- package/dist/assets/dql-notebook/assets/{AgentLogPage-BPz-UWFh.js → AgentLogPage-Jbyb4so-.js} +1 -1
- package/dist/assets/dql-notebook/assets/{AiBuildDialog-BEl53WA_.js → AiBuildDialog-Du07X1qO.js} +1 -1
- package/dist/assets/dql-notebook/assets/{AiBuildResult-B4yfGTTZ.js → AiBuildResult-xKtGthWv.js} +1 -1
- package/dist/assets/dql-notebook/assets/{AiSidePanel-CSZAAvuD.js → AiSidePanel-CE_L04dK.js} +1 -1
- package/dist/assets/dql-notebook/assets/AnalyticsHome-CiUE10uF.js +6 -0
- package/dist/assets/dql-notebook/assets/{AppsView-DQOwU9Cg.js → AppsView-DlNaTuwD.js} +30 -35
- package/dist/assets/dql-notebook/assets/AskObservabilityPage-DracZPI9.js +1 -0
- package/dist/assets/dql-notebook/assets/AskTracePage-CSMoMw9a.js +8 -0
- package/dist/assets/dql-notebook/assets/{BlockStudio-B4ap0GdY.js → BlockStudio-DQS5Hcq9.js} +9 -14
- package/dist/assets/dql-notebook/assets/BusinessArtifactView-CqV4i9l_.js +1 -0
- package/dist/assets/dql-notebook/assets/{DbtFirstModelingPage-D72byb2g.js → DbtFirstModelingPage-JKhB_Y2H.js} +3 -3
- package/dist/assets/dql-notebook/assets/{GitPage-lQb1uXH2.js → GitPage-DjaNp0o3.js} +1 -1
- package/dist/assets/dql-notebook/assets/{GlobalAiRail-CVECf6Xj.js → GlobalAiRail-CsV3zlc8.js} +1 -1
- package/dist/assets/dql-notebook/assets/{GovernedContextPage-trOyMCY6.js → GovernedContextPage-uXUHUOIJ.js} +3 -3
- package/dist/assets/dql-notebook/assets/{HelpDocsPage-D8hLS5lE.js → HelpDocsPage-Hbh9IeYB.js} +1 -1
- package/dist/assets/dql-notebook/assets/{HomePage-eIkfBIep.js → HomePage-CRRl-R_v.js} +1 -1
- package/dist/assets/dql-notebook/assets/LineageDAG-OMUP2sbl.js +1 -0
- package/dist/assets/dql-notebook/assets/LineageDetailView-C964BLuV.js +1 -0
- package/dist/assets/dql-notebook/assets/LineageDrawer-CzY0nfpD.js +1 -0
- package/dist/assets/dql-notebook/assets/{LineagePathBreadcrumb-CviIf8PN.js → LineagePathBreadcrumb-0Gi-Fm1B.js} +1 -1
- package/dist/assets/dql-notebook/assets/MiniLineageGraph-wn0wLc9m.js +1 -0
- package/dist/assets/dql-notebook/assets/{NewBlockModal-DbCQg-pj.js → NewBlockModal-kMAzk91d.js} +1 -1
- package/dist/assets/dql-notebook/assets/{NewNotebookModal-5Vp6XiuK.js → NewNotebookModal-D_cWd_6M.js} +1 -1
- package/dist/assets/dql-notebook/assets/{NotebookEditor-DjqJS44s.js → NotebookEditor-Bax0lxaz.js} +25 -30
- package/dist/assets/dql-notebook/assets/{ReadinessPage-BHGrC5ho.js → ReadinessPage-DEUIXQQY.js} +1 -1
- package/dist/assets/dql-notebook/assets/{SetupOnboarding-BfS9Tdx-.js → SetupOnboarding-CyE-Ex41.js} +1 -1
- package/dist/assets/dql-notebook/assets/{SkillsPage-BFH21wSj.js → SkillsPage-QgvKGPxE.js} +1 -1
- package/dist/assets/dql-notebook/assets/{TrustBadge-zm6g_SxZ.js → TrustBadge-D5CGp0cu.js} +1 -1
- package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel-BjsTE6yf.js +89 -0
- package/dist/assets/dql-notebook/assets/{answer-to-notebook-DPhxIEzF.js → answer-to-notebook-tACdCsTV.js} +1 -1
- package/dist/assets/dql-notebook/assets/{arrow-left-DNEb86Xc.js → arrow-left-CF6wxXU5.js} +1 -1
- package/dist/assets/dql-notebook/assets/{arrow-right-DpPWbwaD.js → arrow-right-C7G3M_S8.js} +1 -1
- package/dist/assets/dql-notebook/assets/{book-open-text-D7s5jo4X.js → book-open-text-DDBO8G7L.js} +1 -1
- package/dist/assets/dql-notebook/assets/chevron-left-DxajrX2v.js +6 -0
- package/dist/assets/dql-notebook/assets/{circle-x-Db3dXKg7.js → circle-x-HBvXjnT6.js} +1 -1
- package/dist/assets/dql-notebook/assets/clock-3-CJIdsPLt.js +6 -0
- package/dist/assets/dql-notebook/assets/dagre.esm-B6nvU4OB.js +1 -0
- package/dist/assets/dql-notebook/assets/{external-link-BxwXitO_.js → external-link-WciAU8Bu.js} +1 -1
- package/dist/assets/dql-notebook/assets/{grip-vertical-Dt4lkWRi.js → grip-vertical-DVu7ok6x.js} +1 -1
- package/dist/assets/dql-notebook/assets/index-B_kaoARS.css +1 -0
- package/dist/assets/dql-notebook/assets/{index-DKo-bwNw.js → index-D3wnucQC.js} +133 -128
- package/dist/assets/dql-notebook/assets/{link-2-Dfo2P6wi.js → link-2-C6uQx50X.js} +1 -1
- package/dist/assets/dql-notebook/assets/{list-tree-DiTmIWAL.js → list-tree-DapsIuQB.js} +1 -1
- package/dist/assets/dql-notebook/assets/{minimize-2-CMTAkPzL.js → minimize-2-BlVoipnT.js} +1 -1
- package/dist/assets/dql-notebook/assets/{panel-right-open-DwYr7FW4.js → panel-right-open-DcnKWxfx.js} +1 -1
- package/dist/assets/dql-notebook/assets/{play-BXhHYQ4x.js → play-CNuRuaAs.js} +1 -1
- package/dist/assets/dql-notebook/assets/{rotate-ccw-BNi6F8pl.js → rotate-ccw-B2p953Zh.js} +1 -1
- package/dist/assets/dql-notebook/assets/{semantic-fields-CNOGysAy.js → semantic-fields-2fWgkTJc.js} +1 -1
- package/dist/assets/dql-notebook/assets/{sliders-horizontal-Ec5MUMUW.js → sliders-horizontal-DwRTu1w4.js} +1 -1
- package/dist/assets/dql-notebook/assets/{star-B9leDkp_.js → star-Cbaj4F3i.js} +1 -1
- package/dist/assets/dql-notebook/assets/style-NlN9F6JE.js +23 -0
- package/dist/assets/dql-notebook/assets/{triangle-alert-BefTYCzx.js → triangle-alert-BPHvH1wA.js} +1 -1
- package/dist/assets/dql-notebook/assets/{upload-SPiOM2tQ.js → upload-DIqK0KE1.js} +1 -1
- package/dist/assets/dql-notebook/assets/{usePersistedAgentThreadId-C4foXeiQ.js → usePersistedAgentThreadId-DpQXOEDw.js} +1 -1
- package/dist/assets/dql-notebook/assets/{user-round-comGmyw-.js → user-round-DukNupB_.js} +1 -1
- package/dist/assets/dql-notebook/assets/{wand-sparkles-BffR4dF8.js → wand-sparkles-CAwLX0b9.js} +1 -1
- package/dist/assets/dql-notebook/assets/{workflow-ChmPTEzH.js → workflow-bOT-NqdO.js} +1 -1
- package/dist/assets/dql-notebook/assets/{wrench-DovaG_ze.js → wrench-1m0_kcza.js} +1 -1
- package/dist/assets/dql-notebook/assets/{x-nRx91AgW.js → x-fp82BETM.js} +1 -1
- package/dist/assets/dql-notebook/index.html +2 -2
- package/dist/commands/agent-eval-cassette.d.ts +97 -6
- package/dist/commands/agent-eval-cassette.d.ts.map +1 -1
- package/dist/commands/agent-eval-cassette.js +165 -22
- package/dist/commands/agent-eval-cassette.js.map +1 -1
- package/dist/commands/agent-eval-runtime.d.ts +23 -2
- package/dist/commands/agent-eval-runtime.d.ts.map +1 -1
- package/dist/commands/agent-eval-runtime.js +19 -2
- package/dist/commands/agent-eval-runtime.js.map +1 -1
- package/dist/commands/agent-trace.d.ts +3 -0
- package/dist/commands/agent-trace.d.ts.map +1 -0
- package/dist/commands/agent-trace.js +169 -0
- package/dist/commands/agent-trace.js.map +1 -0
- package/dist/commands/agent.d.ts +37 -5
- package/dist/commands/agent.d.ts.map +1 -1
- package/dist/commands/agent.js +534 -84
- package/dist/commands/agent.js.map +1 -1
- package/dist/commands/compile.d.ts +13 -1
- package/dist/commands/compile.d.ts.map +1 -1
- package/dist/commands/compile.js +36 -4
- package/dist/commands/compile.js.map +1 -1
- package/dist/commands/notebook.d.ts +2 -0
- package/dist/commands/notebook.d.ts.map +1 -1
- package/dist/commands/notebook.js +4 -0
- package/dist/commands/notebook.js.map +1 -1
- package/dist/commands/sync.d.ts.map +1 -1
- package/dist/commands/sync.js +11 -3
- package/dist/commands/sync.js.map +1 -1
- package/dist/index.js +2 -0
- package/dist/index.js.map +1 -1
- package/dist/llm/providers/dql-agent-provider.d.ts +29 -2
- package/dist/llm/providers/dql-agent-provider.d.ts.map +1 -1
- package/dist/llm/providers/dql-agent-provider.js +1008 -144
- package/dist/llm/providers/dql-agent-provider.js.map +1 -1
- package/dist/llm/types.d.ts +48 -1
- package/dist/llm/types.d.ts.map +1 -1
- package/dist/local-runtime.d.ts +271 -33
- package/dist/local-runtime.d.ts.map +1 -1
- package/dist/local-runtime.js +3658 -546
- package/dist/local-runtime.js.map +1 -1
- package/dist/package.json +10 -10
- package/dist/providers/oauth/claude-oauth.d.ts.map +1 -1
- package/dist/providers/oauth/claude-oauth.js +52 -18
- package/dist/providers/oauth/claude-oauth.js.map +1 -1
- package/dist/providers/oauth/codex-oauth.d.ts.map +1 -1
- package/dist/providers/oauth/codex-oauth.js +72 -44
- package/dist/providers/oauth/codex-oauth.js.map +1 -1
- package/dist/providers/subscription-cli.d.ts +20 -0
- package/dist/providers/subscription-cli.d.ts.map +1 -1
- package/dist/providers/subscription-cli.js +69 -11
- package/dist/providers/subscription-cli.js.map +1 -1
- package/package.json +10 -10
- package/dist/assets/dql-notebook/assets/AnalyticsHome-D5P6Ujwi.js +0 -6
- package/dist/assets/dql-notebook/assets/BusinessArtifactView-BIfNI-0S.js +0 -1
- package/dist/assets/dql-notebook/assets/LineageDAG-CSqcbDrE.js +0 -1
- package/dist/assets/dql-notebook/assets/LineageDetailView-DJZZjZu-.js +0 -1
- package/dist/assets/dql-notebook/assets/LineageDrawer-BcIipIc3.js +0 -1
- package/dist/assets/dql-notebook/assets/MiniLineageGraph-vH_MY_Ju.js +0 -1
- package/dist/assets/dql-notebook/assets/UnifiedAgentRunPanel--oxmjlgr.js +0 -88
- package/dist/assets/dql-notebook/assets/dagre.esm-C7pppQ1a.js +0 -23
- package/dist/assets/dql-notebook/assets/index-B3shyZsg.css +0 -1
- /package/dist/assets/dql-notebook/assets/{dagre-BZV40eAE.css → style-BZV40eAE.css} +0 -0
|
@@ -1,120 +1,115 @@
|
|
|
1
|
-
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/UnifiedAgentRunPanel
|
|
2
|
-
import{c as
|
|
1
|
+
const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/UnifiedAgentRunPanel-BjsTE6yf.js","assets/index-D3wnucQC.js","assets/react-CRB3T2We.js","assets/index-B_kaoARS.css","assets/usePersistedAgentThreadId-DpQXOEDw.js","assets/TrustBadge-D5CGp0cu.js","assets/AiBuildResult-xKtGthWv.js","assets/user-round-DukNupB_.js","assets/triangle-alert-BPHvH1wA.js","assets/rotate-ccw-B2p953Zh.js","assets/wrench-1m0_kcza.js","assets/x-fp82BETM.js","assets/list-tree-DapsIuQB.js","assets/minimize-2-BlVoipnT.js","assets/arrow-right-C7G3M_S8.js"])))=>i.map(i=>d[i]);
|
|
2
|
+
import{c as Je,r as p,a as D,j as e,b1 as At,P as xt,l as Qe,b2 as Zn,T as ir,B as yr,aJ as Zt,F as mt,b3 as _a,t as Ht,S as ht,d as dr,ar as Dn,as as jt,b4 as Vi,g as Pt,b5 as oa,u as Ki,G as Qi,L as Un,f as es,q as ts,p as rs,ax as as,b6 as is,h as ns,i as ss,k as Gi,b7 as os,a6 as ls,V as ds,a7 as ua,b8 as Gr,b9 as Yi,aZ as ps}from"./index-D3wnucQC.js";import{A as Ea,a as ya,b as cs}from"./AiSidePanel-CE_L04dK.js";import{u as Ba,E as ta,T as Xi,b as Ji,S as us,C as Zi,f as xs,M as gs,c as fs,i as ms,e as hs,P as Di}from"./usePersistedAgentThreadId-DpQXOEDw.js";import{A as _r}from"./arrow-left-CF6wxXU5.js";import{B as nr,P as Jt}from"./play-CNuRuaAs.js";import{U as bs}from"./upload-DIqK0KE1.js";import{X as $t}from"./x-fp82BETM.js";import{B as Ui}from"./book-open-text-DDBO8G7L.js";import{W as ar}from"./workflow-bOT-NqdO.js";import{T as Er}from"./triangle-alert-BPHvH1wA.js";import{c as vs,r as en}from"./semantic-fields-2fWgkTJc.js";import{u as ys}from"./answer-to-notebook-tACdCsTV.js";import{W as tn}from"./wand-sparkles-CAwLX0b9.js";import{G as ws}from"./grip-vertical-DVu7ok6x.js";import{W as wa}from"./wrench-1m0_kcza.js";import{S as rn}from"./sliders-horizontal-DwRTu1w4.js";import{A as qs}from"./arrow-right-C7G3M_S8.js";import{S as js}from"./star-Cbaj4F3i.js";import"./react-CRB3T2We.js";import"./minimize-2-BlVoipnT.js";import"./TrustBadge-D5CGp0cu.js";import"./AiBuildResult-xKtGthWv.js";import"./user-round-DukNupB_.js";import"./rotate-ccw-B2p953Zh.js";/**
|
|
3
3
|
* @license lucide-react v0.563.0 - ISC
|
|
4
4
|
*
|
|
5
5
|
* This source code is licensed under the ISC license.
|
|
6
6
|
* See the LICENSE file in the root directory of this source tree.
|
|
7
|
-
*/const
|
|
7
|
+
*/const ks=[["path",{d:"M8 2v4",key:"1cmpym"}],["path",{d:"M16 2v4",key:"4m81vk"}],["rect",{width:"18",height:"18",x:"3",y:"4",rx:"2",key:"1hopcy"}],["path",{d:"M3 10h18",key:"8toen8"}],["path",{d:"M8 14h.01",key:"6423bh"}],["path",{d:"M12 14h.01",key:"1etili"}],["path",{d:"M16 14h.01",key:"1gbofw"}],["path",{d:"M8 18h.01",key:"lrp35t"}],["path",{d:"M12 18h.01",key:"mhygvu"}],["path",{d:"M16 18h.01",key:"kzsmim"}]],Ss=Je("calendar-days",ks);/**
|
|
8
8
|
* @license lucide-react v0.563.0 - ISC
|
|
9
9
|
*
|
|
10
10
|
* This source code is licensed under the ISC license.
|
|
11
11
|
* See the LICENSE file in the root directory of this source tree.
|
|
12
|
-
*/const
|
|
12
|
+
*/const zs=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M7 11.207a.5.5 0 0 1 .146-.353l2-2a.5.5 0 0 1 .708 0l3.292 3.292a.5.5 0 0 0 .708 0l4.292-4.292a.5.5 0 0 1 .854.353V16a1 1 0 0 1-1 1H8a1 1 0 0 1-1-1z",key:"q0gr47"}]],Cs=Je("chart-area",zs);/**
|
|
13
13
|
* @license lucide-react v0.563.0 - ISC
|
|
14
14
|
*
|
|
15
15
|
* This source code is licensed under the ISC license.
|
|
16
16
|
* See the LICENSE file in the root directory of this source tree.
|
|
17
|
-
*/const
|
|
17
|
+
*/const As=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"15",y:"5",width:"4",height:"12",rx:"1",key:"q8uenq"}],["rect",{x:"7",y:"8",width:"4",height:"9",rx:"1",key:"sr5ea"}]],Is=Je("chart-column-big",As);/**
|
|
18
18
|
* @license lucide-react v0.563.0 - ISC
|
|
19
19
|
*
|
|
20
20
|
* This source code is licensed under the ISC license.
|
|
21
21
|
* See the LICENSE file in the root directory of this source tree.
|
|
22
|
-
*/const
|
|
22
|
+
*/const Ns=[["path",{d:"M13 17V9",key:"1fwyjl"}],["path",{d:"M18 17V5",key:"sfb6ij"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M8 17v-3",key:"17ska0"}]],Rs=Je("chart-column-increasing",Ns);/**
|
|
23
23
|
* @license lucide-react v0.563.0 - ISC
|
|
24
24
|
*
|
|
25
25
|
* This source code is licensed under the ISC license.
|
|
26
26
|
* See the LICENSE file in the root directory of this source tree.
|
|
27
|
-
*/const
|
|
27
|
+
*/const Ts=[["path",{d:"M11 13H7",key:"t0o9gq"}],["path",{d:"M19 9h-4",key:"rera1j"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["rect",{x:"15",y:"5",width:"4",height:"12",rx:"1",key:"q8uenq"}],["rect",{x:"7",y:"8",width:"4",height:"9",rx:"1",key:"sr5ea"}]],Ps=Je("chart-column-stacked",Ts);/**
|
|
28
28
|
* @license lucide-react v0.563.0 - ISC
|
|
29
29
|
*
|
|
30
30
|
* This source code is licensed under the ISC license.
|
|
31
31
|
* See the LICENSE file in the root directory of this source tree.
|
|
32
|
-
*/const
|
|
32
|
+
*/const $s=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"M18 17V9",key:"2bz60n"}],["path",{d:"M13 17V5",key:"1frdt8"}],["path",{d:"M8 17v-3",key:"17ska0"}]],an=Je("chart-column",$s);/**
|
|
33
33
|
* @license lucide-react v0.563.0 - ISC
|
|
34
34
|
*
|
|
35
35
|
* This source code is licensed under the ISC license.
|
|
36
36
|
* See the LICENSE file in the root directory of this source tree.
|
|
37
|
-
*/const _s=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"
|
|
37
|
+
*/const _s=[["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}],["path",{d:"m19 9-5 5-4-4-3 3",key:"2osh9i"}]],nn=Je("chart-line",_s);/**
|
|
38
38
|
* @license lucide-react v0.563.0 - ISC
|
|
39
39
|
*
|
|
40
40
|
* This source code is licensed under the ISC license.
|
|
41
41
|
* See the LICENSE file in the root directory of this source tree.
|
|
42
|
-
*/const Es=[["path",{d:"
|
|
42
|
+
*/const Es=[["path",{d:"M21 12c.552 0 1.005-.449.95-.998a10 10 0 0 0-8.953-8.951c-.55-.055-.998.398-.998.95v8a1 1 0 0 0 1 1z",key:"pzmjnu"}],["path",{d:"M21.21 15.89A10 10 0 1 1 8 2.83",key:"k2fpak"}]],Bs=Je("chart-pie",Es);/**
|
|
43
43
|
* @license lucide-react v0.563.0 - ISC
|
|
44
44
|
*
|
|
45
45
|
* This source code is licensed under the ISC license.
|
|
46
46
|
* See the LICENSE file in the root directory of this source tree.
|
|
47
|
-
*/const
|
|
47
|
+
*/const Ms=[["circle",{cx:"7.5",cy:"7.5",r:".5",fill:"currentColor",key:"kqv944"}],["circle",{cx:"18.5",cy:"5.5",r:".5",fill:"currentColor",key:"lysivs"}],["circle",{cx:"11.5",cy:"11.5",r:".5",fill:"currentColor",key:"byv1b8"}],["circle",{cx:"7.5",cy:"16.5",r:".5",fill:"currentColor",key:"nkw3mc"}],["circle",{cx:"17.5",cy:"14.5",r:".5",fill:"currentColor",key:"1gjh6j"}],["path",{d:"M3 3v16a2 2 0 0 0 2 2h16",key:"c24i48"}]],Ls=Je("chart-scatter",Ms);/**
|
|
48
48
|
* @license lucide-react v0.563.0 - ISC
|
|
49
49
|
*
|
|
50
50
|
* This source code is licensed under the ISC license.
|
|
51
51
|
* See the LICENSE file in the root directory of this source tree.
|
|
52
|
-
*/const
|
|
52
|
+
*/const Fs=[["path",{d:"M20.5 10a2.5 2.5 0 0 1-2.4-3H18a2.95 2.95 0 0 1-2.6-4.4 10 10 0 1 0 6.3 7.1c-.3.2-.8.3-1.2.3",key:"19sr3x"}],["circle",{cx:"12",cy:"12",r:"3",key:"1v7zrd"}]],Os=Je("donut",Fs);/**
|
|
53
53
|
* @license lucide-react v0.563.0 - ISC
|
|
54
54
|
*
|
|
55
55
|
* This source code is licensed under the ISC license.
|
|
56
56
|
* See the LICENSE file in the root directory of this source tree.
|
|
57
|
-
*/const
|
|
57
|
+
*/const Ws=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M3 9h18",key:"1pudct"}],["path",{d:"M3 15h18",key:"5xshup"}],["path",{d:"M9 3v18",key:"fh3hqa"}],["path",{d:"M15 3v18",key:"14nvp0"}]],Hs=Je("grid-3x3",Ws);/**
|
|
58
58
|
* @license lucide-react v0.563.0 - ISC
|
|
59
59
|
*
|
|
60
60
|
* This source code is licensed under the ISC license.
|
|
61
61
|
* See the LICENSE file in the root directory of this source tree.
|
|
62
|
-
*/const
|
|
62
|
+
*/const Vs=[["line",{x1:"4",x2:"20",y1:"9",y2:"9",key:"4lhtct"}],["line",{x1:"4",x2:"20",y1:"15",y2:"15",key:"vyu0kd"}],["line",{x1:"10",x2:"8",y1:"3",y2:"21",key:"1ggp8o"}],["line",{x1:"16",x2:"14",y1:"3",y2:"21",key:"weycgp"}]],sn=Je("hash",Vs);/**
|
|
63
63
|
* @license lucide-react v0.563.0 - ISC
|
|
64
64
|
*
|
|
65
65
|
* This source code is licensed under the ISC license.
|
|
66
66
|
* See the LICENSE file in the root directory of this source tree.
|
|
67
|
-
*/const Ks=[["
|
|
67
|
+
*/const Ks=[["path",{d:"M6 12h12",key:"8npq4p"}],["path",{d:"M6 20V4",key:"1w1bmo"}],["path",{d:"M18 20V4",key:"o2hl4u"}]],Qs=Je("heading",Ks);/**
|
|
68
68
|
* @license lucide-react v0.563.0 - ISC
|
|
69
69
|
*
|
|
70
70
|
* This source code is licensed under the ISC license.
|
|
71
71
|
* See the LICENSE file in the root directory of this source tree.
|
|
72
|
-
*/const
|
|
72
|
+
*/const Gs=[["path",{d:"M20 10c0 4.993-5.539 10.193-7.399 11.799a1 1 0 0 1-1.202 0C9.539 20.193 4 14.993 4 10a8 8 0 0 1 16 0",key:"1r0f0z"}],["circle",{cx:"12",cy:"10",r:"3",key:"ilqhr7"}]],Ys=Je("map-pin",Gs);/**
|
|
73
73
|
* @license lucide-react v0.563.0 - ISC
|
|
74
74
|
*
|
|
75
75
|
* This source code is licensed under the ISC license.
|
|
76
76
|
* See the LICENSE file in the root directory of this source tree.
|
|
77
|
-
*/const
|
|
77
|
+
*/const Xs=[["rect",{width:"18",height:"18",x:"3",y:"3",rx:"2",key:"afitv7"}],["path",{d:"M15 3v18",key:"14nvp0"}]],Js=Je("panel-right",Xs);/**
|
|
78
78
|
* @license lucide-react v0.563.0 - ISC
|
|
79
79
|
*
|
|
80
80
|
* This source code is licensed under the ISC license.
|
|
81
81
|
* See the LICENSE file in the root directory of this source tree.
|
|
82
|
-
*/const
|
|
82
|
+
*/const Zs=[["path",{d:"m15 14 5-5-5-5",key:"12vg1m"}],["path",{d:"M20 9H9.5A5.5 5.5 0 0 0 4 14.5A5.5 5.5 0 0 0 9.5 20H13",key:"6uklza"}]],Ds=Je("redo-2",Zs);/**
|
|
83
83
|
* @license lucide-react v0.563.0 - ISC
|
|
84
84
|
*
|
|
85
85
|
* This source code is licensed under the ISC license.
|
|
86
86
|
* See the LICENSE file in the root directory of this source tree.
|
|
87
|
-
*/const
|
|
87
|
+
*/const Us=[["circle",{cx:"18",cy:"5",r:"3",key:"gq8acd"}],["circle",{cx:"6",cy:"12",r:"3",key:"w7nqdw"}],["circle",{cx:"18",cy:"19",r:"3",key:"1xt0gg"}],["line",{x1:"8.59",x2:"15.42",y1:"13.51",y2:"17.49",key:"47mynk"}],["line",{x1:"15.41",x2:"8.59",y1:"6.51",y2:"10.49",key:"1n3mei"}]],eo=Je("share-2",Us);/**
|
|
88
88
|
* @license lucide-react v0.563.0 - ISC
|
|
89
89
|
*
|
|
90
90
|
* This source code is licensed under the ISC license.
|
|
91
91
|
* See the LICENSE file in the root directory of this source tree.
|
|
92
|
-
*/const
|
|
92
|
+
*/const to=[["rect",{width:"14",height:"20",x:"5",y:"2",rx:"2",ry:"2",key:"1yt0o3"}],["path",{d:"M12 18h.01",key:"mhygvu"}]],ro=Je("smartphone",to);/**
|
|
93
93
|
* @license lucide-react v0.563.0 - ISC
|
|
94
94
|
*
|
|
95
95
|
* This source code is licensed under the ISC license.
|
|
96
96
|
* See the LICENSE file in the root directory of this source tree.
|
|
97
|
-
*/const
|
|
97
|
+
*/const ao=[["path",{d:"M9 3H5a2 2 0 0 0-2 2v4m6-6h10a2 2 0 0 1 2 2v4M9 3v18m0 0h10a2 2 0 0 0 2-2V9M9 21H5a2 2 0 0 1-2-2V9m0 0h18",key:"gugj83"}]],on=Je("table-2",ao);/**
|
|
98
98
|
* @license lucide-react v0.563.0 - ISC
|
|
99
99
|
*
|
|
100
100
|
* This source code is licensed under the ISC license.
|
|
101
101
|
* See the LICENSE file in the root directory of this source tree.
|
|
102
|
-
*/const io=[["path",{d:"
|
|
102
|
+
*/const io=[["path",{d:"M12 4v16",key:"1654pz"}],["path",{d:"M4 7V5a1 1 0 0 1 1-1h14a1 1 0 0 1 1 1v2",key:"e0r10z"}],["path",{d:"M9 20h6",key:"s66wpe"}]],no=Je("type",io);/**
|
|
103
103
|
* @license lucide-react v0.563.0 - ISC
|
|
104
104
|
*
|
|
105
105
|
* This source code is licensed under the ISC license.
|
|
106
106
|
* See the LICENSE file in the root directory of this source tree.
|
|
107
|
-
*/const
|
|
107
|
+
*/const so=[["path",{d:"M9 14 4 9l5-5",key:"102s5s"}],["path",{d:"M4 9h10.5a5.5 5.5 0 0 1 5.5 5.5a5.5 5.5 0 0 1-5.5 5.5H11",key:"f3b9sd"}]],oo=Je("undo-2",so);/**
|
|
108
108
|
* @license lucide-react v0.563.0 - ISC
|
|
109
109
|
*
|
|
110
110
|
* This source code is licensed under the ISC license.
|
|
111
111
|
* See the LICENSE file in the root directory of this source tree.
|
|
112
|
-
*/const
|
|
113
|
-
* @license lucide-react v0.563.0 - ISC
|
|
114
|
-
*
|
|
115
|
-
* This source code is licensed under the ISC license.
|
|
116
|
-
* See the LICENSE file in the root directory of this source tree.
|
|
117
|
-
*/const po=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],co=Ge("users",po),ra=`
|
|
112
|
+
*/const lo=[["path",{d:"M16 21v-2a4 4 0 0 0-4-4H6a4 4 0 0 0-4 4v2",key:"1yyitq"}],["path",{d:"M16 3.128a4 4 0 0 1 0 7.744",key:"16gr8j"}],["path",{d:"M22 21v-2a4 4 0 0 0-3-3.87",key:"kshegd"}],["circle",{cx:"9",cy:"7",r:"4",key:"nufk8"}]],po=Je("users",lo),ra=`
|
|
118
113
|
.dql-studio-v2, .dql-studio-v2-launch, .dql-app-studio-home, .dql-studio-v2-loading { width:100%; min-height:0; color:var(--text-primary); font-family:var(--font-sans, Inter, ui-sans-serif, system-ui); }
|
|
119
114
|
.dql-studio-v2, .dql-studio-v2-launch, .dql-studio-v2-loading { height:100%; background:var(--bg-canvas); }
|
|
120
115
|
.dql-studio-v2 button, .dql-studio-v2 input, .dql-studio-v2 textarea, .dql-studio-v2 select, .dql-studio-v2-launch button, .dql-studio-v2-launch input, .dql-studio-v2-launch textarea, .dql-app-studio-home button, .dql-app-studio-home input, .dql-app-studio-home textarea, .dql-studio-v2-loading button { font:inherit; color:inherit; }
|
|
@@ -751,13 +746,13 @@ import{c as Ge,r as p,a as D,j as e,b0 as At,P as xt,l as Qe,b1 as Zn,T as ir,B
|
|
|
751
746
|
.studio-readiness-card > footer { display:grid; grid-template-columns:1fr 1fr; }
|
|
752
747
|
}
|
|
753
748
|
@media (prefers-reduced-motion:reduce) { .studio-canvas-frame, .policy-toggle i:after, .studio-review-toggle i:after, .dql-studio-v2-loading .loading-mark, .preview-state.loading .preview-loading-mark { transition:none; animation:none; } }
|
|
754
|
-
`,qa=["Understanding your decision","Finding certified and draft blocks","Checking trust and capabilities","Preparing source review"];function uo(t){return(Math.max(0,t)+1)%qa.length}function Ma(t){return Array.from(new Set(t.map(r=>r.trim()).filter(Boolean)))}function ri(t,r){return{kind:"propose",prompt:t,requiredSourceIds:Ma(r)}}function xo(t,r){return{kind:"revise",...t?{answers:{...t}}:{},requiredSourceIds:Ma(r)}}function go(t,r,a){return{kind:"enable_review_and_propose",prompt:t,sourceId:r,requiredSourceIds:Ma(a)}}function ln(t){var r;return t.status==="adding"?"Adding…":t.status==="added"?`Added to ${((r=t.pageTitle)==null?void 0:r.trim())||"Overview"}`:t.status==="error"?`Try add ${t.view}`:t.reviewRequired?`Enable review lane & add ${t.view}`:t.alreadyUsed?`Add another ${t.view}`:`Add ${t.view}`}function ai(t,r){return Array.from(new Set([...t,r??""].map(a=>a.trim()).filter(Boolean)))}function fo(t,r){const a=t===void 0?r?[r]:void 0:t;if(a!==void 0)return Array.from(new Set(a.map(i=>i.trim()).filter(Boolean)))}function mo(t){return t.reviewRequired&&t.sourcePolicy==="governed_only"?"enable_review_and_replan":t.alreadyProposed?"select_existing":"replan"}function ho(t){let r;const a=new Map,i=new Map,s=new Map,n=t.operations.filter(l=>l.type==="upsert_source").map(l=>l.source),o=l=>{var y,u,w,q,C,k;const d=l.block?"blockId"in l.block?l.block.blockId:l.block.ref:void 0,x=((u=(y=l.semantic)==null?void 0:y.qualifiedMetricIds)==null?void 0:u.join(", "))||((w=l.semantic)==null?void 0:w.id),b=(q=l.draftAnalysis)==null?void 0:q.ref,m=vo(l,n),f=((C=l.display)==null?void 0:C.rationale)||((k=l.sourceEvidence)==null?void 0:k.map(M=>M.reason).filter(Boolean).join(" "));i.set(l.i,{id:l.i,title:l.title||xa(l.i),visualization:xa(l.viz.type),source:d||x||b||(l.text?"Page content":"Governed source"),...m?{sourceId:m}:{},...f?{rationale:f}:{}})};for(const l of t.operations)l.type==="set_frame"?r=l.frame:l.type==="upsert_source"?s.set(l.source.id,{id:l.source.id,label:xa(l.source.qualifiedIdentity||l.source.sourceRef),sourceRef:l.source.sourceRef,kind:l.source.kind,trustState:l.source.trustState,reviewStatus:l.source.reviewStatus,componentIds:[]}):l.type==="upsert_page"?(a.set(l.page.id,{id:l.page.id,title:l.page.metadata.title}),l.page.layout.items.forEach(o)):l.type==="add_tile"&&o(l.tile);for(const l of i.values()){if(!l.sourceId)continue;const d=s.get(l.sourceId);d==null||d.componentIds.push(l.id),d&&!d.rationale&&l.rationale&&(d.rationale=l.rationale)}return{frame:r,pages:Array.from(a.values()),components:Array.from(i.values()),sources:Array.from(s.values())}}function bo(t,r,a){const i=new Set(t.sources.flatMap(n=>[n.sourceRef,n.label]).map(n=>ii(n))),s=a.trim().toLowerCase();return r.filter(n=>[n.id,n.name,n.path].some(o=>i.has(ii(o)))?!1:s?[n.name,n.domain,n.description,n.owner??"",...n.tags].join(" ").toLowerCase().includes(s):!0)}function vo(t,r){var a,i,s;if(t.sourceId)return t.sourceId;if(t.block){const n="blockId"in t.block?t.block.blockId:t.block.ref;return((a=r.find(o=>["block","certified_block","review_block"].includes(o.kind)&&o.sourceRef===n))==null?void 0:a.id)??`block:${n}`}if(t.semantic)return((i=r.find(n=>{var o;return["governed_semantic","semantic_query"].includes(n.kind)&&n.sourceRef===((o=t.semantic)==null?void 0:o.id)}))==null?void 0:i.id)??`semantic:${t.semantic.id}`;if(t.draftAnalysis)return(s=r.find(n=>{var o;return["review_block","review_dql","exploratory_sql"].includes(n.kind)&&n.sourceRef===((o=t.draftAnalysis)==null?void 0:o.ref)}))==null?void 0:s.id}function xa(t){return t.replace(/[_-]+/g," ").replace(/\b\w/g,r=>r.toUpperCase()).trim()}function ii(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"")}function dn(t){return/date|time|month|week|quarter|year|created|updated|ordered|(_at|_on)$/i.test(t)?"daterange":/count|amount|limit|top_?n|score/i.test(t)?"number":"select"}function yo(t,r,a={},i=[]){var n,o;const s=new Set;for(const l of t){for(const d of l.filters??[]){const x=((n=d.field)==null?void 0:n.name)??d.bindsTo??d.id;x&&s.add(x)}for(const d of pn(l)){for(const x of cn(d,r,i))s.add(x);for(const x of((o=a[l.id])==null?void 0:o[d.i])??[])s.add(x.column);for(const x of d.filterBindings??[])x.binding&&x.capability!=="unsupported"&&s.add(x.binding)}}return[...s].map(l=>{const d=Rr(t,r,l,a,i).filter(x=>x.supported);return{id:l,sourceNames:[...new Set(d.map(x=>x.sourceName))].sort(),affectedTileCount:d.length,pageCount:new Set(d.map(x=>x.pageId)).size}}).filter(l=>l.affectedTileCount>0).sort((l,d)=>l.id.localeCompare(d.id))}function Rr(t,r,a,i={},s=[]){return t.flatMap(n=>pn(n).map(o=>{var f;const l=cn(o,r,s),d=(((f=i[n.id])==null?void 0:f[o.i])??[]).find(y=>wo(y.column,a)),x=(o.filterBindings??[]).find(y=>y.filter===a||y.binding===a),b=l.includes(a)||!!d||(x==null?void 0:x.binding)===a&&x.capability!=="unsupported",m=jo(o,r,s);return{key:qo(n.id,o.i),pageId:n.id,pageTitle:n.metadata.title,tileId:o.i,tileTitle:o.title||o.i,sourceName:m,supported:b,...b?{binding:(d==null?void 0:d.column)??a,mode:o.semantic?"semantic":(x==null?void 0:x.mode)??"predicate"}:{reason:`${a.replace(/_/g," ")} is not exposed by ${m}.`}}}))}function wo(t,r){const a=i=>{const s=i.trim().toLowerCase().replace(/["`\[\]]/g,"").split(".");return(s[s.length-1]??"").replace(/[^a-z0-9]/g,"")};return a(t)===a(r)}function qo(t,r){return`${t}:${r}`}function pn(t){return t.layout.items.filter(r=>!!(r.block||r.semantic||r.draftAnalysis))}function cn(t,r,a){const i=t.sourceId?a.find(o=>o.id===t.sourceId):void 0;if(i!=null&&i.capabilities)return[...new Set([...i.capabilities.filters,...i.capabilities.dimensions])];const s=t.block?"blockId"in t.block?t.block.blockId:t.block.ref:null,n=s?r.find(o=>o.id===s||o.name===s):null;return n?[...new Set([...n.filterIds??[],...n.dimensionIds??[]])]:t.semantic?t.semantic.dimensions??[]:t.draftAnalysis?[]:(t.filterBindings??[]).filter(o=>o.capability!=="unsupported"&&!!o.binding).map(o=>o.binding)}function jo(t,r,a){const i=t.sourceId?a.find(o=>o.id===t.sourceId):void 0;if(i)return i.qualifiedIdentity??i.sourceRef;const s=t.block?"blockId"in t.block?t.block.blockId:t.block.ref:null,n=s?r.find(o=>o.id===s||o.name===s):null;return n?n.name:t.semantic?t.semantic.id:t.draftAnalysis?t.draftAnalysis.ref:t.title||t.i}function un(t){const r=/Required App question is unresolved|Review task is still open|Run a current settled preview|requires snapshot-bound semantic approval|is review-required and cannot be published|references app-scoped exploratory DQL|Resolve required Build Frame clarifications/i,a=t.filter(i=>!r.test(i)).map(i=>{const s=i.match(/^[^/]+\/[^ ]+ does not have a preflighted binding for filter (.+)\.$/i);if(s){const o=s[1],l=t.filter(d=>d.endsWith(`binding for filter ${o}.`)).length;return{id:`filters:${o.toLowerCase()}`,title:`Limit ${o} to compatible components`,detail:`${o} is applied to ${l} ${l===1?"component that cannot":"components that cannot"} use it. Open Filters, edit ${o}, and keep only the compatible components selected.`,action:"filters"}}if(/filter|binding/i.test(i))return{id:"filters",title:"Finish filter wiring",detail:i,action:"filters"};const n=i.match(/^Source (.+?) changed after selection\.$/i);if(n){const o=ko(n[1]);return{id:`sources:${n[1]}`,title:`Review ${o}`,detail:`${o} changed since it was selected. Accept the current certified version; DQL will then request a fresh preview.`,action:"refresh_sources"}}return/does not resolve to (?:a current |a )?certified block|no longer resolves to a certified block/i.test(i)?{id:`unavailable:${i}`,title:"Replace or remove this source",detail:i,action:"sources"}:/changed after selection|certified block|source/i.test(i)?{id:"sources",title:"Review changed sources",detail:i,action:"sources"}:/preview|settled run|receipt|runtime/i.test(i)?{id:"preview",title:"Refresh the settled preview",detail:"The saved preview no longer matches the current App data contract.",action:"preview"}:{id:`validation:${i}`,title:"Complete governed validation",detail:i,action:"sources"}});return Array.from(new Map(a.map(i=>[i.id,i])).values())}function ko(t){return t.replace(/[_-]+/g," ").replace(/\b\w/g,r=>r.toUpperCase())}function La(t){return t.requirements.filter(r=>{if(!r.required||!So(t,r))return!1;const a=t.coverage.find(i=>i.requirementId===r.id);return(a==null?void 0:a.status)!=="covered"})}function So(t,r){return!(t.authoringMode==="manual"&&t.frame.metrics.length===0&&r.measures.length===0)}function la(t){const r=new Set(t.pages.map(s=>s.id)),a=new Set(t.pages.flatMap(s=>s.layout.items.map(n=>n.i))),i=new Set(t.sources.map(s=>s.id));return t.reviewTasks.filter(s=>s.status!=="open"?!1:!!(s.sourceId&&i.has(s.sourceId)||s.tileId&&a.has(s.tileId)||s.pageId&&r.has(s.pageId)))}function Fa(t){const r=t.previewReceipts??(t.previewReceipt?[t.previewReceipt]:[]);return t.pages.filter(a=>a.layout.items.some(s=>!s.text&&!s.aiPin)?!r.some(s=>s.pageId===a.id&&s.revision===t.revision):!1)}function da(t){return t.sources.filter(r=>r.kind==="governed_semantic"||r.kind==="semantic_query"?r.reviewStatus!=="approved"||!r.snapshotId||!r.receiptId:r.kind==="block"?r.lifecycle!=="certified"||r.trustState!=="certified"||r.reviewStatus==="required":r.kind==="certified_block"?r.lifecycle!==void 0&&r.lifecycle!=="certified"||r.trustState!=="certified"||r.reviewStatus==="required":r.kind==="review_block"||r.kind==="review_dql"||r.kind==="exploratory_sql")}function xn(t,r=[]){const a=(t.frame.clarificationQuestions??[]).filter(i=>i.required&&!i.answerId);return La(t).length+a.length+la(t).length+Fa(t).length+da(t).length+un(r).length}function zo(t){const r=(t.frame.clarificationQuestions??[]).filter(l=>l.required&&!l.answerId),a=La(t),i=la(t),s=Fa(t),n=da(t),o=[];if(r.length||a.length){const l=r.length+a.length;o.push({id:"questions",title:"Confirm the App questions",detail:`${l} ${l===1?"question needs":"questions need"} an answer, governed coverage, or removal from this publish scope.`,count:l})}return i.length&&o.push({id:"review",title:"Complete scoped review",detail:`${i.length} review ${i.length===1?"task is":"tasks are"} attached to content still in this App.`,count:i.length}),s.length&&o.push({id:"preview",title:"Run a current preview",detail:`${s.length} data ${s.length===1?"page needs":"pages need"} a settled result before publication.`,count:s.length}),n.length&&o.push({id:"sources",title:"Finish source review",detail:`${n.length} ${n.length===1?"source needs":"sources need"} approval, replacement, or removal.`,count:n.length}),o}const Co=p.lazy(()=>oa(()=>import("./UnifiedAgentRunPanel--oxmjlgr.js").then(t=>t.c),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14])).then(t=>({default:t.UnifiedAgentRunPanel}))),ja=[{id:"executive_brief",title:"Executive Brief",description:"Editorial summary, KPI band, decision evidence, and appendix."},{id:"operational_dashboard",title:"Operational Dashboard",description:"Filters, KPIs, trends, drivers, and operating detail."},{id:"investigation",title:"Investigation",description:"Question, findings, comparisons, caveats, and evidence."},{id:"blank",title:"Blank canvas",description:"Start with one clean responsive page."}];function Ao({config:t,busy:r=!1,error:a,onChange:i,onSubmit:s}){var o;const n=t.mode==="ai"?!!t.prompt.trim():!!t.name.trim();return e.jsxs("section",{className:"dql-app-studio-home","aria-labelledby":"app-studio-home-title",children:[e.jsx("style",{children:ra}),e.jsxs("div",{className:"dql-studio-v2-intro",children:[e.jsxs("span",{className:"eyebrow",children:[e.jsx(ht,{size:14})," DQL App Studio 2.0"]}),e.jsxs("h1",{id:"app-studio-home-title",children:["Start with the decision.",e.jsx("br",{}),"Shape the experience together."]}),e.jsx("p",{children:"AI and manual authoring use one private draft, one responsive canvas, and one governed path to Project publication."})]}),e.jsxs("div",{className:"dql-studio-v2-start-card",children:[e.jsxs("div",{className:"mode-switch",role:"tablist","aria-label":"Authoring mode",children:[e.jsxs("button",{type:"button",role:"tab","aria-selected":t.mode==="ai",className:t.mode==="ai"?"on":"",onClick:()=>i({mode:"ai",template:t.template==="blank"?"operational_dashboard":t.template}),children:[e.jsx(ht,{size:16})," Describe with AI"]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":t.mode==="manual",className:t.mode==="manual"?"on":"",onClick:()=>i({mode:"manual",template:"blank",name:t.name||"Untitled Analytics App"}),children:[e.jsx(At,{size:16})," Start manually"]})]}),e.jsxs("label",{className:"primary-field",children:[e.jsx("span",{children:t.mode==="ai"?"What decision should this App support?":"What should this App be called?"}),t.mode==="ai"?e.jsx("textarea",{value:t.prompt,onChange:l=>i({prompt:l.target.value}),placeholder:"Build a weekly revenue health App for finance leaders with trends, drivers, and customer detail.",rows:4}):e.jsx("input",{value:t.name,onChange:l=>i({name:l.target.value}),placeholder:"Revenue Operations"})]}),t.mode==="ai"?e.jsxs("div",{className:"ai-launch-explainer",children:[e.jsx("span",{children:e.jsx(ht,{size:16})}),e.jsxs("div",{children:[e.jsx("strong",{children:"AI selects governed data and creates an editable first draft"}),e.jsx("small",{children:"Next, review the actual blocks, semantic sources, components, and gaps before applying anything."})]})]}):null,e.jsxs("details",{className:"launch-options",open:t.mode==="manual",children:[e.jsxs("summary",{children:[e.jsx("span",{children:"Starting layout"}),e.jsx("strong",{children:((o=ja.find(l=>l.id===t.template))==null?void 0:o.title)??"Operational Dashboard"}),e.jsx(dr,{size:15})]}),e.jsx("div",{className:"template-grid",children:ja.map(l=>e.jsxs("button",{type:"button",className:t.template===l.id?"on":"",onClick:()=>i({template:l.id}),children:[e.jsx("span",{children:gn(l.id)}),e.jsx("strong",{children:l.title}),e.jsx("small",{children:l.description})]},l.id))})]}),e.jsxs("section",{className:"studio-source-policy-row","aria-label":"App source policy",children:[e.jsxs("header",{children:[e.jsx("span",{className:"policy-mark",children:e.jsx(Qe,{size:17})}),e.jsxs("p",{children:[e.jsx("strong",{children:"Governed sources only"}),e.jsx("small",{children:"Certified blocks and governed semantic sources. Recommended for every App."})]})]}),e.jsxs("label",{className:"studio-review-toggle",children:[e.jsx("input",{type:"checkbox",checked:t.sourcePolicy==="include_review_required",onChange:l=>i({sourcePolicy:l.target.checked?"include_review_required":"governed_only"})}),e.jsx("i",{"aria-hidden":"true"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Also allow review-required analysis"}),e.jsx("small",{children:"Stays local and cannot publish until replaced, promoted, or removed."})]})]})]}),a?e.jsx("div",{className:"studio-error",role:"alert",children:a}):null,e.jsx("button",{type:"button",className:"launch-action",onClick:s,disabled:r||!n,children:r?"Preparing local draft…":t.mode==="ai"?e.jsxs(e.Fragment,{children:[e.jsx(ht,{size:17})," Generate editable App"]}):e.jsxs(e.Fragment,{children:[e.jsx(At,{size:17})," Open blank Studio"]})}),e.jsx("small",{className:"launch-next-step",children:"Private local draft first · review sources and preview results · publish only when ready"})]})]})}function Io({activity:t,label:r,onBack:a,onReturn:i,onRetry:s}){return e.jsxs("section",{className:"dql-studio-v2-loading studio-ai-activity","aria-labelledby":"studio-ai-activity-title","aria-busy":t.status==="running",children:[e.jsx("style",{children:ra}),e.jsx("button",{type:"button",className:"icon",onClick:a,"aria-label":"Back to Apps",children:e.jsx(_r,{size:18})}),e.jsxs("div",{children:[e.jsx("span",{className:"loading-mark",children:e.jsx(ht,{size:20})}),t.status==="running"?e.jsxs(e.Fragment,{children:[e.jsx("strong",{id:"studio-ai-activity-title",children:"Preparing your editable App proposal"}),e.jsx("small",{className:"studio-ai-activity-label",role:"status","aria-live":"polite",children:r}),e.jsx("small",{children:"Sources remain governed or review-required exactly as cataloged. You will review them before the canvas is generated."})]}):e.jsxs(e.Fragment,{children:[e.jsx("strong",{id:"studio-ai-activity-title",children:"The source proposal needs another try"}),e.jsx("small",{role:"alert",children:t.error??"App Studio could not prepare the source proposal."}),e.jsxs("span",{className:"studio-ai-activity-actions",children:[i?e.jsx("button",{type:"button",onClick:i,children:"Back to source review"}):null,e.jsx("button",{type:"button",className:"primary",onClick:s,children:"Try AI proposal again"})]})]})]})]})}function No({initialMode:t,initialPrompt:r,initialName:a="",initialDraftId:i,initialSourcePolicy:s="governed_only",initialTemplate:n,startImmediately:o=!1,baseAppId:l,domain:d,audience:x,themeMode:b,onBack:m,onPublished:f,onDraftDeleted:y}){var ei,ti;const[u,w]=p.useState(null),[q,C]=p.useState(t),[k,M]=p.useState(s),[L,X]=p.useState(n??(t==="manual"?"blank":"operational_dashboard")),[I,O]=p.useState(r),[F,U]=p.useState(a),[_,A]=p.useState("sources"),[te,Q]=p.useState(()=>typeof window>"u"||window.innerWidth>820),[Y,S]=p.useState("auto"),[h,$]=p.useState(1260),[ee,W]=p.useState("overview"),[$e,se]=p.useState(null),[oe,Be]=p.useState(null),[ue,Ae]=p.useState([]),[_e,Ie]=p.useState(""),[xe,Ze]=p.useState(),[it,R]=p.useState(0),[le,ge]=p.useState(!1),[ve,Te]=p.useState(null),[de,Pe]=p.useState(null),[Ye,Xe]=p.useState(new Set),[De,Ee]=p.useState(null),[ze,Z]=p.useState(null),[pe,ye]=p.useState(0),[Ne,We]=p.useState(null),[Me,Ue]=p.useState([]),[we,nt]=p.useState([]),[Le,re]=p.useState(!1),[lt,Ce]=p.useState(null),[bt,ie]=p.useState("Local draft"),[dt,He]=p.useState({}),[et,Re]=p.useState(!1),[gt,H]=p.useState({}),[ke,fe]=p.useState({}),[qe,zt]=p.useState(null),[vt,Vt]=p.useState(!1),[Dt,Ut]=p.useState(!1),[pr,pt]=p.useState(!1),[_t,st]=p.useState([]),[Kt,Qt]=p.useState(!1),[cr,er]=p.useState(!1),[ur,xr]=p.useState(!1),Gt=p.useRef(null),Yt=p.useRef(!1),ct=p.useRef(0),ft=p.useRef(null),Nt=p.useRef(null),N=p.useRef(null),B=Ba(`app-studio:${(u==null?void 0:u.id)??i??"new"}`);p.useEffect(()=>{const c=()=>{const v=window.innerWidth;Q(v>820)};return c(),window.addEventListener("resize",c),()=>window.removeEventListener("resize",c)},[]),p.useEffect(()=>{const c=N.current;if(!c||typeof ResizeObserver>"u")return;const v=new ResizeObserver(([z])=>$(Math.max(0,Math.floor(z.contentRect.width))));return v.observe(c),()=>v.disconnect()},[u]),p.useEffect(()=>{var v;if((ze==null?void 0:ze.status)!=="running"||(ye(0),typeof window>"u"||(v=window.matchMedia)!=null&&v.call(window,"(prefers-reduced-motion: reduce)").matches))return;const c=window.setInterval(()=>{ye(z=>uo(z))},1200);return()=>window.clearInterval(c)},[ze==null?void 0:ze.status,ze==null?void 0:ze.retry.requiredSourceIds.join("|")]),p.useEffect(()=>{let c=!0;return re(!!(l||i)),D.listAppBuilds().then(async v=>{var J,ae;if(!c)return;const z=v.drafts.filter(T=>T.state!=="project_published");if(i){const T=z.find(G=>G.id===i);if(!T)throw new Error("The local App draft is no longer available.");w(T),U(T.name),W(((J=T.pages[0])==null?void 0:J.id)??"overview"),ie("Resumed local draft");return}if(!l)return;const V=z.find(T=>{var G;return((G=T.baseApp)==null?void 0:G.appId)===l})??(await D.createAppBuild({baseAppId:l,goal:I.trim()||"Edit this governed App",audience:x,domain:d,authoringMode:"manual",sourcePolicy:"governed_only",template:"blank"})).draft;c&&(w(V),U(V.name),W(((ae=V.pages[0])==null?void 0:ae.id)??"overview"),ie("Safe local edit draft"))}).catch(v=>{c&&(l||i)&&Ce(Ct(v))}).finally(()=>{c&&re(!1)}),()=>{c=!1}},[l,i]),p.useEffect(()=>{if(!u)return;let c=!0;const v=new AbortController;ge(!0),Te(null);const z=window.setTimeout(()=>{D.listAppSourceCandidates(u.id,{query:_e,limit:50},v.signal).then(P=>{c&&(Ae(P.items),Ze(P.nextCursor),R(P.total))}).catch(P=>{c&&!v.signal.aborted&&(Ae([]),Te(Ct(P)))}).finally(()=>{c&&ge(!1)})},_e?180:0);return()=>{c=!1,v.abort(),window.clearTimeout(z)}},[u==null?void 0:u.id,u==null?void 0:u.sourcePolicy,_e]),p.useEffect(()=>{const c=v=>{var P;const z=v.detail;!(z!=null&&z.draft)||z.draft.id!==(u==null?void 0:u.id)||(ct.current+=1,Re(!1),He({}),fe({}),w(z.draft),U(z.draft.name),W(z.pageId??((P=z.draft.pages[0])==null?void 0:P.id)??"overview"),se(z.tileId??null),Pe(null),ie("Ask result added · loading preview…"))};return window.addEventListener("dql-app-build-updated",c),()=>window.removeEventListener("dql-app-build-updated",c)},[u==null?void 0:u.id]);const g=p.useMemo(()=>(u==null?void 0:u.pages.find(c=>c.id===ee))??(u==null?void 0:u.pages[0])??null,[ee,u]),K=g?dt[g.id]??null:null,me=g?gt[g.id]??{}:{},rt=g?ke[g.id]??{}:{},Ve=Y==="auto"?h<720?"narrow":h<1120?"medium":"wide":Y,yt=p.useMemo(()=>{var z;if(!g)return[];const c=(z=g.layout.responsive)==null?void 0:z[Ve],v=Ve==="wide"?12:Ve==="medium"?6:1;return Tr(si((c==null?void 0:c.items)??g.layout.items,u==null?void 0:u.template),v)},[g,Ve,u==null?void 0:u.template]),Je=(g==null?void 0:g.layout.items.find(c=>c.i===$e))??null,je=ue,wt=p.useMemo(()=>Object.fromEntries(Object.entries(dt).map(([c,v])=>[c,Object.fromEntries(v.tiles.map(z=>[z.tileId,z.filterableColumns??[]]))])),[dt]),gr=p.useMemo(()=>yo((u==null?void 0:u.pages)??[],ue,wt,(u==null?void 0:u.sources)??[]),[ue,u==null?void 0:u.pages,u==null?void 0:u.sources,wt]),ut=p.useMemo(()=>de?ho(de):null,[de]),Mt=p.useMemo(()=>u?xn(u,_t):0,[u,_t]);p.useEffect(()=>{Xe(new Set((de==null?void 0:de.defaultSelectedSourceIds)??(ut==null?void 0:ut.sources.map(c=>c.id))??[]))},[de,ut]),p.useEffect(()=>{if(!ut||oe||ue.length===0)return;const c=new Set(ut.sources.map(z=>z.label.toLowerCase())),v=ue.find(z=>c.has(be(z.name).toLowerCase()))??ue.find(z=>ut.components.some(P=>P.source===z.id||P.source===z.name));v&&Be(v)},[ue,ut,oe]);const Or=async()=>{var c;re(!0),Ce(null);try{const v=await D.createAppBuild({baseAppId:l??void 0,name:F.trim()||void 0,goal:I.trim()||F.trim()||"Create a governed analytical App",audience:x,domain:d,authoringMode:q,sourcePolicy:k,template:L});w(v.draft),U(v.draft.name),W(((c=v.draft.pages[0])==null?void 0:c.id)??"overview"),ie("Saved locally"),He({}),H({}),fe({}),q==="ai"&&(ye(0),Z({status:"running",retry:ri(I,[]),returnToProposal:!1}),await tr(v.draft,I,[],!1))}catch(v){Ce(Ct(v))}finally{re(!1)}},tr=async(c=u,v=I,z,P=!!de)=>{if(!c)return!1;const V=fo(z,oe==null?void 0:oe.id),J=ri(v,V??[]);ye(0),Z({status:"running",retry:J,returnToProposal:P}),re(!0),Ce(null);try{const ae=await D.proposeAppBuildChanges(c.id,{prompt:v.trim()||c.frame.goal,expectedRevision:c.revision,proposalHash:c.proposalHash,selectedBlockIds:V});return Pe(ae.proposal),Z(null),Qt(!1),ie("AI plan ready for review"),!0}catch(ae){const T=Ct(ae);return ie("AI proposal needs attention"),Z({status:"error",retry:J,returnToProposal:P,error:T}),!1}finally{re(!1)}},jr=async(c,v=Array.from(Ye),z=!0)=>{if(!u||!de)return!1;const P=Array.from(new Set(v.filter(Boolean))),V=xo(c,P);z&&(ye(0),Z({status:"running",retry:V,returnToProposal:!0})),re(!0),Ce(null);try{const J=await D.reviseAppBuildProposal(u.id,de.id,{expectedRevision:u.revision,expectedProposalHash:u.proposalHash,answers:c,selectedSourceIds:P});return Pe(J.proposal),z&&Z(null),ie("AI proposal revised on the server"),!0}catch(J){const ae=Ct(J);return z?Z({status:"error",retry:V,returnToProposal:!0,error:ae}):Ce(ae),!1}finally{re(!1)}},pa=async c=>{if(!(!u||!de)){re(!0),Ce(null);try{const v=await D.generateAppBuildGap(u.id,de.id,{expectedRevision:u.revision,expectedProposalHash:u.proposalHash,requirementId:c});Pe(v.proposal),ie("Review-required gap added to the proposal")}catch(v){Ce(Ct(v))}finally{re(!1)}}},kr=async(c,v,z)=>{if(!u||!de||!ut)return;const P=ai(Ye,c),V=mo({alreadyProposed:ut.sources.some(J=>J.id===c),reviewRequired:v,sourcePolicy:u.sourcePolicy});if(z&&Be(z),V==="select_existing"){Xe(J=>new Set([...J,c]));return}Ee(c);try{if(V==="enable_review_and_replan"){const J=go(I,c,P);ye(0),Z({status:"running",retry:J,returnToProposal:!0});const ae=await Fe([{type:"set_source_policy",sourcePolicy:"include_review_required"}]);if(!ae){Z({status:"error",retry:J,returnToProposal:!0,error:"The review lane could not be enabled. Your existing proposal is unchanged."});return}await tr(ae,I,P,!0)}else await jr(void 0,P,!1)}finally{Ee(null)}},ca=c=>{const v=c.retry;if(v.kind==="revise"){jr(v.answers,v.requiredSourceIds,!0);return}if(v.kind==="enable_review_and_propose"){kr(v.sourceId,!0);return}tr(u,v.prompt,v.requiredSourceIds,c.returnToProposal)};p.useEffect(()=>{!o||i||l||u||Yt.current||(Yt.current=!0,Or())},[l,u,i,o]);const Fe=async(c,v=!0)=>{if(!u||c.length===0)return null;re(!0),ie("Saving…"),Ce(null);try{const z=u,P=c.every(Ko),V=await D.patchAppBuild(u.id,u.revision,c,u.proposalHash);return w(V.draft),P||(ct.current+=1,He({}),fe({}),Re(!1)),v&&(Ue(J=>[...J.slice(-29),z]),nt([])),ie("Saved locally"),V.draft}catch(z){return ie("Save failed"),Ce(Ct(z)),null}finally{re(!1)}},Wr=async()=>{if(!(!de||!u)){re(!0),Ce(null),ie("Composing App…");try{const c=u,z=(await D.composeAppBuild(u.id,{mode:"ai",expectedRevision:u.revision,expectedProposalHash:u.proposalHash,proposalId:de.id,selectedSourceIds:Array.from(Ye)})).draft;w(z),Ue(V=>[...V.slice(-29),c]),nt([]),He({}),fe({}),Pe(null),U(z.name);const P=z.pages[0];W((P==null?void 0:P.id)??ee),P&&Cr(P)&&(ie("App generated · loading governed data…"),await Xt(z,P.id))}catch(c){ie("Compose failed"),Ce(Ct(c))}finally{re(!1)}}},Hr=async()=>{if(!u||Me.length===0)return;const c=Me[Me.length-1],v=u;await Fe(ni(v,c),!1)&&(Ue(P=>P.slice(0,-1)),nt(P=>[...P,v]))},Vr=async()=>{if(!u||we.length===0)return;const c=we[we.length-1],v=u;await Fe(ni(v,c),!1)&&(nt(P=>P.slice(0,-1)),Ue(P=>[...P,v]))},Sr=async()=>{var V;if(!u)return;const c=u.pages.length+1,v=`page-${c}`,z={version:2,id:v,metadata:{title:`Page ${c}`,description:"Responsive analytical page",domain:(V=u.pages[0])==null?void 0:V.metadata.domain,audience:u.frame.audience,visibility:"private",lifecycle:"draft"},layout:{kind:"grid",cols:12,rowHeight:80,items:[],responsive:{wide:{kind:"grid",cols:12,rowHeight:80,items:[]},medium:{kind:"grid",cols:6,rowHeight:80,items:[]},narrow:{kind:"grid",cols:1,rowHeight:80,items:[]}}}};await Fe([{type:"upsert_page",page:z}])&&W(v)},j=c=>{Be(c),Ce(null)},E=async()=>{if(!(!u||!xe||le)){ge(!0),Te(null);try{const c=await D.listAppSourceCandidates(u.id,{query:_e,cursor:xe,limit:50});Ae(v=>{const z=new Set(v.map(P=>P.id));return[...v,...c.items.filter(P=>!z.has(P.id))]}),Ze(c.nextCursor),R(c.total)}catch(c){Te(Ct(c))}finally{ge(!1)}}},ce=async(c,v)=>{var Ke;if(!u||!g)return;const z=c==="heading"||c==="text"?null:v===void 0?oe:v;if(c!=="heading"&&c!=="text"&&!z){A("sources"),Q(!0),Ce("Choose a governed source, then use Add to page.");return}if(z){const tt=z.sourceId??z.id,he=Sa(c),ot=((Ke=z.eligibility)==null?void 0:Ke.localPreview)===!1&&u.sourcePolicy==="governed_only";Be(z),Nt.current!==null&&window.clearTimeout(Nt.current),We({sourceId:tt,status:"adding",view:he,pageTitle:g.metadata.title}),re(!0),ie("Composing source…"),Ce(null);try{const Tt=u,Lt=await D.composeAppBuild(u.id,{mode:"manual",expectedRevision:u.revision,expectedProposalHash:u.proposalHash,enableReviewRequired:ot,selections:[{sourceId:tt,pageId:g.id,view:c}]});w(Lt.draft),Ue(Ft=>[...Ft.slice(-29),Tt]),nt([]),se(Lt.tileIds[0]??null),We({sourceId:tt,status:"added",view:he,pageTitle:g.metadata.title}),Nt.current=window.setTimeout(()=>{We(Ft=>(Ft==null?void 0:Ft.sourceId)===tt?null:Ft),Nt.current=null},1800),ie(`${c==="chart"?"Chart":be(c)} added · loading data…`),ct.current+=1,He({}),fe({}),await Xt(Lt.draft,g.id)}catch(Tt){const Lt=Ct(Tt);ie("Compose failed"),We({sourceId:tt,status:"error",view:he,pageTitle:g.metadata.title,message:Lt}),Ce(Lt)}finally{re(!1)}return}if(c!=="heading"&&c!=="text")return;const P=`${c}-${Date.now().toString(36)}`,V=12,J=c==="heading"?1:2,ae=g.layout.items.reduce((tt,he)=>Math.max(tt,he.y+he.h),0),T={i:P,x:0,y:ae,w:V,h:J,title:c==="heading"?"Section heading":"Narrative",text:{markdown:c==="heading"?"## New section":"Add context, interpretation, or guidance."},sourceClass:"narrative",viz:{type:c==="heading"?"heading":"text"},trustState:"draft_ready",reviewStatus:"draft_ready"},G=[{type:"add_tile",pageId:g.id,tile:T}];await Fe(G)&&(se(P),ie(`${be(c)} added`))},Se=async()=>{if(!g||!u)return;const c=Tr(si(g.layout.items,u.template),12);await Fe([{type:"set_layout",pageId:g.id,layout:{...g.layout,items:c}}])&&ie("Page arranged · preview preserved")},Rt=async c=>{if(!u||!g)return;const v=new Set(c.selectedMappingKeys),z=Rr(u.pages,ue,c.fieldId,wt,u.sources);if(z.filter(T=>T.supported&&v.has(T.key)).length===0){Ce("Link this filter to at least one compatible component.");return}const V=[];for(const T of u.pages){const G=z.filter(he=>he.pageId===T.id),ne=G.filter(he=>he.supported&&v.has(he.key)),Ke=ne.length>0&&(c.scope==="app"||T.id===g.id),tt=(T.filters??[]).some(he=>he.id===c.id);Ke?V.push({type:"set_filter",pageId:T.id,filter:{id:c.id,label:c.label.trim()||be(c.fieldId),type:c.type,bindsTo:c.fieldId,field:{name:c.fieldId},required:c.required,multiple:c.type==="multiselect",scope:{page:T.id,tileIds:ne.map(he=>he.tileId)},optionSource:{mode:"distinct_query",field:c.fieldId,limit:100}}}):tt&&V.push({type:"remove_filter",pageId:T.id,filterId:c.id});for(const he of T.layout.items.filter(ot=>ot.block||ot.semantic||ot.draftAnalysis)){const ot=G.find(Ft=>Ft.tileId===he.i),Tt=he.filterBindings??[],Lt=Tt.filter(Ft=>Ft.filter!==c.id);Ke&&(ot!=null&&ot.supported)&&v.has(ot.key)&&Lt.push({filter:c.id,binding:ot.binding??c.fieldId,mode:ot.mode??"predicate",required:c.required,capability:"preflight_required"}),JSON.stringify(Lt)!==JSON.stringify(Tt)&&V.push({type:"update_tile",pageId:T.id,tileId:he.i,patch:{filterBindings:Lt}})}}const J=await Fe(V);if(!J)return;H(T=>Object.fromEntries(Object.entries(T).map(([G,ne])=>{var he,ot;if((ot=(he=J.pages.find(Tt=>Tt.id===G))==null?void 0:he.filters)!=null&&ot.some(Tt=>Tt.id===c.id))return[G,ne];const{[c.id]:Ke,...tt}=ne;return[G,tt]})));const ae=J.pages.find(T=>T.id===g.id);ae&&Cr(ae)?(ie(`${c.label.trim()||be(c.fieldId)} filter linked · refreshing ${fn(J,c.id)} components…`),await Xt(J,g.id,gt[g.id]??{})):ie(`${c.label.trim()||be(c.fieldId)} filter saved`)},Kr=async c=>{if(!u||!g)return;const v=[];for(const J of u.pages){(J.filters??[]).some(ae=>ae.id===c)&&v.push({type:"remove_filter",pageId:J.id,filterId:c});for(const ae of J.layout.items.filter(T=>{var G;return(G=T.filterBindings)==null?void 0:G.some(ne=>ne.filter===c)}))v.push({type:"update_tile",pageId:J.id,tileId:ae.i,patch:{filterBindings:(ae.filterBindings??[]).filter(T=>T.filter!==c)}})}const z=Object.fromEntries(Object.entries(gt).map(([J,ae])=>{const{[c]:T,...G}=ae;return[J,G]}));H(z),fe(J=>Object.fromEntries(Object.entries(J).map(([ae,T])=>{const{[c]:G,...ne}=T;return[ae,ne]})));const P=await Fe(v),V=P==null?void 0:P.pages.find(J=>J.id===g.id);P&&V&&Cr(V)?(ie(`${be(c)} filter removed · refreshing linked components…`),await Xt(P,g.id,z[g.id]??{})):P&&ie(`${be(c)} filter removed`)},fr=async c=>{if(!u||!g)return;const v=[{type:"set_template",template:c},{type:"upsert_page",page:Vo(g,c,u.name)}];await Fe(v)},Fn=async c=>{const v=Gt.current??qe;if(!g||!v||v===c)return;const z=[...g.layout.items],P=z.findIndex(G=>G.i===v),V=z.findIndex(G=>G.i===c);if(P<0||V<0)return;const[J]=z.splice(P,1);z.splice(V,0,J);const ae=z.map((G,ne)=>({...G,x:0,y:ne})),T=await Fe([{type:"set_layout",pageId:g.id,layout:{...g.layout,items:Tr(ae,12)}}]);Gt.current=null,zt(null),T&&ie("Layout saved · preview preserved")},Za=async()=>{if(!u||!g||!K){Ce("Run this page successfully before approving governed semantic results.");return}const c=[];for(const z of u.sources.filter(P=>P.kind==="governed_semantic"||P.kind==="semantic_query"))c.push({type:"upsert_source",source:{...z,snapshotId:K.snapshotId,receiptId:K.runId,reviewStatus:"approved"}});for(const z of g.layout.items.filter(P=>P.semantic&&K.tiles.some(V=>V.tileId===P.i&&V.status==="ok")))c.push({type:"update_tile",pageId:g.id,tileId:z.i,patch:{semantic:{...z.semantic,snapshotId:K.snapshotId},review:{status:"approved",sourceFingerprint:z.semantic.definitionFingerprint,preflightReceiptId:K.runId,reviewedAt:new Date().toISOString(),reviewedBy:"local-author"}}});await Fe(c)&&ie("Semantic results approved · run preview once more")},On=async()=>{if(!u)return;const c=da(u).filter(T=>T.kind!=="governed_semantic"&&T.kind!=="semantic_query");if(c.length===0)return;const v=new Set(c.map(T=>T.id)),z=new Set(c.flatMap(T=>[T.id,T.sourceRef,T.id.replace(/^[^:]+:/,"")])),P=u.pages.flatMap(T=>T.layout.items.filter(G=>{var tt;const ne=G.block?"blockId"in G.block?G.block.blockId:G.block.ref:null;return[(tt=G.draftAnalysis)==null?void 0:tt.ref,ne].filter(he=>!!he).some(he=>z.has(he)||z.has(he.replace(/^[^:]+:/,"")))}).map(G=>({pageId:T.id,tileId:G.i}))),V=new Set(P.map(T=>T.tileId)),J=[...P.map(T=>({type:"remove_tile",pageId:T.pageId,tileId:T.tileId})),...c.map(T=>({type:"remove_source",sourceId:T.id})),...u.reviewTasks.filter(T=>T.sourceId&&v.has(T.sourceId)||T.tileId&&V.has(T.tileId)).map(T=>({type:"remove_review_task",taskId:T.id})),{type:"set_coverage",coverage:u.coverage.map(T=>{const G=T.sourceIds.filter(Ke=>!v.has(Ke)),ne=T.componentIds.filter(Ke=>!V.has(Ke));return{...T,sourceIds:G,componentIds:ne,...T.status==="covered"&&(G.length===0||ne.length===0)?{status:"gap",reasons:[...T.reasons,"Review-required local analysis was removed from the publication draft."]}:{}}})}];await Fe(J)&&(st([]),ie("Local analysis removed · Undo is available"))},zr=async(c=!0,v=u)=>{var z,P;if(v){re(!0),Ce(null);try{if(c&&v.state==="preflight_ready"&&zo(v).length===0&&_t.length===0){const ae=await D.publishAppBuild(v.id,v.revision,v.proposalHash);w(ae.draft),pt(!1),f(ae.app,(z=ae.draft.pages[0])==null?void 0:z.id);return}const V=await D.preflightAppBuild(v.id,v.revision,v.proposalHash);if(w(V.draft),!c){st([]),pt(!0);return}const J=await D.publishAppBuild(V.draft.id,V.draft.revision,V.draft.proposalHash);w(J.draft),pt(!1),f(J.app,(P=J.draft.pages[0])==null?void 0:P.id)}catch(V){const J=V instanceof Dn&&V.details&&typeof V.details=="object"?V.details:null,ae=Array.isArray(J==null?void 0:J.errors)?J.errors.filter(T=>typeof T=="string"&&T.trim().length>0):[];ae.length?(J!=null&&J.draft&&typeof J.draft=="object"&&w(J.draft),st(ae),pt(!0)):Ce(`Project publication needs attention. ${Ct(V)}`)}finally{re(!1)}}},Wn=async c=>{if(!u)return;await Fe([{type:"set_requirements",requirements:u.requirements.map(z=>z.id===c?{...z,required:!1}:z),coverage:u.coverage}])&&st([])},Hn=c=>{if(!u)return;const v=`Revise this App so it can answer this publish question with governed evidence: ${c}`;O(v),pt(!1),tr(u,v)},Vn=async(c,v)=>{if(!u)return;const z=(u.frame.clarificationQuestions??[]).map(V=>V.id===c?{...V,answerId:v}:V);await Fe([{type:"set_frame",frame:{...u.frame,clarificationQuestions:z}}])&&st([])},Kn=async()=>{var ae,T;if(!u)return;const c=[],v=u.sources.filter(G=>G.kind==="block"||G.kind==="certified_block"||G.kind==="review_block"),z=await D.resolveAppSourceCandidates(u.id,v.map(G=>G.id)),P=new Map(z.items.map(G=>[G.id,G])),V=v.filter(G=>!P.has(G.id));if(V.length){pt(!1),A("sources"),Q(!0),Ce(`${V.map(G=>be(G.sourceRef)).join(", ")} ${V.length===1?"is":"are"} no longer certified. Replace or remove ${V.length===1?"this source":"these sources"} before publication.`);return}for(const G of v){const ne=P.get(G.id);ne&&ne.lifecycle==="certified"&&(G.sourceRevision!==ne.sourceRevision||G.trustState!=="certified"||G.reviewStatus!=="not_required")&&c.push({type:"upsert_source",source:{...G,kind:"block",sourceRef:ne.path,sourcePath:ne.path,executionRef:ne.path,qualifiedIdentity:ne.qualifiedIdentity,snapshotId:ne.snapshotId,sourceRevision:ne.sourceRevision,sourceFingerprint:ne.sourceRevision,lifecycle:"certified",capabilities:ne.capabilities,trustState:"certified",reviewStatus:"not_required"}})}for(const G of u.pages)for(const ne of G.layout.items){if(!ne.sourceId)continue;const Ke=P.get(ne.sourceId);!Ke||Ke.lifecycle!=="certified"||(ne.sourceRevision!==Ke.sourceRevision||((ae=ne.review)==null?void 0:ae.sourceFingerprint)!==Ke.sourceRevision||((T=ne.review)==null?void 0:T.status)!=="not_required")&&c.push({type:"update_tile",pageId:G.id,tileId:ne.i,patch:{sourceRevision:Ke.sourceRevision,block:{ref:Ke.path},sourceClass:"certified_block",trustState:"certified",reviewStatus:"certified",review:{...ne.review,status:"not_required",sourceFingerprint:Ke.sourceRevision}}})}if(!c.length){st([]),ie("Certified sources are already current"),await zr(!1);return}await Fe(c)&&(st([]),ie("Source trust refreshed · run preview again"))},Qn=async()=>{if(u){re(!0),Ce(null);try{const c=await D.deleteAppBuild(u.id,u.revision,u.proposalHash);y({appName:u.name,recoveryId:c.recoveryId})}catch(c){Ut(!1),Ce(Ct(c))}finally{re(!1)}}};async function Xt(c,v,z){var J;const P=c.pages.find(ae=>ae.id===v);if(!P)return null;const V=ct.current+1;ct.current=V,W(P.id),Re(!0),Ce(null);try{const ae=z??gt[P.id]??{},T=await D.runAppBuildPreview(c.id,P.id,ae);if(V!==ct.current)return null;const G=await D.patchAppBuild(c.id,c.revision,[{type:"set_preview_receipt",receipt:{id:T.runId,pageId:P.id,revision:c.revision,snapshotId:T.snapshotId,filterFingerprint:T.filterFingerprint,resultFingerprint:T.resultFingerprint,createdAt:new Date().toISOString()}}],c.proposalHash);return V!==ct.current?null:(w(G.draft),He(ne=>({...ne,[P.id]:T})),(J=T.filterOptions)!=null&&J.length&&fe(ne=>{const Ke={...ne[P.id]??{}};for(const tt of T.filterOptions??[]){const he=Ke[tt.filterId];Ke[tt.filterId]={values:Array.from(new Set([...(he==null?void 0:he.values)??[],...tt.values])).sort((ot,Tt)=>ot.localeCompare(Tt,void 0,{numeric:!0,sensitivity:"base"})),truncated:!!(he!=null&&he.truncated||tt.truncated),valueCount:tt.valueCount??(he==null?void 0:he.valueCount),dateRange:Jo(he==null?void 0:he.dateRange,tt.dateRange)}}return{...ne,[P.id]:Ke}}),ie(`Preview settled · ${T.tiles.filter(ne=>ne.status==="ok").length}/${T.tiles.length} ready`),G.draft)}catch(ae){return V===ct.current&&Ce(Ct(ae)),null}finally{V===ct.current&&Re(!1)}}const Da=async(c=g==null?void 0:g.id)=>{!u||!c||await Xt(u,c)},Gn=async c=>{if(!u||!c)return;const v=await Xt(u,c);v&&(st([]),await zr(!1,v))},Yn=async()=>{if(!u)return;let c=u;const v=c.pages.filter(z=>Cr(z));for(const z of v){const P=await Xt(c,z.id,gt[z.id]??{});if(!P)return;c=P}st([]),await zr(!1,c)},Xn=(c,v)=>{if(!u||!g)return;const z=g.id,P=new Set(u.pages.filter(T=>{var G;return(G=T.filters)==null?void 0:G.some(ne=>ne.id===c.id)}).map(T=>T.id)),V={...gt};for(const T of P)V[T]={...V[T]??{},[c.id]:v};const J=V[z]??{[c.id]:v};H(V),He(T=>{const G={...T};for(const ne of P)delete G[ne];return G}),ct.current+=1,Re(!1),ft.current!==null&&window.clearTimeout(ft.current);const ae=c.type==="daterange"&&v&&typeof v=="object"&&!Array.isArray(v)?v:null;if(ae&&!!ae.start!=!!ae.end){ie(`Choose both ${c.label??be(c.id)} dates`);return}ie(`${c.label??be(c.id)} changed · applying automatically…`),ft.current=window.setTimeout(()=>{ft.current=null,Xt(u,z,J)},320)};if(p.useEffect(()=>{if(!u||!g||de||et||dt[g.id]||!Cr(g))return;const c=window.setTimeout(()=>{Xt(u,g.id,gt[g.id]??{})},0);return()=>window.clearTimeout(c)},[g==null?void 0:g.id,u==null?void 0:u.revision,de]),p.useEffect(()=>()=>{ft.current!==null&&window.clearTimeout(ft.current),Nt.current!==null&&window.clearTimeout(Nt.current)},[]),!u)return e.jsxs("div",{className:"dql-studio-v2-loading",children:[e.jsx("style",{children:ra}),e.jsx("button",{type:"button",className:"icon",onClick:m,"aria-label":"Back to Apps",children:e.jsx(_r,{size:18})}),e.jsxs("div",{children:[e.jsx("span",{className:"loading-mark",children:e.jsx(At,{size:20})}),e.jsx("strong",{children:lt?"Studio could not open":i?"Opening your local draft…":l?"Preparing a safe edit draft…":"Preparing your Build Frame…"}),e.jsx("small",{children:lt??"Keeping all work local until you explicitly publish it to the Project."}),lt?e.jsx("button",{type:"button",onClick:()=>{Yt.current=!1,Or()},children:"Try again"}):null]})]});if(ze)return e.jsx(Io,{activity:ze,label:qa[pe]??qa[0],onBack:m,onReturn:ze.returnToProposal&&de?()=>Z(null):void 0,onRetry:()=>ca(ze)});const Qr=oe?ka(oe):null,Ua=(oe==null?void 0:oe.sourceId)??(oe==null?void 0:oe.id),mr=(Ne==null?void 0:Ne.sourceId)===Ua?Ne:null,Jn=oe&&Qr?ln({view:Sa(Qr),status:(mr==null?void 0:mr.status)??"idle",reviewRequired:((ei=oe.eligibility)==null?void 0:ei.localPreview)===!1&&u.sourcePolicy==="governed_only",alreadyUsed:u.sources.some(c=>c.id===Ua||c.sourceRef===oe.path),pageTitle:mr==null?void 0:mr.pageTitle}):"";return e.jsxs("div",{className:`dql-studio-v2 ${de?"proposal-focus":""}`,children:[e.jsx("style",{children:ra}),e.jsxs("header",{className:"studio-topbar",children:[e.jsxs("div",{className:"studio-brand",children:[e.jsx("button",{type:"button",className:"icon",onClick:m,children:e.jsx(_r,{size:17})}),e.jsx("span",{className:"mark",children:e.jsx(At,{size:16})}),e.jsxs("div",{children:[e.jsx("input",{value:F||u.name,onChange:c=>U(c.target.value),onBlur:()=>{F.trim()&&F.trim()!==u.name&&Fe([{type:"set_name",name:F.trim()}])}}),e.jsx("small",{children:bt})]})]}),de?e.jsxs("div",{className:"proposal-focus-title",children:[e.jsx("small",{children:"AI APP BUILD · STEP 2"}),e.jsx("strong",{children:"Choose proposed sources"})]}):e.jsxs("nav",{className:"page-nav","aria-label":"App pages",children:[u.pages.map(c=>e.jsx("button",{type:"button",className:(g==null?void 0:g.id)===c.id?"on":"",onClick:()=>{W(c.id),se(null)},children:c.metadata.title},c.id)),e.jsx("button",{type:"button",className:"icon",onClick:()=>void Sr(),"aria-label":"Add page",children:e.jsx(xt,{size:15})})]}),de?e.jsxs("div",{className:"proposal-focus-status",children:[e.jsx(Qe,{size:14}),e.jsx("span",{children:"Private draft · nothing generated yet"})]}):e.jsxs("div",{className:"studio-actions",children:[e.jsx("button",{type:"button",className:"icon",disabled:!Me.length||Le,onClick:()=>void Hr(),title:"Undo",children:e.jsx(lo,{size:16})}),e.jsx("button",{type:"button",className:"icon",disabled:!we.length||Le,onClick:()=>void Vr(),title:"Redo",children:e.jsx(Us,{size:16})}),e.jsxs("div",{className:"breakpoints",children:[e.jsx("button",{type:"button",className:Y==="auto"?"on":"",onClick:()=>S("auto"),title:"Fit to available canvas",children:e.jsx(At,{size:15})}),e.jsx("button",{type:"button",className:Y==="wide"?"on":"",onClick:()=>S("wide"),title:"Wide preview",children:e.jsx(Zn,{size:15})}),e.jsx("button",{type:"button",className:Y==="medium"?"on":"",onClick:()=>S("medium"),title:"Tablet preview",children:e.jsx(Zs,{size:15})}),e.jsx("button",{type:"button",className:Y==="narrow"?"on":"",onClick:()=>S("narrow"),title:"Phone preview",children:e.jsx(ao,{size:15})})]}),e.jsxs("button",{type:"button",className:`copilot ${Kt?"on":""}`,onClick:()=>Qt(c=>!c),"aria-pressed":Kt,"aria-label":"Open App Copilot",children:[e.jsx(nr,{size:14}),e.jsx("span",{children:"App Copilot"})]}),e.jsxs("button",{type:"button",className:"preview",onClick:()=>void Da(),disabled:et||Le,"aria-label":et?"Running preview":"Run preview",children:[e.jsx(Jt,{size:13}),e.jsx("span",{children:et?"Running…":"Run preview"})]}),e.jsxs("button",{type:"button",className:"publish",onClick:()=>void zr(!1),disabled:Le,"aria-label":`Review and publish to Project${Mt?`, ${Mt} ${Mt===1?"fix":"fixes"} needed`:""}`,children:[e.jsx(hs,{size:13}),e.jsx("span",{children:"Publish to Project"}),Mt?e.jsxs("small",{children:[Mt," ",Mt===1?"fix":"fixes"]}):null]}),e.jsx("button",{type:"button",className:"icon overflow-button","aria-label":"More draft actions","aria-expanded":vt,onClick:()=>Vt(c=>!c),children:e.jsx(ta,{size:17})}),vt?e.jsx("div",{className:"studio-overflow-menu",role:"menu",children:e.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{Vt(!1),Ut(!0)},children:[e.jsx(ir,{size:14})," Delete local draft"]})}):null]})]}),de?null:e.jsxs("aside",{className:"studio-left",children:[e.jsx("nav",{children:[["sources",yr,"Sources"],["pages",At,"Pages"],["filters",Zt,"Filters"],["templates",mt,"Design"]].map(([c,v,z])=>e.jsxs("button",{type:"button",className:_===c&&te?"on":"",onClick:()=>{window.innerWidth<=820&&_===c?Q(P=>!P):(A(c),Q(!0))},children:[e.jsx(v,{size:17}),e.jsx("span",{children:z})]},c))}),e.jsxs("section",{className:`left-content ${te?"open":""}`,children:[e.jsx("button",{type:"button",className:"mobile-drawer-close",onClick:()=>Q(!1),"aria-label":"Close Studio drawer",children:e.jsx($t,{size:16})}),_==="pages"?e.jsx($o,{draft:u,activePageId:g==null?void 0:g.id,onOpen:W,onAdd:()=>void Sr()}):null,_==="sources"?e.jsx(_o,{usedSources:u.sources,items:je,selected:oe,query:_e,loading:le,error:ve,disabled:Le||et,sourceFeedback:Ne,onQuery:Ie,onSelect:j,onAdd:(c,v)=>void ce(v,c),onAddContent:c=>void ce(c,null),policy:u.sourcePolicy,total:it,hasMore:!!xe,onLoadMore:()=>void E(),onEnableReview:()=>void Fe([{type:"set_source_policy",sourcePolicy:"include_review_required"}])}):null,_==="filters"?e.jsx(Eo,{draft:u,activePageId:g==null?void 0:g.id,catalog:ue,candidates:gr,runtimeFilterFields:wt,previewRunsByPage:dt,previewing:et,disabled:Le||et,onRunPreview:()=>void Da(),onSave:c=>void Rt(c),onRemove:c=>void Kr(c)}):null,_==="templates"?e.jsx(Bo,{current:u.template,onApply:c=>void fr(c)}):null]})]}),e.jsxs("main",{ref:N,className:"studio-workspace",children:[lt?e.jsxs("div",{className:"studio-error floating",role:"alert",children:[lt,e.jsx("button",{type:"button",onClick:()=>Ce(null),children:"×"})]}):null,de&&ut?e.jsx(To,{proposal:de,summary:ut,catalog:ue,catalogQuery:_e,sourcePolicy:u.sourcePolicy,selectedSourceIds:Ye,addingSourceId:De,busy:Le,onRevise:()=>void tr(u,I,ai(Ye),!0),onApply:()=>void Wr(),onDismiss:()=>Pe(null),onCatalogQuery:Ie,onAddSource:c=>{var v;return void kr(c.sourceId??c.id,((v=c.eligibility)==null?void 0:v.localPreview)===!1,c)},onAddProposalSource:(c,v)=>void kr(c,v),onAnswerClarification:(c,v)=>void jr({[c]:v}),onGenerateGap:c=>void pa(c),onToggleSource:c=>Xe(v=>{const z=new Set(v);return z.has(c)?z.delete(c):z.add(c),z})}):null,de?null:e.jsxs("div",{className:`studio-canvas-frame ${Ve} preview-mode-${Y}`,children:[e.jsxs("div",{className:"studio-canvas-label",children:[e.jsxs("div",{children:[e.jsxs("span",{children:[Y==="auto"?"Fit canvas":`${Ve.charAt(0).toUpperCase()+Ve.slice(1)} preview`," · ",Ve==="wide"?"12 columns":Ve==="medium"?"6 columns":"1 column"]}),e.jsx("small",{children:"Drag components to reorder · saved instantly"})]}),e.jsxs("button",{type:"button",onClick:()=>void Se(),disabled:!(g!=null&&g.layout.items.length)||Le,title:"Compact gaps and restore a clean reading order",children:[e.jsx(At,{size:13})," Auto arrange"]})]}),e.jsxs("section",{className:"studio-canvas","aria-label":"App canvas",children:[e.jsxs("header",{className:"studio-page-heading",children:[e.jsxs("div",{children:[e.jsx("small",{children:"APP PAGE"}),e.jsx("span",{children:(g==null?void 0:g.metadata.title)??"Overview"})]}),e.jsxs("small",{children:[u.frame.audience||"Stakeholders"," · ",((ti=u.pages[0])==null?void 0:ti.metadata.domain)||"General"]})]}),oe&&Qr?e.jsxs("div",{className:"studio-source-ready",children:[e.jsxs("div",{children:[e.jsx("span",{className:"certified",children:e.jsx(Qe,{size:14})}),e.jsxs("p",{children:[e.jsx("small",{children:"Selected data"}),e.jsx("strong",{children:be(oe.name)})]})]}),e.jsxs("span",{className:"studio-source-actions",children:[e.jsxs("button",{type:"button",disabled:Le||et,onClick:()=>void ce(Qr,oe),children:[e.jsx(xt,{size:14})," ",Jn]}),e.jsx("button",{type:"button",className:"source-clear",onClick:()=>Be(null),"aria-label":"Clear selected data",children:e.jsx($t,{size:14})})]})]}):null,((g==null?void 0:g.filters)??[]).length?e.jsx("div",{className:"studio-page-filterbar",children:g.filters.map(c=>e.jsx(Oo,{filter:c,availability:rt[c.id],value:me[c.id]??c.default,applying:et,onChange:v=>Xn(c,v)},c.id))}):null,e.jsxs("div",{className:"studio-page-grid",children:[yt.map(c=>e.jsxs("article",{role:"button",tabIndex:0,draggable:!0,className:`studio-component-card ${$e===c.i?"selected":""} ${qe===c.i?"dragging":""}`,style:{"--studio-tile-width":Math.min(c.w,Ve==="medium"?6:Ve==="narrow"?1:12),minHeight:Ve==="narrow"?Math.max(180,c.h*58):Math.max(150,c.h*68)},onDragStart:()=>{Gt.current=c.i,zt(c.i)},onDragEnd:()=>{Gt.current=null,zt(null)},onDragOver:v=>v.preventDefault(),onDrop:v=>{v.preventDefault(),Fn(c.i)},onClick:()=>se(c.i),onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&se(c.i)},children:[e.jsxs("header",{children:[e.jsx("span",{className:"drag-handle","aria-hidden":"true",children:"⠿"}),e.jsx("span",{className:`trust-dot ${c.trustState??"draft_ready"}`})," ",e.jsx("strong",{children:c.title||be(c.i)}),e.jsx("small",{children:c.viz.type.replace(/_/g," ")})]}),Qo(c).map(v=>e.jsxs("div",{className:"tile-filter-notice",children:[e.jsx(Zt,{size:11}),e.jsx("span",{children:v.unsupportedReason??`${be(v.filter)} does not affect this component.`})]},v.filter)),c.text?e.jsx("div",{className:c.viz.type==="heading"?"tile-heading":"tile-text",children:c.text.markdown.replace(/^#+\s*/,"")}):e.jsx(Ho,{tile:c,run:K==null?void 0:K.tiles.find(v=>v.tileId===c.i),loading:et,themeMode:b})]},c.i)),yt.length?null:e.jsxs("div",{className:"empty-canvas",children:[e.jsx("span",{children:e.jsx(xt,{size:22})}),e.jsx("strong",{children:"Build this page"}),e.jsx("p",{children:"Open Sources on the left, choose governed data, and add its recommended view. You can also add text or a heading."}),e.jsx("button",{type:"button",onClick:()=>{A("sources"),Q(!0)},children:"Open Sources"})]})]})]})]})]}),de?null:e.jsxs("aside",{className:`studio-right ${Je?"has-selection":""}`,children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx(_a,{size:16}),e.jsx("strong",{children:Je?"Component properties":"App Build Frame"})]}),e.jsx("button",{type:"button",className:"icon",onClick:()=>se(null),"aria-label":Je?"Close component properties":"More App settings",children:Je?e.jsx($t,{size:16}):e.jsx(ta,{size:16})})]}),Je&&g?e.jsx(Lo,{tile:Je,run:K==null?void 0:K.tiles.find(c=>c.tileId===Je.i),pageId:g.id,onUpdate:c=>void Fe([{type:"update_tile",pageId:g.id,tileId:Je.i,patch:c}]),onDelete:()=>void Fe([{type:"remove_tile",pageId:g.id,tileId:Je.i}]).then(()=>se(null))}):e.jsx(Mo,{draft:u,prompt:I,previewRun:K,onPrompt:O,onAskAi:()=>void tr(),onSourcePolicy:c=>void Fe([{type:"set_source_policy",sourcePolicy:c}]),onResolveTask:c=>void Fe([{type:"set_review_task",task:{...c,status:"resolved"}}]),onApproveSemantic:()=>void Za()})]}),Kt&&!de?e.jsx(Ea,{t:Ht[b],title:"App Copilot",subtitle:u.name,dock:"overlay",expanded:cr,onToggleExpanded:()=>er(c=>!c),onNewChat:B.resetThreadId,onClose:()=>Qt(!1),running:ur,resizable:!0,minResizeWidth:390,maxResizeWidth:1100,ariaLabel:"App Copilot",className:"studio-copilot-panel",style:{top:58,bottom:0,height:"auto"},children:e.jsx(p.Suspense,{fallback:e.jsx("div",{className:"studio-copilot-loading",children:"Loading App Copilot…"}),children:e.jsx(Co,{themeMode:b,title:"App Copilot",scopeHint:`Draft · ${(g==null?void 0:g.metadata.title)??"Overview"}`,composerPlaceholder:"Ask about this App, its sources, filters, results, or a deeper business question…",emptyHint:"Ask a detailed question about the current draft. Copilot uses the App Build Frame, selected governed sources, filters, and settled preview evidence.",audience:"stakeholder",initialMode:"auto",selectedObject:oe?{kind:"block",id:oe.id,title:oe.name}:{kind:"app",id:u.appId,title:u.name},workspaceContext:Po(u,g,oe,Je,K),threadId:B.threadId,onThreadIdChange:B.onThreadIdChange,onRunningChange:xr,answerFirstCards:!0,examplePrompts:[{label:"Explain the planned story",prompt:"Explain the business story this App currently tells, the evidence behind it, and what is still missing."},{label:"Check source wiring",prompt:"Which governed source supports each component and filter in this App? Call out unsupported or review-required wiring."},{label:"Go deeper",prompt:"What deeper driver question should I investigate next based on this App and its current preview evidence?"}]})})}):null,pr?e.jsx(Ro,{draft:u,serverIssues:_t,busy:Le||et,previewRun:K,onClose:()=>pt(!1),onRetry:()=>void zr(!0),onRunPreview:c=>void Gn(c),onRunAllPreviews:()=>void Yn(),onRemoveRequirement:c=>void Wn(c),onReviseRequirement:Hn,onAnswerQuestion:(c,v)=>void Vn(c,v),onResolveTask:c=>void Fe([{type:"set_review_task",task:{...c,status:"resolved"}}]).then(v=>{v&&st([])}),onOpenSources:()=>{pt(!1),A("sources"),Q(!0)},onOpenFilters:()=>{pt(!1),A("filters"),Q(!0)},onRefreshSources:()=>void Kn(),onApproveSemantic:()=>void Za(),onRemoveLocalAnalysis:()=>void On()}):null,Dt?e.jsx("div",{className:"proposal-scrim",role:"dialog","aria-modal":"true","aria-label":"Delete local App draft",children:e.jsxs("section",{className:"studio-delete-card",children:[e.jsx("span",{className:"delete-mark",children:e.jsx(ir,{size:18})}),e.jsx("h2",{children:"Delete this local draft?"}),e.jsxs("p",{children:[e.jsx("strong",{children:u.name})," will leave the App list. Its pages, components, and local history move to a recovery bundle so you can Undo."]}),e.jsxs("footer",{children:[e.jsx("button",{type:"button",onClick:()=>Ut(!1),disabled:Le,children:"Cancel"}),e.jsx("button",{type:"button",className:"danger",onClick:()=>void Qn(),disabled:Le,children:Le?"Deleting…":"Delete draft"})]})]})}):null]})}function Ro({draft:t,serverIssues:r,busy:a,previewRun:i,onClose:s,onRetry:n,onRunPreview:o,onRunAllPreviews:l,onRemoveRequirement:d,onReviseRequirement:x,onAnswerQuestion:b,onResolveTask:m,onOpenSources:f,onOpenFilters:y,onRefreshSources:u,onApproveSemantic:w,onRemoveLocalAnalysis:q}){const C=La(t),k=(t.frame.clarificationQuestions??[]).filter(A=>A.required&&!A.answerId),M=la(t),L=Fa(t),X=da(t),I=X.filter(A=>A.kind==="governed_semantic"||A.kind==="semantic_query"),O=X.filter(A=>A.kind!=="governed_semantic"&&A.kind!=="semantic_query"),F=un(r),U=C.length===0&&k.length===0&&M.length===0&&L.length===0&&X.length===0&&F.length===0,_=xn(t,r);return e.jsx("div",{className:"proposal-scrim",role:"dialog","aria-modal":"true","aria-labelledby":"publish-readiness-title",children:e.jsxs("section",{className:"studio-readiness-card",children:[e.jsxs("header",{children:[e.jsx("span",{className:U?"ready":"",children:U?e.jsx(Pt,{size:19}):e.jsx(Qe,{size:19})}),e.jsxs("div",{children:[e.jsx("h2",{id:"publish-readiness-title",children:U?"Ready to publish":`${_} ${_===1?"fix":"fixes"} before publishing`}),e.jsx("p",{children:U?"Every governed publication check passed.":"Complete the actions below. Each action updates this review automatically; there is no separate recheck loop."})]}),e.jsx("button",{type:"button",className:"icon",onClick:s,"aria-label":"Close publish checklist",children:e.jsx($t,{size:16})})]}),e.jsxs("div",{className:"readiness-body",children:[k.map(A=>e.jsxs("section",{className:"readiness-item",children:[e.jsx("span",{className:"step-mark",children:e.jsx(nr,{size:15})}),e.jsxs("div",{children:[e.jsx("strong",{children:"Choose what you mean"}),e.jsx("p",{children:A.question}),e.jsx("div",{className:"readiness-choices",children:A.choices.map(te=>e.jsx("button",{type:"button",onClick:()=>b(A.id,te.id),disabled:a,children:te.label},te.id))})]})]},A.id)),C.map(A=>e.jsxs("section",{className:"readiness-item",children:[e.jsx("span",{className:"step-mark",children:e.jsx(ht,{size:15})}),e.jsxs("div",{children:[e.jsx("strong",{children:"Unanswered App question"}),e.jsx("p",{children:A.question}),e.jsx("small",{children:"DQL will not pretend that an unrelated tile covers this question."}),e.jsxs("div",{className:"readiness-actions",children:[e.jsxs("button",{type:"button",className:"primary",onClick:()=>x(A.question),disabled:a,children:[e.jsx(nr,{size:13})," Revise with AI"]}),e.jsx("button",{type:"button",onClick:()=>d(A.id),disabled:a,children:"Remove from publish scope"})]})]})]},A.id)),M.map(A=>e.jsxs("section",{className:"readiness-item",children:[e.jsx("span",{className:"step-mark",children:e.jsx(mt,{size:15})}),e.jsxs("div",{children:[e.jsx("strong",{children:"Scoped review"}),e.jsx("p",{children:A.message}),e.jsx("div",{className:"readiness-actions",children:e.jsxs("button",{type:"button",className:"primary",onClick:()=>m(A),disabled:a,children:[e.jsx(Pt,{size:13})," Mark resolved"]})})]})]},A.id)),L.map(A=>e.jsxs("section",{className:"readiness-item",children:[e.jsx("span",{className:"step-mark",children:e.jsx(Jt,{size:15})}),e.jsxs("div",{children:[e.jsxs("strong",{children:["Run ",A.metadata.title||A.id]}),e.jsx("p",{children:"Settle the current data, filters, and component results before publishing this page."}),e.jsx("div",{className:"readiness-actions",children:e.jsxs("button",{type:"button",className:"primary",onClick:()=>o(A.id),disabled:a,children:[e.jsx(Jt,{size:13})," ",a?"Running…":"Run preview"]})})]})]},A.id)),I.length?e.jsxs("section",{className:"readiness-item",children:[e.jsx("span",{className:"step-mark",children:e.jsx(Qe,{size:15})}),e.jsxs("div",{children:[e.jsx("strong",{children:"Approve governed semantic results"}),e.jsx("p",{children:I.map(A=>be(A.sourceRef)).join(", ")}),e.jsx("small",{children:"Approval binds the source to the settled snapshot you reviewed."}),e.jsxs("div",{className:"readiness-actions",children:[i?e.jsxs("button",{type:"button",className:"primary",onClick:w,disabled:a,children:[e.jsx(Qe,{size:13})," Approve settled result"]}):e.jsxs("button",{type:"button",onClick:()=>{var A;return o(((A=t.pages[0])==null?void 0:A.id)??"")},disabled:a,children:[e.jsx(Jt,{size:13})," Run preview first"]}),e.jsx("button",{type:"button",onClick:f,children:"Open Sources"})]})]})]}):null,O.length?e.jsxs("section",{className:"readiness-item warning",children:[e.jsx("span",{className:"step-mark",children:e.jsx(mt,{size:15})}),e.jsxs("div",{children:[e.jsx("strong",{children:"Local analysis cannot publish"}),e.jsx("p",{children:O.map(A=>be(A.sourceRef)).join(", ")}),e.jsx("small",{children:"Replace it with governed data, or remove it from this draft. Removal is saved locally and can be undone from the Studio toolbar."}),e.jsxs("div",{className:"readiness-actions",children:[e.jsxs("button",{type:"button",className:"primary",onClick:f,children:[e.jsx(yr,{size:13})," Replace with governed data"]}),e.jsxs("button",{type:"button",onClick:q,disabled:a,children:[e.jsx(ir,{size:13})," Remove local analysis"]})]})]})]}):null,F.map(A=>e.jsxs("section",{className:"readiness-item",children:[e.jsx("span",{className:"step-mark",children:e.jsx(_a,{size:15})}),e.jsxs("div",{children:[e.jsx("strong",{children:A.title}),e.jsx("p",{children:A.detail}),e.jsx("div",{className:"readiness-actions",children:A.action==="filters"?e.jsxs("button",{type:"button",className:"primary",onClick:y,children:[e.jsx(Zt,{size:13})," Open Filters"]}):A.action==="refresh_sources"?e.jsxs("button",{type:"button",className:"primary",onClick:u,disabled:a,children:[e.jsx(Qe,{size:13})," Accept current certified source"]}):A.action==="preview"?e.jsxs("button",{type:"button",className:"primary",onClick:l,disabled:a,children:[e.jsx(Jt,{size:13})," ",a?"Refreshing previews…":"Refresh all page previews"]}):e.jsxs("button",{type:"button",className:"primary",onClick:f,children:[e.jsx(yr,{size:13})," Replace or remove source"]})})]})]},A.id)),U?e.jsxs("div",{className:"readiness-ready",children:[e.jsx(Pt,{size:18}),e.jsxs("div",{children:[e.jsx("strong",{children:"Governed checks passed"}),e.jsx("span",{children:"The published package will be Git-reviewable and no files are auto-staged or committed."})]})]}):null]}),e.jsxs("footer",{children:[e.jsx("button",{type:"button",onClick:s,disabled:a,children:"Back to editing"}),U?e.jsx("button",{type:"button",className:"primary",onClick:n,disabled:a,children:a?"Publishing…":"Publish to Project"}):e.jsx("span",{className:"readiness-footer-hint",children:"Choose a fix above. This review updates as you work."})]})]})})}function To({proposal:t,summary:r,catalog:a,catalogQuery:i,sourcePolicy:s,selectedSourceIds:n,addingSourceId:o,busy:l,onRevise:d,onApply:x,onDismiss:b,onCatalogQuery:m,onAddSource:f,onAddProposalSource:y,onAnswerClarification:u,onGenerateGap:w,onToggleSource:q}){var Y;const C=t.clarifications.filter(S=>S.required&&!S.answerId),k=t.operations.find(S=>S.type==="set_requirements"),M=(k==null?void 0:k.type)==="set_requirements"?k.requirements.filter(S=>{var h;return(h=k.coverage)==null?void 0:h.some($=>$.requirementId===S.id&&$.status==="gap")}):[],L=r.components.filter(S=>!S.sourceId||n.has(S.sourceId)),X=r.sources.filter(S=>n.has(S.id)),I=r.sources.filter(S=>!n.has(S.id)),O=bo(r,a,i).slice(0,10),F=i.trim().toLowerCase(),U=S=>!F||[S.label,S.sourceRef,za(S.kind),S.rationale??"",...r.components.filter(h=>h.sourceId===S.id).flatMap(h=>[h.title,h.visualization])].join(" ").toLowerCase().includes(F),_=X.filter(U),A=I.filter(U),te=S=>{const h=r.components.filter($=>$.sourceId===S.id);return h.length?`Creates ${h.length} ${h.length===1?"view":"views"}: ${h.map($=>$.title).join(", ")}`:"AI will use this source as governed context."},Q=(S,h)=>{const $=S.trustState!=="certified"&&s==="governed_only",ee=o===S.id;return e.jsxs("article",{className:`proposal-source-row ${h?"selected":""}`,children:[e.jsx("span",{className:`proposal-source-trust ${S.trustState}`,children:S.trustState==="certified"?e.jsx(Qe,{size:15}):e.jsx(mt,{size:15})}),e.jsxs("div",{children:[e.jsx("strong",{children:S.label}),e.jsxs("small",{children:[za(S.kind)," · ",S.trustState==="certified"?"Certified":"Review required"]}),e.jsx("p",{children:te(S)})]}),e.jsx("button",{type:"button",className:h?"remove":"add",disabled:l,title:$?"Enable the local review lane and rebuild the proposal with this source.":void 0,onClick:()=>h?q(S.id):y(S.id,$),"aria-label":`${h?"Remove":$?"Enable review lane and add":"Add"} ${S.label}${r.sources.filter(W=>W.label===S.label).length>1?` for ${r.components.filter(W=>W.sourceId===S.id).map(W=>W.title).join(", ")||S.id}`:""}`,children:h?e.jsxs(e.Fragment,{children:[e.jsx($t,{size:13})," Remove"]}):ee?"Adding…":$?"Enable review lane & add":e.jsxs(e.Fragment,{children:[e.jsx(xt,{size:13})," Add"]})})]},S.id)};return e.jsxs("section",{className:"studio-ai-plan proposal-source-picker","aria-labelledby":"proposal-source-title",children:[e.jsxs("header",{children:[e.jsx("span",{children:e.jsx(ht,{size:18})}),e.jsxs("div",{children:[e.jsx("small",{children:"REVIEW BEFORE GENERATION"}),e.jsx("h1",{id:"proposal-source-title",children:"Choose proposed sources"}),e.jsxs("p",{children:["AI understood: ",e.jsx("strong",{children:((Y=r.frame)==null?void 0:Y.goal)??"Build a governed analytics App"}),". Select the data you trust; DQL will generate the App only after you continue."]})]}),e.jsx("button",{type:"button",onClick:b,"aria-label":"Back to App decision",children:e.jsx($t,{size:16})})]}),e.jsxs("div",{className:"proposal-source-summary","aria-label":"AI proposal summary",children:[e.jsxs("span",{children:[e.jsx("strong",{children:X.length})," selected sources"]}),e.jsxs("span",{children:[e.jsx("strong",{children:L.length})," planned views"]}),e.jsxs("span",{children:[e.jsx("strong",{children:s==="governed_only"?"Governed only":"Review lane enabled"})," source policy"]})]}),e.jsxs("div",{className:"proposal-source-body",children:[e.jsxs("label",{className:"proposal-source-search",children:[e.jsx(jt,{size:15}),e.jsx("input",{value:i,onChange:S=>m(S.target.value),placeholder:"Search proposed and available sources","aria-label":"Search proposed and available sources"})]}),e.jsxs("section",{className:"proposal-source-group","aria-labelledby":"selected-proposal-sources",children:[e.jsxs("div",{className:"proposal-source-heading",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"selected-proposal-sources",children:"Selected for this App"}),e.jsx("p",{children:"Remove anything you do not want AI to use."})]}),e.jsx("strong",{children:X.length})]}),e.jsxs("div",{className:"proposal-source-list",children:[_.map(S=>Q(S,!0)),X.length?null:e.jsxs("div",{className:"proposal-source-empty",children:[e.jsx(yr,{size:18}),e.jsxs("div",{children:[e.jsx("strong",{children:"Select at least one source"}),e.jsx("p",{children:"Add an AI suggestion or another governed block below."})]})]}),X.length>0&&!_.length?e.jsx("p",{className:"studio-ai-plan-empty",children:"No selected source matches this search."}):null]})]}),A.length?e.jsxs("section",{className:"proposal-source-group","aria-labelledby":"ai-source-suggestions",children:[e.jsxs("div",{className:"proposal-source-heading",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"ai-source-suggestions",children:"AI suggestions"}),e.jsx("p",{children:"Sources removed from the selection remain available here."})]}),e.jsx("strong",{children:I.length})]}),e.jsx("div",{className:"proposal-source-list",children:A.map(S=>Q(S,!1))})]}):null,e.jsxs("section",{className:"proposal-source-group","aria-labelledby":"available-proposal-sources",children:[e.jsxs("div",{className:"proposal-source-heading",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"available-proposal-sources",children:"More App sources"}),e.jsx("p",{children:"Add a certified block, or explicitly open the local review lane for a draft."})]}),e.jsx("strong",{children:O.length})]}),e.jsxs("div",{className:"proposal-catalog-list",children:[O.map(S=>{var h,$;return e.jsxs("article",{children:[e.jsx("span",{className:S.status==="certified"?"certified":"review_required",children:S.status==="certified"?e.jsx(Qe,{size:14}):e.jsx(mt,{size:14})}),e.jsxs("div",{children:[e.jsx("strong",{children:be(S.name)}),e.jsxs("small",{children:[S.domain||"General"," · ",S.status==="certified"?"Certified block":"Review required"]}),e.jsx("p",{children:S.description||S.reasons[0]||"Available governed data source"})]}),e.jsx("button",{type:"button",onClick:()=>f(S),disabled:l,title:((h=S.eligibility)==null?void 0:h.localPreview)===!1?"Enable the local review lane and rebuild the proposal with this source.":void 0,children:o===(S.sourceId??S.id)?"Adding…":(($=S.eligibility)==null?void 0:$.localPreview)===!1?"Enable review lane & add":e.jsxs(e.Fragment,{children:[e.jsx(xt,{size:13})," Add"]})})]},S.id)}),O.length?null:e.jsx("p",{className:"studio-ai-plan-empty",children:i.trim()?"No additional source matches this search.":"All available governed sources are already proposed."})]})]}),s==="include_review_required"?e.jsxs("div",{className:"studio-ai-review-lane",children:[e.jsx(mt,{size:14}),e.jsxs("p",{children:[e.jsx("strong",{children:"Review-required analysis is enabled"}),e.jsx("small",{children:"It stays clearly labeled and cannot be published to the Project until it is replaced, promoted, or removed."})]})]}):e.jsxs("div",{className:"studio-ai-review-lane",children:[e.jsx(mt,{size:14}),e.jsxs("p",{children:[e.jsx("strong",{children:"Draft sources require an explicit review lane"}),e.jsx("small",{children:"Use “Enable review lane & add” on the draft you want. Its trust does not change."})]})]}),M.length?e.jsxs("section",{className:"studio-ai-questions",children:[e.jsxs("header",{children:[e.jsx("strong",{children:"Uncovered requirements"}),e.jsxs("small",{children:[M.length," gaps"]})]}),M.map(S=>e.jsxs("div",{children:[e.jsx("p",{children:S.question}),e.jsx("button",{type:"button",onClick:()=>w(S.id),disabled:l||s!=="include_review_required",children:s==="include_review_required"?"Explicitly generate review-required DQL":"Enable review lane to generate"})]},S.id))]}):null,C.length?e.jsxs("section",{className:"studio-ai-questions",children:[e.jsxs("header",{children:[e.jsx("strong",{children:"AI needs one more decision"}),e.jsxs("small",{children:[C.length," required"]})]}),C.map(S=>e.jsxs("fieldset",{children:[e.jsx("legend",{children:S.question}),S.choices.map(h=>e.jsxs("button",{type:"button",onClick:()=>u(S.id,h.id),disabled:l,children:[e.jsx("strong",{children:h.label}),h.description?e.jsx("small",{children:h.description}):null]},h.id))]},S.id)),e.jsx("button",{type:"button",onClick:d,disabled:l,children:l?"Updating…":"Re-run proposal"})]}):null]}),e.jsxs("footer",{children:[e.jsxs("span",{children:[X.length," sources · ",L.length," views will be generated"]}),e.jsx("button",{type:"button",onClick:b,children:"Back to decision"}),e.jsxs("button",{type:"button",className:"primary",onClick:x,disabled:l||C.length>0||X.length===0,children:[e.jsx(ht,{size:14})," ",l?"Generating…":`Generate App with ${X.length} ${X.length===1?"source":"sources"}`]})]})]})}function Po(t,r,a,i,s){return{surface:"app-studio",appBuildId:t.id,appId:t.appId,appName:t.name,authoringMode:t.authoringMode,sourcePolicy:t.sourcePolicy,state:t.state,buildFrame:t.frame,requirements:t.requirements,coverage:t.coverage,sources:t.sources.map(n=>({id:n.id,kind:n.kind,sourceRef:n.sourceRef,trustState:n.trustState,reviewStatus:n.reviewStatus})),page:r?{id:r.id,title:r.metadata.title,filters:r.filters,components:r.layout.items.map(n=>({id:n.i,title:n.title,visualization:n.viz.type,trustState:n.trustState}))}:void 0,selectedSource:a?{id:a.id,name:a.name,domain:a.domain,status:a.status}:void 0,selectedComponent:i?{id:i.i,title:i.title,visualization:i.viz.type,trustState:i.trustState}:void 0,preview:s?{runId:s.runId,snapshotId:s.snapshotId,filterFingerprint:s.filterFingerprint,tiles:s.tiles.map(n=>{var o,l,d;return{tileId:n.tileId,status:n.status,rowCount:(o=n.result)==null?void 0:o.rowCount,columns:(d=(l=n.result)==null?void 0:l.columns)==null?void 0:d.slice(0,12),error:n.error}})}:{status:"not_run"},reviewTasks:t.reviewTasks.filter(n=>n.status==="open")}}function $o({draft:t,activePageId:r,onOpen:a,onAdd:i}){return e.jsxs(e.Fragment,{children:[e.jsx(Br,{title:"Pages",detail:"Organize the App story",action:e.jsx("button",{type:"button",onClick:i,children:e.jsx(xt,{size:14})})}),e.jsx("div",{className:"studio-list",children:t.pages.map((s,n)=>e.jsxs("button",{type:"button",className:s.id===r?"on":"",onClick:()=>a(s.id),children:[e.jsx("span",{children:n+1}),e.jsxs("div",{children:[e.jsx("strong",{children:s.metadata.title}),e.jsxs("small",{children:[s.layout.items.length," components"]})]})]},s.id))})]})}function _o({usedSources:t,items:r,selected:a,query:i,loading:s,error:n,disabled:o,sourceFeedback:l,onQuery:d,onSelect:x,onAdd:b,onAddContent:m,policy:f,total:y,hasMore:u,onLoadMore:w,onEnableReview:q}){const[C,k]=p.useState("all"),M=t.filter(I=>I.kind!=="text"),L=new Set(M.flatMap(I=>[I.id,I.sourceRef])),X=r.filter(I=>C==="all"||ka(I)===C);return e.jsxs(e.Fragment,{children:[e.jsx(Br,{title:"Sources",detail:"Search governed data and add a view"}),e.jsxs("label",{className:"source-search-primary",children:[e.jsx(jt,{size:15}),e.jsx("input",{value:i,onChange:I=>d(I.target.value),placeholder:"Search blocks, metrics, or domains","aria-label":"Search governed sources"}),i?e.jsx("button",{type:"button",onClick:()=>d(""),"aria-label":"Clear source search",title:"Clear search",children:e.jsx($t,{size:13})}):null]}),e.jsxs("details",{className:"used-sources-disclosure",children:[e.jsxs("summary",{children:[e.jsxs("div",{children:[e.jsx("strong",{children:"In this App"}),e.jsx("small",{children:M.length?`${M.length} data ${M.length===1?"source":"sources"}`:"No source added yet"})]}),e.jsx("span",{children:M.length}),e.jsx(dr,{size:14})]}),M.length?e.jsx("div",{className:"used-source-list",children:M.map(I=>e.jsxs("div",{children:[e.jsx("span",{className:I.trustState,children:I.trustState==="certified"?e.jsx(Qe,{size:14}):e.jsx(mt,{size:14})}),e.jsxs("p",{children:[e.jsx("strong",{title:I.sourceRef,children:be(I.sourceRef)}),e.jsxs("small",{children:[za(I.kind)," · ",I.trustState==="certified"?"Certified":"Review required"]})]})]},I.id))}):e.jsxs("div",{className:"source-panel-state compact",children:[e.jsx(yr,{size:15}),e.jsxs("div",{children:[e.jsx("strong",{children:"No data source added yet"}),e.jsx("small",{children:"Choose a source below and add a view."})]})]})]}),f==="include_review_required"?e.jsxs("div",{className:"source-review-lane",children:[e.jsx(mt,{size:14}),e.jsxs("p",{children:[e.jsx("strong",{children:"Review-required analysis lane is on"}),e.jsx("small",{children:"Referenced DQL or exploratory SQL appears here with a review label. It remains local and cannot publish until resolved."})]})]}):null,e.jsxs("div",{className:"source-catalog-toolbar",children:[e.jsx("div",{className:"source-view-tabs",role:"tablist","aria-label":"Filter sources by recommended view",children:[["all","All"],["kpi","KPI"],["chart","Charts"],["table","Tables"]].map(([I,O])=>e.jsx("button",{type:"button",role:"tab","aria-selected":C===I,className:C===I?"on":"",onClick:()=>k(I),children:O},I))}),e.jsx("small",{"aria-live":"polite",children:s?"Finding…":`${X.length} of ${y} ${y===1?"result":"results"}`})]}),s?e.jsxs("div",{className:"source-panel-state",children:[e.jsx(ht,{size:16}),e.jsxs("div",{children:[e.jsx("strong",{children:"Finding governed sources"}),e.jsx("small",{children:"Matching certified blocks and semantic data to this App decision."})]})]}):null,!s&&n?e.jsxs("div",{className:"source-panel-state error",children:[e.jsx($t,{size:16}),e.jsxs("div",{children:[e.jsx("strong",{children:"Sources could not load"}),e.jsx("small",{children:n})]})]}):null,!s&&!n&&X.length===0?e.jsxs("div",{className:"source-panel-state",children:[e.jsx(jt,{size:16}),e.jsxs("div",{children:[e.jsx("strong",{children:i.trim()||C!=="all"?"No source matches these filters":"No governed source matched yet"}),e.jsx("small",{children:i.trim()||C!=="all"?"Clear the search or choose All to see every governed source.":"Refine the business decision or enable the review-required lane for additional local options."})]})]}):null,e.jsx("div",{className:"source-catalog-list",children:X.map(I=>{var S,h;const O=ka(I),F=(a==null?void 0:a.id)===I.id,U=I.sourceId??I.id,_=L.has(U)||L.has(I.id)||L.has(I.name),A=((S=I.eligibility)==null?void 0:S.localPreview)===!1&&f==="governed_only",te=(l==null?void 0:l.sourceId)===U?l:null,Q=(te==null?void 0:te.status)??"idle",Y=ln({view:Sa(O),status:Q,reviewRequired:A,alreadyUsed:_,pageTitle:te==null?void 0:te.pageTitle});return e.jsxs("article",{className:`source-catalog-row ${F?"on":""}`,children:[e.jsxs("button",{type:"button",className:"source-catalog-summary",onClick:()=>x(I),"aria-label":`View ${I.name} source details`,"aria-expanded":F,children:[e.jsx("span",{className:I.status==="certified"?"certified":"review",children:I.status==="certified"?e.jsx(Qe,{size:14}):e.jsx(mt,{size:14})}),e.jsxs("div",{children:[e.jsx("strong",{title:I.name,children:be(I.name)}),e.jsxs("small",{children:[be(I.domain)," · ",I.status==="certified"?"Certified block":"Review required",_?" · In App":""]})]})]}),e.jsxs("button",{type:"button",className:"source-add-view",disabled:o,title:A?"Enable the review lane and add this draft block in one saved change.":void 0,onClick:()=>b(I,O),"aria-label":`${Y}: ${I.name}`,children:[e.jsx(xt,{size:13})," ",Y]}),te?e.jsx("small",{className:`source-action-feedback ${te.status}`,role:te.status==="error"?"alert":"status",children:te.status==="error"?te.message:Y}):null,F?e.jsxs("div",{className:"source-catalog-detail",children:[e.jsx("p",{children:I.description||`${be(I.name)} from the ${be(I.domain)} domain.`}),A?e.jsxs("button",{type:"button",className:"review-action",onClick:q,children:[e.jsx(mt,{size:12})," Enable review-required sources"]}):null,(((h=I.filterIds)==null?void 0:h.length)??0)>0?e.jsxs("span",{children:[e.jsx(Zt,{size:12})," ",I.filterIds.length," supported ",I.filterIds.length===1?"filter":"filters"]}):null,e.jsxs("div",{className:"source-view-options","aria-label":`Add ${I.name} with another view`,children:[e.jsxs("button",{type:"button",disabled:o,"aria-label":A?`Enable review lane and add ${I.name} as KPI`:void 0,onClick:()=>b(I,"kpi"),children:[e.jsx(Vi,{size:13})," KPI"]}),e.jsxs("button",{type:"button",disabled:o,"aria-label":A?`Enable review lane and add ${I.name} as Chart`:void 0,onClick:()=>b(I,"chart"),children:[e.jsx(an,{size:13})," Chart"]}),e.jsxs("button",{type:"button",disabled:o,"aria-label":A?`Enable review lane and add ${I.name} as Table`:void 0,onClick:()=>b(I,"table"),children:[e.jsx(on,{size:13})," Table"]})]})]}):null]},I.id)})}),u?e.jsx("button",{type:"button",className:"source-load-more",onClick:w,disabled:s||o,children:s?"Loading…":"Load 50 more sources"}):null,e.jsxs("div",{className:"panel-section-label",children:[e.jsx("span",{children:"Page elements"}),e.jsx("small",{children:"No data required"})]}),e.jsxs("div",{className:"content-quick-add",children:[e.jsxs("button",{type:"button",disabled:o,onClick:()=>m("heading"),children:[e.jsx(Gs,{size:15}),e.jsxs("span",{children:[e.jsx("strong",{children:"Heading"}),e.jsx("small",{children:"Organize the story"})]}),e.jsx(xt,{size:13})]}),e.jsxs("button",{type:"button",disabled:o,onClick:()=>m("text"),children:[e.jsx(so,{size:15}),e.jsxs("span",{children:[e.jsx("strong",{children:"Text"}),e.jsx("small",{children:"Add context or guidance"})]}),e.jsx(xt,{size:13})]})]})]})}function Eo({draft:t,activePageId:r,catalog:a,candidates:i,runtimeFilterFields:s,previewRunsByPage:n,previewing:o,disabled:l,onRunPreview:d,onSave:x,onRemove:b}){const[m,f]=p.useState(null),[y,u]=p.useState(""),w=t.pages.find(h=>h.id===r)??t.pages[0],q=p.useMemo(()=>{const h=new Map;for(const $ of t.pages)for(const ee of $.filters??[]){const W=h.get(ee.id);W?W.pageIds.push($.id):h.set(ee.id,{filter:ee,pageIds:[$.id]})}return[...h.values()]},[t.pages]),C=new Set(q.map(h=>h.filter.id)),k=i.filter(h=>{const $=y.trim().toLowerCase();return!$||[h.id,...h.sourceNames].join(" ").toLowerCase().includes($)}),M=p.useMemo(()=>m!=null&&m.fieldId?Rr(t.pages,a,m.fieldId,s,t.sources):[],[a,m==null?void 0:m.fieldId,t.pages,t.sources,s]),L=(m==null?void 0:m.scope)==="page"?M.filter(h=>h.pageId===(w==null?void 0:w.id)):M,X=new Set((m==null?void 0:m.selectedMappingKeys)??[]),I=L.filter(h=>h.supported&&X.has(h.key)).length,O=L.filter(h=>h.supported).length,F=p.useMemo(()=>m!=null&&m.fieldId?Xo(m.fieldId,L.filter(h=>h.supported),n):null,[m==null?void 0:m.fieldId,n,L]),U=(m==null?void 0:m.type)==="daterange"||(m==null?void 0:m.type)==="date",A=!!(!!(U&&F&&F.compatibleComponents>0&&F.checkedComponents===F.compatibleComponents)&&(F==null?void 0:F.valueCount)===0),te=h=>{const $=Rr(t.pages,a,h.id,s,t.sources);f({id:h.id,fieldId:h.id,label:be(h.id),type:dn(h.id),scope:"app",required:!1,selectedMappingKeys:$.filter(ee=>ee.supported).map(ee=>ee.key)})},Q=h=>{var $e;const $=(($e=h.filter.field)==null?void 0:$e.name)??h.filter.bindsTo??h.filter.id,W=Rr(t.pages,a,$,s,t.sources).filter(se=>{var ue,Ae,_e,Ie;const oe=t.pages.find(xe=>xe.id===se.pageId),Be=(ue=oe==null?void 0:oe.filters)==null?void 0:ue.find(xe=>xe.id===h.filter.id);return Be?(Ae=Be.scope)!=null&&Ae.tileIds?Be.scope.tileIds.includes(se.tileId):((Ie=(_e=oe==null?void 0:oe.layout.items.find(xe=>xe.i===se.tileId))==null?void 0:_e.filterBindings)==null?void 0:Ie.some(xe=>xe.filter===h.filter.id&&xe.capability!=="unsupported"))??!1:!1});f({id:h.filter.id,fieldId:$,label:h.filter.label??be(h.filter.id),type:h.filter.type,scope:h.pageIds.length>1?"app":"page",required:h.filter.required??!1,selectedMappingKeys:W.map(se=>se.key)})},Y=h=>{if(!m)return;const $=new Set(L.filter(W=>W.supported).map(W=>W.key)),ee=new Set(m.selectedMappingKeys);for(const W of $)h?ee.add(W):ee.delete(W);f({...m,selectedMappingKeys:[...ee]})},S=h=>{if(!m||!h.supported)return;const $=new Set(m.selectedMappingKeys);$.has(h.key)?$.delete(h.key):$.add(h.key),f({...m,selectedMappingKeys:[...$]})};if(m){const h=C.has(m.id);return e.jsxs(e.Fragment,{children:[e.jsx(Br,{title:h?"Configure filter":"New filter",detail:"Choose a governed field and link its components",action:e.jsx("button",{type:"button",onClick:()=>{f(null),u("")},"aria-label":"Back to filters",children:e.jsx(_r,{size:14})})}),m.fieldId?e.jsxs("div",{className:"filter-builder",children:[e.jsxs("section",{className:"filter-builder-field",children:[e.jsx("span",{children:e.jsx(Qe,{size:15})}),e.jsxs("div",{children:[e.jsx("small",{children:"GOVERNED FIELD"}),e.jsx("strong",{children:be(m.fieldId)})]}),h?null:e.jsx("button",{type:"button",onClick:()=>f({...m,fieldId:"",selectedMappingKeys:[]}),children:"Change"})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Display label"}),e.jsx("input",{value:m.label,onChange:$=>f({...m,label:$.target.value})})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Control"}),e.jsx("select",{value:m.type,onChange:$=>f({...m,type:$.target.value}),children:Yo(m.fieldId).map($=>e.jsx("option",{value:$.value,children:$.label},$.value))})]}),U?e.jsxs("section",{className:`filter-availability ${A?"empty":F!=null&&F.dateRange?"ready":""}`,children:[e.jsx("span",{children:A?e.jsx($t,{size:14}):F!=null&&F.dateRange?e.jsx(Pt,{size:14}):e.jsx(Jt,{size:14})}),e.jsxs("div",{children:[e.jsx("strong",{children:o?"Checking available dates…":A?"No date values found":F!=null&&F.dateRange?`${F.dateRange.min} – ${F.dateRange.max}`:"Check available dates"}),e.jsx("small",{children:o?"The settled preview is checking the selected field.":A?"This field has no usable dates in the current governed result. Choose another field or refresh the data.":F!=null&&F.dateRange?`${F.valueCount} dated rows found across ${F.checkedComponents} linked ${F.checkedComponents===1?"component":"components"}.`:"Run the current page once before creating this date control."})]}),!o&&!(F!=null&&F.dateRange)?e.jsxs("button",{type:"button",onClick:d,disabled:l,children:[e.jsx(Jt,{size:12})," Run preview"]}):null]}):null,e.jsxs("fieldset",{children:[e.jsx("legend",{children:"Apply to"}),e.jsxs("div",{className:"filter-scope-switch",children:[e.jsx("button",{type:"button",className:m.scope==="page"?"on":"",onClick:()=>f({...m,scope:"page"}),children:"This page"}),e.jsx("button",{type:"button",className:m.scope==="app"?"on":"",onClick:()=>f({...m,scope:"app"}),children:"All compatible pages"})]}),e.jsx("small",{children:m.scope==="app"?"One dashboard control is added to every page with a compatible tile.":`Only ${(w==null?void 0:w.metadata.title)??"this page"} receives this control.`})]}),e.jsxs("fieldset",{className:"filter-mapping",children:[e.jsx("legend",{children:"Linked components"}),e.jsxs("header",{children:[e.jsxs("span",{children:[I,"/",O," compatible linked"]}),e.jsx("button",{type:"button",onClick:()=>Y(I!==O),children:I===O?"Clear compatible":"Link all compatible"})]}),e.jsx("div",{children:t.pages.filter($=>m.scope==="app"||$.id===(w==null?void 0:w.id)).map($=>{const ee=L.filter(W=>W.pageId===$.id);return ee.length?e.jsxs("section",{children:[e.jsx("small",{children:$.metadata.title}),ee.map(W=>e.jsxs("label",{className:W.supported?"":"unsupported",title:W.reason,children:[e.jsx("input",{type:"checkbox",checked:W.supported&&X.has(W.key),disabled:!W.supported,onChange:()=>S(W)}),e.jsxs("span",{children:[e.jsx("strong",{children:be(W.tileTitle)}),e.jsx("small",{children:W.supported?`${be(W.sourceName)} · ${W.mode==="semantic"?"semantic":"column"} binding`:W.reason})]}),W.supported?e.jsx(Pt,{size:13}):e.jsx($t,{size:13})]},W.key))]},$.id):null})})]}),e.jsxs("label",{className:"filter-required",children:[e.jsx("input",{type:"checkbox",checked:m.required,onChange:$=>f({...m,required:$.target.checked})}),e.jsxs("span",{children:[e.jsx("strong",{children:"Require a value"}),e.jsx("small",{children:"Publication and runs require this filter to be set."})]})]}),e.jsxs("div",{className:"filter-builder-actions",children:[e.jsx("button",{type:"button",onClick:()=>f(null),children:"Cancel"}),e.jsx("button",{type:"button",className:"primary",disabled:l||!m.label.trim()||I===0||A,onClick:()=>{x(m),f(null)},children:h?"Save filter":"Create filter"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"filter-field-search",children:[e.jsx(jt,{size:14}),e.jsx("input",{autoFocus:!0,value:y,onChange:$=>u($.target.value),placeholder:"Search governed columns"})]}),e.jsx("div",{className:"filter-field-results",children:k.filter($=>!C.has($.id)).map($=>e.jsxs("button",{type:"button",onClick:()=>te($),children:[e.jsx("span",{children:e.jsx(Zt,{size:14})}),e.jsxs("div",{children:[e.jsx("strong",{children:be($.id)}),e.jsx("small",{children:$.sourceNames.map(be).join(", ")}),e.jsxs("em",{children:[$.affectedTileCount," compatible · ",$.pageCount," ",$.pageCount===1?"page":"pages"]})]}),e.jsx(dr,{size:13})]},$.id))}),k.filter($=>!C.has($.id)).length===0?e.jsx("p",{className:"panel-empty",children:"No additional governed filter fields match this search."}):null]})]})}return e.jsxs(e.Fragment,{children:[e.jsx(Br,{title:"Filters",detail:"Dashboard controls linked to governed columns",action:e.jsx("button",{type:"button",disabled:l||i.length===0,onClick:()=>f({id:"",fieldId:"",label:"",type:"select",scope:"app",required:!1,selectedMappingKeys:[]}),"aria-label":"Create filter",children:e.jsx(xt,{size:14})})}),e.jsxs("div",{className:"filter-workflow","aria-label":"How App filters work",children:[e.jsxs("span",{children:[e.jsx("b",{children:"1"}),"Choose a governed column"]}),e.jsxs("span",{children:[e.jsx("b",{children:"2"}),"Link all or selected components"]}),e.jsxs("span",{children:[e.jsx("b",{children:"3"}),"Use the control directly on the canvas"]}),e.jsx("small",{children:"Changing a filter refreshes every linked tile together."})]}),q.length>0?e.jsxs("div",{className:"panel-section-label",children:[e.jsx("span",{children:"Dashboard filters"}),e.jsxs("small",{children:[q.length," configured"]})]}):null,e.jsx("div",{className:"filter-contract-list",children:q.map(h=>{var W,$e;const $=((W=h.filter.field)==null?void 0:W.name)??h.filter.bindsTo??h.filter.id,ee=fn(t,h.filter.id);return e.jsxs("article",{children:[e.jsxs("button",{type:"button",className:"filter-contract-summary",onClick:()=>Q(h),children:[e.jsx("span",{children:e.jsx(Zt,{size:14})}),e.jsxs("div",{children:[e.jsx("strong",{children:h.filter.label??be(h.filter.id)}),e.jsxs("small",{children:[be($)," · ",be(h.filter.type)]}),e.jsxs("em",{children:[ee," linked ",ee===1?"component":"components"," · ",h.pageIds.length>1?"App-wide":be((($e=t.pages.find(se=>se.id===h.pageIds[0]))==null?void 0:$e.metadata.title)??"Page")]})]}),e.jsx(_a,{size:14})]}),e.jsx("button",{type:"button",className:"filter-remove",onClick:()=>b(h.filter.id),"aria-label":`Delete ${h.filter.label??be(h.filter.id)} filter`,title:"Delete filter",children:e.jsx(ir,{size:13})})]},h.filter.id)})}),q.length===0?e.jsxs("div",{className:"filter-empty",children:[e.jsx("span",{children:e.jsx(Zt,{size:18})}),e.jsx("strong",{children:"Create a dashboard filter"}),e.jsx("p",{children:"Pick a governed column, choose a dropdown or search control, then link every compatible tile."}),e.jsxs("button",{type:"button",disabled:l||i.length===0,onClick:()=>f({id:"",fieldId:"",label:"",type:"select",scope:"app",required:!1,selectedMappingKeys:[]}),children:[e.jsx(xt,{size:13})," New filter"]})]}):null,i.length===0?e.jsx("p",{className:"panel-empty",children:"Add a governed KPI, chart, or table first. Certified filter columns and semantic dimensions will appear here."}):q.length>0?e.jsxs("button",{type:"button",className:"filter-add-another",disabled:l,onClick:()=>f({id:"",fieldId:"",label:"",type:"select",scope:"app",required:!1,selectedMappingKeys:[]}),children:[e.jsx(xt,{size:13})," Add another filter"]}):null]})}function Bo({current:t,onApply:r}){return e.jsxs(e.Fragment,{children:[e.jsx(Br,{title:"Templates",detail:"Professional analytical structures"}),e.jsx("div",{className:"template-list",children:ja.map(a=>e.jsxs("button",{type:"button",className:t===a.id?"on":"",onClick:()=>r(a.id),children:[e.jsx("span",{children:gn(a.id)}),e.jsxs("div",{children:[e.jsx("strong",{children:a.title}),e.jsx("small",{children:a.description})]})]},a.id))})]})}function Mo({draft:t,prompt:r,previewRun:a,onPrompt:i,onAskAi:s,onSourcePolicy:n,onResolveTask:o,onApproveSemantic:l}){const d=la(t),x=t.sources.some(b=>(b.kind==="governed_semantic"||b.kind==="semantic_query")&&b.reviewStatus!=="approved");return e.jsxs("div",{className:"inspector-body",children:[e.jsxs("section",{children:[e.jsx("label",{children:"Business decision"}),e.jsx("textarea",{value:r,onChange:b=>i(b.target.value),rows:5})]}),e.jsxs("section",{children:[e.jsx("label",{children:"Source policy"}),e.jsxs("select",{value:t.sourcePolicy,onChange:b=>n(b.target.value),children:[e.jsx("option",{value:"governed_only",children:"Governed sources only"}),e.jsx("option",{value:"include_review_required",children:"Include review-required analysis"})]}),e.jsx("small",{className:"field-help",children:"Review-required sources stay local and block Project publication until replaced or promoted."})]}),e.jsxs("section",{className:"frame-facts",children:[e.jsx("label",{children:"Build Frame"}),e.jsxs("div",{children:[e.jsx("span",{children:"Audience"}),e.jsx("strong",{children:t.frame.audience||"Stakeholders"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Metrics"}),e.jsx("strong",{children:t.frame.metrics.join(", ")||"Needs clarification"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Dimensions"}),e.jsx("strong",{children:t.frame.dimensions.join(", ")||"Automatic"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Source policy"}),e.jsx("strong",{children:t.sourcePolicy==="governed_only"?"Governed only":"Includes review lane"})]})]}),x?e.jsxs("section",{children:[e.jsx("label",{children:"Semantic review"}),e.jsxs("button",{type:"button",className:"review-action",onClick:l,disabled:!a,children:[e.jsx(Qe,{size:14})," ",a?"Approve this settled result":"Run preview to approve"]})]}):null,d.length?e.jsxs("section",{className:"review-task-list",children:[e.jsx("label",{children:"Review tasks"}),d.map(b=>e.jsxs("div",{children:[e.jsx("span",{children:b.message}),e.jsxs("button",{type:"button",onClick:()=>o(b),children:[e.jsx(Pt,{size:12})," Resolve"]})]},b.id))]}):null,e.jsxs("button",{type:"button",className:"ask-ai",onClick:s,children:[e.jsx(nr,{size:16})," Ask AI to compose or revise"]}),e.jsxs("section",{className:"trust-summary",children:[e.jsx(Qe,{size:17}),e.jsxs("div",{children:[e.jsx("strong",{children:"Nothing publishes silently"}),e.jsx("p",{children:"AI changes are typed diffs. Project publication revalidates live source trust and filter bindings."})]})]})]})}function Lo({tile:t,run:r,pageId:a,onUpdate:i,onDelete:s}){var f,y,u,w,q,C;const[n,o]=p.useState(t.title??""),[l,d]=p.useState(((f=t.text)==null?void 0:f.markdown)??"");p.useEffect(()=>o(t.title??""),[t.i,t.title]),p.useEffect(()=>{var k;return d(((k=t.text)==null?void 0:k.markdown)??"")},[t.i,(y=t.text)==null?void 0:y.markdown]);const x=t.viz.options??{},b=((u=r==null?void 0:r.result)==null?void 0:u.columns)??[],m=(k,M)=>i({viz:{...t.viz,options:{...x,[k]:M||void 0}}});return e.jsxs("div",{className:"inspector-body",children:[e.jsxs("section",{children:[e.jsx("label",{children:"Title"}),e.jsx("input",{value:n,onChange:k=>o(k.target.value),onBlur:()=>{n.trim()!==(t.title??"")&&i({title:n.trim()})}})]}),t.text?e.jsxs("section",{children:[e.jsx("label",{children:"Content"}),e.jsx("textarea",{rows:7,value:l,onChange:k=>d(k.target.value),onBlur:()=>{var k;l!==((k=t.text)==null?void 0:k.markdown)&&i({text:{markdown:l}})}}),e.jsx("small",{className:"field-help",children:"Safe Markdown only. Executable HTML and JavaScript are not supported."})]}):null,e.jsxs("section",{children:[e.jsx("label",{children:"Visualization"}),e.jsx("select",{value:t.viz.type,onChange:k=>i({viz:{...t.viz,type:k.target.value}}),children:["single_value","bar","line","area","scatter","heatmap","table","pivot","text","heading"].map(k=>e.jsx("option",{value:k,children:be(k)},k))})]}),t.text?null:e.jsxs("section",{className:"field-mapping",children:[e.jsx("label",{children:"Field mapping"}),e.jsxs("div",{children:[e.jsx("span",{children:"X / category"}),e.jsxs("select",{value:String(x.x??""),onChange:k=>m("x",k.target.value),children:[e.jsx("option",{value:"",children:"Auto"}),b.map(k=>e.jsx("option",{value:k,children:be(k)},k))]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Y / value"}),e.jsxs("select",{value:String(x.y??""),onChange:k=>m("y",k.target.value),children:[e.jsx("option",{value:"",children:"Auto"}),b.map(k=>e.jsx("option",{value:k,children:be(k)},k))]})]}),e.jsx("small",{className:"field-help",children:"Run preview to load the exact result fields."})]}),t.text?null:e.jsxs("section",{className:"format-grid",children:[e.jsx("label",{children:"Formatting"}),e.jsxs("div",{children:[e.jsx("span",{children:"Number"}),e.jsxs("select",{value:String(x.format??"number"),onChange:k=>m("format",k.target.value),children:[e.jsx("option",{value:"number",children:"Number"}),e.jsx("option",{value:"currency",children:"Currency"}),e.jsx("option",{value:"percent",children:"Percent"}),e.jsx("option",{value:"duration",children:"Duration"})]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Legend"}),e.jsxs("select",{value:String(x.legendPosition??"right"),onChange:k=>m("legendPosition",k.target.value),children:[e.jsx("option",{value:"top",children:"Top"}),e.jsx("option",{value:"right",children:"Right"}),e.jsx("option",{value:"bottom",children:"Bottom"}),e.jsx("option",{value:"none",children:"Hidden"})]})]})]}),e.jsxs("section",{children:[e.jsx("label",{children:"Responsive size"}),e.jsx("div",{className:"size-buttons",children:[["Compact",3,2],["Standard",6,4],["Wide",12,4],["Tall",6,7]].map(([k,M,L])=>e.jsx("button",{type:"button",onClick:()=>i({w:Number(M),h:Number(L)}),children:k},k))})]}),e.jsxs("section",{className:"data-trust",children:[e.jsx("label",{children:"Data & trust"}),e.jsxs("div",{children:[e.jsx("span",{className:`trust-dot ${t.trustState??"draft_ready"}`}),e.jsx("strong",{children:be(t.trustState??"draft_ready")})]}),e.jsx("p",{children:t.block?`${t.trustState==="certified"?"Certified":"Review-required"} block: ${"blockId"in t.block?t.block.blockId:t.block.ref}`:t.semantic?`Governed semantic query: ${t.semantic.id}`:t.draftAnalysis?`Review-required DQL: ${t.draftAnalysis.ref}`:"Local narrative component"}),(w=t.sourceEvidence)==null?void 0:w.slice(0,2).map((k,M)=>e.jsx("small",{children:k.reason},`${k.source}-${M}`)),r?e.jsx("small",{children:r.status==="ok"?`Settled on ${((q=r.result)==null?void 0:q.rowCount)??((C=r.result)==null?void 0:C.rows.length)??0} rows`:r.error}):null]}),e.jsxs("button",{type:"button",className:"delete-component",onClick:s,children:[e.jsx(ir,{size:15})," Remove component"]}),e.jsxs("small",{className:"inspector-id",children:[a," / ",t.i]})]})}function Fo({loading:t}){return t?e.jsxs("div",{className:"preview-state loading",children:[e.jsx("span",{className:"preview-loading-mark",children:e.jsx(Jt,{size:15})}),e.jsx("strong",{children:"Running governed preview…"}),e.jsx("span",{children:"Loading current data with this App’s filters and source policy."})]}):e.jsxs("div",{className:"preview-state idle",children:[e.jsx("span",{className:"preview-idle-mark",children:e.jsx(Jt,{size:15})}),e.jsx("strong",{children:"Preview is not loaded"}),e.jsx("span",{children:"App Studio runs this automatically when the data tile is added. Use Run preview to refresh an older draft."})]})}function Oo({filter:t,availability:r,value:a,applying:i,onChange:s}){var x,b,m,f,y,u;const n=t.label??be(t.id),o=Array.from(new Set([...t.options??[],...(r==null?void 0:r.values)??[]])),[l,d]=p.useState(String(a??""));if(p.useEffect(()=>d(String(a??"")),[a]),t.type==="daterange"){const w=a&&typeof a=="object"&&!Array.isArray(a)?a:{},q=i?"Checking dates…":r!=null&&r.dateRange?`Available ${r.dateRange.min} – ${r.dateRange.max}`:(r==null?void 0:r.valueCount)===0?"No date values exist for this field":"Run preview to check available dates";return e.jsxs("label",{className:`studio-filter range ${(r==null?void 0:r.valueCount)===0?"empty":""}`,"aria-busy":i,children:[e.jsx("span",{children:n}),e.jsx("input",{type:"date",min:(x=r==null?void 0:r.dateRange)==null?void 0:x.min,max:(b=r==null?void 0:r.dateRange)==null?void 0:b.max,"aria-label":`${n} start`,value:w.start??"",onChange:C=>s({...w,start:C.target.value})}),e.jsx("i",{children:"–"}),e.jsx("input",{type:"date",min:(m=r==null?void 0:r.dateRange)==null?void 0:m.min,max:(f=r==null?void 0:r.dateRange)==null?void 0:f.max,"aria-label":`${n} end`,value:w.end??"",onChange:C=>s({...w,end:C.target.value})}),e.jsx("small",{children:q})]})}if(t.type==="boolean")return e.jsxs("label",{className:"studio-filter boolean","aria-busy":i,children:[e.jsx("input",{type:"checkbox",checked:!!a,onChange:w=>s(w.target.checked)}),e.jsx("span",{children:n})]});if(t.type==="date")return e.jsxs("label",{className:`studio-filter ${(r==null?void 0:r.valueCount)===0?"empty":""}`,"aria-busy":i,children:[e.jsx("span",{children:n}),e.jsx("input",{type:"date",min:(y=r==null?void 0:r.dateRange)==null?void 0:y.min,max:(u=r==null?void 0:r.dateRange)==null?void 0:u.max,value:String(a??""),onChange:w=>s(w.target.value)}),e.jsx("small",{children:i?"Checking dates…":r!=null&&r.dateRange?`Available ${r.dateRange.min} – ${r.dateRange.max}`:(r==null?void 0:r.valueCount)===0?"No date values exist for this field":"Run preview to check available dates"})]});if(o.length>0&&(t.type==="select"||t.type==="multiselect"))return e.jsx(Wo,{label:n,values:o,value:a,multiple:t.type==="multiselect",applying:i,truncated:(r==null?void 0:r.truncated)??!1,onChange:s});if(o.length>0&&t.type==="search"){const w=`studio-filter-${t.id.replace(/[^a-z0-9_-]/gi,"-")}-options`;return e.jsxs("div",{className:"studio-filter searchable","aria-busy":i,children:[e.jsx("label",{htmlFor:`${w}-input`,children:n}),e.jsxs("span",{className:"studio-filter-combobox",children:[e.jsx(jt,{size:12,"aria-hidden":"true"}),e.jsx("input",{id:`${w}-input`,type:"search",list:w,value:l,placeholder:"All values",autoComplete:"off",onChange:q=>{const C=q.target.value;d(C),s(C)}}),e.jsx(dr,{size:12,"aria-hidden":"true"})]}),e.jsx("datalist",{id:w,children:o.map(q=>e.jsx("option",{value:q},q))}),e.jsx("small",{children:i?"Applying…":`${o.length}${r!=null&&r.truncated?"+":""} ${o.length===1&&!(r!=null&&r.truncated)?"value":"values"} · type or choose`})]})}return e.jsxs("label",{className:"studio-filter","aria-busy":i,children:[e.jsx("span",{children:n}),e.jsx("input",{type:t.type==="number"?"number":"search",value:String(a??""),placeholder:"All values",onChange:w=>s(t.type==="number"&&w.target.value!==""?Number(w.target.value):w.target.value)}),e.jsx("small",{children:i?"Applying…":"Updates automatically"})]})}function Wo({label:t,values:r,value:a,multiple:i,applying:s,truncated:n,onChange:o}){const[l,d]=p.useState(""),x=p.useRef(null),b=i?new Set(Array.isArray(a)?a.map(String):a==null||a===""?[]:[String(a)]):new Set(a==null||a===""?[]:[String(a)]),m=r.filter(u=>u.toLowerCase().includes(l.trim().toLowerCase())),f=b.size===0?"All values":i?`${b.size} selected`:[...b][0],y=u=>{if(!i){o(u),x.current&&(x.current.open=!1),d("");return}const w=new Set(b);w.has(u)?w.delete(u):w.add(u),o([...w])};return e.jsxs("details",{ref:x,className:"studio-filter dropdown","aria-busy":s,children:[e.jsxs("summary",{children:[e.jsxs("span",{children:[e.jsx("small",{children:t}),e.jsx("strong",{children:f})]}),e.jsx(dr,{size:12})]}),e.jsxs("div",{className:"studio-filter-menu",children:[e.jsxs("label",{children:[e.jsx(jt,{size:12}),e.jsx("input",{value:l,onChange:u=>d(u.target.value),placeholder:"Search values",autoComplete:"off"})]}),e.jsx("button",{type:"button",className:"filter-option-clear",onClick:()=>{o(i?[]:""),!i&&x.current&&(x.current.open=!1)},children:"All values"}),e.jsx("div",{children:m.map(u=>e.jsxs("button",{type:"button",className:b.has(u)?"on":"",onClick:()=>y(u),children:[i?e.jsx("span",{className:"filter-option-check",children:b.has(u)?e.jsx(Pt,{size:11}):null}):null,e.jsx("span",{children:u}),!i&&b.has(u)?e.jsx(Pt,{size:12}):null]},u))}),m.length===0?e.jsx("small",{children:"No matching values"}):null,e.jsx("footer",{children:s?"Applying…":`${r.length}${n?"+":""} available values`})]})]})}function Ho({tile:t,run:r,loading:a,themeMode:i}){const s=p.useRef(null),[n,o]=p.useState(560),[l,d]=p.useState(190);if(p.useEffect(()=>{const m=s.current;if(!m||typeof ResizeObserver>"u")return;const f=new ResizeObserver(([y])=>{o(Math.max(220,Math.floor(y.contentRect.width))),d(Math.max(120,Math.floor(y.contentRect.height)))});return f.observe(m),()=>f.disconnect()},[r]),!r)return e.jsx(Fo,{loading:a});if(r.status!=="ok"||!r.result)return e.jsxs("div",{className:"preview-state error",children:[e.jsx("strong",{children:be(r.status)}),e.jsx("span",{children:r.error??"This component could not run with the current source and filters."})]});const x=t.viz.type==="single_value"?"kpi":t.viz.type,b={...r.chartConfig??{},...t.viz.options??{},chart:x};return e.jsx("div",{ref:s,className:"live-component-preview",onClick:m=>m.stopPropagation(),children:x==="table"||x==="pivot"?e.jsx(Xi,{result:r.result,themeMode:i,maxHeight:l,initialPageSize:10}):e.jsx(Ji,{result:r.result,themeMode:i,chartConfig:{...b,title:void 0},availableHeight:l,availableWidth:n})})}function Br({title:t,detail:r,action:a}){return e.jsxs("header",{className:"panel-title",children:[e.jsxs("div",{children:[e.jsx("strong",{children:t}),e.jsx("small",{children:r})]}),a]})}function ni(t,r){return[{type:"set_name",name:r.name},{type:"set_template",template:r.template},{type:"set_frame",frame:r.frame},{type:"set_source_policy",sourcePolicy:r.sourcePolicy},{type:"set_requirements",requirements:r.requirements,coverage:r.coverage},...t.sources.filter(a=>!r.sources.some(i=>i.id===a.id)).map(a=>({type:"remove_source",sourceId:a.id})),...r.sources.map(a=>({type:"upsert_source",source:a})),...t.pages.filter(a=>!r.pages.some(i=>i.id===a.id)).map(a=>({type:"remove_page",pageId:a.id})),...r.pages.map(a=>({type:"upsert_page",page:a})),...t.reviewTasks.filter(a=>!r.reviewTasks.some(i=>i.id===a.id)).map(a=>({type:"remove_review_task",taskId:a.id})),...r.reviewTasks.map(a=>({type:"set_review_task",task:a}))]}function Vo(t,r,a){const i=t.layout.items.filter(l=>!(l.i.startsWith("template-")&&l.i.endsWith("-introduction")));if(r==="blank")return{...t,sections:[],layout:{...t.layout,items:Tr(i,12)}};const n={i:`template-${r}-introduction`,x:0,y:0,w:12,h:2,title:r==="investigation"?"Investigation question":"Executive context",sectionId:"exec_summary",text:{markdown:r==="executive_brief"?`# ${a}
|
|
749
|
+
`,qa=["Understanding your decision","Finding certified and draft blocks","Checking trust and capabilities","Preparing source review"];function co(t){return(Math.max(0,t)+1)%qa.length}function Ma(t){return Array.from(new Set(t.map(r=>r.trim()).filter(Boolean)))}function ri(t,r){return{kind:"propose",prompt:t,requiredSourceIds:Ma(r)}}function uo(t,r){return{kind:"revise",...t?{answers:{...t}}:{},requiredSourceIds:Ma(r)}}function xo(t,r,a){return{kind:"enable_review_and_propose",prompt:t,sourceId:r,requiredSourceIds:Ma(a)}}function ln(t){var r;return t.status==="adding"?"Adding…":t.status==="added"?`Added to ${((r=t.pageTitle)==null?void 0:r.trim())||"Overview"}`:t.status==="error"?`Try add ${t.view}`:t.reviewRequired?`Enable review lane & add ${t.view}`:t.alreadyUsed?`Add another ${t.view}`:`Add ${t.view}`}function ai(t,r){return Array.from(new Set([...t,r??""].map(a=>a.trim()).filter(Boolean)))}function go(t,r){const a=t===void 0?r?[r]:void 0:t;if(a!==void 0)return Array.from(new Set(a.map(i=>i.trim()).filter(Boolean)))}function fo(t){return t.reviewRequired&&t.sourcePolicy==="governed_only"?"enable_review_and_replan":t.alreadyProposed?"select_existing":"replan"}function mo(t){let r;const a=new Map,i=new Map,s=new Map,n=t.operations.filter(l=>l.type==="upsert_source").map(l=>l.source),o=l=>{var y,u,w,q,C,k;const d=l.block?"blockId"in l.block?l.block.blockId:l.block.ref:void 0,x=((u=(y=l.semantic)==null?void 0:y.qualifiedMetricIds)==null?void 0:u.join(", "))||((w=l.semantic)==null?void 0:w.id),b=(q=l.draftAnalysis)==null?void 0:q.ref,m=bo(l,n),f=((C=l.display)==null?void 0:C.rationale)||((k=l.sourceEvidence)==null?void 0:k.map(M=>M.reason).filter(Boolean).join(" "));i.set(l.i,{id:l.i,title:l.title||xa(l.i),visualization:xa(l.viz.type),source:d||x||b||(l.text?"Page content":"Governed source"),...m?{sourceId:m}:{},...f?{rationale:f}:{}})};for(const l of t.operations)l.type==="set_frame"?r=l.frame:l.type==="upsert_source"?s.set(l.source.id,{id:l.source.id,label:xa(l.source.qualifiedIdentity||l.source.sourceRef),sourceRef:l.source.sourceRef,kind:l.source.kind,trustState:l.source.trustState,reviewStatus:l.source.reviewStatus,componentIds:[]}):l.type==="upsert_page"?(a.set(l.page.id,{id:l.page.id,title:l.page.metadata.title}),l.page.layout.items.forEach(o)):l.type==="add_tile"&&o(l.tile);for(const l of i.values()){if(!l.sourceId)continue;const d=s.get(l.sourceId);d==null||d.componentIds.push(l.id),d&&!d.rationale&&l.rationale&&(d.rationale=l.rationale)}return{frame:r,pages:Array.from(a.values()),components:Array.from(i.values()),sources:Array.from(s.values())}}function ho(t,r,a){const i=new Set(t.sources.flatMap(n=>[n.sourceRef,n.label]).map(n=>ii(n))),s=a.trim().toLowerCase();return r.filter(n=>[n.id,n.name,n.path].some(o=>i.has(ii(o)))?!1:s?[n.name,n.domain,n.description,n.owner??"",...n.tags].join(" ").toLowerCase().includes(s):!0)}function bo(t,r){var a,i,s;if(t.sourceId)return t.sourceId;if(t.block){const n="blockId"in t.block?t.block.blockId:t.block.ref;return((a=r.find(o=>["block","certified_block","review_block"].includes(o.kind)&&o.sourceRef===n))==null?void 0:a.id)??`block:${n}`}if(t.semantic)return((i=r.find(n=>{var o;return["governed_semantic","semantic_query"].includes(n.kind)&&n.sourceRef===((o=t.semantic)==null?void 0:o.id)}))==null?void 0:i.id)??`semantic:${t.semantic.id}`;if(t.draftAnalysis)return(s=r.find(n=>{var o;return["review_block","review_dql","exploratory_sql"].includes(n.kind)&&n.sourceRef===((o=t.draftAnalysis)==null?void 0:o.ref)}))==null?void 0:s.id}function xa(t){return t.replace(/[_-]+/g," ").replace(/\b\w/g,r=>r.toUpperCase()).trim()}function ii(t){return t.trim().toLowerCase().replace(/[^a-z0-9]+/g,"")}function dn(t){return/date|time|month|week|quarter|year|created|updated|ordered|(_at|_on)$/i.test(t)?"daterange":/count|amount|limit|top_?n|score/i.test(t)?"number":"select"}function vo(t,r,a={},i=[]){var n,o;const s=new Set;for(const l of t){for(const d of l.filters??[]){const x=((n=d.field)==null?void 0:n.name)??d.bindsTo??d.id;x&&s.add(x)}for(const d of pn(l)){for(const x of cn(d,r,i))s.add(x);for(const x of((o=a[l.id])==null?void 0:o[d.i])??[])s.add(x.column);for(const x of d.filterBindings??[])x.binding&&x.capability!=="unsupported"&&s.add(x.binding)}}return[...s].map(l=>{const d=Rr(t,r,l,a,i).filter(x=>x.supported);return{id:l,sourceNames:[...new Set(d.map(x=>x.sourceName))].sort(),affectedTileCount:d.length,pageCount:new Set(d.map(x=>x.pageId)).size}}).filter(l=>l.affectedTileCount>0).sort((l,d)=>l.id.localeCompare(d.id))}function Rr(t,r,a,i={},s=[]){return t.flatMap(n=>pn(n).map(o=>{var f;const l=cn(o,r,s),d=(((f=i[n.id])==null?void 0:f[o.i])??[]).find(y=>yo(y.column,a)),x=(o.filterBindings??[]).find(y=>y.filter===a||y.binding===a),b=l.includes(a)||!!d||(x==null?void 0:x.binding)===a&&x.capability!=="unsupported",m=qo(o,r,s);return{key:wo(n.id,o.i),pageId:n.id,pageTitle:n.metadata.title,tileId:o.i,tileTitle:o.title||o.i,sourceName:m,supported:b,...b?{binding:(d==null?void 0:d.column)??a,mode:o.semantic?"semantic":(x==null?void 0:x.mode)??"predicate"}:{reason:`${a.replace(/_/g," ")} is not exposed by ${m}.`}}}))}function yo(t,r){const a=i=>{const s=i.trim().toLowerCase().replace(/["`\[\]]/g,"").split(".");return(s[s.length-1]??"").replace(/[^a-z0-9]/g,"")};return a(t)===a(r)}function wo(t,r){return`${t}:${r}`}function pn(t){return t.layout.items.filter(r=>!!(r.block||r.semantic||r.draftAnalysis))}function cn(t,r,a){const i=t.sourceId?a.find(o=>o.id===t.sourceId):void 0;if(i!=null&&i.capabilities)return[...new Set([...i.capabilities.filters,...i.capabilities.dimensions])];const s=t.block?"blockId"in t.block?t.block.blockId:t.block.ref:null,n=s?r.find(o=>o.id===s||o.name===s):null;return n?[...new Set([...n.filterIds??[],...n.dimensionIds??[]])]:t.semantic?t.semantic.dimensions??[]:t.draftAnalysis?[]:(t.filterBindings??[]).filter(o=>o.capability!=="unsupported"&&!!o.binding).map(o=>o.binding)}function qo(t,r,a){const i=t.sourceId?a.find(o=>o.id===t.sourceId):void 0;if(i)return i.qualifiedIdentity??i.sourceRef;const s=t.block?"blockId"in t.block?t.block.blockId:t.block.ref:null,n=s?r.find(o=>o.id===s||o.name===s):null;return n?n.name:t.semantic?t.semantic.id:t.draftAnalysis?t.draftAnalysis.ref:t.title||t.i}function un(t){const r=/Required App question is unresolved|Review task is still open|Run a current settled preview|requires snapshot-bound semantic approval|is review-required and cannot be published|references app-scoped exploratory DQL|Resolve required Build Frame clarifications/i,a=t.filter(i=>!r.test(i)).map(i=>{const s=i.match(/^[^/]+\/[^ ]+ does not have a preflighted binding for filter (.+)\.$/i);if(s){const o=s[1],l=t.filter(d=>d.endsWith(`binding for filter ${o}.`)).length;return{id:`filters:${o.toLowerCase()}`,title:`Limit ${o} to compatible components`,detail:`${o} is applied to ${l} ${l===1?"component that cannot":"components that cannot"} use it. Open Filters, edit ${o}, and keep only the compatible components selected.`,action:"filters"}}if(/filter|binding/i.test(i))return{id:"filters",title:"Finish filter wiring",detail:i,action:"filters"};const n=i.match(/^Source (.+?) changed after selection\.$/i);if(n){const o=jo(n[1]);return{id:`sources:${n[1]}`,title:`Review ${o}`,detail:`${o} changed since it was selected. Accept the current certified version; DQL will then request a fresh preview.`,action:"refresh_sources"}}return/does not resolve to (?:a current |a )?certified block|no longer resolves to a certified block/i.test(i)?{id:`unavailable:${i}`,title:"Replace or remove this source",detail:i,action:"sources"}:/changed after selection|certified block|source/i.test(i)?{id:"sources",title:"Review changed sources",detail:i,action:"sources"}:/preview|settled run|receipt|runtime/i.test(i)?{id:"preview",title:"Refresh the settled preview",detail:"The saved preview no longer matches the current App data contract.",action:"preview"}:{id:`validation:${i}`,title:"Complete governed validation",detail:i,action:"sources"}});return Array.from(new Map(a.map(i=>[i.id,i])).values())}function jo(t){return t.replace(/[_-]+/g," ").replace(/\b\w/g,r=>r.toUpperCase())}function La(t){return t.requirements.filter(r=>{if(!r.required||!ko(t,r))return!1;const a=t.coverage.find(i=>i.requirementId===r.id);return(a==null?void 0:a.status)!=="covered"})}function ko(t,r){return!(t.authoringMode==="manual"&&t.frame.metrics.length===0&&r.measures.length===0)}function la(t){const r=new Set(t.pages.map(s=>s.id)),a=new Set(t.pages.flatMap(s=>s.layout.items.map(n=>n.i))),i=new Set(t.sources.map(s=>s.id));return t.reviewTasks.filter(s=>s.status!=="open"?!1:!!(s.sourceId&&i.has(s.sourceId)||s.tileId&&a.has(s.tileId)||s.pageId&&r.has(s.pageId)))}function Fa(t){const r=t.previewReceipts??(t.previewReceipt?[t.previewReceipt]:[]);return t.pages.filter(a=>a.layout.items.some(s=>!s.text&&!s.aiPin)?!r.some(s=>s.pageId===a.id&&s.revision===t.revision):!1)}function da(t){return t.sources.filter(r=>r.kind==="governed_semantic"||r.kind==="semantic_query"?r.reviewStatus!=="approved"||!r.snapshotId||!r.receiptId:r.kind==="block"?r.lifecycle!=="certified"||r.trustState!=="certified"||r.reviewStatus==="required":r.kind==="certified_block"?r.lifecycle!==void 0&&r.lifecycle!=="certified"||r.trustState!=="certified"||r.reviewStatus==="required":r.kind==="review_block"||r.kind==="review_dql"||r.kind==="exploratory_sql")}function xn(t,r=[]){const a=(t.frame.clarificationQuestions??[]).filter(i=>i.required&&!i.answerId);return La(t).length+a.length+la(t).length+Fa(t).length+da(t).length+un(r).length}function So(t){const r=(t.frame.clarificationQuestions??[]).filter(l=>l.required&&!l.answerId),a=La(t),i=la(t),s=Fa(t),n=da(t),o=[];if(r.length||a.length){const l=r.length+a.length;o.push({id:"questions",title:"Confirm the App questions",detail:`${l} ${l===1?"question needs":"questions need"} an answer, governed coverage, or removal from this publish scope.`,count:l})}return i.length&&o.push({id:"review",title:"Complete scoped review",detail:`${i.length} review ${i.length===1?"task is":"tasks are"} attached to content still in this App.`,count:i.length}),s.length&&o.push({id:"preview",title:"Run a current preview",detail:`${s.length} data ${s.length===1?"page needs":"pages need"} a settled result before publication.`,count:s.length}),n.length&&o.push({id:"sources",title:"Finish source review",detail:`${n.length} ${n.length===1?"source needs":"sources need"} approval, replacement, or removal.`,count:n.length}),o}const zo=p.lazy(()=>oa(()=>import("./UnifiedAgentRunPanel-BjsTE6yf.js").then(t=>t.c),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14])).then(t=>({default:t.UnifiedAgentRunPanel}))),ja=[{id:"executive_brief",title:"Executive Brief",description:"Editorial summary, KPI band, decision evidence, and appendix."},{id:"operational_dashboard",title:"Operational Dashboard",description:"Filters, KPIs, trends, drivers, and operating detail."},{id:"investigation",title:"Investigation",description:"Question, findings, comparisons, caveats, and evidence."},{id:"blank",title:"Blank canvas",description:"Start with one clean responsive page."}];function Co({config:t,busy:r=!1,error:a,onChange:i,onSubmit:s}){var o;const n=t.mode==="ai"?!!t.prompt.trim():!!t.name.trim();return e.jsxs("section",{className:"dql-app-studio-home","aria-labelledby":"app-studio-home-title",children:[e.jsx("style",{children:ra}),e.jsxs("div",{className:"dql-studio-v2-intro",children:[e.jsxs("span",{className:"eyebrow",children:[e.jsx(ht,{size:14})," DQL App Studio 2.0"]}),e.jsxs("h1",{id:"app-studio-home-title",children:["Start with the decision.",e.jsx("br",{}),"Shape the experience together."]}),e.jsx("p",{children:"AI and manual authoring use one private draft, one responsive canvas, and one governed path to Project publication."})]}),e.jsxs("div",{className:"dql-studio-v2-start-card",children:[e.jsxs("div",{className:"mode-switch",role:"tablist","aria-label":"Authoring mode",children:[e.jsxs("button",{type:"button",role:"tab","aria-selected":t.mode==="ai",className:t.mode==="ai"?"on":"",onClick:()=>i({mode:"ai",template:t.template==="blank"?"operational_dashboard":t.template}),children:[e.jsx(ht,{size:16})," Describe with AI"]}),e.jsxs("button",{type:"button",role:"tab","aria-selected":t.mode==="manual",className:t.mode==="manual"?"on":"",onClick:()=>i({mode:"manual",template:"blank",name:t.name||"Untitled Analytics App"}),children:[e.jsx(At,{size:16})," Start manually"]})]}),e.jsxs("label",{className:"primary-field",children:[e.jsx("span",{children:t.mode==="ai"?"What decision should this App support?":"What should this App be called?"}),t.mode==="ai"?e.jsx("textarea",{value:t.prompt,onChange:l=>i({prompt:l.target.value}),placeholder:"Build a weekly revenue health App for finance leaders with trends, drivers, and customer detail.",rows:4}):e.jsx("input",{value:t.name,onChange:l=>i({name:l.target.value}),placeholder:"Revenue Operations"})]}),t.mode==="ai"?e.jsxs("div",{className:"ai-launch-explainer",children:[e.jsx("span",{children:e.jsx(ht,{size:16})}),e.jsxs("div",{children:[e.jsx("strong",{children:"AI selects governed data and creates an editable first draft"}),e.jsx("small",{children:"Next, review the actual blocks, semantic sources, components, and gaps before applying anything."})]})]}):null,e.jsxs("details",{className:"launch-options",open:t.mode==="manual",children:[e.jsxs("summary",{children:[e.jsx("span",{children:"Starting layout"}),e.jsx("strong",{children:((o=ja.find(l=>l.id===t.template))==null?void 0:o.title)??"Operational Dashboard"}),e.jsx(dr,{size:15})]}),e.jsx("div",{className:"template-grid",children:ja.map(l=>e.jsxs("button",{type:"button",className:t.template===l.id?"on":"",onClick:()=>i({template:l.id}),children:[e.jsx("span",{children:gn(l.id)}),e.jsx("strong",{children:l.title}),e.jsx("small",{children:l.description})]},l.id))})]}),e.jsxs("section",{className:"studio-source-policy-row","aria-label":"App source policy",children:[e.jsxs("header",{children:[e.jsx("span",{className:"policy-mark",children:e.jsx(Qe,{size:17})}),e.jsxs("p",{children:[e.jsx("strong",{children:"Governed sources only"}),e.jsx("small",{children:"Certified blocks and governed semantic sources. Recommended for every App."})]})]}),e.jsxs("label",{className:"studio-review-toggle",children:[e.jsx("input",{type:"checkbox",checked:t.sourcePolicy==="include_review_required",onChange:l=>i({sourcePolicy:l.target.checked?"include_review_required":"governed_only"})}),e.jsx("i",{"aria-hidden":"true"}),e.jsxs("span",{children:[e.jsx("strong",{children:"Also allow review-required analysis"}),e.jsx("small",{children:"Stays local and cannot publish until replaced, promoted, or removed."})]})]})]}),a?e.jsx("div",{className:"studio-error",role:"alert",children:a}):null,e.jsx("button",{type:"button",className:"launch-action",onClick:s,disabled:r||!n,children:r?"Preparing local draft…":t.mode==="ai"?e.jsxs(e.Fragment,{children:[e.jsx(ht,{size:17})," Generate editable App"]}):e.jsxs(e.Fragment,{children:[e.jsx(At,{size:17})," Open blank Studio"]})}),e.jsx("small",{className:"launch-next-step",children:"Private local draft first · review sources and preview results · publish only when ready"})]})]})}function Ao({activity:t,label:r,onBack:a,onReturn:i,onRetry:s}){return e.jsxs("section",{className:"dql-studio-v2-loading studio-ai-activity","aria-labelledby":"studio-ai-activity-title","aria-busy":t.status==="running",children:[e.jsx("style",{children:ra}),e.jsx("button",{type:"button",className:"icon",onClick:a,"aria-label":"Back to Apps",children:e.jsx(_r,{size:18})}),e.jsxs("div",{children:[e.jsx("span",{className:"loading-mark",children:e.jsx(ht,{size:20})}),t.status==="running"?e.jsxs(e.Fragment,{children:[e.jsx("strong",{id:"studio-ai-activity-title",children:"Preparing your editable App proposal"}),e.jsx("small",{className:"studio-ai-activity-label",role:"status","aria-live":"polite",children:r}),e.jsx("small",{children:"Sources remain governed or review-required exactly as cataloged. You will review them before the canvas is generated."})]}):e.jsxs(e.Fragment,{children:[e.jsx("strong",{id:"studio-ai-activity-title",children:"The source proposal needs another try"}),e.jsx("small",{role:"alert",children:t.error??"App Studio could not prepare the source proposal."}),e.jsxs("span",{className:"studio-ai-activity-actions",children:[i?e.jsx("button",{type:"button",onClick:i,children:"Back to source review"}):null,e.jsx("button",{type:"button",className:"primary",onClick:s,children:"Try AI proposal again"})]})]})]})]})}function Io({initialMode:t,initialPrompt:r,initialName:a="",initialDraftId:i,initialSourcePolicy:s="governed_only",initialTemplate:n,startImmediately:o=!1,baseAppId:l,domain:d,audience:x,themeMode:b,onBack:m,onPublished:f,onDraftDeleted:y}){var ei,ti;const[u,w]=p.useState(null),[q,C]=p.useState(t),[k,M]=p.useState(s),[L,X]=p.useState(n??(t==="manual"?"blank":"operational_dashboard")),[I,O]=p.useState(r),[F,U]=p.useState(a),[_,A]=p.useState("sources"),[te,Q]=p.useState(()=>typeof window>"u"||window.innerWidth>820),[Y,S]=p.useState("auto"),[h,$]=p.useState(1260),[ee,W]=p.useState("overview"),[$e,se]=p.useState(null),[oe,Be]=p.useState(null),[ue,Ae]=p.useState([]),[_e,Ie]=p.useState(""),[xe,Ze]=p.useState(),[it,R]=p.useState(0),[le,ge]=p.useState(!1),[ve,Te]=p.useState(null),[de,Pe]=p.useState(null),[Ge,Ye]=p.useState(new Set),[De,Ee]=p.useState(null),[ze,Z]=p.useState(null),[pe,ye]=p.useState(0),[Ne,We]=p.useState(null),[Me,Ue]=p.useState([]),[we,nt]=p.useState([]),[Le,re]=p.useState(!1),[lt,Ce]=p.useState(null),[bt,ie]=p.useState("Local draft"),[dt,He]=p.useState({}),[et,Re]=p.useState(!1),[gt,H]=p.useState({}),[ke,fe]=p.useState({}),[qe,zt]=p.useState(null),[vt,Vt]=p.useState(!1),[Dt,Ut]=p.useState(!1),[pr,pt]=p.useState(!1),[_t,st]=p.useState([]),[Kt,Qt]=p.useState(!1),[cr,er]=p.useState(!1),[ur,xr]=p.useState(!1),Gt=p.useRef(null),Yt=p.useRef(!1),ct=p.useRef(0),ft=p.useRef(null),Nt=p.useRef(null),N=p.useRef(null),B=Ba(`app-studio:${(u==null?void 0:u.id)??i??"new"}`);p.useEffect(()=>{const c=()=>{const v=window.innerWidth;Q(v>820)};return c(),window.addEventListener("resize",c),()=>window.removeEventListener("resize",c)},[]),p.useEffect(()=>{const c=N.current;if(!c||typeof ResizeObserver>"u")return;const v=new ResizeObserver(([z])=>$(Math.max(0,Math.floor(z.contentRect.width))));return v.observe(c),()=>v.disconnect()},[u]),p.useEffect(()=>{var v;if((ze==null?void 0:ze.status)!=="running"||(ye(0),typeof window>"u"||(v=window.matchMedia)!=null&&v.call(window,"(prefers-reduced-motion: reduce)").matches))return;const c=window.setInterval(()=>{ye(z=>co(z))},1200);return()=>window.clearInterval(c)},[ze==null?void 0:ze.status,ze==null?void 0:ze.retry.requiredSourceIds.join("|")]),p.useEffect(()=>{let c=!0;return re(!!(l||i)),D.listAppBuilds().then(async v=>{var J,ae;if(!c)return;const z=v.drafts.filter(T=>T.state!=="project_published");if(i){const T=z.find(G=>G.id===i);if(!T)throw new Error("The local App draft is no longer available.");w(T),U(T.name),W(((J=T.pages[0])==null?void 0:J.id)??"overview"),ie("Resumed local draft");return}if(!l)return;const V=z.find(T=>{var G;return((G=T.baseApp)==null?void 0:G.appId)===l})??(await D.createAppBuild({baseAppId:l,goal:I.trim()||"Edit this governed App",audience:x,domain:d,authoringMode:"manual",sourcePolicy:"governed_only",template:"blank"})).draft;c&&(w(V),U(V.name),W(((ae=V.pages[0])==null?void 0:ae.id)??"overview"),ie("Safe local edit draft"))}).catch(v=>{c&&(l||i)&&Ce(Ct(v))}).finally(()=>{c&&re(!1)}),()=>{c=!1}},[l,i]),p.useEffect(()=>{if(!u)return;let c=!0;const v=new AbortController;ge(!0),Te(null);const z=window.setTimeout(()=>{D.listAppSourceCandidates(u.id,{query:_e,limit:50},v.signal).then(P=>{c&&(Ae(P.items),Ze(P.nextCursor),R(P.total))}).catch(P=>{c&&!v.signal.aborted&&(Ae([]),Te(Ct(P)))}).finally(()=>{c&&ge(!1)})},_e?180:0);return()=>{c=!1,v.abort(),window.clearTimeout(z)}},[u==null?void 0:u.id,u==null?void 0:u.sourcePolicy,_e]),p.useEffect(()=>{const c=v=>{var P;const z=v.detail;!(z!=null&&z.draft)||z.draft.id!==(u==null?void 0:u.id)||(ct.current+=1,Re(!1),He({}),fe({}),w(z.draft),U(z.draft.name),W(z.pageId??((P=z.draft.pages[0])==null?void 0:P.id)??"overview"),se(z.tileId??null),Pe(null),ie("Ask result added · loading preview…"))};return window.addEventListener("dql-app-build-updated",c),()=>window.removeEventListener("dql-app-build-updated",c)},[u==null?void 0:u.id]);const g=p.useMemo(()=>(u==null?void 0:u.pages.find(c=>c.id===ee))??(u==null?void 0:u.pages[0])??null,[ee,u]),K=g?dt[g.id]??null:null,me=g?gt[g.id]??{}:{},rt=g?ke[g.id]??{}:{},Ve=Y==="auto"?h<720?"narrow":h<1120?"medium":"wide":Y,yt=p.useMemo(()=>{var z;if(!g)return[];const c=(z=g.layout.responsive)==null?void 0:z[Ve],v=Ve==="wide"?12:Ve==="medium"?6:1;return Tr(si((c==null?void 0:c.items)??g.layout.items,u==null?void 0:u.template),v)},[g,Ve,u==null?void 0:u.template]),Xe=(g==null?void 0:g.layout.items.find(c=>c.i===$e))??null,je=ue,wt=p.useMemo(()=>Object.fromEntries(Object.entries(dt).map(([c,v])=>[c,Object.fromEntries(v.tiles.map(z=>[z.tileId,z.filterableColumns??[]]))])),[dt]),gr=p.useMemo(()=>vo((u==null?void 0:u.pages)??[],ue,wt,(u==null?void 0:u.sources)??[]),[ue,u==null?void 0:u.pages,u==null?void 0:u.sources,wt]),ut=p.useMemo(()=>de?mo(de):null,[de]),Mt=p.useMemo(()=>u?xn(u,_t):0,[u,_t]);p.useEffect(()=>{Ye(new Set((de==null?void 0:de.defaultSelectedSourceIds)??(ut==null?void 0:ut.sources.map(c=>c.id))??[]))},[de,ut]),p.useEffect(()=>{if(!ut||oe||ue.length===0)return;const c=new Set(ut.sources.map(z=>z.label.toLowerCase())),v=ue.find(z=>c.has(be(z.name).toLowerCase()))??ue.find(z=>ut.components.some(P=>P.source===z.id||P.source===z.name));v&&Be(v)},[ue,ut,oe]);const Or=async()=>{var c;re(!0),Ce(null);try{const v=await D.createAppBuild({baseAppId:l??void 0,name:F.trim()||void 0,goal:I.trim()||F.trim()||"Create a governed analytical App",audience:x,domain:d,authoringMode:q,sourcePolicy:k,template:L});w(v.draft),U(v.draft.name),W(((c=v.draft.pages[0])==null?void 0:c.id)??"overview"),ie("Saved locally"),He({}),H({}),fe({}),q==="ai"&&(ye(0),Z({status:"running",retry:ri(I,[]),returnToProposal:!1}),await tr(v.draft,I,[],!1))}catch(v){Ce(Ct(v))}finally{re(!1)}},tr=async(c=u,v=I,z,P=!!de)=>{if(!c)return!1;const V=go(z,oe==null?void 0:oe.id),J=ri(v,V??[]);ye(0),Z({status:"running",retry:J,returnToProposal:P}),re(!0),Ce(null);try{const ae=await D.proposeAppBuildChanges(c.id,{prompt:v.trim()||c.frame.goal,expectedRevision:c.revision,proposalHash:c.proposalHash,selectedBlockIds:V});return Pe(ae.proposal),Z(null),Qt(!1),ie("AI plan ready for review"),!0}catch(ae){const T=Ct(ae);return ie("AI proposal needs attention"),Z({status:"error",retry:J,returnToProposal:P,error:T}),!1}finally{re(!1)}},jr=async(c,v=Array.from(Ge),z=!0)=>{if(!u||!de)return!1;const P=Array.from(new Set(v.filter(Boolean))),V=uo(c,P);z&&(ye(0),Z({status:"running",retry:V,returnToProposal:!0})),re(!0),Ce(null);try{const J=await D.reviseAppBuildProposal(u.id,de.id,{expectedRevision:u.revision,expectedProposalHash:u.proposalHash,answers:c,selectedSourceIds:P});return Pe(J.proposal),z&&Z(null),ie("AI proposal revised on the server"),!0}catch(J){const ae=Ct(J);return z?Z({status:"error",retry:V,returnToProposal:!0,error:ae}):Ce(ae),!1}finally{re(!1)}},pa=async c=>{if(!(!u||!de)){re(!0),Ce(null);try{const v=await D.generateAppBuildGap(u.id,de.id,{expectedRevision:u.revision,expectedProposalHash:u.proposalHash,requirementId:c});Pe(v.proposal),ie("Review-required gap added to the proposal")}catch(v){Ce(Ct(v))}finally{re(!1)}}},kr=async(c,v,z)=>{if(!u||!de||!ut)return;const P=ai(Ge,c),V=fo({alreadyProposed:ut.sources.some(J=>J.id===c),reviewRequired:v,sourcePolicy:u.sourcePolicy});if(z&&Be(z),V==="select_existing"){Ye(J=>new Set([...J,c]));return}Ee(c);try{if(V==="enable_review_and_replan"){const J=xo(I,c,P);ye(0),Z({status:"running",retry:J,returnToProposal:!0});const ae=await Fe([{type:"set_source_policy",sourcePolicy:"include_review_required"}]);if(!ae){Z({status:"error",retry:J,returnToProposal:!0,error:"The review lane could not be enabled. Your existing proposal is unchanged."});return}await tr(ae,I,P,!0)}else await jr(void 0,P,!1)}finally{Ee(null)}},ca=c=>{const v=c.retry;if(v.kind==="revise"){jr(v.answers,v.requiredSourceIds,!0);return}if(v.kind==="enable_review_and_propose"){kr(v.sourceId,!0);return}tr(u,v.prompt,v.requiredSourceIds,c.returnToProposal)};p.useEffect(()=>{!o||i||l||u||Yt.current||(Yt.current=!0,Or())},[l,u,i,o]);const Fe=async(c,v=!0)=>{if(!u||c.length===0)return null;re(!0),ie("Saving…"),Ce(null);try{const z=u,P=c.every(Vo),V=await D.patchAppBuild(u.id,u.revision,c,u.proposalHash);return w(V.draft),P||(ct.current+=1,He({}),fe({}),Re(!1)),v&&(Ue(J=>[...J.slice(-29),z]),nt([])),ie("Saved locally"),V.draft}catch(z){return ie("Save failed"),Ce(Ct(z)),null}finally{re(!1)}},Wr=async()=>{if(!(!de||!u)){re(!0),Ce(null),ie("Composing App…");try{const c=u,z=(await D.composeAppBuild(u.id,{mode:"ai",expectedRevision:u.revision,expectedProposalHash:u.proposalHash,proposalId:de.id,selectedSourceIds:Array.from(Ge)})).draft;w(z),Ue(V=>[...V.slice(-29),c]),nt([]),He({}),fe({}),Pe(null),U(z.name);const P=z.pages[0];W((P==null?void 0:P.id)??ee),P&&Cr(P)&&(ie("App generated · loading governed data…"),await Xt(z,P.id))}catch(c){ie("Compose failed"),Ce(Ct(c))}finally{re(!1)}}},Hr=async()=>{if(!u||Me.length===0)return;const c=Me[Me.length-1],v=u;await Fe(ni(v,c),!1)&&(Ue(P=>P.slice(0,-1)),nt(P=>[...P,v]))},Vr=async()=>{if(!u||we.length===0)return;const c=we[we.length-1],v=u;await Fe(ni(v,c),!1)&&(nt(P=>P.slice(0,-1)),Ue(P=>[...P,v]))},Sr=async()=>{var V;if(!u)return;const c=u.pages.length+1,v=`page-${c}`,z={version:2,id:v,metadata:{title:`Page ${c}`,description:"Responsive analytical page",domain:(V=u.pages[0])==null?void 0:V.metadata.domain,audience:u.frame.audience,visibility:"private",lifecycle:"draft"},layout:{kind:"grid",cols:12,rowHeight:80,items:[],responsive:{wide:{kind:"grid",cols:12,rowHeight:80,items:[]},medium:{kind:"grid",cols:6,rowHeight:80,items:[]},narrow:{kind:"grid",cols:1,rowHeight:80,items:[]}}}};await Fe([{type:"upsert_page",page:z}])&&W(v)},j=c=>{Be(c),Ce(null)},E=async()=>{if(!(!u||!xe||le)){ge(!0),Te(null);try{const c=await D.listAppSourceCandidates(u.id,{query:_e,cursor:xe,limit:50});Ae(v=>{const z=new Set(v.map(P=>P.id));return[...v,...c.items.filter(P=>!z.has(P.id))]}),Ze(c.nextCursor),R(c.total)}catch(c){Te(Ct(c))}finally{ge(!1)}}},ce=async(c,v)=>{var Ke;if(!u||!g)return;const z=c==="heading"||c==="text"?null:v===void 0?oe:v;if(c!=="heading"&&c!=="text"&&!z){A("sources"),Q(!0),Ce("Choose a governed source, then use Add to page.");return}if(z){const tt=z.sourceId??z.id,he=Sa(c),ot=((Ke=z.eligibility)==null?void 0:Ke.localPreview)===!1&&u.sourcePolicy==="governed_only";Be(z),Nt.current!==null&&window.clearTimeout(Nt.current),We({sourceId:tt,status:"adding",view:he,pageTitle:g.metadata.title}),re(!0),ie("Composing source…"),Ce(null);try{const Tt=u,Lt=await D.composeAppBuild(u.id,{mode:"manual",expectedRevision:u.revision,expectedProposalHash:u.proposalHash,enableReviewRequired:ot,selections:[{sourceId:tt,pageId:g.id,view:c}]});w(Lt.draft),Ue(Ft=>[...Ft.slice(-29),Tt]),nt([]),se(Lt.tileIds[0]??null),We({sourceId:tt,status:"added",view:he,pageTitle:g.metadata.title}),Nt.current=window.setTimeout(()=>{We(Ft=>(Ft==null?void 0:Ft.sourceId)===tt?null:Ft),Nt.current=null},1800),ie(`${c==="chart"?"Chart":be(c)} added · loading data…`),ct.current+=1,He({}),fe({}),await Xt(Lt.draft,g.id)}catch(Tt){const Lt=Ct(Tt);ie("Compose failed"),We({sourceId:tt,status:"error",view:he,pageTitle:g.metadata.title,message:Lt}),Ce(Lt)}finally{re(!1)}return}if(c!=="heading"&&c!=="text")return;const P=`${c}-${Date.now().toString(36)}`,V=12,J=c==="heading"?1:2,ae=g.layout.items.reduce((tt,he)=>Math.max(tt,he.y+he.h),0),T={i:P,x:0,y:ae,w:V,h:J,title:c==="heading"?"Section heading":"Narrative",text:{markdown:c==="heading"?"## New section":"Add context, interpretation, or guidance."},sourceClass:"narrative",viz:{type:c==="heading"?"heading":"text"},trustState:"draft_ready",reviewStatus:"draft_ready"},G=[{type:"add_tile",pageId:g.id,tile:T}];await Fe(G)&&(se(P),ie(`${be(c)} added`))},Se=async()=>{if(!g||!u)return;const c=Tr(si(g.layout.items,u.template),12);await Fe([{type:"set_layout",pageId:g.id,layout:{...g.layout,items:c}}])&&ie("Page arranged · preview preserved")},Rt=async c=>{if(!u||!g)return;const v=new Set(c.selectedMappingKeys),z=Rr(u.pages,ue,c.fieldId,wt,u.sources);if(z.filter(T=>T.supported&&v.has(T.key)).length===0){Ce("Link this filter to at least one compatible component.");return}const V=[];for(const T of u.pages){const G=z.filter(he=>he.pageId===T.id),ne=G.filter(he=>he.supported&&v.has(he.key)),Ke=ne.length>0&&(c.scope==="app"||T.id===g.id),tt=(T.filters??[]).some(he=>he.id===c.id);Ke?V.push({type:"set_filter",pageId:T.id,filter:{id:c.id,label:c.label.trim()||be(c.fieldId),type:c.type,bindsTo:c.fieldId,field:{name:c.fieldId},required:c.required,multiple:c.type==="multiselect",scope:{page:T.id,tileIds:ne.map(he=>he.tileId)},optionSource:{mode:"distinct_query",field:c.fieldId,limit:100}}}):tt&&V.push({type:"remove_filter",pageId:T.id,filterId:c.id});for(const he of T.layout.items.filter(ot=>ot.block||ot.semantic||ot.draftAnalysis)){const ot=G.find(Ft=>Ft.tileId===he.i),Tt=he.filterBindings??[],Lt=Tt.filter(Ft=>Ft.filter!==c.id);Ke&&(ot!=null&&ot.supported)&&v.has(ot.key)&&Lt.push({filter:c.id,binding:ot.binding??c.fieldId,mode:ot.mode??"predicate",required:c.required,capability:"preflight_required"}),JSON.stringify(Lt)!==JSON.stringify(Tt)&&V.push({type:"update_tile",pageId:T.id,tileId:he.i,patch:{filterBindings:Lt}})}}const J=await Fe(V);if(!J)return;H(T=>Object.fromEntries(Object.entries(T).map(([G,ne])=>{var he,ot;if((ot=(he=J.pages.find(Tt=>Tt.id===G))==null?void 0:he.filters)!=null&&ot.some(Tt=>Tt.id===c.id))return[G,ne];const{[c.id]:Ke,...tt}=ne;return[G,tt]})));const ae=J.pages.find(T=>T.id===g.id);ae&&Cr(ae)?(ie(`${c.label.trim()||be(c.fieldId)} filter linked · refreshing ${fn(J,c.id)} components…`),await Xt(J,g.id,gt[g.id]??{})):ie(`${c.label.trim()||be(c.fieldId)} filter saved`)},Kr=async c=>{if(!u||!g)return;const v=[];for(const J of u.pages){(J.filters??[]).some(ae=>ae.id===c)&&v.push({type:"remove_filter",pageId:J.id,filterId:c});for(const ae of J.layout.items.filter(T=>{var G;return(G=T.filterBindings)==null?void 0:G.some(ne=>ne.filter===c)}))v.push({type:"update_tile",pageId:J.id,tileId:ae.i,patch:{filterBindings:(ae.filterBindings??[]).filter(T=>T.filter!==c)}})}const z=Object.fromEntries(Object.entries(gt).map(([J,ae])=>{const{[c]:T,...G}=ae;return[J,G]}));H(z),fe(J=>Object.fromEntries(Object.entries(J).map(([ae,T])=>{const{[c]:G,...ne}=T;return[ae,ne]})));const P=await Fe(v),V=P==null?void 0:P.pages.find(J=>J.id===g.id);P&&V&&Cr(V)?(ie(`${be(c)} filter removed · refreshing linked components…`),await Xt(P,g.id,z[g.id]??{})):P&&ie(`${be(c)} filter removed`)},fr=async c=>{if(!u||!g)return;const v=[{type:"set_template",template:c},{type:"upsert_page",page:Ho(g,c,u.name)}];await Fe(v)},Fn=async c=>{const v=Gt.current??qe;if(!g||!v||v===c)return;const z=[...g.layout.items],P=z.findIndex(G=>G.i===v),V=z.findIndex(G=>G.i===c);if(P<0||V<0)return;const[J]=z.splice(P,1);z.splice(V,0,J);const ae=z.map((G,ne)=>({...G,x:0,y:ne})),T=await Fe([{type:"set_layout",pageId:g.id,layout:{...g.layout,items:Tr(ae,12)}}]);Gt.current=null,zt(null),T&&ie("Layout saved · preview preserved")},Za=async()=>{if(!u||!g||!K){Ce("Run this page successfully before approving governed semantic results.");return}const c=[];for(const z of u.sources.filter(P=>P.kind==="governed_semantic"||P.kind==="semantic_query"))c.push({type:"upsert_source",source:{...z,snapshotId:K.snapshotId,receiptId:K.runId,reviewStatus:"approved"}});for(const z of g.layout.items.filter(P=>P.semantic&&K.tiles.some(V=>V.tileId===P.i&&V.status==="ok")))c.push({type:"update_tile",pageId:g.id,tileId:z.i,patch:{semantic:{...z.semantic,snapshotId:K.snapshotId},review:{status:"approved",sourceFingerprint:z.semantic.definitionFingerprint,preflightReceiptId:K.runId,reviewedAt:new Date().toISOString(),reviewedBy:"local-author"}}});await Fe(c)&&ie("Semantic results approved · run preview once more")},On=async()=>{if(!u)return;const c=da(u).filter(T=>T.kind!=="governed_semantic"&&T.kind!=="semantic_query");if(c.length===0)return;const v=new Set(c.map(T=>T.id)),z=new Set(c.flatMap(T=>[T.id,T.sourceRef,T.id.replace(/^[^:]+:/,"")])),P=u.pages.flatMap(T=>T.layout.items.filter(G=>{var tt;const ne=G.block?"blockId"in G.block?G.block.blockId:G.block.ref:null;return[(tt=G.draftAnalysis)==null?void 0:tt.ref,ne].filter(he=>!!he).some(he=>z.has(he)||z.has(he.replace(/^[^:]+:/,"")))}).map(G=>({pageId:T.id,tileId:G.i}))),V=new Set(P.map(T=>T.tileId)),J=[...P.map(T=>({type:"remove_tile",pageId:T.pageId,tileId:T.tileId})),...c.map(T=>({type:"remove_source",sourceId:T.id})),...u.reviewTasks.filter(T=>T.sourceId&&v.has(T.sourceId)||T.tileId&&V.has(T.tileId)).map(T=>({type:"remove_review_task",taskId:T.id})),{type:"set_coverage",coverage:u.coverage.map(T=>{const G=T.sourceIds.filter(Ke=>!v.has(Ke)),ne=T.componentIds.filter(Ke=>!V.has(Ke));return{...T,sourceIds:G,componentIds:ne,...T.status==="covered"&&(G.length===0||ne.length===0)?{status:"gap",reasons:[...T.reasons,"Review-required local analysis was removed from the publication draft."]}:{}}})}];await Fe(J)&&(st([]),ie("Local analysis removed · Undo is available"))},zr=async(c=!0,v=u)=>{var z,P;if(v){re(!0),Ce(null);try{if(c&&v.state==="preflight_ready"&&So(v).length===0&&_t.length===0){const ae=await D.publishAppBuild(v.id,v.revision,v.proposalHash);w(ae.draft),pt(!1),f(ae.app,(z=ae.draft.pages[0])==null?void 0:z.id);return}const V=await D.preflightAppBuild(v.id,v.revision,v.proposalHash);if(w(V.draft),!c){st([]),pt(!0);return}const J=await D.publishAppBuild(V.draft.id,V.draft.revision,V.draft.proposalHash);w(J.draft),pt(!1),f(J.app,(P=J.draft.pages[0])==null?void 0:P.id)}catch(V){const J=V instanceof Dn&&V.details&&typeof V.details=="object"?V.details:null,ae=Array.isArray(J==null?void 0:J.errors)?J.errors.filter(T=>typeof T=="string"&&T.trim().length>0):[];ae.length?(J!=null&&J.draft&&typeof J.draft=="object"&&w(J.draft),st(ae),pt(!0)):Ce(`Project publication needs attention. ${Ct(V)}`)}finally{re(!1)}}},Wn=async c=>{if(!u)return;await Fe([{type:"set_requirements",requirements:u.requirements.map(z=>z.id===c?{...z,required:!1}:z),coverage:u.coverage}])&&st([])},Hn=c=>{if(!u)return;const v=`Revise this App so it can answer this publish question with governed evidence: ${c}`;O(v),pt(!1),tr(u,v)},Vn=async(c,v)=>{if(!u)return;const z=(u.frame.clarificationQuestions??[]).map(V=>V.id===c?{...V,answerId:v}:V);await Fe([{type:"set_frame",frame:{...u.frame,clarificationQuestions:z}}])&&st([])},Kn=async()=>{var ae,T;if(!u)return;const c=[],v=u.sources.filter(G=>G.kind==="block"||G.kind==="certified_block"||G.kind==="review_block"),z=await D.resolveAppSourceCandidates(u.id,v.map(G=>G.id)),P=new Map(z.items.map(G=>[G.id,G])),V=v.filter(G=>!P.has(G.id));if(V.length){pt(!1),A("sources"),Q(!0),Ce(`${V.map(G=>be(G.sourceRef)).join(", ")} ${V.length===1?"is":"are"} no longer certified. Replace or remove ${V.length===1?"this source":"these sources"} before publication.`);return}for(const G of v){const ne=P.get(G.id);ne&&ne.lifecycle==="certified"&&(G.sourceRevision!==ne.sourceRevision||G.trustState!=="certified"||G.reviewStatus!=="not_required")&&c.push({type:"upsert_source",source:{...G,kind:"block",sourceRef:ne.path,sourcePath:ne.path,executionRef:ne.path,qualifiedIdentity:ne.qualifiedIdentity,snapshotId:ne.snapshotId,sourceRevision:ne.sourceRevision,sourceFingerprint:ne.sourceRevision,lifecycle:"certified",capabilities:ne.capabilities,trustState:"certified",reviewStatus:"not_required"}})}for(const G of u.pages)for(const ne of G.layout.items){if(!ne.sourceId)continue;const Ke=P.get(ne.sourceId);!Ke||Ke.lifecycle!=="certified"||(ne.sourceRevision!==Ke.sourceRevision||((ae=ne.review)==null?void 0:ae.sourceFingerprint)!==Ke.sourceRevision||((T=ne.review)==null?void 0:T.status)!=="not_required")&&c.push({type:"update_tile",pageId:G.id,tileId:ne.i,patch:{sourceRevision:Ke.sourceRevision,block:{ref:Ke.path},sourceClass:"certified_block",trustState:"certified",reviewStatus:"certified",review:{...ne.review,status:"not_required",sourceFingerprint:Ke.sourceRevision}}})}if(!c.length){st([]),ie("Certified sources are already current"),await zr(!1);return}await Fe(c)&&(st([]),ie("Source trust refreshed · run preview again"))},Qn=async()=>{if(u){re(!0),Ce(null);try{const c=await D.deleteAppBuild(u.id,u.revision,u.proposalHash);y({appName:u.name,recoveryId:c.recoveryId})}catch(c){Ut(!1),Ce(Ct(c))}finally{re(!1)}}};async function Xt(c,v,z){var J;const P=c.pages.find(ae=>ae.id===v);if(!P)return null;const V=ct.current+1;ct.current=V,W(P.id),Re(!0),Ce(null);try{const ae=z??gt[P.id]??{},T=await D.runAppBuildPreview(c.id,P.id,ae);if(V!==ct.current)return null;const G=await D.patchAppBuild(c.id,c.revision,[{type:"set_preview_receipt",receipt:{id:T.runId,pageId:P.id,revision:c.revision,snapshotId:T.snapshotId,filterFingerprint:T.filterFingerprint,resultFingerprint:T.resultFingerprint,createdAt:new Date().toISOString()}}],c.proposalHash);return V!==ct.current?null:(w(G.draft),He(ne=>({...ne,[P.id]:T})),(J=T.filterOptions)!=null&&J.length&&fe(ne=>{const Ke={...ne[P.id]??{}};for(const tt of T.filterOptions??[]){const he=Ke[tt.filterId];Ke[tt.filterId]={values:Array.from(new Set([...(he==null?void 0:he.values)??[],...tt.values])).sort((ot,Tt)=>ot.localeCompare(Tt,void 0,{numeric:!0,sensitivity:"base"})),truncated:!!(he!=null&&he.truncated||tt.truncated),valueCount:tt.valueCount??(he==null?void 0:he.valueCount),dateRange:Xo(he==null?void 0:he.dateRange,tt.dateRange)}}return{...ne,[P.id]:Ke}}),ie(`Preview settled · ${T.tiles.filter(ne=>ne.status==="ok").length}/${T.tiles.length} ready`),G.draft)}catch(ae){return V===ct.current&&Ce(Ct(ae)),null}finally{V===ct.current&&Re(!1)}}const Da=async(c=g==null?void 0:g.id)=>{!u||!c||await Xt(u,c)},Gn=async c=>{if(!u||!c)return;const v=await Xt(u,c);v&&(st([]),await zr(!1,v))},Yn=async()=>{if(!u)return;let c=u;const v=c.pages.filter(z=>Cr(z));for(const z of v){const P=await Xt(c,z.id,gt[z.id]??{});if(!P)return;c=P}st([]),await zr(!1,c)},Xn=(c,v)=>{if(!u||!g)return;const z=g.id,P=new Set(u.pages.filter(T=>{var G;return(G=T.filters)==null?void 0:G.some(ne=>ne.id===c.id)}).map(T=>T.id)),V={...gt};for(const T of P)V[T]={...V[T]??{},[c.id]:v};const J=V[z]??{[c.id]:v};H(V),He(T=>{const G={...T};for(const ne of P)delete G[ne];return G}),ct.current+=1,Re(!1),ft.current!==null&&window.clearTimeout(ft.current);const ae=c.type==="daterange"&&v&&typeof v=="object"&&!Array.isArray(v)?v:null;if(ae&&!!ae.start!=!!ae.end){ie(`Choose both ${c.label??be(c.id)} dates`);return}ie(`${c.label??be(c.id)} changed · applying automatically…`),ft.current=window.setTimeout(()=>{ft.current=null,Xt(u,z,J)},320)};if(p.useEffect(()=>{if(!u||!g||de||et||dt[g.id]||!Cr(g))return;const c=window.setTimeout(()=>{Xt(u,g.id,gt[g.id]??{})},0);return()=>window.clearTimeout(c)},[g==null?void 0:g.id,u==null?void 0:u.revision,de]),p.useEffect(()=>()=>{ft.current!==null&&window.clearTimeout(ft.current),Nt.current!==null&&window.clearTimeout(Nt.current)},[]),!u)return e.jsxs("div",{className:"dql-studio-v2-loading",children:[e.jsx("style",{children:ra}),e.jsx("button",{type:"button",className:"icon",onClick:m,"aria-label":"Back to Apps",children:e.jsx(_r,{size:18})}),e.jsxs("div",{children:[e.jsx("span",{className:"loading-mark",children:e.jsx(At,{size:20})}),e.jsx("strong",{children:lt?"Studio could not open":i?"Opening your local draft…":l?"Preparing a safe edit draft…":"Preparing your Build Frame…"}),e.jsx("small",{children:lt??"Keeping all work local until you explicitly publish it to the Project."}),lt?e.jsx("button",{type:"button",onClick:()=>{Yt.current=!1,Or()},children:"Try again"}):null]})]});if(ze)return e.jsx(Ao,{activity:ze,label:qa[pe]??qa[0],onBack:m,onReturn:ze.returnToProposal&&de?()=>Z(null):void 0,onRetry:()=>ca(ze)});const Qr=oe?ka(oe):null,Ua=(oe==null?void 0:oe.sourceId)??(oe==null?void 0:oe.id),mr=(Ne==null?void 0:Ne.sourceId)===Ua?Ne:null,Jn=oe&&Qr?ln({view:Sa(Qr),status:(mr==null?void 0:mr.status)??"idle",reviewRequired:((ei=oe.eligibility)==null?void 0:ei.localPreview)===!1&&u.sourcePolicy==="governed_only",alreadyUsed:u.sources.some(c=>c.id===Ua||c.sourceRef===oe.path),pageTitle:mr==null?void 0:mr.pageTitle}):"";return e.jsxs("div",{className:`dql-studio-v2 ${de?"proposal-focus":""}`,children:[e.jsx("style",{children:ra}),e.jsxs("header",{className:"studio-topbar",children:[e.jsxs("div",{className:"studio-brand",children:[e.jsx("button",{type:"button",className:"icon",onClick:m,children:e.jsx(_r,{size:17})}),e.jsx("span",{className:"mark",children:e.jsx(At,{size:16})}),e.jsxs("div",{children:[e.jsx("input",{value:F||u.name,onChange:c=>U(c.target.value),onBlur:()=>{F.trim()&&F.trim()!==u.name&&Fe([{type:"set_name",name:F.trim()}])}}),e.jsx("small",{children:bt})]})]}),de?e.jsxs("div",{className:"proposal-focus-title",children:[e.jsx("small",{children:"AI APP BUILD · STEP 2"}),e.jsx("strong",{children:"Choose proposed sources"})]}):e.jsxs("nav",{className:"page-nav","aria-label":"App pages",children:[u.pages.map(c=>e.jsx("button",{type:"button",className:(g==null?void 0:g.id)===c.id?"on":"",onClick:()=>{W(c.id),se(null)},children:c.metadata.title},c.id)),e.jsx("button",{type:"button",className:"icon",onClick:()=>void Sr(),"aria-label":"Add page",children:e.jsx(xt,{size:15})})]}),de?e.jsxs("div",{className:"proposal-focus-status",children:[e.jsx(Qe,{size:14}),e.jsx("span",{children:"Private draft · nothing generated yet"})]}):e.jsxs("div",{className:"studio-actions",children:[e.jsx("button",{type:"button",className:"icon",disabled:!Me.length||Le,onClick:()=>void Hr(),title:"Undo",children:e.jsx(oo,{size:16})}),e.jsx("button",{type:"button",className:"icon",disabled:!we.length||Le,onClick:()=>void Vr(),title:"Redo",children:e.jsx(Ds,{size:16})}),e.jsxs("div",{className:"breakpoints",children:[e.jsx("button",{type:"button",className:Y==="auto"?"on":"",onClick:()=>S("auto"),title:"Fit to available canvas",children:e.jsx(At,{size:15})}),e.jsx("button",{type:"button",className:Y==="wide"?"on":"",onClick:()=>S("wide"),title:"Wide preview",children:e.jsx(Zn,{size:15})}),e.jsx("button",{type:"button",className:Y==="medium"?"on":"",onClick:()=>S("medium"),title:"Tablet preview",children:e.jsx(Js,{size:15})}),e.jsx("button",{type:"button",className:Y==="narrow"?"on":"",onClick:()=>S("narrow"),title:"Phone preview",children:e.jsx(ro,{size:15})})]}),e.jsxs("button",{type:"button",className:`copilot ${Kt?"on":""}`,onClick:()=>Qt(c=>!c),"aria-pressed":Kt,"aria-label":"Open App Copilot",children:[e.jsx(nr,{size:14}),e.jsx("span",{children:"App Copilot"})]}),e.jsxs("button",{type:"button",className:"preview",onClick:()=>void Da(),disabled:et||Le,"aria-label":et?"Running preview":"Run preview",children:[e.jsx(Jt,{size:13}),e.jsx("span",{children:et?"Running…":"Run preview"})]}),e.jsxs("button",{type:"button",className:"publish",onClick:()=>void zr(!1),disabled:Le,"aria-label":`Review and publish to Project${Mt?`, ${Mt} ${Mt===1?"fix":"fixes"} needed`:""}`,children:[e.jsx(bs,{size:13}),e.jsx("span",{children:"Publish to Project"}),Mt?e.jsxs("small",{children:[Mt," ",Mt===1?"fix":"fixes"]}):null]}),e.jsx("button",{type:"button",className:"icon overflow-button","aria-label":"More draft actions","aria-expanded":vt,onClick:()=>Vt(c=>!c),children:e.jsx(ta,{size:17})}),vt?e.jsx("div",{className:"studio-overflow-menu",role:"menu",children:e.jsxs("button",{type:"button",role:"menuitem",onClick:()=>{Vt(!1),Ut(!0)},children:[e.jsx(ir,{size:14})," Delete local draft"]})}):null]})]}),de?null:e.jsxs("aside",{className:"studio-left",children:[e.jsx("nav",{children:[["sources",yr,"Sources"],["pages",At,"Pages"],["filters",Zt,"Filters"],["templates",mt,"Design"]].map(([c,v,z])=>e.jsxs("button",{type:"button",className:_===c&&te?"on":"",onClick:()=>{window.innerWidth<=820&&_===c?Q(P=>!P):(A(c),Q(!0))},children:[e.jsx(v,{size:17}),e.jsx("span",{children:z})]},c))}),e.jsxs("section",{className:`left-content ${te?"open":""}`,children:[e.jsx("button",{type:"button",className:"mobile-drawer-close",onClick:()=>Q(!1),"aria-label":"Close Studio drawer",children:e.jsx($t,{size:16})}),_==="pages"?e.jsx(Po,{draft:u,activePageId:g==null?void 0:g.id,onOpen:W,onAdd:()=>void Sr()}):null,_==="sources"?e.jsx($o,{usedSources:u.sources,items:je,selected:oe,query:_e,loading:le,error:ve,disabled:Le||et,sourceFeedback:Ne,onQuery:Ie,onSelect:j,onAdd:(c,v)=>void ce(v,c),onAddContent:c=>void ce(c,null),policy:u.sourcePolicy,total:it,hasMore:!!xe,onLoadMore:()=>void E(),onEnableReview:()=>void Fe([{type:"set_source_policy",sourcePolicy:"include_review_required"}])}):null,_==="filters"?e.jsx(_o,{draft:u,activePageId:g==null?void 0:g.id,catalog:ue,candidates:gr,runtimeFilterFields:wt,previewRunsByPage:dt,previewing:et,disabled:Le||et,onRunPreview:()=>void Da(),onSave:c=>void Rt(c),onRemove:c=>void Kr(c)}):null,_==="templates"?e.jsx(Eo,{current:u.template,onApply:c=>void fr(c)}):null]})]}),e.jsxs("main",{ref:N,className:"studio-workspace",children:[lt?e.jsxs("div",{className:"studio-error floating",role:"alert",children:[lt,e.jsx("button",{type:"button",onClick:()=>Ce(null),children:"×"})]}):null,de&&ut?e.jsx(Ro,{proposal:de,summary:ut,catalog:ue,catalogQuery:_e,sourcePolicy:u.sourcePolicy,selectedSourceIds:Ge,addingSourceId:De,busy:Le,onRevise:()=>void tr(u,I,ai(Ge),!0),onApply:()=>void Wr(),onDismiss:()=>Pe(null),onCatalogQuery:Ie,onAddSource:c=>{var v;return void kr(c.sourceId??c.id,((v=c.eligibility)==null?void 0:v.localPreview)===!1,c)},onAddProposalSource:(c,v)=>void kr(c,v),onAnswerClarification:(c,v)=>void jr({[c]:v}),onGenerateGap:c=>void pa(c),onToggleSource:c=>Ye(v=>{const z=new Set(v);return z.has(c)?z.delete(c):z.add(c),z})}):null,de?null:e.jsxs("div",{className:`studio-canvas-frame ${Ve} preview-mode-${Y}`,children:[e.jsxs("div",{className:"studio-canvas-label",children:[e.jsxs("div",{children:[e.jsxs("span",{children:[Y==="auto"?"Fit canvas":`${Ve.charAt(0).toUpperCase()+Ve.slice(1)} preview`," · ",Ve==="wide"?"12 columns":Ve==="medium"?"6 columns":"1 column"]}),e.jsx("small",{children:"Drag components to reorder · saved instantly"})]}),e.jsxs("button",{type:"button",onClick:()=>void Se(),disabled:!(g!=null&&g.layout.items.length)||Le,title:"Compact gaps and restore a clean reading order",children:[e.jsx(At,{size:13})," Auto arrange"]})]}),e.jsxs("section",{className:"studio-canvas","aria-label":"App canvas",children:[e.jsxs("header",{className:"studio-page-heading",children:[e.jsxs("div",{children:[e.jsx("small",{children:"APP PAGE"}),e.jsx("span",{children:(g==null?void 0:g.metadata.title)??"Overview"})]}),e.jsxs("small",{children:[u.frame.audience||"Stakeholders"," · ",((ti=u.pages[0])==null?void 0:ti.metadata.domain)||"General"]})]}),oe&&Qr?e.jsxs("div",{className:"studio-source-ready",children:[e.jsxs("div",{children:[e.jsx("span",{className:"certified",children:e.jsx(Qe,{size:14})}),e.jsxs("p",{children:[e.jsx("small",{children:"Selected data"}),e.jsx("strong",{children:be(oe.name)})]})]}),e.jsxs("span",{className:"studio-source-actions",children:[e.jsxs("button",{type:"button",disabled:Le||et,onClick:()=>void ce(Qr,oe),children:[e.jsx(xt,{size:14})," ",Jn]}),e.jsx("button",{type:"button",className:"source-clear",onClick:()=>Be(null),"aria-label":"Clear selected data",children:e.jsx($t,{size:14})})]})]}):null,((g==null?void 0:g.filters)??[]).length?e.jsx("div",{className:"studio-page-filterbar",children:g.filters.map(c=>e.jsx(Fo,{filter:c,availability:rt[c.id],value:me[c.id]??c.default,applying:et,onChange:v=>Xn(c,v)},c.id))}):null,e.jsxs("div",{className:"studio-page-grid",children:[yt.map(c=>e.jsxs("article",{role:"button",tabIndex:0,draggable:!0,className:`studio-component-card ${$e===c.i?"selected":""} ${qe===c.i?"dragging":""}`,style:{"--studio-tile-width":Math.min(c.w,Ve==="medium"?6:Ve==="narrow"?1:12),minHeight:Ve==="narrow"?Math.max(180,c.h*58):Math.max(150,c.h*68)},onDragStart:()=>{Gt.current=c.i,zt(c.i)},onDragEnd:()=>{Gt.current=null,zt(null)},onDragOver:v=>v.preventDefault(),onDrop:v=>{v.preventDefault(),Fn(c.i)},onClick:()=>se(c.i),onKeyDown:v=>{(v.key==="Enter"||v.key===" ")&&se(c.i)},children:[e.jsxs("header",{children:[e.jsx("span",{className:"drag-handle","aria-hidden":"true",children:"⠿"}),e.jsx("span",{className:`trust-dot ${c.trustState??"draft_ready"}`})," ",e.jsx("strong",{children:c.title||be(c.i)}),e.jsx("small",{children:c.viz.type.replace(/_/g," ")})]}),Ko(c).map(v=>e.jsxs("div",{className:"tile-filter-notice",children:[e.jsx(Zt,{size:11}),e.jsx("span",{children:v.unsupportedReason??`${be(v.filter)} does not affect this component.`})]},v.filter)),c.text?e.jsx("div",{className:c.viz.type==="heading"?"tile-heading":"tile-text",children:c.text.markdown.replace(/^#+\s*/,"")}):e.jsx(Wo,{tile:c,run:K==null?void 0:K.tiles.find(v=>v.tileId===c.i),loading:et,themeMode:b})]},c.i)),yt.length?null:e.jsxs("div",{className:"empty-canvas",children:[e.jsx("span",{children:e.jsx(xt,{size:22})}),e.jsx("strong",{children:"Build this page"}),e.jsx("p",{children:"Open Sources on the left, choose governed data, and add its recommended view. You can also add text or a heading."}),e.jsx("button",{type:"button",onClick:()=>{A("sources"),Q(!0)},children:"Open Sources"})]})]})]})]})]}),de?null:e.jsxs("aside",{className:`studio-right ${Xe?"has-selection":""}`,children:[e.jsxs("header",{children:[e.jsxs("div",{children:[e.jsx(_a,{size:16}),e.jsx("strong",{children:Xe?"Component properties":"App Build Frame"})]}),e.jsx("button",{type:"button",className:"icon",onClick:()=>se(null),"aria-label":Xe?"Close component properties":"More App settings",children:Xe?e.jsx($t,{size:16}):e.jsx(ta,{size:16})})]}),Xe&&g?e.jsx(Mo,{tile:Xe,run:K==null?void 0:K.tiles.find(c=>c.tileId===Xe.i),pageId:g.id,onUpdate:c=>void Fe([{type:"update_tile",pageId:g.id,tileId:Xe.i,patch:c}]),onDelete:()=>void Fe([{type:"remove_tile",pageId:g.id,tileId:Xe.i}]).then(()=>se(null))}):e.jsx(Bo,{draft:u,prompt:I,previewRun:K,onPrompt:O,onAskAi:()=>void tr(),onSourcePolicy:c=>void Fe([{type:"set_source_policy",sourcePolicy:c}]),onResolveTask:c=>void Fe([{type:"set_review_task",task:{...c,status:"resolved"}}]),onApproveSemantic:()=>void Za()})]}),Kt&&!de?e.jsx(Ea,{t:Ht[b],title:"App Copilot",subtitle:u.name,dock:"overlay",expanded:cr,onToggleExpanded:()=>er(c=>!c),onNewChat:B.resetThreadId,onClose:()=>Qt(!1),running:ur,resizable:!0,minResizeWidth:390,maxResizeWidth:1100,ariaLabel:"App Copilot",className:"studio-copilot-panel",style:{top:58,bottom:0,height:"auto"},children:e.jsx(p.Suspense,{fallback:e.jsx("div",{className:"studio-copilot-loading",children:"Loading App Copilot…"}),children:e.jsx(zo,{themeMode:b,title:"App Copilot",scopeHint:`Draft · ${(g==null?void 0:g.metadata.title)??"Overview"}`,composerPlaceholder:"Ask about this App, its sources, filters, results, or a deeper business question…",emptyHint:"Ask a detailed question about the current draft. Copilot uses the App Build Frame, selected governed sources, filters, and settled preview evidence.",audience:"stakeholder",initialMode:"auto",selectedObject:oe?{kind:"block",id:oe.id,title:oe.name}:{kind:"app",id:u.appId,title:u.name},workspaceContext:To(u,g,oe,Xe,K),threadId:B.threadId,onThreadIdChange:B.onThreadIdChange,onRunningChange:xr,answerFirstCards:!0,examplePrompts:[{label:"Explain the planned story",prompt:"Explain the business story this App currently tells, the evidence behind it, and what is still missing."},{label:"Check source wiring",prompt:"Which governed source supports each component and filter in this App? Call out unsupported or review-required wiring."},{label:"Go deeper",prompt:"What deeper driver question should I investigate next based on this App and its current preview evidence?"}]})})}):null,pr?e.jsx(No,{draft:u,serverIssues:_t,busy:Le||et,previewRun:K,onClose:()=>pt(!1),onRetry:()=>void zr(!0),onRunPreview:c=>void Gn(c),onRunAllPreviews:()=>void Yn(),onRemoveRequirement:c=>void Wn(c),onReviseRequirement:Hn,onAnswerQuestion:(c,v)=>void Vn(c,v),onResolveTask:c=>void Fe([{type:"set_review_task",task:{...c,status:"resolved"}}]).then(v=>{v&&st([])}),onOpenSources:()=>{pt(!1),A("sources"),Q(!0)},onOpenFilters:()=>{pt(!1),A("filters"),Q(!0)},onRefreshSources:()=>void Kn(),onApproveSemantic:()=>void Za(),onRemoveLocalAnalysis:()=>void On()}):null,Dt?e.jsx("div",{className:"proposal-scrim",role:"dialog","aria-modal":"true","aria-label":"Delete local App draft",children:e.jsxs("section",{className:"studio-delete-card",children:[e.jsx("span",{className:"delete-mark",children:e.jsx(ir,{size:18})}),e.jsx("h2",{children:"Delete this local draft?"}),e.jsxs("p",{children:[e.jsx("strong",{children:u.name})," will leave the App list. Its pages, components, and local history move to a recovery bundle so you can Undo."]}),e.jsxs("footer",{children:[e.jsx("button",{type:"button",onClick:()=>Ut(!1),disabled:Le,children:"Cancel"}),e.jsx("button",{type:"button",className:"danger",onClick:()=>void Qn(),disabled:Le,children:Le?"Deleting…":"Delete draft"})]})]})}):null]})}function No({draft:t,serverIssues:r,busy:a,previewRun:i,onClose:s,onRetry:n,onRunPreview:o,onRunAllPreviews:l,onRemoveRequirement:d,onReviseRequirement:x,onAnswerQuestion:b,onResolveTask:m,onOpenSources:f,onOpenFilters:y,onRefreshSources:u,onApproveSemantic:w,onRemoveLocalAnalysis:q}){const C=La(t),k=(t.frame.clarificationQuestions??[]).filter(A=>A.required&&!A.answerId),M=la(t),L=Fa(t),X=da(t),I=X.filter(A=>A.kind==="governed_semantic"||A.kind==="semantic_query"),O=X.filter(A=>A.kind!=="governed_semantic"&&A.kind!=="semantic_query"),F=un(r),U=C.length===0&&k.length===0&&M.length===0&&L.length===0&&X.length===0&&F.length===0,_=xn(t,r);return e.jsx("div",{className:"proposal-scrim",role:"dialog","aria-modal":"true","aria-labelledby":"publish-readiness-title",children:e.jsxs("section",{className:"studio-readiness-card",children:[e.jsxs("header",{children:[e.jsx("span",{className:U?"ready":"",children:U?e.jsx(Pt,{size:19}):e.jsx(Qe,{size:19})}),e.jsxs("div",{children:[e.jsx("h2",{id:"publish-readiness-title",children:U?"Ready to publish":`${_} ${_===1?"fix":"fixes"} before publishing`}),e.jsx("p",{children:U?"Every governed publication check passed.":"Complete the actions below. Each action updates this review automatically; there is no separate recheck loop."})]}),e.jsx("button",{type:"button",className:"icon",onClick:s,"aria-label":"Close publish checklist",children:e.jsx($t,{size:16})})]}),e.jsxs("div",{className:"readiness-body",children:[k.map(A=>e.jsxs("section",{className:"readiness-item",children:[e.jsx("span",{className:"step-mark",children:e.jsx(nr,{size:15})}),e.jsxs("div",{children:[e.jsx("strong",{children:"Choose what you mean"}),e.jsx("p",{children:A.question}),e.jsx("div",{className:"readiness-choices",children:A.choices.map(te=>e.jsx("button",{type:"button",onClick:()=>b(A.id,te.id),disabled:a,children:te.label},te.id))})]})]},A.id)),C.map(A=>e.jsxs("section",{className:"readiness-item",children:[e.jsx("span",{className:"step-mark",children:e.jsx(ht,{size:15})}),e.jsxs("div",{children:[e.jsx("strong",{children:"Unanswered App question"}),e.jsx("p",{children:A.question}),e.jsx("small",{children:"DQL will not pretend that an unrelated tile covers this question."}),e.jsxs("div",{className:"readiness-actions",children:[e.jsxs("button",{type:"button",className:"primary",onClick:()=>x(A.question),disabled:a,children:[e.jsx(nr,{size:13})," Revise with AI"]}),e.jsx("button",{type:"button",onClick:()=>d(A.id),disabled:a,children:"Remove from publish scope"})]})]})]},A.id)),M.map(A=>e.jsxs("section",{className:"readiness-item",children:[e.jsx("span",{className:"step-mark",children:e.jsx(mt,{size:15})}),e.jsxs("div",{children:[e.jsx("strong",{children:"Scoped review"}),e.jsx("p",{children:A.message}),e.jsx("div",{className:"readiness-actions",children:e.jsxs("button",{type:"button",className:"primary",onClick:()=>m(A),disabled:a,children:[e.jsx(Pt,{size:13})," Mark resolved"]})})]})]},A.id)),L.map(A=>e.jsxs("section",{className:"readiness-item",children:[e.jsx("span",{className:"step-mark",children:e.jsx(Jt,{size:15})}),e.jsxs("div",{children:[e.jsxs("strong",{children:["Run ",A.metadata.title||A.id]}),e.jsx("p",{children:"Settle the current data, filters, and component results before publishing this page."}),e.jsx("div",{className:"readiness-actions",children:e.jsxs("button",{type:"button",className:"primary",onClick:()=>o(A.id),disabled:a,children:[e.jsx(Jt,{size:13})," ",a?"Running…":"Run preview"]})})]})]},A.id)),I.length?e.jsxs("section",{className:"readiness-item",children:[e.jsx("span",{className:"step-mark",children:e.jsx(Qe,{size:15})}),e.jsxs("div",{children:[e.jsx("strong",{children:"Approve governed semantic results"}),e.jsx("p",{children:I.map(A=>be(A.sourceRef)).join(", ")}),e.jsx("small",{children:"Approval binds the source to the settled snapshot you reviewed."}),e.jsxs("div",{className:"readiness-actions",children:[i?e.jsxs("button",{type:"button",className:"primary",onClick:w,disabled:a,children:[e.jsx(Qe,{size:13})," Approve settled result"]}):e.jsxs("button",{type:"button",onClick:()=>{var A;return o(((A=t.pages[0])==null?void 0:A.id)??"")},disabled:a,children:[e.jsx(Jt,{size:13})," Run preview first"]}),e.jsx("button",{type:"button",onClick:f,children:"Open Sources"})]})]})]}):null,O.length?e.jsxs("section",{className:"readiness-item warning",children:[e.jsx("span",{className:"step-mark",children:e.jsx(mt,{size:15})}),e.jsxs("div",{children:[e.jsx("strong",{children:"Local analysis cannot publish"}),e.jsx("p",{children:O.map(A=>be(A.sourceRef)).join(", ")}),e.jsx("small",{children:"Replace it with governed data, or remove it from this draft. Removal is saved locally and can be undone from the Studio toolbar."}),e.jsxs("div",{className:"readiness-actions",children:[e.jsxs("button",{type:"button",className:"primary",onClick:f,children:[e.jsx(yr,{size:13})," Replace with governed data"]}),e.jsxs("button",{type:"button",onClick:q,disabled:a,children:[e.jsx(ir,{size:13})," Remove local analysis"]})]})]})]}):null,F.map(A=>e.jsxs("section",{className:"readiness-item",children:[e.jsx("span",{className:"step-mark",children:e.jsx(_a,{size:15})}),e.jsxs("div",{children:[e.jsx("strong",{children:A.title}),e.jsx("p",{children:A.detail}),e.jsx("div",{className:"readiness-actions",children:A.action==="filters"?e.jsxs("button",{type:"button",className:"primary",onClick:y,children:[e.jsx(Zt,{size:13})," Open Filters"]}):A.action==="refresh_sources"?e.jsxs("button",{type:"button",className:"primary",onClick:u,disabled:a,children:[e.jsx(Qe,{size:13})," Accept current certified source"]}):A.action==="preview"?e.jsxs("button",{type:"button",className:"primary",onClick:l,disabled:a,children:[e.jsx(Jt,{size:13})," ",a?"Refreshing previews…":"Refresh all page previews"]}):e.jsxs("button",{type:"button",className:"primary",onClick:f,children:[e.jsx(yr,{size:13})," Replace or remove source"]})})]})]},A.id)),U?e.jsxs("div",{className:"readiness-ready",children:[e.jsx(Pt,{size:18}),e.jsxs("div",{children:[e.jsx("strong",{children:"Governed checks passed"}),e.jsx("span",{children:"The published package will be Git-reviewable and no files are auto-staged or committed."})]})]}):null]}),e.jsxs("footer",{children:[e.jsx("button",{type:"button",onClick:s,disabled:a,children:"Back to editing"}),U?e.jsx("button",{type:"button",className:"primary",onClick:n,disabled:a,children:a?"Publishing…":"Publish to Project"}):e.jsx("span",{className:"readiness-footer-hint",children:"Choose a fix above. This review updates as you work."})]})]})})}function Ro({proposal:t,summary:r,catalog:a,catalogQuery:i,sourcePolicy:s,selectedSourceIds:n,addingSourceId:o,busy:l,onRevise:d,onApply:x,onDismiss:b,onCatalogQuery:m,onAddSource:f,onAddProposalSource:y,onAnswerClarification:u,onGenerateGap:w,onToggleSource:q}){var Y;const C=t.clarifications.filter(S=>S.required&&!S.answerId),k=t.operations.find(S=>S.type==="set_requirements"),M=(k==null?void 0:k.type)==="set_requirements"?k.requirements.filter(S=>{var h;return(h=k.coverage)==null?void 0:h.some($=>$.requirementId===S.id&&$.status==="gap")}):[],L=r.components.filter(S=>!S.sourceId||n.has(S.sourceId)),X=r.sources.filter(S=>n.has(S.id)),I=r.sources.filter(S=>!n.has(S.id)),O=ho(r,a,i).slice(0,10),F=i.trim().toLowerCase(),U=S=>!F||[S.label,S.sourceRef,za(S.kind),S.rationale??"",...r.components.filter(h=>h.sourceId===S.id).flatMap(h=>[h.title,h.visualization])].join(" ").toLowerCase().includes(F),_=X.filter(U),A=I.filter(U),te=S=>{const h=r.components.filter($=>$.sourceId===S.id);return h.length?`Creates ${h.length} ${h.length===1?"view":"views"}: ${h.map($=>$.title).join(", ")}`:"AI will use this source as governed context."},Q=(S,h)=>{const $=S.trustState!=="certified"&&s==="governed_only",ee=o===S.id;return e.jsxs("article",{className:`proposal-source-row ${h?"selected":""}`,children:[e.jsx("span",{className:`proposal-source-trust ${S.trustState}`,children:S.trustState==="certified"?e.jsx(Qe,{size:15}):e.jsx(mt,{size:15})}),e.jsxs("div",{children:[e.jsx("strong",{children:S.label}),e.jsxs("small",{children:[za(S.kind)," · ",S.trustState==="certified"?"Certified":"Review required"]}),e.jsx("p",{children:te(S)})]}),e.jsx("button",{type:"button",className:h?"remove":"add",disabled:l,title:$?"Enable the local review lane and rebuild the proposal with this source.":void 0,onClick:()=>h?q(S.id):y(S.id,$),"aria-label":`${h?"Remove":$?"Enable review lane and add":"Add"} ${S.label}${r.sources.filter(W=>W.label===S.label).length>1?` for ${r.components.filter(W=>W.sourceId===S.id).map(W=>W.title).join(", ")||S.id}`:""}`,children:h?e.jsxs(e.Fragment,{children:[e.jsx($t,{size:13})," Remove"]}):ee?"Adding…":$?"Enable review lane & add":e.jsxs(e.Fragment,{children:[e.jsx(xt,{size:13})," Add"]})})]},S.id)};return e.jsxs("section",{className:"studio-ai-plan proposal-source-picker","aria-labelledby":"proposal-source-title",children:[e.jsxs("header",{children:[e.jsx("span",{children:e.jsx(ht,{size:18})}),e.jsxs("div",{children:[e.jsx("small",{children:"REVIEW BEFORE GENERATION"}),e.jsx("h1",{id:"proposal-source-title",children:"Choose proposed sources"}),e.jsxs("p",{children:["AI understood: ",e.jsx("strong",{children:((Y=r.frame)==null?void 0:Y.goal)??"Build a governed analytics App"}),". Select the data you trust; DQL will generate the App only after you continue."]})]}),e.jsx("button",{type:"button",onClick:b,"aria-label":"Back to App decision",children:e.jsx($t,{size:16})})]}),e.jsxs("div",{className:"proposal-source-summary","aria-label":"AI proposal summary",children:[e.jsxs("span",{children:[e.jsx("strong",{children:X.length})," selected sources"]}),e.jsxs("span",{children:[e.jsx("strong",{children:L.length})," planned views"]}),e.jsxs("span",{children:[e.jsx("strong",{children:s==="governed_only"?"Governed only":"Review lane enabled"})," source policy"]})]}),e.jsxs("div",{className:"proposal-source-body",children:[e.jsxs("label",{className:"proposal-source-search",children:[e.jsx(jt,{size:15}),e.jsx("input",{value:i,onChange:S=>m(S.target.value),placeholder:"Search proposed and available sources","aria-label":"Search proposed and available sources"})]}),e.jsxs("section",{className:"proposal-source-group","aria-labelledby":"selected-proposal-sources",children:[e.jsxs("div",{className:"proposal-source-heading",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"selected-proposal-sources",children:"Selected for this App"}),e.jsx("p",{children:"Remove anything you do not want AI to use."})]}),e.jsx("strong",{children:X.length})]}),e.jsxs("div",{className:"proposal-source-list",children:[_.map(S=>Q(S,!0)),X.length?null:e.jsxs("div",{className:"proposal-source-empty",children:[e.jsx(yr,{size:18}),e.jsxs("div",{children:[e.jsx("strong",{children:"Select at least one source"}),e.jsx("p",{children:"Add an AI suggestion or another governed block below."})]})]}),X.length>0&&!_.length?e.jsx("p",{className:"studio-ai-plan-empty",children:"No selected source matches this search."}):null]})]}),A.length?e.jsxs("section",{className:"proposal-source-group","aria-labelledby":"ai-source-suggestions",children:[e.jsxs("div",{className:"proposal-source-heading",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"ai-source-suggestions",children:"AI suggestions"}),e.jsx("p",{children:"Sources removed from the selection remain available here."})]}),e.jsx("strong",{children:I.length})]}),e.jsx("div",{className:"proposal-source-list",children:A.map(S=>Q(S,!1))})]}):null,e.jsxs("section",{className:"proposal-source-group","aria-labelledby":"available-proposal-sources",children:[e.jsxs("div",{className:"proposal-source-heading",children:[e.jsxs("div",{children:[e.jsx("h2",{id:"available-proposal-sources",children:"More App sources"}),e.jsx("p",{children:"Add a certified block, or explicitly open the local review lane for a draft."})]}),e.jsx("strong",{children:O.length})]}),e.jsxs("div",{className:"proposal-catalog-list",children:[O.map(S=>{var h,$;return e.jsxs("article",{children:[e.jsx("span",{className:S.status==="certified"?"certified":"review_required",children:S.status==="certified"?e.jsx(Qe,{size:14}):e.jsx(mt,{size:14})}),e.jsxs("div",{children:[e.jsx("strong",{children:be(S.name)}),e.jsxs("small",{children:[S.domain||"General"," · ",S.status==="certified"?"Certified block":"Review required"]}),e.jsx("p",{children:S.description||S.reasons[0]||"Available governed data source"})]}),e.jsx("button",{type:"button",onClick:()=>f(S),disabled:l,title:((h=S.eligibility)==null?void 0:h.localPreview)===!1?"Enable the local review lane and rebuild the proposal with this source.":void 0,children:o===(S.sourceId??S.id)?"Adding…":(($=S.eligibility)==null?void 0:$.localPreview)===!1?"Enable review lane & add":e.jsxs(e.Fragment,{children:[e.jsx(xt,{size:13})," Add"]})})]},S.id)}),O.length?null:e.jsx("p",{className:"studio-ai-plan-empty",children:i.trim()?"No additional source matches this search.":"All available governed sources are already proposed."})]})]}),s==="include_review_required"?e.jsxs("div",{className:"studio-ai-review-lane",children:[e.jsx(mt,{size:14}),e.jsxs("p",{children:[e.jsx("strong",{children:"Review-required analysis is enabled"}),e.jsx("small",{children:"It stays clearly labeled and cannot be published to the Project until it is replaced, promoted, or removed."})]})]}):e.jsxs("div",{className:"studio-ai-review-lane",children:[e.jsx(mt,{size:14}),e.jsxs("p",{children:[e.jsx("strong",{children:"Draft sources require an explicit review lane"}),e.jsx("small",{children:"Use “Enable review lane & add” on the draft you want. Its trust does not change."})]})]}),M.length?e.jsxs("section",{className:"studio-ai-questions",children:[e.jsxs("header",{children:[e.jsx("strong",{children:"Uncovered requirements"}),e.jsxs("small",{children:[M.length," gaps"]})]}),M.map(S=>e.jsxs("div",{children:[e.jsx("p",{children:S.question}),e.jsx("button",{type:"button",onClick:()=>w(S.id),disabled:l||s!=="include_review_required",children:s==="include_review_required"?"Explicitly generate review-required DQL":"Enable review lane to generate"})]},S.id))]}):null,C.length?e.jsxs("section",{className:"studio-ai-questions",children:[e.jsxs("header",{children:[e.jsx("strong",{children:"AI needs one more decision"}),e.jsxs("small",{children:[C.length," required"]})]}),C.map(S=>e.jsxs("fieldset",{children:[e.jsx("legend",{children:S.question}),S.choices.map(h=>e.jsxs("button",{type:"button",onClick:()=>u(S.id,h.id),disabled:l,children:[e.jsx("strong",{children:h.label}),h.description?e.jsx("small",{children:h.description}):null]},h.id))]},S.id)),e.jsx("button",{type:"button",onClick:d,disabled:l,children:l?"Updating…":"Re-run proposal"})]}):null]}),e.jsxs("footer",{children:[e.jsxs("span",{children:[X.length," sources · ",L.length," views will be generated"]}),e.jsx("button",{type:"button",onClick:b,children:"Back to decision"}),e.jsxs("button",{type:"button",className:"primary",onClick:x,disabled:l||C.length>0||X.length===0,children:[e.jsx(ht,{size:14})," ",l?"Generating…":`Generate App with ${X.length} ${X.length===1?"source":"sources"}`]})]})]})}function To(t,r,a,i,s){return{surface:"app-studio",appBuildId:t.id,appId:t.appId,appName:t.name,authoringMode:t.authoringMode,sourcePolicy:t.sourcePolicy,state:t.state,buildFrame:t.frame,requirements:t.requirements,coverage:t.coverage,sources:t.sources.map(n=>({id:n.id,kind:n.kind,sourceRef:n.sourceRef,trustState:n.trustState,reviewStatus:n.reviewStatus})),page:r?{id:r.id,title:r.metadata.title,filters:r.filters,components:r.layout.items.map(n=>({id:n.i,title:n.title,visualization:n.viz.type,trustState:n.trustState}))}:void 0,selectedSource:a?{id:a.id,name:a.name,domain:a.domain,status:a.status}:void 0,selectedComponent:i?{id:i.i,title:i.title,visualization:i.viz.type,trustState:i.trustState}:void 0,preview:s?{runId:s.runId,snapshotId:s.snapshotId,filterFingerprint:s.filterFingerprint,tiles:s.tiles.map(n=>{var o,l,d;return{tileId:n.tileId,status:n.status,rowCount:(o=n.result)==null?void 0:o.rowCount,columns:(d=(l=n.result)==null?void 0:l.columns)==null?void 0:d.slice(0,12),error:n.error}})}:{status:"not_run"},reviewTasks:t.reviewTasks.filter(n=>n.status==="open")}}function Po({draft:t,activePageId:r,onOpen:a,onAdd:i}){return e.jsxs(e.Fragment,{children:[e.jsx(Br,{title:"Pages",detail:"Organize the App story",action:e.jsx("button",{type:"button",onClick:i,children:e.jsx(xt,{size:14})})}),e.jsx("div",{className:"studio-list",children:t.pages.map((s,n)=>e.jsxs("button",{type:"button",className:s.id===r?"on":"",onClick:()=>a(s.id),children:[e.jsx("span",{children:n+1}),e.jsxs("div",{children:[e.jsx("strong",{children:s.metadata.title}),e.jsxs("small",{children:[s.layout.items.length," components"]})]})]},s.id))})]})}function $o({usedSources:t,items:r,selected:a,query:i,loading:s,error:n,disabled:o,sourceFeedback:l,onQuery:d,onSelect:x,onAdd:b,onAddContent:m,policy:f,total:y,hasMore:u,onLoadMore:w,onEnableReview:q}){const[C,k]=p.useState("all"),M=t.filter(I=>I.kind!=="text"),L=new Set(M.flatMap(I=>[I.id,I.sourceRef])),X=r.filter(I=>C==="all"||ka(I)===C);return e.jsxs(e.Fragment,{children:[e.jsx(Br,{title:"Sources",detail:"Search governed data and add a view"}),e.jsxs("label",{className:"source-search-primary",children:[e.jsx(jt,{size:15}),e.jsx("input",{value:i,onChange:I=>d(I.target.value),placeholder:"Search blocks, metrics, or domains","aria-label":"Search governed sources"}),i?e.jsx("button",{type:"button",onClick:()=>d(""),"aria-label":"Clear source search",title:"Clear search",children:e.jsx($t,{size:13})}):null]}),e.jsxs("details",{className:"used-sources-disclosure",children:[e.jsxs("summary",{children:[e.jsxs("div",{children:[e.jsx("strong",{children:"In this App"}),e.jsx("small",{children:M.length?`${M.length} data ${M.length===1?"source":"sources"}`:"No source added yet"})]}),e.jsx("span",{children:M.length}),e.jsx(dr,{size:14})]}),M.length?e.jsx("div",{className:"used-source-list",children:M.map(I=>e.jsxs("div",{children:[e.jsx("span",{className:I.trustState,children:I.trustState==="certified"?e.jsx(Qe,{size:14}):e.jsx(mt,{size:14})}),e.jsxs("p",{children:[e.jsx("strong",{title:I.sourceRef,children:be(I.sourceRef)}),e.jsxs("small",{children:[za(I.kind)," · ",I.trustState==="certified"?"Certified":"Review required"]})]})]},I.id))}):e.jsxs("div",{className:"source-panel-state compact",children:[e.jsx(yr,{size:15}),e.jsxs("div",{children:[e.jsx("strong",{children:"No data source added yet"}),e.jsx("small",{children:"Choose a source below and add a view."})]})]})]}),f==="include_review_required"?e.jsxs("div",{className:"source-review-lane",children:[e.jsx(mt,{size:14}),e.jsxs("p",{children:[e.jsx("strong",{children:"Review-required analysis lane is on"}),e.jsx("small",{children:"Referenced DQL or exploratory SQL appears here with a review label. It remains local and cannot publish until resolved."})]})]}):null,e.jsxs("div",{className:"source-catalog-toolbar",children:[e.jsx("div",{className:"source-view-tabs",role:"tablist","aria-label":"Filter sources by recommended view",children:[["all","All"],["kpi","KPI"],["chart","Charts"],["table","Tables"]].map(([I,O])=>e.jsx("button",{type:"button",role:"tab","aria-selected":C===I,className:C===I?"on":"",onClick:()=>k(I),children:O},I))}),e.jsx("small",{"aria-live":"polite",children:s?"Finding…":`${X.length} of ${y} ${y===1?"result":"results"}`})]}),s?e.jsxs("div",{className:"source-panel-state",children:[e.jsx(ht,{size:16}),e.jsxs("div",{children:[e.jsx("strong",{children:"Finding governed sources"}),e.jsx("small",{children:"Matching certified blocks and semantic data to this App decision."})]})]}):null,!s&&n?e.jsxs("div",{className:"source-panel-state error",children:[e.jsx($t,{size:16}),e.jsxs("div",{children:[e.jsx("strong",{children:"Sources could not load"}),e.jsx("small",{children:n})]})]}):null,!s&&!n&&X.length===0?e.jsxs("div",{className:"source-panel-state",children:[e.jsx(jt,{size:16}),e.jsxs("div",{children:[e.jsx("strong",{children:i.trim()||C!=="all"?"No source matches these filters":"No governed source matched yet"}),e.jsx("small",{children:i.trim()||C!=="all"?"Clear the search or choose All to see every governed source.":"Refine the business decision or enable the review-required lane for additional local options."})]})]}):null,e.jsx("div",{className:"source-catalog-list",children:X.map(I=>{var S,h;const O=ka(I),F=(a==null?void 0:a.id)===I.id,U=I.sourceId??I.id,_=L.has(U)||L.has(I.id)||L.has(I.name),A=((S=I.eligibility)==null?void 0:S.localPreview)===!1&&f==="governed_only",te=(l==null?void 0:l.sourceId)===U?l:null,Q=(te==null?void 0:te.status)??"idle",Y=ln({view:Sa(O),status:Q,reviewRequired:A,alreadyUsed:_,pageTitle:te==null?void 0:te.pageTitle});return e.jsxs("article",{className:`source-catalog-row ${F?"on":""}`,children:[e.jsxs("button",{type:"button",className:"source-catalog-summary",onClick:()=>x(I),"aria-label":`View ${I.name} source details`,"aria-expanded":F,children:[e.jsx("span",{className:I.status==="certified"?"certified":"review",children:I.status==="certified"?e.jsx(Qe,{size:14}):e.jsx(mt,{size:14})}),e.jsxs("div",{children:[e.jsx("strong",{title:I.name,children:be(I.name)}),e.jsxs("small",{children:[be(I.domain)," · ",I.status==="certified"?"Certified block":"Review required",_?" · In App":""]})]})]}),e.jsxs("button",{type:"button",className:"source-add-view",disabled:o,title:A?"Enable the review lane and add this draft block in one saved change.":void 0,onClick:()=>b(I,O),"aria-label":`${Y}: ${I.name}`,children:[e.jsx(xt,{size:13})," ",Y]}),te?e.jsx("small",{className:`source-action-feedback ${te.status}`,role:te.status==="error"?"alert":"status",children:te.status==="error"?te.message:Y}):null,F?e.jsxs("div",{className:"source-catalog-detail",children:[e.jsx("p",{children:I.description||`${be(I.name)} from the ${be(I.domain)} domain.`}),A?e.jsxs("button",{type:"button",className:"review-action",onClick:q,children:[e.jsx(mt,{size:12})," Enable review-required sources"]}):null,(((h=I.filterIds)==null?void 0:h.length)??0)>0?e.jsxs("span",{children:[e.jsx(Zt,{size:12})," ",I.filterIds.length," supported ",I.filterIds.length===1?"filter":"filters"]}):null,e.jsxs("div",{className:"source-view-options","aria-label":`Add ${I.name} with another view`,children:[e.jsxs("button",{type:"button",disabled:o,"aria-label":A?`Enable review lane and add ${I.name} as KPI`:void 0,onClick:()=>b(I,"kpi"),children:[e.jsx(Vi,{size:13})," KPI"]}),e.jsxs("button",{type:"button",disabled:o,"aria-label":A?`Enable review lane and add ${I.name} as Chart`:void 0,onClick:()=>b(I,"chart"),children:[e.jsx(an,{size:13})," Chart"]}),e.jsxs("button",{type:"button",disabled:o,"aria-label":A?`Enable review lane and add ${I.name} as Table`:void 0,onClick:()=>b(I,"table"),children:[e.jsx(on,{size:13})," Table"]})]})]}):null]},I.id)})}),u?e.jsx("button",{type:"button",className:"source-load-more",onClick:w,disabled:s||o,children:s?"Loading…":"Load 50 more sources"}):null,e.jsxs("div",{className:"panel-section-label",children:[e.jsx("span",{children:"Page elements"}),e.jsx("small",{children:"No data required"})]}),e.jsxs("div",{className:"content-quick-add",children:[e.jsxs("button",{type:"button",disabled:o,onClick:()=>m("heading"),children:[e.jsx(Qs,{size:15}),e.jsxs("span",{children:[e.jsx("strong",{children:"Heading"}),e.jsx("small",{children:"Organize the story"})]}),e.jsx(xt,{size:13})]}),e.jsxs("button",{type:"button",disabled:o,onClick:()=>m("text"),children:[e.jsx(no,{size:15}),e.jsxs("span",{children:[e.jsx("strong",{children:"Text"}),e.jsx("small",{children:"Add context or guidance"})]}),e.jsx(xt,{size:13})]})]})]})}function _o({draft:t,activePageId:r,catalog:a,candidates:i,runtimeFilterFields:s,previewRunsByPage:n,previewing:o,disabled:l,onRunPreview:d,onSave:x,onRemove:b}){const[m,f]=p.useState(null),[y,u]=p.useState(""),w=t.pages.find(h=>h.id===r)??t.pages[0],q=p.useMemo(()=>{const h=new Map;for(const $ of t.pages)for(const ee of $.filters??[]){const W=h.get(ee.id);W?W.pageIds.push($.id):h.set(ee.id,{filter:ee,pageIds:[$.id]})}return[...h.values()]},[t.pages]),C=new Set(q.map(h=>h.filter.id)),k=i.filter(h=>{const $=y.trim().toLowerCase();return!$||[h.id,...h.sourceNames].join(" ").toLowerCase().includes($)}),M=p.useMemo(()=>m!=null&&m.fieldId?Rr(t.pages,a,m.fieldId,s,t.sources):[],[a,m==null?void 0:m.fieldId,t.pages,t.sources,s]),L=(m==null?void 0:m.scope)==="page"?M.filter(h=>h.pageId===(w==null?void 0:w.id)):M,X=new Set((m==null?void 0:m.selectedMappingKeys)??[]),I=L.filter(h=>h.supported&&X.has(h.key)).length,O=L.filter(h=>h.supported).length,F=p.useMemo(()=>m!=null&&m.fieldId?Yo(m.fieldId,L.filter(h=>h.supported),n):null,[m==null?void 0:m.fieldId,n,L]),U=(m==null?void 0:m.type)==="daterange"||(m==null?void 0:m.type)==="date",A=!!(!!(U&&F&&F.compatibleComponents>0&&F.checkedComponents===F.compatibleComponents)&&(F==null?void 0:F.valueCount)===0),te=h=>{const $=Rr(t.pages,a,h.id,s,t.sources);f({id:h.id,fieldId:h.id,label:be(h.id),type:dn(h.id),scope:"app",required:!1,selectedMappingKeys:$.filter(ee=>ee.supported).map(ee=>ee.key)})},Q=h=>{var $e;const $=(($e=h.filter.field)==null?void 0:$e.name)??h.filter.bindsTo??h.filter.id,W=Rr(t.pages,a,$,s,t.sources).filter(se=>{var ue,Ae,_e,Ie;const oe=t.pages.find(xe=>xe.id===se.pageId),Be=(ue=oe==null?void 0:oe.filters)==null?void 0:ue.find(xe=>xe.id===h.filter.id);return Be?(Ae=Be.scope)!=null&&Ae.tileIds?Be.scope.tileIds.includes(se.tileId):((Ie=(_e=oe==null?void 0:oe.layout.items.find(xe=>xe.i===se.tileId))==null?void 0:_e.filterBindings)==null?void 0:Ie.some(xe=>xe.filter===h.filter.id&&xe.capability!=="unsupported"))??!1:!1});f({id:h.filter.id,fieldId:$,label:h.filter.label??be(h.filter.id),type:h.filter.type,scope:h.pageIds.length>1?"app":"page",required:h.filter.required??!1,selectedMappingKeys:W.map(se=>se.key)})},Y=h=>{if(!m)return;const $=new Set(L.filter(W=>W.supported).map(W=>W.key)),ee=new Set(m.selectedMappingKeys);for(const W of $)h?ee.add(W):ee.delete(W);f({...m,selectedMappingKeys:[...ee]})},S=h=>{if(!m||!h.supported)return;const $=new Set(m.selectedMappingKeys);$.has(h.key)?$.delete(h.key):$.add(h.key),f({...m,selectedMappingKeys:[...$]})};if(m){const h=C.has(m.id);return e.jsxs(e.Fragment,{children:[e.jsx(Br,{title:h?"Configure filter":"New filter",detail:"Choose a governed field and link its components",action:e.jsx("button",{type:"button",onClick:()=>{f(null),u("")},"aria-label":"Back to filters",children:e.jsx(_r,{size:14})})}),m.fieldId?e.jsxs("div",{className:"filter-builder",children:[e.jsxs("section",{className:"filter-builder-field",children:[e.jsx("span",{children:e.jsx(Qe,{size:15})}),e.jsxs("div",{children:[e.jsx("small",{children:"GOVERNED FIELD"}),e.jsx("strong",{children:be(m.fieldId)})]}),h?null:e.jsx("button",{type:"button",onClick:()=>f({...m,fieldId:"",selectedMappingKeys:[]}),children:"Change"})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Display label"}),e.jsx("input",{value:m.label,onChange:$=>f({...m,label:$.target.value})})]}),e.jsxs("label",{children:[e.jsx("span",{children:"Control"}),e.jsx("select",{value:m.type,onChange:$=>f({...m,type:$.target.value}),children:Go(m.fieldId).map($=>e.jsx("option",{value:$.value,children:$.label},$.value))})]}),U?e.jsxs("section",{className:`filter-availability ${A?"empty":F!=null&&F.dateRange?"ready":""}`,children:[e.jsx("span",{children:A?e.jsx($t,{size:14}):F!=null&&F.dateRange?e.jsx(Pt,{size:14}):e.jsx(Jt,{size:14})}),e.jsxs("div",{children:[e.jsx("strong",{children:o?"Checking available dates…":A?"No date values found":F!=null&&F.dateRange?`${F.dateRange.min} – ${F.dateRange.max}`:"Check available dates"}),e.jsx("small",{children:o?"The settled preview is checking the selected field.":A?"This field has no usable dates in the current governed result. Choose another field or refresh the data.":F!=null&&F.dateRange?`${F.valueCount} dated rows found across ${F.checkedComponents} linked ${F.checkedComponents===1?"component":"components"}.`:"Run the current page once before creating this date control."})]}),!o&&!(F!=null&&F.dateRange)?e.jsxs("button",{type:"button",onClick:d,disabled:l,children:[e.jsx(Jt,{size:12})," Run preview"]}):null]}):null,e.jsxs("fieldset",{children:[e.jsx("legend",{children:"Apply to"}),e.jsxs("div",{className:"filter-scope-switch",children:[e.jsx("button",{type:"button",className:m.scope==="page"?"on":"",onClick:()=>f({...m,scope:"page"}),children:"This page"}),e.jsx("button",{type:"button",className:m.scope==="app"?"on":"",onClick:()=>f({...m,scope:"app"}),children:"All compatible pages"})]}),e.jsx("small",{children:m.scope==="app"?"One dashboard control is added to every page with a compatible tile.":`Only ${(w==null?void 0:w.metadata.title)??"this page"} receives this control.`})]}),e.jsxs("fieldset",{className:"filter-mapping",children:[e.jsx("legend",{children:"Linked components"}),e.jsxs("header",{children:[e.jsxs("span",{children:[I,"/",O," compatible linked"]}),e.jsx("button",{type:"button",onClick:()=>Y(I!==O),children:I===O?"Clear compatible":"Link all compatible"})]}),e.jsx("div",{children:t.pages.filter($=>m.scope==="app"||$.id===(w==null?void 0:w.id)).map($=>{const ee=L.filter(W=>W.pageId===$.id);return ee.length?e.jsxs("section",{children:[e.jsx("small",{children:$.metadata.title}),ee.map(W=>e.jsxs("label",{className:W.supported?"":"unsupported",title:W.reason,children:[e.jsx("input",{type:"checkbox",checked:W.supported&&X.has(W.key),disabled:!W.supported,onChange:()=>S(W)}),e.jsxs("span",{children:[e.jsx("strong",{children:be(W.tileTitle)}),e.jsx("small",{children:W.supported?`${be(W.sourceName)} · ${W.mode==="semantic"?"semantic":"column"} binding`:W.reason})]}),W.supported?e.jsx(Pt,{size:13}):e.jsx($t,{size:13})]},W.key))]},$.id):null})})]}),e.jsxs("label",{className:"filter-required",children:[e.jsx("input",{type:"checkbox",checked:m.required,onChange:$=>f({...m,required:$.target.checked})}),e.jsxs("span",{children:[e.jsx("strong",{children:"Require a value"}),e.jsx("small",{children:"Publication and runs require this filter to be set."})]})]}),e.jsxs("div",{className:"filter-builder-actions",children:[e.jsx("button",{type:"button",onClick:()=>f(null),children:"Cancel"}),e.jsx("button",{type:"button",className:"primary",disabled:l||!m.label.trim()||I===0||A,onClick:()=>{x(m),f(null)},children:h?"Save filter":"Create filter"})]})]}):e.jsxs(e.Fragment,{children:[e.jsxs("label",{className:"filter-field-search",children:[e.jsx(jt,{size:14}),e.jsx("input",{autoFocus:!0,value:y,onChange:$=>u($.target.value),placeholder:"Search governed columns"})]}),e.jsx("div",{className:"filter-field-results",children:k.filter($=>!C.has($.id)).map($=>e.jsxs("button",{type:"button",onClick:()=>te($),children:[e.jsx("span",{children:e.jsx(Zt,{size:14})}),e.jsxs("div",{children:[e.jsx("strong",{children:be($.id)}),e.jsx("small",{children:$.sourceNames.map(be).join(", ")}),e.jsxs("em",{children:[$.affectedTileCount," compatible · ",$.pageCount," ",$.pageCount===1?"page":"pages"]})]}),e.jsx(dr,{size:13})]},$.id))}),k.filter($=>!C.has($.id)).length===0?e.jsx("p",{className:"panel-empty",children:"No additional governed filter fields match this search."}):null]})]})}return e.jsxs(e.Fragment,{children:[e.jsx(Br,{title:"Filters",detail:"Dashboard controls linked to governed columns",action:e.jsx("button",{type:"button",disabled:l||i.length===0,onClick:()=>f({id:"",fieldId:"",label:"",type:"select",scope:"app",required:!1,selectedMappingKeys:[]}),"aria-label":"Create filter",children:e.jsx(xt,{size:14})})}),e.jsxs("div",{className:"filter-workflow","aria-label":"How App filters work",children:[e.jsxs("span",{children:[e.jsx("b",{children:"1"}),"Choose a governed column"]}),e.jsxs("span",{children:[e.jsx("b",{children:"2"}),"Link all or selected components"]}),e.jsxs("span",{children:[e.jsx("b",{children:"3"}),"Use the control directly on the canvas"]}),e.jsx("small",{children:"Changing a filter refreshes every linked tile together."})]}),q.length>0?e.jsxs("div",{className:"panel-section-label",children:[e.jsx("span",{children:"Dashboard filters"}),e.jsxs("small",{children:[q.length," configured"]})]}):null,e.jsx("div",{className:"filter-contract-list",children:q.map(h=>{var W,$e;const $=((W=h.filter.field)==null?void 0:W.name)??h.filter.bindsTo??h.filter.id,ee=fn(t,h.filter.id);return e.jsxs("article",{children:[e.jsxs("button",{type:"button",className:"filter-contract-summary",onClick:()=>Q(h),children:[e.jsx("span",{children:e.jsx(Zt,{size:14})}),e.jsxs("div",{children:[e.jsx("strong",{children:h.filter.label??be(h.filter.id)}),e.jsxs("small",{children:[be($)," · ",be(h.filter.type)]}),e.jsxs("em",{children:[ee," linked ",ee===1?"component":"components"," · ",h.pageIds.length>1?"App-wide":be((($e=t.pages.find(se=>se.id===h.pageIds[0]))==null?void 0:$e.metadata.title)??"Page")]})]}),e.jsx(_a,{size:14})]}),e.jsx("button",{type:"button",className:"filter-remove",onClick:()=>b(h.filter.id),"aria-label":`Delete ${h.filter.label??be(h.filter.id)} filter`,title:"Delete filter",children:e.jsx(ir,{size:13})})]},h.filter.id)})}),q.length===0?e.jsxs("div",{className:"filter-empty",children:[e.jsx("span",{children:e.jsx(Zt,{size:18})}),e.jsx("strong",{children:"Create a dashboard filter"}),e.jsx("p",{children:"Pick a governed column, choose a dropdown or search control, then link every compatible tile."}),e.jsxs("button",{type:"button",disabled:l||i.length===0,onClick:()=>f({id:"",fieldId:"",label:"",type:"select",scope:"app",required:!1,selectedMappingKeys:[]}),children:[e.jsx(xt,{size:13})," New filter"]})]}):null,i.length===0?e.jsx("p",{className:"panel-empty",children:"Add a governed KPI, chart, or table first. Certified filter columns and semantic dimensions will appear here."}):q.length>0?e.jsxs("button",{type:"button",className:"filter-add-another",disabled:l,onClick:()=>f({id:"",fieldId:"",label:"",type:"select",scope:"app",required:!1,selectedMappingKeys:[]}),children:[e.jsx(xt,{size:13})," Add another filter"]}):null]})}function Eo({current:t,onApply:r}){return e.jsxs(e.Fragment,{children:[e.jsx(Br,{title:"Templates",detail:"Professional analytical structures"}),e.jsx("div",{className:"template-list",children:ja.map(a=>e.jsxs("button",{type:"button",className:t===a.id?"on":"",onClick:()=>r(a.id),children:[e.jsx("span",{children:gn(a.id)}),e.jsxs("div",{children:[e.jsx("strong",{children:a.title}),e.jsx("small",{children:a.description})]})]},a.id))})]})}function Bo({draft:t,prompt:r,previewRun:a,onPrompt:i,onAskAi:s,onSourcePolicy:n,onResolveTask:o,onApproveSemantic:l}){const d=la(t),x=t.sources.some(b=>(b.kind==="governed_semantic"||b.kind==="semantic_query")&&b.reviewStatus!=="approved");return e.jsxs("div",{className:"inspector-body",children:[e.jsxs("section",{children:[e.jsx("label",{children:"Business decision"}),e.jsx("textarea",{value:r,onChange:b=>i(b.target.value),rows:5})]}),e.jsxs("section",{children:[e.jsx("label",{children:"Source policy"}),e.jsxs("select",{value:t.sourcePolicy,onChange:b=>n(b.target.value),children:[e.jsx("option",{value:"governed_only",children:"Governed sources only"}),e.jsx("option",{value:"include_review_required",children:"Include review-required analysis"})]}),e.jsx("small",{className:"field-help",children:"Review-required sources stay local and block Project publication until replaced or promoted."})]}),e.jsxs("section",{className:"frame-facts",children:[e.jsx("label",{children:"Build Frame"}),e.jsxs("div",{children:[e.jsx("span",{children:"Audience"}),e.jsx("strong",{children:t.frame.audience||"Stakeholders"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Metrics"}),e.jsx("strong",{children:t.frame.metrics.join(", ")||"Needs clarification"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Dimensions"}),e.jsx("strong",{children:t.frame.dimensions.join(", ")||"Automatic"})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Source policy"}),e.jsx("strong",{children:t.sourcePolicy==="governed_only"?"Governed only":"Includes review lane"})]})]}),x?e.jsxs("section",{children:[e.jsx("label",{children:"Semantic review"}),e.jsxs("button",{type:"button",className:"review-action",onClick:l,disabled:!a,children:[e.jsx(Qe,{size:14})," ",a?"Approve this settled result":"Run preview to approve"]})]}):null,d.length?e.jsxs("section",{className:"review-task-list",children:[e.jsx("label",{children:"Review tasks"}),d.map(b=>e.jsxs("div",{children:[e.jsx("span",{children:b.message}),e.jsxs("button",{type:"button",onClick:()=>o(b),children:[e.jsx(Pt,{size:12})," Resolve"]})]},b.id))]}):null,e.jsxs("button",{type:"button",className:"ask-ai",onClick:s,children:[e.jsx(nr,{size:16})," Ask AI to compose or revise"]}),e.jsxs("section",{className:"trust-summary",children:[e.jsx(Qe,{size:17}),e.jsxs("div",{children:[e.jsx("strong",{children:"Nothing publishes silently"}),e.jsx("p",{children:"AI changes are typed diffs. Project publication revalidates live source trust and filter bindings."})]})]})]})}function Mo({tile:t,run:r,pageId:a,onUpdate:i,onDelete:s}){var f,y,u,w,q,C;const[n,o]=p.useState(t.title??""),[l,d]=p.useState(((f=t.text)==null?void 0:f.markdown)??"");p.useEffect(()=>o(t.title??""),[t.i,t.title]),p.useEffect(()=>{var k;return d(((k=t.text)==null?void 0:k.markdown)??"")},[t.i,(y=t.text)==null?void 0:y.markdown]);const x=t.viz.options??{},b=((u=r==null?void 0:r.result)==null?void 0:u.columns)??[],m=(k,M)=>i({viz:{...t.viz,options:{...x,[k]:M||void 0}}});return e.jsxs("div",{className:"inspector-body",children:[e.jsxs("section",{children:[e.jsx("label",{children:"Title"}),e.jsx("input",{value:n,onChange:k=>o(k.target.value),onBlur:()=>{n.trim()!==(t.title??"")&&i({title:n.trim()})}})]}),t.text?e.jsxs("section",{children:[e.jsx("label",{children:"Content"}),e.jsx("textarea",{rows:7,value:l,onChange:k=>d(k.target.value),onBlur:()=>{var k;l!==((k=t.text)==null?void 0:k.markdown)&&i({text:{markdown:l}})}}),e.jsx("small",{className:"field-help",children:"Safe Markdown only. Executable HTML and JavaScript are not supported."})]}):null,e.jsxs("section",{children:[e.jsx("label",{children:"Visualization"}),e.jsx("select",{value:t.viz.type,onChange:k=>i({viz:{...t.viz,type:k.target.value}}),children:["single_value","bar","line","area","scatter","heatmap","table","pivot","text","heading"].map(k=>e.jsx("option",{value:k,children:be(k)},k))})]}),t.text?null:e.jsxs("section",{className:"field-mapping",children:[e.jsx("label",{children:"Field mapping"}),e.jsxs("div",{children:[e.jsx("span",{children:"X / category"}),e.jsxs("select",{value:String(x.x??""),onChange:k=>m("x",k.target.value),children:[e.jsx("option",{value:"",children:"Auto"}),b.map(k=>e.jsx("option",{value:k,children:be(k)},k))]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Y / value"}),e.jsxs("select",{value:String(x.y??""),onChange:k=>m("y",k.target.value),children:[e.jsx("option",{value:"",children:"Auto"}),b.map(k=>e.jsx("option",{value:k,children:be(k)},k))]})]}),e.jsx("small",{className:"field-help",children:"Run preview to load the exact result fields."})]}),t.text?null:e.jsxs("section",{className:"format-grid",children:[e.jsx("label",{children:"Formatting"}),e.jsxs("div",{children:[e.jsx("span",{children:"Number"}),e.jsxs("select",{value:String(x.format??"number"),onChange:k=>m("format",k.target.value),children:[e.jsx("option",{value:"number",children:"Number"}),e.jsx("option",{value:"currency",children:"Currency"}),e.jsx("option",{value:"percent",children:"Percent"}),e.jsx("option",{value:"duration",children:"Duration"})]})]}),e.jsxs("div",{children:[e.jsx("span",{children:"Legend"}),e.jsxs("select",{value:String(x.legendPosition??"right"),onChange:k=>m("legendPosition",k.target.value),children:[e.jsx("option",{value:"top",children:"Top"}),e.jsx("option",{value:"right",children:"Right"}),e.jsx("option",{value:"bottom",children:"Bottom"}),e.jsx("option",{value:"none",children:"Hidden"})]})]})]}),e.jsxs("section",{children:[e.jsx("label",{children:"Responsive size"}),e.jsx("div",{className:"size-buttons",children:[["Compact",3,2],["Standard",6,4],["Wide",12,4],["Tall",6,7]].map(([k,M,L])=>e.jsx("button",{type:"button",onClick:()=>i({w:Number(M),h:Number(L)}),children:k},k))})]}),e.jsxs("section",{className:"data-trust",children:[e.jsx("label",{children:"Data & trust"}),e.jsxs("div",{children:[e.jsx("span",{className:`trust-dot ${t.trustState??"draft_ready"}`}),e.jsx("strong",{children:be(t.trustState??"draft_ready")})]}),e.jsx("p",{children:t.block?`${t.trustState==="certified"?"Certified":"Review-required"} block: ${"blockId"in t.block?t.block.blockId:t.block.ref}`:t.semantic?`Governed semantic query: ${t.semantic.id}`:t.draftAnalysis?`Review-required DQL: ${t.draftAnalysis.ref}`:"Local narrative component"}),(w=t.sourceEvidence)==null?void 0:w.slice(0,2).map((k,M)=>e.jsx("small",{children:k.reason},`${k.source}-${M}`)),r?e.jsx("small",{children:r.status==="ok"?`Settled on ${((q=r.result)==null?void 0:q.rowCount)??((C=r.result)==null?void 0:C.rows.length)??0} rows`:r.error}):null]}),e.jsxs("button",{type:"button",className:"delete-component",onClick:s,children:[e.jsx(ir,{size:15})," Remove component"]}),e.jsxs("small",{className:"inspector-id",children:[a," / ",t.i]})]})}function Lo({loading:t}){return t?e.jsxs("div",{className:"preview-state loading",children:[e.jsx("span",{className:"preview-loading-mark",children:e.jsx(Jt,{size:15})}),e.jsx("strong",{children:"Running governed preview…"}),e.jsx("span",{children:"Loading current data with this App’s filters and source policy."})]}):e.jsxs("div",{className:"preview-state idle",children:[e.jsx("span",{className:"preview-idle-mark",children:e.jsx(Jt,{size:15})}),e.jsx("strong",{children:"Preview is not loaded"}),e.jsx("span",{children:"App Studio runs this automatically when the data tile is added. Use Run preview to refresh an older draft."})]})}function Fo({filter:t,availability:r,value:a,applying:i,onChange:s}){var x,b,m,f,y,u;const n=t.label??be(t.id),o=Array.from(new Set([...t.options??[],...(r==null?void 0:r.values)??[]])),[l,d]=p.useState(String(a??""));if(p.useEffect(()=>d(String(a??"")),[a]),t.type==="daterange"){const w=a&&typeof a=="object"&&!Array.isArray(a)?a:{},q=i?"Checking dates…":r!=null&&r.dateRange?`Available ${r.dateRange.min} – ${r.dateRange.max}`:(r==null?void 0:r.valueCount)===0?"No date values exist for this field":"Run preview to check available dates";return e.jsxs("label",{className:`studio-filter range ${(r==null?void 0:r.valueCount)===0?"empty":""}`,"aria-busy":i,children:[e.jsx("span",{children:n}),e.jsx("input",{type:"date",min:(x=r==null?void 0:r.dateRange)==null?void 0:x.min,max:(b=r==null?void 0:r.dateRange)==null?void 0:b.max,"aria-label":`${n} start`,value:w.start??"",onChange:C=>s({...w,start:C.target.value})}),e.jsx("i",{children:"–"}),e.jsx("input",{type:"date",min:(m=r==null?void 0:r.dateRange)==null?void 0:m.min,max:(f=r==null?void 0:r.dateRange)==null?void 0:f.max,"aria-label":`${n} end`,value:w.end??"",onChange:C=>s({...w,end:C.target.value})}),e.jsx("small",{children:q})]})}if(t.type==="boolean")return e.jsxs("label",{className:"studio-filter boolean","aria-busy":i,children:[e.jsx("input",{type:"checkbox",checked:!!a,onChange:w=>s(w.target.checked)}),e.jsx("span",{children:n})]});if(t.type==="date")return e.jsxs("label",{className:`studio-filter ${(r==null?void 0:r.valueCount)===0?"empty":""}`,"aria-busy":i,children:[e.jsx("span",{children:n}),e.jsx("input",{type:"date",min:(y=r==null?void 0:r.dateRange)==null?void 0:y.min,max:(u=r==null?void 0:r.dateRange)==null?void 0:u.max,value:String(a??""),onChange:w=>s(w.target.value)}),e.jsx("small",{children:i?"Checking dates…":r!=null&&r.dateRange?`Available ${r.dateRange.min} – ${r.dateRange.max}`:(r==null?void 0:r.valueCount)===0?"No date values exist for this field":"Run preview to check available dates"})]});if(o.length>0&&(t.type==="select"||t.type==="multiselect"))return e.jsx(Oo,{label:n,values:o,value:a,multiple:t.type==="multiselect",applying:i,truncated:(r==null?void 0:r.truncated)??!1,onChange:s});if(o.length>0&&t.type==="search"){const w=`studio-filter-${t.id.replace(/[^a-z0-9_-]/gi,"-")}-options`;return e.jsxs("div",{className:"studio-filter searchable","aria-busy":i,children:[e.jsx("label",{htmlFor:`${w}-input`,children:n}),e.jsxs("span",{className:"studio-filter-combobox",children:[e.jsx(jt,{size:12,"aria-hidden":"true"}),e.jsx("input",{id:`${w}-input`,type:"search",list:w,value:l,placeholder:"All values",autoComplete:"off",onChange:q=>{const C=q.target.value;d(C),s(C)}}),e.jsx(dr,{size:12,"aria-hidden":"true"})]}),e.jsx("datalist",{id:w,children:o.map(q=>e.jsx("option",{value:q},q))}),e.jsx("small",{children:i?"Applying…":`${o.length}${r!=null&&r.truncated?"+":""} ${o.length===1&&!(r!=null&&r.truncated)?"value":"values"} · type or choose`})]})}return e.jsxs("label",{className:"studio-filter","aria-busy":i,children:[e.jsx("span",{children:n}),e.jsx("input",{type:t.type==="number"?"number":"search",value:String(a??""),placeholder:"All values",onChange:w=>s(t.type==="number"&&w.target.value!==""?Number(w.target.value):w.target.value)}),e.jsx("small",{children:i?"Applying…":"Updates automatically"})]})}function Oo({label:t,values:r,value:a,multiple:i,applying:s,truncated:n,onChange:o}){const[l,d]=p.useState(""),x=p.useRef(null),b=i?new Set(Array.isArray(a)?a.map(String):a==null||a===""?[]:[String(a)]):new Set(a==null||a===""?[]:[String(a)]),m=r.filter(u=>u.toLowerCase().includes(l.trim().toLowerCase())),f=b.size===0?"All values":i?`${b.size} selected`:[...b][0],y=u=>{if(!i){o(u),x.current&&(x.current.open=!1),d("");return}const w=new Set(b);w.has(u)?w.delete(u):w.add(u),o([...w])};return e.jsxs("details",{ref:x,className:"studio-filter dropdown","aria-busy":s,children:[e.jsxs("summary",{children:[e.jsxs("span",{children:[e.jsx("small",{children:t}),e.jsx("strong",{children:f})]}),e.jsx(dr,{size:12})]}),e.jsxs("div",{className:"studio-filter-menu",children:[e.jsxs("label",{children:[e.jsx(jt,{size:12}),e.jsx("input",{value:l,onChange:u=>d(u.target.value),placeholder:"Search values",autoComplete:"off"})]}),e.jsx("button",{type:"button",className:"filter-option-clear",onClick:()=>{o(i?[]:""),!i&&x.current&&(x.current.open=!1)},children:"All values"}),e.jsx("div",{children:m.map(u=>e.jsxs("button",{type:"button",className:b.has(u)?"on":"",onClick:()=>y(u),children:[i?e.jsx("span",{className:"filter-option-check",children:b.has(u)?e.jsx(Pt,{size:11}):null}):null,e.jsx("span",{children:u}),!i&&b.has(u)?e.jsx(Pt,{size:12}):null]},u))}),m.length===0?e.jsx("small",{children:"No matching values"}):null,e.jsx("footer",{children:s?"Applying…":`${r.length}${n?"+":""} available values`})]})]})}function Wo({tile:t,run:r,loading:a,themeMode:i}){const s=p.useRef(null),[n,o]=p.useState(560),[l,d]=p.useState(190);if(p.useEffect(()=>{const m=s.current;if(!m||typeof ResizeObserver>"u")return;const f=new ResizeObserver(([y])=>{o(Math.max(220,Math.floor(y.contentRect.width))),d(Math.max(120,Math.floor(y.contentRect.height)))});return f.observe(m),()=>f.disconnect()},[r]),!r)return e.jsx(Lo,{loading:a});if(r.status!=="ok"||!r.result)return e.jsxs("div",{className:"preview-state error",children:[e.jsx("strong",{children:be(r.status)}),e.jsx("span",{children:r.error??"This component could not run with the current source and filters."})]});const x=t.viz.type==="single_value"?"kpi":t.viz.type,b={...r.chartConfig??{},...t.viz.options??{},chart:x};return e.jsx("div",{ref:s,className:"live-component-preview",onClick:m=>m.stopPropagation(),children:x==="table"||x==="pivot"?e.jsx(Xi,{result:r.result,themeMode:i,maxHeight:l,initialPageSize:10}):e.jsx(Ji,{result:r.result,themeMode:i,chartConfig:{...b,title:void 0},availableHeight:l,availableWidth:n})})}function Br({title:t,detail:r,action:a}){return e.jsxs("header",{className:"panel-title",children:[e.jsxs("div",{children:[e.jsx("strong",{children:t}),e.jsx("small",{children:r})]}),a]})}function ni(t,r){return[{type:"set_name",name:r.name},{type:"set_template",template:r.template},{type:"set_frame",frame:r.frame},{type:"set_source_policy",sourcePolicy:r.sourcePolicy},{type:"set_requirements",requirements:r.requirements,coverage:r.coverage},...t.sources.filter(a=>!r.sources.some(i=>i.id===a.id)).map(a=>({type:"remove_source",sourceId:a.id})),...r.sources.map(a=>({type:"upsert_source",source:a})),...t.pages.filter(a=>!r.pages.some(i=>i.id===a.id)).map(a=>({type:"remove_page",pageId:a.id})),...r.pages.map(a=>({type:"upsert_page",page:a})),...t.reviewTasks.filter(a=>!r.reviewTasks.some(i=>i.id===a.id)).map(a=>({type:"remove_review_task",taskId:a.id})),...r.reviewTasks.map(a=>({type:"set_review_task",task:a}))]}function Ho(t,r,a){const i=t.layout.items.filter(l=>!(l.i.startsWith("template-")&&l.i.endsWith("-introduction")));if(r==="blank")return{...t,sections:[],layout:{...t.layout,items:Tr(i,12)}};const n={i:`template-${r}-introduction`,x:0,y:0,w:12,h:2,title:r==="investigation"?"Investigation question":"Executive context",sectionId:"exec_summary",text:{markdown:r==="executive_brief"?`# ${a}
|
|
755
750
|
|
|
756
751
|
Summarize the decision and the governed evidence that supports it.`:r==="operational_dashboard"?`# ${a}
|
|
757
752
|
|
|
758
753
|
Monitor performance, changes, drivers, and the details that require action.`:`# ${a}
|
|
759
754
|
|
|
760
|
-
Document the question, findings, caveats, and supporting evidence.`},viz:{type:"text"},sourceClass:"narrative",trustState:"draft_ready",reviewStatus:"draft_ready"};return{...t,sections:r==="investigation"?[{id:"exec_summary",title:"Question",kind:"exec_summary",order:0},{id:"insight",title:"Findings and comparisons",kind:"insight",order:1},{id:"appendix",title:"Caveats and evidence",kind:"appendix",order:2}]:[{id:"exec_summary",title:"Executive summary",kind:"exec_summary",order:0},{id:"kpi_band",title:"Key metrics",kind:"kpi_band",order:1},{id:"insight",title:r==="executive_brief"?"Decision evidence":"Trends and drivers",kind:"insight",order:2},{id:"appendix",title:"Detail and evidence",kind:"appendix",order:3}],layout:{...t.layout,items:Tr([n,...i],12)}}}function si(t,r){const a="template-",i="-introduction",s=t.filter(l=>l.i.startsWith(a)&&l.i.endsWith(i));if(s.length<=1)return t;const n=r&&r!=="blank"?`template-${r}-introduction`:void 0,o=s.find(l=>l.i===n)??s[s.length-1];return t.filter(l=>!(l.i.startsWith(a)&&l.i.endsWith(i))||l.i===o.i)}function Tr(t,r){const a=Math.max(1,Math.floor(r));let i=0,s=0,n=0;return t.map((o,l)=>({item:o,index:l})).sort((o,l)=>o.item.y-l.item.y||o.item.x-l.item.x||o.index-l.index).map(({item:o})=>{const l=Math.min(a,Math.max(1,o.w)),d=Math.max(1,o.h);i+l>a&&(i=0,s+=n||d,n=0);const x={...o,x:i,y:s,w:l,h:d};return i+=l,n=Math.max(n,d),i>=a&&(i=0,s+=n,n=0),x})}function ka(t){const r=
|
|
755
|
+
Document the question, findings, caveats, and supporting evidence.`},viz:{type:"text"},sourceClass:"narrative",trustState:"draft_ready",reviewStatus:"draft_ready"};return{...t,sections:r==="investigation"?[{id:"exec_summary",title:"Question",kind:"exec_summary",order:0},{id:"insight",title:"Findings and comparisons",kind:"insight",order:1},{id:"appendix",title:"Caveats and evidence",kind:"appendix",order:2}]:[{id:"exec_summary",title:"Executive summary",kind:"exec_summary",order:0},{id:"kpi_band",title:"Key metrics",kind:"kpi_band",order:1},{id:"insight",title:r==="executive_brief"?"Decision evidence":"Trends and drivers",kind:"insight",order:2},{id:"appendix",title:"Detail and evidence",kind:"appendix",order:3}],layout:{...t.layout,items:Tr([n,...i],12)}}}function si(t,r){const a="template-",i="-introduction",s=t.filter(l=>l.i.startsWith(a)&&l.i.endsWith(i));if(s.length<=1)return t;const n=r&&r!=="blank"?`template-${r}-introduction`:void 0,o=s.find(l=>l.i===n)??s[s.length-1];return t.filter(l=>!(l.i.startsWith(a)&&l.i.endsWith(i))||l.i===o.i)}function Tr(t,r){const a=Math.max(1,Math.floor(r));let i=0,s=0,n=0;return t.map((o,l)=>({item:o,index:l})).sort((o,l)=>o.item.y-l.item.y||o.item.x-l.item.x||o.index-l.index).map(({item:o})=>{const l=Math.min(a,Math.max(1,o.w)),d=Math.max(1,o.h);i+l>a&&(i=0,s+=n||d,n=0);const x={...o,x:i,y:s,w:l,h:d};return i+=l,n=Math.max(n,d),i>=a&&(i=0,s+=n,n=0),x})}function ka(t){const r=Qo(t.chartType);return r==="single_value"?"kpi":r==="table"?"table":"chart"}function Sa(t){return t==="kpi"?"KPI":t==="table"?"Table":"Chart"}function za(t){return t==="certified_block"?"Certified block":t==="governed_semantic"||t==="semantic_query"?"Governed semantic query":t==="review_block"?"Review-required block":t==="review_dql"?"Review-required DQL":t==="exploratory_sql"?"Review-required SQL":"Page content"}function Vo(t){if(t.type==="set_layout")return!0;if(t.type!=="update_tile")return!1;const r=new Set(["title","viz","display","x","y","w","h","sectionId"]);return Object.keys(t.patch).every(a=>r.has(a))}function Cr(t){return t.layout.items.some(r=>!!(r.block||r.semantic||r.draftAnalysis))}function Ko(t){return(t.filterBindings??[]).filter(r=>r.capability==="unsupported"||!!r.unsupportedReason)}function gn(t){return t==="executive_brief"?e.jsx(mt,{size:18}):t==="operational_dashboard"?e.jsx(At,{size:18}):t==="investigation"?e.jsx(jt,{size:18}):e.jsx(xt,{size:18})}function Qo(t){const r=(t==null?void 0:t.toLowerCase())??"";return r.includes("line")||r.includes("trend")?"line":r.includes("area")?"area":r.includes("table")?"table":r.includes("kpi")||r.includes("single")?"single_value":"bar"}function Go(t){const r=[{value:"select",label:"Searchable dropdown"},{value:"multiselect",label:"Searchable multi-select"}];return dn(t)==="daterange"?[{value:"daterange",label:"Date range"},{value:"date",label:"Single date"},...r]:/count|amount|total|score|quantity|price|revenue|cost|limit|top_?n/i.test(t)?[{value:"number",label:"Number"},...r]:/^(is_|has_)|_flag$|enabled|active/i.test(t)?[{value:"boolean",label:"Yes / no"},...r]:r}function Yo(t,r,a){var l;let i=0,s=0,n=Number.POSITIVE_INFINITY,o=Number.NEGATIVE_INFINITY;for(const d of r){const x=(l=a[d.pageId])==null?void 0:l.tiles.find(f=>f.tileId===d.tileId);if((x==null?void 0:x.status)!=="ok"||!x.result)continue;const b=oi(d.binding??t),m=x.result.columns.find(f=>oi(f)===b);if(m){i+=1;for(const f of x.result.rows){const y=Date.parse(String(f[m]??""));Number.isFinite(y)&&(s+=1,n=Math.min(n,y),o=Math.max(o,y))}}}return{checkedComponents:i,compatibleComponents:r.length,valueCount:s,...s>0?{dateRange:{min:new Date(n).toISOString().slice(0,10),max:new Date(o).toISOString().slice(0,10)}}:{}}}function oi(t){var r;return((r=t.trim().toLowerCase().replace(/["`\[\]]/g,"").split(".").at(-1))==null?void 0:r.replace(/[^a-z0-9]/g,""))??""}function Xo(t,r){return t?r?{min:t.min<r.min?t.min:r.min,max:t.max>r.max?t.max:r.max}:t:r}function fn(t,r){return t.pages.reduce((a,i)=>{var n;const s=(n=i.filters)==null?void 0:n.find(o=>o.id===r);return s?a+i.layout.items.filter(o=>{var l,d;return(l=s.scope)!=null&&l.tileIds&&!s.scope.tileIds.includes(o.i)?!1:((d=o.filterBindings)==null?void 0:d.some(x=>x.filter===r&&x.capability!=="unsupported"))??!1}).length:a},0)}function be(t){return t.replace(/[_-]+/g," ").replace(/\b\w/g,r=>r.toUpperCase())}function Ct(t){return t instanceof Error?t.message:String(t)}const Jo=`
|
|
761
756
|
.dql-apps-waterline {
|
|
762
757
|
--dql-app-canvas: var(--color-bg-primary, #f7f8fb);
|
|
763
758
|
--dql-app-surface: var(--color-bg-card, #ffffff);
|
|
@@ -5581,7 +5576,7 @@ Document the question, findings, caveats, and supporting evidence.`},viz:{type:"
|
|
|
5581
5576
|
color: var(--text-secondary); box-shadow: 0 16px 46px rgba(15,23,42,.24); font-size: 11.5px;
|
|
5582
5577
|
}
|
|
5583
5578
|
.dql-app-delete-undo button { border: 0; background: transparent; color: var(--accent); font-weight: 750; cursor: pointer; }
|
|
5584
|
-
`;function hr(t){return String(t??"").replace(/\s+/g," ").replace(/[\s,;:.–—-]+$/,"").trim()}function Oe(t){const r=String(t??"").replace(/[_-]+/g," ").replace(/\s+/g," ").trim();return r?r.split(" ").map(a=>{const i=a.toLowerCase();return i==="ai"?"AI":i==="cxo"?"CXO":i==="kpi"?"KPI":i==="vs"||i==="vs."?"vs.":`${a.charAt(0).toUpperCase()}${a.slice(1)}`}).join(" "):"Business"}function Oa(t){return t.replace(/\bDraft gaps stay in Research until reviewed\.?/gi,"Follow-up analysis stays out of the stakeholder view until reviewed.").replace(/\bresearch path\b/gi,"analysis path").replace(/\bresearch suggestions\b/gi,"analysis suggestions").replace(/\bfollow-up research\b/gi,"follow-up analysis").replace(/\bevidence chips\b/gi,"proof chips").replace(/\bevidence, lineage\b/gi,"proof and lineage").replace(/\bevidence and lineage\b/gi,"proof and lineage").replace(/\bsource evidence\b/gi,"source proof").replace(/\bOpen Research\b/g,"Open Analysis").replace(/\bResearch\b/g,"Analysis")}function sr({icon:t,children:r}){return e.jsxs("div",{className:"dql-app-panel-card",children:[e.jsx("span",{children:t}),e.jsx("div",{children:r})]})}function kt({title:t,detail:r,compact:a=!1}){return e.jsxs("div",{className:`dql-app-empty ${a?"compact":""}`,children:[e.jsx(At,{size:a?24:34,strokeWidth:1.5}),e.jsx("b",{children:t}),e.jsx("span",{children:r})]})}function Do({appDoc:t}){const r=(t==null?void 0:t.notebooks)??(t==null?void 0:t.app.notebooks)??[];return r.length?e.jsx("div",{className:"dql-app-simple-list",children:r.map(a=>e.jsxs(sr,{icon:e.jsx(Ui,{size:16}),children:[e.jsx("b",{children:a.title??a.path.split("/").pop()}),e.jsxs("span",{children:[a.role," / ",a.visibility," / ",a.path]})]},a.path))}):e.jsx(kt,{title:"No notebooks attached.",detail:"Attach analysis notebooks in Build mode when this App needs supporting work."})}function Uo({appDoc:t}){const r=(t==null?void 0:t.aiPins)??[];return r.length?e.jsx("div",{className:"dql-app-simple-list",children:r.map(a=>e.jsxs(sr,{icon:e.jsx(nr,{size:16}),children:[e.jsx("b",{children:a.title}),e.jsxs("span",{children:[a.certification," / ",a.reviewStatus]})]},a.id))}):e.jsx(kt,{title:"No pinned insights yet.",detail:"Use Copilot from a dashboard page, create analysis, then add useful reviewed insights to this App."})}function el({appDoc:t}){const r=(t==null?void 0:t.drafts)??[];return r.length?e.jsx("div",{className:"dql-app-simple-list",children:r.map(a=>e.jsxs(sr,{icon:e.jsx(mt,{size:16}),children:[e.jsx("b",{children:a.name}),e.jsxs("span",{children:[a.reviewStatus??"needs review"," / ",a.path]})]},a.path))}):e.jsx(kt,{title:"No drafts.",detail:"Generated and promoted draft blocks will appear here for review."})}function tl({appDoc:t}){var r;return t?e.jsxs("div",{className:"dql-app-settings-grid",children:[e.jsxs(sr,{icon:e.jsx(Qe,{size:16}),children:[e.jsx("b",{children:"Owners"}),e.jsx("span",{children:t.app.owners.join(", ")})]}),e.jsxs(sr,{icon:e.jsx(ar,{size:16}),children:[e.jsx("b",{children:"Lifecycle"}),e.jsx("span",{children:t.app.lifecycle??"draft"})]}),e.jsxs(sr,{icon:e.jsx(yr,{size:16}),children:[e.jsx("b",{children:"Policies"}),e.jsxs("span",{children:[t.app.policies.length," local access policies"]})]}),e.jsxs(sr,{icon:e.jsx(At,{size:16}),children:[e.jsx("b",{children:"Homepage"}),e.jsx("span",{children:((r=t.app.homepage)==null?void 0:r.type)??"dashboard"})]})]}):e.jsx(kt,{title:"No App selected.",detail:"Choose an App to inspect its settings."})}function br({children:t,tone:r="certified"}){return e.jsx("span",{className:`dql-app-seal ${r}`,children:t})}function mn(t){return t==null||t===""?"All":Array.isArray(t)?t.map(mn).join(", "):typeof t=="boolean"?t?"On":"Off":typeof t=="number"?t.toLocaleString():typeof t=="object"?JSON.stringify(t):String(t)}function hn(t,r){if(Array.isArray(r))return r.map(i=>hn(t,i)).join(", ");const a=typeof r=="number"?r:typeof r=="string"&&r.trim()!==""?Number(r):NaN;return/(season|year)/i.test(t)&&Number.isInteger(a)&&a>=1900&&a<=2200?String(a):mn(r)}const ga=new Map;function rl(t){const r=Object.entries(t).filter(([a])=>a!=="smartView");return r.length?r.map(([a,i])=>`${Oe(a)} ${hn(a,i)}`).join(", "):"No app filters set"}function al(t){return t==null?"":typeof t=="number"?Pr(t):typeof t=="string"?t:JSON.stringify(t)}function at(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function li({label:t,value:r}){return e.jsxs("div",{className:"dql-app-keyvalue-inline",children:[e.jsx("span",{children:t}),e.jsx("b",{children:r})]})}function il({appDoc:t,dashboardDoc:r,seed:a,themeMode:i,onSeedHandled:s,onDashboardChanged:n,onInvestigationsChanged:o,onActiveInvestigationChange:l}){var it;const d=t==null?void 0:t.app.id,x=r==null?void 0:r.dashboard.id,b=Ht[i],[m,f]=p.useState(()=>(t==null?void 0:t.investigations)??[]),[y,u]=p.useState(null),[w,q]=p.useState(!1),[C,k]=p.useState(null),[M,L]=p.useState(null),[X,I]=p.useState("preview"),[O,F]=p.useState(""),[U,_]=p.useState(!1),[A,te]=p.useState(!1),[Q,Y]=p.useState(null);p.useEffect(()=>{if(!d){f([]),u(null);return}let R=!1;return q(!0),D.listAppInvestigations(d).then(le=>{if(R)return;L(null),f(le);const ge=Ca(le);u(ve=>{var Te,de;return ve??((Te=ge.find(Pe=>Pe.status==="ready"))==null?void 0:Te.id)??((de=ge[0])==null?void 0:de.id)??null})}).finally(()=>{R||q(!1)}),()=>{R=!0}},[d]),p.useEffect(()=>{o(m)},[m,o]),p.useEffect(()=>{if(!a||!d)return;let R=!1;const le={dashboardId:a.dashboardId??x,sourceTileId:a.sourceTileId,sourceBlockId:a.sourceBlockId,title:a.title,question:a.question,intent:a.intent,context:a.context,generatedSql:a.generatedSql,run:!0},ge=Mr(a.title??a.question)||"requested follow-up",ve=`${d}:${JSON.stringify(le)}`,Te=async()=>{k("create"),Y(ge),L(null);let Pe=ga.get(ve);Pe||(Pe=D.createAppInvestigation(d,le),ga.set(ve,Pe),Pe.finally(()=>{window.setTimeout(()=>ga.delete(ve),5e3)}));const Ye=await Pe;if(R)return;if(k(null),!Ye.ok){L(Ye.error),Y(null),s();return}const Xe=Ye.investigation,De=Ee=>{f(ze=>Ar(ze,Ee)),u(Ee.id),I("preview"),te(!1),Ee.status!=="draft"&&Ee.status!=="running"&&Y(null)};if(De(Xe),Xe.status!=="draft"&&Xe.status!=="running"){s();return}k(Xe.id);for(let Ee=0;Ee<20;Ee+=1){if(await new Promise(Z=>{window.setTimeout(Z,1e3)}),R)return;const ze=await D.getAppInvestigation(d,Xe.id);if(R)return;if(ze&&ze.status!=="draft"&&ze.status!=="running"){k(null),De(ze),s();return}}s(),k(null),Y(null),L("Analysis is still running. Reopen it or refresh to load the latest proof.")},de=window.setTimeout(()=>void Te(),0);return()=>{R=!0,window.clearTimeout(de)}},[a==null?void 0:a.nonce,d,x,s]);const S=p.useMemo(()=>Ca(m),[m]),h=S.find(R=>R.id===y)??S.find(R=>R.status==="ready")??S[0]??null;p.useEffect(()=>(l(h),()=>l(null)),[h,l]);const $=S.filter(R=>R.id!==(h==null?void 0:h.id)).filter(R=>U||R.status!=="error").slice(0,U?40:5),ee=Math.max(0,S.length-(h?1:0)-$.length),W=h?ol(h):null,$e=W?hl(W):"",se=C==="create"||!!Q,oe=se&&!!Q,Be=se&&!h;p.useEffect(()=>{F((h==null?void 0:h.generatedSql)??"")},[h==null?void 0:h.id,h==null?void 0:h.generatedSql]);const ue=async(R,le)=>{if(!d)return null;k(R.id),L(null);const ge=le==null?void 0:le.trim(),ve=await D.runAppInvestigation(d,R.id,ge?{generatedSql:ge}:void 0);return k(null),ve.ok?(f(Te=>Ar(Te,ve.investigation)),I("preview"),ve.investigation):(L(ve.error),null)},Ae=async R=>{if(!d)return null;k(`rebuild:${R.id}`),L(null);const le=await D.runAppInvestigation(d,R.id,{repairMode:"rebuild_from_certified"});return k(null),le.ok?(f(ge=>Ar(ge,le.investigation)),I(le.investigation.error?"sql":"preview"),le.investigation):(L(le.error),null)},_e=async R=>{if(!d)return null;k(`pin:${R.id}`),L(null);const le=await D.pinAppInvestigation(d,R.id,{dashboardId:R.dashboardId??x,title:R.title});return k(null),le.ok?(f(ge=>Ar(ge,le.investigation)),u(le.investigation.id),le.dashboard&&n(le.dashboard),le.investigation):(L(le.error),null)},Ie=async R=>{if(!d)return;if(!R.generatedSql){L("Add reviewed SQL before creating a draft block.");return}const le=R.pinnedAiPinId?R:await _e(R),ge=le==null?void 0:le.pinnedAiPinId;if(!ge)return;k(`promote:${R.id}`),L(null);const ve=await D.promoteAiPin(d,ge);if(k(null),!ve.ok){L(ve.error??"Draft block could not be created.");return}const Te=await D.getAppInvestigation(d,R.id);Te&&f(de=>Ar(de,Te))},xe=async R=>{const le=O.trim();let ge=R;if(le&&le!==(R.generatedSql??"").trim()){const ve=await ue(R,le);if(!ve)return;ge=ve}await Ie(ge)},Ze=async R=>{const le=O.trim();let ge=R;if(le&&le!==(R.generatedSql??"").trim()){const ve=await ue(R,le);if(!ve)return null;ge=ve}return _e(ge)};return t?e.jsxs("div",{className:`dql-app-research-shell ${A||!h&&!Be?"history-open":"history-collapsed"}`,children:[e.jsxs("section",{className:"dql-app-research-list",children:[e.jsxs("div",{className:"dql-app-research-head",children:[e.jsxs("span",{children:[e.jsx(jt,{size:14})," Analysis"]}),e.jsxs("div",{children:[e.jsx("b",{children:m.length}),h?e.jsx("button",{type:"button",onClick:()=>te(!1),title:"Close analysis history",children:"Close"}):null]})]}),w?e.jsx(kt,{title:"Loading analysis...",detail:"Reading local app analysis.",compact:!0}):null,M?e.jsx("div",{className:"dql-app-error",children:M}):null,!w&&m.length===0?e.jsx(kt,{title:"No analysis yet.",detail:"Start from Copilot so the analysis keeps the original question, filters, and selected result context.",compact:!0}):null,e.jsxs("div",{className:"dql-app-research-items",children:[h?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"dql-app-research-group-label",children:"Current analysis"}),e.jsx(di,{item:h,selected:!0,onClick:()=>{L(null),u(h.id),I("preview"),te(!1)}})]}):null,$.length?e.jsx("div",{className:"dql-app-research-group-label",children:"Recent history"}):null,$.map(R=>e.jsx(di,{item:R,selected:(h==null?void 0:h.id)===R.id,onClick:()=>{L(null),u(R.id),I("preview"),te(!1)}},R.id)),ee>0?e.jsxs("button",{type:"button",className:"dql-app-research-history-toggle",onClick:()=>_(R=>!R),children:[e.jsx("span",{children:U?"Hide older runs":`Show ${ee} older run${ee===1?"":"s"}`}),e.jsx("small",{children:U?"Keep the current analysis focused":"Includes failed and superseded analysis attempts"})]}):null]})]}),e.jsx("section",{className:"dql-app-research-detail",children:oe?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dql-app-report-toolbar",children:[e.jsxs("div",{children:[e.jsx("span",{children:"New memo"}),e.jsx("b",{children:Q})]}),m.length?e.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>te(R=>!R),children:[e.jsx(jt,{size:13})," ",A?"Hide history":`Analysis history (${m.length})`]}):null]}),M?e.jsx("div",{className:"dql-app-error",children:M}):null,e.jsxs("div",{className:"dql-app-research-creating active",children:[e.jsx(ar,{size:24}),e.jsx("span",{children:"Preparing business memo"}),e.jsx("h2",{children:"Writing business memo..."}),e.jsxs("p",{children:['DQL is opening a scoped memo for "',Q,'". The previous memo stays in history while this answer is built from the typed context, active filters, certified block evidence, and preview proof.']}),e.jsxs("div",{className:"dql-app-research-creating-steps",children:[e.jsx("small",{children:"Reading current filters"}),e.jsx("small",{children:"Checking certified block context"}),e.jsx("small",{children:"Building narrative and proof appendix"})]})]})]}):h&&W?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dql-app-report-toolbar",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Current memo"}),e.jsx("b",{children:bn(h)})]}),e.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>te(R=>!R),children:[e.jsx(jt,{size:13})," ",A?"Hide history":`Memo history (${m.length})`]})]}),se||C===h.id||h.status==="running"?e.jsxs("div",{className:`dql-app-research-status ${se?"opening":""}`,children:[e.jsx(ar,{size:14}),e.jsxs("div",{children:[e.jsx("span",{children:se?"Opening a new business memo...":"Refreshing the memo from certified evidence, active filters, and optional preview proof..."}),Q?e.jsx("small",{children:Q}):null]})]}):null,M?e.jsx("div",{className:"dql-app-error",children:M}):null,e.jsxs("article",{className:"dql-app-research-report",children:[e.jsxs("header",{className:"dql-app-report-hero",children:[e.jsxs("div",{className:"dql-app-report-status-row",children:[e.jsxs("span",{children:[e.jsx(jt,{size:13})," Business memo"]}),e.jsx(br,{tone:h.status==="error"?"draft":"agentic",children:h.reviewStatus})]}),e.jsx("h2",{children:W.title}),e.jsx("p",{children:W.scope}),e.jsx("div",{className:"dql-app-report-context-line",children:W.contextFacts.map(R=>e.jsxs("span",{children:[e.jsx("b",{children:R.label}),R.value]},R.label))}),e.jsxs("div",{className:"dql-app-report-actions",children:[e.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>void Ze(h),disabled:C===`pin:${h.id}`,children:[e.jsx(Xs,{size:13})," ",h.pinnedAiPinId?"Added to App":"Add reviewed insight to App"]}),e.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-primary",onClick:()=>void xe(h),disabled:!(O.trim()||h.generatedSql)||C===`promote:${h.id}`,children:[e.jsx(mt,{size:13})," ",C===`promote:${h.id}`?"Drafting...":"Create draft block"]}),e.jsxs("details",{className:"dql-app-report-review-actions",children:[e.jsx("summary",{children:"Reviewer tools"}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>void ue(h,O),disabled:C===h.id,children:[e.jsx(ar,{size:13})," ",C===h.id?"Refreshing...":"Refresh memo"]}),(it=W.previewIssue)!=null&&it.canRebuild?e.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>void Ae(h),disabled:C===`rebuild:${h.id}`,children:[e.jsx(ar,{size:13})," ",C===`rebuild:${h.id}`?"Rebuilding...":"Rebuild SQL"]}):null]})]})]}),W.previewIssue?e.jsxs("div",{className:"dql-app-report-warning",children:[e.jsx(Er,{size:14}),e.jsx("span",{children:W.previewIssue.message})]}):null]}),e.jsx("section",{className:"dql-app-report-section dql-app-report-paper",children:W.sections.length?e.jsx(bl,{sections:W.sections}):e.jsx(cs,{text:$e,t:b,compact:!0})}),W.keyNumbers.length||W.drivers.length?e.jsxs("section",{className:`dql-app-report-section dql-app-report-evidence-story ${W.keyNumbers.length&&W.drivers.length?"":"single"}`,children:[W.keyNumbers.length?e.jsxs("div",{children:[e.jsx("h3",{children:W.intent==="segment_compare"?"Segment numbers":W.intent==="diagnose_change"?"Movement numbers":"Key numbers"}),e.jsx("div",{className:"dql-app-report-numbers",children:W.keyNumbers.map(R=>e.jsxs("div",{className:"dql-app-report-number",children:[e.jsx("span",{children:R.label}),e.jsx("b",{children:R.value}),e.jsx("small",{children:R.detail})]},R.label))})]}):null,W.drivers.length?e.jsxs("div",{children:[e.jsx("h3",{children:W.intent==="anomaly_investigation"?"Exception view":W.intent==="entity_drilldown"?"Entity view":"Driver view"}),e.jsx(ql,{drivers:W.drivers})]}):null]}):null,e.jsxs("details",{className:"dql-app-report-section dql-app-report-appendix",children:[e.jsxs("summary",{children:[e.jsx("span",{children:"Technical appendix"}),e.jsx("small",{children:"SQL, preview rows, caveats, routing, and source context for analyst review"}),e.jsx(dr,{size:15})]}),e.jsxs("div",{className:"dql-app-research-evidence-head",children:[e.jsxs("div",{children:[e.jsx("h3",{children:"SQL and proof"}),e.jsx("p",{children:"Use this appendix only when you need to inspect routing, repair generated SQL, or validate source context before pinning this memo to the app."})]}),e.jsx("div",{className:"dql-app-research-tabs",children:["preview","sql","assumptions","context"].map(R=>e.jsx("button",{type:"button",className:X===R?"on":"",onClick:()=>I(R),children:R==="assumptions"?"Caveats":Oe(R)},R))})]}),e.jsx(kl,{investigation:h,tab:X,sqlDraft:O,onSqlDraftChange:F})]})]})]}):e.jsxs(e.Fragment,{children:[M?e.jsx("div",{className:"dql-app-error",children:M}):null,Be?e.jsxs("div",{className:"dql-app-research-creating",children:[e.jsx(ar,{size:22}),e.jsx("span",{children:"Preparing business memo"}),e.jsx("h2",{children:"Writing business memo..."}),e.jsx("p",{children:Q?`DQL is opening a scoped memo for "${Q}".`:"DQL is using the Copilot context, active filters, certified block evidence, and any available preview proof to create the main-canvas memo."})]}):e.jsx(kt,{title:"Start analysis from Copilot.",detail:"Ask a follow-up, add context, then review the analysis here."})]})})]}):e.jsx(kt,{title:"No App selected.",detail:"Choose an App before writing analysis."})}function di({item:t,selected:r,onClick:a}){return e.jsxs("button",{type:"button",className:[r?"on":"",`status-${t.status}`].filter(Boolean).join(" "),onClick:a,children:[e.jsx("span",{children:bn(t)}),e.jsx("small",{children:zl(t)})]})}function nl(t,r){const a=Mr(r)||"Review this app result.",i=typeof t=="string"?t.trim():"";if(!i)return a;const s=sl(i);if(s)return s;const n=i.replace(/\bCurrent app filters:\s*[\s\S]*$/i,"").replace(/\bCertified block to start from:\s*[\s\S]*$/i,"").replace(/\bSource result:\s*[\s\S]*$/i,"").replace(/\bUser intent:\s*[\s\S]*$/i,"");return Mr(n)||a}function sl(t){const a=/(?:^|\n)\s*(Analysis goal|Analysis question|Report question|Research question|Proof question|Evidence question|Validation question|Reusable block goal|Business question|Question):\s*/i.exec(t);if(!a)return"";const i=(a.index??0)+a[0].length,s=t.slice(i),n=s.search(/(?:^|\n)\s*(Current app filters|Certified block to start from|Source result|User intent|Review status|Trust status):/i),o=n>=0?s.slice(0,n):s;return Mr(o)}function Mr(t){const r=t.replace(/^\/(ask|research|report|analy[sz]e|analysis|proof|evidence|validate|verify|add\s+block|create\s+block|draft\s+block|block)\b/i,"").replace(/\s+/g," ").trim();if(r.length<=280)return r;const a=r.slice(0,280).replace(/\s+\S*$/,"").trim();return a?`${a}...`:r.slice(0,280)}function ol(t){var O,F;const r=at(t.metrics),a=at(t.context),i=at(t.evidence),s=at(i.planner),n=ll(a,i,s),o=at(a.focusBlock),l=Wa(t),d=at(l==null?void 0:l.result),x=Array.isArray(d.rows)?d.rows.length:0,b=nl(a.userProvidedContext,t.question),m=typeof a.actionMode=="string"?a.actionMode:void 0,f=String(r.context??o.title??t.sourceBlockId??"selected app result"),y=String(a.activeFilterSummary??rl(at(a.activeFilters))),u=fl(t.intent,m),w=ul(t,b,m,f),q=xl(u,b,f,y),C=((O=t.summary)==null?void 0:O.trim())||`DQL wrote review-required analysis for ${f}: ${t.question}. The selected app result is available, but this analysis still needs human review before it becomes governed business logic.`,k=((F=t.recommendation)==null?void 0:F.trim())||"Use this as analyst-reviewed analysis first. Confirm the metric grain, filters, source tables, and caveats before adding it to the app or drafting a reusable DQL block.",M=[{label:String(r.currentLabel??"Current"),value:Pr(r.currentValue),detail:String(r.currentDetail??"current selected result")},{label:String(r.baselineLabel??"Baseline"),value:Pr(r.baselineValue),detail:String(r.baselineDetail??"comparison or prior value")},{label:String(r.deltaLabel??"Delta"),value:Pr(r.delta),detail:String(r.deltaDetail??"change or gap to explain")},{label:"Preview",value:x?`${x} rows`:"not captured",detail:"bounded preview sample"}].filter(cl),L=ml(t),X=x>0||M.length>0||L.length>0||Object.keys(r).length>0,I=wl(t.reportSections).filter(U=>pl(U,t.error,X));return{title:w,intent:t.intent,actionMode:m,scope:q,summary:C,recommendation:k,routeDecision:n,sections:I,previewIssue:dl(t.error,typeof s.sqlErrorKind=="string"?s.sqlErrorKind:void 0,X),contextFacts:[{label:"Type",value:u},{label:"Source",value:f},{label:"Filters",value:y},{label:"Review",value:Oe(t.reviewStatus)}],keyNumbers:M,drivers:L}}function ll(t,r,a){const i=at(t.originatingAnswer),s=at(t.routeDecision),n=at(i.decision),o=at(r.routeDecision),l=at(a.routeDecision),d=Object.keys(s).length?s:Object.keys(n).length?n:Object.keys(o).length?o:Object.keys(l).length?l:{},x=typeof d.reason=="string"?d.reason.trim():"",b=typeof d.nextAction=="string"?d.nextAction.trim():"";if(!x&&!b)return null;const m=typeof d.mode=="string"&&d.mode.trim()?Oe(d.mode):"Analysis",f=typeof d.confidence=="number"&&Number.isFinite(d.confidence)?Math.round(Math.max(0,Math.min(1,d.confidence))*100):void 0;return{mode:m,reason:x,nextAction:b,confidence:f}}function dl(t,r,a=!1){const i=t==null?void 0:t.trim();return!i||a&&(r==="runtime_unavailable"||r==="unknown"||/\bAI provider did not return a governed answer\b/i.test(i))?null:r==="runtime_unavailable"?{message:"Preview could not run because the warehouse or execution runtime is unavailable. Resume or choose an active warehouse, then refresh the report. The SQL may not need to change.",canRebuild:!1}:r==="timeout"?{message:"Preview timed out. Narrow filters or simplify the SQL in the trace appendix, then refresh before promoting this report.",canRebuild:!1}:r==="safety"?{message:"DQL blocked this preview because the SQL is not safe read-only analytical SQL. Rebuild from the certified block or edit it as a SELECT/WITH query before refreshing.",canRebuild:!0}:{message:"SQL preview needs review. Edit the SQL in the trace appendix or rebuild it from the certified block context before promoting this report.",canRebuild:!0}}function pl(t,r,a){const i=String(t.id??"").toLowerCase();return!(t.kind==="review_boundary"||i==="review-boundary"||i==="preview-unavailable"&&a||i==="sql-repair-path"&&a&&/\bAI provider did not return a governed answer\b/i.test(r??""))}function cl(t){const r=t.value.trim().toLowerCase();return!!r&&r!=="n/a"&&r!=="not captured"&&r!=="not available"}function ul(t,r,a,i){const s=Ur(r)||Ur(t.title)||Ur(t.question),n=a==="block"?"Reusable logic":a==="evidence"?"Proof brief":"Analysis",o=Oe(i);return`${n}: ${gl(s||o)}`}function xl(t,r,a,i){const s=Ur(r);return[s?`Question: ${s}`:"",`Source: ${a}`,i&&i!=="No app filters set"?`Filters: ${i}`:"",`Status: ${t} / review-required`].filter(Boolean).join(" · ")}function Ur(t){return Mr(String(t??"")).replace(/^(analysis|report|research|proof|proof brief|reusable logic|reusable logic brief|change analysis|driver analysis|segment comparison|entity drilldown|anomaly review|validation result)\s*:\s*/i,"").replace(/^(analysis goal|analysis question|report question|research question|proof question|evidence question|validation question|reusable block goal|business question|question)\s*:\s*/i,"").trim()}function gl(t){const r=t.replace(/\s+/g," ").trim();return r.length<=96?r:`${r.slice(0,96).replace(/\s+\S*$/,"").trim()||r.slice(0,96)}...`}function fl(t,r){return r==="evidence"?"Proof Brief":r==="block"?"Reusable Logic Brief":t==="diagnose_change"?"Change Analysis":t==="segment_compare"?"Segment Comparison":t==="entity_drilldown"?"Entity Drilldown":t==="anomaly_investigation"?"Anomaly Review":t==="trust_gap_review"?"Proof Review":"Driver Analysis"}function ml(t){const r=(t.driverCards??[]).map(at).filter(n=>Object.keys(n).length>0);if(r.length)return r.slice(0,8).map((n,o)=>({title:String(n.title??`Driver ${o+1}`),value:String(n.contribution??n.value??n.metric??"Proof"),explanation:String(n.explanation??"Review this driver against the source rows and metric grain.")}));const a=Wa(t),i=at(a==null?void 0:a.result);return(Array.isArray(i.rows)?i.rows.map(at).filter(n=>Object.keys(n).length>0):[]).slice(0,5).map((n,o)=>{const l=Object.keys(n),d=l.find(b=>/name|player|customer|account|segment|team/i.test(b))??l[0]??`row_${o+1}`,x=l.find(b=>/point|revenue|total|score|value|delta|count/i.test(b)&&b!==d)??l[1]??d;return{title:String(n[d]??`Preview row ${o+1}`),value:Pr(n[x]),explanation:`This row is part of the bounded preview sample for ${Oe(x)}.`}})}function hl(t){var u,w;if(t.sections.length>0)return t.sections.map(q=>{var k;const C=(k=q.bullets)!=null&&k.length?`
|
|
5579
|
+
`;function hr(t){return String(t??"").replace(/\s+/g," ").replace(/[\s,;:.–—-]+$/,"").trim()}function Oe(t){const r=String(t??"").replace(/[_-]+/g," ").replace(/\s+/g," ").trim();return r?r.split(" ").map(a=>{const i=a.toLowerCase();return i==="ai"?"AI":i==="cxo"?"CXO":i==="kpi"?"KPI":i==="vs"||i==="vs."?"vs.":`${a.charAt(0).toUpperCase()}${a.slice(1)}`}).join(" "):"Business"}function Oa(t){return t.replace(/\bDraft gaps stay in Research until reviewed\.?/gi,"Follow-up analysis stays out of the stakeholder view until reviewed.").replace(/\bresearch path\b/gi,"analysis path").replace(/\bresearch suggestions\b/gi,"analysis suggestions").replace(/\bfollow-up research\b/gi,"follow-up analysis").replace(/\bevidence chips\b/gi,"proof chips").replace(/\bevidence, lineage\b/gi,"proof and lineage").replace(/\bevidence and lineage\b/gi,"proof and lineage").replace(/\bsource evidence\b/gi,"source proof").replace(/\bOpen Research\b/g,"Open Analysis").replace(/\bResearch\b/g,"Analysis")}function sr({icon:t,children:r}){return e.jsxs("div",{className:"dql-app-panel-card",children:[e.jsx("span",{children:t}),e.jsx("div",{children:r})]})}function kt({title:t,detail:r,compact:a=!1}){return e.jsxs("div",{className:`dql-app-empty ${a?"compact":""}`,children:[e.jsx(At,{size:a?24:34,strokeWidth:1.5}),e.jsx("b",{children:t}),e.jsx("span",{children:r})]})}function Zo({appDoc:t}){const r=(t==null?void 0:t.notebooks)??(t==null?void 0:t.app.notebooks)??[];return r.length?e.jsx("div",{className:"dql-app-simple-list",children:r.map(a=>e.jsxs(sr,{icon:e.jsx(Ui,{size:16}),children:[e.jsx("b",{children:a.title??a.path.split("/").pop()}),e.jsxs("span",{children:[a.role," / ",a.visibility," / ",a.path]})]},a.path))}):e.jsx(kt,{title:"No notebooks attached.",detail:"Attach analysis notebooks in Build mode when this App needs supporting work."})}function Do({appDoc:t}){const r=(t==null?void 0:t.aiPins)??[];return r.length?e.jsx("div",{className:"dql-app-simple-list",children:r.map(a=>e.jsxs(sr,{icon:e.jsx(nr,{size:16}),children:[e.jsx("b",{children:a.title}),e.jsxs("span",{children:[a.certification," / ",a.reviewStatus]})]},a.id))}):e.jsx(kt,{title:"No pinned insights yet.",detail:"Use Copilot from a dashboard page, create analysis, then add useful reviewed insights to this App."})}function Uo({appDoc:t}){const r=(t==null?void 0:t.drafts)??[];return r.length?e.jsx("div",{className:"dql-app-simple-list",children:r.map(a=>e.jsxs(sr,{icon:e.jsx(mt,{size:16}),children:[e.jsx("b",{children:a.name}),e.jsxs("span",{children:[a.reviewStatus??"needs review"," / ",a.path]})]},a.path))}):e.jsx(kt,{title:"No drafts.",detail:"Generated and promoted draft blocks will appear here for review."})}function el({appDoc:t}){var r;return t?e.jsxs("div",{className:"dql-app-settings-grid",children:[e.jsxs(sr,{icon:e.jsx(Qe,{size:16}),children:[e.jsx("b",{children:"Owners"}),e.jsx("span",{children:t.app.owners.join(", ")})]}),e.jsxs(sr,{icon:e.jsx(ar,{size:16}),children:[e.jsx("b",{children:"Lifecycle"}),e.jsx("span",{children:t.app.lifecycle??"draft"})]}),e.jsxs(sr,{icon:e.jsx(yr,{size:16}),children:[e.jsx("b",{children:"Policies"}),e.jsxs("span",{children:[t.app.policies.length," local access policies"]})]}),e.jsxs(sr,{icon:e.jsx(At,{size:16}),children:[e.jsx("b",{children:"Homepage"}),e.jsx("span",{children:((r=t.app.homepage)==null?void 0:r.type)??"dashboard"})]})]}):e.jsx(kt,{title:"No App selected.",detail:"Choose an App to inspect its settings."})}function br({children:t,tone:r="certified"}){return e.jsx("span",{className:`dql-app-seal ${r}`,children:t})}function mn(t){return t==null||t===""?"All":Array.isArray(t)?t.map(mn).join(", "):typeof t=="boolean"?t?"On":"Off":typeof t=="number"?t.toLocaleString():typeof t=="object"?JSON.stringify(t):String(t)}function hn(t,r){if(Array.isArray(r))return r.map(i=>hn(t,i)).join(", ");const a=typeof r=="number"?r:typeof r=="string"&&r.trim()!==""?Number(r):NaN;return/(season|year)/i.test(t)&&Number.isInteger(a)&&a>=1900&&a<=2200?String(a):mn(r)}const ga=new Map;function tl(t){const r=Object.entries(t).filter(([a])=>a!=="smartView");return r.length?r.map(([a,i])=>`${Oe(a)} ${hn(a,i)}`).join(", "):"No app filters set"}function rl(t){return t==null?"":typeof t=="number"?Pr(t):typeof t=="string"?t:JSON.stringify(t)}function at(t){return t&&typeof t=="object"&&!Array.isArray(t)?t:{}}function li({label:t,value:r}){return e.jsxs("div",{className:"dql-app-keyvalue-inline",children:[e.jsx("span",{children:t}),e.jsx("b",{children:r})]})}function al({appDoc:t,dashboardDoc:r,seed:a,themeMode:i,onSeedHandled:s,onDashboardChanged:n,onInvestigationsChanged:o,onActiveInvestigationChange:l}){var it;const d=t==null?void 0:t.app.id,x=r==null?void 0:r.dashboard.id,b=Ht[i],[m,f]=p.useState(()=>(t==null?void 0:t.investigations)??[]),[y,u]=p.useState(null),[w,q]=p.useState(!1),[C,k]=p.useState(null),[M,L]=p.useState(null),[X,I]=p.useState("preview"),[O,F]=p.useState(""),[U,_]=p.useState(!1),[A,te]=p.useState(!1),[Q,Y]=p.useState(null);p.useEffect(()=>{if(!d){f([]),u(null);return}let R=!1;return q(!0),D.listAppInvestigations(d).then(le=>{if(R)return;L(null),f(le);const ge=Ca(le);u(ve=>{var Te,de;return ve??((Te=ge.find(Pe=>Pe.status==="ready"))==null?void 0:Te.id)??((de=ge[0])==null?void 0:de.id)??null})}).finally(()=>{R||q(!1)}),()=>{R=!0}},[d]),p.useEffect(()=>{o(m)},[m,o]),p.useEffect(()=>{if(!a||!d)return;let R=!1;const le={dashboardId:a.dashboardId??x,sourceTileId:a.sourceTileId,sourceBlockId:a.sourceBlockId,title:a.title,question:a.question,intent:a.intent,context:a.context,generatedSql:a.generatedSql,run:!0},ge=Mr(a.title??a.question)||"requested follow-up",ve=`${d}:${JSON.stringify(le)}`,Te=async()=>{k("create"),Y(ge),L(null);let Pe=ga.get(ve);Pe||(Pe=D.createAppInvestigation(d,le),ga.set(ve,Pe),Pe.finally(()=>{window.setTimeout(()=>ga.delete(ve),5e3)}));const Ge=await Pe;if(R)return;if(k(null),!Ge.ok){L(Ge.error),Y(null),s();return}const Ye=Ge.investigation,De=Ee=>{f(ze=>Ar(ze,Ee)),u(Ee.id),I("preview"),te(!1),Ee.status!=="draft"&&Ee.status!=="running"&&Y(null)};if(De(Ye),Ye.status!=="draft"&&Ye.status!=="running"){s();return}k(Ye.id);for(let Ee=0;Ee<20;Ee+=1){if(await new Promise(Z=>{window.setTimeout(Z,1e3)}),R)return;const ze=await D.getAppInvestigation(d,Ye.id);if(R)return;if(ze&&ze.status!=="draft"&&ze.status!=="running"){k(null),De(ze),s();return}}s(),k(null),Y(null),L("Analysis is still running. Reopen it or refresh to load the latest proof.")},de=window.setTimeout(()=>void Te(),0);return()=>{R=!0,window.clearTimeout(de)}},[a==null?void 0:a.nonce,d,x,s]);const S=p.useMemo(()=>Ca(m),[m]),h=S.find(R=>R.id===y)??S.find(R=>R.status==="ready")??S[0]??null;p.useEffect(()=>(l(h),()=>l(null)),[h,l]);const $=S.filter(R=>R.id!==(h==null?void 0:h.id)).filter(R=>U||R.status!=="error").slice(0,U?40:5),ee=Math.max(0,S.length-(h?1:0)-$.length),W=h?sl(h):null,$e=W?ml(W):"",se=C==="create"||!!Q,oe=se&&!!Q,Be=se&&!h;p.useEffect(()=>{F((h==null?void 0:h.generatedSql)??"")},[h==null?void 0:h.id,h==null?void 0:h.generatedSql]);const ue=async(R,le)=>{if(!d)return null;k(R.id),L(null);const ge=le==null?void 0:le.trim(),ve=await D.runAppInvestigation(d,R.id,ge?{generatedSql:ge}:void 0);return k(null),ve.ok?(f(Te=>Ar(Te,ve.investigation)),I("preview"),ve.investigation):(L(ve.error),null)},Ae=async R=>{if(!d)return null;k(`rebuild:${R.id}`),L(null);const le=await D.runAppInvestigation(d,R.id,{repairMode:"rebuild_from_certified"});return k(null),le.ok?(f(ge=>Ar(ge,le.investigation)),I(le.investigation.error?"sql":"preview"),le.investigation):(L(le.error),null)},_e=async R=>{if(!d)return null;k(`pin:${R.id}`),L(null);const le=await D.pinAppInvestigation(d,R.id,{dashboardId:R.dashboardId??x,title:R.title});return k(null),le.ok?(f(ge=>Ar(ge,le.investigation)),u(le.investigation.id),le.dashboard&&n(le.dashboard),le.investigation):(L(le.error),null)},Ie=async R=>{if(!d)return;if(!R.generatedSql){L("Add reviewed SQL before creating a draft block.");return}const le=R.pinnedAiPinId?R:await _e(R),ge=le==null?void 0:le.pinnedAiPinId;if(!ge)return;k(`promote:${R.id}`),L(null);const ve=await D.promoteAiPin(d,ge);if(k(null),!ve.ok){L(ve.error??"Draft block could not be created.");return}const Te=await D.getAppInvestigation(d,R.id);Te&&f(de=>Ar(de,Te))},xe=async R=>{const le=O.trim();let ge=R;if(le&&le!==(R.generatedSql??"").trim()){const ve=await ue(R,le);if(!ve)return;ge=ve}await Ie(ge)},Ze=async R=>{const le=O.trim();let ge=R;if(le&&le!==(R.generatedSql??"").trim()){const ve=await ue(R,le);if(!ve)return null;ge=ve}return _e(ge)};return t?e.jsxs("div",{className:`dql-app-research-shell ${A||!h&&!Be?"history-open":"history-collapsed"}`,children:[e.jsxs("section",{className:"dql-app-research-list",children:[e.jsxs("div",{className:"dql-app-research-head",children:[e.jsxs("span",{children:[e.jsx(jt,{size:14})," Analysis"]}),e.jsxs("div",{children:[e.jsx("b",{children:m.length}),h?e.jsx("button",{type:"button",onClick:()=>te(!1),title:"Close analysis history",children:"Close"}):null]})]}),w?e.jsx(kt,{title:"Loading analysis...",detail:"Reading local app analysis.",compact:!0}):null,M?e.jsx("div",{className:"dql-app-error",children:M}):null,!w&&m.length===0?e.jsx(kt,{title:"No analysis yet.",detail:"Start from Copilot so the analysis keeps the original question, filters, and selected result context.",compact:!0}):null,e.jsxs("div",{className:"dql-app-research-items",children:[h?e.jsxs(e.Fragment,{children:[e.jsx("div",{className:"dql-app-research-group-label",children:"Current analysis"}),e.jsx(di,{item:h,selected:!0,onClick:()=>{L(null),u(h.id),I("preview"),te(!1)}})]}):null,$.length?e.jsx("div",{className:"dql-app-research-group-label",children:"Recent history"}):null,$.map(R=>e.jsx(di,{item:R,selected:(h==null?void 0:h.id)===R.id,onClick:()=>{L(null),u(R.id),I("preview"),te(!1)}},R.id)),ee>0?e.jsxs("button",{type:"button",className:"dql-app-research-history-toggle",onClick:()=>_(R=>!R),children:[e.jsx("span",{children:U?"Hide older runs":`Show ${ee} older run${ee===1?"":"s"}`}),e.jsx("small",{children:U?"Keep the current analysis focused":"Includes failed and superseded analysis attempts"})]}):null]})]}),e.jsx("section",{className:"dql-app-research-detail",children:oe?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dql-app-report-toolbar",children:[e.jsxs("div",{children:[e.jsx("span",{children:"New memo"}),e.jsx("b",{children:Q})]}),m.length?e.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>te(R=>!R),children:[e.jsx(jt,{size:13})," ",A?"Hide history":`Analysis history (${m.length})`]}):null]}),M?e.jsx("div",{className:"dql-app-error",children:M}):null,e.jsxs("div",{className:"dql-app-research-creating active",children:[e.jsx(ar,{size:24}),e.jsx("span",{children:"Preparing business memo"}),e.jsx("h2",{children:"Writing business memo..."}),e.jsxs("p",{children:['DQL is opening a scoped memo for "',Q,'". The previous memo stays in history while this answer is built from the typed context, active filters, certified block evidence, and preview proof.']}),e.jsxs("div",{className:"dql-app-research-creating-steps",children:[e.jsx("small",{children:"Reading current filters"}),e.jsx("small",{children:"Checking certified block context"}),e.jsx("small",{children:"Building narrative and proof appendix"})]})]})]}):h&&W?e.jsxs(e.Fragment,{children:[e.jsxs("div",{className:"dql-app-report-toolbar",children:[e.jsxs("div",{children:[e.jsx("span",{children:"Current memo"}),e.jsx("b",{children:bn(h)})]}),e.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>te(R=>!R),children:[e.jsx(jt,{size:13})," ",A?"Hide history":`Memo history (${m.length})`]})]}),se||C===h.id||h.status==="running"?e.jsxs("div",{className:`dql-app-research-status ${se?"opening":""}`,children:[e.jsx(ar,{size:14}),e.jsxs("div",{children:[e.jsx("span",{children:se?"Opening a new business memo...":"Refreshing the memo from certified evidence, active filters, and optional preview proof..."}),Q?e.jsx("small",{children:Q}):null]})]}):null,M?e.jsx("div",{className:"dql-app-error",children:M}):null,e.jsxs("article",{className:"dql-app-research-report",children:[e.jsxs("header",{className:"dql-app-report-hero",children:[e.jsxs("div",{className:"dql-app-report-status-row",children:[e.jsxs("span",{children:[e.jsx(jt,{size:13})," Business memo"]}),e.jsx(br,{tone:h.status==="error"?"draft":"agentic",children:h.reviewStatus})]}),e.jsx("h2",{children:W.title}),e.jsx("p",{children:W.scope}),e.jsx("div",{className:"dql-app-report-context-line",children:W.contextFacts.map(R=>e.jsxs("span",{children:[e.jsx("b",{children:R.label}),R.value]},R.label))}),e.jsxs("div",{className:"dql-app-report-actions",children:[e.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>void Ze(h),disabled:C===`pin:${h.id}`,children:[e.jsx(Ys,{size:13})," ",h.pinnedAiPinId?"Added to App":"Add reviewed insight to App"]}),e.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-primary",onClick:()=>void xe(h),disabled:!(O.trim()||h.generatedSql)||C===`promote:${h.id}`,children:[e.jsx(mt,{size:13})," ",C===`promote:${h.id}`?"Drafting...":"Create draft block"]}),e.jsxs("details",{className:"dql-app-report-review-actions",children:[e.jsx("summary",{children:"Reviewer tools"}),e.jsxs("div",{children:[e.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>void ue(h,O),disabled:C===h.id,children:[e.jsx(ar,{size:13})," ",C===h.id?"Refreshing...":"Refresh memo"]}),(it=W.previewIssue)!=null&&it.canRebuild?e.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>void Ae(h),disabled:C===`rebuild:${h.id}`,children:[e.jsx(ar,{size:13})," ",C===`rebuild:${h.id}`?"Rebuilding...":"Rebuild SQL"]}):null]})]})]}),W.previewIssue?e.jsxs("div",{className:"dql-app-report-warning",children:[e.jsx(Er,{size:14}),e.jsx("span",{children:W.previewIssue.message})]}):null]}),e.jsx("section",{className:"dql-app-report-section dql-app-report-paper",children:W.sections.length?e.jsx(hl,{sections:W.sections}):e.jsx(us,{text:$e,t:b,compact:!0})}),W.keyNumbers.length||W.drivers.length?e.jsxs("section",{className:`dql-app-report-section dql-app-report-evidence-story ${W.keyNumbers.length&&W.drivers.length?"":"single"}`,children:[W.keyNumbers.length?e.jsxs("div",{children:[e.jsx("h3",{children:W.intent==="segment_compare"?"Segment numbers":W.intent==="diagnose_change"?"Movement numbers":"Key numbers"}),e.jsx("div",{className:"dql-app-report-numbers",children:W.keyNumbers.map(R=>e.jsxs("div",{className:"dql-app-report-number",children:[e.jsx("span",{children:R.label}),e.jsx("b",{children:R.value}),e.jsx("small",{children:R.detail})]},R.label))})]}):null,W.drivers.length?e.jsxs("div",{children:[e.jsx("h3",{children:W.intent==="anomaly_investigation"?"Exception view":W.intent==="entity_drilldown"?"Entity view":"Driver view"}),e.jsx(wl,{drivers:W.drivers})]}):null]}):null,e.jsxs("details",{className:"dql-app-report-section dql-app-report-appendix",children:[e.jsxs("summary",{children:[e.jsx("span",{children:"Technical appendix"}),e.jsx("small",{children:"SQL, preview rows, caveats, routing, and source context for analyst review"}),e.jsx(dr,{size:15})]}),e.jsxs("div",{className:"dql-app-research-evidence-head",children:[e.jsxs("div",{children:[e.jsx("h3",{children:"SQL and proof"}),e.jsx("p",{children:"Use this appendix only when you need to inspect routing, repair generated SQL, or validate source context before pinning this memo to the app."})]}),e.jsx("div",{className:"dql-app-research-tabs",children:["preview","sql","assumptions","context"].map(R=>e.jsx("button",{type:"button",className:X===R?"on":"",onClick:()=>I(R),children:R==="assumptions"?"Caveats":Oe(R)},R))})]}),e.jsx(jl,{investigation:h,tab:X,sqlDraft:O,onSqlDraftChange:F})]})]})]}):e.jsxs(e.Fragment,{children:[M?e.jsx("div",{className:"dql-app-error",children:M}):null,Be?e.jsxs("div",{className:"dql-app-research-creating",children:[e.jsx(ar,{size:22}),e.jsx("span",{children:"Preparing business memo"}),e.jsx("h2",{children:"Writing business memo..."}),e.jsx("p",{children:Q?`DQL is opening a scoped memo for "${Q}".`:"DQL is using the Copilot context, active filters, certified block evidence, and any available preview proof to create the main-canvas memo."})]}):e.jsx(kt,{title:"Start analysis from Copilot.",detail:"Ask a follow-up, add context, then review the analysis here."})]})})]}):e.jsx(kt,{title:"No App selected.",detail:"Choose an App before writing analysis."})}function di({item:t,selected:r,onClick:a}){return e.jsxs("button",{type:"button",className:[r?"on":"",`status-${t.status}`].filter(Boolean).join(" "),onClick:a,children:[e.jsx("span",{children:bn(t)}),e.jsx("small",{children:Sl(t)})]})}function il(t,r){const a=Mr(r)||"Review this app result.",i=typeof t=="string"?t.trim():"";if(!i)return a;const s=nl(i);if(s)return s;const n=i.replace(/\bCurrent app filters:\s*[\s\S]*$/i,"").replace(/\bCertified block to start from:\s*[\s\S]*$/i,"").replace(/\bSource result:\s*[\s\S]*$/i,"").replace(/\bUser intent:\s*[\s\S]*$/i,"");return Mr(n)||a}function nl(t){const a=/(?:^|\n)\s*(Analysis goal|Analysis question|Report question|Research question|Proof question|Evidence question|Validation question|Reusable block goal|Business question|Question):\s*/i.exec(t);if(!a)return"";const i=(a.index??0)+a[0].length,s=t.slice(i),n=s.search(/(?:^|\n)\s*(Current app filters|Certified block to start from|Source result|User intent|Review status|Trust status):/i),o=n>=0?s.slice(0,n):s;return Mr(o)}function Mr(t){const r=t.replace(/^\/(ask|research|report|analy[sz]e|analysis|proof|evidence|validate|verify|add\s+block|create\s+block|draft\s+block|block)\b/i,"").replace(/\s+/g," ").trim();if(r.length<=280)return r;const a=r.slice(0,280).replace(/\s+\S*$/,"").trim();return a?`${a}...`:r.slice(0,280)}function sl(t){var O,F;const r=at(t.metrics),a=at(t.context),i=at(t.evidence),s=at(i.planner),n=ol(a,i,s),o=at(a.focusBlock),l=Wa(t),d=at(l==null?void 0:l.result),x=Array.isArray(d.rows)?d.rows.length:0,b=il(a.userProvidedContext,t.question),m=typeof a.actionMode=="string"?a.actionMode:void 0,f=String(r.context??o.title??t.sourceBlockId??"selected app result"),y=String(a.activeFilterSummary??tl(at(a.activeFilters))),u=gl(t.intent,m),w=cl(t,b,m,f),q=ul(u,b,f,y),C=((O=t.summary)==null?void 0:O.trim())||`DQL wrote review-required analysis for ${f}: ${t.question}. The selected app result is available, but this analysis still needs human review before it becomes governed business logic.`,k=((F=t.recommendation)==null?void 0:F.trim())||"Use this as analyst-reviewed analysis first. Confirm the metric grain, filters, source tables, and caveats before adding it to the app or drafting a reusable DQL block.",M=[{label:String(r.currentLabel??"Current"),value:Pr(r.currentValue),detail:String(r.currentDetail??"current selected result")},{label:String(r.baselineLabel??"Baseline"),value:Pr(r.baselineValue),detail:String(r.baselineDetail??"comparison or prior value")},{label:String(r.deltaLabel??"Delta"),value:Pr(r.delta),detail:String(r.deltaDetail??"change or gap to explain")},{label:"Preview",value:x?`${x} rows`:"not captured",detail:"bounded preview sample"}].filter(pl),L=fl(t),X=x>0||M.length>0||L.length>0||Object.keys(r).length>0,I=yl(t.reportSections).filter(U=>dl(U,t.error,X));return{title:w,intent:t.intent,actionMode:m,scope:q,summary:C,recommendation:k,routeDecision:n,sections:I,previewIssue:ll(t.error,typeof s.sqlErrorKind=="string"?s.sqlErrorKind:void 0,X),contextFacts:[{label:"Type",value:u},{label:"Source",value:f},{label:"Filters",value:y},{label:"Review",value:Oe(t.reviewStatus)}],keyNumbers:M,drivers:L}}function ol(t,r,a){const i=at(t.originatingAnswer),s=at(t.routeDecision),n=at(i.decision),o=at(r.routeDecision),l=at(a.routeDecision),d=Object.keys(s).length?s:Object.keys(n).length?n:Object.keys(o).length?o:Object.keys(l).length?l:{},x=typeof d.reason=="string"?d.reason.trim():"",b=typeof d.nextAction=="string"?d.nextAction.trim():"";if(!x&&!b)return null;const m=typeof d.mode=="string"&&d.mode.trim()?Oe(d.mode):"Analysis",f=typeof d.confidence=="number"&&Number.isFinite(d.confidence)?Math.round(Math.max(0,Math.min(1,d.confidence))*100):void 0;return{mode:m,reason:x,nextAction:b,confidence:f}}function ll(t,r,a=!1){const i=t==null?void 0:t.trim();return!i||a&&(r==="runtime_unavailable"||r==="unknown"||/\bAI provider did not return a governed answer\b/i.test(i))?null:r==="runtime_unavailable"?{message:"Preview could not run because the warehouse or execution runtime is unavailable. Resume or choose an active warehouse, then refresh the report. The SQL may not need to change.",canRebuild:!1}:r==="timeout"?{message:"Preview timed out. Narrow filters or simplify the SQL in the trace appendix, then refresh before promoting this report.",canRebuild:!1}:r==="safety"?{message:"DQL blocked this preview because the SQL is not safe read-only analytical SQL. Rebuild from the certified block or edit it as a SELECT/WITH query before refreshing.",canRebuild:!0}:{message:"SQL preview needs review. Edit the SQL in the trace appendix or rebuild it from the certified block context before promoting this report.",canRebuild:!0}}function dl(t,r,a){const i=String(t.id??"").toLowerCase();return!(t.kind==="review_boundary"||i==="review-boundary"||i==="preview-unavailable"&&a||i==="sql-repair-path"&&a&&/\bAI provider did not return a governed answer\b/i.test(r??""))}function pl(t){const r=t.value.trim().toLowerCase();return!!r&&r!=="n/a"&&r!=="not captured"&&r!=="not available"}function cl(t,r,a,i){const s=Ur(r)||Ur(t.title)||Ur(t.question),n=a==="block"?"Reusable logic":a==="evidence"?"Proof brief":"Analysis",o=Oe(i);return`${n}: ${xl(s||o)}`}function ul(t,r,a,i){const s=Ur(r);return[s?`Question: ${s}`:"",`Source: ${a}`,i&&i!=="No app filters set"?`Filters: ${i}`:"",`Status: ${t} / review-required`].filter(Boolean).join(" · ")}function Ur(t){return Mr(String(t??"")).replace(/^(analysis|report|research|proof|proof brief|reusable logic|reusable logic brief|change analysis|driver analysis|segment comparison|entity drilldown|anomaly review|validation result)\s*:\s*/i,"").replace(/^(analysis goal|analysis question|report question|research question|proof question|evidence question|validation question|reusable block goal|business question|question)\s*:\s*/i,"").trim()}function xl(t){const r=t.replace(/\s+/g," ").trim();return r.length<=96?r:`${r.slice(0,96).replace(/\s+\S*$/,"").trim()||r.slice(0,96)}...`}function gl(t,r){return r==="evidence"?"Proof Brief":r==="block"?"Reusable Logic Brief":t==="diagnose_change"?"Change Analysis":t==="segment_compare"?"Segment Comparison":t==="entity_drilldown"?"Entity Drilldown":t==="anomaly_investigation"?"Anomaly Review":t==="trust_gap_review"?"Proof Review":"Driver Analysis"}function fl(t){const r=(t.driverCards??[]).map(at).filter(n=>Object.keys(n).length>0);if(r.length)return r.slice(0,8).map((n,o)=>({title:String(n.title??`Driver ${o+1}`),value:String(n.contribution??n.value??n.metric??"Proof"),explanation:String(n.explanation??"Review this driver against the source rows and metric grain.")}));const a=Wa(t),i=at(a==null?void 0:a.result);return(Array.isArray(i.rows)?i.rows.map(at).filter(n=>Object.keys(n).length>0):[]).slice(0,5).map((n,o)=>{const l=Object.keys(n),d=l.find(b=>/name|player|customer|account|segment|team/i.test(b))??l[0]??`row_${o+1}`,x=l.find(b=>/point|revenue|total|score|value|delta|count/i.test(b)&&b!==d)??l[1]??d;return{title:String(n[d]??`Preview row ${o+1}`),value:Pr(n[x]),explanation:`This row is part of the bounded preview sample for ${Oe(x)}.`}})}function ml(t){var u,w;if(t.sections.length>0)return t.sections.map(q=>{var k;const C=(k=q.bullets)!=null&&k.length?`
|
|
5585
5580
|
|
|
5586
5581
|
${q.bullets.map(M=>`- ${M}`).join(`
|
|
5587
5582
|
`)}`:"";return`## ${q.title}
|
|
@@ -5589,7 +5584,7 @@ ${q.body}${C}`}).join(`
|
|
|
5589
5584
|
|
|
5590
5585
|
`);const r=t.keyNumbers.find(q=>q.value!=="not available"&&q.label!=="Preview"),a=t.keyNumbers.find(q=>/baseline|comparison|next/i.test(q.label)&&q.value!=="not available"),i=t.keyNumbers.find(q=>/delta|gap|change/i.test(q.label)&&q.value!=="not available"),s=t.drivers[0],n=t.drivers[1],o=(u=t.contextFacts.find(q=>q.label==="Source"))==null?void 0:u.value,l=(w=t.contextFacts.find(q=>q.label==="Filters"))==null?void 0:w.value,d=[r?`${r.label}: ${r.value} (${r.detail})`:"",a?`${a.label}: ${a.value} (${a.detail})`:"",i?`${i.label}: ${i.value} (${i.detail})`:""].filter(Boolean).join("; "),x=s?`${s.title} is the strongest visible driver in this bounded preview${s.value?` (${s.value})`:""}.${n?` The next visible comparison is ${n.title}${n.value?` (${n.value})`:""}.`:""}`:"The report does not yet have ranked drivers. Add a clearer metric, time grain, or segment field before treating the analysis as complete.",b=[o?`source: ${o}`:"",l?`filters: ${l}`:""].filter(Boolean).join("; "),m=t.actionMode==="block"?"## Reusable logic decision":t.actionMode==="evidence"||t.intent==="trust_gap_review"?"## Validation result":"## Business interpretation",f=t.actionMode==="block"?"This is a candidate reusable block design, not a certified answer yet. Preserve the business question, parameter defaults, allowed filters, output grain, and proof path before certification.":t.actionMode==="evidence"||t.intent==="trust_gap_review"?`The claim should be treated as validated only inside this bounded analysis context${b?` (${b})`:""}. Use the appendix when a reviewer needs SQL, preview rows, caveats, or source trace.`:`${x} Treat the conclusion as a directional stakeholder explanation until the analyst confirms SQL, grain, filters, joins, and lineage.`,y=["## Executive answer",t.summary,m,f];return d&&y.push("## Key numbers",`The bounded preview shows ${d}. These numbers are useful for review and stakeholder framing but still need source validation before promotion.`),y.push("## Recommended next step",t.recommendation,"## Review boundary","This report is AI-generated and review-required. Use it to guide analysis, then validate SQL, grain, filters, joins, and source proof before pinning it to the app or turning it into a reusable DQL block."),y.join(`
|
|
5591
5586
|
|
|
5592
|
-
`)}function bl({sections:t}){return e.jsx("div",{className:"dql-app-report-dynamic-sections",children:t.map(r=>{var a;return e.jsxs("section",{className:`dql-app-report-dynamic-section tone-${r.tone??"neutral"}`,children:[e.jsxs("div",{className:"dql-app-report-dynamic-head",children:[e.jsx("span",{children:yl(r)}),e.jsx("h3",{children:r.title})]}),e.jsx(vl,{text:r.body}),(a=r.bullets)!=null&&a.length?e.jsx("ul",{children:r.bullets.map(i=>e.jsx("li",{children:i},i))}):null]},r.id)})})}function vl({text:t}){const r=t.split(/\n{2,}/).map(a=>a.replace(/\s*\n\s*/g," ").trim()).filter(Boolean);return r.length?e.jsx("div",{className:"dql-app-report-memo-body",children:r.map(a=>e.jsx("p",{children:a},a))}):null}function yl(t){switch(t.kind){case"executive_answer":return"Answer";case"business_interpretation":return"Interpretation";case"key_numbers":return"Numbers";case"validation":return"Proof";case"reusable_logic":return"Reusable logic";case"recommended_next_step":return"Next step";case"review_boundary":return"Review boundary";default:return/focus/i.test(t.title)?"Scope":/repair|preview|sql/i.test(t.title)?"Appendix note":"Report note"}}function wl(t){return Array.isArray(t)?t.filter(r=>!!r&&typeof r.title=="string"&&r.title.trim().length>0&&typeof r.body=="string"&&r.body.trim().length>0).slice(0,8).map((r,a)=>({...r,id:r.id||`section-${a+1}`,title:r.title.trim(),body:r.body.trim(),bullets:Array.isArray(r.bullets)?r.bullets.filter(Boolean).slice(0,8):void 0,evidenceRefs:Array.isArray(r.evidenceRefs)?r.evidenceRefs.filter(Boolean).slice(0,8):void 0})):[]}function ql({drivers:t}){if(!t.length)return e.jsx("p",{className:"dql-app-report-muted",children:"No ranked drivers are available yet. Refresh the report after adding a clearer metric, time grain, or comparison group."});const r=t.slice(0,6).map(i=>({...i,numericValue:Math.abs(jl(i.value))})),a=Math.max(...r.map(i=>i.numericValue),0);return e.jsx("div",{className:"dql-app-report-driver-chart","aria-label":"Report driver chart",children:r.map((i,s)=>{const n=a>0?Math.max(8,Math.round(i.numericValue/a*100)):28;return e.jsxs("div",{className:"dql-app-report-driver-bar",children:[e.jsxs("div",{children:[e.jsx("b",{children:i.title}),e.jsx("span",{children:i.value})]}),e.jsx("i",{style:{"--driver-width":`${n}%`}}),e.jsx("p",{children:i.explanation})]},`${i.title}-${s}`)})})}function jl(t){const r=t.replace(/,/g,"").match(/-?\+?\d+(?:\.\d+)?/);if(!r)return 0;const a=Number(r[0].replace(/^\+/,""));return Number.isFinite(a)?a:0}function kl({investigation:t,tab:r,sqlDraft:a,onSqlDraftChange:i}){if(r==="sql")return e.jsxs("div",{className:"dql-app-research-sql-review",children:[e.jsx("textarea",{value:a,onChange:n=>i(n.target.value),spellCheck:!1,placeholder:"Generated SQL will appear here for review."}),t.error?e.jsx("div",{className:"dql-app-error",children:t.error}):null]});const s=at(t.evidence);if(r==="assumptions"){const n=Array.isArray(s.assumptions)?s.assumptions:[],o=at(s.trustStatus);return e.jsxs("div",{className:"dql-app-research-assumptions",children:[n.length?n.map((l,d)=>e.jsx("p",{children:String(l)},d)):e.jsx("p",{children:"Refresh the report to capture assumptions."}),e.jsx(li,{label:"Trust",value:String(o.label??"AI-generated report")}),e.jsx(li,{label:"Review",value:t.reviewStatus})]})}return r==="context"?e.jsx("pre",{className:"dql-app-research-code",children:JSON.stringify({certifiedContext:s.certifiedContext,trustStatus:s.trustStatus,planner:s.planner},null,2)}):e.jsx(Sl,{investigation:t})}function Sl({investigation:t}){const r=Wa(t);if(!r)return e.jsx(kt,{title:"No preview rows yet.",detail:"Refresh the report with SQL or selected tile results to capture proof.",compact:!0});const a=at(r.result),i=Array.isArray(a.rows)?a.rows.map(at).filter(n=>!!n).slice(0,8):[],s=Array.isArray(a.columns)?a.columns.map(String).slice(0,8):Object.keys(i[0]??{}).slice(0,8);return!i.length||!s.length?e.jsx(kt,{title:"No preview rows yet.",detail:"The report captured proof, but no row preview was available.",compact:!0}):e.jsx("div",{className:"dql-app-research-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsx("tr",{children:s.map(n=>e.jsx("th",{children:Oe(n)},n))})}),e.jsx("tbody",{children:i.map((n,o)=>e.jsx("tr",{children:s.map(l=>e.jsx("td",{children:al(n[l])},l))},o))})]})})}function Wa(t){return(Array.isArray(t.resultPreviews)?t.resultPreviews:[]).map(at).find(a=>!!a.result)??null}function Ar(t,r){const a=t.filter(i=>i.id!==r.id);return Ca([r,...a])}function Ca(t){return[...t].sort((r,a)=>pi(a)-pi(r))}function pi(t){const r=new Date(t.updatedAt||t.lastRunAt||t.createdAt).getTime();return Number.isFinite(r)?r:0}function bn(t){const r=t.title.replace(/^\s*(write\s+the\s+report\s+brief|the\s+research\s+question|research\s+question)\s*:\s*/i,"").replace(/^\s*research\b/i,"Analysis").replace(/^\s*report\b/i,"Analysis").trim(),a=Oe(r||t.title);return a.length<=64?a:`${a.slice(0,61).trim()}...`}function zl(t){const r=t.status==="error"?"Needs SQL review":t.status==="ready"?"Ready":t.status==="running"?"Running":"Draft",a=Cl(t.updatedAt||t.lastRunAt||t.createdAt);return`${Oe(t.intent)} / ${r}${a?` / ${a}`:""}`}function Cl(t){if(!t)return"";const r=new Date(t).getTime();if(!Number.isFinite(r))return"";const a=Math.max(0,Date.now()-r),i=Math.floor(a/6e4);if(i<1)return"just now";if(i<60)return`${i}m ago`;const s=Math.floor(i/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`}function Pr(t){return typeof t=="number"&&Number.isFinite(t)?Math.abs(t)>=100?Math.round(t).toLocaleString():Number(t.toFixed(2)).toLocaleString():typeof t=="string"&&t.trim()?t:"n/a"}function ci(t){if(!t)return[];const r=new Map;for(const i of t.filters??[])r.set(i.id,{...i});const a=i=>{var s,n;return((s=i.block)==null?void 0:s.blockId)??((n=i.block)==null?void 0:n.ref)};for(const i of t.layout.items??[]){const s=a(i);for(const n of i.filterBindings??[]){const o=n.mode??(n.binding?"predicate":void 0);if(!s||o!=="predicate"||!n.binding||n.unsupportedReason)continue;const l=r.get(n.filter);l&&(l.bindsTo||(l.bindsTo=n.binding),l.sourceBlockId||(l.sourceBlockId=s))}for(const n of i.parameterBindings??[]){const o=n.filter||n.field||n.param;o&&(r.has(o)||El(r,n)||r.set(o,_l(n)))}}return Array.from(r.values()).filter($l)}function Al(t,r,a){const i=((t==null?void 0:t.layout.items)??[]).filter(l=>!Pl(l));if(!((t==null?void 0:t.filters)??[]).some(l=>l.id===r)&&a){const l=new Set((a.tiles??[]).filter(d=>(d.filterableColumns??[]).some(x=>x.column===r)).map(d=>d.tileId).filter(d=>!!d));return{filterId:r,applied:i.filter(d=>l.has(d.i)).map(d=>d.i),unaffected:i.filter(d=>!l.has(d.i)).map(d=>({tileId:d.i,title:d.title,reason:"This tile does not return a column that can be filtered by this value."})),filterable:i.length}}const n=[],o=[];for(const l of i){const d=(l.filterBindings??[]).find(b=>b.filter===r)??(l.parameterBindings??[]).find(b=>(b.filter||b.field||b.param)===r);!!d&&!d.unsupportedReason&&!!(d.binding??d.param)?n.push(l.i):o.push({tileId:l.i,title:l.title,reason:(d==null?void 0:d.unsupportedReason)??(d?"The tile declares this filter but nothing to bind it to.":"This tile has no column matching the filter.")})}return{filterId:r,applied:n,unaffected:o,filterable:i.length}}function Il(t,r,a){var n;if((t.filters??[]).some(o=>o.id===r))return t;const i=new Map;for(const o of(a==null?void 0:a.tiles)??[]){const l=(n=o.filterableColumns)==null?void 0:n.find(d=>d.column===r);o.tileId&&(l!=null&&l.predicateTarget)&&i.set(o.tileId,l.predicateTarget)}const s=o=>o.map(l=>{const d=i.get(l.i);if(!d)return l;const x=(l.filterBindings??[]).filter(b=>b.filter!==r);return{...l,filterBindings:[...x,{filter:r,binding:d,mode:"predicate"}]}});return{...t,filters:[...t.filters??[],{id:r,type:Rl(r),bindsTo:r}],layout:{...t.layout,items:s(t.layout.items)}}}function Nl(t,r){const a=i=>i.map(s=>({...s,filterBindings:(s.filterBindings??[]).filter(n=>n.filter!==r),parameterBindings:(s.parameterBindings??[]).filter(n=>n.filter!==r)}));return{...t,filters:(t.filters??[]).filter(i=>i.id!==r),layout:{...t.layout,items:a(t.layout.items)}}}function Rl(t){return/(_at$|_date$|_time$|_ts$|date|time|day|week|month|quarter|period)/i.test(t)?"daterange":/(top[_-]?n|limit|count|amount|number|year|score|rank)/i.test(t)?"number":/(_name$|_id$|^name$|search|email)/i.test(t)?"search":"select"}function Tl(t,r){var s;const a=new Set(((t==null?void 0:t.filters)??[]).map(n=>n.id)),i=new Map;for(const n of(r==null?void 0:r.tiles)??[])for(const o of n.filterableColumns??[]){if(a.has(o.column))continue;const l=i.get(o.column)??{tiles:0,values:new Set};l.tiles+=1;for(const d of(((s=n.result)==null?void 0:s.rows)??[]).slice(0,24)){const x=d==null?void 0:d[o.column];(typeof x=="string"||typeof x=="number")&&String(x).trim()&&l.values.size<24&&l.values.add(String(x))}i.set(o.column,l)}return Array.from(i.entries()).map(([n,o])=>({column:n,tiles:o.tiles,sampleValues:Array.from(o.values).sort()})).sort((n,o)=>o.tiles-n.tiles||n.column.localeCompare(o.column))}function Pl(t){var a;const r=String(((a=t.viz)==null?void 0:a.type)??"");return!!t.text||r==="text"||r==="heading"}function $l(t){var r;return!(t.type==="select"&&!((r=t.options)!=null&&r.length)&&t.default===void 0&&!t.sourceBlockId)}function _l(t){const r=t.filter||t.field||t.param;return{id:r,type:Bl(r,t.parameterType),default:t.default??vn(r),bindsTo:t.param}}function El(t,r){return Array.from(t.values()).some(a=>r.filter&&a.id===r.filter||r.field&&a.bindsTo===r.field?!0:!!(r.param&&a.bindsTo===r.param))}function Bl(t,r){return r==="number"||r==="number[]"?"number":r==="boolean"?"boolean":r==="date"||r==="date[]"?"date":/(_at$|_date$|_time$|_ts$|date|time|day|week|month|quarter|period)/i.test(t)?"daterange":/(top[_-]?n|limit|count|number|year|season)/i.test(t)?"number":"string"}function vn(t){const r=t.toLowerCase();return/(top[_-]?n|limit)/.test(r)?5:/(season|year).*start|start.*(season|year)/.test(r)?2016:/(season|year).*end|end.*(season|year)/.test(r)?2017:""}function Ml({filters:t,values:r,onChange:a}){return t.length===0?e.jsx("span",{className:"dql-app-filter-empty",children:"No filters"}):e.jsx(e.Fragment,{children:t.map(i=>e.jsx(Ol,{filter:i,value:r[i.id]??$r(i),onChange:s=>a(i,s)},i.id))})}function Ll({candidates:t,coverageFor:r,onApply:a}){const[i,s]=p.useState(""),[n,o]=p.useState(""),l=t.find(x=>x.column===i);if(t.length===0)return null;const d=l?r(l.column):null;return e.jsxs("div",{className:"dql-app-filter-picker",children:[e.jsxs("select",{"aria-label":"Filter this page by",value:i,onChange:x=>{s(x.target.value),o("")},children:[e.jsx("option",{value:"",children:"Filter by…"}),t.map(x=>e.jsx("option",{value:x.column,children:Oe(x.column)},x.column))]}),l?e.jsxs(e.Fragment,{children:[l.sampleValues.length>0?e.jsxs("select",{"aria-label":`${Oe(l.column)} value`,value:n,onChange:x=>o(x.target.value),children:[e.jsx("option",{value:"",children:"Choose a value…"}),l.sampleValues.map(x=>e.jsx("option",{value:x,children:x},x))]}):e.jsx("input",{"aria-label":`${Oe(l.column)} value`,value:n,placeholder:"Value…",onChange:x=>o(x.target.value)}),d?e.jsx("span",{className:"dql-app-filter-coverage-hint",children:d.applied.length===0?"No tile on this page can apply it":`Will narrow ${d.applied.length} of ${d.filterable} tiles`}):null,e.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-primary",disabled:!n.trim(),onClick:()=>{a(l.column,n.trim()),s(""),o("")},children:"Apply"})]}):null]})}function Fl({filters:t,candidates:r,coverageFor:a,onAdd:i,onRemove:s,busy:n}){const[o,l]=p.useState("");return e.jsxs("div",{className:"dql-app-filter-editor",children:[t.map(d=>{const x=a(d.id),b=x.unaffected.length>0&&x.applied.length>0,m=x.applied.length===0;return e.jsxs("div",{className:"dql-app-filter-editor-row",children:[e.jsx("span",{className:"dql-app-filter-editor-name",children:Oe(d.id)}),e.jsx("span",{className:`dql-app-filter-coverage${b?" is-partial":""}${m?" is-none":""}`,title:x.unaffected.length?`Not applied to: ${x.unaffected.map(f=>`${f.title??f.tileId}${f.reason?` — ${f.reason}`:""}`).join("; ")}`:"Applies to every tile on this page.",children:m?"Reaches no tile":`Applies to ${x.applied.length} of ${x.filterable} tile${x.filterable===1?"":"s"}`}),e.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",disabled:n,"aria-label":`Remove the ${Oe(d.id)} filter`,onClick:()=>s(d.id),children:"Remove"})]},d.id)}),r.length>0?e.jsxs("div",{className:"dql-app-filter-editor-row",children:[e.jsxs("select",{"aria-label":"Add a filter column",value:o,disabled:n,onChange:d=>l(d.target.value),children:[e.jsx("option",{value:"",children:"Add a filter…"}),r.map(d=>e.jsxs("option",{value:d.column,children:[Oe(d.column)," — in ",d.tiles," tile",d.tiles===1?"":"s"]},d.column))]}),e.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-primary",disabled:!o||n,onClick:()=>{i(o),l("")},children:"Add filter"})]}):t.length===0?e.jsx("span",{className:"dql-app-filter-empty",children:"No column is shared by enough tiles on this page to act as a global filter."}):null]})}function Ol({filter:t,value:r,onChange:a}){var b,m,f;const i=((b=t.label)==null?void 0:b.trim())||Oe(t.id),s=Wl(t,r),n=t.sourceBlockId,o=t.bindsTo||t.id,l=(t.type==="string"||t.type==="select"||t.type==="multiselect"||t.type==="search")&&!!n&&!((m=t.options)!=null&&m.length),[d,x]=p.useState(null);if(p.useEffect(()=>{if(!l||!n)return;let y=!1;return D.dashboardFilterOptions(n,o).then(u=>{y||x(u&&u.options.length>0&&!u.truncated?u.options:[])}),()=>{y=!0}},[n,o,l]),t.type!=="multiselect"&&d&&d.length>0)return e.jsx(Yr,{icon:rr(t),label:i,value:s,onChange:a,options:[["",`All ${i.toLowerCase()}`],...d.map(y=>[y,y])]});if(t.type==="select"&&ui(t).length>0)return e.jsx(Yr,{icon:rr(t),label:i,value:s,onChange:a,options:ui(t)});if(t.type==="multiselect"){const y=Array.isArray(r)?r.map(String):[],u=t.options??d??[];return e.jsxs("label",{className:"dql-app-filter-select",title:i,"aria-label":i,children:[e.jsx("span",{className:"dql-app-filter-icon",children:rr(t)}),e.jsx("select",{multiple:!0,value:y,"aria-label":`${i} multiple selection`,onChange:w=>a(Array.from(w.currentTarget.selectedOptions,q=>q.value)),children:u.map(w=>e.jsx("option",{value:String(w),children:Oe(String(w))},String(w)))})]})}if(t.type==="relative_date"){const y=(f=t.options)!=null&&f.length?t.options:["last_7_days","last_30_days","last_90_days","month_to_date","quarter_to_date","year_to_date"];return e.jsx(Yr,{icon:rr(t),label:i,value:s,onChange:a,options:y.map(u=>[String(u),Oe(String(u))])})}if(t.type==="boolean")return e.jsx(Yr,{icon:rr(t),label:i,value:String(!!r),onChange:y=>a(y==="true"),options:[["true","Yes"],["false","No"]]});if(t.type==="daterange"){const y=r&&typeof r=="object"&&!Array.isArray(r)?r:{},u=typeof y.start=="string"?y.start:"",w=typeof y.end=="string"?y.end:"",q=(C,k)=>a(C&&k?{start:C,end:k}:void 0);return e.jsxs("label",{className:"dql-app-filter-select dql-app-filter-range",title:t.bindsTo?`${i} -> ${t.bindsTo}`:i,"aria-label":i,children:[e.jsx("span",{className:"dql-app-filter-icon",children:rr(t)}),e.jsx("input",{type:"date",value:u,"aria-label":`${i} from`,onChange:C=>q(C.target.value,w)}),e.jsx("span",{className:"dql-app-filter-range-sep",children:"–"}),e.jsx("input",{type:"date",value:w,"aria-label":`${i} to`,onChange:C=>q(u,C.target.value)})]})}if(t.type==="number_range"){const y=r&&typeof r=="object"&&!Array.isArray(r)?r:{},u=typeof y.min=="number"||typeof y.min=="string"?String(y.min):"",w=typeof y.max=="number"||typeof y.max=="string"?String(y.max):"",q=(C,k)=>a({min:C===""?void 0:Number(C),max:k===""?void 0:Number(k)});return e.jsxs("label",{className:"dql-app-filter-select dql-app-filter-range",title:i,"aria-label":i,children:[e.jsx("span",{className:"dql-app-filter-icon",children:rr(t)}),e.jsx("input",{type:"number",value:u,"aria-label":`${i} minimum`,placeholder:"Min",onChange:C=>q(C.target.value,w)}),e.jsx("span",{className:"dql-app-filter-range-sep",children:"–"}),e.jsx("input",{type:"number",value:w,"aria-label":`${i} maximum`,placeholder:"Max",onChange:C=>q(u,C.target.value)})]})}return e.jsxs("label",{className:"dql-app-filter-select",title:t.bindsTo?`${i} -> ${t.bindsTo}`:i,"aria-label":i,children:[e.jsx("span",{className:"dql-app-filter-icon",children:rr(t)}),e.jsx("input",{type:t.type==="number"?"number":t.type==="date"?"date":"text",value:s,placeholder:i,onChange:y=>a(y.target.value)})]})}function rr(t){return t.type==="date"||t.type==="daterange"||/season|year|date|time|period/i.test(t.id)?e.jsx(zs,{size:13}):e.jsx(sn,{size:13})}function ui(t){var a;return((a=t.options)!=null&&a.length?t.options:[t.default].filter(i=>i!==void 0)).map(i=>[String(i),Oe(String(i))])}function $r(t){var r,a;return t.default!==void 0?t.default:t.type==="number"?vn(t.id):t.type==="boolean"?!1:t.type==="select"?((r=t.options)==null?void 0:r[0])??"":t.type==="multiselect"?[]:t.type==="number_range"?{min:void 0,max:void 0}:t.type==="relative_date"?((a=t.options)==null?void 0:a[0])??"last_30_days":""}function Wl(t,r){return r==null?String($r(t)??""):(t.type==="daterange"||t.type==="number_range"||t.type==="multiselect")&&typeof r=="object"?JSON.stringify(r):String(r)}function Hl(t,r){if(t.type==="number"){if(typeof r=="string"&&r.trim()==="")return"";const a=Number(r);return Number.isFinite(a)?a:r}if(t.type==="boolean")return r===!0||r==="true";if(t.type==="multiselect")return Array.isArray(r)?r.map(String):[];if(t.type==="select"&&typeof t.default=="number"){const a=Number(r);return Number.isFinite(a)?a:r}return r}function xi(t,r){const a=Object.keys(t),i=Object.keys(r);return a.length!==i.length?!1:a.every(s=>Object.is(t[s],r[s]))}function Yr({label:t,icon:r,value:a,options:i,onChange:s}){return e.jsxs("label",{className:"dql-app-filter-select",title:t,"aria-label":t,children:[r?e.jsx("span",{className:"dql-app-filter-icon",children:r}):e.jsx("span",{children:t}),e.jsx("select",{value:a,onChange:n=>s(n.target.value),children:i.map(([n,o])=>e.jsx("option",{value:n,children:o},n))})]})}const Vl=new Set(["table",...Zi.map(t=>t.value)]);function Ha(t){const r=String(t??"table").toLowerCase().replace(/_/g,"-");return r==="single-value"?"kpi":Vl.has(r)?r:"table"}function Va(t,r){const a=t.viz.options??{},i=a,s=typeof a.valueField=="string"?a.valueField:typeof a.field=="string"?a.field:void 0;return{...r??{},...i,chart:Ha(i.chart??t.viz.type??(r==null?void 0:r.chart)),y:i.y??s??(r==null?void 0:r.y),title:i.title??(r==null?void 0:r.title)??t.title,colorPalette:i.colorPalette??(r==null?void 0:r.colorPalette)??"corporate"}}function Kl(t,r){if(!r||t.rows.length<=1||!t.columns.includes(r))return t;const a=t.rows.map(s=>s[r]).filter(s=>typeof s=="number"||typeof s=="string"&&s.trim()!=="").map(Number).filter(Number.isFinite);if(a.length===0)return t;const i=Number(a.reduce((s,n)=>s+n,0).toPrecision(15));return{...t,columns:[r],rows:[{[r]:i}],rowCount:1}}function Bt(t){return t.block?"blockId"in t.block?t.block.blockId??null:t.block.ref??null:null}function Ql(t){return Ha(t)}function aa(t){const r=Ql(t);return r==="table"?"table":r.replace(/-/g,"_")}function gi(t){const r={};for(const[a,i]of Object.entries(t))i===void 0||i===""||(r[a]=i);return r.chart||(r.chart="table"),r}function Wt(t){var a;if(Xr(t.display)){const i=t.display,s=typeof i.component=="string"?i.component:void 0;return{version:1,component:s,role:wn(s),layoutIntent:typeof i.layoutIntent=="string"?i.layoutIntent:void 0,defaultVisualization:typeof i.defaultVisualization=="string"?i.defaultVisualization:void 0,allowedVisualizations:Array.isArray(i.allowedVisualizations)?i.allowedVisualizations.filter(n=>typeof n=="string"):void 0,fieldHints:Xr(i.fieldHints)?Object.fromEntries(Object.entries(i.fieldHints).filter(n=>typeof n[1]=="string")):void 0,insightTitle:t.title,trustState:typeof i.trustState=="string"?i.trustState:void 0,reviewStatus:typeof i.reviewStatus=="string"?i.reviewStatus:void 0,rationale:typeof i.rationale=="string"?i.rationale:void 0}}const r=(a=t.viz.options)==null?void 0:a.dqlGenUi;return Xr(r)?{version:typeof r.version=="number"?r.version:void 0,component:typeof r.component=="string"?r.component:void 0,role:typeof r.role=="string"?r.role:void 0,layoutIntent:typeof r.layoutIntent=="string"?r.layoutIntent:void 0,defaultVisualization:typeof r.defaultVisualization=="string"?r.defaultVisualization:void 0,allowedVisualizations:Array.isArray(r.allowedVisualizations)?r.allowedVisualizations.filter(i=>typeof i=="string"):void 0,fieldHints:Xr(r.fieldHints)?Object.fromEntries(Object.entries(r.fieldHints).filter(i=>typeof i[1]=="string")):void 0,insightTitle:typeof r.insightTitle=="string"?r.insightTitle:void 0,trustState:typeof r.trustState=="string"?r.trustState:void 0,reviewStatus:typeof r.reviewStatus=="string"?r.reviewStatus:void 0,sourceNodeId:typeof r.sourceNodeId=="string"?r.sourceNodeId:void 0,followUpActions:Array.isArray(r.followUpActions)?r.followUpActions.filter(i=>typeof i=="string"):void 0,rationale:typeof r.rationale=="string"?r.rationale:void 0}:null}function fi(t,r){return{mode:"manual",component:t==="heading"?"NarrativePanel":"BusinessBrief",defaultVisualization:t,allowedVisualizations:[t],layoutIntent:t==="heading"?"wide":"standard",rationale:r?`Manual narrative tile for "${r}" on this app surface.`:"Manual narrative tile for this app surface.",trustState:"review_required",reviewStatus:"review_required"}}function yn(t,r,a){var n,o,l,d,x,b,m,f,y;const i=Gl([r,...((n=t.display)==null?void 0:n.allowedVisualizations)??[],...(a==null?void 0:a.allowedVisualizations)??[]]),s=((o=t.display)==null?void 0:o.component)??Yl(r);return{mode:((l=t.display)==null?void 0:l.mode)??(a?"ai_generated":t.block?"block_hint":"manual"),component:s,defaultVisualization:r,allowedVisualizations:i.length?i:[r],...(d=t.display)!=null&&d.fieldHints||a!=null&&a.fieldHints?{fieldHints:((x=t.display)==null?void 0:x.fieldHints)??(a==null?void 0:a.fieldHints)}:{},layoutIntent:Xl(((b=t.display)==null?void 0:b.layoutIntent)??(a==null?void 0:a.layoutIntent)),rationale:((m=t.display)==null?void 0:m.rationale)??(a==null?void 0:a.rationale)??"Visualization selected for this consumer surface.",trustState:Ka(((f=t.display)==null?void 0:f.trustState)??(a==null?void 0:a.trustState)),reviewStatus:Jl(((y=t.display)==null?void 0:y.reviewStatus)??(a==null?void 0:a.reviewStatus))}}function Gl(t){return Array.from(new Set(t.filter(r=>typeof r=="string"&&r.trim()).map(r=>r.trim())))}function Yl(t){return t==="single_value"||t==="kpi"||t==="gauge"?"KpiMetric":t==="line"||t==="area"?"TrendPanel":t==="bar"||t==="grouped_bar"||t==="stacked_bar"||t==="donut"||t==="pie"?"RankingPanel":t==="pivot"?"PivotTable":t==="text"||t==="heading"?"NarrativePanel":"EvidenceTable"}function wn(t){return t==="BusinessBrief"?"business_summary":t==="KpiMetric"?"kpi":t==="TrendPanel"?"trend":t==="RankingPanel"?"breakdown":t==="TrustCallout"?"trust":t==="ResearchActions"?"research":t==="NarrativePanel"?"narrative":t?"evidence":void 0}function Xl(t){return t==="compact"||t==="standard"||t==="wide"||t==="tall"||t==="full"||t==="auto"?t:"auto"}function Ka(t){return t==="certified"||t==="draft_ready"||t==="review_required"?t:"review_required"}function Jl(t){return t==="certified"||t==="draft_ready"||t==="review_required"?t:"review_required"}function Xr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Fr(t){const r=(t??"table").toLowerCase().replace(/-/g,"_");return r==="single_value"||r==="kpi"||r==="gauge"||r==="line"||r==="bar"||r==="area"||r==="pie"||r==="donut"||r==="grouped_bar"||r==="stacked_bar"||r==="scatter"||r==="heatmap"||r==="histogram"||r==="waterfall"||r==="pivot"||r==="map"||r==="funnel"||r==="sankey"||r==="heading"||r==="text"?r:"table"}const qn=[{id:"auto",label:"Auto fit",description:"Choose a practical size from the tile content"},{id:"compact",label:"Compact",description:"Small KPI or short summary"},{id:"standard",label:"Standard",description:"Default chart or table card"},{id:"wide",label:"Wide",description:"Full-row trend or comparison"},{id:"tall",label:"Tall",description:"More vertical room for tables and dense charts"},{id:"full",label:"Full page",description:"Large focused view across the page"}];function Qa(t,r){const a=Fr(t);return a==="heading"?Et("wide",r,"heading"):a==="text"?Et("standard",r,"text"):Et(a==="single_value"||a==="kpi"||a==="gauge"?"compact":a==="table"||a==="pivot"?"tall":a==="line"||a==="area"?"wide":"standard",r,a)}function Ga(t,r){const a=Wt(t),i=Ul(a==null?void 0:a.layoutIntent);return i&&i!=="auto"?Et(i,r,String(t.viz.type??"table")):Qa(Fr(String(t.viz.type??"table")),r)}function Zl(t,r){return t.viz.type==="heading"?90:(r==null?void 0:r.component)==="BusinessBrief"||(r==null?void 0:r.component)==="NarrativePanel"||t.viz.type==="text"?180:(r==null?void 0:r.component)==="TrustCallout"||(r==null?void 0:r.component)==="ResearchActions"?210:(r==null?void 0:r.component)==="EvidenceTable"||(r==null?void 0:r.component)==="PivotTable"?330:(r==null?void 0:r.component)==="KpiMetric"?150:Math.max(280,Math.min(420,t.h*76))}function Et(t,r,a="table"){const i=Math.max(1,r),s=Math.max(1,Math.ceil(i/2)),n=Math.max(1,Math.ceil(i/3));return t==="auto"?Qa(a,i):t==="compact"?{w:n,h:2}:t==="wide"?{w:i,h:a==="heading"?1:4}:t==="tall"?{w:s,h:6}:t==="full"?{w:i,h:7}:{w:s,h:a==="text"?2:4}}function jn(t,r,a){const i=String(t.viz.type??"table"),s=a==="auto"?Ga(t,r):Et(a,r,i);return{w:s.w,h:s.h,x:ia(t.x,0,Math.max(0,r-s.w))}}function Dl(t,r,a){const i=a==="auto"?Ga(t,r):Et(a,r,String(t.viz.type??"table"));return t.w===i.w&&t.h===i.h}function Ul(t){return t==="auto"||t==="compact"||t==="standard"||t==="wide"||t==="tall"||t==="full"?t:null}function ia(t,r,a){return Math.min(a,Math.max(r,t))}function na(t,r){const a=Math.max(1,r),i=[],s=(o,l,d,x)=>{for(let b=0;b<x;b++){const m=i[l+b];if(m){for(let f=0;f<d;f++)if(m[o+f])return!1}}return!0},n=(o,l,d,x)=>{for(let b=0;b<x;b++){const m=l+b;i[m]||(i[m]=new Array(a).fill(!1));for(let f=0;f<d;f++)i[m][o+f]=!0}};return t.map(o=>{const l=ia(Math.round(o.w||1),1,a),d=Math.max(1,Math.round(o.h||1));let x=0,b=0;e:for(let m=0;;m++)for(let f=0;f+l<=a;f++)if(s(f,m,l,d)){x=f,b=m;break e}return n(x,b,l,d),{...o,x,y:b,w:l,h:d}})}function ed(t,r){const a=[...t].map((i,s)=>({item:i,index:s})).sort((i,s)=>{const n=Aa(i.item)-Aa(s.item);return n!==0?n:i.index-s.index}).map(({item:i})=>{const s=Ga(i,r);return{...i,w:s.w,h:s.h}});return na(a,r)}function td(t,r,a){const i=t.filter(o=>o.i!==r.i).sort((o,l)=>or(o,a)-or(l,a)),s=or(r,a),n=i.findIndex(o=>or(o,a)>s);return n===-1?[...i,r]:[...i.slice(0,n),r,...i.slice(n)]}function or(t,r){return t.y*r+t.x}function Aa(t){const r=Wt(t);if((r==null?void 0:r.role)==="business_summary")return 0;if((r==null?void 0:r.role)==="kpi")return 1;if((r==null?void 0:r.component)==="RankingPanel"||(r==null?void 0:r.component)==="TrendPanel")return 2;if((r==null?void 0:r.component)==="EvidenceTable"||(r==null?void 0:r.component)==="PivotTable")return 3;if((r==null?void 0:r.component)==="TrustCallout"||(r==null?void 0:r.component)==="ResearchActions")return 4;if((r==null?void 0:r.role)==="narrative")return 5;const a=Fr(String(t.viz.type??"table"));return a==="heading"?0:a==="single_value"||a==="kpi"||a==="gauge"?1:a==="line"||a==="area"||a==="bar"||a==="pie"||a==="funnel"||a==="map"?2:a==="table"||a==="pivot"?3:a==="text"?4:2}function It(t,r,a=[],i={}){if(r==null||r==="")return"N/A";const s=us(t,r,a,i);return s?typeof r=="string"&&s===r?s.replace(/_/g," "):s:"N/A"}function St(t){return t.replace(/[_-]+/g," ").replace(/\b\w/g,r=>r.toUpperCase())}function wr(t,r){const a=r.slice(0,8).map(i=>i[t]).filter(i=>i!=null&&i!=="");return a.length===0?!1:a.every(i=>typeof i=="number"||typeof i=="string"&&i.trim()!==""&&Number.isFinite(Number(i)))}function rd(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function ad(t,r,a){if(t.length===0)return;const i=a==null?void 0:a.toLowerCase();if(i){const s=t.find(n=>{const o=n.toLowerCase();return o===i||o.includes(i)||i.includes(o)});if(s)return s}return t.find(s=>/\b(name|label|title|dataset|table|block|player|customer|account)\b/i.test(s))??t.find(s=>!wr(s,r))??t[0]}function fa(t){const r=t.toLowerCase();return/(total|count|records|rows|volume)/.test(r)?1:/(rate|percent|pct|score|quality|freshness)/.test(r)?2:/(amount|revenue|arr|value)/.test(r)?3:/(date|time|season)/.test(r)?6:/(^|_)id($|_)/.test(r)?20:100}function kn(t,r){return new Map(t.map(a=>[a,r.slice(0,32).map(i=>i[a])]))}function id(t){var o,l,d,x;if(Bt(t)||t.aiPin)return!1;const r=Wt(t),a=(r==null?void 0:r.component)??((o=t.display)==null?void 0:o.component),i=(r==null?void 0:r.role)??wn(a),s=Ka(String((r==null?void 0:r.trustState)??((l=t.display)==null?void 0:l.trustState)??"review_required"));if(a==="TrustCallout"||a==="ResearchActions"||i==="trust"||i==="research")return!0;if(a!=="NarrativePanel"&&a!=="BusinessBrief"||s==="certified")return!1;const n=[t.title,(d=t.text)==null?void 0:d.markdown,(x=t.display)==null?void 0:x.rationale,r==null?void 0:r.rationale,r==null?void 0:r.insightTitle].filter(Boolean).join(" ").toLowerCase();return/\b(draft ready|review-required|review required|missing evidence|missing proof|trust gap|research drilldown|promote to a certified block|generated review placeholder|generated section)\b/.test(n)}function nd(t,r,a){const s=[...t.filter(n=>!sd(n,r.get(n.i))&&!dd(n,t,r)&&!od(n,t,r))].sort((n,o)=>{const l=hi(o,r.get(o.i),a)-hi(n,r.get(n.i),a);return l!==0?l:or(n,a)-or(o,a)});return na(s,a)}function sd(t,r){var s,n;if(!t.aiPin)return!1;const a=(s=r==null?void 0:r.aiPin)==null?void 0:s.certification,i=(n=r==null?void 0:r.aiPin)==null?void 0:n.reviewStatus;return a!=="certified"&&i!=="certified"}function od(t,r,a){if(!t.aiPin)return!1;const i=mi(t,a.get(t.i));if(!i)return!1;const s=r.findIndex(n=>n.i===t.i);return r.some((n,o)=>n.i===t.i||o>=s||!n.aiPin?!1:mi(n,a.get(n.i))===i)}function mi(t,r){const a=r==null?void 0:r.aiPin,i=a!=null&&a.analysisPlan&&typeof a.analysisPlan=="object"?a.analysisPlan:null,s=Jr(a==null?void 0:a.question)||Jr(t.title),n=Jr(i==null?void 0:i.sourceBlockId),o=Jr(i==null?void 0:i.sourceTileId),l=a!=null&&a.result?ld(a.result):"";return!s&&!n&&!o?"":[s,n,o,l].filter(Boolean).join("|")}function Jr(t){return String(t??"").toLowerCase().replace(/[^a-z0-9]+/g," ").replace(/\s+/g," ").trim()}function ld(t){if(!t||typeof t!="object")return"";const r=t,a=Array.isArray(r.columns)?r.columns.map(s=>String(s).toLowerCase()).join(","):"",i=Array.isArray(r.rows)?r.rows.slice(0,8).map(s=>Ia(s)).join(";"):"";return a||i?`${a}:${i}`:""}function Ia(t){if(t==null)return"";if(typeof t!="object")return String(t);if(Array.isArray(t))return`[${t.map(Ia).join(",")}]`;const r=t;return`{${Object.keys(r).sort().map(a=>`${a}:${Ia(r[a])}`).join(",")}}`}function hi(t,r,a){var s,n,o,l,d;let i=0;return(s=t.parameterBindings)!=null&&s.length&&(i+=5e3),(o=(n=r==null?void 0:r.filters)==null?void 0:n.applied)!=null&&o.length&&(i+=4e3),(r==null?void 0:r.certificationStatus)==="certified"&&(i+=1800),Bt(t)&&(i+=900),(r==null?void 0:r.status)==="ok"&&((d=(l=r.result)==null?void 0:l.rows)!=null&&d.length)&&(i+=500),i-=Aa(t)*80,i-=or(t,a)/1e3,i}function dd(t,r,a){var n;if((n=t.parameterBindings)!=null&&n.length||t.aiPin||!Bt(t))return!1;const i=a.get(t.i),s=i!=null&&i.result?bi(i.result):null;return s?r.some(o=>{if(o.i===t.i||!pd(o,a.get(o.i)))return!1;const l=a.get(o.i),d=l!=null&&l.result?bi(l.result):null;return!!(d&&cd(s,d))}):!1}function pd(t,r){var a,i,s;return!!((a=t.parameterBindings)!=null&&a.length||(s=(i=r==null?void 0:r.filters)==null?void 0:i.applied)!=null&&s.length)}function bi(t){var o;const r=t.rows??[];if(!r.length)return null;const a=(o=t.columns)!=null&&o.length?t.columns:Object.keys(r[0]??{});if(!a.length)return null;const i=Ya(a,r),s=Xa(a,r),n=r[0];return{columns:a.map(l=>l.toLowerCase()).sort().join("|"),label:i?vi(n[i]):"",metric:(s==null?void 0:s.toLowerCase())??"",metricValue:s?vi(n[s]):""}}function cd(t,r){return t.columns===r.columns&&t.label===r.label&&t.metric===r.metric&&t.metricValue===r.metricValue}function vi(t){return t==null?"":typeof t=="number"?Number.isFinite(t)?String(t):"":String(t).trim().toLowerCase().replace(/\s+/g," ")}function ud(t,r,a){var _,A,te,Q;const i=t.map((Y,S)=>({item:Y,tile:r.get(Y.i),index:S})).filter(Y=>{var S,h;return((S=Y.tile)==null?void 0:S.status)==="ok"&&!!Y.tile.result&&Array.isArray((h=Y.tile.result)==null?void 0:h.rows)&&Y.tile.result.rows.length>0}).sort((Y,S)=>{const h=yi(Y.item,Y.tile,Y.index);return yi(S.item,S.tile,S.index)-h})[0];if(!(i!=null&&i.tile.result))return null;const s=i.tile.result,n=s.rows,o=s.columns??Object.keys(n[0]??{});if(!o.length)return null;const l=Wt(i.item),d=Ya(o,n,(_=l==null?void 0:l.fieldHints)==null?void 0:_.label),x=Xa(o,n,((A=l==null?void 0:l.fieldHints)==null?void 0:A.value)??((te=l==null?void 0:l.fieldHints)==null?void 0:te.y)),b=n[0],m=n[1],f=d?n.map(Y=>Y[d]):[],y=x?n.map(Y=>Y[x]):[],u=d?It(d,b[d],f):"The leading result",w=m&&d?It(d,m[d],f):null,q=x?ji(b[x]):null,C=x&&m?ji(m[x]):null,k=x?xd(x):null,M=gd(a),L=M.length?"under the selected app filters":"in the current dashboard view",X=i.item.title??i.tile.title??Bt(i.item)??"Dashboard result",I=s.rowCount??n.length,O=i.tile.certificationStatus==="certified"?"certified":Ka(String(((Q=i.item.display)==null?void 0:Q.trustState)??(l==null?void 0:l.trustState)??"review_required")),F=k?`${St(k)} snapshot`:"Dashboard snapshot";let U;if(x&&k&&q!==null){const Y=`${u} leads ${k} with ${It(x,q,y,{compact:!0})}`;if(w&&C!==null&&Number.isFinite(q-C)){const S=Math.abs(q-C);U=`${Y}, ahead of ${w} by ${It(x,S,y,{compact:!0})} ${L}.`}else U=`${Y} ${L}.`}else U=`${X} returned ${I} ${I===1?"row":"rows"} ${L}.`;return{title:F,summary:U,sourceTitle:X,trust:O,filters:M,chips:[`${I} ${I===1?"row":"rows"}`,o.length?`${o.length} fields`:""].filter(Boolean)}}function yi(t,r,a){var l,d,x,b;const i=Wt(t),s=(i==null?void 0:i.component)??((l=t.display)==null?void 0:l.component),n=r.result;let o=1e3-a;return r.certificationStatus==="certified"&&(o+=500),Bt(t)&&(o+=180),(x=(d=r.filters)==null?void 0:d.applied)!=null&&x.length&&(o+=260),(b=t.parameterBindings)!=null&&b.length&&(o+=220),(s==="RankingPanel"||s==="EvidenceTable"||s==="KpiMetric")&&(o+=120),(t.viz.type==="table"||t.viz.type==="bar"||t.viz.type==="kpi")&&(o+=70),n&&Xa(n.columns,n.rows)&&(o+=80),n&&Ya(n.columns,n.rows)&&(o+=50),o}function Ya(t,r,a){const i=Sn(t,a);return i||(t.find(s=>/\b(player|customer|account|team|segment|category|name|label|title|entity)\b/i.test(s))??t.find(s=>!wr(s,r)&&!/\b(date|time|year|month|id)\b/i.test(s))??t.find(s=>!wr(s,r)))}function Xa(t,r,a){const i=Sn(t,a);return i&&wr(i,r)?i:t.filter(s=>wr(s,r)).sort((s,n)=>wi(s)-wi(n))[0]}function Sn(t,r){const a=r==null?void 0:r.toLowerCase().trim();if(a)return t.find(i=>{const s=i.toLowerCase();return s===a||s.includes(a)||a.includes(s)})}function wi(t){const r=t.toLowerCase();return/(total|revenue|amount|points|score|value|sales|arr|mrr)/.test(r)?1:/(count|orders|games|customers|rows|volume)/.test(r)?2:/(rate|pct|percent|ratio|margin|average|avg)/.test(r)?3:/(rank|position|index)/.test(r)?20:/(date|year|month|day|week|id)/.test(r)?90:30}function xd(t){return St(t).toLowerCase()}function gd(t){return Object.entries(t).filter(([r,a])=>/^(smartView|persona|dashboardId|appId)$/i.test(r)||r.startsWith("__")||a==null||a===""||Array.isArray(a)&&a.length===0?!1:typeof a!="object"||Array.isArray(a)).slice(0,6).map(([r,a])=>({label:St(r),value:Array.isArray(a)?a.map(i=>qi(r,i)).join(", "):qi(r,a)}))}function qi(t,r){const a=typeof r=="number"?r:typeof r=="string"&&r.trim()!==""?Number(r):NaN;return/(season|year)/i.test(t)&&Number.isInteger(a)&&a>=1900&&a<=2200?String(a):It(t,r,[r])}function ji(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim()!==""){const r=Number(t);return Number.isFinite(r)?r:null}return null}function lr(t){return Ha(t)}const fd=p.lazy(()=>oa(()=>import("./UnifiedAgentRunPanel--oxmjlgr.js").then(t=>t.c),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14])).then(t=>({default:t.UnifiedAgentRunPanel}))),md="clamp(320px, calc(100vh - 220px), 760px)",zn=[{value:"table",label:"Table"},...Zi];function hd(t,r){if(!Array.isArray(t)||t.length===0)return;const a=Array.isArray(r)&&r.length>0?r.slice(0,8):Object.keys(t[0]??{}).slice(0,8);return t.slice(0,5).map(i=>Object.fromEntries(a.map(s=>[s,i[s]])))}function bd({appId:t,dashboard:r,variables:a,editable:i=!1,embeddedHeader:s=!1,onDashboardChanged:n,selectedBlockId:o,onBlockFocus:l,onAskBlock:d,onOpenLineageNode:x,copilotOpen:b,onCopilotChange:m,onRunChange:f}){var Nt;const{state:y}=Ki(),u=Ht[y.themeMode],[w,q]=p.useState(null),[C,k]=p.useState(null),M=p.useRef(null),[L,X]=p.useState(!1),I=p.useRef(0),[O,F]=p.useState(null),[U,_]=p.useState(!1),A=Ba(`app:${t}:${r.id}`),[te,Q]=p.useState(!1),[Y,S]=p.useState([]),[h,$]=p.useState(""),[ee,W]=p.useState(!1),[$e,se]=p.useState(null),[oe,Be]=p.useState(!1),[ue,Ae]=p.useState(null),[_e,Ie]=p.useState(null),[xe,Ze]=p.useState(null),[it,R]=p.useState(!1),[le,ge]=p.useState(!1),[ve,Te]=p.useState(null),[de,Pe]=p.useState(""),[Ye,Xe]=p.useState(null),De=p.useRef(null),Ee=p.useRef(null),[ze,Z]=p.useState(1120),pe=ze<720?"narrow":ze<1120?"medium":"wide",ye=r.layout.responsive,Ne=vs(),We=p.useMemo(()=>JSON.stringify(a??{}),[a]),Me=p.useMemo(()=>JSON.parse(We),[We]),Ue=p.useMemo(()=>{const N=new Map;for(const B of(w==null?void 0:w.tiles)??[])N.set(B.tileId,B);return N},[w]),we=ue??r.layout.items,nt=p.useMemo(()=>{const N=ye==null?void 0:ye[pe],B=pe==="wide"?{kind:"grid",cols:r.layout.cols,rowHeight:r.layout.rowHeight,items:we}:N??{kind:"grid",cols:pe==="medium"?6:1,rowHeight:r.layout.rowHeight,items:Ip(we,pe==="medium"?6:1)},g=new Map(we.map(K=>[K.i,K]));return{...B,items:B.items.map(K=>({...g.get(K.i),...K}))}},[pe,r.layout.cols,r.layout.rowHeight,ye,we]),Le=pe==="narrow",re=nt.cols,lt=nt.rowHeight,Ce=i&&pe==="wide",bt=p.useMemo(()=>({...r,layout:{...r.layout,items:we}}),[r,we]),ie=p.useMemo(()=>i?nt.items:nt.items.filter(N=>!id(N)),[nt.items,i]),dt=p.useMemo(()=>i?ie:nd(ie,Ue,re),[ie,re,i,Ue]),He=r.layout.items.length-ie.length,et=ie.length-dt.length,Re=p.useMemo(()=>!i&&!r.story&&r.sections&&r.sections.length>0?[...r.sections].sort((N,B)=>N.order-B.order):null,[r.sections,r.story,i]),gt=p.useMemo(()=>Re?nt.items:null,[nt.items,Re]),H=p.useMemo(()=>i||Re?null:ud(dt,Ue,Me),[i,Me,Re,Ue,dt]);p.useEffect(()=>{Ae(null),Ie(null)},[r.id]),p.useEffect(()=>{const N=I.current+1;I.current=N;const B=()=>I.current===N;X(!0),F(null),D.runDashboard(t,r.id,Me).then(g=>{B()&&(q(g),k((g==null?void 0:g.story)??null),M.current=(g==null?void 0:g.runId)??null,f==null||f(g),g||F("Dashboard run failed."),g!=null&&g.runId&&D.getDashboardStory(t,r.id,g.runId).then(K=>{!B()||!K||M.current!==K.runId||K.snapshotId!==g.snapshotId||K.filterFingerprint!==g.filterFingerprint||K.resultFingerprint!==g.resultFingerprint||K.personaFingerprint!==g.personaFingerprint||k(K.story)}))}).catch(g=>{B()&&(F(g instanceof Error?g.message:String(g)),f==null||f(null))}).finally(()=>{B()&&X(!1)})},[t,r.id,r.layout.items.length,f,Me,(Nt=y.activePersona)==null?void 0:Nt.userId]),p.useEffect(()=>{const N=B=>{const g=B.detail;(g==null?void 0:g.appId)!==t||g.dashboardId!==r.id||(D.getDashboard(t,r.id).then(K=>{K!=null&&K.dashboard&&(n==null||n(K.dashboard))}),D.runDashboard(t,r.id,Me).then(K=>{K&&(q(K),k(K.story),M.current=K.runId,f==null||f(K))}))};return window.addEventListener("dql-app-dashboard-updated",N),()=>window.removeEventListener("dql-app-dashboard-updated",N)},[t,r.id,n,f,Me]),p.useEffect(()=>{const N=De.current;if(!N)return;const B=()=>Z(N.getBoundingClientRect().width);B();const g=new ResizeObserver(B);return g.observe(N),()=>g.disconnect()},[]);const ke=p.useMemo(()=>{const N=r.layout.items.map(B=>{var me,rt,Ve,yt,Je;const g=Ue.get(B.i),K=B.block?"blockId"in B.block?B.block.blockId:B.block.ref:B.semantic?`semantic:${B.semantic.id}`:B.draftAnalysis?`draft:${B.draftAnalysis.ref}`:B.aiPin?`aiPin:${B.aiPin.id}`:"text";return{title:B.title,blockRef:K,viz:B.viz.type,certificationStatus:g==null?void 0:g.certificationStatus,status:g==null?void 0:g.status,rowCount:(me=g==null?void 0:g.result)==null?void 0:me.rowCount,columns:(Ve=(rt=g==null?void 0:g.result)==null?void 0:rt.columns)==null?void 0:Ve.slice(0,8),sampleRows:hd((yt=g==null?void 0:g.result)==null?void 0:yt.rows,(Je=g==null?void 0:g.result)==null?void 0:Je.columns)}});return JSON.stringify({scope:"dashboard",appId:t,dashboardId:r.id,title:r.metadata.title,description:r.metadata.description,domain:r.metadata.domain,filters:r.filters,variables:Me,run:w?{runId:w.runId,snapshotId:w.snapshotId,filterFingerprint:w.filterFingerprint,resultFingerprint:w.resultFingerprint,personaFingerprint:w.personaFingerprint,story:w.story,facts:w.facts}:null,tiles:N},null,2)},[t,r,w,Me,Ue]),fe=p.useCallback(async(N,B="Changes saved")=>{Be(!0),F(null);const g={...r,layout:{...r.layout,items:N}};try{const K=await D.patchDashboardLayout(t,r.id,g.layout);K.ok?(Ae(null),Ie(B),n==null||n(K.dashboard)):F(K.error)}finally{Be(!1)}},[t,r,n]),qe=p.useCallback(async(N,B="geometry")=>{if(ue&&B==="geometry"){Ae(N),Ie("Layout preview ready");return}ue&&Ae(N),await fe(N)},[ue,fe]),zt=p.useCallback(async()=>{Q(!0);const N=await D.getAppEditorCatalog(t);S((N==null?void 0:N.blocks)??[])},[t]),vt=p.useCallback(async N=>{const B=Fr(N.chartType),g=await D.recommendDashboardTile(t,r.id,{blockRef:N.name,appAudience:r.metadata.audience,prompt:`${r.metadata.title} ${N.name} ${N.description}`,defaultVisualization:B}),K=Qa(B,re),me={i:ha(bt,N.name),...ma(bt,K),block:{blockId:N.name},viz:{type:B},...g.ok?{display:g.display,filterBindings:"filterBindings"in g?g.filterBindings:void 0,parameterBindings:"parameterBindings"in g?g.parameterBindings:void 0,sourceEvidence:"sourceEvidence"in g?g.sourceEvidence:void 0,trustState:"trustState"in g?g.trustState:g.display.trustState,reviewStatus:"reviewStatus"in g?g.reviewStatus:g.display.reviewStatus}:{},title:N.name};await qe([...we,me],"content"),Q(!1)},[t,re,r.id,r.metadata.audience,r.metadata.title,qe,bt,we]),Vt=p.useCallback(async()=>{Te("text"),Pe("")},[]),Dt=p.useCallback(async()=>{Te("heading"),Pe("")},[]),Ut=p.useCallback(async()=>{var B;const N=de.trim();if(!(!N||!ve)){if(ve==="heading")await qe([...we,{i:ha(bt,"section"),...ma(bt,Et("wide",re,"heading")),text:{markdown:N},viz:{type:"heading"},display:fi("heading",N),title:N}],"content");else{const g=((B=N.split(/\r?\n/)[0])==null?void 0:B.slice(0,60))||"Summary";await qe([...we,{i:ha(bt,"text"),...ma(bt,Et("standard",re,"text")),text:{markdown:N},viz:{type:"text"},display:fi("text",g),title:g}])}Te(null),Pe("")}},[re,qe,ve,de,bt,we]),pr=p.useCallback(async(N,B)=>{const g=B===null?we.filter(me=>me.i!==N):we.map(me=>me.i===N?{...me,...B}:me),K=B!==null&&Object.keys(B).every(me=>me==="x"||me==="y"||me==="w"||me==="h");await qe(na(g,re),K?"geometry":"content")},[re,qe,we]),pt=p.useCallback(async(N,B)=>{const g=Ee.current,K=we.find(Mt=>Mt.i===N);if(!g||!K)return;const me=g.getBoundingClientRect(),rt=12,yt=(me.width-rt*(re-1))/re+rt,Je=lt+rt,je=Math.round((B.clientX-me.left)/yt),wt=Math.round((B.clientY-me.top)/Je),gr={...K,x:ia(je,0,Math.max(0,re-K.w)),y:Math.max(0,wt)};Xe(null);const ut=td(we,gr,re);await qe(na(ut,re))},[re,lt,qe,we]),_t=p.useCallback((N,B)=>{const g=Ee.current,K=we.find(je=>je.i===N);if(!g||!K)return;const me=g.getBoundingClientRect(),rt=12,Ve=(me.width-rt*(re-1))/re,yt=Math.round((B.clientX-me.left)/(Ve+rt)),Je=Math.round((B.clientY-me.top)/(lt+rt));Xe({tileId:N,x:ia(yt,0,Math.max(0,re-K.w)),y:Math.max(0,Je),w:K.w,h:K.h})},[re,lt,we]),st=p.useCallback(()=>Xe(null),[]),Kt=p.useCallback(()=>{we.length!==0&&(Ae(ed(we,re)),Ie("Layout preview ready"))},[re,we]),Qt=p.useCallback(async()=>{ue&&await fe(ue,"Layout applied")},[ue,fe]),cr=p.useCallback(()=>{Ae(null),Ie("Layout preview cancelled")},[]),er=p.useCallback(async N=>{Ze(N);const B=await D.retryDashboardTile(t,r.id,N,Me);Ze(null);const g=B==null?void 0:B.tiles.find(me=>me.tileId===N);if(!B||!g){F("This App tile could not be retried.");return}const K=w?{...w,tiles:w.tiles.map(me=>me.tileId===N?g:me)}:B;q(K),k(null),f==null||f(K)},[t,r.id,f,w,Me]),ur=p.useCallback(async(N,B)=>{const g=B.artifact,K={title:N.title??(g==null?void 0:g.name)??B.title??"App analysis",sql:g==null?void 0:g.sql,result:B.result,chartConfig:Va(N,B.chartConfig),sourceRunId:w==null?void 0:w.runId,question:`App tile: ${N.title??B.title??N.i}`,executionTarget:g==null?void 0:g.executionTarget,...g!=null&&g.dql?{dqlArtifact:{kind:g.sourceKind==="certified_block"?"certified_block":"sql_block",source:g.dql,name:g.name,sourcePath:g.sourcePath,persistence:g.sourcePath?"saved":"transient",trustState:g.trustState,compiledSql:g.sql}}:{}};await Ne(K)},[Ne,w==null?void 0:w.runId]),xr=p.useCallback(async()=>{if(W(N=>!N),!$e){const N=await D.fetchScopedLineage({domain:r.metadata.domain,appId:t,dashboardId:r.id});se(N)}},[t,r.id,r.metadata.domain,$e]),Gt=p.useCallback(()=>{if(x){x(`dashboard:${t}/${r.id}`);return}xr()},[t,r.id,xr,x]),Yt=m?!!b:U,ct=p.useCallback(()=>{if(R(!1),m){m(!0);return}_(!0)},[m]),ft=p.useCallback(()=>{if(R(!1),m){m(!b);return}_(N=>!N)},[b,m]);return e.jsxs("div",{ref:De,"data-dashboard-breakpoint":pe,style:{display:"block",minHeight:0,containerType:"inline-size"},children:[e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx(Kd,{saving:oe,error:O,pending:!!ue,notice:_e,onDismissError:()=>F(null)}),!i&&dt.length>0&&He+et>0?e.jsxs("div",{role:"status",style:Nr("var(--text-tertiary)"),children:[e.jsx(Qe,{size:13}),He+et," tile",He+et===1?" is":"s are"," hidden from this stakeholder view because ",He>0?"they still need review":"a certified tile already answers the same question",". Switch to Edit to see everything on this page."]}):null,(!s||i)&&e.jsxs("div",{style:Jd,children:[e.jsx("div",{style:{flex:1,minWidth:0},children:s?null:e.jsxs(e.Fragment,{children:[e.jsx("h2",{style:{margin:0,fontSize:20,lineHeight:1.18,fontWeight:780},children:r.metadata.title}),r.metadata.description?e.jsx("div",{style:{fontSize:13,opacity:.72,marginTop:4,maxWidth:680,lineHeight:1.4},children:r.metadata.description}):null]})}),i&&r.layout.items.length>0&&e.jsx(Ii,{open:it,onToggle:()=>R(N=>!N),buttonStyle:Xd,onCertifiedBlock:()=>{R(!1),zt()},onText:()=>{R(!1),Vt()},onHeading:()=>{R(!1),Dt()},onAi:ct}),i&&r.layout.items.length>1&&!ue&&e.jsxs("button",{type:"button",onClick:Kt,disabled:oe,style:Ot(!1),title:"Auto-arrange every tile into a clean, gap-free grid",children:[e.jsx(tn,{size:15,strokeWidth:2}),"Auto layout"]}),i&&ue?e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>void Qt(),disabled:oe,style:Ot(!0),children:oe?"Applying…":"Apply layout"}),e.jsx("button",{type:"button",onClick:cr,disabled:oe,style:Ot(!1),children:"Cancel"})]}):null,!s&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:ft,style:Ot(Yt),children:[e.jsx(nr,{size:14,strokeWidth:2}),Yt?"Hide copilot":"AI Copilot"]}),e.jsxs("button",{type:"button",onClick:Gt,style:Ot(!1),title:"Open focused dashboard lineage",children:[e.jsx(Qi,{size:14,strokeWidth:2}),"Lineage"]})]})]}),i&&e.jsx("div",{style:rp,children:Ce?"Drag tiles, select a block for Copilot context, or use the tile controls for sizing and chart settings.":`${pe==="medium"?"Tablet":"Mobile"} preview uses the saved responsive projection. Return to a wide canvas to rearrange tiles.`}),!i&&C?e.jsx(kd,{story:C,onResearch:ct,onEvidence:Gt}):H?e.jsx(jd,{story:H}):null,dt.length===0?e.jsxs("div",{style:{border:"1px dashed var(--border-color, rgba(0,0,0,0.15))",borderRadius:8,padding:36,textAlign:"center",fontSize:13,minHeight:260,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},children:[e.jsx("div",{style:{fontSize:16,fontWeight:700,marginBottom:6},children:He>0||et>0?"No stakeholder-ready tiles yet":"Build this dashboard page"}),e.jsx("div",{style:{maxWidth:520,opacity:.68,lineHeight:1.45},children:He>0?"Generated analysis and trust placeholders are hidden from the stakeholder view. Open Customize or Analysis to review them, then add certified blocks or pinned insights.":et>0?"Static duplicate tiles are hidden from the stakeholder view because a filter-aware certified tile can answer the same question.":"Add certified domain blocks, narrative text, or use the scoped AI drawer and pin an answer into this layout."}),e.jsx("div",{style:{marginTop:18,display:"flex",gap:8,flexWrap:"wrap",justifyContent:"center"},children:e.jsx(Ii,{open:it,onToggle:()=>R(N=>!N),buttonLabel:"Add tile",buttonStyle:Bn,onCertifiedBlock:()=>{R(!1),zt()},onText:()=>{R(!1),Vt()},onHeading:()=>{R(!1),Dt()},onAi:ct})})]}):Re?e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:22},children:Re.map(N=>{var yt,Je;const B=(yt=Re.find(je=>je.kind==="appendix"))==null?void 0:yt.id,g=((Je=Re.find(je=>je.kind==="insight"))==null?void 0:Je.id)??Re[0].id,K=je=>je.sectionId&&Re.some(wt=>wt.id===je.sectionId)?je.sectionId:(je.trustState==="review_required"||je.reviewStatus==="review_required")&&B?B:g,me=(gt??dt).filter(je=>K(je)===N.id);if(me.length===0)return null;const rt=Math.min(...me.map(je=>je.y)),Ve=N.kind==="appendix";return e.jsxs("section",{"aria-label":N.title,children:[N.kind!=="exec_summary"?e.jsxs("div",{style:{marginBottom:10},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("h3",{style:{margin:0,fontSize:15,fontWeight:800,color:"var(--dql-app-text, #0f172a)"},children:N.title}),Ve?e.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:4,border:"1px solid rgba(217,119,6,0.4)",color:"#b45309",background:"rgba(217,119,6,0.08)",borderRadius:999,padding:"1px 8px",fontSize:10,fontWeight:800},children:"needs review"}):null]}),N.narrative?e.jsx("p",{style:{margin:"4px 0 0",fontSize:12.5,lineHeight:1.5,color:"var(--dql-app-text-muted, #64748b)",maxWidth:860},children:N.narrative}):null]}):null,e.jsx("div",{style:{display:"grid",gridTemplateColumns:Le?"minmax(0, 1fr)":`repeat(${re}, 1fr)`,gridAutoRows:Le?"auto":`${lt}px`,gap:12,...Ve?{opacity:.96}:{}},children:me.map(je=>e.jsx(ki,{item:{...je,y:je.y-rt},tile:Ue.get(je.i),loading:L,error:O,themeMode:y.themeMode,editable:!1,narrow:Le,cols:re,selected:!!(Bt(je)&&Bt(je)===o),onFocusBlock:l,onAskBlock:d,onMove:()=>{},onDragMove:()=>{},onDragEnd:()=>{},onPatch:wt=>void pr(je.i,wt),onRetry:()=>void er(je.i),retrying:xe===je.i,retryDisabled:!!(xe&&xe!==je.i),onOpenNotebook:wt=>void ur(je,wt),activeVariables:Me},je.i))})]},N.id)})}):e.jsxs("div",{ref:Ee,style:{display:"grid",gridTemplateColumns:Le?"minmax(0, 1fr)":`repeat(${re}, 1fr)`,gridAutoRows:Le?"auto":`${lt}px`,gap:12},children:[Ye&&!Le&&e.jsx("div",{"aria-hidden":"true",style:{gridColumn:`${Ye.x+1} / span ${Ye.w}`,gridRow:`${Ye.y+1} / span ${Ye.h}`,border:"2px dashed var(--dql-app-accent, var(--accent, #4f46e5))",background:"var(--dql-app-accent-soft, rgba(79,70,229,0.10))",borderRadius:10,pointerEvents:"none",zIndex:10}}),dt.map(N=>e.jsx(ki,{item:N,tile:Ue.get(N.i),loading:L,error:O,themeMode:y.themeMode,editable:Ce,narrow:Le,cols:re,selected:!!(Bt(N)&&Bt(N)===o),onFocusBlock:l,onAskBlock:d,onMove:B=>void pt(N.i,B),onDragMove:B=>_t(N.i,B),onDragEnd:st,onPatch:B=>void pr(N.i,B),onRetry:()=>void er(N.i),retrying:xe===N.i,retryDisabled:!!(xe&&xe!==N.i),onOpenNotebook:B=>void ur(N,B),activeVariables:Me},N.i))]}),!i&&w?e.jsx(Sd,{run:w,variables:Me}):null]}),ee&&!x&&e.jsx("aside",{style:{width:340,minWidth:300,maxWidth:"34vw",border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:8,overflow:"auto",alignSelf:"flex-start",height:md,position:"sticky",top:12,padding:12},children:e.jsx(Wd,{lineage:$e})}),U&&!m&&e.jsx(Ea,{t:u,title:"Dashboard AI",subtitle:"Scoped to this App dashboard first",expanded:le,onToggleExpanded:()=>ge(N=>!N),onClose:()=>{_(!1),ge(!1)},floating:!0,ariaLabel:"Dashboard AI",style:ap(le),children:e.jsx(p.Suspense,{fallback:e.jsx("div",{style:{padding:16,fontSize:12,color:u.textSecondary},children:"Loading Dashboard AI…"}),children:e.jsx(fd,{themeMode:y.themeMode,title:"Dashboard AI",scopeHint:"Scoped to this App dashboard first",audience:"stakeholder",workspaceContext:{appId:t,dashboardId:r.id,dashboardContext:ke},initialMode:"auto",threadId:A.threadId,onThreadIdChange:A.onThreadIdChange},`${t}:${r.id}`)})}),te&&e.jsx(Od,{blocks:Y,search:h,onSearch:$,onClose:()=>Q(!1),onAdd:N=>void vt(N)}),ve&&e.jsx(Fd,{kind:ve,value:de,onChange:Pe,onClose:()=>{Te(null),Pe("")},onSave:()=>void Ut()})]})}function ki({item:t,tile:r,loading:a,error:i,themeMode:s,editable:n,narrow:o,cols:l,selected:d,onFocusBlock:x,onAskBlock:b,onMove:m,onDragMove:f,onDragEnd:y,onPatch:u,onRetry:w,retrying:q=!1,retryDisabled:C=!1,onOpenNotebook:k,activeVariables:M}){var Ee,ze;const L=p.useRef(null),[X,I]=p.useState(null),[O,F]=p.useState(!1),[U,_]=p.useState(!1),[A,te]=p.useState("how"),Q=Bt(t),Y=!!(!n&&Q&&b),S=Q?`block:${Q}`:t.semantic?`semantic:${t.semantic.id}`:t.draftAnalysis?`draft:${t.draftAnalysis.ref}`:t.aiPin?`aiPin:${t.aiPin.id}`:"text",[h,$]=p.useState(()=>lr(t.viz.type));p.useEffect(()=>$(lr(t.viz.type)),[t.i,t.viz.type]);const ee=n?lr(t.viz.type):h,W=p.useMemo(()=>n||ee===lr(t.viz.type)?t:{...t,viz:{...t.viz,type:aa(ee),options:{...t.viz.options??{},chart:ee}}},[ee,n,t]),$e=Fr(String(W.viz.type??"table")),se=Wt(t),oe=se==null?void 0:se.component,Be=t.title||(se==null?void 0:se.insightTitle)||S,ue=(r==null?void 0:r.tileType)==="aiPin"?((Ee=r.aiPin)==null?void 0:Ee.certification)==="certified"?"certified":"review_required":void 0,Ae=r==null?void 0:r.repair,_e=Ae?"review_required":((ze=r==null?void 0:r.artifact)==null?void 0:ze.trustState)??(se==null?void 0:se.trustState)??ue??((r==null?void 0:r.certificationStatus)==="certified"?"certified":void 0),Ie=!!se,xe=t.h<=2&&($e==="single_value"||$e==="kpi"||$e==="gauge"),[Ze,it]=p.useState(!1),R=n&&(Ze||d||O);p.useEffect(()=>{if(!n)return;const Z=pe=>{pe.detail!==t.i&&F(!1)};return window.addEventListener("dql-app-tile-settings-open",Z),()=>window.removeEventListener("dql-app-tile-settings-open",Z)},[n,t.i]);const le=()=>{F(Z=>{const pe=!Z;return pe&&window.dispatchEvent(new CustomEvent("dql-app-tile-settings-open",{detail:t.i})),pe})},ge=p.useMemo(()=>{const Z=Object.entries(M??{}).filter(([,ye])=>ye!=null&&ye!=="").map(([ye])=>ye);if(Z.length===0)return null;const pe=Z.filter(ye=>{const Ne=(t.filterBindings??[]).find(We=>We.filter===ye)??(t.parameterBindings??[]).find(We=>(We.filter||We.field||We.param)===ye);return!Ne||!!Ne.unsupportedReason||!(Ne.binding??Ne.param)});return pe.length===0?null:{label:pe.length===1?`Not filtered by ${pe[0]}`:`Not filtered by ${pe.length} page filters`,detail:`This tile has no column bound to ${pe.join(", ")}, so it shows the full scope while the rest of the page is narrowed.`}},[M,t.filterBindings,t.parameterBindings]),ve=Z=>{const pe=Z.trim();if(!pe||pe===t.title)return;const ye=Wt(t);u({title:pe,...ye?{viz:{...t.viz,options:{...t.viz.options??{},dqlGenUi:{...ye,insightTitle:pe}}}}:{}})},Te=Hd(t,se),de=!!(!n&&(r!=null&&r.result)&&Te.length>1),Pe=!!(r&&r.tileType!=="text"&&(r.artifact||r.result||r.citation||r.repair)),Ye=!!(Y&&(Ze||d)),Xe=Z=>{if(!n){$(Z);return}const pe=aa(Z),ye=t.viz.options??{},Ne=Wt(t);u({viz:{...t.viz,type:pe,options:{...ye,chart:Z,...Ne?{dqlGenUi:{...Ne,defaultVisualization:pe}}:{}}},display:yn(t,pe,Ne)})},De=Z=>{if(o)return;const pe=L.current;if(!pe)return;Z.preventDefault(),Z.stopPropagation();const ye=pe.getBoundingClientRect(),Ne={x:Z.clientX-ye.left,y:Z.clientY-ye.top},We={x:Z.clientX,y:Z.clientY},Me=we=>{I({x:we.clientX-We.x,y:we.clientY-We.y}),f==null||f({clientX:we.clientX-Ne.x,clientY:we.clientY-Ne.y})},Ue=we=>{window.removeEventListener("pointermove",Me),window.removeEventListener("pointerup",Ue),I(null),y==null||y(),m({clientX:we.clientX-Ne.x,clientY:we.clientY-Ne.y})};window.addEventListener("pointermove",Me),window.addEventListener("pointerup",Ue,{once:!0})};return e.jsxs("div",{ref:L,onMouseEnter:()=>it(!0),onMouseLeave:()=>it(!1),onClick:()=>{Q&&(x==null||x(Q))},style:{gridColumn:o?"1 / -1":`${t.x+1} / span ${t.w}`,gridRow:o?"auto":`${t.y+1} / span ${t.h}`,transform:X?`translate(${X.x}px, ${X.y}px) scale(1.02)`:void 0,opacity:X?.92:1,zIndex:X?30:void 0,position:"relative",background:Ie?Vd(oe):"var(--dql-app-surface, var(--surface, rgba(0,0,0,0.02)))",border:d||X?"1.5px solid var(--dql-app-accent, var(--accent, #4f46e5))":Ie?"1px solid var(--dql-app-line-2, var(--border-color, rgba(15,23,42,0.10)))":"1px solid var(--dql-app-line, var(--border-color, rgba(0,0,0,0.08)))",borderRadius:8,padding:xe?12:14,paddingBottom:Ye?xe?42:46:xe?12:14,display:"flex",flexDirection:"column",gap:xe?4:Ie?10:6,minHeight:o?Zl(t,se):0,overflow:"visible",boxShadow:X?"0 16px 40px rgba(0,0,0,0.22)":d?"0 0 0 3px var(--dql-app-accent-soft, rgba(79,70,229,0.12))":void 0,cursor:X?"grabbing":Q?"pointer":void 0,transition:X?void 0:"box-shadow 120ms ease, transform 120ms ease"},children:[Ye?e.jsxs("button",{type:"button",style:Id,onClick:Z=>{Z.stopPropagation(),Q&&(x==null||x(Q)),Q&&(b==null||b(Q,Nd(t.title??Q)))},title:"Open app Copilot for this tile",children:[e.jsx(ht,{size:11,strokeWidth:2})," Ask AI"]}):null,n&&!o?e.jsx("div",{style:{position:"absolute",top:10,left:10,zIndex:3,opacity:R?1:0,pointerEvents:R?"auto":"none",transition:"opacity 120ms ease"},children:e.jsx("button",{type:"button",title:"Drag to move tile",onPointerDown:De,style:Sp,children:e.jsx(ys,{size:14,strokeWidth:2.2})})}):null,n?e.jsxs("div",{style:{position:"absolute",top:10,right:10,zIndex:4,display:"flex",alignItems:"center",gap:4,opacity:R?1:0,pointerEvents:R?"auto":"none",transition:"opacity 120ms ease"},children:[xe?null:e.jsx("span",{style:{fontSize:10,padding:"2px 8px",borderRadius:999,background:"var(--surface-hover, rgba(0,0,0,0.06))",opacity:.85},children:t.viz.type}),e.jsx($d,{item:t,cols:l,settingsOpen:O,onToggleSettings:le,onPatch:u})]}):null,Ie?e.jsx("div",{style:{minHeight:xe?26:42,paddingLeft:R?30:0,paddingRight:R?xe?82:134:0,transition:"padding 120ms ease",display:"grid",gap:7},children:e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,minWidth:0},children:[e.jsxs("div",{style:{flex:1,minWidth:0},children:[n?e.jsx("div",{style:{fontSize:xe?12:13,fontWeight:780,lineHeight:1.25,minWidth:0},children:e.jsx(Si,{value:Be??"",compact:xe,onCommit:Z=>ve(Z)})}):e.jsx("div",{title:Be,style:{fontSize:xe?12:13,fontWeight:780,lineHeight:1.25,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical"},children:Be}),e.jsxs("div",{style:up,children:[_e?e.jsx(Lr,{trust:_e}):null,Ae?e.jsxs("span",{style:qt,title:Ae.message,children:[e.jsx(wa,{size:9})," ",Ae.status==="repaired"?`${Ae.mode==="ai"?"AI ":""}repaired · review`:"repair blocked"]}):null,se?e.jsx("span",{style:qt,children:An(se)}):null,se!=null&&se.layoutIntent?e.jsx("span",{style:qt,children:St(String(se.layoutIntent))}):null]})]}),de?e.jsx(zi,{value:ee,options:Te,onChange:Xe}):null]})}):e.jsxs("div",{style:{minHeight:xe?22:26,paddingLeft:R?30:0,paddingRight:R?xe?82:134:0,transition:"padding 120ms ease"},children:[e.jsxs("div",{style:{fontSize:xe?12:13,fontWeight:720,lineHeight:1.25,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[n?e.jsx(Si,{value:t.title??S??"",compact:xe,onCommit:Z=>ve(Z)}):e.jsx("span",{children:t.title??S}),de?e.jsx("span",{style:{float:"right",marginLeft:8},children:e.jsx(zi,{value:ee,options:Te,onChange:Xe})}):null]}),ge?e.jsx("div",{style:{marginTop:5},children:e.jsxs("span",{style:qt,title:ge.detail,children:[e.jsx(Zt,{size:9})," ",ge.label]})}):null,ue||Ae?e.jsxs("div",{style:{marginTop:5,display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[ue?e.jsx(Lr,{trust:ue}):null,ue?e.jsx("span",{style:qt,children:"AI generated"}):null,Ae?e.jsxs("span",{style:qt,title:Ae.message,children:[e.jsx(wa,{size:9})," ",Ae.status==="repaired"?`${Ae.mode==="ai"?"AI ":""}repaired · review`:"repair blocked"]}):null]}):xe?null:e.jsx("div",{style:{marginTop:5,fontSize:10.5,opacity:.58,fontFamily:"var(--font-mono, monospace)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S})]}),n&&O?e.jsx(Ed,{item:t,tile:r,cols:l,onPatch:u,onClose:()=>F(!1)}):null,e.jsx("div",{style:{flex:1,minHeight:0,overflow:"hidden",display:"flex",alignItems:"stretch",justifyContent:"stretch",marginTop:xe?0:2,fontSize:12,opacity:(r==null?void 0:r.status)==="ok"?1:.7,fontStyle:(r==null?void 0:r.status)==="ok"?"normal":"italic"},children:e.jsx(Rd,{item:W,tile:r,loading:a,error:i,themeMode:s,genUi:se,editable:n,onEditText:Z=>u({text:{...t.text??{},markdown:Z}}),onRetry:w,retrying:q,retryDisabled:C})}),n?null:e.jsx(vd,{tile:r,themeMode:s}),!n&&Pe?e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:6,paddingTop:2},children:e.jsx("button",{type:"button",onClick:Z=>{Z.stopPropagation(),_(pe=>!pe)},style:In,children:U?"Hide details":"How it works"})}):null,!n&&U&&r?e.jsx(Pd,{item:t,tile:r,tab:A,onTab:te,onOpenNotebook:k,onClose:()=>_(!1)}):null]})}function vd({tile:t,themeMode:r}){const a=Ht[r],i=p.useMemo(()=>yd(t),[t]);return i?e.jsxs("div",{style:{padding:"4px 10px 8px",fontSize:11.5,color:a.textMuted,lineHeight:1.4,display:"flex",gap:5,alignItems:"baseline"},children:[e.jsx("span",{style:{color:a.accent},children:"•"}),e.jsx("span",{children:i})]}):null}function yd(t){var u,w;const r=(u=t==null?void 0:t.result)==null?void 0:u.rows,a=(w=t==null?void 0:t.result)==null?void 0:w.columns;if(!Array.isArray(r)||r.length===0||!Array.isArray(a)||a.length===0)return null;const i=r[0],s=q=>{if(typeof q=="number"&&Number.isFinite(q))return q;if(typeof q=="string"){const C=Number(q.replace(/[$,%\s]/g,""));return Number.isFinite(C)&&q.trim()?C:void 0}},n=a.find(q=>s(i==null?void 0:i[q])!==void 0),o=a.find(q=>q!==n&&typeof(i==null?void 0:i[q])=="string");if(!n)return null;const l=r.map(q=>q[n]),d=o?r.map(q=>q[o]):[],x=St(n);if(r.length===1){const q=s(r[0][n]);return q!==void 0?`${x}: ${It(n,q,l,{compact:!0})}.`:null}const b=r.map(q=>({label:o?It(o,q[o],d):"top",value:s(q[n])??0})).sort((q,C)=>C.value-q.value),m=b.reduce((q,C)=>q+C.value,0),f=b[0];if(!f)return null;const y=It(n,f.value,l,{compact:!0});return m>0?`${f.label} leads ${x} at ${y} (${Math.round(f.value/m*100)}%).`:`${f.label} leads ${x} at ${y}.`}function wd({markdown:t,variant:r,themeMode:a,onCommit:i}){const[s,n]=p.useState(!1),[o,l]=p.useState(t);return p.useEffect(()=>{l(t)},[t]),s?e.jsx("textarea",{autoFocus:!0,"aria-label":r==="heading"?"Heading text":"Tile text",value:o,onChange:d=>l(d.target.value),onPointerDown:d=>d.stopPropagation(),onBlur:()=>{n(!1),o!==t&&i(o)},onKeyDown:d=>{d.stopPropagation(),d.key==="Escape"&&(l(t),n(!1))},style:{width:"100%",minHeight:72,resize:"vertical",boxSizing:"border-box",font:r==="heading"?"700 17px/1.3 inherit":"inherit",color:"inherit",background:"var(--bg-1, #fff)",border:"1px solid var(--accent, #4f46e5)",borderRadius:7,padding:"7px 9px",outline:"none"}}):e.jsx("div",{role:"button",tabIndex:0,title:"Click to edit this text",onClick:()=>n(!0),onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),n(!0))},style:{cursor:"text",minHeight:24,borderRadius:6,outline:"none"},children:t.trim()?e.jsx(Cn,{markdown:t,variant:r,themeMode:a}):e.jsx("span",{style:{opacity:.55,fontSize:12},children:"Click to write this section…"})})}function Si({value:t,compact:r,onCommit:a}){const[i,s]=p.useState(t),[n,o]=p.useState(!1);return p.useEffect(()=>{s(t)},[t]),e.jsx("input",{"aria-label":"Tile name",title:"Tile name — press Enter to save",value:i,maxLength:140,onChange:l=>s(l.target.value),onFocus:()=>o(!0),onBlur:()=>{o(!1);const l=i.trim();l&&l!==t?a(l):s(t)},onKeyDown:l=>{l.stopPropagation(),l.key==="Enter"&&l.currentTarget.blur(),l.key==="Escape"&&(s(t),l.currentTarget.blur())},onPointerDown:l=>l.stopPropagation(),style:{font:"inherit",color:"inherit",background:n?"var(--bg-1, #fff)":"transparent",border:`1px solid ${n?"var(--accent, #4f46e5)":"transparent"}`,borderRadius:6,padding:r?"0 4px":"1px 5px",margin:r?"0 0 0 -4px":"0 0 0 -5px",maxWidth:"100%",width:`${Math.max(6,Math.min(48,i.length+1))}ch`,outline:"none",cursor:n?"text":"pointer"},onMouseEnter:l=>{n||(l.currentTarget.style.borderColor="var(--border-subtle, #d8d8d8)")},onMouseLeave:l=>{n||(l.currentTarget.style.borderColor="transparent")}})}function zi({value:t,options:r,onChange:a}){const s=r.slice(0,4);if(!s.some(o=>o.value===t)){const o=r.find(l=>l.value===t);o&&s.splice(3,1,o)}const n=r.filter(o=>!s.some(l=>l.value===o.value));return e.jsxs("div",{style:gp,"aria-label":"Visualization",children:[s.map(o=>e.jsx("button",{type:"button",title:o.label,"aria-label":o.label,"aria-pressed":t===o.value,onClick:l=>{l.stopPropagation(),a(o.value)},style:fp(t===o.value),children:Gd(o.value)},o.value)),n.length>0?e.jsxs("select",{"aria-label":"More visualizations",title:"More visualizations",value:"",onClick:o=>o.stopPropagation(),onChange:o=>{o.target.value&&a(o.target.value)},style:qd,children:[e.jsx("option",{value:"",children:"More…"}),n.map(o=>e.jsx("option",{value:o.value,children:o.label},o.value))]}):null]})}const qd={border:"none",background:"transparent",color:"inherit",font:"inherit",fontSize:10.5,cursor:"pointer",maxWidth:74};function Lr({trust:t}){const r=t==="certified",a=r?"Certified":t==="review_required"?"Review required":"Draft ready";return e.jsxs("span",{style:xp(r),children:[r?e.jsx(Qe,{size:10,strokeWidth:2.4}):e.jsx(Er,{size:10,strokeWidth:2.4}),a]})}function jd({story:t}){return e.jsxs("section",{style:Nn,"aria-label":"Current dashboard story",children:[e.jsxs("div",{style:Rn,children:[e.jsx("div",{style:Tn,children:e.jsx(ht,{size:15,strokeWidth:2.2})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:Pn,children:"Story from current results"}),e.jsx("h3",{style:$n,children:t.title})]}),t.trust?e.jsx(Lr,{trust:t.trust}):null]}),e.jsx("p",{style:_n,children:t.summary}),e.jsxs("div",{style:Ja,children:[e.jsx("span",{style:En,children:t.sourceTitle}),t.filters.map(r=>e.jsxs("span",{style:qr,children:[r.label,": ",r.value]},`${r.label}:${r.value}`)),t.chips.map(r=>e.jsx("span",{style:qr,children:r},r))]})]})}function kd({story:t,onEvidence:r,onResearch:a}){return e.jsxs("section",{style:{...Nn,padding:"20px 22px",marginBottom:16},"aria-label":"Business Story",children:[e.jsxs("div",{style:Rn,children:[e.jsx("div",{style:Tn,children:e.jsx(ht,{size:15,strokeWidth:2.2})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:Pn,children:"Business Story · current filters"}),e.jsx("h2",{style:{...$n,fontSize:19},children:t.headline})]}),e.jsx(Lr,{trust:t.trustState})]}),e.jsxs("div",{style:{display:"grid",gap:10,marginTop:12,maxWidth:920},children:[t.paragraphs.slice(0,2).map((i,s)=>e.jsx("p",{style:{..._n,margin:0,fontSize:14,lineHeight:1.65},children:Ci(i)},s)),t.implication?e.jsxs("p",{style:{margin:0,fontSize:13,lineHeight:1.55,fontWeight:650},children:["What this means: ",Ci(t.implication)]}):null]}),e.jsxs("div",{style:{...Ja,marginTop:14},children:[e.jsx("span",{style:En,children:t.generatedBy==="ai"?"AI wording · verified facts":"Verified result summary"}),e.jsxs("span",{style:qr,children:[t.evidenceRefs.length," evidence source",t.evidenceRefs.length===1?"":"s"]}),t.caveat?e.jsx("span",{style:qr,children:t.caveat}):null,e.jsx("span",{style:{flex:1}}),e.jsx("button",{type:"button",onClick:r,style:Ti,children:"View evidence"}),e.jsx("button",{type:"button",onClick:a,style:Ti,children:"Research deeper"})]})]})}function Sd({run:t,variables:r}){const a=t.tiles.filter(s=>s.status!=="ok"),i=Object.entries(r).filter(([,s])=>s!=null&&s!=="");return e.jsxs("details",{style:zd,"aria-label":"Evidence and review appendix",children:[e.jsxs("summary",{style:Cd,children:["Evidence & review appendix",e.jsxs("span",{style:{opacity:.62,fontWeight:600},children:[t.story.evidenceRefs.length," sources · ",a.length?`${a.length} issue${a.length===1?"":"s"}`:"all visible sources ran"]})]}),e.jsxs("div",{style:{display:"grid",gap:12,padding:"0 16px 16px"},children:[e.jsxs("div",{style:Ad,children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Run"}),e.jsx("br",{}),e.jsx("span",{children:t.runId})]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Snapshot"}),e.jsx("br",{}),e.jsx("span",{children:t.snapshotId})]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Trust"}),e.jsx("br",{}),e.jsx("span",{children:t.story.trustState})]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Filters"}),e.jsx("br",{}),e.jsx("span",{children:i.length?i.map(([s,n])=>`${s}: ${String(n)}`).join(" · "):"Current unfiltered scope"})]})]}),e.jsxs("div",{children:[e.jsx("strong",{style:{fontSize:12},children:"Evidence used by the story"}),e.jsx("div",{style:{...Ja,marginTop:7},children:t.story.evidenceRefs.map(s=>e.jsx("span",{style:qr,children:s},s))})]}),a.length?e.jsxs("div",{children:[e.jsx("strong",{style:{fontSize:12},children:"Items requiring review"}),e.jsx("ul",{style:{margin:"7px 0 0",paddingLeft:18,fontSize:12,lineHeight:1.55},children:a.map(s=>e.jsxs("li",{children:[s.title??s.tileId,": ",s.error??s.status]},s.tileId))})]}):null]})]})}function Ci(t){return t.split(/(\*\*[^*]+\*\*)/g).filter(Boolean).map((r,a)=>r.startsWith("**")&&r.endsWith("**")?e.jsx("strong",{children:r.slice(2,-2)},a):r)}const zd={marginTop:16,border:"1px solid var(--dql-app-line, var(--border-color, rgba(15,23,42,0.10)))",borderRadius:8,background:"var(--dql-app-surface, var(--surface, rgba(0,0,0,0.02)))",color:"var(--dql-app-text, var(--text-primary, #0f172a))"},Cd={cursor:"pointer",padding:"12px 16px",fontSize:12.5,fontWeight:760,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},Ad={display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:10,fontSize:11.5,lineHeight:1.45,color:"var(--dql-app-text-muted, var(--text-secondary, #64748b))"},Id={position:"absolute",bottom:10,right:10,zIndex:5,display:"inline-flex",alignItems:"center",gap:4,padding:"3px 8px",borderRadius:999,fontSize:10.5,fontWeight:700,color:"var(--dql-app-accent, var(--accent, #4f46e5))",background:"var(--dql-app-accent-soft, rgba(79,70,229,0.12))",border:"1px solid var(--dql-app-accent, rgba(79,70,229,0.4))",cursor:"pointer",lineHeight:1.2,fontFamily:"inherit"};function Nd(t){return`/ask Explain ${t} for a stakeholder. Start with the business meaning, current result, active filters, caveats, and recommended next action.`}function Rd({item:t,tile:r,loading:a,error:i,themeMode:s,genUi:n,editable:o=!1,onEditText:l,onRetry:d,retrying:x,retryDisabled:b}){var u,w,q,C,k,M;if(a&&!r)return e.jsx("span",{children:"Loading data..."});if((r==null?void 0:r.tileType)==="text"){if(n)return e.jsx(Bd,{title:t.title??n.insightTitle??"Generated section",markdown:((u=r.text)==null?void 0:u.markdown)??"",genUi:n,themeMode:s});const L=((w=r.text)==null?void 0:w.markdown)??"";return o&&l?e.jsx(wd,{markdown:L,variant:((q=r.viz)==null?void 0:q.type)==="heading"?"heading":"text",themeMode:s,onCommit:l}):e.jsx(Cn,{markdown:L,variant:((C=r.viz)==null?void 0:C.type)==="heading"?"heading":"text",themeMode:s})}if(i&&!r)return e.jsx("span",{children:i});if(!r)return e.jsx("span",{children:"No run result."});if(r.status==="unauthorized")return e.jsx("span",{children:"Not authorized."});if(r.status==="unresolved")return e.jsx("span",{children:r.error??"Block reference unresolved."});if(r.status==="error")return e.jsxs("div",{style:{display:"grid",gap:8,justifyItems:"center",textAlign:"center",padding:8},children:[e.jsx("span",{children:r.error??"Tile failed."}),((k=r.repair)==null?void 0:k.status)==="failed"?e.jsx("small",{children:r.repair.message}):null,d?e.jsxs("button",{type:"button",disabled:x||b,onClick:L=>{L.stopPropagation(),d()},style:Zd,children:[e.jsx(wa,{size:12})," ",x?"Fixing…":"Fix and retry"]}):null]});if(!r.result)return r.tileType==="aiPin"&&r.aiPin?e.jsx(Ni,{pin:r.aiPin,themeMode:s}):e.jsx("span",{children:"No result."});const m=Va(t,r.chartConfig),f=String(m.chart??((M=r.viz)==null?void 0:M.type)??"").toLowerCase();let y;if(f==="table"||t.viz.type==="table"||t.viz.type==="pivot")r.tileType!=="aiPin"&&((n==null?void 0:n.component)==="EvidenceTable"||(n==null?void 0:n.component)==="PivotTable")?y=e.jsx(Md,{result:r.result,genUi:n,themeMode:s}):y=e.jsx("div",{style:{width:"100%",alignSelf:"stretch"},children:e.jsx(Xi,{result:r.result,themeMode:s,initialPageSize:10})});else{const L=f==="kpi"?Kl(r.result,m.y):r.result;y=e.jsx(Td,{children:X=>e.jsx(Ji,{result:L,themeMode:s,chartConfig:{...m,title:void 0},availableHeight:X})})}return r.tileType==="aiPin"&&r.aiPin?e.jsx(Ni,{pin:r.aiPin,themeMode:s,dataView:y}):y}function Td({children:t}){const r=p.useRef(null),[a,i]=p.useState();return p.useEffect(()=>{const s=r.current;if(!s)return;const n=()=>{const l=Math.floor(s.getBoundingClientRect().height);i(l>0?l:void 0)};n();const o=new ResizeObserver(n);return o.observe(s),()=>o.disconnect()},[]),e.jsx("div",{ref:r,"data-testid":"dashboard-chart-frame",style:{width:"100%",height:"100%",minWidth:0,minHeight:0,alignSelf:"stretch",overflow:"auto",scrollbarWidth:"thin"},children:t(a)})}function Pd({item:t,tile:r,tab:a,onTab:i,onOpenNotebook:s,onClose:n}){var x,b,m;const o=r.artifact,l=!!(r.result&&(o!=null&&o.dql||o!=null&&o.sql)),d=(o==null?void 0:o.sourceKind)==="certified_block"?"Certified block":(o==null?void 0:o.sourceKind)==="semantic_query"?"Governed semantic query":(o==null?void 0:o.sourceKind)==="draft_analysis"?"App analysis":(o==null?void 0:o.sourceKind)==="ai_pin"?"Saved AI insight":r.tileType??"App tile";return e.jsx("div",{style:Dd,role:"presentation",onClick:n,children:e.jsxs("section",{role:"dialog","aria-modal":"true","aria-label":`How ${t.title??r.title??t.i} works`,style:Ud,onClick:f=>f.stopPropagation(),children:[e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12},children:[e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:16,fontWeight:800},children:t.title??r.title??(o==null?void 0:o.name)??"App tile"}),e.jsxs("div",{style:{marginTop:4,fontSize:12,color:"var(--text-secondary)"},children:[d," · ",(o==null?void 0:o.trustState)==="certified"&&!r.repair?"Certified":"Review required"]})]}),e.jsx("button",{type:"button",onClick:n,"aria-label":"Close details",style:ea,children:e.jsx($t,{size:14})})]}),e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap",borderBottom:"1px solid var(--border-subtle)",paddingBottom:10},children:["how","dql","sql"].map(f=>e.jsx("button",{type:"button",onClick:()=>i(f),style:ep(a===f),children:f==="how"?"How it works":f.toUpperCase()},f))}),e.jsx("div",{style:{minHeight:180,maxHeight:"56vh",overflow:"auto"},children:a==="how"?e.jsxs("div",{style:{display:"grid",gap:12,fontSize:12.5,lineHeight:1.5},children:[e.jsx(Ir,{label:"Source",value:(o==null?void 0:o.sourcePath)??((x=r.citation)==null?void 0:x.path)??((b=r.citation)==null?void 0:b.name)??d}),e.jsx(Ir,{label:"Result",value:r.result?`${r.result.rowCount} rows · ${r.result.columns.length} columns`:r.status}),(m=o==null?void 0:o.explanation)!=null&&m.length?e.jsxs("div",{children:[e.jsx("b",{children:"Execution"}),e.jsx("ul",{style:{margin:"6px 0 0",paddingLeft:18},children:o.explanation.map(f=>e.jsx("li",{children:f},f))})]}):null,r.filters?e.jsx(Ir,{label:"Filters",value:`${r.filters.applied.map(f=>f.filter).join(", ")||"None applied"}${r.filters.skipped.length?` · ${r.filters.skipped.length} skipped`:""}`}):null,r.invocation?e.jsx(Ir,{label:"Parameters",value:r.invocation.resolvedParameters.map(f=>`${f.name} (${f.source})`).join(", ")||"None"}):null,r.repair?e.jsx(Ir,{label:"Repair",value:r.repair.message}):null,e.jsx("div",{style:{padding:10,borderRadius:8,background:"var(--bg-2)",color:"var(--text-secondary)"},children:"Parameter values are intentionally omitted here. Open the editable Notebook cell to inspect or change the full execution contract."})]}):e.jsx("pre",{style:tp,children:a==="dql"?(o==null?void 0:o.dql)??"This tile does not expose DQL source. Its governed semantic intent is composed into SQL at runtime.":(o==null?void 0:o.sql)??"Executed SQL is not available for this saved result."})}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,borderTop:"1px solid var(--border-subtle)",paddingTop:10},children:[e.jsx("button",{type:"button",onClick:n,style:Ot(!1),children:"Close"}),l?e.jsx("button",{type:"button",onClick:()=>s==null?void 0:s(r),style:Ot(!0),children:"Open in Notebook"}):null]})]})})}function Ir({label:t,value:r}){return e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"110px minmax(0, 1fr)",gap:12},children:[e.jsx("b",{children:t}),e.jsx("span",{style:{minWidth:0,overflowWrap:"anywhere",color:"var(--text-secondary)"},children:r})]})}function $d({item:t,cols:r,settingsOpen:a,onToggleSettings:i,onPatch:s}){const[n,o]=p.useState(!1),l=d=>{o(!1),s(jn(t,r,d))};return e.jsxs("div",{style:{display:"flex",gap:4,alignItems:"center",flexWrap:"wrap",justifyContent:"flex-end"},children:[e.jsxs("div",{style:{position:"relative"},children:[e.jsx("button",{type:"button",title:"Choose tile size",onClick:()=>o(d=>!d),style:ea,children:e.jsx(xs,{size:13,strokeWidth:2})}),n?e.jsx(_d,{onPick:l,onClose:()=>o(!1)}):null]}),e.jsx("button",{type:"button",title:"Tile settings","aria-label":"Tile settings",onClick:i,style:ea,children:e.jsx(rn,{size:13,strokeWidth:2,color:a?"var(--accent, #4f46e5)":void 0})}),e.jsx("button",{type:"button",title:"Remove tile",onClick:()=>s(null),style:ea,children:e.jsx(ir,{size:13,strokeWidth:2})})]})}function _d({onPick:t,onClose:r}){return e.jsx("div",{style:zp,onMouseLeave:r,children:qn.map(a=>e.jsxs("button",{type:"button",onClick:()=>t(a.id),style:Cp,children:[e.jsx("span",{style:{fontSize:12,fontWeight:750},children:a.label}),e.jsx("span",{style:{fontSize:11,opacity:.66},children:a.description})]},a.id))})}function Ed({item:t,tile:r,cols:a,onPatch:i,onClose:s}){var U;const n=r==null?void 0:r.result,o=Va(t,r==null?void 0:r.chartConfig),l=lr(o.chart),d=Wt(t),[x,b]=p.useState(!1),[m,f]=p.useState(null),[y,u]=p.useState(null),w=p.useMemo(()=>bs(n),[n]),q=p.useMemo(()=>{const _=new Map;if(!n)return _;const A=new Set(w.metrics),te=new Set(w.dimensions);for(const Q of n.columns)A.has(Q)?_.set(Q,"measure"):te.has(Q)?_.set(Q,"dimension"):_.set(Q,gs(fs(Q,n.rows)));return _},[n,w]),C=(n==null?void 0:n.columns.filter(_=>q.get(_)==="measure"))??[],k=(n==null?void 0:n.columns.filter(_=>q.get(_)!=="measure"))??[],M=t.title??o.title??"",[L,X]=p.useState(M);p.useEffect(()=>{X(M)},[M]);const I=()=>{const _=L.trim();_!==M&&O({title:_||void 0})},O=_=>{const A=gi({...o,..._}),te=aa(A.chart),Q=Wt(t),Y={...A};Q&&(Y.dqlGenUi={...Q,defaultVisualization:te,...A.title?{insightTitle:A.title}:{}}),i({title:A.title||t.title,viz:{...t.viz,type:te,options:Y},display:yn(t,te,Q)})},F=async()=>{b(!0),u(null),f(null);const _=Bt(t)??t.title,A=await D.recommendVisualization({..._?{blockRef:_}:{},resultSchema:n?{columns:n.columns}:void 0,rowSample:n==null?void 0:n.rows.slice(0,5),prompt:[t.title,d==null?void 0:d.rationale].filter(Boolean).join(" "),allowedVisualizations:d==null?void 0:d.allowedVisualizations});if(b(!1),!A.ok){u(A.error);return}const te=lr(A.display.defaultVisualization),Q=aa(te),Y=A.display.fieldHints??{},S=gi({...o,chart:te,title:o.title??t.title,x:Y.x??Y.label??o.x,y:Y.y??Y.value??o.y,color:Y.color??o.color});i({title:S.title||t.title,viz:{...t.viz,type:Q,options:{...S}},display:A.display});const h=A.evidence.map(ee=>ee.source).slice(0,3).join(", "),$=A.warnings[0];f($?`${A.display.component}: ${$}`:`${A.display.component}${h?` from ${h}`:""}`)};return e.jsxs("aside",{role:"dialog","aria-label":`Tile settings for ${t.title??t.i}`,style:np,onClick:_=>_.stopPropagation(),children:[e.jsxs("header",{style:sp,children:[e.jsxs("div",{style:{minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,fontSize:13,fontWeight:820},children:[e.jsx(rn,{size:14})," Tile settings"]}),e.jsx("div",{style:{marginTop:2,color:"var(--text-tertiary)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.title??t.i})]}),e.jsx("button",{type:"button","aria-label":"Close tile settings",title:"Close",onClick:s,style:op,children:e.jsx($t,{size:15})})]}),e.jsxs("section",{style:$i,children:[e.jsx("div",{style:_i,children:"Layout"}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:qn.map(_=>e.jsx("button",{type:"button",title:_.description,onClick:()=>i(jn(t,a,_.id)),style:Ap(Dl(t,a,_.id)),children:_.label},_.id))})]}),e.jsxs("section",{style:$i,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[e.jsx("div",{style:_i,children:"Visualization"}),e.jsxs("button",{type:"button",onClick:()=>void F(),disabled:x,style:dp(x),title:"Recommend a visualization from governed result fields",children:[e.jsx(tn,{size:12,strokeWidth:2.2}),x?"Thinking…":"Recommend"]})]}),e.jsxs("div",{style:Ei,children:[e.jsxs("label",{style:{...Na,gridColumn:"1 / -1"},children:["Title",e.jsx("input",{"aria-label":"Tile name",value:L,onChange:_=>X(_.target.value),onBlur:()=>I(),onKeyDown:_=>{_.key==="Enter"&&_.currentTarget.blur(),_.key==="Escape"&&(X(M),_.currentTarget.blur())},style:Ra})]}),e.jsxs("label",{style:{...Na,gridColumn:"1 / -1"},children:["Chart type",e.jsx("select",{value:l,onChange:_=>O({chart:_.target.value}),style:Ra,children:zn.map(_=>e.jsx("option",{value:_.value,children:_.label},_.value))})]})]}),m?e.jsx("div",{style:Mn,children:m}):null,y?e.jsx("div",{style:pp,children:y}):null]}),e.jsxs("details",{style:Bi,children:[e.jsx("summary",{style:Mi,children:"Data fields and advanced options"}),e.jsxs("div",{style:{display:"grid",gap:10,marginTop:10},children:[e.jsxs("div",{style:Ei,children:[e.jsx(Zr,{label:"Category / X",value:o.x,columns:(n==null?void 0:n.columns)??[],onChange:_=>O({x:_})}),e.jsx(Zr,{label:"Value / Y",value:o.y,columns:(n==null?void 0:n.columns)??[],onChange:_=>O({y:_})}),e.jsx(Zr,{label:"Color",value:o.color,columns:(n==null?void 0:n.columns)??[],onChange:_=>O({color:_})}),e.jsx(Zr,{label:"Facet",value:o.facet,columns:(n==null?void 0:n.columns)??[],onChange:_=>O({facet:_})})]}),n?e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[e.jsx(Ai,{title:"Measures",columns:C,onPick:_=>O({y:_})}),e.jsx(Ai,{title:"Dimensions",columns:k,onPick:_=>O({x:_})})]}):e.jsx("div",{style:{fontSize:11,opacity:.64},children:"Run the tile once to map result fields."})]})]}),e.jsxs("details",{style:Bi,children:[e.jsx("summary",{style:Mi,children:"Why this visualization"}),e.jsxs("div",{style:lp,children:[e.jsx("div",{style:{fontSize:11.5,lineHeight:1.5,color:"var(--text-secondary)"},children:(d==null?void 0:d.rationale)??((U=t.display)==null?void 0:U.rationale)??"This visualization is constrained by the governed result fields and the saved App display contract."}),e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:[d!=null&&d.component?e.jsx("span",{style:qt,children:An(d)}):null,d!=null&&d.defaultVisualization?e.jsx("span",{style:qt,children:St(String(d.defaultVisualization))}):null,d!=null&&d.reviewStatus?e.jsx("span",{style:qt,children:St(String(d.reviewStatus))}):null]})]})]})]})}function Zr({label:t,value:r,columns:a,onChange:i}){return e.jsxs("label",{style:Na,children:[t,e.jsxs("select",{value:r??"",onChange:s=>i(s.target.value||void 0),style:Ra,children:[e.jsx("option",{value:"",children:"Auto"}),a.map(s=>e.jsx("option",{value:s,children:s},s))]})]})}function Ai({title:t,columns:r,onPick:a}){return e.jsxs("div",{style:{display:"grid",gap:4,minWidth:0},children:[e.jsx("div",{style:{fontSize:10,fontWeight:800,textTransform:"uppercase",opacity:.58},children:t}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:r.length===0?e.jsx("span",{style:{fontSize:11,opacity:.55},children:"None"}):r.slice(0,10).map(i=>e.jsx("button",{type:"button",onClick:()=>a(i),style:cp,children:i},i))})]})}function Ii({open:t,onToggle:r,onCertifiedBlock:a,onText:i,onHeading:s,onAi:n,buttonLabel:o,buttonStyle:l}){return e.jsxs("div",{style:{position:"relative",display:"inline-flex"},children:[e.jsxs("button",{type:"button",onClick:r,title:"Add tile",style:l??Ot(t),children:[e.jsx(xt,{size:15,strokeWidth:2.2}),o?e.jsx("span",{children:o}):null]}),t&&e.jsxs("div",{style:{position:"absolute",top:"calc(100% + 6px)",right:0,zIndex:30,width:260,border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:8,background:"var(--color-bg, #fff)",boxShadow:"0 14px 38px rgba(0,0,0,0.16)",padding:6,display:"grid",gap:4,textAlign:"left"},children:[e.jsx(Dr,{title:"Certified block",description:"Chart, table, or KPI from this App domain",onClick:a}),e.jsx(Dr,{title:"Text / summary",description:"Narrative, notes, caveats, or CXO context",onClick:i}),e.jsx(Dr,{title:"Section heading",description:"Separate an App page into readable groups",onClick:s}),e.jsx(Dr,{title:"Copilot insight",description:"Open scoped AI, then pin the reviewed answer to this App",onClick:n})]})]})}function Dr({title:t,description:r,onClick:a}){return e.jsxs("button",{type:"button",onClick:a,style:ip,children:[e.jsx("span",{style:{fontSize:12,fontWeight:700},children:t}),e.jsx("span",{style:{fontSize:11,opacity:.66},children:r})]})}function Bd({title:t,markdown:r,genUi:a,themeMode:i}){var d;const s=Ht[i],n=Yd(r,t),o=a.component==="TrustCallout",l=a.component==="ResearchActions";return e.jsxs("div",{style:mp(o),children:[e.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-start"},children:[e.jsx("span",{style:hp(o),children:o?e.jsx(Er,{size:15}):l?e.jsx(ht,{size:15}):e.jsx(Qe,{size:15})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:13,fontWeight:780,lineHeight:1.25},children:t??a.insightTitle}),e.jsx("div",{style:{marginTop:6,fontSize:13,lineHeight:1.45,color:s.textSecondary},children:n})]})]}),e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[a.trustState?e.jsx(Lr,{trust:a.trustState}):null,a.reviewStatus?e.jsx("span",{style:qt,children:St(a.reviewStatus)}):null]}),(d=a.followUpActions)!=null&&d.length?e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:a.followUpActions.slice(0,3).map(x=>e.jsx("span",{style:bp,children:St(x)},x))}):null]})}function Md({result:t,genUi:r,themeMode:a}){var f;const i=Ht[a],s=t.rows??[],n=t.columns??[],o=ad(n,s,(f=r.fieldHints)==null?void 0:f.label),l=n.find(y=>/\b(status|quality|trust|certification|review)\b/i.test(y)),d=n.filter(y=>y!==o&&y!==l).filter(y=>fa(y)<90||wr(y,s)).sort((y,u)=>fa(y)-fa(u)).slice(0,2),x=n.filter(y=>y!==o&&y!==l&&!d.includes(y)).slice(0,2),b=t.rowCount??s.length,m=kn(n,s);return e.jsxs("div",{style:vp,children:[e.jsxs("div",{style:{fontSize:11.5,color:i.textSecondary},children:[b," ",b===1?"row":"rows"," across ",n.length," ",n.length===1?"field":"fields"]}),e.jsx("div",{style:yp,children:s.slice(0,4).map((y,u)=>{const w=o?It(o,y[o],m.get(o)??[]):`Row ${u+1}`,q=l?It(l,y[l],m.get(l)??[]):null;return e.jsxs("div",{style:wp,children:[e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{style:{fontSize:12.5,fontWeight:760,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:w}),x.length?e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5,marginTop:4},children:x.map(C=>e.jsxs("span",{style:qp,children:[St(C),": ",It(C,y[C],m.get(C)??[])]},C))}):null]}),e.jsxs("div",{style:{display:"flex",gap:5,flexWrap:"wrap",justifyContent:"flex-start",minWidth:0},children:[d.map(C=>e.jsxs("span",{style:jp,children:[e.jsx("span",{style:{opacity:.62},children:St(C)}),e.jsx("strong",{children:It(C,y[C],m.get(C)??[])})]},C)),q?e.jsx("span",{style:kp,children:q}):null]})]},u)})}),s.length>4?e.jsx("div",{style:{fontSize:11,color:i.textSecondary},children:"Showing first 4 rows in generated view. Switch tile settings for full table controls."}):null]})}function Cn({markdown:t,variant:r="text",themeMode:a}){const i=Ht[a];return e.jsx("div",{style:{width:"100%",alignSelf:"stretch",overflow:"auto",whiteSpace:"normal",lineHeight:1.45,fontStyle:"normal",opacity:1,fontSize:r==="heading"?18:void 0,fontWeight:r==="heading"?800:void 0,display:r==="heading"?"flex":void 0,alignItems:r==="heading"?"center":void 0},children:en(t,i)})}function Ni({pin:t,themeMode:r,dataView:a}){var d,x;const[i,s]=p.useState(null),n=Ht[r]??Ht.light,o=async()=>{s("Refreshing...");const b=await D.refreshAiPin(t.appId,t.id);s(b.ok?"Refreshed.":b.error??"Refresh failed."),window.dispatchEvent(new CustomEvent("dql-app-dashboard-updated",{detail:{appId:t.appId,dashboardId:t.dashboardId}}))},l=async()=>{s("Creating draft...");const b=await D.promoteAiPin(t.appId,t.id);s(b.ok?`Draft created: ${b.blockPath}`:b.error??"Promotion failed."),window.dispatchEvent(new CustomEvent("dql-app-dashboard-updated",{detail:{appId:t.appId,dashboardId:t.dashboardId}}))};return e.jsxs("div",{style:{width:"100%",alignSelf:"stretch",overflow:"auto",fontStyle:"normal",lineHeight:1.5,display:"grid",gap:10},children:[a||e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center",flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:10.5,fontWeight:800,color:t.certification==="certified"?"#15803d":"#b45309",background:t.certification==="certified"?"rgba(22,163,74,0.1)":"rgba(245,158,11,0.12)",border:`1px solid ${t.certification==="certified"?"rgba(22,163,74,0.22)":"rgba(245,158,11,0.24)"}`,borderRadius:999,padding:"3px 7px"},children:t.certification==="certified"?"Certified":"Review required"}),e.jsx("span",{style:{fontSize:10.5,color:"var(--color-text-muted, rgba(0,0,0,0.58))"},children:"Pinned report insight"})]}),e.jsx("div",{style:{minWidth:0},children:en(t.answer,n)}),(x=(d=t.result)==null?void 0:d.rows)!=null&&x.length?e.jsx(Ld,{result:t.result}):null]}),e.jsxs("div",{style:{display:"flex",gap:6,marginTop:8,flexWrap:"wrap"},children:[t.sql&&e.jsx("button",{type:"button",onClick:()=>void o(),style:Li,children:"Refresh"}),t.sql&&t.reviewStatus==="needs_review"&&e.jsx("button",{type:"button",onClick:()=>void l(),style:Li,children:"Promote"}),t.refreshCadence==="daily"&&e.jsx("span",{style:{fontSize:11,opacity:.62},children:"daily"})]}),i&&e.jsx("div",{style:{marginTop:6,fontSize:11,opacity:.72},children:i}),t.lastRefreshError&&e.jsx("div",{style:{marginTop:8,color:"#f85149"},children:t.lastRefreshError})]})}function Ld({result:t}){var s,n;const r=((s=t.columns)!=null&&s.length?t.columns:Object.keys(((n=t.rows)==null?void 0:n[0])??{})).slice(0,4),a=(t.rows??[]).slice(0,3),i=kn(r,t.rows??[]);return!r.length||!a.length?null:e.jsxs("div",{style:{display:"grid",gap:6},children:[e.jsx("div",{style:{color:"var(--color-text-muted, rgba(0,0,0,0.58))",fontSize:11,fontWeight:750},children:"Supporting rows"}),e.jsx("div",{style:{overflow:"auto",border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6},children:e.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11},children:[e.jsx("thead",{children:e.jsx("tr",{children:r.map(o=>e.jsx("th",{style:{textAlign:"left",padding:"5px 7px",borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.08))",color:"var(--color-text-muted, rgba(0,0,0,0.58))"},children:St(o)},o))})}),e.jsx("tbody",{children:a.map((o,l)=>e.jsx("tr",{children:r.map(d=>e.jsx("td",{style:{padding:"5px 7px",borderBottom:l===a.length-1?"none":"1px solid var(--border-color, rgba(0,0,0,0.06))"},children:It(d,o[d],i.get(d)??[])},d))},l))})]})})]})}function Fd({kind:t,value:r,onChange:a,onClose:i,onSave:s}){const n=t==="heading";return e.jsx("div",{style:{position:"fixed",inset:0,zIndex:90,background:"rgba(0,0,0,0.36)",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:e.jsxs("div",{style:{width:"min(520px, 92vw)",display:"grid",gap:12,background:"var(--color-bg, #fff)",color:"inherit",borderRadius:8,boxShadow:"0 18px 60px rgba(0,0,0,0.35)",padding:16},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:16,fontWeight:800},children:n?"Add heading":"Add text tile"}),e.jsx("div",{style:{fontSize:12,opacity:.65,marginTop:4},children:n?"Create a section heading on this dashboard page.":"Create a narrative text tile on this dashboard page."})]}),n?e.jsx("input",{value:r,onChange:o=>a(o.target.value),onKeyDown:o=>{o.key==="Enter"&&s(),o.key==="Escape"&&i()},placeholder:"Executive summary",autoFocus:!0,style:Pi}):e.jsx("textarea",{value:r,onChange:o=>a(o.target.value),onKeyDown:o=>{o.key==="Escape"&&i(),o.key==="Enter"&&(o.metaKey||o.ctrlKey)&&s()},placeholder:"Add context, assumptions, or decisions...",rows:6,autoFocus:!0,style:{...Pi,resize:"vertical",lineHeight:1.45}}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e.jsx("button",{type:"button",onClick:i,style:Ot(!1),children:"Cancel"}),e.jsx("button",{type:"button",onClick:s,disabled:!r.trim(),style:{...Bn,opacity:r.trim()?1:.65},children:"Add"})]})]})})}function Od({blocks:t,search:r,onSearch:a,onClose:i,onAdd:s}){const n=t.filter(o=>{const l=r.trim().toLowerCase();return l?[o.name,o.description,o.domain,...o.tags??[]].join(" ").toLowerCase().includes(l):!0});return e.jsx("div",{style:{position:"fixed",inset:0,zIndex:90,background:"rgba(0,0,0,0.36)",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:e.jsxs("div",{style:{width:"min(860px, 94vw)",maxHeight:"86vh",display:"flex",flexDirection:"column",background:"var(--color-bg, #fff)",color:"inherit",borderRadius:8,overflow:"hidden",boxShadow:"0 18px 60px rgba(0,0,0,0.35)"},children:[e.jsxs("div",{style:{padding:14,borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.1))",display:"flex",gap:10,alignItems:"center"},children:[e.jsx("div",{style:{fontSize:15,fontWeight:700,flex:1},children:"Add Certified Block"}),e.jsx("button",{type:"button",onClick:i,style:Ot(!1),children:"Close"})]}),e.jsx("div",{style:{padding:14,borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.08))"},children:e.jsx("input",{value:r,onChange:o=>a(o.target.value),placeholder:"Search domain blocks...",style:{width:"100%",boxSizing:"border-box",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,padding:"8px 10px",background:"var(--surface, transparent)",color:"inherit"}})}),e.jsx("div",{style:{overflow:"auto",padding:12,display:"grid",gap:8},children:n.length===0?e.jsx("div",{style:{padding:18,fontSize:12,opacity:.66},children:"No certified blocks match this App scope."}):n.map(o=>e.jsxs("button",{type:"button",onClick:()=>s(o),style:{textAlign:"left",border:"1px solid var(--border-color, rgba(0,0,0,0.1))",borderRadius:7,background:"transparent",color:"inherit",padding:10,cursor:"pointer"},children:[e.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:4},children:[e.jsx("span",{style:{fontSize:13,fontWeight:700},children:o.name}),e.jsx("span",{style:{fontSize:10,padding:"2px 6px",borderRadius:999,background:"rgba(63,185,80,0.14)",color:"#2ea043"},children:o.status}),e.jsx("span",{style:{fontSize:10,opacity:.68},children:o.domain}),e.jsx("span",{style:{fontSize:10,opacity:.68},children:o.chartType??"table"})]}),e.jsx("div",{style:{fontSize:12,opacity:.72},children:o.description||o.path})]},o.id))})]})})}function Wd({lineage:t}){var s,n;const r=((s=t==null?void 0:t.graph)==null?void 0:s.nodes)??[],a=((n=t==null?void 0:t.graph)==null?void 0:n.edges)??[],i=(t==null?void 0:t.breadcrumbs)??[];return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:12,fontWeight:800,textTransform:"uppercase",opacity:.62,marginBottom:6},children:"App Lineage"}),e.jsx("div",{style:{fontSize:12,opacity:.72},children:"Terms and business views connect the App back to DQL blocks, dbt models, and source tables."})]}),i.length>0&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:i.map((o,l)=>e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"64px 1fr",gap:8,fontSize:12},children:[e.jsx("span",{style:{fontFamily:"monospace",opacity:.6},children:o.type}),e.jsx("span",{children:o.name})]},`${o.id}-${l}`))}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[e.jsx(Ri,{label:"Nodes",value:r.length}),e.jsx(Ri,{label:"Edges",value:a.length})]}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:r.slice(0,18).map(o=>e.jsxs("div",{style:{border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6,padding:8},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[e.jsx("span",{style:{color:"#0d1117",background:rs[o.type]??"#8b949e",borderRadius:3,padding:"1px 4px",fontSize:9,fontWeight:800,flexShrink:0},children:ts[o.type]??o.type.slice(0,4).toUpperCase()}),e.jsx("div",{style:{fontSize:12,fontWeight:700,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o.name})]}),e.jsxs("div",{style:{fontSize:11,opacity:.62,fontFamily:"monospace",marginTop:4},children:[as[o.type]??o.type," · ",o.id]})]},o.id))})]})}function Ri({label:t,value:r}){return e.jsxs("div",{style:{border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6,padding:8},children:[e.jsx("div",{style:{fontSize:11,opacity:.62},children:t}),e.jsx("div",{style:{fontSize:18,fontWeight:800},children:r})]})}function Hd(t,r){const a=new Set(["table",String(t.viz.type??"table"),...(r==null?void 0:r.allowedVisualizations)??[]]);return Array.from(a).map(s=>lr(s)).filter((s,n,o)=>o.indexOf(s)===n).map(s=>zn.find(n=>n.value===s)??{value:s,label:St(s)})}function Vd(t){return t==="TrustCallout"?"linear-gradient(180deg, rgba(255,255,255,0.92), rgba(255,251,235,0.72))":t==="RankingPanel"||t==="TrendPanel"||t==="PivotTable"?"linear-gradient(180deg, rgba(255,255,255,0.96), rgba(248,250,252,0.86))":t==="BusinessBrief"?"var(--dql-app-surface, rgba(255,255,255,0.90))":"var(--dql-app-surface, var(--surface, rgba(255,255,255,0.84)))"}function Kd({saving:t,error:r,pending:a,notice:i,onDismissError:s}){return r?e.jsxs("div",{role:"alert",style:Nr("var(--status-error, #c45555)"),children:[e.jsx(Er,{size:13}),e.jsxs("span",{style:{flex:1,minWidth:0},children:["Save failed — ",r]}),e.jsx("button",{type:"button",onClick:s,style:Qd,children:"Dismiss"})]}):t?e.jsxs("div",{role:"status",style:Nr("var(--text-secondary)"),children:[e.jsx(Un,{size:13})," Saving…"]}):a?e.jsxs("div",{role:"status",style:Nr("var(--status-warning, #b8860b)"),children:[e.jsx(Er,{size:13})," Layout preview not saved — Apply or Cancel to continue."]}):i?e.jsxs("div",{role:"status",style:Nr("var(--text-tertiary)"),children:[e.jsx(es,{size:13})," ",i]}):null}const Nr=t=>({display:"flex",alignItems:"center",gap:7,padding:"5px 12px",fontSize:11.5,color:t,borderBottom:"1px solid var(--border-subtle)"}),Qd={border:"none",background:"transparent",color:"inherit",cursor:"pointer",fontSize:11,fontWeight:700,textDecoration:"underline",padding:0};function Gd(t){const r={size:13,strokeWidth:2.2};switch(t){case"line":return e.jsx(nn,{...r});case"area":return e.jsx(As,{...r});case"pie":return e.jsx(Ms,{...r});case"donut":return e.jsx(Ws,{...r});case"table":return e.jsx(on,{...r});case"kpi":return e.jsx(sn,{...r});case"gauge":return e.jsx(Vi,{...r});case"scatter":return e.jsx(Fs,{...r});case"heatmap":return e.jsx(Vs,{...r});case"histogram":return e.jsx(Ts,{...r});case"stacked-bar":return e.jsx($s,{...r});case"grouped-bar":return e.jsx(Ns,{...r});case"funnel":return e.jsx(Zt,{...r});case"waterfall":return e.jsx(ks,{...r});case"sankey":return e.jsx(ar,{...r});default:return e.jsx(an,{...r})}}function An(t){switch(t.component){case"BusinessBrief":return"Business summary";case"KpiMetric":return"KPI";case"TrendPanel":return"Trend";case"RankingPanel":return"Ranking";case"EvidenceTable":return"Evidence";case"PivotTable":return"Pivot";case"TrustCallout":return"Trust";case"ResearchActions":return"Analysis";case"NarrativePanel":return"Narrative";default:return t.role?St(t.role):"Generated"}}function Yd(t,r){const a=new RegExp(`^###\\s*${rd(r)}\\s*`,"i");return t.replace(a,"").replace(/\*\*Trust:\*\*.*$/gim,"").replace(/\*\*Review status:\*\*.*$/gim,"").replace(/\*\*Next actions:\*\*[\s\S]*$/im,"").replace(/\*\*Review tasks:\*\*[\s\S]*$/im,"").trim().split(/\n{2,}/).map(n=>n.trim()).find(Boolean)||"Generated app section pending analyst review."}function Ot(t){return{border:"1px solid var(--dql-app-line, var(--border-color, rgba(0,0,0,0.12)))",borderRadius:8,background:t?"var(--dql-app-accent-soft, var(--surface-hover, rgba(0,0,0,0.06)))":"var(--dql-app-surface, var(--surface, rgba(0,0,0,0.02)))",color:"inherit",padding:"7px 10px",cursor:"pointer",fontSize:12,fontWeight:720,display:"inline-flex",alignItems:"center",gap:6,minHeight:32}}const Xd={width:34,height:34,border:"1px solid var(--dql-app-accent, #4f46e5)",borderRadius:8,background:"var(--dql-app-accent-soft, rgba(79,70,229,0.12))",color:"var(--dql-app-accent, #4f46e5)",cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center"},Jd={display:"flex",alignItems:"center",flexWrap:"wrap",gap:6,marginBottom:10,minWidth:0},In={border:"1px solid var(--border-subtle)",borderRadius:7,background:"var(--bg-1)",color:"var(--text-secondary)",padding:"4px 8px",cursor:"pointer",fontSize:10.5,fontWeight:720},Zd={...In,display:"inline-flex",alignItems:"center",gap:5,color:"var(--accent)",borderColor:"var(--accent-dim)"},Dd={position:"fixed",inset:0,zIndex:120,display:"grid",placeItems:"center",padding:24,background:"rgba(0, 0, 0, 0.38)"},Ud={width:"min(780px, calc(100vw - 32px))",maxHeight:"min(760px, calc(100vh - 48px))",overflow:"hidden",display:"grid",gap:12,padding:16,border:"1px solid var(--border-default)",borderRadius:12,background:"var(--bg-0)",color:"var(--text-primary)",boxShadow:"0 24px 80px rgba(0,0,0,0.28)"};function ep(t){return{border:t?"1px solid var(--accent)":"1px solid var(--border-subtle)",borderRadius:7,background:t?"var(--accent-dim)":"var(--bg-1)",color:t?"var(--accent)":"var(--text-secondary)",padding:"5px 9px",cursor:"pointer",fontSize:11,fontWeight:750}}const tp={margin:0,minHeight:180,padding:14,borderRadius:8,background:"var(--bg-2)",color:"var(--text-primary)",whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontFamily:"var(--font-mono, monospace)",fontSize:12,lineHeight:1.55},rp={marginBottom:12,color:"var(--dql-app-muted, var(--color-text-secondary, rgba(0,0,0,0.64)))",fontSize:12,lineHeight:1.45},Nn={border:"1px solid var(--dql-app-line-2, var(--border-color, rgba(15,23,42,0.10)))",borderRadius:10,background:"linear-gradient(180deg, rgba(255,255,255,0.96), rgba(248,250,252,0.88))",boxShadow:"0 8px 24px rgba(15,23,42,0.05)",padding:14,marginBottom:12,display:"grid",gap:9},Rn={display:"flex",alignItems:"flex-start",gap:10,minWidth:0},Tn={width:30,height:30,borderRadius:8,background:"var(--dql-app-accent-soft, rgba(79,70,229,0.10))",color:"var(--dql-app-accent, #4f46e5)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},Pn={fontSize:10.5,fontWeight:820,letterSpacing:0,textTransform:"uppercase",color:"var(--dql-app-muted, rgba(15,23,42,0.58))"},$n={margin:"2px 0 0",fontSize:15,lineHeight:1.25,fontWeight:820,color:"var(--dql-app-text, inherit)"},_n={margin:0,fontSize:13.5,lineHeight:1.48,color:"var(--dql-app-muted, rgba(15,23,42,0.72))"},Ja={display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},qr={border:"1px solid var(--dql-app-line, var(--border-color, rgba(15,23,42,0.10)))",borderRadius:999,background:"var(--dql-app-surface, rgba(255,255,255,0.78))",color:"var(--dql-app-muted, rgba(15,23,42,0.68))",padding:"3px 8px",fontSize:11,fontWeight:720,lineHeight:1.2,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},En={...qr,color:"var(--dql-app-accent, #4f46e5)",borderColor:"rgba(79,70,229,0.22)",background:"var(--dql-app-accent-soft, rgba(79,70,229,0.08))"},Ti={border:"1px solid var(--dql-app-line-2, var(--border-color, rgba(15,23,42,0.14)))",borderRadius:8,background:"var(--dql-app-surface, var(--surface, #fff))",color:"var(--dql-app-text, var(--text-primary, #0f172a))",padding:"6px 10px",fontSize:11.5,fontWeight:720,cursor:"pointer"};function ap(t){return{position:"fixed",right:24,top:76,bottom:24,zIndex:70,width:t?`min(${ya}px, calc(100vw - 96px))`:`min(${ps}px, calc(100vw - 64px))`,minWidth:0}}const Pi={width:"100%",boxSizing:"border-box",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,background:"var(--surface, transparent)",color:"inherit",fontSize:12,padding:"8px 10px"},Bn={border:"1px solid var(--accent, #4f46e5)",borderRadius:6,background:"var(--accent, #4f46e5)",color:"var(--color-text-on-accent, #fff)",padding:"7px 11px",cursor:"pointer",fontSize:12,fontWeight:700},ip={border:"none",borderRadius:6,background:"transparent",color:"inherit",padding:"9px 10px",cursor:"pointer",textAlign:"left",display:"grid",gap:2},np={position:"fixed",top:72,right:16,bottom:16,zIndex:120,width:"min(360px, calc(100vw - 32px))",boxSizing:"border-box",border:"1px solid var(--border-default)",borderRadius:12,padding:14,background:"var(--bg-0)",color:"var(--text-primary)",boxShadow:"0 22px 70px rgba(15,23,42,0.22)",display:"grid",alignContent:"start",gap:12,fontStyle:"normal",overflowY:"auto",overscrollBehavior:"contain"},sp={position:"sticky",top:-14,zIndex:2,margin:"-14px -14px 0",padding:"13px 14px 11px",display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,borderBottom:"1px solid var(--border-subtle)",background:"var(--bg-0)"},op={width:30,height:30,padding:0,border:"1px solid var(--border-subtle)",borderRadius:7,background:"var(--bg-1)",color:"var(--text-secondary)",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",flex:"none"},$i={display:"grid",gap:9,padding:12,border:"1px solid var(--border-subtle)",borderRadius:9,background:"var(--bg-1)"},_i={fontSize:10.5,fontWeight:820,textTransform:"uppercase",letterSpacing:"0.055em",color:"var(--text-tertiary)"},Ei={display:"grid",gridTemplateColumns:"repeat(2, minmax(0, 1fr))",gap:8},Na={display:"grid",gap:3,fontSize:10,fontWeight:700,opacity:.78},Ra={width:"100%",minWidth:0,boxSizing:"border-box",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:5,background:"var(--surface, transparent)",color:"inherit",padding:"5px 6px",fontSize:11},lp={display:"grid",gap:6,paddingTop:9},Bi={border:"1px solid var(--border-subtle)",borderRadius:9,background:"var(--bg-1)",padding:"0 12px 11px"},Mi={cursor:"pointer",padding:"11px 0 0",color:"var(--text-secondary)",fontSize:11.5,fontWeight:760};function dp(t){return{border:"1px solid var(--accent, rgba(79,70,229,0.55))",background:t?"rgba(79,70,229,0.10)":"rgba(79,70,229,0.08)",color:"var(--accent, #4f46e5)",borderRadius:5,padding:"5px 7px",fontSize:11,fontWeight:750,display:"inline-flex",alignItems:"center",gap:5,cursor:t?"wait":"pointer",opacity:t?.72:1,whiteSpace:"nowrap"}}const Mn={fontSize:11,lineHeight:1.35,color:"var(--dql-app-muted, rgba(15,23,42,0.68))"},pp={...Mn,color:"var(--error-color, #b91c1c)"},cp={border:"1px solid var(--border-color, rgba(0,0,0,0.10))",borderRadius:4,background:"var(--surface, rgba(0,0,0,0.02))",color:"inherit",padding:"2px 5px",fontSize:10,cursor:"pointer",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},up={marginTop:7,display:"flex",flexWrap:"wrap",gap:5,alignItems:"center",minWidth:0},qt={display:"inline-flex",alignItems:"center",minHeight:18,borderRadius:999,border:"1px solid var(--border-color, rgba(15,23,42,0.10))",background:"rgba(148,163,184,0.10)",color:"var(--dql-app-muted, rgba(15,23,42,0.70))",padding:"2px 7px",fontSize:10,fontWeight:720,lineHeight:1.1};function xp(t){return{...qt,border:t?"1px solid rgba(22,163,74,0.26)":"1px solid rgba(217,119,6,0.28)",background:t?"rgba(22,163,74,0.10)":"rgba(245,158,11,0.12)",color:t?"#15803d":"#b45309",gap:4}}const gp={display:"inline-flex",alignItems:"center",gap:2,padding:2,border:"1px solid var(--border-color, rgba(15,23,42,0.12))",borderRadius:6,background:"rgba(255,255,255,0.74)",flexShrink:0};function fp(t){return{width:24,height:24,border:"none",borderRadius:4,background:t?"var(--dql-app-accent, var(--accent, #4f46e5))":"transparent",color:t?"var(--color-text-on-accent, #fff)":"inherit",cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:0}}function mp(t){return{width:"100%",alignSelf:"stretch",overflow:"auto",display:"flex",flexDirection:"column",gap:10,fontStyle:"normal",opacity:1,lineHeight:1.45,borderRadius:6,padding:t?10:0,background:t?"rgba(245,158,11,0.08)":"transparent"}}function hp(t){return{width:30,height:30,borderRadius:7,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,background:t?"rgba(245,158,11,0.14)":"rgba(79,70,229,0.10)",color:t?"#b45309":"var(--dql-app-accent, var(--accent, #4f46e5))"}}const bp={...qt,background:"rgba(79,70,229,0.08)",color:"var(--dql-app-accent, var(--accent, #4f46e5))",border:"1px solid rgba(79,70,229,0.16)"},vp={width:"100%",alignSelf:"stretch",overflow:"auto",display:"flex",flexDirection:"column",gap:9,fontStyle:"normal",opacity:1,lineHeight:1.35},yp={display:"grid",gap:6},wp={display:"grid",gridTemplateColumns:"minmax(0, 1fr)",gap:7,alignItems:"start",border:"1px solid var(--border-color, rgba(15,23,42,0.09))",borderRadius:7,background:"rgba(255,255,255,0.56)",padding:"7px 8px"},qp={...qt,minHeight:16,borderRadius:5,padding:"1px 5px",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},jp={display:"grid",gap:1,minWidth:82,textAlign:"left",fontSize:10.5},kp={...qt,minHeight:18,background:"rgba(22,163,74,0.09)",border:"1px solid rgba(22,163,74,0.18)",color:"#15803d"},ea={width:24,height:24,borderRadius:5,border:"1px solid var(--border-color, rgba(0,0,0,0.12))",background:"var(--surface, rgba(255,255,255,0.72))",color:"inherit",cursor:"pointer",padding:0,display:"inline-flex",alignItems:"center",justifyContent:"center"},Sp={width:26,height:26,borderRadius:6,border:"1px solid var(--border-color, rgba(0,0,0,0.12))",background:"var(--surface, rgba(255,255,255,0.72))",color:"inherit",cursor:"grab",padding:0,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},zp={position:"absolute",top:"calc(100% + 6px)",right:0,zIndex:40,width:240,border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:8,background:"var(--color-bg, #fff)",boxShadow:"0 14px 38px rgba(0,0,0,0.16)",padding:6,display:"grid",gap:4},Cp={border:"none",borderRadius:6,background:"transparent",color:"inherit",padding:"8px 9px",cursor:"pointer",textAlign:"left",display:"grid",gap:2};function Ap(t){return{border:`1px solid ${t?"var(--accent, #4f46e5)":"var(--border-color, rgba(0,0,0,0.12))"}`,borderRadius:999,background:t?"var(--color-bg-active, rgba(79,70,229,0.12))":"var(--surface, rgba(0,0,0,0.02))",color:t?"var(--accent, #4f46e5)":"inherit",padding:"4px 8px",fontSize:11,fontWeight:t?750:600,cursor:"pointer"}}const Li={border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:4,background:"var(--surface, rgba(0,0,0,0.02))",color:"inherit",padding:"3px 7px",cursor:"pointer",fontSize:11};function ma(t,r={w:6,h:3}){return{x:0,y:t.layout.items.reduce((i,s)=>Math.max(i,s.y+s.h),0),w:r.w,h:r.h}}function ha(t,r){const a=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"tile",i=new Set(t.layout.items.map(s=>s.i));if(!i.has(a))return a;for(let s=2;s<1e3;s++){const n=`${a}-${s}`;if(!i.has(n))return n}return`${a}-${Date.now()}`}function Ip(t,r){let a=0,i=0,s=0;return[...t].sort((n,o)=>n.y-o.y||n.x-o.x).map(n=>{const o=r===1?1:Math.min(r,Math.max(2,Math.ceil(n.w/2)));a+o>r&&(a=0,i+=s||n.h,s=0);const l={...n,x:a,y:i,w:o};return a+=o,s=Math.max(s,n.h),l})}function Np({app:t}){var l,d;const{state:r,dispatch:a}=Ki(),[i,s]=p.useState(!1),n=p.useRef(null);p.useEffect(()=>{if(!i)return;const x=b=>{var m;(m=n.current)!=null&&m.contains(b.target)||s(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[i]);const o=r.activePersona?`${r.activePersona.displayName??r.activePersona.userId} [${r.activePersona.roles.join(", ")}]`:"View as: Owner";return!t||t.members.length===0?e.jsx("span",{style:{fontSize:12,opacity:.6},children:o}):e.jsxs("div",{ref:n,style:{position:"relative"},children:[e.jsxs("button",{onClick:()=>s(x=>!x),style:{padding:"6px 12px",fontSize:12,background:"var(--surface, rgba(0,0,0,0.04))",border:"1px solid var(--border-color, rgba(0,0,0,0.1))",borderRadius:6,cursor:"pointer",color:"inherit",display:"inline-flex",alignItems:"center",gap:6},"aria-haspopup":"menu","aria-expanded":i,children:[e.jsx("span",{style:{fontSize:11,opacity:.65},children:"View as:"}),e.jsx("span",{style:{fontWeight:600},children:((l=r.activePersona)==null?void 0:l.displayName)??((d=r.activePersona)==null?void 0:d.userId)??"Owner"}),r.activePersona&&e.jsxs("span",{style:{fontSize:11,opacity:.7},children:["[",r.activePersona.roles.join(", "),"]"]}),e.jsx("span",{style:{fontSize:10,opacity:.6},children:"▾"})]}),i&&e.jsxs("div",{role:"menu",style:{position:"absolute",top:"100%",right:0,marginTop:4,minWidth:240,background:"var(--surface-elevated, #fff)",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,boxShadow:"0 4px 12px rgba(0,0,0,0.08)",zIndex:50},children:[e.jsxs("button",{role:"menuitem",onClick:async()=>{await D.clearPersona(),a({type:"SET_ACTIVE_PERSONA",persona:null}),s(!1)},style:Fi(r.activePersona===null),children:[e.jsx("div",{style:{fontWeight:500},children:"Owner (local)"}),e.jsx("div",{style:{fontSize:11,opacity:.65},children:"Default — no RLS narrowing"})]}),e.jsx("div",{style:{height:1,background:"var(--border-color, rgba(0,0,0,0.08))",margin:"4px 0"}}),t.members.map(x=>{var b;return e.jsxs("button",{role:"menuitem",onClick:async()=>{const m=await D.setPersona(x.userId,t.id);a({type:"SET_ACTIVE_PERSONA",persona:m}),s(!1)},style:Fi(((b=r.activePersona)==null?void 0:b.userId)===x.userId),children:[e.jsx("div",{style:{fontWeight:500},children:x.displayName??x.userId}),e.jsxs("div",{style:{fontSize:11,opacity:.65},children:["[",x.roles.join(", "),"]",x.attributes&&Object.keys(x.attributes).length>0?` · ${Object.entries(x.attributes).map(([m,f])=>`${m}=${f}`).join(", ")}`:""]})]},x.userId)})]})]})}function Fi(t){return{display:"block",width:"100%",textAlign:"left",padding:"8px 12px",background:t?"var(--surface-hover, rgba(0,0,0,0.06))":"transparent",border:"none",cursor:"pointer",color:"inherit",fontSize:13}}function Rp(t,r){const a=t.filter(i=>r==null?void 0:r.tiles.some(s=>{var n;return s.tileId===i&&((n=s.repair)==null?void 0:n.approvalEligible)===!1}));return{ready:t.length>0&&t.every(i=>r==null?void 0:r.tiles.some(s=>{var n;return s.tileId===i&&s.status==="ok"&&((n=s.repair)==null?void 0:n.approvalEligible)!==!1})),repairedTileIds:a}}function Tp(t){return t.preference==="expanded"?!0:t.preference==="collapsed"||t.loading?!1:t.appCount===0&&t.localDraftCount===0}const Pp=p.lazy(()=>oa(()=>import("./UnifiedAgentRunPanel--oxmjlgr.js").then(t=>t.c),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14])).then(t=>({default:t.UnifiedAgentRunPanel})));p.lazy(()=>oa(()=>import("./usePersistedAgentThreadId-C4foXeiQ.js").then(t=>t.h),__vite__mapDeps([4,1,2,3,5,6,7,8,9,10])).then(t=>({default:t.StructuredAnswerText})));const Ta="Build an analytics app from my certified DQL blocks and available warehouse tables.",Pa="dql.apps.active-ai-build.v1";function Oi(){try{const t=window.localStorage.getItem(Pa);if(!t)return null;const r=JSON.parse(t);return typeof r.sessionId=="string"&&typeof r.prompt=="string"&&typeof r.createdAt=="string"?r:null}catch{return null}}function ba(t){try{t?window.localStorage.setItem(Pa,JSON.stringify(t)):window.localStorage.removeItem(Pa)}catch{}}const $p={all:"All",drafts:"Local drafts",private:"Private",shared:"Shared",fav:"Favourites"};function _p(t){return t==="obsidian"||t==="dark"||t==="midnight"?"obsidian":t==="white"||t==="arctic"?"white":"paper"}function zc(){var Hr,Vr,Sr;const t=is(ns(j=>({activeAppExperience:j.activeAppExperience,activeAppId:j.activeAppId,activeAppDraftId:j.activeAppDraftId,activeAppSection:j.activeAppSection,activeDashboardId:j.activeDashboardId,apps:j.apps,appsLoading:j.appsLoading,authoredDomains:j.authoredDomains,themeMode:j.themeMode}))),r=Gi(),a=ss(),{operations:i,track:s}=os(),n=p.useMemo(()=>_p(t.themeMode),[t.themeMode]),[o,l]=p.useState(()=>t.activeAppDraftId?"create":t.activeAppId?"workspace":"library"),d=t.activeAppExperience,x=t.activeAppSection,b=j=>{r({type:"SET_APP_WORKSPACE_STATE",experience:j})},m=j=>{r({type:"SET_APP_WORKSPACE_STATE",section:j})},[f,y]=p.useState(""),[u,w]=p.useState("all"),[q,C]=p.useState(()=>new Set),[k,M]=p.useState(null),[L,X]=p.useState(null),[I,O]=p.useState(!1),[F,U]=p.useState("ai"),[_,A]=p.useState(!1),[te,Q]=p.useState("operational_dashboard"),[Y,S]=p.useState(Ta),[h,$]=p.useState(""),ee=p.useRef(!1),[W,$e]=p.useState("");p.useMemo(()=>ls(t.authoredDomains),[t.authoredDomains]);const[se,oe]=p.useState("analytics"),[Be,ue]=p.useState("stakeholders"),Ae=p.useRef(!1),[_e,Ie]=p.useState(null),[xe,Ze]=p.useState(()=>t.activeAppDraftId),[it,R]=p.useState([]),[le,ge]=p.useState(!1),[ve,Te]=p.useState(null),[de,Pe]=p.useState(()=>new Set),[Ye,Xe]=p.useState(null),[De,Ee]=p.useState(null),ze=p.useRef(Oi()),[Z,pe]=p.useState(((Hr=ze.current)==null?void 0:Hr.sessionId)??null),[ye,Ne]=p.useState(((Vr=ze.current)==null?void 0:Vr.operationId)??null),We=p.useRef(null),[Me,Ue]=p.useState(new Set),[we,nt]=p.useState(new Set),[Le,re]=p.useState({}),[lt,Ce]=p.useState(!1),[bt,ie]=p.useState(null),[dt,He]=p.useState(!1),[et,Re]=p.useState(!1),[gt,H]=p.useState(""),[ke,fe]=p.useState(!1),[qe,zt]=p.useState(null),[vt,Vt]=p.useState(null),[Dt,Ut]=p.useState(!1),[pr,pt]=p.useState(null),[_t,st]=p.useState(null),[Kt,Qt]=p.useState({}),[cr,er]=p.useState({}),[ur,xr]=p.useState(!1),[Gt,Yt]=p.useState(!1),ct=p.useCallback(j=>{xr(j),j||Yt(!1)},[]),ft=ua({queryKey:["apps"],queryFn:()=>D.listAppsStrict(),staleTime:3e4}),Nt=ua({queryKey:["app-builds"],queryFn:()=>D.listAppBuilds(),staleTime:1e4}),N=ua({queryKey:["persona"],queryFn:()=>D.getPersona(),staleTime:6e4});p.useEffect(()=>{r({type:"SET_APPS_LOADING",loading:ft.isLoading}),ft.data&&r({type:"SET_APPS",apps:ft.data})},[ft.data,ft.isLoading,r]),p.useEffect(()=>{N.data&&r({type:"SET_ACTIVE_PERSONA",persona:N.data})},[r,N.data]),p.useEffect(()=>{t.activeAppDraftId&&(Ze(t.activeAppDraftId),Ie(null),l("create"))},[t.activeAppDraftId]);const B=p.useCallback(j=>{var Se;if(Ee(j),Ze(null),l("create"),U("ai"),S(j.prompt||Ta),Ie(j.inputs.existingAppId??null),$e(Gr(j.inputs.domain,t.authoredDomains)),oe(j.inputs.owner??"analytics"),ue(j.inputs.audience??"stakeholders"),A(j.inputs.exploreGaps===!0),j.status==="building"){He(!0);return}if(He(!1),j.status==="error"){ie(j.error??"The App proposal did not complete.");return}ie(null),Ue(j.proposal?ms(j.proposal):new Set),re(Rt=>{var Kr;return Object.fromEntries((((Kr=j.proposal)==null?void 0:Kr.tiles)??[]).map(fr=>[fr.id,Rt[fr.id]??{title:fr.title,viz:fr.viz}]))});const E=j.plan;nt(new Set(Kp(E)));const ce=j.inputs.existingAppId?(Se=E==null?void 0:E.pages[0])==null?void 0:Se.title:E==null?void 0:E.name;ce&&$(Rt=>ee.current?Rt:ce),E!=null&&E.audience&&ue(Rt=>Ae.current?Rt:E.audience)},[t.authoredDomains]),g=p.useMemo(()=>Z?i.find(j=>j.id===ye)??i.find(j=>j.type==="app_ai_build"&&j.scope===`app-build:${Z}`)??null:null,[ye,Z,i]);p.useEffect(()=>{const j=ze.current;j&&(ze.current=null,S(j.prompt),Ie(j.existingAppId??null),U("ai"),He(!0),l("create"))},[]),p.useEffect(()=>{if(!Z)return;if(g!=null&&g.id&&g.id!==ye){Ne(g.id);const Se=Oi();(Se==null?void 0:Se.sessionId)===Z&&ba({...Se,operationId:g.id})}g&&(g.status==="queued"||g.status==="running")&&(!De||De.status==="building")&&(He(!0),l("create"));let j=!1,E;const ce=async()=>{var Rt;const Se=await D.getAppAiBuild(Z);if(!j){if(!Se||Se.status==="building"){if(Se&&B(Se),g&&["failed","cancelled","interrupted"].includes(g.status)){He(!1),ie(((Rt=g.error)==null?void 0:Rt.message)??(g.status==="cancelled"?"The App proposal was cancelled.":"The App proposal did not complete."));return}E=window.setTimeout(()=>{ce()},900);return}He(!1),!(We.current===Se.id&&(De==null?void 0:De.status)===Se.status)&&(We.current=Se.id,B(Se))}};return ce(),()=>{j=!0,E!==void 0&&window.clearTimeout(E)}},[g,B,ye,De==null?void 0:De.status,Z]),p.useEffect(()=>{if(!t.activeAppId||o!=="workspace"){M(null),X(null);return}let j=!1;O(!0);const E=D.getApp(t.activeAppId).then(Se=>{j||M(Se)}),ce=t.activeDashboardId?D.getDashboard(t.activeAppId,t.activeDashboardId).then(Se=>{j||X(Se)}):Promise.resolve().then(()=>{j||X(null)});return Promise.allSettled([E,ce]).finally(()=>{j||O(!1)}),()=>{j=!0}},[t.activeAppId,t.activeDashboardId,o]);const K=p.useMemo(()=>JSON.stringify(ci((L==null?void 0:L.dashboard)??null)),[L==null?void 0:L.dashboard]),me=p.useMemo(()=>ci((L==null?void 0:L.dashboard)??null),[L==null?void 0:L.dashboard,K]);p.useEffect(()=>{const j=me;Qt(E=>{const ce={};for(const Se of j)ce[Se.id]=E[Se.id]??$r(Se);return xi(E,ce)?E:ce}),er(E=>{const ce={};for(const Se of j)ce[Se.id]=E[Se.id]??$r(Se);return xi(E,ce)?E:ce})},[L==null?void 0:L.dashboard.id,K,me]);const rt=async(j,E,ce,Se)=>{r({type:"SET_APPS_LOADING",loading:!0});const Rt=await D.listApps();r({type:"SET_APPS",apps:Rt}),r({type:"SET_APPS_LOADING",loading:!1}),j&&r({type:"OPEN_APP",appId:j,dashboardId:E,...Se}),ce&&l(ce)},Ve=(((Sr=Nt.data)==null?void 0:Sr.drafts)??[]).filter(j=>j.state!=="project_published"),yt=t.appsLoading||ft.isLoading||Nt.isLoading,Je=p.useMemo(()=>{const j=f.trim().toLowerCase();return t.apps.filter(E=>u==="drafts"||u==="private"&&sa(E)||u==="shared"&&!sa(E)||u==="fav"&&!q.has(E.id)?!1:j?[E.name,E.description??"",E.domain,E.audience??"",E.lifecycle??"",...E.tags??[],...E.owners??[],...E.dashboards.map(Se=>Se.title)].join(" ").toLowerCase().includes(j):!0)},[q,u,f,t.apps]),je=p.useMemo(()=>t.apps.find(j=>j.id===t.activeAppId)??null,[t.apps,t.activeAppId]),wt=p.useCallback(j=>{M(E=>E&&{...E,investigations:j})},[]),gr=(j,E="view")=>{if(E==="build"){Ie(j.id),Ze(null),U("classic"),Q("blank"),$(j.name),S(j.description??`Improve ${j.name} for ${j.audience??"stakeholders"}.`),$e(Gr(j.domain,t.authoredDomains)),ue(j.audience??"stakeholders"),ie(null),l("create");return}r({type:"OPEN_APP",appId:j.id,experience:E,section:"dashboards"}),l("workspace")},ut=j=>{ba(null),pe(null),Ne(null),Ie(null),Ze(null),U(j.mode==="ai"?"ai":"classic"),A(j.sourcePolicy==="include_review_required"),Q(j.template),S(j.mode==="ai"?j.prompt:"Create a governed analytical App"),$(j.mode==="manual"?j.name:""),$e(E=>Gr(E,t.authoredDomains)),ue("stakeholders"),Pe(new Set),ie(null),Xe(null),Ee(null),re({}),nt(new Set),l("create")},Mt=async(j,E)=>{const ce=t.activeAppId;if(!ce||!j.trim())return;const Se=await D.renameApp(ce,E?{pageTitle:j.trim(),dashboardId:E}:{name:j.trim()});if(!Se.ok){ie(Se.error);return}await rt(ce,E??t.activeDashboardId??void 0,"workspace")},Or=()=>{if(!t.activeAppId||!k)return;const j=gt.trim();if(!j){zt("Describe the business question this page should answer.");return}zt(null),ba(null),pe(null),Ne(null),Ie(t.activeAppId),Ze(null),U("ai"),S(j),$("New App page"),$e(Gr(k.app.domain,t.authoredDomains)),oe(k.app.owners[0]??"analytics"),ue(k.app.audience??"stakeholders");const E=k.app.publicationIntent==="personal"||!k.app.publicationIntent&&k.app.visibility==="private";A(E&&ke),Pe(new Set),ie(null),Xe(null),Ee(null),re({}),Re(!1),H(""),fe(!1),l("create")},tr=p.useMemo(()=>({...cr}),[cr]),jr=p.useCallback((j,E)=>{Qt(ce=>({...ce,[j.id]:Hl(j,E)}))},[]),pa=p.useCallback(()=>{er({...Kt})},[Kt]),kr=p.useCallback(()=>{const j=Object.fromEntries(me.map(E=>[E.id,$r(E)]));Qt(j),er(j)},[me]),ca=async()=>{if(!(!vt||Dt)){Ut(!0),pt(null);try{const j=await D.deleteApp(vt.id,vt.fingerprint);C(E=>{const ce=new Set(E);return ce.delete(vt.id),ce}),r({type:"SET_APPS",apps:t.apps.filter(E=>E.id!==vt.id)}),t.activeAppId===vt.id&&r({type:"CLOSE_APP"}),Vt(null),l("library"),await a.invalidateQueries({queryKey:["apps"]}),st({appName:vt.name,recoveryId:j.recoveryId})}catch(j){pt(j instanceof Error?j.message:String(j))}finally{Ut(!1)}}},Fe=async()=>{if(!_t)return;const j=_t;st(null);try{await D.restoreApp(j.recoveryId),await a.invalidateQueries({queryKey:["apps"]}),await a.invalidateQueries({queryKey:["app-builds"]}),await rt()}catch(E){ie(E instanceof Error?E.message:String(E))}},Wr=p.useCallback(()=>{r({type:"CLOSE_APP"}),M(null),X(null),Ie(null),Ze(null),l("library")},[r]);return e.jsxs("div",{className:`dql-apps-waterline dql-apps-theme-${n}`,children:[e.jsx("style",{children:Zo}),o==="library"?e.jsx(Ep,{apps:Je,allApps:t.apps,loading:yt,search:f,filter:u,favorites:q,localDrafts:Ve,onSearch:y,onFilter:w,onToggleFavorite:j=>{C(E=>{const ce=new Set(E);return ce.has(j)?ce.delete(j):ce.add(j),ce})},onStartStudio:ut,onContinueDraft:j=>{var E,ce;Ze(j.id),Ie(((E=j.baseApp)==null?void 0:E.appId)??null),U(j.authoringMode==="ai"?"ai":"classic"),Q(j.template),A(j.sourcePolicy==="include_review_required"),S(j.frame.goal),$(j.name),$e(((ce=j.pages[0])==null?void 0:ce.metadata.domain)??""),ue(j.frame.audience??"stakeholders"),l("create")},onOpenApp:gr,onDeleteApp:j=>{pt(null),Vt(j)}}):o==="create"?e.jsx(No,{initialMode:F==="ai"?"ai":"manual",initialPrompt:Y,initialName:h,initialDraftId:xe,initialSourcePolicy:_?"include_review_required":"governed_only",initialTemplate:te,startImmediately:!0,baseAppId:_e,domain:W,audience:Be,themeMode:t.themeMode,onBack:Wr,onPublished:(j,E)=>{a.invalidateQueries({queryKey:["app-builds"]}),rt(j.id,E,"workspace",{experience:"view",section:"dashboards"})},onDraftDeleted:j=>{st(j),l("library"),a.invalidateQueries({queryKey:["app-builds"]})}}):e.jsx(Op,{app:je,appDoc:k,dashboardDoc:L,loading:I,experience:d,section:x,explainOpen:ur,explainExpanded:Gt,dashboardFilters:me,dashboardFilterValues:Kt,themeMode:t.themeMode,variables:tr,onBack:Wr,onExperienceChange:j=>{j==="build"&&je?gr(je,"build"):b(j)},onSectionChange:m,onDashboardFilterChange:jr,onApplyDashboardFilters:pa,onResetDashboardFilters:kr,onExplainChange:ct,onExplainExpandedChange:Yt,onAddPage:()=>{fe(!1),Re(!0)},onOpenDashboard:j=>r({type:"OPEN_DASHBOARD",dashboardId:j}),onOpenApp:(j,E,ce)=>{if(ce){Ze(ce),Ie(null),r({type:"OPEN_APP_DRAFT",draftId:ce,appId:j,dashboardId:E}),l("create");return}rt(j,E,"workspace",{experience:"build",section:"dashboards"})},onRenameApp:(j,E)=>void Mt(j,E),onDashboardChanged:j=>{X(E=>E&&{...E,dashboard:j}),rt(t.activeAppId,j.id,"workspace")},onInvestigationsChanged:wt,onOpenLineageNode:j=>{r({type:"OPEN_LINEAGE_DETAIL",nodeId:j,returnTo:t.activeAppId?{view:"apps",appId:t.activeAppId,dashboardId:t.activeDashboardId,label:je==null?void 0:je.name,experience:d,section:x}:null})}}),et&&e.jsx(Up,{title:gt,allowExploration:(k==null?void 0:k.app.publicationIntent)==="personal"||!(k!=null&&k.app.publicationIntent)&&(k==null?void 0:k.app.visibility)==="private",exploreGaps:ke,error:qe,onChange:H,onExploreGapsChange:fe,onCancel:()=>{Re(!1),fe(!1),zt(null)},onCreate:Or}),vt&&e.jsx(Lp,{app:vt,deleting:Dt,error:pr,onCancel:()=>{Dt||(Vt(null),pt(null))},onConfirm:()=>void ca()}),_t?e.jsxs("div",{className:"dql-app-delete-undo",role:"status",children:[e.jsxs("span",{children:[e.jsx("strong",{children:_t.appName})," moved to local recovery."]}),e.jsx("button",{type:"button",onClick:()=>void Fe(),children:"Undo"}),e.jsx("button",{type:"button","aria-label":"Dismiss delete recovery message",onClick:()=>st(null),children:"×"})]}):null]})}function Ep({apps:t,allApps:r,loading:a,search:i,filter:s,favorites:n,localDrafts:o,onSearch:l,onFilter:d,onToggleFavorite:x,onStartStudio:b,onContinueDraft:m,onOpenApp:f,onDeleteApp:y}){const u=ec(r,o,n),[w,q]=p.useState({mode:"ai",prompt:Ta,name:"Untitled Analytics App",template:"operational_dashboard",sourcePolicy:"governed_only"}),[C,k]=p.useState("auto"),M=Tp({preference:C,loading:a,appCount:r.length,localDraftCount:o.length}),L=i.trim().toLowerCase(),X=s==="all"||s==="drafts"?o.filter(O=>{var F;return!L||[O.name,O.frame.goal,O.frame.audience??"",((F=O.pages[0])==null?void 0:F.metadata.domain)??"",O.authoringMode].join(" ").toLowerCase().includes(L)}):[],I=X.length>0||t.length>0;return e.jsxs("main",{className:"dql-apps-wrap",children:[e.jsx("div",{id:"app-studio-launcher",hidden:!M,children:M?e.jsx(Ao,{config:w,onChange:O=>q(F=>({...F,...O})),onSubmit:()=>b(w)}):null}),e.jsxs("section",{className:"dql-apps-library-head","aria-labelledby":"app-library-title",children:[e.jsxs("div",{children:[e.jsx("span",{className:"dql-app-eyebrow",children:"Your workspace"}),e.jsx("h2",{id:"app-library-title",children:"Apps"}),e.jsx("p",{children:"Local drafts and Project-published Apps live together here, with their visibility and trust state always clear."})]}),e.jsxs("div",{className:"dql-apps-library-summary","aria-label":"App library summary",children:[e.jsxs("button",{type:"button",className:"dql-app-card-act primary","aria-controls":"app-studio-launcher","aria-expanded":M,onClick:()=>k(M?"collapsed":"expanded"),children:[M?e.jsx(dr,{size:13,"aria-hidden":"true"}):e.jsx(xt,{size:13,"aria-hidden":"true"}),M?"Hide new App form":"Build new App"]}),e.jsxs("span",{children:[e.jsx("strong",{children:o.length})," local draft",o.length===1?"":"s"]}),e.jsxs("span",{children:[e.jsx("strong",{children:u.private})," private"]}),e.jsxs("span",{children:[e.jsx("strong",{children:u.shared})," shared"]})]})]}),e.jsxs("div",{className:"dql-apps-libbar",children:[e.jsx("div",{className:"dql-apps-filter-tabs",children:["all","drafts","private","shared","fav"].map(O=>e.jsxs("button",{className:s===O?"on":"",onClick:()=>d(O),children:[$p[O]," ",e.jsx("span",{children:u[O]})]},O))}),e.jsxs("label",{className:"dql-apps-search",children:[e.jsx(jt,{size:15,strokeWidth:2,"aria-hidden":"true"}),e.jsx("input",{value:i,onChange:O=>l(O.target.value),placeholder:"Search apps, domains, owners..."})]})]}),a&&r.length===0&&o.length===0?e.jsx(kt,{title:"Loading Apps...",detail:"Reading local app files from this DQL project."}):I?e.jsxs("div",{className:"dql-apps-grid","aria-label":"App library",children:[X.map(O=>e.jsx(Bp,{draft:O,onOpen:()=>m(O)},O.id)),t.map(O=>e.jsx(Mp,{app:O,favorite:n.has(O.id),onToggleFavorite:()=>x(O.id),onOpen:()=>f(O,"view"),onEdit:()=>f(O,"build"),onDelete:()=>y(O)},O.id))]}):e.jsx(kt,{title:"No Apps match this view.",detail:"Change the filter or start a new App above. New work always begins as a local private draft."})]})}function Bp({draft:t,onOpen:r}){var s;const a=t.reviewTasks.some(n=>n.status==="open"),i=((s=t.pages[0])==null?void 0:s.metadata.domain)||"Local workspace";return e.jsxs("article",{className:"dql-app-card dql-app-draft-card",children:[e.jsxs("div",{className:"dql-app-card-body",onClick:r,role:"button",tabIndex:0,onKeyDown:n=>{(n.key==="Enter"||n.key===" ")&&r()},children:[e.jsxs("div",{className:"dql-app-card-top",children:[e.jsxs("div",{className:"dql-app-card-labels",children:[e.jsx("span",{className:"dql-app-eyebrow",children:i}),e.jsxs("span",{className:"dql-app-visibility private",children:[e.jsx(Qe,{size:12})," Private draft"]})]}),e.jsx("span",{className:"dql-app-draft-mark",children:e.jsx(At,{size:15})})]}),e.jsx(br,{tone:a?"draft":"agentic",children:a?"review required":"local draft"}),e.jsx("h3",{children:t.name}),e.jsx("p",{children:Oa(t.frame.goal||"A private App draft ready to shape in Studio.")}),e.jsxs("div",{className:"dql-app-card-mini",children:[e.jsx(vr,{label:"Pages",value:String(t.pages.length)}),e.jsx(vr,{label:"Mode",value:t.authoringMode==="ai"?"AI + manual":"Manual"}),e.jsx(vr,{label:"Revision",value:String(t.revision)})]}),e.jsxs("div",{className:"dql-app-card-signals",children:[e.jsxs("span",{children:[e.jsx(Qe,{size:13})," Not in Project source"]}),e.jsxs("span",{children:[e.jsx(ht,{size:13})," ",t.sourcePolicy==="include_review_required"?"Review lane enabled":"Governed sources"]})]})]}),e.jsxs("div",{className:"dql-app-card-depth",children:[e.jsx("span",{children:"Saved locally"}),e.jsxs("button",{type:"button",className:"dql-app-card-act primary",onClick:r,children:["Continue ",e.jsx(ws,{size:12})]})]})]})}function Mp({app:t,favorite:r,onToggleFavorite:a,onOpen:i,onEdit:s,onDelete:n}){var u,w;const[o,l]=p.useState(!1),d=t.certification==="certified"||t.lifecycle==="certified",x=((u=t.drafts)==null?void 0:u.length)??0,b=t.investigations??0,m=t.aiPins??0,f=sa(t),y=d?"Certified app":x>0||b>0||m>0?"Review needed":"Draft app";return e.jsxs("article",{className:"dql-app-card",children:[e.jsxs("div",{className:"dql-app-card-body",onClick:i,role:"button",tabIndex:0,children:[e.jsxs("div",{className:"dql-app-card-top",children:[e.jsxs("div",{className:"dql-app-card-labels",children:[e.jsx("span",{className:"dql-app-eyebrow",children:t.domain||"Domain"}),e.jsxs("span",{className:`dql-app-visibility ${f?"shared":"private"}`,children:[f?e.jsx(co,{size:12}):e.jsx(Qe,{size:12}),f?"Shared Project":"Private Project"]})]}),e.jsx("button",{type:"button",className:`dql-app-star ${r?"on":""}`,onClick:q=>{q.stopPropagation(),a()},"aria-label":r?"Remove favourite":"Add favourite",children:e.jsx(qs,{size:14,strokeWidth:1.8})})]}),e.jsx(br,{tone:d?"certified":x>0?"draft":"agentic",children:d?"certified":x>0?"mixed":t.lifecycle??"draft"}),e.jsx("h3",{children:t.name}),e.jsx("p",{children:Oa(t.description||`${t.name} consumption surface for ${t.domain}.`)}),e.jsxs("div",{className:"dql-app-card-mini",children:[e.jsx(vr,{label:"Pages",value:String(t.dashboards.length)}),e.jsx(vr,{label:"Books",value:String(((w=t.notebooks)==null?void 0:w.length)??0)}),e.jsx(vr,{label:"Drafts",value:String(x)})]}),e.jsxs("div",{className:"dql-app-card-signals",children:[e.jsxs("span",{children:[e.jsx(Qe,{size:13})," ",y]}),e.jsxs("span",{children:[e.jsx(jt,{size:13})," ",b," analysis"]}),e.jsxs("span",{children:[e.jsx(ht,{size:13})," ",m," local insights"]})]})]}),e.jsxs("div",{className:"dql-app-card-depth",children:[e.jsx("span",{children:tc(t)}),e.jsxs("button",{type:"button",className:"dql-app-card-act",onClick:i,title:"View app",children:[e.jsx(Yi,{size:12})," View"]}),e.jsxs("button",{type:"button",className:"dql-app-card-act",onClick:s,title:"Edit app",children:[e.jsx(Di,{size:12})," Edit"]}),e.jsxs("div",{className:"dql-app-card-menu",children:[e.jsx("button",{type:"button",className:"dql-app-card-act",onClick:q=>{q.stopPropagation(),l(C=>!C)},title:"More App actions","aria-expanded":o,children:e.jsx(ta,{size:14})}),o?e.jsx("div",{role:"menu",children:e.jsxs("button",{type:"button",role:"menuitem",className:"danger",onClick:q=>{q.stopPropagation(),l(!1),n()},children:[e.jsx(ir,{size:13})," Delete App"]})}):null]})]})]})}function Lp({app:t,deleting:r,error:a,onCancel:i,onConfirm:s}){const[n,o]=p.useState(""),l=n.trim()===t.name;return e.jsx("div",{className:"dql-app-delete-backdrop",role:"presentation",onMouseDown:d=>{d.target===d.currentTarget&&i()},children:e.jsxs("section",{className:"dql-app-delete-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"delete-app-title",children:[e.jsxs("div",{className:"dql-app-delete-heading",children:[e.jsx("span",{className:"dql-app-delete-icon",children:e.jsx(ir,{size:16})}),e.jsxs("div",{children:[e.jsxs("h2",{id:"delete-app-title",children:["Delete ",t.name,"?"]}),e.jsx("p",{children:"Its project files and App-scoped local context move to recoverable local trash. Source control will show the canonical project files as deleted."})]})]}),e.jsxs("label",{className:"dql-app-delete-confirm",children:["Type ",e.jsx("strong",{children:t.name})," to confirm",e.jsx("input",{autoFocus:!0,value:n,onChange:d=>o(d.target.value),onKeyDown:d=>{d.key==="Enter"&&l&&!r&&s()},disabled:r})]}),a?e.jsx("div",{className:"dql-app-delete-error",role:"alert",children:a}):null,e.jsxs("div",{className:"dql-app-delete-actions",children:[e.jsx("button",{type:"button",className:"secondary",onClick:i,disabled:r,children:"Cancel"}),e.jsx("button",{type:"button",className:"danger",onClick:s,disabled:!l||r,children:r?"Deleting…":"Delete App"})]})]})})}async function Fp(t){const r=new TextEncoder().encode(JSON.stringify(t)),a=await crypto.subtle.digest("SHA-256",r);return`sha256:${Array.from(new Uint8Array(a)).map(i=>i.toString(16).padStart(2,"0")).join("")}`}function Op({app:t,appDoc:r,dashboardDoc:a,loading:i,experience:s,section:n,explainOpen:o,explainExpanded:l,dashboardFilters:d,dashboardFilterValues:x,themeMode:b,variables:m,onBack:f,onExperienceChange:y,onRenameApp:u,onSectionChange:w,onDashboardFilterChange:q,onApplyDashboardFilters:C,onResetDashboardFilters:k,onExplainChange:M,onExplainExpandedChange:L,onAddPage:X,onOpenDashboard:I,onOpenApp:O,onDashboardChanged:F,onInvestigationsChanged:U,onOpenLineageNode:_}){var gt;const A=Gi(),te=(a==null?void 0:a.dashboard.layout.items.filter(H=>!!H.block).length)??0,Q=((gt=r==null?void 0:r.drafts)==null?void 0:gt.length)??0,Y=p.useMemo(()=>Ln((a==null?void 0:a.dashboard)??null).map(H=>H.blockId),[a]),S=Y.join("|"),[h,$]=p.useState(Y[0]??null),[ee,W]=p.useState(null),[$e,se]=p.useState(null),[oe,Be]=p.useState(null),[ue,Ae]=p.useState(null),[_e,Ie]=p.useState("idle"),[xe,Ze]=p.useState(""),[it,R]=p.useState("idle"),[le,ge]=p.useState(""),ve=(a==null?void 0:a.dashboard.layout.items.filter(H=>H.semantic).map(H=>H.i))??[],{ready:Te,repairedTileIds:de}=Rp(ve,ee),Pe=p.useCallback(H=>{W(H)},[]),[Ye,Xe]=p.useState(!1),[De,Ee]=p.useState(null),ze=p.useMemo(()=>Tl((a==null?void 0:a.dashboard)??null,ee),[a,ee]),Z=p.useCallback(H=>Al((a==null?void 0:a.dashboard)??null,H,ee),[a,ee]),pe=p.useCallback(async H=>{var zt;if(!(t!=null&&t.id)||!a)return;const ke=((zt=a.app)==null?void 0:zt.id)??t.id;if(ke!==t.id){Ee("This page belongs to a different app than the one open. Reload the app and try again.");return}Xe(!0),Ee(null);const fe=await D.saveDashboard(ke,a.dashboard.id,{...H});if(Xe(!1),!fe.ok){Ee(fe.error);return}const qe=await D.getDashboard(t.id,a.dashboard.id);qe!=null&&qe.dashboard&&(F==null||F(qe.dashboard))},[t==null?void 0:t.id,a,F]),ye=p.useCallback(H=>{if(!a)return;const ke=Il(a.dashboard,H,ee);ke!==a.dashboard&&pe(ke)},[a,ee,pe]),[Ne,We]=p.useState([]);p.useEffect(()=>{We([])},[a==null?void 0:a.dashboard.id]);const Me=p.useCallback((H,ke)=>{We(fe=>fe.some(qe=>qe.column===H)?fe:[...fe,{id:H,column:H}]),q({id:H,type:"select",bindsTo:H},ke),C()},[C,q]),Ue=p.useCallback(H=>{ye(H),We(ke=>ke.filter(fe=>fe.column!==H))},[ye]),we=p.useCallback(H=>{a&&pe(Nl(a.dashboard,H))},[a,pe]);p.useCallback(H=>{Be({...H,nonce:Date.now()}),w("research"),M(!0)},[M,w]);const nt=p.useCallback(H=>{Ae(H)},[]),Le=p.useCallback(()=>{Be(null)},[]),re=p.useCallback((H,ke)=>{var fe,qe;if($(H),s==="view"){A({type:"OPEN_GLOBAL_AI",audience:"stakeholder",context:{title:"App copilot",scopeHint:hr(t==null?void 0:t.name)?`Follow up on ${hr(t==null?void 0:t.name)}`:"Follow up on this tile",selectedObject:{kind:"block",id:H,title:a==null?void 0:a.dashboard.metadata.title},workspaceContext:{appId:t==null?void 0:t.id,dashboardId:a==null?void 0:a.dashboard.id,blockId:H},suggestedQuestions:(qe=(fe=a==null?void 0:a.app)==null?void 0:fe.copilot)==null?void 0:qe.suggestedQuestions},autoRun:{text:ke,mode:"auto"}});return}M(!0),se({text:ke,nonce:Date.now()})},[A,s,t==null?void 0:t.id,t==null?void 0:t.name,a==null?void 0:a.dashboard.id,a==null?void 0:a.dashboard.metadata.title,M]);p.useEffect(()=>{s==="view"&&(n==="notebooks"||n==="ai"||n==="drafts"||n==="settings")&&w("dashboards")},[s,n,w]),p.useEffect(()=>{if(Y.length===0){h!==null&&$(null);return}(!h||!Y.includes(h))&&$(Y[0])},[Y,S,h]),p.useEffect(()=>{W(null),Ae(null)},[t==null?void 0:t.id,a==null?void 0:a.dashboard.id]);const lt=!!(t&&a&&(n==="dashboards"||n==="research")),Ce=lt&&o,bt=H=>{Ie(H),H!=="ready"&&window.setTimeout(()=>Ie("idle"),1800)},ie=async()=>{var fe;const H=Zp(t,r,a);Ze(H);let ke=!1;try{typeof navigator<"u"&&((fe=navigator.clipboard)!=null&&fe.writeText)&&(await navigator.clipboard.writeText(H),ke=!0)}catch{ke=!1}if(!ke){const qe=document.createElement("textarea");qe.value=H,qe.style.position="fixed",qe.style.left="-9999px",document.body.appendChild(qe),qe.focus(),qe.select(),ke=document.execCommand("copy"),document.body.removeChild(qe)}bt(ke?"copied":"ready")},dt=()=>{const H=Dp(t,r,a),ke=new Blob([H],{type:"text/markdown;charset=utf-8"}),fe=URL.createObjectURL(ke),qe=document.createElement("a");qe.href=fe,qe.download=`${(t==null?void 0:t.id)??(r==null?void 0:r.app.id)??"dql-app"}-brief.md`,document.body.appendChild(qe),qe.click(),document.body.removeChild(qe),URL.revokeObjectURL(fe),bt("downloaded")},He=async()=>{if(!(t!=null&&t.id))return;R("running"),ge("");const H=await D.publishAppToProject(t.id,{lifecycle:"review"});if(!H.ok){R("error"),ge(H.error);return}R("done"),ge(`${H.paths.length} shared files published from the private draft${H.removedLocalTiles?`; ${H.removedLocalTiles} local-only insight removed`:""}.`),window.setTimeout(()=>R("idle"),2400)},et=async()=>{if(!(t!=null&&t.id)||!a||!ee||ve.length===0)return;R("running"),ge("");const H=await Fp(a.dashboard),ke=await D.approveAppSemanticTiles(t.id,a.dashboard.id,{runId:ee.runId,tileIds:ve,expectedDashboardFingerprint:H});if(!ke.ok){R("error"),ge(ke.error);return}F(ke.dashboard),R("done"),ge(`${ve.length} semantic result${ve.length===1?"":"s"} approved with run ${ee.runId}.`)},Re=n==="dashboards"&&!!a;return e.jsxs("div",{className:"dql-app-workspace",children:[e.jsxs("div",{className:"dql-app-view-topbar",children:[e.jsxs("button",{type:"button",className:"dql-app-back dql-app-back-label",onClick:f,title:"Back to apps",children:[e.jsx(_r,{size:14}),e.jsx("span",{children:"Apps"})]}),e.jsx("span",{className:"dql-app-crumb",children:e.jsx("b",{children:(t==null?void 0:t.id)??"app"})}),e.jsx(br,{tone:"certified",children:Q>0?`${te} certified`:"All certified"}),Q>0?e.jsxs(br,{tone:"draft",children:[Q," draft"]}):null,e.jsx("span",{className:"dql-app-topbar-divider","aria-hidden":"true"}),e.jsxs("div",{className:"dql-app-modeseg",role:"group","aria-label":"App mode",children:[e.jsxs("button",{type:"button",className:s==="view"?"on":"",onClick:()=>y("view"),title:"Clean stakeholder view",children:[e.jsx(Yi,{size:12})," View"]}),e.jsxs("button",{type:"button",className:s==="build"?"on":"",onClick:()=>y("build"),title:"Rearrange tiles and edit this app",children:[e.jsx(Di,{size:12})," Edit"]})]}),e.jsxs("div",{className:"dql-app-view-actions",children:[e.jsx(Np,{app:(r==null?void 0:r.app)??null}),s==="build"&&ve.length>0?e.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>void et(),disabled:it==="running"||!Te,title:Te?"Approve the successful semantic run for publication":de.length>0?"AI-repaired semantic previews are review-required and cannot be approved as governed semantic results":"Run this dashboard successfully before semantic approval",children:[e.jsx(Pt,{size:14})," Approve semantic (",ve.length,")"]}):null,s==="build"?e.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>void He(),disabled:it==="running",children:[e.jsx(Qe,{size:14})," ",it==="running"?"Checking":"Publish to Project"]}):null,e.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line dql-apps-btn-icon",title:_e==="copied"?"Copied handoff":"Share local app handoff",onClick:()=>void ie(),children:_e==="copied"?e.jsx(Pt,{size:15}):e.jsx(to,{size:15})}),e.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line dql-apps-btn-icon",title:_e==="downloaded"?"Brief saved":"Download app brief",onClick:dt,children:_e==="downloaded"?e.jsx(Pt,{size:15}):e.jsx(ds,{size:15})}),_e==="ready"?e.jsxs("div",{className:"dql-app-share-popover",children:[e.jsx("b",{children:"Local handoff"}),e.jsx("textarea",{readOnly:!0,value:xe,onFocus:H=>H.currentTarget.select()})]}):null,it==="done"||it==="error"?e.jsx("div",{className:`dql-app-promote-popover ${it==="error"?"error":""}`,children:le}):null]})]}),e.jsxs("main",{className:"dql-app-view-wrap",children:[e.jsxs("div",{className:"dql-app-title-row",children:[e.jsxs("div",{className:"dql-app-title-copy",children:[e.jsxs("div",{className:"dql-app-title-meta",children:[e.jsxs("span",{children:[e.jsx(At,{size:14})," ",(t==null?void 0:t.domain)??(a==null?void 0:a.dashboard.metadata.domain)??"DQL App"]}),Re?s==="build"&&t?e.jsx("span",{className:"dql-app-title-context",children:e.jsx(Wi,{variant:"compact",value:hr(t.name)||"App",label:"App name",onCommit:H=>void u(H)},`${t.id}:name`)}):e.jsx("span",{className:"dql-app-title-context",children:hr(t==null?void 0:t.name)||"App"}):null,s==="build"?e.jsx(br,{tone:"draft",children:"Customizing"}):null]}),s==="build"&&t?e.jsx(Wi,{value:hr(Re?a==null?void 0:a.dashboard.metadata.title:t.name)||"App",label:Re?"Page name":"App name",onCommit:H=>void u(H,Re?a==null?void 0:a.dashboard.id:void 0)},`${t.id}:${Re?(a==null?void 0:a.dashboard.id)??"":"app"}`):e.jsx("h1",{children:hr(Re?a==null?void 0:a.dashboard.metadata.title:t==null?void 0:t.name)||"App"}),e.jsx("p",{children:Oa((Re?a==null?void 0:a.dashboard.metadata.description:t==null?void 0:t.description)??"Local DQL App")})]}),e.jsxs("div",{className:"dql-app-nav-row",children:[e.jsx(Wp,{appDoc:r,section:n,experience:s,onChange:w}),n==="dashboards"&&(r!=null&&r.dashboards.length)?e.jsx(Hp,{dashboards:r.dashboards,activeDashboardId:a==null?void 0:a.dashboard.id,isBuild:s==="build",onOpen:I,onAdd:X}):null,lt?e.jsx("button",{type:"button",className:`dql-apps-btn dql-apps-btn-line dql-apps-btn-icon ${o?"on":""}`,title:o?"Hide AI copilot":"Show AI copilot",onClick:()=>M(!o),children:e.jsx(nr,{size:15})}):null,Re?e.jsx(e.Fragment,{children:e.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line dql-apps-btn-icon",title:"Open dashboard lineage",onClick:()=>{t&&a&&_(`dashboard:${t.id}/${a.dashboard.id}`)},children:e.jsx(Qi,{size:15})})}):null]})]}),e.jsxs("div",{className:`dql-app-view-layout ${Ce?"":"no-explain"}`,children:[e.jsxs("div",{className:"dql-app-main-column",children:[n==="dashboards"&&a&&(d.length>0||ze.length>0||s==="build")?e.jsxs("section",{className:"dql-app-filter-row","aria-label":"Dashboard filters",children:[e.jsxs("div",{className:"dql-app-filter-row-copy",children:[e.jsx("b",{children:"Filters"}),e.jsx("span",{children:"Set the business scope, then apply once to refresh the full story."})]}),d.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Ml,{filters:d,values:x,onChange:q}),d.some(H=>Z(H.id).unaffected.length>0)?e.jsx("div",{className:"dql-app-filter-runtime-coverage","aria-label":"Filter coverage",children:d.map(H=>{const ke=Z(H.id);return ke.unaffected.length===0?null:e.jsxs("span",{className:`dql-app-filter-coverage ${ke.applied.length===0?"is-none":"is-partial"}`,title:`Unaffected: ${ke.unaffected.map(fe=>`${fe.title??fe.tileId}${fe.reason?` — ${fe.reason}`:""}`).join("; ")}`,children:[Oe(H.id)," affects ",ke.applied.length," of ",ke.filterable," tiles"]},H.id)})}):null,e.jsxs("div",{className:"dql-app-filter-row-actions",children:[e.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:k,children:"Reset"}),e.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-primary",onClick:C,children:"Apply filters"})]})]}):null,e.jsx(Ll,{candidates:ze,coverageFor:Z,onApply:Me}),Ne.length>0?e.jsxs("div",{className:"dql-app-filter-session",children:[e.jsx("span",{children:"Your filters, this session only."}),s==="build"?Ne.map(H=>e.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",disabled:Ye,onClick:()=>Ue(H.column),children:["Save “",Oe(H.column),"” to page"]},H.id)):null]}):null,s==="build"?e.jsx(Fl,{filters:a.dashboard.filters??[],candidates:ze,coverageFor:Z,onAdd:ye,onRemove:we,busy:Ye}):null,De?e.jsx("div",{className:"dql-app-filter-error",role:"alert",children:De}):null]}):null,i?e.jsx(kt,{title:"Loading app...",detail:"Reading dashboard files and running local blocks."}):n==="dashboards"&&a&&t?e.jsx(bd,{appId:t.id,dashboard:a.dashboard,editable:s==="build",embeddedHeader:!0,variables:m,selectedBlockId:h,onBlockFocus:$,onAskBlock:re,onOpenLineageNode:_,copilotOpen:o,onCopilotChange:M,onDashboardChanged:F,onRunChange:Pe}):n==="notebooks"?e.jsx(Do,{appDoc:r}):n==="research"?e.jsx(il,{appDoc:r,dashboardDoc:a,seed:oe,themeMode:b,onSeedHandled:Le,onDashboardChanged:F,onInvestigationsChanged:U,onActiveInvestigationChange:nt}):n==="ai"?e.jsx(Uo,{appDoc:r}):n==="drafts"?e.jsx(el,{appDoc:r}):n==="settings"?e.jsx(tl,{appDoc:r}):e.jsx(kt,{title:"No dashboard page selected.",detail:"Choose a dashboard page or add one in Build mode."})]}),Ce?e.jsx(Vp,{app:t,appDoc:r,dashboardDoc:a,dashboardRun:ee,variables:m,selectedBlockId:h,askSeed:$e,themeMode:b,expanded:l,onToggleExpanded:()=>L(!l),onClose:()=>M(!1),onOpenApp:O}):null]})]})]})}function Wi({value:t,label:r,onCommit:a,variant:i="title"}){const[s,n]=p.useState(t);return p.useEffect(()=>{n(t)},[t]),e.jsx("input",{className:i==="compact"?"dql-app-title-input dql-app-title-input-compact":"dql-app-title-input","aria-label":r,title:`${r} — press Enter to save`,value:s,size:i==="compact"?Math.max(8,Math.min(36,s.length+1)):void 0,maxLength:120,onChange:o=>n(o.target.value),onBlur:()=>{const o=s.trim();o&&o!==t?a(o):n(t)},onKeyDown:o=>{o.key==="Enter"&&o.currentTarget.blur(),o.key==="Escape"&&(n(t),o.currentTarget.blur())}})}function Wp({appDoc:t,section:r,experience:a,onChange:i}){var l,d,x,b,m;const s=((l=t==null?void 0:t.investigations)==null?void 0:l.length)??0,n={id:"dashboards",label:"Canvas",count:(t==null?void 0:t.dashboards.length)??0,icon:e.jsx(At,{size:14})},o=[{id:"research",label:"Analysis & evidence",count:s,icon:e.jsx(jt,{size:14})},{id:"notebooks",label:"Source notebooks",count:((d=t==null?void 0:t.notebooks)==null?void 0:d.length)??((x=t==null?void 0:t.app.notebooks)==null?void 0:x.length)??0,icon:e.jsx(Ui,{size:14})},{id:"ai",label:"Saved insights",count:((b=t==null?void 0:t.aiPins)==null?void 0:b.length)??0,icon:e.jsx(nr,{size:14})},{id:"drafts",label:"Review drafts",count:((m=t==null?void 0:t.drafts)==null?void 0:m.length)??0,icon:e.jsx(mt,{size:14})},{id:"settings",label:"App settings",icon:e.jsx(ar,{size:14})}];return e.jsxs("nav",{className:"dql-app-section-tabs","aria-label":"App sections",children:[e.jsxs("button",{className:r===n.id?"on":"","data-app-section":n.id,onClick:()=>i(n.id),children:[e.jsx("i",{className:"dql-app-tab-icon",children:n.icon}),e.jsx("span",{className:"dql-app-tab-label",children:n.label}),e.jsx("b",{children:n.count})]}),a==="build"?e.jsxs("details",{className:"dql-app-context-menu",children:[e.jsxs("summary",{children:[e.jsx(ta,{size:14})," Context"]}),e.jsx("div",{children:o.map(f=>e.jsxs("button",{type:"button",className:r===f.id?"on":"",onClick:()=>i(f.id),children:[f.icon,e.jsx("span",{children:f.label}),f.count!==void 0?e.jsx("b",{children:f.count}):null]},f.id))})]}):null]})}function Hp({dashboards:t,activeDashboardId:r,isBuild:a,onOpen:i,onAdd:s}){const n=t.find(o=>o.id===r)??t[0];return e.jsxs("div",{className:"dql-app-page-picker","aria-label":"Dashboard page",children:[e.jsxs("span",{children:[e.jsx(nn,{size:14})," Page"]}),e.jsx("select",{value:(n==null?void 0:n.id)??"",onChange:o=>i(o.target.value),title:(n==null?void 0:n.title)??"Dashboard page",children:t.map(o=>e.jsxs("option",{value:o.id,children:[o.title," (",o.itemCount,")"]},o.id))}),a?e.jsx("button",{type:"button",onClick:s,title:"Add dashboard page",children:e.jsx(xt,{size:14})}):null]})}function Vp({app:t,appDoc:r,dashboardDoc:a,dashboardRun:i,variables:s,selectedBlockId:n,askSeed:o,themeMode:l,expanded:d,onToggleExpanded:x,onClose:b,onOpenApp:m}){const f=Ht[l],y=(a==null?void 0:a.dashboard)??null,w=p.useMemo(()=>Ln(y,i),[y,i]).find(A=>A.blockId===n)??null,q=w?i==null?void 0:i.tiles.find(A=>A.tileId===w.tileId||A.blockId===w.blockId):null,C=(t==null?void 0:t.id)??(r==null?void 0:r.app.id)??"app",k=(y==null?void 0:y.id)??"dashboard",M=Ba(`app:${C}:${k}`),[L,X]=p.useState(!1),I=Oe((t==null?void 0:t.name)??(r==null?void 0:r.app.name)??(y==null?void 0:y.metadata.title)??"App workspace"),O=Oe((y==null?void 0:y.metadata.title)??"Dashboard"),F=w?`Focused on ${Oe(w.title)} in ${O}`:`Scoped to ${O}`,U=w?{kind:"block",id:w.blockId,title:w.title}:y?{kind:"dashboard",id:y.id,title:y.metadata.title}:{kind:"app",id:C,title:I},_=p.useMemo(()=>{var A,te,Q,Y,S;return{surface:"apps",appId:C,appName:(t==null?void 0:t.name)??(r==null?void 0:r.app.name),appDomain:(t==null?void 0:t.domain)??(r==null?void 0:r.app.domain),appDescription:(t==null?void 0:t.description)??(r==null?void 0:r.app.description),dashboardId:y==null?void 0:y.id,dashboardTitle:y==null?void 0:y.metadata.title,dashboardDescription:y==null?void 0:y.metadata.description,dashboardFilters:s,selectedBlock:w?{blockId:w.blockId,tileId:w.tileId,title:w.title,visualization:w.viz,status:q==null?void 0:q.status,certificationStatus:q==null?void 0:q.certificationStatus,rowCount:(A=q==null?void 0:q.result)==null?void 0:A.rowCount,columns:(Q=(te=q==null?void 0:q.result)==null?void 0:te.columns)==null?void 0:Q.slice(0,12),sampleRows:Jp((Y=q==null?void 0:q.result)==null?void 0:Y.rows,(S=q==null?void 0:q.result)==null?void 0:S.columns)}:void 0}},[t,r,C,y,w,q,s]);return e.jsx(Ea,{t:f,title:"App AI",subtitle:I,expanded:d,onToggleExpanded:x,resizable:!0,minResizeWidth:390,maxResizeWidth:1200,fitViewportHeight:!0,heightResizable:!0,minResizeHeight:520,onClose:b,onNewChat:M.resetThreadId,running:L,ariaLabel:"App AI",className:"dql-app-explain-panel dql-app-assistant-panel",children:e.jsx(p.Suspense,{fallback:e.jsx("div",{style:{padding:16,fontSize:12,color:f.textSecondary},children:"Loading App AI…"}),children:e.jsx(Pp,{themeMode:l,title:"App AI",scopeHint:F,audience:"stakeholder",selectedObject:U,workspaceContext:_,initialMode:"auto",autoRun:o!=null&&o.text?{text:o.text,mode:"ask",nonce:o.nonce}:void 0,threadId:M.threadId,onThreadIdChange:M.onThreadIdChange,onRunningChange:X,onOpenApp:m,answerFirstCards:!0,examplePrompts:[{label:"Explain this dashboard",prompt:"Explain the most important business story in this dashboard and what action it suggests."},{label:"Find the main driver",prompt:"What is the main driver behind the current result? Use the active app filters and governed evidence."},{label:"Check this result",prompt:"Validate the current result against its certified block, semantic definitions, and lineage."}]},`${C}:${k}`)})})}function Kp(t){return t?Array.from(new Set([...(t.globalFilters??[]).map(r=>r.id),...t.pages.flatMap(r=>(r.filters??[]).map(a=>a.id))])):[]}function va(t){return t.block?"blockId"in t.block?t.block.blockId??null:t.block.ref??null:null}function Ln(t,r){if(!t)return[];const a=new Map(((r==null?void 0:r.tiles)??[]).map(d=>[d.tileId,d])),i=new Map(((r==null?void 0:r.tiles)??[]).filter(d=>d.blockId).map(d=>[d.blockId,d])),s=new Set(t.layout.items.filter(d=>va(d)&&Hi(d)).map(d=>$a(`${d.title??""} ${va(d)??""}`)).filter(Boolean)),n=t.layout.items.map((d,x)=>{const b=va(d);if(!b)return null;const m=$a(`${d.title??""} ${b}`);if(m&&s.has(m)&&!Hi(d))return null;const f=a.get(d.i)??i.get(b);return{block:{blockId:b,title:d.title??b,viz:d.viz.type,tileId:d.i},duplicateKeys:Qp(d,f,b),score:Xp(d,f,x)}}).filter(d=>!!d).sort((d,x)=>x.score-d.score),o=new Set,l=[];for(const d of n)if(!d.duplicateKeys.some(x=>o.has(x))){for(const x of d.duplicateKeys)o.add(x);l.push(d.block)}return l}function Hi(t){var r,a;return(r=t.parameterBindings)!=null&&r.length?!0:!!((a=t.filterBindings)!=null&&a.some(i=>!i.unsupportedReason&&(i.mode==="parameter"||i.mode==="predicate"||!!i.binding)))}function Qp(t,r,a){const i=[`block:${a}`],s=Gp(r==null?void 0:r.result);s&&i.push(`result:${s}`);const n=$a(`${t.title??""} ${a}`);return n&&i.push(`topic:${n}`),i}function Gp(t){var i,s;if(!((i=t==null?void 0:t.columns)!=null&&i.length)||!((s=t.rows)!=null&&s.length))return"";const r=t.columns.slice(0,6).map(n=>n.toLowerCase()),a=t.rows.slice(0,3).map(n=>r.map(o=>Yp(n[o]??n[t.columns.find(l=>l.toLowerCase()===o)??o])).join(","));return[...r,...a].join("|")}function Yp(t){return t==null?"":typeof t=="number"?Number.isFinite(t)?String(Math.round(t*1e3)/1e3):"":String(t).toLowerCase().replace(/\s+/g," ").trim().slice(0,80)}function $a(t){const r=t.toLowerCase().replace(/\b(codex|e2e|qa|draft|imported|pasted|raw|sql|block)\b/g," ").replace(/\b20\d{10,}\b/g," "),a=/\b(player|players|scorer|scorers|athlete)\b/.test(r)?"player":/\b(customer|account|user)\b/.test(r)?"customer":/\b(team|teams)\b/.test(r)?"team":"",i=/\b(top|bottom|rank|ranking|leader|leaderboard|scorer|scorers)\b/.test(r)?"ranking":/\b(availability|freshness|record|records|quality|coverage)\b/.test(r)?"availability":/\b(trend|weekly|monthly|daily|over time)\b/.test(r)?"trend":"",s=/\b(point|points|pts|score|scoring|scorer|scorers)\b/.test(r)?"points":/\b(field goal|fgm|fga|field-goal|field_goals?)\b/.test(r)?"field_goals":/\b(count|records|games played)\b/.test(r)?"count":/\b(availability|freshness|quality|coverage)\b/.test(r)?"quality":"";return!a||!i||!s?"":`${a}|${i}|${s}`}function Xp(t,r,a){var s,n,o,l,d;let i=1e4-a;return(s=t.parameterBindings)!=null&&s.length&&(i+=5e4),(n=t.filterBindings)!=null&&n.length&&(i+=2e4),(r==null?void 0:r.status)==="ok"&&(i+=15e3),(l=(o=r==null?void 0:r.result)==null?void 0:o.rows)!=null&&l.length&&(i+=8e3),(r==null?void 0:r.certificationStatus)==="certified"&&(i+=5e3),String(t.trustState??((d=t.display)==null?void 0:d.trustState)??"").toLowerCase()==="certified"&&(i+=3e3),/codex\s+e2e|test|pasted/i.test(String(t.title??""))&&(i-=6e3),i}function Jp(t,r){if(!Array.isArray(t)||t.length===0)return;const a=Array.isArray(r)&&r.length>0?r.slice(0,8):Object.keys(t[0]??{}).slice(0,8);return t.slice(0,5).map(i=>Object.fromEntries(a.map(s=>[s,i[s]])))}function Zp(t,r,a){var l;const i=(t==null?void 0:t.id)??(r==null?void 0:r.app.id)??"app",s=(t==null?void 0:t.name)??(r==null?void 0:r.app.name)??"DQL App",n=(a==null?void 0:a.dashboard.metadata.title)??((l=r==null?void 0:r.dashboards[0])==null?void 0:l.title)??"Overview",o=typeof window<"u"?window.location.origin:"local DQL";return[s,`App ID: ${i}`,`Dashboard: ${n}`,`Domain: ${(t==null?void 0:t.domain)??(r==null?void 0:r.app.domain)??(a==null?void 0:a.dashboard.metadata.domain)??"unknown"}`,`Open locally: ${o}`].join(`
|
|
5593
|
-
`)}function
|
|
5587
|
+
`)}function hl({sections:t}){return e.jsx("div",{className:"dql-app-report-dynamic-sections",children:t.map(r=>{var a;return e.jsxs("section",{className:`dql-app-report-dynamic-section tone-${r.tone??"neutral"}`,children:[e.jsxs("div",{className:"dql-app-report-dynamic-head",children:[e.jsx("span",{children:vl(r)}),e.jsx("h3",{children:r.title})]}),e.jsx(bl,{text:r.body}),(a=r.bullets)!=null&&a.length?e.jsx("ul",{children:r.bullets.map(i=>e.jsx("li",{children:i},i))}):null]},r.id)})})}function bl({text:t}){const r=t.split(/\n{2,}/).map(a=>a.replace(/\s*\n\s*/g," ").trim()).filter(Boolean);return r.length?e.jsx("div",{className:"dql-app-report-memo-body",children:r.map(a=>e.jsx("p",{children:a},a))}):null}function vl(t){switch(t.kind){case"executive_answer":return"Answer";case"business_interpretation":return"Interpretation";case"key_numbers":return"Numbers";case"validation":return"Proof";case"reusable_logic":return"Reusable logic";case"recommended_next_step":return"Next step";case"review_boundary":return"Review boundary";default:return/focus/i.test(t.title)?"Scope":/repair|preview|sql/i.test(t.title)?"Appendix note":"Report note"}}function yl(t){return Array.isArray(t)?t.filter(r=>!!r&&typeof r.title=="string"&&r.title.trim().length>0&&typeof r.body=="string"&&r.body.trim().length>0).slice(0,8).map((r,a)=>({...r,id:r.id||`section-${a+1}`,title:r.title.trim(),body:r.body.trim(),bullets:Array.isArray(r.bullets)?r.bullets.filter(Boolean).slice(0,8):void 0,evidenceRefs:Array.isArray(r.evidenceRefs)?r.evidenceRefs.filter(Boolean).slice(0,8):void 0})):[]}function wl({drivers:t}){if(!t.length)return e.jsx("p",{className:"dql-app-report-muted",children:"No ranked drivers are available yet. Refresh the report after adding a clearer metric, time grain, or comparison group."});const r=t.slice(0,6).map(i=>({...i,numericValue:Math.abs(ql(i.value))})),a=Math.max(...r.map(i=>i.numericValue),0);return e.jsx("div",{className:"dql-app-report-driver-chart","aria-label":"Report driver chart",children:r.map((i,s)=>{const n=a>0?Math.max(8,Math.round(i.numericValue/a*100)):28;return e.jsxs("div",{className:"dql-app-report-driver-bar",children:[e.jsxs("div",{children:[e.jsx("b",{children:i.title}),e.jsx("span",{children:i.value})]}),e.jsx("i",{style:{"--driver-width":`${n}%`}}),e.jsx("p",{children:i.explanation})]},`${i.title}-${s}`)})})}function ql(t){const r=t.replace(/,/g,"").match(/-?\+?\d+(?:\.\d+)?/);if(!r)return 0;const a=Number(r[0].replace(/^\+/,""));return Number.isFinite(a)?a:0}function jl({investigation:t,tab:r,sqlDraft:a,onSqlDraftChange:i}){if(r==="sql")return e.jsxs("div",{className:"dql-app-research-sql-review",children:[e.jsx("textarea",{value:a,onChange:n=>i(n.target.value),spellCheck:!1,placeholder:"Generated SQL will appear here for review."}),t.error?e.jsx("div",{className:"dql-app-error",children:t.error}):null]});const s=at(t.evidence);if(r==="assumptions"){const n=Array.isArray(s.assumptions)?s.assumptions:[],o=at(s.trustStatus);return e.jsxs("div",{className:"dql-app-research-assumptions",children:[n.length?n.map((l,d)=>e.jsx("p",{children:String(l)},d)):e.jsx("p",{children:"Refresh the report to capture assumptions."}),e.jsx(li,{label:"Trust",value:String(o.label??"AI-generated report")}),e.jsx(li,{label:"Review",value:t.reviewStatus})]})}return r==="context"?e.jsx("pre",{className:"dql-app-research-code",children:JSON.stringify({certifiedContext:s.certifiedContext,trustStatus:s.trustStatus,planner:s.planner},null,2)}):e.jsx(kl,{investigation:t})}function kl({investigation:t}){const r=Wa(t);if(!r)return e.jsx(kt,{title:"No preview rows yet.",detail:"Refresh the report with SQL or selected tile results to capture proof.",compact:!0});const a=at(r.result),i=Array.isArray(a.rows)?a.rows.map(at).filter(n=>!!n).slice(0,8):[],s=Array.isArray(a.columns)?a.columns.map(String).slice(0,8):Object.keys(i[0]??{}).slice(0,8);return!i.length||!s.length?e.jsx(kt,{title:"No preview rows yet.",detail:"The report captured proof, but no row preview was available.",compact:!0}):e.jsx("div",{className:"dql-app-research-table",children:e.jsxs("table",{children:[e.jsx("thead",{children:e.jsx("tr",{children:s.map(n=>e.jsx("th",{children:Oe(n)},n))})}),e.jsx("tbody",{children:i.map((n,o)=>e.jsx("tr",{children:s.map(l=>e.jsx("td",{children:rl(n[l])},l))},o))})]})})}function Wa(t){return(Array.isArray(t.resultPreviews)?t.resultPreviews:[]).map(at).find(a=>!!a.result)??null}function Ar(t,r){const a=t.filter(i=>i.id!==r.id);return Ca([r,...a])}function Ca(t){return[...t].sort((r,a)=>pi(a)-pi(r))}function pi(t){const r=new Date(t.updatedAt||t.lastRunAt||t.createdAt).getTime();return Number.isFinite(r)?r:0}function bn(t){const r=t.title.replace(/^\s*(write\s+the\s+report\s+brief|the\s+research\s+question|research\s+question)\s*:\s*/i,"").replace(/^\s*research\b/i,"Analysis").replace(/^\s*report\b/i,"Analysis").trim(),a=Oe(r||t.title);return a.length<=64?a:`${a.slice(0,61).trim()}...`}function Sl(t){const r=t.status==="error"?"Needs SQL review":t.status==="ready"?"Ready":t.status==="running"?"Running":"Draft",a=zl(t.updatedAt||t.lastRunAt||t.createdAt);return`${Oe(t.intent)} / ${r}${a?` / ${a}`:""}`}function zl(t){if(!t)return"";const r=new Date(t).getTime();if(!Number.isFinite(r))return"";const a=Math.max(0,Date.now()-r),i=Math.floor(a/6e4);if(i<1)return"just now";if(i<60)return`${i}m ago`;const s=Math.floor(i/60);return s<24?`${s}h ago`:`${Math.floor(s/24)}d ago`}function Pr(t){return typeof t=="number"&&Number.isFinite(t)?Math.abs(t)>=100?Math.round(t).toLocaleString():Number(t.toFixed(2)).toLocaleString():typeof t=="string"&&t.trim()?t:"n/a"}function ci(t){if(!t)return[];const r=new Map;for(const i of t.filters??[])r.set(i.id,{...i});const a=i=>{var s,n;return((s=i.block)==null?void 0:s.blockId)??((n=i.block)==null?void 0:n.ref)};for(const i of t.layout.items??[]){const s=a(i);for(const n of i.filterBindings??[]){const o=n.mode??(n.binding?"predicate":void 0);if(!s||o!=="predicate"||!n.binding||n.unsupportedReason)continue;const l=r.get(n.filter);l&&(l.bindsTo||(l.bindsTo=n.binding),l.sourceBlockId||(l.sourceBlockId=s))}for(const n of i.parameterBindings??[]){const o=n.filter||n.field||n.param;o&&(r.has(o)||_l(r,n)||r.set(o,$l(n)))}}return Array.from(r.values()).filter(Pl)}function Cl(t,r,a){const i=((t==null?void 0:t.layout.items)??[]).filter(l=>!Tl(l));if(!((t==null?void 0:t.filters)??[]).some(l=>l.id===r)&&a){const l=new Set((a.tiles??[]).filter(d=>(d.filterableColumns??[]).some(x=>x.column===r)).map(d=>d.tileId).filter(d=>!!d));return{filterId:r,applied:i.filter(d=>l.has(d.i)).map(d=>d.i),unaffected:i.filter(d=>!l.has(d.i)).map(d=>({tileId:d.i,title:d.title,reason:"This tile does not return a column that can be filtered by this value."})),filterable:i.length}}const n=[],o=[];for(const l of i){const d=(l.filterBindings??[]).find(b=>b.filter===r)??(l.parameterBindings??[]).find(b=>(b.filter||b.field||b.param)===r);!!d&&!d.unsupportedReason&&!!(d.binding??d.param)?n.push(l.i):o.push({tileId:l.i,title:l.title,reason:(d==null?void 0:d.unsupportedReason)??(d?"The tile declares this filter but nothing to bind it to.":"This tile has no column matching the filter.")})}return{filterId:r,applied:n,unaffected:o,filterable:i.length}}function Al(t,r,a){var n;if((t.filters??[]).some(o=>o.id===r))return t;const i=new Map;for(const o of(a==null?void 0:a.tiles)??[]){const l=(n=o.filterableColumns)==null?void 0:n.find(d=>d.column===r);o.tileId&&(l!=null&&l.predicateTarget)&&i.set(o.tileId,l.predicateTarget)}const s=o=>o.map(l=>{const d=i.get(l.i);if(!d)return l;const x=(l.filterBindings??[]).filter(b=>b.filter!==r);return{...l,filterBindings:[...x,{filter:r,binding:d,mode:"predicate"}]}});return{...t,filters:[...t.filters??[],{id:r,type:Nl(r),bindsTo:r}],layout:{...t.layout,items:s(t.layout.items)}}}function Il(t,r){const a=i=>i.map(s=>({...s,filterBindings:(s.filterBindings??[]).filter(n=>n.filter!==r),parameterBindings:(s.parameterBindings??[]).filter(n=>n.filter!==r)}));return{...t,filters:(t.filters??[]).filter(i=>i.id!==r),layout:{...t.layout,items:a(t.layout.items)}}}function Nl(t){return/(_at$|_date$|_time$|_ts$|date|time|day|week|month|quarter|period)/i.test(t)?"daterange":/(top[_-]?n|limit|count|amount|number|year|score|rank)/i.test(t)?"number":/(_name$|_id$|^name$|search|email)/i.test(t)?"search":"select"}function Rl(t,r){var s;const a=new Set(((t==null?void 0:t.filters)??[]).map(n=>n.id)),i=new Map;for(const n of(r==null?void 0:r.tiles)??[])for(const o of n.filterableColumns??[]){if(a.has(o.column))continue;const l=i.get(o.column)??{tiles:0,values:new Set};l.tiles+=1;for(const d of(((s=n.result)==null?void 0:s.rows)??[]).slice(0,24)){const x=d==null?void 0:d[o.column];(typeof x=="string"||typeof x=="number")&&String(x).trim()&&l.values.size<24&&l.values.add(String(x))}i.set(o.column,l)}return Array.from(i.entries()).map(([n,o])=>({column:n,tiles:o.tiles,sampleValues:Array.from(o.values).sort()})).sort((n,o)=>o.tiles-n.tiles||n.column.localeCompare(o.column))}function Tl(t){var a;const r=String(((a=t.viz)==null?void 0:a.type)??"");return!!t.text||r==="text"||r==="heading"}function Pl(t){var r;return!(t.type==="select"&&!((r=t.options)!=null&&r.length)&&t.default===void 0&&!t.sourceBlockId)}function $l(t){const r=t.filter||t.field||t.param;return{id:r,type:El(r,t.parameterType),default:t.default??vn(r),bindsTo:t.param}}function _l(t,r){return Array.from(t.values()).some(a=>r.filter&&a.id===r.filter||r.field&&a.bindsTo===r.field?!0:!!(r.param&&a.bindsTo===r.param))}function El(t,r){return r==="number"||r==="number[]"?"number":r==="boolean"?"boolean":r==="date"||r==="date[]"?"date":/(_at$|_date$|_time$|_ts$|date|time|day|week|month|quarter|period)/i.test(t)?"daterange":/(top[_-]?n|limit|count|number|year|season)/i.test(t)?"number":"string"}function vn(t){const r=t.toLowerCase();return/(top[_-]?n|limit)/.test(r)?5:/(season|year).*start|start.*(season|year)/.test(r)?2016:/(season|year).*end|end.*(season|year)/.test(r)?2017:""}function Bl({filters:t,values:r,onChange:a}){return t.length===0?e.jsx("span",{className:"dql-app-filter-empty",children:"No filters"}):e.jsx(e.Fragment,{children:t.map(i=>e.jsx(Fl,{filter:i,value:r[i.id]??$r(i),onChange:s=>a(i,s)},i.id))})}function Ml({candidates:t,coverageFor:r,onApply:a}){const[i,s]=p.useState(""),[n,o]=p.useState(""),l=t.find(x=>x.column===i);if(t.length===0)return null;const d=l?r(l.column):null;return e.jsxs("div",{className:"dql-app-filter-picker",children:[e.jsxs("select",{"aria-label":"Filter this page by",value:i,onChange:x=>{s(x.target.value),o("")},children:[e.jsx("option",{value:"",children:"Filter by…"}),t.map(x=>e.jsx("option",{value:x.column,children:Oe(x.column)},x.column))]}),l?e.jsxs(e.Fragment,{children:[l.sampleValues.length>0?e.jsxs("select",{"aria-label":`${Oe(l.column)} value`,value:n,onChange:x=>o(x.target.value),children:[e.jsx("option",{value:"",children:"Choose a value…"}),l.sampleValues.map(x=>e.jsx("option",{value:x,children:x},x))]}):e.jsx("input",{"aria-label":`${Oe(l.column)} value`,value:n,placeholder:"Value…",onChange:x=>o(x.target.value)}),d?e.jsx("span",{className:"dql-app-filter-coverage-hint",children:d.applied.length===0?"No tile on this page can apply it":`Will narrow ${d.applied.length} of ${d.filterable} tiles`}):null,e.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-primary",disabled:!n.trim(),onClick:()=>{a(l.column,n.trim()),s(""),o("")},children:"Apply"})]}):null]})}function Ll({filters:t,candidates:r,coverageFor:a,onAdd:i,onRemove:s,busy:n}){const[o,l]=p.useState("");return e.jsxs("div",{className:"dql-app-filter-editor",children:[t.map(d=>{const x=a(d.id),b=x.unaffected.length>0&&x.applied.length>0,m=x.applied.length===0;return e.jsxs("div",{className:"dql-app-filter-editor-row",children:[e.jsx("span",{className:"dql-app-filter-editor-name",children:Oe(d.id)}),e.jsx("span",{className:`dql-app-filter-coverage${b?" is-partial":""}${m?" is-none":""}`,title:x.unaffected.length?`Not applied to: ${x.unaffected.map(f=>`${f.title??f.tileId}${f.reason?` — ${f.reason}`:""}`).join("; ")}`:"Applies to every tile on this page.",children:m?"Reaches no tile":`Applies to ${x.applied.length} of ${x.filterable} tile${x.filterable===1?"":"s"}`}),e.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",disabled:n,"aria-label":`Remove the ${Oe(d.id)} filter`,onClick:()=>s(d.id),children:"Remove"})]},d.id)}),r.length>0?e.jsxs("div",{className:"dql-app-filter-editor-row",children:[e.jsxs("select",{"aria-label":"Add a filter column",value:o,disabled:n,onChange:d=>l(d.target.value),children:[e.jsx("option",{value:"",children:"Add a filter…"}),r.map(d=>e.jsxs("option",{value:d.column,children:[Oe(d.column)," — in ",d.tiles," tile",d.tiles===1?"":"s"]},d.column))]}),e.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-primary",disabled:!o||n,onClick:()=>{i(o),l("")},children:"Add filter"})]}):t.length===0?e.jsx("span",{className:"dql-app-filter-empty",children:"No column is shared by enough tiles on this page to act as a global filter."}):null]})}function Fl({filter:t,value:r,onChange:a}){var b,m,f;const i=((b=t.label)==null?void 0:b.trim())||Oe(t.id),s=Ol(t,r),n=t.sourceBlockId,o=t.bindsTo||t.id,l=(t.type==="string"||t.type==="select"||t.type==="multiselect"||t.type==="search")&&!!n&&!((m=t.options)!=null&&m.length),[d,x]=p.useState(null);if(p.useEffect(()=>{if(!l||!n)return;let y=!1;return D.dashboardFilterOptions(n,o).then(u=>{y||x(u&&u.options.length>0&&!u.truncated?u.options:[])}),()=>{y=!0}},[n,o,l]),t.type!=="multiselect"&&d&&d.length>0)return e.jsx(Yr,{icon:rr(t),label:i,value:s,onChange:a,options:[["",`All ${i.toLowerCase()}`],...d.map(y=>[y,y])]});if(t.type==="select"&&ui(t).length>0)return e.jsx(Yr,{icon:rr(t),label:i,value:s,onChange:a,options:ui(t)});if(t.type==="multiselect"){const y=Array.isArray(r)?r.map(String):[],u=t.options??d??[];return e.jsxs("label",{className:"dql-app-filter-select",title:i,"aria-label":i,children:[e.jsx("span",{className:"dql-app-filter-icon",children:rr(t)}),e.jsx("select",{multiple:!0,value:y,"aria-label":`${i} multiple selection`,onChange:w=>a(Array.from(w.currentTarget.selectedOptions,q=>q.value)),children:u.map(w=>e.jsx("option",{value:String(w),children:Oe(String(w))},String(w)))})]})}if(t.type==="relative_date"){const y=(f=t.options)!=null&&f.length?t.options:["last_7_days","last_30_days","last_90_days","month_to_date","quarter_to_date","year_to_date"];return e.jsx(Yr,{icon:rr(t),label:i,value:s,onChange:a,options:y.map(u=>[String(u),Oe(String(u))])})}if(t.type==="boolean")return e.jsx(Yr,{icon:rr(t),label:i,value:String(!!r),onChange:y=>a(y==="true"),options:[["true","Yes"],["false","No"]]});if(t.type==="daterange"){const y=r&&typeof r=="object"&&!Array.isArray(r)?r:{},u=typeof y.start=="string"?y.start:"",w=typeof y.end=="string"?y.end:"",q=(C,k)=>a(C&&k?{start:C,end:k}:void 0);return e.jsxs("label",{className:"dql-app-filter-select dql-app-filter-range",title:t.bindsTo?`${i} -> ${t.bindsTo}`:i,"aria-label":i,children:[e.jsx("span",{className:"dql-app-filter-icon",children:rr(t)}),e.jsx("input",{type:"date",value:u,"aria-label":`${i} from`,onChange:C=>q(C.target.value,w)}),e.jsx("span",{className:"dql-app-filter-range-sep",children:"–"}),e.jsx("input",{type:"date",value:w,"aria-label":`${i} to`,onChange:C=>q(u,C.target.value)})]})}if(t.type==="number_range"){const y=r&&typeof r=="object"&&!Array.isArray(r)?r:{},u=typeof y.min=="number"||typeof y.min=="string"?String(y.min):"",w=typeof y.max=="number"||typeof y.max=="string"?String(y.max):"",q=(C,k)=>a({min:C===""?void 0:Number(C),max:k===""?void 0:Number(k)});return e.jsxs("label",{className:"dql-app-filter-select dql-app-filter-range",title:i,"aria-label":i,children:[e.jsx("span",{className:"dql-app-filter-icon",children:rr(t)}),e.jsx("input",{type:"number",value:u,"aria-label":`${i} minimum`,placeholder:"Min",onChange:C=>q(C.target.value,w)}),e.jsx("span",{className:"dql-app-filter-range-sep",children:"–"}),e.jsx("input",{type:"number",value:w,"aria-label":`${i} maximum`,placeholder:"Max",onChange:C=>q(u,C.target.value)})]})}return e.jsxs("label",{className:"dql-app-filter-select",title:t.bindsTo?`${i} -> ${t.bindsTo}`:i,"aria-label":i,children:[e.jsx("span",{className:"dql-app-filter-icon",children:rr(t)}),e.jsx("input",{type:t.type==="number"?"number":t.type==="date"?"date":"text",value:s,placeholder:i,onChange:y=>a(y.target.value)})]})}function rr(t){return t.type==="date"||t.type==="daterange"||/season|year|date|time|period/i.test(t.id)?e.jsx(Ss,{size:13}):e.jsx(sn,{size:13})}function ui(t){var a;return((a=t.options)!=null&&a.length?t.options:[t.default].filter(i=>i!==void 0)).map(i=>[String(i),Oe(String(i))])}function $r(t){var r,a;return t.default!==void 0?t.default:t.type==="number"?vn(t.id):t.type==="boolean"?!1:t.type==="select"?((r=t.options)==null?void 0:r[0])??"":t.type==="multiselect"?[]:t.type==="number_range"?{min:void 0,max:void 0}:t.type==="relative_date"?((a=t.options)==null?void 0:a[0])??"last_30_days":""}function Ol(t,r){return r==null?String($r(t)??""):(t.type==="daterange"||t.type==="number_range"||t.type==="multiselect")&&typeof r=="object"?JSON.stringify(r):String(r)}function Wl(t,r){if(t.type==="number"){if(typeof r=="string"&&r.trim()==="")return"";const a=Number(r);return Number.isFinite(a)?a:r}if(t.type==="boolean")return r===!0||r==="true";if(t.type==="multiselect")return Array.isArray(r)?r.map(String):[];if(t.type==="select"&&typeof t.default=="number"){const a=Number(r);return Number.isFinite(a)?a:r}return r}function xi(t,r){const a=Object.keys(t),i=Object.keys(r);return a.length!==i.length?!1:a.every(s=>Object.is(t[s],r[s]))}function Yr({label:t,icon:r,value:a,options:i,onChange:s}){return e.jsxs("label",{className:"dql-app-filter-select",title:t,"aria-label":t,children:[r?e.jsx("span",{className:"dql-app-filter-icon",children:r}):e.jsx("span",{children:t}),e.jsx("select",{value:a,onChange:n=>s(n.target.value),children:i.map(([n,o])=>e.jsx("option",{value:n,children:o},n))})]})}const Hl=new Set(["table",...Zi.map(t=>t.value)]);function Ha(t){const r=String(t??"table").toLowerCase().replace(/_/g,"-");return r==="single-value"?"kpi":Hl.has(r)?r:"table"}function Va(t,r){const a=t.viz.options??{},i=a,s=typeof a.valueField=="string"?a.valueField:typeof a.field=="string"?a.field:void 0;return{...r??{},...i,chart:Ha(i.chart??t.viz.type??(r==null?void 0:r.chart)),y:i.y??s??(r==null?void 0:r.y),title:i.title??(r==null?void 0:r.title)??t.title,colorPalette:i.colorPalette??(r==null?void 0:r.colorPalette)??"corporate"}}function Vl(t,r){if(!r||t.rows.length<=1||!t.columns.includes(r))return t;const a=t.rows.map(s=>s[r]).filter(s=>typeof s=="number"||typeof s=="string"&&s.trim()!=="").map(Number).filter(Number.isFinite);if(a.length===0)return t;const i=Number(a.reduce((s,n)=>s+n,0).toPrecision(15));return{...t,columns:[r],rows:[{[r]:i}],rowCount:1}}function Bt(t){return t.block?"blockId"in t.block?t.block.blockId??null:t.block.ref??null:null}function Kl(t){return Ha(t)}function aa(t){const r=Kl(t);return r==="table"?"table":r.replace(/-/g,"_")}function gi(t){const r={};for(const[a,i]of Object.entries(t))i===void 0||i===""||(r[a]=i);return r.chart||(r.chart="table"),r}function Wt(t){var a;if(Xr(t.display)){const i=t.display,s=typeof i.component=="string"?i.component:void 0;return{version:1,component:s,role:wn(s),layoutIntent:typeof i.layoutIntent=="string"?i.layoutIntent:void 0,defaultVisualization:typeof i.defaultVisualization=="string"?i.defaultVisualization:void 0,allowedVisualizations:Array.isArray(i.allowedVisualizations)?i.allowedVisualizations.filter(n=>typeof n=="string"):void 0,fieldHints:Xr(i.fieldHints)?Object.fromEntries(Object.entries(i.fieldHints).filter(n=>typeof n[1]=="string")):void 0,insightTitle:t.title,trustState:typeof i.trustState=="string"?i.trustState:void 0,reviewStatus:typeof i.reviewStatus=="string"?i.reviewStatus:void 0,rationale:typeof i.rationale=="string"?i.rationale:void 0}}const r=(a=t.viz.options)==null?void 0:a.dqlGenUi;return Xr(r)?{version:typeof r.version=="number"?r.version:void 0,component:typeof r.component=="string"?r.component:void 0,role:typeof r.role=="string"?r.role:void 0,layoutIntent:typeof r.layoutIntent=="string"?r.layoutIntent:void 0,defaultVisualization:typeof r.defaultVisualization=="string"?r.defaultVisualization:void 0,allowedVisualizations:Array.isArray(r.allowedVisualizations)?r.allowedVisualizations.filter(i=>typeof i=="string"):void 0,fieldHints:Xr(r.fieldHints)?Object.fromEntries(Object.entries(r.fieldHints).filter(i=>typeof i[1]=="string")):void 0,insightTitle:typeof r.insightTitle=="string"?r.insightTitle:void 0,trustState:typeof r.trustState=="string"?r.trustState:void 0,reviewStatus:typeof r.reviewStatus=="string"?r.reviewStatus:void 0,sourceNodeId:typeof r.sourceNodeId=="string"?r.sourceNodeId:void 0,followUpActions:Array.isArray(r.followUpActions)?r.followUpActions.filter(i=>typeof i=="string"):void 0,rationale:typeof r.rationale=="string"?r.rationale:void 0}:null}function fi(t,r){return{mode:"manual",component:t==="heading"?"NarrativePanel":"BusinessBrief",defaultVisualization:t,allowedVisualizations:[t],layoutIntent:t==="heading"?"wide":"standard",rationale:r?`Manual narrative tile for "${r}" on this app surface.`:"Manual narrative tile for this app surface.",trustState:"review_required",reviewStatus:"review_required"}}function yn(t,r,a){var n,o,l,d,x,b,m,f,y;const i=Ql([r,...((n=t.display)==null?void 0:n.allowedVisualizations)??[],...(a==null?void 0:a.allowedVisualizations)??[]]),s=((o=t.display)==null?void 0:o.component)??Gl(r);return{mode:((l=t.display)==null?void 0:l.mode)??(a?"ai_generated":t.block?"block_hint":"manual"),component:s,defaultVisualization:r,allowedVisualizations:i.length?i:[r],...(d=t.display)!=null&&d.fieldHints||a!=null&&a.fieldHints?{fieldHints:((x=t.display)==null?void 0:x.fieldHints)??(a==null?void 0:a.fieldHints)}:{},layoutIntent:Yl(((b=t.display)==null?void 0:b.layoutIntent)??(a==null?void 0:a.layoutIntent)),rationale:((m=t.display)==null?void 0:m.rationale)??(a==null?void 0:a.rationale)??"Visualization selected for this consumer surface.",trustState:Ka(((f=t.display)==null?void 0:f.trustState)??(a==null?void 0:a.trustState)),reviewStatus:Xl(((y=t.display)==null?void 0:y.reviewStatus)??(a==null?void 0:a.reviewStatus))}}function Ql(t){return Array.from(new Set(t.filter(r=>typeof r=="string"&&r.trim()).map(r=>r.trim())))}function Gl(t){return t==="single_value"||t==="kpi"||t==="gauge"?"KpiMetric":t==="line"||t==="area"?"TrendPanel":t==="bar"||t==="grouped_bar"||t==="stacked_bar"||t==="donut"||t==="pie"?"RankingPanel":t==="pivot"?"PivotTable":t==="text"||t==="heading"?"NarrativePanel":"EvidenceTable"}function wn(t){return t==="BusinessBrief"?"business_summary":t==="KpiMetric"?"kpi":t==="TrendPanel"?"trend":t==="RankingPanel"?"breakdown":t==="TrustCallout"?"trust":t==="ResearchActions"?"research":t==="NarrativePanel"?"narrative":t?"evidence":void 0}function Yl(t){return t==="compact"||t==="standard"||t==="wide"||t==="tall"||t==="full"||t==="auto"?t:"auto"}function Ka(t){return t==="certified"||t==="draft_ready"||t==="review_required"?t:"review_required"}function Xl(t){return t==="certified"||t==="draft_ready"||t==="review_required"?t:"review_required"}function Xr(t){return typeof t=="object"&&t!==null&&!Array.isArray(t)}function Fr(t){const r=(t??"table").toLowerCase().replace(/-/g,"_");return r==="single_value"||r==="kpi"||r==="gauge"||r==="line"||r==="bar"||r==="area"||r==="pie"||r==="donut"||r==="grouped_bar"||r==="stacked_bar"||r==="scatter"||r==="heatmap"||r==="histogram"||r==="waterfall"||r==="pivot"||r==="map"||r==="funnel"||r==="sankey"||r==="heading"||r==="text"?r:"table"}const qn=[{id:"auto",label:"Auto fit",description:"Choose a practical size from the tile content"},{id:"compact",label:"Compact",description:"Small KPI or short summary"},{id:"standard",label:"Standard",description:"Default chart or table card"},{id:"wide",label:"Wide",description:"Full-row trend or comparison"},{id:"tall",label:"Tall",description:"More vertical room for tables and dense charts"},{id:"full",label:"Full page",description:"Large focused view across the page"}];function Qa(t,r){const a=Fr(t);return a==="heading"?Et("wide",r,"heading"):a==="text"?Et("standard",r,"text"):Et(a==="single_value"||a==="kpi"||a==="gauge"?"compact":a==="table"||a==="pivot"?"tall":a==="line"||a==="area"?"wide":"standard",r,a)}function Ga(t,r){const a=Wt(t),i=Dl(a==null?void 0:a.layoutIntent);return i&&i!=="auto"?Et(i,r,String(t.viz.type??"table")):Qa(Fr(String(t.viz.type??"table")),r)}function Jl(t,r){return t.viz.type==="heading"?90:(r==null?void 0:r.component)==="BusinessBrief"||(r==null?void 0:r.component)==="NarrativePanel"||t.viz.type==="text"?180:(r==null?void 0:r.component)==="TrustCallout"||(r==null?void 0:r.component)==="ResearchActions"?210:(r==null?void 0:r.component)==="EvidenceTable"||(r==null?void 0:r.component)==="PivotTable"?330:(r==null?void 0:r.component)==="KpiMetric"?150:Math.max(280,Math.min(420,t.h*76))}function Et(t,r,a="table"){const i=Math.max(1,r),s=Math.max(1,Math.ceil(i/2)),n=Math.max(1,Math.ceil(i/3));return t==="auto"?Qa(a,i):t==="compact"?{w:n,h:2}:t==="wide"?{w:i,h:a==="heading"?1:4}:t==="tall"?{w:s,h:6}:t==="full"?{w:i,h:7}:{w:s,h:a==="text"?2:4}}function jn(t,r,a){const i=String(t.viz.type??"table"),s=a==="auto"?Ga(t,r):Et(a,r,i);return{w:s.w,h:s.h,x:ia(t.x,0,Math.max(0,r-s.w))}}function Zl(t,r,a){const i=a==="auto"?Ga(t,r):Et(a,r,String(t.viz.type??"table"));return t.w===i.w&&t.h===i.h}function Dl(t){return t==="auto"||t==="compact"||t==="standard"||t==="wide"||t==="tall"||t==="full"?t:null}function ia(t,r,a){return Math.min(a,Math.max(r,t))}function na(t,r){const a=Math.max(1,r),i=[],s=(o,l,d,x)=>{for(let b=0;b<x;b++){const m=i[l+b];if(m){for(let f=0;f<d;f++)if(m[o+f])return!1}}return!0},n=(o,l,d,x)=>{for(let b=0;b<x;b++){const m=l+b;i[m]||(i[m]=new Array(a).fill(!1));for(let f=0;f<d;f++)i[m][o+f]=!0}};return t.map(o=>{const l=ia(Math.round(o.w||1),1,a),d=Math.max(1,Math.round(o.h||1));let x=0,b=0;e:for(let m=0;;m++)for(let f=0;f+l<=a;f++)if(s(f,m,l,d)){x=f,b=m;break e}return n(x,b,l,d),{...o,x,y:b,w:l,h:d}})}function Ul(t,r){const a=[...t].map((i,s)=>({item:i,index:s})).sort((i,s)=>{const n=Aa(i.item)-Aa(s.item);return n!==0?n:i.index-s.index}).map(({item:i})=>{const s=Ga(i,r);return{...i,w:s.w,h:s.h}});return na(a,r)}function ed(t,r,a){const i=t.filter(o=>o.i!==r.i).sort((o,l)=>or(o,a)-or(l,a)),s=or(r,a),n=i.findIndex(o=>or(o,a)>s);return n===-1?[...i,r]:[...i.slice(0,n),r,...i.slice(n)]}function or(t,r){return t.y*r+t.x}function Aa(t){const r=Wt(t);if((r==null?void 0:r.role)==="business_summary")return 0;if((r==null?void 0:r.role)==="kpi")return 1;if((r==null?void 0:r.component)==="RankingPanel"||(r==null?void 0:r.component)==="TrendPanel")return 2;if((r==null?void 0:r.component)==="EvidenceTable"||(r==null?void 0:r.component)==="PivotTable")return 3;if((r==null?void 0:r.component)==="TrustCallout"||(r==null?void 0:r.component)==="ResearchActions")return 4;if((r==null?void 0:r.role)==="narrative")return 5;const a=Fr(String(t.viz.type??"table"));return a==="heading"?0:a==="single_value"||a==="kpi"||a==="gauge"?1:a==="line"||a==="area"||a==="bar"||a==="pie"||a==="funnel"||a==="map"?2:a==="table"||a==="pivot"?3:a==="text"?4:2}function It(t,r,a=[],i={}){if(r==null||r==="")return"N/A";const s=xs(t,r,a,i);return s?typeof r=="string"&&s===r?s.replace(/_/g," "):s:"N/A"}function St(t){return t.replace(/[_-]+/g," ").replace(/\b\w/g,r=>r.toUpperCase())}function wr(t,r){const a=r.slice(0,8).map(i=>i[t]).filter(i=>i!=null&&i!=="");return a.length===0?!1:a.every(i=>typeof i=="number"||typeof i=="string"&&i.trim()!==""&&Number.isFinite(Number(i)))}function td(t){return t.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function rd(t,r,a){if(t.length===0)return;const i=a==null?void 0:a.toLowerCase();if(i){const s=t.find(n=>{const o=n.toLowerCase();return o===i||o.includes(i)||i.includes(o)});if(s)return s}return t.find(s=>/\b(name|label|title|dataset|table|block|player|customer|account)\b/i.test(s))??t.find(s=>!wr(s,r))??t[0]}function fa(t){const r=t.toLowerCase();return/(total|count|records|rows|volume)/.test(r)?1:/(rate|percent|pct|score|quality|freshness)/.test(r)?2:/(amount|revenue|arr|value)/.test(r)?3:/(date|time|season)/.test(r)?6:/(^|_)id($|_)/.test(r)?20:100}function kn(t,r){return new Map(t.map(a=>[a,r.slice(0,32).map(i=>i[a])]))}function ad(t){var o,l,d,x;if(Bt(t)||t.aiPin)return!1;const r=Wt(t),a=(r==null?void 0:r.component)??((o=t.display)==null?void 0:o.component),i=(r==null?void 0:r.role)??wn(a),s=Ka(String((r==null?void 0:r.trustState)??((l=t.display)==null?void 0:l.trustState)??"review_required"));if(a==="TrustCallout"||a==="ResearchActions"||i==="trust"||i==="research")return!0;if(a!=="NarrativePanel"&&a!=="BusinessBrief"||s==="certified")return!1;const n=[t.title,(d=t.text)==null?void 0:d.markdown,(x=t.display)==null?void 0:x.rationale,r==null?void 0:r.rationale,r==null?void 0:r.insightTitle].filter(Boolean).join(" ").toLowerCase();return/\b(draft ready|review-required|review required|missing evidence|missing proof|trust gap|research drilldown|promote to a certified block|generated review placeholder|generated section)\b/.test(n)}function id(t,r,a){const s=[...t.filter(n=>!nd(n,r.get(n.i))&&!ld(n,t,r)&&!sd(n,t,r))].sort((n,o)=>{const l=hi(o,r.get(o.i),a)-hi(n,r.get(n.i),a);return l!==0?l:or(n,a)-or(o,a)});return na(s,a)}function nd(t,r){var s,n;if(!t.aiPin)return!1;const a=(s=r==null?void 0:r.aiPin)==null?void 0:s.certification,i=(n=r==null?void 0:r.aiPin)==null?void 0:n.reviewStatus;return a!=="certified"&&i!=="certified"}function sd(t,r,a){if(!t.aiPin)return!1;const i=mi(t,a.get(t.i));if(!i)return!1;const s=r.findIndex(n=>n.i===t.i);return r.some((n,o)=>n.i===t.i||o>=s||!n.aiPin?!1:mi(n,a.get(n.i))===i)}function mi(t,r){const a=r==null?void 0:r.aiPin,i=a!=null&&a.analysisPlan&&typeof a.analysisPlan=="object"?a.analysisPlan:null,s=Jr(a==null?void 0:a.question)||Jr(t.title),n=Jr(i==null?void 0:i.sourceBlockId),o=Jr(i==null?void 0:i.sourceTileId),l=a!=null&&a.result?od(a.result):"";return!s&&!n&&!o?"":[s,n,o,l].filter(Boolean).join("|")}function Jr(t){return String(t??"").toLowerCase().replace(/[^a-z0-9]+/g," ").replace(/\s+/g," ").trim()}function od(t){if(!t||typeof t!="object")return"";const r=t,a=Array.isArray(r.columns)?r.columns.map(s=>String(s).toLowerCase()).join(","):"",i=Array.isArray(r.rows)?r.rows.slice(0,8).map(s=>Ia(s)).join(";"):"";return a||i?`${a}:${i}`:""}function Ia(t){if(t==null)return"";if(typeof t!="object")return String(t);if(Array.isArray(t))return`[${t.map(Ia).join(",")}]`;const r=t;return`{${Object.keys(r).sort().map(a=>`${a}:${Ia(r[a])}`).join(",")}}`}function hi(t,r,a){var s,n,o,l,d;let i=0;return(s=t.parameterBindings)!=null&&s.length&&(i+=5e3),(o=(n=r==null?void 0:r.filters)==null?void 0:n.applied)!=null&&o.length&&(i+=4e3),(r==null?void 0:r.certificationStatus)==="certified"&&(i+=1800),Bt(t)&&(i+=900),(r==null?void 0:r.status)==="ok"&&((d=(l=r.result)==null?void 0:l.rows)!=null&&d.length)&&(i+=500),i-=Aa(t)*80,i-=or(t,a)/1e3,i}function ld(t,r,a){var n;if((n=t.parameterBindings)!=null&&n.length||t.aiPin||!Bt(t))return!1;const i=a.get(t.i),s=i!=null&&i.result?bi(i.result):null;return s?r.some(o=>{if(o.i===t.i||!dd(o,a.get(o.i)))return!1;const l=a.get(o.i),d=l!=null&&l.result?bi(l.result):null;return!!(d&&pd(s,d))}):!1}function dd(t,r){var a,i,s;return!!((a=t.parameterBindings)!=null&&a.length||(s=(i=r==null?void 0:r.filters)==null?void 0:i.applied)!=null&&s.length)}function bi(t){var o;const r=t.rows??[];if(!r.length)return null;const a=(o=t.columns)!=null&&o.length?t.columns:Object.keys(r[0]??{});if(!a.length)return null;const i=Ya(a,r),s=Xa(a,r),n=r[0];return{columns:a.map(l=>l.toLowerCase()).sort().join("|"),label:i?vi(n[i]):"",metric:(s==null?void 0:s.toLowerCase())??"",metricValue:s?vi(n[s]):""}}function pd(t,r){return t.columns===r.columns&&t.label===r.label&&t.metric===r.metric&&t.metricValue===r.metricValue}function vi(t){return t==null?"":typeof t=="number"?Number.isFinite(t)?String(t):"":String(t).trim().toLowerCase().replace(/\s+/g," ")}function cd(t,r,a){var _,A,te,Q;const i=t.map((Y,S)=>({item:Y,tile:r.get(Y.i),index:S})).filter(Y=>{var S,h;return((S=Y.tile)==null?void 0:S.status)==="ok"&&!!Y.tile.result&&Array.isArray((h=Y.tile.result)==null?void 0:h.rows)&&Y.tile.result.rows.length>0}).sort((Y,S)=>{const h=yi(Y.item,Y.tile,Y.index);return yi(S.item,S.tile,S.index)-h})[0];if(!(i!=null&&i.tile.result))return null;const s=i.tile.result,n=s.rows,o=s.columns??Object.keys(n[0]??{});if(!o.length)return null;const l=Wt(i.item),d=Ya(o,n,(_=l==null?void 0:l.fieldHints)==null?void 0:_.label),x=Xa(o,n,((A=l==null?void 0:l.fieldHints)==null?void 0:A.value)??((te=l==null?void 0:l.fieldHints)==null?void 0:te.y)),b=n[0],m=n[1],f=d?n.map(Y=>Y[d]):[],y=x?n.map(Y=>Y[x]):[],u=d?It(d,b[d],f):"The leading result",w=m&&d?It(d,m[d],f):null,q=x?ji(b[x]):null,C=x&&m?ji(m[x]):null,k=x?ud(x):null,M=xd(a),L=M.length?"under the selected app filters":"in the current dashboard view",X=i.item.title??i.tile.title??Bt(i.item)??"Dashboard result",I=s.rowCount??n.length,O=i.tile.certificationStatus==="certified"?"certified":Ka(String(((Q=i.item.display)==null?void 0:Q.trustState)??(l==null?void 0:l.trustState)??"review_required")),F=k?`${St(k)} snapshot`:"Dashboard snapshot";let U;if(x&&k&&q!==null){const Y=`${u} leads ${k} with ${It(x,q,y,{compact:!0})}`;if(w&&C!==null&&Number.isFinite(q-C)){const S=Math.abs(q-C);U=`${Y}, ahead of ${w} by ${It(x,S,y,{compact:!0})} ${L}.`}else U=`${Y} ${L}.`}else U=`${X} returned ${I} ${I===1?"row":"rows"} ${L}.`;return{title:F,summary:U,sourceTitle:X,trust:O,filters:M,chips:[`${I} ${I===1?"row":"rows"}`,o.length?`${o.length} fields`:""].filter(Boolean)}}function yi(t,r,a){var l,d,x,b;const i=Wt(t),s=(i==null?void 0:i.component)??((l=t.display)==null?void 0:l.component),n=r.result;let o=1e3-a;return r.certificationStatus==="certified"&&(o+=500),Bt(t)&&(o+=180),(x=(d=r.filters)==null?void 0:d.applied)!=null&&x.length&&(o+=260),(b=t.parameterBindings)!=null&&b.length&&(o+=220),(s==="RankingPanel"||s==="EvidenceTable"||s==="KpiMetric")&&(o+=120),(t.viz.type==="table"||t.viz.type==="bar"||t.viz.type==="kpi")&&(o+=70),n&&Xa(n.columns,n.rows)&&(o+=80),n&&Ya(n.columns,n.rows)&&(o+=50),o}function Ya(t,r,a){const i=Sn(t,a);return i||(t.find(s=>/\b(player|customer|account|team|segment|category|name|label|title|entity)\b/i.test(s))??t.find(s=>!wr(s,r)&&!/\b(date|time|year|month|id)\b/i.test(s))??t.find(s=>!wr(s,r)))}function Xa(t,r,a){const i=Sn(t,a);return i&&wr(i,r)?i:t.filter(s=>wr(s,r)).sort((s,n)=>wi(s)-wi(n))[0]}function Sn(t,r){const a=r==null?void 0:r.toLowerCase().trim();if(a)return t.find(i=>{const s=i.toLowerCase();return s===a||s.includes(a)||a.includes(s)})}function wi(t){const r=t.toLowerCase();return/(total|revenue|amount|points|score|value|sales|arr|mrr)/.test(r)?1:/(count|orders|games|customers|rows|volume)/.test(r)?2:/(rate|pct|percent|ratio|margin|average|avg)/.test(r)?3:/(rank|position|index)/.test(r)?20:/(date|year|month|day|week|id)/.test(r)?90:30}function ud(t){return St(t).toLowerCase()}function xd(t){return Object.entries(t).filter(([r,a])=>/^(smartView|persona|dashboardId|appId)$/i.test(r)||r.startsWith("__")||a==null||a===""||Array.isArray(a)&&a.length===0?!1:typeof a!="object"||Array.isArray(a)).slice(0,6).map(([r,a])=>({label:St(r),value:Array.isArray(a)?a.map(i=>qi(r,i)).join(", "):qi(r,a)}))}function qi(t,r){const a=typeof r=="number"?r:typeof r=="string"&&r.trim()!==""?Number(r):NaN;return/(season|year)/i.test(t)&&Number.isInteger(a)&&a>=1900&&a<=2200?String(a):It(t,r,[r])}function ji(t){if(typeof t=="number"&&Number.isFinite(t))return t;if(typeof t=="string"&&t.trim()!==""){const r=Number(t);return Number.isFinite(r)?r:null}return null}function lr(t){return Ha(t)}const gd=p.lazy(()=>oa(()=>import("./UnifiedAgentRunPanel-BjsTE6yf.js").then(t=>t.c),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14])).then(t=>({default:t.UnifiedAgentRunPanel}))),fd="clamp(320px, calc(100vh - 220px), 760px)",zn=[{value:"table",label:"Table"},...Zi];function md(t,r){if(!Array.isArray(t)||t.length===0)return;const a=Array.isArray(r)&&r.length>0?r.slice(0,8):Object.keys(t[0]??{}).slice(0,8);return t.slice(0,5).map(i=>Object.fromEntries(a.map(s=>[s,i[s]])))}function hd({appId:t,dashboard:r,variables:a,editable:i=!1,embeddedHeader:s=!1,onDashboardChanged:n,selectedBlockId:o,onBlockFocus:l,onAskBlock:d,onOpenLineageNode:x,copilotOpen:b,onCopilotChange:m,onRunChange:f}){var Nt;const{state:y}=Ki(),u=Ht[y.themeMode],[w,q]=p.useState(null),[C,k]=p.useState(null),M=p.useRef(null),[L,X]=p.useState(!1),I=p.useRef(0),[O,F]=p.useState(null),[U,_]=p.useState(!1),A=Ba(`app:${t}:${r.id}`),[te,Q]=p.useState(!1),[Y,S]=p.useState([]),[h,$]=p.useState(""),[ee,W]=p.useState(!1),[$e,se]=p.useState(null),[oe,Be]=p.useState(!1),[ue,Ae]=p.useState(null),[_e,Ie]=p.useState(null),[xe,Ze]=p.useState(null),[it,R]=p.useState(!1),[le,ge]=p.useState(!1),[ve,Te]=p.useState(null),[de,Pe]=p.useState(""),[Ge,Ye]=p.useState(null),De=p.useRef(null),Ee=p.useRef(null),[ze,Z]=p.useState(1120),pe=ze<720?"narrow":ze<1120?"medium":"wide",ye=r.layout.responsive,Ne=ys(),We=p.useMemo(()=>JSON.stringify(a??{}),[a]),Me=p.useMemo(()=>JSON.parse(We),[We]),Ue=p.useMemo(()=>{const N=new Map;for(const B of(w==null?void 0:w.tiles)??[])N.set(B.tileId,B);return N},[w]),we=ue??r.layout.items,nt=p.useMemo(()=>{const N=ye==null?void 0:ye[pe],B=pe==="wide"?{kind:"grid",cols:r.layout.cols,rowHeight:r.layout.rowHeight,items:we}:N??{kind:"grid",cols:pe==="medium"?6:1,rowHeight:r.layout.rowHeight,items:Ap(we,pe==="medium"?6:1)},g=new Map(we.map(K=>[K.i,K]));return{...B,items:B.items.map(K=>({...g.get(K.i),...K}))}},[pe,r.layout.cols,r.layout.rowHeight,ye,we]),Le=pe==="narrow",re=nt.cols,lt=nt.rowHeight,Ce=i&&pe==="wide",bt=p.useMemo(()=>({...r,layout:{...r.layout,items:we}}),[r,we]),ie=p.useMemo(()=>i?nt.items:nt.items.filter(N=>!ad(N)),[nt.items,i]),dt=p.useMemo(()=>i?ie:id(ie,Ue,re),[ie,re,i,Ue]),He=r.layout.items.length-ie.length,et=ie.length-dt.length,Re=p.useMemo(()=>!i&&!r.story&&r.sections&&r.sections.length>0?[...r.sections].sort((N,B)=>N.order-B.order):null,[r.sections,r.story,i]),gt=p.useMemo(()=>Re?nt.items:null,[nt.items,Re]),H=p.useMemo(()=>i||Re?null:cd(dt,Ue,Me),[i,Me,Re,Ue,dt]);p.useEffect(()=>{Ae(null),Ie(null)},[r.id]),p.useEffect(()=>{const N=I.current+1;I.current=N;const B=()=>I.current===N;X(!0),F(null),D.runDashboard(t,r.id,Me).then(g=>{B()&&(q(g),k((g==null?void 0:g.story)??null),M.current=(g==null?void 0:g.runId)??null,f==null||f(g),g||F("Dashboard run failed."),g!=null&&g.runId&&D.getDashboardStory(t,r.id,g.runId).then(K=>{!B()||!K||M.current!==K.runId||K.snapshotId!==g.snapshotId||K.filterFingerprint!==g.filterFingerprint||K.resultFingerprint!==g.resultFingerprint||K.personaFingerprint!==g.personaFingerprint||k(K.story)}))}).catch(g=>{B()&&(F(g instanceof Error?g.message:String(g)),f==null||f(null))}).finally(()=>{B()&&X(!1)})},[t,r.id,r.layout.items.length,f,Me,(Nt=y.activePersona)==null?void 0:Nt.userId]),p.useEffect(()=>{const N=B=>{const g=B.detail;(g==null?void 0:g.appId)!==t||g.dashboardId!==r.id||(D.getDashboard(t,r.id).then(K=>{K!=null&&K.dashboard&&(n==null||n(K.dashboard))}),D.runDashboard(t,r.id,Me).then(K=>{K&&(q(K),k(K.story),M.current=K.runId,f==null||f(K))}))};return window.addEventListener("dql-app-dashboard-updated",N),()=>window.removeEventListener("dql-app-dashboard-updated",N)},[t,r.id,n,f,Me]),p.useEffect(()=>{const N=De.current;if(!N)return;const B=()=>Z(N.getBoundingClientRect().width);B();const g=new ResizeObserver(B);return g.observe(N),()=>g.disconnect()},[]);const ke=p.useMemo(()=>{const N=r.layout.items.map(B=>{var me,rt,Ve,yt,Xe;const g=Ue.get(B.i),K=B.block?"blockId"in B.block?B.block.blockId:B.block.ref:B.semantic?`semantic:${B.semantic.id}`:B.draftAnalysis?`draft:${B.draftAnalysis.ref}`:B.aiPin?`aiPin:${B.aiPin.id}`:"text";return{title:B.title,blockRef:K,viz:B.viz.type,certificationStatus:g==null?void 0:g.certificationStatus,status:g==null?void 0:g.status,rowCount:(me=g==null?void 0:g.result)==null?void 0:me.rowCount,columns:(Ve=(rt=g==null?void 0:g.result)==null?void 0:rt.columns)==null?void 0:Ve.slice(0,8),sampleRows:md((yt=g==null?void 0:g.result)==null?void 0:yt.rows,(Xe=g==null?void 0:g.result)==null?void 0:Xe.columns)}});return JSON.stringify({scope:"dashboard",appId:t,dashboardId:r.id,title:r.metadata.title,description:r.metadata.description,domain:r.metadata.domain,filters:r.filters,variables:Me,run:w?{runId:w.runId,snapshotId:w.snapshotId,filterFingerprint:w.filterFingerprint,resultFingerprint:w.resultFingerprint,personaFingerprint:w.personaFingerprint,story:w.story,facts:w.facts}:null,tiles:N},null,2)},[t,r,w,Me,Ue]),fe=p.useCallback(async(N,B="Changes saved")=>{Be(!0),F(null);const g={...r,layout:{...r.layout,items:N}};try{const K=await D.patchDashboardLayout(t,r.id,g.layout);K.ok?(Ae(null),Ie(B),n==null||n(K.dashboard)):F(K.error)}finally{Be(!1)}},[t,r,n]),qe=p.useCallback(async(N,B="geometry")=>{if(ue&&B==="geometry"){Ae(N),Ie("Layout preview ready");return}ue&&Ae(N),await fe(N)},[ue,fe]),zt=p.useCallback(async()=>{Q(!0);const N=await D.getAppEditorCatalog(t);S((N==null?void 0:N.blocks)??[])},[t]),vt=p.useCallback(async N=>{const B=Fr(N.chartType),g=await D.recommendDashboardTile(t,r.id,{blockRef:N.name,appAudience:r.metadata.audience,prompt:`${r.metadata.title} ${N.name} ${N.description}`,defaultVisualization:B}),K=Qa(B,re),me={i:ha(bt,N.name),...ma(bt,K),block:{blockId:N.name},viz:{type:B},...g.ok?{display:g.display,filterBindings:"filterBindings"in g?g.filterBindings:void 0,parameterBindings:"parameterBindings"in g?g.parameterBindings:void 0,sourceEvidence:"sourceEvidence"in g?g.sourceEvidence:void 0,trustState:"trustState"in g?g.trustState:g.display.trustState,reviewStatus:"reviewStatus"in g?g.reviewStatus:g.display.reviewStatus}:{},title:N.name};await qe([...we,me],"content"),Q(!1)},[t,re,r.id,r.metadata.audience,r.metadata.title,qe,bt,we]),Vt=p.useCallback(async()=>{Te("text"),Pe("")},[]),Dt=p.useCallback(async()=>{Te("heading"),Pe("")},[]),Ut=p.useCallback(async()=>{var B;const N=de.trim();if(!(!N||!ve)){if(ve==="heading")await qe([...we,{i:ha(bt,"section"),...ma(bt,Et("wide",re,"heading")),text:{markdown:N},viz:{type:"heading"},display:fi("heading",N),title:N}],"content");else{const g=((B=N.split(/\r?\n/)[0])==null?void 0:B.slice(0,60))||"Summary";await qe([...we,{i:ha(bt,"text"),...ma(bt,Et("standard",re,"text")),text:{markdown:N},viz:{type:"text"},display:fi("text",g),title:g}])}Te(null),Pe("")}},[re,qe,ve,de,bt,we]),pr=p.useCallback(async(N,B)=>{const g=B===null?we.filter(me=>me.i!==N):we.map(me=>me.i===N?{...me,...B}:me),K=B!==null&&Object.keys(B).every(me=>me==="x"||me==="y"||me==="w"||me==="h");await qe(na(g,re),K?"geometry":"content")},[re,qe,we]),pt=p.useCallback(async(N,B)=>{const g=Ee.current,K=we.find(Mt=>Mt.i===N);if(!g||!K)return;const me=g.getBoundingClientRect(),rt=12,yt=(me.width-rt*(re-1))/re+rt,Xe=lt+rt,je=Math.round((B.clientX-me.left)/yt),wt=Math.round((B.clientY-me.top)/Xe),gr={...K,x:ia(je,0,Math.max(0,re-K.w)),y:Math.max(0,wt)};Ye(null);const ut=ed(we,gr,re);await qe(na(ut,re))},[re,lt,qe,we]),_t=p.useCallback((N,B)=>{const g=Ee.current,K=we.find(je=>je.i===N);if(!g||!K)return;const me=g.getBoundingClientRect(),rt=12,Ve=(me.width-rt*(re-1))/re,yt=Math.round((B.clientX-me.left)/(Ve+rt)),Xe=Math.round((B.clientY-me.top)/(lt+rt));Ye({tileId:N,x:ia(yt,0,Math.max(0,re-K.w)),y:Math.max(0,Xe),w:K.w,h:K.h})},[re,lt,we]),st=p.useCallback(()=>Ye(null),[]),Kt=p.useCallback(()=>{we.length!==0&&(Ae(Ul(we,re)),Ie("Layout preview ready"))},[re,we]),Qt=p.useCallback(async()=>{ue&&await fe(ue,"Layout applied")},[ue,fe]),cr=p.useCallback(()=>{Ae(null),Ie("Layout preview cancelled")},[]),er=p.useCallback(async N=>{Ze(N);const B=await D.retryDashboardTile(t,r.id,N,Me);Ze(null);const g=B==null?void 0:B.tiles.find(me=>me.tileId===N);if(!B||!g){F("This App tile could not be retried.");return}const K=w?{...w,tiles:w.tiles.map(me=>me.tileId===N?g:me)}:B;q(K),k(null),f==null||f(K)},[t,r.id,f,w,Me]),ur=p.useCallback(async(N,B)=>{const g=B.artifact,K={title:N.title??(g==null?void 0:g.name)??B.title??"App analysis",sql:g==null?void 0:g.sql,result:B.result,chartConfig:Va(N,B.chartConfig),sourceRunId:w==null?void 0:w.runId,question:`App tile: ${N.title??B.title??N.i}`,executionTarget:g==null?void 0:g.executionTarget,...g!=null&&g.dql?{dqlArtifact:{kind:g.sourceKind==="certified_block"?"certified_block":"sql_block",source:g.dql,name:g.name,sourcePath:g.sourcePath,persistence:g.sourcePath?"saved":"transient",trustState:g.trustState,compiledSql:g.sql}}:{}};await Ne(K)},[Ne,w==null?void 0:w.runId]),xr=p.useCallback(async()=>{if(W(N=>!N),!$e){const N=await D.fetchScopedLineage({domain:r.metadata.domain,appId:t,dashboardId:r.id});se(N)}},[t,r.id,r.metadata.domain,$e]),Gt=p.useCallback(()=>{if(x){x(`dashboard:${t}/${r.id}`);return}xr()},[t,r.id,xr,x]),Yt=m?!!b:U,ct=p.useCallback(()=>{if(R(!1),m){m(!0);return}_(!0)},[m]),ft=p.useCallback(()=>{if(R(!1),m){m(!b);return}_(N=>!N)},[b,m]);return e.jsxs("div",{ref:De,"data-dashboard-breakpoint":pe,style:{display:"block",minHeight:0,containerType:"inline-size"},children:[e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx(Vd,{saving:oe,error:O,pending:!!ue,notice:_e,onDismissError:()=>F(null)}),!i&&dt.length>0&&He+et>0?e.jsxs("div",{role:"status",style:Nr("var(--text-tertiary)"),children:[e.jsx(Qe,{size:13}),He+et," tile",He+et===1?" is":"s are"," hidden from this stakeholder view because ",He>0?"they still need review":"a certified tile already answers the same question",". Switch to Edit to see everything on this page."]}):null,(!s||i)&&e.jsxs("div",{style:Xd,children:[e.jsx("div",{style:{flex:1,minWidth:0},children:s?null:e.jsxs(e.Fragment,{children:[e.jsx("h2",{style:{margin:0,fontSize:20,lineHeight:1.18,fontWeight:780},children:r.metadata.title}),r.metadata.description?e.jsx("div",{style:{fontSize:13,opacity:.72,marginTop:4,maxWidth:680,lineHeight:1.4},children:r.metadata.description}):null]})}),i&&r.layout.items.length>0&&e.jsx(Ii,{open:it,onToggle:()=>R(N=>!N),buttonStyle:Yd,onCertifiedBlock:()=>{R(!1),zt()},onText:()=>{R(!1),Vt()},onHeading:()=>{R(!1),Dt()},onAi:ct}),i&&r.layout.items.length>1&&!ue&&e.jsxs("button",{type:"button",onClick:Kt,disabled:oe,style:Ot(!1),title:"Auto-arrange every tile into a clean, gap-free grid",children:[e.jsx(tn,{size:15,strokeWidth:2}),"Auto layout"]}),i&&ue?e.jsxs(e.Fragment,{children:[e.jsx("button",{type:"button",onClick:()=>void Qt(),disabled:oe,style:Ot(!0),children:oe?"Applying…":"Apply layout"}),e.jsx("button",{type:"button",onClick:cr,disabled:oe,style:Ot(!1),children:"Cancel"})]}):null,!s&&e.jsxs(e.Fragment,{children:[e.jsxs("button",{type:"button",onClick:ft,style:Ot(Yt),children:[e.jsx(nr,{size:14,strokeWidth:2}),Yt?"Hide copilot":"AI Copilot"]}),e.jsxs("button",{type:"button",onClick:Gt,style:Ot(!1),title:"Open focused dashboard lineage",children:[e.jsx(Qi,{size:14,strokeWidth:2}),"Lineage"]})]})]}),i&&e.jsx("div",{style:tp,children:Ce?"Drag tiles, select a block for Copilot context, or use the tile controls for sizing and chart settings.":`${pe==="medium"?"Tablet":"Mobile"} preview uses the saved responsive projection. Return to a wide canvas to rearrange tiles.`}),!i&&C?e.jsx(jd,{story:C,onResearch:ct,onEvidence:Gt}):H?e.jsx(qd,{story:H}):null,dt.length===0?e.jsxs("div",{style:{border:"1px dashed var(--border-color, rgba(0,0,0,0.15))",borderRadius:8,padding:36,textAlign:"center",fontSize:13,minHeight:260,display:"flex",flexDirection:"column",alignItems:"center",justifyContent:"center"},children:[e.jsx("div",{style:{fontSize:16,fontWeight:700,marginBottom:6},children:He>0||et>0?"No stakeholder-ready tiles yet":"Build this dashboard page"}),e.jsx("div",{style:{maxWidth:520,opacity:.68,lineHeight:1.45},children:He>0?"Generated analysis and trust placeholders are hidden from the stakeholder view. Open Customize or Analysis to review them, then add certified blocks or pinned insights.":et>0?"Static duplicate tiles are hidden from the stakeholder view because a filter-aware certified tile can answer the same question.":"Add certified domain blocks, narrative text, or use the scoped AI drawer and pin an answer into this layout."}),e.jsx("div",{style:{marginTop:18,display:"flex",gap:8,flexWrap:"wrap",justifyContent:"center"},children:e.jsx(Ii,{open:it,onToggle:()=>R(N=>!N),buttonLabel:"Add tile",buttonStyle:Bn,onCertifiedBlock:()=>{R(!1),zt()},onText:()=>{R(!1),Vt()},onHeading:()=>{R(!1),Dt()},onAi:ct})})]}):Re?e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:22},children:Re.map(N=>{var yt,Xe;const B=(yt=Re.find(je=>je.kind==="appendix"))==null?void 0:yt.id,g=((Xe=Re.find(je=>je.kind==="insight"))==null?void 0:Xe.id)??Re[0].id,K=je=>je.sectionId&&Re.some(wt=>wt.id===je.sectionId)?je.sectionId:(je.trustState==="review_required"||je.reviewStatus==="review_required")&&B?B:g,me=(gt??dt).filter(je=>K(je)===N.id);if(me.length===0)return null;const rt=Math.min(...me.map(je=>je.y)),Ve=N.kind==="appendix";return e.jsxs("section",{"aria-label":N.title,children:[N.kind!=="exec_summary"?e.jsxs("div",{style:{marginBottom:10},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[e.jsx("h3",{style:{margin:0,fontSize:15,fontWeight:800,color:"var(--dql-app-text, #0f172a)"},children:N.title}),Ve?e.jsx("span",{style:{display:"inline-flex",alignItems:"center",gap:4,border:"1px solid rgba(217,119,6,0.4)",color:"#b45309",background:"rgba(217,119,6,0.08)",borderRadius:999,padding:"1px 8px",fontSize:10,fontWeight:800},children:"needs review"}):null]}),N.narrative?e.jsx("p",{style:{margin:"4px 0 0",fontSize:12.5,lineHeight:1.5,color:"var(--dql-app-text-muted, #64748b)",maxWidth:860},children:N.narrative}):null]}):null,e.jsx("div",{style:{display:"grid",gridTemplateColumns:Le?"minmax(0, 1fr)":`repeat(${re}, 1fr)`,gridAutoRows:Le?"auto":`${lt}px`,gap:12,...Ve?{opacity:.96}:{}},children:me.map(je=>e.jsx(ki,{item:{...je,y:je.y-rt},tile:Ue.get(je.i),loading:L,error:O,themeMode:y.themeMode,editable:!1,narrow:Le,cols:re,selected:!!(Bt(je)&&Bt(je)===o),onFocusBlock:l,onAskBlock:d,onMove:()=>{},onDragMove:()=>{},onDragEnd:()=>{},onPatch:wt=>void pr(je.i,wt),onRetry:()=>void er(je.i),retrying:xe===je.i,retryDisabled:!!(xe&&xe!==je.i),onOpenNotebook:wt=>void ur(je,wt),activeVariables:Me},je.i))})]},N.id)})}):e.jsxs("div",{ref:Ee,style:{display:"grid",gridTemplateColumns:Le?"minmax(0, 1fr)":`repeat(${re}, 1fr)`,gridAutoRows:Le?"auto":`${lt}px`,gap:12},children:[Ge&&!Le&&e.jsx("div",{"aria-hidden":"true",style:{gridColumn:`${Ge.x+1} / span ${Ge.w}`,gridRow:`${Ge.y+1} / span ${Ge.h}`,border:"2px dashed var(--dql-app-accent, var(--accent, #4f46e5))",background:"var(--dql-app-accent-soft, rgba(79,70,229,0.10))",borderRadius:10,pointerEvents:"none",zIndex:10}}),dt.map(N=>e.jsx(ki,{item:N,tile:Ue.get(N.i),loading:L,error:O,themeMode:y.themeMode,editable:Ce,narrow:Le,cols:re,selected:!!(Bt(N)&&Bt(N)===o),onFocusBlock:l,onAskBlock:d,onMove:B=>void pt(N.i,B),onDragMove:B=>_t(N.i,B),onDragEnd:st,onPatch:B=>void pr(N.i,B),onRetry:()=>void er(N.i),retrying:xe===N.i,retryDisabled:!!(xe&&xe!==N.i),onOpenNotebook:B=>void ur(N,B),activeVariables:Me},N.i))]}),!i&&w?e.jsx(kd,{run:w,variables:Me}):null]}),ee&&!x&&e.jsx("aside",{style:{width:340,minWidth:300,maxWidth:"34vw",border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:8,overflow:"auto",alignSelf:"flex-start",height:fd,position:"sticky",top:12,padding:12},children:e.jsx(Od,{lineage:$e})}),U&&!m&&e.jsx(Ea,{t:u,title:"Dashboard AI",subtitle:"Scoped to this App dashboard first",expanded:le,onToggleExpanded:()=>ge(N=>!N),onClose:()=>{_(!1),ge(!1)},floating:!0,ariaLabel:"Dashboard AI",style:rp(le),children:e.jsx(p.Suspense,{fallback:e.jsx("div",{style:{padding:16,fontSize:12,color:u.textSecondary},children:"Loading Dashboard AI…"}),children:e.jsx(gd,{themeMode:y.themeMode,title:"Dashboard AI",scopeHint:"Scoped to this App dashboard first",audience:"stakeholder",workspaceContext:{appId:t,dashboardId:r.id,dashboardContext:ke},initialMode:"auto",threadId:A.threadId,onThreadIdChange:A.onThreadIdChange},`${t}:${r.id}`)})}),te&&e.jsx(Fd,{blocks:Y,search:h,onSearch:$,onClose:()=>Q(!1),onAdd:N=>void vt(N)}),ve&&e.jsx(Ld,{kind:ve,value:de,onChange:Pe,onClose:()=>{Te(null),Pe("")},onSave:()=>void Ut()})]})}function ki({item:t,tile:r,loading:a,error:i,themeMode:s,editable:n,narrow:o,cols:l,selected:d,onFocusBlock:x,onAskBlock:b,onMove:m,onDragMove:f,onDragEnd:y,onPatch:u,onRetry:w,retrying:q=!1,retryDisabled:C=!1,onOpenNotebook:k,activeVariables:M}){var Ee,ze;const L=p.useRef(null),[X,I]=p.useState(null),[O,F]=p.useState(!1),[U,_]=p.useState(!1),[A,te]=p.useState("how"),Q=Bt(t),Y=!!(!n&&Q&&b),S=Q?`block:${Q}`:t.semantic?`semantic:${t.semantic.id}`:t.draftAnalysis?`draft:${t.draftAnalysis.ref}`:t.aiPin?`aiPin:${t.aiPin.id}`:"text",[h,$]=p.useState(()=>lr(t.viz.type));p.useEffect(()=>$(lr(t.viz.type)),[t.i,t.viz.type]);const ee=n?lr(t.viz.type):h,W=p.useMemo(()=>n||ee===lr(t.viz.type)?t:{...t,viz:{...t.viz,type:aa(ee),options:{...t.viz.options??{},chart:ee}}},[ee,n,t]),$e=Fr(String(W.viz.type??"table")),se=Wt(t),oe=se==null?void 0:se.component,Be=t.title||(se==null?void 0:se.insightTitle)||S,ue=(r==null?void 0:r.tileType)==="aiPin"?((Ee=r.aiPin)==null?void 0:Ee.certification)==="certified"?"certified":"review_required":void 0,Ae=r==null?void 0:r.repair,_e=Ae?"review_required":((ze=r==null?void 0:r.artifact)==null?void 0:ze.trustState)??(se==null?void 0:se.trustState)??ue??((r==null?void 0:r.certificationStatus)==="certified"?"certified":void 0),Ie=!!se,xe=t.h<=2&&($e==="single_value"||$e==="kpi"||$e==="gauge"),[Ze,it]=p.useState(!1),R=n&&(Ze||d||O);p.useEffect(()=>{if(!n)return;const Z=pe=>{pe.detail!==t.i&&F(!1)};return window.addEventListener("dql-app-tile-settings-open",Z),()=>window.removeEventListener("dql-app-tile-settings-open",Z)},[n,t.i]);const le=()=>{F(Z=>{const pe=!Z;return pe&&window.dispatchEvent(new CustomEvent("dql-app-tile-settings-open",{detail:t.i})),pe})},ge=p.useMemo(()=>{const Z=Object.entries(M??{}).filter(([,ye])=>ye!=null&&ye!=="").map(([ye])=>ye);if(Z.length===0)return null;const pe=Z.filter(ye=>{const Ne=(t.filterBindings??[]).find(We=>We.filter===ye)??(t.parameterBindings??[]).find(We=>(We.filter||We.field||We.param)===ye);return!Ne||!!Ne.unsupportedReason||!(Ne.binding??Ne.param)});return pe.length===0?null:{label:pe.length===1?`Not filtered by ${pe[0]}`:`Not filtered by ${pe.length} page filters`,detail:`This tile has no column bound to ${pe.join(", ")}, so it shows the full scope while the rest of the page is narrowed.`}},[M,t.filterBindings,t.parameterBindings]),ve=Z=>{const pe=Z.trim();if(!pe||pe===t.title)return;const ye=Wt(t);u({title:pe,...ye?{viz:{...t.viz,options:{...t.viz.options??{},dqlGenUi:{...ye,insightTitle:pe}}}}:{}})},Te=Wd(t,se),de=!!(!n&&(r!=null&&r.result)&&Te.length>1),Pe=!!(r&&r.tileType!=="text"&&(r.artifact||r.result||r.citation||r.repair)),Ge=!!(Y&&(Ze||d)),Ye=Z=>{if(!n){$(Z);return}const pe=aa(Z),ye=t.viz.options??{},Ne=Wt(t);u({viz:{...t.viz,type:pe,options:{...ye,chart:Z,...Ne?{dqlGenUi:{...Ne,defaultVisualization:pe}}:{}}},display:yn(t,pe,Ne)})},De=Z=>{if(o)return;const pe=L.current;if(!pe)return;Z.preventDefault(),Z.stopPropagation();const ye=pe.getBoundingClientRect(),Ne={x:Z.clientX-ye.left,y:Z.clientY-ye.top},We={x:Z.clientX,y:Z.clientY},Me=we=>{I({x:we.clientX-We.x,y:we.clientY-We.y}),f==null||f({clientX:we.clientX-Ne.x,clientY:we.clientY-Ne.y})},Ue=we=>{window.removeEventListener("pointermove",Me),window.removeEventListener("pointerup",Ue),I(null),y==null||y(),m({clientX:we.clientX-Ne.x,clientY:we.clientY-Ne.y})};window.addEventListener("pointermove",Me),window.addEventListener("pointerup",Ue,{once:!0})};return e.jsxs("div",{ref:L,onMouseEnter:()=>it(!0),onMouseLeave:()=>it(!1),onClick:()=>{Q&&(x==null||x(Q))},style:{gridColumn:o?"1 / -1":`${t.x+1} / span ${t.w}`,gridRow:o?"auto":`${t.y+1} / span ${t.h}`,transform:X?`translate(${X.x}px, ${X.y}px) scale(1.02)`:void 0,opacity:X?.92:1,zIndex:X?30:void 0,position:"relative",background:Ie?Hd(oe):"var(--dql-app-surface, var(--surface, rgba(0,0,0,0.02)))",border:d||X?"1.5px solid var(--dql-app-accent, var(--accent, #4f46e5))":Ie?"1px solid var(--dql-app-line-2, var(--border-color, rgba(15,23,42,0.10)))":"1px solid var(--dql-app-line, var(--border-color, rgba(0,0,0,0.08)))",borderRadius:8,padding:xe?12:14,paddingBottom:Ge?xe?42:46:xe?12:14,display:"flex",flexDirection:"column",gap:xe?4:Ie?10:6,minHeight:o?Jl(t,se):0,overflow:"visible",boxShadow:X?"0 16px 40px rgba(0,0,0,0.22)":d?"0 0 0 3px var(--dql-app-accent-soft, rgba(79,70,229,0.12))":void 0,cursor:X?"grabbing":Q?"pointer":void 0,transition:X?void 0:"box-shadow 120ms ease, transform 120ms ease"},children:[Ge?e.jsxs("button",{type:"button",style:Ad,onClick:Z=>{Z.stopPropagation(),Q&&(x==null||x(Q)),Q&&(b==null||b(Q,Id(t.title??Q)))},title:"Open app Copilot for this tile",children:[e.jsx(ht,{size:11,strokeWidth:2})," Ask AI"]}):null,n&&!o?e.jsx("div",{style:{position:"absolute",top:10,left:10,zIndex:3,opacity:R?1:0,pointerEvents:R?"auto":"none",transition:"opacity 120ms ease"},children:e.jsx("button",{type:"button",title:"Drag to move tile",onPointerDown:De,style:kp,children:e.jsx(ws,{size:14,strokeWidth:2.2})})}):null,n?e.jsxs("div",{style:{position:"absolute",top:10,right:10,zIndex:4,display:"flex",alignItems:"center",gap:4,opacity:R?1:0,pointerEvents:R?"auto":"none",transition:"opacity 120ms ease"},children:[xe?null:e.jsx("span",{style:{fontSize:10,padding:"2px 8px",borderRadius:999,background:"var(--surface-hover, rgba(0,0,0,0.06))",opacity:.85},children:t.viz.type}),e.jsx(Pd,{item:t,cols:l,settingsOpen:O,onToggleSettings:le,onPatch:u})]}):null,Ie?e.jsx("div",{style:{minHeight:xe?26:42,paddingLeft:R?30:0,paddingRight:R?xe?82:134:0,transition:"padding 120ms ease",display:"grid",gap:7},children:e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,minWidth:0},children:[e.jsxs("div",{style:{flex:1,minWidth:0},children:[n?e.jsx("div",{style:{fontSize:xe?12:13,fontWeight:780,lineHeight:1.25,minWidth:0},children:e.jsx(Si,{value:Be??"",compact:xe,onCommit:Z=>ve(Z)})}):e.jsx("div",{title:Be,style:{fontSize:xe?12:13,fontWeight:780,lineHeight:1.25,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",display:"-webkit-box",WebkitLineClamp:2,WebkitBoxOrient:"vertical"},children:Be}),e.jsxs("div",{style:cp,children:[_e?e.jsx(Lr,{trust:_e}):null,Ae?e.jsxs("span",{style:qt,title:Ae.message,children:[e.jsx(wa,{size:9})," ",Ae.status==="repaired"?`${Ae.mode==="ai"?"AI ":""}repaired · review`:"repair blocked"]}):null,se?e.jsx("span",{style:qt,children:An(se)}):null,se!=null&&se.layoutIntent?e.jsx("span",{style:qt,children:St(String(se.layoutIntent))}):null]})]}),de?e.jsx(zi,{value:ee,options:Te,onChange:Ye}):null]})}):e.jsxs("div",{style:{minHeight:xe?22:26,paddingLeft:R?30:0,paddingRight:R?xe?82:134:0,transition:"padding 120ms ease"},children:[e.jsxs("div",{style:{fontSize:xe?12:13,fontWeight:720,lineHeight:1.25,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:[n?e.jsx(Si,{value:t.title??S??"",compact:xe,onCommit:Z=>ve(Z)}):e.jsx("span",{children:t.title??S}),de?e.jsx("span",{style:{float:"right",marginLeft:8},children:e.jsx(zi,{value:ee,options:Te,onChange:Ye})}):null]}),ge?e.jsx("div",{style:{marginTop:5},children:e.jsxs("span",{style:qt,title:ge.detail,children:[e.jsx(Zt,{size:9})," ",ge.label]})}):null,ue||Ae?e.jsxs("div",{style:{marginTop:5,display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[ue?e.jsx(Lr,{trust:ue}):null,ue?e.jsx("span",{style:qt,children:"AI generated"}):null,Ae?e.jsxs("span",{style:qt,title:Ae.message,children:[e.jsx(wa,{size:9})," ",Ae.status==="repaired"?`${Ae.mode==="ai"?"AI ":""}repaired · review`:"repair blocked"]}):null]}):xe?null:e.jsx("div",{style:{marginTop:5,fontSize:10.5,opacity:.58,fontFamily:"var(--font-mono, monospace)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S})]}),n&&O?e.jsx(_d,{item:t,tile:r,cols:l,onPatch:u,onClose:()=>F(!1)}):null,e.jsx("div",{style:{flex:1,minHeight:0,overflow:"hidden",display:"flex",alignItems:"stretch",justifyContent:"stretch",marginTop:xe?0:2,fontSize:12,opacity:(r==null?void 0:r.status)==="ok"?1:.7,fontStyle:(r==null?void 0:r.status)==="ok"?"normal":"italic"},children:e.jsx(Nd,{item:W,tile:r,loading:a,error:i,themeMode:s,genUi:se,editable:n,onEditText:Z=>u({text:{...t.text??{},markdown:Z}}),onRetry:w,retrying:q,retryDisabled:C})}),n?null:e.jsx(bd,{tile:r,themeMode:s}),!n&&Pe?e.jsx("div",{style:{display:"flex",justifyContent:"flex-end",gap:6,paddingTop:2},children:e.jsx("button",{type:"button",onClick:Z=>{Z.stopPropagation(),_(pe=>!pe)},style:In,children:U?"Hide details":"How it works"})}):null,!n&&U&&r?e.jsx(Td,{item:t,tile:r,tab:A,onTab:te,onOpenNotebook:k,onClose:()=>_(!1)}):null]})}function bd({tile:t,themeMode:r}){const a=Ht[r],i=p.useMemo(()=>vd(t),[t]);return i?e.jsxs("div",{style:{padding:"4px 10px 8px",fontSize:11.5,color:a.textMuted,lineHeight:1.4,display:"flex",gap:5,alignItems:"baseline"},children:[e.jsx("span",{style:{color:a.accent},children:"•"}),e.jsx("span",{children:i})]}):null}function vd(t){var u,w;const r=(u=t==null?void 0:t.result)==null?void 0:u.rows,a=(w=t==null?void 0:t.result)==null?void 0:w.columns;if(!Array.isArray(r)||r.length===0||!Array.isArray(a)||a.length===0)return null;const i=r[0],s=q=>{if(typeof q=="number"&&Number.isFinite(q))return q;if(typeof q=="string"){const C=Number(q.replace(/[$,%\s]/g,""));return Number.isFinite(C)&&q.trim()?C:void 0}},n=a.find(q=>s(i==null?void 0:i[q])!==void 0),o=a.find(q=>q!==n&&typeof(i==null?void 0:i[q])=="string");if(!n)return null;const l=r.map(q=>q[n]),d=o?r.map(q=>q[o]):[],x=St(n);if(r.length===1){const q=s(r[0][n]);return q!==void 0?`${x}: ${It(n,q,l,{compact:!0})}.`:null}const b=r.map(q=>({label:o?It(o,q[o],d):"top",value:s(q[n])??0})).sort((q,C)=>C.value-q.value),m=b.reduce((q,C)=>q+C.value,0),f=b[0];if(!f)return null;const y=It(n,f.value,l,{compact:!0});return m>0?`${f.label} leads ${x} at ${y} (${Math.round(f.value/m*100)}%).`:`${f.label} leads ${x} at ${y}.`}function yd({markdown:t,variant:r,themeMode:a,onCommit:i}){const[s,n]=p.useState(!1),[o,l]=p.useState(t);return p.useEffect(()=>{l(t)},[t]),s?e.jsx("textarea",{autoFocus:!0,"aria-label":r==="heading"?"Heading text":"Tile text",value:o,onChange:d=>l(d.target.value),onPointerDown:d=>d.stopPropagation(),onBlur:()=>{n(!1),o!==t&&i(o)},onKeyDown:d=>{d.stopPropagation(),d.key==="Escape"&&(l(t),n(!1))},style:{width:"100%",minHeight:72,resize:"vertical",boxSizing:"border-box",font:r==="heading"?"700 17px/1.3 inherit":"inherit",color:"inherit",background:"var(--bg-1, #fff)",border:"1px solid var(--accent, #4f46e5)",borderRadius:7,padding:"7px 9px",outline:"none"}}):e.jsx("div",{role:"button",tabIndex:0,title:"Click to edit this text",onClick:()=>n(!0),onKeyDown:d=>{(d.key==="Enter"||d.key===" ")&&(d.preventDefault(),n(!0))},style:{cursor:"text",minHeight:24,borderRadius:6,outline:"none"},children:t.trim()?e.jsx(Cn,{markdown:t,variant:r,themeMode:a}):e.jsx("span",{style:{opacity:.55,fontSize:12},children:"Click to write this section…"})})}function Si({value:t,compact:r,onCommit:a}){const[i,s]=p.useState(t),[n,o]=p.useState(!1);return p.useEffect(()=>{s(t)},[t]),e.jsx("input",{"aria-label":"Tile name",title:"Tile name — press Enter to save",value:i,maxLength:140,onChange:l=>s(l.target.value),onFocus:()=>o(!0),onBlur:()=>{o(!1);const l=i.trim();l&&l!==t?a(l):s(t)},onKeyDown:l=>{l.stopPropagation(),l.key==="Enter"&&l.currentTarget.blur(),l.key==="Escape"&&(s(t),l.currentTarget.blur())},onPointerDown:l=>l.stopPropagation(),style:{font:"inherit",color:"inherit",background:n?"var(--bg-1, #fff)":"transparent",border:`1px solid ${n?"var(--accent, #4f46e5)":"transparent"}`,borderRadius:6,padding:r?"0 4px":"1px 5px",margin:r?"0 0 0 -4px":"0 0 0 -5px",maxWidth:"100%",width:`${Math.max(6,Math.min(48,i.length+1))}ch`,outline:"none",cursor:n?"text":"pointer"},onMouseEnter:l=>{n||(l.currentTarget.style.borderColor="var(--border-subtle, #d8d8d8)")},onMouseLeave:l=>{n||(l.currentTarget.style.borderColor="transparent")}})}function zi({value:t,options:r,onChange:a}){const s=r.slice(0,4);if(!s.some(o=>o.value===t)){const o=r.find(l=>l.value===t);o&&s.splice(3,1,o)}const n=r.filter(o=>!s.some(l=>l.value===o.value));return e.jsxs("div",{style:xp,"aria-label":"Visualization",children:[s.map(o=>e.jsx("button",{type:"button",title:o.label,"aria-label":o.label,"aria-pressed":t===o.value,onClick:l=>{l.stopPropagation(),a(o.value)},style:gp(t===o.value),children:Qd(o.value)},o.value)),n.length>0?e.jsxs("select",{"aria-label":"More visualizations",title:"More visualizations",value:"",onClick:o=>o.stopPropagation(),onChange:o=>{o.target.value&&a(o.target.value)},style:wd,children:[e.jsx("option",{value:"",children:"More…"}),n.map(o=>e.jsx("option",{value:o.value,children:o.label},o.value))]}):null]})}const wd={border:"none",background:"transparent",color:"inherit",font:"inherit",fontSize:10.5,cursor:"pointer",maxWidth:74};function Lr({trust:t}){const r=t==="certified",a=r?"Certified":t==="review_required"?"Review required":"Draft ready";return e.jsxs("span",{style:up(r),children:[r?e.jsx(Qe,{size:10,strokeWidth:2.4}):e.jsx(Er,{size:10,strokeWidth:2.4}),a]})}function qd({story:t}){return e.jsxs("section",{style:Nn,"aria-label":"Current dashboard story",children:[e.jsxs("div",{style:Rn,children:[e.jsx("div",{style:Tn,children:e.jsx(ht,{size:15,strokeWidth:2.2})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:Pn,children:"Story from current results"}),e.jsx("h3",{style:$n,children:t.title})]}),t.trust?e.jsx(Lr,{trust:t.trust}):null]}),e.jsx("p",{style:_n,children:t.summary}),e.jsxs("div",{style:Ja,children:[e.jsx("span",{style:En,children:t.sourceTitle}),t.filters.map(r=>e.jsxs("span",{style:qr,children:[r.label,": ",r.value]},`${r.label}:${r.value}`)),t.chips.map(r=>e.jsx("span",{style:qr,children:r},r))]})]})}function jd({story:t,onEvidence:r,onResearch:a}){return e.jsxs("section",{style:{...Nn,padding:"20px 22px",marginBottom:16},"aria-label":"Business Story",children:[e.jsxs("div",{style:Rn,children:[e.jsx("div",{style:Tn,children:e.jsx(ht,{size:15,strokeWidth:2.2})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:Pn,children:"Business Story · current filters"}),e.jsx("h2",{style:{...$n,fontSize:19},children:t.headline})]}),e.jsx(Lr,{trust:t.trustState})]}),e.jsxs("div",{style:{display:"grid",gap:10,marginTop:12,maxWidth:920},children:[t.paragraphs.slice(0,2).map((i,s)=>e.jsx("p",{style:{..._n,margin:0,fontSize:14,lineHeight:1.65},children:Ci(i)},s)),t.implication?e.jsxs("p",{style:{margin:0,fontSize:13,lineHeight:1.55,fontWeight:650},children:["What this means: ",Ci(t.implication)]}):null]}),e.jsxs("div",{style:{...Ja,marginTop:14},children:[e.jsx("span",{style:En,children:t.generatedBy==="ai"?"AI wording · verified facts":"Verified result summary"}),e.jsxs("span",{style:qr,children:[t.evidenceRefs.length," evidence source",t.evidenceRefs.length===1?"":"s"]}),t.caveat?e.jsx("span",{style:qr,children:t.caveat}):null,e.jsx("span",{style:{flex:1}}),e.jsx("button",{type:"button",onClick:r,style:Ti,children:"View evidence"}),e.jsx("button",{type:"button",onClick:a,style:Ti,children:"Research deeper"})]})]})}function kd({run:t,variables:r}){const a=t.tiles.filter(s=>s.status!=="ok"),i=Object.entries(r).filter(([,s])=>s!=null&&s!=="");return e.jsxs("details",{style:Sd,"aria-label":"Evidence and review appendix",children:[e.jsxs("summary",{style:zd,children:["Evidence & review appendix",e.jsxs("span",{style:{opacity:.62,fontWeight:600},children:[t.story.evidenceRefs.length," sources · ",a.length?`${a.length} issue${a.length===1?"":"s"}`:"all visible sources ran"]})]}),e.jsxs("div",{style:{display:"grid",gap:12,padding:"0 16px 16px"},children:[e.jsxs("div",{style:Cd,children:[e.jsxs("div",{children:[e.jsx("strong",{children:"Run"}),e.jsx("br",{}),e.jsx("span",{children:t.runId})]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Snapshot"}),e.jsx("br",{}),e.jsx("span",{children:t.snapshotId})]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Trust"}),e.jsx("br",{}),e.jsx("span",{children:t.story.trustState})]}),e.jsxs("div",{children:[e.jsx("strong",{children:"Filters"}),e.jsx("br",{}),e.jsx("span",{children:i.length?i.map(([s,n])=>`${s}: ${String(n)}`).join(" · "):"Current unfiltered scope"})]})]}),e.jsxs("div",{children:[e.jsx("strong",{style:{fontSize:12},children:"Evidence used by the story"}),e.jsx("div",{style:{...Ja,marginTop:7},children:t.story.evidenceRefs.map(s=>e.jsx("span",{style:qr,children:s},s))})]}),a.length?e.jsxs("div",{children:[e.jsx("strong",{style:{fontSize:12},children:"Items requiring review"}),e.jsx("ul",{style:{margin:"7px 0 0",paddingLeft:18,fontSize:12,lineHeight:1.55},children:a.map(s=>e.jsxs("li",{children:[s.title??s.tileId,": ",s.error??s.status]},s.tileId))})]}):null]})]})}function Ci(t){return t.split(/(\*\*[^*]+\*\*)/g).filter(Boolean).map((r,a)=>r.startsWith("**")&&r.endsWith("**")?e.jsx("strong",{children:r.slice(2,-2)},a):r)}const Sd={marginTop:16,border:"1px solid var(--dql-app-line, var(--border-color, rgba(15,23,42,0.10)))",borderRadius:8,background:"var(--dql-app-surface, var(--surface, rgba(0,0,0,0.02)))",color:"var(--dql-app-text, var(--text-primary, #0f172a))"},zd={cursor:"pointer",padding:"12px 16px",fontSize:12.5,fontWeight:760,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},Cd={display:"grid",gridTemplateColumns:"repeat(auto-fit, minmax(170px, 1fr))",gap:10,fontSize:11.5,lineHeight:1.45,color:"var(--dql-app-text-muted, var(--text-secondary, #64748b))"},Ad={position:"absolute",bottom:10,right:10,zIndex:5,display:"inline-flex",alignItems:"center",gap:4,padding:"3px 8px",borderRadius:999,fontSize:10.5,fontWeight:700,color:"var(--dql-app-accent, var(--accent, #4f46e5))",background:"var(--dql-app-accent-soft, rgba(79,70,229,0.12))",border:"1px solid var(--dql-app-accent, rgba(79,70,229,0.4))",cursor:"pointer",lineHeight:1.2,fontFamily:"inherit"};function Id(t){return`/ask Explain ${t} for a stakeholder. Start with the business meaning, current result, active filters, caveats, and recommended next action.`}function Nd({item:t,tile:r,loading:a,error:i,themeMode:s,genUi:n,editable:o=!1,onEditText:l,onRetry:d,retrying:x,retryDisabled:b}){var u,w,q,C,k,M;if(a&&!r)return e.jsx("span",{children:"Loading data..."});if((r==null?void 0:r.tileType)==="text"){if(n)return e.jsx(Ed,{title:t.title??n.insightTitle??"Generated section",markdown:((u=r.text)==null?void 0:u.markdown)??"",genUi:n,themeMode:s});const L=((w=r.text)==null?void 0:w.markdown)??"";return o&&l?e.jsx(yd,{markdown:L,variant:((q=r.viz)==null?void 0:q.type)==="heading"?"heading":"text",themeMode:s,onCommit:l}):e.jsx(Cn,{markdown:L,variant:((C=r.viz)==null?void 0:C.type)==="heading"?"heading":"text",themeMode:s})}if(i&&!r)return e.jsx("span",{children:i});if(!r)return e.jsx("span",{children:"No run result."});if(r.status==="unauthorized")return e.jsx("span",{children:"Not authorized."});if(r.status==="unresolved")return e.jsx("span",{children:r.error??"Block reference unresolved."});if(r.status==="error")return e.jsxs("div",{style:{display:"grid",gap:8,justifyItems:"center",textAlign:"center",padding:8},children:[e.jsx("span",{children:r.error??"Tile failed."}),((k=r.repair)==null?void 0:k.status)==="failed"?e.jsx("small",{children:r.repair.message}):null,d?e.jsxs("button",{type:"button",disabled:x||b,onClick:L=>{L.stopPropagation(),d()},style:Jd,children:[e.jsx(wa,{size:12})," ",x?"Fixing…":"Fix and retry"]}):null]});if(!r.result)return r.tileType==="aiPin"&&r.aiPin?e.jsx(Ni,{pin:r.aiPin,themeMode:s}):e.jsx("span",{children:"No result."});const m=Va(t,r.chartConfig),f=String(m.chart??((M=r.viz)==null?void 0:M.type)??"").toLowerCase();let y;if(f==="table"||t.viz.type==="table"||t.viz.type==="pivot")r.tileType!=="aiPin"&&((n==null?void 0:n.component)==="EvidenceTable"||(n==null?void 0:n.component)==="PivotTable")?y=e.jsx(Bd,{result:r.result,genUi:n,themeMode:s}):y=e.jsx("div",{style:{width:"100%",alignSelf:"stretch"},children:e.jsx(Xi,{result:r.result,themeMode:s,initialPageSize:10})});else{const L=f==="kpi"?Vl(r.result,m.y):r.result;y=e.jsx(Rd,{children:X=>e.jsx(Ji,{result:L,themeMode:s,chartConfig:{...m,title:void 0},availableHeight:X})})}return r.tileType==="aiPin"&&r.aiPin?e.jsx(Ni,{pin:r.aiPin,themeMode:s,dataView:y}):y}function Rd({children:t}){const r=p.useRef(null),[a,i]=p.useState();return p.useEffect(()=>{const s=r.current;if(!s)return;const n=()=>{const l=Math.floor(s.getBoundingClientRect().height);i(l>0?l:void 0)};n();const o=new ResizeObserver(n);return o.observe(s),()=>o.disconnect()},[]),e.jsx("div",{ref:r,"data-testid":"dashboard-chart-frame",style:{width:"100%",height:"100%",minWidth:0,minHeight:0,alignSelf:"stretch",overflow:"auto",scrollbarWidth:"thin"},children:t(a)})}function Td({item:t,tile:r,tab:a,onTab:i,onOpenNotebook:s,onClose:n}){var x,b,m;const o=r.artifact,l=!!(r.result&&(o!=null&&o.dql||o!=null&&o.sql)),d=(o==null?void 0:o.sourceKind)==="certified_block"?"Certified block":(o==null?void 0:o.sourceKind)==="semantic_query"?"Governed semantic query":(o==null?void 0:o.sourceKind)==="draft_analysis"?"App analysis":(o==null?void 0:o.sourceKind)==="ai_pin"?"Saved AI insight":r.tileType??"App tile";return e.jsx("div",{style:Zd,role:"presentation",onClick:n,children:e.jsxs("section",{role:"dialog","aria-modal":"true","aria-label":`How ${t.title??r.title??t.i} works`,style:Dd,onClick:f=>f.stopPropagation(),children:[e.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:12},children:[e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:16,fontWeight:800},children:t.title??r.title??(o==null?void 0:o.name)??"App tile"}),e.jsxs("div",{style:{marginTop:4,fontSize:12,color:"var(--text-secondary)"},children:[d," · ",(o==null?void 0:o.trustState)==="certified"&&!r.repair?"Certified":"Review required"]})]}),e.jsx("button",{type:"button",onClick:n,"aria-label":"Close details",style:ea,children:e.jsx($t,{size:14})})]}),e.jsx("div",{style:{display:"flex",gap:6,flexWrap:"wrap",borderBottom:"1px solid var(--border-subtle)",paddingBottom:10},children:["how","dql","sql"].map(f=>e.jsx("button",{type:"button",onClick:()=>i(f),style:Ud(a===f),children:f==="how"?"How it works":f.toUpperCase()},f))}),e.jsx("div",{style:{minHeight:180,maxHeight:"56vh",overflow:"auto"},children:a==="how"?e.jsxs("div",{style:{display:"grid",gap:12,fontSize:12.5,lineHeight:1.5},children:[e.jsx(Ir,{label:"Source",value:(o==null?void 0:o.sourcePath)??((x=r.citation)==null?void 0:x.path)??((b=r.citation)==null?void 0:b.name)??d}),e.jsx(Ir,{label:"Result",value:r.result?`${r.result.rowCount} rows · ${r.result.columns.length} columns`:r.status}),(m=o==null?void 0:o.explanation)!=null&&m.length?e.jsxs("div",{children:[e.jsx("b",{children:"Execution"}),e.jsx("ul",{style:{margin:"6px 0 0",paddingLeft:18},children:o.explanation.map(f=>e.jsx("li",{children:f},f))})]}):null,r.filters?e.jsx(Ir,{label:"Filters",value:`${r.filters.applied.map(f=>f.filter).join(", ")||"None applied"}${r.filters.skipped.length?` · ${r.filters.skipped.length} skipped`:""}`}):null,r.invocation?e.jsx(Ir,{label:"Parameters",value:r.invocation.resolvedParameters.map(f=>`${f.name} (${f.source})`).join(", ")||"None"}):null,r.repair?e.jsx(Ir,{label:"Repair",value:r.repair.message}):null,e.jsx("div",{style:{padding:10,borderRadius:8,background:"var(--bg-2)",color:"var(--text-secondary)"},children:"Parameter values are intentionally omitted here. Open the editable Notebook cell to inspect or change the full execution contract."})]}):e.jsx("pre",{style:ep,children:a==="dql"?(o==null?void 0:o.dql)??"This tile does not expose DQL source. Its governed semantic intent is composed into SQL at runtime.":(o==null?void 0:o.sql)??"Executed SQL is not available for this saved result."})}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8,borderTop:"1px solid var(--border-subtle)",paddingTop:10},children:[e.jsx("button",{type:"button",onClick:n,style:Ot(!1),children:"Close"}),l?e.jsx("button",{type:"button",onClick:()=>s==null?void 0:s(r),style:Ot(!0),children:"Open in Notebook"}):null]})]})})}function Ir({label:t,value:r}){return e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"110px minmax(0, 1fr)",gap:12},children:[e.jsx("b",{children:t}),e.jsx("span",{style:{minWidth:0,overflowWrap:"anywhere",color:"var(--text-secondary)"},children:r})]})}function Pd({item:t,cols:r,settingsOpen:a,onToggleSettings:i,onPatch:s}){const[n,o]=p.useState(!1),l=d=>{o(!1),s(jn(t,r,d))};return e.jsxs("div",{style:{display:"flex",gap:4,alignItems:"center",flexWrap:"wrap",justifyContent:"flex-end"},children:[e.jsxs("div",{style:{position:"relative"},children:[e.jsx("button",{type:"button",title:"Choose tile size",onClick:()=>o(d=>!d),style:ea,children:e.jsx(gs,{size:13,strokeWidth:2})}),n?e.jsx($d,{onPick:l,onClose:()=>o(!1)}):null]}),e.jsx("button",{type:"button",title:"Tile settings","aria-label":"Tile settings",onClick:i,style:ea,children:e.jsx(rn,{size:13,strokeWidth:2,color:a?"var(--accent, #4f46e5)":void 0})}),e.jsx("button",{type:"button",title:"Remove tile",onClick:()=>s(null),style:ea,children:e.jsx(ir,{size:13,strokeWidth:2})})]})}function $d({onPick:t,onClose:r}){return e.jsx("div",{style:Sp,onMouseLeave:r,children:qn.map(a=>e.jsxs("button",{type:"button",onClick:()=>t(a.id),style:zp,children:[e.jsx("span",{style:{fontSize:12,fontWeight:750},children:a.label}),e.jsx("span",{style:{fontSize:11,opacity:.66},children:a.description})]},a.id))})}function _d({item:t,tile:r,cols:a,onPatch:i,onClose:s}){var U;const n=r==null?void 0:r.result,o=Va(t,r==null?void 0:r.chartConfig),l=lr(o.chart),d=Wt(t),[x,b]=p.useState(!1),[m,f]=p.useState(null),[y,u]=p.useState(null),w=p.useMemo(()=>vs(n),[n]),q=p.useMemo(()=>{const _=new Map;if(!n)return _;const A=new Set(w.metrics),te=new Set(w.dimensions);for(const Q of n.columns)A.has(Q)?_.set(Q,"measure"):te.has(Q)?_.set(Q,"dimension"):_.set(Q,fs(ms(Q,n.rows)));return _},[n,w]),C=(n==null?void 0:n.columns.filter(_=>q.get(_)==="measure"))??[],k=(n==null?void 0:n.columns.filter(_=>q.get(_)!=="measure"))??[],M=t.title??o.title??"",[L,X]=p.useState(M);p.useEffect(()=>{X(M)},[M]);const I=()=>{const _=L.trim();_!==M&&O({title:_||void 0})},O=_=>{const A=gi({...o,..._}),te=aa(A.chart),Q=Wt(t),Y={...A};Q&&(Y.dqlGenUi={...Q,defaultVisualization:te,...A.title?{insightTitle:A.title}:{}}),i({title:A.title||t.title,viz:{...t.viz,type:te,options:Y},display:yn(t,te,Q)})},F=async()=>{b(!0),u(null),f(null);const _=Bt(t)??t.title,A=await D.recommendVisualization({..._?{blockRef:_}:{},resultSchema:n?{columns:n.columns}:void 0,rowSample:n==null?void 0:n.rows.slice(0,5),prompt:[t.title,d==null?void 0:d.rationale].filter(Boolean).join(" "),allowedVisualizations:d==null?void 0:d.allowedVisualizations});if(b(!1),!A.ok){u(A.error);return}const te=lr(A.display.defaultVisualization),Q=aa(te),Y=A.display.fieldHints??{},S=gi({...o,chart:te,title:o.title??t.title,x:Y.x??Y.label??o.x,y:Y.y??Y.value??o.y,color:Y.color??o.color});i({title:S.title||t.title,viz:{...t.viz,type:Q,options:{...S}},display:A.display});const h=A.evidence.map(ee=>ee.source).slice(0,3).join(", "),$=A.warnings[0];f($?`${A.display.component}: ${$}`:`${A.display.component}${h?` from ${h}`:""}`)};return e.jsxs("aside",{role:"dialog","aria-label":`Tile settings for ${t.title??t.i}`,style:ip,onClick:_=>_.stopPropagation(),children:[e.jsxs("header",{style:np,children:[e.jsxs("div",{style:{minWidth:0},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:7,fontSize:13,fontWeight:820},children:[e.jsx(rn,{size:14})," Tile settings"]}),e.jsx("div",{style:{marginTop:2,color:"var(--text-tertiary)",fontSize:11,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:t.title??t.i})]}),e.jsx("button",{type:"button","aria-label":"Close tile settings",title:"Close",onClick:s,style:sp,children:e.jsx($t,{size:15})})]}),e.jsxs("section",{style:$i,children:[e.jsx("div",{style:_i,children:"Layout"}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:qn.map(_=>e.jsx("button",{type:"button",title:_.description,onClick:()=>i(jn(t,a,_.id)),style:Cp(Zl(t,a,_.id)),children:_.label},_.id))})]}),e.jsxs("section",{style:$i,children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",justifyContent:"space-between",gap:10},children:[e.jsx("div",{style:_i,children:"Visualization"}),e.jsxs("button",{type:"button",onClick:()=>void F(),disabled:x,style:lp(x),title:"Recommend a visualization from governed result fields",children:[e.jsx(tn,{size:12,strokeWidth:2.2}),x?"Thinking…":"Recommend"]})]}),e.jsxs("div",{style:Ei,children:[e.jsxs("label",{style:{...Na,gridColumn:"1 / -1"},children:["Title",e.jsx("input",{"aria-label":"Tile name",value:L,onChange:_=>X(_.target.value),onBlur:()=>I(),onKeyDown:_=>{_.key==="Enter"&&_.currentTarget.blur(),_.key==="Escape"&&(X(M),_.currentTarget.blur())},style:Ra})]}),e.jsxs("label",{style:{...Na,gridColumn:"1 / -1"},children:["Chart type",e.jsx("select",{value:l,onChange:_=>O({chart:_.target.value}),style:Ra,children:zn.map(_=>e.jsx("option",{value:_.value,children:_.label},_.value))})]})]}),m?e.jsx("div",{style:Mn,children:m}):null,y?e.jsx("div",{style:dp,children:y}):null]}),e.jsxs("details",{style:Bi,children:[e.jsx("summary",{style:Mi,children:"Data fields and advanced options"}),e.jsxs("div",{style:{display:"grid",gap:10,marginTop:10},children:[e.jsxs("div",{style:Ei,children:[e.jsx(Zr,{label:"Category / X",value:o.x,columns:(n==null?void 0:n.columns)??[],onChange:_=>O({x:_})}),e.jsx(Zr,{label:"Value / Y",value:o.y,columns:(n==null?void 0:n.columns)??[],onChange:_=>O({y:_})}),e.jsx(Zr,{label:"Color",value:o.color,columns:(n==null?void 0:n.columns)??[],onChange:_=>O({color:_})}),e.jsx(Zr,{label:"Facet",value:o.facet,columns:(n==null?void 0:n.columns)??[],onChange:_=>O({facet:_})})]}),n?e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:10},children:[e.jsx(Ai,{title:"Measures",columns:C,onPick:_=>O({y:_})}),e.jsx(Ai,{title:"Dimensions",columns:k,onPick:_=>O({x:_})})]}):e.jsx("div",{style:{fontSize:11,opacity:.64},children:"Run the tile once to map result fields."})]})]}),e.jsxs("details",{style:Bi,children:[e.jsx("summary",{style:Mi,children:"Why this visualization"}),e.jsxs("div",{style:op,children:[e.jsx("div",{style:{fontSize:11.5,lineHeight:1.5,color:"var(--text-secondary)"},children:(d==null?void 0:d.rationale)??((U=t.display)==null?void 0:U.rationale)??"This visualization is constrained by the governed result fields and the saved App display contract."}),e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:[d!=null&&d.component?e.jsx("span",{style:qt,children:An(d)}):null,d!=null&&d.defaultVisualization?e.jsx("span",{style:qt,children:St(String(d.defaultVisualization))}):null,d!=null&&d.reviewStatus?e.jsx("span",{style:qt,children:St(String(d.reviewStatus))}):null]})]})]})]})}function Zr({label:t,value:r,columns:a,onChange:i}){return e.jsxs("label",{style:Na,children:[t,e.jsxs("select",{value:r??"",onChange:s=>i(s.target.value||void 0),style:Ra,children:[e.jsx("option",{value:"",children:"Auto"}),a.map(s=>e.jsx("option",{value:s,children:s},s))]})]})}function Ai({title:t,columns:r,onPick:a}){return e.jsxs("div",{style:{display:"grid",gap:4,minWidth:0},children:[e.jsx("div",{style:{fontSize:10,fontWeight:800,textTransform:"uppercase",opacity:.58},children:t}),e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:r.length===0?e.jsx("span",{style:{fontSize:11,opacity:.55},children:"None"}):r.slice(0,10).map(i=>e.jsx("button",{type:"button",onClick:()=>a(i),style:pp,children:i},i))})]})}function Ii({open:t,onToggle:r,onCertifiedBlock:a,onText:i,onHeading:s,onAi:n,buttonLabel:o,buttonStyle:l}){return e.jsxs("div",{style:{position:"relative",display:"inline-flex"},children:[e.jsxs("button",{type:"button",onClick:r,title:"Add tile",style:l??Ot(t),children:[e.jsx(xt,{size:15,strokeWidth:2.2}),o?e.jsx("span",{children:o}):null]}),t&&e.jsxs("div",{style:{position:"absolute",top:"calc(100% + 6px)",right:0,zIndex:30,width:260,border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:8,background:"var(--color-bg, #fff)",boxShadow:"0 14px 38px rgba(0,0,0,0.16)",padding:6,display:"grid",gap:4,textAlign:"left"},children:[e.jsx(Dr,{title:"Certified block",description:"Chart, table, or KPI from this App domain",onClick:a}),e.jsx(Dr,{title:"Text / summary",description:"Narrative, notes, caveats, or CXO context",onClick:i}),e.jsx(Dr,{title:"Section heading",description:"Separate an App page into readable groups",onClick:s}),e.jsx(Dr,{title:"Copilot insight",description:"Open scoped AI, then pin the reviewed answer to this App",onClick:n})]})]})}function Dr({title:t,description:r,onClick:a}){return e.jsxs("button",{type:"button",onClick:a,style:ap,children:[e.jsx("span",{style:{fontSize:12,fontWeight:700},children:t}),e.jsx("span",{style:{fontSize:11,opacity:.66},children:r})]})}function Ed({title:t,markdown:r,genUi:a,themeMode:i}){var d;const s=Ht[i],n=Gd(r,t),o=a.component==="TrustCallout",l=a.component==="ResearchActions";return e.jsxs("div",{style:fp(o),children:[e.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-start"},children:[e.jsx("span",{style:mp(o),children:o?e.jsx(Er,{size:15}):l?e.jsx(ht,{size:15}):e.jsx(Qe,{size:15})}),e.jsxs("div",{style:{flex:1,minWidth:0},children:[e.jsx("div",{style:{fontSize:13,fontWeight:780,lineHeight:1.25},children:t??a.insightTitle}),e.jsx("div",{style:{marginTop:6,fontSize:13,lineHeight:1.45,color:s.textSecondary},children:n})]})]}),e.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[a.trustState?e.jsx(Lr,{trust:a.trustState}):null,a.reviewStatus?e.jsx("span",{style:qt,children:St(a.reviewStatus)}):null]}),(d=a.followUpActions)!=null&&d.length?e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:a.followUpActions.slice(0,3).map(x=>e.jsx("span",{style:hp,children:St(x)},x))}):null]})}function Bd({result:t,genUi:r,themeMode:a}){var f;const i=Ht[a],s=t.rows??[],n=t.columns??[],o=rd(n,s,(f=r.fieldHints)==null?void 0:f.label),l=n.find(y=>/\b(status|quality|trust|certification|review)\b/i.test(y)),d=n.filter(y=>y!==o&&y!==l).filter(y=>fa(y)<90||wr(y,s)).sort((y,u)=>fa(y)-fa(u)).slice(0,2),x=n.filter(y=>y!==o&&y!==l&&!d.includes(y)).slice(0,2),b=t.rowCount??s.length,m=kn(n,s);return e.jsxs("div",{style:bp,children:[e.jsxs("div",{style:{fontSize:11.5,color:i.textSecondary},children:[b," ",b===1?"row":"rows"," across ",n.length," ",n.length===1?"field":"fields"]}),e.jsx("div",{style:vp,children:s.slice(0,4).map((y,u)=>{const w=o?It(o,y[o],m.get(o)??[]):`Row ${u+1}`,q=l?It(l,y[l],m.get(l)??[]):null;return e.jsxs("div",{style:yp,children:[e.jsxs("div",{style:{minWidth:0},children:[e.jsx("div",{style:{fontSize:12.5,fontWeight:760,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:w}),x.length?e.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5,marginTop:4},children:x.map(C=>e.jsxs("span",{style:wp,children:[St(C),": ",It(C,y[C],m.get(C)??[])]},C))}):null]}),e.jsxs("div",{style:{display:"flex",gap:5,flexWrap:"wrap",justifyContent:"flex-start",minWidth:0},children:[d.map(C=>e.jsxs("span",{style:qp,children:[e.jsx("span",{style:{opacity:.62},children:St(C)}),e.jsx("strong",{children:It(C,y[C],m.get(C)??[])})]},C)),q?e.jsx("span",{style:jp,children:q}):null]})]},u)})}),s.length>4?e.jsx("div",{style:{fontSize:11,color:i.textSecondary},children:"Showing first 4 rows in generated view. Switch tile settings for full table controls."}):null]})}function Cn({markdown:t,variant:r="text",themeMode:a}){const i=Ht[a];return e.jsx("div",{style:{width:"100%",alignSelf:"stretch",overflow:"auto",whiteSpace:"normal",lineHeight:1.45,fontStyle:"normal",opacity:1,fontSize:r==="heading"?18:void 0,fontWeight:r==="heading"?800:void 0,display:r==="heading"?"flex":void 0,alignItems:r==="heading"?"center":void 0},children:en(t,i)})}function Ni({pin:t,themeMode:r,dataView:a}){var d,x;const[i,s]=p.useState(null),n=Ht[r]??Ht.light,o=async()=>{s("Refreshing...");const b=await D.refreshAiPin(t.appId,t.id);s(b.ok?"Refreshed.":b.error??"Refresh failed."),window.dispatchEvent(new CustomEvent("dql-app-dashboard-updated",{detail:{appId:t.appId,dashboardId:t.dashboardId}}))},l=async()=>{s("Creating draft...");const b=await D.promoteAiPin(t.appId,t.id);s(b.ok?`Draft created: ${b.blockPath}`:b.error??"Promotion failed."),window.dispatchEvent(new CustomEvent("dql-app-dashboard-updated",{detail:{appId:t.appId,dashboardId:t.dashboardId}}))};return e.jsxs("div",{style:{width:"100%",alignSelf:"stretch",overflow:"auto",fontStyle:"normal",lineHeight:1.5,display:"grid",gap:10},children:[a||e.jsxs(e.Fragment,{children:[e.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center",flexWrap:"wrap"},children:[e.jsx("span",{style:{fontSize:10.5,fontWeight:800,color:t.certification==="certified"?"#15803d":"#b45309",background:t.certification==="certified"?"rgba(22,163,74,0.1)":"rgba(245,158,11,0.12)",border:`1px solid ${t.certification==="certified"?"rgba(22,163,74,0.22)":"rgba(245,158,11,0.24)"}`,borderRadius:999,padding:"3px 7px"},children:t.certification==="certified"?"Certified":"Review required"}),e.jsx("span",{style:{fontSize:10.5,color:"var(--color-text-muted, rgba(0,0,0,0.58))"},children:"Pinned report insight"})]}),e.jsx("div",{style:{minWidth:0},children:en(t.answer,n)}),(x=(d=t.result)==null?void 0:d.rows)!=null&&x.length?e.jsx(Md,{result:t.result}):null]}),e.jsxs("div",{style:{display:"flex",gap:6,marginTop:8,flexWrap:"wrap"},children:[t.sql&&e.jsx("button",{type:"button",onClick:()=>void o(),style:Li,children:"Refresh"}),t.sql&&t.reviewStatus==="needs_review"&&e.jsx("button",{type:"button",onClick:()=>void l(),style:Li,children:"Promote"}),t.refreshCadence==="daily"&&e.jsx("span",{style:{fontSize:11,opacity:.62},children:"daily"})]}),i&&e.jsx("div",{style:{marginTop:6,fontSize:11,opacity:.72},children:i}),t.lastRefreshError&&e.jsx("div",{style:{marginTop:8,color:"#f85149"},children:t.lastRefreshError})]})}function Md({result:t}){var s,n;const r=((s=t.columns)!=null&&s.length?t.columns:Object.keys(((n=t.rows)==null?void 0:n[0])??{})).slice(0,4),a=(t.rows??[]).slice(0,3),i=kn(r,t.rows??[]);return!r.length||!a.length?null:e.jsxs("div",{style:{display:"grid",gap:6},children:[e.jsx("div",{style:{color:"var(--color-text-muted, rgba(0,0,0,0.58))",fontSize:11,fontWeight:750},children:"Supporting rows"}),e.jsx("div",{style:{overflow:"auto",border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6},children:e.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11},children:[e.jsx("thead",{children:e.jsx("tr",{children:r.map(o=>e.jsx("th",{style:{textAlign:"left",padding:"5px 7px",borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.08))",color:"var(--color-text-muted, rgba(0,0,0,0.58))"},children:St(o)},o))})}),e.jsx("tbody",{children:a.map((o,l)=>e.jsx("tr",{children:r.map(d=>e.jsx("td",{style:{padding:"5px 7px",borderBottom:l===a.length-1?"none":"1px solid var(--border-color, rgba(0,0,0,0.06))"},children:It(d,o[d],i.get(d)??[])},d))},l))})]})})]})}function Ld({kind:t,value:r,onChange:a,onClose:i,onSave:s}){const n=t==="heading";return e.jsx("div",{style:{position:"fixed",inset:0,zIndex:90,background:"rgba(0,0,0,0.36)",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:e.jsxs("div",{style:{width:"min(520px, 92vw)",display:"grid",gap:12,background:"var(--color-bg, #fff)",color:"inherit",borderRadius:8,boxShadow:"0 18px 60px rgba(0,0,0,0.35)",padding:16},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:16,fontWeight:800},children:n?"Add heading":"Add text tile"}),e.jsx("div",{style:{fontSize:12,opacity:.65,marginTop:4},children:n?"Create a section heading on this dashboard page.":"Create a narrative text tile on this dashboard page."})]}),n?e.jsx("input",{value:r,onChange:o=>a(o.target.value),onKeyDown:o=>{o.key==="Enter"&&s(),o.key==="Escape"&&i()},placeholder:"Executive summary",autoFocus:!0,style:Pi}):e.jsx("textarea",{value:r,onChange:o=>a(o.target.value),onKeyDown:o=>{o.key==="Escape"&&i(),o.key==="Enter"&&(o.metaKey||o.ctrlKey)&&s()},placeholder:"Add context, assumptions, or decisions...",rows:6,autoFocus:!0,style:{...Pi,resize:"vertical",lineHeight:1.45}}),e.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[e.jsx("button",{type:"button",onClick:i,style:Ot(!1),children:"Cancel"}),e.jsx("button",{type:"button",onClick:s,disabled:!r.trim(),style:{...Bn,opacity:r.trim()?1:.65},children:"Add"})]})]})})}function Fd({blocks:t,search:r,onSearch:a,onClose:i,onAdd:s}){const n=t.filter(o=>{const l=r.trim().toLowerCase();return l?[o.name,o.description,o.domain,...o.tags??[]].join(" ").toLowerCase().includes(l):!0});return e.jsx("div",{style:{position:"fixed",inset:0,zIndex:90,background:"rgba(0,0,0,0.36)",display:"flex",alignItems:"center",justifyContent:"center",padding:24},children:e.jsxs("div",{style:{width:"min(860px, 94vw)",maxHeight:"86vh",display:"flex",flexDirection:"column",background:"var(--color-bg, #fff)",color:"inherit",borderRadius:8,overflow:"hidden",boxShadow:"0 18px 60px rgba(0,0,0,0.35)"},children:[e.jsxs("div",{style:{padding:14,borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.1))",display:"flex",gap:10,alignItems:"center"},children:[e.jsx("div",{style:{fontSize:15,fontWeight:700,flex:1},children:"Add Certified Block"}),e.jsx("button",{type:"button",onClick:i,style:Ot(!1),children:"Close"})]}),e.jsx("div",{style:{padding:14,borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.08))"},children:e.jsx("input",{value:r,onChange:o=>a(o.target.value),placeholder:"Search domain blocks...",style:{width:"100%",boxSizing:"border-box",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,padding:"8px 10px",background:"var(--surface, transparent)",color:"inherit"}})}),e.jsx("div",{style:{overflow:"auto",padding:12,display:"grid",gap:8},children:n.length===0?e.jsx("div",{style:{padding:18,fontSize:12,opacity:.66},children:"No certified blocks match this App scope."}):n.map(o=>e.jsxs("button",{type:"button",onClick:()=>s(o),style:{textAlign:"left",border:"1px solid var(--border-color, rgba(0,0,0,0.1))",borderRadius:7,background:"transparent",color:"inherit",padding:10,cursor:"pointer"},children:[e.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:4},children:[e.jsx("span",{style:{fontSize:13,fontWeight:700},children:o.name}),e.jsx("span",{style:{fontSize:10,padding:"2px 6px",borderRadius:999,background:"rgba(63,185,80,0.14)",color:"#2ea043"},children:o.status}),e.jsx("span",{style:{fontSize:10,opacity:.68},children:o.domain}),e.jsx("span",{style:{fontSize:10,opacity:.68},children:o.chartType??"table"})]}),e.jsx("div",{style:{fontSize:12,opacity:.72},children:o.description||o.path})]},o.id))})]})})}function Od({lineage:t}){var s,n;const r=((s=t==null?void 0:t.graph)==null?void 0:s.nodes)??[],a=((n=t==null?void 0:t.graph)==null?void 0:n.edges)??[],i=(t==null?void 0:t.breadcrumbs)??[];return e.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[e.jsxs("div",{children:[e.jsx("div",{style:{fontSize:12,fontWeight:800,textTransform:"uppercase",opacity:.62,marginBottom:6},children:"App Lineage"}),e.jsx("div",{style:{fontSize:12,opacity:.72},children:"Terms and business views connect the App back to DQL blocks, dbt models, and source tables."})]}),i.length>0&&e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:i.map((o,l)=>e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"64px 1fr",gap:8,fontSize:12},children:[e.jsx("span",{style:{fontFamily:"monospace",opacity:.6},children:o.type}),e.jsx("span",{children:o.name})]},`${o.id}-${l}`))}),e.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[e.jsx(Ri,{label:"Nodes",value:r.length}),e.jsx(Ri,{label:"Edges",value:a.length})]}),e.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:r.slice(0,18).map(o=>e.jsxs("div",{style:{border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6,padding:8},children:[e.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[e.jsx("span",{style:{color:"#0d1117",background:rs[o.type]??"#8b949e",borderRadius:3,padding:"1px 4px",fontSize:9,fontWeight:800,flexShrink:0},children:ts[o.type]??o.type.slice(0,4).toUpperCase()}),e.jsx("div",{style:{fontSize:12,fontWeight:700,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:o.name})]}),e.jsxs("div",{style:{fontSize:11,opacity:.62,fontFamily:"monospace",marginTop:4},children:[as[o.type]??o.type," · ",o.id]})]},o.id))})]})}function Ri({label:t,value:r}){return e.jsxs("div",{style:{border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6,padding:8},children:[e.jsx("div",{style:{fontSize:11,opacity:.62},children:t}),e.jsx("div",{style:{fontSize:18,fontWeight:800},children:r})]})}function Wd(t,r){const a=new Set(["table",String(t.viz.type??"table"),...(r==null?void 0:r.allowedVisualizations)??[]]);return Array.from(a).map(s=>lr(s)).filter((s,n,o)=>o.indexOf(s)===n).map(s=>zn.find(n=>n.value===s)??{value:s,label:St(s)})}function Hd(t){return t==="TrustCallout"?"linear-gradient(180deg, rgba(255,255,255,0.92), rgba(255,251,235,0.72))":t==="RankingPanel"||t==="TrendPanel"||t==="PivotTable"?"linear-gradient(180deg, rgba(255,255,255,0.96), rgba(248,250,252,0.86))":t==="BusinessBrief"?"var(--dql-app-surface, rgba(255,255,255,0.90))":"var(--dql-app-surface, var(--surface, rgba(255,255,255,0.84)))"}function Vd({saving:t,error:r,pending:a,notice:i,onDismissError:s}){return r?e.jsxs("div",{role:"alert",style:Nr("var(--status-error, #c45555)"),children:[e.jsx(Er,{size:13}),e.jsxs("span",{style:{flex:1,minWidth:0},children:["Save failed — ",r]}),e.jsx("button",{type:"button",onClick:s,style:Kd,children:"Dismiss"})]}):t?e.jsxs("div",{role:"status",style:Nr("var(--text-secondary)"),children:[e.jsx(Un,{size:13})," Saving…"]}):a?e.jsxs("div",{role:"status",style:Nr("var(--status-warning, #b8860b)"),children:[e.jsx(Er,{size:13})," Layout preview not saved — Apply or Cancel to continue."]}):i?e.jsxs("div",{role:"status",style:Nr("var(--text-tertiary)"),children:[e.jsx(es,{size:13})," ",i]}):null}const Nr=t=>({display:"flex",alignItems:"center",gap:7,padding:"5px 12px",fontSize:11.5,color:t,borderBottom:"1px solid var(--border-subtle)"}),Kd={border:"none",background:"transparent",color:"inherit",cursor:"pointer",fontSize:11,fontWeight:700,textDecoration:"underline",padding:0};function Qd(t){const r={size:13,strokeWidth:2.2};switch(t){case"line":return e.jsx(nn,{...r});case"area":return e.jsx(Cs,{...r});case"pie":return e.jsx(Bs,{...r});case"donut":return e.jsx(Os,{...r});case"table":return e.jsx(on,{...r});case"kpi":return e.jsx(sn,{...r});case"gauge":return e.jsx(Vi,{...r});case"scatter":return e.jsx(Ls,{...r});case"heatmap":return e.jsx(Hs,{...r});case"histogram":return e.jsx(Rs,{...r});case"stacked-bar":return e.jsx(Ps,{...r});case"grouped-bar":return e.jsx(Is,{...r});case"funnel":return e.jsx(Zt,{...r});case"waterfall":return e.jsx(is,{...r});case"sankey":return e.jsx(ar,{...r});default:return e.jsx(an,{...r})}}function An(t){switch(t.component){case"BusinessBrief":return"Business summary";case"KpiMetric":return"KPI";case"TrendPanel":return"Trend";case"RankingPanel":return"Ranking";case"EvidenceTable":return"Evidence";case"PivotTable":return"Pivot";case"TrustCallout":return"Trust";case"ResearchActions":return"Analysis";case"NarrativePanel":return"Narrative";default:return t.role?St(t.role):"Generated"}}function Gd(t,r){const a=new RegExp(`^###\\s*${td(r)}\\s*`,"i");return t.replace(a,"").replace(/\*\*Trust:\*\*.*$/gim,"").replace(/\*\*Review status:\*\*.*$/gim,"").replace(/\*\*Next actions:\*\*[\s\S]*$/im,"").replace(/\*\*Review tasks:\*\*[\s\S]*$/im,"").trim().split(/\n{2,}/).map(n=>n.trim()).find(Boolean)||"Generated app section pending analyst review."}function Ot(t){return{border:"1px solid var(--dql-app-line, var(--border-color, rgba(0,0,0,0.12)))",borderRadius:8,background:t?"var(--dql-app-accent-soft, var(--surface-hover, rgba(0,0,0,0.06)))":"var(--dql-app-surface, var(--surface, rgba(0,0,0,0.02)))",color:"inherit",padding:"7px 10px",cursor:"pointer",fontSize:12,fontWeight:720,display:"inline-flex",alignItems:"center",gap:6,minHeight:32}}const Yd={width:34,height:34,border:"1px solid var(--dql-app-accent, #4f46e5)",borderRadius:8,background:"var(--dql-app-accent-soft, rgba(79,70,229,0.12))",color:"var(--dql-app-accent, #4f46e5)",cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center"},Xd={display:"flex",alignItems:"center",flexWrap:"wrap",gap:6,marginBottom:10,minWidth:0},In={border:"1px solid var(--border-subtle)",borderRadius:7,background:"var(--bg-1)",color:"var(--text-secondary)",padding:"4px 8px",cursor:"pointer",fontSize:10.5,fontWeight:720},Jd={...In,display:"inline-flex",alignItems:"center",gap:5,color:"var(--accent)",borderColor:"var(--accent-dim)"},Zd={position:"fixed",inset:0,zIndex:120,display:"grid",placeItems:"center",padding:24,background:"rgba(0, 0, 0, 0.38)"},Dd={width:"min(780px, calc(100vw - 32px))",maxHeight:"min(760px, calc(100vh - 48px))",overflow:"hidden",display:"grid",gap:12,padding:16,border:"1px solid var(--border-default)",borderRadius:12,background:"var(--bg-0)",color:"var(--text-primary)",boxShadow:"0 24px 80px rgba(0,0,0,0.28)"};function Ud(t){return{border:t?"1px solid var(--accent)":"1px solid var(--border-subtle)",borderRadius:7,background:t?"var(--accent-dim)":"var(--bg-1)",color:t?"var(--accent)":"var(--text-secondary)",padding:"5px 9px",cursor:"pointer",fontSize:11,fontWeight:750}}const ep={margin:0,minHeight:180,padding:14,borderRadius:8,background:"var(--bg-2)",color:"var(--text-primary)",whiteSpace:"pre-wrap",overflowWrap:"anywhere",fontFamily:"var(--font-mono, monospace)",fontSize:12,lineHeight:1.55},tp={marginBottom:12,color:"var(--dql-app-muted, var(--color-text-secondary, rgba(0,0,0,0.64)))",fontSize:12,lineHeight:1.45},Nn={border:"1px solid var(--dql-app-line-2, var(--border-color, rgba(15,23,42,0.10)))",borderRadius:10,background:"linear-gradient(180deg, rgba(255,255,255,0.96), rgba(248,250,252,0.88))",boxShadow:"0 8px 24px rgba(15,23,42,0.05)",padding:14,marginBottom:12,display:"grid",gap:9},Rn={display:"flex",alignItems:"flex-start",gap:10,minWidth:0},Tn={width:30,height:30,borderRadius:8,background:"var(--dql-app-accent-soft, rgba(79,70,229,0.10))",color:"var(--dql-app-accent, #4f46e5)",display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},Pn={fontSize:10.5,fontWeight:820,letterSpacing:0,textTransform:"uppercase",color:"var(--dql-app-muted, rgba(15,23,42,0.58))"},$n={margin:"2px 0 0",fontSize:15,lineHeight:1.25,fontWeight:820,color:"var(--dql-app-text, inherit)"},_n={margin:0,fontSize:13.5,lineHeight:1.48,color:"var(--dql-app-muted, rgba(15,23,42,0.72))"},Ja={display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},qr={border:"1px solid var(--dql-app-line, var(--border-color, rgba(15,23,42,0.10)))",borderRadius:999,background:"var(--dql-app-surface, rgba(255,255,255,0.78))",color:"var(--dql-app-muted, rgba(15,23,42,0.68))",padding:"3px 8px",fontSize:11,fontWeight:720,lineHeight:1.2,maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},En={...qr,color:"var(--dql-app-accent, #4f46e5)",borderColor:"rgba(79,70,229,0.22)",background:"var(--dql-app-accent-soft, rgba(79,70,229,0.08))"},Ti={border:"1px solid var(--dql-app-line-2, var(--border-color, rgba(15,23,42,0.14)))",borderRadius:8,background:"var(--dql-app-surface, var(--surface, #fff))",color:"var(--dql-app-text, var(--text-primary, #0f172a))",padding:"6px 10px",fontSize:11.5,fontWeight:720,cursor:"pointer"};function rp(t){return{position:"fixed",right:24,top:76,bottom:24,zIndex:70,width:t?`min(${ya}px, calc(100vw - 96px))`:`min(${cs}px, calc(100vw - 64px))`,minWidth:0}}const Pi={width:"100%",boxSizing:"border-box",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,background:"var(--surface, transparent)",color:"inherit",fontSize:12,padding:"8px 10px"},Bn={border:"1px solid var(--accent, #4f46e5)",borderRadius:6,background:"var(--accent, #4f46e5)",color:"var(--color-text-on-accent, #fff)",padding:"7px 11px",cursor:"pointer",fontSize:12,fontWeight:700},ap={border:"none",borderRadius:6,background:"transparent",color:"inherit",padding:"9px 10px",cursor:"pointer",textAlign:"left",display:"grid",gap:2},ip={position:"fixed",top:72,right:16,bottom:16,zIndex:120,width:"min(360px, calc(100vw - 32px))",boxSizing:"border-box",border:"1px solid var(--border-default)",borderRadius:12,padding:14,background:"var(--bg-0)",color:"var(--text-primary)",boxShadow:"0 22px 70px rgba(15,23,42,0.22)",display:"grid",alignContent:"start",gap:12,fontStyle:"normal",overflowY:"auto",overscrollBehavior:"contain"},np={position:"sticky",top:-14,zIndex:2,margin:"-14px -14px 0",padding:"13px 14px 11px",display:"flex",alignItems:"center",justifyContent:"space-between",gap:12,borderBottom:"1px solid var(--border-subtle)",background:"var(--bg-0)"},sp={width:30,height:30,padding:0,border:"1px solid var(--border-subtle)",borderRadius:7,background:"var(--bg-1)",color:"var(--text-secondary)",display:"inline-flex",alignItems:"center",justifyContent:"center",cursor:"pointer",flex:"none"},$i={display:"grid",gap:9,padding:12,border:"1px solid var(--border-subtle)",borderRadius:9,background:"var(--bg-1)"},_i={fontSize:10.5,fontWeight:820,textTransform:"uppercase",letterSpacing:"0.055em",color:"var(--text-tertiary)"},Ei={display:"grid",gridTemplateColumns:"repeat(2, minmax(0, 1fr))",gap:8},Na={display:"grid",gap:3,fontSize:10,fontWeight:700,opacity:.78},Ra={width:"100%",minWidth:0,boxSizing:"border-box",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:5,background:"var(--surface, transparent)",color:"inherit",padding:"5px 6px",fontSize:11},op={display:"grid",gap:6,paddingTop:9},Bi={border:"1px solid var(--border-subtle)",borderRadius:9,background:"var(--bg-1)",padding:"0 12px 11px"},Mi={cursor:"pointer",padding:"11px 0 0",color:"var(--text-secondary)",fontSize:11.5,fontWeight:760};function lp(t){return{border:"1px solid var(--accent, rgba(79,70,229,0.55))",background:t?"rgba(79,70,229,0.10)":"rgba(79,70,229,0.08)",color:"var(--accent, #4f46e5)",borderRadius:5,padding:"5px 7px",fontSize:11,fontWeight:750,display:"inline-flex",alignItems:"center",gap:5,cursor:t?"wait":"pointer",opacity:t?.72:1,whiteSpace:"nowrap"}}const Mn={fontSize:11,lineHeight:1.35,color:"var(--dql-app-muted, rgba(15,23,42,0.68))"},dp={...Mn,color:"var(--error-color, #b91c1c)"},pp={border:"1px solid var(--border-color, rgba(0,0,0,0.10))",borderRadius:4,background:"var(--surface, rgba(0,0,0,0.02))",color:"inherit",padding:"2px 5px",fontSize:10,cursor:"pointer",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},cp={marginTop:7,display:"flex",flexWrap:"wrap",gap:5,alignItems:"center",minWidth:0},qt={display:"inline-flex",alignItems:"center",minHeight:18,borderRadius:999,border:"1px solid var(--border-color, rgba(15,23,42,0.10))",background:"rgba(148,163,184,0.10)",color:"var(--dql-app-muted, rgba(15,23,42,0.70))",padding:"2px 7px",fontSize:10,fontWeight:720,lineHeight:1.1};function up(t){return{...qt,border:t?"1px solid rgba(22,163,74,0.26)":"1px solid rgba(217,119,6,0.28)",background:t?"rgba(22,163,74,0.10)":"rgba(245,158,11,0.12)",color:t?"#15803d":"#b45309",gap:4}}const xp={display:"inline-flex",alignItems:"center",gap:2,padding:2,border:"1px solid var(--border-color, rgba(15,23,42,0.12))",borderRadius:6,background:"rgba(255,255,255,0.74)",flexShrink:0};function gp(t){return{width:24,height:24,border:"none",borderRadius:4,background:t?"var(--dql-app-accent, var(--accent, #4f46e5))":"transparent",color:t?"var(--color-text-on-accent, #fff)":"inherit",cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:0}}function fp(t){return{width:"100%",alignSelf:"stretch",overflow:"auto",display:"flex",flexDirection:"column",gap:10,fontStyle:"normal",opacity:1,lineHeight:1.45,borderRadius:6,padding:t?10:0,background:t?"rgba(245,158,11,0.08)":"transparent"}}function mp(t){return{width:30,height:30,borderRadius:7,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,background:t?"rgba(245,158,11,0.14)":"rgba(79,70,229,0.10)",color:t?"#b45309":"var(--dql-app-accent, var(--accent, #4f46e5))"}}const hp={...qt,background:"rgba(79,70,229,0.08)",color:"var(--dql-app-accent, var(--accent, #4f46e5))",border:"1px solid rgba(79,70,229,0.16)"},bp={width:"100%",alignSelf:"stretch",overflow:"auto",display:"flex",flexDirection:"column",gap:9,fontStyle:"normal",opacity:1,lineHeight:1.35},vp={display:"grid",gap:6},yp={display:"grid",gridTemplateColumns:"minmax(0, 1fr)",gap:7,alignItems:"start",border:"1px solid var(--border-color, rgba(15,23,42,0.09))",borderRadius:7,background:"rgba(255,255,255,0.56)",padding:"7px 8px"},wp={...qt,minHeight:16,borderRadius:5,padding:"1px 5px",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},qp={display:"grid",gap:1,minWidth:82,textAlign:"left",fontSize:10.5},jp={...qt,minHeight:18,background:"rgba(22,163,74,0.09)",border:"1px solid rgba(22,163,74,0.18)",color:"#15803d"},ea={width:24,height:24,borderRadius:5,border:"1px solid var(--border-color, rgba(0,0,0,0.12))",background:"var(--surface, rgba(255,255,255,0.72))",color:"inherit",cursor:"pointer",padding:0,display:"inline-flex",alignItems:"center",justifyContent:"center"},kp={width:26,height:26,borderRadius:6,border:"1px solid var(--border-color, rgba(0,0,0,0.12))",background:"var(--surface, rgba(255,255,255,0.72))",color:"inherit",cursor:"grab",padding:0,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0},Sp={position:"absolute",top:"calc(100% + 6px)",right:0,zIndex:40,width:240,border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:8,background:"var(--color-bg, #fff)",boxShadow:"0 14px 38px rgba(0,0,0,0.16)",padding:6,display:"grid",gap:4},zp={border:"none",borderRadius:6,background:"transparent",color:"inherit",padding:"8px 9px",cursor:"pointer",textAlign:"left",display:"grid",gap:2};function Cp(t){return{border:`1px solid ${t?"var(--accent, #4f46e5)":"var(--border-color, rgba(0,0,0,0.12))"}`,borderRadius:999,background:t?"var(--color-bg-active, rgba(79,70,229,0.12))":"var(--surface, rgba(0,0,0,0.02))",color:t?"var(--accent, #4f46e5)":"inherit",padding:"4px 8px",fontSize:11,fontWeight:t?750:600,cursor:"pointer"}}const Li={border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:4,background:"var(--surface, rgba(0,0,0,0.02))",color:"inherit",padding:"3px 7px",cursor:"pointer",fontSize:11};function ma(t,r={w:6,h:3}){return{x:0,y:t.layout.items.reduce((i,s)=>Math.max(i,s.y+s.h),0),w:r.w,h:r.h}}function ha(t,r){const a=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"tile",i=new Set(t.layout.items.map(s=>s.i));if(!i.has(a))return a;for(let s=2;s<1e3;s++){const n=`${a}-${s}`;if(!i.has(n))return n}return`${a}-${Date.now()}`}function Ap(t,r){let a=0,i=0,s=0;return[...t].sort((n,o)=>n.y-o.y||n.x-o.x).map(n=>{const o=r===1?1:Math.min(r,Math.max(2,Math.ceil(n.w/2)));a+o>r&&(a=0,i+=s||n.h,s=0);const l={...n,x:a,y:i,w:o};return a+=o,s=Math.max(s,n.h),l})}function Ip({app:t}){var l,d;const{state:r,dispatch:a}=Ki(),[i,s]=p.useState(!1),n=p.useRef(null);p.useEffect(()=>{if(!i)return;const x=b=>{var m;(m=n.current)!=null&&m.contains(b.target)||s(!1)};return document.addEventListener("mousedown",x),()=>document.removeEventListener("mousedown",x)},[i]);const o=r.activePersona?`${r.activePersona.displayName??r.activePersona.userId} [${r.activePersona.roles.join(", ")}]`:"View as: Owner";return!t||t.members.length===0?e.jsx("span",{style:{fontSize:12,opacity:.6},children:o}):e.jsxs("div",{ref:n,style:{position:"relative"},children:[e.jsxs("button",{onClick:()=>s(x=>!x),style:{padding:"6px 12px",fontSize:12,background:"var(--surface, rgba(0,0,0,0.04))",border:"1px solid var(--border-color, rgba(0,0,0,0.1))",borderRadius:6,cursor:"pointer",color:"inherit",display:"inline-flex",alignItems:"center",gap:6},"aria-haspopup":"menu","aria-expanded":i,children:[e.jsx("span",{style:{fontSize:11,opacity:.65},children:"View as:"}),e.jsx("span",{style:{fontWeight:600},children:((l=r.activePersona)==null?void 0:l.displayName)??((d=r.activePersona)==null?void 0:d.userId)??"Owner"}),r.activePersona&&e.jsxs("span",{style:{fontSize:11,opacity:.7},children:["[",r.activePersona.roles.join(", "),"]"]}),e.jsx("span",{style:{fontSize:10,opacity:.6},children:"▾"})]}),i&&e.jsxs("div",{role:"menu",style:{position:"absolute",top:"100%",right:0,marginTop:4,minWidth:240,background:"var(--surface-elevated, #fff)",border:"1px solid var(--border-color, rgba(0,0,0,0.12))",borderRadius:6,boxShadow:"0 4px 12px rgba(0,0,0,0.08)",zIndex:50},children:[e.jsxs("button",{role:"menuitem",onClick:async()=>{await D.clearPersona(),a({type:"SET_ACTIVE_PERSONA",persona:null}),s(!1)},style:Fi(r.activePersona===null),children:[e.jsx("div",{style:{fontWeight:500},children:"Owner (local)"}),e.jsx("div",{style:{fontSize:11,opacity:.65},children:"Default — no RLS narrowing"})]}),e.jsx("div",{style:{height:1,background:"var(--border-color, rgba(0,0,0,0.08))",margin:"4px 0"}}),t.members.map(x=>{var b;return e.jsxs("button",{role:"menuitem",onClick:async()=>{const m=await D.setPersona(x.userId,t.id);a({type:"SET_ACTIVE_PERSONA",persona:m}),s(!1)},style:Fi(((b=r.activePersona)==null?void 0:b.userId)===x.userId),children:[e.jsx("div",{style:{fontWeight:500},children:x.displayName??x.userId}),e.jsxs("div",{style:{fontSize:11,opacity:.65},children:["[",x.roles.join(", "),"]",x.attributes&&Object.keys(x.attributes).length>0?` · ${Object.entries(x.attributes).map(([m,f])=>`${m}=${f}`).join(", ")}`:""]})]},x.userId)})]})]})}function Fi(t){return{display:"block",width:"100%",textAlign:"left",padding:"8px 12px",background:t?"var(--surface-hover, rgba(0,0,0,0.06))":"transparent",border:"none",cursor:"pointer",color:"inherit",fontSize:13}}function Np(t,r){const a=t.filter(i=>r==null?void 0:r.tiles.some(s=>{var n;return s.tileId===i&&((n=s.repair)==null?void 0:n.approvalEligible)===!1}));return{ready:t.length>0&&t.every(i=>r==null?void 0:r.tiles.some(s=>{var n;return s.tileId===i&&s.status==="ok"&&((n=s.repair)==null?void 0:n.approvalEligible)!==!1})),repairedTileIds:a}}function Rp(t){return t.preference==="expanded"?!0:t.preference==="collapsed"||t.loading?!1:t.appCount===0&&t.localDraftCount===0}const Tp=p.lazy(()=>oa(()=>import("./UnifiedAgentRunPanel-BjsTE6yf.js").then(t=>t.c),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14])).then(t=>({default:t.UnifiedAgentRunPanel})));p.lazy(()=>oa(()=>import("./usePersistedAgentThreadId-DpQXOEDw.js").then(t=>t.h),__vite__mapDeps([4,1,2,3,5,6,7,8,9,10])).then(t=>({default:t.StructuredAnswerText})));const Ta="Build an analytics app from my certified DQL blocks and available warehouse tables.",Pa="dql.apps.active-ai-build.v1";function Oi(){try{const t=window.localStorage.getItem(Pa);if(!t)return null;const r=JSON.parse(t);return typeof r.sessionId=="string"&&typeof r.prompt=="string"&&typeof r.createdAt=="string"?r:null}catch{return null}}function ba(t){try{t?window.localStorage.setItem(Pa,JSON.stringify(t)):window.localStorage.removeItem(Pa)}catch{}}const Pp={all:"All",drafts:"Local drafts",private:"Private",shared:"Shared",fav:"Favourites"};function $p(t){return t==="obsidian"||t==="dark"||t==="midnight"?"obsidian":t==="white"||t==="arctic"?"white":"paper"}function Sc(){var Hr,Vr,Sr;const t=ns(ss(j=>({activeAppExperience:j.activeAppExperience,activeAppId:j.activeAppId,activeAppDraftId:j.activeAppDraftId,activeAppSection:j.activeAppSection,activeDashboardId:j.activeDashboardId,apps:j.apps,appsLoading:j.appsLoading,authoredDomains:j.authoredDomains,themeMode:j.themeMode}))),r=Gi(),a=os(),{operations:i,track:s}=ls(),n=p.useMemo(()=>$p(t.themeMode),[t.themeMode]),[o,l]=p.useState(()=>t.activeAppDraftId?"create":t.activeAppId?"workspace":"library"),d=t.activeAppExperience,x=t.activeAppSection,b=j=>{r({type:"SET_APP_WORKSPACE_STATE",experience:j})},m=j=>{r({type:"SET_APP_WORKSPACE_STATE",section:j})},[f,y]=p.useState(""),[u,w]=p.useState("all"),[q,C]=p.useState(()=>new Set),[k,M]=p.useState(null),[L,X]=p.useState(null),[I,O]=p.useState(!1),[F,U]=p.useState("ai"),[_,A]=p.useState(!1),[te,Q]=p.useState("operational_dashboard"),[Y,S]=p.useState(Ta),[h,$]=p.useState(""),ee=p.useRef(!1),[W,$e]=p.useState("");p.useMemo(()=>ds(t.authoredDomains),[t.authoredDomains]);const[se,oe]=p.useState("analytics"),[Be,ue]=p.useState("stakeholders"),Ae=p.useRef(!1),[_e,Ie]=p.useState(null),[xe,Ze]=p.useState(()=>t.activeAppDraftId),[it,R]=p.useState([]),[le,ge]=p.useState(!1),[ve,Te]=p.useState(null),[de,Pe]=p.useState(()=>new Set),[Ge,Ye]=p.useState(null),[De,Ee]=p.useState(null),ze=p.useRef(Oi()),[Z,pe]=p.useState(((Hr=ze.current)==null?void 0:Hr.sessionId)??null),[ye,Ne]=p.useState(((Vr=ze.current)==null?void 0:Vr.operationId)??null),We=p.useRef(null),[Me,Ue]=p.useState(new Set),[we,nt]=p.useState(new Set),[Le,re]=p.useState({}),[lt,Ce]=p.useState(!1),[bt,ie]=p.useState(null),[dt,He]=p.useState(!1),[et,Re]=p.useState(!1),[gt,H]=p.useState(""),[ke,fe]=p.useState(!1),[qe,zt]=p.useState(null),[vt,Vt]=p.useState(null),[Dt,Ut]=p.useState(!1),[pr,pt]=p.useState(null),[_t,st]=p.useState(null),[Kt,Qt]=p.useState({}),[cr,er]=p.useState({}),[ur,xr]=p.useState(!1),[Gt,Yt]=p.useState(!1),ct=p.useCallback(j=>{xr(j),j||Yt(!1)},[]),ft=ua({queryKey:["apps"],queryFn:()=>D.listAppsStrict(),staleTime:3e4}),Nt=ua({queryKey:["app-builds"],queryFn:()=>D.listAppBuilds(),staleTime:1e4}),N=ua({queryKey:["persona"],queryFn:()=>D.getPersona(),staleTime:6e4});p.useEffect(()=>{r({type:"SET_APPS_LOADING",loading:ft.isLoading}),ft.data&&r({type:"SET_APPS",apps:ft.data})},[ft.data,ft.isLoading,r]),p.useEffect(()=>{N.data&&r({type:"SET_ACTIVE_PERSONA",persona:N.data})},[r,N.data]),p.useEffect(()=>{t.activeAppDraftId&&(Ze(t.activeAppDraftId),Ie(null),l("create"))},[t.activeAppDraftId]);const B=p.useCallback(j=>{var Se;if(Ee(j),Ze(null),l("create"),U("ai"),S(j.prompt||Ta),Ie(j.inputs.existingAppId??null),$e(Gr(j.inputs.domain,t.authoredDomains)),oe(j.inputs.owner??"analytics"),ue(j.inputs.audience??"stakeholders"),A(j.inputs.exploreGaps===!0),j.status==="building"){He(!0);return}if(He(!1),j.status==="error"){ie(j.error??"The App proposal did not complete.");return}ie(null),Ue(j.proposal?hs(j.proposal):new Set),re(Rt=>{var Kr;return Object.fromEntries((((Kr=j.proposal)==null?void 0:Kr.tiles)??[]).map(fr=>[fr.id,Rt[fr.id]??{title:fr.title,viz:fr.viz}]))});const E=j.plan;nt(new Set(Vp(E)));const ce=j.inputs.existingAppId?(Se=E==null?void 0:E.pages[0])==null?void 0:Se.title:E==null?void 0:E.name;ce&&$(Rt=>ee.current?Rt:ce),E!=null&&E.audience&&ue(Rt=>Ae.current?Rt:E.audience)},[t.authoredDomains]),g=p.useMemo(()=>Z?i.find(j=>j.id===ye)??i.find(j=>j.type==="app_ai_build"&&j.scope===`app-build:${Z}`)??null:null,[ye,Z,i]);p.useEffect(()=>{const j=ze.current;j&&(ze.current=null,S(j.prompt),Ie(j.existingAppId??null),U("ai"),He(!0),l("create"))},[]),p.useEffect(()=>{if(!Z)return;if(g!=null&&g.id&&g.id!==ye){Ne(g.id);const Se=Oi();(Se==null?void 0:Se.sessionId)===Z&&ba({...Se,operationId:g.id})}g&&(g.status==="queued"||g.status==="running")&&(!De||De.status==="building")&&(He(!0),l("create"));let j=!1,E;const ce=async()=>{var Rt;const Se=await D.getAppAiBuild(Z);if(!j){if(!Se||Se.status==="building"){if(Se&&B(Se),g&&["failed","cancelled","interrupted"].includes(g.status)){He(!1),ie(((Rt=g.error)==null?void 0:Rt.message)??(g.status==="cancelled"?"The App proposal was cancelled.":"The App proposal did not complete."));return}E=window.setTimeout(()=>{ce()},900);return}He(!1),!(We.current===Se.id&&(De==null?void 0:De.status)===Se.status)&&(We.current=Se.id,B(Se))}};return ce(),()=>{j=!0,E!==void 0&&window.clearTimeout(E)}},[g,B,ye,De==null?void 0:De.status,Z]),p.useEffect(()=>{if(!t.activeAppId||o!=="workspace"){M(null),X(null);return}let j=!1;O(!0);const E=D.getApp(t.activeAppId).then(Se=>{j||M(Se)}),ce=t.activeDashboardId?D.getDashboard(t.activeAppId,t.activeDashboardId).then(Se=>{j||X(Se)}):Promise.resolve().then(()=>{j||X(null)});return Promise.allSettled([E,ce]).finally(()=>{j||O(!1)}),()=>{j=!0}},[t.activeAppId,t.activeDashboardId,o]);const K=p.useMemo(()=>JSON.stringify(ci((L==null?void 0:L.dashboard)??null)),[L==null?void 0:L.dashboard]),me=p.useMemo(()=>ci((L==null?void 0:L.dashboard)??null),[L==null?void 0:L.dashboard,K]);p.useEffect(()=>{const j=me;Qt(E=>{const ce={};for(const Se of j)ce[Se.id]=E[Se.id]??$r(Se);return xi(E,ce)?E:ce}),er(E=>{const ce={};for(const Se of j)ce[Se.id]=E[Se.id]??$r(Se);return xi(E,ce)?E:ce})},[L==null?void 0:L.dashboard.id,K,me]);const rt=async(j,E,ce,Se)=>{r({type:"SET_APPS_LOADING",loading:!0});const Rt=await D.listApps();r({type:"SET_APPS",apps:Rt}),r({type:"SET_APPS_LOADING",loading:!1}),j&&r({type:"OPEN_APP",appId:j,dashboardId:E,...Se}),ce&&l(ce)},Ve=(((Sr=Nt.data)==null?void 0:Sr.drafts)??[]).filter(j=>j.state!=="project_published"),yt=t.appsLoading||ft.isLoading||Nt.isLoading,Xe=p.useMemo(()=>{const j=f.trim().toLowerCase();return t.apps.filter(E=>u==="drafts"||u==="private"&&sa(E)||u==="shared"&&!sa(E)||u==="fav"&&!q.has(E.id)?!1:j?[E.name,E.description??"",E.domain,E.audience??"",E.lifecycle??"",...E.tags??[],...E.owners??[],...E.dashboards.map(Se=>Se.title)].join(" ").toLowerCase().includes(j):!0)},[q,u,f,t.apps]),je=p.useMemo(()=>t.apps.find(j=>j.id===t.activeAppId)??null,[t.apps,t.activeAppId]),wt=p.useCallback(j=>{M(E=>E&&{...E,investigations:j})},[]),gr=(j,E="view")=>{if(E==="build"){Ie(j.id),Ze(null),U("classic"),Q("blank"),$(j.name),S(j.description??`Improve ${j.name} for ${j.audience??"stakeholders"}.`),$e(Gr(j.domain,t.authoredDomains)),ue(j.audience??"stakeholders"),ie(null),l("create");return}r({type:"OPEN_APP",appId:j.id,experience:E,section:"dashboards"}),l("workspace")},ut=j=>{ba(null),pe(null),Ne(null),Ie(null),Ze(null),U(j.mode==="ai"?"ai":"classic"),A(j.sourcePolicy==="include_review_required"),Q(j.template),S(j.mode==="ai"?j.prompt:"Create a governed analytical App"),$(j.mode==="manual"?j.name:""),$e(E=>Gr(E,t.authoredDomains)),ue("stakeholders"),Pe(new Set),ie(null),Ye(null),Ee(null),re({}),nt(new Set),l("create")},Mt=async(j,E)=>{const ce=t.activeAppId;if(!ce||!j.trim())return;const Se=await D.renameApp(ce,E?{pageTitle:j.trim(),dashboardId:E}:{name:j.trim()});if(!Se.ok){ie(Se.error);return}await rt(ce,E??t.activeDashboardId??void 0,"workspace")},Or=()=>{if(!t.activeAppId||!k)return;const j=gt.trim();if(!j){zt("Describe the business question this page should answer.");return}zt(null),ba(null),pe(null),Ne(null),Ie(t.activeAppId),Ze(null),U("ai"),S(j),$("New App page"),$e(Gr(k.app.domain,t.authoredDomains)),oe(k.app.owners[0]??"analytics"),ue(k.app.audience??"stakeholders");const E=k.app.publicationIntent==="personal"||!k.app.publicationIntent&&k.app.visibility==="private";A(E&&ke),Pe(new Set),ie(null),Ye(null),Ee(null),re({}),Re(!1),H(""),fe(!1),l("create")},tr=p.useMemo(()=>({...cr}),[cr]),jr=p.useCallback((j,E)=>{Qt(ce=>({...ce,[j.id]:Wl(j,E)}))},[]),pa=p.useCallback(()=>{er({...Kt})},[Kt]),kr=p.useCallback(()=>{const j=Object.fromEntries(me.map(E=>[E.id,$r(E)]));Qt(j),er(j)},[me]),ca=async()=>{if(!(!vt||Dt)){Ut(!0),pt(null);try{const j=await D.deleteApp(vt.id,vt.fingerprint);C(E=>{const ce=new Set(E);return ce.delete(vt.id),ce}),r({type:"SET_APPS",apps:t.apps.filter(E=>E.id!==vt.id)}),t.activeAppId===vt.id&&r({type:"CLOSE_APP"}),Vt(null),l("library"),await a.invalidateQueries({queryKey:["apps"]}),st({appName:vt.name,recoveryId:j.recoveryId})}catch(j){pt(j instanceof Error?j.message:String(j))}finally{Ut(!1)}}},Fe=async()=>{if(!_t)return;const j=_t;st(null);try{await D.restoreApp(j.recoveryId),await a.invalidateQueries({queryKey:["apps"]}),await a.invalidateQueries({queryKey:["app-builds"]}),await rt()}catch(E){ie(E instanceof Error?E.message:String(E))}},Wr=p.useCallback(()=>{r({type:"CLOSE_APP"}),M(null),X(null),Ie(null),Ze(null),l("library")},[r]);return e.jsxs("div",{className:`dql-apps-waterline dql-apps-theme-${n}`,children:[e.jsx("style",{children:Jo}),o==="library"?e.jsx(_p,{apps:Xe,allApps:t.apps,loading:yt,search:f,filter:u,favorites:q,localDrafts:Ve,onSearch:y,onFilter:w,onToggleFavorite:j=>{C(E=>{const ce=new Set(E);return ce.has(j)?ce.delete(j):ce.add(j),ce})},onStartStudio:ut,onContinueDraft:j=>{var E,ce;Ze(j.id),Ie(((E=j.baseApp)==null?void 0:E.appId)??null),U(j.authoringMode==="ai"?"ai":"classic"),Q(j.template),A(j.sourcePolicy==="include_review_required"),S(j.frame.goal),$(j.name),$e(((ce=j.pages[0])==null?void 0:ce.metadata.domain)??""),ue(j.frame.audience??"stakeholders"),l("create")},onOpenApp:gr,onDeleteApp:j=>{pt(null),Vt(j)}}):o==="create"?e.jsx(Io,{initialMode:F==="ai"?"ai":"manual",initialPrompt:Y,initialName:h,initialDraftId:xe,initialSourcePolicy:_?"include_review_required":"governed_only",initialTemplate:te,startImmediately:!0,baseAppId:_e,domain:W,audience:Be,themeMode:t.themeMode,onBack:Wr,onPublished:(j,E)=>{a.invalidateQueries({queryKey:["app-builds"]}),rt(j.id,E,"workspace",{experience:"view",section:"dashboards"})},onDraftDeleted:j=>{st(j),l("library"),a.invalidateQueries({queryKey:["app-builds"]})}}):e.jsx(Fp,{app:je,appDoc:k,dashboardDoc:L,loading:I,experience:d,section:x,explainOpen:ur,explainExpanded:Gt,dashboardFilters:me,dashboardFilterValues:Kt,themeMode:t.themeMode,variables:tr,onBack:Wr,onExperienceChange:j=>{j==="build"&&je?gr(je,"build"):b(j)},onSectionChange:m,onDashboardFilterChange:jr,onApplyDashboardFilters:pa,onResetDashboardFilters:kr,onExplainChange:ct,onExplainExpandedChange:Yt,onAddPage:()=>{fe(!1),Re(!0)},onOpenDashboard:j=>r({type:"OPEN_DASHBOARD",dashboardId:j}),onOpenApp:(j,E,ce)=>{if(ce){Ze(ce),Ie(null),r({type:"OPEN_APP_DRAFT",draftId:ce,appId:j,dashboardId:E}),l("create");return}rt(j,E,"workspace",{experience:"build",section:"dashboards"})},onRenameApp:(j,E)=>void Mt(j,E),onDashboardChanged:j=>{X(E=>E&&{...E,dashboard:j}),rt(t.activeAppId,j.id,"workspace")},onInvestigationsChanged:wt,onOpenLineageNode:j=>{r({type:"OPEN_LINEAGE_DETAIL",nodeId:j,returnTo:t.activeAppId?{view:"apps",appId:t.activeAppId,dashboardId:t.activeDashboardId,label:je==null?void 0:je.name,experience:d,section:x}:null})}}),et&&e.jsx(Dp,{title:gt,allowExploration:(k==null?void 0:k.app.publicationIntent)==="personal"||!(k!=null&&k.app.publicationIntent)&&(k==null?void 0:k.app.visibility)==="private",exploreGaps:ke,error:qe,onChange:H,onExploreGapsChange:fe,onCancel:()=>{Re(!1),fe(!1),zt(null)},onCreate:Or}),vt&&e.jsx(Mp,{app:vt,deleting:Dt,error:pr,onCancel:()=>{Dt||(Vt(null),pt(null))},onConfirm:()=>void ca()}),_t?e.jsxs("div",{className:"dql-app-delete-undo",role:"status",children:[e.jsxs("span",{children:[e.jsx("strong",{children:_t.appName})," moved to local recovery."]}),e.jsx("button",{type:"button",onClick:()=>void Fe(),children:"Undo"}),e.jsx("button",{type:"button","aria-label":"Dismiss delete recovery message",onClick:()=>st(null),children:"×"})]}):null]})}function _p({apps:t,allApps:r,loading:a,search:i,filter:s,favorites:n,localDrafts:o,onSearch:l,onFilter:d,onToggleFavorite:x,onStartStudio:b,onContinueDraft:m,onOpenApp:f,onDeleteApp:y}){const u=Up(r,o,n),[w,q]=p.useState({mode:"ai",prompt:Ta,name:"Untitled Analytics App",template:"operational_dashboard",sourcePolicy:"governed_only"}),[C,k]=p.useState("auto"),M=Rp({preference:C,loading:a,appCount:r.length,localDraftCount:o.length}),L=i.trim().toLowerCase(),X=s==="all"||s==="drafts"?o.filter(O=>{var F;return!L||[O.name,O.frame.goal,O.frame.audience??"",((F=O.pages[0])==null?void 0:F.metadata.domain)??"",O.authoringMode].join(" ").toLowerCase().includes(L)}):[],I=X.length>0||t.length>0;return e.jsxs("main",{className:"dql-apps-wrap",children:[e.jsx("div",{id:"app-studio-launcher",hidden:!M,children:M?e.jsx(Co,{config:w,onChange:O=>q(F=>({...F,...O})),onSubmit:()=>b(w)}):null}),e.jsxs("section",{className:"dql-apps-library-head","aria-labelledby":"app-library-title",children:[e.jsxs("div",{children:[e.jsx("span",{className:"dql-app-eyebrow",children:"Your workspace"}),e.jsx("h2",{id:"app-library-title",children:"Apps"}),e.jsx("p",{children:"Local drafts and Project-published Apps live together here, with their visibility and trust state always clear."})]}),e.jsxs("div",{className:"dql-apps-library-summary","aria-label":"App library summary",children:[e.jsxs("button",{type:"button",className:"dql-app-card-act primary","aria-controls":"app-studio-launcher","aria-expanded":M,onClick:()=>k(M?"collapsed":"expanded"),children:[M?e.jsx(dr,{size:13,"aria-hidden":"true"}):e.jsx(xt,{size:13,"aria-hidden":"true"}),M?"Hide new App form":"Build new App"]}),e.jsxs("span",{children:[e.jsx("strong",{children:o.length})," local draft",o.length===1?"":"s"]}),e.jsxs("span",{children:[e.jsx("strong",{children:u.private})," private"]}),e.jsxs("span",{children:[e.jsx("strong",{children:u.shared})," shared"]})]})]}),e.jsxs("div",{className:"dql-apps-libbar",children:[e.jsx("div",{className:"dql-apps-filter-tabs",children:["all","drafts","private","shared","fav"].map(O=>e.jsxs("button",{className:s===O?"on":"",onClick:()=>d(O),children:[Pp[O]," ",e.jsx("span",{children:u[O]})]},O))}),e.jsxs("label",{className:"dql-apps-search",children:[e.jsx(jt,{size:15,strokeWidth:2,"aria-hidden":"true"}),e.jsx("input",{value:i,onChange:O=>l(O.target.value),placeholder:"Search apps, domains, owners..."})]})]}),a&&r.length===0&&o.length===0?e.jsx(kt,{title:"Loading Apps...",detail:"Reading local app files from this DQL project."}):I?e.jsxs("div",{className:"dql-apps-grid","aria-label":"App library",children:[X.map(O=>e.jsx(Ep,{draft:O,onOpen:()=>m(O)},O.id)),t.map(O=>e.jsx(Bp,{app:O,favorite:n.has(O.id),onToggleFavorite:()=>x(O.id),onOpen:()=>f(O,"view"),onEdit:()=>f(O,"build"),onDelete:()=>y(O)},O.id))]}):e.jsx(kt,{title:"No Apps match this view.",detail:"Change the filter or start a new App above. New work always begins as a local private draft."})]})}function Ep({draft:t,onOpen:r}){var s;const a=t.reviewTasks.some(n=>n.status==="open"),i=((s=t.pages[0])==null?void 0:s.metadata.domain)||"Local workspace";return e.jsxs("article",{className:"dql-app-card dql-app-draft-card",children:[e.jsxs("div",{className:"dql-app-card-body",onClick:r,role:"button",tabIndex:0,onKeyDown:n=>{(n.key==="Enter"||n.key===" ")&&r()},children:[e.jsxs("div",{className:"dql-app-card-top",children:[e.jsxs("div",{className:"dql-app-card-labels",children:[e.jsx("span",{className:"dql-app-eyebrow",children:i}),e.jsxs("span",{className:"dql-app-visibility private",children:[e.jsx(Qe,{size:12})," Private draft"]})]}),e.jsx("span",{className:"dql-app-draft-mark",children:e.jsx(At,{size:15})})]}),e.jsx(br,{tone:a?"draft":"agentic",children:a?"review required":"local draft"}),e.jsx("h3",{children:t.name}),e.jsx("p",{children:Oa(t.frame.goal||"A private App draft ready to shape in Studio.")}),e.jsxs("div",{className:"dql-app-card-mini",children:[e.jsx(vr,{label:"Pages",value:String(t.pages.length)}),e.jsx(vr,{label:"Mode",value:t.authoringMode==="ai"?"AI + manual":"Manual"}),e.jsx(vr,{label:"Revision",value:String(t.revision)})]}),e.jsxs("div",{className:"dql-app-card-signals",children:[e.jsxs("span",{children:[e.jsx(Qe,{size:13})," Not in Project source"]}),e.jsxs("span",{children:[e.jsx(ht,{size:13})," ",t.sourcePolicy==="include_review_required"?"Review lane enabled":"Governed sources"]})]})]}),e.jsxs("div",{className:"dql-app-card-depth",children:[e.jsx("span",{children:"Saved locally"}),e.jsxs("button",{type:"button",className:"dql-app-card-act primary",onClick:r,children:["Continue ",e.jsx(qs,{size:12})]})]})]})}function Bp({app:t,favorite:r,onToggleFavorite:a,onOpen:i,onEdit:s,onDelete:n}){var u,w;const[o,l]=p.useState(!1),d=t.certification==="certified"||t.lifecycle==="certified",x=((u=t.drafts)==null?void 0:u.length)??0,b=t.investigations??0,m=t.aiPins??0,f=sa(t),y=d?"Certified app":x>0||b>0||m>0?"Review needed":"Draft app";return e.jsxs("article",{className:"dql-app-card",children:[e.jsxs("div",{className:"dql-app-card-body",onClick:i,role:"button",tabIndex:0,children:[e.jsxs("div",{className:"dql-app-card-top",children:[e.jsxs("div",{className:"dql-app-card-labels",children:[e.jsx("span",{className:"dql-app-eyebrow",children:t.domain||"Domain"}),e.jsxs("span",{className:`dql-app-visibility ${f?"shared":"private"}`,children:[f?e.jsx(po,{size:12}):e.jsx(Qe,{size:12}),f?"Shared Project":"Private Project"]})]}),e.jsx("button",{type:"button",className:`dql-app-star ${r?"on":""}`,onClick:q=>{q.stopPropagation(),a()},"aria-label":r?"Remove favourite":"Add favourite",children:e.jsx(js,{size:14,strokeWidth:1.8})})]}),e.jsx(br,{tone:d?"certified":x>0?"draft":"agentic",children:d?"certified":x>0?"mixed":t.lifecycle??"draft"}),e.jsx("h3",{children:t.name}),e.jsx("p",{children:Oa(t.description||`${t.name} consumption surface for ${t.domain}.`)}),e.jsxs("div",{className:"dql-app-card-mini",children:[e.jsx(vr,{label:"Pages",value:String(t.dashboards.length)}),e.jsx(vr,{label:"Books",value:String(((w=t.notebooks)==null?void 0:w.length)??0)}),e.jsx(vr,{label:"Drafts",value:String(x)})]}),e.jsxs("div",{className:"dql-app-card-signals",children:[e.jsxs("span",{children:[e.jsx(Qe,{size:13})," ",y]}),e.jsxs("span",{children:[e.jsx(jt,{size:13})," ",b," analysis"]}),e.jsxs("span",{children:[e.jsx(ht,{size:13})," ",m," local insights"]})]})]}),e.jsxs("div",{className:"dql-app-card-depth",children:[e.jsx("span",{children:ec(t)}),e.jsxs("button",{type:"button",className:"dql-app-card-act",onClick:i,title:"View app",children:[e.jsx(Yi,{size:12})," View"]}),e.jsxs("button",{type:"button",className:"dql-app-card-act",onClick:s,title:"Edit app",children:[e.jsx(Di,{size:12})," Edit"]}),e.jsxs("div",{className:"dql-app-card-menu",children:[e.jsx("button",{type:"button",className:"dql-app-card-act",onClick:q=>{q.stopPropagation(),l(C=>!C)},title:"More App actions","aria-expanded":o,children:e.jsx(ta,{size:14})}),o?e.jsx("div",{role:"menu",children:e.jsxs("button",{type:"button",role:"menuitem",className:"danger",onClick:q=>{q.stopPropagation(),l(!1),n()},children:[e.jsx(ir,{size:13})," Delete App"]})}):null]})]})]})}function Mp({app:t,deleting:r,error:a,onCancel:i,onConfirm:s}){const[n,o]=p.useState(""),l=n.trim()===t.name;return e.jsx("div",{className:"dql-app-delete-backdrop",role:"presentation",onMouseDown:d=>{d.target===d.currentTarget&&i()},children:e.jsxs("section",{className:"dql-app-delete-dialog",role:"dialog","aria-modal":"true","aria-labelledby":"delete-app-title",children:[e.jsxs("div",{className:"dql-app-delete-heading",children:[e.jsx("span",{className:"dql-app-delete-icon",children:e.jsx(ir,{size:16})}),e.jsxs("div",{children:[e.jsxs("h2",{id:"delete-app-title",children:["Delete ",t.name,"?"]}),e.jsx("p",{children:"Its project files and App-scoped local context move to recoverable local trash. Source control will show the canonical project files as deleted."})]})]}),e.jsxs("label",{className:"dql-app-delete-confirm",children:["Type ",e.jsx("strong",{children:t.name})," to confirm",e.jsx("input",{autoFocus:!0,value:n,onChange:d=>o(d.target.value),onKeyDown:d=>{d.key==="Enter"&&l&&!r&&s()},disabled:r})]}),a?e.jsx("div",{className:"dql-app-delete-error",role:"alert",children:a}):null,e.jsxs("div",{className:"dql-app-delete-actions",children:[e.jsx("button",{type:"button",className:"secondary",onClick:i,disabled:r,children:"Cancel"}),e.jsx("button",{type:"button",className:"danger",onClick:s,disabled:!l||r,children:r?"Deleting…":"Delete App"})]})]})})}async function Lp(t){const r=new TextEncoder().encode(JSON.stringify(t)),a=await crypto.subtle.digest("SHA-256",r);return`sha256:${Array.from(new Uint8Array(a)).map(i=>i.toString(16).padStart(2,"0")).join("")}`}function Fp({app:t,appDoc:r,dashboardDoc:a,loading:i,experience:s,section:n,explainOpen:o,explainExpanded:l,dashboardFilters:d,dashboardFilterValues:x,themeMode:b,variables:m,onBack:f,onExperienceChange:y,onRenameApp:u,onSectionChange:w,onDashboardFilterChange:q,onApplyDashboardFilters:C,onResetDashboardFilters:k,onExplainChange:M,onExplainExpandedChange:L,onAddPage:X,onOpenDashboard:I,onOpenApp:O,onDashboardChanged:F,onInvestigationsChanged:U,onOpenLineageNode:_}){var gt;const A=Gi(),te=(a==null?void 0:a.dashboard.layout.items.filter(H=>!!H.block).length)??0,Q=((gt=r==null?void 0:r.drafts)==null?void 0:gt.length)??0,Y=p.useMemo(()=>Ln((a==null?void 0:a.dashboard)??null).map(H=>H.blockId),[a]),S=Y.join("|"),[h,$]=p.useState(Y[0]??null),[ee,W]=p.useState(null),[$e,se]=p.useState(null),[oe,Be]=p.useState(null),[ue,Ae]=p.useState(null),[_e,Ie]=p.useState("idle"),[xe,Ze]=p.useState(""),[it,R]=p.useState("idle"),[le,ge]=p.useState(""),ve=(a==null?void 0:a.dashboard.layout.items.filter(H=>H.semantic).map(H=>H.i))??[],{ready:Te,repairedTileIds:de}=Np(ve,ee),Pe=p.useCallback(H=>{W(H)},[]),[Ge,Ye]=p.useState(!1),[De,Ee]=p.useState(null),ze=p.useMemo(()=>Rl((a==null?void 0:a.dashboard)??null,ee),[a,ee]),Z=p.useCallback(H=>Cl((a==null?void 0:a.dashboard)??null,H,ee),[a,ee]),pe=p.useCallback(async H=>{var zt;if(!(t!=null&&t.id)||!a)return;const ke=((zt=a.app)==null?void 0:zt.id)??t.id;if(ke!==t.id){Ee("This page belongs to a different app than the one open. Reload the app and try again.");return}Ye(!0),Ee(null);const fe=await D.saveDashboard(ke,a.dashboard.id,{...H});if(Ye(!1),!fe.ok){Ee(fe.error);return}const qe=await D.getDashboard(t.id,a.dashboard.id);qe!=null&&qe.dashboard&&(F==null||F(qe.dashboard))},[t==null?void 0:t.id,a,F]),ye=p.useCallback(H=>{if(!a)return;const ke=Al(a.dashboard,H,ee);ke!==a.dashboard&&pe(ke)},[a,ee,pe]),[Ne,We]=p.useState([]);p.useEffect(()=>{We([])},[a==null?void 0:a.dashboard.id]);const Me=p.useCallback((H,ke)=>{We(fe=>fe.some(qe=>qe.column===H)?fe:[...fe,{id:H,column:H}]),q({id:H,type:"select",bindsTo:H},ke),C()},[C,q]),Ue=p.useCallback(H=>{ye(H),We(ke=>ke.filter(fe=>fe.column!==H))},[ye]),we=p.useCallback(H=>{a&&pe(Il(a.dashboard,H))},[a,pe]);p.useCallback(H=>{Be({...H,nonce:Date.now()}),w("research"),M(!0)},[M,w]);const nt=p.useCallback(H=>{Ae(H)},[]),Le=p.useCallback(()=>{Be(null)},[]),re=p.useCallback((H,ke)=>{var fe,qe;if($(H),s==="view"){A({type:"OPEN_GLOBAL_AI",audience:"stakeholder",context:{title:"App copilot",scopeHint:hr(t==null?void 0:t.name)?`Follow up on ${hr(t==null?void 0:t.name)}`:"Follow up on this tile",selectedObject:{kind:"block",id:H,title:a==null?void 0:a.dashboard.metadata.title},workspaceContext:{appId:t==null?void 0:t.id,dashboardId:a==null?void 0:a.dashboard.id,blockId:H},suggestedQuestions:(qe=(fe=a==null?void 0:a.app)==null?void 0:fe.copilot)==null?void 0:qe.suggestedQuestions},autoRun:{text:ke,mode:"auto"}});return}M(!0),se({text:ke,nonce:Date.now()})},[A,s,t==null?void 0:t.id,t==null?void 0:t.name,a==null?void 0:a.dashboard.id,a==null?void 0:a.dashboard.metadata.title,M]);p.useEffect(()=>{s==="view"&&(n==="notebooks"||n==="ai"||n==="drafts"||n==="settings")&&w("dashboards")},[s,n,w]),p.useEffect(()=>{if(Y.length===0){h!==null&&$(null);return}(!h||!Y.includes(h))&&$(Y[0])},[Y,S,h]),p.useEffect(()=>{W(null),Ae(null)},[t==null?void 0:t.id,a==null?void 0:a.dashboard.id]);const lt=!!(t&&a&&(n==="dashboards"||n==="research")),Ce=lt&&o,bt=H=>{Ie(H),H!=="ready"&&window.setTimeout(()=>Ie("idle"),1800)},ie=async()=>{var fe;const H=Jp(t,r,a);Ze(H);let ke=!1;try{typeof navigator<"u"&&((fe=navigator.clipboard)!=null&&fe.writeText)&&(await navigator.clipboard.writeText(H),ke=!0)}catch{ke=!1}if(!ke){const qe=document.createElement("textarea");qe.value=H,qe.style.position="fixed",qe.style.left="-9999px",document.body.appendChild(qe),qe.focus(),qe.select(),ke=document.execCommand("copy"),document.body.removeChild(qe)}bt(ke?"copied":"ready")},dt=()=>{const H=Zp(t,r,a),ke=new Blob([H],{type:"text/markdown;charset=utf-8"}),fe=URL.createObjectURL(ke),qe=document.createElement("a");qe.href=fe,qe.download=`${(t==null?void 0:t.id)??(r==null?void 0:r.app.id)??"dql-app"}-brief.md`,document.body.appendChild(qe),qe.click(),document.body.removeChild(qe),URL.revokeObjectURL(fe),bt("downloaded")},He=async()=>{if(!(t!=null&&t.id))return;R("running"),ge("");const H=await D.publishAppToProject(t.id,{lifecycle:"review"});if(!H.ok){R("error"),ge(H.error);return}R("done"),ge(`${H.paths.length} shared files published from the private draft${H.removedLocalTiles?`; ${H.removedLocalTiles} local-only insight removed`:""}.`),window.setTimeout(()=>R("idle"),2400)},et=async()=>{if(!(t!=null&&t.id)||!a||!ee||ve.length===0)return;R("running"),ge("");const H=await Lp(a.dashboard),ke=await D.approveAppSemanticTiles(t.id,a.dashboard.id,{runId:ee.runId,tileIds:ve,expectedDashboardFingerprint:H});if(!ke.ok){R("error"),ge(ke.error);return}F(ke.dashboard),R("done"),ge(`${ve.length} semantic result${ve.length===1?"":"s"} approved with run ${ee.runId}.`)},Re=n==="dashboards"&&!!a;return e.jsxs("div",{className:"dql-app-workspace",children:[e.jsxs("div",{className:"dql-app-view-topbar",children:[e.jsxs("button",{type:"button",className:"dql-app-back dql-app-back-label",onClick:f,title:"Back to apps",children:[e.jsx(_r,{size:14}),e.jsx("span",{children:"Apps"})]}),e.jsx("span",{className:"dql-app-crumb",children:e.jsx("b",{children:(t==null?void 0:t.id)??"app"})}),e.jsx(br,{tone:"certified",children:Q>0?`${te} certified`:"All certified"}),Q>0?e.jsxs(br,{tone:"draft",children:[Q," draft"]}):null,e.jsx("span",{className:"dql-app-topbar-divider","aria-hidden":"true"}),e.jsxs("div",{className:"dql-app-modeseg",role:"group","aria-label":"App mode",children:[e.jsxs("button",{type:"button",className:s==="view"?"on":"",onClick:()=>y("view"),title:"Clean stakeholder view",children:[e.jsx(Yi,{size:12})," View"]}),e.jsxs("button",{type:"button",className:s==="build"?"on":"",onClick:()=>y("build"),title:"Rearrange tiles and edit this app",children:[e.jsx(Di,{size:12})," Edit"]})]}),e.jsxs("div",{className:"dql-app-view-actions",children:[e.jsx(Ip,{app:(r==null?void 0:r.app)??null}),s==="build"&&ve.length>0?e.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>void et(),disabled:it==="running"||!Te,title:Te?"Approve the successful semantic run for publication":de.length>0?"AI-repaired semantic previews are review-required and cannot be approved as governed semantic results":"Run this dashboard successfully before semantic approval",children:[e.jsx(Pt,{size:14})," Approve semantic (",ve.length,")"]}):null,s==="build"?e.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>void He(),disabled:it==="running",children:[e.jsx(Qe,{size:14})," ",it==="running"?"Checking":"Publish to Project"]}):null,e.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line dql-apps-btn-icon",title:_e==="copied"?"Copied handoff":"Share local app handoff",onClick:()=>void ie(),children:_e==="copied"?e.jsx(Pt,{size:15}):e.jsx(eo,{size:15})}),e.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line dql-apps-btn-icon",title:_e==="downloaded"?"Brief saved":"Download app brief",onClick:dt,children:_e==="downloaded"?e.jsx(Pt,{size:15}):e.jsx(ps,{size:15})}),_e==="ready"?e.jsxs("div",{className:"dql-app-share-popover",children:[e.jsx("b",{children:"Local handoff"}),e.jsx("textarea",{readOnly:!0,value:xe,onFocus:H=>H.currentTarget.select()})]}):null,it==="done"||it==="error"?e.jsx("div",{className:`dql-app-promote-popover ${it==="error"?"error":""}`,children:le}):null]})]}),e.jsxs("main",{className:"dql-app-view-wrap",children:[e.jsxs("div",{className:"dql-app-title-row",children:[e.jsxs("div",{className:"dql-app-title-copy",children:[e.jsxs("div",{className:"dql-app-title-meta",children:[e.jsxs("span",{children:[e.jsx(At,{size:14})," ",(t==null?void 0:t.domain)??(a==null?void 0:a.dashboard.metadata.domain)??"DQL App"]}),Re?s==="build"&&t?e.jsx("span",{className:"dql-app-title-context",children:e.jsx(Wi,{variant:"compact",value:hr(t.name)||"App",label:"App name",onCommit:H=>void u(H)},`${t.id}:name`)}):e.jsx("span",{className:"dql-app-title-context",children:hr(t==null?void 0:t.name)||"App"}):null,s==="build"?e.jsx(br,{tone:"draft",children:"Customizing"}):null]}),s==="build"&&t?e.jsx(Wi,{value:hr(Re?a==null?void 0:a.dashboard.metadata.title:t.name)||"App",label:Re?"Page name":"App name",onCommit:H=>void u(H,Re?a==null?void 0:a.dashboard.id:void 0)},`${t.id}:${Re?(a==null?void 0:a.dashboard.id)??"":"app"}`):e.jsx("h1",{children:hr(Re?a==null?void 0:a.dashboard.metadata.title:t==null?void 0:t.name)||"App"}),e.jsx("p",{children:Oa((Re?a==null?void 0:a.dashboard.metadata.description:t==null?void 0:t.description)??"Local DQL App")})]}),e.jsxs("div",{className:"dql-app-nav-row",children:[e.jsx(Op,{appDoc:r,section:n,experience:s,onChange:w}),n==="dashboards"&&(r!=null&&r.dashboards.length)?e.jsx(Wp,{dashboards:r.dashboards,activeDashboardId:a==null?void 0:a.dashboard.id,isBuild:s==="build",onOpen:I,onAdd:X}):null,lt?e.jsx("button",{type:"button",className:`dql-apps-btn dql-apps-btn-line dql-apps-btn-icon ${o?"on":""}`,title:o?"Hide AI copilot":"Show AI copilot",onClick:()=>M(!o),children:e.jsx(nr,{size:15})}):null,Re?e.jsx(e.Fragment,{children:e.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line dql-apps-btn-icon",title:"Open dashboard lineage",onClick:()=>{t&&a&&_(`dashboard:${t.id}/${a.dashboard.id}`)},children:e.jsx(Qi,{size:15})})}):null]})]}),e.jsxs("div",{className:`dql-app-view-layout ${Ce?"":"no-explain"}`,children:[e.jsxs("div",{className:"dql-app-main-column",children:[n==="dashboards"&&a&&(d.length>0||ze.length>0||s==="build")?e.jsxs("section",{className:"dql-app-filter-row","aria-label":"Dashboard filters",children:[e.jsxs("div",{className:"dql-app-filter-row-copy",children:[e.jsx("b",{children:"Filters"}),e.jsx("span",{children:"Set the business scope, then apply once to refresh the full story."})]}),d.length>0?e.jsxs(e.Fragment,{children:[e.jsx(Bl,{filters:d,values:x,onChange:q}),d.some(H=>Z(H.id).unaffected.length>0)?e.jsx("div",{className:"dql-app-filter-runtime-coverage","aria-label":"Filter coverage",children:d.map(H=>{const ke=Z(H.id);return ke.unaffected.length===0?null:e.jsxs("span",{className:`dql-app-filter-coverage ${ke.applied.length===0?"is-none":"is-partial"}`,title:`Unaffected: ${ke.unaffected.map(fe=>`${fe.title??fe.tileId}${fe.reason?` — ${fe.reason}`:""}`).join("; ")}`,children:[Oe(H.id)," affects ",ke.applied.length," of ",ke.filterable," tiles"]},H.id)})}):null,e.jsxs("div",{className:"dql-app-filter-row-actions",children:[e.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:k,children:"Reset"}),e.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-primary",onClick:C,children:"Apply filters"})]})]}):null,e.jsx(Ml,{candidates:ze,coverageFor:Z,onApply:Me}),Ne.length>0?e.jsxs("div",{className:"dql-app-filter-session",children:[e.jsx("span",{children:"Your filters, this session only."}),s==="build"?Ne.map(H=>e.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",disabled:Ge,onClick:()=>Ue(H.column),children:["Save “",Oe(H.column),"” to page"]},H.id)):null]}):null,s==="build"?e.jsx(Ll,{filters:a.dashboard.filters??[],candidates:ze,coverageFor:Z,onAdd:ye,onRemove:we,busy:Ge}):null,De?e.jsx("div",{className:"dql-app-filter-error",role:"alert",children:De}):null]}):null,i?e.jsx(kt,{title:"Loading app...",detail:"Reading dashboard files and running local blocks."}):n==="dashboards"&&a&&t?e.jsx(hd,{appId:t.id,dashboard:a.dashboard,editable:s==="build",embeddedHeader:!0,variables:m,selectedBlockId:h,onBlockFocus:$,onAskBlock:re,onOpenLineageNode:_,copilotOpen:o,onCopilotChange:M,onDashboardChanged:F,onRunChange:Pe}):n==="notebooks"?e.jsx(Zo,{appDoc:r}):n==="research"?e.jsx(al,{appDoc:r,dashboardDoc:a,seed:oe,themeMode:b,onSeedHandled:Le,onDashboardChanged:F,onInvestigationsChanged:U,onActiveInvestigationChange:nt}):n==="ai"?e.jsx(Do,{appDoc:r}):n==="drafts"?e.jsx(Uo,{appDoc:r}):n==="settings"?e.jsx(el,{appDoc:r}):e.jsx(kt,{title:"No dashboard page selected.",detail:"Choose a dashboard page or add one in Build mode."})]}),Ce?e.jsx(Hp,{app:t,appDoc:r,dashboardDoc:a,dashboardRun:ee,variables:m,selectedBlockId:h,askSeed:$e,themeMode:b,expanded:l,onToggleExpanded:()=>L(!l),onClose:()=>M(!1),onOpenApp:O}):null]})]})]})}function Wi({value:t,label:r,onCommit:a,variant:i="title"}){const[s,n]=p.useState(t);return p.useEffect(()=>{n(t)},[t]),e.jsx("input",{className:i==="compact"?"dql-app-title-input dql-app-title-input-compact":"dql-app-title-input","aria-label":r,title:`${r} — press Enter to save`,value:s,size:i==="compact"?Math.max(8,Math.min(36,s.length+1)):void 0,maxLength:120,onChange:o=>n(o.target.value),onBlur:()=>{const o=s.trim();o&&o!==t?a(o):n(t)},onKeyDown:o=>{o.key==="Enter"&&o.currentTarget.blur(),o.key==="Escape"&&(n(t),o.currentTarget.blur())}})}function Op({appDoc:t,section:r,experience:a,onChange:i}){var l,d,x,b,m;const s=((l=t==null?void 0:t.investigations)==null?void 0:l.length)??0,n={id:"dashboards",label:"Canvas",count:(t==null?void 0:t.dashboards.length)??0,icon:e.jsx(At,{size:14})},o=[{id:"research",label:"Analysis & evidence",count:s,icon:e.jsx(jt,{size:14})},{id:"notebooks",label:"Source notebooks",count:((d=t==null?void 0:t.notebooks)==null?void 0:d.length)??((x=t==null?void 0:t.app.notebooks)==null?void 0:x.length)??0,icon:e.jsx(Ui,{size:14})},{id:"ai",label:"Saved insights",count:((b=t==null?void 0:t.aiPins)==null?void 0:b.length)??0,icon:e.jsx(nr,{size:14})},{id:"drafts",label:"Review drafts",count:((m=t==null?void 0:t.drafts)==null?void 0:m.length)??0,icon:e.jsx(mt,{size:14})},{id:"settings",label:"App settings",icon:e.jsx(ar,{size:14})}];return e.jsxs("nav",{className:"dql-app-section-tabs","aria-label":"App sections",children:[e.jsxs("button",{className:r===n.id?"on":"","data-app-section":n.id,onClick:()=>i(n.id),children:[e.jsx("i",{className:"dql-app-tab-icon",children:n.icon}),e.jsx("span",{className:"dql-app-tab-label",children:n.label}),e.jsx("b",{children:n.count})]}),a==="build"?e.jsxs("details",{className:"dql-app-context-menu",children:[e.jsxs("summary",{children:[e.jsx(ta,{size:14})," Context"]}),e.jsx("div",{children:o.map(f=>e.jsxs("button",{type:"button",className:r===f.id?"on":"",onClick:()=>i(f.id),children:[f.icon,e.jsx("span",{children:f.label}),f.count!==void 0?e.jsx("b",{children:f.count}):null]},f.id))})]}):null]})}function Wp({dashboards:t,activeDashboardId:r,isBuild:a,onOpen:i,onAdd:s}){const n=t.find(o=>o.id===r)??t[0];return e.jsxs("div",{className:"dql-app-page-picker","aria-label":"Dashboard page",children:[e.jsxs("span",{children:[e.jsx(nn,{size:14})," Page"]}),e.jsx("select",{value:(n==null?void 0:n.id)??"",onChange:o=>i(o.target.value),title:(n==null?void 0:n.title)??"Dashboard page",children:t.map(o=>e.jsxs("option",{value:o.id,children:[o.title," (",o.itemCount,")"]},o.id))}),a?e.jsx("button",{type:"button",onClick:s,title:"Add dashboard page",children:e.jsx(xt,{size:14})}):null]})}function Hp({app:t,appDoc:r,dashboardDoc:a,dashboardRun:i,variables:s,selectedBlockId:n,askSeed:o,themeMode:l,expanded:d,onToggleExpanded:x,onClose:b,onOpenApp:m}){const f=Ht[l],y=(a==null?void 0:a.dashboard)??null,w=p.useMemo(()=>Ln(y,i),[y,i]).find(A=>A.blockId===n)??null,q=w?i==null?void 0:i.tiles.find(A=>A.tileId===w.tileId||A.blockId===w.blockId):null,C=(t==null?void 0:t.id)??(r==null?void 0:r.app.id)??"app",k=(y==null?void 0:y.id)??"dashboard",M=Ba(`app:${C}:${k}`),[L,X]=p.useState(!1),I=Oe((t==null?void 0:t.name)??(r==null?void 0:r.app.name)??(y==null?void 0:y.metadata.title)??"App workspace"),O=Oe((y==null?void 0:y.metadata.title)??"Dashboard"),F=w?`Focused on ${Oe(w.title)} in ${O}`:`Scoped to ${O}`,U=w?{kind:"block",id:w.blockId,title:w.title}:y?{kind:"dashboard",id:y.id,title:y.metadata.title}:{kind:"app",id:C,title:I},_=p.useMemo(()=>{var A,te,Q,Y,S;return{surface:"apps",appId:C,appName:(t==null?void 0:t.name)??(r==null?void 0:r.app.name),appDomain:(t==null?void 0:t.domain)??(r==null?void 0:r.app.domain),appDescription:(t==null?void 0:t.description)??(r==null?void 0:r.app.description),dashboardId:y==null?void 0:y.id,dashboardTitle:y==null?void 0:y.metadata.title,dashboardDescription:y==null?void 0:y.metadata.description,dashboardFilters:s,selectedBlock:w?{blockId:w.blockId,tileId:w.tileId,title:w.title,visualization:w.viz,status:q==null?void 0:q.status,certificationStatus:q==null?void 0:q.certificationStatus,rowCount:(A=q==null?void 0:q.result)==null?void 0:A.rowCount,columns:(Q=(te=q==null?void 0:q.result)==null?void 0:te.columns)==null?void 0:Q.slice(0,12),sampleRows:Xp((Y=q==null?void 0:q.result)==null?void 0:Y.rows,(S=q==null?void 0:q.result)==null?void 0:S.columns)}:void 0}},[t,r,C,y,w,q,s]);return e.jsx(Ea,{t:f,title:"App AI",subtitle:I,expanded:d,onToggleExpanded:x,resizable:!0,minResizeWidth:390,maxResizeWidth:1200,fitViewportHeight:!0,heightResizable:!0,minResizeHeight:520,onClose:b,onNewChat:M.resetThreadId,running:L,ariaLabel:"App AI",className:"dql-app-explain-panel dql-app-assistant-panel",children:e.jsx(p.Suspense,{fallback:e.jsx("div",{style:{padding:16,fontSize:12,color:f.textSecondary},children:"Loading App AI…"}),children:e.jsx(Tp,{themeMode:l,title:"App AI",scopeHint:F,audience:"stakeholder",selectedObject:U,workspaceContext:_,initialMode:"auto",autoRun:o!=null&&o.text?{text:o.text,mode:"ask",nonce:o.nonce}:void 0,threadId:M.threadId,onThreadIdChange:M.onThreadIdChange,onRunningChange:X,onOpenApp:m,answerFirstCards:!0,examplePrompts:[{label:"Explain this dashboard",prompt:"Explain the most important business story in this dashboard and what action it suggests."},{label:"Find the main driver",prompt:"What is the main driver behind the current result? Use the active app filters and governed evidence."},{label:"Check this result",prompt:"Validate the current result against its certified block, semantic definitions, and lineage."}]},`${C}:${k}`)})})}function Vp(t){return t?Array.from(new Set([...(t.globalFilters??[]).map(r=>r.id),...t.pages.flatMap(r=>(r.filters??[]).map(a=>a.id))])):[]}function va(t){return t.block?"blockId"in t.block?t.block.blockId??null:t.block.ref??null:null}function Ln(t,r){if(!t)return[];const a=new Map(((r==null?void 0:r.tiles)??[]).map(d=>[d.tileId,d])),i=new Map(((r==null?void 0:r.tiles)??[]).filter(d=>d.blockId).map(d=>[d.blockId,d])),s=new Set(t.layout.items.filter(d=>va(d)&&Hi(d)).map(d=>$a(`${d.title??""} ${va(d)??""}`)).filter(Boolean)),n=t.layout.items.map((d,x)=>{const b=va(d);if(!b)return null;const m=$a(`${d.title??""} ${b}`);if(m&&s.has(m)&&!Hi(d))return null;const f=a.get(d.i)??i.get(b);return{block:{blockId:b,title:d.title??b,viz:d.viz.type,tileId:d.i},duplicateKeys:Kp(d,f,b),score:Yp(d,f,x)}}).filter(d=>!!d).sort((d,x)=>x.score-d.score),o=new Set,l=[];for(const d of n)if(!d.duplicateKeys.some(x=>o.has(x))){for(const x of d.duplicateKeys)o.add(x);l.push(d.block)}return l}function Hi(t){var r,a;return(r=t.parameterBindings)!=null&&r.length?!0:!!((a=t.filterBindings)!=null&&a.some(i=>!i.unsupportedReason&&(i.mode==="parameter"||i.mode==="predicate"||!!i.binding)))}function Kp(t,r,a){const i=[`block:${a}`],s=Qp(r==null?void 0:r.result);s&&i.push(`result:${s}`);const n=$a(`${t.title??""} ${a}`);return n&&i.push(`topic:${n}`),i}function Qp(t){var i,s;if(!((i=t==null?void 0:t.columns)!=null&&i.length)||!((s=t.rows)!=null&&s.length))return"";const r=t.columns.slice(0,6).map(n=>n.toLowerCase()),a=t.rows.slice(0,3).map(n=>r.map(o=>Gp(n[o]??n[t.columns.find(l=>l.toLowerCase()===o)??o])).join(","));return[...r,...a].join("|")}function Gp(t){return t==null?"":typeof t=="number"?Number.isFinite(t)?String(Math.round(t*1e3)/1e3):"":String(t).toLowerCase().replace(/\s+/g," ").trim().slice(0,80)}function $a(t){const r=t.toLowerCase().replace(/\b(codex|e2e|qa|draft|imported|pasted|raw|sql|block)\b/g," ").replace(/\b20\d{10,}\b/g," "),a=/\b(player|players|scorer|scorers|athlete)\b/.test(r)?"player":/\b(customer|account|user)\b/.test(r)?"customer":/\b(team|teams)\b/.test(r)?"team":"",i=/\b(top|bottom|rank|ranking|leader|leaderboard|scorer|scorers)\b/.test(r)?"ranking":/\b(availability|freshness|record|records|quality|coverage)\b/.test(r)?"availability":/\b(trend|weekly|monthly|daily|over time)\b/.test(r)?"trend":"",s=/\b(point|points|pts|score|scoring|scorer|scorers)\b/.test(r)?"points":/\b(field goal|fgm|fga|field-goal|field_goals?)\b/.test(r)?"field_goals":/\b(count|records|games played)\b/.test(r)?"count":/\b(availability|freshness|quality|coverage)\b/.test(r)?"quality":"";return!a||!i||!s?"":`${a}|${i}|${s}`}function Yp(t,r,a){var s,n,o,l,d;let i=1e4-a;return(s=t.parameterBindings)!=null&&s.length&&(i+=5e4),(n=t.filterBindings)!=null&&n.length&&(i+=2e4),(r==null?void 0:r.status)==="ok"&&(i+=15e3),(l=(o=r==null?void 0:r.result)==null?void 0:o.rows)!=null&&l.length&&(i+=8e3),(r==null?void 0:r.certificationStatus)==="certified"&&(i+=5e3),String(t.trustState??((d=t.display)==null?void 0:d.trustState)??"").toLowerCase()==="certified"&&(i+=3e3),/codex\s+e2e|test|pasted/i.test(String(t.title??""))&&(i-=6e3),i}function Xp(t,r){if(!Array.isArray(t)||t.length===0)return;const a=Array.isArray(r)&&r.length>0?r.slice(0,8):Object.keys(t[0]??{}).slice(0,8);return t.slice(0,5).map(i=>Object.fromEntries(a.map(s=>[s,i[s]])))}function Jp(t,r,a){var l;const i=(t==null?void 0:t.id)??(r==null?void 0:r.app.id)??"app",s=(t==null?void 0:t.name)??(r==null?void 0:r.app.name)??"DQL App",n=(a==null?void 0:a.dashboard.metadata.title)??((l=r==null?void 0:r.dashboards[0])==null?void 0:l.title)??"Overview",o=typeof window<"u"?window.location.origin:"local DQL";return[s,`App ID: ${i}`,`Dashboard: ${n}`,`Domain: ${(t==null?void 0:t.domain)??(r==null?void 0:r.app.domain)??(a==null?void 0:a.dashboard.metadata.domain)??"unknown"}`,`Open locally: ${o}`].join(`
|
|
5588
|
+
`)}function Zp(t,r,a){const i=r==null?void 0:r.app,s=(t==null?void 0:t.name)??(i==null?void 0:i.name)??"DQL App",n=(r==null?void 0:r.dashboards)??[],o=(r==null?void 0:r.notebooks)??(i==null?void 0:i.notebooks)??[],l=(r==null?void 0:r.drafts)??[],d=(r==null?void 0:r.aiPins)??[],x=a==null?void 0:a.dashboard,b=(x==null?void 0:x.layout.items.map(f=>f.block?f.block.blockId??f.block.ref??f.title??f.i:null).filter(f=>!!f))??[];return`${[`# ${s}`,"",(t==null?void 0:t.description)??(x==null?void 0:x.metadata.description)??(i==null?void 0:i.description)??"Local DQL App brief.","","## App Metadata","",`- App ID: ${(t==null?void 0:t.id)??(i==null?void 0:i.id)??"unknown"}`,`- Domain: ${(t==null?void 0:t.domain)??(i==null?void 0:i.domain)??(x==null?void 0:x.metadata.domain)??"unknown"}`,`- Lifecycle: ${(t==null?void 0:t.lifecycle)??(i==null?void 0:i.lifecycle)??(x==null?void 0:x.metadata.lifecycle)??"draft"}`,`- Audience: ${(t==null?void 0:t.audience)??(i==null?void 0:i.audience)??(x==null?void 0:x.metadata.audience)??"stakeholder"}`,`- Owners: ${((t==null?void 0:t.owners)??(i==null?void 0:i.owners)??[]).join(", ")||"owner@local"}`,"","## Pages","",...n.length?n.map(f=>`- ${f.title} (${f.itemCount} tiles)`):["- No dashboard pages found."],"","## Governed Blocks","",...b.length?b.map(f=>`- ${f}`):["- No block-backed tiles found."],"","## Supporting Assets","",`- Notebooks: ${o.length}`,`- Pinned insights: ${d.length}`,`- Drafts needing review: ${l.length}`,""].join(`
|
|
5594
5589
|
`)}
|
|
5595
|
-
`}function vr({label:t,value:r}){return e.jsxs("span",{children:[e.jsx("small",{children:t}),e.jsx("b",{children:r})]})}function
|
|
5590
|
+
`}function vr({label:t,value:r}){return e.jsxs("span",{children:[e.jsx("small",{children:t}),e.jsx("b",{children:r})]})}function Dp({title:t,allowExploration:r,exploreGaps:a,error:i,onChange:s,onExploreGapsChange:n,onCancel:o,onCreate:l}){return e.jsx("div",{className:"dql-app-modal-backdrop",children:e.jsxs("div",{className:"dql-app-modal",children:[e.jsx("h3",{children:"Build a new App page"}),e.jsx("p",{children:"Describe the business question. AI will propose exactly one page for review before changing the App."}),e.jsxs("label",{children:["What should this page answer?",e.jsx("textarea",{value:t,onChange:d=>s(d.target.value),autoFocus:!0,rows:4,placeholder:"Show quarterly revenue drivers by region and segment for leadership."})]}),r?e.jsxs("button",{type:"button",className:`dql-app-page-explore ${a?"on":""}`,onClick:()=>n(!a),"aria-pressed":a,children:[e.jsx("span",{children:a?e.jsx(Pt,{size:11,strokeWidth:3}):null}),e.jsx("b",{children:"Explore uncovered gaps with AI SQL"}),e.jsx("small",{children:"Personal App only · bounded preview · review required"})]}):e.jsx("small",{className:"dql-app-page-source-policy",children:"Shared-project pages use certified blocks and governed semantic metrics."}),i?e.jsx("div",{className:"dql-app-error",children:i}):null,e.jsxs("div",{children:[e.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:o,children:"Cancel"}),e.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-primary",onClick:l,children:"Create Build Brief"})]})]})})}function sa(t){return t.publicationIntent?t.publicationIntent==="shared_project":t.visibility?t.visibility==="shared":(t.storage??"shared")==="shared"}function Up(t,r,a){const i=t.filter(sa).length;return{all:t.length+r.length,drafts:r.length,private:t.length-i,shared:i,fav:t.filter(s=>a.has(s.id)).length}}function ec(t){var r;return((r=t.owners)==null?void 0:r[0])??"owner@local"}export{Sc as AppsView};
|