@duckcodeailabs/dql-cli 1.12.3 → 1.12.5

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.
Files changed (79) hide show
  1. package/dist/assets/dql-notebook/assets/AgentAnswerCard-BJAnjaLA.js +5 -0
  2. package/dist/assets/dql-notebook/assets/{AgentLogPage-CsSC2tOR.js → AgentLogPage-J72WR6hk.js} +1 -1
  3. package/dist/assets/dql-notebook/assets/{AiBuildDialog-CjJ-9bQW.js → AiBuildDialog-CHJZfDmp.js} +1 -1
  4. package/dist/assets/dql-notebook/assets/{AiBuildResult-BvTcW9oE.js → AiBuildResult-Da7_Cn12.js} +1 -1
  5. package/dist/assets/dql-notebook/assets/{AiSidePanel-CxFrOfCE.js → AiSidePanel-BY6W_5aC.js} +1 -1
  6. package/dist/assets/dql-notebook/assets/{AnalyticsHome-BtXEdJNR.js → AnalyticsHome-u-buXgdv.js} +1 -1
  7. package/dist/assets/dql-notebook/assets/{AppsView-HjQkbbE6.js → AppsView-3k7ftDpd.js} +3 -3
  8. package/dist/assets/dql-notebook/assets/{BlockStudio-oQHTJsXC.js → BlockStudio-CLX4EUyO.js} +14 -14
  9. package/dist/assets/dql-notebook/assets/{BusinessArtifactView-Dpsftjs7.js → BusinessArtifactView-3THMNeyO.js} +1 -1
  10. package/dist/assets/dql-notebook/assets/{DbtFirstModelingPage-c6ZteaI6.js → DbtFirstModelingPage-BwBPwtdA.js} +1 -1
  11. package/dist/assets/dql-notebook/assets/{GitPage-Cj6mc-Yv.js → GitPage-CvEki0pe.js} +1 -1
  12. package/dist/assets/dql-notebook/assets/{GlobalAiRail-8G_rEyhK.js → GlobalAiRail-NXdk9kNy.js} +1 -1
  13. package/dist/assets/dql-notebook/assets/{GovernedContextPage-BTtzt0Za.js → GovernedContextPage-DILbw-Vr.js} +1 -1
  14. package/dist/assets/dql-notebook/assets/{HelpDocsPage-e2CesE73.js → HelpDocsPage-DgCu4bvY.js} +1 -1
  15. package/dist/assets/dql-notebook/assets/{HomePage-U3ryMLEF.js → HomePage-CK3fXTQo.js} +1 -1
  16. package/dist/assets/dql-notebook/assets/{LineageDAG-CEmgJzm3.js → LineageDAG-DW_NO3P2.js} +1 -1
  17. package/dist/assets/dql-notebook/assets/{LineageDetailView-CeV5QMXS.js → LineageDetailView-VT7DLJOB.js} +1 -1
  18. package/dist/assets/dql-notebook/assets/{LineageDrawer-B1oAn-N_.js → LineageDrawer-DSTm8aXw.js} +1 -1
  19. package/dist/assets/dql-notebook/assets/{LineagePathBreadcrumb-fP6RTXut.js → LineagePathBreadcrumb-DRlAYasJ.js} +1 -1
  20. package/dist/assets/dql-notebook/assets/{MiniLineageGraph-CBYSTmRC.js → MiniLineageGraph-CR_nhwhZ.js} +1 -1
  21. package/dist/assets/dql-notebook/assets/{NewBlockModal-ksEwimjl.js → NewBlockModal-CJvjYiBF.js} +1 -1
  22. package/dist/assets/dql-notebook/assets/{NewNotebookModal-CUx0WmXb.js → NewNotebookModal-BEpPH93n.js} +1 -1
  23. package/dist/assets/dql-notebook/assets/{NotebookEditor-BdxJL3LX.js → NotebookEditor-C7GDFwhF.js} +1 -1
  24. package/dist/assets/dql-notebook/assets/{ReadinessPage-DZ9wDW76.js → ReadinessPage-rZiOp2xr.js} +1 -1
  25. package/dist/assets/dql-notebook/assets/{SetupOnboarding-Bt0AAe0h.js → SetupOnboarding-BWjhTjPB.js} +1 -1
  26. package/dist/assets/dql-notebook/assets/{TrustBadge-DNVJK_mP.js → TrustBadge-RvZ9s6OQ.js} +1 -1
  27. package/dist/assets/dql-notebook/assets/{UnifiedAgentRunPanel-BNqE169i.js → UnifiedAgentRunPanel-CGPcpY1B.js} +18 -18
  28. package/dist/assets/dql-notebook/assets/{answer-to-notebook-B_gE6rsY.js → answer-to-notebook-Di227Cd4.js} +1 -1
  29. package/dist/assets/dql-notebook/assets/{arrow-left-DnKGhzOR.js → arrow-left-BZHDcWHR.js} +1 -1
  30. package/dist/assets/dql-notebook/assets/{arrow-right-CQ73DG7_.js → arrow-right-DlM1pC3_.js} +1 -1
  31. package/dist/assets/dql-notebook/assets/{book-open-text-CyBV5Nhw.js → book-open-text-DBcXFQAu.js} +1 -1
  32. package/dist/assets/dql-notebook/assets/{bot-UOPtBzCj.js → bot-BAywbvPm.js} +1 -1
  33. package/dist/assets/dql-notebook/assets/{chevron-up-CDHDU3N3.js → chevron-up-B_GfKE_F.js} +1 -1
  34. package/dist/assets/dql-notebook/assets/{circle-x-DC5nkL_u.js → circle-x-BcxtZ-ym.js} +1 -1
  35. package/dist/assets/dql-notebook/assets/{dagre.esm-C7ujXipB.js → dagre.esm-Bqs0lsEz.js} +1 -1
  36. package/dist/assets/dql-notebook/assets/{external-link-BiJ_dtTM.js → external-link-B24Dk9_t.js} +1 -1
  37. package/dist/assets/dql-notebook/assets/{grip-vertical-eXvkUerq.js → grip-vertical-D9g31N3j.js} +1 -1
  38. package/dist/assets/dql-notebook/assets/index-DU7j3Sqk.js +644 -0
  39. package/dist/assets/dql-notebook/assets/{link-2-DkHVJTuH.js → link-2-B36oR5Bj.js} +1 -1
  40. package/dist/assets/dql-notebook/assets/{list-tree-8lYW2Itb.js → list-tree-B9ZzGc4U.js} +1 -1
  41. package/dist/assets/dql-notebook/assets/{maximize-2-DjSovOdP.js → maximize-2-BrvQLPoj.js} +1 -1
  42. package/dist/assets/dql-notebook/assets/{minimize-2-DGlmQLES.js → minimize-2-BrpFmsxS.js} +1 -1
  43. package/dist/assets/dql-notebook/assets/{panel-right-open-DPc4gShM.js → panel-right-open-B1g1qhh5.js} +1 -1
  44. package/dist/assets/dql-notebook/assets/{pencil-nwaGtOdL.js → pencil-DwywbTqQ.js} +1 -1
  45. package/dist/assets/dql-notebook/assets/{rotate-ccw-ByjLhAu7.js → rotate-ccw-Db_KVs3J.js} +1 -1
  46. package/dist/assets/dql-notebook/assets/{semantic-fields-eEhwnQhG.js → semantic-fields-BIVuvP2l.js} +1 -1
  47. package/dist/assets/dql-notebook/assets/{triangle-alert-zws0cKhp.js → triangle-alert-Cne6C2aG.js} +1 -1
  48. package/dist/assets/dql-notebook/assets/usePersistedAgentThreadId-D6mtrJ-_.js +18 -0
  49. package/dist/assets/dql-notebook/assets/{user-round-CM8xNakq.js → user-round-DkzxN1xD.js} +1 -1
  50. package/dist/assets/dql-notebook/assets/{wand-sparkles-CIKc8r-4.js → wand-sparkles-CJUvFtur.js} +1 -1
  51. package/dist/assets/dql-notebook/assets/{workflow-6C0ZLbTi.js → workflow-BOvVTg7R.js} +1 -1
  52. package/dist/assets/dql-notebook/assets/{wrench-CeU7hF12.js → wrench-YeSpzZRt.js} +1 -1
  53. package/dist/assets/dql-notebook/assets/{x-DLWEzvri.js → x-C6tsHUR7.js} +1 -1
  54. package/dist/assets/dql-notebook/index.html +1 -1
  55. package/dist/block-invocation.js +4 -0
  56. package/dist/block-invocation.js.map +1 -1
  57. package/dist/llm/answer-loop-tools.d.ts +8 -2
  58. package/dist/llm/answer-loop-tools.d.ts.map +1 -1
  59. package/dist/llm/answer-loop-tools.js +29 -2
  60. package/dist/llm/answer-loop-tools.js.map +1 -1
  61. package/dist/llm/providers/dql-agent-provider.d.ts +27 -1
  62. package/dist/llm/providers/dql-agent-provider.d.ts.map +1 -1
  63. package/dist/llm/providers/dql-agent-provider.js +79 -15
  64. package/dist/llm/providers/dql-agent-provider.js.map +1 -1
  65. package/dist/llm/types.d.ts +8 -1
  66. package/dist/llm/types.d.ts.map +1 -1
  67. package/dist/local-runtime.d.ts +46 -0
  68. package/dist/local-runtime.d.ts.map +1 -1
  69. package/dist/local-runtime.js +647 -66
  70. package/dist/local-runtime.js.map +1 -1
  71. package/dist/package.json +10 -10
  72. package/dist/sql-result-filter.d.ts +39 -0
  73. package/dist/sql-result-filter.d.ts.map +1 -0
  74. package/dist/sql-result-filter.js +256 -0
  75. package/dist/sql-result-filter.js.map +1 -0
  76. package/package.json +10 -10
  77. package/dist/assets/dql-notebook/assets/AgentAnswerCard-BEIwKGm4.js +0 -5
  78. package/dist/assets/dql-notebook/assets/index-BMVfPaXr.js +0 -644
  79. package/dist/assets/dql-notebook/assets/usePersistedAgentThreadId-hxi1RZDm.js +0 -18
@@ -1,5 +1,5 @@
1
- const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/UnifiedAgentRunPanel-BNqE169i.js","assets/index-BMVfPaXr.js","assets/react-CRB3T2We.js","assets/index-DKu4CZt3.css","assets/AgentAnswerCard-BEIwKGm4.js","assets/usePersistedAgentThreadId-hxi1RZDm.js","assets/TrustBadge-DNVJK_mP.js","assets/AiBuildResult-BvTcW9oE.js","assets/user-round-CM8xNakq.js","assets/triangle-alert-zws0cKhp.js","assets/rotate-ccw-ByjLhAu7.js","assets/x-DLWEzvri.js","assets/pencil-nwaGtOdL.js","assets/list-tree-8lYW2Itb.js","assets/wrench-CeU7hF12.js","assets/arrow-right-CQ73DG7_.js","assets/chevron-up-CDHDU3N3.js"])))=>i.map(i=>d[i]);
2
- import{g as Ee,u as At,t as Ne,r as u,a as Z,j as t,G as Lr,P as kt,S as Re,o as ma,n as ba,an as va,aG as Ut,h as We,T as ya,aH as Ye,ax as qa,ai as Be,f as nt,B as er,b as Er,aI as _r,aD as wa,k as tr}from"./index-BMVfPaXr.js";import{A as Mr,a as Qt,b as ja}from"./AiSidePanel-CxFrOfCE.js";import{u as Or,C as ka,c as Sa,i as za,T as Aa,b as Ca,e as Na,S as Ia,A as Ta}from"./usePersistedAgentThreadId-hxi1RZDm.js";import{c as $a,r as Fr}from"./semantic-fields-eEhwnQhG.js";import{W as Wr}from"./wand-sparkles-CIKc8r-4.js";import{B as Ct}from"./bot-UOPtBzCj.js";import{G as Pa}from"./grip-vertical-eXvkUerq.js";import{T as Qe}from"./triangle-alert-zws0cKhp.js";import{M as Ra}from"./maximize-2-DjSovOdP.js";import{A as Vr}from"./arrow-left-DnKGhzOR.js";import{W as Oe}from"./workflow-6C0ZLbTi.js";import{P as Hr}from"./pencil-nwaGtOdL.js";import{B as Qr}from"./book-open-text-CyBV5Nhw.js";import"./react-CRB3T2We.js";import"./minimize-2-DGlmQLES.js";import"./x-DLWEzvri.js";/**
1
+ const __vite__mapDeps=(i,m=__vite__mapDeps,d=(m.f||(m.f=["assets/UnifiedAgentRunPanel-CGPcpY1B.js","assets/index-DU7j3Sqk.js","assets/react-CRB3T2We.js","assets/index-DKu4CZt3.css","assets/AgentAnswerCard-BJAnjaLA.js","assets/usePersistedAgentThreadId-D6mtrJ-_.js","assets/TrustBadge-RvZ9s6OQ.js","assets/AiBuildResult-Da7_Cn12.js","assets/user-round-DkzxN1xD.js","assets/triangle-alert-Cne6C2aG.js","assets/rotate-ccw-Db_KVs3J.js","assets/x-C6tsHUR7.js","assets/pencil-DwywbTqQ.js","assets/list-tree-B9ZzGc4U.js","assets/wrench-YeSpzZRt.js","assets/arrow-right-DlM1pC3_.js","assets/chevron-up-B_GfKE_F.js"])))=>i.map(i=>d[i]);
2
+ import{g as Ee,u as At,t as Ne,r as u,a as Z,j as t,G as Lr,P as kt,S as Re,o as ma,n as ba,an as va,aG as Ut,h as We,T as ya,aH as Ye,ax as qa,ai as Be,f as nt,B as er,b as Er,aI as _r,aD as wa,k as tr}from"./index-DU7j3Sqk.js";import{A as Mr,a as Qt,b as ja}from"./AiSidePanel-BY6W_5aC.js";import{u as Or,C as ka,c as Sa,i as za,T as Aa,b as Ca,e as Na,S as Ia,A as Ta}from"./usePersistedAgentThreadId-D6mtrJ-_.js";import{c as $a,r as Fr}from"./semantic-fields-BIVuvP2l.js";import{W as Wr}from"./wand-sparkles-CJUvFtur.js";import{B as Ct}from"./bot-BAywbvPm.js";import{G as Pa}from"./grip-vertical-D9g31N3j.js";import{T as Qe}from"./triangle-alert-Cne6C2aG.js";import{M as Ra}from"./maximize-2-BrvQLPoj.js";import{A as Vr}from"./arrow-left-BZHDcWHR.js";import{W as Oe}from"./workflow-BOvVTg7R.js";import{P as Hr}from"./pencil-DwywbTqQ.js";import{B as Qr}from"./book-open-text-DBcXFQAu.js";import"./react-CRB3T2We.js";import"./minimize-2-BrpFmsxS.js";import"./x-C6tsHUR7.js";/**
3
3
  * @license lucide-react v0.563.0 - ISC
4
4
  *
5
5
  * This source code is licensed under the ISC license.
@@ -44,7 +44,7 @@ import{g as Ee,u as At,t as Ne,r as u,a as Z,j as t,G as Lr,P as kt,S as Re,o as
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 Xa=[["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"}]],Ja=Ee("table-2",Xa),Za=u.lazy(()=>Ut(()=>import("./UnifiedAgentRunPanel-BNqE169i.js").then(e=>e.c),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])).then(e=>({default:e.UnifiedAgentRunPanel}))),Da="clamp(320px, calc(100vh - 220px), 760px)",ar=[{value:"table",label:"Table"},...ka];function Ua(e,r){if(!Array.isArray(e)||e.length===0)return;const a=Array.isArray(r)&&r.length>0?r.slice(0,8):Object.keys(e[0]??{}).slice(0,8);return e.slice(0,5).map(i=>Object.fromEntries(a.map(n=>[n,i[n]])))}const Gr=[{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 ei({appId:e,dashboard:r,variables:a,editable:i=!1,embeddedHeader:n=!1,onDashboardChanged:l,selectedBlockId:s,onBlockFocus:o,onAskBlock:p,onOpenLineageNode:d,copilotOpen:f,onCopilotChange:x,onRunChange:c}){var ft;const{state:A}=At(),S=Ne[A.themeMode],[q,h]=u.useState(null),[T,z]=u.useState(null),Y=u.useRef(null),[$,k]=u.useState(!1),[E,M]=u.useState(null),[I,Q]=u.useState(!1),re=Or(`app:${e}:${r.id}`),[D,_]=u.useState(!1),[V,W]=u.useState([]),[de,C]=u.useState(""),[le,we]=u.useState(!1),[B,ee]=u.useState(null),[ne,he]=u.useState(!1),[X,K]=u.useState(!1),[me,pe]=u.useState(!1),[ye,ce]=u.useState(null),[be,J]=u.useState(""),[b,P]=u.useState(null),U=u.useRef(null),[G,N]=u.useState(!1),L=r.layout.cols,se=r.layout.rowHeight,ve=u.useMemo(()=>JSON.stringify(a??{}),[a]),oe=u.useMemo(()=>JSON.parse(ve),[ve]),ue=u.useMemo(()=>{const m=new Map;for(const j of(q==null?void 0:q.tiles)??[])m.set(j.tileId,j);return m},[q]),xe=u.useMemo(()=>i?r.layout.items:r.layout.items.filter(m=>!zi(m)),[r.layout.items,i]),ae=u.useMemo(()=>i?xe:Ai(xe,ue,L),[xe,L,i,ue]),Ce=r.layout.items.length-xe.length,H=xe.length-ae.length,y=u.useMemo(()=>!i&&!r.story&&r.sections&&r.sections.length>0?[...r.sections].sort((m,j)=>m.order-j.order):null,[r.sections,r.story,i]),te=u.useMemo(()=>y?r.layout.items:null,[r.layout.items,y]),ie=u.useMemo(()=>i||y?null:Ri(ae,ue,oe),[i,oe,y,ue,ae]);u.useEffect(()=>{let m=!1;return k(!0),M(null),Z.runDashboard(e,r.id,oe).then(j=>{m||(h(j),z((j==null?void 0:j.story)??null),Y.current=(j==null?void 0:j.runId)??null,c==null||c(j),j||M("Dashboard run failed."),j!=null&&j.runId&&Z.getDashboardStory(e,r.id,j.runId).then(w=>{m||!w||Y.current!==w.runId||w.snapshotId!==j.snapshotId||w.filterFingerprint!==j.filterFingerprint||w.resultFingerprint!==j.resultFingerprint||w.personaFingerprint!==j.personaFingerprint||z(w.story)}))}).catch(j=>{m||(M(j instanceof Error?j.message:String(j)),c==null||c(null))}).finally(()=>{m||k(!1)}),()=>{m=!0}},[e,r.id,r.layout.items.length,c,oe,(ft=A.activePersona)==null?void 0:ft.userId]),u.useEffect(()=>{const m=j=>{const w=j.detail;(w==null?void 0:w.appId)!==e||w.dashboardId!==r.id||(Z.getDashboard(e,r.id).then(F=>{F!=null&&F.dashboard&&(l==null||l(F.dashboard))}),Z.runDashboard(e,r.id,oe).then(F=>{F&&(h(F),z(F.story),Y.current=F.runId,c==null||c(F))}))};return window.addEventListener("dql-app-dashboard-updated",m),()=>window.removeEventListener("dql-app-dashboard-updated",m)},[e,r.id,l,c,oe]),u.useEffect(()=>{const m=()=>N(window.innerWidth<760);return m(),window.addEventListener("resize",m),()=>window.removeEventListener("resize",m)},[]);const _e=u.useMemo(()=>{const m=r.layout.items.map(j=>{var fe,je,g,v,R;const w=ue.get(j.i),F=j.block?"blockId"in j.block?j.block.blockId:j.block.ref:j.semantic?`semantic:${j.semantic.id}`:j.aiPin?`aiPin:${j.aiPin.id}`:"text";return{title:j.title,blockRef:F,viz:j.viz.type,certificationStatus:w==null?void 0:w.certificationStatus,status:w==null?void 0:w.status,rowCount:(fe=w==null?void 0:w.result)==null?void 0:fe.rowCount,columns:(g=(je=w==null?void 0:w.result)==null?void 0:je.columns)==null?void 0:g.slice(0,8),sampleRows:Ua((v=w==null?void 0:w.result)==null?void 0:v.rows,(R=w==null?void 0:w.result)==null?void 0:R.columns)}});return JSON.stringify({scope:"dashboard",appId:e,dashboardId:r.id,title:r.metadata.title,description:r.metadata.description,domain:r.metadata.domain,filters:r.filters,variables:oe,run:q?{runId:q.runId,snapshotId:q.snapshotId,filterFingerprint:q.filterFingerprint,resultFingerprint:q.resultFingerprint,personaFingerprint:q.personaFingerprint,story:q.story,facts:q.facts}:null,tiles:m},null,2)},[e,r,q,oe,ue]),Se=u.useCallback(async m=>{he(!0);const j={...r,layout:{...r.layout,items:m}},w=await Z.patchDashboardLayout(e,r.id,j.layout);he(!1),w.ok?l==null||l(w.dashboard):M(w.error)},[e,r,l]),tt=u.useCallback(async()=>{_(!0);const m=await Z.getAppEditorCatalog(e);W((m==null?void 0:m.blocks)??[])},[e]),ct=u.useCallback(async m=>{const j=dt(m.chartType),w=await Z.recommendDashboardTile(e,r.id,{blockRef:m.name,appAudience:r.metadata.audience,prompt:`${r.metadata.title} ${m.name} ${m.description}`,defaultVisualization:j}),F=or(j,L),fe={i:Mt(r,m.name),..._t(r,F),block:{blockId:m.name},viz:{type:j},...w.ok?{display:w.display,filterBindings:"filterBindings"in w?w.filterBindings:void 0,parameterBindings:"parameterBindings"in w?w.parameterBindings:void 0,sourceEvidence:"sourceEvidence"in w?w.sourceEvidence:void 0,trustState:"trustState"in w?w.trustState:w.display.trustState,reviewStatus:"reviewStatus"in w?w.reviewStatus:w.display.reviewStatus}:{},title:m.name};await Se([...r.layout.items,fe]),_(!1)},[e,L,r,Se]),Me=u.useCallback(async()=>{ce("text"),J("")},[]),Ve=u.useCallback(async()=>{ce("heading"),J("")},[]),Nt=u.useCallback(async()=>{var j;const m=be.trim();if(!(!m||!ye)){if(ye==="heading")await Se([...r.layout.items,{i:Mt(r,"section"),..._t(r,Ie("wide",L,"heading")),text:{markdown:m},viz:{type:"heading"},display:mr("heading",m),title:m}]);else{const w=((j=m.split(/\r?\n/)[0])==null?void 0:j.slice(0,60))||"Summary";await Se([...r.layout.items,{i:Mt(r,"text"),..._t(r,Ie("standard",L,"text")),text:{markdown:m},viz:{type:"text"},display:mr("text",w),title:w}])}ce(null),J("")}},[L,r,Se,ye,be]),He=u.useCallback(async(m,j)=>{const w=j===null?r.layout.items.filter(F=>F.i!==m):r.layout.items.map(F=>F.i===m?{...F,...j}:F);await Se(wt(w,L))},[L,r.layout.items,Se]),It=u.useCallback(async(m,j)=>{const w=U.current,F=r.layout.items.find(ht=>ht.i===m);if(!w||!F)return;const fe=w.getBoundingClientRect(),je=12,v=(fe.width-je*(L-1))/L+je,R=se+je,O=Math.round((j.clientX-fe.left)/v),ze=Math.round((j.clientY-fe.top)/R),Je={...F,x:St(O,0,Math.max(0,L-F.w)),y:Math.max(0,ze)};P(null);const gt=kn(r.layout.items,Je,L);await Se(wt(gt,L))},[L,r.layout.items,se,Se]),Tt=u.useCallback((m,j)=>{const w=U.current,F=r.layout.items.find(O=>O.i===m);if(!w||!F)return;const fe=w.getBoundingClientRect(),je=12,g=(fe.width-je*(L-1))/L,v=Math.round((j.clientX-fe.left)/(g+je)),R=Math.round((j.clientY-fe.top)/(se+je));P({tileId:m,x:St(v,0,Math.max(0,L-F.w)),y:Math.max(0,R),w:F.w,h:F.h})},[L,r.layout.items,se]),$t=u.useCallback(()=>P(null),[]),Pt=u.useCallback(async()=>{const m=r.layout.items;if(m.length===0)return;const j=[...m].map((w,F)=>({item:w,index:F})).sort((w,F)=>{const fe=Jt(w.item)-Jt(F.item);return fe!==0?fe:w.index-F.index}).map(({item:w})=>{const F=pr(w,L);return{...w,w:F.w,h:F.h}});await Se(wt(j,L))},[L,r.layout.items,Se]),ut=u.useCallback(async()=>{if(we(m=>!m),!B){const m=await Z.fetchScopedLineage({domain:r.metadata.domain,appId:e,dashboardId:r.id});ee(m)}},[e,r.id,r.metadata.domain,B]),Xe=u.useCallback(()=>{if(d){d(`dashboard:${e}/${r.id}`);return}ut()},[e,r.id,ut,d]),xt=x?!!f:I,rt=u.useCallback(()=>{if(K(!1),x){x(!0);return}Q(!0)},[x]),Rt=u.useCallback(()=>{if(K(!1),x){x(!f);return}Q(m=>!m)},[f,x]);return t.jsxs("div",{style:{display:"block",minHeight:0},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[(!n||i)&&t.jsxs("div",{style:Gi,children:[t.jsx("div",{style:{flex:1,minWidth:0},children:n?null:t.jsxs(t.Fragment,{children:[t.jsx("h2",{style:{margin:0,fontSize:20,lineHeight:1.18,fontWeight:780},children:r.metadata.title}),r.metadata.description?t.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&&t.jsx(fr,{open:X,onToggle:()=>K(m=>!m),buttonStyle:Ki,onCertifiedBlock:()=>{K(!1),tt()},onText:()=>{K(!1),Me()},onHeading:()=>{K(!1),Ve()},onAi:rt}),i&&r.layout.items.length>1&&t.jsx("button",{type:"button",onClick:()=>void Pt(),disabled:ne,style:Qi(!1),title:"Auto-arrange every tile into a clean, gap-free grid",children:t.jsx(Wr,{size:15,strokeWidth:2})}),!n&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",onClick:Rt,style:Ue(xt),children:[t.jsx(Ct,{size:14,strokeWidth:2}),xt?"Hide copilot":"AI Copilot"]}),t.jsxs("button",{type:"button",onClick:Xe,style:Ue(!1),title:"Open focused dashboard lineage",children:[t.jsx(Lr,{size:14,strokeWidth:2}),"Lineage"]})]})]}),i&&t.jsx("div",{style:Yi,children:"Drag tiles, select a block for Copilot context, or use the tile controls for sizing and chart settings."}),!i&&T?t.jsx(ni,{story:T,onResearch:rt,onEvidence:Xe}):ie?t.jsx(ii,{story:ie}):null,ae.length===0?t.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:[t.jsx("div",{style:{fontSize:16,fontWeight:700,marginBottom:6},children:Ce>0||H>0?"No stakeholder-ready tiles yet":"Build this dashboard page"}),t.jsx("div",{style:{maxWidth:520,opacity:.68,lineHeight:1.45},children:Ce>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.":H>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."}),t.jsx("div",{style:{marginTop:18,display:"flex",gap:8,flexWrap:"wrap",justifyContent:"center"},children:t.jsx(fr,{open:X,onToggle:()=>K(m=>!m),buttonLabel:"Add tile",buttonStyle:la,onCertifiedBlock:()=>{K(!1),tt()},onText:()=>{K(!1),Me()},onHeading:()=>{K(!1),Ve()},onAi:rt})})]}):y?t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:22},children:y.map(m=>{var v,R;const j=(v=y.find(O=>O.kind==="appendix"))==null?void 0:v.id,w=((R=y.find(O=>O.kind==="insight"))==null?void 0:R.id)??y[0].id,F=O=>O.sectionId&&y.some(ze=>ze.id===O.sectionId)?O.sectionId:(O.trustState==="review_required"||O.reviewStatus==="review_required")&&j?j:w,fe=(te??ae).filter(O=>F(O)===m.id);if(fe.length===0)return null;const je=Math.min(...fe.map(O=>O.y)),g=m.kind==="appendix";return t.jsxs("section",{"aria-label":m.title,children:[m.kind!=="exec_summary"?t.jsxs("div",{style:{marginBottom:10},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("h3",{style:{margin:0,fontSize:15,fontWeight:800,color:"var(--dql-app-text, #0f172a)"},children:m.title}),g?t.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]}),m.narrative?t.jsx("p",{style:{margin:"4px 0 0",fontSize:12.5,lineHeight:1.5,color:"var(--dql-app-text-muted, #64748b)",maxWidth:860},children:m.narrative}):null]}):null,t.jsx("div",{style:{display:"grid",gridTemplateColumns:G?"minmax(0, 1fr)":`repeat(${L}, 1fr)`,gridAutoRows:G?"auto":`${se}px`,gap:12,...g?{opacity:.96}:{}},children:fe.map(O=>t.jsx(cr,{item:{...O,y:O.y-je},tile:ue.get(O.i),loading:$,error:E,themeMode:A.themeMode,editable:!1,narrow:G,cols:L,selected:!!(Te(O)&&Te(O)===s),onFocusBlock:o,onAskBlock:p,onMove:()=>{},onDragMove:()=>{},onDragEnd:()=>{},onPatch:ze=>void He(O.i,ze)},O.i))})]},m.id)})}):t.jsxs("div",{ref:U,style:{display:"grid",gridTemplateColumns:G?"minmax(0, 1fr)":`repeat(${L}, 1fr)`,gridAutoRows:G?"auto":`${se}px`,gap:12},children:[b&&!G&&t.jsx("div",{"aria-hidden":"true",style:{gridColumn:`${b.x+1} / span ${b.w}`,gridRow:`${b.y+1} / span ${b.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}}),ae.map(m=>t.jsx(cr,{item:m,tile:ue.get(m.i),loading:$,error:E,themeMode:A.themeMode,editable:i,narrow:G,cols:L,selected:!!(Te(m)&&Te(m)===s),onFocusBlock:o,onAskBlock:p,onMove:j=>void It(m.i,j),onDragMove:j=>Tt(m.i,j),onDragEnd:$t,onPatch:j=>void He(m.i,j)},m.i))]}),!i&&q?t.jsx(li,{run:q,variables:oe}):null]}),le&&!d&&t.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:Da,position:"sticky",top:12,padding:12},children:t.jsx(ji,{lineage:B})}),I&&!x&&t.jsx(Mr,{t:S,title:"Dashboard AI",subtitle:"Scoped to this App dashboard first",expanded:me,onToggleExpanded:()=>pe(m=>!m),onClose:()=>{Q(!1),pe(!1)},floating:!0,ariaLabel:"Dashboard AI",style:Xi(me),children:t.jsx(u.Suspense,{fallback:t.jsx("div",{style:{padding:16,fontSize:12,color:S.textSecondary},children:"Loading Dashboard AI…"}),children:t.jsx(Za,{themeMode:A.themeMode,title:"Dashboard AI",scopeHint:"Scoped to this App dashboard first",audience:"stakeholder",workspaceContext:{appId:e,dashboardId:r.id,dashboardContext:_e},initialMode:"auto",threadId:re.threadId,onThreadIdChange:re.onThreadIdChange},`${e}:${r.id}`)})}),D&&t.jsx(wi,{blocks:V,search:de,onSearch:C,onClose:()=>_(!1),onAdd:m=>void ct(m)}),ye&&t.jsx(qi,{kind:ye,value:be,onChange:J,onClose:()=>{ce(null),J("")},onSave:()=>void Nt()})]})}function cr({item:e,tile:r,loading:a,error:i,themeMode:n,editable:l,narrow:s,cols:o,selected:p,onFocusBlock:d,onAskBlock:f,onMove:x,onDragMove:c,onDragEnd:A,onPatch:S}){var he;const q=u.useRef(null),[h,T]=u.useState(null),[z,Y]=u.useState(!1),$=Te(e),k=!!(!l&&$&&f),E=$?`block:${$}`:e.semantic?`semantic:${e.semantic.id}`:e.aiPin?`aiPin:${e.aiPin.id}`:"text",M=dt(String(e.viz.type??"table")),I=Le(e),Q=I==null?void 0:I.component,re=(I==null?void 0:I.insightTitle)||e.title||E,D=(r==null?void 0:r.tileType)==="aiPin"?((he=r.aiPin)==null?void 0:he.certification)==="certified"?"certified":"review_required":void 0,_=(I==null?void 0:I.trustState)??D??((r==null?void 0:r.certificationStatus)==="certified"?"certified":void 0),V=!!I,W=e.h<=2&&(M==="single_value"||M==="kpi"||M==="gauge"),[de,C]=u.useState(!1),le=l&&(de||p||z),we=Mi(e,I),B=!!(k&&(de||p)),ee=X=>{const K=Kt(X),me=e.viz.options??{},pe=Le(e);S({viz:{...e.viz,type:K,options:{...me,chart:X,...pe?{dqlGenUi:{...pe,defaultVisualization:K}}:{}}},display:Xr(e,K,pe)})},ne=X=>{if(s)return;const K=q.current;if(!K)return;X.preventDefault(),X.stopPropagation();const me=K.getBoundingClientRect(),pe={x:X.clientX-me.left,y:X.clientY-me.top},ye={x:X.clientX,y:X.clientY},ce=J=>{T({x:J.clientX-ye.x,y:J.clientY-ye.y}),c==null||c({clientX:J.clientX-pe.x,clientY:J.clientY-pe.y})},be=J=>{window.removeEventListener("pointermove",ce),window.removeEventListener("pointerup",be),T(null),A==null||A(),x({clientX:J.clientX-pe.x,clientY:J.clientY-pe.y})};window.addEventListener("pointermove",ce),window.addEventListener("pointerup",be,{once:!0})};return t.jsxs("div",{ref:q,onMouseEnter:()=>C(!0),onMouseLeave:()=>C(!1),onClick:()=>{$&&(d==null||d($))},style:{gridColumn:s?"1 / -1":`${e.x+1} / span ${e.w}`,gridRow:s?"auto":`${e.y+1} / span ${e.h}`,transform:h?`translate(${h.x}px, ${h.y}px) scale(1.02)`:void 0,opacity:h?.92:1,zIndex:h?30:void 0,position:"relative",background:V?Oi(Q):"var(--dql-app-surface, var(--surface, rgba(0,0,0,0.02)))",border:p||h?"1.5px solid var(--dql-app-accent, var(--accent, #4f46e5))":V?"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:W?12:14,paddingBottom:B?W?42:46:W?12:14,display:"flex",flexDirection:"column",gap:W?4:V?10:6,minHeight:s?qn(e,I):0,overflow:"visible",boxShadow:h?"0 16px 40px rgba(0,0,0,0.22)":p?"0 0 0 3px var(--dql-app-accent-soft, rgba(79,70,229,0.12))":void 0,cursor:h?"grabbing":$?"pointer":void 0,transition:h?void 0:"box-shadow 120ms ease, transform 120ms ease"},children:[B?t.jsxs("button",{type:"button",style:di,onClick:X=>{X.stopPropagation(),$&&(d==null||d($)),$&&(f==null||f($,ci(e.title??$)))},title:"Open app Copilot for this tile",children:[t.jsx(Re,{size:11,strokeWidth:2})," Ask AI"]}):null,l&&!s?t.jsx("div",{style:{position:"absolute",top:10,left:10,zIndex:3,opacity:le?1:0,pointerEvents:le?"auto":"none",transition:"opacity 120ms ease"},children:t.jsx("button",{type:"button",title:"Drag to move tile",onPointerDown:ne,style:mn,children:t.jsx(Pa,{size:14,strokeWidth:2.2})})}):null,l?t.jsxs("div",{style:{position:"absolute",top:10,right:10,zIndex:4,display:"flex",alignItems:"center",gap:4,opacity:le?1:0,pointerEvents:le?"auto":"none",transition:"opacity 120ms ease"},children:[W?null:t.jsx("span",{style:{fontSize:10,padding:"2px 8px",borderRadius:999,background:"var(--surface-hover, rgba(0,0,0,0.06))",opacity:.85},children:e.viz.type}),t.jsx(xi,{item:e,cols:o,settingsOpen:z,onToggleSettings:()=>Y(X=>!X),onPatch:S})]}):null,V?t.jsx("div",{style:{minHeight:W?26:42,paddingLeft:le?30:0,paddingRight:le?W?82:134:0,transition:"padding 120ms ease",display:"grid",gap:7},children:t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,minWidth:0},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:W?12:13,fontWeight:780,lineHeight:1.25,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:re}),t.jsxs("div",{style:an,children:[_?t.jsx(ot,{trust:_}):null,I?t.jsx("span",{style:$e,children:Dr(I)}):null,I!=null&&I.layoutIntent?t.jsx("span",{style:$e,children:Ae(String(I.layoutIntent))}):null]})]}),l&&we.length>1?t.jsx(ai,{value:Ze(e.viz.type),options:we,onChange:ee}):null]})}):t.jsxs("div",{style:{minHeight:W?22:26,paddingLeft:le?30:0,paddingRight:le?W?82:134:0,transition:"padding 120ms ease"},children:[t.jsx("div",{style:{fontSize:W?12:13,fontWeight:720,lineHeight:1.25,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title??E}),D?t.jsxs("div",{style:{marginTop:5,display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[t.jsx(ot,{trust:D}),t.jsx("span",{style:$e,children:"AI generated"})]}):W?null:t.jsx("div",{style:{marginTop:5,fontSize:10.5,opacity:.58,fontFamily:"var(--font-mono, monospace)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:E})]}),l&&z?t.jsx(gi,{item:e,tile:r,cols:o,onPatch:S}):null,t.jsx("div",{style:{flex:1,minHeight:0,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",marginTop:W?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:t.jsx(ui,{item:e,tile:r,loading:a,error:i,themeMode:n,genUi:I})}),l?null:t.jsx(ti,{tile:r,themeMode:n})]})}function ti({tile:e,themeMode:r}){const a=Ne[r],i=u.useMemo(()=>ri(e),[e]);return i?t.jsxs("div",{style:{padding:"4px 10px 8px",fontSize:11.5,color:a.textMuted,lineHeight:1.4,display:"flex",gap:5,alignItems:"baseline"},children:[t.jsx("span",{style:{color:a.accent},children:"•"}),t.jsx("span",{children:i})]}):null}function ri(e){var f,x;const r=(f=e==null?void 0:e.result)==null?void 0:f.rows,a=(x=e==null?void 0:e.result)==null?void 0:x.columns;if(!Array.isArray(r)||r.length===0||!Array.isArray(a)||a.length===0)return null;const i=r[0],n=c=>{if(typeof c=="number"&&Number.isFinite(c))return c;if(typeof c=="string"){const A=Number(c.replace(/[$,%\s]/g,""));return Number.isFinite(A)&&c.trim()?A:void 0}},l=a.find(c=>n(i==null?void 0:i[c])!==void 0),s=a.find(c=>c!==l&&typeof(i==null?void 0:i[c])=="string");if(!l)return null;if(r.length===1){const c=n(r[0][l]);return c!==void 0?`${l}: ${Bt(c)}.`:null}const o=r.map(c=>({label:s?String(c[s]??"—"):"top",value:n(c[l])??0})).sort((c,A)=>A.value-c.value),p=o.reduce((c,A)=>c+A.value,0),d=o[0];return d?p>0?`${d.label} leads ${l} at ${Bt(d.value)} (${Math.round(d.value/p*100)}%).`:`${d.label} leads ${l} at ${Bt(d.value)}.`:null}function Bt(e){const r=Math.abs(e);return r>=1e6?`${(e/1e6).toFixed(1)}M`:r>=1e3?`${(e/1e3).toFixed(1)}K`:Number.isInteger(e)?String(e):e.toFixed(2)}function ai({value:e,options:r,onChange:a}){return t.jsx("div",{style:ln,"aria-label":"Visualization",children:r.map(i=>t.jsx("button",{type:"button",title:i.label,onClick:n=>{n.stopPropagation(),a(i.value)},style:sn(e===i.value),children:Fi(i.value)},i.value))})}function ot({trust:e}){const r=e==="certified",a=r?"Certified":e==="review_required"?"Review required":"Draft ready";return t.jsxs("span",{style:nn(r),children:[r?t.jsx(We,{size:10,strokeWidth:2.4}):t.jsx(Qe,{size:10,strokeWidth:2.4}),a]})}function ii({story:e}){return t.jsxs("section",{style:Ur,"aria-label":"Current dashboard story",children:[t.jsxs("div",{style:ea,children:[t.jsx("div",{style:ta,children:t.jsx(Re,{size:15,strokeWidth:2.2})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:ra,children:"Story from current results"}),t.jsx("h3",{style:aa,children:e.title})]}),e.trust?t.jsx(ot,{trust:e.trust}):null]}),t.jsx("p",{style:ia,children:e.summary}),t.jsxs("div",{style:sr,children:[t.jsx("span",{style:na,children:e.sourceTitle}),e.filters.map(r=>t.jsxs("span",{style:et,children:[r.label,": ",r.value]},`${r.label}:${r.value}`)),e.chips.map(r=>t.jsx("span",{style:et,children:r},r))]})]})}function ni({story:e,onEvidence:r,onResearch:a}){return t.jsxs("section",{style:{...Ur,padding:"20px 22px",marginBottom:16},"aria-label":"Business Story",children:[t.jsxs("div",{style:ea,children:[t.jsx("div",{style:ta,children:t.jsx(Re,{size:15,strokeWidth:2.2})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:ra,children:"Business Story · current filters"}),t.jsx("h2",{style:{...aa,fontSize:19},children:e.headline})]}),t.jsx(ot,{trust:e.trustState})]}),t.jsxs("div",{style:{display:"grid",gap:10,marginTop:12,maxWidth:920},children:[e.paragraphs.slice(0,2).map((i,n)=>t.jsx("p",{style:{...ia,margin:0,fontSize:14,lineHeight:1.65},children:ur(i)},n)),e.implication?t.jsxs("p",{style:{margin:0,fontSize:13,lineHeight:1.55,fontWeight:650},children:["What this means: ",ur(e.implication)]}):null]}),t.jsxs("div",{style:{...sr,marginTop:14},children:[t.jsx("span",{style:na,children:e.generatedBy==="ai"?"AI wording · verified facts":"Verified result summary"}),t.jsxs("span",{style:et,children:[e.evidenceRefs.length," evidence source",e.evidenceRefs.length===1?"":"s"]}),e.caveat?t.jsx("span",{style:et,children:e.caveat}):null,t.jsx("span",{style:{flex:1}}),t.jsx("button",{type:"button",onClick:r,style:zr,children:"View evidence"}),t.jsx("button",{type:"button",onClick:a,style:zr,children:"Research deeper"})]})]})}function li({run:e,variables:r}){const a=e.tiles.filter(n=>n.status!=="ok"),i=Object.entries(r).filter(([,n])=>n!=null&&n!=="");return t.jsxs("details",{style:si,"aria-label":"Evidence and review appendix",children:[t.jsxs("summary",{style:oi,children:["Evidence & review appendix",t.jsxs("span",{style:{opacity:.62,fontWeight:600},children:[e.story.evidenceRefs.length," sources · ",a.length?`${a.length} issue${a.length===1?"":"s"}`:"all visible sources ran"]})]}),t.jsxs("div",{style:{display:"grid",gap:12,padding:"0 16px 16px"},children:[t.jsxs("div",{style:pi,children:[t.jsxs("div",{children:[t.jsx("strong",{children:"Run"}),t.jsx("br",{}),t.jsx("span",{children:e.runId})]}),t.jsxs("div",{children:[t.jsx("strong",{children:"Snapshot"}),t.jsx("br",{}),t.jsx("span",{children:e.snapshotId})]}),t.jsxs("div",{children:[t.jsx("strong",{children:"Trust"}),t.jsx("br",{}),t.jsx("span",{children:e.story.trustState})]}),t.jsxs("div",{children:[t.jsx("strong",{children:"Filters"}),t.jsx("br",{}),t.jsx("span",{children:i.length?i.map(([n,l])=>`${n}: ${String(l)}`).join(" · "):"Current unfiltered scope"})]})]}),t.jsxs("div",{children:[t.jsx("strong",{style:{fontSize:12},children:"Evidence used by the story"}),t.jsx("div",{style:{...sr,marginTop:7},children:e.story.evidenceRefs.map(n=>t.jsx("span",{style:et,children:n},n))})]}),a.length?t.jsxs("div",{children:[t.jsx("strong",{style:{fontSize:12},children:"Items requiring review"}),t.jsx("ul",{style:{margin:"7px 0 0",paddingLeft:18,fontSize:12,lineHeight:1.55},children:a.map(n=>t.jsxs("li",{children:[n.title??n.tileId,": ",n.error??n.status]},n.tileId))})]}):null]})]})}function ur(e){return e.split(/(\*\*[^*]+\*\*)/g).filter(Boolean).map((r,a)=>r.startsWith("**")&&r.endsWith("**")?t.jsx("strong",{children:r.slice(2,-2)},a):r)}const si={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))"},oi={cursor:"pointer",padding:"12px 16px",fontSize:12.5,fontWeight:760,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},pi={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))"},di={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 ci(e){return`/ask Explain ${e} for a stakeholder. Start with the business meaning, current result, active filters, caveats, and recommended next action.`}function ui({item:e,tile:r,loading:a,error:i,themeMode:n,genUi:l}){var p,d,f,x;if(a&&!r)return t.jsx("span",{children:"Loading data..."});if((r==null?void 0:r.tileType)==="text")return l?t.jsx(hi,{title:e.title??l.insightTitle??"Generated section",markdown:((p=r.text)==null?void 0:p.markdown)??"",genUi:l,themeMode:n}):t.jsx(bi,{markdown:((d=r.text)==null?void 0:d.markdown)??"",variant:((f=r.viz)==null?void 0:f.type)==="heading"?"heading":"text",themeMode:n});if((r==null?void 0:r.tileType)==="aiPin"&&r.aiPin)return t.jsx(vi,{pin:r.aiPin,result:r.result,themeMode:n});if(i&&!r)return t.jsx("span",{children:i});if(!r)return t.jsx("span",{children:"No run result."});if(r.status==="unauthorized")return t.jsx("span",{children:"Not authorized."});if(r.status==="unresolved")return t.jsx("span",{children:r.error??"Block reference unresolved."});if(r.status==="error")return t.jsx("span",{children:r.error??"Tile failed."});if(!r.result)return t.jsx("span",{children:"No result."});const s=Yr(e,r.chartConfig);return String(s.chart??((x=r.viz)==null?void 0:x.type)??"").toLowerCase()==="table"||e.viz.type==="table"||e.viz.type==="pivot"?(l==null?void 0:l.component)==="EvidenceTable"||(l==null?void 0:l.component)==="PivotTable"?t.jsx(mi,{result:r.result,genUi:l,themeMode:n}):t.jsx("div",{style:{width:"100%",alignSelf:"stretch"},children:t.jsx(Aa,{result:r.result,themeMode:n})}):t.jsx("div",{style:{width:"100%",alignSelf:"stretch"},children:t.jsx(Ca,{result:r.result,themeMode:n,chartConfig:s})})}function xi({item:e,cols:r,settingsOpen:a,onToggleSettings:i,onPatch:n}){const[l,s]=u.useState(!1),o=p=>{s(!1),n(oa(e,r,p))};return t.jsxs("div",{style:{display:"flex",gap:4,alignItems:"center",flexWrap:"wrap",justifyContent:"flex-end"},children:[t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{type:"button",title:"Choose tile size",onClick:()=>s(p=>!p),style:Et,children:t.jsx(Ra,{size:13,strokeWidth:2})}),l?t.jsx(fi,{onPick:o,onClose:()=>s(!1)}):null]}),t.jsx("button",{type:"button",title:"Chart and field settings",onClick:i,style:Et,children:t.jsx(Ka,{size:13,strokeWidth:2,color:a?"var(--accent, #4f46e5)":void 0})}),t.jsx("button",{type:"button",title:"Remove tile",onClick:()=>n(null),style:Et,children:t.jsx(ya,{size:13,strokeWidth:2})})]})}function fi({onPick:e,onClose:r}){return t.jsx("div",{style:bn,onMouseLeave:r,children:Gr.map(a=>t.jsxs("button",{type:"button",onClick:()=>e(a.id),style:vn,children:[t.jsx("span",{style:{fontSize:12,fontWeight:750},children:a.label}),t.jsx("span",{style:{fontSize:11,opacity:.66},children:a.description})]},a.id))})}function gi({item:e,tile:r,cols:a,onPatch:i}){var $;const n=r==null?void 0:r.result,l=Yr(e,r==null?void 0:r.chartConfig),s=Ze(l.chart),o=Le(e),[p,d]=u.useState(!1),[f,x]=u.useState(null),[c,A]=u.useState(null),S=u.useMemo(()=>$a(n),[n]),q=u.useMemo(()=>{const k=new Map;if(!n)return k;const E=new Set(S.metrics),M=new Set(S.dimensions);for(const I of n.columns)E.has(I)?k.set(I,"measure"):M.has(I)?k.set(I,"dimension"):k.set(I,Sa(za(I,n.rows)));return k},[n,S]),h=(n==null?void 0:n.columns.filter(k=>q.get(k)==="measure"))??[],T=(n==null?void 0:n.columns.filter(k=>q.get(k)!=="measure"))??[],z=k=>{const E=hr({...l,...k}),M=Kt(E.chart),I=Le(e),Q={...E};I&&(Q.dqlGenUi={...I,defaultVisualization:M}),i({title:E.title||e.title,viz:{...e.viz,type:M,options:Q},display:Xr(e,M,I)})},Y=async()=>{d(!0),A(null),x(null);const k=Te(e)??e.title,E=await Z.recommendVisualization({...k?{blockRef:k}:{},resultSchema:n?{columns:n.columns}:void 0,rowSample:n==null?void 0:n.rows.slice(0,5),prompt:[e.title,o==null?void 0:o.rationale].filter(Boolean).join(" "),allowedVisualizations:o==null?void 0:o.allowedVisualizations});if(d(!1),!E.ok){A(E.error);return}const M=Ze(E.display.defaultVisualization),I=Kt(M),Q=E.display.fieldHints??{},re=hr({...l,chart:M,title:l.title??e.title,x:Q.x??Q.label??l.x,y:Q.y??Q.value??l.y,color:Q.color??l.color});i({title:re.title||e.title,viz:{...e.viz,type:I,options:{...re}},display:E.display});const D=E.evidence.map(V=>V.source).slice(0,3).join(", "),_=E.warnings[0];x(_?`${E.display.component}: ${_}`:`${E.display.component}${D?` from ${D}`:""}`)};return t.jsxs("div",{style:Zi,children:[t.jsxs("div",{style:{display:"grid",gap:6},children:[t.jsx("div",{style:{fontSize:10,fontWeight:800,textTransform:"uppercase",opacity:.58},children:"Tile size"}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:Gr.map(k=>t.jsx("button",{type:"button",title:k.description,onClick:()=>i(oa(e,a,k.id)),style:yn(wn(e,a,k.id)),children:k.label},k.id))})]}),t.jsxs("div",{style:Ui,children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,justifyContent:"space-between"},children:[t.jsxs("div",{style:{minWidth:0},children:[t.jsx("div",{style:{fontSize:10,fontWeight:800,textTransform:"uppercase",opacity:.58},children:"Display contract"}),t.jsx("div",{style:{marginTop:3,fontSize:11,lineHeight:1.35,opacity:.76},children:(o==null?void 0:o.rationale)??(($=e.display)==null?void 0:$.rationale)??"Choose a governed visualization for this app tile."})]}),t.jsxs("button",{type:"button",onClick:()=>void Y(),disabled:p,style:en(p),title:"Recommend visualization from block hints and result fields",children:[t.jsx(Wr,{size:12,strokeWidth:2.2}),p?"Thinking":"AI recommend"]})]}),t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:[o!=null&&o.component?t.jsx("span",{style:$e,children:Dr(o)}):null,o!=null&&o.defaultVisualization?t.jsx("span",{style:$e,children:Ae(String(o.defaultVisualization))}):null,o!=null&&o.reviewStatus?t.jsx("span",{style:$e,children:Ae(String(o.reviewStatus))}):null]}),f?t.jsx("div",{style:sa,children:f}):null,c?t.jsx("div",{style:tn,children:c}):null]}),t.jsxs("div",{style:Di,children:[t.jsxs("label",{style:Yt,children:["Title",t.jsx("input",{value:l.title??e.title??"",onChange:k=>z({title:k.target.value||void 0}),style:Xt})]}),t.jsxs("label",{style:Yt,children:["Chart",t.jsx("select",{value:s,onChange:k=>z({chart:k.target.value}),style:Xt,children:ar.map(k=>t.jsx("option",{value:k.value,children:k.label},k.value))})]}),t.jsx(mt,{label:"X",value:l.x,columns:(n==null?void 0:n.columns)??[],onChange:k=>z({x:k})}),t.jsx(mt,{label:"Y",value:l.y,columns:(n==null?void 0:n.columns)??[],onChange:k=>z({y:k})}),t.jsx(mt,{label:"Color",value:l.color,columns:(n==null?void 0:n.columns)??[],onChange:k=>z({color:k})}),t.jsx(mt,{label:"Facet",value:l.facet,columns:(n==null?void 0:n.columns)??[],onChange:k=>z({facet:k})})]}),n?t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[t.jsx(xr,{title:"Measures",columns:h,onPick:k=>z({y:k})}),t.jsx(xr,{title:"Dimensions",columns:T,onPick:k=>z({x:k})})]}):t.jsx("div",{style:{fontSize:11,opacity:.64},children:"Run results are needed before field slots can be inferred."})]})}function mt({label:e,value:r,columns:a,onChange:i}){return t.jsxs("label",{style:Yt,children:[e,t.jsxs("select",{value:r??"",onChange:n=>i(n.target.value||void 0),style:Xt,children:[t.jsx("option",{value:"",children:"Auto"}),a.map(n=>t.jsx("option",{value:n,children:n},n))]})]})}function xr({title:e,columns:r,onPick:a}){return t.jsxs("div",{style:{display:"grid",gap:4,minWidth:0},children:[t.jsx("div",{style:{fontSize:10,fontWeight:800,textTransform:"uppercase",opacity:.58},children:e}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:r.length===0?t.jsx("span",{style:{fontSize:11,opacity:.55},children:"None"}):r.slice(0,10).map(i=>t.jsx("button",{type:"button",onClick:()=>a(i),style:rn,children:i},i))})]})}function fr({open:e,onToggle:r,onCertifiedBlock:a,onText:i,onHeading:n,onAi:l,buttonLabel:s,buttonStyle:o}){return t.jsxs("div",{style:{position:"relative",display:"inline-flex"},children:[t.jsxs("button",{type:"button",onClick:r,title:"Add tile",style:o??Ue(e),children:[t.jsx(kt,{size:15,strokeWidth:2.2}),s?t.jsx("span",{children:s}):null]}),e&&t.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:[t.jsx(bt,{title:"Certified block",description:"Chart, table, or KPI from this App domain",onClick:a}),t.jsx(bt,{title:"Text / summary",description:"Narrative, notes, caveats, or CXO context",onClick:i}),t.jsx(bt,{title:"Section heading",description:"Separate an App page into readable groups",onClick:n}),t.jsx(bt,{title:"Copilot insight",description:"Open scoped AI, then pin the reviewed answer to this App",onClick:l})]})]})}function bt({title:e,description:r,onClick:a}){return t.jsxs("button",{type:"button",onClick:a,style:Ji,children:[t.jsx("span",{style:{fontSize:12,fontWeight:700},children:e}),t.jsx("span",{style:{fontSize:11,opacity:.66},children:r})]})}function hi({title:e,markdown:r,genUi:a,themeMode:i}){var p;const n=Ne[i],l=Wi(r,e),s=a.component==="TrustCallout",o=a.component==="ResearchActions";return t.jsxs("div",{style:on(s),children:[t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-start"},children:[t.jsx("span",{style:pn(s),children:s?t.jsx(Qe,{size:15}):o?t.jsx(Re,{size:15}):t.jsx(We,{size:15})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:13,fontWeight:780,lineHeight:1.25},children:a.insightTitle??e}),t.jsx("div",{style:{marginTop:6,fontSize:13,lineHeight:1.45,color:n.textSecondary},children:l})]})]}),t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[a.trustState?t.jsx(ot,{trust:a.trustState}):null,a.reviewStatus?t.jsx("span",{style:$e,children:Ae(a.reviewStatus)}):null]}),(p=a.followUpActions)!=null&&p.length?t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:a.followUpActions.slice(0,3).map(d=>t.jsx("span",{style:dn,children:Ae(d)},d))}):null]})}function mi({result:e,genUi:r,themeMode:a}){var x;const i=Ne[a],n=e.rows??[],l=e.columns??[],s=Vi(l,n,(x=r.fieldHints)==null?void 0:x.label),o=l.find(c=>/\b(status|quality|trust|certification|review)\b/i.test(c)),p=l.filter(c=>c!==s&&c!==o).filter(c=>Lt(c)<90||De(c,n)).sort((c,A)=>Lt(c)-Lt(A)).slice(0,2),d=l.filter(c=>c!==s&&c!==o&&!p.includes(c)).slice(0,2),f=e.rowCount??n.length;return t.jsxs("div",{style:cn,children:[t.jsxs("div",{style:{fontSize:11.5,color:i.textSecondary},children:[f," ",f===1?"row":"rows"," across ",l.length," ",l.length===1?"field":"fields"]}),t.jsx("div",{style:un,children:n.slice(0,4).map((c,A)=>{const S=s?Pe(c[s]):`Row ${A+1}`,q=o?Pe(c[o]):null;return t.jsxs("div",{style:xn,children:[t.jsxs("div",{style:{minWidth:0},children:[t.jsx("div",{style:{fontSize:12.5,fontWeight:760,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S}),d.length?t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5,marginTop:4},children:d.map(h=>t.jsxs("span",{style:fn,children:[Ae(h),": ",Pe(c[h])]},h))}):null]}),t.jsxs("div",{style:{display:"flex",gap:5,flexWrap:"wrap",justifyContent:"flex-start",minWidth:0},children:[p.map(h=>t.jsxs("span",{style:gn,children:[t.jsx("span",{style:{opacity:.62},children:Ae(h)}),t.jsx("strong",{children:Pe(c[h])})]},h)),q?t.jsx("span",{style:hn,children:q}):null]})]},A)})}),n.length>4?t.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 bi({markdown:e,variant:r="text",themeMode:a}){const i=Ne[a];return t.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:Fr(e,i)})}function vi({pin:e,result:r,themeMode:a}){var p;const[i,n]=u.useState(null),l=Ne[a]??Ne.light,s=async()=>{n("Refreshing...");const d=await Z.refreshAiPin(e.appId,e.id);n(d.ok?"Refreshed.":d.error??"Refresh failed."),window.dispatchEvent(new CustomEvent("dql-app-dashboard-updated",{detail:{appId:e.appId,dashboardId:e.dashboardId}}))},o=async()=>{n("Creating draft...");const d=await Z.promoteAiPin(e.appId,e.id);n(d.ok?`Draft created: ${d.blockPath}`:d.error??"Promotion failed."),window.dispatchEvent(new CustomEvent("dql-app-dashboard-updated",{detail:{appId:e.appId,dashboardId:e.dashboardId}}))};return t.jsxs("div",{style:{width:"100%",alignSelf:"stretch",overflow:"auto",fontStyle:"normal",lineHeight:1.5,display:"grid",gap:10},children:[t.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center",flexWrap:"wrap"},children:[t.jsx("span",{style:{fontSize:10.5,fontWeight:800,color:e.certification==="certified"?"#15803d":"#b45309",background:e.certification==="certified"?"rgba(22,163,74,0.1)":"rgba(245,158,11,0.12)",border:`1px solid ${e.certification==="certified"?"rgba(22,163,74,0.22)":"rgba(245,158,11,0.24)"}`,borderRadius:999,padding:"3px 7px"},children:e.certification==="certified"?"Certified":"Review required"}),t.jsx("span",{style:{fontSize:10.5,color:"var(--color-text-muted, rgba(0,0,0,0.58))"},children:"Pinned report insight"})]}),t.jsx("div",{style:{minWidth:0},children:Fr(e.answer,l)}),(p=r==null?void 0:r.rows)!=null&&p.length?t.jsx(yi,{result:r}):null,t.jsxs("div",{style:{display:"flex",gap:6,marginTop:8,flexWrap:"wrap"},children:[e.sql&&t.jsx("button",{type:"button",onClick:()=>void s(),style:Cr,children:"Refresh"}),e.sql&&e.reviewStatus==="needs_review"&&t.jsx("button",{type:"button",onClick:()=>void o(),style:Cr,children:"Promote"}),e.refreshCadence==="daily"&&t.jsx("span",{style:{fontSize:11,opacity:.62},children:"daily"})]}),i&&t.jsx("div",{style:{marginTop:6,fontSize:11,opacity:.72},children:i}),e.lastRefreshError&&t.jsx("div",{style:{marginTop:8,color:"#f85149"},children:e.lastRefreshError})]})}function yi({result:e}){var i,n;const r=((i=e.columns)!=null&&i.length?e.columns:Object.keys(((n=e.rows)==null?void 0:n[0])??{})).slice(0,4),a=(e.rows??[]).slice(0,3);return!r.length||!a.length?null:t.jsxs("div",{style:{display:"grid",gap:6},children:[t.jsx("div",{style:{color:"var(--color-text-muted, rgba(0,0,0,0.58))",fontSize:11,fontWeight:750},children:"Supporting rows"}),t.jsx("div",{style:{overflow:"auto",border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11},children:[t.jsx("thead",{children:t.jsx("tr",{children:r.map(l=>t.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:Ae(l)},l))})}),t.jsx("tbody",{children:a.map((l,s)=>t.jsx("tr",{children:r.map(o=>t.jsx("td",{style:{padding:"5px 7px",borderBottom:s===a.length-1?"none":"1px solid var(--border-color, rgba(0,0,0,0.06))"},children:Pe(l[o])},o))},s))})]})})]})}function qi({kind:e,value:r,onChange:a,onClose:i,onSave:n}){const l=e==="heading";return t.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:t.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:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:16,fontWeight:800},children:l?"Add heading":"Add text tile"}),t.jsx("div",{style:{fontSize:12,opacity:.65,marginTop:4},children:l?"Create a section heading on this dashboard page.":"Create a narrative text tile on this dashboard page."})]}),l?t.jsx("input",{value:r,onChange:s=>a(s.target.value),onKeyDown:s=>{s.key==="Enter"&&n(),s.key==="Escape"&&i()},placeholder:"Executive summary",autoFocus:!0,style:Ar}):t.jsx("textarea",{value:r,onChange:s=>a(s.target.value),onKeyDown:s=>{s.key==="Escape"&&i(),s.key==="Enter"&&(s.metaKey||s.ctrlKey)&&n()},placeholder:"Add context, assumptions, or decisions...",rows:6,autoFocus:!0,style:{...Ar,resize:"vertical",lineHeight:1.45}}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[t.jsx("button",{type:"button",onClick:i,style:Ue(!1),children:"Cancel"}),t.jsx("button",{type:"button",onClick:n,disabled:!r.trim(),style:{...la,opacity:r.trim()?1:.65},children:"Add"})]})]})})}function wi({blocks:e,search:r,onSearch:a,onClose:i,onAdd:n}){const l=e.filter(s=>{const o=r.trim().toLowerCase();return o?[s.name,s.description,s.domain,...s.tags??[]].join(" ").toLowerCase().includes(o):!0});return t.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:t.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:[t.jsxs("div",{style:{padding:14,borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.1))",display:"flex",gap:10,alignItems:"center"},children:[t.jsx("div",{style:{fontSize:15,fontWeight:700,flex:1},children:"Add Certified Block"}),t.jsx("button",{type:"button",onClick:i,style:Ue(!1),children:"Close"})]}),t.jsx("div",{style:{padding:14,borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.08))"},children:t.jsx("input",{value:r,onChange:s=>a(s.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"}})}),t.jsx("div",{style:{overflow:"auto",padding:12,display:"grid",gap:8},children:l.length===0?t.jsx("div",{style:{padding:18,fontSize:12,opacity:.66},children:"No certified blocks match this App scope."}):l.map(s=>t.jsxs("button",{type:"button",onClick:()=>n(s),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:[t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:4},children:[t.jsx("span",{style:{fontSize:13,fontWeight:700},children:s.name}),t.jsx("span",{style:{fontSize:10,padding:"2px 6px",borderRadius:999,background:"rgba(63,185,80,0.14)",color:"#2ea043"},children:s.status}),t.jsx("span",{style:{fontSize:10,opacity:.68},children:s.domain}),t.jsx("span",{style:{fontSize:10,opacity:.68},children:s.chartType??"table"})]}),t.jsx("div",{style:{fontSize:12,opacity:.72},children:s.description||s.path})]},s.id))})]})})}function ji({lineage:e}){var n,l;const r=((n=e==null?void 0:e.graph)==null?void 0:n.nodes)??[],a=((l=e==null?void 0:e.graph)==null?void 0:l.edges)??[],i=(e==null?void 0:e.breadcrumbs)??[];return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:12,fontWeight:800,textTransform:"uppercase",opacity:.62,marginBottom:6},children:"App Lineage"}),t.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&&t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:i.map((s,o)=>t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"64px 1fr",gap:8,fontSize:12},children:[t.jsx("span",{style:{fontFamily:"monospace",opacity:.6},children:s.type}),t.jsx("span",{children:s.name})]},`${s.id}-${o}`))}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[t.jsx(gr,{label:"Nodes",value:r.length}),t.jsx(gr,{label:"Edges",value:a.length})]}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:r.slice(0,18).map(s=>t.jsxs("div",{style:{border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6,padding:8},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[t.jsx("span",{style:{color:"#0d1117",background:ba[s.type]??"#8b949e",borderRadius:3,padding:"1px 4px",fontSize:9,fontWeight:800,flexShrink:0},children:ma[s.type]??s.type.slice(0,4).toUpperCase()}),t.jsx("div",{style:{fontSize:12,fontWeight:700,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.name})]}),t.jsxs("div",{style:{fontSize:11,opacity:.62,fontFamily:"monospace",marginTop:4},children:[va[s.type]??s.type," · ",s.id]})]},s.id))})]})}function gr({label:e,value:r}){return t.jsxs("div",{style:{border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6,padding:8},children:[t.jsx("div",{style:{fontSize:11,opacity:.62},children:e}),t.jsx("div",{style:{fontSize:18,fontWeight:800},children:r})]})}function Te(e){return e.block?"blockId"in e.block?e.block.blockId??null:e.block.ref??null:null}function Yr(e,r){const a=e.viz.options??{};return{...r??{},...a,chart:Ze(String(a.chart??(r==null?void 0:r.chart)??e.viz.type)),title:a.title??(r==null?void 0:r.title)??e.title,colorPalette:a.colorPalette??(r==null?void 0:r.colorPalette)??"corporate"}}function Ze(e){const r=String(e??"table").toLowerCase().replace(/_/g,"-");return r==="single-value"?"kpi":ar.some(a=>a.value===r)?r:"table"}function Kt(e){const r=Ze(e);return r==="table"?"table":r.replace(/-/g,"_")}function hr(e){const r={};for(const[a,i]of Object.entries(e))i===void 0||i===""||(r[a]=i);return r.chart||(r.chart="table"),r}function Le(e){var a;if(yt(e.display)){const i=e.display,n=typeof i.component=="string"?i.component:void 0;return{version:1,component:n,role:Jr(n),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(l=>typeof l=="string"):void 0,fieldHints:yt(i.fieldHints)?Object.fromEntries(Object.entries(i.fieldHints).filter(l=>typeof l[1]=="string")):void 0,insightTitle:e.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=e.viz.options)==null?void 0:a.dqlGenUi;return yt(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:yt(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 mr(e,r){return{mode:"manual",component:e==="heading"?"NarrativePanel":"BusinessBrief",defaultVisualization:e,allowedVisualizations:[e],layoutIntent:e==="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 Xr(e,r,a){var l,s,o,p,d,f,x,c,A;const i=ki([r,...((l=e.display)==null?void 0:l.allowedVisualizations)??[],...(a==null?void 0:a.allowedVisualizations)??[]]),n=((s=e.display)==null?void 0:s.component)??Si(r);return{mode:((o=e.display)==null?void 0:o.mode)??(a?"ai_generated":e.block?"block_hint":"manual"),component:n,defaultVisualization:r,allowedVisualizations:i.length?i:[r],...(p=e.display)!=null&&p.fieldHints||a!=null&&a.fieldHints?{fieldHints:((d=e.display)==null?void 0:d.fieldHints)??(a==null?void 0:a.fieldHints)}:{},layoutIntent:Ei(((f=e.display)==null?void 0:f.layoutIntent)??(a==null?void 0:a.layoutIntent)),rationale:((x=e.display)==null?void 0:x.rationale)??(a==null?void 0:a.rationale)??"Visualization selected for this consumer surface.",trustState:lr(((c=e.display)==null?void 0:c.trustState)??(a==null?void 0:a.trustState)),reviewStatus:_i(((A=e.display)==null?void 0:A.reviewStatus)??(a==null?void 0:a.reviewStatus))}}function ki(e){return Array.from(new Set(e.filter(r=>typeof r=="string"&&r.trim()).map(r=>r.trim())))}function Si(e){return e==="single_value"||e==="kpi"||e==="gauge"?"KpiMetric":e==="line"||e==="area"?"TrendPanel":e==="bar"||e==="grouped_bar"||e==="stacked_bar"||e==="donut"||e==="pie"?"RankingPanel":e==="pivot"?"PivotTable":e==="text"||e==="heading"?"NarrativePanel":"EvidenceTable"}function Jr(e){return e==="BusinessBrief"?"business_summary":e==="KpiMetric"?"kpi":e==="TrendPanel"?"trend":e==="RankingPanel"?"breakdown":e==="TrustCallout"?"trust":e==="ResearchActions"?"research":e==="NarrativePanel"?"narrative":e?"evidence":void 0}function zi(e){var s,o,p,d;if(Te(e)||e.aiPin)return!1;const r=Le(e),a=(r==null?void 0:r.component)??((s=e.display)==null?void 0:s.component),i=(r==null?void 0:r.role)??Jr(a),n=lr(String((r==null?void 0:r.trustState)??((o=e.display)==null?void 0:o.trustState)??"review_required"));if(a==="TrustCallout"||a==="ResearchActions"||i==="trust"||i==="research")return!0;if(a!=="NarrativePanel"&&a!=="BusinessBrief"||n==="certified")return!1;const l=[e.title,(p=e.text)==null?void 0:p.markdown,(d=e.display)==null?void 0:d.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(l)}function Ai(e,r,a){const n=[...e.filter(l=>!Ci(l,r.get(l.i))&&!Ti(l,e,r)&&!Ni(l,e,r))].sort((l,s)=>{const o=vr(s,r.get(s.i),a)-vr(l,r.get(l.i),a);return o!==0?o:Ke(l,a)-Ke(s,a)});return wt(n,a)}function Ci(e,r){var n,l;if(!e.aiPin)return!1;const a=(n=r==null?void 0:r.aiPin)==null?void 0:n.certification,i=(l=r==null?void 0:r.aiPin)==null?void 0:l.reviewStatus;return a!=="certified"&&i!=="certified"}function Ni(e,r,a){if(!e.aiPin)return!1;const i=br(e,a.get(e.i));if(!i)return!1;const n=r.findIndex(l=>l.i===e.i);return r.some((l,s)=>l.i===e.i||s>=n||!l.aiPin?!1:br(l,a.get(l.i))===i)}function br(e,r){const a=r==null?void 0:r.aiPin,i=a!=null&&a.analysisPlan&&typeof a.analysisPlan=="object"?a.analysisPlan:null,n=vt(a==null?void 0:a.question)||vt(e.title),l=vt(i==null?void 0:i.sourceBlockId),s=vt(i==null?void 0:i.sourceTileId),o=a!=null&&a.result?Ii(a.result):"";return!n&&!l&&!s?"":[n,l,s,o].filter(Boolean).join("|")}function vt(e){return String(e??"").toLowerCase().replace(/[^a-z0-9]+/g," ").replace(/\s+/g," ").trim()}function Ii(e){if(!e||typeof e!="object")return"";const r=e,a=Array.isArray(r.columns)?r.columns.map(n=>String(n).toLowerCase()).join(","):"",i=Array.isArray(r.rows)?r.rows.slice(0,8).map(n=>Gt(n)).join(";"):"";return a||i?`${a}:${i}`:""}function Gt(e){if(e==null)return"";if(typeof e!="object")return String(e);if(Array.isArray(e))return`[${e.map(Gt).join(",")}]`;const r=e;return`{${Object.keys(r).sort().map(a=>`${a}:${Gt(r[a])}`).join(",")}}`}function vr(e,r,a){var n,l,s,o,p;let i=0;return(n=e.parameterBindings)!=null&&n.length&&(i+=5e3),(s=(l=r==null?void 0:r.filters)==null?void 0:l.applied)!=null&&s.length&&(i+=4e3),(r==null?void 0:r.certificationStatus)==="certified"&&(i+=1800),Te(e)&&(i+=900),(r==null?void 0:r.status)==="ok"&&((p=(o=r.result)==null?void 0:o.rows)!=null&&p.length)&&(i+=500),i-=Jt(e)*80,i-=Ke(e,a)/1e3,i}function Ti(e,r,a){var l;if((l=e.parameterBindings)!=null&&l.length||e.aiPin||!Te(e))return!1;const i=a.get(e.i),n=i!=null&&i.result?yr(i.result):null;return n?r.some(s=>{if(s.i===e.i||!$i(s,a.get(s.i)))return!1;const o=a.get(s.i),p=o!=null&&o.result?yr(o.result):null;return!!(p&&Pi(n,p))}):!1}function $i(e,r){var a,i,n;return!!((a=e.parameterBindings)!=null&&a.length||(n=(i=r==null?void 0:r.filters)==null?void 0:i.applied)!=null&&n.length)}function yr(e){var s;const r=e.rows??[];if(!r.length)return null;const a=(s=e.columns)!=null&&s.length?e.columns:Object.keys(r[0]??{});if(!a.length)return null;const i=ir(a,r),n=nr(a,r),l=r[0];return{columns:a.map(o=>o.toLowerCase()).sort().join("|"),label:i?qr(l[i]):"",metric:(n==null?void 0:n.toLowerCase())??"",metricValue:n?qr(l[n]):""}}function Pi(e,r){return e.columns===r.columns&&e.label===r.label&&e.metric===r.metric&&e.metricValue===r.metricValue}function qr(e){return e==null?"":typeof e=="number"?Number.isFinite(e)?String(e):"":String(e).trim().toLowerCase().replace(/\s+/g," ")}function Ri(e,r,a){var I,Q,re,D;const i=e.map((_,V)=>({item:_,tile:r.get(_.i),index:V})).filter(_=>{var V,W;return((V=_.tile)==null?void 0:V.status)==="ok"&&!!_.tile.result&&Array.isArray((W=_.tile.result)==null?void 0:W.rows)&&_.tile.result.rows.length>0}).sort((_,V)=>{const W=wr(_.item,_.tile,_.index);return wr(V.item,V.tile,V.index)-W})[0];if(!(i!=null&&i.tile.result))return null;const n=i.tile.result,l=n.rows,s=n.columns??Object.keys(l[0]??{});if(!s.length)return null;const o=Le(i.item),p=ir(s,l,(I=o==null?void 0:o.fieldHints)==null?void 0:I.label),d=nr(s,l,((Q=o==null?void 0:o.fieldHints)==null?void 0:Q.value)??((re=o==null?void 0:o.fieldHints)==null?void 0:re.y)),f=l[0],x=l[1],c=p?Pe(f[p]):"The leading result",A=x&&p?Pe(x[p]):null,S=d?Sr(f[d]):null,q=d&&x?Sr(x[d]):null,h=d?Bi(d):null,T=Li(a),z=T.length?"under the selected app filters":"in the current dashboard view",Y=i.item.title??i.tile.title??Te(i.item)??"Dashboard result",$=n.rowCount??l.length,k=i.tile.certificationStatus==="certified"?"certified":lr(String(((D=i.item.display)==null?void 0:D.trustState)??(o==null?void 0:o.trustState)??"review_required")),E=h?`${Ae(h)} snapshot`:"Dashboard snapshot";let M;if(h&&S!==null){const _=`${c} leads ${h} with ${Pe(S)}`;if(A&&q!==null&&Number.isFinite(S-q)){const V=Math.abs(S-q);M=`${_}, ahead of ${A} by ${Pe(V)} ${z}.`}else M=`${_} ${z}.`}else M=`${Y} returned ${$} ${$===1?"row":"rows"} ${z}.`;return{title:E,summary:M,sourceTitle:Y,trust:k,filters:T,chips:[`${$} ${$===1?"row":"rows"}`,s.length?`${s.length} fields`:""].filter(Boolean)}}function wr(e,r,a){var o,p,d,f;const i=Le(e),n=(i==null?void 0:i.component)??((o=e.display)==null?void 0:o.component),l=r.result;let s=1e3-a;return r.certificationStatus==="certified"&&(s+=500),Te(e)&&(s+=180),(d=(p=r.filters)==null?void 0:p.applied)!=null&&d.length&&(s+=260),(f=e.parameterBindings)!=null&&f.length&&(s+=220),(n==="RankingPanel"||n==="EvidenceTable"||n==="KpiMetric")&&(s+=120),(e.viz.type==="table"||e.viz.type==="bar"||e.viz.type==="kpi")&&(s+=70),l&&nr(l.columns,l.rows)&&(s+=80),l&&ir(l.columns,l.rows)&&(s+=50),s}function ir(e,r,a){const i=Zr(e,a);return i||(e.find(n=>/\b(player|customer|account|team|segment|category|name|label|title|entity)\b/i.test(n))??e.find(n=>!De(n,r)&&!/\b(date|time|year|month|id)\b/i.test(n))??e.find(n=>!De(n,r)))}function nr(e,r,a){const i=Zr(e,a);return i&&De(i,r)?i:e.filter(n=>De(n,r)).sort((n,l)=>jr(n)-jr(l))[0]}function Zr(e,r){const a=r==null?void 0:r.toLowerCase().trim();if(a)return e.find(i=>{const n=i.toLowerCase();return n===a||n.includes(a)||a.includes(n)})}function jr(e){const r=e.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 Bi(e){return Ae(e).toLowerCase()}function Li(e){return Object.entries(e).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:Ae(r),value:Array.isArray(a)?a.map(i=>kr(r,i)).join(", "):kr(r,a)}))}function kr(e,r){const a=typeof r=="number"?r:typeof r=="string"&&r.trim()!==""?Number(r):NaN;return/(season|year)/i.test(e)&&Number.isInteger(a)&&a>=1900&&a<=2200?String(a):Pe(r)}function Sr(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""){const r=Number(e);return Number.isFinite(r)?r:null}return null}function Ei(e){return e==="compact"||e==="standard"||e==="wide"||e==="tall"||e==="full"||e==="auto"?e:"auto"}function lr(e){return e==="certified"||e==="draft_ready"||e==="review_required"?e:"review_required"}function _i(e){return e==="certified"||e==="draft_ready"||e==="review_required"?e:"review_required"}function yt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mi(e,r){const a=new Set([String(e.viz.type??"table"),...(r==null?void 0:r.allowedVisualizations)??[]]),i=Array.from(a).map(n=>Ze(n)).filter((n,l,s)=>s.indexOf(n)===l);return i.map(n=>ar.find(l=>l.value===n)??{value:n,label:Ae(n)}).filter(n=>n.value!=="table"||i.length===1||e.block)}function Oi(e){return e==="TrustCallout"?"linear-gradient(180deg, rgba(255,255,255,0.92), rgba(255,251,235,0.72))":e==="RankingPanel"||e==="TrendPanel"||e==="PivotTable"?"linear-gradient(180deg, rgba(255,255,255,0.96), rgba(248,250,252,0.86))":e==="BusinessBrief"?"var(--dql-app-surface, rgba(255,255,255,0.90))":"var(--dql-app-surface, var(--surface, rgba(255,255,255,0.84)))"}function Fi(e){return e==="line"||e==="area"?t.jsx(rr,{size:13,strokeWidth:2.2}):e==="pie"||e==="donut"?t.jsx(Oa,{size:13,strokeWidth:2.2}):e==="table"?t.jsx(Ja,{size:13,strokeWidth:2.2}):t.jsx(Kr,{size:13,strokeWidth:2.2})}function Ae(e){return e.replace(/[_-]+/g," ").replace(/\b\w/g,r=>r.toUpperCase())}function Dr(e){switch(e.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 e.role?Ae(e.role):"Generated"}}function Wi(e,r){const a=new RegExp(`^###\\s*${Hi(r)}\\s*`,"i");return e.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(l=>l.trim()).find(Boolean)||"Generated app section pending analyst review."}function Vi(e,r,a){if(e.length===0)return;const i=a==null?void 0:a.toLowerCase();if(i){const n=e.find(l=>{const s=l.toLowerCase();return s===i||s.includes(i)||i.includes(s)});if(n)return n}return e.find(n=>/\b(name|label|title|dataset|table|block|player|customer|account)\b/i.test(n))??e.find(n=>!De(n,r))??e[0]}function Lt(e){const r=e.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 De(e,r){const a=r.slice(0,8).map(i=>i[e]).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 Pe(e){if(e==null||e==="")return"N/A";if(typeof e=="number")return Number.isFinite(e)?new Intl.NumberFormat("en-US",{maximumFractionDigits:2}).format(e):String(e);if(typeof e=="boolean")return e?"Yes":"No";const r=String(e),a=Number(r);return r.trim()!==""&&Number.isFinite(a)&&/^-?\d+(\.\d+)?$/.test(r.trim())?new Intl.NumberFormat("en-US",{maximumFractionDigits:2}).format(a):r.replace(/_/g," ")}function Hi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ue(e){return{border:"1px solid var(--dql-app-line, var(--border-color, rgba(0,0,0,0.12)))",borderRadius:8,background:e?"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}}function Qi(e){return{...Ue(e),width:34,height:34,padding:0,justifyContent:"center"}}const Ki={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"},Gi={display:"flex",alignItems:"center",gap:6,marginBottom:10},Yi={marginBottom:12,color:"var(--dql-app-muted, var(--color-text-secondary, rgba(0,0,0,0.64)))",fontSize:12,lineHeight:1.45},Ur={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},ea={display:"flex",alignItems:"flex-start",gap:10,minWidth:0},ta={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},ra={fontSize:10.5,fontWeight:820,letterSpacing:0,textTransform:"uppercase",color:"var(--dql-app-muted, rgba(15,23,42,0.58))"},aa={margin:"2px 0 0",fontSize:15,lineHeight:1.25,fontWeight:820,color:"var(--dql-app-text, inherit)"},ia={margin:0,fontSize:13.5,lineHeight:1.48,color:"var(--dql-app-muted, rgba(15,23,42,0.72))"},sr={display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},et={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"},na={...et,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))"},zr={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 Xi(e){return{position:"fixed",right:24,top:76,bottom:24,zIndex:70,width:e?`min(${Qt}px, calc(100vw - 96px))`:`min(${ja}px, calc(100vw - 64px))`,minWidth:0}}const Ar={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"},la={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},Ji={border:"none",borderRadius:6,background:"transparent",color:"inherit",padding:"9px 10px",cursor:"pointer",textAlign:"left",display:"grid",gap:2},Zi={border:"1px solid var(--border-color, rgba(0,0,0,0.10))",borderRadius:6,padding:8,background:"var(--color-bg, rgba(255,255,255,0.72))",display:"grid",gap:8,fontStyle:"normal"},Di={display:"grid",gridTemplateColumns:"repeat(4, minmax(0, 1fr))",gap:6},Yt={display:"grid",gap:3,fontSize:10,fontWeight:700,opacity:.78},Xt={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},Ui={display:"grid",gap:6,border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6,background:"var(--surface, rgba(248,250,252,0.62))",padding:8};function en(e){return{border:"1px solid var(--accent, rgba(79,70,229,0.55))",background:e?"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:e?"wait":"pointer",opacity:e?.72:1,whiteSpace:"nowrap"}}const sa={fontSize:11,lineHeight:1.35,color:"var(--dql-app-muted, rgba(15,23,42,0.68))"},tn={...sa,color:"var(--error-color, #b91c1c)"},rn={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"},an={marginTop:7,display:"flex",flexWrap:"wrap",gap:5,alignItems:"center",minWidth:0},$e={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 nn(e){return{...$e,border:e?"1px solid rgba(22,163,74,0.26)":"1px solid rgba(217,119,6,0.28)",background:e?"rgba(22,163,74,0.10)":"rgba(245,158,11,0.12)",color:e?"#15803d":"#b45309",gap:4}}const ln={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 sn(e){return{width:24,height:24,border:"none",borderRadius:4,background:e?"var(--dql-app-accent, var(--accent, #4f46e5))":"transparent",color:e?"var(--color-text-on-accent, #fff)":"inherit",cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:0}}function on(e){return{width:"100%",alignSelf:"stretch",overflow:"auto",display:"flex",flexDirection:"column",gap:10,fontStyle:"normal",opacity:1,lineHeight:1.45,borderRadius:6,padding:e?10:0,background:e?"rgba(245,158,11,0.08)":"transparent"}}function pn(e){return{width:30,height:30,borderRadius:7,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,background:e?"rgba(245,158,11,0.14)":"rgba(79,70,229,0.10)",color:e?"#b45309":"var(--dql-app-accent, var(--accent, #4f46e5))"}}const dn={...$e,background:"rgba(79,70,229,0.08)",color:"var(--dql-app-accent, var(--accent, #4f46e5))",border:"1px solid rgba(79,70,229,0.16)"},cn={width:"100%",alignSelf:"stretch",overflow:"auto",display:"flex",flexDirection:"column",gap:9,fontStyle:"normal",opacity:1,lineHeight:1.35},un={display:"grid",gap:6},xn={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"},fn={...$e,minHeight:16,borderRadius:5,padding:"1px 5px",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},gn={display:"grid",gap:1,minWidth:82,textAlign:"left",fontSize:10.5},hn={...$e,minHeight:18,background:"rgba(22,163,74,0.09)",border:"1px solid rgba(22,163,74,0.18)",color:"#15803d"},Et={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"},mn={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},bn={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},vn={border:"none",borderRadius:6,background:"transparent",color:"inherit",padding:"8px 9px",cursor:"pointer",textAlign:"left",display:"grid",gap:2};function yn(e){return{border:`1px solid ${e?"var(--accent, #4f46e5)":"var(--border-color, rgba(0,0,0,0.12))"}`,borderRadius:999,background:e?"var(--color-bg-active, rgba(79,70,229,0.12))":"var(--surface, rgba(0,0,0,0.02))",color:e?"var(--accent, #4f46e5)":"inherit",padding:"4px 8px",fontSize:11,fontWeight:e?750:600,cursor:"pointer"}}const Cr={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 or(e,r){const a=dt(e);return a==="heading"?Ie("wide",r,"heading"):a==="text"?Ie("standard",r,"text"):Ie(a==="single_value"||a==="kpi"||a==="gauge"?"compact":a==="table"||a==="pivot"?"tall":a==="line"||a==="area"?"wide":"standard",r,a)}function pr(e,r){const a=Le(e),i=jn(a==null?void 0:a.layoutIntent);return i&&i!=="auto"?Ie(i,r,String(e.viz.type??"table")):or(dt(String(e.viz.type??"table")),r)}function qn(e,r){return e.viz.type==="heading"?90:(r==null?void 0:r.component)==="BusinessBrief"||(r==null?void 0:r.component)==="NarrativePanel"||e.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,e.h*76))}function Ie(e,r,a="table"){const i=Math.max(1,r),n=Math.max(1,Math.ceil(i/2)),l=Math.max(1,Math.ceil(i/3));return e==="auto"?or(a,i):e==="compact"?{w:l,h:2}:e==="wide"?{w:i,h:a==="heading"?1:4}:e==="tall"?{w:n,h:6}:e==="full"?{w:i,h:7}:{w:n,h:a==="text"?2:4}}function oa(e,r,a){const i=String(e.viz.type??"table"),n=a==="auto"?pr(e,r):Ie(a,r,i);return{w:n.w,h:n.h,x:St(e.x,0,Math.max(0,r-n.w))}}function wn(e,r,a){const i=a==="auto"?pr(e,r):Ie(a,r,String(e.viz.type??"table"));return e.w===i.w&&e.h===i.h}function jn(e){return e==="auto"||e==="compact"||e==="standard"||e==="wide"||e==="tall"||e==="full"?e:null}function _t(e,r={w:6,h:3}){return{x:0,y:e.layout.items.reduce((i,n)=>Math.max(i,n.y+n.h),0),w:r.w,h:r.h}}function Mt(e,r){const a=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"tile",i=new Set(e.layout.items.map(n=>n.i));if(!i.has(a))return a;for(let n=2;n<1e3;n++){const l=`${a}-${n}`;if(!i.has(l))return l}return`${a}-${Date.now()}`}function wt(e,r){const a=Math.max(1,r),i=[],n=(s,o,p,d)=>{for(let f=0;f<d;f++){const x=i[o+f];if(x){for(let c=0;c<p;c++)if(x[s+c])return!1}}return!0},l=(s,o,p,d)=>{for(let f=0;f<d;f++){const x=o+f;i[x]||(i[x]=new Array(a).fill(!1));for(let c=0;c<p;c++)i[x][s+c]=!0}};return e.map(s=>{const o=St(Math.round(s.w||1),1,a),p=Math.max(1,Math.round(s.h||1));let d=0,f=0;e:for(let x=0;;x++)for(let c=0;c+o<=a;c++)if(n(c,x,o,p)){d=c,f=x;break e}return l(d,f,o,p),{...s,x:d,y:f,w:o,h:p}})}function kn(e,r,a){const i=e.filter(s=>s.i!==r.i).sort((s,o)=>Ke(s,a)-Ke(o,a)),n=Ke(r,a),l=i.findIndex(s=>Ke(s,a)>n);return l===-1?[...i,r]:[...i.slice(0,l),r,...i.slice(l)]}function Ke(e,r){return e.y*r+e.x}function Jt(e){const r=Le(e);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=dt(String(e.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 dt(e){const r=(e??"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"}function St(e,r,a){return Math.min(a,Math.max(r,e))}function Sn({app:e}){var o,p;const{state:r,dispatch:a}=At(),[i,n]=u.useState(!1),l=u.useRef(null);u.useEffect(()=>{if(!i)return;const d=f=>{var x;(x=l.current)!=null&&x.contains(f.target)||n(!1)};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[i]);const s=r.activePersona?`${r.activePersona.displayName??r.activePersona.userId} [${r.activePersona.roles.join(", ")}]`:"View as: Owner";return!e||e.members.length===0?t.jsx("span",{style:{fontSize:12,opacity:.6},children:s}):t.jsxs("div",{ref:l,style:{position:"relative"},children:[t.jsxs("button",{onClick:()=>n(d=>!d),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:[t.jsx("span",{style:{fontSize:11,opacity:.65},children:"View as:"}),t.jsx("span",{style:{fontWeight:600},children:((o=r.activePersona)==null?void 0:o.displayName)??((p=r.activePersona)==null?void 0:p.userId)??"Owner"}),r.activePersona&&t.jsxs("span",{style:{fontSize:11,opacity:.7},children:["[",r.activePersona.roles.join(", "),"]"]}),t.jsx("span",{style:{fontSize:10,opacity:.6},children:"▾"})]}),i&&t.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:[t.jsxs("button",{role:"menuitem",onClick:async()=>{await Z.clearPersona(),a({type:"SET_ACTIVE_PERSONA",persona:null}),n(!1)},style:Nr(r.activePersona===null),children:[t.jsx("div",{style:{fontWeight:500},children:"Owner (local)"}),t.jsx("div",{style:{fontSize:11,opacity:.65},children:"Default — no RLS narrowing"})]}),t.jsx("div",{style:{height:1,background:"var(--border-color, rgba(0,0,0,0.08))",margin:"4px 0"}}),e.members.map(d=>{var f;return t.jsxs("button",{role:"menuitem",onClick:async()=>{const x=await Z.setPersona(d.userId,e.id);a({type:"SET_ACTIVE_PERSONA",persona:x}),n(!1)},style:Nr(((f=r.activePersona)==null?void 0:f.userId)===d.userId),children:[t.jsx("div",{style:{fontWeight:500},children:d.displayName??d.userId}),t.jsxs("div",{style:{fontSize:11,opacity:.65},children:["[",d.roles.join(", "),"]",d.attributes&&Object.keys(d.attributes).length>0?` · ${Object.entries(d.attributes).map(([x,c])=>`${x}=${c}`).join(", ")}`:""]})]},d.userId)})]})]})}function Nr(e){return{display:"block",width:"100%",textAlign:"left",padding:"8px 12px",background:e?"var(--surface-hover, rgba(0,0,0,0.06))":"transparent",border:"none",cursor:"pointer",color:"inherit",fontSize:13}}function Ir(e){if(!e)return[];const r=new Map;for(const i of e.filters??[])zn(i)&&r.set(i.id,{...i});const a=i=>{var n,l;return((n=i.block)==null?void 0:n.blockId)??((l=i.block)==null?void 0:l.ref)};for(const i of e.layout.items??[]){const n=a(i);for(const l of i.filterBindings??[]){const s=l.mode??(l.binding?"predicate":void 0);if(!n||s!=="predicate"||!l.binding||l.unsupportedReason)continue;const o=r.get(l.filter);o&&(o.bindsTo||(o.bindsTo=l.binding),o.sourceBlockId||(o.sourceBlockId=n))}for(const l of i.parameterBindings??[]){const s=l.filter||l.field||l.param;s&&(r.has(s)||Cn(r,l)||r.set(s,An(l)))}}return Array.from(r.values())}function zn(e){var r;return!(e.type==="select"&&!((r=e.options)!=null&&r.length)&&e.default===void 0)}function An(e){const r=e.filter||e.field||e.param;return{id:r,type:Nn(r,e.parameterType),default:e.default??pa(r),bindsTo:e.param}}function Cn(e,r){return Array.from(e.values()).some(a=>r.filter&&a.id===r.filter||r.field&&a.bindsTo===r.field?!0:!!(r.param&&a.bindsTo===r.param))}function Nn(e,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(e)?"daterange":/(top[_-]?n|limit|count|number|year|season)/i.test(e)?"number":"string"}function pa(e){const r=e.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:""}const In=u.lazy(()=>Ut(()=>import("./UnifiedAgentRunPanel-BNqE169i.js").then(e=>e.c),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])).then(e=>({default:e.UnifiedAgentRunPanel}))),Tn=u.lazy(()=>Ut(()=>import("./AgentAnswerCard-BEIwKGm4.js").then(e=>e.A),__vite__mapDeps([4,1,2,3,5,6,7,8,9,10])).then(e=>({default:e.StructuredAnswerText}))),Ot=new Map,da="Build an analytics app from my certified DQL blocks and available warehouse tables.",ca=[{title:"Revenue story",domain:"Revenue",prompt:"Build a weekly revenue health app for the COO with risk flags."},{title:"Customer 360",domain:"Customer",prompt:"Customer 360: value, engagement, retention, orders, and service risk by segment."},{title:"Quality monitor",domain:"Platform",prompt:"Build a data quality monitor with freshness, failing tests, null rates, and model risk notes."},{title:"Experiment Readout",domain:"Product",prompt:"Create an experiment readout for product leadership with outcome, guardrails, and decision checklist."}],$n=[{id:"match",title:"Find blocks",description:"Search certified blocks, terms, views, and lineage."},{id:"story",title:"Shape story",description:"Order the app around the business decision."},{id:"draft",title:"Draft gaps",description:"Keep missing sections visible as draft work instead of hiding them."}],Pn={all:"All",mine:"Mine",shared:"Shared",fav:"Favourites"};function Rn(e){return e==="obsidian"||e==="dark"||e==="midnight"?"obsidian":e==="white"||e==="arctic"?"white":"paper"}function ts(){const{state:e,dispatch:r}=At(),a=u.useMemo(()=>Rn(e.themeMode),[e.themeMode]),[i,n]=u.useState(()=>e.activeAppId?"workspace":"library"),l=e.activeAppExperience,s=e.activeAppSection,o=g=>{r({type:"SET_APP_WORKSPACE_STATE",experience:g})},p=g=>{r({type:"SET_APP_WORKSPACE_STATE",section:g})},[d,f]=u.useState(""),[x,c]=u.useState("all"),[A,S]=u.useState(()=>new Set),[q,h]=u.useState(null),[T,z]=u.useState(null),[Y,$]=u.useState(!1),[k,E]=u.useState("ai"),[M,I]=u.useState(da),[Q,re]=u.useState("Business Analytics"),[D,_]=u.useState(""),[V,W]=u.useState("analytics"),[de,C]=u.useState([]),[le,we]=u.useState(!1),[B,ee]=u.useState(()=>new Set),[ne,he]=u.useState(null),[X,K]=u.useState(null),[me,pe]=u.useState(new Set),[ye,ce]=u.useState(!1),[be,J]=u.useState(null),[b,P]=u.useState(!1),[U,G]=u.useState(!1),[N,L]=u.useState(""),[se,ve]=u.useState(null),[oe,ue]=u.useState({}),[xe,ae]=u.useState({}),[Ce,H]=u.useState(!1),[y,te]=u.useState(!1),ie=u.useCallback(g=>{H(g),g||te(!1)},[]),[_e,Se]=u.useState(0),tt=u.useRef(0);u.useEffect(()=>{let g=!1;return r({type:"SET_APPS_LOADING",loading:!0}),Z.listApps().then(v=>{g||(r({type:"SET_APPS",apps:v}),r({type:"SET_APPS_LOADING",loading:!1}))}),()=>{g=!0}},[r]),u.useEffect(()=>{Z.getPersona().then(g=>r({type:"SET_ACTIVE_PERSONA",persona:g}))},[r]),u.useEffect(()=>{if(i!=="create")return;let g=!1;return we(!0),Z.recommendAppBlocks({domain:D||void 0,purpose:M,audience:"stakeholder",certifiedOnly:!0}).then(v=>{g||C(v)}).finally(()=>{g||we(!1)}),()=>{g=!0}},[i,k,D,M]),u.useEffect(()=>{if(!e.activeAppId||i!=="workspace"){h(null),z(null);return}let g=!1;return $(!0),Z.getApp(e.activeAppId).then(v=>{g||h(v)}),e.activeDashboardId?Z.getDashboard(e.activeAppId,e.activeDashboardId).then(v=>{g||z(v)}).finally(()=>{g||$(!1)}):(z(null),$(!1)),()=>{g=!0}},[e.activeAppId,e.activeDashboardId,i]);const ct=u.useMemo(()=>JSON.stringify(Ir((T==null?void 0:T.dashboard)??null)),[T==null?void 0:T.dashboard]),Me=u.useMemo(()=>Ir((T==null?void 0:T.dashboard)??null),[T==null?void 0:T.dashboard,ct]);u.useEffect(()=>{const g=Me;ue(v=>{const R={};for(const O of g)R[O.id]=v[O.id]??lt(O);return $r(v,R)?v:R}),ae(v=>{const R={};for(const O of g)R[O.id]=v[O.id]??lt(O);return $r(v,R)?v:R})},[T==null?void 0:T.dashboard.id,ct,Me]);const Ve=async(g,v,R,O)=>{r({type:"SET_APPS_LOADING",loading:!0});const ze=await Z.listApps();r({type:"SET_APPS",apps:ze}),r({type:"SET_APPS_LOADING",loading:!1}),g&&r({type:"OPEN_APP",appId:g,dashboardId:v,...O}),n(R)},Nt=u.useMemo(()=>{const g=d.trim().toLowerCase();return e.apps.filter(v=>x==="mine"&&(v.storage??"shared")!=="mine"||x==="shared"&&(v.storage??"shared")!=="shared"||x==="fav"&&!A.has(v.id)?!1:g?[v.name,v.description??"",v.domain,v.audience??"",v.lifecycle??"",...v.tags??[],...v.owners??[],...v.dashboards.map(O=>O.title)].join(" ").toLowerCase().includes(g):!0)},[A,x,d,e.apps]),He=u.useMemo(()=>e.apps.find(g=>g.id===e.activeAppId)??null,[e.apps,e.activeAppId]),It=u.useCallback(g=>{h(v=>v&&{...v,investigations:g})},[]),Tt=(g,v="view")=>{r({type:"OPEN_APP",appId:g.id,experience:v,section:"dashboards"}),n("workspace")},$t=(g=M,v)=>{E("ai"),I(g),_(""),ee(new Set),J(null),he(null),K(null),n("create"),Se(R=>R+1)},Pt=()=>{E("classic"),J(null),he(null),K(null),n("create")},ut=g=>{ee(v=>{const R=new Set(v);return R.has(g)?R.delete(g):R.add(g),R})},Xe=async g=>{var ht;const v=Array.isArray(g)?g.filter(ha=>typeof ha=="string"):[],R=M.trim();if(!R){J("Describe the app you want to build.");return}P(!0),J(null);const O=Array.from(k==="classic"?B:new Set([...Array.from(B),...v])),ze=await Z.proposeAppAiBuild({prompt:R,domain:D.trim()||void 0,owner:V.trim()||void 0,force:!1,selectedBlockIds:O,plannerMode:"ai_assisted"});if(P(!1),!ze.ok){J(ze.error),ze.session&&K(ze.session);return}const Je=ze.session;K(Je),he(null),pe(Je.proposal?Na(Je.proposal):new Set);const gt=(ht=Je.plan)==null?void 0:ht.name;gt&&re(gt)};u.useEffect(()=>{i!=="create"||k!=="ai"||_e===0||tt.current===_e||(tt.current=_e,Xe())},[i,k,_e]);const xt=g=>{ee(v=>{const R=new Set(v);return R.add(g),R}),Xe([g])},rt=g=>{pe(v=>{const R=new Set(v);return R.has(g)?R.delete(g):R.add(g),R})},Rt=async()=>{var O;if(!X||X.status!=="proposed")return;ce(!0),J(null);const g=await Z.commitAppAiBuild(X.id,{selectedTileIds:Array.from(me),expectedProposalHash:X.proposalHash});if(ce(!1),!g.ok){J(g.error);return}const v=g.session;K(v);const R={ok:!0,plan:v.plan,validation:v.validation,generated:{paths:v.generatedPaths},app:g.app,dashboardId:g.dashboardId};he(R),H(!0),await Ve(((O=g.app)==null?void 0:O.id)??R.plan.appId,g.dashboardId,"workspace",{experience:"view",section:"dashboards"})},ft=async()=>{if(!Q.trim()){J("Name the app before creating it.");return}if(!D.trim()){J("Choose a domain before creating the app.");return}P(!0),J(null);try{const g=await Z.createApp({name:Q.trim(),domain:D.trim(),dashboardTitle:"Overview",purpose:M.trim(),audience:"stakeholder",visibility:"shared",lifecycle:"draft",tags:["app-builder",D.trim().toLowerCase()],owners:[V.trim()||"owner@local"],selectedBlockIds:Array.from(B)});await Ve(g.app.id,g.dashboardId,"workspace",{experience:"build",section:"dashboards"})}catch(g){J(g instanceof Error?g.message:String(g))}finally{P(!1)}},m=()=>{var v;const g=((v=ne==null?void 0:ne.app)==null?void 0:v.id)??(ne==null?void 0:ne.plan.appId);g&&(r({type:"OPEN_APP",appId:g,dashboardId:(ne==null?void 0:ne.dashboardId)??void 0,experience:"build",section:"dashboards"}),n("workspace"))},j=async()=>{if(!e.activeAppId)return;const g=N.trim();if(!g){ve("Enter a dashboard page name.");return}ve(null);const v=await Z.createAppDashboard(e.activeAppId,{title:g});if(!v.ok){ve(v.error);return}G(!1),L(""),r({type:"OPEN_APP",appId:e.activeAppId,dashboardId:v.dashboard.id,experience:l,section:s}),await Ve(e.activeAppId,v.dashboard.id,"workspace")},w=u.useMemo(()=>({...xe}),[xe]),F=u.useCallback((g,v)=>{ue(R=>({...R,[g.id]:el(g,v)}))},[]),fe=u.useCallback(()=>{ae({...oe})},[oe]),je=u.useCallback(()=>{const g=Object.fromEntries(Me.map(v=>[v.id,lt(v)]));ue(g),ae(g)},[Me]);return t.jsxs("div",{className:`dql-apps-waterline dql-apps-theme-${a}`,children:[t.jsx("style",{children:_l}),i==="library"?t.jsx(Bn,{apps:Nt,allApps:e.apps,loading:e.appsLoading,search:d,filter:x,favorites:A,onSearch:f,onFilter:c,onToggleFavorite:g=>{S(v=>{const R=new Set(v);return R.has(g)?R.delete(g):R.add(g),R})},onStartAi:g=>$t(g),onStartClassic:Pt,onOpenApp:Tt}):i==="create"?t.jsx(En,{mode:k,appName:Q,prompt:M,domain:D,owner:V,promptExamples:ca,catalog:de,catalogLoading:le,selectedBlocks:B,generated:ne,buildSession:X,proposalSelection:me,committing:ye,themeMode:e.themeMode,onToggleProposalTile:rt,onCommitProposal:()=>void Rt(),onAddBlock:xt,saving:b,error:be,onBack:()=>n("library"),onModeChange:g=>{E(g),g==="ai"&&ee(new Set)},onAppNameChange:re,onPromptChange:I,onDomainChange:_,onOwnerChange:W,onToggleBlock:ut,onBuild:()=>k==="ai"?void Xe():void ft(),onOpenGenerated:m}):t.jsx(_n,{app:He,appDoc:q,dashboardDoc:T,loading:Y,experience:l,section:s,explainOpen:Ce,explainExpanded:y,dashboardFilters:Me,dashboardFilterValues:oe,themeMode:e.themeMode,variables:w,onBack:()=>n("library"),onExperienceChange:o,onSectionChange:p,onDashboardFilterChange:F,onApplyDashboardFilters:fe,onResetDashboardFilters:je,onExplainChange:ie,onExplainExpandedChange:te,onAddPage:()=>G(!0),onOpenDashboard:g=>r({type:"OPEN_DASHBOARD",dashboardId:g}),onDashboardChanged:g=>{z(v=>v&&{...v,dashboard:g}),Ve(e.activeAppId,g.id,"workspace")},onInvestigationsChanged:It,onOpenLineageNode:g=>{r({type:"OPEN_LINEAGE_DETAIL",nodeId:g,returnTo:e.activeAppId?{view:"apps",appId:e.activeAppId,dashboardId:e.activeDashboardId,label:He==null?void 0:He.name,experience:l,section:s}:null})}}),U&&t.jsx(Pl,{title:N,error:se,onChange:L,onCancel:()=>{G(!1),ve(null)},onCreate:()=>void j()})]})}function Bn({apps:e,allApps:r,loading:a,search:i,filter:n,favorites:l,onSearch:s,onFilter:o,onToggleFavorite:p,onStartAi:d,onStartClassic:f,onOpenApp:x}){const c=Bl(r,l),[A,S]=u.useState(da),q=()=>{const h=A.trim();h&&d(h)};return t.jsxs("main",{className:"dql-apps-wrap",children:[t.jsxs("section",{className:"dql-apps-createhead",children:[t.jsx("h1",{children:"Build an app"}),t.jsx("p",{children:"One request. DQL finds certified blocks, binds filters, and opens a stakeholder-ready app."})]}),t.jsxs("section",{className:"dql-apps-composer","aria-label":"Build an app with AI",children:[t.jsx("textarea",{value:A,onChange:h=>S(h.target.value),rows:2,"aria-label":"App build request",placeholder:"Build an EMEA revenue app for the CFO…",onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),q())}}),t.jsxs("div",{className:"dql-apps-composer-row",children:[t.jsxs("span",{className:"dql-apps-composer-chip",children:[t.jsx(We,{size:11})," Certified blocks first"]}),t.jsx("i",{}),t.jsxs("button",{type:"button",className:"dql-apps-composer-blank",onClick:f,children:[t.jsx(Ye,{size:12})," Create blank"]}),t.jsx("button",{type:"button",className:"dql-apps-composer-send",onClick:q,disabled:!A.trim(),title:"Build",children:t.jsx(qa,{size:15,strokeWidth:2})})]})]}),t.jsxs("div",{className:"dql-apps-try",children:[t.jsx("span",{children:"Try:"}),ca.slice(0,3).map(h=>t.jsx("button",{type:"button",onClick:()=>S(h.prompt),children:h.title},h.title))]}),t.jsxs("div",{className:"dql-apps-sectionhead",children:[t.jsx("span",{children:"App library"}),t.jsx("i",{}),t.jsxs("b",{children:[r.length," app",r.length===1?"":"s"]})]}),t.jsxs("div",{className:"dql-apps-libbar",children:[t.jsx("div",{className:"dql-apps-filter-tabs",children:["all","mine","shared","fav"].map(h=>t.jsxs("button",{className:n===h?"on":"",onClick:()=>o(h),children:[Pn[h]," ",t.jsx("span",{children:c[h]})]},h))}),t.jsxs("label",{className:"dql-apps-search",children:[t.jsx(Be,{size:15,strokeWidth:2,"aria-hidden":"true"}),t.jsx("input",{value:i,onChange:h=>s(h.target.value),placeholder:"Search apps, domains, owners..."})]})]}),a&&r.length===0?t.jsx(qe,{title:"Loading Apps...",detail:"Reading local app files from this DQL project."}):e.length===0?t.jsx(qe,{title:"No Apps match this view.",detail:"Change the filter or start a new App above."}):t.jsx("div",{className:"dql-apps-grid",children:e.map(h=>t.jsx(Ln,{app:h,favorite:l.has(h.id),onToggleFavorite:()=>p(h.id),onOpen:()=>x(h,"view"),onEdit:()=>x(h,"build")},h.id))})]})}function Ln({app:e,favorite:r,onToggleFavorite:a,onOpen:i,onEdit:n}){var f,x;const l=e.certification==="certified"||e.lifecycle==="certified",s=((f=e.drafts)==null?void 0:f.length)??0,o=e.investigations??0,p=e.aiPins??0,d=l?"Certified app":s>0||o>0||p>0?"Review needed":"Draft app";return t.jsxs("article",{className:"dql-app-card",children:[t.jsxs("div",{className:"dql-app-card-body",onClick:i,role:"button",tabIndex:0,children:[t.jsxs("div",{className:"dql-app-card-top",children:[t.jsx("span",{className:"dql-app-eyebrow",children:e.domain||"Domain"}),t.jsx("button",{type:"button",className:`dql-app-star ${r?"on":""}`,onClick:c=>{c.stopPropagation(),a()},"aria-label":r?"Remove favourite":"Add favourite",children:t.jsx(Ya,{size:14,strokeWidth:1.8})})]}),t.jsx(Fe,{tone:l?"certified":s>0?"draft":"agentic",children:l?"certified":s>0?"mixed":e.lifecycle??"draft"}),t.jsx("h3",{children:e.name}),t.jsx("p",{children:xa(e.description||`${e.name} consumption surface for ${e.domain}.`)}),t.jsxs("div",{className:"dql-app-card-mini",children:[t.jsx(Ht,{label:"Pages",value:String(e.dashboards.length)}),t.jsx(Ht,{label:"Books",value:String(((x=e.notebooks)==null?void 0:x.length)??0)}),t.jsx(Ht,{label:"Drafts",value:String(s)})]}),t.jsxs("div",{className:"dql-app-card-signals",children:[t.jsxs("span",{children:[t.jsx(We,{size:13})," ",d]}),t.jsxs("span",{children:[t.jsx(Be,{size:13})," ",o," analysis"]}),t.jsxs("span",{children:[t.jsx(Re,{size:13})," ",p," local insights"]})]})]}),t.jsxs("div",{className:"dql-app-card-depth",children:[t.jsx("span",{children:Ll(e)}),t.jsxs("button",{type:"button",className:"dql-app-card-act",onClick:i,title:"View app",children:[t.jsx(_r,{size:12})," View"]}),t.jsxs("button",{type:"button",className:"dql-app-card-act",onClick:n,title:"Edit app",children:[t.jsx(Hr,{size:12})," Edit"]})]})]})}function En({mode:e,appName:r,prompt:a,domain:i,owner:n,promptExamples:l,catalog:s,catalogLoading:o,selectedBlocks:p,generated:d,buildSession:f,proposalSelection:x,committing:c,themeMode:A,onToggleProposalTile:S,onCommitProposal:q,saving:h,error:T,onBack:z,onModeChange:Y,onAppNameChange:$,onPromptChange:k,onDomainChange:E,onOwnerChange:M,onToggleBlock:I,onBuild:Q,onOpenGenerated:re,onAddBlock:D}){var me,pe,ye,ce,be,J,b,P,U,G;const[_,V]=u.useState(!1),[W,de]=u.useState(""),C=s.filter(N=>p.has(N.id)),le=i.trim()||"Auto domain",we=n.trim()||"Local owner",B=(f==null?void 0:f.status)==="proposed"?f.proposal:void 0,ee=(d==null?void 0:d.plan)??(f==null?void 0:f.plan)??Rl(r,a,i,n,C),he=(((me=ee.pages[0])==null?void 0:me.tiles)??[]).filter(Yn),X=(f==null?void 0:f.warnings)??[],K=Xn(ee);if(e==="ai"){const N=(B==null?void 0:B.tiles)??[],L=N.filter(y=>y.certification==="certified").length,se=N.filter(y=>y.certification==="reviewed_semantic").length,ve=N.filter(y=>x.has(y.id)).length,oe=new Set(N.map(y=>y.blockId).filter(Boolean)),ue=W.trim().toLowerCase(),xe=s.filter(y=>!oe.has(y.id)&&(!ue||y.name.toLowerCase().includes(ue)||(y.description??"").toLowerCase().includes(ue))),ae=((pe=ee.globalFilters)!=null&&pe.length?ee.globalFilters:((ye=ee.pages[0])==null?void 0:ye.filters)??[]).slice(0,4),Ce=y=>{const te=y.toLowerCase();return te.includes("kpi")||te.includes("metric")||te.includes("single")?"Σ":te.includes("table")?"▤":"▦"},H=y=>{const te=y.toLowerCase();return te.includes("kpi")||te.includes("single")?"KPI":te.includes("table")?"Table":te.includes("line")?"Line chart":te.includes("bar")?"Bar chart":y?y.charAt(0).toUpperCase()+y.slice(1):"Auto"};return t.jsx("div",{className:"dql-app-flow-scroll",children:t.jsxs("div",{className:"dql-app-flow",children:[t.jsxs("div",{className:"dql-app-flow-head",children:[t.jsx("h2",{children:"Build an app"}),t.jsx("p",{children:"One request. DQL finds certified blocks, binds filters, and opens a stakeholder-ready app."})]}),t.jsx("div",{className:"dql-app-flow-bubble",children:a}),h?t.jsxs("div",{className:"dql-app-buildstream",children:[t.jsx("span",{className:"dql-app-buildorb",children:t.jsx(Re,{size:14})}),t.jsxs("div",{className:"dql-app-buildbody",children:[t.jsx("span",{className:"dql-app-shimmer",children:"Finding certified blocks…"}),t.jsxs("div",{className:"dql-app-buildsteps",children:[t.jsxs("span",{style:{animationDelay:"0.2s"},children:[t.jsx(nt,{size:11,className:"ok"}),"Matched domain ",t.jsx("code",{children:le.toLowerCase()})]}),t.jsxs("span",{style:{animationDelay:"0.8s"},children:[t.jsx(nt,{size:11,className:"ok"}),"Scanning certified blocks and semantic metrics"]}),t.jsxs("span",{style:{animationDelay:"1.4s"},children:[t.jsx("i",{className:"dot"}),"Detecting app filters from block parameters…"]})]})]})]}):null,!h&&B?t.jsxs("div",{className:"dql-app-buildstream proposal",children:[t.jsx("span",{className:"dql-app-buildorb still",children:t.jsx(Re,{size:14})}),t.jsxs("div",{className:"dql-app-buildbody wide",children:[t.jsxs("div",{className:"dql-app-proposal-lede",children:["Found ",t.jsxs("strong",{children:[L," certified block",L===1?"":"s"]}),se>0?` and ${se} reviewed semantic view${se===1?"":"s"}`:""," for your app. Uncheck any you don't need, or add more — everything ships governed."]}),t.jsxs("div",{className:"dql-app-proposal-card",children:[N.map(y=>{const te=x.has(y.id),ie=y.certification==="certified",_e=y.certification==="reviewed_semantic";return t.jsxs("button",{type:"button",className:`dql-app-proposal-row ${te?"":"off"}`,onClick:()=>S(y.id),children:[t.jsx("span",{className:`dql-app-prop-check ${te?"on":""}`,children:te?t.jsx(nt,{size:10,strokeWidth:3.2}):null}),t.jsx("span",{className:`dql-app-prop-glyph ${ie&&Ce(y.viz)==="▤"?"green":""}`,children:Ce(y.viz)}),t.jsxs("span",{className:"dql-app-prop-name",children:[t.jsx("b",{children:y.blockId??y.title}),t.jsx("small",{children:y.description??y.question??y.title})]}),t.jsx("span",{className:`dql-app-prop-badge ${ie?"certified":"draft"}`,children:ie?"Certified":_e?"Reviewed semantic":"Draft"}),t.jsx("span",{className:"dql-app-prop-viz",children:H(y.viz)})]},y.id)}),t.jsxs("button",{type:"button",className:"dql-app-addmore",onClick:()=>V(y=>!y),children:[t.jsx(kt,{size:13,strokeWidth:2.2})," Add more blocks"]}),_?t.jsxs("div",{className:"dql-app-addmore-panel",children:[t.jsxs("div",{className:"dql-app-addmore-search",children:[t.jsx(Be,{size:12}),t.jsx("input",{value:W,onChange:y=>de(y.target.value),placeholder:`Search ${s.length} certified block${s.length===1?"":"s"}…`})]}),o?t.jsx("div",{className:"dql-app-addmore-hint",children:"Loading certified blocks…"}):null,xe.slice(0,6).map(y=>t.jsxs("button",{type:"button",className:"dql-app-addmore-row",onClick:()=>{de(""),D(y.id)},children:[t.jsx(kt,{size:12,strokeWidth:2.2}),t.jsx("span",{children:y.name}),t.jsxs("small",{children:[y.domain??"certified"," · ",y.status]})]},y.id)),!o&&xe.length===0?t.jsx("div",{className:"dql-app-addmore-hint",children:"No more matching certified blocks."}):null]}):null]}),ae.length>0?t.jsxs("div",{className:"dql-app-detected",children:[t.jsx("span",{className:"dql-app-detected-label",children:"Detected filters"}),ae.map(y=>t.jsxs("span",{className:"dql-app-detected-pill",children:[y.label," · ",t.jsx("strong",{children:zt(y.default??"Any")})]},y.id))]}):null,B.gaps.length>0?t.jsx("div",{className:"dql-app-flow-gaps",children:B.gaps.slice(0,3).map(y=>t.jsxs("span",{children:[t.jsx(Qe,{size:12})," ",y.question]},y.id))}):null,t.jsxs("div",{className:"dql-app-flow-actions",children:[t.jsxs("button",{type:"button",className:"dql-app-flow-build",onClick:q,disabled:c||ve===0,children:[t.jsx(Ye,{size:13}),c?"Building app…":`Build app with ${ve} governed tile${ve===1?"":"s"}`]}),t.jsx("button",{type:"button",className:"dql-app-flow-reset",onClick:z,children:"Start over"})]})]})]}):null,!h&&!B?t.jsxs("div",{className:"dql-app-flow-actions",children:[t.jsxs("button",{type:"button",className:"dql-app-flow-build",onClick:Q,children:[t.jsx(Re,{size:13})," Find certified blocks"]}),t.jsx("button",{type:"button",className:"dql-app-flow-reset",onClick:z,children:"Start over"})]}):null,T?t.jsx("div",{className:"dql-app-error",children:T}):null,X.length>0&&!h?t.jsx("div",{className:"dql-app-flow-gaps",children:X.slice(0,2).map((y,te)=>t.jsxs("span",{children:[t.jsx(Qe,{size:12})," ",y]},`${y}-${te}`))}):null]})})}return t.jsxs("div",{className:"dql-app-create-shell",children:[t.jsxs("div",{className:"dql-app-buildbar",children:[t.jsxs("button",{type:"button",className:"dql-app-back dql-app-back-label",onClick:z,children:[t.jsx(Vr,{size:14}),t.jsx("span",{children:"Apps"})]}),t.jsx("span",{className:"dql-app-name-input",children:t.jsx("input",{value:r,onChange:N=>$(N.target.value),spellCheck:!1})}),t.jsx(Fe,{tone:d?"agentic":"draft",children:d?"generated":"draft"}),t.jsxs("div",{className:"dql-app-mode-seg",children:[t.jsxs("button",{type:"button",onClick:()=>Y("ai"),children:[t.jsx(Re,{size:15})," Build AI"]}),t.jsxs("button",{type:"button",className:"on",onClick:()=>Y("classic"),children:[t.jsx(er,{size:15})," Classic"]})]}),t.jsxs("div",{className:"dql-app-build-actions",children:[t.jsxs("span",{className:"dql-app-persona",children:[t.jsx("b",{children:"CFO"})," CFO"]}),d?t.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:re,children:"Open app"}):null,t.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-primary",onClick:Q,disabled:h,children:h?"Building...":"Create app"})]})]}),t.jsx("div",{className:"dql-app-create-workspace clean classic",children:t.jsxs("section",{className:"dql-app-ai-start",children:[t.jsxs("div",{className:"dql-app-ai-start-main",children:[t.jsxs("div",{className:"dql-app-ai-start-copy",children:[t.jsx("h1",{children:"Start with one AI input."}),t.jsx("p",{children:"DQL finds certified blocks, detects app filters, and opens the generated app in a clean stakeholder view."})]}),t.jsxs("div",{className:"dql-app-ai-start-card",children:[t.jsx("textarea",{value:a,onChange:N=>k(N.target.value),rows:5,"aria-label":"App request",placeholder:"Build an NBA player performance app for stakeholders..."}),t.jsx("button",{type:"button",className:"dql-app-ai-start-send",onClick:Q,disabled:h||!a.trim(),title:"Build app",children:h?t.jsx(Oe,{size:19}):t.jsx(Ia,{size:19})})]}),t.jsxs("div",{className:"dql-app-suggestions dql-app-ai-start-examples","aria-label":"Prompt examples",children:[t.jsx("span",{children:"Examples"}),l.slice(0,4).map(N=>t.jsx("button",{type:"button",onClick:()=>{k(N.prompt),E(N.domain)},children:N.title},N.title))]}),t.jsxs("details",{className:"dql-app-ai-context dql-app-ai-start-advanced",children:[t.jsxs("summary",{children:[t.jsx("span",{children:"Advanced controls"}),t.jsxs("b",{children:[le," / ",we]}),t.jsx(Er,{size:14})]}),t.jsxs("div",{className:"dql-app-ai-context-grid",children:[t.jsxs("label",{children:["Domain",t.jsx("input",{value:i,onChange:N=>E(N.target.value)})]}),t.jsxs("label",{children:["Owner",t.jsx("input",{value:n,onChange:N=>M(N.target.value)})]}),t.jsxs("label",{children:["Build mode",t.jsxs("select",{value:e,onChange:N=>Y(N.target.value),children:[t.jsx("option",{value:"ai",children:"AI first"}),t.jsx("option",{value:"classic",children:"Manual block selection"})]})]})]}),e==="classic"?t.jsx(Mn,{title:"Manual certified block selection",subtitle:`${p.size} selected`,catalog:s,loading:o,selectedBlocks:p,onToggleBlock:I}):null]}),B&&!d?t.jsx("div",{style:{border:`1px solid ${Ne[A].cellBorder}`,background:Ne[A].appBg,borderRadius:10,padding:14},children:t.jsx(Ta,{proposal:B,t:Ne[A],selected:x,onToggle:S,onCreate:q,busy:c,error:null})}):null,d?t.jsxs("div",{className:"dql-app-ai-result dql-app-ai-start-result",children:["Generated ",t.jsx("b",{children:d.plan.name})," with ",d.validation.certifiedTiles," certified app tile",d.validation.certifiedTiles===1?"":"s"," and ",K," scoped report",K===1?"":"s",".",f?t.jsxs("small",{children:["Session ",f.id]}):null]}):null,T?t.jsx("div",{className:"dql-app-error",children:T}):null]}),t.jsxs("aside",{className:"dql-app-ai-start-context",children:[t.jsxs("section",{className:"dql-app-ai-context-card",children:[t.jsx(Ft,{title:"Certified blocks found",meta:ee.coverage?`${ee.coverage.certifiedTiles} certified · ${ee.coverage.gaps} gap${ee.coverage.gaps===1?"":"s"}`:`${he.length||s.length} matches`}),t.jsxs("div",{className:"dql-app-ai-evidence-list",children:[(he.length?he:s.slice(0,4)).map((N,L)=>"name"in N?t.jsxs("div",{className:"dql-app-ai-evidence-row",children:[t.jsx("span",{children:t.jsx(We,{size:14})}),t.jsxs("div",{children:[t.jsx("b",{children:N.name}),t.jsx("small",{children:N.description})]}),t.jsx(Fe,{tone:N.status==="certified"?"certified":"draft",children:N.status})]},`catalog-${N.id}-${L}`):t.jsxs("div",{className:"dql-app-ai-evidence-row",children:[t.jsx("span",{children:t.jsx(We,{size:14})}),t.jsxs("div",{children:[t.jsx("b",{children:N.title}),t.jsx("small",{children:N.description??N.rationale??"Certified DQL block"})]}),t.jsx(Fe,{tone:"certified",children:"Certified"})]},`plan-${N.id}-${L}`)),!he.length&&!s.length?t.jsx(qe,{title:"No matches yet.",detail:"Enter a prompt to retrieve certified blocks.",compact:!0}):null]})]}),t.jsxs("section",{className:"dql-app-ai-context-card",children:[t.jsx(Ft,{title:"Detected app filters",meta:"bound to block params"}),t.jsxs("div",{className:"dql-app-ai-filter-preview",children:[((ce=ee.globalFilters)!=null&&ce.length?ee.globalFilters:((be=ee.pages[0])==null?void 0:be.filters)??[]).slice(0,4).map(N=>t.jsxs("span",{children:[t.jsx("small",{children:N.label}),t.jsx("b",{children:zt(N.default??"Any")})]},N.id)),(J=ee.globalFilters)!=null&&J.length||(P=(b=ee.pages[0])==null?void 0:b.filters)!=null&&P.length?null:t.jsxs(t.Fragment,{children:[t.jsxs("span",{children:[t.jsx("small",{children:"Domain"}),t.jsx("b",{children:le})]}),t.jsxs("span",{children:[t.jsx("small",{children:"Owner"}),t.jsx("b",{children:we})]}),t.jsxs("span",{children:[t.jsx("small",{children:"Top N"}),t.jsx("b",{children:"Any"})]})]})]})]}),t.jsxs("section",{className:"dql-app-ai-context-card",children:[t.jsx(Ft,{title:"Possible deeper analysis",meta:"Copilot asks for context first"}),t.jsxs("div",{className:"dql-app-ai-gap-list",children:[((U=ee.missingEvidence)!=null&&U.length?ee.missingEvidence:X).slice(0,4).map((N,L)=>t.jsxs("span",{children:[t.jsx(Qe,{size:13})," ",N]},`${N}-${L}`)),!((G=ee.missingEvidence)!=null&&G.length)&&!X.length?t.jsxs("span",{children:[t.jsx(Qe,{size:13})," Driver explanations, new grains, and reusable block proposals require typed context before DQL creates SQL."]}):null]})]})]})]})})]})}function _n({app:e,appDoc:r,dashboardDoc:a,loading:i,experience:n,section:l,explainOpen:s,explainExpanded:o,dashboardFilters:p,dashboardFilterValues:d,themeMode:f,variables:x,onBack:c,onExperienceChange:A,onSectionChange:S,onDashboardFilterChange:q,onApplyDashboardFilters:h,onResetDashboardFilters:T,onExplainChange:z,onExplainExpandedChange:Y,onAddPage:$,onOpenDashboard:k,onDashboardChanged:E,onInvestigationsChanged:M,onOpenLineageNode:I}){var Ce;const{dispatch:Q}=At(),re=(a==null?void 0:a.dashboard.layout.items.filter(H=>!!H.block).length)??0,D=((Ce=r==null?void 0:r.drafts)==null?void 0:Ce.length)??0,_=u.useMemo(()=>ua((a==null?void 0:a.dashboard)??null).map(H=>H.blockId),[a]),V=_.join("|"),[W,de]=u.useState(_[0]??null),[C,le]=u.useState(null),[we,B]=u.useState(null),[ee,ne]=u.useState(null),[he,X]=u.useState(null),[K,me]=u.useState("idle"),[pe,ye]=u.useState(""),[ce,be]=u.useState("idle"),[J,b]=u.useState(""),P=u.useCallback(H=>{le(H)},[]);u.useCallback(H=>{ne({...H,nonce:Date.now()}),S("research"),z(!0)},[z,S]);const U=u.useCallback(H=>{X(H)},[]),G=u.useCallback(()=>{ne(null)},[]),N=u.useCallback((H,y)=>{var te,ie;if(de(H),n==="view"){Q({type:"OPEN_GLOBAL_AI",audience:"stakeholder",context:{title:"App copilot",scopeHint:qt(e==null?void 0:e.name)?`Follow up on ${qt(e==null?void 0:e.name)}`:"Follow up on this tile",selectedObject:{kind:"block",id:H,title:a==null?void 0:a.dashboard.metadata.title},workspaceContext:{appId:e==null?void 0:e.id,dashboardId:a==null?void 0:a.dashboard.id,blockId:H},suggestedQuestions:(ie=(te=a==null?void 0:a.app)==null?void 0:te.copilot)==null?void 0:ie.suggestedQuestions},autoRun:{text:y,mode:"auto"}});return}z(!0),B({text:y,nonce:Date.now()})},[Q,n,e==null?void 0:e.id,e==null?void 0:e.name,a==null?void 0:a.dashboard.id,a==null?void 0:a.dashboard.metadata.title,z]);u.useEffect(()=>{n==="view"&&(l==="notebooks"||l==="ai"||l==="drafts"||l==="settings")&&S("dashboards")},[n,l,S]),u.useEffect(()=>{if(_.length===0){W!==null&&de(null);return}(!W||!_.includes(W))&&de(_[0])},[_,V,W]),u.useEffect(()=>{le(null),X(null)},[e==null?void 0:e.id,a==null?void 0:a.dashboard.id]);const L=!!(e&&a&&(l==="dashboards"||l==="research")),se=L&&s,ve=H=>{me(H),H!=="ready"&&window.setTimeout(()=>me("idle"),1800)},oe=async()=>{var te;const H=ll(e,r,a);ye(H);let y=!1;try{typeof navigator<"u"&&((te=navigator.clipboard)!=null&&te.writeText)&&(await navigator.clipboard.writeText(H),y=!0)}catch{y=!1}if(!y){const ie=document.createElement("textarea");ie.value=H,ie.style.position="fixed",ie.style.left="-9999px",document.body.appendChild(ie),ie.focus(),ie.select(),y=document.execCommand("copy"),document.body.removeChild(ie)}ve(y?"copied":"ready")},ue=()=>{const H=sl(e,r,a),y=new Blob([H],{type:"text/markdown;charset=utf-8"}),te=URL.createObjectURL(y),ie=document.createElement("a");ie.href=te,ie.download=`${(e==null?void 0:e.id)??(r==null?void 0:r.app.id)??"dql-app"}-brief.md`,document.body.appendChild(ie),ie.click(),document.body.removeChild(ie),URL.revokeObjectURL(te),ve("downloaded")},xe=async()=>{if(!(e!=null&&e.id))return;be("running"),b("");const H=await Z.promoteApp(e.id,{lifecycle:"review"});if(!H.ok){be("error"),b(H.error);return}be("done"),b(`${H.paths.length} shared files updated${H.removedLocalTiles?`, ${H.removedLocalTiles} local AI tile removed`:""}.`),window.setTimeout(()=>be("idle"),2400)},ae=l==="dashboards"&&!!a;return t.jsxs("div",{className:"dql-app-workspace",children:[t.jsxs("div",{className:"dql-app-view-topbar",children:[t.jsxs("button",{type:"button",className:"dql-app-back dql-app-back-label",onClick:c,title:"Back to apps",children:[t.jsx(Vr,{size:14}),t.jsx("span",{children:"Apps"})]}),t.jsx("span",{className:"dql-app-crumb",children:t.jsx("b",{children:(e==null?void 0:e.id)??"app"})}),t.jsx(Fe,{tone:"certified",children:D>0?`${re} certified`:"All certified"}),D>0?t.jsxs(Fe,{tone:"draft",children:[D," draft"]}):null,t.jsx("span",{className:"dql-app-topbar-divider","aria-hidden":"true"}),t.jsxs("div",{className:"dql-app-modeseg",role:"group","aria-label":"App mode",children:[t.jsxs("button",{type:"button",className:n==="view"?"on":"",onClick:()=>A("view"),title:"Clean stakeholder view",children:[t.jsx(_r,{size:12})," View"]}),t.jsxs("button",{type:"button",className:n==="build"?"on":"",onClick:()=>A("build"),title:"Rearrange tiles and edit this app",children:[t.jsx(Hr,{size:12})," Edit"]})]}),t.jsxs("div",{className:"dql-app-view-actions",children:[t.jsx(Sn,{app:(r==null?void 0:r.app)??null}),n==="build"?t.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>void xe(),disabled:ce==="running",children:[t.jsx(We,{size:14})," ",ce==="running"?"Promoting":"Promote"]}):null,t.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line dql-apps-btn-icon",title:K==="copied"?"Copied handoff":"Share local app handoff",onClick:()=>void oe(),children:K==="copied"?t.jsx(nt,{size:15}):t.jsx(Ha,{size:15})}),t.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line dql-apps-btn-icon",title:K==="downloaded"?"Brief saved":"Download app brief",onClick:ue,children:K==="downloaded"?t.jsx(nt,{size:15}):t.jsx(wa,{size:15})}),K==="ready"?t.jsxs("div",{className:"dql-app-share-popover",children:[t.jsx("b",{children:"Local handoff"}),t.jsx("textarea",{readOnly:!0,value:pe,onFocus:H=>H.currentTarget.select()})]}):null,ce==="done"||ce==="error"?t.jsx("div",{className:`dql-app-promote-popover ${ce==="error"?"error":""}`,children:J}):null]})]}),t.jsxs("main",{className:"dql-app-view-wrap",children:[t.jsxs("div",{className:"dql-app-title-row",children:[t.jsxs("div",{className:"dql-app-title-copy",children:[t.jsxs("div",{className:"dql-app-title-meta",children:[t.jsxs("span",{children:[t.jsx(Ye,{size:14})," ",(e==null?void 0:e.domain)??(a==null?void 0:a.dashboard.metadata.domain)??"DQL App"]}),ae?t.jsx("span",{className:"dql-app-title-context",children:qt(e==null?void 0:e.name)||"App"}):null,n==="build"?t.jsx(Fe,{tone:"draft",children:"Customizing"}):null]}),t.jsx("h1",{children:qt(ae?a==null?void 0:a.dashboard.metadata.title:e==null?void 0:e.name)||"App"}),t.jsx("p",{children:xa((ae?a==null?void 0:a.dashboard.metadata.description:e==null?void 0:e.description)??"Local DQL App")})]}),t.jsxs("div",{className:"dql-app-nav-row",children:[t.jsx(On,{appDoc:r,section:l,experience:n,onChange:S}),l==="dashboards"&&(r!=null&&r.dashboards.length)?t.jsx(Fn,{dashboards:r.dashboards,activeDashboardId:a==null?void 0:a.dashboard.id,isBuild:n==="build",onOpen:k,onAdd:$}):null,L?t.jsx("button",{type:"button",className:`dql-apps-btn dql-apps-btn-line dql-apps-btn-icon ${s?"on":""}`,title:s?"Hide AI copilot":"Show AI copilot",onClick:()=>z(!s),children:t.jsx(Ct,{size:15})}):null,ae?t.jsx(t.Fragment,{children:t.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line dql-apps-btn-icon",title:"Open dashboard lineage",onClick:()=>{e&&a&&I(`dashboard:${e.id}/${a.dashboard.id}`)},children:t.jsx(Lr,{size:15})})}):null]})]}),t.jsxs("div",{className:`dql-app-view-layout ${se?"":"no-explain"}`,children:[t.jsxs("div",{className:"dql-app-main-column",children:[l==="dashboards"&&a&&p.length>0?t.jsxs("section",{className:"dql-app-filter-row","aria-label":"Dashboard filters",children:[t.jsxs("div",{className:"dql-app-filter-row-copy",children:[t.jsx("b",{children:"Filters"}),t.jsx("span",{children:"Set the business scope, then apply once to refresh the full story."})]}),t.jsx(Jn,{filters:p,values:d,onChange:q}),t.jsxs("div",{className:"dql-app-filter-row-actions",children:[t.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:T,children:"Reset"}),t.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-primary",onClick:h,children:"Apply"})]})]}):null,i?t.jsx(qe,{title:"Loading app...",detail:"Reading dashboard files and running local blocks."}):l==="dashboards"&&a&&e?t.jsx(ei,{appId:e.id,dashboard:a.dashboard,editable:n==="build",embeddedHeader:!0,variables:x,selectedBlockId:W,onBlockFocus:de,onAskBlock:N,onOpenLineageNode:I,copilotOpen:s,onCopilotChange:z,onDashboardChanged:E,onRunChange:P}):l==="notebooks"?t.jsx(Hn,{appDoc:r}):l==="research"?t.jsx(Vn,{appDoc:r,dashboardDoc:a,seed:ee,themeMode:f,onSeedHandled:G,onDashboardChanged:E,onInvestigationsChanged:M,onActiveInvestigationChange:U}):l==="ai"?t.jsx(Qn,{appDoc:r}):l==="drafts"?t.jsx(Kn,{appDoc:r}):l==="settings"?t.jsx(Gn,{appDoc:r}):t.jsx(qe,{title:"No dashboard page selected.",detail:"Choose a dashboard page or add one in Build mode."})]}),se?t.jsx(Wn,{app:e,appDoc:r,dashboardDoc:a,dashboardRun:C,variables:x,selectedBlockId:W,askSeed:we,themeMode:f,expanded:o,onToggleExpanded:()=>Y(!o),onClose:()=>z(!1)}):null]})]})]})}function Mn({title:e,subtitle:r,catalog:a,loading:i,selectedBlocks:n,onToggleBlock:l}){const[s,o]=u.useState(""),p=u.useMemo(()=>{const d=s.trim().toLowerCase();return d?a.filter(f=>[f.name,f.domain,f.status,f.description,f.owner??"",...f.tags??[]].join(" ").toLowerCase().includes(d)):a},[a,s]);return t.jsxs("div",{className:"dql-app-palette",children:[t.jsxs("div",{className:"dql-app-palette-title",children:[t.jsxs("span",{children:[t.jsx(er,{size:14})," ",e]}),t.jsx("b",{children:r})]}),t.jsxs("label",{className:"dql-app-palette-search",children:[t.jsx(Be,{size:14}),t.jsx("input",{value:s,onChange:d=>o(d.target.value),placeholder:"Search blocks, domains, tags"})]}),i?t.jsx(qe,{title:"Loading blocks...",detail:"Finding certified blocks for this domain.",compact:!0}):null,!i&&p.length===0?t.jsx(qe,{title:"No blocks found.",detail:"Try another domain or search term.",compact:!0}):null,p.slice(0,24).map((d,f)=>{const x=n.has(d.id);return t.jsxs("button",{type:"button",className:x?"selected":"",onClick:()=>l(d.id),children:[t.jsx("span",{className:"dql-app-palette-icon",children:t.jsx(rr,{size:14})}),t.jsxs("span",{children:[t.jsx("b",{children:d.name}),t.jsxs("small",{children:[d.domain," / ",d.chartType??"table"]})]}),t.jsx("i",{children:x?"using":d.status})]},`${d.id}-${f}`)}),p.length>24?t.jsxs("div",{className:"dql-app-palette-more",children:[p.length-24," more matches"]}):null]})}function On({appDoc:e,section:r,experience:a,onChange:i}){var s,o,p,d,f;const n=((s=e==null?void 0:e.investigations)==null?void 0:s.length)??0,l=a==="view"?[{id:"dashboards",label:"App",count:(e==null?void 0:e.dashboards.length)??0,icon:t.jsx(Ye,{size:14})}]:[{id:"dashboards",label:"App",count:(e==null?void 0:e.dashboards.length)??0,icon:t.jsx(Ye,{size:14})},{id:"research",label:"Analysis",count:n,icon:t.jsx(Be,{size:14})},{id:"notebooks",label:"Notebooks",count:((o=e==null?void 0:e.notebooks)==null?void 0:o.length)??((p=e==null?void 0:e.app.notebooks)==null?void 0:p.length)??0,icon:t.jsx(Qr,{size:14})},{id:"ai",label:"Pins",count:((d=e==null?void 0:e.aiPins)==null?void 0:d.length)??0,icon:t.jsx(Ct,{size:14})},{id:"drafts",label:"Drafts",count:((f=e==null?void 0:e.drafts)==null?void 0:f.length)??0,icon:t.jsx(tr,{size:14})},{id:"settings",label:"Settings",icon:t.jsx(Oe,{size:14})}];return t.jsx("nav",{className:"dql-app-section-tabs","aria-label":"App sections",children:l.map(x=>t.jsxs("button",{className:r===x.id?"on":"","data-app-section":x.id,onClick:()=>i(x.id),title:x.label,"aria-label":`${x.label}${x.count!==void 0?` ${x.count}`:""}`,children:[t.jsx("i",{className:"dql-app-tab-icon",children:x.icon}),t.jsx("span",{className:"dql-app-tab-label",children:x.label}),x.count!==void 0?t.jsx("b",{children:x.count}):null]},x.id))})}function Fn({dashboards:e,activeDashboardId:r,isBuild:a,onOpen:i,onAdd:n}){const l=e.find(s=>s.id===r)??e[0];return t.jsxs("div",{className:"dql-app-page-picker","aria-label":"Dashboard page",children:[t.jsxs("span",{children:[t.jsx(rr,{size:14})," Page"]}),t.jsx("select",{value:(l==null?void 0:l.id)??"",onChange:s=>i(s.target.value),title:(l==null?void 0:l.title)??"Dashboard page",children:e.map(s=>t.jsxs("option",{value:s.id,children:[s.title," (",s.itemCount,")"]},s.id))}),a?t.jsx("button",{type:"button",onClick:n,title:"Add dashboard page",children:t.jsx(kt,{size:14})}):null]})}function Wn({app:e,appDoc:r,dashboardDoc:a,dashboardRun:i,variables:n,selectedBlockId:l,askSeed:s,themeMode:o,expanded:p,onToggleExpanded:d,onClose:f}){const x=Ne[o],c=(a==null?void 0:a.dashboard)??null,S=u.useMemo(()=>ua(c,i),[c,i]).find(re=>re.blockId===l)??null,q=S?i==null?void 0:i.tiles.find(re=>re.tileId===S.tileId||re.blockId===S.blockId):null,h=(e==null?void 0:e.id)??(r==null?void 0:r.app.id)??"app",T=(c==null?void 0:c.id)??"dashboard",z=Or(`app:${h}:${T}`),[Y,$]=u.useState(!1),k=ke((e==null?void 0:e.name)??(r==null?void 0:r.app.name)??(c==null?void 0:c.metadata.title)??"App workspace"),E=ke((c==null?void 0:c.metadata.title)??"Dashboard"),M=S?`Focused on ${ke(S.title)} in ${E}`:`Scoped to ${E}`,I=S?{kind:"block",id:S.blockId,title:S.title}:c?{kind:"dashboard",id:c.id,title:c.metadata.title}:{kind:"app",id:h,title:k},Q=u.useMemo(()=>{var re,D,_,V,W;return{surface:"apps",appId:h,appName:(e==null?void 0:e.name)??(r==null?void 0:r.app.name),appDomain:(e==null?void 0:e.domain)??(r==null?void 0:r.app.domain),appDescription:(e==null?void 0:e.description)??(r==null?void 0:r.app.description),dashboardId:c==null?void 0:c.id,dashboardTitle:c==null?void 0:c.metadata.title,dashboardDescription:c==null?void 0:c.metadata.description,dashboardFilters:n,selectedBlock:S?{blockId:S.blockId,tileId:S.tileId,title:S.title,visualization:S.viz,status:q==null?void 0:q.status,certificationStatus:q==null?void 0:q.certificationStatus,rowCount:(re=q==null?void 0:q.result)==null?void 0:re.rowCount,columns:(_=(D=q==null?void 0:q.result)==null?void 0:D.columns)==null?void 0:_.slice(0,12),sampleRows:nl((V=q==null?void 0:q.result)==null?void 0:V.rows,(W=q==null?void 0:q.result)==null?void 0:W.columns)}:void 0}},[e,r,h,c,S,q,n]);return t.jsx(Mr,{t:x,title:"App AI",subtitle:k,expanded:p,onToggleExpanded:d,onClose:f,onNewChat:z.resetThreadId,running:Y,ariaLabel:"App AI",className:"dql-app-explain-panel dql-app-assistant-panel",children:t.jsx(u.Suspense,{fallback:t.jsx("div",{style:{padding:16,fontSize:12,color:x.textSecondary},children:"Loading App AI…"}),children:t.jsx(In,{themeMode:o,title:"App AI",scopeHint:M,audience:"stakeholder",selectedObject:I,workspaceContext:Q,initialMode:"auto",autoRun:s!=null&&s.text?{text:s.text,mode:"ask",nonce:s.nonce}:void 0,threadId:z.threadId,onThreadIdChange:z.onThreadIdChange,onRunningChange:$,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."}]},`${h}:${T}`)})})}function Vn({appDoc:e,dashboardDoc:r,seed:a,themeMode:i,onSeedHandled:n,onDashboardChanged:l,onInvestigationsChanged:s,onActiveInvestigationChange:o}){var J;const p=e==null?void 0:e.app.id,d=r==null?void 0:r.dashboard.id,f=Ne[i],[x,c]=u.useState(()=>(e==null?void 0:e.investigations)??[]),[A,S]=u.useState(null),[q,h]=u.useState(!1),[T,z]=u.useState(null),[Y,$]=u.useState(null),[k,E]=u.useState("preview"),[M,I]=u.useState(""),[Q,re]=u.useState(!1),[D,_]=u.useState(!1),[V,W]=u.useState(null);u.useEffect(()=>{if(!p){c([]),S(null);return}let b=!1;return h(!0),Z.listAppInvestigations(p).then(P=>{if(b)return;$(null),c(P);const U=Dt(P);S(G=>{var N,L;return G??((N=U.find(se=>se.status==="ready"))==null?void 0:N.id)??((L=U[0])==null?void 0:L.id)??null})}).finally(()=>{b||h(!1)}),()=>{b=!0}},[p]),u.useEffect(()=>{s(x)},[x,s]),u.useEffect(()=>{if(!a||!p)return;let b=!1;const P={dashboardId:a.dashboardId??d,sourceTileId:a.sourceTileId,sourceBlockId:a.sourceBlockId,title:a.title,question:a.question,intent:a.intent,context:a.context,generatedSql:a.generatedSql,run:!0},U=pt(a.title??a.question)||"requested follow-up",G=`${p}:${JSON.stringify(P)}`,N=async()=>{z("create"),W(U),$(null);let se=Ot.get(G);se||(se=Z.createAppInvestigation(p,P),Ot.set(G,se),se.finally(()=>{window.setTimeout(()=>Ot.delete(G),5e3)}));const ve=await se;if(b)return;if(z(null),!ve.ok){$(ve.error),W(null),n();return}const oe=ve.investigation,ue=xe=>{c(ae=>it(ae,xe)),S(xe.id),E("preview"),_(!1),xe.status!=="draft"&&xe.status!=="running"&&W(null)};if(ue(oe),oe.status!=="draft"&&oe.status!=="running"){n();return}z(oe.id);for(let xe=0;xe<20;xe+=1){if(await new Promise(Ce=>{window.setTimeout(Ce,1e3)}),b)return;const ae=await Z.getAppInvestigation(p,oe.id);if(b)return;if(ae&&ae.status!=="draft"&&ae.status!=="running"){z(null),ue(ae),n();return}}n(),z(null),W(null),$("Analysis is still running. Reopen it or refresh to load the latest proof.")},L=window.setTimeout(()=>void N(),0);return()=>{b=!0,window.clearTimeout(L)}},[a==null?void 0:a.nonce,p,d,n]);const de=u.useMemo(()=>Dt(x),[x]),C=de.find(b=>b.id===A)??de.find(b=>b.status==="ready")??de[0]??null;u.useEffect(()=>(o(C),()=>o(null)),[C,o]);const le=de.filter(b=>b.id!==(C==null?void 0:C.id)).filter(b=>Q||b.status!=="error").slice(0,Q?40:5),we=Math.max(0,de.length-(C?1:0)-le.length),B=C?dl(C):null,ee=B?yl(B):"",ne=T==="create"||!!V,he=ne&&!!V,X=ne&&!C;u.useEffect(()=>{I((C==null?void 0:C.generatedSql)??"")},[C==null?void 0:C.id,C==null?void 0:C.generatedSql]);const K=async(b,P)=>{if(!p)return null;z(b.id),$(null);const U=P==null?void 0:P.trim(),G=await Z.runAppInvestigation(p,b.id,U?{generatedSql:U}:void 0);return z(null),G.ok?(c(N=>it(N,G.investigation)),E("preview"),G.investigation):($(G.error),null)},me=async b=>{if(!p)return null;z(`rebuild:${b.id}`),$(null);const P=await Z.runAppInvestigation(p,b.id,{repairMode:"rebuild_from_certified"});return z(null),P.ok?(c(U=>it(U,P.investigation)),E(P.investigation.error?"sql":"preview"),P.investigation):($(P.error),null)},pe=async b=>{if(!p)return null;z(`pin:${b.id}`),$(null);const P=await Z.pinAppInvestigation(p,b.id,{dashboardId:b.dashboardId??d,title:b.title});return z(null),P.ok?(c(U=>it(U,P.investigation)),S(P.investigation.id),P.dashboard&&l(P.dashboard),P.investigation):($(P.error),null)},ye=async b=>{if(!p)return;if(!b.generatedSql){$("Add reviewed SQL before creating a draft block.");return}const P=b.pinnedAiPinId?b:await pe(b),U=P==null?void 0:P.pinnedAiPinId;if(!U)return;z(`promote:${b.id}`),$(null);const G=await Z.promoteAiPin(p,U);if(z(null),!G.ok){$(G.error??"Draft block could not be created.");return}const N=await Z.getAppInvestigation(p,b.id);N&&c(L=>it(L,N))},ce=async b=>{const P=M.trim();let U=b;if(P&&P!==(b.generatedSql??"").trim()){const G=await K(b,P);if(!G)return;U=G}await ye(U)},be=async b=>{const P=M.trim();let U=b;if(P&&P!==(b.generatedSql??"").trim()){const G=await K(b,P);if(!G)return null;U=G}return pe(U)};return e?t.jsxs("div",{className:`dql-app-research-shell ${D||!C&&!X?"history-open":"history-collapsed"}`,children:[t.jsxs("section",{className:"dql-app-research-list",children:[t.jsxs("div",{className:"dql-app-research-head",children:[t.jsxs("span",{children:[t.jsx(Be,{size:14})," Analysis"]}),t.jsxs("div",{children:[t.jsx("b",{children:x.length}),C?t.jsx("button",{type:"button",onClick:()=>_(!1),title:"Close analysis history",children:"Close"}):null]})]}),q?t.jsx(qe,{title:"Loading analysis...",detail:"Reading local app analysis.",compact:!0}):null,Y?t.jsx("div",{className:"dql-app-error",children:Y}):null,!q&&x.length===0?t.jsx(qe,{title:"No analysis yet.",detail:"Start from Copilot so the analysis keeps the original question, filters, and selected result context.",compact:!0}):null,t.jsxs("div",{className:"dql-app-research-items",children:[C?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"dql-app-research-group-label",children:"Current analysis"}),t.jsx(Tr,{item:C,selected:!0,onClick:()=>{$(null),S(C.id),E("preview"),_(!1)}})]}):null,le.length?t.jsx("div",{className:"dql-app-research-group-label",children:"Recent history"}):null,le.map(b=>t.jsx(Tr,{item:b,selected:(C==null?void 0:C.id)===b.id,onClick:()=>{$(null),S(b.id),E("preview"),_(!1)}},b.id)),we>0?t.jsxs("button",{type:"button",className:"dql-app-research-history-toggle",onClick:()=>re(b=>!b),children:[t.jsx("span",{children:Q?"Hide older runs":`Show ${we} older run${we===1?"":"s"}`}),t.jsx("small",{children:Q?"Keep the current analysis focused":"Includes failed and superseded analysis attempts"})]}):null]})]}),t.jsx("section",{className:"dql-app-research-detail",children:he?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"dql-app-report-toolbar",children:[t.jsxs("div",{children:[t.jsx("span",{children:"New memo"}),t.jsx("b",{children:V})]}),x.length?t.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>_(b=>!b),children:[t.jsx(Be,{size:13})," ",D?"Hide history":`Analysis history (${x.length})`]}):null]}),Y?t.jsx("div",{className:"dql-app-error",children:Y}):null,t.jsxs("div",{className:"dql-app-research-creating active",children:[t.jsx(Oe,{size:24}),t.jsx("span",{children:"Preparing business memo"}),t.jsx("h2",{children:"Writing business memo..."}),t.jsxs("p",{children:['DQL is opening a scoped memo for "',V,'". The previous memo stays in history while this answer is built from the typed context, active filters, certified block evidence, and preview proof.']}),t.jsxs("div",{className:"dql-app-research-creating-steps",children:[t.jsx("small",{children:"Reading current filters"}),t.jsx("small",{children:"Checking certified block context"}),t.jsx("small",{children:"Building narrative and proof appendix"})]})]})]}):C&&B?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"dql-app-report-toolbar",children:[t.jsxs("div",{children:[t.jsx("span",{children:"Current memo"}),t.jsx("b",{children:ga(C)})]}),t.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>_(b=>!b),children:[t.jsx(Be,{size:13})," ",D?"Hide history":`Memo history (${x.length})`]})]}),ne||T===C.id||C.status==="running"?t.jsxs("div",{className:`dql-app-research-status ${ne?"opening":""}`,children:[t.jsx(Oe,{size:14}),t.jsxs("div",{children:[t.jsx("span",{children:ne?"Opening a new business memo...":"Refreshing the memo from certified evidence, active filters, and optional preview proof..."}),V?t.jsx("small",{children:V}):null]})]}):null,Y?t.jsx("div",{className:"dql-app-error",children:Y}):null,t.jsxs("article",{className:"dql-app-research-report",children:[t.jsxs("header",{className:"dql-app-report-hero",children:[t.jsxs("div",{className:"dql-app-report-status-row",children:[t.jsxs("span",{children:[t.jsx(Be,{size:13})," Business memo"]}),t.jsx(Fe,{tone:C.status==="error"?"draft":"agentic",children:C.reviewStatus})]}),t.jsx("h2",{children:B.title}),t.jsx("p",{children:B.scope}),t.jsx("div",{className:"dql-app-report-context-line",children:B.contextFacts.map(b=>t.jsxs("span",{children:[t.jsx("b",{children:b.label}),b.value]},b.label))}),t.jsxs("div",{className:"dql-app-report-actions",children:[t.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>void be(C),disabled:T===`pin:${C.id}`,children:[t.jsx(Wa,{size:13})," ",C.pinnedAiPinId?"Pinned to app":"Pin insight"]}),t.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-primary",onClick:()=>void ce(C),disabled:!(M.trim()||C.generatedSql)||T===`promote:${C.id}`,children:[t.jsx(tr,{size:13})," ",T===`promote:${C.id}`?"Drafting...":"Create draft block"]}),t.jsxs("details",{className:"dql-app-report-review-actions",children:[t.jsx("summary",{children:"Reviewer tools"}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>void K(C,M),disabled:T===C.id,children:[t.jsx(Oe,{size:13})," ",T===C.id?"Refreshing...":"Refresh memo"]}),(J=B.previewIssue)!=null&&J.canRebuild?t.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>void me(C),disabled:T===`rebuild:${C.id}`,children:[t.jsx(Oe,{size:13})," ",T===`rebuild:${C.id}`?"Rebuilding...":"Rebuild SQL"]}):null]})]})]}),B.previewIssue?t.jsxs("div",{className:"dql-app-report-warning",children:[t.jsx(Qe,{size:14}),t.jsx("span",{children:B.previewIssue.message})]}):null]}),t.jsx("section",{className:"dql-app-report-section dql-app-report-paper",children:B.sections.length?t.jsx(ql,{sections:B.sections}):t.jsx(Tn,{text:ee,t:f,compact:!0})}),B.keyNumbers.length||B.drivers.length?t.jsxs("section",{className:`dql-app-report-section dql-app-report-evidence-story ${B.keyNumbers.length&&B.drivers.length?"":"single"}`,children:[B.keyNumbers.length?t.jsxs("div",{children:[t.jsx("h3",{children:B.intent==="segment_compare"?"Segment numbers":B.intent==="diagnose_change"?"Movement numbers":"Key numbers"}),t.jsx("div",{className:"dql-app-report-numbers",children:B.keyNumbers.map(b=>t.jsxs("div",{className:"dql-app-report-number",children:[t.jsx("span",{children:b.label}),t.jsx("b",{children:b.value}),t.jsx("small",{children:b.detail})]},b.label))})]}):null,B.drivers.length?t.jsxs("div",{children:[t.jsx("h3",{children:B.intent==="anomaly_investigation"?"Exception view":B.intent==="entity_drilldown"?"Entity view":"Driver view"}),t.jsx(Sl,{drivers:B.drivers})]}):null]}):null,t.jsxs("details",{className:"dql-app-report-section dql-app-report-appendix",children:[t.jsxs("summary",{children:[t.jsx("span",{children:"Technical appendix"}),t.jsx("small",{children:"SQL, preview rows, caveats, routing, and source context for analyst review"}),t.jsx(Er,{size:15})]}),t.jsxs("div",{className:"dql-app-research-evidence-head",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"SQL and proof"}),t.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."})]}),t.jsx("div",{className:"dql-app-research-tabs",children:["preview","sql","assumptions","context"].map(b=>t.jsx("button",{type:"button",className:k===b?"on":"",onClick:()=>E(b),children:b==="assumptions"?"Caveats":ke(b)},b))})]}),t.jsx(Cl,{investigation:C,tab:k,sqlDraft:M,onSqlDraftChange:I})]})]})]}):t.jsxs(t.Fragment,{children:[Y?t.jsx("div",{className:"dql-app-error",children:Y}):null,X?t.jsxs("div",{className:"dql-app-research-creating",children:[t.jsx(Oe,{size:22}),t.jsx("span",{children:"Preparing business memo"}),t.jsx("h2",{children:"Writing business memo..."}),t.jsx("p",{children:V?`DQL is opening a scoped memo for "${V}".`:"DQL is using the Copilot context, active filters, certified block evidence, and any available preview proof to create the main-canvas memo."})]}):t.jsx(qe,{title:"Start analysis from Copilot.",detail:"Ask a follow-up, add context, then review the analysis here."})]})})]}):t.jsx(qe,{title:"No App selected.",detail:"Choose an App before writing analysis."})}function Tr({item:e,selected:r,onClick:a}){return t.jsxs("button",{type:"button",className:[r?"on":"",`status-${e.status}`].filter(Boolean).join(" "),onClick:a,children:[t.jsx("span",{children:ga(e)}),t.jsx("small",{children:Il(e)})]})}function Hn({appDoc:e}){const r=(e==null?void 0:e.notebooks)??(e==null?void 0:e.app.notebooks)??[];return r.length?t.jsx("div",{className:"dql-app-simple-list",children:r.map(a=>t.jsxs(Ge,{icon:t.jsx(Qr,{size:16}),children:[t.jsx("b",{children:a.title??a.path.split("/").pop()}),t.jsxs("span",{children:[a.role," / ",a.visibility," / ",a.path]})]},a.path))}):t.jsx(qe,{title:"No notebooks attached.",detail:"Attach analysis notebooks in Build mode when this App needs supporting work."})}function Qn({appDoc:e}){const r=(e==null?void 0:e.aiPins)??[];return r.length?t.jsx("div",{className:"dql-app-simple-list",children:r.map(a=>t.jsxs(Ge,{icon:t.jsx(Ct,{size:16}),children:[t.jsx("b",{children:a.title}),t.jsxs("span",{children:[a.certification," / ",a.reviewStatus]})]},a.id))}):t.jsx(qe,{title:"No pinned insights yet.",detail:"Use Copilot from a dashboard page, create analysis, then add useful reviewed insights to this App."})}function Kn({appDoc:e}){const r=(e==null?void 0:e.drafts)??[];return r.length?t.jsx("div",{className:"dql-app-simple-list",children:r.map(a=>t.jsxs(Ge,{icon:t.jsx(tr,{size:16}),children:[t.jsx("b",{children:a.name}),t.jsxs("span",{children:[a.reviewStatus??"needs review"," / ",a.path]})]},a.path))}):t.jsx(qe,{title:"No drafts.",detail:"Generated and promoted draft blocks will appear here for review."})}function Gn({appDoc:e}){var r;return e?t.jsxs("div",{className:"dql-app-settings-grid",children:[t.jsxs(Ge,{icon:t.jsx(We,{size:16}),children:[t.jsx("b",{children:"Owners"}),t.jsx("span",{children:e.app.owners.join(", ")})]}),t.jsxs(Ge,{icon:t.jsx(Oe,{size:16}),children:[t.jsx("b",{children:"Lifecycle"}),t.jsx("span",{children:e.app.lifecycle??"draft"})]}),t.jsxs(Ge,{icon:t.jsx(er,{size:16}),children:[t.jsx("b",{children:"Policies"}),t.jsxs("span",{children:[e.app.policies.length," local access policies"]})]}),t.jsxs(Ge,{icon:t.jsx(Ye,{size:16}),children:[t.jsx("b",{children:"Homepage"}),t.jsx("span",{children:((r=e.app.homepage)==null?void 0:r.type)??"dashboard"})]})]}):t.jsx(qe,{title:"No App selected.",detail:"Choose an App to inspect its settings."})}function Ft({title:e,meta:r}){return t.jsxs("div",{className:"dql-app-panel-head",children:[t.jsx("span",{children:e}),r?t.jsx("b",{children:r}):null]})}function Yn(e){return e.kind==="certified_block"&&e.certification==="certified"}function Xn(e){var i;const r=Array.isArray(e.scopedReports)?e.scopedReports.length:0,a=Array.isArray((i=e.planning)==null?void 0:i.scopedReports)?e.planning.scopedReports.length:0;return r>0||a>0?Math.max(r,a):Array.isArray(e.missingEvidence)?e.missingEvidence.length:0}function Jn({filters:e,values:r,onChange:a}){return e.length===0?t.jsx("span",{className:"dql-app-filter-empty",children:"No filters"}):t.jsx(t.Fragment,{children:e.map(i=>t.jsx(Zn,{filter:i,value:r[i.id]??lt(i),onChange:n=>a(i,n)},i.id))})}function Zn({filter:e,value:r,onChange:a}){var f;const i=ke(e.id),n=Un(e,r),l=e.sourceBlockId,s=e.bindsTo||e.id,o=(e.type==="string"||e.type==="select")&&!!l&&!((f=e.options)!=null&&f.length),[p,d]=u.useState(null);if(u.useEffect(()=>{if(!o||!l)return;let x=!1;return Z.dashboardFilterOptions(l,s).then(c=>{!x&&c&&c.options.length>0&&!c.truncated&&d(c.options)}),()=>{x=!0}},[l,s,o]),p&&p.length>0)return t.jsx(Wt,{icon:at(e),label:i,value:n,onChange:a,options:[["",`All ${i.toLowerCase()}`],...p.map(x=>[x,x])]});if(e.type==="select")return t.jsx(Wt,{icon:at(e),label:i,value:n,onChange:a,options:Dn(e)});if(e.type==="boolean")return t.jsx(Wt,{icon:at(e),label:i,value:String(!!r),onChange:x=>a(x==="true"),options:[["true","Yes"],["false","No"]]});if(e.type==="daterange"){const x=r&&typeof r=="object"&&!Array.isArray(r)?r:{},c=typeof x.start=="string"?x.start:"",A=typeof x.end=="string"?x.end:"",S=(q,h)=>a(q&&h?{start:q,end:h}:void 0);return t.jsxs("label",{className:"dql-app-filter-select dql-app-filter-range",title:e.bindsTo?`${i} -> ${e.bindsTo}`:i,"aria-label":i,children:[t.jsx("span",{className:"dql-app-filter-icon",children:at(e)}),t.jsx("input",{type:"date",value:c,"aria-label":`${i} from`,onChange:q=>S(q.target.value,A)}),t.jsx("span",{className:"dql-app-filter-range-sep",children:"–"}),t.jsx("input",{type:"date",value:A,"aria-label":`${i} to`,onChange:q=>S(c,q.target.value)})]})}return t.jsxs("label",{className:"dql-app-filter-select",title:e.bindsTo?`${i} -> ${e.bindsTo}`:i,"aria-label":i,children:[t.jsx("span",{className:"dql-app-filter-icon",children:at(e)}),t.jsx("input",{type:e.type==="number"?"number":e.type==="date"?"date":"text",value:n,placeholder:i,onChange:x=>a(x.target.value)})]})}function at(e){return e.type==="date"||e.type==="daterange"||/season|year|date|time|period/i.test(e.id)?t.jsx(La,{size:13}):t.jsx(Kr,{size:13})}function Dn(e){var a;return((a=e.options)!=null&&a.length?e.options:[e.default].filter(i=>i!==void 0)).map(i=>[String(i),ke(String(i))])}function lt(e){var r;return e.default!==void 0?e.default:e.type==="number"?pa(e.id):e.type==="boolean"?!1:e.type==="select"?((r=e.options)==null?void 0:r[0])??"":""}function Un(e,r){return r==null?String(lt(e)??""):e.type==="daterange"&&typeof r=="object"?JSON.stringify(r):String(r)}function el(e,r){if(e.type==="number"){if(typeof r=="string"&&r.trim()==="")return"";const a=Number(r);return Number.isFinite(a)?a:r}if(e.type==="boolean")return r===!0||r==="true";if(e.type==="select"&&typeof e.default=="number"){const a=Number(r);return Number.isFinite(a)?a:r}return r}function $r(e,r){const a=Object.keys(e),i=Object.keys(r);return a.length!==i.length?!1:a.every(n=>Object.is(e[n],r[n]))}function Wt({label:e,icon:r,value:a,options:i,onChange:n}){return t.jsxs("label",{className:"dql-app-filter-select",title:e,"aria-label":e,children:[r?t.jsx("span",{className:"dql-app-filter-icon",children:r}):t.jsx("span",{children:e}),t.jsx("select",{value:a,onChange:l=>n(l.target.value),children:i.map(([l,s])=>t.jsx("option",{value:l,children:s},l))})]})}function Vt(e){return e.block?"blockId"in e.block?e.block.blockId??null:e.block.ref??null:null}function ua(e,r){if(!e)return[];const a=new Map(((r==null?void 0:r.tiles)??[]).map(p=>[p.tileId,p])),i=new Map(((r==null?void 0:r.tiles)??[]).filter(p=>p.blockId).map(p=>[p.blockId,p])),n=new Set(e.layout.items.filter(p=>Vt(p)&&Pr(p)).map(p=>Zt(`${p.title??""} ${Vt(p)??""}`)).filter(Boolean)),l=e.layout.items.map((p,d)=>{const f=Vt(p);if(!f)return null;const x=Zt(`${p.title??""} ${f}`);if(x&&n.has(x)&&!Pr(p))return null;const c=a.get(p.i)??i.get(f);return{block:{blockId:f,title:p.title??f,viz:p.viz.type,tileId:p.i},duplicateKeys:tl(p,c,f),score:il(p,c,d)}}).filter(p=>!!p).sort((p,d)=>d.score-p.score),s=new Set,o=[];for(const p of l)if(!p.duplicateKeys.some(d=>s.has(d))){for(const d of p.duplicateKeys)s.add(d);o.push(p.block)}return o}function Pr(e){var r,a;return(r=e.parameterBindings)!=null&&r.length?!0:!!((a=e.filterBindings)!=null&&a.some(i=>!i.unsupportedReason&&(i.mode==="parameter"||i.mode==="predicate"||!!i.binding)))}function tl(e,r,a){const i=[`block:${a}`],n=rl(r==null?void 0:r.result);n&&i.push(`result:${n}`);const l=Zt(`${e.title??""} ${a}`);return l&&i.push(`topic:${l}`),i}function rl(e){var i,n;if(!((i=e==null?void 0:e.columns)!=null&&i.length)||!((n=e.rows)!=null&&n.length))return"";const r=e.columns.slice(0,6).map(l=>l.toLowerCase()),a=e.rows.slice(0,3).map(l=>r.map(s=>al(l[s]??l[e.columns.find(o=>o.toLowerCase()===s)??s])).join(","));return[...r,...a].join("|")}function al(e){return e==null?"":typeof e=="number"?Number.isFinite(e)?String(Math.round(e*1e3)/1e3):"":String(e).toLowerCase().replace(/\s+/g," ").trim().slice(0,80)}function Zt(e){const r=e.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":"",n=/\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||!n?"":`${a}|${i}|${n}`}function il(e,r,a){var n,l,s,o,p;let i=1e4-a;return(n=e.parameterBindings)!=null&&n.length&&(i+=5e4),(l=e.filterBindings)!=null&&l.length&&(i+=2e4),(r==null?void 0:r.status)==="ok"&&(i+=15e3),(o=(s=r==null?void 0:r.result)==null?void 0:s.rows)!=null&&o.length&&(i+=8e3),(r==null?void 0:r.certificationStatus)==="certified"&&(i+=5e3),String(e.trustState??((p=e.display)==null?void 0:p.trustState)??"").toLowerCase()==="certified"&&(i+=3e3),/codex\s+e2e|test|pasted/i.test(String(e.title??""))&&(i-=6e3),i}function nl(e,r){if(!Array.isArray(e)||e.length===0)return;const a=Array.isArray(r)&&r.length>0?r.slice(0,8):Object.keys(e[0]??{}).slice(0,8);return e.slice(0,5).map(i=>Object.fromEntries(a.map(n=>[n,i[n]])))}function qt(e){return String(e??"").replace(/\s+/g," ").replace(/[\s,;:.–—-]+$/,"").trim()}function ke(e){const r=String(e??"").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 xa(e){return e.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 zt(e){return e==null||e===""?"All":Array.isArray(e)?e.map(zt).join(", "):typeof e=="boolean"?e?"On":"Off":typeof e=="number"?e.toLocaleString():typeof e=="object"?JSON.stringify(e):String(e)}function fa(e,r){if(Array.isArray(r))return r.map(i=>fa(e,i)).join(", ");const a=typeof r=="number"?r:typeof r=="string"&&r.trim()!==""?Number(r):NaN;return/(season|year)/i.test(e)&&Number.isInteger(a)&&a>=1900&&a<=2200?String(a):zt(r)}function ll(e,r,a){var o;const i=(e==null?void 0:e.id)??(r==null?void 0:r.app.id)??"app",n=(e==null?void 0:e.name)??(r==null?void 0:r.app.name)??"DQL App",l=(a==null?void 0:a.dashboard.metadata.title)??((o=r==null?void 0:r.dashboards[0])==null?void 0:o.title)??"Overview",s=typeof window<"u"?window.location.origin:"local DQL";return[n,`App ID: ${i}`,`Dashboard: ${l}`,`Domain: ${(e==null?void 0:e.domain)??(r==null?void 0:r.app.domain)??(a==null?void 0:a.dashboard.metadata.domain)??"unknown"}`,`Open locally: ${s}`].join(`
47
+ */const Xa=[["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"}]],Ja=Ee("table-2",Xa),Za=u.lazy(()=>Ut(()=>import("./UnifiedAgentRunPanel-CGPcpY1B.js").then(e=>e.c),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])).then(e=>({default:e.UnifiedAgentRunPanel}))),Da="clamp(320px, calc(100vh - 220px), 760px)",ar=[{value:"table",label:"Table"},...ka];function Ua(e,r){if(!Array.isArray(e)||e.length===0)return;const a=Array.isArray(r)&&r.length>0?r.slice(0,8):Object.keys(e[0]??{}).slice(0,8);return e.slice(0,5).map(i=>Object.fromEntries(a.map(n=>[n,i[n]])))}const Gr=[{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 ei({appId:e,dashboard:r,variables:a,editable:i=!1,embeddedHeader:n=!1,onDashboardChanged:l,selectedBlockId:s,onBlockFocus:o,onAskBlock:p,onOpenLineageNode:d,copilotOpen:f,onCopilotChange:x,onRunChange:c}){var ft;const{state:A}=At(),S=Ne[A.themeMode],[q,h]=u.useState(null),[T,z]=u.useState(null),Y=u.useRef(null),[$,k]=u.useState(!1),[E,M]=u.useState(null),[I,Q]=u.useState(!1),re=Or(`app:${e}:${r.id}`),[D,_]=u.useState(!1),[V,W]=u.useState([]),[de,C]=u.useState(""),[le,we]=u.useState(!1),[B,ee]=u.useState(null),[ne,he]=u.useState(!1),[X,K]=u.useState(!1),[me,pe]=u.useState(!1),[ye,ce]=u.useState(null),[be,J]=u.useState(""),[b,P]=u.useState(null),U=u.useRef(null),[G,N]=u.useState(!1),L=r.layout.cols,se=r.layout.rowHeight,ve=u.useMemo(()=>JSON.stringify(a??{}),[a]),oe=u.useMemo(()=>JSON.parse(ve),[ve]),ue=u.useMemo(()=>{const m=new Map;for(const j of(q==null?void 0:q.tiles)??[])m.set(j.tileId,j);return m},[q]),xe=u.useMemo(()=>i?r.layout.items:r.layout.items.filter(m=>!zi(m)),[r.layout.items,i]),ae=u.useMemo(()=>i?xe:Ai(xe,ue,L),[xe,L,i,ue]),Ce=r.layout.items.length-xe.length,H=xe.length-ae.length,y=u.useMemo(()=>!i&&!r.story&&r.sections&&r.sections.length>0?[...r.sections].sort((m,j)=>m.order-j.order):null,[r.sections,r.story,i]),te=u.useMemo(()=>y?r.layout.items:null,[r.layout.items,y]),ie=u.useMemo(()=>i||y?null:Ri(ae,ue,oe),[i,oe,y,ue,ae]);u.useEffect(()=>{let m=!1;return k(!0),M(null),Z.runDashboard(e,r.id,oe).then(j=>{m||(h(j),z((j==null?void 0:j.story)??null),Y.current=(j==null?void 0:j.runId)??null,c==null||c(j),j||M("Dashboard run failed."),j!=null&&j.runId&&Z.getDashboardStory(e,r.id,j.runId).then(w=>{m||!w||Y.current!==w.runId||w.snapshotId!==j.snapshotId||w.filterFingerprint!==j.filterFingerprint||w.resultFingerprint!==j.resultFingerprint||w.personaFingerprint!==j.personaFingerprint||z(w.story)}))}).catch(j=>{m||(M(j instanceof Error?j.message:String(j)),c==null||c(null))}).finally(()=>{m||k(!1)}),()=>{m=!0}},[e,r.id,r.layout.items.length,c,oe,(ft=A.activePersona)==null?void 0:ft.userId]),u.useEffect(()=>{const m=j=>{const w=j.detail;(w==null?void 0:w.appId)!==e||w.dashboardId!==r.id||(Z.getDashboard(e,r.id).then(F=>{F!=null&&F.dashboard&&(l==null||l(F.dashboard))}),Z.runDashboard(e,r.id,oe).then(F=>{F&&(h(F),z(F.story),Y.current=F.runId,c==null||c(F))}))};return window.addEventListener("dql-app-dashboard-updated",m),()=>window.removeEventListener("dql-app-dashboard-updated",m)},[e,r.id,l,c,oe]),u.useEffect(()=>{const m=()=>N(window.innerWidth<760);return m(),window.addEventListener("resize",m),()=>window.removeEventListener("resize",m)},[]);const _e=u.useMemo(()=>{const m=r.layout.items.map(j=>{var fe,je,g,v,R;const w=ue.get(j.i),F=j.block?"blockId"in j.block?j.block.blockId:j.block.ref:j.semantic?`semantic:${j.semantic.id}`:j.aiPin?`aiPin:${j.aiPin.id}`:"text";return{title:j.title,blockRef:F,viz:j.viz.type,certificationStatus:w==null?void 0:w.certificationStatus,status:w==null?void 0:w.status,rowCount:(fe=w==null?void 0:w.result)==null?void 0:fe.rowCount,columns:(g=(je=w==null?void 0:w.result)==null?void 0:je.columns)==null?void 0:g.slice(0,8),sampleRows:Ua((v=w==null?void 0:w.result)==null?void 0:v.rows,(R=w==null?void 0:w.result)==null?void 0:R.columns)}});return JSON.stringify({scope:"dashboard",appId:e,dashboardId:r.id,title:r.metadata.title,description:r.metadata.description,domain:r.metadata.domain,filters:r.filters,variables:oe,run:q?{runId:q.runId,snapshotId:q.snapshotId,filterFingerprint:q.filterFingerprint,resultFingerprint:q.resultFingerprint,personaFingerprint:q.personaFingerprint,story:q.story,facts:q.facts}:null,tiles:m},null,2)},[e,r,q,oe,ue]),Se=u.useCallback(async m=>{he(!0);const j={...r,layout:{...r.layout,items:m}},w=await Z.patchDashboardLayout(e,r.id,j.layout);he(!1),w.ok?l==null||l(w.dashboard):M(w.error)},[e,r,l]),tt=u.useCallback(async()=>{_(!0);const m=await Z.getAppEditorCatalog(e);W((m==null?void 0:m.blocks)??[])},[e]),ct=u.useCallback(async m=>{const j=dt(m.chartType),w=await Z.recommendDashboardTile(e,r.id,{blockRef:m.name,appAudience:r.metadata.audience,prompt:`${r.metadata.title} ${m.name} ${m.description}`,defaultVisualization:j}),F=or(j,L),fe={i:Mt(r,m.name),..._t(r,F),block:{blockId:m.name},viz:{type:j},...w.ok?{display:w.display,filterBindings:"filterBindings"in w?w.filterBindings:void 0,parameterBindings:"parameterBindings"in w?w.parameterBindings:void 0,sourceEvidence:"sourceEvidence"in w?w.sourceEvidence:void 0,trustState:"trustState"in w?w.trustState:w.display.trustState,reviewStatus:"reviewStatus"in w?w.reviewStatus:w.display.reviewStatus}:{},title:m.name};await Se([...r.layout.items,fe]),_(!1)},[e,L,r,Se]),Me=u.useCallback(async()=>{ce("text"),J("")},[]),Ve=u.useCallback(async()=>{ce("heading"),J("")},[]),Nt=u.useCallback(async()=>{var j;const m=be.trim();if(!(!m||!ye)){if(ye==="heading")await Se([...r.layout.items,{i:Mt(r,"section"),..._t(r,Ie("wide",L,"heading")),text:{markdown:m},viz:{type:"heading"},display:mr("heading",m),title:m}]);else{const w=((j=m.split(/\r?\n/)[0])==null?void 0:j.slice(0,60))||"Summary";await Se([...r.layout.items,{i:Mt(r,"text"),..._t(r,Ie("standard",L,"text")),text:{markdown:m},viz:{type:"text"},display:mr("text",w),title:w}])}ce(null),J("")}},[L,r,Se,ye,be]),He=u.useCallback(async(m,j)=>{const w=j===null?r.layout.items.filter(F=>F.i!==m):r.layout.items.map(F=>F.i===m?{...F,...j}:F);await Se(wt(w,L))},[L,r.layout.items,Se]),It=u.useCallback(async(m,j)=>{const w=U.current,F=r.layout.items.find(ht=>ht.i===m);if(!w||!F)return;const fe=w.getBoundingClientRect(),je=12,v=(fe.width-je*(L-1))/L+je,R=se+je,O=Math.round((j.clientX-fe.left)/v),ze=Math.round((j.clientY-fe.top)/R),Je={...F,x:St(O,0,Math.max(0,L-F.w)),y:Math.max(0,ze)};P(null);const gt=kn(r.layout.items,Je,L);await Se(wt(gt,L))},[L,r.layout.items,se,Se]),Tt=u.useCallback((m,j)=>{const w=U.current,F=r.layout.items.find(O=>O.i===m);if(!w||!F)return;const fe=w.getBoundingClientRect(),je=12,g=(fe.width-je*(L-1))/L,v=Math.round((j.clientX-fe.left)/(g+je)),R=Math.round((j.clientY-fe.top)/(se+je));P({tileId:m,x:St(v,0,Math.max(0,L-F.w)),y:Math.max(0,R),w:F.w,h:F.h})},[L,r.layout.items,se]),$t=u.useCallback(()=>P(null),[]),Pt=u.useCallback(async()=>{const m=r.layout.items;if(m.length===0)return;const j=[...m].map((w,F)=>({item:w,index:F})).sort((w,F)=>{const fe=Jt(w.item)-Jt(F.item);return fe!==0?fe:w.index-F.index}).map(({item:w})=>{const F=pr(w,L);return{...w,w:F.w,h:F.h}});await Se(wt(j,L))},[L,r.layout.items,Se]),ut=u.useCallback(async()=>{if(we(m=>!m),!B){const m=await Z.fetchScopedLineage({domain:r.metadata.domain,appId:e,dashboardId:r.id});ee(m)}},[e,r.id,r.metadata.domain,B]),Xe=u.useCallback(()=>{if(d){d(`dashboard:${e}/${r.id}`);return}ut()},[e,r.id,ut,d]),xt=x?!!f:I,rt=u.useCallback(()=>{if(K(!1),x){x(!0);return}Q(!0)},[x]),Rt=u.useCallback(()=>{if(K(!1),x){x(!f);return}Q(m=>!m)},[f,x]);return t.jsxs("div",{style:{display:"block",minHeight:0},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[(!n||i)&&t.jsxs("div",{style:Gi,children:[t.jsx("div",{style:{flex:1,minWidth:0},children:n?null:t.jsxs(t.Fragment,{children:[t.jsx("h2",{style:{margin:0,fontSize:20,lineHeight:1.18,fontWeight:780},children:r.metadata.title}),r.metadata.description?t.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&&t.jsx(fr,{open:X,onToggle:()=>K(m=>!m),buttonStyle:Ki,onCertifiedBlock:()=>{K(!1),tt()},onText:()=>{K(!1),Me()},onHeading:()=>{K(!1),Ve()},onAi:rt}),i&&r.layout.items.length>1&&t.jsx("button",{type:"button",onClick:()=>void Pt(),disabled:ne,style:Qi(!1),title:"Auto-arrange every tile into a clean, gap-free grid",children:t.jsx(Wr,{size:15,strokeWidth:2})}),!n&&t.jsxs(t.Fragment,{children:[t.jsxs("button",{type:"button",onClick:Rt,style:Ue(xt),children:[t.jsx(Ct,{size:14,strokeWidth:2}),xt?"Hide copilot":"AI Copilot"]}),t.jsxs("button",{type:"button",onClick:Xe,style:Ue(!1),title:"Open focused dashboard lineage",children:[t.jsx(Lr,{size:14,strokeWidth:2}),"Lineage"]})]})]}),i&&t.jsx("div",{style:Yi,children:"Drag tiles, select a block for Copilot context, or use the tile controls for sizing and chart settings."}),!i&&T?t.jsx(ni,{story:T,onResearch:rt,onEvidence:Xe}):ie?t.jsx(ii,{story:ie}):null,ae.length===0?t.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:[t.jsx("div",{style:{fontSize:16,fontWeight:700,marginBottom:6},children:Ce>0||H>0?"No stakeholder-ready tiles yet":"Build this dashboard page"}),t.jsx("div",{style:{maxWidth:520,opacity:.68,lineHeight:1.45},children:Ce>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.":H>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."}),t.jsx("div",{style:{marginTop:18,display:"flex",gap:8,flexWrap:"wrap",justifyContent:"center"},children:t.jsx(fr,{open:X,onToggle:()=>K(m=>!m),buttonLabel:"Add tile",buttonStyle:la,onCertifiedBlock:()=>{K(!1),tt()},onText:()=>{K(!1),Me()},onHeading:()=>{K(!1),Ve()},onAi:rt})})]}):y?t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:22},children:y.map(m=>{var v,R;const j=(v=y.find(O=>O.kind==="appendix"))==null?void 0:v.id,w=((R=y.find(O=>O.kind==="insight"))==null?void 0:R.id)??y[0].id,F=O=>O.sectionId&&y.some(ze=>ze.id===O.sectionId)?O.sectionId:(O.trustState==="review_required"||O.reviewStatus==="review_required")&&j?j:w,fe=(te??ae).filter(O=>F(O)===m.id);if(fe.length===0)return null;const je=Math.min(...fe.map(O=>O.y)),g=m.kind==="appendix";return t.jsxs("section",{"aria-label":m.title,children:[m.kind!=="exec_summary"?t.jsxs("div",{style:{marginBottom:10},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8},children:[t.jsx("h3",{style:{margin:0,fontSize:15,fontWeight:800,color:"var(--dql-app-text, #0f172a)"},children:m.title}),g?t.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]}),m.narrative?t.jsx("p",{style:{margin:"4px 0 0",fontSize:12.5,lineHeight:1.5,color:"var(--dql-app-text-muted, #64748b)",maxWidth:860},children:m.narrative}):null]}):null,t.jsx("div",{style:{display:"grid",gridTemplateColumns:G?"minmax(0, 1fr)":`repeat(${L}, 1fr)`,gridAutoRows:G?"auto":`${se}px`,gap:12,...g?{opacity:.96}:{}},children:fe.map(O=>t.jsx(cr,{item:{...O,y:O.y-je},tile:ue.get(O.i),loading:$,error:E,themeMode:A.themeMode,editable:!1,narrow:G,cols:L,selected:!!(Te(O)&&Te(O)===s),onFocusBlock:o,onAskBlock:p,onMove:()=>{},onDragMove:()=>{},onDragEnd:()=>{},onPatch:ze=>void He(O.i,ze)},O.i))})]},m.id)})}):t.jsxs("div",{ref:U,style:{display:"grid",gridTemplateColumns:G?"minmax(0, 1fr)":`repeat(${L}, 1fr)`,gridAutoRows:G?"auto":`${se}px`,gap:12},children:[b&&!G&&t.jsx("div",{"aria-hidden":"true",style:{gridColumn:`${b.x+1} / span ${b.w}`,gridRow:`${b.y+1} / span ${b.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}}),ae.map(m=>t.jsx(cr,{item:m,tile:ue.get(m.i),loading:$,error:E,themeMode:A.themeMode,editable:i,narrow:G,cols:L,selected:!!(Te(m)&&Te(m)===s),onFocusBlock:o,onAskBlock:p,onMove:j=>void It(m.i,j),onDragMove:j=>Tt(m.i,j),onDragEnd:$t,onPatch:j=>void He(m.i,j)},m.i))]}),!i&&q?t.jsx(li,{run:q,variables:oe}):null]}),le&&!d&&t.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:Da,position:"sticky",top:12,padding:12},children:t.jsx(ji,{lineage:B})}),I&&!x&&t.jsx(Mr,{t:S,title:"Dashboard AI",subtitle:"Scoped to this App dashboard first",expanded:me,onToggleExpanded:()=>pe(m=>!m),onClose:()=>{Q(!1),pe(!1)},floating:!0,ariaLabel:"Dashboard AI",style:Xi(me),children:t.jsx(u.Suspense,{fallback:t.jsx("div",{style:{padding:16,fontSize:12,color:S.textSecondary},children:"Loading Dashboard AI…"}),children:t.jsx(Za,{themeMode:A.themeMode,title:"Dashboard AI",scopeHint:"Scoped to this App dashboard first",audience:"stakeholder",workspaceContext:{appId:e,dashboardId:r.id,dashboardContext:_e},initialMode:"auto",threadId:re.threadId,onThreadIdChange:re.onThreadIdChange},`${e}:${r.id}`)})}),D&&t.jsx(wi,{blocks:V,search:de,onSearch:C,onClose:()=>_(!1),onAdd:m=>void ct(m)}),ye&&t.jsx(qi,{kind:ye,value:be,onChange:J,onClose:()=>{ce(null),J("")},onSave:()=>void Nt()})]})}function cr({item:e,tile:r,loading:a,error:i,themeMode:n,editable:l,narrow:s,cols:o,selected:p,onFocusBlock:d,onAskBlock:f,onMove:x,onDragMove:c,onDragEnd:A,onPatch:S}){var he;const q=u.useRef(null),[h,T]=u.useState(null),[z,Y]=u.useState(!1),$=Te(e),k=!!(!l&&$&&f),E=$?`block:${$}`:e.semantic?`semantic:${e.semantic.id}`:e.aiPin?`aiPin:${e.aiPin.id}`:"text",M=dt(String(e.viz.type??"table")),I=Le(e),Q=I==null?void 0:I.component,re=(I==null?void 0:I.insightTitle)||e.title||E,D=(r==null?void 0:r.tileType)==="aiPin"?((he=r.aiPin)==null?void 0:he.certification)==="certified"?"certified":"review_required":void 0,_=(I==null?void 0:I.trustState)??D??((r==null?void 0:r.certificationStatus)==="certified"?"certified":void 0),V=!!I,W=e.h<=2&&(M==="single_value"||M==="kpi"||M==="gauge"),[de,C]=u.useState(!1),le=l&&(de||p||z),we=Mi(e,I),B=!!(k&&(de||p)),ee=X=>{const K=Kt(X),me=e.viz.options??{},pe=Le(e);S({viz:{...e.viz,type:K,options:{...me,chart:X,...pe?{dqlGenUi:{...pe,defaultVisualization:K}}:{}}},display:Xr(e,K,pe)})},ne=X=>{if(s)return;const K=q.current;if(!K)return;X.preventDefault(),X.stopPropagation();const me=K.getBoundingClientRect(),pe={x:X.clientX-me.left,y:X.clientY-me.top},ye={x:X.clientX,y:X.clientY},ce=J=>{T({x:J.clientX-ye.x,y:J.clientY-ye.y}),c==null||c({clientX:J.clientX-pe.x,clientY:J.clientY-pe.y})},be=J=>{window.removeEventListener("pointermove",ce),window.removeEventListener("pointerup",be),T(null),A==null||A(),x({clientX:J.clientX-pe.x,clientY:J.clientY-pe.y})};window.addEventListener("pointermove",ce),window.addEventListener("pointerup",be,{once:!0})};return t.jsxs("div",{ref:q,onMouseEnter:()=>C(!0),onMouseLeave:()=>C(!1),onClick:()=>{$&&(d==null||d($))},style:{gridColumn:s?"1 / -1":`${e.x+1} / span ${e.w}`,gridRow:s?"auto":`${e.y+1} / span ${e.h}`,transform:h?`translate(${h.x}px, ${h.y}px) scale(1.02)`:void 0,opacity:h?.92:1,zIndex:h?30:void 0,position:"relative",background:V?Oi(Q):"var(--dql-app-surface, var(--surface, rgba(0,0,0,0.02)))",border:p||h?"1.5px solid var(--dql-app-accent, var(--accent, #4f46e5))":V?"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:W?12:14,paddingBottom:B?W?42:46:W?12:14,display:"flex",flexDirection:"column",gap:W?4:V?10:6,minHeight:s?qn(e,I):0,overflow:"visible",boxShadow:h?"0 16px 40px rgba(0,0,0,0.22)":p?"0 0 0 3px var(--dql-app-accent-soft, rgba(79,70,229,0.12))":void 0,cursor:h?"grabbing":$?"pointer":void 0,transition:h?void 0:"box-shadow 120ms ease, transform 120ms ease"},children:[B?t.jsxs("button",{type:"button",style:di,onClick:X=>{X.stopPropagation(),$&&(d==null||d($)),$&&(f==null||f($,ci(e.title??$)))},title:"Open app Copilot for this tile",children:[t.jsx(Re,{size:11,strokeWidth:2})," Ask AI"]}):null,l&&!s?t.jsx("div",{style:{position:"absolute",top:10,left:10,zIndex:3,opacity:le?1:0,pointerEvents:le?"auto":"none",transition:"opacity 120ms ease"},children:t.jsx("button",{type:"button",title:"Drag to move tile",onPointerDown:ne,style:mn,children:t.jsx(Pa,{size:14,strokeWidth:2.2})})}):null,l?t.jsxs("div",{style:{position:"absolute",top:10,right:10,zIndex:4,display:"flex",alignItems:"center",gap:4,opacity:le?1:0,pointerEvents:le?"auto":"none",transition:"opacity 120ms ease"},children:[W?null:t.jsx("span",{style:{fontSize:10,padding:"2px 8px",borderRadius:999,background:"var(--surface-hover, rgba(0,0,0,0.06))",opacity:.85},children:e.viz.type}),t.jsx(xi,{item:e,cols:o,settingsOpen:z,onToggleSettings:()=>Y(X=>!X),onPatch:S})]}):null,V?t.jsx("div",{style:{minHeight:W?26:42,paddingLeft:le?30:0,paddingRight:le?W?82:134:0,transition:"padding 120ms ease",display:"grid",gap:7},children:t.jsxs("div",{style:{display:"flex",alignItems:"flex-start",gap:8,minWidth:0},children:[t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:W?12:13,fontWeight:780,lineHeight:1.25,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:re}),t.jsxs("div",{style:an,children:[_?t.jsx(ot,{trust:_}):null,I?t.jsx("span",{style:$e,children:Dr(I)}):null,I!=null&&I.layoutIntent?t.jsx("span",{style:$e,children:Ae(String(I.layoutIntent))}):null]})]}),l&&we.length>1?t.jsx(ai,{value:Ze(e.viz.type),options:we,onChange:ee}):null]})}):t.jsxs("div",{style:{minHeight:W?22:26,paddingLeft:le?30:0,paddingRight:le?W?82:134:0,transition:"padding 120ms ease"},children:[t.jsx("div",{style:{fontSize:W?12:13,fontWeight:720,lineHeight:1.25,minWidth:0,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:e.title??E}),D?t.jsxs("div",{style:{marginTop:5,display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},children:[t.jsx(ot,{trust:D}),t.jsx("span",{style:$e,children:"AI generated"})]}):W?null:t.jsx("div",{style:{marginTop:5,fontSize:10.5,opacity:.58,fontFamily:"var(--font-mono, monospace)",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:E})]}),l&&z?t.jsx(gi,{item:e,tile:r,cols:o,onPatch:S}):null,t.jsx("div",{style:{flex:1,minHeight:0,overflow:"hidden",display:"flex",alignItems:"center",justifyContent:"center",marginTop:W?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:t.jsx(ui,{item:e,tile:r,loading:a,error:i,themeMode:n,genUi:I})}),l?null:t.jsx(ti,{tile:r,themeMode:n})]})}function ti({tile:e,themeMode:r}){const a=Ne[r],i=u.useMemo(()=>ri(e),[e]);return i?t.jsxs("div",{style:{padding:"4px 10px 8px",fontSize:11.5,color:a.textMuted,lineHeight:1.4,display:"flex",gap:5,alignItems:"baseline"},children:[t.jsx("span",{style:{color:a.accent},children:"•"}),t.jsx("span",{children:i})]}):null}function ri(e){var f,x;const r=(f=e==null?void 0:e.result)==null?void 0:f.rows,a=(x=e==null?void 0:e.result)==null?void 0:x.columns;if(!Array.isArray(r)||r.length===0||!Array.isArray(a)||a.length===0)return null;const i=r[0],n=c=>{if(typeof c=="number"&&Number.isFinite(c))return c;if(typeof c=="string"){const A=Number(c.replace(/[$,%\s]/g,""));return Number.isFinite(A)&&c.trim()?A:void 0}},l=a.find(c=>n(i==null?void 0:i[c])!==void 0),s=a.find(c=>c!==l&&typeof(i==null?void 0:i[c])=="string");if(!l)return null;if(r.length===1){const c=n(r[0][l]);return c!==void 0?`${l}: ${Bt(c)}.`:null}const o=r.map(c=>({label:s?String(c[s]??"—"):"top",value:n(c[l])??0})).sort((c,A)=>A.value-c.value),p=o.reduce((c,A)=>c+A.value,0),d=o[0];return d?p>0?`${d.label} leads ${l} at ${Bt(d.value)} (${Math.round(d.value/p*100)}%).`:`${d.label} leads ${l} at ${Bt(d.value)}.`:null}function Bt(e){const r=Math.abs(e);return r>=1e6?`${(e/1e6).toFixed(1)}M`:r>=1e3?`${(e/1e3).toFixed(1)}K`:Number.isInteger(e)?String(e):e.toFixed(2)}function ai({value:e,options:r,onChange:a}){return t.jsx("div",{style:ln,"aria-label":"Visualization",children:r.map(i=>t.jsx("button",{type:"button",title:i.label,onClick:n=>{n.stopPropagation(),a(i.value)},style:sn(e===i.value),children:Fi(i.value)},i.value))})}function ot({trust:e}){const r=e==="certified",a=r?"Certified":e==="review_required"?"Review required":"Draft ready";return t.jsxs("span",{style:nn(r),children:[r?t.jsx(We,{size:10,strokeWidth:2.4}):t.jsx(Qe,{size:10,strokeWidth:2.4}),a]})}function ii({story:e}){return t.jsxs("section",{style:Ur,"aria-label":"Current dashboard story",children:[t.jsxs("div",{style:ea,children:[t.jsx("div",{style:ta,children:t.jsx(Re,{size:15,strokeWidth:2.2})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:ra,children:"Story from current results"}),t.jsx("h3",{style:aa,children:e.title})]}),e.trust?t.jsx(ot,{trust:e.trust}):null]}),t.jsx("p",{style:ia,children:e.summary}),t.jsxs("div",{style:sr,children:[t.jsx("span",{style:na,children:e.sourceTitle}),e.filters.map(r=>t.jsxs("span",{style:et,children:[r.label,": ",r.value]},`${r.label}:${r.value}`)),e.chips.map(r=>t.jsx("span",{style:et,children:r},r))]})]})}function ni({story:e,onEvidence:r,onResearch:a}){return t.jsxs("section",{style:{...Ur,padding:"20px 22px",marginBottom:16},"aria-label":"Business Story",children:[t.jsxs("div",{style:ea,children:[t.jsx("div",{style:ta,children:t.jsx(Re,{size:15,strokeWidth:2.2})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:ra,children:"Business Story · current filters"}),t.jsx("h2",{style:{...aa,fontSize:19},children:e.headline})]}),t.jsx(ot,{trust:e.trustState})]}),t.jsxs("div",{style:{display:"grid",gap:10,marginTop:12,maxWidth:920},children:[e.paragraphs.slice(0,2).map((i,n)=>t.jsx("p",{style:{...ia,margin:0,fontSize:14,lineHeight:1.65},children:ur(i)},n)),e.implication?t.jsxs("p",{style:{margin:0,fontSize:13,lineHeight:1.55,fontWeight:650},children:["What this means: ",ur(e.implication)]}):null]}),t.jsxs("div",{style:{...sr,marginTop:14},children:[t.jsx("span",{style:na,children:e.generatedBy==="ai"?"AI wording · verified facts":"Verified result summary"}),t.jsxs("span",{style:et,children:[e.evidenceRefs.length," evidence source",e.evidenceRefs.length===1?"":"s"]}),e.caveat?t.jsx("span",{style:et,children:e.caveat}):null,t.jsx("span",{style:{flex:1}}),t.jsx("button",{type:"button",onClick:r,style:zr,children:"View evidence"}),t.jsx("button",{type:"button",onClick:a,style:zr,children:"Research deeper"})]})]})}function li({run:e,variables:r}){const a=e.tiles.filter(n=>n.status!=="ok"),i=Object.entries(r).filter(([,n])=>n!=null&&n!=="");return t.jsxs("details",{style:si,"aria-label":"Evidence and review appendix",children:[t.jsxs("summary",{style:oi,children:["Evidence & review appendix",t.jsxs("span",{style:{opacity:.62,fontWeight:600},children:[e.story.evidenceRefs.length," sources · ",a.length?`${a.length} issue${a.length===1?"":"s"}`:"all visible sources ran"]})]}),t.jsxs("div",{style:{display:"grid",gap:12,padding:"0 16px 16px"},children:[t.jsxs("div",{style:pi,children:[t.jsxs("div",{children:[t.jsx("strong",{children:"Run"}),t.jsx("br",{}),t.jsx("span",{children:e.runId})]}),t.jsxs("div",{children:[t.jsx("strong",{children:"Snapshot"}),t.jsx("br",{}),t.jsx("span",{children:e.snapshotId})]}),t.jsxs("div",{children:[t.jsx("strong",{children:"Trust"}),t.jsx("br",{}),t.jsx("span",{children:e.story.trustState})]}),t.jsxs("div",{children:[t.jsx("strong",{children:"Filters"}),t.jsx("br",{}),t.jsx("span",{children:i.length?i.map(([n,l])=>`${n}: ${String(l)}`).join(" · "):"Current unfiltered scope"})]})]}),t.jsxs("div",{children:[t.jsx("strong",{style:{fontSize:12},children:"Evidence used by the story"}),t.jsx("div",{style:{...sr,marginTop:7},children:e.story.evidenceRefs.map(n=>t.jsx("span",{style:et,children:n},n))})]}),a.length?t.jsxs("div",{children:[t.jsx("strong",{style:{fontSize:12},children:"Items requiring review"}),t.jsx("ul",{style:{margin:"7px 0 0",paddingLeft:18,fontSize:12,lineHeight:1.55},children:a.map(n=>t.jsxs("li",{children:[n.title??n.tileId,": ",n.error??n.status]},n.tileId))})]}):null]})]})}function ur(e){return e.split(/(\*\*[^*]+\*\*)/g).filter(Boolean).map((r,a)=>r.startsWith("**")&&r.endsWith("**")?t.jsx("strong",{children:r.slice(2,-2)},a):r)}const si={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))"},oi={cursor:"pointer",padding:"12px 16px",fontSize:12.5,fontWeight:760,display:"flex",alignItems:"center",justifyContent:"space-between",gap:12},pi={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))"},di={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 ci(e){return`/ask Explain ${e} for a stakeholder. Start with the business meaning, current result, active filters, caveats, and recommended next action.`}function ui({item:e,tile:r,loading:a,error:i,themeMode:n,genUi:l}){var p,d,f,x;if(a&&!r)return t.jsx("span",{children:"Loading data..."});if((r==null?void 0:r.tileType)==="text")return l?t.jsx(hi,{title:e.title??l.insightTitle??"Generated section",markdown:((p=r.text)==null?void 0:p.markdown)??"",genUi:l,themeMode:n}):t.jsx(bi,{markdown:((d=r.text)==null?void 0:d.markdown)??"",variant:((f=r.viz)==null?void 0:f.type)==="heading"?"heading":"text",themeMode:n});if((r==null?void 0:r.tileType)==="aiPin"&&r.aiPin)return t.jsx(vi,{pin:r.aiPin,result:r.result,themeMode:n});if(i&&!r)return t.jsx("span",{children:i});if(!r)return t.jsx("span",{children:"No run result."});if(r.status==="unauthorized")return t.jsx("span",{children:"Not authorized."});if(r.status==="unresolved")return t.jsx("span",{children:r.error??"Block reference unresolved."});if(r.status==="error")return t.jsx("span",{children:r.error??"Tile failed."});if(!r.result)return t.jsx("span",{children:"No result."});const s=Yr(e,r.chartConfig);return String(s.chart??((x=r.viz)==null?void 0:x.type)??"").toLowerCase()==="table"||e.viz.type==="table"||e.viz.type==="pivot"?(l==null?void 0:l.component)==="EvidenceTable"||(l==null?void 0:l.component)==="PivotTable"?t.jsx(mi,{result:r.result,genUi:l,themeMode:n}):t.jsx("div",{style:{width:"100%",alignSelf:"stretch"},children:t.jsx(Aa,{result:r.result,themeMode:n})}):t.jsx("div",{style:{width:"100%",alignSelf:"stretch"},children:t.jsx(Ca,{result:r.result,themeMode:n,chartConfig:s})})}function xi({item:e,cols:r,settingsOpen:a,onToggleSettings:i,onPatch:n}){const[l,s]=u.useState(!1),o=p=>{s(!1),n(oa(e,r,p))};return t.jsxs("div",{style:{display:"flex",gap:4,alignItems:"center",flexWrap:"wrap",justifyContent:"flex-end"},children:[t.jsxs("div",{style:{position:"relative"},children:[t.jsx("button",{type:"button",title:"Choose tile size",onClick:()=>s(p=>!p),style:Et,children:t.jsx(Ra,{size:13,strokeWidth:2})}),l?t.jsx(fi,{onPick:o,onClose:()=>s(!1)}):null]}),t.jsx("button",{type:"button",title:"Chart and field settings",onClick:i,style:Et,children:t.jsx(Ka,{size:13,strokeWidth:2,color:a?"var(--accent, #4f46e5)":void 0})}),t.jsx("button",{type:"button",title:"Remove tile",onClick:()=>n(null),style:Et,children:t.jsx(ya,{size:13,strokeWidth:2})})]})}function fi({onPick:e,onClose:r}){return t.jsx("div",{style:bn,onMouseLeave:r,children:Gr.map(a=>t.jsxs("button",{type:"button",onClick:()=>e(a.id),style:vn,children:[t.jsx("span",{style:{fontSize:12,fontWeight:750},children:a.label}),t.jsx("span",{style:{fontSize:11,opacity:.66},children:a.description})]},a.id))})}function gi({item:e,tile:r,cols:a,onPatch:i}){var $;const n=r==null?void 0:r.result,l=Yr(e,r==null?void 0:r.chartConfig),s=Ze(l.chart),o=Le(e),[p,d]=u.useState(!1),[f,x]=u.useState(null),[c,A]=u.useState(null),S=u.useMemo(()=>$a(n),[n]),q=u.useMemo(()=>{const k=new Map;if(!n)return k;const E=new Set(S.metrics),M=new Set(S.dimensions);for(const I of n.columns)E.has(I)?k.set(I,"measure"):M.has(I)?k.set(I,"dimension"):k.set(I,Sa(za(I,n.rows)));return k},[n,S]),h=(n==null?void 0:n.columns.filter(k=>q.get(k)==="measure"))??[],T=(n==null?void 0:n.columns.filter(k=>q.get(k)!=="measure"))??[],z=k=>{const E=hr({...l,...k}),M=Kt(E.chart),I=Le(e),Q={...E};I&&(Q.dqlGenUi={...I,defaultVisualization:M}),i({title:E.title||e.title,viz:{...e.viz,type:M,options:Q},display:Xr(e,M,I)})},Y=async()=>{d(!0),A(null),x(null);const k=Te(e)??e.title,E=await Z.recommendVisualization({...k?{blockRef:k}:{},resultSchema:n?{columns:n.columns}:void 0,rowSample:n==null?void 0:n.rows.slice(0,5),prompt:[e.title,o==null?void 0:o.rationale].filter(Boolean).join(" "),allowedVisualizations:o==null?void 0:o.allowedVisualizations});if(d(!1),!E.ok){A(E.error);return}const M=Ze(E.display.defaultVisualization),I=Kt(M),Q=E.display.fieldHints??{},re=hr({...l,chart:M,title:l.title??e.title,x:Q.x??Q.label??l.x,y:Q.y??Q.value??l.y,color:Q.color??l.color});i({title:re.title||e.title,viz:{...e.viz,type:I,options:{...re}},display:E.display});const D=E.evidence.map(V=>V.source).slice(0,3).join(", "),_=E.warnings[0];x(_?`${E.display.component}: ${_}`:`${E.display.component}${D?` from ${D}`:""}`)};return t.jsxs("div",{style:Zi,children:[t.jsxs("div",{style:{display:"grid",gap:6},children:[t.jsx("div",{style:{fontSize:10,fontWeight:800,textTransform:"uppercase",opacity:.58},children:"Tile size"}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:Gr.map(k=>t.jsx("button",{type:"button",title:k.description,onClick:()=>i(oa(e,a,k.id)),style:yn(wn(e,a,k.id)),children:k.label},k.id))})]}),t.jsxs("div",{style:Ui,children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:8,justifyContent:"space-between"},children:[t.jsxs("div",{style:{minWidth:0},children:[t.jsx("div",{style:{fontSize:10,fontWeight:800,textTransform:"uppercase",opacity:.58},children:"Display contract"}),t.jsx("div",{style:{marginTop:3,fontSize:11,lineHeight:1.35,opacity:.76},children:(o==null?void 0:o.rationale)??(($=e.display)==null?void 0:$.rationale)??"Choose a governed visualization for this app tile."})]}),t.jsxs("button",{type:"button",onClick:()=>void Y(),disabled:p,style:en(p),title:"Recommend visualization from block hints and result fields",children:[t.jsx(Wr,{size:12,strokeWidth:2.2}),p?"Thinking":"AI recommend"]})]}),t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:5},children:[o!=null&&o.component?t.jsx("span",{style:$e,children:Dr(o)}):null,o!=null&&o.defaultVisualization?t.jsx("span",{style:$e,children:Ae(String(o.defaultVisualization))}):null,o!=null&&o.reviewStatus?t.jsx("span",{style:$e,children:Ae(String(o.reviewStatus))}):null]}),f?t.jsx("div",{style:sa,children:f}):null,c?t.jsx("div",{style:tn,children:c}):null]}),t.jsxs("div",{style:Di,children:[t.jsxs("label",{style:Yt,children:["Title",t.jsx("input",{value:l.title??e.title??"",onChange:k=>z({title:k.target.value||void 0}),style:Xt})]}),t.jsxs("label",{style:Yt,children:["Chart",t.jsx("select",{value:s,onChange:k=>z({chart:k.target.value}),style:Xt,children:ar.map(k=>t.jsx("option",{value:k.value,children:k.label},k.value))})]}),t.jsx(mt,{label:"X",value:l.x,columns:(n==null?void 0:n.columns)??[],onChange:k=>z({x:k})}),t.jsx(mt,{label:"Y",value:l.y,columns:(n==null?void 0:n.columns)??[],onChange:k=>z({y:k})}),t.jsx(mt,{label:"Color",value:l.color,columns:(n==null?void 0:n.columns)??[],onChange:k=>z({color:k})}),t.jsx(mt,{label:"Facet",value:l.facet,columns:(n==null?void 0:n.columns)??[],onChange:k=>z({facet:k})})]}),n?t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[t.jsx(xr,{title:"Measures",columns:h,onPick:k=>z({y:k})}),t.jsx(xr,{title:"Dimensions",columns:T,onPick:k=>z({x:k})})]}):t.jsx("div",{style:{fontSize:11,opacity:.64},children:"Run results are needed before field slots can be inferred."})]})}function mt({label:e,value:r,columns:a,onChange:i}){return t.jsxs("label",{style:Yt,children:[e,t.jsxs("select",{value:r??"",onChange:n=>i(n.target.value||void 0),style:Xt,children:[t.jsx("option",{value:"",children:"Auto"}),a.map(n=>t.jsx("option",{value:n,children:n},n))]})]})}function xr({title:e,columns:r,onPick:a}){return t.jsxs("div",{style:{display:"grid",gap:4,minWidth:0},children:[t.jsx("div",{style:{fontSize:10,fontWeight:800,textTransform:"uppercase",opacity:.58},children:e}),t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:4},children:r.length===0?t.jsx("span",{style:{fontSize:11,opacity:.55},children:"None"}):r.slice(0,10).map(i=>t.jsx("button",{type:"button",onClick:()=>a(i),style:rn,children:i},i))})]})}function fr({open:e,onToggle:r,onCertifiedBlock:a,onText:i,onHeading:n,onAi:l,buttonLabel:s,buttonStyle:o}){return t.jsxs("div",{style:{position:"relative",display:"inline-flex"},children:[t.jsxs("button",{type:"button",onClick:r,title:"Add tile",style:o??Ue(e),children:[t.jsx(kt,{size:15,strokeWidth:2.2}),s?t.jsx("span",{children:s}):null]}),e&&t.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:[t.jsx(bt,{title:"Certified block",description:"Chart, table, or KPI from this App domain",onClick:a}),t.jsx(bt,{title:"Text / summary",description:"Narrative, notes, caveats, or CXO context",onClick:i}),t.jsx(bt,{title:"Section heading",description:"Separate an App page into readable groups",onClick:n}),t.jsx(bt,{title:"Copilot insight",description:"Open scoped AI, then pin the reviewed answer to this App",onClick:l})]})]})}function bt({title:e,description:r,onClick:a}){return t.jsxs("button",{type:"button",onClick:a,style:Ji,children:[t.jsx("span",{style:{fontSize:12,fontWeight:700},children:e}),t.jsx("span",{style:{fontSize:11,opacity:.66},children:r})]})}function hi({title:e,markdown:r,genUi:a,themeMode:i}){var p;const n=Ne[i],l=Wi(r,e),s=a.component==="TrustCallout",o=a.component==="ResearchActions";return t.jsxs("div",{style:on(s),children:[t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"flex-start"},children:[t.jsx("span",{style:pn(s),children:s?t.jsx(Qe,{size:15}):o?t.jsx(Re,{size:15}):t.jsx(We,{size:15})}),t.jsxs("div",{style:{flex:1,minWidth:0},children:[t.jsx("div",{style:{fontSize:13,fontWeight:780,lineHeight:1.25},children:a.insightTitle??e}),t.jsx("div",{style:{marginTop:6,fontSize:13,lineHeight:1.45,color:n.textSecondary},children:l})]})]}),t.jsxs("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:[a.trustState?t.jsx(ot,{trust:a.trustState}):null,a.reviewStatus?t.jsx("span",{style:$e,children:Ae(a.reviewStatus)}):null]}),(p=a.followUpActions)!=null&&p.length?t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:6},children:a.followUpActions.slice(0,3).map(d=>t.jsx("span",{style:dn,children:Ae(d)},d))}):null]})}function mi({result:e,genUi:r,themeMode:a}){var x;const i=Ne[a],n=e.rows??[],l=e.columns??[],s=Vi(l,n,(x=r.fieldHints)==null?void 0:x.label),o=l.find(c=>/\b(status|quality|trust|certification|review)\b/i.test(c)),p=l.filter(c=>c!==s&&c!==o).filter(c=>Lt(c)<90||De(c,n)).sort((c,A)=>Lt(c)-Lt(A)).slice(0,2),d=l.filter(c=>c!==s&&c!==o&&!p.includes(c)).slice(0,2),f=e.rowCount??n.length;return t.jsxs("div",{style:cn,children:[t.jsxs("div",{style:{fontSize:11.5,color:i.textSecondary},children:[f," ",f===1?"row":"rows"," across ",l.length," ",l.length===1?"field":"fields"]}),t.jsx("div",{style:un,children:n.slice(0,4).map((c,A)=>{const S=s?Pe(c[s]):`Row ${A+1}`,q=o?Pe(c[o]):null;return t.jsxs("div",{style:xn,children:[t.jsxs("div",{style:{minWidth:0},children:[t.jsx("div",{style:{fontSize:12.5,fontWeight:760,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:S}),d.length?t.jsx("div",{style:{display:"flex",flexWrap:"wrap",gap:5,marginTop:4},children:d.map(h=>t.jsxs("span",{style:fn,children:[Ae(h),": ",Pe(c[h])]},h))}):null]}),t.jsxs("div",{style:{display:"flex",gap:5,flexWrap:"wrap",justifyContent:"flex-start",minWidth:0},children:[p.map(h=>t.jsxs("span",{style:gn,children:[t.jsx("span",{style:{opacity:.62},children:Ae(h)}),t.jsx("strong",{children:Pe(c[h])})]},h)),q?t.jsx("span",{style:hn,children:q}):null]})]},A)})}),n.length>4?t.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 bi({markdown:e,variant:r="text",themeMode:a}){const i=Ne[a];return t.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:Fr(e,i)})}function vi({pin:e,result:r,themeMode:a}){var p;const[i,n]=u.useState(null),l=Ne[a]??Ne.light,s=async()=>{n("Refreshing...");const d=await Z.refreshAiPin(e.appId,e.id);n(d.ok?"Refreshed.":d.error??"Refresh failed."),window.dispatchEvent(new CustomEvent("dql-app-dashboard-updated",{detail:{appId:e.appId,dashboardId:e.dashboardId}}))},o=async()=>{n("Creating draft...");const d=await Z.promoteAiPin(e.appId,e.id);n(d.ok?`Draft created: ${d.blockPath}`:d.error??"Promotion failed."),window.dispatchEvent(new CustomEvent("dql-app-dashboard-updated",{detail:{appId:e.appId,dashboardId:e.dashboardId}}))};return t.jsxs("div",{style:{width:"100%",alignSelf:"stretch",overflow:"auto",fontStyle:"normal",lineHeight:1.5,display:"grid",gap:10},children:[t.jsxs("div",{style:{display:"flex",gap:6,alignItems:"center",flexWrap:"wrap"},children:[t.jsx("span",{style:{fontSize:10.5,fontWeight:800,color:e.certification==="certified"?"#15803d":"#b45309",background:e.certification==="certified"?"rgba(22,163,74,0.1)":"rgba(245,158,11,0.12)",border:`1px solid ${e.certification==="certified"?"rgba(22,163,74,0.22)":"rgba(245,158,11,0.24)"}`,borderRadius:999,padding:"3px 7px"},children:e.certification==="certified"?"Certified":"Review required"}),t.jsx("span",{style:{fontSize:10.5,color:"var(--color-text-muted, rgba(0,0,0,0.58))"},children:"Pinned report insight"})]}),t.jsx("div",{style:{minWidth:0},children:Fr(e.answer,l)}),(p=r==null?void 0:r.rows)!=null&&p.length?t.jsx(yi,{result:r}):null,t.jsxs("div",{style:{display:"flex",gap:6,marginTop:8,flexWrap:"wrap"},children:[e.sql&&t.jsx("button",{type:"button",onClick:()=>void s(),style:Cr,children:"Refresh"}),e.sql&&e.reviewStatus==="needs_review"&&t.jsx("button",{type:"button",onClick:()=>void o(),style:Cr,children:"Promote"}),e.refreshCadence==="daily"&&t.jsx("span",{style:{fontSize:11,opacity:.62},children:"daily"})]}),i&&t.jsx("div",{style:{marginTop:6,fontSize:11,opacity:.72},children:i}),e.lastRefreshError&&t.jsx("div",{style:{marginTop:8,color:"#f85149"},children:e.lastRefreshError})]})}function yi({result:e}){var i,n;const r=((i=e.columns)!=null&&i.length?e.columns:Object.keys(((n=e.rows)==null?void 0:n[0])??{})).slice(0,4),a=(e.rows??[]).slice(0,3);return!r.length||!a.length?null:t.jsxs("div",{style:{display:"grid",gap:6},children:[t.jsx("div",{style:{color:"var(--color-text-muted, rgba(0,0,0,0.58))",fontSize:11,fontWeight:750},children:"Supporting rows"}),t.jsx("div",{style:{overflow:"auto",border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6},children:t.jsxs("table",{style:{width:"100%",borderCollapse:"collapse",fontSize:11},children:[t.jsx("thead",{children:t.jsx("tr",{children:r.map(l=>t.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:Ae(l)},l))})}),t.jsx("tbody",{children:a.map((l,s)=>t.jsx("tr",{children:r.map(o=>t.jsx("td",{style:{padding:"5px 7px",borderBottom:s===a.length-1?"none":"1px solid var(--border-color, rgba(0,0,0,0.06))"},children:Pe(l[o])},o))},s))})]})})]})}function qi({kind:e,value:r,onChange:a,onClose:i,onSave:n}){const l=e==="heading";return t.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:t.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:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:16,fontWeight:800},children:l?"Add heading":"Add text tile"}),t.jsx("div",{style:{fontSize:12,opacity:.65,marginTop:4},children:l?"Create a section heading on this dashboard page.":"Create a narrative text tile on this dashboard page."})]}),l?t.jsx("input",{value:r,onChange:s=>a(s.target.value),onKeyDown:s=>{s.key==="Enter"&&n(),s.key==="Escape"&&i()},placeholder:"Executive summary",autoFocus:!0,style:Ar}):t.jsx("textarea",{value:r,onChange:s=>a(s.target.value),onKeyDown:s=>{s.key==="Escape"&&i(),s.key==="Enter"&&(s.metaKey||s.ctrlKey)&&n()},placeholder:"Add context, assumptions, or decisions...",rows:6,autoFocus:!0,style:{...Ar,resize:"vertical",lineHeight:1.45}}),t.jsxs("div",{style:{display:"flex",justifyContent:"flex-end",gap:8},children:[t.jsx("button",{type:"button",onClick:i,style:Ue(!1),children:"Cancel"}),t.jsx("button",{type:"button",onClick:n,disabled:!r.trim(),style:{...la,opacity:r.trim()?1:.65},children:"Add"})]})]})})}function wi({blocks:e,search:r,onSearch:a,onClose:i,onAdd:n}){const l=e.filter(s=>{const o=r.trim().toLowerCase();return o?[s.name,s.description,s.domain,...s.tags??[]].join(" ").toLowerCase().includes(o):!0});return t.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:t.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:[t.jsxs("div",{style:{padding:14,borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.1))",display:"flex",gap:10,alignItems:"center"},children:[t.jsx("div",{style:{fontSize:15,fontWeight:700,flex:1},children:"Add Certified Block"}),t.jsx("button",{type:"button",onClick:i,style:Ue(!1),children:"Close"})]}),t.jsx("div",{style:{padding:14,borderBottom:"1px solid var(--border-color, rgba(0,0,0,0.08))"},children:t.jsx("input",{value:r,onChange:s=>a(s.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"}})}),t.jsx("div",{style:{overflow:"auto",padding:12,display:"grid",gap:8},children:l.length===0?t.jsx("div",{style:{padding:18,fontSize:12,opacity:.66},children:"No certified blocks match this App scope."}):l.map(s=>t.jsxs("button",{type:"button",onClick:()=>n(s),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:[t.jsxs("div",{style:{display:"flex",gap:8,alignItems:"center",marginBottom:4},children:[t.jsx("span",{style:{fontSize:13,fontWeight:700},children:s.name}),t.jsx("span",{style:{fontSize:10,padding:"2px 6px",borderRadius:999,background:"rgba(63,185,80,0.14)",color:"#2ea043"},children:s.status}),t.jsx("span",{style:{fontSize:10,opacity:.68},children:s.domain}),t.jsx("span",{style:{fontSize:10,opacity:.68},children:s.chartType??"table"})]}),t.jsx("div",{style:{fontSize:12,opacity:.72},children:s.description||s.path})]},s.id))})]})})}function ji({lineage:e}){var n,l;const r=((n=e==null?void 0:e.graph)==null?void 0:n.nodes)??[],a=((l=e==null?void 0:e.graph)==null?void 0:l.edges)??[],i=(e==null?void 0:e.breadcrumbs)??[];return t.jsxs("div",{style:{display:"flex",flexDirection:"column",gap:12},children:[t.jsxs("div",{children:[t.jsx("div",{style:{fontSize:12,fontWeight:800,textTransform:"uppercase",opacity:.62,marginBottom:6},children:"App Lineage"}),t.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&&t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:i.map((s,o)=>t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"64px 1fr",gap:8,fontSize:12},children:[t.jsx("span",{style:{fontFamily:"monospace",opacity:.6},children:s.type}),t.jsx("span",{children:s.name})]},`${s.id}-${o}`))}),t.jsxs("div",{style:{display:"grid",gridTemplateColumns:"1fr 1fr",gap:8},children:[t.jsx(gr,{label:"Nodes",value:r.length}),t.jsx(gr,{label:"Edges",value:a.length})]}),t.jsx("div",{style:{display:"flex",flexDirection:"column",gap:6},children:r.slice(0,18).map(s=>t.jsxs("div",{style:{border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6,padding:8},children:[t.jsxs("div",{style:{display:"flex",alignItems:"center",gap:6,minWidth:0},children:[t.jsx("span",{style:{color:"#0d1117",background:ba[s.type]??"#8b949e",borderRadius:3,padding:"1px 4px",fontSize:9,fontWeight:800,flexShrink:0},children:ma[s.type]??s.type.slice(0,4).toUpperCase()}),t.jsx("div",{style:{fontSize:12,fontWeight:700,overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},children:s.name})]}),t.jsxs("div",{style:{fontSize:11,opacity:.62,fontFamily:"monospace",marginTop:4},children:[va[s.type]??s.type," · ",s.id]})]},s.id))})]})}function gr({label:e,value:r}){return t.jsxs("div",{style:{border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6,padding:8},children:[t.jsx("div",{style:{fontSize:11,opacity:.62},children:e}),t.jsx("div",{style:{fontSize:18,fontWeight:800},children:r})]})}function Te(e){return e.block?"blockId"in e.block?e.block.blockId??null:e.block.ref??null:null}function Yr(e,r){const a=e.viz.options??{};return{...r??{},...a,chart:Ze(String(a.chart??(r==null?void 0:r.chart)??e.viz.type)),title:a.title??(r==null?void 0:r.title)??e.title,colorPalette:a.colorPalette??(r==null?void 0:r.colorPalette)??"corporate"}}function Ze(e){const r=String(e??"table").toLowerCase().replace(/_/g,"-");return r==="single-value"?"kpi":ar.some(a=>a.value===r)?r:"table"}function Kt(e){const r=Ze(e);return r==="table"?"table":r.replace(/-/g,"_")}function hr(e){const r={};for(const[a,i]of Object.entries(e))i===void 0||i===""||(r[a]=i);return r.chart||(r.chart="table"),r}function Le(e){var a;if(yt(e.display)){const i=e.display,n=typeof i.component=="string"?i.component:void 0;return{version:1,component:n,role:Jr(n),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(l=>typeof l=="string"):void 0,fieldHints:yt(i.fieldHints)?Object.fromEntries(Object.entries(i.fieldHints).filter(l=>typeof l[1]=="string")):void 0,insightTitle:e.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=e.viz.options)==null?void 0:a.dqlGenUi;return yt(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:yt(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 mr(e,r){return{mode:"manual",component:e==="heading"?"NarrativePanel":"BusinessBrief",defaultVisualization:e,allowedVisualizations:[e],layoutIntent:e==="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 Xr(e,r,a){var l,s,o,p,d,f,x,c,A;const i=ki([r,...((l=e.display)==null?void 0:l.allowedVisualizations)??[],...(a==null?void 0:a.allowedVisualizations)??[]]),n=((s=e.display)==null?void 0:s.component)??Si(r);return{mode:((o=e.display)==null?void 0:o.mode)??(a?"ai_generated":e.block?"block_hint":"manual"),component:n,defaultVisualization:r,allowedVisualizations:i.length?i:[r],...(p=e.display)!=null&&p.fieldHints||a!=null&&a.fieldHints?{fieldHints:((d=e.display)==null?void 0:d.fieldHints)??(a==null?void 0:a.fieldHints)}:{},layoutIntent:Ei(((f=e.display)==null?void 0:f.layoutIntent)??(a==null?void 0:a.layoutIntent)),rationale:((x=e.display)==null?void 0:x.rationale)??(a==null?void 0:a.rationale)??"Visualization selected for this consumer surface.",trustState:lr(((c=e.display)==null?void 0:c.trustState)??(a==null?void 0:a.trustState)),reviewStatus:_i(((A=e.display)==null?void 0:A.reviewStatus)??(a==null?void 0:a.reviewStatus))}}function ki(e){return Array.from(new Set(e.filter(r=>typeof r=="string"&&r.trim()).map(r=>r.trim())))}function Si(e){return e==="single_value"||e==="kpi"||e==="gauge"?"KpiMetric":e==="line"||e==="area"?"TrendPanel":e==="bar"||e==="grouped_bar"||e==="stacked_bar"||e==="donut"||e==="pie"?"RankingPanel":e==="pivot"?"PivotTable":e==="text"||e==="heading"?"NarrativePanel":"EvidenceTable"}function Jr(e){return e==="BusinessBrief"?"business_summary":e==="KpiMetric"?"kpi":e==="TrendPanel"?"trend":e==="RankingPanel"?"breakdown":e==="TrustCallout"?"trust":e==="ResearchActions"?"research":e==="NarrativePanel"?"narrative":e?"evidence":void 0}function zi(e){var s,o,p,d;if(Te(e)||e.aiPin)return!1;const r=Le(e),a=(r==null?void 0:r.component)??((s=e.display)==null?void 0:s.component),i=(r==null?void 0:r.role)??Jr(a),n=lr(String((r==null?void 0:r.trustState)??((o=e.display)==null?void 0:o.trustState)??"review_required"));if(a==="TrustCallout"||a==="ResearchActions"||i==="trust"||i==="research")return!0;if(a!=="NarrativePanel"&&a!=="BusinessBrief"||n==="certified")return!1;const l=[e.title,(p=e.text)==null?void 0:p.markdown,(d=e.display)==null?void 0:d.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(l)}function Ai(e,r,a){const n=[...e.filter(l=>!Ci(l,r.get(l.i))&&!Ti(l,e,r)&&!Ni(l,e,r))].sort((l,s)=>{const o=vr(s,r.get(s.i),a)-vr(l,r.get(l.i),a);return o!==0?o:Ke(l,a)-Ke(s,a)});return wt(n,a)}function Ci(e,r){var n,l;if(!e.aiPin)return!1;const a=(n=r==null?void 0:r.aiPin)==null?void 0:n.certification,i=(l=r==null?void 0:r.aiPin)==null?void 0:l.reviewStatus;return a!=="certified"&&i!=="certified"}function Ni(e,r,a){if(!e.aiPin)return!1;const i=br(e,a.get(e.i));if(!i)return!1;const n=r.findIndex(l=>l.i===e.i);return r.some((l,s)=>l.i===e.i||s>=n||!l.aiPin?!1:br(l,a.get(l.i))===i)}function br(e,r){const a=r==null?void 0:r.aiPin,i=a!=null&&a.analysisPlan&&typeof a.analysisPlan=="object"?a.analysisPlan:null,n=vt(a==null?void 0:a.question)||vt(e.title),l=vt(i==null?void 0:i.sourceBlockId),s=vt(i==null?void 0:i.sourceTileId),o=a!=null&&a.result?Ii(a.result):"";return!n&&!l&&!s?"":[n,l,s,o].filter(Boolean).join("|")}function vt(e){return String(e??"").toLowerCase().replace(/[^a-z0-9]+/g," ").replace(/\s+/g," ").trim()}function Ii(e){if(!e||typeof e!="object")return"";const r=e,a=Array.isArray(r.columns)?r.columns.map(n=>String(n).toLowerCase()).join(","):"",i=Array.isArray(r.rows)?r.rows.slice(0,8).map(n=>Gt(n)).join(";"):"";return a||i?`${a}:${i}`:""}function Gt(e){if(e==null)return"";if(typeof e!="object")return String(e);if(Array.isArray(e))return`[${e.map(Gt).join(",")}]`;const r=e;return`{${Object.keys(r).sort().map(a=>`${a}:${Gt(r[a])}`).join(",")}}`}function vr(e,r,a){var n,l,s,o,p;let i=0;return(n=e.parameterBindings)!=null&&n.length&&(i+=5e3),(s=(l=r==null?void 0:r.filters)==null?void 0:l.applied)!=null&&s.length&&(i+=4e3),(r==null?void 0:r.certificationStatus)==="certified"&&(i+=1800),Te(e)&&(i+=900),(r==null?void 0:r.status)==="ok"&&((p=(o=r.result)==null?void 0:o.rows)!=null&&p.length)&&(i+=500),i-=Jt(e)*80,i-=Ke(e,a)/1e3,i}function Ti(e,r,a){var l;if((l=e.parameterBindings)!=null&&l.length||e.aiPin||!Te(e))return!1;const i=a.get(e.i),n=i!=null&&i.result?yr(i.result):null;return n?r.some(s=>{if(s.i===e.i||!$i(s,a.get(s.i)))return!1;const o=a.get(s.i),p=o!=null&&o.result?yr(o.result):null;return!!(p&&Pi(n,p))}):!1}function $i(e,r){var a,i,n;return!!((a=e.parameterBindings)!=null&&a.length||(n=(i=r==null?void 0:r.filters)==null?void 0:i.applied)!=null&&n.length)}function yr(e){var s;const r=e.rows??[];if(!r.length)return null;const a=(s=e.columns)!=null&&s.length?e.columns:Object.keys(r[0]??{});if(!a.length)return null;const i=ir(a,r),n=nr(a,r),l=r[0];return{columns:a.map(o=>o.toLowerCase()).sort().join("|"),label:i?qr(l[i]):"",metric:(n==null?void 0:n.toLowerCase())??"",metricValue:n?qr(l[n]):""}}function Pi(e,r){return e.columns===r.columns&&e.label===r.label&&e.metric===r.metric&&e.metricValue===r.metricValue}function qr(e){return e==null?"":typeof e=="number"?Number.isFinite(e)?String(e):"":String(e).trim().toLowerCase().replace(/\s+/g," ")}function Ri(e,r,a){var I,Q,re,D;const i=e.map((_,V)=>({item:_,tile:r.get(_.i),index:V})).filter(_=>{var V,W;return((V=_.tile)==null?void 0:V.status)==="ok"&&!!_.tile.result&&Array.isArray((W=_.tile.result)==null?void 0:W.rows)&&_.tile.result.rows.length>0}).sort((_,V)=>{const W=wr(_.item,_.tile,_.index);return wr(V.item,V.tile,V.index)-W})[0];if(!(i!=null&&i.tile.result))return null;const n=i.tile.result,l=n.rows,s=n.columns??Object.keys(l[0]??{});if(!s.length)return null;const o=Le(i.item),p=ir(s,l,(I=o==null?void 0:o.fieldHints)==null?void 0:I.label),d=nr(s,l,((Q=o==null?void 0:o.fieldHints)==null?void 0:Q.value)??((re=o==null?void 0:o.fieldHints)==null?void 0:re.y)),f=l[0],x=l[1],c=p?Pe(f[p]):"The leading result",A=x&&p?Pe(x[p]):null,S=d?Sr(f[d]):null,q=d&&x?Sr(x[d]):null,h=d?Bi(d):null,T=Li(a),z=T.length?"under the selected app filters":"in the current dashboard view",Y=i.item.title??i.tile.title??Te(i.item)??"Dashboard result",$=n.rowCount??l.length,k=i.tile.certificationStatus==="certified"?"certified":lr(String(((D=i.item.display)==null?void 0:D.trustState)??(o==null?void 0:o.trustState)??"review_required")),E=h?`${Ae(h)} snapshot`:"Dashboard snapshot";let M;if(h&&S!==null){const _=`${c} leads ${h} with ${Pe(S)}`;if(A&&q!==null&&Number.isFinite(S-q)){const V=Math.abs(S-q);M=`${_}, ahead of ${A} by ${Pe(V)} ${z}.`}else M=`${_} ${z}.`}else M=`${Y} returned ${$} ${$===1?"row":"rows"} ${z}.`;return{title:E,summary:M,sourceTitle:Y,trust:k,filters:T,chips:[`${$} ${$===1?"row":"rows"}`,s.length?`${s.length} fields`:""].filter(Boolean)}}function wr(e,r,a){var o,p,d,f;const i=Le(e),n=(i==null?void 0:i.component)??((o=e.display)==null?void 0:o.component),l=r.result;let s=1e3-a;return r.certificationStatus==="certified"&&(s+=500),Te(e)&&(s+=180),(d=(p=r.filters)==null?void 0:p.applied)!=null&&d.length&&(s+=260),(f=e.parameterBindings)!=null&&f.length&&(s+=220),(n==="RankingPanel"||n==="EvidenceTable"||n==="KpiMetric")&&(s+=120),(e.viz.type==="table"||e.viz.type==="bar"||e.viz.type==="kpi")&&(s+=70),l&&nr(l.columns,l.rows)&&(s+=80),l&&ir(l.columns,l.rows)&&(s+=50),s}function ir(e,r,a){const i=Zr(e,a);return i||(e.find(n=>/\b(player|customer|account|team|segment|category|name|label|title|entity)\b/i.test(n))??e.find(n=>!De(n,r)&&!/\b(date|time|year|month|id)\b/i.test(n))??e.find(n=>!De(n,r)))}function nr(e,r,a){const i=Zr(e,a);return i&&De(i,r)?i:e.filter(n=>De(n,r)).sort((n,l)=>jr(n)-jr(l))[0]}function Zr(e,r){const a=r==null?void 0:r.toLowerCase().trim();if(a)return e.find(i=>{const n=i.toLowerCase();return n===a||n.includes(a)||a.includes(n)})}function jr(e){const r=e.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 Bi(e){return Ae(e).toLowerCase()}function Li(e){return Object.entries(e).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:Ae(r),value:Array.isArray(a)?a.map(i=>kr(r,i)).join(", "):kr(r,a)}))}function kr(e,r){const a=typeof r=="number"?r:typeof r=="string"&&r.trim()!==""?Number(r):NaN;return/(season|year)/i.test(e)&&Number.isInteger(a)&&a>=1900&&a<=2200?String(a):Pe(r)}function Sr(e){if(typeof e=="number"&&Number.isFinite(e))return e;if(typeof e=="string"&&e.trim()!==""){const r=Number(e);return Number.isFinite(r)?r:null}return null}function Ei(e){return e==="compact"||e==="standard"||e==="wide"||e==="tall"||e==="full"||e==="auto"?e:"auto"}function lr(e){return e==="certified"||e==="draft_ready"||e==="review_required"?e:"review_required"}function _i(e){return e==="certified"||e==="draft_ready"||e==="review_required"?e:"review_required"}function yt(e){return typeof e=="object"&&e!==null&&!Array.isArray(e)}function Mi(e,r){const a=new Set([String(e.viz.type??"table"),...(r==null?void 0:r.allowedVisualizations)??[]]),i=Array.from(a).map(n=>Ze(n)).filter((n,l,s)=>s.indexOf(n)===l);return i.map(n=>ar.find(l=>l.value===n)??{value:n,label:Ae(n)}).filter(n=>n.value!=="table"||i.length===1||e.block)}function Oi(e){return e==="TrustCallout"?"linear-gradient(180deg, rgba(255,255,255,0.92), rgba(255,251,235,0.72))":e==="RankingPanel"||e==="TrendPanel"||e==="PivotTable"?"linear-gradient(180deg, rgba(255,255,255,0.96), rgba(248,250,252,0.86))":e==="BusinessBrief"?"var(--dql-app-surface, rgba(255,255,255,0.90))":"var(--dql-app-surface, var(--surface, rgba(255,255,255,0.84)))"}function Fi(e){return e==="line"||e==="area"?t.jsx(rr,{size:13,strokeWidth:2.2}):e==="pie"||e==="donut"?t.jsx(Oa,{size:13,strokeWidth:2.2}):e==="table"?t.jsx(Ja,{size:13,strokeWidth:2.2}):t.jsx(Kr,{size:13,strokeWidth:2.2})}function Ae(e){return e.replace(/[_-]+/g," ").replace(/\b\w/g,r=>r.toUpperCase())}function Dr(e){switch(e.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 e.role?Ae(e.role):"Generated"}}function Wi(e,r){const a=new RegExp(`^###\\s*${Hi(r)}\\s*`,"i");return e.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(l=>l.trim()).find(Boolean)||"Generated app section pending analyst review."}function Vi(e,r,a){if(e.length===0)return;const i=a==null?void 0:a.toLowerCase();if(i){const n=e.find(l=>{const s=l.toLowerCase();return s===i||s.includes(i)||i.includes(s)});if(n)return n}return e.find(n=>/\b(name|label|title|dataset|table|block|player|customer|account)\b/i.test(n))??e.find(n=>!De(n,r))??e[0]}function Lt(e){const r=e.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 De(e,r){const a=r.slice(0,8).map(i=>i[e]).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 Pe(e){if(e==null||e==="")return"N/A";if(typeof e=="number")return Number.isFinite(e)?new Intl.NumberFormat("en-US",{maximumFractionDigits:2}).format(e):String(e);if(typeof e=="boolean")return e?"Yes":"No";const r=String(e),a=Number(r);return r.trim()!==""&&Number.isFinite(a)&&/^-?\d+(\.\d+)?$/.test(r.trim())?new Intl.NumberFormat("en-US",{maximumFractionDigits:2}).format(a):r.replace(/_/g," ")}function Hi(e){return e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}function Ue(e){return{border:"1px solid var(--dql-app-line, var(--border-color, rgba(0,0,0,0.12)))",borderRadius:8,background:e?"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}}function Qi(e){return{...Ue(e),width:34,height:34,padding:0,justifyContent:"center"}}const Ki={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"},Gi={display:"flex",alignItems:"center",gap:6,marginBottom:10},Yi={marginBottom:12,color:"var(--dql-app-muted, var(--color-text-secondary, rgba(0,0,0,0.64)))",fontSize:12,lineHeight:1.45},Ur={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},ea={display:"flex",alignItems:"flex-start",gap:10,minWidth:0},ta={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},ra={fontSize:10.5,fontWeight:820,letterSpacing:0,textTransform:"uppercase",color:"var(--dql-app-muted, rgba(15,23,42,0.58))"},aa={margin:"2px 0 0",fontSize:15,lineHeight:1.25,fontWeight:820,color:"var(--dql-app-text, inherit)"},ia={margin:0,fontSize:13.5,lineHeight:1.48,color:"var(--dql-app-muted, rgba(15,23,42,0.72))"},sr={display:"flex",alignItems:"center",gap:6,flexWrap:"wrap"},et={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"},na={...et,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))"},zr={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 Xi(e){return{position:"fixed",right:24,top:76,bottom:24,zIndex:70,width:e?`min(${Qt}px, calc(100vw - 96px))`:`min(${ja}px, calc(100vw - 64px))`,minWidth:0}}const Ar={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"},la={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},Ji={border:"none",borderRadius:6,background:"transparent",color:"inherit",padding:"9px 10px",cursor:"pointer",textAlign:"left",display:"grid",gap:2},Zi={border:"1px solid var(--border-color, rgba(0,0,0,0.10))",borderRadius:6,padding:8,background:"var(--color-bg, rgba(255,255,255,0.72))",display:"grid",gap:8,fontStyle:"normal"},Di={display:"grid",gridTemplateColumns:"repeat(4, minmax(0, 1fr))",gap:6},Yt={display:"grid",gap:3,fontSize:10,fontWeight:700,opacity:.78},Xt={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},Ui={display:"grid",gap:6,border:"1px solid var(--border-color, rgba(0,0,0,0.08))",borderRadius:6,background:"var(--surface, rgba(248,250,252,0.62))",padding:8};function en(e){return{border:"1px solid var(--accent, rgba(79,70,229,0.55))",background:e?"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:e?"wait":"pointer",opacity:e?.72:1,whiteSpace:"nowrap"}}const sa={fontSize:11,lineHeight:1.35,color:"var(--dql-app-muted, rgba(15,23,42,0.68))"},tn={...sa,color:"var(--error-color, #b91c1c)"},rn={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"},an={marginTop:7,display:"flex",flexWrap:"wrap",gap:5,alignItems:"center",minWidth:0},$e={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 nn(e){return{...$e,border:e?"1px solid rgba(22,163,74,0.26)":"1px solid rgba(217,119,6,0.28)",background:e?"rgba(22,163,74,0.10)":"rgba(245,158,11,0.12)",color:e?"#15803d":"#b45309",gap:4}}const ln={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 sn(e){return{width:24,height:24,border:"none",borderRadius:4,background:e?"var(--dql-app-accent, var(--accent, #4f46e5))":"transparent",color:e?"var(--color-text-on-accent, #fff)":"inherit",cursor:"pointer",display:"inline-flex",alignItems:"center",justifyContent:"center",padding:0}}function on(e){return{width:"100%",alignSelf:"stretch",overflow:"auto",display:"flex",flexDirection:"column",gap:10,fontStyle:"normal",opacity:1,lineHeight:1.45,borderRadius:6,padding:e?10:0,background:e?"rgba(245,158,11,0.08)":"transparent"}}function pn(e){return{width:30,height:30,borderRadius:7,display:"inline-flex",alignItems:"center",justifyContent:"center",flexShrink:0,background:e?"rgba(245,158,11,0.14)":"rgba(79,70,229,0.10)",color:e?"#b45309":"var(--dql-app-accent, var(--accent, #4f46e5))"}}const dn={...$e,background:"rgba(79,70,229,0.08)",color:"var(--dql-app-accent, var(--accent, #4f46e5))",border:"1px solid rgba(79,70,229,0.16)"},cn={width:"100%",alignSelf:"stretch",overflow:"auto",display:"flex",flexDirection:"column",gap:9,fontStyle:"normal",opacity:1,lineHeight:1.35},un={display:"grid",gap:6},xn={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"},fn={...$e,minHeight:16,borderRadius:5,padding:"1px 5px",maxWidth:"100%",overflow:"hidden",textOverflow:"ellipsis",whiteSpace:"nowrap"},gn={display:"grid",gap:1,minWidth:82,textAlign:"left",fontSize:10.5},hn={...$e,minHeight:18,background:"rgba(22,163,74,0.09)",border:"1px solid rgba(22,163,74,0.18)",color:"#15803d"},Et={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"},mn={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},bn={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},vn={border:"none",borderRadius:6,background:"transparent",color:"inherit",padding:"8px 9px",cursor:"pointer",textAlign:"left",display:"grid",gap:2};function yn(e){return{border:`1px solid ${e?"var(--accent, #4f46e5)":"var(--border-color, rgba(0,0,0,0.12))"}`,borderRadius:999,background:e?"var(--color-bg-active, rgba(79,70,229,0.12))":"var(--surface, rgba(0,0,0,0.02))",color:e?"var(--accent, #4f46e5)":"inherit",padding:"4px 8px",fontSize:11,fontWeight:e?750:600,cursor:"pointer"}}const Cr={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 or(e,r){const a=dt(e);return a==="heading"?Ie("wide",r,"heading"):a==="text"?Ie("standard",r,"text"):Ie(a==="single_value"||a==="kpi"||a==="gauge"?"compact":a==="table"||a==="pivot"?"tall":a==="line"||a==="area"?"wide":"standard",r,a)}function pr(e,r){const a=Le(e),i=jn(a==null?void 0:a.layoutIntent);return i&&i!=="auto"?Ie(i,r,String(e.viz.type??"table")):or(dt(String(e.viz.type??"table")),r)}function qn(e,r){return e.viz.type==="heading"?90:(r==null?void 0:r.component)==="BusinessBrief"||(r==null?void 0:r.component)==="NarrativePanel"||e.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,e.h*76))}function Ie(e,r,a="table"){const i=Math.max(1,r),n=Math.max(1,Math.ceil(i/2)),l=Math.max(1,Math.ceil(i/3));return e==="auto"?or(a,i):e==="compact"?{w:l,h:2}:e==="wide"?{w:i,h:a==="heading"?1:4}:e==="tall"?{w:n,h:6}:e==="full"?{w:i,h:7}:{w:n,h:a==="text"?2:4}}function oa(e,r,a){const i=String(e.viz.type??"table"),n=a==="auto"?pr(e,r):Ie(a,r,i);return{w:n.w,h:n.h,x:St(e.x,0,Math.max(0,r-n.w))}}function wn(e,r,a){const i=a==="auto"?pr(e,r):Ie(a,r,String(e.viz.type??"table"));return e.w===i.w&&e.h===i.h}function jn(e){return e==="auto"||e==="compact"||e==="standard"||e==="wide"||e==="tall"||e==="full"?e:null}function _t(e,r={w:6,h:3}){return{x:0,y:e.layout.items.reduce((i,n)=>Math.max(i,n.y+n.h),0),w:r.w,h:r.h}}function Mt(e,r){const a=r.toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-+|-+$/g,"")||"tile",i=new Set(e.layout.items.map(n=>n.i));if(!i.has(a))return a;for(let n=2;n<1e3;n++){const l=`${a}-${n}`;if(!i.has(l))return l}return`${a}-${Date.now()}`}function wt(e,r){const a=Math.max(1,r),i=[],n=(s,o,p,d)=>{for(let f=0;f<d;f++){const x=i[o+f];if(x){for(let c=0;c<p;c++)if(x[s+c])return!1}}return!0},l=(s,o,p,d)=>{for(let f=0;f<d;f++){const x=o+f;i[x]||(i[x]=new Array(a).fill(!1));for(let c=0;c<p;c++)i[x][s+c]=!0}};return e.map(s=>{const o=St(Math.round(s.w||1),1,a),p=Math.max(1,Math.round(s.h||1));let d=0,f=0;e:for(let x=0;;x++)for(let c=0;c+o<=a;c++)if(n(c,x,o,p)){d=c,f=x;break e}return l(d,f,o,p),{...s,x:d,y:f,w:o,h:p}})}function kn(e,r,a){const i=e.filter(s=>s.i!==r.i).sort((s,o)=>Ke(s,a)-Ke(o,a)),n=Ke(r,a),l=i.findIndex(s=>Ke(s,a)>n);return l===-1?[...i,r]:[...i.slice(0,l),r,...i.slice(l)]}function Ke(e,r){return e.y*r+e.x}function Jt(e){const r=Le(e);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=dt(String(e.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 dt(e){const r=(e??"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"}function St(e,r,a){return Math.min(a,Math.max(r,e))}function Sn({app:e}){var o,p;const{state:r,dispatch:a}=At(),[i,n]=u.useState(!1),l=u.useRef(null);u.useEffect(()=>{if(!i)return;const d=f=>{var x;(x=l.current)!=null&&x.contains(f.target)||n(!1)};return document.addEventListener("mousedown",d),()=>document.removeEventListener("mousedown",d)},[i]);const s=r.activePersona?`${r.activePersona.displayName??r.activePersona.userId} [${r.activePersona.roles.join(", ")}]`:"View as: Owner";return!e||e.members.length===0?t.jsx("span",{style:{fontSize:12,opacity:.6},children:s}):t.jsxs("div",{ref:l,style:{position:"relative"},children:[t.jsxs("button",{onClick:()=>n(d=>!d),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:[t.jsx("span",{style:{fontSize:11,opacity:.65},children:"View as:"}),t.jsx("span",{style:{fontWeight:600},children:((o=r.activePersona)==null?void 0:o.displayName)??((p=r.activePersona)==null?void 0:p.userId)??"Owner"}),r.activePersona&&t.jsxs("span",{style:{fontSize:11,opacity:.7},children:["[",r.activePersona.roles.join(", "),"]"]}),t.jsx("span",{style:{fontSize:10,opacity:.6},children:"▾"})]}),i&&t.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:[t.jsxs("button",{role:"menuitem",onClick:async()=>{await Z.clearPersona(),a({type:"SET_ACTIVE_PERSONA",persona:null}),n(!1)},style:Nr(r.activePersona===null),children:[t.jsx("div",{style:{fontWeight:500},children:"Owner (local)"}),t.jsx("div",{style:{fontSize:11,opacity:.65},children:"Default — no RLS narrowing"})]}),t.jsx("div",{style:{height:1,background:"var(--border-color, rgba(0,0,0,0.08))",margin:"4px 0"}}),e.members.map(d=>{var f;return t.jsxs("button",{role:"menuitem",onClick:async()=>{const x=await Z.setPersona(d.userId,e.id);a({type:"SET_ACTIVE_PERSONA",persona:x}),n(!1)},style:Nr(((f=r.activePersona)==null?void 0:f.userId)===d.userId),children:[t.jsx("div",{style:{fontWeight:500},children:d.displayName??d.userId}),t.jsxs("div",{style:{fontSize:11,opacity:.65},children:["[",d.roles.join(", "),"]",d.attributes&&Object.keys(d.attributes).length>0?` · ${Object.entries(d.attributes).map(([x,c])=>`${x}=${c}`).join(", ")}`:""]})]},d.userId)})]})]})}function Nr(e){return{display:"block",width:"100%",textAlign:"left",padding:"8px 12px",background:e?"var(--surface-hover, rgba(0,0,0,0.06))":"transparent",border:"none",cursor:"pointer",color:"inherit",fontSize:13}}function Ir(e){if(!e)return[];const r=new Map;for(const i of e.filters??[])zn(i)&&r.set(i.id,{...i});const a=i=>{var n,l;return((n=i.block)==null?void 0:n.blockId)??((l=i.block)==null?void 0:l.ref)};for(const i of e.layout.items??[]){const n=a(i);for(const l of i.filterBindings??[]){const s=l.mode??(l.binding?"predicate":void 0);if(!n||s!=="predicate"||!l.binding||l.unsupportedReason)continue;const o=r.get(l.filter);o&&(o.bindsTo||(o.bindsTo=l.binding),o.sourceBlockId||(o.sourceBlockId=n))}for(const l of i.parameterBindings??[]){const s=l.filter||l.field||l.param;s&&(r.has(s)||Cn(r,l)||r.set(s,An(l)))}}return Array.from(r.values())}function zn(e){var r;return!(e.type==="select"&&!((r=e.options)!=null&&r.length)&&e.default===void 0)}function An(e){const r=e.filter||e.field||e.param;return{id:r,type:Nn(r,e.parameterType),default:e.default??pa(r),bindsTo:e.param}}function Cn(e,r){return Array.from(e.values()).some(a=>r.filter&&a.id===r.filter||r.field&&a.bindsTo===r.field?!0:!!(r.param&&a.bindsTo===r.param))}function Nn(e,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(e)?"daterange":/(top[_-]?n|limit|count|number|year|season)/i.test(e)?"number":"string"}function pa(e){const r=e.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:""}const In=u.lazy(()=>Ut(()=>import("./UnifiedAgentRunPanel-CGPcpY1B.js").then(e=>e.c),__vite__mapDeps([0,1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16])).then(e=>({default:e.UnifiedAgentRunPanel}))),Tn=u.lazy(()=>Ut(()=>import("./AgentAnswerCard-BJAnjaLA.js").then(e=>e.A),__vite__mapDeps([4,1,2,3,5,6,7,8,9,10])).then(e=>({default:e.StructuredAnswerText}))),Ot=new Map,da="Build an analytics app from my certified DQL blocks and available warehouse tables.",ca=[{title:"Revenue story",domain:"Revenue",prompt:"Build a weekly revenue health app for the COO with risk flags."},{title:"Customer 360",domain:"Customer",prompt:"Customer 360: value, engagement, retention, orders, and service risk by segment."},{title:"Quality monitor",domain:"Platform",prompt:"Build a data quality monitor with freshness, failing tests, null rates, and model risk notes."},{title:"Experiment Readout",domain:"Product",prompt:"Create an experiment readout for product leadership with outcome, guardrails, and decision checklist."}],$n=[{id:"match",title:"Find blocks",description:"Search certified blocks, terms, views, and lineage."},{id:"story",title:"Shape story",description:"Order the app around the business decision."},{id:"draft",title:"Draft gaps",description:"Keep missing sections visible as draft work instead of hiding them."}],Pn={all:"All",mine:"Mine",shared:"Shared",fav:"Favourites"};function Rn(e){return e==="obsidian"||e==="dark"||e==="midnight"?"obsidian":e==="white"||e==="arctic"?"white":"paper"}function ts(){const{state:e,dispatch:r}=At(),a=u.useMemo(()=>Rn(e.themeMode),[e.themeMode]),[i,n]=u.useState(()=>e.activeAppId?"workspace":"library"),l=e.activeAppExperience,s=e.activeAppSection,o=g=>{r({type:"SET_APP_WORKSPACE_STATE",experience:g})},p=g=>{r({type:"SET_APP_WORKSPACE_STATE",section:g})},[d,f]=u.useState(""),[x,c]=u.useState("all"),[A,S]=u.useState(()=>new Set),[q,h]=u.useState(null),[T,z]=u.useState(null),[Y,$]=u.useState(!1),[k,E]=u.useState("ai"),[M,I]=u.useState(da),[Q,re]=u.useState("Business Analytics"),[D,_]=u.useState(""),[V,W]=u.useState("analytics"),[de,C]=u.useState([]),[le,we]=u.useState(!1),[B,ee]=u.useState(()=>new Set),[ne,he]=u.useState(null),[X,K]=u.useState(null),[me,pe]=u.useState(new Set),[ye,ce]=u.useState(!1),[be,J]=u.useState(null),[b,P]=u.useState(!1),[U,G]=u.useState(!1),[N,L]=u.useState(""),[se,ve]=u.useState(null),[oe,ue]=u.useState({}),[xe,ae]=u.useState({}),[Ce,H]=u.useState(!1),[y,te]=u.useState(!1),ie=u.useCallback(g=>{H(g),g||te(!1)},[]),[_e,Se]=u.useState(0),tt=u.useRef(0);u.useEffect(()=>{let g=!1;return r({type:"SET_APPS_LOADING",loading:!0}),Z.listApps().then(v=>{g||(r({type:"SET_APPS",apps:v}),r({type:"SET_APPS_LOADING",loading:!1}))}),()=>{g=!0}},[r]),u.useEffect(()=>{Z.getPersona().then(g=>r({type:"SET_ACTIVE_PERSONA",persona:g}))},[r]),u.useEffect(()=>{if(i!=="create")return;let g=!1;return we(!0),Z.recommendAppBlocks({domain:D||void 0,purpose:M,audience:"stakeholder",certifiedOnly:!0}).then(v=>{g||C(v)}).finally(()=>{g||we(!1)}),()=>{g=!0}},[i,k,D,M]),u.useEffect(()=>{if(!e.activeAppId||i!=="workspace"){h(null),z(null);return}let g=!1;return $(!0),Z.getApp(e.activeAppId).then(v=>{g||h(v)}),e.activeDashboardId?Z.getDashboard(e.activeAppId,e.activeDashboardId).then(v=>{g||z(v)}).finally(()=>{g||$(!1)}):(z(null),$(!1)),()=>{g=!0}},[e.activeAppId,e.activeDashboardId,i]);const ct=u.useMemo(()=>JSON.stringify(Ir((T==null?void 0:T.dashboard)??null)),[T==null?void 0:T.dashboard]),Me=u.useMemo(()=>Ir((T==null?void 0:T.dashboard)??null),[T==null?void 0:T.dashboard,ct]);u.useEffect(()=>{const g=Me;ue(v=>{const R={};for(const O of g)R[O.id]=v[O.id]??lt(O);return $r(v,R)?v:R}),ae(v=>{const R={};for(const O of g)R[O.id]=v[O.id]??lt(O);return $r(v,R)?v:R})},[T==null?void 0:T.dashboard.id,ct,Me]);const Ve=async(g,v,R,O)=>{r({type:"SET_APPS_LOADING",loading:!0});const ze=await Z.listApps();r({type:"SET_APPS",apps:ze}),r({type:"SET_APPS_LOADING",loading:!1}),g&&r({type:"OPEN_APP",appId:g,dashboardId:v,...O}),n(R)},Nt=u.useMemo(()=>{const g=d.trim().toLowerCase();return e.apps.filter(v=>x==="mine"&&(v.storage??"shared")!=="mine"||x==="shared"&&(v.storage??"shared")!=="shared"||x==="fav"&&!A.has(v.id)?!1:g?[v.name,v.description??"",v.domain,v.audience??"",v.lifecycle??"",...v.tags??[],...v.owners??[],...v.dashboards.map(O=>O.title)].join(" ").toLowerCase().includes(g):!0)},[A,x,d,e.apps]),He=u.useMemo(()=>e.apps.find(g=>g.id===e.activeAppId)??null,[e.apps,e.activeAppId]),It=u.useCallback(g=>{h(v=>v&&{...v,investigations:g})},[]),Tt=(g,v="view")=>{r({type:"OPEN_APP",appId:g.id,experience:v,section:"dashboards"}),n("workspace")},$t=(g=M,v)=>{E("ai"),I(g),_(""),ee(new Set),J(null),he(null),K(null),n("create"),Se(R=>R+1)},Pt=()=>{E("classic"),J(null),he(null),K(null),n("create")},ut=g=>{ee(v=>{const R=new Set(v);return R.has(g)?R.delete(g):R.add(g),R})},Xe=async g=>{var ht;const v=Array.isArray(g)?g.filter(ha=>typeof ha=="string"):[],R=M.trim();if(!R){J("Describe the app you want to build.");return}P(!0),J(null);const O=Array.from(k==="classic"?B:new Set([...Array.from(B),...v])),ze=await Z.proposeAppAiBuild({prompt:R,domain:D.trim()||void 0,owner:V.trim()||void 0,force:!1,selectedBlockIds:O,plannerMode:"ai_assisted"});if(P(!1),!ze.ok){J(ze.error),ze.session&&K(ze.session);return}const Je=ze.session;K(Je),he(null),pe(Je.proposal?Na(Je.proposal):new Set);const gt=(ht=Je.plan)==null?void 0:ht.name;gt&&re(gt)};u.useEffect(()=>{i!=="create"||k!=="ai"||_e===0||tt.current===_e||(tt.current=_e,Xe())},[i,k,_e]);const xt=g=>{ee(v=>{const R=new Set(v);return R.add(g),R}),Xe([g])},rt=g=>{pe(v=>{const R=new Set(v);return R.has(g)?R.delete(g):R.add(g),R})},Rt=async()=>{var O;if(!X||X.status!=="proposed")return;ce(!0),J(null);const g=await Z.commitAppAiBuild(X.id,{selectedTileIds:Array.from(me),expectedProposalHash:X.proposalHash});if(ce(!1),!g.ok){J(g.error);return}const v=g.session;K(v);const R={ok:!0,plan:v.plan,validation:v.validation,generated:{paths:v.generatedPaths},app:g.app,dashboardId:g.dashboardId};he(R),H(!0),await Ve(((O=g.app)==null?void 0:O.id)??R.plan.appId,g.dashboardId,"workspace",{experience:"view",section:"dashboards"})},ft=async()=>{if(!Q.trim()){J("Name the app before creating it.");return}if(!D.trim()){J("Choose a domain before creating the app.");return}P(!0),J(null);try{const g=await Z.createApp({name:Q.trim(),domain:D.trim(),dashboardTitle:"Overview",purpose:M.trim(),audience:"stakeholder",visibility:"shared",lifecycle:"draft",tags:["app-builder",D.trim().toLowerCase()],owners:[V.trim()||"owner@local"],selectedBlockIds:Array.from(B)});await Ve(g.app.id,g.dashboardId,"workspace",{experience:"build",section:"dashboards"})}catch(g){J(g instanceof Error?g.message:String(g))}finally{P(!1)}},m=()=>{var v;const g=((v=ne==null?void 0:ne.app)==null?void 0:v.id)??(ne==null?void 0:ne.plan.appId);g&&(r({type:"OPEN_APP",appId:g,dashboardId:(ne==null?void 0:ne.dashboardId)??void 0,experience:"build",section:"dashboards"}),n("workspace"))},j=async()=>{if(!e.activeAppId)return;const g=N.trim();if(!g){ve("Enter a dashboard page name.");return}ve(null);const v=await Z.createAppDashboard(e.activeAppId,{title:g});if(!v.ok){ve(v.error);return}G(!1),L(""),r({type:"OPEN_APP",appId:e.activeAppId,dashboardId:v.dashboard.id,experience:l,section:s}),await Ve(e.activeAppId,v.dashboard.id,"workspace")},w=u.useMemo(()=>({...xe}),[xe]),F=u.useCallback((g,v)=>{ue(R=>({...R,[g.id]:el(g,v)}))},[]),fe=u.useCallback(()=>{ae({...oe})},[oe]),je=u.useCallback(()=>{const g=Object.fromEntries(Me.map(v=>[v.id,lt(v)]));ue(g),ae(g)},[Me]);return t.jsxs("div",{className:`dql-apps-waterline dql-apps-theme-${a}`,children:[t.jsx("style",{children:_l}),i==="library"?t.jsx(Bn,{apps:Nt,allApps:e.apps,loading:e.appsLoading,search:d,filter:x,favorites:A,onSearch:f,onFilter:c,onToggleFavorite:g=>{S(v=>{const R=new Set(v);return R.has(g)?R.delete(g):R.add(g),R})},onStartAi:g=>$t(g),onStartClassic:Pt,onOpenApp:Tt}):i==="create"?t.jsx(En,{mode:k,appName:Q,prompt:M,domain:D,owner:V,promptExamples:ca,catalog:de,catalogLoading:le,selectedBlocks:B,generated:ne,buildSession:X,proposalSelection:me,committing:ye,themeMode:e.themeMode,onToggleProposalTile:rt,onCommitProposal:()=>void Rt(),onAddBlock:xt,saving:b,error:be,onBack:()=>n("library"),onModeChange:g=>{E(g),g==="ai"&&ee(new Set)},onAppNameChange:re,onPromptChange:I,onDomainChange:_,onOwnerChange:W,onToggleBlock:ut,onBuild:()=>k==="ai"?void Xe():void ft(),onOpenGenerated:m}):t.jsx(_n,{app:He,appDoc:q,dashboardDoc:T,loading:Y,experience:l,section:s,explainOpen:Ce,explainExpanded:y,dashboardFilters:Me,dashboardFilterValues:oe,themeMode:e.themeMode,variables:w,onBack:()=>n("library"),onExperienceChange:o,onSectionChange:p,onDashboardFilterChange:F,onApplyDashboardFilters:fe,onResetDashboardFilters:je,onExplainChange:ie,onExplainExpandedChange:te,onAddPage:()=>G(!0),onOpenDashboard:g=>r({type:"OPEN_DASHBOARD",dashboardId:g}),onDashboardChanged:g=>{z(v=>v&&{...v,dashboard:g}),Ve(e.activeAppId,g.id,"workspace")},onInvestigationsChanged:It,onOpenLineageNode:g=>{r({type:"OPEN_LINEAGE_DETAIL",nodeId:g,returnTo:e.activeAppId?{view:"apps",appId:e.activeAppId,dashboardId:e.activeDashboardId,label:He==null?void 0:He.name,experience:l,section:s}:null})}}),U&&t.jsx(Pl,{title:N,error:se,onChange:L,onCancel:()=>{G(!1),ve(null)},onCreate:()=>void j()})]})}function Bn({apps:e,allApps:r,loading:a,search:i,filter:n,favorites:l,onSearch:s,onFilter:o,onToggleFavorite:p,onStartAi:d,onStartClassic:f,onOpenApp:x}){const c=Bl(r,l),[A,S]=u.useState(da),q=()=>{const h=A.trim();h&&d(h)};return t.jsxs("main",{className:"dql-apps-wrap",children:[t.jsxs("section",{className:"dql-apps-createhead",children:[t.jsx("h1",{children:"Build an app"}),t.jsx("p",{children:"One request. DQL finds certified blocks, binds filters, and opens a stakeholder-ready app."})]}),t.jsxs("section",{className:"dql-apps-composer","aria-label":"Build an app with AI",children:[t.jsx("textarea",{value:A,onChange:h=>S(h.target.value),rows:2,"aria-label":"App build request",placeholder:"Build an EMEA revenue app for the CFO…",onKeyDown:h=>{h.key==="Enter"&&!h.shiftKey&&(h.preventDefault(),q())}}),t.jsxs("div",{className:"dql-apps-composer-row",children:[t.jsxs("span",{className:"dql-apps-composer-chip",children:[t.jsx(We,{size:11})," Certified blocks first"]}),t.jsx("i",{}),t.jsxs("button",{type:"button",className:"dql-apps-composer-blank",onClick:f,children:[t.jsx(Ye,{size:12})," Create blank"]}),t.jsx("button",{type:"button",className:"dql-apps-composer-send",onClick:q,disabled:!A.trim(),title:"Build",children:t.jsx(qa,{size:15,strokeWidth:2})})]})]}),t.jsxs("div",{className:"dql-apps-try",children:[t.jsx("span",{children:"Try:"}),ca.slice(0,3).map(h=>t.jsx("button",{type:"button",onClick:()=>S(h.prompt),children:h.title},h.title))]}),t.jsxs("div",{className:"dql-apps-sectionhead",children:[t.jsx("span",{children:"App library"}),t.jsx("i",{}),t.jsxs("b",{children:[r.length," app",r.length===1?"":"s"]})]}),t.jsxs("div",{className:"dql-apps-libbar",children:[t.jsx("div",{className:"dql-apps-filter-tabs",children:["all","mine","shared","fav"].map(h=>t.jsxs("button",{className:n===h?"on":"",onClick:()=>o(h),children:[Pn[h]," ",t.jsx("span",{children:c[h]})]},h))}),t.jsxs("label",{className:"dql-apps-search",children:[t.jsx(Be,{size:15,strokeWidth:2,"aria-hidden":"true"}),t.jsx("input",{value:i,onChange:h=>s(h.target.value),placeholder:"Search apps, domains, owners..."})]})]}),a&&r.length===0?t.jsx(qe,{title:"Loading Apps...",detail:"Reading local app files from this DQL project."}):e.length===0?t.jsx(qe,{title:"No Apps match this view.",detail:"Change the filter or start a new App above."}):t.jsx("div",{className:"dql-apps-grid",children:e.map(h=>t.jsx(Ln,{app:h,favorite:l.has(h.id),onToggleFavorite:()=>p(h.id),onOpen:()=>x(h,"view"),onEdit:()=>x(h,"build")},h.id))})]})}function Ln({app:e,favorite:r,onToggleFavorite:a,onOpen:i,onEdit:n}){var f,x;const l=e.certification==="certified"||e.lifecycle==="certified",s=((f=e.drafts)==null?void 0:f.length)??0,o=e.investigations??0,p=e.aiPins??0,d=l?"Certified app":s>0||o>0||p>0?"Review needed":"Draft app";return t.jsxs("article",{className:"dql-app-card",children:[t.jsxs("div",{className:"dql-app-card-body",onClick:i,role:"button",tabIndex:0,children:[t.jsxs("div",{className:"dql-app-card-top",children:[t.jsx("span",{className:"dql-app-eyebrow",children:e.domain||"Domain"}),t.jsx("button",{type:"button",className:`dql-app-star ${r?"on":""}`,onClick:c=>{c.stopPropagation(),a()},"aria-label":r?"Remove favourite":"Add favourite",children:t.jsx(Ya,{size:14,strokeWidth:1.8})})]}),t.jsx(Fe,{tone:l?"certified":s>0?"draft":"agentic",children:l?"certified":s>0?"mixed":e.lifecycle??"draft"}),t.jsx("h3",{children:e.name}),t.jsx("p",{children:xa(e.description||`${e.name} consumption surface for ${e.domain}.`)}),t.jsxs("div",{className:"dql-app-card-mini",children:[t.jsx(Ht,{label:"Pages",value:String(e.dashboards.length)}),t.jsx(Ht,{label:"Books",value:String(((x=e.notebooks)==null?void 0:x.length)??0)}),t.jsx(Ht,{label:"Drafts",value:String(s)})]}),t.jsxs("div",{className:"dql-app-card-signals",children:[t.jsxs("span",{children:[t.jsx(We,{size:13})," ",d]}),t.jsxs("span",{children:[t.jsx(Be,{size:13})," ",o," analysis"]}),t.jsxs("span",{children:[t.jsx(Re,{size:13})," ",p," local insights"]})]})]}),t.jsxs("div",{className:"dql-app-card-depth",children:[t.jsx("span",{children:Ll(e)}),t.jsxs("button",{type:"button",className:"dql-app-card-act",onClick:i,title:"View app",children:[t.jsx(_r,{size:12})," View"]}),t.jsxs("button",{type:"button",className:"dql-app-card-act",onClick:n,title:"Edit app",children:[t.jsx(Hr,{size:12})," Edit"]})]})]})}function En({mode:e,appName:r,prompt:a,domain:i,owner:n,promptExamples:l,catalog:s,catalogLoading:o,selectedBlocks:p,generated:d,buildSession:f,proposalSelection:x,committing:c,themeMode:A,onToggleProposalTile:S,onCommitProposal:q,saving:h,error:T,onBack:z,onModeChange:Y,onAppNameChange:$,onPromptChange:k,onDomainChange:E,onOwnerChange:M,onToggleBlock:I,onBuild:Q,onOpenGenerated:re,onAddBlock:D}){var me,pe,ye,ce,be,J,b,P,U,G;const[_,V]=u.useState(!1),[W,de]=u.useState(""),C=s.filter(N=>p.has(N.id)),le=i.trim()||"Auto domain",we=n.trim()||"Local owner",B=(f==null?void 0:f.status)==="proposed"?f.proposal:void 0,ee=(d==null?void 0:d.plan)??(f==null?void 0:f.plan)??Rl(r,a,i,n,C),he=(((me=ee.pages[0])==null?void 0:me.tiles)??[]).filter(Yn),X=(f==null?void 0:f.warnings)??[],K=Xn(ee);if(e==="ai"){const N=(B==null?void 0:B.tiles)??[],L=N.filter(y=>y.certification==="certified").length,se=N.filter(y=>y.certification==="reviewed_semantic").length,ve=N.filter(y=>x.has(y.id)).length,oe=new Set(N.map(y=>y.blockId).filter(Boolean)),ue=W.trim().toLowerCase(),xe=s.filter(y=>!oe.has(y.id)&&(!ue||y.name.toLowerCase().includes(ue)||(y.description??"").toLowerCase().includes(ue))),ae=((pe=ee.globalFilters)!=null&&pe.length?ee.globalFilters:((ye=ee.pages[0])==null?void 0:ye.filters)??[]).slice(0,4),Ce=y=>{const te=y.toLowerCase();return te.includes("kpi")||te.includes("metric")||te.includes("single")?"Σ":te.includes("table")?"▤":"▦"},H=y=>{const te=y.toLowerCase();return te.includes("kpi")||te.includes("single")?"KPI":te.includes("table")?"Table":te.includes("line")?"Line chart":te.includes("bar")?"Bar chart":y?y.charAt(0).toUpperCase()+y.slice(1):"Auto"};return t.jsx("div",{className:"dql-app-flow-scroll",children:t.jsxs("div",{className:"dql-app-flow",children:[t.jsxs("div",{className:"dql-app-flow-head",children:[t.jsx("h2",{children:"Build an app"}),t.jsx("p",{children:"One request. DQL finds certified blocks, binds filters, and opens a stakeholder-ready app."})]}),t.jsx("div",{className:"dql-app-flow-bubble",children:a}),h?t.jsxs("div",{className:"dql-app-buildstream",children:[t.jsx("span",{className:"dql-app-buildorb",children:t.jsx(Re,{size:14})}),t.jsxs("div",{className:"dql-app-buildbody",children:[t.jsx("span",{className:"dql-app-shimmer",children:"Finding certified blocks…"}),t.jsxs("div",{className:"dql-app-buildsteps",children:[t.jsxs("span",{style:{animationDelay:"0.2s"},children:[t.jsx(nt,{size:11,className:"ok"}),"Matched domain ",t.jsx("code",{children:le.toLowerCase()})]}),t.jsxs("span",{style:{animationDelay:"0.8s"},children:[t.jsx(nt,{size:11,className:"ok"}),"Scanning certified blocks and semantic metrics"]}),t.jsxs("span",{style:{animationDelay:"1.4s"},children:[t.jsx("i",{className:"dot"}),"Detecting app filters from block parameters…"]})]})]})]}):null,!h&&B?t.jsxs("div",{className:"dql-app-buildstream proposal",children:[t.jsx("span",{className:"dql-app-buildorb still",children:t.jsx(Re,{size:14})}),t.jsxs("div",{className:"dql-app-buildbody wide",children:[t.jsxs("div",{className:"dql-app-proposal-lede",children:["Found ",t.jsxs("strong",{children:[L," certified block",L===1?"":"s"]}),se>0?` and ${se} reviewed semantic view${se===1?"":"s"}`:""," for your app. Uncheck any you don't need, or add more — everything ships governed."]}),t.jsxs("div",{className:"dql-app-proposal-card",children:[N.map(y=>{const te=x.has(y.id),ie=y.certification==="certified",_e=y.certification==="reviewed_semantic";return t.jsxs("button",{type:"button",className:`dql-app-proposal-row ${te?"":"off"}`,onClick:()=>S(y.id),children:[t.jsx("span",{className:`dql-app-prop-check ${te?"on":""}`,children:te?t.jsx(nt,{size:10,strokeWidth:3.2}):null}),t.jsx("span",{className:`dql-app-prop-glyph ${ie&&Ce(y.viz)==="▤"?"green":""}`,children:Ce(y.viz)}),t.jsxs("span",{className:"dql-app-prop-name",children:[t.jsx("b",{children:y.blockId??y.title}),t.jsx("small",{children:y.description??y.question??y.title})]}),t.jsx("span",{className:`dql-app-prop-badge ${ie?"certified":"draft"}`,children:ie?"Certified":_e?"Reviewed semantic":"Draft"}),t.jsx("span",{className:"dql-app-prop-viz",children:H(y.viz)})]},y.id)}),t.jsxs("button",{type:"button",className:"dql-app-addmore",onClick:()=>V(y=>!y),children:[t.jsx(kt,{size:13,strokeWidth:2.2})," Add more blocks"]}),_?t.jsxs("div",{className:"dql-app-addmore-panel",children:[t.jsxs("div",{className:"dql-app-addmore-search",children:[t.jsx(Be,{size:12}),t.jsx("input",{value:W,onChange:y=>de(y.target.value),placeholder:`Search ${s.length} certified block${s.length===1?"":"s"}…`})]}),o?t.jsx("div",{className:"dql-app-addmore-hint",children:"Loading certified blocks…"}):null,xe.slice(0,6).map(y=>t.jsxs("button",{type:"button",className:"dql-app-addmore-row",onClick:()=>{de(""),D(y.id)},children:[t.jsx(kt,{size:12,strokeWidth:2.2}),t.jsx("span",{children:y.name}),t.jsxs("small",{children:[y.domain??"certified"," · ",y.status]})]},y.id)),!o&&xe.length===0?t.jsx("div",{className:"dql-app-addmore-hint",children:"No more matching certified blocks."}):null]}):null]}),ae.length>0?t.jsxs("div",{className:"dql-app-detected",children:[t.jsx("span",{className:"dql-app-detected-label",children:"Detected filters"}),ae.map(y=>t.jsxs("span",{className:"dql-app-detected-pill",children:[y.label," · ",t.jsx("strong",{children:zt(y.default??"Any")})]},y.id))]}):null,B.gaps.length>0?t.jsx("div",{className:"dql-app-flow-gaps",children:B.gaps.slice(0,3).map(y=>t.jsxs("span",{children:[t.jsx(Qe,{size:12})," ",y.question]},y.id))}):null,t.jsxs("div",{className:"dql-app-flow-actions",children:[t.jsxs("button",{type:"button",className:"dql-app-flow-build",onClick:q,disabled:c||ve===0,children:[t.jsx(Ye,{size:13}),c?"Building app…":`Build app with ${ve} governed tile${ve===1?"":"s"}`]}),t.jsx("button",{type:"button",className:"dql-app-flow-reset",onClick:z,children:"Start over"})]})]})]}):null,!h&&!B?t.jsxs("div",{className:"dql-app-flow-actions",children:[t.jsxs("button",{type:"button",className:"dql-app-flow-build",onClick:Q,children:[t.jsx(Re,{size:13})," Find certified blocks"]}),t.jsx("button",{type:"button",className:"dql-app-flow-reset",onClick:z,children:"Start over"})]}):null,T?t.jsx("div",{className:"dql-app-error",children:T}):null,X.length>0&&!h?t.jsx("div",{className:"dql-app-flow-gaps",children:X.slice(0,2).map((y,te)=>t.jsxs("span",{children:[t.jsx(Qe,{size:12})," ",y]},`${y}-${te}`))}):null]})})}return t.jsxs("div",{className:"dql-app-create-shell",children:[t.jsxs("div",{className:"dql-app-buildbar",children:[t.jsxs("button",{type:"button",className:"dql-app-back dql-app-back-label",onClick:z,children:[t.jsx(Vr,{size:14}),t.jsx("span",{children:"Apps"})]}),t.jsx("span",{className:"dql-app-name-input",children:t.jsx("input",{value:r,onChange:N=>$(N.target.value),spellCheck:!1})}),t.jsx(Fe,{tone:d?"agentic":"draft",children:d?"generated":"draft"}),t.jsxs("div",{className:"dql-app-mode-seg",children:[t.jsxs("button",{type:"button",onClick:()=>Y("ai"),children:[t.jsx(Re,{size:15})," Build AI"]}),t.jsxs("button",{type:"button",className:"on",onClick:()=>Y("classic"),children:[t.jsx(er,{size:15})," Classic"]})]}),t.jsxs("div",{className:"dql-app-build-actions",children:[t.jsxs("span",{className:"dql-app-persona",children:[t.jsx("b",{children:"CFO"})," CFO"]}),d?t.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:re,children:"Open app"}):null,t.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-primary",onClick:Q,disabled:h,children:h?"Building...":"Create app"})]})]}),t.jsx("div",{className:"dql-app-create-workspace clean classic",children:t.jsxs("section",{className:"dql-app-ai-start",children:[t.jsxs("div",{className:"dql-app-ai-start-main",children:[t.jsxs("div",{className:"dql-app-ai-start-copy",children:[t.jsx("h1",{children:"Start with one AI input."}),t.jsx("p",{children:"DQL finds certified blocks, detects app filters, and opens the generated app in a clean stakeholder view."})]}),t.jsxs("div",{className:"dql-app-ai-start-card",children:[t.jsx("textarea",{value:a,onChange:N=>k(N.target.value),rows:5,"aria-label":"App request",placeholder:"Build an NBA player performance app for stakeholders..."}),t.jsx("button",{type:"button",className:"dql-app-ai-start-send",onClick:Q,disabled:h||!a.trim(),title:"Build app",children:h?t.jsx(Oe,{size:19}):t.jsx(Ia,{size:19})})]}),t.jsxs("div",{className:"dql-app-suggestions dql-app-ai-start-examples","aria-label":"Prompt examples",children:[t.jsx("span",{children:"Examples"}),l.slice(0,4).map(N=>t.jsx("button",{type:"button",onClick:()=>{k(N.prompt),E(N.domain)},children:N.title},N.title))]}),t.jsxs("details",{className:"dql-app-ai-context dql-app-ai-start-advanced",children:[t.jsxs("summary",{children:[t.jsx("span",{children:"Advanced controls"}),t.jsxs("b",{children:[le," / ",we]}),t.jsx(Er,{size:14})]}),t.jsxs("div",{className:"dql-app-ai-context-grid",children:[t.jsxs("label",{children:["Domain",t.jsx("input",{value:i,onChange:N=>E(N.target.value)})]}),t.jsxs("label",{children:["Owner",t.jsx("input",{value:n,onChange:N=>M(N.target.value)})]}),t.jsxs("label",{children:["Build mode",t.jsxs("select",{value:e,onChange:N=>Y(N.target.value),children:[t.jsx("option",{value:"ai",children:"AI first"}),t.jsx("option",{value:"classic",children:"Manual block selection"})]})]})]}),e==="classic"?t.jsx(Mn,{title:"Manual certified block selection",subtitle:`${p.size} selected`,catalog:s,loading:o,selectedBlocks:p,onToggleBlock:I}):null]}),B&&!d?t.jsx("div",{style:{border:`1px solid ${Ne[A].cellBorder}`,background:Ne[A].appBg,borderRadius:10,padding:14},children:t.jsx(Ta,{proposal:B,t:Ne[A],selected:x,onToggle:S,onCreate:q,busy:c,error:null})}):null,d?t.jsxs("div",{className:"dql-app-ai-result dql-app-ai-start-result",children:["Generated ",t.jsx("b",{children:d.plan.name})," with ",d.validation.certifiedTiles," certified app tile",d.validation.certifiedTiles===1?"":"s"," and ",K," scoped report",K===1?"":"s",".",f?t.jsxs("small",{children:["Session ",f.id]}):null]}):null,T?t.jsx("div",{className:"dql-app-error",children:T}):null]}),t.jsxs("aside",{className:"dql-app-ai-start-context",children:[t.jsxs("section",{className:"dql-app-ai-context-card",children:[t.jsx(Ft,{title:"Certified blocks found",meta:ee.coverage?`${ee.coverage.certifiedTiles} certified · ${ee.coverage.gaps} gap${ee.coverage.gaps===1?"":"s"}`:`${he.length||s.length} matches`}),t.jsxs("div",{className:"dql-app-ai-evidence-list",children:[(he.length?he:s.slice(0,4)).map((N,L)=>"name"in N?t.jsxs("div",{className:"dql-app-ai-evidence-row",children:[t.jsx("span",{children:t.jsx(We,{size:14})}),t.jsxs("div",{children:[t.jsx("b",{children:N.name}),t.jsx("small",{children:N.description})]}),t.jsx(Fe,{tone:N.status==="certified"?"certified":"draft",children:N.status})]},`catalog-${N.id}-${L}`):t.jsxs("div",{className:"dql-app-ai-evidence-row",children:[t.jsx("span",{children:t.jsx(We,{size:14})}),t.jsxs("div",{children:[t.jsx("b",{children:N.title}),t.jsx("small",{children:N.description??N.rationale??"Certified DQL block"})]}),t.jsx(Fe,{tone:"certified",children:"Certified"})]},`plan-${N.id}-${L}`)),!he.length&&!s.length?t.jsx(qe,{title:"No matches yet.",detail:"Enter a prompt to retrieve certified blocks.",compact:!0}):null]})]}),t.jsxs("section",{className:"dql-app-ai-context-card",children:[t.jsx(Ft,{title:"Detected app filters",meta:"bound to block params"}),t.jsxs("div",{className:"dql-app-ai-filter-preview",children:[((ce=ee.globalFilters)!=null&&ce.length?ee.globalFilters:((be=ee.pages[0])==null?void 0:be.filters)??[]).slice(0,4).map(N=>t.jsxs("span",{children:[t.jsx("small",{children:N.label}),t.jsx("b",{children:zt(N.default??"Any")})]},N.id)),(J=ee.globalFilters)!=null&&J.length||(P=(b=ee.pages[0])==null?void 0:b.filters)!=null&&P.length?null:t.jsxs(t.Fragment,{children:[t.jsxs("span",{children:[t.jsx("small",{children:"Domain"}),t.jsx("b",{children:le})]}),t.jsxs("span",{children:[t.jsx("small",{children:"Owner"}),t.jsx("b",{children:we})]}),t.jsxs("span",{children:[t.jsx("small",{children:"Top N"}),t.jsx("b",{children:"Any"})]})]})]})]}),t.jsxs("section",{className:"dql-app-ai-context-card",children:[t.jsx(Ft,{title:"Possible deeper analysis",meta:"Copilot asks for context first"}),t.jsxs("div",{className:"dql-app-ai-gap-list",children:[((U=ee.missingEvidence)!=null&&U.length?ee.missingEvidence:X).slice(0,4).map((N,L)=>t.jsxs("span",{children:[t.jsx(Qe,{size:13})," ",N]},`${N}-${L}`)),!((G=ee.missingEvidence)!=null&&G.length)&&!X.length?t.jsxs("span",{children:[t.jsx(Qe,{size:13})," Driver explanations, new grains, and reusable block proposals require typed context before DQL creates SQL."]}):null]})]})]})]})})]})}function _n({app:e,appDoc:r,dashboardDoc:a,loading:i,experience:n,section:l,explainOpen:s,explainExpanded:o,dashboardFilters:p,dashboardFilterValues:d,themeMode:f,variables:x,onBack:c,onExperienceChange:A,onSectionChange:S,onDashboardFilterChange:q,onApplyDashboardFilters:h,onResetDashboardFilters:T,onExplainChange:z,onExplainExpandedChange:Y,onAddPage:$,onOpenDashboard:k,onDashboardChanged:E,onInvestigationsChanged:M,onOpenLineageNode:I}){var Ce;const{dispatch:Q}=At(),re=(a==null?void 0:a.dashboard.layout.items.filter(H=>!!H.block).length)??0,D=((Ce=r==null?void 0:r.drafts)==null?void 0:Ce.length)??0,_=u.useMemo(()=>ua((a==null?void 0:a.dashboard)??null).map(H=>H.blockId),[a]),V=_.join("|"),[W,de]=u.useState(_[0]??null),[C,le]=u.useState(null),[we,B]=u.useState(null),[ee,ne]=u.useState(null),[he,X]=u.useState(null),[K,me]=u.useState("idle"),[pe,ye]=u.useState(""),[ce,be]=u.useState("idle"),[J,b]=u.useState(""),P=u.useCallback(H=>{le(H)},[]);u.useCallback(H=>{ne({...H,nonce:Date.now()}),S("research"),z(!0)},[z,S]);const U=u.useCallback(H=>{X(H)},[]),G=u.useCallback(()=>{ne(null)},[]),N=u.useCallback((H,y)=>{var te,ie;if(de(H),n==="view"){Q({type:"OPEN_GLOBAL_AI",audience:"stakeholder",context:{title:"App copilot",scopeHint:qt(e==null?void 0:e.name)?`Follow up on ${qt(e==null?void 0:e.name)}`:"Follow up on this tile",selectedObject:{kind:"block",id:H,title:a==null?void 0:a.dashboard.metadata.title},workspaceContext:{appId:e==null?void 0:e.id,dashboardId:a==null?void 0:a.dashboard.id,blockId:H},suggestedQuestions:(ie=(te=a==null?void 0:a.app)==null?void 0:te.copilot)==null?void 0:ie.suggestedQuestions},autoRun:{text:y,mode:"auto"}});return}z(!0),B({text:y,nonce:Date.now()})},[Q,n,e==null?void 0:e.id,e==null?void 0:e.name,a==null?void 0:a.dashboard.id,a==null?void 0:a.dashboard.metadata.title,z]);u.useEffect(()=>{n==="view"&&(l==="notebooks"||l==="ai"||l==="drafts"||l==="settings")&&S("dashboards")},[n,l,S]),u.useEffect(()=>{if(_.length===0){W!==null&&de(null);return}(!W||!_.includes(W))&&de(_[0])},[_,V,W]),u.useEffect(()=>{le(null),X(null)},[e==null?void 0:e.id,a==null?void 0:a.dashboard.id]);const L=!!(e&&a&&(l==="dashboards"||l==="research")),se=L&&s,ve=H=>{me(H),H!=="ready"&&window.setTimeout(()=>me("idle"),1800)},oe=async()=>{var te;const H=ll(e,r,a);ye(H);let y=!1;try{typeof navigator<"u"&&((te=navigator.clipboard)!=null&&te.writeText)&&(await navigator.clipboard.writeText(H),y=!0)}catch{y=!1}if(!y){const ie=document.createElement("textarea");ie.value=H,ie.style.position="fixed",ie.style.left="-9999px",document.body.appendChild(ie),ie.focus(),ie.select(),y=document.execCommand("copy"),document.body.removeChild(ie)}ve(y?"copied":"ready")},ue=()=>{const H=sl(e,r,a),y=new Blob([H],{type:"text/markdown;charset=utf-8"}),te=URL.createObjectURL(y),ie=document.createElement("a");ie.href=te,ie.download=`${(e==null?void 0:e.id)??(r==null?void 0:r.app.id)??"dql-app"}-brief.md`,document.body.appendChild(ie),ie.click(),document.body.removeChild(ie),URL.revokeObjectURL(te),ve("downloaded")},xe=async()=>{if(!(e!=null&&e.id))return;be("running"),b("");const H=await Z.promoteApp(e.id,{lifecycle:"review"});if(!H.ok){be("error"),b(H.error);return}be("done"),b(`${H.paths.length} shared files updated${H.removedLocalTiles?`, ${H.removedLocalTiles} local AI tile removed`:""}.`),window.setTimeout(()=>be("idle"),2400)},ae=l==="dashboards"&&!!a;return t.jsxs("div",{className:"dql-app-workspace",children:[t.jsxs("div",{className:"dql-app-view-topbar",children:[t.jsxs("button",{type:"button",className:"dql-app-back dql-app-back-label",onClick:c,title:"Back to apps",children:[t.jsx(Vr,{size:14}),t.jsx("span",{children:"Apps"})]}),t.jsx("span",{className:"dql-app-crumb",children:t.jsx("b",{children:(e==null?void 0:e.id)??"app"})}),t.jsx(Fe,{tone:"certified",children:D>0?`${re} certified`:"All certified"}),D>0?t.jsxs(Fe,{tone:"draft",children:[D," draft"]}):null,t.jsx("span",{className:"dql-app-topbar-divider","aria-hidden":"true"}),t.jsxs("div",{className:"dql-app-modeseg",role:"group","aria-label":"App mode",children:[t.jsxs("button",{type:"button",className:n==="view"?"on":"",onClick:()=>A("view"),title:"Clean stakeholder view",children:[t.jsx(_r,{size:12})," View"]}),t.jsxs("button",{type:"button",className:n==="build"?"on":"",onClick:()=>A("build"),title:"Rearrange tiles and edit this app",children:[t.jsx(Hr,{size:12})," Edit"]})]}),t.jsxs("div",{className:"dql-app-view-actions",children:[t.jsx(Sn,{app:(r==null?void 0:r.app)??null}),n==="build"?t.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>void xe(),disabled:ce==="running",children:[t.jsx(We,{size:14})," ",ce==="running"?"Promoting":"Promote"]}):null,t.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line dql-apps-btn-icon",title:K==="copied"?"Copied handoff":"Share local app handoff",onClick:()=>void oe(),children:K==="copied"?t.jsx(nt,{size:15}):t.jsx(Ha,{size:15})}),t.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line dql-apps-btn-icon",title:K==="downloaded"?"Brief saved":"Download app brief",onClick:ue,children:K==="downloaded"?t.jsx(nt,{size:15}):t.jsx(wa,{size:15})}),K==="ready"?t.jsxs("div",{className:"dql-app-share-popover",children:[t.jsx("b",{children:"Local handoff"}),t.jsx("textarea",{readOnly:!0,value:pe,onFocus:H=>H.currentTarget.select()})]}):null,ce==="done"||ce==="error"?t.jsx("div",{className:`dql-app-promote-popover ${ce==="error"?"error":""}`,children:J}):null]})]}),t.jsxs("main",{className:"dql-app-view-wrap",children:[t.jsxs("div",{className:"dql-app-title-row",children:[t.jsxs("div",{className:"dql-app-title-copy",children:[t.jsxs("div",{className:"dql-app-title-meta",children:[t.jsxs("span",{children:[t.jsx(Ye,{size:14})," ",(e==null?void 0:e.domain)??(a==null?void 0:a.dashboard.metadata.domain)??"DQL App"]}),ae?t.jsx("span",{className:"dql-app-title-context",children:qt(e==null?void 0:e.name)||"App"}):null,n==="build"?t.jsx(Fe,{tone:"draft",children:"Customizing"}):null]}),t.jsx("h1",{children:qt(ae?a==null?void 0:a.dashboard.metadata.title:e==null?void 0:e.name)||"App"}),t.jsx("p",{children:xa((ae?a==null?void 0:a.dashboard.metadata.description:e==null?void 0:e.description)??"Local DQL App")})]}),t.jsxs("div",{className:"dql-app-nav-row",children:[t.jsx(On,{appDoc:r,section:l,experience:n,onChange:S}),l==="dashboards"&&(r!=null&&r.dashboards.length)?t.jsx(Fn,{dashboards:r.dashboards,activeDashboardId:a==null?void 0:a.dashboard.id,isBuild:n==="build",onOpen:k,onAdd:$}):null,L?t.jsx("button",{type:"button",className:`dql-apps-btn dql-apps-btn-line dql-apps-btn-icon ${s?"on":""}`,title:s?"Hide AI copilot":"Show AI copilot",onClick:()=>z(!s),children:t.jsx(Ct,{size:15})}):null,ae?t.jsx(t.Fragment,{children:t.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line dql-apps-btn-icon",title:"Open dashboard lineage",onClick:()=>{e&&a&&I(`dashboard:${e.id}/${a.dashboard.id}`)},children:t.jsx(Lr,{size:15})})}):null]})]}),t.jsxs("div",{className:`dql-app-view-layout ${se?"":"no-explain"}`,children:[t.jsxs("div",{className:"dql-app-main-column",children:[l==="dashboards"&&a&&p.length>0?t.jsxs("section",{className:"dql-app-filter-row","aria-label":"Dashboard filters",children:[t.jsxs("div",{className:"dql-app-filter-row-copy",children:[t.jsx("b",{children:"Filters"}),t.jsx("span",{children:"Set the business scope, then apply once to refresh the full story."})]}),t.jsx(Jn,{filters:p,values:d,onChange:q}),t.jsxs("div",{className:"dql-app-filter-row-actions",children:[t.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:T,children:"Reset"}),t.jsx("button",{type:"button",className:"dql-apps-btn dql-apps-btn-primary",onClick:h,children:"Apply"})]})]}):null,i?t.jsx(qe,{title:"Loading app...",detail:"Reading dashboard files and running local blocks."}):l==="dashboards"&&a&&e?t.jsx(ei,{appId:e.id,dashboard:a.dashboard,editable:n==="build",embeddedHeader:!0,variables:x,selectedBlockId:W,onBlockFocus:de,onAskBlock:N,onOpenLineageNode:I,copilotOpen:s,onCopilotChange:z,onDashboardChanged:E,onRunChange:P}):l==="notebooks"?t.jsx(Hn,{appDoc:r}):l==="research"?t.jsx(Vn,{appDoc:r,dashboardDoc:a,seed:ee,themeMode:f,onSeedHandled:G,onDashboardChanged:E,onInvestigationsChanged:M,onActiveInvestigationChange:U}):l==="ai"?t.jsx(Qn,{appDoc:r}):l==="drafts"?t.jsx(Kn,{appDoc:r}):l==="settings"?t.jsx(Gn,{appDoc:r}):t.jsx(qe,{title:"No dashboard page selected.",detail:"Choose a dashboard page or add one in Build mode."})]}),se?t.jsx(Wn,{app:e,appDoc:r,dashboardDoc:a,dashboardRun:C,variables:x,selectedBlockId:W,askSeed:we,themeMode:f,expanded:o,onToggleExpanded:()=>Y(!o),onClose:()=>z(!1)}):null]})]})]})}function Mn({title:e,subtitle:r,catalog:a,loading:i,selectedBlocks:n,onToggleBlock:l}){const[s,o]=u.useState(""),p=u.useMemo(()=>{const d=s.trim().toLowerCase();return d?a.filter(f=>[f.name,f.domain,f.status,f.description,f.owner??"",...f.tags??[]].join(" ").toLowerCase().includes(d)):a},[a,s]);return t.jsxs("div",{className:"dql-app-palette",children:[t.jsxs("div",{className:"dql-app-palette-title",children:[t.jsxs("span",{children:[t.jsx(er,{size:14})," ",e]}),t.jsx("b",{children:r})]}),t.jsxs("label",{className:"dql-app-palette-search",children:[t.jsx(Be,{size:14}),t.jsx("input",{value:s,onChange:d=>o(d.target.value),placeholder:"Search blocks, domains, tags"})]}),i?t.jsx(qe,{title:"Loading blocks...",detail:"Finding certified blocks for this domain.",compact:!0}):null,!i&&p.length===0?t.jsx(qe,{title:"No blocks found.",detail:"Try another domain or search term.",compact:!0}):null,p.slice(0,24).map((d,f)=>{const x=n.has(d.id);return t.jsxs("button",{type:"button",className:x?"selected":"",onClick:()=>l(d.id),children:[t.jsx("span",{className:"dql-app-palette-icon",children:t.jsx(rr,{size:14})}),t.jsxs("span",{children:[t.jsx("b",{children:d.name}),t.jsxs("small",{children:[d.domain," / ",d.chartType??"table"]})]}),t.jsx("i",{children:x?"using":d.status})]},`${d.id}-${f}`)}),p.length>24?t.jsxs("div",{className:"dql-app-palette-more",children:[p.length-24," more matches"]}):null]})}function On({appDoc:e,section:r,experience:a,onChange:i}){var s,o,p,d,f;const n=((s=e==null?void 0:e.investigations)==null?void 0:s.length)??0,l=a==="view"?[{id:"dashboards",label:"App",count:(e==null?void 0:e.dashboards.length)??0,icon:t.jsx(Ye,{size:14})}]:[{id:"dashboards",label:"App",count:(e==null?void 0:e.dashboards.length)??0,icon:t.jsx(Ye,{size:14})},{id:"research",label:"Analysis",count:n,icon:t.jsx(Be,{size:14})},{id:"notebooks",label:"Notebooks",count:((o=e==null?void 0:e.notebooks)==null?void 0:o.length)??((p=e==null?void 0:e.app.notebooks)==null?void 0:p.length)??0,icon:t.jsx(Qr,{size:14})},{id:"ai",label:"Pins",count:((d=e==null?void 0:e.aiPins)==null?void 0:d.length)??0,icon:t.jsx(Ct,{size:14})},{id:"drafts",label:"Drafts",count:((f=e==null?void 0:e.drafts)==null?void 0:f.length)??0,icon:t.jsx(tr,{size:14})},{id:"settings",label:"Settings",icon:t.jsx(Oe,{size:14})}];return t.jsx("nav",{className:"dql-app-section-tabs","aria-label":"App sections",children:l.map(x=>t.jsxs("button",{className:r===x.id?"on":"","data-app-section":x.id,onClick:()=>i(x.id),title:x.label,"aria-label":`${x.label}${x.count!==void 0?` ${x.count}`:""}`,children:[t.jsx("i",{className:"dql-app-tab-icon",children:x.icon}),t.jsx("span",{className:"dql-app-tab-label",children:x.label}),x.count!==void 0?t.jsx("b",{children:x.count}):null]},x.id))})}function Fn({dashboards:e,activeDashboardId:r,isBuild:a,onOpen:i,onAdd:n}){const l=e.find(s=>s.id===r)??e[0];return t.jsxs("div",{className:"dql-app-page-picker","aria-label":"Dashboard page",children:[t.jsxs("span",{children:[t.jsx(rr,{size:14})," Page"]}),t.jsx("select",{value:(l==null?void 0:l.id)??"",onChange:s=>i(s.target.value),title:(l==null?void 0:l.title)??"Dashboard page",children:e.map(s=>t.jsxs("option",{value:s.id,children:[s.title," (",s.itemCount,")"]},s.id))}),a?t.jsx("button",{type:"button",onClick:n,title:"Add dashboard page",children:t.jsx(kt,{size:14})}):null]})}function Wn({app:e,appDoc:r,dashboardDoc:a,dashboardRun:i,variables:n,selectedBlockId:l,askSeed:s,themeMode:o,expanded:p,onToggleExpanded:d,onClose:f}){const x=Ne[o],c=(a==null?void 0:a.dashboard)??null,S=u.useMemo(()=>ua(c,i),[c,i]).find(re=>re.blockId===l)??null,q=S?i==null?void 0:i.tiles.find(re=>re.tileId===S.tileId||re.blockId===S.blockId):null,h=(e==null?void 0:e.id)??(r==null?void 0:r.app.id)??"app",T=(c==null?void 0:c.id)??"dashboard",z=Or(`app:${h}:${T}`),[Y,$]=u.useState(!1),k=ke((e==null?void 0:e.name)??(r==null?void 0:r.app.name)??(c==null?void 0:c.metadata.title)??"App workspace"),E=ke((c==null?void 0:c.metadata.title)??"Dashboard"),M=S?`Focused on ${ke(S.title)} in ${E}`:`Scoped to ${E}`,I=S?{kind:"block",id:S.blockId,title:S.title}:c?{kind:"dashboard",id:c.id,title:c.metadata.title}:{kind:"app",id:h,title:k},Q=u.useMemo(()=>{var re,D,_,V,W;return{surface:"apps",appId:h,appName:(e==null?void 0:e.name)??(r==null?void 0:r.app.name),appDomain:(e==null?void 0:e.domain)??(r==null?void 0:r.app.domain),appDescription:(e==null?void 0:e.description)??(r==null?void 0:r.app.description),dashboardId:c==null?void 0:c.id,dashboardTitle:c==null?void 0:c.metadata.title,dashboardDescription:c==null?void 0:c.metadata.description,dashboardFilters:n,selectedBlock:S?{blockId:S.blockId,tileId:S.tileId,title:S.title,visualization:S.viz,status:q==null?void 0:q.status,certificationStatus:q==null?void 0:q.certificationStatus,rowCount:(re=q==null?void 0:q.result)==null?void 0:re.rowCount,columns:(_=(D=q==null?void 0:q.result)==null?void 0:D.columns)==null?void 0:_.slice(0,12),sampleRows:nl((V=q==null?void 0:q.result)==null?void 0:V.rows,(W=q==null?void 0:q.result)==null?void 0:W.columns)}:void 0}},[e,r,h,c,S,q,n]);return t.jsx(Mr,{t:x,title:"App AI",subtitle:k,expanded:p,onToggleExpanded:d,onClose:f,onNewChat:z.resetThreadId,running:Y,ariaLabel:"App AI",className:"dql-app-explain-panel dql-app-assistant-panel",children:t.jsx(u.Suspense,{fallback:t.jsx("div",{style:{padding:16,fontSize:12,color:x.textSecondary},children:"Loading App AI…"}),children:t.jsx(In,{themeMode:o,title:"App AI",scopeHint:M,audience:"stakeholder",selectedObject:I,workspaceContext:Q,initialMode:"auto",autoRun:s!=null&&s.text?{text:s.text,mode:"ask",nonce:s.nonce}:void 0,threadId:z.threadId,onThreadIdChange:z.onThreadIdChange,onRunningChange:$,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."}]},`${h}:${T}`)})})}function Vn({appDoc:e,dashboardDoc:r,seed:a,themeMode:i,onSeedHandled:n,onDashboardChanged:l,onInvestigationsChanged:s,onActiveInvestigationChange:o}){var J;const p=e==null?void 0:e.app.id,d=r==null?void 0:r.dashboard.id,f=Ne[i],[x,c]=u.useState(()=>(e==null?void 0:e.investigations)??[]),[A,S]=u.useState(null),[q,h]=u.useState(!1),[T,z]=u.useState(null),[Y,$]=u.useState(null),[k,E]=u.useState("preview"),[M,I]=u.useState(""),[Q,re]=u.useState(!1),[D,_]=u.useState(!1),[V,W]=u.useState(null);u.useEffect(()=>{if(!p){c([]),S(null);return}let b=!1;return h(!0),Z.listAppInvestigations(p).then(P=>{if(b)return;$(null),c(P);const U=Dt(P);S(G=>{var N,L;return G??((N=U.find(se=>se.status==="ready"))==null?void 0:N.id)??((L=U[0])==null?void 0:L.id)??null})}).finally(()=>{b||h(!1)}),()=>{b=!0}},[p]),u.useEffect(()=>{s(x)},[x,s]),u.useEffect(()=>{if(!a||!p)return;let b=!1;const P={dashboardId:a.dashboardId??d,sourceTileId:a.sourceTileId,sourceBlockId:a.sourceBlockId,title:a.title,question:a.question,intent:a.intent,context:a.context,generatedSql:a.generatedSql,run:!0},U=pt(a.title??a.question)||"requested follow-up",G=`${p}:${JSON.stringify(P)}`,N=async()=>{z("create"),W(U),$(null);let se=Ot.get(G);se||(se=Z.createAppInvestigation(p,P),Ot.set(G,se),se.finally(()=>{window.setTimeout(()=>Ot.delete(G),5e3)}));const ve=await se;if(b)return;if(z(null),!ve.ok){$(ve.error),W(null),n();return}const oe=ve.investigation,ue=xe=>{c(ae=>it(ae,xe)),S(xe.id),E("preview"),_(!1),xe.status!=="draft"&&xe.status!=="running"&&W(null)};if(ue(oe),oe.status!=="draft"&&oe.status!=="running"){n();return}z(oe.id);for(let xe=0;xe<20;xe+=1){if(await new Promise(Ce=>{window.setTimeout(Ce,1e3)}),b)return;const ae=await Z.getAppInvestigation(p,oe.id);if(b)return;if(ae&&ae.status!=="draft"&&ae.status!=="running"){z(null),ue(ae),n();return}}n(),z(null),W(null),$("Analysis is still running. Reopen it or refresh to load the latest proof.")},L=window.setTimeout(()=>void N(),0);return()=>{b=!0,window.clearTimeout(L)}},[a==null?void 0:a.nonce,p,d,n]);const de=u.useMemo(()=>Dt(x),[x]),C=de.find(b=>b.id===A)??de.find(b=>b.status==="ready")??de[0]??null;u.useEffect(()=>(o(C),()=>o(null)),[C,o]);const le=de.filter(b=>b.id!==(C==null?void 0:C.id)).filter(b=>Q||b.status!=="error").slice(0,Q?40:5),we=Math.max(0,de.length-(C?1:0)-le.length),B=C?dl(C):null,ee=B?yl(B):"",ne=T==="create"||!!V,he=ne&&!!V,X=ne&&!C;u.useEffect(()=>{I((C==null?void 0:C.generatedSql)??"")},[C==null?void 0:C.id,C==null?void 0:C.generatedSql]);const K=async(b,P)=>{if(!p)return null;z(b.id),$(null);const U=P==null?void 0:P.trim(),G=await Z.runAppInvestigation(p,b.id,U?{generatedSql:U}:void 0);return z(null),G.ok?(c(N=>it(N,G.investigation)),E("preview"),G.investigation):($(G.error),null)},me=async b=>{if(!p)return null;z(`rebuild:${b.id}`),$(null);const P=await Z.runAppInvestigation(p,b.id,{repairMode:"rebuild_from_certified"});return z(null),P.ok?(c(U=>it(U,P.investigation)),E(P.investigation.error?"sql":"preview"),P.investigation):($(P.error),null)},pe=async b=>{if(!p)return null;z(`pin:${b.id}`),$(null);const P=await Z.pinAppInvestigation(p,b.id,{dashboardId:b.dashboardId??d,title:b.title});return z(null),P.ok?(c(U=>it(U,P.investigation)),S(P.investigation.id),P.dashboard&&l(P.dashboard),P.investigation):($(P.error),null)},ye=async b=>{if(!p)return;if(!b.generatedSql){$("Add reviewed SQL before creating a draft block.");return}const P=b.pinnedAiPinId?b:await pe(b),U=P==null?void 0:P.pinnedAiPinId;if(!U)return;z(`promote:${b.id}`),$(null);const G=await Z.promoteAiPin(p,U);if(z(null),!G.ok){$(G.error??"Draft block could not be created.");return}const N=await Z.getAppInvestigation(p,b.id);N&&c(L=>it(L,N))},ce=async b=>{const P=M.trim();let U=b;if(P&&P!==(b.generatedSql??"").trim()){const G=await K(b,P);if(!G)return;U=G}await ye(U)},be=async b=>{const P=M.trim();let U=b;if(P&&P!==(b.generatedSql??"").trim()){const G=await K(b,P);if(!G)return null;U=G}return pe(U)};return e?t.jsxs("div",{className:`dql-app-research-shell ${D||!C&&!X?"history-open":"history-collapsed"}`,children:[t.jsxs("section",{className:"dql-app-research-list",children:[t.jsxs("div",{className:"dql-app-research-head",children:[t.jsxs("span",{children:[t.jsx(Be,{size:14})," Analysis"]}),t.jsxs("div",{children:[t.jsx("b",{children:x.length}),C?t.jsx("button",{type:"button",onClick:()=>_(!1),title:"Close analysis history",children:"Close"}):null]})]}),q?t.jsx(qe,{title:"Loading analysis...",detail:"Reading local app analysis.",compact:!0}):null,Y?t.jsx("div",{className:"dql-app-error",children:Y}):null,!q&&x.length===0?t.jsx(qe,{title:"No analysis yet.",detail:"Start from Copilot so the analysis keeps the original question, filters, and selected result context.",compact:!0}):null,t.jsxs("div",{className:"dql-app-research-items",children:[C?t.jsxs(t.Fragment,{children:[t.jsx("div",{className:"dql-app-research-group-label",children:"Current analysis"}),t.jsx(Tr,{item:C,selected:!0,onClick:()=>{$(null),S(C.id),E("preview"),_(!1)}})]}):null,le.length?t.jsx("div",{className:"dql-app-research-group-label",children:"Recent history"}):null,le.map(b=>t.jsx(Tr,{item:b,selected:(C==null?void 0:C.id)===b.id,onClick:()=>{$(null),S(b.id),E("preview"),_(!1)}},b.id)),we>0?t.jsxs("button",{type:"button",className:"dql-app-research-history-toggle",onClick:()=>re(b=>!b),children:[t.jsx("span",{children:Q?"Hide older runs":`Show ${we} older run${we===1?"":"s"}`}),t.jsx("small",{children:Q?"Keep the current analysis focused":"Includes failed and superseded analysis attempts"})]}):null]})]}),t.jsx("section",{className:"dql-app-research-detail",children:he?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"dql-app-report-toolbar",children:[t.jsxs("div",{children:[t.jsx("span",{children:"New memo"}),t.jsx("b",{children:V})]}),x.length?t.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>_(b=>!b),children:[t.jsx(Be,{size:13})," ",D?"Hide history":`Analysis history (${x.length})`]}):null]}),Y?t.jsx("div",{className:"dql-app-error",children:Y}):null,t.jsxs("div",{className:"dql-app-research-creating active",children:[t.jsx(Oe,{size:24}),t.jsx("span",{children:"Preparing business memo"}),t.jsx("h2",{children:"Writing business memo..."}),t.jsxs("p",{children:['DQL is opening a scoped memo for "',V,'". The previous memo stays in history while this answer is built from the typed context, active filters, certified block evidence, and preview proof.']}),t.jsxs("div",{className:"dql-app-research-creating-steps",children:[t.jsx("small",{children:"Reading current filters"}),t.jsx("small",{children:"Checking certified block context"}),t.jsx("small",{children:"Building narrative and proof appendix"})]})]})]}):C&&B?t.jsxs(t.Fragment,{children:[t.jsxs("div",{className:"dql-app-report-toolbar",children:[t.jsxs("div",{children:[t.jsx("span",{children:"Current memo"}),t.jsx("b",{children:ga(C)})]}),t.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>_(b=>!b),children:[t.jsx(Be,{size:13})," ",D?"Hide history":`Memo history (${x.length})`]})]}),ne||T===C.id||C.status==="running"?t.jsxs("div",{className:`dql-app-research-status ${ne?"opening":""}`,children:[t.jsx(Oe,{size:14}),t.jsxs("div",{children:[t.jsx("span",{children:ne?"Opening a new business memo...":"Refreshing the memo from certified evidence, active filters, and optional preview proof..."}),V?t.jsx("small",{children:V}):null]})]}):null,Y?t.jsx("div",{className:"dql-app-error",children:Y}):null,t.jsxs("article",{className:"dql-app-research-report",children:[t.jsxs("header",{className:"dql-app-report-hero",children:[t.jsxs("div",{className:"dql-app-report-status-row",children:[t.jsxs("span",{children:[t.jsx(Be,{size:13})," Business memo"]}),t.jsx(Fe,{tone:C.status==="error"?"draft":"agentic",children:C.reviewStatus})]}),t.jsx("h2",{children:B.title}),t.jsx("p",{children:B.scope}),t.jsx("div",{className:"dql-app-report-context-line",children:B.contextFacts.map(b=>t.jsxs("span",{children:[t.jsx("b",{children:b.label}),b.value]},b.label))}),t.jsxs("div",{className:"dql-app-report-actions",children:[t.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>void be(C),disabled:T===`pin:${C.id}`,children:[t.jsx(Wa,{size:13})," ",C.pinnedAiPinId?"Pinned to app":"Pin insight"]}),t.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-primary",onClick:()=>void ce(C),disabled:!(M.trim()||C.generatedSql)||T===`promote:${C.id}`,children:[t.jsx(tr,{size:13})," ",T===`promote:${C.id}`?"Drafting...":"Create draft block"]}),t.jsxs("details",{className:"dql-app-report-review-actions",children:[t.jsx("summary",{children:"Reviewer tools"}),t.jsxs("div",{children:[t.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>void K(C,M),disabled:T===C.id,children:[t.jsx(Oe,{size:13})," ",T===C.id?"Refreshing...":"Refresh memo"]}),(J=B.previewIssue)!=null&&J.canRebuild?t.jsxs("button",{type:"button",className:"dql-apps-btn dql-apps-btn-line",onClick:()=>void me(C),disabled:T===`rebuild:${C.id}`,children:[t.jsx(Oe,{size:13})," ",T===`rebuild:${C.id}`?"Rebuilding...":"Rebuild SQL"]}):null]})]})]}),B.previewIssue?t.jsxs("div",{className:"dql-app-report-warning",children:[t.jsx(Qe,{size:14}),t.jsx("span",{children:B.previewIssue.message})]}):null]}),t.jsx("section",{className:"dql-app-report-section dql-app-report-paper",children:B.sections.length?t.jsx(ql,{sections:B.sections}):t.jsx(Tn,{text:ee,t:f,compact:!0})}),B.keyNumbers.length||B.drivers.length?t.jsxs("section",{className:`dql-app-report-section dql-app-report-evidence-story ${B.keyNumbers.length&&B.drivers.length?"":"single"}`,children:[B.keyNumbers.length?t.jsxs("div",{children:[t.jsx("h3",{children:B.intent==="segment_compare"?"Segment numbers":B.intent==="diagnose_change"?"Movement numbers":"Key numbers"}),t.jsx("div",{className:"dql-app-report-numbers",children:B.keyNumbers.map(b=>t.jsxs("div",{className:"dql-app-report-number",children:[t.jsx("span",{children:b.label}),t.jsx("b",{children:b.value}),t.jsx("small",{children:b.detail})]},b.label))})]}):null,B.drivers.length?t.jsxs("div",{children:[t.jsx("h3",{children:B.intent==="anomaly_investigation"?"Exception view":B.intent==="entity_drilldown"?"Entity view":"Driver view"}),t.jsx(Sl,{drivers:B.drivers})]}):null]}):null,t.jsxs("details",{className:"dql-app-report-section dql-app-report-appendix",children:[t.jsxs("summary",{children:[t.jsx("span",{children:"Technical appendix"}),t.jsx("small",{children:"SQL, preview rows, caveats, routing, and source context for analyst review"}),t.jsx(Er,{size:15})]}),t.jsxs("div",{className:"dql-app-research-evidence-head",children:[t.jsxs("div",{children:[t.jsx("h3",{children:"SQL and proof"}),t.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."})]}),t.jsx("div",{className:"dql-app-research-tabs",children:["preview","sql","assumptions","context"].map(b=>t.jsx("button",{type:"button",className:k===b?"on":"",onClick:()=>E(b),children:b==="assumptions"?"Caveats":ke(b)},b))})]}),t.jsx(Cl,{investigation:C,tab:k,sqlDraft:M,onSqlDraftChange:I})]})]})]}):t.jsxs(t.Fragment,{children:[Y?t.jsx("div",{className:"dql-app-error",children:Y}):null,X?t.jsxs("div",{className:"dql-app-research-creating",children:[t.jsx(Oe,{size:22}),t.jsx("span",{children:"Preparing business memo"}),t.jsx("h2",{children:"Writing business memo..."}),t.jsx("p",{children:V?`DQL is opening a scoped memo for "${V}".`:"DQL is using the Copilot context, active filters, certified block evidence, and any available preview proof to create the main-canvas memo."})]}):t.jsx(qe,{title:"Start analysis from Copilot.",detail:"Ask a follow-up, add context, then review the analysis here."})]})})]}):t.jsx(qe,{title:"No App selected.",detail:"Choose an App before writing analysis."})}function Tr({item:e,selected:r,onClick:a}){return t.jsxs("button",{type:"button",className:[r?"on":"",`status-${e.status}`].filter(Boolean).join(" "),onClick:a,children:[t.jsx("span",{children:ga(e)}),t.jsx("small",{children:Il(e)})]})}function Hn({appDoc:e}){const r=(e==null?void 0:e.notebooks)??(e==null?void 0:e.app.notebooks)??[];return r.length?t.jsx("div",{className:"dql-app-simple-list",children:r.map(a=>t.jsxs(Ge,{icon:t.jsx(Qr,{size:16}),children:[t.jsx("b",{children:a.title??a.path.split("/").pop()}),t.jsxs("span",{children:[a.role," / ",a.visibility," / ",a.path]})]},a.path))}):t.jsx(qe,{title:"No notebooks attached.",detail:"Attach analysis notebooks in Build mode when this App needs supporting work."})}function Qn({appDoc:e}){const r=(e==null?void 0:e.aiPins)??[];return r.length?t.jsx("div",{className:"dql-app-simple-list",children:r.map(a=>t.jsxs(Ge,{icon:t.jsx(Ct,{size:16}),children:[t.jsx("b",{children:a.title}),t.jsxs("span",{children:[a.certification," / ",a.reviewStatus]})]},a.id))}):t.jsx(qe,{title:"No pinned insights yet.",detail:"Use Copilot from a dashboard page, create analysis, then add useful reviewed insights to this App."})}function Kn({appDoc:e}){const r=(e==null?void 0:e.drafts)??[];return r.length?t.jsx("div",{className:"dql-app-simple-list",children:r.map(a=>t.jsxs(Ge,{icon:t.jsx(tr,{size:16}),children:[t.jsx("b",{children:a.name}),t.jsxs("span",{children:[a.reviewStatus??"needs review"," / ",a.path]})]},a.path))}):t.jsx(qe,{title:"No drafts.",detail:"Generated and promoted draft blocks will appear here for review."})}function Gn({appDoc:e}){var r;return e?t.jsxs("div",{className:"dql-app-settings-grid",children:[t.jsxs(Ge,{icon:t.jsx(We,{size:16}),children:[t.jsx("b",{children:"Owners"}),t.jsx("span",{children:e.app.owners.join(", ")})]}),t.jsxs(Ge,{icon:t.jsx(Oe,{size:16}),children:[t.jsx("b",{children:"Lifecycle"}),t.jsx("span",{children:e.app.lifecycle??"draft"})]}),t.jsxs(Ge,{icon:t.jsx(er,{size:16}),children:[t.jsx("b",{children:"Policies"}),t.jsxs("span",{children:[e.app.policies.length," local access policies"]})]}),t.jsxs(Ge,{icon:t.jsx(Ye,{size:16}),children:[t.jsx("b",{children:"Homepage"}),t.jsx("span",{children:((r=e.app.homepage)==null?void 0:r.type)??"dashboard"})]})]}):t.jsx(qe,{title:"No App selected.",detail:"Choose an App to inspect its settings."})}function Ft({title:e,meta:r}){return t.jsxs("div",{className:"dql-app-panel-head",children:[t.jsx("span",{children:e}),r?t.jsx("b",{children:r}):null]})}function Yn(e){return e.kind==="certified_block"&&e.certification==="certified"}function Xn(e){var i;const r=Array.isArray(e.scopedReports)?e.scopedReports.length:0,a=Array.isArray((i=e.planning)==null?void 0:i.scopedReports)?e.planning.scopedReports.length:0;return r>0||a>0?Math.max(r,a):Array.isArray(e.missingEvidence)?e.missingEvidence.length:0}function Jn({filters:e,values:r,onChange:a}){return e.length===0?t.jsx("span",{className:"dql-app-filter-empty",children:"No filters"}):t.jsx(t.Fragment,{children:e.map(i=>t.jsx(Zn,{filter:i,value:r[i.id]??lt(i),onChange:n=>a(i,n)},i.id))})}function Zn({filter:e,value:r,onChange:a}){var f;const i=ke(e.id),n=Un(e,r),l=e.sourceBlockId,s=e.bindsTo||e.id,o=(e.type==="string"||e.type==="select")&&!!l&&!((f=e.options)!=null&&f.length),[p,d]=u.useState(null);if(u.useEffect(()=>{if(!o||!l)return;let x=!1;return Z.dashboardFilterOptions(l,s).then(c=>{!x&&c&&c.options.length>0&&!c.truncated&&d(c.options)}),()=>{x=!0}},[l,s,o]),p&&p.length>0)return t.jsx(Wt,{icon:at(e),label:i,value:n,onChange:a,options:[["",`All ${i.toLowerCase()}`],...p.map(x=>[x,x])]});if(e.type==="select")return t.jsx(Wt,{icon:at(e),label:i,value:n,onChange:a,options:Dn(e)});if(e.type==="boolean")return t.jsx(Wt,{icon:at(e),label:i,value:String(!!r),onChange:x=>a(x==="true"),options:[["true","Yes"],["false","No"]]});if(e.type==="daterange"){const x=r&&typeof r=="object"&&!Array.isArray(r)?r:{},c=typeof x.start=="string"?x.start:"",A=typeof x.end=="string"?x.end:"",S=(q,h)=>a(q&&h?{start:q,end:h}:void 0);return t.jsxs("label",{className:"dql-app-filter-select dql-app-filter-range",title:e.bindsTo?`${i} -> ${e.bindsTo}`:i,"aria-label":i,children:[t.jsx("span",{className:"dql-app-filter-icon",children:at(e)}),t.jsx("input",{type:"date",value:c,"aria-label":`${i} from`,onChange:q=>S(q.target.value,A)}),t.jsx("span",{className:"dql-app-filter-range-sep",children:"–"}),t.jsx("input",{type:"date",value:A,"aria-label":`${i} to`,onChange:q=>S(c,q.target.value)})]})}return t.jsxs("label",{className:"dql-app-filter-select",title:e.bindsTo?`${i} -> ${e.bindsTo}`:i,"aria-label":i,children:[t.jsx("span",{className:"dql-app-filter-icon",children:at(e)}),t.jsx("input",{type:e.type==="number"?"number":e.type==="date"?"date":"text",value:n,placeholder:i,onChange:x=>a(x.target.value)})]})}function at(e){return e.type==="date"||e.type==="daterange"||/season|year|date|time|period/i.test(e.id)?t.jsx(La,{size:13}):t.jsx(Kr,{size:13})}function Dn(e){var a;return((a=e.options)!=null&&a.length?e.options:[e.default].filter(i=>i!==void 0)).map(i=>[String(i),ke(String(i))])}function lt(e){var r;return e.default!==void 0?e.default:e.type==="number"?pa(e.id):e.type==="boolean"?!1:e.type==="select"?((r=e.options)==null?void 0:r[0])??"":""}function Un(e,r){return r==null?String(lt(e)??""):e.type==="daterange"&&typeof r=="object"?JSON.stringify(r):String(r)}function el(e,r){if(e.type==="number"){if(typeof r=="string"&&r.trim()==="")return"";const a=Number(r);return Number.isFinite(a)?a:r}if(e.type==="boolean")return r===!0||r==="true";if(e.type==="select"&&typeof e.default=="number"){const a=Number(r);return Number.isFinite(a)?a:r}return r}function $r(e,r){const a=Object.keys(e),i=Object.keys(r);return a.length!==i.length?!1:a.every(n=>Object.is(e[n],r[n]))}function Wt({label:e,icon:r,value:a,options:i,onChange:n}){return t.jsxs("label",{className:"dql-app-filter-select",title:e,"aria-label":e,children:[r?t.jsx("span",{className:"dql-app-filter-icon",children:r}):t.jsx("span",{children:e}),t.jsx("select",{value:a,onChange:l=>n(l.target.value),children:i.map(([l,s])=>t.jsx("option",{value:l,children:s},l))})]})}function Vt(e){return e.block?"blockId"in e.block?e.block.blockId??null:e.block.ref??null:null}function ua(e,r){if(!e)return[];const a=new Map(((r==null?void 0:r.tiles)??[]).map(p=>[p.tileId,p])),i=new Map(((r==null?void 0:r.tiles)??[]).filter(p=>p.blockId).map(p=>[p.blockId,p])),n=new Set(e.layout.items.filter(p=>Vt(p)&&Pr(p)).map(p=>Zt(`${p.title??""} ${Vt(p)??""}`)).filter(Boolean)),l=e.layout.items.map((p,d)=>{const f=Vt(p);if(!f)return null;const x=Zt(`${p.title??""} ${f}`);if(x&&n.has(x)&&!Pr(p))return null;const c=a.get(p.i)??i.get(f);return{block:{blockId:f,title:p.title??f,viz:p.viz.type,tileId:p.i},duplicateKeys:tl(p,c,f),score:il(p,c,d)}}).filter(p=>!!p).sort((p,d)=>d.score-p.score),s=new Set,o=[];for(const p of l)if(!p.duplicateKeys.some(d=>s.has(d))){for(const d of p.duplicateKeys)s.add(d);o.push(p.block)}return o}function Pr(e){var r,a;return(r=e.parameterBindings)!=null&&r.length?!0:!!((a=e.filterBindings)!=null&&a.some(i=>!i.unsupportedReason&&(i.mode==="parameter"||i.mode==="predicate"||!!i.binding)))}function tl(e,r,a){const i=[`block:${a}`],n=rl(r==null?void 0:r.result);n&&i.push(`result:${n}`);const l=Zt(`${e.title??""} ${a}`);return l&&i.push(`topic:${l}`),i}function rl(e){var i,n;if(!((i=e==null?void 0:e.columns)!=null&&i.length)||!((n=e.rows)!=null&&n.length))return"";const r=e.columns.slice(0,6).map(l=>l.toLowerCase()),a=e.rows.slice(0,3).map(l=>r.map(s=>al(l[s]??l[e.columns.find(o=>o.toLowerCase()===s)??s])).join(","));return[...r,...a].join("|")}function al(e){return e==null?"":typeof e=="number"?Number.isFinite(e)?String(Math.round(e*1e3)/1e3):"":String(e).toLowerCase().replace(/\s+/g," ").trim().slice(0,80)}function Zt(e){const r=e.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":"",n=/\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||!n?"":`${a}|${i}|${n}`}function il(e,r,a){var n,l,s,o,p;let i=1e4-a;return(n=e.parameterBindings)!=null&&n.length&&(i+=5e4),(l=e.filterBindings)!=null&&l.length&&(i+=2e4),(r==null?void 0:r.status)==="ok"&&(i+=15e3),(o=(s=r==null?void 0:r.result)==null?void 0:s.rows)!=null&&o.length&&(i+=8e3),(r==null?void 0:r.certificationStatus)==="certified"&&(i+=5e3),String(e.trustState??((p=e.display)==null?void 0:p.trustState)??"").toLowerCase()==="certified"&&(i+=3e3),/codex\s+e2e|test|pasted/i.test(String(e.title??""))&&(i-=6e3),i}function nl(e,r){if(!Array.isArray(e)||e.length===0)return;const a=Array.isArray(r)&&r.length>0?r.slice(0,8):Object.keys(e[0]??{}).slice(0,8);return e.slice(0,5).map(i=>Object.fromEntries(a.map(n=>[n,i[n]])))}function qt(e){return String(e??"").replace(/\s+/g," ").replace(/[\s,;:.–—-]+$/,"").trim()}function ke(e){const r=String(e??"").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 xa(e){return e.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 zt(e){return e==null||e===""?"All":Array.isArray(e)?e.map(zt).join(", "):typeof e=="boolean"?e?"On":"Off":typeof e=="number"?e.toLocaleString():typeof e=="object"?JSON.stringify(e):String(e)}function fa(e,r){if(Array.isArray(r))return r.map(i=>fa(e,i)).join(", ");const a=typeof r=="number"?r:typeof r=="string"&&r.trim()!==""?Number(r):NaN;return/(season|year)/i.test(e)&&Number.isInteger(a)&&a>=1900&&a<=2200?String(a):zt(r)}function ll(e,r,a){var o;const i=(e==null?void 0:e.id)??(r==null?void 0:r.app.id)??"app",n=(e==null?void 0:e.name)??(r==null?void 0:r.app.name)??"DQL App",l=(a==null?void 0:a.dashboard.metadata.title)??((o=r==null?void 0:r.dashboards[0])==null?void 0:o.title)??"Overview",s=typeof window<"u"?window.location.origin:"local DQL";return[n,`App ID: ${i}`,`Dashboard: ${l}`,`Domain: ${(e==null?void 0:e.domain)??(r==null?void 0:r.app.domain)??(a==null?void 0:a.dashboard.metadata.domain)??"unknown"}`,`Open locally: ${s}`].join(`
48
48
  `)}function sl(e,r,a){const i=r==null?void 0:r.app,n=(e==null?void 0:e.name)??(i==null?void 0:i.name)??"DQL App",l=(r==null?void 0:r.dashboards)??[],s=(r==null?void 0:r.notebooks)??(i==null?void 0:i.notebooks)??[],o=(r==null?void 0:r.drafts)??[],p=(r==null?void 0:r.aiPins)??[],d=a==null?void 0:a.dashboard,f=(d==null?void 0:d.layout.items.map(c=>c.block?c.block.blockId??c.block.ref??c.title??c.i:null).filter(c=>!!c))??[];return`${[`# ${n}`,"",(e==null?void 0:e.description)??(d==null?void 0:d.metadata.description)??(i==null?void 0:i.description)??"Local DQL App brief.","","## App Metadata","",`- App ID: ${(e==null?void 0:e.id)??(i==null?void 0:i.id)??"unknown"}`,`- Domain: ${(e==null?void 0:e.domain)??(i==null?void 0:i.domain)??(d==null?void 0:d.metadata.domain)??"unknown"}`,`- Lifecycle: ${(e==null?void 0:e.lifecycle)??(i==null?void 0:i.lifecycle)??(d==null?void 0:d.metadata.lifecycle)??"draft"}`,`- Audience: ${(e==null?void 0:e.audience)??(i==null?void 0:i.audience)??(d==null?void 0:d.metadata.audience)??"stakeholder"}`,`- Owners: ${((e==null?void 0:e.owners)??(i==null?void 0:i.owners)??[]).join(", ")||"owner@local"}`,"","## Pages","",...l.length?l.map(c=>`- ${c.title} (${c.itemCount} tiles)`):["- No dashboard pages found."],"","## Governed Blocks","",...f.length?f.map(c=>`- ${c}`):["- No block-backed tiles found."],"","## Supporting Assets","",`- Notebooks: ${s.length}`,`- Pinned insights: ${p.length}`,`- Drafts needing review: ${o.length}`,""].join(`
49
49
  `)}
50
50
  `}function Fe({children:e,tone:r="certified"}){return t.jsx("span",{className:`dql-app-seal ${r}`,children:e})}function Ht({label:e,value:r}){return t.jsxs("span",{children:[t.jsx("small",{children:e}),t.jsx("b",{children:r})]})}function Rr({label:e,value:r}){return t.jsxs("div",{className:"dql-app-keyvalue-inline",children:[t.jsx("span",{children:e}),t.jsx("b",{children:r})]})}function ol(e,r){const a=pt(r)||"Review this app result.",i=typeof e=="string"?e.trim():"";if(!i)return a;const n=pl(i);if(n)return n;const l=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 pt(l)||a}function pl(e){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(e);if(!a)return"";const i=(a.index??0)+a[0].length,n=e.slice(i),l=n.search(/(?:^|\n)\s*(Current app filters|Certified block to start from|Source result|User intent|Review status|Trust status):/i),s=l>=0?n.slice(0,l):n;return pt(s)}function pt(e){const r=e.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 dl(e){var M,I;const r=ge(e.metrics),a=ge(e.context),i=ge(e.evidence),n=ge(i.planner),l=cl(a,i,n),s=ge(a.focusBlock),o=dr(e),p=ge(o==null?void 0:o.result),d=Array.isArray(p.rows)?p.rows.length:0,f=ol(a.userProvidedContext,e.question),x=typeof a.actionMode=="string"?a.actionMode:void 0,c=String(r.context??s.title??e.sourceBlockId??"selected app result"),A=String(a.activeFilterSummary??Al(ge(a.activeFilters))),S=bl(e.intent,x),q=gl(e,f,x,c),h=hl(S,f,c,A),T=((M=e.summary)==null?void 0:M.trim())||`DQL wrote review-required analysis for ${c}: ${e.question}. The selected app result is available, but this analysis still needs human review before it becomes governed business logic.`,z=((I=e.recommendation)==null?void 0:I.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.",Y=[{label:String(r.currentLabel??"Current"),value:st(r.currentValue),detail:String(r.currentDetail??"current selected result")},{label:String(r.baselineLabel??"Baseline"),value:st(r.baselineValue),detail:String(r.baselineDetail??"comparison or prior value")},{label:String(r.deltaLabel??"Delta"),value:st(r.delta),detail:String(r.deltaDetail??"change or gap to explain")},{label:"Preview",value:d?`${d} rows`:"not captured",detail:"bounded preview sample"}].filter(fl),$=vl(e),k=d>0||Y.length>0||$.length>0||Object.keys(r).length>0,E=kl(e.reportSections).filter(Q=>xl(Q,e.error,k));return{title:q,intent:e.intent,actionMode:x,scope:h,summary:T,recommendation:z,routeDecision:l,sections:E,previewIssue:ul(e.error,typeof n.sqlErrorKind=="string"?n.sqlErrorKind:void 0,k),contextFacts:[{label:"Type",value:S},{label:"Source",value:c},{label:"Filters",value:A},{label:"Review",value:ke(e.reviewStatus)}],keyNumbers:Y,drivers:$}}function cl(e,r,a){const i=ge(e.originatingAnswer),n=ge(e.routeDecision),l=ge(i.decision),s=ge(r.routeDecision),o=ge(a.routeDecision),p=Object.keys(n).length?n:Object.keys(l).length?l:Object.keys(s).length?s:Object.keys(o).length?o:{},d=typeof p.reason=="string"?p.reason.trim():"",f=typeof p.nextAction=="string"?p.nextAction.trim():"";if(!d&&!f)return null;const x=typeof p.mode=="string"&&p.mode.trim()?ke(p.mode):"Analysis",c=typeof p.confidence=="number"&&Number.isFinite(p.confidence)?Math.round(Math.max(0,Math.min(1,p.confidence))*100):void 0;return{mode:x,reason:d,nextAction:f,confidence:c}}function ul(e,r,a=!1){const i=e==null?void 0:e.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 xl(e,r,a){const i=String(e.id??"").toLowerCase();return!(e.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 fl(e){const r=e.value.trim().toLowerCase();return!!r&&r!=="n/a"&&r!=="not captured"&&r!=="not available"}function gl(e,r,a,i){const n=jt(r)||jt(e.title)||jt(e.question),l=a==="block"?"Reusable logic":a==="evidence"?"Proof brief":"Analysis",s=ke(i);return`${l}: ${ml(n||s)}`}function hl(e,r,a,i){const n=jt(r);return[n?`Question: ${n}`:"",`Source: ${a}`,i&&i!=="No app filters set"?`Filters: ${i}`:"",`Status: ${e} / review-required`].filter(Boolean).join(" · ")}function jt(e){return pt(String(e??"")).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 ml(e){const r=e.replace(/\s+/g," ").trim();return r.length<=96?r:`${r.slice(0,96).replace(/\s+\S*$/,"").trim()||r.slice(0,96)}...`}function bl(e,r){return r==="evidence"?"Proof Brief":r==="block"?"Reusable Logic Brief":e==="diagnose_change"?"Change Analysis":e==="segment_compare"?"Segment Comparison":e==="entity_drilldown"?"Entity Drilldown":e==="anomaly_investigation"?"Anomaly Review":e==="trust_gap_review"?"Proof Review":"Driver Analysis"}function vl(e){const r=(e.driverCards??[]).map(ge).filter(l=>Object.keys(l).length>0);if(r.length)return r.slice(0,8).map((l,s)=>({title:String(l.title??`Driver ${s+1}`),value:String(l.contribution??l.value??l.metric??"Proof"),explanation:String(l.explanation??"Review this driver against the source rows and metric grain.")}));const a=dr(e),i=ge(a==null?void 0:a.result);return(Array.isArray(i.rows)?i.rows.map(ge).filter(l=>Object.keys(l).length>0):[]).slice(0,5).map((l,s)=>{const o=Object.keys(l),p=o.find(f=>/name|player|customer|account|segment|team/i.test(f))??o[0]??`row_${s+1}`,d=o.find(f=>/point|revenue|total|score|value|delta|count/i.test(f)&&f!==p)??o[1]??p;return{title:String(l[p]??`Preview row ${s+1}`),value:st(l[d]),explanation:`This row is part of the bounded preview sample for ${ke(d)}.`}})}function yl(e){var S,q;if(e.sections.length>0)return e.sections.map(h=>{var z;const T=(z=h.bullets)!=null&&z.length?`